@stoker-platform/node-client 0.5.44 → 0.5.46

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 He=require("lodash/isEqual.js"),Wo=require("lodash/merge.js"),jo=require("lodash/set.js"),he=require("lodash/cloneDeep.js"),Rt=require("firebase-admin/app"),B=require("firebase-admin/firestore"),ai=require("node:url"),zo=require("cross-spawn"),li=require("firebase-admin/database"),yt=require("firebase-admin/auth"),Wn=n=>!!n.auth,be=(n,e)=>{if(e?.operations)return e.operations.includes(n)},jn=(n,e)=>e?e.Role?n.access?.includes(e.Role):!1:!0,Zo=(n,e)=>e?!e.Role||n.restrictCreate===!0?!1:typeof n.restrictCreate=="object"?n.restrictCreate?.includes(e.Role):!0:!0,ci=(n,e)=>e?!e.Role||n.restrictUpdate===!0?!1:typeof n.restrictUpdate=="object"?n.restrictUpdate?.includes(e.Role):!0:!0,cr=(n,e,t)=>{const{labels:s}=n;return t.collections&&be("Update",t.collections[s.collection])&&(!e.access||jn(e,t))&&ci(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),ui=(n,e)=>{const t={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=n,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const u=a?.[t[l.type]];c.role===e.Role&&(!c.assignable||u?.active)&&s.push(l)})}),s},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},di=(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 d=h.restrictions?.find(f=>f.type===o.type&&f.roles.some(p=>p.role===t.Role));if(!d)throw new Error("PERMISSION_DENIED");d.roles.forEach(f=>{f.role===t.Role&&(!h.assignable?.includes(t.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:d})})}),s},fi=(n,e,t)=>{const s=Object.values(e.collections),{labels:r}=n,i=[];for(const o of s){const{fields:a}=o;for(const l of a)if(!(l.access&&!jn(l,t))&&t.Role&&X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)!i.find(h=>h.field===c.field)&&c.roles.includes(t.Role)&&i.push(c)}return i},qo=(n,e,t,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const u=ui(e,r),h=Ms(e,r),d=di(e,t,r);u?.filter(E=>E.type==="Record_Owner").forEach(E=>{"operations"in E&&E.operations&&!E.operations.includes(n)||i.Created_By!==s&&(c=!1)}),u?.filter(E=>E.type==="Record_User").forEach(E=>{if("operations"in E&&E.operations&&!E.operations.includes(n))return;const C=W(a,E.collectionField);i[`${C.name}_Array`]?.includes(r.Doc_ID)||(c=!1)}),u?.filter(E=>E.type==="Record_Property").forEach(E=>{if("operations"in E&&E.operations&&!E.operations.includes(n))return;const C=W(a,E.propertyField),_=E.roles.find(z=>z.role===r.Role);C.type==="Array"?_.values?.some(z=>i[C.name].includes(z))||(c=!1):_.values?.includes(i[C.name])||(c=!1)});let f=!0,p=!1;h?.filter(E=>E.type==="Individual").forEach(()=>{p=!0,l?.individualEntities?.includes(i.id)||(f=!1)});let O=!0,y=!1;if(h?.filter(E=>E.type==="Parent").forEach(E=>{y=!0;const C=W(a,E.collectionField);l?.parentEntities?.some(_=>i[`${C.name}_Array`].includes(_))||(O=!1)}),h?.filter(E=>E.type==="Parent_Property").forEach(E=>{y=!0;const C=W(a,E.collectionField),_=W(a,E.propertyField);Object.entries(l?.parentPropertyEntities||{}).some(z=>{const[k,m]=z;return k===i[_.name]&&i[`${C.name}_Array`].some($=>m.includes($))})||(O=!1)}),p&&y){if(!(f||O)){c=!1;return}}else if(!f||!O){c=!1;return}let g=!0,N=!1;d?.filter(E=>E.parentFilter.type==="Individual").forEach(E=>{N=!0;const{parentFilter:C}=E,_=W(a,C.collectionField),z=r.collections?.[_.collection];if(!z){c=!1;return}z.individualEntities?.some(k=>i[`${_.name}_Array`].includes(k))||(g=!1)});let b=!0,x=!1;if(d?.filter(E=>E.parentFilter.type==="Parent").forEach(E=>{x=!0;const{parentFilter:C}=E,_=W(a,C.collectionField),z=W(a,C.parentCollectionField),k=r.collections?.[_.collection];if(!k){c=!1;return}k.parentEntities?.some(m=>i[`${z.name}_Array`].includes(m))||(b=!1)}),d?.filter(E=>E.parentFilter.type==="Parent_Property").forEach(E=>{x=!0;const{parentFilter:C}=E,_=W(a,C.collectionField),z=W(a,C.parentPropertyField),k=W(a,C.parentCollectionField),m=r.collections?.[_.collection];if(!m){c=!1;return}Object.entries(m.parentPropertyEntities||{}).some($=>{const[v,H]=$;return v===i[z.name]&&i[`${k.name}_Array`].some(w=>H.includes(w))})||(b=!1)}),N&&x){if(!(g||b)){c=!1;return}}else if(!g||!b){c=!1;return}return c},it=(n,e,t,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;be(n,a)||(l=!1);const u=Ms(e,r)?.filter(h=>h.type==="Individual").length>0;return n==="Create"&&u&&(l=!1),qo(n,e,t,s,r,i)||(l=!1),l},hi=(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 u=i.access.attributeRestrictions?.filter(d=>d.type===c&&d.roles.some(f=>f.role===e.Role)),h=i.access.entityRestrictions?.restrictions?.filter(d=>d.type===c&&d.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(d=>n.config.roles.includes(d)))){s=`Collection ${r} has invalid entity restrictions assignable value`,t=!1;return}if(u?.length||h?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const d=Object.keys(l);if(d.length!==1||d[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 d=Object.keys(l);if(!(d.length===1&&Object.keys(n.collections).includes(d[0])&&Array.isArray(l[d[0]]))){s=`Collection ${r} has invalid parent entities value`,t=!1;return}}if(a==="Parent_Property"){const d=Object.keys(l);if(!(d.length===1&&Object.keys(n.collections).includes(d[0])&&typeof l[d[0]]=="object"&&l[d[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:u,entityRestrictions:h}=a,d=c.assignable,f=e.collections?.[o.collection],p=["read","create","update","delete"];if(d!==!0&&!(typeof d=="object"&&d.includes(t))?p.forEach(y=>{const g=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const N=!!a.operations[y]?.includes(t),b=!!f?.operations.includes(g);if(!N&&b){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}if(N&&!b){r=`Collection ${o.collection} has missing ${y} operation for role ${t}`,s=!1;return}}}):p.forEach(y=>{const g=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const N=!!a.operations[y]?.includes(t),b=!!f?.operations.includes(g);if(!N&&b){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}}}),!u&&!h||(u?.forEach(y=>{for(const g of y.roles)if(g.role===t&&!g.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${t}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${t}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${t}`,s=!1;return}}}),h?.assignable?.includes(t)))continue;let O=!1;if(h?.restrictions?.forEach(y=>{for(const g of y.roles)if(g.role===t){if(O=!0,y.type==="Individual"&&!e.collections?.[o.collection]?.individualEntities){r=`Collection ${o.collection} is missing individual entities`,s=!1;return}if(y.type==="Parent"){const N=W(l,y.collectionField);if(!X(N)){s=!1;return}if(!e.collections?.[o.collection]?.parentEntities){r=`Collection ${o.collection} is missing parent entities`,s=!1;return}}if(y.type==="Parent_Property"){const N=W(l,y.collectionField);if(!X(N)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[N.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),O&&!e.collections?.[o.collection]?.restrictEntities){r=`Collection ${o.collection} must have restrictEntities set to true`,s=!1;return}}return r&&console.error(`PERMISSION_DENIED: ${r}`),s},Go=(n,e,t,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:u}=c;let h=!0,d="";const f=u?.filter(p=>s===p.userRole);return f?.length&&!f.some(p=>p.recordRole===r)?(d=`User ${s} does not have write access to record with role ${r}`,h=!1,h):n==="update"&&o.User_ID&&f?.length&&!f.some(p=>p.recordRole===a)?(d=`User ${s} does not have write access to record with role ${r}`,h=!1,h):(u?.forEach(p=>{s===p.userRole&&p.recordRole===r&&n!=="delete"&&i&&Object.keys(t.collections).forEach(O=>{const y=i.collections?.[O],g=l?.collections?.[O];if(!(n==="update"&&He(y,g))&&y){const N=p.collections.some(b=>b.collection===O);if(N){if(N){const b=p.collections.find(E=>E.collection===O);if(!(y.operations.every(E=>b.operations.includes(E))||n==="update"&&He(y.operations,g?.operations))){d=`User ${s} does not have write access to all included operations for collection ${O}`,h=!1;return}if(!b.auth&&y.auth&&!(n==="update"&&He(y.auth,g?.auth))){d=`User ${s} does not have write access to auth for collection ${O}`,h=!1;return}const x={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(x).forEach(E=>{const C=x[E];if(b.attributeRestrictions?.includes(C)&&!(y[E]?.active||n==="update"&&He(y[E],g?.[E]))){d=`User ${s} does not have write access to attribute restriction ${E} for collection ${O}`,h=!1;return}}),b.restrictEntities&&!y.restrictEntities&&!(n==="update"&&He(y.restrictEntities,g?.restrictEntities))){d=`User ${s} does not have write access to restrictEntities for collection ${O}`,h=!1;return}}}else{d=`User ${s} does not have write access to collection ${O}`,h=!1;return}}})}),d&&console.error(`PERMISSION_DENIED: ${d}`),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&&!Wn(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const u of a?.operations||[])if(!l?.operations.includes(u)&&(!be("Read",c)||!be(u,c))){i=`User does not have ${u.toLowerCase()} access to collection ${o.labels.collection}`,r=!1;return}if(!a?.recordOwner&&l?.recordOwner&&c?.recordOwner){i=`User does not have write access to recordOwner for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordUser&&l?.recordUser&&c?.recordUser){i=`User does not have write access to recordUser for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordProperty&&l?.recordProperty&&c?.recordProperty){i=`User does not have write access to recordProperty for collection ${o.labels.collection}`,r=!1;return}if(!a?.restrictEntities&&l?.restrictEntities&&c?.restrictEntities){i=`User does not have write access to restrictEntities for collection ${o.labels.collection}`,r=!1;return}}),i&&console.error(`PERMISSION_DENIED: ${i}`),r},Ps=(n,e,t,s,r,i,o,a,l,c,u)=>{const{labels:h}=s;let d=!0,f="";if(!e.Role)return f="Record does not have a role",d=!1,d;if(n==="update"&&!c)return f="Original record is required for update operations",d=!1,d;if(n==="update"&&i&&u==="update"&&a&&!l)return f="Original permissions are required for this operation",d=!1,d;if(i){if(!o?.Role)return f="Current user does not have a role",d=!1,d;if(!Go(n,s,r,o.Role,e.Role,a,c,c?.Role,l))return d=!1,d;if(n==="update"&&u!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",d=!1,d;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",d=!1,d;if(n==="delete"&&i===e.User_ID)return f="User cannot delete their own record",d=!1,d}return n==="delete"||u==="delete"||!a?d:a.Role?(Bo(r,a)||(d=!1),a.Collection&&a.Collection!==h.collection?(f="Permissions collection does not match record collection",d=!1,d):a.Role!==e.Role?(f="Permissions role does not match record role",d=!1,d):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",d=!1,d):a.Doc_ID&&a.Doc_ID!==t?(f="Permissions doc ID does not match record doc ID",d=!1,d):!Ho(r,a,a.Role)||i&&o&&l&&!Yo(r,o,a,l)?(d=!1,d):(f&&console.error(`PERMISSION_DENIED: ${f}`),d)):(f="Permissions do not have a role",d=!1,d)},ur=(n,e,t,s,r,i,o)=>{const{labels:a,fields:l}=t,c=i?.collections?.[a.collection];let u=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!be("Create",c)&&(u=!1),r&&!it("Create",t,s,r,i,n)&&(u=!1),t.auth&&o&&(r&&!Wn(c)&&(u=!1),Ps("create",n,e,t,s,r,i,o)||(u=!1));for(const h of l){const d=n[h.name];h.access&&!jn(h,i)&&d!==void 0&&(u=!1),d!==void 0&&!Zo(h,i)&&(u=!1)}if(!u)throw new Error("PERMISSION_DENIED")},xe=n=>n&&(n._methodName==="deleteField"||n.constructor.name==="DeleteTransform"),nt=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(xe(n[e])?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&nt(n[e]))},dr=(n,e,t,s,r,i,o,a,l,c)=>{const{labels:u,fields:h}=s,d=o?.collections?.[u.collection],f={...e,...n};nt(f);let p=!0,O="";if(i&&!d)throw new Error("PERMISSION_DENIED");i&&!be("Update",d)&&(p=!1,O="Authenticated user does not have Update access to this collection"),i&&(!it("Update",s,r,i,o,e)||!it("Update",s,r,i,o,f))&&(p=!1,O="Authenticated user does not have Update access to this document"),i&&s.softDelete&&f[s.softDelete.archivedField]!==e[s.softDelete.archivedField]&&!be("Delete",d)&&(p=!1,O="Authenticated user does not have Delete or Restore access to this document"),a&&(i&&!Wn(d)&&(p=!1,O="Authenticated user does not have Auth access for this collection"),Ps("update",f,t,s,r,i,o,l,c,e,a)||(O="Authenticated user does not have sufficient write access for this record",p=!1));for(const y of h){const g=n[y.name];y.access&&!jn(y,o)&&g!==void 0&&(O=`Authenticated user does not have access to field ${y.name}`,p=!1),g!==void 0&&!ci(y,o)&&(O=`Authenticated user does not have Update access to field ${y.name}`,p=!1)}if(!p)throw O&&console.error(`PERMISSION_DENIED: ${O}`),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(be("Delete",a)||(l=!1),it("Delete",t,s,r,i,n)||(l=!1),t.auth&&n.User_ID&&(Wn(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(be("Read",o)||(a=!1),it("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(be("Read",o)||(a=!1),n.forEach(l=>{it("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(u=>u.role===n));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},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 u in c)u==="custom"||u==="admin"||u==="name"||u==="formula"||delete c[u];i[o]=l}return i},Ae=(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,oe=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 u of e)if(u==="__proto__"||u==="constructor"||u==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=Qn,i=!0;for(const u of e){if(u===void 0||r[u]===void 0){i=!1;break}r=r[u]}if(r&&i&&!s)return r;let o,a=n,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const u of o){if(u===void 0||a[u]===void 0){l=!1;break}a=a[u]}let c;if(l&&(c=await oe(a,t)),c){let u=Qn;const h={};for(let d=0;d<e.length;d++){const f=e[d];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");d===e.length-1?jo(h,e.join("."),c):(u[f]||={},u=u[f])}}Wo(Qn,h)}return c},at=(n,e,t)=>{const s=Object.values(t.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field==n.name&&(i=!0)}return i},mi=(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)),ht=["id","Collection_Path","Last_Write_At","Last_Save_At","Last_Write_By","Last_Write_App","Last_Write_Connection_Status","Last_Write_Version","Created_At","Saved_At","Created_By"],zn=()=>ht.map(n=>{let e="",t;switch(n){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",t=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:n,type:e,required:!0};return t&&(s.values=t),s}),pi=(n,e)=>{const t=[],{access:s,fields:r}=n,{attributeRestrictions:i,entityRestrictions:o}=s,a=zn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":t.push(W(a,"Created_By"));break;case"Record_User":t.push(W(r,l.collectionField));break;case"Record_Property":t.push(W(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(W(a,"id"));break;case"Parent":t.push(W(r,l.collectionField));break;case"Parent_Property":t.push(W(r,l.collectionField)),t.push(W(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(W(r,l.collectionField));break;case"Parent":t.push(W(r,l.parentCollectionField));break;case"Parent_Property":t.push(W(r,l.parentCollectionField)),t.push(W(r,l.parentPropertyField));break}})),[...new Set(t)]},sa=(n,e)=>{const t=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=n,a=zn();return t.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{(!c.access||c.access.includes(e))&&t.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{t.push(W(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{ht.includes(c)&&t.push(W(a,c))}),o?.forEach(c=>{const u=W(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&u&&(!u.access||u.access?.includes(e))&&ht.includes(c.field)&&t.push(W(a,c.field))}),pi(n,e).forEach(c=>{ht.includes(c.name)&&t.push(W(a,c.name))}),[...new Set(t)]},ra=(n,e,t)=>{const s=[],{fields:r,preloadCache:i}=e,o=zn();i?.range&&i.range.fields.forEach(c=>{ht.includes(c)?s.push(W(o,c)):s.push(W(r,c))});const a=new Set,l=mi(e,t);return Object.entries(l).map(([c,u])=>{n.name===c&&Object.values(u).forEach(h=>{h.forEach(d=>{a.add(d)})})}),a.forEach(c=>{s.push(...pi(e,c))}),[...new Set(s)]},un=(n,e,t)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=mi(e,t);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{t.collections[c].fields.forEach(h=>{X(h)&&h.collection===e.labels.collection&&h.dependencyFields?.some(d=>d.field===n.name)&&h.constraints&&h.constraints.forEach(d=>{o.push(d[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)]},yi=(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},gi=(n,e,t)=>{const s=yi(e,t);for(const r of s.values())if(r.roles.includes(n))return r},ia=(n,e)=>{const{fields:t}=e,s=zn(),r=[];return[...t,...s.filter(o=>o.name!=="id")].forEach(o=>{n?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ls=(n,e,t)=>{const s={};return Object.values(n.collections).forEach(r=>{const i=yi(r,n),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},bn=n=>({Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_Version:n.Last_Write_Version,Last_Write_App:n.Last_Write_App,Last_Save_At:n.Last_Save_At}),Xn=async(n,e,t)=>{if(e){const s=await oe(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),ut=(n,e)=>{const{access:t,queries:s}=n,{serverReadOnly:r}=t,i=new Set;if(s)for(const o of s){const a=W(e,o.field);e.find(l=>l.name===o.field)&&X(a)&&["OneToOne","OneToMany"].includes(a.type)&&i.add(a)}return e.forEach(o=>{X(o)&&["OneToOne","OneToMany"].includes(o.type)&&o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a)))&&i.add(o)}),i},gt=(n,e)=>{const{access:t,recordTitleField:s}=n,{serverReadOnly:r}=t,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},Tn=(n,e,t)=>{const{fields:s}=n;s.forEach(i=>{if(X(i))if(e[i.name]){if(xe(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=t.collections[i.collection],l=W(a.fields,o);gt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(u=>{e[i.name][u][o]?e[i.name][u][`${o}_Lowercase`]=e[i.name][u][o].toLowerCase():delete e[i.name][u][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),ut(n,s).forEach(i=>{if(e[i.name])if(xe(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`]={id:o,...a}}}})},Sn=(n,e)=>{gt(n,n.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},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!==void 0&&!(s&&o.access&&!o.access.includes(s))&&(n[i.name]=await oe(i.custom.initialValue,[n]),gt(e,[o]).size===1&&(n[`${i.name}_Lowercase`]=n[i.name].toLowerCase()))}for(const i of r)s&&i.access&&!i.access.includes(s)||("autoIncrement"in i&&i.autoIncrement&&!n[i.name]&&(n[i.name]="Pending"),!X(i)&&i.nullable&&n[i.name]===void 0&&(n[i.name]=null))};var se;(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})(se||(se={}));var fr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(fr||(fr={}));const U=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xe=n=>{switch(typeof n){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN(n)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":return Array.isArray(n)?U.array:n===null?U.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?U.promise:typeof Map<"u"&&n instanceof Map?U.map:typeof Set<"u"&&n instanceof Set?U.set:typeof Date<"u"&&n instanceof Date?U.date:U.object;default:return U.unknown}},D=se.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 Ye 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 Ye))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.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()}}Ye.create=n=>new Ye(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,se.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:t=`Unrecognized key(s) in object: ${se.joinValues(n.keys,", ")}`;break;case D.invalid_union:t="Invalid input";break;case D.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${se.joinValues(n.options)}`;break;case D.invalid_enum_value:t=`Invalid enum value. Expected ${se.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}"`:se.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,se.assertNever(n)}return{message:t}};let aa=ys;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 M(n,e){const t=la(),s=ca({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 ve{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const r of t){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return ve.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return J;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const J=Object.freeze({status:"aborted"}),qt=n=>({status:"dirty",value:n}),Ce=n=>({status:"valid",value:n}),hr=n=>n.status==="aborted",mr=n=>n.status==="dirty",Nt=n=>n.status==="valid",Rn=n=>typeof Promise<"u"&&n instanceof Promise;var j;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(j||(j={}));class We{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const pr=(n,e)=>{if(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 Ye(n.common.issues);return this._error=t,this._error}}};function Q(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:r}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=n;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:r}}class ee{get description(){return this._def.description}_getType(e){return Xe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ve,ctx:{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Rn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},r=this._parseSync({data:e,path:s.path,parent:s});return pr(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return 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:Xe(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Rn(r)?r:Promise.resolve(r));return pr(s,i)}refine(e,t){const s=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:D.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof t=="function"?t(s,r):t),!1))}_refinement(e){return new Ct({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return st.create(this,this._def)}nullable(){return Ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ve.create(this)}promise(){return An.create(this,this._def)}or(e){return xn.create([this,e],this._def)}and(e){return Nn.create(this,e,this._def)}transform(e){return new Ct({...Q(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Os({...Q(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new Aa({typeName:Y.ZodBranded,type:this,...Q(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ks({...Q(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Us.create(this,e)}readonly(){return bs.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 es;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])$/,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])$/,Ea=/^(([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}(=)?))?$/,wi="((\\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(`^${wi}$`);function _i(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 Sa(n){return new RegExp(`^${_i(n)}$`)}function Ra(n){let e=`${wi}T${_i(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ia(n,e){return!!((e==="v4"||!e)&&_a.test(n)||(e==="v6"||!e)&&Ea.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 Na(n,e){return!!((e==="v4"||!e)&&va.test(n)||(e==="v6"||!e)&&Oa.test(n))}class Ge extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){const i=this._getOrReturnCtx(e);return M(i,{code:D.invalid_type,expected:U.string,received:i.parsedType}),J}const s=new ve;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),M(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),M(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?M(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&M(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),M(r,{validation:"email",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")es||(es=new RegExp(wa,"u")),es.test(e.data)||(r=this._getOrReturnCtx(e,r),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(r,{code:D.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ta.test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:D.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Sa(i).test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:D.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ya.test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{validation:"duration",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ia(e.data,i.version)||(r=this._getOrReturnCtx(e,r),M(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),M(r,{validation:"jwt",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Na(e.data,i.version)||(r=this._getOrReturnCtx(e,r),M(r,{validation:"cidr",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?ka.test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?ba.test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{validation:"base64url",code:D.invalid_string,message:i.message}),s.dirty()):se.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,...j.errToObj(s)})}_addCheck(e){return new Ge({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...j.errToObj(e)})}url(e){return this._addCheck({kind:"url",...j.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...j.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...j.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...j.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...j.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...j.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...j.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...j.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...j.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...j.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...j.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...j.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,...j.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,...j.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...j.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...j.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...j.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...j.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...j.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...j.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...j.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...j.errToObj(t)})}nonempty(e){return this.min(1,j.errToObj(e))}trim(){return new Ge({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ge({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ge({...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}}Ge.create=n=>new Ge({checks:[],typeName:Y.ZodString,coerce:n?.coerce??!1,...Q(n)});function Da(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=t>s?t:s,i=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Dt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==U.number){const i=this._getOrReturnCtx(e);return M(i,{code:D.invalid_type,expected:U.number,received:i.parsedType}),J}let s;const r=new ve;for(const i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),M(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),M(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),M(s,{code:D.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Da(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),M(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),M(s,{code:D.not_finite,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,s,r){return new Dt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:j.toString(r)}]})}_addCheck(e){return new Dt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:j.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:j.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.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"&&se.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Dt.create=n=>new Dt({checks:[],typeName:Y.ZodNumber,coerce:n?.coerce||!1,...Q(n)});class Xt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==U.bigint)return this._getInvalidInput(e);let s;const r=new ve;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),M(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),M(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),M(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return M(t,{code:D.invalid_type,expected:U.bigint,received:t.parsedType}),J}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,s,r){return new Xt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:j.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:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.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:Y.ZodBigInt,coerce:n?.coerce??!1,...Q(n)});class gs extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.boolean,received:s.parsedType}),J}return Ce(e.data)}}gs.create=n=>new gs({typeName:Y.ZodBoolean,coerce:n?.coerce||!1,...Q(n)});class In extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){const i=this._getOrReturnCtx(e);return M(i,{code:D.invalid_type,expected:U.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return M(i,{code:D.invalid_date}),J}const s=new ve;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),M(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),M(r,{code:D.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):se.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new In({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:j.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:j.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}}In.create=n=>new In({checks:[],coerce:n?.coerce||!1,typeName:Y.ZodDate,...Q(n)});class yr extends ee{_parse(e){if(this._getType(e)!==U.symbol){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.symbol,received:s.parsedType}),J}return Ce(e.data)}}yr.create=n=>new yr({typeName:Y.ZodSymbol,...Q(n)});class ws extends ee{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.undefined,received:s.parsedType}),J}return Ce(e.data)}}ws.create=n=>new ws({typeName:Y.ZodUndefined,...Q(n)});class gr extends ee{_parse(e){if(this._getType(e)!==U.null){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.null,received:s.parsedType}),J}return Ce(e.data)}}gr.create=n=>new gr({typeName:Y.ZodNull,...Q(n)});class _s extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return Ce(e.data)}}_s.create=n=>new _s({typeName:Y.ZodAny,...Q(n)});class wr extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ce(e.data)}}wr.create=n=>new wr({typeName:Y.ZodUnknown,...Q(n)});class ot extends ee{_parse(e){const t=this._getOrReturnCtx(e);return M(t,{code:D.invalid_type,expected:U.never,received:t.parsedType}),J}}ot.create=n=>new ot({typeName:Y.ZodNever,...Q(n)});class _r extends ee{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.void,received:s.parsedType}),J}return Ce(e.data)}}_r.create=n=>new _r({typeName:Y.ZodVoid,...Q(n)});class Ve extends ee{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==U.array)return M(t,{code:D.invalid_type,expected:U.array,received:t.parsedType}),J;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(M(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&&(M(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&&(M(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=>ve.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new We(t,o,t.path,a)));return ve.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new Ve({...this._def,minLength:{value:e,message:j.toString(t)}})}max(e,t){return new Ve({...this._def,maxLength:{value:e,message:j.toString(t)}})}length(e,t){return new Ve({...this._def,exactLength:{value:e,message:j.toString(t)}})}nonempty(e){return this.min(1,e)}}Ve.create=(n,e)=>new Ve({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...Q(e)});function bt(n){if(n instanceof ue){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=st.create(bt(s))}return new ue({...n._def,shape:()=>e})}else return n instanceof Ve?new Ve({...n._def,type:bt(n.element)}):n instanceof st?st.create(bt(n.unwrap())):n instanceof Ft?Ft.create(bt(n.unwrap())):n instanceof mt?mt.create(n.items.map(e=>bt(e))):n}class ue extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=se.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 M(c,{code:D.invalid_type,expected:U.object,received:c.parsedType}),J}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const u=i[c],h=r.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new We(r,h,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ot){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(c==="strict")a.length>0&&(M(r,{code:D.unrecognized_keys,keys:a}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const h=r.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new We(r,h,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,d=await u.value;c.push({key:h,value:d,alwaysSet:u.alwaysSet})}return c}).then(c=>ve.mergeObjectSync(s,c)):ve.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return j.errToObj,new ue({...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:j.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(e){return new ue({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ue({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ue({...this._def,catchall:e})}pick(e){const t={};for(const s of se.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new ue({...this._def,shape:()=>t})}omit(e){const t={};for(const s of se.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new ue({...this._def,shape:()=>t})}deepPartial(){return bt(this)}partial(e){const t={};for(const s of se.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new ue({...this._def,shape:()=>t})}required(e){const t={};for(const s of se.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof st;)i=i._def.innerType;t[s]=i}return new ue({...this._def,shape:()=>t})}keyof(){return vi(se.objectKeys(this.shape))}}ue.create=(n,e)=>new ue({shape:()=>n,unknownKeys:"strip",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});ue.strictCreate=(n,e)=>new ue({shape:()=>n,unknownKeys:"strict",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});ue.lazycreate=(n,e)=>new ue({shape:n,unknownKeys:"strip",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});class xn extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Ye(a.ctx.common.issues));return M(t,{code:D.invalid_union,unionErrors:o}),J}if(t.common.async)return Promise.all(s.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new Ye(l));return M(t,{code:D.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}xn.create=(n,e)=>new xn({options:n,typeName:Y.ZodUnion,...Q(e)});function vs(n,e){const t=Xe(n),s=Xe(e);if(n===e)return{valid:!0,data:n};if(t===U.object&&s===U.object){const r=se.objectKeys(e),i=se.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(const a of i){const l=vs(n[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===U.array&&s===U.array){if(n.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<n.length;i++){const o=n[i],a=e[i],l=vs(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return t===U.date&&s===U.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Nn extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(hr(i)||hr(o))return J;const a=vs(i.value,o.value);return a.valid?((mr(i)||mr(o))&&t.dirty(),{status:t.value,value:a.data}):(M(s,{code:D.invalid_intersection_types}),J)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Nn.create=(n,e,t)=>new Nn({left:n,right:e,typeName:Y.ZodIntersection,...Q(t)});class mt extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.array)return M(s,{code:D.invalid_type,expected:U.array,received:s.parsedType}),J;if(s.data.length<this._def.items.length)return M(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&s.data.length>this._def.items.length&&(M(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=>ve.mergeArray(t,o)):ve.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new mt({...this._def,rest:e})}}mt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:n,typeName:Y.ZodTuple,rest:null,...Q(e)})};class Dn extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.object)return M(s,{code:D.invalid_type,expected:U.object,received:s.parsedType}),J;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new We(s,a,s.path,a)),value:o._parse(new We(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?ve.mergeObjectAsync(t,r):ve.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof ee?new Dn({keyType:e,valueType:t,typeName:Y.ZodRecord,...Q(s)}):new Dn({keyType:Ge.create(),valueType:e,typeName:Y.ZodRecord,...Q(t)})}}class vr extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.map)return M(s,{code:D.invalid_type,expected:U.map,received:s.parsedType}),J;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,l],c)=>({key:r._parse(new We(s,a,s.path,[c,"key"])),value:i._parse(new We(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return J;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(c.value,u.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return J;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(c.value,u.value)}return{status:t.value,value:a}}}}vr.create=(n,e,t)=>new vr({valueType:e,keyType:n,typeName:Y.ZodMap,...Q(t)});class en extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.set)return M(s,{code:D.invalid_type,expected:U.set,received:s.parsedType}),J;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(M(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&&(M(s,{code:D.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const u of l){if(u.status==="aborted")return J;u.status==="dirty"&&t.dirty(),c.add(u.value)}return{status:t.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new We(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new en({...this._def,minSize:{value:e,message:j.toString(t)}})}max(e,t){return new en({...this._def,maxSize:{value:e,message:j.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:Y.ZodSet,...Q(e)});class Er extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Er.create=(n,e)=>new Er({getter:n,typeName:Y.ZodLazy,...Q(e)});class Es extends ee{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return M(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}Es.create=(n,e)=>new Es({value:n,typeName:Y.ZodLiteral,...Q(e)});function vi(n,e){return new At({values:n,typeName:Y.ZodEnum,...Q(e)})}class At extends ee{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return M(t,{expected:se.joinValues(s),received:t.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return M(t,{received:t.data,code:D.invalid_enum_value,options:s}),J}return Ce(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return At.create(e,{...this._def,...t})}exclude(e,t=this._def){return At.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}At.create=vi;class Or extends ee{_parse(e){const t=se.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==U.string&&s.parsedType!==U.number){const r=se.objectValues(t);return M(s,{expected:se.joinValues(r),received:s.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=se.objectValues(t);return M(s,{received:s.data,code:D.invalid_enum_value,options:r}),J}return Ce(e.data)}get enum(){return this._def.values}}Or.create=(n,e)=>new Or({values:n,typeName:Y.ZodNativeEnum,...Q(e)});class An extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.promise&&t.common.async===!1)return M(t,{code:D.invalid_type,expected:U.promise,received:t.parsedType}),J;const s=t.parsedType===U.promise?t.data:Promise.resolve(t.data);return Ce(s.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}An.create=(n,e)=>new An({type:n,typeName:Y.ZodPromise,...Q(e)});class Ct extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{M(s,o),o.fatal?t.abort():t.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return J;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?J:l.status==="dirty"||t.value==="dirty"?qt(l.value):l});{if(t.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?J:a.status==="dirty"||t.value==="dirty"?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"?J:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Nt(o))return J;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Nt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):J);se.assertNever(r)}}Ct.create=(n,e,t)=>new Ct({schema:n,typeName:Y.ZodEffects,effect:e,...Q(t)});Ct.createWithPreprocess=(n,e,t)=>new Ct({schema:e,effect:{type:"preprocess",transform:n},typeName:Y.ZodEffects,...Q(t)});class st extends ee{_parse(e){return this._getType(e)===U.undefined?Ce(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}st.create=(n,e)=>new st({innerType:n,typeName:Y.ZodOptional,...Q(e)});class Ft extends ee{_parse(e){return this._getType(e)===U.null?Ce(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ft.create=(n,e)=>new Ft({innerType:n,typeName:Y.ZodNullable,...Q(e)});class Os extends ee{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===U.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Os.create=(n,e)=>new Os({innerType:n,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});class ks extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Rn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ye(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Ye(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}ks.create=(n,e)=>new ks({innerType:n,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});class kr extends ee{_parse(e){if(this._getType(e)!==U.nan){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.nan,received:s.parsedType}),J}return{status:"valid",value:e.data}}}kr.create=n=>new kr({typeName:Y.ZodNaN,...Q(n)});class Aa extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Us extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?J:i.status==="dirty"?(t.dirty(),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"?J:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,t){return new Us({in:e,out:t,typeName:Y.ZodPipeline})}}class bs extends ee{_parse(e){const t=this._def.innerType._parse(e),s=r=>(Nt(r)&&(r.value=Object.freeze(r.value)),r);return Rn(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}bs.create=(n,e)=>new bs({innerType:n,typeName:Y.ZodReadonly,...Q(e)});var Y;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Y||(Y={}));const ke=Ge.create,dt=Dt.create,Qt=gs.create,ts=ws.create,me=_s.create;ot.create;const wt=Ve.create,Ue=ue.create,Ee=xn.create;Nn.create;mt.create;const sn=Dn.create,Oe=Es.create,Cn=At.create;An.create;st.create;Ft.create;const gn=()=>me().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),br=()=>me().refine(n=>n&&(n._methodName==="serverTimestamp"||n.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),Ei=(n,e,t)=>{const s={};if(n.includeFields){const i=e.collections[n.collection];if(!i)return sn(me());n.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${n.collection}`);s[o]=Fn(i,a),gt(i,[a]).size===1&&(s[`${o}_Lowercase`]=Fn(i,a,!0))})}const r={Collection_Path:wt(ke()),...s};return t&&(r.id=ke().length(20)),Ue(r)},Ca=(n,e)=>{let t=sn(Ei(n,e));return n.required||(t=t.optional()),t},Fa=n=>{let e=wt(Ee([ke().length(20),ke().length(28)]));return["OneToOne","OneToMany"].includes(n.type)?e=e.max(1):(n.min&&(e=e.min(n.min)),n.max&&(e=e.max(n.max)),n.length&&(e=e.length(n.length))),n.required?e=e.nonempty():e=e.optional(),e},Fn=(n,e,t)=>{const{softDelete:s}=n,r=s?.timestampField;let i;switch(e.type){case"String":if(i=ke(),e.length&&(i=i.length(e.length)),e.minlength&&(i=i.min(e.minlength)),e.maxlength&&(i=i.max(e.maxlength)),e.email&&(i=i.email()),e.uuid&&(i=i.uuid()),e.url&&(i=i.url()),e.emoji&&(i=i.emoji()),e.ip&&(i=i.ip()),e.pattern&&(i=i.regex(new RegExp(e.pattern))),t&&(i=i.toLowerCase()),e.values)if(t){const o=e.values.map(a=>a.toLowerCase());i=Cn(o)}else i=Cn(e.values);break;case"Boolean":i=Qt();break;case"Number":e.autoIncrement?i=Ee([Oe("Pending"),dt().int()]):(i=dt(),e.min&&(i=i.min(e.min)),e.max&&(i=i.max(e.max)),e.decimal?i=i.refine(o=>e.decimal?(o.toString().split(".")[1]?.length||0)<=e.decimal:!1,{message:`Value must have ${e.decimal} or fewer decimal places`}):i=i.int(),e.values&&(i=i.refine(o=>e.values?.includes(o),{message:"Value is not an allowed value"})));break;case"Timestamp":e.name===r?i=me().refine(o=>o&&(o._methodName==="serverTimestamp"||o.constructor.name==="ServerTimestampTransform"||o.seconds!==void 0&&o.nanoseconds!==void 0||o._seconds!==void 0&&o._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}):(i=gn(),e.min&&(i=i.refine(o=>o.toMillis()>=e.min,{message:`Value is less than the minimum allowed value of ${e.min}`})),e.max&&(i=i.refine(o=>o.toMillis()<=e.max,{message:`Value is greater than the maximum allowed value of ${e.max}`})));break;case"Array":i=wt(me()),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(me()),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=me();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},Oi=(n,e,t)=>{const s={Collection_Path:wt(ke()),Last_Write_App:ke(),Last_Write_At:gn(),Last_Save_At:br(),Last_Write_By:Ee([ke().length(28),Oe("System")]),Last_Write_Connection_Status:Cn(["Online","Offline"]),Last_Write_Version:dt().int(),id:ke().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:gn(),Created_By:Ee([ke().length(28),Oe("System")])};n==="create"&&(s.Saved_At=br()),n==="update"&&(s.Saved_At=gn(),s.Collection_Path=s.Collection_Path.optional(),s.id=s.id.optional(),s.Created_At=s.Created_At.optional(),s.Saved_At=s.Saved_At.optional(),s.Created_By=s.Created_By.optional());const r=ut(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{X(l)?(s[l.name]=Ca(l,t),s[`${l.name}_Array`]=Fa(l),i.includes(l.name)&&(s[`${l.name}_Single`]=Ei(l,t,!0),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=Fn(e,l))}),gt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=Fn(e,l,!0))});const a=Ue(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class _t extends Error{}class $a extends _t{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Ma extends _t{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class Pa extends _t{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Tt extends _t{}class ki extends _t{constructor(e){super(`Invalid unit ${e}`)}}class pe extends _t{}class Ke extends _t{constructor(){super("Zone is an abstract class")}}const F="numeric",Pe="short",Te="long",$n={year:F,month:F,day:F},bi={year:F,month:Pe,day:F},La={year:F,month:Pe,day:F,weekday:Pe},Ti={year:F,month:Te,day:F},Si={year:F,month:Te,day:F,weekday:Te},Ri={hour:F,minute:F},Ii={hour:F,minute:F,second:F},xi={hour:F,minute:F,second:F,timeZoneName:Pe},Ni={hour:F,minute:F,second:F,timeZoneName:Te},Di={hour:F,minute:F,hourCycle:"h23"},Ai={hour:F,minute:F,second:F,hourCycle:"h23"},Ci={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:Pe},Fi={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:Te},$i={year:F,month:F,day:F,hour:F,minute:F},Mi={year:F,month:F,day:F,hour:F,minute:F,second:F},Pi={year:F,month:Pe,day:F,hour:F,minute:F},Li={year:F,month:Pe,day:F,hour:F,minute:F,second:F},Va={year:F,month:Pe,day:F,weekday:Pe,hour:F,minute:F},Vi={year:F,month:Te,day:F,hour:F,minute:F,timeZoneName:Pe},Ui={year:F,month:Te,day:F,hour:F,minute:F,second:F,timeZoneName:Pe},Wi={year:F,month:Te,day:F,weekday:Te,hour:F,minute:F,timeZoneName:Te},ji={year:F,month:Te,day:F,weekday:Te,hour:F,minute:F,second:F,timeZoneName:Te};class rn{get type(){throw new Ke}get name(){throw new Ke}get ianaName(){return this.name}get isUniversal(){throw new Ke}offsetName(e,t){throw new Ke}formatOffset(e,t){throw new Ke}offset(e){throw new Ke}equals(e){throw new Ke}get isValid(){throw new Ke}}let ns=null;class Zn extends rn{static get instance(){return ns===null&&(ns=new Zn),ns}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Xi(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 Ts=new Map;function Ua(n){let e=Ts.get(n);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Ts.set(n,e)),e}const 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,u]=s;return[o,r,i,a,l,c,u]}function za(n,e){const t=n.formatToParts(e),s=[];for(let r=0;r<t.length;r++){const{type:i,value:o}=t[r],a=Wa[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const ss=new Map;class Je extends rn{static create(e){let t=ss.get(e);return t===void 0&&ss.set(e,t=new Je(e)),t}static resetCache(){ss.clear(),Ts.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=Je.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Xi(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=Ua(this.name);let[r,i,o,a,l,c,u]=s.formatToParts?za(s,t):ja(s,t);a==="BC"&&(r=-Math.abs(r)+1);const d=Bn({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:u,millisecond:0});let f=+t;const p=f%1e3;return f-=p>=0?p:1e3+p,(d-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Tr={};function Za(n,e={}){const t=JSON.stringify([n,e]);let s=Tr[t];return s||(s=new Intl.ListFormat(n,e),Tr[t]=s),s}const Ss=new Map;function Rs(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 Is=new Map;function qa(n,e={}){const t=JSON.stringify([n,e]);let s=Is.get(t);return s===void 0&&(s=new Intl.NumberFormat(n,e),Is.set(t,s)),s}const xs=new Map;function Ba(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 Ha(){return Bt||(Bt=new Intl.DateTimeFormat().resolvedOptions().locale,Bt)}const Ns=new Map;function zi(n){let e=Ns.get(n);return e===void 0&&(e=new Intl.DateTimeFormat(n).resolvedOptions(),Ns.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={...Zi,...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=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 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=V.utc(2009,t,1);e.push(n(s))}return e}function Ka(n){const e=[];for(let t=1;t<=7;t++){const s=V.utc(2016,11,13+t);e.push(n(s))}return e}function dn(n,e,t,s){const r=n.listingMode();return r==="error"?null:r==="en"?t(e):s(e)}function Xa(n){return n.numberingSystem&&n.numberingSystem!=="latn"?!1:n.numberingSystem==="latn"||!n.locale||n.locale.startsWith("en")||zi(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):qs(e,3);return de(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&&Je.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 nl{constructor(e,t,s){this.opts={style:"long",...s},!t&&Qi()&&(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 Zi={firstDay:1,minimalDays:4,weekend:[6,7]};class ie{static fromOpts(e){return ie.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,u=Cs(r)||ce.defaultWeekSettings;return new ie(a,l,c,u,o)}static resetCache(){Bt=null,Ss.clear(),Is.clear(),xs.clear(),Ns.clear(),Ds.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:r}={}){return ie.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:ie.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 dn(this,e,no,()=>{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 dn(this,e,io,()=>{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 dn(this,void 0,()=>oo,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[V.utc(2016,11,13,9),V.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return dn(this,e,ao,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[V.utc(-40,1,1),V.utc(2017,1,1)].map(s=>this.extract(s,t,"era"))),this.eraCache[e]})}extract(e,t,s){const r=this.dtFormatter(e,t),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new 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"||zi(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Ki()?Ga(this.locale):Zi}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 _e extends rn{static get utcInstance(){return rs===null&&(rs=new _e(0)),rs}static instance(e){return e===0?_e.utcInstance:new _e(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new _e(Hn(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${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 sl 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 tt(n,e){if(G(n)||n===null)return e;if(n instanceof rn)return n;if(cl(n)){const t=n.toLowerCase();return t==="default"?e:t==="local"||t==="system"?Zn.instance:t==="utc"||t==="gmt"?_e.utcInstance:_e.parseSpecifier(t)||Je.create(n)}else return rt(n)?_e.instance(n):typeof n=="object"&&"offset"in n&&typeof n.offset=="function"?n:new sl(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]},rl=Ws.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(Ws.hanidec)!==-1)e+=rl.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 ol(){As.clear()}function Fe({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 Rr=()=>Date.now(),Ir="system",xr=null,Nr=null,Dr=null,Ar=60,Cr,Fr=null;class ce{static get now(){return Rr}static set now(e){Rr=e}static set defaultZone(e){Ir=e}static get defaultZone(){return tt(Ir,Zn.instance)}static get defaultLocale(){return xr}static set defaultLocale(e){xr=e}static get defaultNumberingSystem(){return Nr}static set defaultNumberingSystem(e){Nr=e}static get defaultOutputCalendar(){return Dr}static set defaultOutputCalendar(e){Dr=e}static get defaultWeekSettings(){return Fr}static set defaultWeekSettings(e){Fr=Cs(e)}static get twoDigitCutoffYear(){return Ar}static set twoDigitCutoffYear(e){Ar=e%100}static get throwOnInvalid(){return Cr}static set throwOnInvalid(e){Cr=e}static resetCaches(){ie.resetCache(),Je.resetCache(),V.resetCache(),ol()}}class Me{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const qi=[0,31,59,90,120,151,181,212,243,273,304,334],Bi=[0,31,60,91,121,152,182,213,244,274,305,335];function Ne(n,e){return new Me("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 Hi(n,e,t){return t+(on(n)?Bi:qi)[e-1]}function Gi(n,e){const t=on(n)?Bi:qi,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 Mn(n,e=4,t=1){const{year:s,month:r,day:i}=n,o=Hi(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,...Gn(n)}}function $r(n,e=4,t=1){const{weekYear:s,weekNumber:r,weekday:i}=n,o=zs(js(s,1,e),t),a=It(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=It(c)):l>a?(c=s+1,l-=It(s)):c=s;const{month:u,day:h}=Gi(c,l);return{year:c,month:u,day:h,...Gn(n)}}function is(n){const{year:e,month:t,day:s}=n,r=Hi(e,t,s);return{year:e,ordinal:r,...Gn(n)}}function Mr(n){const{year:e,ordinal:t}=n,{month:s,day:r}=Gi(e,t);return{year:e,month:s,day:r,...Gn(n)}}function Pr(n,e){if(!G(n.localWeekday)||!G(n.localWeekNumber)||!G(n.localWeekYear)){if(!G(n.weekday)||!G(n.weekNumber)||!G(n.weekYear))throw new Tt("Cannot mix locale-based week fields with ISO-based week fields");return G(n.localWeekday)||(n.weekday=n.localWeekday),G(n.localWeekNumber)||(n.weekNumber=n.localWeekNumber),G(n.localWeekYear)||(n.weekYear=n.localWeekYear),delete n.localWeekday,delete n.localWeekNumber,delete n.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function al(n,e=4,t=1){const s=qn(n.weekYear),r=De(n.weekNumber,1,tn(n.weekYear,e,t)),i=De(n.weekday,1,7);return s?r?i?!1:Ne("weekday",n.weekday):Ne("week",n.weekNumber):Ne("weekYear",n.weekYear)}function ll(n){const e=qn(n.year),t=De(n.ordinal,1,It(n.year));return e?t?!1:Ne("ordinal",n.ordinal):Ne("year",n.year)}function Yi(n){const e=qn(n.year),t=De(n.month,1,12),s=De(n.day,1,Pn(n.year,n.month));return e?t?s?!1:Ne("day",n.day):Ne("month",n.month):Ne("year",n.year)}function Ji(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:Ne("millisecond",r):Ne("second",s):Ne("minute",t):Ne("hour",e)}function G(n){return typeof n>"u"}function rt(n){return typeof n=="number"}function qn(n){return typeof n=="number"&&n%1===0}function cl(n){return typeof n=="string"}function ul(n){return Object.prototype.toString.call(n)==="[object Date]"}function Qi(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ki(){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 Lr(n,e,t){if(n.length!==0)return n.reduce((s,r)=>{const i=[e(r),r];return s&&t(s[0],i[0])===s[0]?s:i},null)[1]}function fl(n,e){return e.reduce((t,s)=>(t[s]=n[s],t),{})}function $t(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Cs(n){if(n==null)return null;if(typeof n!="object")throw new pe("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 pe("Invalid week settings");return{firstDay:n.firstDay,minimalDays:n.minimalDays,weekend:Array.from(n.weekend)}}function De(n,e,t){return qn(n)&&n>=e&&n<=t}function hl(n,e){return n-e*Math.floor(n/e)}function de(n,e=2){const t=n<0;let s;return t?s="-"+(""+-n).padStart(e,"0"):s=(""+n).padStart(e,"0"),s}function et(n){if(!(G(n)||n===null||n===""))return parseInt(n,10)}function lt(n){if(!(G(n)||n===null||n===""))return parseFloat(n)}function Zs(n){if(!(G(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 It(n){return on(n)?366:365}function Pn(n,e){const t=hl(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 Bn(n){let e=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return n.year<100&&n.year>=0&&(e=new Date(e),e.setUTCFullYear(n.year,n.month-1,n.day)),+e}function Vr(n,e,t){return-zs(js(n,1,e),t)+e-1}function tn(n,e=4,t=1){const s=Vr(n,e,t),r=Vr(n+1,e,t);return(It(n)-s+r)/7}function Fs(n){return n>99?n:n>ce.twoDigitCutoffYear?1900+n:2e3+n}function Xi(n,e,t,s=null){const r=new Date(n),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(t,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function Hn(n,e){let t=parseInt(n,10);Number.isNaN(t)&&(t=0);const s=parseInt(e,10)||0,r=t<0||Object.is(t,-0)?-s:s;return t*60+r}function eo(n){const e=Number(n);if(typeof n=="boolean"||n===""||!Number.isFinite(e))throw new pe(`Invalid unit value ${n}`);return e}function Ln(n,e){const t={};for(const s in n)if($t(n,s)){const r=n[s];if(r==null)continue;t[e(s)]=eo(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}${de(t,2)}:${de(s,2)}`;case"narrow":return`${r}${t}${s>0?`:${s}`:""}`;case"techie":return`${r}${de(t,2)}${de(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Gn(n){return fl(n,["hour","minute","second","millisecond"])}const ml=["January","February","March","April","May","June","July","August","September","October","November","December"],to=["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 no(n){switch(n){case"narrow":return[...pl];case"short":return[...to];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 so=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],ro=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],yl=["M","T","W","T","F","S","S"];function io(n){switch(n){case"narrow":return[...yl];case"short":return[...ro];case"long":return[...so];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const oo=["AM","PM"],gl=["Before Christ","Anno Domini"],wl=["BC","AD"],_l=["B","A"];function ao(n){switch(n){case"narrow":return[..._l];case"short":return[...wl];case"long":return[...gl];default:return null}}function vl(n){return oo[n.hour<12?0:1]}function El(n,e){return io(e)[n.weekday-1]}function Ol(n,e){return no(e)[n.month-1]}function kl(n,e){return ao(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],u=s?l?c[1]:c[2]||c[1]:l?r[n][0]:n;return o?`${a} ${u} ago`:`in ${a} ${u}`}function Ur(n,e){let t="";for(const s of n)s.literal?t+=s.val:t+=e(s.val);return t}const Tl={D:$n,DD:bi,DDD:Ti,DDDD:Si,t:Ri,tt:Ii,ttt:xi,tttt:Ni,T:Di,TT:Ai,TTT:Ci,TTTT:Fi,f:$i,ff:Pi,fff:Vi,ffff:Wi,F:Mi,FF:Li,FFF:Ui,FFFF:ji};class ye{static create(e,t={}){return new ye(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 de(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,p)=>this.loc.extract(e,f,p),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,p)=>s?Ol(e,f):i(p?{month:f}:{month:f,day:"numeric"},"month"),c=(f,p)=>s?El(e,f):i(p?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),u=f=>{const p=ye.macroTokenToFormatOpts(f);return p?this.formatWithSystemDefault(e,p):f},h=f=>s?kl(e,f):i({era:f},"era"),d=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 u(f)}};return Ur(ye.parseFormat(t),d)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=u=>{switch(u[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(u,h)=>d=>{const f=r(d);if(f){const p=h.isNegativeDuration&&f!==h.largestUnit?s:1;let O;return this.opts.signMode==="negativeLargestOnly"&&f!==h.largestUnit?O="never":this.opts.signMode==="all"?O="always":O="auto",this.num(u.get(f)*p,d.length,O)}else return d},o=ye.parseFormat(t),a=o.reduce((u,{literal:h,val:d})=>h?u:u.concat(d),[]),l=e.shiftTo(...a.map(r).filter(u=>u)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Ur(o,i(l,c))}}const lo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Mt(...n){const e=n.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function Pt(...n){return e=>n.reduce(([t,s,r],i)=>{const[o,a,l]=i(e,r);return[{...t,...o},a||s,l]},[{},null,1]).slice(0,2)}function Lt(n,...e){if(n==null)return[null,null];for(const[t,s]of e){const r=t.exec(n);if(r)return s(r)}return[null,null]}function co(...n){return(e,t)=>{const s={};let r;for(r=0;r<n.length;r++)s[n[r]]=et(e[t+r]);return[s,null,t+r]}}const uo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Sl=`(?:${uo.source}?(?:\\[(${lo.source})\\])?)?`,Bs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,fo=RegExp(`${Bs.source}${Sl}`),Hs=RegExp(`(?:[Tt]${fo.source})?`),Rl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Il=/(\d{4})-?W(\d\d)(?:-?(\d))?/,xl=/(\d{4})-?(\d{3})/,Nl=co("weekYear","weekNumber","weekDay"),Dl=co("year","ordinal"),Al=/(\d{4})-(\d\d)-(\d\d)/,ho=RegExp(`${Bs.source} ?(?:${uo.source}|(${lo.source}))?`),Cl=RegExp(`(?: ${ho.source})?`);function xt(n,e,t){const s=n[e];return G(s)?t:et(s)}function Fl(n,e){return[{year:xt(n,e),month:xt(n,e+1,1),day:xt(n,e+2,1)},null,e+3]}function Vt(n,e){return[{hours:xt(n,e,0),minutes:xt(n,e+1,0),seconds:xt(n,e+2,0),milliseconds:Zs(n[e+3])},null,e+4]}function an(n,e){const t=!n[e]&&!n[e+1],s=Hn(n[e+1],n[e+2]),r=t?null:_e.instance(s);return[{},r,e+3]}function ln(n,e){const t=n[e]?Je.create(n[e]):null;return[{},t,e+1]}const $l=RegExp(`^T?${Bs.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,u=e[0]==="-",h=l&&l[0]==="-",d=(f,p=!1)=>f!==void 0&&(p||f&&u)?-f:f;return[{years:d(lt(t)),months:d(lt(s)),weeks:d(lt(r)),days:d(lt(i)),hours:d(lt(o)),minutes:d(lt(a)),seconds:d(lt(l),l==="-0"),milliseconds:d(Zs(c),h)}]}const Ll={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(et(e)):et(e),month:to.indexOf(t)+1,day:et(s),hour:et(r),minute:et(i)};return o&&(a.second=et(o)),n&&(a.weekday=n.length>3?so.indexOf(n)+1:ro.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,u,h]=n,d=Gs(e,r,s,t,i,o,a);let f;return l?f=Ll[l]:c?f=0:f=Hn(u,h),[d,new _e(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 Wr(n){const[,e,t,s,r,i,o,a]=n;return[Gs(e,r,s,t,i,o,a),_e.utcInstance]}function ql(n){const[,e,t,s,r,i,o,a]=n;return[Gs(e,a,t,s,r,i,o),_e.utcInstance]}const Bl=Mt(Rl,Hs),Hl=Mt(Il,Hs),Gl=Mt(xl,Hs),Yl=Mt(fo),mo=Pt(Fl,Vt,an,ln),Jl=Pt(Nl,Vt,an,ln),Ql=Pt(Dl,Vt,an,ln),Kl=Pt(Vt,an,ln);function Xl(n){return Lt(n,[Bl,mo],[Hl,Jl],[Gl,Ql],[Yl,Kl])}function ec(n){return Lt(Wl(n),[Vl,Ul])}function tc(n){return Lt(n,[jl,Wr],[zl,Wr],[Zl,ql])}function nc(n){return Lt(n,[Ml,Pl])}const sc=Pt(Vt);function rc(n){return Lt(n,[$l,sc])}const ic=Mt(Al,Cl),oc=Mt(ho),ac=Pt(Vt,an,ln);function lc(n){return Lt(n,[ic,mo],[oc,ac])}const jr="Invalid Duration",po={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},...po},Ie=146097/400,Et=146097/4800,uc={years:{quarters:4,months:12,weeks:Ie/7,days:Ie,hours:Ie*24,minutes:Ie*24*60,seconds:Ie*24*60*60,milliseconds:Ie*24*60*60*1e3},quarters:{months:3,weeks:Ie/28,days:Ie/4,hours:Ie*24/4,minutes:Ie*24*60/4,seconds:Ie*24*60*60/4,milliseconds:Ie*24*60*60*1e3/4},months:{weeks:Et/7,days:Et,hours:Et*24,minutes:Et*24*60,seconds:Et*24*60*60,milliseconds:Et*24*60*60*1e3},...po},ft=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],dc=ft.slice(0).reverse();function Be(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 ne(s)}function yo(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 zr(n,e){const t=yo(n,e)<0?-1:1;ft.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*t,o=n[r][s],a=Math.floor(i/o);e[r]+=a*t,e[s]-=a*o*t}return r},null),ft.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*n[s][r]}return r},null)}function Zr(n){const e={};for(const[t,s]of Object.entries(n))s!==0&&(e[t]=s);return e}class ne{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||ie.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return ne.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new pe(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ne({values:Ln(e,ne.normalizeUnit),loc:ie.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(rt(e))return ne.fromMillis(e);if(ne.isDuration(e))return e;if(typeof e=="object")return ne.fromObject(e);throw new pe(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=nc(e);return s?ne.fromObject(s,t):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=rc(e);return s?ne.fromObject(s,t):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new pe("need to specify a reason the Duration is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new Pa(s);return new ne({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 ki(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?ye.create(this.loc,s).formatDurationFromString(this,e):jr}toHuman(e={}){if(!this.isValid)return jr;const t=e.showZeros!==!1,s=ft.map(r=>{const i=this.values[r];return G(i)||i===0&&!t?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=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},V.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?yo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e),s={};for(const r of ft)($t(t.values,r)||$t(this.values,r))&&(s[r]=t.get(r)+this.get(r));return Be(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const t=ne.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]=eo(e(this.values[s],s));return Be(this,{values:t},!0)}get(e){return this[ne.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...Ln(e,ne.normalizeUnit)};return Be(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 Be(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return zr(this.matrix,e),Be(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=Zr(this.normalize().shiftToAll().toObject());return Be(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>ne.normalizeUnit(o));const t={},s={},r=this.toObject();let i;for(const o of ft)if(e.indexOf(o)>=0){i=o;let a=0;for(const c in s)a+=this.matrix[c][o]*s[c],s[c]=0;rt(r[o])&&(a+=r[o]);const l=Math.trunc(a);t[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else rt(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(t[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return zr(this.matrix,t),Be(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 Be(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=Zr(this.values);return Be(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of ft)if(!t(this.values[s],e.values[s]))return!1;return!0}}const Ot="Invalid Interval";function 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 pe("need to specify a reason the Interval is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new Ma(s);return new le({invalid:s})}static fromDateTimes(e,t){const s=zt(e),r=zt(t),i=fc(s,r);return i??new le({start:s,end:r})}static after(e,t){const s=ne.fromDurationLike(t),r=zt(e);return le.fromDateTimes(r,r.plus(s))}static before(e,t){const s=ne.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=V.fromISO(s,t),o=i.isValid}catch{o=!1}let a,l;try{a=V.fromISO(r,t),l=a.isValid}catch{l=!1}if(o&&l)return le.fromDateTimes(i,a);if(o){const c=ne.fromISO(r,t);if(c.isValid)return le.after(i,c)}else if(l){const c=ne.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=ne.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()})`:Ot}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=$n,t={}){return this.isValid?ye.create(this.s.loc.clone(t),e).formatInterval(this):Ot}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Ot}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Ot}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Ot}toFormat(e,{separator:t=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Ot}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):ne.invalid(this.invalidReason)}mapEndpoints(e){return le.fromDateTimes(e(this.s),e(this.e))}}class fn{static hasDST(e=ce.defaultZone){const t=V.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return Je.isValidZone(e)}static normalizeZone(e){return tt(e,ce.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ie.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return ie.create(t,null,"gregory").eras(e)}static features(){return{relative:Qi(),localeWeek:Ki()}}}function qr(n,e){const t=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(n);return Math.floor(ne.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 u=qr(l,c);return(u-u%7)/7}],["days",qr]],r={},i=n;let o,a;for(const[l,c]of s)t.indexOf(l)>=0&&(o=l,r[l]=c(n,e),a=i.plus(r),a>e?(r[l]--,n=i.plus(r),n>e&&(a=n,r[l]--,n=i.plus(r))):n=a);return[n,r,a,o]}function 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 u=ne.fromObject(i,s);return c.length>0?ne.fromMillis(l,s).shiftTo(...c).plus(u):u}const pc="missing Intl.DateTimeFormat.formatToParts support";function re(n,e=t=>t){return{regex:n,deser:([t])=>e(il(t))}}const yc=" ",go=`[ ${yc}]`,wo=new RegExp(go,"g");function gc(n){return n.replace(/\./g,"\\.?").replace(wo,go)}function Br(n){return n.replace(/\./g,"").replace(wo," ").toLowerCase()}function $e(n,e){return n===null?null:{regex:RegExp(n.map(gc).join("|")),deser:([t])=>n.findIndex(s=>Br(t)===Br(s))+e}}function Hr(n,e){return{regex:n,deser:([,t,s])=>Hn(t,s),groups:e}}function hn(n){return{regex:n,deser:([e])=>e}}function wc(n){return n.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _c(n,e){const t=Fe(e),s=Fe(e,"{2}"),r=Fe(e,"{3}"),i=Fe(e,"{4}"),o=Fe(e,"{6}"),a=Fe(e,"{1,2}"),l=Fe(e,"{1,3}"),c=Fe(e,"{1,6}"),u=Fe(e,"{1,9}"),h=Fe(e,"{2,4}"),d=Fe(e,"{4,6}"),f=y=>({regex:RegExp(wc(y.val)),deser:([g])=>g,literal:!0}),O=(y=>{if(n.literal)return f(y);switch(y.val){case"G":return $e(e.eras("short"),0);case"GG":return $e(e.eras("long"),0);case"y":return re(c);case"yy":return re(h,Fs);case"yyyy":return re(i);case"yyyyy":return re(d);case"yyyyyy":return re(o);case"M":return re(a);case"MM":return re(s);case"MMM":return $e(e.months("short",!0),1);case"MMMM":return $e(e.months("long",!0),1);case"L":return re(a);case"LL":return re(s);case"LLL":return $e(e.months("short",!1),1);case"LLLL":return $e(e.months("long",!1),1);case"d":return re(a);case"dd":return re(s);case"o":return re(l);case"ooo":return re(r);case"HH":return re(s);case"H":return re(a);case"hh":return re(s);case"h":return re(a);case"mm":return re(s);case"m":return re(a);case"q":return re(a);case"qq":return re(s);case"s":return re(a);case"ss":return re(s);case"S":return re(l);case"SSS":return re(r);case"u":return hn(u);case"uu":return hn(a);case"uuu":return re(t);case"a":return $e(e.meridiems(),0);case"kkkk":return re(i);case"kk":return re(h,Fs);case"W":return re(a);case"WW":return re(s);case"E":case"c":return re(t);case"EEE":return $e(e.weekdays("short",!1),1);case"EEEE":return $e(e.weekdays("long",!1),1);case"ccc":return $e(e.weekdays("short",!0),1);case"cccc":return $e(e.weekdays("long",!0),1);case"Z":case"ZZ":return Hr(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return Hr(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return hn(/[a-z_+-/]{1,256}?/i);case" ":return hn(/[^\S\n\r]/);default:return f(y)}})(n)||{invalidReason:pc};return O.token=n,O}const vc={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Ec(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 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($t(t,o)){const a=t[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function 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 G(n.z)||(t=Je.create(n.z)),G(n.Z)||(t||(t=new _e(n.Z)),s=n.Z),G(n.q)||(n.M=(n.q-1)*3+1),G(n.h)||(n.h<12&&n.a===1?n.h+=12:n.h===12&&n.a===0&&(n.h=0)),n.G===0&&n.y&&(n.y=-n.y),G(n.u)||(n.S=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=V.fromMillis(1555555555555)),os}function Sc(n,e){if(n.literal)return n;const t=ye.macroTokenToFormatOpts(n.val),s=Oo(t,e);return s==null||s.includes(void 0)?n:s}function _o(n,e){return Array.prototype.concat(...n.map(t=>Sc(t,e)))}class vo{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=_o(ye.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($t(s,"a")&&$t(s,"H"))throw new Tt("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 Eo(n,e,t){return new vo(n,t).explainFromTokens(e)}function Rc(n,e,t){const{result:s,zone:r,specificOffset:i,invalidReason:o}=Eo(n,e,t);return[s,r,i,o]}function Oo(n,e){if(!n)return null;const s=ye.create(e,n).dtFormatter(Tc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Ec(o,n,i))}const as="Invalid DateTime",Gr=864e13;function Ht(n){return new Me("unsupported zone",`the zone "${n.name}" is not supported`)}function ls(n){return n.weekData===null&&(n.weekData=Mn(n.c)),n.weekData}function cs(n){return n.localWeekData===null&&(n.localWeekData=Mn(n.c,n.loc.getMinDaysInFirstWeek(),n.loc.getStartOfWeek())),n.localWeekData}function ct(n,e){const t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new V({...t,...e,old:t})}function ko(n,e,t){let s=n-e*60*1e3;const r=t.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=t.offset(s);return r===i?[s,r]:[n-Math.min(r,i)*60*1e3,Math.max(r,i)]}function mn(n,e){n+=e*60*1e3;const t=new Date(n);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function wn(n,e,t){return ko(Bn(n),e,t)}function Yr(n,e){const t=n.o,s=n.c.year+Math.trunc(e.years),r=n.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...n.c,year:s,month:r,day:Math.min(n.c.day,Pn(s,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ne.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=Bn(i);let[l,c]=ko(a,t,n.zone);return o!==0&&(l+=o,c=n.zone.offset(l)),{ts:l,o:c}}function kt(n,e,t,s,r,i){const{setZone:o,zone:a}=t;if(n&&Object.keys(n).length!==0||e){const l=e||a,c=V.fromObject(n,{...t,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return V.invalid(new Me("unparsable",`the input "${r}" can't be parsed as ${s}`))}function pn(n,e,t=!0){return n.isValid?ye.create(ie.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+=de(n.c.year,s?6:4),t==="year")return r;if(e){if(r+="-",r+=de(n.c.month),t==="month")return r;r+="-"}else if(r+=de(n.c.month),t==="month")return r;return r+=de(n.c.day),r}function Jr(n,e,t,s,r,i,o){let a=!t||n.c.millisecond!==0||n.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=de(n.c.hour),o==="hour")break;if(e){if(l+=":",l+=de(n.c.minute),o==="minute")break;a&&(l+=":",l+=de(n.c.second))}else{if(l+=de(n.c.minute),o==="minute")break;a&&(l+=de(n.c.second))}if(o==="second")break;a&&(!s||n.c.millisecond!==0)&&(l+=".",l+=de(n.c.millisecond,3))}return r&&(n.isOffsetFixed&&n.offset===0&&!i?l+="Z":n.o<0?(l+="-",l+=de(Math.trunc(-n.o/60)),l+=":",l+=de(Math.trunc(-n.o%60))):(l+="+",l+=de(Math.trunc(n.o/60)),l+=":",l+=de(Math.trunc(n.o%60)))),i&&(l+="["+n.zone.ianaName+"]"),l}const bo={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ic={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},xc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},_n=["year","month","day","hour","minute","second","millisecond"],Nc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Dc=["year","ordinal","hour","minute","second","millisecond"];function vn(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 ki(n);return e}function Qr(n){switch(n.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return vn(n)}}function Ac(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 Kr(n,e){const t=tt(e.zone,ce.defaultZone);if(!t.isValid)return V.invalid(Ht(t));const s=ie.fromObject(e);let r,i;if(G(n.year))r=ce.now();else{for(const l of _n)G(n[l])&&(n[l]=bo[l]);const o=Yi(n)||Ji(n);if(o)return V.invalid(o);const a=Ac(t);[r,i]=wn(n,a,t)}return new V({ts:r,zone:t,loc:s,o:i})}function Xr(n,e,t){const s=G(t.round)?!0:t.round,r=G(t.rounding)?"trunc":t.rounding,i=(a,l)=>(a=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 ei(n){let e={},t;return n.length>0&&typeof n[n.length-1]=="object"?(e=n[n.length-1],t=Array.from(n).slice(0,n.length-1)):t=Array.from(n),[e,t]}let Gt;const $s=new Map;class V{constructor(e){const t=e.zone||ce.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Me("invalid input"):null)||(t.isValid?null:Ht(t));this.ts=G(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=rt(e.o)&&!e.old?e.o:t.offset(this.ts);r=mn(this.ts,a),s=Number.isNaN(r.year)?new Me("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=t,this.loc=e.loc||ie.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new V({})}static local(){const[e,t]=ei(arguments),[s,r,i,o,a,l,c]=t;return Kr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,t]=ei(arguments),[s,r,i,o,a,l,c]=t;return e.zone=_e.utcInstance,Kr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){const s=ul(e)?e.valueOf():NaN;if(Number.isNaN(s))return V.invalid("invalid input");const r=tt(t.zone,ce.defaultZone);return r.isValid?new V({ts:s,zone:r,loc:ie.fromObject(t)}):V.invalid(Ht(r))}static fromMillis(e,t={}){if(rt(e))return e<-Gr||e>Gr?V.invalid("Timestamp out of range"):new V({ts:e,zone:tt(t.zone,ce.defaultZone),loc:ie.fromObject(t)});throw new pe(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(rt(e))return new V({ts:e*1e3,zone:tt(t.zone,ce.defaultZone),loc:ie.fromObject(t)});throw new pe("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=tt(t.zone,ce.defaultZone);if(!s.isValid)return V.invalid(Ht(s));const r=ie.fromObject(t),i=Ln(e,Qr),{minDaysInFirstWeek:o,startOfWeek:a}=Pr(i,r),l=ce.now(),c=G(t.specificOffset)?s.offset(l):t.specificOffset,u=!G(i.ordinal),h=!G(i.year),d=!G(i.month)||!G(i.day),f=h||d,p=i.weekYear||i.weekNumber;if((f||u)&&p)throw new Tt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(d&&u)throw new Tt("Can't mix ordinal dates with month/day");const O=p||i.weekday&&!f;let y,g,N=mn(l,c);O?(y=Nc,g=Ic,N=Mn(N,o,a)):u?(y=Dc,g=xc,N=is(N)):(y=_n,g=bo);let b=!1;for(const m of y){const $=i[m];G($)?b?i[m]=g[m]:i[m]=N[m]:b=!0}const x=O?al(i,o,a):u?ll(i):Yi(i),E=x||Ji(i);if(E)return V.invalid(E);const C=O?$r(i,o,a):u?Mr(i):i,[_,z]=wn(C,c,s),k=new V({ts:_,zone:s,o:z,loc:r});return i.weekday&&f&&e.weekday!==k.weekday?V.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${k.toISO()}`):k.isValid?k:V.invalid(k.invalid)}static fromISO(e,t={}){const[s,r]=Xl(e);return kt(s,r,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,r]=ec(e);return kt(s,r,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,r]=tc(e);return kt(s,r,t,"HTTP",t)}static fromFormat(e,t,s={}){if(G(e)||G(t))throw new pe("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,u]=Rc(o,e,t);return u?V.invalid(u):kt(a,l,s,`format ${t}`,e,c)}static fromString(e,t,s={}){return V.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,r]=lc(e);return kt(s,r,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new pe("need to specify a reason the DateTime is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new $a(s);return new V({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=Oo(e,ie.fromObject(t));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,t={}){return _o(ye.parseFormat(e),ie.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?fn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?fn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?fn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?fn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,t=6e4,s=Bn(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*t),a=this.zone.offset(s-i*t);if(o===a)return[this];const l=s-o*t,c=s-a*t,u=mn(l,o),h=mn(c,a);return u.hour===h.hour&&u.minute===h.minute&&u.second===h.second&&u.millisecond===h.millisecond?[ct(this,{ts:l}),ct(this,{ts:c})]:[this]}get isInLeapYear(){return on(this.year)}get daysInMonth(){return Pn(this.year,this.month)}get daysInYear(){return this.isValid?It(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}=ye.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(_e.instance(e),t)}toLocal(){return this.setZone(ce.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=tt(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]=wn(o,i,e)}return ct(this,{ts:r,zone:e})}else return V.invalid(Ht(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return ct(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=Ln(e,Qr),{minDaysInFirstWeek:s,startOfWeek:r}=Pr(t,this.loc),i=!G(t.weekYear)||!G(t.weekNumber)||!G(t.weekday),o=!G(t.ordinal),a=!G(t.year),l=!G(t.month)||!G(t.day),c=a||l,u=t.weekYear||t.weekNumber;if((c||o)&&u)throw new Tt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new Tt("Can't mix ordinal dates with month/day");let h;i?h=$r({...Mn(this.c,s,r),...t},s,r):G(t.ordinal)?(h={...this.toObject(),...t},G(t.day)&&(h.day=Math.min(Pn(h.year,h.month),h.day))):h=Mr({...is(this.c),...t});const[d,f]=wn(h,this.o,this.zone);return ct(this,{ts:d,o:f})}plus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e);return ct(this,Yr(this,t))}minus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e).negate();return ct(this,Yr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},r=ne.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?ye.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):as}toLocaleString(e=$n,t={}){return this.isValid?ye.create(this.loc.clone(t),e).formatDateTime(this):as}toLocaleParts(e={}){return this.isValid?ye.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=vn(o);const a=e==="extended";let l=us(this,a,o);return _n.indexOf(o)>=3&&(l+="T"),l+=Jr(this,a,t,s,r,i,o),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?us(this,e==="extended",vn(t)):null}toISOWeekDate(){return pn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=vn(a),(r&&_n.indexOf(a)>=3?"T":"")+Jr(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return pn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return pn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?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")),pn(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 ne.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=dl(t).map(ne.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(V.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||V.fromObject({},{zone:this.zone}),s=e.padding?this<t?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),Xr(t,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?Xr(e.base||V.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(V.isDateTime))throw new pe("min requires all arguments be DateTimes");return Lr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(V.isDateTime))throw new pe("max requires all arguments be DateTimes");return Lr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return Eo(o,e,t)}static fromStringExplain(e,t,s={}){return V.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:r=null}=t,i=ie.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new vo(i,e)}static fromFormatParser(e,t,s={}){if(G(e)||G(t))throw new pe("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new pe(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:u}=t.explainFromTokens(e);return u?V.invalid(u):kt(a,l,s,`format ${t.format}`,e,c)}static get DATE_SHORT(){return $n}static get DATE_MED(){return bi}static get DATE_MED_WITH_WEEKDAY(){return La}static get DATE_FULL(){return Ti}static get DATE_HUGE(){return Si}static get TIME_SIMPLE(){return Ri}static get TIME_WITH_SECONDS(){return Ii}static get TIME_WITH_SHORT_OFFSET(){return xi}static get TIME_WITH_LONG_OFFSET(){return Ni}static get TIME_24_SIMPLE(){return Di}static get TIME_24_WITH_SECONDS(){return Ai}static get TIME_24_WITH_SHORT_OFFSET(){return Ci}static get TIME_24_WITH_LONG_OFFSET(){return Fi}static get DATETIME_SHORT(){return $i}static get DATETIME_SHORT_WITH_SECONDS(){return Mi}static get DATETIME_MED(){return Pi}static get DATETIME_MED_WITH_SECONDS(){return Li}static get DATETIME_MED_WITH_WEEKDAY(){return Va}static get DATETIME_FULL(){return Vi}static get DATETIME_FULL_WITH_SECONDS(){return Ui}static get DATETIME_HUGE(){return Wi}static get DATETIME_HUGE_WITH_SECONDS(){return ji}}function zt(n){if(V.isDateTime(n))return n;if(n&&n.valueOf&&rt(n.valueOf()))return V.fromJSDate(n);if(n&&typeof n=="object")return V.fromObject(n);throw new pe(`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 sn(me());n.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?t[r]=To(i)?.nullable():t[r]=me()})}return Ue({Collection_Path:wt(ke()),...t})},Fc=(n,e,t,s)=>{let r=Ue({}).catchall(Cc(n,e)),i;if(!s&&t){const o=Ae(n,t);i=Zt(o.admin?.skipFormRequiredValidation)}return(!n.required||i)&&(r=r.optional()),r},$c=()=>me().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Must be a valid date"}),To=(n,e,t)=>{let s;const r=`${Zt(n.description)}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const He=require("lodash/isEqual.js"),Wo=require("lodash/merge.js"),jo=require("lodash/set.js"),he=require("lodash/cloneDeep.js"),Rt=require("firebase-admin/app"),B=require("firebase-admin/firestore"),ai=require("node:url"),zo=require("cross-spawn"),li=require("firebase-admin/database"),yt=require("firebase-admin/auth"),Wn=n=>!!n.auth,be=(n,e)=>{if(e?.operations)return e.operations.includes(n)},jn=(n,e)=>e?e.Role?n.access?.includes(e.Role):!1:!0,Zo=(n,e)=>e?!e.Role||n.restrictCreate===!0?!1:typeof n.restrictCreate=="object"?n.restrictCreate?.includes(e.Role):!0:!0,ci=(n,e)=>e?!e.Role||n.restrictUpdate===!0?!1:typeof n.restrictUpdate=="object"?n.restrictUpdate?.includes(e.Role):!0:!0,cr=(n,e,t)=>{const{labels:s}=n;return t.collections&&be("Update",t.collections[s.collection])&&(!e.access||jn(e,t))&&ci(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),ui=(n,e)=>{const t={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=n,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const u=a?.[t[l.type]];c.role===e.Role&&(!c.assignable||u?.active)&&s.push(l)})}),s},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},di=(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 d=h.restrictions?.find(f=>f.type===o.type&&f.roles.some(p=>p.role===t.Role));if(!d)throw new Error("PERMISSION_DENIED");d.roles.forEach(f=>{f.role===t.Role&&(!h.assignable?.includes(t.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:d})})}),s},fi=(n,e,t)=>{const s=Object.values(e.collections),{labels:r}=n,i=[];for(const o of s){const{fields:a}=o;for(const l of a)if(!(l.access&&!jn(l,t))&&t.Role&&X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)!i.find(h=>h.field===c.field)&&c.roles.includes(t.Role)&&i.push(c)}return i},qo=(n,e,t,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const u=ui(e,r),h=Ms(e,r),d=di(e,t,r);u?.filter(v=>v.type==="Record_Owner").forEach(v=>{"operations"in v&&v.operations&&!v.operations.includes(n)||i.Created_By!==s&&(c=!1)}),u?.filter(v=>v.type==="Record_User").forEach(v=>{if("operations"in v&&v.operations&&!v.operations.includes(n))return;const C=W(a,v.collectionField);i[`${C.name}_Array`]?.includes(r.Doc_ID)||(c=!1)}),u?.filter(v=>v.type==="Record_Property").forEach(v=>{if("operations"in v&&v.operations&&!v.operations.includes(n))return;const C=W(a,v.propertyField),_=v.roles.find(z=>z.role===r.Role);C.type==="Array"?_.values?.some(z=>i[C.name].includes(z))||(c=!1):_.values?.includes(i[C.name])||(c=!1)});let f=!0,p=!1;h?.filter(v=>v.type==="Individual").forEach(()=>{p=!0,l?.individualEntities?.includes(i.id)||(f=!1)});let O=!0,y=!1;if(h?.filter(v=>v.type==="Parent").forEach(v=>{y=!0;const C=W(a,v.collectionField);l?.parentEntities?.some(_=>i[`${C.name}_Array`].includes(_))||(O=!1)}),h?.filter(v=>v.type==="Parent_Property").forEach(v=>{y=!0;const C=W(a,v.collectionField),_=W(a,v.propertyField);Object.entries(l?.parentPropertyEntities||{}).some(z=>{const[k,m]=z;return k===i[_.name]&&i[`${C.name}_Array`].some($=>m.includes($))})||(O=!1)}),p&&y){if(!(f||O)){c=!1;return}}else if(!f||!O){c=!1;return}let g=!0,N=!1;d?.filter(v=>v.parentFilter.type==="Individual").forEach(v=>{N=!0;const{parentFilter:C}=v,_=W(a,C.collectionField),z=r.collections?.[_.collection];if(!z){c=!1;return}z.individualEntities?.some(k=>i[`${_.name}_Array`].includes(k))||(g=!1)});let b=!0,x=!1;if(d?.filter(v=>v.parentFilter.type==="Parent").forEach(v=>{x=!0;const{parentFilter:C}=v,_=W(a,C.collectionField),z=W(a,C.parentCollectionField),k=r.collections?.[_.collection];if(!k){c=!1;return}k.parentEntities?.some(m=>i[`${z.name}_Array`].includes(m))||(b=!1)}),d?.filter(v=>v.parentFilter.type==="Parent_Property").forEach(v=>{x=!0;const{parentFilter:C}=v,_=W(a,C.collectionField),z=W(a,C.parentPropertyField),k=W(a,C.parentCollectionField),m=r.collections?.[_.collection];if(!m){c=!1;return}Object.entries(m.parentPropertyEntities||{}).some($=>{const[E,H]=$;return E===i[z.name]&&i[`${k.name}_Array`].some(w=>H.includes(w))})||(b=!1)}),N&&x){if(!(g||b)){c=!1;return}}else if(!g||!b){c=!1;return}return c},it=(n,e,t,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;be(n,a)||(l=!1);const u=Ms(e,r)?.filter(h=>h.type==="Individual").length>0;return n==="Create"&&u&&(l=!1),qo(n,e,t,s,r,i)||(l=!1),l},hi=(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 u=i.access.attributeRestrictions?.filter(d=>d.type===c&&d.roles.some(f=>f.role===e.Role)),h=i.access.entityRestrictions?.restrictions?.filter(d=>d.type===c&&d.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(d=>n.config.roles.includes(d)))){s=`Collection ${r} has invalid entity restrictions assignable value`,t=!1;return}if(u?.length||h?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const d=Object.keys(l);if(d.length!==1||d[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 d=Object.keys(l);if(!(d.length===1&&Object.keys(n.collections).includes(d[0])&&Array.isArray(l[d[0]]))){s=`Collection ${r} has invalid parent entities value`,t=!1;return}}if(a==="Parent_Property"){const d=Object.keys(l);if(!(d.length===1&&Object.keys(n.collections).includes(d[0])&&typeof l[d[0]]=="object"&&l[d[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:u,entityRestrictions:h}=a,d=c.assignable,f=e.collections?.[o.collection],p=["read","create","update","delete"];if(d!==!0&&!(typeof d=="object"&&d.includes(t))?p.forEach(y=>{const g=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const N=!!a.operations[y]?.includes(t),b=!!f?.operations.includes(g);if(!N&&b){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}if(N&&!b){r=`Collection ${o.collection} has missing ${y} operation for role ${t}`,s=!1;return}}}):p.forEach(y=>{const g=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const N=!!a.operations[y]?.includes(t),b=!!f?.operations.includes(g);if(!N&&b){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}}}),!u&&!h||(u?.forEach(y=>{for(const g of y.roles)if(g.role===t&&!g.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${t}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${t}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${t}`,s=!1;return}}}),h?.assignable?.includes(t)))continue;let O=!1;if(h?.restrictions?.forEach(y=>{for(const g of y.roles)if(g.role===t){if(O=!0,y.type==="Individual"&&!e.collections?.[o.collection]?.individualEntities){r=`Collection ${o.collection} is missing individual entities`,s=!1;return}if(y.type==="Parent"){const N=W(l,y.collectionField);if(!X(N)){s=!1;return}if(!e.collections?.[o.collection]?.parentEntities){r=`Collection ${o.collection} is missing parent entities`,s=!1;return}}if(y.type==="Parent_Property"){const N=W(l,y.collectionField);if(!X(N)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[N.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),O&&!e.collections?.[o.collection]?.restrictEntities){r=`Collection ${o.collection} must have restrictEntities set to true`,s=!1;return}}return r&&console.error(`PERMISSION_DENIED: ${r}`),s},Go=(n,e,t,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:u}=c;let h=!0,d="";const f=u?.filter(p=>s===p.userRole);return f?.length&&!f.some(p=>p.recordRole===r)?(d=`User ${s} does not have write access to record with role ${r}`,h=!1,h):n==="update"&&o.User_ID&&f?.length&&!f.some(p=>p.recordRole===a)?(d=`User ${s} does not have write access to record with role ${r}`,h=!1,h):(u?.forEach(p=>{s===p.userRole&&p.recordRole===r&&n!=="delete"&&i&&Object.keys(t.collections).forEach(O=>{const y=i.collections?.[O],g=l?.collections?.[O];if(!(n==="update"&&He(y,g))&&y){const N=p.collections.some(b=>b.collection===O);if(N){if(N){const b=p.collections.find(v=>v.collection===O);if(!(y.operations.every(v=>b.operations.includes(v))||n==="update"&&He(y.operations,g?.operations))){d=`User ${s} does not have write access to all included operations for collection ${O}`,h=!1;return}if(!b.auth&&y.auth&&!(n==="update"&&He(y.auth,g?.auth))){d=`User ${s} does not have write access to auth for collection ${O}`,h=!1;return}const x={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(x).forEach(v=>{const C=x[v];if(b.attributeRestrictions?.includes(C)&&!(y[v]?.active||n==="update"&&He(y[v],g?.[v]))){d=`User ${s} does not have write access to attribute restriction ${v} for collection ${O}`,h=!1;return}}),b.restrictEntities&&!y.restrictEntities&&!(n==="update"&&He(y.restrictEntities,g?.restrictEntities))){d=`User ${s} does not have write access to restrictEntities for collection ${O}`,h=!1;return}}}else{d=`User ${s} does not have write access to collection ${O}`,h=!1;return}}})}),d&&console.error(`PERMISSION_DENIED: ${d}`),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&&!Wn(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const u of a?.operations||[])if(!l?.operations.includes(u)&&(!be("Read",c)||!be(u,c))){i=`User does not have ${u.toLowerCase()} access to collection ${o.labels.collection}`,r=!1;return}if(!a?.recordOwner&&l?.recordOwner&&c?.recordOwner){i=`User does not have write access to recordOwner for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordUser&&l?.recordUser&&c?.recordUser){i=`User does not have write access to recordUser for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordProperty&&l?.recordProperty&&c?.recordProperty){i=`User does not have write access to recordProperty for collection ${o.labels.collection}`,r=!1;return}if(!a?.restrictEntities&&l?.restrictEntities&&c?.restrictEntities){i=`User does not have write access to restrictEntities for collection ${o.labels.collection}`,r=!1;return}}),i&&console.error(`PERMISSION_DENIED: ${i}`),r},Ps=(n,e,t,s,r,i,o,a,l,c,u)=>{const{labels:h}=s;let d=!0,f="";if(!e.Role)return f="Record does not have a role",d=!1,d;if(n==="update"&&!c)return f="Original record is required for update operations",d=!1,d;if(n==="update"&&i&&u==="update"&&a&&!l)return f="Original permissions are required for this operation",d=!1,d;if(i){if(!o?.Role)return f="Current user does not have a role",d=!1,d;if(!Go(n,s,r,o.Role,e.Role,a,c,c?.Role,l))return d=!1,d;if(n==="update"&&u!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",d=!1,d;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",d=!1,d;if(n==="delete"&&i===e.User_ID)return f="User cannot delete their own record",d=!1,d}return n==="delete"||u==="delete"||!a?d:a.Role?(Bo(r,a)||(d=!1),a.Collection&&a.Collection!==h.collection?(f="Permissions collection does not match record collection",d=!1,d):a.Role!==e.Role?(f="Permissions role does not match record role",d=!1,d):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",d=!1,d):a.Doc_ID&&a.Doc_ID!==t?(f="Permissions doc ID does not match record doc ID",d=!1,d):!Ho(r,a,a.Role)||i&&o&&l&&!Yo(r,o,a,l)?(d=!1,d):(f&&console.error(`PERMISSION_DENIED: ${f}`),d)):(f="Permissions do not have a role",d=!1,d)},ur=(n,e,t,s,r,i,o)=>{const{labels:a,fields:l}=t,c=i?.collections?.[a.collection];let u=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!be("Create",c)&&(u=!1),r&&!it("Create",t,s,r,i,n)&&(u=!1),t.auth&&o&&(r&&!Wn(c)&&(u=!1),Ps("create",n,e,t,s,r,i,o)||(u=!1));for(const h of l){const d=n[h.name];h.access&&!jn(h,i)&&d!==void 0&&(u=!1),d!==void 0&&!Zo(h,i)&&(u=!1)}if(!u)throw new Error("PERMISSION_DENIED")},xe=n=>n&&(n._methodName==="deleteField"||n.constructor.name==="DeleteTransform"),nt=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(xe(n[e])?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&nt(n[e]))},dr=(n,e,t,s,r,i,o,a,l,c)=>{const{labels:u,fields:h}=s,d=o?.collections?.[u.collection],f={...e,...n};nt(f);let p=!0,O="";if(i&&!d)throw new Error("PERMISSION_DENIED");i&&!be("Update",d)&&(p=!1,O="Authenticated user does not have Update access to this collection"),i&&(!it("Update",s,r,i,o,e)||!it("Update",s,r,i,o,f))&&(p=!1,O="Authenticated user does not have Update access to this document"),i&&s.softDelete&&f[s.softDelete.archivedField]!==e[s.softDelete.archivedField]&&!be("Delete",d)&&(p=!1,O="Authenticated user does not have Delete or Restore access to this document"),a&&(i&&!Wn(d)&&(p=!1,O="Authenticated user does not have Auth access for this collection"),Ps("update",f,t,s,r,i,o,l,c,e,a)||(O="Authenticated user does not have sufficient write access for this record",p=!1));for(const y of h){const g=n[y.name];y.access&&!jn(y,o)&&g!==void 0&&(O=`Authenticated user does not have access to field ${y.name}`,p=!1),g!==void 0&&!ci(y,o)&&(O=`Authenticated user does not have Update access to field ${y.name}`,p=!1)}if(!p)throw O&&console.error(`PERMISSION_DENIED: ${O}`),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(be("Delete",a)||(l=!1),it("Delete",t,s,r,i,n)||(l=!1),t.auth&&n.User_ID&&(Wn(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(be("Read",o)||(a=!1),it("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(be("Read",o)||(a=!1),n.forEach(l=>{it("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(u=>u.role===n));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},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 u in c)u==="custom"||u==="admin"||u==="name"||u==="formula"||delete c[u];i[o]=l}return i},Ae=(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,oe=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 u of e)if(u==="__proto__"||u==="constructor"||u==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=Qn,i=!0;for(const u of e){if(u===void 0||r[u]===void 0){i=!1;break}r=r[u]}if(r&&i&&!s)return r;let o,a=n,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const u of o){if(u===void 0||a[u]===void 0){l=!1;break}a=a[u]}let c;if(l&&(c=await oe(a,t)),c){let u=Qn;const h={};for(let d=0;d<e.length;d++){const f=e[d];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");d===e.length-1?jo(h,e.join("."),c):(u[f]||={},u=u[f])}}Wo(Qn,h)}return c},at=(n,e,t)=>{const s=Object.values(t.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field===n.name&&(i=!0)}return i},mi=(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)),ht=["id","Collection_Path","Last_Write_At","Last_Save_At","Last_Write_By","Last_Write_App","Last_Write_Connection_Status","Last_Write_Version","Created_At","Saved_At","Created_By"],zn=()=>ht.map(n=>{let e="",t;switch(n){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",t=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:n,type:e,required:!0};return t&&(s.values=t),s}),pi=(n,e)=>{const t=[],{access:s,fields:r}=n,{attributeRestrictions:i,entityRestrictions:o}=s,a=zn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":t.push(W(a,"Created_By"));break;case"Record_User":t.push(W(r,l.collectionField));break;case"Record_Property":t.push(W(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(W(a,"id"));break;case"Parent":t.push(W(r,l.collectionField));break;case"Parent_Property":t.push(W(r,l.collectionField)),t.push(W(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(W(r,l.collectionField));break;case"Parent":t.push(W(r,l.parentCollectionField));break;case"Parent_Property":t.push(W(r,l.parentCollectionField)),t.push(W(r,l.parentPropertyField));break}})),[...new Set(t)]},sa=(n,e)=>{const t=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=n,a=zn();return t.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{(!c.access||c.access.includes(e))&&t.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{t.push(W(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{ht.includes(c)&&t.push(W(a,c))}),o?.forEach(c=>{const u=W(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&u&&(!u.access||u.access?.includes(e))&&ht.includes(c.field)&&t.push(W(a,c.field))}),pi(n,e).forEach(c=>{ht.includes(c.name)&&t.push(W(a,c.name))}),[...new Set(t)]},ra=(n,e,t)=>{const s=[],{fields:r,preloadCache:i}=e,o=zn();i?.range&&i.range.fields.forEach(c=>{ht.includes(c)?s.push(W(o,c)):s.push(W(r,c))});const a=new Set,l=mi(e,t);return Object.entries(l).map(([c,u])=>{n.name===c&&Object.values(u).forEach(h=>{h.forEach(d=>{a.add(d)})})}),a.forEach(c=>{s.push(...pi(e,c))}),[...new Set(s)]},un=(n,e,t)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=mi(e,t);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{t.collections[c].fields.forEach(h=>{X(h)&&h.collection===e.labels.collection&&h.dependencyFields?.some(d=>d.field===n.name)&&h.constraints&&h.constraints.forEach(d=>{o.push(d[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)]},yi=(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},gi=(n,e,t)=>{const s=yi(e,t);for(const r of s.values())if(r.roles.includes(n))return r},ia=(n,e)=>{const{fields:t}=e,s=zn(),r=[];return[...t,...s.filter(o=>o.name!=="id")].forEach(o=>{n?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ls=(n,e,t)=>{const s={};return Object.values(n.collections).forEach(r=>{const i=yi(r,n),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},bn=n=>({Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_Version:n.Last_Write_Version,Last_Write_App:n.Last_Write_App,Last_Save_At:n.Last_Save_At}),Xn=async(n,e,t)=>{if(e){const s=await oe(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),ut=(n,e)=>{const{access:t,queries:s}=n,{serverReadOnly:r}=t,i=new Set;if(s)for(const o of s){const a=W(e,o.field);e.find(l=>l.name===o.field)&&X(a)&&["OneToOne","OneToMany"].includes(a.type)&&i.add(a)}return e.forEach(o=>{X(o)&&["OneToOne","OneToMany"].includes(o.type)&&o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a)))&&i.add(o)}),i},gt=(n,e)=>{const{access:t,recordTitleField:s}=n,{serverReadOnly:r}=t,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},Tn=(n,e,t)=>{const{fields:s}=n;s.forEach(i=>{if(X(i))if(e[i.name]){if(xe(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=t.collections[i.collection],l=W(a.fields,o);gt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(u=>{e[i.name][u][o]?e[i.name][u][`${o}_Lowercase`]=e[i.name][u][o].toLowerCase():delete e[i.name][u][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),ut(n,s).forEach(i=>{if(e[i.name])if(xe(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`]={id:o,...a}}}})},Sn=(n,e)=>{gt(n,n.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},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!==void 0&&!(s&&o.access&&!o.access.includes(s))&&(n[i.name]=await oe(i.custom.initialValue,[n]),gt(e,[o]).size===1&&(n[`${i.name}_Lowercase`]=n[i.name].toLowerCase()))}for(const i of r)s&&i.access&&!i.access.includes(s)||("autoIncrement"in i&&i.autoIncrement&&!n[i.name]&&(n[i.name]="Pending"),!X(i)&&i.nullable&&n[i.name]===void 0&&(n[i.name]=null))};var se;(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})(se||(se={}));var fr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(fr||(fr={}));const U=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xe=n=>{switch(typeof n){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN(n)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":return Array.isArray(n)?U.array:n===null?U.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?U.promise:typeof Map<"u"&&n instanceof Map?U.map:typeof Set<"u"&&n instanceof Set?U.set:typeof Date<"u"&&n instanceof Date?U.date:U.object;default:return U.unknown}},D=se.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 Ye 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 Ye))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.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()}}Ye.create=n=>new Ye(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,se.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:t=`Unrecognized key(s) in object: ${se.joinValues(n.keys,", ")}`;break;case D.invalid_union:t="Invalid input";break;case D.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${se.joinValues(n.options)}`;break;case D.invalid_enum_value:t=`Invalid enum value. Expected ${se.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}"`:se.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,se.assertNever(n)}return{message:t}};let aa=ys;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 M(n,e){const t=la(),s=ca({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 Ee{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const r of t){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Ee.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return J;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const J=Object.freeze({status:"aborted"}),qt=n=>({status:"dirty",value:n}),Ce=n=>({status:"valid",value:n}),hr=n=>n.status==="aborted",mr=n=>n.status==="dirty",Nt=n=>n.status==="valid",Rn=n=>typeof Promise<"u"&&n instanceof Promise;var j;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(j||(j={}));class We{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const pr=(n,e)=>{if(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 Ye(n.common.issues);return this._error=t,this._error}}};function Q(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:r}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=n;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:r}}class ee{get description(){return this._def.description}_getType(e){return Xe(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ee,ctx:{common:e.parent.common,data:e.data,parsedType:Xe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Rn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)},r=this._parseSync({data:e,path:s.path,parent:s});return pr(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Xe(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return 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:Xe(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Rn(r)?r:Promise.resolve(r));return pr(s,i)}refine(e,t){const s=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:D.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof t=="function"?t(s,r):t),!1))}_refinement(e){return new Ct({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return st.create(this,this._def)}nullable(){return Ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ve.create(this)}promise(){return An.create(this,this._def)}or(e){return xn.create([this,e],this._def)}and(e){return Nn.create(this,e,this._def)}transform(e){return new Ct({...Q(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Os({...Q(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new Aa({typeName:Y.ZodBranded,type:this,...Q(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ks({...Q(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Us.create(this,e)}readonly(){return bs.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 es;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}(=)?))?$/,wi="((\\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(`^${wi}$`);function _i(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 Sa(n){return new RegExp(`^${_i(n)}$`)}function Ra(n){let e=`${wi}T${_i(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ia(n,e){return!!((e==="v4"||!e)&&_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 Na(n,e){return!!((e==="v4"||!e)&&Ea.test(n)||(e==="v6"||!e)&&Oa.test(n))}class Ge extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){const i=this._getOrReturnCtx(e);return M(i,{code:D.invalid_type,expected:U.string,received:i.parsedType}),J}const s=new Ee;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),M(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),M(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?M(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&M(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),M(r,{validation:"email",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")es||(es=new RegExp(wa,"u")),es.test(e.data)||(r=this._getOrReturnCtx(e,r),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(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),M(r,{code:D.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Ta.test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:D.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Sa(i).test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{code:D.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?ya.test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{validation:"duration",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ia(e.data,i.version)||(r=this._getOrReturnCtx(e,r),M(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),M(r,{validation:"jwt",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Na(e.data,i.version)||(r=this._getOrReturnCtx(e,r),M(r,{validation:"cidr",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?ka.test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?ba.test(e.data)||(r=this._getOrReturnCtx(e,r),M(r,{validation:"base64url",code:D.invalid_string,message:i.message}),s.dirty()):se.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,...j.errToObj(s)})}_addCheck(e){return new Ge({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...j.errToObj(e)})}url(e){return this._addCheck({kind:"url",...j.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...j.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...j.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...j.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...j.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...j.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...j.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...j.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...j.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...j.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...j.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...j.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,...j.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,...j.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...j.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...j.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...j.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...j.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...j.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...j.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...j.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...j.errToObj(t)})}nonempty(e){return this.min(1,j.errToObj(e))}trim(){return new Ge({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ge({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ge({...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}}Ge.create=n=>new Ge({checks:[],typeName:Y.ZodString,coerce:n?.coerce??!1,...Q(n)});function Da(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=t>s?t:s,i=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Dt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==U.number){const i=this._getOrReturnCtx(e);return M(i,{code:D.invalid_type,expected:U.number,received:i.parsedType}),J}let s;const r=new Ee;for(const i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),M(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),M(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),M(s,{code:D.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Da(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),M(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),M(s,{code:D.not_finite,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,s,r){return new Dt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:j.toString(r)}]})}_addCheck(e){return new Dt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:j.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:j.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.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"&&se.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Dt.create=n=>new Dt({checks:[],typeName:Y.ZodNumber,coerce:n?.coerce||!1,...Q(n)});class Xt extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==U.bigint)return this._getInvalidInput(e);let s;const r=new Ee;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),M(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),M(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),M(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return M(t,{code:D.invalid_type,expected:U.bigint,received:t.parsedType}),J}gte(e,t){return this.setLimit("min",e,!0,j.toString(t))}gt(e,t){return this.setLimit("min",e,!1,j.toString(t))}lte(e,t){return this.setLimit("max",e,!0,j.toString(t))}lt(e,t){return this.setLimit("max",e,!1,j.toString(t))}setLimit(e,t,s,r){return new Xt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:j.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:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:j.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:Y.ZodBigInt,coerce:n?.coerce??!1,...Q(n)});class gs extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.boolean,received:s.parsedType}),J}return Ce(e.data)}}gs.create=n=>new gs({typeName:Y.ZodBoolean,coerce:n?.coerce||!1,...Q(n)});class In extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){const i=this._getOrReturnCtx(e);return M(i,{code:D.invalid_type,expected:U.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return M(i,{code:D.invalid_date}),J}const s=new Ee;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),M(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),M(r,{code:D.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):se.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new In({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:j.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:j.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}}In.create=n=>new In({checks:[],coerce:n?.coerce||!1,typeName:Y.ZodDate,...Q(n)});class yr extends ee{_parse(e){if(this._getType(e)!==U.symbol){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.symbol,received:s.parsedType}),J}return Ce(e.data)}}yr.create=n=>new yr({typeName:Y.ZodSymbol,...Q(n)});class ws extends ee{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.undefined,received:s.parsedType}),J}return Ce(e.data)}}ws.create=n=>new ws({typeName:Y.ZodUndefined,...Q(n)});class gr extends ee{_parse(e){if(this._getType(e)!==U.null){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.null,received:s.parsedType}),J}return Ce(e.data)}}gr.create=n=>new gr({typeName:Y.ZodNull,...Q(n)});class _s extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return Ce(e.data)}}_s.create=n=>new _s({typeName:Y.ZodAny,...Q(n)});class wr extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ce(e.data)}}wr.create=n=>new wr({typeName:Y.ZodUnknown,...Q(n)});class ot extends ee{_parse(e){const t=this._getOrReturnCtx(e);return M(t,{code:D.invalid_type,expected:U.never,received:t.parsedType}),J}}ot.create=n=>new ot({typeName:Y.ZodNever,...Q(n)});class _r extends ee{_parse(e){if(this._getType(e)!==U.undefined){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.void,received:s.parsedType}),J}return Ce(e.data)}}_r.create=n=>new _r({typeName:Y.ZodVoid,...Q(n)});class Ve extends ee{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==U.array)return M(t,{code:D.invalid_type,expected:U.array,received:t.parsedType}),J;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(M(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&&(M(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&&(M(t,{code:D.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new We(t,o,t.path,a)))).then(o=>Ee.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new We(t,o,t.path,a)));return Ee.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new Ve({...this._def,minLength:{value:e,message:j.toString(t)}})}max(e,t){return new Ve({...this._def,maxLength:{value:e,message:j.toString(t)}})}length(e,t){return new Ve({...this._def,exactLength:{value:e,message:j.toString(t)}})}nonempty(e){return this.min(1,e)}}Ve.create=(n,e)=>new Ve({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...Q(e)});function bt(n){if(n instanceof ue){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=st.create(bt(s))}return new ue({...n._def,shape:()=>e})}else return n instanceof Ve?new Ve({...n._def,type:bt(n.element)}):n instanceof st?st.create(bt(n.unwrap())):n instanceof Ft?Ft.create(bt(n.unwrap())):n instanceof mt?mt.create(n.items.map(e=>bt(e))):n}class ue extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=se.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 M(c,{code:D.invalid_type,expected:U.object,received:c.parsedType}),J}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const u=i[c],h=r.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new We(r,h,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ot){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:r.data[u]}});else if(c==="strict")a.length>0&&(M(r,{code:D.unrecognized_keys,keys:a}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of a){const h=r.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new We(r,h,r.path,u)),alwaysSet:u in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of l){const h=await u.key,d=await u.value;c.push({key:h,value:d,alwaysSet:u.alwaysSet})}return c}).then(c=>Ee.mergeObjectSync(s,c)):Ee.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return j.errToObj,new ue({...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:j.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(e){return new ue({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ue({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ue({...this._def,catchall:e})}pick(e){const t={};for(const s of se.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new ue({...this._def,shape:()=>t})}omit(e){const t={};for(const s of se.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new ue({...this._def,shape:()=>t})}deepPartial(){return bt(this)}partial(e){const t={};for(const s of se.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new ue({...this._def,shape:()=>t})}required(e){const t={};for(const s of se.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof st;)i=i._def.innerType;t[s]=i}return new ue({...this._def,shape:()=>t})}keyof(){return Ei(se.objectKeys(this.shape))}}ue.create=(n,e)=>new ue({shape:()=>n,unknownKeys:"strip",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});ue.strictCreate=(n,e)=>new ue({shape:()=>n,unknownKeys:"strict",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});ue.lazycreate=(n,e)=>new ue({shape:n,unknownKeys:"strip",catchall:ot.create(),typeName:Y.ZodObject,...Q(e)});class xn extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Ye(a.ctx.common.issues));return M(t,{code:D.invalid_union,unionErrors:o}),J}if(t.common.async)return Promise.all(s.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new Ye(l));return M(t,{code:D.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}xn.create=(n,e)=>new xn({options:n,typeName:Y.ZodUnion,...Q(e)});function Es(n,e){const t=Xe(n),s=Xe(e);if(n===e)return{valid:!0,data:n};if(t===U.object&&s===U.object){const r=se.objectKeys(e),i=se.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 ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(hr(i)||hr(o))return J;const a=Es(i.value,o.value);return a.valid?((mr(i)||mr(o))&&t.dirty(),{status:t.value,value:a.data}):(M(s,{code:D.invalid_intersection_types}),J)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,o])=>r(i,o)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Nn.create=(n,e,t)=>new Nn({left:n,right:e,typeName:Y.ZodIntersection,...Q(t)});class mt extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.array)return M(s,{code:D.invalid_type,expected:U.array,received:s.parsedType}),J;if(s.data.length<this._def.items.length)return M(s,{code:D.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&s.data.length>this._def.items.length&&(M(s,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...s.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new We(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Ee.mergeArray(t,o)):Ee.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new mt({...this._def,rest:e})}}mt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:n,typeName:Y.ZodTuple,rest:null,...Q(e)})};class Dn extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.object)return M(s,{code:D.invalid_type,expected:U.object,received:s.parsedType}),J;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new We(s,a,s.path,a)),value:o._parse(new We(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Ee.mergeObjectAsync(t,r):Ee.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof ee?new Dn({keyType:e,valueType:t,typeName:Y.ZodRecord,...Q(s)}):new Dn({keyType:Ge.create(),valueType:e,typeName:Y.ZodRecord,...Q(t)})}}class Er extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.map)return M(s,{code:D.invalid_type,expected:U.map,received:s.parsedType}),J;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,l],c)=>({key:r._parse(new We(s,a,s.path,[c,"key"])),value:i._parse(new We(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return J;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(c.value,u.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return J;(c.status==="dirty"||u.status==="dirty")&&t.dirty(),a.set(c.value,u.value)}return{status:t.value,value:a}}}}Er.create=(n,e,t)=>new Er({valueType:e,keyType:n,typeName:Y.ZodMap,...Q(t)});class en extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==U.set)return M(s,{code:D.invalid_type,expected:U.set,received:s.parsedType}),J;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(M(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&&(M(s,{code:D.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const u of l){if(u.status==="aborted")return J;u.status==="dirty"&&t.dirty(),c.add(u.value)}return{status:t.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new We(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,t){return new en({...this._def,minSize:{value:e,message:j.toString(t)}})}max(e,t){return new en({...this._def,maxSize:{value:e,message:j.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:Y.ZodSet,...Q(e)});class vr extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}vr.create=(n,e)=>new vr({getter:n,typeName:Y.ZodLazy,...Q(e)});class vs extends ee{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return M(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}vs.create=(n,e)=>new vs({value:n,typeName:Y.ZodLiteral,...Q(e)});function Ei(n,e){return new At({values:n,typeName:Y.ZodEnum,...Q(e)})}class At extends ee{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return M(t,{expected:se.joinValues(s),received:t.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return M(t,{received:t.data,code:D.invalid_enum_value,options:s}),J}return Ce(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return At.create(e,{...this._def,...t})}exclude(e,t=this._def){return At.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}At.create=Ei;class Or extends ee{_parse(e){const t=se.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==U.string&&s.parsedType!==U.number){const r=se.objectValues(t);return M(s,{expected:se.joinValues(r),received:s.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=se.objectValues(t);return M(s,{received:s.data,code:D.invalid_enum_value,options:r}),J}return Ce(e.data)}get enum(){return this._def.values}}Or.create=(n,e)=>new Or({values:n,typeName:Y.ZodNativeEnum,...Q(e)});class An extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==U.promise&&t.common.async===!1)return M(t,{code:D.invalid_type,expected:U.promise,received:t.parsedType}),J;const s=t.parsedType===U.promise?t.data:Promise.resolve(t.data);return Ce(s.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}An.create=(n,e)=>new An({type:n,typeName:Y.ZodPromise,...Q(e)});class Ct extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{M(s,o),o.fatal?t.abort():t.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return J;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?J:l.status==="dirty"||t.value==="dirty"?qt(l.value):l});{if(t.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?J:a.status==="dirty"||t.value==="dirty"?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"?J:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Nt(o))return J;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Nt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):J);se.assertNever(r)}}Ct.create=(n,e,t)=>new Ct({schema:n,typeName:Y.ZodEffects,effect:e,...Q(t)});Ct.createWithPreprocess=(n,e,t)=>new Ct({schema:e,effect:{type:"preprocess",transform:n},typeName:Y.ZodEffects,...Q(t)});class st extends ee{_parse(e){return this._getType(e)===U.undefined?Ce(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}st.create=(n,e)=>new st({innerType:n,typeName:Y.ZodOptional,...Q(e)});class Ft extends ee{_parse(e){return this._getType(e)===U.null?Ce(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ft.create=(n,e)=>new Ft({innerType:n,typeName:Y.ZodNullable,...Q(e)});class Os extends ee{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===U.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Os.create=(n,e)=>new Os({innerType:n,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});class ks extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Rn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ye(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Ye(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}ks.create=(n,e)=>new ks({innerType:n,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});class kr extends ee{_parse(e){if(this._getType(e)!==U.nan){const s=this._getOrReturnCtx(e);return M(s,{code:D.invalid_type,expected:U.nan,received:s.parsedType}),J}return{status:"valid",value:e.data}}}kr.create=n=>new kr({typeName:Y.ZodNaN,...Q(n)});class Aa extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Us extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?J:i.status==="dirty"?(t.dirty(),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"?J:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,t){return new Us({in:e,out:t,typeName:Y.ZodPipeline})}}class bs extends ee{_parse(e){const t=this._def.innerType._parse(e),s=r=>(Nt(r)&&(r.value=Object.freeze(r.value)),r);return Rn(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}bs.create=(n,e)=>new bs({innerType:n,typeName:Y.ZodReadonly,...Q(e)});var Y;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Y||(Y={}));const ke=Ge.create,dt=Dt.create,Qt=gs.create,ts=ws.create,me=_s.create;ot.create;const wt=Ve.create,Ue=ue.create,ve=xn.create;Nn.create;mt.create;const sn=Dn.create,Oe=vs.create,Cn=At.create;An.create;st.create;Ft.create;const gn=()=>me().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),br=()=>me().refine(n=>n&&(n._methodName==="serverTimestamp"||n.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),vi=(n,e,t)=>{const s={};if(n.includeFields){const i=e.collections[n.collection];if(!i)return sn(me());n.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${n.collection}`);s[o]=Fn(i,a),gt(i,[a]).size===1&&(s[`${o}_Lowercase`]=Fn(i,a,!0))})}const r={Collection_Path:wt(ke()),...s};return t&&(r.id=ke().length(20)),Ue(r)},Ca=(n,e)=>{let t=sn(vi(n,e));return n.required||(t=t.optional()),t},Fa=n=>{let e=wt(ve([ke().length(20),ke().length(28)]));return["OneToOne","OneToMany"].includes(n.type)?e=e.max(1):(n.min&&(e=e.min(n.min)),n.max&&(e=e.max(n.max)),n.length&&(e=e.length(n.length))),n.required?e=e.nonempty():e=e.optional(),e},Fn=(n,e,t)=>{const{softDelete:s}=n,r=s?.timestampField;let i;switch(e.type){case"String":if(i=ke(),e.length&&(i=i.length(e.length)),e.minlength&&(i=i.min(e.minlength)),e.maxlength&&(i=i.max(e.maxlength)),e.email&&(i=i.email()),e.uuid&&(i=i.uuid()),e.url&&(i=i.url()),e.emoji&&(i=i.emoji()),e.ip&&(i=i.ip()),e.pattern&&(i=i.regex(new RegExp(e.pattern))),t&&(i=i.toLowerCase()),e.values)if(t){const o=e.values.map(a=>a.toLowerCase());i=Cn(o)}else i=Cn(e.values);break;case"Boolean":i=Qt();break;case"Number":e.autoIncrement?i=ve([Oe("Pending"),dt().int()]):(i=dt(),e.min&&(i=i.min(e.min)),e.max&&(i=i.max(e.max)),e.decimal?i=i.refine(o=>e.decimal?(o.toString().split(".")[1]?.length||0)<=e.decimal:!1,{message:`Value must have ${e.decimal} or fewer decimal places`}):i=i.int(),e.values&&(i=i.refine(o=>e.values?.includes(o),{message:"Value is not an allowed value"})));break;case"Timestamp":e.name===r?i=me().refine(o=>o&&(o._methodName==="serverTimestamp"||o.constructor.name==="ServerTimestampTransform"||o.seconds!==void 0&&o.nanoseconds!==void 0||o._seconds!==void 0&&o._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}):(i=gn(),e.min&&(i=i.refine(o=>o.toMillis()>=e.min,{message:`Value is less than the minimum allowed value of ${e.min}`})),e.max&&(i=i.refine(o=>o.toMillis()<=e.max,{message:`Value is greater than the maximum allowed value of ${e.max}`})));break;case"Array":i=wt(me()),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(me()),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=me();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},Oi=(n,e,t)=>{const s={Collection_Path:wt(ke()),Last_Write_App:ke(),Last_Write_At:gn(),Last_Save_At:br(),Last_Write_By:ve([ke().length(28),Oe("System")]),Last_Write_Connection_Status:Cn(["Online","Offline"]),Last_Write_Version:dt().int(),id:ke().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:gn(),Created_By:ve([ke().length(28),Oe("System")])};n==="create"&&(s.Saved_At=br()),n==="update"&&(s.Saved_At=gn(),s.Collection_Path=s.Collection_Path.optional(),s.id=s.id.optional(),s.Created_At=s.Created_At.optional(),s.Saved_At=s.Saved_At.optional(),s.Created_By=s.Created_By.optional());const r=ut(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{X(l)?(s[l.name]=Ca(l,t),s[`${l.name}_Array`]=Fa(l),i.includes(l.name)&&(s[`${l.name}_Single`]=vi(l,t,!0),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=Fn(e,l))}),gt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=Fn(e,l,!0))});const a=Ue(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class _t extends Error{}class $a extends _t{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Ma extends _t{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class Pa extends _t{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Tt extends _t{}class ki extends _t{constructor(e){super(`Invalid unit ${e}`)}}class pe extends _t{}class Ke extends _t{constructor(){super("Zone is an abstract class")}}const F="numeric",Pe="short",Te="long",$n={year:F,month:F,day:F},bi={year:F,month:Pe,day:F},La={year:F,month:Pe,day:F,weekday:Pe},Ti={year:F,month:Te,day:F},Si={year:F,month:Te,day:F,weekday:Te},Ri={hour:F,minute:F},Ii={hour:F,minute:F,second:F},xi={hour:F,minute:F,second:F,timeZoneName:Pe},Ni={hour:F,minute:F,second:F,timeZoneName:Te},Di={hour:F,minute:F,hourCycle:"h23"},Ai={hour:F,minute:F,second:F,hourCycle:"h23"},Ci={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:Pe},Fi={hour:F,minute:F,second:F,hourCycle:"h23",timeZoneName:Te},$i={year:F,month:F,day:F,hour:F,minute:F},Mi={year:F,month:F,day:F,hour:F,minute:F,second:F},Pi={year:F,month:Pe,day:F,hour:F,minute:F},Li={year:F,month:Pe,day:F,hour:F,minute:F,second:F},Va={year:F,month:Pe,day:F,weekday:Pe,hour:F,minute:F},Vi={year:F,month:Te,day:F,hour:F,minute:F,timeZoneName:Pe},Ui={year:F,month:Te,day:F,hour:F,minute:F,second:F,timeZoneName:Pe},Wi={year:F,month:Te,day:F,weekday:Te,hour:F,minute:F,timeZoneName:Te},ji={year:F,month:Te,day:F,weekday:Te,hour:F,minute:F,second:F,timeZoneName:Te};class rn{get type(){throw new Ke}get name(){throw new Ke}get ianaName(){return this.name}get isUniversal(){throw new Ke}offsetName(e,t){throw new Ke}formatOffset(e,t){throw new Ke}offset(e){throw new Ke}equals(e){throw new Ke}get isValid(){throw new Ke}}let ns=null;class Zn extends rn{static get instance(){return ns===null&&(ns=new Zn),ns}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Xi(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 Ts=new Map;function Ua(n){let e=Ts.get(n);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Ts.set(n,e)),e}const 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,u]=s;return[o,r,i,a,l,c,u]}function za(n,e){const t=n.formatToParts(e),s=[];for(let r=0;r<t.length;r++){const{type:i,value:o}=t[r],a=Wa[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const ss=new Map;class Je extends rn{static create(e){let t=ss.get(e);return t===void 0&&ss.set(e,t=new Je(e)),t}static resetCache(){ss.clear(),Ts.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=Je.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return Xi(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=Ua(this.name);let[r,i,o,a,l,c,u]=s.formatToParts?za(s,t):ja(s,t);a==="BC"&&(r=-Math.abs(r)+1);const d=Bn({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:u,millisecond:0});let f=+t;const p=f%1e3;return f-=p>=0?p:1e3+p,(d-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Tr={};function Za(n,e={}){const t=JSON.stringify([n,e]);let s=Tr[t];return s||(s=new Intl.ListFormat(n,e),Tr[t]=s),s}const Ss=new Map;function Rs(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 Is=new Map;function qa(n,e={}){const t=JSON.stringify([n,e]);let s=Is.get(t);return s===void 0&&(s=new Intl.NumberFormat(n,e),Is.set(t,s)),s}const xs=new Map;function Ba(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 Ha(){return Bt||(Bt=new Intl.DateTimeFormat().resolvedOptions().locale,Bt)}const Ns=new Map;function zi(n){let e=Ns.get(n);return e===void 0&&(e=new Intl.DateTimeFormat(n).resolvedOptions(),Ns.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={...Zi,...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=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 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=V.utc(2009,t,1);e.push(n(s))}return e}function Ka(n){const e=[];for(let t=1;t<=7;t++){const s=V.utc(2016,11,13+t);e.push(n(s))}return e}function dn(n,e,t,s){const r=n.listingMode();return r==="error"?null:r==="en"?t(e):s(e)}function Xa(n){return n.numberingSystem&&n.numberingSystem!=="latn"?!1:n.numberingSystem==="latn"||!n.locale||n.locale.startsWith("en")||zi(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):qs(e,3);return de(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&&Je.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 nl{constructor(e,t,s){this.opts={style:"long",...s},!t&&Qi()&&(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 Zi={firstDay:1,minimalDays:4,weekend:[6,7]};class ie{static fromOpts(e){return ie.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,u=Cs(r)||ce.defaultWeekSettings;return new ie(a,l,c,u,o)}static resetCache(){Bt=null,Ss.clear(),Is.clear(),xs.clear(),Ns.clear(),Ds.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:r}={}){return ie.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:ie.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 dn(this,e,no,()=>{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 dn(this,e,io,()=>{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 dn(this,void 0,()=>oo,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[V.utc(2016,11,13,9),V.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return dn(this,e,ao,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[V.utc(-40,1,1),V.utc(2017,1,1)].map(s=>this.extract(s,t,"era"))),this.eraCache[e]})}extract(e,t,s){const r=this.dtFormatter(e,t),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new 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"||zi(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Ki()?Ga(this.locale):Zi}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 _e extends rn{static get utcInstance(){return rs===null&&(rs=new _e(0)),rs}static instance(e){return e===0?_e.utcInstance:new _e(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new _e(Hn(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${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 sl 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 tt(n,e){if(G(n)||n===null)return e;if(n instanceof rn)return n;if(cl(n)){const t=n.toLowerCase();return t==="default"?e:t==="local"||t==="system"?Zn.instance:t==="utc"||t==="gmt"?_e.utcInstance:_e.parseSpecifier(t)||Je.create(n)}else return rt(n)?_e.instance(n):typeof n=="object"&&"offset"in n&&typeof n.offset=="function"?n:new sl(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]},rl=Ws.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(Ws.hanidec)!==-1)e+=rl.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 ol(){As.clear()}function Fe({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 Rr=()=>Date.now(),Ir="system",xr=null,Nr=null,Dr=null,Ar=60,Cr,Fr=null;class ce{static get now(){return Rr}static set now(e){Rr=e}static set defaultZone(e){Ir=e}static get defaultZone(){return tt(Ir,Zn.instance)}static get defaultLocale(){return xr}static set defaultLocale(e){xr=e}static get defaultNumberingSystem(){return Nr}static set defaultNumberingSystem(e){Nr=e}static get defaultOutputCalendar(){return Dr}static set defaultOutputCalendar(e){Dr=e}static get defaultWeekSettings(){return Fr}static set defaultWeekSettings(e){Fr=Cs(e)}static get twoDigitCutoffYear(){return Ar}static set twoDigitCutoffYear(e){Ar=e%100}static get throwOnInvalid(){return Cr}static set throwOnInvalid(e){Cr=e}static resetCaches(){ie.resetCache(),Je.resetCache(),V.resetCache(),ol()}}class Me{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const qi=[0,31,59,90,120,151,181,212,243,273,304,334],Bi=[0,31,60,91,121,152,182,213,244,274,305,335];function Ne(n,e){return new Me("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 Hi(n,e,t){return t+(on(n)?Bi:qi)[e-1]}function Gi(n,e){const t=on(n)?Bi:qi,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 Mn(n,e=4,t=1){const{year:s,month:r,day:i}=n,o=Hi(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,...Gn(n)}}function $r(n,e=4,t=1){const{weekYear:s,weekNumber:r,weekday:i}=n,o=zs(js(s,1,e),t),a=It(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=It(c)):l>a?(c=s+1,l-=It(s)):c=s;const{month:u,day:h}=Gi(c,l);return{year:c,month:u,day:h,...Gn(n)}}function is(n){const{year:e,month:t,day:s}=n,r=Hi(e,t,s);return{year:e,ordinal:r,...Gn(n)}}function Mr(n){const{year:e,ordinal:t}=n,{month:s,day:r}=Gi(e,t);return{year:e,month:s,day:r,...Gn(n)}}function Pr(n,e){if(!G(n.localWeekday)||!G(n.localWeekNumber)||!G(n.localWeekYear)){if(!G(n.weekday)||!G(n.weekNumber)||!G(n.weekYear))throw new Tt("Cannot mix locale-based week fields with ISO-based week fields");return G(n.localWeekday)||(n.weekday=n.localWeekday),G(n.localWeekNumber)||(n.weekNumber=n.localWeekNumber),G(n.localWeekYear)||(n.weekYear=n.localWeekYear),delete n.localWeekday,delete n.localWeekNumber,delete n.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function al(n,e=4,t=1){const s=qn(n.weekYear),r=De(n.weekNumber,1,tn(n.weekYear,e,t)),i=De(n.weekday,1,7);return s?r?i?!1:Ne("weekday",n.weekday):Ne("week",n.weekNumber):Ne("weekYear",n.weekYear)}function ll(n){const e=qn(n.year),t=De(n.ordinal,1,It(n.year));return e?t?!1:Ne("ordinal",n.ordinal):Ne("year",n.year)}function Yi(n){const e=qn(n.year),t=De(n.month,1,12),s=De(n.day,1,Pn(n.year,n.month));return e?t?s?!1:Ne("day",n.day):Ne("month",n.month):Ne("year",n.year)}function Ji(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:Ne("millisecond",r):Ne("second",s):Ne("minute",t):Ne("hour",e)}function G(n){return typeof n>"u"}function rt(n){return typeof n=="number"}function qn(n){return typeof n=="number"&&n%1===0}function cl(n){return typeof n=="string"}function ul(n){return Object.prototype.toString.call(n)==="[object Date]"}function Qi(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ki(){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 Lr(n,e,t){if(n.length!==0)return n.reduce((s,r)=>{const i=[e(r),r];return s&&t(s[0],i[0])===s[0]?s:i},null)[1]}function fl(n,e){return e.reduce((t,s)=>(t[s]=n[s],t),{})}function $t(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Cs(n){if(n==null)return null;if(typeof n!="object")throw new pe("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 pe("Invalid week settings");return{firstDay:n.firstDay,minimalDays:n.minimalDays,weekend:Array.from(n.weekend)}}function De(n,e,t){return qn(n)&&n>=e&&n<=t}function hl(n,e){return n-e*Math.floor(n/e)}function de(n,e=2){const t=n<0;let s;return t?s="-"+(""+-n).padStart(e,"0"):s=(""+n).padStart(e,"0"),s}function et(n){if(!(G(n)||n===null||n===""))return parseInt(n,10)}function lt(n){if(!(G(n)||n===null||n===""))return parseFloat(n)}function Zs(n){if(!(G(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 It(n){return on(n)?366:365}function Pn(n,e){const t=hl(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 Bn(n){let e=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return n.year<100&&n.year>=0&&(e=new Date(e),e.setUTCFullYear(n.year,n.month-1,n.day)),+e}function Vr(n,e,t){return-zs(js(n,1,e),t)+e-1}function tn(n,e=4,t=1){const s=Vr(n,e,t),r=Vr(n+1,e,t);return(It(n)-s+r)/7}function Fs(n){return n>99?n:n>ce.twoDigitCutoffYear?1900+n:2e3+n}function Xi(n,e,t,s=null){const r=new Date(n),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(t,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function Hn(n,e){let t=parseInt(n,10);Number.isNaN(t)&&(t=0);const s=parseInt(e,10)||0,r=t<0||Object.is(t,-0)?-s:s;return t*60+r}function eo(n){const e=Number(n);if(typeof n=="boolean"||n===""||!Number.isFinite(e))throw new pe(`Invalid unit value ${n}`);return e}function Ln(n,e){const t={};for(const s in n)if($t(n,s)){const r=n[s];if(r==null)continue;t[e(s)]=eo(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}${de(t,2)}:${de(s,2)}`;case"narrow":return`${r}${t}${s>0?`:${s}`:""}`;case"techie":return`${r}${de(t,2)}${de(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Gn(n){return fl(n,["hour","minute","second","millisecond"])}const ml=["January","February","March","April","May","June","July","August","September","October","November","December"],to=["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 no(n){switch(n){case"narrow":return[...pl];case"short":return[...to];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 so=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],ro=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],yl=["M","T","W","T","F","S","S"];function io(n){switch(n){case"narrow":return[...yl];case"short":return[...ro];case"long":return[...so];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const oo=["AM","PM"],gl=["Before Christ","Anno Domini"],wl=["BC","AD"],_l=["B","A"];function ao(n){switch(n){case"narrow":return[..._l];case"short":return[...wl];case"long":return[...gl];default:return null}}function El(n){return oo[n.hour<12?0:1]}function vl(n,e){return io(e)[n.weekday-1]}function Ol(n,e){return no(e)[n.month-1]}function kl(n,e){return ao(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],u=s?l?c[1]:c[2]||c[1]:l?r[n][0]:n;return o?`${a} ${u} ago`:`in ${a} ${u}`}function Ur(n,e){let t="";for(const s of n)s.literal?t+=s.val:t+=e(s.val);return t}const Tl={D:$n,DD:bi,DDD:Ti,DDDD:Si,t:Ri,tt:Ii,ttt:xi,tttt:Ni,T:Di,TT:Ai,TTT:Ci,TTTT:Fi,f:$i,ff:Pi,fff:Vi,ffff:Wi,F:Mi,FF:Li,FFF:Ui,FFFF:ji};class ye{static create(e,t={}){return new ye(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 de(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,p)=>this.loc.extract(e,f,p),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,p)=>s?Ol(e,f):i(p?{month:f}:{month:f,day:"numeric"},"month"),c=(f,p)=>s?vl(e,f):i(p?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),u=f=>{const p=ye.macroTokenToFormatOpts(f);return p?this.formatWithSystemDefault(e,p):f},h=f=>s?kl(e,f):i({era:f},"era"),d=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 u(f)}};return Ur(ye.parseFormat(t),d)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=u=>{switch(u[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(u,h)=>d=>{const f=r(d);if(f){const p=h.isNegativeDuration&&f!==h.largestUnit?s:1;let O;return this.opts.signMode==="negativeLargestOnly"&&f!==h.largestUnit?O="never":this.opts.signMode==="all"?O="always":O="auto",this.num(u.get(f)*p,d.length,O)}else return d},o=ye.parseFormat(t),a=o.reduce((u,{literal:h,val:d})=>h?u:u.concat(d),[]),l=e.shiftTo(...a.map(r).filter(u=>u)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Ur(o,i(l,c))}}const lo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Mt(...n){const e=n.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function Pt(...n){return e=>n.reduce(([t,s,r],i)=>{const[o,a,l]=i(e,r);return[{...t,...o},a||s,l]},[{},null,1]).slice(0,2)}function Lt(n,...e){if(n==null)return[null,null];for(const[t,s]of e){const r=t.exec(n);if(r)return s(r)}return[null,null]}function co(...n){return(e,t)=>{const s={};let r;for(r=0;r<n.length;r++)s[n[r]]=et(e[t+r]);return[s,null,t+r]}}const uo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Sl=`(?:${uo.source}?(?:\\[(${lo.source})\\])?)?`,Bs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,fo=RegExp(`${Bs.source}${Sl}`),Hs=RegExp(`(?:[Tt]${fo.source})?`),Rl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Il=/(\d{4})-?W(\d\d)(?:-?(\d))?/,xl=/(\d{4})-?(\d{3})/,Nl=co("weekYear","weekNumber","weekDay"),Dl=co("year","ordinal"),Al=/(\d{4})-(\d\d)-(\d\d)/,ho=RegExp(`${Bs.source} ?(?:${uo.source}|(${lo.source}))?`),Cl=RegExp(`(?: ${ho.source})?`);function xt(n,e,t){const s=n[e];return G(s)?t:et(s)}function Fl(n,e){return[{year:xt(n,e),month:xt(n,e+1,1),day:xt(n,e+2,1)},null,e+3]}function Vt(n,e){return[{hours:xt(n,e,0),minutes:xt(n,e+1,0),seconds:xt(n,e+2,0),milliseconds:Zs(n[e+3])},null,e+4]}function an(n,e){const t=!n[e]&&!n[e+1],s=Hn(n[e+1],n[e+2]),r=t?null:_e.instance(s);return[{},r,e+3]}function ln(n,e){const t=n[e]?Je.create(n[e]):null;return[{},t,e+1]}const $l=RegExp(`^T?${Bs.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,u=e[0]==="-",h=l&&l[0]==="-",d=(f,p=!1)=>f!==void 0&&(p||f&&u)?-f:f;return[{years:d(lt(t)),months:d(lt(s)),weeks:d(lt(r)),days:d(lt(i)),hours:d(lt(o)),minutes:d(lt(a)),seconds:d(lt(l),l==="-0"),milliseconds:d(Zs(c),h)}]}const Ll={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(et(e)):et(e),month:to.indexOf(t)+1,day:et(s),hour:et(r),minute:et(i)};return o&&(a.second=et(o)),n&&(a.weekday=n.length>3?so.indexOf(n)+1:ro.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,u,h]=n,d=Gs(e,r,s,t,i,o,a);let f;return l?f=Ll[l]:c?f=0:f=Hn(u,h),[d,new _e(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 Wr(n){const[,e,t,s,r,i,o,a]=n;return[Gs(e,r,s,t,i,o,a),_e.utcInstance]}function ql(n){const[,e,t,s,r,i,o,a]=n;return[Gs(e,a,t,s,r,i,o),_e.utcInstance]}const Bl=Mt(Rl,Hs),Hl=Mt(Il,Hs),Gl=Mt(xl,Hs),Yl=Mt(fo),mo=Pt(Fl,Vt,an,ln),Jl=Pt(Nl,Vt,an,ln),Ql=Pt(Dl,Vt,an,ln),Kl=Pt(Vt,an,ln);function Xl(n){return Lt(n,[Bl,mo],[Hl,Jl],[Gl,Ql],[Yl,Kl])}function ec(n){return Lt(Wl(n),[Vl,Ul])}function tc(n){return Lt(n,[jl,Wr],[zl,Wr],[Zl,ql])}function nc(n){return Lt(n,[Ml,Pl])}const sc=Pt(Vt);function rc(n){return Lt(n,[$l,sc])}const ic=Mt(Al,Cl),oc=Mt(ho),ac=Pt(Vt,an,ln);function lc(n){return Lt(n,[ic,mo],[oc,ac])}const jr="Invalid Duration",po={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},...po},Ie=146097/400,vt=146097/4800,uc={years:{quarters:4,months:12,weeks:Ie/7,days:Ie,hours:Ie*24,minutes:Ie*24*60,seconds:Ie*24*60*60,milliseconds:Ie*24*60*60*1e3},quarters:{months:3,weeks:Ie/28,days:Ie/4,hours:Ie*24/4,minutes:Ie*24*60/4,seconds:Ie*24*60*60/4,milliseconds:Ie*24*60*60*1e3/4},months:{weeks:vt/7,days:vt,hours:vt*24,minutes:vt*24*60,seconds:vt*24*60*60,milliseconds:vt*24*60*60*1e3},...po},ft=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],dc=ft.slice(0).reverse();function Be(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 ne(s)}function yo(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 zr(n,e){const t=yo(n,e)<0?-1:1;ft.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*t,o=n[r][s],a=Math.floor(i/o);e[r]+=a*t,e[s]-=a*o*t}return r},null),ft.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*n[s][r]}return r},null)}function Zr(n){const e={};for(const[t,s]of Object.entries(n))s!==0&&(e[t]=s);return e}class ne{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||ie.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return ne.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new pe(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ne({values:Ln(e,ne.normalizeUnit),loc:ie.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(rt(e))return ne.fromMillis(e);if(ne.isDuration(e))return e;if(typeof e=="object")return ne.fromObject(e);throw new pe(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=nc(e);return s?ne.fromObject(s,t):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=rc(e);return s?ne.fromObject(s,t):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new pe("need to specify a reason the Duration is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new Pa(s);return new ne({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 ki(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?ye.create(this.loc,s).formatDurationFromString(this,e):jr}toHuman(e={}){if(!this.isValid)return jr;const t=e.showZeros!==!1,s=ft.map(r=>{const i=this.values[r];return G(i)||i===0&&!t?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=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},V.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?yo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e),s={};for(const r of ft)($t(t.values,r)||$t(this.values,r))&&(s[r]=t.get(r)+this.get(r));return Be(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const t=ne.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]=eo(e(this.values[s],s));return Be(this,{values:t},!0)}get(e){return this[ne.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...Ln(e,ne.normalizeUnit)};return Be(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 Be(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return zr(this.matrix,e),Be(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=Zr(this.normalize().shiftToAll().toObject());return Be(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>ne.normalizeUnit(o));const t={},s={},r=this.toObject();let i;for(const o of ft)if(e.indexOf(o)>=0){i=o;let a=0;for(const c in s)a+=this.matrix[c][o]*s[c],s[c]=0;rt(r[o])&&(a+=r[o]);const l=Math.trunc(a);t[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else rt(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(t[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return zr(this.matrix,t),Be(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 Be(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=Zr(this.values);return Be(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of ft)if(!t(this.values[s],e.values[s]))return!1;return!0}}const Ot="Invalid Interval";function 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 pe("need to specify a reason the Interval is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new Ma(s);return new le({invalid:s})}static fromDateTimes(e,t){const s=zt(e),r=zt(t),i=fc(s,r);return i??new le({start:s,end:r})}static after(e,t){const s=ne.fromDurationLike(t),r=zt(e);return le.fromDateTimes(r,r.plus(s))}static before(e,t){const s=ne.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=V.fromISO(s,t),o=i.isValid}catch{o=!1}let a,l;try{a=V.fromISO(r,t),l=a.isValid}catch{l=!1}if(o&&l)return le.fromDateTimes(i,a);if(o){const c=ne.fromISO(r,t);if(c.isValid)return le.after(i,c)}else if(l){const c=ne.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=ne.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()})`:Ot}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=$n,t={}){return this.isValid?ye.create(this.s.loc.clone(t),e).formatInterval(this):Ot}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Ot}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Ot}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Ot}toFormat(e,{separator:t=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Ot}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):ne.invalid(this.invalidReason)}mapEndpoints(e){return le.fromDateTimes(e(this.s),e(this.e))}}class fn{static hasDST(e=ce.defaultZone){const t=V.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return Je.isValidZone(e)}static normalizeZone(e){return tt(e,ce.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ie.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return ie.create(t,null,"gregory").eras(e)}static features(){return{relative:Qi(),localeWeek:Ki()}}}function qr(n,e){const t=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(n);return Math.floor(ne.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 u=qr(l,c);return(u-u%7)/7}],["days",qr]],r={},i=n;let o,a;for(const[l,c]of s)t.indexOf(l)>=0&&(o=l,r[l]=c(n,e),a=i.plus(r),a>e?(r[l]--,n=i.plus(r),n>e&&(a=n,r[l]--,n=i.plus(r))):n=a);return[n,r,a,o]}function 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 u=ne.fromObject(i,s);return c.length>0?ne.fromMillis(l,s).shiftTo(...c).plus(u):u}const pc="missing Intl.DateTimeFormat.formatToParts support";function re(n,e=t=>t){return{regex:n,deser:([t])=>e(il(t))}}const yc=" ",go=`[ ${yc}]`,wo=new RegExp(go,"g");function gc(n){return n.replace(/\./g,"\\.?").replace(wo,go)}function Br(n){return n.replace(/\./g,"").replace(wo," ").toLowerCase()}function $e(n,e){return n===null?null:{regex:RegExp(n.map(gc).join("|")),deser:([t])=>n.findIndex(s=>Br(t)===Br(s))+e}}function Hr(n,e){return{regex:n,deser:([,t,s])=>Hn(t,s),groups:e}}function hn(n){return{regex:n,deser:([e])=>e}}function wc(n){return n.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _c(n,e){const t=Fe(e),s=Fe(e,"{2}"),r=Fe(e,"{3}"),i=Fe(e,"{4}"),o=Fe(e,"{6}"),a=Fe(e,"{1,2}"),l=Fe(e,"{1,3}"),c=Fe(e,"{1,6}"),u=Fe(e,"{1,9}"),h=Fe(e,"{2,4}"),d=Fe(e,"{4,6}"),f=y=>({regex:RegExp(wc(y.val)),deser:([g])=>g,literal:!0}),O=(y=>{if(n.literal)return f(y);switch(y.val){case"G":return $e(e.eras("short"),0);case"GG":return $e(e.eras("long"),0);case"y":return re(c);case"yy":return re(h,Fs);case"yyyy":return re(i);case"yyyyy":return re(d);case"yyyyyy":return re(o);case"M":return re(a);case"MM":return re(s);case"MMM":return $e(e.months("short",!0),1);case"MMMM":return $e(e.months("long",!0),1);case"L":return re(a);case"LL":return re(s);case"LLL":return $e(e.months("short",!1),1);case"LLLL":return $e(e.months("long",!1),1);case"d":return re(a);case"dd":return re(s);case"o":return re(l);case"ooo":return re(r);case"HH":return re(s);case"H":return re(a);case"hh":return re(s);case"h":return re(a);case"mm":return re(s);case"m":return re(a);case"q":return re(a);case"qq":return re(s);case"s":return re(a);case"ss":return re(s);case"S":return re(l);case"SSS":return re(r);case"u":return hn(u);case"uu":return hn(a);case"uuu":return re(t);case"a":return $e(e.meridiems(),0);case"kkkk":return re(i);case"kk":return re(h,Fs);case"W":return re(a);case"WW":return re(s);case"E":case"c":return re(t);case"EEE":return $e(e.weekdays("short",!1),1);case"EEEE":return $e(e.weekdays("long",!1),1);case"ccc":return $e(e.weekdays("short",!0),1);case"cccc":return $e(e.weekdays("long",!0),1);case"Z":case"ZZ":return Hr(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return Hr(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return hn(/[a-z_+-/]{1,256}?/i);case" ":return hn(/[^\S\n\r]/);default:return f(y)}})(n)||{invalidReason:pc};return O.token=n,O}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($t(t,o)){const a=t[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function 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 G(n.z)||(t=Je.create(n.z)),G(n.Z)||(t||(t=new _e(n.Z)),s=n.Z),G(n.q)||(n.M=(n.q-1)*3+1),G(n.h)||(n.h<12&&n.a===1?n.h+=12:n.h===12&&n.a===0&&(n.h=0)),n.G===0&&n.y&&(n.y=-n.y),G(n.u)||(n.S=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=V.fromMillis(1555555555555)),os}function Sc(n,e){if(n.literal)return n;const t=ye.macroTokenToFormatOpts(n.val),s=Oo(t,e);return s==null||s.includes(void 0)?n:s}function _o(n,e){return Array.prototype.concat(...n.map(t=>Sc(t,e)))}class Eo{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=_o(ye.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($t(s,"a")&&$t(s,"H"))throw new Tt("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 vo(n,e,t){return new Eo(n,t).explainFromTokens(e)}function Rc(n,e,t){const{result:s,zone:r,specificOffset:i,invalidReason:o}=vo(n,e,t);return[s,r,i,o]}function Oo(n,e){if(!n)return null;const s=ye.create(e,n).dtFormatter(Tc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>vc(o,n,i))}const as="Invalid DateTime",Gr=864e13;function Ht(n){return new Me("unsupported zone",`the zone "${n.name}" is not supported`)}function ls(n){return n.weekData===null&&(n.weekData=Mn(n.c)),n.weekData}function cs(n){return n.localWeekData===null&&(n.localWeekData=Mn(n.c,n.loc.getMinDaysInFirstWeek(),n.loc.getStartOfWeek())),n.localWeekData}function ct(n,e){const t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new V({...t,...e,old:t})}function ko(n,e,t){let s=n-e*60*1e3;const r=t.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=t.offset(s);return r===i?[s,r]:[n-Math.min(r,i)*60*1e3,Math.max(r,i)]}function mn(n,e){n+=e*60*1e3;const t=new Date(n);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function wn(n,e,t){return ko(Bn(n),e,t)}function Yr(n,e){const t=n.o,s=n.c.year+Math.trunc(e.years),r=n.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...n.c,year:s,month:r,day:Math.min(n.c.day,Pn(s,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=ne.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=Bn(i);let[l,c]=ko(a,t,n.zone);return o!==0&&(l+=o,c=n.zone.offset(l)),{ts:l,o:c}}function kt(n,e,t,s,r,i){const{setZone:o,zone:a}=t;if(n&&Object.keys(n).length!==0||e){const l=e||a,c=V.fromObject(n,{...t,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return V.invalid(new Me("unparsable",`the input "${r}" can't be parsed as ${s}`))}function pn(n,e,t=!0){return n.isValid?ye.create(ie.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+=de(n.c.year,s?6:4),t==="year")return r;if(e){if(r+="-",r+=de(n.c.month),t==="month")return r;r+="-"}else if(r+=de(n.c.month),t==="month")return r;return r+=de(n.c.day),r}function Jr(n,e,t,s,r,i,o){let a=!t||n.c.millisecond!==0||n.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=de(n.c.hour),o==="hour")break;if(e){if(l+=":",l+=de(n.c.minute),o==="minute")break;a&&(l+=":",l+=de(n.c.second))}else{if(l+=de(n.c.minute),o==="minute")break;a&&(l+=de(n.c.second))}if(o==="second")break;a&&(!s||n.c.millisecond!==0)&&(l+=".",l+=de(n.c.millisecond,3))}return r&&(n.isOffsetFixed&&n.offset===0&&!i?l+="Z":n.o<0?(l+="-",l+=de(Math.trunc(-n.o/60)),l+=":",l+=de(Math.trunc(-n.o%60))):(l+="+",l+=de(Math.trunc(n.o/60)),l+=":",l+=de(Math.trunc(n.o%60)))),i&&(l+="["+n.zone.ianaName+"]"),l}const bo={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ic={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},xc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},_n=["year","month","day","hour","minute","second","millisecond"],Nc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Dc=["year","ordinal","hour","minute","second","millisecond"];function En(n){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[n.toLowerCase()];if(!e)throw new ki(n);return e}function Qr(n){switch(n.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return En(n)}}function Ac(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 Kr(n,e){const t=tt(e.zone,ce.defaultZone);if(!t.isValid)return V.invalid(Ht(t));const s=ie.fromObject(e);let r,i;if(G(n.year))r=ce.now();else{for(const l of _n)G(n[l])&&(n[l]=bo[l]);const o=Yi(n)||Ji(n);if(o)return V.invalid(o);const a=Ac(t);[r,i]=wn(n,a,t)}return new V({ts:r,zone:t,loc:s,o:i})}function Xr(n,e,t){const s=G(t.round)?!0:t.round,r=G(t.rounding)?"trunc":t.rounding,i=(a,l)=>(a=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 ei(n){let e={},t;return n.length>0&&typeof n[n.length-1]=="object"?(e=n[n.length-1],t=Array.from(n).slice(0,n.length-1)):t=Array.from(n),[e,t]}let Gt;const $s=new Map;class V{constructor(e){const t=e.zone||ce.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Me("invalid input"):null)||(t.isValid?null:Ht(t));this.ts=G(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=rt(e.o)&&!e.old?e.o:t.offset(this.ts);r=mn(this.ts,a),s=Number.isNaN(r.year)?new Me("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=t,this.loc=e.loc||ie.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new V({})}static local(){const[e,t]=ei(arguments),[s,r,i,o,a,l,c]=t;return Kr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,t]=ei(arguments),[s,r,i,o,a,l,c]=t;return e.zone=_e.utcInstance,Kr({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){const s=ul(e)?e.valueOf():NaN;if(Number.isNaN(s))return V.invalid("invalid input");const r=tt(t.zone,ce.defaultZone);return r.isValid?new V({ts:s,zone:r,loc:ie.fromObject(t)}):V.invalid(Ht(r))}static fromMillis(e,t={}){if(rt(e))return e<-Gr||e>Gr?V.invalid("Timestamp out of range"):new V({ts:e,zone:tt(t.zone,ce.defaultZone),loc:ie.fromObject(t)});throw new pe(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(rt(e))return new V({ts:e*1e3,zone:tt(t.zone,ce.defaultZone),loc:ie.fromObject(t)});throw new pe("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=tt(t.zone,ce.defaultZone);if(!s.isValid)return V.invalid(Ht(s));const r=ie.fromObject(t),i=Ln(e,Qr),{minDaysInFirstWeek:o,startOfWeek:a}=Pr(i,r),l=ce.now(),c=G(t.specificOffset)?s.offset(l):t.specificOffset,u=!G(i.ordinal),h=!G(i.year),d=!G(i.month)||!G(i.day),f=h||d,p=i.weekYear||i.weekNumber;if((f||u)&&p)throw new Tt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(d&&u)throw new Tt("Can't mix ordinal dates with month/day");const O=p||i.weekday&&!f;let y,g,N=mn(l,c);O?(y=Nc,g=Ic,N=Mn(N,o,a)):u?(y=Dc,g=xc,N=is(N)):(y=_n,g=bo);let b=!1;for(const m of y){const $=i[m];G($)?b?i[m]=g[m]:i[m]=N[m]:b=!0}const x=O?al(i,o,a):u?ll(i):Yi(i),v=x||Ji(i);if(v)return V.invalid(v);const C=O?$r(i,o,a):u?Mr(i):i,[_,z]=wn(C,c,s),k=new V({ts:_,zone:s,o:z,loc:r});return i.weekday&&f&&e.weekday!==k.weekday?V.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${k.toISO()}`):k.isValid?k:V.invalid(k.invalid)}static fromISO(e,t={}){const[s,r]=Xl(e);return kt(s,r,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,r]=ec(e);return kt(s,r,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,r]=tc(e);return kt(s,r,t,"HTTP",t)}static fromFormat(e,t,s={}){if(G(e)||G(t))throw new pe("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,u]=Rc(o,e,t);return u?V.invalid(u):kt(a,l,s,`format ${t}`,e,c)}static fromString(e,t,s={}){return V.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,r]=lc(e);return kt(s,r,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new pe("need to specify a reason the DateTime is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new $a(s);return new V({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=Oo(e,ie.fromObject(t));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,t={}){return _o(ye.parseFormat(e),ie.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?fn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?fn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?fn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?fn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,t=6e4,s=Bn(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*t),a=this.zone.offset(s-i*t);if(o===a)return[this];const l=s-o*t,c=s-a*t,u=mn(l,o),h=mn(c,a);return u.hour===h.hour&&u.minute===h.minute&&u.second===h.second&&u.millisecond===h.millisecond?[ct(this,{ts:l}),ct(this,{ts:c})]:[this]}get isInLeapYear(){return on(this.year)}get daysInMonth(){return Pn(this.year,this.month)}get daysInYear(){return this.isValid?It(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}=ye.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(_e.instance(e),t)}toLocal(){return this.setZone(ce.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=tt(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]=wn(o,i,e)}return ct(this,{ts:r,zone:e})}else return V.invalid(Ht(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return ct(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=Ln(e,Qr),{minDaysInFirstWeek:s,startOfWeek:r}=Pr(t,this.loc),i=!G(t.weekYear)||!G(t.weekNumber)||!G(t.weekday),o=!G(t.ordinal),a=!G(t.year),l=!G(t.month)||!G(t.day),c=a||l,u=t.weekYear||t.weekNumber;if((c||o)&&u)throw new Tt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new Tt("Can't mix ordinal dates with month/day");let h;i?h=$r({...Mn(this.c,s,r),...t},s,r):G(t.ordinal)?(h={...this.toObject(),...t},G(t.day)&&(h.day=Math.min(Pn(h.year,h.month),h.day))):h=Mr({...is(this.c),...t});const[d,f]=wn(h,this.o,this.zone);return ct(this,{ts:d,o:f})}plus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e);return ct(this,Yr(this,t))}minus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e).negate();return ct(this,Yr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},r=ne.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?ye.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):as}toLocaleString(e=$n,t={}){return this.isValid?ye.create(this.loc.clone(t),e).formatDateTime(this):as}toLocaleParts(e={}){return this.isValid?ye.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=En(o);const a=e==="extended";let l=us(this,a,o);return _n.indexOf(o)>=3&&(l+="T"),l+=Jr(this,a,t,s,r,i,o),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?us(this,e==="extended",En(t)):null}toISOWeekDate(){return pn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=En(a),(r&&_n.indexOf(a)>=3?"T":"")+Jr(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return pn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return pn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?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")),pn(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 ne.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=dl(t).map(ne.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(V.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||V.fromObject({},{zone:this.zone}),s=e.padding?this<t?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),Xr(t,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?Xr(e.base||V.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(V.isDateTime))throw new pe("min requires all arguments be DateTimes");return Lr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(V.isDateTime))throw new pe("max requires all arguments be DateTimes");return Lr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return vo(o,e,t)}static fromStringExplain(e,t,s={}){return V.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:r=null}=t,i=ie.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new Eo(i,e)}static fromFormatParser(e,t,s={}){if(G(e)||G(t))throw new pe("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new pe(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:u}=t.explainFromTokens(e);return u?V.invalid(u):kt(a,l,s,`format ${t.format}`,e,c)}static get DATE_SHORT(){return $n}static get DATE_MED(){return bi}static get DATE_MED_WITH_WEEKDAY(){return La}static get DATE_FULL(){return Ti}static get DATE_HUGE(){return Si}static get TIME_SIMPLE(){return Ri}static get TIME_WITH_SECONDS(){return Ii}static get TIME_WITH_SHORT_OFFSET(){return xi}static get TIME_WITH_LONG_OFFSET(){return Ni}static get TIME_24_SIMPLE(){return Di}static get TIME_24_WITH_SECONDS(){return Ai}static get TIME_24_WITH_SHORT_OFFSET(){return Ci}static get TIME_24_WITH_LONG_OFFSET(){return Fi}static get DATETIME_SHORT(){return $i}static get DATETIME_SHORT_WITH_SECONDS(){return Mi}static get DATETIME_MED(){return Pi}static get DATETIME_MED_WITH_SECONDS(){return Li}static get DATETIME_MED_WITH_WEEKDAY(){return Va}static get DATETIME_FULL(){return Vi}static get DATETIME_FULL_WITH_SECONDS(){return Ui}static get DATETIME_HUGE(){return Wi}static get DATETIME_HUGE_WITH_SECONDS(){return ji}}function zt(n){if(V.isDateTime(n))return n;if(n&&n.valueOf&&rt(n.valueOf()))return V.fromJSDate(n);if(n&&typeof n=="object")return V.fromObject(n);throw new pe(`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 sn(me());n.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?t[r]=To(i)?.nullable():t[r]=me()})}return Ue({Collection_Path:wt(ke()),...t})},Fc=(n,e,t,s)=>{let r=Ue({}).catchall(Cc(n,e)),i;if(!s&&t){const o=Ae(n,t);i=Zt(o.admin?.skipFormRequiredValidation)}return(!n.required||i)&&(r=r.optional()),r},$c=()=>me().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Must be a valid date"}),To=(n,e,t)=>{let s;const r=`${Zt(n.description)}
2
2
 
3
- `||"";let i,o,a;if(!t&&e){const l=Ae(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=Ee([s.uuid("Must be a valid UUID"),Oe("")]):n.url?s=Ee([s.url("Must be a valid URL"),Oe("")]):n.emoji?s=Ee([s.emoji("Must be a valid emoji"),Oe("")]):n.ip?s=Ee([s.ip("Must be a valid IP address"),Oe("")]):n.pattern&&(!t&&a?s=Ee([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=Ee([Cn(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=Ee([ts(),dt().int()],{message:"Must be a valid number"}):(s=dt({message:"Must be a valid number"}),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=Ee([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:dt(),nanoseconds:dt()}),n.min&&n.max?s=s.describe(`${r}Must be between ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)} and ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`):n.min?s=s.describe(`${r}Must be greater than or equal to ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)}`):n.max?s=s.describe(`${r}Must be less than or equal to ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=$c(),n.min&&(s=s.refine(l=>l.toMillis()>=n.min,{message:`Must be greater than or equal to ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)}`})),n.max&&(s=s.refine(l=>l.toMillis()<=n.max,{message:`Must be less than or equal to ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`})));break;case"Array":s=wt(me()),n.length&&(s=s.length(n.length,`Must contain ${n.length} item(s)`)),n.minlength?s=s.min(n.minlength,`Must contain at least ${n.minlength} item(s)`):n.required&&!i&&(s=s.nonempty("Must contain at least one item")),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} item(s)`)),n.values?(t||(s=s.refine(l=>{let c=!0;return l.forEach(u=>{n.values&&!n.values.includes(u)&&(c=!1)}),c},{message:`Must only contain the following values: ${n.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())),n.nullable&&(s=s.nullable());break;case"Map":n.required&&!i?t?s=Ue({}).catchall(me()).describe(`${r}Must be an object. Must contain at least one object property.`):s=sn(me()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=Ue({}).catchall(me()).describe(`${r}Must be an object`);break;case"Computed":s=me()}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)||(X(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(u=>c.length&&u&&Object.keys(u).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(u=>c.min&&u&&Object.keys(u).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(u=>c.max&&(!u||Object.keys(u).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=To(c,t,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=Ee([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}`]=wt(Ee([Oe("Read"),Oe("Create"),Oe("Update"),Oe("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=Qt().optional(),c.access.attributeRestrictions?.forEach(u=>{a[`attribute-${c.labels.collection}-${u.type}`]=Qt().optional()}),c.access.entityRestrictions?.restrictions?.forEach(u=>{if(u.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=Ue({}).catchall(me()).optional()),u.type==="Parent"||u.type==="Parent_Property"){const h=W(c.fields,u.collectionField);a[`accessible-${c.labels.collection}-${h.collection}`]=Ue({}).catchall(me()).optional()}})}));const l=Ue(a);return n.allowSchemalessFields?l.passthrough():l.strict()},ti=async(n,e)=>{if(n){const t=await oe(n,e);if(!t.valid)throw new Error(t.message)}},nn=async(n,e,t,s,r,i)=>{await ti(s.custom?.preValidate,r);for(const a of s.fields)await ti(a.custom?.preValidate,r);return Oi(n,t,i).parse(e),e},Ys=(n,e,t,s,r,i,o,a,l,c,u,h,d,f,p,O,y,g,N,b,x)=>{const{fields:E}=o;E.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}),x&&x.size++)}),E.forEach(m=>{if(at(m,o,i)){const $=un(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`])),$.forEach(H=>{r[H.name]!==void 0&&(X(H)?v[`${H.name}_Array`]=r[`${H.name}_Array`]:v[H.name]=r[H.name])}),Object.keys(v).length>0&&(n==="create"&&(v.Collection_Path=t,v.Collection_Path_String=t.join("/"),e.set(d(m),v)),n==="update"&&e.update(d(m),v),n==="delete"&&e.delete(d(m)),x&&x.size++)}});const C=l[o.labels.collection];for(const m of C){const $=ia(m,o),v={...r};$.forEach(H=>{delete v[H.name],delete v[`${H.name}_Array`],delete v[`${H.name}_Single`],delete v[`${H.name}_Lowercase`]}),Object.keys(v).length>0&&(n==="create"&&(v.Collection_Path||=t,v.Collection_Path_String=t.join("/"),e.set(p(m.key),v)),n==="update"&&e.update(p(m.key),v),n==="delete"&&e.delete(p(m.key)),x&&x.size++)}const _=(m,$)=>{let v=1;at($,m,i)&&v++,m.fields.forEach(w=>{at(w,m,i)&&JSON.parse(Kn(un(w,m,i))).includes($.name)&&v++});const H=l[m.labels.collection];for(const w of H)w.fields.some(I=>I.name===$.name)&&X($)&&v++;return v},z=(m,$,v,H,w)=>{const I={};I[`${v.name}.${s}`]=h(),I[`${v.name}_Array`]=u(s),I[`${v.name}_Single`]=h(),e.update(O(w,H),I),at(v,$,i)&&e.update(y(m,v.name,H),{[`${v.name}.${s}`]:h(),[`${v.name}_Array`]:u(s)}),$.fields.forEach(R=>{at(R,$,i)&&JSON.parse(Kn(un(R,$,i))).includes(v.name)&&e.update(y(m,R.name,H),{[`${v.name}_Array`]:u(s)})});const T=l[$.labels.collection];for(const R of T)R.fields.some(A=>A.name===v.name)&&X(v)&&e.update(g(m,R.key,H),I)};if(n==="delete")return;const k=E.filter(m=>X(m)&&m.twoWay);if(!a?.noTwoWay){for(const m of k){if(!x)throw new Error("VALIDATION_ERROR: batchSize is required");const $=i.collections[m.collection],v=W($.fields,m.twoWay),H=ut($,$.fields),w=Array.from(H).map(I=>I.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[I,T]of Object.entries(r[m.name])){if(n==="update"&&N&&N[`${m.name}_Array`]?.includes(I))continue;const R={...N,...r};nt(R);const A={};v.includeFields&&v.includeFields.forEach(L=>{if(R[L]!==void 0){A[L]=R[L];const Z=W(o.fields,L);gt(o,[Z]).size===1&&(A[`${L}_Lowercase`]=R[`${L}_Lowercase`])}});const q={[`${m.twoWay}.${s}`]:{Collection_Path:t,...A},[`${m.twoWay}_Array`]:c(s)};w.includes(v.name)&&(q[`${m.twoWay}_Single`]={Collection_Path:t,id:s,...A});const P=bn(r);e.update(O(T.Collection_Path,I),{...q,...P}),x.size++,at(v,$,i)&&(e.update(y(m,v.name,I),{[`${v.name}.${s}`]:{Collection_Path:t,...A},[`${v.name}_Array`]:c(s)}),x.size++),$.fields.forEach(L=>{if(at(L,$,i)){const Z=JSON.parse(Kn(un(L,$,i))),K={};Z.includes(v.name)&&(K[`${m.twoWay}_Array`]=c(s)),Object.keys(P).forEach(te=>{Z.includes(te)&&(K[te]=P[te])}),Object.keys(K).length>0&&(e.update(y(m,L.name,I),K),x.size++)}});const S=l[$.labels.collection];for(const L of S)if(L.fields.some(Z=>Z.name===v.name)){const Z={...q};Object.keys(P).forEach(K=>{L.fields.some(te=>te.name===K)&&(Z[K]=P[K])}),Object.keys(Z).length>0&&(e.update(g(m,L.key,I),Z),x.size++)}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${v.type}`)}x&&x.size>500&&console.error(new Error(`VALIDATION_ERROR: ${x.size} operations in the Firestore transaction has exceeded the recommended 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 k){if(!x)throw new Error("VALIDATION_ERROR: batchSize is required");const $=i.collections[m.collection],v=W($.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"&&N&&!(r[m.name]&&xe(r[m.name]))&&r[`${m.name}_Array`]&&N[`${m.name}_Array`]?.length>0)for(const[H,w]of Object.entries(N[m.name]))!r[`${m.name}_Array`].includes(H)&&!b?.get(m.name)?.includes(H)&&(x.size+=_($,v),x.size<=500&&z(m,$,v,H,w.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${v.type}`)}for(const m of k){if(!x)throw new Error("VALIDATION_ERROR: batchSize is required");const $=i.collections[m.collection],v=W($.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"&&N&&r[m.name]&&xe(r[m.name])&&N[`${m.name}_Array`]?.length>0)for(const[H,w]of Object.entries(N[m.name]))b?.get(m.name)?.includes(H)||(x.size+=_($,v),x.size<=500&&z(m,$,v,H,w.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]))},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)},ni=async(n,e,t,s=1e3,r=5)=>{for(;r>0;)try{await n(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Vn=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},ds=n=>n?Array.isArray(n)?n.map(s=>Vn(s)).filter(s=>s.length>0):Vn(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},si=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
3
+ `||"";let i,o,a;if(!t&&e){const l=Ae(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([Cn(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(),dt().int()],{message:"Must be a valid number"}):(s=dt({message:"Must be a valid number"}),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:dt(),nanoseconds:dt()}),n.min&&n.max?s=s.describe(`${r}Must be between ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)} and ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`):n.min?s=s.describe(`${r}Must be greater than or equal to ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)}`):n.max?s=s.describe(`${r}Must be less than or equal to ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=$c(),n.min&&(s=s.refine(l=>l.toMillis()>=n.min,{message:`Must be greater than or equal to ${V.fromMillis(n.min).toLocaleString(V.DATE_MED)}`})),n.max&&(s=s.refine(l=>l.toMillis()<=n.max,{message:`Must be less than or equal to ${V.fromMillis(n.max).toLocaleString(V.DATE_MED)}`})));break;case"Array":s=wt(me()),n.length&&(s=s.length(n.length,`Must contain ${n.length} item(s)`)),n.minlength?s=s.min(n.minlength,`Must contain at least ${n.minlength} item(s)`):n.required&&!i&&(s=s.nonempty("Must contain at least one item")),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} item(s)`)),n.values?(t||(s=s.refine(l=>{let c=!0;return l.forEach(u=>{n.values&&!n.values.includes(u)&&(c=!1)}),c},{message:`Must only contain the following values: ${n.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())),n.nullable&&(s=s.nullable());break;case"Map":n.required&&!i?t?s=Ue({}).catchall(me()).describe(`${r}Must be an object. Must contain at least one object property.`):s=sn(me()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=Ue({}).catchall(me()).describe(`${r}Must be an object`);break;case"Computed":s=me()}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)||(X(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(u=>c.length&&u&&Object.keys(u).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(u=>c.min&&u&&Object.keys(u).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(u=>c.max&&(!u||Object.keys(u).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=To(c,t,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=ve([Oe("create"),Oe("update"),Oe("delete")]).optional(),a.password=ke().optional(),a.passwordConfirm=ke().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=Qt().optional(),a[`operations-${c.labels.collection}`]=wt(ve([Oe("Read"),Oe("Create"),Oe("Update"),Oe("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=Qt().optional(),c.access.attributeRestrictions?.forEach(u=>{a[`attribute-${c.labels.collection}-${u.type}`]=Qt().optional()}),c.access.entityRestrictions?.restrictions?.forEach(u=>{if(u.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=Ue({}).catchall(me()).optional()),u.type==="Parent"||u.type==="Parent_Property"){const h=W(c.fields,u.collectionField);a[`accessible-${c.labels.collection}-${h.collection}`]=Ue({}).catchall(me()).optional()}})}));const l=Ue(a);return n.allowSchemalessFields?l.passthrough():l.strict()},ti=async(n,e)=>{if(n){const t=await oe(n,[e]);if(!t.valid)throw new Error(t.message)}},nn=async(n,e,t,s,r,i)=>{await ti(s.custom?.preValidate,r);for(const a of s.fields)await ti(a.custom?.preValidate,r);return Oi(n,t,i).parse(e),e},Ys=(n,e,t,s,r,i,o,a,l,c,u,h,d,f,p,O,y,g,N,b,x)=>{const{fields:v}=o;v.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}),x&&x.size++)}),v.forEach(m=>{if(at(m,o,i)){const $=un(m,o,i),E={};r[m.name]!==void 0&&(E[m.name]=r[m.name],X(m)&&(E[`${m.name}_Array`]=r[`${m.name}_Array`])),$.forEach(H=>{r[H.name]!==void 0&&(X(H)?E[`${H.name}_Array`]=r[`${H.name}_Array`]:E[H.name]=r[H.name])}),Object.keys(E).length>0&&(n==="create"&&(E.Collection_Path=t,E.Collection_Path_String=t.join("/"),e.set(d(m),E)),n==="update"&&e.update(d(m),E),n==="delete"&&e.delete(d(m)),x&&x.size++)}});const C=l[o.labels.collection];for(const m of C){const $=ia(m,o),E={...r};$.forEach(H=>{delete E[H.name],delete E[`${H.name}_Array`],delete E[`${H.name}_Single`],delete E[`${H.name}_Lowercase`]}),Object.keys(E).length>0&&(n==="create"&&(E.Collection_Path||=t,E.Collection_Path_String=t.join("/"),e.set(p(m.key),E)),n==="update"&&e.update(p(m.key),E),n==="delete"&&e.delete(p(m.key)),x&&x.size++)}const _=(m,$)=>{let E=1;at($,m,i)&&E++,m.fields.forEach(w=>{at(w,m,i)&&JSON.parse(Kn(un(w,m,i))).includes($.name)&&E++});const H=l[m.labels.collection];for(const w of H)w.fields.some(I=>I.name===$.name)&&X($)&&E++;return E},z=(m,$,E,H,w)=>{const I={};I[`${E.name}.${s}`]=h(),I[`${E.name}_Array`]=u(s),I[`${E.name}_Single`]=h(),e.update(O(w,H),I),at(E,$,i)&&e.update(y(m,E.name,H),{[`${E.name}.${s}`]:h(),[`${E.name}_Array`]:u(s)}),$.fields.forEach(R=>{at(R,$,i)&&JSON.parse(Kn(un(R,$,i))).includes(E.name)&&e.update(y(m,R.name,H),{[`${E.name}_Array`]:u(s)})});const T=l[$.labels.collection];for(const R of T)R.fields.some(A=>A.name===E.name)&&X(E)&&e.update(g(m,R.key,H),I)};if(n==="delete")return;const k=v.filter(m=>X(m)&&m.twoWay);if(!a?.noTwoWay){for(const m of k){if(!x)throw new Error("VALIDATION_ERROR: batchSize is required");const $=i.collections[m.collection],E=W($.fields,m.twoWay),H=ut($,$.fields),w=Array.from(H).map(I=>I.name);if(!E)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(X(E)){if(r[`${m.name}_Array`])for(const[I,T]of Object.entries(r[m.name])){if(n==="update"&&N&&N[`${m.name}_Array`]?.includes(I))continue;const R={...N,...r};nt(R);const A={};E.includeFields&&E.includeFields.forEach(L=>{if(R[L]!==void 0){A[L]=R[L];const Z=W(o.fields,L);gt(o,[Z]).size===1&&(A[`${L}_Lowercase`]=R[`${L}_Lowercase`])}});const q={[`${m.twoWay}.${s}`]:{Collection_Path:t,...A},[`${m.twoWay}_Array`]:c(s)};w.includes(E.name)&&(q[`${m.twoWay}_Single`]={Collection_Path:t,id:s,...A});const P=bn(r);e.update(O(T.Collection_Path,I),{...q,...P}),x.size++,at(E,$,i)&&(e.update(y(m,E.name,I),{[`${E.name}.${s}`]:{Collection_Path:t,...A},[`${E.name}_Array`]:c(s)}),x.size++),$.fields.forEach(L=>{if(at(L,$,i)){const Z=JSON.parse(Kn(un(L,$,i))),K={};Z.includes(E.name)&&(K[`${m.twoWay}_Array`]=c(s)),Object.keys(P).forEach(te=>{Z.includes(te)&&(K[te]=P[te])}),Object.keys(K).length>0&&(e.update(y(m,L.name,I),K),x.size++)}});const S=l[$.labels.collection];for(const L of S)if(L.fields.some(Z=>Z.name===E.name)){const Z={...q};Object.keys(P).forEach(K=>{L.fields.some(te=>te.name===K)&&(Z[K]=P[K])}),Object.keys(Z).length>0&&(e.update(g(m,L.key,I),Z),x.size++)}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${E.type}`)}x&&x.size>500&&console.error(new Error(`VALIDATION_ERROR: ${x.size} operations in the Firestore transaction has exceeded the recommended 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 k){if(!x)throw new Error("VALIDATION_ERROR: batchSize is required");const $=i.collections[m.collection],E=W($.fields,m.twoWay);if(!E)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(X(E)){if(n==="update"&&N&&!(r[m.name]&&xe(r[m.name]))&&r[`${m.name}_Array`]&&N[`${m.name}_Array`]?.length>0)for(const[H,w]of Object.entries(N[m.name]))!r[`${m.name}_Array`].includes(H)&&!b?.get(m.name)?.includes(H)&&(x.size+=_($,E),x.size<=500&&z(m,$,E,H,w.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${E.type}`)}for(const m of k){if(!x)throw new Error("VALIDATION_ERROR: batchSize is required");const $=i.collections[m.collection],E=W($.fields,m.twoWay);if(!E)throw new Error(`SCHEMA_ERROR: Field ${m.twoWay} not found in collection ${m.collection}`);if(X(E)){if(n==="update"&&N&&r[m.name]&&xe(r[m.name])&&N[`${m.name}_Array`]?.length>0)for(const[H,w]of Object.entries(N[m.name]))b?.get(m.name)?.includes(H)||(x.size+=_($,E),x.size<=500&&z(m,$,E,H,w.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${E.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]))},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)},ni=async(n,e,t,s=1e3,r=5)=>{for(;r>0;)try{await n(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Vn=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},ds=n=>n?Array.isArray(n)?n.map(s=>Vn(s)).filter(s=>s.length>0):Vn(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},si=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},So=async(n,e)=>{const t={};for(const s of e){const r=`${n}/${s}.js`,i=ai.pathToFileURL(r).href;t[s]=await import(i)}return t};let fs,Ro,En,Io,Yt,xo,On,kn,hs=0,ri=!1;const St={getTenant(){if(!En)throw new Error("Tenant not provided");return En},setTenant(n){En=n},getMode(){return Ro},getTimezone(){return Io},getGlobalConfigModule(){return he(Yt)},getCustomizationFile(n,e){if(!Object.keys(e.collections).includes(n))throw new Error("PERMISSION_DENIED");const t=ta([n],xo,"node",St);return he(t?.[n])},getVersionInfo(){return On},getMaintenanceInfo(){return kn}},Lc=async(n,e,t,s,r)=>{const i=!!ri;if(ri=!0,e&&(En=e),Ro=n,fs&&!r)return St;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const o=process.env.STOKER_FB_WEB_APP_CONFIG,a=JSON.parse(o),u=(await import(ai.pathToFileURL(t).href)).default;Yt=u("node",St),!r&&n==="development"&&(process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099",process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000",process.env.FIRESTORE_EMULATOR_HOST="127.0.0.1:8080",process.env.FIREBASE_STORAGE_EMULATOR_HOST="127.0.0.1:9199");try{fs=Rt.getApp()}catch{fs=Rt.initializeApp({credential:Rt.applicationDefault(),databaseURL:a.databaseURL,storageBucket:a.storageBucket,projectId:a.projectId})}const h=await je();return xo=await So(s,Object.keys(h.collections)),Io=await oe(Yt.timezone),i||B.getFirestore().collection("system_deployment").doc("maintenance_mode").onSnapshot(d=>{d.exists?(kn=d.data(),oe(Yt.onMaintenanceUpdate,["node",kn.active?"on":"off"])):console.error("Maintenance status not found")},d=>{console.error(d.message)}),i||B.getFirestore().collection("system_deployment").doc("latest_deploy").onSnapshot(d=>{d.exists?(On=d.data(),hs++,hs>1&&oe(Yt.onVersionUpdate,["node",On,hs])):console.error("Version info not found")},d=>{console.error(d.message)}),await new Promise(d=>{const f=()=>{kn&&On?d(St):setTimeout(f,100)};f()}),St},{getTenant:ze,setTenant:Vc,getMode:Qs,getTimezone:Ks,getGlobalConfigModule:vt,getCustomizationFile:Ze,getVersionInfo:Uc,getMaintenanceInfo:Wc}=St,jc=async(n,e,t,s)=>new Promise((r,i)=>{const o=zo(n,e,{cwd:t||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},u=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout?.on("data",h=>{a+=h.toString(),console.log(h.toString())}),o.stderr?.on("data",h=>{console.log(h.toString())}),o.on("exit",h=>{u(),h===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),zc=async()=>{const n=process.env.STOKER_FB_WEB_APP_CONFIG;if(!n)throw new Error("Firebase web app config not found");const e=JSON.parse(n);try{return Rt.getApp()}catch{return Rt.initializeApp({credential:Rt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},je=async(n=!1)=>{const s=await li.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=Ae(o,Ze(i.labels.collection,r));a.formula&&(o.formula=a.formula)}}else for(const i of Object.values(r.collections))i.fields=i.fields.filter(o=>o.type!=="Computed");return r},Zc=async()=>{const t=await li.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(t.numChildren()<2))return Object.values(t.val())[0]},Se=(n,e,t)=>{let s=n.collection("tenants").doc(t);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},No=(n,e,t,s,r)=>{const i=B.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=t.collections[o],{labels:l,fields:c,preloadCache:u}=a,h=Ze(o,t),d=Se(i,e,n);if(r)if(s){const f=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const p=f&&be("Read",f),O=fi(a,t,r),y=ui(a,r),g=Ms(a,r),N=di(a,t,r),b=(w=[])=>{const I=[],T=gi(r.Role,a,t);if(!T)throw new Error("PERMISSION_DENIED");if(p){let R=i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${T.key}`).where("Collection_Path_String","==",e.join("/"));w.forEach(A=>{R=R.where(...A)}),I.push(R)}else if(O)for(const R of O){let A=i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${R.field}`).where("Collection_Path_String","==",e.join("/"));w.forEach(q=>{A=A.where(...q)}),I.push(A)}return I},x=y.filter(w=>"operations"in w&&w.operations?w.operations.includes("Read"):!0);if(x.length===0&&g.length===0&&N.length===0)return b();let E=0;const C=w=>{w&&(E===0?E=w:E*=w)};if(x.length>0){for(const w of x)if(w.operations&&w.type==="Record_Property"){const I=w.roles.find(T=>T.role===r.Role);if(!I)throw new Error("PERMISSION_DENIED");C(I.values?.length)}}u?.roles.includes(r.Role)&&u.range&&C(u.range.fields.length);const _=h.admin?.statusField;_&&!u?.roles.includes(r.Role)&&C(Math.max(_.active?.length||0,_.archived?.length||0));const z=E===0?30:Math.max(1,Math.floor(30/E)),k=[];x.filter(w=>w.type==="Record_Owner").forEach(()=>k.push(["Created_By","==",s])),x.filter(w=>w.type==="Record_User").forEach(w=>{if("collectionField"in w){const I=W(c,w.collectionField);k.push([`${I.name}_Array`,"array-contains",r.Doc_ID])}}),x.filter(w=>w.type==="Record_Property").forEach(w=>{if("propertyField"in w){const I=w.roles.find(R=>R.role===r.Role);if(!I)throw new Error("PERMISSION_DENIED");const T=W(c,w.propertyField);T.type==="Array"?k.push([`${T.name}_Array`,"array-contains-any",I.values]):k.push([T.name,"in",I.values])}});const m=[];g.filter(w=>w.type==="Individual").forEach(w=>{const I=f?.individualEntities,T=[];if(I){const R=w.singleQuery?w.singleQuery:z;for(let A=0;A<I.length;A+=R){const q=I.slice(A,A+R);T.push(q)}if(!w.singleQuery)T.forEach(A=>{m.push(...b(k.concat([["id","in",A]])))});else{if(I.length>R)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${w.singleQuery} entities`);k.push(["id","in",I])}}}),N.filter(w=>w.parentFilter.type==="Individual").forEach(w=>{const{parentFilter:I,parentRestriction:T}=w;if("collectionField"in I){const R=W(c,I.collectionField);if("collection"in R){const A=r.collections?.[R.collection];if(!A)throw new Error("PERMISSION_DENIED");const q=A.individualEntities,P=[];if(q){const S=T.singleQuery?T.singleQuery:z;for(let L=0;L<q.length;L+=S){const Z=q.slice(L,L+S);P.push(Z)}if(!T.singleQuery)P.forEach(L=>{m.push(...b(k.concat([[`${R.name}_Array`,"array-contains-any",L]])))});else{if(q.length>S)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${T.singleQuery} entities`);k.push([`${R.name}_Array`,"array-contains-any",q])}}}}});const $=[];g.filter(w=>w.type==="Parent").forEach(w=>{if("collectionField"in w){const I=W(c,w.collectionField);if("collection"in I){const T=f?.parentEntities,R=[];if(T){const A=w.singleQuery?w.singleQuery:z;for(let q=0;q<T.length;q+=A){const P=T.slice(q,q+A);R.push(P)}if(!w.singleQuery)R.forEach(q=>{$.push(...b(k.concat([[`${I.name}_Array`,"array-contains-any",q]])))});else{if(T&&T.length>A)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${w.singleQuery} entities`);k.push([`${I.name}_Array`,"array-contains-any",T])}}}}}),N.filter(w=>w.parentFilter.type==="Parent").forEach(w=>{const{parentFilter:I,parentRestriction:T}=w;if("collectionField"in I&&"parentCollectionField"in I){const R=W(c,I.collectionField),A=W(c,I.parentCollectionField);if("collection"in R&&"collection"in A){const q=r.collections?.[R.collection];if(!q)throw new Error("PERMISSION_DENIED");const P=q.parentEntities,S=[];if(P){const L=T.singleQuery?T.singleQuery:z;for(let Z=0;Z<P.length;Z+=L){const K=P.slice(Z,Z+L);S.push(K)}if(!T.singleQuery)S.forEach(Z=>{$.push(...b(k.concat([[`${A.name}_Array`,"array-contains-any",Z]])))});else{if(P&&P.length>L)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${T.singleQuery} entities`);k.push([`${A.name}_Array`,"array-contains-any",P])}}}}});const v=[];$.length===0&&(g.filter(w=>w.type==="Parent_Property").forEach(w=>{if("collectionField"in w&&"propertyField"in w){const I=W(c,w.collectionField),T=W(c,w.propertyField);if("collection"in I){const R=f?.parentPropertyEntities||{};Object.entries(R).forEach(([A,q])=>{if(q.length>0){const P=[];for(let S=0;S<q.length;S+=z){const L=q.slice(S,S+z);P.push(L)}P.forEach(S=>{v.push(...b(k.concat([[`${I.name}_Array`,"array-contains-any",S],[T.name,"==",A]])))})}})}}}),N.filter(w=>w.parentFilter.type==="Parent_Property").forEach(w=>{const{parentFilter:I}=w;if("collectionField"in I&&"parentCollectionField"in I&&"parentPropertyField"in I){const T=W(c,I.collectionField),R=W(c,I.parentCollectionField),A=W(c,I.parentPropertyField);if("collection"in T&&"collection"in R){const q=r.collections?.[T.collection];if(!q)throw new Error("PERMISSION_DENIED");const P=q.parentPropertyEntities||{};Object.entries(P).forEach(([S,L])=>{if(L.length>0){const Z=[];for(let K=0;K<L.length;K+=z){const te=L.slice(K,K+z);Z.push(te)}Z.forEach(K=>{v.push(...b(k.concat([[`${R.name}_Array`,"array-contains-any",K],[A.name,"==",S]])))})}})}}}));const H=[...m,...$,...v];return!g.length&&!N.length?b(k):H}else throw new Error("PERMISSION_DENIED");else return[d]},Xs=(n,e,t,s,r)=>{const i=B.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=s.collections[o],{labels:l}=a,c=Se(i,e,n);if(r){const u=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const h=u&&be("Read",u),d=fi(a,s,r),f=[],p=gi(r.Role,a,s);if(!p)throw new Error("PERMISSION_DENIED");if(h)f.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${p.key}`).doc(t));else if(d)for(const O of d)f.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${O.field}`).doc(t));return f}else return[c.doc(t)]},Do=async(n,e,t,s,r,i,o,a,l,c)=>{const u=t.at(-2),h=hi(r.collections[u],r).map(p=>p.labels.collection);s.collections?s.collections.forEach(p=>{if(!h.includes(p))throw new Error(`SCHEMA_ERROR: Collection ${p} not found in subcollections of ${u}`)}):s.collections=h;const d=s.depth-1,f=s.collections.map(async p=>{const O=await tr([...t,p],{constraints:s.constraints,userId:a,pagination:s.limit,providedTransaction:l,noEmbeddingFields:c}).catch(y=>{throw y.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${p} for document at ${t.join("/")}`),y});e[p]=O.docs,i&&await Promise.all(e[p].map(y=>er(n,y,[...t,p,y.id],i,r,void 0,a,l,c))),d>0&&await Promise.all(e[p].map(y=>Do(n,y,[...t,p,y.id],{depth:d},r,i,o,a,l,c)))});await Promise.all(f)},er=async(n,e,t,s,r,i,o,a,l)=>{const c=t.at(-2);s.fields||=r.collections[c].fields.filter(d=>X(d));const u=s.depth-1,h=[];for(const d of s.fields)if("collection"in d){const f=e[d.name];if(!f)continue;const p=Object.keys(f);for(const O of p){const y=f[O],g=Qe(y.Collection_Path,O,{userId:o,providedTransaction:a,noEmbeddingFields:l}).then(N=>{if(f[O]=N,u>0)return er(n,f[O],[...y.Collection_Path,O],{depth:u},r,i,o,a,l)}).catch(N=>{if(N.message.includes("NOT_FOUND")||N.code==="permission-denied")delete f[O];else throw N});h.push(g)}}await Promise.all(h)},tr=async(n,e)=>{if(e?.subcollections?.depth&&e.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(e?.relations?.depth&&e.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");if(e?.pagination?.number!==void 0){const c=e.pagination.number;if(typeof c!="number"||!Number.isFinite(c)||!Number.isInteger(c)||c<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const t=e?.constraints,s=ze(),r=B.getFirestore();let i,o,a;const l=async c=>{const[u,h,d]=await Promise.all([e?.userId?c.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(e.userId)):Promise.resolve({}),c.get(r.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!h.exists)throw new Error("MAINTENANCE_MODE");if(h.data().active)throw new Error("MAINTENANCE_MODE");const p=d;let O;const y=vt(),g=n.at(-1);if(!g)throw new Error("EMPTY_PATH");const N=Object.keys(p.collections).includes(g),b=y.disabledCollections?.includes(g);if(!N||b)throw new Error("COLLECTION_NOT_FOUND");const x=p.collections[g],{labels:E}=x,C=Ze(E.collection,p);if(e?.userId){if(!u?.exists)throw new Error("PERMISSION_DENIED");if(O=u.data(),!O.Role)throw new Error("USER_ERROR");if(!O.Enabled)throw new Error("PERMISSION_DENIED")}let _=No(s,n,p,e?.userId,O);if(_.length===0)return{cursor:{},pages:0,docs:[]};if(t&&(_=_.map(w=>(t.forEach(([I,T,R])=>{w=w.where(I,T,R)}),w))),o=e?.pagination?.startAfter||e?.pagination?.endBefore||{first:new Map,last:new Map},e?.pagination){if(e.pagination.startAfter&&e.pagination.endBefore)throw new Error("INPUT_ERROR: startAfter and endBefore cannot be provided together");const w=e.pagination.startAfter||e.pagination.endBefore;if(e?.userId){const I=ea(O.Role,x,p);if(w&&I!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+I)}e.pagination.orderByField&&e.pagination.orderByDirection?!e.pagination.startAfter&&!e.pagination.endBefore?_=_.map(I=>I.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).limit(e.pagination.number)):e.pagination.startAfter?_=_.map((I,T)=>I.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).startAfter(o.last.get(T)).limit(e.pagination.number)):_=_.map((I,T)=>I.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).endBefore(o.first.get(T)).limitToLast(e.pagination.number)):!e.pagination.startAfter&&!e.pagination.endBefore?_=_.map(I=>I.limit(e.pagination.number)):e.pagination.startAfter?_=_.map((I,T)=>I.startAfter(o.last.get(T)).limit(e.pagination.number)):_=_.map((I,T)=>I.endBefore(o.first.get(T)).limitToLast(e.pagination.number))}const z={};await ae("preOperation",y,C,["read",void 0,void 0,z]),await ae("preRead",y,C,[z,_,!0,!1]),a=new Map;const $=_.map(async w=>await c.get(w)),v=await Promise.all($);for(const w of v){for(const I of w.docs){a.has(I.id)||a.set(I.id,{});const T=I.data(),R=a.get(I.id);R.id||=I.id;const A={...R,...T};delete A.Collection_Path_String,a.set(I.id,A)}o.first.set(v.indexOf(w),w.docs[0]),o.last.set(v.indexOf(w),w.docs.at(-1)||w.docs[0])}if(e?.pagination){let w=_[0];t&&(w=t.reduce((A,[q,P,S])=>A.where(q,P,S),w)),e.pagination.orderByField&&e.pagination.orderByDirection&&(w=w.orderBy(e.pagination.orderByField,e.pagination.orderByDirection));const T=(await w.count().get()).data().count,R=e.pagination.number;i=R>0?Math.ceil(T/R):0}let H;e?.noComputedFields||(H=await oe(C.admin?.retriever));for(const w of a.values()){const I=[],T=[...w.Collection_Path,w.id];e?.subcollections&&I.push(Do(s,a.get(w.id),T,he(e.subcollections),p,he(e?.relations),void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields)),e?.relations&&(e.relations.fields&&(e.relations.fields=e.relations.fields.map(P=>{if(typeof P=="string"){const S=x.fields.find(L=>L.name===P);if(S)return S;throw new Error(`SCHEMA_ERROR: Field ${P} not found in collection ${g}`)}return P})),I.push(er(s,a.get(w.id),T,he(e.relations),p,void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields))),await Promise.all(I);const R=[];for(const P of x.fields){if(P.type==="Computed"&&!e?.noComputedFields){const S=Ae(P,C);if(!S.formula)continue;R.push(oe(S.formula,[w,H]).then(L=>{w[P.name]=L}))}e?.noEmbeddingFields&&P.type==="Embedding"&&delete w[P.name]}if(await Promise.all(R),e?.userId&&O?.Role){const P=O.Role;if(!(C.custom?.serverAccess?.read!==void 0?await oe(C.custom.serverAccess.read,[P,w]):!0)){a.delete(w.id);continue}for(const L of x.fields){const Z=!L.access||L.access.includes(P),K=Ae(L,C),te=K?.custom?.serverAccess?.read!==void 0?await oe(K.custom.serverAccess.read,[P,w]):!0;(!Z||!te)&&(X(L)?(delete a.get(w.id)[L.name],delete a.get(w.id)[`${L.name}_Array`],delete a.get(w.id)[`${L.name}_Single`]):delete a.get(w.id)[L.name])}}const A=["read",w,w.id,z];await ae("postOperation",y,C,A),await ae("postRead",y,C,[z,_,w,!1])}e?.userId&&await Ko(Array.from(a.values()),x,p,e.userId,O)};return e?.providedTransaction?await l(e.providedTransaction):await r.runTransaction(async c=>{await l(c)},{readOnly:!0}),{cursor:o,pages:i,docs:Array.from(a.values())}},Ao=async(n,e,t,s,r,i,o,a)=>{const l=s.at(-2),c=hi(i.collections[l],i).map(d=>d.labels.collection);r.collections?r.collections.forEach(d=>{if(!c.includes(d))throw new Error(`SCHEMA_ERROR: Collection ${d} not found in subcollections of ${l}`)}):r.collections=c;const u=r.depth-1,h=r.collections.map(async d=>{const f=await tr([...s,d],{constraints:r.constraints||[],userId:a,relations:o,pagination:r.limit,providedTransaction:e}).catch(p=>{throw p.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${d} for document at ${s.join("/")}`),p});t[d]=f.docs,u>0&&await Promise.all(t[d].map(async p=>{await Ao(n,e,p,[...s,d,p.id],{depth:u},i,o,a)}))});await Promise.all(h)},Co=async(n,e,t,s,r,i,o,a,l)=>{const c=s.at(-2);i.fields||=r.collections[c].fields.filter(d=>X(d));const u=i.depth-1,h=[];for(const d of i.fields)if("collection"in d){const f=t[d.name];if(!f)continue;for(const[p,O]of Object.entries(f)){const y=Qe(O.Collection_Path,p,{userId:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(g=>{if(f[p]=g,u>0)return Co(n,e,f[p],[...O.Collection_Path,p],r,{depth:u},o,a,l)}).catch(g=>{if(g.message.includes("NOT_FOUND")||g.code==="permission-denied")delete f[p];else throw g});h.push(y)}}await Promise.all(h)},Qe=async(n,e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(t?.relations?.depth&&t.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=ze(),r=B.getFirestore();let i;const o=async a=>{const[l,c,u]=await Promise.all([t?.userId?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(t.userId)):Promise.resolve({}),a.get(r.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!c.exists)throw new Error("MAINTENANCE_MODE");if(c.data().active)throw new Error("MAINTENANCE_MODE");const d=u;let f;const p=vt(),O=n.at(-1);if(!O)throw new Error("EMPTY_PATH");const y=Object.keys(d.collections).includes(O),g=p.disabledCollections?.includes(O);if(!y||g)throw new Error("COLLECTION_NOT_FOUND");const N=d.collections[O],{labels:b}=N,x=Ze(b.collection,d);let E;if(t?.userId){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(f=l.data(),!f.Role)throw new Error("USER_ERROR");if(!f.Enabled)throw new Error("PERMISSION_DENIED");if(E=f.collections?.[b.collection],!E)throw new Error("PERMISSION_DENIED")}if(t?.userId&&(!E||!be("Read",E)))throw new Error("PERMISSION_DENIED");const C=Xs(s,n,e,d,f);if(C.length===0)throw new Error("PERMISSION_DENIED");const _={};await ae("preOperation",p,x,["read",void 0,e,_]),await ae("preRead",p,x,[_,C,!1,!1]),i={};const m=C.map(T=>a.get(T)),$=await Promise.all(m);for(const T of $)if(T.exists){const R=T.data();i.id||=T.id,i={...i,...R},delete i.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${n?.join("/")||b.collection}`);const v=[],H=n?[...n,e]:[b.collection,e];if(t?.subcollections&&v.push(Ao(s,a,i,H,t.subcollections,d,void 0,t.userId)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(T=>{if(typeof T=="string"){const R=N.fields.find(A=>A.name===T);if(R)return R;throw new Error(`SCHEMA_ERROR: Field ${T} not found in collection ${O}`)}return T})),v.push(Co(s,a,i,H,d,t.relations,t.userId,t.noComputedFields,t.noEmbeddingFields))),await Promise.all(v),!t?.noComputedFields){for(const T of N.fields)if(T.type==="Computed"){const R=Ae(T,x);if(!R.formula)continue;i[T.name]=await R.formula(i)}}if(t?.noEmbeddingFields)for(const T of N.fields)T.type==="Embedding"&&delete i[T.name];if(t?.userId&&f?.Role){const T=f.Role;if(!(x.custom?.serverAccess?.read!==void 0?await oe(x.custom?.serverAccess?.read,[T,i]):!0))throw new Error("PERMISSION_DENIED");for(const A of N.fields){const q=!A.access||A.access.includes(T),P=Ae(A,x),S=P?.custom?.serverAccess?.read!==void 0?await oe(P.custom.serverAccess.read,[T,i]):!0;(!q||!S)&&(X(A)?(delete i[A.name],delete i[`${A.name}_Array`],delete i[`${A.name}_Single`]):delete i[A.name])}}await ae("postOperation",p,x,["read",i,e,_]),await ae("postRead",p,x,[_,C,i,!1]),t?.userId&&await Qo(i,N,d,t.userId,f)};return t?.providedTransaction?await o(t.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},Fo=async(n,e,t,s,r,i,o,a)=>{const l=B.getFirestore(),c=Ze(r.labels.collection,i),u=r.labels.collection,h=r.fields.filter(f=>"unique"in f&&f.unique),d=[];if(await Promise.all(h.map(async f=>{{if(s[f.name]===void 0||xe(s[f.name]))return;Ae(f,c);const p=s[f.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(!Js(p))d.push(`${f.name} "${s[f.name]}" is invalid`);else{const O=await l.collection("tenants").doc(e).collection("system_unique").doc(u).collection(`Unique-${u}-${f.name}`).doc(p).get();O.exists&&!(n==="update"&&O.data().id===t)&&d.push(`${f.name} "${s[f.name]}" already exists`)}}})),d.length>0)throw new Error(d.join(", "))},pt=async(n,e,t,s,r,i,o,a,l)=>{const{labels:c}=o,u=B.getFirestore(),h=vt(),d=await oe(h.firebase?.writeLogTTL),f={operation:n,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_App:t.Last_Write_App,Last_Write_Version:t.Last_Write_Version,data:{}};if(d){const g=new Date,N=new Date(new Date().setDate(g.getDate()+d));f.TTL=B.Timestamp.fromDate(N)}const p=he(t);nt(p),n!=="delete"&&(f.data.data=he(p)),n==="update"&&(f.data.originalRecord=he(l)),n!=="delete"&&["started","written"].includes(e)&&(delete f.data.data.Saved_At,delete f.data.data.Last_Save_At),e==="failed"&&(f.data.error=JSON.stringify(a));const O=Se(u,r,s),y=t.Last_Write_At;await O.doc(i).collection("system_write_log").doc(`${t.Last_Write_By}-${y.valueOf()}`).set(f)},Ut=async n=>{const e=ze(),t=yt.getAuth(),s=B.getFirestore(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(n.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
6
+ `),e.length>5e6)throw new Error("Email body is too long");return e},So=async(n,e)=>{const t={};for(const s of e){const r=`${n}/${s}.js`,i=ai.pathToFileURL(r).href;t[s]=await import(i)}return t};let fs,Ro,vn,Io,Yt,xo,On,kn,hs=0,ri=!1;const St={getTenant(){if(!vn)throw new Error("Tenant not provided");return vn},setTenant(n){vn=n},getMode(){return Ro},getTimezone(){return Io},getGlobalConfigModule(){return he(Yt)},getCustomizationFile(n,e){if(!Object.keys(e.collections).includes(n))throw new Error("PERMISSION_DENIED");const t=ta([n],xo,"node",St);return he(t?.[n])},getVersionInfo(){return On},getMaintenanceInfo(){return kn}},Lc=async(n,e,t,s,r)=>{const i=!!ri;if(ri=!0,e&&(vn=e),Ro=n,fs&&!r)return St;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const o=process.env.STOKER_FB_WEB_APP_CONFIG,a=JSON.parse(o),u=(await import(ai.pathToFileURL(t).href)).default;Yt=u("node",St),!r&&n==="development"&&(process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099",process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000",process.env.FIRESTORE_EMULATOR_HOST="127.0.0.1:8080",process.env.FIREBASE_STORAGE_EMULATOR_HOST="127.0.0.1:9199");try{fs=Rt.getApp()}catch{fs=Rt.initializeApp({credential:Rt.applicationDefault(),databaseURL:a.databaseURL,storageBucket:a.storageBucket,projectId:a.projectId})}const h=await je();return xo=await So(s,Object.keys(h.collections)),Io=await oe(Yt.timezone),i||B.getFirestore().collection("system_deployment").doc("maintenance_mode").onSnapshot(d=>{d.exists?(kn=d.data(),oe(Yt.onMaintenanceUpdate,["node",kn.active?"on":"off"])):console.error("Maintenance status not found")},d=>{console.error(d.message)}),i||B.getFirestore().collection("system_deployment").doc("latest_deploy").onSnapshot(d=>{d.exists?(On=d.data(),hs++,hs>1&&oe(Yt.onVersionUpdate,["node",On,hs])):console.error("Version info not found")},d=>{console.error(d.message)}),await new Promise(d=>{const f=()=>{kn&&On?d(St):setTimeout(f,100)};f()}),St},{getTenant:ze,setTenant:Vc,getMode:Qs,getTimezone:Ks,getGlobalConfigModule:Et,getCustomizationFile:Ze,getVersionInfo:Uc,getMaintenanceInfo:Wc}=St,jc=async(n,e,t,s)=>new Promise((r,i)=>{const o=zo(n,e,{cwd:t||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},u=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout?.on("data",h=>{a+=h.toString(),console.log(h.toString())}),o.stderr?.on("data",h=>{console.log(h.toString())}),o.on("exit",h=>{u(),h===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),zc=async()=>{const n=process.env.STOKER_FB_WEB_APP_CONFIG;if(!n)throw new Error("Firebase web app config not found");const e=JSON.parse(n);try{return Rt.getApp()}catch{return Rt.initializeApp({credential:Rt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},je=async(n=!1)=>{const s=await li.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=Ae(o,Ze(i.labels.collection,r));a.formula&&(o.formula=a.formula)}}else for(const i of Object.values(r.collections))i.fields=i.fields.filter(o=>o.type!=="Computed");return r},Zc=async()=>{const t=await li.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(t.numChildren()<2))return Object.values(t.val())[0]},Se=(n,e,t)=>{let s=n.collection("tenants").doc(t);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},No=(n,e,t,s,r)=>{const i=B.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=t.collections[o],{labels:l,fields:c,preloadCache:u}=a,h=Ze(o,t),d=Se(i,e,n);if(r)if(s){const f=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const p=f&&be("Read",f),O=fi(a,t,r),y=ui(a,r),g=Ms(a,r),N=di(a,t,r),b=(w=[])=>{const I=[],T=gi(r.Role,a,t);if(!T)throw new Error("PERMISSION_DENIED");if(p){let R=i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${T.key}`).where("Collection_Path_String","==",e.join("/"));w.forEach(A=>{R=R.where(...A)}),I.push(R)}else if(O)for(const R of O){let A=i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${R.field}`).where("Collection_Path_String","==",e.join("/"));w.forEach(q=>{A=A.where(...q)}),I.push(A)}return I},x=y.filter(w=>"operations"in w&&w.operations?w.operations.includes("Read"):!0);if(x.length===0&&g.length===0&&N.length===0)return b();let v=0;const C=w=>{w&&(v===0?v=w:v*=w)};if(x.length>0){for(const w of x)if(w.operations&&w.type==="Record_Property"){const I=w.roles.find(T=>T.role===r.Role);if(!I)throw new Error("PERMISSION_DENIED");C(I.values?.length)}}u?.roles.includes(r.Role)&&u.range&&C(u.range.fields.length);const _=h.admin?.statusField;_&&!u?.roles.includes(r.Role)&&C(Math.max(_.active?.length||0,_.archived?.length||0));const z=v===0?30:Math.max(1,Math.floor(30/v)),k=[];x.filter(w=>w.type==="Record_Owner").forEach(()=>k.push(["Created_By","==",s])),x.filter(w=>w.type==="Record_User").forEach(w=>{if("collectionField"in w){const I=W(c,w.collectionField);k.push([`${I.name}_Array`,"array-contains",r.Doc_ID])}}),x.filter(w=>w.type==="Record_Property").forEach(w=>{if("propertyField"in w){const I=w.roles.find(R=>R.role===r.Role);if(!I)throw new Error("PERMISSION_DENIED");const T=W(c,w.propertyField);T.type==="Array"?k.push([`${T.name}_Array`,"array-contains-any",I.values]):k.push([T.name,"in",I.values])}});const m=[];g.filter(w=>w.type==="Individual").forEach(w=>{const I=f?.individualEntities,T=[];if(I){const R=w.singleQuery?w.singleQuery:z;for(let A=0;A<I.length;A+=R){const q=I.slice(A,A+R);T.push(q)}if(!w.singleQuery)T.forEach(A=>{m.push(...b(k.concat([["id","in",A]])))});else{if(I.length>R)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${w.singleQuery} entities`);k.push(["id","in",I])}}}),N.filter(w=>w.parentFilter.type==="Individual").forEach(w=>{const{parentFilter:I,parentRestriction:T}=w;if("collectionField"in I){const R=W(c,I.collectionField);if("collection"in R){const A=r.collections?.[R.collection];if(!A)throw new Error("PERMISSION_DENIED");const q=A.individualEntities,P=[];if(q){const S=T.singleQuery?T.singleQuery:z;for(let L=0;L<q.length;L+=S){const Z=q.slice(L,L+S);P.push(Z)}if(!T.singleQuery)P.forEach(L=>{m.push(...b(k.concat([[`${R.name}_Array`,"array-contains-any",L]])))});else{if(q.length>S)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${T.singleQuery} entities`);k.push([`${R.name}_Array`,"array-contains-any",q])}}}}});const $=[];g.filter(w=>w.type==="Parent").forEach(w=>{if("collectionField"in w){const I=W(c,w.collectionField);if("collection"in I){const T=f?.parentEntities,R=[];if(T){const A=w.singleQuery?w.singleQuery:z;for(let q=0;q<T.length;q+=A){const P=T.slice(q,q+A);R.push(P)}if(!w.singleQuery)R.forEach(q=>{$.push(...b(k.concat([[`${I.name}_Array`,"array-contains-any",q]])))});else{if(T&&T.length>A)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${w.singleQuery} entities`);k.push([`${I.name}_Array`,"array-contains-any",T])}}}}}),N.filter(w=>w.parentFilter.type==="Parent").forEach(w=>{const{parentFilter:I,parentRestriction:T}=w;if("collectionField"in I&&"parentCollectionField"in I){const R=W(c,I.collectionField),A=W(c,I.parentCollectionField);if("collection"in R&&"collection"in A){const q=r.collections?.[R.collection];if(!q)throw new Error("PERMISSION_DENIED");const P=q.parentEntities,S=[];if(P){const L=T.singleQuery?T.singleQuery:z;for(let Z=0;Z<P.length;Z+=L){const K=P.slice(Z,Z+L);S.push(K)}if(!T.singleQuery)S.forEach(Z=>{$.push(...b(k.concat([[`${A.name}_Array`,"array-contains-any",Z]])))});else{if(P&&P.length>L)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${T.singleQuery} entities`);k.push([`${A.name}_Array`,"array-contains-any",P])}}}}});const E=[];$.length===0&&(g.filter(w=>w.type==="Parent_Property").forEach(w=>{if("collectionField"in w&&"propertyField"in w){const I=W(c,w.collectionField),T=W(c,w.propertyField);if("collection"in I){const R=f?.parentPropertyEntities||{};Object.entries(R).forEach(([A,q])=>{if(q.length>0){const P=[];for(let S=0;S<q.length;S+=z){const L=q.slice(S,S+z);P.push(L)}P.forEach(S=>{E.push(...b(k.concat([[`${I.name}_Array`,"array-contains-any",S],[T.name,"==",A]])))})}})}}}),N.filter(w=>w.parentFilter.type==="Parent_Property").forEach(w=>{const{parentFilter:I}=w;if("collectionField"in I&&"parentCollectionField"in I&&"parentPropertyField"in I){const T=W(c,I.collectionField),R=W(c,I.parentCollectionField),A=W(c,I.parentPropertyField);if("collection"in T&&"collection"in R){const q=r.collections?.[T.collection];if(!q)throw new Error("PERMISSION_DENIED");const P=q.parentPropertyEntities||{};Object.entries(P).forEach(([S,L])=>{if(L.length>0){const Z=[];for(let K=0;K<L.length;K+=z){const te=L.slice(K,K+z);Z.push(te)}Z.forEach(K=>{E.push(...b(k.concat([[`${R.name}_Array`,"array-contains-any",K],[A.name,"==",S]])))})}})}}}));const H=[...m,...$,...E];return!g.length&&!N.length?b(k):H}else throw new Error("PERMISSION_DENIED");else return[d]},Xs=(n,e,t,s,r)=>{const i=B.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=s.collections[o],{labels:l}=a,c=Se(i,e,n);if(r){const u=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const h=u&&be("Read",u),d=fi(a,s,r),f=[],p=gi(r.Role,a,s);if(!p)throw new Error("PERMISSION_DENIED");if(h)f.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${p.key}`).doc(t));else if(d)for(const O of d)f.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${O.field}`).doc(t));return f}else return[c.doc(t)]},Do=async(n,e,t,s,r,i,o,a,l,c)=>{const u=t.at(-2),h=hi(r.collections[u],r).map(p=>p.labels.collection);s.collections?s.collections.forEach(p=>{if(!h.includes(p))throw new Error(`SCHEMA_ERROR: Collection ${p} not found in subcollections of ${u}`)}):s.collections=h;const d=s.depth-1,f=s.collections.map(async p=>{const O=await tr([...t,p],{constraints:s.constraints,userId:a,pagination:s.limit,providedTransaction:l,noEmbeddingFields:c}).catch(y=>{throw y.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${p} for document at ${t.join("/")}`),y});e[p]=O.docs,i&&await Promise.all(e[p].map(y=>er(n,y,[...t,p,y.id],i,r,void 0,a,l,c))),d>0&&await Promise.all(e[p].map(y=>Do(n,y,[...t,p,y.id],{depth:d},r,i,o,a,l,c)))});await Promise.all(f)},er=async(n,e,t,s,r,i,o,a,l)=>{const c=t.at(-2);s.fields||=r.collections[c].fields.filter(d=>X(d));const u=s.depth-1,h=[];for(const d of s.fields)if("collection"in d){const f=e[d.name];if(!f)continue;const p=Object.keys(f);for(const O of p){const y=f[O],g=Qe(y.Collection_Path,O,{userId:o,providedTransaction:a,noEmbeddingFields:l}).then(N=>{if(f[O]=N,u>0)return er(n,f[O],[...y.Collection_Path,O],{depth:u},r,i,o,a,l)}).catch(N=>{if(N.message.includes("NOT_FOUND")||N.code==="permission-denied")delete f[O];else throw N});h.push(g)}}await Promise.all(h)},tr=async(n,e)=>{if(e?.subcollections?.depth&&e.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(e?.relations?.depth&&e.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");if(e?.pagination?.number!==void 0){const c=e.pagination.number;if(typeof c!="number"||!Number.isFinite(c)||!Number.isInteger(c)||c<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const t=e?.constraints,s=ze(),r=B.getFirestore();let i,o,a;const l=async c=>{const[u,h,d]=await Promise.all([e?.userId?c.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(e.userId)):Promise.resolve({}),c.get(r.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!h.exists)throw new Error("MAINTENANCE_MODE");if(h.data().active)throw new Error("MAINTENANCE_MODE");const p=d;let O;const y=Et(),g=n.at(-1);if(!g)throw new Error("EMPTY_PATH");const N=Object.keys(p.collections).includes(g),b=y.disabledCollections?.includes(g);if(!N||b)throw new Error("COLLECTION_NOT_FOUND");const x=p.collections[g],{labels:v}=x,C=Ze(v.collection,p);if(e?.userId){if(!u?.exists)throw new Error("PERMISSION_DENIED");if(O=u.data(),!O.Role)throw new Error("USER_ERROR");if(!O.Enabled)throw new Error("PERMISSION_DENIED")}let _=No(s,n,p,e?.userId,O);if(_.length===0)return{cursor:{},pages:0,docs:[]};if(t&&(_=_.map(w=>(t.forEach(([I,T,R])=>{w=w.where(I,T,R)}),w))),o=e?.pagination?.startAfter||e?.pagination?.endBefore||{first:new Map,last:new Map},e?.pagination){if(e.pagination.startAfter&&e.pagination.endBefore)throw new Error("INPUT_ERROR: startAfter and endBefore cannot be provided together");const w=e.pagination.startAfter||e.pagination.endBefore;if(e?.userId){const I=ea(O.Role,x,p);if(w&&I!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+I)}e.pagination.orderByField&&e.pagination.orderByDirection?!e.pagination.startAfter&&!e.pagination.endBefore?_=_.map(I=>I.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).limit(e.pagination.number)):e.pagination.startAfter?_=_.map((I,T)=>I.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).startAfter(o.last.get(T)).limit(e.pagination.number)):_=_.map((I,T)=>I.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).endBefore(o.first.get(T)).limitToLast(e.pagination.number)):!e.pagination.startAfter&&!e.pagination.endBefore?_=_.map(I=>I.limit(e.pagination.number)):e.pagination.startAfter?_=_.map((I,T)=>I.startAfter(o.last.get(T)).limit(e.pagination.number)):_=_.map((I,T)=>I.endBefore(o.first.get(T)).limitToLast(e.pagination.number))}const z={};await ae("preOperation",y,C,{operation:"read",context:z}),await ae("preRead",y,C,{context:z,refs:_,multiple:!0,listener:!1}),a=new Map;const $=_.map(async w=>await c.get(w)),E=await Promise.all($);for(const w of E){for(const I of w.docs){a.has(I.id)||a.set(I.id,{});const T=I.data(),R=a.get(I.id);R.id||=I.id;const A={...R,...T};delete A.Collection_Path_String,a.set(I.id,A)}o.first.set(E.indexOf(w),w.docs[0]),o.last.set(E.indexOf(w),w.docs.at(-1)||w.docs[0])}if(e?.pagination){let w=_[0];t&&(w=t.reduce((A,[q,P,S])=>A.where(q,P,S),w)),e.pagination.orderByField&&e.pagination.orderByDirection&&(w=w.orderBy(e.pagination.orderByField,e.pagination.orderByDirection));const T=(await w.count().get()).data().count,R=e.pagination.number;i=R>0?Math.ceil(T/R):0}let H;e?.noComputedFields||(H=await oe(C.admin?.retriever));for(const w of a.values()){const I=[],T=[...w.Collection_Path,w.id];e?.subcollections&&I.push(Do(s,a.get(w.id),T,he(e.subcollections),p,he(e?.relations),void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields)),e?.relations&&(e.relations.fields&&(e.relations.fields=e.relations.fields.map(P=>{if(typeof P=="string"){const S=x.fields.find(L=>L.name===P);if(S)return S;throw new Error(`SCHEMA_ERROR: Field ${P} not found in collection ${g}`)}return P})),I.push(er(s,a.get(w.id),T,he(e.relations),p,void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields))),await Promise.all(I);const R=[];for(const P of x.fields){if(P.type==="Computed"&&!e?.noComputedFields){const S=Ae(P,C);if(!S.formula)continue;R.push(oe(S.formula,[w,H]).then(L=>{w[P.name]=L}))}e?.noEmbeddingFields&&P.type==="Embedding"&&delete w[P.name]}if(await Promise.all(R),e?.userId&&O?.Role){const P=O.Role;if(!(C.custom?.serverAccess?.read!==void 0?await oe(C.custom.serverAccess.read,[P,w]):!0)){a.delete(w.id);continue}for(const L of x.fields){const Z=!L.access||L.access.includes(P),K=Ae(L,C),te=K?.custom?.serverAccess?.read!==void 0?await oe(K.custom.serverAccess.read,[P,w]):!0;(!Z||!te)&&(X(L)?(delete a.get(w.id)[L.name],delete a.get(w.id)[`${L.name}_Array`],delete a.get(w.id)[`${L.name}_Single`]):delete a.get(w.id)[L.name])}}const A={operation:"read",data:w,docId:w.id,context:z};await ae("postOperation",y,C,A),await ae("postRead",y,C,{context:z,refs:_,doc:w,listener:!1})}e?.userId&&await Ko(Array.from(a.values()),x,p,e.userId,O)};return e?.providedTransaction?await l(e.providedTransaction):await r.runTransaction(async c=>{await l(c)},{readOnly:!0}),{cursor:o,pages:i,docs:Array.from(a.values())}},Ao=async(n,e,t,s,r,i,o,a)=>{const l=s.at(-2),c=hi(i.collections[l],i).map(d=>d.labels.collection);r.collections?r.collections.forEach(d=>{if(!c.includes(d))throw new Error(`SCHEMA_ERROR: Collection ${d} not found in subcollections of ${l}`)}):r.collections=c;const u=r.depth-1,h=r.collections.map(async d=>{const f=await tr([...s,d],{constraints:r.constraints||[],userId:a,relations:o,pagination:r.limit,providedTransaction:e}).catch(p=>{throw p.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${d} for document at ${s.join("/")}`),p});t[d]=f.docs,u>0&&await Promise.all(t[d].map(async p=>{await Ao(n,e,p,[...s,d,p.id],{depth:u},i,o,a)}))});await Promise.all(h)},Co=async(n,e,t,s,r,i,o,a,l)=>{const c=s.at(-2);i.fields||=r.collections[c].fields.filter(d=>X(d));const u=i.depth-1,h=[];for(const d of i.fields)if("collection"in d){const f=t[d.name];if(!f)continue;for(const[p,O]of Object.entries(f)){const y=Qe(O.Collection_Path,p,{userId:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(g=>{if(f[p]=g,u>0)return Co(n,e,f[p],[...O.Collection_Path,p],r,{depth:u},o,a,l)}).catch(g=>{if(g.message.includes("NOT_FOUND")||g.code==="permission-denied")delete f[p];else throw g});h.push(y)}}await Promise.all(h)},Qe=async(n,e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(t?.relations?.depth&&t.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=ze(),r=B.getFirestore();let i;const o=async a=>{const[l,c,u]=await Promise.all([t?.userId?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(t.userId)):Promise.resolve({}),a.get(r.collection("system_deployment").doc("maintenance_mode")),je(!0)]);if(!c.exists)throw new Error("MAINTENANCE_MODE");if(c.data().active)throw new Error("MAINTENANCE_MODE");const d=u;let f;const p=Et(),O=n.at(-1);if(!O)throw new Error("EMPTY_PATH");const y=Object.keys(d.collections).includes(O),g=p.disabledCollections?.includes(O);if(!y||g)throw new Error("COLLECTION_NOT_FOUND");const N=d.collections[O],{labels:b}=N,x=Ze(b.collection,d);let v;if(t?.userId){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(f=l.data(),!f.Role)throw new Error("USER_ERROR");if(!f.Enabled)throw new Error("PERMISSION_DENIED");if(v=f.collections?.[b.collection],!v)throw new Error("PERMISSION_DENIED")}if(t?.userId&&(!v||!be("Read",v)))throw new Error("PERMISSION_DENIED");const C=Xs(s,n,e,d,f);if(C.length===0)throw new Error("PERMISSION_DENIED");const _={};await ae("preOperation",p,x,{operation:"read",docId:e,context:_}),await ae("preRead",p,x,{context:_,refs:C,multiple:!1,listener:!1}),i={};const m=C.map(T=>a.get(T)),$=await Promise.all(m);for(const T of $)if(T.exists){const R=T.data();i.id||=T.id,i={...i,...R},delete i.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${n?.join("/")||b.collection}`);const E=[],H=n?[...n,e]:[b.collection,e];if(t?.subcollections&&E.push(Ao(s,a,i,H,t.subcollections,d,void 0,t.userId)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.relations.fields.map(T=>{if(typeof T=="string"){const R=N.fields.find(A=>A.name===T);if(R)return R;throw new Error(`SCHEMA_ERROR: Field ${T} not found in collection ${O}`)}return T})),E.push(Co(s,a,i,H,d,t.relations,t.userId,t.noComputedFields,t.noEmbeddingFields))),await Promise.all(E),!t?.noComputedFields){for(const T of N.fields)if(T.type==="Computed"){const R=Ae(T,x);if(!R.formula)continue;i[T.name]=await R.formula(i)}}if(t?.noEmbeddingFields)for(const T of N.fields)T.type==="Embedding"&&delete i[T.name];if(t?.userId&&f?.Role){const T=f.Role;if(!(x.custom?.serverAccess?.read!==void 0?await oe(x.custom?.serverAccess?.read,[T,i]):!0))throw new Error("PERMISSION_DENIED");for(const A of N.fields){const q=!A.access||A.access.includes(T),P=Ae(A,x),S=P?.custom?.serverAccess?.read!==void 0?await oe(P.custom.serverAccess.read,[T,i]):!0;(!q||!S)&&(X(A)?(delete i[A.name],delete i[`${A.name}_Array`],delete i[`${A.name}_Single`]):delete i[A.name])}}await ae("postOperation",p,x,{operation:"read",data:i,docId:e,context:_}),await ae("postRead",p,x,{context:_,refs:C,doc:i,listener:!1}),t?.userId&&await Qo(i,N,d,t.userId,f)};return t?.providedTransaction?await o(t.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},Fo=async(n,e,t,s,r,i,o,a)=>{const l=B.getFirestore(),c=Ze(r.labels.collection,i),u=r.labels.collection,h=r.fields.filter(f=>"unique"in f&&f.unique),d=[];if(await Promise.all(h.map(async f=>{{if(s[f.name]===void 0||xe(s[f.name]))return;Ae(f,c);const p=s[f.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(!Js(p))d.push(`${f.name} "${s[f.name]}" is invalid`);else{const O=await l.collection("tenants").doc(e).collection("system_unique").doc(u).collection(`Unique-${u}-${f.name}`).doc(p).get();O.exists&&!(n==="update"&&O.data().id===t)&&d.push(`${f.name} "${s[f.name]}" already exists`)}}})),d.length>0)throw new Error(d.join(", "))},pt=async(n,e,t,s,r,i,o,a,l)=>{const{labels:c}=o,u=B.getFirestore(),h=Et(),d=await oe(h.firebase?.writeLogTTL),f={operation:n,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_App:t.Last_Write_App,Last_Write_Version:t.Last_Write_Version,data:{}};if(d){const g=new Date,N=new Date(new Date().setDate(g.getDate()+d));f.TTL=B.Timestamp.fromDate(N)}const p=he(t);nt(p),n!=="delete"&&(f.data.data=he(p)),n==="update"&&(f.data.originalRecord=he(l)),n!=="delete"&&["started","written"].includes(e)&&(delete f.data.data.Saved_At,delete f.data.data.Last_Save_At),e==="failed"&&(f.data.error=JSON.stringify(a));const O=Se(u,r,s),y=t.Last_Write_At;await O.doc(i).collection("system_write_log").doc(`${t.Last_Write_By}-${y.valueOf()}`).set(f)},Ut=async n=>{const e=ze(),t=yt.getAuth(),s=B.getFirestore(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(n.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
7
7
  ${i}`)}})(),(async()=>{try{await t.deleteUser(n.User_ID)}catch(i){if(i.code==="auth/user-not-found")return;r.push(`Error deleting user:
8
- ${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},nr=async(n,e,t,s,r,i,o,a,l)=>{const c=B.getFirestore(),u=Qs(),h=process.env.ADMIN_EMAIL;if(u==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(h)n=h;else throw new Error("Admin email not set");const d=ds(n),f=Pc(e),p=t?si(t):void 0,O=s?si(s):void 0,y=r?ds(r):void 0,g=i?ds(i):void 0,N=o?Vn(o):void 0,b=l?Vn(l):void 0,x=Array.isArray(d)?d:[d];if(x.length===0||x.length===1&&!x[0])throw new Error("No valid email addresses provided");const E={to:d,message:{subject:f}};if(p&&(E.message.text=p),O&&(E.message.html=O),y){const C=Array.isArray(y)?y:[y];C.length>0&&C[0]&&(E.cc=y)}if(g){const C=Array.isArray(g)?g:[g];C.length>0&&C[0]&&(E.bcc=g)}N&&(E.replyTo=N),a&&(E.message.attachments=a),b&&(E.from=b),await c.collection("system_mail").add(E)},sr=async(n,e,t,s,r,i,o)=>{const a=yt.getAuth(),l=B.getFirestore(),c="USER_ERROR",u=async(f,p)=>{try{await Ut(f)}catch{throw new Error(`ROLLBACK_FAILED: ${p}`)}};let h;try{h=await a.createUser({email:r.Email,emailVerified:!1,password:o,displayName:r.Name,photoURL:r.Photo_URL,disabled:!r.Enabled})}catch{throw new Error(c)}try{await a.setCustomUserClaims(h.uid,{tenant:n,role:r.Role,collection:s,doc:e})}catch{throw await u(r,c),new Error(c)}try{await l.collection("tenants").doc(n).collection("system_user_permissions").doc(h.uid).set({...i,Role:r.Role,Enabled:r.Enabled??!1,Collection:s,Doc_ID:e})}catch{throw await u(r,c),new Error(c)}const d=t.auth.enableMultiFactorAuth;if(d===!0||typeof d=="object"&&d.includes(r.Role)){let f;try{f=await a.generateEmailVerificationLink(r.Email)}catch{throw await u(r,c),new Error(c)}if(f.includes("apiKey=&")){const p=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);f=f.replace("apiKey=&",`apiKey=${p.apiKey}&`)}if(f){const p=`https://${a.app.options.projectId}.firebaseapp.com/__/auth/action${f}`,O=await oe(t.appName),y=t?.mail?.emailVerification&&t.mail.emailVerification(p,O);try{await nr(r.Email,y?.subject||"Please verify your email address",void 0,y?.html||`Please verify your email address by clicking the link:
8
+ ${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},nr=async(n,e,t,s,r,i,o,a,l)=>{const c=B.getFirestore(),u=Qs(),h=process.env.ADMIN_EMAIL;if(u==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(h)n=h;else throw new Error("Admin email not set");const d=ds(n),f=Pc(e),p=t?si(t):void 0,O=s?si(s):void 0,y=r?ds(r):void 0,g=i?ds(i):void 0,N=o?Vn(o):void 0,b=l?Vn(l):void 0,x=Array.isArray(d)?d:[d];if(x.length===0||x.length===1&&!x[0])throw new Error("No valid email addresses provided");const v={to:d,message:{subject:f}};if(p&&(v.message.text=p),O&&(v.message.html=O),y){const C=Array.isArray(y)?y:[y];C.length>0&&C[0]&&(v.cc=y)}if(g){const C=Array.isArray(g)?g:[g];C.length>0&&C[0]&&(v.bcc=g)}N&&(v.replyTo=N),a&&(v.message.attachments=a),b&&(v.from=b),await c.collection("system_mail").add(v)},sr=async(n,e,t,s,r,i,o)=>{const a=yt.getAuth(),l=B.getFirestore(),c="USER_ERROR",u=async(f,p)=>{try{await Ut(f)}catch{throw new Error(`ROLLBACK_FAILED: ${p}`)}};let h;try{h=await a.createUser({email:r.Email,emailVerified:!1,password:o,displayName:r.Name,photoURL:r.Photo_URL,disabled:!r.Enabled})}catch{throw new Error(c)}try{await a.setCustomUserClaims(h.uid,{tenant:n,role:r.Role,collection:s,doc:e})}catch{throw await u(r,c),new Error(c)}try{await l.collection("tenants").doc(n).collection("system_user_permissions").doc(h.uid).set({...i,Role:r.Role,Enabled:r.Enabled??!1,Collection:s,Doc_ID:e})}catch{throw await u(r,c),new Error(c)}const d=t.auth.enableMultiFactorAuth;if(d===!0||typeof d=="object"&&d.includes(r.Role)){let f;try{f=await a.generateEmailVerificationLink(r.Email)}catch{throw await u(r,c),new Error(c)}if(f.includes("apiKey=&")){const p=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);f=f.replace("apiKey=&",`apiKey=${p.apiKey}&`)}if(f){const p=`https://${a.app.options.projectId}.firebaseapp.com/__/auth/action${f}`,O=await oe(t.appName),y=t?.mail?.emailVerification&&t.mail.emailVerification(p,O);try{await nr(r.Email,y?.subject||"Please verify your email address",void 0,y?.html||`Please verify your email address by clicking the link:
9
9
  </br>
10
10
  </br>
11
- <a href="${p}">${p}</a>`)}catch{throw await u(r,c),new Error(c)}}}return h.uid},rr=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 Qe(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(t.collection),!He(n,a))throw new Error("PERMISSION_DENIED")}else if(n.length>1)throw new Error("PERMISSION_DENIED")},Un=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),qc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Un(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?t[s]=new B.Timestamp(r.seconds,r.nanoseconds):Un(r)&&e(r)})};e(n)},ir=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Un(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?t[s]=new B.Timestamp(r._seconds,r._nanoseconds):Un(r)&&e(r)})};e(n)},Yn=n=>{if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]==="_DELETE_FIELD"?n[e]=B.FieldValue.delete():Yn(n[e]))},Bc=(n,e,t)=>{if(X(t)&&t.includeFields){const s={};return t.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=W(n.fields,r);gt(n,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},ii=async(n,e,t,s,r,i,o)=>{if(!X(t)||!t.enforceHierarchy)return;const{fields:a}=e,l=B.getFirestore(),c=Object.entries(s[t.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${t.name} is required`);const[u,h]=c[0];if(!h)throw new Error(`VALIDATION_ERROR: Relation ${t.name} is required`);const d=Se(l,h.Collection_Path,n);if(i.size++,!o&&i.size>500)throw new Error("VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const f=await r.get(d.doc(u));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${u} not found in collection ${t.collection}`);const p=f.data(),O=W(a,t.enforceHierarchy.field),y=t.enforceHierarchy;if(!p[y.recordLinkField]||!s[O.name]||!Object.keys(s[O.name]).every(g=>Object.keys(p[y.recordLinkField]).includes(g)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},yn=async(n,e,t)=>{delete e[n.name][t],e[`${n.name}_Array`]=e[`${n.name}_Array`]?.filter(s=>s!==t),delete e[`${n.name}_Single`]},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`]={id:s,...t})},Hc=(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}},or=async(n,e,t,s,r,i,o,a,l,c,u,h)=>{const{fields:d}=i,f=B.getFirestore(),p=new Map,O=new Map,y=new Map;for(const g of d)X(g)&&["OneToOne","OneToMany"].includes(g.type)&&g.enforceHierarchy&&s[g.name]&&(n==="Create"||n==="Update"&&!He(h?.[g.name],s[g.name]))&&await ii(e,i,g,s,a,l);for(const g of d)if(X(g)&&g.twoWay){const N=o.collections[g.collection],b=W(N.fields,g.twoWay),x=ut(N,[b]);if(s[g.name]){const E=Object.entries(s[g.name]);for(const C of E){const[_,z]=C;if(n==="Create"||!h?.[g.name]?.[_]){let k;const m=y.get(g.collection)?.[_];if(m)k=m;else{l.size++,l&&l.size>500&&console.error(new Error(`VALIDATION_ERROR: ${l.size} 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 v=Se(f,z.Collection_Path,e),H=await a.get(v.doc(_));if(!H.exists){yn(g,r,_);continue}const w=H.data();O.set(g.collection,{...O.get(g.collection)||{},[_]:w}),k=he({...w,...bn(s)})}const $={...k[b.name],[t]:{Collection_Path:s.Collection_Path,...Bc(i,s,b)}};k[b.name]=$,k[`${b.name}_Array`]||=[],k[`${b.name}_Array`].push(t),x.size===1&&(k[`${b.name}_Single`]={id:t,...$}),y.set(g.collection,{...y.get(g.collection)||{},[_]:k})}}}if(n==="Update"){const E=Object.entries(h?.[g.name]||{});for(const C of E){const[_,z]=C;if(!s[g.name]?.[_]){let k;const m=y.get(g.collection)?.[_];if(m)k=m;else{l.size++,l&&l.size>500&&console.error(new Error(`VALIDATION_ERROR: ${l.size} 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 $=Se(f,z.Collection_Path,e),v=await a.get($.doc(_));if(!v.exists){p.set(g.name,[...p.get(g.name)||[],_]);continue}const H=v.data();O.set(g.collection,{...O.get(g.collection)||{},[_]:H}),k=he({...H,...bn(s)})}k[b.name][t]&&delete k[b.name][t],Array.isArray(k[`${b.name}_Array`])&&(k[`${b.name}_Array`]=k[`${b.name}_Array`].filter($=>$!==t)),x.size===1&&delete k[`${b.name}_Single`],y.set(g.collection,{...y.get(g.collection)||{},[_]:k})}}}}for(const[g,N]of y.entries()){const b=o.collections[g],x=Ze(g,o);for(const[E,C]of Object.entries(N)){const{addedFields:_,removedFields:z}=Hc(n,E,g,i,s,h);if(c&&u){for(const k of _){const m=W(b.fields,k.twoWay);if(!cr(b,m,u)){yn(k,r,E);continue}}for(const k of z){const m=W(b.fields,k.twoWay),$=ut(b,[m]);if(!cr(b,m,u)){ms(k,r,h?.[k.name]?.[E],E,$.size===1);continue}}if(!it("Update",b,o,c,u,O.get(g)?.[E])){for(const k of _)yn(k,r,E);for(const k of z){const m=W(b.fields,k.twoWay),$=ut(b,[m]);ms(k,r,h?.[k.name]?.[E],E,$.size===1)}}if(!it("Update",b,o,c,u,C)){for(const k of _)yn(k,r,E);for(const k of z){const m=W(b.fields,k.twoWay),$=ut(b,[m]);ms(k,r,h?.[k.name]?.[E],E,$.size===1)}}}try{await nn("update",C,b,x,["update",C,{},void 0,C],o)}catch(k){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${E} in ${g}: ${k.message}`)}for(const k of _){const m=W(b.fields,k.twoWay);["OneToOne","OneToMany"].includes(m.type)&&X(m)&&m.enforceHierarchy&&await ii(e,b,m,C,a,l,!0)}}}return p},$o=(n,e,t)=>{n==="create"&&ht.forEach(s=>{if(!He(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),n==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),ht.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!He(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},ar=(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(!be("Read",r.collections?.[e.labels.collection]))return!1;try{await Qe([e.labels.collection],t,{userId:s,providedTransaction:n})}catch{return!1}return!0},Gc=10,Yc=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))},Mo=async(n,e,t,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,u=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const d=i?.collections?.[a],f=[];if(l.individualEntities){const p=l.individualEntities,O=d?.individualEntities||[],y=i?p.filter(g=>!O.includes(g)):p;for(const g of y){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");f.push(async()=>{if(!await ps(n,u,g,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const p=c.entityRestrictions?.restrictions?.find(x=>x.type==="Parent"&&x.roles.some(E=>E.role===e.Role));if(!p)throw new Error("PERMISSION_DENIED");const O=W(u.fields,p.collectionField),y=r.collections[O.collection],g=l.parentEntities,N=d?.parentEntities||[],b=i?g.filter(x=>!N.includes(x)):g;for(const x of b){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,y,x,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const p=c.entityRestrictions?.restrictions?.find(b=>b.type==="Parent_Property"&&b.roles.some(x=>x.role===e.Role));if(!p)throw new Error("PERMISSION_DENIED");const O=W(u.fields,p.collectionField),y=r.collections[O.collection],g=l.parentPropertyEntities,N=d?.parentPropertyEntities||{};for(const[b,x]of Object.entries(g)){const E=N[b]||[],C=i?x.filter(_=>!E.includes(_)):x;for(const _ of C){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");f.push(async()=>{if(!await ps(n,y,_,t,s))throw new Error("PERMISSION_DENIED")})}}}await Yc(f,Gc)}}},Jc=async(n,e,t)=>{const s=t?.userId,r=t?.user;let i=t?.context;const o=ze(),a=vt();if(t?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(t?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=t?.providedSchema||await je();if(n.length===0)throw new Error("EMPTY_PATH");const c=n.at(-1),u=Object.keys(l.collections).includes(c),h=a.disabledCollections?.includes(c);if(!u||h)throw new Error("COLLECTION_NOT_FOUND");const d=l.collections[c],{labels:f,fields:p,enableWriteLog:O,softDelete:y}=d,g=Ze(f.collection,l),N=await oe(a.appName),b=B.getFirestore(),x=yt.getAuth(),C=(s?await x.getUser(s):void 0)?.customClaims?.role;let _;s&&await rr(n,d);const z=Se(b,n,o),k=t?.id||z.doc().id;i=i||{},i.collection=f.collection,e.id=k,ir(e),Yn(e);const m=Vs("create",n,e,l,N,"Online",s||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp());t?.createdAt&&(m.Created_At=t.createdAt),t?.createdBy&&(m.Created_By=t.createdBy);const $=he(m);y&&(m[y.archivedField]=!1),Le(e),O&&!t?.providedTransaction&&await pt("create","started",m,o,n,k,d),await ae("preOperation",a,g,["create",m,k,i]),await ae("preWrite",a,g,["create",m,k,i]),Tn(d,m,l),Sn(d,m),await oa(m,d,g,C),Le(m);try{if(d.auth&&r&&!r.password)throw new Error("Password is required");t?.providedTransaction||(await Fo("create",o,k,m,d,l),await nn("create",m,d,g,["create",m,i],l))}catch(R){throw new Error(`VALIDATION_ERROR: ${R.message}`)}Le(m),e.id=k,y&&(m[y.archivedField]=!1),Tn(d,m,l),Sn(d,m);try{$o("create",m,$),ar("create",d,m),await nn("create",m,d,g,["create",m,i],l)}catch(R){throw new Error(`VALIDATION_ERROR: ${R.message}`)}if(s){const R=C;if(!R)throw new Error("USER_ERROR");if(!(g.custom?.serverAccess?.create!==void 0?await oe(g.custom.serverAccess.create,[R,m]):!0))throw new Error("PERMISSION_DENIED");for(const q of d.fields){if(!(q.name in m))continue;const P=Ae(q,g);if(P?.custom?.serverAccess?.create!==void 0&&!await oe(P.custom.serverAccess.create,[R,m]))throw new Error("PERMISSION_DENIED")}}r&&(r.permissions||={},r.permissions.Role||=m.Role,r.permissions.Enabled||=m.Enabled);const w=async(R,A)=>{const[q,P,S,L]=await Promise.all([t?.providedTransaction?Promise.resolve({}):R.get(b.collection("system_deployment").doc("latest_deploy")),t?.providedTransaction?Promise.resolve({}):R.get(b.collection("system_deployment").doc("maintenance_mode")),s?R.get(b.collection("tenants").doc(o).collection("system_user_permissions").doc(s)):Promise.resolve({}),t?.providedSchema?Promise.resolve(t.providedSchema):je()]);if(A&&(A.size+=3),!t?.providedTransaction){if(!q.exists)throw new Error("VERSION_ERROR");const Z=q.data();if(Z.force&&m.Last_Write_At.valueOf()<Z.time.valueOf())throw new Error("VERSION_ERROR");if(!P.exists)throw new Error("MAINTENANCE_MODE");if(P.data().active)throw new Error("MAINTENANCE_MODE")}if(l=L,s){if(!S?.exists)throw new Error("PERMISSION_DENIED");if(_=S.data(),!_.Role)throw new Error("USER_ERROR");if(!_.Enabled)throw new Error("PERMISSION_DENIED")}if(!t?.providedTransaction){const K=p.filter(te=>"unique"in te&&te.unique).map(async te=>{if(!s||!te.access||te.access.includes(_.Role)){if(!e[te.name])return;const qe=Ae(te,g);if(!(s&&qe?.custom?.serverAccess?.read!==void 0?await oe(qe.custom.serverAccess.read,[_?.Role,m]):!0))throw new Error("PERMISSION_DENIED");const Re=e[te.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Js(Re)){if(A&&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 unique field checks.");if((await R.get(b.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${te.name}`).doc(Re)))?.exists)throw new Error(`VALIDATION_ERROR: ${te.name} "${m[te.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${te.name} "${m[te.name]}" is invalid`)}});await Promise.all(K)}ur(m,k,d,l,s,_,r?.permissions),r?.permissions&&s&&_&&await Mo(R,r.permissions,s,_,l),ur(m,k,d,l,s,_,r?.permissions)};if(d.auth&&r){await b.runTransaction(async A=>{await w(A)},{maxAttempts:10});const R=await sr(o,k,a,f.collection,m,r.permissions,r.password);m.User_ID=R}const I=async R=>{try{const A={size:1};await w(R,A),t?.noTwoWay||await or("Create",o,k,m,m,d,l,R,A,s,_);const q=Ls(l);Ys("create",R,n,k,m,l,d,t,q,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,P=>b.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${P.name}`).doc(k),(P,S)=>b.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${P.name}`).doc(S),P=>b.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${P}`).doc(k),(P,S)=>Se(b,P,o).doc(S),(P,S,L)=>b.collection("tenants").doc(o).collection("system_fields").doc(P.collection).collection(`${P.collection}-${S}`).doc(L),(P,S,L)=>b.collection("tenants").doc(o).collection("system_fields").doc(P.collection).collection(`${P.collection}-${S.replaceAll(" ","-")}`).doc(L),void 0,void 0,A),R.set(z.doc(k),m)}catch(A){if(t?.providedTransaction)throw A;{const P=await ae("postWriteError",a,g,["create",m,k,i,A]);if(O&&(await new Promise(S=>{setTimeout(S,250)}),await pt("create",P?.resolved?"success":"failed",m,o,n,k,d,P?.resolved?void 0:A)),!P?.resolved)throw d.auth&&r&&await Ut(m),A}}};if(t?.providedTransaction?await I(t.providedTransaction):await b.runTransaction(async R=>{await I(R)},{maxAttempts:10}),!t?.providedTransaction){const R=["create",m,k,i],A=[...R];await ae("postWrite",a,g,R),await ae("postOperation",a,g,A)}return{id:k,...m}},Jt=async(n,e,t,s)=>{const r=ze(),i=yt.getAuth(),o=B.getFirestore(),a=e.customClaims||{};let l=!1;try{await i.updateUser(n,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(n,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(n).update({...t,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Po=async(n,e,t,s,r,i,o,a,l,c,u)=>{const h=yt.getAuth(),d=B.getFirestore(),f=a?.customClaims||{},p="USER_ERROR";let O="";if(n==="create"){if(!u)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{O=await sr(e,t,s,r,i,l,u)}catch(y){throw new Error(y.message)}}else if(n==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),u&&(y.password=u),Object.keys(y).length)try{await h.updateUser(o.User_ID,y),y.disabled===!0&&await h.revokeRefreshTokens(o.User_ID)}catch{throw await Jt(o.User_ID,a,c,p),new Error(p)}if(i.Role&&i.Role!==o.Role)try{await h.setCustomUserClaims(o.User_ID,{...f,role:i.Role}),await h.revokeRefreshTokens(o.User_ID)}catch{throw await Jt(o.User_ID,a,c,p),new Error(p)}try{await d.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:f.collection,Doc_ID:f.doc,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await Jt(o.User_ID,a,c,p),new Error(p)}if(o.Email!==i.Email){const g=s.auth.enableMultiFactorAuth;if(g===!0||typeof g=="object"&&g.includes(i.Role)){let N=await h.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(N.includes("apiKey=&")){const b=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);N=N.replace("apiKey=&",`apiKey=${b.apiKey}&`)}if(N){const b=`https://${h.app.options.projectId}.firebaseapp.com/__/auth/action${N}`,x=await oe(s.appName),E=s?.mail?.emailVerification&&s.mail.emailVerification(b,x);try{await nr(i.Email,E?.subject||"Please verify your email address",void 0,E?.html||`Please verify your email address by clicking the link:
11
+ <a href="${p}">${p}</a>`)}catch{throw await u(r,c),new Error(c)}}}return h.uid},rr=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 Qe(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(t.collection),!He(n,a))throw new Error("PERMISSION_DENIED")}else if(n.length>1)throw new Error("PERMISSION_DENIED")},Un=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),qc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Un(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?t[s]=new B.Timestamp(r.seconds,r.nanoseconds):Un(r)&&e(r)})};e(n)},ir=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{Un(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?t[s]=new B.Timestamp(r._seconds,r._nanoseconds):Un(r)&&e(r)})};e(n)},Yn=n=>{if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]==="_DELETE_FIELD"?n[e]=B.FieldValue.delete():Yn(n[e]))},Bc=(n,e,t)=>{if(X(t)&&t.includeFields){const s={};return t.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=W(n.fields,r);gt(n,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},ii=async(n,e,t,s,r,i,o)=>{if(!X(t)||!t.enforceHierarchy)return;const{fields:a}=e,l=B.getFirestore(),c=Object.entries(s[t.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${t.name} is required`);const[u,h]=c[0];if(!h)throw new Error(`VALIDATION_ERROR: Relation ${t.name} is required`);const d=Se(l,h.Collection_Path,n);if(i.size++,!o&&i.size>500)throw new Error("VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const f=await r.get(d.doc(u));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${u} not found in collection ${t.collection}`);const p=f.data(),O=W(a,t.enforceHierarchy.field),y=t.enforceHierarchy;if(!p[y.recordLinkField]||!s[O.name]||!Object.keys(s[O.name]).every(g=>Object.keys(p[y.recordLinkField]).includes(g)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},yn=async(n,e,t)=>{delete e[n.name][t],e[`${n.name}_Array`]=e[`${n.name}_Array`]?.filter(s=>s!==t),delete e[`${n.name}_Single`]},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`]={id:s,...t})},Hc=(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}},or=async(n,e,t,s,r,i,o,a,l,c,u,h)=>{const{fields:d}=i,f=B.getFirestore(),p=new Map,O=new Map,y=new Map;for(const g of d)X(g)&&["OneToOne","OneToMany"].includes(g.type)&&g.enforceHierarchy&&s[g.name]&&(n==="Create"||n==="Update"&&!He(h?.[g.name],s[g.name]))&&await ii(e,i,g,s,a,l);for(const g of d)if(X(g)&&g.twoWay){const N=o.collections[g.collection],b=W(N.fields,g.twoWay),x=ut(N,[b]);if(s[g.name]){const v=Object.entries(s[g.name]);for(const C of v){const[_,z]=C;if(n==="Create"||!h?.[g.name]?.[_]){let k;const m=y.get(g.collection)?.[_];if(m)k=m;else{l.size++,l&&l.size>500&&console.error(new Error(`VALIDATION_ERROR: ${l.size} 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 E=Se(f,z.Collection_Path,e),H=await a.get(E.doc(_));if(!H.exists){yn(g,r,_);continue}const w=H.data();O.set(g.collection,{...O.get(g.collection)||{},[_]:w}),k=he({...w,...bn(s)})}const $={...k[b.name],[t]:{Collection_Path:s.Collection_Path,...Bc(i,s,b)}};k[b.name]=$,k[`${b.name}_Array`]||=[],k[`${b.name}_Array`].push(t),x.size===1&&(k[`${b.name}_Single`]={id:t,...$}),y.set(g.collection,{...y.get(g.collection)||{},[_]:k})}}}if(n==="Update"){const v=Object.entries(h?.[g.name]||{});for(const C of v){const[_,z]=C;if(!s[g.name]?.[_]){let k;const m=y.get(g.collection)?.[_];if(m)k=m;else{l.size++,l&&l.size>500&&console.error(new Error(`VALIDATION_ERROR: ${l.size} 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 $=Se(f,z.Collection_Path,e),E=await a.get($.doc(_));if(!E.exists){p.set(g.name,[...p.get(g.name)||[],_]);continue}const H=E.data();O.set(g.collection,{...O.get(g.collection)||{},[_]:H}),k=he({...H,...bn(s)})}k[b.name][t]&&delete k[b.name][t],Array.isArray(k[`${b.name}_Array`])&&(k[`${b.name}_Array`]=k[`${b.name}_Array`].filter($=>$!==t)),x.size===1&&delete k[`${b.name}_Single`],y.set(g.collection,{...y.get(g.collection)||{},[_]:k})}}}}for(const[g,N]of y.entries()){const b=o.collections[g],x=Ze(g,o);for(const[v,C]of Object.entries(N)){const{addedFields:_,removedFields:z}=Hc(n,v,g,i,s,h);if(c&&u){for(const k of _){const m=W(b.fields,k.twoWay);if(!cr(b,m,u)){yn(k,r,v);continue}}for(const k of z){const m=W(b.fields,k.twoWay),$=ut(b,[m]);if(!cr(b,m,u)){ms(k,r,h?.[k.name]?.[v],v,$.size===1);continue}}if(!it("Update",b,o,c,u,O.get(g)?.[v])){for(const k of _)yn(k,r,v);for(const k of z){const m=W(b.fields,k.twoWay),$=ut(b,[m]);ms(k,r,h?.[k.name]?.[v],v,$.size===1)}}if(!it("Update",b,o,c,u,C)){for(const k of _)yn(k,r,v);for(const k of z){const m=W(b.fields,k.twoWay),$=ut(b,[m]);ms(k,r,h?.[k.name]?.[v],v,$.size===1)}}}try{await nn("update",C,b,x,{operation:"update",record:C,context:{},originalRecord:C},o)}catch(k){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${v} in ${g}: ${k.message}`)}for(const k of _){const m=W(b.fields,k.twoWay);["OneToOne","OneToMany"].includes(m.type)&&X(m)&&m.enforceHierarchy&&await ii(e,b,m,C,a,l,!0)}}}return p},$o=(n,e,t)=>{n==="create"&&ht.forEach(s=>{if(!He(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),n==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),ht.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!He(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},ar=(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(!be("Read",r.collections?.[e.labels.collection]))return!1;try{await Qe([e.labels.collection],t,{userId:s,providedTransaction:n})}catch{return!1}return!0},Gc=10,Yc=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))},Mo=async(n,e,t,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,u=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const d=i?.collections?.[a],f=[];if(l.individualEntities){const p=l.individualEntities,O=d?.individualEntities||[],y=i?p.filter(g=>!O.includes(g)):p;for(const g of y){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");f.push(async()=>{if(!await ps(n,u,g,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const p=c.entityRestrictions?.restrictions?.find(x=>x.type==="Parent"&&x.roles.some(v=>v.role===e.Role));if(!p)throw new Error("PERMISSION_DENIED");const O=W(u.fields,p.collectionField),y=r.collections[O.collection],g=l.parentEntities,N=d?.parentEntities||[],b=i?g.filter(x=>!N.includes(x)):g;for(const x of b){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,y,x,t,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const p=c.entityRestrictions?.restrictions?.find(b=>b.type==="Parent_Property"&&b.roles.some(x=>x.role===e.Role));if(!p)throw new Error("PERMISSION_DENIED");const O=W(u.fields,p.collectionField),y=r.collections[O.collection],g=l.parentPropertyEntities,N=d?.parentPropertyEntities||{};for(const[b,x]of Object.entries(g)){const v=N[b]||[],C=i?x.filter(_=>!v.includes(_)):x;for(const _ of C){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");f.push(async()=>{if(!await ps(n,y,_,t,s))throw new Error("PERMISSION_DENIED")})}}}await Yc(f,Gc)}}},Jc=async(n,e,t)=>{const s=t?.userId,r=t?.user;let i=t?.context;const o=ze(),a=Et();if(t?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(t?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=t?.providedSchema||await je();if(n.length===0)throw new Error("EMPTY_PATH");const c=n.at(-1),u=Object.keys(l.collections).includes(c),h=a.disabledCollections?.includes(c);if(!u||h)throw new Error("COLLECTION_NOT_FOUND");const d=l.collections[c],{labels:f,fields:p,enableWriteLog:O,softDelete:y}=d,g=Ze(f.collection,l),N=await oe(a.appName),b=B.getFirestore(),x=yt.getAuth(),C=(s?await x.getUser(s):void 0)?.customClaims?.role;let _;s&&await rr(n,d);const z=Se(b,n,o),k=t?.id||z.doc().id;i=i||{},i.collection=f.collection,e.id=k,ir(e),Yn(e);const m=Vs("create",n,e,l,N,"Online",s||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp());t?.createdAt&&(m.Created_At=t.createdAt),t?.createdBy&&(m.Created_By=t.createdBy);const $=he(m);y&&(m[y.archivedField]=!1),Le(e),O&&!t?.providedTransaction&&await pt("create","started",m,o,n,k,d),await ae("preOperation",a,g,{operation:"create",data:m,docId:k,context:i}),await ae("preWrite",a,g,{operation:"create",data:m,docId:k,context:i}),Tn(d,m,l),Sn(d,m),await oa(m,d,g,C),Le(m);try{if(d.auth&&r&&!r.password)throw new Error("Password is required");t?.providedTransaction||(await Fo("create",o,k,m,d,l),await nn("create",m,d,g,{operation:"create",record:m,context:i},l))}catch(R){throw new Error(`VALIDATION_ERROR: ${R.message}`)}Le(m),e.id=k,y&&(m[y.archivedField]=!1),Tn(d,m,l),Sn(d,m);try{$o("create",m,$),ar("create",d,m),await nn("create",m,d,g,{operation:"create",record:m,context:i},l)}catch(R){throw new Error(`VALIDATION_ERROR: ${R.message}`)}if(s){const R=C;if(!R)throw new Error("USER_ERROR");if(!(g.custom?.serverAccess?.create!==void 0?await oe(g.custom.serverAccess.create,[R,m]):!0))throw new Error("PERMISSION_DENIED");for(const q of d.fields){if(!(q.name in m))continue;const P=Ae(q,g);if(P?.custom?.serverAccess?.create!==void 0&&!await oe(P.custom.serverAccess.create,[R,m]))throw new Error("PERMISSION_DENIED")}}r&&(r.permissions||={},r.permissions.Role||=m.Role,r.permissions.Enabled||=m.Enabled);const w=async(R,A)=>{const[q,P,S,L]=await Promise.all([t?.providedTransaction?Promise.resolve({}):R.get(b.collection("system_deployment").doc("latest_deploy")),t?.providedTransaction?Promise.resolve({}):R.get(b.collection("system_deployment").doc("maintenance_mode")),s?R.get(b.collection("tenants").doc(o).collection("system_user_permissions").doc(s)):Promise.resolve({}),t?.providedSchema?Promise.resolve(t.providedSchema):je()]);if(A&&(A.size+=3),!t?.providedTransaction){if(!q.exists)throw new Error("VERSION_ERROR");const Z=q.data();if(Z.force&&m.Last_Write_At.valueOf()<Z.time.valueOf())throw new Error("VERSION_ERROR");if(!P.exists)throw new Error("MAINTENANCE_MODE");if(P.data().active)throw new Error("MAINTENANCE_MODE")}if(l=L,s){if(!S?.exists)throw new Error("PERMISSION_DENIED");if(_=S.data(),!_.Role)throw new Error("USER_ERROR");if(!_.Enabled)throw new Error("PERMISSION_DENIED")}if(!t?.providedTransaction){const K=p.filter(te=>"unique"in te&&te.unique).map(async te=>{if(!s||!te.access||te.access.includes(_.Role)){if(!e[te.name])return;const qe=Ae(te,g);if(!(s&&qe?.custom?.serverAccess?.read!==void 0?await oe(qe.custom.serverAccess.read,[_?.Role,m]):!0))throw new Error("PERMISSION_DENIED");const Re=e[te.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Js(Re)){if(A&&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 unique field checks.");if((await R.get(b.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${te.name}`).doc(Re)))?.exists)throw new Error(`VALIDATION_ERROR: ${te.name} "${m[te.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${te.name} "${m[te.name]}" is invalid`)}});await Promise.all(K)}ur(m,k,d,l,s,_,r?.permissions),r?.permissions&&s&&_&&await Mo(R,r.permissions,s,_,l),ur(m,k,d,l,s,_,r?.permissions)};if(d.auth&&r){await b.runTransaction(async A=>{await w(A)},{maxAttempts:10});const R=await sr(o,k,a,f.collection,m,r.permissions,r.password);m.User_ID=R}const I=async R=>{try{const A={size:1};await w(R,A),t?.noTwoWay||await or("Create",o,k,m,m,d,l,R,A,s,_);const q=Ls(l);Ys("create",R,n,k,m,l,d,t,q,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,P=>b.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${P.name}`).doc(k),(P,S)=>b.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${P.name}`).doc(S),P=>b.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${P}`).doc(k),(P,S)=>Se(b,P,o).doc(S),(P,S,L)=>b.collection("tenants").doc(o).collection("system_fields").doc(P.collection).collection(`${P.collection}-${S}`).doc(L),(P,S,L)=>b.collection("tenants").doc(o).collection("system_fields").doc(P.collection).collection(`${P.collection}-${S.replaceAll(" ","-")}`).doc(L),void 0,void 0,A),R.set(z.doc(k),m)}catch(A){if(t?.providedTransaction)throw A;{const P=await ae("postWriteError",a,g,{operation:"create",data:m,docId:k,context:i,error:A});if(O&&(await new Promise(S=>{setTimeout(S,250)}),await pt("create",P?.resolved?"success":"failed",m,o,n,k,d,P?.resolved?void 0:A)),!P?.resolved)throw d.auth&&r&&await Ut(m),A}}};if(t?.providedTransaction?await I(t.providedTransaction):await b.runTransaction(async R=>{await I(R)},{maxAttempts:10}),!t?.providedTransaction){const R={operation:"create",data:m,docId:k,context:i},A={...R};await ae("postWrite",a,g,R),await ae("postOperation",a,g,A)}return{id:k,...m}},Jt=async(n,e,t,s)=>{const r=ze(),i=yt.getAuth(),o=B.getFirestore(),a=e.customClaims||{};let l=!1;try{await i.updateUser(n,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(n,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(n).update({...t,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Po=async(n,e,t,s,r,i,o,a,l,c,u)=>{const h=yt.getAuth(),d=B.getFirestore(),f=a?.customClaims||{},p="USER_ERROR";let O="";if(n==="create"){if(!u)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{O=await sr(e,t,s,r,i,l,u)}catch(y){throw new Error(y.message)}}else if(n==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),u&&(y.password=u),Object.keys(y).length)try{await h.updateUser(o.User_ID,y),y.disabled===!0&&await h.revokeRefreshTokens(o.User_ID)}catch{throw await Jt(o.User_ID,a,c,p),new Error(p)}if(i.Role&&i.Role!==o.Role)try{await h.setCustomUserClaims(o.User_ID,{...f,role:i.Role}),await h.revokeRefreshTokens(o.User_ID)}catch{throw await Jt(o.User_ID,a,c,p),new Error(p)}try{await d.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:f.collection,Doc_ID:f.doc,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await Jt(o.User_ID,a,c,p),new Error(p)}if(o.Email!==i.Email){const g=s.auth.enableMultiFactorAuth;if(g===!0||typeof g=="object"&&g.includes(i.Role)){let N=await h.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(N.includes("apiKey=&")){const b=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);N=N.replace("apiKey=&",`apiKey=${b.apiKey}&`)}if(N){const b=`https://${h.app.options.projectId}.firebaseapp.com/__/auth/action${N}`,x=await oe(s.appName),v=s?.mail?.emailVerification&&s.mail.emailVerification(b,x);try{await nr(i.Email,v?.subject||"Please verify your email address",void 0,v?.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(o.User_ID,a,c,p),new Error(p)}}}}}else if(n==="delete")try{await Ut(o)}catch(y){throw new Error(y.message)}if(O)return O},Qc=async(n,e,t)=>{const s=ze(),r=B.getFirestore(),i=[e];t&&t.trim()!==""&&i.push(t),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await n.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)n.set(a,{locked:!0})},oi=async(n,e)=>{const t=ze(),s=B.getFirestore(),r=[n];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(t).collection("system_locks").doc(o);i.delete(a)}await i.commit()},Lo=async(n,e,t,s)=>{const r=s?.userId,i=s?.user;let o=s?.context;const a=ze(),l=vt();if(s?.providedTransaction&&r)throw new Error("PERMISSION_DENIED");if(s?.providedSchema&&r)throw new Error("PERMISSION_DENIED");if(s?.providedTransaction&&!s?.originalRecord)throw new Error("PERMISSION_DENIED");let c=s?.providedSchema||await je(!0);if(n.length===0)throw new Error("EMPTY_PATH");const u=n.at(-1),h=Object.keys(c.collections).includes(u),d=l.disabledCollections?.includes(u);if(!h||d)throw new Error("COLLECTION_NOT_FOUND");const f=c.collections[u],{labels:p,fields:O,enableWriteLog:y}=f,g=Ze(p.collection,c),N=await oe(l.appName),b=yt.getAuth(),x=B.getFirestore();let E;r&&await rr(n,f);const C=Se(x,n,a);o=o||{},o.collection=p.collection;let _=s?.originalRecord||await Qe(n,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0});for(const S of O)S.type==="Computed"&&delete t[S.name];if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([S,L])=>[S,{...L,fields:L.fields.filter(Z=>Z.type!=="Computed")}]))},i&&!i.operation)throw new Error("VALIDATION_ERROR: User operation is required");if(i&&!f.auth)throw new Error("VALIDATION_ERROR: User operations are only permitted for auth collections");if(i?.operation==="delete"&&i.permissions)throw new Error("VALIDATION_ERROR: Permissions are not allowed for delete operations");const z=f.auth&&i?.operation==="create",k=f.auth&&i?.operation==="delete",m=f.auth&&!z&&!k&&(i?.operation==="update"||t.Role||t.Enabled!==void 0||t.Name||t.Email||t.Photo_URL),$=S=>S.User_ID&&(f.auth&&!z&&!k&&i?.operation==="update"||t.Role&&t.Role!==S.Role||t.Enabled!==void 0&&t.Enabled!==S.Enabled||t.Name&&t.Name!==S.Name||t.Email&&t.Email!==S.Email||t.Photo_URL&&t.Photo_URL!==S.Photo_URL);delete t.id,ir(t),Yn(t);const v=Vs("update",n,t,c,N,"Online",r||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp()),H=he(v);for(const S of O)!X(S)&&xe(v[S.name])&&S.nullable&&(v[S.name]=null);Le(v),Le(_),y&&!s?.providedTransaction&&await pt("update","started",v,a,n,e,f,void 0,_);const w=["update",v,e,o,void 0,he(_)];await ae("preOperation",l,g,w);const I=["update",v,e,o,void 0,he(_)];await ae("preWrite",l,g,I),Tn(f,v,c),Sn(f,v),Le(v);try{if(z&&!i.password)throw new Error("Password is required");if(!s?.providedTransaction){const S={..._,...v};await Fo("update",a,e,S,f,c),nt(S),await nn("update",S,f,g,["update",v,o,void 0,he(_)],c)}}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}Le(v),delete t.id,Tn(f,v,c),Sn(f,v);for(const S of O)!X(S)&&xe(v[S.name])&&S.nullable&&(v[S.name]=null);try{const S={..._,...v};nt(S),ar("update",f,v,_),$o("update",v,H),await nn("update",S,f,g,["update",v,o,void 0,_],c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}let T;i&&(i.permissions||={});const R=async(S,L,Z)=>{const[K,te,qe,fe,Re]=await Promise.all([s?.providedTransaction?Promise.resolve({}):S.get(x.collection("system_deployment").doc("latest_deploy")),s?.providedTransaction?Promise.resolve({}):S.get(x.collection("system_deployment").doc("maintenance_mode")),s?.providedTransaction?Promise.resolve(_):Qe(n,e,{userId:r,providedTransaction:S,noComputedFields:!0}),r?S.get(x.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve({}),s?.providedSchema?Promise.resolve(s.providedSchema):je()]);if(Z&&(Z.size+=3),!s?.providedTransaction){if(!K.exists)throw new Error("VERSION_ERROR");const ge=K.data();if(ge.force&&v.Last_Write_At.valueOf()<ge.time.valueOf())throw new Error("VERSION_ERROR");if(!te.exists)throw new Error("MAINTENANCE_MODE");if(te.data().active)throw new Error("MAINTENANCE_MODE")}if(!qe)throw new Error("NOT_FOUND");if(_=qe,c=Re,r){if(!fe?.exists)throw new Error("PERMISSION_DENIED");if(E=fe.data(),!E.Role)throw new Error("USER_ERROR");if(!E.Enabled)throw new Error("PERMISSION_DENIED")}if(Z&&(Z.size+=Xs(a,n,e,c,E).length),z&&_.User_ID||k&&!_.User_ID)throw new Error("USER_ERROR");if($(_)){const ge=await S.get(x.collection("tenants").doc(a).collection("system_user_permissions").doc(_.User_ID));if(Z&&Z.size++,!ge?.exists)throw new Error("PERMISSION_DENIED");if(T=ge.data(),i?.permissions){if(i.permissions.Role||=v.Role||_.Role,i.permissions.Enabled??=v.Enabled??_.Enabled,xe(i.permissions.Role))throw new Error("VALIDATION_ERROR: Role field is required");if(xe(i.permissions.Enabled))throw new Error("VALIDATION_ERROR: Enabled field is required")}}if(!s?.providedTransaction){const Wt=O.filter(we=>"unique"in we&&we.unique).map(async we=>{if(!r||!we.access||we.access.includes(E.Role)){if(v[we.name]===void 0||xe(v[we.name]))return;const jt=Ae(we,g),cn={..._,...v};if(!(r&&jt?.custom?.serverAccess?.read!==void 0?await oe(jt.custom.serverAccess.read,[E?.Role,cn]):!0))throw new Error("PERMISSION_DENIED");const Jn=v[we.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Js(Jn)){if(Z&&Z.size++,Z&&Z.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 lr=await S.get(x.collection("tenants").doc(a).collection("system_unique").doc(p.collection).collection(`Unique-${p.collection}-${we.name}`).doc(Jn));if(lr.exists&&lr.data().id!==e)throw new Error(`VALIDATION_ERROR: ${we.name} "${v[we.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${we.name} "${v[we.name]}" is invalid`)}});await Promise.all(Wt)}if(r&&E?.Role){const ge=E.Role,Wt={..._,...v};if(!(g.custom?.serverAccess?.update!==void 0?await oe(g.custom.serverAccess.update,[ge,Wt,_]):!0))throw new Error("PERMISSION_DENIED");for(const jt of f.fields){const cn=Ae(jt,g);if(Object.prototype.hasOwnProperty.call(v,jt.name)&&cn?.custom?.serverAccess?.update!==void 0&&!await oe(cn.custom.serverAccess.update,[ge,Wt,_]))throw new Error("PERMISSION_DENIED")}}dr(v,_,e,f,c,r,E,i?.operation?i.operation:m?"update":void 0,i?.permissions,T),i?.permissions&&r&&E&&await Mo(S,i.permissions,r,E,c,T,Z),dr(v,_,e,f,c,r,E,i?.operation?i.operation:m?"update":void 0,i?.permissions,T),L&&(z||$(_)||k)&&await Qc(S,e,_.User_ID)};(z||m||k)&&await x.runTransaction(async S=>{await R(S,!0)},{maxAttempts:10});const A=async(S,L)=>{if(!_)throw new Error("NOT_FOUND");try{const Z={size:1},K={..._,...v};await R(S,!1,Z);let te;!s?.noTwoWay&&!s?.providedTransaction&&(te=await or("Update",a,e,K,v,f,c,S,Z,r,E,_));const qe=Ls(c);Ys("update",S,n,e,v,c,f,s,qe,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,fe=>x.collection("tenants").doc(a).collection("system_fields").doc(p.collection).collection(`${p.collection}-${fe.name}`).doc(e),(fe,Re)=>x.collection("tenants").doc(a).collection("system_unique").doc(p.collection).collection(`Unique-${p.collection}-${fe.name}`).doc(Re),fe=>x.collection("tenants").doc(a).collection("system_fields").doc(p.collection).collection(`${p.collection}-${fe}`).doc(e),(fe,Re)=>Se(x,fe,a).doc(Re),(fe,Re,ge)=>x.collection("tenants").doc(a).collection("system_fields").doc(fe.collection).collection(`${fe.collection}-${Re}`).doc(ge),(fe,Re,ge)=>x.collection("tenants").doc(a).collection("system_fields").doc(fe.collection).collection(`${fe.collection}-${Re.replaceAll(" ","-")}`).doc(ge),_,te,Z),S.update(C.doc(e),v)}catch(Z){if(s?.providedTransaction)throw Z;{const K=["update",v,e,o,Z,void 0,void 0,void 0,he(_)],te=await ae("postWriteError",l,g,K);if(y&&(await new Promise(qe=>{setTimeout(qe,250)}),await pt("update",te?.resolved?"success":"failed",v,a,n,e,f,te?.resolved?void 0:Z,_)),!te?.resolved)throw z&&await Ut(_),$(_)&&await Jt(_.User_ID,L,T,"USER_ERROR"),k&&await x.collection("tenants").doc(a).collection(p.collection).doc(e).update({User_ID:B.FieldValue.delete()}),Z}}(z||$(_)||k)&&await ni(oi,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")})};try{let S;if(z||$(_)||k){if($(_)){S=await b.getUser(_.User_ID);const K=S.customClaims;if(!(K&&K.role&&K.collection&&K.doc))throw new Error("USER_ERROR")}const L={..._,...v};nt(L);const Z=await Po(i?.operation||"update",a,e,l,p.collection,L,_,S,i?.permissions,T,i?.password);z&&(v.User_ID=Z),k&&(v.User_ID=B.FieldValue.delete())}s?.providedTransaction?await A(s.providedTransaction,S):await x.runTransaction(async L=>{await A(L,S)},{maxAttempts:10})}catch(S){throw(z||$(_)||k)&&await ni(oi,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),S}if(!s?.providedTransaction){const S=["update",v,e,o,void 0,he(_)],L=[...S];await ae("postWrite",l,g,S),await ae("postOperation",l,g,L)}const q={..._,...v};return nt(q),{id:e,...q}},Kc=async(n,e,t)=>{const s=t?.userId;let r=t?.context;const i=ze(),o=vt();let a=await je();if(n.length===0)throw new Error("EMPTY_PATH");const l=n.at(-1),c=Object.keys(a.collections).includes(l),u=o.disabledCollections?.includes(l);if(!c||u)throw new Error("COLLECTION_NOT_FOUND");const h=a.collections[l],{labels:d,auth:f,enableWriteLog:p,softDelete:O}=h,y=Ze(d.collection,a),g=await oe(o.appName);if(O&&!f&&!t?.force)return await Lo(n,e,{[O.archivedField]:!0,[O.timestampField]:B.FieldValue.serverTimestamp()},{userId:s});const N=B.getFirestore();let b;s&&await rr(n,h);const x=Se(N,n,i);r=r||{},r.collection=d.collection;const E=await Qe(n,e,{userId:s});let C=Vs("delete",n,E,a,g,"Online",s||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp());const _=bn(C);Le(C),p&&await pt("delete","started",C,i,n,e,h),await ae("preOperation",o,y,["delete",C,e,r]),await ae("preWrite",o,y,["delete",C,e,r]),Le(C);const m=async w=>{const[I,T,R,A]=await Promise.all([w.get(N.collection("system_deployment").doc("maintenance_mode")),Qe([d.collection],e,{userId:s,providedTransaction:w}),s?w.get(N.collection("tenants").doc(i).collection("system_user_permissions").doc(s)):Promise.resolve({}),je()]);if(!I.exists)throw new Error("MAINTENANCE_MODE");if(I.data().active)throw new Error("MAINTENANCE_MODE");if(!T)throw new Error("NOT_FOUND");if(C={...T,..._},a=A,s){if(!R?.exists)throw new Error("PERMISSION_DENIED");if(b=R.data(),!b.Role)throw new Error("USER_ERROR");if(!b.Enabled)throw new Error("PERMISSION_DENIED");Jo(C,e,h,a,s,b)}if(s&&b?.Role){const P=b.Role;if(!(y.custom?.serverAccess?.delete!==void 0?await oe(y.custom.serverAccess.delete,[P,C]):!0))throw new Error("PERMISSION_DENIED")}};h.auth&&(await N.runTransaction(async w=>{await m(w)},{maxAttempts:10}),C.User_ID&&await Ut(C));try{await N.runTransaction(async w=>{await m(w);const I=Ls(a);Ys("delete",w,n,e,C,a,h,t,I,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,T=>N.collection("tenants").doc(i).collection("system_fields").doc(d.collection).collection(`${d.collection}-${T.name}`).doc(e),(T,R)=>N.collection("tenants").doc(i).collection("system_unique").doc(d.collection).collection(`Unique-${d.collection}-${T.name}`).doc(R),T=>N.collection("tenants").doc(i).collection("system_fields").doc(d.collection).collection(`${d.collection}-${T}`).doc(e),(T,R)=>Se(N,T,i).doc(R),(T,R,A)=>N.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${R}`).doc(A),(T,R,A)=>N.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${R.replaceAll(" ","-")}`).doc(A)),w.delete(x.doc(e))},{maxAttempts:10})}catch(w){const T=await ae("postWriteError",o,y,["delete",C,e,r,w]);if(p&&(await new Promise(R=>{setTimeout(R,250)}),await pt("delete",T?.resolved?"success":"failed",C,i,n,e,h,T?.resolved?void 0:w)),!T?.resolved)throw h.auth&&C.User_ID&&await N.collection("tenants").doc(i).collection(d.collection).doc(e).update({User_ID:B.FieldValue.delete()}),w}const $=["delete",C,e,r],v=[...$];return await ae("postWrite",o,y,$),await ae("postOperation",o,y,v),{id:e,...C}},Xc=async(n,e)=>{const t=B.getFirestore(),s=Qs(),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)},eu=n=>n!==null&&typeof n=="object",tu=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{r instanceof B.Timestamp?t[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:eu(r)&&e(r)})};e(n)},nu=async n=>await yt.getAuth().getUser(n),su=n=>{const e=Ks();return V.fromJSDate(n).setZone(e)},Vo=n=>{const e=Ks();return V.fromJSDate(n.toDate()).setZone(e)},ru=(n,e)=>{const s=V.fromJSDate(n,{zone:e}).offset,i=V.fromJSDate(n).offset,o=s-i;return V.fromJSDate(n).plus({minutes:o}).toJSDate()},iu=(n,e)=>{const s=V.fromJSDate(n,{zone:e}).offset,i=V.fromJSDate(n).offset,o=s-i;return V.fromJSDate(n).minus({minutes:o}).toJSDate()},ou=n=>"seconds"in n&&"nanoseconds"in n?Vo(new B.Timestamp(n.seconds,n.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=Jc;exports.addUser=sr;exports.convertDateToTimezone=su;exports.convertTimestampToTimezone=Vo;exports.deleteRecord=Kc;exports.deleteUser=Ut;exports.deserializeDeleteSentinels=Yn;exports.deserializeTimestamps=ir;exports.deserializeTimestampsWithoutUnderscores=qc;exports.displayDate=ou;exports.fetchCurrentSchema=je;exports.fetchLastSchema=Zc;exports.getCachedConfigValue=na;exports.getCollectionRefs=No;exports.getCustomizationFile=Ze;exports.getCustomizationFiles=So;exports.getDocumentRefs=Xs;exports.getFirestorePathRef=Se;exports.getGlobalConfigModule=vt;exports.getInputSchema=Mc;exports.getMaintenanceInfo=Wc;exports.getMode=Qs;exports.getOne=Qe;exports.getSome=tr;exports.getTenant=ze;exports.getTimezone=Ks;exports.getUser=nu;exports.getVersionInfo=Uc;exports.getZodSchema=Oi;exports.initializeFirebase=zc;exports.initializeStoker=Lc;exports.isDeleteSentinel=xe;exports.keepTimezone=ru;exports.removeTimezone=iu;exports.runChildProcess=jc;exports.sendMail=nr;exports.sendMessage=Xc;exports.serializeTimestamps=tu;exports.setTenant=Vc;exports.tryPromise=oe;exports.updateRecord=Lo;exports.updateUser=Po;exports.validateRelations=or;exports.validateSoftDelete=ar;exports.writeLog=pt;
14
+ <a href="${b}">${b}</a>`)}catch{throw await Jt(o.User_ID,a,c,p),new Error(p)}}}}}else if(n==="delete")try{await Ut(o)}catch(y){throw new Error(y.message)}if(O)return O},Qc=async(n,e,t)=>{const s=ze(),r=B.getFirestore(),i=[e];t&&t.trim()!==""&&i.push(t),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await n.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)n.set(a,{locked:!0})},oi=async(n,e)=>{const t=ze(),s=B.getFirestore(),r=[n];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(t).collection("system_locks").doc(o);i.delete(a)}await i.commit()},Lo=async(n,e,t,s)=>{const r=s?.userId,i=s?.user;let o=s?.context;const a=ze(),l=Et();if(s?.providedTransaction&&r)throw new Error("PERMISSION_DENIED");if(s?.providedSchema&&r)throw new Error("PERMISSION_DENIED");if(s?.providedTransaction&&!s?.originalRecord)throw new Error("PERMISSION_DENIED");let c=s?.providedSchema||await je(!0);if(n.length===0)throw new Error("EMPTY_PATH");const u=n.at(-1),h=Object.keys(c.collections).includes(u),d=l.disabledCollections?.includes(u);if(!h||d)throw new Error("COLLECTION_NOT_FOUND");const f=c.collections[u],{labels:p,fields:O,enableWriteLog:y}=f,g=Ze(p.collection,c),N=await oe(l.appName),b=yt.getAuth(),x=B.getFirestore();let v;r&&await rr(n,f);const C=Se(x,n,a);o=o||{},o.collection=p.collection;let _=s?.originalRecord||await Qe(n,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0});for(const S of O)S.type==="Computed"&&delete t[S.name];if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([S,L])=>[S,{...L,fields:L.fields.filter(Z=>Z.type!=="Computed")}]))},i&&!i.operation)throw new Error("VALIDATION_ERROR: User operation is required");if(i&&!f.auth)throw new Error("VALIDATION_ERROR: User operations are only permitted for auth collections");if(i?.operation==="delete"&&i.permissions)throw new Error("VALIDATION_ERROR: Permissions are not allowed for delete operations");const z=f.auth&&i?.operation==="create",k=f.auth&&i?.operation==="delete",m=f.auth&&!z&&!k&&(i?.operation==="update"||t.Role||t.Enabled!==void 0||t.Name||t.Email||t.Photo_URL),$=S=>S.User_ID&&(f.auth&&!z&&!k&&i?.operation==="update"||t.Role&&t.Role!==S.Role||t.Enabled!==void 0&&t.Enabled!==S.Enabled||t.Name&&t.Name!==S.Name||t.Email&&t.Email!==S.Email||t.Photo_URL&&t.Photo_URL!==S.Photo_URL);delete t.id,ir(t),Yn(t);const E=Vs("update",n,t,c,N,"Online",r||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp()),H=he(E);for(const S of O)!X(S)&&xe(E[S.name])&&S.nullable&&(E[S.name]=null);Le(E),Le(_),y&&!s?.providedTransaction&&await pt("update","started",E,a,n,e,f,void 0,_);const w={operation:"update",data:E,docId:e,context:o,originalRecord:he(_)};await ae("preOperation",l,g,w);const I={operation:"update",data:E,docId:e,context:o,originalRecord:he(_)};await ae("preWrite",l,g,I),Tn(f,E,c),Sn(f,E),Le(E);try{if(z&&!i.password)throw new Error("Password is required");if(!s?.providedTransaction){const S={..._,...E};await Fo("update",a,e,S,f,c),nt(S),await nn("update",S,f,g,{operation:"update",record:E,context:o,originalRecord:he(_)},c)}}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}Le(E),delete t.id,Tn(f,E,c),Sn(f,E);for(const S of O)!X(S)&&xe(E[S.name])&&S.nullable&&(E[S.name]=null);try{const S={..._,...E};nt(S),ar("update",f,E,_),$o("update",E,H),await nn("update",S,f,g,{operation:"update",record:E,context:o,originalRecord:_},c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}let T;i&&(i.permissions||={});const R=async(S,L,Z)=>{const[K,te,qe,fe,Re]=await Promise.all([s?.providedTransaction?Promise.resolve({}):S.get(x.collection("system_deployment").doc("latest_deploy")),s?.providedTransaction?Promise.resolve({}):S.get(x.collection("system_deployment").doc("maintenance_mode")),s?.providedTransaction?Promise.resolve(_):Qe(n,e,{userId:r,providedTransaction:S,noComputedFields:!0}),r?S.get(x.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve({}),s?.providedSchema?Promise.resolve(s.providedSchema):je()]);if(Z&&(Z.size+=3),!s?.providedTransaction){if(!K.exists)throw new Error("VERSION_ERROR");const ge=K.data();if(ge.force&&E.Last_Write_At.valueOf()<ge.time.valueOf())throw new Error("VERSION_ERROR");if(!te.exists)throw new Error("MAINTENANCE_MODE");if(te.data().active)throw new Error("MAINTENANCE_MODE")}if(!qe)throw new Error("NOT_FOUND");if(_=qe,c=Re,r){if(!fe?.exists)throw new Error("PERMISSION_DENIED");if(v=fe.data(),!v.Role)throw new Error("USER_ERROR");if(!v.Enabled)throw new Error("PERMISSION_DENIED")}if(Z&&(Z.size+=Xs(a,n,e,c,v).length),z&&_.User_ID||k&&!_.User_ID)throw new Error("USER_ERROR");if($(_)){const ge=await S.get(x.collection("tenants").doc(a).collection("system_user_permissions").doc(_.User_ID));if(Z&&Z.size++,!ge?.exists)throw new Error("PERMISSION_DENIED");if(T=ge.data(),i?.permissions){if(i.permissions.Role||=E.Role||_.Role,i.permissions.Enabled??=E.Enabled??_.Enabled,xe(i.permissions.Role))throw new Error("VALIDATION_ERROR: Role field is required");if(xe(i.permissions.Enabled))throw new Error("VALIDATION_ERROR: Enabled field is required")}}if(!s?.providedTransaction){const Wt=O.filter(we=>"unique"in we&&we.unique).map(async we=>{if(!r||!we.access||we.access.includes(v.Role)){if(E[we.name]===void 0||xe(E[we.name]))return;const jt=Ae(we,g),cn={..._,...E};if(!(r&&jt?.custom?.serverAccess?.read!==void 0?await oe(jt.custom.serverAccess.read,[v?.Role,cn]):!0))throw new Error("PERMISSION_DENIED");const Jn=E[we.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Js(Jn)){if(Z&&Z.size++,Z&&Z.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 lr=await S.get(x.collection("tenants").doc(a).collection("system_unique").doc(p.collection).collection(`Unique-${p.collection}-${we.name}`).doc(Jn));if(lr.exists&&lr.data().id!==e)throw new Error(`VALIDATION_ERROR: ${we.name} "${E[we.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${we.name} "${E[we.name]}" is invalid`)}});await Promise.all(Wt)}if(r&&v?.Role){const ge=v.Role,Wt={..._,...E};if(!(g.custom?.serverAccess?.update!==void 0?await oe(g.custom.serverAccess.update,[ge,Wt,_]):!0))throw new Error("PERMISSION_DENIED");for(const jt of f.fields){const cn=Ae(jt,g);if(Object.prototype.hasOwnProperty.call(E,jt.name)&&cn?.custom?.serverAccess?.update!==void 0&&!await oe(cn.custom.serverAccess.update,[ge,Wt,_]))throw new Error("PERMISSION_DENIED")}}dr(E,_,e,f,c,r,v,i?.operation?i.operation:m?"update":void 0,i?.permissions,T),i?.permissions&&r&&v&&await Mo(S,i.permissions,r,v,c,T,Z),dr(E,_,e,f,c,r,v,i?.operation?i.operation:m?"update":void 0,i?.permissions,T),L&&(z||$(_)||k)&&await Qc(S,e,_.User_ID)};(z||m||k)&&await x.runTransaction(async S=>{await R(S,!0)},{maxAttempts:10});const A=async(S,L)=>{if(!_)throw new Error("NOT_FOUND");try{const Z={size:1},K={..._,...E};await R(S,!1,Z);let te;!s?.noTwoWay&&!s?.providedTransaction&&(te=await or("Update",a,e,K,E,f,c,S,Z,r,v,_));const qe=Ls(c);Ys("update",S,n,e,E,c,f,s,qe,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,fe=>x.collection("tenants").doc(a).collection("system_fields").doc(p.collection).collection(`${p.collection}-${fe.name}`).doc(e),(fe,Re)=>x.collection("tenants").doc(a).collection("system_unique").doc(p.collection).collection(`Unique-${p.collection}-${fe.name}`).doc(Re),fe=>x.collection("tenants").doc(a).collection("system_fields").doc(p.collection).collection(`${p.collection}-${fe}`).doc(e),(fe,Re)=>Se(x,fe,a).doc(Re),(fe,Re,ge)=>x.collection("tenants").doc(a).collection("system_fields").doc(fe.collection).collection(`${fe.collection}-${Re}`).doc(ge),(fe,Re,ge)=>x.collection("tenants").doc(a).collection("system_fields").doc(fe.collection).collection(`${fe.collection}-${Re.replaceAll(" ","-")}`).doc(ge),_,te,Z),S.update(C.doc(e),E)}catch(Z){if(s?.providedTransaction)throw Z;{const K={operation:"update",data:E,docId:e,context:o,error:Z,originalRecord:he(_)},te=await ae("postWriteError",l,g,K);if(y&&(await new Promise(qe=>{setTimeout(qe,250)}),await pt("update",te?.resolved?"success":"failed",E,a,n,e,f,te?.resolved?void 0:Z,_)),!te?.resolved)throw z&&await Ut(_),$(_)&&await Jt(_.User_ID,L,T,"USER_ERROR"),k&&await x.collection("tenants").doc(a).collection(p.collection).doc(e).update({User_ID:B.FieldValue.delete()}),Z}}(z||$(_)||k)&&await ni(oi,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")})};try{let S;if(z||$(_)||k){if($(_)){S=await b.getUser(_.User_ID);const K=S.customClaims;if(!(K&&K.role&&K.collection&&K.doc))throw new Error("USER_ERROR")}const L={..._,...E};nt(L);const Z=await Po(i?.operation||"update",a,e,l,p.collection,L,_,S,i?.permissions,T,i?.password);z&&(E.User_ID=Z),k&&(E.User_ID=B.FieldValue.delete())}s?.providedTransaction?await A(s.providedTransaction,S):await x.runTransaction(async L=>{await A(L,S)},{maxAttempts:10})}catch(S){throw(z||$(_)||k)&&await ni(oi,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),S}if(!s?.providedTransaction){const S={operation:"update",data:E,docId:e,context:o,originalRecord:he(_)},L={...S};await ae("postWrite",l,g,S),await ae("postOperation",l,g,L)}const q={..._,...E};return nt(q),{id:e,...q}},Kc=async(n,e,t)=>{const s=t?.userId;let r=t?.context;const i=ze(),o=Et();let a=await je();if(n.length===0)throw new Error("EMPTY_PATH");const l=n.at(-1),c=Object.keys(a.collections).includes(l),u=o.disabledCollections?.includes(l);if(!c||u)throw new Error("COLLECTION_NOT_FOUND");const h=a.collections[l],{labels:d,auth:f,enableWriteLog:p,softDelete:O}=h,y=Ze(d.collection,a),g=await oe(o.appName);if(O&&!f&&!t?.force)return await Lo(n,e,{[O.archivedField]:!0,[O.timestampField]:B.FieldValue.serverTimestamp()},{userId:s});const N=B.getFirestore();let b;s&&await rr(n,h);const x=Se(N,n,i);r=r||{},r.collection=d.collection;const v=await Qe(n,e,{userId:s});let C=Vs("delete",n,v,a,g,"Online",s||"System",B.Timestamp.now(),B.FieldValue.serverTimestamp());const _=bn(C);Le(C),p&&await pt("delete","started",C,i,n,e,h),await ae("preOperation",o,y,{operation:"delete",data:C,docId:e,context:r}),await ae("preWrite",o,y,{operation:"delete",data:C,docId:e,context:r}),Le(C);const m=async w=>{const[I,T,R,A]=await Promise.all([w.get(N.collection("system_deployment").doc("maintenance_mode")),Qe(n,e,{userId:s,providedTransaction:w}),s?w.get(N.collection("tenants").doc(i).collection("system_user_permissions").doc(s)):Promise.resolve({}),je()]);if(!I.exists)throw new Error("MAINTENANCE_MODE");if(I.data().active)throw new Error("MAINTENANCE_MODE");if(!T)throw new Error("NOT_FOUND");if(C={...T,..._},a=A,s){if(!R?.exists)throw new Error("PERMISSION_DENIED");if(b=R.data(),!b.Role)throw new Error("USER_ERROR");if(!b.Enabled)throw new Error("PERMISSION_DENIED");Jo(C,e,h,a,s,b)}if(s&&b?.Role){const P=b.Role;if(!(y.custom?.serverAccess?.delete!==void 0?await oe(y.custom.serverAccess.delete,[P,C]):!0))throw new Error("PERMISSION_DENIED")}};h.auth&&(await N.runTransaction(async w=>{await m(w)},{maxAttempts:10}),C.User_ID&&await Ut(C));try{await N.runTransaction(async w=>{await m(w);const I=Ls(a);Ys("delete",w,n,e,C,a,h,t,I,B.FieldValue.arrayUnion,B.FieldValue.arrayRemove,B.FieldValue.delete,T=>N.collection("tenants").doc(i).collection("system_fields").doc(d.collection).collection(`${d.collection}-${T.name}`).doc(e),(T,R)=>N.collection("tenants").doc(i).collection("system_unique").doc(d.collection).collection(`Unique-${d.collection}-${T.name}`).doc(R),T=>N.collection("tenants").doc(i).collection("system_fields").doc(d.collection).collection(`${d.collection}-${T}`).doc(e),(T,R)=>Se(N,T,i).doc(R),(T,R,A)=>N.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${R}`).doc(A),(T,R,A)=>N.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${R.replaceAll(" ","-")}`).doc(A)),w.delete(x.doc(e))},{maxAttempts:10})}catch(w){const T=await ae("postWriteError",o,y,{operation:"delete",data:C,docId:e,context:r,error:w});if(p&&(await new Promise(R=>{setTimeout(R,250)}),await pt("delete",T?.resolved?"success":"failed",C,i,n,e,h,T?.resolved?void 0:w)),!T?.resolved)throw h.auth&&C.User_ID&&await N.collection("tenants").doc(i).collection(d.collection).doc(e).update({User_ID:B.FieldValue.delete()}),w}const $={operation:"delete",data:C,docId:e,context:r},E={...$};return await ae("postWrite",o,y,$),await ae("postOperation",o,y,E),{id:e,...C}},Xc=async(n,e)=>{const t=B.getFirestore(),s=Qs(),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)},eu=n=>n!==null&&typeof n=="object",tu=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{r instanceof B.Timestamp?t[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:eu(r)&&e(r)})};e(n)},nu=async n=>await yt.getAuth().getUser(n),su=n=>{const e=Ks();return V.fromJSDate(n).setZone(e)},Vo=n=>{const e=Ks();return V.fromJSDate(n.toDate()).setZone(e)},ru=(n,e)=>{const s=V.fromJSDate(n,{zone:e}).offset,i=V.fromJSDate(n).offset,o=s-i;return V.fromJSDate(n).plus({minutes:o}).toJSDate()},iu=(n,e)=>{const s=V.fromJSDate(n,{zone:e}).offset,i=V.fromJSDate(n).offset,o=s-i;return V.fromJSDate(n).minus({minutes:o}).toJSDate()},ou=n=>"seconds"in n&&"nanoseconds"in n?Vo(new B.Timestamp(n.seconds,n.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=Jc;exports.addUser=sr;exports.convertDateToTimezone=su;exports.convertTimestampToTimezone=Vo;exports.deleteRecord=Kc;exports.deleteUser=Ut;exports.deserializeDeleteSentinels=Yn;exports.deserializeTimestamps=ir;exports.deserializeTimestampsWithoutUnderscores=qc;exports.displayDate=ou;exports.fetchCurrentSchema=je;exports.fetchLastSchema=Zc;exports.getCachedConfigValue=na;exports.getCollectionRefs=No;exports.getCustomizationFile=Ze;exports.getCustomizationFiles=So;exports.getDocumentRefs=Xs;exports.getFirestorePathRef=Se;exports.getGlobalConfigModule=Et;exports.getInputSchema=Mc;exports.getMaintenanceInfo=Wc;exports.getMode=Qs;exports.getOne=Qe;exports.getSome=tr;exports.getTenant=ze;exports.getTimezone=Ks;exports.getUser=nu;exports.getVersionInfo=Uc;exports.getZodSchema=Oi;exports.initializeFirebase=zc;exports.initializeStoker=Lc;exports.isDeleteSentinel=xe;exports.keepTimezone=ru;exports.removeTimezone=iu;exports.runChildProcess=jc;exports.sendMail=nr;exports.sendMessage=Xc;exports.serializeTimestamps=tu;exports.setTenant=Vc;exports.tryPromise=oe;exports.updateRecord=Lo;exports.updateUser=Po;exports.validateRelations=or;exports.validateSoftDelete=ar;exports.writeLog=pt;