@stoker-platform/node-client 0.5.96 → 0.5.98
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 +5 -5
- package/dist/bundle.js +114 -106
- package/package.json +2 -2
package/dist/bundle.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("lodash/isEqual.js"),ta=require("lodash/merge.js"),na=require("lodash/set.js"),pe=require("lodash/cloneDeep.js"),vt=require("firebase-admin/app"),oe=require("firebase-admin/firestore"),Ei=require("node:url"),sa=require("cross-spawn"),vi=require("firebase-admin/database"),bt=require("firebase-admin/auth"),Qn=t=>!!t&&!Array.isArray(t),cn=(t,e)=>t.access?Qn(t.access)?!1:t.access.includes(e):!0,ra=(t,e)=>{if(Qn(t.access))return e.fieldAccessGroups?.[t.access.group]},qs=t=>{const e={};return Object.keys(t.fieldAccessGroups||{}).forEach(n=>{e[n]=[]}),t.fields.forEach(n=>{if(Qn(n.access)){const{group:s}=n.access;e[s]&&e[s].push(n)}}),e},Kn=(t,e,n,s)=>{if(!n)return!0;if(n.Role&&!t.applicableRoles.includes(n.Role))return!1;const r=n.collections?.[e],i=[];if(t.collectionAuth!==void 0&&i.push(!!r?.auth===t.collectionAuth),t.roles&&i.push(!!n.Role&&t.roles.includes(n.Role)),t.claims&&i.push(Object.entries(t.claims).every(([o,a])=>{let l=s?.[o];return l===void 0&&o==="role"&&(l=n.Role),Array.isArray(a)?a.some(c=>c===l):l===a})),t.restrictions){const{recordOwner:o,recordUser:a,recordProperty:l,restrictEntities:c}=t.restrictions;i.push((o===void 0||!!r?.recordOwner?.active===o)&&(a===void 0||!!r?.recordUser?.active===a)&&(l===void 0||!!r?.recordProperty?.active===l)&&(c===void 0||!!r?.restrictEntities===c))}return i.length===0?!1:t.match==="all"?i.every(Boolean):i.some(Boolean)},ia=(t,e,n,s)=>{const r=ra(t,e);return r?Kn(r,e.labels.collection,n,s):!1},Xn=t=>!!t.auth,xe=(t,e)=>{if(e?.operations)return e.operations.includes(t)},He=(t,e,n,s)=>e?e.Role?Qn(t.access)?!n||!s?!1:ia(t,n,e,s):t.access?.includes(e.Role):!1:!0,Oi=(t,e,n,s)=>t===!0?!1:Array.isArray(t)?t.includes(e.Role):typeof t=="object"&&t!==null?!n||!s?!1:Kn(t,n,e,s):!0,oa=(t,e,n,s)=>e?e.Role?Oi(t.restrictCreate,e,n,s):!1:!0,ki=(t,e,n,s)=>e?e.Role?Oi(t.restrictUpdate,e,n,s):!1:!0,Or=(t,e,n,s)=>{const{labels:r}=t;return n.collections&&xe("Update",n.collections[r.collection])&&(!e.access||He(e,n,t,s))&&ki(e,n,r.collection,s)&&!(t.auth&&!n.collections?.[r.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},L=(t,e)=>t.filter(n=>n.name===e)[0],X=t=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(t.type),bi=(t,e)=>{const n={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=t,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const d=a?.[n[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},Bs=(t,e)=>{const n=[],{labels:s,access:r}=t,{entityRestrictions:i}=r,o=e.collections?.[s.collection];return i?.restrictions?.forEach(a=>{"roles"in a&&a.roles.forEach(l=>{l.role===e.Role&&(!i.assignable?.includes(e.Role)||o?.restrictEntities)&&n.push(a)})}),n},Ri=(t,e,n)=>{const s=[],{access:r}=t,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.role===n.Role))return;const a=o.collectionField,l=L(t.fields,a);if(!X(l))throw new Error("PERMISSION_DENIED");const c=n.collections?.[l.collection],p=e.collections[l.collection].access.entityRestrictions;if(!p)throw new Error("PERMISSION_DENIED");const u=p.restrictions?.find(f=>f.type===o.type&&f.roles.some(g=>g.role===n.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===n.Role&&(!p.assignable?.includes(n.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},Ti=(t,e,n,s)=>{const r=Object.values(e.collections),{labels:i}=t,o=[];for(const a of r){const{fields:l}=a;for(const c of l)if(!(c.access&&!He(c,n,a,s))&&n.Role&&X(c)&&c.collection===i.collection&&c.dependencyFields)for(const d of c.dependencyFields)!o.find(u=>u.field===d.field)&&d.roles.includes(n.Role)&&o.push(d)}return o},aa=(t,e,n,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const d=bi(e,r),p=Bs(e,r),u=Ri(e,n,r);d?.filter(_=>_.type==="Record_Owner").forEach(_=>{"operations"in _&&_.operations&&!_.operations.includes(t)||i.Created_By!==s&&(c=!1)}),d?.filter(_=>_.type==="Record_User").forEach(_=>{if("operations"in _&&_.operations&&!_.operations.includes(t))return;const I=L(a,_.collectionField);i[`${I.name}_Array`]?.includes(r.Doc_ID)||(c=!1)}),d?.filter(_=>_.type==="Record_Property").forEach(_=>{if("operations"in _&&_.operations&&!_.operations.includes(t))return;const I=L(a,_.propertyField),j=_.roles.find(v=>v.role===r.Role);I.type==="Array"?j.values?.some(v=>i[I.name].includes(v))||(c=!1):j.values?.includes(i[I.name])||(c=!1)});let f=!0,g=!1;p?.filter(_=>_.type==="Individual").forEach(()=>{g=!0,l?.individualEntities?.includes(i.id)||(f=!1)});let k=!0,y=!1;if(p?.filter(_=>_.type==="Parent").forEach(_=>{y=!0;const I=L(a,_.collectionField);l?.parentEntities?.some(j=>i[`${I.name}_Array`].includes(j))||(k=!1)}),p?.filter(_=>_.type==="Parent_Property").forEach(_=>{y=!0;const I=L(a,_.collectionField),j=L(a,_.propertyField);Object.entries(l?.parentPropertyEntities||{}).some(v=>{const[U,h]=v;return U===i[j.name]&&i[`${I.name}_Array`].some(x=>h.includes(x))})||(k=!1)}),g&&y){if(!(f||k)){c=!1;return}}else if(!f||!k){c=!1;return}let E=!0,w=!1;u?.filter(_=>_.parentFilter.type==="Individual").forEach(_=>{w=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=r.collections?.[j.collection];if(!v){c=!1;return}v.individualEntities?.some(U=>i[`${j.name}_Array`].includes(U))||(E=!1)});let A=!0,O=!1;if(u?.filter(_=>_.parentFilter.type==="Parent").forEach(_=>{O=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=L(a,I.parentCollectionField),U=r.collections?.[j.collection];if(!U){c=!1;return}U.parentEntities?.some(h=>i[`${v.name}_Array`].includes(h))||(A=!1)}),u?.filter(_=>_.parentFilter.type==="Parent_Property").forEach(_=>{O=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=L(a,I.parentPropertyField),U=L(a,I.parentCollectionField),h=r.collections?.[j.collection];if(!h){c=!1;return}Object.entries(h.parentPropertyEntities||{}).some(x=>{const[R,q]=x;return R===i[v.name]&&i[`${U.name}_Array`].some(Z=>q.includes(Z))})||(A=!1)}),w&&O){if(!(E||A)){c=!1;return}}else if(!E||!A){c=!1;return}return c},ft=(t,e,n,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;xe(t,a)||(l=!1);const d=Bs(e,r)?.filter(p=>p.type==="Individual").length>0;return t==="Create"&&d&&(l=!1),aa(t,e,n,s,r,i)||(l=!1),l},Si=(t,e,n)=>{const{labels:s}=t,r=[];for(const i of Object.values(e.collections));return r},la=(t,e)=>{let n=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){n=!1,s="Permissions object must contain Doc_ID, Role, Collection, Enabled, and collections";return}}),e.collections&&(Object.keys(e.collections).forEach(r=>{if(!Object.keys(t.collections).includes(r)){s=`Collection ${r} not found in schema`,n=!1;return}const i=t.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,n=!1;return}if(!Object.keys(o).every(a=>["operations","auth","restrictEntities","individualEntities","parentEntities","parentPropertyEntities","recordProperty","recordUser","recordOwner"].includes(a))){s=`Collection ${r} has invalid properties`,n=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,n=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,n=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,n=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),p=i.access.entityRestrictions?.restrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(u=>t.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,n=!1;return}if(d?.length||p?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const u=Object.keys(l);if(u.length!==1||u[0]!=="active"||typeof l.active!="boolean"){s=`Collection ${r} has invalid attribute restriction value`,n=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,n=!1;return}if(a==="Parent"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,n=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,n=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,n=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),n},ca=(t,e,n)=>{let s=!0,r="";Object.values(t.collections).filter(i=>i.auth).forEach(i=>{const o=e.collections?.[i.labels.collection],a=i.access.auth,l=e.Role;if(o?.auth&&!a?.roles.includes(l)){r="Record cannot have auth access to collection",s=!1;return}if(a?.roles.includes(l)&&!a.assignable?.includes(l)&&!o?.auth){r="Record is missing required auth access to collection",s=!1;return}});for(const i of Object.values(t.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:d,entityRestrictions:p}=a,u=c.assignable,f=e.collections?.[o.collection],g=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(n))?g.forEach(y=>{const E=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const w=!!a.operations[y]?.includes(n),A=!!f?.operations.includes(E);if(!w&&A){r=`Collection ${o.collection} has excess ${y} operation for role ${n}`,s=!1;return}if(w&&!A){r=`Collection ${o.collection} has missing ${y} operation for role ${n}`,s=!1;return}}}):g.forEach(y=>{const E=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const w=!!a.operations[y]?.includes(n),A=!!f?.operations.includes(E);if(!w&&A){r=`Collection ${o.collection} has excess ${y} operation for role ${n}`,s=!1;return}}}),!d&&!p||(d?.forEach(y=>{for(const E of y.roles)if(E.role===n&&!E.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${n}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${n}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${n}`,s=!1;return}}}),p?.assignable?.includes(n)))continue;let k=!1;if(p?.restrictions?.forEach(y=>{for(const E of y.roles)if(E.role===n){if(k=!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 w=L(l,y.collectionField);if(!X(w)){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 w=L(l,y.collectionField);if(!X(w)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[w.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),k&&!e.collections?.[o.collection]?.restrictEntities){r=`Collection ${o.collection} must have restrictEntities set to true`,s=!1;return}}return r&&console.error(`PERMISSION_DENIED: ${r}`),s},ua=(t,e,n,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:d}=c;let p=!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}`,p=!1,p):t==="update"&&o.User_ID&&f?.length&&!f.some(g=>g.recordRole===a)?(u=`User ${s} does not have write access to record with role ${r}`,p=!1,p):(d?.forEach(g=>{s===g.userRole&&g.recordRole===r&&t!=="delete"&&i&&Object.keys(n.collections).forEach(k=>{const y=i.collections?.[k],E=l?.collections?.[k];if(!(t==="update"&&Xe(y,E))&&y){const w=g.collections.some(A=>A.collection===k);if(w){if(w){const A=g.collections.find(_=>_.collection===k);if(!(y.operations.every(_=>A.operations.includes(_))||t==="update"&&Xe(y.operations,E?.operations))){u=`User ${s} does not have write access to all included operations for collection ${k}`,p=!1;return}if(!A.auth&&y.auth&&!(t==="update"&&Xe(y.auth,E?.auth))){u=`User ${s} does not have write access to auth for collection ${k}`,p=!1;return}const O={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(O).forEach(_=>{const I=O[_];if(A.attributeRestrictions?.includes(I)&&!(y[_]?.active||t==="update"&&Xe(y[_],E?.[_]))){u=`User ${s} does not have write access to attribute restriction ${_} for collection ${k}`,p=!1;return}}),A.restrictEntities&&!y.restrictEntities&&!(t==="update"&&Xe(y.restrictEntities,E?.restrictEntities))){u=`User ${s} does not have write access to restrictEntities for collection ${k}`,p=!1;return}}}else{u=`User ${s} does not have write access to collection ${k}`,p=!1;return}}})}),u&&console.error(`PERMISSION_DENIED: ${u}`),p)},da=(t,e,n,s)=>{let r=!0,i="";return Object.values(t.collections).forEach(o=>{const a=n.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!Xn(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)&&(!xe("Read",c)||!xe(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},Hs=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:p}=s;let u=!0,f="";if(!e.Role)return f="Record does not have a role",u=!1,u;if(t==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(t==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!ua(t,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(t==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;if(t==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return f="User cannot update their own record",u=!1,u;if(t==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return t==="delete"||d==="delete"||!a?u:a.Role?(la(r,a)||(u=!1),a.Collection&&a.Collection!==p.collection?(f="Permissions collection does not match record collection",u=!1,u):a.Role!==e.Role?(f="Permissions role does not match record role",u=!1,u):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",u=!1,u):a.Doc_ID&&a.Doc_ID!==n?(f="Permissions doc ID does not match record doc ID",u=!1,u):!ca(r,a,a.Role)||i&&o&&l&&!da(r,o,a,l)?(u=!1,u):(f&&console.error(`PERMISSION_DENIED: ${f}`),u)):(f="Permissions do not have a role",u=!1,u)},kr=(t,e,n,s,r,i,o,a)=>{const{labels:l,fields:c}=n,d=i?.collections?.[l.collection];let p=!0;if(r&&!d)throw new Error("PERMISSION_DENIED");r&&!xe("Create",d)&&(p=!1),r&&!ft("Create",n,s,r,i,t)&&(p=!1),n.auth&&o&&(r&&!Xn(d)&&(p=!1),Hs("create",t,e,n,s,r,i,o)||(p=!1));for(const u of c){const f=t[u.name];u.access&&!He(u,i,n,a)&&f!==void 0&&(p=!1),f!==void 0&&!oa(u,i,l.collection,a)&&(p=!1)}if(!p)throw new Error("PERMISSION_DENIED")},Oe=t=>t&&(t._methodName==="deleteField"||t.constructor.name==="DeleteTransform"),et=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(Oe(t[e])?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&et(t[e]))},br=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:p,fields:u}=s,f=o?.collections?.[p.collection],g={...e,...t};et(g);let k=!0,y="";if(i&&!f)throw new Error("PERMISSION_DENIED");i&&!xe("Update",f)&&(k=!1,y="Authenticated user does not have Update access to this collection"),i&&(!ft("Update",s,r,i,o,e)||!ft("Update",s,r,i,o,g))&&(k=!1,y="Authenticated user does not have Update access to this document"),i&&s.softDelete&&g[s.softDelete.archivedField]!==e[s.softDelete.archivedField]&&!xe("Delete",f)&&(k=!1,y="Authenticated user does not have Delete or Restore access to this document"),a&&(i&&!Xn(f)&&(k=!1,y="Authenticated user does not have Auth access for this collection"),Hs("update",g,n,s,r,i,o,l,c,e,a)||(y="Authenticated user does not have sufficient write access for this record",k=!1));for(const E of u){const w=t[E.name];E.access&&!He(E,o,s,d)&&w!==void 0&&(y=`Authenticated user does not have access to field ${E.name}`,k=!1),w!==void 0&&!ki(E,o,p.collection,d)&&(y=`Authenticated user does not have Update access to field ${E.name}`,k=!1)}if(!k)throw y&&console.error(`PERMISSION_DENIED: ${y}`),new Error("PERMISSION_DENIED")},fa=(t,e,n,s,r,i)=>{const{labels:o}=n,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(xe("Delete",a)||(l=!1),ft("Delete",n,s,r,i,t)||(l=!1),n.auth&&t.User_ID&&(Xn(a)||(l=!1),Hs("delete",t,e,n,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},ha=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(xe("Read",o)||(a=!1),ft("Read",e,n,s,r,t)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},ma=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(xe("Read",o)||(a=!1),t.forEach(l=>{ft("Read",e,n,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},pa=(t,e,n)=>{const{access:s}=t;return s.operations[n]?.includes(e)},ya=(t,e,n)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===t)&&!("singleQuery"in i&&i.singleQuery))return`${i.type} entity restriction`}if(r?.parentFilters)for(const i of r.parentFilters){if(!i.roles.some(c=>c.role===t))continue;const o=L(e.fields,i.collectionField);if(!X(o))throw new Error("PERMISSION_DENIED");const l=n.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(d=>d.role===t));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},ga=(t,e,n,s,r)=>{const i={};for(const o of t){const l=e[o].default({sdk:n,utils:s,context:r});for(const c in l)c==="custom"||c==="admin"||c==="fields"||delete l[c];for(const c of l.fields)for(const d in c)d==="custom"||d==="admin"||d==="name"||d==="formula"||delete c[d];i[o]=l}return i},We=(t,e)=>e.fields.filter(n=>n.name===t.name)[0],os={global:{},collections:{}},Kt=(t,e)=>t&&typeof t=="function"?e?t(...e):t():t,ae=async(t,e)=>{let n=t;return t&&(typeof t=="function"||typeof t.then=="function")&&(e?n=await t(...e):n=await t()),n},wa=async(t,e,n,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=os,i=!0;for(const d of e){if(d===void 0||r[d]===void 0){i=!1;break}r=r[d]}if(r&&i&&!s)return r;let o,a=t,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await ae(a,n)),c){let d=os;const p={};for(let u=0;u<e.length;u++){const f=e[u];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");u===e.length-1?na(p,e.join("."),c):(d[f]||={},d=d[f])}}ta(os,p)}return c},mt=(t,e,n)=>{const s=Object.values(n.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field===t.name&&(i=!0)}return i},Ii=(t,e)=>{const n=Object.values(e.collections),{labels:s}=t,r={};return n.forEach(i=>{const{labels:o,fields:a}=i;a.forEach(l=>{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},as=t=>JSON.stringify(t.map(e=>e.name)),ct=["id","Collection_Path","Last_Write_At","Last_Save_At","Last_Write_By","Last_Write_App","Last_Write_Connection_Status","Last_Write_Version","Created_At","Saved_At","Created_By"],mn=()=>ct.map(t=>{let e="",n;switch(t){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",n=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:t,type:e,required:!0};return n&&(s.values=n),s}),Gs=(t,e)=>{const n=[],{access:s,fields:r}=t,{attributeRestrictions:i,entityRestrictions:o}=s,a=mn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":n.push(L(a,"Created_By"));break;case"Record_User":n.push(L(r,l.collectionField));break;case"Record_Property":n.push(L(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(L(a,"id"));break;case"Parent":n.push(L(r,l.collectionField));break;case"Parent_Property":n.push(L(r,l.collectionField)),n.push(L(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(L(r,l.collectionField));break;case"Parent":n.push(L(r,l.parentCollectionField));break;case"Parent_Property":n.push(L(r,l.parentCollectionField)),n.push(L(r,l.parentPropertyField));break}})),[...new Set(n)]},_a=(t,e)=>{const n=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=t,a=mn();return n.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{cn(c,e)&&n.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{n.push(L(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{ct.includes(c)&&n.push(L(a,c))}),o?.forEach(c=>{const d=L(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&d&&cn(d,e)&&ct.includes(c.field)&&n.push(L(a,c.field))}),Gs(t,e).forEach(c=>{ct.includes(c.name)&&n.push(L(a,c.name))}),[...new Set(n)]},Ea=(t,e,n)=>{const s=[],{fields:r,preloadCache:i}=e,o=mn(),a=new Set,l=Ii(e,n);return Object.entries(l).map(([c,d])=>{t.name===c&&Object.values(d).forEach(p=>{p.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(...Gs(e,c))}),i?.range&&i.range.fields.forEach(c=>{ct.includes(c)?s.push(L(o,c)):Array.from(a).some(d=>cn(L(r,c),d))&&s.push(L(r,c))}),[...new Set(s)]},En=(t,e,n)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=Ii(e,n);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{n.collections[c].fields.forEach(p=>{X(p)&&p.collection===e.labels.collection&&p.dependencyFields?.some(u=>u.field===t.name)&&p.constraints&&p.constraints.forEach(u=>{o.push(u[0])})})})}),o.forEach(l=>{s.push(L(r,l))}),i){const l=L(r,i.archivedField);l&&s.push(l)}return s.push(...Ea(t,e,n)),[...new Set(s)]},va=(t,e,n)=>{const s=e.fieldAccessGroups?.[t]?.applicableRoles||[];return n.roles.filter(r=>s.includes(r))},on=(t,e)=>`${t}-${e}`,vn=(t,e,n)=>{if(!e.fieldAccessGroups?.[t])return[];const s=va(t,e,n);if(s.length===0)return[];const r=[],{fields:i,softDelete:o,preloadCache:a,roleSystemFields:l,queries:c}=e,d=mn();r.push({name:"Collection_Path",type:"Array",required:!0}),r.push({name:"id",type:"String",required:!0});const p=qs(e)[t]||[];if(r.push(...p),o){const u=L(i,o.archivedField);u&&!p.includes(u)&&r.push(u)}a?.range&&a.range.fields.forEach(u=>{ct.includes(u)?r.push(L(d,u)):s.some(f=>cn(L(i,u),f))&&r.push(L(i,u))}),l?.filter(u=>u.field!=="Collection_Path"&&s.some(f=>!u.roles||u.roles.includes(f))).forEach(u=>{r.push(L(d,u.field))}),c?.forEach(u=>{const f=L(i.concat(d),u.field);f&&s.some(g=>(!u.roles||u.roles.includes(g))&&cn(f,g))&&r.push(f)});for(const u of s)r.push(...Gs(e,u));return[...new Set(r)]},xi=(t,e)=>{const{preloadCache:n}=t,s=new Set;for(const r of e.config.roles){if(!pa(t,r,"read"))continue;const i=_a(t,r);let o=!1;if(s.size===0)s.add({key:"1",roles:[r],fields:i}),o=!0;else for(const a of s)i.length===a.fields.length&&i.every(l=>a.fields.some(c=>c.name===l.name))&&!!n?.roles.includes(r)==!!a.roles.every(l=>n?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},Ai=(t,e,n)=>{const s=xi(e,n);for(const r of s.values())if(r.roles.includes(t))return r},Oa=(t,e)=>{const{fields:n}=e,s=mn(),r=[];return[...n,...s.filter(o=>o.name!=="id")].forEach(o=>{t?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ys=(t,e,n)=>{const s={};return Object.values(t.collections).forEach(r=>{const i=xi(r,t),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},$n=t=>({Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_Version:t.Last_Write_Version,Last_Write_App:t.Last_Write_App,Last_Save_At:t.Last_Save_At}),ls=async(t,e,n)=>{if(e){const s=await ae(e,[n]);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${t}`);return s}};async function ce(t,e,n,s){const r=await ls(t,n.custom?.[t],s);for(const i of n.fields)await ls(t,i.custom?.[t],s);if(t!=="setEmbedding"&&(await ls(t,e?.[t],s),t==="postWriteError"))return r}const Js=(t,e,n,s,r,i,o,a,l,c)=>(t==="create"&&(n.Collection_Path=e,n.Created_At=a,n.Saved_At=l,n.Created_By=o||"System"),n.Last_Write_App=r,n.Last_Write_At=a,n.Last_Save_At=l,n.Last_Write_By=o||"System",n.Last_Write_Connection_Status=i,n.Last_Write_Version=s.version,n),gt=(t,e)=>{const{access:n,queries:s}=t,{serverReadOnly:r}=n,i=new Set;if(s)for(const o of s){const a=L(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},Rt=(t,e)=>{const{access:n,recordTitleField:s}=t,{serverReadOnly:r}=n,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},ka=(t,e)=>{const n={Collection_Path:t.Collection_Path};if(t.deleted!==void 0&&(n.deleted=t.deleted),e)for(const s of e)t[s]!==void 0&&(n[s]=t[s]);return n},wt=(t,e,n)=>{const{fields:s}=t;s.forEach(i=>{if(X(i))if(e[i.name]){if(Oe(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(Object.keys(e[i.name]).forEach(o=>{const a=e[i.name][o];e[i.name][o]=ka(a,i.includeFields)}),e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=n.collections[i.collection],l=L(a.fields,o);Rt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(d=>{e[i.name][d][o]?e[i.name][d][`${o}_Lowercase`]=e[i.name][d][o].toLowerCase():delete e[i.name][d][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),gt(t,s).forEach(i=>{if(e[i.name])if(Oe(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}}}})},Mn=(t,e)=>{Rt(t,t.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},ba=async(t,e,n,s,r)=>{const{fields:i}=e;for(const o of n.fields){const a=L(i,o.name);o.custom?.initialValue!==void 0&&(!a.access||He(a,s,e,r||{}))&&(t[o.name]=await ae(o.custom.initialValue,[t]),Rt(e,[a]).size===1&&(t[`${o.name}_Lowercase`]=t[o.name].toLowerCase()))}for(const o of i)(!o.access||He(o,s,e,r||{}))&&("autoIncrement"in o&&o.autoIncrement&&!t[o.name]&&(t[o.name]="Pending"),!X(o)&&o.nullable&&t[o.name]===void 0&&(t[o.name]=null))};var se;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},t.find=(r,i)=>{for(const o of r)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(se||(se={}));var Rr;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Rr||(Rr={}));const W=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ot=t=>{switch(typeof t){case"undefined":return W.undefined;case"string":return W.string;case"number":return Number.isNaN(t)?W.nan:W.number;case"boolean":return W.boolean;case"function":return W.function;case"bigint":return W.bigint;case"symbol":return W.symbol;case"object":return Array.isArray(t)?W.array:t===null?W.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?W.promise:typeof Map<"u"&&t instanceof Map?W.map:typeof Set<"u"&&t instanceof Set?W.set:typeof Date<"u"&&t instanceof Date?W.date:W.object;default:return W.unknown}},N=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 nt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let a=s,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof nt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}nt.create=t=>new nt(t);const Rs=(t,e)=>{let n;switch(t.code){case N.invalid_type:t.received===W.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:se.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case N.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case N.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=e.defaultError,se.assertNever(t)}return{message:n}};let Ra=Rs;function Ta(){return Ra}const Sa=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)a=c(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function P(t,e){const n=Ta(),s=Sa({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Rs?void 0:Rs].filter(r=>!!r)});t.common.issues.push(s)}class Re{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Re.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return J;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const J=Object.freeze({status:"aborted"}),Xt=t=>({status:"dirty",value:t}),Pe=t=>({status:"valid",value:t}),Tr=t=>t.status==="aborted",Sr=t=>t.status==="dirty",Pt=t=>t.status==="valid",Pn=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));class Ge{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ir=(t,e)=>{if(Pt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new nt(t.common.issues);return this._error=n,this._error}}};function K(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:r}}class te{get description(){return this._def.description}_getType(e){return ot(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Re,ctx:{common:e.parent.common,data:e.data,parsedType:ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Pn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)},r=this._parseSync({data:e,path:s.path,parent:s});return Ir(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return Pt(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>Pt(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Pn(r)?r:Promise.resolve(r));return Ir(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:N.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new Ut({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return ut.create(this,this._def)}nullable(){return Wt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ze.create(this)}promise(){return jn.create(this,this._def)}or(e){return Vn.create([this,e],this._def)}and(e){return Un.create(this,e,this._def)}transform(e){return new Ut({...K(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Ns({...K(this._def),innerType:this,defaultValue:n,typeName:Y.ZodDefault})}brand(){return new Ja({typeName:Y.ZodBranded,type:this,...K(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Ds({...K(this._def),innerType:this,catchValue:n,typeName:Y.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Qs.create(this,e)}readonly(){return Cs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ia=/^c[^\s-]{8,}$/i,xa=/^[0-9a-z]+$/,Aa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Na=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Da=/^[a-z0-9_-]{21}$/i,Ca=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fa=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$a=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ma="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let cs;const Pa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,La=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Va=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ua=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Wa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ja=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ni="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Za=new RegExp(`^${Ni}$`);function Di(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function za(t){return new RegExp(`^${Di(t)}$`)}function qa(t){let e=`${Ni}T${Di(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Ba(t,e){return!!((e==="v4"||!e)&&Pa.test(t)||(e==="v6"||!e)&&Va.test(t))}function Ha(t,e){if(!Ca.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Ga(t,e){return!!((e==="v4"||!e)&&La.test(t)||(e==="v6"||!e)&&Ua.test(t))}class tt extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==W.string){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.string,received:i.parsedType}),J}const s=new Re;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:N.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:N.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:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&P(r,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")$a.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"email",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")cs||(cs=new RegExp(Ma,"u")),cs.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"emoji",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")Na.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"uuid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")Da.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"nanoid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Ia.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")xa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid2",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Aa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ulid",code:N.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:N.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:N.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:N.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:N.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:N.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?qa(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Za.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?za(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?Fa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"duration",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ba(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ip",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Ha(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"jwt",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ga(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cidr",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Wa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?ja.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64url",code:N.invalid_string,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:N.invalid_string,...z.errToObj(s)})}_addCheck(e){return new tt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...z.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...z.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...z.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...z.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...z.errToObj(n)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new tt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new tt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new tt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}tt.create=t=>new tt({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...K(t)});function Ya(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Lt 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)!==W.number){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.number,received:i.parsedType}),J}let s;const r=new Re;for(const i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:N.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:N.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:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Ya(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),P(s,{code:N.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:N.not_finite,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,z.toString(n))}setLimit(e,n,s,r){return new Lt({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new Lt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&se.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Lt.create=t=>new Lt({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...K(t)});class un extends te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==W.bigint)return this._getInvalidInput(e);let s;const r=new Re;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:N.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:N.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:N.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return P(n,{code:N.invalid_type,expected:W.bigint,received:n.parsedType}),J}gte(e,n){return this.setLimit("min",e,!0,z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,z.toString(n))}setLimit(e,n,s,r){return new un({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new un({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}un.create=t=>new un({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...K(t)});class Ts extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==W.boolean){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.boolean,received:s.parsedType}),J}return Pe(e.data)}}Ts.create=t=>new Ts({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...K(t)});class Ln extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==W.date){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_date}),J}const s=new Re;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:N.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:N.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 Ln({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Ln.create=t=>new Ln({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...K(t)});class xr extends te{_parse(e){if(this._getType(e)!==W.symbol){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.symbol,received:s.parsedType}),J}return Pe(e.data)}}xr.create=t=>new xr({typeName:Y.ZodSymbol,...K(t)});class Ss extends te{_parse(e){if(this._getType(e)!==W.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.undefined,received:s.parsedType}),J}return Pe(e.data)}}Ss.create=t=>new Ss({typeName:Y.ZodUndefined,...K(t)});class Ar extends te{_parse(e){if(this._getType(e)!==W.null){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.null,received:s.parsedType}),J}return Pe(e.data)}}Ar.create=t=>new Ar({typeName:Y.ZodNull,...K(t)});class Is extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return Pe(e.data)}}Is.create=t=>new Is({typeName:Y.ZodAny,...K(t)});class Nr extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Pe(e.data)}}Nr.create=t=>new Nr({typeName:Y.ZodUnknown,...K(t)});class ht extends te{_parse(e){const n=this._getOrReturnCtx(e);return P(n,{code:N.invalid_type,expected:W.never,received:n.parsedType}),J}}ht.create=t=>new ht({typeName:Y.ZodNever,...K(t)});class Dr extends te{_parse(e){if(this._getType(e)!==W.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.void,received:s.parsedType}),J}return Pe(e.data)}}Dr.create=t=>new Dr({typeName:Y.ZodVoid,...K(t)});class ze extends te{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==W.array)return P(n,{code:N.invalid_type,expected:W.array,received:n.parsedType}),J;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,a=n.data.length<r.exactLength.value;(o||a)&&(P(n,{code:o?N.too_big:N.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(P(n,{code:N.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(P(n,{code:N.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>r.type._parseAsync(new Ge(n,o,n.path,a)))).then(o=>Re.mergeArray(s,o));const i=[...n.data].map((o,a)=>r.type._parseSync(new Ge(n,o,n.path,a)));return Re.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new ze({...this._def,minLength:{value:e,message:z.toString(n)}})}max(e,n){return new ze({...this._def,maxLength:{value:e,message:z.toString(n)}})}length(e,n){return new ze({...this._def,exactLength:{value:e,message:z.toString(n)}})}nonempty(e){return this.min(1,e)}}ze.create=(t,e)=>new ze({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...K(e)});function Dt(t){if(t instanceof he){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=ut.create(Dt(s))}return new he({...t._def,shape:()=>e})}else return t instanceof ze?new ze({...t._def,type:Dt(t.element)}):t instanceof ut?ut.create(Dt(t.unwrap())):t instanceof Wt?Wt.create(Dt(t.unwrap())):t instanceof Ot?Ot.create(t.items.map(e=>Dt(e))):t}class he extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=se.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==W.object){const c=this._getOrReturnCtx(e);return P(c,{code:N.invalid_type,expected:W.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 ht&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const d=i[c],p=r.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Ge(r,p,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ht){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")a.length>0&&(P(r,{code:N.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 p=r.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Ge(r,p,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const p=await d.key,u=await d.value;c.push({key:p,value:u,alwaysSet:d.alwaysSet})}return c}).then(c=>Re.mergeObjectSync(s,c)):Re.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new he({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:z.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new he({...this._def,unknownKeys:"strip"})}passthrough(){return new he({...this._def,unknownKeys:"passthrough"})}extend(e){return new he({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new he({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new he({...this._def,catchall:e})}pick(e){const n={};for(const s of se.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new he({...this._def,shape:()=>n})}omit(e){const n={};for(const s of se.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new he({...this._def,shape:()=>n})}deepPartial(){return Dt(this)}partial(e){const n={};for(const s of se.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new he({...this._def,shape:()=>n})}required(e){const n={};for(const s of se.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof ut;)i=i._def.innerType;n[s]=i}return new he({...this._def,shape:()=>n})}keyof(){return Ci(se.objectKeys(this.shape))}}he.create=(t,e)=>new he({shape:()=>t,unknownKeys:"strip",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});he.strictCreate=(t,e)=>new he({shape:()=>t,unknownKeys:"strict",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});he.lazycreate=(t,e)=>new he({shape:t,unknownKeys:"strip",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});class Vn extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new nt(a.ctx.common.issues));return P(n,{code:N.invalid_union,unionErrors:o}),J}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new nt(l));return P(n,{code:N.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}Vn.create=(t,e)=>new Vn({options:t,typeName:Y.ZodUnion,...K(e)});function xs(t,e){const n=ot(t),s=ot(e);if(t===e)return{valid:!0,data:t};if(n===W.object&&s===W.object){const r=se.objectKeys(e),i=se.objectKeys(t).filter(a=>r.indexOf(a)!==-1),o={...t,...e};for(const a of i){const l=xs(t[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(n===W.array&&s===W.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const o=t[i],a=e[i],l=xs(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===W.date&&s===W.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Un extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(Tr(i)||Tr(o))return J;const a=xs(i.value,o.value);return a.valid?((Sr(i)||Sr(o))&&n.dirty(),{status:n.value,value:a.data}):(P(s,{code:N.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}))}}Un.create=(t,e,n)=>new Un({left:t,right:e,typeName:Y.ZodIntersection,...K(n)});class Ot extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.array)return P(s,{code:N.invalid_type,expected:W.array,received:s.parsedType}),J;if(s.data.length<this._def.items.length)return P(s,{code:N.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:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Ge(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Re.mergeArray(n,o)):Re.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new Ot({...this._def,rest:e})}}Ot.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ot({items:t,typeName:Y.ZodTuple,rest:null,...K(e)})};class Wn extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.object)return P(s,{code:N.invalid_type,expected:W.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 Ge(s,a,s.path,a)),value:o._parse(new Ge(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Re.mergeObjectAsync(n,r):Re.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof te?new Wn({keyType:e,valueType:n,typeName:Y.ZodRecord,...K(s)}):new Wn({keyType:tt.create(),valueType:e,typeName:Y.ZodRecord,...K(n)})}}class Cr extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.map)return P(s,{code:N.invalid_type,expected:W.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 Ge(s,a,s.path,[c,"key"])),value:i._parse(new Ge(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}}}}Cr.create=(t,e,n)=>new Cr({valueType:e,keyType:t,typeName:Y.ZodMap,...K(n)});class dn extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.set)return P(s,{code:N.invalid_type,expected:W.set,received:s.parsedType}),J;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(P(s,{code:N.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(P(s,{code:N.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const d of l){if(d.status==="aborted")return J;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new Ge(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,n){return new dn({...this._def,minSize:{value:e,message:z.toString(n)}})}max(e,n){return new dn({...this._def,maxSize:{value:e,message:z.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}dn.create=(t,e)=>new dn({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...K(e)});class Fr extends te{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Fr.create=(t,e)=>new Fr({getter:t,typeName:Y.ZodLazy,...K(e)});class As extends te{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return P(n,{received:n.data,code:N.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}As.create=(t,e)=>new As({value:t,typeName:Y.ZodLiteral,...K(e)});function Ci(t,e){return new Vt({values:t,typeName:Y.ZodEnum,...K(e)})}class Vt extends te{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return P(n,{expected:se.joinValues(s),received:n.parsedType,code:N.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return P(n,{received:n.data,code:N.invalid_enum_value,options:s}),J}return Pe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Vt.create(e,{...this._def,...n})}exclude(e,n=this._def){return Vt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}Vt.create=Ci;class $r extends te{_parse(e){const n=se.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==W.string&&s.parsedType!==W.number){const r=se.objectValues(n);return P(s,{expected:se.joinValues(r),received:s.parsedType,code:N.invalid_type}),J}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=se.objectValues(n);return P(s,{received:s.data,code:N.invalid_enum_value,options:r}),J}return Pe(e.data)}get enum(){return this._def.values}}$r.create=(t,e)=>new $r({values:t,typeName:Y.ZodNativeEnum,...K(e)});class jn extends te{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==W.promise&&n.common.async===!1)return P(n,{code:N.invalid_type,expected:W.promise,received:n.parsedType}),J;const s=n.parsedType===W.promise?n.data:Promise.resolve(n.data);return Pe(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}jn.create=(t,e)=>new jn({type:t,typeName:Y.ZodPromise,...K(e)});class Ut extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{P(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(n.value==="aborted")return J;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?J:l.status==="dirty"||n.value==="dirty"?Xt(l.value):l});{if(n.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?J:a.status==="dirty"||n.value==="dirty"?Xt(a.value):a}}if(r.type==="refinement"){const o=a=>{const l=r.refinement(a,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?J:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Pt(o))return J;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Pt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:n.value,value:a})):J);se.assertNever(r)}}Ut.create=(t,e,n)=>new Ut({schema:t,typeName:Y.ZodEffects,effect:e,...K(n)});Ut.createWithPreprocess=(t,e,n)=>new Ut({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...K(n)});class ut extends te{_parse(e){return this._getType(e)===W.undefined?Pe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ut.create=(t,e)=>new ut({innerType:t,typeName:Y.ZodOptional,...K(e)});class Wt extends te{_parse(e){return this._getType(e)===W.null?Pe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Wt.create=(t,e)=>new Wt({innerType:t,typeName:Y.ZodNullable,...K(e)});class Ns extends te{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===W.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ns.create=(t,e)=>new Ns({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});class Ds extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Pn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new nt(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new nt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ds.create=(t,e)=>new Ds({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...K(e)});class Mr extends te{_parse(e){if(this._getType(e)!==W.nan){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.nan,received:s.parsedType}),J}return{status:"valid",value:e.data}}}Mr.create=t=>new Mr({typeName:Y.ZodNaN,...K(t)});class Ja extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Qs extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?J:i.status==="dirty"?(n.dirty(),Xt(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?J:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new Qs({in:e,out:n,typeName:Y.ZodPipeline})}}class Cs extends te{_parse(e){const n=this._def.innerType._parse(e),s=r=>(Pt(r)&&(r.value=Object.freeze(r.value)),r);return Pn(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}Cs.create=(t,e)=>new Cs({innerType:t,typeName:Y.ZodReadonly,...K(e)});var Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(Y={}));const Ie=tt.create,_t=Lt.create,an=Ts.create,us=Ss.create,Ee=Is.create;ht.create;const Tt=ze.create,qe=he.create,Te=Vn.create;Un.create;Ot.create;const pn=Wn.create,Se=As.create,Zn=Vt.create;jn.create;ut.create;Wt.create;const In=()=>Ee().refine(t=>t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),Pr=()=>Ee().refine(t=>t&&(t._methodName==="serverTimestamp"||t.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),Fi=(t,e,n)=>{const s={};if(t.includeFields){const i=e.collections[t.collection];if(!i)return pn(Ee());t.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${t.collection}`);s[o]=zn(i,a),Rt(i,[a]).size===1&&(s[`${o}_Lowercase`]=zn(i,a,!0))})}const r={Collection_Path:Tt(Ie()),...s};return n&&(r.id=Ie().length(20)),qe(r)},Qa=(t,e)=>{let n=pn(Fi(t,e));return t.required||(n=n.optional()),n},Ka=t=>{let e=Tt(Te([Ie().length(20),Ie().length(28)]));return["OneToOne","OneToMany"].includes(t.type)?e=e.max(1):(t.min&&(e=e.min(t.min)),t.max&&(e=e.max(t.max)),t.length&&(e=e.length(t.length))),t.required?e=e.nonempty():e=e.optional(),e},zn=(t,e,n)=>{const{softDelete:s}=t,r=s?.timestampField;let i;switch(e.type){case"String":if(i=Ie(),e.length&&(i=i.length(e.length)),e.minlength&&(i=i.min(e.minlength)),e.maxlength&&(i=i.max(e.maxlength)),e.email&&(i=i.email()),e.uuid&&(i=i.uuid()),e.url&&(i=i.url()),e.emoji&&(i=i.emoji()),e.ip&&(i=i.ip()),e.pattern&&(i=i.regex(new RegExp(e.pattern))),n&&(i=i.toLowerCase()),e.values)if(n){const o=e.values.map(a=>a.toLowerCase());i=Zn(o)}else i=Zn(e.values);break;case"Boolean":i=an();break;case"Number":e.autoIncrement?i=Te([Se("Pending"),_t().int()]):(i=_t(),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=Ee().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=In(),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=Tt(Ee()),e.length&&(i=i.length(e.length)),e.minlength?i=i.min(e.minlength):e.required&&(i=i.nonempty()),e.maxlength&&(i=i.max(e.maxlength)),e.values&&(i=i.refine(o=>{let a=!0;return o.forEach(l=>{e.values&&!e.values.includes(l)&&(a=!1)}),a},{message:"Value is not an allowed value"}));break;case"Map":i=pn(Ee()),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=Ee();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},$i=(t,e,n)=>{const s={Collection_Path:Tt(Ie()),Last_Write_App:Ie(),Last_Write_At:In(),Last_Save_At:Pr(),Last_Write_By:Te([Ie().length(28),Se("System")]),Last_Write_Connection_Status:Zn(["Online","Offline"]),Last_Write_Version:_t().int(),id:Ie().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:In(),Created_By:Te([Ie().length(28),Se("System")])};t==="create"&&(s.Saved_At=Pr()),t==="update"&&(s.Saved_At=In(),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=gt(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{X(l)?(s[l.name]=Qa(l,n),s[`${l.name}_Array`]=Ka(l),i.includes(l.name)&&(s[`${l.name}_Single`]=Fi(l,n,!0),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=zn(e,l))}),Rt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=zn(e,l,!0))});const a=qe(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class St extends Error{}class Xa extends St{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class el extends St{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class tl extends St{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Ct extends St{}class Mi extends St{constructor(e){super(`Invalid unit ${e}`)}}class ve extends St{}class it extends St{constructor(){super("Zone is an abstract class")}}const $="numeric",je="short",Ae="long",qn={year:$,month:$,day:$},Pi={year:$,month:je,day:$},nl={year:$,month:je,day:$,weekday:je},Li={year:$,month:Ae,day:$},Vi={year:$,month:Ae,day:$,weekday:Ae},Ui={hour:$,minute:$},Wi={hour:$,minute:$,second:$},ji={hour:$,minute:$,second:$,timeZoneName:je},Zi={hour:$,minute:$,second:$,timeZoneName:Ae},zi={hour:$,minute:$,hourCycle:"h23"},qi={hour:$,minute:$,second:$,hourCycle:"h23"},Bi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:je},Hi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:Ae},Gi={year:$,month:$,day:$,hour:$,minute:$},Yi={year:$,month:$,day:$,hour:$,minute:$,second:$},Ji={year:$,month:je,day:$,hour:$,minute:$},Qi={year:$,month:je,day:$,hour:$,minute:$,second:$},sl={year:$,month:je,day:$,weekday:je,hour:$,minute:$},Ki={year:$,month:Ae,day:$,hour:$,minute:$,timeZoneName:je},Xi={year:$,month:Ae,day:$,hour:$,minute:$,second:$,timeZoneName:je},eo={year:$,month:Ae,day:$,weekday:Ae,hour:$,minute:$,timeZoneName:Ae},to={year:$,month:Ae,day:$,weekday:Ae,hour:$,minute:$,second:$,timeZoneName:Ae};class yn{get type(){throw new it}get name(){throw new it}get ianaName(){return this.name}get isUniversal(){throw new it}offsetName(e,n){throw new it}formatOffset(e,n){throw new it}offset(e){throw new it}equals(e){throw new it}get isValid(){throw new it}}let ds=null;class es extends yn{static get instance(){return ds===null&&(ds=new es),ds}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return ho(e,n,s)}formatOffset(e,n){return ln(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Fs=new Map;function rl(t){let e=Fs.get(t);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Fs.set(t,e)),e}const il={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ol(t,e){const n=t.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,r,i,o,a,l,c,d]=s;return[o,r,i,a,l,c,d]}function al(t,e){const n=t.formatToParts(e),s=[];for(let r=0;r<n.length;r++){const{type:i,value:o}=n[r],a=il[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const fs=new Map;class st extends yn{static create(e){let n=fs.get(e);return n===void 0&&fs.set(e,n=new st(e)),n}static resetCache(){fs.clear(),Fs.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=st.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return ho(e,n,s,this.name)}formatOffset(e,n){return ln(this.offset(e),n)}offset(e){if(!this.valid)return NaN;const n=new Date(e);if(isNaN(n))return NaN;const s=rl(this.name);let[r,i,o,a,l,c,d]=s.formatToParts?al(s,n):ol(s,n);a==="BC"&&(r=-Math.abs(r)+1);const u=ns({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:d,millisecond:0});let f=+n;const g=f%1e3;return f-=g>=0?g:1e3+g,(u-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Lr={};function ll(t,e={}){const n=JSON.stringify([t,e]);let s=Lr[n];return s||(s=new Intl.ListFormat(t,e),Lr[n]=s),s}const $s=new Map;function Ms(t,e={}){const n=JSON.stringify([t,e]);let s=$s.get(n);return s===void 0&&(s=new Intl.DateTimeFormat(t,e),$s.set(n,s)),s}const Ps=new Map;function cl(t,e={}){const n=JSON.stringify([t,e]);let s=Ps.get(n);return s===void 0&&(s=new Intl.NumberFormat(t,e),Ps.set(n,s)),s}const Ls=new Map;function ul(t,e={}){const{base:n,...s}=e,r=JSON.stringify([t,s]);let i=Ls.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(t,e),Ls.set(r,i)),i}let en=null;function dl(){return en||(en=new Intl.DateTimeFormat().resolvedOptions().locale,en)}const Vs=new Map;function no(t){let e=Vs.get(t);return e===void 0&&(e=new Intl.DateTimeFormat(t).resolvedOptions(),Vs.set(t,e)),e}const Us=new Map;function fl(t){let e=Us.get(t);if(!e){const n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,"minimalDays"in e||(e={...so,...e}),Us.set(t,e)}return e}function hl(t){const e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));const n=t.indexOf("-u-");if(n===-1)return[t];{let s,r;try{s=Ms(t).resolvedOptions(),r=t}catch{const l=t.substring(0,n);s=Ms(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function ml(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function pl(t){const e=[];for(let n=1;n<=12;n++){const s=V.utc(2009,n,1);e.push(t(s))}return e}function yl(t){const e=[];for(let n=1;n<=7;n++){const s=V.utc(2016,11,13+n);e.push(t(s))}return e}function On(t,e,n,s){const r=t.listingMode();return r==="error"?null:r==="en"?n(e):s(e)}function gl(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||no(t.locale).numberingSystem==="latn"}class wl{constructor(e,n,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!n||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=cl(e,a)}}format(e){if(this.inf){const n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):nr(e,3);return me(n,this.padTo)}}}class _l{constructor(e,n,s){this.opts=s,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&st.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=Ms(n,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(n=>{if(n.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:s}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class El{constructor(e,n,s){this.opts={style:"long",...s},!n&&uo()&&(this.rtf=ul(e,s))}format(e,n){return this.rtf?this.rtf.format(e,n):jl(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}const so={firstDay:1,minimalDays:4,weekend:[6,7]};class ie{static fromOpts(e){return ie.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,s,r,i=!1){const o=e||de.defaultLocale,a=o||(i?"en-US":dl()),l=n||de.defaultNumberingSystem,c=s||de.defaultOutputCalendar,d=js(r)||de.defaultWeekSettings;return new ie(a,l,c,d,o)}static resetCache(){en=null,$s.clear(),Ps.clear(),Ls.clear(),Vs.clear(),Us.clear()}static fromObject({locale:e,numberingSystem:n,outputCalendar:s,weekSettings:r}={}){return ie.create(e,n,s,r)}constructor(e,n,s,r,i){const[o,a,l]=hl(e);this.locale=o,this.numberingSystem=n||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=ml(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=gl(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:ie.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,js(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1){return On(this,e,yo,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");n&=!s;const r=n?{month:e,day:"numeric"}:{month:e},i=n?"format":"standalone";if(!this.monthsCache[i][e]){const o=s?a=>this.dtFormatter(a,r).format():a=>this.extract(a,r,"month");this.monthsCache[i][e]=pl(o)}return this.monthsCache[i][e]})}weekdays(e,n=!1){return On(this,e,_o,()=>{const s=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=n?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=yl(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return On(this,void 0,()=>Eo,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[V.utc(2016,11,13,9),V.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return On(this,e,vo,()=>{const n={era:e};return this.eraCache[e]||(this.eraCache[e]=[V.utc(-40,1,1),V.utc(2017,1,1)].map(s=>this.extract(s,n,"era"))),this.eraCache[e]})}extract(e,n,s){const r=this.dtFormatter(e,n),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new wl(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new _l(e,this.intl,n)}relFormatter(e={}){return new El(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ll(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||no(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:fo()?fl(this.locale):so}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let hs=null;class be extends yn{static get utcInstance(){return hs===null&&(hs=new be(0)),hs}static instance(e){return e===0?be.utcInstance:new be(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new be(ss(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${ln(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${ln(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return ln(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class vl extends yn{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function lt(t,e){if(G(t)||t===null)return e;if(t instanceof yn)return t;if(Sl(t)){const n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?es.instance:n==="utc"||n==="gmt"?be.utcInstance:be.parseSpecifier(n)||st.create(t)}else return dt(t)?be.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new vl(t)}const Ks={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Vr={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Ol=Ks.hanidec.replace(/[\[|\]]/g,"").split("");function kl(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);if(t[n].search(Ks.hanidec)!==-1)e+=Ol.indexOf(t[n]);else for(const r in Vr){const[i,o]=Vr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const Ws=new Map;function bl(){Ws.clear()}function Le({numberingSystem:t},e=""){const n=t||"latn";let s=Ws.get(n);s===void 0&&(s=new Map,Ws.set(n,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${Ks[n]}${e}`),s.set(e,r)),r}let Ur=()=>Date.now(),Wr="system",jr=null,Zr=null,zr=null,qr=60,Br,Hr=null;class de{static get now(){return Ur}static set now(e){Ur=e}static set defaultZone(e){Wr=e}static get defaultZone(){return lt(Wr,es.instance)}static get defaultLocale(){return jr}static set defaultLocale(e){jr=e}static get defaultNumberingSystem(){return Zr}static set defaultNumberingSystem(e){Zr=e}static get defaultOutputCalendar(){return zr}static set defaultOutputCalendar(e){zr=e}static get defaultWeekSettings(){return Hr}static set defaultWeekSettings(e){Hr=js(e)}static get twoDigitCutoffYear(){return qr}static set twoDigitCutoffYear(e){qr=e%100}static get throwOnInvalid(){return Br}static set throwOnInvalid(e){Br=e}static resetCaches(){ie.resetCache(),st.resetCache(),V.resetCache(),bl()}}class Ue{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const ro=[0,31,59,90,120,151,181,212,243,273,304,334],io=[0,31,60,91,121,152,182,213,244,274,305,335];function $e(t,e){return new Ue("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Xs(t,e,n){const s=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function oo(t,e,n){return n+(gn(t)?io:ro)[e-1]}function ao(t,e){const n=gn(t)?io:ro,s=n.findIndex(i=>i<e),r=e-n[s];return{month:s+1,day:r}}function er(t,e){return(t-e+7)%7+1}function Bn(t,e=4,n=1){const{year:s,month:r,day:i}=t,o=oo(s,r,i),a=er(Xs(s,r,i),n);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=fn(c,e,n)):l>fn(s,e,n)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...rs(t)}}function Gr(t,e=4,n=1){const{weekYear:s,weekNumber:r,weekday:i}=t,o=er(Xs(s,1,e),n),a=$t(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=$t(c)):l>a?(c=s+1,l-=$t(s)):c=s;const{month:d,day:p}=ao(c,l);return{year:c,month:d,day:p,...rs(t)}}function ms(t){const{year:e,month:n,day:s}=t,r=oo(e,n,s);return{year:e,ordinal:r,...rs(t)}}function Yr(t){const{year:e,ordinal:n}=t,{month:s,day:r}=ao(e,n);return{year:e,month:s,day:r,...rs(t)}}function Jr(t,e){if(!G(t.localWeekday)||!G(t.localWeekNumber)||!G(t.localWeekYear)){if(!G(t.weekday)||!G(t.weekNumber)||!G(t.weekYear))throw new Ct("Cannot mix locale-based week fields with ISO-based week fields");return G(t.localWeekday)||(t.weekday=t.localWeekday),G(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),G(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function Rl(t,e=4,n=1){const s=ts(t.weekYear),r=Me(t.weekNumber,1,fn(t.weekYear,e,n)),i=Me(t.weekday,1,7);return s?r?i?!1:$e("weekday",t.weekday):$e("week",t.weekNumber):$e("weekYear",t.weekYear)}function Tl(t){const e=ts(t.year),n=Me(t.ordinal,1,$t(t.year));return e?n?!1:$e("ordinal",t.ordinal):$e("year",t.year)}function lo(t){const e=ts(t.year),n=Me(t.month,1,12),s=Me(t.day,1,Hn(t.year,t.month));return e?n?s?!1:$e("day",t.day):$e("month",t.month):$e("year",t.year)}function co(t){const{hour:e,minute:n,second:s,millisecond:r}=t,i=Me(e,0,23)||e===24&&n===0&&s===0&&r===0,o=Me(n,0,59),a=Me(s,0,59),l=Me(r,0,999);return i?o?a?l?!1:$e("millisecond",r):$e("second",s):$e("minute",n):$e("hour",e)}function G(t){return typeof t>"u"}function dt(t){return typeof t=="number"}function ts(t){return typeof t=="number"&&t%1===0}function Sl(t){return typeof t=="string"}function Il(t){return Object.prototype.toString.call(t)==="[object Date]"}function uo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function fo(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function xl(t){return Array.isArray(t)?t:[t]}function Qr(t,e,n){if(t.length!==0)return t.reduce((s,r)=>{const i=[e(r),r];return s&&n(s[0],i[0])===s[0]?s:i},null)[1]}function Al(t,e){return e.reduce((n,s)=>(n[s]=t[s],n),{})}function jt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function js(t){if(t==null)return null;if(typeof t!="object")throw new ve("Week settings must be an object");if(!Me(t.firstDay,1,7)||!Me(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Me(e,1,7)))throw new ve("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Me(t,e,n){return ts(t)&&t>=e&&t<=n}function Nl(t,e){return t-e*Math.floor(t/e)}function me(t,e=2){const n=t<0;let s;return n?s="-"+(""+-t).padStart(e,"0"):s=(""+t).padStart(e,"0"),s}function at(t){if(!(G(t)||t===null||t===""))return parseInt(t,10)}function pt(t){if(!(G(t)||t===null||t===""))return parseFloat(t)}function tr(t){if(!(G(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function nr(t,e,n="round"){const s=10**e;switch(n){case"expand":return t>0?Math.ceil(t*s)/s:Math.floor(t*s)/s;case"trunc":return Math.trunc(t*s)/s;case"round":return Math.round(t*s)/s;case"floor":return Math.floor(t*s)/s;case"ceil":return Math.ceil(t*s)/s;default:throw new RangeError(`Value rounding ${n} is out of range`)}}function gn(t){return t%4===0&&(t%100!==0||t%400===0)}function $t(t){return gn(t)?366:365}function Hn(t,e){const n=Nl(e-1,12)+1,s=t+(e-n)/12;return n===2?gn(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function ns(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Kr(t,e,n){return-er(Xs(t,1,e),n)+e-1}function fn(t,e=4,n=1){const s=Kr(t,e,n),r=Kr(t+1,e,n);return($t(t)-s+r)/7}function Zs(t){return t>99?t:t>de.twoDigitCutoffYear?1900+t:2e3+t}function ho(t,e,n,s=null){const r=new Date(t),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(n,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function ss(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const s=parseInt(e,10)||0,r=n<0||Object.is(n,-0)?-s:s;return n*60+r}function mo(t){const e=Number(t);if(typeof t=="boolean"||t===""||!Number.isFinite(e))throw new ve(`Invalid unit value ${t}`);return e}function Gn(t,e){const n={};for(const s in t)if(jt(t,s)){const r=t[s];if(r==null)continue;n[e(s)]=mo(r)}return n}function ln(t,e){const n=Math.trunc(Math.abs(t/60)),s=Math.trunc(Math.abs(t%60)),r=t>=0?"+":"-";switch(e){case"short":return`${r}${me(n,2)}:${me(s,2)}`;case"narrow":return`${r}${n}${s>0?`:${s}`:""}`;case"techie":return`${r}${me(n,2)}${me(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function rs(t){return Al(t,["hour","minute","second","millisecond"])}const Dl=["January","February","March","April","May","June","July","August","September","October","November","December"],po=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Cl=["J","F","M","A","M","J","J","A","S","O","N","D"];function yo(t){switch(t){case"narrow":return[...Cl];case"short":return[...po];case"long":return[...Dl];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const go=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],wo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Fl=["M","T","W","T","F","S","S"];function _o(t){switch(t){case"narrow":return[...Fl];case"short":return[...wo];case"long":return[...go];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Eo=["AM","PM"],$l=["Before Christ","Anno Domini"],Ml=["BC","AD"],Pl=["B","A"];function vo(t){switch(t){case"narrow":return[...Pl];case"short":return[...Ml];case"long":return[...$l];default:return null}}function Ll(t){return Eo[t.hour<12?0:1]}function Vl(t,e){return _o(e)[t.weekday-1]}function Ul(t,e){return yo(e)[t.month-1]}function Wl(t,e){return vo(e)[t.year<0?0:1]}function jl(t,e,n="always",s=!1){const r={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&i){const p=t==="days";switch(e){case 1:return p?"tomorrow":`next ${r[t][0]}`;case-1:return p?"yesterday":`last ${r[t][0]}`;case 0:return p?"today":`this ${r[t][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[t],d=s?l?c[1]:c[2]||c[1]:l?r[t][0]:t;return o?`${a} ${d} ago`:`in ${a} ${d}`}function Xr(t,e){let n="";for(const s of t)s.literal?n+=s.val:n+=e(s.val);return n}const Zl={D:qn,DD:Pi,DDD:Li,DDDD:Vi,t:Ui,tt:Wi,ttt:ji,tttt:Zi,T:zi,TT:qi,TTT:Bi,TTTT:Hi,f:Gi,ff:Ji,fff:Ki,ffff:eo,F:Yi,FF:Qi,FFF:Xi,FFFF:to};class ke{static create(e,n={}){return new ke(e,n)}static parseFormat(e){let n=null,s="",r=!1;const i=[];for(let o=0;o<e.length;o++){const a=e.charAt(o);a==="'"?((s.length>0||r)&&i.push({literal:r||/^\s+$/.test(s),val:s===""?"'":s}),n=null,s="",r=!r):r||a===n?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,n=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return Zl[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0,s=void 0){if(this.opts.forceSimple)return me(e,n);const r={...this.opts};return n>0&&(r.padTo=n),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(f,g)=>this.loc.extract(e,f,g),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>s?Ll(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,g)=>s?Ul(e,f):i(g?{month:f}:{month:f,day:"numeric"},"month"),c=(f,g)=>s?Vl(e,f):i(g?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),d=f=>{const g=ke.macroTokenToFormatOpts(f);return g?this.formatWithSystemDefault(e,g):f},p=f=>s?Wl(e,f):i({era:f},"era"),u=f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return r?i({day:"numeric"},"day"):this.num(e.day);case"dd":return r?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return r?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return r?i({month:"numeric"},"month"):this.num(e.month);case"MM":return r?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return r?i({year:"numeric"},"year"):this.num(e.year);case"yy":return r?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return p("short");case"GG":return p("long");case"GGGGG":return p("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return d(f)}};return Xr(ke.parseFormat(n),u)}formatDurationFromString(e,n){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(d,p)=>u=>{const f=r(u);if(f){const g=p.isNegativeDuration&&f!==p.largestUnit?s:1;let k;return this.opts.signMode==="negativeLargestOnly"&&f!==p.largestUnit?k="never":this.opts.signMode==="all"?k="always":k="auto",this.num(d.get(f)*g,u.length,k)}else return u},o=ke.parseFormat(n),a=o.reduce((d,{literal:p,val:u})=>p?d:d.concat(u),[]),l=e.shiftTo(...a.map(r).filter(d=>d)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Xr(o,i(l,c))}}const Oo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Zt(...t){const e=t.reduce((n,s)=>n+s.source,"");return RegExp(`^${e}$`)}function zt(...t){return e=>t.reduce(([n,s,r],i)=>{const[o,a,l]=i(e,r);return[{...n,...o},a||s,l]},[{},null,1]).slice(0,2)}function qt(t,...e){if(t==null)return[null,null];for(const[n,s]of e){const r=n.exec(t);if(r)return s(r)}return[null,null]}function ko(...t){return(e,n)=>{const s={};let r;for(r=0;r<t.length;r++)s[t[r]]=at(e[n+r]);return[s,null,n+r]}}const bo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,zl=`(?:${bo.source}?(?:\\[(${Oo.source})\\])?)?`,sr=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Ro=RegExp(`${sr.source}${zl}`),rr=RegExp(`(?:[Tt]${Ro.source})?`),ql=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Bl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Hl=/(\d{4})-?(\d{3})/,Gl=ko("weekYear","weekNumber","weekDay"),Yl=ko("year","ordinal"),Jl=/(\d{4})-(\d\d)-(\d\d)/,To=RegExp(`${sr.source} ?(?:${bo.source}|(${Oo.source}))?`),Ql=RegExp(`(?: ${To.source})?`);function Mt(t,e,n){const s=t[e];return G(s)?n:at(s)}function Kl(t,e){return[{year:Mt(t,e),month:Mt(t,e+1,1),day:Mt(t,e+2,1)},null,e+3]}function Bt(t,e){return[{hours:Mt(t,e,0),minutes:Mt(t,e+1,0),seconds:Mt(t,e+2,0),milliseconds:tr(t[e+3])},null,e+4]}function wn(t,e){const n=!t[e]&&!t[e+1],s=ss(t[e+1],t[e+2]),r=n?null:be.instance(s);return[{},r,e+3]}function _n(t,e){const n=t[e]?st.create(t[e]):null;return[{},n,e+1]}const Xl=RegExp(`^T?${sr.source}$`),ec=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function tc(t){const[e,n,s,r,i,o,a,l,c]=t,d=e[0]==="-",p=l&&l[0]==="-",u=(f,g=!1)=>f!==void 0&&(g||f&&d)?-f:f;return[{years:u(pt(n)),months:u(pt(s)),weeks:u(pt(r)),days:u(pt(i)),hours:u(pt(o)),minutes:u(pt(a)),seconds:u(pt(l),l==="-0"),milliseconds:u(tr(c),p)}]}const nc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ir(t,e,n,s,r,i,o){const a={year:e.length===2?Zs(at(e)):at(e),month:po.indexOf(n)+1,day:at(s),hour:at(r),minute:at(i)};return o&&(a.second=at(o)),t&&(a.weekday=t.length>3?go.indexOf(t)+1:wo.indexOf(t)+1),a}const sc=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function rc(t){const[,e,n,s,r,i,o,a,l,c,d,p]=t,u=ir(e,r,s,n,i,o,a);let f;return l?f=nc[l]:c?f=0:f=ss(d,p),[u,new be(f)]}function ic(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const oc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,ac=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,lc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function ei(t){const[,e,n,s,r,i,o,a]=t;return[ir(e,r,s,n,i,o,a),be.utcInstance]}function cc(t){const[,e,n,s,r,i,o,a]=t;return[ir(e,a,n,s,r,i,o),be.utcInstance]}const uc=Zt(ql,rr),dc=Zt(Bl,rr),fc=Zt(Hl,rr),hc=Zt(Ro),So=zt(Kl,Bt,wn,_n),mc=zt(Gl,Bt,wn,_n),pc=zt(Yl,Bt,wn,_n),yc=zt(Bt,wn,_n);function gc(t){return qt(t,[uc,So],[dc,mc],[fc,pc],[hc,yc])}function wc(t){return qt(ic(t),[sc,rc])}function _c(t){return qt(t,[oc,ei],[ac,ei],[lc,cc])}function Ec(t){return qt(t,[ec,tc])}const vc=zt(Bt);function Oc(t){return qt(t,[Xl,vc])}const kc=Zt(Jl,Ql),bc=Zt(To),Rc=zt(Bt,wn,_n);function Tc(t){return qt(t,[kc,So],[bc,Rc])}const ti="Invalid Duration",Io={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Sc={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...Io},Fe=146097/400,xt=146097/4800,Ic={years:{quarters:4,months:12,weeks:Fe/7,days:Fe,hours:Fe*24,minutes:Fe*24*60,seconds:Fe*24*60*60,milliseconds:Fe*24*60*60*1e3},quarters:{months:3,weeks:Fe/28,days:Fe/4,hours:Fe*24/4,minutes:Fe*24*60/4,seconds:Fe*24*60*60/4,milliseconds:Fe*24*60*60*1e3/4},months:{weeks:xt/7,days:xt,hours:xt*24,minutes:xt*24*60,seconds:xt*24*60*60,milliseconds:xt*24*60*60*1e3},...Io},Et=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],xc=Et.slice(0).reverse();function Ke(t,e,n=!1){const s={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new ne(s)}function xo(t,e){let n=e.milliseconds??0;for(const s of xc.slice(1))e[s]&&(n+=e[s]*t[s].milliseconds);return n}function ni(t,e){const n=xo(t,e)<0?-1:1;Et.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*n,o=t[r][s],a=Math.floor(i/o);e[r]+=a*n,e[s]-=a*o*n}return r},null),Et.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*t[s][r]}return r},null)}function si(t){const e={};for(const[n,s]of Object.entries(t))s!==0&&(e[n]=s);return e}class ne{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;let s=n?Ic:Sc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||ie.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,n){return ne.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new ve(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ne({values:Gn(e,ne.normalizeUnit),loc:ie.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(dt(e))return ne.fromMillis(e);if(ne.isDuration(e))return e;if(typeof e=="object")return ne.fromObject(e);throw new ve(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[s]=Ec(e);return s?ne.fromObject(s,n):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[s]=Oc(e);return s?ne.fromObject(s,n):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new ve("need to specify a reason the Duration is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new tl(s);return new ne({invalid:s})}static normalizeUnit(e){const n={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!n)throw new Mi(e);return n}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,n={}){const s={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?ke.create(this.loc,s).formatDurationFromString(this,e):ti}toHuman(e={}){if(!this.isValid)return ti;const n=e.showZeros!==!1,s=Et.map(r=>{const i=this.values[r];return G(i)||i===0&&!n?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=nr(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},V.fromMillis(n,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?xo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e),s={};for(const r of Et)(jt(n.values,r)||jt(this.values,r))&&(s[r]=n.get(r)+this.get(r));return Ke(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const s of Object.keys(this.values))n[s]=mo(e(this.values[s],s));return Ke(this,{values:n},!0)}get(e){return this[ne.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...Gn(e,ne.normalizeUnit)};return Ke(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:r,conversionAccuracy:s};return Ke(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return ni(this.matrix,e),Ke(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=si(this.normalize().shiftToAll().toObject());return Ke(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>ne.normalizeUnit(o));const n={},s={},r=this.toObject();let i;for(const o of Et)if(e.indexOf(o)>=0){i=o;let a=0;for(const c in s)a+=this.matrix[c][o]*s[c],s[c]=0;dt(r[o])&&(a+=r[o]);const l=Math.trunc(a);n[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else dt(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(n[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return ni(this.matrix,n),Ke(this,{values:n},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return Ke(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=si(this.values);return Ke(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function n(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of Et)if(!n(this.values[s],e.values[s]))return!1;return!0}}const At="Invalid Interval";function Ac(t,e){return!t||!t.isValid?ue.invalid("missing or invalid start"):!e||!e.isValid?ue.invalid("missing or invalid end"):e<t?ue.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}class ue{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new ve("need to specify a reason the Interval is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new el(s);return new ue({invalid:s})}static fromDateTimes(e,n){const s=Qt(e),r=Qt(n),i=Ac(s,r);return i??new ue({start:s,end:r})}static after(e,n){const s=ne.fromDurationLike(n),r=Qt(e);return ue.fromDateTimes(r,r.plus(s))}static before(e,n){const s=ne.fromDurationLike(n),r=Qt(e);return ue.fromDateTimes(r.minus(s),r)}static fromISO(e,n){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=V.fromISO(s,n),o=i.isValid}catch{o=!1}let a,l;try{a=V.fromISO(r,n),l=a.isValid}catch{l=!1}if(o&&l)return ue.fromDateTimes(i,a);if(o){const c=ne.fromISO(r,n);if(c.isValid)return ue.after(i,c)}else if(l){const c=ne.fromISO(s,n);if(c.isValid)return ue.before(a,c)}}return ue.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",n){if(!this.isValid)return NaN;const s=this.start.startOf(e,n);let r;return n?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,n),Math.floor(r.diff(s,e).get(e))+(r.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:n}={}){return this.isValid?ue.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(Qt).filter(o=>this.contains(o)).sort((o,a)=>o.toMillis()-a.toMillis()),s=[];let{s:r}=this,i=0;for(;r<this.e;){const o=n[i]||this.e,a=+o>+this.e?this.e:o;s.push(ue.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const n=ne.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(n.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(ue.fromDateTimes(s,i)),s=i,r+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const n=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return n>=s?null:ue.fromDateTimes(n,s)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return ue.fromDateTimes(n,s)}static merge(e){const[n,s]=e.sort((r,i)=>r.s-i.s).reduce(([r,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[r,i.union(o)]:[r.concat([i]),o]:[r,o],[[],null]);return s&&n.push(s),n}static xor(e){let n=null,s=0;const r=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((l,c)=>l.time-c.time);for(const l of a)s+=l.type==="s"?1:-1,s===1?n=l.time:(n&&+n!=+l.time&&r.push(ue.fromDateTimes(n,l.time)),n=null);return ue.merge(r)}difference(...e){return ue.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:At}[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=qn,n={}){return this.isValid?ke.create(this.s.loc.clone(n),e).formatInterval(this):At}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:At}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:At}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:At}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:At}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):ne.invalid(this.invalidReason)}mapEndpoints(e){return ue.fromDateTimes(e(this.s),e(this.e))}}class kn{static hasDST(e=de.defaultZone){const n=V.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return st.isValidZone(e)}static normalizeZone(e){return lt(e,de.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(n,s,i)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(n,s,i)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(n,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(n,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ie.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return ie.create(n,null,"gregory").eras(e)}static features(){return{relative:uo(),localeWeek:fo()}}}function ri(t,e){const n=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=n(e)-n(t);return Math.floor(ne.fromMillis(s).as("days"))}function Nc(t,e,n){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const d=ri(l,c);return(d-d%7)/7}],["days",ri]],r={},i=t;let o,a;for(const[l,c]of s)n.indexOf(l)>=0&&(o=l,r[l]=c(t,e),a=i.plus(r),a>e?(r[l]--,t=i.plus(r),t>e&&(a=t,r[l]--,t=i.plus(r))):t=a);return[t,r,a,o]}function Dc(t,e,n,s){let[r,i,o,a]=Nc(t,e,n);const l=e-r,c=n.filter(p=>["hours","minutes","seconds","milliseconds"].indexOf(p)>=0);c.length===0&&(o<e&&(o=r.plus({[a]:1})),o!==r&&(i[a]=(i[a]||0)+l/(o-r)));const d=ne.fromObject(i,s);return c.length>0?ne.fromMillis(l,s).shiftTo(...c).plus(d):d}const Cc="missing Intl.DateTimeFormat.formatToParts support";function re(t,e=n=>n){return{regex:t,deser:([n])=>e(kl(n))}}const Fc=" ",Ao=`[ ${Fc}]`,No=new RegExp(Ao,"g");function $c(t){return t.replace(/\./g,"\\.?").replace(No,Ao)}function ii(t){return t.replace(/\./g,"").replace(No," ").toLowerCase()}function Ve(t,e){return t===null?null:{regex:RegExp(t.map($c).join("|")),deser:([n])=>t.findIndex(s=>ii(n)===ii(s))+e}}function oi(t,e){return{regex:t,deser:([,n,s])=>ss(n,s),groups:e}}function bn(t){return{regex:t,deser:([e])=>e}}function Mc(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Pc(t,e){const n=Le(e),s=Le(e,"{2}"),r=Le(e,"{3}"),i=Le(e,"{4}"),o=Le(e,"{6}"),a=Le(e,"{1,2}"),l=Le(e,"{1,3}"),c=Le(e,"{1,6}"),d=Le(e,"{1,9}"),p=Le(e,"{2,4}"),u=Le(e,"{4,6}"),f=y=>({regex:RegExp(Mc(y.val)),deser:([E])=>E,literal:!0}),k=(y=>{if(t.literal)return f(y);switch(y.val){case"G":return Ve(e.eras("short"),0);case"GG":return Ve(e.eras("long"),0);case"y":return re(c);case"yy":return re(p,Zs);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 Ve(e.months("short",!0),1);case"MMMM":return Ve(e.months("long",!0),1);case"L":return re(a);case"LL":return re(s);case"LLL":return Ve(e.months("short",!1),1);case"LLLL":return Ve(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 bn(d);case"uu":return bn(a);case"uuu":return re(n);case"a":return Ve(e.meridiems(),0);case"kkkk":return re(i);case"kk":return re(p,Zs);case"W":return re(a);case"WW":return re(s);case"E":case"c":return re(n);case"EEE":return Ve(e.weekdays("short",!1),1);case"EEEE":return Ve(e.weekdays("long",!1),1);case"ccc":return Ve(e.weekdays("short",!0),1);case"cccc":return Ve(e.weekdays("long",!0),1);case"Z":case"ZZ":return oi(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return oi(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return bn(/[a-z_+-/]{1,256}?/i);case" ":return bn(/[^\S\n\r]/);default:return f(y)}})(t)||{invalidReason:Cc};return k.token=t,k}const Lc={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Vc(t,e,n){const{type:s,value:r}=t;if(s==="literal"){const l=/^\s+$/.test(r);return{literal:!l,val:l?" ":r}}const i=e[s];let o=s;s==="hour"&&(e.hour12!=null?o=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?o="hour12":o="hour24":o=n.hour12?"hour12":"hour24");let a=Lc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Uc(t){return[`^${t.map(n=>n.regex).reduce((n,s)=>`${n}(${s.source})`,"")}$`,t]}function Wc(t,e,n){const s=t.match(e);if(s){const r={};let i=1;for(const o in n)if(jt(n,o)){const a=n[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function jc(t){const e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let n=null,s;return G(t.z)||(n=st.create(t.z)),G(t.Z)||(n||(n=new be(t.Z)),s=t.Z),G(t.q)||(t.M=(t.q-1)*3+1),G(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),G(t.u)||(t.S=tr(t.u)),[Object.keys(t).reduce((i,o)=>{const a=e(o);return a&&(i[a]=t[o]),i},{}),n,s]}let ps=null;function Zc(){return ps||(ps=V.fromMillis(1555555555555)),ps}function zc(t,e){if(t.literal)return t;const n=ke.macroTokenToFormatOpts(t.val),s=$o(n,e);return s==null||s.includes(void 0)?t:s}function Do(t,e){return Array.prototype.concat(...t.map(n=>zc(n,e)))}class Co{constructor(e,n){if(this.locale=e,this.format=n,this.tokens=Do(ke.parseFormat(n),e),this.units=this.tokens.map(s=>Pc(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Uc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[n,s]=Wc(e,this.regex,this.handlers),[r,i,o]=s?jc(s):[null,null,void 0];if(jt(s,"a")&&jt(s,"H"))throw new Ct("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:n,matches:s,result:r,zone:i,specificOffset:o}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function Fo(t,e,n){return new Co(t,n).explainFromTokens(e)}function qc(t,e,n){const{result:s,zone:r,specificOffset:i,invalidReason:o}=Fo(t,e,n);return[s,r,i,o]}function $o(t,e){if(!t)return null;const s=ke.create(e,t).dtFormatter(Zc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Vc(o,t,i))}const ys="Invalid DateTime",ai=864e13;function tn(t){return new Ue("unsupported zone",`the zone "${t.name}" is not supported`)}function gs(t){return t.weekData===null&&(t.weekData=Bn(t.c)),t.weekData}function ws(t){return t.localWeekData===null&&(t.localWeekData=Bn(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function yt(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new V({...n,...e,old:n})}function Mo(t,e,n){let s=t-e*60*1e3;const r=n.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=n.offset(s);return r===i?[s,r]:[t-Math.min(r,i)*60*1e3,Math.max(r,i)]}function Rn(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function xn(t,e,n){return Mo(ns(t),e,n)}function li(t,e){const n=t.o,s=t.c.year+Math.trunc(e.years),r=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...t.c,year:s,month:r,day:Math.min(t.c.day,Hn(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=ns(i);let[l,c]=Mo(a,n,t.zone);return o!==0&&(l+=o,c=t.zone.offset(l)),{ts:l,o:c}}function Nt(t,e,n,s,r,i){const{setZone:o,zone:a}=n;if(t&&Object.keys(t).length!==0||e){const l=e||a,c=V.fromObject(t,{...n,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return V.invalid(new Ue("unparsable",`the input "${r}" can't be parsed as ${s}`))}function Tn(t,e,n=!0){return t.isValid?ke.create(ie.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function _s(t,e,n){const s=t.c.year>9999||t.c.year<0;let r="";if(s&&t.c.year>=0&&(r+="+"),r+=me(t.c.year,s?6:4),n==="year")return r;if(e){if(r+="-",r+=me(t.c.month),n==="month")return r;r+="-"}else if(r+=me(t.c.month),n==="month")return r;return r+=me(t.c.day),r}function ci(t,e,n,s,r,i,o){let a=!n||t.c.millisecond!==0||t.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=me(t.c.hour),o==="hour")break;if(e){if(l+=":",l+=me(t.c.minute),o==="minute")break;a&&(l+=":",l+=me(t.c.second))}else{if(l+=me(t.c.minute),o==="minute")break;a&&(l+=me(t.c.second))}if(o==="second")break;a&&(!s||t.c.millisecond!==0)&&(l+=".",l+=me(t.c.millisecond,3))}return r&&(t.isOffsetFixed&&t.offset===0&&!i?l+="Z":t.o<0?(l+="-",l+=me(Math.trunc(-t.o/60)),l+=":",l+=me(Math.trunc(-t.o%60))):(l+="+",l+=me(Math.trunc(t.o/60)),l+=":",l+=me(Math.trunc(t.o%60)))),i&&(l+="["+t.zone.ianaName+"]"),l}const Po={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Bc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Hc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},An=["year","month","day","hour","minute","second","millisecond"],Gc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Yc=["year","ordinal","hour","minute","second","millisecond"];function Nn(t){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new Mi(t);return e}function ui(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Nn(t)}}function Jc(t){if(nn===void 0&&(nn=de.now()),t.type!=="iana")return t.offset(nn);const e=t.name;let n=zs.get(e);return n===void 0&&(n=t.offset(nn),zs.set(e,n)),n}function di(t,e){const n=lt(e.zone,de.defaultZone);if(!n.isValid)return V.invalid(tn(n));const s=ie.fromObject(e);let r,i;if(G(t.year))r=de.now();else{for(const l of An)G(t[l])&&(t[l]=Po[l]);const o=lo(t)||co(t);if(o)return V.invalid(o);const a=Jc(n);[r,i]=xn(t,a,n)}return new V({ts:r,zone:n,loc:s,o:i})}function fi(t,e,n){const s=G(n.round)?!0:n.round,r=G(n.rounding)?"trunc":n.rounding,i=(a,l)=>(a=nr(a,s||n.calendary?0:2,n.calendary?"round":r),e.loc.clone(n).relFormatter(n).format(a,l)),o=a=>n.calendary?e.hasSame(t,a)?0:e.startOf(a).diff(t.startOf(a),a).get(a):e.diff(t,a).get(a);if(n.unit)return i(o(n.unit),n.unit);for(const a of n.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(t>e?-0:0,n.units[n.units.length-1])}function hi(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}let nn;const zs=new Map;class V{constructor(e){const n=e.zone||de.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Ue("invalid input"):null)||(n.isValid?null:tn(n));this.ts=G(e.ts)?de.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[r,i]=[e.old.c,e.old.o];else{const a=dt(e.o)&&!e.old?e.o:n.offset(this.ts);r=Rn(this.ts,a),s=Number.isNaN(r.year)?new Ue("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=n,this.loc=e.loc||ie.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new V({})}static local(){const[e,n]=hi(arguments),[s,r,i,o,a,l,c]=n;return di({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,n]=hi(arguments),[s,r,i,o,a,l,c]=n;return e.zone=be.utcInstance,di({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,n={}){const s=Il(e)?e.valueOf():NaN;if(Number.isNaN(s))return V.invalid("invalid input");const r=lt(n.zone,de.defaultZone);return r.isValid?new V({ts:s,zone:r,loc:ie.fromObject(n)}):V.invalid(tn(r))}static fromMillis(e,n={}){if(dt(e))return e<-ai||e>ai?V.invalid("Timestamp out of range"):new V({ts:e,zone:lt(n.zone,de.defaultZone),loc:ie.fromObject(n)});throw new ve(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(dt(e))return new V({ts:e*1e3,zone:lt(n.zone,de.defaultZone),loc:ie.fromObject(n)});throw new ve("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const s=lt(n.zone,de.defaultZone);if(!s.isValid)return V.invalid(tn(s));const r=ie.fromObject(n),i=Gn(e,ui),{minDaysInFirstWeek:o,startOfWeek:a}=Jr(i,r),l=de.now(),c=G(n.specificOffset)?s.offset(l):n.specificOffset,d=!G(i.ordinal),p=!G(i.year),u=!G(i.month)||!G(i.day),f=p||u,g=i.weekYear||i.weekNumber;if((f||d)&&g)throw new Ct("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new Ct("Can't mix ordinal dates with month/day");const k=g||i.weekday&&!f;let y,E,w=Rn(l,c);k?(y=Gc,E=Bc,w=Bn(w,o,a)):d?(y=Yc,E=Hc,w=ms(w)):(y=An,E=Po);let A=!1;for(const h of y){const x=i[h];G(x)?A?i[h]=E[h]:i[h]=w[h]:A=!0}const O=k?Rl(i,o,a):d?Tl(i):lo(i),_=O||co(i);if(_)return V.invalid(_);const I=k?Gr(i,o,a):d?Yr(i):i,[j,v]=xn(I,c,s),U=new V({ts:j,zone:s,o:v,loc:r});return i.weekday&&f&&e.weekday!==U.weekday?V.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${U.toISO()}`):U.isValid?U:V.invalid(U.invalid)}static fromISO(e,n={}){const[s,r]=gc(e);return Nt(s,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[s,r]=wc(e);return Nt(s,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[s,r]=_c(e);return Nt(s,r,n,"HTTP",n)}static fromFormat(e,n,s={}){if(G(e)||G(n))throw new ve("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,d]=qc(o,e,n);return d?V.invalid(d):Nt(a,l,s,`format ${n}`,e,c)}static fromString(e,n,s={}){return V.fromFormat(e,n,s)}static fromSQL(e,n={}){const[s,r]=Tc(e);return Nt(s,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new ve("need to specify a reason the DateTime is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new Xa(s);return new V({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){const s=$o(e,ie.fromObject(n));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return Do(ke.parseFormat(e),ie.fromObject(n)).map(r=>r.val).join("")}static resetCache(){nn=void 0,zs.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?gs(this).weekYear:NaN}get weekNumber(){return this.isValid?gs(this).weekNumber:NaN}get weekday(){return this.isValid?gs(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ws(this).weekday:NaN}get localWeekNumber(){return this.isValid?ws(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ws(this).weekYear:NaN}get ordinal(){return this.isValid?ms(this.c).ordinal:NaN}get monthShort(){return this.isValid?kn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?kn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?kn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?kn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,n=6e4,s=ns(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*n),a=this.zone.offset(s-i*n);if(o===a)return[this];const l=s-o*n,c=s-a*n,d=Rn(l,o),p=Rn(c,a);return d.hour===p.hour&&d.minute===p.minute&&d.second===p.second&&d.millisecond===p.millisecond?[yt(this,{ts:l}),yt(this,{ts:c})]:[this]}get isInLeapYear(){return gn(this.year)}get daysInMonth(){return Hn(this.year,this.month)}get daysInYear(){return this.isValid?$t(this.year):NaN}get weeksInWeekYear(){return this.isValid?fn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?fn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:s,calendar:r}=ke.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:s,outputCalendar:r}}toUTC(e=0,n={}){return this.setZone(be.instance(e),n)}toLocal(){return this.setZone(de.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:s=!1}={}){if(e=lt(e,de.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(n||s){const i=e.offset(this.ts),o=this.toObject();[r]=xn(o,i,e)}return yt(this,{ts:r,zone:e})}else return V.invalid(tn(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:s});return yt(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=Gn(e,ui),{minDaysInFirstWeek:s,startOfWeek:r}=Jr(n,this.loc),i=!G(n.weekYear)||!G(n.weekNumber)||!G(n.weekday),o=!G(n.ordinal),a=!G(n.year),l=!G(n.month)||!G(n.day),c=a||l,d=n.weekYear||n.weekNumber;if((c||o)&&d)throw new Ct("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new Ct("Can't mix ordinal dates with month/day");let p;i?p=Gr({...Bn(this.c,s,r),...n},s,r):G(n.ordinal)?(p={...this.toObject(),...n},G(n.day)&&(p.day=Math.min(Hn(p.year,p.month),p.day))):p=Yr({...ms(this.c),...n});const[u,f]=xn(p,this.o,this.zone);return yt(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e);return yt(this,li(this,n))}minus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e).negate();return yt(this,li(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;const s={},r=ne.normalizeUnit(e);switch(r){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(r==="weeks")if(n){const i=this.loc.getStartOfWeek(),{weekday:o}=this;o<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(r==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?ke.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):ys}toLocaleString(e=qn,n={}){return this.isValid?ke.create(this.loc.clone(n),e).formatDateTime(this):ys}toLocaleParts(e={}){return this.isValid?ke.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=Nn(o);const a=e==="extended";let l=_s(this,a,o);return An.indexOf(o)>=3&&(l+="T"),l+=ci(this,a,n,s,r,i,o),l}toISODate({format:e="extended",precision:n="day"}={}){return this.isValid?_s(this,e==="extended",Nn(n)):null}toISOWeekDate(){return Tn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=Nn(a),(r&&An.indexOf(a)>=3?"T":"")+ci(this,o==="extended",n,e,s,i,a)):null}toRFC2822(){return Tn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Tn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?_s(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(n||e)&&(s&&(r+=" "),n?r+="z":e&&(r+="ZZ")),Tn(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():ys}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",s={}){if(!this.isValid||!e.isValid)return ne.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=xl(n).map(ne.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=Dc(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",n={}){return this.diff(V.now(),e,n)}until(e){return this.isValid?ue.fromDateTimes(this,e):this}hasSame(e,n,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n,s)<=r&&r<=i.endOf(n,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const n=e.base||V.fromObject({},{zone:this.zone}),s=e.padding?this<n?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),fi(n,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?fi(e.base||V.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(V.isDateTime))throw new ve("min requires all arguments be DateTimes");return Qr(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(V.isDateTime))throw new ve("max requires all arguments be DateTimes");return Qr(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return Fo(o,e,n)}static fromStringExplain(e,n,s={}){return V.fromFormatExplain(e,n,s)}static buildFormatParser(e,n={}){const{locale:s=null,numberingSystem:r=null}=n,i=ie.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new Co(i,e)}static fromFormatParser(e,n,s={}){if(G(e)||G(n))throw new ve("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(n.locale))throw new ve(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${n.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=n.explainFromTokens(e);return d?V.invalid(d):Nt(a,l,s,`format ${n.format}`,e,c)}static get DATE_SHORT(){return qn}static get DATE_MED(){return Pi}static get DATE_MED_WITH_WEEKDAY(){return nl}static get DATE_FULL(){return Li}static get DATE_HUGE(){return Vi}static get TIME_SIMPLE(){return Ui}static get TIME_WITH_SECONDS(){return Wi}static get TIME_WITH_SHORT_OFFSET(){return ji}static get TIME_WITH_LONG_OFFSET(){return Zi}static get TIME_24_SIMPLE(){return zi}static get TIME_24_WITH_SECONDS(){return qi}static get TIME_24_WITH_SHORT_OFFSET(){return Bi}static get TIME_24_WITH_LONG_OFFSET(){return Hi}static get DATETIME_SHORT(){return Gi}static get DATETIME_SHORT_WITH_SECONDS(){return Yi}static get DATETIME_MED(){return Ji}static get DATETIME_MED_WITH_SECONDS(){return Qi}static get DATETIME_MED_WITH_WEEKDAY(){return sl}static get DATETIME_FULL(){return Ki}static get DATETIME_FULL_WITH_SECONDS(){return Xi}static get DATETIME_HUGE(){return eo}static get DATETIME_HUGE_WITH_SECONDS(){return to}}function Qt(t){if(V.isDateTime(t))return t;if(t&&t.valueOf&&dt(t.valueOf()))return V.fromJSDate(t);if(t&&typeof t=="object")return V.fromObject(t);throw new ve(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const Qc=(t,e)=>{const n={};if(t.includeFields){const s=e.collections[t.collection];if(!s)return pn(Ee());t.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?n[r]=Lo(i)?.nullable():n[r]=Ee()})}return qe({Collection_Path:Tt(Ie()),...n})},Kc=(t,e,n,s)=>{let r=qe({}).catchall(Qc(t,e)),i;if(!s&&n){const o=We(t,n);i=Kt(o.admin?.skipFormRequiredValidation)}return(!t.required||i)&&(r=r.optional()),r},Xc=()=>Ee().refine(t=>t===null||t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Must be a valid date"}),Lo=(t,e,n)=>{let s;const r=`${Kt(t.description)}
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("lodash/isEqual.js"),ta=require("lodash/merge.js"),na=require("lodash/set.js"),pe=require("lodash/cloneDeep.js"),vt=require("firebase-admin/app"),oe=require("firebase-admin/firestore"),Ei=require("node:url"),sa=require("cross-spawn"),vi=require("firebase-admin/database"),bt=require("firebase-admin/auth"),Qn=t=>!!t&&!Array.isArray(t),cn=(t,e)=>t.access?Qn(t.access)?!1:t.access.includes(e):!0,ra=(t,e)=>{if(Qn(t.access))return e.fieldAccessGroups?.[t.access.group]},qs=t=>{const e={};return Object.keys(t.fieldAccessGroups||{}).forEach(n=>{e[n]=[]}),t.fields.forEach(n=>{if(Qn(n.access)){const{group:s}=n.access;e[s]&&e[s].push(n)}}),e},Kn=(t,e,n,s)=>{if(!n)return!0;if(n.Role&&!t.applicableRoles.includes(n.Role))return!1;const r=n.collections?.[e],i=[];if(t.collectionAuth!==void 0&&i.push(!!r?.auth===t.collectionAuth),t.roles&&i.push(!!n.Role&&t.roles.includes(n.Role)),t.claims&&i.push(Object.entries(t.claims).every(([o,a])=>{let l=s?.[o];return l===void 0&&o==="role"&&(l=n.Role),Array.isArray(a)?a.some(c=>c===l):l===a})),t.restrictions){const{recordOwner:o,recordUser:a,recordProperty:l,restrictEntities:c}=t.restrictions;i.push((o===void 0||!!r?.recordOwner?.active===o)&&(a===void 0||!!r?.recordUser?.active===a)&&(l===void 0||!!r?.recordProperty?.active===l)&&(c===void 0||!!r?.restrictEntities===c))}return i.length===0?!1:t.match==="all"?i.every(Boolean):i.some(Boolean)},ia=(t,e,n,s)=>{const r=ra(t,e);return r?Kn(r,e.labels.collection,n,s):!1},Xn=t=>!!t.auth,xe=(t,e)=>{if(e?.operations)return e.operations.includes(t)},He=(t,e,n,s)=>e?e.Role?Qn(t.access)?!n||!s?!1:ia(t,n,e,s):t.access?.includes(e.Role):!1:!0,Oi=(t,e,n,s)=>t===!0?!1:Array.isArray(t)?t.includes(e.Role):typeof t=="object"&&t!==null?!n||!s?!1:Kn(t,n,e,s):!0,oa=(t,e,n,s)=>e?e.Role?Oi(t.restrictCreate,e,n,s):!1:!0,ki=(t,e,n,s)=>e?e.Role?Oi(t.restrictUpdate,e,n,s):!1:!0,Or=(t,e,n,s)=>{const{labels:r}=t;return n.collections&&xe("Update",n.collections[r.collection])&&(!e.access||He(e,n,t,s))&&ki(e,n,r.collection,s)&&!(t.auth&&!n.collections?.[r.collection].auth&&["Enabled","Role","Name","Email","Photo_URL"].includes(e.name))},L=(t,e)=>t.filter(n=>n.name===e)[0],X=t=>["OneToOne","OneToMany","ManyToOne","ManyToMany"].includes(t.type),bi=(t,e)=>{const n={Record_Owner:"recordOwner",Record_User:"recordUser",Record_Property:"recordProperty"},s=[],{labels:r,access:i}=t,{attributeRestrictions:o}=i,a=e.collections?.[r.collection];return o?.forEach(l=>{"roles"in l&&l.roles.forEach(c=>{const d=a?.[n[l.type]];c.role===e.Role&&(!c.assignable||d?.active)&&s.push(l)})}),s},Bs=(t,e)=>{const n=[],{labels:s,access:r}=t,{entityRestrictions:i}=r,o=e.collections?.[s.collection];return i?.restrictions?.forEach(a=>{"roles"in a&&a.roles.forEach(l=>{l.role===e.Role&&(!i.assignable?.includes(e.Role)||o?.restrictEntities)&&n.push(a)})}),n},Ri=(t,e,n)=>{const s=[],{access:r}=t,{entityRestrictions:i}=r;return i?.parentFilters?.forEach(o=>{if(!o.roles.some(f=>f.role===n.Role))return;const a=o.collectionField,l=L(t.fields,a);if(!X(l))throw new Error("PERMISSION_DENIED");const c=n.collections?.[l.collection],p=e.collections[l.collection].access.entityRestrictions;if(!p)throw new Error("PERMISSION_DENIED");const u=p.restrictions?.find(f=>f.type===o.type&&f.roles.some(g=>g.role===n.Role));if(!u)throw new Error("PERMISSION_DENIED");u.roles.forEach(f=>{f.role===n.Role&&(!p.assignable?.includes(n.Role)||c?.restrictEntities)&&s.push({parentFilter:o,parentRestriction:u})})}),s},Ti=(t,e,n,s)=>{const r=Object.values(e.collections),{labels:i}=t,o=[];for(const a of r){const{fields:l}=a;for(const c of l)if(!(c.access&&!He(c,n,a,s))&&n.Role&&X(c)&&c.collection===i.collection&&c.dependencyFields)for(const d of c.dependencyFields)!o.find(u=>u.field===d.field)&&d.roles.includes(n.Role)&&o.push(d)}return o},aa=(t,e,n,s,r,i,o)=>{const{fields:a}=e,l=r.collections?.[e.labels.collection];let c=!0;if(!l){c=!1;return}const d=bi(e,r),p=Bs(e,r),u=Ri(e,n,r);d?.filter(_=>_.type==="Record_Owner").forEach(_=>{"operations"in _&&_.operations&&!_.operations.includes(t)||i.Created_By!==s&&(c=!1)}),d?.filter(_=>_.type==="Record_User").forEach(_=>{if("operations"in _&&_.operations&&!_.operations.includes(t))return;const I=L(a,_.collectionField);i[`${I.name}_Array`]?.includes(r.Doc_ID)||(c=!1)}),d?.filter(_=>_.type==="Record_Property").forEach(_=>{if("operations"in _&&_.operations&&!_.operations.includes(t))return;const I=L(a,_.propertyField),j=_.roles.find(v=>v.role===r.Role);I.type==="Array"?j.values?.some(v=>i[I.name].includes(v))||(c=!1):j.values?.includes(i[I.name])||(c=!1)});let f=!0,g=!1;p?.filter(_=>_.type==="Individual").forEach(()=>{g=!0,l?.individualEntities?.includes(i.id)||(f=!1)});let k=!0,y=!1;if(p?.filter(_=>_.type==="Parent").forEach(_=>{y=!0;const I=L(a,_.collectionField);l?.parentEntities?.some(j=>i[`${I.name}_Array`].includes(j))||(k=!1)}),p?.filter(_=>_.type==="Parent_Property").forEach(_=>{y=!0;const I=L(a,_.collectionField),j=L(a,_.propertyField);Object.entries(l?.parentPropertyEntities||{}).some(v=>{const[U,h]=v;return U===i[j.name]&&i[`${I.name}_Array`].some(x=>h.includes(x))})||(k=!1)}),g&&y){if(!(f||k)){c=!1;return}}else if(!f||!k){c=!1;return}let E=!0,w=!1;u?.filter(_=>_.parentFilter.type==="Individual").forEach(_=>{w=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=r.collections?.[j.collection];if(!v){c=!1;return}v.individualEntities?.some(U=>i[`${j.name}_Array`].includes(U))||(E=!1)});let A=!0,O=!1;if(u?.filter(_=>_.parentFilter.type==="Parent").forEach(_=>{O=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=L(a,I.parentCollectionField),U=r.collections?.[j.collection];if(!U){c=!1;return}U.parentEntities?.some(h=>i[`${v.name}_Array`].includes(h))||(A=!1)}),u?.filter(_=>_.parentFilter.type==="Parent_Property").forEach(_=>{O=!0;const{parentFilter:I}=_,j=L(a,I.collectionField),v=L(a,I.parentPropertyField),U=L(a,I.parentCollectionField),h=r.collections?.[j.collection];if(!h){c=!1;return}Object.entries(h.parentPropertyEntities||{}).some(x=>{const[R,q]=x;return R===i[v.name]&&i[`${U.name}_Array`].some(Z=>q.includes(Z))})||(A=!1)}),w&&O){if(!(E||A)){c=!1;return}}else if(!E||!A){c=!1;return}return c},ft=(t,e,n,s,r,i)=>{const{labels:o}=e,a=r.collections?.[o.collection];let l=!0;if(!a||!r.Role)return l=!1,l;xe(t,a)||(l=!1);const d=Bs(e,r)?.filter(p=>p.type==="Individual").length>0;return t==="Create"&&d&&(l=!1),aa(t,e,n,s,r,i)||(l=!1),l},Si=(t,e,n)=>{const{labels:s}=t,r=[];for(const i of Object.values(e.collections));return r},la=(t,e)=>{let n=!0,s="";return Object.keys(e).forEach(r=>{if(!["Doc_ID","Role","Collection","Enabled","collections"].includes(r)){n=!1,s="Permissions object must contain Doc_ID, Role, Collection, Enabled, and collections";return}}),e.collections&&(Object.keys(e.collections).forEach(r=>{if(!Object.keys(t.collections).includes(r)){s=`Collection ${r} not found in schema`,n=!1;return}const i=t.collections[r],o=e.collections?.[r];if(o){if(!o.operations){s=`Collection ${r} does not have operations`,n=!1;return}if(!Object.keys(o).every(a=>["operations","auth","restrictEntities","individualEntities","parentEntities","parentPropertyEntities","recordProperty","recordUser","recordOwner"].includes(a))){s=`Collection ${r} has invalid properties`,n=!1;return}if(!o.operations.every(a=>["Read","Create","Update","Delete"].includes(a))){s=`Collection ${r} has invalid operations`,n=!1;return}if(o.auth&&(typeof o.auth!="boolean"||!i.auth)){s=`Collection ${r} has invalid auth value`,n=!1;return}if(o.restrictEntities&&!i.access.entityRestrictions?.restrictions){s=`Collection ${r} has invalid restrictEntities value`,n=!1;return}Object.entries(o).forEach(([a,l])=>{if(a!=="operations"&&a!=="auth"&&a!=="restrictEntities"){let c;a==="recordOwner"?c="Record_Owner":a==="recordUser"?c="Record_User":a==="recordProperty"?c="Record_Property":a==="individualEntities"?c="Individual":a==="parentEntities"?c="Parent":a==="parentPropertyEntities"&&(c="Parent_Property");const d=i.access.attributeRestrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role)),p=i.access.entityRestrictions?.restrictions?.filter(u=>u.type===c&&u.roles.some(f=>f.role===e.Role));if(i.access.entityRestrictions?.assignable&&!(Array.isArray(i.access.entityRestrictions.assignable)&&i.access.entityRestrictions.assignable.every(u=>t.config.roles.includes(u)))){s=`Collection ${r} has invalid entity restrictions assignable value`,n=!1;return}if(d?.length||p?.length){if(a==="Record_Owner"||a==="Record_User"||a==="Record_Property"){const u=Object.keys(l);if(u.length!==1||u[0]!=="active"||typeof l.active!="boolean"){s=`Collection ${r} has invalid attribute restriction value`,n=!1;return}}if(a==="Individual"&&!Array.isArray(l)){s=`Collection ${r} has invalid individual entities value`,n=!1;return}if(a==="Parent"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&Array.isArray(l[u[0]]))){s=`Collection ${r} has invalid parent entities value`,n=!1;return}}if(a==="Parent_Property"){const u=Object.keys(l);if(!(u.length===1&&Object.keys(t.collections).includes(u[0])&&typeof l[u[0]]=="object"&&l[u[0]]!==null)){s=`Collection ${r} has invalid parent property entities value`,n=!1;return}}}else{s=`Collection ${r} has invalid restriction type ${a}`,n=!1;return}}})}}),s&&console.error(`PERMISSION_DENIED: ${s}`)),n},ca=(t,e,n)=>{let s=!0,r="";Object.values(t.collections).filter(i=>i.auth).forEach(i=>{const o=e.collections?.[i.labels.collection],a=i.access.auth,l=e.Role;if(o?.auth&&!a?.roles.includes(l)){r="Record cannot have auth access to collection",s=!1;return}if(a?.roles.includes(l)&&!a.assignable?.includes(l)&&!o?.auth){r="Record is missing required auth access to collection",s=!1;return}});for(const i of Object.values(t.collections)){const{labels:o,access:a,fields:l}=i,{operations:c,attributeRestrictions:d,entityRestrictions:p}=a,u=c.assignable,f=e.collections?.[o.collection],g=["read","create","update","delete"];if(u!==!0&&!(typeof u=="object"&&u.includes(n))?g.forEach(y=>{const E=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const w=!!a.operations[y]?.includes(n),A=!!f?.operations.includes(E);if(!w&&A){r=`Collection ${o.collection} has excess ${y} operation for role ${n}`,s=!1;return}if(w&&!A){r=`Collection ${o.collection} has missing ${y} operation for role ${n}`,s=!1;return}}}):g.forEach(y=>{const E=y.charAt(0).toUpperCase()+y.slice(1);if(y!=="assignable"){const w=!!a.operations[y]?.includes(n),A=!!f?.operations.includes(E);if(!w&&A){r=`Collection ${o.collection} has excess ${y} operation for role ${n}`,s=!1;return}}}),!d&&!p||(d?.forEach(y=>{for(const E of y.roles)if(E.role===n&&!E.assignable){if(y.type==="Record_Owner"&&!e.collections?.[o.collection]?.recordOwner?.active){r=`Collection ${o.collection} is missing Record_Owner restriction for role ${n}`,s=!1;return}if(y.type==="Record_User"&&!e.collections?.[o.collection]?.recordUser?.active){r=`Collection ${o.collection} is missing Record_User restriction for role ${n}`,s=!1;return}if(y.type==="Record_Property"&&!e.collections?.[o.collection]?.recordProperty?.active){r=`Collection ${o.collection} is missing Record_Property restriction for role ${n}`,s=!1;return}}}),p?.assignable?.includes(n)))continue;let k=!1;if(p?.restrictions?.forEach(y=>{for(const E of y.roles)if(E.role===n){if(k=!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 w=L(l,y.collectionField);if(!X(w)){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 w=L(l,y.collectionField);if(!X(w)){s=!1;return}if(!e.collections?.[o.collection]?.parentPropertyEntities?.[w.collection]){r=`Collection ${o.collection} is missing parent property entities`,s=!1;return}}}}),k&&!e.collections?.[o.collection]?.restrictEntities){r=`Collection ${o.collection} must have restrictEntities set to true`,s=!1;return}}return r&&console.error(`PERMISSION_DENIED: ${r}`),s},ua=(t,e,n,s,r,i,o,a,l)=>{const{access:c}=e,{permissionWriteRestrictions:d}=c;let p=!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}`,p=!1,p):t==="update"&&o.User_ID&&f?.length&&!f.some(g=>g.recordRole===a)?(u=`User ${s} does not have write access to record with role ${r}`,p=!1,p):(d?.forEach(g=>{s===g.userRole&&g.recordRole===r&&t!=="delete"&&i&&Object.keys(n.collections).forEach(k=>{const y=i.collections?.[k],E=l?.collections?.[k];if(!(t==="update"&&Xe(y,E))&&y){const w=g.collections.some(A=>A.collection===k);if(w){if(w){const A=g.collections.find(_=>_.collection===k);if(!(y.operations.every(_=>A.operations.includes(_))||t==="update"&&Xe(y.operations,E?.operations))){u=`User ${s} does not have write access to all included operations for collection ${k}`,p=!1;return}if(!A.auth&&y.auth&&!(t==="update"&&Xe(y.auth,E?.auth))){u=`User ${s} does not have write access to auth for collection ${k}`,p=!1;return}const O={recordOwner:"Record_Owner",recordUser:"Record_User",recordProperty:"Record_Property"};if(Object.keys(O).forEach(_=>{const I=O[_];if(A.attributeRestrictions?.includes(I)&&!(y[_]?.active||t==="update"&&Xe(y[_],E?.[_]))){u=`User ${s} does not have write access to attribute restriction ${_} for collection ${k}`,p=!1;return}}),A.restrictEntities&&!y.restrictEntities&&!(t==="update"&&Xe(y.restrictEntities,E?.restrictEntities))){u=`User ${s} does not have write access to restrictEntities for collection ${k}`,p=!1;return}}}else{u=`User ${s} does not have write access to collection ${k}`,p=!1;return}}})}),u&&console.error(`PERMISSION_DENIED: ${u}`),p)},da=(t,e,n,s)=>{let r=!0,i="";return Object.values(t.collections).forEach(o=>{const a=n.collections?.[o.labels.collection],l=s?.collections?.[o.labels.collection],c=e?.collections?.[o.labels.collection];if(a?.auth&&!l?.auth&&!Xn(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)&&(!xe("Read",c)||!xe(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},Hs=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:p}=s;let u=!0,f="";if(!e.Role)return f="Record does not have a role",u=!1,u;if(t==="update"&&!c)return f="Original record is required for update operations",u=!1,u;if(t==="update"&&i&&d==="update"&&a&&!l)return f="Original permissions are required for this operation",u=!1,u;if(i){if(!o?.Role)return f="Current user does not have a role",u=!1,u;if(!ua(t,s,r,o.Role,e.Role,a,c,c?.Role,l))return u=!1,u;if(t==="update"&&d!=="delete"&&c?.User_ID&&e.User_ID!==c.User_ID)return f="User ID does not match original user ID",u=!1,u;if(t==="update"&&c&&c.User_ID&&i===c.User_ID&&(a||e.Role!==c.Role||e.Enabled!==void 0&&e.Enabled!==c.Enabled))return f="User cannot update their own record",u=!1,u;if(t==="delete"&&i===e.User_ID)return f="User cannot delete their own record",u=!1,u}return t==="delete"||d==="delete"||!a?u:a.Role?(la(r,a)||(u=!1),a.Collection&&a.Collection!==p.collection?(f="Permissions collection does not match record collection",u=!1,u):a.Role!==e.Role?(f="Permissions role does not match record role",u=!1,u):a.Enabled!==void 0&&!!a.Enabled!=!!e.Enabled?(f="Permissions enabled state does not match record enabled state",u=!1,u):a.Doc_ID&&a.Doc_ID!==n?(f="Permissions doc ID does not match record doc ID",u=!1,u):!ca(r,a,a.Role)||i&&o&&l&&!da(r,o,a,l)?(u=!1,u):(f&&console.error(`PERMISSION_DENIED: ${f}`),u)):(f="Permissions do not have a role",u=!1,u)},kr=(t,e,n,s,r,i,o,a)=>{const{labels:l,fields:c}=n,d=i?.collections?.[l.collection];let p=!0;if(r&&!d)throw new Error("PERMISSION_DENIED");r&&!xe("Create",d)&&(p=!1),r&&!ft("Create",n,s,r,i,t)&&(p=!1),n.auth&&o&&(r&&!Xn(d)&&(p=!1),Hs("create",t,e,n,s,r,i,o)||(p=!1));for(const u of c){const f=t[u.name];u.access&&!He(u,i,n,a)&&f!==void 0&&(p=!1),f!==void 0&&!oa(u,i,l.collection,a)&&(p=!1)}if(!p)throw new Error("PERMISSION_DENIED")},be=t=>t&&(t._methodName==="deleteField"||t.constructor.name==="DeleteTransform"),et=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(be(t[e])?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&et(t[e]))},br=(t,e,n,s,r,i,o,a,l,c,d)=>{const{labels:p,fields:u}=s,f=o?.collections?.[p.collection],g={...e,...t};et(g);let k=!0,y="";if(i&&!f)throw new Error("PERMISSION_DENIED");i&&!xe("Update",f)&&(k=!1,y="Authenticated user does not have Update access to this collection"),i&&(!ft("Update",s,r,i,o,e)||!ft("Update",s,r,i,o,g))&&(k=!1,y="Authenticated user does not have Update access to this document"),i&&s.softDelete&&g[s.softDelete.archivedField]!==e[s.softDelete.archivedField]&&!xe("Delete",f)&&(k=!1,y="Authenticated user does not have Delete or Restore access to this document"),a&&(i&&!Xn(f)&&(k=!1,y="Authenticated user does not have Auth access for this collection"),Hs("update",g,n,s,r,i,o,l,c,e,a)||(y="Authenticated user does not have sufficient write access for this record",k=!1));for(const E of u){const w=t[E.name];E.access&&!He(E,o,s,d)&&w!==void 0&&(y=`Authenticated user does not have access to field ${E.name}`,k=!1),w!==void 0&&!ki(E,o,p.collection,d)&&(y=`Authenticated user does not have Update access to field ${E.name}`,k=!1)}if(!k)throw y&&console.error(`PERMISSION_DENIED: ${y}`),new Error("PERMISSION_DENIED")},fa=(t,e,n,s,r,i)=>{const{labels:o}=n,a=i.collections?.[o.collection];let l=!0;if(!a)throw new Error("PERMISSION_DENIED");if(xe("Delete",a)||(l=!1),ft("Delete",n,s,r,i,t)||(l=!1),n.auth&&t.User_ID&&(Xn(a)||(l=!1),Hs("delete",t,e,n,s,r,i)||(l=!1)),!l)throw new Error("PERMISSION_DENIED")},ha=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(xe("Read",o)||(a=!1),ft("Read",e,n,s,r,t)||(a=!1),!a)throw new Error("PERMISSION_DENIED")},ma=async(t,e,n,s,r)=>{const{labels:i}=e,o=r.collections?.[i.collection];let a=!0;if(!o){a=!1;return}if(xe("Read",o)||(a=!1),t.forEach(l=>{ft("Read",e,n,s,r,l)||(a=!1)}),!a)throw new Error("PERMISSION_DENIED")},pa=(t,e,n)=>{const{access:s}=t;return s.operations[n]?.includes(e)},ya=(t,e,n)=>{const{access:s}=e,{entityRestrictions:r}=s;if(r?.restrictions){for(const i of r.restrictions)if(i.roles?.some(o=>o.role===t)&&!("singleQuery"in i&&i.singleQuery))return`${i.type} entity restriction`}if(r?.parentFilters)for(const i of r.parentFilters){if(!i.roles.some(c=>c.role===t))continue;const o=L(e.fields,i.collectionField);if(!X(o))throw new Error("PERMISSION_DENIED");const l=n.collections[o.collection].access.entityRestrictions?.restrictions?.find(c=>c.type===i.type&&c.roles.some(d=>d.role===t));if(!l)throw new Error("PERMISSION_DENIED");if(l.type!==i.type)throw new Error("PERMISSION_DENIED");if(!("singleQuery"in l&&l.singleQuery))return`${i.type} parent filter`}return!0},ga=(t,e,n,s,r)=>{const i={};for(const o of t){const l=e[o].default({sdk:n,utils:s,context:r});for(const c in l)c==="custom"||c==="admin"||c==="fields"||delete l[c];for(const c of l.fields)for(const d in c)d==="custom"||d==="admin"||d==="name"||d==="formula"||delete c[d];i[o]=l}return i},We=(t,e)=>e.fields.filter(n=>n.name===t.name)[0],os={global:{},collections:{}},Kt=(t,e)=>t&&typeof t=="function"?e?t(...e):t():t,ae=async(t,e)=>{let n=t;return t&&(typeof t=="function"||typeof t.then=="function")&&(e?n=await t(...e):n=await t()),n},wa=async(t,e,n,s)=>{for(const d of e)if(d==="__proto__"||d==="constructor"||d==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");let r=os,i=!0;for(const d of e){if(d===void 0||r[d]===void 0){i=!1;break}r=r[d]}if(r&&i&&!s)return r;let o,a=t,l=!0;e[0]==="collections"?o=e.slice(2):o=e.slice(1);for(const d of o){if(d===void 0||a[d]===void 0){l=!1;break}a=a[d]}let c;if(l&&(c=await ae(a,n)),c){let d=os;const p={};for(let u=0;u<e.length;u++){const f=e[u];if(f!==void 0){if(f==="__proto__"||f==="constructor"||f==="prototype")throw new Error("Invalid config path: prototype pollution keys are not allowed");u===e.length-1?na(p,e.join("."),c):(d[f]||={},d=d[f])}}ta(os,p)}return c},mt=(t,e,n)=>{const s=Object.values(n.collections),{labels:r}=e;let i=!1;for(const o of s){const{fields:a}=o;for(const l of a)if(X(l)&&l.collection===r.collection&&l.dependencyFields)for(const c of l.dependencyFields)c.field===t.name&&(i=!0)}return i},Ii=(t,e)=>{const n=Object.values(e.collections),{labels:s}=t,r={};return n.forEach(i=>{const{labels:o,fields:a}=i;a.forEach(l=>{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},as=t=>JSON.stringify(t.map(e=>e.name)),ct=["id","Collection_Path","Last_Write_At","Last_Save_At","Last_Write_By","Last_Write_App","Last_Write_Connection_Status","Last_Write_Version","Created_At","Saved_At","Created_By"],mn=()=>ct.map(t=>{let e="",n;switch(t){case"id":e="String";break;case"Collection_Path":e="Array";break;case"Created_At":e="Timestamp";break;case"Saved_At":e="Timestamp";break;case"Created_By":e="String";break;case"Last_Write_At":e="Timestamp";break;case"Last_Save_At":e="Timestamp";break;case"Last_Write_By":e="String";break;case"Last_Write_App":e="String";break;case"Last_Write_Connection_Status":e="String",n=["Online","Offline"];break;case"Last_Write_Version":e="Number";break}const s={name:t,type:e,required:!0};return n&&(s.values=n),s}),Gs=(t,e)=>{const n=[],{access:s,fields:r}=t,{attributeRestrictions:i,entityRestrictions:o}=s,a=mn();return i&&i.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Record_Owner":n.push(L(a,"Created_By"));break;case"Record_User":n.push(L(r,l.collectionField));break;case"Record_Property":n.push(L(r,l.propertyField));break}}),o&&(o.restrictions?.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(L(a,"id"));break;case"Parent":n.push(L(r,l.collectionField));break;case"Parent_Property":n.push(L(r,l.collectionField)),n.push(L(r,l.propertyField));break}}),o.parentFilters&&o.parentFilters.forEach(l=>{if(l.roles.some(c=>c.role===e))switch(l.type){case"Individual":n.push(L(r,l.collectionField));break;case"Parent":n.push(L(r,l.parentCollectionField));break;case"Parent_Property":n.push(L(r,l.parentCollectionField)),n.push(L(r,l.parentPropertyField));break}})),[...new Set(n)]},_a=(t,e)=>{const n=[],{fields:s,roleSystemFields:r,preloadCache:i,queries:o}=t,a=mn();return n.push({name:"Collection_Path",type:"Array",required:!0}),s.forEach(c=>{cn(c,e)&&n.push(c)}),r?.filter(c=>(!c.roles||c.roles.includes(e))&&c.field!=="Collection_Path").forEach(c=>{n.push(L(a,c.field))}),i?.range&&i.range.fields.forEach(c=>{ct.includes(c)&&n.push(L(a,c))}),o?.forEach(c=>{const d=L(s.concat(a),c.field);(!c.roles||c.roles.includes(e))&&d&&cn(d,e)&&ct.includes(c.field)&&n.push(L(a,c.field))}),Gs(t,e).forEach(c=>{ct.includes(c.name)&&n.push(L(a,c.name))}),[...new Set(n)]},Ea=(t,e,n)=>{const s=[],{fields:r,preloadCache:i}=e,o=mn(),a=new Set,l=Ii(e,n);return Object.entries(l).map(([c,d])=>{t.name===c&&Object.values(d).forEach(p=>{p.forEach(u=>{a.add(u)})})}),a.forEach(c=>{s.push(...Gs(e,c))}),i?.range&&i.range.fields.forEach(c=>{ct.includes(c)?s.push(L(o,c)):Array.from(a).some(d=>cn(L(r,c),d))&&s.push(L(r,c))}),[...new Set(s)]},En=(t,e,n)=>{const s=[],{fields:r,softDelete:i}=e;s.push({name:"Collection_Path",type:"Array",required:!0}),s.push({name:"id",type:"String",required:!0});const o=[],a=Ii(e,n);if(Object.values(a).forEach(l=>{Object.keys(l).forEach(c=>{n.collections[c].fields.forEach(p=>{X(p)&&p.collection===e.labels.collection&&p.dependencyFields?.some(u=>u.field===t.name)&&p.constraints&&p.constraints.forEach(u=>{o.push(u[0])})})})}),o.forEach(l=>{s.push(L(r,l))}),i){const l=L(r,i.archivedField);l&&s.push(l)}return s.push(...Ea(t,e,n)),[...new Set(s)]},va=(t,e,n)=>{const s=e.fieldAccessGroups?.[t]?.applicableRoles||[];return n.roles.filter(r=>s.includes(r))},on=(t,e)=>`${t}-${e}`,vn=(t,e,n)=>{if(!e.fieldAccessGroups?.[t])return[];const s=va(t,e,n);if(s.length===0)return[];const r=[],{fields:i,softDelete:o,preloadCache:a,roleSystemFields:l,queries:c}=e,d=mn();r.push({name:"Collection_Path",type:"Array",required:!0}),r.push({name:"id",type:"String",required:!0});const p=qs(e)[t]||[];if(r.push(...p),o){const u=L(i,o.archivedField);u&&!p.includes(u)&&r.push(u)}a?.range&&a.range.fields.forEach(u=>{ct.includes(u)?r.push(L(d,u)):s.some(f=>cn(L(i,u),f))&&r.push(L(i,u))}),l?.filter(u=>u.field!=="Collection_Path"&&s.some(f=>!u.roles||u.roles.includes(f))).forEach(u=>{r.push(L(d,u.field))}),c?.forEach(u=>{const f=L(i.concat(d),u.field);f&&s.some(g=>(!u.roles||u.roles.includes(g))&&cn(f,g))&&r.push(f)});for(const u of s)r.push(...Gs(e,u));return[...new Set(r)]},xi=(t,e)=>{const{preloadCache:n}=t,s=new Set;for(const r of e.config.roles){if(!pa(t,r,"read"))continue;const i=_a(t,r);let o=!1;if(s.size===0)s.add({key:"1",roles:[r],fields:i}),o=!0;else for(const a of s)i.length===a.fields.length&&i.every(l=>a.fields.some(c=>c.name===l.name))&&!!n?.roles.includes(r)==!!a.roles.every(l=>n?.roles.includes(l))&&(a.roles.push(r),o=!0);o||s.add({key:(s.size+1).toString(),roles:[r],fields:i})}return s},Ai=(t,e,n)=>{const s=xi(e,n);for(const r of s.values())if(r.roles.includes(t))return r},Oa=(t,e)=>{const{fields:n}=e,s=mn(),r=[];return[...n,...s.filter(o=>o.name!=="id")].forEach(o=>{t?.fields.some(a=>a.name===o.name)||r.push(o)}),r},Ys=(t,e,n)=>{const s={};return Object.values(t.collections).forEach(r=>{const i=xi(r,t),o=Array.from(i);o.map(a=>(a.fields.forEach(l=>{}),a)),s[r.labels.collection]=new Set(o)}),s},$n=t=>({Last_Write_At:t.Last_Write_At,Last_Write_By:t.Last_Write_By,Last_Write_Connection_Status:t.Last_Write_Connection_Status,Last_Write_Version:t.Last_Write_Version,Last_Write_App:t.Last_Write_App,Last_Save_At:t.Last_Save_At}),ls=async(t,e,n)=>{if(e){const s=await ae(e,[n]);if(s===!1)throw new Error(`CANCELLED: Operation cancelled by ${t}`);return s}};async function ce(t,e,n,s){const r=await ls(t,n.custom?.[t],s);for(const i of n.fields)await ls(t,i.custom?.[t],s);if(t!=="setEmbedding"&&(await ls(t,e?.[t],s),t==="postWriteError"))return r}const Js=(t,e,n,s,r,i,o,a,l,c)=>(t==="create"&&(n.Collection_Path=e,n.Created_At=a,n.Saved_At=l,n.Created_By=o||"System"),n.Last_Write_App=r,n.Last_Write_At=a,n.Last_Save_At=l,n.Last_Write_By=o||"System",n.Last_Write_Connection_Status=i,n.Last_Write_Version=s.version,n),gt=(t,e)=>{const{access:n,queries:s}=t,{serverReadOnly:r}=n,i=new Set;if(s)for(const o of s){const a=L(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},Rt=(t,e)=>{const{access:n,recordTitleField:s}=t,{serverReadOnly:r}=n,i=new Set;return e.forEach(o=>{(s===o.name||o.sorting&&(typeof o.sorting=="boolean"||!o.sorting.roles?.every(a=>r?.includes(a))))&&o.type==="String"&&i.add(o)}),i},ka=(t,e)=>{const n={Collection_Path:t.Collection_Path};if(t.deleted!==void 0&&(n.deleted=t.deleted),e)for(const s of e)t[s]!==void 0&&(n[s]=t[s]);return n},wt=(t,e,n)=>{const{fields:s}=t;s.forEach(i=>{if(X(i))if(e[i.name]){if(be(e[i.name]))e[`${i.name}_Array`]=e[i.name];else if(Object.keys(e[i.name]).forEach(o=>{const a=e[i.name][o];e[i.name][o]=ka(a,i.includeFields)}),e[`${i.name}_Array`]=Object.keys(e[i.name]),i.includeFields)for(const o of i.includeFields){const a=n.collections[i.collection],l=L(a.fields,o);Rt(a,[l]).size===1&&Object.keys(e[i.name]).forEach(d=>{e[i.name][d][o]?e[i.name][d][`${o}_Lowercase`]=e[i.name][d][o].toLowerCase():delete e[i.name][d][`${o}_Lowercase`]})}}else delete e[`${i.name}_Array`],delete e[`${i.name}_Single`]}),gt(t,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}}}})},Mn=(t,e)=>{Rt(t,t.fields).forEach(s=>{e[s.name]?e[`${s.name}_Lowercase`]=e[s.name].toLowerCase():delete e[`${s.name}_Lowercase`]})},ba=async(t,e,n,s,r)=>{const{fields:i}=e;for(const o of n.fields){const a=L(i,o.name);o.custom?.initialValue!==void 0&&(!a.access||He(a,s,e,r||{}))&&(t[o.name]=await ae(o.custom.initialValue,[t]),Rt(e,[a]).size===1&&(t[`${o.name}_Lowercase`]=t[o.name].toLowerCase()))}for(const o of i)(!o.access||He(o,s,e,r||{}))&&("autoIncrement"in o&&o.autoIncrement&&!t[o.name]&&(t[o.name]="Pending"),!X(o)&&o.nullable&&t[o.name]===void 0&&(t[o.name]=null))};var se;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{const i={};for(const o of r)i[o]=o;return i},t.getValidEnumValues=r=>{const i=t.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of i)o[a]=r[a];return t.objectValues(o)},t.objectValues=r=>t.objectKeys(r).map(function(i){return r[i]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&i.push(o);return i},t.find=(r,i)=>{for(const o of r)if(i(o))return o},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function s(r,i=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}t.joinValues=s,t.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(se||(se={}));var Rr;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Rr||(Rr={}));const W=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ot=t=>{switch(typeof t){case"undefined":return W.undefined;case"string":return W.string;case"number":return Number.isNaN(t)?W.nan:W.number;case"boolean":return W.boolean;case"function":return W.function;case"bigint":return W.bigint;case"symbol":return W.symbol;case"object":return Array.isArray(t)?W.array:t===null?W.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?W.promise:typeof Map<"u"&&t instanceof Map?W.map:typeof Set<"u"&&t instanceof Set?W.set:typeof Date<"u"&&t instanceof Date?W.date:W.object;default:return W.unknown}},N=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 nt extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(i){return i.message},s={_errors:[]},r=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)s._errors.push(n(o));else{let a=s,l=0;for(;l<o.path.length;){const c=o.path[l];l===o.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(o))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return r(this),s}static assert(e){if(!(e instanceof nt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},s=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];n[i]=n[i]||[],n[i].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}nt.create=t=>new nt(t);const Rs=(t,e)=>{let n;switch(t.code){case N.invalid_type:t.received===W.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:n=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case N.invalid_union:n="Invalid input";break;case N.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case N.invalid_enum_value:n=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:n="Invalid function arguments";break;case N.invalid_return_type:n="Invalid function return type";break;case N.invalid_date:n="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:se.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case N.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case N.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case N.custom:n="Invalid input";break;case N.invalid_intersection_types:n="Intersection results could not be merged";break;case N.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:n="Number must be finite";break;default:n=e.defaultError,se.assertNever(t)}return{message:n}};let Ra=Rs;function Ta(){return Ra}const Sa=t=>{const{data:e,path:n,errorMaps:s,issueData:r}=t,i=[...n,...r.path||[]],o={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let a="";const l=s.filter(c=>!!c).slice().reverse();for(const c of l)a=c(o,{data:e,defaultError:a}).message;return{...r,path:i,message:a}};function P(t,e){const n=Ta(),s=Sa({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Rs?void 0:Rs].filter(r=>!!r)});t.common.issues.push(s)}class Se{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const s=[];for(const r of n){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,n){const s=[];for(const r of n){const i=await r.key,o=await r.value;s.push({key:i,value:o})}return Se.mergeObjectSync(e,s)}static mergeObjectSync(e,n){const s={};for(const r of n){const{key:i,value:o}=r;if(i.status==="aborted"||o.status==="aborted")return J;i.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(s[i.value]=o.value)}return{status:e.value,value:s}}}const J=Object.freeze({status:"aborted"}),Xt=t=>({status:"dirty",value:t}),Pe=t=>({status:"valid",value:t}),Tr=t=>t.status==="aborted",Sr=t=>t.status==="dirty",Pt=t=>t.status==="valid",Pn=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));class Ge{constructor(e,n,s,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=s,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ir=(t,e)=>{if(Pt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new nt(t.common.issues);return this._error=n,this._error}}};function K(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:s,description:r}=t;if(e&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:l}=t;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??s??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:r}}class te{get description(){return this._def.description}_getType(e){return ot(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Se,ctx:{common:e.parent.common,data:e.data,parsedType:ot(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Pn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const s=this.safeParse(e,n);if(s.success)return s.data;throw s.error}safeParse(e,n){const s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)},r=this._parseSync({data:e,path:s.path,parent:s});return Ir(s,r)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return Pt(s)?{value:s.value}:{issues:n.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>Pt(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const s=await this.safeParseAsync(e,n);if(s.success)return s.data;throw s.error}async safeParseAsync(e,n){const s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ot(e)},r=this._parse({data:e,path:s.path,parent:s}),i=await(Pn(r)?r:Promise.resolve(r));return Ir(s,i)}refine(e,n){const s=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,i)=>{const o=e(r),a=()=>i.addIssue({code:N.custom,...s(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,n){return this._refinement((s,r)=>e(s)?!0:(r.addIssue(typeof n=="function"?n(s,r):n),!1))}_refinement(e){return new Ut({schema:this,typeName:Y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return ut.create(this,this._def)}nullable(){return Wt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ze.create(this)}promise(){return jn.create(this,this._def)}or(e){return Vn.create([this,e],this._def)}and(e){return Un.create(this,e,this._def)}transform(e){return new Ut({...K(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Ns({...K(this._def),innerType:this,defaultValue:n,typeName:Y.ZodDefault})}brand(){return new Ja({typeName:Y.ZodBranded,type:this,...K(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Ds({...K(this._def),innerType:this,catchValue:n,typeName:Y.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Qs.create(this,e)}readonly(){return Cs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ia=/^c[^\s-]{8,}$/i,xa=/^[0-9a-z]+$/,Aa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Na=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Da=/^[a-z0-9_-]{21}$/i,Ca=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Fa=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$a=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ma="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let cs;const Pa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,La=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Va=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ua=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Wa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ja=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ni="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Za=new RegExp(`^${Ni}$`);function Di(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function za(t){return new RegExp(`^${Di(t)}$`)}function qa(t){let e=`${Ni}T${Di(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function Ba(t,e){return!!((e==="v4"||!e)&&Pa.test(t)||(e==="v6"||!e)&&Va.test(t))}function Ha(t,e){if(!Ca.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(s));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Ga(t,e){return!!((e==="v4"||!e)&&La.test(t)||(e==="v6"||!e)&&Ua.test(t))}class tt extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==W.string){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.string,received:i.parsedType}),J}const s=new Se;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:N.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:N.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:N.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&P(r,{code:N.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),s.dirty())}else if(i.kind==="email")$a.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"email",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="emoji")cs||(cs=new RegExp(Ma,"u")),cs.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"emoji",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="uuid")Na.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"uuid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="nanoid")Da.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"nanoid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid")Ia.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="cuid2")xa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cuid2",code:N.invalid_string,message:i.message}),s.dirty());else if(i.kind==="ulid")Aa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ulid",code:N.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:N.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:N.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:N.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:N.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:N.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()):i.kind==="datetime"?qa(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"datetime",message:i.message}),s.dirty()):i.kind==="date"?Za.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"date",message:i.message}),s.dirty()):i.kind==="time"?za(i).test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{code:N.invalid_string,validation:"time",message:i.message}),s.dirty()):i.kind==="duration"?Fa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"duration",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="ip"?Ba(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"ip",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="jwt"?Ha(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"jwt",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="cidr"?Ga(e.data,i.version)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"cidr",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="base64"?Wa.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64",code:N.invalid_string,message:i.message}),s.dirty()):i.kind==="base64url"?ja.test(e.data)||(r=this._getOrReturnCtx(e,r),P(r,{validation:"base64url",code:N.invalid_string,message:i.message}),s.dirty()):se.assertNever(i);return{status:s.value,value:e.data}}_regex(e,n,s){return this.refinement(r=>e.test(r),{validation:n,code:N.invalid_string,...z.errToObj(s)})}_addCheck(e){return new tt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...z.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...z.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...z.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...z.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...z.errToObj(n)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new tt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new tt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new tt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}tt.create=t=>new tt({checks:[],typeName:Y.ZodString,coerce:t?.coerce??!1,...K(t)});function Ya(t,e){const n=(t.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,r=n>s?n:s,i=Number.parseInt(t.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return i%o/10**r}class Lt 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)!==W.number){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.number,received:i.parsedType}),J}let s;const r=new Se;for(const i of this._def.checks)i.kind==="int"?se.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),P(s,{code:N.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:N.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:N.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?Ya(e.data,i.value)!==0&&(s=this._getOrReturnCtx(e,s),P(s,{code:N.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:N.not_finite,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,z.toString(n))}setLimit(e,n,s,r){return new Lt({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new Lt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&se.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Lt.create=t=>new Lt({checks:[],typeName:Y.ZodNumber,coerce:t?.coerce||!1,...K(t)});class un extends te{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==W.bigint)return this._getInvalidInput(e);let s;const r=new Se;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:N.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:N.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:N.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):se.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return P(n,{code:N.invalid_type,expected:W.bigint,received:n.parsedType}),J}gte(e,n){return this.setLimit("min",e,!0,z.toString(n))}gt(e,n){return this.setLimit("min",e,!1,z.toString(n))}lte(e,n){return this.setLimit("max",e,!0,z.toString(n))}lt(e,n){return this.setLimit("max",e,!1,z.toString(n))}setLimit(e,n,s,r){return new un({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:s,message:z.toString(r)}]})}_addCheck(e){return new un({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}un.create=t=>new un({checks:[],typeName:Y.ZodBigInt,coerce:t?.coerce??!1,...K(t)});class Ts extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==W.boolean){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.boolean,received:s.parsedType}),J}return Pe(e.data)}}Ts.create=t=>new Ts({typeName:Y.ZodBoolean,coerce:t?.coerce||!1,...K(t)});class Ln extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==W.date){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_type,expected:W.date,received:i.parsedType}),J}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return P(i,{code:N.invalid_date}),J}const s=new Se;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:N.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:N.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 Ln({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Ln.create=t=>new Ln({checks:[],coerce:t?.coerce||!1,typeName:Y.ZodDate,...K(t)});class xr extends te{_parse(e){if(this._getType(e)!==W.symbol){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.symbol,received:s.parsedType}),J}return Pe(e.data)}}xr.create=t=>new xr({typeName:Y.ZodSymbol,...K(t)});class Ss extends te{_parse(e){if(this._getType(e)!==W.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.undefined,received:s.parsedType}),J}return Pe(e.data)}}Ss.create=t=>new Ss({typeName:Y.ZodUndefined,...K(t)});class Ar extends te{_parse(e){if(this._getType(e)!==W.null){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.null,received:s.parsedType}),J}return Pe(e.data)}}Ar.create=t=>new Ar({typeName:Y.ZodNull,...K(t)});class Is extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return Pe(e.data)}}Is.create=t=>new Is({typeName:Y.ZodAny,...K(t)});class Nr extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Pe(e.data)}}Nr.create=t=>new Nr({typeName:Y.ZodUnknown,...K(t)});class ht extends te{_parse(e){const n=this._getOrReturnCtx(e);return P(n,{code:N.invalid_type,expected:W.never,received:n.parsedType}),J}}ht.create=t=>new ht({typeName:Y.ZodNever,...K(t)});class Dr extends te{_parse(e){if(this._getType(e)!==W.undefined){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.void,received:s.parsedType}),J}return Pe(e.data)}}Dr.create=t=>new Dr({typeName:Y.ZodVoid,...K(t)});class ze extends te{_parse(e){const{ctx:n,status:s}=this._processInputParams(e),r=this._def;if(n.parsedType!==W.array)return P(n,{code:N.invalid_type,expected:W.array,received:n.parsedType}),J;if(r.exactLength!==null){const o=n.data.length>r.exactLength.value,a=n.data.length<r.exactLength.value;(o||a)&&(P(n,{code:o?N.too_big:N.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(P(n,{code:N.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(P(n,{code:N.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>r.type._parseAsync(new Ge(n,o,n.path,a)))).then(o=>Se.mergeArray(s,o));const i=[...n.data].map((o,a)=>r.type._parseSync(new Ge(n,o,n.path,a)));return Se.mergeArray(s,i)}get element(){return this._def.type}min(e,n){return new ze({...this._def,minLength:{value:e,message:z.toString(n)}})}max(e,n){return new ze({...this._def,maxLength:{value:e,message:z.toString(n)}})}length(e,n){return new ze({...this._def,exactLength:{value:e,message:z.toString(n)}})}nonempty(e){return this.min(1,e)}}ze.create=(t,e)=>new ze({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...K(e)});function Dt(t){if(t instanceof he){const e={};for(const n in t.shape){const s=t.shape[n];e[n]=ut.create(Dt(s))}return new he({...t._def,shape:()=>e})}else return t instanceof ze?new ze({...t._def,type:Dt(t.element)}):t instanceof ut?ut.create(Dt(t.unwrap())):t instanceof Wt?Wt.create(Dt(t.unwrap())):t instanceof Ot?Ot.create(t.items.map(e=>Dt(e))):t}class he extends te{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=se.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==W.object){const c=this._getOrReturnCtx(e);return P(c,{code:N.invalid_type,expected:W.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 ht&&this._def.unknownKeys==="strip"))for(const c in r.data)o.includes(c)||a.push(c);const l=[];for(const c of o){const d=i[c],p=r.data[c];l.push({key:{status:"valid",value:c},value:d._parse(new Ge(r,p,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof ht){const c=this._def.unknownKeys;if(c==="passthrough")for(const d of a)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(c==="strict")a.length>0&&(P(r,{code:N.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 p=r.data[d];l.push({key:{status:"valid",value:d},value:c._parse(new Ge(r,p,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const c=[];for(const d of l){const p=await d.key,u=await d.value;c.push({key:p,value:u,alwaysSet:d.alwaysSet})}return c}).then(c=>Se.mergeObjectSync(s,c)):Se.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new he({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,s)=>{const r=this._def.errorMap?.(n,s).message??s.defaultError;return n.code==="unrecognized_keys"?{message:z.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new he({...this._def,unknownKeys:"strip"})}passthrough(){return new he({...this._def,unknownKeys:"passthrough"})}extend(e){return new he({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new he({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Y.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new he({...this._def,catchall:e})}pick(e){const n={};for(const s of se.objectKeys(e))e[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new he({...this._def,shape:()=>n})}omit(e){const n={};for(const s of se.objectKeys(this.shape))e[s]||(n[s]=this.shape[s]);return new he({...this._def,shape:()=>n})}deepPartial(){return Dt(this)}partial(e){const n={};for(const s of se.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?n[s]=r:n[s]=r.optional()}return new he({...this._def,shape:()=>n})}required(e){const n={};for(const s of se.objectKeys(this.shape))if(e&&!e[s])n[s]=this.shape[s];else{let i=this.shape[s];for(;i instanceof ut;)i=i._def.innerType;n[s]=i}return new he({...this._def,shape:()=>n})}keyof(){return Ci(se.objectKeys(this.shape))}}he.create=(t,e)=>new he({shape:()=>t,unknownKeys:"strip",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});he.strictCreate=(t,e)=>new he({shape:()=>t,unknownKeys:"strict",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});he.lazycreate=(t,e)=>new he({shape:t,unknownKeys:"strip",catchall:ht.create(),typeName:Y.ZodObject,...K(e)});class Vn extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s=this._def.options;function r(i){for(const a of i)if(a.result.status==="valid")return a.result;for(const a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(a=>new nt(a.ctx.common.issues));return P(n,{code:N.invalid_union,unionErrors:o}),J}if(n.common.async)return Promise.all(s.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(r);{let i;const o=[];for(const l of s){const c={...n,common:{...n.common,issues:[]},parent:null},d=l._parseSync({data:n.data,path:n.path,parent:c});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:c}),c.common.issues.length&&o.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const a=o.map(l=>new nt(l));return P(n,{code:N.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}Vn.create=(t,e)=>new Vn({options:t,typeName:Y.ZodUnion,...K(e)});function xs(t,e){const n=ot(t),s=ot(e);if(t===e)return{valid:!0,data:t};if(n===W.object&&s===W.object){const r=se.objectKeys(e),i=se.objectKeys(t).filter(a=>r.indexOf(a)!==-1),o={...t,...e};for(const a of i){const l=xs(t[a],e[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(n===W.array&&s===W.array){if(t.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<t.length;i++){const o=t[i],a=e[i],l=xs(o,a);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===W.date&&s===W.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Un extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=(i,o)=>{if(Tr(i)||Tr(o))return J;const a=xs(i.value,o.value);return a.valid?((Sr(i)||Sr(o))&&n.dirty(),{status:n.value,value:a.data}):(P(s,{code:N.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}))}}Un.create=(t,e,n)=>new Un({left:t,right:e,typeName:Y.ZodIntersection,...K(n)});class Ot extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.array)return P(s,{code:N.invalid_type,expected:W.array,received:s.parsedType}),J;if(s.data.length<this._def.items.length)return P(s,{code:N.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:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...s.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new Ge(s,o,s.path,a)):null}).filter(o=>!!o);return s.common.async?Promise.all(i).then(o=>Se.mergeArray(n,o)):Se.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new Ot({...this._def,rest:e})}}Ot.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ot({items:t,typeName:Y.ZodTuple,rest:null,...K(e)})};class Wn extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.object)return P(s,{code:N.invalid_type,expected:W.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 Ge(s,a,s.path,a)),value:o._parse(new Ge(s,s.data[a],s.path,a)),alwaysSet:a in s.data});return s.common.async?Se.mergeObjectAsync(n,r):Se.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,s){return n instanceof te?new Wn({keyType:e,valueType:n,typeName:Y.ZodRecord,...K(s)}):new Wn({keyType:tt.create(),valueType:e,typeName:Y.ZodRecord,...K(n)})}}class Cr extends te{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.map)return P(s,{code:N.invalid_type,expected:W.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 Ge(s,a,s.path,[c,"key"])),value:i._parse(new Ge(s,l,s.path,[c,"value"]))}));if(s.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const c=await l.key,d=await l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of o){const c=l.key,d=l.value;if(c.status==="aborted"||d.status==="aborted")return J;(c.status==="dirty"||d.status==="dirty")&&n.dirty(),a.set(c.value,d.value)}return{status:n.value,value:a}}}}Cr.create=(t,e,n)=>new Cr({valueType:e,keyType:t,typeName:Y.ZodMap,...K(n)});class dn extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.parsedType!==W.set)return P(s,{code:N.invalid_type,expected:W.set,received:s.parsedType}),J;const r=this._def;r.minSize!==null&&s.data.size<r.minSize.value&&(P(s,{code:N.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&s.data.size>r.maxSize.value&&(P(s,{code:N.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());const i=this._def.valueType;function o(l){const c=new Set;for(const d of l){if(d.status==="aborted")return J;d.status==="dirty"&&n.dirty(),c.add(d.value)}return{status:n.value,value:c}}const a=[...s.data.values()].map((l,c)=>i._parse(new Ge(s,l,s.path,c)));return s.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(e,n){return new dn({...this._def,minSize:{value:e,message:z.toString(n)}})}max(e,n){return new dn({...this._def,maxSize:{value:e,message:z.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}dn.create=(t,e)=>new dn({valueType:t,minSize:null,maxSize:null,typeName:Y.ZodSet,...K(e)});class Fr extends te{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Fr.create=(t,e)=>new Fr({getter:t,typeName:Y.ZodLazy,...K(e)});class As extends te{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return P(n,{received:n.data,code:N.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}As.create=(t,e)=>new As({value:t,typeName:Y.ZodLiteral,...K(e)});function Ci(t,e){return new Vt({values:t,typeName:Y.ZodEnum,...K(e)})}class Vt extends te{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),s=this._def.values;return P(n,{expected:se.joinValues(s),received:n.parsedType,code:N.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),s=this._def.values;return P(n,{received:n.data,code:N.invalid_enum_value,options:s}),J}return Pe(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Vt.create(e,{...this._def,...n})}exclude(e,n=this._def){return Vt.create(this.options.filter(s=>!e.includes(s)),{...this._def,...n})}}Vt.create=Ci;class $r extends te{_parse(e){const n=se.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==W.string&&s.parsedType!==W.number){const r=se.objectValues(n);return P(s,{expected:se.joinValues(r),received:s.parsedType,code:N.invalid_type}),J}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=se.objectValues(n);return P(s,{received:s.data,code:N.invalid_enum_value,options:r}),J}return Pe(e.data)}get enum(){return this._def.values}}$r.create=(t,e)=>new $r({values:t,typeName:Y.ZodNativeEnum,...K(e)});class jn extends te{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==W.promise&&n.common.async===!1)return P(n,{code:N.invalid_type,expected:W.promise,received:n.parsedType}),J;const s=n.parsedType===W.promise?n.data:Promise.resolve(n.data);return Pe(s.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}}jn.create=(t,e)=>new jn({type:t,typeName:Y.ZodPromise,...K(e)});class Ut extends te{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:s}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:o=>{P(s,o),o.fatal?n.abort():n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const o=r.transform(s.data,i);if(s.common.async)return Promise.resolve(o).then(async a=>{if(n.value==="aborted")return J;const l=await this._def.schema._parseAsync({data:a,path:s.path,parent:s});return l.status==="aborted"?J:l.status==="dirty"||n.value==="dirty"?Xt(l.value):l});{if(n.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:s.path,parent:s});return a.status==="aborted"?J:a.status==="dirty"||n.value==="dirty"?Xt(a.value):a}}if(r.type==="refinement"){const o=a=>{const l=r.refinement(a,i);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(s.common.async===!1){const a=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?J:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(r.type==="transform")if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!Pt(o))return J;const a=r.transform(o.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>Pt(o)?Promise.resolve(r.transform(o.value,i)).then(a=>({status:n.value,value:a})):J);se.assertNever(r)}}Ut.create=(t,e,n)=>new Ut({schema:t,typeName:Y.ZodEffects,effect:e,...K(n)});Ut.createWithPreprocess=(t,e,n)=>new Ut({schema:e,effect:{type:"preprocess",transform:t},typeName:Y.ZodEffects,...K(n)});class ut extends te{_parse(e){return this._getType(e)===W.undefined?Pe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ut.create=(t,e)=>new ut({innerType:t,typeName:Y.ZodOptional,...K(e)});class Wt extends te{_parse(e){return this._getType(e)===W.null?Pe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Wt.create=(t,e)=>new Wt({innerType:t,typeName:Y.ZodNullable,...K(e)});class Ns extends te{_parse(e){const{ctx:n}=this._processInputParams(e);let s=n.data;return n.parsedType===W.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ns.create=(t,e)=>new Ns({innerType:t,typeName:Y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...K(e)});class Ds extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Pn(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new nt(s.common.issues)},input:s.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new nt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ds.create=(t,e)=>new Ds({innerType:t,typeName:Y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...K(e)});class Mr extends te{_parse(e){if(this._getType(e)!==W.nan){const s=this._getOrReturnCtx(e);return P(s,{code:N.invalid_type,expected:W.nan,received:s.parsedType}),J}return{status:"valid",value:e.data}}}Mr.create=t=>new Mr({typeName:Y.ZodNaN,...K(t)});class Ja extends te{_parse(e){const{ctx:n}=this._processInputParams(e),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Qs extends te{_parse(e){const{status:n,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return i.status==="aborted"?J:i.status==="dirty"?(n.dirty(),Xt(i.value)):this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();{const r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?J:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(e,n){return new Qs({in:e,out:n,typeName:Y.ZodPipeline})}}class Cs extends te{_parse(e){const n=this._def.innerType._parse(e),s=r=>(Pt(r)&&(r.value=Object.freeze(r.value)),r);return Pn(n)?n.then(r=>s(r)):s(n)}unwrap(){return this._def.innerType}}Cs.create=(t,e)=>new Cs({innerType:t,typeName:Y.ZodReadonly,...K(e)});var Y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Y||(Y={}));const Ie=tt.create,_t=Lt.create,an=Ts.create,us=Ss.create,ve=Is.create;ht.create;const Tt=ze.create,qe=he.create,Oe=Vn.create;Un.create;Ot.create;const pn=Wn.create,Ee=As.create,Zn=Vt.create;jn.create;ut.create;Wt.create;const In=()=>ve().refine(t=>t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Value is not a valid timestamp"}),Pr=()=>ve().refine(t=>t&&(t._methodName==="serverTimestamp"||t.constructor.name==="ServerTimestampTransform"),{message:"Value is not a valid server timestamp"}),Fi=(t,e,n)=>{const s={};if(t.includeFields){const i=e.collections[t.collection];if(!i)return pn(ve());t.includeFields.forEach(o=>{const a=i.fields.find(c=>c.name===o);if(!a)throw new Error(`Field ${o} not found in collection ${t.collection}`);s[o]=zn(i,a),Rt(i,[a]).size===1&&(s[`${o}_Lowercase`]=zn(i,a,!0))})}const r={Collection_Path:Tt(Ie()),...s};return n&&(r.id=Ie().length(20)),qe(r)},Qa=(t,e)=>{let n=pn(Fi(t,e));return t.required||(n=n.optional()),n},Ka=t=>{let e=Tt(Oe([Ie().length(20),Ie().length(28)]));return["OneToOne","OneToMany"].includes(t.type)?e=e.max(1):(t.min&&(e=e.min(t.min)),t.max&&(e=e.max(t.max)),t.length&&(e=e.length(t.length))),t.required?e=e.nonempty():e=e.optional(),e},zn=(t,e,n)=>{const{softDelete:s}=t,r=s?.timestampField;let i;switch(e.type){case"String":if(i=Ie(),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()),n&&(i=i.toLowerCase()),e.pattern&&(i=Oe([i.regex(new RegExp(e.pattern)),Ee("")])),e.values)if(n){const o=e.values.map(a=>a.toLowerCase());i=Zn(o)}else i=Zn(e.values);break;case"Boolean":i=an();break;case"Number":e.autoIncrement?i=Oe([Ee("Pending"),_t().int()]):(i=_t(),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=ve().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=In(),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=Tt(ve()),e.length&&(i=i.length(e.length)),e.minlength?i=i.min(e.minlength):e.required&&(i=i.nonempty()),e.maxlength&&(i=i.max(e.maxlength)),e.values&&(i=i.refine(o=>{let a=!0;return o.forEach(l=>{e.values&&!e.values.includes(l)&&(a=!1)}),a},{message:"Value is not an allowed value"}));break;case"Map":i=pn(ve()),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=ve();break}return!X(e)&&e.nullable&&(i=i.nullable()),e.required||(i=i.optional()),i},$i=(t,e,n)=>{const s={Collection_Path:Tt(Ie()),Last_Write_App:Ie(),Last_Write_At:In(),Last_Save_At:Pr(),Last_Write_By:Oe([Ie().length(28),Ee("System")]),Last_Write_Connection_Status:Zn(["Online","Offline"]),Last_Write_Version:_t().int(),id:Ie().regex(new RegExp("^[a-zA-Z0-9]+$")).length(20),Created_At:In(),Created_By:Oe([Ie().length(28),Ee("System")])};t==="create"&&(s.Saved_At=Pr()),t==="update"&&(s.Saved_At=In(),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=gt(e,e.fields),i=Array.from(r).map(l=>l.name);e.fields.forEach(l=>{X(l)?(s[l.name]=Qa(l,n),s[`${l.name}_Array`]=Ka(l),i.includes(l.name)&&(s[`${l.name}_Single`]=Fi(l,n,!0),l.required||(s[`${l.name}_Single`]=s[`${l.name}_Single`].optional())),l.length&&(s[l.name]=s[l.name].refine(c=>l.length&&c&&Object.keys(c).length===l.length,{message:`Value must contain ${l.length} item(s)`})),l.min&&(s[l.name]=s[l.name].refine(c=>l.min&&c&&Object.keys(c).length>=l.min,{message:`Value must contain at least ${l.min} item(s)`})),l.max&&(s[l.name]=s[l.name].refine(c=>l.max&&(!c||Object.keys(c).length<=l.max),{message:`Value must contain at most ${l.max} item(s)`}))):l.type!=="Computed"&&(s[l.name]=zn(e,l))}),Rt(e,e.fields).forEach(l=>{s[l.name]&&(s[`${l.name}_Lowercase`]=zn(e,l,!0))});const a=qe(s);return e.allowSchemalessFields?a.passthrough():a.strict()};class St extends Error{}class Xa extends St{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class el extends St{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class tl extends St{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class Ct extends St{}class Mi extends St{constructor(e){super(`Invalid unit ${e}`)}}class ke extends St{}class it extends St{constructor(){super("Zone is an abstract class")}}const $="numeric",je="short",Ae="long",qn={year:$,month:$,day:$},Pi={year:$,month:je,day:$},nl={year:$,month:je,day:$,weekday:je},Li={year:$,month:Ae,day:$},Vi={year:$,month:Ae,day:$,weekday:Ae},Ui={hour:$,minute:$},Wi={hour:$,minute:$,second:$},ji={hour:$,minute:$,second:$,timeZoneName:je},Zi={hour:$,minute:$,second:$,timeZoneName:Ae},zi={hour:$,minute:$,hourCycle:"h23"},qi={hour:$,minute:$,second:$,hourCycle:"h23"},Bi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:je},Hi={hour:$,minute:$,second:$,hourCycle:"h23",timeZoneName:Ae},Gi={year:$,month:$,day:$,hour:$,minute:$},Yi={year:$,month:$,day:$,hour:$,minute:$,second:$},Ji={year:$,month:je,day:$,hour:$,minute:$},Qi={year:$,month:je,day:$,hour:$,minute:$,second:$},sl={year:$,month:je,day:$,weekday:je,hour:$,minute:$},Ki={year:$,month:Ae,day:$,hour:$,minute:$,timeZoneName:je},Xi={year:$,month:Ae,day:$,hour:$,minute:$,second:$,timeZoneName:je},eo={year:$,month:Ae,day:$,weekday:Ae,hour:$,minute:$,timeZoneName:Ae},to={year:$,month:Ae,day:$,weekday:Ae,hour:$,minute:$,second:$,timeZoneName:Ae};class yn{get type(){throw new it}get name(){throw new it}get ianaName(){return this.name}get isUniversal(){throw new it}offsetName(e,n){throw new it}formatOffset(e,n){throw new it}offset(e){throw new it}equals(e){throw new it}get isValid(){throw new it}}let ds=null;class es extends yn{static get instance(){return ds===null&&(ds=new es),ds}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return ho(e,n,s)}formatOffset(e,n){return ln(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const Fs=new Map;function rl(t){let e=Fs.get(t);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Fs.set(t,e)),e}const il={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ol(t,e){const n=t.format(e).replace(/\u200E/g,""),s=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,r,i,o,a,l,c,d]=s;return[o,r,i,a,l,c,d]}function al(t,e){const n=t.formatToParts(e),s=[];for(let r=0;r<n.length;r++){const{type:i,value:o}=n[r],a=il[i];i==="era"?s[a]=o:G(a)||(s[a]=parseInt(o,10))}return s}const fs=new Map;class st extends yn{static create(e){let n=fs.get(e);return n===void 0&&fs.set(e,n=new st(e)),n}static resetCache(){fs.clear(),Fs.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=st.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:s}){return ho(e,n,s,this.name)}formatOffset(e,n){return ln(this.offset(e),n)}offset(e){if(!this.valid)return NaN;const n=new Date(e);if(isNaN(n))return NaN;const s=rl(this.name);let[r,i,o,a,l,c,d]=s.formatToParts?al(s,n):ol(s,n);a==="BC"&&(r=-Math.abs(r)+1);const u=ns({year:r,month:i,day:o,hour:l===24?0:l,minute:c,second:d,millisecond:0});let f=+n;const g=f%1e3;return f-=g>=0?g:1e3+g,(u-f)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let Lr={};function ll(t,e={}){const n=JSON.stringify([t,e]);let s=Lr[n];return s||(s=new Intl.ListFormat(t,e),Lr[n]=s),s}const $s=new Map;function Ms(t,e={}){const n=JSON.stringify([t,e]);let s=$s.get(n);return s===void 0&&(s=new Intl.DateTimeFormat(t,e),$s.set(n,s)),s}const Ps=new Map;function cl(t,e={}){const n=JSON.stringify([t,e]);let s=Ps.get(n);return s===void 0&&(s=new Intl.NumberFormat(t,e),Ps.set(n,s)),s}const Ls=new Map;function ul(t,e={}){const{base:n,...s}=e,r=JSON.stringify([t,s]);let i=Ls.get(r);return i===void 0&&(i=new Intl.RelativeTimeFormat(t,e),Ls.set(r,i)),i}let en=null;function dl(){return en||(en=new Intl.DateTimeFormat().resolvedOptions().locale,en)}const Vs=new Map;function no(t){let e=Vs.get(t);return e===void 0&&(e=new Intl.DateTimeFormat(t).resolvedOptions(),Vs.set(t,e)),e}const Us=new Map;function fl(t){let e=Us.get(t);if(!e){const n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,"minimalDays"in e||(e={...so,...e}),Us.set(t,e)}return e}function hl(t){const e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));const n=t.indexOf("-u-");if(n===-1)return[t];{let s,r;try{s=Ms(t).resolvedOptions(),r=t}catch{const l=t.substring(0,n);s=Ms(l).resolvedOptions(),r=l}const{numberingSystem:i,calendar:o}=s;return[r,i,o]}}function ml(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function pl(t){const e=[];for(let n=1;n<=12;n++){const s=V.utc(2009,n,1);e.push(t(s))}return e}function yl(t){const e=[];for(let n=1;n<=7;n++){const s=V.utc(2016,11,13+n);e.push(t(s))}return e}function On(t,e,n,s){const r=t.listingMode();return r==="error"?null:r==="en"?n(e):s(e)}function gl(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||no(t.locale).numberingSystem==="latn"}class wl{constructor(e,n,s){this.padTo=s.padTo||0,this.floor=s.floor||!1;const{padTo:r,floor:i,...o}=s;if(!n||Object.keys(o).length>0){const a={useGrouping:!1,...s};s.padTo>0&&(a.minimumIntegerDigits=s.padTo),this.inf=cl(e,a)}}format(e){if(this.inf){const n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{const n=this.floor?Math.floor(e):nr(e,3);return me(n,this.padTo)}}}class _l{constructor(e,n,s){this.opts=s,this.originalZone=void 0;let r;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const o=-1*(e.offset/60),a=o>=0?`Etc/GMT+${o}`:`Etc/GMT${o}`;e.offset!==0&&st.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=Ms(n,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(n=>{if(n.type==="timeZoneName"){const s=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:s}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class El{constructor(e,n,s){this.opts={style:"long",...s},!n&&uo()&&(this.rtf=ul(e,s))}format(e,n){return this.rtf?this.rtf.format(e,n):jl(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}}const so={firstDay:1,minimalDays:4,weekend:[6,7]};class ie{static fromOpts(e){return ie.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,s,r,i=!1){const o=e||de.defaultLocale,a=o||(i?"en-US":dl()),l=n||de.defaultNumberingSystem,c=s||de.defaultOutputCalendar,d=js(r)||de.defaultWeekSettings;return new ie(a,l,c,d,o)}static resetCache(){en=null,$s.clear(),Ps.clear(),Ls.clear(),Vs.clear(),Us.clear()}static fromObject({locale:e,numberingSystem:n,outputCalendar:s,weekSettings:r}={}){return ie.create(e,n,s,r)}constructor(e,n,s,r,i){const[o,a,l]=hl(e);this.locale=o,this.numberingSystem=n||a||null,this.outputCalendar=s||l||null,this.weekSettings=r,this.intl=ml(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=gl(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:ie.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,js(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1){return On(this,e,yo,()=>{const s=this.intl==="ja"||this.intl.startsWith("ja-");n&=!s;const r=n?{month:e,day:"numeric"}:{month:e},i=n?"format":"standalone";if(!this.monthsCache[i][e]){const o=s?a=>this.dtFormatter(a,r).format():a=>this.extract(a,r,"month");this.monthsCache[i][e]=pl(o)}return this.monthsCache[i][e]})}weekdays(e,n=!1){return On(this,e,_o,()=>{const s=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},r=n?"format":"standalone";return this.weekdaysCache[r][e]||(this.weekdaysCache[r][e]=yl(i=>this.extract(i,s,"weekday"))),this.weekdaysCache[r][e]})}meridiems(){return On(this,void 0,()=>Eo,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[V.utc(2016,11,13,9),V.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return On(this,e,vo,()=>{const n={era:e};return this.eraCache[e]||(this.eraCache[e]=[V.utc(-40,1,1),V.utc(2017,1,1)].map(s=>this.extract(s,n,"era"))),this.eraCache[e]})}extract(e,n,s){const r=this.dtFormatter(e,n),i=r.formatToParts(),o=i.find(a=>a.type.toLowerCase()===s);return o?o.value:null}numberFormatter(e={}){return new wl(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new _l(e,this.intl,n)}relFormatter(e={}){return new El(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ll(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||no(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:fo()?fl(this.locale):so}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let hs=null;class Te extends yn{static get utcInstance(){return hs===null&&(hs=new Te(0)),hs}static instance(e){return e===0?Te.utcInstance:new Te(e)}static parseSpecifier(e){if(e){const n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new Te(ss(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${ln(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${ln(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return ln(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class vl extends yn{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function lt(t,e){if(G(t)||t===null)return e;if(t instanceof yn)return t;if(Sl(t)){const n=t.toLowerCase();return n==="default"?e:n==="local"||n==="system"?es.instance:n==="utc"||n==="gmt"?Te.utcInstance:Te.parseSpecifier(n)||st.create(t)}else return dt(t)?Te.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new vl(t)}const Ks={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Vr={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Ol=Ks.hanidec.replace(/[\[|\]]/g,"").split("");function kl(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);if(t[n].search(Ks.hanidec)!==-1)e+=Ol.indexOf(t[n]);else for(const r in Vr){const[i,o]=Vr[r];s>=i&&s<=o&&(e+=s-i)}}return parseInt(e,10)}else return e}const Ws=new Map;function bl(){Ws.clear()}function Le({numberingSystem:t},e=""){const n=t||"latn";let s=Ws.get(n);s===void 0&&(s=new Map,Ws.set(n,s));let r=s.get(e);return r===void 0&&(r=new RegExp(`${Ks[n]}${e}`),s.set(e,r)),r}let Ur=()=>Date.now(),Wr="system",jr=null,Zr=null,zr=null,qr=60,Br,Hr=null;class de{static get now(){return Ur}static set now(e){Ur=e}static set defaultZone(e){Wr=e}static get defaultZone(){return lt(Wr,es.instance)}static get defaultLocale(){return jr}static set defaultLocale(e){jr=e}static get defaultNumberingSystem(){return Zr}static set defaultNumberingSystem(e){Zr=e}static get defaultOutputCalendar(){return zr}static set defaultOutputCalendar(e){zr=e}static get defaultWeekSettings(){return Hr}static set defaultWeekSettings(e){Hr=js(e)}static get twoDigitCutoffYear(){return qr}static set twoDigitCutoffYear(e){qr=e%100}static get throwOnInvalid(){return Br}static set throwOnInvalid(e){Br=e}static resetCaches(){ie.resetCache(),st.resetCache(),V.resetCache(),bl()}}class Ue{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const ro=[0,31,59,90,120,151,181,212,243,273,304,334],io=[0,31,60,91,121,152,182,213,244,274,305,335];function $e(t,e){return new Ue("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function Xs(t,e,n){const s=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&s.setUTCFullYear(s.getUTCFullYear()-1900);const r=s.getUTCDay();return r===0?7:r}function oo(t,e,n){return n+(gn(t)?io:ro)[e-1]}function ao(t,e){const n=gn(t)?io:ro,s=n.findIndex(i=>i<e),r=e-n[s];return{month:s+1,day:r}}function er(t,e){return(t-e+7)%7+1}function Bn(t,e=4,n=1){const{year:s,month:r,day:i}=t,o=oo(s,r,i),a=er(Xs(s,r,i),n);let l=Math.floor((o-a+14-e)/7),c;return l<1?(c=s-1,l=fn(c,e,n)):l>fn(s,e,n)?(c=s+1,l=1):c=s,{weekYear:c,weekNumber:l,weekday:a,...rs(t)}}function Gr(t,e=4,n=1){const{weekYear:s,weekNumber:r,weekday:i}=t,o=er(Xs(s,1,e),n),a=$t(s);let l=r*7+i-o-7+e,c;l<1?(c=s-1,l+=$t(c)):l>a?(c=s+1,l-=$t(s)):c=s;const{month:d,day:p}=ao(c,l);return{year:c,month:d,day:p,...rs(t)}}function ms(t){const{year:e,month:n,day:s}=t,r=oo(e,n,s);return{year:e,ordinal:r,...rs(t)}}function Yr(t){const{year:e,ordinal:n}=t,{month:s,day:r}=ao(e,n);return{year:e,month:s,day:r,...rs(t)}}function Jr(t,e){if(!G(t.localWeekday)||!G(t.localWeekNumber)||!G(t.localWeekYear)){if(!G(t.weekday)||!G(t.weekNumber)||!G(t.weekYear))throw new Ct("Cannot mix locale-based week fields with ISO-based week fields");return G(t.localWeekday)||(t.weekday=t.localWeekday),G(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),G(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function Rl(t,e=4,n=1){const s=ts(t.weekYear),r=Me(t.weekNumber,1,fn(t.weekYear,e,n)),i=Me(t.weekday,1,7);return s?r?i?!1:$e("weekday",t.weekday):$e("week",t.weekNumber):$e("weekYear",t.weekYear)}function Tl(t){const e=ts(t.year),n=Me(t.ordinal,1,$t(t.year));return e?n?!1:$e("ordinal",t.ordinal):$e("year",t.year)}function lo(t){const e=ts(t.year),n=Me(t.month,1,12),s=Me(t.day,1,Hn(t.year,t.month));return e?n?s?!1:$e("day",t.day):$e("month",t.month):$e("year",t.year)}function co(t){const{hour:e,minute:n,second:s,millisecond:r}=t,i=Me(e,0,23)||e===24&&n===0&&s===0&&r===0,o=Me(n,0,59),a=Me(s,0,59),l=Me(r,0,999);return i?o?a?l?!1:$e("millisecond",r):$e("second",s):$e("minute",n):$e("hour",e)}function G(t){return typeof t>"u"}function dt(t){return typeof t=="number"}function ts(t){return typeof t=="number"&&t%1===0}function Sl(t){return typeof t=="string"}function Il(t){return Object.prototype.toString.call(t)==="[object Date]"}function uo(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function fo(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function xl(t){return Array.isArray(t)?t:[t]}function Qr(t,e,n){if(t.length!==0)return t.reduce((s,r)=>{const i=[e(r),r];return s&&n(s[0],i[0])===s[0]?s:i},null)[1]}function Al(t,e){return e.reduce((n,s)=>(n[s]=t[s],n),{})}function jt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function js(t){if(t==null)return null;if(typeof t!="object")throw new ke("Week settings must be an object");if(!Me(t.firstDay,1,7)||!Me(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Me(e,1,7)))throw new ke("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Me(t,e,n){return ts(t)&&t>=e&&t<=n}function Nl(t,e){return t-e*Math.floor(t/e)}function me(t,e=2){const n=t<0;let s;return n?s="-"+(""+-t).padStart(e,"0"):s=(""+t).padStart(e,"0"),s}function at(t){if(!(G(t)||t===null||t===""))return parseInt(t,10)}function pt(t){if(!(G(t)||t===null||t===""))return parseFloat(t)}function tr(t){if(!(G(t)||t===null||t==="")){const e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function nr(t,e,n="round"){const s=10**e;switch(n){case"expand":return t>0?Math.ceil(t*s)/s:Math.floor(t*s)/s;case"trunc":return Math.trunc(t*s)/s;case"round":return Math.round(t*s)/s;case"floor":return Math.floor(t*s)/s;case"ceil":return Math.ceil(t*s)/s;default:throw new RangeError(`Value rounding ${n} is out of range`)}}function gn(t){return t%4===0&&(t%100!==0||t%400===0)}function $t(t){return gn(t)?366:365}function Hn(t,e){const n=Nl(e-1,12)+1,s=t+(e-n)/12;return n===2?gn(s)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function ns(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function Kr(t,e,n){return-er(Xs(t,1,e),n)+e-1}function fn(t,e=4,n=1){const s=Kr(t,e,n),r=Kr(t+1,e,n);return($t(t)-s+r)/7}function Zs(t){return t>99?t:t>de.twoDigitCutoffYear?1900+t:2e3+t}function ho(t,e,n,s=null){const r=new Date(t),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};s&&(i.timeZone=s);const o={timeZoneName:e,...i},a=new Intl.DateTimeFormat(n,o).formatToParts(r).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function ss(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);const s=parseInt(e,10)||0,r=n<0||Object.is(n,-0)?-s:s;return n*60+r}function mo(t){const e=Number(t);if(typeof t=="boolean"||t===""||!Number.isFinite(e))throw new ke(`Invalid unit value ${t}`);return e}function Gn(t,e){const n={};for(const s in t)if(jt(t,s)){const r=t[s];if(r==null)continue;n[e(s)]=mo(r)}return n}function ln(t,e){const n=Math.trunc(Math.abs(t/60)),s=Math.trunc(Math.abs(t%60)),r=t>=0?"+":"-";switch(e){case"short":return`${r}${me(n,2)}:${me(s,2)}`;case"narrow":return`${r}${n}${s>0?`:${s}`:""}`;case"techie":return`${r}${me(n,2)}${me(s,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function rs(t){return Al(t,["hour","minute","second","millisecond"])}const Dl=["January","February","March","April","May","June","July","August","September","October","November","December"],po=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Cl=["J","F","M","A","M","J","J","A","S","O","N","D"];function yo(t){switch(t){case"narrow":return[...Cl];case"short":return[...po];case"long":return[...Dl];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const go=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],wo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Fl=["M","T","W","T","F","S","S"];function _o(t){switch(t){case"narrow":return[...Fl];case"short":return[...wo];case"long":return[...go];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Eo=["AM","PM"],$l=["Before Christ","Anno Domini"],Ml=["BC","AD"],Pl=["B","A"];function vo(t){switch(t){case"narrow":return[...Pl];case"short":return[...Ml];case"long":return[...$l];default:return null}}function Ll(t){return Eo[t.hour<12?0:1]}function Vl(t,e){return _o(e)[t.weekday-1]}function Ul(t,e){return yo(e)[t.month-1]}function Wl(t,e){return vo(e)[t.year<0?0:1]}function jl(t,e,n="always",s=!1){const r={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&i){const p=t==="days";switch(e){case 1:return p?"tomorrow":`next ${r[t][0]}`;case-1:return p?"yesterday":`last ${r[t][0]}`;case 0:return p?"today":`this ${r[t][0]}`}}const o=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=r[t],d=s?l?c[1]:c[2]||c[1]:l?r[t][0]:t;return o?`${a} ${d} ago`:`in ${a} ${d}`}function Xr(t,e){let n="";for(const s of t)s.literal?n+=s.val:n+=e(s.val);return n}const Zl={D:qn,DD:Pi,DDD:Li,DDDD:Vi,t:Ui,tt:Wi,ttt:ji,tttt:Zi,T:zi,TT:qi,TTT:Bi,TTTT:Hi,f:Gi,ff:Ji,fff:Ki,ffff:eo,F:Yi,FF:Qi,FFF:Xi,FFFF:to};class Re{static create(e,n={}){return new Re(e,n)}static parseFormat(e){let n=null,s="",r=!1;const i=[];for(let o=0;o<e.length;o++){const a=e.charAt(o);a==="'"?((s.length>0||r)&&i.push({literal:r||/^\s+$/.test(s),val:s===""?"'":s}),n=null,s="",r=!r):r||a===n?s+=a:(s.length>0&&i.push({literal:/^\s+$/.test(s),val:s}),s=a,n=a)}return s.length>0&&i.push({literal:r||/^\s+$/.test(s),val:s}),i}static macroTokenToFormatOpts(e){return Zl[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0,s=void 0){if(this.opts.forceSimple)return me(e,n);const r={...this.opts};return n>0&&(r.padTo=n),s&&(r.signDisplay=s),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){const s=this.loc.listingMode()==="en",r=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(f,g)=>this.loc.extract(e,f,g),o=f=>e.isOffsetFixed&&e.offset===0&&f.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,f.format):"",a=()=>s?Ll(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(f,g)=>s?Ul(e,f):i(g?{month:f}:{month:f,day:"numeric"},"month"),c=(f,g)=>s?Vl(e,f):i(g?{weekday:f}:{weekday:f,month:"long",day:"numeric"},"weekday"),d=f=>{const g=Re.macroTokenToFormatOpts(f);return g?this.formatWithSystemDefault(e,g):f},p=f=>s?Wl(e,f):i({era:f},"era"),u=f=>{switch(f){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return o({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return o({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return o({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return r?i({day:"numeric"},"day"):this.num(e.day);case"dd":return r?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return r?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return r?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return r?i({month:"numeric"},"month"):this.num(e.month);case"MM":return r?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return r?i({year:"numeric"},"year"):this.num(e.year);case"yy":return r?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return r?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return r?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return p("short");case"GG":return p("long");case"GGGGG":return p("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return d(f)}};return Xr(Re.parseFormat(n),u)}formatDurationFromString(e,n){const s=this.opts.signMode==="negativeLargestOnly"?-1:1,r=d=>{switch(d[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},i=(d,p)=>u=>{const f=r(u);if(f){const g=p.isNegativeDuration&&f!==p.largestUnit?s:1;let k;return this.opts.signMode==="negativeLargestOnly"&&f!==p.largestUnit?k="never":this.opts.signMode==="all"?k="always":k="auto",this.num(d.get(f)*g,u.length,k)}else return u},o=Re.parseFormat(n),a=o.reduce((d,{literal:p,val:u})=>p?d:d.concat(u),[]),l=e.shiftTo(...a.map(r).filter(d=>d)),c={isNegativeDuration:l<0,largestUnit:Object.keys(l.values)[0]};return Xr(o,i(l,c))}}const Oo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Zt(...t){const e=t.reduce((n,s)=>n+s.source,"");return RegExp(`^${e}$`)}function zt(...t){return e=>t.reduce(([n,s,r],i)=>{const[o,a,l]=i(e,r);return[{...n,...o},a||s,l]},[{},null,1]).slice(0,2)}function qt(t,...e){if(t==null)return[null,null];for(const[n,s]of e){const r=n.exec(t);if(r)return s(r)}return[null,null]}function ko(...t){return(e,n)=>{const s={};let r;for(r=0;r<t.length;r++)s[t[r]]=at(e[n+r]);return[s,null,n+r]}}const bo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,zl=`(?:${bo.source}?(?:\\[(${Oo.source})\\])?)?`,sr=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Ro=RegExp(`${sr.source}${zl}`),rr=RegExp(`(?:[Tt]${Ro.source})?`),ql=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Bl=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Hl=/(\d{4})-?(\d{3})/,Gl=ko("weekYear","weekNumber","weekDay"),Yl=ko("year","ordinal"),Jl=/(\d{4})-(\d\d)-(\d\d)/,To=RegExp(`${sr.source} ?(?:${bo.source}|(${Oo.source}))?`),Ql=RegExp(`(?: ${To.source})?`);function Mt(t,e,n){const s=t[e];return G(s)?n:at(s)}function Kl(t,e){return[{year:Mt(t,e),month:Mt(t,e+1,1),day:Mt(t,e+2,1)},null,e+3]}function Bt(t,e){return[{hours:Mt(t,e,0),minutes:Mt(t,e+1,0),seconds:Mt(t,e+2,0),milliseconds:tr(t[e+3])},null,e+4]}function wn(t,e){const n=!t[e]&&!t[e+1],s=ss(t[e+1],t[e+2]),r=n?null:Te.instance(s);return[{},r,e+3]}function _n(t,e){const n=t[e]?st.create(t[e]):null;return[{},n,e+1]}const Xl=RegExp(`^T?${sr.source}$`),ec=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function tc(t){const[e,n,s,r,i,o,a,l,c]=t,d=e[0]==="-",p=l&&l[0]==="-",u=(f,g=!1)=>f!==void 0&&(g||f&&d)?-f:f;return[{years:u(pt(n)),months:u(pt(s)),weeks:u(pt(r)),days:u(pt(i)),hours:u(pt(o)),minutes:u(pt(a)),seconds:u(pt(l),l==="-0"),milliseconds:u(tr(c),p)}]}const nc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ir(t,e,n,s,r,i,o){const a={year:e.length===2?Zs(at(e)):at(e),month:po.indexOf(n)+1,day:at(s),hour:at(r),minute:at(i)};return o&&(a.second=at(o)),t&&(a.weekday=t.length>3?go.indexOf(t)+1:wo.indexOf(t)+1),a}const sc=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function rc(t){const[,e,n,s,r,i,o,a,l,c,d,p]=t,u=ir(e,r,s,n,i,o,a);let f;return l?f=nc[l]:c?f=0:f=ss(d,p),[u,new Te(f)]}function ic(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const oc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,ac=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,lc=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function ei(t){const[,e,n,s,r,i,o,a]=t;return[ir(e,r,s,n,i,o,a),Te.utcInstance]}function cc(t){const[,e,n,s,r,i,o,a]=t;return[ir(e,a,n,s,r,i,o),Te.utcInstance]}const uc=Zt(ql,rr),dc=Zt(Bl,rr),fc=Zt(Hl,rr),hc=Zt(Ro),So=zt(Kl,Bt,wn,_n),mc=zt(Gl,Bt,wn,_n),pc=zt(Yl,Bt,wn,_n),yc=zt(Bt,wn,_n);function gc(t){return qt(t,[uc,So],[dc,mc],[fc,pc],[hc,yc])}function wc(t){return qt(ic(t),[sc,rc])}function _c(t){return qt(t,[oc,ei],[ac,ei],[lc,cc])}function Ec(t){return qt(t,[ec,tc])}const vc=zt(Bt);function Oc(t){return qt(t,[Xl,vc])}const kc=Zt(Jl,Ql),bc=Zt(To),Rc=zt(Bt,wn,_n);function Tc(t){return qt(t,[kc,So],[bc,Rc])}const ti="Invalid Duration",Io={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Sc={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...Io},Fe=146097/400,xt=146097/4800,Ic={years:{quarters:4,months:12,weeks:Fe/7,days:Fe,hours:Fe*24,minutes:Fe*24*60,seconds:Fe*24*60*60,milliseconds:Fe*24*60*60*1e3},quarters:{months:3,weeks:Fe/28,days:Fe/4,hours:Fe*24/4,minutes:Fe*24*60/4,seconds:Fe*24*60*60/4,milliseconds:Fe*24*60*60*1e3/4},months:{weeks:xt/7,days:xt,hours:xt*24,minutes:xt*24*60,seconds:xt*24*60*60,milliseconds:xt*24*60*60*1e3},...Io},Et=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],xc=Et.slice(0).reverse();function Ke(t,e,n=!1){const s={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new ne(s)}function xo(t,e){let n=e.milliseconds??0;for(const s of xc.slice(1))e[s]&&(n+=e[s]*t[s].milliseconds);return n}function ni(t,e){const n=xo(t,e)<0?-1:1;Et.reduceRight((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]*n,o=t[r][s],a=Math.floor(i/o);e[r]+=a*n,e[s]-=a*o*n}return r},null),Et.reduce((s,r)=>{if(G(e[r]))return s;if(s){const i=e[s]%1;e[s]-=i,e[r]+=i*t[s][r]}return r},null)}function si(t){const e={};for(const[n,s]of Object.entries(t))s!==0&&(e[n]=s);return e}class ne{constructor(e){const n=e.conversionAccuracy==="longterm"||!1;let s=n?Ic:Sc;e.matrix&&(s=e.matrix),this.values=e.values,this.loc=e.loc||ie.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=s,this.isLuxonDuration=!0}static fromMillis(e,n){return ne.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new ke(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ne({values:Gn(e,ne.normalizeUnit),loc:ie.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(dt(e))return ne.fromMillis(e);if(ne.isDuration(e))return e;if(typeof e=="object")return ne.fromObject(e);throw new ke(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){const[s]=Ec(e);return s?ne.fromObject(s,n):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){const[s]=Oc(e);return s?ne.fromObject(s,n):ne.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new ke("need to specify a reason the Duration is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new tl(s);return new ne({invalid:s})}static normalizeUnit(e){const n={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!n)throw new Mi(e);return n}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,n={}){const s={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?Re.create(this.loc,s).formatDurationFromString(this,e):ti}toHuman(e={}){if(!this.isValid)return ti;const n=e.showZeros!==!1,s=Et.map(r=>{const i=this.values[r];return G(i)||i===0&&!n?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(i)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(s)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=nr(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},V.fromMillis(n,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?xo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e),s={};for(const r of Et)(jt(n.values,r)||jt(this.values,r))&&(s[r]=n.get(r)+this.get(r));return Ke(this,{values:s},!0)}minus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;const n={};for(const s of Object.keys(this.values))n[s]=mo(e(this.values[s],s));return Ke(this,{values:n},!0)}get(e){return this[ne.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const n={...this.values,...Gn(e,ne.normalizeUnit)};return Ke(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:s,matrix:r}={}){const o={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:r,conversionAccuracy:s};return Ke(this,o)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return ni(this.matrix,e),Ke(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=si(this.normalize().shiftToAll().toObject());return Ke(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(o=>ne.normalizeUnit(o));const n={},s={},r=this.toObject();let i;for(const o of Et)if(e.indexOf(o)>=0){i=o;let a=0;for(const c in s)a+=this.matrix[c][o]*s[c],s[c]=0;dt(r[o])&&(a+=r[o]);const l=Math.trunc(a);n[o]=l,s[o]=(a*1e3-l*1e3)/1e3}else dt(r[o])&&(s[o]=r[o]);for(const o in s)s[o]!==0&&(n[i]+=o===i?s[o]:s[o]/this.matrix[i][o]);return ni(this.matrix,n),Ke(this,{values:n},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return Ke(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=si(this.values);return Ke(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function n(s,r){return s===void 0||s===0?r===void 0||r===0:s===r}for(const s of Et)if(!n(this.values[s],e.values[s]))return!1;return!0}}const At="Invalid Interval";function Ac(t,e){return!t||!t.isValid?ue.invalid("missing or invalid start"):!e||!e.isValid?ue.invalid("missing or invalid end"):e<t?ue.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}class ue{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new ke("need to specify a reason the Interval is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new el(s);return new ue({invalid:s})}static fromDateTimes(e,n){const s=Qt(e),r=Qt(n),i=Ac(s,r);return i??new ue({start:s,end:r})}static after(e,n){const s=ne.fromDurationLike(n),r=Qt(e);return ue.fromDateTimes(r,r.plus(s))}static before(e,n){const s=ne.fromDurationLike(n),r=Qt(e);return ue.fromDateTimes(r.minus(s),r)}static fromISO(e,n){const[s,r]=(e||"").split("/",2);if(s&&r){let i,o;try{i=V.fromISO(s,n),o=i.isValid}catch{o=!1}let a,l;try{a=V.fromISO(r,n),l=a.isValid}catch{l=!1}if(o&&l)return ue.fromDateTimes(i,a);if(o){const c=ne.fromISO(r,n);if(c.isValid)return ue.after(i,c)}else if(l){const c=ne.fromISO(s,n);if(c.isValid)return ue.before(a,c)}}return ue.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",n){if(!this.isValid)return NaN;const s=this.start.startOf(e,n);let r;return n?.useLocaleWeeks?r=this.end.reconfigure({locale:s.locale}):r=this.end,r=r.startOf(e,n),Math.floor(r.diff(s,e).get(e))+(r.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:n}={}){return this.isValid?ue.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];const n=e.map(Qt).filter(o=>this.contains(o)).sort((o,a)=>o.toMillis()-a.toMillis()),s=[];let{s:r}=this,i=0;for(;r<this.e;){const o=n[i]||this.e,a=+o>+this.e?this.e:o;s.push(ue.fromDateTimes(r,a)),r=a,i+=1}return s}splitBy(e){const n=ne.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s}=this,r=1,i;const o=[];for(;s<this.e;){const a=this.start.plus(n.mapUnits(l=>l*r));i=+a>+this.e?this.e:a,o.push(ue.fromDateTimes(s,i)),s=i,r+=1}return o}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const n=this.s>e.s?this.s:e.s,s=this.e<e.e?this.e:e.e;return n>=s?null:ue.fromDateTimes(n,s)}union(e){if(!this.isValid)return this;const n=this.s<e.s?this.s:e.s,s=this.e>e.e?this.e:e.e;return ue.fromDateTimes(n,s)}static merge(e){const[n,s]=e.sort((r,i)=>r.s-i.s).reduce(([r,i],o)=>i?i.overlaps(o)||i.abutsStart(o)?[r,i.union(o)]:[r.concat([i]),o]:[r,o],[[],null]);return s&&n.push(s),n}static xor(e){let n=null,s=0;const r=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),o=Array.prototype.concat(...i),a=o.sort((l,c)=>l.time-c.time);for(const l of a)s+=l.type==="s"?1:-1,s===1?n=l.time:(n&&+n!=+l.time&&r.push(ue.fromDateTimes(n,l.time)),n=null);return ue.merge(r)}difference(...e){return ue.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:At}[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=qn,n={}){return this.isValid?Re.create(this.s.loc.clone(n),e).formatInterval(this):At}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:At}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:At}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:At}toFormat(e,{separator:n=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:At}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):ne.invalid(this.invalidReason)}mapEndpoints(e){return ue.fromDateTimes(e(this.s),e(this.e))}}class kn{static hasDST(e=de.defaultZone){const n=V.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return st.isValidZone(e)}static normalizeZone(e){return lt(e,de.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||ie.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(n,s,i)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null,outputCalendar:i="gregory"}={}){return(r||ie.create(n,s,i)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(n,s,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:s=null,locObj:r=null}={}){return(r||ie.create(n,s,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ie.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return ie.create(n,null,"gregory").eras(e)}static features(){return{relative:uo(),localeWeek:fo()}}}function ri(t,e){const n=r=>r.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),s=n(e)-n(t);return Math.floor(ne.fromMillis(s).as("days"))}function Nc(t,e,n){const s=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{const d=ri(l,c);return(d-d%7)/7}],["days",ri]],r={},i=t;let o,a;for(const[l,c]of s)n.indexOf(l)>=0&&(o=l,r[l]=c(t,e),a=i.plus(r),a>e?(r[l]--,t=i.plus(r),t>e&&(a=t,r[l]--,t=i.plus(r))):t=a);return[t,r,a,o]}function Dc(t,e,n,s){let[r,i,o,a]=Nc(t,e,n);const l=e-r,c=n.filter(p=>["hours","minutes","seconds","milliseconds"].indexOf(p)>=0);c.length===0&&(o<e&&(o=r.plus({[a]:1})),o!==r&&(i[a]=(i[a]||0)+l/(o-r)));const d=ne.fromObject(i,s);return c.length>0?ne.fromMillis(l,s).shiftTo(...c).plus(d):d}const Cc="missing Intl.DateTimeFormat.formatToParts support";function re(t,e=n=>n){return{regex:t,deser:([n])=>e(kl(n))}}const Fc=" ",Ao=`[ ${Fc}]`,No=new RegExp(Ao,"g");function $c(t){return t.replace(/\./g,"\\.?").replace(No,Ao)}function ii(t){return t.replace(/\./g,"").replace(No," ").toLowerCase()}function Ve(t,e){return t===null?null:{regex:RegExp(t.map($c).join("|")),deser:([n])=>t.findIndex(s=>ii(n)===ii(s))+e}}function oi(t,e){return{regex:t,deser:([,n,s])=>ss(n,s),groups:e}}function bn(t){return{regex:t,deser:([e])=>e}}function Mc(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Pc(t,e){const n=Le(e),s=Le(e,"{2}"),r=Le(e,"{3}"),i=Le(e,"{4}"),o=Le(e,"{6}"),a=Le(e,"{1,2}"),l=Le(e,"{1,3}"),c=Le(e,"{1,6}"),d=Le(e,"{1,9}"),p=Le(e,"{2,4}"),u=Le(e,"{4,6}"),f=y=>({regex:RegExp(Mc(y.val)),deser:([E])=>E,literal:!0}),k=(y=>{if(t.literal)return f(y);switch(y.val){case"G":return Ve(e.eras("short"),0);case"GG":return Ve(e.eras("long"),0);case"y":return re(c);case"yy":return re(p,Zs);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 Ve(e.months("short",!0),1);case"MMMM":return Ve(e.months("long",!0),1);case"L":return re(a);case"LL":return re(s);case"LLL":return Ve(e.months("short",!1),1);case"LLLL":return Ve(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 bn(d);case"uu":return bn(a);case"uuu":return re(n);case"a":return Ve(e.meridiems(),0);case"kkkk":return re(i);case"kk":return re(p,Zs);case"W":return re(a);case"WW":return re(s);case"E":case"c":return re(n);case"EEE":return Ve(e.weekdays("short",!1),1);case"EEEE":return Ve(e.weekdays("long",!1),1);case"ccc":return Ve(e.weekdays("short",!0),1);case"cccc":return Ve(e.weekdays("long",!0),1);case"Z":case"ZZ":return oi(new RegExp(`([+-]${a.source})(?::(${s.source}))?`),2);case"ZZZ":return oi(new RegExp(`([+-]${a.source})(${s.source})?`),2);case"z":return bn(/[a-z_+-/]{1,256}?/i);case" ":return bn(/[^\S\n\r]/);default:return f(y)}})(t)||{invalidReason:Cc};return k.token=t,k}const Lc={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Vc(t,e,n){const{type:s,value:r}=t;if(s==="literal"){const l=/^\s+$/.test(r);return{literal:!l,val:l?" ":r}}const i=e[s];let o=s;s==="hour"&&(e.hour12!=null?o=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?o="hour12":o="hour24":o=n.hour12?"hour12":"hour24");let a=Lc[o];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function Uc(t){return[`^${t.map(n=>n.regex).reduce((n,s)=>`${n}(${s.source})`,"")}$`,t]}function Wc(t,e,n){const s=t.match(e);if(s){const r={};let i=1;for(const o in n)if(jt(n,o)){const a=n[o],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(r[a.token.val[0]]=a.deser(s.slice(i,i+l))),i+=l}return[s,r]}else return[s,{}]}function jc(t){const e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let n=null,s;return G(t.z)||(n=st.create(t.z)),G(t.Z)||(n||(n=new Te(t.Z)),s=t.Z),G(t.q)||(t.M=(t.q-1)*3+1),G(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),G(t.u)||(t.S=tr(t.u)),[Object.keys(t).reduce((i,o)=>{const a=e(o);return a&&(i[a]=t[o]),i},{}),n,s]}let ps=null;function Zc(){return ps||(ps=V.fromMillis(1555555555555)),ps}function zc(t,e){if(t.literal)return t;const n=Re.macroTokenToFormatOpts(t.val),s=$o(n,e);return s==null||s.includes(void 0)?t:s}function Do(t,e){return Array.prototype.concat(...t.map(n=>zc(n,e)))}class Co{constructor(e,n){if(this.locale=e,this.format=n,this.tokens=Do(Re.parseFormat(n),e),this.units=this.tokens.map(s=>Pc(s,e)),this.disqualifyingUnit=this.units.find(s=>s.invalidReason),!this.disqualifyingUnit){const[s,r]=Uc(this.units);this.regex=RegExp(s,"i"),this.handlers=r}}explainFromTokens(e){if(this.isValid){const[n,s]=Wc(e,this.regex,this.handlers),[r,i,o]=s?jc(s):[null,null,void 0];if(jt(s,"a")&&jt(s,"H"))throw new Ct("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:n,matches:s,result:r,zone:i,specificOffset:o}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function Fo(t,e,n){return new Co(t,n).explainFromTokens(e)}function qc(t,e,n){const{result:s,zone:r,specificOffset:i,invalidReason:o}=Fo(t,e,n);return[s,r,i,o]}function $o(t,e){if(!t)return null;const s=Re.create(e,t).dtFormatter(Zc()),r=s.formatToParts(),i=s.resolvedOptions();return r.map(o=>Vc(o,t,i))}const ys="Invalid DateTime",ai=864e13;function tn(t){return new Ue("unsupported zone",`the zone "${t.name}" is not supported`)}function gs(t){return t.weekData===null&&(t.weekData=Bn(t.c)),t.weekData}function ws(t){return t.localWeekData===null&&(t.localWeekData=Bn(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function yt(t,e){const n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new V({...n,...e,old:n})}function Mo(t,e,n){let s=t-e*60*1e3;const r=n.offset(s);if(e===r)return[s,e];s-=(r-e)*60*1e3;const i=n.offset(s);return r===i?[s,r]:[t-Math.min(r,i)*60*1e3,Math.max(r,i)]}function Rn(t,e){t+=e*60*1e3;const n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function xn(t,e,n){return Mo(ns(t),e,n)}function li(t,e){const n=t.o,s=t.c.year+Math.trunc(e.years),r=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...t.c,year:s,month:r,day:Math.min(t.c.day,Hn(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=ns(i);let[l,c]=Mo(a,n,t.zone);return o!==0&&(l+=o,c=t.zone.offset(l)),{ts:l,o:c}}function Nt(t,e,n,s,r,i){const{setZone:o,zone:a}=n;if(t&&Object.keys(t).length!==0||e){const l=e||a,c=V.fromObject(t,{...n,zone:l,specificOffset:i});return o?c:c.setZone(a)}else return V.invalid(new Ue("unparsable",`the input "${r}" can't be parsed as ${s}`))}function Tn(t,e,n=!0){return t.isValid?Re.create(ie.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function _s(t,e,n){const s=t.c.year>9999||t.c.year<0;let r="";if(s&&t.c.year>=0&&(r+="+"),r+=me(t.c.year,s?6:4),n==="year")return r;if(e){if(r+="-",r+=me(t.c.month),n==="month")return r;r+="-"}else if(r+=me(t.c.month),n==="month")return r;return r+=me(t.c.day),r}function ci(t,e,n,s,r,i,o){let a=!n||t.c.millisecond!==0||t.c.second!==0,l="";switch(o){case"day":case"month":case"year":break;default:if(l+=me(t.c.hour),o==="hour")break;if(e){if(l+=":",l+=me(t.c.minute),o==="minute")break;a&&(l+=":",l+=me(t.c.second))}else{if(l+=me(t.c.minute),o==="minute")break;a&&(l+=me(t.c.second))}if(o==="second")break;a&&(!s||t.c.millisecond!==0)&&(l+=".",l+=me(t.c.millisecond,3))}return r&&(t.isOffsetFixed&&t.offset===0&&!i?l+="Z":t.o<0?(l+="-",l+=me(Math.trunc(-t.o/60)),l+=":",l+=me(Math.trunc(-t.o%60))):(l+="+",l+=me(Math.trunc(t.o/60)),l+=":",l+=me(Math.trunc(t.o%60)))),i&&(l+="["+t.zone.ianaName+"]"),l}const Po={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Bc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Hc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},An=["year","month","day","hour","minute","second","millisecond"],Gc=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Yc=["year","ordinal","hour","minute","second","millisecond"];function Nn(t){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new Mi(t);return e}function ui(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Nn(t)}}function Jc(t){if(nn===void 0&&(nn=de.now()),t.type!=="iana")return t.offset(nn);const e=t.name;let n=zs.get(e);return n===void 0&&(n=t.offset(nn),zs.set(e,n)),n}function di(t,e){const n=lt(e.zone,de.defaultZone);if(!n.isValid)return V.invalid(tn(n));const s=ie.fromObject(e);let r,i;if(G(t.year))r=de.now();else{for(const l of An)G(t[l])&&(t[l]=Po[l]);const o=lo(t)||co(t);if(o)return V.invalid(o);const a=Jc(n);[r,i]=xn(t,a,n)}return new V({ts:r,zone:n,loc:s,o:i})}function fi(t,e,n){const s=G(n.round)?!0:n.round,r=G(n.rounding)?"trunc":n.rounding,i=(a,l)=>(a=nr(a,s||n.calendary?0:2,n.calendary?"round":r),e.loc.clone(n).relFormatter(n).format(a,l)),o=a=>n.calendary?e.hasSame(t,a)?0:e.startOf(a).diff(t.startOf(a),a).get(a):e.diff(t,a).get(a);if(n.unit)return i(o(n.unit),n.unit);for(const a of n.units){const l=o(a);if(Math.abs(l)>=1)return i(l,a)}return i(t>e?-0:0,n.units[n.units.length-1])}function hi(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}let nn;const zs=new Map;class V{constructor(e){const n=e.zone||de.defaultZone;let s=e.invalid||(Number.isNaN(e.ts)?new Ue("invalid input"):null)||(n.isValid?null:tn(n));this.ts=G(e.ts)?de.now():e.ts;let r=null,i=null;if(!s)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[r,i]=[e.old.c,e.old.o];else{const a=dt(e.o)&&!e.old?e.o:n.offset(this.ts);r=Rn(this.ts,a),s=Number.isNaN(r.year)?new Ue("invalid input"):null,r=s?null:r,i=s?null:a}this._zone=n,this.loc=e.loc||ie.create(),this.invalid=s,this.weekData=null,this.localWeekData=null,this.c=r,this.o=i,this.isLuxonDateTime=!0}static now(){return new V({})}static local(){const[e,n]=hi(arguments),[s,r,i,o,a,l,c]=n;return di({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static utc(){const[e,n]=hi(arguments),[s,r,i,o,a,l,c]=n;return e.zone=Te.utcInstance,di({year:s,month:r,day:i,hour:o,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,n={}){const s=Il(e)?e.valueOf():NaN;if(Number.isNaN(s))return V.invalid("invalid input");const r=lt(n.zone,de.defaultZone);return r.isValid?new V({ts:s,zone:r,loc:ie.fromObject(n)}):V.invalid(tn(r))}static fromMillis(e,n={}){if(dt(e))return e<-ai||e>ai?V.invalid("Timestamp out of range"):new V({ts:e,zone:lt(n.zone,de.defaultZone),loc:ie.fromObject(n)});throw new ke(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(dt(e))return new V({ts:e*1e3,zone:lt(n.zone,de.defaultZone),loc:ie.fromObject(n)});throw new ke("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};const s=lt(n.zone,de.defaultZone);if(!s.isValid)return V.invalid(tn(s));const r=ie.fromObject(n),i=Gn(e,ui),{minDaysInFirstWeek:o,startOfWeek:a}=Jr(i,r),l=de.now(),c=G(n.specificOffset)?s.offset(l):n.specificOffset,d=!G(i.ordinal),p=!G(i.year),u=!G(i.month)||!G(i.day),f=p||u,g=i.weekYear||i.weekNumber;if((f||d)&&g)throw new Ct("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(u&&d)throw new Ct("Can't mix ordinal dates with month/day");const k=g||i.weekday&&!f;let y,E,w=Rn(l,c);k?(y=Gc,E=Bc,w=Bn(w,o,a)):d?(y=Yc,E=Hc,w=ms(w)):(y=An,E=Po);let A=!1;for(const h of y){const x=i[h];G(x)?A?i[h]=E[h]:i[h]=w[h]:A=!0}const O=k?Rl(i,o,a):d?Tl(i):lo(i),_=O||co(i);if(_)return V.invalid(_);const I=k?Gr(i,o,a):d?Yr(i):i,[j,v]=xn(I,c,s),U=new V({ts:j,zone:s,o:v,loc:r});return i.weekday&&f&&e.weekday!==U.weekday?V.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${U.toISO()}`):U.isValid?U:V.invalid(U.invalid)}static fromISO(e,n={}){const[s,r]=gc(e);return Nt(s,r,n,"ISO 8601",e)}static fromRFC2822(e,n={}){const[s,r]=wc(e);return Nt(s,r,n,"RFC 2822",e)}static fromHTTP(e,n={}){const[s,r]=_c(e);return Nt(s,r,n,"HTTP",n)}static fromFormat(e,n,s={}){if(G(e)||G(n))throw new ke("fromFormat requires an input string and a format");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0}),[a,l,c,d]=qc(o,e,n);return d?V.invalid(d):Nt(a,l,s,`format ${n}`,e,c)}static fromString(e,n,s={}){return V.fromFormat(e,n,s)}static fromSQL(e,n={}){const[s,r]=Tc(e);return Nt(s,r,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new ke("need to specify a reason the DateTime is invalid");const s=e instanceof Ue?e:new Ue(e,n);if(de.throwOnInvalid)throw new Xa(s);return new V({invalid:s})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){const s=$o(e,ie.fromObject(n));return s?s.map(r=>r?r.val:null).join(""):null}static expandFormat(e,n={}){return Do(Re.parseFormat(e),ie.fromObject(n)).map(r=>r.val).join("")}static resetCache(){nn=void 0,zs.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?gs(this).weekYear:NaN}get weekNumber(){return this.isValid?gs(this).weekNumber:NaN}get weekday(){return this.isValid?gs(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ws(this).weekday:NaN}get localWeekNumber(){return this.isValid?ws(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ws(this).weekYear:NaN}get ordinal(){return this.isValid?ms(this.c).ordinal:NaN}get monthShort(){return this.isValid?kn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?kn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?kn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?kn.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,n=6e4,s=ns(this.c),r=this.zone.offset(s-e),i=this.zone.offset(s+e),o=this.zone.offset(s-r*n),a=this.zone.offset(s-i*n);if(o===a)return[this];const l=s-o*n,c=s-a*n,d=Rn(l,o),p=Rn(c,a);return d.hour===p.hour&&d.minute===p.minute&&d.second===p.second&&d.millisecond===p.millisecond?[yt(this,{ts:l}),yt(this,{ts:c})]:[this]}get isInLeapYear(){return gn(this.year)}get daysInMonth(){return Hn(this.year,this.month)}get daysInYear(){return this.isValid?$t(this.year):NaN}get weeksInWeekYear(){return this.isValid?fn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?fn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:n,numberingSystem:s,calendar:r}=Re.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:s,outputCalendar:r}}toUTC(e=0,n={}){return this.setZone(Te.instance(e),n)}toLocal(){return this.setZone(de.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:s=!1}={}){if(e=lt(e,de.defaultZone),e.equals(this.zone))return this;if(e.isValid){let r=this.ts;if(n||s){const i=e.offset(this.ts),o=this.toObject();[r]=xn(o,i,e)}return yt(this,{ts:r,zone:e})}else return V.invalid(tn(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:s}={}){const r=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:s});return yt(this,{loc:r})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const n=Gn(e,ui),{minDaysInFirstWeek:s,startOfWeek:r}=Jr(n,this.loc),i=!G(n.weekYear)||!G(n.weekNumber)||!G(n.weekday),o=!G(n.ordinal),a=!G(n.year),l=!G(n.month)||!G(n.day),c=a||l,d=n.weekYear||n.weekNumber;if((c||o)&&d)throw new Ct("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&o)throw new Ct("Can't mix ordinal dates with month/day");let p;i?p=Gr({...Bn(this.c,s,r),...n},s,r):G(n.ordinal)?(p={...this.toObject(),...n},G(n.day)&&(p.day=Math.min(Hn(p.year,p.month),p.day))):p=Yr({...ms(this.c),...n});const[u,f]=xn(p,this.o,this.zone);return yt(this,{ts:u,o:f})}plus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e);return yt(this,li(this,n))}minus(e){if(!this.isValid)return this;const n=ne.fromDurationLike(e).negate();return yt(this,li(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;const s={},r=ne.normalizeUnit(e);switch(r){case"years":s.month=1;case"quarters":case"months":s.day=1;case"weeks":case"days":s.hour=0;case"hours":s.minute=0;case"minutes":s.second=0;case"seconds":s.millisecond=0;break}if(r==="weeks")if(n){const i=this.loc.getStartOfWeek(),{weekday:o}=this;o<i&&(s.weekNumber=this.weekNumber-1),s.weekday=i}else s.weekday=1;if(r==="quarters"){const i=Math.ceil(this.month/3);s.month=(i-1)*3+1}return this.set(s)}endOf(e,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?Re.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):ys}toLocaleString(e=qn,n={}){return this.isValid?Re.create(this.loc.clone(n),e).formatDateTime(this):ys}toLocaleParts(e={}){return this.isValid?Re.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:s=!1,includeOffset:r=!0,extendedZone:i=!1,precision:o="milliseconds"}={}){if(!this.isValid)return null;o=Nn(o);const a=e==="extended";let l=_s(this,a,o);return An.indexOf(o)>=3&&(l+="T"),l+=ci(this,a,n,s,r,i,o),l}toISODate({format:e="extended",precision:n="day"}={}){return this.isValid?_s(this,e==="extended",Nn(n)):null}toISOWeekDate(){return Tn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:s=!0,includePrefix:r=!1,extendedZone:i=!1,format:o="extended",precision:a="milliseconds"}={}){return this.isValid?(a=Nn(a),(r&&An.indexOf(a)>=3?"T":"")+ci(this,o==="extended",n,e,s,i,a)):null}toRFC2822(){return Tn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Tn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?_s(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:s=!0}={}){let r="HH:mm:ss.SSS";return(n||e)&&(s&&(r+=" "),n?r+="z":e&&(r+="ZZ")),Tn(this,r,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():ys}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",s={}){if(!this.isValid||!e.isValid)return ne.invalid("created by diffing an invalid DateTime");const r={locale:this.locale,numberingSystem:this.numberingSystem,...s},i=xl(n).map(ne.normalizeUnit),o=e.valueOf()>this.valueOf(),a=o?this:e,l=o?e:this,c=Dc(a,l,i,r);return o?c.negate():c}diffNow(e="milliseconds",n={}){return this.diff(V.now(),e,n)}until(e){return this.isValid?ue.fromDateTimes(this,e):this}hasSame(e,n,s){if(!this.isValid)return!1;const r=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n,s)<=r&&r<=i.endOf(n,s)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const n=e.base||V.fromObject({},{zone:this.zone}),s=e.padding?this<n?-e.padding:e.padding:0;let r=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(r=e.unit,i=void 0),fi(n,this.plus(s),{...e,numeric:"always",units:r,unit:i})}toRelativeCalendar(e={}){return this.isValid?fi(e.base||V.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(V.isDateTime))throw new ke("min requires all arguments be DateTimes");return Qr(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(V.isDateTime))throw new ke("max requires all arguments be DateTimes");return Qr(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,s={}){const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});return Fo(o,e,n)}static fromStringExplain(e,n,s={}){return V.fromFormatExplain(e,n,s)}static buildFormatParser(e,n={}){const{locale:s=null,numberingSystem:r=null}=n,i=ie.fromOpts({locale:s,numberingSystem:r,defaultToEN:!0});return new Co(i,e)}static fromFormatParser(e,n,s={}){if(G(e)||G(n))throw new ke("fromFormatParser requires an input string and a format parser");const{locale:r=null,numberingSystem:i=null}=s,o=ie.fromOpts({locale:r,numberingSystem:i,defaultToEN:!0});if(!o.equals(n.locale))throw new ke(`fromFormatParser called with a locale of ${o}, but the format parser was created for ${n.locale}`);const{result:a,zone:l,specificOffset:c,invalidReason:d}=n.explainFromTokens(e);return d?V.invalid(d):Nt(a,l,s,`format ${n.format}`,e,c)}static get DATE_SHORT(){return qn}static get DATE_MED(){return Pi}static get DATE_MED_WITH_WEEKDAY(){return nl}static get DATE_FULL(){return Li}static get DATE_HUGE(){return Vi}static get TIME_SIMPLE(){return Ui}static get TIME_WITH_SECONDS(){return Wi}static get TIME_WITH_SHORT_OFFSET(){return ji}static get TIME_WITH_LONG_OFFSET(){return Zi}static get TIME_24_SIMPLE(){return zi}static get TIME_24_WITH_SECONDS(){return qi}static get TIME_24_WITH_SHORT_OFFSET(){return Bi}static get TIME_24_WITH_LONG_OFFSET(){return Hi}static get DATETIME_SHORT(){return Gi}static get DATETIME_SHORT_WITH_SECONDS(){return Yi}static get DATETIME_MED(){return Ji}static get DATETIME_MED_WITH_SECONDS(){return Qi}static get DATETIME_MED_WITH_WEEKDAY(){return sl}static get DATETIME_FULL(){return Ki}static get DATETIME_FULL_WITH_SECONDS(){return Xi}static get DATETIME_HUGE(){return eo}static get DATETIME_HUGE_WITH_SECONDS(){return to}}function Qt(t){if(V.isDateTime(t))return t;if(t&&t.valueOf&&dt(t.valueOf()))return V.fromJSDate(t);if(t&&typeof t=="object")return V.fromObject(t);throw new ke(`Unknown datetime argument: ${t}, of type ${typeof t}`)}const Qc=(t,e)=>{const n={};if(t.includeFields){const s=e.collections[t.collection];if(!s)return pn(ve());t.includeFields.forEach(r=>{const i=s.fields.find(o=>o.name===r);i?n[r]=Lo(i)?.nullable():n[r]=ve()})}return qe({Collection_Path:Tt(Ie()),...n})},Kc=(t,e,n,s)=>{let r=qe({}).catchall(Qc(t,e)),i;if(!s&&n){const o=We(t,n);i=Kt(o.admin?.skipFormRequiredValidation)}return(!t.required||i)&&(r=r.optional()),r},Xc=()=>ve().refine(t=>t===null||t&&(t.seconds!==void 0&&t.nanoseconds!==void 0||t._seconds!==void 0&&t._nanoseconds!==void 0),{message:"Must be a valid date"}),Lo=(t,e,n)=>{let s;const r=`${Kt(t.description)}
|
|
2
2
|
|
|
3
|
-
`||"";let i,o,a;if(!n&&e){const l=We(t,e);i=l.admin?.condition?.form!==void 0&&!Kt(l.admin.condition.form),o=Kt(l.admin?.skipFormRequiredValidation),a=Kt(l.admin?.image)}switch(t.type){case"String":s=Ie(),t.length&&(s=s.length(t.length,`Must be ${t.length} character(s) long`)),t.minlength&&(s=s.min(t.minlength,`Must contain at least ${t.minlength} character(s)`)),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} character(s)`)),t.email?s=s.email("Must be a valid email address"):t.uuid?s=Te([s.uuid("Must be a valid UUID"),Se("")]):t.url?s=Te([s.url("Must be a valid URL"),Se("")]):t.emoji?s=Te([s.emoji("Must be a valid emoji"),Se("")]):t.ip?s=Te([s.ip("Must be a valid IP address"),Se("")]):t.pattern&&(!n&&a?s=Te([s.regex(new RegExp(t.pattern)),s.regex(/^blob:/)],{message:"Must be a valid value"}):s=s.regex(new RegExp(t.pattern),"Must be a valid value")),t.values&&(s=Te([Zn(t.values,{message:`Must be one of the following values: ${t.values.join(", ")}`}),us()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=an(),r&&(s=s.describe(r.trim()));break;case"Number":t.autoIncrement?s=Te([us(),_t().int()],{message:"Must be a valid number"}):(s=_t({message:"Must be a valid number"}),t.min&&(s=s.min(t.min,`Must be greater than or equal to ${t.min}`)),t.max&&(s=s.max(t.max,`Must be less than or equal to ${t.max}`)),t.decimal?n?s=s.describe(`${r}Must have ${t.decimal} decimal places`):s=s.refine(l=>t.decimal?(l.toString().split(".")[1]?.length||0)<=t.decimal:!1,{message:`Must have ${t.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),t.values?(n||(s=Te([s.refine(l=>t.values?.includes(l),{message:`Must be one of the following values: ${t.values.join(", ")}`}),us()])),s=s.describe(`${r}Must be one of the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":n?(s=qe({seconds:_t(),nanoseconds:_t()}),t.min&&t.max?s=s.describe(`${r}Must be between ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)} and ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`):t.min?s=s.describe(`${r}Must be greater than or equal to ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)}`):t.max?s=s.describe(`${r}Must be less than or equal to ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Xc(),t.min&&(s=s.refine(l=>l.toMillis()>=t.min,{message:`Must be greater than or equal to ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)}`})),t.max&&(s=s.refine(l=>l.toMillis()<=t.max,{message:`Must be less than or equal to ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`})));break;case"Array":s=Tt(Ee()),t.length&&(s=s.length(t.length,`Must contain ${t.length} item(s)`)),t.minlength?s=s.min(t.minlength,`Must contain at least ${t.minlength} item(s)`):t.required&&!i&&(s=s.nonempty("Must contain at least one item")),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} item(s)`)),t.values?(n||(s=s.refine(l=>{let c=!0;return l.forEach(d=>{t.values&&!t.values.includes(d)&&(c=!1)}),c},{message:`Must only contain the following values: ${t.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())),t.nullable&&(s=s.nullable());break;case"Map":t.required&&!i?n?s=qe({}).catchall(Ee()).describe(`${r}Must be an object. Must contain at least one object property.`):s=pn(Ee()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=qe({}).catchall(Ee()).describe(`${r}Must be an object`);break;case"Computed":s=Ee()}return(!t.required||i||o)&&(s=s.optional()),s},eu=(t,e,n,s,r)=>{const{auth:i,softDelete:o}=t,a={};t.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(X(c)?(a[c.name]=Kc(c,e,n,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=Lo(c,n,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=Te([Se("create"),Se("update"),Se("delete")]).optional(),a.password=Ie().optional(),a.passwordConfirm=Ie().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=an().optional(),a[`operations-${c.labels.collection}`]=Tt(Te([Se("Read"),Se("Create"),Se("Update"),Se("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=an().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=an().optional()}),c.access.entityRestrictions?.restrictions?.forEach(d=>{if(d.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=qe({}).catchall(Ee()).optional()),d.type==="Parent"||d.type==="Parent_Property"){const p=L(c.fields,d.collectionField);a[`accessible-${c.labels.collection}-${p.collection}`]=qe({}).catchall(Ee()).optional()}})}));const l=qe(a);return t.allowSchemalessFields?l.passthrough():l.strict()},mi=async(t,e)=>{if(t){const n=await ae(t,[e]);if(!n.valid)throw new Error(n.message)}},hn=async(t,e,n,s,r,i)=>{await mi(s.custom?.preValidate,r);for(const a of s.fields)await mi(a.custom?.preValidate,r);return $i(t,n,i).parse(e),e},or=(t,e,n,s,r,i,o,a,l,c,d,p,u,f,g,k,y,E,w,A,O)=>{const{fields:_}=o;_.filter(h=>"unique"in h&&h.unique).forEach(h=>{t!=="delete"&&(typeof r[h.name]=="string"||typeof r[h.name]=="number")&&(e.set(f(h,r[h.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:n}),O&&O.size++)}),_.forEach(h=>{if(mt(h,o,i)){const x=En(h,o,i),R={};r[h.name]!==void 0&&(R[h.name]=r[h.name],X(h)&&(R[`${h.name}_Array`]=r[`${h.name}_Array`])),x.forEach(q=>{r[q.name]!==void 0&&(X(q)?R[`${q.name}_Array`]=r[`${q.name}_Array`]:R[q.name]=r[q.name])}),Object.keys(R).length>0&&(t==="create"&&(R.Collection_Path=n,R.Collection_Path_String=n.join("/"),e.set(u(h),R)),t==="update"&&e.update(u(h),R),t==="delete"&&e.delete(u(h)),O&&O.size++)}});const I=l[o.labels.collection];Object.keys(o.fieldAccessGroups||{}).forEach(h=>{for(const x of I){const R=vn(h,o,x);if(R.length===0)continue;const q=on(h,x.key),Z={};R.forEach(m=>{[m.name,`${m.name}_Array`,`${m.name}_Single`,`${m.name}_Lowercase`].forEach(b=>{r[b]!==void 0&&(Z[b]=r[b])})}),t==="create"&&(Z.Collection_Path||=n,Z.Collection_Path_String=n.join("/"),e.set(g(q),Z),O&&O.size++),t==="update"&&Object.keys(Z).length>0&&(e.update(g(q),Z),O&&O.size++),t==="delete"&&(e.delete(g(q)),O&&O.size++)}});for(const h of I){const x=Oa(h,o),R={...r};x.forEach(q=>{delete R[q.name],delete R[`${q.name}_Array`],delete R[`${q.name}_Single`],delete R[`${q.name}_Lowercase`]}),Object.keys(R).length>0&&(t==="create"&&(R.Collection_Path||=n,R.Collection_Path_String=n.join("/"),e.set(g(h.key),R)),t==="update"&&e.update(g(h.key),R),t==="delete"&&e.delete(g(h.key)),O&&O.size++)}const j=(h,x)=>{let R=1;mt(x,h,i)&&R++,h.fields.forEach(Z=>{mt(Z,h,i)&&JSON.parse(as(En(Z,h,i))).includes(x.name)&&R++});const q=l[h.labels.collection];for(const Z of q)Z.fields.some(m=>m.name===x.name)&&X(x)&&R++;for(const Z of Object.keys(h.fieldAccessGroups||{}))for(const m of q)vn(Z,h,m).some(b=>b.name===x.name)&&X(x)&&R++;return R},v=(h,x,R,q,Z)=>{const m={};m[`${R.name}.${s}`]=p(),m[`${R.name}_Array`]=d(s),m[`${R.name}_Single`]=p(),e.update(k(Z,q),m),mt(R,x,i)&&e.update(y(h,R.name,q),{[`${R.name}.${s}`]:p(),[`${R.name}_Array`]:d(s)}),x.fields.forEach(b=>{mt(b,x,i)&&JSON.parse(as(En(b,x,i))).includes(R.name)&&e.update(y(h,b.name,q),{[`${R.name}_Array`]:d(s)})});const T=l[x.labels.collection];for(const b of T)b.fields.some(F=>F.name===R.name)&&X(R)&&e.update(E(h,b.key,q),m);for(const b of Object.keys(x.fieldAccessGroups||{}))for(const F of T){const D=vn(b,x,F),M=on(b,F.key);D.some(H=>H.name===R.name)&&X(R)&&e.update(E(h,M,q),m)}};if(t==="delete")return;const U=_.filter(h=>X(h)&&h.twoWay);if(!a?.noTwoWay){for(const h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay),q=gt(x,x.fields),Z=Array.from(q).map(m=>m.name);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(r[`${h.name}_Array`])for(const[m,T]of Object.entries(r[h.name])){if(t==="update"&&w&&w[`${h.name}_Array`]?.includes(m))continue;const b={...w,...r};et(b);const F={};R.includeFields&&R.includeFields.forEach(C=>{if(b[C]!==void 0){F[C]=b[C];const B=L(o.fields,C);Rt(o,[B]).size===1&&(F[`${C}_Lowercase`]=b[`${C}_Lowercase`])}});const D={[`${h.twoWay}.${s}`]:{Collection_Path:n,...F},[`${h.twoWay}_Array`]:c(s)};Z.includes(R.name)&&(D[`${h.twoWay}_Single`]={Collection_Path:n,id:s,...F});const M=$n(r);e.update(k(T.Collection_Path,m),{...D,...M}),O.size++,mt(R,x,i)&&(e.update(y(h,R.name,m),{[`${R.name}.${s}`]:{Collection_Path:n,...F},[`${R.name}_Array`]:c(s)}),O.size++),x.fields.forEach(C=>{if(mt(C,x,i)){const B=JSON.parse(as(En(C,x,i))),S={};B.includes(R.name)&&(S[`${h.twoWay}_Array`]=c(s)),Object.keys(M).forEach(Q=>{B.includes(Q)&&(S[Q]=M[Q])}),Object.keys(S).length>0&&(e.update(y(h,C.name,m),S),O.size++)}});const H=l[x.labels.collection];for(const C of H)if(C.fields.some(B=>B.name===R.name)){const B={...D};Object.keys(M).forEach(S=>{C.fields.some(Q=>Q.name===S)&&(B[S]=M[S])}),Object.keys(B).length>0&&(e.update(E(h,C.key,m),B),O.size++)}for(const C of Object.keys(x.fieldAccessGroups||{}))for(const B of H){const S=vn(C,x,B),Q=on(C,B.key);if(S.some(ee=>ee.name===R.name)){const ee={...D};Object.keys(M).forEach(ye=>{S.some(le=>le.name===ye)&&(ee[ye]=M[ye])}),Object.keys(ee).length>0&&(e.update(E(h,Q,m),ee),O.size++)}}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}O&&O.size>500&&console.error(new Error(`VALIDATION_ERROR: ${O.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 h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(t==="update"&&w&&!(r[h.name]&&Oe(r[h.name]))&&r[`${h.name}_Array`]&&w[`${h.name}_Array`]?.length>0)for(const[q,Z]of Object.entries(w[h.name]))!r[`${h.name}_Array`].includes(q)&&!A?.get(h.name)?.includes(q)&&(O.size+=j(x,R),O.size<=500&&v(h,x,R,q,Z.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}for(const h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(t==="update"&&w&&r[h.name]&&Oe(r[h.name])&&w[`${h.name}_Array`]?.length>0)for(const[q,Z]of Object.entries(w[h.name]))A?.get(h.name)?.includes(q)||(O.size+=j(x,R),O.size<=500&&v(h,x,R,q,Z.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}}},Ze=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]===void 0?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&Ze(t[e]))},Vo=t=>{if(t=t.toString(),/[/]|^\.+$|^__.*__$/.test(t))return!1;try{const s=new TextEncoder().encode(t),r=new TextDecoder().decode(s);if(t!==r)return!1}catch{return!1}return!(new Blob([t]).size>1500)},pi=async(t,e,n,s=1e3,r=5)=>{for(;r>0;)try{await t(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Yn=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},Es=t=>t?Array.isArray(t)?t.map(s=>Yn(s)).filter(s=>s.length>0):Yn(t)||"":"",tu=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/[\r\n]/g," ");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>998)throw new Error("Email subject is too long");return e},yi=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
|
|
3
|
+
`||"";let i,o,a;if(!n&&e){const l=We(t,e);i=l.admin?.condition?.form!==void 0&&!Kt(l.admin.condition.form),o=Kt(l.admin?.skipFormRequiredValidation),a=Kt(l.admin?.image)}switch(t.type){case"String":s=Ie(),t.length&&(s=s.length(t.length,`Must be ${t.length} character(s) long`)),t.minlength&&(s=s.min(t.minlength,`Must contain at least ${t.minlength} character(s)`)),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} character(s)`)),t.email?s=s.email("Must be a valid email address"):t.uuid?s=Oe([s.uuid("Must be a valid UUID"),Ee("")]):t.url?s=Oe([s.url("Must be a valid URL"),Ee("")]):t.emoji?s=Oe([s.emoji("Must be a valid emoji"),Ee("")]):t.ip?s=Oe([s.ip("Must be a valid IP address"),Ee("")]):t.pattern&&(!n&&a?s=Oe([s.regex(new RegExp(t.pattern)),s.regex(/^blob:/),Ee("")],{message:"Must be a valid value"}):s=Oe([s.regex(new RegExp(t.pattern),"Must be a valid value"),Ee("")])),t.values&&(s=Oe([Zn(t.values,{message:`Must be one of the following values: ${t.values.join(", ")}`}),us()])),r&&(s=s.describe(r.trim()));break;case"Boolean":s=an(),r&&(s=s.describe(r.trim()));break;case"Number":t.autoIncrement?s=Oe([us(),_t().int()],{message:"Must be a valid number"}):(s=_t({message:"Must be a valid number"}),t.min&&(s=s.min(t.min,`Must be greater than or equal to ${t.min}`)),t.max&&(s=s.max(t.max,`Must be less than or equal to ${t.max}`)),t.decimal?n?s=s.describe(`${r}Must have ${t.decimal} decimal places`):s=s.refine(l=>t.decimal?(l.toString().split(".")[1]?.length||0)<=t.decimal:!1,{message:`Must have ${t.decimal} or fewer decimal places`}):s=s.int("Must not have decimal places"),t.values?(n||(s=Oe([s.refine(l=>t.values?.includes(l),{message:`Must be one of the following values: ${t.values.join(", ")}`}),us()])),s=s.describe(`${r}Must be one of the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())));break;case"Timestamp":n?(s=qe({seconds:_t(),nanoseconds:_t()}),t.min&&t.max?s=s.describe(`${r}Must be between ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)} and ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`):t.min?s=s.describe(`${r}Must be greater than or equal to ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)}`):t.max?s=s.describe(`${r}Must be less than or equal to ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`):r&&(s=s.describe(r.trim()))):(s=Xc(),t.min&&(s=s.refine(l=>l.toMillis()>=t.min,{message:`Must be greater than or equal to ${V.fromMillis(t.min).toLocaleString(V.DATE_MED)}`})),t.max&&(s=s.refine(l=>l.toMillis()<=t.max,{message:`Must be less than or equal to ${V.fromMillis(t.max).toLocaleString(V.DATE_MED)}`})));break;case"Array":s=Tt(ve()),t.length&&(s=s.length(t.length,`Must contain ${t.length} item(s)`)),t.minlength?s=s.min(t.minlength,`Must contain at least ${t.minlength} item(s)`):t.required&&!i&&(s=s.nonempty("Must contain at least one item")),t.maxlength&&(s=s.max(t.maxlength,`Must contain at most ${t.maxlength} item(s)`)),t.values?(n||(s=s.refine(l=>{let c=!0;return l.forEach(d=>{t.values&&!t.values.includes(d)&&(c=!1)}),c},{message:`Must only contain the following values: ${t.values.join(", ")}`})),s=s.describe(`${r}Must only contain the following values: ${t.values.join(", ")}`)):r&&(s=s.describe(r.trim())),t.nullable&&(s=s.nullable());break;case"Map":t.required&&!i?n?s=qe({}).catchall(ve()).describe(`${r}Must be an object. Must contain at least one object property.`):s=pn(ve()).refine(l=>l&&typeof l=="object"&&Object.keys(l).length>0,{message:"Must not be an empty value"}):s=qe({}).catchall(ve()).describe(`${r}Must be an object`);break;case"Computed":s=ve()}return(!t.required||i||o)&&(s=s.optional()),s},eu=(t,e,n,s,r)=>{const{auth:i,softDelete:o}=t,a={};t.fields.forEach(c=>{c.type==="Embedding"||s&&c.type==="Computed"||s&&(c.name===o?.archivedField||c.name===o?.timestampField)||(X(c)?(a[c.name]=Kc(c,e,n,s),s?(c.length&&(a[c.name]=a[c.name].describe(`Must contain ${c.length} item(s)`)),c.min&&(a[c.name]=a[c.name].describe(`Must contain at least ${c.min} item(s)`)),c.max&&(a[c.name]=a[c.name].describe(`Must contain at most ${c.max} item(s)`))):(c.length&&(a[c.name]=a[c.name].refine(d=>c.length&&d&&Object.keys(d).length===c.length,{message:`Must contain ${c.length} item(s)`})),c.min&&(a[c.name]=a[c.name].refine(d=>c.min&&d&&Object.keys(d).length>=c.min,{message:`Must contain at least ${c.min} item(s)`})),c.max&&(a[c.name]=a[c.name].refine(d=>c.max&&(!d||Object.keys(d).length<=c.max),{message:`Must contain at most ${c.max} item(s)`})))):a[c.name]=Lo(c,n,s),r&&(a[c.name]=a[c.name].optional()))}),!s&&i&&(a.operation=Oe([Ee("create"),Ee("update"),Ee("delete")]).optional(),a.password=Ie().optional(),a.passwordConfirm=Ie().optional(),Object.values(e.collections).forEach(c=>{a[`auth-${c.labels.collection}`]=an().optional(),a[`operations-${c.labels.collection}`]=Tt(Oe([Ee("Read"),Ee("Create"),Ee("Update"),Ee("Delete")])).optional(),a[`restrict-${c.labels.collection}`]=an().optional(),c.access.attributeRestrictions?.forEach(d=>{a[`attribute-${c.labels.collection}-${d.type}`]=an().optional()}),c.access.entityRestrictions?.restrictions?.forEach(d=>{if(d.type==="Individual"&&(a[`accessible-${c.labels.collection}-${c.labels.collection}`]=qe({}).catchall(ve()).optional()),d.type==="Parent"||d.type==="Parent_Property"){const p=L(c.fields,d.collectionField);a[`accessible-${c.labels.collection}-${p.collection}`]=qe({}).catchall(ve()).optional()}})}));const l=qe(a);return t.allowSchemalessFields?l.passthrough():l.strict()},mi=async(t,e)=>{if(t){const n=await ae(t,[e]);if(!n.valid)throw new Error(n.message)}},hn=async(t,e,n,s,r,i)=>{await mi(s.custom?.preValidate,r);for(const a of s.fields)await mi(a.custom?.preValidate,r);return $i(t,n,i).parse(e),e},or=(t,e,n,s,r,i,o,a,l,c,d,p,u,f,g,k,y,E,w,A,O)=>{const{fields:_}=o;_.filter(h=>"unique"in h&&h.unique).forEach(h=>{t!=="delete"&&(typeof r[h.name]=="string"||typeof r[h.name]=="number")&&(e.set(f(h,r[h.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||")),{id:s,Collection_Path:n}),O&&O.size++)}),_.forEach(h=>{if(mt(h,o,i)){const x=En(h,o,i),R={};r[h.name]!==void 0&&(R[h.name]=r[h.name],X(h)&&(R[`${h.name}_Array`]=r[`${h.name}_Array`])),x.forEach(q=>{r[q.name]!==void 0&&(X(q)?R[`${q.name}_Array`]=r[`${q.name}_Array`]:R[q.name]=r[q.name])}),Object.keys(R).length>0&&(t==="create"&&(R.Collection_Path=n,R.Collection_Path_String=n.join("/"),e.set(u(h),R)),t==="update"&&e.update(u(h),R),t==="delete"&&e.delete(u(h)),O&&O.size++)}});const I=l[o.labels.collection];Object.keys(o.fieldAccessGroups||{}).forEach(h=>{for(const x of I){const R=vn(h,o,x);if(R.length===0)continue;const q=on(h,x.key),Z={};R.forEach(m=>{[m.name,`${m.name}_Array`,`${m.name}_Single`,`${m.name}_Lowercase`].forEach(b=>{r[b]!==void 0&&(Z[b]=r[b])})}),t==="create"&&(Z.Collection_Path||=n,Z.Collection_Path_String=n.join("/"),e.set(g(q),Z),O&&O.size++),t==="update"&&Object.keys(Z).length>0&&(e.update(g(q),Z),O&&O.size++),t==="delete"&&(e.delete(g(q)),O&&O.size++)}});for(const h of I){const x=Oa(h,o),R={...r};x.forEach(q=>{delete R[q.name],delete R[`${q.name}_Array`],delete R[`${q.name}_Single`],delete R[`${q.name}_Lowercase`]}),Object.keys(R).length>0&&(t==="create"&&(R.Collection_Path||=n,R.Collection_Path_String=n.join("/"),e.set(g(h.key),R)),t==="update"&&e.update(g(h.key),R),t==="delete"&&e.delete(g(h.key)),O&&O.size++)}const j=(h,x)=>{let R=1;mt(x,h,i)&&R++,h.fields.forEach(Z=>{mt(Z,h,i)&&JSON.parse(as(En(Z,h,i))).includes(x.name)&&R++});const q=l[h.labels.collection];for(const Z of q)Z.fields.some(m=>m.name===x.name)&&X(x)&&R++;for(const Z of Object.keys(h.fieldAccessGroups||{}))for(const m of q)vn(Z,h,m).some(b=>b.name===x.name)&&X(x)&&R++;return R},v=(h,x,R,q,Z)=>{const m={};m[`${R.name}.${s}`]=p(),m[`${R.name}_Array`]=d(s),m[`${R.name}_Single`]=p(),e.update(k(Z,q),m),mt(R,x,i)&&e.update(y(h,R.name,q),{[`${R.name}.${s}`]:p(),[`${R.name}_Array`]:d(s)}),x.fields.forEach(b=>{mt(b,x,i)&&JSON.parse(as(En(b,x,i))).includes(R.name)&&e.update(y(h,b.name,q),{[`${R.name}_Array`]:d(s)})});const T=l[x.labels.collection];for(const b of T)b.fields.some(F=>F.name===R.name)&&X(R)&&e.update(E(h,b.key,q),m);for(const b of Object.keys(x.fieldAccessGroups||{}))for(const F of T){const D=vn(b,x,F),M=on(b,F.key);D.some(H=>H.name===R.name)&&X(R)&&e.update(E(h,M,q),m)}};if(t==="delete")return;const U=_.filter(h=>X(h)&&h.twoWay);if(!a?.noTwoWay){for(const h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay),q=gt(x,x.fields),Z=Array.from(q).map(m=>m.name);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(r[`${h.name}_Array`])for(const[m,T]of Object.entries(r[h.name])){if(t==="update"&&w&&w[`${h.name}_Array`]?.includes(m))continue;const b={...w,...r};et(b);const F={};R.includeFields&&R.includeFields.forEach(C=>{if(b[C]!==void 0){F[C]=b[C];const B=L(o.fields,C);Rt(o,[B]).size===1&&(F[`${C}_Lowercase`]=b[`${C}_Lowercase`])}});const D={[`${h.twoWay}.${s}`]:{Collection_Path:n,...F},[`${h.twoWay}_Array`]:c(s)};Z.includes(R.name)&&(D[`${h.twoWay}_Single`]={Collection_Path:n,id:s,...F});const M=$n(r);e.update(k(T.Collection_Path,m),{...D,...M}),O.size++,mt(R,x,i)&&(e.update(y(h,R.name,m),{[`${R.name}.${s}`]:{Collection_Path:n,...F},[`${R.name}_Array`]:c(s)}),O.size++),x.fields.forEach(C=>{if(mt(C,x,i)){const B=JSON.parse(as(En(C,x,i))),S={};B.includes(R.name)&&(S[`${h.twoWay}_Array`]=c(s)),Object.keys(M).forEach(Q=>{B.includes(Q)&&(S[Q]=M[Q])}),Object.keys(S).length>0&&(e.update(y(h,C.name,m),S),O.size++)}});const H=l[x.labels.collection];for(const C of H)if(C.fields.some(B=>B.name===R.name)){const B={...D};Object.keys(M).forEach(S=>{C.fields.some(Q=>Q.name===S)&&(B[S]=M[S])}),Object.keys(B).length>0&&(e.update(E(h,C.key,m),B),O.size++)}for(const C of Object.keys(x.fieldAccessGroups||{}))for(const B of H){const S=vn(C,x,B),Q=on(C,B.key);if(S.some(ee=>ee.name===R.name)){const ee={...D};Object.keys(M).forEach(ye=>{S.some(le=>le.name===ye)&&(ee[ye]=M[ye])}),Object.keys(ee).length>0&&(e.update(E(h,Q,m),ee),O.size++)}}}}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}O&&O.size>500&&console.error(new Error(`VALIDATION_ERROR: ${O.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 h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(t==="update"&&w&&!(r[h.name]&&be(r[h.name]))&&r[`${h.name}_Array`]&&w[`${h.name}_Array`]?.length>0)for(const[q,Z]of Object.entries(w[h.name]))!r[`${h.name}_Array`].includes(q)&&!A?.get(h.name)?.includes(q)&&(O.size+=j(x,R),O.size<=500&&v(h,x,R,q,Z.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}for(const h of U){if(!O)throw new Error("VALIDATION_ERROR: batchSize is required");const x=i.collections[h.collection],R=L(x.fields,h.twoWay);if(!R)throw new Error(`SCHEMA_ERROR: Field ${h.twoWay} not found in collection ${h.collection}`);if(X(R)){if(t==="update"&&w&&r[h.name]&&be(r[h.name])&&w[`${h.name}_Array`]?.length>0)for(const[q,Z]of Object.entries(w[h.name]))A?.get(h.name)?.includes(q)||(O.size+=j(x,R),O.size<=500&&v(h,x,R,q,Z.Collection_Path))}else throw new Error(`SCHEMA_ERROR: Invalid field type: ${R.type}`)}}},Ze=t=>{for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]===void 0?delete t[e]:typeof t[e]=="object"&&t[e]!==null&&Ze(t[e]))},Vo=t=>{if(t=t.toString(),/[/]|^\.+$|^__.*__$/.test(t))return!1;try{const s=new TextEncoder().encode(t),r=new TextDecoder().decode(s);if(t!==r)return!1}catch{return!1}return!(new Blob([t]).size>1500)},pi=async(t,e,n,s=1e3,r=5)=>{for(;r>0;)try{await t(...e);break}catch(i){if(r--,r===0)throw i;await new Promise(o=>setTimeout(o,s)),s*=2}},Yn=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/[\r\n]/g,"");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>254)throw new Error("Email address is too long");return e},Es=t=>t?Array.isArray(t)?t.map(s=>Yn(s)).filter(s=>s.length>0):Yn(t)||"":"",tu=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/[\r\n]/g," ");if(e=e.replace(/\0/g,""),e=e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,""),e=e.trim(),e.length>998)throw new Error("Email subject is too long");return e},yi=t=>{if(!t||typeof t!="string")return"";let e=t.replace(/\0/g,"");if(e=e.replace(/\r\n\r\n/g,`
|
|
4
4
|
|
|
5
5
|
`),e=e.replace(/\r\n/g,`
|
|
6
6
|
`),e.length>5e6)throw new Error("Email body is too long");return e},nu=(t="enterprise",e)=>t==="enterprise"?e:"(default)",fe=()=>{const t=vt.getApp(),e=process.env.STOKER_FB_WEB_APP_CONFIG;if(!e)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const n=JSON.parse(e),s=nu(process.env.FB_FIRESTORE_EDITION,n.projectId);return oe.getFirestore(t,s)},Uo=async(t,e)=>{const n={};for(const s of e){const r=`${t}/${s}.js`,i=Ei.pathToFileURL(r).href;n[s]=await import(i)}return n};let vs,Wo,Dn,jo,sn,Zo,Cn,Fn,Os=0,gi=!1;const Ft={getTenant(){if(!Dn)throw new Error("Tenant not provided");return Dn},setTenant(t){Dn=t},getMode(){return Wo},getTimezone(){return jo},getGlobalConfigModule(){return pe(sn)},getCustomizationFile(t,e){if(!Object.keys(e.collections).includes(t))throw new Error("PERMISSION_DENIED");const n=ga([t],Zo,"node",Ft);return pe(n?.[t])},getVersionInfo(){return Cn},getMaintenanceInfo(){return Fn},getStokerFirestore:fe},su=async(t,e,n,s,r)=>{const i=!!gi;if(gi=!0,e&&(Dn=e),Wo=t,vs&&!r)return Ft;if(!process.env.STOKER_FB_WEB_APP_CONFIG)throw new Error("STOKER_FB_WEB_APP_CONFIG not set.");const o=process.env.STOKER_FB_WEB_APP_CONFIG,a=JSON.parse(o),d=(await import(Ei.pathToFileURL(n).href)).default;sn=d({sdk:"node",utils:Ft}),!r&&t==="development"&&(process.env.FIREBASE_AUTH_EMULATOR_HOST="127.0.0.1:9099",process.env.FIREBASE_DATABASE_EMULATOR_HOST="127.0.0.1:9000",process.env.FIRESTORE_EMULATOR_HOST="127.0.0.1:8080",process.env.FIREBASE_STORAGE_EMULATOR_HOST="127.0.0.1:9199");try{vs=vt.getApp()}catch{vs=vt.initializeApp({credential:vt.applicationDefault(),databaseURL:a.databaseURL,storageBucket:a.storageBucket,projectId:a.projectId})}const p=await Ye();return Zo=await Uo(s,Object.keys(p.collections)),jo=await ae(sn.timezone),i||fe().collection("system_deployment").doc("maintenance_mode").onSnapshot(u=>{u.exists?(Fn=u.data(),ae(sn.onMaintenanceUpdate,["node",Fn.active?"on":"off"])):console.error("Maintenance status not found")},u=>{console.error(u.message)}),i||fe().collection("system_deployment").doc("latest_deploy").onSnapshot(u=>{u.exists?(Cn=u.data(),Os++,Os>1&&ae(sn.onVersionUpdate,["node",Cn,Os])):console.error("Version info not found")},u=>{console.error(u.message)}),await new Promise(u=>{const f=()=>{Fn&&Cn?u(Ft):setTimeout(f,100)};f()}),Ft},{getTenant:Je,setTenant:ru,getMode:ar,getTimezone:lr,getGlobalConfigModule:It,getCustomizationFile:rt,getVersionInfo:iu,getMaintenanceInfo:ou}=Ft,au=async(t,e,n,s)=>new Promise((r,i)=>{const o=sa(t,e,{cwd:n||process.cwd(),env:{...process.env,...s}});let a="";const l=()=>{o.kill("SIGINT")},c=()=>{o.kill("SIGTERM")},d=()=>{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",c)};o.stdout?.on("data",p=>{a+=p.toString(),console.log(p.toString())}),o.stderr?.on("data",p=>{console.log(p.toString())}),o.on("exit",p=>{d(),p===0?r(a):i()}),process.on("SIGINT",l),process.on("SIGTERM",c)}),lu=async()=>{const t=process.env.STOKER_FB_WEB_APP_CONFIG;if(!t)throw new Error("Firebase web app config not found");const e=JSON.parse(t);try{return vt.getApp()}catch{return vt.initializeApp({credential:vt.applicationDefault(),databaseURL:e.databaseURL,storageBucket:e.storageBucket,projectId:e.projectId})}},Ye=async(t=!1)=>{const s=await vi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(1).get(),r=Object.values(s.val())[0];if(t){for(const i of Object.values(r.collections))for(const o of i.fields)if(o.type==="Computed"){const a=We(o,rt(i.labels.collection,r));a.formula&&(o.formula=a.formula)}}else for(const i of Object.values(r.collections))i.fields=i.fields.filter(o=>o.type!=="Computed");return r},cu=async()=>{const n=await vi.getDatabase().ref("schema").orderByChild("published_time").limitToLast(2).get();if(!(n.numChildren()<2))return Object.values(n.val())[0]},Ne=(t,e,n)=>{let s=t.collection("tenants").doc(n);for(let r=0;r<e.length;r++)r%2===0?s=s.collection(e[r]):s=s.doc(e[r]);return s},zo=(t,e,n,s,r,i)=>{const o=fe(),a=e.at(-1);if(!a)throw new Error("EMPTY_PATH");const l=n.collections[a],{labels:c,fields:d,preloadCache:p}=l,u=rt(a,n),f=Ne(o,e,t);if(r)if(s){const g=r.collections?.[c.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const k=g&&xe("Read",g),y=Ti(l,n,r,i??{}),E=bi(l,r),w=Bs(l,r),A=Ri(l,n,r),O=(m=[])=>{const T=[],b=Ai(r.Role,l,n);if(!b)throw new Error("PERMISSION_DENIED");if(k){let F=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${b.key}`).where("Collection_Path_String","==",e.join("/"));m.forEach(M=>{F=F.where(...M)}),T.push(F);const D=qs(l);Object.entries(l.fieldAccessGroups||{}).forEach(([M,H])=>{if(!D[M]?.length||!Kn(H,c.collection,r,i??{}))return;const C=on(M,b.key);let B=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${C}`).where("Collection_Path_String","==",e.join("/"));m.forEach(S=>{B=B.where(...S)}),T.push(B)})}else if(y)for(const F of y){let D=o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${F.field}`).where("Collection_Path_String","==",e.join("/"));m.forEach(M=>{D=D.where(...M)}),T.push(D)}return T},_=E.filter(m=>"operations"in m&&m.operations?m.operations.includes("Read"):!0);if(_.length===0&&w.length===0&&A.length===0)return O();let I=0;const j=m=>{m&&(I===0?I=m:I*=m)};if(_.length>0){for(const m of _)if(m.operations&&m.type==="Record_Property"){const T=m.roles.find(b=>b.role===r.Role);if(!T)throw new Error("PERMISSION_DENIED");j(T.values?.length)}}p?.roles.includes(r.Role)&&p.range&&j(p.range.fields.length);const v=u.admin?.statusField;v&&!p?.roles.includes(r.Role)&&j(Math.max(v.active?.length||0,v.archived?.length||0));const U=I===0?30:Math.max(1,Math.floor(30/I)),h=[];_.filter(m=>m.type==="Record_Owner").forEach(()=>h.push(["Created_By","==",s])),_.filter(m=>m.type==="Record_User").forEach(m=>{if("collectionField"in m){const T=L(d,m.collectionField);h.push([`${T.name}_Array`,"array-contains",r.Doc_ID])}}),_.filter(m=>m.type==="Record_Property").forEach(m=>{if("propertyField"in m){const T=m.roles.find(F=>F.role===r.Role);if(!T)throw new Error("PERMISSION_DENIED");const b=L(d,m.propertyField);b.type==="Array"?h.push([`${b.name}_Array`,"array-contains-any",T.values]):h.push([b.name,"in",T.values])}});const x=[];w.filter(m=>m.type==="Individual").forEach(m=>{const T=g?.individualEntities,b=[];if(T){const F=m.singleQuery?m.singleQuery:U;for(let D=0;D<T.length;D+=F){const M=T.slice(D,D+F);b.push(M)}if(!m.singleQuery)b.forEach(D=>{x.push(...O(h.concat([["id","in",D]])))});else{if(T.length>F)throw new Error(`INPUT_ERROR: Individual entity restriction with singleQuery set to true must not have more than ${m.singleQuery} entities`);h.push(["id","in",T])}}}),A.filter(m=>m.parentFilter.type==="Individual").forEach(m=>{const{parentFilter:T,parentRestriction:b}=m;if("collectionField"in T){const F=L(d,T.collectionField);if("collection"in F){const D=r.collections?.[F.collection];if(!D)throw new Error("PERMISSION_DENIED");const M=D.individualEntities,H=[];if(M){const C=b.singleQuery?b.singleQuery:U;for(let B=0;B<M.length;B+=C){const S=M.slice(B,B+C);H.push(S)}if(!b.singleQuery)H.forEach(B=>{x.push(...O(h.concat([[`${F.name}_Array`,"array-contains-any",B]])))});else{if(M.length>C)throw new Error(`INPUT_ERROR: Individual entity parentFilter with singleQuery set to true must not have more than ${b.singleQuery} entities`);h.push([`${F.name}_Array`,"array-contains-any",M])}}}}});const R=[];w.filter(m=>m.type==="Parent").forEach(m=>{if("collectionField"in m){const T=L(d,m.collectionField);if("collection"in T){const b=g?.parentEntities,F=[];if(b){const D=m.singleQuery?m.singleQuery:U;for(let M=0;M<b.length;M+=D){const H=b.slice(M,M+D);F.push(H)}if(!m.singleQuery)F.forEach(M=>{R.push(...O(h.concat([[`${T.name}_Array`,"array-contains-any",M]])))});else{if(b&&b.length>D)throw new Error(`INPUT_ERROR: Parent entity restriction with singleQuery set to true must not have more than ${m.singleQuery} entities`);h.push([`${T.name}_Array`,"array-contains-any",b])}}}}}),A.filter(m=>m.parentFilter.type==="Parent").forEach(m=>{const{parentFilter:T,parentRestriction:b}=m;if("collectionField"in T&&"parentCollectionField"in T){const F=L(d,T.collectionField),D=L(d,T.parentCollectionField);if("collection"in F&&"collection"in D){const M=r.collections?.[F.collection];if(!M)throw new Error("PERMISSION_DENIED");const H=M.parentEntities,C=[];if(H){const B=b.singleQuery?b.singleQuery:U;for(let S=0;S<H.length;S+=B){const Q=H.slice(S,S+B);C.push(Q)}if(!b.singleQuery)C.forEach(S=>{R.push(...O(h.concat([[`${D.name}_Array`,"array-contains-any",S]])))});else{if(H&&H.length>B)throw new Error(`INPUT_ERROR: Profile_Parent entity parentFilter with singleQuery set to true must not have more than ${b.singleQuery} entities`);h.push([`${D.name}_Array`,"array-contains-any",H])}}}}});const q=[];R.length===0&&(w.filter(m=>m.type==="Parent_Property").forEach(m=>{if("collectionField"in m&&"propertyField"in m){const T=L(d,m.collectionField),b=L(d,m.propertyField);if("collection"in T){const F=g?.parentPropertyEntities||{};Object.entries(F).forEach(([D,M])=>{if(M.length>0){const H=[];for(let C=0;C<M.length;C+=U){const B=M.slice(C,C+U);H.push(B)}H.forEach(C=>{q.push(...O(h.concat([[`${T.name}_Array`,"array-contains-any",C],[b.name,"==",D]])))})}})}}}),A.filter(m=>m.parentFilter.type==="Parent_Property").forEach(m=>{const{parentFilter:T}=m;if("collectionField"in T&&"parentCollectionField"in T&&"parentPropertyField"in T){const b=L(d,T.collectionField),F=L(d,T.parentCollectionField),D=L(d,T.parentPropertyField);if("collection"in b&&"collection"in F){const M=r.collections?.[b.collection];if(!M)throw new Error("PERMISSION_DENIED");const H=M.parentPropertyEntities||{};Object.entries(H).forEach(([C,B])=>{if(B.length>0){const S=[];for(let Q=0;Q<B.length;Q+=U){const ee=B.slice(Q,Q+U);S.push(ee)}S.forEach(Q=>{q.push(...O(h.concat([[`${F.name}_Array`,"array-contains-any",Q],[D.name,"==",C]])))})}})}}}));const Z=[...x,...R,...q];return!w.length&&!A.length?O(h):Z}else throw new Error("PERMISSION_DENIED");else return[f]},cr=(t,e,n,s,r,i)=>{const o=fe(),a=e.at(-1);if(!a)throw new Error("EMPTY_PATH");const l=s.collections[a],{labels:c}=l,d=Ne(o,e,t);if(r){const p=r.collections?.[c.collection];if(!r.Role)throw new Error("PERMISSION_DENIED");const u=p&&xe("Read",p),f=Ti(l,s,r,i??{}),g=[],k=Ai(r.Role,l,s);if(!k)throw new Error("PERMISSION_DENIED");if(u){g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${k.key}`).doc(n));const y=qs(l);Object.entries(l.fieldAccessGroups||{}).forEach(([E,w])=>{if(!y[E]?.length||!Kn(w,c.collection,r,i??{}))return;const A=on(E,k.key);g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${A}`).doc(n))})}else if(f)for(const y of f)g.push(o.collection("tenants").doc(t).collection("system_fields").doc(c.collection).collection(`${c.collection}-${y.field}`).doc(n));return g}else return[d.doc(n)]},Ht=async t=>await bt.getAuth().getUser(t),qo=async(t,e,n,s,r,i,o,a,l,c)=>{const d=n.at(-2),p=Si(r.collections[d],r).map(g=>g.labels.collection);s.collections?s.collections.forEach(g=>{if(!p.includes(g))throw new Error(`SCHEMA_ERROR: Collection ${g} not found in subcollections of ${d}`)}):s.collections=p;const u=s.depth-1,f=s.collections.map(async g=>{const k=await dr([...n,g],{constraints:s.constraints,userId:a,pagination:s.limit,providedTransaction:l,noEmbeddingFields:c}).catch(y=>{throw y.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${g} for document at ${n.join("/")}`),y});e[g]=k.records,i&&await Promise.all(e[g].map(y=>ur(t,y,[...n,g,y.id],i,r,void 0,a,l,c))),u>0&&await Promise.all(e[g].map(y=>qo(t,y,[...n,g,y.id],{depth:u},r,i,o,a,l,c)))});await Promise.all(f)},ur=async(t,e,n,s,r,i,o,a,l)=>{const c=n.at(-2);s.fields||=r.collections[c].fields.filter(u=>X(u));const d=s.depth-1,p=[];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 k of g){const y=f[k],E=Be(y.Collection_Path,k,{userId:o,providedTransaction:a,noEmbeddingFields:l}).then(w=>{if(f[k]=w,d>0)return ur(t,f[k],[...y.Collection_Path,k],{depth:d},r,i,o,a,l)}).catch(w=>{if(w.message.includes("NOT_FOUND")||w.code==="permission-denied")delete f[k];else throw w});p.push(E)}}await Promise.all(p)},dr=async(t,e)=>{if(e?.subcollections?.depth&&e.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(e?.relations?.depth&&e.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");if(e?.pagination?.number!==void 0){const c=e.pagination.number;if(typeof c!="number"||!Number.isFinite(c)||!Number.isInteger(c)||c<1)throw new Error("INPUT_ERROR: Pagination number must be a positive finite integer")}const n=e?.constraints,s=Je(),r=fe();let i,o,a;const l=async c=>{const[d,p,u,f]=await Promise.all([e?.userId?c.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(e.userId)):Promise.resolve({}),c.get(r.collection("system_deployment").doc("maintenance_mode")),Ye(!0),e?.userId?Ht(e.userId):Promise.resolve(void 0)]);if(!p.exists)throw new Error("MAINTENANCE_MODE");if(p.data().active)throw new Error("MAINTENANCE_MODE");const k=u;let y;const E=It(),w=t.at(-1);if(!w)throw new Error("EMPTY_PATH");const A=Object.keys(k.collections).includes(w),O=E.disabledCollections?.includes(w);if(!A||O)throw new Error("COLLECTION_NOT_FOUND");const _=k.collections[w],{labels:I}=_,j=rt(I.collection,k);if(e?.userId){if(!d?.exists)throw new Error("PERMISSION_DENIED");if(y=d.data(),!y.Role)throw new Error("USER_ERROR");if(!y.Enabled)throw new Error("PERMISSION_DENIED")}let v=zo(s,t,k,e?.userId,y,f?.customClaims??{});if(v.length===0)return{cursor:{},pages:0,records:[]};if(n&&(v=v.map(m=>(n.forEach(([T,b,F])=>{m=m.where(T,b,F)}),m))),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 m=e.pagination.startAfter||e.pagination.endBefore;if(e?.userId){const T=ya(y.Role,_,k);if(m&&T!==!0)throw new Error("INPUT_ERROR: Pagination is not allowed when using "+T)}e.pagination.orderByField&&e.pagination.orderByDirection?!e.pagination.startAfter&&!e.pagination.endBefore?v=v.map(T=>T.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).limit(e.pagination.number)):e.pagination.startAfter?v=v.map((T,b)=>T.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).startAfter(o.last.get(b)).limit(e.pagination.number)):v=v.map((T,b)=>T.orderBy(e.pagination.orderByField,e.pagination.orderByDirection).endBefore(o.first.get(b)).limitToLast(e.pagination.number)):!e.pagination.startAfter&&!e.pagination.endBefore?v=v.map(T=>T.limit(e.pagination.number)):e.pagination.startAfter?v=v.map((T,b)=>T.startAfter(o.last.get(b)).limit(e.pagination.number)):v=v.map((T,b)=>T.endBefore(o.first.get(b)).limitToLast(e.pagination.number))}const U={};await ce("preOperation",E,j,{operation:"read",context:U}),await ce("preRead",E,j,{context:U,refs:v,multiple:!0,listener:!1}),a=new Map;const R=v.map(async m=>await c.get(m)),q=await Promise.all(R);for(const m of q){for(const T of m.docs){a.has(T.id)||a.set(T.id,{});const b=T.data(),F=a.get(T.id);F.id||=T.id;const D={...F,...b};delete D.Collection_Path_String,a.set(T.id,D)}o.first.set(q.indexOf(m),m.docs[0]),o.last.set(q.indexOf(m),m.docs.at(-1)||m.docs[0])}if(e?.pagination){let m=v[0];n&&(m=n.reduce((D,[M,H,C])=>D.where(M,H,C),m)),e.pagination.orderByField&&e.pagination.orderByDirection&&(m=m.orderBy(e.pagination.orderByField,e.pagination.orderByDirection));const b=(await m.count().get()).data().count,F=e.pagination.number;i=F>0?Math.ceil(b/F):0}let Z;e?.noComputedFields||(Z=await ae(j.admin?.retriever));for(const m of a.values()){const T=[],b=[...m.Collection_Path,m.id];e?.subcollections&&T.push(qo(s,a.get(m.id),b,pe(e.subcollections),k,pe(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(H=>{if(typeof H=="string"){const C=_.fields.find(B=>B.name===H);if(C)return C;throw new Error(`SCHEMA_ERROR: Field ${H} not found in collection ${w}`)}return H})),T.push(ur(s,a.get(m.id),b,pe(e.relations),k,void 0,e.userId,e.transactional?c:void 0,e?.noEmbeddingFields))),await Promise.all(T);const F=[];for(const H of _.fields){if(H.type==="Computed"&&!e?.noComputedFields){const C=We(H,j);if(!C.formula)continue;F.push(ae(C.formula,[m,Z]).then(B=>{m[H.name]=B}))}e?.noEmbeddingFields&&H.type==="Embedding"&&delete m[H.name]}if(await Promise.all(F),e?.userId&&y?.Role){if(!f)throw new Error("USER_ERROR");if(!(j.custom?.serverAccess?.read!==void 0?await ae(j.custom.serverAccess.read,[y,f,m]):!0)){a.delete(m.id);continue}for(const C of _.fields){const B=!C.access||He(C,y,_,f?.customClaims??{}),S=We(C,j),Q=S?.custom?.serverAccess?.read!==void 0?await ae(S.custom.serverAccess.read,[y,f,m]):!0;(!B||!Q)&&(X(C)?(delete a.get(m.id)[C.name],delete a.get(m.id)[`${C.name}_Array`],delete a.get(m.id)[`${C.name}_Single`]):delete a.get(m.id)[C.name])}}const D={operation:"read",data:m,recordId:m.id,context:U};await ce("postOperation",E,j,D),await ce("postRead",E,j,{context:U,refs:v,record:m,listener:!1})}e?.userId&&await ma(Array.from(a.values()),_,k,e.userId,y)};return e?.providedTransaction?await l(e.providedTransaction):await r.runTransaction(async c=>{await l(c)},{readOnly:!0}),{cursor:o,pages:i,records:Array.from(a.values())}},Bo=async(t,e,n,s,r,i,o,a)=>{const l=s.at(-2),c=Si(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,p=r.collections.map(async u=>{const f=await dr([...s,u],{constraints:r.constraints||[],userId:a,relations:o,pagination:r.limit,providedTransaction:e}).catch(g=>{throw g.code==="permission-denied"&&console.info(`PERMISSION_DENIED for subcollection ${u} for document at ${s.join("/")}`),g});n[u]=f.records,d>0&&await Promise.all(n[u].map(async g=>{await Bo(t,e,g,[...s,u,g.id],{depth:d},i,o,a)}))});await Promise.all(p)},Ho=async(t,e,n,s,r,i,o,a,l)=>{const c=s.at(-2);i.fields||=r.collections[c].fields.filter(u=>X(u));const d=i.depth-1,p=[];for(const u of i.fields)if("collection"in u){const f=n[u.name];if(!f)continue;for(const[g,k]of Object.entries(f)){const y=Be(k.Collection_Path,g,{userId:o,providedTransaction:e,noComputedFields:a,noEmbeddingFields:l}).then(E=>{if(f[g]=E,d>0)return Ho(t,e,f[g],[...k.Collection_Path,g],r,{depth:d},o,a,l)}).catch(E=>{if(E.message.includes("NOT_FOUND")||E.code==="permission-denied")delete f[g];else throw E});p.push(y)}}await Promise.all(p)},Be=async(t,e,n)=>{if(n?.subcollections?.depth&&n.subcollections.depth>10)throw new Error("INPUT_ERROR: Subcollections depth cannot exceed 10");if(n?.relations?.depth&&n.relations.depth>10)throw new Error("INPUT_ERROR: Relations depth cannot exceed 10");const s=Je(),r=fe();let i;const o=async a=>{const[l,c,d,p]=await Promise.all([n?.userId?a.get(r.collection("tenants").doc(s).collection("system_user_permissions").doc(n.userId)):Promise.resolve({}),a.get(r.collection("system_deployment").doc("maintenance_mode")),Ye(!0),n?.userId?Ht(n.userId):Promise.resolve(void 0)]);if(!c.exists)throw new Error("MAINTENANCE_MODE");if(c.data().active)throw new Error("MAINTENANCE_MODE");const f=d;let g;const k=It(),y=t.at(-1);if(!y)throw new Error("EMPTY_PATH");const E=Object.keys(f.collections).includes(y),w=k.disabledCollections?.includes(y);if(!E||w)throw new Error("COLLECTION_NOT_FOUND");const A=f.collections[y],{labels:O}=A,_=rt(O.collection,f);let I;if(n?.userId){if(!l?.exists)throw new Error("PERMISSION_DENIED");if(g=l.data(),!g.Role)throw new Error("USER_ERROR");if(!g.Enabled)throw new Error("PERMISSION_DENIED");if(I=g.collections?.[O.collection],!I)throw new Error("PERMISSION_DENIED")}if(n?.userId&&(!I||!xe("Read",I)))throw new Error("PERMISSION_DENIED");const j=cr(s,t,e,f,g,p?.customClaims??{});if(j.length===0)throw new Error("PERMISSION_DENIED");const v={};await ce("preOperation",k,_,{operation:"read",recordId:e,context:v}),await ce("preRead",k,_,{context:v,refs:j,multiple:!1,listener:!1}),i={};const x=j.map(b=>a.get(b)),R=await Promise.all(x);for(const b of R)if(b.exists){const F=b.data();i.id||=b.id,i={...i,...F},delete i.Collection_Path_String}else throw new Error(`NOT_FOUND: Document with ID ${e} does not exist at location ${t?.join("/")||O.collection}`);const q=[],Z=t?[...t,e]:[O.collection,e];if(n?.subcollections&&q.push(Bo(s,a,i,Z,n.subcollections,f,void 0,n.userId)),n?.relations&&(n.relations.fields&&(n.relations.fields=n.relations.fields.map(b=>{if(typeof b=="string"){const F=A.fields.find(D=>D.name===b);if(F)return F;throw new Error(`SCHEMA_ERROR: Field ${b} not found in collection ${y}`)}return b})),q.push(Ho(s,a,i,Z,f,n.relations,n.userId,n.noComputedFields,n.noEmbeddingFields))),await Promise.all(q),!n?.noComputedFields){for(const b of A.fields)if(b.type==="Computed"){const F=We(b,_);if(!F.formula)continue;i[b.name]=await F.formula(i)}}if(n?.noEmbeddingFields)for(const b of A.fields)b.type==="Embedding"&&delete i[b.name];if(n?.userId&&g?.Role){if(!p)throw new Error("USER_ERROR");if(!(_.custom?.serverAccess?.read!==void 0?await ae(_.custom?.serverAccess?.read,[g,p,i]):!0))throw new Error("PERMISSION_DENIED");for(const F of A.fields){const D=!F.access||He(F,g,A,p?.customClaims??{}),M=We(F,_),H=M?.custom?.serverAccess?.read!==void 0?await ae(M.custom.serverAccess.read,[g,p,i]):!0;(!D||!H)&&(X(F)?(delete i[F.name],delete i[`${F.name}_Array`],delete i[`${F.name}_Single`]):delete i[F.name])}}await ce("postOperation",k,_,{operation:"read",data:i,recordId:e,context:v}),await ce("postRead",k,_,{context:v,refs:j,record:i,listener:!1}),n?.userId&&await ha(i,A,f,n.userId,g)};return n?.providedTransaction?await o(n.providedTransaction):await r.runTransaction(async a=>{await o(a)},{readOnly:!0}),i},kt=async(t,e,n,s,r,i,o,a,l)=>{const{labels:c}=o,d=fe(),p=It(),u=await ae(p.firebase?.writeLogTTL),f={operation:t,collection:c.collection,docId:i,user:"System",status:e,Collection_Path:r,Last_Write_At:n.Last_Write_At,Last_Write_By:n.Last_Write_By,Last_Write_Connection_Status:n.Last_Write_Connection_Status,Last_Write_App:n.Last_Write_App,Last_Write_Version:n.Last_Write_Version,data:{}};if(u){const E=new Date,w=new Date(new Date().setDate(E.getDate()+u));f.TTL=oe.Timestamp.fromDate(w)}const g=pe(n);et(g),t!=="delete"&&(f.data.data=pe(g)),t==="update"&&(f.data.originalRecord=pe(l)),t!=="delete"&&["started","written"].includes(e)&&(delete f.data.data.Saved_At,delete f.data.data.Last_Save_At),e==="failed"&&(f.data.error=JSON.stringify(a));const k=Ne(d,r,s),y=n.Last_Write_At;await k.doc(i).collection("system_write_log").doc(`${n.Last_Write_By}-${y.valueOf()}`).set(f)},Gt=async t=>{const e=Je(),n=bt.getAuth(),s=fe(),r=[];if(await Promise.all([(async()=>{try{await s.collection("tenants").doc(e).collection("system_user_permissions").doc(t.User_ID).delete()}catch(i){r.push(`Error deleting user permissions:
|
|
7
7
|
${i}`)}})(),(async()=>{try{await n.deleteUser(t.User_ID)}catch(i){if(i.code==="auth/user-not-found")return;r.push(`Error deleting user:
|
|
8
|
-
${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},fr=async(t,e,n,s,r,i,o,a,l)=>{const c=fe(),d=ar(),p=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(p)t=p;else throw new Error("Admin email not set");const u=Es(t),f=tu(e),g=n?yi(n):void 0,k=s?yi(s):void 0,y=r?Es(r):void 0,E=i?Es(i):void 0,w=o?Yn(o):void 0,A=l?Yn(l):void 0,O=Array.isArray(u)?u:[u];if(O.length===0||O.length===1&&!O[0])throw new Error("No valid email addresses provided");const _={to:u,message:{subject:f}};if(g&&(_.message.text=g),k&&(_.message.html=k),y){const I=Array.isArray(y)?y:[y];I.length>0&&I[0]&&(_.cc=y)}if(E){const I=Array.isArray(E)?E:[E];I.length>0&&I[0]&&(_.bcc=E)}w&&(_.replyTo=w),a&&(_.message.attachments=a),A&&(_.from=A),await c.collection("system_mail").add(_)},uu=["tenant","role","collection","doc"],Go=new Set(uu);function hr(t){return Go.has(t)}function du(t){if(!t)return{};const e={};for(const n of Object.keys(t))Go.has(n)||(e[n]=t[n]);return e}const mr=async(t,e,n,s,r,i,o)=>{const a=bt.getAuth(),l=fe(),{labels:c,fields:d}=s;if(
|
|
8
|
+
${i}`)}})()]),r.length>0)throw new Error(r.join(", "))},fr=async(t,e,n,s,r,i,o,a,l)=>{const c=fe(),d=ar(),p=process.env.ADMIN_EMAIL;if(d==="development"||process.env.FIRESTORE_EMULATOR_HOST)if(p)t=p;else throw new Error("Admin email not set");const u=Es(t),f=tu(e),g=n?yi(n):void 0,k=s?yi(s):void 0,y=r?Es(r):void 0,E=i?Es(i):void 0,w=o?Yn(o):void 0,A=l?Yn(l):void 0,O=Array.isArray(u)?u:[u];if(O.length===0||O.length===1&&!O[0])throw new Error("No valid email addresses provided");const _={to:u,message:{subject:f}};if(g&&(_.message.text=g),k&&(_.message.html=k),y){const I=Array.isArray(y)?y:[y];I.length>0&&I[0]&&(_.cc=y)}if(E){const I=Array.isArray(E)?E:[E];I.length>0&&I[0]&&(_.bcc=E)}w&&(_.replyTo=w),a&&(_.message.attachments=a),A&&(_.from=A),await c.collection("system_mail").add(_)},uu=["tenant","role","collection","doc"],Go=new Set(uu);function hr(t){return Go.has(t)}function du(t){if(!t)return{};const e={};for(const n of Object.keys(t))Go.has(n)||(e[n]=t[n]);return e}const mr=async(t,e,n,s,r,i,o)=>{const a=bt.getAuth(),l=fe(),{labels:c,fields:d}=s;if(be(r.Email)||!r.Email)throw new Error("VALIDATION_ERROR: Email field is required");if(be(r.Role)||!r.Role)throw new Error("VALIDATION_ERROR: Role field is required");if(r.Enabled===void 0||r.Enabled===null||be(r.Enabled))throw new Error("VALIDATION_ERROR: Enabled field is required");const p="USER_ERROR",u=async(y,E)=>{try{await Gt(y)}catch{throw new Error(`ROLLBACK_FAILED: ${E}`)}};let f;try{f=await a.createUser({email:r.Email,emailVerified:!1,password:o,displayName:r.Name,photoURL:r.Photo_URL,disabled:!r.Enabled})}catch{throw new Error(p)}const g={};for(const y of d)y.saveToAuthToken&&!hr(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:t,role:r.Role,collection:c.collection,doc:e})}catch{throw await u(r,p),new Error(p)}try{await l.collection("tenants").doc(t).collection("system_user_permissions").doc(f.uid).set({...i,Role:r.Role,Enabled:r.Enabled??!1,Collection:c.collection,Doc_ID:e})}catch{throw await u(r,p),new Error(p)}const k=n.auth.enableMultiFactorAuth;if(k===!0||typeof k=="object"&&k.includes(r.Role)){let y;try{y=await a.generateEmailVerificationLink(r.Email)}catch{throw await u(r,p),new Error(p)}if(y.includes("apiKey=&")){const E=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);y=y.replace("apiKey=&",`apiKey=${E.apiKey}&`)}if(y){const E=`https://${a.app.options.projectId}.firebaseapp.com/__/auth/action${y}`,w=await ae(n.appName),A=n?.mail?.emailVerification&&n.mail.emailVerification(E,w);try{await fr(r.Email,A?.subject||"Please verify your email address",void 0,A?.html||`Please verify your email address by clicking the link:
|
|
9
9
|
</br>
|
|
10
10
|
</br>
|
|
11
|
-
<a href="${E}">${E}</a>`)}catch{throw await u(r,p),new Error(p)}}}return f.uid},pr=async(t,e)=>{const{labels:n,parentCollection:s}=e;if(s){const r=t.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...t].slice(0,-2),o=await Be(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(n.collection),!Xe(t,a))throw new Error("PERMISSION_DENIED")}else if(t.length>1)throw new Error("PERMISSION_DENIED")},Jn=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),fu=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{Jn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?n[s]=new oe.Timestamp(r.seconds,r.nanoseconds):Jn(r)&&e(r)})};e(t)},yr=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{Jn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?n[s]=new oe.Timestamp(r._seconds,r._nanoseconds):Jn(r)&&e(r)})};e(t)},is=t=>{if(typeof t=="object")for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]==="_DELETE_FIELD"?t[e]=oe.FieldValue.delete():is(t[e]))},hu=(t,e,n)=>{if(X(n)&&n.includeFields){const s={};return n.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=L(t.fields,r);Rt(t,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},wi=async(t,e,n,s,r,i,o)=>{if(!X(n)||!n.enforceHierarchy)return;const{fields:a}=e,l=fe(),c=Object.entries(s[n.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${n.name} is required`);const[d,p]=c[0];if(!p)throw new Error(`VALIDATION_ERROR: Relation ${n.name} is required`);const u=Ne(l,p.Collection_Path,t);if(i.size++,!o&&i.size>500)throw new Error("VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const f=await r.get(u.doc(d));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${d} not found in collection ${n.collection}`);const g=f.data(),k=L(a,n.enforceHierarchy.field),y=n.enforceHierarchy;if(!g[y.recordLinkField]||!s[k.name]||!Object.keys(s[k.name]).every(E=>Object.keys(g[y.recordLinkField]).includes(E)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},Sn=async(t,e,n)=>{delete e[t.name][n],e[`${t.name}_Array`]=e[`${t.name}_Array`]?.filter(s=>s!==n),delete e[`${t.name}_Single`]},ks=async(t,e,n,s,r)=>{e[t.name]||={},e[t.name][s]=n,e[`${t.name}_Array`]||=[],e[`${t.name}_Array`].push(s),r&&(e[`${t.name}_Single`]={id:s,...n})},mu=(t,e,n,s,r,i)=>{const o=[],a=[];for(const l of s.fields)X(l)&&l.twoWay&&l.collection===n&&((t==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),t==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},gr=async(t,e,n,s,r,i,o,a,l,c,d,p,u)=>{const{fields:f}=i,g=fe(),k=new Map,y=new Map,E=new Map;for(const w of f)X(w)&&["OneToOne","OneToMany"].includes(w.type)&&w.enforceHierarchy&&s[w.name]&&(t==="Create"||t==="Update"&&!Xe(p?.[w.name],s[w.name]))&&await wi(e,i,w,s,a,l);for(const w of f)if(X(w)&&w.twoWay){const A=o.collections[w.collection],O=L(A.fields,w.twoWay),_=gt(A,[O]);if(s[w.name]){const I=Object.entries(s[w.name]);for(const j of I){const[v,U]=j;if(t==="Create"||!p?.[w.name]?.[v]){let h;const x=E.get(w.collection)?.[v];if(x)h=x;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 q=Ne(g,U.Collection_Path,e),Z=await a.get(q.doc(v));if(!Z.exists){Sn(w,r,v);continue}const m=Z.data();y.set(w.collection,{...y.get(w.collection)||{},[v]:m}),h=pe({...m,...$n(s)})}const R={...h[O.name],[n]:{Collection_Path:s.Collection_Path,...hu(i,s,O)}};h[O.name]=R,h[`${O.name}_Array`]||=[],h[`${O.name}_Array`].push(n),_.size===1&&(h[`${O.name}_Single`]={id:n,...R}),E.set(w.collection,{...E.get(w.collection)||{},[v]:h})}}}if(t==="Update"){const I=Object.entries(p?.[w.name]||{});for(const j of I){const[v,U]=j;if(!s[w.name]?.[v]){let h;const x=E.get(w.collection)?.[v];if(x)h=x;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 R=Ne(g,U.Collection_Path,e),q=await a.get(R.doc(v));if(!q.exists){k.set(w.name,[...k.get(w.name)||[],v]);continue}const Z=q.data();y.set(w.collection,{...y.get(w.collection)||{},[v]:Z}),h=pe({...Z,...$n(s)})}h[O.name][n]&&delete h[O.name][n],Array.isArray(h[`${O.name}_Array`])&&(h[`${O.name}_Array`]=h[`${O.name}_Array`].filter(R=>R!==n)),_.size===1&&delete h[`${O.name}_Single`],E.set(w.collection,{...E.get(w.collection)||{},[v]:h})}}}}for(const[w,A]of E.entries()){const O=o.collections[w],_=rt(w,o);for(const[I,j]of Object.entries(A)){const{addedFields:v,removedFields:U}=mu(t,I,w,i,s,p);if(c&&d){for(const h of v){const x=L(O.fields,h.twoWay);if(!Or(O,x,d,u??{})){Sn(h,r,I);continue}}for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);if(!Or(O,x,d,u??{})){ks(h,r,p?.[h.name]?.[I],I,R.size===1);continue}}if(!ft("Update",O,o,c,d,y.get(w)?.[I])){for(const h of v)Sn(h,r,I);for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);ks(h,r,p?.[h.name]?.[I],I,R.size===1)}}if(!ft("Update",O,o,c,d,j)){for(const h of v)Sn(h,r,I);for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);ks(h,r,p?.[h.name]?.[I],I,R.size===1)}}}try{await hn("update",j,O,_,{operation:"update",data:j,context:{},originalRecord:j},o)}catch(h){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${I} in ${w}: ${h.message}`)}for(const h of v){const x=L(O.fields,h.twoWay);["OneToOne","OneToMany"].includes(x.type)&&X(x)&&x.enforceHierarchy&&await wi(e,O,x,j,a,l,!0)}}}return k},Yo=(t,e,n)=>{t==="create"&&ct.forEach(s=>{if(!Xe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),t==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),ct.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!Xe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},wr=(t,e,n,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(n[i]===!0)if(t==="create")n[o]=oe.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])n[o]=oe.FieldValue.serverTimestamp();else if(n[o]&&n[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},bs=async(t,e,n,s,r)=>{if(!xe("Read",r.collections?.[e.labels.collection]))return!1;try{await Be([e.labels.collection],n,{userId:s,providedTransaction:t})}catch{return!1}return!0},pu=10,yu=async(t,e)=>{if(t.length===0)return;const n=Math.min(e,t.length);let s=0;const r=async()=>{for(;s<t.length;){const i=s;s+=1,await t[i]()}};await Promise.all(Array.from({length:n},r))},Jo=async(t,e,n,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const g=l.individualEntities,k=u?.individualEntities||[],y=i?g.filter(E=>!k.includes(E)):g;for(const E 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 bs(t,d,E,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const g=c.entityRestrictions?.restrictions?.find(O=>O.type==="Parent"&&O.roles.some(_=>_.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const k=L(d.fields,g.collectionField),y=r.collections[k.collection],E=l.parentEntities,w=u?.parentEntities||[],A=i?E.filter(O=>!w.includes(O)):E;for(const O of A){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 bs(t,y,O,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const g=c.entityRestrictions?.restrictions?.find(A=>A.type==="Parent_Property"&&A.roles.some(O=>O.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const k=L(d.fields,g.collectionField),y=r.collections[k.collection],E=l.parentPropertyEntities,w=u?.parentPropertyEntities||{};for(const[A,O]of Object.entries(E)){const _=w[A]||[],I=i?O.filter(j=>!_.includes(j)):O;for(const j of I){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 bs(t,y,j,n,s))throw new Error("PERMISSION_DENIED")})}}}await yu(f,pu)}}},gu=async(t,e,n)=>{const s=n?.userId,r=n?.user;let i=n?.context;const o=Je(),a=It();if(n?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(n?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=n?.providedSchema||await Ye();if(t.length===0)throw new Error("EMPTY_PATH");const c=t.at(-1),d=Object.keys(l.collections).includes(c),p=a.disabledCollections?.includes(c);if(!d||p)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:g,enableWriteLog:k,softDelete:y}=u,E=rt(f.collection,l),w=await ae(a.appName),A=fe(),O=bt.getAuth(),_=s?await O.getUser(s):void 0;let I,j;s&&await pr(t,u);const v=Ne(A,t,o),U=n?.id||v.doc().id;i=i||{},i.collection=f.collection,e.id=U,yr(e),is(e);const h=Js("create",t,e,l,w,"Online",s||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp());n?.createdAt&&(h.Created_At=n.createdAt),n?.createdBy&&(h.Created_By=n.createdBy);const x=pe(h);y&&(h[y.archivedField]=!1),Ze(e),wt(u,h,l),k&&!n?.providedTransaction&&await kt("create","started",h,o,t,U,u),await ce("preOperation",a,E,{operation:"create",data:h,recordId:U,context:i}),await ce("preWrite",a,E,{operation:"create",data:h,recordId:U,context:i}),wt(u,h,l),Mn(u,h);const m=(s?await A.collection("tenants").doc(o).collection("system_user_permissions").doc(s).get():void 0)?.data();await ba(h,u,E,m,_?.customClaims||{}),Ze(h);try{if(u.auth&&r){if(!r.password)throw new Error("Password is required");if(!h.Role)throw new Error("Role field is required");if(!h.Email)throw new Error("Email field is required");if(h.Enabled===void 0||h.Enabled===null)throw new Error("Enabled field is required")}n?.providedTransaction||await hn("create",h,u,E,{operation:"create",data:h,context:i},l)}catch(D){throw new Error(`VALIDATION_ERROR: ${D.message}`)}Ze(h),e.id=U,y&&(h[y.archivedField]=!1),wt(u,h,l),Mn(u,h);try{Yo("create",h,x),wr("create",u,h),await hn("create",h,u,E,{operation:"create",data:h,context:i},l)}catch(D){throw new Error(`VALIDATION_ERROR: ${D.message}`)}if(s){if(!_)throw new Error("USER_ERROR");if(!m?.Role)throw new Error("USER_ERROR");const D=m;if(!(E.custom?.serverAccess?.create!==void 0?await ae(E.custom.serverAccess.create,[D,_,h]):!0))throw new Error("PERMISSION_DENIED");for(const H of u.fields){if(!(H.name in h))continue;const C=We(H,E);if(C?.custom?.serverAccess?.create!==void 0&&!await ae(C.custom.serverAccess.create,[D,_,h]))throw new Error("PERMISSION_DENIED")}}r&&(r.permissions||={},r.permissions.Role||=h.Role,r.permissions.Enabled||=h.Enabled);const T=async(D,M)=>{const[H,C,B,S,Q]=await Promise.all([n?.providedTransaction?Promise.resolve({}):D.get(A.collection("system_deployment").doc("latest_deploy")),n?.providedTransaction?Promise.resolve({}):D.get(A.collection("system_deployment").doc("maintenance_mode")),s?D.get(A.collection("tenants").doc(o).collection("system_user_permissions").doc(s)):Promise.resolve({}),n?.providedSchema?Promise.resolve(n.providedSchema):Ye(),s?Ht(s):Promise.resolve(void 0)]);if(M&&(M.size+=3),!n?.providedTransaction){if(!H.exists)throw new Error("VERSION_ERROR");const ee=H.data();if(ee.force&&h.Last_Write_At.valueOf()<ee.time.valueOf())throw new Error("VERSION_ERROR");if(!C.exists)throw new Error("MAINTENANCE_MODE");if(C.data().active)throw new Error("MAINTENANCE_MODE")}if(l=S,s){if(!B?.exists)throw new Error("PERMISSION_DENIED");if(I=B.data(),!I.Role)throw new Error("USER_ERROR");if(!I.Enabled)throw new Error("PERMISSION_DENIED");j=Q?.customClaims??{}}if(!n?.providedTransaction){const ye=g.filter(le=>"unique"in le&&le.unique).map(async le=>{if(!s||!le.access||He(le,I,u,j)){if(!h[le.name])return;const Qe=We(le,E);if(!(s&&I&&Q&&Qe?.custom?.serverAccess?.read!==void 0?await ae(Qe.custom.serverAccess.read,[I,Q,h]):!0))throw new Error("PERMISSION_DENIED");const De=h[le.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Vo(De)){if(M&&M.size++,M&&M.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");if((await D.get(A.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${le.name}`).doc(De)))?.exists)throw new Error(`VALIDATION_ERROR: ${le.name} "${h[le.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${le.name} "${h[le.name]}" is invalid`)}});await Promise.all(ye)}kr(h,U,u,l,s,I,r?.permissions,j),r?.permissions&&s&&I&&await Jo(D,r.permissions,s,I,l),kr(h,U,u,l,s,I,r?.permissions,j)};if(u.auth&&r){await A.runTransaction(async M=>{await T(M)},{maxAttempts:10});const D=await mr(o,U,a,u,h,r.permissions,r.password);h.User_ID=D}const b=async D=>{try{const M={size:1};await T(D,M),n?.noTwoWay||await gr("Create",o,U,h,h,u,l,D,M,s,I,void 0,j);const H=Ys(l);or("create",D,t,U,h,l,u,n,H,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,C=>A.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${C.name}`).doc(U),(C,B)=>A.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${C.name}`).doc(B),C=>A.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${C}`).doc(U),(C,B)=>Ne(A,C,o).doc(B),(C,B,S)=>A.collection("tenants").doc(o).collection("system_fields").doc(C.collection).collection(`${C.collection}-${B}`).doc(S),(C,B,S)=>A.collection("tenants").doc(o).collection("system_fields").doc(C.collection).collection(`${C.collection}-${B.replaceAll(" ","-")}`).doc(S),void 0,void 0,M),D.set(v.doc(U),h)}catch(M){if(n?.providedTransaction)throw M;{const C=await ce("postWriteError",a,E,{operation:"create",data:h,recordId:U,context:i,error:M});if(k&&(await new Promise(B=>{setTimeout(B,250)}),await kt("create",C?.resolved?"success":"failed",h,o,t,U,u,C?.resolved?void 0:M)),!C?.resolved)throw u.auth&&r&&await Gt(h),M}}};if(n?.providedTransaction?await b(n.providedTransaction):await A.runTransaction(async D=>{await b(D)},{maxAttempts:10}),!n?.providedTransaction){const D={operation:"create",data:h,recordId:U,context:i},M={...D};await ce("postWrite",a,E,D),await ce("postOperation",a,E,M)}return{id:U,...h}},rn=async(t,e,n,s)=>{const r=Je(),i=bt.getAuth(),o=fe(),a=e.customClaims||{};let l=!1;try{await i.updateUser(t,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(t,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(t).update({...n,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Qo=async(t,e,n,s,r,i,o,a,l,c,d)=>{const p=bt.getAuth(),u=fe(),f={};for(const y of r.fields)y.saveToAuthToken&&!hr(y.name)&&i[y.name]!==void 0&&y.type!=="Timestamp"&&y.type!=="Computed"&&y.type!=="Embedding"&&(Oe(i[y.name])?f[y.name]=null:f[y.name]=i[y.name]);const g="USER_ERROR";let k="";if(t==="create"){if(!d)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{k=await mr(e,n,s,r,i,l,d)}catch(y){throw new Error(y.message)}}else if(t==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),d&&(y.password=d),Object.keys(y).length)try{await p.updateUser(o.User_ID,y),y.disabled===!0&&await p.revokeRefreshTokens(o.User_ID)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}if(i.Role&&i.Role!==o.Role||Object.keys(f).length)try{const E={...du(a.customClaims),...f};await p.setCustomUserClaims(o.User_ID,{...E,tenant:e,role:i.Role,collection:r.labels.collection,doc:n}),await p.revokeRefreshTokens(o.User_ID)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}try{await u.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:r.labels.collection,Doc_ID:n,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}if(o.Email!==i.Email){const E=s.auth.enableMultiFactorAuth;if(E===!0||typeof E=="object"&&E.includes(i.Role)){let w=await p.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(w.includes("apiKey=&")){const A=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);w=w.replace("apiKey=&",`apiKey=${A.apiKey}&`)}if(w){const A=`https://${p.app.options.projectId}.firebaseapp.com/__/auth/action${w}`,O=await ae(s.appName),_=s?.mail?.emailVerification&&s.mail.emailVerification(A,O);try{await fr(i.Email,_?.subject||"Please verify your email address",void 0,_?.html||`Please verify your email address by clicking the link:
|
|
11
|
+
<a href="${E}">${E}</a>`)}catch{throw await u(r,p),new Error(p)}}}return f.uid},pr=async(t,e)=>{const{labels:n,parentCollection:s}=e;if(s){const r=t.at(-2);if(!r)throw new Error("PERMISSION_DENIED");const i=[...t].slice(0,-2),o=await Be(i,r).catch(()=>{throw new Error("PERMISSION_DENIED")}),a=o.Collection_Path;if(a.push(o.id),a.push(n.collection),!Xe(t,a))throw new Error("PERMISSION_DENIED")}else if(t.length>1)throw new Error("PERMISSION_DENIED")},Jn=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),fu=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{Jn(r)&&Object.keys(r).length===2&&typeof r.seconds=="number"&&typeof r.nanoseconds=="number"?n[s]=new oe.Timestamp(r.seconds,r.nanoseconds):Jn(r)&&e(r)})};e(t)},yr=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{Jn(r)&&Object.keys(r).length===2&&typeof r._seconds=="number"&&typeof r._nanoseconds=="number"?n[s]=new oe.Timestamp(r._seconds,r._nanoseconds):Jn(r)&&e(r)})};e(t)},is=t=>{if(typeof t=="object")for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(t[e]==="_DELETE_FIELD"?t[e]=oe.FieldValue.delete():is(t[e]))},hu=(t,e,n)=>{if(X(n)&&n.includeFields){const s={};return n.includeFields.forEach(r=>{if(e[r]!==void 0){s[r]=e[r];const i=L(t.fields,r);Rt(t,[i]).size===1&&(s[`${r}_Lowercase`]=e[`${r}_Lowercase`])}}),s}return{}},wi=async(t,e,n,s,r,i,o)=>{if(!X(n)||!n.enforceHierarchy)return;const{fields:a}=e,l=fe(),c=Object.entries(s[n.name]);if(!c.length)throw new Error(`VALIDATION_ERROR: relation ${n.name} is required`);const[d,p]=c[0];if(!p)throw new Error(`VALIDATION_ERROR: Relation ${n.name} is required`);const u=Ne(l,p.Collection_Path,t);if(i.size++,!o&&i.size>500)throw new Error("VALIDATION ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks, entity restrictions (in permissions when dealing with user collections) or relation hierarchy checks.");const f=await r.get(u.doc(d));if(!f.exists)throw new Error(`VALIDATION_ERROR: Record ${d} not found in collection ${n.collection}`);const g=f.data(),k=L(a,n.enforceHierarchy.field),y=n.enforceHierarchy;if(!g[y.recordLinkField]||!s[k.name]||!Object.keys(s[k.name]).every(E=>Object.keys(g[y.recordLinkField]).includes(E)))throw new Error("VALIDATION_ERROR: Invalid relation hierarchy")},Sn=async(t,e,n)=>{delete e[t.name][n],e[`${t.name}_Array`]=e[`${t.name}_Array`]?.filter(s=>s!==n),delete e[`${t.name}_Single`]},ks=async(t,e,n,s,r)=>{e[t.name]||={},e[t.name][s]=n,e[`${t.name}_Array`]||=[],e[`${t.name}_Array`].push(s),r&&(e[`${t.name}_Single`]={id:s,...n})},mu=(t,e,n,s,r,i)=>{const o=[],a=[];for(const l of s.fields)X(l)&&l.twoWay&&l.collection===n&&((t==="Create"||!i?.[l.name]?.[e])&&r[l.name]?.[e]&&o.push(l),t==="Update"&&i?.[l.name]?.[e]&&!r[l.name]?.[e]&&a.push(l));return{addedFields:o,removedFields:a}},gr=async(t,e,n,s,r,i,o,a,l,c,d,p,u)=>{const{fields:f}=i,g=fe(),k=new Map,y=new Map,E=new Map;for(const w of f)X(w)&&["OneToOne","OneToMany"].includes(w.type)&&w.enforceHierarchy&&s[w.name]&&(t==="Create"||t==="Update"&&!Xe(p?.[w.name],s[w.name]))&&await wi(e,i,w,s,a,l);for(const w of f)if(X(w)&&w.twoWay){const A=o.collections[w.collection],O=L(A.fields,w.twoWay),_=gt(A,[O]);if(s[w.name]){const I=Object.entries(s[w.name]);for(const j of I){const[v,U]=j;if(t==="Create"||!p?.[w.name]?.[v]){let h;const x=E.get(w.collection)?.[v];if(x)h=x;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 q=Ne(g,U.Collection_Path,e),Z=await a.get(q.doc(v));if(!Z.exists){Sn(w,r,v);continue}const m=Z.data();y.set(w.collection,{...y.get(w.collection)||{},[v]:m}),h=pe({...m,...$n(s)})}const R={...h[O.name],[n]:{Collection_Path:s.Collection_Path,...hu(i,s,O)}};h[O.name]=R,h[`${O.name}_Array`]||=[],h[`${O.name}_Array`].push(n),_.size===1&&(h[`${O.name}_Single`]={id:n,...R}),E.set(w.collection,{...E.get(w.collection)||{},[v]:h})}}}if(t==="Update"){const I=Object.entries(p?.[w.name]||{});for(const j of I){const[v,U]=j;if(!s[w.name]?.[v]){let h;const x=E.get(w.collection)?.[v];if(x)h=x;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 R=Ne(g,U.Collection_Path,e),q=await a.get(R.doc(v));if(!q.exists){k.set(w.name,[...k.get(w.name)||[],v]);continue}const Z=q.data();y.set(w.collection,{...y.get(w.collection)||{},[v]:Z}),h=pe({...Z,...$n(s)})}h[O.name][n]&&delete h[O.name][n],Array.isArray(h[`${O.name}_Array`])&&(h[`${O.name}_Array`]=h[`${O.name}_Array`].filter(R=>R!==n)),_.size===1&&delete h[`${O.name}_Single`],E.set(w.collection,{...E.get(w.collection)||{},[v]:h})}}}}for(const[w,A]of E.entries()){const O=o.collections[w],_=rt(w,o);for(const[I,j]of Object.entries(A)){const{addedFields:v,removedFields:U}=mu(t,I,w,i,s,p);if(c&&d){for(const h of v){const x=L(O.fields,h.twoWay);if(!Or(O,x,d,u??{})){Sn(h,r,I);continue}}for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);if(!Or(O,x,d,u??{})){ks(h,r,p?.[h.name]?.[I],I,R.size===1);continue}}if(!ft("Update",O,o,c,d,y.get(w)?.[I])){for(const h of v)Sn(h,r,I);for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);ks(h,r,p?.[h.name]?.[I],I,R.size===1)}}if(!ft("Update",O,o,c,d,j)){for(const h of v)Sn(h,r,I);for(const h of U){const x=L(O.fields,h.twoWay),R=gt(O,[x]);ks(h,r,p?.[h.name]?.[I],I,R.size===1)}}}try{await hn("update",j,O,_,{operation:"update",data:j,context:{},originalRecord:j},o)}catch(h){throw new Error(`VALIDATION_ERROR: Two way relation update would invalidate record ${I} in ${w}: ${h.message}`)}for(const h of v){const x=L(O.fields,h.twoWay);["OneToOne","OneToMany"].includes(x.type)&&X(x)&&x.enforceHierarchy&&await wi(e,O,x,j,a,l,!0)}}}return k},Yo=(t,e,n)=>{t==="create"&&ct.forEach(s=>{if(!Xe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}),t==="update"&&(["id","Collection_Path","Created_At","Saved_At","Created_By"].forEach(s=>{if(s in e)throw new Error(`Cannot update system field: ${s}`)}),ct.forEach(s=>{if(!["id","Collection_Path","Created_At","Saved_At","Created_By"].includes(s)&&!Xe(e[s],n[s]))throw new Error(`Updating system fields in hooks is not allowed: ${s}`)}))},wr=(t,e,n,s)=>{const{softDelete:r}=e;if(!r)return;const i=r?.archivedField,o=r?.timestampField;if(n[i]===!0)if(t==="create")n[o]=oe.FieldValue.serverTimestamp();else{if(!s)throw new Error("Original record is required for update");if(!s[i])n[o]=oe.FieldValue.serverTimestamp();else if(n[o]&&n[o]?.valueOf()!==s[o]?.valueOf())throw new Error("Soft delete timestamp cannot be changed")}},bs=async(t,e,n,s,r)=>{if(!xe("Read",r.collections?.[e.labels.collection]))return!1;try{await Be([e.labels.collection],n,{userId:s,providedTransaction:t})}catch{return!1}return!0},pu=10,yu=async(t,e)=>{if(t.length===0)return;const n=Math.min(e,t.length);let s=0;const r=async()=>{for(;s<t.length;){const i=s;s+=1,await t[i]()}};await Promise.all(Array.from({length:n},r))},Jo=async(t,e,n,s,r,i,o)=>{for(const[a,l]of Object.entries(e?.collections||{})){if(!r.collections[a])throw new Error("PERMISSION_DENIED");const c=r.collections[a].access,d=r.collections[a];if(s.collections?.[a]?.restrictEntities||s?.collections?.[a]?.recordOwner?.active||s?.collections?.[a]?.recordUser?.active||s?.collections?.[a]?.recordProperty?.active){const u=i?.collections?.[a],f=[];if(l.individualEntities){const g=l.individualEntities,k=u?.individualEntities||[],y=i?g.filter(E=>!k.includes(E)):g;for(const E 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 bs(t,d,E,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentEntities){const g=c.entityRestrictions?.restrictions?.find(O=>O.type==="Parent"&&O.roles.some(_=>_.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const k=L(d.fields,g.collectionField),y=r.collections[k.collection],E=l.parentEntities,w=u?.parentEntities||[],A=i?E.filter(O=>!w.includes(O)):E;for(const O of A){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 bs(t,y,O,n,s))throw new Error("PERMISSION_DENIED")})}}if(l.parentPropertyEntities){const g=c.entityRestrictions?.restrictions?.find(A=>A.type==="Parent_Property"&&A.roles.some(O=>O.role===e.Role));if(!g)throw new Error("PERMISSION_DENIED");const k=L(d.fields,g.collectionField),y=r.collections[k.collection],E=l.parentPropertyEntities,w=u?.parentPropertyEntities||{};for(const[A,O]of Object.entries(E)){const _=w[A]||[],I=i?O.filter(j=>!_.includes(j)):O;for(const j of I){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 bs(t,y,j,n,s))throw new Error("PERMISSION_DENIED")})}}}await yu(f,pu)}}},gu=async(t,e,n)=>{const s=n?.userId,r=n?.user;let i=n?.context;const o=Je(),a=It();if(n?.providedTransaction&&s)throw new Error("PERMISSION_DENIED");if(n?.providedSchema&&s)throw new Error("PERMISSION_DENIED");let l=n?.providedSchema||await Ye();if(t.length===0)throw new Error("EMPTY_PATH");const c=t.at(-1),d=Object.keys(l.collections).includes(c),p=a.disabledCollections?.includes(c);if(!d||p)throw new Error("COLLECTION_NOT_FOUND");const u=l.collections[c],{labels:f,fields:g,enableWriteLog:k,softDelete:y}=u,E=rt(f.collection,l),w=await ae(a.appName),A=fe(),O=bt.getAuth(),_=s?await O.getUser(s):void 0;let I,j;s&&await pr(t,u);const v=Ne(A,t,o),U=n?.id||v.doc().id;i=i||{},i.collection=f.collection,e.id=U,yr(e),is(e);const h=Js("create",t,e,l,w,"Online",s||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp());n?.createdAt&&(h.Created_At=n.createdAt),n?.createdBy&&(h.Created_By=n.createdBy);const x=pe(h);y&&(h[y.archivedField]=!1),Ze(e),wt(u,h,l),k&&!n?.providedTransaction&&await kt("create","started",h,o,t,U,u),await ce("preOperation",a,E,{operation:"create",data:h,recordId:U,context:i}),await ce("preWrite",a,E,{operation:"create",data:h,recordId:U,context:i}),wt(u,h,l),Mn(u,h);const m=(s?await A.collection("tenants").doc(o).collection("system_user_permissions").doc(s).get():void 0)?.data();await ba(h,u,E,m,_?.customClaims||{}),Ze(h);try{if(u.auth&&r){if(!r.password)throw new Error("Password is required");if(!h.Role)throw new Error("Role field is required");if(!h.Email)throw new Error("Email field is required");if(h.Enabled===void 0||h.Enabled===null)throw new Error("Enabled field is required")}n?.providedTransaction||await hn("create",h,u,E,{operation:"create",data:h,context:i},l)}catch(D){throw new Error(`VALIDATION_ERROR: ${D.message}`)}Ze(h),e.id=U,y&&(h[y.archivedField]=!1),wt(u,h,l),Mn(u,h);try{Yo("create",h,x),wr("create",u,h),await hn("create",h,u,E,{operation:"create",data:h,context:i},l)}catch(D){throw new Error(`VALIDATION_ERROR: ${D.message}`)}if(s){if(!_)throw new Error("USER_ERROR");if(!m?.Role)throw new Error("USER_ERROR");const D=m;if(!(E.custom?.serverAccess?.create!==void 0?await ae(E.custom.serverAccess.create,[D,_,h]):!0))throw new Error("PERMISSION_DENIED");for(const H of u.fields){if(!(H.name in h))continue;const C=We(H,E);if(C?.custom?.serverAccess?.create!==void 0&&!await ae(C.custom.serverAccess.create,[D,_,h]))throw new Error("PERMISSION_DENIED")}}r&&(r.permissions||={},r.permissions.Role||=h.Role,r.permissions.Enabled||=h.Enabled);const T=async(D,M)=>{const[H,C,B,S,Q]=await Promise.all([n?.providedTransaction?Promise.resolve({}):D.get(A.collection("system_deployment").doc("latest_deploy")),n?.providedTransaction?Promise.resolve({}):D.get(A.collection("system_deployment").doc("maintenance_mode")),s?D.get(A.collection("tenants").doc(o).collection("system_user_permissions").doc(s)):Promise.resolve({}),n?.providedSchema?Promise.resolve(n.providedSchema):Ye(),s?Ht(s):Promise.resolve(void 0)]);if(M&&(M.size+=3),!n?.providedTransaction){if(!H.exists)throw new Error("VERSION_ERROR");const ee=H.data();if(ee.force&&h.Last_Write_At.valueOf()<ee.time.valueOf())throw new Error("VERSION_ERROR");if(!C.exists)throw new Error("MAINTENANCE_MODE");if(C.data().active)throw new Error("MAINTENANCE_MODE")}if(l=S,s){if(!B?.exists)throw new Error("PERMISSION_DENIED");if(I=B.data(),!I.Role)throw new Error("USER_ERROR");if(!I.Enabled)throw new Error("PERMISSION_DENIED");j=Q?.customClaims??{}}if(!n?.providedTransaction){const ye=g.filter(le=>"unique"in le&&le.unique).map(async le=>{if(!s||!le.access||He(le,I,u,j)){if(!h[le.name])return;const Qe=We(le,E);if(!(s&&I&&Q&&Qe?.custom?.serverAccess?.read!==void 0?await ae(Qe.custom.serverAccess.read,[I,Q,h]):!0))throw new Error("PERMISSION_DENIED");const De=h[le.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Vo(De)){if(M&&M.size++,M&&M.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");if((await D.get(A.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${le.name}`).doc(De)))?.exists)throw new Error(`VALIDATION_ERROR: ${le.name} "${h[le.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${le.name} "${h[le.name]}" is invalid`)}});await Promise.all(ye)}kr(h,U,u,l,s,I,r?.permissions,j),r?.permissions&&s&&I&&await Jo(D,r.permissions,s,I,l),kr(h,U,u,l,s,I,r?.permissions,j)};if(u.auth&&r){await A.runTransaction(async M=>{await T(M)},{maxAttempts:10});const D=await mr(o,U,a,u,h,r.permissions,r.password);h.User_ID=D}const b=async D=>{try{const M={size:1};await T(D,M),n?.noTwoWay||await gr("Create",o,U,h,h,u,l,D,M,s,I,void 0,j);const H=Ys(l);or("create",D,t,U,h,l,u,n,H,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,C=>A.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${C.name}`).doc(U),(C,B)=>A.collection("tenants").doc(o).collection("system_unique").doc(f.collection).collection(`Unique-${f.collection}-${C.name}`).doc(B),C=>A.collection("tenants").doc(o).collection("system_fields").doc(f.collection).collection(`${f.collection}-${C}`).doc(U),(C,B)=>Ne(A,C,o).doc(B),(C,B,S)=>A.collection("tenants").doc(o).collection("system_fields").doc(C.collection).collection(`${C.collection}-${B}`).doc(S),(C,B,S)=>A.collection("tenants").doc(o).collection("system_fields").doc(C.collection).collection(`${C.collection}-${B.replaceAll(" ","-")}`).doc(S),void 0,void 0,M),D.set(v.doc(U),h)}catch(M){if(n?.providedTransaction)throw M;{const C=await ce("postWriteError",a,E,{operation:"create",data:h,recordId:U,context:i,error:M});if(k&&(await new Promise(B=>{setTimeout(B,250)}),await kt("create",C?.resolved?"success":"failed",h,o,t,U,u,C?.resolved?void 0:M)),!C?.resolved)throw u.auth&&r&&await Gt(h),M}}};if(n?.providedTransaction?await b(n.providedTransaction):await A.runTransaction(async D=>{await b(D)},{maxAttempts:10}),!n?.providedTransaction){const D={operation:"create",data:h,recordId:U,context:i},M={...D};await ce("postWrite",a,E,D),await ce("postOperation",a,E,M)}return{id:U,...h}},rn=async(t,e,n,s)=>{const r=Je(),i=bt.getAuth(),o=fe(),a=e.customClaims||{};let l=!1;try{await i.updateUser(t,{email:e.email,disabled:e.disabled,displayName:e.displayName,photoURL:e.photoURL,emailVerified:!!e.emailVerified})}catch{l=!0}try{await i.setCustomUserClaims(t,{...a})}catch{l=!0}try{await o.collection("tenants").doc(r).collection("system_user_permissions").doc(t).update({...n,Collection:a.collection,Doc_ID:a.doc,Role:a.role,Enabled:!e.disabled})}catch{l=!0}if(l)throw new Error(`ROLLBACK_FAILED: ${s}`)},Qo=async(t,e,n,s,r,i,o,a,l,c,d)=>{const p=bt.getAuth(),u=fe(),f={};for(const y of r.fields)y.saveToAuthToken&&!hr(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 k="";if(t==="create"){if(!d)throw new Error("VALIDATION_ERROR: Password is required");if(!l)throw new Error("VALIDATION_ERROR: Permissions are required");try{k=await mr(e,n,s,r,i,l,d)}catch(y){throw new Error(y.message)}}else if(t==="update"){if(!c||!a)throw new Error("USER_ERROR");const y={};if(o.Name!==i.Name&&(y.displayName=i.Name),o.Email!==i.Email&&(y.email=i.Email,y.emailVerified=!1),o.Photo_URL!==i.Photo_URL&&(y.photoURL=i.Photo_URL?i.Photo_URL:void 0),o.Enabled!==i.Enabled&&(y.disabled=!i.Enabled),d&&(y.password=d),Object.keys(y).length)try{await p.updateUser(o.User_ID,y),y.disabled===!0&&await p.revokeRefreshTokens(o.User_ID)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}if(i.Role&&i.Role!==o.Role||Object.keys(f).length)try{const E={...du(a.customClaims),...f};await p.setCustomUserClaims(o.User_ID,{...E,tenant:e,role:i.Role,collection:r.labels.collection,doc:n}),await p.revokeRefreshTokens(o.User_ID)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}try{await u.collection("tenants").doc(e).collection("system_user_permissions").doc(o.User_ID).set({...l||c,Collection:r.labels.collection,Doc_ID:n,Role:i.Role,Enabled:i.Enabled??o.Enabled??!1})}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}if(o.Email!==i.Email){const E=s.auth.enableMultiFactorAuth;if(E===!0||typeof E=="object"&&E.includes(i.Role)){let w=await p.generateEmailVerificationLink(i.Email).catch(()=>{throw new Error("Error generating email verification link")});if(w.includes("apiKey=&")){const A=JSON.parse(process.env.STOKER_FB_WEB_APP_CONFIG);w=w.replace("apiKey=&",`apiKey=${A.apiKey}&`)}if(w){const A=`https://${p.app.options.projectId}.firebaseapp.com/__/auth/action${w}`,O=await ae(s.appName),_=s?.mail?.emailVerification&&s.mail.emailVerification(A,O);try{await fr(i.Email,_?.subject||"Please verify your email address",void 0,_?.html||`Please verify your email address by clicking the link:
|
|
12
12
|
</br>
|
|
13
13
|
</br>
|
|
14
|
-
<a href="${A}">${A}</a>`)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}}}}}else if(t==="delete")try{await Gt(o)}catch(y){throw new Error(y.message)}if(k)return k},wu=async(t,e,n)=>{const s=Je(),r=fe(),i=[e];n&&n.trim()!==""&&i.push(n),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await t.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)t.set(a,{locked:!0})},_i=async(t,e)=>{const n=Je(),s=fe(),r=[t];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(n).collection("system_locks").doc(o);i.delete(a)}await i.commit()},Ko=async(t,e,n,s)=>{const r=s?.userId;let i=s?.user,o=s?.context;const a=Je(),l=It();if(s?.providedTransaction&&r)throw new Error("PERMISSION_DENIED");if(s?.providedSchema&&r)throw new Error("PERMISSION_DENIED");if(s?.providedTransaction&&!s?.originalRecord)throw new Error("PERMISSION_DENIED");let c=s?.providedSchema||await Ye(!0);if(t.length===0)throw new Error("EMPTY_PATH");const d=t.at(-1),p=Object.keys(c.collections).includes(d),u=l.disabledCollections?.includes(d);if(!p||u)throw new Error("COLLECTION_NOT_FOUND");const f=c.collections[d],{labels:g,fields:k,enableWriteLog:y}=f,E=rt(g.collection,c),w=await ae(l.appName),A=bt.getAuth(),O=fe();let _,I;r&&await pr(t,f);const j=Ne(O,t,a);o=o||{},o.collection=g.collection;let v=s?.originalRecord||await Be(t,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0}),U=v;r&&(U=await Be(t,e,{noComputedFields:!0,noEmbeddingFields:!0}));for(const S of k)S.type==="Computed"&&(delete n[S.name],delete v[S.name]);if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([S,Q])=>[S,{...Q,fields:Q.fields.filter(ee=>ee.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 h=f.fields.filter(S=>S.saveToAuthToken&&!hr(S.name)),x=f.auth&&i?.operation==="create",R=f.auth&&i?.operation==="delete",q=f.auth&&!x&&!R&&(i?.operation==="update"||v.User_ID&&(n.Role||n.Enabled!==void 0||n.Name||n.Email||n.Photo_URL||h.some(S=>n[S.name]!==void 0))),Z=S=>S.User_ID&&(f.auth&&!x&&!R&&i?.operation==="update"||n.Role&&n.Role!==S.Role||n.Enabled!==void 0&&n.Enabled!==S.Enabled||n.Name&&n.Name!==S.Name||n.Email&&n.Email!==S.Email||n.Photo_URL&&n.Photo_URL!==S.Photo_URL||h.some(Q=>n[Q.name]!==void 0&&n[Q.name]!==S[Q.name]));delete n.id,yr(n),is(n);const m=Js("update",t,n,c,w,"Online",r||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp()),T=pe(m);for(const S of k)!X(S)&&Oe(m[S.name])&&S.nullable&&(m[S.name]=null);Ze(m),Ze(v),wt(f,m,c),wt(f,v,c),y&&!s?.providedTransaction&&await kt("update","started",m,a,t,e,f,void 0,v);const b={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)};await ce("preOperation",l,E,b);const F={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)};await ce("preWrite",l,E,F),wt(f,m,c),Mn(f,m),Ze(m);try{if(x&&!i?.password)throw new Error("Password is required");if(!s?.providedTransaction){const S={...U,...m};et(S),await hn("update",S,f,E,{operation:"update",data:m,context:o,originalRecord:pe(v)},c)}}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}Ze(m),delete n.id,wt(f,m,c),Mn(f,m);for(const S of k)!X(S)&&Oe(m[S.name])&&S.nullable&&(m[S.name]=null);try{const S={...U,...m};et(S),wr("update",f,m,v),Yo("update",m,T),await hn("update",S,f,E,{operation:"update",data:m,context:o,originalRecord:pe(v)},c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}let D;i&&(i.permissions||={});const M=async(S,Q,ee)=>{const[ye,le,Qe,ge,De,Ce]=await Promise.all([s?.providedTransaction?Promise.resolve({}):S.get(O.collection("system_deployment").doc("latest_deploy")),s?.providedTransaction?Promise.resolve({}):S.get(O.collection("system_deployment").doc("maintenance_mode")),s?.providedTransaction?Promise.resolve(v):Be(t,e,{userId:r,providedTransaction:S,noComputedFields:!0}),r?S.get(O.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve({}),s?.providedSchema?Promise.resolve(s.providedSchema):Ye(),r?Ht(r):Promise.resolve(void 0)]);if(ee&&(ee.size+=3),!s?.providedTransaction){if(!ye.exists)throw new Error("VERSION_ERROR");const we=ye.data();if(we.force&&m.Last_Write_At.valueOf()<we.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(!Qe)throw new Error("NOT_FOUND");if(v=Qe,c=De,r){if(!ge?.exists)throw new Error("PERMISSION_DENIED");if(_=ge.data(),!_.Role)throw new Error("USER_ERROR");if(!_.Enabled)throw new Error("PERMISSION_DENIED");I=Ce?.customClaims??{}}if(ee&&(ee.size+=cr(a,t,e,c,_,I).length),x&&v.User_ID||R&&!v.User_ID)throw new Error("USER_ERROR");if(Z(v)){const we=await S.get(O.collection("tenants").doc(a).collection("system_user_permissions").doc(v.User_ID));if(ee&&ee.size++,!we?.exists)throw new Error("PERMISSION_DENIED");D=we.data();const Yt=i?.permissions&&Object.keys(i.permissions).length>0?i.permissions:void 0;if(m.Role&&m.Role!==v.Role&&!Yt&&(i||={operation:"update",permissions:{}},i.permissions=pe(D),i.permissions.Role=m.Role),i?.permissions){if(i.permissions.Role||=m.Role||v.Role,i.permissions.Enabled??=m.Enabled??v.Enabled,Oe(i.permissions.Role)||!i.permissions.Role)throw new Error("VALIDATION_ERROR: Role field is required");if(Oe(i.permissions.Enabled)||i.permissions.Enabled===void 0||i.permissions.Enabled===null)throw new Error("VALIDATION_ERROR: Enabled field is required")}}if(x){const we={...v,...m};if(et(we),!we.Role)throw new Error("VALIDATION_ERROR: Role field is required");if(we.Enabled===void 0||we.Enabled===null)throw new Error("VALIDATION_ERROR: Enabled field is required");if(!we.Email)throw new Error("VALIDATION_ERROR: Email field is required");i?.permissions&&(i.permissions.Role||=we.Role,i.permissions.Enabled??=we.Enabled)}if(!s?.providedTransaction){const Yt=k.filter(_e=>"unique"in _e&&_e.unique).map(async _e=>{if(!r||!_e.access||He(_e,_,f,I)){if(m[_e.name]===void 0||Oe(m[_e.name]))return;const Jt=We(_e,E),_r={...v,...m};if(!(r&&_&&Ce&&Jt?.custom?.serverAccess?.read!==void 0?await ae(Jt.custom.serverAccess.read,[_,Ce,_r]):!0))throw new Error("PERMISSION_DENIED");const Er=m[_e.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Vo(Er)){if(ee&&ee.size++,ee&&ee.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");const vr=await S.get(O.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${_e.name}`).doc(Er));if(vr.exists&&vr.data().id!==e)throw new Error(`VALIDATION_ERROR: ${_e.name} "${m[_e.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${_e.name} "${m[_e.name]}" is invalid`)}});await Promise.all(Yt)}if(r&&_?.Role){if(!Ce)throw new Error("USER_ERROR");const we={...v,...m};if(!(E.custom?.serverAccess?.update!==void 0?await ae(E.custom.serverAccess.update,[_,Ce,we,v]):!0))throw new Error("PERMISSION_DENIED");for(const _e of f.fields){const Jt=We(_e,E);if(Object.prototype.hasOwnProperty.call(m,_e.name)&&Jt?.custom?.serverAccess?.update!==void 0&&!await ae(Jt.custom.serverAccess.update,[_,Ce,we,v]))throw new Error("PERMISSION_DENIED")}}br(m,v,e,f,c,r,_,i?.operation?i.operation:q?"update":void 0,i?.permissions,D,I),i?.permissions&&r&&_&&await Jo(S,i.permissions,r,_,c,D,ee),br(m,v,e,f,c,r,_,i?.operation?i.operation:q?"update":void 0,i?.permissions,D,I),Q&&(x||Z(v)||R)&&await wu(S,e,v.User_ID)};(x||q||R)&&await O.runTransaction(async S=>{await M(S,!0)},{maxAttempts:10});const H=async(S,Q)=>{if(!v)throw new Error("NOT_FOUND");try{const ee={size:1},ye={...v,...m};await M(S,!1,ee);let le;!s?.noTwoWay&&!s?.providedTransaction&&(le=await gr("Update",a,e,ye,m,f,c,S,ee,r,_,v,I));const Qe=Ys(c);or("update",S,t,e,m,c,f,s,Qe,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,ge=>O.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${ge.name}`).doc(e),(ge,De)=>O.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${ge.name}`).doc(De),ge=>O.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${ge}`).doc(e),(ge,De)=>Ne(O,ge,a).doc(De),(ge,De,Ce)=>O.collection("tenants").doc(a).collection("system_fields").doc(ge.collection).collection(`${ge.collection}-${De}`).doc(Ce),(ge,De,Ce)=>O.collection("tenants").doc(a).collection("system_fields").doc(ge.collection).collection(`${ge.collection}-${De.replaceAll(" ","-")}`).doc(Ce),v,le,ee),S.update(j.doc(e),m)}catch(ee){if(s?.providedTransaction)throw ee;{const ye={operation:"update",data:m,recordId:e,context:o,error:ee,originalRecord:pe(v)},le=await ce("postWriteError",l,E,ye);if(y&&(await new Promise(Qe=>{setTimeout(Qe,250)}),await kt("update",le?.resolved?"success":"failed",m,a,t,e,f,le?.resolved?void 0:ee,v)),!le?.resolved)throw x&&await Gt(v),Z(v)&&await rn(v.User_ID,Q,D,"USER_ERROR"),R&&await O.collection("tenants").doc(a).collection(g.collection).doc(e).update({User_ID:oe.FieldValue.delete()}),ee}}(x||Z(v)||R)&&await pi(_i,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")})};try{let S;if(x||Z(v)||R){if(Z(v)){S=await A.getUser(v.User_ID);const ye=S.customClaims;if(!(ye&&ye.role&&ye.collection&&ye.doc))throw new Error("USER_ERROR")}const Q={...v,...m};et(Q);const ee=await Qo(i?.operation||"update",a,e,l,f,Q,v,S,i?.permissions,D,i?.password);x&&(m.User_ID=ee),R&&(m.User_ID=oe.FieldValue.delete())}s?.providedTransaction?await H(s.providedTransaction,S):await O.runTransaction(async Q=>{await H(Q,S)},{maxAttempts:10})}catch(S){throw(x||Z(v)||R)&&await pi(_i,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),S}if(!s?.providedTransaction){const S={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)},Q={...S};await ce("postWrite",l,E,S),await ce("postOperation",l,E,Q)}const C={...v,...m};return et(C),{id:e,...C}},_u=async(t,e,n)=>{const s=n?.userId;let r=n?.context;const i=Je(),o=It();let a=await Ye();if(t.length===0)throw new Error("EMPTY_PATH");const l=t.at(-1),c=Object.keys(a.collections).includes(l),d=o.disabledCollections?.includes(l);if(!c||d)throw new Error("COLLECTION_NOT_FOUND");const p=a.collections[l],{labels:u,auth:f,enableWriteLog:g,softDelete:k}=p,y=rt(u.collection,a),E=await ae(o.appName);if(k&&!f&&!n?.force)return await Ko(t,e,{[k.archivedField]:!0,[k.timestampField]:oe.FieldValue.serverTimestamp()},{userId:s});const w=fe();let A;s&&await pr(t,p);const O=Ne(w,t,i);r=r||{},r.collection=u.collection;const _=await Be(t,e,{userId:s});let I=Js("delete",t,_,a,E,"Online",s||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp());const j=$n(I);Ze(I),g&&await kt("delete","started",I,i,t,e,p),await ce("preOperation",o,y,{operation:"delete",data:I,recordId:e,context:r}),await ce("preWrite",o,y,{operation:"delete",data:I,recordId:e,context:r}),Ze(I);const h=async Z=>{const[m,T,b,F,D]=await Promise.all([Z.get(w.collection("system_deployment").doc("maintenance_mode")),Be(t,e,{userId:s,providedTransaction:Z}),s?Z.get(w.collection("tenants").doc(i).collection("system_user_permissions").doc(s)):Promise.resolve({}),Ye(),s?Ht(s):Promise.resolve(void 0)]);if(!m.exists)throw new Error("MAINTENANCE_MODE");if(m.data().active)throw new Error("MAINTENANCE_MODE");if(!T)throw new Error("NOT_FOUND");if(I={...T,...j},a=F,s){if(!b?.exists)throw new Error("PERMISSION_DENIED");if(A=b.data(),!A.Role)throw new Error("USER_ERROR");if(!A.Enabled)throw new Error("PERMISSION_DENIED");fa(I,e,p,a,s,A)}if(s&&A?.Role){if(!D)throw new Error("USER_ERROR");if(!(y.custom?.serverAccess?.delete!==void 0?await ae(y.custom.serverAccess.delete,[A,D,I]):!0))throw new Error("PERMISSION_DENIED")}};p.auth&&(await w.runTransaction(async Z=>{await h(Z)},{maxAttempts:10}),I.User_ID&&await Gt(I));try{await w.runTransaction(async Z=>{await h(Z);const m=Ys(a);or("delete",Z,t,e,I,a,p,n,m,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,T=>w.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${T.name}`).doc(e),(T,b)=>w.collection("tenants").doc(i).collection("system_unique").doc(u.collection).collection(`Unique-${u.collection}-${T.name}`).doc(b),T=>w.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${T}`).doc(e),(T,b)=>Ne(w,T,i).doc(b),(T,b,F)=>w.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${b}`).doc(F),(T,b,F)=>w.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${b.replaceAll(" ","-")}`).doc(F)),Z.delete(O.doc(e))},{maxAttempts:10})}catch(Z){const T=await ce("postWriteError",o,y,{operation:"delete",data:I,recordId:e,context:r,error:Z});if(g&&(await new Promise(b=>{setTimeout(b,250)}),await kt("delete",T?.resolved?"success":"failed",I,i,t,e,p,T?.resolved?void 0:Z)),!T?.resolved)throw p.auth&&I.User_ID&&await w.collection("tenants").doc(i).collection(u.collection).doc(e).update({User_ID:oe.FieldValue.delete()}),Z}const x={operation:"delete",data:I,recordId:e,context:r},R={...x};return await ce("postWrite",o,y,x),await ce("postOperation",o,y,R),{id:e,...I}},Eu=async(t,e)=>{const n=fe(),s=ar(),r=process.env.ADMIN_SMS;if(s==="development")if(r)t=r;else throw new Error("Admin phone not set");const i={to:t,body:e};await n.collection("system_messages").add(i)},vu=t=>t!==null&&typeof t=="object",Ou=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{r instanceof oe.Timestamp?n[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:vu(r)&&e(r)})};e(t)},ku=t=>{const e=lr();return V.fromJSDate(t).setZone(e)},Xo=t=>{const e=lr();return V.fromJSDate(t.toDate()).setZone(e)},bu=(t,e)=>{const s=V.fromJSDate(t,{zone:e}).offset,i=V.fromJSDate(t).offset,o=s-i;return V.fromJSDate(t).plus({minutes:o}).toJSDate()},Ru=(t,e)=>{const s=V.fromJSDate(t,{zone:e}).offset,i=V.fromJSDate(t).offset,o=s-i;return V.fromJSDate(t).minus({minutes:o}).toJSDate()},Tu=t=>"seconds"in t&&"nanoseconds"in t?Xo(new oe.Timestamp(t.seconds,t.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=gu;exports.addUser=mr;exports.convertDateToTimezone=ku;exports.convertTimestampToTimezone=Xo;exports.deleteRecord=_u;exports.deleteUser=Gt;exports.deserializeDeleteSentinels=is;exports.deserializeTimestamps=yr;exports.deserializeTimestampsWithoutUnderscores=fu;exports.displayDate=Tu;exports.fetchCurrentSchema=Ye;exports.fetchLastSchema=cu;exports.getCachedConfigValue=wa;exports.getCollectionRefs=zo;exports.getCustomizationFile=rt;exports.getCustomizationFiles=Uo;exports.getDocumentRefs=cr;exports.getFirestorePathRef=Ne;exports.getGlobalConfigModule=It;exports.getInputSchema=eu;exports.getMaintenanceInfo=ou;exports.getMode=ar;exports.getOne=Be;exports.getSome=dr;exports.getStokerFirestore=fe;exports.getTenant=Je;exports.getTimezone=lr;exports.getUser=Ht;exports.getVersionInfo=iu;exports.getZodSchema=$i;exports.initializeFirebase=lu;exports.initializeStoker=su;exports.isDeleteSentinel=Oe;exports.keepTimezone=bu;exports.removeTimezone=Ru;exports.runChildProcess=au;exports.sendMail=fr;exports.sendMessage=Eu;exports.serializeTimestamps=Ou;exports.setTenant=ru;exports.tryPromise=ae;exports.updateRecord=Ko;exports.updateUser=Qo;exports.validateRelations=gr;exports.validateSoftDelete=wr;exports.writeLog=kt;
|
|
14
|
+
<a href="${A}">${A}</a>`)}catch{throw await rn(o.User_ID,a,c,g),new Error(g)}}}}}else if(t==="delete")try{await Gt(o)}catch(y){throw new Error(y.message)}if(k)return k},wu=async(t,e,n)=>{const s=Je(),r=fe(),i=[e];n&&n.trim()!==""&&i.push(n),i.sort();const o=[];for(const a of i){const l=r.collection("tenants").doc(s).collection("system_locks").doc(a);if((await t.get(l)).exists)throw new Error("DOCUMENT_LOCKED");o.push(l)}for(const a of o)t.set(a,{locked:!0})},_i=async(t,e)=>{const n=Je(),s=fe(),r=[t];e&&e.trim()!==""&&r.push(e),r.sort();const i=s.batch();for(const o of r){const a=s.collection("tenants").doc(n).collection("system_locks").doc(o);i.delete(a)}await i.commit()},Ko=async(t,e,n,s)=>{const r=s?.userId;let i=s?.user,o=s?.context;const a=Je(),l=It();if(s?.providedTransaction&&r)throw new Error("PERMISSION_DENIED");if(s?.providedSchema&&r)throw new Error("PERMISSION_DENIED");if(s?.providedTransaction&&!s?.originalRecord)throw new Error("PERMISSION_DENIED");let c=s?.providedSchema||await Ye(!0);if(t.length===0)throw new Error("EMPTY_PATH");const d=t.at(-1),p=Object.keys(c.collections).includes(d),u=l.disabledCollections?.includes(d);if(!p||u)throw new Error("COLLECTION_NOT_FOUND");const f=c.collections[d],{labels:g,fields:k,enableWriteLog:y}=f,E=rt(g.collection,c),w=await ae(l.appName),A=bt.getAuth(),O=fe();let _,I;r&&await pr(t,f);const j=Ne(O,t,a);o=o||{},o.collection=g.collection;let v=s?.originalRecord||await Be(t,e,{userId:r,noComputedFields:!0,noEmbeddingFields:!0}),U=v;r&&(U=await Be(t,e,{noComputedFields:!0,noEmbeddingFields:!0}));for(const S of k)S.type==="Computed"&&(delete n[S.name],delete v[S.name]);if(c={...c,collections:Object.fromEntries(Object.entries(c.collections).map(([S,Q])=>[S,{...Q,fields:Q.fields.filter(ee=>ee.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 h=f.fields.filter(S=>S.saveToAuthToken&&!hr(S.name)),x=f.auth&&i?.operation==="create",R=f.auth&&i?.operation==="delete",q=f.auth&&!x&&!R&&(i?.operation==="update"||v.User_ID&&(n.Role||n.Enabled!==void 0||n.Name||n.Email||n.Photo_URL||h.some(S=>n[S.name]!==void 0))),Z=S=>S.User_ID&&(f.auth&&!x&&!R&&i?.operation==="update"||n.Role&&n.Role!==S.Role||n.Enabled!==void 0&&n.Enabled!==S.Enabled||n.Name&&n.Name!==S.Name||n.Email&&n.Email!==S.Email||n.Photo_URL&&n.Photo_URL!==S.Photo_URL||h.some(Q=>n[Q.name]!==void 0&&n[Q.name]!==S[Q.name]));delete n.id,yr(n),is(n);const m=Js("update",t,n,c,w,"Online",r||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp()),T=pe(m);for(const S of k)!X(S)&&be(m[S.name])&&S.nullable&&(m[S.name]=null);Ze(m),Ze(v),wt(f,m,c),wt(f,v,c),y&&!s?.providedTransaction&&await kt("update","started",m,a,t,e,f,void 0,v);const b={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)};await ce("preOperation",l,E,b);const F={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)};await ce("preWrite",l,E,F),wt(f,m,c),Mn(f,m),Ze(m);try{if(x&&!i?.password)throw new Error("Password is required");if(!s?.providedTransaction){const S={...U,...m};et(S),await hn("update",S,f,E,{operation:"update",data:m,context:o,originalRecord:pe(v)},c)}}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}Ze(m),delete n.id,wt(f,m,c),Mn(f,m);for(const S of k)!X(S)&&be(m[S.name])&&S.nullable&&(m[S.name]=null);try{const S={...U,...m};et(S),wr("update",f,m,v),Yo("update",m,T),await hn("update",S,f,E,{operation:"update",data:m,context:o,originalRecord:pe(v)},c)}catch(S){throw new Error(`VALIDATION_ERROR: ${S.message}`)}let D;i&&(i.permissions||={});const M=async(S,Q,ee)=>{const[ye,le,Qe,ge,De,Ce]=await Promise.all([s?.providedTransaction?Promise.resolve({}):S.get(O.collection("system_deployment").doc("latest_deploy")),s?.providedTransaction?Promise.resolve({}):S.get(O.collection("system_deployment").doc("maintenance_mode")),s?.providedTransaction?Promise.resolve(v):Be(t,e,{userId:r,providedTransaction:S,noComputedFields:!0}),r?S.get(O.collection("tenants").doc(a).collection("system_user_permissions").doc(r)):Promise.resolve({}),s?.providedSchema?Promise.resolve(s.providedSchema):Ye(),r?Ht(r):Promise.resolve(void 0)]);if(ee&&(ee.size+=3),!s?.providedTransaction){if(!ye.exists)throw new Error("VERSION_ERROR");const we=ye.data();if(we.force&&m.Last_Write_At.valueOf()<we.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(!Qe)throw new Error("NOT_FOUND");if(v=Qe,c=De,r){if(!ge?.exists)throw new Error("PERMISSION_DENIED");if(_=ge.data(),!_.Role)throw new Error("USER_ERROR");if(!_.Enabled)throw new Error("PERMISSION_DENIED");I=Ce?.customClaims??{}}if(ee&&(ee.size+=cr(a,t,e,c,_,I).length),x&&v.User_ID||R&&!v.User_ID)throw new Error("USER_ERROR");if(Z(v)){const we=await S.get(O.collection("tenants").doc(a).collection("system_user_permissions").doc(v.User_ID));if(ee&&ee.size++,!we?.exists)throw new Error("PERMISSION_DENIED");D=we.data();const Yt=i?.permissions&&Object.keys(i.permissions).length>0?i.permissions:void 0;if(m.Role&&m.Role!==v.Role&&!Yt&&(i||={operation:"update",permissions:{}},i.permissions=pe(D),i.permissions.Role=m.Role),i?.permissions){if(i.permissions.Role||=m.Role||v.Role,i.permissions.Enabled??=m.Enabled??v.Enabled,be(i.permissions.Role)||!i.permissions.Role)throw new Error("VALIDATION_ERROR: Role field is required");if(be(i.permissions.Enabled)||i.permissions.Enabled===void 0||i.permissions.Enabled===null)throw new Error("VALIDATION_ERROR: Enabled field is required")}}if(x){const we={...v,...m};if(et(we),!we.Role)throw new Error("VALIDATION_ERROR: Role field is required");if(we.Enabled===void 0||we.Enabled===null)throw new Error("VALIDATION_ERROR: Enabled field is required");if(!we.Email)throw new Error("VALIDATION_ERROR: Email field is required");i?.permissions&&(i.permissions.Role||=we.Role,i.permissions.Enabled??=we.Enabled)}if(!s?.providedTransaction){const Yt=k.filter(_e=>"unique"in _e&&_e.unique).map(async _e=>{if(!r||!_e.access||He(_e,_,f,I)){if(m[_e.name]===void 0||be(m[_e.name]))return;const Jt=We(_e,E),_r={...v,...m};if(!(r&&_&&Ce&&Jt?.custom?.serverAccess?.read!==void 0?await ae(Jt.custom.serverAccess.read,[_,Ce,_r]):!0))throw new Error("PERMISSION_DENIED");const Er=m[_e.name].toString().toLowerCase().replace(/\s/g,"---").replaceAll("/","|||");if(Vo(Er)){if(ee&&ee.size++,ee&&ee.size>500)throw new Error("VALIDATION_ERROR: The number of operations in the Firestore transaction has exceeded the limit of 500. This is likely due to a large number of unique field checks.");const vr=await S.get(O.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${_e.name}`).doc(Er));if(vr.exists&&vr.data().id!==e)throw new Error(`VALIDATION_ERROR: ${_e.name} "${m[_e.name]}" already exists`)}else throw new Error(`VALIDATION_ERROR: ${_e.name} "${m[_e.name]}" is invalid`)}});await Promise.all(Yt)}if(r&&_?.Role){if(!Ce)throw new Error("USER_ERROR");const we={...v,...m};if(!(E.custom?.serverAccess?.update!==void 0?await ae(E.custom.serverAccess.update,[_,Ce,we,v]):!0))throw new Error("PERMISSION_DENIED");for(const _e of f.fields){const Jt=We(_e,E);if(Object.prototype.hasOwnProperty.call(m,_e.name)&&Jt?.custom?.serverAccess?.update!==void 0&&!await ae(Jt.custom.serverAccess.update,[_,Ce,we,v]))throw new Error("PERMISSION_DENIED")}}br(m,v,e,f,c,r,_,i?.operation?i.operation:q?"update":void 0,i?.permissions,D,I),i?.permissions&&r&&_&&await Jo(S,i.permissions,r,_,c,D,ee),br(m,v,e,f,c,r,_,i?.operation?i.operation:q?"update":void 0,i?.permissions,D,I),Q&&(x||Z(v)||R)&&await wu(S,e,v.User_ID)};(x||q||R)&&await O.runTransaction(async S=>{await M(S,!0)},{maxAttempts:10});const H=async(S,Q)=>{if(!v)throw new Error("NOT_FOUND");try{const ee={size:1},ye={...v,...m};await M(S,!1,ee);let le;!s?.noTwoWay&&!s?.providedTransaction&&(le=await gr("Update",a,e,ye,m,f,c,S,ee,r,_,v,I));const Qe=Ys(c);or("update",S,t,e,m,c,f,s,Qe,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,ge=>O.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${ge.name}`).doc(e),(ge,De)=>O.collection("tenants").doc(a).collection("system_unique").doc(g.collection).collection(`Unique-${g.collection}-${ge.name}`).doc(De),ge=>O.collection("tenants").doc(a).collection("system_fields").doc(g.collection).collection(`${g.collection}-${ge}`).doc(e),(ge,De)=>Ne(O,ge,a).doc(De),(ge,De,Ce)=>O.collection("tenants").doc(a).collection("system_fields").doc(ge.collection).collection(`${ge.collection}-${De}`).doc(Ce),(ge,De,Ce)=>O.collection("tenants").doc(a).collection("system_fields").doc(ge.collection).collection(`${ge.collection}-${De.replaceAll(" ","-")}`).doc(Ce),v,le,ee),S.update(j.doc(e),m)}catch(ee){if(s?.providedTransaction)throw ee;{const ye={operation:"update",data:m,recordId:e,context:o,error:ee,originalRecord:pe(v)},le=await ce("postWriteError",l,E,ye);if(y&&(await new Promise(Qe=>{setTimeout(Qe,250)}),await kt("update",le?.resolved?"success":"failed",m,a,t,e,f,le?.resolved?void 0:ee,v)),!le?.resolved)throw x&&await Gt(v),Z(v)&&await rn(v.User_ID,Q,D,"USER_ERROR"),R&&await O.collection("tenants").doc(a).collection(g.collection).doc(e).update({User_ID:oe.FieldValue.delete()}),ee}}(x||Z(v)||R)&&await pi(_i,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")})};try{let S;if(x||Z(v)||R){if(Z(v)){S=await A.getUser(v.User_ID);const ye=S.customClaims;if(!(ye&&ye.role&&ye.collection&&ye.doc))throw new Error("USER_ERROR")}const Q={...v,...m};et(Q);const ee=await Qo(i?.operation||"update",a,e,l,f,Q,v,S,i?.permissions,D,i?.password);x&&(m.User_ID=ee),R&&(m.User_ID=oe.FieldValue.delete())}s?.providedTransaction?await H(s.providedTransaction,S):await O.runTransaction(async Q=>{await H(Q,S)},{maxAttempts:10})}catch(S){throw(x||Z(v)||R)&&await pi(_i,[e,v.User_ID]).catch(()=>{throw new Error("USER_ERROR")}),S}if(!s?.providedTransaction){const S={operation:"update",data:m,recordId:e,context:o,originalRecord:pe(v)},Q={...S};await ce("postWrite",l,E,S),await ce("postOperation",l,E,Q)}const C={...v,...m};return et(C),{id:e,...C}},_u=async(t,e,n)=>{const s=n?.userId;let r=n?.context;const i=Je(),o=It();let a=await Ye();if(t.length===0)throw new Error("EMPTY_PATH");const l=t.at(-1),c=Object.keys(a.collections).includes(l),d=o.disabledCollections?.includes(l);if(!c||d)throw new Error("COLLECTION_NOT_FOUND");const p=a.collections[l],{labels:u,auth:f,enableWriteLog:g,softDelete:k}=p,y=rt(u.collection,a),E=await ae(o.appName);if(k&&!f&&!n?.force)return await Ko(t,e,{[k.archivedField]:!0,[k.timestampField]:oe.FieldValue.serverTimestamp()},{userId:s});const w=fe();let A;s&&await pr(t,p);const O=Ne(w,t,i);r=r||{},r.collection=u.collection;const _=await Be(t,e,{userId:s});let I=Js("delete",t,_,a,E,"Online",s||"System",oe.Timestamp.now(),oe.FieldValue.serverTimestamp());const j=$n(I);Ze(I),g&&await kt("delete","started",I,i,t,e,p),await ce("preOperation",o,y,{operation:"delete",data:I,recordId:e,context:r}),await ce("preWrite",o,y,{operation:"delete",data:I,recordId:e,context:r}),Ze(I);const h=async Z=>{const[m,T,b,F,D]=await Promise.all([Z.get(w.collection("system_deployment").doc("maintenance_mode")),Be(t,e,{userId:s,providedTransaction:Z}),s?Z.get(w.collection("tenants").doc(i).collection("system_user_permissions").doc(s)):Promise.resolve({}),Ye(),s?Ht(s):Promise.resolve(void 0)]);if(!m.exists)throw new Error("MAINTENANCE_MODE");if(m.data().active)throw new Error("MAINTENANCE_MODE");if(!T)throw new Error("NOT_FOUND");if(I={...T,...j},a=F,s){if(!b?.exists)throw new Error("PERMISSION_DENIED");if(A=b.data(),!A.Role)throw new Error("USER_ERROR");if(!A.Enabled)throw new Error("PERMISSION_DENIED");fa(I,e,p,a,s,A)}if(s&&A?.Role){if(!D)throw new Error("USER_ERROR");if(!(y.custom?.serverAccess?.delete!==void 0?await ae(y.custom.serverAccess.delete,[A,D,I]):!0))throw new Error("PERMISSION_DENIED")}};p.auth&&(await w.runTransaction(async Z=>{await h(Z)},{maxAttempts:10}),I.User_ID&&await Gt(I));try{await w.runTransaction(async Z=>{await h(Z);const m=Ys(a);or("delete",Z,t,e,I,a,p,n,m,oe.FieldValue.arrayUnion,oe.FieldValue.arrayRemove,oe.FieldValue.delete,T=>w.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${T.name}`).doc(e),(T,b)=>w.collection("tenants").doc(i).collection("system_unique").doc(u.collection).collection(`Unique-${u.collection}-${T.name}`).doc(b),T=>w.collection("tenants").doc(i).collection("system_fields").doc(u.collection).collection(`${u.collection}-${T}`).doc(e),(T,b)=>Ne(w,T,i).doc(b),(T,b,F)=>w.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${b}`).doc(F),(T,b,F)=>w.collection("tenants").doc(i).collection("system_fields").doc(T.collection).collection(`${T.collection}-${b.replaceAll(" ","-")}`).doc(F)),Z.delete(O.doc(e))},{maxAttempts:10})}catch(Z){const T=await ce("postWriteError",o,y,{operation:"delete",data:I,recordId:e,context:r,error:Z});if(g&&(await new Promise(b=>{setTimeout(b,250)}),await kt("delete",T?.resolved?"success":"failed",I,i,t,e,p,T?.resolved?void 0:Z)),!T?.resolved)throw p.auth&&I.User_ID&&await w.collection("tenants").doc(i).collection(u.collection).doc(e).update({User_ID:oe.FieldValue.delete()}),Z}const x={operation:"delete",data:I,recordId:e,context:r},R={...x};return await ce("postWrite",o,y,x),await ce("postOperation",o,y,R),{id:e,...I}},Eu=async(t,e)=>{const n=fe(),s=ar(),r=process.env.ADMIN_SMS;if(s==="development")if(r)t=r;else throw new Error("Admin phone not set");const i={to:t,body:e};await n.collection("system_messages").add(i)},vu=t=>t!==null&&typeof t=="object",Ou=t=>{const e=n=>{Object.entries(n).forEach(([s,r])=>{r instanceof oe.Timestamp?n[s]={_seconds:r.seconds,_nanoseconds:r.nanoseconds}:vu(r)&&e(r)})};e(t)},ku=t=>{const e=lr();return V.fromJSDate(t).setZone(e)},Xo=t=>{const e=lr();return V.fromJSDate(t.toDate()).setZone(e)},bu=(t,e)=>{const s=V.fromJSDate(t,{zone:e}).offset,i=V.fromJSDate(t).offset,o=s-i;return V.fromJSDate(t).plus({minutes:o}).toJSDate()},Ru=(t,e)=>{const s=V.fromJSDate(t,{zone:e}).offset,i=V.fromJSDate(t).offset,o=s-i;return V.fromJSDate(t).minus({minutes:o}).toJSDate()},Tu=t=>"seconds"in t&&"nanoseconds"in t?Xo(new oe.Timestamp(t.seconds,t.nanoseconds)).toFormat("MMMM d, yyyy '@' h:mm a"):"";exports.addRecord=gu;exports.addUser=mr;exports.convertDateToTimezone=ku;exports.convertTimestampToTimezone=Xo;exports.deleteRecord=_u;exports.deleteUser=Gt;exports.deserializeDeleteSentinels=is;exports.deserializeTimestamps=yr;exports.deserializeTimestampsWithoutUnderscores=fu;exports.displayDate=Tu;exports.fetchCurrentSchema=Ye;exports.fetchLastSchema=cu;exports.getCachedConfigValue=wa;exports.getCollectionRefs=zo;exports.getCustomizationFile=rt;exports.getCustomizationFiles=Uo;exports.getDocumentRefs=cr;exports.getFirestorePathRef=Ne;exports.getGlobalConfigModule=It;exports.getInputSchema=eu;exports.getMaintenanceInfo=ou;exports.getMode=ar;exports.getOne=Be;exports.getSome=dr;exports.getStokerFirestore=fe;exports.getTenant=Je;exports.getTimezone=lr;exports.getUser=Ht;exports.getVersionInfo=iu;exports.getZodSchema=$i;exports.initializeFirebase=lu;exports.initializeStoker=su;exports.isDeleteSentinel=be;exports.keepTimezone=bu;exports.removeTimezone=Ru;exports.runChildProcess=au;exports.sendMail=fr;exports.sendMessage=Eu;exports.serializeTimestamps=Ou;exports.setTenant=ru;exports.tryPromise=ae;exports.updateRecord=Ko;exports.updateUser=Qo;exports.validateRelations=gr;exports.validateSoftDelete=wr;exports.writeLog=kt;
|