@stoker-platform/node-client 0.2.5 → 0.2.7

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 CHANGED
@@ -1,14 +1,14 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Vo=require("node:child_process"),St=require("firebase-admin/app"),ze=require("lodash/isEqual.js"),Uo=require("lodash/merge.js"),Wo=require("lodash/set.js"),me=require("lodash/cloneDeep.js"),B=require("firebase-admin/firestore"),ii=require("firebase-admin/database"),pt=require("firebase-admin/auth"),jo=async(n,e,t,s)=>new Promise((r,i)=>{const o=Vo.spawn(n,e,{cwd:t||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},d=()=>{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=>{d(),h===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),Zo=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 St.getApp()}catch{return St.initializeApp({credential:St.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},Vn=n=>!!n.auth,Se=(n,e)=>{if(e?.operations)return e.operations.includes(n)},Un=(n,e)=>e?e.Role?n.access?.includes(e.Role):!1:!0,zo=(n,e)=>n.restrictCreate===!0?!1:e&&typeof n.restrictCreate=="object"?e.Role?n.restrictCreate?.includes(e.Role):!1:!0,oi=(n,e)=>n.restrictUpdate===!0?!1:e&&typeof n.restrictUpdate=="object"?e.Role?n.restrictUpdate?.includes(e.Role):!1:!0,lr=(n,e,t)=>{const{labels:s}=n;return t.collections&&Se("Update",t.collections[s.collection])&&(!e.access||Un(e,t))&&oi(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),ai=(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 d=a?.[t[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},Ms=(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},li=(n,e,t)=>{const s=[],{access:r}=n,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.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 u=h.restrictions?.find(f=>f.type===o.type&&f.roles.some(w=>w.role===t.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===t.Role&&(!h.assignable?.includes(t.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},ci=(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&&!Un(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},qo=(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=ai(e,r),d=Ms(e,r),h=li(e,t,r);c?.filter(g=>g.type==="Record_Owner").forEach(g=>{"operations"in g&&g.operations&&!g.operations.includes(n)||i.Created_By!==s&&(l=!1)}),c?.filter(g=>g.type==="Record_User").forEach(g=>{if("operations"in g&&g.operations&&!g.operations.includes(n))return;const T=W(o,g.collectionField);i[`${T.name}_Array`]?.includes(r.Doc_ID)||(l=!1)}),c?.filter(g=>g.type==="Record_Property").forEach(g=>{if("operations"in g&&g.operations&&!g.operations.includes(n))return;const T=W(o,g.propertyField),_=g.roles.find(P=>P.role===r.Role);T.type==="Array"?_.values?.some(P=>i[T.name].includes(P))||(l=!1):_.values?.includes(i[T.name])||(l=!1)});let u=!0,f=!1;d?.filter(g=>g.type==="Individual").forEach(()=>{f=!0,a.individualEntities?.includes(i.id)||(u=!1)});let w=!0,E=!1;if(d?.filter(g=>g.type==="Parent").forEach(g=>{E=!0;const T=W(o,g.collectionField);a.parentEntities?.some(_=>i[`${T.name}_Array`].includes(_))||(w=!1)}),d?.filter(g=>g.type==="Parent_Property").forEach(g=>{E=!0;const T=W(o,g.collectionField),_=W(o,g.propertyField);Object.entries(a.parentPropertyEntities||{}).some(P=>{const[x,M]=P;return x===i[_.name]&&i[`${T.name}_Array`].some(m=>M.includes(m))})||(w=!1)}),f&&E){if(!(u||w)){l=!1;return}}else if(!u||!w){l=!1;return}let p=!0,k=!1;h?.filter(g=>g.parentFilter.type==="Individual").forEach(g=>{k=!0;const{parentFilter:T}=g,_=W(o,T.collectionField),P=r.collections?.[_.collection];if(!P){l=!1;return}P.individualEntities?.some(x=>i[`${_.name}_Array`].includes(x))||(p=!1)});let b=!0,R=!1;if(h?.filter(g=>g.parentFilter.type==="Parent").forEach(g=>{R=!0;const{parentFilter:T}=g,_=W(o,T.collectionField),P=W(o,T.parentCollectionField),x=r.collections?.[_.collection];if(!x){l=!1;return}x.parentEntities?.some(M=>i[`${P.name}_Array`].includes(M))||(b=!1)}),h?.filter(g=>g.parentFilter.type==="Parent_Property").forEach(g=>{R=!0;const{parentFilter:T}=g,_=W(o,T.collectionField),P=W(o,T.parentPropertyField),x=W(o,T.parentCollectionField),M=r.collections?.[_.collection];if(!M){l=!1;return}Object.entries(M.parentPropertyEntities||{}).some(m=>{const[S,v]=m;return S===i[P.name]&&i[`${x.name}_Array`].some(y=>v.includes(y))})||(b=!1)}),k&&R){if(!(p||b)){l=!1;return}}else if(!p||!b){l=!1;return}return l},rt=(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 d=Ms(e,r)?.filter(h=>h.type==="Individual").length>0;return n==="Create"&&d&&(l=!1),qo(n,e,t,s,r,i)||(l=!1),l},ui=(n,e,t)=>{const{labels:s}=n,r=[];for(const i of Object.values(e.collections));return r},Bo=(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 d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),h=i.access.entityRestrictions?.restrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(u=>n.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,t=!1;return}if(d?.length||h?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const u=Object.keys(l);if(u.length!==1||u[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 u=Object.keys(l);if(!(u.length===1&&Object.keys(n.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,t=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(n.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[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},Ho=(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:d,entityRestrictions:h}=a,u=c.assignable,f=e.collections?.[o.collection],w=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(t))?w.forEach(p=>{const k=p.charAt(0).toUpperCase()+p.slice(1);if(p!=="assignable"){const b=!!a.operations[p]?.includes(t),R=!!f?.operations.includes(k);if(!b&&R){r=`Collection ${o.collection} has excess ${p} operation for role ${t}`,s=!1;return}if(b&&!R){r=`Collection ${o.collection} has missing ${p} operation for role ${t}`,s=!1;return}}}):w.forEach(p=>{const k=p.charAt(0).toUpperCase()+p.slice(1);if(p!=="assignable"){const b=!!a.operations[p]?.includes(t),R=!!f?.operations.includes(k);if(!b&&R){r=`Collection ${o.collection} has excess ${p} operation for role ${t}`,s=!1;return}}}),!d&&!h||(d?.forEach(p=>{for(const k of p.roles)if(k.role===t&&!k.assignable){if(p.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(p.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(p.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 E=!1;if(h?.restrictions?.forEach(p=>{for(const k of p.roles)if(k.role===t){if(E=!0,p.type==="Individual"&&!e.collections?.[o.collection]?.individualEntities){r=`Collection ${o.collection} is missing individual entities`,s=!1;return}if(p.type==="Parent"){const b=W(l,p.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(p.type==="Parent_Property"){const b=W(l,p.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}}}}),E&&!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},Go=(n,e,t,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:d}=c;let h=!0,u="";const f=d?.filter(w=>s===w.userRole);return f?.length&&!f.some(w=>w.recordRole===r)?(u=`User ${s} does not have write access to record with role ${r}`,h=!1,h):n==="update"&&o.User_ID&&f?.length&&!f.some(w=>w.recordRole===a)?(u=`User ${s} does not have write access to record with role ${r}`,h=!1,h):(d?.forEach(w=>{s===w.userRole&&w.recordRole===r&&n!=="delete"&&i&&Object.keys(t.collections).forEach(E=>{const p=i.collections?.[E],k=l?.collections?.[E];if(!(n==="update"&&ze(p,k))&&p){const b=w.collections.some(R=>R.collection===E);if(b){if(b){const R=w.collections.find(T=>T.collection===E);if(!(p.operations.every(T=>R.operations.includes(T))||n==="update"&&ze(p.operations,k?.operations))){u=`User ${s} does not have write access to all included operations for collection ${E}`,h=!1;return}if(!R.auth&&p.auth&&!(n==="update"&&ze(p.auth,k?.auth))){u=`User ${s} does not have write access to auth for collection ${E}`,h=!1;return}const g={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(g).forEach(T=>{const _=g[T];if(R.attributeRestrictions?.includes(_)&&!(p[T]?.active||n==="update"&&ze(p[T],k?.[T]))){u=`User ${s} does not have write access to attribute restriction ${T} for collection ${E}`,h=!1;return}}),R.restrictEntities&&!p.restrictEntities&&!(n==="update"&&ze(p.restrictEntities,k?.restrictEntities))){u=`User ${s} does not have write access to restrictEntities for collection ${E}`,h=!1;return}}}else{u=`User ${s} does not have write access to collection ${E}`,h=!1;return}}})}),u&&console.error(`PERMISSION_DENIED: ${u}`),h)},Yo=(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&&!Vn(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const d of a?.operations||[])if(!l?.operations.includes(d)&&(!Se("Read",c)||!Se(d,c))){i=`User does not have ${d.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},Ps=(n,e,t,s,r,i,o,a,l,c,d)=>{const{labels:h}=s;let u=!0,f="";if(!e.Role)return f="Record does not have a role",u=!1,u;if(n==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(n==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!Go(n,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(n==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;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 f="User cannot update their own record",u=!1,u;if(n==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return n==="delete"||d==="delete"||!a?u:a.Role?(Bo(r,a)||(u=!1),a.Collection&&a.Collection!==h.collection?(f="Permissions collection does not match record collection",u=!1,u):a.Role!==e.Role?(f="Permissions role does not match record role",u=!1,u):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",u=!1,u):a.Doc_ID&&a.Doc_ID!==t?(f="Permissions doc ID does not match record doc ID",u=!1,u):!Ho(r,a,a.Role)||i&&o&&l&&!Yo(r,o,a,l)?(u=!1,u):(f&&console.error(`PERMISSION_DENIED: ${f}`),u)):(f="Permissions do not have a role",u=!1,u)},cr=(n,e,t,s,r,i,o)=>{const{labels:a,fields:l}=t,c=i?.collections?.[a.collection];let d=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!Se("Create",c)&&(d=!1),r&&!rt("Create",t,s,r,i,n)&&(d=!1),t.auth&&o&&(r&&!Vn(c)&&(d=!1),Ps("create",n,e,t,s,r,i,o)||(d=!1));for(const h of l){const u=n[h.name];h.access&&!Un(h,i)&&u!==void 0&&(d=!1),u!==void 0&&!zo(h,i)&&(d=!1)}if(!d)throw new Error("PERMISSION_DENIED")},Ne=n=>n&&(n._methodName==="deleteField"||n.constructor.name==="DeleteTransform"),et=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&&et(n[e]))},ur=(n,e,t,s,r,i,o,a,l,c)=>{const{labels:d,fields:h}=s,u=o?.collections?.[d.collection],f={...e,...n};et(f);let w=!0,E="";if(i&&!u)throw new Error("PERMISSION_DENIED");i&&!Se("Update",u)&&(w=!1,E="Authenticated user does not have Update access to this collection"),i&&(!rt("Update",s,r,i,o,e)||!rt("Update",s,r,i,o,f))&&(w=!1,E="Authenticated user does not have Update access to this document"),a&&(i&&!Vn(u)&&(w=!1,E="Authenticated user does not have Auth access for this collection"),Ps("update",f,t,s,r,i,o,l,c,e,a)||(E="Authenticated user does not have sufficient write access for this record",w=!1));for(const p of h){const k=n[p.name];p.access&&!Un(p,o)&&k!==void 0&&(E=`Authenticated user does not have access to field ${p.name}`,w=!1),k!==void 0&&!oi(p,o)&&(E=`Authenticated user does not have Update access to field ${p.name}`,w=!1)}if(!w)throw E&&console.error(`PERMISSION_DENIED: ${E}`),new Error("PERMISSION_DENIED")},Jo=(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),rt("Delete",t,s,r,i,n)||(l=!1),t.auth&&n.User_ID&&(Vn(a)||(l=!1),Ps("delete",n,e,t,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},Qo=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),rt("Read",e,t,s,r,n)||(a=!1),!a)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),n.forEach(l=>{rt("Read",e,t,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},Xo=(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)},ea=(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(d=>d.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},ta=(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 d in c)d==="custom"||d==="admin"||d==="name"||d==="formula"||delete c[d];i[o]=l}return i},Ie=(n,e)=>e.fields.filter(t=>t.name===n.name)[0],Qn={global:{},collections:{}},zt=(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},na=async(n,e,t,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=Qn,i=!0;for(const d of e){if(d===void 0||r[d]===void 0){i=!1;break}r=r[d]}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 d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await ie(a,t)),c){let d=Qn;const h={};for(let u=0;u<e.length;u++){const f=e[u];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");u===e.length-1?Wo(h,e.join("."),c):(d[f]||={},d=d[f])}}Uo(Qn,h)}return c},ot=(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},sa=(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},Kn=n=>JSON.stringify(n.map(e=>e.name)),ft=["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"],Wn=()=>ft.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}),di=(n,e)=>{const t=[],{access:s,fields:r}=n,{attributeRestrictions:i,entityRestrictions:o}=s,a=Wn();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=Wn();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=>{ft.includes(c)&&t.push(W(a,c))}),o?.forEach(c=>{const d=W(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&d&&(!d.access||d.access?.includes(e))&&ft.includes(c.field)&&t.push(W(a,c.field))}),di(n,e).forEach(c=>{ft.includes(c.name)&&t.push(W(a,c.name))}),[...new Set(t)]},ia=(n,e,t)=>{const s=[],{fields:r,preloadCache:i}=e,o=Wn();i?.range&&i.range.fields.forEach(c=>{ft.includes(c)?s.push(W(o,c)):s.push(W(r,c))});const a=new Set,l=sa(e,t);return Object.entries(l).map(([c,d])=>{n.name===c&&Object.values(d).forEach(h=>{h.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(...di(e,c))}),[...new Set(s)]},cn=(n,e,t)=>{const s=[],{fields:r,softDelete:i}=e;if(s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0}),i){const o=W(r,i.archivedField);o&&s.push(o)}return s.push(...ia(n,e,t)),[...new Set(s)]},fi=(n,e)=>{const{preloadCache:t}=n,s=new Set;for(const r of e.config.roles){if(!Xo(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},hi=(n,e,t)=>{const s=fi(e,t);for(const r of s.values())if(r.roles.includes(n))return r},oa=(n,e)=>{const{fields:t}=e,s=Wn(),r=[];return[...t,...s.filter(o=>o.name!=="id")].forEach(o=>{n?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ls=(n,e,t)=>{const s={};return Object.values(n.collections).forEach(r=>{const i=fi(r,n),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},On=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}),Xn=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 ae(n,e,t,s){const r=await Xn(n,t.custom?.[n],s);for(const i of t.fields)await Xn(n,i.custom?.[n],s);if(n!=="setEmbedding"&&(await Xn(n,e?.[n],s),n==="postWriteError"))return r}const Vs=(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),ct=(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},yt=(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},kn=(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);yt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(d=>{e[i.name][d][o]?e[i.name][d][`${o}_Lowercase`]=e[i.name][d][o].toLowerCase():delete e[i.name][d][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),ct(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}}}})},bn=(n,e)=>{yt(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]),yt(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 te;(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})(te||(te={}));var dr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(dr||(dr={}));const U=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Qe=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=te.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,te.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 ys=(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,te.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:t=`Unrecognized key(s) in object: ${te.joinValues(n.keys,", ")}`;break;case D.invalid_union:t="Invalid input";break;case D.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${te.joinValues(n.options)}`;break;case D.invalid_enum_value:t=`Invalid enum value. Expected ${te.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}"`:te.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,te.assertNever(n)}return{message:t}};let la=ys;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 $(n,e){const t=ca(),s=ua({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ys?void 0:ys].filter(r=>!!r)});n.common.issues.push(s)}class _e{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 Y;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 _e.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 Y;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 Y=Object.freeze({status:"aborted"}),qt=n=>({status:"dirty",value:n}),Ae=n=>({status:"valid",value:n}),fr=n=>n.status==="aborted",hr=n=>n.status==="dirty",Nt=n=>n.status==="valid",Sn=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 mr=(n,e)=>{if(Nt(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 J(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 K{get description(){return this._def.description}_getType(e){return Qe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Qe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _e,ctx:{common:e.parent.common,data:e.data,parsedType:Qe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Sn(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:Qe(e)},r=this._parseSync({data:e,path:s.path,parent:s});return mr(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qe(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return Nt(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=>Nt(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:Qe(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Sn(r)?r:Promise.resolve(r));return mr(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 It({schema:this,typeName:G.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 nt.create(this,this._def)}nullable(){return At.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ve.create(this)}promise(){return Dn.create(this,this._def)}or(e){return Rn.create([this,e],this._def)}and(e){return Nn.create(this,e,this._def)}transform(e){return new It({...J(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Os({...J(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new Ca({typeName:G.ZodBranded,type:this,...J(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ks({...J(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Us.create(this,e)}readonly(){return bs.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 es;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}(=)?))?$/,mi="((\\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(`^${mi}$`);function pi(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(`^${pi(n)}$`)}function Na(n){let e=`${mi}T${pi(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 qe extends K{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){const i=this._getOrReturnCtx(e);return $(i,{code:D.invalid_type,expected:U.string,received:i.parsedType}),Y}const s=new _e;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),$(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),$(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?$(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&$(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),$(r,{validation:"email",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")es||(es=new RegExp(_a,"u")),es.test(e.data)||(r=this._getOrReturnCtx(e,r),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(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),$(r,{code:D.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ta.test(e.data)||(r=this._getOrReturnCtx(e,r),$(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),$(r,{code:D.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ga.test(e.data)||(r=this._getOrReturnCtx(e,r),$(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),$(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),$(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),$(r,{validation:"cidr",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?ba.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Sa.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"base64url",code:D.invalid_string,message:i.message}),s.dirty()):te.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:G.ZodString,coerce:n?.coerce??!1,...J(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 xt extends K{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 $(i,{code:D.invalid_type,expected:U.number,received:i.parsedType}),Y}let s;const r=new _e;for(const i of this._def.checks)i.kind==="int"?te.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),$(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),$(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),$(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),$(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),$(s,{code:D.not_finite,message:i.message}),r.dirty()):te.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 xt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:Z.toString(r)}]})}_addCheck(e){return new xt({...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"&&te.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)}}xt.create=n=>new xt({checks:[],typeName:G.ZodNumber,coerce:n?.coerce||!1,...J(n)});class Xt extends K{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 _e;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),$(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),$(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),$(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):te.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return $(t,{code:D.invalid_type,expected:U.bigint,received:t.parsedType}),Y}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 Xt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:Z.toString(r)}]})}_addCheck(e){return new Xt({...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}}Xt.create=n=>new Xt({checks:[],typeName:G.ZodBigInt,coerce:n?.coerce??!1,...J(n)});class gs extends K{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.boolean,received:s.parsedType}),Y}return Ae(e.data)}}gs.create=n=>new gs({typeName:G.ZodBoolean,coerce:n?.coerce||!1,...J(n)});class Tn extends K{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){const i=this._getOrReturnCtx(e);return $(i,{code:D.invalid_type,expected:U.date,received:i.parsedType}),Y}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return $(i,{code:D.invalid_date}),Y}const s=new _e;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),$(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),$(r,{code:D.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):te.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Tn({...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}}Tn.create=n=>new Tn({checks:[],coerce:n?.coerce||!1,typeName:G.ZodDate,...J(n)});class pr extends K{_parse(e){if(this._getType(e)!==U.symbol){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.symbol,received:s.parsedType}),Y}return Ae(e.data)}}pr.create=n=>new pr({typeName:G.ZodSymbol,...J(n)});class ws extends K{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.undefined,received:s.parsedType}),Y}return Ae(e.data)}}ws.create=n=>new ws({typeName:G.ZodUndefined,...J(n)});class yr extends K{_parse(e){if(this._getType(e)!==U.null){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.null,received:s.parsedType}),Y}return Ae(e.data)}}yr.create=n=>new yr({typeName:G.ZodNull,...J(n)});class _s extends K{constructor(){super(...arguments),this._any=!0}_parse(e){return Ae(e.data)}}_s.create=n=>new _s({typeName:G.ZodAny,...J(n)});class gr extends K{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ae(e.data)}}gr.create=n=>new gr({typeName:G.ZodUnknown,...J(n)});class it extends K{_parse(e){const t=this._getOrReturnCtx(e);return $(t,{code:D.invalid_type,expected:U.never,received:t.parsedType}),Y}}it.create=n=>new it({typeName:G.ZodNever,...J(n)});class wr extends K{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.void,received:s.parsedType}),Y}return Ae(e.data)}}wr.create=n=>new wr({typeName:G.ZodVoid,...J(n)});class Ve extends K{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==U.array)return $(t,{code:D.invalid_type,expected:U.array,received:t.parsedType}),Y;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&($(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&&($(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&&($(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=>_e.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new We(t,o,t.path,a)));return _e.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:G.ZodArray,...J(e)});function Ot(n){if(n instanceof de){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=nt.create(Ot(s))}return new de({...n._def,shape:()=>e})}else return n instanceof Ve?new Ve({...n._def,type:Ot(n.element)}):n instanceof nt?nt.create(Ot(n.unwrap())):n instanceof At?At.create(Ot(n.unwrap())):n instanceof ht?ht.create(n.items.map(e=>Ot(e))):n}class de extends K{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=te.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 $(c,{code:D.invalid_type,expected:U.object,received:c.parsedType}),Y}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof it&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const d=i[c],h=r.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new We(r,h,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof it){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")a.length>0&&($(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 d of a){const h=r.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new We(r,h,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const h=await d.key,u=await d.value;c.push({key:h,value:u,alwaysSet:d.alwaysSet})}return c}).then(c=>_e.mergeObjectSync(s,c)):_e.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return Z.errToObj,new de({...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 de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:G.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const t={};for(const s of te.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const s of te.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new de({...this._def,shape:()=>t})}deepPartial(){return Ot(this)}partial(e){const t={};for(const s of te.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const s of te.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof nt;)i=i._def.innerType;t[s]=i}return new de({...this._def,shape:()=>t})}keyof(){return yi(te.objectKeys(this.shape))}}de.create=(n,e)=>new de({shape:()=>n,unknownKeys:"strip",catchall:it.create(),typeName:G.ZodObject,...J(e)});de.strictCreate=(n,e)=>new de({shape:()=>n,unknownKeys:"strict",catchall:it.create(),typeName:G.ZodObject,...J(e)});de.lazycreate=(n,e)=>new de({shape:n,unknownKeys:"strip",catchall:it.create(),typeName:G.ZodObject,...J(e)});class Rn extends K{_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 $(t,{code:D.invalid_union,unionErrors:o}),Y}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},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,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 $(t,{code:D.invalid_union,unionErrors:a}),Y}}get options(){return this._def.options}}Rn.create=(n,e)=>new Rn({options:n,typeName:G.ZodUnion,...J(e)});function Es(n,e){const t=Qe(n),s=Qe(e);if(n===e)return{valid:!0,data:n};if(t===U.object&&s===U.object){const r=te.objectKeys(e),i=te.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(const a of i){const l=Es(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=Es(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 Nn extends K{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(fr(i)||fr(o))return Y;const a=Es(i.value,o.value);return a.valid?((hr(i)||hr(o))&&t.dirty(),{status:t.value,value:a.data}):($(s,{code:D.invalid_intersection_types}),Y)};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}))}}Nn.create=(n,e,t)=>new Nn({left:n,right:e,typeName:G.ZodIntersection,...J(t)});class ht extends K{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.array)return $(s,{code:D.invalid_type,expected:U.array,received:s.parsedType}),Y;if(s.data.length<this._def.items.length)return $(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y;!this._def.rest&&s.data.length>this._def.items.length&&($(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=>_e.mergeArray(t,o)):_e.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new ht({...this._def,rest:e})}}ht.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ht({items:n,typeName:G.ZodTuple,rest:null,...J(e)})};class xn extends K{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 $(s,{code:D.invalid_type,expected:U.object,received:s.parsedType}),Y;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?_e.mergeObjectAsync(t,r):_e.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof K?new xn({keyType:e,valueType:t,typeName:G.ZodRecord,...J(s)}):new xn({keyType:qe.create(),valueType:e,typeName:G.ZodRecord,...J(t)})}}class _r extends K{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 $(s,{code:D.invalid_type,expected:U.map,received:s.parsedType}),Y;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,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return Y;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return Y;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}}}}_r.create=(n,e,t)=>new _r({valueType:e,keyType:n,typeName:G.ZodMap,...J(t)});class en extends K{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.set)return $(s,{code:D.invalid_type,expected:U.set,received:s.parsedType}),Y;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&($(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&&($(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 d of l){if(d.status==="aborted")return Y;d.status==="dirty"&&t.dirty(),c.add(d.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 en({...this._def,minSize:{value:e,message:Z.toString(t)}})}max(e,t){return new en({...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)}}en.create=(n,e)=>new en({valueType:n,minSize:null,maxSize:null,typeName:G.ZodSet,...J(e)});class Er extends K{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})}}Er.create=(n,e)=>new Er({getter:n,typeName:G.ZodLazy,...J(e)});class vs extends K{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return $(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),Y}return{status:"valid",value:e.data}}get value(){return this._def.value}}vs.create=(n,e)=>new vs({value:n,typeName:G.ZodLiteral,...J(e)});function yi(n,e){return new Dt({values:n,typeName:G.ZodEnum,...J(e)})}class Dt extends K{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return $(t,{expected:te.joinValues(s),received:t.parsedType,code:D.invalid_type}),Y}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 $(t,{received:t.data,code:D.invalid_enum_value,options:s}),Y}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 Dt.create(e,{...this._def,...t})}exclude(e,t=this._def){return Dt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}Dt.create=yi;class vr extends K{_parse(e){const t=te.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==U.string&&s.parsedType!==U.number){const r=te.objectValues(t);return $(s,{expected:te.joinValues(r),received:s.parsedType,code:D.invalid_type}),Y}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=te.objectValues(t);return $(s,{received:s.data,code:D.invalid_enum_value,options:r}),Y}return Ae(e.data)}get enum(){return this._def.values}}vr.create=(n,e)=>new vr({values:n,typeName:G.ZodNativeEnum,...J(e)});class Dn extends K{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.promise&&t.common.async===!1)return $(t,{code:D.invalid_type,expected:U.promise,received:t.parsedType}),Y;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})))}}Dn.create=(n,e)=>new Dn({type:n,typeName:G.ZodPromise,...J(e)});class It extends K{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.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=>{$(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 Y;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?Y:l.status==="dirty"||t.value==="dirty"?qt(l.value):l});{if(t.value==="aborted")return Y;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?Y:a.status==="dirty"||t.value==="dirty"?qt(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"?Y:(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"?Y:(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(!Nt(o))return Y;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=>Nt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):Y);te.assertNever(r)}}It.create=(n,e,t)=>new It({schema:n,typeName:G.ZodEffects,effect:e,...J(t)});It.createWithPreprocess=(n,e,t)=>new It({schema:e,effect:{type:"preprocess",transform:n},typeName:G.ZodEffects,...J(t)});class nt extends K{_parse(e){return this._getType(e)===U.undefined?Ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}nt.create=(n,e)=>new nt({innerType:n,typeName:G.ZodOptional,...J(e)});class At extends K{_parse(e){return this._getType(e)===U.null?Ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}At.create=(n,e)=>new At({innerType:n,typeName:G.ZodNullable,...J(e)});class Os extends K{_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}}Os.create=(n,e)=>new Os({innerType:n,typeName:G.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});class ks extends K{_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 Sn(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}}ks.create=(n,e)=>new ks({innerType:n,typeName:G.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});class Or extends K{_parse(e){if(this._getType(e)!==U.nan){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.nan,received:s.parsedType}),Y}return{status:"valid",value:e.data}}}Or.create=n=>new Or({typeName:G.ZodNaN,...J(n)});class Ca extends K{_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 Us extends K{_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"?Y:i.status==="dirty"?(t.dirty(),qt(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"?Y: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 Us({in:e,out:t,typeName:G.ZodPipeline})}}class bs extends K{_parse(e){const t=this._def.innerType._parse(e),s=r=>(Nt(r)&&(r.value=Object.freeze(r.value)),r);return Sn(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}bs.create=(n,e)=>new bs({innerType:n,typeName:G.ZodReadonly,...J(e)});var G;(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"})(G||(G={}));const ke=qe.create,ut=xt.create,Qt=gs.create,ts=ws.create,pe=_s.create;it.create;const gt=Ve.create,Ue=de.create,ve=Rn.create;Nn.create;ht.create;const sn=xn.create,Oe=vs.create,In=Dt.create;Dn.create;nt.create;At.create;const yn=()=>pe().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"}),kr=()=>pe().refine(n=>n&&(n._methodName==="serverTimestamp"||n.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),gi=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return sn(pe());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]=An(s,i),yt(s,[i]).size===1&&(t[`${r}_Lowercase`]=An(s,i,!0))})}return Ue({Collection_Path:gt(ke()),...t})},Fa=(n,e)=>{let t=sn(gi(n,e));return n.required||(t=t.optional()),t},$a=n=>{let e=gt(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},An=(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=In(o)}else i=In(e.values);break;case"Boolean":i=Qt();break;case"Number":e.autoIncrement?i=ve([Oe("Pending"),ut().int()]):(i=ut(),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=pe().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=yn(),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=gt(pe()),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=sn(pe()),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=pe();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},wi=(n,e,t)=>{const s={Collection_Path:gt(ke()),Last_Write_App:ke(),Last_Write_At:yn(),Last_Save_At:kr(),Last_Write_By:ve([ke().length(28),Oe("System")]),Last_Write_Connection_Status:In(["Online","Offline"]),Last_Write_Version:ut().int(),id:ke().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:yn(),Created_By:ve([ke().length(28),Oe("System")])};n==="create"&&(s.Saved_At=kr()),n==="update"&&(s.Saved_At=yn(),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=ct(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`]=gi(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]=An(e,l))}),yt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=An(e,l,!0))});const a=Ue(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class wt extends Error{}class Ma extends wt{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Pa extends wt{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class La extends wt{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class kt extends wt{}class _i extends wt{constructor(e){super(`Invalid unit ${e}`)}}class ye extends wt{}class Je extends wt{constructor(){super("Zone is an abstract class")}}const F="numeric",Me="short",be="long",Cn={year:F,month:F,day:F},Ei={year:F,month:Me,day:F},Va={year:F,month:Me,day:F,weekday:Me},vi={year:F,month:be,day:F},Oi={year:F,month:be,day:F,weekday:be},ki={hour:F,minute:F},bi={hour:F,minute:F,second:F},Si={hour:F,minute:F,second:F,timeZoneName:Me},Ti={hour:F,minute:F,second:F,timeZoneName:be},Ri={hour:F,minute:F,hourCycle:"h23"},Ni={hour:F,minute:F,second:F,hourCycle:"h23"},xi={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:Me},Di={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:be},Ii={year:F,month:F,day:F,hour:F,minute:F},Ai={year:F,month:F,day:F,hour:F,minute:F,second:F},Ci={year:F,month:Me,day:F,hour:F,minute:F},Fi={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},$i={year:F,month:be,day:F,hour:F,minute:F,timeZoneName:Me},Mi={year:F,month:be,day:F,hour:F,minute:F,second:F,timeZoneName:Me},Pi={year:F,month:be,day:F,weekday:be,hour:F,minute:F,timeZoneName:be},Li={year:F,month:be,day:F,weekday:be,hour:F,minute:F,second:F,timeZoneName:be};class rn{get type(){throw new Je}get name(){throw new Je}get ianaName(){return this.name}get isUniversal(){throw new Je}offsetName(e,t){throw new Je}formatOffset(e,t){throw new Je}offset(e){throw new Je}equals(e){throw new Je}get isValid(){throw new Je}}let ns=null;class jn extends rn{static get instance(){return ns===null&&(ns=new jn),ns}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Yi(e,t,s)}formatOffset(e,t){return Kt(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Ss=new Map;function Wa(n){let e=Ss.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"}),Ss.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,d]=s;return[o,r,i,a,l,c,d]}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:H(a)||(s[a]=parseInt(o,10))}return s}const ss=new Map;class He extends rn{static create(e){let t=ss.get(e);return t===void 0&&ss.set(e,t=new He(e)),t}static resetCache(){ss.clear(),Ss.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 Yi(e,t,s,this.name)}formatOffset(e,t){return Kt(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,d]=s.formatToParts?za(s,t):Za(s,t);a==="BC"&&(r=-Math.abs(r)+1);const u=zn({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:d,millisecond:0});let f=+t;const w=f%1e3;return f-=w>=0?w:1e3+w,(u-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let br={};function qa(n,e={}){const t=JSON.stringify([n,e]);let s=br[t];return s||(s=new Intl.ListFormat(n,e),br[t]=s),s}const Ts=new Map;function Rs(n,e={}){const t=JSON.stringify([n,e]);let s=Ts.get(t);return s===void 0&&(s=new Intl.DateTimeFormat(n,e),Ts.set(t,s)),s}const Ns=new Map;function Ba(n,e={}){const t=JSON.stringify([n,e]);let s=Ns.get(t);return s===void 0&&(s=new Intl.NumberFormat(n,e),Ns.set(t,s)),s}const xs=new Map;function Ha(n,e={}){const{base:t,...s}=e,r=JSON.stringify([n,s]);let i=xs.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(n,e),xs.set(r,i)),i}let Bt=null;function Ga(){return Bt||(Bt=new Intl.DateTimeFormat().resolvedOptions().locale,Bt)}const Ds=new Map;function Vi(n){let e=Ds.get(n);return e===void 0&&(e=new Intl.DateTimeFormat(n).resolvedOptions(),Ds.set(n,e)),e}const Is=new Map;function Ya(n){let e=Is.get(n);if(!e){const t=new Intl.Locale(n);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,"minimalDays"in e||(e={...Ui,...e}),Is.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=Rs(n).resolvedOptions(),r=n}catch{const l=n.substring(0,t);s=Rs(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=L.utc(2009,t,1);e.push(n(s))}return e}function Xa(n){const e=[];for(let t=1;t<=7;t++){const s=L.utc(2016,11,13+t);e.push(n(s))}return e}function un(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")||Vi(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):qs(e,3);return fe(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&&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=Rs(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&&Hi()&&(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 Ui={firstDay:1,minimalDays:4,weekend:[6,7]};class se{static fromOpts(e){return se.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,s,r,i=!1){const o=e||ce.defaultLocale,a=o||(i?"en-US":Ga()),l=t||ce.defaultNumberingSystem,c=s||ce.defaultOutputCalendar,d=Cs(r)||ce.defaultWeekSettings;return new se(a,l,c,d,o)}static resetCache(){Bt=null,Ts.clear(),Ns.clear(),xs.clear(),Ds.clear(),Is.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:r}={}){return se.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:se.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,Cs(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 un(this,e,Ki,()=>{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 un(this,e,to,()=>{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 un(this,void 0,()=>no,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[L.utc(2016,11,13,9),L.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return un(this,e,so,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[L.utc(-40,1,1),L.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"||Vi(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Gi()?Ya(this.locale):Ui}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 rs=null;class we extends rn{static get utcInstance(){return rs===null&&(rs=new we(0)),rs}static instance(e){return e===0?we.utcInstance:new we(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new we(qn(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Kt(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Kt(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return Kt(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 rn{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 Xe(n,e){if(H(n)||n===null)return e;if(n instanceof rn)return n;if(ul(n)){const t=n.toLowerCase();return t==="default"?e:t==="local"||t==="system"?jn.instance:t==="utc"||t==="gmt"?we.utcInstance:we.parseSpecifier(t)||He.create(n)}else return st(n)?we.instance(n):typeof n=="object"&&"offset"in n&&typeof n.offset=="function"?n:new rl(n)}const Ws={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Sr={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=Ws.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(Ws.hanidec)!==-1)e+=il.indexOf(n[t]);else for(const r in Sr){const[i,o]=Sr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const As=new Map;function al(){As.clear()}function Ce({numberingSystem:n},e=""){const t=n||"latn";let s=As.get(t);s===void 0&&(s=new Map,As.set(t,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${Ws[t]}${e}`),s.set(e,r)),r}let Tr=()=>Date.now(),Rr="system",Nr=null,xr=null,Dr=null,Ir=60,Ar,Cr=null;class ce{static get now(){return Tr}static set now(e){Tr=e}static set defaultZone(e){Rr=e}static get defaultZone(){return Xe(Rr,jn.instance)}static get defaultLocale(){return Nr}static set defaultLocale(e){Nr=e}static get defaultNumberingSystem(){return xr}static set defaultNumberingSystem(e){xr=e}static get defaultOutputCalendar(){return Dr}static set defaultOutputCalendar(e){Dr=e}static get defaultWeekSettings(){return Cr}static set defaultWeekSettings(e){Cr=Cs(e)}static get twoDigitCutoffYear(){return Ir}static set twoDigitCutoffYear(e){Ir=e%100}static get throwOnInvalid(){return Ar}static set throwOnInvalid(e){Ar=e}static resetCaches(){se.resetCache(),He.resetCache(),L.resetCache(),al()}}class $e{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Wi=[0,31,59,90,120,151,181,212,243,273,304,334],ji=[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 js(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 Zi(n,e,t){return t+(on(n)?ji:Wi)[e-1]}function zi(n,e){const t=on(n)?ji:Wi,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 Fn(n,e=4,t=1){const{year:s,month:r,day:i}=n,o=Zi(s,r,i),a=Zs(js(s,r,i),t);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=tn(c,e,t)):l>tn(s,e,t)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...Bn(n)}}function Fr(n,e=4,t=1){const{weekYear:s,weekNumber:r,weekday:i}=n,o=Zs(js(s,1,e),t),a=Tt(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=Tt(c)):l>a?(c=s+1,l-=Tt(s)):c=s;const{month:d,day:h}=zi(c,l);return{year:c,month:d,day:h,...Bn(n)}}function is(n){const{year:e,month:t,day:s}=n,r=Zi(e,t,s);return{year:e,ordinal:r,...Bn(n)}}function $r(n){const{year:e,ordinal:t}=n,{month:s,day:r}=zi(e,t);return{year:e,month:s,day:r,...Bn(n)}}function Mr(n,e){if(!H(n.localWeekday)||!H(n.localWeekNumber)||!H(n.localWeekYear)){if(!H(n.weekday)||!H(n.weekNumber)||!H(n.weekYear))throw new kt("Cannot mix locale-based week fields with ISO-based week fields");return H(n.localWeekday)||(n.weekday=n.localWeekday),H(n.localWeekNumber)||(n.weekNumber=n.localWeekNumber),H(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=Zn(n.weekYear),r=De(n.weekNumber,1,tn(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=Zn(n.year),t=De(n.ordinal,1,Tt(n.year));return e?t?!1:xe("ordinal",n.ordinal):xe("year",n.year)}function qi(n){const e=Zn(n.year),t=De(n.month,1,12),s=De(n.day,1,$n(n.year,n.month));return e?t?s?!1:xe("day",n.day):xe("month",n.month):xe("year",n.year)}function Bi(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 H(n){return typeof n>"u"}function st(n){return typeof n=="number"}function Zn(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 Hi(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Gi(){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 Pr(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 Ct(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Cs(n){if(n==null)return null;if(typeof n!="object")throw new ye("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 ye("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 ml(n,e){return n-e*Math.floor(n/e)}function fe(n,e=2){const t=n<0;let s;return t?s="-"+(""+-n).padStart(e,"0"):s=(""+n).padStart(e,"0"),s}function Ke(n){if(!(H(n)||n===null||n===""))return parseInt(n,10)}function at(n){if(!(H(n)||n===null||n===""))return parseFloat(n)}function zs(n){if(!(H(n)||n===null||n==="")){const e=parseFloat("0."+n)*1e3;return Math.floor(e)}}function qs(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 on(n){return n%4===0&&(n%100!==0||n%400===0)}function Tt(n){return on(n)?366:365}function $n(n,e){const t=ml(e-1,12)+1,s=n+(e-t)/12;return t===2?on(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function zn(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 Lr(n,e,t){return-Zs(js(n,1,e),t)+e-1}function tn(n,e=4,t=1){const s=Lr(n,e,t),r=Lr(n+1,e,t);return(Tt(n)-s+r)/7}function Fs(n){return n>99?n:n>ce.twoDigitCutoffYear?1900+n:2e3+n}function Yi(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 qn(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 Ji(n){const e=Number(n);if(typeof n=="boolean"||n===""||!Number.isFinite(e))throw new ye(`Invalid unit value ${n}`);return e}function Mn(n,e){const t={};for(const s in n)if(Ct(n,s)){const r=n[s];if(r==null)continue;t[e(s)]=Ji(r)}return t}function Kt(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}${fe(t,2)}:${fe(s,2)}`;case"narrow":return`${r}${t}${s>0?`:${s}`:""}`;case"techie":return`${r}${fe(t,2)}${fe(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Bn(n){return hl(n,["hour","minute","second","millisecond"])}const pl=["January","February","March","April","May","June","July","August","September","October","November","December"],Qi=["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 Ki(n){switch(n){case"narrow":return[...yl];case"short":return[...Qi];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 Xi=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],eo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],gl=["M","T","W","T","F","S","S"];function to(n){switch(n){case"narrow":return[...gl];case"short":return[...eo];case"long":return[...Xi];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const no=["AM","PM"],wl=["Before Christ","Anno Domini"],_l=["BC","AD"],El=["B","A"];function so(n){switch(n){case"narrow":return[...El];case"short":return[..._l];case"long":return[...wl];default:return null}}function vl(n){return no[n.hour<12?0:1]}function Ol(n,e){return to(e)[n.weekday-1]}function kl(n,e){return Ki(e)[n.month-1]}function bl(n,e){return so(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],d=s?l?c[1]:c[2]||c[1]:l?r[n][0]:n;return o?`${a} ${d} ago`:`in ${a} ${d}`}function Vr(n,e){let t="";for(const s of n)s.literal?t+=s.val:t+=e(s.val);return t}const Tl={D:Cn,DD:Ei,DDD:vi,DDDD:Oi,t:ki,tt:bi,ttt:Si,tttt:Ti,T:Ri,TT:Ni,TTT:xi,TTTT:Di,f:Ii,ff:Ci,fff:$i,ffff:Pi,F:Ai,FF:Fi,FFF:Mi,FFFF:Li};class ge{static create(e,t={}){return new ge(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 fe(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=(f,w)=>this.loc.extract(e,f,w),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>s?vl(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,w)=>s?kl(e,f):i(w?{month:f}:{month:f,day:"numeric"},"month"),c=(f,w)=>s?Ol(e,f):i(w?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),d=f=>{const w=ge.macroTokenToFormatOpts(f);return w?this.formatWithSystemDefault(e,w):f},h=f=>s?bl(e,f):i({era:f},"era"),u=f=>{switch(f){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 d(f)}};return Vr(ge.parseFormat(t),u)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[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=(d,h)=>u=>{const f=r(u);if(f){const w=h.isNegativeDuration&&f!==h.largestUnit?s:1;let E;return this.opts.signMode==="negativeLargestOnly"&&f!==h.largestUnit?E="never":this.opts.signMode==="all"?E="always":E="auto",this.num(d.get(f)*w,u.length,E)}else return u},o=ge.parseFormat(t),a=o.reduce((d,{literal:h,val:u})=>h?d:d.concat(u),[]),l=e.shiftTo(...a.map(r).filter(d=>d)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Vr(o,i(l,c))}}const ro=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Ft(...n){const e=n.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function $t(...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 Mt(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 io(...n){return(e,t)=>{const s={};let r;for(r=0;r<n.length;r++)s[n[r]]=Ke(e[t+r]);return[s,null,t+r]}}const oo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Rl=`(?:${oo.source}?(?:\\[(${ro.source})\\])?)?`,Bs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,ao=RegExp(`${Bs.source}${Rl}`),Hs=RegExp(`(?:[Tt]${ao.source})?`),Nl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,xl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Dl=/(\d{4})-?(\d{3})/,Il=io("weekYear","weekNumber","weekDay"),Al=io("year","ordinal"),Cl=/(\d{4})-(\d\d)-(\d\d)/,lo=RegExp(`${Bs.source} ?(?:${oo.source}|(${ro.source}))?`),Fl=RegExp(`(?: ${lo.source})?`);function Rt(n,e,t){const s=n[e];return H(s)?t:Ke(s)}function $l(n,e){return[{year:Rt(n,e),month:Rt(n,e+1,1),day:Rt(n,e+2,1)},null,e+3]}function Pt(n,e){return[{hours:Rt(n,e,0),minutes:Rt(n,e+1,0),seconds:Rt(n,e+2,0),milliseconds:zs(n[e+3])},null,e+4]}function an(n,e){const t=!n[e]&&!n[e+1],s=qn(n[e+1],n[e+2]),r=t?null:we.instance(s);return[{},r,e+3]}function ln(n,e){const t=n[e]?He.create(n[e]):null;return[{},t,e+1]}const Ml=RegExp(`^T?${Bs.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,d=e[0]==="-",h=l&&l[0]==="-",u=(f,w=!1)=>f!==void 0&&(w||f&&d)?-f:f;return[{years:u(at(t)),months:u(at(s)),weeks:u(at(r)),days:u(at(i)),hours:u(at(o)),minutes:u(at(a)),seconds:u(at(l),l==="-0"),milliseconds:u(zs(c),h)}]}const Vl={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Gs(n,e,t,s,r,i,o){const a={year:e.length===2?Fs(Ke(e)):Ke(e),month:Qi.indexOf(t)+1,day:Ke(s),hour:Ke(r),minute:Ke(i)};return o&&(a.second=Ke(o)),n&&(a.weekday=n.length>3?Xi.indexOf(n)+1:eo.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,d,h]=n,u=Gs(e,r,s,t,i,o,a);let f;return l?f=Vl[l]:c?f=0:f=qn(d,h),[u,new we(f)]}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 Ur(n){const[,e,t,s,r,i,o,a]=n;return[Gs(e,r,s,t,i,o,a),we.utcInstance]}function Bl(n){const[,e,t,s,r,i,o,a]=n;return[Gs(e,a,t,s,r,i,o),we.utcInstance]}const Hl=Ft(Nl,Hs),Gl=Ft(xl,Hs),Yl=Ft(Dl,Hs),Jl=Ft(ao),co=$t($l,Pt,an,ln),Ql=$t(Il,Pt,an,ln),Kl=$t(Al,Pt,an,ln),Xl=$t(Pt,an,ln);function ec(n){return Mt(n,[Hl,co],[Gl,Ql],[Yl,Kl],[Jl,Xl])}function tc(n){return Mt(jl(n),[Ul,Wl])}function nc(n){return Mt(n,[Zl,Ur],[zl,Ur],[ql,Bl])}function sc(n){return Mt(n,[Pl,Ll])}const rc=$t(Pt);function ic(n){return Mt(n,[Ml,rc])}const oc=Ft(Cl,Fl),ac=Ft(lo),lc=$t(Pt,an,ln);function cc(n){return Mt(n,[oc,co],[ac,lc])}const Wr="Invalid Duration",uo={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},...uo},Re=146097/400,_t=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:_t/7,days:_t,hours:_t*24,minutes:_t*24*60,seconds:_t*24*60*60,milliseconds:_t*24*60*60*1e3},...uo},dt=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],fc=dt.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 ee(s)}function fo(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 jr(n,e){const t=fo(n,e)<0?-1:1;dt.reduceRight((s,r)=>{if(H(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),dt.reduce((s,r)=>{if(H(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 ee{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||se.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return ee.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new ye(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ee({values:Mn(e,ee.normalizeUnit),loc:se.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(st(e))return ee.fromMillis(e);if(ee.isDuration(e))return e;if(typeof e=="object")return ee.fromObject(e);throw new ye(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=sc(e);return s?ee.fromObject(s,t):ee.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=ic(e);return s?ee.fromObject(s,t):ee.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new ye("need to specify a reason the Duration is invalid");const s=e instanceof $e?e:new $e(e,t);if(ce.throwOnInvalid)throw new La(s);return new ee({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 _i(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?ge.create(this.loc,s).formatDurationFromString(this,e):Wr}toHuman(e={}){if(!this.isValid)return Wr;const t=e.showZeros!==!1,s=dt.map(r=>{const i=this.values[r];return H(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+=qs(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},L.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?fo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=ee.fromDurationLike(e),s={};for(const r of dt)(Ct(t.values,r)||Ct(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=ee.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]=Ji(e(this.values[s],s));return Ze(this,{values:t},!0)}get(e){return this[ee.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...Mn(e,ee.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 jr(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=>ee.normalizeUnit(o));const t={},s={},r=this.toObject();let i;for(const o of dt)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;st(r[o])&&(a+=r[o]);const l=Math.trunc(a);t[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else st(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 jr(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 dt)if(!t(this.values[s],e.values[s]))return!1;return!0}}const Et="Invalid Interval";function hc(n,e){return!n||!n.isValid?le.invalid("missing or invalid start"):!e||!e.isValid?le.invalid("missing or invalid end"):e<n?le.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 le{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 ye("need to specify a reason the Interval is invalid");const s=e instanceof $e?e:new $e(e,t);if(ce.throwOnInvalid)throw new Pa(s);return new le({invalid:s})}static fromDateTimes(e,t){const s=Zt(e),r=Zt(t),i=hc(s,r);return i??new le({start:s,end:r})}static after(e,t){const s=ee.fromDurationLike(t),r=Zt(e);return le.fromDateTimes(r,r.plus(s))}static before(e,t){const s=ee.fromDurationLike(t),r=Zt(e);return le.fromDateTimes(r.minus(s),r)}static fromISO(e,t){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=L.fromISO(s,t),o=i.isValid}catch{o=!1}let a,l;try{a=L.fromISO(r,t),l=a.isValid}catch{l=!1}if(o&&l)return le.fromDateTimes(i,a);if(o){const c=ee.fromISO(r,t);if(c.isValid)return le.after(i,c)}else if(l){const c=ee.fromISO(s,t);if(c.isValid)return le.before(a,c)}}return le.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?le.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(le.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const t=ee.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(le.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:le.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 le.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(le.fromDateTimes(t,l.time)),t=null);return le.merge(r)}difference(...e){return le.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Et}[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=Cn,t={}){return this.isValid?ge.create(this.s.loc.clone(t),e).formatInterval(this):Et}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Et}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Et}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Et}toFormat(e,{separator:t=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Et}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):ee.invalid(this.invalidReason)}mapEndpoints(e){return le.fromDateTimes(e(this.s),e(this.e))}}class dn{static hasDST(e=ce.defaultZone){const t=L.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 Xe(e,ce.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||se.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||se.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||se.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||se.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||se.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||se.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||se.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return se.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return se.create(t,null,"gregory").eras(e)}static features(){return{relative:Hi(),localeWeek:Gi()}}}function zr(n,e){const t=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(n);return Math.floor(ee.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 d=zr(l,c);return(d-d%7)/7}],["days",zr]],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 d=ee.fromObject(i,s);return c.length>0?ee.fromMillis(l,s).shiftTo(...c).plus(d):d}const yc="missing Intl.DateTimeFormat.formatToParts support";function ne(n,e=t=>t){return{regex:n,deser:([t])=>e(ol(t))}}const gc=" ",ho=`[ ${gc}]`,mo=new RegExp(ho,"g");function wc(n){return n.replace(/\./g,"\\.?").replace(mo,ho)}function qr(n){return n.replace(/\./g,"").replace(mo," ").toLowerCase()}function Fe(n,e){return n===null?null:{regex:RegExp(n.map(wc).join("|")),deser:([t])=>n.findIndex(s=>qr(t)===qr(s))+e}}function Br(n,e){return{regex:n,deser:([,t,s])=>qn(t,s),groups:e}}function fn(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}"),d=Ce(e,"{1,9}"),h=Ce(e,"{2,4}"),u=Ce(e,"{4,6}"),f=p=>({regex:RegExp(_c(p.val)),deser:([k])=>k,literal:!0}),E=(p=>{if(n.literal)return f(p);switch(p.val){case"G":return Fe(e.eras("short"),0);case"GG":return Fe(e.eras("long"),0);case"y":return ne(c);case"yy":return ne(h,Fs);case"yyyy":return ne(i);case"yyyyy":return ne(u);case"yyyyyy":return ne(o);case"M":return ne(a);case"MM":return ne(s);case"MMM":return Fe(e.months("short",!0),1);case"MMMM":return Fe(e.months("long",!0),1);case"L":return ne(a);case"LL":return ne(s);case"LLL":return Fe(e.months("short",!1),1);case"LLLL":return Fe(e.months("long",!1),1);case"d":return ne(a);case"dd":return ne(s);case"o":return ne(l);case"ooo":return ne(r);case"HH":return ne(s);case"H":return ne(a);case"hh":return ne(s);case"h":return ne(a);case"mm":return ne(s);case"m":return ne(a);case"q":return ne(a);case"qq":return ne(s);case"s":return ne(a);case"ss":return ne(s);case"S":return ne(l);case"SSS":return ne(r);case"u":return fn(d);case"uu":return fn(a);case"uuu":return ne(t);case"a":return Fe(e.meridiems(),0);case"kkkk":return ne(i);case"kk":return ne(h,Fs);case"W":return ne(a);case"WW":return ne(s);case"E":case"c":return ne(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 Br(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return Br(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return fn(/[a-z_+-/]{1,256}?/i);case" ":return fn(/[^\S\n\r]/);default:return f(p)}})(n)||{invalidReason:yc};return E.token=n,E}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(Ct(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 H(n.z)||(t=He.create(n.z)),H(n.Z)||(t||(t=new we(n.Z)),s=n.Z),H(n.q)||(n.M=(n.q-1)*3+1),H(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),H(n.u)||(n.S=zs(n.u)),[Object.keys(n).reduce((i,o)=>{const a=e(o);return a&&(i[a]=n[o]),i},{}),t,s]}let os=null;function Tc(){return os||(os=L.fromMillis(1555555555555)),os}function Rc(n,e){if(n.literal)return n;const t=ge.macroTokenToFormatOpts(n.val),s=wo(t,e);return s==null||s.includes(void 0)?n:s}function po(n,e){return Array.prototype.concat(...n.map(t=>Rc(t,e)))}class yo{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=po(ge.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(Ct(s,"a")&&Ct(s,"H"))throw new kt("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 go(n,e,t){return new yo(n,t).explainFromTokens(e)}function Nc(n,e,t){const{result:s,zone:r,specificOffset:i,invalidReason:o}=go(n,e,t);return[s,r,i,o]}function wo(n,e){if(!n)return null;const s=ge.create(e,n).dtFormatter(Tc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Oc(o,n,i))}const as="Invalid DateTime",Hr=864e13;function Ht(n){return new $e("unsupported zone",`the zone "${n.name}" is not supported`)}function ls(n){return n.weekData===null&&(n.weekData=Fn(n.c)),n.weekData}function cs(n){return n.localWeekData===null&&(n.localWeekData=Fn(n.c,n.loc.getMinDaysInFirstWeek(),n.loc.getStartOfWeek())),n.localWeekData}function lt(n,e){const t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new L({...t,...e,old:t})}function _o(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 hn(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 gn(n,e,t){return _o(zn(n),e,t)}function Gr(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,$n(s,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ee.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=zn(i);let[l,c]=_o(a,t,n.zone);return o!==0&&(l+=o,c=n.zone.offset(l)),{ts:l,o:c}}function vt(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=L.fromObject(n,{...t,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return L.invalid(new $e("unparsable",`the input "${r}" can't be parsed as ${s}`))}function mn(n,e,t=!0){return n.isValid?ge.create(se.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(n,e):null}function us(n,e,t){const s=n.c.year>9999||n.c.year<0;let r="";if(s&&n.c.year>=0&&(r+="+"),r+=fe(n.c.year,s?6:4),t==="year")return r;if(e){if(r+="-",r+=fe(n.c.month),t==="month")return r;r+="-"}else if(r+=fe(n.c.month),t==="month")return r;return r+=fe(n.c.day),r}function Yr(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+=fe(n.c.hour),o==="hour")break;if(e){if(l+=":",l+=fe(n.c.minute),o==="minute")break;a&&(l+=":",l+=fe(n.c.second))}else{if(l+=fe(n.c.minute),o==="minute")break;a&&(l+=fe(n.c.second))}if(o==="second")break;a&&(!s||n.c.millisecond!==0)&&(l+=".",l+=fe(n.c.millisecond,3))}return r&&(n.isOffsetFixed&&n.offset===0&&!i?l+="Z":n.o<0?(l+="-",l+=fe(Math.trunc(-n.o/60)),l+=":",l+=fe(Math.trunc(-n.o%60))):(l+="+",l+=fe(Math.trunc(n.o/60)),l+=":",l+=fe(Math.trunc(n.o%60)))),i&&(l+="["+n.zone.ianaName+"]"),l}const Eo={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},wn=["year","month","day","hour","minute","second","millisecond"],Ic=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Ac=["year","ordinal","hour","minute","second","millisecond"];function _n(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 _i(n);return e}function Jr(n){switch(n.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return _n(n)}}function Cc(n){if(Gt===void 0&&(Gt=ce.now()),n.type!=="iana")return n.offset(Gt);const e=n.name;let t=$s.get(e);return t===void 0&&(t=n.offset(Gt),$s.set(e,t)),t}function Qr(n,e){const t=Xe(e.zone,ce.defaultZone);if(!t.isValid)return L.invalid(Ht(t));const s=se.fromObject(e);let r,i;if(H(n.year))r=ce.now();else{for(const l of wn)H(n[l])&&(n[l]=Eo[l]);const o=qi(n)||Bi(n);if(o)return L.invalid(o);const a=Cc(t);[r,i]=gn(n,a,t)}return new L({ts:r,zone:t,loc:s,o:i})}function Kr(n,e,t){const s=H(t.round)?!0:t.round,r=H(t.rounding)?"trunc":t.rounding,i=(a,l)=>(a=qs(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 Xr(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 Gt;const $s=new Map;class L{constructor(e){const t=e.zone||ce.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new $e("invalid input"):null)||(t.isValid?null:Ht(t));this.ts=H(e.ts)?ce.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=st(e.o)&&!e.old?e.o:t.offset(this.ts);r=hn(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||se.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new L({})}static local(){const[e,t]=Xr(arguments),[s,r,i,o,a,l,c]=t;return Qr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,t]=Xr(arguments),[s,r,i,o,a,l,c]=t;return e.zone=we.utcInstance,Qr({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 L.invalid("invalid input");const r=Xe(t.zone,ce.defaultZone);return r.isValid?new L({ts:s,zone:r,loc:se.fromObject(t)}):L.invalid(Ht(r))}static fromMillis(e,t={}){if(st(e))return e<-Hr||e>Hr?L.invalid("Timestamp out of range"):new L({ts:e,zone:Xe(t.zone,ce.defaultZone),loc:se.fromObject(t)});throw new ye(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(st(e))return new L({ts:e*1e3,zone:Xe(t.zone,ce.defaultZone),loc:se.fromObject(t)});throw new ye("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=Xe(t.zone,ce.defaultZone);if(!s.isValid)return L.invalid(Ht(s));const r=se.fromObject(t),i=Mn(e,Jr),{minDaysInFirstWeek:o,startOfWeek:a}=Mr(i,r),l=ce.now(),c=H(t.specificOffset)?s.offset(l):t.specificOffset,d=!H(i.ordinal),h=!H(i.year),u=!H(i.month)||!H(i.day),f=h||u,w=i.weekYear||i.weekNumber;if((f||d)&&w)throw new kt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new kt("Can't mix ordinal dates with month/day");const E=w||i.weekday&&!f;let p,k,b=hn(l,c);E?(p=Ic,k=xc,b=Fn(b,o,a)):d?(p=Ac,k=Dc,b=is(b)):(p=wn,k=Eo);let R=!1;for(const m of p){const S=i[m];H(S)?R?i[m]=k[m]:i[m]=b[m]:R=!0}const g=E?ll(i,o,a):d?cl(i):qi(i),T=g||Bi(i);if(T)return L.invalid(T);const _=E?Fr(i,o,a):d?$r(i):i,[P,x]=gn(_,c,s),M=new L({ts:P,zone:s,o:x,loc:r});return i.weekday&&f&&e.weekday!==M.weekday?L.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${M.toISO()}`):M.isValid?M:L.invalid(M.invalid)}static fromISO(e,t={}){const[s,r]=ec(e);return vt(s,r,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,r]=tc(e);return vt(s,r,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,r]=nc(e);return vt(s,r,t,"HTTP",t)}static fromFormat(e,t,s={}){if(H(e)||H(t))throw new ye("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=se.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,d]=Nc(o,e,t);return d?L.invalid(d):vt(a,l,s,`format ${t}`,e,c)}static fromString(e,t,s={}){return L.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,r]=cc(e);return vt(s,r,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new ye("need to specify a reason the DateTime is invalid");const s=e instanceof $e?e:new $e(e,t);if(ce.throwOnInvalid)throw new Ma(s);return new L({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=wo(e,se.fromObject(t));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,t={}){return po(ge.parseFormat(e),se.fromObject(t)).map(r=>r.val).join("")}static resetCache(){Gt=void 0,$s.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?ls(this).weekYear:NaN}get weekNumber(){return this.isValid?ls(this).weekNumber:NaN}get weekday(){return this.isValid?ls(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?cs(this).weekday:NaN}get localWeekNumber(){return this.isValid?cs(this).weekNumber:NaN}get localWeekYear(){return this.isValid?cs(this).weekYear:NaN}get ordinal(){return this.isValid?is(this.c).ordinal:NaN}get monthShort(){return this.isValid?dn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?dn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?dn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?dn.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=zn(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,d=hn(l,o),h=hn(c,a);return d.hour===h.hour&&d.minute===h.minute&&d.second===h.second&&d.millisecond===h.millisecond?[lt(this,{ts:l}),lt(this,{ts:c})]:[this]}get isInLeapYear(){return on(this.year)}get daysInMonth(){return $n(this.year,this.month)}get daysInYear(){return this.isValid?Tt(this.year):NaN}get weeksInWeekYear(){return this.isValid?tn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?tn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:t,numberingSystem:s,calendar:r}=ge.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(we.instance(e),t)}toLocal(){return this.setZone(ce.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=Xe(e,ce.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]=gn(o,i,e)}return lt(this,{ts:r,zone:e})}else return L.invalid(Ht(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return lt(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=Mn(e,Jr),{minDaysInFirstWeek:s,startOfWeek:r}=Mr(t,this.loc),i=!H(t.weekYear)||!H(t.weekNumber)||!H(t.weekday),o=!H(t.ordinal),a=!H(t.year),l=!H(t.month)||!H(t.day),c=a||l,d=t.weekYear||t.weekNumber;if((c||o)&&d)throw new kt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new kt("Can't mix ordinal dates with month/day");let h;i?h=Fr({...Fn(this.c,s,r),...t},s,r):H(t.ordinal)?(h={...this.toObject(),...t},H(t.day)&&(h.day=Math.min($n(h.year,h.month),h.day))):h=$r({...is(this.c),...t});const[u,f]=gn(h,this.o,this.zone);return lt(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const t=ee.fromDurationLike(e);return lt(this,Gr(this,t))}minus(e){if(!this.isValid)return this;const t=ee.fromDurationLike(e).negate();return lt(this,Gr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},r=ee.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?ge.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):as}toLocaleString(e=Cn,t={}){return this.isValid?ge.create(this.loc.clone(t),e).formatDateTime(this):as}toLocaleParts(e={}){return this.isValid?ge.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=_n(o);const a=e==="extended";let l=us(this,a,o);return wn.indexOf(o)>=3&&(l+="T"),l+=Yr(this,a,t,s,r,i,o),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?us(this,e==="extended",_n(t)):null}toISOWeekDate(){return mn(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=_n(a),(r&&wn.indexOf(a)>=3?"T":"")+Yr(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return mn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return mn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?us(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")),mn(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():as}[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 ee.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=fl(t).map(ee.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(L.now(),e,t)}until(e){return this.isValid?le.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||L.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),Kr(t,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?Kr(e.base||L.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(L.isDateTime))throw new ye("min requires all arguments be DateTimes");return Pr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(L.isDateTime))throw new ye("max requires all arguments be DateTimes");return Pr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=se.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return go(o,e,t)}static fromStringExplain(e,t,s={}){return L.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:r=null}=t,i=se.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new yo(i,e)}static fromFormatParser(e,t,s={}){if(H(e)||H(t))throw new ye("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=se.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new ye(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=t.explainFromTokens(e);return d?L.invalid(d):vt(a,l,s,`format ${t.format}`,e,c)}static get DATE_SHORT(){return Cn}static get DATE_MED(){return Ei}static get DATE_MED_WITH_WEEKDAY(){return Va}static get DATE_FULL(){return vi}static get DATE_HUGE(){return Oi}static get TIME_SIMPLE(){return ki}static get TIME_WITH_SECONDS(){return bi}static get TIME_WITH_SHORT_OFFSET(){return Si}static get TIME_WITH_LONG_OFFSET(){return Ti}static get TIME_24_SIMPLE(){return Ri}static get TIME_24_WITH_SECONDS(){return Ni}static get TIME_24_WITH_SHORT_OFFSET(){return xi}static get TIME_24_WITH_LONG_OFFSET(){return Di}static get DATETIME_SHORT(){return Ii}static get DATETIME_SHORT_WITH_SECONDS(){return Ai}static get DATETIME_MED(){return Ci}static get DATETIME_MED_WITH_SECONDS(){return Fi}static get DATETIME_MED_WITH_WEEKDAY(){return Ua}static get DATETIME_FULL(){return $i}static get DATETIME_FULL_WITH_SECONDS(){return Mi}static get DATETIME_HUGE(){return Pi}static get DATETIME_HUGE_WITH_SECONDS(){return Li}}function Zt(n){if(L.isDateTime(n))return n;if(n&&n.valueOf&&st(n.valueOf()))return L.fromJSDate(n);if(n&&typeof n=="object")return L.fromObject(n);throw new ye(`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 sn(pe());n.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?t[r]=vo(i)?.nullable():t[r]=pe()})}return Ue({Collection_Path:gt(ke()),...t})},$c=(n,e,t,s)=>{let r=Ue({}).catchall(Fc(n,e)),i;if(!s&&t){const o=Ie(n,t);i=zt(o.admin?.skipFormRequiredValidation)}return(!n.required||i)&&(r=r.optional()),r},Mc=()=>pe().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"}),vo=(n,e,t)=>{let s;const r=`${zt(n.description)}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Vo=require("node:child_process"),bt=require("firebase-admin/app"),ze=require("lodash/isEqual.js"),Uo=require("lodash/merge.js"),Wo=require("lodash/set.js"),me=require("lodash/cloneDeep.js"),B=require("firebase-admin/firestore"),ri=require("firebase-admin/database"),mt=require("firebase-admin/auth"),jo=async(n,e,t,s)=>new Promise((r,i)=>{const o=Vo.spawn(n,e,{cwd:t||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},d=()=>{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=>{d(),h===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),Zo=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 bt.getApp()}catch{return bt.initializeApp({credential:bt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},Ln=n=>!!n.auth,Se=(n,e)=>{if(e?.operations)return e.operations.includes(n)},Vn=(n,e)=>e?e.Role?n.access?.includes(e.Role):!1:!0,zo=(n,e)=>n.restrictCreate===!0?!1:e&&typeof n.restrictCreate=="object"?e.Role?n.restrictCreate?.includes(e.Role):!1:!0,ii=(n,e)=>n.restrictUpdate===!0?!1:e&&typeof n.restrictUpdate=="object"?e.Role?n.restrictUpdate?.includes(e.Role):!1:!0,ar=(n,e,t)=>{const{labels:s}=n;return t.collections&&Se("Update",t.collections[s.collection])&&(!e.access||Vn(e,t))&&ii(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],K=n=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(n.type),oi=(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 d=a?.[t[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},$s=(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},ai=(n,e,t)=>{const s=[],{access:r}=n,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.role===t.Role))return;const a=o.collectionField,l=W(n.fields,a);if(!K(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 u=h.restrictions?.find(f=>f.type===o.type&&f.roles.some(w=>w.role===t.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===t.Role&&(!h.assignable?.includes(t.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},li=(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&&!Vn(l,t))&&t.Role&&K(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},qo=(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=oi(e,r),d=$s(e,r),h=ai(e,t,r);c?.filter(g=>g.type==="Record_Owner").forEach(g=>{"operations"in g&&g.operations&&!g.operations.includes(n)||i.Created_By!==s&&(l=!1)}),c?.filter(g=>g.type==="Record_User").forEach(g=>{if("operations"in g&&g.operations&&!g.operations.includes(n))return;const T=W(o,g.collectionField);i[`${T.name}_Array`]?.includes(r.Doc_ID)||(l=!1)}),c?.filter(g=>g.type==="Record_Property").forEach(g=>{if("operations"in g&&g.operations&&!g.operations.includes(n))return;const T=W(o,g.propertyField),_=g.roles.find(P=>P.role===r.Role);T.type==="Array"?_.values?.some(P=>i[T.name].includes(P))||(l=!1):_.values?.includes(i[T.name])||(l=!1)});let u=!0,f=!1;d?.filter(g=>g.type==="Individual").forEach(()=>{f=!0,a.individualEntities?.includes(i.id)||(u=!1)});let w=!0,E=!1;if(d?.filter(g=>g.type==="Parent").forEach(g=>{E=!0;const T=W(o,g.collectionField);a.parentEntities?.some(_=>i[`${T.name}_Array`].includes(_))||(w=!1)}),d?.filter(g=>g.type==="Parent_Property").forEach(g=>{E=!0;const T=W(o,g.collectionField),_=W(o,g.propertyField);Object.entries(a.parentPropertyEntities||{}).some(P=>{const[x,M]=P;return x===i[_.name]&&i[`${T.name}_Array`].some(m=>M.includes(m))})||(w=!1)}),f&&E){if(!(u||w)){l=!1;return}}else if(!u||!w){l=!1;return}let p=!0,k=!1;h?.filter(g=>g.parentFilter.type==="Individual").forEach(g=>{k=!0;const{parentFilter:T}=g,_=W(o,T.collectionField),P=r.collections?.[_.collection];if(!P){l=!1;return}P.individualEntities?.some(x=>i[`${_.name}_Array`].includes(x))||(p=!1)});let b=!0,R=!1;if(h?.filter(g=>g.parentFilter.type==="Parent").forEach(g=>{R=!0;const{parentFilter:T}=g,_=W(o,T.collectionField),P=W(o,T.parentCollectionField),x=r.collections?.[_.collection];if(!x){l=!1;return}x.parentEntities?.some(M=>i[`${P.name}_Array`].includes(M))||(b=!1)}),h?.filter(g=>g.parentFilter.type==="Parent_Property").forEach(g=>{R=!0;const{parentFilter:T}=g,_=W(o,T.collectionField),P=W(o,T.parentPropertyField),x=W(o,T.parentCollectionField),M=r.collections?.[_.collection];if(!M){l=!1;return}Object.entries(M.parentPropertyEntities||{}).some(m=>{const[S,v]=m;return S===i[P.name]&&i[`${x.name}_Array`].some(y=>v.includes(y))})||(b=!1)}),k&&R){if(!(p||b)){l=!1;return}}else if(!p||!b){l=!1;return}return l},st=(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 d=$s(e,r)?.filter(h=>h.type==="Individual").length>0;return n==="Create"&&d&&(l=!1),qo(n,e,t,s,r,i)||(l=!1),l},ci=(n,e,t)=>{const{labels:s}=n,r=[];for(const i of Object.values(e.collections));return r},Bo=(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 d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),h=i.access.entityRestrictions?.restrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(u=>n.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,t=!1;return}if(d?.length||h?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const u=Object.keys(l);if(u.length!==1||u[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 u=Object.keys(l);if(!(u.length===1&&Object.keys(n.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,t=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(n.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[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},Ho=(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:d,entityRestrictions:h}=a,u=c.assignable,f=e.collections?.[o.collection],w=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(t))?w.forEach(p=>{const k=p.charAt(0).toUpperCase()+p.slice(1);if(p!=="assignable"){const b=!!a.operations[p]?.includes(t),R=!!f?.operations.includes(k);if(!b&&R){r=`Collection ${o.collection} has excess ${p} operation for role ${t}`,s=!1;return}if(b&&!R){r=`Collection ${o.collection} has missing ${p} operation for role ${t}`,s=!1;return}}}):w.forEach(p=>{const k=p.charAt(0).toUpperCase()+p.slice(1);if(p!=="assignable"){const b=!!a.operations[p]?.includes(t),R=!!f?.operations.includes(k);if(!b&&R){r=`Collection ${o.collection} has excess ${p} operation for role ${t}`,s=!1;return}}}),!d&&!h||(d?.forEach(p=>{for(const k of p.roles)if(k.role===t&&!k.assignable){if(p.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(p.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(p.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 E=!1;if(h?.restrictions?.forEach(p=>{for(const k of p.roles)if(k.role===t){if(E=!0,p.type==="Individual"&&!e.collections?.[o.collection]?.individualEntities){r=`Collection ${o.collection} is missing individual entities`,s=!1;return}if(p.type==="Parent"){const b=W(l,p.collectionField);if(!K(b)){s=!1;return}if(!e.collections?.[o.collection]?.parentEntities){r=`Collection ${o.collection} is missing parent entities`,s=!1;return}}if(p.type==="Parent_Property"){const b=W(l,p.collectionField);if(!K(b)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[b.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),E&&!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},Go=(n,e,t,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:d}=c;let h=!0,u="";const f=d?.filter(w=>s===w.userRole);return f?.length&&!f.some(w=>w.recordRole===r)?(u=`User ${s} does not have write access to record with role ${r}`,h=!1,h):n==="update"&&o.User_ID&&f?.length&&!f.some(w=>w.recordRole===a)?(u=`User ${s} does not have write access to record with role ${r}`,h=!1,h):(d?.forEach(w=>{s===w.userRole&&w.recordRole===r&&n!=="delete"&&i&&Object.keys(t.collections).forEach(E=>{const p=i.collections?.[E],k=l?.collections?.[E];if(!(n==="update"&&ze(p,k))&&p){const b=w.collections.some(R=>R.collection===E);if(b){if(b){const R=w.collections.find(T=>T.collection===E);if(!(p.operations.every(T=>R.operations.includes(T))||n==="update"&&ze(p.operations,k?.operations))){u=`User ${s} does not have write access to all included operations for collection ${E}`,h=!1;return}if(!R.auth&&p.auth&&!(n==="update"&&ze(p.auth,k?.auth))){u=`User ${s} does not have write access to auth for collection ${E}`,h=!1;return}const g={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(g).forEach(T=>{const _=g[T];if(R.attributeRestrictions?.includes(_)&&!(p[T]?.active||n==="update"&&ze(p[T],k?.[T]))){u=`User ${s} does not have write access to attribute restriction ${T} for collection ${E}`,h=!1;return}}),R.restrictEntities&&!p.restrictEntities&&!(n==="update"&&ze(p.restrictEntities,k?.restrictEntities))){u=`User ${s} does not have write access to restrictEntities for collection ${E}`,h=!1;return}}}else{u=`User ${s} does not have write access to collection ${E}`,h=!1;return}}})}),u&&console.error(`PERMISSION_DENIED: ${u}`),h)},Yo=(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&&!Ln(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const d of a?.operations||[])if(!l?.operations.includes(d)&&(!Se("Read",c)||!Se(d,c))){i=`User does not have ${d.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},Ms=(n,e,t,s,r,i,o,a,l,c,d)=>{const{labels:h}=s;let u=!0,f="";if(!e.Role)return f="Record does not have a role",u=!1,u;if(n==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(n==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!Go(n,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(n==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;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 f="User cannot update their own record",u=!1,u;if(n==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return n==="delete"||d==="delete"||!a?u:a.Role?(Bo(r,a)||(u=!1),a.Collection&&a.Collection!==h.collection?(f="Permissions collection does not match record collection",u=!1,u):a.Role!==e.Role?(f="Permissions role does not match record role",u=!1,u):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",u=!1,u):a.Doc_ID&&a.Doc_ID!==t?(f="Permissions doc ID does not match record doc ID",u=!1,u):!Ho(r,a,a.Role)||i&&o&&l&&!Yo(r,o,a,l)?(u=!1,u):(f&&console.error(`PERMISSION_DENIED: ${f}`),u)):(f="Permissions do not have a role",u=!1,u)},lr=(n,e,t,s,r,i,o)=>{const{labels:a,fields:l}=t,c=i?.collections?.[a.collection];let d=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!Se("Create",c)&&(d=!1),r&&!st("Create",t,s,r,i,n)&&(d=!1),t.auth&&o&&(r&&!Ln(c)&&(d=!1),Ms("create",n,e,t,s,r,i,o)||(d=!1));for(const h of l){const u=n[h.name];h.access&&!Vn(h,i)&&u!==void 0&&(d=!1),u!==void 0&&!zo(h,i)&&(d=!1)}if(!d)throw new Error("PERMISSION_DENIED")},Ne=n=>n&&(n._methodName==="deleteField"||n.constructor.name==="DeleteTransform"),et=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&&et(n[e]))},cr=(n,e,t,s,r,i,o,a,l,c)=>{const{labels:d,fields:h}=s,u=o?.collections?.[d.collection],f={...e,...n};et(f);let w=!0,E="";if(i&&!u)throw new Error("PERMISSION_DENIED");i&&!Se("Update",u)&&(w=!1,E="Authenticated user does not have Update access to this collection"),i&&(!st("Update",s,r,i,o,e)||!st("Update",s,r,i,o,f))&&(w=!1,E="Authenticated user does not have Update access to this document"),a&&(i&&!Ln(u)&&(w=!1,E="Authenticated user does not have Auth access for this collection"),Ms("update",f,t,s,r,i,o,l,c,e,a)||(E="Authenticated user does not have sufficient write access for this record",w=!1));for(const p of h){const k=n[p.name];p.access&&!Vn(p,o)&&k!==void 0&&(E=`Authenticated user does not have access to field ${p.name}`,w=!1),k!==void 0&&!ii(p,o)&&(E=`Authenticated user does not have Update access to field ${p.name}`,w=!1)}if(!w)throw E&&console.error(`PERMISSION_DENIED: ${E}`),new Error("PERMISSION_DENIED")},Jo=(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),st("Delete",t,s,r,i,n)||(l=!1),t.auth&&n.User_ID&&(Ln(a)||(l=!1),Ms("delete",n,e,t,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},Qo=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),st("Read",e,t,s,r,n)||(a=!1),!a)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),n.forEach(l=>{st("Read",e,t,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},Xo=(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)},ea=(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(!K(o))throw new Error("PERMISSION_DENIED");const l=t.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(d=>d.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},ta=(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 d in c)d==="custom"||d==="admin"||d==="name"||d==="formula"||delete c[d];i[o]=l}return i},Ie=(n,e)=>e.fields.filter(t=>t.name===n.name)[0],Jn={global:{},collections:{}},Zt=(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},na=async(n,e,t,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=Jn,i=!0;for(const d of e){if(d===void 0||r[d]===void 0){i=!1;break}r=r[d]}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 d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await ie(a,t)),c){let d=Jn;const h={};for(let u=0;u<e.length;u++){const f=e[u];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");u===e.length-1?Wo(h,e.join("."),c):(d[f]||={},d=d[f])}}Uo(Jn,h)}return c},it=(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(K(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field==n.name&&(i=!0)}return i},ui=(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=>{K(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},Qn=n=>JSON.stringify(n.map(e=>e.name)),dt=["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"],Un=()=>dt.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}),di=(n,e)=>{const t=[],{access:s,fields:r}=n,{attributeRestrictions:i,entityRestrictions:o}=s,a=Un();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)]},sa=(n,e)=>{const t=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=n,a=Un();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=>{dt.includes(c)&&t.push(W(a,c))}),o?.forEach(c=>{const d=W(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&d&&(!d.access||d.access?.includes(e))&&dt.includes(c.field)&&t.push(W(a,c.field))}),di(n,e).forEach(c=>{dt.includes(c.name)&&t.push(W(a,c.name))}),[...new Set(t)]},ra=(n,e,t)=>{const s=[],{fields:r,preloadCache:i}=e,o=Un();i?.range&&i.range.fields.forEach(c=>{dt.includes(c)?s.push(W(o,c)):s.push(W(r,c))});const a=new Set,l=ui(e,t);return Object.entries(l).map(([c,d])=>{n.name===c&&Object.values(d).forEach(h=>{h.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(...di(e,c))}),[...new Set(s)]},ln=(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=ui(e,t);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{t.collections[c].fields.forEach(h=>{K(h)&&h.collection===e.labels.collection&&h.dependencyFields?.some(u=>u.field===n.name)&&h.constraints&&h.constraints.forEach(u=>{o.push(u[0])})})})}),o.forEach(l=>{s.push(W(r,l))}),i){const l=W(r,i.archivedField);l&&s.push(l)}return s.push(...ra(n,e,t)),[...new Set(s)]},fi=(n,e)=>{const{preloadCache:t}=n,s=new Set;for(const r of e.config.roles){if(!Xo(n,r,"read"))continue;const i=sa(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},hi=(n,e,t)=>{const s=fi(e,t);for(const r of s.values())if(r.roles.includes(n))return r},ia=(n,e)=>{const{fields:t}=e,s=Un(),r=[];return[...t,...s.filter(o=>o.name!=="id")].forEach(o=>{n?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ps=(n,e,t)=>{const s={};return Object.values(n.collections).forEach(r=>{const i=fi(r,n),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},vn=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}),Kn=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 ae(n,e,t,s){const r=await Kn(n,t.custom?.[n],s);for(const i of t.fields)await Kn(n,i.custom?.[n],s);if(n!=="setEmbedding"&&(await Kn(n,e?.[n],s),n==="postWriteError"))return r}const Ls=(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),lt=(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)&&K(a)&&["OneToOne","OneToMany"].includes(a.type)&&i.add(a)}return e.forEach(o=>{K(o)&&["OneToOne","OneToMany"].includes(o.type)&&o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a)))&&i.add(o)}),i},pt=(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},On=(n,e,t)=>{const{fields:s}=n;s.forEach(i=>{if(K(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);pt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(d=>{e[i.name][d][o]?e[i.name][d][`${o}_Lowercase`]=e[i.name][d][o].toLowerCase():delete e[i.name][d][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),lt(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}}}})},kn=(n,e)=>{pt(n,n.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},oa=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]),pt(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"),!K(i)&&i.nullable&&n[i.name]===void 0&&(n[i.name]=null))};var te;(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})(te||(te={}));var ur;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(ur||(ur={}));const U=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Qe=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=te.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,te.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 ps=(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,te.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:t=`Unrecognized key(s) in object: ${te.joinValues(n.keys,", ")}`;break;case D.invalid_union:t="Invalid input";break;case D.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${te.joinValues(n.options)}`;break;case D.invalid_enum_value:t=`Invalid enum value. Expected ${te.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}"`:te.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,te.assertNever(n)}return{message:t}};let aa=ps;function la(){return aa}const ca=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 $(n,e){const t=la(),s=ca({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ps?void 0:ps].filter(r=>!!r)});n.common.issues.push(s)}class _e{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 Y;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 _e.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 Y;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 Y=Object.freeze({status:"aborted"}),zt=n=>({status:"dirty",value:n}),Ae=n=>({status:"valid",value:n}),dr=n=>n.status==="aborted",fr=n=>n.status==="dirty",Rt=n=>n.status==="valid",bn=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 hr=(n,e)=>{if(Rt(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 J(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 X{get description(){return this._def.description}_getType(e){return Qe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Qe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _e,ctx:{common:e.parent.common,data:e.data,parsedType:Qe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(bn(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:Qe(e)},r=this._parseSync({data:e,path:s.path,parent:s});return hr(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Qe(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return Rt(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=>Rt(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:Qe(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(bn(r)?r:Promise.resolve(r));return hr(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 Dt({schema:this,typeName:G.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 tt.create(this,this._def)}nullable(){return It.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ve.create(this)}promise(){return xn.create(this,this._def)}or(e){return Tn.create([this,e],this._def)}and(e){return Rn.create(this,e,this._def)}transform(e){return new Dt({...J(this._def),schema:this,typeName:G.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new vs({...J(this._def),innerType:this,defaultValue:t,typeName:G.ZodDefault})}brand(){return new Aa({typeName:G.ZodBranded,type:this,...J(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Os({...J(this._def),innerType:this,catchValue:t,typeName:G.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Vs.create(this,e)}readonly(){return ks.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ua=/^c[^\s-]{8,}$/i,da=/^[0-9a-z]+$/,fa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ha=/^[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,ma=/^[a-z0-9_-]{21}$/i,pa=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ya=/^[-+]?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)?)??$/,ga=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wa="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Xn;const _a=/^(?:(?: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])$/,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])\/(3[0-2]|[12]?[0-9])$/,va=/^(([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]))$/,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]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ka=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ba=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mi="((\\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])))",Sa=new RegExp(`^${mi}$`);function pi(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 Ta(n){return new RegExp(`^${pi(n)}$`)}function Ra(n){let e=`${mi}T${pi(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 Na(n,e){return!!((e==="v4"||!e)&&_a.test(n)||(e==="v6"||!e)&&va.test(n))}function xa(n,e){if(!pa.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 Da(n,e){return!!((e==="v4"||!e)&&Ea.test(n)||(e==="v6"||!e)&&Oa.test(n))}class qe extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){const i=this._getOrReturnCtx(e);return $(i,{code:D.invalid_type,expected:U.string,received:i.parsedType}),Y}const s=new _e;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),$(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),$(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?$(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&$(r,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")ga.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"email",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")Xn||(Xn=new RegExp(wa,"u")),Xn.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"emoji",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")ha.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"uuid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")ma.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"nanoid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")ua.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"cuid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")da.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"cuid2",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")fa.test(e.data)||(r=this._getOrReturnCtx(e,r),$(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),$(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),$(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),$(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),$(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),$(r,{code:D.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Ra(i).test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{code:D.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Sa.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{code:D.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Ta(i).test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{code:D.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ya.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"duration",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Na(e.data,i.version)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"ip",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?xa(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"jwt",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Da(e.data,i.version)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"cidr",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?ka.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?ba.test(e.data)||(r=this._getOrReturnCtx(e,r),$(r,{validation:"base64url",code:D.invalid_string,message:i.message}),s.dirty()):te.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:G.ZodString,coerce:n?.coerce??!1,...J(n)});function Ia(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 Nt extends X{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 $(i,{code:D.invalid_type,expected:U.number,received:i.parsedType}),Y}let s;const r=new _e;for(const i of this._def.checks)i.kind==="int"?te.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),$(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),$(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),$(s,{code:D.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Ia(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),$(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),$(s,{code:D.not_finite,message:i.message}),r.dirty()):te.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 Nt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:Z.toString(r)}]})}_addCheck(e){return new Nt({...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"&&te.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)}}Nt.create=n=>new Nt({checks:[],typeName:G.ZodNumber,coerce:n?.coerce||!1,...J(n)});class Kt extends X{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 _e;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),$(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),$(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),$(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):te.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return $(t,{code:D.invalid_type,expected:U.bigint,received:t.parsedType}),Y}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 Kt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:Z.toString(r)}]})}_addCheck(e){return new Kt({...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}}Kt.create=n=>new Kt({checks:[],typeName:G.ZodBigInt,coerce:n?.coerce??!1,...J(n)});class ys extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.boolean,received:s.parsedType}),Y}return Ae(e.data)}}ys.create=n=>new ys({typeName:G.ZodBoolean,coerce:n?.coerce||!1,...J(n)});class Sn extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){const i=this._getOrReturnCtx(e);return $(i,{code:D.invalid_type,expected:U.date,received:i.parsedType}),Y}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return $(i,{code:D.invalid_date}),Y}const s=new _e;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),$(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),$(r,{code:D.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):te.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Sn({...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}}Sn.create=n=>new Sn({checks:[],coerce:n?.coerce||!1,typeName:G.ZodDate,...J(n)});class mr extends X{_parse(e){if(this._getType(e)!==U.symbol){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.symbol,received:s.parsedType}),Y}return Ae(e.data)}}mr.create=n=>new mr({typeName:G.ZodSymbol,...J(n)});class gs extends X{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.undefined,received:s.parsedType}),Y}return Ae(e.data)}}gs.create=n=>new gs({typeName:G.ZodUndefined,...J(n)});class pr extends X{_parse(e){if(this._getType(e)!==U.null){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.null,received:s.parsedType}),Y}return Ae(e.data)}}pr.create=n=>new pr({typeName:G.ZodNull,...J(n)});class ws extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return Ae(e.data)}}ws.create=n=>new ws({typeName:G.ZodAny,...J(n)});class yr extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ae(e.data)}}yr.create=n=>new yr({typeName:G.ZodUnknown,...J(n)});class rt extends X{_parse(e){const t=this._getOrReturnCtx(e);return $(t,{code:D.invalid_type,expected:U.never,received:t.parsedType}),Y}}rt.create=n=>new rt({typeName:G.ZodNever,...J(n)});class gr extends X{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.void,received:s.parsedType}),Y}return Ae(e.data)}}gr.create=n=>new gr({typeName:G.ZodVoid,...J(n)});class Ve extends X{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==U.array)return $(t,{code:D.invalid_type,expected:U.array,received:t.parsedType}),Y;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&($(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&&($(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&&($(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=>_e.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new We(t,o,t.path,a)));return _e.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:G.ZodArray,...J(e)});function vt(n){if(n instanceof de){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=tt.create(vt(s))}return new de({...n._def,shape:()=>e})}else return n instanceof Ve?new Ve({...n._def,type:vt(n.element)}):n instanceof tt?tt.create(vt(n.unwrap())):n instanceof It?It.create(vt(n.unwrap())):n instanceof ft?ft.create(n.items.map(e=>vt(e))):n}class de extends X{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=te.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 $(c,{code:D.invalid_type,expected:U.object,received:c.parsedType}),Y}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof rt&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const d=i[c],h=r.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new We(r,h,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof rt){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")a.length>0&&($(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 d of a){const h=r.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new We(r,h,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const h=await d.key,u=await d.value;c.push({key:h,value:u,alwaysSet:d.alwaysSet})}return c}).then(c=>_e.mergeObjectSync(s,c)):_e.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return Z.errToObj,new de({...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 de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:G.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const t={};for(const s of te.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const s of te.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new de({...this._def,shape:()=>t})}deepPartial(){return vt(this)}partial(e){const t={};for(const s of te.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const s of te.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof tt;)i=i._def.innerType;t[s]=i}return new de({...this._def,shape:()=>t})}keyof(){return yi(te.objectKeys(this.shape))}}de.create=(n,e)=>new de({shape:()=>n,unknownKeys:"strip",catchall:rt.create(),typeName:G.ZodObject,...J(e)});de.strictCreate=(n,e)=>new de({shape:()=>n,unknownKeys:"strict",catchall:rt.create(),typeName:G.ZodObject,...J(e)});de.lazycreate=(n,e)=>new de({shape:n,unknownKeys:"strip",catchall:rt.create(),typeName:G.ZodObject,...J(e)});class Tn extends X{_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 $(t,{code:D.invalid_union,unionErrors:o}),Y}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},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,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 $(t,{code:D.invalid_union,unionErrors:a}),Y}}get options(){return this._def.options}}Tn.create=(n,e)=>new Tn({options:n,typeName:G.ZodUnion,...J(e)});function _s(n,e){const t=Qe(n),s=Qe(e);if(n===e)return{valid:!0,data:n};if(t===U.object&&s===U.object){const r=te.objectKeys(e),i=te.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(const a of i){const l=_s(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=_s(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 Rn extends X{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(dr(i)||dr(o))return Y;const a=_s(i.value,o.value);return a.valid?((fr(i)||fr(o))&&t.dirty(),{status:t.value,value:a.data}):($(s,{code:D.invalid_intersection_types}),Y)};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}))}}Rn.create=(n,e,t)=>new Rn({left:n,right:e,typeName:G.ZodIntersection,...J(t)});class ft extends X{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.array)return $(s,{code:D.invalid_type,expected:U.array,received:s.parsedType}),Y;if(s.data.length<this._def.items.length)return $(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Y;!this._def.rest&&s.data.length>this._def.items.length&&($(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=>_e.mergeArray(t,o)):_e.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new ft({...this._def,rest:e})}}ft.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ft({items:n,typeName:G.ZodTuple,rest:null,...J(e)})};class Nn extends X{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 $(s,{code:D.invalid_type,expected:U.object,received:s.parsedType}),Y;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?_e.mergeObjectAsync(t,r):_e.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof X?new Nn({keyType:e,valueType:t,typeName:G.ZodRecord,...J(s)}):new Nn({keyType:qe.create(),valueType:e,typeName:G.ZodRecord,...J(t)})}}class wr extends X{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 $(s,{code:D.invalid_type,expected:U.map,received:s.parsedType}),Y;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,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return Y;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return Y;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}}}}wr.create=(n,e,t)=>new wr({valueType:e,keyType:n,typeName:G.ZodMap,...J(t)});class Xt extends X{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.set)return $(s,{code:D.invalid_type,expected:U.set,received:s.parsedType}),Y;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&($(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&&($(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 d of l){if(d.status==="aborted")return Y;d.status==="dirty"&&t.dirty(),c.add(d.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 Xt({...this._def,minSize:{value:e,message:Z.toString(t)}})}max(e,t){return new Xt({...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)}}Xt.create=(n,e)=>new Xt({valueType:n,minSize:null,maxSize:null,typeName:G.ZodSet,...J(e)});class _r extends X{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})}}_r.create=(n,e)=>new _r({getter:n,typeName:G.ZodLazy,...J(e)});class Es extends X{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return $(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),Y}return{status:"valid",value:e.data}}get value(){return this._def.value}}Es.create=(n,e)=>new Es({value:n,typeName:G.ZodLiteral,...J(e)});function yi(n,e){return new xt({values:n,typeName:G.ZodEnum,...J(e)})}class xt extends X{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return $(t,{expected:te.joinValues(s),received:t.parsedType,code:D.invalid_type}),Y}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 $(t,{received:t.data,code:D.invalid_enum_value,options:s}),Y}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 xt.create(e,{...this._def,...t})}exclude(e,t=this._def){return xt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}xt.create=yi;class Er extends X{_parse(e){const t=te.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==U.string&&s.parsedType!==U.number){const r=te.objectValues(t);return $(s,{expected:te.joinValues(r),received:s.parsedType,code:D.invalid_type}),Y}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=te.objectValues(t);return $(s,{received:s.data,code:D.invalid_enum_value,options:r}),Y}return Ae(e.data)}get enum(){return this._def.values}}Er.create=(n,e)=>new Er({values:n,typeName:G.ZodNativeEnum,...J(e)});class xn extends X{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.promise&&t.common.async===!1)return $(t,{code:D.invalid_type,expected:U.promise,received:t.parsedType}),Y;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})))}}xn.create=(n,e)=>new xn({type:n,typeName:G.ZodPromise,...J(e)});class Dt extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===G.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=>{$(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 Y;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?Y:l.status==="dirty"||t.value==="dirty"?zt(l.value):l});{if(t.value==="aborted")return Y;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?Y:a.status==="dirty"||t.value==="dirty"?zt(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"?Y:(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"?Y:(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(!Rt(o))return Y;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=>Rt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):Y);te.assertNever(r)}}Dt.create=(n,e,t)=>new Dt({schema:n,typeName:G.ZodEffects,effect:e,...J(t)});Dt.createWithPreprocess=(n,e,t)=>new Dt({schema:e,effect:{type:"preprocess",transform:n},typeName:G.ZodEffects,...J(t)});class tt extends X{_parse(e){return this._getType(e)===U.undefined?Ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}tt.create=(n,e)=>new tt({innerType:n,typeName:G.ZodOptional,...J(e)});class It extends X{_parse(e){return this._getType(e)===U.null?Ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}It.create=(n,e)=>new It({innerType:n,typeName:G.ZodNullable,...J(e)});class vs extends X{_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}}vs.create=(n,e)=>new vs({innerType:n,typeName:G.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});class Os extends X{_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 bn(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}}Os.create=(n,e)=>new Os({innerType:n,typeName:G.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});class vr extends X{_parse(e){if(this._getType(e)!==U.nan){const s=this._getOrReturnCtx(e);return $(s,{code:D.invalid_type,expected:U.nan,received:s.parsedType}),Y}return{status:"valid",value:e.data}}}vr.create=n=>new vr({typeName:G.ZodNaN,...J(n)});class Aa extends X{_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 Vs extends X{_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"?Y:i.status==="dirty"?(t.dirty(),zt(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"?Y: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 Vs({in:e,out:t,typeName:G.ZodPipeline})}}class ks extends X{_parse(e){const t=this._def.innerType._parse(e),s=r=>(Rt(r)&&(r.value=Object.freeze(r.value)),r);return bn(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}ks.create=(n,e)=>new ks({innerType:n,typeName:G.ZodReadonly,...J(e)});var G;(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"})(G||(G={}));const ke=qe.create,ct=Nt.create,Jt=ys.create,es=gs.create,pe=ws.create;rt.create;const yt=Ve.create,Ue=de.create,ve=Tn.create;Rn.create;ft.create;const nn=Nn.create,Oe=Es.create,Dn=xt.create;xn.create;tt.create;It.create;const pn=()=>pe().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"}),Or=()=>pe().refine(n=>n&&(n._methodName==="serverTimestamp"||n.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),gi=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return nn(pe());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]=In(s,i),pt(s,[i]).size===1&&(t[`${r}_Lowercase`]=In(s,i,!0))})}return Ue({Collection_Path:yt(ke()),...t})},Ca=(n,e)=>{let t=nn(gi(n,e));return n.required||(t=t.optional()),t},Fa=n=>{let e=yt(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},In=(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=Dn(o)}else i=Dn(e.values);break;case"Boolean":i=Jt();break;case"Number":e.autoIncrement?i=ve([Oe("Pending"),ct().int()]):(i=ct(),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=pe().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=pn(),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=yt(pe()),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=nn(pe()),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=pe();break}return!K(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},wi=(n,e,t)=>{const s={Collection_Path:yt(ke()),Last_Write_App:ke(),Last_Write_At:pn(),Last_Save_At:Or(),Last_Write_By:ve([ke().length(28),Oe("System")]),Last_Write_Connection_Status:Dn(["Online","Offline"]),Last_Write_Version:ct().int(),id:ke().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:pn(),Created_By:ve([ke().length(28),Oe("System")])};n==="create"&&(s.Saved_At=Or()),n==="update"&&(s.Saved_At=pn(),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=lt(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{K(l)?(s[l.name]=Ca(l,t),s[`${l.name}_Array`]=Fa(l),i.includes(l.name)&&(s[`${l.name}_Single`]=gi(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]=In(e,l))}),pt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=In(e,l,!0))});const a=Ue(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class gt extends Error{}class $a extends gt{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Ma extends gt{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class Pa extends gt{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Ot extends gt{}class _i extends gt{constructor(e){super(`Invalid unit ${e}`)}}class ye extends gt{}class Je extends gt{constructor(){super("Zone is an abstract class")}}const F="numeric",Me="short",be="long",An={year:F,month:F,day:F},Ei={year:F,month:Me,day:F},La={year:F,month:Me,day:F,weekday:Me},vi={year:F,month:be,day:F},Oi={year:F,month:be,day:F,weekday:be},ki={hour:F,minute:F},bi={hour:F,minute:F,second:F},Si={hour:F,minute:F,second:F,timeZoneName:Me},Ti={hour:F,minute:F,second:F,timeZoneName:be},Ri={hour:F,minute:F,hourCycle:"h23"},Ni={hour:F,minute:F,second:F,hourCycle:"h23"},xi={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:Me},Di={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:be},Ii={year:F,month:F,day:F,hour:F,minute:F},Ai={year:F,month:F,day:F,hour:F,minute:F,second:F},Ci={year:F,month:Me,day:F,hour:F,minute:F},Fi={year:F,month:Me,day:F,hour:F,minute:F,second:F},Va={year:F,month:Me,day:F,weekday:Me,hour:F,minute:F},$i={year:F,month:be,day:F,hour:F,minute:F,timeZoneName:Me},Mi={year:F,month:be,day:F,hour:F,minute:F,second:F,timeZoneName:Me},Pi={year:F,month:be,day:F,weekday:be,hour:F,minute:F,timeZoneName:be},Li={year:F,month:be,day:F,weekday:be,hour:F,minute:F,second:F,timeZoneName:be};class sn{get type(){throw new Je}get name(){throw new Je}get ianaName(){return this.name}get isUniversal(){throw new Je}offsetName(e,t){throw new Je}formatOffset(e,t){throw new Je}offset(e){throw new Je}equals(e){throw new Je}get isValid(){throw new Je}}let ts=null;class Wn extends sn{static get instance(){return ts===null&&(ts=new Wn),ts}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Yi(e,t,s)}formatOffset(e,t){return Qt(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const bs=new Map;function Ua(n){let e=bs.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"}),bs.set(n,e)),e}const Wa={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ja(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,d]=s;return[o,r,i,a,l,c,d]}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=Wa[i];i==="era"?s[a]=o:H(a)||(s[a]=parseInt(o,10))}return s}const ns=new Map;class He extends sn{static create(e){let t=ns.get(e);return t===void 0&&ns.set(e,t=new He(e)),t}static resetCache(){ns.clear(),bs.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 Yi(e,t,s,this.name)}formatOffset(e,t){return Qt(this.offset(e),t)}offset(e){if(!this.valid)return NaN;const t=new Date(e);if(isNaN(t))return NaN;const s=Ua(this.name);let[r,i,o,a,l,c,d]=s.formatToParts?Za(s,t):ja(s,t);a==="BC"&&(r=-Math.abs(r)+1);const u=Zn({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:d,millisecond:0});let f=+t;const w=f%1e3;return f-=w>=0?w:1e3+w,(u-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let kr={};function za(n,e={}){const t=JSON.stringify([n,e]);let s=kr[t];return s||(s=new Intl.ListFormat(n,e),kr[t]=s),s}const Ss=new Map;function Ts(n,e={}){const t=JSON.stringify([n,e]);let s=Ss.get(t);return s===void 0&&(s=new Intl.DateTimeFormat(n,e),Ss.set(t,s)),s}const Rs=new Map;function qa(n,e={}){const t=JSON.stringify([n,e]);let s=Rs.get(t);return s===void 0&&(s=new Intl.NumberFormat(n,e),Rs.set(t,s)),s}const Ns=new Map;function Ba(n,e={}){const{base:t,...s}=e,r=JSON.stringify([n,s]);let i=Ns.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(n,e),Ns.set(r,i)),i}let qt=null;function Ha(){return qt||(qt=new Intl.DateTimeFormat().resolvedOptions().locale,qt)}const xs=new Map;function Vi(n){let e=xs.get(n);return e===void 0&&(e=new Intl.DateTimeFormat(n).resolvedOptions(),xs.set(n,e)),e}const Ds=new Map;function Ga(n){let e=Ds.get(n);if(!e){const t=new Intl.Locale(n);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,"minimalDays"in e||(e={...Ui,...e}),Ds.set(n,e)}return e}function Ya(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=Ts(n).resolvedOptions(),r=n}catch{const l=n.substring(0,t);s=Ts(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function Ja(n,e,t){return(t||e)&&(n.includes("-u-")||(n+="-u"),t&&(n+=`-ca-${t}`),e&&(n+=`-nu-${e}`)),n}function Qa(n){const e=[];for(let t=1;t<=12;t++){const s=L.utc(2009,t,1);e.push(n(s))}return e}function Ka(n){const e=[];for(let t=1;t<=7;t++){const s=L.utc(2016,11,13+t);e.push(n(s))}return e}function cn(n,e,t,s){const r=n.listingMode();return r==="error"?null:r==="en"?t(e):s(e)}function Xa(n){return n.numberingSystem&&n.numberingSystem!=="latn"?!1:n.numberingSystem==="latn"||!n.locale||n.locale.startsWith("en")||Vi(n.locale).numberingSystem==="latn"}class el{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=qa(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):zs(e,3);return fe(t,this.padTo)}}}class tl{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=Ts(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 nl{constructor(e,t,s){this.opts={style:"long",...s},!t&&Hi()&&(this.rtf=Ba(e,s))}format(e,t){return this.rtf?this.rtf.format(e,t):bl(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}}const Ui={firstDay:1,minimalDays:4,weekend:[6,7]};class se{static fromOpts(e){return se.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,s,r,i=!1){const o=e||ce.defaultLocale,a=o||(i?"en-US":Ha()),l=t||ce.defaultNumberingSystem,c=s||ce.defaultOutputCalendar,d=As(r)||ce.defaultWeekSettings;return new se(a,l,c,d,o)}static resetCache(){qt=null,Ss.clear(),Rs.clear(),Ns.clear(),xs.clear(),Ds.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:r}={}){return se.create(e,t,s,r)}constructor(e,t,s,r,i){const[o,a,l]=Ya(e);this.locale=o,this.numberingSystem=t||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=Ja(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=Xa(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:se.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,As(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 cn(this,e,Ki,()=>{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]=Qa(o)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return cn(this,e,to,()=>{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]=Ka(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return cn(this,void 0,()=>no,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[L.utc(2016,11,13,9),L.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return cn(this,e,so,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[L.utc(-40,1,1),L.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 el(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new tl(e,this.intl,t)}relFormatter(e={}){return new nl(this.intl,this.isEnglish(),e)}listFormatter(e={}){return za(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||Vi(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Gi()?Ga(this.locale):Ui}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 ss=null;class we extends sn{static get utcInstance(){return ss===null&&(ss=new we(0)),ss}static instance(e){return e===0?we.utcInstance:new we(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new we(zn(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Qt(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Qt(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return Qt(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 sl extends sn{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 Xe(n,e){if(H(n)||n===null)return e;if(n instanceof sn)return n;if(cl(n)){const t=n.toLowerCase();return t==="default"?e:t==="local"||t==="system"?Wn.instance:t==="utc"||t==="gmt"?we.utcInstance:we.parseSpecifier(t)||He.create(n)}else return nt(n)?we.instance(n):typeof n=="object"&&"offset"in n&&typeof n.offset=="function"?n:new sl(n)}const Us={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},br={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]},rl=Us.hanidec.replace(/[\[|\]]/g,"").split("");function il(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(Us.hanidec)!==-1)e+=rl.indexOf(n[t]);else for(const r in br){const[i,o]=br[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const Is=new Map;function ol(){Is.clear()}function Ce({numberingSystem:n},e=""){const t=n||"latn";let s=Is.get(t);s===void 0&&(s=new Map,Is.set(t,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${Us[t]}${e}`),s.set(e,r)),r}let Sr=()=>Date.now(),Tr="system",Rr=null,Nr=null,xr=null,Dr=60,Ir,Ar=null;class ce{static get now(){return Sr}static set now(e){Sr=e}static set defaultZone(e){Tr=e}static get defaultZone(){return Xe(Tr,Wn.instance)}static get defaultLocale(){return Rr}static set defaultLocale(e){Rr=e}static get defaultNumberingSystem(){return Nr}static set defaultNumberingSystem(e){Nr=e}static get defaultOutputCalendar(){return xr}static set defaultOutputCalendar(e){xr=e}static get defaultWeekSettings(){return Ar}static set defaultWeekSettings(e){Ar=As(e)}static get twoDigitCutoffYear(){return Dr}static set twoDigitCutoffYear(e){Dr=e%100}static get throwOnInvalid(){return Ir}static set throwOnInvalid(e){Ir=e}static resetCaches(){se.resetCache(),He.resetCache(),L.resetCache(),ol()}}class $e{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Wi=[0,31,59,90,120,151,181,212,243,273,304,334],ji=[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 Ws(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 Zi(n,e,t){return t+(rn(n)?ji:Wi)[e-1]}function zi(n,e){const t=rn(n)?ji:Wi,s=t.findIndex(i=>i<e),r=e-t[s];return{month:s+1,day:r}}function js(n,e){return(n-e+7)%7+1}function Cn(n,e=4,t=1){const{year:s,month:r,day:i}=n,o=Zi(s,r,i),a=js(Ws(s,r,i),t);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=en(c,e,t)):l>en(s,e,t)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...qn(n)}}function Cr(n,e=4,t=1){const{weekYear:s,weekNumber:r,weekday:i}=n,o=js(Ws(s,1,e),t),a=St(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=St(c)):l>a?(c=s+1,l-=St(s)):c=s;const{month:d,day:h}=zi(c,l);return{year:c,month:d,day:h,...qn(n)}}function rs(n){const{year:e,month:t,day:s}=n,r=Zi(e,t,s);return{year:e,ordinal:r,...qn(n)}}function Fr(n){const{year:e,ordinal:t}=n,{month:s,day:r}=zi(e,t);return{year:e,month:s,day:r,...qn(n)}}function $r(n,e){if(!H(n.localWeekday)||!H(n.localWeekNumber)||!H(n.localWeekYear)){if(!H(n.weekday)||!H(n.weekNumber)||!H(n.weekYear))throw new Ot("Cannot mix locale-based week fields with ISO-based week fields");return H(n.localWeekday)||(n.weekday=n.localWeekday),H(n.localWeekNumber)||(n.weekNumber=n.localWeekNumber),H(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 al(n,e=4,t=1){const s=jn(n.weekYear),r=De(n.weekNumber,1,en(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 ll(n){const e=jn(n.year),t=De(n.ordinal,1,St(n.year));return e?t?!1:xe("ordinal",n.ordinal):xe("year",n.year)}function qi(n){const e=jn(n.year),t=De(n.month,1,12),s=De(n.day,1,Fn(n.year,n.month));return e?t?s?!1:xe("day",n.day):xe("month",n.month):xe("year",n.year)}function Bi(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 H(n){return typeof n>"u"}function nt(n){return typeof n=="number"}function jn(n){return typeof n=="number"&&n%1===0}function cl(n){return typeof n=="string"}function ul(n){return Object.prototype.toString.call(n)==="[object Date]"}function Hi(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Gi(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function dl(n){return Array.isArray(n)?n:[n]}function Mr(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 fl(n,e){return e.reduce((t,s)=>(t[s]=n[s],t),{})}function At(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function As(n){if(n==null)return null;if(typeof n!="object")throw new ye("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 ye("Invalid week settings");return{firstDay:n.firstDay,minimalDays:n.minimalDays,weekend:Array.from(n.weekend)}}function De(n,e,t){return jn(n)&&n>=e&&n<=t}function hl(n,e){return n-e*Math.floor(n/e)}function fe(n,e=2){const t=n<0;let s;return t?s="-"+(""+-n).padStart(e,"0"):s=(""+n).padStart(e,"0"),s}function Ke(n){if(!(H(n)||n===null||n===""))return parseInt(n,10)}function ot(n){if(!(H(n)||n===null||n===""))return parseFloat(n)}function Zs(n){if(!(H(n)||n===null||n==="")){const e=parseFloat("0."+n)*1e3;return Math.floor(e)}}function zs(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 rn(n){return n%4===0&&(n%100!==0||n%400===0)}function St(n){return rn(n)?366:365}function Fn(n,e){const t=hl(e-1,12)+1,s=n+(e-t)/12;return t===2?rn(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function Zn(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 Pr(n,e,t){return-js(Ws(n,1,e),t)+e-1}function en(n,e=4,t=1){const s=Pr(n,e,t),r=Pr(n+1,e,t);return(St(n)-s+r)/7}function Cs(n){return n>99?n:n>ce.twoDigitCutoffYear?1900+n:2e3+n}function Yi(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 zn(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 Ji(n){const e=Number(n);if(typeof n=="boolean"||n===""||!Number.isFinite(e))throw new ye(`Invalid unit value ${n}`);return e}function $n(n,e){const t={};for(const s in n)if(At(n,s)){const r=n[s];if(r==null)continue;t[e(s)]=Ji(r)}return t}function Qt(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}${fe(t,2)}:${fe(s,2)}`;case"narrow":return`${r}${t}${s>0?`:${s}`:""}`;case"techie":return`${r}${fe(t,2)}${fe(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function qn(n){return fl(n,["hour","minute","second","millisecond"])}const ml=["January","February","March","April","May","June","July","August","September","October","November","December"],Qi=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],pl=["J","F","M","A","M","J","J","A","S","O","N","D"];function Ki(n){switch(n){case"narrow":return[...pl];case"short":return[...Qi];case"long":return[...ml];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 Xi=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],eo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],yl=["M","T","W","T","F","S","S"];function to(n){switch(n){case"narrow":return[...yl];case"short":return[...eo];case"long":return[...Xi];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const no=["AM","PM"],gl=["Before Christ","Anno Domini"],wl=["BC","AD"],_l=["B","A"];function so(n){switch(n){case"narrow":return[..._l];case"short":return[...wl];case"long":return[...gl];default:return null}}function El(n){return no[n.hour<12?0:1]}function vl(n,e){return to(e)[n.weekday-1]}function Ol(n,e){return Ki(e)[n.month-1]}function kl(n,e){return so(e)[n.year<0?0:1]}function bl(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],d=s?l?c[1]:c[2]||c[1]:l?r[n][0]:n;return o?`${a} ${d} ago`:`in ${a} ${d}`}function Lr(n,e){let t="";for(const s of n)s.literal?t+=s.val:t+=e(s.val);return t}const Sl={D:An,DD:Ei,DDD:vi,DDDD:Oi,t:ki,tt:bi,ttt:Si,tttt:Ti,T:Ri,TT:Ni,TTT:xi,TTTT:Di,f:Ii,ff:Ci,fff:$i,ffff:Pi,F:Ai,FF:Fi,FFF:Mi,FFFF:Li};class ge{static create(e,t={}){return new ge(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 Sl[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 fe(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=(f,w)=>this.loc.extract(e,f,w),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>s?El(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,w)=>s?Ol(e,f):i(w?{month:f}:{month:f,day:"numeric"},"month"),c=(f,w)=>s?vl(e,f):i(w?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),d=f=>{const w=ge.macroTokenToFormatOpts(f);return w?this.formatWithSystemDefault(e,w):f},h=f=>s?kl(e,f):i({era:f},"era"),u=f=>{switch(f){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 d(f)}};return Lr(ge.parseFormat(t),u)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[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=(d,h)=>u=>{const f=r(u);if(f){const w=h.isNegativeDuration&&f!==h.largestUnit?s:1;let E;return this.opts.signMode==="negativeLargestOnly"&&f!==h.largestUnit?E="never":this.opts.signMode==="all"?E="always":E="auto",this.num(d.get(f)*w,u.length,E)}else return u},o=ge.parseFormat(t),a=o.reduce((d,{literal:h,val:u})=>h?d:d.concat(u),[]),l=e.shiftTo(...a.map(r).filter(d=>d)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Lr(o,i(l,c))}}const ro=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Ct(...n){const e=n.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function Ft(...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 $t(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 io(...n){return(e,t)=>{const s={};let r;for(r=0;r<n.length;r++)s[n[r]]=Ke(e[t+r]);return[s,null,t+r]}}const oo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Tl=`(?:${oo.source}?(?:\\[(${ro.source})\\])?)?`,qs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,ao=RegExp(`${qs.source}${Tl}`),Bs=RegExp(`(?:[Tt]${ao.source})?`),Rl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Nl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,xl=/(\d{4})-?(\d{3})/,Dl=io("weekYear","weekNumber","weekDay"),Il=io("year","ordinal"),Al=/(\d{4})-(\d\d)-(\d\d)/,lo=RegExp(`${qs.source} ?(?:${oo.source}|(${ro.source}))?`),Cl=RegExp(`(?: ${lo.source})?`);function Tt(n,e,t){const s=n[e];return H(s)?t:Ke(s)}function Fl(n,e){return[{year:Tt(n,e),month:Tt(n,e+1,1),day:Tt(n,e+2,1)},null,e+3]}function Mt(n,e){return[{hours:Tt(n,e,0),minutes:Tt(n,e+1,0),seconds:Tt(n,e+2,0),milliseconds:Zs(n[e+3])},null,e+4]}function on(n,e){const t=!n[e]&&!n[e+1],s=zn(n[e+1],n[e+2]),r=t?null:we.instance(s);return[{},r,e+3]}function an(n,e){const t=n[e]?He.create(n[e]):null;return[{},t,e+1]}const $l=RegExp(`^T?${qs.source}$`),Ml=/^-?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 Pl(n){const[e,t,s,r,i,o,a,l,c]=n,d=e[0]==="-",h=l&&l[0]==="-",u=(f,w=!1)=>f!==void 0&&(w||f&&d)?-f:f;return[{years:u(ot(t)),months:u(ot(s)),weeks:u(ot(r)),days:u(ot(i)),hours:u(ot(o)),minutes:u(ot(a)),seconds:u(ot(l),l==="-0"),milliseconds:u(Zs(c),h)}]}const Ll={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Hs(n,e,t,s,r,i,o){const a={year:e.length===2?Cs(Ke(e)):Ke(e),month:Qi.indexOf(t)+1,day:Ke(s),hour:Ke(r),minute:Ke(i)};return o&&(a.second=Ke(o)),n&&(a.weekday=n.length>3?Xi.indexOf(n)+1:eo.indexOf(n)+1),a}const Vl=/^(?:(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 Ul(n){const[,e,t,s,r,i,o,a,l,c,d,h]=n,u=Hs(e,r,s,t,i,o,a);let f;return l?f=Ll[l]:c?f=0:f=zn(d,h),[u,new we(f)]}function Wl(n){return n.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const jl=/^(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$/,zl=/^(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 Vr(n){const[,e,t,s,r,i,o,a]=n;return[Hs(e,r,s,t,i,o,a),we.utcInstance]}function ql(n){const[,e,t,s,r,i,o,a]=n;return[Hs(e,a,t,s,r,i,o),we.utcInstance]}const Bl=Ct(Rl,Bs),Hl=Ct(Nl,Bs),Gl=Ct(xl,Bs),Yl=Ct(ao),co=Ft(Fl,Mt,on,an),Jl=Ft(Dl,Mt,on,an),Ql=Ft(Il,Mt,on,an),Kl=Ft(Mt,on,an);function Xl(n){return $t(n,[Bl,co],[Hl,Jl],[Gl,Ql],[Yl,Kl])}function ec(n){return $t(Wl(n),[Vl,Ul])}function tc(n){return $t(n,[jl,Vr],[Zl,Vr],[zl,ql])}function nc(n){return $t(n,[Ml,Pl])}const sc=Ft(Mt);function rc(n){return $t(n,[$l,sc])}const ic=Ct(Al,Cl),oc=Ct(lo),ac=Ft(Mt,on,an);function lc(n){return $t(n,[ic,co],[oc,ac])}const Ur="Invalid Duration",uo={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}},cc={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},...uo},Re=146097/400,wt=146097/4800,uc={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:wt/7,days:wt,hours:wt*24,minutes:wt*24*60,seconds:wt*24*60*60,milliseconds:wt*24*60*60*1e3},...uo},ut=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],dc=ut.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 ee(s)}function fo(n,e){let t=e.milliseconds??0;for(const s of dc.slice(1))e[s]&&(t+=e[s]*n[s].milliseconds);return t}function Wr(n,e){const t=fo(n,e)<0?-1:1;ut.reduceRight((s,r)=>{if(H(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),ut.reduce((s,r)=>{if(H(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*n[s][r]}return r},null)}function jr(n){const e={};for(const[t,s]of Object.entries(n))s!==0&&(e[t]=s);return e}class ee{constructor(e){const t=e.conversionAccuracy==="longterm"||!1;let s=t?uc:cc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||se.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return ee.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new ye(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ee({values:$n(e,ee.normalizeUnit),loc:se.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(nt(e))return ee.fromMillis(e);if(ee.isDuration(e))return e;if(typeof e=="object")return ee.fromObject(e);throw new ye(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=nc(e);return s?ee.fromObject(s,t):ee.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=rc(e);return s?ee.fromObject(s,t):ee.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new ye("need to specify a reason the Duration is invalid");const s=e instanceof $e?e:new $e(e,t);if(ce.throwOnInvalid)throw new Pa(s);return new ee({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 _i(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?ge.create(this.loc,s).formatDurationFromString(this,e):Ur}toHuman(e={}){if(!this.isValid)return Ur;const t=e.showZeros!==!1,s=ut.map(r=>{const i=this.values[r];return H(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+=zs(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},L.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?fo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=ee.fromDurationLike(e),s={};for(const r of ut)(At(t.values,r)||At(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=ee.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]=Ji(e(this.values[s],s));return Ze(this,{values:t},!0)}get(e){return this[ee.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...$n(e,ee.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 Wr(this.matrix,e),Ze(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=jr(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=>ee.normalizeUnit(o));const t={},s={},r=this.toObject();let i;for(const o of ut)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;nt(r[o])&&(a+=r[o]);const l=Math.trunc(a);t[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else nt(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 Wr(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=jr(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 ut)if(!t(this.values[s],e.values[s]))return!1;return!0}}const _t="Invalid Interval";function fc(n,e){return!n||!n.isValid?le.invalid("missing or invalid start"):!e||!e.isValid?le.invalid("missing or invalid end"):e<n?le.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 le{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 ye("need to specify a reason the Interval is invalid");const s=e instanceof $e?e:new $e(e,t);if(ce.throwOnInvalid)throw new Ma(s);return new le({invalid:s})}static fromDateTimes(e,t){const s=jt(e),r=jt(t),i=fc(s,r);return i??new le({start:s,end:r})}static after(e,t){const s=ee.fromDurationLike(t),r=jt(e);return le.fromDateTimes(r,r.plus(s))}static before(e,t){const s=ee.fromDurationLike(t),r=jt(e);return le.fromDateTimes(r.minus(s),r)}static fromISO(e,t){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=L.fromISO(s,t),o=i.isValid}catch{o=!1}let a,l;try{a=L.fromISO(r,t),l=a.isValid}catch{l=!1}if(o&&l)return le.fromDateTimes(i,a);if(o){const c=ee.fromISO(r,t);if(c.isValid)return le.after(i,c)}else if(l){const c=ee.fromISO(s,t);if(c.isValid)return le.before(a,c)}}return le.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?le.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];const t=e.map(jt).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(le.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const t=ee.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(le.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:le.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 le.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(le.fromDateTimes(t,l.time)),t=null);return le.merge(r)}difference(...e){return le.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:_t}[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=An,t={}){return this.isValid?ge.create(this.s.loc.clone(t),e).formatInterval(this):_t}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:_t}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:_t}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:_t}toFormat(e,{separator:t=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:_t}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):ee.invalid(this.invalidReason)}mapEndpoints(e){return le.fromDateTimes(e(this.s),e(this.e))}}class un{static hasDST(e=ce.defaultZone){const t=L.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 Xe(e,ce.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||se.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||se.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||se.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||se.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||se.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||se.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||se.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return se.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return se.create(t,null,"gregory").eras(e)}static features(){return{relative:Hi(),localeWeek:Gi()}}}function Zr(n,e){const t=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(n);return Math.floor(ee.fromMillis(s).as("days"))}function hc(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 d=Zr(l,c);return(d-d%7)/7}],["days",Zr]],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 mc(n,e,t,s){let[r,i,o,a]=hc(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 d=ee.fromObject(i,s);return c.length>0?ee.fromMillis(l,s).shiftTo(...c).plus(d):d}const pc="missing Intl.DateTimeFormat.formatToParts support";function ne(n,e=t=>t){return{regex:n,deser:([t])=>e(il(t))}}const yc=" ",ho=`[ ${yc}]`,mo=new RegExp(ho,"g");function gc(n){return n.replace(/\./g,"\\.?").replace(mo,ho)}function zr(n){return n.replace(/\./g,"").replace(mo," ").toLowerCase()}function Fe(n,e){return n===null?null:{regex:RegExp(n.map(gc).join("|")),deser:([t])=>n.findIndex(s=>zr(t)===zr(s))+e}}function qr(n,e){return{regex:n,deser:([,t,s])=>zn(t,s),groups:e}}function dn(n){return{regex:n,deser:([e])=>e}}function wc(n){return n.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _c(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}"),d=Ce(e,"{1,9}"),h=Ce(e,"{2,4}"),u=Ce(e,"{4,6}"),f=p=>({regex:RegExp(wc(p.val)),deser:([k])=>k,literal:!0}),E=(p=>{if(n.literal)return f(p);switch(p.val){case"G":return Fe(e.eras("short"),0);case"GG":return Fe(e.eras("long"),0);case"y":return ne(c);case"yy":return ne(h,Cs);case"yyyy":return ne(i);case"yyyyy":return ne(u);case"yyyyyy":return ne(o);case"M":return ne(a);case"MM":return ne(s);case"MMM":return Fe(e.months("short",!0),1);case"MMMM":return Fe(e.months("long",!0),1);case"L":return ne(a);case"LL":return ne(s);case"LLL":return Fe(e.months("short",!1),1);case"LLLL":return Fe(e.months("long",!1),1);case"d":return ne(a);case"dd":return ne(s);case"o":return ne(l);case"ooo":return ne(r);case"HH":return ne(s);case"H":return ne(a);case"hh":return ne(s);case"h":return ne(a);case"mm":return ne(s);case"m":return ne(a);case"q":return ne(a);case"qq":return ne(s);case"s":return ne(a);case"ss":return ne(s);case"S":return ne(l);case"SSS":return ne(r);case"u":return dn(d);case"uu":return dn(a);case"uuu":return ne(t);case"a":return Fe(e.meridiems(),0);case"kkkk":return ne(i);case"kk":return ne(h,Cs);case"W":return ne(a);case"WW":return ne(s);case"E":case"c":return ne(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 qr(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return qr(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return dn(/[a-z_+-/]{1,256}?/i);case" ":return dn(/[^\S\n\r]/);default:return f(p)}})(n)||{invalidReason:pc};return E.token=n,E}const Ec={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 vc(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=Ec[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Oc(n){return[`^${n.map(t=>t.regex).reduce((t,s)=>`${t}(${s.source})`,"")}$`,n]}function kc(n,e,t){const s=n.match(e);if(s){const r={};let i=1;for(const o in t)if(At(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 bc(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 H(n.z)||(t=He.create(n.z)),H(n.Z)||(t||(t=new we(n.Z)),s=n.Z),H(n.q)||(n.M=(n.q-1)*3+1),H(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),H(n.u)||(n.S=Zs(n.u)),[Object.keys(n).reduce((i,o)=>{const a=e(o);return a&&(i[a]=n[o]),i},{}),t,s]}let is=null;function Sc(){return is||(is=L.fromMillis(1555555555555)),is}function Tc(n,e){if(n.literal)return n;const t=ge.macroTokenToFormatOpts(n.val),s=wo(t,e);return s==null||s.includes(void 0)?n:s}function po(n,e){return Array.prototype.concat(...n.map(t=>Tc(t,e)))}class yo{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=po(ge.parseFormat(t),e),this.units=this.tokens.map(s=>_c(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Oc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[t,s]=kc(e,this.regex,this.handlers),[r,i,o]=s?bc(s):[null,null,void 0];if(At(s,"a")&&At(s,"H"))throw new Ot("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 go(n,e,t){return new yo(n,t).explainFromTokens(e)}function Rc(n,e,t){const{result:s,zone:r,specificOffset:i,invalidReason:o}=go(n,e,t);return[s,r,i,o]}function wo(n,e){if(!n)return null;const s=ge.create(e,n).dtFormatter(Sc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>vc(o,n,i))}const os="Invalid DateTime",Br=864e13;function Bt(n){return new $e("unsupported zone",`the zone "${n.name}" is not supported`)}function as(n){return n.weekData===null&&(n.weekData=Cn(n.c)),n.weekData}function ls(n){return n.localWeekData===null&&(n.localWeekData=Cn(n.c,n.loc.getMinDaysInFirstWeek(),n.loc.getStartOfWeek())),n.localWeekData}function at(n,e){const t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new L({...t,...e,old:t})}function _o(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 fn(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 yn(n,e,t){return _o(Zn(n),e,t)}function Hr(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,Fn(s,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ee.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=Zn(i);let[l,c]=_o(a,t,n.zone);return o!==0&&(l+=o,c=n.zone.offset(l)),{ts:l,o:c}}function Et(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=L.fromObject(n,{...t,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return L.invalid(new $e("unparsable",`the input "${r}" can't be parsed as ${s}`))}function hn(n,e,t=!0){return n.isValid?ge.create(se.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(n,e):null}function cs(n,e,t){const s=n.c.year>9999||n.c.year<0;let r="";if(s&&n.c.year>=0&&(r+="+"),r+=fe(n.c.year,s?6:4),t==="year")return r;if(e){if(r+="-",r+=fe(n.c.month),t==="month")return r;r+="-"}else if(r+=fe(n.c.month),t==="month")return r;return r+=fe(n.c.day),r}function Gr(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+=fe(n.c.hour),o==="hour")break;if(e){if(l+=":",l+=fe(n.c.minute),o==="minute")break;a&&(l+=":",l+=fe(n.c.second))}else{if(l+=fe(n.c.minute),o==="minute")break;a&&(l+=fe(n.c.second))}if(o==="second")break;a&&(!s||n.c.millisecond!==0)&&(l+=".",l+=fe(n.c.millisecond,3))}return r&&(n.isOffsetFixed&&n.offset===0&&!i?l+="Z":n.o<0?(l+="-",l+=fe(Math.trunc(-n.o/60)),l+=":",l+=fe(Math.trunc(-n.o%60))):(l+="+",l+=fe(Math.trunc(n.o/60)),l+=":",l+=fe(Math.trunc(n.o%60)))),i&&(l+="["+n.zone.ianaName+"]"),l}const Eo={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Nc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},xc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},gn=["year","month","day","hour","minute","second","millisecond"],Dc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Ic=["year","ordinal","hour","minute","second","millisecond"];function wn(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 _i(n);return e}function Yr(n){switch(n.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return wn(n)}}function Ac(n){if(Ht===void 0&&(Ht=ce.now()),n.type!=="iana")return n.offset(Ht);const e=n.name;let t=Fs.get(e);return t===void 0&&(t=n.offset(Ht),Fs.set(e,t)),t}function Jr(n,e){const t=Xe(e.zone,ce.defaultZone);if(!t.isValid)return L.invalid(Bt(t));const s=se.fromObject(e);let r,i;if(H(n.year))r=ce.now();else{for(const l of gn)H(n[l])&&(n[l]=Eo[l]);const o=qi(n)||Bi(n);if(o)return L.invalid(o);const a=Ac(t);[r,i]=yn(n,a,t)}return new L({ts:r,zone:t,loc:s,o:i})}function Qr(n,e,t){const s=H(t.round)?!0:t.round,r=H(t.rounding)?"trunc":t.rounding,i=(a,l)=>(a=zs(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 Kr(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 Ht;const Fs=new Map;class L{constructor(e){const t=e.zone||ce.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new $e("invalid input"):null)||(t.isValid?null:Bt(t));this.ts=H(e.ts)?ce.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=nt(e.o)&&!e.old?e.o:t.offset(this.ts);r=fn(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||se.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new L({})}static local(){const[e,t]=Kr(arguments),[s,r,i,o,a,l,c]=t;return Jr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,t]=Kr(arguments),[s,r,i,o,a,l,c]=t;return e.zone=we.utcInstance,Jr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){const s=ul(e)?e.valueOf():NaN;if(Number.isNaN(s))return L.invalid("invalid input");const r=Xe(t.zone,ce.defaultZone);return r.isValid?new L({ts:s,zone:r,loc:se.fromObject(t)}):L.invalid(Bt(r))}static fromMillis(e,t={}){if(nt(e))return e<-Br||e>Br?L.invalid("Timestamp out of range"):new L({ts:e,zone:Xe(t.zone,ce.defaultZone),loc:se.fromObject(t)});throw new ye(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(nt(e))return new L({ts:e*1e3,zone:Xe(t.zone,ce.defaultZone),loc:se.fromObject(t)});throw new ye("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=Xe(t.zone,ce.defaultZone);if(!s.isValid)return L.invalid(Bt(s));const r=se.fromObject(t),i=$n(e,Yr),{minDaysInFirstWeek:o,startOfWeek:a}=$r(i,r),l=ce.now(),c=H(t.specificOffset)?s.offset(l):t.specificOffset,d=!H(i.ordinal),h=!H(i.year),u=!H(i.month)||!H(i.day),f=h||u,w=i.weekYear||i.weekNumber;if((f||d)&&w)throw new Ot("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new Ot("Can't mix ordinal dates with month/day");const E=w||i.weekday&&!f;let p,k,b=fn(l,c);E?(p=Dc,k=Nc,b=Cn(b,o,a)):d?(p=Ic,k=xc,b=rs(b)):(p=gn,k=Eo);let R=!1;for(const m of p){const S=i[m];H(S)?R?i[m]=k[m]:i[m]=b[m]:R=!0}const g=E?al(i,o,a):d?ll(i):qi(i),T=g||Bi(i);if(T)return L.invalid(T);const _=E?Cr(i,o,a):d?Fr(i):i,[P,x]=yn(_,c,s),M=new L({ts:P,zone:s,o:x,loc:r});return i.weekday&&f&&e.weekday!==M.weekday?L.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${M.toISO()}`):M.isValid?M:L.invalid(M.invalid)}static fromISO(e,t={}){const[s,r]=Xl(e);return Et(s,r,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,r]=ec(e);return Et(s,r,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,r]=tc(e);return Et(s,r,t,"HTTP",t)}static fromFormat(e,t,s={}){if(H(e)||H(t))throw new ye("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=se.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,d]=Rc(o,e,t);return d?L.invalid(d):Et(a,l,s,`format ${t}`,e,c)}static fromString(e,t,s={}){return L.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,r]=lc(e);return Et(s,r,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new ye("need to specify a reason the DateTime is invalid");const s=e instanceof $e?e:new $e(e,t);if(ce.throwOnInvalid)throw new $a(s);return new L({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=wo(e,se.fromObject(t));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,t={}){return po(ge.parseFormat(e),se.fromObject(t)).map(r=>r.val).join("")}static resetCache(){Ht=void 0,Fs.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?as(this).weekYear:NaN}get weekNumber(){return this.isValid?as(this).weekNumber:NaN}get weekday(){return this.isValid?as(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ls(this).weekday:NaN}get localWeekNumber(){return this.isValid?ls(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ls(this).weekYear:NaN}get ordinal(){return this.isValid?rs(this.c).ordinal:NaN}get monthShort(){return this.isValid?un.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?un.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?un.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?un.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=Zn(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,d=fn(l,o),h=fn(c,a);return d.hour===h.hour&&d.minute===h.minute&&d.second===h.second&&d.millisecond===h.millisecond?[at(this,{ts:l}),at(this,{ts:c})]:[this]}get isInLeapYear(){return rn(this.year)}get daysInMonth(){return Fn(this.year,this.month)}get daysInYear(){return this.isValid?St(this.year):NaN}get weeksInWeekYear(){return this.isValid?en(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?en(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:t,numberingSystem:s,calendar:r}=ge.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(we.instance(e),t)}toLocal(){return this.setZone(ce.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=Xe(e,ce.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]=yn(o,i,e)}return at(this,{ts:r,zone:e})}else return L.invalid(Bt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return at(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=$n(e,Yr),{minDaysInFirstWeek:s,startOfWeek:r}=$r(t,this.loc),i=!H(t.weekYear)||!H(t.weekNumber)||!H(t.weekday),o=!H(t.ordinal),a=!H(t.year),l=!H(t.month)||!H(t.day),c=a||l,d=t.weekYear||t.weekNumber;if((c||o)&&d)throw new Ot("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new Ot("Can't mix ordinal dates with month/day");let h;i?h=Cr({...Cn(this.c,s,r),...t},s,r):H(t.ordinal)?(h={...this.toObject(),...t},H(t.day)&&(h.day=Math.min(Fn(h.year,h.month),h.day))):h=Fr({...rs(this.c),...t});const[u,f]=yn(h,this.o,this.zone);return at(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const t=ee.fromDurationLike(e);return at(this,Hr(this,t))}minus(e){if(!this.isValid)return this;const t=ee.fromDurationLike(e).negate();return at(this,Hr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},r=ee.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?ge.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):os}toLocaleString(e=An,t={}){return this.isValid?ge.create(this.loc.clone(t),e).formatDateTime(this):os}toLocaleParts(e={}){return this.isValid?ge.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=wn(o);const a=e==="extended";let l=cs(this,a,o);return gn.indexOf(o)>=3&&(l+="T"),l+=Gr(this,a,t,s,r,i,o),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?cs(this,e==="extended",wn(t)):null}toISOWeekDate(){return hn(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=wn(a),(r&&gn.indexOf(a)>=3?"T":"")+Gr(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return hn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return hn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?cs(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")),hn(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():os}[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 ee.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=dl(t).map(ee.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=mc(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",t={}){return this.diff(L.now(),e,t)}until(e){return this.isValid?le.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||L.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),Qr(t,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?Qr(e.base||L.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(L.isDateTime))throw new ye("min requires all arguments be DateTimes");return Mr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(L.isDateTime))throw new ye("max requires all arguments be DateTimes");return Mr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=se.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return go(o,e,t)}static fromStringExplain(e,t,s={}){return L.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:r=null}=t,i=se.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new yo(i,e)}static fromFormatParser(e,t,s={}){if(H(e)||H(t))throw new ye("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=se.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new ye(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=t.explainFromTokens(e);return d?L.invalid(d):Et(a,l,s,`format ${t.format}`,e,c)}static get DATE_SHORT(){return An}static get DATE_MED(){return Ei}static get DATE_MED_WITH_WEEKDAY(){return La}static get DATE_FULL(){return vi}static get DATE_HUGE(){return Oi}static get TIME_SIMPLE(){return ki}static get TIME_WITH_SECONDS(){return bi}static get TIME_WITH_SHORT_OFFSET(){return Si}static get TIME_WITH_LONG_OFFSET(){return Ti}static get TIME_24_SIMPLE(){return Ri}static get TIME_24_WITH_SECONDS(){return Ni}static get TIME_24_WITH_SHORT_OFFSET(){return xi}static get TIME_24_WITH_LONG_OFFSET(){return Di}static get DATETIME_SHORT(){return Ii}static get DATETIME_SHORT_WITH_SECONDS(){return Ai}static get DATETIME_MED(){return Ci}static get DATETIME_MED_WITH_SECONDS(){return Fi}static get DATETIME_MED_WITH_WEEKDAY(){return Va}static get DATETIME_FULL(){return $i}static get DATETIME_FULL_WITH_SECONDS(){return Mi}static get DATETIME_HUGE(){return Pi}static get DATETIME_HUGE_WITH_SECONDS(){return Li}}function jt(n){if(L.isDateTime(n))return n;if(n&&n.valueOf&&nt(n.valueOf()))return L.fromJSDate(n);if(n&&typeof n=="object")return L.fromObject(n);throw new ye(`Unknown datetime argument: ${n}, of type ${typeof n}`)}const Cc=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return nn(pe());n.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?t[r]=vo(i)?.nullable():t[r]=pe()})}return Ue({Collection_Path:yt(ke()),...t})},Fc=(n,e,t,s)=>{let r=Ue({}).catchall(Cc(n,e)),i;if(!s&&t){const o=Ie(n,t);i=Zt(o.admin?.skipFormRequiredValidation)}return(!n.required||i)&&(r=r.optional()),r},$c=()=>pe().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"}),vo=(n,e,t)=>{let s;const r=`${Zt(n.description)}
2
2
 
3
- `||"";let i,o,a;if(!t&&e){const l=Ie(n,e);i=l.admin?.condition?.form!==void 0&&!zt(l.admin.condition.form),o=zt(l.admin?.skipFormRequiredValidation),a=zt(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([In(n.values,{message:`Must be one of the following values: ${n.values.join(", ")}`}),ts()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=Qt(),r&&(s=s.describe(r.trim()));break;case"Number":n.autoIncrement?s=ve([ts(),ut().int()],{message:"Must be a valid number"}):(s=ut(),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(", ")}`}),ts()])),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:ut(),nanoseconds:ut()}),n.min&&n.max?s=s.describe(`${r}Must be between ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)} and ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`):n.min?s=s.describe(`${r}Must be greater than or equal to ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)}`):n.max?s=s.describe(`${r}Must be less than or equal to ${L.fromMillis(n.max).toLocaleString(L.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 ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)}`})),n.max&&(s=s.refine(l=>l.toMillis()<=n.max,{message:`Must be less than or equal to ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`})));break;case"Array":s=gt(pe()),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(d=>{n.values&&!n.values.includes(d)&&(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(pe()).describe(`${r}Must be an object. Must contain at least one object property.`):s=sn(pe()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=Ue({}).catchall(pe()).describe(`${r}Must be an object`);break;case"Computed":s=pe()}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(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=vo(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}`]=Qt().optional(),a[`operations-${c.labels.collection}`]=gt(ve([Oe("Read"),Oe("Create"),Oe("Update"),Oe("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=Qt().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=Qt().optional()}),c.access.entityRestrictions?.restrictions?.forEach(d=>{if(d.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=Ue({}).catchall(pe()).optional()),d.type==="Parent"||d.type==="Parent_Property"){const h=W(c.fields,d.collectionField);a[`accessible-${c.labels.collection}-${h.collection}`]=Ue({}).catchall(pe()).optional()}})}));const l=Ue(a);return n.allowSchemalessFields?l.passthrough():l.strict()},ei=async(n,e)=>{if(n){const t=await ie(n,e);if(!t.valid)throw new Error(`VALIDATION_ERROR: ${t.message}`)}},nn=async(n,e,t,s,r,i)=>{await ei(s.custom?.preValidate,r);for(const a of s.fields)await ei(a.custom?.preValidate,r);return wi(n,t,i).parse(e),e},Ys=(n,e,t,s,r,i,o,a,l,c,d,h,u,f,w,E,p,k,b,R,g)=>{const{fields:T}=o;T.filter(m=>"unique"in m&&m.unique).forEach(m=>{n!=="delete"&&(typeof r[m.name]=="string"||typeof r[m.name]=="number")&&(e.set(f(m,r[m.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:t}),g&&g.size++)}),T.forEach(m=>{if(ot(m,o,i)){const S=cn(m,o,i),v={};r[m.name]!==void 0&&(v[m.name]=r[m.name],X(m)&&(v[`${m.name}_Array`]=r[`${m.name}_Array`])),S.forEach(y=>{r[y.name]!==void 0&&(X(y)?v[`${y.name}_Array`]=r[`${y.name}_Array`]:v[y.name]=r[y.name])}),Object.keys(v).length>0&&(n==="create"&&(v.Collection_Path=t,v.Collection_Path_String=t.join("/"),e.set(u(m),v)),n==="update"&&e.update(u(m),v),n==="delete"&&e.delete(u(m)),g&&g.size++)}});const _=l[o.labels.collection];for(const m of _){const S=oa(m,o),v={...r};S.forEach(y=>{delete v[y.name],delete v[`${y.name}_Array`],delete v[`${y.name}_Single`],delete v[`${y.name}_Lowercase`]}),Object.keys(v).length>0&&(n==="create"&&(v.Collection_Path||=t,v.Collection_Path_String=t.join("/"),e.set(w(m.key),v)),n==="update"&&e.update(w(m.key),v),n==="delete"&&e.delete(w(m.key)),g&&g.size++)}const P=(m,S)=>{let v=1;ot(S,m,i)&&v++,m.fields.forEach(I=>{ot(I,m,i)&&JSON.parse(Kn(cn(I,m,i))).includes(S.name)&&v++});const y=l[m.labels.collection];for(const I of y)I.fields.some(O=>O.name===S.name)&&X(S)&&v++;return v},x=(m,S,v,y,I)=>{const O={};O[`${v.name}.${s}`]=h(),O[`${v.name}_Array`]=d(s),O[`${v.name}_Single`]=h(),e.update(E(I,y),O),ot(v,S,i)&&e.update(p(m,v.name,y),{[`${v.name}.${s}`]:h(),[`${v.name}_Array`]:d(s)}),S.fields.forEach(A=>{ot(A,S,i)&&JSON.parse(Kn(cn(A,S,i))).includes(v.name)&&e.update(p(m,A.name,y),{[`${v.name}_Array`]:d(s)})});const V=l[S.labels.collection];for(const A of V)A.fields.some(C=>C.name===v.name)&&X(v)&&e.update(k(m,A.key,y),O)};if(n==="delete")return;const M=T.filter(m=>X(m)&&m.twoWay);if(!a?.noTwoWay){for(const m of M){if(!g)throw new Error("VALIDATION_ERROR: batchSize is required");const S=i.collections[m.collection],v=W(S.fields,m.twoWay),y=ct(S,S.fields),I=Array.from(y).map(O=>O.name);if(!v)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(X(v)){if(r[`${m.name}_Array`])for(const[O,V]of Object.entries(r[m.name])){if(n==="update"&&b&&b[`${m.name}_Array`]?.includes(O))continue;const A={...b,...r};et(A);const C={};v.includeFields&&v.includeFields.forEach(z=>{if(A[z]!==void 0){C[z]=A[z];const q=W(o.fields,z);yt(o,[q]).size===1&&(C[`${z}_Lowercase`]=A[`${z}_Lowercase`])}});const j={[`${m.twoWay}.${s}`]:{Collection_Path:t,...C},[`${m.twoWay}_Array`]:c(s)};I.includes(v.name)&&(j[`${m.twoWay}_Single`]={Collection_Path:t,...C});const Q=On(r);e.update(E(V.Collection_Path,O),{...j,...Q}),g.size++,ot(v,S,i)&&(e.update(p(m,v.name,O),{[`${v.name}.${s}`]:{Collection_Path:t,...C},[`${v.name}_Array`]:c(s)}),g.size++),S.fields.forEach(z=>{if(ot(z,S,i)){const q=JSON.parse(Kn(cn(z,S,i))),re={};q.includes(v.name)&&(re[`${m.twoWay}_Array`]=c(s)),Object.keys(Q).forEach(Ee=>{q.includes(Ee)&&(re[Ee]=Q[Ee])}),Object.keys(re).length>0&&(e.update(p(m,z.name,O),re),g.size++)}});const N=l[S.labels.collection];for(const z of N)if(z.fields.some(q=>q.name===v.name)){const q={...j};Object.keys(Q).forEach(re=>{z.fields.some(Ee=>Ee.name===re)&&(q[re]=Q[re])}),Object.keys(q).length>0&&(e.update(k(m,z.key,O),q),g.size++)}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${v.type}`)}if(g&&g.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 m of M){if(!g)throw new Error("VALIDATION_ERROR: batchSize is required");const S=i.collections[m.collection],v=W(S.fields,m.twoWay);if(!v)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(X(v)){if(n==="update"&&b&&!(r[m.name]&&Ne(r[m.name]))&&r[`${m.name}_Array`]&&b[`${m.name}_Array`]?.length>0)for(const[y,I]of Object.entries(b[m.name]))!r[`${m.name}_Array`].includes(y)&&!R?.get(m.name)?.includes(y)&&(g.size+=P(S,v),g.size<=500&&x(m,S,v,y,I.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${v.type}`)}for(const m of M){if(!g)throw new Error("VALIDATION_ERROR: batchSize is required");const S=i.collections[m.collection],v=W(S.fields,m.twoWay);if(!v)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(X(v)){if(n==="update"&&b&&r[m.name]&&Ne(r[m.name])&&b[`${m.name}_Array`]?.length>0)for(const[y,I]of Object.entries(b[m.name]))R?.get(m.name)?.includes(y)||(g.size+=P(S,v),g.size<=500&&x(m,S,v,y,I.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${v.type}`)}}},tt=(n,e)=>{const{fields:t}=e,s=me(n);return Object.keys(n).filter(r=>{W(t,r)?.access&&delete s[r]}),s},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]))},Js=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)},ti=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}},Pn=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},ds=n=>n?Array.isArray(n)?n.map(s=>Pn(s)).filter(s=>s.length>0):Pn(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},ni=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&&!Zt(l.admin.condition.form),o=Zt(l.admin?.skipFormRequiredValidation),a=Zt(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([Dn(n.values,{message:`Must be one of the following values: ${n.values.join(", ")}`}),es()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=Jt(),r&&(s=s.describe(r.trim()));break;case"Number":n.autoIncrement?s=ve([es(),ct().int()],{message:"Must be a valid number"}):(s=ct(),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(", ")}`}),es()])),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:ct(),nanoseconds:ct()}),n.min&&n.max?s=s.describe(`${r}Must be between ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)} and ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`):n.min?s=s.describe(`${r}Must be greater than or equal to ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)}`):n.max?s=s.describe(`${r}Must be less than or equal to ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=$c(),n.min&&(s=s.refine(l=>l.toMillis()>=n.min,{message:`Must be greater than or equal to ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)}`})),n.max&&(s=s.refine(l=>l.toMillis()<=n.max,{message:`Must be less than or equal to ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`})));break;case"Array":s=yt(pe()),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(d=>{n.values&&!n.values.includes(d)&&(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(pe()).describe(`${r}Must be an object. Must contain at least one object property.`):s=nn(pe()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=Ue({}).catchall(pe()).describe(`${r}Must be an object`);break;case"Computed":s=pe()}return(!n.required||i||o)&&(s=s.optional()),s},Mc=(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)||(K(c)?(a[c.name]=Fc(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(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=vo(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}`]=Jt().optional(),a[`operations-${c.labels.collection}`]=yt(ve([Oe("Read"),Oe("Create"),Oe("Update"),Oe("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=Jt().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=Jt().optional()}),c.access.entityRestrictions?.restrictions?.forEach(d=>{if(d.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=Ue({}).catchall(pe()).optional()),d.type==="Parent"||d.type==="Parent_Property"){const h=W(c.fields,d.collectionField);a[`accessible-${c.labels.collection}-${h.collection}`]=Ue({}).catchall(pe()).optional()}})}));const l=Ue(a);return n.allowSchemalessFields?l.passthrough():l.strict()},Xr=async(n,e)=>{if(n){const t=await ie(n,e);if(!t.valid)throw new Error(`VALIDATION_ERROR: ${t.message}`)}},tn=async(n,e,t,s,r,i)=>{await Xr(s.custom?.preValidate,r);for(const a of s.fields)await Xr(a.custom?.preValidate,r);return wi(n,t,i).parse(e),e},Gs=(n,e,t,s,r,i,o,a,l,c,d,h,u,f,w,E,p,k,b,R,g)=>{const{fields:T}=o;T.filter(m=>"unique"in m&&m.unique).forEach(m=>{n!=="delete"&&(typeof r[m.name]=="string"||typeof r[m.name]=="number")&&(e.set(f(m,r[m.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:t}),g&&g.size++)}),T.forEach(m=>{if(it(m,o,i)){const S=ln(m,o,i),v={};r[m.name]!==void 0&&(v[m.name]=r[m.name],K(m)&&(v[`${m.name}_Array`]=r[`${m.name}_Array`])),S.forEach(y=>{r[y.name]!==void 0&&(K(y)?v[`${y.name}_Array`]=r[`${y.name}_Array`]:v[y.name]=r[y.name])}),Object.keys(v).length>0&&(n==="create"&&(v.Collection_Path=t,v.Collection_Path_String=t.join("/"),e.set(u(m),v)),n==="update"&&e.update(u(m),v),n==="delete"&&e.delete(u(m)),g&&g.size++)}});const _=l[o.labels.collection];for(const m of _){const S=ia(m,o),v={...r};S.forEach(y=>{delete v[y.name],delete v[`${y.name}_Array`],delete v[`${y.name}_Single`],delete v[`${y.name}_Lowercase`]}),Object.keys(v).length>0&&(n==="create"&&(v.Collection_Path||=t,v.Collection_Path_String=t.join("/"),e.set(w(m.key),v)),n==="update"&&e.update(w(m.key),v),n==="delete"&&e.delete(w(m.key)),g&&g.size++)}const P=(m,S)=>{let v=1;it(S,m,i)&&v++,m.fields.forEach(I=>{it(I,m,i)&&JSON.parse(Qn(ln(I,m,i))).includes(S.name)&&v++});const y=l[m.labels.collection];for(const I of y)I.fields.some(O=>O.name===S.name)&&K(S)&&v++;return v},x=(m,S,v,y,I)=>{const O={};O[`${v.name}.${s}`]=h(),O[`${v.name}_Array`]=d(s),O[`${v.name}_Single`]=h(),e.update(E(I,y),O),it(v,S,i)&&e.update(p(m,v.name,y),{[`${v.name}.${s}`]:h(),[`${v.name}_Array`]:d(s)}),S.fields.forEach(A=>{it(A,S,i)&&JSON.parse(Qn(ln(A,S,i))).includes(v.name)&&e.update(p(m,A.name,y),{[`${v.name}_Array`]:d(s)})});const V=l[S.labels.collection];for(const A of V)A.fields.some(C=>C.name===v.name)&&K(v)&&e.update(k(m,A.key,y),O)};if(n==="delete")return;const M=T.filter(m=>K(m)&&m.twoWay);if(!a?.noTwoWay){for(const m of M){if(!g)throw new Error("VALIDATION_ERROR: batchSize is required");const S=i.collections[m.collection],v=W(S.fields,m.twoWay),y=lt(S,S.fields),I=Array.from(y).map(O=>O.name);if(!v)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(K(v)){if(r[`${m.name}_Array`])for(const[O,V]of Object.entries(r[m.name])){if(n==="update"&&b&&b[`${m.name}_Array`]?.includes(O))continue;const A={...b,...r};et(A);const C={};v.includeFields&&v.includeFields.forEach(z=>{if(A[z]!==void 0){C[z]=A[z];const q=W(o.fields,z);pt(o,[q]).size===1&&(C[`${z}_Lowercase`]=A[`${z}_Lowercase`])}});const j={[`${m.twoWay}.${s}`]:{Collection_Path:t,...C},[`${m.twoWay}_Array`]:c(s)};I.includes(v.name)&&(j[`${m.twoWay}_Single`]={Collection_Path:t,...C});const Q=vn(r);e.update(E(V.Collection_Path,O),{...j,...Q}),g.size++,it(v,S,i)&&(e.update(p(m,v.name,O),{[`${v.name}.${s}`]:{Collection_Path:t,...C},[`${v.name}_Array`]:c(s)}),g.size++),S.fields.forEach(z=>{if(it(z,S,i)){const q=JSON.parse(Qn(ln(z,S,i))),re={};q.includes(v.name)&&(re[`${m.twoWay}_Array`]=c(s)),Object.keys(Q).forEach(Ee=>{q.includes(Ee)&&(re[Ee]=Q[Ee])}),Object.keys(re).length>0&&(e.update(p(m,z.name,O),re),g.size++)}});const N=l[S.labels.collection];for(const z of N)if(z.fields.some(q=>q.name===v.name)){const q={...j};Object.keys(Q).forEach(re=>{z.fields.some(Ee=>Ee.name===re)&&(q[re]=Q[re])}),Object.keys(q).length>0&&(e.update(k(m,z.key,O),q),g.size++)}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${v.type}`)}if(g&&g.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 m of M){if(!g)throw new Error("VALIDATION_ERROR: batchSize is required");const S=i.collections[m.collection],v=W(S.fields,m.twoWay);if(!v)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(K(v)){if(n==="update"&&b&&!(r[m.name]&&Ne(r[m.name]))&&r[`${m.name}_Array`]&&b[`${m.name}_Array`]?.length>0)for(const[y,I]of Object.entries(b[m.name]))!r[`${m.name}_Array`].includes(y)&&!R?.get(m.name)?.includes(y)&&(g.size+=P(S,v),g.size<=500&&x(m,S,v,y,I.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${v.type}`)}for(const m of M){if(!g)throw new Error("VALIDATION_ERROR: batchSize is required");const S=i.collections[m.collection],v=W(S.fields,m.twoWay);if(!v)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(K(v)){if(n==="update"&&b&&r[m.name]&&Ne(r[m.name])&&b[`${m.name}_Array`]?.length>0)for(const[y,I]of Object.entries(b[m.name]))R?.get(m.name)?.includes(y)||(g.size+=P(S,v),g.size<=500&&x(m,S,v,y,I.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${v.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]))},Ys=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)},ei=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}},Mn=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},us=n=>n?Array.isArray(n)?n.map(s=>Mn(s)).filter(s=>s.length>0):Mn(n)||"":"",Pc=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},ti=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},Oo=async(n,e)=>{const t={};for(const s of e)t[s]=await import(`${n}/${s}.js`);return t};let fs,ko,bo,Yt,So,En,vn,hs=0;const bt={getMode(){return ko},getTimezone(){return bo},getGlobalConfigModule(){return me(Yt)},getCustomizationFile(n,e){if(!Object.keys(e.collections).includes(n))throw new Error("PERMISSION_DENIED");const t=ta([n],So,"node",bt);return me(t?.[n])},getVersionInfo(){return En},getMaintenanceInfo(){return vn}},Vc=async(n,e,t,s)=>{if(fs&&!s)return bt;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const r=process.env.STOKER_FB_WEB_APP_CONFIG,i=JSON.parse(r);ko=n;const a=(await import(e)).default;Yt=a("node",bt),!s&&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{fs=St.getApp()}catch{fs=St.initializeApp({credential:St.applicationDefault(),databaseURL:i.databaseURL,storageBucket:i.storageBucket,projectId:i.projectId})}const l=await je();return So=await Oo(t,Object.keys(l.collections)),bo=await ie(Yt.timezone),B.getFirestore().collection("system_deployment").doc("maintenance_mode").onSnapshot(c=>{c.exists?(vn=c.data(),ie(Yt.onMaintenanceUpdate,["node",vn.active?"on":"off"])):console.error("Maintenance status not found")},c=>{console.error(c.message)}),B.getFirestore().collection("system_deployment").doc("latest_deploy").onSnapshot(c=>{c.exists?(En=c.data(),hs++,hs>1&&ie(Yt.onVersionUpdate,["node",En,hs])):console.error("Version info not found")},c=>{console.error(c.message)}),await new Promise(c=>{const d=()=>{vn&&En?c(bt):setTimeout(d,100)};d()}),bt},{getMode:To,getTimezone:Ro,getGlobalConfigModule:Lt,getCustomizationFile:Ye,getVersionInfo:ru,getMaintenanceInfo:iu}=bt,je=async(n=!1)=>{const s=await ii.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,Ye(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},Uc=async()=>{const t=await ii.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(t.numChildren()<2))return Object.values(t.val())[0]},Te=(n,e)=>{let t=n;for(let s=0;s<e.length;s++)s%2===0?t=t.collection(e[s]):t=t.doc(e[s]);return t},No=(n,e,t,s)=>{const r=B.getFirestore(),i=n.at(-1);if(!i)throw new Error("EMPTY_PATH");const o=e.collections[i],{labels:a,fields:l,preloadCache:c}=o,d=Ye(i,e),h=Te(r,n);if(s)if(t){const u=s.collections?.[a.collection];if(!s.Role)throw new Error("PERMISSION_DENIED");const f=u&&Se("Read",u),w=ci(o,e,s),E=ai(o,s),p=Ms(o,s),k=li(o,e,s),b=(y=[])=>{const I=[],O=hi(s.Role,o,e);if(!O)throw new Error("PERMISSION_DENIED");if(f){let V=r.collection("system_fields").doc(a.collection).collection(`${a.collection}-${O.key}`).where("Collection_Path_String","==",n.join("/"));y.forEach(A=>{V=V.where(...A)}),I.push(V)}else if(w)for(const V of w){let A=r.collection("system_fields").doc(a.collection).collection(`${a.collection}-${V.field}`).where("Collection_Path_String","==",n.join("/"));y.forEach(C=>{A=A.where(...C)}),I.push(A)}return I},R=E.filter(y=>"operations"in y&&y.operations?y.operations.includes("Read"):!0);if(R.length===0&&p.length===0&&k.length===0)return b();let g=0;const T=y=>{y&&(g===0?g=y:g*=y)};if(R.length>0){for(const y of R)if(y.operations&&y.type==="Record_Property"){const I=y.roles.find(O=>O.role===s.Role);if(!I)throw new Error("PERMISSION_DENIED");T(I.values?.length)}}c?.roles.includes(s.Role)&&c.range&&T(c.range.fields.length);const _=d.admin?.statusField;_&&!c?.roles.includes(s.Role)&&T(Math.max(_.active?.length||0,_.archived?.length||0));const P=g===0?30:Math.max(1,Math.floor(30/g)),x=[];R.filter(y=>y.type==="Record_Owner").forEach(()=>x.push(["Created_By","==",t])),R.filter(y=>y.type==="Record_User").forEach(y=>{if("collectionField"in y){const I=W(l,y.collectionField);x.push([`${I.name}_Array`,"array-contains",s.Doc_ID])}}),R.filter(y=>y.type==="Record_Property").forEach(y=>{if("propertyField"in y){const I=y.roles.find(V=>V.role===s.Role);if(!I)throw new Error("PERMISSION_DENIED");const O=W(l,y.propertyField);O.type==="Array"?x.push([`${O.name}_Array`,"array-contains-any",I.values]):x.push([O.name,"in",I.values])}});const M=[];p.filter(y=>y.type==="Individual").forEach(y=>{const I=u?.individualEntities,O=[];if(I){const V=y.singleQuery?y.singleQuery:P;for(let A=0;A<I.length;A+=V){const C=I.slice(A,A+V);O.push(C)}if(!y.singleQuery)O.forEach(A=>{M.push(...b(x.concat([["id","in",A]])))});else{if(I.length>V)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${y.singleQuery} entities`);x.push(["id","in",I])}}}),k.filter(y=>y.parentFilter.type==="Individual").forEach(y=>{const{parentFilter:I,parentRestriction:O}=y;if("collectionField"in I){const V=W(l,I.collectionField);if("collection"in V){const A=s.collections?.[V.collection];if(!A)throw new Error("PERMISSION_DENIED");const C=A.individualEntities,j=[];if(C){const Q=O.singleQuery?O.singleQuery:P;for(let N=0;N<C.length;N+=Q){const z=C.slice(N,N+Q);j.push(z)}if(!O.singleQuery)j.forEach(N=>{M.push(...b(x.concat([[`${V.name}_Array`,"array-contains-any",N]])))});else{if(C.length>Q)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${O.singleQuery} entities`);x.push([`${V.name}_Array`,"array-contains-any",C])}}}}});const m=[];p.filter(y=>y.type==="Parent").forEach(y=>{if("collectionField"in y){const I=W(l,y.collectionField);if("collection"in I){const O=u?.parentEntities,V=[];if(O){const A=y.singleQuery?y.singleQuery:P;for(let C=0;C<O.length;C+=A){const j=O.slice(C,C+A);V.push(j)}if(!y.singleQuery)V.forEach(C=>{m.push(...b(x.concat([[`${I.name}_Array`,"array-contains-any",C]])))});else{if(O&&O.length>A)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${y.singleQuery} entities`);x.push([`${I.name}_Array`,"array-contains-any",O])}}}}}),k.filter(y=>y.parentFilter.type==="Parent").forEach(y=>{const{parentFilter:I,parentRestriction:O}=y;if("collectionField"in I&&"parentCollectionField"in I){const V=W(l,I.collectionField),A=W(l,I.parentCollectionField);if("collection"in V&&"collection"in A){const C=s.collections?.[V.collection];if(!C)throw new Error("PERMISSION_DENIED");const j=C.parentEntities,Q=[];if(j){const N=O.singleQuery?O.singleQuery:P;for(let z=0;z<j.length;z+=N){const q=j.slice(z,z+N);Q.push(q)}if(!O.singleQuery)Q.forEach(z=>{m.push(...b(x.concat([[`${A.name}_Array`,"array-contains-any",z]])))});else{if(j&&j.length>N)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${O.singleQuery} entities`);x.push([`${A.name}_Array`,"array-contains-any",j])}}}}});const S=[];m.length===0&&(p.filter(y=>y.type==="Parent_Property").forEach(y=>{if("collectionField"in y&&"propertyField"in y){const I=W(l,y.collectionField),O=W(l,y.propertyField);if("collection"in I){const V=u?.parentPropertyEntities||{};Object.entries(V).forEach(([A,C])=>{if(C.length>0){const j=[];for(let Q=0;Q<C.length;Q+=P){const N=C.slice(Q,Q+P);j.push(N)}j.forEach(Q=>{S.push(...b(x.concat([[`${I.name}_Array`,"array-contains-any",Q],[O.name,"==",A]])))})}})}}}),k.filter(y=>y.parentFilter.type==="Parent_Property").forEach(y=>{const{parentFilter:I}=y;if("collectionField"in I&&"parentCollectionField"in I&&"parentPropertyField"in I){const O=W(l,I.collectionField),V=W(l,I.parentCollectionField),A=W(l,I.parentPropertyField);if("collection"in O&&"collection"in V){const C=s.collections?.[O.collection];if(!C)throw new Error("PERMISSION_DENIED");const j=C.parentPropertyEntities||{};Object.entries(j).forEach(([Q,N])=>{if(N.length>0){const z=[];for(let q=0;q<N.length;q+=P){const re=N.slice(q,q+P);z.push(re)}z.forEach(q=>{S.push(...b(x.concat([[`${V.name}_Array`,"array-contains-any",q],[A.name,"==",Q]])))})}})}}}));const v=[...M,...m,...S];return!p.length&&!k.length?b(x):v}else throw new Error("PERMISSION_DENIED");else return[h]},Qs=(n,e,t,s)=>{const r=B.getFirestore(),i=n.at(-1);if(!i)throw new Error("EMPTY_PATH");const o=t.collections[i],{labels:a}=o,l=Te(r,n);if(s){const c=s.collections?.[a.collection];if(!s.Role)throw new Error("PERMISSION_DENIED");const d=c&&Se("Read",c),h=ci(o,t,s),u=[],f=hi(s.Role,o,t);if(!f)throw new Error("PERMISSION_DENIED");if(d)u.push(r.collection("system_fields").doc(a.collection).collection(`${a.collection}-${f.key}`).doc(e));else if(h)for(const w of h)u.push(r.collection("system_fields").doc(a.collection).collection(`${a.collection}-${w.field}`).doc(e));return u}else return[l.doc(e)]},xo=async(n,e,t,s,r,i,o,a,l)=>{const c=e.at(-2),d=ui(s.collections[c],s).map(f=>f.labels.collection);t.collections?t.collections.forEach(f=>{if(!d.includes(f))throw new Error(`SCHEMA_ERROR: Collection ${f} not found in subcollections of ${c}`)}):t.collections=d;const h=t.depth-1,u=t.collections.map(async f=>{const w=await Xs([...e,f],t.constraints,{user:o,pagination:t.limit,providedTransaction:a,noEmbeddingFields:l}).catch(E=>{throw E.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${f} for document at ${e.join("/")}`),E});n[f]=w.docs,r&&await Promise.all(n[f].map(E=>Ks(E,[...e,f,E.id],r,s,void 0,o,a,l))),h>0&&await Promise.all(n[f].map(E=>xo(E,[...e,f,E.id],{depth:h},s,r,i,o,a,l)))});await Promise.all(u)},Ks=async(n,e,t,s,r,i,o,a)=>{const l=e.at(-2);t.fields||=s.collections[l].fields.filter(h=>X(h));const c=t.depth-1,d=[];for(const h of t.fields)if("collection"in h){const u=n[h.name];if(!u)continue;const f=Object.keys(u);for(const w of f){const E=u[w],p=Ge(E.Collection_Path,w,{user:i,providedTransaction:o,noEmbeddingFields:a}).then(k=>{if(u[w]=k,c>0)return Ks(u[w],[...E.Collection_Path,w],{depth:c},s,r,i,o,a)}).catch(k=>{if(k.message.includes("NOT_FOUND")||k.code==="permission-denied")delete u[w];else throw k});d.push(p)}}await Promise.all(d)},Xs=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 l=t.pagination.number;if(typeof l!="number"||!Number.isFinite(l)||!Number.isInteger(l)||l<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const s=B.getFirestore();let r,i,o;const a=async l=>{const[c,d,h]=await Promise.all([t?.user?l.get(s.collection("system_user_permissions").doc(t.user)):Promise.resolve(Promise.resolve({})),l.get(s.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!d.exists)throw new Error("MAINTENANCE_MODE");if(d.data().active)throw new Error("MAINTENANCE_MODE");const f=h;let w;const E=Lt(),p=n.at(-1);if(!p)throw new Error("EMPTY_PATH");const k=Object.keys(f.collections).includes(p),b=E.disabledCollections?.includes(p);if(!k||b)throw new Error("COLLECTION_NOT_FOUND");const R=f.collections[p],{labels:g}=R,T=Ye(g.collection,f);if(t?.user){if(!c?.exists)throw new Error("PERMISSION_DENIED");if(w=c.data(),!w.Role)throw new Error("USER_ERROR");if(!w.Enabled)throw new Error("PERMISSION_DENIED")}let _=No(n,f,t?.user,w);if(_.length===0)return{cursor:{},pages:0,docs:[]};if(e&&(_=_.map(v=>(e.forEach(([y,I,O])=>{v=v.where(y,I,O)}),v))),i=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 v=t.pagination.startAfter||t.pagination.endBefore;if(t?.user){const y=ea(w.Role,R,f);if(v&&y!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+y)}t.pagination.orderByField&&t.pagination.orderByDirection?!t.pagination.startAfter&&!t.pagination.endBefore?_=_.map(y=>y.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).limit(t.pagination.number)):t.pagination.startAfter?_=_.map((y,I)=>y.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).startAfter(i.last.get(I)).limit(t.pagination.number)):_=_.map((y,I)=>y.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).endBefore(i.first.get(I)).limitToLast(t.pagination.number)):!t.pagination.startAfter&&!t.pagination.endBefore?_=_.map(y=>y.limit(t.pagination.number)):t.pagination.startAfter?_=_.map((y,I)=>y.startAfter(i.last.get(I)).limit(t.pagination.number)):_=_.map((y,I)=>y.endBefore(i.first.get(I)).limitToLast(t.pagination.number))}const P={};await ae("preOperation",E,T,["read",void 0,void 0,P]),await ae("preRead",E,T,[P,_,!0,!1]),o=new Map;const m=_.map(async v=>await l.get(v)),S=await Promise.all(m);for(const v of S){for(const y of v.docs){o.has(y.id)||o.set(y.id,{});const I=y.data(),O=o.get(y.id);O.id||=y.id;const V={...O,...I};delete V.Collection_Path_String,o.set(y.id,V)}i.first.set(S.indexOf(v),v.docs[0]),i.last.set(S.indexOf(v),v.docs.at(-1)||v.docs[0])}if(t?.pagination){let v=_[0];e&&(v=e.reduce((V,[A,C,j])=>V.where(A,C,j),v)),t.pagination.orderByField&&t.pagination.orderByDirection&&(v=v.orderBy(t.pagination.orderByField,t.pagination.orderByDirection));const I=(await v.count().get()).data().count,O=t.pagination.number;r=O>0?Math.ceil(I/O):0}for(const v of o.values()){const y=[],I=[...v.Collection_Path,v.id];t?.subcollections&&y.push(xo(o.get(v.id),I,me(t.subcollections),f,me(t?.relations),void 0,t.user,t.transactional?l:void 0,t?.noEmbeddingFields)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(A=>{if(typeof A=="string"){const C=R.fields.find(j=>j.name===A);if(C)return C;throw new Error(`SCHEMA_ERROR: Field ${A} not found in collection ${p}`)}return A})),y.push(Ks(o.get(v.id),I,me(t.relations),f,void 0,t.user,t.transactional?l:void 0,t?.noEmbeddingFields))),await Promise.all(y);for(const A of o.values())for(const C of R.fields){if(C.type==="Computed"){const j=Ie(C,T);if(!j.formula)continue;A[C.name]=await j.formula(A)}t?.noEmbeddingFields&&C.type==="Embedding"&&delete A[C.name]}if(t?.user&&w?.Role){const A=w.Role;if(!(T.custom?.serverAccess?.read!==void 0?await ie(T.custom.serverAccess.read,[A,v]):!0)){o.delete(v.id);continue}for(const j of R.fields){const Q=!j.access||j.access.includes(A),N=Ie(j,T),z=N?.custom?.serverAccess?.read!==void 0?await ie(N.custom.serverAccess.read,[A,v]):!0;(!Q||!z)&&(X(j)?(delete o.get(v.id)[j.name],delete o.get(v.id)[`${j.name}_Array`],delete o.get(v.id)[`${j.name}_Single`]):delete o.get(v.id)[j.name])}}const O=["read",v,v.id,P];await ae("postOperation",E,T,O),await ae("postRead",E,T,[P,_,v,!1])}t?.user&&await Ko(Array.from(o.values()),R,f,t.user,w)};return t?.providedTransaction?await a(t.providedTransaction):await s.runTransaction(async l=>{await a(l)},{readOnly:!0}),{cursor:i,pages:r,docs:Array.from(o.values())}},Do=async(n,e,t,s,r,i,o)=>{const a=t.at(-2),l=ui(r.collections[a],r).map(h=>h.labels.collection);s.collections?s.collections.forEach(h=>{if(!l.includes(h))throw new Error(`SCHEMA_ERROR: Collection ${h} not found in subcollections of ${a}`)}):s.collections=l;const c=s.depth-1,d=s.collections.map(async h=>{const u=await Xs([...t,h],s.constraints||[],{user:o,relations:i,pagination:s.limit,providedTransaction:n}).catch(f=>{throw f.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${h} for document at ${t.join("/")}`),f});e[h]=u.docs,c>0&&await Promise.all(e[h].map(async f=>{await Do(n,f,[...t,h,f.id],{depth:c},r,i,o)}))});await Promise.all(d)},Io=async(n,e,t,s,r,i,o,a)=>{const l=t.at(-2);r.fields||=s.collections[l].fields.filter(h=>X(h));const c=r.depth-1,d=[];for(const h of r.fields)if("collection"in h){const u=e[h.name];if(!u)continue;for(const[f,w]of Object.entries(u)){const E=Ge(w.Collection_Path,f,{user:i,providedTransaction:n,noComputedFields:o,noEmbeddingFields:a}).then(p=>{if(u[f]=p,c>0)return Io(n,u[f],[...w.Collection_Path,f],s,{depth:c},i,o,a)}).catch(p=>{if(p.message.includes("NOT_FOUND")||p.code==="permission-denied")delete u[f];else throw p});d.push(E)}}await Promise.all(d)},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=B.getFirestore();let r;const i=async o=>{const[a,l,c]=await Promise.all([t?.user?o.get(s.collection("system_user_permissions").doc(t.user)):Promise.resolve(Promise.resolve({})),o.get(s.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!l.exists)throw new Error("MAINTENANCE_MODE");if(l.data().active)throw new Error("MAINTENANCE_MODE");const h=c;let u;const f=Lt(),w=n.at(-1);if(!w)throw new Error("EMPTY_PATH");const E=Object.keys(h.collections).includes(w),p=f.disabledCollections?.includes(w);if(!E||p)throw new Error("COLLECTION_NOT_FOUND");const k=h.collections[w],{labels:b}=k,R=Ye(b.collection,h);let g;if(t?.user){if(!a?.exists)throw new Error("PERMISSION_DENIED");if(u=a.data(),!u.Role)throw new Error("USER_ERROR");if(!u.Enabled)throw new Error("PERMISSION_DENIED");if(g=u.collections?.[b.collection],!g)throw new Error("PERMISSION_DENIED")}if(t?.user&&(!g||!Se("Read",g)))throw new Error("PERMISSION_DENIED");const T=Qs(n,e,h,u);if(T.length===0)throw new Error("PERMISSION_DENIED");const _={};await ae("preOperation",f,R,["read",void 0,e,_]),await ae("preRead",f,R,[_,T,!1,!1]),r={};const M=T.map(O=>o.get(O)),m=await Promise.all(M);for(const O of m)if(O.exists){const V=O.data();r.id||=O.id,r={...r,...V},delete r.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${n?.join("/")||b.collection}`);const S=[],v=n?[...n,e]:[b.collection,e];if(t?.subcollections&&S.push(Do(o,r,v,t.subcollections,h,void 0,t.user)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(O=>{if(typeof O=="string"){const V=k.fields.find(A=>A.name===O);if(V)return V;throw new Error(`SCHEMA_ERROR: Field ${O} not found in collection ${w}`)}return O})),S.push(Io(o,r,v,h,t.relations,t.user,t.noComputedFields,t.noEmbeddingFields))),await Promise.all(S),!t?.noComputedFields){for(const O of k.fields)if(O.type==="Computed"){const V=Ie(O,R);if(!V.formula)continue;r[O.name]=await V.formula(r)}}if(t?.noEmbeddingFields)for(const O of k.fields)O.type==="Embedding"&&delete r[O.name];if(t?.user&&u?.Role){const O=u.Role;if(!(R.custom?.serverAccess?.read!==void 0?await ie(R.custom?.serverAccess?.read,[O,r]):!0))throw new Error("PERMISSION_DENIED");for(const A of k.fields){const C=!A.access||A.access.includes(O),j=Ie(A,R),Q=j?.custom?.serverAccess?.read!==void 0?await ie(j.custom.serverAccess.read,[O,r]):!0;(!C||!Q)&&(X(A)?(delete r[A.name],delete r[`${A.name}_Array`],delete r[`${A.name}_Single`]):delete r[A.name])}}await ae("postOperation",f,R,["read",r,e,_]),await ae("postRead",f,R,[_,T,r,!1]),t?.user&&await Qo(r,k,h,t.user,u)};return t?.providedTransaction?await i(t.providedTransaction):await s.runTransaction(async o=>{await i(o)},{readOnly:!0}),r},Ao=async(n,e,t,s,r,i,o)=>{const a=B.getFirestore(),l=Ye(s.labels.collection,r),c=s.labels.collection,d=s.fields.filter(u=>"unique"in u&&u.unique),h=[];if(await Promise.all(d.map(async u=>{{if(t[u.name]===void 0||Ne(t[u.name]))return;Ie(u,l);const f=t[u.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(!Js(f))h.push(`${u.name} "${t[u.name]}" is invalid`);else{const w=await a.collection("system_unique").doc(c).collection(`Unique-${c}-${u.name}`).doc(f).get();w.exists&&!(n==="update"&&w.data().id===e)&&h.push(`${u.name} "${t[u.name]}" already exists`)}}})),h.length>0)throw new Error(h.join(", "))},mt=async(n,e,t,s,r,i,o,a)=>{const{labels:l}=i,c=B.getFirestore(),d=Lt(),h=await ie(d.firebase?.writeLogTTL),u={operation:n,collection:l.collection,docId:r,user:"System",status:e,Collection_Path:s,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(h){const p=new Date,k=new Date(new Date().setDate(p.getDate()+h));u.TTL=B.Timestamp.fromDate(k)}const f=me(t);et(f),n!=="delete"&&(u.data.data=me(f)),n==="update"&&(u.data.originalRecord=me(a)),n!=="delete"&&["started","written"].includes(e)&&(delete u.data.data.Saved_At,delete u.data.data.Last_Save_At),e==="failed"&&(u.data.error=JSON.stringify(o));const w=Te(c,s),E=t.Last_Write_At;await w.doc(r).collection("system_write_log").doc(`${t.Last_Write_By}-${E.valueOf()}`).set(u)},Vt=async n=>{const e=pt.getAuth(),t=B.getFirestore(),s=[];if(await Promise.all([(async()=>{try{await t.collection("system_user_permissions").doc(n.User_ID).delete()}catch(r){s.push(`Error deleting user permissions:
6
+ `),e.length>5e6)throw new Error("Email body is too long");return e},Oo=async(n,e)=>{const t={};for(const s of e)t[s]=await import(`${n}/${s}.js`);return t};let ds,ko,bo,Gt,So,_n,En,fs=0;const kt={getMode(){return ko},getTimezone(){return bo},getGlobalConfigModule(){return me(Gt)},getCustomizationFile(n,e){if(!Object.keys(e.collections).includes(n))throw new Error("PERMISSION_DENIED");const t=ta([n],So,"node",kt);return me(t?.[n])},getVersionInfo(){return _n},getMaintenanceInfo(){return En}},Lc=async(n,e,t,s)=>{if(ds&&!s)return kt;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const r=process.env.STOKER_FB_WEB_APP_CONFIG,i=JSON.parse(r);ko=n;const a=(await import(e)).default;Gt=a("node",kt),!s&&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{ds=bt.getApp()}catch{ds=bt.initializeApp({credential:bt.applicationDefault(),databaseURL:i.databaseURL,storageBucket:i.storageBucket,projectId:i.projectId})}const l=await je();return So=await Oo(t,Object.keys(l.collections)),bo=await ie(Gt.timezone),B.getFirestore().collection("system_deployment").doc("maintenance_mode").onSnapshot(c=>{c.exists?(En=c.data(),ie(Gt.onMaintenanceUpdate,["node",En.active?"on":"off"])):console.error("Maintenance status not found")},c=>{console.error(c.message)}),B.getFirestore().collection("system_deployment").doc("latest_deploy").onSnapshot(c=>{c.exists?(_n=c.data(),fs++,fs>1&&ie(Gt.onVersionUpdate,["node",_n,fs])):console.error("Version info not found")},c=>{console.error(c.message)}),await new Promise(c=>{const d=()=>{En&&_n?c(kt):setTimeout(d,100)};d()}),kt},{getMode:To,getTimezone:Ro,getGlobalConfigModule:Pt,getCustomizationFile:Ye,getVersionInfo:su,getMaintenanceInfo:ru}=kt,je=async(n=!1)=>{const s=await ri.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,Ye(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},Vc=async()=>{const t=await ri.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(t.numChildren()<2))return Object.values(t.val())[0]},Te=(n,e)=>{let t=n;for(let s=0;s<e.length;s++)s%2===0?t=t.collection(e[s]):t=t.doc(e[s]);return t},No=(n,e,t,s)=>{const r=B.getFirestore(),i=n.at(-1);if(!i)throw new Error("EMPTY_PATH");const o=e.collections[i],{labels:a,fields:l,preloadCache:c}=o,d=Ye(i,e),h=Te(r,n);if(s)if(t){const u=s.collections?.[a.collection];if(!s.Role)throw new Error("PERMISSION_DENIED");const f=u&&Se("Read",u),w=li(o,e,s),E=oi(o,s),p=$s(o,s),k=ai(o,e,s),b=(y=[])=>{const I=[],O=hi(s.Role,o,e);if(!O)throw new Error("PERMISSION_DENIED");if(f){let V=r.collection("system_fields").doc(a.collection).collection(`${a.collection}-${O.key}`).where("Collection_Path_String","==",n.join("/"));y.forEach(A=>{V=V.where(...A)}),I.push(V)}else if(w)for(const V of w){let A=r.collection("system_fields").doc(a.collection).collection(`${a.collection}-${V.field}`).where("Collection_Path_String","==",n.join("/"));y.forEach(C=>{A=A.where(...C)}),I.push(A)}return I},R=E.filter(y=>"operations"in y&&y.operations?y.operations.includes("Read"):!0);if(R.length===0&&p.length===0&&k.length===0)return b();let g=0;const T=y=>{y&&(g===0?g=y:g*=y)};if(R.length>0){for(const y of R)if(y.operations&&y.type==="Record_Property"){const I=y.roles.find(O=>O.role===s.Role);if(!I)throw new Error("PERMISSION_DENIED");T(I.values?.length)}}c?.roles.includes(s.Role)&&c.range&&T(c.range.fields.length);const _=d.admin?.statusField;_&&!c?.roles.includes(s.Role)&&T(Math.max(_.active?.length||0,_.archived?.length||0));const P=g===0?30:Math.max(1,Math.floor(30/g)),x=[];R.filter(y=>y.type==="Record_Owner").forEach(()=>x.push(["Created_By","==",t])),R.filter(y=>y.type==="Record_User").forEach(y=>{if("collectionField"in y){const I=W(l,y.collectionField);x.push([`${I.name}_Array`,"array-contains",s.Doc_ID])}}),R.filter(y=>y.type==="Record_Property").forEach(y=>{if("propertyField"in y){const I=y.roles.find(V=>V.role===s.Role);if(!I)throw new Error("PERMISSION_DENIED");const O=W(l,y.propertyField);O.type==="Array"?x.push([`${O.name}_Array`,"array-contains-any",I.values]):x.push([O.name,"in",I.values])}});const M=[];p.filter(y=>y.type==="Individual").forEach(y=>{const I=u?.individualEntities,O=[];if(I){const V=y.singleQuery?y.singleQuery:P;for(let A=0;A<I.length;A+=V){const C=I.slice(A,A+V);O.push(C)}if(!y.singleQuery)O.forEach(A=>{M.push(...b(x.concat([["id","in",A]])))});else{if(I.length>V)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${y.singleQuery} entities`);x.push(["id","in",I])}}}),k.filter(y=>y.parentFilter.type==="Individual").forEach(y=>{const{parentFilter:I,parentRestriction:O}=y;if("collectionField"in I){const V=W(l,I.collectionField);if("collection"in V){const A=s.collections?.[V.collection];if(!A)throw new Error("PERMISSION_DENIED");const C=A.individualEntities,j=[];if(C){const Q=O.singleQuery?O.singleQuery:P;for(let N=0;N<C.length;N+=Q){const z=C.slice(N,N+Q);j.push(z)}if(!O.singleQuery)j.forEach(N=>{M.push(...b(x.concat([[`${V.name}_Array`,"array-contains-any",N]])))});else{if(C.length>Q)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${O.singleQuery} entities`);x.push([`${V.name}_Array`,"array-contains-any",C])}}}}});const m=[];p.filter(y=>y.type==="Parent").forEach(y=>{if("collectionField"in y){const I=W(l,y.collectionField);if("collection"in I){const O=u?.parentEntities,V=[];if(O){const A=y.singleQuery?y.singleQuery:P;for(let C=0;C<O.length;C+=A){const j=O.slice(C,C+A);V.push(j)}if(!y.singleQuery)V.forEach(C=>{m.push(...b(x.concat([[`${I.name}_Array`,"array-contains-any",C]])))});else{if(O&&O.length>A)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${y.singleQuery} entities`);x.push([`${I.name}_Array`,"array-contains-any",O])}}}}}),k.filter(y=>y.parentFilter.type==="Parent").forEach(y=>{const{parentFilter:I,parentRestriction:O}=y;if("collectionField"in I&&"parentCollectionField"in I){const V=W(l,I.collectionField),A=W(l,I.parentCollectionField);if("collection"in V&&"collection"in A){const C=s.collections?.[V.collection];if(!C)throw new Error("PERMISSION_DENIED");const j=C.parentEntities,Q=[];if(j){const N=O.singleQuery?O.singleQuery:P;for(let z=0;z<j.length;z+=N){const q=j.slice(z,z+N);Q.push(q)}if(!O.singleQuery)Q.forEach(z=>{m.push(...b(x.concat([[`${A.name}_Array`,"array-contains-any",z]])))});else{if(j&&j.length>N)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${O.singleQuery} entities`);x.push([`${A.name}_Array`,"array-contains-any",j])}}}}});const S=[];m.length===0&&(p.filter(y=>y.type==="Parent_Property").forEach(y=>{if("collectionField"in y&&"propertyField"in y){const I=W(l,y.collectionField),O=W(l,y.propertyField);if("collection"in I){const V=u?.parentPropertyEntities||{};Object.entries(V).forEach(([A,C])=>{if(C.length>0){const j=[];for(let Q=0;Q<C.length;Q+=P){const N=C.slice(Q,Q+P);j.push(N)}j.forEach(Q=>{S.push(...b(x.concat([[`${I.name}_Array`,"array-contains-any",Q],[O.name,"==",A]])))})}})}}}),k.filter(y=>y.parentFilter.type==="Parent_Property").forEach(y=>{const{parentFilter:I}=y;if("collectionField"in I&&"parentCollectionField"in I&&"parentPropertyField"in I){const O=W(l,I.collectionField),V=W(l,I.parentCollectionField),A=W(l,I.parentPropertyField);if("collection"in O&&"collection"in V){const C=s.collections?.[O.collection];if(!C)throw new Error("PERMISSION_DENIED");const j=C.parentPropertyEntities||{};Object.entries(j).forEach(([Q,N])=>{if(N.length>0){const z=[];for(let q=0;q<N.length;q+=P){const re=N.slice(q,q+P);z.push(re)}z.forEach(q=>{S.push(...b(x.concat([[`${V.name}_Array`,"array-contains-any",q],[A.name,"==",Q]])))})}})}}}));const v=[...M,...m,...S];return!p.length&&!k.length?b(x):v}else throw new Error("PERMISSION_DENIED");else return[h]},Js=(n,e,t,s)=>{const r=B.getFirestore(),i=n.at(-1);if(!i)throw new Error("EMPTY_PATH");const o=t.collections[i],{labels:a}=o,l=Te(r,n);if(s){const c=s.collections?.[a.collection];if(!s.Role)throw new Error("PERMISSION_DENIED");const d=c&&Se("Read",c),h=li(o,t,s),u=[],f=hi(s.Role,o,t);if(!f)throw new Error("PERMISSION_DENIED");if(d)u.push(r.collection("system_fields").doc(a.collection).collection(`${a.collection}-${f.key}`).doc(e));else if(h)for(const w of h)u.push(r.collection("system_fields").doc(a.collection).collection(`${a.collection}-${w.field}`).doc(e));return u}else return[l.doc(e)]},xo=async(n,e,t,s,r,i,o,a,l)=>{const c=e.at(-2),d=ci(s.collections[c],s).map(f=>f.labels.collection);t.collections?t.collections.forEach(f=>{if(!d.includes(f))throw new Error(`SCHEMA_ERROR: Collection ${f} not found in subcollections of ${c}`)}):t.collections=d;const h=t.depth-1,u=t.collections.map(async f=>{const w=await Ks([...e,f],t.constraints,{user:o,pagination:t.limit,providedTransaction:a,noEmbeddingFields:l}).catch(E=>{throw E.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${f} for document at ${e.join("/")}`),E});n[f]=w.docs,r&&await Promise.all(n[f].map(E=>Qs(E,[...e,f,E.id],r,s,void 0,o,a,l))),h>0&&await Promise.all(n[f].map(E=>xo(E,[...e,f,E.id],{depth:h},s,r,i,o,a,l)))});await Promise.all(u)},Qs=async(n,e,t,s,r,i,o,a)=>{const l=e.at(-2);t.fields||=s.collections[l].fields.filter(h=>K(h));const c=t.depth-1,d=[];for(const h of t.fields)if("collection"in h){const u=n[h.name];if(!u)continue;const f=Object.keys(u);for(const w of f){const E=u[w],p=Ge(E.Collection_Path,w,{user:i,providedTransaction:o,noEmbeddingFields:a}).then(k=>{if(u[w]=k,c>0)return Qs(u[w],[...E.Collection_Path,w],{depth:c},s,r,i,o,a)}).catch(k=>{if(k.message.includes("NOT_FOUND")||k.code==="permission-denied")delete u[w];else throw k});d.push(p)}}await Promise.all(d)},Ks=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 l=t.pagination.number;if(typeof l!="number"||!Number.isFinite(l)||!Number.isInteger(l)||l<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const s=B.getFirestore();let r,i,o;const a=async l=>{const[c,d,h]=await Promise.all([t?.user?l.get(s.collection("system_user_permissions").doc(t.user)):Promise.resolve(Promise.resolve({})),l.get(s.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!d.exists)throw new Error("MAINTENANCE_MODE");if(d.data().active)throw new Error("MAINTENANCE_MODE");const f=h;let w;const E=Pt(),p=n.at(-1);if(!p)throw new Error("EMPTY_PATH");const k=Object.keys(f.collections).includes(p),b=E.disabledCollections?.includes(p);if(!k||b)throw new Error("COLLECTION_NOT_FOUND");const R=f.collections[p],{labels:g}=R,T=Ye(g.collection,f);if(t?.user){if(!c?.exists)throw new Error("PERMISSION_DENIED");if(w=c.data(),!w.Role)throw new Error("USER_ERROR");if(!w.Enabled)throw new Error("PERMISSION_DENIED")}let _=No(n,f,t?.user,w);if(_.length===0)return{cursor:{},pages:0,docs:[]};if(e&&(_=_.map(v=>(e.forEach(([y,I,O])=>{v=v.where(y,I,O)}),v))),i=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 v=t.pagination.startAfter||t.pagination.endBefore;if(t?.user){const y=ea(w.Role,R,f);if(v&&y!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+y)}t.pagination.orderByField&&t.pagination.orderByDirection?!t.pagination.startAfter&&!t.pagination.endBefore?_=_.map(y=>y.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).limit(t.pagination.number)):t.pagination.startAfter?_=_.map((y,I)=>y.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).startAfter(i.last.get(I)).limit(t.pagination.number)):_=_.map((y,I)=>y.orderBy(t.pagination.orderByField,t.pagination.orderByDirection).endBefore(i.first.get(I)).limitToLast(t.pagination.number)):!t.pagination.startAfter&&!t.pagination.endBefore?_=_.map(y=>y.limit(t.pagination.number)):t.pagination.startAfter?_=_.map((y,I)=>y.startAfter(i.last.get(I)).limit(t.pagination.number)):_=_.map((y,I)=>y.endBefore(i.first.get(I)).limitToLast(t.pagination.number))}const P={};await ae("preOperation",E,T,["read",void 0,void 0,P]),await ae("preRead",E,T,[P,_,!0,!1]),o=new Map;const m=_.map(async v=>await l.get(v)),S=await Promise.all(m);for(const v of S){for(const y of v.docs){o.has(y.id)||o.set(y.id,{});const I=y.data(),O=o.get(y.id);O.id||=y.id;const V={...O,...I};delete V.Collection_Path_String,o.set(y.id,V)}i.first.set(S.indexOf(v),v.docs[0]),i.last.set(S.indexOf(v),v.docs.at(-1)||v.docs[0])}if(t?.pagination){let v=_[0];e&&(v=e.reduce((V,[A,C,j])=>V.where(A,C,j),v)),t.pagination.orderByField&&t.pagination.orderByDirection&&(v=v.orderBy(t.pagination.orderByField,t.pagination.orderByDirection));const I=(await v.count().get()).data().count,O=t.pagination.number;r=O>0?Math.ceil(I/O):0}for(const v of o.values()){const y=[],I=[...v.Collection_Path,v.id];t?.subcollections&&y.push(xo(o.get(v.id),I,me(t.subcollections),f,me(t?.relations),void 0,t.user,t.transactional?l:void 0,t?.noEmbeddingFields)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(A=>{if(typeof A=="string"){const C=R.fields.find(j=>j.name===A);if(C)return C;throw new Error(`SCHEMA_ERROR: Field ${A} not found in collection ${p}`)}return A})),y.push(Qs(o.get(v.id),I,me(t.relations),f,void 0,t.user,t.transactional?l:void 0,t?.noEmbeddingFields))),await Promise.all(y);for(const A of o.values())for(const C of R.fields){if(C.type==="Computed"){const j=Ie(C,T);if(!j.formula)continue;A[C.name]=await j.formula(A)}t?.noEmbeddingFields&&C.type==="Embedding"&&delete A[C.name]}if(t?.user&&w?.Role){const A=w.Role;if(!(T.custom?.serverAccess?.read!==void 0?await ie(T.custom.serverAccess.read,[A,v]):!0)){o.delete(v.id);continue}for(const j of R.fields){const Q=!j.access||j.access.includes(A),N=Ie(j,T),z=N?.custom?.serverAccess?.read!==void 0?await ie(N.custom.serverAccess.read,[A,v]):!0;(!Q||!z)&&(K(j)?(delete o.get(v.id)[j.name],delete o.get(v.id)[`${j.name}_Array`],delete o.get(v.id)[`${j.name}_Single`]):delete o.get(v.id)[j.name])}}const O=["read",v,v.id,P];await ae("postOperation",E,T,O),await ae("postRead",E,T,[P,_,v,!1])}t?.user&&await Ko(Array.from(o.values()),R,f,t.user,w)};return t?.providedTransaction?await a(t.providedTransaction):await s.runTransaction(async l=>{await a(l)},{readOnly:!0}),{cursor:i,pages:r,docs:Array.from(o.values())}},Do=async(n,e,t,s,r,i,o)=>{const a=t.at(-2),l=ci(r.collections[a],r).map(h=>h.labels.collection);s.collections?s.collections.forEach(h=>{if(!l.includes(h))throw new Error(`SCHEMA_ERROR: Collection ${h} not found in subcollections of ${a}`)}):s.collections=l;const c=s.depth-1,d=s.collections.map(async h=>{const u=await Ks([...t,h],s.constraints||[],{user:o,relations:i,pagination:s.limit,providedTransaction:n}).catch(f=>{throw f.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${h} for document at ${t.join("/")}`),f});e[h]=u.docs,c>0&&await Promise.all(e[h].map(async f=>{await Do(n,f,[...t,h,f.id],{depth:c},r,i,o)}))});await Promise.all(d)},Io=async(n,e,t,s,r,i,o,a)=>{const l=t.at(-2);r.fields||=s.collections[l].fields.filter(h=>K(h));const c=r.depth-1,d=[];for(const h of r.fields)if("collection"in h){const u=e[h.name];if(!u)continue;for(const[f,w]of Object.entries(u)){const E=Ge(w.Collection_Path,f,{user:i,providedTransaction:n,noComputedFields:o,noEmbeddingFields:a}).then(p=>{if(u[f]=p,c>0)return Io(n,u[f],[...w.Collection_Path,f],s,{depth:c},i,o,a)}).catch(p=>{if(p.message.includes("NOT_FOUND")||p.code==="permission-denied")delete u[f];else throw p});d.push(E)}}await Promise.all(d)},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=B.getFirestore();let r;const i=async o=>{const[a,l,c]=await Promise.all([t?.user?o.get(s.collection("system_user_permissions").doc(t.user)):Promise.resolve(Promise.resolve({})),o.get(s.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!l.exists)throw new Error("MAINTENANCE_MODE");if(l.data().active)throw new Error("MAINTENANCE_MODE");const h=c;let u;const f=Pt(),w=n.at(-1);if(!w)throw new Error("EMPTY_PATH");const E=Object.keys(h.collections).includes(w),p=f.disabledCollections?.includes(w);if(!E||p)throw new Error("COLLECTION_NOT_FOUND");const k=h.collections[w],{labels:b}=k,R=Ye(b.collection,h);let g;if(t?.user){if(!a?.exists)throw new Error("PERMISSION_DENIED");if(u=a.data(),!u.Role)throw new Error("USER_ERROR");if(!u.Enabled)throw new Error("PERMISSION_DENIED");if(g=u.collections?.[b.collection],!g)throw new Error("PERMISSION_DENIED")}if(t?.user&&(!g||!Se("Read",g)))throw new Error("PERMISSION_DENIED");const T=Js(n,e,h,u);if(T.length===0)throw new Error("PERMISSION_DENIED");const _={};await ae("preOperation",f,R,["read",void 0,e,_]),await ae("preRead",f,R,[_,T,!1,!1]),r={};const M=T.map(O=>o.get(O)),m=await Promise.all(M);for(const O of m)if(O.exists){const V=O.data();r.id||=O.id,r={...r,...V},delete r.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${n?.join("/")||b.collection}`);const S=[],v=n?[...n,e]:[b.collection,e];if(t?.subcollections&&S.push(Do(o,r,v,t.subcollections,h,void 0,t.user)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(O=>{if(typeof O=="string"){const V=k.fields.find(A=>A.name===O);if(V)return V;throw new Error(`SCHEMA_ERROR: Field ${O} not found in collection ${w}`)}return O})),S.push(Io(o,r,v,h,t.relations,t.user,t.noComputedFields,t.noEmbeddingFields))),await Promise.all(S),!t?.noComputedFields){for(const O of k.fields)if(O.type==="Computed"){const V=Ie(O,R);if(!V.formula)continue;r[O.name]=await V.formula(r)}}if(t?.noEmbeddingFields)for(const O of k.fields)O.type==="Embedding"&&delete r[O.name];if(t?.user&&u?.Role){const O=u.Role;if(!(R.custom?.serverAccess?.read!==void 0?await ie(R.custom?.serverAccess?.read,[O,r]):!0))throw new Error("PERMISSION_DENIED");for(const A of k.fields){const C=!A.access||A.access.includes(O),j=Ie(A,R),Q=j?.custom?.serverAccess?.read!==void 0?await ie(j.custom.serverAccess.read,[O,r]):!0;(!C||!Q)&&(K(A)?(delete r[A.name],delete r[`${A.name}_Array`],delete r[`${A.name}_Single`]):delete r[A.name])}}await ae("postOperation",f,R,["read",r,e,_]),await ae("postRead",f,R,[_,T,r,!1]),t?.user&&await Qo(r,k,h,t.user,u)};return t?.providedTransaction?await i(t.providedTransaction):await s.runTransaction(async o=>{await i(o)},{readOnly:!0}),r},Ao=async(n,e,t,s,r,i,o)=>{const a=B.getFirestore(),l=Ye(s.labels.collection,r),c=s.labels.collection,d=s.fields.filter(u=>"unique"in u&&u.unique),h=[];if(await Promise.all(d.map(async u=>{{if(t[u.name]===void 0||Ne(t[u.name]))return;Ie(u,l);const f=t[u.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(!Ys(f))h.push(`${u.name} "${t[u.name]}" is invalid`);else{const w=await a.collection("system_unique").doc(c).collection(`Unique-${c}-${u.name}`).doc(f).get();w.exists&&!(n==="update"&&w.data().id===e)&&h.push(`${u.name} "${t[u.name]}" already exists`)}}})),h.length>0)throw new Error(h.join(", "))},ht=async(n,e,t,s,r,i,o,a)=>{const{labels:l}=i,c=B.getFirestore(),d=Pt(),h=await ie(d.firebase?.writeLogTTL),u={operation:n,collection:l.collection,docId:r,user:"System",status:e,Collection_Path:s,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(h){const p=new Date,k=new Date(new Date().setDate(p.getDate()+h));u.TTL=B.Timestamp.fromDate(k)}const f=me(t);et(f),n!=="delete"&&(u.data.data=me(f)),n==="update"&&(u.data.originalRecord=me(a)),n!=="delete"&&["started","written"].includes(e)&&(delete u.data.data.Saved_At,delete u.data.data.Last_Save_At),e==="failed"&&(u.data.error=JSON.stringify(o));const w=Te(c,s),E=t.Last_Write_At;await w.doc(r).collection("system_write_log").doc(`${t.Last_Write_By}-${E.valueOf()}`).set(u)},Lt=async n=>{const e=mt.getAuth(),t=B.getFirestore(),s=[];if(await Promise.all([(async()=>{try{await t.collection("system_user_permissions").doc(n.User_ID).delete()}catch(r){s.push(`Error deleting user permissions:
7
7
  ${r}`)}})(),(async()=>{try{await e.deleteUser(n.User_ID)}catch(r){if(r.code==="auth/user-not-found")return;s.push(`Error deleting user:
8
- ${r}`)}})()]),s.length>0)throw new Error(s.join(", "))},er=async(n,e,t,s,r,i,o,a,l)=>{const c=B.getFirestore(),d=To(),h=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(h)n=h;else throw new Error("Admin email not set");const u=ds(n),f=Lc(e),w=t?ni(t):void 0,E=s?ni(s):void 0,p=r?ds(r):void 0,k=i?ds(i):void 0,b=o?Pn(o):void 0,R=l?Pn(l):void 0,g=Array.isArray(u)?u:[u];if(g.length===0||g.length===1&&!g[0])throw new Error("No valid email addresses provided");const T={to:u,message:{subject:f}};if(w&&(T.message.text=w),E&&(T.message.html=E),p){const _=Array.isArray(p)?p:[p];_.length>0&&_[0]&&(T.cc=p)}if(k){const _=Array.isArray(k)?k:[k];_.length>0&&_[0]&&(T.bcc=k)}b&&(T.replyTo=b),a&&(T.message.attachments=a),R&&(T.from=R),await c.collection("system_mail").add(T)},tr=async(n,e,t,s,r,i)=>{const o=pt.getAuth(),a=B.getFirestore(),l="USER_ERROR",c=async(u,f)=>{try{await Vt(u)}catch{throw new Error(`ROLLBACK_FAILED: ${f}`)}};let d;try{d=await o.createUser({email:s.Email,emailVerified:!1,password:i,displayName:s.Name,photoURL:s.Photo_URL,disabled:!s.Enabled})}catch{throw new Error(l)}try{await o.setCustomUserClaims(d.uid,{role:s.Role,collection:t,doc:n})}catch{throw await c(s,l),new Error(l)}try{await a.collection("system_user_permissions").doc(d.uid).set({...r,Role:s.Role,Enabled:s.Enabled??!1,Collection:t,Doc_ID:n})}catch{throw await c(s,l),new Error(l)}const h=e.auth.enableMultiFactorAuth;if(h===!0||typeof h=="object"&&h.includes(s.Role)){let u;try{u=await o.generateEmailVerificationLink(s.Email)}catch{throw await c(s,l),new Error(l)}if(u.includes("apiKey=&")){const f=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);u=u.replace("apiKey=&",`apiKey=${f.apiKey}&`)}if(u){const f=`https://${o.app.options.projectId}.firebaseapp.com/__/auth/action${u}`,w=await ie(e.appName),E=e?.mail?.emailVerification&&e.mail.emailVerification(f,w);try{await er(s.Email,E?.subject||"Please verify your email address",void 0,E?.html||`Please verify your email address by clicking the link:
8
+ ${r}`)}})()]),s.length>0)throw new Error(s.join(", "))},Xs=async(n,e,t,s,r,i,o,a,l)=>{const c=B.getFirestore(),d=To(),h=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(h)n=h;else throw new Error("Admin email not set");const u=us(n),f=Pc(e),w=t?ti(t):void 0,E=s?ti(s):void 0,p=r?us(r):void 0,k=i?us(i):void 0,b=o?Mn(o):void 0,R=l?Mn(l):void 0,g=Array.isArray(u)?u:[u];if(g.length===0||g.length===1&&!g[0])throw new Error("No valid email addresses provided");const T={to:u,message:{subject:f}};if(w&&(T.message.text=w),E&&(T.message.html=E),p){const _=Array.isArray(p)?p:[p];_.length>0&&_[0]&&(T.cc=p)}if(k){const _=Array.isArray(k)?k:[k];_.length>0&&_[0]&&(T.bcc=k)}b&&(T.replyTo=b),a&&(T.message.attachments=a),R&&(T.from=R),await c.collection("system_mail").add(T)},er=async(n,e,t,s,r,i)=>{const o=mt.getAuth(),a=B.getFirestore(),l="USER_ERROR",c=async(u,f)=>{try{await Lt(u)}catch{throw new Error(`ROLLBACK_FAILED: ${f}`)}};let d;try{d=await o.createUser({email:s.Email,emailVerified:!1,password:i,displayName:s.Name,photoURL:s.Photo_URL,disabled:!s.Enabled})}catch{throw new Error(l)}try{await o.setCustomUserClaims(d.uid,{role:s.Role,collection:t,doc:n})}catch{throw await c(s,l),new Error(l)}try{await a.collection("system_user_permissions").doc(d.uid).set({...r,Role:s.Role,Enabled:s.Enabled??!1,Collection:t,Doc_ID:n})}catch{throw await c(s,l),new Error(l)}const h=e.auth.enableMultiFactorAuth;if(h===!0||typeof h=="object"&&h.includes(s.Role)){let u;try{u=await o.generateEmailVerificationLink(s.Email)}catch{throw await c(s,l),new Error(l)}if(u.includes("apiKey=&")){const f=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);u=u.replace("apiKey=&",`apiKey=${f.apiKey}&`)}if(u){const f=`https://${o.app.options.projectId}.firebaseapp.com/__/auth/action${u}`,w=await ie(e.appName),E=e?.mail?.emailVerification&&e.mail.emailVerification(f,w);try{await Xs(s.Email,E?.subject||"Please verify your email address",void 0,E?.html||`Please verify your email address by clicking the link:
9
9
  </br>
10
10
  </br>
11
- <a href="${f}">${f}</a>`)}catch{throw await c(s,l),new Error(l)}}}return d.uid},nr=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")},Ln=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Wc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Ln(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?t[s]=new B.Timestamp(r.seconds,r.nanoseconds):Ln(r)&&e(r)})};e(n)},sr=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Ln(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?t[s]=new B.Timestamp(r._seconds,r._nanoseconds):Ln(r)&&e(r)})};e(n)},Hn=n=>{if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]==="_DELETE_FIELD"?n[e]=B.FieldValue.delete():Hn(n[e]))},jc=(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);yt(n,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},si=async(n,e,t,s,r,i)=>{if(!X(e)||!e.enforceHierarchy)return;const{fields:o}=n,a=B.getFirestore(),l=Object.entries(t[e.name]);if(!l.length)throw new Error(`VALIDATION_ERROR: relation ${e.name} is required`);const[c,d]=l[0];if(!d)throw new Error(`VALIDATION_ERROR: Relation ${e.name} is required`);const h=Te(a,d.Collection_Path);if(r.size++,!i&&r.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 u=await s.get(h.doc(c));if(!u.exists)throw new Error(`VALIDATION_ERROR: Record ${c} not found in collection ${e.collection}`);const f=u.data(),w=W(o,e.enforceHierarchy.field),E=e.enforceHierarchy;if(!f[E.recordLinkField]||!t[w.name]||!Object.keys(t[w.name]).every(p=>Object.keys(f[E.recordLinkField]).includes(p)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},pn=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`]},ms=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)},Zc=(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}},rr=async(n,e,t,s,r,i,o,a,l,c,d)=>{const{fields:h}=r,u=B.getFirestore(),f=new Map,w=new Map,E=new Map;for(const p of h)X(p)&&["OneToOne","OneToMany"].includes(p.type)&&p.enforceHierarchy&&t[p.name]&&(n==="Create"||n==="Update"&&!ze(d?.[p.name],t[p.name]))&&await si(r,p,t,o,a);for(const p of h)if(X(p)&&p.twoWay){const k=i.collections[p.collection],b=W(k.fields,p.twoWay),R=ct(k,[b]);if(t[p.name]){const g=Object.entries(t[p.name]);for(const T of g){const[_,P]=T;if(n==="Create"||!d?.[p.name]?.[_]){let x;const M=E.get(p.collection)?.[_];if(M)x=M;else{if(a.size++,a&&a.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 S=Te(u,P.Collection_Path),v=await o.get(S.doc(_));if(!v.exists){pn(p,s,_);continue}const y=v.data();w.set(p.collection,{...w.get(p.collection)||{},[_]:y}),x=me({...y,...On(t)})}const m={...x[b.name],[e]:{Collection_Path:t.Collection_Path,...jc(r,t,b)}};x[b.name]=m,x[`${b.name}_Array`]||=[],x[`${b.name}_Array`].push(e),R.size===1&&(x[`${b.name}_Single`]=m),E.set(p.collection,{...E.get(p.collection)||{},[_]:x})}}}if(n==="Update"){const g=Object.entries(d?.[p.name]||{});for(const T of g){const[_,P]=T;if(!t[p.name]?.[_]){let x;const M=E.get(p.collection)?.[_];if(M)x=M;else{if(a.size++,a&&a.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 m=Te(u,P.Collection_Path),S=await o.get(m.doc(_));if(!S.exists){f.set(p.name,[...f.get(p.name)||[],_]);continue}const v=S.data();w.set(p.collection,{...w.get(p.collection)||{},[_]:v}),x=me({...v,...On(t)})}x[b.name][e]&&delete x[b.name][e],Array.isArray(x[`${b.name}_Array`])&&(x[`${b.name}_Array`]=x[`${b.name}_Array`].filter(m=>m!==e)),R.size===1&&delete x[`${b.name}_Single`],E.set(p.collection,{...E.get(p.collection)||{},[_]:x})}}}}for(const[p,k]of E.entries()){const b=i.collections[p],R=Ye(p,i);for(const[g,T]of Object.entries(k)){const{addedFields:_,removedFields:P}=Zc(n,g,p,r,t,d);if(l&&c){for(const x of _){const M=W(b.fields,x.twoWay);if(!lr(b,M,c)){pn(x,s,g);continue}}for(const x of P){const M=W(b.fields,x.twoWay),m=ct(b,[M]);if(!lr(b,M,c)){ms(x,s,d?.[x.name]?.[g],g,m.size===1);continue}}if(!rt("Update",b,i,l,c,w.get(p)?.[g])){for(const x of _)pn(x,s,g);for(const x of P){const M=W(b.fields,x.twoWay),m=ct(b,[M]);ms(x,s,d?.[x.name]?.[g],g,m.size===1)}}if(!rt("Update",b,i,l,c,T)){for(const x of _)pn(x,s,g);for(const x of P){const M=W(b.fields,x.twoWay),m=ct(b,[M]);ms(x,s,d?.[x.name]?.[g],g,m.size===1)}}}try{await nn("update",T,b,R,["update",T,{},void 0,T],i)}catch(x){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${g} in ${p}: ${x.message}`)}for(const x of _){const M=W(b.fields,x.twoWay);["OneToOne","OneToMany"].includes(M.type)&&X(M)&&M.enforceHierarchy&&await si(b,M,T,o,a,!0)}}}return f},Co=(n,e,t)=>{n==="create"&&ft.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}`)}),ft.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}`)}))},ir=(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]=B.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])t[o]=B.FieldValue.serverTimestamp();else if(t[o]&&t[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},ps=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},zc=10,qc=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))},Fo=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,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const w=l.individualEntities,E=u?.individualEntities||[],p=i?w.filter(k=>!E.includes(k)):w;for(const k of p){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).");f.push(async()=>{if(!await ps(n,d,k,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const w=c.entityRestrictions?.restrictions?.find(g=>g.type==="Parent"&&g.roles.some(T=>T.role===e.Role));if(!w)throw new Error("PERMISSION_DENIED");const E=W(d.fields,w.collectionField),p=r.collections[E.collection],k=l.parentEntities,b=u?.parentEntities||[],R=i?k.filter(g=>!b.includes(g)):k;for(const g of R){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).");f.push(async()=>{if(!await ps(n,p,g,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const w=c.entityRestrictions?.restrictions?.find(R=>R.type==="Parent_Property"&&R.roles.some(g=>g.role===e.Role));if(!w)throw new Error("PERMISSION_DENIED");const E=W(d.fields,w.collectionField),p=r.collections[E.collection],k=l.parentPropertyEntities,b=u?.parentPropertyEntities||{};for(const[R,g]of Object.entries(k)){const T=b[R]||[],_=i?g.filter(P=>!T.includes(P)):g;for(const P of _){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).");f.push(async()=>{if(!await ps(n,p,P,t,s))throw new Error("PERMISSION_DENIED")})}}}await qc(f,zc)}}},Bc=async(n,e,t,s,r,i,o)=>{const a=Lt();let l=await je();if(n.length===0)throw new Error("EMPTY_PATH");const c=n.at(-1),d=Object.keys(l.collections).includes(c),h=a.disabledCollections?.includes(c);if(!d||h)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:w,enableWriteLog:E,softDelete:p}=u,k=Ye(f.collection,l),b=await ie(a.appName),R=B.getFirestore(),g=pt.getAuth(),_=(s?await g.getUser(s):void 0)?.customClaims?.role;let P;s&&await nr(n,u);const x=Te(R,n),M=o||x.doc().id;i=i||{},i.collection=f.collection,e.id=M,sr(e),Hn(e);const m=Vs("create",n,e,l,b,"Online",s||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp()),S=me(m);p&&(m[p.archivedField]=!1),Le(e),E&&await mt("create","started",tt(m,u),n,M,u),await ae("preOperation",a,k,["create",m,M,i]),await ae("preWrite",a,k,["create",m,M,i]),kn(u,m,l),bn(u,m),await aa(m,u,k,_),Le(m);try{if(u.auth&&t&&!t.password)throw new Error("Password is required");await Ao("create",M,m,u,l),await nn("create",m,u,k,["create",m,i],l)}catch(C){throw new Error(`VALIDATION_ERROR: ${C.message}`)}Le(m),e.id=M,p&&(m[p.archivedField]=!1),kn(u,m,l),bn(u,m);try{Co("create",m,S),ir("create",u,m),await nn("create",m,u,k,["create",m,i],l)}catch(C){throw new Error(`VALIDATION_ERROR: ${C.message}`)}if(s){const C=_;if(!C)throw new Error("USER_ERROR");if(!(k.custom?.serverAccess?.create!==void 0?await ie(k.custom.serverAccess.create,[C,m]):!0))throw new Error("PERMISSION_DENIED");for(const Q of u.fields){if(!(Q.name in m))continue;const N=Ie(Q,k);if(N?.custom?.serverAccess?.create!==void 0&&!await ie(N.custom.serverAccess.create,[C,m]))throw new Error("PERMISSION_DENIED")}}t&&(t.permissions||={},t.permissions.Role||=m.Role,t.permissions.Enabled||=m.Enabled);const I=async(C,j)=>{const[Q,N,z,q]=await Promise.all([C.get(R.collection("system_deployment").doc("latest_deploy")),C.get(R.collection("system_deployment").doc("maintenance_mode")),s?C.get(R.collection("system_user_permissions").doc(s)):Promise.resolve(Promise.resolve({})),je()]);if(j&&(j.size+=3),!Q.exists)throw new Error("VERSION_ERROR");const re=Q.data();if(re.force&&m.Last_Write_At.valueOf()<re.time.valueOf())throw new Error("VERSION_ERROR");if(!N.exists)throw new Error("MAINTENANCE_MODE");if(N.data().active)throw new Error("MAINTENANCE_MODE");if(l=q,s){if(!z?.exists)throw new Error("PERMISSION_DENIED");if(P=z.data(),!P.Role)throw new Error("USER_ERROR");if(!P.Enabled)throw new Error("PERMISSION_DENIED")}const he=w.filter(oe=>"unique"in oe&&oe.unique).map(async oe=>{if(!s||!oe.access||oe.access.includes(P.Role)){if(!e[oe.name])return;const Pe=Ie(oe,k);if(!(s&&Pe?.custom?.serverAccess?.read!==void 0?await ie(Pe.custom.serverAccess.read,[P?.Role,m]):!0))throw new Error("PERMISSION_DENIED");const Gn=e[oe.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Js(Gn)){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 C.get(R.collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${oe.name}`).doc(Gn)))?.exists)throw new Error(`VALIDATION_ERROR: ${oe.name} "${m[oe.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${oe.name} "${m[oe.name]}" is invalid`)}});await Promise.all(he),cr(m,M,u,l,s,P,t?.permissions),t?.permissions&&s&&P&&await Fo(C,t.permissions,s,P,l),cr(m,M,u,l,s,P,t?.permissions)};if(u.auth&&t){await R.runTransaction(async j=>{await I(j)},{maxAttempts:10});const C=await tr(M,a,f.collection,m,t.permissions,t.password);m.User_ID=C}try{const C={size:1};await R.runTransaction(async j=>{await I(j,C),r?.noTwoWay||await rr("Create",M,m,m,u,l,j,C,s,P);const Q=Ls(l);Ys("create",j,n,M,m,l,u,r,Q,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,N=>R.collection("system_fields").doc(f.collection).collection(`${f.collection}-${N.name}`).doc(M),(N,z)=>R.collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${N.name}`).doc(z),N=>R.collection("system_fields").doc(f.collection).collection(`${f.collection}-${N}`).doc(M),(N,z)=>Te(R,N).doc(z),(N,z,q)=>R.collection("system_fields").doc(N.collection).collection(`${N.collection}-${z}`).doc(q),(N,z,q)=>R.collection("system_fields").doc(N.collection).collection(`${N.collection}-${z.replaceAll(" ","-")}`).doc(q),void 0,void 0,C),j.set(x.doc(M),m)},{maxAttempts:10})}catch(C){const Q=await ae("postWriteError",a,k,["create",m,M,i,C]);if(E&&(await new Promise(N=>{setTimeout(N,250)}),await mt("create",Q?.resolved?"success":"failed",tt(m,u),n,M,u,Q?.resolved?void 0:C)),!Q?.resolved)throw u.auth&&t&&await Vt(m),C}const O=["create",m,M,i],V=[...O];return await ae("postWrite",a,k,O),await ae("postOperation",a,k,V),{id:M,...m}},Jt=async(n,e,t,s)=>{const r=pt.getAuth(),i=B.getFirestore(),o=e.customClaims||{};let a=!1;try{await r.updateUser(n,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{a=!0}try{await r.setCustomUserClaims(n,{...o})}catch{a=!0}try{await i.collection("system_user_permissions").doc(n).update({...t,Collection:o.collection,Doc_ID:o.doc,Role:o.role,Enabled:!e.disabled})}catch{a=!0}if(a)throw new Error(`ROLLBACK_FAILED: ${s}`)},$o=async(n,e,t,s,r,i,o,a,l,c)=>{const d=pt.getAuth(),h=B.getFirestore(),u=o?.customClaims||{},f="USER_ERROR";let w="";if(n==="create"){if(!c)throw new Error("VALIDATION_ERROR: Password is required");if(!a)throw new Error("VALIDATION_ERROR: Permissions are required");try{w=await tr(e,t,s,r,a,c)}catch(E){throw new Error(E.message)}}else if(n==="update"){if(!l||!o)throw new Error("USER_ERROR");const E={};if(i.Name!==r.Name&&(E.displayName=r.Name),i.Email!==r.Email&&(E.email=r.Email,E.emailVerified=!1),i.Photo_URL!==r.Photo_URL&&(E.photoURL=r.Photo_URL?r.Photo_URL:void 0),i.Enabled!==r.Enabled&&(E.disabled=!r.Enabled),c&&(E.password=c),Object.keys(E).length)try{await d.updateUser(i.User_ID,E),E.disabled===!0&&await d.revokeRefreshTokens(i.User_ID)}catch{throw await Jt(i.User_ID,o,l,f),new Error(f)}if(r.Role&&r.Role!==i.Role)try{await d.setCustomUserClaims(i.User_ID,{...u,role:r.Role}),await d.revokeRefreshTokens(i.User_ID)}catch{throw await Jt(i.User_ID,o,l,f),new Error(f)}try{await h.collection("system_user_permissions").doc(i.User_ID).set({...a||l,Collection:u.collection,Doc_ID:u.doc,Role:r.Role,Enabled:r.Enabled??i.Enabled??!1})}catch{throw await Jt(i.User_ID,o,l,f),new Error(f)}if(i.Email!==r.Email){const p=t.auth.enableMultiFactorAuth;if(p===!0||typeof p=="object"&&p.includes(r.Role)){let k=await d.generateEmailVerificationLink(r.Email).catch(()=>{throw new Error("Error generating email verification link")});if(k.includes("apiKey=&")){const b=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);k=k.replace("apiKey=&",`apiKey=${b.apiKey}&`)}if(k){const b=`https://${d.app.options.projectId}.firebaseapp.com/__/auth/action${k}`,R=await ie(t.appName),g=t?.mail?.emailVerification&&t.mail.emailVerification(b,R);try{await er(r.Email,g?.subject||"Please verify your email address",void 0,g?.html||`Please verify your email address by clicking the link:
11
+ <a href="${f}">${f}</a>`)}catch{throw await c(s,l),new Error(l)}}}return d.uid},tr=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")},Pn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Uc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Pn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?t[s]=new B.Timestamp(r.seconds,r.nanoseconds):Pn(r)&&e(r)})};e(n)},nr=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Pn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?t[s]=new B.Timestamp(r._seconds,r._nanoseconds):Pn(r)&&e(r)})};e(n)},Bn=n=>{if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]==="_DELETE_FIELD"?n[e]=B.FieldValue.delete():Bn(n[e]))},Wc=(n,e,t)=>{if(K(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);pt(n,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},ni=async(n,e,t,s,r,i)=>{if(!K(e)||!e.enforceHierarchy)return;const{fields:o}=n,a=B.getFirestore(),l=Object.entries(t[e.name]);if(!l.length)throw new Error(`VALIDATION_ERROR: relation ${e.name} is required`);const[c,d]=l[0];if(!d)throw new Error(`VALIDATION_ERROR: Relation ${e.name} is required`);const h=Te(a,d.Collection_Path);if(r.size++,!i&&r.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 u=await s.get(h.doc(c));if(!u.exists)throw new Error(`VALIDATION_ERROR: Record ${c} not found in collection ${e.collection}`);const f=u.data(),w=W(o,e.enforceHierarchy.field),E=e.enforceHierarchy;if(!f[E.recordLinkField]||!t[w.name]||!Object.keys(t[w.name]).every(p=>Object.keys(f[E.recordLinkField]).includes(p)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},mn=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`]},hs=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)},jc=(n,e,t,s,r,i)=>{const o=[],a=[];for(const l of s.fields)K(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}},sr=async(n,e,t,s,r,i,o,a,l,c,d)=>{const{fields:h}=r,u=B.getFirestore(),f=new Map,w=new Map,E=new Map;for(const p of h)K(p)&&["OneToOne","OneToMany"].includes(p.type)&&p.enforceHierarchy&&t[p.name]&&(n==="Create"||n==="Update"&&!ze(d?.[p.name],t[p.name]))&&await ni(r,p,t,o,a);for(const p of h)if(K(p)&&p.twoWay){const k=i.collections[p.collection],b=W(k.fields,p.twoWay),R=lt(k,[b]);if(t[p.name]){const g=Object.entries(t[p.name]);for(const T of g){const[_,P]=T;if(n==="Create"||!d?.[p.name]?.[_]){let x;const M=E.get(p.collection)?.[_];if(M)x=M;else{if(a.size++,a&&a.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 S=Te(u,P.Collection_Path),v=await o.get(S.doc(_));if(!v.exists){mn(p,s,_);continue}const y=v.data();w.set(p.collection,{...w.get(p.collection)||{},[_]:y}),x=me({...y,...vn(t)})}const m={...x[b.name],[e]:{Collection_Path:t.Collection_Path,...Wc(r,t,b)}};x[b.name]=m,x[`${b.name}_Array`]||=[],x[`${b.name}_Array`].push(e),R.size===1&&(x[`${b.name}_Single`]=m),E.set(p.collection,{...E.get(p.collection)||{},[_]:x})}}}if(n==="Update"){const g=Object.entries(d?.[p.name]||{});for(const T of g){const[_,P]=T;if(!t[p.name]?.[_]){let x;const M=E.get(p.collection)?.[_];if(M)x=M;else{if(a.size++,a&&a.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 m=Te(u,P.Collection_Path),S=await o.get(m.doc(_));if(!S.exists){f.set(p.name,[...f.get(p.name)||[],_]);continue}const v=S.data();w.set(p.collection,{...w.get(p.collection)||{},[_]:v}),x=me({...v,...vn(t)})}x[b.name][e]&&delete x[b.name][e],Array.isArray(x[`${b.name}_Array`])&&(x[`${b.name}_Array`]=x[`${b.name}_Array`].filter(m=>m!==e)),R.size===1&&delete x[`${b.name}_Single`],E.set(p.collection,{...E.get(p.collection)||{},[_]:x})}}}}for(const[p,k]of E.entries()){const b=i.collections[p],R=Ye(p,i);for(const[g,T]of Object.entries(k)){const{addedFields:_,removedFields:P}=jc(n,g,p,r,t,d);if(l&&c){for(const x of _){const M=W(b.fields,x.twoWay);if(!ar(b,M,c)){mn(x,s,g);continue}}for(const x of P){const M=W(b.fields,x.twoWay),m=lt(b,[M]);if(!ar(b,M,c)){hs(x,s,d?.[x.name]?.[g],g,m.size===1);continue}}if(!st("Update",b,i,l,c,w.get(p)?.[g])){for(const x of _)mn(x,s,g);for(const x of P){const M=W(b.fields,x.twoWay),m=lt(b,[M]);hs(x,s,d?.[x.name]?.[g],g,m.size===1)}}if(!st("Update",b,i,l,c,T)){for(const x of _)mn(x,s,g);for(const x of P){const M=W(b.fields,x.twoWay),m=lt(b,[M]);hs(x,s,d?.[x.name]?.[g],g,m.size===1)}}}try{await tn("update",T,b,R,["update",T,{},void 0,T],i)}catch(x){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${g} in ${p}: ${x.message}`)}for(const x of _){const M=W(b.fields,x.twoWay);["OneToOne","OneToMany"].includes(M.type)&&K(M)&&M.enforceHierarchy&&await ni(b,M,T,o,a,!0)}}}return f},Co=(n,e,t)=>{n==="create"&&dt.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}`)}),dt.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}`)}))},rr=(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]=B.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])t[o]=B.FieldValue.serverTimestamp();else if(t[o]&&t[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},ms=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},Zc=10,zc=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))},Fo=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,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const w=l.individualEntities,E=u?.individualEntities||[],p=i?w.filter(k=>!E.includes(k)):w;for(const k of p){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).");f.push(async()=>{if(!await ms(n,d,k,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const w=c.entityRestrictions?.restrictions?.find(g=>g.type==="Parent"&&g.roles.some(T=>T.role===e.Role));if(!w)throw new Error("PERMISSION_DENIED");const E=W(d.fields,w.collectionField),p=r.collections[E.collection],k=l.parentEntities,b=u?.parentEntities||[],R=i?k.filter(g=>!b.includes(g)):k;for(const g of R){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).");f.push(async()=>{if(!await ms(n,p,g,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const w=c.entityRestrictions?.restrictions?.find(R=>R.type==="Parent_Property"&&R.roles.some(g=>g.role===e.Role));if(!w)throw new Error("PERMISSION_DENIED");const E=W(d.fields,w.collectionField),p=r.collections[E.collection],k=l.parentPropertyEntities,b=u?.parentPropertyEntities||{};for(const[R,g]of Object.entries(k)){const T=b[R]||[],_=i?g.filter(P=>!T.includes(P)):g;for(const P of _){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).");f.push(async()=>{if(!await ms(n,p,P,t,s))throw new Error("PERMISSION_DENIED")})}}}await zc(f,Zc)}}},qc=async(n,e,t,s,r,i,o)=>{const a=Pt();let l=await je();if(n.length===0)throw new Error("EMPTY_PATH");const c=n.at(-1),d=Object.keys(l.collections).includes(c),h=a.disabledCollections?.includes(c);if(!d||h)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:w,enableWriteLog:E,softDelete:p}=u,k=Ye(f.collection,l),b=await ie(a.appName),R=B.getFirestore(),g=mt.getAuth(),_=(s?await g.getUser(s):void 0)?.customClaims?.role;let P;s&&await tr(n,u);const x=Te(R,n),M=o||x.doc().id;i=i||{},i.collection=f.collection,e.id=M,nr(e),Bn(e);const m=Ls("create",n,e,l,b,"Online",s||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp()),S=me(m);p&&(m[p.archivedField]=!1),Le(e),E&&await ht("create","started",m,n,M,u),await ae("preOperation",a,k,["create",m,M,i]),await ae("preWrite",a,k,["create",m,M,i]),On(u,m,l),kn(u,m),await oa(m,u,k,_),Le(m);try{if(u.auth&&t&&!t.password)throw new Error("Password is required");await Ao("create",M,m,u,l),await tn("create",m,u,k,["create",m,i],l)}catch(C){throw new Error(`VALIDATION_ERROR: ${C.message}`)}Le(m),e.id=M,p&&(m[p.archivedField]=!1),On(u,m,l),kn(u,m);try{Co("create",m,S),rr("create",u,m),await tn("create",m,u,k,["create",m,i],l)}catch(C){throw new Error(`VALIDATION_ERROR: ${C.message}`)}if(s){const C=_;if(!C)throw new Error("USER_ERROR");if(!(k.custom?.serverAccess?.create!==void 0?await ie(k.custom.serverAccess.create,[C,m]):!0))throw new Error("PERMISSION_DENIED");for(const Q of u.fields){if(!(Q.name in m))continue;const N=Ie(Q,k);if(N?.custom?.serverAccess?.create!==void 0&&!await ie(N.custom.serverAccess.create,[C,m]))throw new Error("PERMISSION_DENIED")}}t&&(t.permissions||={},t.permissions.Role||=m.Role,t.permissions.Enabled||=m.Enabled);const I=async(C,j)=>{const[Q,N,z,q]=await Promise.all([C.get(R.collection("system_deployment").doc("latest_deploy")),C.get(R.collection("system_deployment").doc("maintenance_mode")),s?C.get(R.collection("system_user_permissions").doc(s)):Promise.resolve(Promise.resolve({})),je()]);if(j&&(j.size+=3),!Q.exists)throw new Error("VERSION_ERROR");const re=Q.data();if(re.force&&m.Last_Write_At.valueOf()<re.time.valueOf())throw new Error("VERSION_ERROR");if(!N.exists)throw new Error("MAINTENANCE_MODE");if(N.data().active)throw new Error("MAINTENANCE_MODE");if(l=q,s){if(!z?.exists)throw new Error("PERMISSION_DENIED");if(P=z.data(),!P.Role)throw new Error("USER_ERROR");if(!P.Enabled)throw new Error("PERMISSION_DENIED")}const he=w.filter(oe=>"unique"in oe&&oe.unique).map(async oe=>{if(!s||!oe.access||oe.access.includes(P.Role)){if(!e[oe.name])return;const Pe=Ie(oe,k);if(!(s&&Pe?.custom?.serverAccess?.read!==void 0?await ie(Pe.custom.serverAccess.read,[P?.Role,m]):!0))throw new Error("PERMISSION_DENIED");const Hn=e[oe.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Ys(Hn)){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 C.get(R.collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${oe.name}`).doc(Hn)))?.exists)throw new Error(`VALIDATION_ERROR: ${oe.name} "${m[oe.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${oe.name} "${m[oe.name]}" is invalid`)}});await Promise.all(he),lr(m,M,u,l,s,P,t?.permissions),t?.permissions&&s&&P&&await Fo(C,t.permissions,s,P,l),lr(m,M,u,l,s,P,t?.permissions)};if(u.auth&&t){await R.runTransaction(async j=>{await I(j)},{maxAttempts:10});const C=await er(M,a,f.collection,m,t.permissions,t.password);m.User_ID=C}try{const C={size:1};await R.runTransaction(async j=>{await I(j,C),r?.noTwoWay||await sr("Create",M,m,m,u,l,j,C,s,P);const Q=Ps(l);Gs("create",j,n,M,m,l,u,r,Q,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,N=>R.collection("system_fields").doc(f.collection).collection(`${f.collection}-${N.name}`).doc(M),(N,z)=>R.collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${N.name}`).doc(z),N=>R.collection("system_fields").doc(f.collection).collection(`${f.collection}-${N}`).doc(M),(N,z)=>Te(R,N).doc(z),(N,z,q)=>R.collection("system_fields").doc(N.collection).collection(`${N.collection}-${z}`).doc(q),(N,z,q)=>R.collection("system_fields").doc(N.collection).collection(`${N.collection}-${z.replaceAll(" ","-")}`).doc(q),void 0,void 0,C),j.set(x.doc(M),m)},{maxAttempts:10})}catch(C){const Q=await ae("postWriteError",a,k,["create",m,M,i,C]);if(E&&(await new Promise(N=>{setTimeout(N,250)}),await ht("create",Q?.resolved?"success":"failed",m,n,M,u,Q?.resolved?void 0:C)),!Q?.resolved)throw u.auth&&t&&await Lt(m),C}const O=["create",m,M,i],V=[...O];return await ae("postWrite",a,k,O),await ae("postOperation",a,k,V),{id:M,...m}},Yt=async(n,e,t,s)=>{const r=mt.getAuth(),i=B.getFirestore(),o=e.customClaims||{};let a=!1;try{await r.updateUser(n,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{a=!0}try{await r.setCustomUserClaims(n,{...o})}catch{a=!0}try{await i.collection("system_user_permissions").doc(n).update({...t,Collection:o.collection,Doc_ID:o.doc,Role:o.role,Enabled:!e.disabled})}catch{a=!0}if(a)throw new Error(`ROLLBACK_FAILED: ${s}`)},$o=async(n,e,t,s,r,i,o,a,l,c)=>{const d=mt.getAuth(),h=B.getFirestore(),u=o?.customClaims||{},f="USER_ERROR";let w="";if(n==="create"){if(!c)throw new Error("VALIDATION_ERROR: Password is required");if(!a)throw new Error("VALIDATION_ERROR: Permissions are required");try{w=await er(e,t,s,r,a,c)}catch(E){throw new Error(E.message)}}else if(n==="update"){if(!l||!o)throw new Error("USER_ERROR");const E={};if(i.Name!==r.Name&&(E.displayName=r.Name),i.Email!==r.Email&&(E.email=r.Email,E.emailVerified=!1),i.Photo_URL!==r.Photo_URL&&(E.photoURL=r.Photo_URL?r.Photo_URL:void 0),i.Enabled!==r.Enabled&&(E.disabled=!r.Enabled),c&&(E.password=c),Object.keys(E).length)try{await d.updateUser(i.User_ID,E),E.disabled===!0&&await d.revokeRefreshTokens(i.User_ID)}catch{throw await Yt(i.User_ID,o,l,f),new Error(f)}if(r.Role&&r.Role!==i.Role)try{await d.setCustomUserClaims(i.User_ID,{...u,role:r.Role}),await d.revokeRefreshTokens(i.User_ID)}catch{throw await Yt(i.User_ID,o,l,f),new Error(f)}try{await h.collection("system_user_permissions").doc(i.User_ID).set({...a||l,Collection:u.collection,Doc_ID:u.doc,Role:r.Role,Enabled:r.Enabled??i.Enabled??!1})}catch{throw await Yt(i.User_ID,o,l,f),new Error(f)}if(i.Email!==r.Email){const p=t.auth.enableMultiFactorAuth;if(p===!0||typeof p=="object"&&p.includes(r.Role)){let k=await d.generateEmailVerificationLink(r.Email).catch(()=>{throw new Error("Error generating email verification link")});if(k.includes("apiKey=&")){const b=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);k=k.replace("apiKey=&",`apiKey=${b.apiKey}&`)}if(k){const b=`https://${d.app.options.projectId}.firebaseapp.com/__/auth/action${k}`,R=await ie(t.appName),g=t?.mail?.emailVerification&&t.mail.emailVerification(b,R);try{await Xs(r.Email,g?.subject||"Please verify your email address",void 0,g?.html||`Please verify your email address by clicking the link:
12
12
  </br>
13
13
  </br>
14
- <a href="${b}">${b}</a>`)}catch{throw await Jt(i.User_ID,o,l,f),new Error(f)}}}}}else if(n==="delete")try{await Vt(i)}catch(E){throw new Error(E.message)}if(w)return w},Hc=async(n,e,t)=>{const s=B.getFirestore(),r=[e];t&&t.trim()!==""&&r.push(t),r.sort();const i=[];for(const o of r){const a=s.collection("system_locks").doc(o);if((await n.get(a)).exists)throw new Error("DOCUMENT_LOCKED");i.push(a)}for(const o of i)n.set(o,{locked:!0})},ri=async(n,e)=>{const t=B.getFirestore(),s=[n];e&&e.trim()!==""&&s.push(e),s.sort();const r=t.batch();for(const i of s){const o=t.collection("system_locks").doc(i);r.delete(o)}await r.commit()},Mo=async(n,e,t,s,r,i,o)=>{const a=Lt();let l=await je(!0);if(n.length===0)throw new Error("EMPTY_PATH");const c=n.at(-1),d=Object.keys(l.collections).includes(c),h=a.disabledCollections?.includes(c);if(!d||h)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:w,enableWriteLog:E}=u,p=Ye(f.collection,l),k=await ie(a.appName),b=pt.getAuth(),R=B.getFirestore();let g;r&&await nr(n,u);const T=Te(R,n);o=o||{},o.collection=f.collection;let _=await Ge([f.collection],e,{user:r,noComputedFields:!0,noEmbeddingFields:!0});for(const N of w)N.type==="Computed"&&delete t[N.name];if(l={...l,collections:Object.fromEntries(Object.entries(l.collections).map(([N,z])=>[N,{...z,fields:z.fields.filter(q=>q.type!=="Computed")}]))},s&&!s.operation)throw new Error("VALIDATION_ERROR: User operation is required");if(s&&!u.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 P=u.auth&&s?.operation==="create",x=u.auth&&s?.operation==="delete",M=u.auth&&!P&&!x&&(s?.operation==="update"||t.Role||t.Enabled!==void 0||t.Name||t.Email||t.Photo_URL),m=N=>N.User_ID&&(u.auth&&!P&&!x&&s?.operation==="update"||t.Role&&t.Role!==N.Role||t.Enabled!==void 0&&t.Enabled!==N.Enabled||t.Name&&t.Name!==N.Name||t.Email&&t.Email!==N.Email||t.Photo_URL&&t.Photo_URL!==N.Photo_URL);delete t.id,sr(t),Hn(t);const S=Vs("update",n,t,l,k,"Online",r||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp()),v=me(S);for(const N of w)!X(N)&&Ne(S[N.name])&&N.nullable&&(S[N.name]=null);Le(S),Le(_),E&&await mt("update","started",tt(S,u),n,e,u,void 0,tt(_,u));const y=["update",S,e,o,void 0,me(_)];await ae("preOperation",a,p,y);const I=["update",S,e,o,void 0,me(_)];await ae("preWrite",a,p,I),kn(u,S,l),bn(u,S),Le(S);try{if(P&&!s.password)throw new Error("Password is required");const N={..._,...S};await Ao("update",e,N,u,l),et(N),await nn("update",N,u,p,["update",S,o,void 0,me(_)],l)}catch(N){throw new Error(`VALIDATION_ERROR: ${N.message}`)}Le(S),delete t.id,kn(u,S,l),bn(u,S);for(const N of w)!X(N)&&Ne(S[N.name])&&N.nullable&&(S[N.name]=null);try{const N={..._,...S};et(N),ir("update",u,S,_),Co("update",S,v),await nn("update",N,u,p,["update",S,o,void 0,_],l)}catch(N){throw new Error(`VALIDATION_ERROR: ${N.message}`)}let O;s&&(s.permissions||={});const V=async(N,z,q)=>{const[re,Ee,Ut,he,oe]=await Promise.all([N.get(R.collection("system_deployment").doc("latest_deploy")),N.get(R.collection("system_deployment").doc("maintenance_mode")),Ge([f.collection],e,{user:r,providedTransaction:N,noComputedFields:!0}),r?N.get(R.collection("system_user_permissions").doc(r)):Promise.resolve(Promise.resolve({})),je()]);if(q&&(q.size+=3),!re.exists)throw new Error("VERSION_ERROR");const Pe=re.data();if(Pe.force&&S.Last_Write_At.valueOf()<Pe.time.valueOf())throw new Error("VERSION_ERROR");if(!Ee.exists)throw new Error("MAINTENANCE_MODE");if(Ee.data().active)throw new Error("MAINTENANCE_MODE");if(!Ut)throw new Error("NOT_FOUND");if(_=Ut,l=oe,r){if(!he?.exists)throw new Error("PERMISSION_DENIED");if(g=he.data(),!g.Role)throw new Error("USER_ERROR");if(!g.Enabled)throw new Error("PERMISSION_DENIED")}if(q&&(q.size+=Qs(n,e,l,g).length),P&&_.User_ID||x&&!_.User_ID)throw new Error("USER_ERROR");if(m(_)){const ue=await N.get(R.collection("system_user_permissions").doc(_.User_ID));if(q&&q.size++,!ue?.exists)throw new Error("PERMISSION_DENIED");if(O=ue.data(),s?.permissions){if(s.permissions.Role||=S.Role||_.Role,s.permissions.Enabled??=S.Enabled??_.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 or=w.filter(ue=>"unique"in ue&&ue.unique).map(async ue=>{if(!r||!ue.access||ue.access.includes(g.Role)){if(S[ue.name]===void 0||Ne(S[ue.name]))return;const Wt=Ie(ue,p),ar={..._,...S};if(!(r&&Wt?.custom?.serverAccess?.read!==void 0?await ie(Wt.custom.serverAccess.read,[g?.Role,ar]):!0))throw new Error("PERMISSION_DENIED");const jt=S[ue.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Js(jt)){if(q&&q.size++,q&&q.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 Jn=await N.get(R.collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${ue.name}`).doc(jt));if(Jn.exists&&Jn.data().id!==e)throw new Error(`VALIDATION_ERROR: ${ue.name} "${S[ue.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${ue.name} "${S[ue.name]}" is invalid`)}});if(await Promise.all(or),r&&g?.Role){const ue=g.Role,Wt={..._,...S};if(!(p.custom?.serverAccess?.update!==void 0?await ie(p.custom.serverAccess.update,[ue,Wt,_]):!0))throw new Error("PERMISSION_DENIED");for(const Yn of u.fields){const jt=Ie(Yn,p);if(Object.prototype.hasOwnProperty.call(S,Yn.name)&&jt?.custom?.serverAccess?.update!==void 0&&!await ie(jt.custom.serverAccess.update,[ue,Wt,_]))throw new Error("PERMISSION_DENIED")}}ur(S,_,e,u,l,r,g,s?.operation?s.operation:M?"update":void 0,s?.permissions,O),s?.permissions&&r&&g&&await Fo(N,s.permissions,r,g,l,O,q),ur(S,_,e,u,l,r,g,s?.operation?s.operation:M?"update":void 0,s?.permissions,O),z&&(P||m(_)||x)&&await Hc(N,e,_.User_ID)};(P||M||x)&&await R.runTransaction(async N=>{await V(N,!0)},{maxAttempts:10});try{let N;if(P||m(_)||x){if(m(_)){N=await b.getUser(_.User_ID);const re=N.customClaims;if(!(re&&re.role&&re.collection&&re.doc))throw new Error("USER_ERROR")}const z={..._,...S};et(z);const q=await $o(s?.operation||"update",e,a,f.collection,z,_,N,s?.permissions,O,s?.password);P&&(S.User_ID=q),x&&(S.User_ID=B.FieldValue.delete())}try{const z={size:1};await R.runTransaction(async q=>{const re={..._,...S};await V(q,!1,z);let Ee;i?.noTwoWay||(Ee=await rr("Update",e,re,S,u,l,q,z,r,g,_));const Ut=Ls(l);Ys("update",q,n,e,S,l,u,i,Ut,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,he=>R.collection("system_fields").doc(f.collection).collection(`${f.collection}-${he.name}`).doc(e),(he,oe)=>R.collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${he.name}`).doc(oe),he=>R.collection("system_fields").doc(f.collection).collection(`${f.collection}-${he}`).doc(e),(he,oe)=>Te(R,he).doc(oe),(he,oe,Pe)=>R.collection("system_fields").doc(he.collection).collection(`${he.collection}-${oe}`).doc(Pe),(he,oe,Pe)=>R.collection("system_fields").doc(he.collection).collection(`${he.collection}-${oe.replaceAll(" ","-")}`).doc(Pe),_,Ee,z),q.update(T.doc(e),S)},{maxAttempts:10})}catch(z){const q=["update",S,e,o,z,void 0,void 0,me(_)],re=await ae("postWriteError",a,p,q);if(E&&(await new Promise(Ee=>{setTimeout(Ee,250)}),await mt("update",re?.resolved?"success":"failed",tt(S,u),n,e,u,re?.resolved?void 0:z,tt(_,u))),!re?.resolved)throw P&&await Vt(_),m(_)&&await Jt(_.User_ID,N,O,"USER_ERROR"),x&&await R.collection(f.collection).doc(e).update({User_ID:B.FieldValue.delete()}),z}(P||m(_)||x)&&await ti(ri,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")})}catch(N){throw(P||m(_)||x)&&await ti(ri,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),N}const A=["update",S,e,o,void 0,me(_)],C=[...A];await ae("postWrite",a,p,A),await ae("postOperation",a,p,C);const j={..._,...S};return et(j),{id:e,...j}},Gc=async(n,e,t,s,r)=>{const i=Lt();let o=await je();if(n.length===0)throw new Error("EMPTY_PATH");const a=n.at(-1),l=Object.keys(o.collections).includes(a),c=i.disabledCollections?.includes(a);if(!l||c)throw new Error("COLLECTION_NOT_FOUND");const d=o.collections[a],{labels:h,auth:u,enableWriteLog:f,softDelete:w}=d,E=Ye(h.collection,o),p=await ie(i.appName);if(w&&!u&&!s?.force)return await Mo(n,e,{[w.archivedField]:!0,[w.timestampField]:B.FieldValue.serverTimestamp()},void 0,t);const k=B.getFirestore();let b;t&&await nr(n,d);const R=Te(k,n);r=r||{},r.collection=h.collection;const g=await Ge([h.collection],e,{user:t});let T=Vs("delete",n,g,o,p,"Online",t||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp());const _=On(T);Le(T),f&&await mt("delete","started",tt(T,d),n,e,d),await ae("preOperation",i,E,["delete",T,e,r]),await ae("preWrite",i,E,["delete",T,e,r]),Le(T);const M=async y=>{const[I,O,V,A]=await Promise.all([y.get(k.collection("system_deployment").doc("maintenance_mode")),Ge([h.collection],e,{user:t,providedTransaction:y}),t?y.get(k.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(!O)throw new Error("NOT_FOUND");if(T={...O,..._},o=A,t){if(!V?.exists)throw new Error("PERMISSION_DENIED");if(b=V.data(),!b.Role)throw new Error("USER_ERROR");if(!b.Enabled)throw new Error("PERMISSION_DENIED");Jo(T,e,d,o,t,b)}if(t&&b?.Role){const j=b.Role;if(!(E.custom?.serverAccess?.delete!==void 0?await ie(E.custom.serverAccess.delete,[j,T]):!0))throw new Error("PERMISSION_DENIED")}};d.auth&&(await k.runTransaction(async y=>{await M(y)},{maxAttempts:10}),T.User_ID&&await Vt(T));try{await k.runTransaction(async y=>{await M(y);const I=Ls(o);Ys("delete",y,n,e,T,o,d,s,I,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,O=>k.collection("system_fields").doc(h.collection).collection(`${h.collection}-${O.name}`).doc(e),(O,V)=>k.collection("system_unique").doc(h.collection).collection(`Unique-${h.collection}-${O.name}`).doc(V),O=>k.collection("system_fields").doc(h.collection).collection(`${h.collection}-${O}`).doc(e),(O,V)=>Te(k,O).doc(V),(O,V,A)=>k.collection("system_fields").doc(O.collection).collection(`${O.collection}-${V}`).doc(A),(O,V,A)=>k.collection("system_fields").doc(O.collection).collection(`${O.collection}-${V.replaceAll(" ","-")}`).doc(A)),y.delete(R.doc(e))},{maxAttempts:10})}catch(y){const O=await ae("postWriteError",i,E,["delete",T,e,r,y]);if(f&&(await new Promise(V=>{setTimeout(V,250)}),await mt("delete",O?.resolved?"success":"failed",tt(T,d),n,e,d,O?.resolved?void 0:y)),!O?.resolved)throw d.auth&&T.User_ID&&await k.collection(h.collection).doc(e).update({User_ID:B.FieldValue.delete()}),y}const m=["delete",T,e,r],S=[...m];return await ae("postWrite",i,E,m),await ae("postOperation",i,E,S),{id:e,...T}},Yc=async(n,e)=>{const t=B.getFirestore(),s=To(),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)},Jc=n=>n!==null&&typeof n=="object",Qc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{r instanceof B.Timestamp?t[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:Jc(r)&&e(r)})};e(n)},Kc=async n=>await pt.getAuth().getUser(n),Xc=n=>{const e=Ro();return L.fromJSDate(n).setZone(e)},Po=n=>{const e=Ro();return L.fromJSDate(n.toDate()).setZone(e)},eu=(n,e)=>{const s=L.fromJSDate(n,{zone:e}).offset,i=L.fromJSDate(n).offset,o=s-i;return L.fromJSDate(n).plus({minutes:o}).toJSDate()},tu=(n,e)=>{const s=L.fromJSDate(n,{zone:e}).offset,i=L.fromJSDate(n).offset,o=s-i;return L.fromJSDate(n).minus({minutes:o}).toJSDate()},nu=n=>"seconds"in n&&"nanoseconds"in n?Po(new B.Timestamp(n.seconds,n.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=Bc;exports.addUser=tr;exports.convertDateToTimezone=Xc;exports.convertTimestampToTimezone=Po;exports.deleteRecord=Gc;exports.deleteUser=Vt;exports.deserializeDeleteSentinels=Hn;exports.deserializeTimestamps=sr;exports.deserializeTimestampsWithoutUnderscores=Wc;exports.displayDate=nu;exports.fetchCurrentSchema=je;exports.fetchLastSchema=Uc;exports.getCachedConfigValue=na;exports.getCollectionRefs=No;exports.getCustomizationFiles=Oo;exports.getDocumentRefs=Qs;exports.getFirestorePathRef=Te;exports.getInputSchema=Pc;exports.getOne=Ge;exports.getSome=Xs;exports.getUser=Kc;exports.getZodSchema=wi;exports.initializeFirebase=Zo;exports.initializeStoker=Vc;exports.isDeleteSentinel=Ne;exports.keepTimezone=eu;exports.removeTimezone=tu;exports.runChildProcess=jo;exports.sendMail=er;exports.sendMessage=Yc;exports.serializeTimestamps=Qc;exports.tryPromise=ie;exports.updateRecord=Mo;exports.updateUser=$o;exports.validateRelations=rr;exports.validateSoftDelete=ir;exports.writeLog=mt;
14
+ <a href="${b}">${b}</a>`)}catch{throw await Yt(i.User_ID,o,l,f),new Error(f)}}}}}else if(n==="delete")try{await Lt(i)}catch(E){throw new Error(E.message)}if(w)return w},Bc=async(n,e,t)=>{const s=B.getFirestore(),r=[e];t&&t.trim()!==""&&r.push(t),r.sort();const i=[];for(const o of r){const a=s.collection("system_locks").doc(o);if((await n.get(a)).exists)throw new Error("DOCUMENT_LOCKED");i.push(a)}for(const o of i)n.set(o,{locked:!0})},si=async(n,e)=>{const t=B.getFirestore(),s=[n];e&&e.trim()!==""&&s.push(e),s.sort();const r=t.batch();for(const i of s){const o=t.collection("system_locks").doc(i);r.delete(o)}await r.commit()},Mo=async(n,e,t,s,r,i,o)=>{const a=Pt();let l=await je(!0);if(n.length===0)throw new Error("EMPTY_PATH");const c=n.at(-1),d=Object.keys(l.collections).includes(c),h=a.disabledCollections?.includes(c);if(!d||h)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:w,enableWriteLog:E}=u,p=Ye(f.collection,l),k=await ie(a.appName),b=mt.getAuth(),R=B.getFirestore();let g;r&&await tr(n,u);const T=Te(R,n);o=o||{},o.collection=f.collection;let _=await Ge([f.collection],e,{user:r,noComputedFields:!0,noEmbeddingFields:!0});for(const N of w)N.type==="Computed"&&delete t[N.name];if(l={...l,collections:Object.fromEntries(Object.entries(l.collections).map(([N,z])=>[N,{...z,fields:z.fields.filter(q=>q.type!=="Computed")}]))},s&&!s.operation)throw new Error("VALIDATION_ERROR: User operation is required");if(s&&!u.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 P=u.auth&&s?.operation==="create",x=u.auth&&s?.operation==="delete",M=u.auth&&!P&&!x&&(s?.operation==="update"||t.Role||t.Enabled!==void 0||t.Name||t.Email||t.Photo_URL),m=N=>N.User_ID&&(u.auth&&!P&&!x&&s?.operation==="update"||t.Role&&t.Role!==N.Role||t.Enabled!==void 0&&t.Enabled!==N.Enabled||t.Name&&t.Name!==N.Name||t.Email&&t.Email!==N.Email||t.Photo_URL&&t.Photo_URL!==N.Photo_URL);delete t.id,nr(t),Bn(t);const S=Ls("update",n,t,l,k,"Online",r||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp()),v=me(S);for(const N of w)!K(N)&&Ne(S[N.name])&&N.nullable&&(S[N.name]=null);Le(S),Le(_),E&&await ht("update","started",S,n,e,u,void 0,_);const y=["update",S,e,o,void 0,me(_)];await ae("preOperation",a,p,y);const I=["update",S,e,o,void 0,me(_)];await ae("preWrite",a,p,I),On(u,S,l),kn(u,S),Le(S);try{if(P&&!s.password)throw new Error("Password is required");const N={..._,...S};await Ao("update",e,N,u,l),et(N),await tn("update",N,u,p,["update",S,o,void 0,me(_)],l)}catch(N){throw new Error(`VALIDATION_ERROR: ${N.message}`)}Le(S),delete t.id,On(u,S,l),kn(u,S);for(const N of w)!K(N)&&Ne(S[N.name])&&N.nullable&&(S[N.name]=null);try{const N={..._,...S};et(N),rr("update",u,S,_),Co("update",S,v),await tn("update",N,u,p,["update",S,o,void 0,_],l)}catch(N){throw new Error(`VALIDATION_ERROR: ${N.message}`)}let O;s&&(s.permissions||={});const V=async(N,z,q)=>{const[re,Ee,Vt,he,oe]=await Promise.all([N.get(R.collection("system_deployment").doc("latest_deploy")),N.get(R.collection("system_deployment").doc("maintenance_mode")),Ge([f.collection],e,{user:r,providedTransaction:N,noComputedFields:!0}),r?N.get(R.collection("system_user_permissions").doc(r)):Promise.resolve(Promise.resolve({})),je()]);if(q&&(q.size+=3),!re.exists)throw new Error("VERSION_ERROR");const Pe=re.data();if(Pe.force&&S.Last_Write_At.valueOf()<Pe.time.valueOf())throw new Error("VERSION_ERROR");if(!Ee.exists)throw new Error("MAINTENANCE_MODE");if(Ee.data().active)throw new Error("MAINTENANCE_MODE");if(!Vt)throw new Error("NOT_FOUND");if(_=Vt,l=oe,r){if(!he?.exists)throw new Error("PERMISSION_DENIED");if(g=he.data(),!g.Role)throw new Error("USER_ERROR");if(!g.Enabled)throw new Error("PERMISSION_DENIED")}if(q&&(q.size+=Js(n,e,l,g).length),P&&_.User_ID||x&&!_.User_ID)throw new Error("USER_ERROR");if(m(_)){const ue=await N.get(R.collection("system_user_permissions").doc(_.User_ID));if(q&&q.size++,!ue?.exists)throw new Error("PERMISSION_DENIED");if(O=ue.data(),s?.permissions){if(s.permissions.Role||=S.Role||_.Role,s.permissions.Enabled??=S.Enabled??_.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 ir=w.filter(ue=>"unique"in ue&&ue.unique).map(async ue=>{if(!r||!ue.access||ue.access.includes(g.Role)){if(S[ue.name]===void 0||Ne(S[ue.name]))return;const Ut=Ie(ue,p),or={..._,...S};if(!(r&&Ut?.custom?.serverAccess?.read!==void 0?await ie(Ut.custom.serverAccess.read,[g?.Role,or]):!0))throw new Error("PERMISSION_DENIED");const Wt=S[ue.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Ys(Wt)){if(q&&q.size++,q&&q.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 Yn=await N.get(R.collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${ue.name}`).doc(Wt));if(Yn.exists&&Yn.data().id!==e)throw new Error(`VALIDATION_ERROR: ${ue.name} "${S[ue.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${ue.name} "${S[ue.name]}" is invalid`)}});if(await Promise.all(ir),r&&g?.Role){const ue=g.Role,Ut={..._,...S};if(!(p.custom?.serverAccess?.update!==void 0?await ie(p.custom.serverAccess.update,[ue,Ut,_]):!0))throw new Error("PERMISSION_DENIED");for(const Gn of u.fields){const Wt=Ie(Gn,p);if(Object.prototype.hasOwnProperty.call(S,Gn.name)&&Wt?.custom?.serverAccess?.update!==void 0&&!await ie(Wt.custom.serverAccess.update,[ue,Ut,_]))throw new Error("PERMISSION_DENIED")}}cr(S,_,e,u,l,r,g,s?.operation?s.operation:M?"update":void 0,s?.permissions,O),s?.permissions&&r&&g&&await Fo(N,s.permissions,r,g,l,O,q),cr(S,_,e,u,l,r,g,s?.operation?s.operation:M?"update":void 0,s?.permissions,O),z&&(P||m(_)||x)&&await Bc(N,e,_.User_ID)};(P||M||x)&&await R.runTransaction(async N=>{await V(N,!0)},{maxAttempts:10});try{let N;if(P||m(_)||x){if(m(_)){N=await b.getUser(_.User_ID);const re=N.customClaims;if(!(re&&re.role&&re.collection&&re.doc))throw new Error("USER_ERROR")}const z={..._,...S};et(z);const q=await $o(s?.operation||"update",e,a,f.collection,z,_,N,s?.permissions,O,s?.password);P&&(S.User_ID=q),x&&(S.User_ID=B.FieldValue.delete())}try{const z={size:1};await R.runTransaction(async q=>{const re={..._,...S};await V(q,!1,z);let Ee;i?.noTwoWay||(Ee=await sr("Update",e,re,S,u,l,q,z,r,g,_));const Vt=Ps(l);Gs("update",q,n,e,S,l,u,i,Vt,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,he=>R.collection("system_fields").doc(f.collection).collection(`${f.collection}-${he.name}`).doc(e),(he,oe)=>R.collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${he.name}`).doc(oe),he=>R.collection("system_fields").doc(f.collection).collection(`${f.collection}-${he}`).doc(e),(he,oe)=>Te(R,he).doc(oe),(he,oe,Pe)=>R.collection("system_fields").doc(he.collection).collection(`${he.collection}-${oe}`).doc(Pe),(he,oe,Pe)=>R.collection("system_fields").doc(he.collection).collection(`${he.collection}-${oe.replaceAll(" ","-")}`).doc(Pe),_,Ee,z),q.update(T.doc(e),S)},{maxAttempts:10})}catch(z){const q=["update",S,e,o,z,void 0,void 0,me(_)],re=await ae("postWriteError",a,p,q);if(E&&(await new Promise(Ee=>{setTimeout(Ee,250)}),await ht("update",re?.resolved?"success":"failed",S,n,e,u,re?.resolved?void 0:z,_)),!re?.resolved)throw P&&await Lt(_),m(_)&&await Yt(_.User_ID,N,O,"USER_ERROR"),x&&await R.collection(f.collection).doc(e).update({User_ID:B.FieldValue.delete()}),z}(P||m(_)||x)&&await ei(si,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")})}catch(N){throw(P||m(_)||x)&&await ei(si,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),N}const A=["update",S,e,o,void 0,me(_)],C=[...A];await ae("postWrite",a,p,A),await ae("postOperation",a,p,C);const j={..._,...S};return et(j),{id:e,...j}},Hc=async(n,e,t,s,r)=>{const i=Pt();let o=await je();if(n.length===0)throw new Error("EMPTY_PATH");const a=n.at(-1),l=Object.keys(o.collections).includes(a),c=i.disabledCollections?.includes(a);if(!l||c)throw new Error("COLLECTION_NOT_FOUND");const d=o.collections[a],{labels:h,auth:u,enableWriteLog:f,softDelete:w}=d,E=Ye(h.collection,o),p=await ie(i.appName);if(w&&!u&&!s?.force)return await Mo(n,e,{[w.archivedField]:!0,[w.timestampField]:B.FieldValue.serverTimestamp()},void 0,t);const k=B.getFirestore();let b;t&&await tr(n,d);const R=Te(k,n);r=r||{},r.collection=h.collection;const g=await Ge([h.collection],e,{user:t});let T=Ls("delete",n,g,o,p,"Online",t||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp());const _=vn(T);Le(T),f&&await ht("delete","started",T,n,e,d),await ae("preOperation",i,E,["delete",T,e,r]),await ae("preWrite",i,E,["delete",T,e,r]),Le(T);const M=async y=>{const[I,O,V,A]=await Promise.all([y.get(k.collection("system_deployment").doc("maintenance_mode")),Ge([h.collection],e,{user:t,providedTransaction:y}),t?y.get(k.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(!O)throw new Error("NOT_FOUND");if(T={...O,..._},o=A,t){if(!V?.exists)throw new Error("PERMISSION_DENIED");if(b=V.data(),!b.Role)throw new Error("USER_ERROR");if(!b.Enabled)throw new Error("PERMISSION_DENIED");Jo(T,e,d,o,t,b)}if(t&&b?.Role){const j=b.Role;if(!(E.custom?.serverAccess?.delete!==void 0?await ie(E.custom.serverAccess.delete,[j,T]):!0))throw new Error("PERMISSION_DENIED")}};d.auth&&(await k.runTransaction(async y=>{await M(y)},{maxAttempts:10}),T.User_ID&&await Lt(T));try{await k.runTransaction(async y=>{await M(y);const I=Ps(o);Gs("delete",y,n,e,T,o,d,s,I,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,O=>k.collection("system_fields").doc(h.collection).collection(`${h.collection}-${O.name}`).doc(e),(O,V)=>k.collection("system_unique").doc(h.collection).collection(`Unique-${h.collection}-${O.name}`).doc(V),O=>k.collection("system_fields").doc(h.collection).collection(`${h.collection}-${O}`).doc(e),(O,V)=>Te(k,O).doc(V),(O,V,A)=>k.collection("system_fields").doc(O.collection).collection(`${O.collection}-${V}`).doc(A),(O,V,A)=>k.collection("system_fields").doc(O.collection).collection(`${O.collection}-${V.replaceAll(" ","-")}`).doc(A)),y.delete(R.doc(e))},{maxAttempts:10})}catch(y){const O=await ae("postWriteError",i,E,["delete",T,e,r,y]);if(f&&(await new Promise(V=>{setTimeout(V,250)}),await ht("delete",O?.resolved?"success":"failed",T,n,e,d,O?.resolved?void 0:y)),!O?.resolved)throw d.auth&&T.User_ID&&await k.collection(h.collection).doc(e).update({User_ID:B.FieldValue.delete()}),y}const m=["delete",T,e,r],S=[...m];return await ae("postWrite",i,E,m),await ae("postOperation",i,E,S),{id:e,...T}},Gc=async(n,e)=>{const t=B.getFirestore(),s=To(),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)},Yc=n=>n!==null&&typeof n=="object",Jc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{r instanceof B.Timestamp?t[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:Yc(r)&&e(r)})};e(n)},Qc=async n=>await mt.getAuth().getUser(n),Kc=n=>{const e=Ro();return L.fromJSDate(n).setZone(e)},Po=n=>{const e=Ro();return L.fromJSDate(n.toDate()).setZone(e)},Xc=(n,e)=>{const s=L.fromJSDate(n,{zone:e}).offset,i=L.fromJSDate(n).offset,o=s-i;return L.fromJSDate(n).plus({minutes:o}).toJSDate()},eu=(n,e)=>{const s=L.fromJSDate(n,{zone:e}).offset,i=L.fromJSDate(n).offset,o=s-i;return L.fromJSDate(n).minus({minutes:o}).toJSDate()},tu=n=>"seconds"in n&&"nanoseconds"in n?Po(new B.Timestamp(n.seconds,n.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=qc;exports.addUser=er;exports.convertDateToTimezone=Kc;exports.convertTimestampToTimezone=Po;exports.deleteRecord=Hc;exports.deleteUser=Lt;exports.deserializeDeleteSentinels=Bn;exports.deserializeTimestamps=nr;exports.deserializeTimestampsWithoutUnderscores=Uc;exports.displayDate=tu;exports.fetchCurrentSchema=je;exports.fetchLastSchema=Vc;exports.getCachedConfigValue=na;exports.getCollectionRefs=No;exports.getCustomizationFiles=Oo;exports.getDocumentRefs=Js;exports.getFirestorePathRef=Te;exports.getInputSchema=Mc;exports.getOne=Ge;exports.getSome=Ks;exports.getUser=Qc;exports.getZodSchema=wi;exports.initializeFirebase=Zo;exports.initializeStoker=Lc;exports.isDeleteSentinel=Ne;exports.keepTimezone=Xc;exports.removeTimezone=eu;exports.runChildProcess=jo;exports.sendMail=Xs;exports.sendMessage=Gc;exports.serializeTimestamps=Jc;exports.tryPromise=ie;exports.updateRecord=Mo;exports.updateUser=$o;exports.validateRelations=sr;exports.validateSoftDelete=rr;exports.writeLog=ht;