insite-users-server 2.2.0 → 2.2.2

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.
@@ -1,7 +1,9 @@
1
1
  import { Err } from "@nesvet/n";
2
+ type Payload = Record<string, unknown>;
2
3
  export declare class AbilityError extends Err {
3
- constructor(payload?: object);
4
- constructor(longId: string, payload?: object);
4
+ constructor(payload?: Payload);
5
+ constructor(longId: string, payload?: Payload);
5
6
  name: string;
6
7
  }
8
+ export {};
7
9
  //# sourceMappingURL=Error.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Error.d.ts","sourceRoot":"","sources":["../../src/abilities/Error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGhC,qBAAa,YAAa,SAAQ,GAAG;gBACxB,OAAO,CAAC,EAAE,MAAM;gBAChB,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM;IAc5C,IAAI,SAAkB;CAEtB"}
1
+ {"version":3,"file":"Error.d.ts","sourceRoot":"","sources":["../../src/abilities/Error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAGhC,KAAK,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAGvC,qBAAa,YAAa,SAAQ,GAAG;gBACxB,OAAO,CAAC,EAAE,OAAO;gBACjB,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO;IAc7C,IAAI,SAAkB;CAEtB"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- function x(r){if(r instanceof Set){let e=[];for(let t of r)e.push(t._id);return e}return r.map(e=>e._id)}function de(r,...e){let t=0;for(let i of e)r.includes(i)||(r.push(i),t++);return t}function E(r,e,t){if(r&&e){if(e.includes(".")){let i=e.split("."),s=r;for(let o=0;o<i.length-1;o++){let n=i[o],l=s[n];s=l&&typeof l=="object"?l:s[n]={}}return s[i.at(-1)]=t}return r[e]=t}return null}function ue(r,...e){for(let t of e)for(let i in t)Object.hasOwn(t,i)&&E(r,i,t[i]);return r}function _(){}function m(r,e=0,t={}){let{leading:i=!1,trailing:s=!0}=t,{maxWait:o=1/0}=t,n,l,a,p,y,A,d,O,pe=async()=>{let v=Date.now();v>=a?(n=void 0,a=void 0,clearTimeout(l),typeof d=="function"&&await d(),g.resolve(O),g.promise.isResolved=!0,A=i):(clearTimeout(n),n=setTimeout(pe,a-v))},J=Number.isFinite(o)?()=>{d===S&&(d=!1),S(),l=setTimeout(J,o)}:null;async function S(){return O=await r.apply(p,y)}i&&typeof i=="boolean"&&(i=S),A=i,s&&typeof s=="boolean"&&(s=S),d=s;let g=Object.assign(function(...v){return y=v,p=this,a=Date.now()+e,d=s,g.promise.isResolved&&(g.promise=Object.assign(new Promise(De=>{g.resolve=De,typeof A=="function"&&(A(),A=!1,d===S&&(d=!1)),n||(n=setTimeout(pe,e),J&&(l=setTimeout(J,o)))}),{isResolved:!1})),g.promise},{callback:r,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:S,clear:async v=>{clearTimeout(n),n=void 0,clearTimeout(l),g.promise.isResolved=!0,g.resolve(v?await S():O)}});return g}m.noop=Object.assign(()=>{},{callback:_,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:_,clear:_});function me(r,e){if(r&&e){if(e.includes(".")){let t=e.split("."),i=r;for(let o=0;o<t.length-1;o++){let n=t[o],l=i[n];if(l&&typeof l=="object")i=l;else return!1}let s=t.at(-1);return s in i&&delete i[s]}return e in r&&delete r[e]}return!1}function u(r,e){if(r){for(let t of e)delete r[t];return r}return null}function k(r){for(let e in r)delete r[e];return r}var q=class extends Array{constructor(){super(),Object.freeze(this)}push(){return 0}unshift(){return 0}splice(){return[]}};var D=class extends Set{constructor(){super()}add(){return this}};var f=class extends Error{constructor(e,t=null,i){super(e),t&&typeof t=="object"&&(i=t,t=null),this.tag=t,i&&Object.assign(this,i)}name="Err-or";tag};function X(r,e,t=!1){return t&&(e=e.filter(i=>r.has(i))),e.map(i=>r.get(i))}function G(r,e){if(e){if(e.includes(".")){let t=r;for(let i of e.split("."))if(t=t?.[i],t===void 0)break;return t}return r[e]}return r}function fe(r,e){for(let t of e)if(r.has(t))return!0;return!1}function he(r,e,t,i,s=!0){return Array.isArray(r)&&(r=r.length),typeof i!="string"&&(s=i??!0,i=t),(s?`${r}\xA0`:"")+he.raw(r,e,t,i)}he.raw=(r,e,t,i=t)=>{r=Math.abs(r);let s=r%10,o=r%100;return s===1&&o!==11?e:s>=2&&s<=4&&!(o>=12&&o<=15)?t:i};function N(...r){let e=[];if(r.length){let[t,...i]=r;e:for(let s of t){for(let o of i)if(o instanceof Set?!o.has(s):!o.includes(s))continue e;e.push(s)}}return e}function be(r,e){let t={};for(let i of e)i in r&&(t[i]=r[i]);return t}function W(r,e){return Math.floor(Math.random()*(e-r+1)+r)}function ge(r,e){return r.delete(e),r.add(e),r}function h(r,e){let t,i=0;for(let s of e)for(;(t=r.indexOf(s))>-1;)r.splice(t,1),i++;return i}function ye(r,e){let t=r.indexOf(e);return t>-1?(r.splice(t,1),!0):!1}function Ae(r,e){for(let t of[...r].sort(e))r.delete(t),r.add(t);return r}var U=new WeakMap,L=class extends Promise{constructor(e){let t,i;super((s,o)=>{t=s,i=o}),U.set(this,{resolve:t,reject:i}),e?.(this.resolve,this.reject)}isPending=!0;isFulfilled=!1;isRejected=!1;state="pending";result;resolve=e=>{if(this.isPending){this.isPending=!1,this.isFulfilled=!0,this.state="fulfilled",this.result=e;let t=U.get(this);t&&(t.resolve.call(this,e),U.delete(this))}};reject=e=>{if(this.isPending){this.isPending=!1,this.isRejected=!0,this.state="rejected",this.result=e;let t=U.get(this);t&&(t.reject.call(this,e),U.delete(this))}}};function Se(...r){return[...new Set(r.flat())]}function C(r,e){return r.filter(t=>!e.includes(t))}var Z=class extends f{constructor(e,t){typeof e=="object"&&(t=e,e=void 0),super("User lacks ability","lacksability",{...e&&{ability:e},...t})}name="AbilityError"};function Y(r){return typeof r=="object"}function Q(r){return typeof r=="number"}function V(r){return Array.isArray(r)}var xe=new Map,B=class extends Map{constructor(e){super();for(let t of e)delete t.top,this.#e.push(t);(function t(i,s,o){for(let n of i){if(xe.set(n,s),n.level=o,!s||n.top){if(n.longId=n._id,this.has(n._id))throw new Error(`Top-level ability duplicate: ${n._id}`);this.set(n._id,n)}else n.longId=s?`${s.longId}.${n._id}`:n._id;n.abilities&&t.call(this,n.abilities,n,o+1)}}).call(this,e,null,0)}#e=[];get(e,t){let i=e.split("."),s=t??super.get(i.shift());if(s&&i.length){for(let o of i)if(s=s?.abilities?.find(({_id:n,top:l})=>!l&&n===o),!s)break}return s}getSchema=this.get;getParamSchema(e,t){return this.get(e)?.params?.find(({_id:i})=>i===t)}getDefaultParam(e,t,i){(t===void 0||typeof t=="boolean")&&(i=t);let s=typeof e=="string"?this.getParamSchema(e,t):e;if(s)switch(s.type){case"number":return i?s.max??1/0:s.min??0;case"items":return i?s.items.map(({_id:o})=>o):[]}}getDefaultAbility(e,t=!e){if(typeof e=="string"&&(e=this.get(e)),e){if(e.abilities||e.params){let i={};if(e.params)for(let s of e.params)i[s._id]=this.getDefaultParam(s,t);if(t&&e.abilities)for(let s of e.abilities)s.top||(i[s._id]=this.getDefaultAbility(s,t));return i}return!0}}getDefaultAbilities(e,t=!e){let i=(e?(Array.isArray(e)?e:[e]).map(o=>typeof o=="string"?this.get(o):o).filter(Boolean):[...this.values()]).sort((o,n)=>o.level-n.level),s=new Map;for(let o of i)(function n(l){let a=xe.get(l);a&&(n(a),s.has(a)||s.set(a,!1))})(o),t?function n(l){if(s.has(l)||s.set(l,!0),l.abilities)for(let a of l.abilities)a.top&&n(a)}(o):s.has(o)||s.set(o,!1);return ue({},Object.fromEntries([...s].map(([o,n])=>[o.longId,this.getDefaultAbility(o,n)])))}getSchemeFor(e){return e=this.adjust(structuredClone(e)),function t(i,s){for(let o=0;o<i.length;o++){let n=i[o],l=n.top?e[n._id]:s[n._id];if(l){if(n.params)for(let a of n.params){let p=l[a._id];switch(a.type){case"number":a.max=p;break;case"items":a.items=a.items.filter(({_id:y})=>p.includes(y))}}n.abilities&&(t(n.abilities,l),n.abilities.length||delete n.abilities)}else i.splice(o--,1)}return i}(structuredClone(this.#e),e)}getParam(e,t,i){if(this.getParamSchema(t,i)){let s=G(e,`${t}.${i}`);return this.isParamFits(t,i,s)?s:this.getDefaultParam(t,i)}}setParam(e,t,i,s){let o=this.getParamSchema(t,i);if(!o)throw new Error(`No such ability param: ${t}.${i}`);return E(e,`${t}.${i}`,this.adjustParam(o,s)),e}isParamFits(e,t,i,s){if(i!==void 0){let o=this.getParamSchema(e,t);if(o)switch(o.type){case"number":return Q(i)&&(o.min===void 0||i>=o.min)&&(s===void 0?o.max===void 0||i<=o.max:i<=s);case"items":return V(i)&&i.length===new Set(i).size&&(s===void 0?i.every(n=>o.items.find(({_id:l})=>l===n)):i.every(n=>s.includes(n)))}}return!1}adjustParam(e,t){switch(e.type){case"number":return Q(t)?Math.max(Math.min(t,e.max??1/0),e.min??0):e.min??0;default:return V(t)?N(e.items.map(i=>i._id),t):[]}}adjust(e,t){let i={};for(let[s,o]of Object.entries(e)){let n=this.get(s,t);if(n)if(n.params||n.abilities){let l={};if(n.params)if(Y(o))for(let a of n.params)l[a._id]=this.adjustParam(a,o[a._id]);else for(let a of n.params)l[a._id]=this.getDefaultParam(a);n.abilities&&Y(o)&&Object.assign(l,this.adjust(be(o,n.abilities.filter(a=>!a.top).map(a=>a._id)),n)),i[s]=l}else i[s]=!0}return Object.assign(k(e),i)}merge(e,t,i){i||(this.adjust(e),t=this.adjust(structuredClone(t)));for(let[s,o]of Object.entries(t)){let n=this.get(s,i);if(n&&n.isInheritable!==!1)if(s in e&&(n.params||n.abilities)){let l=e[s],a=o;if(n.params){for(let p of n.params)if(p.isInheritable!==!1)switch(p.type){case"number":l[p._id]=Math.max(l[p._id],a[p._id]);break;case"items":de(l[p._id],...a[p._id])}}n.abilities&&this.merge(l,a,n)}else e[s]=o}return e}hasAbility(e,t){return!!G(e,t)}setAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return this.merge(e,this.getDefaultAbilities(i)),e}unsetAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return function s(o){if(me(e,o.longId),o.abilities)for(let n of o.abilities)s(n)}(i),e}};var ee=class extends f{constructor(e,t){super(`User lacks role${Array.isArray(e)?"s":""}`,"lacksroles",{roles:Array.isArray(e)?e:[e],...t})}name="RolesError"};var te=new Map,P=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t)}#e;_id;ownInvolveIds;ownAbilities;title="";displayTitle="";_o=0;ownInvolves=[];involves=new Set;abilities={};inheritedAbilities={};update({_id:e,involves:t,abilities:i,title:s,...o},n){if(Object.assign(this,o),t&&(this.ownInvolveIds=t),i&&(this.ownAbilities=i),s!==void 0&&(this.title=s,this.displayTitle=s||this._id),t||i){let l=[this.ownInvolveIds.join(","),JSON.stringify(this.ownAbilities)].join(`
2
- `);l!==te.get(this._id)&&(te.set(this._id,l),this.#e.users.isInited&&this.#e.updateDebounced().then(()=>this.#e.users.emit("roles-role-update",this,n)))}}delete(){this.#e.delete(this._id),te.delete(this._id),this.#e.updateDebounced()}};var c={_id:/^[\dA-Fa-f]{24}$/,email:/^[^\s@]{1,63}@[^\s@]{1,63}\.[^\s@]{1,63}$/,argon2:/^\$argon2(?:i|d|id)\$v=\d+\$m=\d+,t=\d+,p=\d+(?:\$[\d+/A-Za-z]+){2}$/,sessionId:/^[\dA-Fa-f]{16,32}\$[\dA-Fa-f]{16,32}$/,role:/^[\d_a-z-]{1,64}$/,ip:/^(?:\d{1,3}\.){3}\d{1,3}$/};var I={required:["_id","involves","abilities","title","description","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},involves:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},additionalItems:!1},abilities:{bsonType:"object"},title:{bsonType:"string",maxLength:256},description:{bsonType:"string",maxLength:10240},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var Pe=[[{involves:1}]];function we(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.")}var F=class extends Map{constructor(e,t={}){super();let{root:i,...s}=t;this.users=e,this.collections=e.collections,this.abilities=e.abilities,this.root=new P(this,{...i,_id:"root",involves:[],abilities:this.abilities.getDefaultAbilities(),title:"Root",description:"Root",meta:{},createdAt:Date.now()}),this.initOptions=s}users;collections;collection;abilities;root;initOptions;#e=!1;async init(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t,collection:i}=this.initOptions;e&&(e.required&&h(e.required,I.required),e.properties&&u(e,Object.keys(I.properties)));let s={...I,...e,required:[...I.required,...e?.required??[]],properties:{...I.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{...i,schema:s}),{deleteOne:we,deleteMany:we}),this.collection.ensureIndexes([...Pe,...t??[]]),await this.#t();for(let o of await this.collection.find().toArray())this.abilities.adjust(o.abilities)&&await this.collection.updateOne({_id:o._id},{$set:{abilities:o.abilities}}),this.load(o);this.update(),this.collection.onChange(this.#i),delete this.initOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}#i=e=>{switch(e.operationType){case"insert":{let t=new P(this,e.fullDocument);this.users.emit("roles-role-update",t,e);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument,e);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields,e);break;case"delete":this.get(e.documentKey._id)?.delete(),this.users.emit("roles-role-update",null,e)}};load(e){new P(this,e)}resolve(e,t){t=[e,...t];for(let i of e.ownInvolveIds){let s=this.get(i);if(s){for(let o of t)ge(o.involves,s),this.abilities.merge(o.inheritedAbilities,s.abilities);s!==e&&this.resolve(s,t)}}}sorted=[];#s(e,t){return t.involves.size-e.involves.size||(e.title&&t.title?e.title>t.title?1:e.title<t.title?-1:0:e.title?-1:t.title||e._id>t._id?1:e._id<t._id?-1:0)}update(){let e=[...this.values()];this.root.ownInvolveIds=[];for(let s of e)s!==this.root&&!e.some(o=>o.ownInvolveIds.includes(s._id))&&this.root.ownInvolveIds.push(s._id),s.involves.clear(),s.abilities=structuredClone(s.ownAbilities),s.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let s of e)s.ownInvolves=X(this,s.ownInvolveIds,!0).sort(this.#s).reverse();let t=[this.root];for(let s=0;s<t.length;s++){let o=t[s];for(let n of o.ownInvolves){let l=t.indexOf(n);~l&&(t.splice(l,1),s--),t.splice(s+1,0,n)}}let i=0;for(let s of t)this.abilities.merge(s.abilities,s.inheritedAbilities),s._o=i++;this.sorted=t,this.users.emit("roles-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update(!0))}updateDebounced=m(this.update,100);create({_id:e,involves:t,title:i,description:s,...o}){return this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:i??"",description:s??"",meta:{},...u(o,["abilities"]),createdAt:Date.now()})}async updateRole(e,t){let i=this.get(e);if(!i)return!1;if(t.involves){h(t.involves,[e]);for(let s of t.involves)this.get(s)?.involves.has(i)&&h(t.involves,[s]);t.involves=this.cleanUpIds(t.involves)}return await this.collection.updateOne({_id:e},{$set:t}),!0}deleteRole(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{involves:t},update:{$pullAll:{involves:[t]}}}},{deleteOne:{filter:{_id:t}}}])}cleanUpIds(e){let t=N(this.sorted,X(this,e,!0)),i=[];for(let s of t)t.every(o=>o===s||!o.involves.has(s))&&i.push(s._id);return i}async setAbility(e,t,i){let s=this.get(e);return s?(await this.collection.updateOne({_id:e},{$set:{abilities:i?this.abilities.setAbility(s.ownAbilities,t):this.abilities.unsetAbility(s.ownAbilities,t)}}),!0):!1}async setAbilityParam(e,t,i,s){let o=this.get(e);return o?(await this.collection.updateOne({_id:e},{$set:{abilities:this.abilities.setParam(o.ownAbilities,t,i,s)}}),!0):!1}};var ie=class extends f{constructor(e){super("Unauthorized","unauthorized",e)}name="UnauthorizedError"},se=class extends f{constructor(e,t,i){switch(arguments.length){case 1:i=e,e=void 0;break;case 2:i=t,t=void 0}super("Insubordination attempt","subordination",{...e&&{type:e},...t&&{ids:Array.isArray(t)?t:[t]},...i})}name="SubordinationError"},oe=class extends f{constructor(e){super("Insufficient permissions","permissions",e)}name="PermissionError"};import*as M from"argon2";import Ue from"eventemitter3";import{newObjectIdString as Ce}from"insite-db";import{newObjectIdString as Ie}from"insite-db";var re=new Map,b=class{constructor(e,t){this.orgs=e,this._id=t._id,e.set(this._id,this),this.update(t)}_id;title="";initials="";displayLabel="";_o=0;orgs;isOrg=!0;ownerOrgs=new Set;ownerUsers=new Set;users=new Set;slaveOrgs=new Set;ownerIds=[];update({_id:e,title:t,owners:i,...s},o){if(Object.assign(this,s),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),i){this.ownerIds=i;let n=this.ownerIds.join(",");n!==re.get(this._id)&&(re.set(this._id,n),this.orgs.users.isInited&&this.orgs.updateDebounced(),this.orgs.users.emit("orgs-org-update",this,o))}}delete(){this.orgs.delete(this._id),re.delete(this._id),this.orgs.replace(this._id),this.orgs.updateDebounced()}};var j={required:["_id","title","note","owners","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},title:{bsonType:"string",maxLength:512},note:{bsonType:"string",maxLength:131072},owners:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c._id.source},additionalItems:!1},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var je=[[{owners:1}]];function Oe(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.")}var z=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.preinitOptions=t}users;collections;preinitOptions;collection;null;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t,null:i,collection:s}=this.preinitOptions;e&&(e.required&&h(e.required,j.required),e.properties&&u(e,Object.keys(j.properties)));let o={...j,...e,required:[...j.required,...e?.required??[]],properties:{...j.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{...s,schema:o}),{deleteOne:Oe,deleteMany:Oe}),this.collection.ensureIndexes([...je,...t??[]]),this.null=Object.assign(new b(this,{...i,_id:"",title:"",note:"",owners:[],meta:{},createdAt:Date.now()}),{_id:null,ownerIds:new q,ownerOrgs:new D,ownerUsers:new D,slaveOrgs:new D}),await this.#t();for(let n of await this.collection.find().toArray())this.load(n);delete this.preinitOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}#i=!1;init(){this.#i||(this.#i=!0,this.update(),this.collection.onChange(this.#s))}#s=e=>{switch(e.operationType){case"insert":{let t=new b(this,e.fullDocument);this.users.emit("orgs-org-update",t,e);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument,e);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields,e);break;case"delete":this.get(e.documentKey._id)?.delete(),this.users.emit("orgs-org-update",null,e)}};load(e){new b(this,e)}#o(e,t){t=[e,...t];for(let i of e.ownerOrgs){this.#o(i,t);for(let s of t)i.slaveOrgs.add(s)}}sorted=[];update(){let e=[...this.values()],t=[];for(let i of e){i.ownerOrgs.clear(),i.ownerUsers.clear(),i.slaveOrgs.clear();for(let s of i.ownerIds){let o=this.get(s);if(o)i.ownerOrgs.add(o);else{let n=this.users.get(s);n&&i.ownerUsers.add(n)}}!i.ownerOrgs.size&&i._id&&t.push(i)}for(let i of e)e.some(s=>s.ownerOrgs.has(i))||this.#o(i,[]);t.sort(this.#r);for(let i of e)Ae(i.slaveOrgs,this.#r);for(let i=0;i<t.length;i++){let s=t[i];for(let o of[...s.slaveOrgs].reverse())if(o.ownerOrgs.has(s)){let n=t.indexOf(o);~n&&(t.splice(n,1),i--),t.splice(i+1,0,o)}}for(let i=0,{length:s}=t;i<s;)t[i]._o=i++;this.sorted=t,this.users.emit("orgs-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update())}#r(e,t){return t.slaveOrgs.size-e.slaveOrgs.size||(e.title>t.title?1:e.title<t.title?-1:0)}updateDebounced=m(this.update,250);create({title:e,note:t,...i},s){return this.collection.insertOne({_id:Ie(),title:e??"",note:t??"",owners:s?[s]:[],meta:{},...u(i,["_id","owners"]),createdAt:Date.now()})}async updateOrg(e,t,i){let s=this.get(e);return s?(t.owners&&(t.owners=this.users.sortIds(Se(i?C(s.ownerIds,i.slaveIds):[],C(t.owners,[e,...x(s.slaveOrgs)])))),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}deleteOrg(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{owners:t},update:{$pullAll:{owners:[t]}}}},{deleteOne:{filter:{_id:t}}}])}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let i of this.replaceHandlers)await i(e,t)}};import ve from"node:crypto";var R={required:["_id","user","remoteAddress","isOnline","meta","createdAt","prolongedAt","expiresAt"],properties:{_id:{bsonType:"string",pattern:c.sessionId.source},user:{bsonType:"string",pattern:c._id.source},userAgent:{bsonType:"string",maxLength:4096},remoteAddress:{bsonType:"string",pattern:c.ip.source},isOnline:{bsonType:"bool"},meta:{bsonType:"object"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}}};var T=class{constructor(e,t){let i=e.users.get(t.user);i?(this.#e=e,this._id=t._id,this.#e.set(this._id,this),this.user=i,this.user.sessions.add(this),this.#e.users.bySessionId.set(this._id,this.user),this.update(t)):e.collection.deleteOne({_id:t._id})}_id;user;isOnline=!1;userAgent;remoteAddress;createdAt;prolongedAt;expiresAt;#e;update({_id:e,user:t,isOnline:i,...s}){i!==void 0&&this.isOnline!==i&&(this.isOnline=i,this.#e.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnline()),Object.assign(this,s)}prolong({_id:e,user:t,...i}){let s=Date.now();return i.prolongedAt=s,i.expiresAt=new Date(s+this.#e.collection.expireAfterSeconds*1e3),this.update(i),this.#e.collection.updateOne({_id:this._id},{$set:i})}offline(){let e={isOnline:!1};return this.update(e),this.#e.collection.updateOne({_id:this._id},{$set:e})}delete(){this.#e.delete(this._id),this.user.sessions.delete(this),this.#e.users.bySessionId.delete(this._id),this.#e.users.emit("session-delete",this),this.isOnline&&this.user.updateIsOnline()}};var ne=3600*24*7,Re=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:ne}]],K=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.initOptions=t}users;collections;initOptions;collection;isInited=!1;async init(){if(!this.isInited){this.isInited=!0;let{schema:e,indexes:t,collection:i}=this.initOptions;e&&(e.required&&h(e.required,R.required),e.properties&&u(e,Object.keys(R.properties)));let s={...R,...e,required:[...R.required,...e?.required??[]],properties:{...R.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{...i,schema:s}),{expireAfterSeconds:ne}),this.collection.ensureIndexes([...Re,...t??[]]),await this.#e();for(let o of await this.collection.find().toArray())this.load(o);this.collection.onChange(this.#t),delete this.initOptions}}async#e(){await this.collection.bulkWrite([{updateMany:{filter:{meta:{$exists:!1}},update:{$set:{meta:{}}}}},{updateMany:{filter:{isOnline:!0},update:{$set:{isOnline:!1}}}}])}#t=e=>{switch(e.operationType){case"insert":this.has(e.documentKey._id)||new T(this,e.fullDocument),this.users.get(e.fullDocument.user)?.trimSessions();break;case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};uid(){let e;do e=`${ve.randomBytes(W(8,16)).toString("hex")}$${ve.randomBytes(W(8,16)).toString("hex")}`;while(this.has(e));return e}load(e){new T(this,e)}async create(e,t){let i=Date.now(),s={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...t,_id:this.uid(),user:e._id,meta:{},createdAt:i,prolongedAt:i,expiresAt:new Date(i+ne*1e3)},o=new T(this,s);return await this.collection.insertOne(s),o}async destroySession(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}};import{Binary as Te}from"insite-db";var _e={required:["_id","type","size","ts","data","meta"],properties:{_id:{bsonType:"string",pattern:c._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"},meta:{bsonType:"object"}},additionalProperties:!1};var H=class{constructor(e,t={}){this.users=e,this.collections=e.collections,this.initOptions=t}TYPES_ACCEPTED=["image/webp"];MAX_SIZE=1024*512;users;collections;collection;initOptions;#e=!1;async init(){if(!this.#e){this.#e=!0;let{collection:e}=this.initOptions;this.collection=await this.collections.ensure("users.avatars",{...e,schema:_e}),await this.#t()}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}async save(e,t,i){let s=Te.createFromBase64(i.slice(i.indexOf(","))),o=Date.now().toString(36);await Promise.all([this.collection.replaceOne({_id:e},{type:t,size:s.length(),ts:o,data:s,meta:{}},{upsert:!0}),this.users.collection.updateOne({_id:e},{$set:{avatar:o}})])}async deleteAvatar(e){let[{deletedCount:t}]=await Promise.all([this.collection.deleteOne({_id:e}),this.users.collection.updateOne({_id:e},{$set:{avatar:null}})]);return!!t}};var $={required:["_id","email","password","roles","name","org","job","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},email:{bsonType:"string",pattern:c.email.source},password:{bsonType:"string",pattern:c.argon2.source},roles:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source},additionalItems:!1},name:{bsonType:"object",required:["first","middle","last"],properties:{first:{bsonType:"string",maxLength:512},middle:{bsonType:"string",maxLength:512},last:{bsonType:"string",maxLength:512}},additionalProperties:!1},org:{oneOf:[{bsonType:"string",pattern:c._id.source},{bsonType:"null"}]},job:{bsonType:"string",maxLength:512},avatar:{oneOf:[{bsonType:"string",maxLength:10},{bsonType:"null"}]},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var le=new Map,ae=new Map,$e=process.env.INSITE_STATIC_URL??"http://localhost:8080",w=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t),e.isInited&&e.emit("user-create",this)}_id;email;name={first:"",middle:"",last:""};initials="";displayLabel="";org;job="";avatar=null;avatarUrl=null;#e;isUser=!0;isRoot;roles=new Set;ownRoles=[];ownRoleIds=[];slaveRoles=new Set;slaveRoleIds=[];abilities={};slaveOrgs=new Set;slaveUsers=new Set;slaves=new Set;slaveIds=[];permissiveIds=[];sessions=new Set;isOnline=!1;update({_id:e,name:t,email:i,roles:s,org:o,avatar:n,...l}){Object.assign(this,l);let a;i&&this.email!==i&&(this.#e.byEmail.delete(this.email),this.email=i,this.#e.byEmail.set(i,this),a=!0);let p,y;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(y=this.name.last!==t.last,this.name={first:t.first??"",middle:t.middle??"",last:t.last??""},this.initials=((t.first?.[0]??"")+(t.last?.[0]??"")||this.email[0]).toUpperCase(),p=!0),(a||p)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let A;if(s){this.ownRoleIds=s;let O=this.ownRoleIds.join(",");O!==le.get(this._id)&&(le.set(this._id,O),this.updateRoles(),A=!0)}let d;o!==void 0&&this.org?._id!==o&&(this.org?.users.delete(this),this.org=o&&this.#e.orgs.get(o)||this.#e.orgs.null,this.org.users.add(this),d=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${$e}/avatars/${this._id}-${n}.webp`),A||d?(this.updatePermissions(),y&&(this.#e.isSortRequired=!0),this.#e.isInited&&this.#e.updateDebounced()):y&&this.#e.sortDebounced()}updateRoles(){if(this.#e.isInited){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),k(this.abilities);for(let e of this.ownRoleIds){let t=this.#e.roles.get(e);if(t){this.ownRoles.push(t),this.roles.add(t);for(let i of t.involves)this.roles.add(i),this.slaveRoles.add(i);this.slaveRoleIds=x(this.slaveRoles),this.#e.abilities.merge(this.abilities,t.abilities)}}this.roles.has(this.#e.roles.root)&&(this.isRoot=!0),this.trimSessions()}}updatePermissions(){if(this.#e.isInited){this.slaveOrgs.clear(),this.slaveUsers.clear(),this.slaves.clear();let e=new Set;for(let s of this.#e.orgs.sorted)if((s.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(s)){this.slaveOrgs.add(s),this.slaves.add(s),e.add(s._id);for(let o of s.slaveOrgs)this.slaveOrgs.add(o),this.slaves.add(o),e.add(o._id)}for(let s of new Set([this.org,...this.slaveOrgs,this.#e.orgs.null]))for(let o of s.users)o!==this&&(fe(this.slaveRoles,o.ownRoles)||!o.ownRoles.length)&&(this.slaveUsers.add(o),this.slaves.add(o),e.add(o._id));this.slaveIds=[...e];let t=[];if(this.org._id){t.push(this.org._id);for(let s of this.org.slaveOrgs)this.slaveOrgs.has(s)||t.push(s._id)}this.permissiveIds=[...t,this._id,...e];let i=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
3
- `);i!==ae.get(this._id)&&(ae.set(this._id,i),this.#e.emit("user-permissions-change",this))}}trimSessions(){let e=this.abilities.login?.sessionsLimit??0;return this.sessions.size>e?this.#e.sessions.collection.deleteMany({_id:{$in:x([...this.sessions].sort((t,i)=>t.expiresAt.valueOf()-i.expiresAt.valueOf()).slice(0,this.sessions.size-e))}}):null}updateIsOnline=m(()=>{let e=!1;for(let t of this.sessions)if(t.isOnline){e=!0;break}this.isOnline!==e&&(this.isOnline=e,this.#e.emit("user-is-online",this))},500);delete(){this.org.users.delete(this),this.#e.delete(this._id),this.#e.byEmail.delete(this.email),ye(this.#e.sorted,this),le.delete(this._id),ae.delete(this._id),this.#e.replace(this._id),this.#e.updateDebounced()}};var Me=[[{email:1},{unique:!0}],[{org:1}]],ce=class r extends Map{constructor(e,t){super();let i=new Ue;this._events=i._events,this._eventsCount=i._eventsCount,this.emit=i.emit,this.on=i.on,this.once=i.once,this.addListener=i.addListener,this.off=i.off,this.removeListener=i.removeListener,this.collections=e,this.abilities=new B(t.abilities),this.initOptions=t,this.init()}_events;_eventsCount;emit;on;once;addListener;off;removeListener;initOptions;collections;abilities;collection;roles;sessions;orgs;avatars;byEmail=new Map;bySessionId=new Map;sorted=[];isSortRequired=!1;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{indexes:e,schema:t,initialRoot:i,collection:s}=this.initOptions;t&&(t.required&&h(t.required,$.required),t.properties&&u(t,Object.keys($.properties)));let o={...$,...t,required:[...$.required,...t?.required??[]],properties:{...$.properties,...t?.properties}};this.collection=await this.collections.ensure("users",{...s,schema:o}),this.collection.ensureIndexes([...Me,...e??[]]),await this.collection.countDocuments({roles:"root"})||await this.create({email:process.env.INSITE_ROOT_EMAIL??"insite@root.email",password:process.env.INSITE_ROOT_PASSWORD??"inSiteRootPassword",name:{first:"Root"},job:"Root",...i,roles:["root"],org:null,meta:{}}),await this.#t();for(let n of await this.collection.find().toArray())this.load(n)}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}isInited=!1;async init(){if(!this.isInited){this.isInited=!0;let{roles:e,orgs:t,sessions:i,avatars:s,collection:{quiet:o}={}}=this.initOptions;this.roles=new F(this,{...e,collection:{quiet:o,...e?.collection}}),this.orgs=new z(this,{...t,collection:{quiet:o,...t?.collection}}),this.sessions=new K(this,{...i,collection:{quiet:o,...i?.collection}}),this.avatars=new H(this,{...s,collection:{quiet:o,...s?.collection}}),await this.roles.init(),await this.orgs.preinit(),await this.preinit(),await this.orgs.init(),await this.avatars.init(),this.update(!0),this.collection.onChange(this.#i),await this.sessions.init(),delete this.initOptions,this.#s.resolve(this)}}#i=e=>{switch(e.operationType){case"insert":new w(this,e.fullDocument);break;case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};load(e){new w(this,e)}sort(){this.isSortRequired=!1,this.sorted=[...this.values()].sort((e,t)=>e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0)}sortDebounced=m(()=>this.sort(),250);update(e){if(e)for(let t of this.values())t.updateRoles();for(let t of this.values())t.updatePermissions();this.isSortRequired&&this.sort()}updateDebounced=m(()=>this.update(),250);#s=new L;whenReady(){return this.#s}async create({email:e,password:t,roles:i,name:s,org:o,job:n,...l}){if(this.byEmail.has(e))throw new Error("User exists");return await this.collection.insertOne({_id:Ce(),email:e,password:await M.hash(t),roles:this.isInited?this.roles.cleanUpIds(i):i,name:{first:s.first??"",middle:s.middle??"",last:s.last??""},org:o??null,job:n??"",meta:{},...u(l,["_id"]),createdAt:Date.now()}),!0}async updateUser(e,t,i){let s=this.get(e);return s?(t.roles&&(t.roles=s.isRoot?["root"]:this.roles.cleanUpIds(i?C(s.ownRoleIds,i.slaveRoleIds).concat(t.roles):t.roles)),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}async changePassword(e,t){if(!this.has(e))throw new Error("usernotfound");if(!t)throw new Error("emptypasswordisnotallowed");await Promise.all([this.collection.updateOne({_id:e},{$set:{password:await M.hash(t)}}),this.sessions.collection.deleteMany({user:e})])}async login(e,t,i){let s=this.byEmail.get(e);if(!s)throw new Error("usernotfound");if(!await M.verify(s.password,t))throw new Error("incorrectpassword");if(!s.abilities.login)throw new Error("userisnotabletologin");return this.sessions.create(s,i)}logout(e){return e.delete(),this.sessions.collection.deleteOne({_id:e._id})}#o(e,t){return e instanceof w&&t instanceof w?e.name.last&&t.name.last?e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0:!e.name.last&&!t.name.last?e.displayLabel>t.displayLabel?1:e.displayLabel<t.displayLabel?-1:0:e.name.last?-1:1:e instanceof b&&t instanceof b?e.title>t.title?1:e.title<t.title?-1:0:e instanceof b?-1:1}sortIds(e){return x(e.map(t=>this.get(t)||this.orgs.get(t)).filter(Boolean).sort(this.#o))}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let i of this.replaceHandlers)await i(e,t)}async deleteUser(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}static init(e,t){return new r(e,t).whenReady()}};export{Z as AbilityError,oe as PermissionError,ee as RolesError,se as SubordinationError,ie as UnauthorizedError,ce as Users};
1
+ function x(r){if(r instanceof Set){let e=[];for(let t of r)e.push(t._id);return e}return r.map(e=>e._id)}function pe(r,...e){let t=0;for(let i of e)r.includes(i)||(r.push(i),t++);return t}function E(r,e,t){if(r&&e){if(e.includes(".")){let i=e.split("."),s=r;for(let o=0;o<i.length-1;o++){let n=i[o],l=s[n];s=l&&typeof l=="object"?l:s[n]={}}return s[i.at(-1)]=t}return r[e]=t}return null}function de(r,...e){for(let t of e)for(let i in t)Object.hasOwn(t,i)&&E(r,i,t[i]);return r}function _(){}function m(r,e=0,t={}){let{leading:i=!1,trailing:s=!0}=t,{maxWait:o=1/0}=t,n,l,a,p,y,A,d,O,ce=async()=>{let v=Date.now();v>=a?(n=void 0,a=void 0,clearTimeout(l),typeof d=="function"&&await d(),g.resolve(O),g.promise.isResolved=!0,A=i):(clearTimeout(n),n=setTimeout(ce,a-v))},J=Number.isFinite(o)?()=>{d===S&&(d=!1),S(),l=setTimeout(J,o)}:null;async function S(){return O=await r.apply(p,y)}i&&typeof i=="boolean"&&(i=S),A=i,s&&typeof s=="boolean"&&(s=S),d=s;let g=Object.assign(function(...v){return y=v,p=this,a=Date.now()+e,d=s,g.promise.isResolved&&(g.promise=Object.assign(new Promise(ve=>{g.resolve=ve,typeof A=="function"&&(A(),A=!1,d===S&&(d=!1)),n||(n=setTimeout(ce,e),J&&(l=setTimeout(J,o)))}),{isResolved:!1})),g.promise},{callback:r,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:S,clear:async v=>{clearTimeout(n),n=void 0,clearTimeout(l),g.promise.isResolved=!0,g.resolve(v?await S():O)}});return g}m.noop=Object.assign(()=>{},{callback:_,promise:Object.assign(Promise.resolve(),{isResolved:!0}),resolve:_,run:_,clear:_});function ue(r,e){if(r&&e){if(e.includes(".")){let t=e.split("."),i=r;for(let o=0;o<t.length-1;o++){let n=t[o],l=i[n];if(l&&typeof l=="object")i=l;else return!1}let s=t.at(-1);return s in i&&delete i[s]}return e in r&&delete r[e]}return!1}function u(r,e){if(r){for(let t of e)delete r[t];return r}return null}function k(r){for(let e in r)delete r[e];return r}var q=class extends Array{constructor(){super(),Object.freeze(this)}push(){return 0}unshift(){return 0}splice(){return[]}};var P=class extends Set{constructor(){super()}add(){return this}};var f=class extends Error{constructor(e,t=null,i){typeof e=="object"?(i=e,e=i.message,delete i.message,t=null):t&&typeof t=="object"&&(i=t,t=null),super(e),this.tag=t,i&&Object.assign(this,i)}name="Err-or";tag};function H(r,e,t=!1){return t&&(e=e.filter(i=>r.has(i))),e.map(i=>r.get(i))}function N(r,e){if(e){if(e.includes(".")){let t=r;for(let i of e.split("."))if(t=t?.[i],t===void 0)break;return t}return r[e]}return r}function me(r,e){for(let t of e)if(r.has(t))return!0;return!1}function fe(r,e,t,i,s=!0){return Array.isArray(r)&&(r=r.length),typeof i!="string"&&(s=i??!0,i=t),(s?`${r}\xA0`:"")+fe.raw(r,e,t,i)}fe.raw=(r,e,t,i=t)=>{r=Math.abs(r);let s=r%10,o=r%100;return s===1&&o!==11?e:s>=2&&s<=4&&!(o>=12&&o<=15)?t:i};function G(...r){let e=[];if(r.length){let[t,...i]=r;e:for(let s of t){for(let o of i)if(o instanceof Set?!o.has(s):!o.includes(s))continue e;e.push(s)}}return e}function he(r,e){let t={};for(let i of e)i in r&&(t[i]=r[i]);return t}function be(r,e){return r.delete(e),r.add(e),r}function h(r,e){let t,i=0;for(let s of e)for(;(t=r.indexOf(s))>-1;)r.splice(t,1),i++;return i}function ge(r,e){let t=r.indexOf(e);return t>-1?(r.splice(t,1),!0):!1}function ye(r,e){for(let t of[...r].sort(e))r.delete(t),r.add(t);return r}var U=new WeakMap,W=class extends Promise{constructor(e){let t,i;super((s,o)=>{t=s,i=o}),U.set(this,{resolve:t,reject:i}),e?.(this.resolve,this.reject)}isPending=!0;isFulfilled=!1;isRejected=!1;state="pending";result;resolve=e=>{if(this.isPending){this.isPending=!1,this.isFulfilled=!0,this.state="fulfilled",this.result=e;let t=U.get(this);t&&(t.resolve.call(this,e),U.delete(this))}};reject=e=>{if(this.isPending){this.isPending=!1,this.isRejected=!0,this.state="rejected",this.result=e;let t=U.get(this);t&&(t.reject.call(this,e),U.delete(this))}}};function Ae(...r){return[...new Set(r.flat())]}function C(r,e){return r.filter(t=>!e.includes(t))}var Z=class extends f{constructor(e,t){typeof e=="object"&&(t=e,e=void 0),super("User lacks ability","lacksability",{...e&&{ability:e},...t})}name="AbilityError"};function X(r){return typeof r=="object"}function Y(r){return typeof r=="number"}function Q(r){return Array.isArray(r)}var Se=new Map,L=class extends Map{constructor(e){super();for(let t of e)delete t.top,this.#e.push(t);(function t(i,s,o){for(let n of i){if(Se.set(n,s),n.level=o,!s||n.top){if(n.longId=n._id,this.has(n._id))throw new Error(`Top-level ability duplicate: ${n._id}`);this.set(n._id,n)}else n.longId=s?`${s.longId}.${n._id}`:n._id;n.abilities&&t.call(this,n.abilities,n,o+1)}}).call(this,e,null,0)}#e=[];get(e,t){let i=e.split("."),s=t??super.get(i.shift());if(s&&i.length){for(let o of i)if(s=s?.abilities?.find(({_id:n,top:l})=>!l&&n===o),!s)break}return s}getSchema=this.get;getParamSchema(e,t){return this.get(e)?.params?.find(({_id:i})=>i===t)}getDefaultParam(e,t,i){(t===void 0||typeof t=="boolean")&&(i=t);let s=typeof e=="string"?this.getParamSchema(e,t):e;if(s)switch(s.type){case"number":return i?s.max??1/0:s.min??0;case"items":return i?s.items.map(({_id:o})=>o):[]}}getDefaultAbility(e,t=!e){if(typeof e=="string"&&(e=this.get(e)),e){if(e.abilities||e.params){let i={};if(e.params)for(let s of e.params)i[s._id]=this.getDefaultParam(s,t);if(t&&e.abilities)for(let s of e.abilities)s.top||(i[s._id]=this.getDefaultAbility(s,t));return i}return!0}}getDefaultAbilities(e,t=!e){let i=(e?(Array.isArray(e)?e:[e]).map(o=>typeof o=="string"?this.get(o):o).filter(Boolean):[...this.values()]).sort((o,n)=>o.level-n.level),s=new Map;for(let o of i)(function n(l){let a=Se.get(l);a&&(n(a),s.has(a)||s.set(a,!1))})(o),t?function n(l){if(s.has(l)||s.set(l,!0),l.abilities)for(let a of l.abilities)a.top&&n(a)}(o):s.has(o)||s.set(o,!1);return de({},Object.fromEntries([...s].map(([o,n])=>[o.longId,this.getDefaultAbility(o,n)])))}getSchemeFor(e){return e=this.adjust(structuredClone(e)),function t(i,s){for(let o=0;o<i.length;o++){let n=i[o],l=n.top?e[n._id]:s[n._id];if(l){if(n.params)for(let a of n.params){let p=l[a._id];switch(a.type){case"number":a.max=p;break;case"items":a.items=a.items.filter(({_id:y})=>p.includes(y))}}n.abilities&&(t(n.abilities,l),n.abilities.length||delete n.abilities)}else i.splice(o--,1)}return i}(structuredClone(this.#e),e)}getParam(e,t,i){if(this.getParamSchema(t,i)){let s=N(e,`${t}.${i}`);return this.isParamFits(t,i,s)?s:this.getDefaultParam(t,i)}}setParam(e,t,i,s){let o=this.getParamSchema(t,i);if(!o)throw new Error(`No such ability param: ${t}.${i}`);return E(e,`${t}.${i}`,this.adjustParam(o,s)),e}isParamFits(e,t,i,s){if(i!==void 0){let o=this.getParamSchema(e,t);if(o)switch(o.type){case"number":return Y(i)&&(o.min===void 0||i>=o.min)&&(s===void 0?o.max===void 0||i<=o.max:i<=s);case"items":return Q(i)&&i.length===new Set(i).size&&(s===void 0?i.every(n=>o.items.find(({_id:l})=>l===n)):i.every(n=>s.includes(n)))}}return!1}adjustParam(e,t){switch(e.type){case"number":return Y(t)?Math.max(Math.min(t,e.max??1/0),e.min??0):e.min??0;default:return Q(t)?G(e.items.map(i=>i._id),t):[]}}adjust(e,t){let i={};for(let[s,o]of Object.entries(e)){let n=this.get(s,t);if(n)if(n.params||n.abilities){let l={};if(n.params)if(X(o))for(let a of n.params)l[a._id]=this.adjustParam(a,o[a._id]);else for(let a of n.params)l[a._id]=this.getDefaultParam(a);n.abilities&&X(o)&&Object.assign(l,this.adjust(he(o,n.abilities.filter(a=>!a.top).map(a=>a._id)),n)),i[s]=l}else i[s]=!0}return Object.assign(k(e),i)}merge(e,t,i){i||(this.adjust(e),t=this.adjust(structuredClone(t)));for(let[s,o]of Object.entries(t)){let n=this.get(s,i);if(n&&n.isInheritable!==!1)if(s in e&&(n.params||n.abilities)){let l=e[s],a=o;if(n.params){for(let p of n.params)if(p.isInheritable!==!1)switch(p.type){case"number":l[p._id]=Math.max(l[p._id],a[p._id]);break;case"items":pe(l[p._id],...a[p._id])}}n.abilities&&this.merge(l,a,n)}else e[s]=o}return e}hasAbility(e,t){return!!N(e,t)}setAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return this.merge(e,this.getDefaultAbilities(i)),e}unsetAbility(e,t){let i=typeof t=="string"?this.get(t):t;if(!i)throw new Error(`No such ability: ${t}`);return function s(o){if(ue(e,o.longId),o.abilities)for(let n of o.abilities)s(n)}(i),e}};var V=class extends f{constructor(e,t){super(`User lacks role${Array.isArray(e)?"s":""}`,"lacksroles",{roles:Array.isArray(e)?e:[e],...t})}name="RolesError"};var ee=new Map,D=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t)}#e;_id;ownInvolveIds;ownAbilities;title="";displayTitle="";_o=0;ownInvolves=[];involves=new Set;abilities={};inheritedAbilities={};update({_id:e,involves:t,abilities:i,title:s,...o},n){if(Object.assign(this,o),t&&(this.ownInvolveIds=t),i&&(this.ownAbilities=i),s!==void 0&&(this.title=s,this.displayTitle=s||this._id),t||i){let l=[this.ownInvolveIds.join(","),JSON.stringify(this.ownAbilities)].join(`
2
+ `);l!==ee.get(this._id)&&(ee.set(this._id,l),this.#e.users.isInited&&this.#e.updateDebounced().then(()=>this.#e.users.emit("roles-role-update",this,n)))}}delete(){this.#e.delete(this._id),ee.delete(this._id),this.#e.updateDebounced()}};var c={_id:/^[\dA-Fa-f]{24}$/,email:/^[^\s@]{1,63}@[^\s@]{1,63}\.[^\s@]{1,63}$/,argon2:/^\$argon2(?:i|d|id)\$v=\d+\$m=\d+,t=\d+,p=\d+(?:\$[\d+/A-Za-z]+){2}$/,sessionId:/^(?:[\dA-Fa-f]{16,32}\$[\dA-Fa-f]{16,32}|[0-9a-f]{24}~[A-Za-z0-9_-]{43})$/,role:/^[\d_a-z-]{1,64}$/,ip:/^(?:\d{1,3}\.){3}\d{1,3}$/};var I={required:["_id","involves","abilities","title","description","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},involves:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source,not:{enum:["root"]}},additionalItems:!1},abilities:{bsonType:"object"},title:{bsonType:"string",maxLength:256},description:{bsonType:"string",maxLength:10240},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var _e=[[{involves:1}]];function xe(){throw new Error("Direct usage of roles collection.deleteOne or .deleteMany is forbidden. Use roles.deleteRole instead.")}var B=class extends Map{constructor(e,t={}){super();let{root:i,...s}=t;this.users=e,this.collections=e.collections,this.abilities=e.abilities,this.root=new D(this,{...i,_id:"root",involves:[],abilities:this.abilities.getDefaultAbilities(),title:"Root",description:"Root",meta:{},createdAt:Date.now()}),this.initOptions=s}users;collections;collection;abilities;root;initOptions;#e=!1;async init(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t,collection:i}=this.initOptions;e&&(e.required&&h(e.required,I.required),e.properties&&u(e,Object.keys(I.properties)));let s={...I,...e,required:[...I.required,...e?.required??[]],properties:{...I.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("roles",{...i,schema:s}),{deleteOne:xe,deleteMany:xe}),this.collection.ensureIndexes([..._e,...t??[]]),await this.#t();for(let o of await this.collection.find().toArray())this.abilities.adjust(o.abilities)&&await this.collection.updateOne({_id:o._id},{$set:{abilities:o.abilities}}),this.load(o);this.update(),this.collection.onChange(this.#i),delete this.initOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}#i=e=>{switch(e.operationType){case"insert":{let t=new D(this,e.fullDocument);this.users.emit("roles-role-update",t,e);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument,e);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields,e);break;case"delete":this.get(e.documentKey._id)?.delete(),this.users.emit("roles-role-update",null,e)}};load(e){new D(this,e)}resolve(e,t){t=[e,...t];for(let i of e.ownInvolveIds){let s=this.get(i);if(s){for(let o of t)be(o.involves,s),this.abilities.merge(o.inheritedAbilities,s.abilities);s!==e&&this.resolve(s,t)}}}sorted=[];#s(e,t){return t.involves.size-e.involves.size||(e.title&&t.title?e.title>t.title?1:e.title<t.title?-1:0:e.title?-1:t.title||e._id>t._id?1:e._id<t._id?-1:0)}update(){let e=[...this.values()];this.root.ownInvolveIds=[];for(let s of e)s!==this.root&&!e.some(o=>o.ownInvolveIds.includes(s._id))&&this.root.ownInvolveIds.push(s._id),s.involves.clear(),s.abilities=structuredClone(s.ownAbilities),s.inheritedAbilities={};this.root.involves.add(this.root),this.resolve(this.root,[]);for(let s of e)s.ownInvolves=H(this,s.ownInvolveIds,!0).sort(this.#s).reverse();let t=[this.root];for(let s=0;s<t.length;s++){let o=t[s];for(let n of o.ownInvolves){let l=t.indexOf(n);~l&&(t.splice(l,1),s--),t.splice(s+1,0,n)}}let i=0;for(let s of t)this.abilities.merge(s.abilities,s.inheritedAbilities),s._o=i++;this.sorted=t,this.users.emit("roles-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update(!0))}updateDebounced=m(this.update,100);async create({_id:e,involves:t,title:i,description:s,...o}){return await this.collection.insertOne({_id:e,involves:t||[],abilities:{},title:i??"",description:s??"",meta:{},...u(o,["abilities"]),createdAt:Date.now()}),e}async updateRole(e,t){let i=this.get(e);if(!i)return!1;if(t.involves){h(t.involves,[e]);for(let s of t.involves)this.get(s)?.involves.has(i)&&h(t.involves,[s]);t.involves=this.cleanUpIds(t.involves)}return await this.collection.updateOne({_id:e},{$set:t}),!0}deleteRole(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{involves:t},update:{$pullAll:{involves:[t]}}}},{deleteOne:{filter:{_id:t}}}])}cleanUpIds(e){let t=G(this.sorted,H(this,e,!0)),i=[];for(let s of t)t.every(o=>o===s||!o.involves.has(s))&&i.push(s._id);return i}async setAbility(e,t,i){let s=this.get(e);return s?(await this.collection.updateOne({_id:e},{$set:{abilities:i?this.abilities.setAbility(s.ownAbilities,t):this.abilities.unsetAbility(s.ownAbilities,t)}}),!0):!1}async setAbilityParam(e,t,i,s){let o=this.get(e);return o?(await this.collection.updateOne({_id:e},{$set:{abilities:this.abilities.setParam(o.ownAbilities,t,i,s)}}),!0):!1}};var te=class extends f{constructor(e){super("Unauthorized","unauthorized",e)}name="UnauthorizedError"},ie=class extends f{constructor(e,t,i){switch(arguments.length){case 1:i=e,e=void 0;break;case 2:i=t,t=void 0}super("Insubordination attempt","subordination",{...e&&{type:e},...t&&{ids:Array.isArray(t)?t:[t]},...i})}name="SubordinationError"},se=class extends f{constructor(e){super("Insufficient permissions","permissions",e)}name="PermissionError"};import*as M from"argon2";import Ue from"eventemitter3";import{newObjectIdString as Ce}from"insite-db";import{newObjectIdString as Pe}from"insite-db";var oe=new Map,b=class{constructor(e,t){this.orgs=e,this._id=t._id,e.set(this._id,this),this.update(t)}_id;title="";initials="";displayLabel="";_o=0;orgs;isOrg=!0;ownerOrgs=new Set;ownerUsers=new Set;users=new Set;slaveOrgs=new Set;ownerIds=[];update({_id:e,title:t,owners:i,...s},o){if(Object.assign(this,s),t!==void 0&&(this.title=t,this.initials=t?.[0]?.toUpperCase()??"",this.displayLabel=t),i){this.ownerIds=i;let n=this.ownerIds.join(",");n!==oe.get(this._id)&&(oe.set(this._id,n),this.orgs.users.isInited&&this.orgs.updateDebounced(),this.orgs.users.emit("orgs-org-update",this,o))}}delete(){this.orgs.delete(this._id),oe.delete(this._id),this.orgs.replace(this._id),this.orgs.updateDebounced()}};var R={required:["_id","title","note","owners","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},title:{bsonType:"string",maxLength:512},note:{bsonType:"string",maxLength:131072},owners:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c._id.source},additionalItems:!1},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var De=[[{owners:1}]];function we(){throw new Error("Direct usage of orgs collection.deleteOne or .deleteMany is forbidden. Use orgs.deleteOrg instead.")}var F=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.preinitOptions=t}users;collections;preinitOptions;collection;null;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{schema:e,indexes:t,null:i,collection:s}=this.preinitOptions;e&&(e.required&&h(e.required,R.required),e.properties&&u(e,Object.keys(R.properties)));let o={...R,...e,required:[...R.required,...e?.required??[]],properties:{...R.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("orgs",{...s,schema:o}),{deleteOne:we,deleteMany:we}),this.collection.ensureIndexes([...De,...t??[]]),this.null=Object.assign(new b(this,{...i,_id:"",title:"",note:"",owners:[],meta:{},createdAt:Date.now()}),{_id:null,ownerIds:new q,ownerOrgs:new P,ownerUsers:new P,slaveOrgs:new P}),await this.#t();for(let n of await this.collection.find().toArray())this.load(n);delete this.preinitOptions}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}#i=!1;init(){this.#i||(this.#i=!0,this.update(),this.collection.onChange(this.#s))}#s=e=>{switch(e.operationType){case"insert":{let t=new b(this,e.fullDocument);this.users.emit("orgs-org-update",t,e);break}case"replace":this.get(e.documentKey._id)?.update(e.fullDocument,e);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields,e);break;case"delete":this.get(e.documentKey._id)?.delete(),this.users.emit("orgs-org-update",null,e)}};load(e){new b(this,e)}#o(e,t){t=[e,...t];for(let i of e.ownerOrgs){this.#o(i,t);for(let s of t)i.slaveOrgs.add(s)}}sorted=[];update(){let e=[...this.values()],t=[];for(let i of e){i.ownerOrgs.clear(),i.ownerUsers.clear(),i.slaveOrgs.clear();for(let s of i.ownerIds){let o=this.get(s);if(o)i.ownerOrgs.add(o);else{let n=this.users.get(s);n&&i.ownerUsers.add(n)}}!i.ownerOrgs.size&&i._id&&t.push(i)}for(let i of e)e.some(s=>s.ownerOrgs.has(i))||this.#o(i,[]);t.sort(this.#r);for(let i of e)ye(i.slaveOrgs,this.#r);for(let i=0;i<t.length;i++){let s=t[i];for(let o of[...s.slaveOrgs].reverse())if(o.ownerOrgs.has(s)){let n=t.indexOf(o);~n&&(t.splice(n,1),i--),t.splice(i+1,0,o)}}for(let i=0,{length:s}=t;i<s;)t[i]._o=i++;this.sorted=t,this.users.emit("orgs-update"),this.users.isInited&&(this.users.updateDebounced.clear(),this.users.update())}#r(e,t){return t.slaveOrgs.size-e.slaveOrgs.size||(e.title>t.title?1:e.title<t.title?-1:0)}updateDebounced=m(this.update,250);async create({title:e,note:t,...i}){let s=Pe();return await this.collection.insertOne({_id:s,title:e??"",note:t??"",meta:{},...u(i,["_id"]),createdAt:Date.now()}),s}async updateOrg(e,t,i){let s=this.get(e);return s?(t.owners&&(t.owners=this.users.sortIds(Ae(i?C(s.ownerIds,i.slaveIds):[],C(t.owners,[e,...x(s.slaveOrgs)])))),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}deleteOrg(e){let t=typeof e=="string"?e:e._id;return this.collection.bulkWrite([{updateMany:{filter:{owners:t},update:{$pullAll:{owners:[t]}}}},{deleteOne:{filter:{_id:t}}}])}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let i of this.replaceHandlers)await i(e,t)}};import{randomBytes as Ie}from"node:crypto";import{newObjectIdString as Re}from"insite-db";var T={required:["_id","user","remoteAddress","isOnline","meta","createdAt","prolongedAt","expiresAt"],properties:{_id:{bsonType:"string",pattern:c.sessionId.source},user:{bsonType:"string",pattern:c._id.source},userAgent:{bsonType:"string",maxLength:4096},remoteAddress:{bsonType:"string",pattern:c.ip.source},isOnline:{bsonType:"bool"},meta:{bsonType:"object"},createdAt:{bsonType:"number"},prolongedAt:{bsonType:"number"},expiresAt:{bsonType:"date"}}};var $=class{constructor(e,t){let i=e.users.get(t.user);i?(this.#e=e,this._id=t._id,this.#e.set(this._id,this),this.user=i,this.user.sessions.add(this),this.#e.users.bySessionId.set(this._id,this.user),this.update(t)):e.collection.deleteOne({_id:t._id})}_id;user;isOnline=!1;userAgent;remoteAddress;createdAt;prolongedAt;expiresAt;#e;update({_id:e,user:t,isOnline:i,...s}){i!==void 0&&this.isOnline!==i&&(this.isOnline=i,this.#e.isInited&&this.user.isOnline!==this.isOnline&&this.user.updateIsOnline()),Object.assign(this,s)}prolong({_id:e,user:t,...i}){let s=Date.now();return i.prolongedAt=s,i.expiresAt=new Date(s+this.#e.collection.expireAfterSeconds*1e3),this.update(i),this.#e.collection.updateOne({_id:this._id},{$set:i})}async online(){if(!this.isOnline){let e={isOnline:!0};this.update(e),await this.#e.collection.updateOne({_id:this._id},{$set:e})}}async offline(){if(this.isOnline){let e={isOnline:!1};this.update(e),await this.#e.collection.updateOne({_id:this._id},{$set:e})}}delete(){this.#e.delete(this._id),this.user.sessions.delete(this),this.#e.users.bySessionId.delete(this._id),this.#e.users.emit("session-delete",this),this.isOnline&&this.user.updateIsOnline()}};var re=3600*24*7,Te=[[{user:1}],[{expiresAt:1},{expireAfterSeconds:re}]],z=class extends Map{constructor(e,t={}){super(),this.users=e,this.collections=e.collections,this.initOptions=t}users;collections;initOptions;collection;isInited=!1;async init(){if(!this.isInited){this.isInited=!0;let{schema:e,indexes:t,collection:i}=this.initOptions;e&&(e.required&&h(e.required,T.required),e.properties&&u(e,Object.keys(T.properties)));let s={...T,...e,required:[...T.required,...e?.required??[]],properties:{...T.properties,...e?.properties}};this.collection=Object.assign(await this.collections.ensure("sessions",{...i,schema:s}),{expireAfterSeconds:re}),this.collection.ensureIndexes([...Te,...t??[]]),await this.#e();for(let o of await this.collection.find().toArray())this.load(o);this.collection.onChange(this.#t),delete this.initOptions}}async#e(){await this.collection.bulkWrite([{updateMany:{filter:{meta:{$exists:!1}},update:{$set:{meta:{}}}}},{updateMany:{filter:{isOnline:!0},update:{$set:{isOnline:!1}}}}])}#t=e=>{switch(e.operationType){case"insert":this.has(e.documentKey._id)||new $(this,e.fullDocument),this.users.get(e.fullDocument.user)?.trimSessions();break;case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};uid(){return`${Re()}~${Ie(32).toString("base64url")}`}load(e){new $(this,e)}async create(e,t){let i=Date.now(),s={userAgent:"",remoteAddress:"127.0.0.1",isOnline:!0,...t,_id:this.uid(),user:e._id,meta:{},createdAt:i,prolongedAt:i,expiresAt:new Date(i+re*1e3)},o=new $(this,s);return await this.collection.insertOne(s),o}async destroySession(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}};import{Binary as $e}from"insite-db";var Oe={required:["_id","type","size","ts","data","meta"],properties:{_id:{bsonType:"string",pattern:c._id.source},type:{bsonType:"string",maxLength:256},size:{bsonType:"number"},ts:{bsonType:"string",maxLength:10},data:{bsonType:"binData"},meta:{bsonType:"object"}},additionalProperties:!1};var K=class{constructor(e,t={}){this.users=e,this.collections=e.collections,this.initOptions=t}TYPES_ACCEPTED=["image/webp"];MAX_SIZE=1024*512;users;collections;collection;initOptions;#e=!1;async init(){if(!this.#e){this.#e=!0;let{collection:e}=this.initOptions;this.collection=await this.collections.ensure("users.avatars",{...e,schema:Oe}),await this.#t()}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}async save(e,t,i){let s=$e.createFromBase64(i.slice(i.indexOf(","))),o=Date.now().toString(36);await Promise.all([this.collection.replaceOne({_id:e},{type:t,size:s.length(),ts:o,data:s,meta:{}},{upsert:!0}),this.users.collection.updateOne({_id:e},{$set:{avatar:o}})])}async deleteAvatar(e){let[{deletedCount:t}]=await Promise.all([this.collection.deleteOne({_id:e}),this.users.collection.updateOne({_id:e},{$set:{avatar:null}})]);return!!t}};var j={required:["_id","email","password","roles","name","org","job","meta","createdAt"],properties:{_id:{bsonType:"string",pattern:c._id.source},email:{bsonType:"string",pattern:c.email.source},password:{bsonType:"string",pattern:c.argon2.source},roles:{bsonType:"array",uniqueItems:!0,items:{bsonType:"string",pattern:c.role.source},additionalItems:!1},name:{bsonType:"object",required:["first","middle","last"],properties:{first:{bsonType:"string",maxLength:512},middle:{bsonType:"string",maxLength:512},last:{bsonType:"string",maxLength:512}},additionalProperties:!1},org:{oneOf:[{bsonType:"string",pattern:c._id.source},{bsonType:"null"}]},job:{bsonType:"string",maxLength:512},avatar:{oneOf:[{bsonType:"string",maxLength:10},{bsonType:"null"}]},meta:{bsonType:"object"},createdAt:{bsonType:"number"}},additionalProperties:!1};var ne=new Map,le=new Map,je=process.env.INSITE_STATIC_URL??"http://localhost:8080",w=class{constructor(e,t){this.#e=e,this._id=t._id,e.set(this._id,this),this.update(t),e.isInited&&e.emit("user-create",this)}_id;email;name={first:"",middle:"",last:""};initials="";displayLabel="";org;job="";avatar=null;avatarUrl=null;#e;isUser=!0;isRoot;roles=new Set;ownRoles=[];ownRoleIds=[];slaveRoles=new Set;slaveRoleIds=[];abilities={};slaveOrgs=new Set;slaveUsers=new Set;slaves=new Set;slaveIds=[];permissiveIds=[];sessions=new Set;isOnline=!1;update({_id:e,name:t,email:i,roles:s,org:o,avatar:n,...l}){Object.assign(this,l);let a;i&&this.email!==i&&(this.#e.byEmail.delete(this.email),this.email=i,this.#e.byEmail.set(i,this),a=!0);let p,y;t&&(this.name.first!==t.first||this.name.middle!==t.middle||this.name.last!==t.last)&&(y=this.name.last!==t.last,this.name={first:t.first??"",middle:t.middle??"",last:t.last??""},this.initials=((t.first?.[0]??"")+(t.last?.[0]??"")||this.email[0]).toUpperCase(),p=!0),(a||p)&&(this.displayLabel=`${this.name.first} ${this.name.last}`.trim()||this.name.middle||this.email);let A;if(s){this.ownRoleIds=s;let O=this.ownRoleIds.join(",");O!==ne.get(this._id)&&(ne.set(this._id,O),this.updateRoles(),A=!0)}let d;o!==void 0&&this.org?._id!==o&&(this.org?.users.delete(this),this.org=o&&this.#e.orgs.get(o)||this.#e.orgs.null,this.org.users.add(this),d=!0),n!==void 0&&this.avatar!==n&&(this.avatar=n,this.avatarUrl=n&&`${je}/avatars/${this._id}-${n}.webp`),A||d?(this.updatePermissions(),y&&(this.#e.isSortRequired=!0),this.#e.isInited&&this.#e.updateDebounced()):y&&this.#e.sortDebounced()}updateRoles(){if(this.#e.isInited){this.ownRoles=[],this.roles.clear(),this.slaveRoles.clear(),k(this.abilities);for(let e of this.ownRoleIds){let t=this.#e.roles.get(e);if(t){this.ownRoles.push(t),this.roles.add(t);for(let i of t.involves)this.roles.add(i),this.slaveRoles.add(i);this.slaveRoleIds=x(this.slaveRoles),this.#e.abilities.merge(this.abilities,t.abilities)}}this.roles.has(this.#e.roles.root)&&(this.isRoot=!0),this.trimSessions()}}updatePermissions(){if(this.#e.isInited){this.slaveOrgs.clear(),this.slaveUsers.clear(),this.slaves.clear();let e=new Set;for(let s of this.#e.orgs.sorted)if((s.ownerUsers.has(this)||this.isRoot)&&!this.slaveOrgs.has(s)){this.slaveOrgs.add(s),this.slaves.add(s),e.add(s._id);for(let o of s.slaveOrgs)this.slaveOrgs.add(o),this.slaves.add(o),e.add(o._id)}for(let s of new Set([this.org,...this.slaveOrgs,this.#e.orgs.null]))for(let o of s.users)o!==this&&(me(this.slaveRoles,o.ownRoles)||!o.ownRoles.length)&&(this.slaveUsers.add(o),this.slaves.add(o),e.add(o._id));this.slaveIds=[...e];let t=[];if(this.org._id){t.push(this.org._id);for(let s of this.org.slaveOrgs)this.slaveOrgs.has(s)||t.push(s._id)}this.permissiveIds=[...t,this._id,...e];let i=[this.permissiveIds.join(","),this.ownRoleIds.join(","),JSON.stringify(this.abilities),this.slaveRoleIds.join(",")].join(`
3
+ `);i!==le.get(this._id)&&(le.set(this._id,i),this.#e.emit("user-permissions-change",this))}}trimSessions(){let e=this.abilities.login?.sessionsLimit??0;if(this.sessions.size>e)return this.#e.sessions.collection.deleteMany({_id:{$in:x([...this.sessions].sort((t,i)=>t.expiresAt.valueOf()-i.expiresAt.valueOf()).slice(0,this.sessions.size-e))}})}updateIsOnline=m(()=>{let e=!1;for(let t of this.sessions)if(t.isOnline){e=!0;break}this.isOnline!==e&&(this.isOnline=e,this.#e.emit("user-is-online",this))},500);delete(){this.org.users.delete(this),this.#e.delete(this._id),this.#e.byEmail.delete(this.email),ge(this.#e.sorted,this),ne.delete(this._id),le.delete(this._id),this.#e.replace(this._id),this.#e.updateDebounced()}};var Me=[[{email:1},{unique:!0}],[{org:1}]],ae=class r extends Map{constructor(e,t){super();let i=new Ue;this._events=i._events,this._eventsCount=i._eventsCount,this.emit=i.emit,this.on=i.on,this.once=i.once,this.addListener=i.addListener,this.off=i.off,this.removeListener=i.removeListener,this.collections=e,this.abilities=new L(t.abilities),this.initOptions=t,this.init()}_events;_eventsCount;emit;on;once;addListener;off;removeListener;initOptions;collections;abilities;collection;roles;sessions;orgs;avatars;byEmail=new Map;bySessionId=new Map;sorted=[];isSortRequired=!1;#e=!1;async preinit(){if(!this.#e){this.#e=!0;let{indexes:e,schema:t,initialRoot:i,collection:s}=this.initOptions;t&&(t.required&&h(t.required,j.required),t.properties&&u(t,Object.keys(j.properties)));let o={...j,...t,required:[...j.required,...t?.required??[]],properties:{...j.properties,...t?.properties}};this.collection=await this.collections.ensure("users",{...s,schema:o}),this.collection.ensureIndexes([...Me,...e??[]]),await this.collection.countDocuments({roles:"root"})||await this.create({email:process.env.INSITE_ROOT_EMAIL??"insite@root.email",password:process.env.INSITE_ROOT_PASSWORD??"inSiteRootPassword",name:{first:"Root"},job:"Root",...i,roles:["root"],org:null,meta:{}}),await this.#t();for(let n of await this.collection.find().toArray())this.load(n)}}async#t(){await this.collection.updateMany({meta:{$exists:!1}},{$set:{meta:{}}})}isInited=!1;async init(){if(!this.isInited){this.isInited=!0;let{roles:e,orgs:t,sessions:i,avatars:s,collection:{quiet:o}={}}=this.initOptions;this.roles=new B(this,{...e,collection:{quiet:o,...e?.collection}}),this.orgs=new F(this,{...t,collection:{quiet:o,...t?.collection}}),this.sessions=new z(this,{...i,collection:{quiet:o,...i?.collection}}),this.avatars=new K(this,{...s,collection:{quiet:o,...s?.collection}}),await this.roles.init(),await this.orgs.preinit(),await this.preinit(),await this.orgs.init(),await this.avatars.init(),this.update(!0),this.collection.onChange(this.#i),await this.sessions.init(),delete this.initOptions,this.#s.resolve(this)}}#i=e=>{switch(e.operationType){case"insert":new w(this,e.fullDocument);break;case"replace":this.get(e.documentKey._id)?.update(e.fullDocument);break;case"update":this.get(e.documentKey._id)?.update(e.updateDescription.updatedFields);break;case"delete":this.get(e.documentKey._id)?.delete()}};load(e){new w(this,e)}sort(){this.isSortRequired=!1,this.sorted=[...this.values()].sort((e,t)=>e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0)}sortDebounced=m(()=>this.sort(),250);update(e){if(e)for(let t of this.values())t.updateRoles();for(let t of this.values())t.updatePermissions();this.isSortRequired&&this.sort()}updateDebounced=m(()=>this.update(),250);#s=new W;whenReady(){return this.#s}async create({email:e,password:t,roles:i,name:s,org:o,job:n,...l}){if(this.byEmail.has(e))throw new Error("User exists");let a=Ce();return await this.collection.insertOne({_id:a,email:e,password:await M.hash(t),roles:this.isInited?this.roles.cleanUpIds(i):i,name:{first:s.first??"",middle:s.middle??"",last:s.last??""},org:o??null,job:n??"",meta:{},...u(l,["_id"]),createdAt:Date.now()}),a}async updateUser(e,t,i){let s=this.get(e);return s?(t.roles&&(t.roles=s.isRoot?["root"]:this.roles.cleanUpIds(i?C(s.ownRoleIds,i.slaveRoleIds).concat(t.roles):t.roles)),await this.collection.updateOne({_id:e},{$set:t}),!0):!1}async changePassword(e,t){if(!this.has(e))throw new Error("usernotfound");if(!t)throw new Error("emptypasswordisnotallowed");await Promise.all([this.collection.updateOne({_id:e},{$set:{password:await M.hash(t)}}),this.sessions.collection.deleteMany({user:e})])}async login(e,t,i){let s=this.byEmail.get(e);if(!s)throw new Error("usernotfound");if(!await M.verify(s.password,t))throw new Error("incorrectpassword");if(!s.abilities.login)throw new Error("userisnotabletologin");return this.sessions.create(s,i)}logout(e){return e.delete(),this.sessions.collection.deleteOne({_id:e._id})}#o(e,t){return e instanceof w&&t instanceof w?e.name.last&&t.name.last?e.name.last>t.name.last?1:e.name.last<t.name.last?-1:0:!e.name.last&&!t.name.last?e.displayLabel>t.displayLabel?1:e.displayLabel<t.displayLabel?-1:0:e.name.last?-1:1:e instanceof b&&t instanceof b?e.title>t.title?1:e.title<t.title?-1:0:e instanceof b?-1:1}sortIds(e){return x(e.map(t=>this.get(t)||this.orgs.get(t)).filter(Boolean).sort(this.#o))}replaceMap=new Map;replaceHandlers=new Set;async replace(e){let t=this.replaceMap.get(e)??null;t&&this.replaceMap.delete(e);for(let i of this.replaceHandlers)await i(e,t)}async deleteUser(e){let{deletedCount:t}=await this.collection.deleteOne({_id:e});return!!t}static init(e,t){return new r(e,t).whenReady()}};export{Z as AbilityError,se as PermissionError,V as RolesError,ie as SubordinationError,te as UnauthorizedError,ae as Users};
4
4
  //# sourceMappingURL=index.js.map