@donotdev/core 0.1.1 → 0.1.44

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.
Files changed (140) hide show
  1. package/LICENSE.md +21 -242
  2. package/README.md +2 -20
  3. package/empty.cjs +0 -0
  4. package/empty.js +0 -0
  5. package/functions/index.js +20 -10
  6. package/i18n/locales/eager/dndev_ar.json +35 -0
  7. package/i18n/locales/eager/dndev_da.json +63 -8
  8. package/i18n/locales/eager/dndev_de.json +35 -0
  9. package/i18n/locales/eager/dndev_en.json +52 -1
  10. package/i18n/locales/eager/dndev_es.json +35 -0
  11. package/i18n/locales/eager/dndev_fr.json +52 -1
  12. package/i18n/locales/eager/dndev_it.json +35 -0
  13. package/i18n/locales/eager/dndev_ja.json +35 -0
  14. package/i18n/locales/eager/dndev_ko.json +35 -0
  15. package/i18n/locales/eager/dndev_nl.json +59 -7
  16. package/i18n/locales/eager/dndev_pt.json +35 -0
  17. package/i18n/locales/eager/dndev_zh.json +36 -1
  18. package/i18n/locales/lazy/ai_en.json +0 -0
  19. package/i18n/locales/lazy/ai_pt.json +0 -0
  20. package/i18n/locales/lazy/ai_zh.json +0 -0
  21. package/i18n/locales/lazy/auth_ar.json +0 -0
  22. package/i18n/locales/lazy/auth_da.json +0 -0
  23. package/i18n/locales/lazy/auth_de.json +0 -0
  24. package/i18n/locales/lazy/auth_en.json +0 -0
  25. package/i18n/locales/lazy/auth_es.json +0 -0
  26. package/i18n/locales/lazy/auth_fr.json +0 -0
  27. package/i18n/locales/lazy/auth_it.json +0 -0
  28. package/i18n/locales/lazy/auth_ja.json +0 -0
  29. package/i18n/locales/lazy/auth_ko.json +0 -0
  30. package/i18n/locales/lazy/auth_nl.json +0 -0
  31. package/i18n/locales/lazy/auth_pt.json +0 -0
  32. package/i18n/locales/lazy/auth_zh.json +0 -0
  33. package/i18n/locales/lazy/billing_ar.json +0 -0
  34. package/i18n/locales/lazy/billing_da.json +0 -0
  35. package/i18n/locales/lazy/billing_de.json +0 -0
  36. package/i18n/locales/lazy/billing_en.json +0 -0
  37. package/i18n/locales/lazy/billing_es.json +0 -0
  38. package/i18n/locales/lazy/billing_fr.json +0 -0
  39. package/i18n/locales/lazy/billing_it.json +0 -0
  40. package/i18n/locales/lazy/billing_ja.json +0 -0
  41. package/i18n/locales/lazy/billing_ko.json +0 -0
  42. package/i18n/locales/lazy/billing_nl.json +0 -0
  43. package/i18n/locales/lazy/billing_pt.json +0 -0
  44. package/i18n/locales/lazy/billing_zh.json +0 -0
  45. package/i18n/locales/lazy/blog_ar.json +0 -0
  46. package/i18n/locales/lazy/blog_da.json +0 -0
  47. package/i18n/locales/lazy/blog_de.json +0 -0
  48. package/i18n/locales/lazy/blog_en.json +0 -0
  49. package/i18n/locales/lazy/blog_es.json +0 -0
  50. package/i18n/locales/lazy/blog_fr.json +0 -0
  51. package/i18n/locales/lazy/blog_it.json +0 -0
  52. package/i18n/locales/lazy/blog_ja.json +0 -0
  53. package/i18n/locales/lazy/blog_ko.json +0 -0
  54. package/i18n/locales/lazy/blog_nl.json +0 -0
  55. package/i18n/locales/lazy/blog_pt.json +0 -0
  56. package/i18n/locales/lazy/blog_zh.json +0 -0
  57. package/i18n/locales/lazy/cookies_ar.json +0 -0
  58. package/i18n/locales/lazy/cookies_da.json +0 -0
  59. package/i18n/locales/lazy/cookies_de.json +0 -0
  60. package/i18n/locales/lazy/cookies_en.json +0 -0
  61. package/i18n/locales/lazy/cookies_es.json +0 -0
  62. package/i18n/locales/lazy/cookies_fr.json +0 -0
  63. package/i18n/locales/lazy/cookies_it.json +0 -0
  64. package/i18n/locales/lazy/cookies_ja.json +0 -0
  65. package/i18n/locales/lazy/cookies_ko.json +0 -0
  66. package/i18n/locales/lazy/cookies_nl.json +0 -0
  67. package/i18n/locales/lazy/cookies_pt.json +0 -0
  68. package/i18n/locales/lazy/cookies_zh.json +0 -0
  69. package/i18n/locales/lazy/crud_ar.json +6 -5
  70. package/i18n/locales/lazy/crud_da.json +6 -5
  71. package/i18n/locales/lazy/crud_de.json +6 -5
  72. package/i18n/locales/lazy/crud_en.json +7 -5
  73. package/i18n/locales/lazy/crud_es.json +6 -5
  74. package/i18n/locales/lazy/crud_fr.json +7 -5
  75. package/i18n/locales/lazy/crud_it.json +6 -5
  76. package/i18n/locales/lazy/crud_ja.json +6 -5
  77. package/i18n/locales/lazy/crud_ko.json +6 -5
  78. package/i18n/locales/lazy/crud_nl.json +6 -5
  79. package/i18n/locales/lazy/crud_pt.json +6 -5
  80. package/i18n/locales/lazy/crud_zh.json +6 -5
  81. package/i18n/locales/lazy/homeTemplate_ar.json +0 -0
  82. package/i18n/locales/lazy/homeTemplate_da.json +0 -0
  83. package/i18n/locales/lazy/homeTemplate_de.json +0 -0
  84. package/i18n/locales/lazy/homeTemplate_en.json +0 -0
  85. package/i18n/locales/lazy/homeTemplate_es.json +0 -0
  86. package/i18n/locales/lazy/homeTemplate_fr.json +0 -0
  87. package/i18n/locales/lazy/homeTemplate_it.json +0 -0
  88. package/i18n/locales/lazy/homeTemplate_ja.json +0 -0
  89. package/i18n/locales/lazy/homeTemplate_ko.json +0 -0
  90. package/i18n/locales/lazy/homeTemplate_nl.json +0 -0
  91. package/i18n/locales/lazy/homeTemplate_pt.json +0 -0
  92. package/i18n/locales/lazy/homeTemplate_zh.json +0 -0
  93. package/i18n/locales/lazy/legalNotice_en.json +0 -0
  94. package/i18n/locales/lazy/legalNotice_fr.json +0 -0
  95. package/i18n/locales/lazy/legalNotice_pt.json +0 -0
  96. package/i18n/locales/lazy/legalNotice_zh.json +0 -0
  97. package/i18n/locales/lazy/oauth_ar.json +0 -0
  98. package/i18n/locales/lazy/oauth_da.json +0 -0
  99. package/i18n/locales/lazy/oauth_de.json +0 -0
  100. package/i18n/locales/lazy/oauth_en.json +0 -0
  101. package/i18n/locales/lazy/oauth_es.json +0 -0
  102. package/i18n/locales/lazy/oauth_fr.json +0 -0
  103. package/i18n/locales/lazy/oauth_it.json +0 -0
  104. package/i18n/locales/lazy/oauth_ja.json +0 -0
  105. package/i18n/locales/lazy/oauth_ko.json +0 -0
  106. package/i18n/locales/lazy/oauth_nl.json +0 -0
  107. package/i18n/locales/lazy/oauth_pt.json +0 -0
  108. package/i18n/locales/lazy/oauth_zh.json +0 -0
  109. package/i18n/locales/lazy/privacy_ar.json +0 -0
  110. package/i18n/locales/lazy/privacy_da.json +0 -0
  111. package/i18n/locales/lazy/privacy_de.json +0 -0
  112. package/i18n/locales/lazy/privacy_en.json +0 -0
  113. package/i18n/locales/lazy/privacy_es.json +0 -0
  114. package/i18n/locales/lazy/privacy_fr.json +0 -0
  115. package/i18n/locales/lazy/privacy_it.json +0 -0
  116. package/i18n/locales/lazy/privacy_ja.json +0 -0
  117. package/i18n/locales/lazy/privacy_ko.json +0 -0
  118. package/i18n/locales/lazy/privacy_nl.json +0 -0
  119. package/i18n/locales/lazy/privacy_pt.json +0 -0
  120. package/i18n/locales/lazy/privacy_zh.json +1 -1
  121. package/i18n/locales/lazy/terms_ar.json +0 -0
  122. package/i18n/locales/lazy/terms_da.json +0 -0
  123. package/i18n/locales/lazy/terms_de.json +0 -0
  124. package/i18n/locales/lazy/terms_en.json +0 -0
  125. package/i18n/locales/lazy/terms_es.json +0 -0
  126. package/i18n/locales/lazy/terms_fr.json +0 -0
  127. package/i18n/locales/lazy/terms_it.json +0 -0
  128. package/i18n/locales/lazy/terms_ja.json +0 -0
  129. package/i18n/locales/lazy/terms_ko.json +0 -0
  130. package/i18n/locales/lazy/terms_nl.json +0 -0
  131. package/i18n/locales/lazy/terms_pt.json +0 -0
  132. package/i18n/locales/lazy/terms_zh.json +0 -0
  133. package/index.d.ts +928 -215
  134. package/index.js +6 -502
  135. package/next/index.js +258 -68
  136. package/package.json +10 -7
  137. package/server.d.ts +866 -119
  138. package/server.js +1 -1
  139. package/vite/index.d.ts +8 -0
  140. package/vite/index.js +66 -58
package/server.js CHANGED
@@ -1,4 +1,4 @@
1
- var qr=Object.create;var je=Object.defineProperty;var Gr=Object.getOwnPropertyDescriptor;var jr=Object.getOwnPropertyNames;var Kr=Object.getPrototypeOf,Wr=Object.prototype.hasOwnProperty;var Dt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Yr=(e,t)=>{for(var r in t)je(e,r,{get:t[r],enumerable:!0})},zr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jr(t))!Wr.call(e,i)&&i!==r&&je(e,i,{get:()=>t[i],enumerable:!(n=Gr(t,i))||n.enumerable});return e};var _t=(e,t,r)=>(r=e!=null?qr(Kr(e)):{},zr(t||!e||!e.__esModule?je(r,"default",{value:e,enumerable:!0}):r,e));var _r=Dt(S=>{"use strict";var St=Symbol.for("react.transitional.element"),Ai=Symbol.for("react.portal"),Ri=Symbol.for("react.fragment"),wi=Symbol.for("react.strict_mode"),Pi=Symbol.for("react.profiler"),ki=Symbol.for("react.consumer"),Oi=Symbol.for("react.context"),Di=Symbol.for("react.forward_ref"),_i=Symbol.for("react.suspense"),Ni=Symbol.for("react.memo"),Rr=Symbol.for("react.lazy"),Ui=Symbol.for("react.activity"),xr=Symbol.iterator;function Fi(e){return e===null||typeof e!="object"?null:(e=xr&&e[xr]||e["@@iterator"],typeof e=="function"?e:null)}var wr={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Pr=Object.assign,kr={};function le(e,t,r){this.props=e,this.context=t,this.refs=kr,this.updater=r||wr}le.prototype.isReactComponent={};le.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};le.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Or(){}Or.prototype=le.prototype;function Tt(e,t,r){this.props=e,this.context=t,this.refs=kr,this.updater=r||wr}var xt=Tt.prototype=new Or;xt.constructor=Tt;Pr(xt,le.prototype);xt.isPureReactComponent=!0;var Ir=Array.isArray;function Et(){}var C={H:null,A:null,T:null,S:null},Dr=Object.prototype.hasOwnProperty;function It(e,t,r){var n=r.ref;return{$$typeof:St,type:e,key:t,ref:n!==void 0?n:null,props:r}}function Mi(e,t){return It(e.type,t,e.props)}function Ct(e){return typeof e=="object"&&e!==null&&e.$$typeof===St}function Li(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var Cr=/\/+/g;function bt(e,t){return typeof e=="object"&&e!==null&&e.key!=null?Li(""+e.key):t.toString(36)}function Vi(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(Et,Et):(e.status="pending",e.then(function(t){e.status==="pending"&&(e.status="fulfilled",e.value=t)},function(t){e.status==="pending"&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function ae(e,t,r,n,i){var s=typeof e;(s==="undefined"||s==="boolean")&&(e=null);var a=!1;if(e===null)a=!0;else switch(s){case"bigint":case"string":case"number":a=!0;break;case"object":switch(e.$$typeof){case St:case Ai:a=!0;break;case Rr:return a=e._init,ae(a(e._payload),t,r,n,i)}}if(a)return i=i(e),a=n===""?"."+bt(e,0):n,Ir(i)?(r="",a!=null&&(r=a.replace(Cr,"$&/")+"/"),ae(i,t,r,"",function(h){return h})):i!=null&&(Ct(i)&&(i=Mi(i,r+(i.key==null||e&&e.key===i.key?"":(""+i.key).replace(Cr,"$&/")+"/")+a)),t.push(i)),1;a=0;var d=n===""?".":n+":";if(Ir(e))for(var p=0;p<e.length;p++)n=e[p],s=d+bt(n,p),a+=ae(n,t,r,s,i);else if(p=Fi(e),typeof p=="function")for(e=p.call(e),p=0;!(n=e.next()).done;)n=n.value,s=d+bt(n,p++),a+=ae(n,t,r,s,i);else if(s==="object"){if(typeof e.then=="function")return ae(Vi(e),t,r,n,i);throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.")}return a}function He(e,t,r){if(e==null)return e;var n=[],i=0;return ae(e,n,"","",function(s){return t.call(r,s,i++)}),n}function Bi(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var Ar=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}},$i={map:He,forEach:function(e,t,r){He(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return He(e,function(){t++}),t},toArray:function(e){return He(e,function(t){return t})||[]},only:function(e){if(!Ct(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};S.Activity=Ui;S.Children=$i;S.Component=le;S.Fragment=Ri;S.Profiler=Pi;S.PureComponent=Tt;S.StrictMode=wi;S.Suspense=_i;S.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=C;S.__COMPILER_RUNTIME={__proto__:null,c:function(e){return C.H.useMemoCache(e)}};S.cache=function(e){return function(){return e.apply(null,arguments)}};S.cacheSignal=function(){return null};S.cloneElement=function(e,t,r){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var n=Pr({},e.props),i=e.key;if(t!=null)for(s in t.key!==void 0&&(i=""+t.key),t)!Dr.call(t,s)||s==="key"||s==="__self"||s==="__source"||s==="ref"&&t.ref===void 0||(n[s]=t[s]);var s=arguments.length-2;if(s===1)n.children=r;else if(1<s){for(var a=Array(s),d=0;d<s;d++)a[d]=arguments[d+2];n.children=a}return It(e.type,i,n)};S.createContext=function(e){return e={$$typeof:Oi,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:ki,_context:e},e};S.createElement=function(e,t,r){var n,i={},s=null;if(t!=null)for(n in t.key!==void 0&&(s=""+t.key),t)Dr.call(t,n)&&n!=="key"&&n!=="__self"&&n!=="__source"&&(i[n]=t[n]);var a=arguments.length-2;if(a===1)i.children=r;else if(1<a){for(var d=Array(a),p=0;p<a;p++)d[p]=arguments[p+2];i.children=d}if(e&&e.defaultProps)for(n in a=e.defaultProps,a)i[n]===void 0&&(i[n]=a[n]);return It(e,s,i)};S.createRef=function(){return{current:null}};S.forwardRef=function(e){return{$$typeof:Di,render:e}};S.isValidElement=Ct;S.lazy=function(e){return{$$typeof:Rr,_payload:{_status:-1,_result:e},_init:Bi}};S.memo=function(e,t){return{$$typeof:Ni,type:e,compare:t===void 0?null:t}};S.startTransition=function(e){var t=C.T,r={};C.T=r;try{var n=e(),i=C.S;i!==null&&i(r,n),typeof n=="object"&&n!==null&&typeof n.then=="function"&&n.then(Et,Ar)}catch(s){Ar(s)}finally{t!==null&&r.types!==null&&(t.types=r.types),C.T=t}};S.unstable_useCacheRefresh=function(){return C.H.useCacheRefresh()};S.use=function(e){return C.H.use(e)};S.useActionState=function(e,t,r){return C.H.useActionState(e,t,r)};S.useCallback=function(e,t){return C.H.useCallback(e,t)};S.useContext=function(e){return C.H.useContext(e)};S.useDebugValue=function(){};S.useDeferredValue=function(e,t){return C.H.useDeferredValue(e,t)};S.useEffect=function(e,t){return C.H.useEffect(e,t)};S.useEffectEvent=function(e){return C.H.useEffectEvent(e)};S.useId=function(){return C.H.useId()};S.useImperativeHandle=function(e,t,r){return C.H.useImperativeHandle(e,t,r)};S.useInsertionEffect=function(e,t){return C.H.useInsertionEffect(e,t)};S.useLayoutEffect=function(e,t){return C.H.useLayoutEffect(e,t)};S.useMemo=function(e,t){return C.H.useMemo(e,t)};S.useOptimistic=function(e,t){return C.H.useOptimistic(e,t)};S.useReducer=function(e,t,r){return C.H.useReducer(e,t,r)};S.useRef=function(e){return C.H.useRef(e)};S.useState=function(e){return C.H.useState(e)};S.useSyncExternalStore=function(e,t,r){return C.H.useSyncExternalStore(e,t,r)};S.useTransition=function(){return C.H.useTransition()};S.version="19.2.4"});var At=Dt((Gp,Nr)=>{"use strict";Nr.exports=_r()});var ir={};Yr(ir,{AuthHardening:()=>Me,CURRENCY_MAP:()=>it,ConditionBuilder:()=>oe,DEFAULT_CRUD_TIMEOUT:()=>Mo,DEFAULT_ERROR_MESSAGES:()=>X,DEFAULT_UPLOAD_TIMEOUT:()=>Fo,DoNotDevError:()=>A,SingletonManager:()=>ct,addMonths:()=>ye,addYears:()=>ft,calculateSubscriptionEndDate:()=>Bo,captureErrorToSentry:()=>nt,clearGlobalSingleton:()=>fo,commonErrorCodeMappings:()=>me,compactToISOString:()=>st,configureProviders:()=>vo,createAsyncSingleton:()=>go,createErrorHandler:()=>B,createMetadata:()=>$n,createMethodProxy:()=>ho,createSingleton:()=>he,createSingletonWithParams:()=>mo,detectErrorSource:()=>tt,ensureSpreadable:()=>Un,evaluateCondition:()=>Q,evaluateFieldConditions:()=>ko,filterVisibleFields:()=>Co,formatCurrency:()=>qn,formatDate:()=>Jt,formatRelativeTime:()=>Xn,generateCodeChallenge:()=>Zt,generateCodeVerifier:()=>Qt,generateFirestoreRuleCondition:()=>ro,generatePKCEPair:()=>oo,generateUUID:()=>Uo,getConditionDependencies:()=>Do,getCurrencyLocale:()=>Xt,getCurrencySymbol:()=>Hn,getCurrentTimestamp:()=>Kn,getGlobalSingleton:()=>dt,getListCardFieldNames:()=>ve,getProvider:()=>yo,getRoleFromClaims:()=>co,getVisibleFields:()=>pt,getWeekFromISOString:()=>zn,handleError:()=>y,hasProvider:()=>bo,hasRestrictedVisibility:()=>Ao,hasRoleAccess:()=>Ne,hasTierAccess:()=>po,isCompactDateString:()=>at,isFieldVisible:()=>nr,isPKCESupported:()=>io,isoToCompactString:()=>Gn,lazyImport:()=>uo,mapToDoNotDevError:()=>J,maybeTranslate:()=>no,normalizeToISOString:()=>jn,parseDate:()=>lt,parseDateToNoonUTC:()=>Qn,parseISODate:()=>$o,parseServerCookie:()=>jo,resetProviders:()=>Eo,safeValidate:()=>Nn,sanitizeHref:()=>No,showNotification:()=>Pn,timestampToISOString:()=>Yn,toDateOnly:()=>Zn,toISOString:()=>Wn,translateArray:()=>Mn,translateArrayRange:()=>Vn,translateArrayWithIndices:()=>Bn,translateObjectArray:()=>Ln,updateMetadata:()=>So,validateCodeChallenge:()=>ao,validateCodeVerifier:()=>so,validateEnvVar:()=>Go,validateMetadata:()=>qo,validateUrl:()=>Ho,validateWithSchema:()=>_n,when:()=>Oo,withErrorHandling:()=>wn,withGracefulDegradation:()=>lo,withTimeout:()=>Lo,wrapAuthError:()=>Dn,wrapCrudError:()=>kn,wrapStorageError:()=>On});var V={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},Pe={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},es={[V.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[V.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[V.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},ts={maxTokens:4096,temperature:.7,stream:!0},rs={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_API_KEY:"invalid_api_key",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",PROVIDER_ERROR:"provider_error",TOKEN_LIMIT_EXCEEDED:"token_limit_exceeded",STREAM_INTERRUPTED:"stream_interrupted"},ns={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},os=4,is={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}};import*as c from"valibot";var Nt=c.object({role:c.picklist([Pe.USER,Pe.ASSISTANT,Pe.SYSTEM]),content:c.pipe(c.string(),c.minLength(1)),id:c.optional(c.string()),createdAt:c.optional(c.string())}),Ke=c.lazy(()=>c.object({type:c.picklist(["string","number","boolean","array","object"]),description:c.optional(c.string()),enum:c.optional(c.array(c.string())),items:c.optional(Ke),properties:c.optional(c.record(c.string(),Ke)),required:c.optional(c.array(c.string()))})),Xr=c.object({description:c.pipe(c.string(),c.minLength(1)),parameters:c.object({type:c.literal("object"),properties:c.record(c.string(),Ke),required:c.optional(c.array(c.string()))})}),Jr=c.object({id:c.string(),name:c.string(),args:c.record(c.string(),c.unknown())}),Qr=c.object({messages:c.pipe(c.array(Nt),c.minLength(1)),provider:c.optional(c.picklist([V.ANTHROPIC,V.OPENAI,V.GOOGLE])),model:c.optional(c.string()),maxTokens:c.optional(c.pipe(c.number(),c.integer(),c.minValue(1))),temperature:c.optional(c.pipe(c.number(),c.minValue(0),c.maxValue(2))),systemPrompt:c.optional(c.string()),stream:c.optional(c.boolean()),tools:c.optional(c.record(c.string(),Xr))}),Zr=c.object({promptTokens:c.number(),completionTokens:c.number(),totalTokens:c.number()}),en=c.object({message:Nt,usage:c.optional(Zr),finishReason:c.optional(c.string()),toolCalls:c.optional(c.array(Jr))}),ls=c.object({provider:c.picklist([V.ANTHROPIC,V.OPENAI,V.GOOGLE]),model:c.optional(c.string()),maxTokens:c.optional(c.pipe(c.number(),c.integer(),c.minValue(1))),temperature:c.optional(c.pipe(c.number(),c.minValue(0),c.maxValue(2))),systemPrompt:c.optional(c.string())});function us(e){return c.safeParse(Qr,e)}function cs(e){return c.safeParse(en,e)}var w={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function hs(e){Object.assign(w,e)}var ce={FREE:"free",PRO:"pro",PREMIUM:"premium"};function vs(e){Object.assign(ce,e)}var We={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function ys(e){Object.assign(We,e)}var Ye={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function bs(e){Object.assign(Ye,e)}import*as l from"valibot";var ne={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Ss(e){Object.assign(ne,e)}var ke={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function Ts(e){Object.assign(ke,e)}var xs={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function Is(e){return{tier:"free",status:"active",subscriptionId:null,customerId:e,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var Ut={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},Cs={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as o from"valibot";var Ft=o.pipe(o.object({userId:o.optional(o.string()),productId:o.optional(o.string()),priceId:o.optional(o.string()),unitAmount:o.optional(o.pipe(o.number(),o.integer(),o.minValue(1))),productName:o.optional(o.pipe(o.string(),o.minLength(1))),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code"))),successUrl:o.pipe(o.string(),o.url()),cancelUrl:o.pipe(o.string(),o.url()),customerEmail:o.optional(o.pipe(o.string(),o.email())),userEmail:o.optional(o.pipe(o.string(),o.email())),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean()),mode:o.optional(o.picklist([ke.PAYMENT,ke.SUBSCRIPTION]))}),o.check(e=>!!(e.priceId||e.unitAmount&&e.productName),"Either priceId or (unitAmount + productName) is required")),Mt=o.object({sessionId:o.string(),sessionUrl:o.nullable(o.pipe(o.string(),o.url()))}),Lt=o.object({userId:o.string(),tier:o.string(),status:o.picklist(Object.values(ne)),subscriptionId:o.nullable(o.string()),customerId:o.string(),subscriptionEnd:o.nullable(o.pipe(o.string(),o.isoTimestamp())),cancelAtPeriodEnd:o.boolean(),updatedAt:o.pipe(o.string(),o.isoTimestamp())}),Vt=o.object({tier:o.string(),subscriptionId:o.nullable(o.string()),customerId:o.string(),status:o.picklist(Object.values(ne)),subscriptionEnd:o.nullable(o.pipe(o.string(),o.isoTimestamp())),cancelAtPeriodEnd:o.boolean(),updatedAt:o.pipe(o.string(),o.isoTimestamp()),isDefault:o.optional(o.boolean())}),Bt=o.object({id:o.string(),type:o.string(),data:o.object({object:o.any()}),created:o.pipe(o.string(),o.isoTimestamp())}),$t=o.looseObject({userId:o.optional(o.string()),firebaseUid:o.optional(o.string()),productType:o.optional(o.string())});function ws(e){return o.safeParse(Ft,e)}function Ps(e){return o.safeParse(Mt,e)}function ks(e){return o.safeParse(Lt,e)}function Os(e){return o.safeParse(Vt,e)}function Ds(e){return o.safeParse(Bt,e)}function _s(e){return o.safeParse($t,e)}var tn=o.object({type:o.literal("StripePayment"),name:o.pipe(o.string(),o.minLength(1,"Product name is required")),description:o.optional(o.string()),price:o.string(),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:o.optional(o.pipe(o.string(),o.minLength(1,"Stripe price ID is required"))),unitAmount:o.optional(o.pipe(o.number(),o.integer(),o.minValue(1))),productName:o.optional(o.pipe(o.string(),o.minLength(1))),maxUnitAmount:o.optional(o.pipe(o.number(),o.integer(),o.minValue(1))),tier:o.pipe(o.string(),o.minLength(1,"Tier is required")),duration:o.pipe(o.string(),o.minLength(1,"Duration is required")),allowPromotionCodes:o.optional(o.boolean()),metadata:o.optional(o.record(o.string(),o.string()))}),rn=o.object({type:o.literal("StripeSubscription"),name:o.pipe(o.string(),o.minLength(1,"Product name is required")),description:o.optional(o.string()),price:o.string(),currency:o.optional(o.pipe(o.string(),o.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:o.pipe(o.string(),o.minLength(1,"Stripe price ID is required")),tier:o.pipe(o.string(),o.minLength(1,"Tier is required")),duration:o.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:o.optional(o.boolean()),metadata:o.optional(o.record(o.string(),o.string()))}),nn=o.variant("type",[tn,rn]),Ns=o.record(o.string(),nn),on=o.record(o.string(),o.object({name:o.string(),price:o.string(),currency:o.string(),description:o.optional(o.string()),features:o.optional(o.array(o.string())),priceId:o.optional(o.string()),unitAmount:o.optional(o.number()),productName:o.optional(o.string()),allowPromotionCodes:o.optional(o.boolean())})),sn=o.record(o.string(),o.object({type:o.picklist(["StripePayment","StripeSubscription"]),name:o.string(),price:o.number(),currency:o.string(),priceId:o.optional(o.string()),unitAmount:o.optional(o.pipe(o.number(),o.integer(),o.minValue(1))),productName:o.optional(o.pipe(o.string(),o.minLength(1))),maxUnitAmount:o.optional(o.pipe(o.number(),o.integer(),o.minValue(1))),tier:o.string(),duration:o.string(),description:o.optional(o.string()),metadata:o.optional(o.record(o.string(),o.string())),allowPromotionCodes:o.optional(o.boolean())}));function Us(e){return o.parse(on,e)}function Fs(e){return o.parse(sn,e)}function Ms(){let e={createCheckoutSessionRequest:o.safeParse(Ft,{}),createCheckoutSessionResponse:o.safeParse(Mt,{}),subscriptionData:o.safeParse(Lt,{}),subscriptionClaims:o.safeParse(Vt,{}),webhookEvent:o.safeParse(Bt,{}),checkoutSessionMetadata:o.safeParse($t,{})};return{success:Object.values(e).every(t=>t.success),results:e}}var Ht=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(Object.values(w))),customClaims:l.optional(l.record(l.string(),l.any()))}),ze=l.object({userId:l.string(),tier:l.picklist(Object.values(ce)),status:l.picklist(Object.values(ne)),isActive:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.nullable(l.string()),customerId:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),cancelAtPeriodEnd:l.boolean(),updatedAt:l.pipe(l.string(),l.isoTimestamp())}),qt=l.object({role:l.optional(l.picklist(Object.values(w))),subscription:l.optional(ze),features:l.optional(l.array(l.picklist(Object.values(We)))),permissions:l.optional(l.array(l.picklist(Object.values(Ye)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function js(e){return l.safeParse(Ht,e)}function Ks(e){return l.safeParse(ze,e)}function Ws(e){return l.safeParse(qt,e)}function Ys(){let e={authUser:l.safeParse(Ht,{}),userSubscription:l.safeParse(ze,{}),customClaims:l.safeParse(qt,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}var Xs={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},Js={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Qs(e){return{userId:e,role:"user",preferences:{},metadata:{}}}var x={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},Y={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},R={CLIENT:"client",SERVER:"server",BUILD:"build"},D={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},de={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},ia={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},sa={USER:"user",GLOBAL:"global",SESSION:"session"},aa={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},la={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},ua={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var da={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},pa={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"},Xe={create:"admin",read:"guest",update:"admin",delete:"admin"},z={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},fa={ASC:"asc",DESC:"desc"},ma={LIST:"list",LIST_CARD:"listCard"},ga=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var ya={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},ba={EQ:z.EQ,NEQ:z.NEQ,LT:z.LT,LTE:z.LTE,GT:z.GT,GTE:z.GTE};import*as m from"valibot";var Ca=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),data:m.record(m.string(),m.unknown()),idempotencyKey:m.optional(m.string())}),Aa=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required"))}),Ra=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required")),data:m.record(m.string(),m.unknown()),merge:m.optional(m.boolean(),!1)}),wa=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required"))}),Pa=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),limit:m.optional(m.pipe(m.number(),m.minValue(1),m.maxValue(1e3)),1e3),offset:m.optional(m.pipe(m.number(),m.minValue(0)),0),orderBy:m.optional(m.string()),orderDirection:m.optional(m.picklist(["asc","desc"]),"desc"),where:m.optional(m.array(m.object({field:m.string(),operator:m.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:m.unknown()})))});var Va={RESEND:"resend"},Ba={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_REQUEST:"invalid_request",PROVIDER_ERROR:"provider_error",TEMPLATE_NOT_FOUND:"template_not_found",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",MISSING_API_KEY:"missing_api_key"};import*as T from"valibot";var an=T.object({templateId:T.pipe(T.string(),T.minLength(1)),to:T.pipe(T.string(),T.email()),data:T.record(T.string(),T.unknown()),locale:T.optional(T.pipe(T.string(),T.minLength(2),T.maxLength(5)),"fr"),from:T.optional(T.string()),replyTo:T.optional(T.string())}),ln=T.object({success:T.boolean(),messageId:T.optional(T.string()),error:T.optional(T.string())});function Ha(e){return T.safeParse(an,e)}function qa(e){return T.safeParse(ln,e)}var pe={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},za={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},Oe={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},Je={[pe.PERMISSION_DENIED]:{type:Oe.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[pe.NOT_FOUND]:{type:Oe.NOT_FOUND,message:"The requested resource was not found"},[pe.ALREADY_EXISTS]:{type:Oe.ALREADY_EXISTS,message:"The resource already exists"},[pe.INVALID_ARGUMENT]:{type:Oe.VALIDATION_ERROR,message:"Invalid argument provided"}},Gt=class extends Error{type;originalError;constructor(t,r,n){super(r),this.name="EntityHookError",this.type=t,this.originalError=n}},Xa={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"},A=class e extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=pe.INTERNAL,n){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=n?.details,this.source=n?.source,this.originalError=n?.originalError,this.context=n?.context,this.displayable=n?.displayable??!0,this.userMessageProvided=n?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var el={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var rl={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var ol={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var sl={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var ll={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var Qe={mobile:0,tablet:768,laptop:1024,desktop:1440},un={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function cn(e){return e>=Qe.desktop?"desktop":e>=Qe.laptop?"laptop":e>=Qe.tablet?"tablet":"mobile"}function Sl(e,t){let r=un[t];return e>=r.min&&e<=r.max}function Tl(e,t){let r=cn(e);return{current:r,width:e,height:t,isMobile:r==="mobile",isTablet:r==="tablet",isLaptop:r==="laptop",isDesktop:r==="desktop",isMobileOrTablet:r==="mobile"||r==="tablet",isLaptopOrDesktop:r==="laptop"||r==="desktop"}}var dn="landing",pn={FIXED:"fixed",SCROLL:"scroll"},fn={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var jt=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var Ze=f.object({owner:f.pipe(f.string(),f.minLength(1,"Repository owner is required")),repo:f.pipe(f.string(),f.minLength(1,"Repository name is required"))}),mn=f.picklist([...jt]),Ul=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Ze,permission:f.optional(mn,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),Fl=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Ze}),Ml=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:Ze}),Ll=f.object({provider:f.string(),purpose:f.picklist(["authentication","api-access"]),code:f.pipe(f.string(),f.minLength(1,"Authorization code is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required")),codeVerifier:f.optional(f.string()),state:f.optional(f.string()),instance:f.optional(f.pipe(f.string(),f.url()))}),Vl=f.object({provider:f.string(),refreshToken:f.pipe(f.string(),f.minLength(1,"Refresh token is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required"))}),Bl=f.object({provider:f.string()}),$l=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var Wl={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as g from"valibot";var Kt=g.object({name:g.string(),color:g.string(),icon:g.string(),customParameters:g.optional(g.record(g.string(),g.string())),button:g.object({backgroundColor:g.string(),textColor:g.string(),borderColor:g.string(),hoverBackgroundColor:g.string(),focusOutlineColor:g.string(),fontWeight:g.optional(g.string(),"500"),textKey:g.optional(g.string())})}),gn=g.object({...Kt.entries,type:g.picklist(["auth","both"]),scopes:g.optional(g.array(g.string())),firebaseProviderId:g.optional(g.string())}),De=g.union([g.literal(""),g.pipe(g.string(),g.url())]),hn=g.object({authUrl:De,tokenUrl:De,profileUrl:De,revokeUrl:g.optional(De)}),vn=g.object({authentication:g.optional(g.array(g.string())),"api-access":g.array(g.string())}),yn=g.optional(g.object({pkce:g.optional(g.boolean(),!1),codeChallengeMethod:g.optional(g.picklist(["S256","plain"]),"S256")})),bn=g.object({...Kt.entries,type:g.picklist(["oauth","both"]),scopes:vn,endpoints:hn,capabilities:yn}),fe={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},et={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},En=g.record(g.string(),gn),Sn=g.record(g.string(),bn);function zl(){return g.safeParse(En,fe)}function Xl(){return g.safeParse(Sn,et)}function Tn(e){return e in fe}function xn(e){return e in et}var Wt={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},su={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},au={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:Wt.ANALYTICS},marketing:{requiresConsent:Wt.MARKETING}};function tt(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}import*as zt from"valibot";function B(e){return(t,r)=>{if(t instanceof A)return t;if(typeof t!="object"||t===null){let d=typeof t=="string"?t:e.defaultErrorMessage;return new A(r||d,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let n;e.extractErrorCode?n=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(n=t.code);let i=e.defaultErrorCode;n&&e.errorCodeMapping&&n in e.errorCodeMapping&&(i=e.errorCodeMapping[n]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),n&&e.friendlyMessageMapping&&n in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[n]),s||(s=e.defaultErrorMessage);let a;return e.processMetadata?a=e.processMetadata(t):(a={originalError:t},n&&(a.originalCode=n)),"originalError"in a||(a.originalError=t),new A(r||s,i,{details:a,source:e.errorSource})}}var me={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var X={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},In={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},rt={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},q={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...me},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...me},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(In).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},processMetadata:e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:me,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:X.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:X["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:X.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},Cn=e=>e instanceof zt.ValiError?new A(X["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):B(q.validation)(e),An=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in rt){let t=e,r=rt[t.type]||"unknown";return new A(t.message||X[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&Je[e.code]){let t=e,r=Je[t.code];if(r){let n=rt[r.type]||"unknown";return new A(r.message||X[n],n,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return B(q.entity)(e)},Yt={auth:B(q.auth),oauth:B(q.oauth),api:B(q.api),firebase:B(q.firebase),ui:B(q.ui),validation:Cn,entity:An,unknown:B(q.unknown)};function J(e,t,r){return e instanceof A?e:(Yt[t]||Yt.unknown)(e,r)}function nt(e,t,r={}){let n=globalThis.Sentry;n&&n.withScope(i=>{i.setTag("errorSource",t),i.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,a])=>{if(typeof a!="function"&&s!=="originalError")try{i.setExtra(s,a)}catch{i.setExtra(s,`[${typeof a}]`)}}),Object.entries(r).forEach(([s,a])=>{if(typeof a!="function")try{i.setExtra(`context.${s}`,a)}catch{i.setExtra(`context.${s}`,`[${typeof a}]`)}}),(e.details?.userId||r.userId)&&i.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),n.captureException(e)})}function Rn(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}function y(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:n,context:i={},log:s=!0,reportToSentry:a=!0,showNotification:d=!1,severity:p="error"}=r,h=tt(e),v=e instanceof A?e:J(e,h,n);if(n&&!v.userMessageProvided&&(v.message.includes("Error")||v.message.includes("Failed")||v.message.length<10?v=new A(n,v.code,{details:{...v.details,originalMessage:v.message},source:h,userMessageProvided:!0}):v=new A(v.message,v.code,{details:{...v.details,userMessage:n},source:h,userMessageProvided:!0})),s){let O=Rn()||typeof window<"u"&&window.__DNDEV_DEBUG,H={code:v.code,message:v.message,source:h};switch(p){case"warning":break;case"info":break;case"success":break;default:}}return a&&nt(v,h,i),v}function wn(e,t){return async(...r)=>{try{return await e(...r)}catch(n){throw y(n,t)}}}function Pn(e,t="info",r){let n=Date.now().toString();return n}function kn(e,t,r,n,i){let s=`${t}.${r}(${n}${i?`, ${i}`:""})`;return J(e,"api",`${s}: ${ot(e)}`)}function On(e,t,r,n){let i=`${t}.${r}(${n})`;return J(e,"api",`${i}: ${ot(e)}`)}function Dn(e,t,r,n){let i=n?` ${JSON.stringify(n)}`:"",s=`${t}.${r}(${i})`,a=J(e,"auth",`${s}: ${ot(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&a.code==="unknown"&&e.code!=="unknown"?new A(a.message,a.code,{details:{...a.details,originalCode:e.code},source:a.source}):a}function ot(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}import*as ge from"valibot";function _n(e,t,r){try{return ge.parse(e,t)}catch(n){throw n instanceof ge.ValiError?new A(`Validation failed in ${r}: ${n.message}`,"validation-failed",{details:{issues:n.issues,input:t},source:"validation"}):new A(`Unexpected validation error in ${r}: ${Fn(n)}`,"validation-failed",{originalError:n instanceof Error?n:new Error(String(n)),source:"validation"})}}function Nn(e,t){try{return ge.parse(e,t)}catch{return null}}function Un(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function Fn(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function Mn(e,t,r,n={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:a}=n;return Array.from({length:r},(d,p)=>{let h=`${t}.${p}`;return e(h)}).filter((d,p)=>{let h=`${t}.${p}`;return!(d===h||s&&d.trim()===""||d.length<i||a&&!a(d,p))})}function Ln(e,t,r,n){return Array.from({length:r},(i,s)=>{let a=`${t}.${s}.${String(n[0])}`;if(e(a)===a)return null;let p={};for(let h of n){let v=`${t}.${s}.${String(h)}`;p[h]=e(v)}return p}).filter(i=>i!==null)}function Vn(e,t,r,n,i={}){let{minLength:s=0,excludeEmpty:a=!0,customFilter:d}=i;return Array.from({length:n-r},(p,h)=>{let v=r+h,O=`${t}.${v}`;return e(O)}).filter((p,h)=>{let v=r+h,O=`${t}.${v}`;return!(p===O||a&&p.trim()===""||p.length<s||d&&!d(p,v))})}function Bn(e,t,r,n={}){let{minLength:i=0,excludeEmpty:s=!0,customFilter:a}=n;return Array.from({length:r},(d,p)=>{let h=`${t}.${p}`;return{item:e(h),originalIndex:p}}).filter(({item:d,originalIndex:p})=>{let h=`${t}.${p}`;return!(d===h||s&&d.trim()===""||d.length<i||a&&!a(d,p))})}function $n(e){let t=new Date().toISOString();return{_createdAt:t,_updatedAt:t,_createdBy:e,_updatedBy:e}}var it={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function Xt(e){return it[e]?.locale??"en-US"}function Hn(e){return!e||typeof e!="string"?e??"":it[e]?.symbol??e}function qn(e,t,r={}){if(e==null||isNaN(e))return"";let n=Xt(t);return new Intl.NumberFormat(n,{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:2,currencyDisplay:"symbol",...r}).format(e)}function st(e){let t=e.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!t||t.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${e}`);let r=t[1],n=t[2],i=t[3],s=t[4],a=t[5],d=new Date(parseInt(r,10),parseInt(n,10)-1,parseInt(i,10),parseInt(s,10),parseInt(a,10));if(isNaN(d.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return d.toISOString()}function Gn(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0"),s=String(t.getUTCHours()).padStart(2,"0"),a=String(t.getUTCMinutes()).padStart(2,"0");return`${r}${n}${i}:${s}${a}`}function at(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function jn(e){if(!e)return new Date().toISOString();if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return e.toISOString()}if(typeof e=="string"){if(at(e))return st(e);let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string: ${e}`);return t.toISOString()}if(typeof e=="number"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp: ${e}`);return t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")return t.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof e}`)}function Kn(){return new Date().toISOString()}function Wn(e){return e.toISOString()}function Yn(e){return new Date(e).toISOString()}function zn(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=new Date(t.getFullYear(),0,1),n=Math.floor((t.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((n+r.getDay()+1)/7)}, ${t.getFullYear()}`}var U={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function Xn(e,t="en",r={}){if(!e)return"";let{style:n="long",numeric:i="auto",fallbackThreshold:s=U.WEEK}=r,a;if(e instanceof Date)a=e;else if(typeof e=="string")a=new Date(e);else if(typeof e=="number")a=new Date(e);else if(typeof e=="object"&&"toDate"in e)a=e.toDate();else return"";if(isNaN(a.getTime()))return"";let d=new Date,p=a.getTime()-d.getTime(),h=Math.round(p/1e3),v=Math.abs(h);if(v>s)return Jt(a.toISOString(),t);let O=new Intl.RelativeTimeFormat(t,{style:n,numeric:i});return v<U.MINUTE?O.format(h,"second"):v<U.HOUR?O.format(Math.round(h/U.MINUTE),"minute"):v<U.DAY?O.format(Math.round(h/U.HOUR),"hour"):v<U.WEEK?O.format(Math.round(h/U.DAY),"day"):v<U.MONTH?O.format(Math.round(h/U.WEEK),"week"):v<U.YEAR?O.format(Math.round(h/U.MONTH),"month"):O.format(Math.round(h/U.YEAR),"year")}function Jn(e){switch(e){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function Jt(e,t="en",r="long"){if(!e)return"";let n;if(e instanceof Date)n=e;else if(typeof e=="string")n=new Date(e);else if(typeof e=="number")n=new Date(e);else if(typeof e=="object"&&"toDate"in e)n=e.toDate();else return"";if(isNaN(n.getTime()))return"";let i=typeof r=="string"?Jn(r):r;return new Intl.DateTimeFormat(t,i).format(n)}function lt(e){if(e!=null){if(e instanceof Date)return isNaN(e.getTime())?void 0:e.toISOString();if(typeof e=="string"){let t=e.trim();if(!t)return;if(at(t))try{return st(t)}catch{return}let r=new Date(t);return isNaN(r.getTime())?void 0:r.toISOString()}if(typeof e=="number"){if(!Number.isFinite(e))return;let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")try{let r=t.toDate();return isNaN(r.getTime())?void 0:r.toISOString()}catch{return}}if(typeof e=="object"&&e!==null&&"seconds"in e&&typeof e.seconds=="number"){let t=e,r=t.seconds*1e3+(t.nanoseconds||0)/1e6,n=new Date(r);return isNaN(n.getTime())?void 0:n.toISOString()}}}function Qn(e){let t=lt(e);if(!t)return;let r=new Date(t);return r.setUTCHours(12,0,0,0),r.toISOString()}function Zn(e){let t=lt(e);return t&&t.split("T")[0]||""}function eo(e){return typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:typeof e=="boolean"?e?"true":"false":String(e)}function to(e){let t=`resource.data.${e.field}`,r=eo(e.value);return`${t} ${e.op} ${r}`}function ro(e){let t=[];if(e.publicCondition&&e.publicCondition.length>0){let r=e.publicCondition.map(to).join(" && ");t.push(`(${r})`)}for(let r of e.ownerFields)t.push(`request.auth.uid == resource.data.${r}`);return t.length===0?"false":t.join(" || ")}function no(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}function Qt(){let e=new Uint8Array(32);return crypto.getRandomValues(e),er(e)}async function Zt(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return er(new Uint8Array(n))}async function oo(){let e=Qt(),t=await Zt(e);return{codeVerifier:e,codeChallenge:t}}function er(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function io(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function so(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function ao(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}async function lo(e,t,r){try{return await e()}catch{return t(),!1}}var _e=new Map;function uo(e,t){if(_e.has(t))return _e.get(t);let r=e().catch(n=>{throw _e.delete(t),n});return _e.set(t,r),r}var tr={[w.GUEST]:0,[w.USER]:1,[w.ADMIN]:2,[w.SUPER]:3};function Ne(e,t){if(!e)return!1;let r=tr[e]??-1,n=tr[t]??1/0;return r>=n}function co(e){return e?e.role===w.SUPER||e.isSuper===!0?w.SUPER:e.role===w.ADMIN||e.isAdmin===!0?w.ADMIN:e.role===w.USER?w.USER:e.role||w.USER:w.USER}function po(e,t,r){if(!e)return!1;let n=r??Ut,i=n[e]?.level??-1,s=n[t]?.level??1/0;return i>=s}var ut="__DNDEV_SINGLETONS__";function rr(){if(typeof globalThis<"u"){let e=globalThis;return e[ut]||(e[ut]=new Map),e[ut]}return new Map}function dt(e,t){let r=rr();return r.has(e)||r.set(e,t()),r.get(e)}function fo(e){rr().delete(e)}function he(e,...t){let r=null,n=!1;return function(){if(r!==null)return r;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{n=!1}}}function mo(e){let t=null,r=!1;return function(...i){if(t!==null)return t;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof e=="function"&&e.prototype?t=new e(...i):t=e(...i),t}finally{r=!1}}}function go(e){let t=null,r=!1,n=null;return async function(){if(t!==null)return t;if(r&&n)return n;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return n=e(),t=await n,t}finally{r=!1,n=null}}}function ho(e,t){return new Proxy({},{get(r,n){if(t.includes(n)){let s=e(),a=s[n];return typeof a=="function"?a.bind(s):a}return e()[n]}})}var ct=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(t,r,n={}){if(this.instances.has(t))return this.instances.get(t);if(this.initialized.has(t))return this.instances.get(t);if(this.initializing.has(t))throw new Error(`Circular dependency detected for singleton: ${t}`);if(n.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u",n.fallbackFactory){let i=n.fallbackFactory();return this.instances.set(t,i),this.initialized.add(t),i}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let i=await r();return this.instances.set(t,i),this.initialized.add(t),i}catch(i){if(typeof process<"u",n.cacheFailures&&this.initialized.add(t),n.fallbackFactory){let s=n.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw i}finally{this.initializing.delete(t)}}static isInitialized(t){return this.initialized.has(t)}static clear(t){this.instances.delete(t),this.initialized.delete(t),this.initializing.delete(t)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function Ue(){return dt("providers",()=>({providers:null}))}function vo(e){let t=Ue();t.providers,t.providers=e}function yo(e){let{providers:t}=Ue();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let r=t[e];if(!r)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return r}function bo(e){return!!Ue().providers?.[e]}function Eo(){Ue().providers=null}function So(e){return{_updatedAt:new Date().toISOString(),_updatedBy:e}}function To(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function xo(e){if(To(e))return e.visibility}function nr(e,t){let r=e??"guest";return r==="hidden"?!1:r==="technical"?Ne(t,"admin"):r==="owner"?!1:Ne(t,r)}function Io(e,t,r){for(let n of r.ownerFields)if(e[n]===t)return!0;return!1}function pt(e,t,r){let n=e;if(!n||typeof n!="object"||!n.entries)return[];let i=n.entries,s=[],{documentData:a,uid:d,ownership:p}=r??{},h=p&&d!=null&&a&&Io(a,d,p);for(let[v,O]of Object.entries(i)){let H=xo(O);if(H==="owner"){h&&s.push(v);continue}nr(H,t)&&s.push(v)}return s}function Co(e,t,r,n){if(!e)return{};let i=n?.uid!=null&&n?.ownership!=null?{documentData:n.documentData??e,uid:n.uid,ownership:n.ownership}:void 0,s=pt(t,r,i),a={};for(let d of s)Object.prototype.hasOwnProperty.call(e,d)&&(a[d]=e[d]);return a}function ve(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let r=t,n=[...r.title??[],...r.subtitle??[],...r.content??[],...r.footer??[]];return[...new Set(n)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}function Fe(e){if(!(!e||typeof e!="object")){if(e.entries&&typeof e.entries=="object")return e.entries;if(Array.isArray(e.pipe))for(let t of e.pipe){let r=Fe(t);if(r)return r}if(e.wrapped)return Fe(e.wrapped);if(Array.isArray(e.options))for(let t of e.options){let r=Fe(t);if(r)return r}}}function Ao(e){let t=Fe(e);if(!t)return!1;for(let r of Object.values(t)){let n=r?.visibility;if(n!==void 0&&n!=="guest")return!0}return!1}var Me=class{store=new Map;maxAttempts;lockoutMs;sessionTimeoutMs;constructor(t={}){this.maxAttempts=t.maxAttempts??5,this.lockoutMs=t.lockoutMs??900*1e3,this.sessionTimeoutMs=t.sessionTimeoutMs??480*60*1e3}checkLockout(t){let r=this.store.get(t);if(r?.lockedUntil){if(Date.now()<r.lockedUntil){let n=Math.ceil((r.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${n} minute${n===1?"":"s"}.`)}this.store.delete(t)}}recordFailure(t){let r=Date.now();!this.store.has(t)&&this.store.size>=1e4&&this._evictExpired(r);let n=this.store.get(t)??{attempts:0,lastAttempt:0,lockedUntil:null};return n.attempts+=1,n.lastAttempt=r,n.attempts>=this.maxAttempts&&(n.lockedUntil=r+this.lockoutMs),this.store.set(t,n),{attempts:n.attempts,locked:n.lockedUntil!==null&&Date.now()<n.lockedUntil,lockedUntil:n.lockedUntil}}_evictExpired(t){for(let[r,n]of this.store)n.lockedUntil!==null&&t>n.lockedUntil?this.store.delete(r):n.lockedUntil===null&&t-n.lastAttempt>this.lockoutMs&&this.store.delete(r)}recordSuccess(t){this.store.delete(t)}isSessionExpired(t){return Date.now()-t>this.sessionTimeoutMs}getEntry(t){return this.store.get(t)}};function Ro(e,t){if(t.includes(".")){let r=t.split("."),n=e;for(let i of r){if(n==null||typeof n!="object")return;n=n[i]}return n}return e[t]}function wo(e,t){let r=Ro(t,e.field);switch(e.operator){case"equals":return r===e.value;case"notEquals":return r!==e.value;case"in":return Array.isArray(e.value)&&e.value.includes(r);case"notIn":return Array.isArray(e.value)&&!e.value.includes(r);case"greaterThan":return typeof r=="number"&&typeof e.value=="number"&&r>e.value;case"lessThan":return typeof r=="number"&&typeof e.value=="number"&&r<e.value;case"greaterThanOrEqual":return typeof r=="number"&&typeof e.value=="number"&&r>=e.value;case"lessThanOrEqual":return typeof r=="number"&&typeof e.value=="number"&&r<=e.value;case"exists":return r!=null&&r!==""&&r!==!1;case"notExists":return r==null||r===""||r===!1;case"contains":return typeof r=="string"&&typeof e.value=="string"||Array.isArray(r)?r.includes(e.value):!1;default:return!1}}function Po(e){return e instanceof oe||"expression"in e?e.expression:e}function Q(e,t){let r=Po(e);if(r.type==="condition")return wo(r,t);let{logic:n,conditions:i}=r;return n==="and"?i.every(s=>Q(s,t)):i.some(s=>Q(s,t))}function ko(e,t){return e?{visible:e.visible?Q(e.visible,t):!0,disabled:e.disabled?Q(e.disabled,t):!1,required:e.required?Q(e.required,t):!1,readonly:e.readonly?Q(e.readonly,t):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var oe=class e{expression;constructor(t){this.expression=t}get type(){return this.expression.type}or(t){let r=t instanceof e?t.expression:t,n=this.expression;return n.type==="group"&&n.logic==="or"?new e({type:"group",logic:"or",conditions:[...n.conditions,r]}):new e({type:"group",logic:"or",conditions:[n,r]})}and(t){let r=t instanceof e?t.expression:t,n=this.expression;return n.type==="group"&&n.logic==="and"?new e({type:"group",logic:"and",conditions:[...n.conditions,r]}):new e({type:"group",logic:"and",conditions:[n,r]})}};function Oo(e){function t(r,n){return new oe({type:"condition",field:e,operator:r,value:n})}return{equals:r=>t("equals",r),notEquals:r=>t("notEquals",r),in:r=>t("in",r),notIn:r=>t("notIn",r),greaterThan:r=>t("greaterThan",r),lessThan:r=>t("lessThan",r),greaterThanOrEqual:r=>t("greaterThanOrEqual",r),lessThanOrEqual:r=>t("lessThanOrEqual",r),exists:()=>t("exists"),notExists:()=>t("notExists"),contains:r=>t("contains",r)}}function Do(e){let t=e instanceof oe?e.expression:e,r=new Set;function n(i){if(i.type==="condition")r.add(i.field);else for(let s of i.conditions)n(s)}return n(t),r}var _o=new Set(["http:","https:","mailto:","tel:","blob:"]);function No(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let r=new URL(t);if(_o.has(r.protocol))return t}catch{return t}return""}function Uo(){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Fo=3e4,Mo=15e3;function Lo(e,t,r){if(r?.aborted)return Promise.reject(or(r.reason));let n=t>0;return!n&&!r?e:new Promise((i,s)=>{let a=!1,d;function p(){a=!0,d!==void 0&&(clearTimeout(d),d=void 0),r&&r.removeEventListener("abort",h)}function h(){a||(p(),s(or(r?.reason)))}r&&r.addEventListener("abort",h,{once:!0}),n&&(d=setTimeout(()=>{a||(p(),s(Vo(t)))},t)),e.then(v=>{a||(p(),i(v))},v=>{a||(p(),s(v))})})}function Vo(e){let t=new Error(`Operation timed out after ${e}ms`);return t.name="TimeoutError",t}function or(e){if(e instanceof Error){let r=new Error(e.message);return r.name="AbortError",r}let t=new Error(typeof e=="string"?e:"Operation was aborted");return t.name="AbortError",t}function ye(e,t){let r=new Date(e),n=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==n&&r.setDate(0),r}function ft(e,t){let r=new Date(e),n=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==n&&r.setDate(0),r}function Bo(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=ye(t,1):e==="3months"?r=ye(t,3):e==="6months"?r=ye(t,6):e==="1year"?r=ft(t,1):e==="2years"?r=ft(t,2):r=ye(t,1),r.toISOString()}function $o(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}function Ho(e,t="URL"){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return e}catch(r){throw new Error(`Invalid ${t}: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}function qo(e){let t={};for(let[r,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);if(/<[^>]*>/.test(n))throw new Error(`Metadata value for key '${r}' must not contain HTML`);let i=n;if(i.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=i}return t}function Go(e,t=!0){let r=process.env[e];if(t&&!r)throw new Error(`Required environment variable '${e}' is not set`);return r||""}function jo(e,t){if(!e)return null;let r=`${encodeURIComponent(t)}=`,n=e.split(";");for(let i=0;i<n.length;i++){let s=n[i];if(s){for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(r)===0)return decodeURIComponent(s.substring(r.length,s.length))}}return null}function Td(e,t){let r=e;return r.metadata=t,r}import*as u from"valibot";var be=new Map;function b(e,t){be.set(e,t)}function Id(e){return be.has(e)}function Cd(){return Array.from(be.keys())}function Ad(){be.clear()}function I(e,t){return t?e:u.nullish(e)}var Le=e=>{let t=[];e.validation?.minLength!==void 0&&t.push(u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(u.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(u.regex(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?u.pipe(u.string(),...t):u.string();return I(r,e.validation?.required)},Ko=e=>{let t=u.pipe(u.string(),u.email("Invalid email address"));return I(t,e.validation?.required)},Wo=e=>{let t=e.validation?.minLength!==void 0?u.pipe(u.string(),u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):u.string();return I(t,e.validation?.required)},Yo=e=>{let t=u.pipe(u.string(),u.url("Invalid URL"));return I(t,e.validation?.required)},ie=e=>{let t=[];e.validation?.min!==void 0&&t.push(u.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(u.maxValue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?u.pipe(u.number(),...t):u.number();return I(r,e.validation?.required)},sr=e=>{let t=u.boolean();return I(t,e.validation?.required)},se=e=>{let t=u.pipe(u.string(),u.check(r=>!isNaN(new Date(r).getTime()),"Invalid date format"));return I(t,e.validation?.required)},cr=u.object({url:u.string(),filename:u.string(),size:u.number(),mimeType:u.nullish(u.string()),uploadedAt:u.nullish(u.string())}),ar=e=>{let t=u.nullable(cr);return I(t,e.validation?.required)},lr=e=>{let t=u.array(cr);return I(t,e.validation?.required)},dr=u.object({fullUrl:u.string(),thumbUrl:u.string()}),zo=e=>I(dr,e.validation?.required),Xo=e=>{let t=u.array(dr);return I(t,e.validation?.required)},Jo=e=>{let t=u.object({lat:u.number(),lng:u.number()});return I(t,e.validation?.required)},Qo=e=>{let t=u.object({formatted_address:u.string(),latitude:u.number(),longitude:u.number(),street_number:u.nullish(u.string()),route:u.nullish(u.string()),locality:u.nullish(u.string()),administrative_area_level_1:u.nullish(u.string()),administrative_area_level_2:u.nullish(u.string()),country:u.nullish(u.string()),postal_code:u.nullish(u.string())});return I(t,e.validation?.required)},Zo=e=>{let t=u.record(u.string(),u.unknown());return I(t,e.validation?.required)},ei=e=>{let t=u.array(u.unknown());return I(t,e.validation?.required)},mt=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(s=>s.value),i=u.picklist(n);return I(i,e.validation?.required)}let r=u.union([u.string(),u.number()]);return I(r,e.validation?.required)},ti=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(s=>s.value),i=u.array(u.picklist(n));return I(i,e.validation?.required)}let r=u.array(u.string());return I(r,e.validation?.required)},ri=e=>{let t=u.pipe(u.string(),u.minLength(1,"Invalid ID format"));return I(t,e.validation?.required)},gt=e=>{let t=u.string();return I(t,e.validation?.required)},ni=e=>{let t=u.string();return I(t,e.validation?.required)},oi=e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,n=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",i=[];if(t!==void 0&&i.push(u.minLength(t,`IBAN must be at least ${t} characters`)),r!==void 0&&i.push(u.maxLength(r,`IBAN must not exceed ${r} characters`)),n){let a=typeof n=="string"?new RegExp(n):n;i.push(u.regex(a,"Invalid IBAN format"))}let s=i.length>0?u.pipe(u.string(),...i):u.string();return I(s,e.validation?.required)},ur=()=>u.never(),ii=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let n=[t.checkedValue,t.uncheckedValue],i=u.picklist(n);return I(i,e.validation?.required)}let r=u.boolean();return I(r,e.validation?.required)},si=e=>u.custom(r=>e.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),ai=e=>{let t=u.object({amount:u.number(),currency:u.optional(u.string()),vatIncluded:u.optional(u.boolean()),discountPercent:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(100)))});return I(t,e.validation?.required)};function li(){b("text",Le),b("textarea",Le),b("richtext",Le),b("color",Le),b("email",Ko),b("password",Wo),b("url",Yo),b("tel",ni),b("iban",oi),b("number",ie),b("currency",ie),b("price",ai),b("range",ie),b("year",ie),b("rating",ie),b("duration",ie),b("boolean",sr),b("checkbox",sr),b("gdprConsent",si),b("date",se),b("datetime-local",se),b("time",se),b("week",se),b("month",se),b("timestamp",se),b("file",ar),b("files",lr),b("document",ar),b("documents",lr),b("image",zo),b("images",Xo),b("geopoint",Jo),b("address",Qo),b("map",Zo),b("array",ei),b("select",mt),b("multiselect",ti),b("radio",mt),b("combobox",mt),b("switch",ii),b("reference",ri),b("hidden",gt),b("avatar",gt),b("badge",gt),b("submit",ur),b("reset",ur)}li();function Ee(e){if(e.validation?.schema){let n=e.validation.schema;return I(n,e.validation?.required)}let t=be.get(e.type);if(t){let n=t(e);if(n!==null)return n}let r=u.unknown();return I(r,e.validation?.required)}function F(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var G=null;function xe(){return fr().platform}function fr(){if(G)return G;let e=F();if(e?.platform)return G={platform:e.platform,mode:e.mode,context:e.context,version:e.version,metadata:{detectedAt:e.timestamp}},G;let t=[];t.push(...ui()),t.push(...ci()),t.push(...di());let r=t.sort((n,i)=>i.confidence-n.confidence)[0];return!r||r.confidence<D.MINIMUM?(G={platform:x.UNKNOWN,mode:pr(),context:pi(),metadata:{detectedAt:Date.now()}},G):(G={platform:r.platform,mode:pr(),context:r.context,version:fi(r.platform),metadata:{...r.metadata,detectedAt:Date.now()}},G)}var Se=null,Te=null;function mr(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return Te=!0,!0;if(Te===!0)return!0;let e=F();if(e?.platform){let r=e.platform===x.NEXTJS;return r&&(Te=!0),r}let t=xe()===x.NEXTJS;return t&&(Te=!0),t}function gr(){if(Se!==null)return Se;let e=F();if(e?.platform)return Se=e.platform===x.VITE,Se;let t=xe()===x.VITE;return Se=t,t}function M(){return typeof window<"u"&&typeof document<"u"}function ht(){return typeof process<"u"&&!!process.versions?.node}function ui(){let e=[];if(M()){globalThis.__vite_plugin_react_preamble_installed__&&e.push({platform:x.VITE,confidence:D.HIGH,context:R.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let t=F();t?.platform===x.VITE&&e.push({platform:x.VITE,confidence:D.HIGH,context:R.CLIENT}),t?.i18n?.mapping&&e.push({platform:x.VITE,confidence:D.MEDIUM,context:R.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&e.push({platform:x.VITE,confidence:D.LOW,context:R.CLIENT})}return ht()&&(process.env.VITE&&e.push({platform:x.VITE,confidence:D.MEDIUM,context:R.SERVER}),process.env.npm_lifecycle_event?.includes(x.VITE)&&e.push({platform:x.VITE,confidence:D.LOW,context:R.BUILD})),e}function ci(){let e=[];return ht()&&(process.env.NEXT_RUNTIME&&e.push({platform:x.NEXTJS,confidence:D.HIGH,context:R.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&e.push({platform:x.NEXTJS,confidence:D.MEDIUM,context:R.SERVER}),process.env._DNDEV_CONFIG_&&e.push({platform:x.NEXTJS,confidence:D.LOW,context:R.SERVER})),M()&&(F()?.platform===x.NEXTJS&&e.push({platform:x.NEXTJS,confidence:D.HIGH,context:R.CLIENT}),globalThis.__NEXT_DATA__&&e.push({platform:x.NEXTJS,confidence:D.LOW,context:R.CLIENT})),e}function di(){let e=[];try{typeof globalThis<"u"&&globalThis.expo?.Constants?.expoConfig&&e.push({platform:x.EXPO,confidence:D.HIGH,context:R.CLIENT})}catch{}try{typeof globalThis<"u"&&globalThis.Platform?.OS&&!M()&&e.push({platform:x.REACT_NATIVE,confidence:D.MEDIUM,context:R.CLIENT})}catch{}let t=F();return t?.platform===x.EXPO?e.push({platform:x.EXPO,confidence:D.HIGH,context:R.CLIENT}):t?.platform===x.REACT_NATIVE&&e.push({platform:x.REACT_NATIVE,confidence:D.HIGH,context:R.CLIENT}),e}function pr(){let e;return typeof import.meta<"u"&&import.meta.env?.MODE?e=import.meta.env.MODE:typeof process<"u"&&(e="production"),e===Y.PRODUCTION?Y.PRODUCTION:e===Y.TEST?Y.TEST:Y.DEVELOPMENT}function pi(){return M()?R.CLIENT:ht()?Y.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?R.BUILD:R.SERVER:R.CLIENT}function fi(e){if(!(typeof process>"u"))return e===x.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:e===x.NEXTJS?process.env.NEXT_PUBLIC_APP_VERSION||process.env.NEXT_PUBLIC_VERSION||process.env.__NEXT_VERSION||process.env.APP_VERSION:process.env.APP_VERSION||process.env.VITE_APP_VERSION||process.env.NEXT_PUBLIC_APP_VERSION}function hr(e){return e&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e)}function mi(e){let t,r=F();return r?.env&&typeof r.env=="object"&&(t=r.env[e]),t===void 0&&typeof import.meta<"u"&&import.meta.env&&(t=import.meta.env[e]),hr(t)}function gi(e){let t=F(),r;return t?.env&&typeof t.env=="object"&&(r=t.env[e]),r===void 0&&typeof process<"u"&&process.env&&(r=process.env[e]),hr(r)}function P(e,t){if(e==="NODE_ENV"||e==="VITE_NODE_ENV"||e==="NEXT_PUBLIC_NODE_ENV"||e==="MODE"||e==="DEV"||e==="PROD"){let a=F();if(a?.env?.MODE)return e==="DEV"?a.env.MODE==="development"?"true":"false":e==="PROD"?a.env.MODE==="production"?"true":"false":a.env.MODE;if(typeof import.meta<"u"&&import.meta.env){let d=import.meta.env;if(e==="MODE"&&d.MODE)return d.MODE;if(e==="DEV")return d.DEV?"true":"false";if(e==="PROD")return d.PROD?"true":"false"}if(typeof process<"u"){let d="production";return e==="DEV"?d==="development"?"true":"false":e==="PROD"?d==="production"?"true":"false":d}return e==="DEV"?"true":e==="PROD"?"false":"development"}let r=F()?.platform,n=t||r||(gr()?"vite":mr()?"nextjs":xe()),i=["MODE","DEV","PROD","SSR"],s;return n==="vite"?i.includes(e)||e.startsWith("VITE_")?s=e:s=`VITE_${e}`:n==="nextjs"?e.startsWith("NEXT_PUBLIC_")?s=e:s=`NEXT_PUBLIC_${e}`:s=e,n==="vite"?mi(s):n==="nextjs"?gi(s):void 0}function Z(){if(typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production"))return!0;let e=P("APP_ENV"),t=P("NODE_ENV");return(e||t||"development").toLowerCase()!=="production"}function Ie(e){return typeof e=="object"&&e!==null&&"currentUser"in e&&typeof e.currentUser=="object"&&e.currentUser!==null}var hi=12e4,vt=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(t=null,r={}){this.authInstance=t,this.refreshBuffer=r.refreshBufferMs??hi,this.maxRefreshAttempts=r.maxRefreshAttempts??3,this.autoRefresh=r.autoRefresh!==!1,this.onTokenExpired=r.onTokenExpired,this.onFatalError=r.onFatalError}initialize(t){this.clearRefreshTimer(),this.refreshAttempts=0;let r=this.calculateTokenStatus(t.expiresAt);this.tokenInfo={...t,status:r},this.autoRefresh&&t.expiresAt&&this.scheduleRefresh(t.expiresAt)}getTokenInfo(){return this.tokenInfo}reset(){this.clearRefreshTimer(),this.tokenInfo={token:null,expiresAt:null,status:"not-initialized"}}async forceRefresh(t){try{if(this.refreshCallback&&await this.refreshCallback()&&this.tokenInfo.token)return this.tokenInfo.token;if(t&&typeof t.getIdToken=="function"){let r=await t.getIdToken(!0),n=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:r,expiresAt:n}),this.refreshAttempts=0,r}else if(t&&typeof t.getIdTokenResult=="function"){let r=await t.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),this.refreshAttempts=0,r.token}if(Ie(this.authInstance)){let r=await this.authInstance.currentUser.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),this.refreshAttempts=0,r.token}throw y(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(r){return this.handleError(r instanceof Error?r:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:t,token:r}=this.tokenInfo;if(t==="valid")return r;if((t==="expiring-soon"||t==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(Ie(this.authInstance))return await this.forceRefresh(this.authInstance.currentUser)}catch(n){this.handleError(n instanceof Error?n:new Error("Failed to refresh token"))}return t==="expired"||t==="not-initialized"||t==="error"?null:r}onRefreshNeeded(t){return this.refreshCallback=t,()=>{this.refreshCallback=void 0}}updateTokenInfo(t){let r={token:t.token??this.tokenInfo.token,expiresAt:t.expiresAt??this.tokenInfo.expiresAt,refreshToken:t.refreshToken??this.tokenInfo.refreshToken,idToken:t.idToken??this.tokenInfo.idToken},n=this.calculateTokenStatus(r.expiresAt);this.tokenInfo={...r,status:n},this.autoRefresh&&r.expiresAt&&this.scheduleRefresh(r.expiresAt)}calculateTokenStatus(t){if(!t)return this.tokenInfo.token?"valid":"not-initialized";let r=new Date;if(r>=t)return"expired";let n=new Date(t.getTime()-this.refreshBuffer);return r>=n?"expiring-soon":"valid"}scheduleRefresh(t){this.clearRefreshTimer();let r=new Date,n=t.getTime()-r.getTime()-this.refreshBuffer;if(n<=0){Ie(this.authInstance)&&this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)});return}this.refreshTimerId=setTimeout(()=>{Ie(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(i=>{this.handleRefreshError(i)}):this.refreshCallback&&this.refreshCallback().catch(i=>{this.handleRefreshError(i)})},n)}handleRefreshError(t){if(Z(),this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let r=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);Z(),setTimeout(()=>{Ie(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(n=>{this.handleRefreshError(n)}):this.refreshCallback&&this.refreshCallback().catch(n=>{this.handleRefreshError(n)})},r)}else this.tokenInfo={...this.tokenInfo,status:"error",error:t instanceof Error?t:new Error("Max token refresh attempts reached")},this.onTokenExpired&&this.onTokenExpired(),this.onFatalError&&this.onFatalError(t instanceof Error?t:new Error("Max token refresh attempts reached"))}handleError(t){Z(),this.tokenInfo={...this.tokenInfo,status:"error",error:t}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},Jd=he(vt,null,{});var Ve=class{buildKey(t,r,n,i=!1){let s="dndev";switch(r){case"user":if(!n){if(i)return null;throw y(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:t,scope:r}})}return`${s}:user:${n}:${t}`;case"global":return`${s}:global:${t}`;case"session":return`${s}:session:${t}`;default:return`${s}:${t}`}}};var ee=null,vi="dndev-keys",Ce="encryption-keys",vr="main";async function yr(){return new Promise((e,t)=>{let r=indexedDB.open(vi,1);r.onupgradeneeded=()=>{r.result.createObjectStore(Ce)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}async function yi(e){let t=await yr();return new Promise((r,n)=>{let i=t.transaction(Ce,"readwrite");i.objectStore(Ce).put(e,vr),i.oncomplete=()=>r(),i.onerror=()=>n(i.error)})}async function bi(){try{let e=await yr();return new Promise((t,r)=>{let i=e.transaction(Ce,"readonly").objectStore(Ce).get(vr);i.onsuccess=()=>t(i.result??null),i.onerror=()=>r(i.error)})}catch{return null}}async function Ei(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(e){throw y(e,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function br(){if(ee)return ee;try{let e=await bi();return e?(ee=e,ee):(ee=await Ei(),await yi(ee),ee)}catch(e){throw y(e,{userMessage:"Failed to get or create encryption key"})}}async function Er(e){try{let t=await br(),r=window.crypto.getRandomValues(new Uint8Array(12)),n=typeof e=="string"?e:JSON.stringify(e),s=new TextEncoder().encode(n),a=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},t,s),d=new Uint8Array(r.length+a.byteLength);return d.set(r,0),d.set(new Uint8Array(a),r.length),btoa(String.fromCharCode(...d))}catch(t){throw y(t,{userMessage:"Failed to encrypt data"})}}async function Sr(e){try{let t=await br(),r=Uint8Array.from(atob(e),p=>p.charCodeAt(0)),n=r.slice(0,12),i=r.slice(12),s=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:n},t,i),d=new TextDecoder().decode(s);try{return JSON.parse(d)}catch{return d}}catch(t){throw y(t,{userMessage:"Failed to decrypt data"})}}var j=class extends Ve{userId=null;constructor(t=null){super(),this.userId=t}setUserId(t){this.userId=t}async get(t,r={}){let{scope:n="user",encryption:i=!1}=r,s=this.buildKey(t,n,this.userId,!0);if(!s)return null;try{if(!M())return null;let a=localStorage.getItem(s);if(!a)return null;let d=JSON.parse(a);if(d.expiresAt&&new Date(d.expiresAt)<new Date)return await this.remove(t),null;let p=d.value;return i&&typeof p=="string"&&(p=await Sr(p)),p}catch(a){throw y(a,{userMessage:"Failed to retrieve data from local storage",context:{key:t,options:r}})}}async set(t,r,n={}){let{scope:i="user",encryption:s=!1,expiry:a=0}=n,d=this.buildKey(t,i,this.userId,!0);if(d)try{let p=r;s&&(p=await Er(r));let h=a>0?new Date(Date.now()+a*1e3).toISOString():null,v=JSON.stringify({value:p,expiresAt:h,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(d,v)}catch(p){let h=p?.name==="QuotaExceededError"||p?.code===22?"Storage quota exceeded. Please free up space or login to sync to cloud.":p?.name==="SecurityError"||p?.code===18?"Storage access denied. Please enable localStorage or login to sync to cloud.":"Failed to store data in local storage";throw y(p,{userMessage:h,context:{key:t,options:n}})}}async remove(t){let r=["user","global","session"];for(let n of r)try{let i=this.buildKey(t,n,this.userId,!0);if(!i)continue;typeof window<"u"&&localStorage.removeItem(i)}catch{}}async clear(t){if(!t){let a=(typeof window<"u"?Object.keys(localStorage):[]).filter(d=>d.startsWith("dndev:"));for(let d of a)typeof window<"u"&&localStorage.removeItem(d);return}let r=t==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${t}:`,i=(typeof window<"u"?Object.keys(localStorage):[]).filter(s=>s.startsWith(r));for(let s of i)typeof window<"u"&&localStorage.removeItem(s)}};var Ae=class{localStrategy;userId;apiEndpoint;getAuthToken;constructor(t,r="/api/storage",n){if(!t)throw y(new Error("User ID is required for HybridStorageStrategy"));this.userId=t,this.localStrategy=new j(t),this.apiEndpoint=r,this.getAuthToken=n}async buildHeaders(t){let r={};if(t&&(r["Content-Type"]=t),this.getAuthToken){let n=await this.getAuthToken();n&&(r.Authorization=`Bearer ${n}`)}return r}async get(t,r={}){try{let n=await this.localStrategy.get(t,r);return n!==null?n:await this.getFromCloud(t,r)}catch(n){try{return await this.localStrategy.get(t,r)}catch(i){throw y(n,{userMessage:"Failed to retrieve data from storage",context:{key:t,options:r,fallbackError:i}})}}}async set(t,r,n={}){await this.localStrategy.set(t,r,n),this.setToCloud(t,r,n).catch(i=>{y(i,{userMessage:"Failed to save data to cloud storage",severity:"warning",context:{key:t,options:n}})})}async remove(t){try{await this.localStrategy.remove(t),this.removeFromCloud(t).catch(r=>{y(r,{severity:"warning",showNotification:!1})})}catch(r){throw y(r,{userMessage:"Failed to remove data",context:{key:t}})}}async clear(t){try{await this.localStrategy.clear(t),this.clearFromCloud(t).catch(r=>{})}catch(r){throw y(r,{userMessage:"Failed to clear storage",context:{scope:t}})}}buildKey(t,r,n,i=!1){let s="dndev";switch(r){case"user":if(!n){if(i)return null;throw y(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:t,scope:r}})}return`${s}:user:${n}:${t}`;case"global":return`${s}:global:${t}`;case"session":return`${s}:session:${t}`;default:return`${s}:${t}`}}async getFromCloud(t,r){try{let{scope:n="user"}=r,i=this.buildKey(t,n,this.userId,!0);if(!i)return null;let s=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{headers:await this.buildHeaders()});if(!s.ok){if(s.status===404)return null;throw y(new Error(`Cloud storage API error: ${s.status} ${s.statusText}`),{userMessage:"Failed to retrieve data from cloud storage",severity:"warning",context:{key:t,status:s.status}})}let a=await s.json();return a.expiresAt&&new Date(a.expiresAt)<new Date?(this.removeFromCloud(t).catch(console.warn),null):(this.localStrategy.set(t,a.value,r).catch(console.warn),a.value)}catch{return null}}async setToCloud(t,r,n){let{scope:i="user",expiry:s=0}=n,a=this.buildKey(t,i,this.userId,!0);if(!a)return;let d=s>0?new Date(Date.now()+s*1e3).toISOString():null,p={value:r,expiresAt:d,createdAt:new Date().toISOString()},h=await fetch(`${this.apiEndpoint}/${encodeURIComponent(a)}`,{method:"PUT",headers:await this.buildHeaders("application/json"),body:JSON.stringify(p)});if(!h.ok)throw y(new Error(`Cloud storage API error: ${h.status} ${h.statusText}`),{userMessage:"Failed to save data to cloud storage",severity:"error",context:{key:t,status:h.status}})}async removeFromCloud(t){let r=["user","global","session"];for(let n of r)try{let i=this.buildKey(t,n,this.userId,!0);if(!i)continue;let s=await fetch(`${this.apiEndpoint}/${encodeURIComponent(i)}`,{method:"DELETE",headers:await this.buildHeaders()});!s.ok&&s.status}catch{}}async clearFromCloud(t){try{let r=new URLSearchParams;t&&r.append("scope",t),t==="user"&&r.append("userId",this.userId);let n=r.toString(),i=n?`${this.apiEndpoint}/clear?${n}`:`${this.apiEndpoint}/clear`;(await fetch(i,{method:"DELETE",headers:await this.buildHeaders()})).ok}catch{}}};var Be=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(t=new j){this.strategy=t}initialize(){if(!this.initialized)try{this.initialized=!0}catch(t){y(t,{severity:"warning",showNotification:!1})}}setStrategy(t){this.initialize(),this.strategy=t}updateUser(t,r){this.initialize(),r&&t?this.strategy=new Ae(t):this.strategy=new j(t)}updateStrategy(){this.isPro&&this.userId?this.strategy=new Ae(this.userId):this.strategy=new j(this.userId)}async get(t,r={}){return this.initialize(),this.strategy.get(t,r)}async set(t,r,n={}){return this.initialize(),this.strategy.set(t,r,n)}async remove(t){return this.initialize(),this.strategy.remove(t)}async clear(t){return this.initialize(),this.strategy.clear(t)}async setSecure(t,r,n={}){return this.initialize(),this.set(t,r,{...n,encryption:!0})}async getSecure(t,r={}){return this.initialize(),this.get(t,{...r,encryption:!0})}},Si=he(Be);import*as E from"valibot";var Tr=E.object({name:E.string(),color:E.string(),icon:E.string(),button:E.object({backgroundColor:E.string(),textColor:E.string(),borderColor:E.string(),hoverBackgroundColor:E.string(),focusOutlineColor:E.string(),fontWeight:E.optional(E.string(),"500")})}),Ti=E.object({...Tr.entries,type:E.picklist(["auth","both"]),scopes:E.optional(E.array(E.string())),firebaseProviderId:E.optional(E.string())}),$e=E.union([E.literal(""),E.pipe(E.string(),E.url())]),xi=E.object({authUrl:$e,tokenUrl:$e,profileUrl:$e,revokeUrl:E.optional($e)}),Ii=E.object({authentication:E.optional(E.array(E.string())),"api-access":E.array(E.string())}),Np=E.object({...Tr.entries,type:E.picklist(["oauth","both"]),scopes:Ii,endpoints:xi}),Re=null;function Ci(){let e=[];for(let[t,r]of Object.entries(fe))E.safeParse(Ti,r).success?e.push(t):typeof window<"u"&&Z();return e}function yt(){if(Re!==null)return Re;let e=P("AUTH_PARTNERS");if(!e)return Re=[],Re;let t=Ci(),r=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>t.includes(n));return Re=r,r}var L={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage",AI:"ai"};function K(e){return!!e&&e.trim()!==""}var Bp={[L.AUTH]:()=>yt().length>0,[L.OAUTH]:()=>["VITE_GOOGLE_CLIENT_ID","VITE_GITHUB_CLIENT_ID","VITE_FACEBOOK_CLIENT_ID","VITE_TWITTER_CLIENT_ID","VITE_LINKEDIN_CLIENT_ID","VITE_DISCORD_CLIENT_ID","VITE_SLACK_CLIENT_ID","VITE_MICROSOFT_CLIENT_ID","VITE_APPLE_CLIENT_ID"].some(t=>K(P(t))),[L.I18N]:()=>!0,[L.BILLING]:()=>!!(K(P("STRIPE_PUBLISHABLE_KEY"))||K(P("BILLING_ENABLED"))&&P("BILLING_ENABLED")==="true"),[L.ROUTES]:()=>!0,[L.THEMES]:()=>!0,[L.COMPONENTS]:()=>!0,[L.CRUD]:()=>!0,[L.FORMS]:()=>!0,[L.REALTIME]:()=>!!(K(P("REALTIME_ENABLED"))&&P("REALTIME_ENABLED")==="true"||K(P("FIREBASE_CONFIG"))),[L.STORAGE]:()=>!!(K(P("STORAGE_ENABLED"))&&P("STORAGE_ENABLED")==="true"||K(P("FIREBASE_CONFIG"))),[L.AI]:()=>!!(K(P("AI_ENABLED"))&&P("AI_ENABLED")==="true")};var Hi=_t(At(),1);var qi=_t(At(),1);var Rt=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(t,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(t),s={handler:r,once:!1,context:n};return i.push(s),this.checkListenerCount(t),()=>{this.off(t,r)}}once(t,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let i=this.getListeners(t),s={handler:r,once:!0,context:n};return i.push(s),this.checkListenerCount(t),()=>{this.off(t,r)}}off(t,r){let n=this.events.get(t);if(!n||n.length===0)return!1;let i=n.findIndex(s=>s.handler===r);return i===-1?!1:(n.splice(i,1),n.length===0&&this.events.delete(t),!0)}emit(t,...r){this.cacheEvent(t,r);let n=this.events.get(t);if(!n||n.length===0)return!1;let i=[...n],s=[];for(let a of i)try{a.context?a.handler.apply(a.context,r):a.handler(...r),a.once&&s.push(a)}catch(d){y(d,{userMessage:`Error in event handler for ${t}`,context:{eventName:t,args:r},severity:"warning"})}if(s.length>0){let a=this.events.get(t);if(a){let d=a.filter(p=>!s.includes(p));d.length===0?this.events.delete(t):this.events.set(t,d)}}return!0}hasListeners(t){let r=this.events.get(t);return!!r&&r.length>0}listenerCount(t){return this.events.get(t)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(t){let r=this.events.get(t);return r?r.map(n=>n.handler):[]}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}setMaxListeners(t){return this.maxListeners=t>0?t:1/0,this}getMaxListeners(){return this.maxListeners}getListeners(t){let r=this.events.get(t);return r||(r=[],this.events.set(t,r)),r}checkListenerCount(t){let r=this.listenerCount(t);this.maxListeners!==1/0&&r>this.maxListeners}cacheEvent(t,r){let n=this.eventCache.get(t);n||(n=[],this.eventCache.set(t,n)),n.push({data:r,timestamp:Date.now()}),this.cleanupCache(t)}getCachedEvents(t){let r=this.eventCache.get(t);return!r||r.length===0?[]:(this.cleanupCache(t),(this.eventCache.get(t)||[]).map(i=>i.data))}clearCachedEvents(t){this.eventCache.delete(t)}clearAllCachedEvents(){this.eventCache.clear()}getCacheStats(){let t=0,r=null,n=null;for(let[s,a]of this.eventCache.entries()){t+=a.length;for(let d of a)(r===null||d.timestamp<r)&&(r=d.timestamp),(n===null||d.timestamp>n)&&(n=d.timestamp)}let i=`${Math.round(t*200/1024)}KB`;return{totalEvents:t,eventTypes:this.eventCache.size,oldestEvent:r,newestEvent:n,memoryEstimate:i}}cleanupCache(t){let r=Date.now()-this.cacheTTL;if(t){let n=this.eventCache.get(t);if(n){let i=n.filter(s=>s.timestamp>r);i.length===0?this.eventCache.delete(t):this.eventCache.set(t,i)}}else for(let[n,i]of this.eventCache.entries()){let s=i.filter(a=>a.timestamp>r);s.length===0?this.eventCache.delete(n):this.eventCache.set(n,s)}}},Cf=new Rt;var Of={user:null,userProfile:null,userSubscription:null,loading:!1,reauthenticateWithPassword:async()=>{},reauthenticateWithProvider:async()=>{},deleteAccount:async()=>{},setRememberMe:async()=>{},error:null,emailVerification:{status:"pending"},passwordResetPending:!1,getPartnerState:()=>"idle",setPartnerState:()=>{},partnerError:null,status:de.DEGRADED,hasRole:async()=>!1,hasTier:async()=>!1,hasFeature:async()=>!1,getCustomClaims:()=>({}),getCustomClaim:()=>null,signInWithEmail:async()=>null,createUserWithEmail:async()=>null,signInWithPartner:async()=>null,linkWithPartner:async()=>null,signInWithGoogleCredential:async()=>null,signOut:async()=>{},sendPasswordResetEmail:async()=>{},updatePassword:async()=>{},verifyPasswordResetCode:async()=>null,confirmPasswordReset:async()=>{},sendEmailVerification:async()=>{},getEmailVerificationStatus:async()=>({status:"pending"}),isEmailVerificationEnabled:async()=>!1,sendSignInLinkToEmail:async()=>{},signInWithEmailLink:async()=>null,isSignInWithEmailLink:()=>!1,getCurrentUser:async()=>null,isAuthenticated:!1,userRole:w.GUEST,userTier:ce.FREE,can:{navigate:e=>e===!1||typeof e=="object"&&!e.required,view:()=>!1,edit:()=>!1,delete:()=>!1,create:()=>!1,perform:()=>!1,has:()=>!1},isAvailable:!1},Df={status:de.DEGRADED,error:null,loading:!1,checkout:async()=>({sessionId:"",sessionUrl:null,success:!1,error:"Billing not available - consent required"}),cancelSubscription:async()=>({success:!1,endsAt:""}),changePlan:async()=>({success:!1}),refreshStatus:async()=>{},openCustomerPortal:async()=>{},clearError:()=>{},isAvailable:!1};var _f={status:de.DEGRADED,data:null,loading:!1,error:null,get:async()=>null,set:async()=>{},update:async()=>{},delete:async()=>{},add:async()=>"",query:async()=>[],subscribe:()=>()=>{},subscribeToCollection:()=>()=>{},invalidate:async()=>{},isAvailable:!1},Nf={status:de.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};var Ur=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function Fr(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function qe(e,t=""){if(Array.isArray(e))e.forEach((r,n)=>{let i=`${t}[${n}]`;if(typeof r=="string"&&Fr(r)){if(!Ur.test(r))throw y(new Error(`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for ${i}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:i,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&qe(r,i)});else if(typeof e=="object"&&e!==null)for(let[r,n]of Object.entries(e)){let i=t?`${t}.${r}`:r;if(typeof n=="string"&&Fr(n)){if(!Ur.test(n))throw y(new Error(`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for field "${i}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:i,value:n},severity:"error"})}else typeof n=="object"&&n!==null&&qe(n,i)}}import*as Lr from"valibot";var wt={};function mm(e){wt.uniqueConstraintValidator=e}async function Mr(e,t,r){let{uniqueFields:n=[],collection:i}=e.metadata;n.length!==0&&wt.uniqueConstraintValidator&&await Promise.all(n.map(async({field:s,errorMessage:a})=>{let d=t[s];if(d==null)return;if(await wt.uniqueConstraintValidator.checkDuplicate(i,s,d,r))throw y(new Error(a||`${s} must be unique`),{userMessage:a||`${s} must be unique`,context:{field:s}})}))}async function ym(e,t,r,n){Lr.parse(e,t),qe(t),await Mr(e,t,n),e.metadata.customValidate&&await e.metadata.customValidate(t,r)}function Gi(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function Rm(e){if(!Gi(e)){let t=e,r=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw y(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return e.metadata.collection}var Pt=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],km="available",Om=["draft","deleted"],Ge=["id","createdAt","updatedAt","createdById","updatedById"],ji=[...Ge,"status"];function Dm(e){return ji.includes(e)}function _m(e){return Ge.includes(e)}var k={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Pt]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"_createdAt",type:"timestamp",visibility:"technical",label:"crud:fields._createdAt",validation:{required:!0}},updatedAt:{name:"_updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields._updatedAt",validation:{required:!0}},createdById:{name:"_createdById",type:"reference",visibility:"technical",label:"crud:fields._createdById",validation:{required:!0}},updatedById:{name:"_updatedById",type:"reference",visibility:"technical",label:"crud:fields._updatedById",validation:{required:!0}}};var Ki=new Set(["__proto__","constructor","prototype"]);function Wi(e){for(let t of Object.keys(e.fields))if(Ki.has(t))throw y(new Error(`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`),{userMessage:`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`,context:{entityName:e.name,fieldName:t,operation:"defineEntity"},severity:"error"})}function Yi(e){let t=e.field.endsWith("Id")?e.field.slice(0,-2):e.field,r=e.collection||(t.endsWith("y")?t.slice(0,-1)+"ies":t+"s");return{name:e.field,label:`crud:fields.${e.field}`,type:"reference",visibility:"technical",editable:"create-only",validation:{required:!0,reference:r}}}function zi(e,t){if(!t||t.length===0)return e.map(i=>({value:i.value,label:i.label}));let r=e.map(i=>({value:i.value,label:i.label})),n=new Set(e.map(i=>i.value));for(let i of t)n.has(i.value)||r.push(i);return r}function Xi(e,t){if(!(!e.uniqueKeys||e.uniqueKeys.length===0))for(let r=0;r<e.uniqueKeys.length;r++){let n=e.uniqueKeys[r];if(!n)continue;if(!n.fields||n.fields.length===0)throw y(new Error(`uniqueKeys[${r}] for entity '${e.name}' must have at least one field`),{userMessage:`uniqueKeys[${r}] for entity '${e.name}' must have at least one field`,context:{entityName:e.name,uniqueKeyIndex:r},severity:"error"});let i=n.fields.filter(s=>!t.has(s));if(i.length>0)throw y(new Error(`uniqueKeys[${r}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`),{userMessage:`uniqueKeys[${r}] for entity '${e.name}' references non-existent fields: ${i.join(", ")}`,context:{entityName:e.name,uniqueKeyIndex:r,invalidFields:i},severity:"error"})}}function Ji(e){let{form:t,fields:r}=e,n=Object.keys(r);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw y(new Error(`Multi-step form for entity '${e.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${e.name}' must have at least one step`,context:{entityName:e.name,operation:"validateFormConfig"},severity:"error"});let i=t.steps.flatMap(p=>p.fields),s=i.filter(p=>!n.includes(p));if(s.length>0)throw y(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`,context:{entityName:e.name,invalidFields:s,operation:"validateFormConfig"},severity:"error"});let a=new Set(i);n.filter(p=>!a.has(p)).length>0}t.rules&&t.rules.forEach((i,s)=>{let d=(Array.isArray(i.condition)?i.condition.map(v=>v.field):[i.condition.field]).filter(v=>!n.includes(v));if(d.length>0)throw y(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${d.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${d.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:d,operation:"validateFormConfig"},severity:"error"});let h=[...i.showFields||[],...i.hideFields||[],...i.disableFields||[],...i.enableFields||[]].filter(v=>!n.includes(v));if(h.length>0)throw y(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:h,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([i,s])=>{if(s.dependsOn&&!n.includes(s.dependsOn.field))throw y(new Error(`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`),{userMessage:`Field '${i}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`,context:{entityName:e.name,fieldName:i,dependsOnField:s.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Qi(e){return e.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...e.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function Lm(e){try{Wi(e),Ji(e);let t=Qi(e),r={...e.fields,...k,...e.fields.createdAt&&{createdAt:{...k.createdAt,...e.fields.createdAt,type:k.createdAt.type,visibility:k.createdAt.visibility}},...e.fields.updatedAt&&{updatedAt:{...k.updatedAt,...e.fields.updatedAt,type:k.updatedAt.type,visibility:k.updatedAt.visibility}},...e.fields.createdById&&{createdById:{...k.createdById,...e.fields.createdById,type:k.createdById.type,visibility:k.createdById.visibility}},...e.fields.updatedById&&{updatedById:{...k.updatedById,...e.fields.updatedById,type:k.updatedById.type,visibility:k.updatedById.visibility}},...e.fields.status&&{status:{...k.status,...e.fields.status,validation:{...k.status.validation,...e.fields.status.validation,options:zi(Pt,e.fields.status.validation?.options)}}},...e.scope&&{[e.scope.field]:Yi(e.scope)}};if(e.listFields){let s=new Set(Object.keys(r)),a=e.listFields.filter(d=>!s.has(d));if(a.length>0)throw y(new Error(`Entity '${e.name}' defines listFields that do not exist: ${a.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${a.join(", ")}`,context:{entityName:e.name,invalidFields:a,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let s=new Set(Object.keys(r)),d=ve(e).filter(p=>!s.has(p));if(d.length>0)throw y(new Error(`Entity '${e.name}' defines listCardFields that do not exist: ${d.join(", ")}`),{userMessage:`Entity '${e.name}' defines listCardFields that do not exist: ${d.join(", ")}`,context:{entityName:e.name,invalidFields:d,operation:"defineEntity"},severity:"error"})}if(e.uniqueKeys){let s=new Set(Object.keys(r));Xi(e,s)}let n={...Xe,...e.access||{}},i=e.namespace||`entity-${e.name.toLowerCase()}`;return{...e,form:t,fields:r,access:n,namespace:i,...e.search&&{search:e.search},...e.defaultSort&&{defaultSort:e.defaultSort}}}catch(t){throw y(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}import*as $ from"valibot";function kt(e,t){return!!(t.visibility==="hidden"||t.editable==="generated"||Ge.includes(e))}function we(e,t){return Object.assign(e,{visibility:t})}function te(e,t){let r=e;return r.metadata={collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys}},r}function Vr(e){let t=Ee(e);return we(t,e.visibility)}function Br(e){let t=Ee({...e,validation:{...e.validation,required:!1}});return we(t,e.visibility)}function Gm(e){let t=e.fields,r={};for(let[_,N]of Object.entries(t))N.visibility!=="hidden"&&(r[_]=Vr(N));let n=te($.object(r),e),i={};for(let[_,N]of Object.entries(t))kt(_,N)||(i[_]=Vr(N));let s=te($.object(i),e),a={};for(let[_,N]of Object.entries(t))if(!kt(_,N))if(_==="status"){let W=$.literal("draft");a[_]=we(W,N.visibility)}else a[_]=Br(N);let d=te($.object(a),e),p={};for(let[_,N]of Object.entries(t))kt(_,N)||(p[_]=Br(N));p.id=we(Ee(k.id),"technical");let h=te($.object(p),e),v;if(e.listFields&&e.listFields.length>0){let _=["id","status"],N=[...new Set([..._,...e.listFields])];v={};for(let W of N){let ue=r[W];ue&&(v[W]=ue)}}else v=r;let O=te($.object(v),e),H,Ot=ve(e);if(Ot.length>0){let _=["id","status"],N=[...new Set([..._,...Ot])];H={};for(let W of N){let ue=r[W];ue&&(H[W]=ue)}}else H=r;let $r=te($.object(H),e),Hr=te($.object({id:we(Ee(k.id),"technical")}),e);return{create:s,draft:d,update:h,get:n,list:O,listCard:$r,delete:Hr}}function Km(e,t,r=1,n=!1){let i=[];if(n)for(let s=t;s>=e;s-=r)i.push({value:String(s),label:String(s)});else for(let s=e;s<=t;s+=r)i.push({value:String(s),label:String(s)});return i}var re=new Map;function Ym(e,t){re.has(e),re.set(e,t)}function zm(e){re.delete(e)}function Xm(e){let t=re.get(e);return t?t():null}function Jm(e){return re.has(e)}function Qm(){return Array.from(re.keys())}function Zm(){re.clear()}export{ba as AGGREGATE_FILTER_OPERATORS,ya as AGGREGATE_OPERATIONS,Qr as AIChatRequestSchema,en as AIChatResponseSchema,Nt as AIMessageSchema,ls as AIProviderConfigSchema,Jr as AIToolCallSchema,Xr as AIToolDefinitionSchema,Zr as AIUsageSchema,rs as AI_ERROR_CODES,es as AI_MODELS,V as AI_PROVIDERS,Pe as AI_ROLES,ns as AI_TIERS,is as AI_TOKEN_PRICING,el as AUTH_EVENTS,fe as AUTH_PARTNERS,Js as AUTH_PARTNER_STATE,Me as AuthHardening,Ht as AuthUserSchema,Ge as BACKEND_GENERATED_FIELD_NAMES,rl as BILLING_EVENTS,un as BREAKPOINT_RANGES,Qe as BREAKPOINT_THRESHOLDS,Ut as COMMON_TIER_CONFIGS,D as CONFIDENCE_LEVELS,Wt as CONSENT_CATEGORY,R as CONTEXTS,z as CRUD_OPERATORS,it as CURRENCY_MAP,$t as CheckoutSessionMetadataSchema,oe as ConditionBuilder,Ft as CreateCheckoutSessionRequestSchema,Mt as CreateCheckoutSessionResponseSchema,qt as CustomClaimsSchema,ts as DEFAULT_AI_CONFIG,os as DEFAULT_AI_MARKUP,Mo as DEFAULT_CRUD_TIMEOUT,Xe as DEFAULT_ENTITY_ACCESS,X as DEFAULT_ERROR_MESSAGES,dn as DEFAULT_LAYOUT_PRESET,Pt as DEFAULT_STATUS_OPTIONS,km as DEFAULT_STATUS_VALUE,Cs as DEFAULT_SUBSCRIPTION,Fo as DEFAULT_UPLOAD_TIMEOUT,su as DENSITY,A as DoNotDevError,pa as EDITABLE,Ba as EMAIL_ERROR_CODES,Va as EMAIL_PROVIDERS,Xs as EMAIL_VERIFICATION_STATUS,Oe as ENTITY_HOOK_ERRORS,Y as ENVIRONMENTS,pe as ERROR_CODES,za as ERROR_SEVERITY,Xa as ERROR_SOURCE,Gt as EntityHookError,We as FEATURES,au as FEATURE_CONSENT_MATRIX,de as FEATURE_STATUS,ga as FIELD_TYPES,Je as FIREBASE_ERROR_MAP,pn as FOOTER_MODE,jt as GITHUB_PERMISSION_LEVELS,Om as HIDDEN_STATUSES,fn as LAYOUT_PRESET,ma as LIST_SCHEMA_TYPE,ol as OAUTH_EVENTS,et as OAUTH_PARTNERS,fa as ORDER_DIRECTION,Wl as PARTNER_ICONS,sl as PAYLOAD_EVENTS,Ye as PERMISSIONS,x as PLATFORMS,la as PWA_ASSET_TYPES,aa as PWA_DISPLAY_MODES,nn as ProductDeclarationSchema,Ns as ProductDeclarationsSchema,ua as ROUTE_SOURCES,sa as STORAGE_SCOPES,ia as STORAGE_TYPES,ll as STRIPE_EVENTS,ke as STRIPE_MODES,xs as SUBSCRIPTION_DURATIONS,ne as SUBSCRIPTION_STATUS,ce as SUBSCRIPTION_TIERS,an as SendEmailRequestSchema,ln as SendEmailResponseSchema,ir as ServerUtils,ct as SingletonManager,sn as StripeBackConfigSchema,on as StripeFrontConfigSchema,tn as StripePaymentSchema,rn as StripeSubscriptionSchema,Vt as SubscriptionClaimsSchema,Lt as SubscriptionDataSchema,ji as TECHNICAL_FIELD_NAMES,w as USER_ROLES,ze as UserSubscriptionSchema,da as VISIBILITY,Bt as WebhookEventSchema,ye as addMonths,ft as addYears,Qo as addressSchema,ei as arraySchema,k as baseFields,sr as booleanSchema,Bo as calculateSubscriptionEndDate,nt as captureErrorToSentry,Ml as checkGitHubAccessSchema,fo as clearGlobalSingleton,Ad as clearSchemaGenerators,Zm as clearScopeProviders,me as commonErrorCodeMappings,st as compactToISOString,vo as configureProviders,go as createAsyncSingleton,Is as createDefaultSubscriptionClaims,Qs as createDefaultUserProfile,Ca as createEntitySchema,B as createErrorHandler,$n as createMetadata,ho as createMethodProxy,Gm as createSchemas,he as createSingleton,mo as createSingletonWithParams,se as dateSchema,Lm as defineEntity,wa as deleteEntitySchema,tt as detectErrorSource,Bl as disconnectOAuthSchema,Ko as emailSchema,Td as enhanceSchema,Un as ensureSpreadable,Q as evaluateCondition,ko as evaluateFieldConditions,Ll as exchangeTokenSchema,ar as fileSchema,lr as filesSchema,Co as filterVisibleFields,qn as formatCurrency,Jt as formatDate,Xn as formatRelativeTime,si as gdprConsentSchema,Zt as generateCodeChallenge,Qt as generateCodeVerifier,ro as generateFirestoreRuleCondition,oo as generatePKCEPair,Uo as generateUUID,Jo as geopointSchema,cn as getBreakpointFromWidth,Tl as getBreakpointUtils,Rm as getCollectionName,Do as getConditionDependencies,$l as getConnectionsSchema,Xt as getCurrencyLocale,Hn as getCurrencySymbol,Kn as getCurrentTimestamp,Aa as getEntitySchema,dt as getGlobalSingleton,ve as getListCardFieldNames,yo as getProvider,Cd as getRegisteredSchemaTypes,Qm as getRegisteredScopeProviders,co as getRoleFromClaims,Ee as getSchemaType,Xm as getScopeValue,pt as getVisibleFields,zn as getWeekFromISOString,mn as githubPermissionSchema,Ze as githubRepoConfigSchema,Ul as grantGitHubAccessSchema,y as handleError,Id as hasCustomSchemaGenerator,Gi as hasMetadata,bo as hasProvider,Ao as hasRestrictedVisibility,Ne as hasRoleAccess,Jm as hasScopeProvider,po as hasTierAccess,oi as ibanSchema,Tn as isAuthPartnerId,_m as isBackendGeneratedField,Sl as isBreakpoint,at as isCompactDateString,nr as isFieldVisible,Dm as isFrameworkField,xn as isOAuthPartnerId,io as isPKCESupported,Gn as isoToCompactString,uo as lazyImport,Pa as listEntitiesSchema,Zo as mapSchema,J as mapToDoNotDevError,no as maybeTranslate,ti as multiselectSchema,ur as neverSchema,jn as normalizeToISOString,ie as numberSchema,ys as overrideFeatures,Ts as overridePaymentModes,bs as overridePermissions,Ss as overrideSubscriptionStatus,vs as overrideSubscriptionTiers,hs as overrideUserRoles,lt as parseDate,Qn as parseDateToNoonUTC,$o as parseISODate,jo as parseServerCookie,Wo as passwordSchema,zo as pictureSchema,Xo as picturesSchema,ai as priceSchema,Km as rangeOptions,ri as referenceSchema,Vl as refreshTokenSchema,b as registerSchemaGenerator,Ym as registerScopeProvider,mm as registerUniqueConstraintValidator,Eo as resetProviders,Fl as revokeGitHubAccessSchema,Nn as safeValidate,No as sanitizeHref,mt as selectSchema,Pn as showNotification,gt as stringSchema,ii as switchSchema,ni as telSchema,Le as textSchema,Yn as timestampToISOString,Zn as toDateOnly,Wn as toISOString,Mn as translateArray,Vn as translateArrayRange,Bn as translateArrayWithIndices,Ln as translateObjectArray,zm as unregisterScopeProvider,Ra as updateEntitySchema,So as updateMetadata,Yo as urlSchema,us as validateAIChatRequest,cs as validateAIChatResponse,zl as validateAuthPartners,Ys as validateAuthSchemas,js as validateAuthUser,Ms as validateBillingSchemas,_s as validateCheckoutSessionMetadata,ao as validateCodeChallenge,so as validateCodeVerifier,ws as validateCreateCheckoutSessionRequest,Ps as validateCreateCheckoutSessionResponse,Ws as validateCustomClaims,qe as validateDates,ym as validateDocument,Go as validateEnvVar,qo as validateMetadata,Xl as validateOAuthPartners,Ha as validateSendEmailRequest,qa as validateSendEmailResponse,Fs as validateStripeBackConfig,Us as validateStripeFrontConfig,Os as validateSubscriptionClaims,ks as validateSubscriptionData,Mr as validateUniqueFields,Ho as validateUrl,Ks as validateUserSubscription,Ds as validateWebhookEvent,_n as validateWithSchema,Oo as when,wn as withErrorHandling,lo as withGracefulDegradation,Lo as withTimeout,Dn as wrapAuthError,kn as wrapCrudError,On as wrapStorageError};
1
+ var Xr=Object.create;var Xe=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Qr=Object.getOwnPropertyNames;var Zr=Object.getPrototypeOf,en=Object.prototype.hasOwnProperty;var Lt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tn=(e,t)=>{for(var r in t)Xe(e,r,{get:t[r],enumerable:!0})},rn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Qr(t))!en.call(e,o)&&o!==r&&Xe(e,o,{get:()=>t[o],enumerable:!(n=Jr(t,o))||n.enumerable});return e};var Bt=(e,t,r)=>(r=e!=null?Xr(Zr(e)):{},rn(t||!e||!e.__esModule?Xe(r,"default",{value:e,enumerable:!0}):r,e));var Hr=Lt(T=>{"use strict";var At=Symbol.for("react.transitional.element"),_i=Symbol.for("react.portal"),Ni=Symbol.for("react.fragment"),Ui=Symbol.for("react.strict_mode"),Fi=Symbol.for("react.profiler"),Mi=Symbol.for("react.consumer"),Li=Symbol.for("react.context"),Bi=Symbol.for("react.forward_ref"),Vi=Symbol.for("react.suspense"),$i=Symbol.for("react.memo"),Fr=Symbol.for("react.lazy"),Hi=Symbol.for("react.activity"),Dr=Symbol.iterator;function qi(e){return e===null||typeof e!="object"?null:(e=Dr&&e[Dr]||e["@@iterator"],typeof e=="function"?e:null)}var Mr={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Lr=Object.assign,Br={};function ce(e,t,r){this.props=e,this.context=t,this.refs=Br,this.updater=r||Mr}ce.prototype.isReactComponent={};ce.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ce.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Vr(){}Vr.prototype=ce.prototype;function Rt(e,t,r){this.props=e,this.context=t,this.refs=Br,this.updater=r||Mr}var wt=Rt.prototype=new Vr;wt.constructor=Rt;Lr(wt,ce.prototype);wt.isPureReactComponent=!0;var _r=Array.isArray;function Ct(){}var R={H:null,A:null,T:null,S:null},$r=Object.prototype.hasOwnProperty;function kt(e,t,r){var n=r.ref;return{$$typeof:At,type:e,key:t,ref:n!==void 0?n:null,props:r}}function Gi(e,t){return kt(e.type,t,e.props)}function Pt(e){return typeof e=="object"&&e!==null&&e.$$typeof===At}function ji(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var Nr=/\/+/g;function It(e,t){return typeof e=="object"&&e!==null&&e.key!=null?ji(""+e.key):t.toString(36)}function Ki(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(Ct,Ct):(e.status="pending",e.then(function(t){e.status==="pending"&&(e.status="fulfilled",e.value=t)},function(t){e.status==="pending"&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function ue(e,t,r,n,o){var s=typeof e;(s==="undefined"||s==="boolean")&&(e=null);var a=!1;if(e===null)a=!0;else switch(s){case"bigint":case"string":case"number":a=!0;break;case"object":switch(e.$$typeof){case At:case _i:a=!0;break;case Fr:return a=e._init,ue(a(e._payload),t,r,n,o)}}if(a)return o=o(e),a=n===""?"."+It(e,0):n,_r(o)?(r="",a!=null&&(r=a.replace(Nr,"$&/")+"/"),ue(o,t,r,"",function(h){return h})):o!=null&&(Pt(o)&&(o=Gi(o,r+(o.key==null||e&&e.key===o.key?"":(""+o.key).replace(Nr,"$&/")+"/")+a)),t.push(o)),1;a=0;var d=n===""?".":n+":";if(_r(e))for(var p=0;p<e.length;p++)n=e[p],s=d+It(n,p),a+=ue(n,t,r,s,o);else if(p=qi(e),typeof p=="function")for(e=p.call(e),p=0;!(n=e.next()).done;)n=n.value,s=d+It(n,p++),a+=ue(n,t,r,s,o);else if(s==="object"){if(typeof e.then=="function")return ue(Ki(e),t,r,n,o);throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.")}return a}function Ke(e,t,r){if(e==null)return e;var n=[],o=0;return ue(e,n,"","",function(s){return t.call(r,s,o++)}),n}function Wi(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var Ur=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}},Yi={map:Ke,forEach:function(e,t,r){Ke(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return Ke(e,function(){t++}),t},toArray:function(e){return Ke(e,function(t){return t})||[]},only:function(e){if(!Pt(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};T.Activity=Hi;T.Children=Yi;T.Component=ce;T.Fragment=Ni;T.Profiler=Fi;T.PureComponent=Rt;T.StrictMode=Ui;T.Suspense=Vi;T.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=R;T.__COMPILER_RUNTIME={__proto__:null,c:function(e){return R.H.useMemoCache(e)}};T.cache=function(e){return function(){return e.apply(null,arguments)}};T.cacheSignal=function(){return null};T.cloneElement=function(e,t,r){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var n=Lr({},e.props),o=e.key;if(t!=null)for(s in t.key!==void 0&&(o=""+t.key),t)!$r.call(t,s)||s==="key"||s==="__self"||s==="__source"||s==="ref"&&t.ref===void 0||(n[s]=t[s]);var s=arguments.length-2;if(s===1)n.children=r;else if(1<s){for(var a=Array(s),d=0;d<s;d++)a[d]=arguments[d+2];n.children=a}return kt(e.type,o,n)};T.createContext=function(e){return e={$$typeof:Li,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:Mi,_context:e},e};T.createElement=function(e,t,r){var n,o={},s=null;if(t!=null)for(n in t.key!==void 0&&(s=""+t.key),t)$r.call(t,n)&&n!=="key"&&n!=="__self"&&n!=="__source"&&(o[n]=t[n]);var a=arguments.length-2;if(a===1)o.children=r;else if(1<a){for(var d=Array(a),p=0;p<a;p++)d[p]=arguments[p+2];o.children=d}if(e&&e.defaultProps)for(n in a=e.defaultProps,a)o[n]===void 0&&(o[n]=a[n]);return kt(e,s,o)};T.createRef=function(){return{current:null}};T.forwardRef=function(e){return{$$typeof:Bi,render:e}};T.isValidElement=Pt;T.lazy=function(e){return{$$typeof:Fr,_payload:{_status:-1,_result:e},_init:Wi}};T.memo=function(e,t){return{$$typeof:$i,type:e,compare:t===void 0?null:t}};T.startTransition=function(e){var t=R.T,r={};R.T=r;try{var n=e(),o=R.S;o!==null&&o(r,n),typeof n=="object"&&n!==null&&typeof n.then=="function"&&n.then(Ct,Ur)}catch(s){Ur(s)}finally{t!==null&&r.types!==null&&(t.types=r.types),R.T=t}};T.unstable_useCacheRefresh=function(){return R.H.useCacheRefresh()};T.use=function(e){return R.H.use(e)};T.useActionState=function(e,t,r){return R.H.useActionState(e,t,r)};T.useCallback=function(e,t){return R.H.useCallback(e,t)};T.useContext=function(e){return R.H.useContext(e)};T.useDebugValue=function(){};T.useDeferredValue=function(e,t){return R.H.useDeferredValue(e,t)};T.useEffect=function(e,t){return R.H.useEffect(e,t)};T.useEffectEvent=function(e){return R.H.useEffectEvent(e)};T.useId=function(){return R.H.useId()};T.useImperativeHandle=function(e,t,r){return R.H.useImperativeHandle(e,t,r)};T.useInsertionEffect=function(e,t){return R.H.useInsertionEffect(e,t)};T.useLayoutEffect=function(e,t){return R.H.useLayoutEffect(e,t)};T.useMemo=function(e,t){return R.H.useMemo(e,t)};T.useOptimistic=function(e,t){return R.H.useOptimistic(e,t)};T.useReducer=function(e,t,r){return R.H.useReducer(e,t,r)};T.useRef=function(e){return R.H.useRef(e)};T.useState=function(e){return R.H.useState(e)};T.useSyncExternalStore=function(e,t,r){return R.H.useSyncExternalStore(e,t,r)};T.useTransition=function(){return R.H.useTransition()};T.version="19.2.5"});var Ot=Lt((uf,qr)=>{"use strict";qr.exports=Hr()});var mr={};tn(mr,{AuthHardening:()=>$e,CURRENCY_MAP:()=>ct,ConditionBuilder:()=>se,DEFAULT_CRUD_TIMEOUT:()=>Go,DEFAULT_ERROR_MESSAGES:()=>Q,DEFAULT_UPLOAD_TIMEOUT:()=>qo,DoNotDevError:()=>w,SingletonManager:()=>gt,addMonths:()=>Se,addYears:()=>yt,calculateSubscriptionEndDate:()=>Wo,captureErrorToSentry:()=>lt,clearGlobalSingleton:()=>Eo,commonErrorCodeMappings:()=>ve,compactToISOString:()=>dt,configureProviders:()=>Io,createAsyncSingleton:()=>To,createErrorHandler:()=>H,createMetadata:()=>Yn,createMethodProxy:()=>xo,createSingleton:()=>be,createSingletonWithParams:()=>So,detectErrorSource:()=>st,ensureSpreadable:()=>Hn,evaluateCondition:()=>ee,evaluateFieldConditions:()=>Mo,filterVisibleFields:()=>Do,formatCurrency:()=>Xn,formatDate:()=>sr,formatRelativeTime:()=>no,generateCodeChallenge:()=>lr,generateCodeVerifier:()=>ar,generateFirestoreRuleCondition:()=>uo,generatePKCEPair:()=>po,generateUUID:()=>Ho,getConditionDependencies:()=>Bo,getCurrencyLocale:()=>ir,getCurrencySymbol:()=>zn,getCurrentTimestamp:()=>Zn,getGlobalSingleton:()=>ht,getListCardFieldNames:()=>Ee,getProvider:()=>Co,getRoleFromClaims:()=>yo,getVisibleFields:()=>vt,getWeekFromISOString:()=>ro,handleError:()=>y,hasProvider:()=>Ao,hasRestrictedVisibility:()=>_o,hasRoleAccess:()=>Le,hasTierAccess:()=>bo,isCompactDateString:()=>pt,isFieldVisible:()=>pr,isPKCESupported:()=>fo,isoToCompactString:()=>Jn,lazyImport:()=>vo,mapToDoNotDevError:()=>Z,maybeTranslate:()=>co,normalizeToISOString:()=>Qn,parseDate:()=>ft,parseDateToNoonUTC:()=>io,parseISODate:()=>Yo,parseServerCookie:()=>Qo,resetProviders:()=>Ro,safeValidate:()=>$n,sanitizeHref:()=>$o,showNotification:()=>Fn,timestampToISOString:()=>to,toDateOnly:()=>so,toISOString:()=>eo,translateArray:()=>Gn,translateArrayRange:()=>Kn,translateArrayWithIndices:()=>Wn,translateObjectArray:()=>jn,updateMetadata:()=>wo,validateCodeChallenge:()=>go,validateCodeVerifier:()=>mo,validateEnvVar:()=>Jo,validateMetadata:()=>Xo,validateUrl:()=>zo,validateWithSchema:()=>Vn,when:()=>Lo,withErrorHandling:()=>Un,withGracefulDegradation:()=>ho,withTimeout:()=>jo,wrapAuthError:()=>Bn,wrapCrudError:()=>Mn,wrapStorageError:()=>Ln});var $={ANTHROPIC:"anthropic",OPENAI:"openai",GOOGLE:"google"},De={USER:"user",ASSISTANT:"assistant",SYSTEM:"system"},hs={[$.ANTHROPIC]:{default:"claude-sonnet-4-6",models:["claude-sonnet-4-6","claude-sonnet-4-20250514","claude-haiku-4-5-20251001","claude-opus-4-6","claude-opus-4-20250514"]},[$.OPENAI]:{default:"gpt-4o",models:["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","o3-mini"]},[$.GOOGLE]:{default:"gemini-2.0-flash",models:["gemini-2.0-flash","gemini-2.5-pro","gemini-2.5-flash"]}},vs={maxTokens:4096,temperature:.7,stream:!0},ys={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_API_KEY:"invalid_api_key",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",PROVIDER_ERROR:"provider_error",TOKEN_LIMIT_EXCEEDED:"token_limit_exceeded",STREAM_INTERRUPTED:"stream_interrupted"},bs={FAST:{id:"fast",defaultModel:"claude-haiku-4-5-20251001"},STANDARD:{id:"standard",defaultModel:"claude-sonnet-4-6"},PREMIUM:{id:"premium",defaultModel:"claude-opus-4-6"}},Es=4,Ss={"claude-sonnet-4-6":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-haiku-4-5-20251001":{promptPer1M:.8,completionPer1M:4,currency:"usd"},"claude-opus-4-6":{promptPer1M:15,completionPer1M:75,currency:"usd"},"claude-sonnet-4-20250514":{promptPer1M:3,completionPer1M:15,currency:"usd"},"claude-opus-4-20250514":{promptPer1M:15,completionPer1M:75,currency:"usd"},"gpt-4o":{promptPer1M:2.5,completionPer1M:10,currency:"usd"},"gpt-4o-mini":{promptPer1M:.15,completionPer1M:.6,currency:"usd"},"gpt-4.1":{promptPer1M:2,completionPer1M:8,currency:"usd"},"gpt-4.1-mini":{promptPer1M:.4,completionPer1M:1.6,currency:"usd"},"o3-mini":{promptPer1M:1.1,completionPer1M:4.4,currency:"usd"},"gemini-2.0-flash":{promptPer1M:.1,completionPer1M:.4,currency:"usd"},"gemini-2.5-pro":{promptPer1M:1.25,completionPer1M:10,currency:"usd"},"gemini-2.5-flash":{promptPer1M:.15,completionPer1M:.6,currency:"usd"}};import*as c from"valibot";var Vt=c.object({role:c.picklist([De.USER,De.ASSISTANT,De.SYSTEM]),content:c.pipe(c.string(),c.minLength(1)),id:c.optional(c.string()),createdAt:c.optional(c.string())}),Je=c.lazy(()=>c.object({type:c.picklist(["string","number","boolean","array","object"]),description:c.optional(c.string()),enum:c.optional(c.array(c.string())),items:c.optional(Je),properties:c.optional(c.record(c.string(),Je)),required:c.optional(c.array(c.string()))})),nn=c.object({description:c.pipe(c.string(),c.minLength(1)),parameters:c.object({type:c.literal("object"),properties:c.record(c.string(),Je),required:c.optional(c.array(c.string()))})}),on=c.object({id:c.string(),name:c.string(),args:c.record(c.string(),c.unknown())}),sn=c.object({messages:c.pipe(c.array(Vt),c.minLength(1)),provider:c.optional(c.picklist([$.ANTHROPIC,$.OPENAI,$.GOOGLE])),model:c.optional(c.string()),maxTokens:c.optional(c.pipe(c.number(),c.integer(),c.minValue(1))),temperature:c.optional(c.pipe(c.number(),c.minValue(0),c.maxValue(2))),systemPrompt:c.optional(c.string()),stream:c.optional(c.boolean()),tools:c.optional(c.record(c.string(),nn))}),an=c.object({promptTokens:c.number(),completionTokens:c.number(),totalTokens:c.number()}),ln=c.object({message:Vt,usage:c.optional(an),finishReason:c.optional(c.string()),toolCalls:c.optional(c.array(on))}),Is=c.object({provider:c.picklist([$.ANTHROPIC,$.OPENAI,$.GOOGLE]),model:c.optional(c.string()),maxTokens:c.optional(c.pipe(c.number(),c.integer(),c.minValue(1))),temperature:c.optional(c.pipe(c.number(),c.minValue(0),c.maxValue(2))),systemPrompt:c.optional(c.string())});function Cs(e){return c.safeParse(sn,e)}function As(e){return c.safeParse(ln,e)}var P={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function Ds(e){Object.assign(P,e)}var fe={FREE:"free",PRO:"pro",PREMIUM:"premium"};function _s(e){Object.assign(fe,e)}var Qe={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function Ns(e){Object.assign(Qe,e)}var Ze={READ_PUBLIC:"read_public",READ_OWN_DATA:"read_own_data",WRITE_OWN_DATA:"write_own_data",READ_ALL_DATA:"read_all_data",MANAGE_USERS:"manage_users"};function Us(e){Object.assign(Ze,e)}import*as l from"valibot";var ie={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function Ms(e){Object.assign(ie,e)}var _e={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function Ls(e){Object.assign(_e,e)}var Bs={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function Vs(e){return{tier:"free",status:"active",subscriptionId:null,customerId:e,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var $t={free:{features:["basic-usage","limited-storage","standard-support"],level:0},pro:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration"],level:1},ai:{features:["basic-usage","limited-storage","standard-support","cloud-sync","advanced-analytics","priority-support","custom-branding","team-collaboration","ai-assistant","custom-models","unlimited-generations","advanced-integrations"],level:2}},$s={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};import*as i from"valibot";var Ht=i.pipe(i.object({userId:i.optional(i.string()),productId:i.optional(i.string()),priceId:i.optional(i.string()),unitAmount:i.optional(i.pipe(i.number(),i.integer(),i.minValue(1))),productName:i.optional(i.pipe(i.string(),i.minLength(1))),currency:i.optional(i.pipe(i.string(),i.length(3,"Currency must be 3-letter ISO code"))),successUrl:i.pipe(i.string(),i.url()),cancelUrl:i.pipe(i.string(),i.url()),customerEmail:i.optional(i.pipe(i.string(),i.email())),userEmail:i.optional(i.pipe(i.string(),i.email())),metadata:i.optional(i.record(i.string(),i.string())),allowPromotionCodes:i.optional(i.boolean()),mode:i.optional(i.picklist([_e.PAYMENT,_e.SUBSCRIPTION]))}),i.check(e=>!!(e.priceId||e.unitAmount&&e.productName),"Either priceId or (unitAmount + productName) is required")),qt=i.object({sessionId:i.string(),sessionUrl:i.nullable(i.pipe(i.string(),i.url()))}),Gt=i.object({userId:i.string(),tier:i.string(),status:i.picklist(Object.values(ie)),subscriptionId:i.nullable(i.string()),customerId:i.string(),subscriptionEnd:i.nullable(i.pipe(i.string(),i.isoTimestamp())),cancelAtPeriodEnd:i.boolean(),updatedAt:i.pipe(i.string(),i.isoTimestamp())}),jt=i.object({tier:i.string(),subscriptionId:i.nullable(i.string()),customerId:i.string(),status:i.picklist(Object.values(ie)),subscriptionEnd:i.nullable(i.pipe(i.string(),i.isoTimestamp())),cancelAtPeriodEnd:i.boolean(),updatedAt:i.pipe(i.string(),i.isoTimestamp()),isDefault:i.optional(i.boolean())}),Kt=i.object({id:i.string(),type:i.string(),data:i.object({object:i.any()}),created:i.pipe(i.string(),i.isoTimestamp())}),Wt=i.looseObject({userId:i.optional(i.string()),firebaseUid:i.optional(i.string()),productType:i.optional(i.string())});function Gs(e){return i.safeParse(Ht,e)}function js(e){return i.safeParse(qt,e)}function Ks(e){return i.safeParse(Gt,e)}function Ws(e){return i.safeParse(jt,e)}function Ys(e){return i.safeParse(Kt,e)}function zs(e){return i.safeParse(Wt,e)}var un=i.object({type:i.literal("StripePayment"),name:i.pipe(i.string(),i.minLength(1,"Product name is required")),description:i.optional(i.string()),price:i.string(),currency:i.optional(i.pipe(i.string(),i.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:i.optional(i.pipe(i.string(),i.minLength(1,"Stripe price ID is required"))),unitAmount:i.optional(i.pipe(i.number(),i.integer(),i.minValue(1))),productName:i.optional(i.pipe(i.string(),i.minLength(1))),maxUnitAmount:i.optional(i.pipe(i.number(),i.integer(),i.minValue(1))),tier:i.pipe(i.string(),i.minLength(1,"Tier is required")),duration:i.pipe(i.string(),i.minLength(1,"Duration is required")),allowPromotionCodes:i.optional(i.boolean()),metadata:i.optional(i.record(i.string(),i.string()))}),cn=i.object({type:i.literal("StripeSubscription"),name:i.pipe(i.string(),i.minLength(1,"Product name is required")),description:i.optional(i.string()),price:i.string(),currency:i.optional(i.pipe(i.string(),i.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:i.pipe(i.string(),i.minLength(1,"Stripe price ID is required")),tier:i.pipe(i.string(),i.minLength(1,"Tier is required")),duration:i.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:i.optional(i.boolean()),metadata:i.optional(i.record(i.string(),i.string()))}),dn=i.variant("type",[un,cn]),Xs=i.record(i.string(),dn),pn=i.record(i.string(),i.object({name:i.string(),price:i.string(),currency:i.string(),description:i.optional(i.string()),features:i.optional(i.array(i.string())),priceId:i.optional(i.string()),unitAmount:i.optional(i.number()),productName:i.optional(i.string()),allowPromotionCodes:i.optional(i.boolean())})),fn=i.record(i.string(),i.object({type:i.picklist(["StripePayment","StripeSubscription"]),name:i.string(),price:i.number(),currency:i.string(),priceId:i.optional(i.string()),unitAmount:i.optional(i.pipe(i.number(),i.integer(),i.minValue(1))),productName:i.optional(i.pipe(i.string(),i.minLength(1))),maxUnitAmount:i.optional(i.pipe(i.number(),i.integer(),i.minValue(1))),tier:i.string(),duration:i.string(),description:i.optional(i.string()),metadata:i.optional(i.record(i.string(),i.string())),allowPromotionCodes:i.optional(i.boolean())}));function Js(e){return i.parse(pn,e)}function Qs(e){return i.parse(fn,e)}function Zs(){let e={createCheckoutSessionRequest:i.safeParse(Ht,{}),createCheckoutSessionResponse:i.safeParse(qt,{}),subscriptionData:i.safeParse(Gt,{}),subscriptionClaims:i.safeParse(jt,{}),webhookEvent:i.safeParse(Kt,{}),checkoutSessionMetadata:i.safeParse(Wt,{})};return{success:Object.values(e).every(t=>t.success),results:e}}var Yt=l.object({id:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),emailVerified:l.optional(l.boolean()),lastLoginAt:l.optional(l.string()),providerData:l.optional(l.array(l.object({providerId:l.string(),uid:l.string(),email:l.optional(l.nullable(l.pipe(l.string(),l.email()))),displayName:l.optional(l.nullable(l.string())),photoURL:l.optional(l.nullable(l.pipe(l.string(),l.url()))),phoneNumber:l.optional(l.nullable(l.string()))}))),role:l.optional(l.picklist(Object.values(P))),customClaims:l.optional(l.record(l.string(),l.any()))}),et=l.object({userId:l.string(),tier:l.picklist(Object.values(fe)),status:l.picklist(Object.values(ie)),isActive:l.optional(l.boolean()),features:l.optional(l.array(l.string())),subscriptionId:l.nullable(l.string()),customerId:l.string(),subscriptionEnd:l.nullable(l.pipe(l.string(),l.isoTimestamp())),cancelAtPeriodEnd:l.boolean(),updatedAt:l.pipe(l.string(),l.isoTimestamp())}),zt=l.object({role:l.optional(l.picklist(Object.values(P))),subscription:l.optional(et),features:l.optional(l.array(l.picklist(Object.values(Qe)))),permissions:l.optional(l.array(l.picklist(Object.values(Ze)))),githubAccess:l.optional(l.object({username:l.optional(l.string()),teamAccess:l.optional(l.array(l.string())),repoAccess:l.optional(l.array(l.string()))}))});function aa(e){return l.safeParse(Yt,e)}function la(e){return l.safeParse(et,e)}function ua(e){return l.safeParse(zt,e)}function ca(){let e={authUser:l.safeParse(Yt,{}),userSubscription:l.safeParse(et,{}),customClaims:l.safeParse(zt,{}),getUserAuthStatus:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1))}),{}),getCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.optional(l.array(l.string()))}),{}),setCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claims:l.record(l.string(),l.any()),merge:l.optional(l.boolean(),!1)}),{}),removeCustomClaims:l.safeParse(l.object({userId:l.pipe(l.string(),l.minLength(1)),claimKeys:l.pipe(l.array(l.string()),l.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}var pa={VERIFIED:"verified",PENDING:"pending",ERROR:"error"},fa={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function ma(e){return{userId:e,role:"user",preferences:{},metadata:{}}}var C={VITE:"vite",NEXTJS:"nextjs",EXPO:"expo",REACT_NATIVE:"react-native",UNKNOWN:"unknown"},X={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},k={CLIENT:"client",SERVER:"server",BUILD:"build"},N={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},me={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},Sa={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},Ta={USER:"user",GLOBAL:"global",SESSION:"session"},xa={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},Ia={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},Ca={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};var Ra={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super",TECHNICAL:"technical",HIDDEN:"hidden",OWNER:"owner"},Ne={TRUE:!0,FALSE:!1,USER:"user",ADMIN:"admin",SUPER:"super",CREATE_ONLY:"create-only",GENERATED:"generated",COMPUTED:"computed"},tt={create:"admin",read:"guest",update:"admin",delete:"admin"},J={EQ:"==",NEQ:"!=",LT:"<",LTE:"<=",GT:">",GTE:">=",IN:"in",NOT_IN:"not-in",ARRAY_CONTAINS:"array-contains",ARRAY_CONTAINS_ANY:"array-contains-any"},wa={ASC:"asc",DESC:"desc"},ka={LIST:"list",LIST_CARD:"listCard"},Pa=["address","array","avatar","badge","boolean","checkbox","color","combobox","date","datetime-local","document","documents","duration","email","field-array","file","files","gdprConsent","geopoint","hidden","iban","image","images","map","month","multiselect","number","currency","price","password","radio","reference","range","rating","reset","richtext","select","submit","switch","tel","text","textarea","time","timestamp","url","week","year"];var _a={COUNT:"count",SUM:"sum",AVG:"avg",MIN:"min",MAX:"max"},Na={EQ:J.EQ,NEQ:J.NEQ,LT:J.LT,LTE:J.LTE,GT:J.GT,GTE:J.GTE};var Xt=class extends Error{collidingIds;where;constructor(t,r){super(`BulkCollisionError: ${t.length} id(s) appear in both "${r.replace("-",'" and "')}" \u2014 ${t.join(", ")}`),this.name="BulkCollisionError",this.collidingIds=t,this.where=r}},Jt=class extends Error{cycle;constructor(t){super(`[dndev] bulkAcross: circular dependency: ${t.join(" \u2192 ")}`),this.name="BulkAcrossCycleError",this.cycle=t}},Qt=class extends Error{adapterName;constructor(t){super(`BulkNotImplementedError: adapter "${t}" has not implemented bulk() yet`),this.name="BulkNotImplementedError",this.adapterName=t}};import*as m from"valibot";var $a=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),data:m.record(m.string(),m.unknown()),idempotencyKey:m.optional(m.string())}),Ha=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required"))}),qa=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required")),data:m.record(m.string(),m.unknown()),merge:m.optional(m.boolean(),!1)}),Ga=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),id:m.pipe(m.string(),m.minLength(1,"Entity ID is required"))}),ja=m.object({collection:m.pipe(m.string(),m.minLength(1,"Collection name is required")),limit:m.optional(m.pipe(m.number(),m.minValue(1),m.maxValue(1e3)),1e3),offset:m.optional(m.pipe(m.number(),m.minValue(0)),0),orderBy:m.optional(m.string()),orderDirection:m.optional(m.picklist(["asc","desc"]),"desc"),where:m.optional(m.array(m.object({field:m.string(),operator:m.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:m.unknown()})))});var rl={RESEND:"resend"},nl={UNKNOWN:"unknown",UNAUTHENTICATED:"unauthenticated",INVALID_REQUEST:"invalid_request",PROVIDER_ERROR:"provider_error",TEMPLATE_NOT_FOUND:"template_not_found",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded",MISSING_API_KEY:"missing_api_key"};import*as x from"valibot";var mn=x.object({templateId:x.pipe(x.string(),x.minLength(1)),to:x.pipe(x.string(),x.email()),data:x.record(x.string(),x.unknown()),locale:x.optional(x.pipe(x.string(),x.minLength(2),x.maxLength(5)),"fr"),from:x.optional(x.string()),replyTo:x.optional(x.string())}),gn=x.object({success:x.boolean(),messageId:x.optional(x.string()),error:x.optional(x.string())});function il(e){return x.safeParse(mn,e)}function sl(e){return x.safeParse(gn,e)}var ge={ALREADY_EXISTS:"already-exists",CANCELLED:"cancelled",DEADLINE_EXCEEDED:"deadline-exceeded",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",INTERNAL:"internal",INVALID_ARGUMENT:"invalid-argument",NOT_FOUND:"not-found",PERMISSION_DENIED:"permission-denied",RATE_LIMIT_EXCEEDED:"rate-limit-exceeded",TIMEOUT:"timeout",UNAUTHENTICATED:"unauthenticated",UNAVAILABLE:"unavailable",UNIMPLEMENTED:"unimplemented",UNKNOWN:"unknown",VALIDATION_FAILED:"validation-failed"},pl={ERROR:"error",WARNING:"warning",INFO:"info",SUCCESS:"success"},Ue={INTERNAL_ERROR:"INTERNAL_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",PERMISSION_DENIED:"PERMISSION_DENIED",NOT_FOUND:"NOT_FOUND",ALREADY_EXISTS:"ALREADY_EXISTS",NETWORK_ERROR:"NETWORK_ERROR"},rt={[ge.PERMISSION_DENIED]:{type:Ue.PERMISSION_DENIED,message:"You do not have permission to perform this action"},[ge.NOT_FOUND]:{type:Ue.NOT_FOUND,message:"The requested resource was not found"},[ge.ALREADY_EXISTS]:{type:Ue.ALREADY_EXISTS,message:"The resource already exists"},[ge.INVALID_ARGUMENT]:{type:Ue.VALIDATION_ERROR,message:"Invalid argument provided"}},Zt=class extends Error{type;originalError;constructor(t,r,n){super(r),this.name="EntityHookError",this.type=t,this.originalError=n}},fl={AUTH:"auth",OAUTH:"oauth",FIREBASE:"firebase",API:"api",VALIDATION:"validation",ENTITY:"entity",UI:"ui",UNKNOWN:"unknown"},w=class e extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r=ge.INTERNAL,n){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=n?.details,this.source=n?.source,this.originalError=n?.originalError,this.context=n?.context,this.displayable=n?.displayable??!0,this.userMessageProvided=n?.userMessageProvided,this.name=this.constructor.name,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}toString(){return`${this.name} [${this.code}]: ${this.message}`}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details,source:this.source,originalError:this.originalError,context:this.context,displayable:this.displayable,userMessageProvided:this.userMessageProvided}}};var vl={AUTH_STATE_CHANGED:"auth.state.changed",USER_SIGNED_IN:"auth.user.signed_in",USER_SIGNED_OUT:"auth.user.signed_out",USER_UPDATED:"auth.user.updated",TOKEN_REFRESHED:"auth.token.refreshed",SUBSCRIPTION_UPDATED:"auth.subscription.updated",SUBSCRIPTION_CHANGED:"auth.subscription.changed",SUBSCRIPTION_CANCELLED:"auth.subscription.cancelled",SUBSCRIPTION_EXPIRED:"auth.subscription.expired",PERMISSIONS_UPDATED:"auth.permissions.updated",ACCOUNT_LINKED:"auth.account.linked",ACCOUNT_UNLINKED:"auth.account.unlinked",ACCOUNT_LINKING_REQUIRED:"auth.account.linking_required",AUTH_SUCCESS:"auth.success",EMAIL_VERIFICATION_SENT:"auth.email.verification_sent",PASSWORD_RESET_SENT:"auth.password.reset_sent",AUTH_ERROR:"auth.error"};var bl={BILLING_INITIALIZED:"billing.initialized",BILLING_ERROR:"billing.error",CHECKOUT_SESSION_CREATED:"billing.checkout_session.created",CHECKOUT_SESSION_FAILED:"billing.checkout_session.failed",SUBSCRIPTION_CREATED:"billing.subscription.created",SUBSCRIPTION_UPDATED:"billing.subscription.updated",SUBSCRIPTION_CANCELLED:"billing.subscription.cancelled",SUBSCRIPTION_RENEWED:"billing.subscription.renewed",SUBSCRIPTION_EXPIRED:"billing.subscription.expired",SUBSCRIPTION_TRIAL_ENDED:"billing.subscription.trial_ended",PAYMENT_SUCCEEDED:"billing.payment.succeeded",PAYMENT_FAILED:"billing.payment.failed",PAYMENT_REFUNDED:"billing.payment.refunded",PAYMENT_METHOD_ADDED:"billing.payment_method.added",PAYMENT_METHOD_UPDATED:"billing.payment_method.updated",PAYMENT_METHOD_REMOVED:"billing.payment_method.removed",PAYMENT_METHOD_DEFAULT_CHANGED:"billing.payment_method.default_changed",INVOICE_CREATED:"billing.invoice.created",INVOICE_UPDATED:"billing.invoice.updated",INVOICE_PAID:"billing.invoice.paid",INVOICE_FAILED:"billing.invoice.failed",WEBHOOK_RECEIVED:"billing.webhook.received",WEBHOOK_PROCESSED:"billing.webhook.processed",WEBHOOK_ERROR:"billing.webhook.error"};var Sl={OAUTH_STARTED:"oauth.started",OAUTH_SUCCESS:"oauth.success",OAUTH_ERROR:"oauth.error",OAUTH_CANCELLED:"oauth.cancelled",OAUTH_TOKEN_EXCHANGED:"oauth.token.exchanged",OAUTH_TOKEN_REFRESHED:"oauth.token.refreshed",OAUTH_PARTNER_LINKED:"oauth.partner.linked",OAUTH_PARTNER_UNLINKED:"oauth.partner.unlinked"};var xl={DOCUMENT_CREATED:"payload.document.created",DOCUMENT_UPDATED:"payload.document.updated",DOCUMENT_DELETED:"payload.document.deleted",MEDIA_CREATED:"payload.media.created",MEDIA_UPDATED:"payload.media.updated",MEDIA_DELETED:"payload.media.deleted",GLOBAL_UPDATED:"payload.global.updated",USER_CREATED:"payload.user.created",USER_UPDATED:"payload.user.updated",USER_DELETED:"payload.user.deleted",CACHE_INVALIDATED:"payload.cache.invalidated",PAGE_REGENERATED:"payload.page.regenerated"};var Cl={PAYMENT_INTENT_SUCCEEDED:"stripe.payment_intent.succeeded",PAYMENT_INTENT_FAILED:"stripe.payment_intent.payment_failed",CHECKOUT_SESSION_COMPLETED:"stripe.checkout.session.completed",CUSTOMER_CREATED:"stripe.customer.created",CUSTOMER_UPDATED:"stripe.customer.updated",CUSTOMER_DELETED:"stripe.customer.deleted",INVOICE_CREATED:"stripe.invoice.created",INVOICE_PAID:"stripe.invoice.paid",INVOICE_PAYMENT_FAILED:"stripe.invoice.payment_failed",SUBSCRIPTION_CREATED:"stripe.subscription.created",SUBSCRIPTION_UPDATED:"stripe.subscription.updated",SUBSCRIPTION_DELETED:"stripe.subscription.deleted"};import"valibot";var nt={mobile:0,tablet:768,laptop:1024,desktop:1440},hn={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function vn(e){return e>=nt.desktop?"desktop":e>=nt.laptop?"laptop":e>=nt.tablet?"tablet":"mobile"}function Ll(e,t){let r=hn[t];return e>=r.min&&e<=r.max}function Bl(e,t){let r=vn(e);return{current:r,width:e,height:t,isMobile:r==="mobile",isTablet:r==="tablet",isLaptop:r==="laptop",isDesktop:r==="desktop",isMobileOrTablet:r==="mobile"||r==="tablet",isLaptopOrDesktop:r==="laptop"||r==="desktop"}}var yn="landing",bn={FIXED:"fixed",SCROLL:"scroll"},En={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"};var er=["pull","push","admin","maintain","triage"];import"valibot";import*as f from"valibot";var ot=f.object({owner:f.pipe(f.string(),f.minLength(1,"Repository owner is required")),repo:f.pipe(f.string(),f.minLength(1,"Repository name is required"))}),Sn=f.picklist([...er]),Ql=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:ot,permission:f.optional(Sn,"push"),customClaims:f.optional(f.record(f.string(),f.any()))}),Zl=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:ot}),eu=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required")),githubUsername:f.pipe(f.string(),f.minLength(1,"GitHub username is required")),repoConfig:ot}),tu=f.object({provider:f.string(),purpose:f.picklist(["authentication","api-access"]),code:f.pipe(f.string(),f.minLength(1,"Authorization code is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required")),codeVerifier:f.optional(f.string()),state:f.optional(f.string()),instance:f.optional(f.pipe(f.string(),f.url()))}),ru=f.object({provider:f.string(),refreshToken:f.pipe(f.string(),f.minLength(1,"Refresh token is required")),redirectUri:f.pipe(f.string(),f.url("Valid redirect URI is required"))}),nu=f.object({provider:f.string()}),ou=f.object({userId:f.pipe(f.string(),f.minLength(1,"User ID is required"))});var cu={apple:"apple",discord:"discord",emailLink:"emailLink",facebook:"facebook",github:"github",google:"google",linkedin:"linkedin",microsoft:"microsoft",password:"password",reddit:"reddit",spotify:"spotify",twitch:"twitch",twitter:"twitter",yahoo:"yahoo",notion:"notion",slack:"slack",medium:"medium",mastodon:"mastodon",youtube:"youtube"};import*as g from"valibot";var tr=g.object({name:g.string(),color:g.string(),icon:g.string(),customParameters:g.optional(g.record(g.string(),g.string())),button:g.object({backgroundColor:g.string(),textColor:g.string(),borderColor:g.string(),hoverBackgroundColor:g.string(),focusOutlineColor:g.string(),fontWeight:g.optional(g.string(),"500"),textKey:g.optional(g.string())})}),Tn=g.object({...tr.entries,type:g.picklist(["auth","both"]),scopes:g.optional(g.array(g.string())),firebaseProviderId:g.optional(g.string())}),Fe=g.union([g.literal(""),g.pipe(g.string(),g.url())]),xn=g.object({authUrl:Fe,tokenUrl:Fe,profileUrl:Fe,revokeUrl:g.optional(Fe)}),In=g.object({authentication:g.optional(g.array(g.string())),"api-access":g.array(g.string())}),Cn=g.optional(g.object({pkce:g.optional(g.boolean(),!1),codeChallengeMethod:g.optional(g.picklist(["S256","plain"]),"S256")})),An=g.object({...tr.entries,type:g.picklist(["oauth","both"]),scopes:In,endpoints:xn,capabilities:Cn}),he={apple:{name:"Apple",color:"#000000",icon:"apple",type:"both",scopes:["email","name"],firebaseProviderId:"apple.com",customParameters:{prompt:"login"},button:{backgroundColor:"#000000",textColor:"#ffffff",borderColor:"#000000",hoverBackgroundColor:"#1a1a1a",focusOutlineColor:"#333333",fontWeight:"500",textKey:"buttons.apple"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:["identify","email"],firebaseProviderId:"discord.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.discord"}},emailLink:{name:"Email Link",color:"#10B981",icon:"emailLink",type:"auth",scopes:[],firebaseProviderId:"emailLink",customParameters:{},button:{backgroundColor:"#10B981",textColor:"#ffffff",borderColor:"#10B981",hoverBackgroundColor:"#059669",focusOutlineColor:"#059669",fontWeight:"500",textKey:"buttons.emailLink"}},facebook:{name:"Facebook",color:"#1877F2",icon:"facebook",type:"both",scopes:["email","public_profile"],firebaseProviderId:"facebook.com",customParameters:{auth_type:"reauthenticate"},button:{backgroundColor:"#1877F2",textColor:"#ffffff",borderColor:"#1877F2",hoverBackgroundColor:"#166FE5",focusOutlineColor:"#166FE5",fontWeight:"600",textKey:"buttons.facebook"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:["read:user","user:email"],firebaseProviderId:"github.com",customParameters:{allow_signup:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.github"}},google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:["email","profile"],firebaseProviderId:"google.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.google"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"both",scopes:["r_liteprofile","r_emailaddress"],firebaseProviderId:"linkedin.com",customParameters:{prompt:"consent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.linkedin"}},microsoft:{name:"Microsoft",color:"#00A4EF",icon:"microsoft",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"microsoft.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.microsoft"}},password:{name:"Email & Password",color:"#6B7280",icon:"password",type:"auth",scopes:[],firebaseProviderId:"password",customParameters:{},button:{backgroundColor:"#ffffff",textColor:"#374151",borderColor:"#D1D5DB",hoverBackgroundColor:"#F9FAFB",focusOutlineColor:"#3B82F6",fontWeight:"500",textKey:"buttons.password"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:["identity"],firebaseProviderId:"reddit.com",customParameters:{duration:"permanent"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.reddit"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:["user-read-email","user-read-private"],firebaseProviderId:"spotify.com",customParameters:{show_dialog:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.spotify"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:["user:read:email"],firebaseProviderId:"twitch.tv",customParameters:{force_verify:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitch"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"both",scopes:[],firebaseProviderId:"twitter.com",customParameters:{force_login:"true"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.twitter"}},yahoo:{name:"Yahoo",color:"#5F01D1",icon:"yahoo",type:"both",scopes:["openid","email","profile"],firebaseProviderId:"yahoo.com",customParameters:{prompt:"select_account"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500",textKey:"buttons.yahoo"}}},it={google:{name:"Google",color:"#4285F4",icon:"google",type:"both",scopes:{authentication:["openid","profile","email"],"api-access":["https://www.googleapis.com/auth/drive.readonly","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/calendar.readonly","https://www.googleapis.com/auth/gmail.readonly"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/oauth2/v3/userinfo",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},github:{name:"GitHub",color:"#24292E",icon:"github",type:"both",scopes:{authentication:["read:user","user:email"],"api-access":["repo","user","read:org","gist","notifications"]},endpoints:{authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",profileUrl:"https://api.github.com/user",revokeUrl:"https://api.github.com/applications/CLIENT_ID/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},discord:{name:"Discord",color:"#5865F2",icon:"discord",type:"both",scopes:{authentication:["identify","email"],"api-access":["guilds","guilds.members.read","bot","messages.read"]},endpoints:{authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",profileUrl:"https://discord.com/api/users/@me",revokeUrl:"https://discord.com/api/oauth2/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},spotify:{name:"Spotify",color:"#1DB954",icon:"spotify",type:"both",scopes:{authentication:["user-read-email","user-read-private"],"api-access":["user-read-playback-state","user-modify-playback-state","user-read-currently-playing","playlist-read-private","playlist-modify-public","user-library-read"]},endpoints:{authUrl:"https://accounts.spotify.com/authorize",tokenUrl:"https://accounts.spotify.com/api/token",profileUrl:"https://api.spotify.com/v1/me",revokeUrl:"https://accounts.spotify.com/api/token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitch:{name:"Twitch",color:"#9146FF",icon:"twitch",type:"both",scopes:{authentication:["user:read:email"],"api-access":["channel:read:subscriptions","bits:read","channel:manage:broadcast","channel:read:stream_key","user:read:follows"]},endpoints:{authUrl:"https://id.twitch.tv/oauth2/authorize",tokenUrl:"https://id.twitch.tv/oauth2/token",profileUrl:"https://api.twitch.tv/helix/users",revokeUrl:"https://id.twitch.tv/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},reddit:{name:"Reddit",color:"#FF4500",icon:"reddit",type:"both",scopes:{authentication:["identity"],"api-access":["read","submit","vote","mysubreddits","subscribe"]},endpoints:{authUrl:"https://www.reddit.com/api/v1/authorize",tokenUrl:"https://www.reddit.com/api/v1/access_token",profileUrl:"https://oauth.reddit.com/api/v1/me",revokeUrl:"https://www.reddit.com/api/v1/revoke_token"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},linkedin:{name:"LinkedIn",color:"#0077B5",icon:"linkedin",type:"oauth",scopes:{"api-access":["r_liteprofile","r_emailaddress","w_member_social","r_organization_social"]},endpoints:{authUrl:"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:"https://www.linkedin.com/oauth/v2/accessToken",profileUrl:"https://api.linkedin.com/v2/me",revokeUrl:"https://www.linkedin.com/oauth/v2/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},slack:{name:"Slack",color:"#E01E5A",icon:"slack",type:"oauth",scopes:{"api-access":["channels:read","chat:write","users:read","files:read","im:read"]},endpoints:{authUrl:"https://slack.com/oauth/v2/authorize",tokenUrl:"https://slack.com/api/oauth.v2.access",profileUrl:"https://slack.com/api/users.identity",revokeUrl:"https://slack.com/api/auth.revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},notion:{name:"Notion",color:"#000000",icon:"notion",type:"oauth",scopes:{"api-access":["read","write"]},endpoints:{authUrl:"https://api.notion.com/v1/oauth/authorize",tokenUrl:"https://api.notion.com/v1/oauth/token",profileUrl:"https://api.notion.com/v1/users/me",revokeUrl:"https://api.notion.com/v1/oauth/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},medium:{name:"Medium",color:"#000000",icon:"medium",type:"oauth",scopes:{"api-access":["basicProfile","publishPost","listPublications"]},endpoints:{authUrl:"https://medium.com/m/oauth/authorize",tokenUrl:"https://medium.com/v1/tokens",profileUrl:"https://medium.com/v1/me",revokeUrl:"https://medium.com/v1/tokens/revoke"},capabilities:{pkce:!1},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},twitter:{name:"X",color:"#000000",icon:"twitter",type:"oauth",scopes:{"api-access":["tweet.read","users.read","follows.read","tweet.write","like.write"]},endpoints:{authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",profileUrl:"https://api.twitter.com/2/users/me",revokeUrl:"https://api.twitter.com/2/oauth2/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},mastodon:{name:"Mastodon",color:"#6364FF",icon:"mastodon",type:"oauth",scopes:{"api-access":["read","write","follow","push"]},endpoints:{authUrl:"",tokenUrl:"",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},youtube:{name:"YouTube",color:"#FF0000",icon:"youtube",type:"oauth",scopes:{"api-access":["https://www.googleapis.com/auth/youtube.readonly","https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.force-ssl"]},endpoints:{authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",profileUrl:"https://www.googleapis.com/youtube/v3/channels",revokeUrl:"https://oauth2.googleapis.com/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}},supabase:{name:"Supabase",color:"#3ECF8E",icon:"supabase",type:"oauth",scopes:{"api-access":["auth:read","auth:write","database:read","database:write","domains:read","domains:write","edge_functions:read","edge_functions:write","environment:read","environment:write","organizations:read","projects:read","projects:write","rest:read","rest:write","secrets:read","secrets:write","storage:read"]},endpoints:{authUrl:"https://api.supabase.com/v1/oauth/authorize",tokenUrl:"https://api.supabase.com/v1/oauth/token",profileUrl:"",revokeUrl:""},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#F1F3F5",textColor:"#11181C",borderColor:"#E6E8EB",hoverBackgroundColor:"#E6E8EB",focusOutlineColor:"#3ECF8E",fontWeight:"500"}},vercel:{name:"Vercel",color:"#000000",icon:"vercel",type:"oauth",scopes:{authentication:["openid","email","profile","offline_access"],"api-access":["project","project-env-vars","deployment","team","user"]},endpoints:{authUrl:"https://vercel.com/oauth/authorize",tokenUrl:"https://api.vercel.com/login/oauth/token",profileUrl:"https://api.vercel.com/login/oauth/userinfo",revokeUrl:"https://api.vercel.com/login/oauth/token/revoke"},capabilities:{pkce:!0,codeChallengeMethod:"S256"},button:{backgroundColor:"#ffffff",textColor:"#000000",borderColor:"#d1d5db",hoverBackgroundColor:"#f9fafb",focusOutlineColor:"#3b82f6",fontWeight:"500"}}},Rn=g.record(g.string(),Tn),wn=g.record(g.string(),An);function pu(){return g.safeParse(Rn,he)}function fu(){return g.safeParse(wn,it)}function kn(e){return e in he}function Pn(e){return e in it}var rr={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},xu={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Iu={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:rr.ANALYTICS},marketing:{requiresConsent:rr.MARKETING}};function st(e){return e instanceof Error&&"source"in e&&typeof e.source=="string"?e.source:typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("auth/")?"auth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("oauth/")?"oauth":typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&["permission-denied","unavailable","not-found","already-exists","unauthenticated","invalid-argument","failed-precondition","resource-exhausted"].includes(e.code)?"firebase":typeof e=="object"&&e!==null&&"issues"in e&&Array.isArray(e.issues)&&"name"in e&&e.name==="ValiError"?"validation":e instanceof Error&&e.name==="EntityHookError"?"entity":typeof e=="object"&&e!==null&&("response"in e||"status"in e||"statusText"in e)?"api":typeof e=="object"&&e!==null&&"componentStack"in e?"ui":"unknown"}import*as or from"valibot";function H(e){return(t,r)=>{if(t instanceof w)return t;if(typeof t!="object"||t===null){let d=typeof t=="string"?t:e.defaultErrorMessage;return new w(r||d,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let n;e.extractErrorCode?n=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(n=t.code);let o=e.defaultErrorCode;n&&e.errorCodeMapping&&n in e.errorCodeMapping&&(o=e.errorCodeMapping[n]);let s;e.extractErrorMessage?s=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(s=t.message),n&&e.friendlyMessageMapping&&n in e.friendlyMessageMapping&&(s=e.friendlyMessageMapping[n]),s||(s=e.defaultErrorMessage);let a;return e.processMetadata?a=e.processMetadata(t):(a={originalError:t},n&&(a.originalCode=n)),"originalError"in a||(a.originalError=t),new w(r||s,o,{details:a,source:e.errorSource})}}var ve={"permission-denied":"permission-denied",unavailable:"unavailable","not-found":"not-found","already-exists":"already-exists",unauthenticated:"unauthenticated","invalid-argument":"invalid-argument","failed-precondition":"invalid-argument","resource-exhausted":"rate-limit-exceeded","deadline-exceeded":"timeout",cancelled:"cancelled","not-implemented":"unimplemented"};var Q={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",DELETE_ACCOUNT_REQUIRES_SERVER:"Account deletion requires a server endpoint. Configure a callable provider or deploy a delete-account Edge Function.",internal:"An internal error occurred.","invalid-argument":"Invalid argument provided.","not-found":"The requested resource was not found.","permission-denied":"You do not have permission to perform this action.","rate-limit-exceeded":"Too many requests. Please try again later.",timeout:"The operation timed out.",unauthenticated:"Authentication is required for this action.",unavailable:"The service is currently unavailable.",unimplemented:"This feature is not implemented.",unknown:"An unknown error occurred.","validation-failed":"Validation failed."},On={400:"invalid-argument",401:"unauthenticated",403:"permission-denied",404:"not-found",409:"already-exists",422:"validation-failed",429:"rate-limit-exceeded",500:"internal",501:"unimplemented",502:"unavailable",503:"unavailable",504:"timeout"},at={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},j={auth:{errorSource:"auth",defaultErrorCode:"unknown",defaultErrorMessage:"An authentication error occurred",errorCodeMapping:{"auth/user-not-found":"not-found","auth/wrong-password":"invalid-argument","auth/email-already-in-use":"already-exists","auth/weak-password":"validation-failed","auth/invalid-email":"validation-failed","auth/account-exists-with-different-credential":"already-exists","auth/credential-already-in-use":"already-exists","auth/requires-recent-login":"unauthenticated","auth/user-disabled":"permission-denied","auth/too-many-requests":"rate-limit-exceeded","auth/network-request-failed":"unavailable","auth/popup-blocked":"unavailable","auth/popup-closed-by-user":"invalid-argument","auth/cancelled-popup-request":"invalid-argument","auth/operation-not-allowed":"unimplemented","auth/invalid-credential":"invalid-argument","auth/invalid-verification-code":"invalid-argument","auth/captcha-check-failed":"validation-failed","auth/invalid-phone-number":"validation-failed","auth/missing-phone-number":"invalid-argument","auth/quota-exceeded":"rate-limit-exceeded","auth/timeout":"unavailable","auth/web-storage-unsupported":"unavailable","auth/unauthorized-domain":"permission-denied","auth/internal-error":"internal","auth/invalid-action-code":"invalid-argument","auth/invalid-continue-uri":"invalid-argument","auth/missing-continue-uri":"invalid-argument","auth/missing-ios-bundle-id":"invalid-argument","auth/missing-android-pkg-name":"invalid-argument","auth/unauthorized-continue-uri":"permission-denied","auth/invalid-dynamic-link-domain":"invalid-argument","auth/invalid-tenant-id":"invalid-argument","auth/tenant-id-mismatch":"invalid-argument","auth/provider-already-linked":"already-exists","auth/invalid-persistence-type":"invalid-argument","auth/unsupported-persistence-type":"unimplemented","auth/invalid-provider":"invalid-argument","auth/invalid-client-id":"invalid-argument","oauth/unauthorized-app":"permission-denied","auth/provider-not-enabled":"unimplemented","auth/unknown-provider":"invalid-argument","auth/missing-provider":"invalid-argument","auth/no-user-signed-in":"unauthenticated",DELETE_ACCOUNT_REQUIRES_SERVER:"DELETE_ACCOUNT_REQUIRES_SERVER",...ve},friendlyMessageMapping:{"auth/user-not-found":"No account found with this email address.","auth/wrong-password":"Incorrect password. Please try again.","auth/email-already-in-use":"An account with this email already exists.","auth/weak-password":"Password is too weak. It should be at least 6 characters.","auth/invalid-email":"Please enter a valid email address.","auth/account-exists-with-different-credential":"An account already exists with the same email but different sign-in method.","auth/credential-already-in-use":"This credential is already associated with a different user account.","auth/requires-recent-login":"This operation requires you to sign in again for security reasons.","auth/user-disabled":"This account has been disabled.","auth/too-many-requests":"Too many sign-in attempts. Please try again later.","auth/network-request-failed":"Network connection error. Please check your internet connection.","auth/popup-blocked":"Sign-in popup was blocked. Please allow popups for this site.","auth/popup-closed-by-user":"Sign-in popup was closed before completion.","auth/operation-not-allowed":"This sign-in method is not enabled for this project.","auth/internal-error":"An internal authentication error occurred. Please try again.","auth/invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","auth/invalid-continue-uri":"The continue URL provided is invalid.","auth/missing-continue-uri":"A continue URL must be provided in the request.","auth/missing-ios-bundle-id":"An iOS Bundle ID must be provided in the request.","auth/missing-android-pkg-name":"An Android package name must be provided in the request.","auth/unauthorized-continue-uri":"The domain of the continue URL is not allowlisted.","auth/invalid-dynamic-link-domain":"The provided dynamic link domain is not authorized.","auth/invalid-tenant-id":"The provided tenant ID is invalid.","auth/tenant-id-mismatch":"The tenant ID of the provider does not match the tenant ID of the current user.","auth/provider-already-linked":"This authentication provider is already linked to the account.","auth/invalid-persistence-type":"The specified persistence type is invalid.","auth/unsupported-persistence-type":"The current environment does not support the specified persistence type.","auth/invalid-provider":"The specified authentication provider is invalid.","auth/invalid-client-id":"The authentication client ID provided is invalid.","oauth/unauthorized-app":"This application is not authorized to use OAuth with the provided client ID.","auth/provider-not-enabled":"This authentication provider is not enabled.","auth/unknown-provider":"Unknown authentication provider.","auth/missing-provider":"No authentication provider specified in the request.","auth/no-user-signed-in":"No user is currently signed in."}},oauth:{errorSource:"oauth",defaultErrorCode:"unknown",defaultErrorMessage:"An OAuth error occurred",errorCodeMapping:{"oauth/invalid-request":"invalid-argument","oauth/invalid-client":"invalid-argument","oauth/invalid-grant":"invalid-argument","oauth/unauthorized-client":"permission-denied","oauth/unsupported-grant-type":"unimplemented","oauth/invalid-scope":"invalid-argument","oauth/insufficient-scope":"permission-denied","oauth/invalid-token":"unauthenticated","oauth/expired-token":"unauthenticated","oauth/redirect-uri-mismatch":"invalid-argument","oauth/access-denied":"permission-denied","oauth/server-error":"unavailable","oauth/temporarily-unavailable":"unavailable","oauth/state-mismatch":"invalid-argument","oauth/invalid-callback":"invalid-argument","oauth/client-secret-mismatch":"permission-denied","oauth/unauthorized-scope":"permission-denied","oauth/rate-limit-exceeded":"rate-limit-exceeded","oauth/token-expired":"unauthenticated","oauth/missing-token":"invalid-argument","oauth/invalid-code":"invalid-argument","oauth/invalid-redirect":"invalid-argument","oauth/provider-error":"unavailable","oauth/invalid-response":"unavailable","oauth/unauthorized-access":"permission-denied",...ve},friendlyMessageMapping:{"oauth/invalid-request":"The OAuth request was invalid or missing parameters.","oauth/invalid-client":"Client authentication failed.","oauth/invalid-grant":"The provided authorization grant is invalid.","oauth/unauthorized-client":"The client is not authorized to use this grant type.","oauth/unsupported-grant-type":"The requested grant type is not supported.","oauth/invalid-scope":"The requested scope is invalid or unknown.","oauth/insufficient-scope":"The token does not have the required scope for this resource.","oauth/invalid-token":"The access token is invalid.","oauth/expired-token":"The access token has expired.","oauth/redirect-uri-mismatch":"The redirect URI does not match the registered URI.","oauth/access-denied":"The resource owner denied the request.","oauth/server-error":"The authorization server encountered an unexpected error.","oauth/temporarily-unavailable":"The authorization server is temporarily unavailable.","oauth/state-mismatch":"Invalid state parameter. This could be a security issue.","oauth/invalid-callback":"The callback URL is invalid or not registered.","oauth/client-secret-mismatch":"The client secret does not match the registered secret.","oauth/unauthorized-scope":"The requested scope is not authorized for this client.","oauth/rate-limit-exceeded":"Too many requests. Please try again later.","oauth/token-expired":"The OAuth token has expired and needs to be refreshed.","oauth/missing-token":"No OAuth token was provided in the request.","oauth/invalid-code":"The authorization code is invalid or expired.","oauth/invalid-redirect":"The redirect URL is invalid or does not match the registered redirect URL.","oauth/provider-error":"The OAuth provider returned an error.","oauth/invalid-response":"The response from the OAuth provider was invalid.","oauth/unauthorized-access":"Unauthorized access to OAuth resources."}},api:{errorSource:"api",defaultErrorCode:"unknown",defaultErrorMessage:"API request failed",errorCodeMapping:Object.fromEntries(Object.entries(On).map(([e,t])=>[e,t])),friendlyMessageMapping:{},extractErrorCode:e=>{if(typeof e!="object"||e===null)return;let t;return"response"in e&&e.response&&"status"in e.response?t=e.response.status:"status"in e&&typeof e.status=="number"&&(t=e.status),t?.toString()},processMetadata:e=>{let t={originalError:e};return typeof e!="object"||e===null||("response"in e&&e.response?("status"in e.response&&(t.statusCode=e.response.status),"data"in e.response&&(t.responseData=e.response.data)):"status"in e&&(t.statusCode=e.status)),t}},firebase:{errorSource:"firebase",defaultErrorCode:"unknown",defaultErrorMessage:"A Firebase error occurred",errorCodeMapping:ve,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:Q.internal,errorCodeMapping:{},friendlyMessageMapping:{},processMetadata:e=>{let t={originalError:e};return typeof e=="object"&&e!==null&&"componentStack"in e&&(t.componentStack=e.componentStack),t}},validation:{errorSource:"validation",defaultErrorCode:"validation-failed",defaultErrorMessage:Q["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:Q.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},Dn=e=>e instanceof or.ValiError?new w(Q["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):H(j.validation)(e),_n=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in at){let t=e,r=at[t.type]||"unknown";return new w(t.message||Q[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&rt[e.code]){let t=e,r=rt[t.code];if(r){let n=at[r.type]||"unknown";return new w(r.message||Q[n],n,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return H(j.entity)(e)},nr={auth:H(j.auth),oauth:H(j.oauth),api:H(j.api),firebase:H(j.firebase),ui:H(j.ui),validation:Dn,entity:_n,unknown:H(j.unknown)};function Z(e,t,r){return e instanceof w?e:(nr[t]||nr.unknown)(e,r)}function lt(e,t,r={}){let n=globalThis.Sentry;n&&n.withScope(o=>{o.setTag("errorSource",t),o.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([s,a])=>{if(typeof a!="function"&&s!=="originalError")try{o.setExtra(s,a)}catch{o.setExtra(s,`[${typeof a}]`)}}),Object.entries(r).forEach(([s,a])=>{if(typeof a!="function")try{o.setExtra(`context.${s}`,a)}catch{o.setExtra(`context.${s}`,`[${typeof a}]`)}}),(e.details?.userId||r.userId)&&o.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),n.captureException(e)})}function Nn(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof process<"u"&&process.env?"production".toLowerCase()!=="production":!1}function y(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:n,context:o={},log:s=!0,reportToSentry:a=!0,showNotification:d=!1,severity:p="error"}=r,h=st(e),v=e instanceof w?e:Z(e,h,n);if(n&&!v.userMessageProvided&&(v.message.includes("Error")||v.message.includes("Failed")||v.message.length<10?v=new w(n,v.code,{details:{...v.details,originalMessage:v.message},source:h,userMessageProvided:!0}):v=new w(v.message,v.code,{details:{...v.details,userMessage:n},source:h,userMessageProvided:!0})),s){let _=Nn()||typeof window<"u"&&window.__DNDEV_DEBUG,G={code:v.code,message:v.message,source:h};switch(p){case"warning":break;case"info":break;case"success":break;default:}}return a&&lt(v,h,o),v}function Un(e,t){return async(...r)=>{try{return await e(...r)}catch(n){throw y(n,t)}}}function Fn(e,t="info",r){let n=Date.now().toString();return n}function Mn(e,t,r,n,o){let s=`${t}.${r}(${n}${o?`, ${o}`:""})`,a=ut(e);return Z({...e instanceof Error?e:new Error(a),message:"Request failed.",details:{context:s,originalMessage:a,originalError:e}},"api")}function Ln(e,t,r,n){let o=`${t}.${r}(${n})`;return Z(e,"api",`${o}: ${ut(e)}`)}function Bn(e,t,r,n){let o=n?` ${JSON.stringify(n)}`:"",s=`${t}.${r}(${o})`,a=Z(e,"auth",`${s}: ${ut(e)}`);return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&a.code==="unknown"&&e.code!=="unknown"?new w(a.message,a.code,{details:{...a.details,originalCode:e.code},source:a.source}):a}function ut(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}import*as ye from"valibot";function Vn(e,t,r){try{return ye.parse(e,t)}catch(n){throw n instanceof ye.ValiError?new w(`Validation failed in ${r}: ${n.message}`,"validation-failed",{details:{issues:n.issues,input:t},source:"validation"}):new w(`Unexpected validation error in ${r}: ${qn(n)}`,"validation-failed",{originalError:n instanceof Error?n:new Error(String(n)),source:"validation"})}}function $n(e,t){try{return ye.parse(e,t)}catch{return null}}function Hn(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e}}function qn(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function Gn(e,t,r,n={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:a}=n;return Array.from({length:r},(d,p)=>{let h=`${t}.${p}`;return e(h)}).filter((d,p)=>{let h=`${t}.${p}`;return!(d===h||s&&d.trim()===""||d.length<o||a&&!a(d,p))})}function jn(e,t,r,n){return Array.from({length:r},(o,s)=>{let a=`${t}.${s}.${String(n[0])}`;if(e(a)===a)return null;let p={};for(let h of n){let v=`${t}.${s}.${String(h)}`;p[h]=e(v)}return p}).filter(o=>o!==null)}function Kn(e,t,r,n,o={}){let{minLength:s=0,excludeEmpty:a=!0,customFilter:d}=o;return Array.from({length:n-r},(p,h)=>{let v=r+h,_=`${t}.${v}`;return e(_)}).filter((p,h)=>{let v=r+h,_=`${t}.${v}`;return!(p===_||a&&p.trim()===""||p.length<s||d&&!d(p,v))})}function Wn(e,t,r,n={}){let{minLength:o=0,excludeEmpty:s=!0,customFilter:a}=n;return Array.from({length:r},(d,p)=>{let h=`${t}.${p}`;return{item:e(h),originalIndex:p}}).filter(({item:d,originalIndex:p})=>{let h=`${t}.${p}`;return!(d===h||s&&d.trim()===""||d.length<o||a&&!a(d,p))})}function Yn(e){let t=new Date().toISOString();return{createdAt:t,updatedAt:t,createdById:e,updatedById:e}}var ct={AED:{locale:"ar-AE",symbol:"\u062F.\u0625"},ARS:{locale:"es-AR",symbol:"$"},AUD:{locale:"en-AU",symbol:"$"},BDT:{locale:"bn-BD",symbol:"\u09F3"},BGN:{locale:"bg-BG",symbol:"\u043B\u0432"},BHD:{locale:"ar-BH",symbol:"\u062F.\u0628"},BRL:{locale:"pt-BR",symbol:"R$"},CAD:{locale:"en-CA",symbol:"$"},CHF:{locale:"fr-CH",symbol:"CHF"},CLP:{locale:"es-CL",symbol:"$"},CNY:{locale:"zh-CN",symbol:"\xA5"},COP:{locale:"es-CO",symbol:"$"},CZK:{locale:"cs-CZ",symbol:"K\u010D"},DKK:{locale:"da-DK",symbol:"kr"},EGP:{locale:"ar-EG",symbol:"E\xA3"},EUR:{locale:"fr-FR",symbol:"\u20AC"},GBP:{locale:"en-GB",symbol:"\xA3"},HKD:{locale:"zh-HK",symbol:"$"},HUF:{locale:"hu-HU",symbol:"Ft"},IDR:{locale:"id-ID",symbol:"Rp"},ILS:{locale:"he-IL",symbol:"\u20AA"},INR:{locale:"en-IN",symbol:"\u20B9"},JOD:{locale:"ar-JO",symbol:"\u062F.\u0623"},JPY:{locale:"ja-JP",symbol:"\xA5"},KES:{locale:"sw-KE",symbol:"KSh"},KRW:{locale:"ko-KR",symbol:"\u20A9"},KWD:{locale:"ar-KW",symbol:"\u062F.\u0643"},LKR:{locale:"si-LK",symbol:"Rs"},MXN:{locale:"es-MX",symbol:"$"},MYR:{locale:"ms-MY",symbol:"RM"},NGN:{locale:"en-NG",symbol:"\u20A6"},NOK:{locale:"nb-NO",symbol:"kr"},NZD:{locale:"en-NZ",symbol:"$"},OMR:{locale:"ar-OM",symbol:"\u0631.\u0639."},PEN:{locale:"es-PE",symbol:"S/."},PHP:{locale:"en-PH",symbol:"\u20B1"},PKR:{locale:"ur-PK",symbol:"\u20A8"},PLN:{locale:"pl-PL",symbol:"z\u0142"},QAR:{locale:"ar-QA",symbol:"\u0631.\u0642"},RON:{locale:"ro-RO",symbol:"lei"},RUB:{locale:"ru-RU",symbol:"\u20BD"},SAR:{locale:"ar-SA",symbol:"\u0631.\u0633"},SEK:{locale:"sv-SE",symbol:"kr"},SGD:{locale:"en-SG",symbol:"$"},THB:{locale:"th-TH",symbol:"\u0E3F"},TRY:{locale:"tr-TR",symbol:"\u20BA"},TWD:{locale:"zh-TW",symbol:"$"},UAH:{locale:"uk-UA",symbol:"\u20B4"},USD:{locale:"en-US",symbol:"$"},UYU:{locale:"es-UY",symbol:"$"},VND:{locale:"vi-VN",symbol:"\u20AB"},ZAR:{locale:"en-ZA",symbol:"R"}};function ir(e){return ct[e]?.locale??"en-US"}function zn(e){return!e||typeof e!="string"?e??"":ct[e]?.symbol??e}function Xn(e,t,r={}){if(e==null||isNaN(e))return"";let n=ir(t);return new Intl.NumberFormat(n,{style:"currency",currency:t,minimumFractionDigits:0,maximumFractionDigits:2,currencyDisplay:"symbol",...r}).format(e)}function dt(e){let t=e.match(/^(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})$/);if(!t||t.length<6)throw new Error(`Invalid compact date format. Expected YYYYMMDD:HHMM, got: ${e}`);let r=t[1],n=t[2],o=t[3],s=t[4],a=t[5],d=new Date(parseInt(r,10),parseInt(n,10)-1,parseInt(o,10),parseInt(s,10),parseInt(a,10));if(isNaN(d.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return d.toISOString()}function Jn(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0"),s=String(t.getUTCHours()).padStart(2,"0"),a=String(t.getUTCMinutes()).padStart(2,"0");return`${r}${n}${o}:${s}${a}`}function pt(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function Qn(e){if(!e)return new Date().toISOString();if(e instanceof Date){if(isNaN(e.getTime()))throw new Error("Invalid Date object");return e.toISOString()}if(typeof e=="string"){if(pt(e))return dt(e);let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid date string: ${e}`);return t.toISOString()}if(typeof e=="number"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid timestamp: ${e}`);return t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")return t.toDate().toISOString()}throw new Error(`Unsupported date type: ${typeof e}`)}function Zn(){return new Date().toISOString()}function eo(e){return e.toISOString()}function to(e){return new Date(e).toISOString()}function ro(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=new Date(t.getFullYear(),0,1),n=Math.floor((t.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((n+r.getDay()+1)/7)}, ${t.getFullYear()}`}var M={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function no(e,t="en",r={}){if(!e)return"";let{style:n="long",numeric:o="auto",fallbackThreshold:s=M.WEEK}=r,a;if(e instanceof Date)a=e;else if(typeof e=="string")a=new Date(e);else if(typeof e=="number")a=new Date(e);else if(typeof e=="object"&&"toDate"in e)a=e.toDate();else return"";if(isNaN(a.getTime()))return"";let d=new Date,p=a.getTime()-d.getTime(),h=Math.round(p/1e3),v=Math.abs(h);if(v>s)return sr(a.toISOString(),t);let _=new Intl.RelativeTimeFormat(t,{style:n,numeric:o});return v<M.MINUTE?_.format(h,"second"):v<M.HOUR?_.format(Math.round(h/M.MINUTE),"minute"):v<M.DAY?_.format(Math.round(h/M.HOUR),"hour"):v<M.WEEK?_.format(Math.round(h/M.DAY),"day"):v<M.MONTH?_.format(Math.round(h/M.WEEK),"week"):v<M.YEAR?_.format(Math.round(h/M.MONTH),"month"):_.format(Math.round(h/M.YEAR),"year")}function oo(e){switch(e){case"full":return{weekday:"long",year:"numeric",month:"long",day:"numeric"};case"long":return{year:"numeric",month:"long",day:"numeric"};case"medium":return{year:"numeric",month:"short",day:"numeric"};case"short":return{year:"2-digit",month:"numeric",day:"numeric"};case"date-only":return{year:"numeric",month:"2-digit",day:"2-digit"};case"time-only":return{hour:"2-digit",minute:"2-digit"};case"datetime":return{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"};default:return{year:"numeric",month:"long",day:"numeric"}}}function sr(e,t="en",r="long"){if(!e)return"";let n;if(e instanceof Date)n=e;else if(typeof e=="string")n=new Date(e);else if(typeof e=="number")n=new Date(e);else if(typeof e=="object"&&"toDate"in e)n=e.toDate();else return"";if(isNaN(n.getTime()))return"";let o=typeof r=="string"?oo(r):r;return new Intl.DateTimeFormat(t,o).format(n)}function ft(e){if(e!=null){if(e instanceof Date)return isNaN(e.getTime())?void 0:e.toISOString();if(typeof e=="string"){let t=e.trim();if(!t)return;if(pt(t))try{return dt(t)}catch{return}let r=new Date(t);return isNaN(r.getTime())?void 0:r.toISOString()}if(typeof e=="number"){if(!Number.isFinite(e))return;let t=new Date(e);return isNaN(t.getTime())?void 0:t.toISOString()}if(typeof e=="object"&&e!==null&&"toDate"in e){let t=e;if(typeof t.toDate=="function")try{let r=t.toDate();return isNaN(r.getTime())?void 0:r.toISOString()}catch{return}}if(typeof e=="object"&&e!==null&&"seconds"in e&&typeof e.seconds=="number"){let t=e,r=t.seconds*1e3+(t.nanoseconds||0)/1e6,n=new Date(r);return isNaN(n.getTime())?void 0:n.toISOString()}}}function io(e){let t=ft(e);if(!t)return;let r=new Date(t);return r.setUTCHours(12,0,0,0),r.toISOString()}function so(e){let t=ft(e);return t&&t.split("T")[0]||""}function ao(e){return typeof e=="string"?`'${e.replace(/'/g,"\\'")}'`:typeof e=="boolean"?e?"true":"false":String(e)}function lo(e){let t=`resource.data.${e.field}`,r=ao(e.value);return`${t} ${e.op} ${r}`}function uo(e){let t=[];if(e.publicCondition&&e.publicCondition.length>0){let r=e.publicCondition.map(lo).join(" && ");t.push(`(${r})`)}for(let r of e.ownerFields)t.push(`request.auth.uid == resource.data.${r}`);return t.length===0?"false":t.join(" || ")}function co(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}function ar(){let e=new Uint8Array(32);return crypto.getRandomValues(e),ur(e)}async function lr(e){let r=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",r);return ur(new Uint8Array(n))}async function po(){let e=ar(),t=await lr(e);return{codeVerifier:e,codeChallenge:t}}function ur(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fo(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function mo(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function go(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}async function ho(e,t,r){try{return await e()}catch{return t(),!1}}var Me=new Map;function vo(e,t){if(Me.has(t))return Me.get(t);let r=e().catch(n=>{throw Me.delete(t),n});return Me.set(t,r),r}var cr={[P.GUEST]:0,[P.USER]:1,[P.ADMIN]:2,[P.SUPER]:3};function Le(e,t){if(!e)return!1;let r=cr[e]??-1,n=cr[t]??1/0;return r>=n}function yo(e){return e?e.role===P.SUPER||e.isSuper===!0?P.SUPER:e.role===P.ADMIN||e.isAdmin===!0?P.ADMIN:e.role===P.USER?P.USER:e.role||P.USER:P.USER}function bo(e,t,r){if(!e)return!1;let n=r??$t,o=n[e]?.level??-1,s=n[t]?.level??1/0;return o>=s}var mt="__DNDEV_SINGLETONS__";function dr(){if(typeof globalThis<"u"){let e=globalThis;return e[mt]||(e[mt]=new Map),e[mt]}return new Map}function ht(e,t){let r=dr();return r.has(e)||r.set(e,t()),r.get(e)}function Eo(e){dr().delete(e)}function be(e,...t){let r=null,n=!1;return function(){if(r!==null)return r;if(n)throw new Error("Circular dependency detected in singleton initialization");n=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{n=!1}}}function So(e){let t=null,r=!1;return function(...o){if(t!==null)return t;if(r)throw new Error("Circular dependency detected in singleton initialization");r=!0;try{return typeof e=="function"&&e.prototype?t=new e(...o):t=e(...o),t}finally{r=!1}}}function To(e){let t=null,r=!1,n=null;return async function(){if(t!==null)return t;if(r&&n)return n;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return n=e(),t=await n,t}finally{r=!1,n=null}}}function xo(e,t){return new Proxy({},{get(r,n){if(t.includes(n)){let s=e(),a=s[n];return typeof a=="function"?a.bind(s):a}return e()[n]}})}var gt=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(t,r,n={}){if(this.instances.has(t))return this.instances.get(t);if(this.initialized.has(t))return this.instances.get(t);if(this.initializing.has(t))throw new Error(`Circular dependency detected for singleton: ${t}`);if(n.ssrSafe===!1&&typeof window>"u"){if(typeof process<"u",n.fallbackFactory){let o=n.fallbackFactory();return this.instances.set(t,o),this.initialized.add(t),o}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let o=await r();return this.instances.set(t,o),this.initialized.add(t),o}catch(o){if(typeof process<"u",n.cacheFailures&&this.initialized.add(t),n.fallbackFactory){let s=n.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw o}finally{this.initializing.delete(t)}}static isInitialized(t){return this.initialized.has(t)}static clear(t){this.instances.delete(t),this.initialized.delete(t),this.initializing.delete(t)}static clearAll(){this.instances.clear(),this.initialized.clear(),this.initializing.clear()}};function Be(){return ht("providers",()=>({providers:null}))}function Io(e){let t=Be();t.providers,t.providers=e}function Co(e){let{providers:t}=Be();if(!t)throw new Error(`[dndev] Provider "${e}" not available. Call configureProviders() at app startup.`);let r=t[e];if(!r)throw new Error(`[dndev] Provider "${e}" not configured. Pass it to configureProviders().`);return r}function Ao(e){return!!Be().providers?.[e]}function Ro(){Be().providers=null}function wo(e){return{updatedAt:new Date().toISOString(),updatedById:e}}function ko(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function Po(e){if(ko(e))return e.visibility}function pr(e,t){let r=e??"guest";return r==="hidden"?!1:r==="technical"?Le(t,"admin"):r==="owner"?!1:Le(t,r)}function Oo(e,t,r){for(let n of r.ownerFields)if(e[n]===t)return!0;return!1}function vt(e,t,r){let n=e;if(!n||typeof n!="object"||!n.entries)return[];let o=n.entries,s=[],{documentData:a,uid:d,ownership:p}=r??{},h=p&&d!=null&&a&&Oo(a,d,p);for(let[v,_]of Object.entries(o)){let G=Po(_);if(G==="owner"){h&&s.push(v);continue}pr(G,t)&&s.push(v)}return s}function Do(e,t,r,n){if(!e)return{};let o=n?.uid!=null&&n?.ownership!=null?{documentData:n.documentData??e,uid:n.uid,ownership:n.ownership}:void 0,s=vt(t,r,o),a={};for(let d of s)Object.prototype.hasOwnProperty.call(e,d)&&(a[d]=e[d]);return a}function Ee(e){let t=e.listCardFields;if(t){if(Array.isArray(t))return t;let r=t,n=[...r.title??[],...r.subtitle??[],...r.content??[],...r.footer??[]];return[...new Set(n)]}return e.listFields&&e.listFields.length>0?e.listFields:e.fields?Object.keys(e.fields):[]}function Ve(e){if(!(!e||typeof e!="object")){if(e.entries&&typeof e.entries=="object")return e.entries;if(Array.isArray(e.pipe))for(let t of e.pipe){let r=Ve(t);if(r)return r}if(e.wrapped)return Ve(e.wrapped);if(Array.isArray(e.options))for(let t of e.options){let r=Ve(t);if(r)return r}}}function _o(e){let t=Ve(e);if(!t)return!1;for(let r of Object.values(t)){let n=r?.visibility;if(n!==void 0&&n!=="guest")return!0}return!1}var $e=class{store=new Map;maxAttempts;lockoutMs;sessionTimeoutMs;constructor(t={}){this.maxAttempts=t.maxAttempts??5,this.lockoutMs=t.lockoutMs??900*1e3,this.sessionTimeoutMs=t.sessionTimeoutMs??480*60*1e3}checkLockout(t){let r=this.store.get(t);if(r?.lockedUntil){if(Date.now()<r.lockedUntil){let n=Math.ceil((r.lockedUntil-Date.now())/6e4);throw new Error(`Account temporarily locked after too many failed attempts. Try again in ${n} minute${n===1?"":"s"}.`)}this.store.delete(t)}}recordFailure(t){let r=Date.now();!this.store.has(t)&&this.store.size>=1e4&&this._evictExpired(r);let n=this.store.get(t)??{attempts:0,lastAttempt:0,lockedUntil:null};return n.attempts+=1,n.lastAttempt=r,n.attempts>=this.maxAttempts&&(n.lockedUntil=r+this.lockoutMs),this.store.set(t,n),{attempts:n.attempts,locked:n.lockedUntil!==null&&Date.now()<n.lockedUntil,lockedUntil:n.lockedUntil}}_evictExpired(t){for(let[r,n]of this.store)n.lockedUntil!==null&&t>n.lockedUntil?this.store.delete(r):n.lockedUntil===null&&t-n.lastAttempt>this.lockoutMs&&this.store.delete(r)}recordSuccess(t){this.store.delete(t)}isSessionExpired(t){return Date.now()-t>this.sessionTimeoutMs}getEntry(t){return this.store.get(t)}};function No(e,t){if(t.includes(".")){let r=t.split("."),n=e;for(let o of r){if(n==null||typeof n!="object")return;n=n[o]}return n}return e[t]}function Uo(e,t){let r=No(t,e.field);switch(e.operator){case"equals":return r===e.value;case"notEquals":return r!==e.value;case"in":return Array.isArray(e.value)&&e.value.includes(r);case"notIn":return Array.isArray(e.value)&&!e.value.includes(r);case"greaterThan":return typeof r=="number"&&typeof e.value=="number"&&r>e.value;case"lessThan":return typeof r=="number"&&typeof e.value=="number"&&r<e.value;case"greaterThanOrEqual":return typeof r=="number"&&typeof e.value=="number"&&r>=e.value;case"lessThanOrEqual":return typeof r=="number"&&typeof e.value=="number"&&r<=e.value;case"exists":return r!=null&&r!==""&&r!==!1;case"notExists":return r==null||r===""||r===!1;case"contains":return typeof r=="string"&&typeof e.value=="string"||Array.isArray(r)?r.includes(e.value):!1;default:return!1}}function Fo(e){return e instanceof se||"expression"in e?e.expression:e}function ee(e,t){let r=Fo(e);if(r.type==="condition")return Uo(r,t);let{logic:n,conditions:o}=r;return n==="and"?o.every(s=>ee(s,t)):o.some(s=>ee(s,t))}function Mo(e,t){return e?{visible:e.visible?ee(e.visible,t):!0,disabled:e.disabled?ee(e.disabled,t):!1,required:e.required?ee(e.required,t):!1,readonly:e.readonly?ee(e.readonly,t):!1}:{visible:!0,disabled:!1,required:!1,readonly:!1}}var se=class e{expression;constructor(t){this.expression=t}get type(){return this.expression.type}or(t){let r=t instanceof e?t.expression:t,n=this.expression;return n.type==="group"&&n.logic==="or"?new e({type:"group",logic:"or",conditions:[...n.conditions,r]}):new e({type:"group",logic:"or",conditions:[n,r]})}and(t){let r=t instanceof e?t.expression:t,n=this.expression;return n.type==="group"&&n.logic==="and"?new e({type:"group",logic:"and",conditions:[...n.conditions,r]}):new e({type:"group",logic:"and",conditions:[n,r]})}};function Lo(e){function t(r,n){return new se({type:"condition",field:e,operator:r,value:n})}return{equals:r=>t("equals",r),notEquals:r=>t("notEquals",r),in:r=>t("in",r),notIn:r=>t("notIn",r),greaterThan:r=>t("greaterThan",r),lessThan:r=>t("lessThan",r),greaterThanOrEqual:r=>t("greaterThanOrEqual",r),lessThanOrEqual:r=>t("lessThanOrEqual",r),exists:()=>t("exists"),notExists:()=>t("notExists"),contains:r=>t("contains",r)}}function Bo(e){let t=e instanceof se?e.expression:e,r=new Set;function n(o){if(o.type==="condition")r.add(o.field);else for(let s of o.conditions)n(s)}return n(t),r}var Vo=new Set(["http:","https:","mailto:","tel:","blob:"]);function $o(e){if(!e||typeof e!="string")return"";let t=e.trim();if(/^[/.?#]/.test(t))return t;try{let r=new URL(t);if(Vo.has(r.protocol))return t}catch{return t}return""}function Ho(){let e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var qo=3e4,Go=15e3;function jo(e,t,r){if(r?.aborted)return Promise.reject(fr(r.reason));let n=t>0;return!n&&!r?e:new Promise((o,s)=>{let a=!1,d;function p(){a=!0,d!==void 0&&(clearTimeout(d),d=void 0),r&&r.removeEventListener("abort",h)}function h(){a||(p(),s(fr(r?.reason)))}r&&r.addEventListener("abort",h,{once:!0}),n&&(d=setTimeout(()=>{a||(p(),s(Ko(t)))},t)),e.then(v=>{a||(p(),o(v))},v=>{a||(p(),s(v))})})}function Ko(e){let t=new Error(`Operation timed out after ${e}ms`);return t.name="TimeoutError",t}function fr(e){if(e instanceof Error){let r=new Error(e.message);return r.name="AbortError",r}let t=new Error(typeof e=="string"?e:"Operation was aborted");return t.name="AbortError",t}function Se(e,t){let r=new Date(e),n=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==n&&r.setDate(0),r}function yt(e,t){let r=new Date(e),n=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==n&&r.setDate(0),r}function Wo(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=Se(t,1):e==="3months"?r=Se(t,3):e==="6months"?r=Se(t,6):e==="1year"?r=yt(t,1):e==="2years"?r=yt(t,2):r=Se(t,1),r.toISOString()}function Yo(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}function zo(e,t="URL"){try{let r=new URL(e);if(!["http:","https:"].includes(r.protocol))throw new Error(`Invalid protocol: ${r.protocol}`);return e}catch(r){throw new Error(`Invalid ${t}: ${e}. ${r instanceof Error?r.message:"Invalid URL format"}`)}}function Xo(e){let t={};for(let[r,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof n}`);if(/<[^>]*>/.test(n))throw new Error(`Metadata value for key '${r}' must not contain HTML`);let o=n;if(o.length>1e3)throw new Error(`Metadata value for key '${r}' is too long (max 1000 characters)`);if(r.length>100)throw new Error(`Metadata key '${r}' is too long (max 100 characters)`);t[r]=o}return t}function Jo(e,t=!0){let r=process.env[e];if(t&&!r)throw new Error(`Required environment variable '${e}' is not set`);return r||""}function Qo(e,t){if(!e)return null;let r=`${encodeURIComponent(t)}=`,n=e.split(";");for(let o=0;o<n.length;o++){let s=n[o];if(s){for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(r)===0)return decodeURIComponent(s.substring(r.length,s.length))}}return null}function Vd(e,t){let r=e;return r.metadata=t,r}import*as u from"valibot";var Te=new Map;function E(e,t){Te.set(e,t)}function Hd(e){return Te.has(e)}function qd(){return Array.from(Te.keys())}function Gd(){Te.clear()}function A(e,t){return t?e:u.nullish(e)}var He=e=>{let t=[];e.validation?.minLength!==void 0&&t.push(u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(u.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(u.regex(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?u.pipe(u.string(),...t):u.string();return A(r,e.validation?.required)},Zo=e=>{let t=u.pipe(u.string(),u.email("Invalid email address"));return A(t,e.validation?.required)},ei=e=>{let t=e.validation?.minLength!==void 0?u.pipe(u.string(),u.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):u.string();return A(t,e.validation?.required)},ti=e=>{let t=u.pipe(u.string(),u.url("Invalid URL"));return A(t,e.validation?.required)},ae=e=>{let t=[];e.validation?.min!==void 0&&t.push(u.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(u.maxValue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?u.pipe(u.number(),...t):u.number();return A(r,e.validation?.required)},gr=e=>{let t=u.boolean();return A(t,e.validation?.required)},le=e=>{let t=u.pipe(u.string(),u.check(r=>!isNaN(new Date(r).getTime()),"Invalid date format"));return A(t,e.validation?.required)},br=u.object({url:u.string(),filename:u.string(),size:u.number(),mimeType:u.nullish(u.string()),uploadedAt:u.nullish(u.string())}),hr=e=>{let t=u.nullable(br);return A(t,e.validation?.required)},vr=e=>{let t=u.array(br);return A(t,e.validation?.required)},Er=u.object({fullUrl:u.string(),thumbUrl:u.string()}),ri=e=>{let t=u.union([u.string(),Er]);return A(t,e.validation?.required)},ni=e=>{let t=u.array(u.union([u.string(),Er]));return A(t,e.validation?.required)},oi=e=>{let t=u.object({lat:u.number(),lng:u.number()});return A(t,e.validation?.required)},ii=e=>{let t=u.object({formatted_address:u.string(),latitude:u.number(),longitude:u.number(),street_number:u.nullish(u.string()),route:u.nullish(u.string()),locality:u.nullish(u.string()),administrative_area_level_1:u.nullish(u.string()),administrative_area_level_2:u.nullish(u.string()),country:u.nullish(u.string()),postal_code:u.nullish(u.string())});return A(t,e.validation?.required)},si=e=>{let t=u.record(u.string(),u.unknown());return A(t,e.validation?.required)},ai=e=>{let t=u.array(u.unknown());return A(t,e.validation?.required)},bt=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(s=>s.value),o=u.picklist(n);return A(o,e.validation?.required)}let r=u.union([u.string(),u.number()]);return A(r,e.validation?.required)},li=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let n=t.map(s=>s.value),o=u.array(u.picklist(n));return A(o,e.validation?.required)}let r=u.array(u.string());return A(r,e.validation?.required)},ui=e=>{let t=u.pipe(u.string(),u.minLength(1,"Invalid ID format"));return A(t,e.validation?.required)},Et=e=>{let t=u.string();return A(t,e.validation?.required)},ci=e=>{let t=u.string();return A(t,e.validation?.required)},di=e=>{let t=e.validation?.minLength??15,r=e.validation?.maxLength??34,n=e.validation?.pattern??"^[A-Z]{2}[0-9]{2}[A-Z0-9]{4,34}$",o=[];if(t!==void 0&&o.push(u.minLength(t,`IBAN must be at least ${t} characters`)),r!==void 0&&o.push(u.maxLength(r,`IBAN must not exceed ${r} characters`)),n){let a=typeof n=="string"?new RegExp(n):n;o.push(u.regex(a,"Invalid IBAN format"))}let s=o.length>0?u.pipe(u.string(),...o):u.string();return A(s,e.validation?.required)},yr=()=>u.never(),pi=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let n=[t.checkedValue,t.uncheckedValue],o=u.picklist(n);return A(o,e.validation?.required)}let r=u.boolean();return A(r,e.validation?.required)},fi=e=>u.custom(r=>e.validation?.required?typeof r=="object"&&r!==null?r.gdprConsent===!0:!1:r===!1||r===null||r===void 0?!0:typeof r=="object"&&r!==null?r.gdprConsent===!0:!1,"GDPR consent must be given"),mi=e=>{let t=u.object({amount:u.number(),currency:u.optional(u.string()),vatIncluded:u.optional(u.boolean()),discountPercent:u.optional(u.pipe(u.number(),u.minValue(0),u.maxValue(100)))});return A(t,e.validation?.required)};function gi(){E("text",He),E("textarea",He),E("richtext",He),E("color",He),E("email",Zo),E("password",ei),E("url",ti),E("tel",ci),E("iban",di),E("number",ae),E("currency",ae),E("price",mi),E("range",ae),E("year",ae),E("rating",ae),E("duration",ae),E("boolean",gr),E("checkbox",gr),E("gdprConsent",fi),E("date",le),E("datetime-local",le),E("time",le),E("week",le),E("month",le),E("timestamp",le),E("file",hr),E("files",vr),E("document",hr),E("documents",vr),E("image",ri),E("images",ni),E("geopoint",oi),E("address",ii),E("map",si),E("array",ai),E("select",bt),E("multiselect",li),E("radio",bt),E("combobox",bt),E("switch",pi),E("reference",ui),E("hidden",Et),E("avatar",Et),E("badge",Et),E("submit",yr),E("reset",yr)}gi();function xe(e){if(e.validation?.schema){let n=e.validation.schema;return A(n,e.validation?.required)}let t=Te.get(e.type);if(t){let n=t(e);if(n!==null)return n}let r=u.unknown();return A(r,e.validation?.required)}function L(){return typeof globalThis<"u"&&globalThis._DNDEV_CONFIG_?globalThis._DNDEV_CONFIG_:null}var K=null;function Ae(){return Tr().platform}function Tr(){if(K)return K;let e=L();if(e?.platform)return K={platform:e.platform,mode:e.mode,context:e.context,version:e.version,metadata:{detectedAt:e.timestamp}},K;let t=[];t.push(...hi()),t.push(...vi()),t.push(...yi());let r=t.sort((n,o)=>o.confidence-n.confidence)[0];return!r||r.confidence<N.MINIMUM?(K={platform:C.UNKNOWN,mode:Sr(),context:bi(),metadata:{detectedAt:Date.now()}},K):(K={platform:r.platform,mode:Sr(),context:r.context,version:Ei(r.platform),metadata:{...r.metadata,detectedAt:Date.now()}},K)}var Ie=null,Ce=null;function xr(){if(typeof globalThis<"u"&&globalThis.__NEXT_DATA__||typeof process<"u"&&process.env?.NEXT_RUNTIME)return Ce=!0,!0;if(Ce===!0)return!0;let e=L();if(e?.platform){let r=e.platform===C.NEXTJS;return r&&(Ce=!0),r}let t=Ae()===C.NEXTJS;return t&&(Ce=!0),t}function Ir(){if(Ie!==null)return Ie;let e=L();if(e?.platform)return Ie=e.platform===C.VITE,Ie;let t=Ae()===C.VITE;return Ie=t,t}function B(){return typeof window<"u"&&typeof document<"u"}function St(){return typeof process<"u"&&!!process.versions?.node}function hi(){let e=[];if(B()){globalThis.__vite_plugin_react_preamble_installed__&&e.push({platform:C.VITE,confidence:N.HIGH,context:k.CLIENT,metadata:{viteHmrPort:globalThis.__vite_hmr_port}});let t=L();t?.platform===C.VITE&&e.push({platform:C.VITE,confidence:N.HIGH,context:k.CLIENT}),t?.i18n?.mapping&&e.push({platform:C.VITE,confidence:N.MEDIUM,context:k.CLIENT}),typeof globalThis<"u"&&globalThis.import?.meta?.hot!==void 0&&e.push({platform:C.VITE,confidence:N.LOW,context:k.CLIENT})}return St()&&(process.env.VITE&&e.push({platform:C.VITE,confidence:N.MEDIUM,context:k.SERVER}),process.env.npm_lifecycle_event?.includes(C.VITE)&&e.push({platform:C.VITE,confidence:N.LOW,context:k.BUILD})),e}function vi(){let e=[];return St()&&(process.env.NEXT_RUNTIME&&e.push({platform:C.NEXTJS,confidence:N.HIGH,context:k.SERVER,metadata:{nextjsRuntime:process.env.NEXT_RUNTIME}}),process.env.__NEXT_PRIVATE_PREBUNDLED_REACT&&e.push({platform:C.NEXTJS,confidence:N.MEDIUM,context:k.SERVER}),process.env._DNDEV_CONFIG_&&e.push({platform:C.NEXTJS,confidence:N.LOW,context:k.SERVER})),B()&&(L()?.platform===C.NEXTJS&&e.push({platform:C.NEXTJS,confidence:N.HIGH,context:k.CLIENT}),globalThis.__NEXT_DATA__&&e.push({platform:C.NEXTJS,confidence:N.LOW,context:k.CLIENT})),e}function yi(){let e=[];try{typeof globalThis<"u"&&globalThis.expo?.Constants?.expoConfig&&e.push({platform:C.EXPO,confidence:N.HIGH,context:k.CLIENT})}catch{}try{typeof globalThis<"u"&&globalThis.Platform?.OS&&!B()&&e.push({platform:C.REACT_NATIVE,confidence:N.MEDIUM,context:k.CLIENT})}catch{}let t=L();return t?.platform===C.EXPO?e.push({platform:C.EXPO,confidence:N.HIGH,context:k.CLIENT}):t?.platform===C.REACT_NATIVE&&e.push({platform:C.REACT_NATIVE,confidence:N.HIGH,context:k.CLIENT}),e}function Sr(){let e;return typeof import.meta<"u"&&import.meta.env?.MODE?e=import.meta.env.MODE:typeof process<"u"&&(e="production"),e===X.PRODUCTION?X.PRODUCTION:e===X.TEST?X.TEST:X.DEVELOPMENT}function bi(){return B()?k.CLIENT:St()?X.PRODUCTION==="production"&&!process.env.NEXT_RUNTIME?k.BUILD:k.SERVER:k.CLIENT}function Ei(e){if(!(typeof process>"u"))return e===C.VITE?process.env.VITE_APP_VERSION||process.env.VITE_VERSION||process.env.APP_VERSION:e===C.NEXTJS?process.env.NEXT_PUBLIC_APP_VERSION||process.env.NEXT_PUBLIC_VERSION||process.env.__NEXT_VERSION||process.env.APP_VERSION:process.env.APP_VERSION||process.env.VITE_APP_VERSION||process.env.NEXT_PUBLIC_APP_VERSION}function Cr(e){return e&&(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e)}function Si(e){let t,r=L();return r?.env&&typeof r.env=="object"&&(t=r.env[e]),t===void 0&&typeof import.meta<"u"&&import.meta.env&&(t=import.meta.env[e]),Cr(t)}function Ti(e){let t=L(),r;return t?.env&&typeof t.env=="object"&&(r=t.env[e]),r===void 0&&typeof process<"u"&&process.env&&(r=process.env[e]),Cr(r)}function D(e,t){if(e==="NODE_ENV"||e==="VITE_NODE_ENV"||e==="NEXT_PUBLIC_NODE_ENV"||e==="MODE"||e==="DEV"||e==="PROD"){let a=L();if(a?.env?.MODE)return e==="DEV"?a.env.MODE==="development"?"true":"false":e==="PROD"?a.env.MODE==="production"?"true":"false":a.env.MODE;if(typeof import.meta<"u"&&import.meta.env){let d=import.meta.env;if(e==="MODE"&&d.MODE)return d.MODE;if(e==="DEV")return d.DEV?"true":"false";if(e==="PROD")return d.PROD?"true":"false"}if(typeof process<"u"){let d="production";return e==="DEV"?d==="development"?"true":"false":e==="PROD"?d==="production"?"true":"false":d}return e==="DEV"?"true":e==="PROD"?"false":"development"}let r=L()?.platform,n=t||r||(Ir()?"vite":xr()?"nextjs":Ae()),o=["MODE","DEV","PROD","SSR"],s;return n==="vite"?o.includes(e)||e.startsWith("VITE_")?s=e:s=`VITE_${e}`:n==="nextjs"?e.startsWith("NEXT_PUBLIC_")?s=e:s=`NEXT_PUBLIC_${e}`:s=e,n==="vite"?Si(s):n==="nextjs"?Ti(s):void 0}function te(){if(typeof import.meta<"u"&&import.meta.env)return import.meta.env.DEV===!0;let e=D("APP_ENV"),t=D("NODE_ENV");return(e||t||"development").toLowerCase()==="development"}function Re(e){return typeof e=="object"&&e!==null&&"currentUser"in e&&typeof e.currentUser=="object"&&e.currentUser!==null}var xi=12e4,Tt=class{refreshTimerId=null;refreshAttempts=0;refreshBuffer;maxRefreshAttempts;autoRefresh;authInstance;onTokenExpired;onFatalError;refreshCallback;tokenInfo={token:null,expiresAt:null,status:"not-initialized"};constructor(t=null,r={}){this.authInstance=t,this.refreshBuffer=r.refreshBufferMs??xi,this.maxRefreshAttempts=r.maxRefreshAttempts??3,this.autoRefresh=r.autoRefresh!==!1,this.onTokenExpired=r.onTokenExpired,this.onFatalError=r.onFatalError}initialize(t){this.clearRefreshTimer(),this.refreshAttempts=0;let r=this.calculateTokenStatus(t.expiresAt);this.tokenInfo={...t,status:r},this.autoRefresh&&t.expiresAt&&this.scheduleRefresh(t.expiresAt)}getTokenInfo(){return this.tokenInfo}reset(){this.clearRefreshTimer(),this.tokenInfo={token:null,expiresAt:null,status:"not-initialized"}}async forceRefresh(t){try{if(this.refreshCallback&&await this.refreshCallback()&&this.tokenInfo.token)return this.tokenInfo.token;if(t&&typeof t.getIdToken=="function"){let r=await t.getIdToken(!0),n=new Date(Date.now()+3600*1e3);return this.updateTokenInfo({token:r,expiresAt:n}),this.refreshAttempts=0,r}else if(t&&typeof t.getIdTokenResult=="function"){let r=await t.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),this.refreshAttempts=0,r.token}if(Re(this.authInstance)){let r=await this.authInstance.currentUser.getIdTokenResult(!0),n=new Date(r.expirationTime);return this.updateTokenInfo({token:r.token,expiresAt:n}),this.refreshAttempts=0,r.token}throw y(new Error("No valid refresh method available"),{userMessage:"Unable to refresh authentication token",severity:"warning",context:{component:"TokenManager"}})}catch(r){return this.handleError(r instanceof Error?r:new Error("Unknown error during token refresh")),null}}async getValidToken(){let{status:t,token:r}=this.tokenInfo;if(t==="valid")return r;if((t==="expiring-soon"||t==="expired")&&this.autoRefresh)try{if(this.refreshCallback&&await this.refreshCallback())return this.tokenInfo.token;if(Re(this.authInstance))return await this.forceRefresh(this.authInstance.currentUser)}catch(n){this.handleError(n instanceof Error?n:new Error("Failed to refresh token"))}return t==="expired"||t==="not-initialized"||t==="error"?null:r}onRefreshNeeded(t){return this.refreshCallback=t,()=>{this.refreshCallback=void 0}}updateTokenInfo(t){let r={token:t.token??this.tokenInfo.token,expiresAt:t.expiresAt??this.tokenInfo.expiresAt,refreshToken:t.refreshToken??this.tokenInfo.refreshToken,idToken:t.idToken??this.tokenInfo.idToken},n=this.calculateTokenStatus(r.expiresAt);this.tokenInfo={...r,status:n},this.autoRefresh&&r.expiresAt&&this.scheduleRefresh(r.expiresAt)}calculateTokenStatus(t){if(!t)return this.tokenInfo.token?"valid":"not-initialized";let r=new Date;if(r>=t)return"expired";let n=new Date(t.getTime()-this.refreshBuffer);return r>=n?"expiring-soon":"valid"}scheduleRefresh(t){this.clearRefreshTimer();let r=new Date,n=t.getTime()-r.getTime()-this.refreshBuffer;if(n<=0){Re(this.authInstance)&&this.forceRefresh(this.authInstance.currentUser).catch(o=>{this.handleRefreshError(o)});return}this.refreshTimerId=setTimeout(()=>{Re(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(o=>{this.handleRefreshError(o)}):this.refreshCallback&&this.refreshCallback().catch(o=>{this.handleRefreshError(o)})},n)}handleRefreshError(t){if(te(),this.refreshAttempts++,this.refreshAttempts<=this.maxRefreshAttempts){let r=Math.min(1e3*Math.pow(2,this.refreshAttempts-1),3e4);te(),setTimeout(()=>{Re(this.authInstance)?this.forceRefresh(this.authInstance.currentUser).catch(n=>{this.handleRefreshError(n)}):this.refreshCallback&&this.refreshCallback().catch(n=>{this.handleRefreshError(n)})},r)}else this.tokenInfo={...this.tokenInfo,status:"error",error:t instanceof Error?t:new Error("Max token refresh attempts reached")},this.onTokenExpired&&this.onTokenExpired(),this.onFatalError&&this.onFatalError(t instanceof Error?t:new Error("Max token refresh attempts reached"))}handleError(t){te(),this.tokenInfo={...this.tokenInfo,status:"error",error:t}}clearRefreshTimer(){this.refreshTimerId!==null&&(clearTimeout(this.refreshTimerId),this.refreshTimerId=null)}},gp=be(Tt,null,{});var qe=class{buildKey(t,r,n,o=!1){let s="dndev";switch(r){case"user":if(!n){if(o)return null;throw y(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:t,scope:r}})}return`${s}:user:${n}:${t}`;case"global":return`${s}:global:${t}`;case"session":return`${s}:session:${t}`;default:return`${s}:${t}`}}};var re=null,Ii="dndev-keys",we="encryption-keys",Ar="main";async function Rr(){return new Promise((e,t)=>{let r=indexedDB.open(Ii,1);r.onupgradeneeded=()=>{r.result.createObjectStore(we)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}async function Ci(e){let t=await Rr();return new Promise((r,n)=>{let o=t.transaction(we,"readwrite");o.objectStore(we).put(e,Ar),o.oncomplete=()=>r(),o.onerror=()=>n(o.error)})}async function Ai(){try{let e=await Rr();return new Promise((t,r)=>{let o=e.transaction(we,"readonly").objectStore(we).get(Ar);o.onsuccess=()=>t(o.result??null),o.onerror=()=>r(o.error)})}catch{return null}}async function Ri(){try{return await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(e){throw y(e,{userMessage:"Failed to generate encryption key",context:{algorithm:"AES-GCM"}})}}async function wr(){if(re)return re;try{let e=await Ai();return e?(re=e,re):(re=await Ri(),await Ci(re),re)}catch(e){throw y(e,{userMessage:"Failed to get or create encryption key"})}}async function kr(e){try{let t=await wr(),r=window.crypto.getRandomValues(new Uint8Array(12)),n=typeof e=="string"?e:JSON.stringify(e),s=new TextEncoder().encode(n),a=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},t,s),d=new Uint8Array(r.length+a.byteLength);return d.set(r,0),d.set(new Uint8Array(a),r.length),btoa(String.fromCharCode(...d))}catch(t){throw y(t,{userMessage:"Failed to encrypt data"})}}async function Pr(e){try{let t=await wr(),r=Uint8Array.from(atob(e),p=>p.charCodeAt(0)),n=r.slice(0,12),o=r.slice(12),s=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:n},t,o),d=new TextDecoder().decode(s);try{return JSON.parse(d)}catch{return d}}catch(t){throw y(t,{userMessage:"Failed to decrypt data"})}}var W=class extends qe{userId=null;constructor(t=null){super(),this.userId=t}setUserId(t){this.userId=t}async get(t,r={}){let{scope:n="user",encryption:o=!1}=r,s=this.buildKey(t,n,this.userId,!0);if(!s)return null;try{if(!B())return null;let a=localStorage.getItem(s);if(!a)return null;let d=JSON.parse(a);if(d.expiresAt&&new Date(d.expiresAt)<new Date)return await this.remove(t),null;let p=d.value;return o&&typeof p=="string"&&(p=await Pr(p)),p}catch(a){throw y(a,{userMessage:"Failed to retrieve data from local storage",context:{key:t,options:r}})}}async set(t,r,n={}){let{scope:o="user",encryption:s=!1,expiry:a=0}=n,d=this.buildKey(t,o,this.userId,!0);if(d)try{let p=r;s&&(p=await kr(r));let h=a>0?new Date(Date.now()+a*1e3).toISOString():null,v=JSON.stringify({value:p,expiresAt:h,createdAt:new Date().toISOString()});typeof window<"u"&&localStorage.setItem(d,v)}catch(p){let h=p?.name==="QuotaExceededError"||p?.code===22?"Storage quota exceeded. Please free up space or login to sync to cloud.":p?.name==="SecurityError"||p?.code===18?"Storage access denied. Please enable localStorage or login to sync to cloud.":"Failed to store data in local storage";throw y(p,{userMessage:h,context:{key:t,options:n}})}}async remove(t){let r=["user","global","session"];for(let n of r)try{let o=this.buildKey(t,n,this.userId,!0);if(!o)continue;typeof window<"u"&&localStorage.removeItem(o)}catch{}}async clear(t){if(!t){let a=(typeof window<"u"?Object.keys(localStorage):[]).filter(d=>d.startsWith("dndev:"));for(let d of a)typeof window<"u"&&localStorage.removeItem(d);return}let r=t==="user"&&this.userId?`dndev:user:${this.userId}:`:`dndev:${t}:`,o=(typeof window<"u"?Object.keys(localStorage):[]).filter(s=>s.startsWith(r));for(let s of o)typeof window<"u"&&localStorage.removeItem(s)}};var ke=class{localStrategy;userId;apiEndpoint;getAuthToken;constructor(t,r="/api/storage",n){if(!t)throw y(new Error("User ID is required for HybridStorageStrategy"));this.userId=t,this.localStrategy=new W(t),this.apiEndpoint=r,this.getAuthToken=n}async buildHeaders(t){let r={};if(t&&(r["Content-Type"]=t),this.getAuthToken){let n=await this.getAuthToken();n&&(r.Authorization=`Bearer ${n}`)}return r}async get(t,r={}){try{let n=await this.localStrategy.get(t,r);return n!==null?n:await this.getFromCloud(t,r)}catch(n){try{return await this.localStrategy.get(t,r)}catch(o){throw y(n,{userMessage:"Failed to retrieve data from storage",context:{key:t,options:r,fallbackError:o}})}}}async set(t,r,n={}){await this.localStrategy.set(t,r,n),this.setToCloud(t,r,n).catch(o=>{y(o,{userMessage:"Failed to save data to cloud storage",severity:"warning",context:{key:t,options:n}})})}async remove(t){try{await this.localStrategy.remove(t),this.removeFromCloud(t).catch(r=>{y(r,{severity:"warning",showNotification:!1})})}catch(r){throw y(r,{userMessage:"Failed to remove data",context:{key:t}})}}async clear(t){try{await this.localStrategy.clear(t),this.clearFromCloud(t).catch(r=>{})}catch(r){throw y(r,{userMessage:"Failed to clear storage",context:{scope:t}})}}buildKey(t,r,n,o=!1){let s="dndev";switch(r){case"user":if(!n){if(o)return null;throw y(new Error("User ID is required for user-scoped storage"),{userMessage:"Cannot access user data: missing user ID",severity:"error",context:{key:t,scope:r}})}return`${s}:user:${n}:${t}`;case"global":return`${s}:global:${t}`;case"session":return`${s}:session:${t}`;default:return`${s}:${t}`}}async getFromCloud(t,r){try{let{scope:n="user"}=r,o=this.buildKey(t,n,this.userId,!0);if(!o)return null;let s=await fetch(`${this.apiEndpoint}/${encodeURIComponent(o)}`,{headers:await this.buildHeaders()});if(!s.ok){if(s.status===404)return null;throw y(new Error(`Cloud storage API error: ${s.status} ${s.statusText}`),{userMessage:"Failed to retrieve data from cloud storage",severity:"warning",context:{key:t,status:s.status}})}let a=await s.json();return a.expiresAt&&new Date(a.expiresAt)<new Date?(this.removeFromCloud(t).catch(console.warn),null):(this.localStrategy.set(t,a.value,r).catch(console.warn),a.value)}catch{return null}}async setToCloud(t,r,n){let{scope:o="user",expiry:s=0}=n,a=this.buildKey(t,o,this.userId,!0);if(!a)return;let d=s>0?new Date(Date.now()+s*1e3).toISOString():null,p={value:r,expiresAt:d,createdAt:new Date().toISOString()},h=await fetch(`${this.apiEndpoint}/${encodeURIComponent(a)}`,{method:"PUT",headers:await this.buildHeaders("application/json"),body:JSON.stringify(p)});if(!h.ok)throw y(new Error(`Cloud storage API error: ${h.status} ${h.statusText}`),{userMessage:"Failed to save data to cloud storage",severity:"error",context:{key:t,status:h.status}})}async removeFromCloud(t){let r=["user","global","session"];for(let n of r)try{let o=this.buildKey(t,n,this.userId,!0);if(!o)continue;let s=await fetch(`${this.apiEndpoint}/${encodeURIComponent(o)}`,{method:"DELETE",headers:await this.buildHeaders()});!s.ok&&s.status}catch{}}async clearFromCloud(t){try{let r=new URLSearchParams;t&&r.append("scope",t),t==="user"&&r.append("userId",this.userId);let n=r.toString(),o=n?`${this.apiEndpoint}/clear?${n}`:`${this.apiEndpoint}/clear`;(await fetch(o,{method:"DELETE",headers:await this.buildHeaders()})).ok}catch{}}};var Ge=class{strategy;initialized=!1;userId=null;isPro=!1;constructor(t=new W){this.strategy=t}initialize(){if(!this.initialized)try{this.initialized=!0}catch(t){y(t,{severity:"warning",showNotification:!1})}}setStrategy(t){this.initialize(),this.strategy=t}updateUser(t,r){this.initialize(),r&&t?this.strategy=new ke(t):this.strategy=new W(t)}updateStrategy(){this.isPro&&this.userId?this.strategy=new ke(this.userId):this.strategy=new W(this.userId)}async get(t,r={}){return this.initialize(),this.strategy.get(t,r)}async set(t,r,n={}){return this.initialize(),this.strategy.set(t,r,n)}async remove(t){return this.initialize(),this.strategy.remove(t)}async clear(t){return this.initialize(),this.strategy.clear(t)}async setSecure(t,r,n={}){return this.initialize(),this.set(t,r,{...n,encryption:!0})}async getSecure(t,r={}){return this.initialize(),this.get(t,{...r,encryption:!0})}},wi=be(Ge);import*as S from"valibot";var Or=S.object({name:S.string(),color:S.string(),icon:S.string(),button:S.object({backgroundColor:S.string(),textColor:S.string(),borderColor:S.string(),hoverBackgroundColor:S.string(),focusOutlineColor:S.string(),fontWeight:S.optional(S.string(),"500")})}),ki=S.object({...Or.entries,type:S.picklist(["auth","both"]),scopes:S.optional(S.array(S.string())),firebaseProviderId:S.optional(S.string())}),je=S.union([S.literal(""),S.pipe(S.string(),S.url())]),Pi=S.object({authUrl:je,tokenUrl:je,profileUrl:je,revokeUrl:S.optional(je)}),Oi=S.object({authentication:S.optional(S.array(S.string())),"api-access":S.array(S.string())}),Qp=S.object({...Or.entries,type:S.picklist(["oauth","both"]),scopes:Oi,endpoints:Pi}),Pe=null;function Di(){let e=[];for(let[t,r]of Object.entries(he))S.safeParse(ki,r).success?e.push(t):typeof window<"u"&&te();return e}function xt(){if(Pe!==null)return Pe;let e=D("AUTH_PARTNERS");if(!e)return Pe=[],Pe;let t=Di(),r=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>t.includes(n));return Pe=r,r}var V={AUTH:"auth",OAUTH:"oauth",I18N:"i18n",BILLING:"billing",ROUTES:"routes",THEMES:"themes",COMPONENTS:"components",CRUD:"crud",FORMS:"forms",REALTIME:"realtime",STORAGE:"storage",AI:"ai"};function Y(e){return!!e&&e.trim()!==""}var of={[V.AUTH]:()=>xt().length>0,[V.OAUTH]:()=>["VITE_GOOGLE_CLIENT_ID","VITE_GITHUB_CLIENT_ID","VITE_FACEBOOK_CLIENT_ID","VITE_TWITTER_CLIENT_ID","VITE_LINKEDIN_CLIENT_ID","VITE_DISCORD_CLIENT_ID","VITE_SLACK_CLIENT_ID","VITE_MICROSOFT_CLIENT_ID","VITE_APPLE_CLIENT_ID"].some(t=>Y(D(t))),[V.I18N]:()=>!0,[V.BILLING]:()=>!!(Y(D("STRIPE_PUBLISHABLE_KEY"))||Y(D("BILLING_ENABLED"))&&D("BILLING_ENABLED")==="true"),[V.ROUTES]:()=>!0,[V.THEMES]:()=>!0,[V.COMPONENTS]:()=>!0,[V.CRUD]:()=>!0,[V.FORMS]:()=>!0,[V.REALTIME]:()=>!!(Y(D("REALTIME_ENABLED"))&&D("REALTIME_ENABLED")==="true"||Y(D("FIREBASE_CONFIG"))),[V.STORAGE]:()=>!!(Y(D("STORAGE_ENABLED"))&&D("STORAGE_ENABLED")==="true"||Y(D("FIREBASE_CONFIG"))),[V.AI]:()=>!!(Y(D("AI_ENABLED"))&&D("AI_ENABLED")==="true")};var zi=Bt(Ot(),1);var Xi=Bt(Ot(),1);var Dt=class{events=new Map;eventCache=new Map;maxListeners=10;cacheTTL=180*1e3;on(t,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let o=this.getListeners(t),s={handler:r,once:!1,context:n};return o.push(s),this.checkListenerCount(t),()=>{this.off(t,r)}}once(t,r,n){if(typeof r!="function")throw new TypeError("Handler must be a function");let o=this.getListeners(t),s={handler:r,once:!0,context:n};return o.push(s),this.checkListenerCount(t),()=>{this.off(t,r)}}off(t,r){let n=this.events.get(t);if(!n||n.length===0)return!1;let o=n.findIndex(s=>s.handler===r);return o===-1?!1:(n.splice(o,1),n.length===0&&this.events.delete(t),!0)}emit(t,...r){this.cacheEvent(t,r);let n=this.events.get(t);if(!n||n.length===0)return!1;let o=[...n],s=[];for(let a of o)try{a.context?a.handler.apply(a.context,r):a.handler(...r),a.once&&s.push(a)}catch(d){y(d,{userMessage:`Error in event handler for ${t}`,context:{eventName:t,args:r},severity:"warning"})}if(s.length>0){let a=this.events.get(t);if(a){let d=a.filter(p=>!s.includes(p));d.length===0?this.events.delete(t):this.events.set(t,d)}}return!0}hasListeners(t){let r=this.events.get(t);return!!r&&r.length>0}listenerCount(t){return this.events.get(t)?.length||0}eventNames(){return Array.from(this.events.keys())}listeners(t){let r=this.events.get(t);return r?r.map(n=>n.handler):[]}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}setMaxListeners(t){return this.maxListeners=t>0?t:1/0,this}getMaxListeners(){return this.maxListeners}getListeners(t){let r=this.events.get(t);return r||(r=[],this.events.set(t,r)),r}checkListenerCount(t){let r=this.listenerCount(t);this.maxListeners!==1/0&&r>this.maxListeners}cacheEvent(t,r){let n=this.eventCache.get(t);n||(n=[],this.eventCache.set(t,n)),n.push({data:r,timestamp:Date.now()}),this.cleanupCache(t)}getCachedEvents(t){let r=this.eventCache.get(t);return!r||r.length===0?[]:(this.cleanupCache(t),(this.eventCache.get(t)||[]).map(o=>o.data))}clearCachedEvents(t){this.eventCache.delete(t)}clearAllCachedEvents(){this.eventCache.clear()}getCacheStats(){let t=0,r=null,n=null;for(let[s,a]of this.eventCache.entries()){t+=a.length;for(let d of a)(r===null||d.timestamp<r)&&(r=d.timestamp),(n===null||d.timestamp>n)&&(n=d.timestamp)}let o=`${Math.round(t*200/1024)}KB`;return{totalEvents:t,eventTypes:this.eventCache.size,oldestEvent:r,newestEvent:n,memoryEstimate:o}}cleanupCache(t){let r=Date.now()-this.cacheTTL;if(t){let n=this.eventCache.get(t);if(n){let o=n.filter(s=>s.timestamp>r);o.length===0?this.eventCache.delete(t):this.eventCache.set(t,o)}}else for(let[n,o]of this.eventCache.entries()){let s=o.filter(a=>a.timestamp>r);s.length===0?this.eventCache.delete(n):this.eventCache.set(n,s)}}},qf=new Dt;var zf={user:null,userProfile:null,userSubscription:null,loading:!1,reauthenticateWithPassword:async()=>{},reauthenticateWithProvider:async()=>{},deleteAccount:async()=>{},setRememberMe:async()=>{},error:null,emailVerification:{status:"pending"},passwordResetPending:!1,getPartnerState:()=>"idle",setPartnerState:()=>{},partnerError:null,status:me.DEGRADED,hasRole:async()=>!1,hasTier:async()=>!1,hasFeature:async()=>!1,getCustomClaims:()=>({}),getCustomClaim:()=>null,signInWithEmail:async()=>null,createUserWithEmail:async()=>null,signInWithPartner:async()=>null,linkWithPartner:async()=>null,signInWithGoogleCredential:async()=>null,signOut:async()=>{},sendPasswordResetEmail:async()=>{},updatePassword:async()=>{},verifyPasswordResetCode:async()=>null,confirmPasswordReset:async()=>{},sendEmailVerification:async()=>{},getEmailVerificationStatus:async()=>({status:"pending"}),isEmailVerificationEnabled:async()=>!1,sendSignInLinkToEmail:async()=>{},signInWithEmailLink:async()=>null,isSignInWithEmailLink:()=>!1,getCurrentUser:async()=>null,isAuthenticated:!1,userRole:P.GUEST,userTier:fe.FREE,can:{navigate:e=>e===!1||typeof e=="object"&&!e.required,view:()=>!1,edit:()=>!1,delete:()=>!1,create:()=>!1,perform:()=>!1,has:()=>!1},isAvailable:!1},Xf={status:me.DEGRADED,error:null,loading:!1,checkout:async()=>({sessionId:"",sessionUrl:null,success:!1,error:"Billing not available - consent required"}),cancelSubscription:async()=>({success:!1,endsAt:""}),changePlan:async()=>({success:!1}),refreshStatus:async()=>{},openCustomerPortal:async()=>{},clearError:()=>{},isAvailable:!1};var Jf={status:me.DEGRADED,data:null,loading:!1,error:null,get:async()=>null,set:async()=>{},update:async()=>{},delete:async()=>{},add:async()=>"",query:async()=>[],subscribe:()=>()=>{},subscribeToCollection:()=>()=>{},invalidate:async()=>{},isAvailable:!1},Qf={status:me.DEGRADED,error:null,partners:{},connectedPartners:[],connect:async()=>{},disconnect:async()=>{},isConnected:()=>!1,getCredentials:()=>null,handleCallback:async()=>{},isAvailable:!1};var Gr=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function jr(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function We(e,t=""){if(Array.isArray(e))e.forEach((r,n)=>{let o=`${t}[${n}]`;if(typeof r=="string"&&jr(r)){if(!Gr.test(r))throw y(new Error(`Invalid date format for ${o}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`),{userMessage:`Invalid date format for ${o}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:o,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&We(r,o)});else if(typeof e=="object"&&e!==null)for(let[r,n]of Object.entries(e)){let o=t?`${t}.${r}`:r;if(typeof n=="string"&&jr(n)){if(!Gr.test(n))throw y(new Error(`Invalid date format for field "${o}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`),{userMessage:`Invalid date format for field "${o}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${n}"`,context:{field:o,value:n},severity:"error"})}else typeof n=="object"&&n!==null&&We(n,o)}}import*as Wr from"valibot";var _t={};function km(e){_t.uniqueConstraintValidator=e}async function Kr(e,t,r){let{uniqueFields:n=[],collection:o}=e.metadata;n.length!==0&&_t.uniqueConstraintValidator&&await Promise.all(n.map(async({field:s,errorMessage:a})=>{let d=t[s];if(d==null)return;if(await _t.uniqueConstraintValidator.checkDuplicate(o,s,d,r))throw y(new Error(a||`${s} must be unique`),{userMessage:a||`${s} must be unique`,context:{field:s}})}))}async function _m(e,t,r,n){Wr.parse(e,t),We(t),await Kr(e,t,n),e.metadata.customValidate&&await e.metadata.customValidate(t,r)}function Ji(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function Hm(e){if(!Ji(e)){let t=e,r=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw y(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return e.metadata.collection}var Nt=[{value:"draft",label:"crud:status.draft"},{value:"available",label:"crud:status.available"},{value:"deleted",label:"crud:status.deleted"}],jm="available",Km=["draft","deleted"],Ye=["id","createdAt","updatedAt","createdById","updatedById"],Qi=[...Ye,"status"];function Wm(e){return Qi.includes(e)}function Ym(e){return Ye.includes(e)}var O={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Nt]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0}},createdAt:{name:"createdAt",type:"timestamp",visibility:"technical",label:"crud:fields.createdAt",validation:{}},updatedAt:{name:"updatedAt",type:"timestamp",visibility:"technical",label:"crud:fields.updatedAt",validation:{}},createdById:{name:"createdById",type:"reference",visibility:"technical",label:"crud:fields.createdById",validation:{}},updatedById:{name:"updatedById",type:"reference",visibility:"technical",label:"crud:fields.updatedById",validation:{}}};var Zi=new Set(["__proto__","constructor","prototype"]);function es(e){for(let t of Object.keys(e.fields))if(Zi.has(t))throw y(new Error(`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`),{userMessage:`Field name '${t}' in entity '${e.name}' is a reserved JavaScript property and cannot be used as a field name.`,context:{entityName:e.name,fieldName:t,operation:"defineEntity"},severity:"error"})}function ts(e){let t=e.field.endsWith("Id")?e.field.slice(0,-2):e.field,r=e.collection||(t.endsWith("y")?t.slice(0,-1)+"ies":t+"s");return{name:e.field,label:`crud:fields.${e.field}`,type:"reference",visibility:"technical",editable:Ne.CREATE_ONLY,validation:{required:!0,reference:r}}}function rs(e,t){if(!t||t.length===0)return e.map(o=>({value:o.value,label:o.label}));let r=e.map(o=>({value:o.value,label:o.label})),n=new Set(e.map(o=>o.value));for(let o of t)n.has(o.value)||r.push(o);return r}function ns(e,t){if(!(!e.uniqueKeys||e.uniqueKeys.length===0))for(let r=0;r<e.uniqueKeys.length;r++){let n=e.uniqueKeys[r];if(!n)continue;if(!n.fields||n.fields.length===0)throw y(new Error(`uniqueKeys[${r}] for entity '${e.name}' must have at least one field`),{userMessage:`uniqueKeys[${r}] for entity '${e.name}' must have at least one field`,context:{entityName:e.name,uniqueKeyIndex:r},severity:"error"});let o=n.fields.filter(s=>!t.has(s));if(o.length>0)throw y(new Error(`uniqueKeys[${r}] for entity '${e.name}' references non-existent fields: ${o.join(", ")}`),{userMessage:`uniqueKeys[${r}] for entity '${e.name}' references non-existent fields: ${o.join(", ")}`,context:{entityName:e.name,uniqueKeyIndex:r,invalidFields:o},severity:"error"})}}function os(e){let{form:t,fields:r}=e,n=Object.keys(r);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw y(new Error(`Multi-step form for entity '${e.name}' must have at least one step`),{userMessage:`Multi-step form for entity '${e.name}' must have at least one step`,context:{entityName:e.name,operation:"validateFormConfig"},severity:"error"});let o=t.steps.flatMap(p=>p.fields),s=o.filter(p=>!n.includes(p));if(s.length>0)throw y(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${s.join(", ")}`,context:{entityName:e.name,invalidFields:s,operation:"validateFormConfig"},severity:"error"});let a=new Set(o);n.filter(p=>!a.has(p)).length>0}t.rules&&t.rules.forEach((o,s)=>{let d=(Array.isArray(o.condition)?o.condition.map(v=>v.field):[o.condition.field]).filter(v=>!n.includes(v));if(d.length>0)throw y(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${d.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent condition fields: ${d.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:d,operation:"validateFormConfig"},severity:"error"});let h=[...o.showFields||[],...o.hideFields||[],...o.disableFields||[],...o.enableFields||[]].filter(v=>!n.includes(v));if(h.length>0)throw y(new Error(`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`),{userMessage:`Dynamic form rule ${s} for entity '${e.name}' references non-existent affected fields: ${h.join(", ")}`,context:{entityName:e.name,ruleIndex:s,invalidFields:h,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([o,s])=>{if(s.dependsOn&&!n.includes(s.dependsOn.field))throw y(new Error(`Field '${o}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`),{userMessage:`Field '${o}' in entity '${e.name}' depends on non-existent field: ${s.dependsOn.field}`,context:{entityName:e.name,fieldName:o,dependsOnField:s.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function is(e){return e.form?{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0},...e.form}:{type:"single",behavior:{showProgress:!1,allowStepNavigation:!0,validateOnStepChange:!0,showStepNumbers:!0},layout:{columns:1,showLabels:!0,showHints:!0}}}function Zm(e){try{es(e),os(e);let t=is(e),r={...e.fields,...O,...e.fields.createdAt&&{createdAt:{...O.createdAt,...e.fields.createdAt,type:O.createdAt.type,visibility:O.createdAt.visibility}},...e.fields.updatedAt&&{updatedAt:{...O.updatedAt,...e.fields.updatedAt,type:O.updatedAt.type,visibility:O.updatedAt.visibility}},...e.fields.createdById&&{createdById:{...O.createdById,...e.fields.createdById,type:O.createdById.type,visibility:O.createdById.visibility}},...e.fields.updatedById&&{updatedById:{...O.updatedById,...e.fields.updatedById,type:O.updatedById.type,visibility:O.updatedById.visibility}},...e.fields.status&&{status:{...O.status,...e.fields.status,validation:{...O.status.validation,...e.fields.status.validation,options:rs(Nt,e.fields.status.validation?.options)}}},...e.scope&&{[e.scope.field]:ts(e.scope)}};if(e.listFields){let s=new Set(Object.keys(r)),a=e.listFields.filter(d=>!s.has(d));if(a.length>0)throw y(new Error(`Entity '${e.name}' defines listFields that do not exist: ${a.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${a.join(", ")}`,context:{entityName:e.name,invalidFields:a,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let s=new Set(Object.keys(r)),d=Ee(e).filter(p=>!s.has(p));if(d.length>0)throw y(new Error(`Entity '${e.name}' defines listCardFields that do not exist: ${d.join(", ")}`),{userMessage:`Entity '${e.name}' defines listCardFields that do not exist: ${d.join(", ")}`,context:{entityName:e.name,invalidFields:d,operation:"defineEntity"},severity:"error"})}if(e.uniqueKeys){let s=new Set(Object.keys(r));ns(e,s)}let n={...tt,...e.access||{}},o=e.namespace||`entity-${e.name.toLowerCase()}`;return{...e,form:t,fields:r,access:n,namespace:o,...e.search&&{search:e.search},...e.defaultSort&&{defaultSort:e.defaultSort}}}catch(t){throw y(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}import*as q from"valibot";function Ut(e,t){return!!(t.visibility==="hidden"||t.editable===Ne.GENERATED||Ye.includes(e))}function Oe(e,t){return Object.assign(e,{visibility:t})}function ne(e,t){let r=e;return r.metadata={collection:t.collection,entity:t.name,...t.uniqueKeys&&{uniqueKeys:t.uniqueKeys}},r}function ss(e){let t=xe(e);return Oe(t,e.visibility)}function Ft(e){let t=xe({...e,validation:{...e.validation,required:!1}});return Oe(t,e.visibility)}function ig(e){let t=e.fields,r={};for(let[U,F]of Object.entries(t))F.visibility!=="hidden"&&(r[U]=Ft(F));let n=ne(q.object(r),e),o={};for(let[U,F]of Object.entries(t))Ut(U,F)||(o[U]=ss(F));let s=ne(q.object(o),e),a={};for(let[U,F]of Object.entries(t))if(!Ut(U,F))if(U==="status"){let z=q.literal("draft");a[U]=Oe(z,F.visibility)}else a[U]=Ft(F);let d=ne(q.object(a),e),p={};for(let[U,F]of Object.entries(t))Ut(U,F)||(p[U]=Ft(F));p.id=Oe(xe(O.id),"technical");let h=ne(q.object(p),e),v;if(e.listFields&&e.listFields.length>0){let U=["id","status"],F=[...new Set([...U,...e.listFields])];v={};for(let z of F){let pe=r[z];pe&&(v[z]=pe)}}else v=r;let _=ne(q.object(v),e),G,Mt=Ee(e);if(Mt.length>0){let U=["id","status"],F=[...new Set([...U,...Mt])];G={};for(let z of F){let pe=r[z];pe&&(G[z]=pe)}}else G=r;let Yr=ne(q.object(G),e),zr=ne(q.object({id:Oe(xe(O.id),"technical")}),e);return{create:s,draft:d,update:h,get:n,list:_,listCard:Yr,delete:zr}}function ag(e,t,r=1,n=!1){let o=[];if(n)for(let s=t;s>=e;s-=r)o.push({value:String(s),label:String(s)});else for(let s=e;s<=t;s+=r)o.push({value:String(s),label:String(s)});return o}var oe=new Map;function ug(e,t){oe.has(e),oe.set(e,t)}function cg(e){oe.delete(e)}function dg(e){let t=oe.get(e);return t?t():null}function pg(e){return oe.has(e)}function fg(){return Array.from(oe.keys())}function mg(){oe.clear()}import*as I from"valibot";var as=I.record(I.string(),I.unknown()),ls=I.object({id:I.string(),patch:I.record(I.string(),I.unknown())}),us=I.string(),hg=I.object({inserts:I.optional(I.array(as)),updates:I.optional(I.array(ls)),deletes:I.optional(I.array(us))}),vg=I.object({insertedIds:I.array(I.string()),updatedIds:I.array(I.string()),deletedIds:I.array(I.string())});function yg(e){let t=new Set((e.updates??[]).map(a=>a.id)),r=e.deletes??[],n=[];for(let a of r)t.has(a)&&n.push(a);if(n.length>0)return{collisions:n,where:"updates-deletes"};let o=e.inserts??[],s=[];for(let a of o)typeof a.id=="string"&&t.has(a.id)&&s.push(a.id);return s.length>0?{collisions:s,where:"inserts-updates"}:{collisions:[],where:null}}import*as b from"valibot";var Tg=b.pipe(b.string(),b.check(e=>e.startsWith("/proxy/")||e.startsWith("data:image/"),"Image URL must be box-proxied (/proxy/...) or an inline data:image URI.")),cs=b.picklist(["ephemeral","session","persistent"]),ds=b.object({title:b.optional(b.string()),pinnable:b.optional(b.boolean()),preferredHeight:b.optional(b.pipe(b.number(),b.minValue(0)))}),ps=b.object({id:b.pipe(b.string(),b.minLength(1)),kind:b.pipe(b.string(),b.minLength(1)),lifetime:b.optional(cs,"ephemeral"),metadata:b.optional(ds),payload:b.unknown()}),fs=b.object({widgetId:b.pipe(b.string(),b.minLength(1)),action:b.pipe(b.string(),b.minLength(1)),payload:b.unknown()}),de=new Map;function xg(e){if(de.has(e.kind))throw new Error(`[canvas] Widget kind "${e.kind}" already registered.`);de.set(e.kind,e)}function Ig(e){return de.get(e)}function Cg(){return Array.from(de.values())}function Ag(e,t){let r=b.safeParse(ps,e);if(!r.success)return{ok:!1,reason:`Invalid canvas block envelope: ${ze(r.issues)}`};let n=de.get(r.output.kind);if(!n)return{ok:!1,reason:`Unknown widget kind: "${r.output.kind}"`};let o=b.safeParse(n.schema,r.output.payload);if(!o.success)return{ok:!1,reason:`Payload rejected by "${r.output.kind}" schema: ${ze(o.issues)}`};if(t?.caller!==void 0){let a=t.caller.access;if(!ms(n.surface,a))return{ok:!1,reason:`surface_forbidden: widget "${r.output.kind}" surface=${n.surface} not reachable by caller access=${a===null?"null":a}`}}return{ok:!0,value:{...r.output,payload:o.output},widget:n}}function ms(e,t){return e==="meta"?!0:e==="household"||e==="private"?t==="admin"||t==="member":!1}function Rg(e,t){let r=b.safeParse(fs,e);if(!r.success)return{ok:!1,reason:`Invalid canvas event envelope: ${ze(r.issues)}`};let n=de.get(t);if(!n)return{ok:!1,reason:`Unknown widget kind: "${t}"`};let o=n.actions[r.output.action];if(!o)return{ok:!1,reason:`Widget "${t}" has no action "${r.output.action}"`};let s=b.safeParse(o,r.output.payload);return s.success?{ok:!0,value:{...r.output,payload:s.output},widget:n}:{ok:!1,reason:`Payload rejected by "${t}.${r.output.action}" schema: ${ze(s.issues)}`}}function ze(e){return e.map(t=>{let r=t.path?.map(n=>String(n.key)).join(".")??"";return r?`${r}: ${t.message}`:t.message}).join("; ")}export{Na as AGGREGATE_FILTER_OPERATORS,_a as AGGREGATE_OPERATIONS,sn as AIChatRequestSchema,ln as AIChatResponseSchema,Vt as AIMessageSchema,Is as AIProviderConfigSchema,on as AIToolCallSchema,nn as AIToolDefinitionSchema,an as AIUsageSchema,ys as AI_ERROR_CODES,hs as AI_MODELS,$ as AI_PROVIDERS,De as AI_ROLES,bs as AI_TIERS,Ss as AI_TOKEN_PRICING,vl as AUTH_EVENTS,he as AUTH_PARTNERS,fa as AUTH_PARTNER_STATE,$e as AuthHardening,Yt as AuthUserSchema,Ye as BACKEND_GENERATED_FIELD_NAMES,bl as BILLING_EVENTS,hn as BREAKPOINT_RANGES,nt as BREAKPOINT_THRESHOLDS,Jt as BulkAcrossCycleError,Xt as BulkCollisionError,us as BulkDeleteIdSchema,as as BulkInsertSchema,Qt as BulkNotImplementedError,hg as BulkRequestSchema,vg as BulkResponseSchema,ls as BulkUpdateSchema,$t as COMMON_TIER_CONFIGS,N as CONFIDENCE_LEVELS,rr as CONSENT_CATEGORY,k as CONTEXTS,J as CRUD_OPERATORS,ct as CURRENCY_MAP,ps as CanvasBlockSchema,fs as CanvasEventSchema,cs as CanvasLifetimeSchema,ds as CanvasWidgetMetadataSchema,Wt as CheckoutSessionMetadataSchema,se as ConditionBuilder,Ht as CreateCheckoutSessionRequestSchema,qt as CreateCheckoutSessionResponseSchema,zt as CustomClaimsSchema,vs as DEFAULT_AI_CONFIG,Es as DEFAULT_AI_MARKUP,Go as DEFAULT_CRUD_TIMEOUT,tt as DEFAULT_ENTITY_ACCESS,Q as DEFAULT_ERROR_MESSAGES,yn as DEFAULT_LAYOUT_PRESET,Nt as DEFAULT_STATUS_OPTIONS,jm as DEFAULT_STATUS_VALUE,$s as DEFAULT_SUBSCRIPTION,qo as DEFAULT_UPLOAD_TIMEOUT,xu as DENSITY,w as DoNotDevError,Ne as EDITABLE,nl as EMAIL_ERROR_CODES,rl as EMAIL_PROVIDERS,pa as EMAIL_VERIFICATION_STATUS,Ue as ENTITY_HOOK_ERRORS,X as ENVIRONMENTS,ge as ERROR_CODES,pl as ERROR_SEVERITY,fl as ERROR_SOURCE,Zt as EntityHookError,Qe as FEATURES,Iu as FEATURE_CONSENT_MATRIX,me as FEATURE_STATUS,Pa as FIELD_TYPES,rt as FIREBASE_ERROR_MAP,bn as FOOTER_MODE,er as GITHUB_PERMISSION_LEVELS,Km as HIDDEN_STATUSES,En as LAYOUT_PRESET,ka as LIST_SCHEMA_TYPE,Sl as OAUTH_EVENTS,it as OAUTH_PARTNERS,wa as ORDER_DIRECTION,cu as PARTNER_ICONS,xl as PAYLOAD_EVENTS,Ze as PERMISSIONS,C as PLATFORMS,Ia as PWA_ASSET_TYPES,xa as PWA_DISPLAY_MODES,dn as ProductDeclarationSchema,Xs as ProductDeclarationsSchema,Tg as ProxiedImageUrlSchema,Ca as ROUTE_SOURCES,Ta as STORAGE_SCOPES,Sa as STORAGE_TYPES,Cl as STRIPE_EVENTS,_e as STRIPE_MODES,Bs as SUBSCRIPTION_DURATIONS,ie as SUBSCRIPTION_STATUS,fe as SUBSCRIPTION_TIERS,mn as SendEmailRequestSchema,gn as SendEmailResponseSchema,mr as ServerUtils,gt as SingletonManager,fn as StripeBackConfigSchema,pn as StripeFrontConfigSchema,un as StripePaymentSchema,cn as StripeSubscriptionSchema,jt as SubscriptionClaimsSchema,Gt as SubscriptionDataSchema,Qi as TECHNICAL_FIELD_NAMES,P as USER_ROLES,et as UserSubscriptionSchema,Ra as VISIBILITY,Kt as WebhookEventSchema,Se as addMonths,yt as addYears,ii as addressSchema,ai as arraySchema,O as baseFields,gr as booleanSchema,Wo as calculateSubscriptionEndDate,lt as captureErrorToSentry,eu as checkGitHubAccessSchema,Eo as clearGlobalSingleton,Gd as clearSchemaGenerators,mg as clearScopeProviders,ve as commonErrorCodeMappings,dt as compactToISOString,Io as configureProviders,To as createAsyncSingleton,Vs as createDefaultSubscriptionClaims,ma as createDefaultUserProfile,$a as createEntitySchema,H as createErrorHandler,Yn as createMetadata,xo as createMethodProxy,ig as createSchemas,be as createSingleton,So as createSingletonWithParams,le as dateSchema,Zm as defineEntity,Ga as deleteEntitySchema,yg as detectBulkCollisions,st as detectErrorSource,nu as disconnectOAuthSchema,Zo as emailSchema,Vd as enhanceSchema,Hn as ensureSpreadable,ee as evaluateCondition,Mo as evaluateFieldConditions,tu as exchangeTokenSchema,hr as fileSchema,vr as filesSchema,Do as filterVisibleFields,Xn as formatCurrency,sr as formatDate,no as formatRelativeTime,fi as gdprConsentSchema,lr as generateCodeChallenge,ar as generateCodeVerifier,uo as generateFirestoreRuleCondition,po as generatePKCEPair,Ho as generateUUID,oi as geopointSchema,vn as getBreakpointFromWidth,Bl as getBreakpointUtils,Hm as getCollectionName,Bo as getConditionDependencies,ou as getConnectionsSchema,ir as getCurrencyLocale,zn as getCurrencySymbol,Zn as getCurrentTimestamp,Ha as getEntitySchema,ht as getGlobalSingleton,Ee as getListCardFieldNames,Co as getProvider,qd as getRegisteredSchemaTypes,fg as getRegisteredScopeProviders,yo as getRoleFromClaims,xe as getSchemaType,dg as getScopeValue,vt as getVisibleFields,ro as getWeekFromISOString,Ig as getWidget,Sn as githubPermissionSchema,ot as githubRepoConfigSchema,Ql as grantGitHubAccessSchema,y as handleError,Hd as hasCustomSchemaGenerator,Ji as hasMetadata,Ao as hasProvider,_o as hasRestrictedVisibility,Le as hasRoleAccess,pg as hasScopeProvider,bo as hasTierAccess,di as ibanSchema,kn as isAuthPartnerId,Ym as isBackendGeneratedField,Ll as isBreakpoint,pt as isCompactDateString,pr as isFieldVisible,Wm as isFrameworkField,Pn as isOAuthPartnerId,fo as isPKCESupported,Jn as isoToCompactString,vo as lazyImport,ja as listEntitiesSchema,Cg as listWidgets,si as mapSchema,Z as mapToDoNotDevError,co as maybeTranslate,li as multiselectSchema,yr as neverSchema,Qn as normalizeToISOString,ae as numberSchema,Ns as overrideFeatures,Ls as overridePaymentModes,Us as overridePermissions,Ms as overrideSubscriptionStatus,_s as overrideSubscriptionTiers,Ds as overrideUserRoles,ft as parseDate,io as parseDateToNoonUTC,Yo as parseISODate,Qo as parseServerCookie,ei as passwordSchema,ri as pictureSchema,ni as picturesSchema,mi as priceSchema,ag as rangeOptions,ui as referenceSchema,ru as refreshTokenSchema,E as registerSchemaGenerator,ug as registerScopeProvider,km as registerUniqueConstraintValidator,xg as registerWidget,Ro as resetProviders,Zl as revokeGitHubAccessSchema,$n as safeValidate,$o as sanitizeHref,bt as selectSchema,Fn as showNotification,Et as stringSchema,pi as switchSchema,ci as telSchema,He as textSchema,to as timestampToISOString,so as toDateOnly,eo as toISOString,Gn as translateArray,Kn as translateArrayRange,Wn as translateArrayWithIndices,jn as translateObjectArray,cg as unregisterScopeProvider,qa as updateEntitySchema,wo as updateMetadata,ti as urlSchema,Cs as validateAIChatRequest,As as validateAIChatResponse,pu as validateAuthPartners,ca as validateAuthSchemas,aa as validateAuthUser,Zs as validateBillingSchemas,Ag as validateBlock,zs as validateCheckoutSessionMetadata,go as validateCodeChallenge,mo as validateCodeVerifier,Gs as validateCreateCheckoutSessionRequest,js as validateCreateCheckoutSessionResponse,ua as validateCustomClaims,We as validateDates,_m as validateDocument,Jo as validateEnvVar,Rg as validateEvent,Xo as validateMetadata,fu as validateOAuthPartners,il as validateSendEmailRequest,sl as validateSendEmailResponse,Qs as validateStripeBackConfig,Js as validateStripeFrontConfig,Ws as validateSubscriptionClaims,Ks as validateSubscriptionData,Kr as validateUniqueFields,zo as validateUrl,la as validateUserSubscription,Ys as validateWebhookEvent,Vn as validateWithSchema,Lo as when,Un as withErrorHandling,ho as withGracefulDegradation,jo as withTimeout,Bn as wrapAuthError,Mn as wrapCrudError,Ln as wrapStorageError};
2
2
  /*! Bundled license information:
3
3
 
4
4
  react/cjs/react.production.js: