@stoker-platform/node-client 0.5.1 → 0.5.2
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/dist/bundle.cjs +6 -6
- package/dist/bundle.js +684 -672
- package/dist/types/initializeStoker.d.ts +2 -2
- package/dist/types/main.d.ts +1 -1
- package/package.json +3 -3
package/dist/bundle.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const jo=require("node:child_process"),Tt=require("firebase-admin/app"),ze=require("lodash/isEqual.js"),Zo=require("lodash/merge.js"),zo=require("lodash/set.js"),pe=require("lodash/cloneDeep.js"),H=require("firebase-admin/firestore"),oi=require("firebase-admin/database"),yt=require("firebase-admin/auth"),qo=async(n,e,t,s)=>new Promise((r,i)=>{const o=jo.spawn(n,e,{cwd:t||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},u=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout.on("data",h=>{a+=h.toString(),console.log(h.toString())}),o.stderr.on("data",h=>{console.log(h.toString())}),o.on("exit",h=>{u(),h===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),Bo=async()=>{const n=process.env.STOKER_FB_WEB_APP_CONFIG;if(!n)throw new Error("Firebase web app config not found");const e=JSON.parse(n);try{return Tt.getApp()}catch{return Tt.initializeApp({credential:Tt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},Un=n=>!!n.auth,Se=(n,e)=>{if(e?.operations)return e.operations.includes(n)},Wn=(n,e)=>e?e.Role?n.access?.includes(e.Role):!1:!0,Ho=(n,e)=>n.restrictCreate===!0?!1:e&&typeof n.restrictCreate=="object"?e.Role?n.restrictCreate?.includes(e.Role):!1:!0,ai=(n,e)=>n.restrictUpdate===!0?!1:e&&typeof n.restrictUpdate=="object"?e.Role?n.restrictUpdate?.includes(e.Role):!1:!0,cr=(n,e,t)=>{const{labels:s}=n;return t.collections&&Se("Update",t.collections[s.collection])&&(!e.access||Wn(e,t))&&ai(e,t)&&!(n.auth&&!t.collections?.[s.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},W=(n,e)=>n.filter(t=>t.name===e)[0],X=n=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(n.type),li=(n,e)=>{const t={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=n,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const u=a?.[t[l.type]];c.role===e.Role&&(!c.assignable||u?.active)&&s.push(l)})}),s},Ps=(n,e)=>{const t=[],{labels:s,access:r}=n,{entityRestrictions:i}=r,o=e.collections?.[s.collection];return i?.restrictions?.forEach(a=>{"roles"in a&&a.roles.forEach(l=>{l.role===e.Role&&(!i.assignable?.includes(e.Role)||o?.restrictEntities)&&t.push(a)})}),t},ci=(n,e,t)=>{const s=[],{access:r}=n,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(d=>d.role===t.Role))return;const a=o.collectionField,l=W(n.fields,a);if(!X(l))throw new Error("PERMISSION_DENIED");const c=t.collections?.[l.collection],h=e.collections[l.collection].access.entityRestrictions;if(!h)throw new Error("PERMISSION_DENIED");const f=h.restrictions?.find(d=>d.type===o.type&&d.roles.some(m=>m.role===t.Role));if(!f)throw new Error("PERMISSION_DENIED");f.roles.forEach(d=>{d.role===t.Role&&(!h.assignable?.includes(t.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:f})})}),s},ui=(n,e,t)=>{const s=Object.values(e.collections),{labels:r}=n,i=[];for(const o of s){const{fields:a}=o;for(const l of a)if(!(l.access&&!Wn(l,t))&&t.Role&&X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)!i.find(h=>h.field===c.field)&&c.roles.includes(t.Role)&&i.push(c)}return i},Go=(n,e,t,s,r,i)=>{const{fields:o}=e,a=r.collections?.[e.labels.collection];let l=!0;if(!a){l=!1;return}const c=li(e,r),u=Ps(e,r),h=ci(e,t,r);c?.filter(p=>p.type==="Record_Owner").forEach(p=>{"operations"in p&&p.operations&&!p.operations.includes(n)||i.Created_By!==s&&(l=!1)}),c?.filter(p=>p.type==="Record_User").forEach(p=>{if("operations"in p&&p.operations&&!p.operations.includes(n))return;const T=W(o,p.collectionField);i[`${T.name}_Array`]?.includes(r.Doc_ID)||(l=!1)}),c?.filter(p=>p.type==="Record_Property").forEach(p=>{if("operations"in p&&p.operations&&!p.operations.includes(n))return;const T=W(o,p.propertyField),C=p.roles.find(v=>v.role===r.Role);T.type==="Array"?C.values?.some(v=>i[T.name].includes(v))||(l=!1):C.values?.includes(i[T.name])||(l=!1)});let f=!0,d=!1;u?.filter(p=>p.type==="Individual").forEach(()=>{d=!0,a.individualEntities?.includes(i.id)||(f=!1)});let m=!0,O=!1;if(u?.filter(p=>p.type==="Parent").forEach(p=>{O=!0;const T=W(o,p.collectionField);a.parentEntities?.some(C=>i[`${T.name}_Array`].includes(C))||(m=!1)}),u?.filter(p=>p.type==="Parent_Property").forEach(p=>{O=!0;const T=W(o,p.collectionField),C=W(o,p.propertyField);Object.entries(a.parentPropertyEntities||{}).some(v=>{const[Z,x]=v;return Z===i[C.name]&&i[`${T.name}_Array`].some(g=>x.includes(g))})||(m=!1)}),d&&O){if(!(f||m)){l=!1;return}}else if(!f||!m){l=!1;return}let y=!0,w=!1;h?.filter(p=>p.parentFilter.type==="Individual").forEach(p=>{w=!0;const{parentFilter:T}=p,C=W(o,T.collectionField),v=r.collections?.[C.collection];if(!v){l=!1;return}v.individualEntities?.some(Z=>i[`${C.name}_Array`].includes(Z))||(y=!1)});let b=!0,N=!1;if(h?.filter(p=>p.parentFilter.type==="Parent").forEach(p=>{N=!0;const{parentFilter:T}=p,C=W(o,T.collectionField),v=W(o,T.parentCollectionField),Z=r.collections?.[C.collection];if(!Z){l=!1;return}Z.parentEntities?.some(x=>i[`${v.name}_Array`].includes(x))||(b=!1)}),h?.filter(p=>p.parentFilter.type==="Parent_Property").forEach(p=>{N=!0;const{parentFilter:T}=p,C=W(o,T.collectionField),v=W(o,T.parentPropertyField),Z=W(o,T.parentCollectionField),x=r.collections?.[C.collection];if(!x){l=!1;return}Object.entries(x.parentPropertyEntities||{}).some(g=>{const[k,_]=g;return k===i[v.name]&&i[`${Z.name}_Array`].some(A=>_.includes(A))})||(b=!1)}),w&&N){if(!(y||b)){l=!1;return}}else if(!y||!b){l=!1;return}return l},it=(n,e,t,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;Se(n,a)||(l=!1);const u=Ps(e,r)?.filter(h=>h.type==="Individual").length>0;return n==="Create"&&u&&(l=!1),Go(n,e,t,s,r,i)||(l=!1),l},di=(n,e,t)=>{const{labels:s}=n,r=[];for(const i of Object.values(e.collections));return r},Yo=(n,e)=>{let t=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){t=!1,s="Permissions object must contain Doc_ID, Role, Collection, Enabled, and collections";return}}),e.collections&&(Object.keys(e.collections).forEach(r=>{if(!Object.keys(n.collections).includes(r)){s=`Collection ${r} not found in schema`,t=!1;return}const i=n.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,t=!1;return}if(!Object.keys(o).every(a=>["operations","auth","restrictEntities","individualEntities","parentEntities","parentPropertyEntities","recordProperty","recordUser","recordOwner"].includes(a))){s=`Collection ${r} has invalid properties`,t=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,t=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,t=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,t=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const u=i.access.attributeRestrictions?.filter(f=>f.type===c&&f.roles.some(d=>d.role===e.Role)),h=i.access.entityRestrictions?.restrictions?.filter(f=>f.type===c&&f.roles.some(d=>d.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(f=>n.config.roles.includes(f)))){s=`Collection ${r} has invalid entity restrictions assignable value`,t=!1;return}if(u?.length||h?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const f=Object.keys(l);if(f.length!==1||f[0]!=="active"||typeof l.active!="boolean"){s=`Collection ${r} has invalid attribute restriction value`,t=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,t=!1;return}if(a==="Parent"){const f=Object.keys(l);if(!(f.length===1&&Object.keys(n.collections).includes(f[0])&&Array.isArray(l[f[0]]))){s=`Collection ${r} has invalid parent entities value`,t=!1;return}}if(a==="Parent_Property"){const f=Object.keys(l);if(!(f.length===1&&Object.keys(n.collections).includes(f[0])&&typeof l[f[0]]=="object"&&l[f[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,t=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,t=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),t},Jo=(n,e,t)=>{let s=!0,r="";Object.values(n.collections).filter(i=>i.auth).forEach(i=>{if(e.collections?.[i.labels.collection]?.auth&&!i.access.auth?.includes(e.Role)){r="Record cannot have auth access to collection",s=!1;return}});for(const i of Object.values(n.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:u,entityRestrictions:h}=a,f=c.assignable,d=e.collections?.[o.collection],m=["read","create","update","delete"];if(f!==!0&&!(typeof f=="object"&&f.includes(t))?m.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const b=!!a.operations[y]?.includes(t),N=!!d?.operations.includes(w);if(!b&&N){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}if(b&&!N){r=`Collection ${o.collection} has missing ${y} operation for role ${t}`,s=!1;return}}}):m.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const b=!!a.operations[y]?.includes(t),N=!!d?.operations.includes(w);if(!b&&N){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}}}),!u&&!h||(u?.forEach(y=>{for(const w of y.roles)if(w.role===t&&!w.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${t}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${t}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${t}`,s=!1;return}}}),h?.assignable?.includes(t)))continue;let O=!1;if(h?.restrictions?.forEach(y=>{for(const w of y.roles)if(w.role===t){if(O=!0,y.type==="Individual"&&!e.collections?.[o.collection]?.individualEntities){r=`Collection ${o.collection} is missing individual entities`,s=!1;return}if(y.type==="Parent"){const b=W(l,y.collectionField);if(!X(b)){s=!1;return}if(!e.collections?.[o.collection]?.parentEntities){r=`Collection ${o.collection} is missing parent entities`,s=!1;return}}if(y.type==="Parent_Property"){const b=W(l,y.collectionField);if(!X(b)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[b.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),O&&!e.collections?.[o.collection]?.restrictEntities){r=`Collection ${o.collection} must have restrictEntities set to true`,s=!1;return}}return r&&console.error(`PERMISSION_DENIED: ${r}`),s},Qo=(n,e,t,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:u}=c;let h=!0,f="";const d=u?.filter(m=>s===m.userRole);return d?.length&&!d.some(m=>m.recordRole===r)?(f=`User ${s} does not have write access to record with role ${r}`,h=!1,h):n==="update"&&o.User_ID&&d?.length&&!d.some(m=>m.recordRole===a)?(f=`User ${s} does not have write access to record with role ${r}`,h=!1,h):(u?.forEach(m=>{s===m.userRole&&m.recordRole===r&&n!=="delete"&&i&&Object.keys(t.collections).forEach(O=>{const y=i.collections?.[O],w=l?.collections?.[O];if(!(n==="update"&&ze(y,w))&&y){const b=m.collections.some(N=>N.collection===O);if(b){if(b){const N=m.collections.find(T=>T.collection===O);if(!(y.operations.every(T=>N.operations.includes(T))||n==="update"&&ze(y.operations,w?.operations))){f=`User ${s} does not have write access to all included operations for collection ${O}`,h=!1;return}if(!N.auth&&y.auth&&!(n==="update"&&ze(y.auth,w?.auth))){f=`User ${s} does not have write access to auth for collection ${O}`,h=!1;return}const p={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(p).forEach(T=>{const C=p[T];if(N.attributeRestrictions?.includes(C)&&!(y[T]?.active||n==="update"&&ze(y[T],w?.[T]))){f=`User ${s} does not have write access to attribute restriction ${T} for collection ${O}`,h=!1;return}}),N.restrictEntities&&!y.restrictEntities&&!(n==="update"&&ze(y.restrictEntities,w?.restrictEntities))){f=`User ${s} does not have write access to restrictEntities for collection ${O}`,h=!1;return}}}else{f=`User ${s} does not have write access to collection ${O}`,h=!1;return}}})}),f&&console.error(`PERMISSION_DENIED: ${f}`),h)},Ko=(n,e,t,s)=>{let r=!0,i="";return Object.values(n.collections).forEach(o=>{const a=t.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!Un(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const u of a?.operations||[])if(!l?.operations.includes(u)&&(!Se("Read",c)||!Se(u,c))){i=`User does not have ${u.toLowerCase()} access to collection ${o.labels.collection}`,r=!1;return}if(!a?.recordOwner&&l?.recordOwner&&c?.recordOwner){i=`User does not have write access to recordOwner for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordUser&&l?.recordUser&&c?.recordUser){i=`User does not have write access to recordUser for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordProperty&&l?.recordProperty&&c?.recordProperty){i=`User does not have write access to recordProperty for collection ${o.labels.collection}`,r=!1;return}if(!a?.restrictEntities&&l?.restrictEntities&&c?.restrictEntities){i=`User does not have write access to restrictEntities for collection ${o.labels.collection}`,r=!1;return}}),i&&console.error(`PERMISSION_DENIED: ${i}`),r},Ls=(n,e,t,s,r,i,o,a,l,c,u)=>{const{labels:h}=s;let f=!0,d="";if(!e.Role)return d="Record does not have a role",f=!1,f;if(n==="update"&&!c)return d="Original record is required for update operations",f=!1,f;if(n==="update"&&i&&u==="update"&&a&&!l)return d="Original permissions are required for this operation",f=!1,f;if(i){if(!o?.Role)return d="Current user does not have a role",f=!1,f;if(!Qo(n,s,r,o.Role,e.Role,a,c,c?.Role,l))return f=!1,f;if(n==="update"&&u!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return d="User ID does not match original user ID",f=!1,f;if(n==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return d="User cannot update their own record",f=!1,f;if(n==="delete"&&i===e.User_ID)return d="User cannot delete their own record",f=!1,f}return n==="delete"||u==="delete"||!a?f:a.Role?(Yo(r,a)||(f=!1),a.Collection&&a.Collection!==h.collection?(d="Permissions collection does not match record collection",f=!1,f):a.Role!==e.Role?(d="Permissions role does not match record role",f=!1,f):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(d="Permissions enabled state does not match record enabled state",f=!1,f):a.Doc_ID&&a.Doc_ID!==t?(d="Permissions doc ID does not match record doc ID",f=!1,f):!Jo(r,a,a.Role)||i&&o&&l&&!Ko(r,o,a,l)?(f=!1,f):(d&&console.error(`PERMISSION_DENIED: ${d}`),f)):(d="Permissions do not have a role",f=!1,f)},ur=(n,e,t,s,r,i,o)=>{const{labels:a,fields:l}=t,c=i?.collections?.[a.collection];let u=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!Se("Create",c)&&(u=!1),r&&!it("Create",t,s,r,i,n)&&(u=!1),t.auth&&o&&(r&&!Un(c)&&(u=!1),Ls("create",n,e,t,s,r,i,o)||(u=!1));for(const h of l){const f=n[h.name];h.access&&!Wn(h,i)&&f!==void 0&&(u=!1),f!==void 0&&!Ho(h,i)&&(u=!1)}if(!u)throw new Error("PERMISSION_DENIED")},Ne=n=>n&&(n._methodName==="deleteField"||n.constructor.name==="DeleteTransform"),nt=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(Ne(n[e])?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&nt(n[e]))},dr=(n,e,t,s,r,i,o,a,l,c)=>{const{labels:u,fields:h}=s,f=o?.collections?.[u.collection],d={...e,...n};nt(d);let m=!0,O="";if(i&&!f)throw new Error("PERMISSION_DENIED");i&&!Se("Update",f)&&(m=!1,O="Authenticated user does not have Update access to this collection"),i&&(!it("Update",s,r,i,o,e)||!it("Update",s,r,i,o,d))&&(m=!1,O="Authenticated user does not have Update access to this document"),a&&(i&&!Un(f)&&(m=!1,O="Authenticated user does not have Auth access for this collection"),Ls("update",d,t,s,r,i,o,l,c,e,a)||(O="Authenticated user does not have sufficient write access for this record",m=!1));for(const y of h){const w=n[y.name];y.access&&!Wn(y,o)&&w!==void 0&&(O=`Authenticated user does not have access to field ${y.name}`,m=!1),w!==void 0&&!ai(y,o)&&(O=`Authenticated user does not have Update access to field ${y.name}`,m=!1)}if(!m)throw O&&console.error(`PERMISSION_DENIED: ${O}`),new Error("PERMISSION_DENIED")},Xo=(n,e,t,s,r,i)=>{const{labels:o}=t,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(Se("Delete",a)||(l=!1),it("Delete",t,s,r,i,n)||(l=!1),t.auth&&n.User_ID&&(Un(a)||(l=!1),Ls("delete",n,e,t,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},ea=async(n,e,t,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Se("Read",o)||(a=!1),it("Read",e,t,s,r,n)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},ta=async(n,e,t,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Se("Read",o)||(a=!1),n.forEach(l=>{it("Read",e,t,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},na=(n,e,t)=>{const{access:s}=n;return s.operations.assignable===!0||typeof s.operations.assignable=="object"&&s.operations.assignable.includes(e)||s.operations[t]?.includes(e)},sa=(n,e,t)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===n)&&!("singleQuery"in i&&i.singleQuery))return`${i.type} entity restriction`}if(r?.parentFilters)for(const i of r.parentFilters){if(!i.roles.some(c=>c.role===n))continue;const o=W(e.fields,i.collectionField);if(!X(o))throw new Error("PERMISSION_DENIED");const l=t.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(u=>u.role===n));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},ra=(n,e,t,s,r)=>{const i={};for(const o of n){const l=e[o].default(t,s,r);for(const c in l)c==="custom"||c==="admin"||c==="fields"||delete l[c];for(const c of l.fields)for(const u in c)u==="custom"||u==="admin"||u==="name"||u==="formula"||delete c[u];i[o]=l}return i},Ie=(n,e)=>e.fields.filter(t=>t.name===n.name)[0],Kn={global:{},collections:{}},qt=(n,e)=>n&&typeof n=="function"?e?n(...e):n():n,ie=async(n,e)=>{let t=n;return n&&(typeof n=="function"||typeof n.then=="function")&&(e?t=await n(...e):t=await n()),t},ia=async(n,e,t,s)=>{for(const u of e)if(u==="__proto__"||u==="constructor"||u==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=Kn,i=!0;for(const u of e){if(u===void 0||r[u]===void 0){i=!1;break}r=r[u]}if(r&&i&&!s)return r;let o,a=n,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const u of o){if(u===void 0||a[u]===void 0){l=!1;break}a=a[u]}let c;if(l&&(c=await ie(a,t)),c){let u=Kn;const h={};for(let f=0;f<e.length;f++){const d=e[f];if(d!==void 0){if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");f===e.length-1?zo(h,e.join("."),c):(u[d]||={},u=u[d])}}Zo(Kn,h)}return c},at=(n,e,t)=>{const s=Object.values(t.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field==n.name&&(i=!0)}return i},fi=(n,e)=>{const t=Object.values(e.collections),{labels:s}=n,r={};return t.forEach(i=>{const{labels:o,fields:a}=i;a.forEach(l=>{X(l)&&l.collection===s.collection&&l.dependencyFields&&l.dependencyFields.forEach(c=>{r[c.field]||={},r[c.field][o.collection]||=[],r[c.field][o.collection]=r[c.field][o.collection].concat(c.roles),r[c.field][o.collection]=[...new Set(r[c.field][o.collection])]})})}),r},Xn=n=>JSON.stringify(n.map(e=>e.name)),ht=["id","Collection_Path","Last_Write_At","Last_Save_At","Last_Write_By","Last_Write_App","Last_Write_Connection_Status","Last_Write_Version","Created_At","Saved_At","Created_By"],jn=()=>ht.map(n=>{let e="",t;switch(n){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",t=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:n,type:e,required:!0};return t&&(s.values=t),s}),hi=(n,e)=>{const t=[],{access:s,fields:r}=n,{attributeRestrictions:i,entityRestrictions:o}=s,a=jn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":t.push(W(a,"Created_By"));break;case"Record_User":t.push(W(r,l.collectionField));break;case"Record_Property":t.push(W(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(W(a,"id"));break;case"Parent":t.push(W(r,l.collectionField));break;case"Parent_Property":t.push(W(r,l.collectionField)),t.push(W(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(W(r,l.collectionField));break;case"Parent":t.push(W(r,l.parentCollectionField));break;case"Parent_Property":t.push(W(r,l.parentCollectionField)),t.push(W(r,l.parentPropertyField));break}})),[...new Set(t)]},oa=(n,e)=>{const t=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=n,a=jn();return t.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{(!c.access||c.access.includes(e))&&t.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{t.push(W(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{ht.includes(c)&&t.push(W(a,c))}),o?.forEach(c=>{const u=W(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&u&&(!u.access||u.access?.includes(e))&&ht.includes(c.field)&&t.push(W(a,c.field))}),hi(n,e).forEach(c=>{ht.includes(c.name)&&t.push(W(a,c.name))}),[...new Set(t)]},aa=(n,e,t)=>{const s=[],{fields:r,preloadCache:i}=e,o=jn();i?.range&&i.range.fields.forEach(c=>{ht.includes(c)?s.push(W(o,c)):s.push(W(r,c))});const a=new Set,l=fi(e,t);return Object.entries(l).map(([c,u])=>{n.name===c&&Object.values(u).forEach(h=>{h.forEach(f=>{a.add(f)})})}),a.forEach(c=>{s.push(...hi(e,c))}),[...new Set(s)]},un=(n,e,t)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=fi(e,t);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{t.collections[c].fields.forEach(h=>{X(h)&&h.collection===e.labels.collection&&h.dependencyFields?.some(f=>f.field===n.name)&&h.constraints&&h.constraints.forEach(f=>{o.push(f[0])})})})}),o.forEach(l=>{s.push(W(r,l))}),i){const l=W(r,i.archivedField);l&&s.push(l)}return s.push(...aa(n,e,t)),[...new Set(s)]},mi=(n,e)=>{const{preloadCache:t}=n,s=new Set;for(const r of e.config.roles){if(!na(n,r,"read"))continue;const i=oa(n,r);let o=!1;if(s.size===0)s.add({key:"1",roles:[r],fields:i}),o=!0;else for(const a of s)i.length===a.fields.length&&i.every(l=>a.fields.some(c=>c.name===l.name))&&!!t?.roles.includes(r)==!!a.roles.every(l=>t?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},pi=(n,e,t)=>{const s=mi(e,t);for(const r of s.values())if(r.roles.includes(n))return r},la=(n,e)=>{const{fields:t}=e,s=jn(),r=[];return[...t,...s.filter(o=>o.name!=="id")].forEach(o=>{n?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Vs=(n,e,t)=>{const s={};return Object.values(n.collections).forEach(r=>{const i=mi(r,n),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},kn=n=>({Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_Version:n.Last_Write_Version,Last_Write_App:n.Last_Write_App,Last_Save_At:n.Last_Save_At}),es=async(n,e,t)=>{if(e){const s=await ie(e,t);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${n}`);return s}};async function le(n,e,t,s){const r=await es(n,t.custom?.[n],s);for(const i of t.fields)await es(n,i.custom?.[n],s);if(n!=="setEmbedding"&&(await es(n,e?.[n],s),n==="postWriteError"))return r}const Us=(n,e,t,s,r,i,o,a,l,c)=>(n=="create"&&(t.Collection_Path=e,t.Created_At=a,t.Saved_At=l,t.Created_By=o||"System"),t.Last_Write_App=r,t.Last_Write_At=a,t.Last_Save_At=l,t.Last_Write_By=o||"System",t.Last_Write_Connection_Status=i,t.Last_Write_Version=s.version,t),ut=(n,e)=>{const{access:t,queries:s}=n,{serverReadOnly:r}=t,i=new Set;if(s)for(const o of s){const a=W(e,o.field);e.find(l=>l.name===o.field)&&X(a)&&["OneToOne","OneToMany"].includes(a.type)&&i.add(a)}return e.forEach(o=>{X(o)&&["OneToOne","OneToMany"].includes(o.type)&&o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a)))&&i.add(o)}),i},gt=(n,e)=>{const{access:t,recordTitleField:s}=n,{serverReadOnly:r}=t,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},bn=(n,e,t)=>{const{fields:s}=n;s.forEach(i=>{if(X(i))if(e[i.name]){if(Ne(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=t.collections[i.collection],l=W(a.fields,o);gt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(u=>{e[i.name][u][o]?e[i.name][u][`${o}_Lowercase`]=e[i.name][u][o].toLowerCase():delete e[i.name][u][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),ut(n,s).forEach(i=>{if(e[i.name])if(Ne(e[i.name]))e[`${i.name}_Single`]=e[i.name];else{const o=e[`${i.name}_Array`]?.[0];if(o){const a=e[i.name][o]||{};e[`${i.name}_Single`]={...a}}}})},Sn=(n,e)=>{gt(n,n.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},ca=async(n,e,t,s)=>{const{fields:r}=e;for(const i of t.fields){const o=W(r,i.name);i.custom?.initialValue&&!(s&&o.access&&!o.access.includes(s))&&(n[i.name]=await ie(i.custom.initialValue,[n]),gt(e,[o]).size===1&&(n[`${i.name}_Lowercase`]=n[i.name].toLowerCase()))}for(const i of r)s&&i.access&&!i.access.includes(s)||("autoIncrement"in i&&i.autoIncrement&&!n[i.name]&&(n[i.name]="Pending"),!X(i)&&i.nullable&&n[i.name]===void 0&&(n[i.name]=null))};var ne;(function(n){n.assertEqual=r=>{};function e(r){}n.assertIs=e;function t(r){throw new Error}n.assertNever=t,n.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},n.getValidEnumValues=r=>{const i=n.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return n.objectValues(o)},n.objectValues=r=>n.objectKeys(r).map(function(i){return r[i]}),n.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},n.find=(r,i)=>{for(const o of r)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=s,n.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(ne||(ne={}));var fr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(fr||(fr={}));const U=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xe=n=>{switch(typeof n){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN(n)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":return Array.isArray(n)?U.array:n===null?U.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?U.promise:typeof Map<"u"&&n instanceof Map?U.map:typeof Set<"u"&&n instanceof Set?U.set:typeof Date<"u"&&n instanceof Date?U.date:U.object;default:return U.unknown}},D=ne.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Be extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(t(o));else{let a=s,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof Be))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}Be.create=n=>new Be(n);const gs=(n,e)=>{let t;switch(n.code){case D.invalid_type:n.received===U.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case D.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,ne.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:t=`Unrecognized key(s) in object: ${ne.joinValues(n.keys,", ")}`;break;case D.invalid_union:t="Invalid input";break;case D.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${ne.joinValues(n.options)}`;break;case D.invalid_enum_value:t=`Invalid enum value. Expected ${ne.joinValues(n.options)}, received '${n.received}'`;break;case D.invalid_arguments:t="Invalid function arguments";break;case D.invalid_return_type:t="Invalid function return type";break;case D.invalid_date:t="Invalid date";break;case D.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:ne.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case D.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case D.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case D.custom:t="Invalid input";break;case D.invalid_intersection_types:t="Intersection results could not be merged";break;case D.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case D.not_finite:t="Number must be finite";break;default:t=e.defaultError,ne.assertNever(n)}return{message:t}};let ua=gs;function da(){return ua}const fa=n=>{const{data:e,path:t,errorMaps:s,issueData:r}=n,i=[...t,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)a=c(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function L(n,e){const t=da(),s=fa({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===gs?void 0:gs].filter(r=>!!r)});n.common.issues.push(s)}class Ee{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const r of t){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Ee.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return J;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const J=Object.freeze({status:"aborted"}),Bt=n=>({status:"dirty",value:n}),Ae=n=>({status:"valid",value:n}),hr=n=>n.status==="aborted",mr=n=>n.status==="dirty",xt=n=>n.status==="valid",Tn=n=>typeof Promise<"u"&&n instanceof Promise;var z;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));class We{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const pr=(n,e)=>{if(xt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Be(n.common.issues);return this._error=t,this._error}}};function Q(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:r}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=n;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:r}}class ee{get description(){return this._def.description}_getType(e){return Xe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ee,ctx:{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Tn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},r=this._parseSync({data:e,path:s.path,parent:s});return pr(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return xt(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>xt(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Tn(r)?r:Promise.resolve(r));return pr(s,i)}refine(e,t){const s=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:D.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof t=="function"?t(s,r):t),!1))}_refinement(e){return new At({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return st.create(this,this._def)}nullable(){return Ct.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ve.create(this)}promise(){return In.create(this,this._def)}or(e){return Nn.create([this,e],this._def)}and(e){return xn.create(this,e,this._def)}transform(e){return new At({...Q(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ks({...Q(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new $a({typeName:Y.ZodBranded,type:this,...Q(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new bs({...Q(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ws.create(this,e)}readonly(){return Ss.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ha=/^c[^\s-]{8,}$/i,ma=/^[0-9a-z]+$/,pa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ya=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ga=/^[a-z0-9_-]{21}$/i,wa=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,_a=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ea=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,va="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ts;const Oa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ka=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ba=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Sa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ta=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ra=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yi="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Na=new RegExp(`^${yi}$`);function gi(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function xa(n){return new RegExp(`^${gi(n)}$`)}function Da(n){let e=`${yi}T${gi(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ia(n,e){return!!((e==="v4"||!e)&&Oa.test(n)||(e==="v6"||!e)&&ba.test(n))}function Aa(n,e){if(!wa.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Ca(n,e){return!!((e==="v4"||!e)&&ka.test(n)||(e==="v6"||!e)&&Sa.test(n))}class qe extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){const i=this._getOrReturnCtx(e);return L(i,{code:D.invalid_type,expected:U.string,received:i.parsedType}),J}const s=new Ee;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?L(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&L(r,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")Ea.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"email",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")ts||(ts=new RegExp(va,"u")),ts.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"emoji",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")ya.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"uuid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")ga.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"nanoid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")ha.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cuid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")ma.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cuid2",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")pa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"ulid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),L(r,{validation:"url",code:D.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"regex",code:D.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Da(i).test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Na.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?xa(i).test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?_a.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"duration",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ia(e.data,i.version)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"ip",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Aa(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"jwt",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ca(e.data,i.version)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cidr",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Ta.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Ra.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"base64url",code:D.invalid_string,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(r=>e.test(r),{validation:t,code:D.invalid_string,...z.errToObj(s)})}_addCheck(e){return new qe({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...z.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...z.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...z.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...z.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...z.errToObj(t)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new qe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new qe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new qe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}qe.create=n=>new qe({checks:[],typeName:Y.ZodString,coerce:n?.coerce??!1,...Q(n)});function Fa(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=t>s?t:s,i=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Dt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==U.number){const i=this._getOrReturnCtx(e);return L(i,{code:D.invalid_type,expected:U.number,received:i.parsedType}),J}let s;const r=new Ee;for(const i of this._def.checks)i.kind==="int"?ne.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),L(s,{code:D.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Fa(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),L(s,{code:D.not_finite,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.toString(t))}setLimit(e,t,s,r){return new Dt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new Dt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Dt.create=n=>new Dt({checks:[],typeName:Y.ZodNumber,coerce:n?.coerce||!1,...Q(n)});class en extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==U.bigint)return this._getInvalidInput(e);let s;const r=new Ee;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return L(t,{code:D.invalid_type,expected:U.bigint,received:t.parsedType}),J}gte(e,t){return this.setLimit("min",e,!0,z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.toString(t))}setLimit(e,t,s,r){return new en({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new en({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}en.create=n=>new en({checks:[],typeName:Y.ZodBigInt,coerce:n?.coerce??!1,...Q(n)});class ws extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.boolean,received:s.parsedType}),J}return Ae(e.data)}}ws.create=n=>new ws({typeName:Y.ZodBoolean,coerce:n?.coerce||!1,...Q(n)});class Rn extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){const i=this._getOrReturnCtx(e);return L(i,{code:D.invalid_type,expected:U.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return L(i,{code:D.invalid_date}),J}const s=new Ee;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:D.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:D.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):ne.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Rn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Rn.create=n=>new Rn({checks:[],coerce:n?.coerce||!1,typeName:Y.ZodDate,...Q(n)});class yr extends ee{_parse(e){if(this._getType(e)!==U.symbol){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.symbol,received:s.parsedType}),J}return Ae(e.data)}}yr.create=n=>new yr({typeName:Y.ZodSymbol,...Q(n)});class _s extends ee{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.undefined,received:s.parsedType}),J}return Ae(e.data)}}_s.create=n=>new _s({typeName:Y.ZodUndefined,...Q(n)});class gr extends ee{_parse(e){if(this._getType(e)!==U.null){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.null,received:s.parsedType}),J}return Ae(e.data)}}gr.create=n=>new gr({typeName:Y.ZodNull,...Q(n)});class Es extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return Ae(e.data)}}Es.create=n=>new Es({typeName:Y.ZodAny,...Q(n)});class wr extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ae(e.data)}}wr.create=n=>new wr({typeName:Y.ZodUnknown,...Q(n)});class ot extends ee{_parse(e){const t=this._getOrReturnCtx(e);return L(t,{code:D.invalid_type,expected:U.never,received:t.parsedType}),J}}ot.create=n=>new ot({typeName:Y.ZodNever,...Q(n)});class _r extends ee{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.void,received:s.parsedType}),J}return Ae(e.data)}}_r.create=n=>new _r({typeName:Y.ZodVoid,...Q(n)});class Ve extends ee{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==U.array)return L(t,{code:D.invalid_type,expected:U.array,received:t.parsedType}),J;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(L(t,{code:o?D.too_big:D.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(L(t,{code:D.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(L(t,{code:D.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new We(t,o,t.path,a)))).then(o=>Ee.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new We(t,o,t.path,a)));return Ee.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new Ve({...this._def,minLength:{value:e,message:z.toString(t)}})}max(e,t){return new Ve({...this._def,maxLength:{value:e,message:z.toString(t)}})}length(e,t){return new Ve({...this._def,exactLength:{value:e,message:z.toString(t)}})}nonempty(e){return this.min(1,e)}}Ve.create=(n,e)=>new Ve({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...Q(e)});function kt(n){if(n instanceof fe){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=st.create(kt(s))}return new fe({...n._def,shape:()=>e})}else return n instanceof Ve?new Ve({...n._def,type:kt(n.element)}):n instanceof st?st.create(kt(n.unwrap())):n instanceof Ct?Ct.create(kt(n.unwrap())):n instanceof mt?mt.create(n.items.map(e=>kt(e))):n}class fe extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=ne.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==U.object){const c=this._getOrReturnCtx(e);return L(c,{code:D.invalid_type,expected:U.object,received:c.parsedType}),J}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const u=i[c],h=r.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new We(r,h,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ot){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(c==="strict")a.length>0&&(L(r,{code:D.unrecognized_keys,keys:a}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const h=r.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new We(r,h,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,f=await u.value;c.push({key:h,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>Ee.mergeObjectSync(s,c)):Ee.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new fe({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const r=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:z.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new fe({...this._def,unknownKeys:"strip"})}passthrough(){return new fe({...this._def,unknownKeys:"passthrough"})}extend(e){return new fe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new fe({...this._def,catchall:e})}pick(e){const t={};for(const s of ne.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new fe({...this._def,shape:()=>t})}omit(e){const t={};for(const s of ne.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new fe({...this._def,shape:()=>t})}deepPartial(){return kt(this)}partial(e){const t={};for(const s of ne.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new fe({...this._def,shape:()=>t})}required(e){const t={};for(const s of ne.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof st;)i=i._def.innerType;t[s]=i}return new fe({...this._def,shape:()=>t})}keyof(){return wi(ne.objectKeys(this.shape))}}fe.create=(n,e)=>new fe({shape:()=>n,unknownKeys:"strip",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});fe.strictCreate=(n,e)=>new fe({shape:()=>n,unknownKeys:"strict",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});fe.lazycreate=(n,e)=>new fe({shape:n,unknownKeys:"strip",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});class Nn extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Be(a.ctx.common.issues));return L(t,{code:D.invalid_union,unionErrors:o}),J}if(t.common.async)return Promise.all(s.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new Be(l));return L(t,{code:D.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}Nn.create=(n,e)=>new Nn({options:n,typeName:Y.ZodUnion,...Q(e)});function vs(n,e){const t=Xe(n),s=Xe(e);if(n===e)return{valid:!0,data:n};if(t===U.object&&s===U.object){const r=ne.objectKeys(e),i=ne.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(const a of i){const l=vs(n[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===U.array&&s===U.array){if(n.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<n.length;i++){const o=n[i],a=e[i],l=vs(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return t===U.date&&s===U.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class xn extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(hr(i)||hr(o))return J;const a=vs(i.value,o.value);return a.valid?((mr(i)||mr(o))&&t.dirty(),{status:t.value,value:a.data}):(L(s,{code:D.invalid_intersection_types}),J)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}xn.create=(n,e,t)=>new xn({left:n,right:e,typeName:Y.ZodIntersection,...Q(t)});class mt extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.array)return L(s,{code:D.invalid_type,expected:U.array,received:s.parsedType}),J;if(s.data.length<this._def.items.length)return L(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&s.data.length>this._def.items.length&&(L(s,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...s.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new We(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Ee.mergeArray(t,o)):Ee.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new mt({...this._def,rest:e})}}mt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:n,typeName:Y.ZodTuple,rest:null,...Q(e)})};class Dn extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.object)return L(s,{code:D.invalid_type,expected:U.object,received:s.parsedType}),J;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new We(s,a,s.path,a)),value:o._parse(new We(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Ee.mergeObjectAsync(t,r):Ee.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof ee?new Dn({keyType:e,valueType:t,typeName:Y.ZodRecord,...Q(s)}):new Dn({keyType:qe.create(),valueType:e,typeName:Y.ZodRecord,...Q(t)})}}class Er extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.map)return L(s,{code:D.invalid_type,expected:U.map,received:s.parsedType}),J;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,l],c)=>({key:r._parse(new We(s,a,s.path,[c,"key"])),value:i._parse(new We(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return J;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(c.value,u.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return J;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(c.value,u.value)}return{status:t.value,value:a}}}}Er.create=(n,e,t)=>new Er({valueType:e,keyType:n,typeName:Y.ZodMap,...Q(t)});class tn extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.set)return L(s,{code:D.invalid_type,expected:U.set,received:s.parsedType}),J;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(L(s,{code:D.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(L(s,{code:D.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const u of l){if(u.status==="aborted")return J;u.status==="dirty"&&t.dirty(),c.add(u.value)}return{status:t.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new We(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new tn({...this._def,minSize:{value:e,message:z.toString(t)}})}max(e,t){return new tn({...this._def,maxSize:{value:e,message:z.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}tn.create=(n,e)=>new tn({valueType:n,minSize:null,maxSize:null,typeName:Y.ZodSet,...Q(e)});class vr extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}vr.create=(n,e)=>new vr({getter:n,typeName:Y.ZodLazy,...Q(e)});class Os extends ee{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return L(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}Os.create=(n,e)=>new Os({value:n,typeName:Y.ZodLiteral,...Q(e)});function wi(n,e){return new It({values:n,typeName:Y.ZodEnum,...Q(e)})}class It extends ee{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return L(t,{expected:ne.joinValues(s),received:t.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return L(t,{received:t.data,code:D.invalid_enum_value,options:s}),J}return Ae(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return It.create(e,{...this._def,...t})}exclude(e,t=this._def){return It.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}It.create=wi;class Or extends ee{_parse(e){const t=ne.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==U.string&&s.parsedType!==U.number){const r=ne.objectValues(t);return L(s,{expected:ne.joinValues(r),received:s.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=ne.objectValues(t);return L(s,{received:s.data,code:D.invalid_enum_value,options:r}),J}return Ae(e.data)}get enum(){return this._def.values}}Or.create=(n,e)=>new Or({values:n,typeName:Y.ZodNativeEnum,...Q(e)});class In extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.promise&&t.common.async===!1)return L(t,{code:D.invalid_type,expected:U.promise,received:t.parsedType}),J;const s=t.parsedType===U.promise?t.data:Promise.resolve(t.data);return Ae(s.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}In.create=(n,e)=>new In({type:n,typeName:Y.ZodPromise,...Q(e)});class At extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{L(s,o),o.fatal?t.abort():t.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return J;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?J:l.status==="dirty"||t.value==="dirty"?Bt(l.value):l});{if(t.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?J:a.status==="dirty"||t.value==="dirty"?Bt(a.value):a}}if(r.type==="refinement"){const o=a=>{const l=r.refinement(a,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!xt(o))return J;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>xt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):J);ne.assertNever(r)}}At.create=(n,e,t)=>new At({schema:n,typeName:Y.ZodEffects,effect:e,...Q(t)});At.createWithPreprocess=(n,e,t)=>new At({schema:e,effect:{type:"preprocess",transform:n},typeName:Y.ZodEffects,...Q(t)});class st extends ee{_parse(e){return this._getType(e)===U.undefined?Ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}st.create=(n,e)=>new st({innerType:n,typeName:Y.ZodOptional,...Q(e)});class Ct extends ee{_parse(e){return this._getType(e)===U.null?Ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ct.create=(n,e)=>new Ct({innerType:n,typeName:Y.ZodNullable,...Q(e)});class ks extends ee{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===U.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ks.create=(n,e)=>new ks({innerType:n,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});class bs extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Tn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Be(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Be(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}bs.create=(n,e)=>new bs({innerType:n,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});class kr extends ee{_parse(e){if(this._getType(e)!==U.nan){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.nan,received:s.parsedType}),J}return{status:"valid",value:e.data}}}kr.create=n=>new kr({typeName:Y.ZodNaN,...Q(n)});class $a extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ws extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?J:i.status==="dirty"?(t.dirty(),Bt(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?J:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,t){return new Ws({in:e,out:t,typeName:Y.ZodPipeline})}}class Ss extends ee{_parse(e){const t=this._def.innerType._parse(e),s=r=>(xt(r)&&(r.value=Object.freeze(r.value)),r);return Tn(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}Ss.create=(n,e)=>new Ss({innerType:n,typeName:Y.ZodReadonly,...Q(e)});var Y;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Y||(Y={}));const ke=qe.create,dt=Dt.create,Kt=ws.create,ns=_s.create,ye=Es.create;ot.create;const wt=Ve.create,Ue=fe.create,ve=Nn.create;xn.create;mt.create;const rn=Dn.create,Oe=Os.create,An=It.create;In.create;st.create;Ct.create;const gn=()=>ye().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),br=()=>ye().refine(n=>n&&(n._methodName==="serverTimestamp"||n.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),_i=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return rn(ye());n.includeFields.forEach(r=>{const i=s.fields.find(a=>a.name===r);if(!i)throw new Error(`Field ${r} not found in collection ${n.collection}`);t[r]=Cn(s,i),gt(s,[i]).size===1&&(t[`${r}_Lowercase`]=Cn(s,i,!0))})}return Ue({Collection_Path:wt(ke()),...t})},Ma=(n,e)=>{let t=rn(_i(n,e));return n.required||(t=t.optional()),t},Pa=n=>{let e=wt(ve([ke().length(20),ke().length(28)]));return["OneToOne","OneToMany"].includes(n.type)?e=e.max(1):(n.min&&(e=e.min(n.min)),n.max&&(e=e.max(n.max)),n.length&&(e=e.length(n.length))),n.required?e=e.nonempty():e=e.optional(),e},Cn=(n,e,t)=>{const{softDelete:s}=n,r=s?.timestampField;let i;switch(e.type){case"String":if(i=ke(),e.length&&(i=i.length(e.length)),e.minlength&&(i=i.min(e.minlength)),e.maxlength&&(i=i.max(e.maxlength)),e.email&&(i=i.email()),e.uuid&&(i=i.uuid()),e.url&&(i=i.url()),e.emoji&&(i=i.emoji()),e.ip&&(i=i.ip()),e.pattern&&(i=i.regex(new RegExp(e.pattern))),t&&(i=i.toLowerCase()),e.values)if(t){const o=e.values.map(a=>a.toLowerCase());i=An(o)}else i=An(e.values);break;case"Boolean":i=Kt();break;case"Number":e.autoIncrement?i=ve([Oe("Pending"),dt().int()]):(i=dt(),e.min&&(i=i.min(e.min)),e.max&&(i=i.max(e.max)),e.decimal?i=i.refine(o=>e.decimal?(o.toString().split(".")[1]?.length||0)<=e.decimal:!1,{message:`Value must have ${e.decimal} or fewer decimal places`}):i=i.int(),e.values&&(i=i.refine(o=>e.values?.includes(o),{message:"Value is not an allowed value"})));break;case"Timestamp":e.name===r?i=ye().refine(o=>o&&(o._methodName==="serverTimestamp"||o.constructor.name==="ServerTimestampTransform"||o.seconds!==void 0&&o.nanoseconds!==void 0||o._seconds!==void 0&&o._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}):(i=gn(),e.min&&(i=i.refine(o=>o.toMillis()>=e.min,{message:`Value is less than the minimum allowed value of ${e.min}`})),e.max&&(i=i.refine(o=>o.toMillis()<=e.max,{message:`Value is greater than the maximum allowed value of ${e.max}`})));break;case"Array":i=wt(ye()),e.length&&(i=i.length(e.length)),e.minlength?i=i.min(e.minlength):e.required&&(i=i.nonempty()),e.maxlength&&(i=i.max(e.maxlength)),e.values&&(i=i.refine(o=>{let a=!0;return o.forEach(l=>{e.values&&!e.values.includes(l)&&(a=!1)}),a},{message:"Value is not an allowed value"}));break;case"Map":i=rn(ye()),e.required&&(i=i.refine(o=>o&&typeof o=="object"&&Object.keys(o).length>0,{message:"Value must have at least one object property"}));break;case"Embedding":i=ye();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},Ei=(n,e,t)=>{const s={Collection_Path:wt(ke()),Last_Write_App:ke(),Last_Write_At:gn(),Last_Save_At:br(),Last_Write_By:ve([ke().length(28),Oe("System")]),Last_Write_Connection_Status:An(["Online","Offline"]),Last_Write_Version:dt().int(),id:ke().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:gn(),Created_By:ve([ke().length(28),Oe("System")])};n==="create"&&(s.Saved_At=br()),n==="update"&&(s.Saved_At=gn(),s.Collection_Path=s.Collection_Path.optional(),s.id=s.id.optional(),s.Created_At=s.Created_At.optional(),s.Saved_At=s.Saved_At.optional(),s.Created_By=s.Created_By.optional());const r=ut(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{X(l)?(s[l.name]=Ma(l,t),s[`${l.name}_Array`]=Pa(l),i.includes(l.name)&&(s[`${l.name}_Single`]=_i(l,t),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=Cn(e,l))}),gt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=Cn(e,l,!0))});const a=Ue(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class _t extends Error{}class La extends _t{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Va extends _t{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class Ua extends _t{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class bt extends _t{}class vi extends _t{constructor(e){super(`Invalid unit ${e}`)}}class ge extends _t{}class Ke extends _t{constructor(){super("Zone is an abstract class")}}const F="numeric",Me="short",be="long",Fn={year:F,month:F,day:F},Oi={year:F,month:Me,day:F},Wa={year:F,month:Me,day:F,weekday:Me},ki={year:F,month:be,day:F},bi={year:F,month:be,day:F,weekday:be},Si={hour:F,minute:F},Ti={hour:F,minute:F,second:F},Ri={hour:F,minute:F,second:F,timeZoneName:Me},Ni={hour:F,minute:F,second:F,timeZoneName:be},xi={hour:F,minute:F,hourCycle:"h23"},Di={hour:F,minute:F,second:F,hourCycle:"h23"},Ii={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:Me},Ai={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:be},Ci={year:F,month:F,day:F,hour:F,minute:F},Fi={year:F,month:F,day:F,hour:F,minute:F,second:F},$i={year:F,month:Me,day:F,hour:F,minute:F},Mi={year:F,month:Me,day:F,hour:F,minute:F,second:F},ja={year:F,month:Me,day:F,weekday:Me,hour:F,minute:F},Pi={year:F,month:be,day:F,hour:F,minute:F,timeZoneName:Me},Li={year:F,month:be,day:F,hour:F,minute:F,second:F,timeZoneName:Me},Vi={year:F,month:be,day:F,weekday:be,hour:F,minute:F,timeZoneName:be},Ui={year:F,month:be,day:F,weekday:be,hour:F,minute:F,second:F,timeZoneName:be};class on{get type(){throw new Ke}get name(){throw new Ke}get ianaName(){return this.name}get isUniversal(){throw new Ke}offsetName(e,t){throw new Ke}formatOffset(e,t){throw new Ke}offset(e){throw new Ke}equals(e){throw new Ke}get isValid(){throw new Ke}}let ss=null;class Zn extends on{static get instance(){return ss===null&&(ss=new Zn),ss}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Qi(e,t,s)}formatOffset(e,t){return Xt(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Ts=new Map;function Za(n){let e=Ts.get(n);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Ts.set(n,e)),e}const za={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function qa(n,e){const t=n.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,r,i,o,a,l,c,u]=s;return[o,r,i,a,l,c,u]}function Ba(n,e){const t=n.formatToParts(e),s=[];for(let r=0;r<t.length;r++){const{type:i,value:o}=t[r],a=za[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const rs=new Map;class He extends on{static create(e){let t=rs.get(e);return t===void 0&&rs.set(e,t=new He(e)),t}static resetCache(){rs.clear(),Ts.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=He.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Qi(e,t,s,this.name)}formatOffset(e,t){return Xt(this.offset(e),t)}offset(e){if(!this.valid)return NaN;const t=new Date(e);if(isNaN(t))return NaN;const s=Za(this.name);let[r,i,o,a,l,c,u]=s.formatToParts?Ba(s,t):qa(s,t);a==="BC"&&(r=-Math.abs(r)+1);const f=qn({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:u,millisecond:0});let d=+t;const m=d%1e3;return d-=m>=0?m:1e3+m,(f-d)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Sr={};function Ha(n,e={}){const t=JSON.stringify([n,e]);let s=Sr[t];return s||(s=new Intl.ListFormat(n,e),Sr[t]=s),s}const Rs=new Map;function Ns(n,e={}){const t=JSON.stringify([n,e]);let s=Rs.get(t);return s===void 0&&(s=new Intl.DateTimeFormat(n,e),Rs.set(t,s)),s}const xs=new Map;function Ga(n,e={}){const t=JSON.stringify([n,e]);let s=xs.get(t);return s===void 0&&(s=new Intl.NumberFormat(n,e),xs.set(t,s)),s}const Ds=new Map;function Ya(n,e={}){const{base:t,...s}=e,r=JSON.stringify([n,s]);let i=Ds.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(n,e),Ds.set(r,i)),i}let Ht=null;function Ja(){return Ht||(Ht=new Intl.DateTimeFormat().resolvedOptions().locale,Ht)}const Is=new Map;function Wi(n){let e=Is.get(n);return e===void 0&&(e=new Intl.DateTimeFormat(n).resolvedOptions(),Is.set(n,e)),e}const As=new Map;function Qa(n){let e=As.get(n);if(!e){const t=new Intl.Locale(n);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,"minimalDays"in e||(e={...ji,...e}),As.set(n,e)}return e}function Ka(n){const e=n.indexOf("-x-");e!==-1&&(n=n.substring(0,e));const t=n.indexOf("-u-");if(t===-1)return[n];{let s,r;try{s=Ns(n).resolvedOptions(),r=n}catch{const l=n.substring(0,t);s=Ns(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function Xa(n,e,t){return(t||e)&&(n.includes("-u-")||(n+="-u"),t&&(n+=`-ca-${t}`),e&&(n+=`-nu-${e}`)),n}function el(n){const e=[];for(let t=1;t<=12;t++){const s=V.utc(2009,t,1);e.push(n(s))}return e}function tl(n){const e=[];for(let t=1;t<=7;t++){const s=V.utc(2016,11,13+t);e.push(n(s))}return e}function dn(n,e,t,s){const r=n.listingMode();return r==="error"?null:r==="en"?t(e):s(e)}function nl(n){return n.numberingSystem&&n.numberingSystem!=="latn"?!1:n.numberingSystem==="latn"||!n.locale||n.locale.startsWith("en")||Wi(n.locale).numberingSystem==="latn"}class sl{constructor(e,t,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!t||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=Ga(e,a)}}format(e){if(this.inf){const t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{const t=this.floor?Math.floor(e):Bs(e,3);return he(t,this.padTo)}}}class rl{constructor(e,t,s){this.opts=s,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&He.create(a).valid?(r=a,this.dt=e):(r="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,r=e.zone.name):(r="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const i={...this.opts};i.timeZone=i.timeZone||r,this.dtf=Ns(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:s}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class il{constructor(e,t,s){this.opts={style:"long",...s},!t&&Yi()&&(this.rtf=Ya(e,s))}format(e,t){return this.rtf?this.rtf.format(e,t):Rl(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}}const ji={firstDay:1,minimalDays:4,weekend:[6,7]};class re{static fromOpts(e){return re.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,s,r,i=!1){const o=e||ue.defaultLocale,a=o||(i?"en-US":Ja()),l=t||ue.defaultNumberingSystem,c=s||ue.defaultOutputCalendar,u=Fs(r)||ue.defaultWeekSettings;return new re(a,l,c,u,o)}static resetCache(){Ht=null,Rs.clear(),xs.clear(),Ds.clear(),Is.clear(),As.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:r}={}){return re.create(e,t,s,r)}constructor(e,t,s,r,i){const[o,a,l]=Ka(e);this.locale=o,this.numberingSystem=t||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=Xa(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=nl(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:re.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,Fs(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return dn(this,e,eo,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");t&=!s;const r=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";if(!this.monthsCache[i][e]){const o=s?a=>this.dtFormatter(a,r).format():a=>this.extract(a,r,"month");this.monthsCache[i][e]=el(o)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return dn(this,e,so,()=>{const s=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=t?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=tl(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return dn(this,void 0,()=>ro,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[V.utc(2016,11,13,9),V.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return dn(this,e,io,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[V.utc(-40,1,1),V.utc(2017,1,1)].map(s=>this.extract(s,t,"era"))),this.eraCache[e]})}extract(e,t,s){const r=this.dtFormatter(e,t),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new sl(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new rl(e,this.intl,t)}relFormatter(e={}){return new il(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Ha(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||Wi(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Ji()?Qa(this.locale):ji}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let is=null;class _e extends on{static get utcInstance(){return is===null&&(is=new _e(0)),is}static instance(e){return e===0?_e.utcInstance:new _e(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new _e(Bn(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Xt(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Xt(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return Xt(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class ol extends on{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function tt(n,e){if(G(n)||n===null)return e;if(n instanceof on)return n;if(fl(n)){const t=n.toLowerCase();return t==="default"?e:t==="local"||t==="system"?Zn.instance:t==="utc"||t==="gmt"?_e.utcInstance:_e.parseSpecifier(t)||He.create(n)}else return rt(n)?_e.instance(n):typeof n=="object"&&"offset"in n&&typeof n.offset=="function"?n:new ol(n)}const js={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Tr={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},al=js.hanidec.replace(/[\[|\]]/g,"").split("");function ll(n){let e=parseInt(n,10);if(isNaN(e)){e="";for(let t=0;t<n.length;t++){const s=n.charCodeAt(t);if(n[t].search(js.hanidec)!==-1)e+=al.indexOf(n[t]);else for(const r in Tr){const[i,o]=Tr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const Cs=new Map;function cl(){Cs.clear()}function Ce({numberingSystem:n},e=""){const t=n||"latn";let s=Cs.get(t);s===void 0&&(s=new Map,Cs.set(t,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${js[t]}${e}`),s.set(e,r)),r}let Rr=()=>Date.now(),Nr="system",xr=null,Dr=null,Ir=null,Ar=60,Cr,Fr=null;class ue{static get now(){return Rr}static set now(e){Rr=e}static set defaultZone(e){Nr=e}static get defaultZone(){return tt(Nr,Zn.instance)}static get defaultLocale(){return xr}static set defaultLocale(e){xr=e}static get defaultNumberingSystem(){return Dr}static set defaultNumberingSystem(e){Dr=e}static get defaultOutputCalendar(){return Ir}static set defaultOutputCalendar(e){Ir=e}static get defaultWeekSettings(){return Fr}static set defaultWeekSettings(e){Fr=Fs(e)}static get twoDigitCutoffYear(){return Ar}static set twoDigitCutoffYear(e){Ar=e%100}static get throwOnInvalid(){return Cr}static set throwOnInvalid(e){Cr=e}static resetCaches(){re.resetCache(),He.resetCache(),V.resetCache(),cl()}}class $e{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Zi=[0,31,59,90,120,151,181,212,243,273,304,334],zi=[0,31,60,91,121,152,182,213,244,274,305,335];function xe(n,e){return new $e("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${n}, which is invalid`)}function Zs(n,e,t){const s=new Date(Date.UTC(n,e-1,t));n<100&&n>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function qi(n,e,t){return t+(an(n)?zi:Zi)[e-1]}function Bi(n,e){const t=an(n)?zi:Zi,s=t.findIndex(i=>i<e),r=e-t[s];return{month:s+1,day:r}}function zs(n,e){return(n-e+7)%7+1}function $n(n,e=4,t=1){const{year:s,month:r,day:i}=n,o=qi(s,r,i),a=zs(Zs(s,r,i),t);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=nn(c,e,t)):l>nn(s,e,t)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...Hn(n)}}function $r(n,e=4,t=1){const{weekYear:s,weekNumber:r,weekday:i}=n,o=zs(Zs(s,1,e),t),a=Rt(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=Rt(c)):l>a?(c=s+1,l-=Rt(s)):c=s;const{month:u,day:h}=Bi(c,l);return{year:c,month:u,day:h,...Hn(n)}}function os(n){const{year:e,month:t,day:s}=n,r=qi(e,t,s);return{year:e,ordinal:r,...Hn(n)}}function Mr(n){const{year:e,ordinal:t}=n,{month:s,day:r}=Bi(e,t);return{year:e,month:s,day:r,...Hn(n)}}function Pr(n,e){if(!G(n.localWeekday)||!G(n.localWeekNumber)||!G(n.localWeekYear)){if(!G(n.weekday)||!G(n.weekNumber)||!G(n.weekYear))throw new bt("Cannot mix locale-based week fields with ISO-based week fields");return G(n.localWeekday)||(n.weekday=n.localWeekday),G(n.localWeekNumber)||(n.weekNumber=n.localWeekNumber),G(n.localWeekYear)||(n.weekYear=n.localWeekYear),delete n.localWeekday,delete n.localWeekNumber,delete n.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function ul(n,e=4,t=1){const s=zn(n.weekYear),r=De(n.weekNumber,1,nn(n.weekYear,e,t)),i=De(n.weekday,1,7);return s?r?i?!1:xe("weekday",n.weekday):xe("week",n.weekNumber):xe("weekYear",n.weekYear)}function dl(n){const e=zn(n.year),t=De(n.ordinal,1,Rt(n.year));return e?t?!1:xe("ordinal",n.ordinal):xe("year",n.year)}function Hi(n){const e=zn(n.year),t=De(n.month,1,12),s=De(n.day,1,Mn(n.year,n.month));return e?t?s?!1:xe("day",n.day):xe("month",n.month):xe("year",n.year)}function Gi(n){const{hour:e,minute:t,second:s,millisecond:r}=n,i=De(e,0,23)||e===24&&t===0&&s===0&&r===0,o=De(t,0,59),a=De(s,0,59),l=De(r,0,999);return i?o?a?l?!1:xe("millisecond",r):xe("second",s):xe("minute",t):xe("hour",e)}function G(n){return typeof n>"u"}function rt(n){return typeof n=="number"}function zn(n){return typeof n=="number"&&n%1===0}function fl(n){return typeof n=="string"}function hl(n){return Object.prototype.toString.call(n)==="[object Date]"}function Yi(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ji(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function ml(n){return Array.isArray(n)?n:[n]}function Lr(n,e,t){if(n.length!==0)return n.reduce((s,r)=>{const i=[e(r),r];return s&&t(s[0],i[0])===s[0]?s:i},null)[1]}function pl(n,e){return e.reduce((t,s)=>(t[s]=n[s],t),{})}function Ft(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Fs(n){if(n==null)return null;if(typeof n!="object")throw new ge("Week settings must be an object");if(!De(n.firstDay,1,7)||!De(n.minimalDays,1,7)||!Array.isArray(n.weekend)||n.weekend.some(e=>!De(e,1,7)))throw new ge("Invalid week settings");return{firstDay:n.firstDay,minimalDays:n.minimalDays,weekend:Array.from(n.weekend)}}function De(n,e,t){return zn(n)&&n>=e&&n<=t}function yl(n,e){return n-e*Math.floor(n/e)}function he(n,e=2){const t=n<0;let s;return t?s="-"+(""+-n).padStart(e,"0"):s=(""+n).padStart(e,"0"),s}function et(n){if(!(G(n)||n===null||n===""))return parseInt(n,10)}function lt(n){if(!(G(n)||n===null||n===""))return parseFloat(n)}function qs(n){if(!(G(n)||n===null||n==="")){const e=parseFloat("0."+n)*1e3;return Math.floor(e)}}function Bs(n,e,t="round"){const s=10**e;switch(t){case"expand":return n>0?Math.ceil(n*s)/s:Math.floor(n*s)/s;case"trunc":return Math.trunc(n*s)/s;case"round":return Math.round(n*s)/s;case"floor":return Math.floor(n*s)/s;case"ceil":return Math.ceil(n*s)/s;default:throw new RangeError(`Value rounding ${t} is out of range`)}}function an(n){return n%4===0&&(n%100!==0||n%400===0)}function Rt(n){return an(n)?366:365}function Mn(n,e){const t=yl(e-1,12)+1,s=n+(e-t)/12;return t===2?an(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function qn(n){let e=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return n.year<100&&n.year>=0&&(e=new Date(e),e.setUTCFullYear(n.year,n.month-1,n.day)),+e}function Vr(n,e,t){return-zs(Zs(n,1,e),t)+e-1}function nn(n,e=4,t=1){const s=Vr(n,e,t),r=Vr(n+1,e,t);return(Rt(n)-s+r)/7}function $s(n){return n>99?n:n>ue.twoDigitCutoffYear?1900+n:2e3+n}function Qi(n,e,t,s=null){const r=new Date(n),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(t,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function Bn(n,e){let t=parseInt(n,10);Number.isNaN(t)&&(t=0);const s=parseInt(e,10)||0,r=t<0||Object.is(t,-0)?-s:s;return t*60+r}function Ki(n){const e=Number(n);if(typeof n=="boolean"||n===""||!Number.isFinite(e))throw new ge(`Invalid unit value ${n}`);return e}function Pn(n,e){const t={};for(const s in n)if(Ft(n,s)){const r=n[s];if(r==null)continue;t[e(s)]=Ki(r)}return t}function Xt(n,e){const t=Math.trunc(Math.abs(n/60)),s=Math.trunc(Math.abs(n%60)),r=n>=0?"+":"-";switch(e){case"short":return`${r}${he(t,2)}:${he(s,2)}`;case"narrow":return`${r}${t}${s>0?`:${s}`:""}`;case"techie":return`${r}${he(t,2)}${he(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Hn(n){return pl(n,["hour","minute","second","millisecond"])}const gl=["January","February","March","April","May","June","July","August","September","October","November","December"],Xi=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wl=["J","F","M","A","M","J","J","A","S","O","N","D"];function eo(n){switch(n){case"narrow":return[...wl];case"short":return[...Xi];case"long":return[...gl];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const to=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],no=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],_l=["M","T","W","T","F","S","S"];function so(n){switch(n){case"narrow":return[..._l];case"short":return[...no];case"long":return[...to];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const ro=["AM","PM"],El=["Before Christ","Anno Domini"],vl=["BC","AD"],Ol=["B","A"];function io(n){switch(n){case"narrow":return[...Ol];case"short":return[...vl];case"long":return[...El];default:return null}}function kl(n){return ro[n.hour<12?0:1]}function bl(n,e){return so(e)[n.weekday-1]}function Sl(n,e){return eo(e)[n.month-1]}function Tl(n,e){return io(e)[n.year<0?0:1]}function Rl(n,e,t="always",s=!1){const r={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(n)===-1;if(t==="auto"&&i){const h=n==="days";switch(e){case 1:return h?"tomorrow":`next ${r[n][0]}`;case-1:return h?"yesterday":`last ${r[n][0]}`;case 0:return h?"today":`this ${r[n][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[n],u=s?l?c[1]:c[2]||c[1]:l?r[n][0]:n;return o?`${a} ${u} ago`:`in ${a} ${u}`}function Ur(n,e){let t="";for(const s of n)s.literal?t+=s.val:t+=e(s.val);return t}const Nl={D:Fn,DD:Oi,DDD:ki,DDDD:bi,t:Si,tt:Ti,ttt:Ri,tttt:Ni,T:xi,TT:Di,TTT:Ii,TTTT:Ai,f:Ci,ff:$i,fff:Pi,ffff:Vi,F:Fi,FF:Mi,FFF:Li,FFFF:Ui};class we{static create(e,t={}){return new we(e,t)}static parseFormat(e){let t=null,s="",r=!1;const i=[];for(let o=0;o<e.length;o++){const a=e.charAt(o);a==="'"?((s.length>0||r)&&i.push({literal:r||/^\s+$/.test(s),val:s===""?"'":s}),t=null,s="",r=!r):r||a===t?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,t=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return Nl[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,s=void 0){if(this.opts.forceSimple)return he(e,t);const r={...this.opts};return t>0&&(r.padTo=t),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,t){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(d,m)=>this.loc.extract(e,d,m),o=d=>e.isOffsetFixed&&e.offset===0&&d.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,d.format):"",a=()=>s?kl(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(d,m)=>s?Sl(e,d):i(m?{month:d}:{month:d,day:"numeric"},"month"),c=(d,m)=>s?bl(e,d):i(m?{weekday:d}:{weekday:d,month:"long",day:"numeric"},"weekday"),u=d=>{const m=we.macroTokenToFormatOpts(d);return m?this.formatWithSystemDefault(e,m):d},h=d=>s?Tl(e,d):i({era:d},"era"),f=d=>{switch(d){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return r?i({day:"numeric"},"day"):this.num(e.day);case"dd":return r?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return r?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return r?i({month:"numeric"},"month"):this.num(e.month);case"MM":return r?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return r?i({year:"numeric"},"year"):this.num(e.year);case"yy":return r?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return h("short");case"GG":return h("long");case"GGGGG":return h("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(d)}};return Ur(we.parseFormat(t),f)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=u=>{switch(u[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(u,h)=>f=>{const d=r(f);if(d){const m=h.isNegativeDuration&&d!==h.largestUnit?s:1;let O;return this.opts.signMode==="negativeLargestOnly"&&d!==h.largestUnit?O="never":this.opts.signMode==="all"?O="always":O="auto",this.num(u.get(d)*m,f.length,O)}else return f},o=we.parseFormat(t),a=o.reduce((u,{literal:h,val:f})=>h?u:u.concat(f),[]),l=e.shiftTo(...a.map(r).filter(u=>u)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Ur(o,i(l,c))}}const oo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function $t(...n){const e=n.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function Mt(...n){return e=>n.reduce(([t,s,r],i)=>{const[o,a,l]=i(e,r);return[{...t,...o},a||s,l]},[{},null,1]).slice(0,2)}function Pt(n,...e){if(n==null)return[null,null];for(const[t,s]of e){const r=t.exec(n);if(r)return s(r)}return[null,null]}function ao(...n){return(e,t)=>{const s={};let r;for(r=0;r<n.length;r++)s[n[r]]=et(e[t+r]);return[s,null,t+r]}}const lo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,xl=`(?:${lo.source}?(?:\\[(${oo.source})\\])?)?`,Hs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,co=RegExp(`${Hs.source}${xl}`),Gs=RegExp(`(?:[Tt]${co.source})?`),Dl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Il=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Al=/(\d{4})-?(\d{3})/,Cl=ao("weekYear","weekNumber","weekDay"),Fl=ao("year","ordinal"),$l=/(\d{4})-(\d\d)-(\d\d)/,uo=RegExp(`${Hs.source} ?(?:${lo.source}|(${oo.source}))?`),Ml=RegExp(`(?: ${uo.source})?`);function Nt(n,e,t){const s=n[e];return G(s)?t:et(s)}function Pl(n,e){return[{year:Nt(n,e),month:Nt(n,e+1,1),day:Nt(n,e+2,1)},null,e+3]}function Lt(n,e){return[{hours:Nt(n,e,0),minutes:Nt(n,e+1,0),seconds:Nt(n,e+2,0),milliseconds:qs(n[e+3])},null,e+4]}function ln(n,e){const t=!n[e]&&!n[e+1],s=Bn(n[e+1],n[e+2]),r=t?null:_e.instance(s);return[{},r,e+3]}function cn(n,e){const t=n[e]?He.create(n[e]):null;return[{},t,e+1]}const Ll=RegExp(`^T?${Hs.source}$`),Vl=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Ul(n){const[e,t,s,r,i,o,a,l,c]=n,u=e[0]==="-",h=l&&l[0]==="-",f=(d,m=!1)=>d!==void 0&&(m||d&&u)?-d:d;return[{years:f(lt(t)),months:f(lt(s)),weeks:f(lt(r)),days:f(lt(i)),hours:f(lt(o)),minutes:f(lt(a)),seconds:f(lt(l),l==="-0"),milliseconds:f(qs(c),h)}]}const Wl={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Ys(n,e,t,s,r,i,o){const a={year:e.length===2?$s(et(e)):et(e),month:Xi.indexOf(t)+1,day:et(s),hour:et(r),minute:et(i)};return o&&(a.second=et(o)),n&&(a.weekday=n.length>3?to.indexOf(n)+1:no.indexOf(n)+1),a}const jl=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Zl(n){const[,e,t,s,r,i,o,a,l,c,u,h]=n,f=Ys(e,r,s,t,i,o,a);let d;return l?d=Wl[l]:c?d=0:d=Bn(u,h),[f,new _e(d)]}function zl(n){return n.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const ql=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Bl=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Hl=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Wr(n){const[,e,t,s,r,i,o,a]=n;return[Ys(e,r,s,t,i,o,a),_e.utcInstance]}function Gl(n){const[,e,t,s,r,i,o,a]=n;return[Ys(e,a,t,s,r,i,o),_e.utcInstance]}const Yl=$t(Dl,Gs),Jl=$t(Il,Gs),Ql=$t(Al,Gs),Kl=$t(co),fo=Mt(Pl,Lt,ln,cn),Xl=Mt(Cl,Lt,ln,cn),ec=Mt(Fl,Lt,ln,cn),tc=Mt(Lt,ln,cn);function nc(n){return Pt(n,[Yl,fo],[Jl,Xl],[Ql,ec],[Kl,tc])}function sc(n){return Pt(zl(n),[jl,Zl])}function rc(n){return Pt(n,[ql,Wr],[Bl,Wr],[Hl,Gl])}function ic(n){return Pt(n,[Vl,Ul])}const oc=Mt(Lt);function ac(n){return Pt(n,[Ll,oc])}const lc=$t($l,Ml),cc=$t(uo),uc=Mt(Lt,ln,cn);function dc(n){return Pt(n,[lc,fo],[cc,uc])}const jr="Invalid Duration",ho={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},fc={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...ho},Re=146097/400,Et=146097/4800,hc={years:{quarters:4,months:12,weeks:Re/7,days:Re,hours:Re*24,minutes:Re*24*60,seconds:Re*24*60*60,milliseconds:Re*24*60*60*1e3},quarters:{months:3,weeks:Re/28,days:Re/4,hours:Re*24/4,minutes:Re*24*60/4,seconds:Re*24*60*60/4,milliseconds:Re*24*60*60*1e3/4},months:{weeks:Et/7,days:Et,hours:Et*24,minutes:Et*24*60,seconds:Et*24*60*60,milliseconds:Et*24*60*60*1e3},...ho},ft=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],mc=ft.slice(0).reverse();function Ze(n,e,t=!1){const s={values:t?e.values:{...n.values,...e.values||{}},loc:n.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||n.conversionAccuracy,matrix:e.matrix||n.matrix};return new te(s)}function mo(n,e){let t=e.milliseconds??0;for(const s of mc.slice(1))e[s]&&(t+=e[s]*n[s].milliseconds);return t}function Zr(n,e){const t=mo(n,e)<0?-1:1;ft.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*t,o=n[r][s],a=Math.floor(i/o);e[r]+=a*t,e[s]-=a*o*t}return r},null),ft.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*n[s][r]}return r},null)}function zr(n){const e={};for(const[t,s]of Object.entries(n))s!==0&&(e[t]=s);return e}class te{constructor(e){const t=e.conversionAccuracy==="longterm"||!1;let s=t?hc:fc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||re.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return te.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new ge(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new te({values:Pn(e,te.normalizeUnit),loc:re.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(rt(e))return te.fromMillis(e);if(te.isDuration(e))return e;if(typeof e=="object")return te.fromObject(e);throw new ge(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=ic(e);return s?te.fromObject(s,t):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=ac(e);return s?te.fromObject(s,t):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new ge("need to specify a reason the Duration is invalid");const s=e instanceof $e?e:new $e(e,t);if(ue.throwOnInvalid)throw new Ua(s);return new te({invalid:s})}static normalizeUnit(e){const t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new vi(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){const s={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?we.create(this.loc,s).formatDurationFromString(this,e):jr}toHuman(e={}){if(!this.isValid)return jr;const t=e.showZeros!==!1,s=ft.map(r=>{const i=this.values[r];return G(i)||i===0&&!t?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Bs(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},V.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?mo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e),s={};for(const r of ft)(Ft(t.values,r)||Ft(this.values,r))&&(s[r]=t.get(r)+this.get(r));return Ze(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;const t={};for(const s of Object.keys(this.values))t[s]=Ki(e(this.values[s],s));return Ze(this,{values:t},!0)}get(e){return this[te.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...Pn(e,te.normalizeUnit)};return Ze(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:r,conversionAccuracy:s};return Ze(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return Zr(this.matrix,e),Ze(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=zr(this.normalize().shiftToAll().toObject());return Ze(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>te.normalizeUnit(o));const t={},s={},r=this.toObject();let i;for(const o of ft)if(e.indexOf(o)>=0){i=o;let a=0;for(const c in s)a+=this.matrix[c][o]*s[c],s[c]=0;rt(r[o])&&(a+=r[o]);const l=Math.trunc(a);t[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else rt(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(t[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return Zr(this.matrix,t),Ze(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return Ze(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=zr(this.values);return Ze(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of ft)if(!t(this.values[s],e.values[s]))return!1;return!0}}const vt="Invalid Interval";function pc(n,e){return!n||!n.isValid?ce.invalid("missing or invalid start"):!e||!e.isValid?ce.invalid("missing or invalid end"):e<n?ce.invalid("end before start",`The end of an interval must be after its start, but you had start=${n.toISO()} and end=${e.toISO()}`):null}class ce{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new ge("need to specify a reason the Interval is invalid");const s=e instanceof $e?e:new $e(e,t);if(ue.throwOnInvalid)throw new Va(s);return new ce({invalid:s})}static fromDateTimes(e,t){const s=zt(e),r=zt(t),i=pc(s,r);return i??new ce({start:s,end:r})}static after(e,t){const s=te.fromDurationLike(t),r=zt(e);return ce.fromDateTimes(r,r.plus(s))}static before(e,t){const s=te.fromDurationLike(t),r=zt(e);return ce.fromDateTimes(r.minus(s),r)}static fromISO(e,t){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=V.fromISO(s,t),o=i.isValid}catch{o=!1}let a,l;try{a=V.fromISO(r,t),l=a.isValid}catch{l=!1}if(o&&l)return ce.fromDateTimes(i,a);if(o){const c=te.fromISO(r,t);if(c.isValid)return ce.after(i,c)}else if(l){const c=te.fromISO(s,t);if(c.isValid)return ce.before(a,c)}}return ce.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",t){if(!this.isValid)return NaN;const s=this.start.startOf(e,t);let r;return t?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,t),Math.floor(r.diff(s,e).get(e))+(r.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?ce.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];const t=e.map(zt).filter(o=>this.contains(o)).sort((o,a)=>o.toMillis()-a.toMillis()),s=[];let{s:r}=this,i=0;for(;r<this.e;){const o=t[i]||this.e,a=+o>+this.e?this.e:o;s.push(ce.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const t=te.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(t.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(ce.fromDateTimes(s,i)),s=i,r+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const t=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return t>=s?null:ce.fromDateTimes(t,s)}union(e){if(!this.isValid)return this;const t=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return ce.fromDateTimes(t,s)}static merge(e){const[t,s]=e.sort((r,i)=>r.s-i.s).reduce(([r,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[r,i.union(o)]:[r.concat([i]),o]:[r,o],[[],null]);return s&&t.push(s),t}static xor(e){let t=null,s=0;const r=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((l,c)=>l.time-c.time);for(const l of a)s+=l.type==="s"?1:-1,s===1?t=l.time:(t&&+t!=+l.time&&r.push(ce.fromDateTimes(t,l.time)),t=null);return ce.merge(r)}difference(...e){return ce.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:vt}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=Fn,t={}){return this.isValid?we.create(this.s.loc.clone(t),e).formatInterval(this):vt}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:vt}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:vt}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:vt}toFormat(e,{separator:t=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:vt}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):te.invalid(this.invalidReason)}mapEndpoints(e){return ce.fromDateTimes(e(this.s),e(this.e))}}class fn{static hasDST(e=ue.defaultZone){const t=V.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return He.isValidZone(e)}static normalizeZone(e){return tt(e,ue.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||re.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||re.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||re.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||re.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return re.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return re.create(t,null,"gregory").eras(e)}static features(){return{relative:Yi(),localeWeek:Ji()}}}function qr(n,e){const t=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(n);return Math.floor(te.fromMillis(s).as("days"))}function yc(n,e,t){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const u=qr(l,c);return(u-u%7)/7}],["days",qr]],r={},i=n;let o,a;for(const[l,c]of s)t.indexOf(l)>=0&&(o=l,r[l]=c(n,e),a=i.plus(r),a>e?(r[l]--,n=i.plus(r),n>e&&(a=n,r[l]--,n=i.plus(r))):n=a);return[n,r,a,o]}function gc(n,e,t,s){let[r,i,o,a]=yc(n,e,t);const l=e-r,c=t.filter(h=>["hours","minutes","seconds","milliseconds"].indexOf(h)>=0);c.length===0&&(o<e&&(o=r.plus({[a]:1})),o!==r&&(i[a]=(i[a]||0)+l/(o-r)));const u=te.fromObject(i,s);return c.length>0?te.fromMillis(l,s).shiftTo(...c).plus(u):u}const wc="missing Intl.DateTimeFormat.formatToParts support";function se(n,e=t=>t){return{regex:n,deser:([t])=>e(ll(t))}}const _c=" ",po=`[ ${_c}]`,yo=new RegExp(po,"g");function Ec(n){return n.replace(/\./g,"\\.?").replace(yo,po)}function Br(n){return n.replace(/\./g,"").replace(yo," ").toLowerCase()}function Fe(n,e){return n===null?null:{regex:RegExp(n.map(Ec).join("|")),deser:([t])=>n.findIndex(s=>Br(t)===Br(s))+e}}function Hr(n,e){return{regex:n,deser:([,t,s])=>Bn(t,s),groups:e}}function hn(n){return{regex:n,deser:([e])=>e}}function vc(n){return n.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Oc(n,e){const t=Ce(e),s=Ce(e,"{2}"),r=Ce(e,"{3}"),i=Ce(e,"{4}"),o=Ce(e,"{6}"),a=Ce(e,"{1,2}"),l=Ce(e,"{1,3}"),c=Ce(e,"{1,6}"),u=Ce(e,"{1,9}"),h=Ce(e,"{2,4}"),f=Ce(e,"{4,6}"),d=y=>({regex:RegExp(vc(y.val)),deser:([w])=>w,literal:!0}),O=(y=>{if(n.literal)return d(y);switch(y.val){case"G":return Fe(e.eras("short"),0);case"GG":return Fe(e.eras("long"),0);case"y":return se(c);case"yy":return se(h,$s);case"yyyy":return se(i);case"yyyyy":return se(f);case"yyyyyy":return se(o);case"M":return se(a);case"MM":return se(s);case"MMM":return Fe(e.months("short",!0),1);case"MMMM":return Fe(e.months("long",!0),1);case"L":return se(a);case"LL":return se(s);case"LLL":return Fe(e.months("short",!1),1);case"LLLL":return Fe(e.months("long",!1),1);case"d":return se(a);case"dd":return se(s);case"o":return se(l);case"ooo":return se(r);case"HH":return se(s);case"H":return se(a);case"hh":return se(s);case"h":return se(a);case"mm":return se(s);case"m":return se(a);case"q":return se(a);case"qq":return se(s);case"s":return se(a);case"ss":return se(s);case"S":return se(l);case"SSS":return se(r);case"u":return hn(u);case"uu":return hn(a);case"uuu":return se(t);case"a":return Fe(e.meridiems(),0);case"kkkk":return se(i);case"kk":return se(h,$s);case"W":return se(a);case"WW":return se(s);case"E":case"c":return se(t);case"EEE":return Fe(e.weekdays("short",!1),1);case"EEEE":return Fe(e.weekdays("long",!1),1);case"ccc":return Fe(e.weekdays("short",!0),1);case"cccc":return Fe(e.weekdays("long",!0),1);case"Z":case"ZZ":return Hr(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return Hr(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return hn(/[a-z_+-/]{1,256}?/i);case" ":return hn(/[^\S\n\r]/);default:return d(y)}})(n)||{invalidReason:wc};return O.token=n,O}const kc={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function bc(n,e,t){const{type:s,value:r}=n;if(s==="literal"){const l=/^\s+$/.test(r);return{literal:!l,val:l?" ":r}}const i=e[s];let o=s;s==="hour"&&(e.hour12!=null?o=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?o="hour12":o="hour24":o=t.hour12?"hour12":"hour24");let a=kc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Sc(n){return[`^${n.map(t=>t.regex).reduce((t,s)=>`${t}(${s.source})`,"")}$`,n]}function Tc(n,e,t){const s=n.match(e);if(s){const r={};let i=1;for(const o in t)if(Ft(t,o)){const a=t[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function Rc(n){const e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let t=null,s;return G(n.z)||(t=He.create(n.z)),G(n.Z)||(t||(t=new _e(n.Z)),s=n.Z),G(n.q)||(n.M=(n.q-1)*3+1),G(n.h)||(n.h<12&&n.a===1?n.h+=12:n.h===12&&n.a===0&&(n.h=0)),n.G===0&&n.y&&(n.y=-n.y),G(n.u)||(n.S=qs(n.u)),[Object.keys(n).reduce((i,o)=>{const a=e(o);return a&&(i[a]=n[o]),i},{}),t,s]}let as=null;function Nc(){return as||(as=V.fromMillis(1555555555555)),as}function xc(n,e){if(n.literal)return n;const t=we.macroTokenToFormatOpts(n.val),s=Eo(t,e);return s==null||s.includes(void 0)?n:s}function go(n,e){return Array.prototype.concat(...n.map(t=>xc(t,e)))}class wo{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=go(we.parseFormat(t),e),this.units=this.tokens.map(s=>Oc(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Sc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[t,s]=Tc(e,this.regex,this.handlers),[r,i,o]=s?Rc(s):[null,null,void 0];if(Ft(s,"a")&&Ft(s,"H"))throw new bt("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:s,result:r,zone:i,specificOffset:o}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function _o(n,e,t){return new wo(n,t).explainFromTokens(e)}function Dc(n,e,t){const{result:s,zone:r,specificOffset:i,invalidReason:o}=_o(n,e,t);return[s,r,i,o]}function Eo(n,e){if(!n)return null;const s=we.create(e,n).dtFormatter(Nc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>bc(o,n,i))}const ls="Invalid DateTime",Gr=864e13;function Gt(n){return new $e("unsupported zone",`the zone "${n.name}" is not supported`)}function cs(n){return n.weekData===null&&(n.weekData=$n(n.c)),n.weekData}function us(n){return n.localWeekData===null&&(n.localWeekData=$n(n.c,n.loc.getMinDaysInFirstWeek(),n.loc.getStartOfWeek())),n.localWeekData}function ct(n,e){const t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new V({...t,...e,old:t})}function vo(n,e,t){let s=n-e*60*1e3;const r=t.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=t.offset(s);return r===i?[s,r]:[n-Math.min(r,i)*60*1e3,Math.max(r,i)]}function mn(n,e){n+=e*60*1e3;const t=new Date(n);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function wn(n,e,t){return vo(qn(n),e,t)}function Yr(n,e){const t=n.o,s=n.c.year+Math.trunc(e.years),r=n.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...n.c,year:s,month:r,day:Math.min(n.c.day,Mn(s,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=te.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=qn(i);let[l,c]=vo(a,t,n.zone);return o!==0&&(l+=o,c=n.zone.offset(l)),{ts:l,o:c}}function Ot(n,e,t,s,r,i){const{setZone:o,zone:a}=t;if(n&&Object.keys(n).length!==0||e){const l=e||a,c=V.fromObject(n,{...t,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return V.invalid(new $e("unparsable",`the input "${r}" can't be parsed as ${s}`))}function pn(n,e,t=!0){return n.isValid?we.create(re.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(n,e):null}function ds(n,e,t){const s=n.c.year>9999||n.c.year<0;let r="";if(s&&n.c.year>=0&&(r+="+"),r+=he(n.c.year,s?6:4),t==="year")return r;if(e){if(r+="-",r+=he(n.c.month),t==="month")return r;r+="-"}else if(r+=he(n.c.month),t==="month")return r;return r+=he(n.c.day),r}function Jr(n,e,t,s,r,i,o){let a=!t||n.c.millisecond!==0||n.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=he(n.c.hour),o==="hour")break;if(e){if(l+=":",l+=he(n.c.minute),o==="minute")break;a&&(l+=":",l+=he(n.c.second))}else{if(l+=he(n.c.minute),o==="minute")break;a&&(l+=he(n.c.second))}if(o==="second")break;a&&(!s||n.c.millisecond!==0)&&(l+=".",l+=he(n.c.millisecond,3))}return r&&(n.isOffsetFixed&&n.offset===0&&!i?l+="Z":n.o<0?(l+="-",l+=he(Math.trunc(-n.o/60)),l+=":",l+=he(Math.trunc(-n.o%60))):(l+="+",l+=he(Math.trunc(n.o/60)),l+=":",l+=he(Math.trunc(n.o%60)))),i&&(l+="["+n.zone.ianaName+"]"),l}const Oo={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ic={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Ac={ordinal:1,hour:0,minute:0,second:0,millisecond:0},_n=["year","month","day","hour","minute","second","millisecond"],Cc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Fc=["year","ordinal","hour","minute","second","millisecond"];function En(n){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[n.toLowerCase()];if(!e)throw new vi(n);return e}function Qr(n){switch(n.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return En(n)}}function $c(n){if(Yt===void 0&&(Yt=ue.now()),n.type!=="iana")return n.offset(Yt);const e=n.name;let t=Ms.get(e);return t===void 0&&(t=n.offset(Yt),Ms.set(e,t)),t}function Kr(n,e){const t=tt(e.zone,ue.defaultZone);if(!t.isValid)return V.invalid(Gt(t));const s=re.fromObject(e);let r,i;if(G(n.year))r=ue.now();else{for(const l of _n)G(n[l])&&(n[l]=Oo[l]);const o=Hi(n)||Gi(n);if(o)return V.invalid(o);const a=$c(t);[r,i]=wn(n,a,t)}return new V({ts:r,zone:t,loc:s,o:i})}function Xr(n,e,t){const s=G(t.round)?!0:t.round,r=G(t.rounding)?"trunc":t.rounding,i=(a,l)=>(a=Bs(a,s||t.calendary?0:2,t.calendary?"round":r),e.loc.clone(t).relFormatter(t).format(a,l)),o=a=>t.calendary?e.hasSame(n,a)?0:e.startOf(a).diff(n.startOf(a),a).get(a):e.diff(n,a).get(a);if(t.unit)return i(o(t.unit),t.unit);for(const a of t.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(n>e?-0:0,t.units[t.units.length-1])}function ei(n){let e={},t;return n.length>0&&typeof n[n.length-1]=="object"?(e=n[n.length-1],t=Array.from(n).slice(0,n.length-1)):t=Array.from(n),[e,t]}let Yt;const Ms=new Map;class V{constructor(e){const t=e.zone||ue.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new $e("invalid input"):null)||(t.isValid?null:Gt(t));this.ts=G(e.ts)?ue.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[r,i]=[e.old.c,e.old.o];else{const a=rt(e.o)&&!e.old?e.o:t.offset(this.ts);r=mn(this.ts,a),s=Number.isNaN(r.year)?new $e("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=t,this.loc=e.loc||re.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new V({})}static local(){const[e,t]=ei(arguments),[s,r,i,o,a,l,c]=t;return Kr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,t]=ei(arguments),[s,r,i,o,a,l,c]=t;return e.zone=_e.utcInstance,Kr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){const s=hl(e)?e.valueOf():NaN;if(Number.isNaN(s))return V.invalid("invalid input");const r=tt(t.zone,ue.defaultZone);return r.isValid?new V({ts:s,zone:r,loc:re.fromObject(t)}):V.invalid(Gt(r))}static fromMillis(e,t={}){if(rt(e))return e<-Gr||e>Gr?V.invalid("Timestamp out of range"):new V({ts:e,zone:tt(t.zone,ue.defaultZone),loc:re.fromObject(t)});throw new ge(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(rt(e))return new V({ts:e*1e3,zone:tt(t.zone,ue.defaultZone),loc:re.fromObject(t)});throw new ge("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=tt(t.zone,ue.defaultZone);if(!s.isValid)return V.invalid(Gt(s));const r=re.fromObject(t),i=Pn(e,Qr),{minDaysInFirstWeek:o,startOfWeek:a}=Pr(i,r),l=ue.now(),c=G(t.specificOffset)?s.offset(l):t.specificOffset,u=!G(i.ordinal),h=!G(i.year),f=!G(i.month)||!G(i.day),d=h||f,m=i.weekYear||i.weekNumber;if((d||u)&&m)throw new bt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(f&&u)throw new bt("Can't mix ordinal dates with month/day");const O=m||i.weekday&&!d;let y,w,b=mn(l,c);O?(y=Cc,w=Ic,b=$n(b,o,a)):u?(y=Fc,w=Ac,b=os(b)):(y=_n,w=Oo);let N=!1;for(const g of y){const k=i[g];G(k)?N?i[g]=w[g]:i[g]=b[g]:N=!0}const p=O?ul(i,o,a):u?dl(i):Hi(i),T=p||Gi(i);if(T)return V.invalid(T);const C=O?$r(i,o,a):u?Mr(i):i,[v,Z]=wn(C,c,s),x=new V({ts:v,zone:s,o:Z,loc:r});return i.weekday&&d&&e.weekday!==x.weekday?V.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${x.toISO()}`):x.isValid?x:V.invalid(x.invalid)}static fromISO(e,t={}){const[s,r]=nc(e);return Ot(s,r,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,r]=sc(e);return Ot(s,r,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,r]=rc(e);return Ot(s,r,t,"HTTP",t)}static fromFormat(e,t,s={}){if(G(e)||G(t))throw new ge("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,u]=Dc(o,e,t);return u?V.invalid(u):Ot(a,l,s,`format ${t}`,e,c)}static fromString(e,t,s={}){return V.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,r]=dc(e);return Ot(s,r,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new ge("need to specify a reason the DateTime is invalid");const s=e instanceof $e?e:new $e(e,t);if(ue.throwOnInvalid)throw new La(s);return new V({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=Eo(e,re.fromObject(t));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,t={}){return go(we.parseFormat(e),re.fromObject(t)).map(r=>r.val).join("")}static resetCache(){Yt=void 0,Ms.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?cs(this).weekYear:NaN}get weekNumber(){return this.isValid?cs(this).weekNumber:NaN}get weekday(){return this.isValid?cs(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?us(this).weekday:NaN}get localWeekNumber(){return this.isValid?us(this).weekNumber:NaN}get localWeekYear(){return this.isValid?us(this).weekYear:NaN}get ordinal(){return this.isValid?os(this.c).ordinal:NaN}get monthShort(){return this.isValid?fn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?fn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?fn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?fn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,t=6e4,s=qn(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*t),a=this.zone.offset(s-i*t);if(o===a)return[this];const l=s-o*t,c=s-a*t,u=mn(l,o),h=mn(c,a);return u.hour===h.hour&&u.minute===h.minute&&u.second===h.second&&u.millisecond===h.millisecond?[ct(this,{ts:l}),ct(this,{ts:c})]:[this]}get isInLeapYear(){return an(this.year)}get daysInMonth(){return Mn(this.year,this.month)}get daysInYear(){return this.isValid?Rt(this.year):NaN}get weeksInWeekYear(){return this.isValid?nn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?nn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:t,numberingSystem:s,calendar:r}=we.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(_e.instance(e),t)}toLocal(){return this.setZone(ue.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=tt(e,ue.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(t||s){const i=e.offset(this.ts),o=this.toObject();[r]=wn(o,i,e)}return ct(this,{ts:r,zone:e})}else return V.invalid(Gt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return ct(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=Pn(e,Qr),{minDaysInFirstWeek:s,startOfWeek:r}=Pr(t,this.loc),i=!G(t.weekYear)||!G(t.weekNumber)||!G(t.weekday),o=!G(t.ordinal),a=!G(t.year),l=!G(t.month)||!G(t.day),c=a||l,u=t.weekYear||t.weekNumber;if((c||o)&&u)throw new bt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new bt("Can't mix ordinal dates with month/day");let h;i?h=$r({...$n(this.c,s,r),...t},s,r):G(t.ordinal)?(h={...this.toObject(),...t},G(t.day)&&(h.day=Math.min(Mn(h.year,h.month),h.day))):h=Mr({...os(this.c),...t});const[f,d]=wn(h,this.o,this.zone);return ct(this,{ts:f,o:d})}plus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e);return ct(this,Yr(this,t))}minus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e).negate();return ct(this,Yr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},r=te.normalizeUnit(e);switch(r){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(r==="weeks")if(t){const i=this.loc.getStartOfWeek(),{weekday:o}=this;o<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(r==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?we.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):ls}toLocaleString(e=Fn,t={}){return this.isValid?we.create(this.loc.clone(t),e).formatDateTime(this):ls}toLocaleParts(e={}){return this.isValid?we.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=En(o);const a=e==="extended";let l=ds(this,a,o);return _n.indexOf(o)>=3&&(l+="T"),l+=Jr(this,a,t,s,r,i,o),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?ds(this,e==="extended",En(t)):null}toISOWeekDate(){return pn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=En(a),(r&&_n.indexOf(a)>=3?"T":"")+Jr(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return pn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return pn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?ds(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(t||e)&&(s&&(r+=" "),t?r+="z":e&&(r+="ZZ")),pn(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():ls}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",s={}){if(!this.isValid||!e.isValid)return te.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=ml(t).map(te.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=gc(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",t={}){return this.diff(V.now(),e,t)}until(e){return this.isValid?ce.fromDateTimes(this,e):this}hasSame(e,t,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,s)<=r&&r<=i.endOf(t,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const t=e.base||V.fromObject({},{zone:this.zone}),s=e.padding?this<t?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),Xr(t,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?Xr(e.base||V.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(V.isDateTime))throw new ge("min requires all arguments be DateTimes");return Lr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(V.isDateTime))throw new ge("max requires all arguments be DateTimes");return Lr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return _o(o,e,t)}static fromStringExplain(e,t,s={}){return V.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:r=null}=t,i=re.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new wo(i,e)}static fromFormatParser(e,t,s={}){if(G(e)||G(t))throw new ge("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new ge(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:u}=t.explainFromTokens(e);return u?V.invalid(u):Ot(a,l,s,`format ${t.format}`,e,c)}static get DATE_SHORT(){return Fn}static get DATE_MED(){return Oi}static get DATE_MED_WITH_WEEKDAY(){return Wa}static get DATE_FULL(){return ki}static get DATE_HUGE(){return bi}static get TIME_SIMPLE(){return Si}static get TIME_WITH_SECONDS(){return Ti}static get TIME_WITH_SHORT_OFFSET(){return Ri}static get TIME_WITH_LONG_OFFSET(){return Ni}static get TIME_24_SIMPLE(){return xi}static get TIME_24_WITH_SECONDS(){return Di}static get TIME_24_WITH_SHORT_OFFSET(){return Ii}static get TIME_24_WITH_LONG_OFFSET(){return Ai}static get DATETIME_SHORT(){return Ci}static get DATETIME_SHORT_WITH_SECONDS(){return Fi}static get DATETIME_MED(){return $i}static get DATETIME_MED_WITH_SECONDS(){return Mi}static get DATETIME_MED_WITH_WEEKDAY(){return ja}static get DATETIME_FULL(){return Pi}static get DATETIME_FULL_WITH_SECONDS(){return Li}static get DATETIME_HUGE(){return Vi}static get DATETIME_HUGE_WITH_SECONDS(){return Ui}}function zt(n){if(V.isDateTime(n))return n;if(n&&n.valueOf&&rt(n.valueOf()))return V.fromJSDate(n);if(n&&typeof n=="object")return V.fromObject(n);throw new ge(`Unknown datetime argument: ${n}, of type ${typeof n}`)}const Mc=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return rn(ye());n.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?t[r]=ko(i)?.nullable():t[r]=ye()})}return Ue({Collection_Path:wt(ke()),...t})},Pc=(n,e,t,s)=>{let r=Ue({}).catchall(Mc(n,e)),i;if(!s&&t){const o=Ie(n,t);i=qt(o.admin?.skipFormRequiredValidation)}return(!n.required||i)&&(r=r.optional()),r},Lc=()=>ye().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Must be a valid date"}),ko=(n,e,t)=>{let s;const r=`${qt(n.description)}
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Be=require("lodash/isEqual.js"),jo=require("lodash/merge.js"),Zo=require("lodash/set.js"),pe=require("lodash/cloneDeep.js"),Rt=require("firebase-admin/app"),H=require("firebase-admin/firestore"),zo=require("node:child_process"),ci=require("firebase-admin/database"),yt=require("firebase-admin/auth"),Wn=n=>!!n.auth,Se=(n,e)=>{if(e?.operations)return e.operations.includes(n)},jn=(n,e)=>e?e.Role?n.access?.includes(e.Role):!1:!0,qo=(n,e)=>n.restrictCreate===!0?!1:e&&typeof n.restrictCreate=="object"?e.Role?n.restrictCreate?.includes(e.Role):!1:!0,ui=(n,e)=>n.restrictUpdate===!0?!1:e&&typeof n.restrictUpdate=="object"?e.Role?n.restrictUpdate?.includes(e.Role):!1:!0,fr=(n,e,t)=>{const{labels:s}=n;return t.collections&&Se("Update",t.collections[s.collection])&&(!e.access||jn(e,t))&&ui(e,t)&&!(n.auth&&!t.collections?.[s.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},W=(n,e)=>n.filter(t=>t.name===e)[0],X=n=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(n.type),di=(n,e)=>{const t={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=n,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const u=a?.[t[l.type]];c.role===e.Role&&(!c.assignable||u?.active)&&s.push(l)})}),s},Ls=(n,e)=>{const t=[],{labels:s,access:r}=n,{entityRestrictions:i}=r,o=e.collections?.[s.collection];return i?.restrictions?.forEach(a=>{"roles"in a&&a.roles.forEach(l=>{l.role===e.Role&&(!i.assignable?.includes(e.Role)||o?.restrictEntities)&&t.push(a)})}),t},fi=(n,e,t)=>{const s=[],{access:r}=n,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(d=>d.role===t.Role))return;const a=o.collectionField,l=W(n.fields,a);if(!X(l))throw new Error("PERMISSION_DENIED");const c=t.collections?.[l.collection],h=e.collections[l.collection].access.entityRestrictions;if(!h)throw new Error("PERMISSION_DENIED");const f=h.restrictions?.find(d=>d.type===o.type&&d.roles.some(m=>m.role===t.Role));if(!f)throw new Error("PERMISSION_DENIED");f.roles.forEach(d=>{d.role===t.Role&&(!h.assignable?.includes(t.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:f})})}),s},hi=(n,e,t)=>{const s=Object.values(e.collections),{labels:r}=n,i=[];for(const o of s){const{fields:a}=o;for(const l of a)if(!(l.access&&!jn(l,t))&&t.Role&&X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)!i.find(h=>h.field===c.field)&&c.roles.includes(t.Role)&&i.push(c)}return i},Bo=(n,e,t,s,r,i)=>{const{fields:o}=e,a=r.collections?.[e.labels.collection];let l=!0;if(!a){l=!1;return}const c=di(e,r),u=Ls(e,r),h=fi(e,t,r);c?.filter(p=>p.type==="Record_Owner").forEach(p=>{"operations"in p&&p.operations&&!p.operations.includes(n)||i.Created_By!==s&&(l=!1)}),c?.filter(p=>p.type==="Record_User").forEach(p=>{if("operations"in p&&p.operations&&!p.operations.includes(n))return;const T=W(o,p.collectionField);i[`${T.name}_Array`]?.includes(r.Doc_ID)||(l=!1)}),c?.filter(p=>p.type==="Record_Property").forEach(p=>{if("operations"in p&&p.operations&&!p.operations.includes(n))return;const T=W(o,p.propertyField),C=p.roles.find(v=>v.role===r.Role);T.type==="Array"?C.values?.some(v=>i[T.name].includes(v))||(l=!1):C.values?.includes(i[T.name])||(l=!1)});let f=!0,d=!1;u?.filter(p=>p.type==="Individual").forEach(()=>{d=!0,a.individualEntities?.includes(i.id)||(f=!1)});let m=!0,O=!1;if(u?.filter(p=>p.type==="Parent").forEach(p=>{O=!0;const T=W(o,p.collectionField);a.parentEntities?.some(C=>i[`${T.name}_Array`].includes(C))||(m=!1)}),u?.filter(p=>p.type==="Parent_Property").forEach(p=>{O=!0;const T=W(o,p.collectionField),C=W(o,p.propertyField);Object.entries(a.parentPropertyEntities||{}).some(v=>{const[Z,x]=v;return Z===i[C.name]&&i[`${T.name}_Array`].some(g=>x.includes(g))})||(m=!1)}),d&&O){if(!(f||m)){l=!1;return}}else if(!f||!m){l=!1;return}let y=!0,w=!1;h?.filter(p=>p.parentFilter.type==="Individual").forEach(p=>{w=!0;const{parentFilter:T}=p,C=W(o,T.collectionField),v=r.collections?.[C.collection];if(!v){l=!1;return}v.individualEntities?.some(Z=>i[`${C.name}_Array`].includes(Z))||(y=!1)});let b=!0,N=!1;if(h?.filter(p=>p.parentFilter.type==="Parent").forEach(p=>{N=!0;const{parentFilter:T}=p,C=W(o,T.collectionField),v=W(o,T.parentCollectionField),Z=r.collections?.[C.collection];if(!Z){l=!1;return}Z.parentEntities?.some(x=>i[`${v.name}_Array`].includes(x))||(b=!1)}),h?.filter(p=>p.parentFilter.type==="Parent_Property").forEach(p=>{N=!0;const{parentFilter:T}=p,C=W(o,T.collectionField),v=W(o,T.parentPropertyField),Z=W(o,T.parentCollectionField),x=r.collections?.[C.collection];if(!x){l=!1;return}Object.entries(x.parentPropertyEntities||{}).some(g=>{const[k,_]=g;return k===i[v.name]&&i[`${Z.name}_Array`].some(A=>_.includes(A))})||(b=!1)}),w&&N){if(!(y||b)){l=!1;return}}else if(!y||!b){l=!1;return}return l},it=(n,e,t,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;Se(n,a)||(l=!1);const u=Ls(e,r)?.filter(h=>h.type==="Individual").length>0;return n==="Create"&&u&&(l=!1),Bo(n,e,t,s,r,i)||(l=!1),l},mi=(n,e,t)=>{const{labels:s}=n,r=[];for(const i of Object.values(e.collections));return r},Ho=(n,e)=>{let t=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){t=!1,s="Permissions object must contain Doc_ID, Role, Collection, Enabled, and collections";return}}),e.collections&&(Object.keys(e.collections).forEach(r=>{if(!Object.keys(n.collections).includes(r)){s=`Collection ${r} not found in schema`,t=!1;return}const i=n.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,t=!1;return}if(!Object.keys(o).every(a=>["operations","auth","restrictEntities","individualEntities","parentEntities","parentPropertyEntities","recordProperty","recordUser","recordOwner"].includes(a))){s=`Collection ${r} has invalid properties`,t=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,t=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,t=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,t=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const u=i.access.attributeRestrictions?.filter(f=>f.type===c&&f.roles.some(d=>d.role===e.Role)),h=i.access.entityRestrictions?.restrictions?.filter(f=>f.type===c&&f.roles.some(d=>d.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(f=>n.config.roles.includes(f)))){s=`Collection ${r} has invalid entity restrictions assignable value`,t=!1;return}if(u?.length||h?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const f=Object.keys(l);if(f.length!==1||f[0]!=="active"||typeof l.active!="boolean"){s=`Collection ${r} has invalid attribute restriction value`,t=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,t=!1;return}if(a==="Parent"){const f=Object.keys(l);if(!(f.length===1&&Object.keys(n.collections).includes(f[0])&&Array.isArray(l[f[0]]))){s=`Collection ${r} has invalid parent entities value`,t=!1;return}}if(a==="Parent_Property"){const f=Object.keys(l);if(!(f.length===1&&Object.keys(n.collections).includes(f[0])&&typeof l[f[0]]=="object"&&l[f[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,t=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,t=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),t},Go=(n,e,t)=>{let s=!0,r="";Object.values(n.collections).filter(i=>i.auth).forEach(i=>{if(e.collections?.[i.labels.collection]?.auth&&!i.access.auth?.includes(e.Role)){r="Record cannot have auth access to collection",s=!1;return}});for(const i of Object.values(n.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:u,entityRestrictions:h}=a,f=c.assignable,d=e.collections?.[o.collection],m=["read","create","update","delete"];if(f!==!0&&!(typeof f=="object"&&f.includes(t))?m.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const b=!!a.operations[y]?.includes(t),N=!!d?.operations.includes(w);if(!b&&N){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}if(b&&!N){r=`Collection ${o.collection} has missing ${y} operation for role ${t}`,s=!1;return}}}):m.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const b=!!a.operations[y]?.includes(t),N=!!d?.operations.includes(w);if(!b&&N){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}}}),!u&&!h||(u?.forEach(y=>{for(const w of y.roles)if(w.role===t&&!w.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${t}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${t}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${t}`,s=!1;return}}}),h?.assignable?.includes(t)))continue;let O=!1;if(h?.restrictions?.forEach(y=>{for(const w of y.roles)if(w.role===t){if(O=!0,y.type==="Individual"&&!e.collections?.[o.collection]?.individualEntities){r=`Collection ${o.collection} is missing individual entities`,s=!1;return}if(y.type==="Parent"){const b=W(l,y.collectionField);if(!X(b)){s=!1;return}if(!e.collections?.[o.collection]?.parentEntities){r=`Collection ${o.collection} is missing parent entities`,s=!1;return}}if(y.type==="Parent_Property"){const b=W(l,y.collectionField);if(!X(b)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[b.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),O&&!e.collections?.[o.collection]?.restrictEntities){r=`Collection ${o.collection} must have restrictEntities set to true`,s=!1;return}}return r&&console.error(`PERMISSION_DENIED: ${r}`),s},Yo=(n,e,t,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:u}=c;let h=!0,f="";const d=u?.filter(m=>s===m.userRole);return d?.length&&!d.some(m=>m.recordRole===r)?(f=`User ${s} does not have write access to record with role ${r}`,h=!1,h):n==="update"&&o.User_ID&&d?.length&&!d.some(m=>m.recordRole===a)?(f=`User ${s} does not have write access to record with role ${r}`,h=!1,h):(u?.forEach(m=>{s===m.userRole&&m.recordRole===r&&n!=="delete"&&i&&Object.keys(t.collections).forEach(O=>{const y=i.collections?.[O],w=l?.collections?.[O];if(!(n==="update"&&Be(y,w))&&y){const b=m.collections.some(N=>N.collection===O);if(b){if(b){const N=m.collections.find(T=>T.collection===O);if(!(y.operations.every(T=>N.operations.includes(T))||n==="update"&&Be(y.operations,w?.operations))){f=`User ${s} does not have write access to all included operations for collection ${O}`,h=!1;return}if(!N.auth&&y.auth&&!(n==="update"&&Be(y.auth,w?.auth))){f=`User ${s} does not have write access to auth for collection ${O}`,h=!1;return}const p={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(p).forEach(T=>{const C=p[T];if(N.attributeRestrictions?.includes(C)&&!(y[T]?.active||n==="update"&&Be(y[T],w?.[T]))){f=`User ${s} does not have write access to attribute restriction ${T} for collection ${O}`,h=!1;return}}),N.restrictEntities&&!y.restrictEntities&&!(n==="update"&&Be(y.restrictEntities,w?.restrictEntities))){f=`User ${s} does not have write access to restrictEntities for collection ${O}`,h=!1;return}}}else{f=`User ${s} does not have write access to collection ${O}`,h=!1;return}}})}),f&&console.error(`PERMISSION_DENIED: ${f}`),h)},Jo=(n,e,t,s)=>{let r=!0,i="";return Object.values(n.collections).forEach(o=>{const a=t.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!Wn(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const u of a?.operations||[])if(!l?.operations.includes(u)&&(!Se("Read",c)||!Se(u,c))){i=`User does not have ${u.toLowerCase()} access to collection ${o.labels.collection}`,r=!1;return}if(!a?.recordOwner&&l?.recordOwner&&c?.recordOwner){i=`User does not have write access to recordOwner for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordUser&&l?.recordUser&&c?.recordUser){i=`User does not have write access to recordUser for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordProperty&&l?.recordProperty&&c?.recordProperty){i=`User does not have write access to recordProperty for collection ${o.labels.collection}`,r=!1;return}if(!a?.restrictEntities&&l?.restrictEntities&&c?.restrictEntities){i=`User does not have write access to restrictEntities for collection ${o.labels.collection}`,r=!1;return}}),i&&console.error(`PERMISSION_DENIED: ${i}`),r},Vs=(n,e,t,s,r,i,o,a,l,c,u)=>{const{labels:h}=s;let f=!0,d="";if(!e.Role)return d="Record does not have a role",f=!1,f;if(n==="update"&&!c)return d="Original record is required for update operations",f=!1,f;if(n==="update"&&i&&u==="update"&&a&&!l)return d="Original permissions are required for this operation",f=!1,f;if(i){if(!o?.Role)return d="Current user does not have a role",f=!1,f;if(!Yo(n,s,r,o.Role,e.Role,a,c,c?.Role,l))return f=!1,f;if(n==="update"&&u!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return d="User ID does not match original user ID",f=!1,f;if(n==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return d="User cannot update their own record",f=!1,f;if(n==="delete"&&i===e.User_ID)return d="User cannot delete their own record",f=!1,f}return n==="delete"||u==="delete"||!a?f:a.Role?(Ho(r,a)||(f=!1),a.Collection&&a.Collection!==h.collection?(d="Permissions collection does not match record collection",f=!1,f):a.Role!==e.Role?(d="Permissions role does not match record role",f=!1,f):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(d="Permissions enabled state does not match record enabled state",f=!1,f):a.Doc_ID&&a.Doc_ID!==t?(d="Permissions doc ID does not match record doc ID",f=!1,f):!Go(r,a,a.Role)||i&&o&&l&&!Jo(r,o,a,l)?(f=!1,f):(d&&console.error(`PERMISSION_DENIED: ${d}`),f)):(d="Permissions do not have a role",f=!1,f)},hr=(n,e,t,s,r,i,o)=>{const{labels:a,fields:l}=t,c=i?.collections?.[a.collection];let u=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!Se("Create",c)&&(u=!1),r&&!it("Create",t,s,r,i,n)&&(u=!1),t.auth&&o&&(r&&!Wn(c)&&(u=!1),Vs("create",n,e,t,s,r,i,o)||(u=!1));for(const h of l){const f=n[h.name];h.access&&!jn(h,i)&&f!==void 0&&(u=!1),f!==void 0&&!qo(h,i)&&(u=!1)}if(!u)throw new Error("PERMISSION_DENIED")},Ne=n=>n&&(n._methodName==="deleteField"||n.constructor.name==="DeleteTransform"),nt=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(Ne(n[e])?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&nt(n[e]))},mr=(n,e,t,s,r,i,o,a,l,c)=>{const{labels:u,fields:h}=s,f=o?.collections?.[u.collection],d={...e,...n};nt(d);let m=!0,O="";if(i&&!f)throw new Error("PERMISSION_DENIED");i&&!Se("Update",f)&&(m=!1,O="Authenticated user does not have Update access to this collection"),i&&(!it("Update",s,r,i,o,e)||!it("Update",s,r,i,o,d))&&(m=!1,O="Authenticated user does not have Update access to this document"),a&&(i&&!Wn(f)&&(m=!1,O="Authenticated user does not have Auth access for this collection"),Vs("update",d,t,s,r,i,o,l,c,e,a)||(O="Authenticated user does not have sufficient write access for this record",m=!1));for(const y of h){const w=n[y.name];y.access&&!jn(y,o)&&w!==void 0&&(O=`Authenticated user does not have access to field ${y.name}`,m=!1),w!==void 0&&!ui(y,o)&&(O=`Authenticated user does not have Update access to field ${y.name}`,m=!1)}if(!m)throw O&&console.error(`PERMISSION_DENIED: ${O}`),new Error("PERMISSION_DENIED")},Qo=(n,e,t,s,r,i)=>{const{labels:o}=t,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(Se("Delete",a)||(l=!1),it("Delete",t,s,r,i,n)||(l=!1),t.auth&&n.User_ID&&(Wn(a)||(l=!1),Vs("delete",n,e,t,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},Ko=async(n,e,t,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Se("Read",o)||(a=!1),it("Read",e,t,s,r,n)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},Xo=async(n,e,t,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Se("Read",o)||(a=!1),n.forEach(l=>{it("Read",e,t,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},ea=(n,e,t)=>{const{access:s}=n;return s.operations.assignable===!0||typeof s.operations.assignable=="object"&&s.operations.assignable.includes(e)||s.operations[t]?.includes(e)},ta=(n,e,t)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===n)&&!("singleQuery"in i&&i.singleQuery))return`${i.type} entity restriction`}if(r?.parentFilters)for(const i of r.parentFilters){if(!i.roles.some(c=>c.role===n))continue;const o=W(e.fields,i.collectionField);if(!X(o))throw new Error("PERMISSION_DENIED");const l=t.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(u=>u.role===n));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},na=(n,e,t,s,r)=>{const i={};for(const o of n){const l=e[o].default(t,s,r);for(const c in l)c==="custom"||c==="admin"||c==="fields"||delete l[c];for(const c of l.fields)for(const u in c)u==="custom"||u==="admin"||u==="name"||u==="formula"||delete c[u];i[o]=l}return i},Ie=(n,e)=>e.fields.filter(t=>t.name===n.name)[0],Xn={global:{},collections:{}},qt=(n,e)=>n&&typeof n=="function"?e?n(...e):n():n,ie=async(n,e)=>{let t=n;return n&&(typeof n=="function"||typeof n.then=="function")&&(e?t=await n(...e):t=await n()),t},sa=async(n,e,t,s)=>{for(const u of e)if(u==="__proto__"||u==="constructor"||u==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=Xn,i=!0;for(const u of e){if(u===void 0||r[u]===void 0){i=!1;break}r=r[u]}if(r&&i&&!s)return r;let o,a=n,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const u of o){if(u===void 0||a[u]===void 0){l=!1;break}a=a[u]}let c;if(l&&(c=await ie(a,t)),c){let u=Xn;const h={};for(let f=0;f<e.length;f++){const d=e[f];if(d!==void 0){if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");f===e.length-1?Zo(h,e.join("."),c):(u[d]||={},u=u[d])}}jo(Xn,h)}return c},at=(n,e,t)=>{const s=Object.values(t.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field==n.name&&(i=!0)}return i},pi=(n,e)=>{const t=Object.values(e.collections),{labels:s}=n,r={};return t.forEach(i=>{const{labels:o,fields:a}=i;a.forEach(l=>{X(l)&&l.collection===s.collection&&l.dependencyFields&&l.dependencyFields.forEach(c=>{r[c.field]||={},r[c.field][o.collection]||=[],r[c.field][o.collection]=r[c.field][o.collection].concat(c.roles),r[c.field][o.collection]=[...new Set(r[c.field][o.collection])]})})}),r},es=n=>JSON.stringify(n.map(e=>e.name)),ht=["id","Collection_Path","Last_Write_At","Last_Save_At","Last_Write_By","Last_Write_App","Last_Write_Connection_Status","Last_Write_Version","Created_At","Saved_At","Created_By"],Zn=()=>ht.map(n=>{let e="",t;switch(n){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",t=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:n,type:e,required:!0};return t&&(s.values=t),s}),yi=(n,e)=>{const t=[],{access:s,fields:r}=n,{attributeRestrictions:i,entityRestrictions:o}=s,a=Zn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":t.push(W(a,"Created_By"));break;case"Record_User":t.push(W(r,l.collectionField));break;case"Record_Property":t.push(W(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(W(a,"id"));break;case"Parent":t.push(W(r,l.collectionField));break;case"Parent_Property":t.push(W(r,l.collectionField)),t.push(W(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(W(r,l.collectionField));break;case"Parent":t.push(W(r,l.parentCollectionField));break;case"Parent_Property":t.push(W(r,l.parentCollectionField)),t.push(W(r,l.parentPropertyField));break}})),[...new Set(t)]},ra=(n,e)=>{const t=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=n,a=Zn();return t.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{(!c.access||c.access.includes(e))&&t.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{t.push(W(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{ht.includes(c)&&t.push(W(a,c))}),o?.forEach(c=>{const u=W(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&u&&(!u.access||u.access?.includes(e))&&ht.includes(c.field)&&t.push(W(a,c.field))}),yi(n,e).forEach(c=>{ht.includes(c.name)&&t.push(W(a,c.name))}),[...new Set(t)]},ia=(n,e,t)=>{const s=[],{fields:r,preloadCache:i}=e,o=Zn();i?.range&&i.range.fields.forEach(c=>{ht.includes(c)?s.push(W(o,c)):s.push(W(r,c))});const a=new Set,l=pi(e,t);return Object.entries(l).map(([c,u])=>{n.name===c&&Object.values(u).forEach(h=>{h.forEach(f=>{a.add(f)})})}),a.forEach(c=>{s.push(...yi(e,c))}),[...new Set(s)]},un=(n,e,t)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=pi(e,t);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{t.collections[c].fields.forEach(h=>{X(h)&&h.collection===e.labels.collection&&h.dependencyFields?.some(f=>f.field===n.name)&&h.constraints&&h.constraints.forEach(f=>{o.push(f[0])})})})}),o.forEach(l=>{s.push(W(r,l))}),i){const l=W(r,i.archivedField);l&&s.push(l)}return s.push(...ia(n,e,t)),[...new Set(s)]},gi=(n,e)=>{const{preloadCache:t}=n,s=new Set;for(const r of e.config.roles){if(!ea(n,r,"read"))continue;const i=ra(n,r);let o=!1;if(s.size===0)s.add({key:"1",roles:[r],fields:i}),o=!0;else for(const a of s)i.length===a.fields.length&&i.every(l=>a.fields.some(c=>c.name===l.name))&&!!t?.roles.includes(r)==!!a.roles.every(l=>t?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},wi=(n,e,t)=>{const s=gi(e,t);for(const r of s.values())if(r.roles.includes(n))return r},oa=(n,e)=>{const{fields:t}=e,s=Zn(),r=[];return[...t,...s.filter(o=>o.name!=="id")].forEach(o=>{n?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Us=(n,e,t)=>{const s={};return Object.values(n.collections).forEach(r=>{const i=gi(r,n),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},bn=n=>({Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_Version:n.Last_Write_Version,Last_Write_App:n.Last_Write_App,Last_Save_At:n.Last_Save_At}),ts=async(n,e,t)=>{if(e){const s=await ie(e,t);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${n}`);return s}};async function le(n,e,t,s){const r=await ts(n,t.custom?.[n],s);for(const i of t.fields)await ts(n,i.custom?.[n],s);if(n!=="setEmbedding"&&(await ts(n,e?.[n],s),n==="postWriteError"))return r}const Ws=(n,e,t,s,r,i,o,a,l,c)=>(n=="create"&&(t.Collection_Path=e,t.Created_At=a,t.Saved_At=l,t.Created_By=o||"System"),t.Last_Write_App=r,t.Last_Write_At=a,t.Last_Save_At=l,t.Last_Write_By=o||"System",t.Last_Write_Connection_Status=i,t.Last_Write_Version=s.version,t),ut=(n,e)=>{const{access:t,queries:s}=n,{serverReadOnly:r}=t,i=new Set;if(s)for(const o of s){const a=W(e,o.field);e.find(l=>l.name===o.field)&&X(a)&&["OneToOne","OneToMany"].includes(a.type)&&i.add(a)}return e.forEach(o=>{X(o)&&["OneToOne","OneToMany"].includes(o.type)&&o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a)))&&i.add(o)}),i},gt=(n,e)=>{const{access:t,recordTitleField:s}=n,{serverReadOnly:r}=t,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},Sn=(n,e,t)=>{const{fields:s}=n;s.forEach(i=>{if(X(i))if(e[i.name]){if(Ne(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=t.collections[i.collection],l=W(a.fields,o);gt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(u=>{e[i.name][u][o]?e[i.name][u][`${o}_Lowercase`]=e[i.name][u][o].toLowerCase():delete e[i.name][u][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),ut(n,s).forEach(i=>{if(e[i.name])if(Ne(e[i.name]))e[`${i.name}_Single`]=e[i.name];else{const o=e[`${i.name}_Array`]?.[0];if(o){const a=e[i.name][o]||{};e[`${i.name}_Single`]={...a}}}})},Tn=(n,e)=>{gt(n,n.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},aa=async(n,e,t,s)=>{const{fields:r}=e;for(const i of t.fields){const o=W(r,i.name);i.custom?.initialValue&&!(s&&o.access&&!o.access.includes(s))&&(n[i.name]=await ie(i.custom.initialValue,[n]),gt(e,[o]).size===1&&(n[`${i.name}_Lowercase`]=n[i.name].toLowerCase()))}for(const i of r)s&&i.access&&!i.access.includes(s)||("autoIncrement"in i&&i.autoIncrement&&!n[i.name]&&(n[i.name]="Pending"),!X(i)&&i.nullable&&n[i.name]===void 0&&(n[i.name]=null))};var ne;(function(n){n.assertEqual=r=>{};function e(r){}n.assertIs=e;function t(r){throw new Error}n.assertNever=t,n.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},n.getValidEnumValues=r=>{const i=n.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return n.objectValues(o)},n.objectValues=r=>n.objectKeys(r).map(function(i){return r[i]}),n.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},n.find=(r,i)=>{for(const o of r)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=s,n.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(ne||(ne={}));var pr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(pr||(pr={}));const U=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xe=n=>{switch(typeof n){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN(n)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":return Array.isArray(n)?U.array:n===null?U.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?U.promise:typeof Map<"u"&&n instanceof Map?U.map:typeof Set<"u"&&n instanceof Set?U.set:typeof Date<"u"&&n instanceof Date?U.date:U.object;default:return U.unknown}},D=ne.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Ge extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(t(o));else{let a=s,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof Ge))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}Ge.create=n=>new Ge(n);const ws=(n,e)=>{let t;switch(n.code){case D.invalid_type:n.received===U.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case D.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,ne.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:t=`Unrecognized key(s) in object: ${ne.joinValues(n.keys,", ")}`;break;case D.invalid_union:t="Invalid input";break;case D.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${ne.joinValues(n.options)}`;break;case D.invalid_enum_value:t=`Invalid enum value. Expected ${ne.joinValues(n.options)}, received '${n.received}'`;break;case D.invalid_arguments:t="Invalid function arguments";break;case D.invalid_return_type:t="Invalid function return type";break;case D.invalid_date:t="Invalid date";break;case D.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:ne.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case D.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case D.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case D.custom:t="Invalid input";break;case D.invalid_intersection_types:t="Intersection results could not be merged";break;case D.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case D.not_finite:t="Number must be finite";break;default:t=e.defaultError,ne.assertNever(n)}return{message:t}};let la=ws;function ca(){return la}const ua=n=>{const{data:e,path:t,errorMaps:s,issueData:r}=n,i=[...t,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)a=c(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function L(n,e){const t=ca(),s=ua({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ws?void 0:ws].filter(r=>!!r)});n.common.issues.push(s)}class Ee{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const r of t){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Ee.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return J;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const J=Object.freeze({status:"aborted"}),Bt=n=>({status:"dirty",value:n}),Ae=n=>({status:"valid",value:n}),yr=n=>n.status==="aborted",gr=n=>n.status==="dirty",Dt=n=>n.status==="valid",Rn=n=>typeof Promise<"u"&&n instanceof Promise;var z;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));class We{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const wr=(n,e)=>{if(Dt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Ge(n.common.issues);return this._error=t,this._error}}};function Q(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:r}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=n;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:r}}class ee{get description(){return this._def.description}_getType(e){return Xe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ee,ctx:{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Rn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},r=this._parseSync({data:e,path:s.path,parent:s});return wr(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return Dt(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>Dt(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Rn(r)?r:Promise.resolve(r));return wr(s,i)}refine(e,t){const s=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:D.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof t=="function"?t(s,r):t),!1))}_refinement(e){return new Ct({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return st.create(this,this._def)}nullable(){return Ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ve.create(this)}promise(){return An.create(this,this._def)}or(e){return xn.create([this,e],this._def)}and(e){return Dn.create(this,e,this._def)}transform(e){return new Ct({...Q(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new bs({...Q(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new Ca({typeName:Y.ZodBranded,type:this,...Q(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ss({...Q(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return js.create(this,e)}readonly(){return Ts.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const da=/^c[^\s-]{8,}$/i,fa=/^[0-9a-z]+$/,ha=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ma=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,pa=/^[a-z0-9_-]{21}$/i,ya=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ga=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,wa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_a="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ns;const Ea=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,va=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Oa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ka=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ba=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Sa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_i="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ta=new RegExp(`^${_i}$`);function Ei(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Ra(n){return new RegExp(`^${Ei(n)}$`)}function Na(n){let e=`${_i}T${Ei(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function xa(n,e){return!!((e==="v4"||!e)&&Ea.test(n)||(e==="v6"||!e)&&Oa.test(n))}function Da(n,e){if(!ya.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Ia(n,e){return!!((e==="v4"||!e)&&va.test(n)||(e==="v6"||!e)&&ka.test(n))}class He extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){const i=this._getOrReturnCtx(e);return L(i,{code:D.invalid_type,expected:U.string,received:i.parsedType}),J}const s=new Ee;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?L(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&L(r,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")wa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"email",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")ns||(ns=new RegExp(_a,"u")),ns.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"emoji",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")ma.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"uuid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")pa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"nanoid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")da.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cuid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")fa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cuid2",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")ha.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"ulid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),L(r,{validation:"url",code:D.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"regex",code:D.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Na(i).test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ta.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Ra(i).test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:D.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ga.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"duration",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?xa(e.data,i.version)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"ip",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Da(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"jwt",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ia(e.data,i.version)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cidr",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?ba.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Sa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"base64url",code:D.invalid_string,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(r=>e.test(r),{validation:t,code:D.invalid_string,...z.errToObj(s)})}_addCheck(e){return new He({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...z.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...z.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...z.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...z.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...z.errToObj(t)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new He({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new He({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new He({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}He.create=n=>new He({checks:[],typeName:Y.ZodString,coerce:n?.coerce??!1,...Q(n)});function Aa(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=t>s?t:s,i=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class It extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==U.number){const i=this._getOrReturnCtx(e);return L(i,{code:D.invalid_type,expected:U.number,received:i.parsedType}),J}let s;const r=new Ee;for(const i of this._def.checks)i.kind==="int"?ne.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),L(s,{code:D.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Aa(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),L(s,{code:D.not_finite,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.toString(t))}setLimit(e,t,s,r){return new It({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new It({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}It.create=n=>new It({checks:[],typeName:Y.ZodNumber,coerce:n?.coerce||!1,...Q(n)});class en extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==U.bigint)return this._getInvalidInput(e);let s;const r=new Ee;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),L(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return L(t,{code:D.invalid_type,expected:U.bigint,received:t.parsedType}),J}gte(e,t){return this.setLimit("min",e,!0,z.toString(t))}gt(e,t){return this.setLimit("min",e,!1,z.toString(t))}lte(e,t){return this.setLimit("max",e,!0,z.toString(t))}lt(e,t){return this.setLimit("max",e,!1,z.toString(t))}setLimit(e,t,s,r){return new en({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new en({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}en.create=n=>new en({checks:[],typeName:Y.ZodBigInt,coerce:n?.coerce??!1,...Q(n)});class _s extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.boolean,received:s.parsedType}),J}return Ae(e.data)}}_s.create=n=>new _s({typeName:Y.ZodBoolean,coerce:n?.coerce||!1,...Q(n)});class Nn extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){const i=this._getOrReturnCtx(e);return L(i,{code:D.invalid_type,expected:U.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return L(i,{code:D.invalid_date}),J}const s=new Ee;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:D.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:D.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):ne.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Nn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Nn.create=n=>new Nn({checks:[],coerce:n?.coerce||!1,typeName:Y.ZodDate,...Q(n)});class _r extends ee{_parse(e){if(this._getType(e)!==U.symbol){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.symbol,received:s.parsedType}),J}return Ae(e.data)}}_r.create=n=>new _r({typeName:Y.ZodSymbol,...Q(n)});class Es extends ee{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.undefined,received:s.parsedType}),J}return Ae(e.data)}}Es.create=n=>new Es({typeName:Y.ZodUndefined,...Q(n)});class Er extends ee{_parse(e){if(this._getType(e)!==U.null){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.null,received:s.parsedType}),J}return Ae(e.data)}}Er.create=n=>new Er({typeName:Y.ZodNull,...Q(n)});class vs extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return Ae(e.data)}}vs.create=n=>new vs({typeName:Y.ZodAny,...Q(n)});class vr extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ae(e.data)}}vr.create=n=>new vr({typeName:Y.ZodUnknown,...Q(n)});class ot extends ee{_parse(e){const t=this._getOrReturnCtx(e);return L(t,{code:D.invalid_type,expected:U.never,received:t.parsedType}),J}}ot.create=n=>new ot({typeName:Y.ZodNever,...Q(n)});class Or extends ee{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.void,received:s.parsedType}),J}return Ae(e.data)}}Or.create=n=>new Or({typeName:Y.ZodVoid,...Q(n)});class Ve extends ee{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==U.array)return L(t,{code:D.invalid_type,expected:U.array,received:t.parsedType}),J;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(L(t,{code:o?D.too_big:D.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(L(t,{code:D.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(L(t,{code:D.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new We(t,o,t.path,a)))).then(o=>Ee.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new We(t,o,t.path,a)));return Ee.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new Ve({...this._def,minLength:{value:e,message:z.toString(t)}})}max(e,t){return new Ve({...this._def,maxLength:{value:e,message:z.toString(t)}})}length(e,t){return new Ve({...this._def,exactLength:{value:e,message:z.toString(t)}})}nonempty(e){return this.min(1,e)}}Ve.create=(n,e)=>new Ve({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...Q(e)});function bt(n){if(n instanceof fe){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=st.create(bt(s))}return new fe({...n._def,shape:()=>e})}else return n instanceof Ve?new Ve({...n._def,type:bt(n.element)}):n instanceof st?st.create(bt(n.unwrap())):n instanceof Ft?Ft.create(bt(n.unwrap())):n instanceof mt?mt.create(n.items.map(e=>bt(e))):n}class fe extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=ne.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==U.object){const c=this._getOrReturnCtx(e);return L(c,{code:D.invalid_type,expected:U.object,received:c.parsedType}),J}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const u=i[c],h=r.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new We(r,h,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ot){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(c==="strict")a.length>0&&(L(r,{code:D.unrecognized_keys,keys:a}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const h=r.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new We(r,h,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,f=await u.value;c.push({key:h,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>Ee.mergeObjectSync(s,c)):Ee.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new fe({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const r=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:z.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new fe({...this._def,unknownKeys:"strip"})}passthrough(){return new fe({...this._def,unknownKeys:"passthrough"})}extend(e){return new fe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new fe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new fe({...this._def,catchall:e})}pick(e){const t={};for(const s of ne.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new fe({...this._def,shape:()=>t})}omit(e){const t={};for(const s of ne.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new fe({...this._def,shape:()=>t})}deepPartial(){return bt(this)}partial(e){const t={};for(const s of ne.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new fe({...this._def,shape:()=>t})}required(e){const t={};for(const s of ne.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof st;)i=i._def.innerType;t[s]=i}return new fe({...this._def,shape:()=>t})}keyof(){return vi(ne.objectKeys(this.shape))}}fe.create=(n,e)=>new fe({shape:()=>n,unknownKeys:"strip",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});fe.strictCreate=(n,e)=>new fe({shape:()=>n,unknownKeys:"strict",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});fe.lazycreate=(n,e)=>new fe({shape:n,unknownKeys:"strip",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});class xn extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Ge(a.ctx.common.issues));return L(t,{code:D.invalid_union,unionErrors:o}),J}if(t.common.async)return Promise.all(s.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new Ge(l));return L(t,{code:D.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}xn.create=(n,e)=>new xn({options:n,typeName:Y.ZodUnion,...Q(e)});function Os(n,e){const t=Xe(n),s=Xe(e);if(n===e)return{valid:!0,data:n};if(t===U.object&&s===U.object){const r=ne.objectKeys(e),i=ne.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(const a of i){const l=Os(n[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===U.array&&s===U.array){if(n.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<n.length;i++){const o=n[i],a=e[i],l=Os(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return t===U.date&&s===U.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Dn extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(yr(i)||yr(o))return J;const a=Os(i.value,o.value);return a.valid?((gr(i)||gr(o))&&t.dirty(),{status:t.value,value:a.data}):(L(s,{code:D.invalid_intersection_types}),J)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Dn.create=(n,e,t)=>new Dn({left:n,right:e,typeName:Y.ZodIntersection,...Q(t)});class mt extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.array)return L(s,{code:D.invalid_type,expected:U.array,received:s.parsedType}),J;if(s.data.length<this._def.items.length)return L(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&s.data.length>this._def.items.length&&(L(s,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...s.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new We(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Ee.mergeArray(t,o)):Ee.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new mt({...this._def,rest:e})}}mt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:n,typeName:Y.ZodTuple,rest:null,...Q(e)})};class In extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.object)return L(s,{code:D.invalid_type,expected:U.object,received:s.parsedType}),J;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new We(s,a,s.path,a)),value:o._parse(new We(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Ee.mergeObjectAsync(t,r):Ee.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof ee?new In({keyType:e,valueType:t,typeName:Y.ZodRecord,...Q(s)}):new In({keyType:He.create(),valueType:e,typeName:Y.ZodRecord,...Q(t)})}}class kr extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.map)return L(s,{code:D.invalid_type,expected:U.map,received:s.parsedType}),J;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,l],c)=>({key:r._parse(new We(s,a,s.path,[c,"key"])),value:i._parse(new We(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return J;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(c.value,u.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return J;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(c.value,u.value)}return{status:t.value,value:a}}}}kr.create=(n,e,t)=>new kr({valueType:e,keyType:n,typeName:Y.ZodMap,...Q(t)});class tn extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.set)return L(s,{code:D.invalid_type,expected:U.set,received:s.parsedType}),J;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(L(s,{code:D.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(L(s,{code:D.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const u of l){if(u.status==="aborted")return J;u.status==="dirty"&&t.dirty(),c.add(u.value)}return{status:t.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new We(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new tn({...this._def,minSize:{value:e,message:z.toString(t)}})}max(e,t){return new tn({...this._def,maxSize:{value:e,message:z.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}tn.create=(n,e)=>new tn({valueType:n,minSize:null,maxSize:null,typeName:Y.ZodSet,...Q(e)});class br extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}br.create=(n,e)=>new br({getter:n,typeName:Y.ZodLazy,...Q(e)});class ks extends ee{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return L(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}ks.create=(n,e)=>new ks({value:n,typeName:Y.ZodLiteral,...Q(e)});function vi(n,e){return new At({values:n,typeName:Y.ZodEnum,...Q(e)})}class At extends ee{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return L(t,{expected:ne.joinValues(s),received:t.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return L(t,{received:t.data,code:D.invalid_enum_value,options:s}),J}return Ae(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return At.create(e,{...this._def,...t})}exclude(e,t=this._def){return At.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}At.create=vi;class Sr extends ee{_parse(e){const t=ne.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==U.string&&s.parsedType!==U.number){const r=ne.objectValues(t);return L(s,{expected:ne.joinValues(r),received:s.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=ne.objectValues(t);return L(s,{received:s.data,code:D.invalid_enum_value,options:r}),J}return Ae(e.data)}get enum(){return this._def.values}}Sr.create=(n,e)=>new Sr({values:n,typeName:Y.ZodNativeEnum,...Q(e)});class An extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.promise&&t.common.async===!1)return L(t,{code:D.invalid_type,expected:U.promise,received:t.parsedType}),J;const s=t.parsedType===U.promise?t.data:Promise.resolve(t.data);return Ae(s.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}An.create=(n,e)=>new An({type:n,typeName:Y.ZodPromise,...Q(e)});class Ct extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{L(s,o),o.fatal?t.abort():t.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return J;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?J:l.status==="dirty"||t.value==="dirty"?Bt(l.value):l});{if(t.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?J:a.status==="dirty"||t.value==="dirty"?Bt(a.value):a}}if(r.type==="refinement"){const o=a=>{const l=r.refinement(a,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Dt(o))return J;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Dt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):J);ne.assertNever(r)}}Ct.create=(n,e,t)=>new Ct({schema:n,typeName:Y.ZodEffects,effect:e,...Q(t)});Ct.createWithPreprocess=(n,e,t)=>new Ct({schema:e,effect:{type:"preprocess",transform:n},typeName:Y.ZodEffects,...Q(t)});class st extends ee{_parse(e){return this._getType(e)===U.undefined?Ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}st.create=(n,e)=>new st({innerType:n,typeName:Y.ZodOptional,...Q(e)});class Ft extends ee{_parse(e){return this._getType(e)===U.null?Ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ft.create=(n,e)=>new Ft({innerType:n,typeName:Y.ZodNullable,...Q(e)});class bs extends ee{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===U.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}bs.create=(n,e)=>new bs({innerType:n,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});class Ss extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Rn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ge(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Ge(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ss.create=(n,e)=>new Ss({innerType:n,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});class Tr extends ee{_parse(e){if(this._getType(e)!==U.nan){const s=this._getOrReturnCtx(e);return L(s,{code:D.invalid_type,expected:U.nan,received:s.parsedType}),J}return{status:"valid",value:e.data}}}Tr.create=n=>new Tr({typeName:Y.ZodNaN,...Q(n)});class Ca extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class js extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?J:i.status==="dirty"?(t.dirty(),Bt(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?J:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,t){return new js({in:e,out:t,typeName:Y.ZodPipeline})}}class Ts extends ee{_parse(e){const t=this._def.innerType._parse(e),s=r=>(Dt(r)&&(r.value=Object.freeze(r.value)),r);return Rn(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}Ts.create=(n,e)=>new Ts({innerType:n,typeName:Y.ZodReadonly,...Q(e)});var Y;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Y||(Y={}));const ke=He.create,dt=It.create,Kt=_s.create,ss=Es.create,ye=vs.create;ot.create;const wt=Ve.create,Ue=fe.create,ve=xn.create;Dn.create;mt.create;const rn=In.create,Oe=ks.create,Cn=At.create;An.create;st.create;Ft.create;const gn=()=>ye().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),Rr=()=>ye().refine(n=>n&&(n._methodName==="serverTimestamp"||n.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),Oi=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return rn(ye());n.includeFields.forEach(r=>{const i=s.fields.find(a=>a.name===r);if(!i)throw new Error(`Field ${r} not found in collection ${n.collection}`);t[r]=Fn(s,i),gt(s,[i]).size===1&&(t[`${r}_Lowercase`]=Fn(s,i,!0))})}return Ue({Collection_Path:wt(ke()),...t})},Fa=(n,e)=>{let t=rn(Oi(n,e));return n.required||(t=t.optional()),t},$a=n=>{let e=wt(ve([ke().length(20),ke().length(28)]));return["OneToOne","OneToMany"].includes(n.type)?e=e.max(1):(n.min&&(e=e.min(n.min)),n.max&&(e=e.max(n.max)),n.length&&(e=e.length(n.length))),n.required?e=e.nonempty():e=e.optional(),e},Fn=(n,e,t)=>{const{softDelete:s}=n,r=s?.timestampField;let i;switch(e.type){case"String":if(i=ke(),e.length&&(i=i.length(e.length)),e.minlength&&(i=i.min(e.minlength)),e.maxlength&&(i=i.max(e.maxlength)),e.email&&(i=i.email()),e.uuid&&(i=i.uuid()),e.url&&(i=i.url()),e.emoji&&(i=i.emoji()),e.ip&&(i=i.ip()),e.pattern&&(i=i.regex(new RegExp(e.pattern))),t&&(i=i.toLowerCase()),e.values)if(t){const o=e.values.map(a=>a.toLowerCase());i=Cn(o)}else i=Cn(e.values);break;case"Boolean":i=Kt();break;case"Number":e.autoIncrement?i=ve([Oe("Pending"),dt().int()]):(i=dt(),e.min&&(i=i.min(e.min)),e.max&&(i=i.max(e.max)),e.decimal?i=i.refine(o=>e.decimal?(o.toString().split(".")[1]?.length||0)<=e.decimal:!1,{message:`Value must have ${e.decimal} or fewer decimal places`}):i=i.int(),e.values&&(i=i.refine(o=>e.values?.includes(o),{message:"Value is not an allowed value"})));break;case"Timestamp":e.name===r?i=ye().refine(o=>o&&(o._methodName==="serverTimestamp"||o.constructor.name==="ServerTimestampTransform"||o.seconds!==void 0&&o.nanoseconds!==void 0||o._seconds!==void 0&&o._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}):(i=gn(),e.min&&(i=i.refine(o=>o.toMillis()>=e.min,{message:`Value is less than the minimum allowed value of ${e.min}`})),e.max&&(i=i.refine(o=>o.toMillis()<=e.max,{message:`Value is greater than the maximum allowed value of ${e.max}`})));break;case"Array":i=wt(ye()),e.length&&(i=i.length(e.length)),e.minlength?i=i.min(e.minlength):e.required&&(i=i.nonempty()),e.maxlength&&(i=i.max(e.maxlength)),e.values&&(i=i.refine(o=>{let a=!0;return o.forEach(l=>{e.values&&!e.values.includes(l)&&(a=!1)}),a},{message:"Value is not an allowed value"}));break;case"Map":i=rn(ye()),e.required&&(i=i.refine(o=>o&&typeof o=="object"&&Object.keys(o).length>0,{message:"Value must have at least one object property"}));break;case"Embedding":i=ye();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},ki=(n,e,t)=>{const s={Collection_Path:wt(ke()),Last_Write_App:ke(),Last_Write_At:gn(),Last_Save_At:Rr(),Last_Write_By:ve([ke().length(28),Oe("System")]),Last_Write_Connection_Status:Cn(["Online","Offline"]),Last_Write_Version:dt().int(),id:ke().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:gn(),Created_By:ve([ke().length(28),Oe("System")])};n==="create"&&(s.Saved_At=Rr()),n==="update"&&(s.Saved_At=gn(),s.Collection_Path=s.Collection_Path.optional(),s.id=s.id.optional(),s.Created_At=s.Created_At.optional(),s.Saved_At=s.Saved_At.optional(),s.Created_By=s.Created_By.optional());const r=ut(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{X(l)?(s[l.name]=Fa(l,t),s[`${l.name}_Array`]=$a(l),i.includes(l.name)&&(s[`${l.name}_Single`]=Oi(l,t),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=Fn(e,l))}),gt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=Fn(e,l,!0))});const a=Ue(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class _t extends Error{}class Ma extends _t{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Pa extends _t{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class La extends _t{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class St extends _t{}class bi extends _t{constructor(e){super(`Invalid unit ${e}`)}}class ge extends _t{}class Ke extends _t{constructor(){super("Zone is an abstract class")}}const F="numeric",Me="short",be="long",$n={year:F,month:F,day:F},Si={year:F,month:Me,day:F},Va={year:F,month:Me,day:F,weekday:Me},Ti={year:F,month:be,day:F},Ri={year:F,month:be,day:F,weekday:be},Ni={hour:F,minute:F},xi={hour:F,minute:F,second:F},Di={hour:F,minute:F,second:F,timeZoneName:Me},Ii={hour:F,minute:F,second:F,timeZoneName:be},Ai={hour:F,minute:F,hourCycle:"h23"},Ci={hour:F,minute:F,second:F,hourCycle:"h23"},Fi={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:Me},$i={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:be},Mi={year:F,month:F,day:F,hour:F,minute:F},Pi={year:F,month:F,day:F,hour:F,minute:F,second:F},Li={year:F,month:Me,day:F,hour:F,minute:F},Vi={year:F,month:Me,day:F,hour:F,minute:F,second:F},Ua={year:F,month:Me,day:F,weekday:Me,hour:F,minute:F},Ui={year:F,month:be,day:F,hour:F,minute:F,timeZoneName:Me},Wi={year:F,month:be,day:F,hour:F,minute:F,second:F,timeZoneName:Me},ji={year:F,month:be,day:F,weekday:be,hour:F,minute:F,timeZoneName:be},Zi={year:F,month:be,day:F,weekday:be,hour:F,minute:F,second:F,timeZoneName:be};class on{get type(){throw new Ke}get name(){throw new Ke}get ianaName(){return this.name}get isUniversal(){throw new Ke}offsetName(e,t){throw new Ke}formatOffset(e,t){throw new Ke}offset(e){throw new Ke}equals(e){throw new Ke}get isValid(){throw new Ke}}let rs=null;class zn extends on{static get instance(){return rs===null&&(rs=new zn),rs}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return eo(e,t,s)}formatOffset(e,t){return Xt(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Rs=new Map;function Wa(n){let e=Rs.get(n);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Rs.set(n,e)),e}const ja={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Za(n,e){const t=n.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,r,i,o,a,l,c,u]=s;return[o,r,i,a,l,c,u]}function za(n,e){const t=n.formatToParts(e),s=[];for(let r=0;r<t.length;r++){const{type:i,value:o}=t[r],a=ja[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const is=new Map;class Ye extends on{static create(e){let t=is.get(e);return t===void 0&&is.set(e,t=new Ye(e)),t}static resetCache(){is.clear(),Rs.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=Ye.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return eo(e,t,s,this.name)}formatOffset(e,t){return Xt(this.offset(e),t)}offset(e){if(!this.valid)return NaN;const t=new Date(e);if(isNaN(t))return NaN;const s=Wa(this.name);let[r,i,o,a,l,c,u]=s.formatToParts?za(s,t):Za(s,t);a==="BC"&&(r=-Math.abs(r)+1);const f=Bn({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:u,millisecond:0});let d=+t;const m=d%1e3;return d-=m>=0?m:1e3+m,(f-d)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Nr={};function qa(n,e={}){const t=JSON.stringify([n,e]);let s=Nr[t];return s||(s=new Intl.ListFormat(n,e),Nr[t]=s),s}const Ns=new Map;function xs(n,e={}){const t=JSON.stringify([n,e]);let s=Ns.get(t);return s===void 0&&(s=new Intl.DateTimeFormat(n,e),Ns.set(t,s)),s}const Ds=new Map;function Ba(n,e={}){const t=JSON.stringify([n,e]);let s=Ds.get(t);return s===void 0&&(s=new Intl.NumberFormat(n,e),Ds.set(t,s)),s}const Is=new Map;function Ha(n,e={}){const{base:t,...s}=e,r=JSON.stringify([n,s]);let i=Is.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(n,e),Is.set(r,i)),i}let Ht=null;function Ga(){return Ht||(Ht=new Intl.DateTimeFormat().resolvedOptions().locale,Ht)}const As=new Map;function zi(n){let e=As.get(n);return e===void 0&&(e=new Intl.DateTimeFormat(n).resolvedOptions(),As.set(n,e)),e}const Cs=new Map;function Ya(n){let e=Cs.get(n);if(!e){const t=new Intl.Locale(n);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,"minimalDays"in e||(e={...qi,...e}),Cs.set(n,e)}return e}function Ja(n){const e=n.indexOf("-x-");e!==-1&&(n=n.substring(0,e));const t=n.indexOf("-u-");if(t===-1)return[n];{let s,r;try{s=xs(n).resolvedOptions(),r=n}catch{const l=n.substring(0,t);s=xs(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function Qa(n,e,t){return(t||e)&&(n.includes("-u-")||(n+="-u"),t&&(n+=`-ca-${t}`),e&&(n+=`-nu-${e}`)),n}function Ka(n){const e=[];for(let t=1;t<=12;t++){const s=V.utc(2009,t,1);e.push(n(s))}return e}function Xa(n){const e=[];for(let t=1;t<=7;t++){const s=V.utc(2016,11,13+t);e.push(n(s))}return e}function dn(n,e,t,s){const r=n.listingMode();return r==="error"?null:r==="en"?t(e):s(e)}function el(n){return n.numberingSystem&&n.numberingSystem!=="latn"?!1:n.numberingSystem==="latn"||!n.locale||n.locale.startsWith("en")||zi(n.locale).numberingSystem==="latn"}class tl{constructor(e,t,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!t||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=Ba(e,a)}}format(e){if(this.inf){const t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{const t=this.floor?Math.floor(e):Hs(e,3);return he(t,this.padTo)}}}class nl{constructor(e,t,s){this.opts=s,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&Ye.create(a).valid?(r=a,this.dt=e):(r="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,r=e.zone.name):(r="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const i={...this.opts};i.timeZone=i.timeZone||r,this.dtf=xs(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:s}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class sl{constructor(e,t,s){this.opts={style:"long",...s},!t&&Ki()&&(this.rtf=Ha(e,s))}format(e,t){return this.rtf?this.rtf.format(e,t):Sl(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}}const qi={firstDay:1,minimalDays:4,weekend:[6,7]};class re{static fromOpts(e){return re.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,s,r,i=!1){const o=e||ue.defaultLocale,a=o||(i?"en-US":Ga()),l=t||ue.defaultNumberingSystem,c=s||ue.defaultOutputCalendar,u=$s(r)||ue.defaultWeekSettings;return new re(a,l,c,u,o)}static resetCache(){Ht=null,Ns.clear(),Ds.clear(),Is.clear(),As.clear(),Cs.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:r}={}){return re.create(e,t,s,r)}constructor(e,t,s,r,i){const[o,a,l]=Ja(e);this.locale=o,this.numberingSystem=t||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=Qa(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=el(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:re.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,$s(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return dn(this,e,so,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");t&=!s;const r=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";if(!this.monthsCache[i][e]){const o=s?a=>this.dtFormatter(a,r).format():a=>this.extract(a,r,"month");this.monthsCache[i][e]=Ka(o)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return dn(this,e,oo,()=>{const s=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=t?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=Xa(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return dn(this,void 0,()=>ao,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[V.utc(2016,11,13,9),V.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return dn(this,e,lo,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[V.utc(-40,1,1),V.utc(2017,1,1)].map(s=>this.extract(s,t,"era"))),this.eraCache[e]})}extract(e,t,s){const r=this.dtFormatter(e,t),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new tl(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new nl(e,this.intl,t)}relFormatter(e={}){return new sl(this.intl,this.isEnglish(),e)}listFormatter(e={}){return qa(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||zi(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Xi()?Ya(this.locale):qi}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let os=null;class _e extends on{static get utcInstance(){return os===null&&(os=new _e(0)),os}static instance(e){return e===0?_e.utcInstance:new _e(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new _e(Hn(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Xt(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Xt(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return Xt(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class rl extends on{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function tt(n,e){if(G(n)||n===null)return e;if(n instanceof on)return n;if(ul(n)){const t=n.toLowerCase();return t==="default"?e:t==="local"||t==="system"?zn.instance:t==="utc"||t==="gmt"?_e.utcInstance:_e.parseSpecifier(t)||Ye.create(n)}else return rt(n)?_e.instance(n):typeof n=="object"&&"offset"in n&&typeof n.offset=="function"?n:new rl(n)}const Zs={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},xr={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},il=Zs.hanidec.replace(/[\[|\]]/g,"").split("");function ol(n){let e=parseInt(n,10);if(isNaN(e)){e="";for(let t=0;t<n.length;t++){const s=n.charCodeAt(t);if(n[t].search(Zs.hanidec)!==-1)e+=il.indexOf(n[t]);else for(const r in xr){const[i,o]=xr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const Fs=new Map;function al(){Fs.clear()}function Ce({numberingSystem:n},e=""){const t=n||"latn";let s=Fs.get(t);s===void 0&&(s=new Map,Fs.set(t,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${Zs[t]}${e}`),s.set(e,r)),r}let Dr=()=>Date.now(),Ir="system",Ar=null,Cr=null,Fr=null,$r=60,Mr,Pr=null;class ue{static get now(){return Dr}static set now(e){Dr=e}static set defaultZone(e){Ir=e}static get defaultZone(){return tt(Ir,zn.instance)}static get defaultLocale(){return Ar}static set defaultLocale(e){Ar=e}static get defaultNumberingSystem(){return Cr}static set defaultNumberingSystem(e){Cr=e}static get defaultOutputCalendar(){return Fr}static set defaultOutputCalendar(e){Fr=e}static get defaultWeekSettings(){return Pr}static set defaultWeekSettings(e){Pr=$s(e)}static get twoDigitCutoffYear(){return $r}static set twoDigitCutoffYear(e){$r=e%100}static get throwOnInvalid(){return Mr}static set throwOnInvalid(e){Mr=e}static resetCaches(){re.resetCache(),Ye.resetCache(),V.resetCache(),al()}}class $e{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Bi=[0,31,59,90,120,151,181,212,243,273,304,334],Hi=[0,31,60,91,121,152,182,213,244,274,305,335];function xe(n,e){return new $e("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${n}, which is invalid`)}function zs(n,e,t){const s=new Date(Date.UTC(n,e-1,t));n<100&&n>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function Gi(n,e,t){return t+(an(n)?Hi:Bi)[e-1]}function Yi(n,e){const t=an(n)?Hi:Bi,s=t.findIndex(i=>i<e),r=e-t[s];return{month:s+1,day:r}}function qs(n,e){return(n-e+7)%7+1}function Mn(n,e=4,t=1){const{year:s,month:r,day:i}=n,o=Gi(s,r,i),a=qs(zs(s,r,i),t);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=nn(c,e,t)):l>nn(s,e,t)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...Gn(n)}}function Lr(n,e=4,t=1){const{weekYear:s,weekNumber:r,weekday:i}=n,o=qs(zs(s,1,e),t),a=Nt(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=Nt(c)):l>a?(c=s+1,l-=Nt(s)):c=s;const{month:u,day:h}=Yi(c,l);return{year:c,month:u,day:h,...Gn(n)}}function as(n){const{year:e,month:t,day:s}=n,r=Gi(e,t,s);return{year:e,ordinal:r,...Gn(n)}}function Vr(n){const{year:e,ordinal:t}=n,{month:s,day:r}=Yi(e,t);return{year:e,month:s,day:r,...Gn(n)}}function Ur(n,e){if(!G(n.localWeekday)||!G(n.localWeekNumber)||!G(n.localWeekYear)){if(!G(n.weekday)||!G(n.weekNumber)||!G(n.weekYear))throw new St("Cannot mix locale-based week fields with ISO-based week fields");return G(n.localWeekday)||(n.weekday=n.localWeekday),G(n.localWeekNumber)||(n.weekNumber=n.localWeekNumber),G(n.localWeekYear)||(n.weekYear=n.localWeekYear),delete n.localWeekday,delete n.localWeekNumber,delete n.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function ll(n,e=4,t=1){const s=qn(n.weekYear),r=De(n.weekNumber,1,nn(n.weekYear,e,t)),i=De(n.weekday,1,7);return s?r?i?!1:xe("weekday",n.weekday):xe("week",n.weekNumber):xe("weekYear",n.weekYear)}function cl(n){const e=qn(n.year),t=De(n.ordinal,1,Nt(n.year));return e?t?!1:xe("ordinal",n.ordinal):xe("year",n.year)}function Ji(n){const e=qn(n.year),t=De(n.month,1,12),s=De(n.day,1,Pn(n.year,n.month));return e?t?s?!1:xe("day",n.day):xe("month",n.month):xe("year",n.year)}function Qi(n){const{hour:e,minute:t,second:s,millisecond:r}=n,i=De(e,0,23)||e===24&&t===0&&s===0&&r===0,o=De(t,0,59),a=De(s,0,59),l=De(r,0,999);return i?o?a?l?!1:xe("millisecond",r):xe("second",s):xe("minute",t):xe("hour",e)}function G(n){return typeof n>"u"}function rt(n){return typeof n=="number"}function qn(n){return typeof n=="number"&&n%1===0}function ul(n){return typeof n=="string"}function dl(n){return Object.prototype.toString.call(n)==="[object Date]"}function Ki(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Xi(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function fl(n){return Array.isArray(n)?n:[n]}function Wr(n,e,t){if(n.length!==0)return n.reduce((s,r)=>{const i=[e(r),r];return s&&t(s[0],i[0])===s[0]?s:i},null)[1]}function hl(n,e){return e.reduce((t,s)=>(t[s]=n[s],t),{})}function $t(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function $s(n){if(n==null)return null;if(typeof n!="object")throw new ge("Week settings must be an object");if(!De(n.firstDay,1,7)||!De(n.minimalDays,1,7)||!Array.isArray(n.weekend)||n.weekend.some(e=>!De(e,1,7)))throw new ge("Invalid week settings");return{firstDay:n.firstDay,minimalDays:n.minimalDays,weekend:Array.from(n.weekend)}}function De(n,e,t){return qn(n)&&n>=e&&n<=t}function ml(n,e){return n-e*Math.floor(n/e)}function he(n,e=2){const t=n<0;let s;return t?s="-"+(""+-n).padStart(e,"0"):s=(""+n).padStart(e,"0"),s}function et(n){if(!(G(n)||n===null||n===""))return parseInt(n,10)}function lt(n){if(!(G(n)||n===null||n===""))return parseFloat(n)}function Bs(n){if(!(G(n)||n===null||n==="")){const e=parseFloat("0."+n)*1e3;return Math.floor(e)}}function Hs(n,e,t="round"){const s=10**e;switch(t){case"expand":return n>0?Math.ceil(n*s)/s:Math.floor(n*s)/s;case"trunc":return Math.trunc(n*s)/s;case"round":return Math.round(n*s)/s;case"floor":return Math.floor(n*s)/s;case"ceil":return Math.ceil(n*s)/s;default:throw new RangeError(`Value rounding ${t} is out of range`)}}function an(n){return n%4===0&&(n%100!==0||n%400===0)}function Nt(n){return an(n)?366:365}function Pn(n,e){const t=ml(e-1,12)+1,s=n+(e-t)/12;return t===2?an(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function Bn(n){let e=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return n.year<100&&n.year>=0&&(e=new Date(e),e.setUTCFullYear(n.year,n.month-1,n.day)),+e}function jr(n,e,t){return-qs(zs(n,1,e),t)+e-1}function nn(n,e=4,t=1){const s=jr(n,e,t),r=jr(n+1,e,t);return(Nt(n)-s+r)/7}function Ms(n){return n>99?n:n>ue.twoDigitCutoffYear?1900+n:2e3+n}function eo(n,e,t,s=null){const r=new Date(n),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(t,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function Hn(n,e){let t=parseInt(n,10);Number.isNaN(t)&&(t=0);const s=parseInt(e,10)||0,r=t<0||Object.is(t,-0)?-s:s;return t*60+r}function to(n){const e=Number(n);if(typeof n=="boolean"||n===""||!Number.isFinite(e))throw new ge(`Invalid unit value ${n}`);return e}function Ln(n,e){const t={};for(const s in n)if($t(n,s)){const r=n[s];if(r==null)continue;t[e(s)]=to(r)}return t}function Xt(n,e){const t=Math.trunc(Math.abs(n/60)),s=Math.trunc(Math.abs(n%60)),r=n>=0?"+":"-";switch(e){case"short":return`${r}${he(t,2)}:${he(s,2)}`;case"narrow":return`${r}${t}${s>0?`:${s}`:""}`;case"techie":return`${r}${he(t,2)}${he(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Gn(n){return hl(n,["hour","minute","second","millisecond"])}const pl=["January","February","March","April","May","June","July","August","September","October","November","December"],no=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],yl=["J","F","M","A","M","J","J","A","S","O","N","D"];function so(n){switch(n){case"narrow":return[...yl];case"short":return[...no];case"long":return[...pl];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const ro=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],io=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],gl=["M","T","W","T","F","S","S"];function oo(n){switch(n){case"narrow":return[...gl];case"short":return[...io];case"long":return[...ro];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const ao=["AM","PM"],wl=["Before Christ","Anno Domini"],_l=["BC","AD"],El=["B","A"];function lo(n){switch(n){case"narrow":return[...El];case"short":return[..._l];case"long":return[...wl];default:return null}}function vl(n){return ao[n.hour<12?0:1]}function Ol(n,e){return oo(e)[n.weekday-1]}function kl(n,e){return so(e)[n.month-1]}function bl(n,e){return lo(e)[n.year<0?0:1]}function Sl(n,e,t="always",s=!1){const r={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(n)===-1;if(t==="auto"&&i){const h=n==="days";switch(e){case 1:return h?"tomorrow":`next ${r[n][0]}`;case-1:return h?"yesterday":`last ${r[n][0]}`;case 0:return h?"today":`this ${r[n][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[n],u=s?l?c[1]:c[2]||c[1]:l?r[n][0]:n;return o?`${a} ${u} ago`:`in ${a} ${u}`}function Zr(n,e){let t="";for(const s of n)s.literal?t+=s.val:t+=e(s.val);return t}const Tl={D:$n,DD:Si,DDD:Ti,DDDD:Ri,t:Ni,tt:xi,ttt:Di,tttt:Ii,T:Ai,TT:Ci,TTT:Fi,TTTT:$i,f:Mi,ff:Li,fff:Ui,ffff:ji,F:Pi,FF:Vi,FFF:Wi,FFFF:Zi};class we{static create(e,t={}){return new we(e,t)}static parseFormat(e){let t=null,s="",r=!1;const i=[];for(let o=0;o<e.length;o++){const a=e.charAt(o);a==="'"?((s.length>0||r)&&i.push({literal:r||/^\s+$/.test(s),val:s===""?"'":s}),t=null,s="",r=!r):r||a===t?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,t=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return Tl[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,s=void 0){if(this.opts.forceSimple)return he(e,t);const r={...this.opts};return t>0&&(r.padTo=t),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,t){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(d,m)=>this.loc.extract(e,d,m),o=d=>e.isOffsetFixed&&e.offset===0&&d.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,d.format):"",a=()=>s?vl(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(d,m)=>s?kl(e,d):i(m?{month:d}:{month:d,day:"numeric"},"month"),c=(d,m)=>s?Ol(e,d):i(m?{weekday:d}:{weekday:d,month:"long",day:"numeric"},"weekday"),u=d=>{const m=we.macroTokenToFormatOpts(d);return m?this.formatWithSystemDefault(e,m):d},h=d=>s?bl(e,d):i({era:d},"era"),f=d=>{switch(d){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return r?i({day:"numeric"},"day"):this.num(e.day);case"dd":return r?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return r?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return r?i({month:"numeric"},"month"):this.num(e.month);case"MM":return r?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return r?i({year:"numeric"},"year"):this.num(e.year);case"yy":return r?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return h("short");case"GG":return h("long");case"GGGGG":return h("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(d)}};return Zr(we.parseFormat(t),f)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=u=>{switch(u[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(u,h)=>f=>{const d=r(f);if(d){const m=h.isNegativeDuration&&d!==h.largestUnit?s:1;let O;return this.opts.signMode==="negativeLargestOnly"&&d!==h.largestUnit?O="never":this.opts.signMode==="all"?O="always":O="auto",this.num(u.get(d)*m,f.length,O)}else return f},o=we.parseFormat(t),a=o.reduce((u,{literal:h,val:f})=>h?u:u.concat(f),[]),l=e.shiftTo(...a.map(r).filter(u=>u)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Zr(o,i(l,c))}}const co=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Mt(...n){const e=n.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function Pt(...n){return e=>n.reduce(([t,s,r],i)=>{const[o,a,l]=i(e,r);return[{...t,...o},a||s,l]},[{},null,1]).slice(0,2)}function Lt(n,...e){if(n==null)return[null,null];for(const[t,s]of e){const r=t.exec(n);if(r)return s(r)}return[null,null]}function uo(...n){return(e,t)=>{const s={};let r;for(r=0;r<n.length;r++)s[n[r]]=et(e[t+r]);return[s,null,t+r]}}const fo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Rl=`(?:${fo.source}?(?:\\[(${co.source})\\])?)?`,Gs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,ho=RegExp(`${Gs.source}${Rl}`),Ys=RegExp(`(?:[Tt]${ho.source})?`),Nl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,xl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Dl=/(\d{4})-?(\d{3})/,Il=uo("weekYear","weekNumber","weekDay"),Al=uo("year","ordinal"),Cl=/(\d{4})-(\d\d)-(\d\d)/,mo=RegExp(`${Gs.source} ?(?:${fo.source}|(${co.source}))?`),Fl=RegExp(`(?: ${mo.source})?`);function xt(n,e,t){const s=n[e];return G(s)?t:et(s)}function $l(n,e){return[{year:xt(n,e),month:xt(n,e+1,1),day:xt(n,e+2,1)},null,e+3]}function Vt(n,e){return[{hours:xt(n,e,0),minutes:xt(n,e+1,0),seconds:xt(n,e+2,0),milliseconds:Bs(n[e+3])},null,e+4]}function ln(n,e){const t=!n[e]&&!n[e+1],s=Hn(n[e+1],n[e+2]),r=t?null:_e.instance(s);return[{},r,e+3]}function cn(n,e){const t=n[e]?Ye.create(n[e]):null;return[{},t,e+1]}const Ml=RegExp(`^T?${Gs.source}$`),Pl=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Ll(n){const[e,t,s,r,i,o,a,l,c]=n,u=e[0]==="-",h=l&&l[0]==="-",f=(d,m=!1)=>d!==void 0&&(m||d&&u)?-d:d;return[{years:f(lt(t)),months:f(lt(s)),weeks:f(lt(r)),days:f(lt(i)),hours:f(lt(o)),minutes:f(lt(a)),seconds:f(lt(l),l==="-0"),milliseconds:f(Bs(c),h)}]}const Vl={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Js(n,e,t,s,r,i,o){const a={year:e.length===2?Ms(et(e)):et(e),month:no.indexOf(t)+1,day:et(s),hour:et(r),minute:et(i)};return o&&(a.second=et(o)),n&&(a.weekday=n.length>3?ro.indexOf(n)+1:io.indexOf(n)+1),a}const Ul=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Wl(n){const[,e,t,s,r,i,o,a,l,c,u,h]=n,f=Js(e,r,s,t,i,o,a);let d;return l?d=Vl[l]:c?d=0:d=Hn(u,h),[f,new _e(d)]}function jl(n){return n.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Zl=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,zl=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,ql=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function zr(n){const[,e,t,s,r,i,o,a]=n;return[Js(e,r,s,t,i,o,a),_e.utcInstance]}function Bl(n){const[,e,t,s,r,i,o,a]=n;return[Js(e,a,t,s,r,i,o),_e.utcInstance]}const Hl=Mt(Nl,Ys),Gl=Mt(xl,Ys),Yl=Mt(Dl,Ys),Jl=Mt(ho),po=Pt($l,Vt,ln,cn),Ql=Pt(Il,Vt,ln,cn),Kl=Pt(Al,Vt,ln,cn),Xl=Pt(Vt,ln,cn);function ec(n){return Lt(n,[Hl,po],[Gl,Ql],[Yl,Kl],[Jl,Xl])}function tc(n){return Lt(jl(n),[Ul,Wl])}function nc(n){return Lt(n,[Zl,zr],[zl,zr],[ql,Bl])}function sc(n){return Lt(n,[Pl,Ll])}const rc=Pt(Vt);function ic(n){return Lt(n,[Ml,rc])}const oc=Mt(Cl,Fl),ac=Mt(mo),lc=Pt(Vt,ln,cn);function cc(n){return Lt(n,[oc,po],[ac,lc])}const qr="Invalid Duration",yo={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},uc={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...yo},Re=146097/400,vt=146097/4800,dc={years:{quarters:4,months:12,weeks:Re/7,days:Re,hours:Re*24,minutes:Re*24*60,seconds:Re*24*60*60,milliseconds:Re*24*60*60*1e3},quarters:{months:3,weeks:Re/28,days:Re/4,hours:Re*24/4,minutes:Re*24*60/4,seconds:Re*24*60*60/4,milliseconds:Re*24*60*60*1e3/4},months:{weeks:vt/7,days:vt,hours:vt*24,minutes:vt*24*60,seconds:vt*24*60*60,milliseconds:vt*24*60*60*1e3},...yo},ft=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],fc=ft.slice(0).reverse();function qe(n,e,t=!1){const s={values:t?e.values:{...n.values,...e.values||{}},loc:n.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||n.conversionAccuracy,matrix:e.matrix||n.matrix};return new te(s)}function go(n,e){let t=e.milliseconds??0;for(const s of fc.slice(1))e[s]&&(t+=e[s]*n[s].milliseconds);return t}function Br(n,e){const t=go(n,e)<0?-1:1;ft.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*t,o=n[r][s],a=Math.floor(i/o);e[r]+=a*t,e[s]-=a*o*t}return r},null),ft.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*n[s][r]}return r},null)}function Hr(n){const e={};for(const[t,s]of Object.entries(n))s!==0&&(e[t]=s);return e}class te{constructor(e){const t=e.conversionAccuracy==="longterm"||!1;let s=t?dc:uc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||re.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return te.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new ge(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new te({values:Ln(e,te.normalizeUnit),loc:re.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(rt(e))return te.fromMillis(e);if(te.isDuration(e))return e;if(typeof e=="object")return te.fromObject(e);throw new ge(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=sc(e);return s?te.fromObject(s,t):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=ic(e);return s?te.fromObject(s,t):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new ge("need to specify a reason the Duration is invalid");const s=e instanceof $e?e:new $e(e,t);if(ue.throwOnInvalid)throw new La(s);return new te({invalid:s})}static normalizeUnit(e){const t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new bi(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){const s={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?we.create(this.loc,s).formatDurationFromString(this,e):qr}toHuman(e={}){if(!this.isValid)return qr;const t=e.showZeros!==!1,s=ft.map(r=>{const i=this.values[r];return G(i)||i===0&&!t?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Hs(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},V.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?go(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e),s={};for(const r of ft)($t(t.values,r)||$t(this.values,r))&&(s[r]=t.get(r)+this.get(r));return qe(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;const t={};for(const s of Object.keys(this.values))t[s]=to(e(this.values[s],s));return qe(this,{values:t},!0)}get(e){return this[te.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...Ln(e,te.normalizeUnit)};return qe(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:r,conversionAccuracy:s};return qe(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return Br(this.matrix,e),qe(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=Hr(this.normalize().shiftToAll().toObject());return qe(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>te.normalizeUnit(o));const t={},s={},r=this.toObject();let i;for(const o of ft)if(e.indexOf(o)>=0){i=o;let a=0;for(const c in s)a+=this.matrix[c][o]*s[c],s[c]=0;rt(r[o])&&(a+=r[o]);const l=Math.trunc(a);t[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else rt(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(t[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return Br(this.matrix,t),qe(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return qe(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=Hr(this.values);return qe(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of ft)if(!t(this.values[s],e.values[s]))return!1;return!0}}const Ot="Invalid Interval";function hc(n,e){return!n||!n.isValid?ce.invalid("missing or invalid start"):!e||!e.isValid?ce.invalid("missing or invalid end"):e<n?ce.invalid("end before start",`The end of an interval must be after its start, but you had start=${n.toISO()} and end=${e.toISO()}`):null}class ce{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new ge("need to specify a reason the Interval is invalid");const s=e instanceof $e?e:new $e(e,t);if(ue.throwOnInvalid)throw new Pa(s);return new ce({invalid:s})}static fromDateTimes(e,t){const s=zt(e),r=zt(t),i=hc(s,r);return i??new ce({start:s,end:r})}static after(e,t){const s=te.fromDurationLike(t),r=zt(e);return ce.fromDateTimes(r,r.plus(s))}static before(e,t){const s=te.fromDurationLike(t),r=zt(e);return ce.fromDateTimes(r.minus(s),r)}static fromISO(e,t){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=V.fromISO(s,t),o=i.isValid}catch{o=!1}let a,l;try{a=V.fromISO(r,t),l=a.isValid}catch{l=!1}if(o&&l)return ce.fromDateTimes(i,a);if(o){const c=te.fromISO(r,t);if(c.isValid)return ce.after(i,c)}else if(l){const c=te.fromISO(s,t);if(c.isValid)return ce.before(a,c)}}return ce.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",t){if(!this.isValid)return NaN;const s=this.start.startOf(e,t);let r;return t?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,t),Math.floor(r.diff(s,e).get(e))+(r.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?ce.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];const t=e.map(zt).filter(o=>this.contains(o)).sort((o,a)=>o.toMillis()-a.toMillis()),s=[];let{s:r}=this,i=0;for(;r<this.e;){const o=t[i]||this.e,a=+o>+this.e?this.e:o;s.push(ce.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const t=te.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(t.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(ce.fromDateTimes(s,i)),s=i,r+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const t=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return t>=s?null:ce.fromDateTimes(t,s)}union(e){if(!this.isValid)return this;const t=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return ce.fromDateTimes(t,s)}static merge(e){const[t,s]=e.sort((r,i)=>r.s-i.s).reduce(([r,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[r,i.union(o)]:[r.concat([i]),o]:[r,o],[[],null]);return s&&t.push(s),t}static xor(e){let t=null,s=0;const r=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((l,c)=>l.time-c.time);for(const l of a)s+=l.type==="s"?1:-1,s===1?t=l.time:(t&&+t!=+l.time&&r.push(ce.fromDateTimes(t,l.time)),t=null);return ce.merge(r)}difference(...e){return ce.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Ot}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=$n,t={}){return this.isValid?we.create(this.s.loc.clone(t),e).formatInterval(this):Ot}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Ot}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Ot}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Ot}toFormat(e,{separator:t=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Ot}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):te.invalid(this.invalidReason)}mapEndpoints(e){return ce.fromDateTimes(e(this.s),e(this.e))}}class fn{static hasDST(e=ue.defaultZone){const t=V.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return Ye.isValidZone(e)}static normalizeZone(e){return tt(e,ue.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||re.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||re.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||re.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||re.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return re.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return re.create(t,null,"gregory").eras(e)}static features(){return{relative:Ki(),localeWeek:Xi()}}}function Gr(n,e){const t=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(n);return Math.floor(te.fromMillis(s).as("days"))}function mc(n,e,t){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const u=Gr(l,c);return(u-u%7)/7}],["days",Gr]],r={},i=n;let o,a;for(const[l,c]of s)t.indexOf(l)>=0&&(o=l,r[l]=c(n,e),a=i.plus(r),a>e?(r[l]--,n=i.plus(r),n>e&&(a=n,r[l]--,n=i.plus(r))):n=a);return[n,r,a,o]}function pc(n,e,t,s){let[r,i,o,a]=mc(n,e,t);const l=e-r,c=t.filter(h=>["hours","minutes","seconds","milliseconds"].indexOf(h)>=0);c.length===0&&(o<e&&(o=r.plus({[a]:1})),o!==r&&(i[a]=(i[a]||0)+l/(o-r)));const u=te.fromObject(i,s);return c.length>0?te.fromMillis(l,s).shiftTo(...c).plus(u):u}const yc="missing Intl.DateTimeFormat.formatToParts support";function se(n,e=t=>t){return{regex:n,deser:([t])=>e(ol(t))}}const gc=" ",wo=`[ ${gc}]`,_o=new RegExp(wo,"g");function wc(n){return n.replace(/\./g,"\\.?").replace(_o,wo)}function Yr(n){return n.replace(/\./g,"").replace(_o," ").toLowerCase()}function Fe(n,e){return n===null?null:{regex:RegExp(n.map(wc).join("|")),deser:([t])=>n.findIndex(s=>Yr(t)===Yr(s))+e}}function Jr(n,e){return{regex:n,deser:([,t,s])=>Hn(t,s),groups:e}}function hn(n){return{regex:n,deser:([e])=>e}}function _c(n){return n.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Ec(n,e){const t=Ce(e),s=Ce(e,"{2}"),r=Ce(e,"{3}"),i=Ce(e,"{4}"),o=Ce(e,"{6}"),a=Ce(e,"{1,2}"),l=Ce(e,"{1,3}"),c=Ce(e,"{1,6}"),u=Ce(e,"{1,9}"),h=Ce(e,"{2,4}"),f=Ce(e,"{4,6}"),d=y=>({regex:RegExp(_c(y.val)),deser:([w])=>w,literal:!0}),O=(y=>{if(n.literal)return d(y);switch(y.val){case"G":return Fe(e.eras("short"),0);case"GG":return Fe(e.eras("long"),0);case"y":return se(c);case"yy":return se(h,Ms);case"yyyy":return se(i);case"yyyyy":return se(f);case"yyyyyy":return se(o);case"M":return se(a);case"MM":return se(s);case"MMM":return Fe(e.months("short",!0),1);case"MMMM":return Fe(e.months("long",!0),1);case"L":return se(a);case"LL":return se(s);case"LLL":return Fe(e.months("short",!1),1);case"LLLL":return Fe(e.months("long",!1),1);case"d":return se(a);case"dd":return se(s);case"o":return se(l);case"ooo":return se(r);case"HH":return se(s);case"H":return se(a);case"hh":return se(s);case"h":return se(a);case"mm":return se(s);case"m":return se(a);case"q":return se(a);case"qq":return se(s);case"s":return se(a);case"ss":return se(s);case"S":return se(l);case"SSS":return se(r);case"u":return hn(u);case"uu":return hn(a);case"uuu":return se(t);case"a":return Fe(e.meridiems(),0);case"kkkk":return se(i);case"kk":return se(h,Ms);case"W":return se(a);case"WW":return se(s);case"E":case"c":return se(t);case"EEE":return Fe(e.weekdays("short",!1),1);case"EEEE":return Fe(e.weekdays("long",!1),1);case"ccc":return Fe(e.weekdays("short",!0),1);case"cccc":return Fe(e.weekdays("long",!0),1);case"Z":case"ZZ":return Jr(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return Jr(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return hn(/[a-z_+-/]{1,256}?/i);case" ":return hn(/[^\S\n\r]/);default:return d(y)}})(n)||{invalidReason:yc};return O.token=n,O}const vc={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Oc(n,e,t){const{type:s,value:r}=n;if(s==="literal"){const l=/^\s+$/.test(r);return{literal:!l,val:l?" ":r}}const i=e[s];let o=s;s==="hour"&&(e.hour12!=null?o=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?o="hour12":o="hour24":o=t.hour12?"hour12":"hour24");let a=vc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function kc(n){return[`^${n.map(t=>t.regex).reduce((t,s)=>`${t}(${s.source})`,"")}$`,n]}function bc(n,e,t){const s=n.match(e);if(s){const r={};let i=1;for(const o in t)if($t(t,o)){const a=t[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function Sc(n){const e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let t=null,s;return G(n.z)||(t=Ye.create(n.z)),G(n.Z)||(t||(t=new _e(n.Z)),s=n.Z),G(n.q)||(n.M=(n.q-1)*3+1),G(n.h)||(n.h<12&&n.a===1?n.h+=12:n.h===12&&n.a===0&&(n.h=0)),n.G===0&&n.y&&(n.y=-n.y),G(n.u)||(n.S=Bs(n.u)),[Object.keys(n).reduce((i,o)=>{const a=e(o);return a&&(i[a]=n[o]),i},{}),t,s]}let ls=null;function Tc(){return ls||(ls=V.fromMillis(1555555555555)),ls}function Rc(n,e){if(n.literal)return n;const t=we.macroTokenToFormatOpts(n.val),s=ko(t,e);return s==null||s.includes(void 0)?n:s}function Eo(n,e){return Array.prototype.concat(...n.map(t=>Rc(t,e)))}class vo{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=Eo(we.parseFormat(t),e),this.units=this.tokens.map(s=>Ec(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=kc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[t,s]=bc(e,this.regex,this.handlers),[r,i,o]=s?Sc(s):[null,null,void 0];if($t(s,"a")&&$t(s,"H"))throw new St("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:s,result:r,zone:i,specificOffset:o}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function Oo(n,e,t){return new vo(n,t).explainFromTokens(e)}function Nc(n,e,t){const{result:s,zone:r,specificOffset:i,invalidReason:o}=Oo(n,e,t);return[s,r,i,o]}function ko(n,e){if(!n)return null;const s=we.create(e,n).dtFormatter(Tc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Oc(o,n,i))}const cs="Invalid DateTime",Qr=864e13;function Gt(n){return new $e("unsupported zone",`the zone "${n.name}" is not supported`)}function us(n){return n.weekData===null&&(n.weekData=Mn(n.c)),n.weekData}function ds(n){return n.localWeekData===null&&(n.localWeekData=Mn(n.c,n.loc.getMinDaysInFirstWeek(),n.loc.getStartOfWeek())),n.localWeekData}function ct(n,e){const t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new V({...t,...e,old:t})}function bo(n,e,t){let s=n-e*60*1e3;const r=t.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=t.offset(s);return r===i?[s,r]:[n-Math.min(r,i)*60*1e3,Math.max(r,i)]}function mn(n,e){n+=e*60*1e3;const t=new Date(n);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function wn(n,e,t){return bo(Bn(n),e,t)}function Kr(n,e){const t=n.o,s=n.c.year+Math.trunc(e.years),r=n.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...n.c,year:s,month:r,day:Math.min(n.c.day,Pn(s,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=te.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=Bn(i);let[l,c]=bo(a,t,n.zone);return o!==0&&(l+=o,c=n.zone.offset(l)),{ts:l,o:c}}function kt(n,e,t,s,r,i){const{setZone:o,zone:a}=t;if(n&&Object.keys(n).length!==0||e){const l=e||a,c=V.fromObject(n,{...t,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return V.invalid(new $e("unparsable",`the input "${r}" can't be parsed as ${s}`))}function pn(n,e,t=!0){return n.isValid?we.create(re.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(n,e):null}function fs(n,e,t){const s=n.c.year>9999||n.c.year<0;let r="";if(s&&n.c.year>=0&&(r+="+"),r+=he(n.c.year,s?6:4),t==="year")return r;if(e){if(r+="-",r+=he(n.c.month),t==="month")return r;r+="-"}else if(r+=he(n.c.month),t==="month")return r;return r+=he(n.c.day),r}function Xr(n,e,t,s,r,i,o){let a=!t||n.c.millisecond!==0||n.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=he(n.c.hour),o==="hour")break;if(e){if(l+=":",l+=he(n.c.minute),o==="minute")break;a&&(l+=":",l+=he(n.c.second))}else{if(l+=he(n.c.minute),o==="minute")break;a&&(l+=he(n.c.second))}if(o==="second")break;a&&(!s||n.c.millisecond!==0)&&(l+=".",l+=he(n.c.millisecond,3))}return r&&(n.isOffsetFixed&&n.offset===0&&!i?l+="Z":n.o<0?(l+="-",l+=he(Math.trunc(-n.o/60)),l+=":",l+=he(Math.trunc(-n.o%60))):(l+="+",l+=he(Math.trunc(n.o/60)),l+=":",l+=he(Math.trunc(n.o%60)))),i&&(l+="["+n.zone.ianaName+"]"),l}const So={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},xc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Dc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},_n=["year","month","day","hour","minute","second","millisecond"],Ic=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Ac=["year","ordinal","hour","minute","second","millisecond"];function En(n){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[n.toLowerCase()];if(!e)throw new bi(n);return e}function ei(n){switch(n.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return En(n)}}function Cc(n){if(Yt===void 0&&(Yt=ue.now()),n.type!=="iana")return n.offset(Yt);const e=n.name;let t=Ps.get(e);return t===void 0&&(t=n.offset(Yt),Ps.set(e,t)),t}function ti(n,e){const t=tt(e.zone,ue.defaultZone);if(!t.isValid)return V.invalid(Gt(t));const s=re.fromObject(e);let r,i;if(G(n.year))r=ue.now();else{for(const l of _n)G(n[l])&&(n[l]=So[l]);const o=Ji(n)||Qi(n);if(o)return V.invalid(o);const a=Cc(t);[r,i]=wn(n,a,t)}return new V({ts:r,zone:t,loc:s,o:i})}function ni(n,e,t){const s=G(t.round)?!0:t.round,r=G(t.rounding)?"trunc":t.rounding,i=(a,l)=>(a=Hs(a,s||t.calendary?0:2,t.calendary?"round":r),e.loc.clone(t).relFormatter(t).format(a,l)),o=a=>t.calendary?e.hasSame(n,a)?0:e.startOf(a).diff(n.startOf(a),a).get(a):e.diff(n,a).get(a);if(t.unit)return i(o(t.unit),t.unit);for(const a of t.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(n>e?-0:0,t.units[t.units.length-1])}function si(n){let e={},t;return n.length>0&&typeof n[n.length-1]=="object"?(e=n[n.length-1],t=Array.from(n).slice(0,n.length-1)):t=Array.from(n),[e,t]}let Yt;const Ps=new Map;class V{constructor(e){const t=e.zone||ue.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new $e("invalid input"):null)||(t.isValid?null:Gt(t));this.ts=G(e.ts)?ue.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[r,i]=[e.old.c,e.old.o];else{const a=rt(e.o)&&!e.old?e.o:t.offset(this.ts);r=mn(this.ts,a),s=Number.isNaN(r.year)?new $e("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=t,this.loc=e.loc||re.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new V({})}static local(){const[e,t]=si(arguments),[s,r,i,o,a,l,c]=t;return ti({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,t]=si(arguments),[s,r,i,o,a,l,c]=t;return e.zone=_e.utcInstance,ti({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){const s=dl(e)?e.valueOf():NaN;if(Number.isNaN(s))return V.invalid("invalid input");const r=tt(t.zone,ue.defaultZone);return r.isValid?new V({ts:s,zone:r,loc:re.fromObject(t)}):V.invalid(Gt(r))}static fromMillis(e,t={}){if(rt(e))return e<-Qr||e>Qr?V.invalid("Timestamp out of range"):new V({ts:e,zone:tt(t.zone,ue.defaultZone),loc:re.fromObject(t)});throw new ge(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(rt(e))return new V({ts:e*1e3,zone:tt(t.zone,ue.defaultZone),loc:re.fromObject(t)});throw new ge("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=tt(t.zone,ue.defaultZone);if(!s.isValid)return V.invalid(Gt(s));const r=re.fromObject(t),i=Ln(e,ei),{minDaysInFirstWeek:o,startOfWeek:a}=Ur(i,r),l=ue.now(),c=G(t.specificOffset)?s.offset(l):t.specificOffset,u=!G(i.ordinal),h=!G(i.year),f=!G(i.month)||!G(i.day),d=h||f,m=i.weekYear||i.weekNumber;if((d||u)&&m)throw new St("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(f&&u)throw new St("Can't mix ordinal dates with month/day");const O=m||i.weekday&&!d;let y,w,b=mn(l,c);O?(y=Ic,w=xc,b=Mn(b,o,a)):u?(y=Ac,w=Dc,b=as(b)):(y=_n,w=So);let N=!1;for(const g of y){const k=i[g];G(k)?N?i[g]=w[g]:i[g]=b[g]:N=!0}const p=O?ll(i,o,a):u?cl(i):Ji(i),T=p||Qi(i);if(T)return V.invalid(T);const C=O?Lr(i,o,a):u?Vr(i):i,[v,Z]=wn(C,c,s),x=new V({ts:v,zone:s,o:Z,loc:r});return i.weekday&&d&&e.weekday!==x.weekday?V.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${x.toISO()}`):x.isValid?x:V.invalid(x.invalid)}static fromISO(e,t={}){const[s,r]=ec(e);return kt(s,r,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,r]=tc(e);return kt(s,r,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,r]=nc(e);return kt(s,r,t,"HTTP",t)}static fromFormat(e,t,s={}){if(G(e)||G(t))throw new ge("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,u]=Nc(o,e,t);return u?V.invalid(u):kt(a,l,s,`format ${t}`,e,c)}static fromString(e,t,s={}){return V.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,r]=cc(e);return kt(s,r,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new ge("need to specify a reason the DateTime is invalid");const s=e instanceof $e?e:new $e(e,t);if(ue.throwOnInvalid)throw new Ma(s);return new V({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=ko(e,re.fromObject(t));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,t={}){return Eo(we.parseFormat(e),re.fromObject(t)).map(r=>r.val).join("")}static resetCache(){Yt=void 0,Ps.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?us(this).weekYear:NaN}get weekNumber(){return this.isValid?us(this).weekNumber:NaN}get weekday(){return this.isValid?us(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ds(this).weekday:NaN}get localWeekNumber(){return this.isValid?ds(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ds(this).weekYear:NaN}get ordinal(){return this.isValid?as(this.c).ordinal:NaN}get monthShort(){return this.isValid?fn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?fn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?fn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?fn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,t=6e4,s=Bn(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*t),a=this.zone.offset(s-i*t);if(o===a)return[this];const l=s-o*t,c=s-a*t,u=mn(l,o),h=mn(c,a);return u.hour===h.hour&&u.minute===h.minute&&u.second===h.second&&u.millisecond===h.millisecond?[ct(this,{ts:l}),ct(this,{ts:c})]:[this]}get isInLeapYear(){return an(this.year)}get daysInMonth(){return Pn(this.year,this.month)}get daysInYear(){return this.isValid?Nt(this.year):NaN}get weeksInWeekYear(){return this.isValid?nn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?nn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:t,numberingSystem:s,calendar:r}=we.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(_e.instance(e),t)}toLocal(){return this.setZone(ue.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=tt(e,ue.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(t||s){const i=e.offset(this.ts),o=this.toObject();[r]=wn(o,i,e)}return ct(this,{ts:r,zone:e})}else return V.invalid(Gt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return ct(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=Ln(e,ei),{minDaysInFirstWeek:s,startOfWeek:r}=Ur(t,this.loc),i=!G(t.weekYear)||!G(t.weekNumber)||!G(t.weekday),o=!G(t.ordinal),a=!G(t.year),l=!G(t.month)||!G(t.day),c=a||l,u=t.weekYear||t.weekNumber;if((c||o)&&u)throw new St("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new St("Can't mix ordinal dates with month/day");let h;i?h=Lr({...Mn(this.c,s,r),...t},s,r):G(t.ordinal)?(h={...this.toObject(),...t},G(t.day)&&(h.day=Math.min(Pn(h.year,h.month),h.day))):h=Vr({...as(this.c),...t});const[f,d]=wn(h,this.o,this.zone);return ct(this,{ts:f,o:d})}plus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e);return ct(this,Kr(this,t))}minus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e).negate();return ct(this,Kr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},r=te.normalizeUnit(e);switch(r){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(r==="weeks")if(t){const i=this.loc.getStartOfWeek(),{weekday:o}=this;o<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(r==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?we.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):cs}toLocaleString(e=$n,t={}){return this.isValid?we.create(this.loc.clone(t),e).formatDateTime(this):cs}toLocaleParts(e={}){return this.isValid?we.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=En(o);const a=e==="extended";let l=fs(this,a,o);return _n.indexOf(o)>=3&&(l+="T"),l+=Xr(this,a,t,s,r,i,o),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?fs(this,e==="extended",En(t)):null}toISOWeekDate(){return pn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=En(a),(r&&_n.indexOf(a)>=3?"T":"")+Xr(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return pn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return pn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?fs(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(t||e)&&(s&&(r+=" "),t?r+="z":e&&(r+="ZZ")),pn(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():cs}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",s={}){if(!this.isValid||!e.isValid)return te.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=fl(t).map(te.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=pc(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",t={}){return this.diff(V.now(),e,t)}until(e){return this.isValid?ce.fromDateTimes(this,e):this}hasSame(e,t,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,s)<=r&&r<=i.endOf(t,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const t=e.base||V.fromObject({},{zone:this.zone}),s=e.padding?this<t?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),ni(t,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?ni(e.base||V.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(V.isDateTime))throw new ge("min requires all arguments be DateTimes");return Wr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(V.isDateTime))throw new ge("max requires all arguments be DateTimes");return Wr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return Oo(o,e,t)}static fromStringExplain(e,t,s={}){return V.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:r=null}=t,i=re.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new vo(i,e)}static fromFormatParser(e,t,s={}){if(G(e)||G(t))throw new ge("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new ge(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:u}=t.explainFromTokens(e);return u?V.invalid(u):kt(a,l,s,`format ${t.format}`,e,c)}static get DATE_SHORT(){return $n}static get DATE_MED(){return Si}static get DATE_MED_WITH_WEEKDAY(){return Va}static get DATE_FULL(){return Ti}static get DATE_HUGE(){return Ri}static get TIME_SIMPLE(){return Ni}static get TIME_WITH_SECONDS(){return xi}static get TIME_WITH_SHORT_OFFSET(){return Di}static get TIME_WITH_LONG_OFFSET(){return Ii}static get TIME_24_SIMPLE(){return Ai}static get TIME_24_WITH_SECONDS(){return Ci}static get TIME_24_WITH_SHORT_OFFSET(){return Fi}static get TIME_24_WITH_LONG_OFFSET(){return $i}static get DATETIME_SHORT(){return Mi}static get DATETIME_SHORT_WITH_SECONDS(){return Pi}static get DATETIME_MED(){return Li}static get DATETIME_MED_WITH_SECONDS(){return Vi}static get DATETIME_MED_WITH_WEEKDAY(){return Ua}static get DATETIME_FULL(){return Ui}static get DATETIME_FULL_WITH_SECONDS(){return Wi}static get DATETIME_HUGE(){return ji}static get DATETIME_HUGE_WITH_SECONDS(){return Zi}}function zt(n){if(V.isDateTime(n))return n;if(n&&n.valueOf&&rt(n.valueOf()))return V.fromJSDate(n);if(n&&typeof n=="object")return V.fromObject(n);throw new ge(`Unknown datetime argument: ${n}, of type ${typeof n}`)}const Fc=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return rn(ye());n.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?t[r]=To(i)?.nullable():t[r]=ye()})}return Ue({Collection_Path:wt(ke()),...t})},$c=(n,e,t,s)=>{let r=Ue({}).catchall(Fc(n,e)),i;if(!s&&t){const o=Ie(n,t);i=qt(o.admin?.skipFormRequiredValidation)}return(!n.required||i)&&(r=r.optional()),r},Mc=()=>ye().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Must be a valid date"}),To=(n,e,t)=>{let s;const r=`${qt(n.description)}
|
|
2
2
|
|
|
3
|
-
`||"";let i,o,a;if(!t&&e){const l=Ie(n,e);i=l.admin?.condition?.form!==void 0&&!qt(l.admin.condition.form),o=qt(l.admin?.skipFormRequiredValidation),a=qt(l.admin?.image)}switch(n.type){case"String":s=ke(),n.length&&(s=s.length(n.length,`Must be ${n.length} character(s) long`)),n.minlength&&(s=s.min(n.minlength,`Must contain at least ${n.minlength} character(s)`)),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} character(s)`)),n.email?s=s.email("Must be a valid email address"):n.uuid?s=ve([s.uuid("Must be a valid UUID"),Oe("")]):n.url?s=ve([s.url("Must be a valid URL"),Oe("")]):n.emoji?s=ve([s.emoji("Must be a valid emoji"),Oe("")]):n.ip?s=ve([s.ip("Must be a valid IP address"),Oe("")]):n.pattern&&(!t&&a?s=ve([s.regex(new RegExp(n.pattern)),s.regex(/^blob:/)],{message:"Must be a valid value"}):s=s.regex(new RegExp(n.pattern),"Must be a valid value")),n.values&&(s=ve([An(n.values,{message:`Must be one of the following values: ${n.values.join(", ")}`}),ns()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=Kt(),r&&(s=s.describe(r.trim()));break;case"Number":n.autoIncrement?s=ve([ns(),dt().int()],{message:"Must be a valid number"}):(s=dt(),n.min&&(s=s.min(n.min,`Must be greater than or equal to ${n.min}`)),n.max&&(s=s.max(n.max,`Must be less than or equal to ${n.max}`)),n.decimal?t?s=s.describe(`${r}Must have ${n.decimal} decimal places`):s=s.refine(l=>n.decimal?(l.toString().split(".")[1]?.length||0)<=n.decimal:!1,{message:`Must have ${n.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),n.values?(t||(s=ve([s.refine(l=>n.values?.includes(l),{message:`Must be one of the following values: ${n.values.join(", ")}`}),ns()])),s=s.describe(`${r}Must be one of the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":t?(s=Ue({seconds:dt(),nanoseconds:dt()}),n.min&&n.max?s=s.describe(`${r}Must be between ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)} and ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`):n.min?s=s.describe(`${r}Must be greater than or equal to ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)}`):n.max?s=s.describe(`${r}Must be less than or equal to ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Lc(),n.min&&(s=s.refine(l=>l.toMillis()>=n.min,{message:`Must be greater than or equal to ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)}`})),n.max&&(s=s.refine(l=>l.toMillis()<=n.max,{message:`Must be less than or equal to ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`})));break;case"Array":s=wt(ye()),n.length&&(s=s.length(n.length,`Must contain ${n.length} item(s)`)),n.minlength?s=s.min(n.minlength,`Must contain at least ${n.minlength} item(s)`):n.required&&!i&&(s=s.nonempty("Must contain at least one item")),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} item(s)`)),n.values?(t||(s=s.refine(l=>{let c=!0;return l.forEach(u=>{n.values&&!n.values.includes(u)&&(c=!1)}),c},{message:`Must only contain the following values: ${n.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())),n.nullable&&(s=s.nullable());break;case"Map":n.required&&!i?t?s=Ue({}).catchall(ye()).describe(`${r}Must be an object. Must contain at least one object property.`):s=rn(ye()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=Ue({}).catchall(ye()).describe(`${r}Must be an object`);break;case"Computed":s=ye()}return(!n.required||i||o)&&(s=s.optional()),s},Vc=(n,e,t,s,r)=>{const{auth:i,softDelete:o}=n,a={};n.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(X(c)?(a[c.name]=Pc(c,e,t,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(u=>c.length&&u&&Object.keys(u).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(u=>c.min&&u&&Object.keys(u).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(u=>c.max&&(!u||Object.keys(u).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=ko(c,t,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=ve([Oe("create"),Oe("update"),Oe("delete")]).optional(),a.password=ke().optional(),a.passwordConfirm=ke().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=Kt().optional(),a[`operations-${c.labels.collection}`]=wt(ve([Oe("Read"),Oe("Create"),Oe("Update"),Oe("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=Kt().optional(),c.access.attributeRestrictions?.forEach(u=>{a[`attribute-${c.labels.collection}-${u.type}`]=Kt().optional()}),c.access.entityRestrictions?.restrictions?.forEach(u=>{if(u.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=Ue({}).catchall(ye()).optional()),u.type==="Parent"||u.type==="Parent_Property"){const h=W(c.fields,u.collectionField);a[`accessible-${c.labels.collection}-${h.collection}`]=Ue({}).catchall(ye()).optional()}})}));const l=Ue(a);return n.allowSchemalessFields?l.passthrough():l.strict()},ti=async(n,e)=>{if(n){const t=await ie(n,e);if(!t.valid)throw new Error(`VALIDATION_ERROR: ${t.message}`)}},sn=async(n,e,t,s,r,i)=>{await ti(s.custom?.preValidate,r);for(const a of s.fields)await ti(a.custom?.preValidate,r);return Ei(n,t,i).parse(e),e},Js=(n,e,t,s,r,i,o,a,l,c,u,h,f,d,m,O,y,w,b,N,p)=>{const{fields:T}=o;T.filter(g=>"unique"in g&&g.unique).forEach(g=>{n!=="delete"&&(typeof r[g.name]=="string"||typeof r[g.name]=="number")&&(e.set(d(g,r[g.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:t}),p&&p.size++)}),T.forEach(g=>{if(at(g,o,i)){const k=un(g,o,i),_={};r[g.name]!==void 0&&(_[g.name]=r[g.name],X(g)&&(_[`${g.name}_Array`]=r[`${g.name}_Array`])),k.forEach(A=>{r[A.name]!==void 0&&(X(A)?_[`${A.name}_Array`]=r[`${A.name}_Array`]:_[A.name]=r[A.name])}),Object.keys(_).length>0&&(n==="create"&&(_.Collection_Path=t,_.Collection_Path_String=t.join("/"),e.set(f(g),_)),n==="update"&&e.update(f(g),_),n==="delete"&&e.delete(f(g)),p&&p.size++)}});const C=l[o.labels.collection];for(const g of C){const k=la(g,o),_={...r};k.forEach(A=>{delete _[A.name],delete _[`${A.name}_Array`],delete _[`${A.name}_Single`],delete _[`${A.name}_Lowercase`]}),Object.keys(_).length>0&&(n==="create"&&(_.Collection_Path||=t,_.Collection_Path_String=t.join("/"),e.set(m(g.key),_)),n==="update"&&e.update(m(g.key),_),n==="delete"&&e.delete(m(g.key)),p&&p.size++)}const v=(g,k)=>{let _=1;at(k,g,i)&&_++,g.fields.forEach(E=>{at(E,g,i)&&JSON.parse(Xn(un(E,g,i))).includes(k.name)&&_++});const A=l[g.labels.collection];for(const E of A)E.fields.some(I=>I.name===k.name)&&X(k)&&_++;return _},Z=(g,k,_,A,E)=>{const I={};I[`${_.name}.${s}`]=h(),I[`${_.name}_Array`]=u(s),I[`${_.name}_Single`]=h(),e.update(O(E,A),I),at(_,k,i)&&e.update(y(g,_.name,A),{[`${_.name}.${s}`]:h(),[`${_.name}_Array`]:u(s)}),k.fields.forEach(M=>{at(M,k,i)&&JSON.parse(Xn(un(M,k,i))).includes(_.name)&&e.update(y(g,M.name,A),{[`${_.name}_Array`]:u(s)})});const R=l[k.labels.collection];for(const M of R)M.fields.some($=>$.name===_.name)&&X(_)&&e.update(w(g,M.key,A),I)};if(n==="delete")return;const x=T.filter(g=>X(g)&&g.twoWay);if(!a?.noTwoWay){for(const g of x){if(!p)throw new Error("VALIDATION_ERROR: batchSize is required");const k=i.collections[g.collection],_=W(k.fields,g.twoWay),A=ut(k,k.fields),E=Array.from(A).map(I=>I.name);if(!_)throw new Error(`SCHEMA_ERROR: Field ${g.twoWay} not found in collection ${g.collection}`);if(X(_)){if(r[`${g.name}_Array`])for(const[I,R]of Object.entries(r[g.name])){if(n==="update"&&b&&b[`${g.name}_Array`]?.includes(I))continue;const M={...b,...r};nt(M);const $={};_.includeFields&&_.includeFields.forEach(S=>{if(M[S]!==void 0){$[S]=M[S];const q=W(o.fields,S);gt(o,[q]).size===1&&($[`${S}_Lowercase`]=M[`${S}_Lowercase`])}});const P={[`${g.twoWay}.${s}`]:{Collection_Path:t,...$},[`${g.twoWay}_Array`]:c(s)};E.includes(_.name)&&(P[`${g.twoWay}_Single`]={Collection_Path:t,...$});const j=kn(r);e.update(O(R.Collection_Path,I),{...P,...j}),p.size++,at(_,k,i)&&(e.update(y(g,_.name,I),{[`${_.name}.${s}`]:{Collection_Path:t,...$},[`${_.name}_Array`]:c(s)}),p.size++),k.fields.forEach(S=>{if(at(S,k,i)){const q=JSON.parse(Xn(un(S,k,i))),B={};q.includes(_.name)&&(B[`${g.twoWay}_Array`]=c(s)),Object.keys(j).forEach(oe=>{q.includes(oe)&&(B[oe]=j[oe])}),Object.keys(B).length>0&&(e.update(y(g,S.name,I),B),p.size++)}});const K=l[k.labels.collection];for(const S of K)if(S.fields.some(q=>q.name===_.name)){const q={...P};Object.keys(j).forEach(B=>{S.fields.some(oe=>oe.name===B)&&(q[B]=j[B])}),Object.keys(q).length>0&&(e.update(w(g,S.key,I),q),p.size++)}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${_.type}`)}if(p&&p.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, roles, dependencies on the collection, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");for(const g of x){if(!p)throw new Error("VALIDATION_ERROR: batchSize is required");const k=i.collections[g.collection],_=W(k.fields,g.twoWay);if(!_)throw new Error(`SCHEMA_ERROR: Field ${g.twoWay} not found in collection ${g.collection}`);if(X(_)){if(n==="update"&&b&&!(r[g.name]&&Ne(r[g.name]))&&r[`${g.name}_Array`]&&b[`${g.name}_Array`]?.length>0)for(const[A,E]of Object.entries(b[g.name]))!r[`${g.name}_Array`].includes(A)&&!N?.get(g.name)?.includes(A)&&(p.size+=v(k,_),p.size<=500&&Z(g,k,_,A,E.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${_.type}`)}for(const g of x){if(!p)throw new Error("VALIDATION_ERROR: batchSize is required");const k=i.collections[g.collection],_=W(k.fields,g.twoWay);if(!_)throw new Error(`SCHEMA_ERROR: Field ${g.twoWay} not found in collection ${g.collection}`);if(X(_)){if(n==="update"&&b&&r[g.name]&&Ne(r[g.name])&&b[`${g.name}_Array`]?.length>0)for(const[A,E]of Object.entries(b[g.name]))N?.get(g.name)?.includes(A)||(p.size+=v(k,_),p.size<=500&&Z(g,k,_,A,E.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${_.type}`)}}},Le=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]===void 0?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&Le(n[e]))},Qs=n=>{if(n=n.toString(),/[/]|^\.+$|^__.*__$/.test(n))return!1;try{const s=new TextEncoder().encode(n),r=new TextDecoder().decode(s);if(n!==r)return!1}catch{return!1}return!(new Blob([n]).size>1500)},ni=async(n,e,t,s=1e3)=>{let r=5;for(;r>0;)try{await n(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Ln=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},fs=n=>n?Array.isArray(n)?n.map(s=>Ln(s)).filter(s=>s.length>0):Ln(n)||"":"",Uc=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g," ");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>998)throw new Error("Email subject is too long");return e},si=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
|
|
3
|
+
`||"";let i,o,a;if(!t&&e){const l=Ie(n,e);i=l.admin?.condition?.form!==void 0&&!qt(l.admin.condition.form),o=qt(l.admin?.skipFormRequiredValidation),a=qt(l.admin?.image)}switch(n.type){case"String":s=ke(),n.length&&(s=s.length(n.length,`Must be ${n.length} character(s) long`)),n.minlength&&(s=s.min(n.minlength,`Must contain at least ${n.minlength} character(s)`)),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} character(s)`)),n.email?s=s.email("Must be a valid email address"):n.uuid?s=ve([s.uuid("Must be a valid UUID"),Oe("")]):n.url?s=ve([s.url("Must be a valid URL"),Oe("")]):n.emoji?s=ve([s.emoji("Must be a valid emoji"),Oe("")]):n.ip?s=ve([s.ip("Must be a valid IP address"),Oe("")]):n.pattern&&(!t&&a?s=ve([s.regex(new RegExp(n.pattern)),s.regex(/^blob:/)],{message:"Must be a valid value"}):s=s.regex(new RegExp(n.pattern),"Must be a valid value")),n.values&&(s=ve([Cn(n.values,{message:`Must be one of the following values: ${n.values.join(", ")}`}),ss()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=Kt(),r&&(s=s.describe(r.trim()));break;case"Number":n.autoIncrement?s=ve([ss(),dt().int()],{message:"Must be a valid number"}):(s=dt(),n.min&&(s=s.min(n.min,`Must be greater than or equal to ${n.min}`)),n.max&&(s=s.max(n.max,`Must be less than or equal to ${n.max}`)),n.decimal?t?s=s.describe(`${r}Must have ${n.decimal} decimal places`):s=s.refine(l=>n.decimal?(l.toString().split(".")[1]?.length||0)<=n.decimal:!1,{message:`Must have ${n.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),n.values?(t||(s=ve([s.refine(l=>n.values?.includes(l),{message:`Must be one of the following values: ${n.values.join(", ")}`}),ss()])),s=s.describe(`${r}Must be one of the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":t?(s=Ue({seconds:dt(),nanoseconds:dt()}),n.min&&n.max?s=s.describe(`${r}Must be between ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)} and ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`):n.min?s=s.describe(`${r}Must be greater than or equal to ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)}`):n.max?s=s.describe(`${r}Must be less than or equal to ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Mc(),n.min&&(s=s.refine(l=>l.toMillis()>=n.min,{message:`Must be greater than or equal to ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)}`})),n.max&&(s=s.refine(l=>l.toMillis()<=n.max,{message:`Must be less than or equal to ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`})));break;case"Array":s=wt(ye()),n.length&&(s=s.length(n.length,`Must contain ${n.length} item(s)`)),n.minlength?s=s.min(n.minlength,`Must contain at least ${n.minlength} item(s)`):n.required&&!i&&(s=s.nonempty("Must contain at least one item")),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} item(s)`)),n.values?(t||(s=s.refine(l=>{let c=!0;return l.forEach(u=>{n.values&&!n.values.includes(u)&&(c=!1)}),c},{message:`Must only contain the following values: ${n.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())),n.nullable&&(s=s.nullable());break;case"Map":n.required&&!i?t?s=Ue({}).catchall(ye()).describe(`${r}Must be an object. Must contain at least one object property.`):s=rn(ye()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=Ue({}).catchall(ye()).describe(`${r}Must be an object`);break;case"Computed":s=ye()}return(!n.required||i||o)&&(s=s.optional()),s},Pc=(n,e,t,s,r)=>{const{auth:i,softDelete:o}=n,a={};n.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(X(c)?(a[c.name]=$c(c,e,t,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(u=>c.length&&u&&Object.keys(u).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(u=>c.min&&u&&Object.keys(u).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(u=>c.max&&(!u||Object.keys(u).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=To(c,t,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=ve([Oe("create"),Oe("update"),Oe("delete")]).optional(),a.password=ke().optional(),a.passwordConfirm=ke().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=Kt().optional(),a[`operations-${c.labels.collection}`]=wt(ve([Oe("Read"),Oe("Create"),Oe("Update"),Oe("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=Kt().optional(),c.access.attributeRestrictions?.forEach(u=>{a[`attribute-${c.labels.collection}-${u.type}`]=Kt().optional()}),c.access.entityRestrictions?.restrictions?.forEach(u=>{if(u.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=Ue({}).catchall(ye()).optional()),u.type==="Parent"||u.type==="Parent_Property"){const h=W(c.fields,u.collectionField);a[`accessible-${c.labels.collection}-${h.collection}`]=Ue({}).catchall(ye()).optional()}})}));const l=Ue(a);return n.allowSchemalessFields?l.passthrough():l.strict()},ri=async(n,e)=>{if(n){const t=await ie(n,e);if(!t.valid)throw new Error(`VALIDATION_ERROR: ${t.message}`)}},sn=async(n,e,t,s,r,i)=>{await ri(s.custom?.preValidate,r);for(const a of s.fields)await ri(a.custom?.preValidate,r);return ki(n,t,i).parse(e),e},Qs=(n,e,t,s,r,i,o,a,l,c,u,h,f,d,m,O,y,w,b,N,p)=>{const{fields:T}=o;T.filter(g=>"unique"in g&&g.unique).forEach(g=>{n!=="delete"&&(typeof r[g.name]=="string"||typeof r[g.name]=="number")&&(e.set(d(g,r[g.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:t}),p&&p.size++)}),T.forEach(g=>{if(at(g,o,i)){const k=un(g,o,i),_={};r[g.name]!==void 0&&(_[g.name]=r[g.name],X(g)&&(_[`${g.name}_Array`]=r[`${g.name}_Array`])),k.forEach(A=>{r[A.name]!==void 0&&(X(A)?_[`${A.name}_Array`]=r[`${A.name}_Array`]:_[A.name]=r[A.name])}),Object.keys(_).length>0&&(n==="create"&&(_.Collection_Path=t,_.Collection_Path_String=t.join("/"),e.set(f(g),_)),n==="update"&&e.update(f(g),_),n==="delete"&&e.delete(f(g)),p&&p.size++)}});const C=l[o.labels.collection];for(const g of C){const k=oa(g,o),_={...r};k.forEach(A=>{delete _[A.name],delete _[`${A.name}_Array`],delete _[`${A.name}_Single`],delete _[`${A.name}_Lowercase`]}),Object.keys(_).length>0&&(n==="create"&&(_.Collection_Path||=t,_.Collection_Path_String=t.join("/"),e.set(m(g.key),_)),n==="update"&&e.update(m(g.key),_),n==="delete"&&e.delete(m(g.key)),p&&p.size++)}const v=(g,k)=>{let _=1;at(k,g,i)&&_++,g.fields.forEach(E=>{at(E,g,i)&&JSON.parse(es(un(E,g,i))).includes(k.name)&&_++});const A=l[g.labels.collection];for(const E of A)E.fields.some(I=>I.name===k.name)&&X(k)&&_++;return _},Z=(g,k,_,A,E)=>{const I={};I[`${_.name}.${s}`]=h(),I[`${_.name}_Array`]=u(s),I[`${_.name}_Single`]=h(),e.update(O(E,A),I),at(_,k,i)&&e.update(y(g,_.name,A),{[`${_.name}.${s}`]:h(),[`${_.name}_Array`]:u(s)}),k.fields.forEach(M=>{at(M,k,i)&&JSON.parse(es(un(M,k,i))).includes(_.name)&&e.update(y(g,M.name,A),{[`${_.name}_Array`]:u(s)})});const R=l[k.labels.collection];for(const M of R)M.fields.some($=>$.name===_.name)&&X(_)&&e.update(w(g,M.key,A),I)};if(n==="delete")return;const x=T.filter(g=>X(g)&&g.twoWay);if(!a?.noTwoWay){for(const g of x){if(!p)throw new Error("VALIDATION_ERROR: batchSize is required");const k=i.collections[g.collection],_=W(k.fields,g.twoWay),A=ut(k,k.fields),E=Array.from(A).map(I=>I.name);if(!_)throw new Error(`SCHEMA_ERROR: Field ${g.twoWay} not found in collection ${g.collection}`);if(X(_)){if(r[`${g.name}_Array`])for(const[I,R]of Object.entries(r[g.name])){if(n==="update"&&b&&b[`${g.name}_Array`]?.includes(I))continue;const M={...b,...r};nt(M);const $={};_.includeFields&&_.includeFields.forEach(S=>{if(M[S]!==void 0){$[S]=M[S];const q=W(o.fields,S);gt(o,[q]).size===1&&($[`${S}_Lowercase`]=M[`${S}_Lowercase`])}});const P={[`${g.twoWay}.${s}`]:{Collection_Path:t,...$},[`${g.twoWay}_Array`]:c(s)};E.includes(_.name)&&(P[`${g.twoWay}_Single`]={Collection_Path:t,...$});const j=bn(r);e.update(O(R.Collection_Path,I),{...P,...j}),p.size++,at(_,k,i)&&(e.update(y(g,_.name,I),{[`${_.name}.${s}`]:{Collection_Path:t,...$},[`${_.name}_Array`]:c(s)}),p.size++),k.fields.forEach(S=>{if(at(S,k,i)){const q=JSON.parse(es(un(S,k,i))),B={};q.includes(_.name)&&(B[`${g.twoWay}_Array`]=c(s)),Object.keys(j).forEach(oe=>{q.includes(oe)&&(B[oe]=j[oe])}),Object.keys(B).length>0&&(e.update(y(g,S.name,I),B),p.size++)}});const K=l[k.labels.collection];for(const S of K)if(S.fields.some(q=>q.name===_.name)){const q={...P};Object.keys(j).forEach(B=>{S.fields.some(oe=>oe.name===B)&&(q[B]=j[B])}),Object.keys(q).length>0&&(e.update(w(g,S.key,I),q),p.size++)}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${_.type}`)}if(p&&p.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, roles, dependencies on the collection, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");for(const g of x){if(!p)throw new Error("VALIDATION_ERROR: batchSize is required");const k=i.collections[g.collection],_=W(k.fields,g.twoWay);if(!_)throw new Error(`SCHEMA_ERROR: Field ${g.twoWay} not found in collection ${g.collection}`);if(X(_)){if(n==="update"&&b&&!(r[g.name]&&Ne(r[g.name]))&&r[`${g.name}_Array`]&&b[`${g.name}_Array`]?.length>0)for(const[A,E]of Object.entries(b[g.name]))!r[`${g.name}_Array`].includes(A)&&!N?.get(g.name)?.includes(A)&&(p.size+=v(k,_),p.size<=500&&Z(g,k,_,A,E.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${_.type}`)}for(const g of x){if(!p)throw new Error("VALIDATION_ERROR: batchSize is required");const k=i.collections[g.collection],_=W(k.fields,g.twoWay);if(!_)throw new Error(`SCHEMA_ERROR: Field ${g.twoWay} not found in collection ${g.collection}`);if(X(_)){if(n==="update"&&b&&r[g.name]&&Ne(r[g.name])&&b[`${g.name}_Array`]?.length>0)for(const[A,E]of Object.entries(b[g.name]))N?.get(g.name)?.includes(A)||(p.size+=v(k,_),p.size<=500&&Z(g,k,_,A,E.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${_.type}`)}}},Le=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]===void 0?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&Le(n[e]))},Ks=n=>{if(n=n.toString(),/[/]|^\.+$|^__.*__$/.test(n))return!1;try{const s=new TextEncoder().encode(n),r=new TextDecoder().decode(s);if(n!==r)return!1}catch{return!1}return!(new Blob([n]).size>1500)},ii=async(n,e,t,s=1e3)=>{let r=5;for(;r>0;)try{await n(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Vn=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},hs=n=>n?Array.isArray(n)?n.map(s=>Vn(s)).filter(s=>s.length>0):Vn(n)||"":"",Lc=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g," ");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>998)throw new Error("Email subject is too long");return e},oi=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
|
|
4
4
|
|
|
5
5
|
`),e=e.replace(/\r\n/g,`
|
|
6
|
-
`),e.length>5e6)throw new Error("Email body is too long");return e},bo=async(n,e)=>{const t={};for(const s of e)t[s]=await import(`${n}/${s}.js`);return t};let hs,So,To,Ro,Jt,No,vn,On,ms=0;const St={getTenant(){return To},getMode(){return So},getTimezone(){return Ro},getGlobalConfigModule(){return pe(Jt)},getCustomizationFile(n,e){if(!Object.keys(e.collections).includes(n))throw new Error("PERMISSION_DENIED");const t=ra([n],No,"node",St);return pe(t?.[n])},getVersionInfo(){return vn},getMaintenanceInfo(){return On}},Wc=async(n,e,t,s,r)=>{if(hs&&!r)return St;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const i=process.env.STOKER_FB_WEB_APP_CONFIG,o=JSON.parse(i);To=e,So=n;const l=(await import(t)).default;Jt=l("node",St),!r&&n==="development"&&(process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099",process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000",process.env.FIRESTORE_EMULATOR_HOST="127.0.0.1:8080",process.env.FIREBASE_STORAGE_EMULATOR_HOST="127.0.0.1:9199");try{hs=Tt.getApp()}catch{hs=Tt.initializeApp({credential:Tt.applicationDefault(),databaseURL:o.databaseURL,storageBucket:o.storageBucket,projectId:o.projectId})}const c=await je();return No=await bo(s,Object.keys(c.collections)),Ro=await ie(Jt.timezone),H.getFirestore().collection("system_deployment").doc("maintenance_mode").onSnapshot(u=>{u.exists?(On=u.data(),ie(Jt.onMaintenanceUpdate,["node",On.active?"on":"off"])):console.error("Maintenance status not found")},u=>{console.error(u.message)}),H.getFirestore().collection("system_deployment").doc("latest_deploy").onSnapshot(u=>{u.exists?(vn=u.data(),ms++,ms>1&&ie(Jt.onVersionUpdate,["node",vn,ms])):console.error("Version info not found")},u=>{console.error(u.message)}),await new Promise(u=>{const h=()=>{On&&vn?u(St):setTimeout(h,100)};h()}),St},{getTenant:Ye,getMode:xo,getTimezone:Do,getGlobalConfigModule:Vt,getCustomizationFile:Je,getVersionInfo:ou,getMaintenanceInfo:au}=St,je=async(n=!1)=>{const s=await oi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(1).get(),r=Object.values(s.val())[0];if(n){for(const i of Object.values(r.collections))for(const o of i.fields)if(o.type==="Computed"){const a=Ie(o,Je(i.labels.collection,r));a.formula&&(o.formula=a.formula)}}else for(const i of Object.values(r.collections))i.fields=i.fields.filter(o=>o.type!=="Computed");return r},jc=async()=>{const t=await oi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(t.numChildren()<2))return Object.values(t.val())[0]},Te=(n,e,t)=>{let s=n.collection("tenants").doc(t);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},Io=(n,e,t,s,r)=>{const i=H.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=t.collections[o],{labels:l,fields:c,preloadCache:u}=a,h=Je(o,t),f=Te(i,e,n);if(r)if(s){const d=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const m=d&&Se("Read",d),O=ui(a,t,r),y=li(a,r),w=Ps(a,r),b=ci(a,t,r),N=(E=[])=>{const I=[],R=pi(r.Role,a,t);if(!R)throw new Error("PERMISSION_DENIED");if(m){let M=i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${R.key}`).where("Collection_Path_String","==",e.join("/"));E.forEach($=>{M=M.where(...$)}),I.push(M)}else if(O)for(const M of O){let $=i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${M.field}`).where("Collection_Path_String","==",e.join("/"));E.forEach(P=>{$=$.where(...P)}),I.push($)}return I},p=y.filter(E=>"operations"in E&&E.operations?E.operations.includes("Read"):!0);if(p.length===0&&w.length===0&&b.length===0)return N();let T=0;const C=E=>{E&&(T===0?T=E:T*=E)};if(p.length>0){for(const E of p)if(E.operations&&E.type==="Record_Property"){const I=E.roles.find(R=>R.role===r.Role);if(!I)throw new Error("PERMISSION_DENIED");C(I.values?.length)}}u?.roles.includes(r.Role)&&u.range&&C(u.range.fields.length);const v=h.admin?.statusField;v&&!u?.roles.includes(r.Role)&&C(Math.max(v.active?.length||0,v.archived?.length||0));const Z=T===0?30:Math.max(1,Math.floor(30/T)),x=[];p.filter(E=>E.type==="Record_Owner").forEach(()=>x.push(["Created_By","==",s])),p.filter(E=>E.type==="Record_User").forEach(E=>{if("collectionField"in E){const I=W(c,E.collectionField);x.push([`${I.name}_Array`,"array-contains",r.Doc_ID])}}),p.filter(E=>E.type==="Record_Property").forEach(E=>{if("propertyField"in E){const I=E.roles.find(M=>M.role===r.Role);if(!I)throw new Error("PERMISSION_DENIED");const R=W(c,E.propertyField);R.type==="Array"?x.push([`${R.name}_Array`,"array-contains-any",I.values]):x.push([R.name,"in",I.values])}});const g=[];w.filter(E=>E.type==="Individual").forEach(E=>{const I=d?.individualEntities,R=[];if(I){const M=E.singleQuery?E.singleQuery:Z;for(let $=0;$<I.length;$+=M){const P=I.slice($,$+M);R.push(P)}if(!E.singleQuery)R.forEach($=>{g.push(...N(x.concat([["id","in",$]])))});else{if(I.length>M)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${E.singleQuery} entities`);x.push(["id","in",I])}}}),b.filter(E=>E.parentFilter.type==="Individual").forEach(E=>{const{parentFilter:I,parentRestriction:R}=E;if("collectionField"in I){const M=W(c,I.collectionField);if("collection"in M){const $=r.collections?.[M.collection];if(!$)throw new Error("PERMISSION_DENIED");const P=$.individualEntities,j=[];if(P){const K=R.singleQuery?R.singleQuery:Z;for(let S=0;S<P.length;S+=K){const q=P.slice(S,S+K);j.push(q)}if(!R.singleQuery)j.forEach(S=>{g.push(...N(x.concat([[`${M.name}_Array`,"array-contains-any",S]])))});else{if(P.length>K)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${R.singleQuery} entities`);x.push([`${M.name}_Array`,"array-contains-any",P])}}}}});const k=[];w.filter(E=>E.type==="Parent").forEach(E=>{if("collectionField"in E){const I=W(c,E.collectionField);if("collection"in I){const R=d?.parentEntities,M=[];if(R){const $=E.singleQuery?E.singleQuery:Z;for(let P=0;P<R.length;P+=$){const j=R.slice(P,P+$);M.push(j)}if(!E.singleQuery)M.forEach(P=>{k.push(...N(x.concat([[`${I.name}_Array`,"array-contains-any",P]])))});else{if(R&&R.length>$)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${E.singleQuery} entities`);x.push([`${I.name}_Array`,"array-contains-any",R])}}}}}),b.filter(E=>E.parentFilter.type==="Parent").forEach(E=>{const{parentFilter:I,parentRestriction:R}=E;if("collectionField"in I&&"parentCollectionField"in I){const M=W(c,I.collectionField),$=W(c,I.parentCollectionField);if("collection"in M&&"collection"in $){const P=r.collections?.[M.collection];if(!P)throw new Error("PERMISSION_DENIED");const j=P.parentEntities,K=[];if(j){const S=R.singleQuery?R.singleQuery:Z;for(let q=0;q<j.length;q+=S){const B=j.slice(q,q+S);K.push(B)}if(!R.singleQuery)K.forEach(q=>{k.push(...N(x.concat([[`${$.name}_Array`,"array-contains-any",q]])))});else{if(j&&j.length>S)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${R.singleQuery} entities`);x.push([`${$.name}_Array`,"array-contains-any",j])}}}}});const _=[];k.length===0&&(w.filter(E=>E.type==="Parent_Property").forEach(E=>{if("collectionField"in E&&"propertyField"in E){const I=W(c,E.collectionField),R=W(c,E.propertyField);if("collection"in I){const M=d?.parentPropertyEntities||{};Object.entries(M).forEach(([$,P])=>{if(P.length>0){const j=[];for(let K=0;K<P.length;K+=Z){const S=P.slice(K,K+Z);j.push(S)}j.forEach(K=>{_.push(...N(x.concat([[`${I.name}_Array`,"array-contains-any",K],[R.name,"==",$]])))})}})}}}),b.filter(E=>E.parentFilter.type==="Parent_Property").forEach(E=>{const{parentFilter:I}=E;if("collectionField"in I&&"parentCollectionField"in I&&"parentPropertyField"in I){const R=W(c,I.collectionField),M=W(c,I.parentCollectionField),$=W(c,I.parentPropertyField);if("collection"in R&&"collection"in M){const P=r.collections?.[R.collection];if(!P)throw new Error("PERMISSION_DENIED");const j=P.parentPropertyEntities||{};Object.entries(j).forEach(([K,S])=>{if(S.length>0){const q=[];for(let B=0;B<S.length;B+=Z){const oe=S.slice(B,B+Z);q.push(oe)}q.forEach(B=>{_.push(...N(x.concat([[`${M.name}_Array`,"array-contains-any",B],[$.name,"==",K]])))})}})}}}));const A=[...g,...k,..._];return!w.length&&!b.length?N(x):A}else throw new Error("PERMISSION_DENIED");else return[f]},Ks=(n,e,t,s,r)=>{const i=H.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=s.collections[o],{labels:l}=a,c=Te(i,e,n);if(r){const u=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const h=u&&Se("Read",u),f=ui(a,s,r),d=[],m=pi(r.Role,a,s);if(!m)throw new Error("PERMISSION_DENIED");if(h)d.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${m.key}`).doc(t));else if(f)for(const O of f)d.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${O.field}`).doc(t));return d}else return[c.doc(t)]},Ao=async(n,e,t,s,r,i,o,a,l,c)=>{const u=t.at(-2),h=di(r.collections[u],r).map(m=>m.labels.collection);s.collections?s.collections.forEach(m=>{if(!h.includes(m))throw new Error(`SCHEMA_ERROR: Collection ${m} not found in subcollections of ${u}`)}):s.collections=h;const f=s.depth-1,d=s.collections.map(async m=>{const O=await er([...t,m],s.constraints,{user:a,pagination:s.limit,providedTransaction:l,noEmbeddingFields:c}).catch(y=>{throw y.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${m} for document at ${t.join("/")}`),y});e[m]=O.docs,i&&await Promise.all(e[m].map(y=>Xs(n,y,[...t,m,y.id],i,r,void 0,a,l,c))),f>0&&await Promise.all(e[m].map(y=>Ao(n,y,[...t,m,y.id],{depth:f},r,i,o,a,l,c)))});await Promise.all(d)},Xs=async(n,e,t,s,r,i,o,a,l)=>{const c=t.at(-2);s.fields||=r.collections[c].fields.filter(f=>X(f));const u=s.depth-1,h=[];for(const f of s.fields)if("collection"in f){const d=e[f.name];if(!d)continue;const m=Object.keys(d);for(const O of m){const y=d[O],w=Ge(y.Collection_Path,O,{user:o,providedTransaction:a,noEmbeddingFields:l}).then(b=>{if(d[O]=b,u>0)return Xs(n,d[O],[...y.Collection_Path,O],{depth:u},r,i,o,a,l)}).catch(b=>{if(b.message.includes("NOT_FOUND")||b.code==="permission-denied")delete d[O];else throw b});h.push(w)}}await Promise.all(h)},er=async(n,e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(t?.relations?.depth&&t.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");if(t?.pagination?.number!==void 0){const c=t.pagination.number;if(typeof c!="number"||!Number.isFinite(c)||!Number.isInteger(c)||c<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const s=Ye(),r=H.getFirestore();let i,o,a;const l=async c=>{const[u,h,f]=await Promise.all([t?.user?c.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(t.user)):Promise.resolve(Promise.resolve({})),c.get(r.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!h.exists)throw new Error("MAINTENANCE_MODE");if(h.data().active)throw new Error("MAINTENANCE_MODE");const m=f;let O;const y=Vt(),w=n.at(-1);if(!w)throw new Error("EMPTY_PATH");const b=Object.keys(m.collections).includes(w),N=y.disabledCollections?.includes(w);if(!b||N)throw new Error("COLLECTION_NOT_FOUND");const p=m.collections[w],{labels:T}=p,C=Je(T.collection,m);if(t?.user){if(!u?.exists)throw new Error("PERMISSION_DENIED");if(O=u.data(),!O.Role)throw new Error("USER_ERROR");if(!O.Enabled)throw new Error("PERMISSION_DENIED")}let v=Io(s,n,m,t?.user,O);if(v.length===0)return{cursor:{},pages:0,docs:[]};if(e&&(v=v.map(A=>(e.forEach(([E,I,R])=>{A=A.where(E,I,R)}),A))),o=t?.pagination?.startAfter||t?.pagination?.endBefore||{first:new Map,last:new Map},t?.pagination){if(t.pagination.startAfter&&t.pagination.endBefore)throw new Error("INPUT_ERROR: startAfter and endBefore cannot be provided together");const A=t.pagination.startAfter||t.pagination.endBefore;if(t?.user){const E=sa(O.Role,p,m);if(A&&E!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+E)}t.pagination.orderByField&&t.pagination.orderByDirection?!t.pagination.startAfter&&!t.pagination.endBefore?v=v.map(E=>E.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).limit(t.pagination.number)):t.pagination.startAfter?v=v.map((E,I)=>E.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).startAfter(o.last.get(I)).limit(t.pagination.number)):v=v.map((E,I)=>E.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).endBefore(o.first.get(I)).limitToLast(t.pagination.number)):!t.pagination.startAfter&&!t.pagination.endBefore?v=v.map(E=>E.limit(t.pagination.number)):t.pagination.startAfter?v=v.map((E,I)=>E.startAfter(o.last.get(I)).limit(t.pagination.number)):v=v.map((E,I)=>E.endBefore(o.first.get(I)).limitToLast(t.pagination.number))}const Z={};await le("preOperation",y,C,["read",void 0,void 0,Z]),await le("preRead",y,C,[Z,v,!0,!1]),a=new Map;const k=v.map(async A=>await c.get(A)),_=await Promise.all(k);for(const A of _){for(const E of A.docs){a.has(E.id)||a.set(E.id,{});const I=E.data(),R=a.get(E.id);R.id||=E.id;const M={...R,...I};delete M.Collection_Path_String,a.set(E.id,M)}o.first.set(_.indexOf(A),A.docs[0]),o.last.set(_.indexOf(A),A.docs.at(-1)||A.docs[0])}if(t?.pagination){let A=v[0];e&&(A=e.reduce((M,[$,P,j])=>M.where($,P,j),A)),t.pagination.orderByField&&t.pagination.orderByDirection&&(A=A.orderBy(t.pagination.orderByField,t.pagination.orderByDirection));const I=(await A.count().get()).data().count,R=t.pagination.number;i=R>0?Math.ceil(I/R):0}for(const A of a.values()){const E=[],I=[...A.Collection_Path,A.id];t?.subcollections&&E.push(Ao(s,a.get(A.id),I,pe(t.subcollections),m,pe(t?.relations),void 0,t.user,t.transactional?c:void 0,t?.noEmbeddingFields)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map($=>{if(typeof $=="string"){const P=p.fields.find(j=>j.name===$);if(P)return P;throw new Error(`SCHEMA_ERROR: Field ${$} not found in collection ${w}`)}return $})),E.push(Xs(s,a.get(A.id),I,pe(t.relations),m,void 0,t.user,t.transactional?c:void 0,t?.noEmbeddingFields))),await Promise.all(E);for(const $ of a.values())for(const P of p.fields){if(P.type==="Computed"){const j=Ie(P,C);if(!j.formula)continue;$[P.name]=await j.formula($)}t?.noEmbeddingFields&&P.type==="Embedding"&&delete $[P.name]}if(t?.user&&O?.Role){const $=O.Role;if(!(C.custom?.serverAccess?.read!==void 0?await ie(C.custom.serverAccess.read,[$,A]):!0)){a.delete(A.id);continue}for(const j of p.fields){const K=!j.access||j.access.includes($),S=Ie(j,C),q=S?.custom?.serverAccess?.read!==void 0?await ie(S.custom.serverAccess.read,[$,A]):!0;(!K||!q)&&(X(j)?(delete a.get(A.id)[j.name],delete a.get(A.id)[`${j.name}_Array`],delete a.get(A.id)[`${j.name}_Single`]):delete a.get(A.id)[j.name])}}const R=["read",A,A.id,Z];await le("postOperation",y,C,R),await le("postRead",y,C,[Z,v,A,!1])}t?.user&&await ta(Array.from(a.values()),p,m,t.user,O)};return t?.providedTransaction?await l(t.providedTransaction):await r.runTransaction(async c=>{await l(c)},{readOnly:!0}),{cursor:o,pages:i,docs:Array.from(a.values())}},Co=async(n,e,t,s,r,i,o,a)=>{const l=s.at(-2),c=di(i.collections[l],i).map(f=>f.labels.collection);r.collections?r.collections.forEach(f=>{if(!c.includes(f))throw new Error(`SCHEMA_ERROR: Collection ${f} not found in subcollections of ${l}`)}):r.collections=c;const u=r.depth-1,h=r.collections.map(async f=>{const d=await er([...s,f],r.constraints||[],{user:a,relations:o,pagination:r.limit,providedTransaction:e}).catch(m=>{throw m.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${f} for document at ${s.join("/")}`),m});t[f]=d.docs,u>0&&await Promise.all(t[f].map(async m=>{await Co(n,e,m,[...s,f,m.id],{depth:u},i,o,a)}))});await Promise.all(h)},Fo=async(n,e,t,s,r,i,o,a,l)=>{const c=s.at(-2);i.fields||=r.collections[c].fields.filter(f=>X(f));const u=i.depth-1,h=[];for(const f of i.fields)if("collection"in f){const d=t[f.name];if(!d)continue;for(const[m,O]of Object.entries(d)){const y=Ge(O.Collection_Path,m,{user:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(w=>{if(d[m]=w,u>0)return Fo(n,e,d[m],[...O.Collection_Path,m],r,{depth:u},o,a,l)}).catch(w=>{if(w.message.includes("NOT_FOUND")||w.code==="permission-denied")delete d[m];else throw w});h.push(y)}}await Promise.all(h)},Ge=async(n,e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(t?.relations?.depth&&t.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=Ye(),r=H.getFirestore();let i;const o=async a=>{const[l,c,u]=await Promise.all([t?.user?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(t.user)):Promise.resolve(Promise.resolve({})),a.get(r.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!c.exists)throw new Error("MAINTENANCE_MODE");if(c.data().active)throw new Error("MAINTENANCE_MODE");const f=u;let d;const m=Vt(),O=n.at(-1);if(!O)throw new Error("EMPTY_PATH");const y=Object.keys(f.collections).includes(O),w=m.disabledCollections?.includes(O);if(!y||w)throw new Error("COLLECTION_NOT_FOUND");const b=f.collections[O],{labels:N}=b,p=Je(N.collection,f);let T;if(t?.user){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(d=l.data(),!d.Role)throw new Error("USER_ERROR");if(!d.Enabled)throw new Error("PERMISSION_DENIED");if(T=d.collections?.[N.collection],!T)throw new Error("PERMISSION_DENIED")}if(t?.user&&(!T||!Se("Read",T)))throw new Error("PERMISSION_DENIED");const C=Ks(s,n,e,f,d);if(C.length===0)throw new Error("PERMISSION_DENIED");const v={};await le("preOperation",m,p,["read",void 0,e,v]),await le("preRead",m,p,[v,C,!1,!1]),i={};const g=C.map(R=>a.get(R)),k=await Promise.all(g);for(const R of k)if(R.exists){const M=R.data();i.id||=R.id,i={...i,...M},delete i.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${n?.join("/")||N.collection}`);const _=[],A=n?[...n,e]:[N.collection,e];if(t?.subcollections&&_.push(Co(s,a,i,A,t.subcollections,f,void 0,t.user)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(R=>{if(typeof R=="string"){const M=b.fields.find($=>$.name===R);if(M)return M;throw new Error(`SCHEMA_ERROR: Field ${R} not found in collection ${O}`)}return R})),_.push(Fo(s,a,i,A,f,t.relations,t.user,t.noComputedFields,t.noEmbeddingFields))),await Promise.all(_),!t?.noComputedFields){for(const R of b.fields)if(R.type==="Computed"){const M=Ie(R,p);if(!M.formula)continue;i[R.name]=await M.formula(i)}}if(t?.noEmbeddingFields)for(const R of b.fields)R.type==="Embedding"&&delete i[R.name];if(t?.user&&d?.Role){const R=d.Role;if(!(p.custom?.serverAccess?.read!==void 0?await ie(p.custom?.serverAccess?.read,[R,i]):!0))throw new Error("PERMISSION_DENIED");for(const $ of b.fields){const P=!$.access||$.access.includes(R),j=Ie($,p),K=j?.custom?.serverAccess?.read!==void 0?await ie(j.custom.serverAccess.read,[R,i]):!0;(!P||!K)&&(X($)?(delete i[$.name],delete i[`${$.name}_Array`],delete i[`${$.name}_Single`]):delete i[$.name])}}await le("postOperation",m,p,["read",i,e,v]),await le("postRead",m,p,[v,C,i,!1]),t?.user&&await ea(i,b,f,t.user,d)};return t?.providedTransaction?await o(t.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},$o=async(n,e,t,s,r,i,o,a)=>{const l=H.getFirestore(),c=Je(r.labels.collection,i),u=r.labels.collection,h=r.fields.filter(d=>"unique"in d&&d.unique),f=[];if(await Promise.all(h.map(async d=>{{if(s[d.name]===void 0||Ne(s[d.name]))return;Ie(d,c);const m=s[d.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(!Qs(m))f.push(`${d.name} "${s[d.name]}" is invalid`);else{const O=await l.collection("tenants").doc(e).collection("system_unique").doc(u).collection(`Unique-${u}-${d.name}`).doc(m).get();O.exists&&!(n==="update"&&O.data().id===t)&&f.push(`${d.name} "${s[d.name]}" already exists`)}}})),f.length>0)throw new Error(f.join(", "))},pt=async(n,e,t,s,r,i,o,a,l)=>{const{labels:c}=o,u=H.getFirestore(),h=Vt(),f=await ie(h.firebase?.writeLogTTL),d={operation:n,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_App:t.Last_Write_App,Last_Write_Version:t.Last_Write_Version,data:{}};if(f){const w=new Date,b=new Date(new Date().setDate(w.getDate()+f));d.TTL=H.Timestamp.fromDate(b)}const m=pe(t);nt(m),n!=="delete"&&(d.data.data=pe(m)),n==="update"&&(d.data.originalRecord=pe(l)),n!=="delete"&&["started","written"].includes(e)&&(delete d.data.data.Saved_At,delete d.data.data.Last_Save_At),e==="failed"&&(d.data.error=JSON.stringify(a));const O=Te(u,r,s),y=t.Last_Write_At;await O.doc(i).collection("system_write_log").doc(`${t.Last_Write_By}-${y.valueOf()}`).set(d)},Ut=async n=>{const e=Ye(),t=yt.getAuth(),s=H.getFirestore(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(n.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
|
|
6
|
+
`),e.length>5e6)throw new Error("Email body is too long");return e},Ro=async(n,e)=>{const t={};for(const s of e)t[s]=await import(`${n}/${s}.js`);return t};let ms,No,vn,xo,Jt,Do,On,kn,ps=0;const Tt={getTenant(){if(!vn)throw new Error("Tenant not provided");return vn},setTenant(n){vn=n},getMode(){return No},getTimezone(){return xo},getGlobalConfigModule(){return pe(Jt)},getCustomizationFile(n,e){if(!Object.keys(e.collections).includes(n))throw new Error("PERMISSION_DENIED");const t=na([n],Do,"node",Tt);return pe(t?.[n])},getVersionInfo(){return On},getMaintenanceInfo(){return kn}},Vc=async(n,e,t,s,r)=>{if(e&&(vn=e),No=n,ms&&!r)return Tt;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const i=process.env.STOKER_FB_WEB_APP_CONFIG,o=JSON.parse(i),l=(await import(t)).default;Jt=l("node",Tt),!r&&n==="development"&&(process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099",process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000",process.env.FIRESTORE_EMULATOR_HOST="127.0.0.1:8080",process.env.FIREBASE_STORAGE_EMULATOR_HOST="127.0.0.1:9199");let c=!1;try{ms=Rt.getApp(),c=!0}catch{ms=Rt.initializeApp({credential:Rt.applicationDefault(),databaseURL:o.databaseURL,storageBucket:o.storageBucket,projectId:o.projectId})}const u=await je();return Do=await Ro(s,Object.keys(u.collections)),xo=await ie(Jt.timezone),c||H.getFirestore().collection("system_deployment").doc("maintenance_mode").onSnapshot(h=>{h.exists?(kn=h.data(),ie(Jt.onMaintenanceUpdate,["node",kn.active?"on":"off"])):console.error("Maintenance status not found")},h=>{console.error(h.message)}),c||H.getFirestore().collection("system_deployment").doc("latest_deploy").onSnapshot(h=>{h.exists?(On=h.data(),ps++,ps>1&&ie(Jt.onVersionUpdate,["node",On,ps])):console.error("Version info not found")},h=>{console.error(h.message)}),await new Promise(h=>{const f=()=>{kn&&On?h(Tt):setTimeout(f,100)};f()}),Tt},{getTenant:Ze,setTenant:Uc,getMode:Xs,getTimezone:er,getGlobalConfigModule:Et,getCustomizationFile:ze,getVersionInfo:Wc,getMaintenanceInfo:jc}=Tt,Zc=async(n,e,t,s)=>new Promise((r,i)=>{const o=zo.spawn(n,e,{cwd:t||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},u=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout.on("data",h=>{a+=h.toString(),console.log(h.toString())}),o.stderr.on("data",h=>{console.log(h.toString())}),o.on("exit",h=>{u(),h===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),zc=async()=>{const n=process.env.STOKER_FB_WEB_APP_CONFIG;if(!n)throw new Error("Firebase web app config not found");const e=JSON.parse(n);try{return Rt.getApp()}catch{return Rt.initializeApp({credential:Rt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},je=async(n=!1)=>{const s=await ci.getDatabase().ref("schema").orderByChild("published_time").limitToLast(1).get(),r=Object.values(s.val())[0];if(n){for(const i of Object.values(r.collections))for(const o of i.fields)if(o.type==="Computed"){const a=Ie(o,ze(i.labels.collection,r));a.formula&&(o.formula=a.formula)}}else for(const i of Object.values(r.collections))i.fields=i.fields.filter(o=>o.type!=="Computed");return r},qc=async()=>{const t=await ci.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(t.numChildren()<2))return Object.values(t.val())[0]},Te=(n,e,t)=>{let s=n.collection("tenants").doc(t);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},Io=(n,e,t,s,r)=>{const i=H.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=t.collections[o],{labels:l,fields:c,preloadCache:u}=a,h=ze(o,t),f=Te(i,e,n);if(r)if(s){const d=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const m=d&&Se("Read",d),O=hi(a,t,r),y=di(a,r),w=Ls(a,r),b=fi(a,t,r),N=(E=[])=>{const I=[],R=wi(r.Role,a,t);if(!R)throw new Error("PERMISSION_DENIED");if(m){let M=i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${R.key}`).where("Collection_Path_String","==",e.join("/"));E.forEach($=>{M=M.where(...$)}),I.push(M)}else if(O)for(const M of O){let $=i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${M.field}`).where("Collection_Path_String","==",e.join("/"));E.forEach(P=>{$=$.where(...P)}),I.push($)}return I},p=y.filter(E=>"operations"in E&&E.operations?E.operations.includes("Read"):!0);if(p.length===0&&w.length===0&&b.length===0)return N();let T=0;const C=E=>{E&&(T===0?T=E:T*=E)};if(p.length>0){for(const E of p)if(E.operations&&E.type==="Record_Property"){const I=E.roles.find(R=>R.role===r.Role);if(!I)throw new Error("PERMISSION_DENIED");C(I.values?.length)}}u?.roles.includes(r.Role)&&u.range&&C(u.range.fields.length);const v=h.admin?.statusField;v&&!u?.roles.includes(r.Role)&&C(Math.max(v.active?.length||0,v.archived?.length||0));const Z=T===0?30:Math.max(1,Math.floor(30/T)),x=[];p.filter(E=>E.type==="Record_Owner").forEach(()=>x.push(["Created_By","==",s])),p.filter(E=>E.type==="Record_User").forEach(E=>{if("collectionField"in E){const I=W(c,E.collectionField);x.push([`${I.name}_Array`,"array-contains",r.Doc_ID])}}),p.filter(E=>E.type==="Record_Property").forEach(E=>{if("propertyField"in E){const I=E.roles.find(M=>M.role===r.Role);if(!I)throw new Error("PERMISSION_DENIED");const R=W(c,E.propertyField);R.type==="Array"?x.push([`${R.name}_Array`,"array-contains-any",I.values]):x.push([R.name,"in",I.values])}});const g=[];w.filter(E=>E.type==="Individual").forEach(E=>{const I=d?.individualEntities,R=[];if(I){const M=E.singleQuery?E.singleQuery:Z;for(let $=0;$<I.length;$+=M){const P=I.slice($,$+M);R.push(P)}if(!E.singleQuery)R.forEach($=>{g.push(...N(x.concat([["id","in",$]])))});else{if(I.length>M)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${E.singleQuery} entities`);x.push(["id","in",I])}}}),b.filter(E=>E.parentFilter.type==="Individual").forEach(E=>{const{parentFilter:I,parentRestriction:R}=E;if("collectionField"in I){const M=W(c,I.collectionField);if("collection"in M){const $=r.collections?.[M.collection];if(!$)throw new Error("PERMISSION_DENIED");const P=$.individualEntities,j=[];if(P){const K=R.singleQuery?R.singleQuery:Z;for(let S=0;S<P.length;S+=K){const q=P.slice(S,S+K);j.push(q)}if(!R.singleQuery)j.forEach(S=>{g.push(...N(x.concat([[`${M.name}_Array`,"array-contains-any",S]])))});else{if(P.length>K)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${R.singleQuery} entities`);x.push([`${M.name}_Array`,"array-contains-any",P])}}}}});const k=[];w.filter(E=>E.type==="Parent").forEach(E=>{if("collectionField"in E){const I=W(c,E.collectionField);if("collection"in I){const R=d?.parentEntities,M=[];if(R){const $=E.singleQuery?E.singleQuery:Z;for(let P=0;P<R.length;P+=$){const j=R.slice(P,P+$);M.push(j)}if(!E.singleQuery)M.forEach(P=>{k.push(...N(x.concat([[`${I.name}_Array`,"array-contains-any",P]])))});else{if(R&&R.length>$)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${E.singleQuery} entities`);x.push([`${I.name}_Array`,"array-contains-any",R])}}}}}),b.filter(E=>E.parentFilter.type==="Parent").forEach(E=>{const{parentFilter:I,parentRestriction:R}=E;if("collectionField"in I&&"parentCollectionField"in I){const M=W(c,I.collectionField),$=W(c,I.parentCollectionField);if("collection"in M&&"collection"in $){const P=r.collections?.[M.collection];if(!P)throw new Error("PERMISSION_DENIED");const j=P.parentEntities,K=[];if(j){const S=R.singleQuery?R.singleQuery:Z;for(let q=0;q<j.length;q+=S){const B=j.slice(q,q+S);K.push(B)}if(!R.singleQuery)K.forEach(q=>{k.push(...N(x.concat([[`${$.name}_Array`,"array-contains-any",q]])))});else{if(j&&j.length>S)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${R.singleQuery} entities`);x.push([`${$.name}_Array`,"array-contains-any",j])}}}}});const _=[];k.length===0&&(w.filter(E=>E.type==="Parent_Property").forEach(E=>{if("collectionField"in E&&"propertyField"in E){const I=W(c,E.collectionField),R=W(c,E.propertyField);if("collection"in I){const M=d?.parentPropertyEntities||{};Object.entries(M).forEach(([$,P])=>{if(P.length>0){const j=[];for(let K=0;K<P.length;K+=Z){const S=P.slice(K,K+Z);j.push(S)}j.forEach(K=>{_.push(...N(x.concat([[`${I.name}_Array`,"array-contains-any",K],[R.name,"==",$]])))})}})}}}),b.filter(E=>E.parentFilter.type==="Parent_Property").forEach(E=>{const{parentFilter:I}=E;if("collectionField"in I&&"parentCollectionField"in I&&"parentPropertyField"in I){const R=W(c,I.collectionField),M=W(c,I.parentCollectionField),$=W(c,I.parentPropertyField);if("collection"in R&&"collection"in M){const P=r.collections?.[R.collection];if(!P)throw new Error("PERMISSION_DENIED");const j=P.parentPropertyEntities||{};Object.entries(j).forEach(([K,S])=>{if(S.length>0){const q=[];for(let B=0;B<S.length;B+=Z){const oe=S.slice(B,B+Z);q.push(oe)}q.forEach(B=>{_.push(...N(x.concat([[`${M.name}_Array`,"array-contains-any",B],[$.name,"==",K]])))})}})}}}));const A=[...g,...k,..._];return!w.length&&!b.length?N(x):A}else throw new Error("PERMISSION_DENIED");else return[f]},tr=(n,e,t,s,r)=>{const i=H.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=s.collections[o],{labels:l}=a,c=Te(i,e,n);if(r){const u=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const h=u&&Se("Read",u),f=hi(a,s,r),d=[],m=wi(r.Role,a,s);if(!m)throw new Error("PERMISSION_DENIED");if(h)d.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${m.key}`).doc(t));else if(f)for(const O of f)d.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${O.field}`).doc(t));return d}else return[c.doc(t)]},Ao=async(n,e,t,s,r,i,o,a,l,c)=>{const u=t.at(-2),h=mi(r.collections[u],r).map(m=>m.labels.collection);s.collections?s.collections.forEach(m=>{if(!h.includes(m))throw new Error(`SCHEMA_ERROR: Collection ${m} not found in subcollections of ${u}`)}):s.collections=h;const f=s.depth-1,d=s.collections.map(async m=>{const O=await sr([...t,m],s.constraints,{user:a,pagination:s.limit,providedTransaction:l,noEmbeddingFields:c}).catch(y=>{throw y.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${m} for document at ${t.join("/")}`),y});e[m]=O.docs,i&&await Promise.all(e[m].map(y=>nr(n,y,[...t,m,y.id],i,r,void 0,a,l,c))),f>0&&await Promise.all(e[m].map(y=>Ao(n,y,[...t,m,y.id],{depth:f},r,i,o,a,l,c)))});await Promise.all(d)},nr=async(n,e,t,s,r,i,o,a,l)=>{const c=t.at(-2);s.fields||=r.collections[c].fields.filter(f=>X(f));const u=s.depth-1,h=[];for(const f of s.fields)if("collection"in f){const d=e[f.name];if(!d)continue;const m=Object.keys(d);for(const O of m){const y=d[O],w=Je(y.Collection_Path,O,{user:o,providedTransaction:a,noEmbeddingFields:l}).then(b=>{if(d[O]=b,u>0)return nr(n,d[O],[...y.Collection_Path,O],{depth:u},r,i,o,a,l)}).catch(b=>{if(b.message.includes("NOT_FOUND")||b.code==="permission-denied")delete d[O];else throw b});h.push(w)}}await Promise.all(h)},sr=async(n,e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(t?.relations?.depth&&t.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");if(t?.pagination?.number!==void 0){const c=t.pagination.number;if(typeof c!="number"||!Number.isFinite(c)||!Number.isInteger(c)||c<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const s=Ze(),r=H.getFirestore();let i,o,a;const l=async c=>{const[u,h,f]=await Promise.all([t?.user?c.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(t.user)):Promise.resolve(Promise.resolve({})),c.get(r.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!h.exists)throw new Error("MAINTENANCE_MODE");if(h.data().active)throw new Error("MAINTENANCE_MODE");const m=f;let O;const y=Et(),w=n.at(-1);if(!w)throw new Error("EMPTY_PATH");const b=Object.keys(m.collections).includes(w),N=y.disabledCollections?.includes(w);if(!b||N)throw new Error("COLLECTION_NOT_FOUND");const p=m.collections[w],{labels:T}=p,C=ze(T.collection,m);if(t?.user){if(!u?.exists)throw new Error("PERMISSION_DENIED");if(O=u.data(),!O.Role)throw new Error("USER_ERROR");if(!O.Enabled)throw new Error("PERMISSION_DENIED")}let v=Io(s,n,m,t?.user,O);if(v.length===0)return{cursor:{},pages:0,docs:[]};if(e&&(v=v.map(A=>(e.forEach(([E,I,R])=>{A=A.where(E,I,R)}),A))),o=t?.pagination?.startAfter||t?.pagination?.endBefore||{first:new Map,last:new Map},t?.pagination){if(t.pagination.startAfter&&t.pagination.endBefore)throw new Error("INPUT_ERROR: startAfter and endBefore cannot be provided together");const A=t.pagination.startAfter||t.pagination.endBefore;if(t?.user){const E=ta(O.Role,p,m);if(A&&E!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+E)}t.pagination.orderByField&&t.pagination.orderByDirection?!t.pagination.startAfter&&!t.pagination.endBefore?v=v.map(E=>E.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).limit(t.pagination.number)):t.pagination.startAfter?v=v.map((E,I)=>E.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).startAfter(o.last.get(I)).limit(t.pagination.number)):v=v.map((E,I)=>E.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).endBefore(o.first.get(I)).limitToLast(t.pagination.number)):!t.pagination.startAfter&&!t.pagination.endBefore?v=v.map(E=>E.limit(t.pagination.number)):t.pagination.startAfter?v=v.map((E,I)=>E.startAfter(o.last.get(I)).limit(t.pagination.number)):v=v.map((E,I)=>E.endBefore(o.first.get(I)).limitToLast(t.pagination.number))}const Z={};await le("preOperation",y,C,["read",void 0,void 0,Z]),await le("preRead",y,C,[Z,v,!0,!1]),a=new Map;const k=v.map(async A=>await c.get(A)),_=await Promise.all(k);for(const A of _){for(const E of A.docs){a.has(E.id)||a.set(E.id,{});const I=E.data(),R=a.get(E.id);R.id||=E.id;const M={...R,...I};delete M.Collection_Path_String,a.set(E.id,M)}o.first.set(_.indexOf(A),A.docs[0]),o.last.set(_.indexOf(A),A.docs.at(-1)||A.docs[0])}if(t?.pagination){let A=v[0];e&&(A=e.reduce((M,[$,P,j])=>M.where($,P,j),A)),t.pagination.orderByField&&t.pagination.orderByDirection&&(A=A.orderBy(t.pagination.orderByField,t.pagination.orderByDirection));const I=(await A.count().get()).data().count,R=t.pagination.number;i=R>0?Math.ceil(I/R):0}for(const A of a.values()){const E=[],I=[...A.Collection_Path,A.id];t?.subcollections&&E.push(Ao(s,a.get(A.id),I,pe(t.subcollections),m,pe(t?.relations),void 0,t.user,t.transactional?c:void 0,t?.noEmbeddingFields)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map($=>{if(typeof $=="string"){const P=p.fields.find(j=>j.name===$);if(P)return P;throw new Error(`SCHEMA_ERROR: Field ${$} not found in collection ${w}`)}return $})),E.push(nr(s,a.get(A.id),I,pe(t.relations),m,void 0,t.user,t.transactional?c:void 0,t?.noEmbeddingFields))),await Promise.all(E);for(const $ of a.values())for(const P of p.fields){if(P.type==="Computed"){const j=Ie(P,C);if(!j.formula)continue;$[P.name]=await j.formula($)}t?.noEmbeddingFields&&P.type==="Embedding"&&delete $[P.name]}if(t?.user&&O?.Role){const $=O.Role;if(!(C.custom?.serverAccess?.read!==void 0?await ie(C.custom.serverAccess.read,[$,A]):!0)){a.delete(A.id);continue}for(const j of p.fields){const K=!j.access||j.access.includes($),S=Ie(j,C),q=S?.custom?.serverAccess?.read!==void 0?await ie(S.custom.serverAccess.read,[$,A]):!0;(!K||!q)&&(X(j)?(delete a.get(A.id)[j.name],delete a.get(A.id)[`${j.name}_Array`],delete a.get(A.id)[`${j.name}_Single`]):delete a.get(A.id)[j.name])}}const R=["read",A,A.id,Z];await le("postOperation",y,C,R),await le("postRead",y,C,[Z,v,A,!1])}t?.user&&await Xo(Array.from(a.values()),p,m,t.user,O)};return t?.providedTransaction?await l(t.providedTransaction):await r.runTransaction(async c=>{await l(c)},{readOnly:!0}),{cursor:o,pages:i,docs:Array.from(a.values())}},Co=async(n,e,t,s,r,i,o,a)=>{const l=s.at(-2),c=mi(i.collections[l],i).map(f=>f.labels.collection);r.collections?r.collections.forEach(f=>{if(!c.includes(f))throw new Error(`SCHEMA_ERROR: Collection ${f} not found in subcollections of ${l}`)}):r.collections=c;const u=r.depth-1,h=r.collections.map(async f=>{const d=await sr([...s,f],r.constraints||[],{user:a,relations:o,pagination:r.limit,providedTransaction:e}).catch(m=>{throw m.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${f} for document at ${s.join("/")}`),m});t[f]=d.docs,u>0&&await Promise.all(t[f].map(async m=>{await Co(n,e,m,[...s,f,m.id],{depth:u},i,o,a)}))});await Promise.all(h)},Fo=async(n,e,t,s,r,i,o,a,l)=>{const c=s.at(-2);i.fields||=r.collections[c].fields.filter(f=>X(f));const u=i.depth-1,h=[];for(const f of i.fields)if("collection"in f){const d=t[f.name];if(!d)continue;for(const[m,O]of Object.entries(d)){const y=Je(O.Collection_Path,m,{user:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(w=>{if(d[m]=w,u>0)return Fo(n,e,d[m],[...O.Collection_Path,m],r,{depth:u},o,a,l)}).catch(w=>{if(w.message.includes("NOT_FOUND")||w.code==="permission-denied")delete d[m];else throw w});h.push(y)}}await Promise.all(h)},Je=async(n,e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(t?.relations?.depth&&t.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=Ze(),r=H.getFirestore();let i;const o=async a=>{const[l,c,u]=await Promise.all([t?.user?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(t.user)):Promise.resolve(Promise.resolve({})),a.get(r.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!c.exists)throw new Error("MAINTENANCE_MODE");if(c.data().active)throw new Error("MAINTENANCE_MODE");const f=u;let d;const m=Et(),O=n.at(-1);if(!O)throw new Error("EMPTY_PATH");const y=Object.keys(f.collections).includes(O),w=m.disabledCollections?.includes(O);if(!y||w)throw new Error("COLLECTION_NOT_FOUND");const b=f.collections[O],{labels:N}=b,p=ze(N.collection,f);let T;if(t?.user){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(d=l.data(),!d.Role)throw new Error("USER_ERROR");if(!d.Enabled)throw new Error("PERMISSION_DENIED");if(T=d.collections?.[N.collection],!T)throw new Error("PERMISSION_DENIED")}if(t?.user&&(!T||!Se("Read",T)))throw new Error("PERMISSION_DENIED");const C=tr(s,n,e,f,d);if(C.length===0)throw new Error("PERMISSION_DENIED");const v={};await le("preOperation",m,p,["read",void 0,e,v]),await le("preRead",m,p,[v,C,!1,!1]),i={};const g=C.map(R=>a.get(R)),k=await Promise.all(g);for(const R of k)if(R.exists){const M=R.data();i.id||=R.id,i={...i,...M},delete i.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${n?.join("/")||N.collection}`);const _=[],A=n?[...n,e]:[N.collection,e];if(t?.subcollections&&_.push(Co(s,a,i,A,t.subcollections,f,void 0,t.user)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(R=>{if(typeof R=="string"){const M=b.fields.find($=>$.name===R);if(M)return M;throw new Error(`SCHEMA_ERROR: Field ${R} not found in collection ${O}`)}return R})),_.push(Fo(s,a,i,A,f,t.relations,t.user,t.noComputedFields,t.noEmbeddingFields))),await Promise.all(_),!t?.noComputedFields){for(const R of b.fields)if(R.type==="Computed"){const M=Ie(R,p);if(!M.formula)continue;i[R.name]=await M.formula(i)}}if(t?.noEmbeddingFields)for(const R of b.fields)R.type==="Embedding"&&delete i[R.name];if(t?.user&&d?.Role){const R=d.Role;if(!(p.custom?.serverAccess?.read!==void 0?await ie(p.custom?.serverAccess?.read,[R,i]):!0))throw new Error("PERMISSION_DENIED");for(const $ of b.fields){const P=!$.access||$.access.includes(R),j=Ie($,p),K=j?.custom?.serverAccess?.read!==void 0?await ie(j.custom.serverAccess.read,[R,i]):!0;(!P||!K)&&(X($)?(delete i[$.name],delete i[`${$.name}_Array`],delete i[`${$.name}_Single`]):delete i[$.name])}}await le("postOperation",m,p,["read",i,e,v]),await le("postRead",m,p,[v,C,i,!1]),t?.user&&await Ko(i,b,f,t.user,d)};return t?.providedTransaction?await o(t.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},$o=async(n,e,t,s,r,i,o,a)=>{const l=H.getFirestore(),c=ze(r.labels.collection,i),u=r.labels.collection,h=r.fields.filter(d=>"unique"in d&&d.unique),f=[];if(await Promise.all(h.map(async d=>{{if(s[d.name]===void 0||Ne(s[d.name]))return;Ie(d,c);const m=s[d.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(!Ks(m))f.push(`${d.name} "${s[d.name]}" is invalid`);else{const O=await l.collection("tenants").doc(e).collection("system_unique").doc(u).collection(`Unique-${u}-${d.name}`).doc(m).get();O.exists&&!(n==="update"&&O.data().id===t)&&f.push(`${d.name} "${s[d.name]}" already exists`)}}})),f.length>0)throw new Error(f.join(", "))},pt=async(n,e,t,s,r,i,o,a,l)=>{const{labels:c}=o,u=H.getFirestore(),h=Et(),f=await ie(h.firebase?.writeLogTTL),d={operation:n,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_App:t.Last_Write_App,Last_Write_Version:t.Last_Write_Version,data:{}};if(f){const w=new Date,b=new Date(new Date().setDate(w.getDate()+f));d.TTL=H.Timestamp.fromDate(b)}const m=pe(t);nt(m),n!=="delete"&&(d.data.data=pe(m)),n==="update"&&(d.data.originalRecord=pe(l)),n!=="delete"&&["started","written"].includes(e)&&(delete d.data.data.Saved_At,delete d.data.data.Last_Save_At),e==="failed"&&(d.data.error=JSON.stringify(a));const O=Te(u,r,s),y=t.Last_Write_At;await O.doc(i).collection("system_write_log").doc(`${t.Last_Write_By}-${y.valueOf()}`).set(d)},Ut=async n=>{const e=Ze(),t=yt.getAuth(),s=H.getFirestore(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(n.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
|
|
7
7
|
${i}`)}})(),(async()=>{try{await t.deleteUser(n.User_ID)}catch(i){if(i.code==="auth/user-not-found")return;r.push(`Error deleting user:
|
|
8
|
-
${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},
|
|
8
|
+
${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},rr=async(n,e,t,s,r,i,o,a,l)=>{const c=H.getFirestore(),u=Xs(),h=process.env.ADMIN_EMAIL;if(u==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(h)n=h;else throw new Error("Admin email not set");const f=hs(n),d=Lc(e),m=t?oi(t):void 0,O=s?oi(s):void 0,y=r?hs(r):void 0,w=i?hs(i):void 0,b=o?Vn(o):void 0,N=l?Vn(l):void 0,p=Array.isArray(f)?f:[f];if(p.length===0||p.length===1&&!p[0])throw new Error("No valid email addresses provided");const T={to:f,message:{subject:d}};if(m&&(T.message.text=m),O&&(T.message.html=O),y){const C=Array.isArray(y)?y:[y];C.length>0&&C[0]&&(T.cc=y)}if(w){const C=Array.isArray(w)?w:[w];C.length>0&&C[0]&&(T.bcc=w)}b&&(T.replyTo=b),a&&(T.message.attachments=a),N&&(T.from=N),await c.collection("system_mail").add(T)},ir=async(n,e,t,s,r,i,o)=>{const a=yt.getAuth(),l=H.getFirestore(),c="USER_ERROR",u=async(d,m)=>{try{await Ut(d)}catch{throw new Error(`ROLLBACK_FAILED: ${m}`)}};let h;try{h=await a.createUser({email:r.Email,emailVerified:!1,password:o,displayName:r.Name,photoURL:r.Photo_URL,disabled:!r.Enabled})}catch{throw new Error(c)}try{await a.setCustomUserClaims(h.uid,{tenant:n,role:r.Role,collection:s,doc:e})}catch{throw await u(r,c),new Error(c)}try{await l.collection("tenants").doc(n).collection("system_user_permissions").doc(h.uid).set({...i,Role:r.Role,Enabled:r.Enabled??!1,Collection:s,Doc_ID:e})}catch{throw await u(r,c),new Error(c)}const f=t.auth.enableMultiFactorAuth;if(f===!0||typeof f=="object"&&f.includes(r.Role)){let d;try{d=await a.generateEmailVerificationLink(r.Email)}catch{throw await u(r,c),new Error(c)}if(d.includes("apiKey=&")){const m=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);d=d.replace("apiKey=&",`apiKey=${m.apiKey}&`)}if(d){const m=`https://${a.app.options.projectId}.firebaseapp.com/__/auth/action${d}`,O=await ie(t.appName),y=t?.mail?.emailVerification&&t.mail.emailVerification(m,O);try{await rr(r.Email,y?.subject||"Please verify your email address",void 0,y?.html||`Please verify your email address by clicking the link:
|
|
9
9
|
</br>
|
|
10
10
|
</br>
|
|
11
|
-
<a href="${m}">${m}</a>`)}catch{throw await u(r,c),new Error(c)}}}return h.uid},sr=async(n,e)=>{const{labels:t,parentCollection:s}=e;if(s){const r=n.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...n].slice(0,-2),o=await Ge(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(t.collection),!ze(n,a))throw new Error("PERMISSION_DENIED")}else if(n.length>1)throw new Error("PERMISSION_DENIED")},Vn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Zc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Vn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?t[s]=new H.Timestamp(r.seconds,r.nanoseconds):Vn(r)&&e(r)})};e(n)},rr=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Vn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?t[s]=new H.Timestamp(r._seconds,r._nanoseconds):Vn(r)&&e(r)})};e(n)},Gn=n=>{if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]==="_DELETE_FIELD"?n[e]=H.FieldValue.delete():Gn(n[e]))},zc=(n,e,t)=>{if(X(t)&&t.includeFields){const s={};return t.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=W(n.fields,r);gt(n,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},ri=async(n,e,t,s,r,i,o)=>{if(!X(t)||!t.enforceHierarchy)return;const{fields:a}=e,l=H.getFirestore(),c=Object.entries(s[t.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${t.name} is required`);const[u,h]=c[0];if(!h)throw new Error(`VALIDATION_ERROR: Relation ${t.name} is required`);const f=Te(l,h.Collection_Path,n);if(i.size++,!o&&i.size>500)throw new Error("VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const d=await r.get(f.doc(u));if(!d.exists)throw new Error(`VALIDATION_ERROR: Record ${u} not found in collection ${t.collection}`);const m=d.data(),O=W(a,t.enforceHierarchy.field),y=t.enforceHierarchy;if(!m[y.recordLinkField]||!s[O.name]||!Object.keys(s[O.name]).every(w=>Object.keys(m[y.recordLinkField]).includes(w)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},yn=async(n,e,t)=>{delete e[n.name][t],e[`${n.name}_Array`]=e[`${n.name}_Array`]?.filter(s=>s!==t),delete e[`${n.name}_Single`]},ps=async(n,e,t,s,r)=>{e[n.name]||={},e[n.name][s]=t,e[`${n.name}_Array`]||=[],e[`${n.name}_Array`].push(s),r&&(e[`${n.name}_Single`]=t)},qc=(n,e,t,s,r,i)=>{const o=[],a=[];for(const l of s.fields)X(l)&&l.twoWay&&l.collection===t&&((n==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),n==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},ir=async(n,e,t,s,r,i,o,a,l,c,u,h)=>{const{fields:f}=i,d=H.getFirestore(),m=new Map,O=new Map,y=new Map;for(const w of f)X(w)&&["OneToOne","OneToMany"].includes(w.type)&&w.enforceHierarchy&&s[w.name]&&(n==="Create"||n==="Update"&&!ze(h?.[w.name],s[w.name]))&&await ri(e,i,w,s,a,l);for(const w of f)if(X(w)&&w.twoWay){const b=o.collections[w.collection],N=W(b.fields,w.twoWay),p=ut(b,[N]);if(s[w.name]){const T=Object.entries(s[w.name]);for(const C of T){const[v,Z]=C;if(n==="Create"||!h?.[w.name]?.[v]){let x;const g=y.get(w.collection)?.[v];if(g)x=g;else{if(l.size++,l&&l.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const _=Te(d,Z.Collection_Path,e),A=await a.get(_.doc(v));if(!A.exists){yn(w,r,v);continue}const E=A.data();O.set(w.collection,{...O.get(w.collection)||{},[v]:E}),x=pe({...E,...kn(s)})}const k={...x[N.name],[t]:{Collection_Path:s.Collection_Path,...zc(i,s,N)}};x[N.name]=k,x[`${N.name}_Array`]||=[],x[`${N.name}_Array`].push(t),p.size===1&&(x[`${N.name}_Single`]=k),y.set(w.collection,{...y.get(w.collection)||{},[v]:x})}}}if(n==="Update"){const T=Object.entries(h?.[w.name]||{});for(const C of T){const[v,Z]=C;if(!s[w.name]?.[v]){let x;const g=y.get(w.collection)?.[v];if(g)x=g;else{if(l.size++,l&&l.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const k=Te(d,Z.Collection_Path,e),_=await a.get(k.doc(v));if(!_.exists){m.set(w.name,[...m.get(w.name)||[],v]);continue}const A=_.data();O.set(w.collection,{...O.get(w.collection)||{},[v]:A}),x=pe({...A,...kn(s)})}x[N.name][t]&&delete x[N.name][t],Array.isArray(x[`${N.name}_Array`])&&(x[`${N.name}_Array`]=x[`${N.name}_Array`].filter(k=>k!==t)),p.size===1&&delete x[`${N.name}_Single`],y.set(w.collection,{...y.get(w.collection)||{},[v]:x})}}}}for(const[w,b]of y.entries()){const N=o.collections[w],p=Je(w,o);for(const[T,C]of Object.entries(b)){const{addedFields:v,removedFields:Z}=qc(n,T,w,i,s,h);if(c&&u){for(const x of v){const g=W(N.fields,x.twoWay);if(!cr(N,g,u)){yn(x,r,T);continue}}for(const x of Z){const g=W(N.fields,x.twoWay),k=ut(N,[g]);if(!cr(N,g,u)){ps(x,r,h?.[x.name]?.[T],T,k.size===1);continue}}if(!it("Update",N,o,c,u,O.get(w)?.[T])){for(const x of v)yn(x,r,T);for(const x of Z){const g=W(N.fields,x.twoWay),k=ut(N,[g]);ps(x,r,h?.[x.name]?.[T],T,k.size===1)}}if(!it("Update",N,o,c,u,C)){for(const x of v)yn(x,r,T);for(const x of Z){const g=W(N.fields,x.twoWay),k=ut(N,[g]);ps(x,r,h?.[x.name]?.[T],T,k.size===1)}}}try{await sn("update",C,N,p,["update",C,{},void 0,C],o)}catch(x){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${T} in ${w}: ${x.message}`)}for(const x of v){const g=W(N.fields,x.twoWay);["OneToOne","OneToMany"].includes(g.type)&&X(g)&&g.enforceHierarchy&&await ri(e,N,g,C,a,l,!0)}}}return m},Mo=(n,e,t)=>{n==="create"&&ht.forEach(s=>{if(!ze(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),n==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),ht.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!ze(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},or=(n,e,t,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(t[i]===!0)if(n==="create")t[o]=H.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])t[o]=H.FieldValue.serverTimestamp();else if(t[o]&&t[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},ys=async(n,e,t,s,r)=>{if(!Se("Read",r.collections?.[e.labels.collection]))return!1;try{await Ge([e.labels.collection],t,{user:s,providedTransaction:n})}catch{return!1}return!0},Bc=10,Hc=async(n,e)=>{if(n.length===0)return;const t=Math.min(e,n.length);let s=0;const r=async()=>{for(;s<n.length;){const i=s;s+=1,await n[i]()}};await Promise.all(Array.from({length:t},r))},Po=async(n,e,t,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,u=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const f=i?.collections?.[a],d=[];if(l.individualEntities){const m=l.individualEntities,O=f?.individualEntities||[],y=i?m.filter(w=>!O.includes(w)):m;for(const w of y){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");d.push(async()=>{if(!await ys(n,u,w,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const m=c.entityRestrictions?.restrictions?.find(p=>p.type==="Parent"&&p.roles.some(T=>T.role===e.Role));if(!m)throw new Error("PERMISSION_DENIED");const O=W(u.fields,m.collectionField),y=r.collections[O.collection],w=l.parentEntities,b=f?.parentEntities||[],N=i?w.filter(p=>!b.includes(p)):w;for(const p of N){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");d.push(async()=>{if(!await ys(n,y,p,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const m=c.entityRestrictions?.restrictions?.find(N=>N.type==="Parent_Property"&&N.roles.some(p=>p.role===e.Role));if(!m)throw new Error("PERMISSION_DENIED");const O=W(u.fields,m.collectionField),y=r.collections[O.collection],w=l.parentPropertyEntities,b=f?.parentPropertyEntities||{};for(const[N,p]of Object.entries(w)){const T=b[N]||[],C=i?p.filter(v=>!T.includes(v)):p;for(const v of C){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");d.push(async()=>{if(!await ys(n,y,v,t,s))throw new Error("PERMISSION_DENIED")})}}}await Hc(d,Bc)}}},Gc=async(n,e,t,s,r,i,o)=>{const a=Ye(),l=Vt();let c=await je();if(n.length===0)throw new Error("EMPTY_PATH");const u=n.at(-1),h=Object.keys(c.collections).includes(u),f=l.disabledCollections?.includes(u);if(!h||f)throw new Error("COLLECTION_NOT_FOUND");const d=c.collections[u],{labels:m,fields:O,enableWriteLog:y,softDelete:w}=d,b=Je(m.collection,c),N=await ie(l.appName),p=H.getFirestore(),T=yt.getAuth(),v=(s?await T.getUser(s):void 0)?.customClaims?.role;let Z;s&&await sr(n,d);const x=Te(p,n,a),g=o||x.doc().id;i=i||{},i.collection=m.collection,e.id=g,rr(e),Gn(e);const k=Us("create",n,e,c,N,"Online",s||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp()),_=pe(k);w&&(k[w.archivedField]=!1),Le(e),y&&await pt("create","started",k,a,n,g,d),await le("preOperation",l,b,["create",k,g,i]),await le("preWrite",l,b,["create",k,g,i]),bn(d,k,c),Sn(d,k),await ca(k,d,b,v),Le(k);try{if(d.auth&&t&&!t.password)throw new Error("Password is required");await $o("create",a,g,k,d,c),await sn("create",k,d,b,["create",k,i],c)}catch(P){throw new Error(`VALIDATION_ERROR: ${P.message}`)}Le(k),e.id=g,w&&(k[w.archivedField]=!1),bn(d,k,c),Sn(d,k);try{Mo("create",k,_),or("create",d,k),await sn("create",k,d,b,["create",k,i],c)}catch(P){throw new Error(`VALIDATION_ERROR: ${P.message}`)}if(s){const P=v;if(!P)throw new Error("USER_ERROR");if(!(b.custom?.serverAccess?.create!==void 0?await ie(b.custom.serverAccess.create,[P,k]):!0))throw new Error("PERMISSION_DENIED");for(const K of d.fields){if(!(K.name in k))continue;const S=Ie(K,b);if(S?.custom?.serverAccess?.create!==void 0&&!await ie(S.custom.serverAccess.create,[P,k]))throw new Error("PERMISSION_DENIED")}}t&&(t.permissions||={},t.permissions.Role||=k.Role,t.permissions.Enabled||=k.Enabled);const I=async(P,j)=>{const[K,S,q,B]=await Promise.all([P.get(p.collection("system_deployment").doc("latest_deploy")),P.get(p.collection("system_deployment").doc("maintenance_mode")),s?P.get(p.collection("tenants").doc(a).collection("system_user_permissions").doc(s)):Promise.resolve(Promise.resolve({})),je()]);if(j&&(j.size+=3),!K.exists)throw new Error("VERSION_ERROR");const oe=K.data();if(oe.force&&k.Last_Write_At.valueOf()<oe.time.valueOf())throw new Error("VERSION_ERROR");if(!S.exists)throw new Error("MAINTENANCE_MODE");if(S.data().active)throw new Error("MAINTENANCE_MODE");if(c=B,s){if(!q?.exists)throw new Error("PERMISSION_DENIED");if(Z=q.data(),!Z.Role)throw new Error("USER_ERROR");if(!Z.Enabled)throw new Error("PERMISSION_DENIED")}const me=O.filter(ae=>"unique"in ae&&ae.unique).map(async ae=>{if(!s||!ae.access||ae.access.includes(Z.Role)){if(!e[ae.name])return;const Pe=Ie(ae,b);if(!(s&&Pe?.custom?.serverAccess?.read!==void 0?await ie(Pe.custom.serverAccess.read,[Z?.Role,k]):!0))throw new Error("PERMISSION_DENIED");const Yn=e[ae.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Qs(Yn)){if(j&&j.size++,j&&j.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");if((await P.get(p.collection("tenants").doc(a).collection("system_unique").doc(m.collection).collection(`Unique-${m.collection}-${ae.name}`).doc(Yn)))?.exists)throw new Error(`VALIDATION_ERROR: ${ae.name} "${k[ae.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${ae.name} "${k[ae.name]}" is invalid`)}});await Promise.all(me),ur(k,g,d,c,s,Z,t?.permissions),t?.permissions&&s&&Z&&await Po(P,t.permissions,s,Z,c),ur(k,g,d,c,s,Z,t?.permissions)};if(d.auth&&t){await p.runTransaction(async j=>{await I(j)},{maxAttempts:10});const P=await nr(a,g,l,m.collection,k,t.permissions,t.password);k.User_ID=P}try{const P={size:1};await p.runTransaction(async j=>{await I(j,P),r?.noTwoWay||await ir("Create",a,g,k,k,d,c,j,P,s,Z);const K=Vs(c);Js("create",j,n,g,k,c,d,r,K,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.FieldValue.delete,S=>p.collection("tenants").doc(a).collection("system_fields").doc(m.collection).collection(`${m.collection}-${S.name}`).doc(g),(S,q)=>p.collection("tenants").doc(a).collection("system_unique").doc(m.collection).collection(`Unique-${m.collection}-${S.name}`).doc(q),S=>p.collection("tenants").doc(a).collection("system_fields").doc(m.collection).collection(`${m.collection}-${S}`).doc(g),(S,q)=>Te(p,S,a).doc(q),(S,q,B)=>p.collection("tenants").doc(a).collection("system_fields").doc(S.collection).collection(`${S.collection}-${q}`).doc(B),(S,q,B)=>p.collection("tenants").doc(a).collection("system_fields").doc(S.collection).collection(`${S.collection}-${q.replaceAll(" ","-")}`).doc(B),void 0,void 0,P),j.set(x.doc(g),k)},{maxAttempts:10})}catch(P){const K=await le("postWriteError",l,b,["create",k,g,i,P]);if(y&&(await new Promise(S=>{setTimeout(S,250)}),await pt("create",K?.resolved?"success":"failed",k,a,n,g,d,K?.resolved?void 0:P)),!K?.resolved)throw d.auth&&t&&await Ut(k),P}const R=["create",k,g,i],M=[...R];return await le("postWrite",l,b,R),await le("postOperation",l,b,M),{id:g,...k}},Qt=async(n,e,t,s)=>{const r=Ye(),i=yt.getAuth(),o=H.getFirestore(),a=e.customClaims||{};let l=!1;try{await i.updateUser(n,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(n,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(n).update({...t,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Lo=async(n,e,t,s,r,i,o,a,l,c,u)=>{const h=yt.getAuth(),f=H.getFirestore(),d=a?.customClaims||{},m="USER_ERROR";let O="";if(n==="create"){if(!u)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{O=await nr(e,t,s,r,i,l,u)}catch(y){throw new Error(y.message)}}else if(n==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),u&&(y.password=u),Object.keys(y).length)try{await h.updateUser(o.User_ID,y),y.disabled===!0&&await h.revokeRefreshTokens(o.User_ID)}catch{throw await Qt(o.User_ID,a,c,m),new Error(m)}if(i.Role&&i.Role!==o.Role)try{await h.setCustomUserClaims(o.User_ID,{...d,role:i.Role}),await h.revokeRefreshTokens(o.User_ID)}catch{throw await Qt(o.User_ID,a,c,m),new Error(m)}try{await f.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:d.collection,Doc_ID:d.doc,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await Qt(o.User_ID,a,c,m),new Error(m)}if(o.Email!==i.Email){const w=s.auth.enableMultiFactorAuth;if(w===!0||typeof w=="object"&&w.includes(i.Role)){let b=await h.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(b.includes("apiKey=&")){const N=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);b=b.replace("apiKey=&",`apiKey=${N.apiKey}&`)}if(b){const N=`https://${h.app.options.projectId}.firebaseapp.com/__/auth/action${b}`,p=await ie(s.appName),T=s?.mail?.emailVerification&&s.mail.emailVerification(N,p);try{await tr(i.Email,T?.subject||"Please verify your email address",void 0,T?.html||`Please verify your email address by clicking the link:
|
|
11
|
+
<a href="${m}">${m}</a>`)}catch{throw await u(r,c),new Error(c)}}}return h.uid},or=async(n,e)=>{const{labels:t,parentCollection:s}=e;if(s){const r=n.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...n].slice(0,-2),o=await Je(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(t.collection),!Be(n,a))throw new Error("PERMISSION_DENIED")}else if(n.length>1)throw new Error("PERMISSION_DENIED")},Un=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Bc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Un(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?t[s]=new H.Timestamp(r.seconds,r.nanoseconds):Un(r)&&e(r)})};e(n)},ar=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Un(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?t[s]=new H.Timestamp(r._seconds,r._nanoseconds):Un(r)&&e(r)})};e(n)},Yn=n=>{if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]==="_DELETE_FIELD"?n[e]=H.FieldValue.delete():Yn(n[e]))},Hc=(n,e,t)=>{if(X(t)&&t.includeFields){const s={};return t.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=W(n.fields,r);gt(n,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},ai=async(n,e,t,s,r,i,o)=>{if(!X(t)||!t.enforceHierarchy)return;const{fields:a}=e,l=H.getFirestore(),c=Object.entries(s[t.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${t.name} is required`);const[u,h]=c[0];if(!h)throw new Error(`VALIDATION_ERROR: Relation ${t.name} is required`);const f=Te(l,h.Collection_Path,n);if(i.size++,!o&&i.size>500)throw new Error("VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const d=await r.get(f.doc(u));if(!d.exists)throw new Error(`VALIDATION_ERROR: Record ${u} not found in collection ${t.collection}`);const m=d.data(),O=W(a,t.enforceHierarchy.field),y=t.enforceHierarchy;if(!m[y.recordLinkField]||!s[O.name]||!Object.keys(s[O.name]).every(w=>Object.keys(m[y.recordLinkField]).includes(w)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},yn=async(n,e,t)=>{delete e[n.name][t],e[`${n.name}_Array`]=e[`${n.name}_Array`]?.filter(s=>s!==t),delete e[`${n.name}_Single`]},ys=async(n,e,t,s,r)=>{e[n.name]||={},e[n.name][s]=t,e[`${n.name}_Array`]||=[],e[`${n.name}_Array`].push(s),r&&(e[`${n.name}_Single`]=t)},Gc=(n,e,t,s,r,i)=>{const o=[],a=[];for(const l of s.fields)X(l)&&l.twoWay&&l.collection===t&&((n==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),n==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},lr=async(n,e,t,s,r,i,o,a,l,c,u,h)=>{const{fields:f}=i,d=H.getFirestore(),m=new Map,O=new Map,y=new Map;for(const w of f)X(w)&&["OneToOne","OneToMany"].includes(w.type)&&w.enforceHierarchy&&s[w.name]&&(n==="Create"||n==="Update"&&!Be(h?.[w.name],s[w.name]))&&await ai(e,i,w,s,a,l);for(const w of f)if(X(w)&&w.twoWay){const b=o.collections[w.collection],N=W(b.fields,w.twoWay),p=ut(b,[N]);if(s[w.name]){const T=Object.entries(s[w.name]);for(const C of T){const[v,Z]=C;if(n==="Create"||!h?.[w.name]?.[v]){let x;const g=y.get(w.collection)?.[v];if(g)x=g;else{if(l.size++,l&&l.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const _=Te(d,Z.Collection_Path,e),A=await a.get(_.doc(v));if(!A.exists){yn(w,r,v);continue}const E=A.data();O.set(w.collection,{...O.get(w.collection)||{},[v]:E}),x=pe({...E,...bn(s)})}const k={...x[N.name],[t]:{Collection_Path:s.Collection_Path,...Hc(i,s,N)}};x[N.name]=k,x[`${N.name}_Array`]||=[],x[`${N.name}_Array`].push(t),p.size===1&&(x[`${N.name}_Single`]=k),y.set(w.collection,{...y.get(w.collection)||{},[v]:x})}}}if(n==="Update"){const T=Object.entries(h?.[w.name]||{});for(const C of T){const[v,Z]=C;if(!s[w.name]?.[v]){let x;const g=y.get(w.collection)?.[v];if(g)x=g;else{if(l.size++,l&&l.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of two way updates, unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const k=Te(d,Z.Collection_Path,e),_=await a.get(k.doc(v));if(!_.exists){m.set(w.name,[...m.get(w.name)||[],v]);continue}const A=_.data();O.set(w.collection,{...O.get(w.collection)||{},[v]:A}),x=pe({...A,...bn(s)})}x[N.name][t]&&delete x[N.name][t],Array.isArray(x[`${N.name}_Array`])&&(x[`${N.name}_Array`]=x[`${N.name}_Array`].filter(k=>k!==t)),p.size===1&&delete x[`${N.name}_Single`],y.set(w.collection,{...y.get(w.collection)||{},[v]:x})}}}}for(const[w,b]of y.entries()){const N=o.collections[w],p=ze(w,o);for(const[T,C]of Object.entries(b)){const{addedFields:v,removedFields:Z}=Gc(n,T,w,i,s,h);if(c&&u){for(const x of v){const g=W(N.fields,x.twoWay);if(!fr(N,g,u)){yn(x,r,T);continue}}for(const x of Z){const g=W(N.fields,x.twoWay),k=ut(N,[g]);if(!fr(N,g,u)){ys(x,r,h?.[x.name]?.[T],T,k.size===1);continue}}if(!it("Update",N,o,c,u,O.get(w)?.[T])){for(const x of v)yn(x,r,T);for(const x of Z){const g=W(N.fields,x.twoWay),k=ut(N,[g]);ys(x,r,h?.[x.name]?.[T],T,k.size===1)}}if(!it("Update",N,o,c,u,C)){for(const x of v)yn(x,r,T);for(const x of Z){const g=W(N.fields,x.twoWay),k=ut(N,[g]);ys(x,r,h?.[x.name]?.[T],T,k.size===1)}}}try{await sn("update",C,N,p,["update",C,{},void 0,C],o)}catch(x){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${T} in ${w}: ${x.message}`)}for(const x of v){const g=W(N.fields,x.twoWay);["OneToOne","OneToMany"].includes(g.type)&&X(g)&&g.enforceHierarchy&&await ai(e,N,g,C,a,l,!0)}}}return m},Mo=(n,e,t)=>{n==="create"&&ht.forEach(s=>{if(!Be(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),n==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),ht.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!Be(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},cr=(n,e,t,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(t[i]===!0)if(n==="create")t[o]=H.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])t[o]=H.FieldValue.serverTimestamp();else if(t[o]&&t[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},gs=async(n,e,t,s,r)=>{if(!Se("Read",r.collections?.[e.labels.collection]))return!1;try{await Je([e.labels.collection],t,{user:s,providedTransaction:n})}catch{return!1}return!0},Yc=10,Jc=async(n,e)=>{if(n.length===0)return;const t=Math.min(e,n.length);let s=0;const r=async()=>{for(;s<n.length;){const i=s;s+=1,await n[i]()}};await Promise.all(Array.from({length:t},r))},Po=async(n,e,t,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,u=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const f=i?.collections?.[a],d=[];if(l.individualEntities){const m=l.individualEntities,O=f?.individualEntities||[],y=i?m.filter(w=>!O.includes(w)):m;for(const w of y){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");d.push(async()=>{if(!await gs(n,u,w,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const m=c.entityRestrictions?.restrictions?.find(p=>p.type==="Parent"&&p.roles.some(T=>T.role===e.Role));if(!m)throw new Error("PERMISSION_DENIED");const O=W(u.fields,m.collectionField),y=r.collections[O.collection],w=l.parentEntities,b=f?.parentEntities||[],N=i?w.filter(p=>!b.includes(p)):w;for(const p of N){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");d.push(async()=>{if(!await gs(n,y,p,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const m=c.entityRestrictions?.restrictions?.find(N=>N.type==="Parent_Property"&&N.roles.some(p=>p.role===e.Role));if(!m)throw new Error("PERMISSION_DENIED");const O=W(u.fields,m.collectionField),y=r.collections[O.collection],w=l.parentPropertyEntities,b=f?.parentPropertyEntities||{};for(const[N,p]of Object.entries(w)){const T=b[N]||[],C=i?p.filter(v=>!T.includes(v)):p;for(const v of C){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");d.push(async()=>{if(!await gs(n,y,v,t,s))throw new Error("PERMISSION_DENIED")})}}}await Jc(d,Yc)}}},Qc=async(n,e,t,s,r,i,o)=>{const a=Ze(),l=Et();let c=await je();if(n.length===0)throw new Error("EMPTY_PATH");const u=n.at(-1),h=Object.keys(c.collections).includes(u),f=l.disabledCollections?.includes(u);if(!h||f)throw new Error("COLLECTION_NOT_FOUND");const d=c.collections[u],{labels:m,fields:O,enableWriteLog:y,softDelete:w}=d,b=ze(m.collection,c),N=await ie(l.appName),p=H.getFirestore(),T=yt.getAuth(),v=(s?await T.getUser(s):void 0)?.customClaims?.role;let Z;s&&await or(n,d);const x=Te(p,n,a),g=o||x.doc().id;i=i||{},i.collection=m.collection,e.id=g,ar(e),Yn(e);const k=Ws("create",n,e,c,N,"Online",s||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp()),_=pe(k);w&&(k[w.archivedField]=!1),Le(e),y&&await pt("create","started",k,a,n,g,d),await le("preOperation",l,b,["create",k,g,i]),await le("preWrite",l,b,["create",k,g,i]),Sn(d,k,c),Tn(d,k),await aa(k,d,b,v),Le(k);try{if(d.auth&&t&&!t.password)throw new Error("Password is required");await $o("create",a,g,k,d,c),await sn("create",k,d,b,["create",k,i],c)}catch(P){throw new Error(`VALIDATION_ERROR: ${P.message}`)}Le(k),e.id=g,w&&(k[w.archivedField]=!1),Sn(d,k,c),Tn(d,k);try{Mo("create",k,_),cr("create",d,k),await sn("create",k,d,b,["create",k,i],c)}catch(P){throw new Error(`VALIDATION_ERROR: ${P.message}`)}if(s){const P=v;if(!P)throw new Error("USER_ERROR");if(!(b.custom?.serverAccess?.create!==void 0?await ie(b.custom.serverAccess.create,[P,k]):!0))throw new Error("PERMISSION_DENIED");for(const K of d.fields){if(!(K.name in k))continue;const S=Ie(K,b);if(S?.custom?.serverAccess?.create!==void 0&&!await ie(S.custom.serverAccess.create,[P,k]))throw new Error("PERMISSION_DENIED")}}t&&(t.permissions||={},t.permissions.Role||=k.Role,t.permissions.Enabled||=k.Enabled);const I=async(P,j)=>{const[K,S,q,B]=await Promise.all([P.get(p.collection("system_deployment").doc("latest_deploy")),P.get(p.collection("system_deployment").doc("maintenance_mode")),s?P.get(p.collection("tenants").doc(a).collection("system_user_permissions").doc(s)):Promise.resolve(Promise.resolve({})),je()]);if(j&&(j.size+=3),!K.exists)throw new Error("VERSION_ERROR");const oe=K.data();if(oe.force&&k.Last_Write_At.valueOf()<oe.time.valueOf())throw new Error("VERSION_ERROR");if(!S.exists)throw new Error("MAINTENANCE_MODE");if(S.data().active)throw new Error("MAINTENANCE_MODE");if(c=B,s){if(!q?.exists)throw new Error("PERMISSION_DENIED");if(Z=q.data(),!Z.Role)throw new Error("USER_ERROR");if(!Z.Enabled)throw new Error("PERMISSION_DENIED")}const me=O.filter(ae=>"unique"in ae&&ae.unique).map(async ae=>{if(!s||!ae.access||ae.access.includes(Z.Role)){if(!e[ae.name])return;const Pe=Ie(ae,b);if(!(s&&Pe?.custom?.serverAccess?.read!==void 0?await ie(Pe.custom.serverAccess.read,[Z?.Role,k]):!0))throw new Error("PERMISSION_DENIED");const Jn=e[ae.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Ks(Jn)){if(j&&j.size++,j&&j.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");if((await P.get(p.collection("tenants").doc(a).collection("system_unique").doc(m.collection).collection(`Unique-${m.collection}-${ae.name}`).doc(Jn)))?.exists)throw new Error(`VALIDATION_ERROR: ${ae.name} "${k[ae.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${ae.name} "${k[ae.name]}" is invalid`)}});await Promise.all(me),hr(k,g,d,c,s,Z,t?.permissions),t?.permissions&&s&&Z&&await Po(P,t.permissions,s,Z,c),hr(k,g,d,c,s,Z,t?.permissions)};if(d.auth&&t){await p.runTransaction(async j=>{await I(j)},{maxAttempts:10});const P=await ir(a,g,l,m.collection,k,t.permissions,t.password);k.User_ID=P}try{const P={size:1};await p.runTransaction(async j=>{await I(j,P),r?.noTwoWay||await lr("Create",a,g,k,k,d,c,j,P,s,Z);const K=Us(c);Qs("create",j,n,g,k,c,d,r,K,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.FieldValue.delete,S=>p.collection("tenants").doc(a).collection("system_fields").doc(m.collection).collection(`${m.collection}-${S.name}`).doc(g),(S,q)=>p.collection("tenants").doc(a).collection("system_unique").doc(m.collection).collection(`Unique-${m.collection}-${S.name}`).doc(q),S=>p.collection("tenants").doc(a).collection("system_fields").doc(m.collection).collection(`${m.collection}-${S}`).doc(g),(S,q)=>Te(p,S,a).doc(q),(S,q,B)=>p.collection("tenants").doc(a).collection("system_fields").doc(S.collection).collection(`${S.collection}-${q}`).doc(B),(S,q,B)=>p.collection("tenants").doc(a).collection("system_fields").doc(S.collection).collection(`${S.collection}-${q.replaceAll(" ","-")}`).doc(B),void 0,void 0,P),j.set(x.doc(g),k)},{maxAttempts:10})}catch(P){const K=await le("postWriteError",l,b,["create",k,g,i,P]);if(y&&(await new Promise(S=>{setTimeout(S,250)}),await pt("create",K?.resolved?"success":"failed",k,a,n,g,d,K?.resolved?void 0:P)),!K?.resolved)throw d.auth&&t&&await Ut(k),P}const R=["create",k,g,i],M=[...R];return await le("postWrite",l,b,R),await le("postOperation",l,b,M),{id:g,...k}},Qt=async(n,e,t,s)=>{const r=Ze(),i=yt.getAuth(),o=H.getFirestore(),a=e.customClaims||{};let l=!1;try{await i.updateUser(n,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(n,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(n).update({...t,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Lo=async(n,e,t,s,r,i,o,a,l,c,u)=>{const h=yt.getAuth(),f=H.getFirestore(),d=a?.customClaims||{},m="USER_ERROR";let O="";if(n==="create"){if(!u)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{O=await ir(e,t,s,r,i,l,u)}catch(y){throw new Error(y.message)}}else if(n==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),u&&(y.password=u),Object.keys(y).length)try{await h.updateUser(o.User_ID,y),y.disabled===!0&&await h.revokeRefreshTokens(o.User_ID)}catch{throw await Qt(o.User_ID,a,c,m),new Error(m)}if(i.Role&&i.Role!==o.Role)try{await h.setCustomUserClaims(o.User_ID,{...d,role:i.Role}),await h.revokeRefreshTokens(o.User_ID)}catch{throw await Qt(o.User_ID,a,c,m),new Error(m)}try{await f.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:d.collection,Doc_ID:d.doc,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await Qt(o.User_ID,a,c,m),new Error(m)}if(o.Email!==i.Email){const w=s.auth.enableMultiFactorAuth;if(w===!0||typeof w=="object"&&w.includes(i.Role)){let b=await h.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(b.includes("apiKey=&")){const N=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);b=b.replace("apiKey=&",`apiKey=${N.apiKey}&`)}if(b){const N=`https://${h.app.options.projectId}.firebaseapp.com/__/auth/action${b}`,p=await ie(s.appName),T=s?.mail?.emailVerification&&s.mail.emailVerification(N,p);try{await rr(i.Email,T?.subject||"Please verify your email address",void 0,T?.html||`Please verify your email address by clicking the link:
|
|
12
12
|
</br>
|
|
13
13
|
</br>
|
|
14
|
-
<a href="${N}">${N}</a>`)}catch{throw await Qt(o.User_ID,a,c,m),new Error(m)}}}}}else if(n==="delete")try{await Ut(o)}catch(y){throw new Error(y.message)}if(O)return O},Yc=async(n,e,t)=>{const s=Ye(),r=H.getFirestore(),i=[e];t&&t.trim()!==""&&i.push(t),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await n.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)n.set(a,{locked:!0})},ii=async(n,e)=>{const t=Ye(),s=H.getFirestore(),r=[n];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(t).collection("system_locks").doc(o);i.delete(a)}await i.commit()},Vo=async(n,e,t,s,r,i,o)=>{const a=Ye(),l=Vt();let c=await je(!0);if(n.length===0)throw new Error("EMPTY_PATH");const u=n.at(-1),h=Object.keys(c.collections).includes(u),f=l.disabledCollections?.includes(u);if(!h||f)throw new Error("COLLECTION_NOT_FOUND");const d=c.collections[u],{labels:m,fields:O,enableWriteLog:y}=d,w=Je(m.collection,c),b=await ie(l.appName),N=yt.getAuth(),p=H.getFirestore();let T;r&&await sr(n,d);const C=Te(p,n,a);o=o||{},o.collection=m.collection;let v=await Ge(n,e,{user:r,noComputedFields:!0,noEmbeddingFields:!0});for(const S of O)S.type==="Computed"&&delete t[S.name];if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([S,q])=>[S,{...q,fields:q.fields.filter(B=>B.type!=="Computed")}]))},s&&!s.operation)throw new Error("VALIDATION_ERROR: User operation is required");if(s&&!d.auth)throw new Error("VALIDATION_ERROR: User operations are only permitted for auth collections");if(s?.operation==="delete"&&s.permissions)throw new Error("VALIDATION_ERROR: Permissions are not allowed for delete operations");const Z=d.auth&&s?.operation==="create",x=d.auth&&s?.operation==="delete",g=d.auth&&!Z&&!x&&(s?.operation==="update"||t.Role||t.Enabled!==void 0||t.Name||t.Email||t.Photo_URL),k=S=>S.User_ID&&(d.auth&&!Z&&!x&&s?.operation==="update"||t.Role&&t.Role!==S.Role||t.Enabled!==void 0&&t.Enabled!==S.Enabled||t.Name&&t.Name!==S.Name||t.Email&&t.Email!==S.Email||t.Photo_URL&&t.Photo_URL!==S.Photo_URL);delete t.id,rr(t),Gn(t);const _=Us("update",n,t,c,b,"Online",r||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp()),A=pe(_);for(const S of O)!X(S)&&Ne(_[S.name])&&S.nullable&&(_[S.name]=null);Le(_),Le(v),y&&await pt("update","started",_,a,n,e,d,void 0,v);const E=["update",_,e,o,void 0,pe(v)];await le("preOperation",l,w,E);const I=["update",_,e,o,void 0,pe(v)];await le("preWrite",l,w,I),bn(d,_,c),Sn(d,_),Le(_);try{if(Z&&!s.password)throw new Error("Password is required");const S={...v,..._};await $o("update",a,e,S,d,c),nt(S),await sn("update",S,d,w,["update",_,o,void 0,pe(v)],c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}Le(_),delete t.id,bn(d,_,c),Sn(d,_);for(const S of O)!X(S)&&Ne(_[S.name])&&S.nullable&&(_[S.name]=null);try{const S={...v,..._};nt(S),or("update",d,_,v),Mo("update",_,A),await sn("update",S,d,w,["update",_,o,void 0,v],c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}let R;s&&(s.permissions||={});const M=async(S,q,B)=>{const[oe,Qe,Wt,me,ae]=await Promise.all([S.get(p.collection("system_deployment").doc("latest_deploy")),S.get(p.collection("system_deployment").doc("maintenance_mode")),Ge(n,e,{user:r,providedTransaction:S,noComputedFields:!0}),r?S.get(p.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve(Promise.resolve({})),je()]);if(B&&(B.size+=3),!oe.exists)throw new Error("VERSION_ERROR");const Pe=oe.data();if(Pe.force&&_.Last_Write_At.valueOf()<Pe.time.valueOf())throw new Error("VERSION_ERROR");if(!Qe.exists)throw new Error("MAINTENANCE_MODE");if(Qe.data().active)throw new Error("MAINTENANCE_MODE");if(!Wt)throw new Error("NOT_FOUND");if(v=Wt,c=ae,r){if(!me?.exists)throw new Error("PERMISSION_DENIED");if(T=me.data(),!T.Role)throw new Error("USER_ERROR");if(!T.Enabled)throw new Error("PERMISSION_DENIED")}if(B&&(B.size+=Ks(a,n,e,c,T).length),Z&&v.User_ID||x&&!v.User_ID)throw new Error("USER_ERROR");if(k(v)){const de=await S.get(p.collection("tenants").doc(a).collection("system_user_permissions").doc(v.User_ID));if(B&&B.size++,!de?.exists)throw new Error("PERMISSION_DENIED");if(R=de.data(),s?.permissions){if(s.permissions.Role||=_.Role||v.Role,s.permissions.Enabled??=_.Enabled??v.Enabled,Ne(s.permissions.Role))throw new Error("VALIDATION_ERROR: Role field is required");if(Ne(s.permissions.Enabled))throw new Error("VALIDATION_ERROR: Enabled field is required")}}const ar=O.filter(de=>"unique"in de&&de.unique).map(async de=>{if(!r||!de.access||de.access.includes(T.Role)){if(_[de.name]===void 0||Ne(_[de.name]))return;const jt=Ie(de,w),lr={...v,..._};if(!(r&&jt?.custom?.serverAccess?.read!==void 0?await ie(jt.custom.serverAccess.read,[T?.Role,lr]):!0))throw new Error("PERMISSION_DENIED");const Zt=_[de.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Qs(Zt)){if(B&&B.size++,B&&B.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");const Qn=await S.get(p.collection("tenants").doc(a).collection("system_unique").doc(m.collection).collection(`Unique-${m.collection}-${de.name}`).doc(Zt));if(Qn.exists&&Qn.data().id!==e)throw new Error(`VALIDATION_ERROR: ${de.name} "${_[de.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${de.name} "${_[de.name]}" is invalid`)}});if(await Promise.all(ar),r&&T?.Role){const de=T.Role,jt={...v,..._};if(!(w.custom?.serverAccess?.update!==void 0?await ie(w.custom.serverAccess.update,[de,jt,v]):!0))throw new Error("PERMISSION_DENIED");for(const Jn of d.fields){const Zt=Ie(Jn,w);if(Object.prototype.hasOwnProperty.call(_,Jn.name)&&Zt?.custom?.serverAccess?.update!==void 0&&!await ie(Zt.custom.serverAccess.update,[de,jt,v]))throw new Error("PERMISSION_DENIED")}}dr(_,v,e,d,c,r,T,s?.operation?s.operation:g?"update":void 0,s?.permissions,R),s?.permissions&&r&&T&&await Po(S,s.permissions,r,T,c,R,B),dr(_,v,e,d,c,r,T,s?.operation?s.operation:g?"update":void 0,s?.permissions,R),q&&(Z||k(v)||x)&&await Yc(S,e,v.User_ID)};(Z||g||x)&&await p.runTransaction(async S=>{await M(S,!0)},{maxAttempts:10});try{let S;if(Z||k(v)||x){if(k(v)){S=await N.getUser(v.User_ID);const oe=S.customClaims;if(!(oe&&oe.role&&oe.collection&&oe.doc))throw new Error("USER_ERROR")}const q={...v,..._};nt(q);const B=await Lo(s?.operation||"update",a,e,l,m.collection,q,v,S,s?.permissions,R,s?.password);Z&&(_.User_ID=B),x&&(_.User_ID=H.FieldValue.delete())}try{const q={size:1};await p.runTransaction(async B=>{const oe={...v,..._};await M(B,!1,q);let Qe;i?.noTwoWay||(Qe=await ir("Update",a,e,oe,_,d,c,B,q,r,T,v));const Wt=Vs(c);Js("update",B,n,e,_,c,d,i,Wt,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.FieldValue.delete,me=>p.collection("tenants").doc(a).collection("system_fields").doc(m.collection).collection(`${m.collection}-${me.name}`).doc(e),(me,ae)=>p.collection("tenants").doc(a).collection("system_unique").doc(m.collection).collection(`Unique-${m.collection}-${me.name}`).doc(ae),me=>p.collection("tenants").doc(a).collection("system_fields").doc(m.collection).collection(`${m.collection}-${me}`).doc(e),(me,ae)=>Te(p,me,a).doc(ae),(me,ae,Pe)=>p.collection("tenants").doc(a).collection("system_fields").doc(me.collection).collection(`${me.collection}-${ae}`).doc(Pe),(me,ae,Pe)=>p.collection("tenants").doc(a).collection("system_fields").doc(me.collection).collection(`${me.collection}-${ae.replaceAll(" ","-")}`).doc(Pe),v,Qe,q),B.update(C.doc(e),_)},{maxAttempts:10})}catch(q){const B=["update",_,e,o,q,void 0,void 0,pe(v)],oe=await le("postWriteError",l,w,B);if(y&&(await new Promise(Qe=>{setTimeout(Qe,250)}),await pt("update",oe?.resolved?"success":"failed",_,a,n,e,d,oe?.resolved?void 0:q,v)),!oe?.resolved)throw Z&&await Ut(v),k(v)&&await Qt(v.User_ID,S,R,"USER_ERROR"),x&&await p.collection("tenants").doc(a).collection(m.collection).doc(e).update({User_ID:H.FieldValue.delete()}),q}(Z||k(v)||x)&&await ni(ii,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")})}catch(S){throw(Z||k(v)||x)&&await ni(ii,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),S}const $=["update",_,e,o,void 0,pe(v)],P=[...$];await le("postWrite",l,w,$),await le("postOperation",l,w,P);const j={...v,..._};return nt(j),{id:e,...j}},Jc=async(n,e,t,s,r)=>{const i=Ye(),o=Vt();let a=await je();if(n.length===0)throw new Error("EMPTY_PATH");const l=n.at(-1),c=Object.keys(a.collections).includes(l),u=o.disabledCollections?.includes(l);if(!c||u)throw new Error("COLLECTION_NOT_FOUND");const h=a.collections[l],{labels:f,auth:d,enableWriteLog:m,softDelete:O}=h,y=Je(f.collection,a),w=await ie(o.appName);if(O&&!d&&!s?.force)return await Vo(n,e,{[O.archivedField]:!0,[O.timestampField]:H.FieldValue.serverTimestamp()},void 0,t);const b=H.getFirestore();let N;t&&await sr(n,h);const p=Te(b,n,i);r=r||{},r.collection=f.collection;const T=await Ge(n,e,{user:t});let C=Us("delete",n,T,a,w,"Online",t||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp());const v=kn(C);Le(C),m&&await pt("delete","started",C,i,n,e,h),await le("preOperation",o,y,["delete",C,e,r]),await le("preWrite",o,y,["delete",C,e,r]),Le(C);const g=async E=>{const[I,R,M,$]=await Promise.all([E.get(b.collection("system_deployment").doc("maintenance_mode")),Ge([f.collection],e,{user:t,providedTransaction:E}),t?E.get(b.collection("tenants").doc(i).collection("system_user_permissions").doc(t)):Promise.resolve(Promise.resolve({})),je()]);if(!I.exists)throw new Error("MAINTENANCE_MODE");if(I.data().active)throw new Error("MAINTENANCE_MODE");if(!R)throw new Error("NOT_FOUND");if(C={...R,...v},a=$,t){if(!M?.exists)throw new Error("PERMISSION_DENIED");if(N=M.data(),!N.Role)throw new Error("USER_ERROR");if(!N.Enabled)throw new Error("PERMISSION_DENIED");Xo(C,e,h,a,t,N)}if(t&&N?.Role){const j=N.Role;if(!(y.custom?.serverAccess?.delete!==void 0?await ie(y.custom.serverAccess.delete,[j,C]):!0))throw new Error("PERMISSION_DENIED")}};h.auth&&(await b.runTransaction(async E=>{await g(E)},{maxAttempts:10}),C.User_ID&&await Ut(C));try{await b.runTransaction(async E=>{await g(E);const I=Vs(a);Js("delete",E,n,e,C,a,h,s,I,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.FieldValue.delete,R=>b.collection("tenants").doc(i).collection("system_fields").doc(f.collection).collection(`${f.collection}-${R.name}`).doc(e),(R,M)=>b.collection("tenants").doc(i).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${R.name}`).doc(M),R=>b.collection("tenants").doc(i).collection("system_fields").doc(f.collection).collection(`${f.collection}-${R}`).doc(e),(R,M)=>Te(b,R,i).doc(M),(R,M,$)=>b.collection("tenants").doc(i).collection("system_fields").doc(R.collection).collection(`${R.collection}-${M}`).doc($),(R,M,$)=>b.collection("tenants").doc(i).collection("system_fields").doc(R.collection).collection(`${R.collection}-${M.replaceAll(" ","-")}`).doc($)),E.delete(p.doc(e))},{maxAttempts:10})}catch(E){const R=await le("postWriteError",o,y,["delete",C,e,r,E]);if(m&&(await new Promise(M=>{setTimeout(M,250)}),await pt("delete",R?.resolved?"success":"failed",C,i,n,e,h,R?.resolved?void 0:E)),!R?.resolved)throw h.auth&&C.User_ID&&await b.collection("tenants").doc(i).collection(f.collection).doc(e).update({User_ID:H.FieldValue.delete()}),E}const k=["delete",C,e,r],_=[...k];return await le("postWrite",o,y,k),await le("postOperation",o,y,_),{id:e,...C}},Qc=async(n,e)=>{const t=H.getFirestore(),s=xo(),r=process.env.ADMIN_SMS;if(s==="development")if(r)n=r;else throw new Error("Admin phone not set");const i={to:n,body:e};await t.collection("system_messages").add(i)},Kc=n=>n!==null&&typeof n=="object",Xc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{r instanceof H.Timestamp?t[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:Kc(r)&&e(r)})};e(n)},eu=async n=>await yt.getAuth().getUser(n),tu=n=>{const e=Do();return V.fromJSDate(n).setZone(e)},Uo=n=>{const e=Do();return V.fromJSDate(n.toDate()).setZone(e)},nu=(n,e)=>{const s=V.fromJSDate(n,{zone:e}).offset,i=V.fromJSDate(n).offset,o=s-i;return V.fromJSDate(n).plus({minutes:o}).toJSDate()},su=(n,e)=>{const s=V.fromJSDate(n,{zone:e}).offset,i=V.fromJSDate(n).offset,o=s-i;return V.fromJSDate(n).minus({minutes:o}).toJSDate()},ru=n=>"seconds"in n&&"nanoseconds"in n?Uo(new H.Timestamp(n.seconds,n.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=Gc;exports.addUser=nr;exports.convertDateToTimezone=tu;exports.convertTimestampToTimezone=Uo;exports.deleteRecord=Jc;exports.deleteUser=Ut;exports.deserializeDeleteSentinels=Gn;exports.deserializeTimestamps=rr;exports.deserializeTimestampsWithoutUnderscores=Zc;exports.displayDate=ru;exports.fetchCurrentSchema=je;exports.fetchLastSchema=jc;exports.getCachedConfigValue=ia;exports.getCollectionRefs=Io;exports.getCustomizationFiles=bo;exports.getDocumentRefs=Ks;exports.getFirestorePathRef=Te;exports.getInputSchema=Vc;exports.getOne=Ge;exports.getSome=er;exports.getUser=eu;exports.getZodSchema=Ei;exports.initializeFirebase=Bo;exports.initializeStoker=Wc;exports.isDeleteSentinel=Ne;exports.keepTimezone=nu;exports.removeTimezone=su;exports.runChildProcess=qo;exports.sendMail=tr;exports.sendMessage=Qc;exports.serializeTimestamps=Xc;exports.tryPromise=ie;exports.updateRecord=Vo;exports.updateUser=Lo;exports.validateRelations=ir;exports.validateSoftDelete=or;exports.writeLog=pt;
|
|
14
|
+
<a href="${N}">${N}</a>`)}catch{throw await Qt(o.User_ID,a,c,m),new Error(m)}}}}}else if(n==="delete")try{await Ut(o)}catch(y){throw new Error(y.message)}if(O)return O},Kc=async(n,e,t)=>{const s=Ze(),r=H.getFirestore(),i=[e];t&&t.trim()!==""&&i.push(t),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await n.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)n.set(a,{locked:!0})},li=async(n,e)=>{const t=Ze(),s=H.getFirestore(),r=[n];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(t).collection("system_locks").doc(o);i.delete(a)}await i.commit()},Vo=async(n,e,t,s,r,i,o)=>{const a=Ze(),l=Et();let c=await je(!0);if(n.length===0)throw new Error("EMPTY_PATH");const u=n.at(-1),h=Object.keys(c.collections).includes(u),f=l.disabledCollections?.includes(u);if(!h||f)throw new Error("COLLECTION_NOT_FOUND");const d=c.collections[u],{labels:m,fields:O,enableWriteLog:y}=d,w=ze(m.collection,c),b=await ie(l.appName),N=yt.getAuth(),p=H.getFirestore();let T;r&&await or(n,d);const C=Te(p,n,a);o=o||{},o.collection=m.collection;let v=await Je(n,e,{user:r,noComputedFields:!0,noEmbeddingFields:!0});for(const S of O)S.type==="Computed"&&delete t[S.name];if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([S,q])=>[S,{...q,fields:q.fields.filter(B=>B.type!=="Computed")}]))},s&&!s.operation)throw new Error("VALIDATION_ERROR: User operation is required");if(s&&!d.auth)throw new Error("VALIDATION_ERROR: User operations are only permitted for auth collections");if(s?.operation==="delete"&&s.permissions)throw new Error("VALIDATION_ERROR: Permissions are not allowed for delete operations");const Z=d.auth&&s?.operation==="create",x=d.auth&&s?.operation==="delete",g=d.auth&&!Z&&!x&&(s?.operation==="update"||t.Role||t.Enabled!==void 0||t.Name||t.Email||t.Photo_URL),k=S=>S.User_ID&&(d.auth&&!Z&&!x&&s?.operation==="update"||t.Role&&t.Role!==S.Role||t.Enabled!==void 0&&t.Enabled!==S.Enabled||t.Name&&t.Name!==S.Name||t.Email&&t.Email!==S.Email||t.Photo_URL&&t.Photo_URL!==S.Photo_URL);delete t.id,ar(t),Yn(t);const _=Ws("update",n,t,c,b,"Online",r||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp()),A=pe(_);for(const S of O)!X(S)&&Ne(_[S.name])&&S.nullable&&(_[S.name]=null);Le(_),Le(v),y&&await pt("update","started",_,a,n,e,d,void 0,v);const E=["update",_,e,o,void 0,pe(v)];await le("preOperation",l,w,E);const I=["update",_,e,o,void 0,pe(v)];await le("preWrite",l,w,I),Sn(d,_,c),Tn(d,_),Le(_);try{if(Z&&!s.password)throw new Error("Password is required");const S={...v,..._};await $o("update",a,e,S,d,c),nt(S),await sn("update",S,d,w,["update",_,o,void 0,pe(v)],c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}Le(_),delete t.id,Sn(d,_,c),Tn(d,_);for(const S of O)!X(S)&&Ne(_[S.name])&&S.nullable&&(_[S.name]=null);try{const S={...v,..._};nt(S),cr("update",d,_,v),Mo("update",_,A),await sn("update",S,d,w,["update",_,o,void 0,v],c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}let R;s&&(s.permissions||={});const M=async(S,q,B)=>{const[oe,Qe,Wt,me,ae]=await Promise.all([S.get(p.collection("system_deployment").doc("latest_deploy")),S.get(p.collection("system_deployment").doc("maintenance_mode")),Je(n,e,{user:r,providedTransaction:S,noComputedFields:!0}),r?S.get(p.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve(Promise.resolve({})),je()]);if(B&&(B.size+=3),!oe.exists)throw new Error("VERSION_ERROR");const Pe=oe.data();if(Pe.force&&_.Last_Write_At.valueOf()<Pe.time.valueOf())throw new Error("VERSION_ERROR");if(!Qe.exists)throw new Error("MAINTENANCE_MODE");if(Qe.data().active)throw new Error("MAINTENANCE_MODE");if(!Wt)throw new Error("NOT_FOUND");if(v=Wt,c=ae,r){if(!me?.exists)throw new Error("PERMISSION_DENIED");if(T=me.data(),!T.Role)throw new Error("USER_ERROR");if(!T.Enabled)throw new Error("PERMISSION_DENIED")}if(B&&(B.size+=tr(a,n,e,c,T).length),Z&&v.User_ID||x&&!v.User_ID)throw new Error("USER_ERROR");if(k(v)){const de=await S.get(p.collection("tenants").doc(a).collection("system_user_permissions").doc(v.User_ID));if(B&&B.size++,!de?.exists)throw new Error("PERMISSION_DENIED");if(R=de.data(),s?.permissions){if(s.permissions.Role||=_.Role||v.Role,s.permissions.Enabled??=_.Enabled??v.Enabled,Ne(s.permissions.Role))throw new Error("VALIDATION_ERROR: Role field is required");if(Ne(s.permissions.Enabled))throw new Error("VALIDATION_ERROR: Enabled field is required")}}const ur=O.filter(de=>"unique"in de&&de.unique).map(async de=>{if(!r||!de.access||de.access.includes(T.Role)){if(_[de.name]===void 0||Ne(_[de.name]))return;const jt=Ie(de,w),dr={...v,..._};if(!(r&&jt?.custom?.serverAccess?.read!==void 0?await ie(jt.custom.serverAccess.read,[T?.Role,dr]):!0))throw new Error("PERMISSION_DENIED");const Zt=_[de.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Ks(Zt)){if(B&&B.size++,B&&B.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");const Kn=await S.get(p.collection("tenants").doc(a).collection("system_unique").doc(m.collection).collection(`Unique-${m.collection}-${de.name}`).doc(Zt));if(Kn.exists&&Kn.data().id!==e)throw new Error(`VALIDATION_ERROR: ${de.name} "${_[de.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${de.name} "${_[de.name]}" is invalid`)}});if(await Promise.all(ur),r&&T?.Role){const de=T.Role,jt={...v,..._};if(!(w.custom?.serverAccess?.update!==void 0?await ie(w.custom.serverAccess.update,[de,jt,v]):!0))throw new Error("PERMISSION_DENIED");for(const Qn of d.fields){const Zt=Ie(Qn,w);if(Object.prototype.hasOwnProperty.call(_,Qn.name)&&Zt?.custom?.serverAccess?.update!==void 0&&!await ie(Zt.custom.serverAccess.update,[de,jt,v]))throw new Error("PERMISSION_DENIED")}}mr(_,v,e,d,c,r,T,s?.operation?s.operation:g?"update":void 0,s?.permissions,R),s?.permissions&&r&&T&&await Po(S,s.permissions,r,T,c,R,B),mr(_,v,e,d,c,r,T,s?.operation?s.operation:g?"update":void 0,s?.permissions,R),q&&(Z||k(v)||x)&&await Kc(S,e,v.User_ID)};(Z||g||x)&&await p.runTransaction(async S=>{await M(S,!0)},{maxAttempts:10});try{let S;if(Z||k(v)||x){if(k(v)){S=await N.getUser(v.User_ID);const oe=S.customClaims;if(!(oe&&oe.role&&oe.collection&&oe.doc))throw new Error("USER_ERROR")}const q={...v,..._};nt(q);const B=await Lo(s?.operation||"update",a,e,l,m.collection,q,v,S,s?.permissions,R,s?.password);Z&&(_.User_ID=B),x&&(_.User_ID=H.FieldValue.delete())}try{const q={size:1};await p.runTransaction(async B=>{const oe={...v,..._};await M(B,!1,q);let Qe;i?.noTwoWay||(Qe=await lr("Update",a,e,oe,_,d,c,B,q,r,T,v));const Wt=Us(c);Qs("update",B,n,e,_,c,d,i,Wt,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.FieldValue.delete,me=>p.collection("tenants").doc(a).collection("system_fields").doc(m.collection).collection(`${m.collection}-${me.name}`).doc(e),(me,ae)=>p.collection("tenants").doc(a).collection("system_unique").doc(m.collection).collection(`Unique-${m.collection}-${me.name}`).doc(ae),me=>p.collection("tenants").doc(a).collection("system_fields").doc(m.collection).collection(`${m.collection}-${me}`).doc(e),(me,ae)=>Te(p,me,a).doc(ae),(me,ae,Pe)=>p.collection("tenants").doc(a).collection("system_fields").doc(me.collection).collection(`${me.collection}-${ae}`).doc(Pe),(me,ae,Pe)=>p.collection("tenants").doc(a).collection("system_fields").doc(me.collection).collection(`${me.collection}-${ae.replaceAll(" ","-")}`).doc(Pe),v,Qe,q),B.update(C.doc(e),_)},{maxAttempts:10})}catch(q){const B=["update",_,e,o,q,void 0,void 0,pe(v)],oe=await le("postWriteError",l,w,B);if(y&&(await new Promise(Qe=>{setTimeout(Qe,250)}),await pt("update",oe?.resolved?"success":"failed",_,a,n,e,d,oe?.resolved?void 0:q,v)),!oe?.resolved)throw Z&&await Ut(v),k(v)&&await Qt(v.User_ID,S,R,"USER_ERROR"),x&&await p.collection("tenants").doc(a).collection(m.collection).doc(e).update({User_ID:H.FieldValue.delete()}),q}(Z||k(v)||x)&&await ii(li,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")})}catch(S){throw(Z||k(v)||x)&&await ii(li,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),S}const $=["update",_,e,o,void 0,pe(v)],P=[...$];await le("postWrite",l,w,$),await le("postOperation",l,w,P);const j={...v,..._};return nt(j),{id:e,...j}},Xc=async(n,e,t,s,r)=>{const i=Ze(),o=Et();let a=await je();if(n.length===0)throw new Error("EMPTY_PATH");const l=n.at(-1),c=Object.keys(a.collections).includes(l),u=o.disabledCollections?.includes(l);if(!c||u)throw new Error("COLLECTION_NOT_FOUND");const h=a.collections[l],{labels:f,auth:d,enableWriteLog:m,softDelete:O}=h,y=ze(f.collection,a),w=await ie(o.appName);if(O&&!d&&!s?.force)return await Vo(n,e,{[O.archivedField]:!0,[O.timestampField]:H.FieldValue.serverTimestamp()},void 0,t);const b=H.getFirestore();let N;t&&await or(n,h);const p=Te(b,n,i);r=r||{},r.collection=f.collection;const T=await Je(n,e,{user:t});let C=Ws("delete",n,T,a,w,"Online",t||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp());const v=bn(C);Le(C),m&&await pt("delete","started",C,i,n,e,h),await le("preOperation",o,y,["delete",C,e,r]),await le("preWrite",o,y,["delete",C,e,r]),Le(C);const g=async E=>{const[I,R,M,$]=await Promise.all([E.get(b.collection("system_deployment").doc("maintenance_mode")),Je([f.collection],e,{user:t,providedTransaction:E}),t?E.get(b.collection("tenants").doc(i).collection("system_user_permissions").doc(t)):Promise.resolve(Promise.resolve({})),je()]);if(!I.exists)throw new Error("MAINTENANCE_MODE");if(I.data().active)throw new Error("MAINTENANCE_MODE");if(!R)throw new Error("NOT_FOUND");if(C={...R,...v},a=$,t){if(!M?.exists)throw new Error("PERMISSION_DENIED");if(N=M.data(),!N.Role)throw new Error("USER_ERROR");if(!N.Enabled)throw new Error("PERMISSION_DENIED");Qo(C,e,h,a,t,N)}if(t&&N?.Role){const j=N.Role;if(!(y.custom?.serverAccess?.delete!==void 0?await ie(y.custom.serverAccess.delete,[j,C]):!0))throw new Error("PERMISSION_DENIED")}};h.auth&&(await b.runTransaction(async E=>{await g(E)},{maxAttempts:10}),C.User_ID&&await Ut(C));try{await b.runTransaction(async E=>{await g(E);const I=Us(a);Qs("delete",E,n,e,C,a,h,s,I,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.FieldValue.delete,R=>b.collection("tenants").doc(i).collection("system_fields").doc(f.collection).collection(`${f.collection}-${R.name}`).doc(e),(R,M)=>b.collection("tenants").doc(i).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${R.name}`).doc(M),R=>b.collection("tenants").doc(i).collection("system_fields").doc(f.collection).collection(`${f.collection}-${R}`).doc(e),(R,M)=>Te(b,R,i).doc(M),(R,M,$)=>b.collection("tenants").doc(i).collection("system_fields").doc(R.collection).collection(`${R.collection}-${M}`).doc($),(R,M,$)=>b.collection("tenants").doc(i).collection("system_fields").doc(R.collection).collection(`${R.collection}-${M.replaceAll(" ","-")}`).doc($)),E.delete(p.doc(e))},{maxAttempts:10})}catch(E){const R=await le("postWriteError",o,y,["delete",C,e,r,E]);if(m&&(await new Promise(M=>{setTimeout(M,250)}),await pt("delete",R?.resolved?"success":"failed",C,i,n,e,h,R?.resolved?void 0:E)),!R?.resolved)throw h.auth&&C.User_ID&&await b.collection("tenants").doc(i).collection(f.collection).doc(e).update({User_ID:H.FieldValue.delete()}),E}const k=["delete",C,e,r],_=[...k];return await le("postWrite",o,y,k),await le("postOperation",o,y,_),{id:e,...C}},eu=async(n,e)=>{const t=H.getFirestore(),s=Xs(),r=process.env.ADMIN_SMS;if(s==="development")if(r)n=r;else throw new Error("Admin phone not set");const i={to:n,body:e};await t.collection("system_messages").add(i)},tu=n=>n!==null&&typeof n=="object",nu=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{r instanceof H.Timestamp?t[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:tu(r)&&e(r)})};e(n)},su=async n=>await yt.getAuth().getUser(n),ru=n=>{const e=er();return V.fromJSDate(n).setZone(e)},Uo=n=>{const e=er();return V.fromJSDate(n.toDate()).setZone(e)},iu=(n,e)=>{const s=V.fromJSDate(n,{zone:e}).offset,i=V.fromJSDate(n).offset,o=s-i;return V.fromJSDate(n).plus({minutes:o}).toJSDate()},ou=(n,e)=>{const s=V.fromJSDate(n,{zone:e}).offset,i=V.fromJSDate(n).offset,o=s-i;return V.fromJSDate(n).minus({minutes:o}).toJSDate()},au=n=>"seconds"in n&&"nanoseconds"in n?Uo(new H.Timestamp(n.seconds,n.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=Qc;exports.addUser=ir;exports.convertDateToTimezone=ru;exports.convertTimestampToTimezone=Uo;exports.deleteRecord=Xc;exports.deleteUser=Ut;exports.deserializeDeleteSentinels=Yn;exports.deserializeTimestamps=ar;exports.deserializeTimestampsWithoutUnderscores=Bc;exports.displayDate=au;exports.fetchCurrentSchema=je;exports.fetchLastSchema=qc;exports.getCachedConfigValue=sa;exports.getCollectionRefs=Io;exports.getCustomizationFile=ze;exports.getCustomizationFiles=Ro;exports.getDocumentRefs=tr;exports.getFirestorePathRef=Te;exports.getGlobalConfigModule=Et;exports.getInputSchema=Pc;exports.getMaintenanceInfo=jc;exports.getMode=Xs;exports.getOne=Je;exports.getSome=sr;exports.getTenant=Ze;exports.getTimezone=er;exports.getUser=su;exports.getVersionInfo=Wc;exports.getZodSchema=ki;exports.initializeFirebase=zc;exports.initializeStoker=Vc;exports.isDeleteSentinel=Ne;exports.keepTimezone=iu;exports.removeTimezone=ou;exports.runChildProcess=Zc;exports.sendMail=rr;exports.sendMessage=eu;exports.serializeTimestamps=nu;exports.setTenant=Uc;exports.tryPromise=ie;exports.updateRecord=Vo;exports.updateUser=Lo;exports.validateRelations=lr;exports.validateSoftDelete=cr;exports.writeLog=pt;
|