@asaidimu/hestia 1.1.0 → 1.2.0

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/README.md CHANGED
@@ -24,10 +24,17 @@ bun add @asaidimu/hestia
24
24
  ## Quick Start
25
25
 
26
26
  ```ts
27
- import { HestiaClient } from "@asaidimu/hestia"
27
+ import { HestiaClient, WailsTransport } from "@asaidimu/hestia"
28
28
 
29
+ // HTTP mode (browser/node)
29
30
  const api = new HestiaClient({ baseUrl: "http://localhost:8070" })
30
31
 
32
+ // Wails desktop mode — same API, different transport
33
+ const desktop = new HestiaClient({
34
+ transport: new WailsTransport(),
35
+ })
36
+ // Now api.auth.login(), api.users.find(), etc. call Go directly
37
+
31
38
  // Login as admin
32
39
  const { token, user } = await api.auth.login("admin@test.local", "password123")
33
40
  console.log("Logged in as", user.email)
@@ -62,7 +69,7 @@ The main entry point. Construct with a `baseUrl` pointing to a Hestia server.
62
69
  | `collections` | `HestiaCollections` | Generic collection metadata |
63
70
  | `blobs` | `HestiaBlobClient` | Blob (file) storage |
64
71
  | `capabilities` | `HestiaCapabilities` | Available capabilities |
65
- | `client` | `HestiaNetworkClient` | Low-level HTTP client |
72
+ | `client` | `Transport` | Low-level transport (HTTP or Wails) |
66
73
 
67
74
  ### Auth
68
75
 
package/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@asaidimu/network-client"),t=require("@asaidimu/utils-error"),n=require("@asaidimu/utils-store"),r=require("@asaidimu/utils-sync"),i=require("@asaidimu/query");async function a(e){try{return(await e.clone().json())?.error??null}catch{return null}}function o(e,n){if(n)return new t.SystemError({code:n.code??`UNKNOWN`,message:n.message??`Unknown error`,issues:n.details?.issues});let r=e.error?.message;if(typeof r==`object`&&r){let e=r;return new t.SystemError({code:e.code??`UNKNOWN`,message:e.message??`Unknown error`})}return new t.SystemError({code:`UNKNOWN`,message:r??`Unknown error`})}function s(e){return t.Errors.notFound(e)}function c(e){return t.Errors.permissionDenied(e)}function l(e){return t.Errors.internalError(e)}var u=class{data;status;constructor(e,t){this.data=e,this.status=t}},d=class{baseUrl;apiPrefix;provider;onAuthStateChanged;raw;heartbeatTimer;defaultHeartbeatInterval=300*1e3;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.provider=r,this.onAuthStateChanged=i,this.raw=(0,e.createNetworkClient)({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`})}base(){return this.baseUrl}prefix(){return this.apiPrefix}startHeartbeat(e){this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval;this.heartbeatTimer=setInterval(()=>this.heartbeat(),t)}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async heartbeat(){try{let e=this.canonicalPath(`system/core/heartbeat`),t=`${this.baseUrl.replace(/\/+$/,``)}/${e}`;await fetch(t,{method:`GET`,credentials:`include`})}catch{}}canonicalPath(e){let t=e.replace(/^\/+/,``);if(this.apiPrefix){let e=this.apiPrefix.replace(/^\/+/,``),n=RegExp(`^${e}/?`);return t=t.replace(n,``),`${e}/${t}`}return t}async request(e,n,r,i){let s=this.canonicalPath(n),c={};i?.headers&&(c.headers={...i.headers}),i?.responseType&&(c.responseType=i.responseType),i?.bodyType&&(c.bodyType=i.bodyType),i?.signal&&(c.signal=i.signal),c.headers||={};let l;if(e===`GET`)l=await this.raw.get(s,c);else{let t=i?.bodyType?{type:i.bodyType}:void 0;l=await this.raw[e.toLowerCase()](s,r,c,t)}if(l.success||l.status===204)return new u(l.data,l.status);if(l.status===401)throw i?.headers?.[`X-API-Key`]||(await this.provider.clear(),this.onAuthStateChanged?.()),new t.SystemError({code:`AUTH-002-UNAUTH`,message:`Session expired`});let d=l.raw?await a(l.raw):null;throw o(l,d)}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async openStream(e,n,r){let i={Accept:`text/event-stream`,...r?.headers??{}},a=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,o;try{o=await fetch(a,{method:`GET`,headers:i,signal:r?.signal})}catch(e){if(e instanceof Error&&e.name===`AbortError`){n.onClose?.();return}n.onError?.(e instanceof Error?e:Error(String(e)));return}if(o.status===401){this.onAuthStateChanged?.(),n.onError?.(new t.SystemError({code:`AUTH-002-UNAUTH`,message:`Session expired`}));return}if(!o.ok||!o.body){n.onError?.(Error(`Stream request failed with status ${o.status}`));return}n.onOpen?.();let s=o.body.getReader(),c=new TextDecoder,l=``;try{for(;;){let{done:e,value:t}=await s.read();if(e)break;l+=c.decode(t,{stream:!0});let r=l.indexOf(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@asaidimu/network-client"),t=require("@asaidimu/utils-error"),n=require("@asaidimu/utils-sync"),r=require("@asaidimu/utils-store"),i=require("@asaidimu/query");async function a(e){try{return(await e.clone().json())?.error??null}catch{return null}}function o(e,n){if(n)return new t.SystemError({code:n.code??`UNKNOWN`,message:n.message??`Unknown error`,issues:n.details?.issues});let r=e.error?.message;if(typeof r==`object`&&r){let e=r;return new t.SystemError({code:e.code??`UNKNOWN`,message:e.message??`Unknown error`})}return new t.SystemError({code:`UNKNOWN`,message:r??`Unknown error`})}function s(e){return t.Errors.notFound(e)}function c(e){return t.Errors.permissionDenied(e)}function l(e){return t.Errors.internalError(e)}var u=class{data;status;constructor(e,t){this.data=e,this.status=t}},d=class{baseUrl;apiPrefix;provider;onAuthStateChanged;raw;heartbeatTimer;defaultHeartbeatInterval=300*1e3;routeCache=null;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.provider=r,this.onAuthStateChanged=i,this.raw=(0,e.createNetworkClient)({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`})}async getRouteCache(){if(this.routeCache)return this.routeCache;this.routeCache=new Map;try{let e=this.canonicalPath(`system/core/docs`),t=await this.raw.get(e,{headers:{}});if(t.success){let e=t.data?.data;if(Array.isArray(e))for(let t of e){if(!t.name||!t.http)continue;let e=[],n=t.input?.fields?.arguments;if(n?.schema?.id){let r=n.schema.id,i=t.input?.schemas?.[r];if(i?.fields)for(let t of Object.keys(i.fields))e.push(t)}this.routeCache.set(t.name,{method:t.http.method,route:t.http.route,arguments:e})}}}catch{}return this.routeCache}substituteArgs(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>t[n]?encodeURIComponent(t[n]):`{${n}}`)}async dispatch(e,n){let r=(await this.getRouteCache()).get(e);if(!r)throw new t.SystemError({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e} — has the server been bootstrapped?`});let i=this.substituteArgs(r.route,n?.arguments??{}),a=r.method,o={};if(n?.headers&&(o.headers=n.headers),n?.responseType&&(o.responseType=n.responseType),n?.bodyType&&(o.bodyType=n.bodyType),n?.signal&&(o.signal=n.signal),n?.modifiers){let e=Object.entries(n.modifiers).flatMap(([e,t])=>(Array.isArray(t)?t:[t]).map(t=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join(`&`);if(e){let t=i.includes(`?`)?`&`:`?`;return this.request(a,`${i}${t}${e}`,n?.payload,o)}}return this.request(a,i,n?.payload,o)}base(){return this.baseUrl}prefix(){return this.apiPrefix}async ready(){}startHeartbeat(e){this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval;this.heartbeatTimer=setInterval(()=>this.heartbeat(),t)}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async heartbeat(){try{let e=this.canonicalPath(`system/core/heartbeat`),t=`${this.baseUrl.replace(/\/+$/,``)}/${e}`;await fetch(t,{method:`GET`,credentials:`include`})}catch{}}canonicalPath(e){let t=e.replace(/^\/+/,``);if(this.apiPrefix){let e=this.apiPrefix.replace(/^\/+/,``),n=RegExp(`^${e}/?`);return t=t.replace(n,``),`${e}/${t}`}return t}async request(e,n,r,i){let s=this.canonicalPath(n),c={};i?.headers&&(c.headers={...i.headers}),i?.responseType&&(c.responseType=i.responseType),i?.bodyType&&(c.bodyType=i.bodyType),i?.signal&&(c.signal=i.signal),c.headers||={};let l;if(e===`GET`)l=await this.raw.get(s,c);else{let t=i?.bodyType?{type:i.bodyType}:void 0;l=await this.raw[e.toLowerCase()](s,r,c,t)}if(l.success||l.status===204)return new u(l.data,l.status);if(l.status===401)throw i?.headers?.[`X-API-Key`]||(await this.provider.clear(),this.onAuthStateChanged?.()),new t.SystemError({code:`AUTH-002-UNAUTH`,message:`Session expired`});let d=l.raw?await a(l.raw):null;throw o(l,d)}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async openStream(e,n,r){let i={Accept:`text/event-stream`,...r?.headers??{}},a=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,o;try{o=await fetch(a,{method:`GET`,headers:i,signal:r?.signal})}catch(e){if(e instanceof Error&&e.name===`AbortError`){n.onClose?.();return}n.onError?.(e instanceof Error?e:Error(String(e)));return}if(o.status===401){this.onAuthStateChanged?.(),n.onError?.(new t.SystemError({code:`AUTH-002-UNAUTH`,message:`Session expired`}));return}if(!o.ok||!o.body){n.onError?.(Error(`Stream request failed with status ${o.status}`));return}n.onOpen?.();let s=o.body.getReader(),c=new TextDecoder,l=``;try{for(;;){let{done:e,value:t}=await s.read();if(e)break;l+=c.decode(t,{stream:!0});let r=l.indexOf(`
2
2
 
3
3
  `);for(;r!==-1;){let e=l.slice(0,r);l=l.slice(r+2);let t=e.split(`
4
4
  `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());t.length>0&&n.onMessage(t.join(`
5
5
  `)),r=l.indexOf(`
6
6
 
7
- `)}}}catch(e){e instanceof Error&&e.name===`AbortError`||n.onError?.(e instanceof Error?e:Error(String(e)))}finally{n.onClose?.()}}};const f={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function p(e,t,i,a){let o=i.page??1,s=i.size??20,c=i.sort,l=i.filter,u=new r.Debouncer({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:n.DELETE_SYMBOL,page:{number:1,size:20,count:0,total:0,pages:1}}});let p=e=>{let t=e?.page??o,n=e?.size??s,r={pagination:{type:`offset`,offset:(t-1)*n,limit:n}},i=e?.sort??c;i&&(r.sort=Array.isArray(i)?i:[i]);let a=e?.filter??l;return a&&(r.filters=a),r},m=async e=>(await t.set({[d]:{loading:!0,error:n.DELETE_SYMBOL}}),await new Promise(n=>{n(u.do(async()=>{requestIdleCallback(()=>{requestIdleCallback(async()=>{try{let n=await a(p(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...f,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),h=t.select(e=>e[d]),g=h.subscribe(()=>{});return{page:()=>h.get()??f,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);o=e,await m({page:e})},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);s=e,o=t,await m()},sort:async e=>{c=Array.isArray(e)?e:[e],o=1,await m()},filter:async e=>{l=e,o=1,await m()},refresh:async e=>{await Promise.all([new Promise(t=>setTimeout(t,e?.delay||0)),m(e)])},subscribe:e=>h.subscribe(e),invalidate:async()=>{await t.set({[d]:n.DELETE_SYMBOL}),g()},id:()=>d}}var m=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,r=50){this.client=e,this.collectionName=t,this.defaultLimit=r,this.pager=p(t,new n.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}get queryPath(){return`/system/collections/document/${encodeURIComponent(this.collectionName)}/query`}get documentsPath(){return`/system/collections/document/${encodeURIComponent(this.collectionName)}`}documentPath(e){return`${this.documentsPath}/${encodeURIComponent(e)}`}async find(e){let t=await this.client.post(this.queryPath,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async read(e){try{return(await this.client.get(this.documentPath(e))).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){return(await this.client.post(this.documentsPath,e.data)).data.data}async update(e){let t=e.options;return(await this.client.patch(this.documentPath(t),e.data)).data.data}async delete(e){await this.client.delete(this.documentPath(e))}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not implemented for dynamic collections`)}async notify(e){throw Error(`Notify not implemented for dynamic collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){return this.pager}},h=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.get(`/system/core/health`)).data.data}async login(e,t){let n=(await this.client.post(`/system/auth/session`,{email:e,password:t})).data.data;return this.provider.setIdentity(n.user),n}async register(e,t,n){return(await this.client.post(`/system/auth/user`,{email:e,password:t,name:n})).data.data}async logout(){await this.client.delete(`/system/auth/session`),await this.provider.clear()}async requestPasswordReset(e){await this.client.post(`/system/auth/password`,{email:e})}async confirmPasswordReset(e,t){await this.client.patch(`/system/auth/password`,{password:t,token:e})}async bootstrap(e,t,n){await this.client.patch(`/system/auth/bootstrap`,{password:t,email:n},{headers:{"X-API-Key":e}})}},g=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=p(`users`,new n.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.post(`/system/users/user/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.get(`/system/users/user/${encodeURIComponent(e)}`)).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){let t=e.options;return(await this.client.patch(`/system/users/user/${encodeURIComponent(t)}`,e.data)).data.data}async delete(e){await this.client.delete(`/system/users/user/${encodeURIComponent(e)}`)}async create(e){throw Error(`User creation requires email/password/name, use register endpoint`)}async upload(e){throw Error(`Upload not supported for users`)}async subscribe(e,t){throw Error(`Subscription not supported for users`)}async notify(e){throw Error(`Notify not supported for users`)}stream(e,t){throw Error(`Stream not supported for users`)}page(e){return this.pager}async changePassword(e,t,n){await this.client.patch(`/system/users/password/${encodeURIComponent(e)}`,{current:t,new:n})}},_=class{client;pager;constructor(e){this.client=e,this.pager=p(`_api_key_`,new n.ReactiveDataStore({}),{},e=>this.find(e))}basePath=`/system/apikeys/key`;async find(e){let t=await this.client.get(this.basePath),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return e?this.find(e):this.find()}async read(e){try{return(await this.client.get(`${this.basePath}/${encodeURIComponent(e)}`)).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){return(await this.client.post(this.basePath,e.data)).data.data}async update(e){let t=e.options;return(await this.client.patch(`${this.basePath}/${encodeURIComponent(t)}`,e.data)).data.data}async delete(e){await this.client.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async upload(e){throw Error(`Upload not supported for API keys`)}async subscribe(e,t){throw Error(`Subscription not supported for API keys`)}async notify(e){throw Error(`Notify not supported for API keys`)}stream(e,t){throw Error(`Stream not supported for API keys`)}page(e){return this.pager}async rotate(e){return(await this.client.post(`${this.basePath}/${encodeURIComponent(e)}`)).data.data}};const v=`/system/policies/operation`;var y=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.get(v)).data?.data?.operations??[];return{data:e.map(e=>({data:e,metadata:{}})),loading:!1,page:{number:1,size:e.length,count:e.length,total:e.length,pages:1},error:null}}async read(e){try{let t=await this.client.get(`${v}/${encodeURIComponent(e)}`);return t.data?.data?{data:t.data.data,metadata:{}}:void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}};const b=`/system/policies/policy`;var x=class{client;pager;constructor(e){this.client=e,this.pager=p(`policies`,new n.ReactiveDataStore({}),{},e=>this.find(e))}async find(e){return this.query(e??{})}async query(e){let t=await this.client.post(`/system/collections/document/_operation_policy_/query`,e),n=t.data?.data??[],r=t.data?.metadata?.page;return{data:n.map(e=>({_id_:e._id_,_metadata_:e._metadata_,id:e._id_,operationName:e.operation??``,ruleName:e.rule??``,enabled:e.enabled??!0,protected:e.protected??!1})),loading:!1,page:r??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){let t=(await this.client.get(b)).data?.data?.policies??[];return{data:t.map(e=>({data:e,metadata:{}})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.get(`${b}/${encodeURIComponent(e)}`);return t.data?.data?{data:t.data.data,metadata:{}}:void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Operation name is required for create`);let n={ruleName:e.data.ruleName??``},r=await this.client.post(`${b}/${encodeURIComponent(t)}`,n);if(r.data?.data)return{data:r.data.data,metadata:{}}}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);let n=await this.client.patch(`${b}/${encodeURIComponent(t)}`,e.data);if(n.data?.data)return{data:n.data.data,metadata:{}}}async setEnabled(e,t){return{data:(await this.client.patch(`${b}/${encodeURIComponent(e)}`,{enabled:t})).data.data,metadata:{}}}async delete(e){throw Error(`Policies cannot be deleted; disable instead`)}async upload(e){throw Error(`Upload not supported for policies`)}async subscribe(e,t){throw Error(`Subscription not supported for policies`)}async notify(e){throw Error(`Notify not supported for policies`)}stream(e,t){throw Error(`Stream not supported for policies`)}page(e){return this.pager}};const S=`/system/policies/rule`;var C=class{client;constructor(e){this.client=e}async find(e){return this.list()}async list(e){let t=(await this.client.get(S)).data?.data?.rules??[];return{data:t.map(e=>({_id_:e.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...e})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.get(`${S}/${encodeURIComponent(e)}`);if(!t.data?.data)return;let n=t.data.data;return{_id_:n.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...n}}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Rule name is required for create`);let n=await this.client.post(`${S}/${encodeURIComponent(t)}`,e.data);if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async update(e){let t=e.options;if(!t)throw Error(`Rule name is required for update`);let n=await this.client.patch(`${S}/${encodeURIComponent(t)}`,e.data);if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async delete(e){await this.client.delete(`${S}/${encodeURIComponent(e)}`)}async validate(e){return(await this.client.check(S,e)).data?.data??{valid:!1}}async reload(){return(await this.client.get(S)).data.data}async upload(e){throw Error(`Upload not supported for rules`)}async subscribe(e,t){throw Error(`Subscription not supported for rules`)}async notify(e){throw Error(`Notify not supported for rules`)}stream(e,t){throw Error(`Stream not supported for rules`)}page(e){throw Error(`Pagination not supported for rules`)}},w=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,r=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=r,this.pager=p(`_audit_log_`,new n.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/audit/log/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){throw Error(`Read by ID not supported for audit logs; use find with filters`)}async create(e){throw Error(`Audit logs are write-only; entries are created by the system`)}async update(e){throw Error(`Audit logs are append-only; updates are not allowed`)}async delete(e){throw Error(`Audit logs are append-only; deletion is not allowed`)}async upload(e){throw Error(`Upload not supported for audit logs`)}async subscribe(e,t){throw Error(`Use stream() for real-time audit log entries`)}async notify(e){throw Error(`Notify not supported for audit logs`)}stream(e,t){let n=this.getStreamUrl(),r=null,i=`active`,a=null,o=async function*(){let e=[];r=new EventSource(n,{withCredentials:!0}),r.onmessage=t=>{for(let n of t.data.split(`
8
- `)){let t=n.trim();if(t)try{let n=JSON.parse(t);n?.data&&e.push(n.data)}catch{}}e.length>0&&a&&(a(),a=null)},r.onerror=()=>{i===`active`&&(i=`completed`),a&&=(a(),null)};try{for(;i===`active`;)e.length>0?yield e.shift():await new Promise(t=>{a=t,e.length>0&&(t(),a=null)})}finally{r?.close(),a&&=(a(),null),i===`active`&&(i=`completed`)}};return{stream:()=>o(),cancel:()=>{i===`active`&&(i=`cancelled`,r?.close())},status:()=>i}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}};function T(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function E(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var D=class{client;ns;pagerOptions={};pager;prefixFilter=``;constructor(e,t){this.client=e,this.ns=t,this.pager=p(`blobs_${t}`,new n.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}basePath(){return`/system/blobs/blob/${encodeURIComponent(this.ns)}`}async find(e){let t=this.prefixFilter||e?.prefix||``,n=e?.limit??e?.pagination?.limit??0,r={};t&&(r.prefix=t),n&&(r.limit=n);let i=(await this.client.post(`${this.basePath()}/query`,r)).data?.data?.blobs??[];return{data:i.map(T),loading:!1,page:E(i),error:void 0}}async read(e){try{let t=await this.client.post(`${this.basePath()}/${encodeURIComponent(e)}/query`);return t.data?.data?T(t.data.data):void 0}catch(e){if(e?.code===`NOT_FOUND`)return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob update`);return T((await this.client.patch(`${this.basePath()}/${encodeURIComponent(t)}`,{custom:e.data})).data.data)}async delete(e){await this.client.delete(`${this.basePath()}/${encodeURIComponent(e)}`)}async list(e){return this.find(e??{})}async upload(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob upload`);let n={},r=e.options?.contentType||e.file.type;return r&&(n[`Content-Type`]=r),T((await this.client.post(`${this.basePath()}/${encodeURIComponent(t)}`,e.file,{headers:n,bodyType:`blob`})).data.data)}async subscribe(e,t){throw Error(`Subscription not supported for blobs`)}async notify(e){throw Error(`Notify not supported for blobs`)}stream(e,t){throw Error(`Stream not supported for blobs`)}page(e){return this.pager}async download(e){let t=(await this.client.get(`${this.basePath()}/${encodeURIComponent(e)}`,{responseType:`blob`})).data;return{data:t,contentType:t.type}}},O=class{client;apiPrefix;constructor(e,t=`/api`){this.client=e,this.apiPrefix=t}nsBase=`/system/blobs`;async namespaces(){return(await this.client.post(`${this.nsBase}/namespace/query`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.post(`${this.nsBase}/namespace`,e)).data.data}async deleteNamespace(e){await this.client.delete(`${this.nsBase}/namespace/${encodeURIComponent(e)}`)}blob(e,t){return`${this.client.base()}${this.apiPrefix}${this.nsBase}/blob/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}namespace(e){return new D(this.client,e)}},k=class{client;constructor(e){this.client=e}async find(e){let t=((await this.client.get(`/system/collections/collection`)).data?.data??[]).map(e=>({_id_:e.name,_metadata_:{checksum:``,created:e.created,updated:e.updated,version:1},name:e.name,schema:e.schema,created:e.created,updated:e.updated}));return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){try{let t=await this.client.get(`/system/collections/collection/${encodeURIComponent(e)}`);if(!t.data)return;let n=t.data.data;return{_id_:n.name,_metadata_:{checksum:``,created:n.created,updated:n.updated,version:1},name:n.name,schema:n.schema,created:n.created,updated:n.updated}}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){return(await this.client.post(`/system/collections/collection`,e.data)).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.delete(`/system/collections/collection/${encodeURIComponent(e)}`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not supported for collections`)}async notify(e){throw Error(`Notify not supported for collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){throw Error(`Pagination not supported for collection metadata; use documents(name)`)}documents(e){return new m(this.client,e)}},A=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.get(`/system/core/docs`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){throw Error(`Read by ID not supported for capabilities; use find()`)}async create(e){throw Error(`Capabilities are read-only`)}async update(e){throw Error(`Capabilities are read-only`)}async delete(e){throw Error(`Capabilities are read-only`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for capabilities`)}async subscribe(e,t){throw Error(`Subscription not supported for capabilities`)}async notify(e){throw Error(`Notify not supported for capabilities`)}stream(e,t){throw Error(`Stream not supported for capabilities`)}page(e){throw Error(`Pagination not supported for capabilities`)}},j=class{store;client;auth;users;keys;policies;rules;logs;collections;blobs;capabilities;tokenProvider;onAuthStateChanged;constructor(e){this.store=new n.ReactiveDataStore({identity:null},e.persistence);let t={identity:()=>this.store.get().identity,setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({identity:null})},r=e.apiPrefix??`/api`;this.tokenProvider=t,this.client=new d(e.baseUrl,r,t,()=>this.onAuthStateChanged?.()),this.auth=new h(this.client,t),this.users=new g(this.client),this.keys=new _(this.client),this.policies=new x(this.client),this.rules=new C(this.client),this.logs=new w(this.client,e.baseUrl,r),this.collections=new k(this.client),this.blobs=new O(this.client,r),this.capabilities=new A(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}authenticated(){return this.tokenProvider.identity()!==null}collection(e){return this.collections.documents(e)}};function M(e){let t=`${e.collectionName}_array_pager_state_`,r=new n.ReactiveDataStore({}),a=[...e.initialData??[]],o=`collection`,s,c=e.page??1,l=e.size??20,u=[],d,f,{match:p}=(0,i.createMatcher)(e.customFunctions??{}),{sort:m}=(0,i.createSorter)(),h=r.select(e=>e[t]),g={data:[],loading:!0,error:void 0,page:{number:1,size:l,count:0,total:0,pages:1}},_=()=>({filters:d,sort:u,pagination:{type:`offset`,offset:(c-1)*l,limit:l}}),v=async(n=!0)=>{if(e.fetch){if(f=void 0,n){let e=h.get()??g;await r.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=_(),n=await e.fetch(t);o=n.scope,s=n.total,a=n.replace?[...n.data]:[...a,...n.data]}catch(e){f=e}}let i=y(e.fetch?n:!1);await r.set({[t]:i})},y=e=>{let t=[...a];if(o===`collection`){d&&(t=t.filter(e=>p(e,d))),u.length>0&&(t=m(t,u));let n=t.length,r=Math.ceil(n/l)||1;c>r&&(c=r),c<1&&(c=1);let i=(c-1)*l,a=t.slice(i,i+l);return{data:a,loading:e,error:f,page:{number:c,size:l,count:a.length,total:n,pages:r}}}let n=s??t.length,r=Math.ceil(n/l)||1;return{data:t,loading:e,error:f,page:{number:c,size:l,count:t.length,total:n,pages:r}}};return v(!0),{id:()=>t,page:()=>h.get()??g,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);c=e,await v(!0)},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);l=e,c=t,await v(!0)},sort:async e=>{u=Array.isArray(e)?e:[e],c=1,await v(!0)},filter:async e=>{d=e,c=1,await v(!0)},refresh:async e=>{let n=h.get()??g;await r.set({[t]:{...n,loading:!0}});let i=e?.delay??600;await Promise.all([new Promise(e=>setTimeout(e,i)),v(!1)]);let a=h.get()??g;await r.set({[t]:{...a,loading:!1}})},subscribe:e=>h.subscribe(t=>{e(t)}),invalidate:async()=>{await r.set({[t]:n.DELETE_SYMBOL}),a=[]}}}exports.BlobNamespace=D,exports.HestiaAuth=h,exports.HestiaBlobClient=O,exports.HestiaClient=j,exports.HestiaCollection=m,exports.HestiaCollections=k,exports.HestiaKeyStore=_,exports.HestiaLogs=w,exports.HestiaNetworkClient=d,exports.HestiaOperations=y,exports.HestiaPolicies=x,exports.HestiaResponse=u,exports.HestiaRules=C,exports.HestiaUsers=g,exports.createArrayPager=M,exports.createPagedController=p,exports.internalError=l,exports.notFound=s,exports.parseErrorBody=a,exports.permissionDenied=c,exports.toSystemError=o;
7
+ `)}}}catch(e){e instanceof Error&&e.name===`AbortError`||n.onError?.(e instanceof Error?e:Error(String(e)))}finally{n.onClose?.()}}};const f=d;function p(){try{let e=window.go;if(!e)return null;for(let t of Object.values(e))for(let e of Object.values(t))if(e?.Dispatch)return e;return null}catch{return null}}var m=class{baseUrl=``;apiPrefix=``;init=new n.Once({throws:!0});config;constructor(e){this.config=e}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return p()}base(){return this.baseUrl}prefix(){return this.apiPrefix}async ready(e=1e4){this.init.do(async()=>{let n=Date.now();for(;!this.resolveService();){if(Date.now()-n>e)throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`Timed out after ${e}ms waiting for Wails bindings on window.go. Are you running inside a Wails desktop window?`});await new Promise(e=>setTimeout(e,50))}},e)}async dispatch(e,n){await this.ready();let r=this.resolveService();if(r?.Dispatch){let t=await r.Dispatch({name:e,arguments:n?.arguments??{},modifiers:n?.modifiers??{},payload:n?.payload??null});return new u(t.data,t.status)}throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Dispatch binding found on window.go. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}.`})}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async request(e,n,r,i){throw new t.SystemError({code:`USE_DISPATCH`,message:`WailsTransport does not support path-based requests. Use dispatch(name, input) instead.`})}async openStream(e,n,r){let i=this.resolveService();try{if(!i?.Stream)throw new t.SystemError({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Stream binding found. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}`});let r=await i.Stream(e),a=`hestia:stream:${e}`;window.runtime?.EventsOn(a,e=>{n.onMessage(typeof e==`string`?e:JSON.stringify(e))}),n.onOpen?.(),r&&n.onMessage(r),n.onClose?.()}catch(e){n.onError?.(e instanceof Error?e:Error(String(e))),n.onClose?.()}}};const h={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function g(e,t,i,a){let o=i.page??1,s=i.size??20,c=i.sort,l=i.filter,u=new n.Debouncer({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:r.DELETE_SYMBOL,page:{number:1,size:20,count:0,total:0,pages:1}}});let f=e=>{let t=e?.page??o,n=e?.size??s,r={pagination:{type:`offset`,offset:(t-1)*n,limit:n}},i=e?.sort??c;i&&(r.sort=Array.isArray(i)?i:[i]);let a=e?.filter??l;return a&&(r.filters=a),r},p=async e=>(await t.set({[d]:{loading:!0,error:r.DELETE_SYMBOL}}),await new Promise(n=>{n(u.do(async()=>{requestIdleCallback(()=>{requestIdleCallback(async()=>{try{let n=await a(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...h,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),g=m.subscribe(()=>{});return{page:()=>m.get()??h,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);o=e,await p({page:e})},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);s=e,o=t,await p()},sort:async e=>{c=Array.isArray(e)?e:[e],o=1,await p()},filter:async e=>{l=e,o=1,await p()},refresh:async e=>{await Promise.all([new Promise(t=>setTimeout(t,e?.delay||0)),p(e)])},subscribe:e=>m.subscribe(e),invalidate:async()=>{await t.set({[d]:r.DELETE_SYMBOL}),g()},id:()=>d}}var _=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=g(t,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.collectionName},payload:e??{}}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async read(e){try{return(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.collectionName,doc_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){return(await this.client.dispatch(`system:collections:document:create`,{arguments:{name:this.collectionName},payload:e.data})).data.data}async update(e){let t=e.options;return(await this.client.dispatch(`system:collections:document:update`,{arguments:{name:this.collectionName,doc_id:t},payload:e.data})).data.data}async delete(e){await this.client.dispatch(`system:collections:document:delete`,{arguments:{name:this.collectionName,doc_id:e}})}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not implemented for dynamic collections`)}async notify(e){throw Error(`Notify not implemented for dynamic collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){return this.pager}},v=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.dispatch(`system:core:health:check`)).data.data}async login(e,t){let n=await this.client.dispatch(`system:auth:session:create`,{payload:{email:e,password:t}});return this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:auth:user:register`,{payload:{email:e,password:t,name:n}})).data.data}async logout(){await this.client.dispatch(`system:auth:session:delete`),await this.provider.clear()}async requestPasswordReset(e){await this.client.dispatch(`system:auth:password:reset`,{payload:{email:e}})}async confirmPasswordReset(e,t){await this.client.dispatch(`system:auth:password:confirm`,{payload:{password:t,token:e}})}async bootstrap(e,t,n){await this.client.dispatch(`system:auth:bootstrap:password:set`,{payload:{password:t,email:n},headers:{"X-API-Key":e}})}},y=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=g(`users`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:users:user:query`,{payload:e??{}}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.dispatch(`system:users:user:get`,{arguments:{user_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){let t=e.options;return(await this.client.dispatch(`system:users:user:update`,{arguments:{user_id:t},payload:e.data})).data.data}async delete(e){await this.client.dispatch(`system:users:user:delete`,{arguments:{user_id:e}})}async create(e){throw Error(`User creation requires email/password/name, use register endpoint`)}async upload(e){throw Error(`Upload not supported for users`)}async subscribe(e,t){throw Error(`Subscription not supported for users`)}async notify(e){throw Error(`Notify not supported for users`)}stream(e,t){throw Error(`Stream not supported for users`)}page(e){return this.pager}async changePassword(e,t,n){await this.client.dispatch(`system:users:password:change`,{arguments:{user_id:e},payload:{current:t,new:n}})}},b=class{client;pager;constructor(e){this.client=e,this.pager=g(`_api_key_`,new r.ReactiveDataStore({}),{},e=>this.find(e))}async find(e){let t=await this.client.dispatch(`system:apikeys:key:list`),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return e?this.find(e):this.find()}async read(e){try{return(await this.client.dispatch(`system:apikeys:key:get`,{arguments:{key_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){return(await this.client.dispatch(`system:apikeys:key:create`,{payload:e.data})).data.data}async update(e){let t=e.options;return(await this.client.dispatch(`system:apikeys:key:update`,{arguments:{key_id:t},payload:e.data})).data.data}async delete(e){await this.client.dispatch(`system:apikeys:key:delete`,{arguments:{key_id:e}})}async upload(e){throw Error(`Upload not supported for API keys`)}async subscribe(e,t){throw Error(`Subscription not supported for API keys`)}async notify(e){throw Error(`Notify not supported for API keys`)}stream(e,t){throw Error(`Stream not supported for API keys`)}page(e){return this.pager}async rotate(e){return(await this.client.dispatch(`system:apikeys:key:rotate`,{arguments:{key_id:e}})).data.data}},x=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:operation:list`)).data?.data?.operations??[];return{data:e.map(e=>({data:e,metadata:{}})),loading:!1,page:{number:1,size:e.length,count:e.length,total:e.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:operation:get`,{arguments:{name:e}});return t.data?.data?{data:t.data.data,metadata:{}}:void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}},S=class{client;pager;constructor(e){this.client=e,this.pager=g(`policies`,new r.ReactiveDataStore({}),{},e=>this.find(e))}async find(e){return this.query(e??{})}async query(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:`_operation_policy_`},payload:e}),n=t.data?.data??[],r=t.data?.metadata?.page;return{data:n.map(e=>({_id_:e._id_,_metadata_:e._metadata_,id:e._id_,operationName:e.operation??``,ruleName:e.rule??``,enabled:e.enabled??!0,protected:e.protected??!1})),loading:!1,page:r??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t.map(e=>({data:e,metadata:{}})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e);return t?{data:{id:t._id_,operationName:t.operation??``,ruleName:t.rule??``,enabled:t.enabled??!0,protected:t.protected??!1},metadata:{}}:void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Operation name is required for create`);let n={ruleName:e.data.ruleName??``},r=await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n});if(r.data?.data)return{data:r.data.data,metadata:{}}}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);let n=await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:e.data});if(n.data?.data)return{data:n.data.data,metadata:{}}}async setEnabled(e,t){return{data:(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data,metadata:{}}}async delete(e){throw Error(`Policies cannot be deleted; disable instead`)}async upload(e){throw Error(`Upload not supported for policies`)}async subscribe(e,t){throw Error(`Subscription not supported for policies`)}async notify(e){throw Error(`Notify not supported for policies`)}stream(e,t){throw Error(`Stream not supported for policies`)}page(e){return this.pager}},C=class{client;constructor(e){this.client=e}async find(e){return this.list()}async list(e){let t=(await this.client.dispatch(`system:policies:rule:list`)).data?.data?.rules??[];return{data:t.map(e=>({_id_:e.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...e})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:rule:get`,{arguments:{name:e}});if(!t.data?.data)return;let n=t.data.data;return{_id_:n.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...n}}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Rule name is required for create`);let n=await this.client.dispatch(`system:policies:rule:create`,{arguments:{name:t},payload:e.data});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async update(e){let t=e.options;if(!t)throw Error(`Rule name is required for update`);let n=await this.client.dispatch(`system:policies:rule:update`,{arguments:{name:t},payload:e.data});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async delete(e){await this.client.dispatch(`system:policies:rule:delete`,{arguments:{name:e}})}async validate(e){return(await this.client.dispatch(`system:policies:rule:validate`,{payload:e})).data?.data??{valid:!1}}async reload(){return(await this.client.dispatch(`system:policies:reload`)).data.data}async upload(e){throw Error(`Upload not supported for rules`)}async subscribe(e,t){throw Error(`Subscription not supported for rules`)}async notify(e){throw Error(`Notify not supported for rules`)}stream(e,t){throw Error(`Stream not supported for rules`)}page(e){throw Error(`Pagination not supported for rules`)}},w=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=g(`_audit_log_`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/audit/log/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){throw Error(`Read by ID not supported for audit logs; use find with filters`)}async create(e){throw Error(`Audit logs are write-only; entries are created by the system`)}async update(e){throw Error(`Audit logs are append-only; updates are not allowed`)}async delete(e){throw Error(`Audit logs are append-only; deletion is not allowed`)}async upload(e){throw Error(`Upload not supported for audit logs`)}async subscribe(e,t){throw Error(`Use stream() for real-time audit log entries`)}async notify(e){throw Error(`Notify not supported for audit logs`)}stream(e,t){let n=this.getStreamUrl(),r=null,i=`active`,a=null,o=async function*(){let e=[];r=new EventSource(n,{withCredentials:!0}),r.onmessage=t=>{for(let n of t.data.split(`
8
+ `)){let t=n.trim();if(t)try{let n=JSON.parse(t);n?.data&&e.push(n.data)}catch{}}e.length>0&&a&&(a(),a=null)},r.onerror=()=>{i===`active`&&(i=`completed`),a&&=(a(),null)};try{for(;i===`active`;)e.length>0?yield e.shift():await new Promise(t=>{a=t,e.length>0&&(t(),a=null)})}finally{r?.close(),a&&=(a(),null),i===`active`&&(i=`completed`)}};return{stream:()=>o(),cancel:()=>{i===`active`&&(i=`cancelled`,r?.close())},status:()=>i}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}};function T(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function E(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var D=class{client;ns;pagerOptions={};pager;prefixFilter=``;constructor(e,t){this.client=e,this.ns=t,this.pager=g(`blobs_${t}`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}async find(e){let t=this.prefixFilter||e?.prefix||``,n=e?.limit??e?.pagination?.limit??0,r={};t&&(r.prefix=t),n&&(r.limit=n);let i=(await this.client.dispatch(`system:blobs:blob:list`,{arguments:{ns:this.ns},payload:r})).data?.data?.blobs??[];return{data:i.map(T),loading:!1,page:E(i),error:void 0}}async read(e){try{let t=await this.client.dispatch(`system:blobs:blob:head`,{arguments:{ns:this.ns,key:e}});return t.data?.data?T(t.data.data):void 0}catch(e){if(e?.code===`NOT_FOUND`)return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob update`);return T((await this.client.dispatch(`system:blobs:blob:update`,{arguments:{ns:this.ns,key:t},payload:{custom:e.data}})).data.data)}async delete(e){await this.client.dispatch(`system:blobs:blob:delete`,{arguments:{ns:this.ns,key:e}})}async list(e){return this.find(e??{})}async upload(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob upload`);let n={},r=e.options?.contentType||e.file.type;return r&&(n[`Content-Type`]=r),T((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},payload:e.file,headers:n,bodyType:`blob`})).data.data)}async subscribe(e,t){throw Error(`Subscription not supported for blobs`)}async notify(e){throw Error(`Notify not supported for blobs`)}stream(e,t){throw Error(`Stream not supported for blobs`)}page(e){return this.pager}async download(e){let t=(await this.client.dispatch(`system:blobs:blob:download`,{arguments:{ns:this.ns,key:e},responseType:`blob`})).data;return{data:t,contentType:t.type}}},O=class{client;apiPrefix;constructor(e,t=`/api`){this.client=e,this.apiPrefix=t}async namespaces(){return(await this.client.dispatch(`system:blobs:namespace:list`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.dispatch(`system:blobs:namespace:create`,{payload:e})).data.data}async deleteNamespace(e){await this.client.dispatch(`system:blobs:namespace:delete`,{arguments:{ns:e}})}blob(e,t){return`${this.client.base()}${this.apiPrefix}/system/blobs/blob/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}namespace(e){return new D(this.client,e)}},k=class{client;constructor(e){this.client=e}async find(e){let t=((await this.client.dispatch(`system:collections:collection:list`)).data?.data??[]).map(e=>({_id_:e.name,_metadata_:{checksum:``,created:e.created,updated:e.updated,version:1},name:e.name,schema:e.schema,created:e.created,updated:e.updated}));return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){try{let t=await this.client.dispatch(`system:collections:collection:get`,{arguments:{name:e}});if(!t.data)return;let n=t.data.data;return{_id_:n.name,_metadata_:{checksum:``,created:n.created,updated:n.updated,version:1},name:n.name,schema:n.schema,created:n.created,updated:n.updated}}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){return(await this.client.dispatch(`system:collections:collection:create`,{payload:e.data})).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.dispatch(`system:collections:collection:delete`,{arguments:{name:e}})}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not supported for collections`)}async notify(e){throw Error(`Notify not supported for collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){throw Error(`Pagination not supported for collection metadata; use documents(name)`)}documents(e){return new _(this.client,e)}},A=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:core:docs:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){throw Error(`Read by ID not supported for capabilities; use find()`)}async create(e){throw Error(`Capabilities are read-only`)}async update(e){throw Error(`Capabilities are read-only`)}async delete(e){throw Error(`Capabilities are read-only`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for capabilities`)}async subscribe(e,t){throw Error(`Subscription not supported for capabilities`)}async notify(e){throw Error(`Notify not supported for capabilities`)}stream(e,t){throw Error(`Stream not supported for capabilities`)}page(e){throw Error(`Pagination not supported for capabilities`)}},j=class{store;client;auth;users;keys;policies;rules;logs;collections;blobs;capabilities;tokenProvider;onAuthStateChanged;constructor(e){this.store=new r.ReactiveDataStore({identity:null},e.persistence);let t={identity:()=>this.store.get().identity,setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({identity:null})},n=e.apiPrefix??`/api`;this.tokenProvider=t,this.client=e.transport??new d(e.baseUrl,n,t,()=>this.onAuthStateChanged?.()),this.auth=new v(this.client,t),this.users=new y(this.client),this.keys=new b(this.client),this.policies=new S(this.client),this.rules=new C(this.client),this.logs=new w(this.client,e.baseUrl,n),this.collections=new k(this.client),this.blobs=new O(this.client,n),this.capabilities=new A(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}authenticated(){return this.tokenProvider.identity()!==null}collection(e){return this.collections.documents(e)}ready(){return this.client.ready()}};function M(e){let t=`${e.collectionName}_array_pager_state_`,n=new r.ReactiveDataStore({}),a=[...e.initialData??[]],o=`collection`,s,c=e.page??1,l=e.size??20,u=[],d,f,{match:p}=(0,i.createMatcher)(e.customFunctions??{}),{sort:m}=(0,i.createSorter)(),h=n.select(e=>e[t]),g={data:[],loading:!0,error:void 0,page:{number:1,size:l,count:0,total:0,pages:1}},_=()=>({filters:d,sort:u,pagination:{type:`offset`,offset:(c-1)*l,limit:l}}),v=async(r=!0)=>{if(e.fetch){if(f=void 0,r){let e=h.get()??g;await n.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=_(),n=await e.fetch(t);o=n.scope,s=n.total,a=n.replace?[...n.data]:[...a,...n.data]}catch(e){f=e}}let i=y(e.fetch?r:!1);await n.set({[t]:i})},y=e=>{let t=[...a];if(o===`collection`){d&&(t=t.filter(e=>p(e,d))),u.length>0&&(t=m(t,u));let n=t.length,r=Math.ceil(n/l)||1;c>r&&(c=r),c<1&&(c=1);let i=(c-1)*l,a=t.slice(i,i+l);return{data:a,loading:e,error:f,page:{number:c,size:l,count:a.length,total:n,pages:r}}}let n=s??t.length,r=Math.ceil(n/l)||1;return{data:t,loading:e,error:f,page:{number:c,size:l,count:t.length,total:n,pages:r}}};return v(!0),{id:()=>t,page:()=>h.get()??g,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);c=e,await v(!0)},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);l=e,c=t,await v(!0)},sort:async e=>{u=Array.isArray(e)?e:[e],c=1,await v(!0)},filter:async e=>{d=e,c=1,await v(!0)},refresh:async e=>{let r=h.get()??g;await n.set({[t]:{...r,loading:!0}});let i=e?.delay??600;await Promise.all([new Promise(e=>setTimeout(e,i)),v(!1)]);let a=h.get()??g;await n.set({[t]:{...a,loading:!1}})},subscribe:e=>h.subscribe(t=>{e(t)}),invalidate:async()=>{await n.set({[t]:r.DELETE_SYMBOL}),a=[]}}}exports.BlobNamespace=D,exports.HestiaAuth=v,exports.HestiaBlobClient=O,exports.HestiaClient=j,exports.HestiaCollection=_,exports.HestiaCollections=k,exports.HestiaKeyStore=b,exports.HestiaLogs=w,exports.HestiaNetworkClient=f,exports.HestiaOperations=x,exports.HestiaPolicies=S,exports.HestiaResponse=u,exports.HestiaRules=C,exports.HestiaUsers=y,exports.HttpTransport=d,exports.WailsTransport=m,exports.createArrayPager=M,exports.createPagedController=g,exports.internalError=l,exports.notFound=s,exports.parseErrorBody=a,exports.permissionDenied=c,exports.toSystemError=o;
package/index.d.cts CHANGED
@@ -3,6 +3,7 @@ import { ApiResponse } from "@asaidimu/network-client";
3
3
  import { Issue, SystemError } from "@asaidimu/utils-error";
4
4
  import { DataStore, ReactiveDataStore } from "@asaidimu/utils-store";
5
5
  import { SchemaDefinition } from "@asaidimu/utils-schema";
6
+ import { SimplePersistence } from "@asaidimu/utils-persistence";
6
7
  //#region core/types.d.ts
7
8
  interface DocumentMetadata$1 {
8
9
  checksum: string;
@@ -272,7 +273,7 @@ declare class HestiaResponse<T> {
272
273
  }
273
274
  type BodyType$1 = "json" | "form" | "text" | "blob" | "stream" | "auto";
274
275
  type ResponseType$1 = "json" | "text" | "blob" | "arrayBuffer" | "formData" | "auto";
275
- interface RequestOptions$1 {
276
+ interface RequestOptions {
276
277
  headers?: Record<string, string>;
277
278
  responseType?: ResponseType$1;
278
279
  bodyType?: BodyType$1;
@@ -288,7 +289,29 @@ interface StreamOptions {
288
289
  headers?: Record<string, string>;
289
290
  signal?: AbortSignal;
290
291
  }
291
- declare class HestiaNetworkClient {
292
+ interface DispatchInput {
293
+ arguments?: Record<string, string>;
294
+ modifiers?: Record<string, string | string[]>;
295
+ payload?: unknown;
296
+ headers?: Record<string, string>;
297
+ responseType?: ResponseType$1;
298
+ bodyType?: BodyType$1;
299
+ signal?: AbortSignal;
300
+ }
301
+ interface Transport {
302
+ base(): string;
303
+ prefix(): string;
304
+ ready(): Promise<void>;
305
+ dispatch<T>(name: string, input?: DispatchInput): Promise<HestiaResponse<T>>;
306
+ get<T>(path: string, options?: RequestOptions): Promise<HestiaResponse<T>>;
307
+ post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
308
+ patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
309
+ put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
310
+ delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
311
+ check<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
312
+ openStream(path: string, handlers: StreamHandlers, options?: StreamOptions): Promise<void>;
313
+ }
314
+ declare class HttpTransport implements Transport {
292
315
  private baseUrl;
293
316
  private apiPrefix;
294
317
  private provider;
@@ -296,26 +319,69 @@ declare class HestiaNetworkClient {
296
319
  private raw;
297
320
  private heartbeatTimer?;
298
321
  private defaultHeartbeatInterval;
322
+ private routeCache;
299
323
  constructor(baseUrl: string, apiPrefix: string, provider: IdentityProvider, onAuthStateChanged?: (() => void) | undefined);
324
+ private getRouteCache;
325
+ private substituteArgs;
326
+ dispatch<T>(name: string, input?: DispatchInput): Promise<HestiaResponse<T>>;
300
327
  base(): string;
301
328
  prefix(): string;
302
- /** Start periodic heartbeat to keep the session alive.
303
- * Sends a lightweight GET to the health-check endpoint at the given
304
- * interval (default 5 min). The server's sliding-window refresh logic
305
- * renews the session cookie automatically. */
329
+ ready(): Promise<void>;
306
330
  startHeartbeat(intervalMs?: number): void;
307
331
  stopHeartbeat(): void;
308
332
  private heartbeat;
309
333
  private canonicalPath;
310
334
  private request;
311
- check<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse<T>>;
312
- get<T>(path: string, options?: RequestOptions$1): Promise<HestiaResponse<T>>;
313
- post<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse<T>>;
314
- patch<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse<T>>;
315
- put<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse<T>>;
316
- delete<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse<T>>;
335
+ check<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
336
+ get<T>(path: string, options?: RequestOptions): Promise<HestiaResponse<T>>;
337
+ post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
338
+ patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
339
+ put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
340
+ delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
317
341
  openStream(path: string, handlers: StreamHandlers, options?: StreamOptions): Promise<void>;
318
342
  }
343
+ declare const HestiaNetworkClient: typeof HttpTransport;
344
+ type HestiaNetworkClient = HttpTransport;
345
+ //#endregion
346
+ //#region core/wails-transport.d.ts
347
+ declare global {
348
+ interface Window {
349
+ go?: Record<string, Record<string, Record<string, (...args: unknown[]) => Promise<unknown>>>>;
350
+ runtime?: {
351
+ Call: (method: string, ...args: unknown[]) => Promise<unknown>;
352
+ EventsOn: (event: string, callback: (...args: unknown[]) => void) => void;
353
+ EventsOff: (event: string) => void;
354
+ };
355
+ }
356
+ }
357
+ interface WailsTransportConfig {
358
+ pkg: string;
359
+ struct: string;
360
+ }
361
+ declare class WailsTransport implements Transport {
362
+ private baseUrl;
363
+ private apiPrefix;
364
+ private init;
365
+ private config?;
366
+ constructor(config?: WailsTransportConfig);
367
+ private resolveService;
368
+ base(): string;
369
+ prefix(): string;
370
+ /**
371
+ * Polls window.go until Wails bindings are available.
372
+ * Concurrent callers share the single initialization attempt.
373
+ */
374
+ ready(timeoutMs?: number): Promise<void>;
375
+ dispatch<T>(name: string, input?: DispatchInput): Promise<HestiaResponse<T>>;
376
+ check<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
377
+ get<T>(path: string, options?: RequestOptions): Promise<HestiaResponse<T>>;
378
+ post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
379
+ patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
380
+ put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
381
+ delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
382
+ private request;
383
+ openStream(path: string, handlers: StreamHandlers, _options?: StreamOptions): Promise<void>;
384
+ }
319
385
  //#endregion
320
386
  //#region core/collection.d.ts
321
387
  declare class HestiaCollection<T extends Record<string, any>> implements DocumentStore<T, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
@@ -324,11 +390,8 @@ declare class HestiaCollection<T extends Record<string, any>> implements Documen
324
390
  private defaultLimit;
325
391
  private pagerOptions;
326
392
  private pager;
327
- constructor(client: HestiaNetworkClient, collectionName: string, defaultLimit?: number);
393
+ constructor(client: Transport, collectionName: string, defaultLimit?: number);
328
394
  name(): string;
329
- private get queryPath();
330
- private get documentsPath();
331
- private documentPath;
332
395
  find(query?: Record<string, unknown>): Promise<Page<T>>;
333
396
  read(id: string): Promise<Document<T> | undefined>;
334
397
  create(props: {
@@ -402,7 +465,7 @@ interface BootstrapPasswordRequest {
402
465
  declare class HestiaAuth {
403
466
  private client;
404
467
  private provider;
405
- constructor(client: HestiaNetworkClient, provider: IdentityProvider);
468
+ constructor(client: Transport, provider: IdentityProvider);
406
469
  health(): Promise<ServerHealth>;
407
470
  login(email: string, password: string): Promise<LoginResult>;
408
471
  register(email: string, password: string, name: string): Promise<{
@@ -421,7 +484,7 @@ declare class HestiaUsers implements DocumentStore<UserData, QueryDSL<UserData>,
421
484
  private client;
422
485
  private pagerOptions;
423
486
  private pager;
424
- constructor(client: HestiaNetworkClient);
487
+ constructor(client: Transport);
425
488
  name(): string;
426
489
  find(query?: QueryDSL<UserData>): Promise<Page<UserData>>;
427
490
  list(options?: QueryDSL<UserData>): Promise<Page<UserData>>;
@@ -431,7 +494,7 @@ declare class HestiaUsers implements DocumentStore<UserData, QueryDSL<UserData>,
431
494
  options?: string;
432
495
  }): Promise<Document<UserData> | undefined>;
433
496
  delete(id: string): Promise<void>;
434
- create(props: {
497
+ create(_props: {
435
498
  data: Partial<UserData>;
436
499
  }): Promise<Document<UserData> | undefined>;
437
500
  upload(_props: {
@@ -482,8 +545,7 @@ interface UpdateKeyRequest {
482
545
  declare class HestiaKeyStore implements DocumentStore<APIKey, QueryDSL<APIKey>, string, QueryDSL<APIKey>, Record<string, unknown>, string, string, Record<string, unknown>> {
483
546
  private client;
484
547
  private pager;
485
- constructor(client: HestiaNetworkClient);
486
- private basePath;
548
+ constructor(client: Transport);
487
549
  find(_query?: QueryDSL<APIKey>): Promise<Page<APIKey>>;
488
550
  list(options?: QueryDSL<APIKey>): Promise<Page<APIKey>>;
489
551
  read(id: string): Promise<Document<APIKey> | undefined>;
@@ -519,7 +581,7 @@ interface Operation {
519
581
  //#region system/operations/store.d.ts
520
582
  declare class HestiaOperations {
521
583
  private client;
522
- constructor(client: HestiaNetworkClient);
584
+ constructor(client: Transport);
523
585
  list(): Promise<Page<Operation>>;
524
586
  read(name: string): Promise<Document<Operation> | undefined>;
525
587
  }
@@ -546,7 +608,7 @@ interface SetPolicyEnabledRequest {
546
608
  declare class HestiaPolicies implements DocumentStore<Policy, QueryDSL<Policy>, string, QueryDSL<Policy>, Record<string, unknown>, string, string, Record<string, unknown>> {
547
609
  private client;
548
610
  private pager;
549
- constructor(client: HestiaNetworkClient);
611
+ constructor(client: Transport);
550
612
  find(_query?: QueryDSL<Policy>): Promise<Page<Policy>>;
551
613
  query(qdsl: Record<string, unknown>): Promise<Page<Policy>>;
552
614
  list(_options?: QueryDSL<Policy>): Promise<Page<Policy>>;
@@ -608,14 +670,17 @@ interface RuleNode {
608
670
  conditions?: RuleNode[];
609
671
  }
610
672
  interface ValidateRuleRequest {
611
- expression: string;
612
- identity?: Record<string, unknown>;
613
- resource?: Record<string, unknown>;
614
- environment?: Record<string, unknown>;
673
+ rule: string | RuleNode;
674
+ context?: {
675
+ identity?: Record<string, unknown>;
676
+ resource?: Record<string, unknown>;
677
+ environment?: Record<string, unknown>;
678
+ };
615
679
  }
616
680
  interface ValidateRuleResult {
617
681
  valid: boolean;
618
682
  result?: boolean;
683
+ error?: string;
619
684
  }
620
685
  interface ReloadResult {
621
686
  operations: number;
@@ -625,7 +690,7 @@ interface ReloadResult {
625
690
  //#region system/rules/store.d.ts
626
691
  declare class HestiaRules implements DocumentStore<PolicyRule, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
627
692
  private client;
628
- constructor(client: HestiaNetworkClient);
693
+ constructor(client: Transport);
629
694
  find(_query?: Record<string, unknown>): Promise<Page<PolicyRule>>;
630
695
  list(_options?: Record<string, unknown>): Promise<Page<PolicyRule>>;
631
696
  read(id: string): Promise<Document<PolicyRule> | undefined>;
@@ -698,7 +763,7 @@ declare class HestiaLogs implements DocumentStore<AuditEntry, QueryDSL<AuditEntr
698
763
  private pagerOptions;
699
764
  private pager;
700
765
  private apiPrefix;
701
- constructor(client: HestiaNetworkClient, baseUrl: string, apiPrefix?: string);
766
+ constructor(client: Transport, baseUrl: string, apiPrefix?: string);
702
767
  find(query?: QueryDSL<AuditEntry>): Promise<Page<AuditEntry>>;
703
768
  list(options?: QueryDSL<AuditEntry>): Promise<Page<AuditEntry>>;
704
769
  read(_id: string): Promise<Document<AuditEntry> | undefined>;
@@ -758,10 +823,9 @@ declare class BlobNamespace implements DocumentStore<BlobMeta, QueryDSL<BlobMeta
758
823
  private pagerOptions;
759
824
  private pager;
760
825
  private prefixFilter;
761
- constructor(client: HestiaNetworkClient, ns: string);
826
+ constructor(client: Transport, ns: string);
762
827
  name(): string;
763
828
  setPrefix(prefix: string): void;
764
- private basePath;
765
829
  find(query?: QueryDSL<BlobMeta>): Promise<Page<BlobMeta>>;
766
830
  read(key: string): Promise<Document<BlobMeta> | undefined>;
767
831
  create(_props: {
@@ -796,8 +860,7 @@ declare class BlobNamespace implements DocumentStore<BlobMeta, QueryDSL<BlobMeta
796
860
  declare class HestiaBlobClient {
797
861
  private client;
798
862
  private apiPrefix;
799
- constructor(client: HestiaNetworkClient, apiPrefix?: string);
800
- private nsBase;
863
+ constructor(client: Transport, apiPrefix?: string);
801
864
  namespaces(): Promise<NamespaceInfo[]>;
802
865
  createNamespace(data: CreateNamespaceRequest): Promise<NamespaceInfo>;
803
866
  deleteNamespace(ns: string): Promise<void>;
@@ -819,7 +882,7 @@ type CollectionDocument = Document<{
819
882
  //#region collections/store.d.ts
820
883
  declare class HestiaCollections implements DocumentStore<CollectionMeta, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
821
884
  private client;
822
- constructor(client: HestiaNetworkClient);
885
+ constructor(client: Transport);
823
886
  find(_query?: Record<string, unknown>): Promise<Page<CollectionMeta>>;
824
887
  read(name: string): Promise<Document<CollectionMeta> | undefined>;
825
888
  create(props: {
@@ -1074,23 +1137,6 @@ interface DocumentStore$1<T extends Record<string, any>, TFindOptions = Record<s
1074
1137
  */
1075
1138
  page(options: TPageOptions): PagedData$1<T>;
1076
1139
  }
1077
- //#endregion
1078
- //#region system/identity/types.d.ts
1079
- interface UserData$1 {
1080
- email: string;
1081
- name: string;
1082
- verified: boolean;
1083
- permissions: string[];
1084
- deleted?: string | null;
1085
- }
1086
- type UserIdentity$1 = Document$1<UserData$1>;
1087
- //#endregion
1088
- //#region core/client.d.ts
1089
- interface IdentityProvider$1 {
1090
- identity(): UserIdentity$1 | null;
1091
- setIdentity(id: UserIdentity$1 | null): Promise<void>;
1092
- clear(): Promise<void>;
1093
- }
1094
1140
  declare class HestiaResponse$1<T> {
1095
1141
  readonly data: T;
1096
1142
  readonly status: number;
@@ -1098,7 +1144,7 @@ declare class HestiaResponse$1<T> {
1098
1144
  }
1099
1145
  type BodyType = "json" | "form" | "text" | "blob" | "stream" | "auto";
1100
1146
  type ResponseType = "json" | "text" | "blob" | "arrayBuffer" | "formData" | "auto";
1101
- interface RequestOptions {
1147
+ interface RequestOptions$1 {
1102
1148
  headers?: Record<string, string>;
1103
1149
  responseType?: ResponseType;
1104
1150
  bodyType?: BodyType;
@@ -1114,35 +1160,41 @@ interface StreamOptions$1 {
1114
1160
  headers?: Record<string, string>;
1115
1161
  signal?: AbortSignal;
1116
1162
  }
1117
- declare class HestiaNetworkClient$1 {
1118
- private baseUrl;
1119
- private apiPrefix;
1120
- private provider;
1121
- private onAuthStateChanged?;
1122
- private raw;
1123
- private heartbeatTimer?;
1124
- private defaultHeartbeatInterval;
1125
- constructor(baseUrl: string, apiPrefix: string, provider: IdentityProvider$1, onAuthStateChanged?: (() => void) | undefined);
1163
+ interface DispatchInput$1 {
1164
+ arguments?: Record<string, string>;
1165
+ modifiers?: Record<string, string | string[]>;
1166
+ payload?: unknown;
1167
+ headers?: Record<string, string>;
1168
+ responseType?: ResponseType;
1169
+ bodyType?: BodyType;
1170
+ signal?: AbortSignal;
1171
+ }
1172
+ interface Transport$1 {
1126
1173
  base(): string;
1127
1174
  prefix(): string;
1128
- /** Start periodic heartbeat to keep the session alive.
1129
- * Sends a lightweight GET to the health-check endpoint at the given
1130
- * interval (default 5 min). The server's sliding-window refresh logic
1131
- * renews the session cookie automatically. */
1132
- startHeartbeat(intervalMs?: number): void;
1133
- stopHeartbeat(): void;
1134
- private heartbeat;
1135
- private canonicalPath;
1136
- private request;
1137
- check<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse$1<T>>;
1138
- get<T>(path: string, options?: RequestOptions): Promise<HestiaResponse$1<T>>;
1139
- post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse$1<T>>;
1140
- patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse$1<T>>;
1141
- put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse$1<T>>;
1142
- delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse$1<T>>;
1175
+ ready(): Promise<void>;
1176
+ dispatch<T>(name: string, input?: DispatchInput$1): Promise<HestiaResponse$1<T>>;
1177
+ get<T>(path: string, options?: RequestOptions$1): Promise<HestiaResponse$1<T>>;
1178
+ post<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse$1<T>>;
1179
+ patch<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse$1<T>>;
1180
+ put<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse$1<T>>;
1181
+ delete<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse$1<T>>;
1182
+ check<T>(path: string, body?: unknown, options?: RequestOptions$1): Promise<HestiaResponse$1<T>>;
1143
1183
  openStream(path: string, handlers: StreamHandlers$1, options?: StreamOptions$1): Promise<void>;
1144
1184
  }
1145
1185
  //#endregion
1186
+ //#region core/wails-transport.d.ts
1187
+ declare global {
1188
+ interface Window {
1189
+ go?: Record<string, Record<string, Record<string, (...args: unknown[]) => Promise<unknown>>>>;
1190
+ runtime?: {
1191
+ Call: (method: string, ...args: unknown[]) => Promise<unknown>;
1192
+ EventsOn: (event: string, callback: (...args: unknown[]) => void) => void;
1193
+ EventsOff: (event: string) => void;
1194
+ };
1195
+ }
1196
+ }
1197
+ //#endregion
1146
1198
  //#region core/collection.d.ts
1147
1199
  declare class HestiaCollection$1<T extends Record<string, any>> implements DocumentStore$1<T, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
1148
1200
  private client;
@@ -1150,11 +1202,8 @@ declare class HestiaCollection$1<T extends Record<string, any>> implements Docum
1150
1202
  private defaultLimit;
1151
1203
  private pagerOptions;
1152
1204
  private pager;
1153
- constructor(client: HestiaNetworkClient$1, collectionName: string, defaultLimit?: number);
1205
+ constructor(client: Transport$1, collectionName: string, defaultLimit?: number);
1154
1206
  name(): string;
1155
- private get queryPath();
1156
- private get documentsPath();
1157
- private documentPath;
1158
1207
  find(query?: Record<string, unknown>): Promise<Page$1<T>>;
1159
1208
  read(id: string): Promise<Document$1<T> | undefined>;
1160
1209
  create(props: {
@@ -1179,65 +1228,10 @@ declare class HestiaCollection$1<T extends Record<string, any>> implements Docum
1179
1228
  page(_options?: Record<string, unknown>): PagedData$1<T>;
1180
1229
  }
1181
1230
  //#endregion
1182
- //#region node_modules/@asaidimu/utils-persistence/index.d.ts
1183
- interface SimplePersistence<T> {
1184
- /**
1185
- * Persists data to storage.
1186
- *
1187
- * @param id The **unique identifier of the *consumer instance*** making the change. This is NOT the ID of the data (`T`) itself.
1188
- * Think of it as the ID of the specific browser tab, component, or module that's currently interacting with the persistence layer.
1189
- * It should typically be a **UUID** generated once at the consumer instance's instantiation.
1190
- * This `id` is crucial for the `subscribe` method, helping to differentiate updates originating from the current instance versus other instances/tabs, thereby preventing self-triggered notification loops.
1191
- * @param state The state (of type T) to persist. This state is generally considered the **global or shared state** that all instances interact with.
1192
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations (like `IndexedDBPersistence`), this returns a `Promise<boolean>`.
1193
- */
1194
- set(id: string, state: T): boolean | Promise<boolean>;
1195
- /**
1196
- * Retrieves the global persisted data from storage.
1197
- *
1198
- * @returns The retrieved state of type `T`, or `null` if no data is found or if an error occurs during retrieval/parsing.
1199
- * For asynchronous implementations, this returns a `Promise<T | null>`.
1200
- */
1201
- get(): (T | null) | Promise<T | null>;
1202
- /**
1203
- * Subscribes to changes in the global persisted data that originate from *other* instances of your application (e.g., other tabs or independent components using the same persistence layer).
1204
- *
1205
- * @param id The **unique identifier of the *consumer instance* subscribing**. This allows the persistence implementation to filter out notifications that were initiated by the subscribing instance itself.
1206
- * @param callback The function to call when the global persisted data changes from *another* source. The new state (`T`) is passed as an argument to this callback.
1207
- * @returns A function that, when called, will unsubscribe the provided callback from future updates. Call this when your component or instance is no longer active to prevent memory leaks.
1208
- */
1209
- subscribe(id: string, callback: (state: T) => void): () => void;
1210
- /**
1211
- * Clears (removes) the entire global persisted data from storage.
1212
- *
1213
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations, this returns a `Promise<boolean>`.
1214
- */
1215
- clear(): boolean | Promise<boolean>;
1216
- /**
1217
- * Returns metadata about the persistence layer.
1218
- *
1219
- * This is useful for distinguishing between multiple apps running on the same host
1220
- * (e.g., several apps served at `localhost:3000` that share the same storage key).
1221
- *
1222
- * @returns An object containing:
1223
- * - `version`: The semantic version string of the persistence schema or application.
1224
- * - `id`: A unique identifier for the application using this persistence instance.
1225
- */
1226
- stats(): {
1227
- version: string;
1228
- id: string;
1229
- };
1230
- /**
1231
- * Closes the persistence instance, releasing the file watcher.
1232
- * Call this when shutting down to clean up resources.
1233
- */
1234
- close?: () => Promise<void>;
1235
- }
1236
- //#endregion
1237
1231
  //#region system/capabilities/store.d.ts
1238
1232
  declare class HestiaCapabilities implements DocumentStore<any, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
1239
1233
  private client;
1240
- constructor(client: HestiaNetworkClient);
1234
+ constructor(client: Transport);
1241
1235
  find(_query?: Record<string, unknown>): Promise<Page<any>>;
1242
1236
  read(_id: string): Promise<Document<any> | undefined>;
1243
1237
  create(_props: {
@@ -1267,13 +1261,14 @@ interface HestiaConfig {
1267
1261
  baseUrl: string;
1268
1262
  apiPrefix?: string;
1269
1263
  persistence?: SimplePersistence<AuthState>;
1264
+ transport?: Transport;
1270
1265
  }
1271
1266
  interface AuthState {
1272
1267
  identity: UserIdentity | null;
1273
1268
  }
1274
1269
  declare class HestiaClient {
1275
1270
  readonly store: ReactiveDataStore<AuthState>;
1276
- readonly client: HestiaNetworkClient;
1271
+ readonly client: Transport;
1277
1272
  readonly auth: HestiaAuth;
1278
1273
  readonly users: HestiaUsers;
1279
1274
  readonly keys: HestiaKeyStore;
@@ -1289,6 +1284,7 @@ declare class HestiaClient {
1289
1284
  onAuthStateChange(callback: () => void): void;
1290
1285
  authenticated(): boolean;
1291
1286
  collection<T extends Record<string, any>>(name: string): HestiaCollection$1<T>;
1287
+ ready(): Promise<void>;
1292
1288
  }
1293
1289
  //#endregion
1294
1290
  //#region utils/pager.d.ts
@@ -1308,4 +1304,4 @@ interface ArrayPagerOptions<T extends Record<string, any>, F = any> {
1308
1304
  }
1309
1305
  declare function createArrayPager<T extends Record<string, any>, F = any>(options: ArrayPagerOptions<T, F>): PagedData<T>;
1310
1306
  //#endregion
1311
- export { APIKey, APIKeyWithSecret, ArrayPagerOptions, AuditEntry, BlobDocument, BlobMeta, BlobNamespace, BootstrapPasswordRequest, ChangePasswordRequest, CollectionDocument, CollectionMeta, CreateKeyRequest, CreateNamespaceRequest, CreatePolicyRequest, CreateRuleRequest, CreateUserRequest, Document, DocumentStore, FetchResult, HestiaAuth, HestiaBlobClient, HestiaClient, HestiaCollection, HestiaCollections, HestiaKeyStore, HestiaLogs, HestiaNetworkClient, HestiaOperations, HestiaPolicies, HestiaResponse, HestiaRules, HestiaUsers, IdentityProvider, ListBlobsRequest, LogFilter, LoginRequest, LoginResult, NamespaceInfo, Operation, Page, PagedData, PagerRefreshOptions, PaginationInfo, Policy, PolicyRule, RegisterRequest, ReloadResult, RequestLogEntry, RuleNode, ServerHealth, SetPolicyEnabledRequest, StoreEvent, StreamHandlers, StreamOptions, UpdateKeyRequest, UpdatePolicyRuleRequest, UpdateRuleRequest, UpdateUserRequest, UserData, UserIdentity, ValidateRuleRequest, ValidateRuleResult, createArrayPager, createPagedController, internalError, notFound, parseErrorBody, permissionDenied, toSystemError };
1307
+ export { APIKey, APIKeyWithSecret, ArrayPagerOptions, AuditEntry, BlobDocument, BlobMeta, BlobNamespace, BootstrapPasswordRequest, ChangePasswordRequest, CollectionDocument, CollectionMeta, CreateKeyRequest, CreateNamespaceRequest, CreatePolicyRequest, CreateRuleRequest, CreateUserRequest, DispatchInput, Document, DocumentStore, FetchResult, HestiaAuth, HestiaBlobClient, HestiaClient, HestiaCollection, HestiaCollections, HestiaKeyStore, HestiaLogs, HestiaNetworkClient, HestiaOperations, HestiaPolicies, HestiaResponse, HestiaRules, HestiaUsers, HttpTransport, IdentityProvider, ListBlobsRequest, LogFilter, LoginRequest, LoginResult, NamespaceInfo, Operation, Page, PagedData, PagerRefreshOptions, PaginationInfo, Policy, PolicyRule, RegisterRequest, ReloadResult, RequestLogEntry, RequestOptions, RuleNode, ServerHealth, SetPolicyEnabledRequest, StoreEvent, StreamHandlers, StreamOptions, Transport, UpdateKeyRequest, UpdatePolicyRuleRequest, UpdateRuleRequest, UpdateUserRequest, UserData, UserIdentity, ValidateRuleRequest, ValidateRuleResult, WailsTransport, createArrayPager, createPagedController, internalError, notFound, parseErrorBody, permissionDenied, toSystemError };
package/index.d.mts CHANGED
@@ -3,6 +3,7 @@ import { Issue, SystemError } from "@asaidimu/utils-error";
3
3
  import { DataStore, ReactiveDataStore } from "@asaidimu/utils-store";
4
4
  import { QueryDSL, QueryFilter, SortConfiguration } from "@asaidimu/query";
5
5
  import { SchemaDefinition } from "@asaidimu/utils-schema";
6
+ import { SimplePersistence } from "@asaidimu/utils-persistence";
6
7
  //#region core/types.d.ts
7
8
  interface DocumentMetadata {
8
9
  checksum: string;
@@ -288,7 +289,29 @@ interface StreamOptions {
288
289
  headers?: Record<string, string>;
289
290
  signal?: AbortSignal;
290
291
  }
291
- declare class HestiaNetworkClient {
292
+ interface DispatchInput {
293
+ arguments?: Record<string, string>;
294
+ modifiers?: Record<string, string | string[]>;
295
+ payload?: unknown;
296
+ headers?: Record<string, string>;
297
+ responseType?: ResponseType;
298
+ bodyType?: BodyType;
299
+ signal?: AbortSignal;
300
+ }
301
+ interface Transport {
302
+ base(): string;
303
+ prefix(): string;
304
+ ready(): Promise<void>;
305
+ dispatch<T>(name: string, input?: DispatchInput): Promise<HestiaResponse<T>>;
306
+ get<T>(path: string, options?: RequestOptions): Promise<HestiaResponse<T>>;
307
+ post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
308
+ patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
309
+ put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
310
+ delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
311
+ check<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
312
+ openStream(path: string, handlers: StreamHandlers, options?: StreamOptions): Promise<void>;
313
+ }
314
+ declare class HttpTransport implements Transport {
292
315
  private baseUrl;
293
316
  private apiPrefix;
294
317
  private provider;
@@ -296,13 +319,14 @@ declare class HestiaNetworkClient {
296
319
  private raw;
297
320
  private heartbeatTimer?;
298
321
  private defaultHeartbeatInterval;
322
+ private routeCache;
299
323
  constructor(baseUrl: string, apiPrefix: string, provider: IdentityProvider, onAuthStateChanged?: (() => void) | undefined);
324
+ private getRouteCache;
325
+ private substituteArgs;
326
+ dispatch<T>(name: string, input?: DispatchInput): Promise<HestiaResponse<T>>;
300
327
  base(): string;
301
328
  prefix(): string;
302
- /** Start periodic heartbeat to keep the session alive.
303
- * Sends a lightweight GET to the health-check endpoint at the given
304
- * interval (default 5 min). The server's sliding-window refresh logic
305
- * renews the session cookie automatically. */
329
+ ready(): Promise<void>;
306
330
  startHeartbeat(intervalMs?: number): void;
307
331
  stopHeartbeat(): void;
308
332
  private heartbeat;
@@ -316,6 +340,48 @@ declare class HestiaNetworkClient {
316
340
  delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
317
341
  openStream(path: string, handlers: StreamHandlers, options?: StreamOptions): Promise<void>;
318
342
  }
343
+ declare const HestiaNetworkClient: typeof HttpTransport;
344
+ type HestiaNetworkClient = HttpTransport;
345
+ //#endregion
346
+ //#region core/wails-transport.d.ts
347
+ declare global {
348
+ interface Window {
349
+ go?: Record<string, Record<string, Record<string, (...args: unknown[]) => Promise<unknown>>>>;
350
+ runtime?: {
351
+ Call: (method: string, ...args: unknown[]) => Promise<unknown>;
352
+ EventsOn: (event: string, callback: (...args: unknown[]) => void) => void;
353
+ EventsOff: (event: string) => void;
354
+ };
355
+ }
356
+ }
357
+ interface WailsTransportConfig {
358
+ pkg: string;
359
+ struct: string;
360
+ }
361
+ declare class WailsTransport implements Transport {
362
+ private baseUrl;
363
+ private apiPrefix;
364
+ private init;
365
+ private config?;
366
+ constructor(config?: WailsTransportConfig);
367
+ private resolveService;
368
+ base(): string;
369
+ prefix(): string;
370
+ /**
371
+ * Polls window.go until Wails bindings are available.
372
+ * Concurrent callers share the single initialization attempt.
373
+ */
374
+ ready(timeoutMs?: number): Promise<void>;
375
+ dispatch<T>(name: string, input?: DispatchInput): Promise<HestiaResponse<T>>;
376
+ check<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
377
+ get<T>(path: string, options?: RequestOptions): Promise<HestiaResponse<T>>;
378
+ post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
379
+ patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
380
+ put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
381
+ delete<T>(path: string, body?: unknown, options?: RequestOptions): Promise<HestiaResponse<T>>;
382
+ private request;
383
+ openStream(path: string, handlers: StreamHandlers, _options?: StreamOptions): Promise<void>;
384
+ }
319
385
  //#endregion
320
386
  //#region core/collection.d.ts
321
387
  declare class HestiaCollection<T extends Record<string, any>> implements DocumentStore<T, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
@@ -324,11 +390,8 @@ declare class HestiaCollection<T extends Record<string, any>> implements Documen
324
390
  private defaultLimit;
325
391
  private pagerOptions;
326
392
  private pager;
327
- constructor(client: HestiaNetworkClient, collectionName: string, defaultLimit?: number);
393
+ constructor(client: Transport, collectionName: string, defaultLimit?: number);
328
394
  name(): string;
329
- private get queryPath();
330
- private get documentsPath();
331
- private documentPath;
332
395
  find(query?: Record<string, unknown>): Promise<Page<T>>;
333
396
  read(id: string): Promise<Document<T> | undefined>;
334
397
  create(props: {
@@ -402,7 +465,7 @@ interface BootstrapPasswordRequest {
402
465
  declare class HestiaAuth {
403
466
  private client;
404
467
  private provider;
405
- constructor(client: HestiaNetworkClient, provider: IdentityProvider);
468
+ constructor(client: Transport, provider: IdentityProvider);
406
469
  health(): Promise<ServerHealth>;
407
470
  login(email: string, password: string): Promise<LoginResult>;
408
471
  register(email: string, password: string, name: string): Promise<{
@@ -421,7 +484,7 @@ declare class HestiaUsers implements DocumentStore<UserData, QueryDSL<UserData>,
421
484
  private client;
422
485
  private pagerOptions;
423
486
  private pager;
424
- constructor(client: HestiaNetworkClient);
487
+ constructor(client: Transport);
425
488
  name(): string;
426
489
  find(query?: QueryDSL<UserData>): Promise<Page<UserData>>;
427
490
  list(options?: QueryDSL<UserData>): Promise<Page<UserData>>;
@@ -431,7 +494,7 @@ declare class HestiaUsers implements DocumentStore<UserData, QueryDSL<UserData>,
431
494
  options?: string;
432
495
  }): Promise<Document<UserData> | undefined>;
433
496
  delete(id: string): Promise<void>;
434
- create(props: {
497
+ create(_props: {
435
498
  data: Partial<UserData>;
436
499
  }): Promise<Document<UserData> | undefined>;
437
500
  upload(_props: {
@@ -482,8 +545,7 @@ interface UpdateKeyRequest {
482
545
  declare class HestiaKeyStore implements DocumentStore<APIKey, QueryDSL<APIKey>, string, QueryDSL<APIKey>, Record<string, unknown>, string, string, Record<string, unknown>> {
483
546
  private client;
484
547
  private pager;
485
- constructor(client: HestiaNetworkClient);
486
- private basePath;
548
+ constructor(client: Transport);
487
549
  find(_query?: QueryDSL<APIKey>): Promise<Page<APIKey>>;
488
550
  list(options?: QueryDSL<APIKey>): Promise<Page<APIKey>>;
489
551
  read(id: string): Promise<Document<APIKey> | undefined>;
@@ -519,7 +581,7 @@ interface Operation {
519
581
  //#region system/operations/store.d.ts
520
582
  declare class HestiaOperations {
521
583
  private client;
522
- constructor(client: HestiaNetworkClient);
584
+ constructor(client: Transport);
523
585
  list(): Promise<Page<Operation>>;
524
586
  read(name: string): Promise<Document<Operation> | undefined>;
525
587
  }
@@ -546,7 +608,7 @@ interface SetPolicyEnabledRequest {
546
608
  declare class HestiaPolicies implements DocumentStore<Policy, QueryDSL<Policy>, string, QueryDSL<Policy>, Record<string, unknown>, string, string, Record<string, unknown>> {
547
609
  private client;
548
610
  private pager;
549
- constructor(client: HestiaNetworkClient);
611
+ constructor(client: Transport);
550
612
  find(_query?: QueryDSL<Policy>): Promise<Page<Policy>>;
551
613
  query(qdsl: Record<string, unknown>): Promise<Page<Policy>>;
552
614
  list(_options?: QueryDSL<Policy>): Promise<Page<Policy>>;
@@ -608,14 +670,17 @@ interface RuleNode {
608
670
  conditions?: RuleNode[];
609
671
  }
610
672
  interface ValidateRuleRequest {
611
- expression: string;
612
- identity?: Record<string, unknown>;
613
- resource?: Record<string, unknown>;
614
- environment?: Record<string, unknown>;
673
+ rule: string | RuleNode;
674
+ context?: {
675
+ identity?: Record<string, unknown>;
676
+ resource?: Record<string, unknown>;
677
+ environment?: Record<string, unknown>;
678
+ };
615
679
  }
616
680
  interface ValidateRuleResult {
617
681
  valid: boolean;
618
682
  result?: boolean;
683
+ error?: string;
619
684
  }
620
685
  interface ReloadResult {
621
686
  operations: number;
@@ -625,7 +690,7 @@ interface ReloadResult {
625
690
  //#region system/rules/store.d.ts
626
691
  declare class HestiaRules implements DocumentStore<PolicyRule, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
627
692
  private client;
628
- constructor(client: HestiaNetworkClient);
693
+ constructor(client: Transport);
629
694
  find(_query?: Record<string, unknown>): Promise<Page<PolicyRule>>;
630
695
  list(_options?: Record<string, unknown>): Promise<Page<PolicyRule>>;
631
696
  read(id: string): Promise<Document<PolicyRule> | undefined>;
@@ -698,7 +763,7 @@ declare class HestiaLogs implements DocumentStore<AuditEntry, QueryDSL<AuditEntr
698
763
  private pagerOptions;
699
764
  private pager;
700
765
  private apiPrefix;
701
- constructor(client: HestiaNetworkClient, baseUrl: string, apiPrefix?: string);
766
+ constructor(client: Transport, baseUrl: string, apiPrefix?: string);
702
767
  find(query?: QueryDSL<AuditEntry>): Promise<Page<AuditEntry>>;
703
768
  list(options?: QueryDSL<AuditEntry>): Promise<Page<AuditEntry>>;
704
769
  read(_id: string): Promise<Document<AuditEntry> | undefined>;
@@ -758,10 +823,9 @@ declare class BlobNamespace implements DocumentStore<BlobMeta, QueryDSL<BlobMeta
758
823
  private pagerOptions;
759
824
  private pager;
760
825
  private prefixFilter;
761
- constructor(client: HestiaNetworkClient, ns: string);
826
+ constructor(client: Transport, ns: string);
762
827
  name(): string;
763
828
  setPrefix(prefix: string): void;
764
- private basePath;
765
829
  find(query?: QueryDSL<BlobMeta>): Promise<Page<BlobMeta>>;
766
830
  read(key: string): Promise<Document<BlobMeta> | undefined>;
767
831
  create(_props: {
@@ -796,8 +860,7 @@ declare class BlobNamespace implements DocumentStore<BlobMeta, QueryDSL<BlobMeta
796
860
  declare class HestiaBlobClient {
797
861
  private client;
798
862
  private apiPrefix;
799
- constructor(client: HestiaNetworkClient, apiPrefix?: string);
800
- private nsBase;
863
+ constructor(client: Transport, apiPrefix?: string);
801
864
  namespaces(): Promise<NamespaceInfo[]>;
802
865
  createNamespace(data: CreateNamespaceRequest): Promise<NamespaceInfo>;
803
866
  deleteNamespace(ns: string): Promise<void>;
@@ -819,7 +882,7 @@ type CollectionDocument = Document<{
819
882
  //#region collections/store.d.ts
820
883
  declare class HestiaCollections implements DocumentStore<CollectionMeta, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
821
884
  private client;
822
- constructor(client: HestiaNetworkClient);
885
+ constructor(client: Transport);
823
886
  find(_query?: Record<string, unknown>): Promise<Page<CollectionMeta>>;
824
887
  read(name: string): Promise<Document<CollectionMeta> | undefined>;
825
888
  create(props: {
@@ -845,65 +908,10 @@ declare class HestiaCollections implements DocumentStore<CollectionMeta, Record<
845
908
  documents<T extends Record<string, any>>(collectionName: string): HestiaCollection<T>;
846
909
  }
847
910
  //#endregion
848
- //#region node_modules/@asaidimu/utils-persistence/index.d.ts
849
- interface SimplePersistence<T> {
850
- /**
851
- * Persists data to storage.
852
- *
853
- * @param id The **unique identifier of the *consumer instance*** making the change. This is NOT the ID of the data (`T`) itself.
854
- * Think of it as the ID of the specific browser tab, component, or module that's currently interacting with the persistence layer.
855
- * It should typically be a **UUID** generated once at the consumer instance's instantiation.
856
- * This `id` is crucial for the `subscribe` method, helping to differentiate updates originating from the current instance versus other instances/tabs, thereby preventing self-triggered notification loops.
857
- * @param state The state (of type T) to persist. This state is generally considered the **global or shared state** that all instances interact with.
858
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations (like `IndexedDBPersistence`), this returns a `Promise<boolean>`.
859
- */
860
- set(id: string, state: T): boolean | Promise<boolean>;
861
- /**
862
- * Retrieves the global persisted data from storage.
863
- *
864
- * @returns The retrieved state of type `T`, or `null` if no data is found or if an error occurs during retrieval/parsing.
865
- * For asynchronous implementations, this returns a `Promise<T | null>`.
866
- */
867
- get(): (T | null) | Promise<T | null>;
868
- /**
869
- * Subscribes to changes in the global persisted data that originate from *other* instances of your application (e.g., other tabs or independent components using the same persistence layer).
870
- *
871
- * @param id The **unique identifier of the *consumer instance* subscribing**. This allows the persistence implementation to filter out notifications that were initiated by the subscribing instance itself.
872
- * @param callback The function to call when the global persisted data changes from *another* source. The new state (`T`) is passed as an argument to this callback.
873
- * @returns A function that, when called, will unsubscribe the provided callback from future updates. Call this when your component or instance is no longer active to prevent memory leaks.
874
- */
875
- subscribe(id: string, callback: (state: T) => void): () => void;
876
- /**
877
- * Clears (removes) the entire global persisted data from storage.
878
- *
879
- * @returns `true` if the operation was successful, `false` if an error occurred. For asynchronous implementations, this returns a `Promise<boolean>`.
880
- */
881
- clear(): boolean | Promise<boolean>;
882
- /**
883
- * Returns metadata about the persistence layer.
884
- *
885
- * This is useful for distinguishing between multiple apps running on the same host
886
- * (e.g., several apps served at `localhost:3000` that share the same storage key).
887
- *
888
- * @returns An object containing:
889
- * - `version`: The semantic version string of the persistence schema or application.
890
- * - `id`: A unique identifier for the application using this persistence instance.
891
- */
892
- stats(): {
893
- version: string;
894
- id: string;
895
- };
896
- /**
897
- * Closes the persistence instance, releasing the file watcher.
898
- * Call this when shutting down to clean up resources.
899
- */
900
- close?: () => Promise<void>;
901
- }
902
- //#endregion
903
911
  //#region system/capabilities/store.d.ts
904
912
  declare class HestiaCapabilities implements DocumentStore<any, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
905
913
  private client;
906
- constructor(client: HestiaNetworkClient);
914
+ constructor(client: Transport);
907
915
  find(_query?: Record<string, unknown>): Promise<Page<any>>;
908
916
  read(_id: string): Promise<Document<any> | undefined>;
909
917
  create(_props: {
@@ -933,13 +941,14 @@ interface HestiaConfig {
933
941
  baseUrl: string;
934
942
  apiPrefix?: string;
935
943
  persistence?: SimplePersistence<AuthState>;
944
+ transport?: Transport;
936
945
  }
937
946
  interface AuthState {
938
947
  identity: UserIdentity | null;
939
948
  }
940
949
  declare class HestiaClient {
941
950
  readonly store: ReactiveDataStore<AuthState>;
942
- readonly client: HestiaNetworkClient;
951
+ readonly client: Transport;
943
952
  readonly auth: HestiaAuth;
944
953
  readonly users: HestiaUsers;
945
954
  readonly keys: HestiaKeyStore;
@@ -955,6 +964,7 @@ declare class HestiaClient {
955
964
  onAuthStateChange(callback: () => void): void;
956
965
  authenticated(): boolean;
957
966
  collection<T extends Record<string, any>>(name: string): HestiaCollection<T>;
967
+ ready(): Promise<void>;
958
968
  }
959
969
  //#endregion
960
970
  //#region utils/pager.d.ts
@@ -974,4 +984,4 @@ interface ArrayPagerOptions<T extends Record<string, any>, F = any> {
974
984
  }
975
985
  declare function createArrayPager<T extends Record<string, any>, F = any>(options: ArrayPagerOptions<T, F>): PagedData<T>;
976
986
  //#endregion
977
- export { APIKey, APIKeyWithSecret, ArrayPagerOptions, AuditEntry, BlobDocument, BlobMeta, BlobNamespace, BootstrapPasswordRequest, ChangePasswordRequest, CollectionDocument, CollectionMeta, CreateKeyRequest, CreateNamespaceRequest, CreatePolicyRequest, CreateRuleRequest, CreateUserRequest, Document, DocumentStore, FetchResult, HestiaAuth, HestiaBlobClient, HestiaClient, HestiaCollection, HestiaCollections, HestiaKeyStore, HestiaLogs, HestiaNetworkClient, HestiaOperations, HestiaPolicies, HestiaResponse, HestiaRules, HestiaUsers, IdentityProvider, ListBlobsRequest, LogFilter, LoginRequest, LoginResult, NamespaceInfo, Operation, Page, PagedData, PagerRefreshOptions, PaginationInfo, Policy, PolicyRule, RegisterRequest, ReloadResult, RequestLogEntry, RuleNode, ServerHealth, SetPolicyEnabledRequest, StoreEvent, StreamHandlers, StreamOptions, UpdateKeyRequest, UpdatePolicyRuleRequest, UpdateRuleRequest, UpdateUserRequest, UserData, UserIdentity, ValidateRuleRequest, ValidateRuleResult, createArrayPager, createPagedController, internalError, notFound, parseErrorBody, permissionDenied, toSystemError };
987
+ export { APIKey, APIKeyWithSecret, ArrayPagerOptions, AuditEntry, BlobDocument, BlobMeta, BlobNamespace, BootstrapPasswordRequest, ChangePasswordRequest, CollectionDocument, CollectionMeta, CreateKeyRequest, CreateNamespaceRequest, CreatePolicyRequest, CreateRuleRequest, CreateUserRequest, DispatchInput, Document, DocumentStore, FetchResult, HestiaAuth, HestiaBlobClient, HestiaClient, HestiaCollection, HestiaCollections, HestiaKeyStore, HestiaLogs, HestiaNetworkClient, HestiaOperations, HestiaPolicies, HestiaResponse, HestiaRules, HestiaUsers, HttpTransport, IdentityProvider, ListBlobsRequest, LogFilter, LoginRequest, LoginResult, NamespaceInfo, Operation, Page, PagedData, PagerRefreshOptions, PaginationInfo, Policy, PolicyRule, RegisterRequest, ReloadResult, RequestLogEntry, RequestOptions, RuleNode, ServerHealth, SetPolicyEnabledRequest, StoreEvent, StreamHandlers, StreamOptions, Transport, UpdateKeyRequest, UpdatePolicyRuleRequest, UpdateRuleRequest, UpdateUserRequest, UserData, UserIdentity, ValidateRuleRequest, ValidateRuleResult, WailsTransport, createArrayPager, createPagedController, internalError, notFound, parseErrorBody, permissionDenied, toSystemError };
package/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import{createNetworkClient as e}from"@asaidimu/network-client";import{Errors as t,SystemError as n}from"@asaidimu/utils-error";import{DELETE_SYMBOL as r,ReactiveDataStore as i}from"@asaidimu/utils-store";import{Debouncer as a}from"@asaidimu/utils-sync";import{createMatcher as o,createSorter as s}from"@asaidimu/query";async function c(e){try{return(await e.clone().json())?.error??null}catch{return null}}function l(e,t){if(t)return new n({code:t.code??`UNKNOWN`,message:t.message??`Unknown error`,issues:t.details?.issues});let r=e.error?.message;if(typeof r==`object`&&r){let e=r;return new n({code:e.code??`UNKNOWN`,message:e.message??`Unknown error`})}return new n({code:`UNKNOWN`,message:r??`Unknown error`})}function u(e){return t.notFound(e)}function d(e){return t.permissionDenied(e)}function f(e){return t.internalError(e)}var p=class{data;status;constructor(e,t){this.data=e,this.status=t}},m=class{baseUrl;apiPrefix;provider;onAuthStateChanged;raw;heartbeatTimer;defaultHeartbeatInterval=300*1e3;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.provider=r,this.onAuthStateChanged=i,this.raw=e({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`})}base(){return this.baseUrl}prefix(){return this.apiPrefix}startHeartbeat(e){this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval;this.heartbeatTimer=setInterval(()=>this.heartbeat(),t)}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async heartbeat(){try{let e=this.canonicalPath(`system/core/heartbeat`),t=`${this.baseUrl.replace(/\/+$/,``)}/${e}`;await fetch(t,{method:`GET`,credentials:`include`})}catch{}}canonicalPath(e){let t=e.replace(/^\/+/,``);if(this.apiPrefix){let e=this.apiPrefix.replace(/^\/+/,``),n=RegExp(`^${e}/?`);return t=t.replace(n,``),`${e}/${t}`}return t}async request(e,t,r,i){let a=this.canonicalPath(t),o={};i?.headers&&(o.headers={...i.headers}),i?.responseType&&(o.responseType=i.responseType),i?.bodyType&&(o.bodyType=i.bodyType),i?.signal&&(o.signal=i.signal),o.headers||={};let s;if(e===`GET`)s=await this.raw.get(a,o);else{let t=i?.bodyType?{type:i.bodyType}:void 0;s=await this.raw[e.toLowerCase()](a,r,o,t)}if(s.success||s.status===204)return new p(s.data,s.status);if(s.status===401)throw i?.headers?.[`X-API-Key`]||(await this.provider.clear(),this.onAuthStateChanged?.()),new n({code:`AUTH-002-UNAUTH`,message:`Session expired`});let u=s.raw?await c(s.raw):null;throw l(s,u)}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async openStream(e,t,r){let i={Accept:`text/event-stream`,...r?.headers??{}},a=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,o;try{o=await fetch(a,{method:`GET`,headers:i,signal:r?.signal})}catch(e){if(e instanceof Error&&e.name===`AbortError`){t.onClose?.();return}t.onError?.(e instanceof Error?e:Error(String(e)));return}if(o.status===401){this.onAuthStateChanged?.(),t.onError?.(new n({code:`AUTH-002-UNAUTH`,message:`Session expired`}));return}if(!o.ok||!o.body){t.onError?.(Error(`Stream request failed with status ${o.status}`));return}t.onOpen?.();let s=o.body.getReader(),c=new TextDecoder,l=``;try{for(;;){let{done:e,value:n}=await s.read();if(e)break;l+=c.decode(n,{stream:!0});let r=l.indexOf(`
1
+ import{createNetworkClient as e}from"@asaidimu/network-client";import{Errors as t,SystemError as n}from"@asaidimu/utils-error";import{Debouncer as r,Once as i}from"@asaidimu/utils-sync";import{DELETE_SYMBOL as a,ReactiveDataStore as o}from"@asaidimu/utils-store";import{createMatcher as s,createSorter as c}from"@asaidimu/query";async function l(e){try{return(await e.clone().json())?.error??null}catch{return null}}function u(e,t){if(t)return new n({code:t.code??`UNKNOWN`,message:t.message??`Unknown error`,issues:t.details?.issues});let r=e.error?.message;if(typeof r==`object`&&r){let e=r;return new n({code:e.code??`UNKNOWN`,message:e.message??`Unknown error`})}return new n({code:`UNKNOWN`,message:r??`Unknown error`})}function d(e){return t.notFound(e)}function f(e){return t.permissionDenied(e)}function p(e){return t.internalError(e)}var m=class{data;status;constructor(e,t){this.data=e,this.status=t}},h=class{baseUrl;apiPrefix;provider;onAuthStateChanged;raw;heartbeatTimer;defaultHeartbeatInterval=300*1e3;routeCache=null;constructor(t,n,r,i){this.baseUrl=t,this.apiPrefix=n,this.provider=r,this.onAuthStateChanged=i,this.raw=e({baseUrl:t,defaultResponseType:`json`,defaultBodyType:`json`})}async getRouteCache(){if(this.routeCache)return this.routeCache;this.routeCache=new Map;try{let e=this.canonicalPath(`system/core/docs`),t=await this.raw.get(e,{headers:{}});if(t.success){let e=t.data?.data;if(Array.isArray(e))for(let t of e){if(!t.name||!t.http)continue;let e=[],n=t.input?.fields?.arguments;if(n?.schema?.id){let r=n.schema.id,i=t.input?.schemas?.[r];if(i?.fields)for(let t of Object.keys(i.fields))e.push(t)}this.routeCache.set(t.name,{method:t.http.method,route:t.http.route,arguments:e})}}}catch{}return this.routeCache}substituteArgs(e,t){return e.replace(/\{(\w+)\}/g,(e,n)=>t[n]?encodeURIComponent(t[n]):`{${n}}`)}async dispatch(e,t){let r=(await this.getRouteCache()).get(e);if(!r)throw new n({code:`ROUTE_NOT_FOUND`,message:`No registered route for handler: ${e} — has the server been bootstrapped?`});let i=this.substituteArgs(r.route,t?.arguments??{}),a=r.method,o={};if(t?.headers&&(o.headers=t.headers),t?.responseType&&(o.responseType=t.responseType),t?.bodyType&&(o.bodyType=t.bodyType),t?.signal&&(o.signal=t.signal),t?.modifiers){let e=Object.entries(t.modifiers).flatMap(([e,t])=>(Array.isArray(t)?t:[t]).map(t=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join(`&`);if(e){let n=i.includes(`?`)?`&`:`?`;return this.request(a,`${i}${n}${e}`,t?.payload,o)}}return this.request(a,i,t?.payload,o)}base(){return this.baseUrl}prefix(){return this.apiPrefix}async ready(){}startHeartbeat(e){this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval;this.heartbeatTimer=setInterval(()=>this.heartbeat(),t)}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0)}async heartbeat(){try{let e=this.canonicalPath(`system/core/heartbeat`),t=`${this.baseUrl.replace(/\/+$/,``)}/${e}`;await fetch(t,{method:`GET`,credentials:`include`})}catch{}}canonicalPath(e){let t=e.replace(/^\/+/,``);if(this.apiPrefix){let e=this.apiPrefix.replace(/^\/+/,``),n=RegExp(`^${e}/?`);return t=t.replace(n,``),`${e}/${t}`}return t}async request(e,t,r,i){let a=this.canonicalPath(t),o={};i?.headers&&(o.headers={...i.headers}),i?.responseType&&(o.responseType=i.responseType),i?.bodyType&&(o.bodyType=i.bodyType),i?.signal&&(o.signal=i.signal),o.headers||={};let s;if(e===`GET`)s=await this.raw.get(a,o);else{let t=i?.bodyType?{type:i.bodyType}:void 0;s=await this.raw[e.toLowerCase()](a,r,o,t)}if(s.success||s.status===204)return new m(s.data,s.status);if(s.status===401)throw i?.headers?.[`X-API-Key`]||(await this.provider.clear(),this.onAuthStateChanged?.()),new n({code:`AUTH-002-UNAUTH`,message:`Session expired`});let c=s.raw?await l(s.raw):null;throw u(s,c)}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async openStream(e,t,r){let i={Accept:`text/event-stream`,...r?.headers??{}},a=`${this.baseUrl.replace(/\/+$/,``)}/${this.canonicalPath(e)}`,o;try{o=await fetch(a,{method:`GET`,headers:i,signal:r?.signal})}catch(e){if(e instanceof Error&&e.name===`AbortError`){t.onClose?.();return}t.onError?.(e instanceof Error?e:Error(String(e)));return}if(o.status===401){this.onAuthStateChanged?.(),t.onError?.(new n({code:`AUTH-002-UNAUTH`,message:`Session expired`}));return}if(!o.ok||!o.body){t.onError?.(Error(`Stream request failed with status ${o.status}`));return}t.onOpen?.();let s=o.body.getReader(),c=new TextDecoder,l=``;try{for(;;){let{done:e,value:n}=await s.read();if(e)break;l+=c.decode(n,{stream:!0});let r=l.indexOf(`
2
2
 
3
3
  `);for(;r!==-1;){let e=l.slice(0,r);l=l.slice(r+2);let n=e.split(`
4
4
  `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());n.length>0&&t.onMessage(n.join(`
5
5
  `)),r=l.indexOf(`
6
6
 
7
- `)}}}catch(e){e instanceof Error&&e.name===`AbortError`||t.onError?.(e instanceof Error?e:Error(String(e)))}finally{t.onClose?.()}}};const h={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function g(e,t,n,i){let o=n.page??1,s=n.size??20,c=n.sort,l=n.filter,u=new a({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:r,page:{number:1,size:20,count:0,total:0,pages:1}}});let f=e=>{let t=e?.page??o,n=e?.size??s,r={pagination:{type:`offset`,offset:(t-1)*n,limit:n}},i=e?.sort??c;i&&(r.sort=Array.isArray(i)?i:[i]);let a=e?.filter??l;return a&&(r.filters=a),r},p=async e=>(await t.set({[d]:{loading:!0,error:r}}),await new Promise(n=>{n(u.do(async()=>{requestIdleCallback(()=>{requestIdleCallback(async()=>{try{let n=await i(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...h,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),g=m.subscribe(()=>{});return{page:()=>m.get()??h,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);o=e,await p({page:e})},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);s=e,o=t,await p()},sort:async e=>{c=Array.isArray(e)?e:[e],o=1,await p()},filter:async e=>{l=e,o=1,await p()},refresh:async e=>{await Promise.all([new Promise(t=>setTimeout(t,e?.delay||0)),p(e)])},subscribe:e=>m.subscribe(e),invalidate:async()=>{await t.set({[d]:r}),g()},id:()=>d}}var _=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=g(t,new i({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}get queryPath(){return`/system/collections/document/${encodeURIComponent(this.collectionName)}/query`}get documentsPath(){return`/system/collections/document/${encodeURIComponent(this.collectionName)}`}documentPath(e){return`${this.documentsPath}/${encodeURIComponent(e)}`}async find(e){let t=await this.client.post(this.queryPath,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async read(e){try{return(await this.client.get(this.documentPath(e))).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){return(await this.client.post(this.documentsPath,e.data)).data.data}async update(e){let t=e.options;return(await this.client.patch(this.documentPath(t),e.data)).data.data}async delete(e){await this.client.delete(this.documentPath(e))}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not implemented for dynamic collections`)}async notify(e){throw Error(`Notify not implemented for dynamic collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){return this.pager}},v=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.get(`/system/core/health`)).data.data}async login(e,t){let n=(await this.client.post(`/system/auth/session`,{email:e,password:t})).data.data;return this.provider.setIdentity(n.user),n}async register(e,t,n){return(await this.client.post(`/system/auth/user`,{email:e,password:t,name:n})).data.data}async logout(){await this.client.delete(`/system/auth/session`),await this.provider.clear()}async requestPasswordReset(e){await this.client.post(`/system/auth/password`,{email:e})}async confirmPasswordReset(e,t){await this.client.patch(`/system/auth/password`,{password:t,token:e})}async bootstrap(e,t,n){await this.client.patch(`/system/auth/bootstrap`,{password:t,email:n},{headers:{"X-API-Key":e}})}},y=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=g(`users`,new i({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.post(`/system/users/user/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.get(`/system/users/user/${encodeURIComponent(e)}`)).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){let t=e.options;return(await this.client.patch(`/system/users/user/${encodeURIComponent(t)}`,e.data)).data.data}async delete(e){await this.client.delete(`/system/users/user/${encodeURIComponent(e)}`)}async create(e){throw Error(`User creation requires email/password/name, use register endpoint`)}async upload(e){throw Error(`Upload not supported for users`)}async subscribe(e,t){throw Error(`Subscription not supported for users`)}async notify(e){throw Error(`Notify not supported for users`)}stream(e,t){throw Error(`Stream not supported for users`)}page(e){return this.pager}async changePassword(e,t,n){await this.client.patch(`/system/users/password/${encodeURIComponent(e)}`,{current:t,new:n})}},b=class{client;pager;constructor(e){this.client=e,this.pager=g(`_api_key_`,new i({}),{},e=>this.find(e))}basePath=`/system/apikeys/key`;async find(e){let t=await this.client.get(this.basePath),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return e?this.find(e):this.find()}async read(e){try{return(await this.client.get(`${this.basePath}/${encodeURIComponent(e)}`)).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){return(await this.client.post(this.basePath,e.data)).data.data}async update(e){let t=e.options;return(await this.client.patch(`${this.basePath}/${encodeURIComponent(t)}`,e.data)).data.data}async delete(e){await this.client.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async upload(e){throw Error(`Upload not supported for API keys`)}async subscribe(e,t){throw Error(`Subscription not supported for API keys`)}async notify(e){throw Error(`Notify not supported for API keys`)}stream(e,t){throw Error(`Stream not supported for API keys`)}page(e){return this.pager}async rotate(e){return(await this.client.post(`${this.basePath}/${encodeURIComponent(e)}`)).data.data}};const x=`/system/policies/operation`;var S=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.get(x)).data?.data?.operations??[];return{data:e.map(e=>({data:e,metadata:{}})),loading:!1,page:{number:1,size:e.length,count:e.length,total:e.length,pages:1},error:null}}async read(e){try{let t=await this.client.get(`${x}/${encodeURIComponent(e)}`);return t.data?.data?{data:t.data.data,metadata:{}}:void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}};const C=`/system/policies/policy`;var w=class{client;pager;constructor(e){this.client=e,this.pager=g(`policies`,new i({}),{},e=>this.find(e))}async find(e){return this.query(e??{})}async query(e){let t=await this.client.post(`/system/collections/document/_operation_policy_/query`,e),n=t.data?.data??[],r=t.data?.metadata?.page;return{data:n.map(e=>({_id_:e._id_,_metadata_:e._metadata_,id:e._id_,operationName:e.operation??``,ruleName:e.rule??``,enabled:e.enabled??!0,protected:e.protected??!1})),loading:!1,page:r??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){let t=(await this.client.get(C)).data?.data?.policies??[];return{data:t.map(e=>({data:e,metadata:{}})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.get(`${C}/${encodeURIComponent(e)}`);return t.data?.data?{data:t.data.data,metadata:{}}:void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Operation name is required for create`);let n={ruleName:e.data.ruleName??``},r=await this.client.post(`${C}/${encodeURIComponent(t)}`,n);if(r.data?.data)return{data:r.data.data,metadata:{}}}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);let n=await this.client.patch(`${C}/${encodeURIComponent(t)}`,e.data);if(n.data?.data)return{data:n.data.data,metadata:{}}}async setEnabled(e,t){return{data:(await this.client.patch(`${C}/${encodeURIComponent(e)}`,{enabled:t})).data.data,metadata:{}}}async delete(e){throw Error(`Policies cannot be deleted; disable instead`)}async upload(e){throw Error(`Upload not supported for policies`)}async subscribe(e,t){throw Error(`Subscription not supported for policies`)}async notify(e){throw Error(`Notify not supported for policies`)}stream(e,t){throw Error(`Stream not supported for policies`)}page(e){return this.pager}};const T=`/system/policies/rule`;var E=class{client;constructor(e){this.client=e}async find(e){return this.list()}async list(e){let t=(await this.client.get(T)).data?.data?.rules??[];return{data:t.map(e=>({_id_:e.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...e})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.get(`${T}/${encodeURIComponent(e)}`);if(!t.data?.data)return;let n=t.data.data;return{_id_:n.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...n}}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Rule name is required for create`);let n=await this.client.post(`${T}/${encodeURIComponent(t)}`,e.data);if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async update(e){let t=e.options;if(!t)throw Error(`Rule name is required for update`);let n=await this.client.patch(`${T}/${encodeURIComponent(t)}`,e.data);if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async delete(e){await this.client.delete(`${T}/${encodeURIComponent(e)}`)}async validate(e){return(await this.client.check(T,e)).data?.data??{valid:!1}}async reload(){return(await this.client.get(T)).data.data}async upload(e){throw Error(`Upload not supported for rules`)}async subscribe(e,t){throw Error(`Subscription not supported for rules`)}async notify(e){throw Error(`Notify not supported for rules`)}stream(e,t){throw Error(`Stream not supported for rules`)}page(e){throw Error(`Pagination not supported for rules`)}},D=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=g(`_audit_log_`,new i({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/audit/log/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){throw Error(`Read by ID not supported for audit logs; use find with filters`)}async create(e){throw Error(`Audit logs are write-only; entries are created by the system`)}async update(e){throw Error(`Audit logs are append-only; updates are not allowed`)}async delete(e){throw Error(`Audit logs are append-only; deletion is not allowed`)}async upload(e){throw Error(`Upload not supported for audit logs`)}async subscribe(e,t){throw Error(`Use stream() for real-time audit log entries`)}async notify(e){throw Error(`Notify not supported for audit logs`)}stream(e,t){let n=this.getStreamUrl(),r=null,i=`active`,a=null,o=async function*(){let e=[];r=new EventSource(n,{withCredentials:!0}),r.onmessage=t=>{for(let n of t.data.split(`
8
- `)){let t=n.trim();if(t)try{let n=JSON.parse(t);n?.data&&e.push(n.data)}catch{}}e.length>0&&a&&(a(),a=null)},r.onerror=()=>{i===`active`&&(i=`completed`),a&&=(a(),null)};try{for(;i===`active`;)e.length>0?yield e.shift():await new Promise(t=>{a=t,e.length>0&&(t(),a=null)})}finally{r?.close(),a&&=(a(),null),i===`active`&&(i=`completed`)}};return{stream:()=>o(),cancel:()=>{i===`active`&&(i=`cancelled`,r?.close())},status:()=>i}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}};function O(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function k(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var A=class{client;ns;pagerOptions={};pager;prefixFilter=``;constructor(e,t){this.client=e,this.ns=t,this.pager=g(`blobs_${t}`,new i({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}basePath(){return`/system/blobs/blob/${encodeURIComponent(this.ns)}`}async find(e){let t=this.prefixFilter||e?.prefix||``,n=e?.limit??e?.pagination?.limit??0,r={};t&&(r.prefix=t),n&&(r.limit=n);let i=(await this.client.post(`${this.basePath()}/query`,r)).data?.data?.blobs??[];return{data:i.map(O),loading:!1,page:k(i),error:void 0}}async read(e){try{let t=await this.client.post(`${this.basePath()}/${encodeURIComponent(e)}/query`);return t.data?.data?O(t.data.data):void 0}catch(e){if(e?.code===`NOT_FOUND`)return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob update`);return O((await this.client.patch(`${this.basePath()}/${encodeURIComponent(t)}`,{custom:e.data})).data.data)}async delete(e){await this.client.delete(`${this.basePath()}/${encodeURIComponent(e)}`)}async list(e){return this.find(e??{})}async upload(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob upload`);let n={},r=e.options?.contentType||e.file.type;return r&&(n[`Content-Type`]=r),O((await this.client.post(`${this.basePath()}/${encodeURIComponent(t)}`,e.file,{headers:n,bodyType:`blob`})).data.data)}async subscribe(e,t){throw Error(`Subscription not supported for blobs`)}async notify(e){throw Error(`Notify not supported for blobs`)}stream(e,t){throw Error(`Stream not supported for blobs`)}page(e){return this.pager}async download(e){let t=(await this.client.get(`${this.basePath()}/${encodeURIComponent(e)}`,{responseType:`blob`})).data;return{data:t,contentType:t.type}}},j=class{client;apiPrefix;constructor(e,t=`/api`){this.client=e,this.apiPrefix=t}nsBase=`/system/blobs`;async namespaces(){return(await this.client.post(`${this.nsBase}/namespace/query`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.post(`${this.nsBase}/namespace`,e)).data.data}async deleteNamespace(e){await this.client.delete(`${this.nsBase}/namespace/${encodeURIComponent(e)}`)}blob(e,t){return`${this.client.base()}${this.apiPrefix}${this.nsBase}/blob/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}namespace(e){return new A(this.client,e)}},M=class{client;constructor(e){this.client=e}async find(e){let t=((await this.client.get(`/system/collections/collection`)).data?.data??[]).map(e=>({_id_:e.name,_metadata_:{checksum:``,created:e.created,updated:e.updated,version:1},name:e.name,schema:e.schema,created:e.created,updated:e.updated}));return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){try{let t=await this.client.get(`/system/collections/collection/${encodeURIComponent(e)}`);if(!t.data)return;let n=t.data.data;return{_id_:n.name,_metadata_:{checksum:``,created:n.created,updated:n.updated,version:1},name:n.name,schema:n.schema,created:n.created,updated:n.updated}}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){return(await this.client.post(`/system/collections/collection`,e.data)).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.delete(`/system/collections/collection/${encodeURIComponent(e)}`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not supported for collections`)}async notify(e){throw Error(`Notify not supported for collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){throw Error(`Pagination not supported for collection metadata; use documents(name)`)}documents(e){return new _(this.client,e)}},N=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.get(`/system/core/docs`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){throw Error(`Read by ID not supported for capabilities; use find()`)}async create(e){throw Error(`Capabilities are read-only`)}async update(e){throw Error(`Capabilities are read-only`)}async delete(e){throw Error(`Capabilities are read-only`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for capabilities`)}async subscribe(e,t){throw Error(`Subscription not supported for capabilities`)}async notify(e){throw Error(`Notify not supported for capabilities`)}stream(e,t){throw Error(`Stream not supported for capabilities`)}page(e){throw Error(`Pagination not supported for capabilities`)}},P=class{store;client;auth;users;keys;policies;rules;logs;collections;blobs;capabilities;tokenProvider;onAuthStateChanged;constructor(e){this.store=new i({identity:null},e.persistence);let t={identity:()=>this.store.get().identity,setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({identity:null})},n=e.apiPrefix??`/api`;this.tokenProvider=t,this.client=new m(e.baseUrl,n,t,()=>this.onAuthStateChanged?.()),this.auth=new v(this.client,t),this.users=new y(this.client),this.keys=new b(this.client),this.policies=new w(this.client),this.rules=new E(this.client),this.logs=new D(this.client,e.baseUrl,n),this.collections=new M(this.client),this.blobs=new j(this.client,n),this.capabilities=new N(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}authenticated(){return this.tokenProvider.identity()!==null}collection(e){return this.collections.documents(e)}};function F(e){let t=`${e.collectionName}_array_pager_state_`,n=new i({}),a=[...e.initialData??[]],c=`collection`,l,u=e.page??1,d=e.size??20,f=[],p,m,{match:h}=o(e.customFunctions??{}),{sort:g}=s(),_=n.select(e=>e[t]),v={data:[],loading:!0,error:void 0,page:{number:1,size:d,count:0,total:0,pages:1}},y=()=>({filters:p,sort:f,pagination:{type:`offset`,offset:(u-1)*d,limit:d}}),b=async(r=!0)=>{if(e.fetch){if(m=void 0,r){let e=_.get()??v;await n.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=y(),n=await e.fetch(t);c=n.scope,l=n.total,a=n.replace?[...n.data]:[...a,...n.data]}catch(e){m=e}}let i=x(e.fetch?r:!1);await n.set({[t]:i})},x=e=>{let t=[...a];if(c===`collection`){p&&(t=t.filter(e=>h(e,p))),f.length>0&&(t=g(t,f));let n=t.length,r=Math.ceil(n/d)||1;u>r&&(u=r),u<1&&(u=1);let i=(u-1)*d,a=t.slice(i,i+d);return{data:a,loading:e,error:m,page:{number:u,size:d,count:a.length,total:n,pages:r}}}let n=l??t.length,r=Math.ceil(n/d)||1;return{data:t,loading:e,error:m,page:{number:u,size:d,count:t.length,total:n,pages:r}}};return b(!0),{id:()=>t,page:()=>_.get()??v,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);u=e,await b(!0)},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);d=e,u=t,await b(!0)},sort:async e=>{f=Array.isArray(e)?e:[e],u=1,await b(!0)},filter:async e=>{p=e,u=1,await b(!0)},refresh:async e=>{let r=_.get()??v;await n.set({[t]:{...r,loading:!0}});let i=e?.delay??600;await Promise.all([new Promise(e=>setTimeout(e,i)),b(!1)]);let a=_.get()??v;await n.set({[t]:{...a,loading:!1}})},subscribe:e=>_.subscribe(t=>{e(t)}),invalidate:async()=>{await n.set({[t]:r}),a=[]}}}export{A as BlobNamespace,v as HestiaAuth,j as HestiaBlobClient,P as HestiaClient,_ as HestiaCollection,M as HestiaCollections,b as HestiaKeyStore,D as HestiaLogs,m as HestiaNetworkClient,S as HestiaOperations,w as HestiaPolicies,p as HestiaResponse,E as HestiaRules,y as HestiaUsers,F as createArrayPager,g as createPagedController,f as internalError,u as notFound,c as parseErrorBody,d as permissionDenied,l as toSystemError};
7
+ `)}}}catch(e){e instanceof Error&&e.name===`AbortError`||t.onError?.(e instanceof Error?e:Error(String(e)))}finally{t.onClose?.()}}};const g=h;function _(){try{let e=window.go;if(!e)return null;for(let t of Object.values(e))for(let e of Object.values(t))if(e?.Dispatch)return e;return null}catch{return null}}var v=class{baseUrl=``;apiPrefix=``;init=new i({throws:!0});config;constructor(e){this.config=e}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return _()}base(){return this.baseUrl}prefix(){return this.apiPrefix}async ready(e=1e4){this.init.do(async()=>{let t=Date.now();for(;!this.resolveService();){if(Date.now()-t>e)throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`Timed out after ${e}ms waiting for Wails bindings on window.go. Are you running inside a Wails desktop window?`});await new Promise(e=>setTimeout(e,50))}},e)}async dispatch(e,t){await this.ready();let r=this.resolveService();if(r?.Dispatch){let n=await r.Dispatch({name:e,arguments:t?.arguments??{},modifiers:t?.modifiers??{},payload:t?.payload??null});return new m(n.data,n.status)}throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Dispatch binding found on window.go. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}.`})}async check(e,t,n){return this.request(`POST`,`${e}/check`,t,n)}async get(e,t){return this.request(`GET`,e,void 0,t)}async post(e,t,n){return this.request(`POST`,e,t,n)}async patch(e,t,n){return this.request(`PATCH`,e,t,n)}async put(e,t,n){return this.request(`PUT`,e,t,n)}async delete(e,t,n){return this.request(`DELETE`,e,t,n)}async request(e,t,r,i){throw new n({code:`USE_DISPATCH`,message:`WailsTransport does not support path-based requests. Use dispatch(name, input) instead.`})}async openStream(e,t,r){let i=this.resolveService();try{if(!i?.Stream)throw new n({code:`TRANSPORT_UNAVAILABLE`,message:`No Wails Stream binding found. Available packages: ${window.go?Object.keys(window.go).join(`, `):`none`}`});let r=await i.Stream(e),a=`hestia:stream:${e}`;window.runtime?.EventsOn(a,e=>{t.onMessage(typeof e==`string`?e:JSON.stringify(e))}),t.onOpen?.(),r&&t.onMessage(r),t.onClose?.()}catch(e){t.onError?.(e instanceof Error?e:Error(String(e))),t.onClose?.()}}};const y={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function b(e,t,n,i){let o=n.page??1,s=n.size??20,c=n.sort,l=n.filter,u=new r({delay:50}),d=`${e}_pager_state_`;t.set({[d]:{data:[],loading:!1,error:a,page:{number:1,size:20,count:0,total:0,pages:1}}});let f=e=>{let t=e?.page??o,n=e?.size??s,r={pagination:{type:`offset`,offset:(t-1)*n,limit:n}},i=e?.sort??c;i&&(r.sort=Array.isArray(i)?i:[i]);let a=e?.filter??l;return a&&(r.filters=a),r},p=async e=>(await t.set({[d]:{loading:!0,error:a}}),await new Promise(n=>{n(u.do(async()=>{requestIdleCallback(()=>{requestIdleCallback(async()=>{try{let n=await i(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...y,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??y,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);o=e,await p({page:e})},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);s=e,o=t,await p()},sort:async e=>{c=Array.isArray(e)?e:[e],o=1,await p()},filter:async e=>{l=e,o=1,await p()},refresh:async e=>{await Promise.all([new Promise(t=>setTimeout(t,e?.delay||0)),p(e)])},subscribe:e=>m.subscribe(e),invalidate:async()=>{await t.set({[d]:a}),h()},id:()=>d}}var x=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=b(t,new o({}),this.pagerOptions,e=>this.find(e))}name(){return this.collectionName}async find(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:this.collectionName},payload:e??{}}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async read(e){try{return(await this.client.dispatch(`system:collections:document:get`,{arguments:{name:this.collectionName,doc_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){return(await this.client.dispatch(`system:collections:document:create`,{arguments:{name:this.collectionName},payload:e.data})).data.data}async update(e){let t=e.options;return(await this.client.dispatch(`system:collections:document:update`,{arguments:{name:this.collectionName,doc_id:t},payload:e.data})).data.data}async delete(e){await this.client.dispatch(`system:collections:document:delete`,{arguments:{name:this.collectionName,doc_id:e}})}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:this.defaultLimit}})}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not implemented for dynamic collections`)}async notify(e){throw Error(`Notify not implemented for dynamic collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){return this.pager}},S=class{client;provider;constructor(e,t){this.client=e,this.provider=t}async health(){return(await this.client.dispatch(`system:core:health:check`)).data.data}async login(e,t){let n=await this.client.dispatch(`system:auth:session:create`,{payload:{email:e,password:t}});return this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:auth:user:register`,{payload:{email:e,password:t,name:n}})).data.data}async logout(){await this.client.dispatch(`system:auth:session:delete`),await this.provider.clear()}async requestPasswordReset(e){await this.client.dispatch(`system:auth:password:reset`,{payload:{email:e}})}async confirmPasswordReset(e,t){await this.client.dispatch(`system:auth:password:confirm`,{payload:{password:t,token:e}})}async bootstrap(e,t,n){await this.client.dispatch(`system:auth:bootstrap:password:set`,{payload:{password:t,email:n},headers:{"X-API-Key":e}})}},C=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=b(`users`,new o({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:users:user:query`,{payload:e??{}}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){try{return(await this.client.dispatch(`system:users:user:get`,{arguments:{user_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async update(e){let t=e.options;return(await this.client.dispatch(`system:users:user:update`,{arguments:{user_id:t},payload:e.data})).data.data}async delete(e){await this.client.dispatch(`system:users:user:delete`,{arguments:{user_id:e}})}async create(e){throw Error(`User creation requires email/password/name, use register endpoint`)}async upload(e){throw Error(`Upload not supported for users`)}async subscribe(e,t){throw Error(`Subscription not supported for users`)}async notify(e){throw Error(`Notify not supported for users`)}stream(e,t){throw Error(`Stream not supported for users`)}page(e){return this.pager}async changePassword(e,t,n){await this.client.dispatch(`system:users:password:change`,{arguments:{user_id:e},payload:{current:t,new:n}})}},w=class{client;pager;constructor(e){this.client=e,this.pager=b(`_api_key_`,new o({}),{},e=>this.find(e))}async find(e){let t=await this.client.dispatch(`system:apikeys:key:list`),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1}}}async list(e){return e?this.find(e):this.find()}async read(e){try{return(await this.client.dispatch(`system:apikeys:key:get`,{arguments:{key_id:e}})).data?.data}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`INTERNAL_ERROR`&&typeof e?.message==`string`&&e.message.includes(`not found`))return;throw e}}async create(e){return(await this.client.dispatch(`system:apikeys:key:create`,{payload:e.data})).data.data}async update(e){let t=e.options;return(await this.client.dispatch(`system:apikeys:key:update`,{arguments:{key_id:t},payload:e.data})).data.data}async delete(e){await this.client.dispatch(`system:apikeys:key:delete`,{arguments:{key_id:e}})}async upload(e){throw Error(`Upload not supported for API keys`)}async subscribe(e,t){throw Error(`Subscription not supported for API keys`)}async notify(e){throw Error(`Notify not supported for API keys`)}stream(e,t){throw Error(`Stream not supported for API keys`)}page(e){return this.pager}async rotate(e){return(await this.client.dispatch(`system:apikeys:key:rotate`,{arguments:{key_id:e}})).data.data}},T=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:operation:list`)).data?.data?.operations??[];return{data:e.map(e=>({data:e,metadata:{}})),loading:!1,page:{number:1,size:e.length,count:e.length,total:e.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:operation:get`,{arguments:{name:e}});return t.data?.data?{data:t.data.data,metadata:{}}:void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}},E=class{client;pager;constructor(e){this.client=e,this.pager=b(`policies`,new o({}),{},e=>this.find(e))}async find(e){return this.query(e??{})}async query(e){let t=await this.client.dispatch(`system:collections:document:query`,{arguments:{name:`_operation_policy_`},payload:e}),n=t.data?.data??[],r=t.data?.metadata?.page;return{data:n.map(e=>({_id_:e._id_,_metadata_:e._metadata_,id:e._id_,operationName:e.operation??``,ruleName:e.rule??``,enabled:e.enabled??!0,protected:e.protected??!1})),loading:!1,page:r??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t.map(e=>({data:e,metadata:{}})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e);return t?{data:{id:t._id_,operationName:t.operation??``,ruleName:t.rule??``,enabled:t.enabled??!0,protected:t.protected??!1},metadata:{}}:void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Operation name is required for create`);let n={ruleName:e.data.ruleName??``},r=await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n});if(r.data?.data)return{data:r.data.data,metadata:{}}}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);let n=await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:e.data});if(n.data?.data)return{data:n.data.data,metadata:{}}}async setEnabled(e,t){return{data:(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data,metadata:{}}}async delete(e){throw Error(`Policies cannot be deleted; disable instead`)}async upload(e){throw Error(`Upload not supported for policies`)}async subscribe(e,t){throw Error(`Subscription not supported for policies`)}async notify(e){throw Error(`Notify not supported for policies`)}stream(e,t){throw Error(`Stream not supported for policies`)}page(e){return this.pager}},D=class{client;constructor(e){this.client=e}async find(e){return this.list()}async list(e){let t=(await this.client.dispatch(`system:policies:rule:list`)).data?.data?.rules??[];return{data:t.map(e=>({_id_:e.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...e})),loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{let t=await this.client.dispatch(`system:policies:rule:get`,{arguments:{name:e}});if(!t.data?.data)return;let n=t.data.data;return{_id_:n.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...n}}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}async create(e){let t=e.options??e.data.name;if(!t)throw Error(`Rule name is required for create`);let n=await this.client.dispatch(`system:policies:rule:create`,{arguments:{name:t},payload:e.data});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async update(e){let t=e.options;if(!t)throw Error(`Rule name is required for update`);let n=await this.client.dispatch(`system:policies:rule:update`,{arguments:{name:t},payload:e.data});if(!n.data?.data)return;let r=n.data.data;return{_id_:r.id,_metadata_:{checksum:``,created:``,updated:``,version:1},...r}}async delete(e){await this.client.dispatch(`system:policies:rule:delete`,{arguments:{name:e}})}async validate(e){return(await this.client.dispatch(`system:policies:rule:validate`,{payload:e})).data?.data??{valid:!1}}async reload(){return(await this.client.dispatch(`system:policies:reload`)).data.data}async upload(e){throw Error(`Upload not supported for rules`)}async subscribe(e,t){throw Error(`Subscription not supported for rules`)}async notify(e){throw Error(`Notify not supported for rules`)}stream(e,t){throw Error(`Stream not supported for rules`)}page(e){throw Error(`Pagination not supported for rules`)}},O=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=b(`_audit_log_`,new o({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/audit/log/query`,e??{}),n=t.data?.data??[];return{data:n,loading:!1,page:t.data?.metadata?.page??{number:1,size:n.length,count:n.length,total:n.length,pages:1},error:null}}async list(e){return this.find(e??{pagination:{type:`offset`,offset:0,limit:50}})}async read(e){throw Error(`Read by ID not supported for audit logs; use find with filters`)}async create(e){throw Error(`Audit logs are write-only; entries are created by the system`)}async update(e){throw Error(`Audit logs are append-only; updates are not allowed`)}async delete(e){throw Error(`Audit logs are append-only; deletion is not allowed`)}async upload(e){throw Error(`Upload not supported for audit logs`)}async subscribe(e,t){throw Error(`Use stream() for real-time audit log entries`)}async notify(e){throw Error(`Notify not supported for audit logs`)}stream(e,t){let n=this.getStreamUrl(),r=null,i=`active`,a=null,o=async function*(){let e=[];r=new EventSource(n,{withCredentials:!0}),r.onmessage=t=>{for(let n of t.data.split(`
8
+ `)){let t=n.trim();if(t)try{let n=JSON.parse(t);n?.data&&e.push(n.data)}catch{}}e.length>0&&a&&(a(),a=null)},r.onerror=()=>{i===`active`&&(i=`completed`),a&&=(a(),null)};try{for(;i===`active`;)e.length>0?yield e.shift():await new Promise(t=>{a=t,e.length>0&&(t(),a=null)})}finally{r?.close(),a&&=(a(),null),i===`active`&&(i=`completed`)}};return{stream:()=>o(),cancel:()=>{i===`active`&&(i=`cancelled`,r?.close())},status:()=>i}}page(e){return this.pager}getStreamUrl(){return`${this.baseUrl}${this.apiPrefix}/system/audit/log/stream`}};function k(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function A(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var j=class{client;ns;pagerOptions={};pager;prefixFilter=``;constructor(e,t){this.client=e,this.ns=t,this.pager=b(`blobs_${t}`,new o({}),this.pagerOptions,e=>this.find(e))}name(){return this.ns}setPrefix(e){this.prefixFilter=e}async find(e){let t=this.prefixFilter||e?.prefix||``,n=e?.limit??e?.pagination?.limit??0,r={};t&&(r.prefix=t),n&&(r.limit=n);let i=(await this.client.dispatch(`system:blobs:blob:list`,{arguments:{ns:this.ns},payload:r})).data?.data?.blobs??[];return{data:i.map(k),loading:!1,page:A(i),error:void 0}}async read(e){try{let t=await this.client.dispatch(`system:blobs:blob:head`,{arguments:{ns:this.ns,key:e}});return t.data?.data?k(t.data.data):void 0}catch(e){if(e?.code===`NOT_FOUND`)return;throw e}}async create(e){throw Error(`Use upload() to create blobs`)}async update(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob update`);return k((await this.client.dispatch(`system:blobs:blob:update`,{arguments:{ns:this.ns,key:t},payload:{custom:e.data}})).data.data)}async delete(e){await this.client.dispatch(`system:blobs:blob:delete`,{arguments:{ns:this.ns,key:e}})}async list(e){return this.find(e??{})}async upload(e){let t=e.options?.key;if(!t)throw Error(`options.key is required for blob upload`);let n={},r=e.options?.contentType||e.file.type;return r&&(n[`Content-Type`]=r),k((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},payload:e.file,headers:n,bodyType:`blob`})).data.data)}async subscribe(e,t){throw Error(`Subscription not supported for blobs`)}async notify(e){throw Error(`Notify not supported for blobs`)}stream(e,t){throw Error(`Stream not supported for blobs`)}page(e){return this.pager}async download(e){let t=(await this.client.dispatch(`system:blobs:blob:download`,{arguments:{ns:this.ns,key:e},responseType:`blob`})).data;return{data:t,contentType:t.type}}},M=class{client;apiPrefix;constructor(e,t=`/api`){this.client=e,this.apiPrefix=t}async namespaces(){return(await this.client.dispatch(`system:blobs:namespace:list`)).data?.data?.namespaces??[]}async createNamespace(e){return(await this.client.dispatch(`system:blobs:namespace:create`,{payload:e})).data.data}async deleteNamespace(e){await this.client.dispatch(`system:blobs:namespace:delete`,{arguments:{ns:e}})}blob(e,t){return`${this.client.base()}${this.apiPrefix}/system/blobs/blob/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}namespace(e){return new j(this.client,e)}},N=class{client;constructor(e){this.client=e}async find(e){let t=((await this.client.dispatch(`system:collections:collection:list`)).data?.data??[]).map(e=>({_id_:e.name,_metadata_:{checksum:``,created:e.created,updated:e.updated,version:1},name:e.name,schema:e.schema,created:e.created,updated:e.updated}));return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){try{let t=await this.client.dispatch(`system:collections:collection:get`,{arguments:{name:e}});if(!t.data)return;let n=t.data.data;return{_id_:n.name,_metadata_:{checksum:``,created:n.created,updated:n.updated,version:1},name:n.name,schema:n.schema,created:n.created,updated:n.updated}}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){return(await this.client.dispatch(`system:collections:collection:create`,{payload:e.data})).data.data}async update(e){throw Error(`Collection update not implemented`)}async delete(e){await this.client.dispatch(`system:collections:collection:delete`,{arguments:{name:e}})}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for collections`)}async subscribe(e,t){throw Error(`Subscription not supported for collections`)}async notify(e){throw Error(`Notify not supported for collections`)}stream(e,t){throw Error(`Stream not supported for collections`)}page(e){throw Error(`Pagination not supported for collection metadata; use documents(name)`)}documents(e){return new x(this.client,e)}},P=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:core:docs:list`)).data?.data??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1}}}async read(e){throw Error(`Read by ID not supported for capabilities; use find()`)}async create(e){throw Error(`Capabilities are read-only`)}async update(e){throw Error(`Capabilities are read-only`)}async delete(e){throw Error(`Capabilities are read-only`)}async list(e){return this.find()}async upload(e){throw Error(`Upload not supported for capabilities`)}async subscribe(e,t){throw Error(`Subscription not supported for capabilities`)}async notify(e){throw Error(`Notify not supported for capabilities`)}stream(e,t){throw Error(`Stream not supported for capabilities`)}page(e){throw Error(`Pagination not supported for capabilities`)}},F=class{store;client;auth;users;keys;policies;rules;logs;collections;blobs;capabilities;tokenProvider;onAuthStateChanged;constructor(e){this.store=new o({identity:null},e.persistence);let t={identity:()=>this.store.get().identity,setIdentity:async e=>void await this.store.set({identity:e}),clear:async()=>void await this.store.set({identity:null})},n=e.apiPrefix??`/api`;this.tokenProvider=t,this.client=e.transport??new h(e.baseUrl,n,t,()=>this.onAuthStateChanged?.()),this.auth=new S(this.client,t),this.users=new C(this.client),this.keys=new w(this.client),this.policies=new E(this.client),this.rules=new D(this.client),this.logs=new O(this.client,e.baseUrl,n),this.collections=new N(this.client),this.blobs=new M(this.client,n),this.capabilities=new P(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}authenticated(){return this.tokenProvider.identity()!==null}collection(e){return this.collections.documents(e)}ready(){return this.client.ready()}};function I(e){let t=`${e.collectionName}_array_pager_state_`,n=new o({}),r=[...e.initialData??[]],i=`collection`,l,u=e.page??1,d=e.size??20,f=[],p,m,{match:h}=s(e.customFunctions??{}),{sort:g}=c(),_=n.select(e=>e[t]),v={data:[],loading:!0,error:void 0,page:{number:1,size:d,count:0,total:0,pages:1}},y=()=>({filters:p,sort:f,pagination:{type:`offset`,offset:(u-1)*d,limit:d}}),b=async(a=!0)=>{if(e.fetch){if(m=void 0,a){let e=_.get()??v;await n.set({[t]:{...e,loading:!0,error:void 0}})}try{let t=y(),n=await e.fetch(t);i=n.scope,l=n.total,r=n.replace?[...n.data]:[...r,...n.data]}catch(e){m=e}}let o=x(e.fetch?a:!1);await n.set({[t]:o})},x=e=>{let t=[...r];if(i===`collection`){p&&(t=t.filter(e=>h(e,p))),f.length>0&&(t=g(t,f));let n=t.length,r=Math.ceil(n/d)||1;u>r&&(u=r),u<1&&(u=1);let i=(u-1)*d,a=t.slice(i,i+d);return{data:a,loading:e,error:m,page:{number:u,size:d,count:a.length,total:n,pages:r}}}let n=l??t.length,a=Math.ceil(n/d)||1;return{data:t,loading:e,error:m,page:{number:u,size:d,count:t.length,total:n,pages:a}}};return b(!0),{id:()=>t,page:()=>_.get()??v,navigate:async e=>{if(e<1)throw Error(`Page number must be >= 1`);u=e,await b(!0)},resize:async(e,t)=>{if(e<1)throw Error(`Page size must be >= 1`);d=e,u=t,await b(!0)},sort:async e=>{f=Array.isArray(e)?e:[e],u=1,await b(!0)},filter:async e=>{p=e,u=1,await b(!0)},refresh:async e=>{let r=_.get()??v;await n.set({[t]:{...r,loading:!0}});let i=e?.delay??600;await Promise.all([new Promise(e=>setTimeout(e,i)),b(!1)]);let a=_.get()??v;await n.set({[t]:{...a,loading:!1}})},subscribe:e=>_.subscribe(t=>{e(t)}),invalidate:async()=>{await n.set({[t]:a}),r=[]}}}export{j as BlobNamespace,S as HestiaAuth,M as HestiaBlobClient,F as HestiaClient,x as HestiaCollection,N as HestiaCollections,w as HestiaKeyStore,O as HestiaLogs,g as HestiaNetworkClient,T as HestiaOperations,E as HestiaPolicies,m as HestiaResponse,D as HestiaRules,C as HestiaUsers,h as HttpTransport,v as WailsTransport,I as createArrayPager,b as createPagedController,p as internalError,d as notFound,l as parseErrorBody,f as permissionDenied,u as toSystemError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asaidimu/hestia",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "TypeScript client SDK for the Hestia platform — auth, collections, API keys, policies, audit logs, blobs, and capabilities",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -44,7 +44,7 @@
44
44
  "@asaidimu/utils-error": "^1.1.10",
45
45
  "@asaidimu/utils-schema": "^1.0.10",
46
46
  "@asaidimu/utils-store": "^10.2.18",
47
- "@asaidimu/utils-sync": "^2.3.0",
47
+ "@asaidimu/utils-sync": "^2.3.10",
48
48
  "uuid": "^14.0.1"
49
49
  }
50
50
  }