@stoker-platform/node-client 0.5.66 → 0.5.68

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 Je=require("lodash/isEqual.js"),qo=require("lodash/merge.js"),Bo=require("lodash/set.js"),fe=require("lodash/cloneDeep.js"),Nt=require("firebase-admin/app"),H=require("firebase-admin/firestore"),ui=require("node:url"),Ho=require("cross-spawn"),di=require("firebase-admin/database"),_t=require("firebase-admin/auth"),zn=n=>!!n.auth,Se=(n,e)=>{if(e?.operations)return e.operations.includes(n)},Zn=(n,e)=>e?e.Role?n.access?.includes(e.Role):!1:!0,Go=(n,e)=>e?!e.Role||n.restrictCreate===!0?!1:typeof n.restrictCreate=="object"?n.restrictCreate?.includes(e.Role):!0:!0,fi=(n,e)=>e?!e.Role||n.restrictUpdate===!0?!1:typeof n.restrictUpdate=="object"?n.restrictUpdate?.includes(e.Role):!0:!0,fr=(n,e,t)=>{const{labels:s}=n;return t.collections&&Se("Update",t.collections[s.collection])&&(!e.access||Zn(e,t))&&fi(e,t)&&!(n.auth&&!t.collections?.[s.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},U=(n,e)=>n.filter(t=>t.name===e)[0],ee=n=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(n.type),hi=(n,e)=>{const t={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=n,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const d=a?.[t[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},Ls=(n,e)=>{const t=[],{labels:s,access:r}=n,{entityRestrictions:i}=r,o=e.collections?.[s.collection];return i?.restrictions?.forEach(a=>{"roles"in a&&a.roles.forEach(l=>{l.role===e.Role&&(!i.assignable?.includes(e.Role)||o?.restrictEntities)&&t.push(a)})}),t},mi=(n,e,t)=>{const s=[],{access:r}=n,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.role===t.Role))return;const a=o.collectionField,l=U(n.fields,a);if(!ee(l))throw new Error("PERMISSION_DENIED");const c=t.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===t.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===t.Role&&(!m.assignable?.includes(t.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},pi=(n,e,t)=>{const s=Object.values(e.collections),{labels:r}=n,i=[];for(const o of s){const{fields:a}=o;for(const l of a)if(!(l.access&&!Zn(l,t))&&t.Role&&ee(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)!i.find(m=>m.field===c.field)&&c.roles.includes(t.Role)&&i.push(c)}return i},Yo=(n,e,t,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const d=hi(e,r),m=Ls(e,r),u=mi(e,t,r);d?.filter(E=>E.type==="Record_Owner").forEach(E=>{"operations"in E&&E.operations&&!E.operations.includes(n)||i.Created_By!==s&&(c=!1)}),d?.filter(E=>E.type==="Record_User").forEach(E=>{if("operations"in E&&E.operations&&!E.operations.includes(n))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(n))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},at=(n,e,t,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;Se(n,a)||(l=!1);const d=Ls(e,r)?.filter(m=>m.type==="Individual").length>0;return n==="Create"&&d&&(l=!1),Yo(n,e,t,s,r,i)||(l=!1),l},yi=(n,e,t)=>{const{labels:s}=n,r=[];for(const i of Object.values(e.collections));return r},Jo=(n,e)=>{let t=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){t=!1,s="Permissions object must contain Doc_ID, Role, Collection, Enabled, and collections";return}}),e.collections&&(Object.keys(e.collections).forEach(r=>{if(!Object.keys(n.collections).includes(r)){s=`Collection ${r} not found in schema`,t=!1;return}const i=n.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,t=!1;return}if(!Object.keys(o).every(a=>["operations","auth","restrictEntities","individualEntities","parentEntities","parentPropertyEntities","recordProperty","recordUser","recordOwner"].includes(a))){s=`Collection ${r} has invalid properties`,t=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,t=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,t=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,t=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),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=>n.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,t=!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`,t=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,t=!1;return}if(a==="Parent"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(n.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,t=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(n.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,t=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,t=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),t},Qo=(n,e,t)=>{let s=!0,r="";Object.values(n.collections).filter(i=>i.auth).forEach(i=>{if(e.collections?.[i.labels.collection]?.auth&&!i.access.auth?.includes(e.Role)){r="Record cannot have auth access to collection",s=!1;return}});for(const i of Object.values(n.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:d,entityRestrictions:m}=a,u=c.assignable,f=e.collections?.[o.collection],g=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(t))?g.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const R=!!a.operations[y]?.includes(t),O=!!f?.operations.includes(w);if(!R&&O){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}if(R&&!O){r=`Collection ${o.collection} has missing ${y} operation for role ${t}`,s=!1;return}}}):g.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const R=!!a.operations[y]?.includes(t),O=!!f?.operations.includes(w);if(!R&&O){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}}}),!d&&!m||(d?.forEach(y=>{for(const w of y.roles)if(w.role===t&&!w.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${t}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${t}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${t}`,s=!1;return}}}),m?.assignable?.includes(t)))continue;let v=!1;if(m?.restrictions?.forEach(y=>{for(const w of y.roles)if(w.role===t){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(!ee(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(!ee(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},Ko=(n,e,t,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):n==="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&&n!=="delete"&&i&&Object.keys(t.collections).forEach(v=>{const y=i.collections?.[v],w=l?.collections?.[v];if(!(n==="update"&&Je(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))||n==="update"&&Je(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&&!(n==="update"&&Je(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||n==="update"&&Je(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&&!(n==="update"&&Je(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)},Xo=(n,e,t,s)=>{let r=!0,i="";return Object.values(n.collections).forEach(o=>{const a=t.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!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)&&(!Se("Read",c)||!Se(d,c))){i=`User does not have ${d.toLowerCase()} access to collection ${o.labels.collection}`,r=!1;return}if(!a?.recordOwner&&l?.recordOwner&&c?.recordOwner){i=`User does not have write access to recordOwner for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordUser&&l?.recordUser&&c?.recordUser){i=`User does not have write access to recordUser for collection ${o.labels.collection}`,r=!1;return}if(!a?.recordProperty&&l?.recordProperty&&c?.recordProperty){i=`User does not have write access to recordProperty for collection ${o.labels.collection}`,r=!1;return}if(!a?.restrictEntities&&l?.restrictEntities&&c?.restrictEntities){i=`User does not have write access to restrictEntities for collection ${o.labels.collection}`,r=!1;return}}),i&&console.error(`PERMISSION_DENIED: ${i}`),r},Vs=(n,e,t,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(n==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(n==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!Ko(n,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(n==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;if(n==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return f="User cannot update their own record",u=!1,u;if(n==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return n==="delete"||d==="delete"||!a?u:a.Role?(Jo(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!==t?(f="Permissions doc ID does not match record doc ID",u=!1,u):!Qo(r,a,a.Role)||i&&o&&l&&!Xo(r,o,a,l)?(u=!1,u):(f&&console.error(`PERMISSION_DENIED: ${f}`),u)):(f="Permissions do not have a role",u=!1,u)},hr=(n,e,t,s,r,i,o)=>{const{labels:a,fields:l}=t,c=i?.collections?.[a.collection];let d=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!Se("Create",c)&&(d=!1),r&&!at("Create",t,s,r,i,n)&&(d=!1),t.auth&&o&&(r&&!zn(c)&&(d=!1),Vs("create",n,e,t,s,r,i,o)||(d=!1));for(const m of l){const u=n[m.name];m.access&&!Zn(m,i)&&u!==void 0&&(d=!1),u!==void 0&&!Go(m,i)&&(d=!1)}if(!d)throw new Error("PERMISSION_DENIED")},be=n=>n&&(n._methodName==="deleteField"||n.constructor.name==="DeleteTransform"),rt=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(be(n[e])?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&rt(n[e]))},mr=(n,e,t,s,r,i,o,a,l,c)=>{const{labels:d,fields:m}=s,u=o?.collections?.[d.collection],f={...e,...n};rt(f);let g=!0,v="";if(i&&!u)throw new Error("PERMISSION_DENIED");i&&!Se("Update",u)&&(g=!1,v="Authenticated user does not have Update access to this collection"),i&&(!at("Update",s,r,i,o,e)||!at("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]&&!Se("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"),Vs("update",f,t,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=n[y.name];y.access&&!Zn(y,o)&&w!==void 0&&(v=`Authenticated user does not have access to field ${y.name}`,g=!1),w!==void 0&&!fi(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")},ea=(n,e,t,s,r,i)=>{const{labels:o}=t,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(Se("Delete",a)||(l=!1),at("Delete",t,s,r,i,n)||(l=!1),t.auth&&n.User_ID&&(zn(a)||(l=!1),Vs("delete",n,e,t,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},ta=async(n,e,t,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Se("Read",o)||(a=!1),at("Read",e,t,s,r,n)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},na=async(n,e,t,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(Se("Read",o)||(a=!1),n.forEach(l=>{at("Read",e,t,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},sa=(n,e,t)=>{const{access:s}=n;return s.operations[t]?.includes(e)},ra=(n,e,t)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===n)&&!("singleQuery"in i&&i.singleQuery))return`${i.type} entity restriction`}if(r?.parentFilters)for(const i of r.parentFilters){if(!i.roles.some(c=>c.role===n))continue;const o=U(e.fields,i.collectionField);if(!ee(o))throw new Error("PERMISSION_DENIED");const l=t.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(d=>d.role===n));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},ia=(n,e,t,s,r)=>{const i={};for(const o of n){const l=e[o].default({sdk:t,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},Ae=(n,e)=>e.fields.filter(t=>t.name===n.name)[0],Xn={global:{},collections:{}},Bt=(n,e)=>n&&typeof n=="function"?e?n(...e):n():n,oe=async(n,e)=>{let t=n;return n&&(typeof n=="function"||typeof n.then=="function")&&(e?t=await n(...e):t=await n()),t},oa=async(n,e,t,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=Xn,i=!0;for(const d of e){if(d===void 0||r[d]===void 0){i=!1;break}r=r[d]}if(r&&i&&!s)return r;let o,a=n,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await oe(a,t)),c){let d=Xn;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?Bo(m,e.join("."),c):(d[f]||={},d=d[f])}}qo(Xn,m)}return c},ut=(n,e,t)=>{const s=Object.values(t.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(ee(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field===n.name&&(i=!0)}return i},gi=(n,e)=>{const t=Object.values(e.collections),{labels:s}=n,r={};return t.forEach(i=>{const{labels:o,fields:a}=i;a.forEach(l=>{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},es=n=>JSON.stringify(n.map(e=>e.name)),yt=["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"],qn=()=>yt.map(n=>{let e="",t;switch(n){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",t=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:n,type:e,required:!0};return t&&(s.values=t),s}),wi=(n,e)=>{const t=[],{access:s,fields:r}=n,{attributeRestrictions:i,entityRestrictions:o}=s,a=qn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":t.push(U(a,"Created_By"));break;case"Record_User":t.push(U(r,l.collectionField));break;case"Record_Property":t.push(U(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(U(a,"id"));break;case"Parent":t.push(U(r,l.collectionField));break;case"Parent_Property":t.push(U(r,l.collectionField)),t.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":t.push(U(r,l.collectionField));break;case"Parent":t.push(U(r,l.parentCollectionField));break;case"Parent_Property":t.push(U(r,l.parentCollectionField)),t.push(U(r,l.parentPropertyField));break}})),[...new Set(t)]},aa=(n,e)=>{const t=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=n,a=qn();return t.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{(!c.access||c.access.includes(e))&&t.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{t.push(U(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{yt.includes(c)&&t.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))&&yt.includes(c.field)&&t.push(U(a,c.field))}),wi(n,e).forEach(c=>{yt.includes(c.name)&&t.push(U(a,c.name))}),[...new Set(t)]},la=(n,e,t)=>{const s=[],{fields:r,preloadCache:i}=e,o=qn();i?.range&&i.range.fields.forEach(c=>{yt.includes(c)?s.push(U(o,c)):s.push(U(r,c))});const a=new Set,l=gi(e,t);return Object.entries(l).map(([c,d])=>{n.name===c&&Object.values(d).forEach(m=>{m.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(...wi(e,c))}),[...new Set(s)]},fn=(n,e,t)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=gi(e,t);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{t.collections[c].fields.forEach(m=>{ee(m)&&m.collection===e.labels.collection&&m.dependencyFields?.some(u=>u.field===n.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(...la(n,e,t)),[...new Set(s)]},_i=(n,e)=>{const{preloadCache:t}=n,s=new Set;for(const r of e.config.roles){if(!sa(n,r,"read"))continue;const i=aa(n,r);let o=!1;if(s.size===0)s.add({key:"1",roles:[r],fields:i}),o=!0;else for(const a of s)i.length===a.fields.length&&i.every(l=>a.fields.some(c=>c.name===l.name))&&!!t?.roles.includes(r)==!!a.roles.every(l=>t?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},Ei=(n,e,t)=>{const s=_i(e,t);for(const r of s.values())if(r.roles.includes(n))return r},ca=(n,e)=>{const{fields:t}=e,s=qn(),r=[];return[...t,...s.filter(o=>o.name!=="id")].forEach(o=>{n?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Us=(n,e,t)=>{const s={};return Object.values(n.collections).forEach(r=>{const i=_i(r,n),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},Sn=n=>({Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_Version:n.Last_Write_Version,Last_Write_App:n.Last_Write_App,Last_Save_At:n.Last_Save_At}),ts=async(n,e,t)=>{if(e){const s=await oe(e,[t]);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${n}`);return s}};async function ae(n,e,t,s){const r=await ts(n,t.custom?.[n],s);for(const i of t.fields)await ts(n,i.custom?.[n],s);if(n!=="setEmbedding"&&(await ts(n,e?.[n],s),n==="postWriteError"))return r}const Ws=(n,e,t,s,r,i,o,a,l,c)=>(n==="create"&&(t.Collection_Path=e,t.Created_At=a,t.Saved_At=l,t.Created_By=o||"System"),t.Last_Write_App=r,t.Last_Write_At=a,t.Last_Save_At=l,t.Last_Write_By=o||"System",t.Last_Write_Connection_Status=i,t.Last_Write_Version=s.version,t),ht=(n,e)=>{const{access:t,queries:s}=n,{serverReadOnly:r}=t,i=new Set;if(s)for(const o of s){const a=U(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},Et=(n,e)=>{const{access:t,recordTitleField:s}=n,{serverReadOnly:r}=t,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},Rn=(n,e,t)=>{const{fields:s}=n;s.forEach(i=>{if(ee(i))if(e[i.name]){if(be(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=t.collections[i.collection],l=U(a.fields,o);Et(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`]}),ht(n,s).forEach(i=>{if(e[i.name])if(be(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}}}})},In=(n,e)=>{Et(n,n.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},ua=async(n,e,t,s)=>{const{fields:r}=e;for(const i of t.fields){const o=U(r,i.name);i.custom?.initialValue!==void 0&&!(s&&o.access&&!o.access.includes(s))&&(n[i.name]=await oe(i.custom.initialValue,[n]),Et(e,[o]).size===1&&(n[`${i.name}_Lowercase`]=n[i.name].toLowerCase()))}for(const i of r)s&&i.access&&!i.access.includes(s)||("autoIncrement"in i&&i.autoIncrement&&!n[i.name]&&(n[i.name]="Pending"),!ee(i)&&i.nullable&&n[i.name]===void 0&&(n[i.name]=null))};var se;(function(n){n.assertEqual=r=>{};function e(r){}n.assertIs=e;function t(r){throw new Error}n.assertNever=t,n.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},n.getValidEnumValues=r=>{const i=n.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return n.objectValues(o)},n.objectValues=r=>n.objectKeys(r).map(function(i){return r[i]}),n.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},n.find=(r,i)=>{for(const o of r)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=s,n.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(se||(se={}));var pr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(pr||(pr={}));const V=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tt=n=>{switch(typeof n){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(n)?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(n)?V.array:n===null?V.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?V.promise:typeof Map<"u"&&n instanceof Map?V.map:typeof Set<"u"&&n instanceof Set?V.set:typeof Date<"u"&&n instanceof Date?V.date:V.object;default:return V.unknown}},D=se.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Ke extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(t(o));else{let a=s,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof Ke))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}Ke.create=n=>new Ke(n);const ws=(n,e)=>{let t;switch(n.code){case D.invalid_type:n.received===V.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case D.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,se.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:t=`Unrecognized key(s) in object: ${se.joinValues(n.keys,", ")}`;break;case D.invalid_union:t="Invalid input";break;case D.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${se.joinValues(n.options)}`;break;case D.invalid_enum_value:t=`Invalid enum value. Expected ${se.joinValues(n.options)}, received '${n.received}'`;break;case D.invalid_arguments:t="Invalid function arguments";break;case D.invalid_return_type:t="Invalid function return type";break;case D.invalid_date:t="Invalid date";break;case D.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:se.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case D.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case D.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case D.custom:t="Invalid input";break;case D.invalid_intersection_types:t="Intersection results could not be merged";break;case D.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case D.not_finite:t="Number must be finite";break;default:t=e.defaultError,se.assertNever(n)}return{message:t}};let da=ws;function fa(){return da}const ha=n=>{const{data:e,path:t,errorMaps:s,issueData:r}=n,i=[...t,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)a=c(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function P(n,e){const t=fa(),s=ha({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ws?void 0:ws].filter(r=>!!r)});n.common.issues.push(s)}class _e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if(r.status==="aborted")return Q;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const r of t){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return _e.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return 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"}),Ht=n=>({status:"dirty",value:n}),Ce=n=>({status:"valid",value:n}),yr=n=>n.status==="aborted",gr=n=>n.status==="dirty",Ct=n=>n.status==="valid",xn=n=>typeof Promise<"u"&&n instanceof Promise;var W;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(W||(W={}));class ze{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const wr=(n,e)=>{if(Ct(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Ke(n.common.issues);return this._error=t,this._error}}};function X(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:r}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=n;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:r}}class te{get description(){return this._def.description}_getType(e){return tt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new _e,ctx:{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(xn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)},r=this._parseSync({data:e,path:s.path,parent:s});return wr(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return Ct(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>Ct(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(xn(r)?r:Promise.resolve(r));return wr(s,i)}refine(e,t){const s=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:D.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof t=="function"?t(s,r):t),!1))}_refinement(e){return new Mt({schema:this,typeName:J.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return it.create(this,this._def)}nullable(){return Pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ue.create(this)}promise(){return Fn.create(this,this._def)}or(e){return Dn.create([this,e],this._def)}and(e){return An.create(this,e,this._def)}transform(e){return new Mt({...X(this._def),schema:this,typeName:J.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new bs({...X(this._def),innerType:this,defaultValue:t,typeName:J.ZodDefault})}brand(){return new Ma({typeName:J.ZodBranded,type:this,...X(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ts({...X(this._def),innerType:this,catchValue:t,typeName:J.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return js.create(this,e)}readonly(){return Ss.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ma=/^c[^\s-]{8,}$/i,pa=/^[0-9a-z]+$/,ya=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ga=/^[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,wa=/^[a-z0-9_-]{21}$/i,_a=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ea=/^[-+]?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)?)??$/,va=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Oa="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ns;const ka=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ba=/^(?:(?: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])$/,Ta=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Sa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ra=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ia=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vi="((\\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])))",xa=new RegExp(`^${vi}$`);function Oi(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Na(n){return new RegExp(`^${Oi(n)}$`)}function Da(n){let e=`${vi}T${Oi(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Aa(n,e){return!!((e==="v4"||!e)&&ka.test(n)||(e==="v6"||!e)&&Ta.test(n))}function Ca(n,e){if(!_a.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Fa(n,e){return!!((e==="v4"||!e)&&ba.test(n)||(e==="v6"||!e)&&Sa.test(n))}class Qe extends te{_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}),Q}const s=new _e;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),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")va.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")ns||(ns=new RegExp(Oa,"u")),ns.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")ga.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")wa.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")ma.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")pa.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")ya.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"?Da(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"?xa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:D.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Na(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"?Ea.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"duration",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Aa(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"?Ca(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"?Fa(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"?Ra.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?Ia.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64url",code:D.invalid_string,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}_regex(e,t,s){return this.refinement(r=>e.test(r),{validation:t,code:D.invalid_string,...W.errToObj(s)})}_addCheck(e){return new Qe({...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,t){return this._addCheck({kind:"regex",regex:e,...W.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...W.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...W.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...W.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...W.errToObj(t)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Qe({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Qe.create=n=>new Qe({checks:[],typeName:J.ZodString,coerce:n?.coerce??!1,...X(n)});function $a(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=t>s?t:s,i=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Ft 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)!==V.number){const i=this._getOrReturnCtx(e);return P(i,{code:D.invalid_type,expected:V.number,received:i.parsedType}),Q}let s;const r=new _e;for(const i of this._def.checks)i.kind==="int"?se.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"?$a(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()):se.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(e,t,s,r){return new Ft({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:W.toString(r)}]})}_addCheck(e){return new Ft({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&se.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Ft.create=n=>new Ft({checks:[],typeName:J.ZodNumber,coerce:n?.coerce||!1,...X(n)});class tn 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)!==V.bigint)return this._getInvalidInput(e);let s;const r=new _e;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(s=this._getOrReturnCtx(e,s),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()):se.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return P(t,{code:D.invalid_type,expected:V.bigint,received:t.parsedType}),Q}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(e,t,s,r){return new tn({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:W.toString(r)}]})}_addCheck(e){return new tn({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}tn.create=n=>new tn({checks:[],typeName:J.ZodBigInt,coerce:n?.coerce??!1,...X(n)});class _s extends te{_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}),Q}return Ce(e.data)}}_s.create=n=>new _s({typeName:J.ZodBoolean,coerce:n?.coerce||!1,...X(n)});class Nn extends te{_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}),Q}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return P(i,{code:D.invalid_date}),Q}const s=new _e;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),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()):se.assertNever(i);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Nn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:W.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Nn.create=n=>new Nn({checks:[],coerce:n?.coerce||!1,typeName:J.ZodDate,...X(n)});class _r extends te{_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}),Q}return Ce(e.data)}}_r.create=n=>new _r({typeName:J.ZodSymbol,...X(n)});class Es extends te{_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}),Q}return Ce(e.data)}}Es.create=n=>new Es({typeName:J.ZodUndefined,...X(n)});class Er extends te{_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}),Q}return Ce(e.data)}}Er.create=n=>new Er({typeName:J.ZodNull,...X(n)});class vs extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return Ce(e.data)}}vs.create=n=>new vs({typeName:J.ZodAny,...X(n)});class vr extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ce(e.data)}}vr.create=n=>new vr({typeName:J.ZodUnknown,...X(n)});class lt extends te{_parse(e){const t=this._getOrReturnCtx(e);return P(t,{code:D.invalid_type,expected:V.never,received:t.parsedType}),Q}}lt.create=n=>new lt({typeName:J.ZodNever,...X(n)});class Or extends te{_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}),Q}return Ce(e.data)}}Or.create=n=>new Or({typeName:J.ZodVoid,...X(n)});class Ue extends te{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==V.array)return P(t,{code:D.invalid_type,expected:V.array,received:t.parsedType}),Q;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(P(t,{code:o?D.too_big:D.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(P(t,{code:D.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(P(t,{code:D.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new ze(t,o,t.path,a)))).then(o=>_e.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new ze(t,o,t.path,a)));return _e.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new Ue({...this._def,minLength:{value:e,message:W.toString(t)}})}max(e,t){return new Ue({...this._def,maxLength:{value:e,message:W.toString(t)}})}length(e,t){return new Ue({...this._def,exactLength:{value:e,message:W.toString(t)}})}nonempty(e){return this.min(1,e)}}Ue.create=(n,e)=>new Ue({type:n,minLength:null,maxLength:null,exactLength:null,typeName:J.ZodArray,...X(e)});function Rt(n){if(n instanceof ue){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=it.create(Rt(s))}return new ue({...n._def,shape:()=>e})}else return n instanceof Ue?new Ue({...n._def,type:Rt(n.element)}):n instanceof it?it.create(Rt(n.unwrap())):n instanceof Pt?Pt.create(Rt(n.unwrap())):n instanceof gt?gt.create(n.items.map(e=>Rt(e))):n}class ue 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(),t=se.objectKeys(e);return this._cached={shape:e,keys:t},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}),Q}const{status:s,ctx:r}=this._processInputParams(e),{shape:i,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof lt&&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 lt){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=>_e.mergeObjectSync(s,c)):_e.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return W.errToObj,new ue({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const r=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:W.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new ue({...this._def,unknownKeys:"strip"})}passthrough(){return new ue({...this._def,unknownKeys:"passthrough"})}extend(e){return new ue({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ue({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:J.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ue({...this._def,catchall:e})}pick(e){const t={};for(const s of se.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new ue({...this._def,shape:()=>t})}omit(e){const t={};for(const s of se.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new ue({...this._def,shape:()=>t})}deepPartial(){return Rt(this)}partial(e){const t={};for(const s of se.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new ue({...this._def,shape:()=>t})}required(e){const t={};for(const s of se.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof it;)i=i._def.innerType;t[s]=i}return new ue({...this._def,shape:()=>t})}keyof(){return ki(se.objectKeys(this.shape))}}ue.create=(n,e)=>new ue({shape:()=>n,unknownKeys:"strip",catchall:lt.create(),typeName:J.ZodObject,...X(e)});ue.strictCreate=(n,e)=>new ue({shape:()=>n,unknownKeys:"strict",catchall:lt.create(),typeName:J.ZodObject,...X(e)});ue.lazycreate=(n,e)=>new ue({shape:n,unknownKeys:"strip",catchall:lt.create(),typeName:J.ZodObject,...X(e)});class Dn extends te{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Ke(a.ctx.common.issues));return P(t,{code:D.invalid_union,unionErrors:o}),Q}if(t.common.async)return Promise.all(s.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new Ke(l));return P(t,{code:D.invalid_union,unionErrors:a}),Q}}get options(){return this._def.options}}Dn.create=(n,e)=>new Dn({options:n,typeName:J.ZodUnion,...X(e)});function Os(n,e){const t=tt(n),s=tt(e);if(n===e)return{valid:!0,data:n};if(t===V.object&&s===V.object){const r=se.objectKeys(e),i=se.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(const a of i){const l=Os(n[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===V.array&&s===V.array){if(n.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<n.length;i++){const o=n[i],a=e[i],l=Os(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return t===V.date&&s===V.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class An extends te{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(yr(i)||yr(o))return Q;const a=Os(i.value,o.value);return a.valid?((gr(i)||gr(o))&&t.dirty(),{status:t.value,value:a.data}):(P(s,{code:D.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}))}}An.create=(n,e,t)=>new An({left:n,right:e,typeName:J.ZodIntersection,...X(t)});class gt extends te{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.array)return P(s,{code:D.invalid_type,expected:V.array,received:s.parsedType}),Q;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"}),Q;!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"}),t.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=>_e.mergeArray(t,o)):_e.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new gt({...this._def,rest:e})}}gt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gt({items:n,typeName:J.ZodTuple,rest:null,...X(e)})};class Cn extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.object)return P(s,{code:D.invalid_type,expected:V.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 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?_e.mergeObjectAsync(t,r):_e.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof te?new Cn({keyType:e,valueType:t,typeName:J.ZodRecord,...X(s)}):new Cn({keyType:Qe.create(),valueType:e,typeName:J.ZodRecord,...X(t)})}}class kr extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.map)return P(s,{code:D.invalid_type,expected:V.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 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 Q;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return Q;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}}}}kr.create=(n,e,t)=>new kr({valueType:e,keyType:n,typeName:J.ZodMap,...X(t)});class nn extends te{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==V.set)return P(s,{code:D.invalid_type,expected:V.set,received:s.parsedType}),Q;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}),t.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}),t.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"&&t.dirty(),c.add(d.value)}return{status:t.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,t){return new nn({...this._def,minSize:{value:e,message:W.toString(t)}})}max(e,t){return new nn({...this._def,maxSize:{value:e,message:W.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}nn.create=(n,e)=>new nn({valueType:n,minSize:null,maxSize:null,typeName:J.ZodSet,...X(e)});class br extends te{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}br.create=(n,e)=>new br({getter:n,typeName:J.ZodLazy,...X(e)});class ks extends te{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}}ks.create=(n,e)=>new ks({value:n,typeName:J.ZodLiteral,...X(e)});function ki(n,e){return new $t({values:n,typeName:J.ZodEnum,...X(e)})}class $t extends te{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return P(t,{expected:se.joinValues(s),received:t.parsedType,code:D.invalid_type}),Q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return P(t,{received:t.data,code:D.invalid_enum_value,options:s}),Q}return Ce(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return $t.create(e,{...this._def,...t})}exclude(e,t=this._def){return $t.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}$t.create=ki;class Tr extends te{_parse(e){const t=se.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==V.string&&s.parsedType!==V.number){const r=se.objectValues(t);return P(s,{expected:se.joinValues(r),received:s.parsedType,code:D.invalid_type}),Q}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=se.objectValues(t);return P(s,{received:s.data,code:D.invalid_enum_value,options:r}),Q}return Ce(e.data)}get enum(){return this._def.values}}Tr.create=(n,e)=>new Tr({values:n,typeName:J.ZodNativeEnum,...X(e)});class Fn extends te{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==V.promise&&t.common.async===!1)return P(t,{code:D.invalid_type,expected:V.promise,received:t.parsedType}),Q;const s=t.parsedType===V.promise?t.data:Promise.resolve(t.data);return Ce(s.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Fn.create=(n,e)=>new Fn({type:n,typeName:J.ZodPromise,...X(e)});class Mt extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===J.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{P(s,o),o.fatal?t.abort():t.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return Q;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?Q:l.status==="dirty"||t.value==="dirty"?Ht(l.value):l});{if(t.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"||t.value==="dirty"?Ht(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"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?Q:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Ct(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:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Ct(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):Q);se.assertNever(r)}}Mt.create=(n,e,t)=>new Mt({schema:n,typeName:J.ZodEffects,effect:e,...X(t)});Mt.createWithPreprocess=(n,e,t)=>new Mt({schema:e,effect:{type:"preprocess",transform:n},typeName:J.ZodEffects,...X(t)});class it extends te{_parse(e){return this._getType(e)===V.undefined?Ce(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}it.create=(n,e)=>new it({innerType:n,typeName:J.ZodOptional,...X(e)});class Pt extends te{_parse(e){return this._getType(e)===V.null?Ce(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Pt.create=(n,e)=>new Pt({innerType:n,typeName:J.ZodNullable,...X(e)});class bs extends te{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===V.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}bs.create=(n,e)=>new bs({innerType:n,typeName:J.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});class Ts extends te{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return xn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ke(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Ke(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ts.create=(n,e)=>new Ts({innerType:n,typeName:J.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});class Sr extends te{_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}),Q}return{status:"valid",value:e.data}}}Sr.create=n=>new Sr({typeName:J.ZodNaN,...X(n)});class Ma extends te{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class js extends te{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?Q:i.status==="dirty"?(t.dirty(),Ht(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"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,t){return new js({in:e,out:t,typeName:J.ZodPipeline})}}class Ss extends te{_parse(e){const t=this._def.innerType._parse(e),s=r=>(Ct(r)&&(r.value=Object.freeze(r.value)),r);return xn(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}Ss.create=(n,e)=>new Ss({innerType:n,typeName:J.ZodReadonly,...X(e)});var J;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(J||(J={}));const Te=Qe.create,mt=Ft.create,Xt=_s.create,ss=Es.create,me=vs.create;lt.create;const vt=Ue.create,We=ue.create,Oe=Dn.create;An.create;gt.create;const on=Cn.create,ke=ks.create,$n=$t.create;Fn.create;it.create;Pt.create;const _n=()=>me().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),Rr=()=>me().refine(n=>n&&(n._methodName==="serverTimestamp"||n.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),bi=(n,e,t)=>{const s={};if(n.includeFields){const i=e.collections[n.collection];if(!i)return on(me());n.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${n.collection}`);s[o]=Mn(i,a),Et(i,[a]).size===1&&(s[`${o}_Lowercase`]=Mn(i,a,!0))})}const r={Collection_Path:vt(Te()),...s};return t&&(r.id=Te().length(20)),We(r)},Pa=(n,e)=>{let t=on(bi(n,e));return n.required||(t=t.optional()),t},La=n=>{let e=vt(Oe([Te().length(20),Te().length(28)]));return["OneToOne","OneToMany"].includes(n.type)?e=e.max(1):(n.min&&(e=e.min(n.min)),n.max&&(e=e.max(n.max)),n.length&&(e=e.length(n.length))),n.required?e=e.nonempty():e=e.optional(),e},Mn=(n,e,t)=>{const{softDelete:s}=n,r=s?.timestampField;let i;switch(e.type){case"String":if(i=Te(),e.length&&(i=i.length(e.length)),e.minlength&&(i=i.min(e.minlength)),e.maxlength&&(i=i.max(e.maxlength)),e.email&&(i=i.email()),e.uuid&&(i=i.uuid()),e.url&&(i=i.url()),e.emoji&&(i=i.emoji()),e.ip&&(i=i.ip()),e.pattern&&(i=i.regex(new RegExp(e.pattern))),t&&(i=i.toLowerCase()),e.values)if(t){const o=e.values.map(a=>a.toLowerCase());i=$n(o)}else i=$n(e.values);break;case"Boolean":i=Xt();break;case"Number":e.autoIncrement?i=Oe([ke("Pending"),mt().int()]):(i=mt(),e.min&&(i=i.min(e.min)),e.max&&(i=i.max(e.max)),e.decimal?i=i.refine(o=>e.decimal?(o.toString().split(".")[1]?.length||0)<=e.decimal:!1,{message:`Value must have ${e.decimal} or fewer decimal places`}):i=i.int(),e.values&&(i=i.refine(o=>e.values?.includes(o),{message:"Value is not an allowed value"})));break;case"Timestamp":e.name===r?i=me().refine(o=>o&&(o._methodName==="serverTimestamp"||o.constructor.name==="ServerTimestampTransform"||o.seconds!==void 0&&o.nanoseconds!==void 0||o._seconds!==void 0&&o._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}):(i=_n(),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=vt(me()),e.length&&(i=i.length(e.length)),e.minlength?i=i.min(e.minlength):e.required&&(i=i.nonempty()),e.maxlength&&(i=i.max(e.maxlength)),e.values&&(i=i.refine(o=>{let a=!0;return o.forEach(l=>{e.values&&!e.values.includes(l)&&(a=!1)}),a},{message:"Value is not an allowed value"}));break;case"Map":i=on(me()),e.required&&(i=i.refine(o=>o&&typeof o=="object"&&Object.keys(o).length>0,{message:"Value must have at least one object property"}));break;case"Embedding":i=me();break}return!ee(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},Ti=(n,e,t)=>{const s={Collection_Path:vt(Te()),Last_Write_App:Te(),Last_Write_At:_n(),Last_Save_At:Rr(),Last_Write_By:Oe([Te().length(28),ke("System")]),Last_Write_Connection_Status:$n(["Online","Offline"]),Last_Write_Version:mt().int(),id:Te().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:_n(),Created_By:Oe([Te().length(28),ke("System")])};n==="create"&&(s.Saved_At=Rr()),n==="update"&&(s.Saved_At=_n(),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=ht(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{ee(l)?(s[l.name]=Pa(l,t),s[`${l.name}_Array`]=La(l),i.includes(l.name)&&(s[`${l.name}_Single`]=bi(l,t,!0),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=Mn(e,l))}),Et(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=Mn(e,l,!0))});const a=We(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class Ot extends Error{}class Va extends Ot{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Ua extends Ot{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class Wa extends Ot{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class It extends Ot{}class Si extends Ot{constructor(e){super(`Invalid unit ${e}`)}}class pe extends Ot{}class et extends Ot{constructor(){super("Zone is an abstract class")}}const $="numeric",Pe="short",Re="long",Pn={year:$,month:$,day:$},Ri={year:$,month:Pe,day:$},ja={year:$,month:Pe,day:$,weekday:Pe},Ii={year:$,month:Re,day:$},xi={year:$,month:Re,day:$,weekday:Re},Ni={hour:$,minute:$},Di={hour:$,minute:$,second:$},Ai={hour:$,minute:$,second:$,timeZoneName:Pe},Ci={hour:$,minute:$,second:$,timeZoneName:Re},Fi={hour:$,minute:$,hourCycle:"h23"},$i={hour:$,minute:$,second:$,hourCycle:"h23"},Mi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:Pe},Pi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:Re},Li={year:$,month:$,day:$,hour:$,minute:$},Vi={year:$,month:$,day:$,hour:$,minute:$,second:$},Ui={year:$,month:Pe,day:$,hour:$,minute:$},Wi={year:$,month:Pe,day:$,hour:$,minute:$,second:$},za={year:$,month:Pe,day:$,weekday:Pe,hour:$,minute:$},ji={year:$,month:Re,day:$,hour:$,minute:$,timeZoneName:Pe},zi={year:$,month:Re,day:$,hour:$,minute:$,second:$,timeZoneName:Pe},Zi={year:$,month:Re,day:$,weekday:Re,hour:$,minute:$,timeZoneName:Re},qi={year:$,month:Re,day:$,weekday:Re,hour:$,minute:$,second:$,timeZoneName:Re};class an{get type(){throw new et}get name(){throw new et}get ianaName(){return this.name}get isUniversal(){throw new et}offsetName(e,t){throw new et}formatOffset(e,t){throw new et}offset(e){throw new et}equals(e){throw new et}get isValid(){throw new et}}let rs=null;class Bn extends an{static get instance(){return rs===null&&(rs=new Bn),rs}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return no(e,t,s)}formatOffset(e,t){return en(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Rs=new Map;function Za(n){let e=Rs.get(n);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Rs.set(n,e)),e}const qa={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Ba(n,e){const t=n.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,r,i,o,a,l,c,d]=s;return[o,r,i,a,l,c,d]}function Ha(n,e){const t=n.formatToParts(e),s=[];for(let r=0;r<t.length;r++){const{type:i,value:o}=t[r],a=qa[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const is=new Map;class Xe extends an{static create(e){let t=is.get(e);return t===void 0&&is.set(e,t=new Xe(e)),t}static resetCache(){is.clear(),Rs.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=Xe.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:s}){return no(e,t,s,this.name)}formatOffset(e,t){return en(this.offset(e),t)}offset(e){if(!this.valid)return NaN;const t=new Date(e);if(isNaN(t))return NaN;const s=Za(this.name);let[r,i,o,a,l,c,d]=s.formatToParts?Ha(s,t):Ba(s,t);a==="BC"&&(r=-Math.abs(r)+1);const u=Gn({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:d,millisecond:0});let f=+t;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 Ir={};function Ga(n,e={}){const t=JSON.stringify([n,e]);let s=Ir[t];return s||(s=new Intl.ListFormat(n,e),Ir[t]=s),s}const Is=new Map;function xs(n,e={}){const t=JSON.stringify([n,e]);let s=Is.get(t);return s===void 0&&(s=new Intl.DateTimeFormat(n,e),Is.set(t,s)),s}const Ns=new Map;function Ya(n,e={}){const t=JSON.stringify([n,e]);let s=Ns.get(t);return s===void 0&&(s=new Intl.NumberFormat(n,e),Ns.set(t,s)),s}const Ds=new Map;function Ja(n,e={}){const{base:t,...s}=e,r=JSON.stringify([n,s]);let i=Ds.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(n,e),Ds.set(r,i)),i}let Gt=null;function Qa(){return Gt||(Gt=new Intl.DateTimeFormat().resolvedOptions().locale,Gt)}const As=new Map;function Bi(n){let e=As.get(n);return e===void 0&&(e=new Intl.DateTimeFormat(n).resolvedOptions(),As.set(n,e)),e}const Cs=new Map;function Ka(n){let e=Cs.get(n);if(!e){const t=new Intl.Locale(n);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,"minimalDays"in e||(e={...Hi,...e}),Cs.set(n,e)}return e}function Xa(n){const e=n.indexOf("-x-");e!==-1&&(n=n.substring(0,e));const t=n.indexOf("-u-");if(t===-1)return[n];{let s,r;try{s=xs(n).resolvedOptions(),r=n}catch{const l=n.substring(0,t);s=xs(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function el(n,e,t){return(t||e)&&(n.includes("-u-")||(n+="-u"),t&&(n+=`-ca-${t}`),e&&(n+=`-nu-${e}`)),n}function tl(n){const e=[];for(let t=1;t<=12;t++){const s=L.utc(2009,t,1);e.push(n(s))}return e}function nl(n){const e=[];for(let t=1;t<=7;t++){const s=L.utc(2016,11,13+t);e.push(n(s))}return e}function hn(n,e,t,s){const r=n.listingMode();return r==="error"?null:r==="en"?t(e):s(e)}function sl(n){return n.numberingSystem&&n.numberingSystem!=="latn"?!1:n.numberingSystem==="latn"||!n.locale||n.locale.startsWith("en")||Bi(n.locale).numberingSystem==="latn"}class rl{constructor(e,t,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!t||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=Ya(e,a)}}format(e){if(this.inf){const t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{const t=this.floor?Math.floor(e):Hs(e,3);return de(t,this.padTo)}}}class il{constructor(e,t,s){this.opts=s,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&Xe.create(a).valid?(r=a,this.dt=e):(r="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,r=e.zone.name):(r="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const i={...this.opts};i.timeZone=i.timeZone||r,this.dtf=xs(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:s}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class ol{constructor(e,t,s){this.opts={style:"long",...s},!t&&eo()&&(this.rtf=Ja(e,s))}format(e,t){return this.rtf?this.rtf.format(e,t):Il(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}}const Hi={firstDay:1,minimalDays:4,weekend:[6,7]};class ie{static fromOpts(e){return ie.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,s,r,i=!1){const o=e||ce.defaultLocale,a=o||(i?"en-US":Qa()),l=t||ce.defaultNumberingSystem,c=s||ce.defaultOutputCalendar,d=$s(r)||ce.defaultWeekSettings;return new ie(a,l,c,d,o)}static resetCache(){Gt=null,Is.clear(),Ns.clear(),Ds.clear(),As.clear(),Cs.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:r}={}){return ie.create(e,t,s,r)}constructor(e,t,s,r,i){const[o,a,l]=Xa(e);this.locale=o,this.numberingSystem=t||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=el(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=sl(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:ie.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,$s(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return hn(this,e,io,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");t&=!s;const r=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";if(!this.monthsCache[i][e]){const o=s?a=>this.dtFormatter(a,r).format():a=>this.extract(a,r,"month");this.monthsCache[i][e]=tl(o)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return hn(this,e,lo,()=>{const s=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=t?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=nl(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return hn(this,void 0,()=>co,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[L.utc(2016,11,13,9),L.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return hn(this,e,uo,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[L.utc(-40,1,1),L.utc(2017,1,1)].map(s=>this.extract(s,t,"era"))),this.eraCache[e]})}extract(e,t,s){const r=this.dtFormatter(e,t),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new rl(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new il(e,this.intl,t)}relFormatter(e={}){return new ol(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Ga(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||Bi(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:to()?Ka(this.locale):Hi}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let os=null;class we extends an{static get utcInstance(){return os===null&&(os=new we(0)),os}static instance(e){return e===0?we.utcInstance:new we(e)}static parseSpecifier(e){if(e){const t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new we(Yn(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${en(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${en(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return en(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class al extends an{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 st(n,e){if(G(n)||n===null)return e;if(n instanceof an)return n;if(hl(n)){const t=n.toLowerCase();return t==="default"?e:t==="local"||t==="system"?Bn.instance:t==="utc"||t==="gmt"?we.utcInstance:we.parseSpecifier(t)||Xe.create(n)}else return ot(n)?we.instance(n):typeof n=="object"&&"offset"in n&&typeof n.offset=="function"?n:new al(n)}const zs={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},xr={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},ll=zs.hanidec.replace(/[\[|\]]/g,"").split("");function cl(n){let e=parseInt(n,10);if(isNaN(e)){e="";for(let t=0;t<n.length;t++){const s=n.charCodeAt(t);if(n[t].search(zs.hanidec)!==-1)e+=ll.indexOf(n[t]);else for(const r in xr){const[i,o]=xr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const Fs=new Map;function ul(){Fs.clear()}function Fe({numberingSystem:n},e=""){const t=n||"latn";let s=Fs.get(t);s===void 0&&(s=new Map,Fs.set(t,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${zs[t]}${e}`),s.set(e,r)),r}let Nr=()=>Date.now(),Dr="system",Ar=null,Cr=null,Fr=null,$r=60,Mr,Pr=null;class ce{static get now(){return Nr}static set now(e){Nr=e}static set defaultZone(e){Dr=e}static get defaultZone(){return st(Dr,Bn.instance)}static get defaultLocale(){return Ar}static set defaultLocale(e){Ar=e}static get defaultNumberingSystem(){return Cr}static set defaultNumberingSystem(e){Cr=e}static get defaultOutputCalendar(){return Fr}static set defaultOutputCalendar(e){Fr=e}static get defaultWeekSettings(){return Pr}static set defaultWeekSettings(e){Pr=$s(e)}static get twoDigitCutoffYear(){return $r}static set twoDigitCutoffYear(e){$r=e%100}static get throwOnInvalid(){return Mr}static set throwOnInvalid(e){Mr=e}static resetCaches(){ie.resetCache(),Xe.resetCache(),L.resetCache(),ul()}}class Me{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Gi=[0,31,59,90,120,151,181,212,243,273,304,334],Yi=[0,31,60,91,121,152,182,213,244,274,305,335];function Ne(n,e){return new Me("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${n}, which is invalid`)}function Zs(n,e,t){const s=new Date(Date.UTC(n,e-1,t));n<100&&n>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function Ji(n,e,t){return t+(ln(n)?Yi:Gi)[e-1]}function Qi(n,e){const t=ln(n)?Yi:Gi,s=t.findIndex(i=>i<e),r=e-t[s];return{month:s+1,day:r}}function qs(n,e){return(n-e+7)%7+1}function Ln(n,e=4,t=1){const{year:s,month:r,day:i}=n,o=Ji(s,r,i),a=qs(Zs(s,r,i),t);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=sn(c,e,t)):l>sn(s,e,t)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...Jn(n)}}function Lr(n,e=4,t=1){const{weekYear:s,weekNumber:r,weekday:i}=n,o=qs(Zs(s,1,e),t),a=Dt(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=Dt(c)):l>a?(c=s+1,l-=Dt(s)):c=s;const{month:d,day:m}=Qi(c,l);return{year:c,month:d,day:m,...Jn(n)}}function as(n){const{year:e,month:t,day:s}=n,r=Ji(e,t,s);return{year:e,ordinal:r,...Jn(n)}}function Vr(n){const{year:e,ordinal:t}=n,{month:s,day:r}=Qi(e,t);return{year:e,month:s,day:r,...Jn(n)}}function Ur(n,e){if(!G(n.localWeekday)||!G(n.localWeekNumber)||!G(n.localWeekYear)){if(!G(n.weekday)||!G(n.weekNumber)||!G(n.weekYear))throw new It("Cannot mix locale-based week fields with ISO-based week fields");return G(n.localWeekday)||(n.weekday=n.localWeekday),G(n.localWeekNumber)||(n.weekNumber=n.localWeekNumber),G(n.localWeekYear)||(n.weekYear=n.localWeekYear),delete n.localWeekday,delete n.localWeekNumber,delete n.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function dl(n,e=4,t=1){const s=Hn(n.weekYear),r=De(n.weekNumber,1,sn(n.weekYear,e,t)),i=De(n.weekday,1,7);return s?r?i?!1:Ne("weekday",n.weekday):Ne("week",n.weekNumber):Ne("weekYear",n.weekYear)}function fl(n){const e=Hn(n.year),t=De(n.ordinal,1,Dt(n.year));return e?t?!1:Ne("ordinal",n.ordinal):Ne("year",n.year)}function Ki(n){const e=Hn(n.year),t=De(n.month,1,12),s=De(n.day,1,Vn(n.year,n.month));return e?t?s?!1:Ne("day",n.day):Ne("month",n.month):Ne("year",n.year)}function Xi(n){const{hour:e,minute:t,second:s,millisecond:r}=n,i=De(e,0,23)||e===24&&t===0&&s===0&&r===0,o=De(t,0,59),a=De(s,0,59),l=De(r,0,999);return i?o?a?l?!1:Ne("millisecond",r):Ne("second",s):Ne("minute",t):Ne("hour",e)}function G(n){return typeof n>"u"}function ot(n){return typeof n=="number"}function Hn(n){return typeof n=="number"&&n%1===0}function hl(n){return typeof n=="string"}function ml(n){return Object.prototype.toString.call(n)==="[object Date]"}function eo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function to(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function pl(n){return Array.isArray(n)?n:[n]}function Wr(n,e,t){if(n.length!==0)return n.reduce((s,r)=>{const i=[e(r),r];return s&&t(s[0],i[0])===s[0]?s:i},null)[1]}function yl(n,e){return e.reduce((t,s)=>(t[s]=n[s],t),{})}function Lt(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function $s(n){if(n==null)return null;if(typeof n!="object")throw new pe("Week settings must be an object");if(!De(n.firstDay,1,7)||!De(n.minimalDays,1,7)||!Array.isArray(n.weekend)||n.weekend.some(e=>!De(e,1,7)))throw new pe("Invalid week settings");return{firstDay:n.firstDay,minimalDays:n.minimalDays,weekend:Array.from(n.weekend)}}function De(n,e,t){return Hn(n)&&n>=e&&n<=t}function gl(n,e){return n-e*Math.floor(n/e)}function de(n,e=2){const t=n<0;let s;return t?s="-"+(""+-n).padStart(e,"0"):s=(""+n).padStart(e,"0"),s}function nt(n){if(!(G(n)||n===null||n===""))return parseInt(n,10)}function dt(n){if(!(G(n)||n===null||n===""))return parseFloat(n)}function Bs(n){if(!(G(n)||n===null||n==="")){const e=parseFloat("0."+n)*1e3;return Math.floor(e)}}function Hs(n,e,t="round"){const s=10**e;switch(t){case"expand":return n>0?Math.ceil(n*s)/s:Math.floor(n*s)/s;case"trunc":return Math.trunc(n*s)/s;case"round":return Math.round(n*s)/s;case"floor":return Math.floor(n*s)/s;case"ceil":return Math.ceil(n*s)/s;default:throw new RangeError(`Value rounding ${t} is out of range`)}}function ln(n){return n%4===0&&(n%100!==0||n%400===0)}function Dt(n){return ln(n)?366:365}function Vn(n,e){const t=gl(e-1,12)+1,s=n+(e-t)/12;return t===2?ln(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function Gn(n){let e=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return n.year<100&&n.year>=0&&(e=new Date(e),e.setUTCFullYear(n.year,n.month-1,n.day)),+e}function jr(n,e,t){return-qs(Zs(n,1,e),t)+e-1}function sn(n,e=4,t=1){const s=jr(n,e,t),r=jr(n+1,e,t);return(Dt(n)-s+r)/7}function Ms(n){return n>99?n:n>ce.twoDigitCutoffYear?1900+n:2e3+n}function no(n,e,t,s=null){const r=new Date(n),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(t,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function Yn(n,e){let t=parseInt(n,10);Number.isNaN(t)&&(t=0);const s=parseInt(e,10)||0,r=t<0||Object.is(t,-0)?-s:s;return t*60+r}function so(n){const e=Number(n);if(typeof n=="boolean"||n===""||!Number.isFinite(e))throw new pe(`Invalid unit value ${n}`);return e}function Un(n,e){const t={};for(const s in n)if(Lt(n,s)){const r=n[s];if(r==null)continue;t[e(s)]=so(r)}return t}function en(n,e){const t=Math.trunc(Math.abs(n/60)),s=Math.trunc(Math.abs(n%60)),r=n>=0?"+":"-";switch(e){case"short":return`${r}${de(t,2)}:${de(s,2)}`;case"narrow":return`${r}${t}${s>0?`:${s}`:""}`;case"techie":return`${r}${de(t,2)}${de(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Jn(n){return yl(n,["hour","minute","second","millisecond"])}const wl=["January","February","March","April","May","June","July","August","September","October","November","December"],ro=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],_l=["J","F","M","A","M","J","J","A","S","O","N","D"];function io(n){switch(n){case"narrow":return[..._l];case"short":return[...ro];case"long":return[...wl];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 oo=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],ao=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],El=["M","T","W","T","F","S","S"];function lo(n){switch(n){case"narrow":return[...El];case"short":return[...ao];case"long":return[...oo];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const co=["AM","PM"],vl=["Before Christ","Anno Domini"],Ol=["BC","AD"],kl=["B","A"];function uo(n){switch(n){case"narrow":return[...kl];case"short":return[...Ol];case"long":return[...vl];default:return null}}function bl(n){return co[n.hour<12?0:1]}function Tl(n,e){return lo(e)[n.weekday-1]}function Sl(n,e){return io(e)[n.month-1]}function Rl(n,e){return uo(e)[n.year<0?0:1]}function Il(n,e,t="always",s=!1){const r={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(n)===-1;if(t==="auto"&&i){const m=n==="days";switch(e){case 1:return m?"tomorrow":`next ${r[n][0]}`;case-1:return m?"yesterday":`last ${r[n][0]}`;case 0:return m?"today":`this ${r[n][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[n],d=s?l?c[1]:c[2]||c[1]:l?r[n][0]:n;return o?`${a} ${d} ago`:`in ${a} ${d}`}function zr(n,e){let t="";for(const s of n)s.literal?t+=s.val:t+=e(s.val);return t}const xl={D:Pn,DD:Ri,DDD:Ii,DDDD:xi,t:Ni,tt:Di,ttt:Ai,tttt:Ci,T:Fi,TT:$i,TTT:Mi,TTTT:Pi,f:Li,ff:Ui,fff:ji,ffff:Zi,F:Vi,FF:Wi,FFF:zi,FFFF:qi};class ye{static create(e,t={}){return new ye(e,t)}static parseFormat(e){let t=null,s="",r=!1;const i=[];for(let o=0;o<e.length;o++){const a=e.charAt(o);a==="'"?((s.length>0||r)&&i.push({literal:r||/^\s+$/.test(s),val:s===""?"'":s}),t=null,s="",r=!r):r||a===t?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,t=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return xl[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,s=void 0){if(this.opts.forceSimple)return de(e,t);const r={...this.opts};return t>0&&(r.padTo=t),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,t){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(f,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?bl(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,g)=>s?Sl(e,f):i(g?{month:f}:{month:f,day:"numeric"},"month"),c=(f,g)=>s?Tl(e,f):i(g?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),d=f=>{const g=ye.macroTokenToFormatOpts(f);return g?this.formatWithSystemDefault(e,g):f},m=f=>s?Rl(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(ye.parseFormat(t),u)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(d,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=ye.parseFormat(t),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 fo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Vt(...n){const e=n.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function Ut(...n){return e=>n.reduce(([t,s,r],i)=>{const[o,a,l]=i(e,r);return[{...t,...o},a||s,l]},[{},null,1]).slice(0,2)}function Wt(n,...e){if(n==null)return[null,null];for(const[t,s]of e){const r=t.exec(n);if(r)return s(r)}return[null,null]}function ho(...n){return(e,t)=>{const s={};let r;for(r=0;r<n.length;r++)s[n[r]]=nt(e[t+r]);return[s,null,t+r]}}const mo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Nl=`(?:${mo.source}?(?:\\[(${fo.source})\\])?)?`,Gs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,po=RegExp(`${Gs.source}${Nl}`),Ys=RegExp(`(?:[Tt]${po.source})?`),Dl=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Al=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Cl=/(\d{4})-?(\d{3})/,Fl=ho("weekYear","weekNumber","weekDay"),$l=ho("year","ordinal"),Ml=/(\d{4})-(\d\d)-(\d\d)/,yo=RegExp(`${Gs.source} ?(?:${mo.source}|(${fo.source}))?`),Pl=RegExp(`(?: ${yo.source})?`);function At(n,e,t){const s=n[e];return G(s)?t:nt(s)}function Ll(n,e){return[{year:At(n,e),month:At(n,e+1,1),day:At(n,e+2,1)},null,e+3]}function jt(n,e){return[{hours:At(n,e,0),minutes:At(n,e+1,0),seconds:At(n,e+2,0),milliseconds:Bs(n[e+3])},null,e+4]}function cn(n,e){const t=!n[e]&&!n[e+1],s=Yn(n[e+1],n[e+2]),r=t?null:we.instance(s);return[{},r,e+3]}function un(n,e){const t=n[e]?Xe.create(n[e]):null;return[{},t,e+1]}const Vl=RegExp(`^T?${Gs.source}$`),Ul=/^-?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 Wl(n){const[e,t,s,r,i,o,a,l,c]=n,d=e[0]==="-",m=l&&l[0]==="-",u=(f,g=!1)=>f!==void 0&&(g||f&&d)?-f:f;return[{years:u(dt(t)),months:u(dt(s)),weeks:u(dt(r)),days:u(dt(i)),hours:u(dt(o)),minutes:u(dt(a)),seconds:u(dt(l),l==="-0"),milliseconds:u(Bs(c),m)}]}const jl={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Js(n,e,t,s,r,i,o){const a={year:e.length===2?Ms(nt(e)):nt(e),month:ro.indexOf(t)+1,day:nt(s),hour:nt(r),minute:nt(i)};return o&&(a.second=nt(o)),n&&(a.weekday=n.length>3?oo.indexOf(n)+1:ao.indexOf(n)+1),a}const zl=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Zl(n){const[,e,t,s,r,i,o,a,l,c,d,m]=n,u=Js(e,r,s,t,i,o,a);let f;return l?f=jl[l]:c?f=0:f=Yn(d,m),[u,new we(f)]}function ql(n){return n.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Bl=/^(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$/,Hl=/^(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$/,Gl=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function Zr(n){const[,e,t,s,r,i,o,a]=n;return[Js(e,r,s,t,i,o,a),we.utcInstance]}function Yl(n){const[,e,t,s,r,i,o,a]=n;return[Js(e,a,t,s,r,i,o),we.utcInstance]}const Jl=Vt(Dl,Ys),Ql=Vt(Al,Ys),Kl=Vt(Cl,Ys),Xl=Vt(po),go=Ut(Ll,jt,cn,un),ec=Ut(Fl,jt,cn,un),tc=Ut($l,jt,cn,un),nc=Ut(jt,cn,un);function sc(n){return Wt(n,[Jl,go],[Ql,ec],[Kl,tc],[Xl,nc])}function rc(n){return Wt(ql(n),[zl,Zl])}function ic(n){return Wt(n,[Bl,Zr],[Hl,Zr],[Gl,Yl])}function oc(n){return Wt(n,[Ul,Wl])}const ac=Ut(jt);function lc(n){return Wt(n,[Vl,ac])}const cc=Vt(Ml,Pl),uc=Vt(yo),dc=Ut(jt,cn,un);function fc(n){return Wt(n,[cc,go],[uc,dc])}const qr="Invalid Duration",wo={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}},hc={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},...wo},xe=146097/400,bt=146097/4800,mc={years:{quarters:4,months:12,weeks:xe/7,days:xe,hours:xe*24,minutes:xe*24*60,seconds:xe*24*60*60,milliseconds:xe*24*60*60*1e3},quarters:{months:3,weeks:xe/28,days:xe/4,hours:xe*24/4,minutes:xe*24*60/4,seconds:xe*24*60*60/4,milliseconds:xe*24*60*60*1e3/4},months:{weeks:bt/7,days:bt,hours:bt*24,minutes:bt*24*60,seconds:bt*24*60*60,milliseconds:bt*24*60*60*1e3},...wo},pt=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],pc=pt.slice(0).reverse();function Ye(n,e,t=!1){const s={values:t?e.values:{...n.values,...e.values||{}},loc:n.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||n.conversionAccuracy,matrix:e.matrix||n.matrix};return new ne(s)}function _o(n,e){let t=e.milliseconds??0;for(const s of pc.slice(1))e[s]&&(t+=e[s]*n[s].milliseconds);return t}function Br(n,e){const t=_o(n,e)<0?-1:1;pt.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*t,o=n[r][s],a=Math.floor(i/o);e[r]+=a*t,e[s]-=a*o*t}return r},null),pt.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*n[s][r]}return r},null)}function Hr(n){const e={};for(const[t,s]of Object.entries(n))s!==0&&(e[t]=s);return e}class ne{constructor(e){const t=e.conversionAccuracy==="longterm"||!1;let s=t?mc:hc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||ie.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return ne.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new pe(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ne({values:Un(e,ne.normalizeUnit),loc:ie.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(ot(e))return ne.fromMillis(e);if(ne.isDuration(e))return e;if(typeof e=="object")return ne.fromObject(e);throw new pe(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){const[s]=oc(e);return s?ne.fromObject(s,t):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=lc(e);return s?ne.fromObject(s,t):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new pe("need to specify a reason the Duration is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new Wa(s);return new ne({invalid:s})}static normalizeUnit(e){const t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new Si(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){const s={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?ye.create(this.loc,s).formatDurationFromString(this,e):qr}toHuman(e={}){if(!this.isValid)return qr;const t=e.showZeros!==!1,s=pt.map(r=>{const i=this.values[r];return G(i)||i===0&&!t?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Hs(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},L.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?_o(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e),s={};for(const r of pt)(Lt(t.values,r)||Lt(this.values,r))&&(s[r]=t.get(r)+this.get(r));return Ye(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;const t={};for(const s of Object.keys(this.values))t[s]=so(e(this.values[s],s));return Ye(this,{values:t},!0)}get(e){return this[ne.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...Un(e,ne.normalizeUnit)};return Ye(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:r,conversionAccuracy:s};return Ye(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return Br(this.matrix,e),Ye(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=Hr(this.normalize().shiftToAll().toObject());return Ye(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>ne.normalizeUnit(o));const t={},s={},r=this.toObject();let i;for(const o of pt)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;ot(r[o])&&(a+=r[o]);const l=Math.trunc(a);t[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else ot(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(t[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return Br(this.matrix,t),Ye(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return Ye(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=Hr(this.values);return Ye(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of pt)if(!t(this.values[s],e.values[s]))return!1;return!0}}const Tt="Invalid Interval";function yc(n,e){return!n||!n.isValid?le.invalid("missing or invalid start"):!e||!e.isValid?le.invalid("missing or invalid end"):e<n?le.invalid("end before start",`The end of an interval must be after its start, but you had start=${n.toISO()} and end=${e.toISO()}`):null}class le{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new pe("need to specify a reason the Interval is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new Ua(s);return new le({invalid:s})}static fromDateTimes(e,t){const s=qt(e),r=qt(t),i=yc(s,r);return i??new le({start:s,end:r})}static after(e,t){const s=ne.fromDurationLike(t),r=qt(e);return le.fromDateTimes(r,r.plus(s))}static before(e,t){const s=ne.fromDurationLike(t),r=qt(e);return le.fromDateTimes(r.minus(s),r)}static fromISO(e,t){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=L.fromISO(s,t),o=i.isValid}catch{o=!1}let a,l;try{a=L.fromISO(r,t),l=a.isValid}catch{l=!1}if(o&&l)return le.fromDateTimes(i,a);if(o){const c=ne.fromISO(r,t);if(c.isValid)return le.after(i,c)}else if(l){const c=ne.fromISO(s,t);if(c.isValid)return le.before(a,c)}}return le.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",t){if(!this.isValid)return NaN;const s=this.start.startOf(e,t);let r;return t?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,t),Math.floor(r.diff(s,e).get(e))+(r.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?le.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];const t=e.map(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=t[i]||this.e,a=+o>+this.e?this.e:o;s.push(le.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const t=ne.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(t.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(le.fromDateTimes(s,i)),s=i,r+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const t=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return t>=s?null:le.fromDateTimes(t,s)}union(e){if(!this.isValid)return this;const t=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return le.fromDateTimes(t,s)}static merge(e){const[t,s]=e.sort((r,i)=>r.s-i.s).reduce(([r,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[r,i.union(o)]:[r.concat([i]),o]:[r,o],[[],null]);return s&&t.push(s),t}static xor(e){let t=null,s=0;const r=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((l,c)=>l.time-c.time);for(const l of a)s+=l.type==="s"?1:-1,s===1?t=l.time:(t&&+t!=+l.time&&r.push(le.fromDateTimes(t,l.time)),t=null);return le.merge(r)}difference(...e){return le.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Tt}[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=Pn,t={}){return this.isValid?ye.create(this.s.loc.clone(t),e).formatInterval(this):Tt}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Tt}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Tt}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Tt}toFormat(e,{separator:t=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Tt}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):ne.invalid(this.invalidReason)}mapEndpoints(e){return le.fromDateTimes(e(this.s),e(this.e))}}class mn{static hasDST(e=ce.defaultZone){const t=L.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return Xe.isValidZone(e)}static normalizeZone(e){return st(e,ce.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||ie.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ie.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return ie.create(t,null,"gregory").eras(e)}static features(){return{relative:eo(),localeWeek:to()}}}function Gr(n,e){const t=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(n);return Math.floor(ne.fromMillis(s).as("days"))}function gc(n,e,t){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const d=Gr(l,c);return(d-d%7)/7}],["days",Gr]],r={},i=n;let o,a;for(const[l,c]of s)t.indexOf(l)>=0&&(o=l,r[l]=c(n,e),a=i.plus(r),a>e?(r[l]--,n=i.plus(r),n>e&&(a=n,r[l]--,n=i.plus(r))):n=a);return[n,r,a,o]}function wc(n,e,t,s){let[r,i,o,a]=gc(n,e,t);const l=e-r,c=t.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=ne.fromObject(i,s);return c.length>0?ne.fromMillis(l,s).shiftTo(...c).plus(d):d}const _c="missing Intl.DateTimeFormat.formatToParts support";function re(n,e=t=>t){return{regex:n,deser:([t])=>e(cl(t))}}const Ec=" ",Eo=`[ ${Ec}]`,vo=new RegExp(Eo,"g");function vc(n){return n.replace(/\./g,"\\.?").replace(vo,Eo)}function Yr(n){return n.replace(/\./g,"").replace(vo," ").toLowerCase()}function $e(n,e){return n===null?null:{regex:RegExp(n.map(vc).join("|")),deser:([t])=>n.findIndex(s=>Yr(t)===Yr(s))+e}}function Jr(n,e){return{regex:n,deser:([,t,s])=>Yn(t,s),groups:e}}function pn(n){return{regex:n,deser:([e])=>e}}function Oc(n){return n.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function kc(n,e){const t=Fe(e),s=Fe(e,"{2}"),r=Fe(e,"{3}"),i=Fe(e,"{4}"),o=Fe(e,"{6}"),a=Fe(e,"{1,2}"),l=Fe(e,"{1,3}"),c=Fe(e,"{1,6}"),d=Fe(e,"{1,9}"),m=Fe(e,"{2,4}"),u=Fe(e,"{4,6}"),f=y=>({regex:RegExp(Oc(y.val)),deser:([w])=>w,literal:!0}),v=(y=>{if(n.literal)return f(y);switch(y.val){case"G":return $e(e.eras("short"),0);case"GG":return $e(e.eras("long"),0);case"y":return re(c);case"yy":return re(m,Ms);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 $e(e.months("short",!0),1);case"MMMM":return $e(e.months("long",!0),1);case"L":return re(a);case"LL":return re(s);case"LLL":return $e(e.months("short",!1),1);case"LLLL":return $e(e.months("long",!1),1);case"d":return re(a);case"dd":return re(s);case"o":return re(l);case"ooo":return re(r);case"HH":return re(s);case"H":return re(a);case"hh":return re(s);case"h":return re(a);case"mm":return re(s);case"m":return re(a);case"q":return re(a);case"qq":return re(s);case"s":return re(a);case"ss":return re(s);case"S":return re(l);case"SSS":return re(r);case"u":return pn(d);case"uu":return pn(a);case"uuu":return re(t);case"a":return $e(e.meridiems(),0);case"kkkk":return re(i);case"kk":return re(m,Ms);case"W":return re(a);case"WW":return re(s);case"E":case"c":return re(t);case"EEE":return $e(e.weekdays("short",!1),1);case"EEEE":return $e(e.weekdays("long",!1),1);case"ccc":return $e(e.weekdays("short",!0),1);case"cccc":return $e(e.weekdays("long",!0),1);case"Z":case"ZZ":return Jr(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return Jr(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return pn(/[a-z_+-/]{1,256}?/i);case" ":return pn(/[^\S\n\r]/);default:return f(y)}})(n)||{invalidReason:_c};return v.token=n,v}const bc={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 Tc(n,e,t){const{type:s,value:r}=n;if(s==="literal"){const l=/^\s+$/.test(r);return{literal:!l,val:l?" ":r}}const i=e[s];let o=s;s==="hour"&&(e.hour12!=null?o=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?o="hour12":o="hour24":o=t.hour12?"hour12":"hour24");let a=bc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Sc(n){return[`^${n.map(t=>t.regex).reduce((t,s)=>`${t}(${s.source})`,"")}$`,n]}function Rc(n,e,t){const s=n.match(e);if(s){const r={};let i=1;for(const o in t)if(Lt(t,o)){const a=t[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function Ic(n){const e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let t=null,s;return G(n.z)||(t=Xe.create(n.z)),G(n.Z)||(t||(t=new we(n.Z)),s=n.Z),G(n.q)||(n.M=(n.q-1)*3+1),G(n.h)||(n.h<12&&n.a===1?n.h+=12:n.h===12&&n.a===0&&(n.h=0)),n.G===0&&n.y&&(n.y=-n.y),G(n.u)||(n.S=Bs(n.u)),[Object.keys(n).reduce((i,o)=>{const a=e(o);return a&&(i[a]=n[o]),i},{}),t,s]}let ls=null;function xc(){return ls||(ls=L.fromMillis(1555555555555)),ls}function Nc(n,e){if(n.literal)return n;const t=ye.macroTokenToFormatOpts(n.val),s=To(t,e);return s==null||s.includes(void 0)?n:s}function Oo(n,e){return Array.prototype.concat(...n.map(t=>Nc(t,e)))}class ko{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=Oo(ye.parseFormat(t),e),this.units=this.tokens.map(s=>kc(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Sc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[t,s]=Rc(e,this.regex,this.handlers),[r,i,o]=s?Ic(s):[null,null,void 0];if(Lt(s,"a")&&Lt(s,"H"))throw new It("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:s,result:r,zone:i,specificOffset:o}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function bo(n,e,t){return new ko(n,t).explainFromTokens(e)}function Dc(n,e,t){const{result:s,zone:r,specificOffset:i,invalidReason:o}=bo(n,e,t);return[s,r,i,o]}function To(n,e){if(!n)return null;const s=ye.create(e,n).dtFormatter(xc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Tc(o,n,i))}const cs="Invalid DateTime",Qr=864e13;function Yt(n){return new Me("unsupported zone",`the zone "${n.name}" is not supported`)}function us(n){return n.weekData===null&&(n.weekData=Ln(n.c)),n.weekData}function ds(n){return n.localWeekData===null&&(n.localWeekData=Ln(n.c,n.loc.getMinDaysInFirstWeek(),n.loc.getStartOfWeek())),n.localWeekData}function ft(n,e){const t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new L({...t,...e,old:t})}function So(n,e,t){let s=n-e*60*1e3;const r=t.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=t.offset(s);return r===i?[s,r]:[n-Math.min(r,i)*60*1e3,Math.max(r,i)]}function yn(n,e){n+=e*60*1e3;const t=new Date(n);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function En(n,e,t){return So(Gn(n),e,t)}function Kr(n,e){const t=n.o,s=n.c.year+Math.trunc(e.years),r=n.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...n.c,year:s,month:r,day:Math.min(n.c.day,Vn(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=Gn(i);let[l,c]=So(a,t,n.zone);return o!==0&&(l+=o,c=n.zone.offset(l)),{ts:l,o:c}}function St(n,e,t,s,r,i){const{setZone:o,zone:a}=t;if(n&&Object.keys(n).length!==0||e){const l=e||a,c=L.fromObject(n,{...t,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return L.invalid(new Me("unparsable",`the input "${r}" can't be parsed as ${s}`))}function gn(n,e,t=!0){return n.isValid?ye.create(ie.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(n,e):null}function fs(n,e,t){const s=n.c.year>9999||n.c.year<0;let r="";if(s&&n.c.year>=0&&(r+="+"),r+=de(n.c.year,s?6:4),t==="year")return r;if(e){if(r+="-",r+=de(n.c.month),t==="month")return r;r+="-"}else if(r+=de(n.c.month),t==="month")return r;return r+=de(n.c.day),r}function Xr(n,e,t,s,r,i,o){let a=!t||n.c.millisecond!==0||n.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=de(n.c.hour),o==="hour")break;if(e){if(l+=":",l+=de(n.c.minute),o==="minute")break;a&&(l+=":",l+=de(n.c.second))}else{if(l+=de(n.c.minute),o==="minute")break;a&&(l+=de(n.c.second))}if(o==="second")break;a&&(!s||n.c.millisecond!==0)&&(l+=".",l+=de(n.c.millisecond,3))}return r&&(n.isOffsetFixed&&n.offset===0&&!i?l+="Z":n.o<0?(l+="-",l+=de(Math.trunc(-n.o/60)),l+=":",l+=de(Math.trunc(-n.o%60))):(l+="+",l+=de(Math.trunc(n.o/60)),l+=":",l+=de(Math.trunc(n.o%60)))),i&&(l+="["+n.zone.ianaName+"]"),l}const Ro={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ac={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Cc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},vn=["year","month","day","hour","minute","second","millisecond"],Fc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],$c=["year","ordinal","hour","minute","second","millisecond"];function On(n){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[n.toLowerCase()];if(!e)throw new Si(n);return e}function ei(n){switch(n.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return On(n)}}function Mc(n){if(Jt===void 0&&(Jt=ce.now()),n.type!=="iana")return n.offset(Jt);const e=n.name;let t=Ps.get(e);return t===void 0&&(t=n.offset(Jt),Ps.set(e,t)),t}function ti(n,e){const t=st(e.zone,ce.defaultZone);if(!t.isValid)return L.invalid(Yt(t));const s=ie.fromObject(e);let r,i;if(G(n.year))r=ce.now();else{for(const l of vn)G(n[l])&&(n[l]=Ro[l]);const o=Ki(n)||Xi(n);if(o)return L.invalid(o);const a=Mc(t);[r,i]=En(n,a,t)}return new L({ts:r,zone:t,loc:s,o:i})}function ni(n,e,t){const s=G(t.round)?!0:t.round,r=G(t.rounding)?"trunc":t.rounding,i=(a,l)=>(a=Hs(a,s||t.calendary?0:2,t.calendary?"round":r),e.loc.clone(t).relFormatter(t).format(a,l)),o=a=>t.calendary?e.hasSame(n,a)?0:e.startOf(a).diff(n.startOf(a),a).get(a):e.diff(n,a).get(a);if(t.unit)return i(o(t.unit),t.unit);for(const a of t.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(n>e?-0:0,t.units[t.units.length-1])}function si(n){let e={},t;return n.length>0&&typeof n[n.length-1]=="object"?(e=n[n.length-1],t=Array.from(n).slice(0,n.length-1)):t=Array.from(n),[e,t]}let Jt;const Ps=new Map;class L{constructor(e){const t=e.zone||ce.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Me("invalid input"):null)||(t.isValid?null:Yt(t));this.ts=G(e.ts)?ce.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[r,i]=[e.old.c,e.old.o];else{const a=ot(e.o)&&!e.old?e.o:t.offset(this.ts);r=yn(this.ts,a),s=Number.isNaN(r.year)?new Me("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=t,this.loc=e.loc||ie.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new L({})}static local(){const[e,t]=si(arguments),[s,r,i,o,a,l,c]=t;return ti({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,t]=si(arguments),[s,r,i,o,a,l,c]=t;return e.zone=we.utcInstance,ti({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){const s=ml(e)?e.valueOf():NaN;if(Number.isNaN(s))return L.invalid("invalid input");const r=st(t.zone,ce.defaultZone);return r.isValid?new L({ts:s,zone:r,loc:ie.fromObject(t)}):L.invalid(Yt(r))}static fromMillis(e,t={}){if(ot(e))return e<-Qr||e>Qr?L.invalid("Timestamp out of range"):new L({ts:e,zone:st(t.zone,ce.defaultZone),loc:ie.fromObject(t)});throw new pe(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(ot(e))return new L({ts:e*1e3,zone:st(t.zone,ce.defaultZone),loc:ie.fromObject(t)});throw new pe("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=st(t.zone,ce.defaultZone);if(!s.isValid)return L.invalid(Yt(s));const r=ie.fromObject(t),i=Un(e,ei),{minDaysInFirstWeek:o,startOfWeek:a}=Ur(i,r),l=ce.now(),c=G(t.specificOffset)?s.offset(l):t.specificOffset,d=!G(i.ordinal),m=!G(i.year),u=!G(i.month)||!G(i.day),f=m||u,g=i.weekYear||i.weekNumber;if((f||d)&&g)throw new It("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new It("Can't mix ordinal dates with month/day");const v=g||i.weekday&&!f;let y,w,R=yn(l,c);v?(y=Fc,w=Ac,R=Ln(R,o,a)):d?(y=$c,w=Cc,R=as(R)):(y=vn,w=Ro);let O=!1;for(const p of y){const F=i[p];G(F)?O?i[p]=w[p]:i[p]=R[p]:O=!0}const I=v?dl(i,o,a):d?fl(i):Ki(i),E=I||Xi(i);if(E)return L.invalid(E);const C=v?Lr(i,o,a):d?Vr(i):i,[_,Z]=En(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,t={}){const[s,r]=sc(e);return St(s,r,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,r]=rc(e);return St(s,r,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,r]=ic(e);return St(s,r,t,"HTTP",t)}static fromFormat(e,t,s={}){if(G(e)||G(t))throw new pe("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,d]=Dc(o,e,t);return d?L.invalid(d):St(a,l,s,`format ${t}`,e,c)}static fromString(e,t,s={}){return L.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,r]=fc(e);return St(s,r,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new pe("need to specify a reason the DateTime is invalid");const s=e instanceof Me?e:new Me(e,t);if(ce.throwOnInvalid)throw new Va(s);return new L({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=To(e,ie.fromObject(t));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,t={}){return Oo(ye.parseFormat(e),ie.fromObject(t)).map(r=>r.val).join("")}static resetCache(){Jt=void 0,Ps.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?us(this).weekYear:NaN}get weekNumber(){return this.isValid?us(this).weekNumber:NaN}get weekday(){return this.isValid?us(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ds(this).weekday:NaN}get localWeekNumber(){return this.isValid?ds(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ds(this).weekYear:NaN}get ordinal(){return this.isValid?as(this.c).ordinal:NaN}get monthShort(){return this.isValid?mn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?mn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?mn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?mn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,t=6e4,s=Gn(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*t),a=this.zone.offset(s-i*t);if(o===a)return[this];const l=s-o*t,c=s-a*t,d=yn(l,o),m=yn(c,a);return d.hour===m.hour&&d.minute===m.minute&&d.second===m.second&&d.millisecond===m.millisecond?[ft(this,{ts:l}),ft(this,{ts:c})]:[this]}get isInLeapYear(){return ln(this.year)}get daysInMonth(){return Vn(this.year,this.month)}get daysInYear(){return this.isValid?Dt(this.year):NaN}get weeksInWeekYear(){return this.isValid?sn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?sn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:t,numberingSystem:s,calendar:r}=ye.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(we.instance(e),t)}toLocal(){return this.setZone(ce.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=st(e,ce.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(t||s){const i=e.offset(this.ts),o=this.toObject();[r]=En(o,i,e)}return ft(this,{ts:r,zone:e})}else return L.invalid(Yt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return ft(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=Un(e,ei),{minDaysInFirstWeek:s,startOfWeek:r}=Ur(t,this.loc),i=!G(t.weekYear)||!G(t.weekNumber)||!G(t.weekday),o=!G(t.ordinal),a=!G(t.year),l=!G(t.month)||!G(t.day),c=a||l,d=t.weekYear||t.weekNumber;if((c||o)&&d)throw new It("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new It("Can't mix ordinal dates with month/day");let m;i?m=Lr({...Ln(this.c,s,r),...t},s,r):G(t.ordinal)?(m={...this.toObject(),...t},G(t.day)&&(m.day=Math.min(Vn(m.year,m.month),m.day))):m=Vr({...as(this.c),...t});const[u,f]=En(m,this.o,this.zone);return ft(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e);return ft(this,Kr(this,t))}minus(e){if(!this.isValid)return this;const t=ne.fromDurationLike(e).negate();return ft(this,Kr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},r=ne.normalizeUnit(e);switch(r){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(r==="weeks")if(t){const i=this.loc.getStartOfWeek(),{weekday:o}=this;o<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(r==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?ye.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):cs}toLocaleString(e=Pn,t={}){return this.isValid?ye.create(this.loc.clone(t),e).formatDateTime(this):cs}toLocaleParts(e={}){return this.isValid?ye.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=On(o);const a=e==="extended";let l=fs(this,a,o);return vn.indexOf(o)>=3&&(l+="T"),l+=Xr(this,a,t,s,r,i,o),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?fs(this,e==="extended",On(t)):null}toISOWeekDate(){return gn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=On(a),(r&&vn.indexOf(a)>=3?"T":"")+Xr(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return gn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return gn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?fs(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(t||e)&&(s&&(r+=" "),t?r+="z":e&&(r+="ZZ")),gn(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():cs}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",s={}){if(!this.isValid||!e.isValid)return ne.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=pl(t).map(ne.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=wc(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",t={}){return this.diff(L.now(),e,t)}until(e){return this.isValid?le.fromDateTimes(this,e):this}hasSame(e,t,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,s)<=r&&r<=i.endOf(t,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const t=e.base||L.fromObject({},{zone:this.zone}),s=e.padding?this<t?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),ni(t,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?ni(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 pe("min requires all arguments be DateTimes");return Wr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(L.isDateTime))throw new pe("max requires all arguments be DateTimes");return Wr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return bo(o,e,t)}static fromStringExplain(e,t,s={}){return L.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:r=null}=t,i=ie.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new ko(i,e)}static fromFormatParser(e,t,s={}){if(G(e)||G(t))throw new pe("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new pe(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=t.explainFromTokens(e);return d?L.invalid(d):St(a,l,s,`format ${t.format}`,e,c)}static get DATE_SHORT(){return Pn}static get DATE_MED(){return Ri}static get DATE_MED_WITH_WEEKDAY(){return ja}static get DATE_FULL(){return Ii}static get DATE_HUGE(){return xi}static get TIME_SIMPLE(){return Ni}static get TIME_WITH_SECONDS(){return Di}static get TIME_WITH_SHORT_OFFSET(){return Ai}static get TIME_WITH_LONG_OFFSET(){return Ci}static get TIME_24_SIMPLE(){return Fi}static get TIME_24_WITH_SECONDS(){return $i}static get TIME_24_WITH_SHORT_OFFSET(){return Mi}static get TIME_24_WITH_LONG_OFFSET(){return Pi}static get DATETIME_SHORT(){return Li}static get DATETIME_SHORT_WITH_SECONDS(){return Vi}static get DATETIME_MED(){return Ui}static get DATETIME_MED_WITH_SECONDS(){return Wi}static get DATETIME_MED_WITH_WEEKDAY(){return za}static get DATETIME_FULL(){return ji}static get DATETIME_FULL_WITH_SECONDS(){return zi}static get DATETIME_HUGE(){return Zi}static get DATETIME_HUGE_WITH_SECONDS(){return qi}}function qt(n){if(L.isDateTime(n))return n;if(n&&n.valueOf&&ot(n.valueOf()))return L.fromJSDate(n);if(n&&typeof n=="object")return L.fromObject(n);throw new pe(`Unknown datetime argument: ${n}, of type ${typeof n}`)}const Pc=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return on(me());n.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?t[r]=Io(i)?.nullable():t[r]=me()})}return We({Collection_Path:vt(Te()),...t})},Lc=(n,e,t,s)=>{let r=We({}).catchall(Pc(n,e)),i;if(!s&&t){const o=Ae(n,t);i=Bt(o.admin?.skipFormRequiredValidation)}return(!n.required||i)&&(r=r.optional()),r},Vc=()=>me().refine(n=>n===null||n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Must be a valid date"}),Io=(n,e,t)=>{let s;const r=`${Bt(n.description)}
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"),gt=require("firebase-admin/app"),ie=require("firebase-admin/firestore"),di=require("node:url"),Go=require("cross-spawn"),fi=require("firebase-admin/database"),vt=require("firebase-admin/auth"),Zn=n=>!!n.auth,Re=(n,e)=>{if(e?.operations)return e.operations.includes(n)},qn=(n,e)=>e?e.Role?n.access?.includes(e.Role):!1:!0,Yo=(n,e)=>e?!e.Role||n.restrictCreate===!0?!1:typeof n.restrictCreate=="object"?n.restrictCreate?.includes(e.Role):!0:!0,hi=(n,e)=>e?!e.Role||n.restrictUpdate===!0?!1:typeof n.restrictUpdate=="object"?n.restrictUpdate?.includes(e.Role):!0:!0,hr=(n,e,t)=>{const{labels:s}=n;return t.collections&&Re("Update",t.collections[s.collection])&&(!e.access||qn(e,t))&&hi(e,t)&&!(n.auth&&!t.collections?.[s.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},U=(n,e)=>n.filter(t=>t.name===e)[0],X=n=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(n.type),mi=(n,e)=>{const t={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=n,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const d=a?.[t[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},Vs=(n,e)=>{const t=[],{labels:s,access:r}=n,{entityRestrictions:i}=r,o=e.collections?.[s.collection];return i?.restrictions?.forEach(a=>{"roles"in a&&a.roles.forEach(l=>{l.role===e.Role&&(!i.assignable?.includes(e.Role)||o?.restrictEntities)&&t.push(a)})}),t},pi=(n,e,t)=>{const s=[],{access:r}=n,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.role===t.Role))return;const a=o.collectionField,l=U(n.fields,a);if(!X(l))throw new Error("PERMISSION_DENIED");const c=t.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===t.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===t.Role&&(!m.assignable?.includes(t.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},yi=(n,e,t)=>{const s=Object.values(e.collections),{labels:r}=n,i=[];for(const o of s){const{fields:a}=o;for(const l of a)if(!(l.access&&!qn(l,t))&&t.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(t.Role)&&i.push(c)}return i},Jo=(n,e,t,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const d=mi(e,r),m=Vs(e,r),u=pi(e,t,r);d?.filter(E=>E.type==="Record_Owner").forEach(E=>{"operations"in E&&E.operations&&!E.operations.includes(n)||i.Created_By!==s&&(c=!1)}),d?.filter(E=>E.type==="Record_User").forEach(E=>{if("operations"in E&&E.operations&&!E.operations.includes(n))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(n))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=(n,e,t,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;Re(n,a)||(l=!1);const d=Vs(e,r)?.filter(m=>m.type==="Individual").length>0;return n==="Create"&&d&&(l=!1),Jo(n,e,t,s,r,i)||(l=!1),l},gi=(n,e,t)=>{const{labels:s}=n,r=[];for(const i of Object.values(e.collections));return r},Qo=(n,e)=>{let t=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){t=!1,s="Permissions object must contain Doc_ID, Role, Collection, Enabled, and collections";return}}),e.collections&&(Object.keys(e.collections).forEach(r=>{if(!Object.keys(n.collections).includes(r)){s=`Collection ${r} not found in schema`,t=!1;return}const i=n.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,t=!1;return}if(!Object.keys(o).every(a=>["operations","auth","restrictEntities","individualEntities","parentEntities","parentPropertyEntities","recordProperty","recordUser","recordOwner"].includes(a))){s=`Collection ${r} has invalid properties`,t=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,t=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,t=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,t=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),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=>n.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,t=!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`,t=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,t=!1;return}if(a==="Parent"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(n.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,t=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(n.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,t=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,t=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),t},Ko=(n,e,t)=>{let s=!0,r="";Object.values(n.collections).filter(i=>i.auth).forEach(i=>{if(e.collections?.[i.labels.collection]?.auth&&!i.access.auth?.includes(e.Role)){r="Record cannot have auth access to collection",s=!1;return}});for(const i of Object.values(n.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:d,entityRestrictions:m}=a,u=c.assignable,f=e.collections?.[o.collection],g=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(t))?g.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const R=!!a.operations[y]?.includes(t),O=!!f?.operations.includes(w);if(!R&&O){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}if(R&&!O){r=`Collection ${o.collection} has missing ${y} operation for role ${t}`,s=!1;return}}}):g.forEach(y=>{const w=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const R=!!a.operations[y]?.includes(t),O=!!f?.operations.includes(w);if(!R&&O){r=`Collection ${o.collection} has excess ${y} operation for role ${t}`,s=!1;return}}}),!d&&!m||(d?.forEach(y=>{for(const w of y.roles)if(w.role===t&&!w.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${t}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${t}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${t}`,s=!1;return}}}),m?.assignable?.includes(t)))continue;let v=!1;if(m?.restrictions?.forEach(y=>{for(const w of y.roles)if(w.role===t){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=(n,e,t,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):n==="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&&n!=="delete"&&i&&Object.keys(t.collections).forEach(v=>{const y=i.collections?.[v],w=l?.collections?.[v];if(!(n==="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))||n==="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&&!(n==="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||n==="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&&!(n==="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=(n,e,t,s)=>{let r=!0,i="";return Object.values(n.collections).forEach(o=>{const a=t.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!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=(n,e,t,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(n==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(n==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!Xo(n,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(n==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;if(n==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return f="User cannot update their own record",u=!1,u;if(n==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return n==="delete"||d==="delete"||!a?u:a.Role?(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!==t?(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=(n,e,t,s,r,i,o)=>{const{labels:a,fields:l}=t,c=i?.collections?.[a.collection];let d=!0;if(r&&!c)throw new Error("PERMISSION_DENIED");r&&!Re("Create",c)&&(d=!1),r&&!lt("Create",t,s,r,i,n)&&(d=!1),t.auth&&o&&(r&&!Zn(c)&&(d=!1),Us("create",n,e,t,s,r,i,o)||(d=!1));for(const m of l){const u=n[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=n=>n&&(n._methodName==="deleteField"||n.constructor.name==="DeleteTransform"),it=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(Te(n[e])?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&it(n[e]))},pr=(n,e,t,s,r,i,o,a,l,c)=>{const{labels:d,fields:m}=s,u=o?.collections?.[d.collection],f={...e,...n};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,t,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=n[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=(n,e,t,s,r,i)=>{const{labels:o}=t,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(Re("Delete",a)||(l=!1),lt("Delete",t,s,r,i,n)||(l=!1),t.auth&&n.User_ID&&(Zn(a)||(l=!1),Us("delete",n,e,t,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},na=async(n,e,t,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,t,s,r,n)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},sa=async(n,e,t,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),n.forEach(l=>{lt("Read",e,t,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},ra=(n,e,t)=>{const{access:s}=n;return s.operations[t]?.includes(e)},ia=(n,e,t)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===n)&&!("singleQuery"in i&&i.singleQuery))return`${i.type} entity restriction`}if(r?.parentFilters)for(const i of r.parentFilters){if(!i.roles.some(c=>c.role===n))continue;const o=U(e.fields,i.collectionField);if(!X(o))throw new Error("PERMISSION_DENIED");const l=t.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(d=>d.role===n));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},oa=(n,e,t,s,r)=>{const i={};for(const o of n){const l=e[o].default({sdk:t,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=(n,e)=>e.fields.filter(t=>t.name===n.name)[0],es={global:{},collections:{}},Ht=(n,e)=>n&&typeof n=="function"?e?n(...e):n():n,oe=async(n,e)=>{let t=n;return n&&(typeof n=="function"||typeof n.then=="function")&&(e?t=await n(...e):t=await n()),t},aa=async(n,e,t,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=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=n,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await oe(a,t)),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=(n,e,t)=>{const s=Object.values(t.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field===n.name&&(i=!0)}return i},wi=(n,e)=>{const t=Object.values(e.collections),{labels:s}=n,r={};return t.forEach(i=>{const{labels:o,fields:a}=i;a.forEach(l=>{X(l)&&l.collection===s.collection&&l.dependencyFields&&l.dependencyFields.forEach(c=>{r[c.field]||={},r[c.field][o.collection]||=[],r[c.field][o.collection]=r[c.field][o.collection].concat(c.roles),r[c.field][o.collection]=[...new Set(r[c.field][o.collection])]})})}),r},ts=n=>JSON.stringify(n.map(e=>e.name)),wt=["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=()=>wt.map(n=>{let e="",t;switch(n){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",t=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:n,type:e,required:!0};return t&&(s.values=t),s}),_i=(n,e)=>{const t=[],{access:s,fields:r}=n,{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":t.push(U(a,"Created_By"));break;case"Record_User":t.push(U(r,l.collectionField));break;case"Record_Property":t.push(U(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":t.push(U(a,"id"));break;case"Parent":t.push(U(r,l.collectionField));break;case"Parent_Property":t.push(U(r,l.collectionField)),t.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":t.push(U(r,l.collectionField));break;case"Parent":t.push(U(r,l.parentCollectionField));break;case"Parent_Property":t.push(U(r,l.parentCollectionField)),t.push(U(r,l.parentPropertyField));break}})),[...new Set(t)]},la=(n,e)=>{const t=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=n,a=Bn();return t.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{(!c.access||c.access.includes(e))&&t.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{t.push(U(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{wt.includes(c)&&t.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))&&wt.includes(c.field)&&t.push(U(a,c.field))}),_i(n,e).forEach(c=>{wt.includes(c.name)&&t.push(U(a,c.name))}),[...new Set(t)]},ca=(n,e,t)=>{const s=[],{fields:r,preloadCache:i}=e,o=Bn();i?.range&&i.range.fields.forEach(c=>{wt.includes(c)?s.push(U(o,c)):s.push(U(r,c))});const a=new Set,l=wi(e,t);return Object.entries(l).map(([c,d])=>{n.name===c&&Object.values(d).forEach(m=>{m.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(..._i(e,c))}),[...new Set(s)]},hn=(n,e,t)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=wi(e,t);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{t.collections[c].fields.forEach(m=>{X(m)&&m.collection===e.labels.collection&&m.dependencyFields?.some(u=>u.field===n.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(n,e,t)),[...new Set(s)]},Ei=(n,e)=>{const{preloadCache:t}=n,s=new Set;for(const r of e.config.roles){if(!ra(n,r,"read"))continue;const i=la(n,r);let o=!1;if(s.size===0)s.add({key:"1",roles:[r],fields:i}),o=!0;else for(const a of s)i.length===a.fields.length&&i.every(l=>a.fields.some(c=>c.name===l.name))&&!!t?.roles.includes(r)==!!a.roles.every(l=>t?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},vi=(n,e,t)=>{const s=Ei(e,t);for(const r of s.values())if(r.roles.includes(n))return r},ua=(n,e)=>{const{fields:t}=e,s=Bn(),r=[];return[...t,...s.filter(o=>o.name!=="id")].forEach(o=>{n?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ws=(n,e,t)=>{const s={};return Object.values(n.collections).forEach(r=>{const i=Ei(r,n),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},Rn=n=>({Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_Version:n.Last_Write_Version,Last_Write_App:n.Last_Write_App,Last_Save_At:n.Last_Save_At}),ns=async(n,e,t)=>{if(e){const s=await oe(e,[t]);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${n}`);return s}};async function ae(n,e,t,s){const r=await ns(n,t.custom?.[n],s);for(const i of t.fields)await ns(n,i.custom?.[n],s);if(n!=="setEmbedding"&&(await ns(n,e?.[n],s),n==="postWriteError"))return r}const js=(n,e,t,s,r,i,o,a,l,c)=>(n==="create"&&(t.Collection_Path=e,t.Created_At=a,t.Saved_At=l,t.Created_By=o||"System"),t.Last_Write_App=r,t.Last_Write_At=a,t.Last_Save_At=l,t.Last_Write_By=o||"System",t.Last_Write_Connection_Status=i,t.Last_Write_Version=s.version,t),mt=(n,e)=>{const{access:t,queries:s}=n,{serverReadOnly:r}=t,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},Ot=(n,e)=>{const{access:t,recordTitleField:s}=n,{serverReadOnly:r}=t,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},In=(n,e,t)=>{const{fields:s}=n;s.forEach(i=>{if(X(i))if(e[i.name]){if(Te(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=t.collections[i.collection],l=U(a.fields,o);Ot(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(n,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=(n,e)=>{Ot(n,n.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},da=async(n,e,t,s)=>{const{fields:r}=e;for(const i of t.fields){const o=U(r,i.name);i.custom?.initialValue!==void 0&&!(s&&o.access&&!o.access.includes(s))&&(n[i.name]=await oe(i.custom.initialValue,[n]),Ot(e,[o]).size===1&&(n[`${i.name}_Lowercase`]=n[i.name].toLowerCase()))}for(const i of r)s&&i.access&&!i.access.includes(s)||("autoIncrement"in i&&i.autoIncrement&&!n[i.name]&&(n[i.name]="Pending"),!X(i)&&i.nullable&&n[i.name]===void 0&&(n[i.name]=null))};var ne;(function(n){n.assertEqual=r=>{};function e(r){}n.assertIs=e;function t(r){throw new Error}n.assertNever=t,n.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},n.getValidEnumValues=r=>{const i=n.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return n.objectValues(o)},n.objectValues=r=>n.objectKeys(r).map(function(i){return r[i]}),n.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},n.find=(r,i)=>{for(const o of r)if(i(o))return o},n.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}n.joinValues=s,n.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(ne||(ne={}));var yr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(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=n=>{switch(typeof n){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(n)?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(n)?V.array:n===null?V.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?V.promise:typeof Map<"u"&&n instanceof Map?V.map:typeof Set<"u"&&n instanceof Set?V.set:typeof Date<"u"&&n 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 t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(t(o));else{let a=s,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(t(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof 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=t=>t.message){const t={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}Xe.create=n=>new Xe(n);const _s=(n,e)=>{let t;switch(n.code){case D.invalid_type:n.received===V.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case D.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,ne.jsonStringifyReplacer)}`;break;case D.unrecognized_keys:t=`Unrecognized key(s) in object: ${ne.joinValues(n.keys,", ")}`;break;case D.invalid_union:t="Invalid input";break;case D.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${ne.joinValues(n.options)}`;break;case D.invalid_enum_value:t=`Invalid enum value. Expected ${ne.joinValues(n.options)}, received '${n.received}'`;break;case D.invalid_arguments:t="Invalid function arguments";break;case D.invalid_return_type:t="Invalid function return type";break;case D.invalid_date:t="Invalid date";break;case D.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:ne.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case D.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case D.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case D.custom:t="Invalid input";break;case D.invalid_intersection_types:t="Intersection results could not be merged";break;case D.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case D.not_finite:t="Number must be finite";break;default:t=e.defaultError,ne.assertNever(n)}return{message:t}};let fa=_s;function ha(){return fa}const ma=n=>{const{data:e,path:t,errorMaps:s,issueData:r}=n,i=[...t,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)a=c(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function P(n,e){const t=ha(),s=ma({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===_s?void 0:_s].filter(r=>!!r)});n.common.issues.push(s)}class Ee{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const r of t){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Ee.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return J;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const J=Object.freeze({status:"aborted"}),Gt=n=>({status:"dirty",value:n}),Fe=n=>({status:"valid",value:n}),gr=n=>n.status==="aborted",wr=n=>n.status==="dirty",Ft=n=>n.status==="valid",Nn=n=>typeof Promise<"u"&&n instanceof Promise;var W;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(W||(W={}));class Ze{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const _r=(n,e)=>{if(Ft(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Xe(n.common.issues);return this._error=t,this._error}}};function K(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:r}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=n;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??t??a.defaultError}},description:r}}class ee{get description(){return this._def.description}_getType(e){return nt(e.data)}_getOrReturnCtx(e,t){return t||{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 t=this._parse(e);if(Nn(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:nt(e)},r=this._parseSync({data:e,path:s.path,parent:s});return _r(s,r)}"~validate"(e){const t={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:t});return Ft(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>Ft(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType: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,t){const s=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:D.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof t=="function"?t(s,r):t),!1))}_refinement(e){return new Pt({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return ot.create(this,this._def)}nullable(){return Lt.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 Pt({...K(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ts({...K(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new Pa({typeName:Y.ZodBranded,type:this,...K(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ss({...K(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return zs.create(this,e)}readonly(){return Rs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const pa=/^c[^\s-]{8,}$/i,ya=/^[0-9a-z]+$/,ga=/^[0-9A-HJKMNP-TV-Z]{26}$/i,wa=/^[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,_a=/^[a-z0-9_-]{21}$/i,Ea=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,va=/^[-+]?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)?)??$/,Oa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ka="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ss;const ba=/^(?:(?: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])$/,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])\/(3[0-2]|[12]?[0-9])$/,Sa=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,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]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ia=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xa=/^([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])))",Na=new RegExp(`^${Oi}$`);function ki(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Da(n){return new RegExp(`^${ki(n)}$`)}function Aa(n){let e=`${Oi}T${ki(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ca(n,e){return!!((e==="v4"||!e)&&ba.test(n)||(e==="v6"||!e)&&Sa.test(n))}function Fa(n,e){if(!Ea.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function $a(n,e){return!!((e==="v4"||!e)&&Ta.test(n)||(e==="v6"||!e)&&Ra.test(n))}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")Oa.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(ka,"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")wa.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")_a.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")pa.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")ya.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")ga.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"?Aa(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"?Na.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:D.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?Da(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"?va.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"duration",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ca(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"?Fa(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"?$a(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"?Ia.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64",code:D.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?xa.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,t,s){return this.refinement(r=>e.test(r),{validation:t,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,t){return this._addCheck({kind:"regex",regex:e,...W.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...W.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...W.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...W.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...W.errToObj(t)})}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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Ke.create=n=>new Ke({checks:[],typeName:Y.ZodString,coerce:n?.coerce??!1,...K(n)});function Ma(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=t>s?t:s,i=Number.parseInt(n.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class $t 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"?Ma(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,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(e,t,s,r){return new $t({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:W.toString(r)}]})}_addCheck(e){return new $t({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}$t.create=n=>new $t({checks:[],typeName:Y.ZodNumber,coerce:n?.coerce||!1,...K(n)});class nn 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 t=this._getOrReturnCtx(e);return P(t,{code:D.invalid_type,expected:V.bigint,received:t.parsedType}),J}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(e,t,s,r){return new nn({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:W.toString(r)}]})}_addCheck(e){return new nn({...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,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}nn.create=n=>new nn({checks:[],typeName:Y.ZodBigInt,coerce:n?.coerce??!1,...K(n)});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=n=>new Es({typeName:Y.ZodBoolean,coerce:n?.coerce||!1,...K(n)});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,t){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:W.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}Dn.create=n=>new Dn({checks:[],coerce:n?.coerce||!1,typeName:Y.ZodDate,...K(n)});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=n=>new Er({typeName:Y.ZodSymbol,...K(n)});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=n=>new vs({typeName:Y.ZodUndefined,...K(n)});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=n=>new vr({typeName:Y.ZodNull,...K(n)});class Os extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return Fe(e.data)}}Os.create=n=>new Os({typeName:Y.ZodAny,...K(n)});class Or extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Fe(e.data)}}Or.create=n=>new Or({typeName:Y.ZodUnknown,...K(n)});class ct extends ee{_parse(e){const t=this._getOrReturnCtx(e);return P(t,{code:D.invalid_type,expected:V.never,received:t.parsedType}),J}}ct.create=n=>new ct({typeName:Y.ZodNever,...K(n)});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=n=>new kr({typeName:Y.ZodVoid,...K(n)});class We extends ee{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==V.array)return P(t,{code:D.invalid_type,expected:V.array,received:t.parsedType}),J;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(P(t,{code:o?D.too_big:D.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(P(t,{code:D.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(P(t,{code:D.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new Ze(t,o,t.path,a)))).then(o=>Ee.mergeArray(s,o));const i=[...t.data].map((o,a)=>r.type._parseSync(new Ze(t,o,t.path,a)));return Ee.mergeArray(s,i)}get element(){return this._def.type}min(e,t){return new We({...this._def,minLength:{value:e,message:W.toString(t)}})}max(e,t){return new We({...this._def,maxLength:{value:e,message:W.toString(t)}})}length(e,t){return new We({...this._def,exactLength:{value:e,message:W.toString(t)}})}nonempty(e){return this.min(1,e)}}We.create=(n,e)=>new We({type:n,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...K(e)});function xt(n){if(n instanceof de){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=ot.create(xt(s))}return new de({...n._def,shape:()=>e})}else return n instanceof We?new We({...n._def,type:xt(n.element)}):n instanceof ot?ot.create(xt(n.unwrap())):n instanceof Lt?Lt.create(xt(n.unwrap())):n instanceof _t?_t.create(n.items.map(e=>xt(e))):n}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(),t=ne.objectKeys(e);return this._cached={shape:e,keys:t},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:(t,s)=>{const r=this._def.errorMap?.(t,s).message??s.defaultError;return t.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,t){return this.augment({[e]:t})}catchall(e){return new de({...this._def,catchall:e})}pick(e){const t={};for(const s of ne.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const s of ne.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new de({...this._def,shape:()=>t})}deepPartial(){return xt(this)}partial(e){const t={};for(const s of ne.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const s of ne.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof ot;)i=i._def.innerType;t[s]=i}return new de({...this._def,shape:()=>t})}keyof(){return bi(ne.objectKeys(this.shape))}}de.create=(n,e)=>new de({shape:()=>n,unknownKeys:"strip",catchall:ct.create(),typeName:Y.ZodObject,...K(e)});de.strictCreate=(n,e)=>new de({shape:()=>n,unknownKeys:"strict",catchall:ct.create(),typeName:Y.ZodObject,...K(e)});de.lazycreate=(n,e)=>new de({shape:n,unknownKeys:"strip",catchall:ct.create(),typeName:Y.ZodObject,...K(e)});class An extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new Xe(a.ctx.common.issues));return P(t,{code:D.invalid_union,unionErrors:o}),J}if(t.common.async)return Promise.all(s.map(async i=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new Xe(l));return P(t,{code:D.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}An.create=(n,e)=>new An({options:n,typeName:Y.ZodUnion,...K(e)});function ks(n,e){const t=nt(n),s=nt(e);if(n===e)return{valid:!0,data:n};if(t===V.object&&s===V.object){const r=ne.objectKeys(e),i=ne.objectKeys(n).filter(a=>r.indexOf(a)!==-1),o={...n,...e};for(const a of i){const l=ks(n[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(t===V.array&&s===V.array){if(n.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<n.length;i++){const o=n[i],a=e[i],l=ks(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return t===V.date&&s===V.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Cn extends ee{_parse(e){const{status:t,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))&&t.dirty(),{status:t.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=(n,e,t)=>new Cn({left:n,right:e,typeName:Y.ZodIntersection,...K(t)});class _t extends ee{_parse(e){const{status:t,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"}),t.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(t,o)):Ee.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new _t({...this._def,rest:e})}}_t.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _t({items:n,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:t,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(t,r):Ee.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof ee?new Fn({keyType:e,valueType:t,typeName:Y.ZodRecord,...K(s)}):new Fn({keyType:Ke.create(),valueType:e,typeName:Y.ZodRecord,...K(t)})}}class br extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==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")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(c.value,d.value)}return{status:t.value,value:a}}}}br.create=(n,e,t)=>new br({valueType:e,keyType:n,typeName:Y.ZodMap,...K(t)});class sn extends ee{_parse(e){const{status:t,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}),t.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}),t.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"&&t.dirty(),c.add(d.value)}return{status:t.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,t){return new sn({...this._def,minSize:{value:e,message:W.toString(t)}})}max(e,t){return new sn({...this._def,maxSize:{value:e,message:W.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}sn.create=(n,e)=>new sn({valueType:n,minSize:null,maxSize:null,typeName:Y.ZodSet,...K(e)});class Tr extends ee{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Tr.create=(n,e)=>new Tr({getter:n,typeName:Y.ZodLazy,...K(e)});class bs extends ee{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return P(t,{received:t.data,code:D.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}bs.create=(n,e)=>new bs({value:n,typeName:Y.ZodLiteral,...K(e)});function bi(n,e){return new Mt({values:n,typeName:Y.ZodEnum,...K(e)})}class Mt extends ee{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return P(t,{expected:ne.joinValues(s),received:t.parsedType,code:D.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return P(t,{received:t.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 t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Mt.create(e,{...this._def,...t})}exclude(e,t=this._def){return Mt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}Mt.create=bi;class Sr extends ee{_parse(e){const t=ne.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==V.string&&s.parsedType!==V.number){const r=ne.objectValues(t);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(t);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=(n,e)=>new Sr({values:n,typeName:Y.ZodNativeEnum,...K(e)});class $n extends ee{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==V.promise&&t.common.async===!1)return P(t,{code:D.invalid_type,expected:V.promise,received:t.parsedType}),J;const s=t.parsedType===V.promise?t.data:Promise.resolve(t.data);return Fe(s.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}$n.create=(n,e)=>new $n({type:n,typeName:Y.ZodPromise,...K(e)});class Pt extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{P(s,o),o.fatal?t.abort():t.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return J;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?J:l.status==="dirty"||t.value==="dirty"?Gt(l.value):l});{if(t.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?J:a.status==="dirty"||t.value==="dirty"?Gt(a.value):a}}if(r.type==="refinement"){const o=a=>{const l=r.refinement(a,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Ft(o))return J;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Ft(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:t.value,value:a})):J);ne.assertNever(r)}}Pt.create=(n,e,t)=>new Pt({schema:n,typeName:Y.ZodEffects,effect:e,...K(t)});Pt.createWithPreprocess=(n,e,t)=>new Pt({schema:e,effect:{type:"preprocess",transform:n},typeName:Y.ZodEffects,...K(t)});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=(n,e)=>new ot({innerType:n,typeName:Y.ZodOptional,...K(e)});class Lt extends ee{_parse(e){return this._getType(e)===V.null?Fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Lt.create=(n,e)=>new Lt({innerType:n,typeName:Y.ZodNullable,...K(e)});class Ts extends ee{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===V.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ts.create=(n,e)=>new Ts({innerType:n,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});class Ss extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return 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=(n,e)=>new Ss({innerType:n,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=n=>new Rr({typeName:Y.ZodNaN,...K(n)});class Pa extends ee{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class zs extends ee{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?J:i.status==="dirty"?(t.dirty(),Gt(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?J:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,t){return new zs({in:e,out:t,typeName:Y.ZodPipeline})}}class Rs extends ee{_parse(e){const t=this._def.innerType._parse(e),s=r=>(Ft(r)&&(r.value=Object.freeze(r.value)),r);return Nn(t)?t.then(r=>s(r)):s(t)}unwrap(){return this._def.innerType}}Rs.create=(n,e)=>new Rs({innerType:n,typeName:Y.ZodReadonly,...K(e)});var Y;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(Y||(Y={}));const Se=Ke.create,pt=$t.create,en=Es.create,rs=vs.create,pe=Os.create;ct.create;const kt=We.create,je=de.create,ke=An.create;Cn.create;_t.create;const an=Fn.create,be=bs.create,Mn=Mt.create;$n.create;ot.create;Lt.create;const En=()=>pe().refine(n=>n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),Ir=()=>pe().refine(n=>n&&(n._methodName==="serverTimestamp"||n.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),Ti=(n,e,t)=>{const s={};if(n.includeFields){const i=e.collections[n.collection];if(!i)return an(pe());n.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${n.collection}`);s[o]=Pn(i,a),Ot(i,[a]).size===1&&(s[`${o}_Lowercase`]=Pn(i,a,!0))})}const r={Collection_Path:kt(Se()),...s};return t&&(r.id=Se().length(20)),je(r)},La=(n,e)=>{let t=an(Ti(n,e));return n.required||(t=t.optional()),t},Va=n=>{let e=kt(ke([Se().length(20),Se().length(28)]));return["OneToOne","OneToMany"].includes(n.type)?e=e.max(1):(n.min&&(e=e.min(n.min)),n.max&&(e=e.max(n.max)),n.length&&(e=e.length(n.length))),n.required?e=e.nonempty():e=e.optional(),e},Pn=(n,e,t)=>{const{softDelete:s}=n,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))),t&&(i=i.toLowerCase()),e.values)if(t){const o=e.values.map(a=>a.toLowerCase());i=Mn(o)}else i=Mn(e.values);break;case"Boolean":i=en();break;case"Number":e.autoIncrement?i=ke([be("Pending"),pt().int()]):(i=pt(),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=En(),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=kt(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=an(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=(n,e,t)=>{const s={Collection_Path:kt(Se()),Last_Write_App:Se(),Last_Write_At:En(),Last_Save_At:Ir(),Last_Write_By:ke([Se().length(28),be("System")]),Last_Write_Connection_Status:Mn(["Online","Offline"]),Last_Write_Version:pt().int(),id:Se().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:En(),Created_By:ke([Se().length(28),be("System")])};n==="create"&&(s.Saved_At=Ir()),n==="update"&&(s.Saved_At=En(),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]=La(l,t),s[`${l.name}_Array`]=Va(l),i.includes(l.name)&&(s[`${l.name}_Single`]=Ti(l,t,!0),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=Pn(e,l))}),Ot(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 bt extends Error{}class Ua extends bt{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class Wa extends bt{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class ja extends bt{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Nt extends bt{}class Ri extends bt{constructor(e){super(`Invalid unit ${e}`)}}class ye extends bt{}class tt extends bt{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:$},Za={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 ln{get type(){throw new tt}get name(){throw new tt}get ianaName(){return this.name}get isUniversal(){throw new tt}offsetName(e,t){throw new tt}formatOffset(e,t){throw new tt}offset(e){throw new tt}equals(e){throw new tt}get isValid(){throw new tt}}let is=null;class Hn extends ln{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:t,locale:s}){return so(e,t,s)}formatOffset(e,t){return tn(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Is=new Map;function qa(n){let e=Is.get(n);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Is.set(n,e)),e}const Ba={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Ha(n,e){const t=n.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,r,i,o,a,l,c,d]=s;return[o,r,i,a,l,c,d]}function Ga(n,e){const t=n.formatToParts(e),s=[];for(let r=0;r<t.length;r++){const{type:i,value:o}=t[r],a=Ba[i];i==="era"?s[a]=o:H(a)||(s[a]=parseInt(o,10))}return s}const os=new Map;class et extends ln{static create(e){let t=os.get(e);return t===void 0&&os.set(e,t=new et(e)),t}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:t,locale:s}){return so(e,t,s,this.name)}formatOffset(e,t){return tn(this.offset(e),t)}offset(e){if(!this.valid)return NaN;const t=new Date(e);if(isNaN(t))return NaN;const s=qa(this.name);let[r,i,o,a,l,c,d]=s.formatToParts?Ga(s,t):Ha(s,t);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=+t;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 Ya(n,e={}){const t=JSON.stringify([n,e]);let s=xr[t];return s||(s=new Intl.ListFormat(n,e),xr[t]=s),s}const xs=new Map;function Ns(n,e={}){const t=JSON.stringify([n,e]);let s=xs.get(t);return s===void 0&&(s=new Intl.DateTimeFormat(n,e),xs.set(t,s)),s}const Ds=new Map;function Ja(n,e={}){const t=JSON.stringify([n,e]);let s=Ds.get(t);return s===void 0&&(s=new Intl.NumberFormat(n,e),Ds.set(t,s)),s}const As=new Map;function Qa(n,e={}){const{base:t,...s}=e,r=JSON.stringify([n,s]);let i=As.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(n,e),As.set(r,i)),i}let Yt=null;function Ka(){return Yt||(Yt=new Intl.DateTimeFormat().resolvedOptions().locale,Yt)}const Cs=new Map;function Hi(n){let e=Cs.get(n);return e===void 0&&(e=new Intl.DateTimeFormat(n).resolvedOptions(),Cs.set(n,e)),e}const Fs=new Map;function Xa(n){let e=Fs.get(n);if(!e){const t=new Intl.Locale(n);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,"minimalDays"in e||(e={...Gi,...e}),Fs.set(n,e)}return e}function el(n){const e=n.indexOf("-x-");e!==-1&&(n=n.substring(0,e));const t=n.indexOf("-u-");if(t===-1)return[n];{let s,r;try{s=Ns(n).resolvedOptions(),r=n}catch{const l=n.substring(0,t);s=Ns(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function tl(n,e,t){return(t||e)&&(n.includes("-u-")||(n+="-u"),t&&(n+=`-ca-${t}`),e&&(n+=`-nu-${e}`)),n}function nl(n){const e=[];for(let t=1;t<=12;t++){const s=L.utc(2009,t,1);e.push(n(s))}return e}function sl(n){const e=[];for(let t=1;t<=7;t++){const s=L.utc(2016,11,13+t);e.push(n(s))}return e}function mn(n,e,t,s){const r=n.listingMode();return r==="error"?null:r==="en"?t(e):s(e)}function rl(n){return n.numberingSystem&&n.numberingSystem!=="latn"?!1:n.numberingSystem==="latn"||!n.locale||n.locale.startsWith("en")||Hi(n.locale).numberingSystem==="latn"}class il{constructor(e,t,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!t||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=Ja(e,a)}}format(e){if(this.inf){const t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{const t=this.floor?Math.floor(e):Gs(e,3);return fe(t,this.padTo)}}}class ol{constructor(e,t,s){this.opts=s,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&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(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:s}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class al{constructor(e,t,s){this.opts={style:"long",...s},!t&&to()&&(this.rtf=Qa(e,s))}format(e,t){return this.rtf?this.rtf.format(e,t):xl(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}}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,t,s,r,i=!1){const o=e||ce.defaultLocale,a=o||(i?"en-US":Ka()),l=t||ce.defaultNumberingSystem,c=s||ce.defaultOutputCalendar,d=Ms(r)||ce.defaultWeekSettings;return new re(a,l,c,d,o)}static resetCache(){Yt=null,xs.clear(),Ds.clear(),As.clear(),Cs.clear(),Fs.clear()}static fromObject({locale:e,numberingSystem:t,outputCalendar:s,weekSettings:r}={}){return re.create(e,t,s,r)}constructor(e,t,s,r,i){const[o,a,l]=el(e);this.locale=o,this.numberingSystem=t||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=tl(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=rl(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:re.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,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,t=!1){return mn(this,e,oo,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");t&=!s;const r=t?{month:e,day:"numeric"}:{month:e},i=t?"format":"standalone";if(!this.monthsCache[i][e]){const o=s?a=>this.dtFormatter(a,r).format():a=>this.extract(a,r,"month");this.monthsCache[i][e]=nl(o)}return this.monthsCache[i][e]})}weekdays(e,t=!1){return mn(this,e,co,()=>{const s=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=t?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=sl(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return mn(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(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return mn(this,e,fo,()=>{const t={era:e};return this.eraCache[e]||(this.eraCache[e]=[L.utc(-40,1,1),L.utc(2017,1,1)].map(s=>this.extract(s,t,"era"))),this.eraCache[e]})}extract(e,t,s){const r=this.dtFormatter(e,t),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new il(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new ol(e,this.intl,t)}relFormatter(e={}){return new al(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Ya(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()?Xa(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 ln{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 t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new _e(Jn(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${tn(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${tn(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return tn(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class ll extends ln{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(n,e){if(H(n)||n===null)return e;if(n instanceof ln)return n;if(ml(n)){const t=n.toLowerCase();return t==="default"?e:t==="local"||t==="system"?Hn.instance:t==="utc"||t==="gmt"?_e.utcInstance:_e.parseSpecifier(t)||et.create(n)}else return at(n)?_e.instance(n):typeof n=="object"&&"offset"in n&&typeof n.offset=="function"?n:new ll(n)}const Zs={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},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]},cl=Zs.hanidec.replace(/[\[|\]]/g,"").split("");function ul(n){let e=parseInt(n,10);if(isNaN(e)){e="";for(let t=0;t<n.length;t++){const s=n.charCodeAt(t);if(n[t].search(Zs.hanidec)!==-1)e+=cl.indexOf(n[t]);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 dl(){$s.clear()}function $e({numberingSystem:n},e=""){const t=n||"latn";let s=$s.get(t);s===void 0&&(s=new Map,$s.set(t,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${Zs[t]}${e}`),s.set(e,r)),r}let Dr=()=>Date.now(),Ar="system",Cr=null,Fr=null,$r=null,Mr=60,Pr,Lr=null;class ce{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(),dl()}}class Pe{constructor(e,t){this.reason=e,this.explanation=t}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(n,e){return new Pe("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${n}, which is invalid`)}function qs(n,e,t){const s=new Date(Date.UTC(n,e-1,t));n<100&&n>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function Qi(n,e,t){return t+(cn(n)?Ji:Yi)[e-1]}function Ki(n,e){const t=cn(n)?Ji:Yi,s=t.findIndex(i=>i<e),r=e-t[s];return{month:s+1,day:r}}function Bs(n,e){return(n-e+7)%7+1}function Vn(n,e=4,t=1){const{year:s,month:r,day:i}=n,o=Qi(s,r,i),a=Bs(qs(s,r,i),t);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=rn(c,e,t)):l>rn(s,e,t)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...Qn(n)}}function Vr(n,e=4,t=1){const{weekYear:s,weekNumber:r,weekday:i}=n,o=Bs(qs(s,1,e),t),a=At(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=At(c)):l>a?(c=s+1,l-=At(s)):c=s;const{month:d,day:m}=Ki(c,l);return{year:c,month:d,day:m,...Qn(n)}}function ls(n){const{year:e,month:t,day:s}=n,r=Qi(e,t,s);return{year:e,ordinal:r,...Qn(n)}}function Ur(n){const{year:e,ordinal:t}=n,{month:s,day:r}=Ki(e,t);return{year:e,month:s,day:r,...Qn(n)}}function Wr(n,e){if(!H(n.localWeekday)||!H(n.localWeekNumber)||!H(n.localWeekYear)){if(!H(n.weekday)||!H(n.weekNumber)||!H(n.weekYear))throw new Nt("Cannot mix locale-based week fields with ISO-based week fields");return H(n.localWeekday)||(n.weekday=n.localWeekday),H(n.localWeekNumber)||(n.weekNumber=n.localWeekNumber),H(n.localWeekYear)||(n.weekYear=n.localWeekYear),delete n.localWeekday,delete n.localWeekNumber,delete n.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function fl(n,e=4,t=1){const s=Gn(n.weekYear),r=Ae(n.weekNumber,1,rn(n.weekYear,e,t)),i=Ae(n.weekday,1,7);return s?r?i?!1:De("weekday",n.weekday):De("week",n.weekNumber):De("weekYear",n.weekYear)}function hl(n){const e=Gn(n.year),t=Ae(n.ordinal,1,At(n.year));return e?t?!1:De("ordinal",n.ordinal):De("year",n.year)}function Xi(n){const e=Gn(n.year),t=Ae(n.month,1,12),s=Ae(n.day,1,Un(n.year,n.month));return e?t?s?!1:De("day",n.day):De("month",n.month):De("year",n.year)}function eo(n){const{hour:e,minute:t,second:s,millisecond:r}=n,i=Ae(e,0,23)||e===24&&t===0&&s===0&&r===0,o=Ae(t,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",t):De("hour",e)}function H(n){return typeof n>"u"}function at(n){return typeof n=="number"}function Gn(n){return typeof n=="number"&&n%1===0}function ml(n){return typeof n=="string"}function pl(n){return Object.prototype.toString.call(n)==="[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 yl(n){return Array.isArray(n)?n:[n]}function jr(n,e,t){if(n.length!==0)return n.reduce((s,r)=>{const i=[e(r),r];return s&&t(s[0],i[0])===s[0]?s:i},null)[1]}function gl(n,e){return e.reduce((t,s)=>(t[s]=n[s],t),{})}function Vt(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Ms(n){if(n==null)return null;if(typeof n!="object")throw new ye("Week settings must be an object");if(!Ae(n.firstDay,1,7)||!Ae(n.minimalDays,1,7)||!Array.isArray(n.weekend)||n.weekend.some(e=>!Ae(e,1,7)))throw new ye("Invalid week settings");return{firstDay:n.firstDay,minimalDays:n.minimalDays,weekend:Array.from(n.weekend)}}function Ae(n,e,t){return Gn(n)&&n>=e&&n<=t}function wl(n,e){return n-e*Math.floor(n/e)}function fe(n,e=2){const t=n<0;let s;return t?s="-"+(""+-n).padStart(e,"0"):s=(""+n).padStart(e,"0"),s}function st(n){if(!(H(n)||n===null||n===""))return parseInt(n,10)}function ft(n){if(!(H(n)||n===null||n===""))return parseFloat(n)}function Hs(n){if(!(H(n)||n===null||n==="")){const e=parseFloat("0."+n)*1e3;return Math.floor(e)}}function Gs(n,e,t="round"){const s=10**e;switch(t){case"expand":return n>0?Math.ceil(n*s)/s:Math.floor(n*s)/s;case"trunc":return Math.trunc(n*s)/s;case"round":return Math.round(n*s)/s;case"floor":return Math.floor(n*s)/s;case"ceil":return Math.ceil(n*s)/s;default:throw new RangeError(`Value rounding ${t} is out of range`)}}function cn(n){return n%4===0&&(n%100!==0||n%400===0)}function At(n){return cn(n)?366:365}function Un(n,e){const t=wl(e-1,12)+1,s=n+(e-t)/12;return t===2?cn(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function Yn(n){let e=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second,n.millisecond);return n.year<100&&n.year>=0&&(e=new Date(e),e.setUTCFullYear(n.year,n.month-1,n.day)),+e}function zr(n,e,t){return-Bs(qs(n,1,e),t)+e-1}function rn(n,e=4,t=1){const s=zr(n,e,t),r=zr(n+1,e,t);return(At(n)-s+r)/7}function Ps(n){return n>99?n:n>ce.twoDigitCutoffYear?1900+n:2e3+n}function so(n,e,t,s=null){const r=new Date(n),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(t,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function Jn(n,e){let t=parseInt(n,10);Number.isNaN(t)&&(t=0);const s=parseInt(e,10)||0,r=t<0||Object.is(t,-0)?-s:s;return t*60+r}function ro(n){const e=Number(n);if(typeof n=="boolean"||n===""||!Number.isFinite(e))throw new ye(`Invalid unit value ${n}`);return e}function Wn(n,e){const t={};for(const s in n)if(Vt(n,s)){const r=n[s];if(r==null)continue;t[e(s)]=ro(r)}return t}function tn(n,e){const t=Math.trunc(Math.abs(n/60)),s=Math.trunc(Math.abs(n%60)),r=n>=0?"+":"-";switch(e){case"short":return`${r}${fe(t,2)}:${fe(s,2)}`;case"narrow":return`${r}${t}${s>0?`:${s}`:""}`;case"techie":return`${r}${fe(t,2)}${fe(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function Qn(n){return gl(n,["hour","minute","second","millisecond"])}const _l=["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"],El=["J","F","M","A","M","J","J","A","S","O","N","D"];function oo(n){switch(n){case"narrow":return[...El];case"short":return[...io];case"long":return[..._l];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"],vl=["M","T","W","T","F","S","S"];function co(n){switch(n){case"narrow":return[...vl];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"],Ol=["Before Christ","Anno Domini"],kl=["BC","AD"],bl=["B","A"];function fo(n){switch(n){case"narrow":return[...bl];case"short":return[...kl];case"long":return[...Ol];default:return null}}function Tl(n){return uo[n.hour<12?0:1]}function Sl(n,e){return co(e)[n.weekday-1]}function Rl(n,e){return oo(e)[n.month-1]}function Il(n,e){return fo(e)[n.year<0?0:1]}function xl(n,e,t="always",s=!1){const r={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(n)===-1;if(t==="auto"&&i){const m=n==="days";switch(e){case 1:return m?"tomorrow":`next ${r[n][0]}`;case-1:return m?"yesterday":`last ${r[n][0]}`;case 0:return m?"today":`this ${r[n][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[n],d=s?l?c[1]:c[2]||c[1]:l?r[n][0]:n;return o?`${a} ${d} ago`:`in ${a} ${d}`}function Zr(n,e){let t="";for(const s of n)s.literal?t+=s.val:t+=e(s.val);return t}const Nl={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,t={}){return new ge(e,t)}static parseFormat(e){let t=null,s="",r=!1;const i=[];for(let o=0;o<e.length;o++){const a=e.charAt(o);a==="'"?((s.length>0||r)&&i.push({literal:r||/^\s+$/.test(s),val:s===""?"'":s}),t=null,s="",r=!r):r||a===t?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,t=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return Nl[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0,s=void 0){if(this.opts.forceSimple)return fe(e,t);const r={...this.opts};return t>0&&(r.padTo=t),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,t){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(f,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?Tl(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,g)=>s?Rl(e,f):i(g?{month:f}:{month:f,day:"numeric"},"month"),c=(f,g)=>s?Sl(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?Il(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(t),u)}formatDurationFromString(e,t){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(d,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(t),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 Ut(...n){const e=n.reduce((t,s)=>t+s.source,"");return RegExp(`^${e}$`)}function Wt(...n){return e=>n.reduce(([t,s,r],i)=>{const[o,a,l]=i(e,r);return[{...t,...o},a||s,l]},[{},null,1]).slice(0,2)}function jt(n,...e){if(n==null)return[null,null];for(const[t,s]of e){const r=t.exec(n);if(r)return s(r)}return[null,null]}function mo(...n){return(e,t)=>{const s={};let r;for(r=0;r<n.length;r++)s[n[r]]=st(e[t+r]);return[s,null,t+r]}}const po=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Dl=`(?:${po.source}?(?:\\[(${ho.source})\\])?)?`,Ys=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,yo=RegExp(`${Ys.source}${Dl}`),Js=RegExp(`(?:[Tt]${yo.source})?`),Al=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Cl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Fl=/(\d{4})-?(\d{3})/,$l=mo("weekYear","weekNumber","weekDay"),Ml=mo("year","ordinal"),Pl=/(\d{4})-(\d\d)-(\d\d)/,go=RegExp(`${Ys.source} ?(?:${po.source}|(${ho.source}))?`),Ll=RegExp(`(?: ${go.source})?`);function Ct(n,e,t){const s=n[e];return H(s)?t:st(s)}function Vl(n,e){return[{year:Ct(n,e),month:Ct(n,e+1,1),day:Ct(n,e+2,1)},null,e+3]}function zt(n,e){return[{hours:Ct(n,e,0),minutes:Ct(n,e+1,0),seconds:Ct(n,e+2,0),milliseconds:Hs(n[e+3])},null,e+4]}function un(n,e){const t=!n[e]&&!n[e+1],s=Jn(n[e+1],n[e+2]),r=t?null:_e.instance(s);return[{},r,e+3]}function dn(n,e){const t=n[e]?et.create(n[e]):null;return[{},t,e+1]}const Ul=RegExp(`^T?${Ys.source}$`),Wl=/^-?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 jl(n){const[e,t,s,r,i,o,a,l,c]=n,d=e[0]==="-",m=l&&l[0]==="-",u=(f,g=!1)=>f!==void 0&&(g||f&&d)?-f:f;return[{years:u(ft(t)),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(n,e,t,s,r,i,o){const a={year:e.length===2?Ps(st(e)):st(e),month:io.indexOf(t)+1,day:st(s),hour:st(r),minute:st(i)};return o&&(a.second=st(o)),n&&(a.weekday=n.length>3?ao.indexOf(n)+1:lo.indexOf(n)+1),a}const Zl=/^(?:(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 ql(n){const[,e,t,s,r,i,o,a,l,c,d,m]=n,u=Qs(e,r,s,t,i,o,a);let f;return l?f=zl[l]:c?f=0:f=Jn(d,m),[u,new _e(f)]}function Bl(n){return n.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Hl=/^(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$/,Gl=/^(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$/,Yl=/^(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(n){const[,e,t,s,r,i,o,a]=n;return[Qs(e,r,s,t,i,o,a),_e.utcInstance]}function Jl(n){const[,e,t,s,r,i,o,a]=n;return[Qs(e,a,t,s,r,i,o),_e.utcInstance]}const Ql=Ut(Al,Js),Kl=Ut(Cl,Js),Xl=Ut(Fl,Js),ec=Ut(yo),wo=Wt(Vl,zt,un,dn),tc=Wt($l,zt,un,dn),nc=Wt(Ml,zt,un,dn),sc=Wt(zt,un,dn);function rc(n){return jt(n,[Ql,wo],[Kl,tc],[Xl,nc],[ec,sc])}function ic(n){return jt(Bl(n),[Zl,ql])}function oc(n){return jt(n,[Hl,qr],[Gl,qr],[Yl,Jl])}function ac(n){return jt(n,[Wl,jl])}const lc=Wt(zt);function cc(n){return jt(n,[Ul,lc])}const uc=Ut(Pl,Ll),dc=Ut(go),fc=Wt(zt,un,dn);function hc(n){return jt(n,[uc,wo],[dc,fc])}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}},mc={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,St=146097/4800,pc={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:St/7,days:St,hours:St*24,minutes:St*24*60,seconds:St*24*60*60,milliseconds:St*24*60*60*1e3},..._o},yt=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],yc=yt.slice(0).reverse();function Je(n,e,t=!1){const s={values:t?e.values:{...n.values,...e.values||{}},loc:n.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||n.conversionAccuracy,matrix:e.matrix||n.matrix};return new te(s)}function Eo(n,e){let t=e.milliseconds??0;for(const s of yc.slice(1))e[s]&&(t+=e[s]*n[s].milliseconds);return t}function Hr(n,e){const t=Eo(n,e)<0?-1:1;yt.reduceRight((s,r)=>{if(H(e[r]))return s;if(s){const i=e[s]*t,o=n[r][s],a=Math.floor(i/o);e[r]+=a*t,e[s]-=a*o*t}return r},null),yt.reduce((s,r)=>{if(H(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*n[s][r]}return r},null)}function Gr(n){const e={};for(const[t,s]of Object.entries(n))s!==0&&(e[t]=s);return e}class te{constructor(e){const t=e.conversionAccuracy==="longterm"||!1;let s=t?pc:mc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||re.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,t){return te.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new 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(t),conversionAccuracy:t.conversionAccuracy,matrix:t.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,t){const[s]=ac(e);return s?te.fromObject(s,t):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){const[s]=cc(e);return s?te.fromObject(s,t):te.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new ye("need to specify a reason the Duration is invalid");const s=e instanceof Pe?e:new Pe(e,t);if(ce.throwOnInvalid)throw new ja(s);return new te({invalid:s})}static normalizeUnit(e){const t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new Ri(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){const s={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?ge.create(this.loc,s).formatDurationFromString(this,e):Br}toHuman(e={}){if(!this.isValid)return Br;const t=e.showZeros!==!1,s=yt.map(r=>{const i=this.values[r];return H(i)||i===0&&!t?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Gs(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},L.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Eo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e),s={};for(const r of yt)(Vt(t.values,r)||Vt(this.values,r))&&(s[r]=t.get(r)+this.get(r));return Je(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;const t={};for(const s of Object.keys(this.values))t[s]=ro(e(this.values[s],s));return Je(this,{values:t},!0)}get(e){return this[te.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const t={...this.values,...Wn(e,te.normalizeUnit)};return Je(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:r,conversionAccuracy:s};return 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 t={},s={},r=this.toObject();let i;for(const o of yt)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);t[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&&(t[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return Hr(this.matrix,t),Je(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return 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 t(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of yt)if(!t(this.values[s],e.values[s]))return!1;return!0}}const Rt="Invalid Interval";function gc(n,e){return!n||!n.isValid?le.invalid("missing or invalid start"):!e||!e.isValid?le.invalid("missing or invalid end"):e<n?le.invalid("end before start",`The end of an interval must be after its start, but you had start=${n.toISO()} and end=${e.toISO()}`):null}class le{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new ye("need to specify a reason the Interval is invalid");const s=e instanceof Pe?e:new Pe(e,t);if(ce.throwOnInvalid)throw new Wa(s);return new le({invalid:s})}static fromDateTimes(e,t){const s=Bt(e),r=Bt(t),i=gc(s,r);return i??new le({start:s,end:r})}static after(e,t){const s=te.fromDurationLike(t),r=Bt(e);return le.fromDateTimes(r,r.plus(s))}static before(e,t){const s=te.fromDurationLike(t),r=Bt(e);return le.fromDateTimes(r.minus(s),r)}static fromISO(e,t){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=L.fromISO(s,t),o=i.isValid}catch{o=!1}let a,l;try{a=L.fromISO(r,t),l=a.isValid}catch{l=!1}if(o&&l)return le.fromDateTimes(i,a);if(o){const c=te.fromISO(r,t);if(c.isValid)return le.after(i,c)}else if(l){const c=te.fromISO(s,t);if(c.isValid)return le.before(a,c)}}return le.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",t){if(!this.isValid)return NaN;const s=this.start.startOf(e,t);let r;return t?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,t),Math.floor(r.diff(s,e).get(e))+(r.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?le.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];const t=e.map(Bt).filter(o=>this.contains(o)).sort((o,a)=>o.toMillis()-a.toMillis()),s=[];let{s:r}=this,i=0;for(;r<this.e;){const o=t[i]||this.e,a=+o>+this.e?this.e:o;s.push(le.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const t=te.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(t.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(le.fromDateTimes(s,i)),s=i,r+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const t=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return t>=s?null:le.fromDateTimes(t,s)}union(e){if(!this.isValid)return this;const t=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return le.fromDateTimes(t,s)}static merge(e){const[t,s]=e.sort((r,i)=>r.s-i.s).reduce(([r,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[r,i.union(o)]:[r.concat([i]),o]:[r,o],[[],null]);return s&&t.push(s),t}static xor(e){let t=null,s=0;const r=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((l,c)=>l.time-c.time);for(const l of a)s+=l.type==="s"?1:-1,s===1?t=l.time:(t&&+t!=+l.time&&r.push(le.fromDateTimes(t,l.time)),t=null);return le.merge(r)}difference(...e){return le.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Rt}[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,t={}){return this.isValid?ge.create(this.s.loc.clone(t),e).formatInterval(this):Rt}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:Rt}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Rt}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:Rt}toFormat(e,{separator:t=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:Rt}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):te.invalid(this.invalidReason)}mapEndpoints(e){return le.fromDateTimes(e(this.s),e(this.e))}}class pn{static hasDST(e=ce.defaultZone){const t=L.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return et.isValidZone(e)}static normalizeZone(e){return rt(e,ce.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||re.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||re.create(t,s,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||re.create(t,s,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||re.create(t,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:s=null,locObj:r=null}={}){return(r||re.create(t,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return re.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return re.create(t,null,"gregory").eras(e)}static features(){return{relative:to(),localeWeek:no()}}}function Yr(n,e){const t=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=t(e)-t(n);return Math.floor(te.fromMillis(s).as("days"))}function wc(n,e,t){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const d=Yr(l,c);return(d-d%7)/7}],["days",Yr]],r={},i=n;let o,a;for(const[l,c]of s)t.indexOf(l)>=0&&(o=l,r[l]=c(n,e),a=i.plus(r),a>e?(r[l]--,n=i.plus(r),n>e&&(a=n,r[l]--,n=i.plus(r))):n=a);return[n,r,a,o]}function _c(n,e,t,s){let[r,i,o,a]=wc(n,e,t);const l=e-r,c=t.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 Ec="missing Intl.DateTimeFormat.formatToParts support";function se(n,e=t=>t){return{regex:n,deser:([t])=>e(ul(t))}}const vc=" ",vo=`[ ${vc}]`,Oo=new RegExp(vo,"g");function Oc(n){return n.replace(/\./g,"\\.?").replace(Oo,vo)}function Jr(n){return n.replace(/\./g,"").replace(Oo," ").toLowerCase()}function Me(n,e){return n===null?null:{regex:RegExp(n.map(Oc).join("|")),deser:([t])=>n.findIndex(s=>Jr(t)===Jr(s))+e}}function Qr(n,e){return{regex:n,deser:([,t,s])=>Jn(t,s),groups:e}}function yn(n){return{regex:n,deser:([e])=>e}}function kc(n){return n.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function bc(n,e){const t=$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(kc(y.val)),deser:([w])=>w,literal:!0}),v=(y=>{if(n.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 yn(d);case"uu":return yn(a);case"uuu":return se(t);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(t);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 yn(/[a-z_+-/]{1,256}?/i);case" ":return yn(/[^\S\n\r]/);default:return f(y)}})(n)||{invalidReason:Ec};return v.token=n,v}const Tc={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 Sc(n,e,t){const{type:s,value:r}=n;if(s==="literal"){const l=/^\s+$/.test(r);return{literal:!l,val:l?" ":r}}const i=e[s];let o=s;s==="hour"&&(e.hour12!=null?o=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?o="hour12":o="hour24":o=t.hour12?"hour12":"hour24");let a=Tc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Rc(n){return[`^${n.map(t=>t.regex).reduce((t,s)=>`${t}(${s.source})`,"")}$`,n]}function Ic(n,e,t){const s=n.match(e);if(s){const r={};let i=1;for(const o in t)if(Vt(t,o)){const a=t[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function xc(n){const e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let t=null,s;return H(n.z)||(t=et.create(n.z)),H(n.Z)||(t||(t=new _e(n.Z)),s=n.Z),H(n.q)||(n.M=(n.q-1)*3+1),H(n.h)||(n.h<12&&n.a===1?n.h+=12:n.h===12&&n.a===0&&(n.h=0)),n.G===0&&n.y&&(n.y=-n.y),H(n.u)||(n.S=Hs(n.u)),[Object.keys(n).reduce((i,o)=>{const a=e(o);return a&&(i[a]=n[o]),i},{}),t,s]}let cs=null;function Nc(){return cs||(cs=L.fromMillis(1555555555555)),cs}function Dc(n,e){if(n.literal)return n;const t=ge.macroTokenToFormatOpts(n.val),s=So(t,e);return s==null||s.includes(void 0)?n:s}function ko(n,e){return Array.prototype.concat(...n.map(t=>Dc(t,e)))}class bo{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=ko(ge.parseFormat(t),e),this.units=this.tokens.map(s=>bc(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Rc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[t,s]=Ic(e,this.regex,this.handlers),[r,i,o]=s?xc(s):[null,null,void 0];if(Vt(s,"a")&&Vt(s,"H"))throw new Nt("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:s,result:r,zone:i,specificOffset:o}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function To(n,e,t){return new bo(n,t).explainFromTokens(e)}function Ac(n,e,t){const{result:s,zone:r,specificOffset:i,invalidReason:o}=To(n,e,t);return[s,r,i,o]}function So(n,e){if(!n)return null;const s=ge.create(e,n).dtFormatter(Nc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Sc(o,n,i))}const us="Invalid DateTime",Kr=864e13;function Jt(n){return new Pe("unsupported zone",`the zone "${n.name}" is not supported`)}function ds(n){return n.weekData===null&&(n.weekData=Vn(n.c)),n.weekData}function fs(n){return n.localWeekData===null&&(n.localWeekData=Vn(n.c,n.loc.getMinDaysInFirstWeek(),n.loc.getStartOfWeek())),n.localWeekData}function ht(n,e){const t={ts:n.ts,zone:n.zone,c:n.c,o:n.o,loc:n.loc,invalid:n.invalid};return new L({...t,...e,old:t})}function Ro(n,e,t){let s=n-e*60*1e3;const r=t.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=t.offset(s);return r===i?[s,r]:[n-Math.min(r,i)*60*1e3,Math.max(r,i)]}function gn(n,e){n+=e*60*1e3;const t=new Date(n);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function vn(n,e,t){return Ro(Yn(n),e,t)}function Xr(n,e){const t=n.o,s=n.c.year+Math.trunc(e.years),r=n.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...n.c,year:s,month:r,day:Math.min(n.c.day,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,t,n.zone);return o!==0&&(l+=o,c=n.zone.offset(l)),{ts:l,o:c}}function It(n,e,t,s,r,i){const{setZone:o,zone:a}=t;if(n&&Object.keys(n).length!==0||e){const l=e||a,c=L.fromObject(n,{...t,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return L.invalid(new Pe("unparsable",`the input "${r}" can't be parsed as ${s}`))}function wn(n,e,t=!0){return n.isValid?ge.create(re.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(n,e):null}function hs(n,e,t){const s=n.c.year>9999||n.c.year<0;let r="";if(s&&n.c.year>=0&&(r+="+"),r+=fe(n.c.year,s?6:4),t==="year")return r;if(e){if(r+="-",r+=fe(n.c.month),t==="month")return r;r+="-"}else if(r+=fe(n.c.month),t==="month")return r;return r+=fe(n.c.day),r}function ei(n,e,t,s,r,i,o){let a=!t||n.c.millisecond!==0||n.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=fe(n.c.hour),o==="hour")break;if(e){if(l+=":",l+=fe(n.c.minute),o==="minute")break;a&&(l+=":",l+=fe(n.c.second))}else{if(l+=fe(n.c.minute),o==="minute")break;a&&(l+=fe(n.c.second))}if(o==="second")break;a&&(!s||n.c.millisecond!==0)&&(l+=".",l+=fe(n.c.millisecond,3))}return r&&(n.isOffsetFixed&&n.offset===0&&!i?l+="Z":n.o<0?(l+="-",l+=fe(Math.trunc(-n.o/60)),l+=":",l+=fe(Math.trunc(-n.o%60))):(l+="+",l+=fe(Math.trunc(n.o/60)),l+=":",l+=fe(Math.trunc(n.o%60)))),i&&(l+="["+n.zone.ianaName+"]"),l}const Io={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Cc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Fc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},On=["year","month","day","hour","minute","second","millisecond"],$c=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Mc=["year","ordinal","hour","minute","second","millisecond"];function kn(n){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[n.toLowerCase()];if(!e)throw new Ri(n);return e}function ti(n){switch(n.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return kn(n)}}function Pc(n){if(Qt===void 0&&(Qt=ce.now()),n.type!=="iana")return n.offset(Qt);const e=n.name;let t=Ls.get(e);return t===void 0&&(t=n.offset(Qt),Ls.set(e,t)),t}function ni(n,e){const t=rt(e.zone,ce.defaultZone);if(!t.isValid)return L.invalid(Jt(t));const s=re.fromObject(e);let r,i;if(H(n.year))r=ce.now();else{for(const l of On)H(n[l])&&(n[l]=Io[l]);const o=Xi(n)||eo(n);if(o)return L.invalid(o);const a=Pc(t);[r,i]=vn(n,a,t)}return new L({ts:r,zone:t,loc:s,o:i})}function si(n,e,t){const s=H(t.round)?!0:t.round,r=H(t.rounding)?"trunc":t.rounding,i=(a,l)=>(a=Gs(a,s||t.calendary?0:2,t.calendary?"round":r),e.loc.clone(t).relFormatter(t).format(a,l)),o=a=>t.calendary?e.hasSame(n,a)?0:e.startOf(a).diff(n.startOf(a),a).get(a):e.diff(n,a).get(a);if(t.unit)return i(o(t.unit),t.unit);for(const a of t.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(n>e?-0:0,t.units[t.units.length-1])}function ri(n){let e={},t;return n.length>0&&typeof n[n.length-1]=="object"?(e=n[n.length-1],t=Array.from(n).slice(0,n.length-1)):t=Array.from(n),[e,t]}let Qt;const Ls=new Map;class L{constructor(e){const t=e.zone||ce.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Pe("invalid input"):null)||(t.isValid?null:Jt(t));this.ts=H(e.ts)?ce.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[r,i]=[e.old.c,e.old.o];else{const a=at(e.o)&&!e.old?e.o:t.offset(this.ts);r=gn(this.ts,a),s=Number.isNaN(r.year)?new Pe("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=t,this.loc=e.loc||re.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new L({})}static local(){const[e,t]=ri(arguments),[s,r,i,o,a,l,c]=t;return ni({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,t]=ri(arguments),[s,r,i,o,a,l,c]=t;return e.zone=_e.utcInstance,ni({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,t={}){const s=pl(e)?e.valueOf():NaN;if(Number.isNaN(s))return L.invalid("invalid input");const r=rt(t.zone,ce.defaultZone);return r.isValid?new L({ts:s,zone:r,loc:re.fromObject(t)}):L.invalid(Jt(r))}static fromMillis(e,t={}){if(at(e))return e<-Kr||e>Kr?L.invalid("Timestamp out of range"):new L({ts:e,zone:rt(t.zone,ce.defaultZone),loc:re.fromObject(t)});throw new ye(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(at(e))return new L({ts:e*1e3,zone:rt(t.zone,ce.defaultZone),loc:re.fromObject(t)});throw new ye("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};const s=rt(t.zone,ce.defaultZone);if(!s.isValid)return L.invalid(Jt(s));const r=re.fromObject(t),i=Wn(e,ti),{minDaysInFirstWeek:o,startOfWeek:a}=Wr(i,r),l=ce.now(),c=H(t.specificOffset)?s.offset(l):t.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 Nt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new Nt("Can't mix ordinal dates with month/day");const v=g||i.weekday&&!f;let y,w,R=gn(l,c);v?(y=$c,w=Cc,R=Vn(R,o,a)):d?(y=Mc,w=Fc,R=ls(R)):(y=On,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?fl(i,o,a):d?hl(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]=vn(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,t={}){const[s,r]=rc(e);return It(s,r,t,"ISO 8601",e)}static fromRFC2822(e,t={}){const[s,r]=ic(e);return It(s,r,t,"RFC 2822",e)}static fromHTTP(e,t={}){const[s,r]=oc(e);return It(s,r,t,"HTTP",t)}static fromFormat(e,t,s={}){if(H(e)||H(t))throw new ye("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,d]=Ac(o,e,t);return d?L.invalid(d):It(a,l,s,`format ${t}`,e,c)}static fromString(e,t,s={}){return L.fromFormat(e,t,s)}static fromSQL(e,t={}){const[s,r]=hc(e);return It(s,r,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new ye("need to specify a reason the DateTime is invalid");const s=e instanceof Pe?e:new Pe(e,t);if(ce.throwOnInvalid)throw new Ua(s);return new L({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){const s=So(e,re.fromObject(t));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,t={}){return ko(ge.parseFormat(e),re.fromObject(t)).map(r=>r.val).join("")}static resetCache(){Qt=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?pn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?pn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?pn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?pn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,t=6e4,s=Yn(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*t),a=this.zone.offset(s-i*t);if(o===a)return[this];const l=s-o*t,c=s-a*t,d=gn(l,o),m=gn(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 cn(this.year)}get daysInMonth(){return Un(this.year,this.month)}get daysInYear(){return this.isValid?At(this.year):NaN}get weeksInWeekYear(){return this.isValid?rn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?rn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:t,numberingSystem:s,calendar:r}=ge.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:s,outputCalendar:r}}toUTC(e=0,t={}){return this.setZone(_e.instance(e),t)}toLocal(){return this.setZone(ce.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:s=!1}={}){if(e=rt(e,ce.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(t||s){const i=e.offset(this.ts),o=this.toObject();[r]=vn(o,i,e)}return ht(this,{ts:r,zone:e})}else return L.invalid(Jt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:s});return ht(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const t=Wn(e,ti),{minDaysInFirstWeek:s,startOfWeek:r}=Wr(t,this.loc),i=!H(t.weekYear)||!H(t.weekNumber)||!H(t.weekday),o=!H(t.ordinal),a=!H(t.year),l=!H(t.month)||!H(t.day),c=a||l,d=t.weekYear||t.weekNumber;if((c||o)&&d)throw new Nt("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new Nt("Can't mix ordinal dates with month/day");let m;i?m=Vr({...Vn(this.c,s,r),...t},s,r):H(t.ordinal)?(m={...this.toObject(),...t},H(t.day)&&(m.day=Math.min(Un(m.year,m.month),m.day))):m=Ur({...ls(this.c),...t});const[u,f]=vn(m,this.o,this.zone);return ht(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e);return ht(this,Xr(this,t))}minus(e){if(!this.isValid)return this;const t=te.fromDurationLike(e).negate();return ht(this,Xr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;const s={},r=te.normalizeUnit(e);switch(r){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(r==="weeks")if(t){const i=this.loc.getStartOfWeek(),{weekday:o}=this;o<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(r==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?ge.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):us}toLocaleString(e=Ln,t={}){return this.isValid?ge.create(this.loc.clone(t),e).formatDateTime(this):us}toLocaleParts(e={}){return this.isValid?ge.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=kn(o);const a=e==="extended";let l=hs(this,a,o);return On.indexOf(o)>=3&&(l+="T"),l+=ei(this,a,t,s,r,i,o),l}toISODate({format:e="extended",precision:t="day"}={}){return this.isValid?hs(this,e==="extended",kn(t)):null}toISOWeekDate(){return wn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=kn(a),(r&&On.indexOf(a)>=3?"T":"")+ei(this,o==="extended",t,e,s,i,a)):null}toRFC2822(){return wn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return wn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?hs(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(t||e)&&(s&&(r+=" "),t?r+="z":e&&(r+="ZZ")),wn(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 t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",s={}){if(!this.isValid||!e.isValid)return te.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=yl(t).map(te.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=_c(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",t={}){return this.diff(L.now(),e,t)}until(e){return this.isValid?le.fromDateTimes(this,e):this}hasSame(e,t,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,s)<=r&&r<=i.endOf(t,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const t=e.base||L.fromObject({},{zone:this.zone}),s=e.padding?this<t?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),si(t,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,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(L.isDateTime))throw new ye("max requires all arguments be DateTimes");return jr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return To(o,e,t)}static fromStringExplain(e,t,s={}){return L.fromFormatExplain(e,t,s)}static buildFormatParser(e,t={}){const{locale:s=null,numberingSystem:r=null}=t,i=re.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new bo(i,e)}static fromFormatParser(e,t,s={}){if(H(e)||H(t))throw new ye("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=re.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(t.locale))throw new ye(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${t.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=t.explainFromTokens(e);return d?L.invalid(d):It(a,l,s,`format ${t.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 Za}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 Bt(n){if(L.isDateTime(n))return n;if(n&&n.valueOf&&at(n.valueOf()))return L.fromJSDate(n);if(n&&typeof n=="object")return L.fromObject(n);throw new ye(`Unknown datetime argument: ${n}, of type ${typeof n}`)}const Lc=(n,e)=>{const t={};if(n.includeFields){const s=e.collections[n.collection];if(!s)return an(pe());n.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?t[r]=xo(i)?.nullable():t[r]=pe()})}return je({Collection_Path:kt(Se()),...t})},Vc=(n,e,t,s)=>{let r=je({}).catchall(Lc(n,e)),i;if(!s&&t){const o=Ce(n,t);i=Ht(o.admin?.skipFormRequiredValidation)}return(!n.required||i)&&(r=r.optional()),r},Uc=()=>pe().refine(n=>n===null||n&&(n.seconds!==void 0&&n.nanoseconds!==void 0||n._seconds!==void 0&&n._nanoseconds!==void 0),{message:"Must be a valid date"}),xo=(n,e,t)=>{let s;const r=`${Ht(n.description)}
2
2
 
3
- `||"";let i,o,a;if(!t&&e){const l=Ae(n,e);i=l.admin?.condition?.form!==void 0&&!Bt(l.admin.condition.form),o=Bt(l.admin?.skipFormRequiredValidation),a=Bt(l.admin?.image)}switch(n.type){case"String":s=Te(),n.length&&(s=s.length(n.length,`Must be ${n.length} character(s) long`)),n.minlength&&(s=s.min(n.minlength,`Must contain at least ${n.minlength} character(s)`)),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} character(s)`)),n.email?s=s.email("Must be a valid email address"):n.uuid?s=Oe([s.uuid("Must be a valid UUID"),ke("")]):n.url?s=Oe([s.url("Must be a valid URL"),ke("")]):n.emoji?s=Oe([s.emoji("Must be a valid emoji"),ke("")]):n.ip?s=Oe([s.ip("Must be a valid IP address"),ke("")]):n.pattern&&(!t&&a?s=Oe([s.regex(new RegExp(n.pattern)),s.regex(/^blob:/)],{message:"Must be a valid value"}):s=s.regex(new RegExp(n.pattern),"Must be a valid value")),n.values&&(s=Oe([$n(n.values,{message:`Must be one of the following values: ${n.values.join(", ")}`}),ss()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=Xt(),r&&(s=s.describe(r.trim()));break;case"Number":n.autoIncrement?s=Oe([ss(),mt().int()],{message:"Must be a valid number"}):(s=mt({message:"Must be a valid number"}),n.min&&(s=s.min(n.min,`Must be greater than or equal to ${n.min}`)),n.max&&(s=s.max(n.max,`Must be less than or equal to ${n.max}`)),n.decimal?t?s=s.describe(`${r}Must have ${n.decimal} decimal places`):s=s.refine(l=>n.decimal?(l.toString().split(".")[1]?.length||0)<=n.decimal:!1,{message:`Must have ${n.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),n.values?(t||(s=Oe([s.refine(l=>n.values?.includes(l),{message:`Must be one of the following values: ${n.values.join(", ")}`}),ss()])),s=s.describe(`${r}Must be one of the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":t?(s=We({seconds:mt(),nanoseconds:mt()}),n.min&&n.max?s=s.describe(`${r}Must be between ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)} and ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`):n.min?s=s.describe(`${r}Must be greater than or equal to ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)}`):n.max?s=s.describe(`${r}Must be less than or equal to ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Vc(),n.min&&(s=s.refine(l=>l.toMillis()>=n.min,{message:`Must be greater than or equal to ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)}`})),n.max&&(s=s.refine(l=>l.toMillis()<=n.max,{message:`Must be less than or equal to ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`})));break;case"Array":s=vt(me()),n.length&&(s=s.length(n.length,`Must contain ${n.length} item(s)`)),n.minlength?s=s.min(n.minlength,`Must contain at least ${n.minlength} item(s)`):n.required&&!i&&(s=s.nonempty("Must contain at least one item")),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} item(s)`)),n.values?(t||(s=s.refine(l=>{let c=!0;return l.forEach(d=>{n.values&&!n.values.includes(d)&&(c=!1)}),c},{message:`Must only contain the following values: ${n.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())),n.nullable&&(s=s.nullable());break;case"Map":n.required&&!i?t?s=We({}).catchall(me()).describe(`${r}Must be an object. Must contain at least one object property.`):s=on(me()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=We({}).catchall(me()).describe(`${r}Must be an object`);break;case"Computed":s=me()}return(!n.required||i||o)&&(s=s.optional()),s},Uc=(n,e,t,s,r)=>{const{auth:i,softDelete:o}=n,a={};n.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(ee(c)?(a[c.name]=Lc(c,e,t,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=Io(c,t,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=Oe([ke("create"),ke("update"),ke("delete")]).optional(),a.password=Te().optional(),a.passwordConfirm=Te().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=Xt().optional(),a[`operations-${c.labels.collection}`]=vt(Oe([ke("Read"),ke("Create"),ke("Update"),ke("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=Xt().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=Xt().optional()}),c.access.entityRestrictions?.restrictions?.forEach(d=>{if(d.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=We({}).catchall(me()).optional()),d.type==="Parent"||d.type==="Parent_Property"){const m=U(c.fields,d.collectionField);a[`accessible-${c.labels.collection}-${m.collection}`]=We({}).catchall(me()).optional()}})}));const l=We(a);return n.allowSchemalessFields?l.passthrough():l.strict()},ri=async(n,e)=>{if(n){const t=await oe(n,[e]);if(!t.valid)throw new Error(t.message)}},rn=async(n,e,t,s,r,i)=>{await ri(s.custom?.preValidate,r);for(const a of s.fields)await ri(a.custom?.preValidate,r);return Ti(n,t,i).parse(e),e},Qs=(n,e,t,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=>{n!=="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:t}),I&&I.size++)}),E.forEach(p=>{if(ut(p,o,i)){const F=fn(p,o,i),A={};r[p.name]!==void 0&&(A[p.name]=r[p.name],ee(p)&&(A[`${p.name}_Array`]=r[`${p.name}_Array`])),F.forEach(j=>{r[j.name]!==void 0&&(ee(j)?A[`${j.name}_Array`]=r[`${j.name}_Array`]:A[j.name]=r[j.name])}),Object.keys(A).length>0&&(n==="create"&&(A.Collection_Path=t,A.Collection_Path_String=t.join("/"),e.set(u(p),A)),n==="update"&&e.update(u(p),A),n==="delete"&&e.delete(u(p)),I&&I.size++)}});const C=l[o.labels.collection];for(const p of C){const F=ca(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&&(n==="create"&&(A.Collection_Path||=t,A.Collection_Path_String=t.join("/"),e.set(g(p.key),A)),n==="update"&&e.update(g(p.key),A),n==="delete"&&e.delete(g(p.key)),I&&I.size++)}const _=(p,F)=>{let A=1;ut(F,p,i)&&A++,p.fields.forEach(h=>{ut(h,p,i)&&JSON.parse(es(fn(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)&&ee(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),ut(A,F,i)&&e.update(y(p,A.name,j),{[`${A.name}.${s}`]:m(),[`${A.name}_Array`]:d(s)}),F.fields.forEach(T=>{ut(T,F,i)&&JSON.parse(es(fn(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)&&ee(A)&&e.update(w(p,T.key,j),S)};if(n==="delete")return;const k=E.filter(p=>ee(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=ht(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(ee(A)){if(r[`${p.name}_Array`])for(const[S,b]of Object.entries(r[p.name])){if(n==="update"&&R&&R[`${p.name}_Array`]?.includes(S))continue;const T={...R,...r};rt(T);const N={};A.includeFields&&A.includeFields.forEach(z=>{if(T[z]!==void 0){N[z]=T[z];const x=U(o.fields,z);Et(o,[x]).size===1&&(N[`${z}_Lowercase`]=T[`${z}_Lowercase`])}});const q={[`${p.twoWay}.${s}`]:{Collection_Path:t,...N},[`${p.twoWay}_Array`]:c(s)};h.includes(A.name)&&(q[`${p.twoWay}_Single`]={Collection_Path:t,id:s,...N});const M=Sn(r);e.update(v(b.Collection_Path,S),{...q,...M}),I.size++,ut(A,F,i)&&(e.update(y(p,A.name,S),{[`${A.name}.${s}`]:{Collection_Path:t,...N},[`${A.name}_Array`]:c(s)}),I.size++),F.fields.forEach(z=>{if(ut(z,F,i)){const x=JSON.parse(es(fn(z,F,i))),K={};x.includes(A.name)&&(K[`${p.twoWay}_Array`]=c(s)),Object.keys(M).forEach(B=>{x.includes(B)&&(K[B]=M[B])}),Object.keys(K).length>0&&(e.update(y(p,z.name,S),K),I.size++)}});const Y=l[F.labels.collection];for(const z of Y)if(z.fields.some(x=>x.name===A.name)){const x={...q};Object.keys(M).forEach(K=>{z.fields.some(B=>B.name===K)&&(x[K]=M[K])}),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(ee(A)){if(n==="update"&&R&&!(r[p.name]&&be(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(ee(A)){if(n==="update"&&R&&r[p.name]&&be(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}`)}}},Ve=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]===void 0?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&Ve(n[e]))},Ks=n=>{if(n=n.toString(),/[/]|^\.+$|^__.*__$/.test(n))return!1;try{const s=new TextEncoder().encode(n),r=new TextDecoder().decode(s);if(n!==r)return!1}catch{return!1}return!(new Blob([n]).size>1500)},ii=async(n,e,t,s=1e3,r=5)=>{for(;r>0;)try{await n(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Wn=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},hs=n=>n?Array.isArray(n)?n.map(s=>Wn(s)).filter(s=>s.length>0):Wn(n)||"":"",Wc=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g," ");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>998)throw new Error("Email subject is too long");return e},oi=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
3
+ `||"";let i,o,a;if(!t&&e){const l=Ce(n,e);i=l.admin?.condition?.form!==void 0&&!Ht(l.admin.condition.form),o=Ht(l.admin?.skipFormRequiredValidation),a=Ht(l.admin?.image)}switch(n.type){case"String":s=Se(),n.length&&(s=s.length(n.length,`Must be ${n.length} character(s) long`)),n.minlength&&(s=s.min(n.minlength,`Must contain at least ${n.minlength} character(s)`)),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} character(s)`)),n.email?s=s.email("Must be a valid email address"):n.uuid?s=ke([s.uuid("Must be a valid UUID"),be("")]):n.url?s=ke([s.url("Must be a valid URL"),be("")]):n.emoji?s=ke([s.emoji("Must be a valid emoji"),be("")]):n.ip?s=ke([s.ip("Must be a valid IP address"),be("")]):n.pattern&&(!t&&a?s=ke([s.regex(new RegExp(n.pattern)),s.regex(/^blob:/)],{message:"Must be a valid value"}):s=s.regex(new RegExp(n.pattern),"Must be a valid value")),n.values&&(s=ke([Mn(n.values,{message:`Must be one of the following values: ${n.values.join(", ")}`}),rs()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=en(),r&&(s=s.describe(r.trim()));break;case"Number":n.autoIncrement?s=ke([rs(),pt().int()],{message:"Must be a valid number"}):(s=pt({message:"Must be a valid number"}),n.min&&(s=s.min(n.min,`Must be greater than or equal to ${n.min}`)),n.max&&(s=s.max(n.max,`Must be less than or equal to ${n.max}`)),n.decimal?t?s=s.describe(`${r}Must have ${n.decimal} decimal places`):s=s.refine(l=>n.decimal?(l.toString().split(".")[1]?.length||0)<=n.decimal:!1,{message:`Must have ${n.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),n.values?(t||(s=ke([s.refine(l=>n.values?.includes(l),{message:`Must be one of the following values: ${n.values.join(", ")}`}),rs()])),s=s.describe(`${r}Must be one of the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":t?(s=je({seconds:pt(),nanoseconds:pt()}),n.min&&n.max?s=s.describe(`${r}Must be between ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)} and ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`):n.min?s=s.describe(`${r}Must be greater than or equal to ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)}`):n.max?s=s.describe(`${r}Must be less than or equal to ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Uc(),n.min&&(s=s.refine(l=>l.toMillis()>=n.min,{message:`Must be greater than or equal to ${L.fromMillis(n.min).toLocaleString(L.DATE_MED)}`})),n.max&&(s=s.refine(l=>l.toMillis()<=n.max,{message:`Must be less than or equal to ${L.fromMillis(n.max).toLocaleString(L.DATE_MED)}`})));break;case"Array":s=kt(pe()),n.length&&(s=s.length(n.length,`Must contain ${n.length} item(s)`)),n.minlength?s=s.min(n.minlength,`Must contain at least ${n.minlength} item(s)`):n.required&&!i&&(s=s.nonempty("Must contain at least one item")),n.maxlength&&(s=s.max(n.maxlength,`Must contain at most ${n.maxlength} item(s)`)),n.values?(t||(s=s.refine(l=>{let c=!0;return l.forEach(d=>{n.values&&!n.values.includes(d)&&(c=!1)}),c},{message:`Must only contain the following values: ${n.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${n.values.join(", ")}`)):r&&(s=s.describe(r.trim())),n.nullable&&(s=s.nullable());break;case"Map":n.required&&!i?t?s=je({}).catchall(pe()).describe(`${r}Must be an object. Must contain at least one object property.`):s=an(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(!n.required||i||o)&&(s=s.optional()),s},Wc=(n,e,t,s,r)=>{const{auth:i,softDelete:o}=n,a={};n.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(X(c)?(a[c.name]=Vc(c,e,t,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=xo(c,t,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}`]=en().optional(),a[`operations-${c.labels.collection}`]=kt(ke([be("Read"),be("Create"),be("Update"),be("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=en().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=en().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 n.allowSchemalessFields?l.passthrough():l.strict()},ii=async(n,e)=>{if(n){const t=await oe(n,[e]);if(!t.valid)throw new Error(t.message)}},on=async(n,e,t,s,r,i)=>{await ii(s.custom?.preValidate,r);for(const a of s.fields)await ii(a.custom?.preValidate,r);return Si(n,t,i).parse(e),e},Ks=(n,e,t,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=>{n!=="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:t}),I&&I.size++)}),E.forEach(p=>{if(dt(p,o,i)){const F=hn(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&&(n==="create"&&(A.Collection_Path=t,A.Collection_Path_String=t.join("/"),e.set(u(p),A)),n==="update"&&e.update(u(p),A),n==="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&&(n==="create"&&(A.Collection_Path||=t,A.Collection_Path_String=t.join("/"),e.set(g(p.key),A)),n==="update"&&e.update(g(p.key),A),n==="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(hn(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(hn(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(n==="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(n==="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);Ot(o,[x]).size===1&&(N[`${z}_Lowercase`]=T[`${z}_Lowercase`])}});const q={[`${p.twoWay}.${s}`]:{Collection_Path:t,...N},[`${p.twoWay}_Array`]:c(s)};h.includes(A.name)&&(q[`${p.twoWay}_Single`]={Collection_Path:t,id:s,...N});const M=Rn(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:t,...N},[`${A.name}_Array`]:c(s)}),I.size++),F.fields.forEach(z=>{if(dt(z,F,i)){const x=JSON.parse(ts(hn(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(n==="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(n==="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=n=>{for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]===void 0?delete n[e]:typeof n[e]=="object"&&n[e]!==null&&Ue(n[e]))},Xs=n=>{if(n=n.toString(),/[/]|^\.+$|^__.*__$/.test(n))return!1;try{const s=new TextEncoder().encode(n),r=new TextDecoder().decode(s);if(n!==r)return!1}catch{return!1}return!(new Blob([n]).size>1500)},oi=async(n,e,t,s=1e3,r=5)=>{for(;r>0;)try{await n(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},jn=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},ms=n=>n?Array.isArray(n)?n.map(s=>jn(s)).filter(s=>s.length>0):jn(n)||"":"",jc=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/[\r\n]/g," ");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>998)throw new Error("Email subject is too long");return e},ai=n=>{if(!n||typeof n!="string")return"";let e=n.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
4
4
 
5
5
  `),e=e.replace(/\r\n/g,`
6
- `),e.length>5e6)throw new Error("Email body is too long");return e},xo=async(n,e)=>{const t={};for(const s of e){const r=`${n}/${s}.js`,i=ui.pathToFileURL(r).href;t[s]=await import(i)}return t};let ms,No,kn,Do,Qt,Ao,bn,Tn,ps=0,ai=!1;const xt={getTenant(){if(!kn)throw new Error("Tenant not provided");return kn},setTenant(n){kn=n},getMode(){return No},getTimezone(){return Do},getGlobalConfigModule(){return fe(Qt)},getCustomizationFile(n,e){if(!Object.keys(e.collections).includes(n))throw new Error("PERMISSION_DENIED");const t=ia([n],Ao,"node",xt);return fe(t?.[n])},getVersionInfo(){return bn},getMaintenanceInfo(){return Tn}},jc=async(n,e,t,s,r)=>{const i=!!ai;if(ai=!0,e&&(kn=e),No=n,ms&&!r)return xt;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(ui.pathToFileURL(t).href)).default;Qt=d({sdk:"node",utils:xt}),!r&&n==="development"&&(process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099",process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000",process.env.FIRESTORE_EMULATOR_HOST="127.0.0.1:8080",process.env.FIREBASE_STORAGE_EMULATOR_HOST="127.0.0.1:9199");try{ms=Nt.getApp()}catch{ms=Nt.initializeApp({credential:Nt.applicationDefault(),databaseURL:a.databaseURL,storageBucket:a.storageBucket,projectId:a.projectId})}const m=await Ze();return Ao=await xo(s,Object.keys(m.collections)),Do=await oe(Qt.timezone),i||H.getFirestore().collection("system_deployment").doc("maintenance_mode").onSnapshot(u=>{u.exists?(Tn=u.data(),oe(Qt.onMaintenanceUpdate,["node",Tn.active?"on":"off"])):console.error("Maintenance status not found")},u=>{console.error(u.message)}),i||H.getFirestore().collection("system_deployment").doc("latest_deploy").onSnapshot(u=>{u.exists?(bn=u.data(),ps++,ps>1&&oe(Qt.onVersionUpdate,["node",bn,ps])):console.error("Version info not found")},u=>{console.error(u.message)}),await new Promise(u=>{const f=()=>{Tn&&bn?u(xt):setTimeout(f,100)};f()}),xt},{getTenant:qe,setTenant:zc,getMode:Xs,getTimezone:er,getGlobalConfigModule:kt,getCustomizationFile:Be,getVersionInfo:Zc,getMaintenanceInfo:qc}=xt,Bc=async(n,e,t,s)=>new Promise((r,i)=>{const o=Ho(n,e,{cwd:t||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},d=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout?.on("data",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)}),Hc=async()=>{const n=process.env.STOKER_FB_WEB_APP_CONFIG;if(!n)throw new Error("Firebase web app config not found");const e=JSON.parse(n);try{return Nt.getApp()}catch{return Nt.initializeApp({credential:Nt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},Ze=async(n=!1)=>{const s=await di.getDatabase().ref("schema").orderByChild("published_time").limitToLast(1).get(),r=Object.values(s.val())[0];if(n){for(const i of Object.values(r.collections))for(const o of i.fields)if(o.type==="Computed"){const a=Ae(o,Be(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},Gc=async()=>{const t=await di.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(t.numChildren()<2))return Object.values(t.val())[0]},Ie=(n,e,t)=>{let s=n.collection("tenants").doc(t);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},Co=(n,e,t,s,r)=>{const i=H.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=t.collections[o],{labels:l,fields:c,preloadCache:d}=a,m=Be(o,t),u=Ie(i,e,n);if(r)if(s){const f=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const g=f&&Se("Read",f),v=pi(a,t,r),y=hi(a,r),w=Ls(a,r),R=mi(a,t,r),O=(h=[])=>{const S=[],b=Ei(r.Role,a,t);if(!b)throw new Error("PERMISSION_DENIED");if(g){let T=i.collection("tenants").doc(n).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(n).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 Y=b.singleQuery?b.singleQuery:Z;for(let z=0;z<q.length;z+=Y){const x=q.slice(z,z+Y);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>Y)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,Y=[];if(M){const z=b.singleQuery?b.singleQuery:Z;for(let x=0;x<M.length;x+=z){const K=M.slice(x,x+z);Y.push(K)}if(!b.singleQuery)Y.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 Y=0;Y<q.length;Y+=Z){const z=q.slice(Y,Y+Z);M.push(z)}M.forEach(Y=>{A.push(...O(k.concat([[`${S.name}_Array`,"array-contains-any",Y],[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(([Y,z])=>{if(z.length>0){const x=[];for(let K=0;K<z.length;K+=Z){const B=z.slice(K,K+Z);x.push(B)}x.forEach(K=>{A.push(...O(k.concat([[`${T.name}_Array`,"array-contains-any",K],[N.name,"==",Y]])))})}})}}}));const j=[...p,...F,...A];return!w.length&&!R.length?O(k):j}else throw new Error("PERMISSION_DENIED");else return[u]},tr=(n,e,t,s,r)=>{const i=H.getFirestore(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=s.collections[o],{labels:l}=a,c=Ie(i,e,n);if(r){const d=r.collections?.[l.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const m=d&&Se("Read",d),u=pi(a,s,r),f=[],g=Ei(r.Role,a,s);if(!g)throw new Error("PERMISSION_DENIED");if(m)f.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${g.key}`).doc(t));else if(u)for(const v of u)f.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${v.field}`).doc(t));return f}else return[c.doc(t)]},Fo=async(n,e,t,s,r,i,o,a,l,c)=>{const d=t.at(-2),m=yi(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 sr([...t,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 ${t.join("/")}`),y});e[g]=v.records,i&&await Promise.all(e[g].map(y=>nr(n,y,[...t,g,y.id],i,r,void 0,a,l,c))),u>0&&await Promise.all(e[g].map(y=>Fo(n,y,[...t,g,y.id],{depth:u},r,i,o,a,l,c)))});await Promise.all(f)},nr=async(n,e,t,s,r,i,o,a,l)=>{const c=t.at(-2);s.fields||=r.collections[c].fields.filter(u=>ee(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=je(y.Collection_Path,v,{userId:o,providedTransaction:a,noEmbeddingFields:l}).then(R=>{if(f[v]=R,d>0)return nr(n,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)},sr=async(n,e)=>{if(e?.subcollections?.depth&&e.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(e?.relations?.depth&&e.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");if(e?.pagination?.number!==void 0){const c=e.pagination.number;if(typeof c!="number"||!Number.isFinite(c)||!Number.isInteger(c)||c<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const t=e?.constraints,s=qe(),r=H.getFirestore();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")),Ze(!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=kt(),w=n.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=Be(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 _=Co(s,n,g,e?.userId,v);if(_.length===0)return{cursor:{},pages:0,records:[]};if(t&&(_=_.map(h=>(t.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=ra(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];t&&(h=t.reduce((N,[q,M,Y])=>N.where(q,M,Y),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(Fo(s,a.get(h.id),b,fe(e.subcollections),g,fe(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 Y=I.fields.find(z=>z.name===M);if(Y)return Y;throw new Error(`SCHEMA_ERROR: Field ${M} not found in collection ${w}`)}return M})),S.push(nr(s,a.get(h.id),b,fe(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 Y=Ae(M,C);if(!Y.formula)continue;T.push(oe(Y.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),K=Ae(z,C),B=K?.custom?.serverAccess?.read!==void 0?await oe(K.custom.serverAccess.read,[M,h]):!0;(!x||!B)&&(ee(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 na(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())}},$o=async(n,e,t,s,r,i,o,a)=>{const l=s.at(-2),c=yi(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 sr([...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});t[u]=f.records,d>0&&await Promise.all(t[u].map(async g=>{await $o(n,e,g,[...s,u,g.id],{depth:d},i,o,a)}))});await Promise.all(m)},Mo=async(n,e,t,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,m=[];for(const u of i.fields)if("collection"in u){const f=t[u.name];if(!f)continue;for(const[g,v]of Object.entries(f)){const y=je(v.Collection_Path,g,{userId:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(w=>{if(f[g]=w,d>0)return Mo(n,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)},je=async(n,e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(t?.relations?.depth&&t.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=qe(),r=H.getFirestore();let i;const o=async a=>{const[l,c,d]=await Promise.all([t?.userId?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(t.userId)):Promise.resolve({}),a.get(r.collection("system_deployment").doc("maintenance_mode")),Ze(!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=kt(),v=n.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=Be(O.collection,u);let E;if(t?.userId){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(f=l.data(),!f.Role)throw new Error("USER_ERROR");if(!f.Enabled)throw new Error("PERMISSION_DENIED");if(E=f.collections?.[O.collection],!E)throw new Error("PERMISSION_DENIED")}if(t?.userId&&(!E||!Se("Read",E)))throw new Error("PERMISSION_DENIED");const C=tr(s,n,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 ${n?.join("/")||O.collection}`);const A=[],j=n?[...n,e]:[O.collection,e];if(t?.subcollections&&A.push($o(s,a,i,j,t.subcollections,u,void 0,t.userId)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.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(Mo(s,a,i,j,u,t.relations,t.userId,t.noComputedFields,t.noEmbeddingFields))),await Promise.all(A),!t?.noComputedFields){for(const b of R.fields)if(b.type==="Computed"){const T=Ae(b,I);if(!T.formula)continue;i[b.name]=await T.formula(i)}}if(t?.noEmbeddingFields)for(const b of R.fields)b.type==="Embedding"&&delete i[b.name];if(t?.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=Ae(N,I),Y=M?.custom?.serverAccess?.read!==void 0?await oe(M.custom.serverAccess.read,[b,i]):!0;(!q||!Y)&&(ee(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}),t?.userId&&await ta(i,R,u,t.userId,f)};return t?.providedTransaction?await o(t.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},Po=async(n,e,t,s,r,i,o,a)=>{const l=H.getFirestore(),c=Be(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||be(s[f.name]))return;Ae(f,c);const g=s[f.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(!Ks(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&&!(n==="update"&&v.data().id===t)&&u.push(`${f.name} "${s[f.name]}" already exists`)}}})),u.length>0)throw new Error(u.join(", "))},wt=async(n,e,t,s,r,i,o,a,l)=>{const{labels:c}=o,d=H.getFirestore(),m=kt(),u=await oe(m.firebase?.writeLogTTL),f={operation:n,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_App:t.Last_Write_App,Last_Write_Version:t.Last_Write_Version,data:{}};if(u){const w=new Date,R=new Date(new Date().setDate(w.getDate()+u));f.TTL=H.Timestamp.fromDate(R)}const g=fe(t);rt(g),n!=="delete"&&(f.data.data=fe(g)),n==="update"&&(f.data.originalRecord=fe(l)),n!=="delete"&&["started","written"].includes(e)&&(delete f.data.data.Saved_At,delete f.data.data.Last_Save_At),e==="failed"&&(f.data.error=JSON.stringify(a));const v=Ie(d,r,s),y=t.Last_Write_At;await v.doc(i).collection("system_write_log").doc(`${t.Last_Write_By}-${y.valueOf()}`).set(f)},zt=async n=>{const e=qe(),t=_t.getAuth(),s=H.getFirestore(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(n.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
6
+ `),e.length>5e6)throw new Error("Email body is too long");return e},zc=(n="enterprise",e)=>n==="enterprise"?e:"(default)",ue=n=>{const e=n||gt.getApp(),t=process.env.STOKER_FB_WEB_APP_CONFIG;if(!t)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const s=JSON.parse(t),r=zc(process.env.FB_FIRESTORE_EDITION,s.projectId);return ie.getFirestore(e,r)},No=async(n,e)=>{const t={};for(const s of e){const r=`${n}/${s}.js`,i=di.pathToFileURL(r).href;t[s]=await import(i)}return t};let ps,Do,bn,Ao,Kt,Co,Tn,Sn,ys=0,li=!1;const Dt={getTenant(){if(!bn)throw new Error("Tenant not provided");return bn},setTenant(n){bn=n},getMode(){return Do},getTimezone(){return Ao},getGlobalConfigModule(){return he(Kt)},getCustomizationFile(n,e){if(!Object.keys(e.collections).includes(n))throw new Error("PERMISSION_DENIED");const t=oa([n],Co,"node",Dt);return he(t?.[n])},getVersionInfo(){return Tn},getMaintenanceInfo(){return Sn}},Zc=async(n,e,t,s,r)=>{const i=!!li;if(li=!0,e&&(bn=e),Do=n,ps&&!r)return Dt;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(t).href)).default;Kt=d({sdk:"node",utils:Dt}),!r&&n==="development"&&(process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099",process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000",process.env.FIRESTORE_EMULATOR_HOST="127.0.0.1:8080",process.env.FIREBASE_STORAGE_EMULATOR_HOST="127.0.0.1:9199");try{ps=gt.getApp()}catch{ps=gt.initializeApp({credential:gt.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(Kt.timezone),i||ue().collection("system_deployment").doc("maintenance_mode").onSnapshot(u=>{u.exists?(Sn=u.data(),oe(Kt.onMaintenanceUpdate,["node",Sn.active?"on":"off"])):console.error("Maintenance status not found")},u=>{console.error(u.message)}),i||ue().collection("system_deployment").doc("latest_deploy").onSnapshot(u=>{u.exists?(Tn=u.data(),ys++,ys>1&&oe(Kt.onVersionUpdate,["node",Tn,ys])):console.error("Version info not found")},u=>{console.error(u.message)}),await new Promise(u=>{const f=()=>{Sn&&Tn?u(Dt):setTimeout(f,100)};f()}),Dt},{getTenant:Be,setTenant:qc,getMode:er,getTimezone:tr,getGlobalConfigModule:Tt,getCustomizationFile:He,getVersionInfo:Bc,getMaintenanceInfo:Hc}=Dt,Gc=async(n,e,t,s)=>new Promise((r,i)=>{const o=Go(n,e,{cwd:t||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},d=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout?.on("data",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)}),Yc=async()=>{const n=process.env.STOKER_FB_WEB_APP_CONFIG;if(!n)throw new Error("Firebase web app config not found");const e=JSON.parse(n);try{return gt.getApp()}catch{return gt.initializeApp({credential:gt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},qe=async(n=!1)=>{const s=await fi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(1).get(),r=Object.values(s.val())[0];if(n){for(const i of Object.values(r.collections))for(const o of i.fields)if(o.type==="Computed"){const a=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},Jc=async()=>{const t=await fi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(t.numChildren()<2))return Object.values(t.val())[0]},xe=(n,e,t)=>{let s=n.collection("tenants").doc(t);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},Fo=(n,e,t,s,r)=>{const i=ue(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=t.collections[o],{labels:l,fields:c,preloadCache:d}=a,m=He(o,t),u=xe(i,e,n);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,t,r),y=mi(a,r),w=Vs(a,r),R=pi(a,t,r),O=(h=[])=>{const S=[],b=vi(r.Role,a,t);if(!b)throw new Error("PERMISSION_DENIED");if(g){let T=i.collection("tenants").doc(n).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(n).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=(n,e,t,s,r)=>{const i=ue(),o=e.at(-1);if(!o)throw new Error("EMPTY_PATH");const a=s.collections[o],{labels:l}=a,c=xe(i,e,n);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(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${g.key}`).doc(t));else if(u)for(const v of u)f.push(i.collection("tenants").doc(n).collection("system_fields").doc(l.collection).collection(`${l.collection}-${v.field}`).doc(t));return f}else return[c.doc(t)]},$o=async(n,e,t,s,r,i,o,a,l,c)=>{const d=t.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([...t,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 ${t.join("/")}`),y});e[g]=v.records,i&&await Promise.all(e[g].map(y=>sr(n,y,[...t,g,y.id],i,r,void 0,a,l,c))),u>0&&await Promise.all(e[g].map(y=>$o(n,y,[...t,g,y.id],{depth:u},r,i,o,a,l,c)))});await Promise.all(f)},sr=async(n,e,t,s,r,i,o,a,l)=>{const c=t.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(n,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(n,e)=>{if(e?.subcollections?.depth&&e.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(e?.relations?.depth&&e.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");if(e?.pagination?.number!==void 0){const c=e.pagination.number;if(typeof c!="number"||!Number.isFinite(c)||!Number.isInteger(c)||c<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const t=e?.constraints,s=Be(),r=ue();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=Tt(),w=n.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,n,g,e?.userId,v);if(_.length===0)return{cursor:{},pages:0,records:[]};if(t&&(_=_.map(h=>(t.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];t&&(h=t.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(n,e,t,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});t[u]=f.records,d>0&&await Promise.all(t[u].map(async g=>{await Mo(n,e,g,[...s,u,g.id],{depth:d},i,o,a)}))});await Promise.all(m)},Po=async(n,e,t,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=t[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(n,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(n,e,t)=>{if(t?.subcollections?.depth&&t.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(t?.relations?.depth&&t.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=Be(),r=ue();let i;const o=async a=>{const[l,c,d]=await Promise.all([t?.userId?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(t.userId)):Promise.resolve({}),a.get(r.collection("system_deployment").doc("maintenance_mode")),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=Tt(),v=n.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(t?.userId){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(f=l.data(),!f.Role)throw new Error("USER_ERROR");if(!f.Enabled)throw new Error("PERMISSION_DENIED");if(E=f.collections?.[O.collection],!E)throw new Error("PERMISSION_DENIED")}if(t?.userId&&(!E||!Re("Read",E)))throw new Error("PERMISSION_DENIED");const C=nr(s,n,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 ${n?.join("/")||O.collection}`);const A=[],j=n?[...n,e]:[O.collection,e];if(t?.subcollections&&A.push(Mo(s,a,i,j,t.subcollections,u,void 0,t.userId)),t?.relations&&(t.relations.fields&&(t.relations.fields=t.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,t.relations,t.userId,t.noComputedFields,t.noEmbeddingFields))),await Promise.all(A),!t?.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(t?.noEmbeddingFields)for(const b of R.fields)b.type==="Embedding"&&delete i[b.name];if(t?.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}),t?.userId&&await na(i,R,u,t.userId,f)};return t?.providedTransaction?await o(t.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},Lo=async(n,e,t,s,r,i,o,a)=>{const l=ue(),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&&!(n==="update"&&v.data().id===t)&&u.push(`${f.name} "${s[f.name]}" already exists`)}}})),u.length>0)throw new Error(u.join(", "))},Et=async(n,e,t,s,r,i,o,a,l)=>{const{labels:c}=o,d=ue(),m=Tt(),u=await oe(m.firebase?.writeLogTTL),f={operation:n,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_App:t.Last_Write_App,Last_Write_Version:t.Last_Write_Version,data:{}};if(u){const w=new Date,R=new Date(new Date().setDate(w.getDate()+u));f.TTL=ie.Timestamp.fromDate(R)}const g=he(t);it(g),n!=="delete"&&(f.data.data=he(g)),n==="update"&&(f.data.originalRecord=he(l)),n!=="delete"&&["started","written"].includes(e)&&(delete f.data.data.Saved_At,delete f.data.data.Last_Save_At),e==="failed"&&(f.data.error=JSON.stringify(a));const v=xe(d,r,s),y=t.Last_Write_At;await v.doc(i).collection("system_write_log").doc(`${t.Last_Write_By}-${y.valueOf()}`).set(f)},Zt=async n=>{const e=Be(),t=vt.getAuth(),s=ue(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(n.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
7
7
  ${i}`)}})(),(async()=>{try{await t.deleteUser(n.User_ID)}catch(i){if(i.code==="auth/user-not-found")return;r.push(`Error deleting user:
8
- ${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},rr=async(n,e,t,s,r,i,o,a,l)=>{const c=H.getFirestore(),d=Xs(),m=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(m)n=m;else throw new Error("Admin email not set");const u=hs(n),f=Wc(e),g=t?oi(t):void 0,v=s?oi(s):void 0,y=r?hs(r):void 0,w=i?hs(i):void 0,R=o?Wn(o):void 0,O=l?Wn(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)},Yc=["tenant","role","collection","doc"],Lo=new Set(Yc);function ir(n){return Lo.has(n)}function Jc(n){if(!n)return{};const e={};for(const t of Object.keys(n))Lo.has(t)||(e[t]=n[t]);return e}const or=async(n,e,t,s,r,i,o)=>{const a=_t.getAuth(),l=H.getFirestore(),{labels:c,fields:d}=s,m="USER_ERROR",u=async(y,w)=>{try{await zt(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&&!ir(y.name)&&r[y.name]!==void 0&&y.type!=="Timestamp"&&y.type!=="Computed"&&y.type!=="Embedding"&&(be(r[y.name])?g[y.name]=null:g[y.name]=r[y.name]);try{await a.setCustomUserClaims(f.uid,{...g,tenant:n,role:r.Role,collection:c.collection,doc:e})}catch{throw await u(r,m),new Error(m)}try{await l.collection("tenants").doc(n).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=t.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(t.appName),O=t?.mail?.emailVerification&&t.mail.emailVerification(w,R);try{await rr(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(", "))},ir=async(n,e,t,s,r,i,o,a,l)=>{const c=ue(),d=er(),m=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(m)n=m;else throw new Error("Admin email not set");const u=ms(n),f=jc(e),g=t?ai(t):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)},Qc=["tenant","role","collection","doc"],Vo=new Set(Qc);function or(n){return Vo.has(n)}function Kc(n){if(!n)return{};const e={};for(const t of Object.keys(n))Vo.has(t)||(e[t]=n[t]);return e}const ar=async(n,e,t,s,r,i,o)=>{const a=vt.getAuth(),l=ue(),{labels:c,fields:d}=s,m="USER_ERROR",u=async(y,w)=>{try{await Zt(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:n,role:r.Role,collection:c.collection,doc:e})}catch{throw await u(r,m),new Error(m)}try{await l.collection("tenants").doc(n).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=t.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(t.appName),O=t?.mail?.emailVerification&&t.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:
9
9
  </br>
10
10
  </br>
11
- <a href="${w}">${w}</a>`)}catch{throw await u(r,m),new Error(m)}}}return f.uid},ar=async(n,e)=>{const{labels:t,parentCollection:s}=e;if(s){const r=n.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...n].slice(0,-2),o=await je(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(t.collection),!Je(n,a))throw new Error("PERMISSION_DENIED")}else if(n.length>1)throw new Error("PERMISSION_DENIED")},jn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Qc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{jn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?t[s]=new H.Timestamp(r.seconds,r.nanoseconds):jn(r)&&e(r)})};e(n)},lr=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{jn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?t[s]=new H.Timestamp(r._seconds,r._nanoseconds):jn(r)&&e(r)})};e(n)},Qn=n=>{if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]==="_DELETE_FIELD"?n[e]=H.FieldValue.delete():Qn(n[e]))},Kc=(n,e,t)=>{if(ee(t)&&t.includeFields){const s={};return t.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=U(n.fields,r);Et(n,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},li=async(n,e,t,s,r,i,o)=>{if(!ee(t)||!t.enforceHierarchy)return;const{fields:a}=e,l=H.getFirestore(),c=Object.entries(s[t.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${t.name} is required`);const[d,m]=c[0];if(!m)throw new Error(`VALIDATION_ERROR: Relation ${t.name} is required`);const u=Ie(l,m.Collection_Path,n);if(i.size++,!o&&i.size>500)throw new Error("VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const f=await r.get(u.doc(d));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${d} not found in collection ${t.collection}`);const g=f.data(),v=U(a,t.enforceHierarchy.field),y=t.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")},wn=async(n,e,t)=>{delete e[n.name][t],e[`${n.name}_Array`]=e[`${n.name}_Array`]?.filter(s=>s!==t),delete e[`${n.name}_Single`]},ys=async(n,e,t,s,r)=>{e[n.name]||={},e[n.name][s]=t,e[`${n.name}_Array`]||=[],e[`${n.name}_Array`].push(s),r&&(e[`${n.name}_Single`]={id:s,...t})},Xc=(n,e,t,s,r,i)=>{const o=[],a=[];for(const l of s.fields)ee(l)&&l.twoWay&&l.collection===t&&((n==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),n==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},cr=async(n,e,t,s,r,i,o,a,l,c,d,m)=>{const{fields:u}=i,f=H.getFirestore(),g=new Map,v=new Map,y=new Map;for(const w of u)ee(w)&&["OneToOne","OneToMany"].includes(w.type)&&w.enforceHierarchy&&s[w.name]&&(n==="Create"||n==="Update"&&!Je(m?.[w.name],s[w.name]))&&await li(e,i,w,s,a,l);for(const w of u)if(ee(w)&&w.twoWay){const R=o.collections[w.collection],O=U(R.fields,w.twoWay),I=ht(R,[O]);if(s[w.name]){const E=Object.entries(s[w.name]);for(const C of E){const[_,Z]=C;if(n==="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=Ie(f,Z.Collection_Path,e),j=await a.get(A.doc(_));if(!j.exists){wn(w,r,_);continue}const h=j.data();v.set(w.collection,{...v.get(w.collection)||{},[_]:h}),k=fe({...h,...Sn(s)})}const F={...k[O.name],[t]:{Collection_Path:s.Collection_Path,...Kc(i,s,O)}};k[O.name]=F,k[`${O.name}_Array`]||=[],k[`${O.name}_Array`].push(t),I.size===1&&(k[`${O.name}_Single`]={id:t,...F}),y.set(w.collection,{...y.get(w.collection)||{},[_]:k})}}}if(n==="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=Ie(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=fe({...j,...Sn(s)})}k[O.name][t]&&delete k[O.name][t],Array.isArray(k[`${O.name}_Array`])&&(k[`${O.name}_Array`]=k[`${O.name}_Array`].filter(F=>F!==t)),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=Be(w,o);for(const[E,C]of Object.entries(R)){const{addedFields:_,removedFields:Z}=Xc(n,E,w,i,s,m);if(c&&d){for(const k of _){const p=U(O.fields,k.twoWay);if(!fr(O,p,d)){wn(k,r,E);continue}}for(const k of Z){const p=U(O.fields,k.twoWay),F=ht(O,[p]);if(!fr(O,p,d)){ys(k,r,m?.[k.name]?.[E],E,F.size===1);continue}}if(!at("Update",O,o,c,d,v.get(w)?.[E])){for(const k of _)wn(k,r,E);for(const k of Z){const p=U(O.fields,k.twoWay),F=ht(O,[p]);ys(k,r,m?.[k.name]?.[E],E,F.size===1)}}if(!at("Update",O,o,c,d,C)){for(const k of _)wn(k,r,E);for(const k of Z){const p=U(O.fields,k.twoWay),F=ht(O,[p]);ys(k,r,m?.[k.name]?.[E],E,F.size===1)}}}try{await rn("update",C,O,I,{operation:"update",record: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)&&ee(p)&&p.enforceHierarchy&&await li(e,O,p,C,a,l,!0)}}}return g},Vo=(n,e,t)=>{n==="create"&&yt.forEach(s=>{if(!Je(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),n==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),yt.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!Je(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},ur=(n,e,t,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(t[i]===!0)if(n==="create")t[o]=H.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])t[o]=H.FieldValue.serverTimestamp();else if(t[o]&&t[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},gs=async(n,e,t,s,r)=>{if(!Se("Read",r.collections?.[e.labels.collection]))return!1;try{await je([e.labels.collection],t,{userId:s,providedTransaction:n})}catch{return!1}return!0},eu=10,tu=async(n,e)=>{if(n.length===0)return;const t=Math.min(e,n.length);let s=0;const r=async()=>{for(;s<n.length;){const i=s;s+=1,await n[i]()}};await Promise.all(Array.from({length:t},r))},Uo=async(n,e,t,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const 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 gs(n,d,w,t,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 gs(n,y,I,t,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 gs(n,y,_,t,s))throw new Error("PERMISSION_DENIED")})}}}await tu(f,eu)}}},nu=async(n,e,t)=>{const s=t?.userId,r=t?.user;let i=t?.context;const o=qe(),a=kt();if(t?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(t?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=t?.providedSchema||await Ze();if(n.length===0)throw new Error("EMPTY_PATH");const c=n.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=Be(f.collection,l),R=await oe(a.appName),O=H.getFirestore(),I=_t.getAuth(),C=(s?await I.getUser(s):void 0)?.customClaims?.role;let _;s&&await ar(n,u);const Z=Ie(O,n,o),k=t?.id||Z.doc().id;i=i||{},i.collection=f.collection,e.id=k,lr(e),Qn(e);const p=Ws("create",n,e,l,R,"Online",s||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp());t?.createdAt&&(p.Created_At=t.createdAt),t?.createdBy&&(p.Created_By=t.createdBy);const F=fe(p);y&&(p[y.archivedField]=!1),Ve(e),v&&!t?.providedTransaction&&await wt("create","started",p,o,n,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}),Rn(u,p,l),In(u,p),await ua(p,u,w,C),Ve(p);try{if(u.auth&&r&&!r.password)throw new Error("Password is required");t?.providedTransaction||(await Po("create",o,k,p,u,l),await rn("create",p,u,w,{operation:"create",record:p,context:i},l))}catch(T){throw new Error(`VALIDATION_ERROR: ${T.message}`)}Ve(p),e.id=k,y&&(p[y.archivedField]=!1),Rn(u,p,l),In(u,p);try{Vo("create",p,F),ur("create",u,p),await rn("create",p,u,w,{operation:"create",record: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=Ae(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,Y,z]=await Promise.all([t?.providedTransaction?Promise.resolve({}):T.get(O.collection("system_deployment").doc("latest_deploy")),t?.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({}),t?.providedSchema?Promise.resolve(t.providedSchema):Ze()]);if(N&&(N.size+=3),!t?.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(!Y?.exists)throw new Error("PERMISSION_DENIED");if(_=Y.data(),!_.Role)throw new Error("USER_ERROR");if(!_.Enabled)throw new Error("PERMISSION_DENIED")}if(!t?.providedTransaction){const K=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 Ee=Ae(B,w);if(!(s&&Ee?.custom?.serverAccess?.read!==void 0?await oe(Ee.custom.serverAccess.read,[_?.Role,p]):!0))throw new Error("PERMISSION_DENIED");const He=e[B.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Ks(He)){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(He)))?.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(K)}hr(p,k,u,l,s,_,r?.permissions),r?.permissions&&s&&_&&await Uo(T,r.permissions,s,_,l),hr(p,k,u,l,s,_,r?.permissions)};if(u.auth&&r){await O.runTransaction(async N=>{await h(N)},{maxAttempts:10});const T=await or(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),t?.noTwoWay||await cr("Create",o,k,p,p,u,l,T,N,s,_);const q=Us(l);Qs("create",T,n,k,p,l,u,t,q,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.FieldValue.delete,M=>O.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${M.name}`).doc(k),(M,Y)=>O.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${M.name}`).doc(Y),M=>O.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${M}`).doc(k),(M,Y)=>Ie(O,M,o).doc(Y),(M,Y,z)=>O.collection("tenants").doc(o).collection("system_fields").doc(M.collection).collection(`${M.collection}-${Y}`).doc(z),(M,Y,z)=>O.collection("tenants").doc(o).collection("system_fields").doc(M.collection).collection(`${M.collection}-${Y.replaceAll(" ","-")}`).doc(z),void 0,void 0,N),T.set(Z.doc(k),p)}catch(N){if(t?.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(Y=>{setTimeout(Y,250)}),await wt("create",M?.resolved?"success":"failed",p,o,n,k,u,M?.resolved?void 0:N)),!M?.resolved)throw u.auth&&r&&await zt(p),N}}};if(t?.providedTransaction?await S(t.providedTransaction):await O.runTransaction(async T=>{await S(T)},{maxAttempts:10}),!t?.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}},Kt=async(n,e,t,s)=>{const r=qe(),i=_t.getAuth(),o=H.getFirestore(),a=e.customClaims||{};let l=!1;try{await i.updateUser(n,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(n,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(n).update({...t,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Wo=async(n,e,t,s,r,i,o,a,l,c,d)=>{const m=_t.getAuth(),u=H.getFirestore(),f={};for(const y of r.fields)y.saveToAuthToken&&!ir(y.name)&&i[y.name]!==void 0&&y.type!=="Timestamp"&&y.type!=="Computed"&&y.type!=="Embedding"&&(be(i[y.name])?f[y.name]=null:f[y.name]=i[y.name]);const g="USER_ERROR";let v="";if(n==="create"){if(!d)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{v=await or(e,t,s,r,i,l,d)}catch(y){throw new Error(y.message)}}else if(n==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),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 Kt(o.User_ID,a,c,g),new Error(g)}if(i.Role&&i.Role!==o.Role||Object.keys(f).length)try{const w={...Jc(a.customClaims),...f};await m.setCustomUserClaims(o.User_ID,{...w,tenant:e,role:i.Role,collection:r.labels.collection,doc:t}),await m.revokeRefreshTokens(o.User_ID)}catch{throw await Kt(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:t,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await Kt(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 rr(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="${w}">${w}</a>`)}catch{throw await u(r,m),new Error(m)}}}return f.uid},lr=async(n,e)=>{const{labels:t,parentCollection:s}=e;if(s){const r=n.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...n].slice(0,-2),o=await ze(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(t.collection),!Qe(n,a))throw new Error("PERMISSION_DENIED")}else if(n.length>1)throw new Error("PERMISSION_DENIED")},zn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),Xc=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{zn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?t[s]=new ie.Timestamp(r.seconds,r.nanoseconds):zn(r)&&e(r)})};e(n)},cr=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{zn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?t[s]=new ie.Timestamp(r._seconds,r._nanoseconds):zn(r)&&e(r)})};e(n)},Kn=n=>{if(typeof n=="object")for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(n[e]==="_DELETE_FIELD"?n[e]=ie.FieldValue.delete():Kn(n[e]))},eu=(n,e,t)=>{if(X(t)&&t.includeFields){const s={};return t.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=U(n.fields,r);Ot(n,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},ci=async(n,e,t,s,r,i,o)=>{if(!X(t)||!t.enforceHierarchy)return;const{fields:a}=e,l=ue(),c=Object.entries(s[t.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${t.name} is required`);const[d,m]=c[0];if(!m)throw new Error(`VALIDATION_ERROR: Relation ${t.name} is required`);const u=xe(l,m.Collection_Path,n);if(i.size++,!o&&i.size>500)throw new Error("VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const f=await r.get(u.doc(d));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${d} not found in collection ${t.collection}`);const g=f.data(),v=U(a,t.enforceHierarchy.field),y=t.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")},_n=async(n,e,t)=>{delete e[n.name][t],e[`${n.name}_Array`]=e[`${n.name}_Array`]?.filter(s=>s!==t),delete e[`${n.name}_Single`]},gs=async(n,e,t,s,r)=>{e[n.name]||={},e[n.name][s]=t,e[`${n.name}_Array`]||=[],e[`${n.name}_Array`].push(s),r&&(e[`${n.name}_Single`]={id:s,...t})},tu=(n,e,t,s,r,i)=>{const o=[],a=[];for(const l of s.fields)X(l)&&l.twoWay&&l.collection===t&&((n==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),n==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},ur=async(n,e,t,s,r,i,o,a,l,c,d,m)=>{const{fields:u}=i,f=ue(),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]&&(n==="Create"||n==="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(n==="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){_n(w,r,_);continue}const h=j.data();v.set(w.collection,{...v.get(w.collection)||{},[_]:h}),k=he({...h,...Rn(s)})}const F={...k[O.name],[t]:{Collection_Path:s.Collection_Path,...eu(i,s,O)}};k[O.name]=F,k[`${O.name}_Array`]||=[],k[`${O.name}_Array`].push(t),I.size===1&&(k[`${O.name}_Single`]={id:t,...F}),y.set(w.collection,{...y.get(w.collection)||{},[_]:k})}}}if(n==="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,...Rn(s)})}k[O.name][t]&&delete k[O.name][t],Array.isArray(k[`${O.name}_Array`])&&(k[`${O.name}_Array`]=k[`${O.name}_Array`].filter(F=>F!==t)),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}=tu(n,E,w,i,s,m);if(c&&d){for(const k of _){const p=U(O.fields,k.twoWay);if(!hr(O,p,d)){_n(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 _)_n(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 _)_n(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 on("update",C,O,I,{operation:"update",record: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=(n,e,t)=>{n==="create"&&wt.forEach(s=>{if(!Qe(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),n==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),wt.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!Qe(e[s],t[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},dr=(n,e,t,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(t[i]===!0)if(n==="create")t[o]=ie.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])t[o]=ie.FieldValue.serverTimestamp();else if(t[o]&&t[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},ws=async(n,e,t,s,r)=>{if(!Re("Read",r.collections?.[e.labels.collection]))return!1;try{await ze([e.labels.collection],t,{userId:s,providedTransaction:n})}catch{return!1}return!0},nu=10,su=async(n,e)=>{if(n.length===0)return;const t=Math.min(e,n.length);let s=0;const r=async()=>{for(;s<n.length;){const i=s;s+=1,await n[i]()}};await Promise.all(Array.from({length:t},r))},Wo=async(n,e,t,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const 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(n,d,w,t,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(n,y,I,t,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(n,y,_,t,s))throw new Error("PERMISSION_DENIED")})}}}await su(f,nu)}}},ru=async(n,e,t)=>{const s=t?.userId,r=t?.user;let i=t?.context;const o=Be(),a=Tt();if(t?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(t?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=t?.providedSchema||await qe();if(n.length===0)throw new Error("EMPTY_PATH");const c=n.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=ue(),I=vt.getAuth(),C=(s?await I.getUser(s):void 0)?.customClaims?.role;let _;s&&await lr(n,u);const Z=xe(O,n,o),k=t?.id||Z.doc().id;i=i||{},i.collection=f.collection,e.id=k,cr(e),Kn(e);const p=js("create",n,e,l,R,"Online",s||"System",ie.Timestamp.now(),ie.FieldValue.serverTimestamp());t?.createdAt&&(p.Created_At=t.createdAt),t?.createdBy&&(p.Created_By=t.createdBy);const F=he(p);y&&(p[y.archivedField]=!1),Ue(e),v&&!t?.providedTransaction&&await Et("create","started",p,o,n,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}),In(u,p,l),xn(u,p),await da(p,u,w,C),Ue(p);try{if(u.auth&&r&&!r.password)throw new Error("Password is required");t?.providedTransaction||(await Lo("create",o,k,p,u,l),await on("create",p,u,w,{operation:"create",record:p,context:i},l))}catch(T){throw new Error(`VALIDATION_ERROR: ${T.message}`)}Ue(p),e.id=k,y&&(p[y.archivedField]=!1),In(u,p,l),xn(u,p);try{Uo("create",p,F),dr("create",u,p),await on("create",p,u,w,{operation:"create",record: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([t?.providedTransaction?Promise.resolve({}):T.get(O.collection("system_deployment").doc("latest_deploy")),t?.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({}),t?.providedSchema?Promise.resolve(t.providedSchema):qe()]);if(N&&(N.size+=3),!t?.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(!t?.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),t?.noTwoWay||await ur("Create",o,k,p,p,u,l,T,N,s,_);const q=Ws(l);Ks("create",T,n,k,p,l,u,t,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(t?.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 Et("create",M?.resolved?"success":"failed",p,o,n,k,u,M?.resolved?void 0:N)),!M?.resolved)throw u.auth&&r&&await Zt(p),N}}};if(t?.providedTransaction?await S(t.providedTransaction):await O.runTransaction(async T=>{await S(T)},{maxAttempts:10}),!t?.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}},Xt=async(n,e,t,s)=>{const r=Be(),i=vt.getAuth(),o=ue(),a=e.customClaims||{};let l=!1;try{await i.updateUser(n,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(n,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(n).update({...t,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},jo=async(n,e,t,s,r,i,o,a,l,c,d)=>{const m=vt.getAuth(),u=ue(),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(n==="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,t,s,r,i,l,d)}catch(y){throw new Error(y.message)}}else if(n==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),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 Xt(o.User_ID,a,c,g),new Error(g)}if(i.Role&&i.Role!==o.Role||Object.keys(f).length)try{const w={...Kc(a.customClaims),...f};await m.setCustomUserClaims(o.User_ID,{...w,tenant:e,role:i.Role,collection:r.labels.collection,doc:t}),await m.revokeRefreshTokens(o.User_ID)}catch{throw await Xt(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:t,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await Xt(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:
12
12
  </br>
13
13
  </br>
14
- <a href="${O}">${O}</a>`)}catch{throw await Kt(o.User_ID,a,c,g),new Error(g)}}}}}else if(n==="delete")try{await zt(o)}catch(y){throw new Error(y.message)}if(v)return v},su=async(n,e,t)=>{const s=qe(),r=H.getFirestore(),i=[e];t&&t.trim()!==""&&i.push(t),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await n.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)n.set(a,{locked:!0})},ci=async(n,e)=>{const t=qe(),s=H.getFirestore(),r=[n];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(t).collection("system_locks").doc(o);i.delete(a)}await i.commit()},jo=async(n,e,t,s)=>{const r=s?.userId;let i=s?.user,o=s?.context;const a=qe(),l=kt();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 Ze(!0);if(n.length===0)throw new Error("EMPTY_PATH");const d=n.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=Be(g.collection,c),R=await oe(l.appName),O=_t.getAuth(),I=H.getFirestore();let E;r&&await ar(n,f);const C=Ie(I,n,a);o=o||{},o.collection=g.collection;let _=s?.originalRecord||await je(n,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0}),Z=_;r&&(Z=await je(n,e,{noComputedFields:!0,noEmbeddingFields:!0}));for(const x of v)x.type==="Computed"&&(delete t[x.name],delete _[x.name]);if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([x,K])=>[x,{...K,fields:K.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&&!ir(x.name)),p=f.auth&&i?.operation==="create",F=f.auth&&i?.operation==="delete",A=f.auth&&!p&&!F&&(i?.operation==="update"||t.Role||t.Enabled!==void 0||t.Name||t.Email||t.Photo_URL||k.some(x=>t[x.name]!==void 0)),j=x=>x.User_ID&&(f.auth&&!p&&!F&&i?.operation==="update"||t.Role&&t.Role!==x.Role||t.Enabled!==void 0&&t.Enabled!==x.Enabled||t.Name&&t.Name!==x.Name||t.Email&&t.Email!==x.Email||t.Photo_URL&&t.Photo_URL!==x.Photo_URL||k.some(K=>t[K.name]!==void 0&&t[K.name]!==x[K.name]));delete t.id,lr(t),Qn(t);const h=Ws("update",n,t,c,R,"Online",r||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp()),S=fe(h);for(const x of v)!ee(x)&&be(h[x.name])&&x.nullable&&(h[x.name]=null);Ve(h),Ve(_),y&&!s?.providedTransaction&&await wt("update","started",h,a,n,e,f,void 0,_);const b={operation:"update",data:h,recordId:e,context:o,originalRecord:fe(_)};await ae("preOperation",l,w,b);const T={operation:"update",data:h,recordId:e,context:o,originalRecord:fe(_)};await ae("preWrite",l,w,T),Rn(f,h,c),In(f,h),Ve(h);try{if(p&&!i?.password)throw new Error("Password is required");if(!s?.providedTransaction){const x={...Z,...h};await Po("update",a,e,x,f,c),rt(x),await rn("update",x,f,w,{operation:"update",record:h,context:o,originalRecord:fe(_)},c)}}catch(x){throw new Error(`VALIDATION_ERROR: ${x.message}`)}Ve(h),delete t.id,Rn(f,h,c),In(f,h);for(const x of v)!ee(x)&&be(h[x.name])&&x.nullable&&(h[x.name]=null);try{const x={...Z,...h};rt(x),ur("update",f,h,_),Vo("update",h,S),await rn("update",x,f,w,{operation:"update",record:h,context:o,originalRecord:fe(_)},c)}catch(x){throw new Error(`VALIDATION_ERROR: ${x.message}`)}let N;i&&(i.permissions||={});const q=async(x,K,B)=>{const[Ee,Le,He,he,Ge]=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(_):je(n,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):Ze()]);if(B&&(B.size+=3),!s?.providedTransaction){if(!Ee.exists)throw new Error("VERSION_ERROR");const ve=Ee.data();if(ve.force&&h.Last_Write_At.valueOf()<ve.time.valueOf())throw new Error("VERSION_ERROR");if(!Le.exists)throw new Error("MAINTENANCE_MODE");if(Le.data().active)throw new Error("MAINTENANCE_MODE")}if(!He)throw new Error("NOT_FOUND");if(_=He,c=Ge,r){if(!he?.exists)throw new Error("PERMISSION_DENIED");if(E=he.data(),!E.Role)throw new Error("USER_ERROR");if(!E.Enabled)throw new Error("PERMISSION_DENIED")}if(B&&(B.size+=tr(a,n,e,c,E).length),p&&_.User_ID||F&&!_.User_ID)throw new Error("USER_ERROR");if(j(_)){const ve=await x.get(I.collection("tenants").doc(a).collection("system_user_permissions").doc(_.User_ID));if(B&&B.size++,!ve?.exists)throw new Error("PERMISSION_DENIED");N=ve.data();const ct=i?.permissions&&Object.keys(i.permissions).length>0?i.permissions:void 0;if(h.Role&&h.Role!==_.Role&&!ct&&(i||={operation:"update",permissions:{}},i.permissions=fe(N),i.permissions.Role=h.Role),i?.permissions){if(i.permissions.Role||=h.Role||_.Role,i.permissions.Enabled??=h.Enabled??_.Enabled,be(i.permissions.Role))throw new Error("VALIDATION_ERROR: Role field is required");if(be(i.permissions.Enabled))throw new Error("VALIDATION_ERROR: Enabled field is required")}}if(!s?.providedTransaction){const ct=v.filter(ge=>"unique"in ge&&ge.unique).map(async ge=>{if(!r||!ge.access||ge.access.includes(E.Role)){if(h[ge.name]===void 0||be(h[ge.name]))return;const Zt=Ae(ge,w),dn={..._,...h};if(!(r&&Zt?.custom?.serverAccess?.read!==void 0?await oe(Zt.custom.serverAccess.read,[E?.Role,dn]):!0))throw new Error("PERMISSION_DENIED");const Kn=h[ge.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Ks(Kn)){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 dr=await x.get(I.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${ge.name}`).doc(Kn));if(dr.exists&&dr.data().id!==e)throw new Error(`VALIDATION_ERROR: ${ge.name} "${h[ge.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${ge.name} "${h[ge.name]}" is invalid`)}});await Promise.all(ct)}if(r&&E?.Role){const ve=E.Role,ct={..._,...h};if(!(w.custom?.serverAccess?.update!==void 0?await oe(w.custom.serverAccess.update,[ve,ct,_]):!0))throw new Error("PERMISSION_DENIED");for(const Zt of f.fields){const dn=Ae(Zt,w);if(Object.prototype.hasOwnProperty.call(h,Zt.name)&&dn?.custom?.serverAccess?.update!==void 0&&!await oe(dn.custom.serverAccess.update,[ve,ct,_]))throw new Error("PERMISSION_DENIED")}}mr(h,_,e,f,c,r,E,i?.operation?i.operation:A?"update":void 0,i?.permissions,N),i?.permissions&&r&&E&&await Uo(x,i.permissions,r,E,c,N,B),mr(h,_,e,f,c,r,E,i?.operation?i.operation:A?"update":void 0,i?.permissions,N),K&&(p||j(_)||F)&&await su(x,e,_.User_ID)};(p||A||F)&&await I.runTransaction(async x=>{await q(x,!0)},{maxAttempts:10});const M=async(x,K)=>{if(!_)throw new Error("NOT_FOUND");try{const B={size:1},Ee={..._,...h};await q(x,!1,B);let Le;!s?.noTwoWay&&!s?.providedTransaction&&(Le=await cr("Update",a,e,Ee,h,f,c,x,B,r,E,_));const He=Us(c);Qs("update",x,n,e,h,c,f,s,He,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.FieldValue.delete,he=>I.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${he.name}`).doc(e),(he,Ge)=>I.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${he.name}`).doc(Ge),he=>I.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${he}`).doc(e),(he,Ge)=>Ie(I,he,a).doc(Ge),(he,Ge,ve)=>I.collection("tenants").doc(a).collection("system_fields").doc(he.collection).collection(`${he.collection}-${Ge}`).doc(ve),(he,Ge,ve)=>I.collection("tenants").doc(a).collection("system_fields").doc(he.collection).collection(`${he.collection}-${Ge.replaceAll(" ","-")}`).doc(ve),_,Le,B),x.update(C.doc(e),h)}catch(B){if(s?.providedTransaction)throw B;{const Ee={operation:"update",data:h,recordId:e,context:o,error:B,originalRecord:fe(_)},Le=await ae("postWriteError",l,w,Ee);if(y&&(await new Promise(He=>{setTimeout(He,250)}),await wt("update",Le?.resolved?"success":"failed",h,a,n,e,f,Le?.resolved?void 0:B,_)),!Le?.resolved)throw p&&await zt(_),j(_)&&await Kt(_.User_ID,K,N,"USER_ERROR"),F&&await I.collection("tenants").doc(a).collection(g.collection).doc(e).update({User_ID:H.FieldValue.delete()}),B}}(p||j(_)||F)&&await ii(ci,[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 Ee=x.customClaims;if(!(Ee&&Ee.role&&Ee.collection&&Ee.doc))throw new Error("USER_ERROR")}const K={..._,...h};rt(K);const B=await Wo(i?.operation||"update",a,e,l,f,K,_,x,i?.permissions,N,i?.password);p&&(h.User_ID=B),F&&(h.User_ID=H.FieldValue.delete())}s?.providedTransaction?await M(s.providedTransaction,x):await I.runTransaction(async K=>{await M(K,x)},{maxAttempts:10})}catch(x){throw(p||j(_)||F)&&await ii(ci,[e,_.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),x}if(!s?.providedTransaction){const x={operation:"update",data:h,recordId:e,context:o,originalRecord:fe(_)},K={...x};await ae("postWrite",l,w,x),await ae("postOperation",l,w,K)}const Y={..._,...h};return rt(Y),{id:e,...Y}},ru=async(n,e,t)=>{const s=t?.userId;let r=t?.context;const i=qe(),o=kt();let a=await Ze();if(n.length===0)throw new Error("EMPTY_PATH");const l=n.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=Be(u.collection,a),w=await oe(o.appName);if(v&&!f&&!t?.force)return await jo(n,e,{[v.archivedField]:!0,[v.timestampField]:H.FieldValue.serverTimestamp()},{userId:s});const R=H.getFirestore();let O;s&&await ar(n,m);const I=Ie(R,n,i);r=r||{},r.collection=u.collection;const E=await je(n,e,{userId:s});let C=Ws("delete",n,E,a,w,"Online",s||"System",H.Timestamp.now(),H.FieldValue.serverTimestamp());const _=Sn(C);Ve(C),g&&await wt("delete","started",C,i,n,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}),Ve(C);const p=async h=>{const[S,b,T,N]=await Promise.all([h.get(R.collection("system_deployment").doc("maintenance_mode")),je(n,e,{userId:s,providedTransaction:h}),s?h.get(R.collection("tenants").doc(i).collection("system_user_permissions").doc(s)):Promise.resolve({}),Ze()]);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");ea(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 zt(C));try{await R.runTransaction(async h=>{await p(h);const S=Us(a);Qs("delete",h,n,e,C,a,m,t,S,H.FieldValue.arrayUnion,H.FieldValue.arrayRemove,H.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)=>Ie(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 wt("delete",b?.resolved?"success":"failed",C,i,n,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:H.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}},iu=async(n,e)=>{const t=H.getFirestore(),s=Xs(),r=process.env.ADMIN_SMS;if(s==="development")if(r)n=r;else throw new Error("Admin phone not set");const i={to:n,body:e};await t.collection("system_messages").add(i)},ou=n=>n!==null&&typeof n=="object",au=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{r instanceof H.Timestamp?t[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:ou(r)&&e(r)})};e(n)},lu=async n=>await _t.getAuth().getUser(n),cu=n=>{const e=er();return L.fromJSDate(n).setZone(e)},zo=n=>{const e=er();return L.fromJSDate(n.toDate()).setZone(e)},uu=(n,e)=>{const s=L.fromJSDate(n,{zone:e}).offset,i=L.fromJSDate(n).offset,o=s-i;return L.fromJSDate(n).plus({minutes:o}).toJSDate()},du=(n,e)=>{const s=L.fromJSDate(n,{zone:e}).offset,i=L.fromJSDate(n).offset,o=s-i;return L.fromJSDate(n).minus({minutes:o}).toJSDate()},fu=n=>"seconds"in n&&"nanoseconds"in n?zo(new H.Timestamp(n.seconds,n.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=nu;exports.addUser=or;exports.convertDateToTimezone=cu;exports.convertTimestampToTimezone=zo;exports.deleteRecord=ru;exports.deleteUser=zt;exports.deserializeDeleteSentinels=Qn;exports.deserializeTimestamps=lr;exports.deserializeTimestampsWithoutUnderscores=Qc;exports.displayDate=fu;exports.fetchCurrentSchema=Ze;exports.fetchLastSchema=Gc;exports.getCachedConfigValue=oa;exports.getCollectionRefs=Co;exports.getCustomizationFile=Be;exports.getCustomizationFiles=xo;exports.getDocumentRefs=tr;exports.getFirestorePathRef=Ie;exports.getGlobalConfigModule=kt;exports.getInputSchema=Uc;exports.getMaintenanceInfo=qc;exports.getMode=Xs;exports.getOne=je;exports.getSome=sr;exports.getTenant=qe;exports.getTimezone=er;exports.getUser=lu;exports.getVersionInfo=Zc;exports.getZodSchema=Ti;exports.initializeFirebase=Hc;exports.initializeStoker=jc;exports.isDeleteSentinel=be;exports.keepTimezone=uu;exports.removeTimezone=du;exports.runChildProcess=Bc;exports.sendMail=rr;exports.sendMessage=iu;exports.serializeTimestamps=au;exports.setTenant=zc;exports.tryPromise=oe;exports.updateRecord=jo;exports.updateUser=Wo;exports.validateRelations=cr;exports.validateSoftDelete=ur;exports.writeLog=wt;
14
+ <a href="${O}">${O}</a>`)}catch{throw await Xt(o.User_ID,a,c,g),new Error(g)}}}}}else if(n==="delete")try{await Zt(o)}catch(y){throw new Error(y.message)}if(v)return v},iu=async(n,e,t)=>{const s=Be(),r=ue(),i=[e];t&&t.trim()!==""&&i.push(t),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await n.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)n.set(a,{locked:!0})},ui=async(n,e)=>{const t=Be(),s=ue(),r=[n];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(t).collection("system_locks").doc(o);i.delete(a)}await i.commit()},zo=async(n,e,t,s)=>{const r=s?.userId;let i=s?.user,o=s?.context;const a=Be(),l=Tt();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(n.length===0)throw new Error("EMPTY_PATH");const d=n.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=vt.getAuth(),I=ue();let E;r&&await lr(n,f);const C=xe(I,n,a);o=o||{},o.collection=g.collection;let _=s?.originalRecord||await ze(n,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0}),Z=_;r&&(Z=await ze(n,e,{noComputedFields:!0,noEmbeddingFields:!0}));for(const x of v)x.type==="Computed"&&(delete t[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"||t.Role||t.Enabled!==void 0||t.Name||t.Email||t.Photo_URL||k.some(x=>t[x.name]!==void 0)),j=x=>x.User_ID&&(f.auth&&!p&&!F&&i?.operation==="update"||t.Role&&t.Role!==x.Role||t.Enabled!==void 0&&t.Enabled!==x.Enabled||t.Name&&t.Name!==x.Name||t.Email&&t.Email!==x.Email||t.Photo_URL&&t.Photo_URL!==x.Photo_URL||k.some(Q=>t[Q.name]!==void 0&&t[Q.name]!==x[Q.name]));delete t.id,cr(t),Kn(t);const h=js("update",n,t,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(_),y&&!s?.providedTransaction&&await Et("update","started",h,a,n,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),In(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 on("update",x,f,w,{operation:"update",record:h,context:o,originalRecord:he(_)},c)}}catch(x){throw new Error(`VALIDATION_ERROR: ${x.message}`)}Ue(h),delete t.id,In(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 on("update",x,f,w,{operation:"update",record: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(n,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,n,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 qt=Ce(we,w),fn={..._,...h};if(!(r&&qt?.custom?.serverAccess?.read!==void 0?await oe(qt.custom.serverAccess.read,[E?.Role,fn]):!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 qt of f.fields){const fn=Ce(qt,w);if(Object.prototype.hasOwnProperty.call(h,qt.name)&&fn?.custom?.serverAccess?.update!==void 0&&!await oe(fn.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 iu(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,n,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 Et("update",Ve?.resolved?"success":"failed",h,a,n,e,f,Ve?.resolved?void 0:B,_)),!Ve?.resolved)throw p&&await Zt(_),j(_)&&await Xt(_.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}},ou=async(n,e,t)=>{const s=t?.userId;let r=t?.context;const i=Be(),o=Tt();let a=await qe();if(n.length===0)throw new Error("EMPTY_PATH");const l=n.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&&!t?.force)return await zo(n,e,{[v.archivedField]:!0,[v.timestampField]:ie.FieldValue.serverTimestamp()},{userId:s});const R=ue();let O;s&&await lr(n,m);const I=xe(R,n,i);r=r||{},r.collection=u.collection;const E=await ze(n,e,{userId:s});let C=js("delete",n,E,a,w,"Online",s||"System",ie.Timestamp.now(),ie.FieldValue.serverTimestamp());const _=Rn(C);Ue(C),g&&await Et("delete","started",C,i,n,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(n,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 Zt(C));try{await R.runTransaction(async h=>{await p(h);const S=Ws(a);Ks("delete",h,n,e,C,a,m,t,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 Et("delete",b?.resolved?"success":"failed",C,i,n,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}},au=async(n,e)=>{const t=ue(),s=er(),r=process.env.ADMIN_SMS;if(s==="development")if(r)n=r;else throw new Error("Admin phone not set");const i={to:n,body:e};await t.collection("system_messages").add(i)},lu=n=>n!==null&&typeof n=="object",cu=n=>{const e=t=>{Object.entries(t).forEach(([s,r])=>{r instanceof ie.Timestamp?t[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:lu(r)&&e(r)})};e(n)},uu=async n=>await vt.getAuth().getUser(n),du=n=>{const e=tr();return L.fromJSDate(n).setZone(e)},Zo=n=>{const e=tr();return L.fromJSDate(n.toDate()).setZone(e)},fu=(n,e)=>{const s=L.fromJSDate(n,{zone:e}).offset,i=L.fromJSDate(n).offset,o=s-i;return L.fromJSDate(n).plus({minutes:o}).toJSDate()},hu=(n,e)=>{const s=L.fromJSDate(n,{zone:e}).offset,i=L.fromJSDate(n).offset,o=s-i;return L.fromJSDate(n).minus({minutes:o}).toJSDate()},mu=n=>"seconds"in n&&"nanoseconds"in n?Zo(new ie.Timestamp(n.seconds,n.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=ru;exports.addUser=ar;exports.convertDateToTimezone=du;exports.convertTimestampToTimezone=Zo;exports.deleteRecord=ou;exports.deleteUser=Zt;exports.deserializeDeleteSentinels=Kn;exports.deserializeTimestamps=cr;exports.deserializeTimestampsWithoutUnderscores=Xc;exports.displayDate=mu;exports.fetchCurrentSchema=qe;exports.fetchLastSchema=Jc;exports.getCachedConfigValue=aa;exports.getCollectionRefs=Fo;exports.getCustomizationFile=He;exports.getCustomizationFiles=No;exports.getDocumentRefs=nr;exports.getFirestorePathRef=xe;exports.getGlobalConfigModule=Tt;exports.getInputSchema=Wc;exports.getMaintenanceInfo=Hc;exports.getMode=er;exports.getOne=ze;exports.getSome=rr;exports.getStokerFirestore=ue;exports.getTenant=Be;exports.getTimezone=tr;exports.getUser=uu;exports.getVersionInfo=Bc;exports.getZodSchema=Si;exports.initializeFirebase=Yc;exports.initializeStoker=Zc;exports.isDeleteSentinel=Te;exports.keepTimezone=fu;exports.removeTimezone=hu;exports.runChildProcess=Gc;exports.sendMail=ir;exports.sendMessage=au;exports.serializeTimestamps=cu;exports.setTenant=qc;exports.tryPromise=oe;exports.updateRecord=zo;exports.updateUser=jo;exports.validateRelations=ur;exports.validateSoftDelete=dr;exports.writeLog=Et;