@donotdev/core 0.0.14 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/functions/index.js +8 -8
- package/package.json +1 -1
- package/server.d.ts +462 -4
- package/server.js +1 -1
package/functions/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var Y=(n,e)=>()=>(n&&(e=n(n=0)),e);function V(n,e=null){let t=R[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(s=>`${e}/${s}`)}:t}function Z(n){return q[n]||q.base}var U,R,q,K=Y(()=>{"use strict";P();U={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},R={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json"],framework:{eager:[`${U.SOURCE_EAGER}/*_*.json`],lazy:[`${U.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},q={base:{absolute:!0,onlyFiles:!0,ignore:R.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...R.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...R.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:R.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:R.globalIgnore}}});import{Buffer as w}from"node:buffer";import{createRequire as pe}from"node:module";import{dirname as fe,resolve as _e}from"node:path";import y from"node:process";import{fileURLToPath as de}from"node:url";var he,F,A,P=Y(()=>{"use strict";he=pe(import.meta.url),F=de(import.meta.url),A=fe(F);typeof globalThis<"u"&&(globalThis.require=he,globalThis.__filename=F,globalThis.__dirname=A,globalThis.Buffer=w,globalThis.process=y,typeof global>"u"&&(globalThis.global=globalThis))});P();P();P();import W from"node:fs";import k from"node:path";import{fileURLToPath as me}from"node:url";var ge=me(import.meta.url),Te=k.dirname(ge);function X(){let n=y.cwd(),e=10;for(let t=0;t<e;t++){let s=k.join(n,"package.json");if(W.existsSync(s))try{let o=JSON.parse(W.readFileSync(s,"utf8")),r=o.workspaces&&Array.isArray(o.workspaces);if(r&&o.workspaces.some(c=>c==="packages/**"||c.startsWith("packages/"))&&(W.existsSync(k.join(n,"packages","core"))||W.existsSync(k.join(n,"packages","functions"))))return{type:"dndev",root:n};if(r&&o.workspaces.some(c=>c.includes("dndev/packages"))){let f=o.workspaces.find(d=>d.includes("dndev/packages")).replace(/\/packages.*$/,""),g=k.resolve(n,f);if(W.existsSync(k.join(g,"packages","core")))return{type:"dndev",root:g}}}catch{}let i=k.dirname(n);if(i===n)break;n=i}return{type:"npm",root:y.cwd()}}function ve(n){return n.type==="dndev"?n.root:null}function Q(n){let e={};if(n.type==="dndev"){let t=ve(n);t&&(e["@donotdev/types"]=k.join(t,"packages","core","types","src"),e["@donotdev/functions"]=k.join(t,"packages","functions","src"),e["@donotdev/utils"]=k.join(t,"packages","core","utils","src"),e["@donotdev/schemas"]=k.join(t,"packages","core","schemas","src"),e["@donotdev/core"]=k.join(t,"packages","core"))}return e}P();import{createRequire as ye}from"node:module";import{resolve as M,join as S,dirname as E,relative as J,normalize as Pe,sep as ee,extname as be}from"node:path";import{fileURLToPath as ke}from"node:url";import*as p from"node:fs";K();import we from"fast-glob";var _={getGlobOptionsFor:Z||void 0,SCAN_PATTERNS:R||void 0,getPatternsFor:V||void 0,I18N_PATHS:U||void 0},v={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};function te(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var re={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},B=class n{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=y.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${y.cwd()}`)}this._appRoot=null,n._instance=this}normalizePath(e){if(!e)return"";try{return Pe(e).split(ee).join("/")}catch{return String(e).split(ee).join("/")}}getRelativePath(e){let t=this.getAppRoot(),s=J(t,e);return this.normalizePath(s)}getBasename(e){if(!e)return"";let s=this.normalizePath(e).split("/");return s[s.length-1]||""}getDirname(e){return e?this.normalizePath(E(e)):""}resolvePackage(e,t=null){try{let s=t||this.getAppRoot(),o=ye(S(s,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let s=this.resolvePackage(`${e}/package.json`,t);if(s)return this.getDirname(s);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let r=e.replace("@donotdev/",""),a=this.resolveRepoPath(`packages/${r}`);if(this.pathExists(a))return a;if(["auth","billing","crud","oauth"].includes(r)){let l=this.resolveRepoPath(`packages/features/${r}`);if(this.pathExists(l))return l}if(r==="firebase"){let l=this.resolveRepoPath(`packages/providers/${r}`);if(this.pathExists(l))return l}}let i=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(i))return i;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),s=M(t,e);return this.normalizePath(s)}resolveRepoPath(e){let t=this.getRepoRoot(),s=this.normalizePath(e),i=M(t,s);return this.normalizePath(i)}resolvePath(e,t){let s=this.normalizePath(t),i=this.normalizePath(e),o=M(s,i);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=p.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:be(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:s="auto",encoding:i="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return await p.promises.readFile(e);let r=await p.promises.readFile(e,i),a=this.stripBom(r);return o==="json"?JSON.parse(a):a}catch(r){return this.options.debug&&v.warn(`Failed to read file: ${e}`,r),null}}readSync(e,t={}){let{format:s="auto",encoding:i="utf8"}=t,o=this._detectFormat(e,s);try{if(o==="buffer")return p.readFileSync(e);let r=p.readFileSync(e,i),a=this.stripBom(r);return o==="json"?JSON.parse(a):a}catch(r){return this.options.debug&&v.warn(`Failed to read file: ${e}`,r),null}}async write(e,t,s={}){let{format:i="auto",overwrite:o=!1,dryRun:r=!1,verbose:a=!1}=s,l=this.normalizePath(e),h=this.normalizePath(E(l)),c=this.pathExists(l);if(c&&!o)return a&&v.info(`Skipping existing file: ${l}`),!1;if(r)return v.info(`[DRY RUN] Would write file: ${l}`),!0;try{await p.promises.mkdir(h,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let f=this._detectFormat(e,i),g;w.isBuffer(t)?g=t:f==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return await te(async()=>(w.isBuffer(g)?await p.promises.writeFile(l,g):await p.promises.writeFile(l,g,"utf8"),a&&v.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,s={}){let{format:i="auto",overwrite:o=!1,dryRun:r=!1,verbose:a=!1}=s,l=this.normalizePath(e),h=this.normalizePath(E(l)),c=this.pathExists(l);if(c&&!o)return a&&v.info(`Skipping existing file: ${l}`),!1;if(r)return v.info(`[DRY RUN] Would write file: ${l}`),!0;try{p.mkdirSync(h,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let f=this._detectFormat(e,i),g;w.isBuffer(t)?g=t:f==="json"&&typeof t=="object"?g=JSON.stringify(t,null,2):g=String(t);try{return w.isBuffer(g)?p.writeFileSync(l,g):p.writeFileSync(l,g,"utf8"),a&&v.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(d){throw new Error(`Failed to write file: ${l}: ${d instanceof Error?d.message:String(d)}`)}}async copy(e,t,s={}){let{overwrite:i=!1,dryRun:o=!1,verbose:r=!1}=s,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!i)return r&&v.info(`Skipping existing file: ${a}`),!1;if(o)return v.info(`[DRY RUN] Would copy file: ${a}`),!0;let h=this.normalizePath(E(a));try{await p.promises.mkdir(h,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await te(async()=>(await p.promises.copyFile(e,a),r&&v.info(`${l?"Updated":"Created"} file: ${a}`),!0),`Failed to copy file from ${e} to ${a}`)}catch{return!1}}copySync(e,t,s={}){let{overwrite:i=!1,dryRun:o=!1,verbose:r=!1}=s,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!i)return r&&v.info(`Skipping existing file: ${a}`),!1;if(o)return v.info(`[DRY RUN] Would copy file: ${a}`),!0;let h=this.normalizePath(E(a));try{p.mkdirSync(h,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return p.copyFileSync(e,a),r&&v.info(`${l?"Updated":"Created"} file: ${a}`),!0}catch{return!1}}pathExists(e,t=!1){try{return p.existsSync(e)}catch(s){return t||v.error(`Error checking path existence: ${e}`,s),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return p.existsSync(t)||p.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return p.readdirSync(e,t)}catch(s){return this.options.debug&&v.warn(`Failed to read directory: ${e}`,s),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return p.statSync(e)}catch(t){return this.options.debug&&v.warn(`Failed to stat file: ${e}`,t),null}}lstatSync(e){try{return p.lstatSync(e)}catch(t){return this.options.debug&&v.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await p.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{p.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await p.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){p.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return p.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||y.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=S(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(M(e)),s=this.getAppRoot(),i=J(s,t),o=this.normalizePath(i);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,s={}){let i=this.normalizePath(S(e,t)),o=this.getAppRoot(),r=this.normalizePath(o),a=i.startsWith(r)?i.slice(r.length+1):i,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:_.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([a],{...l,...s})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=_.I18N_PATHS;if(!t)return null;let s=e.replace(t.SOURCE_ROOT+"/",""),i=this.resolveFrameworkPackage("@donotdev/core");if(!i)return null;let o=this.normalizePath(S(i,t.PUBLISHED_ROOT,s)),r=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(r),o}async _globWithNormalization(e,t){return(await we(e,t)).map(i=>{let o=typeof i=="string"?i:i.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let s=[...e.framework,...e.consumer];for(let c of s)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let i=this.getAppRoot(),o=_.getGlobOptionsFor?_.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},r=this.normalizePath(i),a=e.framework.map(c=>{let f=this.normalizePath(c);return f.startsWith(r)?f.slice(r.length+1):f}),l=e.consumer.map(c=>{let f=this.normalizePath(c);return f.startsWith(r)?f.slice(r.length+1):f}),h={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:i};try{let c=a.length>0?await this._globWithNormalization(a,h):[],f=await this._globWithNormalization(l,h);return{frameworkFiles:c,consumerFiles:f}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!_.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),s=this.getRepoRoot();if(e==="i18n"&&(!t||t===s))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${s}). Ensure configResolved hook has run before discovery.`);let i=_.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=i,h={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return h.all=[...h.eager,...h.lazy,...h.framework.eager,...h.framework.lazy],h}let r=i,a={framework:o?(r.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(r.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return a.all=[...a.consumer,...a.framework],a}getEmptyModulePath(e=!1){if(e)return"@donotdev/core/empty";let t=this.resolvePackage("@donotdev/core/empty");if(t)return t;let s=E(ke(import.meta.url));return this.normalizePath(S(s,"../empty.js"))}_findRepoRoot(e){let t=this.normalizePath(e),s=0,i=this.options.maxLevels;for(;s<i;){let o=this.normalizePath(S(t,re.TOOLING)),r=this.normalizePath(S(t,re.CORE));if(this.pathExists(o)&&this.pathExists(r))return t;let a=S(t,"apps");if(this.pathExists(a)&&this.statSync(a)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(S(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(E(t))===t)return t;let h=this.normalizePath(E(t));if(h===t)break;t=h,s++}return this.normalizePath(e)}};function se(n={}){let{entry:e="src/index.ts",outDir:t="lib",minify:s=!1,sourcemap:i=!0,platform:o="firebase",workspace:r,bundleWorkspaceDeps:a=!1,importFramework:l=!1,external:h=!1,...c}=n,f=B.getInstance(),g=Q(r),d={entryPoints:[e],bundle:!0,platform:"node",target:"node20",format:"esm",outdir:t,outExtension:{".js":".js"},minify:s,sourcemap:i,metafile:!0,logLevel:"info",loader:{".ts":"ts",".tsx":"tsx",".css":"empty"},keepNames:!0,treeShaking:!0,...c};a&&Object.keys(g).length>0&&(d.alias=Object.fromEntries(Object.entries(g).map(([b,u])=>[b,f.normalizePath(u)]))),d.mainFields=["module","main"],d.conditions=["import","module","node"];let ce=["fs","path","crypto","util","stream","events","buffer","url","querystring","http","https","zlib","os","child_process","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","perf_hooks","async_hooks"],G=[];if(a)try{let b=r?.root||y.cwd(),u=y.cwd(),m=10;for(let x=0;x<m;x++){let H=f.normalizePath(`${u}/package.json`);if(f.pathExists(H)){let $=f.readSync(H,{format:"json"});if($&&Array.isArray($.workspaces)){b=f.normalizePath(u);for(let z of $.workspaces)z==="apps/*"||z==="functions"||!z.includes("*")&&!z.includes("/")&&G.push(z);break}}let L=f.getDirname(u);if(L===u)break;u=L}}catch{}let le={name:"external-node-modules",setup(b){b.onResolve({filter:/^firebase($|\/)/},u=>{if(u.path==="firebase-admin"||u.path.startsWith("firebase-admin/")||u.path==="firebase-functions"||u.path.startsWith("firebase-functions/"))return null;let m;if(r?.type==="dndev"&&r.root)m=f.normalizePath(`${r.root}/packages/core/config/functions/firebase-stub.js`);else{let x=import.meta.url,L=new URL(x).pathname.replace(/^\/([A-Z]:)/i,"$1"),$=f.getDirname(L);m=f.normalizePath(`${$}/firebase-stub.js`)}return{path:m}}),b.onResolve({filter:/.*/},u=>{if(u.kind==="entry-point")return null;if(u.path.match(/@donotdev\/functions\/.+/)&&a&&r?.type==="dndev"){let m=u.path.replace("@donotdev/functions/","");return{path:f.normalizePath(`${r.root}/packages/functions/src/${m}/index.ts`)}}if(u.path==="@donotdev/utils")return r?.type==="dndev"?{path:f.normalizePath(`${r.root}/packages/core/utils/src/server/index.ts`)}:b.resolve("@donotdev/utils/server",{kind:u.kind,resolveDir:u.resolveDir});if(u.path.match(/@donotdev\/utils\/.+/)&&r?.type==="dndev"){let m=u.path.replace("@donotdev/utils/","");return{path:f.normalizePath(`${r.root}/packages/core/utils/src/${m}/index.ts`)}}if(u.path==="@donotdev/schemas")return r?.type==="dndev"?{path:f.normalizePath(`${r.root}/packages/core/schemas/src/server/index.ts`)}:b.resolve("@donotdev/schemas/server",{kind:u.kind,resolveDir:u.resolveDir});if(u.path.match(/@donotdev\/schemas\/.+/)&&r?.type==="dndev"){let m=u.path.replace("@donotdev/schemas/","");return{path:f.normalizePath(`${r.root}/packages/core/schemas/src/${m}/index.ts`)}}if(u.path==="@donotdev/core")return r?.type==="dndev"?{path:f.normalizePath(`${r.root}/packages/core/server.ts`)}:b.resolve("@donotdev/core/server",{kind:u.kind,resolveDir:u.resolveDir});if(u.path.match(/@donotdev\/core\/.+/)&&a&&r?.type==="dndev"){let m=u.path.replace("@donotdev/core/","");return{path:f.normalizePath(`${r.root}/packages/core/${m}.ts`)}}if(u.path==="firebase-admin"||u.path.startsWith("firebase-admin/")||u.path==="firebase-functions"||u.path.startsWith("firebase-functions/"))return{path:u.path,external:!0};if(u.path.match(/@donotdev\/core\/.+/)&&a&&r?.type==="dndev"){let m=u.path.replace("@donotdev/core/","");return{path:f.normalizePath(`${r.root}/packages/core/${m}.ts`)}}if(u.path.startsWith("@donotdev/")||u.path==="valibot"||u.path.startsWith("valibot/"))return null;if(G.length>0){let m=u.path.split("/")[0];if(G.includes(m))return null}return u.path.startsWith(".")||u.path.startsWith("/")?null:{path:u.path,external:!0}})}};if(d.external=[...ce,"firebase-admin","firebase-functions"],d.plugins=[le,...d.plugins||[]],d.define={"process.env.NODE_ENV":JSON.stringify(y.env.NODE_ENV||"production"),...d.define||{}},l&&r.type==="dndev"){let b=r.root,u=f.normalizePath(`${b}/functions/lib`);d.alias={...d.alias,"@donotdev/functions":u}}return o==="framework"&&(d.entryPoints={"firebase/index":"src/firebase/index.ts","vercel/api/index":"src/vercel/api/index.ts","shared/index":"src/shared/index.ts"}),d}P();var oe=["create","get","list","listCard","update","delete"];function ne(n,e=0){let t=" ".repeat(e),s="";for(let[i,o]of Object.entries(n))if(o!=null)if(typeof o=="object"&&!Array.isArray(o))Object.keys(o).length===0?s+=`${t}${i}: {}
|
|
2
|
-
`:
|
|
3
|
-
${ne(o,e+1)}`;else if(Array.isArray(o))if(o.length===0)
|
|
4
|
-
`;else{
|
|
5
|
-
`;for(let
|
|
6
|
-
`}else
|
|
7
|
-
`;return
|
|
1
|
+
var Y=(n,e)=>()=>(n&&(e=n(n=0)),e);function V(n,e=null){let t=R[n];if(!t)throw new Error(`Unknown pattern type: ${n}`);return e&&t.framework?{...t,framework:t.framework.map(r=>`${e}/${r}`)}:t}function Z(n){return q[n]||q.base}var U,R,q,K=Y(()=>{"use strict";P();U={SOURCE_ROOT:"packages/core/i18n",SOURCE_LOCALES:"packages/core/i18n/locales",SOURCE_EAGER:"packages/core/i18n/locales/eager",SOURCE_LAZY:"packages/core/i18n/locales/lazy",PUBLISHED_ROOT:"i18n",PUBLISHED_LOCALES:"i18n/locales",PUBLISHED_EAGER:"i18n/locales/eager",PUBLISHED_LAZY:"i18n/locales/lazy"},R={routes:{consumer:["src/**/*Page.tsx","src/pages/**/*Page.tsx"],exclude:["**/node_modules/**","**/dist/**","**/build/**","**/*.test.tsx","**/*.stories.tsx"],extensions:[".tsx"]},css:{consumer:["src/**/*.css"],themes:["src/**/*.css"],extensions:[".css",".scss",".sass"],framework:["packages/ui/src/**/*.css","packages/core/components/src/**/*.css","packages/core/templates/src/**/*.css"]},i18n:{eager:["src/locales/*_*.json"],lazy:["src/**/locales/*_*.json","!src/locales/*_*.json"],framework:{eager:[`${U.SOURCE_EAGER}/*_*.json`],lazy:[`${U.SOURCE_LAZY}/*_*.json`]},extensions:[".json"]},assets:{consumer:["public/**/*"],fallback:["manifest.json"],modern:["logo.svg","favicon.svg","apple-touch-icon.png","android-chrome-192x192.png","android-chrome-512x512.png"],patterns:["favicon.svg","favicon.ico","favicon-*.png","logo.svg","logo.png","logo.webp","logo.avif","apple-touch-icon*.png","android-chrome-*.png","manifest.json"],fonts:["fonts/**/*.woff2","fonts/**/*.woff","fonts/**/*.ttf"],framework:["packages/ui/assets/**/*"]},pwa:{consumer:["public/manifest.json","public/service-worker.js","public/sw.js","public/icon-192x192.png","public/icon-512x512.png","public/favicon.ico","public/favicon.svg","public/apple-touch-icon.png","public/logo.svg"],exclude:["**/node_modules/**","**/dist/**","**/build/**"],extensions:[".json",".js",".png",".svg",".ico"],framework:["packages/ui/assets/**/*"]},globalIgnore:["**/node_modules/**","**/dist/**","**/build/**","**/.git/**","**/coverage/**","**/test/**"]},q={base:{absolute:!0,onlyFiles:!0,ignore:R.globalIgnore},css:{absolute:!0,onlyFiles:!0,ignore:[...R.globalIgnore,"**/*.test.css"]},routes:{absolute:!0,onlyFiles:!0,ignore:[...R.globalIgnore,"**/*.test.tsx","**/*.stories.tsx"]},i18n:{absolute:!0,onlyFiles:!0,ignore:R.globalIgnore},assets:{absolute:!0,onlyFiles:!0,ignore:R.globalIgnore}}});import{Buffer as w}from"node:buffer";import{createRequire as pe}from"node:module";import{dirname as fe,resolve as _e}from"node:path";import y from"node:process";import{fileURLToPath as de}from"node:url";var he,F,A,P=Y(()=>{"use strict";he=pe(import.meta.url),F=de(import.meta.url),A=fe(F);typeof globalThis<"u"&&(globalThis.require=he,globalThis.__filename=F,globalThis.__dirname=A,globalThis.Buffer=w,globalThis.process=y,typeof global>"u"&&(globalThis.global=globalThis))});P();P();P();import W from"node:fs";import b from"node:path";import{fileURLToPath as me}from"node:url";var ge=me(import.meta.url),Te=b.dirname(ge);function X(){let n=y.cwd(),e=10;for(let t=0;t<e;t++){let r=b.join(n,"package.json");if(W.existsSync(r))try{let o=JSON.parse(W.readFileSync(r,"utf8")),s=o.workspaces&&Array.isArray(o.workspaces);if(s&&o.workspaces.some(c=>c==="packages/**"||c.startsWith("packages/"))&&(W.existsSync(b.join(n,"packages","core"))||W.existsSync(b.join(n,"packages","functions"))))return{type:"dndev",root:n};if(s&&o.workspaces.some(c=>c.includes("dndev/packages"))){let f=o.workspaces.find(d=>d.includes("dndev/packages")).replace(/\/packages.*$/,""),m=b.resolve(n,f);if(W.existsSync(b.join(m,"packages","core")))return{type:"dndev",root:m}}}catch{}let i=b.dirname(n);if(i===n)break;n=i}return{type:"npm",root:y.cwd()}}function ve(n){return n.type==="dndev"?n.root:null}function Q(n){let e={};if(n.type==="dndev"){let t=ve(n);t&&(e["@donotdev/types"]=b.join(t,"packages","core","types","src"),e["@donotdev/functions"]=b.join(t,"packages","functions","src"),e["@donotdev/utils"]=b.join(t,"packages","core","utils","src"),e["@donotdev/schemas"]=b.join(t,"packages","core","schemas","src"),e["@donotdev/core"]=b.join(t,"packages","core"))}return e}P();import{createRequire as ye}from"node:module";import{resolve as M,join as x,dirname as E,relative as J,normalize as Pe,sep as ee,extname as be}from"node:path";import{fileURLToPath as ke}from"node:url";import*as p from"node:fs";K();import we from"fast-glob";var _={getGlobOptionsFor:Z||void 0,SCAN_PATTERNS:R||void 0,getPatternsFor:V||void 0,I18N_PATHS:U||void 0},g={error:(n,e)=>{},warn:(n,e)=>{},info:n=>{}};function te(n,e){return n().catch(t=>{throw new Error(`${e}: ${t instanceof Error?t.message:String(t)}`)})}var re={CLI:"packages/cli",COMPONENTS:"packages/core/components",CONFIG:"packages/core/config",CORE:"packages/core",CRUD:"packages/core/crud",FEATURES:"packages/features",HOOKS:"packages/core/hooks",I18N:"packages/core/i18n",SCHEMAS:"packages/core/schemas",STORES:"packages/core/stores",TEMPLATES:"packages/templates",TOOLING:"packages/tooling",TYPES:"packages/core/types",UI:"packages/ui",UTILS:"packages/core/utils",AUTH:"packages/features/auth",BILLING:"packages/features/billing",OAUTH:"packages/features/oauth",FIREBASE:"packages/providers/firebase",FUNCTIONS:"packages/functions"},B=class n{static _instance=null;options;_repoRoot;_appRoot=null;static getInstance(e={}){return n._instance||(n._instance=new n(e)),n._instance}static _reset(){n._instance=null}constructor(e={}){if(n._instance)return n._instance;this.options={maxLevels:e.maxLevels??10,customMarkers:e.customMarkers||[],cache:e.cache??!1,debug:e.debug??!1};try{let t=y.cwd();if(!t)throw new Error("PathResolver: process.cwd() returned undefined. This should never happen.");this._repoRoot=this._findRepoRoot(t)}catch(t){throw new Error(`PathResolver constructor failed: ${t instanceof Error?t.message:String(t)}. cwd: ${y.cwd()}`)}this._appRoot=null,n._instance=this}normalizePath(e){if(!e)return"";try{return Pe(e).split(ee).join("/")}catch{return String(e).split(ee).join("/")}}getRelativePath(e){let t=this.getAppRoot(),r=J(t,e);return this.normalizePath(r)}getBasename(e){if(!e)return"";let r=this.normalizePath(e).split("/");return r[r.length-1]||""}getDirname(e){return e?this.normalizePath(E(e)):""}resolvePackage(e,t=null){try{let r=t||this.getAppRoot(),o=ye(x(r,"package.json")).resolve(e);return this.normalizePath(o)}catch{return null}}resolveFrameworkPackage(e,t=null){let r=this.resolvePackage(`${e}/package.json`,t);if(r)return this.getDirname(r);if(this.isMonorepo()&&e.startsWith("@donotdev/")){let s=e.replace("@donotdev/",""),a=this.resolveRepoPath(`packages/${s}`);if(this.pathExists(a))return a;if(["auth","billing","crud","oauth"].includes(s)){let l=this.resolveRepoPath(`packages/features/${s}`);if(this.pathExists(l))return l}if(s==="firebase"){let l=this.resolveRepoPath(`packages/providers/${s}`);if(this.pathExists(l))return l}}let i=this.resolveAppPath(`node_modules/${e}`);if(this.pathExists(i))return i;let o=this.resolveRepoPath(`node_modules/${e}`);return this.pathExists(o)?o:null}resolvePackageAsset(e,t=null){return this.resolvePackage(e,t)}resolveAppPath(e){let t=this.getAppRoot(),r=M(t,e);return this.normalizePath(r)}resolveRepoPath(e){let t=this.getRepoRoot(),r=this.normalizePath(e),i=M(t,r);return this.normalizePath(i)}resolvePath(e,t){let r=this.normalizePath(t),i=this.normalizePath(e),o=M(r,i);return this.normalizePath(o)}createImportPath(e){return"./"+this.getRelativePath(e)}getFileInfo(e){try{let t=p.statSync(e);return{absolutePath:this.normalizePath(e),relativePath:this.getRelativePath(e),importPath:this.createImportPath(e),size:t.size,isFile:t.isFile(),isDirectory:t.isDirectory()}}catch{return null}}_detectFormat(e,t){return t&&t!=="auto"?t:be(e).toLowerCase()===".json"?"json":"text"}async read(e,t={}){let{format:r="auto",encoding:i="utf8"}=t,o=this._detectFormat(e,r);try{if(o==="buffer")return await p.promises.readFile(e);let s=await p.promises.readFile(e,i),a=this.stripBom(s);return o==="json"?JSON.parse(a):a}catch(s){return this.options.debug&&g.warn(`Failed to read file: ${e}`,s),null}}readSync(e,t={}){let{format:r="auto",encoding:i="utf8"}=t,o=this._detectFormat(e,r);try{if(o==="buffer")return p.readFileSync(e);let s=p.readFileSync(e,i),a=this.stripBom(s);return o==="json"?JSON.parse(a):a}catch(s){return this.options.debug&&g.warn(`Failed to read file: ${e}`,s),null}}async write(e,t,r={}){let{format:i="auto",overwrite:o=!1,dryRun:s=!1,verbose:a=!1}=r,l=this.normalizePath(e),h=this.normalizePath(E(l)),c=this.pathExists(l);if(c&&!o)return a&&g.info(`Skipping existing file: ${l}`),!1;if(s)return g.info(`[DRY RUN] Would write file: ${l}`),!0;try{await p.promises.mkdir(h,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let f=this._detectFormat(e,i),m;w.isBuffer(t)?m=t:f==="json"&&typeof t=="object"?m=JSON.stringify(t,null,2):m=String(t);try{return await te(async()=>(w.isBuffer(m)?await p.promises.writeFile(l,m):await p.promises.writeFile(l,m,"utf8"),a&&g.info(`${c?"Updated":"Created"} file: ${l}`),!0),`Failed to write file: ${l}`)}catch{return!1}}writeSync(e,t,r={}){let{format:i="auto",overwrite:o=!1,dryRun:s=!1,verbose:a=!1}=r,l=this.normalizePath(e),h=this.normalizePath(E(l)),c=this.pathExists(l);if(c&&!o)return a&&g.info(`Skipping existing file: ${l}`),!1;if(s)return g.info(`[DRY RUN] Would write file: ${l}`),!0;try{p.mkdirSync(h,{recursive:!0})}catch(d){if(d?.code!=="EEXIST")throw d}let f=this._detectFormat(e,i),m;w.isBuffer(t)?m=t:f==="json"&&typeof t=="object"?m=JSON.stringify(t,null,2):m=String(t);try{return w.isBuffer(m)?p.writeFileSync(l,m):p.writeFileSync(l,m,"utf8"),a&&g.info(`${c?"Updated":"Created"} file: ${l}`),!0}catch(d){throw new Error(`Failed to write file: ${l}: ${d instanceof Error?d.message:String(d)}`)}}async copy(e,t,r={}){let{overwrite:i=!1,dryRun:o=!1,verbose:s=!1}=r,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!i)return s&&g.info(`Skipping existing file: ${a}`),!1;if(o)return g.info(`[DRY RUN] Would copy file: ${a}`),!0;let h=this.normalizePath(E(a));try{await p.promises.mkdir(h,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return await te(async()=>(await p.promises.copyFile(e,a),s&&g.info(`${l?"Updated":"Created"} file: ${a}`),!0),`Failed to copy file from ${e} to ${a}`)}catch{return!1}}copySync(e,t,r={}){let{overwrite:i=!1,dryRun:o=!1,verbose:s=!1}=r,a=this.normalizePath(t),l=this.pathExists(a);if(l&&!i)return s&&g.info(`Skipping existing file: ${a}`),!1;if(o)return g.info(`[DRY RUN] Would copy file: ${a}`),!0;let h=this.normalizePath(E(a));try{p.mkdirSync(h,{recursive:!0})}catch(c){if(c?.code!=="EEXIST")throw c}try{return p.copyFileSync(e,a),s&&g.info(`${l?"Updated":"Created"} file: ${a}`),!0}catch{return!1}}pathExists(e,t=!1){try{return p.existsSync(e)}catch(r){return t||g.error(`Error checking path existence: ${e}`,r),!1}}mkdir(e){try{let t=e.startsWith("/")||e.match(/^[A-Z]:/)?this.normalizePath(e):this.resolveAppPath(e);return p.existsSync(t)||p.mkdirSync(t,{recursive:!0}),!0}catch{return!1}}readdirSync(e,t){try{return p.readdirSync(e,t)}catch(r){return this.options.debug&&g.warn(`Failed to read directory: ${e}`,r),t&&typeof t=="object"&&"withFileTypes"in t&&t.withFileTypes?[]:[]}}statSync(e){try{return p.statSync(e)}catch(t){return this.options.debug&&g.warn(`Failed to stat file: ${e}`,t),null}}lstatSync(e){try{return p.lstatSync(e)}catch(t){return this.options.debug&&g.warn(`Failed to lstat file: ${e}`,t),null}}async ensureDir(e){try{await p.promises.mkdir(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}ensureDirSync(e){try{p.mkdirSync(e,{recursive:!0})}catch(t){if(t?.code!=="EEXIST")throw t}}async remove(e){await p.promises.rm(e,{recursive:!0,force:!0})}removeSync(e){p.rmSync(e,{recursive:!0,force:!0})}async readdir(e,t){return p.promises.readdir(e,t)}stripBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}getRepoRoot(){return this._repoRoot||y.cwd()}getAppRoot(){return this._appRoot?this._appRoot:this._repoRoot}setAppRoot(e){if(!e)throw new Error("PathResolver.setAppRoot: root cannot be undefined or null");this._appRoot=this.normalizePath(e)}isMonorepo(){let e=x(this._repoRoot,"packages");return this.pathExists(e)}isWithinApp(e){let t=this.normalizePath(M(e)),r=this.getAppRoot(),i=J(r,t),o=this.normalizePath(i);return!o.startsWith("../")&&!o.startsWith("/")}async findFiles(e,t,r={}){let i=this.normalizePath(x(e,t)),o=this.getAppRoot(),s=this.normalizePath(o),a=i.startsWith(s)?i.slice(s.length+1):i,l={absolute:!0,onlyFiles:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:o,ignore:_.SCAN_PATTERNS?.globalIgnore||["**/node_modules/**","**/dist/**","**/build/**","**/.git/**"]};return await this._globWithNormalization([a],{...l,...r})}clearCache(){}async _resolveFrameworkI18nPattern(e){let t=_.I18N_PATHS;if(!t)return null;let r=e.replace(t.SOURCE_ROOT+"/",""),i=this.resolveFrameworkPackage("@donotdev/core");if(!i)return null;let o=this.normalizePath(x(i,t.PUBLISHED_ROOT,r)),s=o.replace(/\/[^/]*\*.*$/,"");return this.pathExists(s),o}async _globWithNormalization(e,t){return(await we(e,t)).map(i=>{let o=typeof i=="string"?i:i.path;return this.normalizePath(o)})}async resolveFiles(e,t="css"){if(!e||typeof e!="object")return{frameworkFiles:[],consumerFiles:[]};if(t==="i18n")return{frameworkFiles:[],consumerFiles:[]};if(Array.isArray(e.framework)||(e.framework=[]),!Array.isArray(e.consumer))return{frameworkFiles:[],consumerFiles:[]};let r=[...e.framework,...e.consumer];for(let c of r)if(typeof c!="string"||c.trim()==="")return{frameworkFiles:[],consumerFiles:[]};let i=this.getAppRoot(),o=_.getGlobOptionsFor?_.getGlobOptionsFor(t):{ignore:["**/node_modules/**","**/dist/**","**/build/**"]},s=this.normalizePath(i),a=e.framework.map(c=>{let f=this.normalizePath(c);return f.startsWith(s)?f.slice(s.length+1):f}),l=e.consumer.map(c=>{let f=this.normalizePath(c);return f.startsWith(s)?f.slice(s.length+1):f}),h={...o,onlyFiles:!0,absolute:!0,braceExpansion:!0,extglob:!0,globstar:!0,cwd:i};try{let c=a.length>0?await this._globWithNormalization(a,h):[],f=await this._globWithNormalization(l,h);return{frameworkFiles:c,consumerFiles:f}}catch{return this.options.debug,{frameworkFiles:[],consumerFiles:[]}}}async resolvePatterns(e){if(!_.getPatternsFor)return{framework:[],consumer:[],all:[]};let t=this.getAppRoot(),r=this.getRepoRoot();if(e==="i18n"&&(!t||t===r))throw new Error(`Cannot resolve i18n patterns: appRoot not set (appRoot: ${t}, repoRoot: ${r}). Ensure configResolved hook has run before discovery.`);let i=_.getPatternsFor(e),o=this.isMonorepo();if(e==="i18n"){let l=i,h={eager:l.eager.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),lazy:l.lazy.map(c=>c.startsWith("!")?"!"+this.resolveAppPath(c.slice(1)):this.resolveAppPath(c)),framework:{eager:o?(l.framework?.eager||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.eager||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean)),lazy:o?(l.framework?.lazy||[]).map(c=>this.resolveRepoPath(c)).filter(Boolean):await Promise.all((l.framework?.lazy||[]).map(c=>this._resolveFrameworkI18nPattern(c))).then(c=>c.filter(Boolean))},all:[]};return h.all=[...h.eager,...h.lazy,...h.framework.eager,...h.framework.lazy],h}let s=i,a={framework:o?(s.framework||[]).map(l=>this.resolveRepoPath(l)).filter(Boolean):[],consumer:(s.consumer||[]).map(l=>this.resolveAppPath(l)),all:[]};return a.all=[...a.consumer,...a.framework],a}getEmptyModulePath(e=!1){if(e)return"@donotdev/core/empty";let t=this.resolvePackage("@donotdev/core/empty");if(t)return t;let r=E(ke(import.meta.url));return this.normalizePath(x(r,"../empty.js"))}_findRepoRoot(e){let t=this.normalizePath(e),r=0,i=this.options.maxLevels;for(;r<i;){let o=this.normalizePath(x(t,re.TOOLING)),s=this.normalizePath(x(t,re.CORE));if(this.pathExists(o)&&this.pathExists(s))return t;let a=x(t,"apps");if(this.pathExists(a)&&this.statSync(a)?.isDirectory())return this.normalizePath(t);let l=this.normalizePath(x(t,"package.json"));if(this.pathExists(l)&&this.normalizePath(E(t))===t)return t;let h=this.normalizePath(E(t));if(h===t)break;t=h,r++}return this.normalizePath(e)}};function se(n={}){let{entry:e="src/index.ts",outDir:t="lib",minify:r=!1,sourcemap:i=!0,platform:o="firebase",workspace:s,bundleWorkspaceDeps:a=!1,importFramework:l=!1,external:h=!1,...c}=n,f=B.getInstance(),m=Q(s),d={entryPoints:[e],bundle:!0,platform:"node",target:"node20",format:"esm",outdir:t,outExtension:{".js":".js"},minify:r,sourcemap:i,metafile:!0,logLevel:"info",loader:{".ts":"ts",".tsx":"tsx",".css":"empty"},keepNames:!0,treeShaking:!0,...c};a&&Object.keys(m).length>0&&(d.alias=Object.fromEntries(Object.entries(m).map(([k,u])=>[k,f.normalizePath(u)]))),d.mainFields=["module","main"],d.conditions=["import","module","node"];let ce=["fs","path","crypto","util","stream","events","buffer","url","querystring","http","https","zlib","os","child_process","assert","constants","domain","punycode","string_decoder","timers","tty","vm","worker_threads","perf_hooks","async_hooks"],G=[];if(a)try{let k=s?.root||y.cwd(),u=y.cwd(),v=10;for(let S=0;S<v;S++){let H=f.normalizePath(`${u}/package.json`);if(f.pathExists(H)){let z=f.readSync(H,{format:"json"});if(z&&Array.isArray(z.workspaces)){k=f.normalizePath(u);for(let $ of z.workspaces)$==="apps/*"||$==="functions"||!$.includes("*")&&!$.includes("/")&&G.push($);break}}let L=f.getDirname(u);if(L===u)break;u=L}}catch{}let le={name:"external-node-modules",setup(k){k.onResolve({filter:/^firebase($|\/)/},u=>{if(u.path==="firebase-admin"||u.path.startsWith("firebase-admin/")||u.path==="firebase-functions"||u.path.startsWith("firebase-functions/"))return null;let v;if(s?.type==="dndev"&&s.root)v=f.normalizePath(`${s.root}/packages/core/config/functions/firebase-stub.js`);else{let S=import.meta.url,L=new URL(S).pathname.replace(/^\/([A-Z]:)/i,"$1"),z=f.getDirname(L);v=f.normalizePath(`${z}/firebase-stub.js`)}return{path:v}}),k.onResolve({filter:/.*/},u=>{if(u.kind==="entry-point")return null;if(u.path.match(/@donotdev\/functions\/.+/)&&a&&s?.type==="dndev"){let v=u.path.replace("@donotdev/functions/","");return{path:f.normalizePath(`${s.root}/packages/functions/src/${v}/index.ts`)}}if(u.path==="@donotdev/utils")return s?.type==="dndev"?{path:f.normalizePath(`${s.root}/packages/core/utils/src/server/index.ts`)}:k.resolve("@donotdev/utils/server",{kind:u.kind,resolveDir:u.resolveDir});if(u.path.match(/@donotdev\/utils\/.+/)&&s?.type==="dndev"){let v=u.path.replace("@donotdev/utils/","");return{path:f.normalizePath(`${s.root}/packages/core/utils/src/${v}/index.ts`)}}if(u.path==="@donotdev/core")return s?.type==="dndev"?{path:f.normalizePath(`${s.root}/packages/core/server.ts`)}:k.resolve("@donotdev/core/server",{kind:u.kind,resolveDir:u.resolveDir});if(u.path.match(/@donotdev\/core\/.+/)&&a&&s?.type==="dndev"){let v=u.path.replace("@donotdev/core/","");return{path:f.normalizePath(`${s.root}/packages/core/${v}.ts`)}}if(u.path==="firebase-admin"||u.path.startsWith("firebase-admin/")||u.path==="firebase-functions"||u.path.startsWith("firebase-functions/"))return{path:u.path,external:!0};if(u.path.match(/@donotdev\/core\/.+/)&&a&&s?.type==="dndev"){let v=u.path.replace("@donotdev/core/","");return{path:f.normalizePath(`${s.root}/packages/core/${v}.ts`)}}if(u.path.startsWith("@donotdev/")||u.path==="valibot"||u.path.startsWith("valibot/"))return null;if(G.length>0){let v=u.path.split("/")[0];if(G.includes(v))return null}return u.path.startsWith(".")||u.path.startsWith("/")?null:{path:u.path,external:!0}})}};if(d.external=[...ce,"firebase-admin","firebase-functions"],d.plugins=[le,...d.plugins||[]],d.define={"process.env.NODE_ENV":JSON.stringify(y.env.NODE_ENV||"production"),...d.define||{}},l&&s.type==="dndev"){let k=s.root,u=f.normalizePath(`${k}/functions/lib`);d.alias={...d.alias,"@donotdev/functions":u}}return o==="framework"&&(d.entryPoints={"firebase/index":"src/firebase/index.ts","vercel/api/index":"src/vercel/api/index.ts","shared/index":"src/shared/index.ts"}),d}P();var oe=["create","get","list","listCard","update","delete"];function ne(n,e=0){let t=" ".repeat(e),r="";for(let[i,o]of Object.entries(n))if(o!=null)if(typeof o=="object"&&!Array.isArray(o))Object.keys(o).length===0?r+=`${t}${i}: {}
|
|
2
|
+
`:r+=`${t}${i}:
|
|
3
|
+
${ne(o,e+1)}`;else if(Array.isArray(o))if(o.length===0)r+=`${t}${i}: []
|
|
4
|
+
`;else{r+=`${t}${i}:
|
|
5
|
+
`;for(let s of o)r+=`${t} - ${s}
|
|
6
|
+
`}else r+=`${t}${i}: ${o}
|
|
7
|
+
`;return r}function ie(n){let e=n.defaults||{},t=e.labels||{},r={};for(let[o,s]of Object.entries(n.functions||{})){let a={...t,...s.labels};s.category&&(a.category=s.category),r[o]={region:s.region||e.region||["us-central1"],platform:s.platform||e.platform||"gcfv2",entryPoint:s.entryPoint||o,labels:a},s.trigger==="http"?r[o].httpsTrigger={}:r[o].callableTrigger={}}if(n.crud?.entities)for(let o of n.crud.entities)for(let s of oe){let a=`${s}_${o}`;r[a]={region:e.region||["us-central1"],platform:e.platform||"gcfv2",callableTrigger:{},entryPoint:a,labels:{...t,category:"crud"}}}return`# Firebase Functions Configuration
|
|
8
8
|
# Generated by @donotdev/core/functions - DO NOT EDIT MANUALLY
|
|
9
9
|
# Generated at: ${new Date().toISOString()}
|
|
10
10
|
|
|
11
|
-
`+ne({endpoints:
|
|
11
|
+
`+ne({endpoints:r,specVersion:"v1alpha1",requiredAPIs:[]})}function xe(n){let e=Object.keys(n.functions||{}),t=[];if(n.crud?.entities)for(let r of n.crud.entities)for(let i of oe)t.push(`${i}_${r}`);return{yaml:ie(n),functions:[...e,...t],staticFunctions:e,crudFunctions:t}}function ae(n={}){let{entry:e="src/index.ts",outDir:t="lib",minify:r=!1,sourcemap:i=!0,platform:o="firebase",...s}=n,a=X();return se({entry:e,outDir:t,minify:r,sourcemap:i,platform:o,workspace:a,...s})}function et(n={}){return ae({...n,platform:"framework",bundleWorkspaceDeps:!0})}function tt(n={}){return ae({...n,platform:"firebase",bundleWorkspaceDeps:!0,importFramework:!0})}export{tt as createAppFunctionsConfig,ae as createFunctionsEsbuildConfig,et as createRootFunctionsConfig,ie as generateFunctionsYaml,xe as generateFunctionsYamlWithInfo};
|
package/package.json
CHANGED
package/server.d.ts
CHANGED
|
@@ -2,8 +2,6 @@ import * as React from 'react';
|
|
|
2
2
|
import { ReactNode, ComponentType } from 'react';
|
|
3
3
|
export { ReactNode } from 'react';
|
|
4
4
|
import * as v from 'valibot';
|
|
5
|
-
export * from '@donotdev/schemas/server';
|
|
6
|
-
export { global } from '@donotdev/schemas/server';
|
|
7
5
|
|
|
8
6
|
// Types
|
|
9
7
|
|
|
@@ -13367,5 +13365,465 @@ declare namespace index_d {
|
|
|
13367
13365
|
export type { index_d_DateFormatOptions as DateFormatOptions, index_d_DateFormatPreset as DateFormatPreset, index_d_ErrorHandlerConfig as ErrorHandlerConfig, index_d_ErrorHandlerFunction as ErrorHandlerFunction, index_d_HandleErrorOptions as HandleErrorOptions };
|
|
13368
13366
|
}
|
|
13369
13367
|
|
|
13370
|
-
|
|
13371
|
-
|
|
13368
|
+
/**
|
|
13369
|
+
* @fileoverview Unified Schema Generation
|
|
13370
|
+
* @description Creates Valibot schemas from entity definitions with visibility metadata.
|
|
13371
|
+
*
|
|
13372
|
+
* Entity → Schema (with visibility) → Used everywhere (frontend + backend)
|
|
13373
|
+
*
|
|
13374
|
+
* Isomorphic code (works in both client and server environments).
|
|
13375
|
+
*
|
|
13376
|
+
* @version 0.0.2
|
|
13377
|
+
* @since 0.0.1
|
|
13378
|
+
* @author AMBROISE PARK Consulting
|
|
13379
|
+
*/
|
|
13380
|
+
|
|
13381
|
+
/**
|
|
13382
|
+
* Valibot schema with visibility metadata attached
|
|
13383
|
+
*/
|
|
13384
|
+
interface SchemaWithVisibility extends v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>> {
|
|
13385
|
+
visibility?: Visibility;
|
|
13386
|
+
}
|
|
13387
|
+
/**
|
|
13388
|
+
* Operation-specific schemas generated from entity
|
|
13389
|
+
*/
|
|
13390
|
+
interface OperationSchemas {
|
|
13391
|
+
/** Create: excludes technical fields, enforces required */
|
|
13392
|
+
create: dndevSchema<unknown>;
|
|
13393
|
+
/** Draft: excludes technical fields, all optional except status='draft' */
|
|
13394
|
+
draft: dndevSchema<unknown>;
|
|
13395
|
+
/** Update: excludes technical fields, all optional */
|
|
13396
|
+
update: dndevSchema<unknown>;
|
|
13397
|
+
/** Get: includes all fields with visibility metadata */
|
|
13398
|
+
get: dndevSchema<unknown>;
|
|
13399
|
+
/** List: optimized for admin table (uses listFields) */
|
|
13400
|
+
list: dndevSchema<unknown>;
|
|
13401
|
+
/** ListCard: optimized for public cards (uses listCardFields, falls back to listFields) */
|
|
13402
|
+
listCard: dndevSchema<unknown>;
|
|
13403
|
+
/** Delete: just { id: string } */
|
|
13404
|
+
delete: dndevSchema<unknown>;
|
|
13405
|
+
}
|
|
13406
|
+
/**
|
|
13407
|
+
* Creates all operation-specific schemas from an entity definition
|
|
13408
|
+
*
|
|
13409
|
+
* Each schema field has `.visibility` attached for backend filtering.
|
|
13410
|
+
*
|
|
13411
|
+
* @param entity - Entity definition
|
|
13412
|
+
* @returns Operation-specific schemas with visibility metadata
|
|
13413
|
+
*
|
|
13414
|
+
* @example
|
|
13415
|
+
* ```typescript
|
|
13416
|
+
* const schemas = createSchemas(carEntity);
|
|
13417
|
+
* // schemas.create - for creating documents
|
|
13418
|
+
* // schemas.draft - for saving incomplete
|
|
13419
|
+
* // schemas.update - for partial updates
|
|
13420
|
+
* // schemas.get - for reading (includes technical fields)
|
|
13421
|
+
* // schemas.list - array of get
|
|
13422
|
+
* // schemas.delete - just { id }
|
|
13423
|
+
* ```
|
|
13424
|
+
*/
|
|
13425
|
+
declare function createSchemas(entity: Entity): OperationSchemas;
|
|
13426
|
+
|
|
13427
|
+
/**
|
|
13428
|
+
* @fileoverview Schema enhancement utility
|
|
13429
|
+
* @description Enhances a Valibot schema with additional metadata
|
|
13430
|
+
*
|
|
13431
|
+
* @version 0.0.1
|
|
13432
|
+
* @since 0.0.1
|
|
13433
|
+
* @author AMBROISE PARK Consulting
|
|
13434
|
+
*/
|
|
13435
|
+
|
|
13436
|
+
/**
|
|
13437
|
+
* Enhances a Valibot schema with additional metadata.
|
|
13438
|
+
*
|
|
13439
|
+
* @param schema - The base Valibot schema
|
|
13440
|
+
* @param metadata - The metadata to attach
|
|
13441
|
+
* @returns The enhanced schema
|
|
13442
|
+
* @version 0.0.1
|
|
13443
|
+
* @since 0.0.1
|
|
13444
|
+
* @author AMBROISE PARK Consulting
|
|
13445
|
+
*/
|
|
13446
|
+
declare function enhanceSchema<T>(schema: v.BaseSchema<unknown, T, v.BaseIssue<unknown>>, metadata: SchemaMetadata): dndevSchema<T>;
|
|
13447
|
+
|
|
13448
|
+
/**
|
|
13449
|
+
* @fileoverview Schema type generation utility
|
|
13450
|
+
* @description Creates Valibot schemas via registry - extensible for custom types
|
|
13451
|
+
*
|
|
13452
|
+
* @version 0.0.2
|
|
13453
|
+
* @since 0.0.1
|
|
13454
|
+
* @author AMBROISE PARK Consulting
|
|
13455
|
+
*/
|
|
13456
|
+
|
|
13457
|
+
/**
|
|
13458
|
+
* Schema generator function type
|
|
13459
|
+
*/
|
|
13460
|
+
type CustomSchemaGenerator = (field: EntityField<FieldType>) => v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>> | null;
|
|
13461
|
+
/**
|
|
13462
|
+
* Register a schema generator for a field type
|
|
13463
|
+
*/
|
|
13464
|
+
declare function registerSchemaGenerator(type: string, generator: CustomSchemaGenerator): void;
|
|
13465
|
+
/**
|
|
13466
|
+
* Check if a schema generator is registered
|
|
13467
|
+
*/
|
|
13468
|
+
declare function hasCustomSchemaGenerator(type: string): boolean;
|
|
13469
|
+
/**
|
|
13470
|
+
* Get all registered schema types
|
|
13471
|
+
*/
|
|
13472
|
+
declare function getRegisteredSchemaTypes(): string[];
|
|
13473
|
+
/**
|
|
13474
|
+
* Clear all schema generators (testing)
|
|
13475
|
+
*/
|
|
13476
|
+
declare function clearSchemaGenerators(): void;
|
|
13477
|
+
/**
|
|
13478
|
+
* Get Valibot schema for an entity field
|
|
13479
|
+
*
|
|
13480
|
+
* Priority order:
|
|
13481
|
+
* 1. field.validation?.schema (custom schema defined directly in entity)
|
|
13482
|
+
* 2. Registry lookup (built-in or registered custom types)
|
|
13483
|
+
* 3. Fallback to v.unknown() for unregistered types
|
|
13484
|
+
*/
|
|
13485
|
+
declare function getSchemaType(field: EntityField<FieldType>): v.BaseSchema<unknown, unknown, v.BaseIssue<unknown>>;
|
|
13486
|
+
|
|
13487
|
+
/**
|
|
13488
|
+
* Recursively validates that all string values that look like potential dates
|
|
13489
|
+
* within an object adhere to the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ).
|
|
13490
|
+
*
|
|
13491
|
+
* @param data - The object or data structure to validate
|
|
13492
|
+
* @param {string} [currentPath=''] - Internal tracking of the object path for error messages
|
|
13493
|
+
* @throws Error if any string resembling a date is not in the correct ISO format
|
|
13494
|
+
* @version 0.0.1
|
|
13495
|
+
* @since 0.0.1
|
|
13496
|
+
* @author AMBROISE PARK Consulting
|
|
13497
|
+
*/
|
|
13498
|
+
declare function validateDates(data: Record<string, any> | any[], currentPath?: string): void;
|
|
13499
|
+
|
|
13500
|
+
/**
|
|
13501
|
+
* Validates a document against the schema, including uniqueness and custom validations.
|
|
13502
|
+
* @param schema - The enhanced schema.
|
|
13503
|
+
* @param data - The document data.
|
|
13504
|
+
* @param operation - 'create' or 'update'.
|
|
13505
|
+
* @param currentDocId - Optional current document ID for update operations.
|
|
13506
|
+
* @throws DoNotDevError if validation fails.
|
|
13507
|
+
*
|
|
13508
|
+
* @version 0.0.1
|
|
13509
|
+
* @since 0.0.1
|
|
13510
|
+
* @author AMBROISE PARK Consulting
|
|
13511
|
+
*/
|
|
13512
|
+
declare function validateDocument<T>(schema: dndevSchema<T>, data: Record<string, any>, operation: 'create' | 'update', currentDocId?: string): Promise<void>;
|
|
13513
|
+
|
|
13514
|
+
/**
|
|
13515
|
+
* @fileoverview Unique field validation utility
|
|
13516
|
+
* @description Validates uniqueness constraints for schema fields
|
|
13517
|
+
*
|
|
13518
|
+
* @version 0.0.1
|
|
13519
|
+
* @since 0.0.1
|
|
13520
|
+
* @author AMBROISE PARK Consulting
|
|
13521
|
+
*/
|
|
13522
|
+
|
|
13523
|
+
/**
|
|
13524
|
+
* Registers a validator for uniqueness constraints
|
|
13525
|
+
*
|
|
13526
|
+
* @param validator - The validator implementation
|
|
13527
|
+
* @version 0.0.1
|
|
13528
|
+
* @since 0.0.1
|
|
13529
|
+
* @author AMBROISE PARK Consulting
|
|
13530
|
+
*/
|
|
13531
|
+
declare function registerUniqueConstraintValidator(validator: UniqueConstraintValidator): void;
|
|
13532
|
+
/**
|
|
13533
|
+
* Validates unique fields for a document across environments.
|
|
13534
|
+
*
|
|
13535
|
+
* @param schema - The Valibot schema with metadata.
|
|
13536
|
+
* @param data - The document data.
|
|
13537
|
+
* @param currentDocId - Optional ID of the current document (for updates).
|
|
13538
|
+
* @throws Error if a unique constraint is violated.
|
|
13539
|
+
* @version 0.0.1
|
|
13540
|
+
* @since 0.0.1
|
|
13541
|
+
* @author AMBROISE PARK Consulting
|
|
13542
|
+
*/
|
|
13543
|
+
declare function validateUniqueFields<T>(schema: dndevSchema<T>, data: Record<string, any>, currentDocId?: string): Promise<void>;
|
|
13544
|
+
|
|
13545
|
+
/**
|
|
13546
|
+
* @fileoverview Schema Utilities
|
|
13547
|
+
* @description Common utility functions for working with schemas. Provides helper functions for schema metadata checking and manipulation.
|
|
13548
|
+
*
|
|
13549
|
+
* @version 0.0.1
|
|
13550
|
+
* @since 0.0.1
|
|
13551
|
+
* @author AMBROISE PARK Consulting
|
|
13552
|
+
*/
|
|
13553
|
+
|
|
13554
|
+
/**
|
|
13555
|
+
* Checks if an object has schema metadata (works with Valibot schemas)
|
|
13556
|
+
*
|
|
13557
|
+
* @param obj - The object to check
|
|
13558
|
+
* @returns Whether the object has schema metadata
|
|
13559
|
+
* @version 0.0.1
|
|
13560
|
+
* @since 0.0.1
|
|
13561
|
+
* @author AMBROISE PARK Consulting
|
|
13562
|
+
*/
|
|
13563
|
+
declare function hasMetadata(obj: unknown): obj is dndevSchema<unknown>;
|
|
13564
|
+
/**
|
|
13565
|
+
* Gets the collection name from a schema
|
|
13566
|
+
*
|
|
13567
|
+
* @param schema - The schema to get the collection name from
|
|
13568
|
+
* @returns The collection name
|
|
13569
|
+
* @version 0.0.1
|
|
13570
|
+
* @since 0.0.1
|
|
13571
|
+
* @author AMBROISE PARK Consulting
|
|
13572
|
+
*/
|
|
13573
|
+
declare function getCollectionName(schema: dndevSchema<unknown>): string;
|
|
13574
|
+
|
|
13575
|
+
/**
|
|
13576
|
+
* @fileoverview The 4 Field Families
|
|
13577
|
+
* @description Every entity in the framework is composed of 4 families
|
|
13578
|
+
*
|
|
13579
|
+
* ## The 4 Families
|
|
13580
|
+
*
|
|
13581
|
+
* ```
|
|
13582
|
+
* Entity = Technical Fields + Status Field + User Fields (Framework Types or Custom Types)
|
|
13583
|
+
* ```
|
|
13584
|
+
*
|
|
13585
|
+
* ### Family 1: TECHNICAL_FIELDS (Backend-Generated)
|
|
13586
|
+
* **Members**: `id`, `createdAt`, `updatedAt`, `createdById`, `updatedById`
|
|
13587
|
+
*
|
|
13588
|
+
* **Rules**:
|
|
13589
|
+
* - ✓ Always present (framework adds automatically)
|
|
13590
|
+
* - ✗ Users cannot set (stripped from submissions)
|
|
13591
|
+
* - ✓ Read-only in edit forms
|
|
13592
|
+
* - ✓ Auto-generated by server
|
|
13593
|
+
*
|
|
13594
|
+
* ### Family 2: STATUS_FIELD (Lifecycle Management)
|
|
13595
|
+
* **Member**: `status`
|
|
13596
|
+
*
|
|
13597
|
+
* **Default Values**: `'draft'`, `'available'`, `'deleted'`
|
|
13598
|
+
*
|
|
13599
|
+
* **Rules**:
|
|
13600
|
+
* - ✓ Always present (framework adds)
|
|
13601
|
+
* - ✓ Users must set value
|
|
13602
|
+
* - ✓ Users can add custom values (`'reserved'`, `'sold'`)
|
|
13603
|
+
* - ✗ Cannot remove default values
|
|
13604
|
+
* - ✓ Draft mode (`status === 'draft'`) relaxes validation
|
|
13605
|
+
*
|
|
13606
|
+
* ### Family 3: FRAMEWORK_TYPES (~30 Built-in)
|
|
13607
|
+
* **Available Types**:
|
|
13608
|
+
* - Text: `text`, `textarea`, `email`, `tel`, `url`, `password`
|
|
13609
|
+
* - Numbers: `number`, `range`
|
|
13610
|
+
* - Dates: `date`, `datetime-local`, `time`, `timestamp`
|
|
13611
|
+
* - Choices: `select`, `multiselect`, `radio`, `checkbox`, `combobox`, `switch`
|
|
13612
|
+
* - Media: `image`, `images`, `file`
|
|
13613
|
+
* - Special: `reference`, `geopoint`, `address`, `map`
|
|
13614
|
+
*
|
|
13615
|
+
* ### Family 4: CUSTOM_TYPES (User-Registered)
|
|
13616
|
+
* **What**: Custom field types registered via `registerFieldType()`
|
|
13617
|
+
*
|
|
13618
|
+
* **Examples**: `repairOperations`, `ratp`, custom widgets
|
|
13619
|
+
*
|
|
13620
|
+
* ## Complete Example
|
|
13621
|
+
*
|
|
13622
|
+
* ```typescript
|
|
13623
|
+
* import { defineEntity } from '@donotdev/core';
|
|
13624
|
+
* import { registerFieldType } from '@donotdev/crud';
|
|
13625
|
+
*
|
|
13626
|
+
* // Register custom type (Family 4)
|
|
13627
|
+
* registerFieldType('repairOperations', {
|
|
13628
|
+
* schema: (field) => v.array(v.object({ operation: v.string(), cost: v.number() })),
|
|
13629
|
+
* component: RepairOperationsField
|
|
13630
|
+
* });
|
|
13631
|
+
*
|
|
13632
|
+
* // Define entity
|
|
13633
|
+
* const carEntity = defineEntity({
|
|
13634
|
+
* name: 'Car',
|
|
13635
|
+
* collection: 'cars',
|
|
13636
|
+
* fields: {
|
|
13637
|
+
* // User fields using FRAMEWORK_TYPES (Family 3)
|
|
13638
|
+
* make: { type: 'text', validation: { required: true } },
|
|
13639
|
+
* year: { type: 'number' },
|
|
13640
|
+
* images: { type: 'images' },
|
|
13641
|
+
* fuelType: { type: 'select', validation: { options: [...] } },
|
|
13642
|
+
*
|
|
13643
|
+
* // User field using CUSTOM_TYPES (Family 4)
|
|
13644
|
+
* repairs: { type: 'repairOperations', visibility: 'admin' },
|
|
13645
|
+
*
|
|
13646
|
+
* // Extend STATUS_FIELD (Family 2)
|
|
13647
|
+
* status: {
|
|
13648
|
+
* validation: {
|
|
13649
|
+
* options: [
|
|
13650
|
+
* { value: 'reserved', label: 'Reserved' },
|
|
13651
|
+
* { value: 'sold', label: 'Sold' }
|
|
13652
|
+
* ]
|
|
13653
|
+
* }
|
|
13654
|
+
* }
|
|
13655
|
+
*
|
|
13656
|
+
* // TECHNICAL_FIELDS (Family 1) auto-added by framework
|
|
13657
|
+
* }
|
|
13658
|
+
* });
|
|
13659
|
+
* ```
|
|
13660
|
+
*
|
|
13661
|
+
* **Result**:
|
|
13662
|
+
* - Family 1 (Technical): `id`, `createdAt`, `updatedAt`, `createdById`, `updatedById`
|
|
13663
|
+
* - Family 2 (Status): `status` with `draft/available/deleted/reserved/sold`
|
|
13664
|
+
* - User fields: `make`, `year`, `images`, `fuelType`, `repairs`
|
|
13665
|
+
*
|
|
13666
|
+
* @version 0.0.1
|
|
13667
|
+
* @since 0.0.1
|
|
13668
|
+
* @author AMBROISE PARK Consulting
|
|
13669
|
+
*/
|
|
13670
|
+
|
|
13671
|
+
/**
|
|
13672
|
+
* Type-safe base fields that all entities inherit
|
|
13673
|
+
* Each field has its specific type for proper TypeScript inference
|
|
13674
|
+
*/
|
|
13675
|
+
interface TypedBaseFields {
|
|
13676
|
+
id: EntityField<'text'>;
|
|
13677
|
+
createdAt: EntityField<'timestamp'>;
|
|
13678
|
+
updatedAt: EntityField<'timestamp'>;
|
|
13679
|
+
createdById: EntityField<'reference'>;
|
|
13680
|
+
updatedById: EntityField<'reference'>;
|
|
13681
|
+
status: EntityField<'select'>;
|
|
13682
|
+
}
|
|
13683
|
+
/**
|
|
13684
|
+
* Default status options for draft/publish/delete workflow
|
|
13685
|
+
* Framework provides 'draft', 'available', 'deleted' - consumers can extend
|
|
13686
|
+
* Labels use translation keys (dndev:status.*) for i18n support
|
|
13687
|
+
*/
|
|
13688
|
+
declare const DEFAULT_STATUS_OPTIONS: readonly [{
|
|
13689
|
+
readonly value: "draft";
|
|
13690
|
+
readonly label: "dndev:status.draft";
|
|
13691
|
+
}, {
|
|
13692
|
+
readonly value: "available";
|
|
13693
|
+
readonly label: "dndev:status.available";
|
|
13694
|
+
}, {
|
|
13695
|
+
readonly value: "deleted";
|
|
13696
|
+
readonly label: "dndev:status.deleted";
|
|
13697
|
+
}];
|
|
13698
|
+
/**
|
|
13699
|
+
* Default status value for new documents (published by default)
|
|
13700
|
+
*/
|
|
13701
|
+
declare const DEFAULT_STATUS_VALUE: "available";
|
|
13702
|
+
/**
|
|
13703
|
+
* Statuses that are hidden from non-admin users
|
|
13704
|
+
*/
|
|
13705
|
+
declare const HIDDEN_STATUSES: readonly ["draft", "deleted"];
|
|
13706
|
+
/**
|
|
13707
|
+
* Fields that are TRULY backend-generated (cannot be set by user)
|
|
13708
|
+
* These are stripped from create operations - backend creates them automatically
|
|
13709
|
+
*
|
|
13710
|
+
* @category Field Families
|
|
13711
|
+
* @constant BACKEND_GENERATED_FIELD_NAMES
|
|
13712
|
+
*/
|
|
13713
|
+
declare const BACKEND_GENERATED_FIELD_NAMES: readonly ["id", "createdAt", "updatedAt", "createdById", "updatedById"];
|
|
13714
|
+
/**
|
|
13715
|
+
* List of technical field names that are auto-generated by the backend
|
|
13716
|
+
* Includes backend-generated fields + status field
|
|
13717
|
+
*
|
|
13718
|
+
* These fields are optional in create schemas (backend creates them automatically).
|
|
13719
|
+
* They can be updated in update operations if provided.
|
|
13720
|
+
*
|
|
13721
|
+
* **Note**: Status is included here for visibility/editability logic but is NOT stripped
|
|
13722
|
+
* from form submissions since users MUST set it. Use BACKEND_GENERATED_FIELD_NAMES for stripping.
|
|
13723
|
+
*
|
|
13724
|
+
* @category Field Families
|
|
13725
|
+
* @constant TECHNICAL_FIELD_NAMES
|
|
13726
|
+
*/
|
|
13727
|
+
declare const TECHNICAL_FIELD_NAMES: readonly ["id", "createdAt", "updatedAt", "createdById", "updatedById", "status"];
|
|
13728
|
+
/**
|
|
13729
|
+
* TypeScript Helper Types for Field Families
|
|
13730
|
+
* @category Field Families
|
|
13731
|
+
*/
|
|
13732
|
+
/** Type for backend-generated field names */
|
|
13733
|
+
type BackendGeneratedField = (typeof BACKEND_GENERATED_FIELD_NAMES)[number];
|
|
13734
|
+
/** Type for the status field */
|
|
13735
|
+
type StatusField = 'status';
|
|
13736
|
+
/** Type for all technical field names */
|
|
13737
|
+
type TechnicalField = (typeof TECHNICAL_FIELD_NAMES)[number];
|
|
13738
|
+
/**
|
|
13739
|
+
* Type guard to check if a field name is a framework-managed field
|
|
13740
|
+
* @param fieldName - Field name to check
|
|
13741
|
+
* @returns True if field is in TECHNICAL_FIELD_NAMES
|
|
13742
|
+
*
|
|
13743
|
+
* @example
|
|
13744
|
+
* ```typescript
|
|
13745
|
+
* if (isFrameworkField('status')) {
|
|
13746
|
+
* // Field is framework-managed (cannot remove)
|
|
13747
|
+
* }
|
|
13748
|
+
* ```
|
|
13749
|
+
*/
|
|
13750
|
+
declare function isFrameworkField(fieldName: string): fieldName is TechnicalField;
|
|
13751
|
+
/**
|
|
13752
|
+
* Type guard to check if a field is backend-generated
|
|
13753
|
+
* @param fieldName - Field name to check
|
|
13754
|
+
* @returns True if field is auto-generated by backend
|
|
13755
|
+
*
|
|
13756
|
+
* @example
|
|
13757
|
+
* ```typescript
|
|
13758
|
+
* if (isBackendGeneratedField('createdAt')) {
|
|
13759
|
+
* // Field is backend-generated (should be stripped on create)
|
|
13760
|
+
* }
|
|
13761
|
+
* ```
|
|
13762
|
+
*/
|
|
13763
|
+
declare function isBackendGeneratedField(fieldName: string): fieldName is BackendGeneratedField;
|
|
13764
|
+
declare const baseFields: TypedBaseFields;
|
|
13765
|
+
|
|
13766
|
+
/**
|
|
13767
|
+
* Defines an entity with validation and default configuration
|
|
13768
|
+
*
|
|
13769
|
+
* Automatically adds technical fields (`id`, `createdAt`, `updatedAt`, `createdById`, `updatedById`)
|
|
13770
|
+
* with `visibility: 'technical'`. User-defined technical fields are merged with defaults, allowing
|
|
13771
|
+
* customization (e.g., `editable: 'admin'`, custom `label`, additional `validation`).
|
|
13772
|
+
*
|
|
13773
|
+
* @param entity - The business entity definition
|
|
13774
|
+
* @returns The validated and configured entity
|
|
13775
|
+
*
|
|
13776
|
+
* @example
|
|
13777
|
+
* ```typescript
|
|
13778
|
+
* export const productEntity = defineEntity({
|
|
13779
|
+
* name: 'Product',
|
|
13780
|
+
* collection: 'products',
|
|
13781
|
+
* fields: {
|
|
13782
|
+
* name: {
|
|
13783
|
+
* type: 'text',
|
|
13784
|
+
* visibility: 'user',
|
|
13785
|
+
* validation: { required: true, minLength: 3 }
|
|
13786
|
+
* },
|
|
13787
|
+
* // Customize technical field (optional)
|
|
13788
|
+
* createdAt: {
|
|
13789
|
+
* editable: 'admin',
|
|
13790
|
+
* label: 'Created Date'
|
|
13791
|
+
* }
|
|
13792
|
+
* },
|
|
13793
|
+
* // Override access defaults (optional)
|
|
13794
|
+
* access: { create: 'guest' } // Public inquiry form
|
|
13795
|
+
* });
|
|
13796
|
+
* ```
|
|
13797
|
+
*
|
|
13798
|
+
* **Technical Fields:**
|
|
13799
|
+
* - Automatically added: `id`, `createdAt`, `updatedAt`, `createdById`, `updatedById`, `status`
|
|
13800
|
+
* - Default: `visibility: 'technical'`, read-only in edit forms
|
|
13801
|
+
* - Customizable: Can override `editable`, `label`, `hint`, `validation` (merged with defaults)
|
|
13802
|
+
*
|
|
13803
|
+
* **Access Configuration:**
|
|
13804
|
+
* - Defaults: `{ read: 'guest', create: 'admin', update: 'admin', delete: 'admin' }`
|
|
13805
|
+
* - Uses role hierarchy: guest (0) < user (1) < admin (2) < super (3)
|
|
13806
|
+
* - Override individual operations: `access: { create: 'guest' }` for public forms
|
|
13807
|
+
* - Field visibility still applies for sensitive data filtering
|
|
13808
|
+
*
|
|
13809
|
+
* **Status Field (Draft/Publish/Delete):**
|
|
13810
|
+
* - Auto-added with `visibility: 'admin'` and options: `['draft', 'available', 'deleted']`
|
|
13811
|
+
* - Default value: `'available'` (new documents are published by default)
|
|
13812
|
+
* - `draft` and `deleted` statuses hidden from non-admin users (server-side filtering)
|
|
13813
|
+
* - `validation.required` on other fields only enforced when status !== 'draft'
|
|
13814
|
+
* - Extend options: `status: { validation: { options: [{ value: 'sold', label: 'sold' }] } }`
|
|
13815
|
+
* - Hide field: `status: { visibility: 'technical' }` if you don't want it in forms
|
|
13816
|
+
*
|
|
13817
|
+
* **Dropdown Options Format:**
|
|
13818
|
+
* - For `select`, `multiselect`, and `radio` field types, options must be defined in `validation.options`
|
|
13819
|
+
* - Options must be an array of objects with `value` (string) and `label` (string)
|
|
13820
|
+
* - Labels can use i18n keys (e.g., `'entities.product.status.active'`) for translation
|
|
13821
|
+
*
|
|
13822
|
+
* @version 0.0.2
|
|
13823
|
+
* @since 0.0.1
|
|
13824
|
+
* @author AMBROISE PARK Consulting
|
|
13825
|
+
*/
|
|
13826
|
+
declare function defineEntity(entity: BusinessEntity): Entity;
|
|
13827
|
+
|
|
13828
|
+
export { AUTH_EVENTS, AUTH_PARTNERS, AUTH_PARTNER_STATE, AuthUserSchema, BACKEND_GENERATED_FIELD_NAMES, BILLING_EVENTS, BREAKPOINT_RANGES, BREAKPOINT_THRESHOLDS, COMMON_TIER_CONFIGS, CONFIDENCE_LEVELS, CONSENT_CATEGORY, CONTEXTS, CheckoutSessionMetadataSchema, CreateCheckoutSessionRequestSchema, CreateCheckoutSessionResponseSchema, CustomClaimsSchema, DEFAULT_ENTITY_ACCESS, DEFAULT_ERROR_MESSAGES, DEFAULT_LAYOUT_PRESET, DEFAULT_STATUS_OPTIONS, DEFAULT_STATUS_VALUE, DEFAULT_SUBSCRIPTION, DENSITY, DoNotDevError, ENVIRONMENTS, EntityHookError, FEATURES, FEATURE_CONSENT_MATRIX, FEATURE_STATUS, FIREBASE_ERROR_MAP, FIRESTORE_ID_PATTERN, GITHUB_PERMISSION_LEVELS, HIDDEN_STATUSES, LAYOUT_PRESET, OAUTH_EVENTS, OAUTH_PARTNERS, PARTNER_ICONS, PAYLOAD_EVENTS, PERMISSIONS, PLATFORMS, PWA_ASSET_TYPES, PWA_DISPLAY_MODES, ProductDeclarationSchema, ProductDeclarationsSchema, ROUTE_SOURCES, STORAGE_SCOPES, STORAGE_TYPES, STRIPE_EVENTS, STRIPE_MODES, SUBSCRIPTION_DURATIONS, SUBSCRIPTION_STATUS, SUBSCRIPTION_TIERS, index_d as ServerUtils, SingletonManager, StripeBackConfigSchema, StripeFrontConfigSchema, StripePaymentSchema, StripeSubscriptionSchema, SubscriptionClaimsSchema, SubscriptionDataSchema, TECHNICAL_FIELD_NAMES, USER_ROLES, UserSubscriptionSchema, WebhookEventSchema, addMonths, addYears, baseFields, calculateSubscriptionEndDate, captureErrorToSentry, checkGitHubAccessSchema, clearSchemaGenerators, commonErrorCodeMappings, compactToISOString, createAsyncSingleton, createDefaultSubscriptionClaims, createDefaultUserProfile, createEntitySchema, createErrorHandler, createMetadata, createMethodProxy, createSchemas, createSingleton, createSingletonWithParams, defineEntity, deleteEntitySchema, detectErrorSource, disconnectOAuthSchema, enhanceSchema, exchangeTokenSchema, filterVisibleFields, formatDate, formatRelativeTime, generateCodeChallenge, generateCodeVerifier, generatePKCEPair, getBreakpointFromWidth, getBreakpointUtils, getCollectionName, getConnectionsSchema, getCurrentTimestamp, getEntitySchema, getRegisteredSchemaTypes, getSchemaType, getVisibleFields, getWeekFromISOString, githubPermissionSchema, githubRepoConfigSchema, grantGitHubAccessSchema, handleError, hasCustomSchemaGenerator, hasMetadata, hasRoleAccess, hasTierAccess, isAuthPartnerId, isBackendGeneratedField, isBreakpoint, isCompactDateString, isFieldVisible, isFrameworkField, isOAuthPartnerId, isPKCESupported, isoToCompactString, lazyImport, listEntitiesSchema, mapToDoNotDevError, maybeTranslate, normalizeToISOString, overrideFeatures, overridePaymentModes, overridePermissions, overrideSubscriptionStatus, overrideSubscriptionTiers, overrideUserRoles, parseDate, parseDateToNoonUTC, parseISODate, parseServerCookie, refreshTokenSchema, registerSchemaGenerator, registerUniqueConstraintValidator, revokeGitHubAccessSchema, showNotification, timestampToISOString, toDateOnly, toISOString, translateArray, translateArrayRange, translateArrayWithIndices, translateObjectArray, updateEntitySchema, updateMetadata, validateAuthPartners, validateAuthSchemas, validateAuthUser, validateBillingSchemas, validateCheckoutSessionMetadata, validateCodeChallenge, validateCodeVerifier, validateCreateCheckoutSessionRequest, validateCreateCheckoutSessionResponse, validateCustomClaims, validateDates, validateDocument, validateEnvVar, validateMetadata, validateOAuthPartners, validateStripeBackConfig, validateStripeFrontConfig, validateSubscriptionClaims, validateSubscriptionData, validateUniqueFields, validateUrl, validateUserSubscription, validateWebhookEvent, withErrorHandling, withGracefulDegradation };
|
|
13829
|
+
export type { AccountLinkResult, AccountLinkingInfo, AdminCheckHookResult, AdminClaims, AggregateConfig, AggregateFilterOperator, AggregateOperation, AggregateRequest, AggregateResponse, ApiResponse, AppConfig, AppCookieCategories, AppMetadata, AppProvidersProps, AssetsPluginConfig, AttemptRecord, AuthAPI, AuthActions, AuthConfig, AuthContextValue, AuthCoreHookResult, AuthError, AuthEventData, AuthEventKey, AuthEventName, AuthMethod, AuthPartner, AuthPartnerButton, AuthPartnerHookResult, AuthPartnerId, AuthPartnerResult, AuthPartnerState, AuthProvider, AuthProviderProps, AuthRedirectHookResult, AuthRedirectOperation, AuthRedirectOptions, AuthResult, AuthState, AuthStateStore, AuthStatus, AuthTokenHookResult, AuthUser, BackendGeneratedField, BaseActions, BaseCredentials, BaseDocument, BaseEntityFields, BasePartnerState, BaseState, BaseStoreActions, BaseStoreState, BaseUserProfile, BasicUserInfo, BillingAPI, BillingAdapter, BillingErrorCode, BillingEvent, BillingEventData, BillingEventKey, BillingEventName, BillingProvider, BillingProviderConfig, BillingRedirectOperation, Breakpoint, BreakpointUtils, BusinessEntity, CachedError, CanAPI, CheckGitHubAccessRequest, CheckoutMode, CheckoutOptions, CheckoutSessionMetadata, ColumnDef, CommonSubscriptionFeatures, CommonTranslations, ConfidenceLevel, ConsentAPI, ConsentActions, ConsentCategory, ConsentState, Context, CookieOptions, CreateCheckoutSessionRequest, CreateCheckoutSessionResponse, CreateEntityData, CreateEntityRequest, CreateEntityResponse, CrudAPI, CrudConfig, CustomClaims, CustomSchemaGenerator, CustomStoreConfig, DateFormatOptions, DateFormatPreset, DateValue, DeleteEntityRequest, DeleteEntityResponse, Density, DnDevLayoutProps, DnDevOverride, DndevFrameworkConfig, DoNotDevCookieCategories, DynamicFormRule, Editable, EffectiveConnectionType, EmailVerificationHookResult, EmailVerificationStatus, Entity, EntityAccessConfig, EntityAccessDefaults, EntityField, EntityHookErrors, EntityMetadata, EntityTemplateProps, EntityTranslations, EnvironmentMode, ErrorCode, ErrorHandlerConfig, ErrorHandlerFunction, ErrorSeverity, ErrorSource, ExchangeTokenParams, ExchangeTokenRequest, FaviconConfig, Feature, FeatureAccessHookResult, FeatureConsentRequirement, FeatureHookResult, FeatureId, FeatureName, FeatureStatus, FeaturesConfig, FeaturesPluginConfig, FeaturesRequiringAnyConsent, FeaturesRequiringConsent, FeaturesWithoutConsent, FieldCondition, FieldType, FieldTypeToValue, FileAsset, FirebaseCallOptions, FirebaseConfig, FirestoreTimestamp, FirestoreUniqueConstraintValidator, FooterConfig, FooterZoneConfig, FormConfig, FormStep, FunctionCallConfig, FunctionCallContext, FunctionCallOptions, FunctionCallResult, FunctionClient, FunctionClientFactoryOptions, FunctionDefaults, FunctionEndpoint, FunctionError, FunctionLoader, FunctionMemory, FunctionMeta, FunctionPlatform, FunctionResponse, FunctionSchema, FunctionSchemas, FunctionSystem, FunctionTrigger, FunctionsConfig, GetCustomClaimsResponse, GetEntityData, GetEntityRequest, GetEntityResponse, GetUserAuthStatusResponse, GitHubPermission, GitHubRepoConfig, GrantGitHubAccessRequest, GroupByDefinition, HandleErrorOptions, HeaderZoneConfig, I18nConfig, I18nPluginConfig, I18nProviderProps, ID, INetworkManager, IStorageManager, IStorageStrategy, Invoice, InvoiceItem, LanguageInfo, LayoutConfig, LayoutInput, LayoutPreset, LegalCompanyInfo, LegalConfig, LegalContactInfo, LegalDirectorInfo, LegalHostingInfo, LegalJurisdictionInfo, LegalSectionsConfig, LegalWebsiteInfo, ListEntitiesRequest, ListEntitiesResponse, ListEntityData, ListOptions, ListResponse, LoadingActions, LoadingState, MergedBarConfig, MetricDefinition, MobileBehaviorConfig, ModalActions, ModalState, MutationResponse, NavigationRoute, NetworkCheckConfig, NetworkConnectionType, NetworkReconnectCallback, NetworkState, NetworkStatus, NetworkStatusHookResult, OAuthAPI, OAuthApiRequestOptions, OAuthCallbackHookResult, OAuthConnection, OAuthConnectionInfo, OAuthConnectionRequest, OAuthConnectionStatus, OAuthCredentials, OAuthEventData, OAuthEventKey, OAuthEventName, OAuthPartner, OAuthPartnerButton, OAuthPartnerHookResult, OAuthPartnerId, OAuthPartnerResult, OAuthPartnerState, OAuthPurpose, OAuthRedirectOperation, OAuthRefreshRequest, OAuthRefreshResponse, OAuthResult, OAuthStoreActions, OAuthStoreState, Observable, OperationSchemas, OrderByClause, PWAAssetType, PWADisplayMode, PWAPluginConfig, PageAuth, PageMeta, PaginationOptions, PartnerButton, PartnerConnectionState, PartnerIconId, PartnerId, PartnerResult, PartnerType, PayloadCacheEventData, PayloadDocument, PayloadDocumentEventData, PayloadEventKey, PayloadEventName, PayloadGlobalEventData, PayloadMediaEventData, PayloadPageRegenerationEventData, PayloadRequest, PayloadUserEventData, PaymentEventData, PaymentMethod, PaymentMethodType, PaymentMode, Permission, Picture, Platform, PresetConfig, PresetRegistry, ProcessPaymentSuccessRequest, ProcessPaymentSuccessResponse, ProductDeclaration, ProviderInstances, QueryConfig, RateLimitConfig, RateLimitManager, RateLimitResult, RateLimitState, RateLimiter, ReadCallback, RedirectOperation, RedirectOverlayActions, RedirectOverlayConfig, RedirectOverlayPhase, RedirectOverlayState, Reference, RefreshSubscriptionRequest, RefreshSubscriptionResponse, RemoveCustomClaimsResponse, ResolvedLayoutConfig, RevokeGitHubAccessRequest, RouteMeta, RouteSource, RoutesPluginConfig, SEOConfig, SchemaMetadata, SchemaWithVisibility, SetCustomClaimsResponse, SidebarZoneConfig, SlotContent, StatusField, StorageOptions, StorageScope, StorageType, Store, StoreApi, StripeBackConfig, StripeCheckoutRequest, StripeCheckoutResponse, StripeCheckoutSessionEventData, StripeConfig, StripeCustomer, StripeCustomerEventData, StripeEventData, StripeEventKey, StripeEventName, StripeFrontConfig, StripeInvoice, StripeInvoiceEventData, StripePayment, StripePaymentIntentEventData, StripePaymentMethod, StripePrice, StripeProduct, StripeProvider, StripeSubscription, StripeSubscriptionData, StripeWebhookEvent, StripeWebhookEventData, Subscription, SubscriptionClaims, SubscriptionConfig, SubscriptionData, SubscriptionDuration, SubscriptionEventData, SubscriptionHookResult, SubscriptionInfo, SubscriptionStatus, SubscriptionTier, SupportedLanguage, TechnicalField, ThemeActions, ThemeInfo, ThemeMode, ThemeState, ThemesPluginConfig, TierAccessHookResult, Timestamp, TokenInfo, TokenResponse, TokenState, TokenStatus, TranslationOptions, TranslationResource, TypedBaseFields, UIFieldOptions, UniqueConstraintValidator, UnsubscribeFn, UpdateEntityData, UpdateEntityRequest, UpdateEntityResponse, UseFunctionsMutationOptions, UseFunctionsQueryOptions, UseTranslationOptionsEnhanced, UserContext, UserProfile, UserProviderData, UserRole, UserSubscription, ValidationRules, ValueTypeForField, Visibility, WebhookEvent, WebhookEventData, WhereClause, WhereOperator, WithMetadata, dndevSchema };
|
package/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ht=Object.defineProperty;var vt=(e,t)=>()=>(e&&(t=e(e=0)),t);var yt=(e,t)=>{for(var r in t)ht(e,r,{get:t[r],enumerable:!0})};import{Buffer as p}from"node:buffer";import{createRequire as bt}from"node:module";import{dirname as St,resolve as Xr}from"node:path";import l from"node:process";import{fileURLToPath as Et}from"node:url";var xt,d,m,o=vt(()=>{"use strict";xt=bt(import.meta.url),d=Et(import.meta.url),m=St(d);typeof globalThis<"u"&&(globalThis.require=xt,globalThis.__filename=d,globalThis.__dirname=m,globalThis.Buffer=p,globalThis.process=l,typeof global>"u"&&(globalThis.global=globalThis))});o();var et={};yt(et,{DEFAULT_ERROR_MESSAGES:()=>H,DoNotDevError:()=>D,SingletonManager:()=>Ce,addMonths:()=>Z,addYears:()=>Ae,calculateSubscriptionEndDate:()=>Er,captureErrorToSentry:()=>xe,commonErrorCodeMappings:()=>X,compactToISOString:()=>ce,createAsyncSingleton:()=>fr,createErrorHandler:()=>L,createMetadata:()=>kt,createMethodProxy:()=>hr,createSingleton:()=>mr,createSingletonWithParams:()=>gr,detectErrorSource:()=>be,filterVisibleFields:()=>Sr,formatDate:()=>we,formatRelativeTime:()=>Nt,generateCodeChallenge:()=>Xe,generateCodeVerifier:()=>Ke,generatePKCEPair:()=>ar,getCurrentTimestamp:()=>_t,getVisibleFields:()=>Ie,getWeekFromISOString:()=>Dt,handleError:()=>O,hasRoleAccess:()=>oe,hasTierAccess:()=>pr,isCompactDateString:()=>le,isFieldVisible:()=>Je,isPKCESupported:()=>sr,isoToCompactString:()=>Rt,lazyImport:()=>dr,mapToDoNotDevError:()=>Ee,maybeTranslate:()=>ir,normalizeToISOString:()=>Pt,parseDate:()=>ue,parseDateToNoonUTC:()=>Ut,parseISODate:()=>xr,parseServerCookie:()=>Ar,showNotification:()=>or,timestampToISOString:()=>Ot,toDateOnly:()=>Mt,toISOString:()=>wt,translateArray:()=>Tt,translateArrayRange:()=>It,translateArrayWithIndices:()=>At,translateObjectArray:()=>Ct,updateMetadata:()=>vr,validateCodeChallenge:()=>lr,validateCodeVerifier:()=>cr,validateEnvVar:()=>Ir,validateMetadata:()=>Cr,validateUrl:()=>Tr,withErrorHandling:()=>nr,withGracefulDegradation:()=>ur});o();o();o();function Tt(e,t,r,i={}){let{minLength:s=0,excludeEmpty:u=!0,customFilter:C}=i;return Array.from({length:r},(A,P)=>{let R=`${t}.${P}`;return e(R)}).filter((A,P)=>{let R=`${t}.${P}`;return!(A===R||u&&A.trim()===""||A.length<s||C&&!C(A,P))})}function Ct(e,t,r,i){return Array.from({length:r},(s,u)=>{let C=`${t}.${u}.${String(i[0])}`;if(e(C)===C)return null;let P={};for(let R of i){let I=`${t}.${u}.${String(R)}`;P[R]=e(I)}return P}).filter(s=>s!==null)}function It(e,t,r,i,s={}){let{minLength:u=0,excludeEmpty:C=!0,customFilter:A}=s;return Array.from({length:i-r},(P,R)=>{let I=r+R,U=`${t}.${I}`;return e(U)}).filter((P,R)=>{let I=r+R,U=`${t}.${I}`;return!(P===U||C&&P.trim()===""||P.length<u||A&&!A(P,I))})}function At(e,t,r,i={}){let{minLength:s=0,excludeEmpty:u=!0,customFilter:C}=i;return Array.from({length:r},(A,P)=>{let R=`${t}.${P}`;return{item:e(R),originalIndex:P}}).filter(({item:A,originalIndex:P})=>{let R=`${t}.${P}`;return!(A===R||u&&A.trim()===""||A.length<s||C&&!C(A,P))})}o();function kt(e){let t=new Date().toISOString();return{_createdAt:t,_updatedAt:t,_createdBy:e,_updatedBy:e}}o();function ce(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],i=t[2],s=t[3],u=t[4],C=t[5],A=new Date(parseInt(r,10),parseInt(i,10)-1,parseInt(s,10),parseInt(u,10),parseInt(C,10));if(isNaN(A.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return A.toISOString()}function Rt(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),u=String(t.getUTCHours()).padStart(2,"0"),C=String(t.getUTCMinutes()).padStart(2,"0");return`${r}${i}${s}:${u}${C}`}function le(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function Pt(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(le(e))return ce(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 _t(){return new Date().toISOString()}function wt(e){return e.toISOString()}function Ot(e){return new Date(e).toISOString()}function Dt(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),i=Math.floor((t.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((i+r.getDay()+1)/7)}, ${t.getFullYear()}`}var M={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function Nt(e,t="en",r={}){if(!e)return"";let{style:i="long",numeric:s="auto",fallbackThreshold:u=M.WEEK}=r,C;if(e instanceof Date)C=e;else if(typeof e=="string")C=new Date(e);else if(typeof e=="number")C=new Date(e);else if(typeof e=="object"&&"toDate"in e)C=e.toDate();else return"";if(isNaN(C.getTime()))return"";let A=new Date,P=C.getTime()-A.getTime(),R=Math.round(P/1e3),I=Math.abs(R);if(I>u)return we(C.toISOString(),t);let U=new Intl.RelativeTimeFormat(t,{style:i,numeric:s});return I<M.MINUTE?U.format(R,"second"):I<M.HOUR?U.format(Math.round(R/M.MINUTE),"minute"):I<M.DAY?U.format(Math.round(R/M.HOUR),"hour"):I<M.WEEK?U.format(Math.round(R/M.DAY),"day"):I<M.MONTH?U.format(Math.round(R/M.WEEK),"week"):I<M.YEAR?U.format(Math.round(R/M.MONTH),"month"):U.format(Math.round(R/M.YEAR),"year")}function Ft(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 we(e,t="en",r="long"){if(!e)return"";let i;if(e instanceof Date)i=e;else if(typeof e=="string")i=new Date(e);else if(typeof e=="number")i=new Date(e);else if(typeof e=="object"&&"toDate"in e)i=e.toDate();else return"";if(isNaN(i.getTime()))return"";let s=typeof r=="string"?Ft(r):r;return new Intl.DateTimeFormat(t,s).format(i)}function ue(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(le(t))try{return ce(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,i=new Date(r);return isNaN(i.getTime())?void 0:i.toISOString()}}}function Ut(e){let t=ue(e);if(!t)return;let r=new Date(t);return r.setUTCHours(12,0,0,0),r.toISOString()}function Mt(e){let t=ue(e);return t&&t.split("T")[0]||""}o();o();o();o();o();var q={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function sn(e){Object.assign(q,e)}var de={FREE:"free",PRO:"pro",PREMIUM:"premium"};function cn(e){Object.assign(de,e)}var pe={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function ln(e){Object.assign(pe,e)}var me={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 un(e){Object.assign(me,e)}o();import*as a from"valibot";o();o();var G={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function mn(e){Object.assign(G,e)}var te={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function gn(e){Object.assign(te,e)}var fn={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function hn(e){return{tier:"free",status:"active",subscriptionId:null,customerId:e,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var Oe={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}},vn={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};o();import*as n from"valibot";var De=n.object({userId:n.string(),productId:n.optional(n.string()),priceId:n.string(),successUrl:n.pipe(n.string(),n.url()),cancelUrl:n.pipe(n.string(),n.url()),customerEmail:n.optional(n.pipe(n.string(),n.email())),userEmail:n.optional(n.pipe(n.string(),n.email())),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean()),mode:n.optional(n.picklist([te.PAYMENT,te.SUBSCRIPTION]))}),Ne=n.object({sessionId:n.string(),sessionUrl:n.nullable(n.pipe(n.string(),n.url()))}),Fe=n.object({userId:n.string(),tier:n.string(),status:n.picklist(Object.values(G)),subscriptionId:n.nullable(n.string()),customerId:n.string(),subscriptionEnd:n.nullable(n.pipe(n.string(),n.isoTimestamp())),cancelAtPeriodEnd:n.boolean(),updatedAt:n.pipe(n.string(),n.isoTimestamp())}),Ue=n.object({tier:n.string(),subscriptionId:n.nullable(n.string()),customerId:n.string(),status:n.picklist(Object.values(G)),subscriptionEnd:n.nullable(n.pipe(n.string(),n.isoTimestamp())),cancelAtPeriodEnd:n.boolean(),updatedAt:n.pipe(n.string(),n.isoTimestamp()),isDefault:n.optional(n.boolean())}),Me=n.object({id:n.string(),type:n.string(),data:n.object({object:n.any()}),created:n.pipe(n.string(),n.isoTimestamp())}),Le=n.looseObject({userId:n.optional(n.string()),firebaseUid:n.optional(n.string()),productType:n.optional(n.string())});function En(e){return n.safeParse(De,e)}function xn(e){return n.safeParse(Ne,e)}function Tn(e){return n.safeParse(Fe,e)}function Cn(e){return n.safeParse(Ue,e)}function In(e){return n.safeParse(Me,e)}function An(e){return n.safeParse(Le,e)}var Lt=n.object({type:n.literal("StripePayment"),name:n.pipe(n.string(),n.minLength(1,"Product name is required")),description:n.optional(n.string()),price:n.string(),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:n.pipe(n.string(),n.minLength(1,"Stripe price ID is required")),tier:n.pipe(n.string(),n.minLength(1,"Tier is required")),duration:n.pipe(n.string(),n.minLength(1,"Duration is required")),allowPromotionCodes:n.optional(n.boolean()),metadata:n.optional(n.record(n.string(),n.string()))}),Bt=n.object({type:n.literal("StripeSubscription"),name:n.pipe(n.string(),n.minLength(1,"Product name is required")),description:n.optional(n.string()),price:n.string(),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:n.pipe(n.string(),n.minLength(1,"Stripe price ID is required")),tier:n.pipe(n.string(),n.minLength(1,"Tier is required")),duration:n.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:n.optional(n.boolean()),metadata:n.optional(n.record(n.string(),n.string()))}),qt=n.variant("type",[Lt,Bt]),kn=n.record(n.string(),qt),Vt=n.record(n.string(),n.object({name:n.string(),price:n.string(),currency:n.string(),description:n.optional(n.string()),features:n.optional(n.array(n.string())),priceId:n.string(),allowPromotionCodes:n.optional(n.boolean())})),jt=n.record(n.string(),n.object({type:n.picklist(["StripePayment","StripeSubscription"]),name:n.string(),price:n.number(),currency:n.string(),priceId:n.string(),tier:n.string(),duration:n.string(),description:n.optional(n.string()),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean())}));function Rn(e){return n.parse(Vt,e)}function Pn(e){return n.parse(jt,e)}function _n(){let e={createCheckoutSessionRequest:n.safeParse(De,{}),createCheckoutSessionResponse:n.safeParse(Ne,{}),subscriptionData:n.safeParse(Fe,{}),subscriptionClaims:n.safeParse(Ue,{}),webhookEvent:n.safeParse(Me,{}),checkoutSessionMetadata:n.safeParse(Le,{})};return{success:Object.values(e).every(t=>t.success),results:e}}o();var Be=a.object({id:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),emailVerified:a.optional(a.boolean()),lastLoginAt:a.optional(a.string()),providerData:a.optional(a.array(a.object({providerId:a.string(),uid:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),phoneNumber:a.optional(a.nullable(a.string()))}))),role:a.optional(a.picklist(Object.values(q))),customClaims:a.optional(a.record(a.string(),a.any()))}),ge=a.object({userId:a.string(),tier:a.picklist(Object.values(de)),status:a.picklist(Object.values(G)),isActive:a.optional(a.boolean()),features:a.optional(a.array(a.string())),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),qe=a.object({role:a.optional(a.picklist(Object.values(q))),subscription:a.optional(ge),features:a.optional(a.array(a.picklist(Object.values(pe)))),permissions:a.optional(a.array(a.picklist(Object.values(me)))),githubAccess:a.optional(a.object({username:a.optional(a.string()),teamAccess:a.optional(a.array(a.string())),repoAccess:a.optional(a.array(a.string()))}))});function Vn(e){return a.safeParse(Be,e)}function jn(e){return a.safeParse(ge,e)}function Hn(e){return a.safeParse(qe,e)}function $n(){let e={authUser:a.safeParse(Be,{}),userSubscription:a.safeParse(ge,{}),customClaims:a.safeParse(qe,{}),getUserAuthStatus:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1))}),{}),getCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.optional(a.array(a.string()))}),{}),setCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claims:a.record(a.string(),a.any()),merge:a.optional(a.boolean(),!1)}),{}),removeCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.pipe(a.array(a.string()),a.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}o();var zn={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Yn(e){return{userId:e,role:"user",preferences:{},metadata:{}}}o();var ro={VITE:"vite",NEXTJS:"nextjs",UNKNOWN:"unknown"},no={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},oo={CLIENT:"client",SERVER:"server",BUILD:"build"},io={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},ao={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},so={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},co={USER:"user",GLOBAL:"global",SESSION:"session"},lo={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},uo={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},po={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};o();o();o();import*as x from"valibot";o();var fe={create:"admin",read:"guest",update:"admin",delete:"admin"};var re=/^[0-9a-zA-Z]+$/,xo=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),data:x.record(x.string(),x.unknown()),idempotencyKey:x.optional(x.string())}),To=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required"))}),Co=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required")),data:x.record(x.string(),x.unknown()),merge:x.optional(x.boolean(),!1)}),Io=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required"))}),Ao=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),limit:x.optional(x.pipe(x.number(),x.minValue(1),x.maxValue(1e3)),50),offset:x.optional(x.pipe(x.number(),x.minValue(0)),0),orderBy:x.optional(x.string()),orderDirection:x.optional(x.picklist(["asc","desc"]),"desc"),where:x.optional(x.array(x.object({field:x.string(),operator:x.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:x.any()})))});o();o();o();var he={"permission-denied":{type:"PERMISSION_DENIED",message:"You do not have permission to perform this action"},"not-found":{type:"NOT_FOUND",message:"The requested resource was not found"},"already-exists":{type:"ALREADY_EXISTS",message:"The resource already exists"},"invalid-argument":{type:"VALIDATION_ERROR",message:"Invalid argument provided"}},Ve=class extends Error{type;originalError;constructor(t,r,i){super(r),this.name="EntityHookError",this.type=t,this.originalError=i}},D=class e extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r="internal",i){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=i?.details,this.source=i?.source,this.originalError=i?.originalError,this.context=i?.context,this.displayable=i?.displayable??!0,this.userMessageProvided=i?.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}}};o();o();var qo={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"};o();var Ho={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"};o();var Wo={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"};o();var Ko={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"};o();var Qo={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"};o();o();o();o();import"valibot";o();o();o();o();o();o();var ve={mobile:0,tablet:768,laptop:1024,desktop:1440},Ht={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function $t(e){return e>=ve.desktop?"desktop":e>=ve.laptop?"laptop":e>=ve.tablet?"tablet":"mobile"}function Ei(e,t){let r=Ht[t];return e>=r.min&&e<=r.max}function xi(e,t){let r=$t(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"}}o();var Ii="landing";o();o();o();o();o();var je=["pull","push","admin","maintain","triage"];o();import"valibot";o();import*as E from"valibot";var ye=E.object({owner:E.pipe(E.string(),E.minLength(1,"Repository owner is required")),repo:E.pipe(E.string(),E.minLength(1,"Repository name is required"))}),Gt=E.picklist([...je]),ji=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye,permission:E.optional(Gt,"push"),customClaims:E.optional(E.record(E.string(),E.any()))}),Hi=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye}),$i=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye}),Gi=E.object({provider:E.string(),purpose:E.picklist(["authentication","api-access"]),code:E.pipe(E.string(),E.minLength(1,"Authorization code is required")),redirectUri:E.pipe(E.string(),E.url("Valid redirect URI is required")),codeVerifier:E.optional(E.string()),state:E.optional(E.string()),instance:E.optional(E.pipe(E.string(),E.url()))}),Wi=E.object({provider:E.string(),refreshToken:E.pipe(E.string(),E.minLength(1,"Refresh token is required")),redirectUri:E.pipe(E.string(),E.url("Valid redirect URI is required"))}),zi=E.object({provider:E.string()}),Yi=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required"))});o();o();var ra={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"};o();import*as T from"valibot";var He=T.object({name:T.string(),color:T.string(),icon:T.string(),customParameters:T.optional(T.record(T.string(),T.string())),button:T.object({backgroundColor:T.string(),textColor:T.string(),borderColor:T.string(),hoverBackgroundColor:T.string(),focusOutlineColor:T.string(),fontWeight:T.optional(T.string(),"500"),textKey:T.optional(T.string())})}),Wt=T.object({...He.entries,type:T.picklist(["auth","both"]),scopes:T.optional(T.array(T.string())),firebaseProviderId:T.optional(T.string())}),ne=T.union([T.literal(""),T.pipe(T.string(),T.url())]),zt=T.object({authUrl:ne,tokenUrl:ne,profileUrl:ne,revokeUrl:T.optional(ne)}),Yt=T.object({authentication:T.optional(T.array(T.string())),"api-access":T.array(T.string())}),Kt=T.optional(T.object({pkce:T.optional(T.boolean(),!1),codeChallengeMethod:T.optional(T.picklist(["S256","plain"]),"S256")})),Xt=T.object({...He.entries,type:T.picklist(["oauth","both"]),scopes:Yt,endpoints:zt,capabilities:Kt}),$e={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"}}},Ge={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"}}},Zt=T.record(T.string(),Wt),Qt=T.record(T.string(),Xt);function ia(){return T.safeParse(Zt,$e)}function aa(){return T.safeParse(Qt,Ge)}function sa(e){return e in $e}function ca(e){return e in Ge}o();o();o();o();o();var We={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Sa={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"},Ea={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},xa={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:We.ANALYTICS},marketing:{requiresConsent:We.MARKETING}};o();o();o();o();o();function be(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"}o();import*as Ye from"valibot";o();function L(e){return(t,r)=>{if(t instanceof D)return t;if(typeof t!="object"||t===null){let A=typeof t=="string"?t:e.defaultErrorMessage;return new D(r||A,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let i;e.extractErrorCode?i=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(i=t.code);let s=e.defaultErrorCode;i&&e.errorCodeMapping&&i in e.errorCodeMapping&&(s=e.errorCodeMapping[i]);let u;e.extractErrorMessage?u=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(u=t.message),i&&e.friendlyMessageMapping&&i in e.friendlyMessageMapping&&(u=e.friendlyMessageMapping[i]),u||(u=e.defaultErrorMessage);let C;return e.processMetadata?C=e.processMetadata(t):(C={originalError:t},i&&(C.originalCode=i)),"originalError"in C||(C.originalError=t),new D(r||u,s,{details:C,source:e.errorSource})}}var X={"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 H={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",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."},Jt={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"},Se={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},V={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",...X},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",...X},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(Jt).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:X,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:H.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:H["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:H.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},er=e=>e instanceof Ye.ValiError?new D(H["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):L(V.validation)(e),tr=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Se){let t=e,r=Se[t.type]||"unknown";return new D(t.message||H[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&he[e.code]){let t=e,r=he[t.code];if(r){let i=Se[r.type]||"unknown";return new D(r.message||H[i],i,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return L(V.entity)(e)},ze={auth:L(V.auth),oauth:L(V.oauth),api:L(V.api),firebase:L(V.firebase),ui:L(V.ui),validation:er,entity:tr,unknown:L(V.unknown)};function Ee(e,t,r){return e instanceof D?e:(ze[t]||ze.unknown)(e,r)}o();function xe(e,t,r={}){let i=globalThis.Sentry;i&&i.withScope(s=>{s.setTag("errorSource",t),s.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([u,C])=>{if(typeof C!="function"&&u!=="originalError")try{s.setExtra(u,C)}catch{s.setExtra(u,`[${typeof C}]`)}}),Object.entries(r).forEach(([u,C])=>{if(typeof C!="function")try{s.setExtra(`context.${u}`,C)}catch{s.setExtra(`context.${u}`,`[${typeof C}]`)}}),(e.details?.userId||r.userId)&&s.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),i.captureException(e)})}function rr(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof l<"u"&&l.env?"production".toLowerCase()!=="production":!0}function O(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:i,context:s={},log:u=!0,reportToSentry:C=!0,showNotification:A=!1,severity:P="error"}=r,R=be(e),I=e instanceof D?e:Ee(e,R,i);if(i&&!I.userMessageProvided&&(I.message.includes("Error")||I.message.includes("Failed")||I.message.length<10?I=new D(i,I.code,{details:{...I.details,originalMessage:I.message},source:R,userMessageProvided:!0}):I=new D(I.message,I.code,{details:{...I.details,userMessage:i},source:R,userMessageProvided:!0})),u){let U=rr()||typeof window<"u"&&window.__DNDEV_DEBUG,Y={code:I.code,message:I.message,source:R};switch(P){case"warning":break;case"info":break;case"success":break;default:}}return C&&xe(I,R,s),I}function nr(e,t){return async(...r)=>{try{return await e(...r)}catch(i){throw O(i,t)}}}function or(e,t="info",r){let i=Date.now().toString();return i}o();function ir(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}o();function Ke(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Ze(e)}async function Xe(e){let r=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",r);return Ze(new Uint8Array(i))}async function ar(){let e=Ke(),t=await Xe(e);return{codeVerifier:e,codeChallenge:t}}function Ze(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function sr(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function cr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function lr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}o();async function ur(e,t,r){try{return await e()}catch{return t(),!1}}o();var Te=new Map;function dr(e,t){if(Te.has(t))return Te.get(t);let r=e();return Te.set(t,r),r}o();var Qe={[q.GUEST]:0,[q.USER]:1,[q.ADMIN]:2,[q.SUPER]:3};function oe(e,t){if(!e)return!1;let r=Qe[e]??-1,i=Qe[t]??1/0;return r>=i}o();function pr(e,t,r){if(!e)return!1;let i=r??Oe,s=i[e]?.level??-1,u=i[t]?.level??1/0;return s>=u}o();function mr(e,...t){let r=null,i=!1;return function(){if(r!==null)return r;if(i)throw new Error("Circular dependency detected in singleton initialization");i=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{i=!1}}}function gr(e){let t=null,r=!1;return function(...s){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(...s):t=e(...s),t}finally{r=!1}}}function fr(e){let t=null,r=!1,i=null;return async function(){if(t!==null)return t;if(r&&i)return i;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return i=e(),t=await i,t}finally{r=!1,i=null}}}function hr(e,t){return new Proxy({},{get(r,i){if(t.includes(i)){let u=e(),C=u[i];return typeof C=="function"?C.bind(u):C}return e()[i]}})}var Ce=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(t,r,i={}){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(i.ssrSafe===!1&&typeof window>"u"){if(i.fallbackFactory){let s=i.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let s=await r();return this.instances.set(t,s),this.initialized.add(t),s}catch(s){if(i.cacheFailures&&this.initialized.add(t),i.fallbackFactory){let u=i.fallbackFactory();return this.instances.set(t,u),this.initialized.add(t),u}throw s}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()}};o();function vr(e){return{_updatedAt:new Date().toISOString(),_updatedBy:e}}o();o();import"valibot";o();import"valibot";function yr(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function br(e){if(yr(e))return e.visibility}function Je(e,t){let r=e??"guest";return r==="hidden"?!1:r==="technical"?oe(t,"admin"):oe(t,r)}function Ie(e,t){let r=e;if(!r||typeof r!="object"||!r.entries)return[];let i=r.entries,s=[];for(let[u,C]of Object.entries(i)){let A=br(C);Je(A,t)&&s.push(u)}return s}function Sr(e,t,r){if(!e)return{};let i=Ie(t,r),s={};for(let u of i)Object.prototype.hasOwnProperty.call(e,u)&&(s[u]=e[u]);return s}o();function Z(e,t){let r=new Date(e),i=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==i&&r.setDate(0),r}function Ae(e,t){let r=new Date(e),i=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==i&&r.setDate(0),r}function Er(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=Z(t,1):e==="3months"?r=Z(t,3):e==="6months"?r=Z(t,6):e==="1year"?r=Ae(t,1):e==="2years"?r=Ae(t,2):r=Z(t,1),r.toISOString()}function xr(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}o();function Tr(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 Cr(e){let t={};for(let[r,i]of Object.entries(e)){if(typeof i!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof i}`);let s=i.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(s.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]=s}return t}function Ir(e,t=!0){let r=l.env[e];if(t&&!r)throw new Error(`Required environment variable '${e}' is not set`);return r||""}o();function Ar(e,t){if(!e)return null;let r=`${encodeURIComponent(t)}=`,i=e.split(";");for(let s=0;s<i.length;s++){let u=i[s];if(u){for(;u.charAt(0)===" ";)u=u.substring(1,u.length);if(u.indexOf(r)===0)return decodeURIComponent(u.substring(r.length,u.length))}}return null}o();o();o();o();import"valibot";function Oc(e,t){let r=e;return r.metadata=t,r}o();import*as c from"valibot";var Q=new Map;function k(e,t){Q.set(e,t)}function Uc(e){return Q.has(e)}function Mc(){return Array.from(Q.keys())}function Lc(){Q.clear()}function _(e,t){return t?e:c.nullish(e)}var ie=e=>{let t=[];e.validation?.minLength!==void 0&&t.push(c.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(c.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(c.regex(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?c.pipe(c.string(),...t):c.string();return _(r,e.validation?.required)},kr=e=>{let t=c.pipe(c.string(),c.email("Invalid email address"));return _(t,e.validation?.required)},Rr=e=>{let t=e.validation?.minLength!==void 0?c.pipe(c.string(),c.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):c.string();return _(t,e.validation?.required)},Pr=e=>{let t=c.pipe(c.string(),c.url("Invalid URL"));return _(t,e.validation?.required)},tt=e=>{let t=[];e.validation?.min!==void 0&&t.push(c.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(c.maxValue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?c.pipe(c.number(),...t):c.number();return _(r,e.validation?.required)},rt=e=>{let t=c.boolean();return _(t,e.validation?.required)},W=e=>{let t=c.pipe(c.string(),c.isoTimestamp("Invalid date format"));return _(t,e.validation?.required)},at=c.object({url:c.string(),filename:c.string(),size:c.number(),mimeType:c.nullish(c.string()),uploadedAt:c.nullish(c.string())}),nt=e=>{let t=c.nullable(at);return _(t,e.validation?.required)},ot=e=>{let t=c.array(at);return _(t,e.validation?.required)},st=c.object({fullUrl:c.string(),thumbUrl:c.string()}),_r=e=>_(st,e.validation?.required),wr=e=>{let t=c.array(st);return _(t,e.validation?.required)},Or=e=>{let t=c.object({lat:c.number(),lng:c.number()});return _(t,e.validation?.required)},Dr=e=>{let t=c.object({formatted_address:c.string(),latitude:c.number(),longitude:c.number(),street_number:c.nullish(c.string()),route:c.nullish(c.string()),locality:c.nullish(c.string()),administrative_area_level_1:c.nullish(c.string()),administrative_area_level_2:c.nullish(c.string()),country:c.nullish(c.string()),postal_code:c.nullish(c.string())});return _(t,e.validation?.required)},Nr=e=>{let t=c.record(c.string(),c.unknown());return _(t,e.validation?.required)},Fr=e=>{let t=c.array(c.unknown());return _(t,e.validation?.required)},ke=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let i=t.map(u=>u.value),s=c.picklist(i);return _(s,e.validation?.required)}let r=c.union([c.string(),c.number()]);return _(r,e.validation?.required)},Ur=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let i=t.map(u=>u.value),s=c.array(c.picklist(i));return _(s,e.validation?.required)}let r=c.array(c.string());return _(r,e.validation?.required)},Mr=e=>{let t=c.pipe(c.string(),c.regex(re,"Invalid ID format"));return _(t,e.validation?.required)},Re=e=>{let t=c.string();return _(t,e.validation?.required)},Lr=e=>{let t=c.string();return _(t,e.validation?.required)},it=()=>c.never(),Br=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let i=[t.checkedValue,t.uncheckedValue],s=c.picklist(i);return _(s,e.validation?.required)}let r=c.boolean();return _(r,e.validation?.required)};function qr(){k("text",ie),k("textarea",ie),k("richtext",ie),k("color",ie),k("email",kr),k("password",Rr),k("url",Pr),k("tel",Lr),k("number",tt),k("range",tt),k("boolean",rt),k("checkbox",rt),k("date",W),k("datetime-local",W),k("time",W),k("week",W),k("month",W),k("timestamp",W),k("file",nt),k("files",ot),k("document",nt),k("documents",ot),k("image",_r),k("images",wr),k("geopoint",Or),k("address",Dr),k("map",Nr),k("array",Fr),k("select",ke),k("multiselect",Ur),k("radio",ke),k("combobox",ke),k("switch",Br),k("reference",Mr),k("hidden",Re),k("avatar",Re),k("badge",Re),k("submit",it),k("reset",it)}qr();function J(e){if(e.validation?.schema){let i=e.validation.schema;return _(i,e.validation?.required)}let t=Q.get(e.type);if(t){let i=t(e);if(i!==null)return i}let r=c.unknown();return _(r,e.validation?.required)}o();var ct=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function lt(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function ae(e,t=""){if(Array.isArray(e))e.forEach((r,i)=>{let s=`${t}[${i}]`;if(typeof r=="string"&<(r)){if(!ct.test(r))throw O({userMessage:`Invalid date format for ${s}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:s,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&ae(r,s)});else if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e)){let s=t?`${t}.${r}`:r;if(typeof i=="string"&<(i)){if(!ct.test(i))throw O({userMessage:`Invalid date format for field "${s}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${i}"`,context:{field:s,value:i},severity:"error"})}else typeof i=="object"&&i!==null&&ae(i,s)}}o();import*as dt from"valibot";o();var Pe={};function Gc(e){Pe.uniqueConstraintValidator=e}async function ut(e,t,r){let{uniqueFields:i=[],collection:s}=e.metadata;i.length!==0&&Pe.uniqueConstraintValidator&&await Promise.all(i.map(async({field:u,errorMessage:C})=>{let A=t[u];if(A==null)return;if(await Pe.uniqueConstraintValidator.checkDuplicate(s,u,A,r))throw O({userMessage:C||`${u} must be unique`,code:"already-exists",context:{field:u}})}))}async function Xc(e,t,r,i){dt.parse(e,t),ae(t),await ut(e,t,i),e.metadata.customValidate&&await e.metadata.customValidate(t,r)}o();function Vr(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function sl(e){if(!Vr(e)){let t=e,r=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw O(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return e.metadata.collection}o();var _e=[{value:"draft",label:"dndev:status.draft"},{value:"available",label:"dndev:status.available"},{value:"deleted",label:"dndev:status.deleted"}],dl="available",pl=["draft","deleted"],z=["id","createdAt","updatedAt","createdById","updatedById"],jr=[...z,"status"];function ml(e){return jr.includes(e)}function gl(e){return z.includes(e)}var w={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[..._e]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0,pattern:re.source}},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}}};o();function Hr(e,t){if(!t||t.length===0)return e.map(s=>({value:s.value,label:s.label}));let r=e.map(s=>({value:s.value,label:s.label})),i=new Set(e.map(s=>s.value));for(let s of t)i.has(s.value)||r.push(s);return r}function $r(e){let{form:t,fields:r}=e,i=Object.keys(r);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw O(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 s=t.steps.flatMap(P=>P.fields),u=s.filter(P=>!i.includes(P));if(u.length>0)throw O(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${u.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${u.join(", ")}`,context:{entityName:e.name,invalidFields:u,operation:"validateFormConfig"},severity:"error"});let C=new Set(s);i.filter(P=>!C.has(P)).length>0}t.rules&&t.rules.forEach((s,u)=>{let A=(Array.isArray(s.condition)?s.condition.map(I=>I.field):[s.condition.field]).filter(I=>!i.includes(I));if(A.length>0)throw O(new Error(`Dynamic form rule ${u} for entity '${e.name}' references non-existent condition fields: ${A.join(", ")}`),{userMessage:`Dynamic form rule ${u} for entity '${e.name}' references non-existent condition fields: ${A.join(", ")}`,context:{entityName:e.name,ruleIndex:u,invalidFields:A,operation:"validateFormConfig"},severity:"error"});let R=[...s.showFields||[],...s.hideFields||[],...s.disableFields||[],...s.enableFields||[]].filter(I=>!i.includes(I));if(R.length>0)throw O(new Error(`Dynamic form rule ${u} for entity '${e.name}' references non-existent affected fields: ${R.join(", ")}`),{userMessage:`Dynamic form rule ${u} for entity '${e.name}' references non-existent affected fields: ${R.join(", ")}`,context:{entityName:e.name,ruleIndex:u,invalidFields:R,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([s,u])=>{if(u.dependsOn&&!i.includes(u.dependsOn.field))throw O(new Error(`Field '${s}' in entity '${e.name}' depends on non-existent field: ${u.dependsOn.field}`),{userMessage:`Field '${s}' in entity '${e.name}' depends on non-existent field: ${u.dependsOn.field}`,context:{entityName:e.name,fieldName:s,dependsOnField:u.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Gr(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 Sl(e){try{$r(e);let t=Gr(e),r={...e.fields,...w,...e.fields.createdAt&&{createdAt:{...w.createdAt,...e.fields.createdAt,type:w.createdAt.type,visibility:w.createdAt.visibility}},...e.fields.updatedAt&&{updatedAt:{...w.updatedAt,...e.fields.updatedAt,type:w.updatedAt.type,visibility:w.updatedAt.visibility}},...e.fields.createdById&&{createdById:{...w.createdById,...e.fields.createdById,type:w.createdById.type,visibility:w.createdById.visibility}},...e.fields.updatedById&&{updatedById:{...w.updatedById,...e.fields.updatedById,type:w.updatedById.type,visibility:w.updatedById.visibility}},...e.fields.status&&{status:{...w.status,...e.fields.status,type:w.status.type,visibility:w.status.visibility,editable:w.status.editable,validation:{...w.status.validation,required:!0,nullable:e.fields.status.validation?.nullable,options:Hr(_e,e.fields.status.validation?.options)}}}};if(e.listFields){let s=new Set(Object.keys(r)),u=e.listFields.filter(C=>!s.has(C));if(u.length>0)throw O(new Error(`Entity '${e.name}' defines listFields that do not exist: ${u.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${u.join(", ")}`,context:{entityName:e.name,invalidFields:u,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let s=new Set(Object.keys(r)),u=e.listCardFields.filter(C=>!s.has(C));if(u.length>0)throw O(new Error(`Entity '${e.name}' defines listCardFields that do not exist: ${u.join(", ")}`),{userMessage:`Entity '${e.name}' defines listCardFields that do not exist: ${u.join(", ")}`,context:{entityName:e.name,invalidFields:u,operation:"defineEntity"},severity:"error"})}let i={...fe,...e.access||{}};return{...e,form:t,fields:r,access:i}}catch(t){throw O(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}o();import*as B from"valibot";function ee(e,t){return Object.assign(e,{visibility:t})}function $(e,t){let r=e;return r.metadata={collection:t.collection,entity:t.name},r}function pt(e){let t=J(e);return ee(t,e.visibility)}function mt(e){let t=J({...e,validation:{...e.validation,required:!1}});return ee(t,e.visibility)}function Al(e){let t=e.fields,r={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(r[N]=pt(F));let i=$(B.object(r),e),s={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(z.includes(N)||(s[N]=pt(F)));let u=$(B.object(s),e),C={};for(let[N,F]of Object.entries(t))if(F.visibility!=="hidden"&&!z.includes(N))if(N==="status"){let j=B.literal("draft");C[N]=ee(j,F.visibility)}else C[N]=mt(F);let A=$(B.object(C),e),P={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(z.includes(N)||(P[N]=mt(F)));P.id=ee(J(w.id),"technical");let R=$(B.object(P),e),I;if(e.listFields&&e.listFields.length>0){let N=["id","status"],F=[...new Set([...N,...e.listFields])];I={};for(let j of F){let K=r[j];K&&(I[j]=K)}}else I=r;let U=$(B.object(I),e),Y,se=e.listCardFields??e.listFields;if(se&&se.length>0){let N=["id","status"],F=[...new Set([...N,...se])];Y={};for(let j of F){let K=r[j];K&&(Y[j]=K)}}else Y=r;let gt=$(B.object(Y),e),ft=$(B.object({id:ee(J(w.id),"technical")}),e);return{create:u,draft:A,update:R,get:i,list:U,listCard:gt,delete:ft}}export{qo as AUTH_EVENTS,$e as AUTH_PARTNERS,zn as AUTH_PARTNER_STATE,Be as AuthUserSchema,z as BACKEND_GENERATED_FIELD_NAMES,Ho as BILLING_EVENTS,Ht as BREAKPOINT_RANGES,ve as BREAKPOINT_THRESHOLDS,Oe as COMMON_TIER_CONFIGS,io as CONFIDENCE_LEVELS,We as CONSENT_CATEGORY,oo as CONTEXTS,Le as CheckoutSessionMetadataSchema,De as CreateCheckoutSessionRequestSchema,Ne as CreateCheckoutSessionResponseSchema,qe as CustomClaimsSchema,fe as DEFAULT_ENTITY_ACCESS,H as DEFAULT_ERROR_MESSAGES,Ii as DEFAULT_LAYOUT_PRESET,_e as DEFAULT_STATUS_OPTIONS,dl as DEFAULT_STATUS_VALUE,vn as DEFAULT_SUBSCRIPTION,Ea as DENSITY,D as DoNotDevError,no as ENVIRONMENTS,Ve as EntityHookError,pe as FEATURES,xa as FEATURE_CONSENT_MATRIX,ao as FEATURE_STATUS,he as FIREBASE_ERROR_MAP,re as FIRESTORE_ID_PATTERN,je as GITHUB_PERMISSION_LEVELS,pl as HIDDEN_STATUSES,Sa as LAYOUT_PRESET,Wo as OAUTH_EVENTS,Ge as OAUTH_PARTNERS,ra as PARTNER_ICONS,Ko as PAYLOAD_EVENTS,me as PERMISSIONS,ro as PLATFORMS,uo as PWA_ASSET_TYPES,lo as PWA_DISPLAY_MODES,qt as ProductDeclarationSchema,kn as ProductDeclarationsSchema,po as ROUTE_SOURCES,co as STORAGE_SCOPES,so as STORAGE_TYPES,Qo as STRIPE_EVENTS,te as STRIPE_MODES,fn as SUBSCRIPTION_DURATIONS,G as SUBSCRIPTION_STATUS,de as SUBSCRIPTION_TIERS,et as ServerUtils,Ce as SingletonManager,jt as StripeBackConfigSchema,Vt as StripeFrontConfigSchema,Lt as StripePaymentSchema,Bt as StripeSubscriptionSchema,Ue as SubscriptionClaimsSchema,Fe as SubscriptionDataSchema,jr as TECHNICAL_FIELD_NAMES,q as USER_ROLES,ge as UserSubscriptionSchema,Me as WebhookEventSchema,Z as addMonths,Ae as addYears,w as baseFields,Er as calculateSubscriptionEndDate,xe as captureErrorToSentry,$i as checkGitHubAccessSchema,Lc as clearSchemaGenerators,X as commonErrorCodeMappings,ce as compactToISOString,fr as createAsyncSingleton,hn as createDefaultSubscriptionClaims,Yn as createDefaultUserProfile,xo as createEntitySchema,L as createErrorHandler,kt as createMetadata,hr as createMethodProxy,Al as createSchemas,mr as createSingleton,gr as createSingletonWithParams,Sl as defineEntity,Io as deleteEntitySchema,be as detectErrorSource,zi as disconnectOAuthSchema,Oc as enhanceSchema,Gi as exchangeTokenSchema,Sr as filterVisibleFields,we as formatDate,Nt as formatRelativeTime,Xe as generateCodeChallenge,Ke as generateCodeVerifier,ar as generatePKCEPair,$t as getBreakpointFromWidth,xi as getBreakpointUtils,sl as getCollectionName,Yi as getConnectionsSchema,_t as getCurrentTimestamp,To as getEntitySchema,Mc as getRegisteredSchemaTypes,J as getSchemaType,Ie as getVisibleFields,Dt as getWeekFromISOString,Gt as githubPermissionSchema,ye as githubRepoConfigSchema,ji as grantGitHubAccessSchema,O as handleError,Uc as hasCustomSchemaGenerator,Vr as hasMetadata,oe as hasRoleAccess,pr as hasTierAccess,sa as isAuthPartnerId,gl as isBackendGeneratedField,Ei as isBreakpoint,le as isCompactDateString,Je as isFieldVisible,ml as isFrameworkField,ca as isOAuthPartnerId,sr as isPKCESupported,Rt as isoToCompactString,dr as lazyImport,Ao as listEntitiesSchema,Ee as mapToDoNotDevError,ir as maybeTranslate,Pt as normalizeToISOString,ln as overrideFeatures,gn as overridePaymentModes,un as overridePermissions,mn as overrideSubscriptionStatus,cn as overrideSubscriptionTiers,sn as overrideUserRoles,ue as parseDate,Ut as parseDateToNoonUTC,xr as parseISODate,Ar as parseServerCookie,Wi as refreshTokenSchema,k as registerSchemaGenerator,Gc as registerUniqueConstraintValidator,Hi as revokeGitHubAccessSchema,or as showNotification,Ot as timestampToISOString,Mt as toDateOnly,wt as toISOString,Tt as translateArray,It as translateArrayRange,At as translateArrayWithIndices,Ct as translateObjectArray,Co as updateEntitySchema,vr as updateMetadata,ia as validateAuthPartners,$n as validateAuthSchemas,Vn as validateAuthUser,_n as validateBillingSchemas,An as validateCheckoutSessionMetadata,lr as validateCodeChallenge,cr as validateCodeVerifier,En as validateCreateCheckoutSessionRequest,xn as validateCreateCheckoutSessionResponse,Hn as validateCustomClaims,ae as validateDates,Xc as validateDocument,Ir as validateEnvVar,Cr as validateMetadata,aa as validateOAuthPartners,Pn as validateStripeBackConfig,Rn as validateStripeFrontConfig,Cn as validateSubscriptionClaims,Tn as validateSubscriptionData,ut as validateUniqueFields,Tr as validateUrl,jn as validateUserSubscription,In as validateWebhookEvent,nr as withErrorHandling,ur as withGracefulDegradation};
|
|
1
|
+
var ht=Object.defineProperty;var vt=(e,t)=>()=>(e&&(t=e(e=0)),t);var yt=(e,t)=>{for(var r in t)ht(e,r,{get:t[r],enumerable:!0})};import{Buffer as p}from"node:buffer";import{createRequire as bt}from"node:module";import{dirname as St,resolve as Zr}from"node:path";import l from"node:process";import{fileURLToPath as Et}from"node:url";var xt,u,m,i=vt(()=>{"use strict";xt=bt(import.meta.url),u=Et(import.meta.url),m=St(u);typeof globalThis<"u"&&(globalThis.require=xt,globalThis.__filename=u,globalThis.__dirname=m,globalThis.Buffer=p,globalThis.process=l,typeof global>"u"&&(globalThis.global=globalThis))});i();var et={};yt(et,{DEFAULT_ERROR_MESSAGES:()=>H,DoNotDevError:()=>D,SingletonManager:()=>Ce,addMonths:()=>Z,addYears:()=>Ae,calculateSubscriptionEndDate:()=>Er,captureErrorToSentry:()=>xe,commonErrorCodeMappings:()=>X,compactToISOString:()=>ce,createAsyncSingleton:()=>fr,createErrorHandler:()=>L,createMetadata:()=>kt,createMethodProxy:()=>hr,createSingleton:()=>mr,createSingletonWithParams:()=>gr,detectErrorSource:()=>be,filterVisibleFields:()=>Sr,formatDate:()=>we,formatRelativeTime:()=>Nt,generateCodeChallenge:()=>Xe,generateCodeVerifier:()=>Ke,generatePKCEPair:()=>ar,getCurrentTimestamp:()=>_t,getVisibleFields:()=>Ie,getWeekFromISOString:()=>Dt,handleError:()=>O,hasRoleAccess:()=>ie,hasTierAccess:()=>pr,isCompactDateString:()=>le,isFieldVisible:()=>Je,isPKCESupported:()=>sr,isoToCompactString:()=>Rt,lazyImport:()=>dr,mapToDoNotDevError:()=>Ee,maybeTranslate:()=>or,normalizeToISOString:()=>Pt,parseDate:()=>ue,parseDateToNoonUTC:()=>Ut,parseISODate:()=>xr,parseServerCookie:()=>Ar,showNotification:()=>ir,timestampToISOString:()=>Ot,toDateOnly:()=>Mt,toISOString:()=>wt,translateArray:()=>Tt,translateArrayRange:()=>It,translateArrayWithIndices:()=>At,translateObjectArray:()=>Ct,updateMetadata:()=>vr,validateCodeChallenge:()=>lr,validateCodeVerifier:()=>cr,validateEnvVar:()=>Ir,validateMetadata:()=>Cr,validateUrl:()=>Tr,withErrorHandling:()=>nr,withGracefulDegradation:()=>ur});i();i();i();function Tt(e,t,r,o={}){let{minLength:s=0,excludeEmpty:d=!0,customFilter:C}=o;return Array.from({length:r},(A,P)=>{let R=`${t}.${P}`;return e(R)}).filter((A,P)=>{let R=`${t}.${P}`;return!(A===R||d&&A.trim()===""||A.length<s||C&&!C(A,P))})}function Ct(e,t,r,o){return Array.from({length:r},(s,d)=>{let C=`${t}.${d}.${String(o[0])}`;if(e(C)===C)return null;let P={};for(let R of o){let I=`${t}.${d}.${String(R)}`;P[R]=e(I)}return P}).filter(s=>s!==null)}function It(e,t,r,o,s={}){let{minLength:d=0,excludeEmpty:C=!0,customFilter:A}=s;return Array.from({length:o-r},(P,R)=>{let I=r+R,U=`${t}.${I}`;return e(U)}).filter((P,R)=>{let I=r+R,U=`${t}.${I}`;return!(P===U||C&&P.trim()===""||P.length<d||A&&!A(P,I))})}function At(e,t,r,o={}){let{minLength:s=0,excludeEmpty:d=!0,customFilter:C}=o;return Array.from({length:r},(A,P)=>{let R=`${t}.${P}`;return{item:e(R),originalIndex:P}}).filter(({item:A,originalIndex:P})=>{let R=`${t}.${P}`;return!(A===R||d&&A.trim()===""||A.length<s||C&&!C(A,P))})}i();function kt(e){let t=new Date().toISOString();return{_createdAt:t,_updatedAt:t,_createdBy:e,_updatedBy:e}}i();function ce(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],o=t[2],s=t[3],d=t[4],C=t[5],A=new Date(parseInt(r,10),parseInt(o,10)-1,parseInt(s,10),parseInt(d,10),parseInt(C,10));if(isNaN(A.getTime()))throw new Error(`Invalid date values in compact format: ${e}`);return A.toISOString()}function Rt(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);let r=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),d=String(t.getUTCHours()).padStart(2,"0"),C=String(t.getUTCMinutes()).padStart(2,"0");return`${r}${o}${s}:${d}${C}`}function le(e){return/^\d{4}\d{2}\d{2}:\d{2}\d{2}$/.test(e)}function Pt(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(le(e))return ce(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 _t(){return new Date().toISOString()}function wt(e){return e.toISOString()}function Ot(e){return new Date(e).toISOString()}function Dt(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),o=Math.floor((t.getTime()-r.getTime())/(1440*60*1e3));return`Week ${Math.ceil((o+r.getDay()+1)/7)}, ${t.getFullYear()}`}var M={SECOND:1,MINUTE:60,HOUR:3600,DAY:86400,WEEK:604800,MONTH:2592e3,YEAR:31536e3};function Nt(e,t="en",r={}){if(!e)return"";let{style:o="long",numeric:s="auto",fallbackThreshold:d=M.WEEK}=r,C;if(e instanceof Date)C=e;else if(typeof e=="string")C=new Date(e);else if(typeof e=="number")C=new Date(e);else if(typeof e=="object"&&"toDate"in e)C=e.toDate();else return"";if(isNaN(C.getTime()))return"";let A=new Date,P=C.getTime()-A.getTime(),R=Math.round(P/1e3),I=Math.abs(R);if(I>d)return we(C.toISOString(),t);let U=new Intl.RelativeTimeFormat(t,{style:o,numeric:s});return I<M.MINUTE?U.format(R,"second"):I<M.HOUR?U.format(Math.round(R/M.MINUTE),"minute"):I<M.DAY?U.format(Math.round(R/M.HOUR),"hour"):I<M.WEEK?U.format(Math.round(R/M.DAY),"day"):I<M.MONTH?U.format(Math.round(R/M.WEEK),"week"):I<M.YEAR?U.format(Math.round(R/M.MONTH),"month"):U.format(Math.round(R/M.YEAR),"year")}function Ft(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 we(e,t="en",r="long"){if(!e)return"";let o;if(e instanceof Date)o=e;else if(typeof e=="string")o=new Date(e);else if(typeof e=="number")o=new Date(e);else if(typeof e=="object"&&"toDate"in e)o=e.toDate();else return"";if(isNaN(o.getTime()))return"";let s=typeof r=="string"?Ft(r):r;return new Intl.DateTimeFormat(t,s).format(o)}function ue(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(le(t))try{return ce(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,o=new Date(r);return isNaN(o.getTime())?void 0:o.toISOString()}}}function Ut(e){let t=ue(e);if(!t)return;let r=new Date(t);return r.setUTCHours(12,0,0,0),r.toISOString()}function Mt(e){let t=ue(e);return t&&t.split("T")[0]||""}i();i();i();i();i();var q={GUEST:"guest",USER:"user",ADMIN:"admin",SUPER:"super"};function cn(e){Object.assign(q,e)}var de={FREE:"free",PRO:"pro",PREMIUM:"premium"};function ln(e){Object.assign(de,e)}var pe={BASIC_ACCESS:"basic_access",ADVANCED_FEATURES:"advanced_features",API_ACCESS:"api_access",PRIORITY_SUPPORT:"priority_support"};function un(e){Object.assign(pe,e)}var me={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 dn(e){Object.assign(me,e)}i();import*as a from"valibot";i();i();var G={ACTIVE:"active",CANCELED:"canceled",INCOMPLETE:"incomplete",INCOMPLETE_EXPIRED:"incomplete_expired",PAST_DUE:"past_due",TRIALING:"trialing",UNPAID:"unpaid"};function gn(e){Object.assign(G,e)}var te={PAYMENT:"payment",SUBSCRIPTION:"subscription"};function fn(e){Object.assign(te,e)}var hn={ONE_MONTH:"1month",THREE_MONTHS:"3months",SIX_MONTHS:"6months",ONE_YEAR:"1year",TWO_YEARS:"2years",LIFETIME:"lifetime"};function vn(e){return{tier:"free",status:"active",subscriptionId:null,customerId:e,subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0}}var Oe={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}},yn={tier:"free",subscriptionId:null,customerId:"",status:"active",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString(),isDefault:!0};i();import*as n from"valibot";var De=n.object({userId:n.string(),productId:n.optional(n.string()),priceId:n.string(),successUrl:n.pipe(n.string(),n.url()),cancelUrl:n.pipe(n.string(),n.url()),customerEmail:n.optional(n.pipe(n.string(),n.email())),userEmail:n.optional(n.pipe(n.string(),n.email())),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean()),mode:n.optional(n.picklist([te.PAYMENT,te.SUBSCRIPTION]))}),Ne=n.object({sessionId:n.string(),sessionUrl:n.nullable(n.pipe(n.string(),n.url()))}),Fe=n.object({userId:n.string(),tier:n.string(),status:n.picklist(Object.values(G)),subscriptionId:n.nullable(n.string()),customerId:n.string(),subscriptionEnd:n.nullable(n.pipe(n.string(),n.isoTimestamp())),cancelAtPeriodEnd:n.boolean(),updatedAt:n.pipe(n.string(),n.isoTimestamp())}),Ue=n.object({tier:n.string(),subscriptionId:n.nullable(n.string()),customerId:n.string(),status:n.picklist(Object.values(G)),subscriptionEnd:n.nullable(n.pipe(n.string(),n.isoTimestamp())),cancelAtPeriodEnd:n.boolean(),updatedAt:n.pipe(n.string(),n.isoTimestamp()),isDefault:n.optional(n.boolean())}),Me=n.object({id:n.string(),type:n.string(),data:n.object({object:n.any()}),created:n.pipe(n.string(),n.isoTimestamp())}),Le=n.looseObject({userId:n.optional(n.string()),firebaseUid:n.optional(n.string()),productType:n.optional(n.string())});function xn(e){return n.safeParse(De,e)}function Tn(e){return n.safeParse(Ne,e)}function Cn(e){return n.safeParse(Fe,e)}function In(e){return n.safeParse(Ue,e)}function An(e){return n.safeParse(Me,e)}function kn(e){return n.safeParse(Le,e)}var Lt=n.object({type:n.literal("StripePayment"),name:n.pipe(n.string(),n.minLength(1,"Product name is required")),description:n.optional(n.string()),price:n.string(),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:n.pipe(n.string(),n.minLength(1,"Stripe price ID is required")),tier:n.pipe(n.string(),n.minLength(1,"Tier is required")),duration:n.pipe(n.string(),n.minLength(1,"Duration is required")),allowPromotionCodes:n.optional(n.boolean()),metadata:n.optional(n.record(n.string(),n.string()))}),Bt=n.object({type:n.literal("StripeSubscription"),name:n.pipe(n.string(),n.minLength(1,"Product name is required")),description:n.optional(n.string()),price:n.string(),currency:n.optional(n.pipe(n.string(),n.length(3,"Currency must be 3-letter ISO code")),"EUR"),priceId:n.pipe(n.string(),n.minLength(1,"Stripe price ID is required")),tier:n.pipe(n.string(),n.minLength(1,"Tier is required")),duration:n.picklist(["1month","3months","6months","1year","2years","lifetime"]),allowPromotionCodes:n.optional(n.boolean()),metadata:n.optional(n.record(n.string(),n.string()))}),qt=n.variant("type",[Lt,Bt]),Rn=n.record(n.string(),qt),Vt=n.record(n.string(),n.object({name:n.string(),price:n.string(),currency:n.string(),description:n.optional(n.string()),features:n.optional(n.array(n.string())),priceId:n.string(),allowPromotionCodes:n.optional(n.boolean())})),jt=n.record(n.string(),n.object({type:n.picklist(["StripePayment","StripeSubscription"]),name:n.string(),price:n.number(),currency:n.string(),priceId:n.string(),tier:n.string(),duration:n.string(),description:n.optional(n.string()),metadata:n.optional(n.record(n.string(),n.string())),allowPromotionCodes:n.optional(n.boolean())}));function Pn(e){return n.parse(Vt,e)}function _n(e){return n.parse(jt,e)}function wn(){let e={createCheckoutSessionRequest:n.safeParse(De,{}),createCheckoutSessionResponse:n.safeParse(Ne,{}),subscriptionData:n.safeParse(Fe,{}),subscriptionClaims:n.safeParse(Ue,{}),webhookEvent:n.safeParse(Me,{}),checkoutSessionMetadata:n.safeParse(Le,{})};return{success:Object.values(e).every(t=>t.success),results:e}}i();var Be=a.object({id:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),emailVerified:a.optional(a.boolean()),lastLoginAt:a.optional(a.string()),providerData:a.optional(a.array(a.object({providerId:a.string(),uid:a.string(),email:a.optional(a.nullable(a.pipe(a.string(),a.email()))),displayName:a.optional(a.nullable(a.string())),photoURL:a.optional(a.nullable(a.pipe(a.string(),a.url()))),phoneNumber:a.optional(a.nullable(a.string()))}))),role:a.optional(a.picklist(Object.values(q))),customClaims:a.optional(a.record(a.string(),a.any()))}),ge=a.object({userId:a.string(),tier:a.picklist(Object.values(de)),status:a.picklist(Object.values(G)),isActive:a.optional(a.boolean()),features:a.optional(a.array(a.string())),subscriptionId:a.nullable(a.string()),customerId:a.string(),subscriptionEnd:a.nullable(a.pipe(a.string(),a.isoTimestamp())),cancelAtPeriodEnd:a.boolean(),updatedAt:a.pipe(a.string(),a.isoTimestamp())}),qe=a.object({role:a.optional(a.picklist(Object.values(q))),subscription:a.optional(ge),features:a.optional(a.array(a.picklist(Object.values(pe)))),permissions:a.optional(a.array(a.picklist(Object.values(me)))),githubAccess:a.optional(a.object({username:a.optional(a.string()),teamAccess:a.optional(a.array(a.string())),repoAccess:a.optional(a.array(a.string()))}))});function jn(e){return a.safeParse(Be,e)}function Hn(e){return a.safeParse(ge,e)}function $n(e){return a.safeParse(qe,e)}function Gn(){let e={authUser:a.safeParse(Be,{}),userSubscription:a.safeParse(ge,{}),customClaims:a.safeParse(qe,{}),getUserAuthStatus:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1))}),{}),getCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.optional(a.array(a.string()))}),{}),setCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claims:a.record(a.string(),a.any()),merge:a.optional(a.boolean(),!1)}),{}),removeCustomClaims:a.safeParse(a.object({userId:a.pipe(a.string(),a.minLength(1)),claimKeys:a.pipe(a.array(a.string()),a.minLength(1))}),{})};return{success:Object.values(e).every(t=>t.success),results:e}}i();var Yn={IDLE:"idle",LOADING:"loading",ERROR:"error",AUTHENTICATED:"authenticated"};function Kn(e){return{userId:e,role:"user",preferences:{},metadata:{}}}i();var ni={VITE:"vite",NEXTJS:"nextjs",UNKNOWN:"unknown"},ii={DEVELOPMENT:"development",PRODUCTION:"production",TEST:"test"},oi={CLIENT:"client",SERVER:"server",BUILD:"build"},ai={HIGH:.95,MEDIUM:.8,LOW:.7,MINIMUM:.3},si={INITIALIZING:"initializing",READY:"ready",DEGRADED:"degraded",ERROR:"error"},ci={LOCAL:"localStorage",SESSION:"sessionStorage",INDEXED_DB:"indexedDB",MEMORY:"memory"},li={USER:"user",GLOBAL:"global",SESSION:"session"},ui={STANDALONE:"standalone",FULLSCREEN:"fullscreen",MINIMAL_UI:"minimal-ui",BROWSER:"browser"},di={MANIFEST:"manifest",SERVICE_WORKER:"service-worker",ICON:"icon"},pi={AUTO:"auto-discovery",MANUAL:"manual",HYBRID:"hybrid"};i();i();i();import*as x from"valibot";i();var fe={create:"admin",read:"guest",update:"admin",delete:"admin"};var re=/^[0-9a-zA-Z]+$/,xi=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),data:x.record(x.string(),x.unknown()),idempotencyKey:x.optional(x.string())}),Ti=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required"))}),Ci=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required")),data:x.record(x.string(),x.unknown()),merge:x.optional(x.boolean(),!1)}),Ii=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),id:x.pipe(x.string(),x.minLength(1,"Entity ID is required"))}),Ai=x.object({collection:x.pipe(x.string(),x.minLength(1,"Collection name is required")),limit:x.optional(x.pipe(x.number(),x.minValue(1),x.maxValue(1e3)),50),offset:x.optional(x.pipe(x.number(),x.minValue(0)),0),orderBy:x.optional(x.string()),orderDirection:x.optional(x.picklist(["asc","desc"]),"desc"),where:x.optional(x.array(x.object({field:x.string(),operator:x.picklist(["==","!=","<","<=",">",">=","array-contains","in","not-in"]),value:x.any()})))});i();i();i();var he={"permission-denied":{type:"PERMISSION_DENIED",message:"You do not have permission to perform this action"},"not-found":{type:"NOT_FOUND",message:"The requested resource was not found"},"already-exists":{type:"ALREADY_EXISTS",message:"The resource already exists"},"invalid-argument":{type:"VALIDATION_ERROR",message:"Invalid argument provided"}},Ve=class extends Error{type;originalError;constructor(t,r,o){super(r),this.name="EntityHookError",this.type=t,this.originalError=o}},D=class e extends Error{code;details;source;originalError;context;displayable;userMessageProvided;constructor(t,r="internal",o){super(t),Object.setPrototypeOf(this,e.prototype),this.code=r,this.details=o?.details,this.source=o?.source,this.originalError=o?.originalError,this.context=o?.context,this.displayable=o?.displayable??!0,this.userMessageProvided=o?.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}}};i();i();var qi={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"};i();var Hi={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"};i();var Wi={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"};i();var Ki={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"};i();var Qi={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"};i();i();i();i();import"valibot";i();i();i();i();i();i();var ve={mobile:0,tablet:768,laptop:1024,desktop:1440},Ht={mobile:{min:0,max:767},tablet:{min:768,max:1023},laptop:{min:1024,max:1439},desktop:{min:1440,max:1/0}};function $t(e){return e>=ve.desktop?"desktop":e>=ve.laptop?"laptop":e>=ve.tablet?"tablet":"mobile"}function xo(e,t){let r=Ht[t];return e>=r.min&&e<=r.max}function To(e,t){let r=$t(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"}}i();var Ao="landing";i();i();i();i();i();var je=["pull","push","admin","maintain","triage"];i();import"valibot";i();import*as E from"valibot";var ye=E.object({owner:E.pipe(E.string(),E.minLength(1,"Repository owner is required")),repo:E.pipe(E.string(),E.minLength(1,"Repository name is required"))}),Gt=E.picklist([...je]),Ho=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye,permission:E.optional(Gt,"push"),customClaims:E.optional(E.record(E.string(),E.any()))}),$o=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye}),Go=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required")),githubUsername:E.pipe(E.string(),E.minLength(1,"GitHub username is required")),repoConfig:ye}),Wo=E.object({provider:E.string(),purpose:E.picklist(["authentication","api-access"]),code:E.pipe(E.string(),E.minLength(1,"Authorization code is required")),redirectUri:E.pipe(E.string(),E.url("Valid redirect URI is required")),codeVerifier:E.optional(E.string()),state:E.optional(E.string()),instance:E.optional(E.pipe(E.string(),E.url()))}),zo=E.object({provider:E.string(),refreshToken:E.pipe(E.string(),E.minLength(1,"Refresh token is required")),redirectUri:E.pipe(E.string(),E.url("Valid redirect URI is required"))}),Yo=E.object({provider:E.string()}),Ko=E.object({userId:E.pipe(E.string(),E.minLength(1,"User ID is required"))});i();i();var na={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"};i();import*as T from"valibot";var He=T.object({name:T.string(),color:T.string(),icon:T.string(),customParameters:T.optional(T.record(T.string(),T.string())),button:T.object({backgroundColor:T.string(),textColor:T.string(),borderColor:T.string(),hoverBackgroundColor:T.string(),focusOutlineColor:T.string(),fontWeight:T.optional(T.string(),"500"),textKey:T.optional(T.string())})}),Wt=T.object({...He.entries,type:T.picklist(["auth","both"]),scopes:T.optional(T.array(T.string())),firebaseProviderId:T.optional(T.string())}),ne=T.union([T.literal(""),T.pipe(T.string(),T.url())]),zt=T.object({authUrl:ne,tokenUrl:ne,profileUrl:ne,revokeUrl:T.optional(ne)}),Yt=T.object({authentication:T.optional(T.array(T.string())),"api-access":T.array(T.string())}),Kt=T.optional(T.object({pkce:T.optional(T.boolean(),!1),codeChallengeMethod:T.optional(T.picklist(["S256","plain"]),"S256")})),Xt=T.object({...He.entries,type:T.picklist(["oauth","both"]),scopes:Yt,endpoints:zt,capabilities:Kt}),$e={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"}}},Ge={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"}}},Zt=T.record(T.string(),Wt),Qt=T.record(T.string(),Xt);function aa(){return T.safeParse(Zt,$e)}function sa(){return T.safeParse(Qt,Ge)}function ca(e){return e in $e}function la(e){return e in Ge}i();i();i();i();i();var We={NECESSARY:"necessary",FUNCTIONAL:"functional",ANALYTICS:"analytics",MARKETING:"marketing"},Ea={ADMIN:"admin",BLOG:"blog",DOCS:"docs",GAME:"game",LANDING:"landing",MOOLTI:"moolti",PLAIN:"plain"},xa={COMPACT:"compact",STANDARD:"standard",EXPRESSIVE:"expressive"},Ta={auth:{requiresConsent:null},oauth:{requiresConsent:null},billing:{requiresConsent:null},analytics:{requiresConsent:We.ANALYTICS},marketing:{requiresConsent:We.MARKETING}};i();i();i();i();i();function be(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"}i();import*as Ye from"valibot";i();function L(e){return(t,r)=>{if(t instanceof D)return t;if(typeof t!="object"||t===null){let A=typeof t=="string"?t:e.defaultErrorMessage;return new D(r||A,e.defaultErrorCode,{details:{originalError:t},source:e.errorSource})}let o;e.extractErrorCode?o=e.extractErrorCode(t):"code"in t&&typeof t.code=="string"&&(o=t.code);let s=e.defaultErrorCode;o&&e.errorCodeMapping&&o in e.errorCodeMapping&&(s=e.errorCodeMapping[o]);let d;e.extractErrorMessage?d=e.extractErrorMessage(t):("message"in t&&typeof t.message=="string"||t instanceof Error)&&(d=t.message),o&&e.friendlyMessageMapping&&o in e.friendlyMessageMapping&&(d=e.friendlyMessageMapping[o]),d||(d=e.defaultErrorMessage);let C;return e.processMetadata?C=e.processMetadata(t):(C={originalError:t},o&&(C.originalCode=o)),"originalError"in C||(C.originalError=t),new D(r||d,s,{details:C,source:e.errorSource})}}var X={"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 H={"already-exists":"The resource already exists.",cancelled:"The operation was cancelled.","deadline-exceeded":"The operation timed out.",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."},Jt={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"},Se={INTERNAL_ERROR:"internal",VALIDATION_ERROR:"validation-failed",PERMISSION_DENIED:"permission-denied",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",NETWORK_ERROR:"unavailable"},V={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",...X},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",...X},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(Jt).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:X,friendlyMessageMapping:{}},ui:{errorSource:"ui",defaultErrorCode:"internal",defaultErrorMessage:H.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:H["validation-failed"],errorCodeMapping:{},friendlyMessageMapping:{}},entity:{errorSource:"entity",defaultErrorCode:"unknown",defaultErrorMessage:"An entity operation error occurred",errorCodeMapping:{},friendlyMessageMapping:{}},unknown:{errorSource:"unknown",defaultErrorCode:"unknown",defaultErrorMessage:H.unknown,errorCodeMapping:{TypeError:"invalid-argument",ReferenceError:"internal",RangeError:"invalid-argument"},friendlyMessageMapping:{},extractErrorCode:e=>{if(e instanceof Error)return e.name}}},er=e=>e instanceof Ye.ValiError?new D(H["validation-failed"],"validation-failed",{details:{validationErrors:e.issues.map(t=>({path:t.path.join("."),message:t.message})),originalError:e},source:"validation"}):L(V.validation)(e),tr=e=>{if(e instanceof Error&&"type"in e&&typeof e.type=="string"&&e.type in Se){let t=e,r=Se[t.type]||"unknown";return new D(t.message||H[r],r,{details:{originalError:e},source:"entity"})}if(typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&he[e.code]){let t=e,r=he[t.code];if(r){let o=Se[r.type]||"unknown";return new D(r.message||H[o],o,{details:{originalCode:t.code,originalError:e},source:"entity"})}}return L(V.entity)(e)},ze={auth:L(V.auth),oauth:L(V.oauth),api:L(V.api),firebase:L(V.firebase),ui:L(V.ui),validation:er,entity:tr,unknown:L(V.unknown)};function Ee(e,t,r){return e instanceof D?e:(ze[t]||ze.unknown)(e,r)}i();function xe(e,t,r={}){let o=globalThis.Sentry;o&&o.withScope(s=>{s.setTag("errorSource",t),s.setTag("errorCode",e.code),e.details&&Object.entries(e.details).forEach(([d,C])=>{if(typeof C!="function"&&d!=="originalError")try{s.setExtra(d,C)}catch{s.setExtra(d,`[${typeof C}]`)}}),Object.entries(r).forEach(([d,C])=>{if(typeof C!="function")try{s.setExtra(`context.${d}`,C)}catch{s.setExtra(`context.${d}`,`[${typeof C}]`)}}),(e.details?.userId||r.userId)&&s.setUser({id:e.details?.userId||r.userId,email:e.details?.userEmail||r.userEmail}),o.captureException(e)})}function rr(){return typeof import.meta<"u"&&import.meta.env&&(import.meta.env.DEV===!0||import.meta.env.MODE&&import.meta.env.MODE!=="production")?!0:typeof l<"u"&&l.env?"production".toLowerCase()!=="production":!0}function O(e,t){let r=typeof t=="string"?{userMessage:t}:t||{},{userMessage:o,context:s={},log:d=!0,reportToSentry:C=!0,showNotification:A=!1,severity:P="error"}=r,R=be(e),I=e instanceof D?e:Ee(e,R,o);if(o&&!I.userMessageProvided&&(I.message.includes("Error")||I.message.includes("Failed")||I.message.length<10?I=new D(o,I.code,{details:{...I.details,originalMessage:I.message},source:R,userMessageProvided:!0}):I=new D(I.message,I.code,{details:{...I.details,userMessage:o},source:R,userMessageProvided:!0})),d){let U=rr()||typeof window<"u"&&window.__DNDEV_DEBUG,Y={code:I.code,message:I.message,source:R};switch(P){case"warning":break;case"info":break;case"success":break;default:}}return C&&xe(I,R,s),I}function nr(e,t){return async(...r)=>{try{return await e(...r)}catch(o){throw O(o,t)}}}function ir(e,t="info",r){let o=Date.now().toString();return o}i();function or(e,t){return t?!t.includes(".")&&!t.includes(":")?t:e(t):""}i();function Ke(){let e=new Uint8Array(32);return crypto.getRandomValues(e),Ze(e)}async function Xe(e){let r=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",r);return Ze(new Uint8Array(o))}async function ar(){let e=Ke(),t=await Xe(e);return{codeVerifier:e,codeChallenge:t}}function Ze(e){return btoa(String.fromCharCode(...e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function sr(){return typeof window<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof crypto.getRandomValues<"u"}function cr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}function lr(e){return e.length<43||e.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(e)}i();async function ur(e,t,r){try{return await e()}catch{return t(),!1}}i();var Te=new Map;function dr(e,t){if(Te.has(t))return Te.get(t);let r=e();return Te.set(t,r),r}i();var Qe={[q.GUEST]:0,[q.USER]:1,[q.ADMIN]:2,[q.SUPER]:3};function ie(e,t){if(!e)return!1;let r=Qe[e]??-1,o=Qe[t]??1/0;return r>=o}i();function pr(e,t,r){if(!e)return!1;let o=r??Oe,s=o[e]?.level??-1,d=o[t]?.level??1/0;return s>=d}i();function mr(e,...t){let r=null,o=!1;return function(){if(r!==null)return r;if(o)throw new Error("Circular dependency detected in singleton initialization");o=!0;try{return typeof e=="function"&&e.prototype?r=new e(...t):r=e(),r}finally{o=!1}}}function gr(e){let t=null,r=!1;return function(...s){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(...s):t=e(...s),t}finally{r=!1}}}function fr(e){let t=null,r=!1,o=null;return async function(){if(t!==null)return t;if(r&&o)return o;if(r)throw new Error("Circular dependency detected in async singleton initialization");r=!0;try{return o=e(),t=await o,t}finally{r=!1,o=null}}}function hr(e,t){return new Proxy({},{get(r,o){if(t.includes(o)){let d=e(),C=d[o];return typeof C=="function"?C.bind(d):C}return e()[o]}})}var Ce=class{static instances=new Map;static initializing=new Set;static initialized=new Set;static async getOrCreate(t,r,o={}){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(o.ssrSafe===!1&&typeof window>"u"){if(o.fallbackFactory){let s=o.fallbackFactory();return this.instances.set(t,s),this.initialized.add(t),s}throw new Error(`Singleton ${t} requires client-side environment`)}this.initializing.add(t);try{let s=await r();return this.instances.set(t,s),this.initialized.add(t),s}catch(s){if(o.cacheFailures&&this.initialized.add(t),o.fallbackFactory){let d=o.fallbackFactory();return this.instances.set(t,d),this.initialized.add(t),d}throw s}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()}};i();function vr(e){return{_updatedAt:new Date().toISOString(),_updatedBy:e}}i();i();import"valibot";i();import"valibot";function yr(e){return typeof e=="object"&&e!==null&&"visibility"in e&&typeof e.visibility=="string"}function br(e){if(yr(e))return e.visibility}function Je(e,t){let r=e??"guest";return r==="hidden"?!1:r==="technical"?ie(t,"admin"):ie(t,r)}function Ie(e,t){let r=e;if(!r||typeof r!="object"||!r.entries)return[];let o=r.entries,s=[];for(let[d,C]of Object.entries(o)){let A=br(C);Je(A,t)&&s.push(d)}return s}function Sr(e,t,r){if(!e)return{};let o=Ie(t,r),s={};for(let d of o)Object.prototype.hasOwnProperty.call(e,d)&&(s[d]=e[d]);return s}i();function Z(e,t){let r=new Date(e),o=r.getDate();return r.setMonth(r.getMonth()+t),r.getDate()!==o&&r.setDate(0),r}function Ae(e,t){let r=new Date(e),o=r.getDate();return r.setFullYear(r.getFullYear()+t),r.getDate()!==o&&r.setDate(0),r}function Er(e,t=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let r;return e==="1month"?r=Z(t,1):e==="3months"?r=Z(t,3):e==="6months"?r=Z(t,6):e==="1year"?r=Ae(t,1):e==="2years"?r=Ae(t,2):r=Z(t,1),r.toISOString()}function xr(e){let t=new Date(e);if(isNaN(t.getTime()))throw new Error(`Invalid ISO date string: ${e}`);return t}i();function Tr(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 Cr(e){let t={};for(let[r,o]of Object.entries(e)){if(typeof o!="string")throw new Error(`Metadata value for key '${r}' must be a string, got ${typeof o}`);let s=o.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(s.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]=s}return t}function Ir(e,t=!0){let r=l.env[e];if(t&&!r)throw new Error(`Required environment variable '${e}' is not set`);return r||""}i();function Ar(e,t){if(!e)return null;let r=`${encodeURIComponent(t)}=`,o=e.split(";");for(let s=0;s<o.length;s++){let d=o[s];if(d){for(;d.charAt(0)===" ";)d=d.substring(1,d.length);if(d.indexOf(r)===0)return decodeURIComponent(d.substring(r.length,d.length))}}return null}i();i();i();import*as B from"valibot";i();import*as c from"valibot";var Q=new Map;function k(e,t){Q.set(e,t)}function Dc(e){return Q.has(e)}function Nc(){return Array.from(Q.keys())}function Fc(){Q.clear()}function _(e,t){return t?e:c.nullish(e)}var oe=e=>{let t=[];e.validation?.minLength!==void 0&&t.push(c.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)),e.validation?.maxLength!==void 0&&t.push(c.maxLength(e.validation.maxLength,`Must be at most ${e.validation.maxLength} characters`)),e.validation?.pattern&&t.push(c.regex(new RegExp(e.validation.pattern),"Invalid format"));let r=t.length>0?c.pipe(c.string(),...t):c.string();return _(r,e.validation?.required)},kr=e=>{let t=c.pipe(c.string(),c.email("Invalid email address"));return _(t,e.validation?.required)},Rr=e=>{let t=e.validation?.minLength!==void 0?c.pipe(c.string(),c.minLength(e.validation.minLength,`Must be at least ${e.validation.minLength} characters`)):c.string();return _(t,e.validation?.required)},Pr=e=>{let t=c.pipe(c.string(),c.url("Invalid URL"));return _(t,e.validation?.required)},tt=e=>{let t=[];e.validation?.min!==void 0&&t.push(c.minValue(e.validation.min,`Must be at least ${e.validation.min}`)),e.validation?.max!==void 0&&t.push(c.maxValue(e.validation.max,`Must be at most ${e.validation.max}`));let r=t.length>0?c.pipe(c.number(),...t):c.number();return _(r,e.validation?.required)},rt=e=>{let t=c.boolean();return _(t,e.validation?.required)},W=e=>{let t=c.pipe(c.string(),c.isoTimestamp("Invalid date format"));return _(t,e.validation?.required)},at=c.object({url:c.string(),filename:c.string(),size:c.number(),mimeType:c.nullish(c.string()),uploadedAt:c.nullish(c.string())}),nt=e=>{let t=c.nullable(at);return _(t,e.validation?.required)},it=e=>{let t=c.array(at);return _(t,e.validation?.required)},st=c.object({fullUrl:c.string(),thumbUrl:c.string()}),_r=e=>_(st,e.validation?.required),wr=e=>{let t=c.array(st);return _(t,e.validation?.required)},Or=e=>{let t=c.object({lat:c.number(),lng:c.number()});return _(t,e.validation?.required)},Dr=e=>{let t=c.object({formatted_address:c.string(),latitude:c.number(),longitude:c.number(),street_number:c.nullish(c.string()),route:c.nullish(c.string()),locality:c.nullish(c.string()),administrative_area_level_1:c.nullish(c.string()),administrative_area_level_2:c.nullish(c.string()),country:c.nullish(c.string()),postal_code:c.nullish(c.string())});return _(t,e.validation?.required)},Nr=e=>{let t=c.record(c.string(),c.unknown());return _(t,e.validation?.required)},Fr=e=>{let t=c.array(c.unknown());return _(t,e.validation?.required)},ke=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(d=>d.value),s=c.picklist(o);return _(s,e.validation?.required)}let r=c.union([c.string(),c.number()]);return _(r,e.validation?.required)},Ur=e=>{let t=e.validation?.options;if(Array.isArray(t)&&t.length>0){let o=t.map(d=>d.value),s=c.array(c.picklist(o));return _(s,e.validation?.required)}let r=c.array(c.string());return _(r,e.validation?.required)},Mr=e=>{let t=c.pipe(c.string(),c.regex(re,"Invalid ID format"));return _(t,e.validation?.required)},Re=e=>{let t=c.string();return _(t,e.validation?.required)},Lr=e=>{let t=c.string();return _(t,e.validation?.required)},ot=()=>c.never(),Br=e=>{let t=e.options?.fieldSpecific;if(t?.checkedValue&&t?.uncheckedValue){let o=[t.checkedValue,t.uncheckedValue],s=c.picklist(o);return _(s,e.validation?.required)}let r=c.boolean();return _(r,e.validation?.required)};function qr(){k("text",oe),k("textarea",oe),k("richtext",oe),k("color",oe),k("email",kr),k("password",Rr),k("url",Pr),k("tel",Lr),k("number",tt),k("range",tt),k("boolean",rt),k("checkbox",rt),k("date",W),k("datetime-local",W),k("time",W),k("week",W),k("month",W),k("timestamp",W),k("file",nt),k("files",it),k("document",nt),k("documents",it),k("image",_r),k("images",wr),k("geopoint",Or),k("address",Dr),k("map",Nr),k("array",Fr),k("select",ke),k("multiselect",Ur),k("radio",ke),k("combobox",ke),k("switch",Br),k("reference",Mr),k("hidden",Re),k("avatar",Re),k("badge",Re),k("submit",ot),k("reset",ot)}qr();function J(e){if(e.validation?.schema){let o=e.validation.schema;return _(o,e.validation?.required)}let t=Q.get(e.type);if(t){let o=t(e);if(o!==null)return o}let r=c.unknown();return _(r,e.validation?.required)}i();var Pe=[{value:"draft",label:"dndev:status.draft"},{value:"available",label:"dndev:status.available"},{value:"deleted",label:"dndev:status.deleted"}],Bc="available",qc=["draft","deleted"],z=["id","createdAt","updatedAt","createdById","updatedById"],Vr=[...z,"status"];function Vc(e){return Vr.includes(e)}function jc(e){return z.includes(e)}var w={status:{name:"status",type:"select",visibility:"admin",label:"crud:fields.status",editable:"admin",validation:{required:!0,options:[...Pe]}},id:{name:"id",type:"text",visibility:"hidden",label:"crud:fields.id",validation:{required:!0,pattern:re.source}},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}}};function ee(e,t){return Object.assign(e,{visibility:t})}function $(e,t){let r=e;return r.metadata={collection:t.collection,entity:t.name},r}function ct(e){let t=J(e);return ee(t,e.visibility)}function lt(e){let t=J({...e,validation:{...e.validation,required:!1}});return ee(t,e.visibility)}function jr(e){let t=e.fields,r={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(r[N]=ct(F));let o=$(B.object(r),e),s={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(z.includes(N)||(s[N]=ct(F)));let d=$(B.object(s),e),C={};for(let[N,F]of Object.entries(t))if(F.visibility!=="hidden"&&!z.includes(N))if(N==="status"){let j=B.literal("draft");C[N]=ee(j,F.visibility)}else C[N]=lt(F);let A=$(B.object(C),e),P={};for(let[N,F]of Object.entries(t))F.visibility!=="hidden"&&(z.includes(N)||(P[N]=lt(F)));P.id=ee(J(w.id),"technical");let R=$(B.object(P),e),I;if(e.listFields&&e.listFields.length>0){let N=["id","status"],F=[...new Set([...N,...e.listFields])];I={};for(let j of F){let K=r[j];K&&(I[j]=K)}}else I=r;let U=$(B.object(I),e),Y,se=e.listCardFields??e.listFields;if(se&&se.length>0){let N=["id","status"],F=[...new Set([...N,...se])];Y={};for(let j of F){let K=r[j];K&&(Y[j]=K)}}else Y=r;let gt=$(B.object(Y),e),ft=$(B.object({id:ee(J(w.id),"technical")}),e);return{create:d,draft:A,update:R,get:o,list:U,listCard:gt,delete:ft}}i();i();i();import"valibot";function el(e,t){let r=e;return r.metadata=t,r}i();var ut=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;function dt(e){return typeof e=="string"&&e.length>=19&&e.includes("-")&&e.includes(":")}function ae(e,t=""){if(Array.isArray(e))e.forEach((r,o)=>{let s=`${t}[${o}]`;if(typeof r=="string"&&dt(r)){if(!ut.test(r))throw O({userMessage:`Invalid date format for ${s}. Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${r}"`,context:{field:s,value:r},severity:"error"})}else typeof r=="object"&&r!==null&&ae(r,s)});else if(typeof e=="object"&&e!==null)for(let[r,o]of Object.entries(e)){let s=t?`${t}.${r}`:r;if(typeof o=="string"&&dt(o)){if(!ut.test(o))throw O({userMessage:`Invalid date format for field "${s}". Expected ISO string (YYYY-MM-DDTHH:mm:ss.sssZ). Received: "${o}"`,context:{field:s,value:o},severity:"error"})}else typeof o=="object"&&o!==null&&ae(o,s)}}i();import*as mt from"valibot";i();var _e={};function sl(e){_e.uniqueConstraintValidator=e}async function pt(e,t,r){let{uniqueFields:o=[],collection:s}=e.metadata;o.length!==0&&_e.uniqueConstraintValidator&&await Promise.all(o.map(async({field:d,errorMessage:C})=>{let A=t[d];if(A==null)return;if(await _e.uniqueConstraintValidator.checkDuplicate(s,d,A,r))throw O({userMessage:C||`${d} must be unique`,code:"already-exists",context:{field:d}})}))}async function pl(e,t,r,o){mt.parse(e,t),ae(t),await pt(e,t,o),e.metadata.customValidate&&await e.metadata.customValidate(t,r)}i();function Hr(e){return e!=null&&typeof e=="object"&&"metadata"in e&&typeof e.metadata=="object"&&e.metadata!==null}function Tl(e){if(!Hr(e)){let t=e,r=t&&typeof t=="object"&&"constructor"in t&&t.constructor&&t.constructor.name||"unknown";throw O(new Error("Schema does not have metadata"),{userMessage:"Invalid schema: missing collection metadata",severity:"error",context:{schemaType:r}})}return e.metadata.collection}i();function $r(e,t){if(!t||t.length===0)return e.map(s=>({value:s.value,label:s.label}));let r=e.map(s=>({value:s.value,label:s.label})),o=new Set(e.map(s=>s.value));for(let s of t)o.has(s.value)||r.push(s);return r}function Gr(e){let{form:t,fields:r}=e,o=Object.keys(r);if(t){if(t.type==="multi-step"||t.type==="wizard"){if(!t.steps||t.steps.length===0)throw O(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 s=t.steps.flatMap(P=>P.fields),d=s.filter(P=>!o.includes(P));if(d.length>0)throw O(new Error(`Multi-step form for entity '${e.name}' references non-existent fields: ${d.join(", ")}`),{userMessage:`Multi-step form for entity '${e.name}' references non-existent fields: ${d.join(", ")}`,context:{entityName:e.name,invalidFields:d,operation:"validateFormConfig"},severity:"error"});let C=new Set(s);o.filter(P=>!C.has(P)).length>0}t.rules&&t.rules.forEach((s,d)=>{let A=(Array.isArray(s.condition)?s.condition.map(I=>I.field):[s.condition.field]).filter(I=>!o.includes(I));if(A.length>0)throw O(new Error(`Dynamic form rule ${d} for entity '${e.name}' references non-existent condition fields: ${A.join(", ")}`),{userMessage:`Dynamic form rule ${d} for entity '${e.name}' references non-existent condition fields: ${A.join(", ")}`,context:{entityName:e.name,ruleIndex:d,invalidFields:A,operation:"validateFormConfig"},severity:"error"});let R=[...s.showFields||[],...s.hideFields||[],...s.disableFields||[],...s.enableFields||[]].filter(I=>!o.includes(I));if(R.length>0)throw O(new Error(`Dynamic form rule ${d} for entity '${e.name}' references non-existent affected fields: ${R.join(", ")}`),{userMessage:`Dynamic form rule ${d} for entity '${e.name}' references non-existent affected fields: ${R.join(", ")}`,context:{entityName:e.name,ruleIndex:d,invalidFields:R,operation:"validateFormConfig"},severity:"error"})}),Object.entries(r).forEach(([s,d])=>{if(d.dependsOn&&!o.includes(d.dependsOn.field))throw O(new Error(`Field '${s}' in entity '${e.name}' depends on non-existent field: ${d.dependsOn.field}`),{userMessage:`Field '${s}' in entity '${e.name}' depends on non-existent field: ${d.dependsOn.field}`,context:{entityName:e.name,fieldName:s,dependsOnField:d.dependsOn.field,operation:"validateFormConfig"},severity:"error"})})}}function Wr(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 Pl(e){try{Gr(e);let t=Wr(e),r={...e.fields,...w,...e.fields.createdAt&&{createdAt:{...w.createdAt,...e.fields.createdAt,type:w.createdAt.type,visibility:w.createdAt.visibility}},...e.fields.updatedAt&&{updatedAt:{...w.updatedAt,...e.fields.updatedAt,type:w.updatedAt.type,visibility:w.updatedAt.visibility}},...e.fields.createdById&&{createdById:{...w.createdById,...e.fields.createdById,type:w.createdById.type,visibility:w.createdById.visibility}},...e.fields.updatedById&&{updatedById:{...w.updatedById,...e.fields.updatedById,type:w.updatedById.type,visibility:w.updatedById.visibility}},...e.fields.status&&{status:{...w.status,...e.fields.status,type:w.status.type,visibility:w.status.visibility,editable:w.status.editable,validation:{...w.status.validation,required:!0,nullable:e.fields.status.validation?.nullable,options:$r(Pe,e.fields.status.validation?.options)}}}};if(e.listFields){let s=new Set(Object.keys(r)),d=e.listFields.filter(C=>!s.has(C));if(d.length>0)throw O(new Error(`Entity '${e.name}' defines listFields that do not exist: ${d.join(", ")}`),{userMessage:`Entity '${e.name}' defines listFields that do not exist: ${d.join(", ")}`,context:{entityName:e.name,invalidFields:d,operation:"defineEntity"},severity:"error"})}if(e.listCardFields){let s=new Set(Object.keys(r)),d=e.listCardFields.filter(C=>!s.has(C));if(d.length>0)throw O(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"})}let o={...fe,...e.access||{}};return{...e,form:t,fields:r,access:o}}catch(t){throw O(t,{userMessage:`Failed to define entity '${e.name}'`,context:{entityName:e.name,operation:"defineEntity"},severity:"error"})}}export{qi as AUTH_EVENTS,$e as AUTH_PARTNERS,Yn as AUTH_PARTNER_STATE,Be as AuthUserSchema,z as BACKEND_GENERATED_FIELD_NAMES,Hi as BILLING_EVENTS,Ht as BREAKPOINT_RANGES,ve as BREAKPOINT_THRESHOLDS,Oe as COMMON_TIER_CONFIGS,ai as CONFIDENCE_LEVELS,We as CONSENT_CATEGORY,oi as CONTEXTS,Le as CheckoutSessionMetadataSchema,De as CreateCheckoutSessionRequestSchema,Ne as CreateCheckoutSessionResponseSchema,qe as CustomClaimsSchema,fe as DEFAULT_ENTITY_ACCESS,H as DEFAULT_ERROR_MESSAGES,Ao as DEFAULT_LAYOUT_PRESET,Pe as DEFAULT_STATUS_OPTIONS,Bc as DEFAULT_STATUS_VALUE,yn as DEFAULT_SUBSCRIPTION,xa as DENSITY,D as DoNotDevError,ii as ENVIRONMENTS,Ve as EntityHookError,pe as FEATURES,Ta as FEATURE_CONSENT_MATRIX,si as FEATURE_STATUS,he as FIREBASE_ERROR_MAP,re as FIRESTORE_ID_PATTERN,je as GITHUB_PERMISSION_LEVELS,qc as HIDDEN_STATUSES,Ea as LAYOUT_PRESET,Wi as OAUTH_EVENTS,Ge as OAUTH_PARTNERS,na as PARTNER_ICONS,Ki as PAYLOAD_EVENTS,me as PERMISSIONS,ni as PLATFORMS,di as PWA_ASSET_TYPES,ui as PWA_DISPLAY_MODES,qt as ProductDeclarationSchema,Rn as ProductDeclarationsSchema,pi as ROUTE_SOURCES,li as STORAGE_SCOPES,ci as STORAGE_TYPES,Qi as STRIPE_EVENTS,te as STRIPE_MODES,hn as SUBSCRIPTION_DURATIONS,G as SUBSCRIPTION_STATUS,de as SUBSCRIPTION_TIERS,et as ServerUtils,Ce as SingletonManager,jt as StripeBackConfigSchema,Vt as StripeFrontConfigSchema,Lt as StripePaymentSchema,Bt as StripeSubscriptionSchema,Ue as SubscriptionClaimsSchema,Fe as SubscriptionDataSchema,Vr as TECHNICAL_FIELD_NAMES,q as USER_ROLES,ge as UserSubscriptionSchema,Me as WebhookEventSchema,Z as addMonths,Ae as addYears,w as baseFields,Er as calculateSubscriptionEndDate,xe as captureErrorToSentry,Go as checkGitHubAccessSchema,Fc as clearSchemaGenerators,X as commonErrorCodeMappings,ce as compactToISOString,fr as createAsyncSingleton,vn as createDefaultSubscriptionClaims,Kn as createDefaultUserProfile,xi as createEntitySchema,L as createErrorHandler,kt as createMetadata,hr as createMethodProxy,jr as createSchemas,mr as createSingleton,gr as createSingletonWithParams,Pl as defineEntity,Ii as deleteEntitySchema,be as detectErrorSource,Yo as disconnectOAuthSchema,el as enhanceSchema,Wo as exchangeTokenSchema,Sr as filterVisibleFields,we as formatDate,Nt as formatRelativeTime,Xe as generateCodeChallenge,Ke as generateCodeVerifier,ar as generatePKCEPair,$t as getBreakpointFromWidth,To as getBreakpointUtils,Tl as getCollectionName,Ko as getConnectionsSchema,_t as getCurrentTimestamp,Ti as getEntitySchema,Nc as getRegisteredSchemaTypes,J as getSchemaType,Ie as getVisibleFields,Dt as getWeekFromISOString,Gt as githubPermissionSchema,ye as githubRepoConfigSchema,Ho as grantGitHubAccessSchema,O as handleError,Dc as hasCustomSchemaGenerator,Hr as hasMetadata,ie as hasRoleAccess,pr as hasTierAccess,ca as isAuthPartnerId,jc as isBackendGeneratedField,xo as isBreakpoint,le as isCompactDateString,Je as isFieldVisible,Vc as isFrameworkField,la as isOAuthPartnerId,sr as isPKCESupported,Rt as isoToCompactString,dr as lazyImport,Ai as listEntitiesSchema,Ee as mapToDoNotDevError,or as maybeTranslate,Pt as normalizeToISOString,un as overrideFeatures,fn as overridePaymentModes,dn as overridePermissions,gn as overrideSubscriptionStatus,ln as overrideSubscriptionTiers,cn as overrideUserRoles,ue as parseDate,Ut as parseDateToNoonUTC,xr as parseISODate,Ar as parseServerCookie,zo as refreshTokenSchema,k as registerSchemaGenerator,sl as registerUniqueConstraintValidator,$o as revokeGitHubAccessSchema,ir as showNotification,Ot as timestampToISOString,Mt as toDateOnly,wt as toISOString,Tt as translateArray,It as translateArrayRange,At as translateArrayWithIndices,Ct as translateObjectArray,Ci as updateEntitySchema,vr as updateMetadata,aa as validateAuthPartners,Gn as validateAuthSchemas,jn as validateAuthUser,wn as validateBillingSchemas,kn as validateCheckoutSessionMetadata,lr as validateCodeChallenge,cr as validateCodeVerifier,xn as validateCreateCheckoutSessionRequest,Tn as validateCreateCheckoutSessionResponse,$n as validateCustomClaims,ae as validateDates,pl as validateDocument,Ir as validateEnvVar,Cr as validateMetadata,sa as validateOAuthPartners,_n as validateStripeBackConfig,Pn as validateStripeFrontConfig,In as validateSubscriptionClaims,Cn as validateSubscriptionData,pt as validateUniqueFields,Tr as validateUrl,Hn as validateUserSubscription,An as validateWebhookEvent,nr as withErrorHandling,ur as withGracefulDegradation};
|