@stoker-platform/node-client 0.5.86 → 0.5.88

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 Qe=require("lodash/isEqual.js"),Bo=require("lodash/merge.js"),Ho=require("lodash/set.js"),he=require("lodash/cloneDeep.js"),wt=require("firebase-admin/app"),ie=require("firebase-admin/firestore"),di=require("node:url"),Go=require("cross-spawn"),fi=require("firebase-admin/database"),Ot=require("firebase-admin/auth"),Zn=t=>!!t.auth,Re=(t,e)=>{if(e?.operations)return e.operations.includes(t)},qn=(t,e)=>e?e.Role?t.access?.includes(e.Role):!1:!0,Yo=(t,e)=>e?!e.Role||t.restrictCreate===!0?!1:typeof t.restrictCreate=="object"?t.restrictCreate?.includes(e.Role):!0:!0,hi=(t,e)=>e?!e.Role||t.restrictUpdate===!0?!1:typeof t.restrictUpdate=="object"?t.restrictUpdate?.includes(e.Role):!0:!0,hr=(t,e,n)=>{const{labels:s}=t;return n.collections&&Re("Update",n.collections[s.collection])&&(!e.access||qn(e,n))&&hi(e,n)&&!(t.auth&&!n.collections?.[s.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},U=(t,e)=>t.filter(n=>n.name===e)[0],X=t=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(t.type),mi=(t,e)=>{const n={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=t,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const d=a?.[n[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},Vs=(t,e)=>{const n=[],{labels:s,access:r}=t,{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)&&n.push(a)})}),n},pi=(t,e,n)=>{const s=[],{access:r}=t,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.role===n.Role))return;const a=o.collectionField,l=U(t.fields,a);if(!X(l))throw new Error("PERMISSION_DENIED");const c=n.collections?.[l.collection],m=e.collections[l.collection].access.entityRestrictions;if(!m)throw new Error("PERMISSION_DENIED");const u=m.restrictions?.find(f=>f.type===o.type&&f.roles.some(g=>g.role===n.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===n.Role&&(!m.assignable?.includes(n.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},yi=(t,e,n)=>{const s=Object.values(e.collections),{labels:r}=t,i=[];for(const o of s){const{fields:a}=o;for(const l of a)if(!(l.access&&!qn(l,n))&&n.Role&&X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)!i.find(m=>m.field===c.field)&&c.roles.includes(n.Role)&&i.push(c)}return i},Jo=(t,e,n,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const d=mi(e,r),m=Vs(e,r),u=pi(e,n,r);d?.filter(E=>E.type==="Record_Owner").forEach(E=>{"operations"in E&&E.operations&&!E.operations.includes(t)||i.Created_By!==s&&(c=!1)}),d?.filter(E=>E.type==="Record_User").forEach(E=>{if("operations"in E&&E.operations&&!E.operations.includes(t))return;const C=U(a,E.collectionField);i[`${C.name}_Array`]?.includes(r.Doc_ID)||(c=!1)}),d?.filter(E=>E.type==="Record_Property").forEach(E=>{if("operations"in E&&E.operations&&!E.operations.includes(t))return;const C=U(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,g=!1;m?.filter(E=>E.type==="Individual").forEach(()=>{g=!0,l?.individualEntities?.includes(i.id)||(f=!1)});let v=!0,y=!1;if(m?.filter(E=>E.type==="Parent").forEach(E=>{y=!0;const C=U(a,E.collectionField);l?.parentEntities?.some(_=>i[`${C.name}_Array`].includes(_))||(v=!1)}),m?.filter(E=>E.type==="Parent_Property").forEach(E=>{y=!0;const C=U(a,E.collectionField),_=U(a,E.propertyField);Object.entries(l?.parentPropertyEntities||{}).some(Z=>{const[k,p]=Z;return k===i[_.name]&&i[`${C.name}_Array`].some(F=>p.includes(F))})||(v=!1)}),g&&y){if(!(f||v)){c=!1;return}}else if(!f||!v){c=!1;return}let w=!0,R=!1;u?.filter(E=>E.parentFilter.type==="Individual").forEach(E=>{R=!0;const{parentFilter:C}=E,_=U(a,C.collectionField),Z=r.collections?.[_.collection];if(!Z){c=!1;return}Z.individualEntities?.some(k=>i[`${_.name}_Array`].includes(k))||(w=!1)});let O=!0,I=!1;if(u?.filter(E=>E.parentFilter.type==="Parent").forEach(E=>{I=!0;const{parentFilter:C}=E,_=U(a,C.collectionField),Z=U(a,C.parentCollectionField),k=r.collections?.[_.collection];if(!k){c=!1;return}k.parentEntities?.some(p=>i[`${Z.name}_Array`].includes(p))||(O=!1)}),u?.filter(E=>E.parentFilter.type==="Parent_Property").forEach(E=>{I=!0;const{parentFilter:C}=E,_=U(a,C.collectionField),Z=U(a,C.parentPropertyField),k=U(a,C.parentCollectionField),p=r.collections?.[_.collection];if(!p){c=!1;return}Object.entries(p.parentPropertyEntities||{}).some(F=>{const[A,j]=F;return A===i[Z.name]&&i[`${k.name}_Array`].some(h=>j.includes(h))})||(O=!1)}),R&&I){if(!(w||O)){c=!1;return}}else if(!w||!O){c=!1;return}return c},lt=(t,e,n,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;Re(t,a)||(l=!1);const d=Vs(e,r)?.filter(m=>m.type==="Individual").length>0;return t==="Create"&&d&&(l=!1),Jo(t,e,n,s,r,i)||(l=!1),l},gi=(t,e,n)=>{const{labels:s}=t,r=[];for(const i of Object.values(e.collections));return r},Qo=(t,e)=>{let n=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){n=!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(t.collections).includes(r)){s=`Collection ${r} not found in schema`,n=!1;return}const i=t.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,n=!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`,n=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,n=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,n=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,n=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),m=i.access.entityRestrictions?.restrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(u=>t.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,n=!1;return}if(d?.length||m?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const u=Object.keys(l);if(u.length!==1||u[0]!=="active"||typeof l.active!="boolean"){s=`Collection ${r} has invalid attribute restriction value`,n=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,n=!1;return}if(a==="Parent"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,n=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,n=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,n=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),n},Ko=(t,e,n)=>{let s=!0,r="";Object.values(t.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(t.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:d,entityRestrictions:m}=a,u=c.assignable,f=e.collections?.[o.collection],g=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(n))?g.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const R=!!a.operations[y]?.includes(n),O=!!f?.operations.includes(w);if(!R&&O){r=`Collection ${o.collection} has excess ${y} operation for role ${n}`,s=!1;return}if(R&&!O){r=`Collection ${o.collection} has missing ${y} operation for role ${n}`,s=!1;return}}}):g.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const R=!!a.operations[y]?.includes(n),O=!!f?.operations.includes(w);if(!R&&O){r=`Collection ${o.collection} has excess ${y} operation for role ${n}`,s=!1;return}}}),!d&&!m||(d?.forEach(y=>{for(const w of y.roles)if(w.role===n&&!w.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${n}`,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 ${n}`,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 ${n}`,s=!1;return}}}),m?.assignable?.includes(n)))continue;let v=!1;if(m?.restrictions?.forEach(y=>{for(const w of y.roles)if(w.role===n){if(v=!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 R=U(l,y.collectionField);if(!X(R)){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 R=U(l,y.collectionField);if(!X(R)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[R.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),v&&!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},Xo=(t,e,n,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:d}=c;let m=!0,u="";const f=d?.filter(g=>s===g.userRole);return f?.length&&!f.some(g=>g.recordRole===r)?(u=`User ${s} does not have write access to record with role ${r}`,m=!1,m):t==="update"&&o.User_ID&&f?.length&&!f.some(g=>g.recordRole===a)?(u=`User ${s} does not have write access to record with role ${r}`,m=!1,m):(d?.forEach(g=>{s===g.userRole&&g.recordRole===r&&t!=="delete"&&i&&Object.keys(n.collections).forEach(v=>{const y=i.collections?.[v],w=l?.collections?.[v];if(!(t==="update"&&Qe(y,w))&&y){const R=g.collections.some(O=>O.collection===v);if(R){if(R){const O=g.collections.find(E=>E.collection===v);if(!(y.operations.every(E=>O.operations.includes(E))||t==="update"&&Qe(y.operations,w?.operations))){u=`User ${s} does not have write access to all included operations for collection ${v}`,m=!1;return}if(!O.auth&&y.auth&&!(t==="update"&&Qe(y.auth,w?.auth))){u=`User ${s} does not have write access to auth for collection ${v}`,m=!1;return}const I={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(I).forEach(E=>{const C=I[E];if(O.attributeRestrictions?.includes(C)&&!(y[E]?.active||t==="update"&&Qe(y[E],w?.[E]))){u=`User ${s} does not have write access to attribute restriction ${E} for collection ${v}`,m=!1;return}}),O.restrictEntities&&!y.restrictEntities&&!(t==="update"&&Qe(y.restrictEntities,w?.restrictEntities))){u=`User ${s} does not have write access to restrictEntities for collection ${v}`,m=!1;return}}}else{u=`User ${s} does not have write access to collection ${v}`,m=!1;return}}})}),u&&console.error(`PERMISSION_DENIED: ${u}`),m)},ea=(t,e,n,s)=>{let r=!0,i="";return Object.values(t.collections).forEach(o=>{const a=n.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!Zn(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const d of a?.operations||[])if(!l?.operations.includes(d)&&(!Re("Read",c)||!Re(d,c))){i=`User does not have ${d.toLowerCase()} access to collection ${o.labels.collection}`,r=!1;return}if(!a?.recordOwner&&l?.recordOwner&&c?.recordOwner){i=`User does not have write access to recordOwner for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordUser&&l?.recordUser&&c?.recordUser){i=`User does not have write access to recordUser for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordProperty&&l?.recordProperty&&c?.recordProperty){i=`User does not have write access to recordProperty for collection ${o.labels.collection}`,r=!1;return}if(!a?.restrictEntities&&l?.restrictEntities&&c?.restrictEntities){i=`User does not have write access to restrictEntities for collection ${o.labels.collection}`,r=!1;return}}),i&&console.error(`PERMISSION_DENIED: ${i}`),r},Us=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:m}=s;let u=!0,f="";if(!e.Role)return f="Record does not have a role",u=!1,u;if(t==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(t==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!Xo(t,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(t==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;if(t==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return f="User cannot update their own record",u=!1,u;if(t==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return t==="delete"||d==="delete"||!a?u:a.Role?(Qo(r,a)||(u=!1),a.Collection&&a.Collection!==m.collection?(f="Permissions collection does not match record collection",u=!1,u):a.Role!==e.Role?(f="Permissions role does not match record role",u=!1,u):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",u=!1,u):a.Doc_ID&&a.Doc_ID!==n?(f="Permissions doc ID does not match record doc ID",u=!1,u):!Ko(r,a,a.Role)||i&&o&&l&&!ea(r,o,a,l)?(u=!1,u):(f&&console.error(`PERMISSION_DENIED: ${f}`),u)):(f="Permissions do not have a role",u=!1,u)},mr=(t,e,n,s,r,i,o)=>{const{labels:a,fields:l}=n,c=i?.collections?.[a.collection];let d=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!Re("Create",c)&&(d=!1),r&&!lt("Create",n,s,r,i,t)&&(d=!1),n.auth&&o&&(r&&!Zn(c)&&(d=!1),Us("create",t,e,n,s,r,i,o)||(d=!1));for(const m of l){const u=t[m.name];m.access&&!qn(m,i)&&u!==void 0&&(d=!1),u!==void 0&&!Yo(m,i)&&(d=!1)}if(!d)throw new Error("PERMISSION_DENIED")},Te=t=>t&&(t._methodName==="deleteField"||t.constructor.name==="DeleteTransform"),it=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(Te(t[e])?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&it(t[e]))},pr=(t,e,n,s,r,i,o,a,l,c)=>{const{labels:d,fields:m}=s,u=o?.collections?.[d.collection],f={...e,...t};it(f);let g=!0,v="";if(i&&!u)throw new Error("PERMISSION_DENIED");i&&!Re("Update",u)&&(g=!1,v="Authenticated user does not have Update access to this collection"),i&&(!lt("Update",s,r,i,o,e)||!lt("Update",s,r,i,o,f))&&(g=!1,v="Authenticated user does not have Update access to this document"),i&&s.softDelete&&f[s.softDelete.archivedField]!==e[s.softDelete.archivedField]&&!Re("Delete",u)&&(g=!1,v="Authenticated user does not have Delete or Restore access to this document"),a&&(i&&!Zn(u)&&(g=!1,v="Authenticated user does not have Auth access for this collection"),Us("update",f,n,s,r,i,o,l,c,e,a)||(v="Authenticated user does not have sufficient write access for this record",g=!1));for(const y of m){const w=t[y.name];y.access&&!qn(y,o)&&w!==void 0&&(v=`Authenticated user does not have access to field ${y.name}`,g=!1),w!==void 0&&!hi(y,o)&&(v=`Authenticated user does not have Update access to field ${y.name}`,g=!1)}if(!g)throw v&&console.error(`PERMISSION_DENIED: ${v}`),new Error("PERMISSION_DENIED")},ta=(t,e,n,s,r,i)=>{const{labels:o}=n,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(Re("Delete",a)||(l=!1),lt("Delete",n,s,r,i,t)||(l=!1),n.auth&&t.User_ID&&(Zn(a)||(l=!1),Us("delete",t,e,n,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},na=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Re("Read",o)||(a=!1),lt("Read",e,n,s,r,t)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},sa=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Re("Read",o)||(a=!1),t.forEach(l=>{lt("Read",e,n,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},ra=(t,e,n)=>{const{access:s}=t;return s.operations[n]?.includes(e)},ia=(t,e,n)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===t)&&!("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===t))continue;const o=U(e.fields,i.collectionField);if(!X(o))throw new Error("PERMISSION_DENIED");const l=n.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(d=>d.role===t));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},oa=(t,e,n,s,r)=>{const i={};for(const o of t){const l=e[o].default({sdk:n,utils:s,context:r});for(const c in l)c==="custom"||c==="admin"||c==="fields"||delete l[c];for(const c of l.fields)for(const d in c)d==="custom"||d==="admin"||d==="name"||d==="formula"||delete c[d];i[o]=l}return i},Ce=(t,e)=>e.fields.filter(n=>n.name===t.name)[0],es={global:{},collections:{}},Gt=(t,e)=>t&&typeof t=="function"?e?t(...e):t():t,oe=async(t,e)=>{let n=t;return t&&(typeof t=="function"||typeof t.then=="function")&&(e?n=await t(...e):n=await t()),n},aa=async(t,e,n,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=es,i=!0;for(const d of e){if(d===void 0||r[d]===void 0){i=!1;break}r=r[d]}if(r&&i&&!s)return r;let o,a=t,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await oe(a,n)),c){let d=es;const m={};for(let u=0;u<e.length;u++){const f=e[u];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");u===e.length-1?Ho(m,e.join("."),c):(d[f]||={},d=d[f])}}Bo(es,m)}return c},dt=(t,e,n)=>{const s=Object.values(n.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===t.name&&(i=!0)}return i},wi=(t,e)=>{const n=Object.values(e.collections),{labels:s}=t,r={};return n.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},ts=t=>JSON.stringify(t.map(e=>e.name)),_t=["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"],Bn=()=>_t.map(t=>{let e="",n;switch(t){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",n=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:t,type:e,required:!0};return n&&(s.values=n),s}),_i=(t,e)=>{const n=[],{access:s,fields:r}=t,{attributeRestrictions:i,entityRestrictions:o}=s,a=Bn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":n.push(U(a,"Created_By"));break;case"Record_User":n.push(U(r,l.collectionField));break;case"Record_Property":n.push(U(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(U(a,"id"));break;case"Parent":n.push(U(r,l.collectionField));break;case"Parent_Property":n.push(U(r,l.collectionField)),n.push(U(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(U(r,l.collectionField));break;case"Parent":n.push(U(r,l.parentCollectionField));break;case"Parent_Property":n.push(U(r,l.parentCollectionField)),n.push(U(r,l.parentPropertyField));break}})),[...new Set(n)]},la=(t,e)=>{const n=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=t,a=Bn();return n.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{(!c.access||c.access.includes(e))&&n.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{n.push(U(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{_t.includes(c)&&n.push(U(a,c))}),o?.forEach(c=>{const d=U(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&d&&(!d.access||d.access?.includes(e))&&_t.includes(c.field)&&n.push(U(a,c.field))}),_i(t,e).forEach(c=>{_t.includes(c.name)&&n.push(U(a,c.name))}),[...new Set(n)]},ca=(t,e,n)=>{const s=[],{fields:r,preloadCache:i}=e,o=Bn();i?.range&&i.range.fields.forEach(c=>{_t.includes(c)?s.push(U(o,c)):s.push(U(r,c))});const a=new Set,l=wi(e,n);return Object.entries(l).map(([c,d])=>{t.name===c&&Object.values(d).forEach(m=>{m.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(..._i(e,c))}),[...new Set(s)]},mn=(t,e,n)=>{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=wi(e,n);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{n.collections[c].fields.forEach(m=>{X(m)&&m.collection===e.labels.collection&&m.dependencyFields?.some(u=>u.field===t.name)&&m.constraints&&m.constraints.forEach(u=>{o.push(u[0])})})})}),o.forEach(l=>{s.push(U(r,l))}),i){const l=U(r,i.archivedField);l&&s.push(l)}return s.push(...ca(t,e,n)),[...new Set(s)]},Ei=(t,e)=>{const{preloadCache:n}=t,s=new Set;for(const r of e.config.roles){if(!ra(t,r,"read"))continue;const i=la(t,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))&&!!n?.roles.includes(r)==!!a.roles.every(l=>n?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},vi=(t,e,n)=>{const s=Ei(e,n);for(const r of s.values())if(r.roles.includes(t))return r},ua=(t,e)=>{const{fields:n}=e,s=Bn(),r=[];return[...n,...s.filter(o=>o.name!=="id")].forEach(o=>{t?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ws=(t,e,n)=>{const s={};return Object.values(t.collections).forEach(r=>{const i=Ei(r,t),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},In=t=>({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_Version:t.Last_Write_Version,Last_Write_App:t.Last_Write_App,Last_Save_At:t.Last_Save_At}),ns=async(t,e,n)=>{if(e){const s=await oe(e,[n]);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${t}`);return s}};async function ae(t,e,n,s){const r=await ns(t,n.custom?.[t],s);for(const i of n.fields)await ns(t,i.custom?.[t],s);if(t!=="setEmbedding"&&(await ns(t,e?.[t],s),t==="postWriteError"))return r}const js=(t,e,n,s,r,i,o,a,l,c)=>(t==="create"&&(n.Collection_Path=e,n.Created_At=a,n.Saved_At=l,n.Created_By=o||"System"),n.Last_Write_App=r,n.Last_Write_At=a,n.Last_Save_At=l,n.Last_Write_By=o||"System",n.Last_Write_Connection_Status=i,n.Last_Write_Version=s.version,n),mt=(t,e)=>{const{access:n,queries:s}=t,{serverReadOnly:r}=n,i=new Set;if(s)for(const o of s){const a=U(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},kt=(t,e)=>{const{access:n,recordTitleField:s}=t,{serverReadOnly:r}=n,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},da=(t,e)=>{const n={Collection_Path:t.Collection_Path};if(t.deleted!==void 0&&(n.deleted=t.deleted),e)for(const s of e)t[s]!==void 0&&(n[s]=t[s]);return n},pt=(t,e,n)=>{const{fields:s}=t;s.forEach(i=>{if(X(i))if(e[i.name]){if(Te(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(Object.keys(e[i.name]).forEach(o=>{const a=e[i.name][o];e[i.name][o]=da(a,i.includeFields)}),e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=n.collections[i.collection],l=U(a.fields,o);kt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(d=>{e[i.name][d][o]?e[i.name][d][`${o}_Lowercase`]=e[i.name][d][o].toLowerCase():delete e[i.name][d][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),mt(t,s).forEach(i=>{if(e[i.name])if(Te(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}}}})},xn=(t,e)=>{kt(t,t.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},fa=async(t,e,n,s)=>{const{fields:r}=e;for(const i of n.fields){const o=U(r,i.name);i.custom?.initialValue!==void 0&&!(s&&o.access&&!o.access.includes(s))&&(t[i.name]=await oe(i.custom.initialValue,[t]),kt(e,[o]).size===1&&(t[`${i.name}_Lowercase`]=t[i.name].toLowerCase()))}for(const i of r)s&&i.access&&!i.access.includes(s)||("autoIncrement"in i&&i.autoIncrement&&!t[i.name]&&(t[i.name]="Pending"),!X(i)&&i.nullable&&t[i.name]===void 0&&(t[i.name]=null))};var ne;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.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},t.find=(r,i)=>{for(const o of r)if(i(o))return o},t.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)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(ne||(ne={}));var yr;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(yr||(yr={}));const V=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),nt=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}},D=ne.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Xe 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 n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=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(n(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(n(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof Xe))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}Xe.create=t=>new Xe(t);const _s=(t,e)=>{let n;switch(t.code){case D.invalid_type:t.received===V.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case D.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,ne.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:n=`Unrecognized key(s) in object: ${ne.joinValues(t.keys,", ")}`;break;case D.invalid_union:n="Invalid input";break;case D.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${ne.joinValues(t.options)}`;break;case D.invalid_enum_value:n=`Invalid enum value. Expected ${ne.joinValues(t.options)}, received '${t.received}'`;break;case D.invalid_arguments:n="Invalid function arguments";break;case D.invalid_return_type:n="Invalid function return type";break;case D.invalid_date:n="Invalid date";break;case D.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:ne.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case D.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case D.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case D.custom:n="Invalid input";break;case D.invalid_intersection_types:n="Intersection results could not be merged";break;case D.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case D.not_finite:n="Number must be finite";break;default:n=e.defaultError,ne.assertNever(t)}return{message:n}};let ha=_s;function ma(){return ha}const pa=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...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 P(t,e){const n=ma(),s=pa({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===_s?void 0:_s].filter(r=>!!r)});t.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,n){const s=[];for(const r of n){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,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Ee.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){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"}),Yt=t=>({status:"dirty",value:t}),Fe=t=>({status:"valid",value:t}),gr=t=>t.status==="aborted",wr=t=>t.status==="dirty",$t=t=>t.status==="valid",Nn=t=>typeof Promise<"u"&&t instanceof Promise;var W;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(W||(W={}));class Ze{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,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 _r=(t,e)=>{if($t(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Xe(t.common.issues);return this._error=n,this._error}}};function K(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||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}=t;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??n??a.defaultError}},description:r}}class ee{get description(){return this._def.description}_getType(e){return nt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:nt(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:nt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Nn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nt(e)},r=this._parseSync({data:e,path:s.path,parent:s});return _r(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nt(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return $t(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>$t(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nt(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Nn(r)?r:Promise.resolve(r));return _r(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;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,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new Lt({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:n=>this["~validate"](n)}}optional(){return ot.create(this,this._def)}nullable(){return Vt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return We.create(this)}promise(){return $n.create(this,this._def)}or(e){return An.create([this,e],this._def)}and(e){return Cn.create(this,e,this._def)}transform(e){return new Lt({...K(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Ts({...K(this._def),innerType:this,defaultValue:n,typeName:Y.ZodDefault})}brand(){return new La({typeName:Y.ZodBranded,type:this,...K(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Ss({...K(this._def),innerType:this,catchValue:n,typeName:Y.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return zs.create(this,e)}readonly(){return Rs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ya=/^c[^\s-]{8,}$/i,ga=/^[0-9a-z]+$/,wa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_a=/^[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,Ea=/^[a-z0-9_-]{21}$/i,va=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Oa=/^[-+]?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)?)??$/,ka=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ba="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ss;const Ta=/^(?:(?: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])$/,Sa=/^(?:(?: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])$/,Ra=/^(([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]))$/,Ia=/^(([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])$/,xa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Na=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Oi="((\\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])))",Da=new RegExp(`^${Oi}$`);function ki(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Aa(t){return new RegExp(`^${ki(t)}$`)}function Ca(t){let e=`${Oi}T${ki(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Fa(t,e){return!!((e==="v4"||!e)&&Ta.test(t)||(e==="v6"||!e)&&Ra.test(t))}function $a(t,e){if(!va.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.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 Ma(t,e){return!!((e==="v4"||!e)&&Sa.test(t)||(e==="v6"||!e)&&Ia.test(t))}class Ke extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){const i=this._getOrReturnCtx(e);return P(i,{code:D.invalid_type,expected:V.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),P(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),P(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?P(r,{code:D.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&P(r,{code:D.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")ka.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"email",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")ss||(ss=new RegExp(ba,"u")),ss.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"emoji",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")_a.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"uuid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")Ea.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"nanoid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")ya.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")ga.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid2",code:D.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")wa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(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),P(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),P(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),P(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),P(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),P(r,{code:D.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?Ca(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:D.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Da.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:D.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Aa(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:D.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?Oa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"duration",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Fa(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ip",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?$a(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"jwt",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ma(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cidr",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?xa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Na.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64url",code:D.invalid_string,message:i.message}),s.dirty()):ne.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:D.invalid_string,...W.errToObj(s)})}_addCheck(e){return new Ke({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.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,...W.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,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...W.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...W.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...W.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...W.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...W.errToObj(n)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new Ke({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ke({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ke({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Ke.create=t=>new Ke({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...K(t)});function Pa(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Mt 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)!==V.number){const i=this._getOrReturnCtx(e);return P(i,{code:D.invalid_type,expected:V.number,received:i.parsedType}),J}let s;const r=new Ee;for(const i of this._def.checks)i.kind==="int"?ne.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),P(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),P(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),P(s,{code:D.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Pa(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),P(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),P(s,{code:D.not_finite,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,W.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.toString(n))}setLimit(e,n,s,r){return new Mt({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:W.toString(r)}]})}_addCheck(e){return new Mt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Mt.create=t=>new Mt({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...K(t)});class sn 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)!==V.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),P(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),P(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),P(s,{code:D.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):ne.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return P(n,{code:D.invalid_type,expected:V.bigint,received:n.parsedType}),J}gte(e,n){return this.setLimit("min",e,!0,W.toString(n))}gt(e,n){return this.setLimit("min",e,!1,W.toString(n))}lte(e,n){return this.setLimit("max",e,!0,W.toString(n))}lt(e,n){return this.setLimit("max",e,!1,W.toString(n))}setLimit(e,n,s,r){return new sn({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:W.toString(r)}]})}_addCheck(e){return new sn({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}sn.create=t=>new sn({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...K(t)});class Es extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){const s=this._getOrReturnCtx(e);return P(s,{code:D.invalid_type,expected:V.boolean,received:s.parsedType}),J}return Fe(e.data)}}Es.create=t=>new Es({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...K(t)});class Dn extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==V.date){const i=this._getOrReturnCtx(e);return P(i,{code:D.invalid_type,expected:V.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return P(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),P(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),P(r,{code:D.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()):ne.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Dn({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:W.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Dn.create=t=>new Dn({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...K(t)});class Er extends ee{_parse(e){if(this._getType(e)!==V.symbol){const s=this._getOrReturnCtx(e);return P(s,{code:D.invalid_type,expected:V.symbol,received:s.parsedType}),J}return Fe(e.data)}}Er.create=t=>new Er({typeName:Y.ZodSymbol,...K(t)});class vs extends ee{_parse(e){if(this._getType(e)!==V.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:D.invalid_type,expected:V.undefined,received:s.parsedType}),J}return Fe(e.data)}}vs.create=t=>new vs({typeName:Y.ZodUndefined,...K(t)});class vr extends ee{_parse(e){if(this._getType(e)!==V.null){const s=this._getOrReturnCtx(e);return P(s,{code:D.invalid_type,expected:V.null,received:s.parsedType}),J}return Fe(e.data)}}vr.create=t=>new vr({typeName:Y.ZodNull,...K(t)});class Os extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return Fe(e.data)}}Os.create=t=>new Os({typeName:Y.ZodAny,...K(t)});class Or extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Fe(e.data)}}Or.create=t=>new Or({typeName:Y.ZodUnknown,...K(t)});class ct extends ee{_parse(e){const n=this._getOrReturnCtx(e);return P(n,{code:D.invalid_type,expected:V.never,received:n.parsedType}),J}}ct.create=t=>new ct({typeName:Y.ZodNever,...K(t)});class kr extends ee{_parse(e){if(this._getType(e)!==V.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:D.invalid_type,expected:V.void,received:s.parsedType}),J}return Fe(e.data)}}kr.create=t=>new kr({typeName:Y.ZodVoid,...K(t)});class We extends ee{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==V.array)return P(n,{code:D.invalid_type,expected:V.array,received:n.parsedType}),J;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,a=n.data.length<r.exactLength.value;(o||a)&&(P(n,{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&&n.data.length<r.minLength.value&&(P(n,{code:D.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(P(n,{code:D.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>r.type._parseAsync(new Ze(n,o,n.path,a)))).then(o=>Ee.mergeArray(s,o));const i=[...n.data].map((o,a)=>r.type._parseSync(new Ze(n,o,n.path,a)));return Ee.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new We({...this._def,minLength:{value:e,message:W.toString(n)}})}max(e,n){return new We({...this._def,maxLength:{value:e,message:W.toString(n)}})}length(e,n){return new We({...this._def,exactLength:{value:e,message:W.toString(n)}})}nonempty(e){return this.min(1,e)}}We.create=(t,e)=>new We({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...K(e)});function Nt(t){if(t instanceof de){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=ot.create(Nt(s))}return new de({...t._def,shape:()=>e})}else return t instanceof We?new We({...t._def,type:Nt(t.element)}):t instanceof ot?ot.create(Nt(t.unwrap())):t instanceof Vt?Vt.create(Nt(t.unwrap())):t instanceof Et?Et.create(t.items.map(e=>Nt(e))):t}class de 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(),n=ne.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==V.object){const c=this._getOrReturnCtx(e);return P(c,{code:D.invalid_type,expected:V.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 ct&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const d=i[c],m=r.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Ze(r,m,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ct){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")a.length>0&&(P(r,{code:D.unrecognized_keys,keys:a}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of a){const m=r.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Ze(r,m,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const m=await d.key,u=await d.value;c.push({key:m,value:u,alwaysSet:d.alwaysSet})}return c}).then(c=>Ee.mergeObjectSync(s,c)):Ee.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return W.errToObj,new de({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:W.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const n={};for(const s of ne.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new de({...this._def,shape:()=>n})}omit(e){const n={};for(const s of ne.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new de({...this._def,shape:()=>n})}deepPartial(){return Nt(this)}partial(e){const n={};for(const s of ne.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new de({...this._def,shape:()=>n})}required(e){const n={};for(const s of ne.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof ot;)i=i._def.innerType;n[s]=i}return new de({...this._def,shape:()=>n})}keyof(){return bi(ne.objectKeys(this.shape))}}de.create=(t,e)=>new de({shape:()=>t,unknownKeys:"strip",catchall:ct.create(),typeName:Y.ZodObject,...K(e)});de.strictCreate=(t,e)=>new de({shape:()=>t,unknownKeys:"strict",catchall:ct.create(),typeName:Y.ZodObject,...K(e)});de.lazycreate=(t,e)=>new de({shape:t,unknownKeys:"strip",catchall:ct.create(),typeName:Y.ZodObject,...K(e)});class An extends ee{_parse(e){const{ctx:n}=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 n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Xe(a.ctx.common.issues));return P(n,{code:D.invalid_union,unionErrors:o}),J}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new Xe(l));return P(n,{code:D.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}An.create=(t,e)=>new An({options:t,typeName:Y.ZodUnion,...K(e)});function ks(t,e){const n=nt(t),s=nt(e);if(t===e)return{valid:!0,data:t};if(n===V.object&&s===V.object){const r=ne.objectKeys(e),i=ne.objectKeys(t).filter(a=>r.indexOf(a)!==-1),o={...t,...e};for(const a of i){const l=ks(t[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(n===V.array&&s===V.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const o=t[i],a=e[i],l=ks(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===V.date&&s===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Cn extends ee{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(gr(i)||gr(o))return J;const a=ks(i.value,o.value);return a.valid?((wr(i)||wr(o))&&n.dirty(),{status:n.value,value:a.data}):(P(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}))}}Cn.create=(t,e,n)=>new Cn({left:t,right:e,typeName:Y.ZodIntersection,...K(n)});class Et extends ee{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.array)return P(s,{code:D.invalid_type,expected:V.array,received:s.parsedType}),J;if(s.data.length<this._def.items.length)return P(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&&(P(s,{code:D.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Ze(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Ee.mergeArray(n,o)):Ee.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new Et({...this._def,rest:e})}}Et.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Et({items:t,typeName:Y.ZodTuple,rest:null,...K(e)})};class Fn extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.object)return P(s,{code:D.invalid_type,expected:V.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 Ze(s,a,s.path,a)),value:o._parse(new Ze(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Ee.mergeObjectAsync(n,r):Ee.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof ee?new Fn({keyType:e,valueType:n,typeName:Y.ZodRecord,...K(s)}):new Fn({keyType:Ke.create(),valueType:e,typeName:Y.ZodRecord,...K(n)})}}class br extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.map)return P(s,{code:D.invalid_type,expected:V.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 Ze(s,a,s.path,[c,"key"])),value:i._parse(new Ze(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}}}}br.create=(t,e,n)=>new br({valueType:e,keyType:t,typeName:Y.ZodMap,...K(n)});class rn extends ee{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.set)return P(s,{code:D.invalid_type,expected:V.set,received:s.parsedType}),J;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(P(s,{code:D.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(P(s,{code:D.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const d of l){if(d.status==="aborted")return J;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new Ze(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,n){return new rn({...this._def,minSize:{value:e,message:W.toString(n)}})}max(e,n){return new rn({...this._def,maxSize:{value:e,message:W.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}rn.create=(t,e)=>new rn({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...K(e)});class Tr extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Tr.create=(t,e)=>new Tr({getter:t,typeName:Y.ZodLazy,...K(e)});class bs extends ee{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return P(n,{received:n.data,code:D.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}bs.create=(t,e)=>new bs({value:t,typeName:Y.ZodLiteral,...K(e)});function bi(t,e){return new Pt({values:t,typeName:Y.ZodEnum,...K(e)})}class Pt extends ee{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return P(n,{expected:ne.joinValues(s),received:n.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return P(n,{received:n.data,code:D.invalid_enum_value,options:s}),J}return Fe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Pt.create(e,{...this._def,...n})}exclude(e,n=this._def){return Pt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}Pt.create=bi;class Sr extends ee{_parse(e){const n=ne.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==V.string&&s.parsedType!==V.number){const r=ne.objectValues(n);return P(s,{expected:ne.joinValues(r),received:s.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=ne.objectValues(n);return P(s,{received:s.data,code:D.invalid_enum_value,options:r}),J}return Fe(e.data)}get enum(){return this._def.values}}Sr.create=(t,e)=>new Sr({values:t,typeName:Y.ZodNativeEnum,...K(e)});class $n extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==V.promise&&n.common.async===!1)return P(n,{code:D.invalid_type,expected:V.promise,received:n.parsedType}),J;const s=n.parsedType===V.promise?n.data:Promise.resolve(n.data);return Fe(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}$n.create=(t,e)=>new $n({type:t,typeName:Y.ZodPromise,...K(e)});class Lt 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:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{P(s,o),o.fatal?n.abort():n.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(n.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"||n.value==="dirty"?Yt(l.value):l});{if(n.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"||n.value==="dirty"?Yt(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"&&n.dirty(),o(a.value),{status:n.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"&&n.dirty(),o(a.value).then(()=>({status:n.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(!$t(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:n.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>$t(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:n.value,value:a})):J);ne.assertNever(r)}}Lt.create=(t,e,n)=>new Lt({schema:t,typeName:Y.ZodEffects,effect:e,...K(n)});Lt.createWithPreprocess=(t,e,n)=>new Lt({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...K(n)});class ot extends ee{_parse(e){return this._getType(e)===V.undefined?Fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ot.create=(t,e)=>new ot({innerType:t,typeName:Y.ZodOptional,...K(e)});class Vt extends ee{_parse(e){return this._getType(e)===V.null?Fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Vt.create=(t,e)=>new Vt({innerType:t,typeName:Y.ZodNullable,...K(e)});class Ts extends ee{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===V.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ts.create=(t,e)=>new Ts({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});class Ss extends ee{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Nn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Xe(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Xe(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ss.create=(t,e)=>new Ss({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...K(e)});class Rr extends ee{_parse(e){if(this._getType(e)!==V.nan){const s=this._getOrReturnCtx(e);return P(s,{code:D.invalid_type,expected:V.nan,received:s.parsedType}),J}return{status:"valid",value:e.data}}}Rr.create=t=>new Rr({typeName:Y.ZodNaN,...K(t)});class La extends ee{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class zs extends ee{_parse(e){const{status:n,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"?(n.dirty(),Yt(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"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new zs({in:e,out:n,typeName:Y.ZodPipeline})}}class Rs extends ee{_parse(e){const n=this._def.innerType._parse(e),s=r=>($t(r)&&(r.value=Object.freeze(r.value)),r);return Nn(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}Rs.create=(t,e)=>new Rs({innerType:t,typeName:Y.ZodReadonly,...K(e)});var Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(Y={}));const Se=Ke.create,yt=Mt.create,tn=Es.create,rs=vs.create,pe=Os.create;ct.create;const bt=We.create,je=de.create,ke=An.create;Cn.create;Et.create;const ln=Fn.create,be=bs.create,Mn=Pt.create;$n.create;ot.create;Vt.create;const vn=()=>pe().refine(t=>t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),Ir=()=>pe().refine(t=>t&&(t._methodName==="serverTimestamp"||t.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),Ti=(t,e,n)=>{const s={};if(t.includeFields){const i=e.collections[t.collection];if(!i)return ln(pe());t.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${t.collection}`);s[o]=Pn(i,a),kt(i,[a]).size===1&&(s[`${o}_Lowercase`]=Pn(i,a,!0))})}const r={Collection_Path:bt(Se()),...s};return n&&(r.id=Se().length(20)),je(r)},Va=(t,e)=>{let n=ln(Ti(t,e));return t.required||(n=n.optional()),n},Ua=t=>{let e=bt(ke([Se().length(20),Se().length(28)]));return["OneToOne","OneToMany"].includes(t.type)?e=e.max(1):(t.min&&(e=e.min(t.min)),t.max&&(e=e.max(t.max)),t.length&&(e=e.length(t.length))),t.required?e=e.nonempty():e=e.optional(),e},Pn=(t,e,n)=>{const{softDelete:s}=t,r=s?.timestampField;let i;switch(e.type){case"String":if(i=Se(),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))),n&&(i=i.toLowerCase()),e.values)if(n){const o=e.values.map(a=>a.toLowerCase());i=Mn(o)}else i=Mn(e.values);break;case"Boolean":i=tn();break;case"Number":e.autoIncrement?i=ke([be("Pending"),yt().int()]):(i=yt(),e.min&&(i=i.min(e.min)),e.max&&(i=i.max(e.max)),e.decimal?i=i.refine(o=>e.decimal?(o.toString().split(".")[1]?.length||0)<=e.decimal:!1,{message:`Value must have ${e.decimal} or fewer decimal places`}):i=i.int(),e.values&&(i=i.refine(o=>e.values?.includes(o),{message:"Value is not an allowed value"})));break;case"Timestamp":e.name===r?i=pe().refine(o=>o&&(o._methodName==="serverTimestamp"||o.constructor.name==="ServerTimestampTransform"||o.seconds!==void 0&&o.nanoseconds!==void 0||o._seconds!==void 0&&o._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}):(i=vn(),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=bt(pe()),e.length&&(i=i.length(e.length)),e.minlength?i=i.min(e.minlength):e.required&&(i=i.nonempty()),e.maxlength&&(i=i.max(e.maxlength)),e.values&&(i=i.refine(o=>{let a=!0;return o.forEach(l=>{e.values&&!e.values.includes(l)&&(a=!1)}),a},{message:"Value is not an allowed value"}));break;case"Map":i=ln(pe()),e.required&&(i=i.refine(o=>o&&typeof o=="object"&&Object.keys(o).length>0,{message:"Value must have at least one object property"}));break;case"Embedding":i=pe();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},Si=(t,e,n)=>{const s={Collection_Path:bt(Se()),Last_Write_App:Se(),Last_Write_At:vn(),Last_Save_At:Ir(),Last_Write_By:ke([Se().length(28),be("System")]),Last_Write_Connection_Status:Mn(["Online","Offline"]),Last_Write_Version:yt().int(),id:Se().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:vn(),Created_By:ke([Se().length(28),be("System")])};t==="create"&&(s.Saved_At=Ir()),t==="update"&&(s.Saved_At=vn(),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=mt(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{X(l)?(s[l.name]=Va(l,n),s[`${l.name}_Array`]=Ua(l),i.includes(l.name)&&(s[`${l.name}_Single`]=Ti(l,n,!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]=Pn(e,l))}),kt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=Pn(e,l,!0))});const a=je(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class Tt extends Error{}class Wa extends Tt{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class ja extends Tt{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class za extends Tt{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Dt extends Tt{}class Ri extends Tt{constructor(e){super(`Invalid unit ${e}`)}}class ye extends Tt{}class tt extends Tt{constructor(){super("Zone is an abstract class")}}const $="numeric",Le="short",Ie="long",Ln={year:$,month:$,day:$},Ii={year:$,month:Le,day:$},Za={year:$,month:Le,day:$,weekday:Le},xi={year:$,month:Ie,day:$},Ni={year:$,month:Ie,day:$,weekday:Ie},Di={hour:$,minute:$},Ai={hour:$,minute:$,second:$},Ci={hour:$,minute:$,second:$,timeZoneName:Le},Fi={hour:$,minute:$,second:$,timeZoneName:Ie},$i={hour:$,minute:$,hourCycle:"h23"},Mi={hour:$,minute:$,second:$,hourCycle:"h23"},Pi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:Le},Li={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:Ie},Vi={year:$,month:$,day:$,hour:$,minute:$},Ui={year:$,month:$,day:$,hour:$,minute:$,second:$},Wi={year:$,month:Le,day:$,hour:$,minute:$},ji={year:$,month:Le,day:$,hour:$,minute:$,second:$},qa={year:$,month:Le,day:$,weekday:Le,hour:$,minute:$},zi={year:$,month:Ie,day:$,hour:$,minute:$,timeZoneName:Le},Zi={year:$,month:Ie,day:$,hour:$,minute:$,second:$,timeZoneName:Le},qi={year:$,month:Ie,day:$,weekday:Ie,hour:$,minute:$,timeZoneName:Ie},Bi={year:$,month:Ie,day:$,weekday:Ie,hour:$,minute:$,second:$,timeZoneName:Ie};class cn{get type(){throw new tt}get name(){throw new tt}get ianaName(){return this.name}get isUniversal(){throw new tt}offsetName(e,n){throw new tt}formatOffset(e,n){throw new tt}offset(e){throw new tt}equals(e){throw new tt}get isValid(){throw new tt}}let is=null;class Hn extends cn{static get instance(){return is===null&&(is=new Hn),is}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return so(e,n,s)}formatOffset(e,n){return nn(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Is=new Map;function Ba(t){let e=Is.get(t);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Is.set(t,e)),e}const Ha={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Ga(t,e){const n=t.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,r,i,o,a,l,c,d]=s;return[o,r,i,a,l,c,d]}function Ya(t,e){const n=t.formatToParts(e),s=[];for(let r=0;r<n.length;r++){const{type:i,value:o}=n[r],a=Ha[i];i==="era"?s[a]=o:H(a)||(s[a]=parseInt(o,10))}return s}const os=new Map;class et extends cn{static create(e){let n=os.get(e);return n===void 0&&os.set(e,n=new et(e)),n}static resetCache(){os.clear(),Is.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=et.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return so(e,n,s,this.name)}formatOffset(e,n){return nn(this.offset(e),n)}offset(e){if(!this.valid)return NaN;const n=new Date(e);if(isNaN(n))return NaN;const s=Ba(this.name);let[r,i,o,a,l,c,d]=s.formatToParts?Ya(s,n):Ga(s,n);a==="BC"&&(r=-Math.abs(r)+1);const u=Yn({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:d,millisecond:0});let f=+n;const g=f%1e3;return f-=g>=0?g:1e3+g,(u-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let xr={};function Ja(t,e={}){const n=JSON.stringify([t,e]);let s=xr[n];return s||(s=new Intl.ListFormat(t,e),xr[n]=s),s}const xs=new Map;function Ns(t,e={}){const n=JSON.stringify([t,e]);let s=xs.get(n);return s===void 0&&(s=new Intl.DateTimeFormat(t,e),xs.set(n,s)),s}const Ds=new Map;function Qa(t,e={}){const n=JSON.stringify([t,e]);let s=Ds.get(n);return s===void 0&&(s=new Intl.NumberFormat(t,e),Ds.set(n,s)),s}const As=new Map;function Ka(t,e={}){const{base:n,...s}=e,r=JSON.stringify([t,s]);let i=As.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(t,e),As.set(r,i)),i}let Jt=null;function Xa(){return Jt||(Jt=new Intl.DateTimeFormat().resolvedOptions().locale,Jt)}const Cs=new Map;function Hi(t){let e=Cs.get(t);return e===void 0&&(e=new Intl.DateTimeFormat(t).resolvedOptions(),Cs.set(t,e)),e}const Fs=new Map;function el(t){let e=Fs.get(t);if(!e){const n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,"minimalDays"in e||(e={...Gi,...e}),Fs.set(t,e)}return e}function tl(t){const e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));const n=t.indexOf("-u-");if(n===-1)return[t];{let s,r;try{s=Ns(t).resolvedOptions(),r=t}catch{const l=t.substring(0,n);s=Ns(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function nl(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function sl(t){const e=[];for(let n=1;n<=12;n++){const s=L.utc(2009,n,1);e.push(t(s))}return e}function rl(t){const e=[];for(let n=1;n<=7;n++){const s=L.utc(2016,11,13+n);e.push(t(s))}return e}function pn(t,e,n,s){const r=t.listingMode();return r==="error"?null:r==="en"?n(e):s(e)}function il(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||Hi(t.locale).numberingSystem==="latn"}class ol{constructor(e,n,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!n||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 n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):Gs(e,3);return fe(n,this.padTo)}}}class al{constructor(e,n,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&&et.create(a).valid?(r=a,this.dt=e):(r="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,r=e.zone.name):(r="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const i={...this.opts};i.timeZone=i.timeZone||r,this.dtf=Ns(n,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(n=>{if(n.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:s}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class ll{constructor(e,n,s){this.opts={style:"long",...s},!n&&to()&&(this.rtf=Ka(e,s))}format(e,n){return this.rtf?this.rtf.format(e,n):Nl(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}const Gi={firstDay:1,minimalDays:4,weekend:[6,7]};class re{static fromOpts(e){return re.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,s,r,i=!1){const o=e||ue.defaultLocale,a=o||(i?"en-US":Xa()),l=n||ue.defaultNumberingSystem,c=s||ue.defaultOutputCalendar,d=Ms(r)||ue.defaultWeekSettings;return new re(a,l,c,d,o)}static resetCache(){Jt=null,xs.clear(),Ds.clear(),As.clear(),Cs.clear(),Fs.clear()}static fromObject({locale:e,numberingSystem:n,outputCalendar:s,weekSettings:r}={}){return re.create(e,n,s,r)}constructor(e,n,s,r,i){const[o,a,l]=tl(e);this.locale=o,this.numberingSystem=n||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=nl(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=il(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:re.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,Ms(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,n=!1){return pn(this,e,oo,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");n&=!s;const r=n?{month:e,day:"numeric"}:{month:e},i=n?"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]=sl(o)}return this.monthsCache[i][e]})}weekdays(e,n=!1){return pn(this,e,co,()=>{const s=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=n?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=rl(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return pn(this,void 0,()=>uo,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[L.utc(2016,11,13,9),L.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return pn(this,e,fo,()=>{const n={era:e};return this.eraCache[e]||(this.eraCache[e]=[L.utc(-40,1,1),L.utc(2017,1,1)].map(s=>this.extract(s,n,"era"))),this.eraCache[e]})}extract(e,n,s){const r=this.dtFormatter(e,n),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new ol(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new al(e,this.intl,n)}relFormatter(e={}){return new ll(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Ja(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||Hi(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:no()?el(this.locale):Gi}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 as=null;class _e extends cn{static get utcInstance(){return as===null&&(as=new _e(0)),as}static instance(e){return e===0?_e.utcInstance:new _e(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new _e(Jn(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${nn(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${nn(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return nn(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class cl extends cn{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 rt(t,e){if(H(t)||t===null)return e;if(t instanceof cn)return t;if(pl(t)){const n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?Hn.instance:n==="utc"||n==="gmt"?_e.utcInstance:_e.parseSpecifier(n)||et.create(t)}else return at(t)?_e.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new cl(t)}const Zs={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Nr={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]},ul=Zs.hanidec.replace(/[\[|\]]/g,"").split("");function dl(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);if(t[n].search(Zs.hanidec)!==-1)e+=ul.indexOf(t[n]);else for(const r in Nr){const[i,o]=Nr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const $s=new Map;function fl(){$s.clear()}function $e({numberingSystem:t},e=""){const n=t||"latn";let s=$s.get(n);s===void 0&&(s=new Map,$s.set(n,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${Zs[n]}${e}`),s.set(e,r)),r}let Dr=()=>Date.now(),Ar="system",Cr=null,Fr=null,$r=null,Mr=60,Pr,Lr=null;class ue{static get now(){return Dr}static set now(e){Dr=e}static set defaultZone(e){Ar=e}static get defaultZone(){return rt(Ar,Hn.instance)}static get defaultLocale(){return Cr}static set defaultLocale(e){Cr=e}static get defaultNumberingSystem(){return Fr}static set defaultNumberingSystem(e){Fr=e}static get defaultOutputCalendar(){return $r}static set defaultOutputCalendar(e){$r=e}static get defaultWeekSettings(){return Lr}static set defaultWeekSettings(e){Lr=Ms(e)}static get twoDigitCutoffYear(){return Mr}static set twoDigitCutoffYear(e){Mr=e%100}static get throwOnInvalid(){return Pr}static set throwOnInvalid(e){Pr=e}static resetCaches(){re.resetCache(),et.resetCache(),L.resetCache(),fl()}}class Pe{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Yi=[0,31,59,90,120,151,181,212,243,273,304,334],Ji=[0,31,60,91,121,152,182,213,244,274,305,335];function De(t,e){return new Pe("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function qs(t,e,n){const s=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function Qi(t,e,n){return n+(un(t)?Ji:Yi)[e-1]}function Ki(t,e){const n=un(t)?Ji:Yi,s=n.findIndex(i=>i<e),r=e-n[s];return{month:s+1,day:r}}function Bs(t,e){return(t-e+7)%7+1}function Vn(t,e=4,n=1){const{year:s,month:r,day:i}=t,o=Qi(s,r,i),a=Bs(qs(s,r,i),n);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=on(c,e,n)):l>on(s,e,n)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...Qn(t)}}function Vr(t,e=4,n=1){const{weekYear:s,weekNumber:r,weekday:i}=t,o=Bs(qs(s,1,e),n),a=Ct(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=Ct(c)):l>a?(c=s+1,l-=Ct(s)):c=s;const{month:d,day:m}=Ki(c,l);return{year:c,month:d,day:m,...Qn(t)}}function ls(t){const{year:e,month:n,day:s}=t,r=Qi(e,n,s);return{year:e,ordinal:r,...Qn(t)}}function Ur(t){const{year:e,ordinal:n}=t,{month:s,day:r}=Ki(e,n);return{year:e,month:s,day:r,...Qn(t)}}function Wr(t,e){if(!H(t.localWeekday)||!H(t.localWeekNumber)||!H(t.localWeekYear)){if(!H(t.weekday)||!H(t.weekNumber)||!H(t.weekYear))throw new Dt("Cannot mix locale-based week fields with ISO-based week fields");return H(t.localWeekday)||(t.weekday=t.localWeekday),H(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),H(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function hl(t,e=4,n=1){const s=Gn(t.weekYear),r=Ae(t.weekNumber,1,on(t.weekYear,e,n)),i=Ae(t.weekday,1,7);return s?r?i?!1:De("weekday",t.weekday):De("week",t.weekNumber):De("weekYear",t.weekYear)}function ml(t){const e=Gn(t.year),n=Ae(t.ordinal,1,Ct(t.year));return e?n?!1:De("ordinal",t.ordinal):De("year",t.year)}function Xi(t){const e=Gn(t.year),n=Ae(t.month,1,12),s=Ae(t.day,1,Un(t.year,t.month));return e?n?s?!1:De("day",t.day):De("month",t.month):De("year",t.year)}function eo(t){const{hour:e,minute:n,second:s,millisecond:r}=t,i=Ae(e,0,23)||e===24&&n===0&&s===0&&r===0,o=Ae(n,0,59),a=Ae(s,0,59),l=Ae(r,0,999);return i?o?a?l?!1:De("millisecond",r):De("second",s):De("minute",n):De("hour",e)}function H(t){return typeof t>"u"}function at(t){return typeof t=="number"}function Gn(t){return typeof t=="number"&&t%1===0}function pl(t){return typeof t=="string"}function yl(t){return Object.prototype.toString.call(t)==="[object Date]"}function to(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function no(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function gl(t){return Array.isArray(t)?t:[t]}function jr(t,e,n){if(t.length!==0)return t.reduce((s,r)=>{const i=[e(r),r];return s&&n(s[0],i[0])===s[0]?s:i},null)[1]}function wl(t,e){return e.reduce((n,s)=>(n[s]=t[s],n),{})}function Ut(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ms(t){if(t==null)return null;if(typeof t!="object")throw new ye("Week settings must be an object");if(!Ae(t.firstDay,1,7)||!Ae(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Ae(e,1,7)))throw new ye("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Ae(t,e,n){return Gn(t)&&t>=e&&t<=n}function _l(t,e){return t-e*Math.floor(t/e)}function fe(t,e=2){const n=t<0;let s;return n?s="-"+(""+-t).padStart(e,"0"):s=(""+t).padStart(e,"0"),s}function st(t){if(!(H(t)||t===null||t===""))return parseInt(t,10)}function ft(t){if(!(H(t)||t===null||t===""))return parseFloat(t)}function Hs(t){if(!(H(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function Gs(t,e,n="round"){const s=10**e;switch(n){case"expand":return t>0?Math.ceil(t*s)/s:Math.floor(t*s)/s;case"trunc":return Math.trunc(t*s)/s;case"round":return Math.round(t*s)/s;case"floor":return Math.floor(t*s)/s;case"ceil":return Math.ceil(t*s)/s;default:throw new RangeError(`Value rounding ${n} is out of range`)}}function un(t){return t%4===0&&(t%100!==0||t%400===0)}function Ct(t){return un(t)?366:365}function Un(t,e){const n=_l(e-1,12)+1,s=t+(e-n)/12;return n===2?un(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function Yn(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function zr(t,e,n){return-Bs(qs(t,1,e),n)+e-1}function on(t,e=4,n=1){const s=zr(t,e,n),r=zr(t+1,e,n);return(Ct(t)-s+r)/7}function Ps(t){return t>99?t:t>ue.twoDigitCutoffYear?1900+t:2e3+t}function so(t,e,n,s=null){const r=new Date(t),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(n,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function Jn(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const s=parseInt(e,10)||0,r=n<0||Object.is(n,-0)?-s:s;return n*60+r}function ro(t){const e=Number(t);if(typeof t=="boolean"||t===""||!Number.isFinite(e))throw new ye(`Invalid unit value ${t}`);return e}function Wn(t,e){const n={};for(const s in t)if(Ut(t,s)){const r=t[s];if(r==null)continue;n[e(s)]=ro(r)}return n}function nn(t,e){const n=Math.trunc(Math.abs(t/60)),s=Math.trunc(Math.abs(t%60)),r=t>=0?"+":"-";switch(e){case"short":return`${r}${fe(n,2)}:${fe(s,2)}`;case"narrow":return`${r}${n}${s>0?`:${s}`:""}`;case"techie":return`${r}${fe(n,2)}${fe(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Qn(t){return wl(t,["hour","minute","second","millisecond"])}const El=["January","February","March","April","May","June","July","August","September","October","November","December"],io=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],vl=["J","F","M","A","M","J","J","A","S","O","N","D"];function oo(t){switch(t){case"narrow":return[...vl];case"short":return[...io];case"long":return[...El];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 ao=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],lo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Ol=["M","T","W","T","F","S","S"];function co(t){switch(t){case"narrow":return[...Ol];case"short":return[...lo];case"long":return[...ao];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const uo=["AM","PM"],kl=["Before Christ","Anno Domini"],bl=["BC","AD"],Tl=["B","A"];function fo(t){switch(t){case"narrow":return[...Tl];case"short":return[...bl];case"long":return[...kl];default:return null}}function Sl(t){return uo[t.hour<12?0:1]}function Rl(t,e){return co(e)[t.weekday-1]}function Il(t,e){return oo(e)[t.month-1]}function xl(t,e){return fo(e)[t.year<0?0:1]}function Nl(t,e,n="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(t)===-1;if(n==="auto"&&i){const m=t==="days";switch(e){case 1:return m?"tomorrow":`next ${r[t][0]}`;case-1:return m?"yesterday":`last ${r[t][0]}`;case 0:return m?"today":`this ${r[t][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[t],d=s?l?c[1]:c[2]||c[1]:l?r[t][0]:t;return o?`${a} ${d} ago`:`in ${a} ${d}`}function Zr(t,e){let n="";for(const s of t)s.literal?n+=s.val:n+=e(s.val);return n}const Dl={D:Ln,DD:Ii,DDD:xi,DDDD:Ni,t:Di,tt:Ai,ttt:Ci,tttt:Fi,T:$i,TT:Mi,TTT:Pi,TTTT:Li,f:Vi,ff:Wi,fff:zi,ffff:qi,F:Ui,FF:ji,FFF:Zi,FFFF:Bi};class ge{static create(e,n={}){return new ge(e,n)}static parseFormat(e){let n=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}),n=null,s="",r=!r):r||a===n?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,n=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return Dl[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0,s=void 0){if(this.opts.forceSimple)return fe(e,n);const r={...this.opts};return n>0&&(r.padTo=n),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(f,g)=>this.loc.extract(e,f,g),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>s?Sl(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,g)=>s?Il(e,f):i(g?{month:f}:{month:f,day:"numeric"},"month"),c=(f,g)=>s?Rl(e,f):i(g?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),d=f=>{const g=ge.macroTokenToFormatOpts(f);return g?this.formatWithSystemDefault(e,g):f},m=f=>s?xl(e,f):i({era:f},"era"),u=f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return r?i({day:"numeric"},"day"):this.num(e.day);case"dd":return r?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return r?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return r?i({month:"numeric"},"month"):this.num(e.month);case"MM":return r?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return r?i({year:"numeric"},"year"):this.num(e.year);case"yy":return r?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return m("short");case"GG":return m("long");case"GGGGG":return m("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return d(f)}};return Zr(ge.parseFormat(n),u)}formatDurationFromString(e,n){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(d,m)=>u=>{const f=r(u);if(f){const g=m.isNegativeDuration&&f!==m.largestUnit?s:1;let v;return this.opts.signMode==="negativeLargestOnly"&&f!==m.largestUnit?v="never":this.opts.signMode==="all"?v="always":v="auto",this.num(d.get(f)*g,u.length,v)}else return u},o=ge.parseFormat(n),a=o.reduce((d,{literal:m,val:u})=>m?d:d.concat(u),[]),l=e.shiftTo(...a.map(r).filter(d=>d)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Zr(o,i(l,c))}}const ho=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Wt(...t){const e=t.reduce((n,s)=>n+s.source,"");return RegExp(`^${e}$`)}function jt(...t){return e=>t.reduce(([n,s,r],i)=>{const[o,a,l]=i(e,r);return[{...n,...o},a||s,l]},[{},null,1]).slice(0,2)}function zt(t,...e){if(t==null)return[null,null];for(const[n,s]of e){const r=n.exec(t);if(r)return s(r)}return[null,null]}function mo(...t){return(e,n)=>{const s={};let r;for(r=0;r<t.length;r++)s[t[r]]=st(e[n+r]);return[s,null,n+r]}}const po=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Al=`(?:${po.source}?(?:\\[(${ho.source})\\])?)?`,Ys=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,yo=RegExp(`${Ys.source}${Al}`),Js=RegExp(`(?:[Tt]${yo.source})?`),Cl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Fl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,$l=/(\d{4})-?(\d{3})/,Ml=mo("weekYear","weekNumber","weekDay"),Pl=mo("year","ordinal"),Ll=/(\d{4})-(\d\d)-(\d\d)/,go=RegExp(`${Ys.source} ?(?:${po.source}|(${ho.source}))?`),Vl=RegExp(`(?: ${go.source})?`);function Ft(t,e,n){const s=t[e];return H(s)?n:st(s)}function Ul(t,e){return[{year:Ft(t,e),month:Ft(t,e+1,1),day:Ft(t,e+2,1)},null,e+3]}function Zt(t,e){return[{hours:Ft(t,e,0),minutes:Ft(t,e+1,0),seconds:Ft(t,e+2,0),milliseconds:Hs(t[e+3])},null,e+4]}function dn(t,e){const n=!t[e]&&!t[e+1],s=Jn(t[e+1],t[e+2]),r=n?null:_e.instance(s);return[{},r,e+3]}function fn(t,e){const n=t[e]?et.create(t[e]):null;return[{},n,e+1]}const Wl=RegExp(`^T?${Ys.source}$`),jl=/^-?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 zl(t){const[e,n,s,r,i,o,a,l,c]=t,d=e[0]==="-",m=l&&l[0]==="-",u=(f,g=!1)=>f!==void 0&&(g||f&&d)?-f:f;return[{years:u(ft(n)),months:u(ft(s)),weeks:u(ft(r)),days:u(ft(i)),hours:u(ft(o)),minutes:u(ft(a)),seconds:u(ft(l),l==="-0"),milliseconds:u(Hs(c),m)}]}const Zl={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Qs(t,e,n,s,r,i,o){const a={year:e.length===2?Ps(st(e)):st(e),month:io.indexOf(n)+1,day:st(s),hour:st(r),minute:st(i)};return o&&(a.second=st(o)),t&&(a.weekday=t.length>3?ao.indexOf(t)+1:lo.indexOf(t)+1),a}const ql=/^(?:(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 Bl(t){const[,e,n,s,r,i,o,a,l,c,d,m]=t,u=Qs(e,r,s,n,i,o,a);let f;return l?f=Zl[l]:c?f=0:f=Jn(d,m),[u,new _e(f)]}function Hl(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Gl=/^(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$/,Yl=/^(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$/,Jl=/^(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 qr(t){const[,e,n,s,r,i,o,a]=t;return[Qs(e,r,s,n,i,o,a),_e.utcInstance]}function Ql(t){const[,e,n,s,r,i,o,a]=t;return[Qs(e,a,n,s,r,i,o),_e.utcInstance]}const Kl=Wt(Cl,Js),Xl=Wt(Fl,Js),ec=Wt($l,Js),tc=Wt(yo),wo=jt(Ul,Zt,dn,fn),nc=jt(Ml,Zt,dn,fn),sc=jt(Pl,Zt,dn,fn),rc=jt(Zt,dn,fn);function ic(t){return zt(t,[Kl,wo],[Xl,nc],[ec,sc],[tc,rc])}function oc(t){return zt(Hl(t),[ql,Bl])}function ac(t){return zt(t,[Gl,qr],[Yl,qr],[Jl,Ql])}function lc(t){return zt(t,[jl,zl])}const cc=jt(Zt);function uc(t){return zt(t,[Wl,cc])}const dc=Wt(Ll,Vl),fc=Wt(go),hc=jt(Zt,dn,fn);function mc(t){return zt(t,[dc,wo],[fc,hc])}const Br="Invalid Duration",_o={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}},pc={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},..._o},Ne=146097/400,Rt=146097/4800,yc={years:{quarters:4,months:12,weeks:Ne/7,days:Ne,hours:Ne*24,minutes:Ne*24*60,seconds:Ne*24*60*60,milliseconds:Ne*24*60*60*1e3},quarters:{months:3,weeks:Ne/28,days:Ne/4,hours:Ne*24/4,minutes:Ne*24*60/4,seconds:Ne*24*60*60/4,milliseconds:Ne*24*60*60*1e3/4},months:{weeks:Rt/7,days:Rt,hours:Rt*24,minutes:Rt*24*60,seconds:Rt*24*60*60,milliseconds:Rt*24*60*60*1e3},..._o},gt=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],gc=gt.slice(0).reverse();function Je(t,e,n=!1){const s={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new te(s)}function Eo(t,e){let n=e.milliseconds??0;for(const s of gc.slice(1))e[s]&&(n+=e[s]*t[s].milliseconds);return n}function Hr(t,e){const n=Eo(t,e)<0?-1:1;gt.reduceRight((s,r)=>{if(H(e[r]))return s;if(s){const i=e[s]*n,o=t[r][s],a=Math.floor(i/o);e[r]+=a*n,e[s]-=a*o*n}return r},null),gt.reduce((s,r)=>{if(H(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*t[s][r]}return r},null)}function Gr(t){const e={};for(const[n,s]of Object.entries(t))s!==0&&(e[n]=s);return e}class te{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;let s=n?yc:pc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||re.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,n){return te.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new ye(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new te({values:Wn(e,te.normalizeUnit),loc:re.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(at(e))return te.fromMillis(e);if(te.isDuration(e))return e;if(typeof e=="object")return te.fromObject(e);throw new ye(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[s]=lc(e);return s?te.fromObject(s,n):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[s]=uc(e);return s?te.fromObject(s,n):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new ye("need to specify a reason the Duration is invalid");const s=e instanceof Pe?e:new Pe(e,n);if(ue.throwOnInvalid)throw new za(s);return new te({invalid:s})}static normalizeUnit(e){const n={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(!n)throw new Ri(e);return n}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,n={}){const s={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?ge.create(this.loc,s).formatDurationFromString(this,e):Br}toHuman(e={}){if(!this.isValid)return Br;const n=e.showZeros!==!1,s=gt.map(r=>{const i=this.values[r];return H(i)||i===0&&!n?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+=Gs(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},L.fromMillis(n,{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?Eo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const n=te.fromDurationLike(e),s={};for(const r of gt)(Ut(n.values,r)||Ut(this.values,r))&&(s[r]=n.get(r)+this.get(r));return Je(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const n=te.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const s of Object.keys(this.values))n[s]=ro(e(this.values[s],s));return Je(this,{values:n},!0)}get(e){return this[te.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...Wn(e,te.normalizeUnit)};return Je(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:r,conversionAccuracy:s};return Je(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return Hr(this.matrix,e),Je(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=Gr(this.normalize().shiftToAll().toObject());return Je(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>te.normalizeUnit(o));const n={},s={},r=this.toObject();let i;for(const o of gt)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;at(r[o])&&(a+=r[o]);const l=Math.trunc(a);n[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else at(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(n[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return Hr(this.matrix,n),Je(this,{values:n},!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 n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return Je(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=Gr(this.values);return Je(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 n(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of gt)if(!n(this.values[s],e.values[s]))return!1;return!0}}const It="Invalid Interval";function wc(t,e){return!t||!t.isValid?ce.invalid("missing or invalid start"):!e||!e.isValid?ce.invalid("missing or invalid end"):e<t?ce.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}class ce{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new ye("need to specify a reason the Interval is invalid");const s=e instanceof Pe?e:new Pe(e,n);if(ue.throwOnInvalid)throw new ja(s);return new ce({invalid:s})}static fromDateTimes(e,n){const s=Ht(e),r=Ht(n),i=wc(s,r);return i??new ce({start:s,end:r})}static after(e,n){const s=te.fromDurationLike(n),r=Ht(e);return ce.fromDateTimes(r,r.plus(s))}static before(e,n){const s=te.fromDurationLike(n),r=Ht(e);return ce.fromDateTimes(r.minus(s),r)}static fromISO(e,n){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=L.fromISO(s,n),o=i.isValid}catch{o=!1}let a,l;try{a=L.fromISO(r,n),l=a.isValid}catch{l=!1}if(o&&l)return ce.fromDateTimes(i,a);if(o){const c=te.fromISO(r,n);if(c.isValid)return ce.after(i,c)}else if(l){const c=te.fromISO(s,n);if(c.isValid)return ce.before(a,c)}}return ce.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",n){if(!this.isValid)return NaN;const s=this.start.startOf(e,n);let r;return n?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,n),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:n}={}){return this.isValid?ce.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(Ht).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=n[i]||this.e,a=+o>+this.e?this.e:o;s.push(ce.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const n=te.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(n.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(ce.fromDateTimes(s,i)),s=i,r+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const n=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return n>=s?null:ce.fromDateTimes(n,s)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return ce.fromDateTimes(n,s)}static merge(e){const[n,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&&n.push(s),n}static xor(e){let n=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?n=l.time:(n&&+n!=+l.time&&r.push(ce.fromDateTimes(n,l.time)),n=null);return ce.merge(r)}difference(...e){return ce.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:It}[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=Ln,n={}){return this.isValid?ge.create(this.s.loc.clone(n),e).formatInterval(this):It}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:It}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:It}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:It}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:It}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):te.invalid(this.invalidReason)}mapEndpoints(e){return ce.fromDateTimes(e(this.s),e(this.e))}}class yn{static hasDST(e=ue.defaultZone){const n=L.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return et.isValidZone(e)}static normalizeZone(e){return rt(e,ue.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||re.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||re.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||re.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||re.create(n,s,i)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||re.create(n,s,i)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||re.create(n,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||re.create(n,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return re.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return re.create(n,null,"gregory").eras(e)}static features(){return{relative:to(),localeWeek:no()}}}function Yr(t,e){const n=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=n(e)-n(t);return Math.floor(te.fromMillis(s).as("days"))}function _c(t,e,n){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const d=Yr(l,c);return(d-d%7)/7}],["days",Yr]],r={},i=t;let o,a;for(const[l,c]of s)n.indexOf(l)>=0&&(o=l,r[l]=c(t,e),a=i.plus(r),a>e?(r[l]--,t=i.plus(r),t>e&&(a=t,r[l]--,t=i.plus(r))):t=a);return[t,r,a,o]}function Ec(t,e,n,s){let[r,i,o,a]=_c(t,e,n);const l=e-r,c=n.filter(m=>["hours","minutes","seconds","milliseconds"].indexOf(m)>=0);c.length===0&&(o<e&&(o=r.plus({[a]:1})),o!==r&&(i[a]=(i[a]||0)+l/(o-r)));const d=te.fromObject(i,s);return c.length>0?te.fromMillis(l,s).shiftTo(...c).plus(d):d}const vc="missing Intl.DateTimeFormat.formatToParts support";function se(t,e=n=>n){return{regex:t,deser:([n])=>e(dl(n))}}const Oc=" ",vo=`[ ${Oc}]`,Oo=new RegExp(vo,"g");function kc(t){return t.replace(/\./g,"\\.?").replace(Oo,vo)}function Jr(t){return t.replace(/\./g,"").replace(Oo," ").toLowerCase()}function Me(t,e){return t===null?null:{regex:RegExp(t.map(kc).join("|")),deser:([n])=>t.findIndex(s=>Jr(n)===Jr(s))+e}}function Qr(t,e){return{regex:t,deser:([,n,s])=>Jn(n,s),groups:e}}function gn(t){return{regex:t,deser:([e])=>e}}function bc(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Tc(t,e){const n=$e(e),s=$e(e,"{2}"),r=$e(e,"{3}"),i=$e(e,"{4}"),o=$e(e,"{6}"),a=$e(e,"{1,2}"),l=$e(e,"{1,3}"),c=$e(e,"{1,6}"),d=$e(e,"{1,9}"),m=$e(e,"{2,4}"),u=$e(e,"{4,6}"),f=y=>({regex:RegExp(bc(y.val)),deser:([w])=>w,literal:!0}),v=(y=>{if(t.literal)return f(y);switch(y.val){case"G":return Me(e.eras("short"),0);case"GG":return Me(e.eras("long"),0);case"y":return se(c);case"yy":return se(m,Ps);case"yyyy":return se(i);case"yyyyy":return se(u);case"yyyyyy":return se(o);case"M":return se(a);case"MM":return se(s);case"MMM":return Me(e.months("short",!0),1);case"MMMM":return Me(e.months("long",!0),1);case"L":return se(a);case"LL":return se(s);case"LLL":return Me(e.months("short",!1),1);case"LLLL":return Me(e.months("long",!1),1);case"d":return se(a);case"dd":return se(s);case"o":return se(l);case"ooo":return se(r);case"HH":return se(s);case"H":return se(a);case"hh":return se(s);case"h":return se(a);case"mm":return se(s);case"m":return se(a);case"q":return se(a);case"qq":return se(s);case"s":return se(a);case"ss":return se(s);case"S":return se(l);case"SSS":return se(r);case"u":return gn(d);case"uu":return gn(a);case"uuu":return se(n);case"a":return Me(e.meridiems(),0);case"kkkk":return se(i);case"kk":return se(m,Ps);case"W":return se(a);case"WW":return se(s);case"E":case"c":return se(n);case"EEE":return Me(e.weekdays("short",!1),1);case"EEEE":return Me(e.weekdays("long",!1),1);case"ccc":return Me(e.weekdays("short",!0),1);case"cccc":return Me(e.weekdays("long",!0),1);case"Z":case"ZZ":return Qr(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return Qr(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return gn(/[a-z_+-/]{1,256}?/i);case" ":return gn(/[^\S\n\r]/);default:return f(y)}})(t)||{invalidReason:vc};return v.token=t,v}const Sc={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 Rc(t,e,n){const{type:s,value:r}=t;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=n.hour12?"hour12":"hour24");let a=Sc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Ic(t){return[`^${t.map(n=>n.regex).reduce((n,s)=>`${n}(${s.source})`,"")}$`,t]}function xc(t,e,n){const s=t.match(e);if(s){const r={};let i=1;for(const o in n)if(Ut(n,o)){const a=n[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 Nc(t){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 n=null,s;return H(t.z)||(n=et.create(t.z)),H(t.Z)||(n||(n=new _e(t.Z)),s=t.Z),H(t.q)||(t.M=(t.q-1)*3+1),H(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),H(t.u)||(t.S=Hs(t.u)),[Object.keys(t).reduce((i,o)=>{const a=e(o);return a&&(i[a]=t[o]),i},{}),n,s]}let cs=null;function Dc(){return cs||(cs=L.fromMillis(1555555555555)),cs}function Ac(t,e){if(t.literal)return t;const n=ge.macroTokenToFormatOpts(t.val),s=So(n,e);return s==null||s.includes(void 0)?t:s}function ko(t,e){return Array.prototype.concat(...t.map(n=>Ac(n,e)))}class bo{constructor(e,n){if(this.locale=e,this.format=n,this.tokens=ko(ge.parseFormat(n),e),this.units=this.tokens.map(s=>Tc(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Ic(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[n,s]=xc(e,this.regex,this.handlers),[r,i,o]=s?Nc(s):[null,null,void 0];if(Ut(s,"a")&&Ut(s,"H"))throw new Dt("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:n,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 To(t,e,n){return new bo(t,n).explainFromTokens(e)}function Cc(t,e,n){const{result:s,zone:r,specificOffset:i,invalidReason:o}=To(t,e,n);return[s,r,i,o]}function So(t,e){if(!t)return null;const s=ge.create(e,t).dtFormatter(Dc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Rc(o,t,i))}const us="Invalid DateTime",Kr=864e13;function Qt(t){return new Pe("unsupported zone",`the zone "${t.name}" is not supported`)}function ds(t){return t.weekData===null&&(t.weekData=Vn(t.c)),t.weekData}function fs(t){return t.localWeekData===null&&(t.localWeekData=Vn(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function ht(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new L({...n,...e,old:n})}function Ro(t,e,n){let s=t-e*60*1e3;const r=n.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=n.offset(s);return r===i?[s,r]:[t-Math.min(r,i)*60*1e3,Math.max(r,i)]}function wn(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function On(t,e,n){return Ro(Yn(t),e,n)}function Xr(t,e){const n=t.o,s=t.c.year+Math.trunc(e.years),r=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...t.c,year:s,month:r,day:Math.min(t.c.day,Un(s,r))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},o=te.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=Yn(i);let[l,c]=Ro(a,n,t.zone);return o!==0&&(l+=o,c=t.zone.offset(l)),{ts:l,o:c}}function xt(t,e,n,s,r,i){const{setZone:o,zone:a}=n;if(t&&Object.keys(t).length!==0||e){const l=e||a,c=L.fromObject(t,{...n,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return L.invalid(new Pe("unparsable",`the input "${r}" can't be parsed as ${s}`))}function _n(t,e,n=!0){return t.isValid?ge.create(re.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function hs(t,e,n){const s=t.c.year>9999||t.c.year<0;let r="";if(s&&t.c.year>=0&&(r+="+"),r+=fe(t.c.year,s?6:4),n==="year")return r;if(e){if(r+="-",r+=fe(t.c.month),n==="month")return r;r+="-"}else if(r+=fe(t.c.month),n==="month")return r;return r+=fe(t.c.day),r}function ei(t,e,n,s,r,i,o){let a=!n||t.c.millisecond!==0||t.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=fe(t.c.hour),o==="hour")break;if(e){if(l+=":",l+=fe(t.c.minute),o==="minute")break;a&&(l+=":",l+=fe(t.c.second))}else{if(l+=fe(t.c.minute),o==="minute")break;a&&(l+=fe(t.c.second))}if(o==="second")break;a&&(!s||t.c.millisecond!==0)&&(l+=".",l+=fe(t.c.millisecond,3))}return r&&(t.isOffsetFixed&&t.offset===0&&!i?l+="Z":t.o<0?(l+="-",l+=fe(Math.trunc(-t.o/60)),l+=":",l+=fe(Math.trunc(-t.o%60))):(l+="+",l+=fe(Math.trunc(t.o/60)),l+=":",l+=fe(Math.trunc(t.o%60)))),i&&(l+="["+t.zone.ianaName+"]"),l}const Io={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Fc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},$c={ordinal:1,hour:0,minute:0,second:0,millisecond:0},kn=["year","month","day","hour","minute","second","millisecond"],Mc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Pc=["year","ordinal","hour","minute","second","millisecond"];function bn(t){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"}[t.toLowerCase()];if(!e)throw new Ri(t);return e}function ti(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return bn(t)}}function Lc(t){if(Kt===void 0&&(Kt=ue.now()),t.type!=="iana")return t.offset(Kt);const e=t.name;let n=Ls.get(e);return n===void 0&&(n=t.offset(Kt),Ls.set(e,n)),n}function ni(t,e){const n=rt(e.zone,ue.defaultZone);if(!n.isValid)return L.invalid(Qt(n));const s=re.fromObject(e);let r,i;if(H(t.year))r=ue.now();else{for(const l of kn)H(t[l])&&(t[l]=Io[l]);const o=Xi(t)||eo(t);if(o)return L.invalid(o);const a=Lc(n);[r,i]=On(t,a,n)}return new L({ts:r,zone:n,loc:s,o:i})}function si(t,e,n){const s=H(n.round)?!0:n.round,r=H(n.rounding)?"trunc":n.rounding,i=(a,l)=>(a=Gs(a,s||n.calendary?0:2,n.calendary?"round":r),e.loc.clone(n).relFormatter(n).format(a,l)),o=a=>n.calendary?e.hasSame(t,a)?0:e.startOf(a).diff(t.startOf(a),a).get(a):e.diff(t,a).get(a);if(n.unit)return i(o(n.unit),n.unit);for(const a of n.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(t>e?-0:0,n.units[n.units.length-1])}function ri(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}let Kt;const Ls=new Map;class L{constructor(e){const n=e.zone||ue.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Pe("invalid input"):null)||(n.isValid?null:Qt(n));this.ts=H(e.ts)?ue.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[r,i]=[e.old.c,e.old.o];else{const a=at(e.o)&&!e.old?e.o:n.offset(this.ts);r=wn(this.ts,a),s=Number.isNaN(r.year)?new Pe("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=n,this.loc=e.loc||re.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new L({})}static local(){const[e,n]=ri(arguments),[s,r,i,o,a,l,c]=n;return ni({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,n]=ri(arguments),[s,r,i,o,a,l,c]=n;return e.zone=_e.utcInstance,ni({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,n={}){const s=yl(e)?e.valueOf():NaN;if(Number.isNaN(s))return L.invalid("invalid input");const r=rt(n.zone,ue.defaultZone);return r.isValid?new L({ts:s,zone:r,loc:re.fromObject(n)}):L.invalid(Qt(r))}static fromMillis(e,n={}){if(at(e))return e<-Kr||e>Kr?L.invalid("Timestamp out of range"):new L({ts:e,zone:rt(n.zone,ue.defaultZone),loc:re.fromObject(n)});throw new ye(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(at(e))return new L({ts:e*1e3,zone:rt(n.zone,ue.defaultZone),loc:re.fromObject(n)});throw new ye("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const s=rt(n.zone,ue.defaultZone);if(!s.isValid)return L.invalid(Qt(s));const r=re.fromObject(n),i=Wn(e,ti),{minDaysInFirstWeek:o,startOfWeek:a}=Wr(i,r),l=ue.now(),c=H(n.specificOffset)?s.offset(l):n.specificOffset,d=!H(i.ordinal),m=!H(i.year),u=!H(i.month)||!H(i.day),f=m||u,g=i.weekYear||i.weekNumber;if((f||d)&&g)throw new Dt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new Dt("Can't mix ordinal dates with month/day");const v=g||i.weekday&&!f;let y,w,R=wn(l,c);v?(y=Mc,w=Fc,R=Vn(R,o,a)):d?(y=Pc,w=$c,R=ls(R)):(y=kn,w=Io);let O=!1;for(const p of y){const F=i[p];H(F)?O?i[p]=w[p]:i[p]=R[p]:O=!0}const I=v?hl(i,o,a):d?ml(i):Xi(i),E=I||eo(i);if(E)return L.invalid(E);const C=v?Vr(i,o,a):d?Ur(i):i,[_,Z]=On(C,c,s),k=new L({ts:_,zone:s,o:Z,loc:r});return i.weekday&&f&&e.weekday!==k.weekday?L.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${k.toISO()}`):k.isValid?k:L.invalid(k.invalid)}static fromISO(e,n={}){const[s,r]=ic(e);return xt(s,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[s,r]=oc(e);return xt(s,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[s,r]=ac(e);return xt(s,r,n,"HTTP",n)}static fromFormat(e,n,s={}){if(H(e)||H(n))throw new ye("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,d]=Cc(o,e,n);return d?L.invalid(d):xt(a,l,s,`format ${n}`,e,c)}static fromString(e,n,s={}){return L.fromFormat(e,n,s)}static fromSQL(e,n={}){const[s,r]=mc(e);return xt(s,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new ye("need to specify a reason the DateTime is invalid");const s=e instanceof Pe?e:new Pe(e,n);if(ue.throwOnInvalid)throw new Wa(s);return new L({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){const s=So(e,re.fromObject(n));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return ko(ge.parseFormat(e),re.fromObject(n)).map(r=>r.val).join("")}static resetCache(){Kt=void 0,Ls.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?ds(this).weekYear:NaN}get weekNumber(){return this.isValid?ds(this).weekNumber:NaN}get weekday(){return this.isValid?ds(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?fs(this).weekday:NaN}get localWeekNumber(){return this.isValid?fs(this).weekNumber:NaN}get localWeekYear(){return this.isValid?fs(this).weekYear:NaN}get ordinal(){return this.isValid?ls(this.c).ordinal:NaN}get monthShort(){return this.isValid?yn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?yn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?yn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?yn.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,n=6e4,s=Yn(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*n),a=this.zone.offset(s-i*n);if(o===a)return[this];const l=s-o*n,c=s-a*n,d=wn(l,o),m=wn(c,a);return d.hour===m.hour&&d.minute===m.minute&&d.second===m.second&&d.millisecond===m.millisecond?[ht(this,{ts:l}),ht(this,{ts:c})]:[this]}get isInLeapYear(){return un(this.year)}get daysInMonth(){return Un(this.year,this.month)}get daysInYear(){return this.isValid?Ct(this.year):NaN}get weeksInWeekYear(){return this.isValid?on(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?on(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:s,calendar:r}=ge.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:s,outputCalendar:r}}toUTC(e=0,n={}){return this.setZone(_e.instance(e),n)}toLocal(){return this.setZone(ue.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:s=!1}={}){if(e=rt(e,ue.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(n||s){const i=e.offset(this.ts),o=this.toObject();[r]=On(o,i,e)}return ht(this,{ts:r,zone:e})}else return L.invalid(Qt(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:s});return ht(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=Wn(e,ti),{minDaysInFirstWeek:s,startOfWeek:r}=Wr(n,this.loc),i=!H(n.weekYear)||!H(n.weekNumber)||!H(n.weekday),o=!H(n.ordinal),a=!H(n.year),l=!H(n.month)||!H(n.day),c=a||l,d=n.weekYear||n.weekNumber;if((c||o)&&d)throw new Dt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new Dt("Can't mix ordinal dates with month/day");let m;i?m=Vr({...Vn(this.c,s,r),...n},s,r):H(n.ordinal)?(m={...this.toObject(),...n},H(n.day)&&(m.day=Math.min(Un(m.year,m.month),m.day))):m=Ur({...ls(this.c),...n});const[u,f]=On(m,this.o,this.zone);return ht(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const n=te.fromDurationLike(e);return ht(this,Xr(this,n))}minus(e){if(!this.isValid)return this;const n=te.fromDurationLike(e).negate();return ht(this,Xr(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;const s={},r=te.normalizeUnit(e);switch(r){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(r==="weeks")if(n){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,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?ge.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):us}toLocaleString(e=Ln,n={}){return this.isValid?ge.create(this.loc.clone(n),e).formatDateTime(this):us}toLocaleParts(e={}){return this.isValid?ge.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=bn(o);const a=e==="extended";let l=hs(this,a,o);return kn.indexOf(o)>=3&&(l+="T"),l+=ei(this,a,n,s,r,i,o),l}toISODate({format:e="extended",precision:n="day"}={}){return this.isValid?hs(this,e==="extended",bn(n)):null}toISOWeekDate(){return _n(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=bn(a),(r&&kn.indexOf(a)>=3?"T":"")+ei(this,o==="extended",n,e,s,i,a)):null}toRFC2822(){return _n(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return _n(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?hs(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(n||e)&&(s&&(r+=" "),n?r+="z":e&&(r+="ZZ")),_n(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():us}[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 n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",s={}){if(!this.isValid||!e.isValid)return te.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=gl(n).map(te.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=Ec(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",n={}){return this.diff(L.now(),e,n)}until(e){return this.isValid?ce.fromDateTimes(this,e):this}hasSame(e,n,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n,s)<=r&&r<=i.endOf(n,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 n=e.base||L.fromObject({},{zone:this.zone}),s=e.padding?this<n?-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),si(n,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?si(e.base||L.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(L.isDateTime))throw new ye("min requires all arguments be DateTimes");return jr(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(L.isDateTime))throw new ye("max requires all arguments be DateTimes");return jr(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return To(o,e,n)}static fromStringExplain(e,n,s={}){return L.fromFormatExplain(e,n,s)}static buildFormatParser(e,n={}){const{locale:s=null,numberingSystem:r=null}=n,i=re.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new bo(i,e)}static fromFormatParser(e,n,s={}){if(H(e)||H(n))throw new ye("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(n.locale))throw new ye(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${n.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=n.explainFromTokens(e);return d?L.invalid(d):xt(a,l,s,`format ${n.format}`,e,c)}static get DATE_SHORT(){return Ln}static get DATE_MED(){return Ii}static get DATE_MED_WITH_WEEKDAY(){return Za}static get DATE_FULL(){return xi}static get DATE_HUGE(){return Ni}static get TIME_SIMPLE(){return Di}static get TIME_WITH_SECONDS(){return Ai}static get TIME_WITH_SHORT_OFFSET(){return Ci}static get TIME_WITH_LONG_OFFSET(){return Fi}static get TIME_24_SIMPLE(){return $i}static get TIME_24_WITH_SECONDS(){return Mi}static get TIME_24_WITH_SHORT_OFFSET(){return Pi}static get TIME_24_WITH_LONG_OFFSET(){return Li}static get DATETIME_SHORT(){return Vi}static get DATETIME_SHORT_WITH_SECONDS(){return Ui}static get DATETIME_MED(){return Wi}static get DATETIME_MED_WITH_SECONDS(){return ji}static get DATETIME_MED_WITH_WEEKDAY(){return qa}static get DATETIME_FULL(){return zi}static get DATETIME_FULL_WITH_SECONDS(){return Zi}static get DATETIME_HUGE(){return qi}static get DATETIME_HUGE_WITH_SECONDS(){return Bi}}function Ht(t){if(L.isDateTime(t))return t;if(t&&t.valueOf&&at(t.valueOf()))return L.fromJSDate(t);if(t&&typeof t=="object")return L.fromObject(t);throw new ye(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const Vc=(t,e)=>{const n={};if(t.includeFields){const s=e.collections[t.collection];if(!s)return ln(pe());t.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?n[r]=xo(i)?.nullable():n[r]=pe()})}return je({Collection_Path:bt(Se()),...n})},Uc=(t,e,n,s)=>{let r=je({}).catchall(Vc(t,e)),i;if(!s&&n){const o=Ce(t,n);i=Gt(o.admin?.skipFormRequiredValidation)}return(!t.required||i)&&(r=r.optional()),r},Wc=()=>pe().refine(t=>t===null||t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Must be a valid date"}),xo=(t,e,n)=>{let s;const r=`${Gt(t.description)}
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("lodash/isEqual.js"),ta=require("lodash/merge.js"),na=require("lodash/set.js"),ge=require("lodash/cloneDeep.js"),kt=require("firebase-admin/app"),oe=require("firebase-admin/firestore"),Ei=require("node:url"),sa=require("cross-spawn"),vi=require("firebase-admin/database"),St=require("firebase-admin/auth"),Xn=t=>!!t&&!Array.isArray(t),cn=(t,e)=>t.access?Xn(t.access)?!1:t.access.includes(e):!0,ra=(t,e)=>{if(Xn(t.access))return e.fieldAccessGroups?.[t.access.group]},wt=t=>{const e={};return Object.keys(t.fieldAccessGroups||{}).forEach(n=>{e[n]=[]}),t.fields.forEach(n=>{if(Xn(n.access)){const{group:s}=n.access;e[s]&&e[s].push(n)}}),e},es=(t,e,n,s)=>{if(!n)return!0;if(n.Role&&!t.applicableRoles.includes(n.Role))return!1;const r=n.collections?.[e],i=[];if(t.collectionAuth!==void 0&&i.push(!!r?.auth===t.collectionAuth),t.roles&&i.push(!!n.Role&&t.roles.includes(n.Role)),t.claims&&i.push(Object.entries(t.claims).every(([o,a])=>{let l=s?.[o];return l===void 0&&o==="role"&&(l=n.Role),Array.isArray(a)?a.some(c=>c===l):l===a})),t.restrictions){const{recordOwner:o,recordUser:a,recordProperty:l,restrictEntities:c}=t.restrictions;i.push((o===void 0||!!r?.recordOwner?.active===o)&&(a===void 0||!!r?.recordUser?.active===a)&&(l===void 0||!!r?.recordProperty?.active===l)&&(c===void 0||!!r?.restrictEntities===c))}return i.length===0?!1:t.match==="all"?i.every(Boolean):i.some(Boolean)},ia=(t,e,n,s)=>{const r=ra(t,e);return r?es(r,e.labels.collection,n,s):!1},ts=t=>!!t.auth,Ie=(t,e)=>{if(e?.operations)return e.operations.includes(t)},He=(t,e,n,s)=>e?e.Role?Xn(t.access)?!n||!s?!1:ia(t,n,e,s):t.access?.includes(e.Role):!1:!0,Oi=(t,e,n,s)=>t===!0?!1:Array.isArray(t)?t.includes(e.Role):typeof t=="object"&&t!==null?!n||!s?!1:es(t,n,e,s):!0,oa=(t,e,n,s)=>e?e.Role?Oi(t.restrictCreate,e,n,s):!1:!0,ki=(t,e,n,s)=>e?e.Role?Oi(t.restrictUpdate,e,n,s):!1:!0,Or=(t,e,n,s)=>{const{labels:r}=t;return n.collections&&Ie("Update",n.collections[r.collection])&&(!e.access||He(e,n,t,s))&&ki(e,n,r.collection,s)&&!(t.auth&&!n.collections?.[r.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},V=(t,e)=>t.filter(n=>n.name===e)[0],ee=t=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(t.type),bi=(t,e)=>{const n={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=t,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const d=a?.[n[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},Gs=(t,e)=>{const n=[],{labels:s,access:r}=t,{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)&&n.push(a)})}),n},Ti=(t,e,n)=>{const s=[],{access:r}=t,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.role===n.Role))return;const a=o.collectionField,l=V(t.fields,a);if(!ee(l))throw new Error("PERMISSION_DENIED");const c=n.collections?.[l.collection],h=e.collections[l.collection].access.entityRestrictions;if(!h)throw new Error("PERMISSION_DENIED");const u=h.restrictions?.find(f=>f.type===o.type&&f.roles.some(g=>g.role===n.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===n.Role&&(!h.assignable?.includes(n.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},Si=(t,e,n,s)=>{const r=Object.values(e.collections),{labels:i}=t,o=[];for(const a of r){const{fields:l}=a;for(const c of l)if(!(c.access&&!He(c,n,a,s))&&n.Role&&ee(c)&&c.collection===i.collection&&c.dependencyFields)for(const d of c.dependencyFields)!o.find(u=>u.field===d.field)&&d.roles.includes(n.Role)&&o.push(d)}return o},aa=(t,e,n,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const d=bi(e,r),h=Gs(e,r),u=Ti(e,n,r);d?.filter(v=>v.type==="Record_Owner").forEach(v=>{"operations"in v&&v.operations&&!v.operations.includes(t)||i.Created_By!==s&&(c=!1)}),d?.filter(v=>v.type==="Record_User").forEach(v=>{if("operations"in v&&v.operations&&!v.operations.includes(t))return;const N=V(a,v.collectionField);i[`${N.name}_Array`]?.includes(r.Doc_ID)||(c=!1)}),d?.filter(v=>v.type==="Record_Property").forEach(v=>{if("operations"in v&&v.operations&&!v.operations.includes(t))return;const N=V(a,v.propertyField),W=v.roles.find(O=>O.role===r.Role);N.type==="Array"?W.values?.some(O=>i[N.name].includes(O))||(c=!1):W.values?.includes(i[N.name])||(c=!1)});let f=!0,g=!1;h?.filter(v=>v.type==="Individual").forEach(()=>{g=!0,l?.individualEntities?.includes(i.id)||(f=!1)});let T=!0,m=!1;if(h?.filter(v=>v.type==="Parent").forEach(v=>{m=!0;const N=V(a,v.collectionField);l?.parentEntities?.some(W=>i[`${N.name}_Array`].includes(W))||(T=!1)}),h?.filter(v=>v.type==="Parent_Property").forEach(v=>{m=!0;const N=V(a,v.collectionField),W=V(a,v.propertyField);Object.entries(l?.parentPropertyEntities||{}).some(O=>{const[H,R]=O;return H===i[W.name]&&i[`${N.name}_Array`].some(p=>R.includes(p))})||(T=!1)}),g&&m){if(!(f||T)){c=!1;return}}else if(!f||!T){c=!1;return}let E=!0,w=!1;u?.filter(v=>v.parentFilter.type==="Individual").forEach(v=>{w=!0;const{parentFilter:N}=v,W=V(a,N.collectionField),O=r.collections?.[W.collection];if(!O){c=!1;return}O.individualEntities?.some(H=>i[`${W.name}_Array`].includes(H))||(E=!1)});let x=!0,k=!1;if(u?.filter(v=>v.parentFilter.type==="Parent").forEach(v=>{k=!0;const{parentFilter:N}=v,W=V(a,N.collectionField),O=V(a,N.parentCollectionField),H=r.collections?.[W.collection];if(!H){c=!1;return}H.parentEntities?.some(R=>i[`${O.name}_Array`].includes(R))||(x=!1)}),u?.filter(v=>v.parentFilter.type==="Parent_Property").forEach(v=>{k=!0;const{parentFilter:N}=v,W=V(a,N.collectionField),O=V(a,N.parentPropertyField),H=V(a,N.parentCollectionField),R=r.collections?.[W.collection];if(!R){c=!1;return}Object.entries(R.parentPropertyEntities||{}).some(p=>{const[C,I]=p;return C===i[O.name]&&i[`${H.name}_Array`].some(P=>I.includes(P))})||(x=!1)}),w&&k){if(!(E||x)){c=!1;return}}else if(!E||!x){c=!1;return}return c},ft=(t,e,n,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;Ie(t,a)||(l=!1);const d=Gs(e,r)?.filter(h=>h.type==="Individual").length>0;return t==="Create"&&d&&(l=!1),aa(t,e,n,s,r,i)||(l=!1),l},Ri=(t,e,n)=>{const{labels:s}=t,r=[];for(const i of Object.values(e.collections));return r},la=(t,e)=>{let n=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){n=!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(t.collections).includes(r)){s=`Collection ${r} not found in schema`,n=!1;return}const i=t.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,n=!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`,n=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,n=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,n=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,n=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),h=i.access.entityRestrictions?.restrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(u=>t.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,n=!1;return}if(d?.length||h?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const u=Object.keys(l);if(u.length!==1||u[0]!=="active"||typeof l.active!="boolean"){s=`Collection ${r} has invalid attribute restriction value`,n=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,n=!1;return}if(a==="Parent"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,n=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,n=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,n=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),n},ca=(t,e,n)=>{let s=!0,r="";Object.values(t.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(t.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:d,entityRestrictions:h}=a,u=c.assignable,f=e.collections?.[o.collection],g=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(n))?g.forEach(m=>{const E=m.charAt(0).toUpperCase()+m.slice(1);if(m!=="assignable"){const w=!!a.operations[m]?.includes(n),x=!!f?.operations.includes(E);if(!w&&x){r=`Collection ${o.collection} has excess ${m} operation for role ${n}`,s=!1;return}if(w&&!x){r=`Collection ${o.collection} has missing ${m} operation for role ${n}`,s=!1;return}}}):g.forEach(m=>{const E=m.charAt(0).toUpperCase()+m.slice(1);if(m!=="assignable"){const w=!!a.operations[m]?.includes(n),x=!!f?.operations.includes(E);if(!w&&x){r=`Collection ${o.collection} has excess ${m} operation for role ${n}`,s=!1;return}}}),!d&&!h||(d?.forEach(m=>{for(const E of m.roles)if(E.role===n&&!E.assignable){if(m.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${n}`,s=!1;return}if(m.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${n}`,s=!1;return}if(m.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${n}`,s=!1;return}}}),h?.assignable?.includes(n)))continue;let T=!1;if(h?.restrictions?.forEach(m=>{for(const E of m.roles)if(E.role===n){if(T=!0,m.type==="Individual"&&!e.collections?.[o.collection]?.individualEntities){r=`Collection ${o.collection} is missing individual entities`,s=!1;return}if(m.type==="Parent"){const w=V(l,m.collectionField);if(!ee(w)){s=!1;return}if(!e.collections?.[o.collection]?.parentEntities){r=`Collection ${o.collection} is missing parent entities`,s=!1;return}}if(m.type==="Parent_Property"){const w=V(l,m.collectionField);if(!ee(w)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[w.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),T&&!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},ua=(t,e,n,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:d}=c;let h=!0,u="";const f=d?.filter(g=>s===g.userRole);return f?.length&&!f.some(g=>g.recordRole===r)?(u=`User ${s} does not have write access to record with role ${r}`,h=!1,h):t==="update"&&o.User_ID&&f?.length&&!f.some(g=>g.recordRole===a)?(u=`User ${s} does not have write access to record with role ${r}`,h=!1,h):(d?.forEach(g=>{s===g.userRole&&g.recordRole===r&&t!=="delete"&&i&&Object.keys(n.collections).forEach(T=>{const m=i.collections?.[T],E=l?.collections?.[T];if(!(t==="update"&&Xe(m,E))&&m){const w=g.collections.some(x=>x.collection===T);if(w){if(w){const x=g.collections.find(v=>v.collection===T);if(!(m.operations.every(v=>x.operations.includes(v))||t==="update"&&Xe(m.operations,E?.operations))){u=`User ${s} does not have write access to all included operations for collection ${T}`,h=!1;return}if(!x.auth&&m.auth&&!(t==="update"&&Xe(m.auth,E?.auth))){u=`User ${s} does not have write access to auth for collection ${T}`,h=!1;return}const k={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(k).forEach(v=>{const N=k[v];if(x.attributeRestrictions?.includes(N)&&!(m[v]?.active||t==="update"&&Xe(m[v],E?.[v]))){u=`User ${s} does not have write access to attribute restriction ${v} for collection ${T}`,h=!1;return}}),x.restrictEntities&&!m.restrictEntities&&!(t==="update"&&Xe(m.restrictEntities,E?.restrictEntities))){u=`User ${s} does not have write access to restrictEntities for collection ${T}`,h=!1;return}}}else{u=`User ${s} does not have write access to collection ${T}`,h=!1;return}}})}),u&&console.error(`PERMISSION_DENIED: ${u}`),h)},da=(t,e,n,s)=>{let r=!0,i="";return Object.values(t.collections).forEach(o=>{const a=n.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!ts(c)){i=`User does not have auth access to collection ${o.labels.collection}`,r=!1;return}for(const d of a?.operations||[])if(!l?.operations.includes(d)&&(!Ie("Read",c)||!Ie(d,c))){i=`User does not have ${d.toLowerCase()} access to collection ${o.labels.collection}`,r=!1;return}if(!a?.recordOwner&&l?.recordOwner&&c?.recordOwner){i=`User does not have write access to recordOwner for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordUser&&l?.recordUser&&c?.recordUser){i=`User does not have write access to recordUser for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordProperty&&l?.recordProperty&&c?.recordProperty){i=`User does not have write access to recordProperty for collection ${o.labels.collection}`,r=!1;return}if(!a?.restrictEntities&&l?.restrictEntities&&c?.restrictEntities){i=`User does not have write access to restrictEntities for collection ${o.labels.collection}`,r=!1;return}}),i&&console.error(`PERMISSION_DENIED: ${i}`),r},Ys=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:h}=s;let u=!0,f="";if(!e.Role)return f="Record does not have a role",u=!1,u;if(t==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(t==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!ua(t,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(t==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;if(t==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return f="User cannot update their own record",u=!1,u;if(t==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return t==="delete"||d==="delete"||!a?u:a.Role?(la(r,a)||(u=!1),a.Collection&&a.Collection!==h.collection?(f="Permissions collection does not match record collection",u=!1,u):a.Role!==e.Role?(f="Permissions role does not match record role",u=!1,u):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",u=!1,u):a.Doc_ID&&a.Doc_ID!==n?(f="Permissions doc ID does not match record doc ID",u=!1,u):!ca(r,a,a.Role)||i&&o&&l&&!da(r,o,a,l)?(u=!1,u):(f&&console.error(`PERMISSION_DENIED: ${f}`),u)):(f="Permissions do not have a role",u=!1,u)},kr=(t,e,n,s,r,i,o,a)=>{const{labels:l,fields:c}=n,d=i?.collections?.[l.collection];let h=!0;if(r&&!d)throw new Error("PERMISSION_DENIED");r&&!Ie("Create",d)&&(h=!1),r&&!ft("Create",n,s,r,i,t)&&(h=!1),n.auth&&o&&(r&&!ts(d)&&(h=!1),Ys("create",t,e,n,s,r,i,o)||(h=!1));for(const u of c){const f=t[u.name];u.access&&!He(u,i,n,a)&&f!==void 0&&(h=!1),f!==void 0&&!oa(u,i,l.collection,a)&&(h=!1)}if(!h)throw new Error("PERMISSION_DENIED")},xe=t=>t&&(t._methodName==="deleteField"||t.constructor.name==="DeleteTransform"),lt=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(xe(t[e])?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&lt(t[e]))},br=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:h,fields:u}=s,f=o?.collections?.[h.collection],g={...e,...t};lt(g);let T=!0,m="";if(i&&!f)throw new Error("PERMISSION_DENIED");i&&!Ie("Update",f)&&(T=!1,m="Authenticated user does not have Update access to this collection"),i&&(!ft("Update",s,r,i,o,e)||!ft("Update",s,r,i,o,g))&&(T=!1,m="Authenticated user does not have Update access to this document"),i&&s.softDelete&&g[s.softDelete.archivedField]!==e[s.softDelete.archivedField]&&!Ie("Delete",f)&&(T=!1,m="Authenticated user does not have Delete or Restore access to this document"),a&&(i&&!ts(f)&&(T=!1,m="Authenticated user does not have Auth access for this collection"),Ys("update",g,n,s,r,i,o,l,c,e,a)||(m="Authenticated user does not have sufficient write access for this record",T=!1));for(const E of u){const w=t[E.name];E.access&&!He(E,o,s,d)&&w!==void 0&&(m=`Authenticated user does not have access to field ${E.name}`,T=!1),w!==void 0&&!ki(E,o,h.collection,d)&&(m=`Authenticated user does not have Update access to field ${E.name}`,T=!1)}if(!T)throw m&&console.error(`PERMISSION_DENIED: ${m}`),new Error("PERMISSION_DENIED")},fa=(t,e,n,s,r,i)=>{const{labels:o}=n,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(Ie("Delete",a)||(l=!1),ft("Delete",n,s,r,i,t)||(l=!1),n.auth&&t.User_ID&&(ts(a)||(l=!1),Ys("delete",t,e,n,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},ha=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Ie("Read",o)||(a=!1),ft("Read",e,n,s,r,t)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},ma=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Ie("Read",o)||(a=!1),t.forEach(l=>{ft("Read",e,n,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},pa=(t,e,n)=>{const{access:s}=t;return s.operations[n]?.includes(e)},ya=(t,e,n)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===t)&&!("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===t))continue;const o=V(e.fields,i.collectionField);if(!ee(o))throw new Error("PERMISSION_DENIED");const l=n.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(d=>d.role===t));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},ga=(t,e,n,s,r)=>{const i={};for(const o of t){const l=e[o].default({sdk:n,utils:s,context:r});for(const c in l)c==="custom"||c==="admin"||c==="fields"||delete l[c];for(const c of l.fields)for(const d in c)d==="custom"||d==="admin"||d==="name"||d==="formula"||delete c[d];i[o]=l}return i},Ue=(t,e)=>e.fields.filter(n=>n.name===t.name)[0],cs={global:{},collections:{}},Kt=(t,e)=>t&&typeof t=="function"?e?t(...e):t():t,ae=async(t,e)=>{let n=t;return t&&(typeof t=="function"||typeof t.then=="function")&&(e?n=await t(...e):n=await t()),n},wa=async(t,e,n,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=cs,i=!0;for(const d of e){if(d===void 0||r[d]===void 0){i=!1;break}r=r[d]}if(r&&i&&!s)return r;let o,a=t,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await ae(a,n)),c){let d=cs;const h={};for(let u=0;u<e.length;u++){const f=e[u];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");u===e.length-1?na(h,e.join("."),c):(d[f]||={},d=d[f])}}ta(cs,h)}return c},pt=(t,e,n)=>{const s=Object.values(n.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(ee(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field===t.name&&(i=!0)}return i},Ii=(t,e)=>{const n=Object.values(e.collections),{labels:s}=t,r={};return n.forEach(i=>{const{labels:o,fields:a}=i;a.forEach(l=>{ee(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},us=t=>JSON.stringify(t.map(e=>e.name)),ct=["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"],mn=()=>ct.map(t=>{let e="",n;switch(t){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",n=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:t,type:e,required:!0};return n&&(s.values=n),s}),Js=(t,e)=>{const n=[],{access:s,fields:r}=t,{attributeRestrictions:i,entityRestrictions:o}=s,a=mn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":n.push(V(a,"Created_By"));break;case"Record_User":n.push(V(r,l.collectionField));break;case"Record_Property":n.push(V(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(V(a,"id"));break;case"Parent":n.push(V(r,l.collectionField));break;case"Parent_Property":n.push(V(r,l.collectionField)),n.push(V(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(V(r,l.collectionField));break;case"Parent":n.push(V(r,l.parentCollectionField));break;case"Parent_Property":n.push(V(r,l.parentCollectionField)),n.push(V(r,l.parentPropertyField));break}})),[...new Set(n)]},_a=(t,e)=>{const n=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=t,a=mn();return n.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{cn(c,e)&&n.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{n.push(V(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{ct.includes(c)&&n.push(V(a,c))}),o?.forEach(c=>{const d=V(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&d&&cn(d,e)&&ct.includes(c.field)&&n.push(V(a,c.field))}),Js(t,e).forEach(c=>{ct.includes(c.name)&&n.push(V(a,c.name))}),[...new Set(n)]},Ea=(t,e,n)=>{const s=[],{fields:r,preloadCache:i}=e,o=mn(),a=new Set,l=Ii(e,n);return Object.entries(l).map(([c,d])=>{t.name===c&&Object.values(d).forEach(h=>{h.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(...Js(e,c))}),i?.range&&i.range.fields.forEach(c=>{ct.includes(c)?s.push(V(o,c)):Array.from(a).some(d=>cn(V(r,c),d))&&s.push(V(r,c))}),[...new Set(s)]},On=(t,e,n)=>{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=Ii(e,n);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{n.collections[c].fields.forEach(h=>{ee(h)&&h.collection===e.labels.collection&&h.dependencyFields?.some(u=>u.field===t.name)&&h.constraints&&h.constraints.forEach(u=>{o.push(u[0])})})})}),o.forEach(l=>{s.push(V(r,l))}),i){const l=V(r,i.archivedField);l&&s.push(l)}return s.push(...Ea(t,e,n)),[...new Set(s)]},va=(t,e,n)=>{const s=e.fieldAccessGroups?.[t]?.applicableRoles||[];return n.roles.filter(r=>s.includes(r))},on=(t,e)=>`${t}-${e}`,kn=(t,e,n)=>{if(!e.fieldAccessGroups?.[t])return[];const s=va(t,e,n);if(s.length===0)return[];const r=[],{fields:i,softDelete:o,preloadCache:a,roleSystemFields:l,queries:c}=e,d=mn();r.push({name:"Collection_Path",type:"Array",required:!0}),r.push({name:"id",type:"String",required:!0});const h=wt(e)[t]||[];if(r.push(...h),o){const u=V(i,o.archivedField);u&&!h.includes(u)&&r.push(u)}a?.range&&a.range.fields.forEach(u=>{ct.includes(u)?r.push(V(d,u)):s.some(f=>cn(V(i,u),f))&&r.push(V(i,u))}),l?.filter(u=>u.field!=="Collection_Path"&&s.some(f=>!u.roles||u.roles.includes(f))).forEach(u=>{r.push(V(d,u.field))}),c?.forEach(u=>{const f=V(i.concat(d),u.field);f&&s.some(g=>(!u.roles||u.roles.includes(g))&&cn(f,g))&&r.push(f)});for(const u of s)r.push(...Js(e,u));return[...new Set(r)]},xi=(t,e)=>{const{preloadCache:n}=t,s=new Set;for(const r of e.config.roles){if(!pa(t,r,"read"))continue;const i=_a(t,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))&&!!n?.roles.includes(r)==!!a.roles.every(l=>n?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},Ni=(t,e,n)=>{const s=xi(e,n);for(const r of s.values())if(r.roles.includes(t))return r},Oa=(t,e)=>{const{fields:n}=e,s=mn(),r=[];return[...n,...s.filter(o=>o.name!=="id")].forEach(o=>{t?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Qs=(t,e,n)=>{const s={};return Object.values(t.collections).forEach(r=>{const i=xi(r,t),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},Pn=t=>({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_Version:t.Last_Write_Version,Last_Write_App:t.Last_Write_App,Last_Save_At:t.Last_Save_At}),ds=async(t,e,n)=>{if(e){const s=await ae(e,[n]);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${t}`);return s}};async function de(t,e,n,s){const r=await ds(t,n.custom?.[t],s);for(const i of n.fields)await ds(t,i.custom?.[t],s);if(t!=="setEmbedding"&&(await ds(t,e?.[t],s),t==="postWriteError"))return r}const Ks=(t,e,n,s,r,i,o,a,l,c)=>(t==="create"&&(n.Collection_Path=e,n.Created_At=a,n.Saved_At=l,n.Created_By=o||"System"),n.Last_Write_App=r,n.Last_Write_At=a,n.Last_Save_At=l,n.Last_Write_By=o||"System",n.Last_Write_Connection_Status=i,n.Last_Write_Version=s.version,n),_t=(t,e)=>{const{access:n,queries:s}=t,{serverReadOnly:r}=n,i=new Set;if(s)for(const o of s){const a=V(e,o.field);e.find(l=>l.name===o.field)&&ee(a)&&["OneToOne","OneToMany"].includes(a.type)&&i.add(a)}return e.forEach(o=>{ee(o)&&["OneToOne","OneToMany"].includes(o.type)&&o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a)))&&i.add(o)}),i},Rt=(t,e)=>{const{access:n,recordTitleField:s}=t,{serverReadOnly:r}=n,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},ka=(t,e)=>{const n={Collection_Path:t.Collection_Path};if(t.deleted!==void 0&&(n.deleted=t.deleted),e)for(const s of e)t[s]!==void 0&&(n[s]=t[s]);return n},Et=(t,e,n)=>{const{fields:s}=t;s.forEach(i=>{if(ee(i))if(e[i.name]){if(xe(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(Object.keys(e[i.name]).forEach(o=>{const a=e[i.name][o];e[i.name][o]=ka(a,i.includeFields)}),e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=n.collections[i.collection],l=V(a.fields,o);Rt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(d=>{e[i.name][d][o]?e[i.name][d][`${o}_Lowercase`]=e[i.name][d][o].toLowerCase():delete e[i.name][d][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),_t(t,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}}}})},Ln=(t,e)=>{Rt(t,t.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},ba=async(t,e,n,s,r)=>{const{fields:i}=e;for(const o of n.fields){const a=V(i,o.name);o.custom?.initialValue!==void 0&&(!a.access||He(a,s,e,r||{}))&&(t[o.name]=await ae(o.custom.initialValue,[t]),Rt(e,[a]).size===1&&(t[`${o.name}_Lowercase`]=t[o.name].toLowerCase()))}for(const o of i)(!o.access||He(o,s,e,r||{}))&&("autoIncrement"in o&&o.autoIncrement&&!t[o.name]&&(t[o.name]="Pending"),!ee(o)&&o.nullable&&t[o.name]===void 0&&(t[o.name]=null))};var se;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.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},t.find=(r,i)=>{for(const o of r)if(i(o))return o},t.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)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(se||(se={}));var Tr;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Tr||(Tr={}));const Z=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),it=t=>{switch(typeof t){case"undefined":return Z.undefined;case"string":return Z.string;case"number":return Number.isNaN(t)?Z.nan:Z.number;case"boolean":return Z.boolean;case"function":return Z.function;case"bigint":return Z.bigint;case"symbol":return Z.symbol;case"object":return Array.isArray(t)?Z.array:t===null?Z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Z.promise:typeof Map<"u"&&t instanceof Map?Z.map:typeof Set<"u"&&t instanceof Set?Z.set:typeof Date<"u"&&t instanceof Date?Z.date:Z.object;default:return Z.unknown}},A=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 tt 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 n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=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(n(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(n(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof tt))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=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}tt.create=t=>new tt(t);const Is=(t,e)=>{let n;switch(t.code){case A.invalid_type:t.received===Z.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case A.invalid_union:n="Invalid input";break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:n="Invalid function arguments";break;case A.invalid_return_type:n="Invalid function return type";break;case A.invalid_date:n="Invalid date";break;case A.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:se.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case A.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case A.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case A.custom:n="Invalid input";break;case A.invalid_intersection_types:n="Intersection results could not be merged";break;case A.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:n="Number must be finite";break;default:n=e.defaultError,se.assertNever(t)}return{message:n}};let Ta=Is;function Sa(){return Ta}const Ra=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)a=c(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function L(t,e){const n=Sa(),s=Ra({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Is?void 0:Is].filter(r=>!!r)});t.common.issues.push(s)}class ke{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return Q;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return ke.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return Q;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 Q=Object.freeze({status:"aborted"}),Xt=t=>({status:"dirty",value:t}),Me=t=>({status:"valid",value:t}),Sr=t=>t.status==="aborted",Rr=t=>t.status==="dirty",Vt=t=>t.status==="valid",Vn=t=>typeof Promise<"u"&&t instanceof Promise;var q;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(q||(q={}));class Ge{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,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 Ir=(t,e)=>{if(Vt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new tt(t.common.issues);return this._error=n,this._error}}};function X(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||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}=t;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??n??a.defaultError}},description:r}}class te{get description(){return this._def.description}_getType(e){return it(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:it(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ke,ctx:{common:e.parent.common,data:e.data,parsedType:it(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Vn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:it(e)},r=this._parseSync({data:e,path:s.path,parent:s});return Ir(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:it(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return Vt(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>Vt(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:it(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Vn(r)?r:Promise.resolve(r));return Ir(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:A.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new jt({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:n=>this["~validate"](n)}}optional(){return ut.create(this,this._def)}nullable(){return Zt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ze.create(this)}promise(){return zn.create(this,this._def)}or(e){return Wn.create([this,e],this._def)}and(e){return jn.create(this,e,this._def)}transform(e){return new jt({...X(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Fs({...X(this._def),innerType:this,defaultValue:n,typeName:Y.ZodDefault})}brand(){return new Ja({typeName:Y.ZodBranded,type:this,...X(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new $s({...X(this._def),innerType:this,catchValue:n,typeName:Y.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Xs.create(this,e)}readonly(){return Ms.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ia=/^c[^\s-]{8,}$/i,xa=/^[0-9a-z]+$/,Na=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Aa=/^[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,Da=/^[a-z0-9_-]{21}$/i,Ca=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fa=/^[-+]?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)?)??$/,$a=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ma="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let fs;const Pa=/^(?:(?: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])$/,La=/^(?:(?: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]))$/,Ua=/^(([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])$/,Wa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ja=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ai="((\\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])))",Za=new RegExp(`^${Ai}$`);function Di(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function za(t){return new RegExp(`^${Di(t)}$`)}function qa(t){let e=`${Ai}T${Di(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Ba(t,e){return!!((e==="v4"||!e)&&Pa.test(t)||(e==="v6"||!e)&&Va.test(t))}function Ha(t,e){if(!Ca.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.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 Ga(t,e){return!!((e==="v4"||!e)&&La.test(t)||(e==="v6"||!e)&&Ua.test(t))}class et extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Z.string){const i=this._getOrReturnCtx(e);return L(i,{code:A.invalid_type,expected:Z.string,received:i.parsedType}),Q}const s=new ke;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty());else if(i.kind==="length"){const o=e.data.length>i.value,a=e.data.length<i.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?L(r,{code:A.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&L(r,{code:A.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")$a.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"email",code:A.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")fs||(fs=new RegExp(Ma,"u")),fs.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"emoji",code:A.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")Aa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"uuid",code:A.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")Da.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"nanoid",code:A.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Ia.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cuid",code:A.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")xa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cuid2",code:A.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Na.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"ulid",code:A.invalid_string,message:i.message}),s.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),L(r,{validation:"url",code:A.invalid_string,message:i.message}),s.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"regex",code:A.invalid_string,message:i.message}),s.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),L(r,{code:A.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),L(r,{code:A.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),L(r,{code:A.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?qa(i).test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:A.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Za.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:A.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?za(i).test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{code:A.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?Fa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"duration",code:A.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ba(e.data,i.version)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"ip",code:A.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Ha(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"jwt",code:A.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ga(e.data,i.version)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"cidr",code:A.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Wa.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"base64",code:A.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?ja.test(e.data)||(r=this._getOrReturnCtx(e,r),L(r,{validation:"base64url",code:A.invalid_string,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:A.invalid_string,...q.errToObj(s)})}_addCheck(e){return new et({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...q.errToObj(e)})}url(e){return this._addCheck({kind:"url",...q.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...q.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...q.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...q.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...q.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...q.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...q.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...q.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...q.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...q.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...q.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...q.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,...q.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,...q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...q.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...q.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...q.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...q.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...q.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...q.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...q.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...q.errToObj(n)})}nonempty(e){return this.min(1,q.errToObj(e))}trim(){return new et({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new et({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new et({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}et.create=t=>new et({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...X(t)});function Ya(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Ut extends te{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)!==Z.number){const i=this._getOrReturnCtx(e);return L(i,{code:A.invalid_type,expected:Z.number,received:i.parsedType}),Q}let s;const r=new ke;for(const i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),L(s,{code:A.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:A.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:A.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Ya(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),L(s,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),L(s,{code:A.not_finite,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,q.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.toString(n))}setLimit(e,n,s,r){return new Ut({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:q.toString(r)}]})}_addCheck(e){return new Ut({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:q.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:q.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.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,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Ut.create=t=>new Ut({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...X(t)});class un extends te{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)!==Z.bigint)return this._getInvalidInput(e);let s;const r=new ke;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:A.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(s=this._getOrReturnCtx(e,s),L(s,{code:A.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),L(s,{code:A.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return L(n,{code:A.invalid_type,expected:Z.bigint,received:n.parsedType}),Q}gte(e,n){return this.setLimit("min",e,!0,q.toString(n))}gt(e,n){return this.setLimit("min",e,!1,q.toString(n))}lte(e,n){return this.setLimit("max",e,!0,q.toString(n))}lt(e,n){return this.setLimit("max",e,!1,q.toString(n))}setLimit(e,n,s,r){return new un({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:q.toString(r)}]})}_addCheck(e){return new un({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:q.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}un.create=t=>new un({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...X(t)});class xs extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Z.boolean){const s=this._getOrReturnCtx(e);return L(s,{code:A.invalid_type,expected:Z.boolean,received:s.parsedType}),Q}return Me(e.data)}}xs.create=t=>new xs({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...X(t)});class Un extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Z.date){const i=this._getOrReturnCtx(e);return L(i,{code:A.invalid_type,expected:Z.date,received:i.parsedType}),Q}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return L(i,{code:A.invalid_date}),Q}const s=new ke;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:A.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),L(r,{code:A.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 Un({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:q.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:q.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Un.create=t=>new Un({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...X(t)});class xr extends te{_parse(e){if(this._getType(e)!==Z.symbol){const s=this._getOrReturnCtx(e);return L(s,{code:A.invalid_type,expected:Z.symbol,received:s.parsedType}),Q}return Me(e.data)}}xr.create=t=>new xr({typeName:Y.ZodSymbol,...X(t)});class Ns extends te{_parse(e){if(this._getType(e)!==Z.undefined){const s=this._getOrReturnCtx(e);return L(s,{code:A.invalid_type,expected:Z.undefined,received:s.parsedType}),Q}return Me(e.data)}}Ns.create=t=>new Ns({typeName:Y.ZodUndefined,...X(t)});class Nr extends te{_parse(e){if(this._getType(e)!==Z.null){const s=this._getOrReturnCtx(e);return L(s,{code:A.invalid_type,expected:Z.null,received:s.parsedType}),Q}return Me(e.data)}}Nr.create=t=>new Nr({typeName:Y.ZodNull,...X(t)});class As extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return Me(e.data)}}As.create=t=>new As({typeName:Y.ZodAny,...X(t)});class Ar extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Me(e.data)}}Ar.create=t=>new Ar({typeName:Y.ZodUnknown,...X(t)});class ht extends te{_parse(e){const n=this._getOrReturnCtx(e);return L(n,{code:A.invalid_type,expected:Z.never,received:n.parsedType}),Q}}ht.create=t=>new ht({typeName:Y.ZodNever,...X(t)});class Dr extends te{_parse(e){if(this._getType(e)!==Z.undefined){const s=this._getOrReturnCtx(e);return L(s,{code:A.invalid_type,expected:Z.void,received:s.parsedType}),Q}return Me(e.data)}}Dr.create=t=>new Dr({typeName:Y.ZodVoid,...X(t)});class ze extends te{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==Z.array)return L(n,{code:A.invalid_type,expected:Z.array,received:n.parsedType}),Q;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,a=n.data.length<r.exactLength.value;(o||a)&&(L(n,{code:o?A.too_big:A.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&&n.data.length<r.minLength.value&&(L(n,{code:A.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(L(n,{code:A.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>r.type._parseAsync(new Ge(n,o,n.path,a)))).then(o=>ke.mergeArray(s,o));const i=[...n.data].map((o,a)=>r.type._parseSync(new Ge(n,o,n.path,a)));return ke.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new ze({...this._def,minLength:{value:e,message:q.toString(n)}})}max(e,n){return new ze({...this._def,maxLength:{value:e,message:q.toString(n)}})}length(e,n){return new ze({...this._def,exactLength:{value:e,message:q.toString(n)}})}nonempty(e){return this.min(1,e)}}ze.create=(t,e)=>new ze({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...X(e)});function Ft(t){if(t instanceof pe){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=ut.create(Ft(s))}return new pe({...t._def,shape:()=>e})}else return t instanceof ze?new ze({...t._def,type:Ft(t.element)}):t instanceof ut?ut.create(Ft(t.unwrap())):t instanceof Zt?Zt.create(Ft(t.unwrap())):t instanceof bt?bt.create(t.items.map(e=>Ft(e))):t}class pe extends te{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(),n=se.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Z.object){const c=this._getOrReturnCtx(e);return L(c,{code:A.invalid_type,expected:Z.object,received:c.parsedType}),Q}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof ht&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const d=i[c],h=r.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Ge(r,h,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ht){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")a.length>0&&(L(r,{code:A.unrecognized_keys,keys:a}),s.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const d of a){const h=r.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Ge(r,h,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const h=await d.key,u=await d.value;c.push({key:h,value:u,alwaysSet:d.alwaysSet})}return c}).then(c=>ke.mergeObjectSync(s,c)):ke.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return q.errToObj,new pe({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:q.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new pe({...this._def,unknownKeys:"strip"})}passthrough(){return new pe({...this._def,unknownKeys:"passthrough"})}extend(e){return new pe({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new pe({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new pe({...this._def,catchall:e})}pick(e){const n={};for(const s of se.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new pe({...this._def,shape:()=>n})}omit(e){const n={};for(const s of se.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new pe({...this._def,shape:()=>n})}deepPartial(){return Ft(this)}partial(e){const n={};for(const s of se.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new pe({...this._def,shape:()=>n})}required(e){const n={};for(const s of se.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof ut;)i=i._def.innerType;n[s]=i}return new pe({...this._def,shape:()=>n})}keyof(){return Ci(se.objectKeys(this.shape))}}pe.create=(t,e)=>new pe({shape:()=>t,unknownKeys:"strip",catchall:ht.create(),typeName:Y.ZodObject,...X(e)});pe.strictCreate=(t,e)=>new pe({shape:()=>t,unknownKeys:"strict",catchall:ht.create(),typeName:Y.ZodObject,...X(e)});pe.lazycreate=(t,e)=>new pe({shape:t,unknownKeys:"strip",catchall:ht.create(),typeName:Y.ZodObject,...X(e)});class Wn extends te{_parse(e){const{ctx:n}=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 n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new tt(a.ctx.common.issues));return L(n,{code:A.invalid_union,unionErrors:o}),Q}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new tt(l));return L(n,{code:A.invalid_union,unionErrors:a}),Q}}get options(){return this._def.options}}Wn.create=(t,e)=>new Wn({options:t,typeName:Y.ZodUnion,...X(e)});function Ds(t,e){const n=it(t),s=it(e);if(t===e)return{valid:!0,data:t};if(n===Z.object&&s===Z.object){const r=se.objectKeys(e),i=se.objectKeys(t).filter(a=>r.indexOf(a)!==-1),o={...t,...e};for(const a of i){const l=Ds(t[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(n===Z.array&&s===Z.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const o=t[i],a=e[i],l=Ds(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===Z.date&&s===Z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class jn extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(Sr(i)||Sr(o))return Q;const a=Ds(i.value,o.value);return a.valid?((Rr(i)||Rr(o))&&n.dirty(),{status:n.value,value:a.data}):(L(s,{code:A.invalid_intersection_types}),Q)};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}))}}jn.create=(t,e,n)=>new jn({left:t,right:e,typeName:Y.ZodIntersection,...X(n)});class bt extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==Z.array)return L(s,{code:A.invalid_type,expected:Z.array,received:s.parsedType}),Q;if(s.data.length<this._def.items.length)return L(s,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;!this._def.rest&&s.data.length>this._def.items.length&&(L(s,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Ge(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>ke.mergeArray(n,o)):ke.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new bt({...this._def,rest:e})}}bt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new bt({items:t,typeName:Y.ZodTuple,rest:null,...X(e)})};class Zn extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==Z.object)return L(s,{code:A.invalid_type,expected:Z.object,received:s.parsedType}),Q;const r=[],i=this._def.keyType,o=this._def.valueType;for(const a in s.data)r.push({key:i._parse(new Ge(s,a,s.path,a)),value:o._parse(new Ge(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?ke.mergeObjectAsync(n,r):ke.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof te?new Zn({keyType:e,valueType:n,typeName:Y.ZodRecord,...X(s)}):new Zn({keyType:et.create(),valueType:e,typeName:Y.ZodRecord,...X(n)})}}class Cr extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==Z.map)return L(s,{code:A.invalid_type,expected:Z.map,received:s.parsedType}),Q;const r=this._def.keyType,i=this._def.valueType,o=[...s.data.entries()].map(([a,l],c)=>({key:r._parse(new Ge(s,a,s.path,[c,"key"])),value:i._parse(new Ge(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return Q;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return Q;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}}}}Cr.create=(t,e,n)=>new Cr({valueType:e,keyType:t,typeName:Y.ZodMap,...X(n)});class dn extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==Z.set)return L(s,{code:A.invalid_type,expected:Z.set,received:s.parsedType}),Q;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(L(s,{code:A.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(L(s,{code:A.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const d of l){if(d.status==="aborted")return Q;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new Ge(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,n){return new dn({...this._def,minSize:{value:e,message:q.toString(n)}})}max(e,n){return new dn({...this._def,maxSize:{value:e,message:q.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}dn.create=(t,e)=>new dn({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...X(e)});class Fr extends te{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Fr.create=(t,e)=>new Fr({getter:t,typeName:Y.ZodLazy,...X(e)});class Cs extends te{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return L(n,{received:n.data,code:A.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}}Cs.create=(t,e)=>new Cs({value:t,typeName:Y.ZodLiteral,...X(e)});function Ci(t,e){return new Wt({values:t,typeName:Y.ZodEnum,...X(e)})}class Wt extends te{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return L(n,{expected:se.joinValues(s),received:n.parsedType,code:A.invalid_type}),Q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return L(n,{received:n.data,code:A.invalid_enum_value,options:s}),Q}return Me(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Wt.create(e,{...this._def,...n})}exclude(e,n=this._def){return Wt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}Wt.create=Ci;class $r extends te{_parse(e){const n=se.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==Z.string&&s.parsedType!==Z.number){const r=se.objectValues(n);return L(s,{expected:se.joinValues(r),received:s.parsedType,code:A.invalid_type}),Q}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=se.objectValues(n);return L(s,{received:s.data,code:A.invalid_enum_value,options:r}),Q}return Me(e.data)}get enum(){return this._def.values}}$r.create=(t,e)=>new $r({values:t,typeName:Y.ZodNativeEnum,...X(e)});class zn extends te{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Z.promise&&n.common.async===!1)return L(n,{code:A.invalid_type,expected:Z.promise,received:n.parsedType}),Q;const s=n.parsedType===Z.promise?n.data:Promise.resolve(n.data);return Me(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}zn.create=(t,e)=>new zn({type:t,typeName:Y.ZodPromise,...X(e)});class jt extends te{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:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{L(s,o),o.fatal?n.abort():n.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(n.value==="aborted")return Q;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?Q:l.status==="dirty"||n.value==="dirty"?Xt(l.value):l});{if(n.value==="aborted")return Q;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?Q:a.status==="dirty"||n.value==="dirty"?Xt(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"?Q:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?Q:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.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(!Vt(o))return Q;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:n.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Vt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:n.value,value:a})):Q);se.assertNever(r)}}jt.create=(t,e,n)=>new jt({schema:t,typeName:Y.ZodEffects,effect:e,...X(n)});jt.createWithPreprocess=(t,e,n)=>new jt({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...X(n)});class ut extends te{_parse(e){return this._getType(e)===Z.undefined?Me(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ut.create=(t,e)=>new ut({innerType:t,typeName:Y.ZodOptional,...X(e)});class Zt extends te{_parse(e){return this._getType(e)===Z.null?Me(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Zt.create=(t,e)=>new Zt({innerType:t,typeName:Y.ZodNullable,...X(e)});class Fs extends te{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===Z.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Fs.create=(t,e)=>new Fs({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});class $s extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Vn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new tt(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new tt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}$s.create=(t,e)=>new $s({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});class Mr extends te{_parse(e){if(this._getType(e)!==Z.nan){const s=this._getOrReturnCtx(e);return L(s,{code:A.invalid_type,expected:Z.nan,received:s.parsedType}),Q}return{status:"valid",value:e.data}}}Mr.create=t=>new Mr({typeName:Y.ZodNaN,...X(t)});class Ja extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Xs extends te{_parse(e){const{status:n,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"?Q:i.status==="dirty"?(n.dirty(),Xt(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"?Q:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new Xs({in:e,out:n,typeName:Y.ZodPipeline})}}class Ms extends te{_parse(e){const n=this._def.innerType._parse(e),s=r=>(Vt(r)&&(r.value=Object.freeze(r.value)),r);return Vn(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}Ms.create=(t,e)=>new Ms({innerType:t,typeName:Y.ZodReadonly,...X(e)});var Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(Y={}));const Re=et.create,vt=Ut.create,an=xs.create,hs=Ns.create,we=As.create;ht.create;const It=ze.create,qe=pe.create,Te=Wn.create;jn.create;bt.create;const pn=Zn.create,Se=Cs.create,qn=Wt.create;zn.create;ut.create;Zt.create;const Nn=()=>we().refine(t=>t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),Pr=()=>we().refine(t=>t&&(t._methodName==="serverTimestamp"||t.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),Fi=(t,e,n)=>{const s={};if(t.includeFields){const i=e.collections[t.collection];if(!i)return pn(we());t.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${t.collection}`);s[o]=Bn(i,a),Rt(i,[a]).size===1&&(s[`${o}_Lowercase`]=Bn(i,a,!0))})}const r={Collection_Path:It(Re()),...s};return n&&(r.id=Re().length(20)),qe(r)},Qa=(t,e)=>{let n=pn(Fi(t,e));return t.required||(n=n.optional()),n},Ka=t=>{let e=It(Te([Re().length(20),Re().length(28)]));return["OneToOne","OneToMany"].includes(t.type)?e=e.max(1):(t.min&&(e=e.min(t.min)),t.max&&(e=e.max(t.max)),t.length&&(e=e.length(t.length))),t.required?e=e.nonempty():e=e.optional(),e},Bn=(t,e,n)=>{const{softDelete:s}=t,r=s?.timestampField;let i;switch(e.type){case"String":if(i=Re(),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))),n&&(i=i.toLowerCase()),e.values)if(n){const o=e.values.map(a=>a.toLowerCase());i=qn(o)}else i=qn(e.values);break;case"Boolean":i=an();break;case"Number":e.autoIncrement?i=Te([Se("Pending"),vt().int()]):(i=vt(),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=we().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=Nn(),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=It(we()),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=pn(we()),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=we();break}return!ee(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},$i=(t,e,n)=>{const s={Collection_Path:It(Re()),Last_Write_App:Re(),Last_Write_At:Nn(),Last_Save_At:Pr(),Last_Write_By:Te([Re().length(28),Se("System")]),Last_Write_Connection_Status:qn(["Online","Offline"]),Last_Write_Version:vt().int(),id:Re().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:Nn(),Created_By:Te([Re().length(28),Se("System")])};t==="create"&&(s.Saved_At=Pr()),t==="update"&&(s.Saved_At=Nn(),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=_t(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{ee(l)?(s[l.name]=Qa(l,n),s[`${l.name}_Array`]=Ka(l),i.includes(l.name)&&(s[`${l.name}_Single`]=Fi(l,n,!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]=Bn(e,l))}),Rt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=Bn(e,l,!0))});const a=qe(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class xt extends Error{}class Xa extends xt{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class el extends xt{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class tl extends xt{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class $t extends xt{}class Mi extends xt{constructor(e){super(`Invalid unit ${e}`)}}class _e extends xt{}class rt extends xt{constructor(){super("Zone is an abstract class")}}const $="numeric",We="short",Ne="long",Hn={year:$,month:$,day:$},Pi={year:$,month:We,day:$},nl={year:$,month:We,day:$,weekday:We},Li={year:$,month:Ne,day:$},Vi={year:$,month:Ne,day:$,weekday:Ne},Ui={hour:$,minute:$},Wi={hour:$,minute:$,second:$},ji={hour:$,minute:$,second:$,timeZoneName:We},Zi={hour:$,minute:$,second:$,timeZoneName:Ne},zi={hour:$,minute:$,hourCycle:"h23"},qi={hour:$,minute:$,second:$,hourCycle:"h23"},Bi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:We},Hi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:Ne},Gi={year:$,month:$,day:$,hour:$,minute:$},Yi={year:$,month:$,day:$,hour:$,minute:$,second:$},Ji={year:$,month:We,day:$,hour:$,minute:$},Qi={year:$,month:We,day:$,hour:$,minute:$,second:$},sl={year:$,month:We,day:$,weekday:We,hour:$,minute:$},Ki={year:$,month:Ne,day:$,hour:$,minute:$,timeZoneName:We},Xi={year:$,month:Ne,day:$,hour:$,minute:$,second:$,timeZoneName:We},eo={year:$,month:Ne,day:$,weekday:Ne,hour:$,minute:$,timeZoneName:Ne},to={year:$,month:Ne,day:$,weekday:Ne,hour:$,minute:$,second:$,timeZoneName:Ne};class yn{get type(){throw new rt}get name(){throw new rt}get ianaName(){return this.name}get isUniversal(){throw new rt}offsetName(e,n){throw new rt}formatOffset(e,n){throw new rt}offset(e){throw new rt}equals(e){throw new rt}get isValid(){throw new rt}}let ms=null;class ns extends yn{static get instance(){return ms===null&&(ms=new ns),ms}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return ho(e,n,s)}formatOffset(e,n){return ln(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Ps=new Map;function rl(t){let e=Ps.get(t);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Ps.set(t,e)),e}const il={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ol(t,e){const n=t.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,r,i,o,a,l,c,d]=s;return[o,r,i,a,l,c,d]}function al(t,e){const n=t.formatToParts(e),s=[];for(let r=0;r<n.length;r++){const{type:i,value:o}=n[r],a=il[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const ps=new Map;class nt extends yn{static create(e){let n=ps.get(e);return n===void 0&&ps.set(e,n=new nt(e)),n}static resetCache(){ps.clear(),Ps.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=nt.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return ho(e,n,s,this.name)}formatOffset(e,n){return ln(this.offset(e),n)}offset(e){if(!this.valid)return NaN;const n=new Date(e);if(isNaN(n))return NaN;const s=rl(this.name);let[r,i,o,a,l,c,d]=s.formatToParts?al(s,n):ol(s,n);a==="BC"&&(r=-Math.abs(r)+1);const u=rs({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:d,millisecond:0});let f=+n;const g=f%1e3;return f-=g>=0?g:1e3+g,(u-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Lr={};function ll(t,e={}){const n=JSON.stringify([t,e]);let s=Lr[n];return s||(s=new Intl.ListFormat(t,e),Lr[n]=s),s}const Ls=new Map;function Vs(t,e={}){const n=JSON.stringify([t,e]);let s=Ls.get(n);return s===void 0&&(s=new Intl.DateTimeFormat(t,e),Ls.set(n,s)),s}const Us=new Map;function cl(t,e={}){const n=JSON.stringify([t,e]);let s=Us.get(n);return s===void 0&&(s=new Intl.NumberFormat(t,e),Us.set(n,s)),s}const Ws=new Map;function ul(t,e={}){const{base:n,...s}=e,r=JSON.stringify([t,s]);let i=Ws.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(t,e),Ws.set(r,i)),i}let en=null;function dl(){return en||(en=new Intl.DateTimeFormat().resolvedOptions().locale,en)}const js=new Map;function no(t){let e=js.get(t);return e===void 0&&(e=new Intl.DateTimeFormat(t).resolvedOptions(),js.set(t,e)),e}const Zs=new Map;function fl(t){let e=Zs.get(t);if(!e){const n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,"minimalDays"in e||(e={...so,...e}),Zs.set(t,e)}return e}function hl(t){const e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));const n=t.indexOf("-u-");if(n===-1)return[t];{let s,r;try{s=Vs(t).resolvedOptions(),r=t}catch{const l=t.substring(0,n);s=Vs(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function ml(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function pl(t){const e=[];for(let n=1;n<=12;n++){const s=j.utc(2009,n,1);e.push(t(s))}return e}function yl(t){const e=[];for(let n=1;n<=7;n++){const s=j.utc(2016,11,13+n);e.push(t(s))}return e}function bn(t,e,n,s){const r=t.listingMode();return r==="error"?null:r==="en"?n(e):s(e)}function gl(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||no(t.locale).numberingSystem==="latn"}class wl{constructor(e,n,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!n||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=cl(e,a)}}format(e){if(this.inf){const n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):rr(e,3);return ye(n,this.padTo)}}}class _l{constructor(e,n,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&&nt.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=Vs(n,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(n=>{if(n.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:s}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class El{constructor(e,n,s){this.opts={style:"long",...s},!n&&uo()&&(this.rtf=ul(e,s))}format(e,n){return this.rtf?this.rtf.format(e,n):jl(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}const so={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,n,s,r,i=!1){const o=e||he.defaultLocale,a=o||(i?"en-US":dl()),l=n||he.defaultNumberingSystem,c=s||he.defaultOutputCalendar,d=qs(r)||he.defaultWeekSettings;return new ie(a,l,c,d,o)}static resetCache(){en=null,Ls.clear(),Us.clear(),Ws.clear(),js.clear(),Zs.clear()}static fromObject({locale:e,numberingSystem:n,outputCalendar:s,weekSettings:r}={}){return ie.create(e,n,s,r)}constructor(e,n,s,r,i){const[o,a,l]=hl(e);this.locale=o,this.numberingSystem=n||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=ml(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=gl(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"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,qs(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,n=!1){return bn(this,e,yo,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");n&=!s;const r=n?{month:e,day:"numeric"}:{month:e},i=n?"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]=pl(o)}return this.monthsCache[i][e]})}weekdays(e,n=!1){return bn(this,e,_o,()=>{const s=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=n?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=yl(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return bn(this,void 0,()=>Eo,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[j.utc(2016,11,13,9),j.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return bn(this,e,vo,()=>{const n={era:e};return this.eraCache[e]||(this.eraCache[e]=[j.utc(-40,1,1),j.utc(2017,1,1)].map(s=>this.extract(s,n,"era"))),this.eraCache[e]})}extract(e,n,s){const r=this.dtFormatter(e,n),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new wl(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new _l(e,this.intl,n)}relFormatter(e={}){return new El(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ll(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||no(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:fo()?fl(this.locale):so}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 ys=null;class Oe extends yn{static get utcInstance(){return ys===null&&(ys=new Oe(0)),ys}static instance(e){return e===0?Oe.utcInstance:new Oe(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new Oe(is(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${ln(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${ln(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return ln(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class vl extends yn{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 at(t,e){if(G(t)||t===null)return e;if(t instanceof yn)return t;if(Rl(t)){const n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?ns.instance:n==="utc"||n==="gmt"?Oe.utcInstance:Oe.parseSpecifier(n)||nt.create(t)}else return dt(t)?Oe.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new vl(t)}const er={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Vr={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]},Ol=er.hanidec.replace(/[\[|\]]/g,"").split("");function kl(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);if(t[n].search(er.hanidec)!==-1)e+=Ol.indexOf(t[n]);else for(const r in Vr){const[i,o]=Vr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const zs=new Map;function bl(){zs.clear()}function Pe({numberingSystem:t},e=""){const n=t||"latn";let s=zs.get(n);s===void 0&&(s=new Map,zs.set(n,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${er[n]}${e}`),s.set(e,r)),r}let Ur=()=>Date.now(),Wr="system",jr=null,Zr=null,zr=null,qr=60,Br,Hr=null;class he{static get now(){return Ur}static set now(e){Ur=e}static set defaultZone(e){Wr=e}static get defaultZone(){return at(Wr,ns.instance)}static get defaultLocale(){return jr}static set defaultLocale(e){jr=e}static get defaultNumberingSystem(){return Zr}static set defaultNumberingSystem(e){Zr=e}static get defaultOutputCalendar(){return zr}static set defaultOutputCalendar(e){zr=e}static get defaultWeekSettings(){return Hr}static set defaultWeekSettings(e){Hr=qs(e)}static get twoDigitCutoffYear(){return qr}static set twoDigitCutoffYear(e){qr=e%100}static get throwOnInvalid(){return Br}static set throwOnInvalid(e){Br=e}static resetCaches(){ie.resetCache(),nt.resetCache(),j.resetCache(),bl()}}class Ve{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const ro=[0,31,59,90,120,151,181,212,243,273,304,334],io=[0,31,60,91,121,152,182,213,244,274,305,335];function Fe(t,e){return new Ve("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function tr(t,e,n){const s=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function oo(t,e,n){return n+(gn(t)?io:ro)[e-1]}function ao(t,e){const n=gn(t)?io:ro,s=n.findIndex(i=>i<e),r=e-n[s];return{month:s+1,day:r}}function nr(t,e){return(t-e+7)%7+1}function Gn(t,e=4,n=1){const{year:s,month:r,day:i}=t,o=oo(s,r,i),a=nr(tr(s,r,i),n);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=fn(c,e,n)):l>fn(s,e,n)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...os(t)}}function Gr(t,e=4,n=1){const{weekYear:s,weekNumber:r,weekday:i}=t,o=nr(tr(s,1,e),n),a=Pt(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=Pt(c)):l>a?(c=s+1,l-=Pt(s)):c=s;const{month:d,day:h}=ao(c,l);return{year:c,month:d,day:h,...os(t)}}function gs(t){const{year:e,month:n,day:s}=t,r=oo(e,n,s);return{year:e,ordinal:r,...os(t)}}function Yr(t){const{year:e,ordinal:n}=t,{month:s,day:r}=ao(e,n);return{year:e,month:s,day:r,...os(t)}}function Jr(t,e){if(!G(t.localWeekday)||!G(t.localWeekNumber)||!G(t.localWeekYear)){if(!G(t.weekday)||!G(t.weekNumber)||!G(t.weekYear))throw new $t("Cannot mix locale-based week fields with ISO-based week fields");return G(t.localWeekday)||(t.weekday=t.localWeekday),G(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),G(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function Tl(t,e=4,n=1){const s=ss(t.weekYear),r=$e(t.weekNumber,1,fn(t.weekYear,e,n)),i=$e(t.weekday,1,7);return s?r?i?!1:Fe("weekday",t.weekday):Fe("week",t.weekNumber):Fe("weekYear",t.weekYear)}function Sl(t){const e=ss(t.year),n=$e(t.ordinal,1,Pt(t.year));return e?n?!1:Fe("ordinal",t.ordinal):Fe("year",t.year)}function lo(t){const e=ss(t.year),n=$e(t.month,1,12),s=$e(t.day,1,Yn(t.year,t.month));return e?n?s?!1:Fe("day",t.day):Fe("month",t.month):Fe("year",t.year)}function co(t){const{hour:e,minute:n,second:s,millisecond:r}=t,i=$e(e,0,23)||e===24&&n===0&&s===0&&r===0,o=$e(n,0,59),a=$e(s,0,59),l=$e(r,0,999);return i?o?a?l?!1:Fe("millisecond",r):Fe("second",s):Fe("minute",n):Fe("hour",e)}function G(t){return typeof t>"u"}function dt(t){return typeof t=="number"}function ss(t){return typeof t=="number"&&t%1===0}function Rl(t){return typeof t=="string"}function Il(t){return Object.prototype.toString.call(t)==="[object Date]"}function uo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function fo(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function xl(t){return Array.isArray(t)?t:[t]}function Qr(t,e,n){if(t.length!==0)return t.reduce((s,r)=>{const i=[e(r),r];return s&&n(s[0],i[0])===s[0]?s:i},null)[1]}function Nl(t,e){return e.reduce((n,s)=>(n[s]=t[s],n),{})}function zt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function qs(t){if(t==null)return null;if(typeof t!="object")throw new _e("Week settings must be an object");if(!$e(t.firstDay,1,7)||!$e(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!$e(e,1,7)))throw new _e("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function $e(t,e,n){return ss(t)&&t>=e&&t<=n}function Al(t,e){return t-e*Math.floor(t/e)}function ye(t,e=2){const n=t<0;let s;return n?s="-"+(""+-t).padStart(e,"0"):s=(""+t).padStart(e,"0"),s}function ot(t){if(!(G(t)||t===null||t===""))return parseInt(t,10)}function yt(t){if(!(G(t)||t===null||t===""))return parseFloat(t)}function sr(t){if(!(G(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function rr(t,e,n="round"){const s=10**e;switch(n){case"expand":return t>0?Math.ceil(t*s)/s:Math.floor(t*s)/s;case"trunc":return Math.trunc(t*s)/s;case"round":return Math.round(t*s)/s;case"floor":return Math.floor(t*s)/s;case"ceil":return Math.ceil(t*s)/s;default:throw new RangeError(`Value rounding ${n} is out of range`)}}function gn(t){return t%4===0&&(t%100!==0||t%400===0)}function Pt(t){return gn(t)?366:365}function Yn(t,e){const n=Al(e-1,12)+1,s=t+(e-n)/12;return n===2?gn(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function rs(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Kr(t,e,n){return-nr(tr(t,1,e),n)+e-1}function fn(t,e=4,n=1){const s=Kr(t,e,n),r=Kr(t+1,e,n);return(Pt(t)-s+r)/7}function Bs(t){return t>99?t:t>he.twoDigitCutoffYear?1900+t:2e3+t}function ho(t,e,n,s=null){const r=new Date(t),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(n,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function is(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const s=parseInt(e,10)||0,r=n<0||Object.is(n,-0)?-s:s;return n*60+r}function mo(t){const e=Number(t);if(typeof t=="boolean"||t===""||!Number.isFinite(e))throw new _e(`Invalid unit value ${t}`);return e}function Jn(t,e){const n={};for(const s in t)if(zt(t,s)){const r=t[s];if(r==null)continue;n[e(s)]=mo(r)}return n}function ln(t,e){const n=Math.trunc(Math.abs(t/60)),s=Math.trunc(Math.abs(t%60)),r=t>=0?"+":"-";switch(e){case"short":return`${r}${ye(n,2)}:${ye(s,2)}`;case"narrow":return`${r}${n}${s>0?`:${s}`:""}`;case"techie":return`${r}${ye(n,2)}${ye(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function os(t){return Nl(t,["hour","minute","second","millisecond"])}const Dl=["January","February","March","April","May","June","July","August","September","October","November","December"],po=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Cl=["J","F","M","A","M","J","J","A","S","O","N","D"];function yo(t){switch(t){case"narrow":return[...Cl];case"short":return[...po];case"long":return[...Dl];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 go=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],wo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Fl=["M","T","W","T","F","S","S"];function _o(t){switch(t){case"narrow":return[...Fl];case"short":return[...wo];case"long":return[...go];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Eo=["AM","PM"],$l=["Before Christ","Anno Domini"],Ml=["BC","AD"],Pl=["B","A"];function vo(t){switch(t){case"narrow":return[...Pl];case"short":return[...Ml];case"long":return[...$l];default:return null}}function Ll(t){return Eo[t.hour<12?0:1]}function Vl(t,e){return _o(e)[t.weekday-1]}function Ul(t,e){return yo(e)[t.month-1]}function Wl(t,e){return vo(e)[t.year<0?0:1]}function jl(t,e,n="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(t)===-1;if(n==="auto"&&i){const h=t==="days";switch(e){case 1:return h?"tomorrow":`next ${r[t][0]}`;case-1:return h?"yesterday":`last ${r[t][0]}`;case 0:return h?"today":`this ${r[t][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[t],d=s?l?c[1]:c[2]||c[1]:l?r[t][0]:t;return o?`${a} ${d} ago`:`in ${a} ${d}`}function Xr(t,e){let n="";for(const s of t)s.literal?n+=s.val:n+=e(s.val);return n}const Zl={D:Hn,DD:Pi,DDD:Li,DDDD:Vi,t:Ui,tt:Wi,ttt:ji,tttt:Zi,T:zi,TT:qi,TTT:Bi,TTTT:Hi,f:Gi,ff:Ji,fff:Ki,ffff:eo,F:Yi,FF:Qi,FFF:Xi,FFFF:to};class Ee{static create(e,n={}){return new Ee(e,n)}static parseFormat(e){let n=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}),n=null,s="",r=!r):r||a===n?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,n=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return Zl[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0,s=void 0){if(this.opts.forceSimple)return ye(e,n);const r={...this.opts};return n>0&&(r.padTo=n),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(f,g)=>this.loc.extract(e,f,g),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>s?Ll(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,g)=>s?Ul(e,f):i(g?{month:f}:{month:f,day:"numeric"},"month"),c=(f,g)=>s?Vl(e,f):i(g?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),d=f=>{const g=Ee.macroTokenToFormatOpts(f);return g?this.formatWithSystemDefault(e,g):f},h=f=>s?Wl(e,f):i({era:f},"era"),u=f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return r?i({day:"numeric"},"day"):this.num(e.day);case"dd":return r?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return r?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return r?i({month:"numeric"},"month"):this.num(e.month);case"MM":return r?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return r?i({year:"numeric"},"year"):this.num(e.year);case"yy":return r?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return h("short");case"GG":return h("long");case"GGGGG":return h("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return d(f)}};return Xr(Ee.parseFormat(n),u)}formatDurationFromString(e,n){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(d,h)=>u=>{const f=r(u);if(f){const g=h.isNegativeDuration&&f!==h.largestUnit?s:1;let T;return this.opts.signMode==="negativeLargestOnly"&&f!==h.largestUnit?T="never":this.opts.signMode==="all"?T="always":T="auto",this.num(d.get(f)*g,u.length,T)}else return u},o=Ee.parseFormat(n),a=o.reduce((d,{literal:h,val:u})=>h?d:d.concat(u),[]),l=e.shiftTo(...a.map(r).filter(d=>d)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Xr(o,i(l,c))}}const Oo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function qt(...t){const e=t.reduce((n,s)=>n+s.source,"");return RegExp(`^${e}$`)}function Bt(...t){return e=>t.reduce(([n,s,r],i)=>{const[o,a,l]=i(e,r);return[{...n,...o},a||s,l]},[{},null,1]).slice(0,2)}function Ht(t,...e){if(t==null)return[null,null];for(const[n,s]of e){const r=n.exec(t);if(r)return s(r)}return[null,null]}function ko(...t){return(e,n)=>{const s={};let r;for(r=0;r<t.length;r++)s[t[r]]=ot(e[n+r]);return[s,null,n+r]}}const bo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,zl=`(?:${bo.source}?(?:\\[(${Oo.source})\\])?)?`,ir=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,To=RegExp(`${ir.source}${zl}`),or=RegExp(`(?:[Tt]${To.source})?`),ql=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Bl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Hl=/(\d{4})-?(\d{3})/,Gl=ko("weekYear","weekNumber","weekDay"),Yl=ko("year","ordinal"),Jl=/(\d{4})-(\d\d)-(\d\d)/,So=RegExp(`${ir.source} ?(?:${bo.source}|(${Oo.source}))?`),Ql=RegExp(`(?: ${So.source})?`);function Lt(t,e,n){const s=t[e];return G(s)?n:ot(s)}function Kl(t,e){return[{year:Lt(t,e),month:Lt(t,e+1,1),day:Lt(t,e+2,1)},null,e+3]}function Gt(t,e){return[{hours:Lt(t,e,0),minutes:Lt(t,e+1,0),seconds:Lt(t,e+2,0),milliseconds:sr(t[e+3])},null,e+4]}function wn(t,e){const n=!t[e]&&!t[e+1],s=is(t[e+1],t[e+2]),r=n?null:Oe.instance(s);return[{},r,e+3]}function _n(t,e){const n=t[e]?nt.create(t[e]):null;return[{},n,e+1]}const Xl=RegExp(`^T?${ir.source}$`),ec=/^-?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 tc(t){const[e,n,s,r,i,o,a,l,c]=t,d=e[0]==="-",h=l&&l[0]==="-",u=(f,g=!1)=>f!==void 0&&(g||f&&d)?-f:f;return[{years:u(yt(n)),months:u(yt(s)),weeks:u(yt(r)),days:u(yt(i)),hours:u(yt(o)),minutes:u(yt(a)),seconds:u(yt(l),l==="-0"),milliseconds:u(sr(c),h)}]}const nc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ar(t,e,n,s,r,i,o){const a={year:e.length===2?Bs(ot(e)):ot(e),month:po.indexOf(n)+1,day:ot(s),hour:ot(r),minute:ot(i)};return o&&(a.second=ot(o)),t&&(a.weekday=t.length>3?go.indexOf(t)+1:wo.indexOf(t)+1),a}const sc=/^(?:(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 rc(t){const[,e,n,s,r,i,o,a,l,c,d,h]=t,u=ar(e,r,s,n,i,o,a);let f;return l?f=nc[l]:c?f=0:f=is(d,h),[u,new Oe(f)]}function ic(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const oc=/^(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$/,ac=/^(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$/,lc=/^(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 ei(t){const[,e,n,s,r,i,o,a]=t;return[ar(e,r,s,n,i,o,a),Oe.utcInstance]}function cc(t){const[,e,n,s,r,i,o,a]=t;return[ar(e,a,n,s,r,i,o),Oe.utcInstance]}const uc=qt(ql,or),dc=qt(Bl,or),fc=qt(Hl,or),hc=qt(To),Ro=Bt(Kl,Gt,wn,_n),mc=Bt(Gl,Gt,wn,_n),pc=Bt(Yl,Gt,wn,_n),yc=Bt(Gt,wn,_n);function gc(t){return Ht(t,[uc,Ro],[dc,mc],[fc,pc],[hc,yc])}function wc(t){return Ht(ic(t),[sc,rc])}function _c(t){return Ht(t,[oc,ei],[ac,ei],[lc,cc])}function Ec(t){return Ht(t,[ec,tc])}const vc=Bt(Gt);function Oc(t){return Ht(t,[Xl,vc])}const kc=qt(Jl,Ql),bc=qt(So),Tc=Bt(Gt,wn,_n);function Sc(t){return Ht(t,[kc,Ro],[bc,Tc])}const ti="Invalid Duration",Io={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}},Rc={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},...Io},Ce=146097/400,At=146097/4800,Ic={years:{quarters:4,months:12,weeks:Ce/7,days:Ce,hours:Ce*24,minutes:Ce*24*60,seconds:Ce*24*60*60,milliseconds:Ce*24*60*60*1e3},quarters:{months:3,weeks:Ce/28,days:Ce/4,hours:Ce*24/4,minutes:Ce*24*60/4,seconds:Ce*24*60*60/4,milliseconds:Ce*24*60*60*1e3/4},months:{weeks:At/7,days:At,hours:At*24,minutes:At*24*60,seconds:At*24*60*60,milliseconds:At*24*60*60*1e3},...Io},Ot=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],xc=Ot.slice(0).reverse();function Ke(t,e,n=!1){const s={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new ne(s)}function xo(t,e){let n=e.milliseconds??0;for(const s of xc.slice(1))e[s]&&(n+=e[s]*t[s].milliseconds);return n}function ni(t,e){const n=xo(t,e)<0?-1:1;Ot.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*n,o=t[r][s],a=Math.floor(i/o);e[r]+=a*n,e[s]-=a*o*n}return r},null),Ot.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*t[s][r]}return r},null)}function si(t){const e={};for(const[n,s]of Object.entries(t))s!==0&&(e[n]=s);return e}class ne{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;let s=n?Ic:Rc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||ie.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,n){return ne.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new _e(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ne({values:Jn(e,ne.normalizeUnit),loc:ie.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(dt(e))return ne.fromMillis(e);if(ne.isDuration(e))return e;if(typeof e=="object")return ne.fromObject(e);throw new _e(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[s]=Ec(e);return s?ne.fromObject(s,n):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[s]=Oc(e);return s?ne.fromObject(s,n):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new _e("need to specify a reason the Duration is invalid");const s=e instanceof Ve?e:new Ve(e,n);if(he.throwOnInvalid)throw new tl(s);return new ne({invalid:s})}static normalizeUnit(e){const n={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(!n)throw new Mi(e);return n}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,n={}){const s={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?Ee.create(this.loc,s).formatDurationFromString(this,e):ti}toHuman(e={}){if(!this.isValid)return ti;const n=e.showZeros!==!1,s=Ot.map(r=>{const i=this.values[r];return G(i)||i===0&&!n?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+=rr(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},j.fromMillis(n,{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?xo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e),s={};for(const r of Ot)(zt(n.values,r)||zt(this.values,r))&&(s[r]=n.get(r)+this.get(r));return Ke(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const s of Object.keys(this.values))n[s]=mo(e(this.values[s],s));return Ke(this,{values:n},!0)}get(e){return this[ne.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...Jn(e,ne.normalizeUnit)};return Ke(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:r,conversionAccuracy:s};return Ke(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return ni(this.matrix,e),Ke(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=si(this.normalize().shiftToAll().toObject());return Ke(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 n={},s={},r=this.toObject();let i;for(const o of Ot)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;dt(r[o])&&(a+=r[o]);const l=Math.trunc(a);n[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else dt(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(n[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return ni(this.matrix,n),Ke(this,{values:n},!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 n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return Ke(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=si(this.values);return Ke(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 n(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of Ot)if(!n(this.values[s],e.values[s]))return!1;return!0}}const Dt="Invalid Interval";function Nc(t,e){return!t||!t.isValid?fe.invalid("missing or invalid start"):!e||!e.isValid?fe.invalid("missing or invalid end"):e<t?fe.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}class fe{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new _e("need to specify a reason the Interval is invalid");const s=e instanceof Ve?e:new Ve(e,n);if(he.throwOnInvalid)throw new el(s);return new fe({invalid:s})}static fromDateTimes(e,n){const s=Qt(e),r=Qt(n),i=Nc(s,r);return i??new fe({start:s,end:r})}static after(e,n){const s=ne.fromDurationLike(n),r=Qt(e);return fe.fromDateTimes(r,r.plus(s))}static before(e,n){const s=ne.fromDurationLike(n),r=Qt(e);return fe.fromDateTimes(r.minus(s),r)}static fromISO(e,n){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=j.fromISO(s,n),o=i.isValid}catch{o=!1}let a,l;try{a=j.fromISO(r,n),l=a.isValid}catch{l=!1}if(o&&l)return fe.fromDateTimes(i,a);if(o){const c=ne.fromISO(r,n);if(c.isValid)return fe.after(i,c)}else if(l){const c=ne.fromISO(s,n);if(c.isValid)return fe.before(a,c)}}return fe.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",n){if(!this.isValid)return NaN;const s=this.start.startOf(e,n);let r;return n?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,n),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:n}={}){return this.isValid?fe.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(Qt).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=n[i]||this.e,a=+o>+this.e?this.e:o;s.push(fe.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const n=ne.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(n.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(fe.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 n=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return n>=s?null:fe.fromDateTimes(n,s)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return fe.fromDateTimes(n,s)}static merge(e){const[n,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&&n.push(s),n}static xor(e){let n=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?n=l.time:(n&&+n!=+l.time&&r.push(fe.fromDateTimes(n,l.time)),n=null);return fe.merge(r)}difference(...e){return fe.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Dt}[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=Hn,n={}){return this.isValid?Ee.create(this.s.loc.clone(n),e).formatInterval(this):Dt}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Dt}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Dt}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Dt}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:Dt}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):ne.invalid(this.invalidReason)}mapEndpoints(e){return fe.fromDateTimes(e(this.s),e(this.e))}}class Tn{static hasDST(e=he.defaultZone){const n=j.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return nt.isValidZone(e)}static normalizeZone(e){return at(e,he.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(n,s,i)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(n,s,i)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(n,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(n,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ie.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return ie.create(n,null,"gregory").eras(e)}static features(){return{relative:uo(),localeWeek:fo()}}}function ri(t,e){const n=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=n(e)-n(t);return Math.floor(ne.fromMillis(s).as("days"))}function Ac(t,e,n){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const d=ri(l,c);return(d-d%7)/7}],["days",ri]],r={},i=t;let o,a;for(const[l,c]of s)n.indexOf(l)>=0&&(o=l,r[l]=c(t,e),a=i.plus(r),a>e?(r[l]--,t=i.plus(r),t>e&&(a=t,r[l]--,t=i.plus(r))):t=a);return[t,r,a,o]}function Dc(t,e,n,s){let[r,i,o,a]=Ac(t,e,n);const l=e-r,c=n.filter(h=>["hours","minutes","seconds","milliseconds"].indexOf(h)>=0);c.length===0&&(o<e&&(o=r.plus({[a]:1})),o!==r&&(i[a]=(i[a]||0)+l/(o-r)));const d=ne.fromObject(i,s);return c.length>0?ne.fromMillis(l,s).shiftTo(...c).plus(d):d}const Cc="missing Intl.DateTimeFormat.formatToParts support";function re(t,e=n=>n){return{regex:t,deser:([n])=>e(kl(n))}}const Fc=" ",No=`[ ${Fc}]`,Ao=new RegExp(No,"g");function $c(t){return t.replace(/\./g,"\\.?").replace(Ao,No)}function ii(t){return t.replace(/\./g,"").replace(Ao," ").toLowerCase()}function Le(t,e){return t===null?null:{regex:RegExp(t.map($c).join("|")),deser:([n])=>t.findIndex(s=>ii(n)===ii(s))+e}}function oi(t,e){return{regex:t,deser:([,n,s])=>is(n,s),groups:e}}function Sn(t){return{regex:t,deser:([e])=>e}}function Mc(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Pc(t,e){const n=Pe(e),s=Pe(e,"{2}"),r=Pe(e,"{3}"),i=Pe(e,"{4}"),o=Pe(e,"{6}"),a=Pe(e,"{1,2}"),l=Pe(e,"{1,3}"),c=Pe(e,"{1,6}"),d=Pe(e,"{1,9}"),h=Pe(e,"{2,4}"),u=Pe(e,"{4,6}"),f=m=>({regex:RegExp(Mc(m.val)),deser:([E])=>E,literal:!0}),T=(m=>{if(t.literal)return f(m);switch(m.val){case"G":return Le(e.eras("short"),0);case"GG":return Le(e.eras("long"),0);case"y":return re(c);case"yy":return re(h,Bs);case"yyyy":return re(i);case"yyyyy":return re(u);case"yyyyyy":return re(o);case"M":return re(a);case"MM":return re(s);case"MMM":return Le(e.months("short",!0),1);case"MMMM":return Le(e.months("long",!0),1);case"L":return re(a);case"LL":return re(s);case"LLL":return Le(e.months("short",!1),1);case"LLLL":return Le(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 Sn(d);case"uu":return Sn(a);case"uuu":return re(n);case"a":return Le(e.meridiems(),0);case"kkkk":return re(i);case"kk":return re(h,Bs);case"W":return re(a);case"WW":return re(s);case"E":case"c":return re(n);case"EEE":return Le(e.weekdays("short",!1),1);case"EEEE":return Le(e.weekdays("long",!1),1);case"ccc":return Le(e.weekdays("short",!0),1);case"cccc":return Le(e.weekdays("long",!0),1);case"Z":case"ZZ":return oi(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return oi(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return Sn(/[a-z_+-/]{1,256}?/i);case" ":return Sn(/[^\S\n\r]/);default:return f(m)}})(t)||{invalidReason:Cc};return T.token=t,T}const Lc={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(t,e,n){const{type:s,value:r}=t;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=n.hour12?"hour12":"hour24");let a=Lc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Uc(t){return[`^${t.map(n=>n.regex).reduce((n,s)=>`${n}(${s.source})`,"")}$`,t]}function Wc(t,e,n){const s=t.match(e);if(s){const r={};let i=1;for(const o in n)if(zt(n,o)){const a=n[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 jc(t){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 n=null,s;return G(t.z)||(n=nt.create(t.z)),G(t.Z)||(n||(n=new Oe(t.Z)),s=t.Z),G(t.q)||(t.M=(t.q-1)*3+1),G(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),G(t.u)||(t.S=sr(t.u)),[Object.keys(t).reduce((i,o)=>{const a=e(o);return a&&(i[a]=t[o]),i},{}),n,s]}let ws=null;function Zc(){return ws||(ws=j.fromMillis(1555555555555)),ws}function zc(t,e){if(t.literal)return t;const n=Ee.macroTokenToFormatOpts(t.val),s=$o(n,e);return s==null||s.includes(void 0)?t:s}function Do(t,e){return Array.prototype.concat(...t.map(n=>zc(n,e)))}class Co{constructor(e,n){if(this.locale=e,this.format=n,this.tokens=Do(Ee.parseFormat(n),e),this.units=this.tokens.map(s=>Pc(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Uc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[n,s]=Wc(e,this.regex,this.handlers),[r,i,o]=s?jc(s):[null,null,void 0];if(zt(s,"a")&&zt(s,"H"))throw new $t("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:n,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 Fo(t,e,n){return new Co(t,n).explainFromTokens(e)}function qc(t,e,n){const{result:s,zone:r,specificOffset:i,invalidReason:o}=Fo(t,e,n);return[s,r,i,o]}function $o(t,e){if(!t)return null;const s=Ee.create(e,t).dtFormatter(Zc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Vc(o,t,i))}const _s="Invalid DateTime",ai=864e13;function tn(t){return new Ve("unsupported zone",`the zone "${t.name}" is not supported`)}function Es(t){return t.weekData===null&&(t.weekData=Gn(t.c)),t.weekData}function vs(t){return t.localWeekData===null&&(t.localWeekData=Gn(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function gt(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new j({...n,...e,old:n})}function Mo(t,e,n){let s=t-e*60*1e3;const r=n.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=n.offset(s);return r===i?[s,r]:[t-Math.min(r,i)*60*1e3,Math.max(r,i)]}function Rn(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function An(t,e,n){return Mo(rs(t),e,n)}function li(t,e){const n=t.o,s=t.c.year+Math.trunc(e.years),r=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...t.c,year:s,month:r,day:Math.min(t.c.day,Yn(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=rs(i);let[l,c]=Mo(a,n,t.zone);return o!==0&&(l+=o,c=t.zone.offset(l)),{ts:l,o:c}}function Ct(t,e,n,s,r,i){const{setZone:o,zone:a}=n;if(t&&Object.keys(t).length!==0||e){const l=e||a,c=j.fromObject(t,{...n,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return j.invalid(new Ve("unparsable",`the input "${r}" can't be parsed as ${s}`))}function In(t,e,n=!0){return t.isValid?Ee.create(ie.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function Os(t,e,n){const s=t.c.year>9999||t.c.year<0;let r="";if(s&&t.c.year>=0&&(r+="+"),r+=ye(t.c.year,s?6:4),n==="year")return r;if(e){if(r+="-",r+=ye(t.c.month),n==="month")return r;r+="-"}else if(r+=ye(t.c.month),n==="month")return r;return r+=ye(t.c.day),r}function ci(t,e,n,s,r,i,o){let a=!n||t.c.millisecond!==0||t.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=ye(t.c.hour),o==="hour")break;if(e){if(l+=":",l+=ye(t.c.minute),o==="minute")break;a&&(l+=":",l+=ye(t.c.second))}else{if(l+=ye(t.c.minute),o==="minute")break;a&&(l+=ye(t.c.second))}if(o==="second")break;a&&(!s||t.c.millisecond!==0)&&(l+=".",l+=ye(t.c.millisecond,3))}return r&&(t.isOffsetFixed&&t.offset===0&&!i?l+="Z":t.o<0?(l+="-",l+=ye(Math.trunc(-t.o/60)),l+=":",l+=ye(Math.trunc(-t.o%60))):(l+="+",l+=ye(Math.trunc(t.o/60)),l+=":",l+=ye(Math.trunc(t.o%60)))),i&&(l+="["+t.zone.ianaName+"]"),l}const Po={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Bc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Hc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Dn=["year","month","day","hour","minute","second","millisecond"],Gc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Yc=["year","ordinal","hour","minute","second","millisecond"];function Cn(t){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"}[t.toLowerCase()];if(!e)throw new Mi(t);return e}function ui(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Cn(t)}}function Jc(t){if(nn===void 0&&(nn=he.now()),t.type!=="iana")return t.offset(nn);const e=t.name;let n=Hs.get(e);return n===void 0&&(n=t.offset(nn),Hs.set(e,n)),n}function di(t,e){const n=at(e.zone,he.defaultZone);if(!n.isValid)return j.invalid(tn(n));const s=ie.fromObject(e);let r,i;if(G(t.year))r=he.now();else{for(const l of Dn)G(t[l])&&(t[l]=Po[l]);const o=lo(t)||co(t);if(o)return j.invalid(o);const a=Jc(n);[r,i]=An(t,a,n)}return new j({ts:r,zone:n,loc:s,o:i})}function fi(t,e,n){const s=G(n.round)?!0:n.round,r=G(n.rounding)?"trunc":n.rounding,i=(a,l)=>(a=rr(a,s||n.calendary?0:2,n.calendary?"round":r),e.loc.clone(n).relFormatter(n).format(a,l)),o=a=>n.calendary?e.hasSame(t,a)?0:e.startOf(a).diff(t.startOf(a),a).get(a):e.diff(t,a).get(a);if(n.unit)return i(o(n.unit),n.unit);for(const a of n.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(t>e?-0:0,n.units[n.units.length-1])}function hi(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}let nn;const Hs=new Map;class j{constructor(e){const n=e.zone||he.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Ve("invalid input"):null)||(n.isValid?null:tn(n));this.ts=G(e.ts)?he.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[r,i]=[e.old.c,e.old.o];else{const a=dt(e.o)&&!e.old?e.o:n.offset(this.ts);r=Rn(this.ts,a),s=Number.isNaN(r.year)?new Ve("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=n,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 j({})}static local(){const[e,n]=hi(arguments),[s,r,i,o,a,l,c]=n;return di({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,n]=hi(arguments),[s,r,i,o,a,l,c]=n;return e.zone=Oe.utcInstance,di({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,n={}){const s=Il(e)?e.valueOf():NaN;if(Number.isNaN(s))return j.invalid("invalid input");const r=at(n.zone,he.defaultZone);return r.isValid?new j({ts:s,zone:r,loc:ie.fromObject(n)}):j.invalid(tn(r))}static fromMillis(e,n={}){if(dt(e))return e<-ai||e>ai?j.invalid("Timestamp out of range"):new j({ts:e,zone:at(n.zone,he.defaultZone),loc:ie.fromObject(n)});throw new _e(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(dt(e))return new j({ts:e*1e3,zone:at(n.zone,he.defaultZone),loc:ie.fromObject(n)});throw new _e("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const s=at(n.zone,he.defaultZone);if(!s.isValid)return j.invalid(tn(s));const r=ie.fromObject(n),i=Jn(e,ui),{minDaysInFirstWeek:o,startOfWeek:a}=Jr(i,r),l=he.now(),c=G(n.specificOffset)?s.offset(l):n.specificOffset,d=!G(i.ordinal),h=!G(i.year),u=!G(i.month)||!G(i.day),f=h||u,g=i.weekYear||i.weekNumber;if((f||d)&&g)throw new $t("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new $t("Can't mix ordinal dates with month/day");const T=g||i.weekday&&!f;let m,E,w=Rn(l,c);T?(m=Gc,E=Bc,w=Gn(w,o,a)):d?(m=Yc,E=Hc,w=gs(w)):(m=Dn,E=Po);let x=!1;for(const R of m){const p=i[R];G(p)?x?i[R]=E[R]:i[R]=w[R]:x=!0}const k=T?Tl(i,o,a):d?Sl(i):lo(i),v=k||co(i);if(v)return j.invalid(v);const N=T?Gr(i,o,a):d?Yr(i):i,[W,O]=An(N,c,s),H=new j({ts:W,zone:s,o:O,loc:r});return i.weekday&&f&&e.weekday!==H.weekday?j.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${H.toISO()}`):H.isValid?H:j.invalid(H.invalid)}static fromISO(e,n={}){const[s,r]=gc(e);return Ct(s,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[s,r]=wc(e);return Ct(s,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[s,r]=_c(e);return Ct(s,r,n,"HTTP",n)}static fromFormat(e,n,s={}){if(G(e)||G(n))throw new _e("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,d]=qc(o,e,n);return d?j.invalid(d):Ct(a,l,s,`format ${n}`,e,c)}static fromString(e,n,s={}){return j.fromFormat(e,n,s)}static fromSQL(e,n={}){const[s,r]=Sc(e);return Ct(s,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new _e("need to specify a reason the DateTime is invalid");const s=e instanceof Ve?e:new Ve(e,n);if(he.throwOnInvalid)throw new Xa(s);return new j({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){const s=$o(e,ie.fromObject(n));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return Do(Ee.parseFormat(e),ie.fromObject(n)).map(r=>r.val).join("")}static resetCache(){nn=void 0,Hs.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?Es(this).weekYear:NaN}get weekNumber(){return this.isValid?Es(this).weekNumber:NaN}get weekday(){return this.isValid?Es(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?vs(this).weekday:NaN}get localWeekNumber(){return this.isValid?vs(this).weekNumber:NaN}get localWeekYear(){return this.isValid?vs(this).weekYear:NaN}get ordinal(){return this.isValid?gs(this.c).ordinal:NaN}get monthShort(){return this.isValid?Tn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Tn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Tn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Tn.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,n=6e4,s=rs(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*n),a=this.zone.offset(s-i*n);if(o===a)return[this];const l=s-o*n,c=s-a*n,d=Rn(l,o),h=Rn(c,a);return d.hour===h.hour&&d.minute===h.minute&&d.second===h.second&&d.millisecond===h.millisecond?[gt(this,{ts:l}),gt(this,{ts:c})]:[this]}get isInLeapYear(){return gn(this.year)}get daysInMonth(){return Yn(this.year,this.month)}get daysInYear(){return this.isValid?Pt(this.year):NaN}get weeksInWeekYear(){return this.isValid?fn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?fn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:s,calendar:r}=Ee.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:s,outputCalendar:r}}toUTC(e=0,n={}){return this.setZone(Oe.instance(e),n)}toLocal(){return this.setZone(he.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:s=!1}={}){if(e=at(e,he.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(n||s){const i=e.offset(this.ts),o=this.toObject();[r]=An(o,i,e)}return gt(this,{ts:r,zone:e})}else return j.invalid(tn(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:s});return gt(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=Jn(e,ui),{minDaysInFirstWeek:s,startOfWeek:r}=Jr(n,this.loc),i=!G(n.weekYear)||!G(n.weekNumber)||!G(n.weekday),o=!G(n.ordinal),a=!G(n.year),l=!G(n.month)||!G(n.day),c=a||l,d=n.weekYear||n.weekNumber;if((c||o)&&d)throw new $t("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new $t("Can't mix ordinal dates with month/day");let h;i?h=Gr({...Gn(this.c,s,r),...n},s,r):G(n.ordinal)?(h={...this.toObject(),...n},G(n.day)&&(h.day=Math.min(Yn(h.year,h.month),h.day))):h=Yr({...gs(this.c),...n});const[u,f]=An(h,this.o,this.zone);return gt(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e);return gt(this,li(this,n))}minus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e).negate();return gt(this,li(this,n))}startOf(e,{useLocaleWeeks:n=!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(n){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,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?Ee.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):_s}toLocaleString(e=Hn,n={}){return this.isValid?Ee.create(this.loc.clone(n),e).formatDateTime(this):_s}toLocaleParts(e={}){return this.isValid?Ee.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=Cn(o);const a=e==="extended";let l=Os(this,a,o);return Dn.indexOf(o)>=3&&(l+="T"),l+=ci(this,a,n,s,r,i,o),l}toISODate({format:e="extended",precision:n="day"}={}){return this.isValid?Os(this,e==="extended",Cn(n)):null}toISOWeekDate(){return In(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=Cn(a),(r&&Dn.indexOf(a)>=3?"T":"")+ci(this,o==="extended",n,e,s,i,a)):null}toRFC2822(){return In(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return In(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Os(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(n||e)&&(s&&(r+=" "),n?r+="z":e&&(r+="ZZ")),In(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():_s}[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 n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="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=xl(n).map(ne.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=Dc(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",n={}){return this.diff(j.now(),e,n)}until(e){return this.isValid?fe.fromDateTimes(this,e):this}hasSame(e,n,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n,s)<=r&&r<=i.endOf(n,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 n=e.base||j.fromObject({},{zone:this.zone}),s=e.padding?this<n?-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),fi(n,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?fi(e.base||j.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(j.isDateTime))throw new _e("min requires all arguments be DateTimes");return Qr(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(j.isDateTime))throw new _e("max requires all arguments be DateTimes");return Qr(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return Fo(o,e,n)}static fromStringExplain(e,n,s={}){return j.fromFormatExplain(e,n,s)}static buildFormatParser(e,n={}){const{locale:s=null,numberingSystem:r=null}=n,i=ie.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new Co(i,e)}static fromFormatParser(e,n,s={}){if(G(e)||G(n))throw new _e("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(n.locale))throw new _e(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${n.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=n.explainFromTokens(e);return d?j.invalid(d):Ct(a,l,s,`format ${n.format}`,e,c)}static get DATE_SHORT(){return Hn}static get DATE_MED(){return Pi}static get DATE_MED_WITH_WEEKDAY(){return nl}static get DATE_FULL(){return Li}static get DATE_HUGE(){return Vi}static get TIME_SIMPLE(){return Ui}static get TIME_WITH_SECONDS(){return Wi}static get TIME_WITH_SHORT_OFFSET(){return ji}static get TIME_WITH_LONG_OFFSET(){return Zi}static get TIME_24_SIMPLE(){return zi}static get TIME_24_WITH_SECONDS(){return qi}static get TIME_24_WITH_SHORT_OFFSET(){return Bi}static get TIME_24_WITH_LONG_OFFSET(){return Hi}static get DATETIME_SHORT(){return Gi}static get DATETIME_SHORT_WITH_SECONDS(){return Yi}static get DATETIME_MED(){return Ji}static get DATETIME_MED_WITH_SECONDS(){return Qi}static get DATETIME_MED_WITH_WEEKDAY(){return sl}static get DATETIME_FULL(){return Ki}static get DATETIME_FULL_WITH_SECONDS(){return Xi}static get DATETIME_HUGE(){return eo}static get DATETIME_HUGE_WITH_SECONDS(){return to}}function Qt(t){if(j.isDateTime(t))return t;if(t&&t.valueOf&&dt(t.valueOf()))return j.fromJSDate(t);if(t&&typeof t=="object")return j.fromObject(t);throw new _e(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const Qc=(t,e)=>{const n={};if(t.includeFields){const s=e.collections[t.collection];if(!s)return pn(we());t.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?n[r]=Lo(i)?.nullable():n[r]=we()})}return qe({Collection_Path:It(Re()),...n})},Kc=(t,e,n,s)=>{let r=qe({}).catchall(Qc(t,e)),i;if(!s&&n){const o=Ue(t,n);i=Kt(o.admin?.skipFormRequiredValidation)}return(!t.required||i)&&(r=r.optional()),r},Xc=()=>we().refine(t=>t===null||t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Must be a valid date"}),Lo=(t,e,n)=>{let s;const r=`${Kt(t.description)}
2
2
 
3
- `||"";let i,o,a;if(!n&&e){const l=Ce(t,e);i=l.admin?.condition?.form!==void 0&&!Gt(l.admin.condition.form),o=Gt(l.admin?.skipFormRequiredValidation),a=Gt(l.admin?.image)}switch(t.type){case"String":s=Se(),t.length&&(s=s.length(t.length,`Must be ${t.length} character(s) long`)),t.minlength&&(s=s.min(t.minlength,`Must contain at least ${t.minlength} character(s)`)),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} character(s)`)),t.email?s=s.email("Must be a valid email address"):t.uuid?s=ke([s.uuid("Must be a valid UUID"),be("")]):t.url?s=ke([s.url("Must be a valid URL"),be("")]):t.emoji?s=ke([s.emoji("Must be a valid emoji"),be("")]):t.ip?s=ke([s.ip("Must be a valid IP address"),be("")]):t.pattern&&(!n&&a?s=ke([s.regex(new RegExp(t.pattern)),s.regex(/^blob:/)],{message:"Must be a valid value"}):s=s.regex(new RegExp(t.pattern),"Must be a valid value")),t.values&&(s=ke([Mn(t.values,{message:`Must be one of the following values: ${t.values.join(", ")}`}),rs()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=tn(),r&&(s=s.describe(r.trim()));break;case"Number":t.autoIncrement?s=ke([rs(),yt().int()],{message:"Must be a valid number"}):(s=yt({message:"Must be a valid number"}),t.min&&(s=s.min(t.min,`Must be greater than or equal to ${t.min}`)),t.max&&(s=s.max(t.max,`Must be less than or equal to ${t.max}`)),t.decimal?n?s=s.describe(`${r}Must have ${t.decimal} decimal places`):s=s.refine(l=>t.decimal?(l.toString().split(".")[1]?.length||0)<=t.decimal:!1,{message:`Must have ${t.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),t.values?(n||(s=ke([s.refine(l=>t.values?.includes(l),{message:`Must be one of the following values: ${t.values.join(", ")}`}),rs()])),s=s.describe(`${r}Must be one of the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":n?(s=je({seconds:yt(),nanoseconds:yt()}),t.min&&t.max?s=s.describe(`${r}Must be between ${L.fromMillis(t.min).toLocaleString(L.DATE_MED)} and ${L.fromMillis(t.max).toLocaleString(L.DATE_MED)}`):t.min?s=s.describe(`${r}Must be greater than or equal to ${L.fromMillis(t.min).toLocaleString(L.DATE_MED)}`):t.max?s=s.describe(`${r}Must be less than or equal to ${L.fromMillis(t.max).toLocaleString(L.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Wc(),t.min&&(s=s.refine(l=>l.toMillis()>=t.min,{message:`Must be greater than or equal to ${L.fromMillis(t.min).toLocaleString(L.DATE_MED)}`})),t.max&&(s=s.refine(l=>l.toMillis()<=t.max,{message:`Must be less than or equal to ${L.fromMillis(t.max).toLocaleString(L.DATE_MED)}`})));break;case"Array":s=bt(pe()),t.length&&(s=s.length(t.length,`Must contain ${t.length} item(s)`)),t.minlength?s=s.min(t.minlength,`Must contain at least ${t.minlength} item(s)`):t.required&&!i&&(s=s.nonempty("Must contain at least one item")),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} item(s)`)),t.values?(n||(s=s.refine(l=>{let c=!0;return l.forEach(d=>{t.values&&!t.values.includes(d)&&(c=!1)}),c},{message:`Must only contain the following values: ${t.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())),t.nullable&&(s=s.nullable());break;case"Map":t.required&&!i?n?s=je({}).catchall(pe()).describe(`${r}Must be an object. Must contain at least one object property.`):s=ln(pe()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=je({}).catchall(pe()).describe(`${r}Must be an object`);break;case"Computed":s=pe()}return(!t.required||i||o)&&(s=s.optional()),s},jc=(t,e,n,s,r)=>{const{auth:i,softDelete:o}=t,a={};t.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(X(c)?(a[c.name]=Uc(c,e,n,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=xo(c,n,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=ke([be("create"),be("update"),be("delete")]).optional(),a.password=Se().optional(),a.passwordConfirm=Se().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=tn().optional(),a[`operations-${c.labels.collection}`]=bt(ke([be("Read"),be("Create"),be("Update"),be("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=tn().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=tn().optional()}),c.access.entityRestrictions?.restrictions?.forEach(d=>{if(d.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=je({}).catchall(pe()).optional()),d.type==="Parent"||d.type==="Parent_Property"){const m=U(c.fields,d.collectionField);a[`accessible-${c.labels.collection}-${m.collection}`]=je({}).catchall(pe()).optional()}})}));const l=je(a);return t.allowSchemalessFields?l.passthrough():l.strict()},ii=async(t,e)=>{if(t){const n=await oe(t,[e]);if(!n.valid)throw new Error(n.message)}},an=async(t,e,n,s,r,i)=>{await ii(s.custom?.preValidate,r);for(const a of s.fields)await ii(a.custom?.preValidate,r);return Si(t,n,i).parse(e),e},Ks=(t,e,n,s,r,i,o,a,l,c,d,m,u,f,g,v,y,w,R,O,I)=>{const{fields:E}=o;E.filter(p=>"unique"in p&&p.unique).forEach(p=>{t!=="delete"&&(typeof r[p.name]=="string"||typeof r[p.name]=="number")&&(e.set(f(p,r[p.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:n}),I&&I.size++)}),E.forEach(p=>{if(dt(p,o,i)){const F=mn(p,o,i),A={};r[p.name]!==void 0&&(A[p.name]=r[p.name],X(p)&&(A[`${p.name}_Array`]=r[`${p.name}_Array`])),F.forEach(j=>{r[j.name]!==void 0&&(X(j)?A[`${j.name}_Array`]=r[`${j.name}_Array`]:A[j.name]=r[j.name])}),Object.keys(A).length>0&&(t==="create"&&(A.Collection_Path=n,A.Collection_Path_String=n.join("/"),e.set(u(p),A)),t==="update"&&e.update(u(p),A),t==="delete"&&e.delete(u(p)),I&&I.size++)}});const C=l[o.labels.collection];for(const p of C){const F=ua(p,o),A={...r};F.forEach(j=>{delete A[j.name],delete A[`${j.name}_Array`],delete A[`${j.name}_Single`],delete A[`${j.name}_Lowercase`]}),Object.keys(A).length>0&&(t==="create"&&(A.Collection_Path||=n,A.Collection_Path_String=n.join("/"),e.set(g(p.key),A)),t==="update"&&e.update(g(p.key),A),t==="delete"&&e.delete(g(p.key)),I&&I.size++)}const _=(p,F)=>{let A=1;dt(F,p,i)&&A++,p.fields.forEach(h=>{dt(h,p,i)&&JSON.parse(ts(mn(h,p,i))).includes(F.name)&&A++});const j=l[p.labels.collection];for(const h of j)h.fields.some(S=>S.name===F.name)&&X(F)&&A++;return A},Z=(p,F,A,j,h)=>{const S={};S[`${A.name}.${s}`]=m(),S[`${A.name}_Array`]=d(s),S[`${A.name}_Single`]=m(),e.update(v(h,j),S),dt(A,F,i)&&e.update(y(p,A.name,j),{[`${A.name}.${s}`]:m(),[`${A.name}_Array`]:d(s)}),F.fields.forEach(T=>{dt(T,F,i)&&JSON.parse(ts(mn(T,F,i))).includes(A.name)&&e.update(y(p,T.name,j),{[`${A.name}_Array`]:d(s)})});const b=l[F.labels.collection];for(const T of b)T.fields.some(N=>N.name===A.name)&&X(A)&&e.update(w(p,T.key,j),S)};if(t==="delete")return;const k=E.filter(p=>X(p)&&p.twoWay);if(!a?.noTwoWay){for(const p of k){if(!I)throw new Error("VALIDATION_ERROR: batchSize is required");const F=i.collections[p.collection],A=U(F.fields,p.twoWay),j=mt(F,F.fields),h=Array.from(j).map(S=>S.name);if(!A)throw new Error(`SCHEMA_ERROR: Field ${p.twoWay} not found in collection ${p.collection}`);if(X(A)){if(r[`${p.name}_Array`])for(const[S,b]of Object.entries(r[p.name])){if(t==="update"&&R&&R[`${p.name}_Array`]?.includes(S))continue;const T={...R,...r};it(T);const N={};A.includeFields&&A.includeFields.forEach(z=>{if(T[z]!==void 0){N[z]=T[z];const x=U(o.fields,z);kt(o,[x]).size===1&&(N[`${z}_Lowercase`]=T[`${z}_Lowercase`])}});const q={[`${p.twoWay}.${s}`]:{Collection_Path:n,...N},[`${p.twoWay}_Array`]:c(s)};h.includes(A.name)&&(q[`${p.twoWay}_Single`]={Collection_Path:n,id:s,...N});const M=In(r);e.update(v(b.Collection_Path,S),{...q,...M}),I.size++,dt(A,F,i)&&(e.update(y(p,A.name,S),{[`${A.name}.${s}`]:{Collection_Path:n,...N},[`${A.name}_Array`]:c(s)}),I.size++),F.fields.forEach(z=>{if(dt(z,F,i)){const x=JSON.parse(ts(mn(z,F,i))),Q={};x.includes(A.name)&&(Q[`${p.twoWay}_Array`]=c(s)),Object.keys(M).forEach(B=>{x.includes(B)&&(Q[B]=M[B])}),Object.keys(Q).length>0&&(e.update(y(p,z.name,S),Q),I.size++)}});const G=l[F.labels.collection];for(const z of G)if(z.fields.some(x=>x.name===A.name)){const x={...q};Object.keys(M).forEach(Q=>{z.fields.some(B=>B.name===Q)&&(x[Q]=M[Q])}),Object.keys(x).length>0&&(e.update(w(p,z.key,S),x),I.size++)}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${A.type}`)}I&&I.size>500&&console.error(new Error(`VALIDATION_ERROR: ${I.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 p of k){if(!I)throw new Error("VALIDATION_ERROR: batchSize is required");const F=i.collections[p.collection],A=U(F.fields,p.twoWay);if(!A)throw new Error(`SCHEMA_ERROR: Field ${p.twoWay} not found in collection ${p.collection}`);if(X(A)){if(t==="update"&&R&&!(r[p.name]&&Te(r[p.name]))&&r[`${p.name}_Array`]&&R[`${p.name}_Array`]?.length>0)for(const[j,h]of Object.entries(R[p.name]))!r[`${p.name}_Array`].includes(j)&&!O?.get(p.name)?.includes(j)&&(I.size+=_(F,A),I.size<=500&&Z(p,F,A,j,h.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${A.type}`)}for(const p of k){if(!I)throw new Error("VALIDATION_ERROR: batchSize is required");const F=i.collections[p.collection],A=U(F.fields,p.twoWay);if(!A)throw new Error(`SCHEMA_ERROR: Field ${p.twoWay} not found in collection ${p.collection}`);if(X(A)){if(t==="update"&&R&&r[p.name]&&Te(r[p.name])&&R[`${p.name}_Array`]?.length>0)for(const[j,h]of Object.entries(R[p.name]))O?.get(p.name)?.includes(j)||(I.size+=_(F,A),I.size<=500&&Z(p,F,A,j,h.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${A.type}`)}}},Ue=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]===void 0?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&Ue(t[e]))},Xs=t=>{if(t=t.toString(),/[/]|^\.+$|^__.*__$/.test(t))return!1;try{const s=new TextEncoder().encode(t),r=new TextDecoder().decode(s);if(t!==r)return!1}catch{return!1}return!(new Blob([t]).size>1500)},oi=async(t,e,n,s=1e3,r=5)=>{for(;r>0;)try{await t(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},jn=t=>{if(!t||typeof t!="string")return"";let e=t.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},ms=t=>t?Array.isArray(t)?t.map(s=>jn(s)).filter(s=>s.length>0):jn(t)||"":"",zc=t=>{if(!t||typeof t!="string")return"";let e=t.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},ai=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
3
+ `||"";let i,o,a;if(!n&&e){const l=Ue(t,e);i=l.admin?.condition?.form!==void 0&&!Kt(l.admin.condition.form),o=Kt(l.admin?.skipFormRequiredValidation),a=Kt(l.admin?.image)}switch(t.type){case"String":s=Re(),t.length&&(s=s.length(t.length,`Must be ${t.length} character(s) long`)),t.minlength&&(s=s.min(t.minlength,`Must contain at least ${t.minlength} character(s)`)),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} character(s)`)),t.email?s=s.email("Must be a valid email address"):t.uuid?s=Te([s.uuid("Must be a valid UUID"),Se("")]):t.url?s=Te([s.url("Must be a valid URL"),Se("")]):t.emoji?s=Te([s.emoji("Must be a valid emoji"),Se("")]):t.ip?s=Te([s.ip("Must be a valid IP address"),Se("")]):t.pattern&&(!n&&a?s=Te([s.regex(new RegExp(t.pattern)),s.regex(/^blob:/)],{message:"Must be a valid value"}):s=s.regex(new RegExp(t.pattern),"Must be a valid value")),t.values&&(s=Te([qn(t.values,{message:`Must be one of the following values: ${t.values.join(", ")}`}),hs()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=an(),r&&(s=s.describe(r.trim()));break;case"Number":t.autoIncrement?s=Te([hs(),vt().int()],{message:"Must be a valid number"}):(s=vt({message:"Must be a valid number"}),t.min&&(s=s.min(t.min,`Must be greater than or equal to ${t.min}`)),t.max&&(s=s.max(t.max,`Must be less than or equal to ${t.max}`)),t.decimal?n?s=s.describe(`${r}Must have ${t.decimal} decimal places`):s=s.refine(l=>t.decimal?(l.toString().split(".")[1]?.length||0)<=t.decimal:!1,{message:`Must have ${t.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),t.values?(n||(s=Te([s.refine(l=>t.values?.includes(l),{message:`Must be one of the following values: ${t.values.join(", ")}`}),hs()])),s=s.describe(`${r}Must be one of the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":n?(s=qe({seconds:vt(),nanoseconds:vt()}),t.min&&t.max?s=s.describe(`${r}Must be between ${j.fromMillis(t.min).toLocaleString(j.DATE_MED)} and ${j.fromMillis(t.max).toLocaleString(j.DATE_MED)}`):t.min?s=s.describe(`${r}Must be greater than or equal to ${j.fromMillis(t.min).toLocaleString(j.DATE_MED)}`):t.max?s=s.describe(`${r}Must be less than or equal to ${j.fromMillis(t.max).toLocaleString(j.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Xc(),t.min&&(s=s.refine(l=>l.toMillis()>=t.min,{message:`Must be greater than or equal to ${j.fromMillis(t.min).toLocaleString(j.DATE_MED)}`})),t.max&&(s=s.refine(l=>l.toMillis()<=t.max,{message:`Must be less than or equal to ${j.fromMillis(t.max).toLocaleString(j.DATE_MED)}`})));break;case"Array":s=It(we()),t.length&&(s=s.length(t.length,`Must contain ${t.length} item(s)`)),t.minlength?s=s.min(t.minlength,`Must contain at least ${t.minlength} item(s)`):t.required&&!i&&(s=s.nonempty("Must contain at least one item")),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} item(s)`)),t.values?(n||(s=s.refine(l=>{let c=!0;return l.forEach(d=>{t.values&&!t.values.includes(d)&&(c=!1)}),c},{message:`Must only contain the following values: ${t.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())),t.nullable&&(s=s.nullable());break;case"Map":t.required&&!i?n?s=qe({}).catchall(we()).describe(`${r}Must be an object. Must contain at least one object property.`):s=pn(we()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=qe({}).catchall(we()).describe(`${r}Must be an object`);break;case"Computed":s=we()}return(!t.required||i||o)&&(s=s.optional()),s},eu=(t,e,n,s,r)=>{const{auth:i,softDelete:o}=t,a={};t.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(ee(c)?(a[c.name]=Kc(c,e,n,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=Lo(c,n,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=Te([Se("create"),Se("update"),Se("delete")]).optional(),a.password=Re().optional(),a.passwordConfirm=Re().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=an().optional(),a[`operations-${c.labels.collection}`]=It(Te([Se("Read"),Se("Create"),Se("Update"),Se("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=an().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=an().optional()}),c.access.entityRestrictions?.restrictions?.forEach(d=>{if(d.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=qe({}).catchall(we()).optional()),d.type==="Parent"||d.type==="Parent_Property"){const h=V(c.fields,d.collectionField);a[`accessible-${c.labels.collection}-${h.collection}`]=qe({}).catchall(we()).optional()}})}));const l=qe(a);return t.allowSchemalessFields?l.passthrough():l.strict()},mi=async(t,e)=>{if(t){const n=await ae(t,[e]);if(!n.valid)throw new Error(n.message)}},hn=async(t,e,n,s,r,i)=>{await mi(s.custom?.preValidate,r);for(const a of s.fields)await mi(a.custom?.preValidate,r);return $i(t,n,i).parse(e),e},lr=(t,e,n,s,r,i,o,a,l,c,d,h,u,f,g,T,m,E,w,x,k)=>{const{fields:v}=o;v.filter(p=>"unique"in p&&p.unique).forEach(p=>{t!=="delete"&&(typeof r[p.name]=="string"||typeof r[p.name]=="number")&&(e.set(f(p,r[p.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:n}),k&&k.size++)}),v.forEach(p=>{if(pt(p,o,i)){const C=On(p,o,i),I={};r[p.name]!==void 0&&(I[p.name]=r[p.name],ee(p)&&(I[`${p.name}_Array`]=r[`${p.name}_Array`])),C.forEach(P=>{r[P.name]!==void 0&&(ee(P)?I[`${P.name}_Array`]=r[`${P.name}_Array`]:I[P.name]=r[P.name])}),Object.keys(I).length>0&&(t==="create"&&(I.Collection_Path=n,I.Collection_Path_String=n.join("/"),e.set(u(p),I)),t==="update"&&e.update(u(p),I),t==="delete"&&e.delete(u(p)),k&&k.size++)}});const N=l[o.labels.collection],W=wt(o);Object.entries(W).forEach(([p,C])=>{if(C.length!==0)for(const I of N){const P=kn(p,o,I);if(P.length===0)continue;const y=on(p,I.key),_={};P.forEach(S=>{[S.name,`${S.name}_Array`,`${S.name}_Single`,`${S.name}_Lowercase`].forEach(F=>{r[F]!==void 0&&(_[F]=r[F])})}),t==="create"&&(_.Collection_Path||=n,_.Collection_Path_String=n.join("/"),e.set(g(y),_),k&&k.size++),t==="update"&&Object.keys(_).length>0&&(e.update(g(y),_),k&&k.size++),t==="delete"&&(e.delete(g(y)),k&&k.size++)}});for(const p of N){const C=Oa(p,o),I={...r};C.forEach(P=>{delete I[P.name],delete I[`${P.name}_Array`],delete I[`${P.name}_Single`],delete I[`${P.name}_Lowercase`]}),Object.keys(I).length>0&&(t==="create"&&(I.Collection_Path||=n,I.Collection_Path_String=n.join("/"),e.set(g(p.key),I)),t==="update"&&e.update(g(p.key),I),t==="delete"&&e.delete(g(p.key)),k&&k.size++)}const O=(p,C)=>{let I=1;pt(C,p,i)&&I++,p.fields.forEach(_=>{pt(_,p,i)&&JSON.parse(us(On(_,p,i))).includes(C.name)&&I++});const P=l[p.labels.collection];for(const _ of P)_.fields.some(S=>S.name===C.name)&&ee(C)&&I++;const y=wt(p);for(const[_,S]of Object.entries(y))if(S.length!==0)for(const U of P)kn(_,p,U).some(D=>D.name===C.name)&&ee(C)&&I++;return I},H=(p,C,I,P,y)=>{const _={};_[`${I.name}.${s}`]=h(),_[`${I.name}_Array`]=d(s),_[`${I.name}_Single`]=h(),e.update(T(y,P),_),pt(I,C,i)&&e.update(m(p,I.name,P),{[`${I.name}.${s}`]:h(),[`${I.name}_Array`]:d(s)}),C.fields.forEach(F=>{pt(F,C,i)&&JSON.parse(us(On(F,C,i))).includes(I.name)&&e.update(m(p,F.name,P),{[`${I.name}_Array`]:d(s)})});const S=l[C.labels.collection];for(const F of S)F.fields.some(D=>D.name===I.name)&&ee(I)&&e.update(E(p,F.key,P),_);const U=wt(C);for(const[F,D]of Object.entries(U))if(D.length!==0)for(const M of S){const J=kn(F,C,M),z=on(F,M.key);J.some(b=>b.name===I.name)&&ee(I)&&e.update(E(p,z,P),_)}};if(t==="delete")return;const R=v.filter(p=>ee(p)&&p.twoWay);if(!a?.noTwoWay){for(const p of R){if(!k)throw new Error("VALIDATION_ERROR: batchSize is required");const C=i.collections[p.collection],I=V(C.fields,p.twoWay),P=_t(C,C.fields),y=Array.from(P).map(_=>_.name);if(!I)throw new Error(`SCHEMA_ERROR: Field ${p.twoWay} not found in collection ${p.collection}`);if(ee(I)){if(r[`${p.name}_Array`])for(const[_,S]of Object.entries(r[p.name])){if(t==="update"&&w&&w[`${p.name}_Array`]?.includes(_))continue;const U={...w,...r};lt(U);const F={};I.includeFields&&I.includeFields.forEach(b=>{if(U[b]!==void 0){F[b]=U[b];const B=V(o.fields,b);Rt(o,[B]).size===1&&(F[`${b}_Lowercase`]=U[`${b}_Lowercase`])}});const D={[`${p.twoWay}.${s}`]:{Collection_Path:n,...F},[`${p.twoWay}_Array`]:c(s)};y.includes(I.name)&&(D[`${p.twoWay}_Single`]={Collection_Path:n,id:s,...F});const M=Pn(r);e.update(T(S.Collection_Path,_),{...D,...M}),k.size++,pt(I,C,i)&&(e.update(m(p,I.name,_),{[`${I.name}.${s}`]:{Collection_Path:n,...F},[`${I.name}_Array`]:c(s)}),k.size++),C.fields.forEach(b=>{if(pt(b,C,i)){const B=JSON.parse(us(On(b,C,i))),K={};B.includes(I.name)&&(K[`${p.twoWay}_Array`]=c(s)),Object.keys(M).forEach(ce=>{B.includes(ce)&&(K[ce]=M[ce])}),Object.keys(K).length>0&&(e.update(m(p,b.name,_),K),k.size++)}});const J=l[C.labels.collection];for(const b of J)if(b.fields.some(B=>B.name===I.name)){const B={...D};Object.keys(M).forEach(K=>{b.fields.some(ce=>ce.name===K)&&(B[K]=M[K])}),Object.keys(B).length>0&&(e.update(E(p,b.key,_),B),k.size++)}const z=wt(C);for(const[b,B]of Object.entries(z))if(B.length!==0)for(const K of J){const ce=kn(b,C,K),be=on(b,K.key);if(ce.some(le=>le.name===I.name)){const le={...D};Object.keys(M).forEach(ue=>{ce.some(De=>De.name===ue)&&(le[ue]=M[ue])}),Object.keys(le).length>0&&(e.update(E(p,be,_),le),k.size++)}}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${I.type}`)}k&&k.size>500&&console.error(new Error(`VALIDATION_ERROR: ${k.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 p of R){if(!k)throw new Error("VALIDATION_ERROR: batchSize is required");const C=i.collections[p.collection],I=V(C.fields,p.twoWay);if(!I)throw new Error(`SCHEMA_ERROR: Field ${p.twoWay} not found in collection ${p.collection}`);if(ee(I)){if(t==="update"&&w&&!(r[p.name]&&xe(r[p.name]))&&r[`${p.name}_Array`]&&w[`${p.name}_Array`]?.length>0)for(const[P,y]of Object.entries(w[p.name]))!r[`${p.name}_Array`].includes(P)&&!x?.get(p.name)?.includes(P)&&(k.size+=O(C,I),k.size<=500&&H(p,C,I,P,y.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${I.type}`)}for(const p of R){if(!k)throw new Error("VALIDATION_ERROR: batchSize is required");const C=i.collections[p.collection],I=V(C.fields,p.twoWay);if(!I)throw new Error(`SCHEMA_ERROR: Field ${p.twoWay} not found in collection ${p.collection}`);if(ee(I)){if(t==="update"&&w&&r[p.name]&&xe(r[p.name])&&w[`${p.name}_Array`]?.length>0)for(const[P,y]of Object.entries(w[p.name]))x?.get(p.name)?.includes(P)||(k.size+=O(C,I),k.size<=500&&H(p,C,I,P,y.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${I.type}`)}}},Ze=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]===void 0?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&Ze(t[e]))},Vo=t=>{if(t=t.toString(),/[/]|^\.+$|^__.*__$/.test(t))return!1;try{const s=new TextEncoder().encode(t),r=new TextDecoder().decode(s);if(t!==r)return!1}catch{return!1}return!(new Blob([t]).size>1500)},pi=async(t,e,n,s=1e3,r=5)=>{for(;r>0;)try{await t(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Qn=t=>{if(!t||typeof t!="string")return"";let e=t.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},ks=t=>t?Array.isArray(t)?t.map(s=>Qn(s)).filter(s=>s.length>0):Qn(t)||"":"",tu=t=>{if(!t||typeof t!="string")return"";let e=t.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},yi=t=>{if(!t||typeof t!="string")return"";let e=t.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},Zc=(t="enterprise",e)=>t==="enterprise"?e:"(default)",le=()=>{const t=wt.getApp(),e=process.env.STOKER_FB_WEB_APP_CONFIG;if(!e)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const n=JSON.parse(e),s=Zc(process.env.FB_FIRESTORE_EDITION,n.projectId);return ie.getFirestore(t,s)},No=async(t,e)=>{const n={};for(const s of e){const r=`${t}/${s}.js`,i=di.pathToFileURL(r).href;n[s]=await import(i)}return n};let ps,Do,Tn,Ao,Xt,Co,Sn,Rn,ys=0,li=!1;const At={getTenant(){if(!Tn)throw new Error("Tenant not provided");return Tn},setTenant(t){Tn=t},getMode(){return Do},getTimezone(){return Ao},getGlobalConfigModule(){return he(Xt)},getCustomizationFile(t,e){if(!Object.keys(e.collections).includes(t))throw new Error("PERMISSION_DENIED");const n=oa([t],Co,"node",At);return he(n?.[t])},getVersionInfo(){return Sn},getMaintenanceInfo(){return Rn},getStokerFirestore:le},qc=async(t,e,n,s,r)=>{const i=!!li;if(li=!0,e&&(Tn=e),Do=t,ps&&!r)return At;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),d=(await import(di.pathToFileURL(n).href)).default;Xt=d({sdk:"node",utils:At}),!r&&t==="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{ps=wt.getApp()}catch{ps=wt.initializeApp({credential:wt.applicationDefault(),databaseURL:a.databaseURL,storageBucket:a.storageBucket,projectId:a.projectId})}const m=await qe();return Co=await No(s,Object.keys(m.collections)),Ao=await oe(Xt.timezone),i||le().collection("system_deployment").doc("maintenance_mode").onSnapshot(u=>{u.exists?(Rn=u.data(),oe(Xt.onMaintenanceUpdate,["node",Rn.active?"on":"off"])):console.error("Maintenance status not found")},u=>{console.error(u.message)}),i||le().collection("system_deployment").doc("latest_deploy").onSnapshot(u=>{u.exists?(Sn=u.data(),ys++,ys>1&&oe(Xt.onVersionUpdate,["node",Sn,ys])):console.error("Version info not found")},u=>{console.error(u.message)}),await new Promise(u=>{const f=()=>{Rn&&Sn?u(At):setTimeout(f,100)};f()}),At},{getTenant:Be,setTenant:Bc,getMode:er,getTimezone:tr,getGlobalConfigModule:St,getCustomizationFile:He,getVersionInfo:Hc,getMaintenanceInfo:Gc}=At,Yc=async(t,e,n,s)=>new Promise((r,i)=>{const o=Go(t,e,{cwd:n||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},d=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout?.on("data",m=>{a+=m.toString(),console.log(m.toString())}),o.stderr?.on("data",m=>{console.log(m.toString())}),o.on("exit",m=>{d(),m===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),Jc=async()=>{const t=process.env.STOKER_FB_WEB_APP_CONFIG;if(!t)throw new Error("Firebase web app config not found");const e=JSON.parse(t);try{return wt.getApp()}catch{return wt.initializeApp({credential:wt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},qe=async(t=!1)=>{const s=await fi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(1).get(),r=Object.values(s.val())[0];if(t){for(const i of Object.values(r.collections))for(const o of i.fields)if(o.type==="Computed"){const a=Ce(o,He(i.labels.collection,r));a.formula&&(o.formula=a.formula)}}else for(const i of Object.values(r.collections))i.fields=i.fields.filter(o=>o.type!=="Computed");return r},Qc=async()=>{const n=await fi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(n.numChildren()<2))return Object.values(n.val())[0]},xe=(t,e,n)=>{let s=t.collection("tenants").doc(n);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},Fo=(t,e,n,s,r)=>{const i=le(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=n.collections[o],{labels:l,fields:c,preloadCache:d}=a,m=He(o,n),u=xe(i,e,t);if(r)if(s){const f=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const g=f&&Re("Read",f),v=yi(a,n,r),y=mi(a,r),w=Vs(a,r),R=pi(a,n,r),O=(h=[])=>{const S=[],b=vi(r.Role,a,n);if(!b)throw new Error("PERMISSION_DENIED");if(g){let T=i.collection("tenants").doc(t).collection("system_fields").doc(l.collection).collection(`${l.collection}-${b.key}`).where("Collection_Path_String","==",e.join("/"));h.forEach(N=>{T=T.where(...N)}),S.push(T)}else if(v)for(const T of v){let N=i.collection("tenants").doc(t).collection("system_fields").doc(l.collection).collection(`${l.collection}-${T.field}`).where("Collection_Path_String","==",e.join("/"));h.forEach(q=>{N=N.where(...q)}),S.push(N)}return S},I=y.filter(h=>"operations"in h&&h.operations?h.operations.includes("Read"):!0);if(I.length===0&&w.length===0&&R.length===0)return O();let E=0;const C=h=>{h&&(E===0?E=h:E*=h)};if(I.length>0){for(const h of I)if(h.operations&&h.type==="Record_Property"){const S=h.roles.find(b=>b.role===r.Role);if(!S)throw new Error("PERMISSION_DENIED");C(S.values?.length)}}d?.roles.includes(r.Role)&&d.range&&C(d.range.fields.length);const _=m.admin?.statusField;_&&!d?.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=[];I.filter(h=>h.type==="Record_Owner").forEach(()=>k.push(["Created_By","==",s])),I.filter(h=>h.type==="Record_User").forEach(h=>{if("collectionField"in h){const S=U(c,h.collectionField);k.push([`${S.name}_Array`,"array-contains",r.Doc_ID])}}),I.filter(h=>h.type==="Record_Property").forEach(h=>{if("propertyField"in h){const S=h.roles.find(T=>T.role===r.Role);if(!S)throw new Error("PERMISSION_DENIED");const b=U(c,h.propertyField);b.type==="Array"?k.push([`${b.name}_Array`,"array-contains-any",S.values]):k.push([b.name,"in",S.values])}});const p=[];w.filter(h=>h.type==="Individual").forEach(h=>{const S=f?.individualEntities,b=[];if(S){const T=h.singleQuery?h.singleQuery:Z;for(let N=0;N<S.length;N+=T){const q=S.slice(N,N+T);b.push(q)}if(!h.singleQuery)b.forEach(N=>{p.push(...O(k.concat([["id","in",N]])))});else{if(S.length>T)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${h.singleQuery} entities`);k.push(["id","in",S])}}}),R.filter(h=>h.parentFilter.type==="Individual").forEach(h=>{const{parentFilter:S,parentRestriction:b}=h;if("collectionField"in S){const T=U(c,S.collectionField);if("collection"in T){const N=r.collections?.[T.collection];if(!N)throw new Error("PERMISSION_DENIED");const q=N.individualEntities,M=[];if(q){const G=b.singleQuery?b.singleQuery:Z;for(let z=0;z<q.length;z+=G){const x=q.slice(z,z+G);M.push(x)}if(!b.singleQuery)M.forEach(z=>{p.push(...O(k.concat([[`${T.name}_Array`,"array-contains-any",z]])))});else{if(q.length>G)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${b.singleQuery} entities`);k.push([`${T.name}_Array`,"array-contains-any",q])}}}}});const F=[];w.filter(h=>h.type==="Parent").forEach(h=>{if("collectionField"in h){const S=U(c,h.collectionField);if("collection"in S){const b=f?.parentEntities,T=[];if(b){const N=h.singleQuery?h.singleQuery:Z;for(let q=0;q<b.length;q+=N){const M=b.slice(q,q+N);T.push(M)}if(!h.singleQuery)T.forEach(q=>{F.push(...O(k.concat([[`${S.name}_Array`,"array-contains-any",q]])))});else{if(b&&b.length>N)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${h.singleQuery} entities`);k.push([`${S.name}_Array`,"array-contains-any",b])}}}}}),R.filter(h=>h.parentFilter.type==="Parent").forEach(h=>{const{parentFilter:S,parentRestriction:b}=h;if("collectionField"in S&&"parentCollectionField"in S){const T=U(c,S.collectionField),N=U(c,S.parentCollectionField);if("collection"in T&&"collection"in N){const q=r.collections?.[T.collection];if(!q)throw new Error("PERMISSION_DENIED");const M=q.parentEntities,G=[];if(M){const z=b.singleQuery?b.singleQuery:Z;for(let x=0;x<M.length;x+=z){const Q=M.slice(x,x+z);G.push(Q)}if(!b.singleQuery)G.forEach(x=>{F.push(...O(k.concat([[`${N.name}_Array`,"array-contains-any",x]])))});else{if(M&&M.length>z)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${b.singleQuery} entities`);k.push([`${N.name}_Array`,"array-contains-any",M])}}}}});const A=[];F.length===0&&(w.filter(h=>h.type==="Parent_Property").forEach(h=>{if("collectionField"in h&&"propertyField"in h){const S=U(c,h.collectionField),b=U(c,h.propertyField);if("collection"in S){const T=f?.parentPropertyEntities||{};Object.entries(T).forEach(([N,q])=>{if(q.length>0){const M=[];for(let G=0;G<q.length;G+=Z){const z=q.slice(G,G+Z);M.push(z)}M.forEach(G=>{A.push(...O(k.concat([[`${S.name}_Array`,"array-contains-any",G],[b.name,"==",N]])))})}})}}}),R.filter(h=>h.parentFilter.type==="Parent_Property").forEach(h=>{const{parentFilter:S}=h;if("collectionField"in S&&"parentCollectionField"in S&&"parentPropertyField"in S){const b=U(c,S.collectionField),T=U(c,S.parentCollectionField),N=U(c,S.parentPropertyField);if("collection"in b&&"collection"in T){const q=r.collections?.[b.collection];if(!q)throw new Error("PERMISSION_DENIED");const M=q.parentPropertyEntities||{};Object.entries(M).forEach(([G,z])=>{if(z.length>0){const x=[];for(let Q=0;Q<z.length;Q+=Z){const B=z.slice(Q,Q+Z);x.push(B)}x.forEach(Q=>{A.push(...O(k.concat([[`${T.name}_Array`,"array-contains-any",Q],[N.name,"==",G]])))})}})}}}));const j=[...p,...F,...A];return!w.length&&!R.length?O(k):j}else throw new Error("PERMISSION_DENIED");else return[u]},nr=(t,e,n,s,r)=>{const i=le(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=s.collections[o],{labels:l}=a,c=xe(i,e,t);if(r){const d=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const m=d&&Re("Read",d),u=yi(a,s,r),f=[],g=vi(r.Role,a,s);if(!g)throw new Error("PERMISSION_DENIED");if(m)f.push(i.collection("tenants").doc(t).collection("system_fields").doc(l.collection).collection(`${l.collection}-${g.key}`).doc(n));else if(u)for(const v of u)f.push(i.collection("tenants").doc(t).collection("system_fields").doc(l.collection).collection(`${l.collection}-${v.field}`).doc(n));return f}else return[c.doc(n)]},$o=async(t,e,n,s,r,i,o,a,l,c)=>{const d=n.at(-2),m=gi(r.collections[d],r).map(g=>g.labels.collection);s.collections?s.collections.forEach(g=>{if(!m.includes(g))throw new Error(`SCHEMA_ERROR: Collection ${g} not found in subcollections of ${d}`)}):s.collections=m;const u=s.depth-1,f=s.collections.map(async g=>{const v=await rr([...n,g],{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 ${g} for document at ${n.join("/")}`),y});e[g]=v.records,i&&await Promise.all(e[g].map(y=>sr(t,y,[...n,g,y.id],i,r,void 0,a,l,c))),u>0&&await Promise.all(e[g].map(y=>$o(t,y,[...n,g,y.id],{depth:u},r,i,o,a,l,c)))});await Promise.all(f)},sr=async(t,e,n,s,r,i,o,a,l)=>{const c=n.at(-2);s.fields||=r.collections[c].fields.filter(u=>X(u));const d=s.depth-1,m=[];for(const u of s.fields)if("collection"in u){const f=e[u.name];if(!f)continue;const g=Object.keys(f);for(const v of g){const y=f[v],w=ze(y.Collection_Path,v,{userId:o,providedTransaction:a,noEmbeddingFields:l}).then(R=>{if(f[v]=R,d>0)return sr(t,f[v],[...y.Collection_Path,v],{depth:d},r,i,o,a,l)}).catch(R=>{if(R.message.includes("NOT_FOUND")||R.code==="permission-denied")delete f[v];else throw R});m.push(w)}}await Promise.all(m)},rr=async(t,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 n=e?.constraints,s=Be(),r=le();let i,o,a;const l=async c=>{const[d,m,u]=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")),qe(!0)]);if(!m.exists)throw new Error("MAINTENANCE_MODE");if(m.data().active)throw new Error("MAINTENANCE_MODE");const g=u;let v;const y=St(),w=t.at(-1);if(!w)throw new Error("EMPTY_PATH");const R=Object.keys(g.collections).includes(w),O=y.disabledCollections?.includes(w);if(!R||O)throw new Error("COLLECTION_NOT_FOUND");const I=g.collections[w],{labels:E}=I,C=He(E.collection,g);if(e?.userId){if(!d?.exists)throw new Error("PERMISSION_DENIED");if(v=d.data(),!v.Role)throw new Error("USER_ERROR");if(!v.Enabled)throw new Error("PERMISSION_DENIED")}let _=Fo(s,t,g,e?.userId,v);if(_.length===0)return{cursor:{},pages:0,records:[]};if(n&&(_=_.map(h=>(n.forEach(([S,b,T])=>{h=h.where(S,b,T)}),h))),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 h=e.pagination.startAfter||e.pagination.endBefore;if(e?.userId){const S=ia(v.Role,I,g);if(h&&S!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+S)}e.pagination.orderByField&&e.pagination.orderByDirection?!e.pagination.startAfter&&!e.pagination.endBefore?_=_.map(S=>S.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).limit(e.pagination.number)):e.pagination.startAfter?_=_.map((S,b)=>S.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).startAfter(o.last.get(b)).limit(e.pagination.number)):_=_.map((S,b)=>S.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).endBefore(o.first.get(b)).limitToLast(e.pagination.number)):!e.pagination.startAfter&&!e.pagination.endBefore?_=_.map(S=>S.limit(e.pagination.number)):e.pagination.startAfter?_=_.map((S,b)=>S.startAfter(o.last.get(b)).limit(e.pagination.number)):_=_.map((S,b)=>S.endBefore(o.first.get(b)).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 F=_.map(async h=>await c.get(h)),A=await Promise.all(F);for(const h of A){for(const S of h.docs){a.has(S.id)||a.set(S.id,{});const b=S.data(),T=a.get(S.id);T.id||=S.id;const N={...T,...b};delete N.Collection_Path_String,a.set(S.id,N)}o.first.set(A.indexOf(h),h.docs[0]),o.last.set(A.indexOf(h),h.docs.at(-1)||h.docs[0])}if(e?.pagination){let h=_[0];n&&(h=n.reduce((N,[q,M,G])=>N.where(q,M,G),h)),e.pagination.orderByField&&e.pagination.orderByDirection&&(h=h.orderBy(e.pagination.orderByField,e.pagination.orderByDirection));const b=(await h.count().get()).data().count,T=e.pagination.number;i=T>0?Math.ceil(b/T):0}let j;e?.noComputedFields||(j=await oe(C.admin?.retriever));for(const h of a.values()){const S=[],b=[...h.Collection_Path,h.id];e?.subcollections&&S.push($o(s,a.get(h.id),b,he(e.subcollections),g,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(M=>{if(typeof M=="string"){const G=I.fields.find(z=>z.name===M);if(G)return G;throw new Error(`SCHEMA_ERROR: Field ${M} not found in collection ${w}`)}return M})),S.push(sr(s,a.get(h.id),b,he(e.relations),g,void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields))),await Promise.all(S);const T=[];for(const M of I.fields){if(M.type==="Computed"&&!e?.noComputedFields){const G=Ce(M,C);if(!G.formula)continue;T.push(oe(G.formula,[h,j]).then(z=>{h[M.name]=z}))}e?.noEmbeddingFields&&M.type==="Embedding"&&delete h[M.name]}if(await Promise.all(T),e?.userId&&v?.Role){const M=v.Role;if(!(C.custom?.serverAccess?.read!==void 0?await oe(C.custom.serverAccess.read,[M,h]):!0)){a.delete(h.id);continue}for(const z of I.fields){const x=!z.access||z.access.includes(M),Q=Ce(z,C),B=Q?.custom?.serverAccess?.read!==void 0?await oe(Q.custom.serverAccess.read,[M,h]):!0;(!x||!B)&&(X(z)?(delete a.get(h.id)[z.name],delete a.get(h.id)[`${z.name}_Array`],delete a.get(h.id)[`${z.name}_Single`]):delete a.get(h.id)[z.name])}}const N={operation:"read",data:h,recordId:h.id,context:Z};await ae("postOperation",y,C,N),await ae("postRead",y,C,{context:Z,refs:_,record:h,listener:!1})}e?.userId&&await sa(Array.from(a.values()),I,g,e.userId,v)};return e?.providedTransaction?await l(e.providedTransaction):await r.runTransaction(async c=>{await l(c)},{readOnly:!0}),{cursor:o,pages:i,records:Array.from(a.values())}},Mo=async(t,e,n,s,r,i,o,a)=>{const l=s.at(-2),c=gi(i.collections[l],i).map(u=>u.labels.collection);r.collections?r.collections.forEach(u=>{if(!c.includes(u))throw new Error(`SCHEMA_ERROR: Collection ${u} not found in subcollections of ${l}`)}):r.collections=c;const d=r.depth-1,m=r.collections.map(async u=>{const f=await rr([...s,u],{constraints:r.constraints||[],userId:a,relations:o,pagination:r.limit,providedTransaction:e}).catch(g=>{throw g.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${u} for document at ${s.join("/")}`),g});n[u]=f.records,d>0&&await Promise.all(n[u].map(async g=>{await Mo(t,e,g,[...s,u,g.id],{depth:d},i,o,a)}))});await Promise.all(m)},Po=async(t,e,n,s,r,i,o,a,l)=>{const c=s.at(-2);i.fields||=r.collections[c].fields.filter(u=>X(u));const d=i.depth-1,m=[];for(const u of i.fields)if("collection"in u){const f=n[u.name];if(!f)continue;for(const[g,v]of Object.entries(f)){const y=ze(v.Collection_Path,g,{userId:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(w=>{if(f[g]=w,d>0)return Po(t,e,f[g],[...v.Collection_Path,g],r,{depth:d},o,a,l)}).catch(w=>{if(w.message.includes("NOT_FOUND")||w.code==="permission-denied")delete f[g];else throw w});m.push(y)}}await Promise.all(m)},ze=async(t,e,n)=>{if(n?.subcollections?.depth&&n.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(n?.relations?.depth&&n.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=Be(),r=le();let i;const o=async a=>{const[l,c,d]=await Promise.all([n?.userId?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(n.userId)):Promise.resolve({}),a.get(r.collection("system_deployment").doc("maintenance_mode")),qe(!0)]);if(!c.exists)throw new Error("MAINTENANCE_MODE");if(c.data().active)throw new Error("MAINTENANCE_MODE");const u=d;let f;const g=St(),v=t.at(-1);if(!v)throw new Error("EMPTY_PATH");const y=Object.keys(u.collections).includes(v),w=g.disabledCollections?.includes(v);if(!y||w)throw new Error("COLLECTION_NOT_FOUND");const R=u.collections[v],{labels:O}=R,I=He(O.collection,u);let E;if(n?.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?.[O.collection],!E)throw new Error("PERMISSION_DENIED")}if(n?.userId&&(!E||!Re("Read",E)))throw new Error("PERMISSION_DENIED");const C=nr(s,t,e,u,f);if(C.length===0)throw new Error("PERMISSION_DENIED");const _={};await ae("preOperation",g,I,{operation:"read",recordId:e,context:_}),await ae("preRead",g,I,{context:_,refs:C,multiple:!1,listener:!1}),i={};const p=C.map(b=>a.get(b)),F=await Promise.all(p);for(const b of F)if(b.exists){const T=b.data();i.id||=b.id,i={...i,...T},delete i.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${t?.join("/")||O.collection}`);const A=[],j=t?[...t,e]:[O.collection,e];if(n?.subcollections&&A.push(Mo(s,a,i,j,n.subcollections,u,void 0,n.userId)),n?.relations&&(n.relations.fields&&(n.relations.fields=n.relations.fields.map(b=>{if(typeof b=="string"){const T=R.fields.find(N=>N.name===b);if(T)return T;throw new Error(`SCHEMA_ERROR: Field ${b} not found in collection ${v}`)}return b})),A.push(Po(s,a,i,j,u,n.relations,n.userId,n.noComputedFields,n.noEmbeddingFields))),await Promise.all(A),!n?.noComputedFields){for(const b of R.fields)if(b.type==="Computed"){const T=Ce(b,I);if(!T.formula)continue;i[b.name]=await T.formula(i)}}if(n?.noEmbeddingFields)for(const b of R.fields)b.type==="Embedding"&&delete i[b.name];if(n?.userId&&f?.Role){const b=f.Role;if(!(I.custom?.serverAccess?.read!==void 0?await oe(I.custom?.serverAccess?.read,[b,i]):!0))throw new Error("PERMISSION_DENIED");for(const N of R.fields){const q=!N.access||N.access.includes(b),M=Ce(N,I),G=M?.custom?.serverAccess?.read!==void 0?await oe(M.custom.serverAccess.read,[b,i]):!0;(!q||!G)&&(X(N)?(delete i[N.name],delete i[`${N.name}_Array`],delete i[`${N.name}_Single`]):delete i[N.name])}}await ae("postOperation",g,I,{operation:"read",data:i,recordId:e,context:_}),await ae("postRead",g,I,{context:_,refs:C,record:i,listener:!1}),n?.userId&&await na(i,R,u,n.userId,f)};return n?.providedTransaction?await o(n.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},Lo=async(t,e,n,s,r,i,o,a)=>{const l=le(),c=He(r.labels.collection,i),d=r.labels.collection,m=r.fields.filter(f=>"unique"in f&&f.unique),u=[];if(await Promise.all(m.map(async f=>{{if(s[f.name]===void 0||Te(s[f.name]))return;Ce(f,c);const g=s[f.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(!Xs(g))u.push(`${f.name} "${s[f.name]}" is invalid`);else{const v=await l.collection("tenants").doc(e).collection("system_unique").doc(d).collection(`Unique-${d}-${f.name}`).doc(g).get();v.exists&&!(t==="update"&&v.data().id===n)&&u.push(`${f.name} "${s[f.name]}" already exists`)}}})),u.length>0)throw new Error(u.join(", "))},vt=async(t,e,n,s,r,i,o,a,l)=>{const{labels:c}=o,d=le(),m=St(),u=await oe(m.firebase?.writeLogTTL),f={operation:t,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,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_App:n.Last_Write_App,Last_Write_Version:n.Last_Write_Version,data:{}};if(u){const w=new Date,R=new Date(new Date().setDate(w.getDate()+u));f.TTL=ie.Timestamp.fromDate(R)}const g=he(n);it(g),t!=="delete"&&(f.data.data=he(g)),t==="update"&&(f.data.originalRecord=he(l)),t!=="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 v=xe(d,r,s),y=n.Last_Write_At;await v.doc(i).collection("system_write_log").doc(`${n.Last_Write_By}-${y.valueOf()}`).set(f)},qt=async t=>{const e=Be(),n=Ot.getAuth(),s=le(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(t.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},nu=(t="enterprise",e)=>t==="enterprise"?e:"(default)",me=()=>{const t=kt.getApp(),e=process.env.STOKER_FB_WEB_APP_CONFIG;if(!e)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const n=JSON.parse(e),s=nu(process.env.FB_FIRESTORE_EDITION,n.projectId);return oe.getFirestore(t,s)},Uo=async(t,e)=>{const n={};for(const s of e){const r=`${t}/${s}.js`,i=Ei.pathToFileURL(r).href;n[s]=await import(i)}return n};let bs,Wo,Fn,jo,sn,Zo,$n,Mn,Ts=0,gi=!1;const Mt={getTenant(){if(!Fn)throw new Error("Tenant not provided");return Fn},setTenant(t){Fn=t},getMode(){return Wo},getTimezone(){return jo},getGlobalConfigModule(){return ge(sn)},getCustomizationFile(t,e){if(!Object.keys(e.collections).includes(t))throw new Error("PERMISSION_DENIED");const n=ga([t],Zo,"node",Mt);return ge(n?.[t])},getVersionInfo(){return $n},getMaintenanceInfo(){return Mn},getStokerFirestore:me},su=async(t,e,n,s,r)=>{const i=!!gi;if(gi=!0,e&&(Fn=e),Wo=t,bs&&!r)return Mt;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),d=(await import(Ei.pathToFileURL(n).href)).default;sn=d({sdk:"node",utils:Mt}),!r&&t==="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{bs=kt.getApp()}catch{bs=kt.initializeApp({credential:kt.applicationDefault(),databaseURL:a.databaseURL,storageBucket:a.storageBucket,projectId:a.projectId})}const h=await Ye();return Zo=await Uo(s,Object.keys(h.collections)),jo=await ae(sn.timezone),i||me().collection("system_deployment").doc("maintenance_mode").onSnapshot(u=>{u.exists?(Mn=u.data(),ae(sn.onMaintenanceUpdate,["node",Mn.active?"on":"off"])):console.error("Maintenance status not found")},u=>{console.error(u.message)}),i||me().collection("system_deployment").doc("latest_deploy").onSnapshot(u=>{u.exists?($n=u.data(),Ts++,Ts>1&&ae(sn.onVersionUpdate,["node",$n,Ts])):console.error("Version info not found")},u=>{console.error(u.message)}),await new Promise(u=>{const f=()=>{Mn&&$n?u(Mt):setTimeout(f,100)};f()}),Mt},{getTenant:Je,setTenant:ru,getMode:cr,getTimezone:ur,getGlobalConfigModule:Nt,getCustomizationFile:st,getVersionInfo:iu,getMaintenanceInfo:ou}=Mt,au=async(t,e,n,s)=>new Promise((r,i)=>{const o=sa(t,e,{cwd:n||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},d=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout?.on("data",h=>{a+=h.toString(),console.log(h.toString())}),o.stderr?.on("data",h=>{console.log(h.toString())}),o.on("exit",h=>{d(),h===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),lu=async()=>{const t=process.env.STOKER_FB_WEB_APP_CONFIG;if(!t)throw new Error("Firebase web app config not found");const e=JSON.parse(t);try{return kt.getApp()}catch{return kt.initializeApp({credential:kt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},Ye=async(t=!1)=>{const s=await vi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(1).get(),r=Object.values(s.val())[0];if(t){for(const i of Object.values(r.collections))for(const o of i.fields)if(o.type==="Computed"){const a=Ue(o,st(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},cu=async()=>{const n=await vi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(n.numChildren()<2))return Object.values(n.val())[0]},Ae=(t,e,n)=>{let s=t.collection("tenants").doc(n);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},zo=(t,e,n,s,r,i)=>{const o=me(),a=e.at(-1);if(!a)throw new Error("EMPTY_PATH");const l=n.collections[a],{labels:c,fields:d,preloadCache:h}=l,u=st(a,n),f=Ae(o,e,t);if(r)if(s){const g=r.collections?.[c.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const T=g&&Ie("Read",g),m=Si(l,n,r,i??{}),E=bi(l,r),w=Gs(l,r),x=Ti(l,n,r),k=(y=[])=>{const _=[],S=Ni(r.Role,l,n);if(!S)throw new Error("PERMISSION_DENIED");if(T){let U=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${S.key}`).where("Collection_Path_String","==",e.join("/"));y.forEach(D=>{U=U.where(...D)}),_.push(U);const F=wt(l);Object.entries(l.fieldAccessGroups||{}).forEach(([D,M])=>{if(!F[D]?.length||!es(M,c.collection,r,i??{}))return;const J=on(D,S.key);let z=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${J}`).where("Collection_Path_String","==",e.join("/"));y.forEach(b=>{z=z.where(...b)}),_.push(z)})}else if(m)for(const U of m){let F=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${U.field}`).where("Collection_Path_String","==",e.join("/"));y.forEach(D=>{F=F.where(...D)}),_.push(F)}return _},v=E.filter(y=>"operations"in y&&y.operations?y.operations.includes("Read"):!0);if(v.length===0&&w.length===0&&x.length===0)return k();let N=0;const W=y=>{y&&(N===0?N=y:N*=y)};if(v.length>0){for(const y of v)if(y.operations&&y.type==="Record_Property"){const _=y.roles.find(S=>S.role===r.Role);if(!_)throw new Error("PERMISSION_DENIED");W(_.values?.length)}}h?.roles.includes(r.Role)&&h.range&&W(h.range.fields.length);const O=u.admin?.statusField;O&&!h?.roles.includes(r.Role)&&W(Math.max(O.active?.length||0,O.archived?.length||0));const H=N===0?30:Math.max(1,Math.floor(30/N)),R=[];v.filter(y=>y.type==="Record_Owner").forEach(()=>R.push(["Created_By","==",s])),v.filter(y=>y.type==="Record_User").forEach(y=>{if("collectionField"in y){const _=V(d,y.collectionField);R.push([`${_.name}_Array`,"array-contains",r.Doc_ID])}}),v.filter(y=>y.type==="Record_Property").forEach(y=>{if("propertyField"in y){const _=y.roles.find(U=>U.role===r.Role);if(!_)throw new Error("PERMISSION_DENIED");const S=V(d,y.propertyField);S.type==="Array"?R.push([`${S.name}_Array`,"array-contains-any",_.values]):R.push([S.name,"in",_.values])}});const p=[];w.filter(y=>y.type==="Individual").forEach(y=>{const _=g?.individualEntities,S=[];if(_){const U=y.singleQuery?y.singleQuery:H;for(let F=0;F<_.length;F+=U){const D=_.slice(F,F+U);S.push(D)}if(!y.singleQuery)S.forEach(F=>{p.push(...k(R.concat([["id","in",F]])))});else{if(_.length>U)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${y.singleQuery} entities`);R.push(["id","in",_])}}}),x.filter(y=>y.parentFilter.type==="Individual").forEach(y=>{const{parentFilter:_,parentRestriction:S}=y;if("collectionField"in _){const U=V(d,_.collectionField);if("collection"in U){const F=r.collections?.[U.collection];if(!F)throw new Error("PERMISSION_DENIED");const D=F.individualEntities,M=[];if(D){const J=S.singleQuery?S.singleQuery:H;for(let z=0;z<D.length;z+=J){const b=D.slice(z,z+J);M.push(b)}if(!S.singleQuery)M.forEach(z=>{p.push(...k(R.concat([[`${U.name}_Array`,"array-contains-any",z]])))});else{if(D.length>J)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${S.singleQuery} entities`);R.push([`${U.name}_Array`,"array-contains-any",D])}}}}});const C=[];w.filter(y=>y.type==="Parent").forEach(y=>{if("collectionField"in y){const _=V(d,y.collectionField);if("collection"in _){const S=g?.parentEntities,U=[];if(S){const F=y.singleQuery?y.singleQuery:H;for(let D=0;D<S.length;D+=F){const M=S.slice(D,D+F);U.push(M)}if(!y.singleQuery)U.forEach(D=>{C.push(...k(R.concat([[`${_.name}_Array`,"array-contains-any",D]])))});else{if(S&&S.length>F)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${y.singleQuery} entities`);R.push([`${_.name}_Array`,"array-contains-any",S])}}}}}),x.filter(y=>y.parentFilter.type==="Parent").forEach(y=>{const{parentFilter:_,parentRestriction:S}=y;if("collectionField"in _&&"parentCollectionField"in _){const U=V(d,_.collectionField),F=V(d,_.parentCollectionField);if("collection"in U&&"collection"in F){const D=r.collections?.[U.collection];if(!D)throw new Error("PERMISSION_DENIED");const M=D.parentEntities,J=[];if(M){const z=S.singleQuery?S.singleQuery:H;for(let b=0;b<M.length;b+=z){const B=M.slice(b,b+z);J.push(B)}if(!S.singleQuery)J.forEach(b=>{C.push(...k(R.concat([[`${F.name}_Array`,"array-contains-any",b]])))});else{if(M&&M.length>z)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${S.singleQuery} entities`);R.push([`${F.name}_Array`,"array-contains-any",M])}}}}});const I=[];C.length===0&&(w.filter(y=>y.type==="Parent_Property").forEach(y=>{if("collectionField"in y&&"propertyField"in y){const _=V(d,y.collectionField),S=V(d,y.propertyField);if("collection"in _){const U=g?.parentPropertyEntities||{};Object.entries(U).forEach(([F,D])=>{if(D.length>0){const M=[];for(let J=0;J<D.length;J+=H){const z=D.slice(J,J+H);M.push(z)}M.forEach(J=>{I.push(...k(R.concat([[`${_.name}_Array`,"array-contains-any",J],[S.name,"==",F]])))})}})}}}),x.filter(y=>y.parentFilter.type==="Parent_Property").forEach(y=>{const{parentFilter:_}=y;if("collectionField"in _&&"parentCollectionField"in _&&"parentPropertyField"in _){const S=V(d,_.collectionField),U=V(d,_.parentCollectionField),F=V(d,_.parentPropertyField);if("collection"in S&&"collection"in U){const D=r.collections?.[S.collection];if(!D)throw new Error("PERMISSION_DENIED");const M=D.parentPropertyEntities||{};Object.entries(M).forEach(([J,z])=>{if(z.length>0){const b=[];for(let B=0;B<z.length;B+=H){const K=z.slice(B,B+H);b.push(K)}b.forEach(B=>{I.push(...k(R.concat([[`${U.name}_Array`,"array-contains-any",B],[F.name,"==",J]])))})}})}}}));const P=[...p,...C,...I];return!w.length&&!x.length?k(R):P}else throw new Error("PERMISSION_DENIED");else return[f]},dr=(t,e,n,s,r,i)=>{const o=me(),a=e.at(-1);if(!a)throw new Error("EMPTY_PATH");const l=s.collections[a],{labels:c}=l,d=Ae(o,e,t);if(r){const h=r.collections?.[c.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const u=h&&Ie("Read",h),f=Si(l,s,r,i??{}),g=[],T=Ni(r.Role,l,s);if(!T)throw new Error("PERMISSION_DENIED");if(u){g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${T.key}`).doc(n));const m=wt(l);Object.entries(l.fieldAccessGroups||{}).forEach(([E,w])=>{if(!m[E]?.length||!es(w,c.collection,r,i??{}))return;const x=on(E,T.key);g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${x}`).doc(n))})}else if(f)for(const m of f)g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${m.field}`).doc(n));return g}else return[d.doc(n)]},En=async t=>await St.getAuth().getUser(t),qo=async(t,e,n,s,r,i,o,a,l,c)=>{const d=n.at(-2),h=Ri(r.collections[d],r).map(g=>g.labels.collection);s.collections?s.collections.forEach(g=>{if(!h.includes(g))throw new Error(`SCHEMA_ERROR: Collection ${g} not found in subcollections of ${d}`)}):s.collections=h;const u=s.depth-1,f=s.collections.map(async g=>{const T=await hr([...n,g],{constraints:s.constraints,userId:a,pagination:s.limit,providedTransaction:l,noEmbeddingFields:c}).catch(m=>{throw m.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${g} for document at ${n.join("/")}`),m});e[g]=T.records,i&&await Promise.all(e[g].map(m=>fr(t,m,[...n,g,m.id],i,r,void 0,a,l,c))),u>0&&await Promise.all(e[g].map(m=>qo(t,m,[...n,g,m.id],{depth:u},r,i,o,a,l,c)))});await Promise.all(f)},fr=async(t,e,n,s,r,i,o,a,l)=>{const c=n.at(-2);s.fields||=r.collections[c].fields.filter(u=>ee(u));const d=s.depth-1,h=[];for(const u of s.fields)if("collection"in u){const f=e[u.name];if(!f)continue;const g=Object.keys(f);for(const T of g){const m=f[T],E=Be(m.Collection_Path,T,{userId:o,providedTransaction:a,noEmbeddingFields:l}).then(w=>{if(f[T]=w,d>0)return fr(t,f[T],[...m.Collection_Path,T],{depth:d},r,i,o,a,l)}).catch(w=>{if(w.message.includes("NOT_FOUND")||w.code==="permission-denied")delete f[T];else throw w});h.push(E)}}await Promise.all(h)},hr=async(t,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 n=e?.constraints,s=Je(),r=me();let i,o,a;const l=async c=>{const[d,h,u,f]=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")),Ye(!0),e?.userId?En(e.userId):Promise.resolve(void 0)]);if(!h.exists)throw new Error("MAINTENANCE_MODE");if(h.data().active)throw new Error("MAINTENANCE_MODE");const T=u;let m;const E=Nt(),w=t.at(-1);if(!w)throw new Error("EMPTY_PATH");const x=Object.keys(T.collections).includes(w),k=E.disabledCollections?.includes(w);if(!x||k)throw new Error("COLLECTION_NOT_FOUND");const v=T.collections[w],{labels:N}=v,W=st(N.collection,T);if(e?.userId){if(!d?.exists)throw new Error("PERMISSION_DENIED");if(m=d.data(),!m.Role)throw new Error("USER_ERROR");if(!m.Enabled)throw new Error("PERMISSION_DENIED")}let O=zo(s,t,T,e?.userId,m,f?.customClaims??{});if(O.length===0)return{cursor:{},pages:0,records:[]};if(n&&(O=O.map(y=>(n.forEach(([_,S,U])=>{y=y.where(_,S,U)}),y))),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 y=e.pagination.startAfter||e.pagination.endBefore;if(e?.userId){const _=ya(m.Role,v,T);if(y&&_!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+_)}e.pagination.orderByField&&e.pagination.orderByDirection?!e.pagination.startAfter&&!e.pagination.endBefore?O=O.map(_=>_.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).limit(e.pagination.number)):e.pagination.startAfter?O=O.map((_,S)=>_.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).startAfter(o.last.get(S)).limit(e.pagination.number)):O=O.map((_,S)=>_.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).endBefore(o.first.get(S)).limitToLast(e.pagination.number)):!e.pagination.startAfter&&!e.pagination.endBefore?O=O.map(_=>_.limit(e.pagination.number)):e.pagination.startAfter?O=O.map((_,S)=>_.startAfter(o.last.get(S)).limit(e.pagination.number)):O=O.map((_,S)=>_.endBefore(o.first.get(S)).limitToLast(e.pagination.number))}const H={};await de("preOperation",E,W,{operation:"read",context:H}),await de("preRead",E,W,{context:H,refs:O,multiple:!0,listener:!1}),a=new Map;const C=O.map(async y=>await c.get(y)),I=await Promise.all(C);for(const y of I){for(const _ of y.docs){a.has(_.id)||a.set(_.id,{});const S=_.data(),U=a.get(_.id);U.id||=_.id;const F={...U,...S};delete F.Collection_Path_String,a.set(_.id,F)}o.first.set(I.indexOf(y),y.docs[0]),o.last.set(I.indexOf(y),y.docs.at(-1)||y.docs[0])}if(e?.pagination){let y=O[0];n&&(y=n.reduce((F,[D,M,J])=>F.where(D,M,J),y)),e.pagination.orderByField&&e.pagination.orderByDirection&&(y=y.orderBy(e.pagination.orderByField,e.pagination.orderByDirection));const S=(await y.count().get()).data().count,U=e.pagination.number;i=U>0?Math.ceil(S/U):0}let P;e?.noComputedFields||(P=await ae(W.admin?.retriever));for(const y of a.values()){const _=[],S=[...y.Collection_Path,y.id];e?.subcollections&&_.push(qo(s,a.get(y.id),S,ge(e.subcollections),T,ge(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(M=>{if(typeof M=="string"){const J=v.fields.find(z=>z.name===M);if(J)return J;throw new Error(`SCHEMA_ERROR: Field ${M} not found in collection ${w}`)}return M})),_.push(fr(s,a.get(y.id),S,ge(e.relations),T,void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields))),await Promise.all(_);const U=[];for(const M of v.fields){if(M.type==="Computed"&&!e?.noComputedFields){const J=Ue(M,W);if(!J.formula)continue;U.push(ae(J.formula,[y,P]).then(z=>{y[M.name]=z}))}e?.noEmbeddingFields&&M.type==="Embedding"&&delete y[M.name]}if(await Promise.all(U),e?.userId&&m?.Role){const M=m.Role;if(!(W.custom?.serverAccess?.read!==void 0?await ae(W.custom.serverAccess.read,[M,y]):!0)){a.delete(y.id);continue}for(const z of v.fields){const b=!z.access||He(z,m,v,f?.customClaims??{}),B=Ue(z,W),K=B?.custom?.serverAccess?.read!==void 0?await ae(B.custom.serverAccess.read,[M,y]):!0;(!b||!K)&&(ee(z)?(delete a.get(y.id)[z.name],delete a.get(y.id)[`${z.name}_Array`],delete a.get(y.id)[`${z.name}_Single`]):delete a.get(y.id)[z.name])}}const F={operation:"read",data:y,recordId:y.id,context:H};await de("postOperation",E,W,F),await de("postRead",E,W,{context:H,refs:O,record:y,listener:!1})}e?.userId&&await ma(Array.from(a.values()),v,T,e.userId,m)};return e?.providedTransaction?await l(e.providedTransaction):await r.runTransaction(async c=>{await l(c)},{readOnly:!0}),{cursor:o,pages:i,records:Array.from(a.values())}},Bo=async(t,e,n,s,r,i,o,a)=>{const l=s.at(-2),c=Ri(i.collections[l],i).map(u=>u.labels.collection);r.collections?r.collections.forEach(u=>{if(!c.includes(u))throw new Error(`SCHEMA_ERROR: Collection ${u} not found in subcollections of ${l}`)}):r.collections=c;const d=r.depth-1,h=r.collections.map(async u=>{const f=await hr([...s,u],{constraints:r.constraints||[],userId:a,relations:o,pagination:r.limit,providedTransaction:e}).catch(g=>{throw g.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${u} for document at ${s.join("/")}`),g});n[u]=f.records,d>0&&await Promise.all(n[u].map(async g=>{await Bo(t,e,g,[...s,u,g.id],{depth:d},i,o,a)}))});await Promise.all(h)},Ho=async(t,e,n,s,r,i,o,a,l)=>{const c=s.at(-2);i.fields||=r.collections[c].fields.filter(u=>ee(u));const d=i.depth-1,h=[];for(const u of i.fields)if("collection"in u){const f=n[u.name];if(!f)continue;for(const[g,T]of Object.entries(f)){const m=Be(T.Collection_Path,g,{userId:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(E=>{if(f[g]=E,d>0)return Ho(t,e,f[g],[...T.Collection_Path,g],r,{depth:d},o,a,l)}).catch(E=>{if(E.message.includes("NOT_FOUND")||E.code==="permission-denied")delete f[g];else throw E});h.push(m)}}await Promise.all(h)},Be=async(t,e,n)=>{if(n?.subcollections?.depth&&n.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(n?.relations?.depth&&n.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=Je(),r=me();let i;const o=async a=>{const[l,c,d,h]=await Promise.all([n?.userId?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(n.userId)):Promise.resolve({}),a.get(r.collection("system_deployment").doc("maintenance_mode")),Ye(!0),n?.userId?En(n.userId):Promise.resolve(void 0)]);if(!c.exists)throw new Error("MAINTENANCE_MODE");if(c.data().active)throw new Error("MAINTENANCE_MODE");const f=d;let g;const T=Nt(),m=t.at(-1);if(!m)throw new Error("EMPTY_PATH");const E=Object.keys(f.collections).includes(m),w=T.disabledCollections?.includes(m);if(!E||w)throw new Error("COLLECTION_NOT_FOUND");const x=f.collections[m],{labels:k}=x,v=st(k.collection,f);let N;if(n?.userId){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(g=l.data(),!g.Role)throw new Error("USER_ERROR");if(!g.Enabled)throw new Error("PERMISSION_DENIED");if(N=g.collections?.[k.collection],!N)throw new Error("PERMISSION_DENIED")}if(n?.userId&&(!N||!Ie("Read",N)))throw new Error("PERMISSION_DENIED");const W=dr(s,t,e,f,g,h?.customClaims??{});if(W.length===0)throw new Error("PERMISSION_DENIED");const O={};await de("preOperation",T,v,{operation:"read",recordId:e,context:O}),await de("preRead",T,v,{context:O,refs:W,multiple:!1,listener:!1}),i={};const p=W.map(S=>a.get(S)),C=await Promise.all(p);for(const S of C)if(S.exists){const U=S.data();i.id||=S.id,i={...i,...U},delete i.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${t?.join("/")||k.collection}`);const I=[],P=t?[...t,e]:[k.collection,e];if(n?.subcollections&&I.push(Bo(s,a,i,P,n.subcollections,f,void 0,n.userId)),n?.relations&&(n.relations.fields&&(n.relations.fields=n.relations.fields.map(S=>{if(typeof S=="string"){const U=x.fields.find(F=>F.name===S);if(U)return U;throw new Error(`SCHEMA_ERROR: Field ${S} not found in collection ${m}`)}return S})),I.push(Ho(s,a,i,P,f,n.relations,n.userId,n.noComputedFields,n.noEmbeddingFields))),await Promise.all(I),!n?.noComputedFields){for(const S of x.fields)if(S.type==="Computed"){const U=Ue(S,v);if(!U.formula)continue;i[S.name]=await U.formula(i)}}if(n?.noEmbeddingFields)for(const S of x.fields)S.type==="Embedding"&&delete i[S.name];if(n?.userId&&g?.Role){const S=g.Role;if(!(v.custom?.serverAccess?.read!==void 0?await ae(v.custom?.serverAccess?.read,[S,i]):!0))throw new Error("PERMISSION_DENIED");for(const F of x.fields){const D=!F.access||He(F,g,x,h?.customClaims??{}),M=Ue(F,v),J=M?.custom?.serverAccess?.read!==void 0?await ae(M.custom.serverAccess.read,[S,i]):!0;(!D||!J)&&(ee(F)?(delete i[F.name],delete i[`${F.name}_Array`],delete i[`${F.name}_Single`]):delete i[F.name])}}await de("postOperation",T,v,{operation:"read",data:i,recordId:e,context:O}),await de("postRead",T,v,{context:O,refs:W,record:i,listener:!1}),n?.userId&&await ha(i,x,f,n.userId,g)};return n?.providedTransaction?await o(n.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},Tt=async(t,e,n,s,r,i,o,a,l)=>{const{labels:c}=o,d=me(),h=Nt(),u=await ae(h.firebase?.writeLogTTL),f={operation:t,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,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_App:n.Last_Write_App,Last_Write_Version:n.Last_Write_Version,data:{}};if(u){const E=new Date,w=new Date(new Date().setDate(E.getDate()+u));f.TTL=oe.Timestamp.fromDate(w)}const g=ge(n);lt(g),t!=="delete"&&(f.data.data=ge(g)),t==="update"&&(f.data.originalRecord=ge(l)),t!=="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 T=Ae(d,r,s),m=n.Last_Write_At;await T.doc(i).collection("system_write_log").doc(`${n.Last_Write_By}-${m.valueOf()}`).set(f)},Yt=async t=>{const e=Je(),n=St.getAuth(),s=me(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(t.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
7
7
  ${i}`)}})(),(async()=>{try{await n.deleteUser(t.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(", "))},ir=async(t,e,n,s,r,i,o,a,l)=>{const c=le(),d=er(),m=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(m)t=m;else throw new Error("Admin email not set");const u=ms(t),f=zc(e),g=n?ai(n):void 0,v=s?ai(s):void 0,y=r?ms(r):void 0,w=i?ms(i):void 0,R=o?jn(o):void 0,O=l?jn(l):void 0,I=Array.isArray(u)?u:[u];if(I.length===0||I.length===1&&!I[0])throw new Error("No valid email addresses provided");const E={to:u,message:{subject:f}};if(g&&(E.message.text=g),v&&(E.message.html=v),y){const C=Array.isArray(y)?y:[y];C.length>0&&C[0]&&(E.cc=y)}if(w){const C=Array.isArray(w)?w:[w];C.length>0&&C[0]&&(E.bcc=w)}R&&(E.replyTo=R),a&&(E.message.attachments=a),O&&(E.from=O),await c.collection("system_mail").add(E)},Kc=["tenant","role","collection","doc"],Vo=new Set(Kc);function or(t){return Vo.has(t)}function Xc(t){if(!t)return{};const e={};for(const n of Object.keys(t))Vo.has(n)||(e[n]=t[n]);return e}const ar=async(t,e,n,s,r,i,o)=>{const a=Ot.getAuth(),l=le(),{labels:c,fields:d}=s,m="USER_ERROR",u=async(y,w)=>{try{await qt(y)}catch{throw new Error(`ROLLBACK_FAILED: ${w}`)}};let f;try{f=await a.createUser({email:r.Email,emailVerified:!1,password:o,displayName:r.Name,photoURL:r.Photo_URL,disabled:!r.Enabled})}catch{throw new Error(m)}const g={};for(const y of d)y.saveToAuthToken&&!or(y.name)&&r[y.name]!==void 0&&y.type!=="Timestamp"&&y.type!=="Computed"&&y.type!=="Embedding"&&(Te(r[y.name])?g[y.name]=null:g[y.name]=r[y.name]);try{await a.setCustomUserClaims(f.uid,{...g,tenant:t,role:r.Role,collection:c.collection,doc:e})}catch{throw await u(r,m),new Error(m)}try{await l.collection("tenants").doc(t).collection("system_user_permissions").doc(f.uid).set({...i,Role:r.Role,Enabled:r.Enabled??!1,Collection:c.collection,Doc_ID:e})}catch{throw await u(r,m),new Error(m)}const v=n.auth.enableMultiFactorAuth;if(v===!0||typeof v=="object"&&v.includes(r.Role)){let y;try{y=await a.generateEmailVerificationLink(r.Email)}catch{throw await u(r,m),new Error(m)}if(y.includes("apiKey=&")){const w=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);y=y.replace("apiKey=&",`apiKey=${w.apiKey}&`)}if(y){const w=`https://${a.app.options.projectId}.firebaseapp.com/__/auth/action${y}`,R=await oe(n.appName),O=n?.mail?.emailVerification&&n.mail.emailVerification(w,R);try{await ir(r.Email,O?.subject||"Please verify your email address",void 0,O?.html||`Please verify your email address by clicking the link:
8
+ ${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},mr=async(t,e,n,s,r,i,o,a,l)=>{const c=me(),d=cr(),h=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(h)t=h;else throw new Error("Admin email not set");const u=ks(t),f=tu(e),g=n?yi(n):void 0,T=s?yi(s):void 0,m=r?ks(r):void 0,E=i?ks(i):void 0,w=o?Qn(o):void 0,x=l?Qn(l):void 0,k=Array.isArray(u)?u:[u];if(k.length===0||k.length===1&&!k[0])throw new Error("No valid email addresses provided");const v={to:u,message:{subject:f}};if(g&&(v.message.text=g),T&&(v.message.html=T),m){const N=Array.isArray(m)?m:[m];N.length>0&&N[0]&&(v.cc=m)}if(E){const N=Array.isArray(E)?E:[E];N.length>0&&N[0]&&(v.bcc=E)}w&&(v.replyTo=w),a&&(v.message.attachments=a),x&&(v.from=x),await c.collection("system_mail").add(v)},uu=["tenant","role","collection","doc"],Go=new Set(uu);function pr(t){return Go.has(t)}function du(t){if(!t)return{};const e={};for(const n of Object.keys(t))Go.has(n)||(e[n]=t[n]);return e}const yr=async(t,e,n,s,r,i,o)=>{const a=St.getAuth(),l=me(),{labels:c,fields:d}=s,h="USER_ERROR",u=async(m,E)=>{try{await Yt(m)}catch{throw new Error(`ROLLBACK_FAILED: ${E}`)}};let f;try{f=await a.createUser({email:r.Email,emailVerified:!1,password:o,displayName:r.Name,photoURL:r.Photo_URL,disabled:!r.Enabled})}catch{throw new Error(h)}const g={};for(const m of d)m.saveToAuthToken&&!pr(m.name)&&r[m.name]!==void 0&&m.type!=="Timestamp"&&m.type!=="Computed"&&m.type!=="Embedding"&&(xe(r[m.name])?g[m.name]=null:g[m.name]=r[m.name]);try{await a.setCustomUserClaims(f.uid,{...g,tenant:t,role:r.Role,collection:c.collection,doc:e})}catch{throw await u(r,h),new Error(h)}try{await l.collection("tenants").doc(t).collection("system_user_permissions").doc(f.uid).set({...i,Role:r.Role,Enabled:r.Enabled??!1,Collection:c.collection,Doc_ID:e})}catch{throw await u(r,h),new Error(h)}const T=n.auth.enableMultiFactorAuth;if(T===!0||typeof T=="object"&&T.includes(r.Role)){let m;try{m=await a.generateEmailVerificationLink(r.Email)}catch{throw await u(r,h),new Error(h)}if(m.includes("apiKey=&")){const E=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);m=m.replace("apiKey=&",`apiKey=${E.apiKey}&`)}if(m){const E=`https://${a.app.options.projectId}.firebaseapp.com/__/auth/action${m}`,w=await ae(n.appName),x=n?.mail?.emailVerification&&n.mail.emailVerification(E,w);try{await mr(r.Email,x?.subject||"Please verify your email address",void 0,x?.html||`Please verify your email address by clicking the link:
9
9
  </br>
10
10
  </br>
11
- <a href="${w}">${w}</a>`)}catch{throw await u(r,m),new Error(m)}}}return f.uid},lr=async(t,e)=>{const{labels:n,parentCollection:s}=e;if(s){const r=t.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...t].slice(0,-2),o=await ze(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(n.collection),!Qe(t,a))throw new Error("PERMISSION_DENIED")}else if(t.length>1)throw new Error("PERMISSION_DENIED")},zn=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),eu=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{zn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?n[s]=new ie.Timestamp(r.seconds,r.nanoseconds):zn(r)&&e(r)})};e(t)},cr=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{zn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?n[s]=new ie.Timestamp(r._seconds,r._nanoseconds):zn(r)&&e(r)})};e(t)},Kn=t=>{if(typeof t=="object")for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]==="_DELETE_FIELD"?t[e]=ie.FieldValue.delete():Kn(t[e]))},tu=(t,e,n)=>{if(X(n)&&n.includeFields){const s={};return n.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=U(t.fields,r);kt(t,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},ci=async(t,e,n,s,r,i,o)=>{if(!X(n)||!n.enforceHierarchy)return;const{fields:a}=e,l=le(),c=Object.entries(s[n.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${n.name} is required`);const[d,m]=c[0];if(!m)throw new Error(`VALIDATION_ERROR: Relation ${n.name} is required`);const u=xe(l,m.Collection_Path,t);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(u.doc(d));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${d} not found in collection ${n.collection}`);const g=f.data(),v=U(a,n.enforceHierarchy.field),y=n.enforceHierarchy;if(!g[y.recordLinkField]||!s[v.name]||!Object.keys(s[v.name]).every(w=>Object.keys(g[y.recordLinkField]).includes(w)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},En=async(t,e,n)=>{delete e[t.name][n],e[`${t.name}_Array`]=e[`${t.name}_Array`]?.filter(s=>s!==n),delete e[`${t.name}_Single`]},gs=async(t,e,n,s,r)=>{e[t.name]||={},e[t.name][s]=n,e[`${t.name}_Array`]||=[],e[`${t.name}_Array`].push(s),r&&(e[`${t.name}_Single`]={id:s,...n})},nu=(t,e,n,s,r,i)=>{const o=[],a=[];for(const l of s.fields)X(l)&&l.twoWay&&l.collection===n&&((t==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),t==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},ur=async(t,e,n,s,r,i,o,a,l,c,d,m)=>{const{fields:u}=i,f=le(),g=new Map,v=new Map,y=new Map;for(const w of u)X(w)&&["OneToOne","OneToMany"].includes(w.type)&&w.enforceHierarchy&&s[w.name]&&(t==="Create"||t==="Update"&&!Qe(m?.[w.name],s[w.name]))&&await ci(e,i,w,s,a,l);for(const w of u)if(X(w)&&w.twoWay){const R=o.collections[w.collection],O=U(R.fields,w.twoWay),I=mt(R,[O]);if(s[w.name]){const E=Object.entries(s[w.name]);for(const C of E){const[_,Z]=C;if(t==="Create"||!m?.[w.name]?.[_]){let k;const p=y.get(w.collection)?.[_];if(p)k=p;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 A=xe(f,Z.Collection_Path,e),j=await a.get(A.doc(_));if(!j.exists){En(w,r,_);continue}const h=j.data();v.set(w.collection,{...v.get(w.collection)||{},[_]:h}),k=he({...h,...In(s)})}const F={...k[O.name],[n]:{Collection_Path:s.Collection_Path,...tu(i,s,O)}};k[O.name]=F,k[`${O.name}_Array`]||=[],k[`${O.name}_Array`].push(n),I.size===1&&(k[`${O.name}_Single`]={id:n,...F}),y.set(w.collection,{...y.get(w.collection)||{},[_]:k})}}}if(t==="Update"){const E=Object.entries(m?.[w.name]||{});for(const C of E){const[_,Z]=C;if(!s[w.name]?.[_]){let k;const p=y.get(w.collection)?.[_];if(p)k=p;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 F=xe(f,Z.Collection_Path,e),A=await a.get(F.doc(_));if(!A.exists){g.set(w.name,[...g.get(w.name)||[],_]);continue}const j=A.data();v.set(w.collection,{...v.get(w.collection)||{},[_]:j}),k=he({...j,...In(s)})}k[O.name][n]&&delete k[O.name][n],Array.isArray(k[`${O.name}_Array`])&&(k[`${O.name}_Array`]=k[`${O.name}_Array`].filter(F=>F!==n)),I.size===1&&delete k[`${O.name}_Single`],y.set(w.collection,{...y.get(w.collection)||{},[_]:k})}}}}for(const[w,R]of y.entries()){const O=o.collections[w],I=He(w,o);for(const[E,C]of Object.entries(R)){const{addedFields:_,removedFields:Z}=nu(t,E,w,i,s,m);if(c&&d){for(const k of _){const p=U(O.fields,k.twoWay);if(!hr(O,p,d)){En(k,r,E);continue}}for(const k of Z){const p=U(O.fields,k.twoWay),F=mt(O,[p]);if(!hr(O,p,d)){gs(k,r,m?.[k.name]?.[E],E,F.size===1);continue}}if(!lt("Update",O,o,c,d,v.get(w)?.[E])){for(const k of _)En(k,r,E);for(const k of Z){const p=U(O.fields,k.twoWay),F=mt(O,[p]);gs(k,r,m?.[k.name]?.[E],E,F.size===1)}}if(!lt("Update",O,o,c,d,C)){for(const k of _)En(k,r,E);for(const k of Z){const p=U(O.fields,k.twoWay),F=mt(O,[p]);gs(k,r,m?.[k.name]?.[E],E,F.size===1)}}}try{await an("update",C,O,I,{operation:"update",data:C,context:{},originalRecord:C},o)}catch(k){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${E} in ${w}: ${k.message}`)}for(const k of _){const p=U(O.fields,k.twoWay);["OneToOne","OneToMany"].includes(p.type)&&X(p)&&p.enforceHierarchy&&await ci(e,O,p,C,a,l,!0)}}}return g},Uo=(t,e,n)=>{t==="create"&&_t.forEach(s=>{if(!Qe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),t==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),_t.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!Qe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},dr=(t,e,n,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(n[i]===!0)if(t==="create")n[o]=ie.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])n[o]=ie.FieldValue.serverTimestamp();else if(n[o]&&n[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},ws=async(t,e,n,s,r)=>{if(!Re("Read",r.collections?.[e.labels.collection]))return!1;try{await ze([e.labels.collection],n,{userId:s,providedTransaction:t})}catch{return!1}return!0},su=10,ru=async(t,e)=>{if(t.length===0)return;const n=Math.min(e,t.length);let s=0;const r=async()=>{for(;s<t.length;){const i=s;s+=1,await t[i]()}};await Promise.all(Array.from({length:n},r))},Wo=async(t,e,n,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const g=l.individualEntities,v=u?.individualEntities||[],y=i?g.filter(w=>!v.includes(w)):g;for(const w of y){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");f.push(async()=>{if(!await ws(t,d,w,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const g=c.entityRestrictions?.restrictions?.find(I=>I.type==="Parent"&&I.roles.some(E=>E.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const v=U(d.fields,g.collectionField),y=r.collections[v.collection],w=l.parentEntities,R=u?.parentEntities||[],O=i?w.filter(I=>!R.includes(I)):w;for(const I of O){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 ws(t,y,I,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const g=c.entityRestrictions?.restrictions?.find(O=>O.type==="Parent_Property"&&O.roles.some(I=>I.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const v=U(d.fields,g.collectionField),y=r.collections[v.collection],w=l.parentPropertyEntities,R=u?.parentPropertyEntities||{};for(const[O,I]of Object.entries(w)){const E=R[O]||[],C=i?I.filter(_=>!E.includes(_)):I;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 ws(t,y,_,n,s))throw new Error("PERMISSION_DENIED")})}}}await ru(f,su)}}},iu=async(t,e,n)=>{const s=n?.userId,r=n?.user;let i=n?.context;const o=Be(),a=St();if(n?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(n?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=n?.providedSchema||await qe();if(t.length===0)throw new Error("EMPTY_PATH");const c=t.at(-1),d=Object.keys(l.collections).includes(c),m=a.disabledCollections?.includes(c);if(!d||m)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:g,enableWriteLog:v,softDelete:y}=u,w=He(f.collection,l),R=await oe(a.appName),O=le(),I=Ot.getAuth(),C=(s?await I.getUser(s):void 0)?.customClaims?.role;let _;s&&await lr(t,u);const Z=xe(O,t,o),k=n?.id||Z.doc().id;i=i||{},i.collection=f.collection,e.id=k,cr(e),Kn(e);const p=js("create",t,e,l,R,"Online",s||"System",ie.Timestamp.now(),ie.FieldValue.serverTimestamp());n?.createdAt&&(p.Created_At=n.createdAt),n?.createdBy&&(p.Created_By=n.createdBy);const F=he(p);y&&(p[y.archivedField]=!1),Ue(e),pt(u,p,l),v&&!n?.providedTransaction&&await vt("create","started",p,o,t,k,u),await ae("preOperation",a,w,{operation:"create",data:p,recordId:k,context:i}),await ae("preWrite",a,w,{operation:"create",data:p,recordId:k,context:i}),pt(u,p,l),xn(u,p),await fa(p,u,w,C),Ue(p);try{if(u.auth&&r&&!r.password)throw new Error("Password is required");n?.providedTransaction||(await Lo("create",o,k,p,u,l),await an("create",p,u,w,{operation:"create",data:p,context:i},l))}catch(T){throw new Error(`VALIDATION_ERROR: ${T.message}`)}Ue(p),e.id=k,y&&(p[y.archivedField]=!1),pt(u,p,l),xn(u,p);try{Uo("create",p,F),dr("create",u,p),await an("create",p,u,w,{operation:"create",data:p,context:i},l)}catch(T){throw new Error(`VALIDATION_ERROR: ${T.message}`)}if(s){const T=C;if(!T)throw new Error("USER_ERROR");if(!(w.custom?.serverAccess?.create!==void 0?await oe(w.custom.serverAccess.create,[T,p]):!0))throw new Error("PERMISSION_DENIED");for(const q of u.fields){if(!(q.name in p))continue;const M=Ce(q,w);if(M?.custom?.serverAccess?.create!==void 0&&!await oe(M.custom.serverAccess.create,[T,p]))throw new Error("PERMISSION_DENIED")}}r&&(r.permissions||={},r.permissions.Role||=p.Role,r.permissions.Enabled||=p.Enabled);const h=async(T,N)=>{const[q,M,G,z]=await Promise.all([n?.providedTransaction?Promise.resolve({}):T.get(O.collection("system_deployment").doc("latest_deploy")),n?.providedTransaction?Promise.resolve({}):T.get(O.collection("system_deployment").doc("maintenance_mode")),s?T.get(O.collection("tenants").doc(o).collection("system_user_permissions").doc(s)):Promise.resolve({}),n?.providedSchema?Promise.resolve(n.providedSchema):qe()]);if(N&&(N.size+=3),!n?.providedTransaction){if(!q.exists)throw new Error("VERSION_ERROR");const x=q.data();if(x.force&&p.Last_Write_At.valueOf()<x.time.valueOf())throw new Error("VERSION_ERROR");if(!M.exists)throw new Error("MAINTENANCE_MODE");if(M.data().active)throw new Error("MAINTENANCE_MODE")}if(l=z,s){if(!G?.exists)throw new Error("PERMISSION_DENIED");if(_=G.data(),!_.Role)throw new Error("USER_ERROR");if(!_.Enabled)throw new Error("PERMISSION_DENIED")}if(!n?.providedTransaction){const Q=g.filter(B=>"unique"in B&&B.unique).map(async B=>{if(!s||!B.access||B.access.includes(_.Role)){if(!e[B.name])return;const ve=Ce(B,w);if(!(s&&ve?.custom?.serverAccess?.read!==void 0?await oe(ve.custom.serverAccess.read,[_?.Role,p]):!0))throw new Error("PERMISSION_DENIED");const Ge=e[B.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Xs(Ge)){if(N&&N.size++,N&&N.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 T.get(O.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${B.name}`).doc(Ge)))?.exists)throw new Error(`VALIDATION_ERROR: ${B.name} "${p[B.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${B.name} "${p[B.name]}" is invalid`)}});await Promise.all(Q)}mr(p,k,u,l,s,_,r?.permissions),r?.permissions&&s&&_&&await Wo(T,r.permissions,s,_,l),mr(p,k,u,l,s,_,r?.permissions)};if(u.auth&&r){await O.runTransaction(async N=>{await h(N)},{maxAttempts:10});const T=await ar(o,k,a,u,p,r.permissions,r.password);p.User_ID=T}const S=async T=>{try{const N={size:1};await h(T,N),n?.noTwoWay||await ur("Create",o,k,p,p,u,l,T,N,s,_);const q=Ws(l);Ks("create",T,t,k,p,l,u,n,q,ie.FieldValue.arrayUnion,ie.FieldValue.arrayRemove,ie.FieldValue.delete,M=>O.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${M.name}`).doc(k),(M,G)=>O.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${M.name}`).doc(G),M=>O.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${M}`).doc(k),(M,G)=>xe(O,M,o).doc(G),(M,G,z)=>O.collection("tenants").doc(o).collection("system_fields").doc(M.collection).collection(`${M.collection}-${G}`).doc(z),(M,G,z)=>O.collection("tenants").doc(o).collection("system_fields").doc(M.collection).collection(`${M.collection}-${G.replaceAll(" ","-")}`).doc(z),void 0,void 0,N),T.set(Z.doc(k),p)}catch(N){if(n?.providedTransaction)throw N;{const M=await ae("postWriteError",a,w,{operation:"create",data:p,recordId:k,context:i,error:N});if(v&&(await new Promise(G=>{setTimeout(G,250)}),await vt("create",M?.resolved?"success":"failed",p,o,t,k,u,M?.resolved?void 0:N)),!M?.resolved)throw u.auth&&r&&await qt(p),N}}};if(n?.providedTransaction?await S(n.providedTransaction):await O.runTransaction(async T=>{await S(T)},{maxAttempts:10}),!n?.providedTransaction){const T={operation:"create",data:p,recordId:k,context:i},N={...T};await ae("postWrite",a,w,T),await ae("postOperation",a,w,N)}return{id:k,...p}},en=async(t,e,n,s)=>{const r=Be(),i=Ot.getAuth(),o=le(),a=e.customClaims||{};let l=!1;try{await i.updateUser(t,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(t,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(t).update({...n,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},jo=async(t,e,n,s,r,i,o,a,l,c,d)=>{const m=Ot.getAuth(),u=le(),f={};for(const y of r.fields)y.saveToAuthToken&&!or(y.name)&&i[y.name]!==void 0&&y.type!=="Timestamp"&&y.type!=="Computed"&&y.type!=="Embedding"&&(Te(i[y.name])?f[y.name]=null:f[y.name]=i[y.name]);const g="USER_ERROR";let v="";if(t==="create"){if(!d)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{v=await ar(e,n,s,r,i,l,d)}catch(y){throw new Error(y.message)}}else if(t==="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),d&&(y.password=d),Object.keys(y).length)try{await m.updateUser(o.User_ID,y),y.disabled===!0&&await m.revokeRefreshTokens(o.User_ID)}catch{throw await en(o.User_ID,a,c,g),new Error(g)}if(i.Role&&i.Role!==o.Role||Object.keys(f).length)try{const w={...Xc(a.customClaims),...f};await m.setCustomUserClaims(o.User_ID,{...w,tenant:e,role:i.Role,collection:r.labels.collection,doc:n}),await m.revokeRefreshTokens(o.User_ID)}catch{throw await en(o.User_ID,a,c,g),new Error(g)}try{await u.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:r.labels.collection,Doc_ID:n,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await en(o.User_ID,a,c,g),new Error(g)}if(o.Email!==i.Email){const w=s.auth.enableMultiFactorAuth;if(w===!0||typeof w=="object"&&w.includes(i.Role)){let R=await m.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(R.includes("apiKey=&")){const O=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);R=R.replace("apiKey=&",`apiKey=${O.apiKey}&`)}if(R){const O=`https://${m.app.options.projectId}.firebaseapp.com/__/auth/action${R}`,I=await oe(s.appName),E=s?.mail?.emailVerification&&s.mail.emailVerification(O,I);try{await ir(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="${E}">${E}</a>`)}catch{throw await u(r,h),new Error(h)}}}return f.uid},gr=async(t,e)=>{const{labels:n,parentCollection:s}=e;if(s){const r=t.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...t].slice(0,-2),o=await Be(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(n.collection),!Xe(t,a))throw new Error("PERMISSION_DENIED")}else if(t.length>1)throw new Error("PERMISSION_DENIED")},Kn=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),fu=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{Kn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?n[s]=new oe.Timestamp(r.seconds,r.nanoseconds):Kn(r)&&e(r)})};e(t)},wr=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{Kn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?n[s]=new oe.Timestamp(r._seconds,r._nanoseconds):Kn(r)&&e(r)})};e(t)},as=t=>{if(typeof t=="object")for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]==="_DELETE_FIELD"?t[e]=oe.FieldValue.delete():as(t[e]))},hu=(t,e,n)=>{if(ee(n)&&n.includeFields){const s={};return n.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=V(t.fields,r);Rt(t,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},wi=async(t,e,n,s,r,i,o)=>{if(!ee(n)||!n.enforceHierarchy)return;const{fields:a}=e,l=me(),c=Object.entries(s[n.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${n.name} is required`);const[d,h]=c[0];if(!h)throw new Error(`VALIDATION_ERROR: Relation ${n.name} is required`);const u=Ae(l,h.Collection_Path,t);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(u.doc(d));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${d} not found in collection ${n.collection}`);const g=f.data(),T=V(a,n.enforceHierarchy.field),m=n.enforceHierarchy;if(!g[m.recordLinkField]||!s[T.name]||!Object.keys(s[T.name]).every(E=>Object.keys(g[m.recordLinkField]).includes(E)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},xn=async(t,e,n)=>{delete e[t.name][n],e[`${t.name}_Array`]=e[`${t.name}_Array`]?.filter(s=>s!==n),delete e[`${t.name}_Single`]},Ss=async(t,e,n,s,r)=>{e[t.name]||={},e[t.name][s]=n,e[`${t.name}_Array`]||=[],e[`${t.name}_Array`].push(s),r&&(e[`${t.name}_Single`]={id:s,...n})},mu=(t,e,n,s,r,i)=>{const o=[],a=[];for(const l of s.fields)ee(l)&&l.twoWay&&l.collection===n&&((t==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),t==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},_r=async(t,e,n,s,r,i,o,a,l,c,d,h,u)=>{const{fields:f}=i,g=me(),T=new Map,m=new Map,E=new Map;for(const w of f)ee(w)&&["OneToOne","OneToMany"].includes(w.type)&&w.enforceHierarchy&&s[w.name]&&(t==="Create"||t==="Update"&&!Xe(h?.[w.name],s[w.name]))&&await wi(e,i,w,s,a,l);for(const w of f)if(ee(w)&&w.twoWay){const x=o.collections[w.collection],k=V(x.fields,w.twoWay),v=_t(x,[k]);if(s[w.name]){const N=Object.entries(s[w.name]);for(const W of N){const[O,H]=W;if(t==="Create"||!h?.[w.name]?.[O]){let R;const p=E.get(w.collection)?.[O];if(p)R=p;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 I=Ae(g,H.Collection_Path,e),P=await a.get(I.doc(O));if(!P.exists){xn(w,r,O);continue}const y=P.data();m.set(w.collection,{...m.get(w.collection)||{},[O]:y}),R=ge({...y,...Pn(s)})}const C={...R[k.name],[n]:{Collection_Path:s.Collection_Path,...hu(i,s,k)}};R[k.name]=C,R[`${k.name}_Array`]||=[],R[`${k.name}_Array`].push(n),v.size===1&&(R[`${k.name}_Single`]={id:n,...C}),E.set(w.collection,{...E.get(w.collection)||{},[O]:R})}}}if(t==="Update"){const N=Object.entries(h?.[w.name]||{});for(const W of N){const[O,H]=W;if(!s[w.name]?.[O]){let R;const p=E.get(w.collection)?.[O];if(p)R=p;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 C=Ae(g,H.Collection_Path,e),I=await a.get(C.doc(O));if(!I.exists){T.set(w.name,[...T.get(w.name)||[],O]);continue}const P=I.data();m.set(w.collection,{...m.get(w.collection)||{},[O]:P}),R=ge({...P,...Pn(s)})}R[k.name][n]&&delete R[k.name][n],Array.isArray(R[`${k.name}_Array`])&&(R[`${k.name}_Array`]=R[`${k.name}_Array`].filter(C=>C!==n)),v.size===1&&delete R[`${k.name}_Single`],E.set(w.collection,{...E.get(w.collection)||{},[O]:R})}}}}for(const[w,x]of E.entries()){const k=o.collections[w],v=st(w,o);for(const[N,W]of Object.entries(x)){const{addedFields:O,removedFields:H}=mu(t,N,w,i,s,h);if(c&&d){for(const R of O){const p=V(k.fields,R.twoWay);if(!Or(k,p,d,u??{})){xn(R,r,N);continue}}for(const R of H){const p=V(k.fields,R.twoWay),C=_t(k,[p]);if(!Or(k,p,d,u??{})){Ss(R,r,h?.[R.name]?.[N],N,C.size===1);continue}}if(!ft("Update",k,o,c,d,m.get(w)?.[N])){for(const R of O)xn(R,r,N);for(const R of H){const p=V(k.fields,R.twoWay),C=_t(k,[p]);Ss(R,r,h?.[R.name]?.[N],N,C.size===1)}}if(!ft("Update",k,o,c,d,W)){for(const R of O)xn(R,r,N);for(const R of H){const p=V(k.fields,R.twoWay),C=_t(k,[p]);Ss(R,r,h?.[R.name]?.[N],N,C.size===1)}}}try{await hn("update",W,k,v,{operation:"update",data:W,context:{},originalRecord:W},o)}catch(R){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${N} in ${w}: ${R.message}`)}for(const R of O){const p=V(k.fields,R.twoWay);["OneToOne","OneToMany"].includes(p.type)&&ee(p)&&p.enforceHierarchy&&await wi(e,k,p,W,a,l,!0)}}}return T},Yo=(t,e,n)=>{t==="create"&&ct.forEach(s=>{if(!Xe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),t==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),ct.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!Xe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},Er=(t,e,n,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(n[i]===!0)if(t==="create")n[o]=oe.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])n[o]=oe.FieldValue.serverTimestamp();else if(n[o]&&n[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},Rs=async(t,e,n,s,r)=>{if(!Ie("Read",r.collections?.[e.labels.collection]))return!1;try{await Be([e.labels.collection],n,{userId:s,providedTransaction:t})}catch{return!1}return!0},pu=10,yu=async(t,e)=>{if(t.length===0)return;const n=Math.min(e,t.length);let s=0;const r=async()=>{for(;s<t.length;){const i=s;s+=1,await t[i]()}};await Promise.all(Array.from({length:n},r))},Jo=async(t,e,n,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const g=l.individualEntities,T=u?.individualEntities||[],m=i?g.filter(E=>!T.includes(E)):g;for(const E of m){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 Rs(t,d,E,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const g=c.entityRestrictions?.restrictions?.find(k=>k.type==="Parent"&&k.roles.some(v=>v.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const T=V(d.fields,g.collectionField),m=r.collections[T.collection],E=l.parentEntities,w=u?.parentEntities||[],x=i?E.filter(k=>!w.includes(k)):E;for(const k of x){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 Rs(t,m,k,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const g=c.entityRestrictions?.restrictions?.find(x=>x.type==="Parent_Property"&&x.roles.some(k=>k.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const T=V(d.fields,g.collectionField),m=r.collections[T.collection],E=l.parentPropertyEntities,w=u?.parentPropertyEntities||{};for(const[x,k]of Object.entries(E)){const v=w[x]||[],N=i?k.filter(W=>!v.includes(W)):k;for(const W of N){if(o&&o.size++,o&&o.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks or entity restrictions (in permissions when dealing with user collections).");f.push(async()=>{if(!await Rs(t,m,W,n,s))throw new Error("PERMISSION_DENIED")})}}}await yu(f,pu)}}},gu=async(t,e,n)=>{const s=n?.userId,r=n?.user;let i=n?.context;const o=Je(),a=Nt();if(n?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(n?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=n?.providedSchema||await Ye();if(t.length===0)throw new Error("EMPTY_PATH");const c=t.at(-1),d=Object.keys(l.collections).includes(c),h=a.disabledCollections?.includes(c);if(!d||h)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:g,enableWriteLog:T,softDelete:m}=u,E=st(f.collection,l),w=await ae(a.appName),x=me(),k=St.getAuth(),v=s?await k.getUser(s):void 0,N=v?.customClaims?.role;let W,O;s&&await gr(t,u);const H=Ae(x,t,o),R=n?.id||H.doc().id;i=i||{},i.collection=f.collection,e.id=R,wr(e),as(e);const p=Ks("create",t,e,l,w,"Online",s||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp());n?.createdAt&&(p.Created_At=n.createdAt),n?.createdBy&&(p.Created_By=n.createdBy);const C=ge(p);m&&(p[m.archivedField]=!1),Ze(e),Et(u,p,l),T&&!n?.providedTransaction&&await Tt("create","started",p,o,t,R,u),await de("preOperation",a,E,{operation:"create",data:p,recordId:R,context:i}),await de("preWrite",a,E,{operation:"create",data:p,recordId:R,context:i}),Et(u,p,l),Ln(u,p);const _=(s?await x.collection("tenants").doc(o).collection("system_user_permissions").doc(s).get():void 0)?.data();await ba(p,u,E,_,v?.customClaims||{}),Ze(p);try{if(u.auth&&r&&!r.password)throw new Error("Password is required");n?.providedTransaction||await hn("create",p,u,E,{operation:"create",data:p,context:i},l)}catch(D){throw new Error(`VALIDATION_ERROR: ${D.message}`)}Ze(p),e.id=R,m&&(p[m.archivedField]=!1),Et(u,p,l),Ln(u,p);try{Yo("create",p,C),Er("create",u,p),await hn("create",p,u,E,{operation:"create",data:p,context:i},l)}catch(D){throw new Error(`VALIDATION_ERROR: ${D.message}`)}if(s){const D=N;if(!D)throw new Error("USER_ERROR");if(!(E.custom?.serverAccess?.create!==void 0?await ae(E.custom.serverAccess.create,[D,p]):!0))throw new Error("PERMISSION_DENIED");for(const J of u.fields){if(!(J.name in p))continue;const z=Ue(J,E);if(z?.custom?.serverAccess?.create!==void 0&&!await ae(z.custom.serverAccess.create,[D,p]))throw new Error("PERMISSION_DENIED")}}r&&(r.permissions||={},r.permissions.Role||=p.Role,r.permissions.Enabled||=p.Enabled);const S=async(D,M)=>{const[J,z,b,B,K]=await Promise.all([n?.providedTransaction?Promise.resolve({}):D.get(x.collection("system_deployment").doc("latest_deploy")),n?.providedTransaction?Promise.resolve({}):D.get(x.collection("system_deployment").doc("maintenance_mode")),s?D.get(x.collection("tenants").doc(o).collection("system_user_permissions").doc(s)):Promise.resolve({}),n?.providedSchema?Promise.resolve(n.providedSchema):Ye(),s?En(s):Promise.resolve(void 0)]);if(M&&(M.size+=3),!n?.providedTransaction){if(!J.exists)throw new Error("VERSION_ERROR");const ce=J.data();if(ce.force&&p.Last_Write_At.valueOf()<ce.time.valueOf())throw new Error("VERSION_ERROR");if(!z.exists)throw new Error("MAINTENANCE_MODE");if(z.data().active)throw new Error("MAINTENANCE_MODE")}if(l=B,s){if(!b?.exists)throw new Error("PERMISSION_DENIED");if(W=b.data(),!W.Role)throw new Error("USER_ERROR");if(!W.Enabled)throw new Error("PERMISSION_DENIED");O=K?.customClaims??{}}if(!n?.providedTransaction){const be=g.filter(le=>"unique"in le&&le.unique).map(async le=>{if(!s||!le.access||He(le,W,u,O)){if(!p[le.name])return;const ue=Ue(le,E);if(!(s&&ue?.custom?.serverAccess?.read!==void 0?await ae(ue.custom.serverAccess.read,[W?.Role,p]):!0))throw new Error("PERMISSION_DENIED");const Qe=p[le.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Vo(Qe)){if(M&&M.size++,M&&M.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 D.get(x.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${le.name}`).doc(Qe)))?.exists)throw new Error(`VALIDATION_ERROR: ${le.name} "${p[le.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${le.name} "${p[le.name]}" is invalid`)}});await Promise.all(be)}kr(p,R,u,l,s,W,r?.permissions,O),r?.permissions&&s&&W&&await Jo(D,r.permissions,s,W,l),kr(p,R,u,l,s,W,r?.permissions,O)};if(u.auth&&r){await x.runTransaction(async M=>{await S(M)},{maxAttempts:10});const D=await yr(o,R,a,u,p,r.permissions,r.password);p.User_ID=D}const U=async D=>{try{const M={size:1};await S(D,M),n?.noTwoWay||await _r("Create",o,R,p,p,u,l,D,M,s,W,void 0,O);const J=Qs(l);lr("create",D,t,R,p,l,u,n,J,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,z=>x.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${z.name}`).doc(R),(z,b)=>x.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${z.name}`).doc(b),z=>x.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${z}`).doc(R),(z,b)=>Ae(x,z,o).doc(b),(z,b,B)=>x.collection("tenants").doc(o).collection("system_fields").doc(z.collection).collection(`${z.collection}-${b}`).doc(B),(z,b,B)=>x.collection("tenants").doc(o).collection("system_fields").doc(z.collection).collection(`${z.collection}-${b.replaceAll(" ","-")}`).doc(B),void 0,void 0,M),D.set(H.doc(R),p)}catch(M){if(n?.providedTransaction)throw M;{const z=await de("postWriteError",a,E,{operation:"create",data:p,recordId:R,context:i,error:M});if(T&&(await new Promise(b=>{setTimeout(b,250)}),await Tt("create",z?.resolved?"success":"failed",p,o,t,R,u,z?.resolved?void 0:M)),!z?.resolved)throw u.auth&&r&&await Yt(p),M}}};if(n?.providedTransaction?await U(n.providedTransaction):await x.runTransaction(async D=>{await U(D)},{maxAttempts:10}),!n?.providedTransaction){const D={operation:"create",data:p,recordId:R,context:i},M={...D};await de("postWrite",a,E,D),await de("postOperation",a,E,M)}return{id:R,...p}},rn=async(t,e,n,s)=>{const r=Je(),i=St.getAuth(),o=me(),a=e.customClaims||{};let l=!1;try{await i.updateUser(t,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(t,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(t).update({...n,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Qo=async(t,e,n,s,r,i,o,a,l,c,d)=>{const h=St.getAuth(),u=me(),f={};for(const m of r.fields)m.saveToAuthToken&&!pr(m.name)&&i[m.name]!==void 0&&m.type!=="Timestamp"&&m.type!=="Computed"&&m.type!=="Embedding"&&(xe(i[m.name])?f[m.name]=null:f[m.name]=i[m.name]);const g="USER_ERROR";let T="";if(t==="create"){if(!d)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{T=await yr(e,n,s,r,i,l,d)}catch(m){throw new Error(m.message)}}else if(t==="update"){if(!c||!a)throw new Error("USER_ERROR");const m={};if(o.Name!==i.Name&&(m.displayName=i.Name),o.Email!==i.Email&&(m.email=i.Email,m.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(m.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(m.disabled=!i.Enabled),d&&(m.password=d),Object.keys(m).length)try{await h.updateUser(o.User_ID,m),m.disabled===!0&&await h.revokeRefreshTokens(o.User_ID)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}if(i.Role&&i.Role!==o.Role||Object.keys(f).length)try{const E={...du(a.customClaims),...f};await h.setCustomUserClaims(o.User_ID,{...E,tenant:e,role:i.Role,collection:r.labels.collection,doc:n}),await h.revokeRefreshTokens(o.User_ID)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}try{await u.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:r.labels.collection,Doc_ID:n,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}if(o.Email!==i.Email){const E=s.auth.enableMultiFactorAuth;if(E===!0||typeof E=="object"&&E.includes(i.Role)){let w=await h.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(w.includes("apiKey=&")){const x=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);w=w.replace("apiKey=&",`apiKey=${x.apiKey}&`)}if(w){const x=`https://${h.app.options.projectId}.firebaseapp.com/__/auth/action${w}`,k=await ae(s.appName),v=s?.mail?.emailVerification&&s.mail.emailVerification(x,k);try{await mr(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="${O}">${O}</a>`)}catch{throw await en(o.User_ID,a,c,g),new Error(g)}}}}}else if(t==="delete")try{await qt(o)}catch(y){throw new Error(y.message)}if(v)return v},ou=async(t,e,n)=>{const s=Be(),r=le(),i=[e];n&&n.trim()!==""&&i.push(n),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await t.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)t.set(a,{locked:!0})},ui=async(t,e)=>{const n=Be(),s=le(),r=[t];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(n).collection("system_locks").doc(o);i.delete(a)}await i.commit()},zo=async(t,e,n,s)=>{const r=s?.userId;let i=s?.user,o=s?.context;const a=Be(),l=St();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 qe(!0);if(t.length===0)throw new Error("EMPTY_PATH");const d=t.at(-1),m=Object.keys(c.collections).includes(d),u=l.disabledCollections?.includes(d);if(!m||u)throw new Error("COLLECTION_NOT_FOUND");const f=c.collections[d],{labels:g,fields:v,enableWriteLog:y}=f,w=He(g.collection,c),R=await oe(l.appName),O=Ot.getAuth(),I=le();let E;r&&await lr(t,f);const C=xe(I,t,a);o=o||{},o.collection=g.collection;let _=s?.originalRecord||await ze(t,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0}),Z=_;r&&(Z=await ze(t,e,{noComputedFields:!0,noEmbeddingFields:!0}));for(const x of v)x.type==="Computed"&&(delete n[x.name],delete _[x.name]);if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([x,Q])=>[x,{...Q,fields:Q.fields.filter(B=>B.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 k=f.fields.filter(x=>x.saveToAuthToken&&!or(x.name)),p=f.auth&&i?.operation==="create",F=f.auth&&i?.operation==="delete",A=f.auth&&!p&&!F&&(i?.operation==="update"||n.Role||n.Enabled!==void 0||n.Name||n.Email||n.Photo_URL||k.some(x=>n[x.name]!==void 0)),j=x=>x.User_ID&&(f.auth&&!p&&!F&&i?.operation==="update"||n.Role&&n.Role!==x.Role||n.Enabled!==void 0&&n.Enabled!==x.Enabled||n.Name&&n.Name!==x.Name||n.Email&&n.Email!==x.Email||n.Photo_URL&&n.Photo_URL!==x.Photo_URL||k.some(Q=>n[Q.name]!==void 0&&n[Q.name]!==x[Q.name]));delete n.id,cr(n),Kn(n);const h=js("update",t,n,c,R,"Online",r||"System",ie.Timestamp.now(),ie.FieldValue.serverTimestamp()),S=he(h);for(const x of v)!X(x)&&Te(h[x.name])&&x.nullable&&(h[x.name]=null);Ue(h),Ue(_),pt(f,h,c),pt(f,_,c),y&&!s?.providedTransaction&&await vt("update","started",h,a,t,e,f,void 0,_);const b={operation:"update",data:h,recordId:e,context:o,originalRecord:he(_)};await ae("preOperation",l,w,b);const T={operation:"update",data:h,recordId:e,context:o,originalRecord:he(_)};await ae("preWrite",l,w,T),pt(f,h,c),xn(f,h),Ue(h);try{if(p&&!i?.password)throw new Error("Password is required");if(!s?.providedTransaction){const x={...Z,...h};await Lo("update",a,e,x,f,c),it(x),await an("update",x,f,w,{operation:"update",data:h,context:o,originalRecord:he(_)},c)}}catch(x){throw new Error(`VALIDATION_ERROR: ${x.message}`)}Ue(h),delete n.id,pt(f,h,c),xn(f,h);for(const x of v)!X(x)&&Te(h[x.name])&&x.nullable&&(h[x.name]=null);try{const x={...Z,...h};it(x),dr("update",f,h,_),Uo("update",h,S),await an("update",x,f,w,{operation:"update",data:h,context:o,originalRecord:he(_)},c)}catch(x){throw new Error(`VALIDATION_ERROR: ${x.message}`)}let N;i&&(i.permissions||={});const q=async(x,Q,B)=>{const[ve,Ve,Ge,me,Ye]=await Promise.all([s?.providedTransaction?Promise.resolve({}):x.get(I.collection("system_deployment").doc("latest_deploy")),s?.providedTransaction?Promise.resolve({}):x.get(I.collection("system_deployment").doc("maintenance_mode")),s?.providedTransaction?Promise.resolve(_):ze(t,e,{userId:r,providedTransaction:x,noComputedFields:!0}),r?x.get(I.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve({}),s?.providedSchema?Promise.resolve(s.providedSchema):qe()]);if(B&&(B.size+=3),!s?.providedTransaction){if(!ve.exists)throw new Error("VERSION_ERROR");const Oe=ve.data();if(Oe.force&&h.Last_Write_At.valueOf()<Oe.time.valueOf())throw new Error("VERSION_ERROR");if(!Ve.exists)throw new Error("MAINTENANCE_MODE");if(Ve.data().active)throw new Error("MAINTENANCE_MODE")}if(!Ge)throw new Error("NOT_FOUND");if(_=Ge,c=Ye,r){if(!me?.exists)throw new Error("PERMISSION_DENIED");if(E=me.data(),!E.Role)throw new Error("USER_ERROR");if(!E.Enabled)throw new Error("PERMISSION_DENIED")}if(B&&(B.size+=nr(a,t,e,c,E).length),p&&_.User_ID||F&&!_.User_ID)throw new Error("USER_ERROR");if(j(_)){const Oe=await x.get(I.collection("tenants").doc(a).collection("system_user_permissions").doc(_.User_ID));if(B&&B.size++,!Oe?.exists)throw new Error("PERMISSION_DENIED");N=Oe.data();const ut=i?.permissions&&Object.keys(i.permissions).length>0?i.permissions:void 0;if(h.Role&&h.Role!==_.Role&&!ut&&(i||={operation:"update",permissions:{}},i.permissions=he(N),i.permissions.Role=h.Role),i?.permissions){if(i.permissions.Role||=h.Role||_.Role,i.permissions.Enabled??=h.Enabled??_.Enabled,Te(i.permissions.Role))throw new Error("VALIDATION_ERROR: Role field is required");if(Te(i.permissions.Enabled))throw new Error("VALIDATION_ERROR: Enabled field is required")}}if(!s?.providedTransaction){const ut=v.filter(we=>"unique"in we&&we.unique).map(async we=>{if(!r||!we.access||we.access.includes(E.Role)){if(h[we.name]===void 0||Te(h[we.name]))return;const Bt=Ce(we,w),hn={..._,...h};if(!(r&&Bt?.custom?.serverAccess?.read!==void 0?await oe(Bt.custom.serverAccess.read,[E?.Role,hn]):!0))throw new Error("PERMISSION_DENIED");const Xn=h[we.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Xs(Xn)){if(B&&B.size++,B&&B.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");const fr=await x.get(I.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${we.name}`).doc(Xn));if(fr.exists&&fr.data().id!==e)throw new Error(`VALIDATION_ERROR: ${we.name} "${h[we.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${we.name} "${h[we.name]}" is invalid`)}});await Promise.all(ut)}if(r&&E?.Role){const Oe=E.Role,ut={..._,...h};if(!(w.custom?.serverAccess?.update!==void 0?await oe(w.custom.serverAccess.update,[Oe,ut,_]):!0))throw new Error("PERMISSION_DENIED");for(const Bt of f.fields){const hn=Ce(Bt,w);if(Object.prototype.hasOwnProperty.call(h,Bt.name)&&hn?.custom?.serverAccess?.update!==void 0&&!await oe(hn.custom.serverAccess.update,[Oe,ut,_]))throw new Error("PERMISSION_DENIED")}}pr(h,_,e,f,c,r,E,i?.operation?i.operation:A?"update":void 0,i?.permissions,N),i?.permissions&&r&&E&&await Wo(x,i.permissions,r,E,c,N,B),pr(h,_,e,f,c,r,E,i?.operation?i.operation:A?"update":void 0,i?.permissions,N),Q&&(p||j(_)||F)&&await ou(x,e,_.User_ID)};(p||A||F)&&await I.runTransaction(async x=>{await q(x,!0)},{maxAttempts:10});const M=async(x,Q)=>{if(!_)throw new Error("NOT_FOUND");try{const B={size:1},ve={..._,...h};await q(x,!1,B);let Ve;!s?.noTwoWay&&!s?.providedTransaction&&(Ve=await ur("Update",a,e,ve,h,f,c,x,B,r,E,_));const Ge=Ws(c);Ks("update",x,t,e,h,c,f,s,Ge,ie.FieldValue.arrayUnion,ie.FieldValue.arrayRemove,ie.FieldValue.delete,me=>I.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${me.name}`).doc(e),(me,Ye)=>I.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${me.name}`).doc(Ye),me=>I.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${me}`).doc(e),(me,Ye)=>xe(I,me,a).doc(Ye),(me,Ye,Oe)=>I.collection("tenants").doc(a).collection("system_fields").doc(me.collection).collection(`${me.collection}-${Ye}`).doc(Oe),(me,Ye,Oe)=>I.collection("tenants").doc(a).collection("system_fields").doc(me.collection).collection(`${me.collection}-${Ye.replaceAll(" ","-")}`).doc(Oe),_,Ve,B),x.update(C.doc(e),h)}catch(B){if(s?.providedTransaction)throw B;{const ve={operation:"update",data:h,recordId:e,context:o,error:B,originalRecord:he(_)},Ve=await ae("postWriteError",l,w,ve);if(y&&(await new Promise(Ge=>{setTimeout(Ge,250)}),await vt("update",Ve?.resolved?"success":"failed",h,a,t,e,f,Ve?.resolved?void 0:B,_)),!Ve?.resolved)throw p&&await qt(_),j(_)&&await en(_.User_ID,Q,N,"USER_ERROR"),F&&await I.collection("tenants").doc(a).collection(g.collection).doc(e).update({User_ID:ie.FieldValue.delete()}),B}}(p||j(_)||F)&&await oi(ui,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")})};try{let x;if(p||j(_)||F){if(j(_)){x=await O.getUser(_.User_ID);const ve=x.customClaims;if(!(ve&&ve.role&&ve.collection&&ve.doc))throw new Error("USER_ERROR")}const Q={..._,...h};it(Q);const B=await jo(i?.operation||"update",a,e,l,f,Q,_,x,i?.permissions,N,i?.password);p&&(h.User_ID=B),F&&(h.User_ID=ie.FieldValue.delete())}s?.providedTransaction?await M(s.providedTransaction,x):await I.runTransaction(async Q=>{await M(Q,x)},{maxAttempts:10})}catch(x){throw(p||j(_)||F)&&await oi(ui,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),x}if(!s?.providedTransaction){const x={operation:"update",data:h,recordId:e,context:o,originalRecord:he(_)},Q={...x};await ae("postWrite",l,w,x),await ae("postOperation",l,w,Q)}const G={..._,...h};return it(G),{id:e,...G}},au=async(t,e,n)=>{const s=n?.userId;let r=n?.context;const i=Be(),o=St();let a=await qe();if(t.length===0)throw new Error("EMPTY_PATH");const l=t.at(-1),c=Object.keys(a.collections).includes(l),d=o.disabledCollections?.includes(l);if(!c||d)throw new Error("COLLECTION_NOT_FOUND");const m=a.collections[l],{labels:u,auth:f,enableWriteLog:g,softDelete:v}=m,y=He(u.collection,a),w=await oe(o.appName);if(v&&!f&&!n?.force)return await zo(t,e,{[v.archivedField]:!0,[v.timestampField]:ie.FieldValue.serverTimestamp()},{userId:s});const R=le();let O;s&&await lr(t,m);const I=xe(R,t,i);r=r||{},r.collection=u.collection;const E=await ze(t,e,{userId:s});let C=js("delete",t,E,a,w,"Online",s||"System",ie.Timestamp.now(),ie.FieldValue.serverTimestamp());const _=In(C);Ue(C),g&&await vt("delete","started",C,i,t,e,m),await ae("preOperation",o,y,{operation:"delete",data:C,recordId:e,context:r}),await ae("preWrite",o,y,{operation:"delete",data:C,recordId:e,context:r}),Ue(C);const p=async h=>{const[S,b,T,N]=await Promise.all([h.get(R.collection("system_deployment").doc("maintenance_mode")),ze(t,e,{userId:s,providedTransaction:h}),s?h.get(R.collection("tenants").doc(i).collection("system_user_permissions").doc(s)):Promise.resolve({}),qe()]);if(!S.exists)throw new Error("MAINTENANCE_MODE");if(S.data().active)throw new Error("MAINTENANCE_MODE");if(!b)throw new Error("NOT_FOUND");if(C={...b,..._},a=N,s){if(!T?.exists)throw new Error("PERMISSION_DENIED");if(O=T.data(),!O.Role)throw new Error("USER_ERROR");if(!O.Enabled)throw new Error("PERMISSION_DENIED");ta(C,e,m,a,s,O)}if(s&&O?.Role){const M=O.Role;if(!(y.custom?.serverAccess?.delete!==void 0?await oe(y.custom.serverAccess.delete,[M,C]):!0))throw new Error("PERMISSION_DENIED")}};m.auth&&(await R.runTransaction(async h=>{await p(h)},{maxAttempts:10}),C.User_ID&&await qt(C));try{await R.runTransaction(async h=>{await p(h);const S=Ws(a);Ks("delete",h,t,e,C,a,m,n,S,ie.FieldValue.arrayUnion,ie.FieldValue.arrayRemove,ie.FieldValue.delete,b=>R.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${b.name}`).doc(e),(b,T)=>R.collection("tenants").doc(i).collection("system_unique").doc(u.collection).collection(`Unique-${u.collection}-${b.name}`).doc(T),b=>R.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${b}`).doc(e),(b,T)=>xe(R,b,i).doc(T),(b,T,N)=>R.collection("tenants").doc(i).collection("system_fields").doc(b.collection).collection(`${b.collection}-${T}`).doc(N),(b,T,N)=>R.collection("tenants").doc(i).collection("system_fields").doc(b.collection).collection(`${b.collection}-${T.replaceAll(" ","-")}`).doc(N)),h.delete(I.doc(e))},{maxAttempts:10})}catch(h){const b=await ae("postWriteError",o,y,{operation:"delete",data:C,recordId:e,context:r,error:h});if(g&&(await new Promise(T=>{setTimeout(T,250)}),await vt("delete",b?.resolved?"success":"failed",C,i,t,e,m,b?.resolved?void 0:h)),!b?.resolved)throw m.auth&&C.User_ID&&await R.collection("tenants").doc(i).collection(u.collection).doc(e).update({User_ID:ie.FieldValue.delete()}),h}const F={operation:"delete",data:C,recordId:e,context:r},A={...F};return await ae("postWrite",o,y,F),await ae("postOperation",o,y,A),{id:e,...C}},lu=async(t,e)=>{const n=le(),s=er(),r=process.env.ADMIN_SMS;if(s==="development")if(r)t=r;else throw new Error("Admin phone not set");const i={to:t,body:e};await n.collection("system_messages").add(i)},cu=t=>t!==null&&typeof t=="object",uu=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{r instanceof ie.Timestamp?n[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:cu(r)&&e(r)})};e(t)},du=async t=>await Ot.getAuth().getUser(t),fu=t=>{const e=tr();return L.fromJSDate(t).setZone(e)},Zo=t=>{const e=tr();return L.fromJSDate(t.toDate()).setZone(e)},hu=(t,e)=>{const s=L.fromJSDate(t,{zone:e}).offset,i=L.fromJSDate(t).offset,o=s-i;return L.fromJSDate(t).plus({minutes:o}).toJSDate()},mu=(t,e)=>{const s=L.fromJSDate(t,{zone:e}).offset,i=L.fromJSDate(t).offset,o=s-i;return L.fromJSDate(t).minus({minutes:o}).toJSDate()},pu=t=>"seconds"in t&&"nanoseconds"in t?Zo(new ie.Timestamp(t.seconds,t.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=iu;exports.addUser=ar;exports.convertDateToTimezone=fu;exports.convertTimestampToTimezone=Zo;exports.deleteRecord=au;exports.deleteUser=qt;exports.deserializeDeleteSentinels=Kn;exports.deserializeTimestamps=cr;exports.deserializeTimestampsWithoutUnderscores=eu;exports.displayDate=pu;exports.fetchCurrentSchema=qe;exports.fetchLastSchema=Qc;exports.getCachedConfigValue=aa;exports.getCollectionRefs=Fo;exports.getCustomizationFile=He;exports.getCustomizationFiles=No;exports.getDocumentRefs=nr;exports.getFirestorePathRef=xe;exports.getGlobalConfigModule=St;exports.getInputSchema=jc;exports.getMaintenanceInfo=Gc;exports.getMode=er;exports.getOne=ze;exports.getSome=rr;exports.getStokerFirestore=le;exports.getTenant=Be;exports.getTimezone=tr;exports.getUser=du;exports.getVersionInfo=Hc;exports.getZodSchema=Si;exports.initializeFirebase=Jc;exports.initializeStoker=qc;exports.isDeleteSentinel=Te;exports.keepTimezone=hu;exports.removeTimezone=mu;exports.runChildProcess=Yc;exports.sendMail=ir;exports.sendMessage=lu;exports.serializeTimestamps=uu;exports.setTenant=Bc;exports.tryPromise=oe;exports.updateRecord=zo;exports.updateUser=jo;exports.validateRelations=ur;exports.validateSoftDelete=dr;exports.writeLog=vt;
14
+ <a href="${x}">${x}</a>`)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}}}}}else if(t==="delete")try{await Yt(o)}catch(m){throw new Error(m.message)}if(T)return T},wu=async(t,e,n)=>{const s=Je(),r=me(),i=[e];n&&n.trim()!==""&&i.push(n),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await t.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)t.set(a,{locked:!0})},_i=async(t,e)=>{const n=Je(),s=me(),r=[t];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(n).collection("system_locks").doc(o);i.delete(a)}await i.commit()},Ko=async(t,e,n,s)=>{const r=s?.userId;let i=s?.user,o=s?.context;const a=Je(),l=Nt();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 Ye(!0);if(t.length===0)throw new Error("EMPTY_PATH");const d=t.at(-1),h=Object.keys(c.collections).includes(d),u=l.disabledCollections?.includes(d);if(!h||u)throw new Error("COLLECTION_NOT_FOUND");const f=c.collections[d],{labels:g,fields:T,enableWriteLog:m}=f,E=st(g.collection,c),w=await ae(l.appName),x=St.getAuth(),k=me();let v,N;r&&await gr(t,f);const W=Ae(k,t,a);o=o||{},o.collection=g.collection;let O=s?.originalRecord||await Be(t,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0}),H=O;r&&(H=await Be(t,e,{noComputedFields:!0,noEmbeddingFields:!0}));for(const b of T)b.type==="Computed"&&(delete n[b.name],delete O[b.name]);if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([b,B])=>[b,{...B,fields:B.fields.filter(K=>K.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 R=f.fields.filter(b=>b.saveToAuthToken&&!pr(b.name)),p=f.auth&&i?.operation==="create",C=f.auth&&i?.operation==="delete",I=f.auth&&!p&&!C&&(i?.operation==="update"||n.Role||n.Enabled!==void 0||n.Name||n.Email||n.Photo_URL||R.some(b=>n[b.name]!==void 0)),P=b=>b.User_ID&&(f.auth&&!p&&!C&&i?.operation==="update"||n.Role&&n.Role!==b.Role||n.Enabled!==void 0&&n.Enabled!==b.Enabled||n.Name&&n.Name!==b.Name||n.Email&&n.Email!==b.Email||n.Photo_URL&&n.Photo_URL!==b.Photo_URL||R.some(B=>n[B.name]!==void 0&&n[B.name]!==b[B.name]));delete n.id,wr(n),as(n);const y=Ks("update",t,n,c,w,"Online",r||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp()),_=ge(y);for(const b of T)!ee(b)&&xe(y[b.name])&&b.nullable&&(y[b.name]=null);Ze(y),Ze(O),Et(f,y,c),Et(f,O,c),m&&!s?.providedTransaction&&await Tt("update","started",y,a,t,e,f,void 0,O);const S={operation:"update",data:y,recordId:e,context:o,originalRecord:ge(O)};await de("preOperation",l,E,S);const U={operation:"update",data:y,recordId:e,context:o,originalRecord:ge(O)};await de("preWrite",l,E,U),Et(f,y,c),Ln(f,y),Ze(y);try{if(p&&!i?.password)throw new Error("Password is required");if(!s?.providedTransaction){const b={...H,...y};lt(b),await hn("update",b,f,E,{operation:"update",data:y,context:o,originalRecord:ge(O)},c)}}catch(b){throw new Error(`VALIDATION_ERROR: ${b.message}`)}Ze(y),delete n.id,Et(f,y,c),Ln(f,y);for(const b of T)!ee(b)&&xe(y[b.name])&&b.nullable&&(y[b.name]=null);try{const b={...H,...y};lt(b),Er("update",f,y,O),Yo("update",y,_),await hn("update",b,f,E,{operation:"update",data:y,context:o,originalRecord:ge(O)},c)}catch(b){throw new Error(`VALIDATION_ERROR: ${b.message}`)}let F;i&&(i.permissions||={});const D=async(b,B,K)=>{const[ce,be,le,ue,De,Qe]=await Promise.all([s?.providedTransaction?Promise.resolve({}):b.get(k.collection("system_deployment").doc("latest_deploy")),s?.providedTransaction?Promise.resolve({}):b.get(k.collection("system_deployment").doc("maintenance_mode")),s?.providedTransaction?Promise.resolve(O):Be(t,e,{userId:r,providedTransaction:b,noComputedFields:!0}),r?b.get(k.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve({}),s?.providedSchema?Promise.resolve(s.providedSchema):Ye(),r?En(r):Promise.resolve(void 0)]);if(K&&(K.size+=3),!s?.providedTransaction){if(!ce.exists)throw new Error("VERSION_ERROR");const je=ce.data();if(je.force&&y.Last_Write_At.valueOf()<je.time.valueOf())throw new Error("VERSION_ERROR");if(!be.exists)throw new Error("MAINTENANCE_MODE");if(be.data().active)throw new Error("MAINTENANCE_MODE")}if(!le)throw new Error("NOT_FOUND");if(O=le,c=De,r){if(!ue?.exists)throw new Error("PERMISSION_DENIED");if(v=ue.data(),!v.Role)throw new Error("USER_ERROR");if(!v.Enabled)throw new Error("PERMISSION_DENIED");N=Qe?.customClaims??{}}if(K&&(K.size+=dr(a,t,e,c,v,N).length),p&&O.User_ID||C&&!O.User_ID)throw new Error("USER_ERROR");if(P(O)){const je=await b.get(k.collection("tenants").doc(a).collection("system_user_permissions").doc(O.User_ID));if(K&&K.size++,!je?.exists)throw new Error("PERMISSION_DENIED");F=je.data();const mt=i?.permissions&&Object.keys(i.permissions).length>0?i.permissions:void 0;if(y.Role&&y.Role!==O.Role&&!mt&&(i||={operation:"update",permissions:{}},i.permissions=ge(F),i.permissions.Role=y.Role),i?.permissions){if(i.permissions.Role||=y.Role||O.Role,i.permissions.Enabled??=y.Enabled??O.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 mt=T.filter(ve=>"unique"in ve&&ve.unique).map(async ve=>{if(!r||!ve.access||He(ve,v,f,N)){if(y[ve.name]===void 0||xe(y[ve.name]))return;const Jt=Ue(ve,E),vn={...O,...y};if(!(r&&Jt?.custom?.serverAccess?.read!==void 0?await ae(Jt.custom.serverAccess.read,[v?.Role,vn]):!0))throw new Error("PERMISSION_DENIED");const ls=y[ve.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Vo(ls)){if(K&&K.size++,K&&K.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 vr=await b.get(k.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${ve.name}`).doc(ls));if(vr.exists&&vr.data().id!==e)throw new Error(`VALIDATION_ERROR: ${ve.name} "${y[ve.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${ve.name} "${y[ve.name]}" is invalid`)}});await Promise.all(mt)}if(r&&v?.Role){const je=v.Role,mt={...O,...y};if(!(E.custom?.serverAccess?.update!==void 0?await ae(E.custom.serverAccess.update,[je,mt,O]):!0))throw new Error("PERMISSION_DENIED");for(const Jt of f.fields){const vn=Ue(Jt,E);if(Object.prototype.hasOwnProperty.call(y,Jt.name)&&vn?.custom?.serverAccess?.update!==void 0&&!await ae(vn.custom.serverAccess.update,[je,mt,O]))throw new Error("PERMISSION_DENIED")}}br(y,O,e,f,c,r,v,i?.operation?i.operation:I?"update":void 0,i?.permissions,F,N),i?.permissions&&r&&v&&await Jo(b,i.permissions,r,v,c,F,K),br(y,O,e,f,c,r,v,i?.operation?i.operation:I?"update":void 0,i?.permissions,F,N),B&&(p||P(O)||C)&&await wu(b,e,O.User_ID)};(p||I||C)&&await k.runTransaction(async b=>{await D(b,!0)},{maxAttempts:10});const M=async(b,B)=>{if(!O)throw new Error("NOT_FOUND");try{const K={size:1},ce={...O,...y};await D(b,!1,K);let be;!s?.noTwoWay&&!s?.providedTransaction&&(be=await _r("Update",a,e,ce,y,f,c,b,K,r,v,O,N));const le=Qs(c);lr("update",b,t,e,y,c,f,s,le,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,ue=>k.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${ue.name}`).doc(e),(ue,De)=>k.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${ue.name}`).doc(De),ue=>k.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${ue}`).doc(e),(ue,De)=>Ae(k,ue,a).doc(De),(ue,De,Qe)=>k.collection("tenants").doc(a).collection("system_fields").doc(ue.collection).collection(`${ue.collection}-${De}`).doc(Qe),(ue,De,Qe)=>k.collection("tenants").doc(a).collection("system_fields").doc(ue.collection).collection(`${ue.collection}-${De.replaceAll(" ","-")}`).doc(Qe),O,be,K),b.update(W.doc(e),y)}catch(K){if(s?.providedTransaction)throw K;{const ce={operation:"update",data:y,recordId:e,context:o,error:K,originalRecord:ge(O)},be=await de("postWriteError",l,E,ce);if(m&&(await new Promise(le=>{setTimeout(le,250)}),await Tt("update",be?.resolved?"success":"failed",y,a,t,e,f,be?.resolved?void 0:K,O)),!be?.resolved)throw p&&await Yt(O),P(O)&&await rn(O.User_ID,B,F,"USER_ERROR"),C&&await k.collection("tenants").doc(a).collection(g.collection).doc(e).update({User_ID:oe.FieldValue.delete()}),K}}(p||P(O)||C)&&await pi(_i,[e,O.User_ID]).catch(()=>{throw new Error("USER_ERROR")})};try{let b;if(p||P(O)||C){if(P(O)){b=await x.getUser(O.User_ID);const ce=b.customClaims;if(!(ce&&ce.role&&ce.collection&&ce.doc))throw new Error("USER_ERROR")}const B={...O,...y};lt(B);const K=await Qo(i?.operation||"update",a,e,l,f,B,O,b,i?.permissions,F,i?.password);p&&(y.User_ID=K),C&&(y.User_ID=oe.FieldValue.delete())}s?.providedTransaction?await M(s.providedTransaction,b):await k.runTransaction(async B=>{await M(B,b)},{maxAttempts:10})}catch(b){throw(p||P(O)||C)&&await pi(_i,[e,O.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),b}if(!s?.providedTransaction){const b={operation:"update",data:y,recordId:e,context:o,originalRecord:ge(O)},B={...b};await de("postWrite",l,E,b),await de("postOperation",l,E,B)}const J={...O,...y};return lt(J),{id:e,...J}},_u=async(t,e,n)=>{const s=n?.userId;let r=n?.context;const i=Je(),o=Nt();let a=await Ye();if(t.length===0)throw new Error("EMPTY_PATH");const l=t.at(-1),c=Object.keys(a.collections).includes(l),d=o.disabledCollections?.includes(l);if(!c||d)throw new Error("COLLECTION_NOT_FOUND");const h=a.collections[l],{labels:u,auth:f,enableWriteLog:g,softDelete:T}=h,m=st(u.collection,a),E=await ae(o.appName);if(T&&!f&&!n?.force)return await Ko(t,e,{[T.archivedField]:!0,[T.timestampField]:oe.FieldValue.serverTimestamp()},{userId:s});const w=me();let x;s&&await gr(t,h);const k=Ae(w,t,i);r=r||{},r.collection=u.collection;const v=await Be(t,e,{userId:s});let N=Ks("delete",t,v,a,E,"Online",s||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp());const W=Pn(N);Ze(N),g&&await Tt("delete","started",N,i,t,e,h),await de("preOperation",o,m,{operation:"delete",data:N,recordId:e,context:r}),await de("preWrite",o,m,{operation:"delete",data:N,recordId:e,context:r}),Ze(N);const R=async P=>{const[y,_,S,U]=await Promise.all([P.get(w.collection("system_deployment").doc("maintenance_mode")),Be(t,e,{userId:s,providedTransaction:P}),s?P.get(w.collection("tenants").doc(i).collection("system_user_permissions").doc(s)):Promise.resolve({}),Ye()]);if(!y.exists)throw new Error("MAINTENANCE_MODE");if(y.data().active)throw new Error("MAINTENANCE_MODE");if(!_)throw new Error("NOT_FOUND");if(N={..._,...W},a=U,s){if(!S?.exists)throw new Error("PERMISSION_DENIED");if(x=S.data(),!x.Role)throw new Error("USER_ERROR");if(!x.Enabled)throw new Error("PERMISSION_DENIED");fa(N,e,h,a,s,x)}if(s&&x?.Role){const D=x.Role;if(!(m.custom?.serverAccess?.delete!==void 0?await ae(m.custom.serverAccess.delete,[D,N]):!0))throw new Error("PERMISSION_DENIED")}};h.auth&&(await w.runTransaction(async P=>{await R(P)},{maxAttempts:10}),N.User_ID&&await Yt(N));try{await w.runTransaction(async P=>{await R(P);const y=Qs(a);lr("delete",P,t,e,N,a,h,n,y,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,_=>w.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${_.name}`).doc(e),(_,S)=>w.collection("tenants").doc(i).collection("system_unique").doc(u.collection).collection(`Unique-${u.collection}-${_.name}`).doc(S),_=>w.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${_}`).doc(e),(_,S)=>Ae(w,_,i).doc(S),(_,S,U)=>w.collection("tenants").doc(i).collection("system_fields").doc(_.collection).collection(`${_.collection}-${S}`).doc(U),(_,S,U)=>w.collection("tenants").doc(i).collection("system_fields").doc(_.collection).collection(`${_.collection}-${S.replaceAll(" ","-")}`).doc(U)),P.delete(k.doc(e))},{maxAttempts:10})}catch(P){const _=await de("postWriteError",o,m,{operation:"delete",data:N,recordId:e,context:r,error:P});if(g&&(await new Promise(S=>{setTimeout(S,250)}),await Tt("delete",_?.resolved?"success":"failed",N,i,t,e,h,_?.resolved?void 0:P)),!_?.resolved)throw h.auth&&N.User_ID&&await w.collection("tenants").doc(i).collection(u.collection).doc(e).update({User_ID:oe.FieldValue.delete()}),P}const p={operation:"delete",data:N,recordId:e,context:r},C={...p};return await de("postWrite",o,m,p),await de("postOperation",o,m,C),{id:e,...N}},Eu=async(t,e)=>{const n=me(),s=cr(),r=process.env.ADMIN_SMS;if(s==="development")if(r)t=r;else throw new Error("Admin phone not set");const i={to:t,body:e};await n.collection("system_messages").add(i)},vu=t=>t!==null&&typeof t=="object",Ou=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{r instanceof oe.Timestamp?n[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:vu(r)&&e(r)})};e(t)},ku=t=>{const e=ur();return j.fromJSDate(t).setZone(e)},Xo=t=>{const e=ur();return j.fromJSDate(t.toDate()).setZone(e)},bu=(t,e)=>{const s=j.fromJSDate(t,{zone:e}).offset,i=j.fromJSDate(t).offset,o=s-i;return j.fromJSDate(t).plus({minutes:o}).toJSDate()},Tu=(t,e)=>{const s=j.fromJSDate(t,{zone:e}).offset,i=j.fromJSDate(t).offset,o=s-i;return j.fromJSDate(t).minus({minutes:o}).toJSDate()},Su=t=>"seconds"in t&&"nanoseconds"in t?Xo(new oe.Timestamp(t.seconds,t.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=gu;exports.addUser=yr;exports.convertDateToTimezone=ku;exports.convertTimestampToTimezone=Xo;exports.deleteRecord=_u;exports.deleteUser=Yt;exports.deserializeDeleteSentinels=as;exports.deserializeTimestamps=wr;exports.deserializeTimestampsWithoutUnderscores=fu;exports.displayDate=Su;exports.fetchCurrentSchema=Ye;exports.fetchLastSchema=cu;exports.getCachedConfigValue=wa;exports.getCollectionRefs=zo;exports.getCustomizationFile=st;exports.getCustomizationFiles=Uo;exports.getDocumentRefs=dr;exports.getFirestorePathRef=Ae;exports.getGlobalConfigModule=Nt;exports.getInputSchema=eu;exports.getMaintenanceInfo=ou;exports.getMode=cr;exports.getOne=Be;exports.getSome=hr;exports.getStokerFirestore=me;exports.getTenant=Je;exports.getTimezone=ur;exports.getUser=En;exports.getVersionInfo=iu;exports.getZodSchema=$i;exports.initializeFirebase=lu;exports.initializeStoker=su;exports.isDeleteSentinel=xe;exports.keepTimezone=bu;exports.removeTimezone=Tu;exports.runChildProcess=au;exports.sendMail=mr;exports.sendMessage=Eu;exports.serializeTimestamps=Ou;exports.setTenant=ru;exports.tryPromise=ae;exports.updateRecord=Ko;exports.updateUser=Qo;exports.validateRelations=_r;exports.validateSoftDelete=Er;exports.writeLog=Tt;