@asaidimu/hestia 1.4.6 → 1.4.7
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/index.cjs +2 -2
- package/index.d.cts +77 -79
- package/index.d.mts +51 -53
- package/index.mjs +2 -2
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -4,5 +4,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require
|
|
|
4
4
|
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());n.length>0&&t.onMessage(n.join(`
|
|
5
5
|
`)),r=c.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 p=f;function m(){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}}function h(){throw new t.SystemError({code:`HTTP_UNAVAILABLE`,message:`WailsTransport needs baseUrl and identityProvider for path-based requests. Use dispatch() instead.`})}var g=class{baseUrl=``;apiPrefix=``;init=new n.Once({throws:!0});config;http;onUnauthorized;constructor(e){this.config=e,this.baseUrl=e?.baseUrl??``,this.apiPrefix=e?.apiPrefix??`/api`,this.onUnauthorized=e?.onUnauthorized,e?.baseUrl&&(this.http=new f(e.baseUrl,this.apiPrefix,()=>this.onUnauthorized?.()))}setOnUnauthorized(e,t){this.onUnauthorized=e,this.http||=new f(this.baseUrl||`http://wails.local`,this.apiPrefix,()=>this.onUnauthorized?.())}configure(e,t,n){this.baseUrl=e,this.apiPrefix=t,this.http||=new f(e,t,()=>this.onUnauthorized?.())}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return m()}base(){return this.baseUrl}prefix(){return this.apiPrefix}routeUrl(e,t){if(!this.http)throw h();return this.http.routeUrl(e,t)}async ready(e=1e4){await 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,r){if(await this.ready(),this.http&&(r?.bodyType===`blob`||r?.bodyType===`stream`))return this.http.dispatch(e,r);let i=r?.notifyAuthStateChange??!0,a=r?.payload??null,o={...r?.modifiers??{}};r?.headers?.[`Content-Type`]&&(o.content_type=r.headers[`Content-Type`]);let s=this.resolveService();if(s?.Dispatch){let c;try{c=await s.Dispatch({name:e,arguments:r?.arguments??{},modifiers:o,payload:a})}catch(n){throw console.error(`[WailsTransport] dispatch "${e}" failed:`,n?.message??n),n instanceof t.SystemError?n:new t.SystemError({code:`DISPATCH_ERROR`,message:n?.message??String(n)})}if(c.status>=400){let r=c.data?.error,a=r?.code??`UNKNOWN`,o=r?.message??`dispatch returned status ${c.status}`;throw console.error(`[WailsTransport] dispatch "${e}" error [${a}]: ${o}`),c.status===401&&i&&(this.init=new n.Once({throws:!0}),this.onUnauthorized?.()),new t.SystemError({code:a,message:o})}return new d(c.data,c.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){if(await this.ready(),!this.http)throw h();return this.http.check(e,t,n)}async get(e,t){if(await this.ready(),!this.http)throw h();return this.http.get(e,t)}async post(e,t,n){if(await this.ready(),!this.http)throw h();return this.http.post(e,t,n)}async patch(e,t,n){if(await this.ready(),!this.http)throw h();return this.http.patch(e,t,n)}async put(e,t,n){if(await this.ready(),!this.http)throw h();return this.http.put(e,t,n)}async delete(e,t,n){if(await this.ready(),!this.http)throw h();return this.http.delete(e,t,n)}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 _=globalThis.requestIdleCallback?.bind(globalThis)??((e,t)=>{let n=performance.now(),r={didTimeout:!1,timeRemaining:()=>Math.max(0,50-(performance.now()-n))};return setTimeout(()=>e(r),t?.timeout==null?0:Math.min(t.timeout,0))}),v={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function y(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()=>{_(()=>{_(async()=>{try{let n=await a(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...v,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??v,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}),h()},id:()=>d}}var b=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=y(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}},x=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 await this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:users:user:create`,{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}})}},S=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=y(`users`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:collections: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({data:e}){if(!e)throw Error(`User creation requires email/password/name`);return(await this.client.dispatch(`system:users:user:create`,{payload:e})).data.data}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}})}},C=class{client;pager;constructor(e){this.client=e,this.pager=y(`_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}};function w(e){return{...e,_id_:e.name,_metadata_:{checksum:``,created:``,updated:``,version:1}}}var T=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:binding:list`)).data?.data?.bindings??[];return{data:e.map(e=>w(e)),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:binding:get`,{arguments:{name:e}});return t.data?.data?w(t.data.data):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=y(`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??[];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){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{return((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e||t.id===e)||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={rule:e.data.rule??``,rateLimit:e.data.rateLimit,throttle:e.data.throttle};return(await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n})).data.data}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);let n={};return e.data.rule!==void 0&&(n.rule=e.data.rule),e.data.enabled!==void 0&&(n.enabled=e.data.enabled),e.data.rateLimit!==void 0&&(n.rateLimit=e.data.rateLimit),e.data.throttle!==void 0&&(n.throttle=e.data.throttle),(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:n})).data.data}async setEnabled(e,t){return(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data}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=y(`_audit_log_`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/collections/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`}};const k=.3;function A(e){return new Promise(t=>setTimeout(t,e))}async function j(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}function M(e,t,n){return e.slice(t,n)}function N(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`upload_`+Date.now()+`_`+Math.random().toString(36).slice(2)}function P(e,t){let n=[],r=0;for(let t of e)t.start>r&&n.push({start:r,end:t.start}),t.end>r&&(r=t.end);return r<t&&n.push({start:r,end:t}),n}function F(e,t){let n=0,r=e.length?e[0].start:0;function i(){for(;n<e.length&&r>=e[n].end;)n++,n<e.length&&(r=e[n].start)}return{hasMore(){return i(),n<e.length},next(){if(i(),n>=e.length)return null;let a=Math.min(r+t,e[n].end),o={start:r,end:a};return r=a,o}}}var I=class{maxConcurrency;consecutiveSuccesses=0;lastBackoff=0;throughputEstimate;constructor(e,t=262144){this.maxConcurrency=e,this.throughputEstimate=t}estThroughput(){return this.throughputEstimate}recordThroughput(e){this.throughputEstimate=this.throughputEstimate*(1-k)+e*k}recordSuccess(){this.consecutiveSuccesses++,this.consecutiveSuccesses>=3&&(this.consecutiveSuccesses=0,this.maxConcurrency=Math.min(6,this.maxConcurrency+1))}recordFailure(){let e=Date.now();e-this.lastBackoff<2500||(this.lastBackoff=e,this.consecutiveSuccesses=0,this.maxConcurrency=Math.max(1,Math.floor(this.maxConcurrency/2)))}},L=class{backing;state={jobs:{}};instanceId=N();ready;constructor(e){this.backing=e,this.ready=this.hydrate()}async hydrate(){if(!this.backing)return;let e=await this.backing.get();e&&(this.state=e)}async save(e){await this.ready,this.state={jobs:{...this.state.jobs,[e.id]:e}},await this.backing?.set(this.instanceId,this.state)}async load(){if(await this.ready,this.backing){let e=await this.backing.get();e&&(this.state=e)}return Object.values(this.state.jobs)}async remove(e){await this.ready;let t={...this.state.jobs};delete t[e],this.state={jobs:t},await this.backing?.set(this.instanceId,this.state)}},R=class{id;status=`queued`;blockSize=0;sessionId=null;uploaded=0;hashed=0;hashTotal=0;bytesPerSecond=0;etaSeconds=0;fingerprint=``;error=null;onStatusChange;get done(){return this.attempt}total;key;file;options;transport;persistence;aimd;startedAt=Date.now();blockHashes=[];pauseRequested=!1;cancelRequested=!1;abortControllers=new Set;running=!1;lastProgressTime=0;lastProgressBytes=0;speedSamples=[];lastReportAt=0;attempt;resolveDone;rejectDone;constructor(e,t,n,r,i,a){this.transport=e,this.file=t,this.key=n,this.options=r,this.persistence=i,this.id=a?.id??N(),this.total=a?.size??t.size,this.blockSize=a?.blockSize??0,this.sessionId=a?.sessionId??null,this.blockHashes=a?.blockHashes??[],this.fingerprint=a?.fingerprint??``,this.uploaded=a?.uploadedBytes??0,this.status=a?`paused`:`queued`,this.aimd=new I(Math.max(1,r.concurrency??4)),this.newAttempt(),r.signal&&(r.signal.aborted?queueMicrotask(()=>void this.cancel()):r.signal.addEventListener(`abort`,()=>void this.cancel(),{once:!0}))}newAttempt(){this.attempt=new Promise((e,t)=>{this.resolveDone=e,this.rejectDone=t})}start(){this.status===`queued`&&(this.pauseRequested=!1,this.cancelRequested=!1,this.run())}resume(){(this.status===`paused`||this.status===`error`)&&(this.status===`error`&&this.newAttempt(),this.error=null,this.pauseRequested=!1,this.cancelRequested=!1,this.run())}retry(){this.resume()}pause(){if(this.status!==`completed`&&this.status!==`cancelled`){this.pauseRequested=!0;for(let e of this.abortControllers)e.abort();this.running||(this.setStatus(`paused`),this.report(),this.persist())}}async cancel(){if(this.status!==`completed`&&this.status!==`cancelled`){this.cancelRequested=!0;for(let e of this.abortControllers)e.abort();if(this.sessionId)try{await this.transport.abort(this.sessionId)}catch{}await this.persistence?.remove(this.id),this.running||(this.setStatus(`cancelled`),this.report(),this.resolveDone(void 0))}}async run(){if(!(this.running||this.status===`completed`||this.status===`cancelled`)){this.running=!0;try{if(this.blockSize===0&&(this.blockSize=this.chooseBlockSize(),await this.persist()),!this.sessionId){let e=await this.transport.beginUpload({key:this.key,size:this.total,contentType:this.options.contentType||this.file.type,blockSize:this.blockSize,overwrite:this.options.overwrite});this.sessionId=e.session_id,this.blockHashes.length===0&&e.block_size>0&&(this.blockSize=e.block_size),await this.persist()}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.blockHashes.length===0&&this.blockSize>0&&(this.setStatus(`hashing`),await this.hashBlocks()),this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.cancelRequested){this.finishCancelled();return}for(this.setStatus(`uploading`);!this.cancelRequested&&!this.pauseRequested;){if(!this.sessionId)throw Error(`upload session missing`);let e=await this.transport.progress(this.sessionId);if(this.uploaded=e.total,this.report(),this.uploaded>=this.total)break;let t=P(e.ranges??[],this.total);if(t.length===0)break;let n=await this.runUploadPool(t);if(n.cancelled)break;if(n.paused){this.setStatus(`paused`),this.report(),await this.persist();return}}if(this.cancelRequested){this.finishCancelled();return}if(!this.sessionId)throw Error(`upload session missing`);this.setStatus(`completing`),this.report();let e=await this.transport.completeUpload({sessionId:this.sessionId,overwrite:this.options.overwrite});this.uploaded=this.total,this.setStatus(`completed`),this.report(),await this.persistence?.remove(this.id),this.resolveDone(e)}catch(e){if(this.cancelRequested){this.finishCancelled();return}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}this.error=e instanceof Error?e:Error(String(e)),this.setStatus(`error`),this.report(),await this.persist(),this.rejectDone(this.error)}finally{this.running=!1}}}finishCancelled(){this.setStatus(`cancelled`),this.report(),this.persistence?.remove(this.id),this.resolveDone(void 0)}chooseBlockSize(){let e=this.options.blockSize??8388608;return this.total<=0?0:Math.min(e,this.total)}async hashBlocks(){let e=this.blockSize,t=Math.ceil(this.total/e);this.blockHashes=Array(t),this.hashTotal=this.total,this.hashed=0;let n=performance.now();for(let r=0;r<t;r++){if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);for(;this.pauseRequested&&!this.cancelRequested;)await A(200);if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);let t=r*e,i=Math.min(t+e,this.total),a=await M(this.file,t,i).arrayBuffer();this.blockHashes[r]=await j(a),this.hashed=i,this.report();let o=performance.now();o-n>12&&(await A(0),n=o)}let r=this.blockHashes.join(``);this.fingerprint=await j(new TextEncoder().encode(r)),await this.persist()}runUploadPool(e){return new Promise(t=>{let n=F(e,this.blockSize),r=!1,i=null,a=!1,o=0,s=()=>{r||o>0||(r=!0,i?(this.failPool(i),t({paused:!1,cancelled:!1})):t({paused:a&&!this.cancelRequested,cancelled:this.cancelRequested}))},c=()=>{o++,(async()=>{for(;!this.cancelRequested;){if(this.pauseRequested){a=!0;break}if(i||o>this.aimd.maxConcurrency)break;let e=n.next();if(!e)break;let t=await this.uploadOneChunk(e);if(!t.success){t.aborted?this.pauseRequested&&(a=!0):i=Error(`Chunk failed at ${e.start}`);break}}})().finally(()=>{o--,!this.cancelRequested&&!this.pauseRequested&&!i&&o<this.aimd.maxConcurrency&&n.hasMore()&&c(),s()})},l=Math.max(1,this.aimd.maxConcurrency),u=0;for(let e=0;e<l&&n.hasMore();e++)c(),u++;u===0&&s()})}failPool(e){this.status!==`completed`&&this.status!==`cancelled`&&(this.error=e,this.setStatus(`error`),this.report(),this.persist(),this.rejectDone(this.error))}async uploadOneChunk(e){let t=M(this.file,e.start,e.end);if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let n=Math.floor(e.start/this.blockSize),r=this.blockHashes[n],i=Math.max(0,this.options.retries??3),a=e.end-e.start;for(let n=1;n<=i+1;n++){if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let o=new AbortController;this.abortControllers.add(o);let s=Math.max(this.aimd.estThroughput(),32*1024),c=Math.max(6e3,a/s*1e3*3),l=setTimeout(()=>o.abort(),c),u=performance.now();try{if(!this.sessionId)throw Error(`upload session missing`);let n=await this.transport.uploadChunk({sessionId:this.sessionId,offset:e.start,data:t,sha256:r,signal:o.signal});clearTimeout(l),this.abortControllers.delete(o);let i=(performance.now()-u)/1e3;return this.aimd.recordSuccess(),this.onChunkUploaded(a,i,n),{success:!0,aborted:!1}}catch(e){if(clearTimeout(l),this.abortControllers.delete(o),this.cancelRequested||this.pauseRequested&&e instanceof DOMException&&e.name===`AbortError`)return{success:!1,aborted:!0};this.aimd.recordFailure(),n<=i&&await A(1500*2**(n-1))}}return{success:!1,aborted:!1}}onChunkUploaded(e,t,n){t>.05&&this.aimd.recordThroughput(e/t),this.uploaded=n;let r=Date.now();if(!this.lastProgressTime)this.lastProgressTime=r,this.lastProgressBytes=n;else if(r-this.lastProgressTime>1e3){let e=n-this.lastProgressBytes,t=(r-this.lastProgressTime)/1e3;if(t>0){let n=e/t;this.speedSamples.push(n),this.speedSamples.length>5&&this.speedSamples.shift()}this.lastProgressTime=r,this.lastProgressBytes=n}let i=this.speedSamples.length>0?this.speedSamples.reduce((e,t)=>e+t,0)/this.speedSamples.length:0;this.bytesPerSecond=i;let a=this.total-this.uploaded;this.etaSeconds=i>0&&a>0?a/i:0,this.report()}report(){let e=performance.now();if(this.status===`uploading`&&e-this.lastReportAt<80)return;this.lastReportAt=e;let t=this.status===`hashing`?`hash`:`upload`,n=t===`hash`?this.hashTotal>0?this.hashed/this.hashTotal:0:this.total>0?this.uploaded/this.total:1;this.options.onProgress?.({phase:t,hashed:this.hashed,hashTotal:this.hashTotal,uploaded:this.uploaded,total:this.total,percent:Math.min(1,n),bytesPerSecond:this.bytesPerSecond,etaSeconds:this.etaSeconds,fingerprint:this.fingerprint||void 0})}snapshot(){return{id:this.id,key:this.key,name:this.file.name,size:this.total,type:this.file.type,file:this.file,sessionId:this.sessionId,blockSize:this.blockSize,blockHashes:this.blockHashes,fingerprint:this.fingerprint,uploadedBytes:this.uploaded,status:this.status,error:this.error?this.error.message:null}}async persist(){if(this.persistence)try{await this.persistence.save(this.snapshot())}catch{}}setStatus(e){this.status!==e&&(this.status=e,this.onStatusChange?.(e))}},z=class{jobs=new Map;queue=[];active=0;runningJobs=new WeakSet;maxConcurrent;persistence;transport;ns;constructor(e,t,n={}){this.transport=e,this.ns=t,this.maxConcurrent=Math.max(1,n.maxConcurrent??3),this.persistence=n.persistence}enqueue(e,t){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);let r=new R(this.transport,e,n,t,this.persistence);return r.onStatusChange=e=>{if(e===`queued`)return;let t=e===`hashing`||e===`uploading`||e===`completing`,n=e===`paused`||e===`completed`||e===`error`||e===`cancelled`;if(t&&!this.runningJobs.has(r)?(this.runningJobs.add(r),this.active++,this.pump()):n&&this.runningJobs.has(r)&&(this.runningJobs.delete(r),this.active=Math.max(0,this.active-1),this.pump()),e===`cancelled`||e===`completed`){let e=this.queue.indexOf(r.id);e!==-1&&this.queue.splice(e,1)}},this.jobs.set(r.id,r),this.queue.push(r.id),this.pump(),r}pump(){for(;this.active<this.maxConcurrent&&this.queue.length>0;){let e=this.queue.shift();if(!e)continue;let t=this.jobs.get(e);t&&(this.runningJobs.add(t),this.active++,t.start())}}restore(e){return(this.persistence?this.persistence.load():Promise.resolve([]))instanceof Promise,[]}async restoreAsync(e){if(!this.persistence)return[];let t=await this.persistence.load(),n=[];for(let r of t){let t=r.file??e?.(r);if(!t)continue;let i=new R(this.transport,t,r.key,{key:r.key,contentType:r.type,overwrite:!1},this.persistence,r);this.jobs.set(i.id,i),n.push(i)}return n}pause(e){let t=this.jobs.get(e);if(t){if(t.status===`queued`){let t=this.queue.indexOf(e);t!==-1&&this.queue.splice(t,1)}t.pause()}}resume(e){this.jobs.get(e)?.resume()}retry(e){this.jobs.get(e)?.retry()}async cancel(e){let t=this.jobs.get(e);if(!t)return;let n=this.queue.indexOf(e);n!==-1&&this.queue.splice(n,1),await t.cancel()}pauseAll(){for(let e of this.jobs.values())(e.status===`uploading`||e.status===`hashing`||e.status===`queued`)&&e.pause()}resumeAll(){for(let e of this.jobs.values())(e.status===`paused`||e.status===`error`)&&e.resume()}clearCompleted(){for(let[e,t]of Array.from(this.jobs))(t.status===`completed`||t.status===`cancelled`)&&this.jobs.delete(e)}all(){return Array.from(this.jobs.values())}summary(){let e=this.all().filter(e=>[`uploading`,`hashing`,`queued`,`completing`].includes(e.status)),t=this.all().filter(e=>e.status===`paused`),n=this.all().filter(e=>e.status===`completed`),r=this.all().filter(e=>e.status===`cancelled`),i=this.all().filter(e=>e.status===`error`),a=0,o=0,s=0;for(let t of e)a+=t.total,o+=t.uploaded,s+=t.bytesPerSecond;let c=Math.max(0,a-o),l=s>0?c/s:0;return{active:e.length,paused:t.length,done:n.length,cancelled:r.length,failed:i.length,totalBytes:a,uploadedBytes:o,bytesPerSecond:s,etaSeconds:l}}};function B(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function V(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var H=class{client;ns;persistence;pagerOptions={};pager;prefixFilter=``;_queue;constructor(e,t,n){this.client=e,this.ns=t,this.persistence=n,this.pager=y(`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(B),loading:!1,page:V(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?B(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 B((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=e.options?.threshold??16777216;if(!e.options?.forceStaged&&e.file.size<=n)return this.uploadDirect(e.file,t,e.options);let r=this.createUpload(e.file,e.options);return r.start(),r.done}createUpload(e,t={}){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);return new R(this,e,n,t,this.persistence)}queue(e){return this._queue||=new z(this,this.ns,e),this._queue}async uploadDirect(e,t,n){let r={},i=n?.contentType||e.type;return i&&(r[`Content-Type`]=i),B((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},modifiers:n?.overwrite?{overwrite:`true`}:void 0,payload:e,headers:r,bodyType:`blob`})).data.data)}async beginUpload(e){return(await this.client.dispatch(`system:blobs:blob:begin`,{arguments:{ns:this.ns},modifiers:e.overwrite?{overwrite:`true`}:void 0,payload:{key:e.key,size:e.size,content_type:e.contentType,block_size:e.blockSize}})).data.data}async uploadChunk(e){let t={"X-Session-ID":e.sessionId,"X-Offset":String(e.offset)};return e.sha256&&(t[`X-Chunk-SHA256`]=e.sha256),(await this.client.dispatch(`system:blobs:blob:chunk`,{arguments:{ns:this.ns},headers:t,payload:e.data,bodyType:`blob`,signal:e.signal})).data.data.total}async completeUpload(e){return B((await this.client.dispatch(`system:blobs:blob:complete`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e.sessionId},modifiers:e.overwrite?{overwrite:`true`}:void 0})).data.data)}async progress(e){return(await this.client.dispatch(`system:blobs:blob:progress`,{arguments:{ns:this.ns},modifiers:{session_id:e}})).data.data}async abort(e){await this.client.dispatch(`system:blobs:blob:abort`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e}})}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}}},U=class{client;uploadPersistence;apiPrefix;constructor(e,t=`/api`,n){this.client=e,this.uploadPersistence=n,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.routeUrl(`system:blobs:blob:download`,{ns:e,key:t})}namespace(e){return new H(this.client,e,this.uploadPersistence)}},W=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 b(this.client,e)}},G=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:notifications:notification:list`)).data?.data??[]}async markRead(e){await this.client.dispatch(`system:notifications:notification:read`,{arguments:{notification_id:e}})}async markAllRead(){await this.client.dispatch(`system:notifications:read:all`)}async countUnread(){return(await this.client.dispatch(`system:notifications:unread:count`)).data?.data?.count??0}},K=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:schedules:schedule:create`,{payload:e})).data?.data?.id??``}async list(){return(await this.client.dispatch(`system:schedules:schedule:list`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:schedules:schedule:get`,{arguments:{id:e}})).data?.data??null}async update(e,t){await this.client.dispatch(`system:schedules:schedule:update`,{arguments:{id:e},payload:t})}async delete(e){await this.client.dispatch(`system:schedules:schedule:delete`,{arguments:{id:e}})}},q=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:settings:list`)).data?.data??[]}async get(e){try{return(await this.client.dispatch(`system:settings:get`,{arguments:{key:e}})).data?.data}catch{return}}async set(e,t){await this.client.dispatch(`system:settings:set`,{arguments:{key:e},payload:{value:t}})}async delete(e){await this.client.dispatch(`system:settings:delete`,{arguments:{key:e}})}},J=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`)}},Y=class{store;client;auth;users;keys;policies;rules;logs;collections;blobs;capabilities;notifications;schedules;settings;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`,i=()=>{t.clear(),this.onAuthStateChanged?.()};this.tokenProvider=t,e.transport instanceof g?(e.transport.configure(e.baseUrl,n,t),e.transport.setOnUnauthorized(i),this.client=e.transport):this.client=e.transport??new f(e.baseUrl,n,i),this.auth=new x(this.client,t),this.users=new S(this.client),this.keys=new C(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 W(this.client),this.blobs=new U(this.client,n,e.uploadPersistence),this.capabilities=new J(this.client),this.notifications=new G(this.client),this.schedules=new K(this.client),this.settings=new q(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}async authenticated(){if(this.tokenProvider.identity()===null)return!1;try{return await this.client.dispatch(`system:core:heartbeat`,{notifyAuthStateChange:!1}),!0}catch{return!1}}heartbeatTimer;defaultHeartbeatInterval=300*1e3;startHeartbeat(e){this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval,n=()=>{this.heartbeatTimer=setTimeout(async()=>{await this.#e(),n()},t)};n()}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0)}async#e(){try{await this.client.dispatch(`system:core:heartbeat`)}catch{}}collection(e){return this.collections.documents(e)}ready(){return this.client.ready()}};function X(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.AimdController=I,exports.BlobNamespace=H,exports.HestiaAuth=x,exports.HestiaBlobClient=U,exports.HestiaClient=Y,exports.HestiaCollection=b,exports.HestiaCollections=W,exports.HestiaKeyStore=C,exports.HestiaLogs=O,exports.HestiaNetworkClient=p,exports.HestiaNotificationStore=G,exports.HestiaOperations=T,exports.HestiaPolicies=E,exports.HestiaResponse=d,exports.HestiaRules=D,exports.HestiaScheduleStore=K,exports.HestiaSettingStore=q,exports.HestiaUsers=S,exports.HttpTransport=f,exports.ResumableUpload=R,exports.UploadJobStore=L,exports.UploadQueue=z,exports.WailsTransport=g,exports.createArrayPager=X,exports.createPagedController=y,exports.getMissingRanges=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`||t.onError?.(e instanceof Error?e:Error(String(e)))}finally{t.onClose?.()}}};const p=f;function m(){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}}function h(){throw new t.SystemError({code:`HTTP_UNAVAILABLE`,message:`WailsTransport needs baseUrl and identityProvider for path-based requests. Use dispatch() instead.`})}var g=class{baseUrl=``;apiPrefix=``;init=new n.Once({throws:!0});config;http;onUnauthorized;constructor(e){this.config=e,this.baseUrl=e?.baseUrl??``,this.apiPrefix=e?.apiPrefix??`/api`,this.onUnauthorized=e?.onUnauthorized,e?.baseUrl&&(this.http=new f(e.baseUrl,this.apiPrefix,()=>this.onUnauthorized?.()))}setOnUnauthorized(e,t){this.onUnauthorized=e,this.http||=new f(this.baseUrl||`http://wails.local`,this.apiPrefix,()=>this.onUnauthorized?.())}configure(e,t,n){this.baseUrl=e,this.apiPrefix=t,this.http||=new f(e,t,()=>this.onUnauthorized?.())}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return m()}base(){return this.baseUrl}prefix(){return this.apiPrefix}routeUrl(e,t){if(!this.http)throw h();return this.http.routeUrl(e,t)}async ready(e=1e4){await 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,r){if(await this.ready(),this.http&&(r?.bodyType===`blob`||r?.bodyType===`stream`))return this.http.dispatch(e,r);let i=r?.notifyAuthStateChange??!0,a=r?.payload??null,o={...r?.modifiers??{}};r?.headers?.[`Content-Type`]&&(o.content_type=r.headers[`Content-Type`]);let s=this.resolveService();if(s?.Dispatch){let c;try{c=await s.Dispatch({name:e,arguments:r?.arguments??{},modifiers:o,payload:a})}catch(n){throw console.error(`[WailsTransport] dispatch "${e}" failed:`,n?.message??n),n instanceof t.SystemError?n:new t.SystemError({code:`DISPATCH_ERROR`,message:n?.message??String(n)})}if(c.status>=400){let r=c.data?.error,a=r?.code??`UNKNOWN`,o=r?.message??`dispatch returned status ${c.status}`;throw console.error(`[WailsTransport] dispatch "${e}" error [${a}]: ${o}`),c.status===401&&i&&(this.init=new n.Once({throws:!0}),this.onUnauthorized?.()),new t.SystemError({code:a,message:o})}return new d(c.data,c.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){if(await this.ready(),!this.http)throw h();return this.http.check(e,t,n)}async get(e,t){if(await this.ready(),!this.http)throw h();return this.http.get(e,t)}async post(e,t,n){if(await this.ready(),!this.http)throw h();return this.http.post(e,t,n)}async patch(e,t,n){if(await this.ready(),!this.http)throw h();return this.http.patch(e,t,n)}async put(e,t,n){if(await this.ready(),!this.http)throw h();return this.http.put(e,t,n)}async delete(e,t,n){if(await this.ready(),!this.http)throw h();return this.http.delete(e,t,n)}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 _=globalThis.requestIdleCallback?.bind(globalThis)??((e,t)=>{let n=performance.now(),r={didTimeout:!1,timeRemaining:()=>Math.max(0,50-(performance.now()-n))};return setTimeout(()=>e(r),t?.timeout==null?0:Math.min(t.timeout,0))}),v={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function y(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()=>{_(()=>{_(async()=>{try{let n=await a(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...v,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??v,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}),h()},id:()=>d}}var b=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=y(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}},x=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 await this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:users:user:create`,{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}})}},S=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=y(`users`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:collections: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({data:e}){if(!e)throw Error(`User creation requires email/password/name`);return(await this.client.dispatch(`system:users:user:create`,{payload:e})).data.data}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}})}},C=class{client;pager;constructor(e){this.client=e,this.pager=y(`_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}};function w(e){let t=e;return{...e,_id_:t._id_??e.name,_metadata_:t._metadata_??{checksum:``,created:``,updated:``,version:1}}}var T=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:binding:list`)).data?.data?.bindings??[];return{data:e.map(e=>w(e)),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:binding:get`,{arguments:{name:e}});return t.data?.data?w(t.data.data):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=y(`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??[];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){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{return((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e||t.id===e)||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={rule:e.data.rule??``,rateLimit:e.data.rateLimit,throttle:e.data.throttle};return(await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n})).data.data}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);let n={};return e.data.rule!==void 0&&(n.rule=e.data.rule),e.data.enabled!==void 0&&(n.enabled=e.data.enabled),e.data.rateLimit!==void 0&&(n.rateLimit=e.data.rateLimit),e.data.throttle!==void 0&&(n.throttle=e.data.throttle),(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:n})).data.data}async setEnabled(e,t){return(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data}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=y(`_audit_log_`,new r.ReactiveDataStore({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/collections/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`}};const k=.3;function A(e){return new Promise(t=>setTimeout(t,e))}async function j(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}function M(e,t,n){return e.slice(t,n)}function N(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`upload_`+Date.now()+`_`+Math.random().toString(36).slice(2)}function P(e,t){let n=[],r=0;for(let t of e)t.start>r&&n.push({start:r,end:t.start}),t.end>r&&(r=t.end);return r<t&&n.push({start:r,end:t}),n}function F(e,t){let n=0,r=e.length?e[0].start:0;function i(){for(;n<e.length&&r>=e[n].end;)n++,n<e.length&&(r=e[n].start)}return{hasMore(){return i(),n<e.length},next(){if(i(),n>=e.length)return null;let a=Math.min(r+t,e[n].end),o={start:r,end:a};return r=a,o}}}var I=class{maxConcurrency;consecutiveSuccesses=0;lastBackoff=0;throughputEstimate;constructor(e,t=262144){this.maxConcurrency=e,this.throughputEstimate=t}estThroughput(){return this.throughputEstimate}recordThroughput(e){this.throughputEstimate=this.throughputEstimate*(1-k)+e*k}recordSuccess(){this.consecutiveSuccesses++,this.consecutiveSuccesses>=3&&(this.consecutiveSuccesses=0,this.maxConcurrency=Math.min(6,this.maxConcurrency+1))}recordFailure(){let e=Date.now();e-this.lastBackoff<2500||(this.lastBackoff=e,this.consecutiveSuccesses=0,this.maxConcurrency=Math.max(1,Math.floor(this.maxConcurrency/2)))}},L=class{backing;state={jobs:{}};instanceId=N();ready;constructor(e){this.backing=e,this.ready=this.hydrate()}async hydrate(){if(!this.backing)return;let e=await this.backing.get();e&&(this.state=e)}async save(e){await this.ready,this.state={jobs:{...this.state.jobs,[e.id]:e}},await this.backing?.set(this.instanceId,this.state)}async load(){if(await this.ready,this.backing){let e=await this.backing.get();e&&(this.state=e)}return Object.values(this.state.jobs)}async remove(e){await this.ready;let t={...this.state.jobs};delete t[e],this.state={jobs:t},await this.backing?.set(this.instanceId,this.state)}},R=class{id;status=`queued`;blockSize=0;sessionId=null;uploaded=0;hashed=0;hashTotal=0;bytesPerSecond=0;etaSeconds=0;fingerprint=``;error=null;onStatusChange;get done(){return this.attempt}total;key;file;options;transport;persistence;aimd;startedAt=Date.now();blockHashes=[];pauseRequested=!1;cancelRequested=!1;abortControllers=new Set;running=!1;lastProgressTime=0;lastProgressBytes=0;speedSamples=[];lastReportAt=0;attempt;resolveDone;rejectDone;constructor(e,t,n,r,i,a){this.transport=e,this.file=t,this.key=n,this.options=r,this.persistence=i,this.id=a?.id??N(),this.total=a?.size??t.size,this.blockSize=a?.blockSize??0,this.sessionId=a?.sessionId??null,this.blockHashes=a?.blockHashes??[],this.fingerprint=a?.fingerprint??``,this.uploaded=a?.uploadedBytes??0,this.status=a?`paused`:`queued`,this.aimd=new I(Math.max(1,r.concurrency??4)),this.newAttempt(),r.signal&&(r.signal.aborted?queueMicrotask(()=>void this.cancel()):r.signal.addEventListener(`abort`,()=>void this.cancel(),{once:!0}))}newAttempt(){this.attempt=new Promise((e,t)=>{this.resolveDone=e,this.rejectDone=t})}start(){this.status===`queued`&&(this.pauseRequested=!1,this.cancelRequested=!1,this.run())}resume(){(this.status===`paused`||this.status===`error`)&&(this.status===`error`&&this.newAttempt(),this.error=null,this.pauseRequested=!1,this.cancelRequested=!1,this.run())}retry(){this.resume()}pause(){if(this.status!==`completed`&&this.status!==`cancelled`){this.pauseRequested=!0;for(let e of this.abortControllers)e.abort();this.running||(this.setStatus(`paused`),this.report(),this.persist())}}async cancel(){if(this.status!==`completed`&&this.status!==`cancelled`){this.cancelRequested=!0;for(let e of this.abortControllers)e.abort();if(this.sessionId)try{await this.transport.abort(this.sessionId)}catch{}await this.persistence?.remove(this.id),this.running||(this.setStatus(`cancelled`),this.report(),this.resolveDone(void 0))}}async run(){if(!(this.running||this.status===`completed`||this.status===`cancelled`)){this.running=!0;try{if(this.blockSize===0&&(this.blockSize=this.chooseBlockSize(),await this.persist()),!this.sessionId){let e=await this.transport.beginUpload({key:this.key,size:this.total,contentType:this.options.contentType||this.file.type,blockSize:this.blockSize,overwrite:this.options.overwrite});this.sessionId=e.session_id,this.blockHashes.length===0&&e.block_size>0&&(this.blockSize=e.block_size),await this.persist()}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.blockHashes.length===0&&this.blockSize>0&&(this.setStatus(`hashing`),await this.hashBlocks()),this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.cancelRequested){this.finishCancelled();return}for(this.setStatus(`uploading`);!this.cancelRequested&&!this.pauseRequested;){if(!this.sessionId)throw Error(`upload session missing`);let e=await this.transport.progress(this.sessionId);if(this.uploaded=e.total,this.report(),this.uploaded>=this.total)break;let t=P(e.ranges??[],this.total);if(t.length===0)break;let n=await this.runUploadPool(t);if(n.cancelled)break;if(n.paused){this.setStatus(`paused`),this.report(),await this.persist();return}}if(this.cancelRequested){this.finishCancelled();return}if(!this.sessionId)throw Error(`upload session missing`);this.setStatus(`completing`),this.report();let e=await this.transport.completeUpload({sessionId:this.sessionId,overwrite:this.options.overwrite});this.uploaded=this.total,this.setStatus(`completed`),this.report(),await this.persistence?.remove(this.id),this.resolveDone(e)}catch(e){if(this.cancelRequested){this.finishCancelled();return}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}this.error=e instanceof Error?e:Error(String(e)),this.setStatus(`error`),this.report(),await this.persist(),this.rejectDone(this.error)}finally{this.running=!1}}}finishCancelled(){this.setStatus(`cancelled`),this.report(),this.persistence?.remove(this.id),this.resolveDone(void 0)}chooseBlockSize(){let e=this.options.blockSize??8388608;return this.total<=0?0:Math.min(e,this.total)}async hashBlocks(){let e=this.blockSize,t=Math.ceil(this.total/e);this.blockHashes=Array(t),this.hashTotal=this.total,this.hashed=0;let n=performance.now();for(let r=0;r<t;r++){if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);for(;this.pauseRequested&&!this.cancelRequested;)await A(200);if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);let t=r*e,i=Math.min(t+e,this.total),a=await M(this.file,t,i).arrayBuffer();this.blockHashes[r]=await j(a),this.hashed=i,this.report();let o=performance.now();o-n>12&&(await A(0),n=o)}let r=this.blockHashes.join(``);this.fingerprint=await j(new TextEncoder().encode(r)),await this.persist()}runUploadPool(e){return new Promise(t=>{let n=F(e,this.blockSize),r=!1,i=null,a=!1,o=0,s=()=>{r||o>0||(r=!0,i?(this.failPool(i),t({paused:!1,cancelled:!1})):t({paused:a&&!this.cancelRequested,cancelled:this.cancelRequested}))},c=()=>{o++,(async()=>{for(;!this.cancelRequested;){if(this.pauseRequested){a=!0;break}if(i||o>this.aimd.maxConcurrency)break;let e=n.next();if(!e)break;let t=await this.uploadOneChunk(e);if(!t.success){t.aborted?this.pauseRequested&&(a=!0):i=Error(`Chunk failed at ${e.start}`);break}}})().finally(()=>{o--,!this.cancelRequested&&!this.pauseRequested&&!i&&o<this.aimd.maxConcurrency&&n.hasMore()&&c(),s()})},l=Math.max(1,this.aimd.maxConcurrency),u=0;for(let e=0;e<l&&n.hasMore();e++)c(),u++;u===0&&s()})}failPool(e){this.status!==`completed`&&this.status!==`cancelled`&&(this.error=e,this.setStatus(`error`),this.report(),this.persist(),this.rejectDone(this.error))}async uploadOneChunk(e){let t=M(this.file,e.start,e.end);if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let n=Math.floor(e.start/this.blockSize),r=this.blockHashes[n],i=Math.max(0,this.options.retries??3),a=e.end-e.start;for(let n=1;n<=i+1;n++){if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let o=new AbortController;this.abortControllers.add(o);let s=Math.max(this.aimd.estThroughput(),32*1024),c=Math.max(6e3,a/s*1e3*3),l=setTimeout(()=>o.abort(),c),u=performance.now();try{if(!this.sessionId)throw Error(`upload session missing`);let n=await this.transport.uploadChunk({sessionId:this.sessionId,offset:e.start,data:t,sha256:r,signal:o.signal});clearTimeout(l),this.abortControllers.delete(o);let i=(performance.now()-u)/1e3;return this.aimd.recordSuccess(),this.onChunkUploaded(a,i,n),{success:!0,aborted:!1}}catch(e){if(clearTimeout(l),this.abortControllers.delete(o),this.cancelRequested||this.pauseRequested&&e instanceof DOMException&&e.name===`AbortError`)return{success:!1,aborted:!0};this.aimd.recordFailure(),n<=i&&await A(1500*2**(n-1))}}return{success:!1,aborted:!1}}onChunkUploaded(e,t,n){t>.05&&this.aimd.recordThroughput(e/t),this.uploaded=n;let r=Date.now();if(!this.lastProgressTime)this.lastProgressTime=r,this.lastProgressBytes=n;else if(r-this.lastProgressTime>1e3){let e=n-this.lastProgressBytes,t=(r-this.lastProgressTime)/1e3;if(t>0){let n=e/t;this.speedSamples.push(n),this.speedSamples.length>5&&this.speedSamples.shift()}this.lastProgressTime=r,this.lastProgressBytes=n}let i=this.speedSamples.length>0?this.speedSamples.reduce((e,t)=>e+t,0)/this.speedSamples.length:0;this.bytesPerSecond=i;let a=this.total-this.uploaded;this.etaSeconds=i>0&&a>0?a/i:0,this.report()}report(){let e=performance.now();if(this.status===`uploading`&&e-this.lastReportAt<80)return;this.lastReportAt=e;let t=this.status===`hashing`?`hash`:`upload`,n=t===`hash`?this.hashTotal>0?this.hashed/this.hashTotal:0:this.total>0?this.uploaded/this.total:1;this.options.onProgress?.({phase:t,hashed:this.hashed,hashTotal:this.hashTotal,uploaded:this.uploaded,total:this.total,percent:Math.min(1,n),bytesPerSecond:this.bytesPerSecond,etaSeconds:this.etaSeconds,fingerprint:this.fingerprint||void 0})}snapshot(){return{id:this.id,key:this.key,name:this.file.name,size:this.total,type:this.file.type,file:this.file,sessionId:this.sessionId,blockSize:this.blockSize,blockHashes:this.blockHashes,fingerprint:this.fingerprint,uploadedBytes:this.uploaded,status:this.status,error:this.error?this.error.message:null}}async persist(){if(this.persistence)try{await this.persistence.save(this.snapshot())}catch{}}setStatus(e){this.status!==e&&(this.status=e,this.onStatusChange?.(e))}},z=class{jobs=new Map;queue=[];active=0;runningJobs=new WeakSet;maxConcurrent;persistence;transport;ns;constructor(e,t,n={}){this.transport=e,this.ns=t,this.maxConcurrent=Math.max(1,n.maxConcurrent??3),this.persistence=n.persistence}enqueue(e,t){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);let r=new R(this.transport,e,n,t,this.persistence);return r.onStatusChange=e=>{if(e===`queued`)return;let t=e===`hashing`||e===`uploading`||e===`completing`,n=e===`paused`||e===`completed`||e===`error`||e===`cancelled`;if(t&&!this.runningJobs.has(r)?(this.runningJobs.add(r),this.active++,this.pump()):n&&this.runningJobs.has(r)&&(this.runningJobs.delete(r),this.active=Math.max(0,this.active-1),this.pump()),e===`cancelled`||e===`completed`){let e=this.queue.indexOf(r.id);e!==-1&&this.queue.splice(e,1)}},this.jobs.set(r.id,r),this.queue.push(r.id),this.pump(),r}pump(){for(;this.active<this.maxConcurrent&&this.queue.length>0;){let e=this.queue.shift();if(!e)continue;let t=this.jobs.get(e);t&&(this.runningJobs.add(t),this.active++,t.start())}}restore(e){return(this.persistence?this.persistence.load():Promise.resolve([]))instanceof Promise,[]}async restoreAsync(e){if(!this.persistence)return[];let t=await this.persistence.load(),n=[];for(let r of t){let t=r.file??e?.(r);if(!t)continue;let i=new R(this.transport,t,r.key,{key:r.key,contentType:r.type,overwrite:!1},this.persistence,r);this.jobs.set(i.id,i),n.push(i)}return n}pause(e){let t=this.jobs.get(e);if(t){if(t.status===`queued`){let t=this.queue.indexOf(e);t!==-1&&this.queue.splice(t,1)}t.pause()}}resume(e){this.jobs.get(e)?.resume()}retry(e){this.jobs.get(e)?.retry()}async cancel(e){let t=this.jobs.get(e);if(!t)return;let n=this.queue.indexOf(e);n!==-1&&this.queue.splice(n,1),await t.cancel()}pauseAll(){for(let e of this.jobs.values())(e.status===`uploading`||e.status===`hashing`||e.status===`queued`)&&e.pause()}resumeAll(){for(let e of this.jobs.values())(e.status===`paused`||e.status===`error`)&&e.resume()}clearCompleted(){for(let[e,t]of Array.from(this.jobs))(t.status===`completed`||t.status===`cancelled`)&&this.jobs.delete(e)}all(){return Array.from(this.jobs.values())}summary(){let e=this.all().filter(e=>[`uploading`,`hashing`,`queued`,`completing`].includes(e.status)),t=this.all().filter(e=>e.status===`paused`),n=this.all().filter(e=>e.status===`completed`),r=this.all().filter(e=>e.status===`cancelled`),i=this.all().filter(e=>e.status===`error`),a=0,o=0,s=0;for(let t of e)a+=t.total,o+=t.uploaded,s+=t.bytesPerSecond;let c=Math.max(0,a-o),l=s>0?c/s:0;return{active:e.length,paused:t.length,done:n.length,cancelled:r.length,failed:i.length,totalBytes:a,uploadedBytes:o,bytesPerSecond:s,etaSeconds:l}}};function B(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function V(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var H=class{client;ns;persistence;pagerOptions={};pager;prefixFilter=``;_queue;constructor(e,t,n){this.client=e,this.ns=t,this.persistence=n,this.pager=y(`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(B),loading:!1,page:V(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?B(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 B((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=e.options?.threshold??16777216;if(!e.options?.forceStaged&&e.file.size<=n)return this.uploadDirect(e.file,t,e.options);let r=this.createUpload(e.file,e.options);return r.start(),r.done}createUpload(e,t={}){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);return new R(this,e,n,t,this.persistence)}queue(e){return this._queue||=new z(this,this.ns,e),this._queue}async uploadDirect(e,t,n){let r={},i=n?.contentType||e.type;return i&&(r[`Content-Type`]=i),B((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},modifiers:n?.overwrite?{overwrite:`true`}:void 0,payload:e,headers:r,bodyType:`blob`})).data.data)}async beginUpload(e){return(await this.client.dispatch(`system:blobs:blob:begin`,{arguments:{ns:this.ns},modifiers:e.overwrite?{overwrite:`true`}:void 0,payload:{key:e.key,size:e.size,content_type:e.contentType,block_size:e.blockSize}})).data.data}async uploadChunk(e){let t={"X-Session-ID":e.sessionId,"X-Offset":String(e.offset)};return e.sha256&&(t[`X-Chunk-SHA256`]=e.sha256),(await this.client.dispatch(`system:blobs:blob:chunk`,{arguments:{ns:this.ns},headers:t,payload:e.data,bodyType:`blob`,signal:e.signal})).data.data.total}async completeUpload(e){return B((await this.client.dispatch(`system:blobs:blob:complete`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e.sessionId},modifiers:e.overwrite?{overwrite:`true`}:void 0})).data.data)}async progress(e){return(await this.client.dispatch(`system:blobs:blob:progress`,{arguments:{ns:this.ns},modifiers:{session_id:e}})).data.data}async abort(e){await this.client.dispatch(`system:blobs:blob:abort`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e}})}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}}},U=class{client;uploadPersistence;apiPrefix;constructor(e,t=`/api`,n){this.client=e,this.uploadPersistence=n,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`,{arguments:{ns:e.ns},payload:{display_name:e.display_name}})).data.data}async deleteNamespace(e){await this.client.dispatch(`system:blobs:namespace:delete`,{arguments:{ns:e}})}blob(e,t){return this.client.routeUrl(`system:blobs:blob:download`,{ns:e,key:t})}namespace(e){return new H(this.client,e,this.uploadPersistence)}},W=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:collections:collection: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){try{let t=await this.client.dispatch(`system:collections:collection:get`,{arguments:{name:e}});return t.data?t.data.data:void 0}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){let t=e.data.schema??e.data;return(await this.client.dispatch(`system:collections:collection:create`,{payload:t})).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 b(this.client,e)}},G=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:notifications:notification:list`)).data?.data??[]}async markRead(e){await this.client.dispatch(`system:notifications:notification:read`,{arguments:{notification_id:e}})}async markAllRead(){await this.client.dispatch(`system:notifications:read:all`)}async countUnread(){return(await this.client.dispatch(`system:notifications:unread:count`)).data?.data?.count??0}},K=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:schedules:schedule:create`,{payload:e})).data?.data?.id??``}async list(){return(await this.client.dispatch(`system:schedules:schedule:list`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:schedules:schedule:get`,{arguments:{id:e}})).data?.data??null}async update(e,t){await this.client.dispatch(`system:schedules:schedule:update`,{arguments:{id:e},payload:t})}async delete(e){await this.client.dispatch(`system:schedules:schedule:delete`,{arguments:{id:e}})}},q=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:settings:list`)).data?.data??[]}async get(e){try{return(await this.client.dispatch(`system:settings:get`,{arguments:{key:e}})).data?.data}catch{return}}async set(e,t){await this.client.dispatch(`system:settings:set`,{arguments:{key:e},payload:{value:t}})}async delete(e){await this.client.dispatch(`system:settings:delete`,{arguments:{key:e}})}},J=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`)}},Y=class{store;client;auth;users;keys;policies;rules;logs;collections;blobs;core;notifications;schedules;settings;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`,i=()=>{t.clear(),this.onAuthStateChanged?.()};this.tokenProvider=t,e.transport instanceof g?(e.transport.configure(e.baseUrl,n,t),e.transport.setOnUnauthorized(i),this.client=e.transport):this.client=e.transport??new f(e.baseUrl,n,i),this.auth=new x(this.client,t),this.users=new S(this.client),this.keys=new C(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 W(this.client),this.blobs=new U(this.client,n,e.uploadPersistence),this.core=new J(this.client),this.notifications=new G(this.client),this.schedules=new K(this.client),this.settings=new q(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}async authenticated(){if(this.tokenProvider.identity()===null)return!1;try{return await this.client.dispatch(`system:core:heartbeat`,{notifyAuthStateChange:!1}),!0}catch{return!1}}heartbeatTimer;defaultHeartbeatInterval=300*1e3;startHeartbeat(e){this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval,n=()=>{this.heartbeatTimer=setTimeout(async()=>{await this.#e(),n()},t)};n()}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0)}async#e(){try{await this.client.dispatch(`system:core:heartbeat`)}catch{}}collection(e){return this.collections.documents(e)}ready(){return this.client.ready()}};function X(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.AimdController=I,exports.BlobNamespace=H,exports.HestiaAuth=x,exports.HestiaBlobClient=U,exports.HestiaClient=Y,exports.HestiaCollection=b,exports.HestiaCollections=W,exports.HestiaCore=J,exports.HestiaKeyStore=C,exports.HestiaLogs=O,exports.HestiaNetworkClient=p,exports.HestiaNotificationStore=G,exports.HestiaOperations=T,exports.HestiaPolicies=E,exports.HestiaResponse=d,exports.HestiaRules=D,exports.HestiaScheduleStore=K,exports.HestiaSettingStore=q,exports.HestiaUsers=S,exports.HttpTransport=f,exports.ResumableUpload=R,exports.UploadJobStore=L,exports.UploadQueue=z,exports.WailsTransport=g,exports.createArrayPager=X,exports.createPagedController=y,exports.getMissingRanges=P,exports.internalError=l,exports.notFound=s,exports.parseErrorBody=a,exports.permissionDenied=c,exports.toSystemError=o;
|
package/index.d.cts
CHANGED
|
@@ -233,7 +233,7 @@ interface DocumentStore<T extends Record<string, any>, TFindOptions = Record<str
|
|
|
233
233
|
page(options: TPageOptions): PagedData<T>;
|
|
234
234
|
}
|
|
235
235
|
//#endregion
|
|
236
|
-
//#region system/
|
|
236
|
+
//#region system/users/types.d.ts
|
|
237
237
|
interface UserData {
|
|
238
238
|
email: string;
|
|
239
239
|
name: string;
|
|
@@ -829,7 +829,7 @@ interface PageOptions<T extends Record<string, any>> {
|
|
|
829
829
|
}
|
|
830
830
|
declare function createPagedController<T extends Record<string, any>>(collectionName: string, store: DataStore<any>, options: PageOptions<T>, find: (query: QueryDSL<T>) => Promise<Page<T>>): PagedData<T>;
|
|
831
831
|
//#endregion
|
|
832
|
-
//#region auth/types.d.ts
|
|
832
|
+
//#region system/auth/types.d.ts
|
|
833
833
|
interface LoginResult {
|
|
834
834
|
user: UserIdentity;
|
|
835
835
|
}
|
|
@@ -851,7 +851,7 @@ interface BootstrapPasswordRequest {
|
|
|
851
851
|
email: string;
|
|
852
852
|
}
|
|
853
853
|
//#endregion
|
|
854
|
-
//#region auth/store.d.ts
|
|
854
|
+
//#region system/auth/store.d.ts
|
|
855
855
|
declare class HestiaAuth {
|
|
856
856
|
private client;
|
|
857
857
|
private provider;
|
|
@@ -869,7 +869,7 @@ declare class HestiaAuth {
|
|
|
869
869
|
bootstrap(key: string, password: string, email: string): Promise<void>;
|
|
870
870
|
}
|
|
871
871
|
//#endregion
|
|
872
|
-
//#region system/
|
|
872
|
+
//#region system/users/store.d.ts
|
|
873
873
|
declare class HestiaUsers implements DocumentStore<UserData, QueryDSL<UserData>, string, QueryDSL<UserData>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
874
874
|
private client;
|
|
875
875
|
private pagerOptions;
|
|
@@ -901,7 +901,7 @@ declare class HestiaUsers implements DocumentStore<UserData, QueryDSL<UserData>,
|
|
|
901
901
|
changePassword(userId: string, current: string, newPassword: string): Promise<void>;
|
|
902
902
|
}
|
|
903
903
|
//#endregion
|
|
904
|
-
//#region system/
|
|
904
|
+
//#region system/apikeys/types.d.ts
|
|
905
905
|
interface APIKey {
|
|
906
906
|
_id_: string;
|
|
907
907
|
name: string;
|
|
@@ -931,7 +931,7 @@ interface UpdateKeyRequest {
|
|
|
931
931
|
expiry?: string;
|
|
932
932
|
}
|
|
933
933
|
//#endregion
|
|
934
|
-
//#region system/
|
|
934
|
+
//#region system/apikeys/store.d.ts
|
|
935
935
|
declare class HestiaKeyStore implements DocumentStore<APIKey, QueryDSL<APIKey>, string, QueryDSL<APIKey>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
936
936
|
private client;
|
|
937
937
|
private pager;
|
|
@@ -1018,40 +1018,6 @@ interface UpdatePolicyRequest {
|
|
|
1018
1018
|
rateLimit?: RateLimitConfig | null;
|
|
1019
1019
|
throttle?: ThrottleConfig | null;
|
|
1020
1020
|
}
|
|
1021
|
-
//#endregion
|
|
1022
|
-
//#region system/policies/store.d.ts
|
|
1023
|
-
declare class HestiaPolicies implements DocumentStore<Policy, QueryDSL<Policy>, string, QueryDSL<Policy>, Record<string, unknown>, string, string, string> {
|
|
1024
|
-
private client;
|
|
1025
|
-
private pager;
|
|
1026
|
-
constructor(client: Transport);
|
|
1027
|
-
find(_query?: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1028
|
-
query(qdsl: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1029
|
-
list(_options?: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1030
|
-
read(id: string): Promise<Document<Policy> | undefined>;
|
|
1031
|
-
create(props: {
|
|
1032
|
-
data: Partial<CreatePolicyRequest>;
|
|
1033
|
-
options?: string;
|
|
1034
|
-
}): Promise<Document<Policy> | undefined>;
|
|
1035
|
-
update(props: {
|
|
1036
|
-
data: UpdatePolicyRequest;
|
|
1037
|
-
options?: string;
|
|
1038
|
-
}): Promise<Document<Policy> | undefined>;
|
|
1039
|
-
setEnabled(name: string, enabled: boolean): Promise<Document<Policy>>;
|
|
1040
|
-
delete(_id: string): Promise<void>;
|
|
1041
|
-
upload(_props: {
|
|
1042
|
-
file: File;
|
|
1043
|
-
}): Promise<Document<Policy> | undefined>;
|
|
1044
|
-
subscribe(_scope: string, _callback: (event: StoreEvent) => void): Promise<() => void>;
|
|
1045
|
-
notify(_event: StoreEvent): Promise<void>;
|
|
1046
|
-
stream(_options: Record<string, unknown>, _onStreamChange: () => void): {
|
|
1047
|
-
stream: () => AsyncIterable<Document<Policy>>;
|
|
1048
|
-
cancel: () => void;
|
|
1049
|
-
status: () => "active" | "cancelled" | "completed";
|
|
1050
|
-
};
|
|
1051
|
-
page(_options?: Record<string, unknown>): PagedData<Policy>;
|
|
1052
|
-
}
|
|
1053
|
-
//#endregion
|
|
1054
|
-
//#region system/rules/types.d.ts
|
|
1055
1021
|
interface PolicyRule {
|
|
1056
1022
|
id: string;
|
|
1057
1023
|
name: string;
|
|
@@ -1102,7 +1068,39 @@ interface ReloadResult {
|
|
|
1102
1068
|
rules: number;
|
|
1103
1069
|
}
|
|
1104
1070
|
//#endregion
|
|
1105
|
-
//#region system/
|
|
1071
|
+
//#region system/policies/store.d.ts
|
|
1072
|
+
declare class HestiaPolicies implements DocumentStore<Policy, QueryDSL<Policy>, string, QueryDSL<Policy>, Record<string, unknown>, string, string, string> {
|
|
1073
|
+
private client;
|
|
1074
|
+
private pager;
|
|
1075
|
+
constructor(client: Transport);
|
|
1076
|
+
find(_query?: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1077
|
+
query(qdsl: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1078
|
+
list(_options?: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1079
|
+
read(id: string): Promise<Document<Policy> | undefined>;
|
|
1080
|
+
create(props: {
|
|
1081
|
+
data: Partial<CreatePolicyRequest>;
|
|
1082
|
+
options?: string;
|
|
1083
|
+
}): Promise<Document<Policy> | undefined>;
|
|
1084
|
+
update(props: {
|
|
1085
|
+
data: UpdatePolicyRequest;
|
|
1086
|
+
options?: string;
|
|
1087
|
+
}): Promise<Document<Policy> | undefined>;
|
|
1088
|
+
setEnabled(name: string, enabled: boolean): Promise<Document<Policy>>;
|
|
1089
|
+
delete(_id: string): Promise<void>;
|
|
1090
|
+
upload(_props: {
|
|
1091
|
+
file: File;
|
|
1092
|
+
}): Promise<Document<Policy> | undefined>;
|
|
1093
|
+
subscribe(_scope: string, _callback: (event: StoreEvent) => void): Promise<() => void>;
|
|
1094
|
+
notify(_event: StoreEvent): Promise<void>;
|
|
1095
|
+
stream(_options: Record<string, unknown>, _onStreamChange: () => void): {
|
|
1096
|
+
stream: () => AsyncIterable<Document<Policy>>;
|
|
1097
|
+
cancel: () => void;
|
|
1098
|
+
status: () => "active" | "cancelled" | "completed";
|
|
1099
|
+
};
|
|
1100
|
+
page(_options?: Record<string, unknown>): PagedData<Policy>;
|
|
1101
|
+
}
|
|
1102
|
+
//#endregion
|
|
1103
|
+
//#region system/policies/rules.d.ts
|
|
1106
1104
|
declare class HestiaRules implements DocumentStore<PolicyRule, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, string> {
|
|
1107
1105
|
private client;
|
|
1108
1106
|
constructor(client: Transport);
|
|
@@ -1133,7 +1131,7 @@ declare class HestiaRules implements DocumentStore<PolicyRule, Record<string, un
|
|
|
1133
1131
|
page(_options?: Record<string, unknown>): any;
|
|
1134
1132
|
}
|
|
1135
1133
|
//#endregion
|
|
1136
|
-
//#region system/
|
|
1134
|
+
//#region system/audit/types.d.ts
|
|
1137
1135
|
interface AuditEntry {
|
|
1138
1136
|
event_id: string;
|
|
1139
1137
|
occurred_at: string;
|
|
@@ -1171,7 +1169,7 @@ interface LogFilter {
|
|
|
1171
1169
|
end?: string;
|
|
1172
1170
|
}
|
|
1173
1171
|
//#endregion
|
|
1174
|
-
//#region system/
|
|
1172
|
+
//#region system/audit/store.d.ts
|
|
1175
1173
|
declare class HestiaLogs implements DocumentStore<AuditEntry, QueryDSL<AuditEntry>, string, QueryDSL<AuditEntry>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
1176
1174
|
private client;
|
|
1177
1175
|
private baseUrl;
|
|
@@ -1204,7 +1202,7 @@ declare class HestiaLogs implements DocumentStore<AuditEntry, QueryDSL<AuditEntr
|
|
|
1204
1202
|
getStreamUrl(): string;
|
|
1205
1203
|
}
|
|
1206
1204
|
//#endregion
|
|
1207
|
-
//#region blobs/types.d.ts
|
|
1205
|
+
//#region system/blobs/types.d.ts
|
|
1208
1206
|
interface NamespaceInfo {
|
|
1209
1207
|
id: string;
|
|
1210
1208
|
display_name: string;
|
|
@@ -1225,7 +1223,7 @@ interface ListBlobsRequest {
|
|
|
1225
1223
|
}
|
|
1226
1224
|
interface CreateNamespaceRequest {
|
|
1227
1225
|
display_name?: string;
|
|
1228
|
-
ns
|
|
1226
|
+
ns: string;
|
|
1229
1227
|
}
|
|
1230
1228
|
interface UploadBeginResult {
|
|
1231
1229
|
session_id: string;
|
|
@@ -1319,7 +1317,7 @@ interface UploadQueueOptions {
|
|
|
1319
1317
|
persistence?: UploadPersistence;
|
|
1320
1318
|
}
|
|
1321
1319
|
//#endregion
|
|
1322
|
-
//#region blobs/store.d.ts
|
|
1320
|
+
//#region system/blobs/store.d.ts
|
|
1323
1321
|
declare function getMissingRanges(ranges: {
|
|
1324
1322
|
start: number;
|
|
1325
1323
|
end: number;
|
|
@@ -1569,7 +1567,7 @@ declare class HestiaBlobClient {
|
|
|
1569
1567
|
namespace(ns: string): BlobNamespace;
|
|
1570
1568
|
}
|
|
1571
1569
|
//#endregion
|
|
1572
|
-
//#region collections/types.d.ts
|
|
1570
|
+
//#region system/collections/types.d.ts
|
|
1573
1571
|
interface CollectionMeta {
|
|
1574
1572
|
name: string;
|
|
1575
1573
|
schema: SchemaDefinition;
|
|
@@ -1577,10 +1575,10 @@ interface CollectionMeta {
|
|
|
1577
1575
|
updated: string;
|
|
1578
1576
|
}
|
|
1579
1577
|
type CollectionDocument = Document<{
|
|
1580
|
-
schema:
|
|
1578
|
+
schema: SchemaDefinition;
|
|
1581
1579
|
}>;
|
|
1582
1580
|
//#endregion
|
|
1583
|
-
//#region collections/store.d.ts
|
|
1581
|
+
//#region system/collections/store.d.ts
|
|
1584
1582
|
declare class HestiaCollections implements DocumentStore<CollectionMeta, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
1585
1583
|
private client;
|
|
1586
1584
|
constructor(client: Transport);
|
|
@@ -1709,6 +1707,34 @@ declare class HestiaSettingStore {
|
|
|
1709
1707
|
delete(key: string): Promise<void>;
|
|
1710
1708
|
}
|
|
1711
1709
|
//#endregion
|
|
1710
|
+
//#region system/core/store.d.ts
|
|
1711
|
+
declare class HestiaCore implements DocumentStore<any, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
1712
|
+
private client;
|
|
1713
|
+
constructor(client: Transport);
|
|
1714
|
+
find(_query?: Record<string, unknown>): Promise<Page<any>>;
|
|
1715
|
+
read(_id: string): Promise<Document<any> | undefined>;
|
|
1716
|
+
create(_props: {
|
|
1717
|
+
data: Partial<any>;
|
|
1718
|
+
}): Promise<Document<any> | undefined>;
|
|
1719
|
+
update(_props: {
|
|
1720
|
+
data: Partial<any>;
|
|
1721
|
+
options?: string;
|
|
1722
|
+
}): Promise<Document<any> | undefined>;
|
|
1723
|
+
delete(_id: string): Promise<void>;
|
|
1724
|
+
list(_options?: Record<string, unknown>): Promise<Page<any>>;
|
|
1725
|
+
upload(_props: {
|
|
1726
|
+
file: File;
|
|
1727
|
+
}): Promise<Document<any> | undefined>;
|
|
1728
|
+
subscribe(_scope: string, _callback: (event: StoreEvent) => void): Promise<() => void>;
|
|
1729
|
+
notify(_event: StoreEvent): Promise<void>;
|
|
1730
|
+
stream(_options: Record<string, unknown>, _onStreamChange: () => void): {
|
|
1731
|
+
stream: () => AsyncIterable<Document<any>>;
|
|
1732
|
+
cancel: () => void;
|
|
1733
|
+
status: () => "active" | "cancelled" | "completed";
|
|
1734
|
+
};
|
|
1735
|
+
page(_options?: Record<string, unknown>): PagedData<any>;
|
|
1736
|
+
}
|
|
1737
|
+
//#endregion
|
|
1712
1738
|
//#region dist/index.d.mts
|
|
1713
1739
|
//#region core/types.d.ts
|
|
1714
1740
|
interface DocumentMetadata {
|
|
@@ -2416,34 +2442,6 @@ declare class HestiaCollection$1<T extends Record<string, any>> implements Docum
|
|
|
2416
2442
|
page(_options?: Record<string, unknown>): PagedData$1<T>;
|
|
2417
2443
|
}
|
|
2418
2444
|
//#endregion
|
|
2419
|
-
//#region system/capabilities/store.d.ts
|
|
2420
|
-
declare class HestiaCapabilities implements DocumentStore<any, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
2421
|
-
private client;
|
|
2422
|
-
constructor(client: Transport);
|
|
2423
|
-
find(_query?: Record<string, unknown>): Promise<Page<any>>;
|
|
2424
|
-
read(_id: string): Promise<Document<any> | undefined>;
|
|
2425
|
-
create(_props: {
|
|
2426
|
-
data: Partial<any>;
|
|
2427
|
-
}): Promise<Document<any> | undefined>;
|
|
2428
|
-
update(_props: {
|
|
2429
|
-
data: Partial<any>;
|
|
2430
|
-
options?: string;
|
|
2431
|
-
}): Promise<Document<any> | undefined>;
|
|
2432
|
-
delete(_id: string): Promise<void>;
|
|
2433
|
-
list(_options?: Record<string, unknown>): Promise<Page<any>>;
|
|
2434
|
-
upload(_props: {
|
|
2435
|
-
file: File;
|
|
2436
|
-
}): Promise<Document<any> | undefined>;
|
|
2437
|
-
subscribe(_scope: string, _callback: (event: StoreEvent) => void): Promise<() => void>;
|
|
2438
|
-
notify(_event: StoreEvent): Promise<void>;
|
|
2439
|
-
stream(_options: Record<string, unknown>, _onStreamChange: () => void): {
|
|
2440
|
-
stream: () => AsyncIterable<Document<any>>;
|
|
2441
|
-
cancel: () => void;
|
|
2442
|
-
status: () => "active" | "cancelled" | "completed";
|
|
2443
|
-
};
|
|
2444
|
-
page(_options?: Record<string, unknown>): PagedData<any>;
|
|
2445
|
-
}
|
|
2446
|
-
//#endregion
|
|
2447
2445
|
//#region container.d.ts
|
|
2448
2446
|
interface HestiaConfig {
|
|
2449
2447
|
baseUrl: string;
|
|
@@ -2467,7 +2465,7 @@ declare class HestiaClient {
|
|
|
2467
2465
|
readonly logs: HestiaLogs;
|
|
2468
2466
|
readonly collections: HestiaCollections;
|
|
2469
2467
|
readonly blobs: HestiaBlobClient;
|
|
2470
|
-
readonly
|
|
2468
|
+
readonly core: HestiaCore;
|
|
2471
2469
|
readonly notifications: HestiaNotificationStore;
|
|
2472
2470
|
readonly schedules: HestiaScheduleStore;
|
|
2473
2471
|
readonly settings: HestiaSettingStore;
|
|
@@ -2501,4 +2499,4 @@ interface ArrayPagerOptions<T extends Record<string, any>, F = any> {
|
|
|
2501
2499
|
}
|
|
2502
2500
|
declare function createArrayPager<T extends Record<string, any>, F = any>(options: ArrayPagerOptions<T, F>): PagedData<T>;
|
|
2503
2501
|
//#endregion
|
|
2504
|
-
export { APIKey, APIKeyWithSecret, AimdController, ArrayPagerOptions, AuditEntry, Binding, BlobDocument, BlobMeta, BlobNamespace, BootstrapPasswordRequest, ChangePasswordRequest, CollectionDocument, CollectionMeta, CreateKeyRequest, CreateNamespaceRequest, CreatePolicyRequest, CreateRuleRequest, CreateSchedulePayload, CreateUserRequest, DispatchInput, Document, DocumentStore, FetchResult, HestiaAuth, HestiaBlobClient, HestiaClient, HestiaCollection, HestiaCollections, HestiaKeyStore, HestiaLogs, HestiaNetworkClient, HestiaNotificationStore, HestiaOperations, HestiaPolicies, HestiaResponse, HestiaRules, HestiaScheduleStore, HestiaSettingStore, HestiaUsers, HttpTransport, IdentityProvider, ListBlobsRequest, LogFilter, LoginRequest, LoginResult, NamespaceInfo, Notification, Page, PagedData, PagerRefreshOptions, PaginationInfo, Policy, PolicyRule, RateLimitConfig, RegisterRequest, ReloadResult, RequestLogEntry, RequestOptions, ResumableUpload, RuleNode, Schedule, ServerHealth, SetPolicyEnabledRequest, SettingDocument, StoreEvent, StreamHandlers, StreamOptions, ThrottleAction, ThrottleConfig, Transport, UnreadCount, UpdateKeyRequest, UpdatePolicyRequest, UpdatePolicyRuleRequest, UpdateRuleRequest, UpdateSchedulePayload, UpdateUserRequest, UploadBeginResult, UploadJobSnapshot, UploadJobStore, UploadJobsState, UploadOptions, UploadPersistence, UploadPhase, UploadProgressInfo, UploadProgressResult, UploadQueue, UploadQueueOptions, UploadStatus, UploadTransport, UserData, UserIdentity, ValidateRuleRequest, ValidateRuleResult, WailsTransport, createArrayPager, createPagedController, getMissingRanges, internalError, notFound, parseErrorBody, permissionDenied, toSystemError };
|
|
2502
|
+
export { APIKey, APIKeyWithSecret, AimdController, ArrayPagerOptions, AuditEntry, Binding, BlobDocument, BlobMeta, BlobNamespace, BootstrapPasswordRequest, ChangePasswordRequest, CollectionDocument, CollectionMeta, CreateKeyRequest, CreateNamespaceRequest, CreatePolicyRequest, CreateRuleRequest, CreateSchedulePayload, CreateUserRequest, DispatchInput, Document, DocumentStore, FetchResult, HestiaAuth, HestiaBlobClient, HestiaClient, HestiaCollection, HestiaCollections, HestiaCore, HestiaKeyStore, HestiaLogs, HestiaNetworkClient, HestiaNotificationStore, HestiaOperations, HestiaPolicies, HestiaResponse, HestiaRules, HestiaScheduleStore, HestiaSettingStore, HestiaUsers, HttpTransport, IdentityProvider, ListBlobsRequest, LogFilter, LoginRequest, LoginResult, NamespaceInfo, Notification, Page, PagedData, PagerRefreshOptions, PaginationInfo, Policy, PolicyRule, RateLimitConfig, RegisterRequest, ReloadResult, RequestLogEntry, RequestOptions, ResumableUpload, RuleNode, Schedule, ServerHealth, SetPolicyEnabledRequest, SettingDocument, StoreEvent, StreamHandlers, StreamOptions, ThrottleAction, ThrottleConfig, Transport, UnreadCount, UpdateKeyRequest, UpdatePolicyRequest, UpdatePolicyRuleRequest, UpdateRuleRequest, UpdateSchedulePayload, UpdateUserRequest, UploadBeginResult, UploadJobSnapshot, UploadJobStore, UploadJobsState, UploadOptions, UploadPersistence, UploadPhase, UploadProgressInfo, UploadProgressResult, UploadQueue, UploadQueueOptions, UploadStatus, UploadTransport, UserData, UserIdentity, ValidateRuleRequest, ValidateRuleResult, WailsTransport, createArrayPager, createPagedController, getMissingRanges, internalError, notFound, parseErrorBody, permissionDenied, toSystemError };
|
package/index.d.mts
CHANGED
|
@@ -233,7 +233,7 @@ interface DocumentStore<T extends Record<string, any>, TFindOptions = Record<str
|
|
|
233
233
|
page(options: TPageOptions): PagedData<T>;
|
|
234
234
|
}
|
|
235
235
|
//#endregion
|
|
236
|
-
//#region system/
|
|
236
|
+
//#region system/users/types.d.ts
|
|
237
237
|
interface UserData {
|
|
238
238
|
email: string;
|
|
239
239
|
name: string;
|
|
@@ -829,7 +829,7 @@ interface PageOptions<T extends Record<string, any>> {
|
|
|
829
829
|
}
|
|
830
830
|
declare function createPagedController<T extends Record<string, any>>(collectionName: string, store: DataStore<any>, options: PageOptions<T>, find: (query: QueryDSL<T>) => Promise<Page<T>>): PagedData<T>;
|
|
831
831
|
//#endregion
|
|
832
|
-
//#region auth/types.d.ts
|
|
832
|
+
//#region system/auth/types.d.ts
|
|
833
833
|
interface LoginResult {
|
|
834
834
|
user: UserIdentity;
|
|
835
835
|
}
|
|
@@ -851,7 +851,7 @@ interface BootstrapPasswordRequest {
|
|
|
851
851
|
email: string;
|
|
852
852
|
}
|
|
853
853
|
//#endregion
|
|
854
|
-
//#region auth/store.d.ts
|
|
854
|
+
//#region system/auth/store.d.ts
|
|
855
855
|
declare class HestiaAuth {
|
|
856
856
|
private client;
|
|
857
857
|
private provider;
|
|
@@ -869,7 +869,7 @@ declare class HestiaAuth {
|
|
|
869
869
|
bootstrap(key: string, password: string, email: string): Promise<void>;
|
|
870
870
|
}
|
|
871
871
|
//#endregion
|
|
872
|
-
//#region system/
|
|
872
|
+
//#region system/users/store.d.ts
|
|
873
873
|
declare class HestiaUsers implements DocumentStore<UserData, QueryDSL<UserData>, string, QueryDSL<UserData>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
874
874
|
private client;
|
|
875
875
|
private pagerOptions;
|
|
@@ -901,7 +901,7 @@ declare class HestiaUsers implements DocumentStore<UserData, QueryDSL<UserData>,
|
|
|
901
901
|
changePassword(userId: string, current: string, newPassword: string): Promise<void>;
|
|
902
902
|
}
|
|
903
903
|
//#endregion
|
|
904
|
-
//#region system/
|
|
904
|
+
//#region system/apikeys/types.d.ts
|
|
905
905
|
interface APIKey {
|
|
906
906
|
_id_: string;
|
|
907
907
|
name: string;
|
|
@@ -931,7 +931,7 @@ interface UpdateKeyRequest {
|
|
|
931
931
|
expiry?: string;
|
|
932
932
|
}
|
|
933
933
|
//#endregion
|
|
934
|
-
//#region system/
|
|
934
|
+
//#region system/apikeys/store.d.ts
|
|
935
935
|
declare class HestiaKeyStore implements DocumentStore<APIKey, QueryDSL<APIKey>, string, QueryDSL<APIKey>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
936
936
|
private client;
|
|
937
937
|
private pager;
|
|
@@ -1018,40 +1018,6 @@ interface UpdatePolicyRequest {
|
|
|
1018
1018
|
rateLimit?: RateLimitConfig | null;
|
|
1019
1019
|
throttle?: ThrottleConfig | null;
|
|
1020
1020
|
}
|
|
1021
|
-
//#endregion
|
|
1022
|
-
//#region system/policies/store.d.ts
|
|
1023
|
-
declare class HestiaPolicies implements DocumentStore<Policy, QueryDSL<Policy>, string, QueryDSL<Policy>, Record<string, unknown>, string, string, string> {
|
|
1024
|
-
private client;
|
|
1025
|
-
private pager;
|
|
1026
|
-
constructor(client: Transport);
|
|
1027
|
-
find(_query?: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1028
|
-
query(qdsl: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1029
|
-
list(_options?: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1030
|
-
read(id: string): Promise<Document<Policy> | undefined>;
|
|
1031
|
-
create(props: {
|
|
1032
|
-
data: Partial<CreatePolicyRequest>;
|
|
1033
|
-
options?: string;
|
|
1034
|
-
}): Promise<Document<Policy> | undefined>;
|
|
1035
|
-
update(props: {
|
|
1036
|
-
data: UpdatePolicyRequest;
|
|
1037
|
-
options?: string;
|
|
1038
|
-
}): Promise<Document<Policy> | undefined>;
|
|
1039
|
-
setEnabled(name: string, enabled: boolean): Promise<Document<Policy>>;
|
|
1040
|
-
delete(_id: string): Promise<void>;
|
|
1041
|
-
upload(_props: {
|
|
1042
|
-
file: File;
|
|
1043
|
-
}): Promise<Document<Policy> | undefined>;
|
|
1044
|
-
subscribe(_scope: string, _callback: (event: StoreEvent) => void): Promise<() => void>;
|
|
1045
|
-
notify(_event: StoreEvent): Promise<void>;
|
|
1046
|
-
stream(_options: Record<string, unknown>, _onStreamChange: () => void): {
|
|
1047
|
-
stream: () => AsyncIterable<Document<Policy>>;
|
|
1048
|
-
cancel: () => void;
|
|
1049
|
-
status: () => "active" | "cancelled" | "completed";
|
|
1050
|
-
};
|
|
1051
|
-
page(_options?: Record<string, unknown>): PagedData<Policy>;
|
|
1052
|
-
}
|
|
1053
|
-
//#endregion
|
|
1054
|
-
//#region system/rules/types.d.ts
|
|
1055
1021
|
interface PolicyRule {
|
|
1056
1022
|
id: string;
|
|
1057
1023
|
name: string;
|
|
@@ -1102,7 +1068,39 @@ interface ReloadResult {
|
|
|
1102
1068
|
rules: number;
|
|
1103
1069
|
}
|
|
1104
1070
|
//#endregion
|
|
1105
|
-
//#region system/
|
|
1071
|
+
//#region system/policies/store.d.ts
|
|
1072
|
+
declare class HestiaPolicies implements DocumentStore<Policy, QueryDSL<Policy>, string, QueryDSL<Policy>, Record<string, unknown>, string, string, string> {
|
|
1073
|
+
private client;
|
|
1074
|
+
private pager;
|
|
1075
|
+
constructor(client: Transport);
|
|
1076
|
+
find(_query?: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1077
|
+
query(qdsl: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1078
|
+
list(_options?: QueryDSL<Policy>): Promise<Page<Policy>>;
|
|
1079
|
+
read(id: string): Promise<Document<Policy> | undefined>;
|
|
1080
|
+
create(props: {
|
|
1081
|
+
data: Partial<CreatePolicyRequest>;
|
|
1082
|
+
options?: string;
|
|
1083
|
+
}): Promise<Document<Policy> | undefined>;
|
|
1084
|
+
update(props: {
|
|
1085
|
+
data: UpdatePolicyRequest;
|
|
1086
|
+
options?: string;
|
|
1087
|
+
}): Promise<Document<Policy> | undefined>;
|
|
1088
|
+
setEnabled(name: string, enabled: boolean): Promise<Document<Policy>>;
|
|
1089
|
+
delete(_id: string): Promise<void>;
|
|
1090
|
+
upload(_props: {
|
|
1091
|
+
file: File;
|
|
1092
|
+
}): Promise<Document<Policy> | undefined>;
|
|
1093
|
+
subscribe(_scope: string, _callback: (event: StoreEvent) => void): Promise<() => void>;
|
|
1094
|
+
notify(_event: StoreEvent): Promise<void>;
|
|
1095
|
+
stream(_options: Record<string, unknown>, _onStreamChange: () => void): {
|
|
1096
|
+
stream: () => AsyncIterable<Document<Policy>>;
|
|
1097
|
+
cancel: () => void;
|
|
1098
|
+
status: () => "active" | "cancelled" | "completed";
|
|
1099
|
+
};
|
|
1100
|
+
page(_options?: Record<string, unknown>): PagedData<Policy>;
|
|
1101
|
+
}
|
|
1102
|
+
//#endregion
|
|
1103
|
+
//#region system/policies/rules.d.ts
|
|
1106
1104
|
declare class HestiaRules implements DocumentStore<PolicyRule, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, string> {
|
|
1107
1105
|
private client;
|
|
1108
1106
|
constructor(client: Transport);
|
|
@@ -1133,7 +1131,7 @@ declare class HestiaRules implements DocumentStore<PolicyRule, Record<string, un
|
|
|
1133
1131
|
page(_options?: Record<string, unknown>): any;
|
|
1134
1132
|
}
|
|
1135
1133
|
//#endregion
|
|
1136
|
-
//#region system/
|
|
1134
|
+
//#region system/audit/types.d.ts
|
|
1137
1135
|
interface AuditEntry {
|
|
1138
1136
|
event_id: string;
|
|
1139
1137
|
occurred_at: string;
|
|
@@ -1171,7 +1169,7 @@ interface LogFilter {
|
|
|
1171
1169
|
end?: string;
|
|
1172
1170
|
}
|
|
1173
1171
|
//#endregion
|
|
1174
|
-
//#region system/
|
|
1172
|
+
//#region system/audit/store.d.ts
|
|
1175
1173
|
declare class HestiaLogs implements DocumentStore<AuditEntry, QueryDSL<AuditEntry>, string, QueryDSL<AuditEntry>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
1176
1174
|
private client;
|
|
1177
1175
|
private baseUrl;
|
|
@@ -1204,7 +1202,7 @@ declare class HestiaLogs implements DocumentStore<AuditEntry, QueryDSL<AuditEntr
|
|
|
1204
1202
|
getStreamUrl(): string;
|
|
1205
1203
|
}
|
|
1206
1204
|
//#endregion
|
|
1207
|
-
//#region blobs/types.d.ts
|
|
1205
|
+
//#region system/blobs/types.d.ts
|
|
1208
1206
|
interface NamespaceInfo {
|
|
1209
1207
|
id: string;
|
|
1210
1208
|
display_name: string;
|
|
@@ -1225,7 +1223,7 @@ interface ListBlobsRequest {
|
|
|
1225
1223
|
}
|
|
1226
1224
|
interface CreateNamespaceRequest {
|
|
1227
1225
|
display_name?: string;
|
|
1228
|
-
ns
|
|
1226
|
+
ns: string;
|
|
1229
1227
|
}
|
|
1230
1228
|
interface UploadBeginResult {
|
|
1231
1229
|
session_id: string;
|
|
@@ -1319,7 +1317,7 @@ interface UploadQueueOptions {
|
|
|
1319
1317
|
persistence?: UploadPersistence;
|
|
1320
1318
|
}
|
|
1321
1319
|
//#endregion
|
|
1322
|
-
//#region blobs/store.d.ts
|
|
1320
|
+
//#region system/blobs/store.d.ts
|
|
1323
1321
|
declare function getMissingRanges(ranges: {
|
|
1324
1322
|
start: number;
|
|
1325
1323
|
end: number;
|
|
@@ -1569,7 +1567,7 @@ declare class HestiaBlobClient {
|
|
|
1569
1567
|
namespace(ns: string): BlobNamespace;
|
|
1570
1568
|
}
|
|
1571
1569
|
//#endregion
|
|
1572
|
-
//#region collections/types.d.ts
|
|
1570
|
+
//#region system/collections/types.d.ts
|
|
1573
1571
|
interface CollectionMeta {
|
|
1574
1572
|
name: string;
|
|
1575
1573
|
schema: SchemaDefinition;
|
|
@@ -1577,10 +1575,10 @@ interface CollectionMeta {
|
|
|
1577
1575
|
updated: string;
|
|
1578
1576
|
}
|
|
1579
1577
|
type CollectionDocument = Document<{
|
|
1580
|
-
schema:
|
|
1578
|
+
schema: SchemaDefinition;
|
|
1581
1579
|
}>;
|
|
1582
1580
|
//#endregion
|
|
1583
|
-
//#region collections/store.d.ts
|
|
1581
|
+
//#region system/collections/store.d.ts
|
|
1584
1582
|
declare class HestiaCollections implements DocumentStore<CollectionMeta, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
1585
1583
|
private client;
|
|
1586
1584
|
constructor(client: Transport);
|
|
@@ -1709,8 +1707,8 @@ declare class HestiaSettingStore {
|
|
|
1709
1707
|
delete(key: string): Promise<void>;
|
|
1710
1708
|
}
|
|
1711
1709
|
//#endregion
|
|
1712
|
-
//#region system/
|
|
1713
|
-
declare class
|
|
1710
|
+
//#region system/core/store.d.ts
|
|
1711
|
+
declare class HestiaCore implements DocumentStore<any, Record<string, unknown>, string, Record<string, unknown>, Record<string, unknown>, string, string, Record<string, unknown>> {
|
|
1714
1712
|
private client;
|
|
1715
1713
|
constructor(client: Transport);
|
|
1716
1714
|
find(_query?: Record<string, unknown>): Promise<Page<any>>;
|
|
@@ -1760,7 +1758,7 @@ declare class HestiaClient {
|
|
|
1760
1758
|
readonly logs: HestiaLogs;
|
|
1761
1759
|
readonly collections: HestiaCollections;
|
|
1762
1760
|
readonly blobs: HestiaBlobClient;
|
|
1763
|
-
readonly
|
|
1761
|
+
readonly core: HestiaCore;
|
|
1764
1762
|
readonly notifications: HestiaNotificationStore;
|
|
1765
1763
|
readonly schedules: HestiaScheduleStore;
|
|
1766
1764
|
readonly settings: HestiaSettingStore;
|
|
@@ -1794,4 +1792,4 @@ interface ArrayPagerOptions<T extends Record<string, any>, F = any> {
|
|
|
1794
1792
|
}
|
|
1795
1793
|
declare function createArrayPager<T extends Record<string, any>, F = any>(options: ArrayPagerOptions<T, F>): PagedData<T>;
|
|
1796
1794
|
//#endregion
|
|
1797
|
-
export { APIKey, APIKeyWithSecret, AimdController, ArrayPagerOptions, AuditEntry, Binding, BlobDocument, BlobMeta, BlobNamespace, BootstrapPasswordRequest, ChangePasswordRequest, CollectionDocument, CollectionMeta, CreateKeyRequest, CreateNamespaceRequest, CreatePolicyRequest, CreateRuleRequest, CreateSchedulePayload, CreateUserRequest, DispatchInput, Document, DocumentStore, FetchResult, HestiaAuth, HestiaBlobClient, HestiaClient, HestiaCollection, HestiaCollections, HestiaKeyStore, HestiaLogs, HestiaNetworkClient, HestiaNotificationStore, HestiaOperations, HestiaPolicies, HestiaResponse, HestiaRules, HestiaScheduleStore, HestiaSettingStore, HestiaUsers, HttpTransport, IdentityProvider, ListBlobsRequest, LogFilter, LoginRequest, LoginResult, NamespaceInfo, Notification, Page, PagedData, PagerRefreshOptions, PaginationInfo, Policy, PolicyRule, RateLimitConfig, RegisterRequest, ReloadResult, RequestLogEntry, RequestOptions, ResumableUpload, RuleNode, Schedule, ServerHealth, SetPolicyEnabledRequest, SettingDocument, StoreEvent, StreamHandlers, StreamOptions, ThrottleAction, ThrottleConfig, Transport, UnreadCount, UpdateKeyRequest, UpdatePolicyRequest, UpdatePolicyRuleRequest, UpdateRuleRequest, UpdateSchedulePayload, UpdateUserRequest, UploadBeginResult, UploadJobSnapshot, UploadJobStore, UploadJobsState, UploadOptions, UploadPersistence, UploadPhase, UploadProgressInfo, UploadProgressResult, UploadQueue, UploadQueueOptions, UploadStatus, UploadTransport, UserData, UserIdentity, ValidateRuleRequest, ValidateRuleResult, WailsTransport, createArrayPager, createPagedController, getMissingRanges, internalError, notFound, parseErrorBody, permissionDenied, toSystemError };
|
|
1795
|
+
export { APIKey, APIKeyWithSecret, AimdController, ArrayPagerOptions, AuditEntry, Binding, BlobDocument, BlobMeta, BlobNamespace, BootstrapPasswordRequest, ChangePasswordRequest, CollectionDocument, CollectionMeta, CreateKeyRequest, CreateNamespaceRequest, CreatePolicyRequest, CreateRuleRequest, CreateSchedulePayload, CreateUserRequest, DispatchInput, Document, DocumentStore, FetchResult, HestiaAuth, HestiaBlobClient, HestiaClient, HestiaCollection, HestiaCollections, HestiaCore, HestiaKeyStore, HestiaLogs, HestiaNetworkClient, HestiaNotificationStore, HestiaOperations, HestiaPolicies, HestiaResponse, HestiaRules, HestiaScheduleStore, HestiaSettingStore, HestiaUsers, HttpTransport, IdentityProvider, ListBlobsRequest, LogFilter, LoginRequest, LoginResult, NamespaceInfo, Notification, Page, PagedData, PagerRefreshOptions, PaginationInfo, Policy, PolicyRule, RateLimitConfig, RegisterRequest, ReloadResult, RequestLogEntry, RequestOptions, ResumableUpload, RuleNode, Schedule, ServerHealth, SetPolicyEnabledRequest, SettingDocument, StoreEvent, StreamHandlers, StreamOptions, ThrottleAction, ThrottleConfig, Transport, UnreadCount, UpdateKeyRequest, UpdatePolicyRequest, UpdatePolicyRuleRequest, UpdateRuleRequest, UpdateSchedulePayload, UpdateUserRequest, UploadBeginResult, UploadJobSnapshot, UploadJobStore, UploadJobsState, UploadOptions, UploadPersistence, UploadPhase, UploadProgressInfo, UploadProgressResult, UploadQueue, UploadQueueOptions, UploadStatus, UploadTransport, UserData, UserIdentity, ValidateRuleRequest, ValidateRuleResult, WailsTransport, createArrayPager, createPagedController, getMissingRanges, internalError, notFound, parseErrorBody, permissionDenied, toSystemError };
|
package/index.mjs
CHANGED
|
@@ -4,5 +4,5 @@ import{createNetworkClient as e}from"@asaidimu/network-client";import{Errors as
|
|
|
4
4
|
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());n.length>0&&t.onMessage(n.join(`
|
|
5
5
|
`)),r=c.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 _=g;function v(){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}}function y(){throw new n({code:`HTTP_UNAVAILABLE`,message:`WailsTransport needs baseUrl and identityProvider for path-based requests. Use dispatch() instead.`})}var b=class{baseUrl=``;apiPrefix=``;init=new i({throws:!0});config;http;onUnauthorized;constructor(e){this.config=e,this.baseUrl=e?.baseUrl??``,this.apiPrefix=e?.apiPrefix??`/api`,this.onUnauthorized=e?.onUnauthorized,e?.baseUrl&&(this.http=new g(e.baseUrl,this.apiPrefix,()=>this.onUnauthorized?.()))}setOnUnauthorized(e,t){this.onUnauthorized=e,this.http||=new g(this.baseUrl||`http://wails.local`,this.apiPrefix,()=>this.onUnauthorized?.())}configure(e,t,n){this.baseUrl=e,this.apiPrefix=t,this.http||=new g(e,t,()=>this.onUnauthorized?.())}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return v()}base(){return this.baseUrl}prefix(){return this.apiPrefix}routeUrl(e,t){if(!this.http)throw y();return this.http.routeUrl(e,t)}async ready(e=1e4){await 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){if(await this.ready(),this.http&&(t?.bodyType===`blob`||t?.bodyType===`stream`))return this.http.dispatch(e,t);let r=t?.notifyAuthStateChange??!0,a=t?.payload??null,o={...t?.modifiers??{}};t?.headers?.[`Content-Type`]&&(o.content_type=t.headers[`Content-Type`]);let s=this.resolveService();if(s?.Dispatch){let c;try{c=await s.Dispatch({name:e,arguments:t?.arguments??{},modifiers:o,payload:a})}catch(t){throw console.error(`[WailsTransport] dispatch "${e}" failed:`,t?.message??t),t instanceof n?t:new n({code:`DISPATCH_ERROR`,message:t?.message??String(t)})}if(c.status>=400){let t=c.data?.error,a=t?.code??`UNKNOWN`,o=t?.message??`dispatch returned status ${c.status}`;throw console.error(`[WailsTransport] dispatch "${e}" error [${a}]: ${o}`),c.status===401&&r&&(this.init=new i({throws:!0}),this.onUnauthorized?.()),new n({code:a,message:o})}return new h(c.data,c.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){if(await this.ready(),!this.http)throw y();return this.http.check(e,t,n)}async get(e,t){if(await this.ready(),!this.http)throw y();return this.http.get(e,t)}async post(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.post(e,t,n)}async patch(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.patch(e,t,n)}async put(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.put(e,t,n)}async delete(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.delete(e,t,n)}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 x=globalThis.requestIdleCallback?.bind(globalThis)??((e,t)=>{let n=performance.now(),r={didTimeout:!1,timeRemaining:()=>Math.max(0,50-(performance.now()-n))};return setTimeout(()=>e(r),t?.timeout==null?0:Math.min(t.timeout,0))}),S={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function C(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()=>{x(()=>{x(async()=>{try{let n=await i(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...S,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??S,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 w=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=C(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}},T=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 await this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:users:user:create`,{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}})}},E=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=C(`users`,new o({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:collections: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({data:e}){if(!e)throw Error(`User creation requires email/password/name`);return(await this.client.dispatch(`system:users:user:create`,{payload:e})).data.data}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}})}},D=class{client;pager;constructor(e){this.client=e,this.pager=C(`_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}};function O(e){return{...e,_id_:e.name,_metadata_:{checksum:``,created:``,updated:``,version:1}}}var k=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:binding:list`)).data?.data?.bindings??[];return{data:e.map(e=>O(e)),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:binding:get`,{arguments:{name:e}});return t.data?.data?O(t.data.data):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}},A=class{client;pager;constructor(e){this.client=e,this.pager=C(`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??[];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){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{return((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e||t.id===e)||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={rule:e.data.rule??``,rateLimit:e.data.rateLimit,throttle:e.data.throttle};return(await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n})).data.data}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);let n={};return e.data.rule!==void 0&&(n.rule=e.data.rule),e.data.enabled!==void 0&&(n.enabled=e.data.enabled),e.data.rateLimit!==void 0&&(n.rateLimit=e.data.rateLimit),e.data.throttle!==void 0&&(n.throttle=e.data.throttle),(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:n})).data.data}async setEnabled(e,t){return(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data}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}},j=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`)}},M=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=C(`_audit_log_`,new o({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/collections/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`}};const N=.3;function P(e){return new Promise(t=>setTimeout(t,e))}async function F(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}function I(e,t,n){return e.slice(t,n)}function L(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`upload_`+Date.now()+`_`+Math.random().toString(36).slice(2)}function R(e,t){let n=[],r=0;for(let t of e)t.start>r&&n.push({start:r,end:t.start}),t.end>r&&(r=t.end);return r<t&&n.push({start:r,end:t}),n}function z(e,t){let n=0,r=e.length?e[0].start:0;function i(){for(;n<e.length&&r>=e[n].end;)n++,n<e.length&&(r=e[n].start)}return{hasMore(){return i(),n<e.length},next(){if(i(),n>=e.length)return null;let a=Math.min(r+t,e[n].end),o={start:r,end:a};return r=a,o}}}var B=class{maxConcurrency;consecutiveSuccesses=0;lastBackoff=0;throughputEstimate;constructor(e,t=262144){this.maxConcurrency=e,this.throughputEstimate=t}estThroughput(){return this.throughputEstimate}recordThroughput(e){this.throughputEstimate=this.throughputEstimate*(1-N)+e*N}recordSuccess(){this.consecutiveSuccesses++,this.consecutiveSuccesses>=3&&(this.consecutiveSuccesses=0,this.maxConcurrency=Math.min(6,this.maxConcurrency+1))}recordFailure(){let e=Date.now();e-this.lastBackoff<2500||(this.lastBackoff=e,this.consecutiveSuccesses=0,this.maxConcurrency=Math.max(1,Math.floor(this.maxConcurrency/2)))}},V=class{backing;state={jobs:{}};instanceId=L();ready;constructor(e){this.backing=e,this.ready=this.hydrate()}async hydrate(){if(!this.backing)return;let e=await this.backing.get();e&&(this.state=e)}async save(e){await this.ready,this.state={jobs:{...this.state.jobs,[e.id]:e}},await this.backing?.set(this.instanceId,this.state)}async load(){if(await this.ready,this.backing){let e=await this.backing.get();e&&(this.state=e)}return Object.values(this.state.jobs)}async remove(e){await this.ready;let t={...this.state.jobs};delete t[e],this.state={jobs:t},await this.backing?.set(this.instanceId,this.state)}},H=class{id;status=`queued`;blockSize=0;sessionId=null;uploaded=0;hashed=0;hashTotal=0;bytesPerSecond=0;etaSeconds=0;fingerprint=``;error=null;onStatusChange;get done(){return this.attempt}total;key;file;options;transport;persistence;aimd;startedAt=Date.now();blockHashes=[];pauseRequested=!1;cancelRequested=!1;abortControllers=new Set;running=!1;lastProgressTime=0;lastProgressBytes=0;speedSamples=[];lastReportAt=0;attempt;resolveDone;rejectDone;constructor(e,t,n,r,i,a){this.transport=e,this.file=t,this.key=n,this.options=r,this.persistence=i,this.id=a?.id??L(),this.total=a?.size??t.size,this.blockSize=a?.blockSize??0,this.sessionId=a?.sessionId??null,this.blockHashes=a?.blockHashes??[],this.fingerprint=a?.fingerprint??``,this.uploaded=a?.uploadedBytes??0,this.status=a?`paused`:`queued`,this.aimd=new B(Math.max(1,r.concurrency??4)),this.newAttempt(),r.signal&&(r.signal.aborted?queueMicrotask(()=>void this.cancel()):r.signal.addEventListener(`abort`,()=>void this.cancel(),{once:!0}))}newAttempt(){this.attempt=new Promise((e,t)=>{this.resolveDone=e,this.rejectDone=t})}start(){this.status===`queued`&&(this.pauseRequested=!1,this.cancelRequested=!1,this.run())}resume(){(this.status===`paused`||this.status===`error`)&&(this.status===`error`&&this.newAttempt(),this.error=null,this.pauseRequested=!1,this.cancelRequested=!1,this.run())}retry(){this.resume()}pause(){if(this.status!==`completed`&&this.status!==`cancelled`){this.pauseRequested=!0;for(let e of this.abortControllers)e.abort();this.running||(this.setStatus(`paused`),this.report(),this.persist())}}async cancel(){if(this.status!==`completed`&&this.status!==`cancelled`){this.cancelRequested=!0;for(let e of this.abortControllers)e.abort();if(this.sessionId)try{await this.transport.abort(this.sessionId)}catch{}await this.persistence?.remove(this.id),this.running||(this.setStatus(`cancelled`),this.report(),this.resolveDone(void 0))}}async run(){if(!(this.running||this.status===`completed`||this.status===`cancelled`)){this.running=!0;try{if(this.blockSize===0&&(this.blockSize=this.chooseBlockSize(),await this.persist()),!this.sessionId){let e=await this.transport.beginUpload({key:this.key,size:this.total,contentType:this.options.contentType||this.file.type,blockSize:this.blockSize,overwrite:this.options.overwrite});this.sessionId=e.session_id,this.blockHashes.length===0&&e.block_size>0&&(this.blockSize=e.block_size),await this.persist()}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.blockHashes.length===0&&this.blockSize>0&&(this.setStatus(`hashing`),await this.hashBlocks()),this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.cancelRequested){this.finishCancelled();return}for(this.setStatus(`uploading`);!this.cancelRequested&&!this.pauseRequested;){if(!this.sessionId)throw Error(`upload session missing`);let e=await this.transport.progress(this.sessionId);if(this.uploaded=e.total,this.report(),this.uploaded>=this.total)break;let t=R(e.ranges??[],this.total);if(t.length===0)break;let n=await this.runUploadPool(t);if(n.cancelled)break;if(n.paused){this.setStatus(`paused`),this.report(),await this.persist();return}}if(this.cancelRequested){this.finishCancelled();return}if(!this.sessionId)throw Error(`upload session missing`);this.setStatus(`completing`),this.report();let e=await this.transport.completeUpload({sessionId:this.sessionId,overwrite:this.options.overwrite});this.uploaded=this.total,this.setStatus(`completed`),this.report(),await this.persistence?.remove(this.id),this.resolveDone(e)}catch(e){if(this.cancelRequested){this.finishCancelled();return}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}this.error=e instanceof Error?e:Error(String(e)),this.setStatus(`error`),this.report(),await this.persist(),this.rejectDone(this.error)}finally{this.running=!1}}}finishCancelled(){this.setStatus(`cancelled`),this.report(),this.persistence?.remove(this.id),this.resolveDone(void 0)}chooseBlockSize(){let e=this.options.blockSize??8388608;return this.total<=0?0:Math.min(e,this.total)}async hashBlocks(){let e=this.blockSize,t=Math.ceil(this.total/e);this.blockHashes=Array(t),this.hashTotal=this.total,this.hashed=0;let n=performance.now();for(let r=0;r<t;r++){if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);for(;this.pauseRequested&&!this.cancelRequested;)await P(200);if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);let t=r*e,i=Math.min(t+e,this.total),a=await I(this.file,t,i).arrayBuffer();this.blockHashes[r]=await F(a),this.hashed=i,this.report();let o=performance.now();o-n>12&&(await P(0),n=o)}let r=this.blockHashes.join(``);this.fingerprint=await F(new TextEncoder().encode(r)),await this.persist()}runUploadPool(e){return new Promise(t=>{let n=z(e,this.blockSize),r=!1,i=null,a=!1,o=0,s=()=>{r||o>0||(r=!0,i?(this.failPool(i),t({paused:!1,cancelled:!1})):t({paused:a&&!this.cancelRequested,cancelled:this.cancelRequested}))},c=()=>{o++,(async()=>{for(;!this.cancelRequested;){if(this.pauseRequested){a=!0;break}if(i||o>this.aimd.maxConcurrency)break;let e=n.next();if(!e)break;let t=await this.uploadOneChunk(e);if(!t.success){t.aborted?this.pauseRequested&&(a=!0):i=Error(`Chunk failed at ${e.start}`);break}}})().finally(()=>{o--,!this.cancelRequested&&!this.pauseRequested&&!i&&o<this.aimd.maxConcurrency&&n.hasMore()&&c(),s()})},l=Math.max(1,this.aimd.maxConcurrency),u=0;for(let e=0;e<l&&n.hasMore();e++)c(),u++;u===0&&s()})}failPool(e){this.status!==`completed`&&this.status!==`cancelled`&&(this.error=e,this.setStatus(`error`),this.report(),this.persist(),this.rejectDone(this.error))}async uploadOneChunk(e){let t=I(this.file,e.start,e.end);if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let n=Math.floor(e.start/this.blockSize),r=this.blockHashes[n],i=Math.max(0,this.options.retries??3),a=e.end-e.start;for(let n=1;n<=i+1;n++){if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let o=new AbortController;this.abortControllers.add(o);let s=Math.max(this.aimd.estThroughput(),32*1024),c=Math.max(6e3,a/s*1e3*3),l=setTimeout(()=>o.abort(),c),u=performance.now();try{if(!this.sessionId)throw Error(`upload session missing`);let n=await this.transport.uploadChunk({sessionId:this.sessionId,offset:e.start,data:t,sha256:r,signal:o.signal});clearTimeout(l),this.abortControllers.delete(o);let i=(performance.now()-u)/1e3;return this.aimd.recordSuccess(),this.onChunkUploaded(a,i,n),{success:!0,aborted:!1}}catch(e){if(clearTimeout(l),this.abortControllers.delete(o),this.cancelRequested||this.pauseRequested&&e instanceof DOMException&&e.name===`AbortError`)return{success:!1,aborted:!0};this.aimd.recordFailure(),n<=i&&await P(1500*2**(n-1))}}return{success:!1,aborted:!1}}onChunkUploaded(e,t,n){t>.05&&this.aimd.recordThroughput(e/t),this.uploaded=n;let r=Date.now();if(!this.lastProgressTime)this.lastProgressTime=r,this.lastProgressBytes=n;else if(r-this.lastProgressTime>1e3){let e=n-this.lastProgressBytes,t=(r-this.lastProgressTime)/1e3;if(t>0){let n=e/t;this.speedSamples.push(n),this.speedSamples.length>5&&this.speedSamples.shift()}this.lastProgressTime=r,this.lastProgressBytes=n}let i=this.speedSamples.length>0?this.speedSamples.reduce((e,t)=>e+t,0)/this.speedSamples.length:0;this.bytesPerSecond=i;let a=this.total-this.uploaded;this.etaSeconds=i>0&&a>0?a/i:0,this.report()}report(){let e=performance.now();if(this.status===`uploading`&&e-this.lastReportAt<80)return;this.lastReportAt=e;let t=this.status===`hashing`?`hash`:`upload`,n=t===`hash`?this.hashTotal>0?this.hashed/this.hashTotal:0:this.total>0?this.uploaded/this.total:1;this.options.onProgress?.({phase:t,hashed:this.hashed,hashTotal:this.hashTotal,uploaded:this.uploaded,total:this.total,percent:Math.min(1,n),bytesPerSecond:this.bytesPerSecond,etaSeconds:this.etaSeconds,fingerprint:this.fingerprint||void 0})}snapshot(){return{id:this.id,key:this.key,name:this.file.name,size:this.total,type:this.file.type,file:this.file,sessionId:this.sessionId,blockSize:this.blockSize,blockHashes:this.blockHashes,fingerprint:this.fingerprint,uploadedBytes:this.uploaded,status:this.status,error:this.error?this.error.message:null}}async persist(){if(this.persistence)try{await this.persistence.save(this.snapshot())}catch{}}setStatus(e){this.status!==e&&(this.status=e,this.onStatusChange?.(e))}},U=class{jobs=new Map;queue=[];active=0;runningJobs=new WeakSet;maxConcurrent;persistence;transport;ns;constructor(e,t,n={}){this.transport=e,this.ns=t,this.maxConcurrent=Math.max(1,n.maxConcurrent??3),this.persistence=n.persistence}enqueue(e,t){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);let r=new H(this.transport,e,n,t,this.persistence);return r.onStatusChange=e=>{if(e===`queued`)return;let t=e===`hashing`||e===`uploading`||e===`completing`,n=e===`paused`||e===`completed`||e===`error`||e===`cancelled`;if(t&&!this.runningJobs.has(r)?(this.runningJobs.add(r),this.active++,this.pump()):n&&this.runningJobs.has(r)&&(this.runningJobs.delete(r),this.active=Math.max(0,this.active-1),this.pump()),e===`cancelled`||e===`completed`){let e=this.queue.indexOf(r.id);e!==-1&&this.queue.splice(e,1)}},this.jobs.set(r.id,r),this.queue.push(r.id),this.pump(),r}pump(){for(;this.active<this.maxConcurrent&&this.queue.length>0;){let e=this.queue.shift();if(!e)continue;let t=this.jobs.get(e);t&&(this.runningJobs.add(t),this.active++,t.start())}}restore(e){return(this.persistence?this.persistence.load():Promise.resolve([]))instanceof Promise,[]}async restoreAsync(e){if(!this.persistence)return[];let t=await this.persistence.load(),n=[];for(let r of t){let t=r.file??e?.(r);if(!t)continue;let i=new H(this.transport,t,r.key,{key:r.key,contentType:r.type,overwrite:!1},this.persistence,r);this.jobs.set(i.id,i),n.push(i)}return n}pause(e){let t=this.jobs.get(e);if(t){if(t.status===`queued`){let t=this.queue.indexOf(e);t!==-1&&this.queue.splice(t,1)}t.pause()}}resume(e){this.jobs.get(e)?.resume()}retry(e){this.jobs.get(e)?.retry()}async cancel(e){let t=this.jobs.get(e);if(!t)return;let n=this.queue.indexOf(e);n!==-1&&this.queue.splice(n,1),await t.cancel()}pauseAll(){for(let e of this.jobs.values())(e.status===`uploading`||e.status===`hashing`||e.status===`queued`)&&e.pause()}resumeAll(){for(let e of this.jobs.values())(e.status===`paused`||e.status===`error`)&&e.resume()}clearCompleted(){for(let[e,t]of Array.from(this.jobs))(t.status===`completed`||t.status===`cancelled`)&&this.jobs.delete(e)}all(){return Array.from(this.jobs.values())}summary(){let e=this.all().filter(e=>[`uploading`,`hashing`,`queued`,`completing`].includes(e.status)),t=this.all().filter(e=>e.status===`paused`),n=this.all().filter(e=>e.status===`completed`),r=this.all().filter(e=>e.status===`cancelled`),i=this.all().filter(e=>e.status===`error`),a=0,o=0,s=0;for(let t of e)a+=t.total,o+=t.uploaded,s+=t.bytesPerSecond;let c=Math.max(0,a-o),l=s>0?c/s:0;return{active:e.length,paused:t.length,done:n.length,cancelled:r.length,failed:i.length,totalBytes:a,uploadedBytes:o,bytesPerSecond:s,etaSeconds:l}}};function W(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function G(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var K=class{client;ns;persistence;pagerOptions={};pager;prefixFilter=``;_queue;constructor(e,t,n){this.client=e,this.ns=t,this.persistence=n,this.pager=C(`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(W),loading:!1,page:G(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?W(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 W((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=e.options?.threshold??16777216;if(!e.options?.forceStaged&&e.file.size<=n)return this.uploadDirect(e.file,t,e.options);let r=this.createUpload(e.file,e.options);return r.start(),r.done}createUpload(e,t={}){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);return new H(this,e,n,t,this.persistence)}queue(e){return this._queue||=new U(this,this.ns,e),this._queue}async uploadDirect(e,t,n){let r={},i=n?.contentType||e.type;return i&&(r[`Content-Type`]=i),W((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},modifiers:n?.overwrite?{overwrite:`true`}:void 0,payload:e,headers:r,bodyType:`blob`})).data.data)}async beginUpload(e){return(await this.client.dispatch(`system:blobs:blob:begin`,{arguments:{ns:this.ns},modifiers:e.overwrite?{overwrite:`true`}:void 0,payload:{key:e.key,size:e.size,content_type:e.contentType,block_size:e.blockSize}})).data.data}async uploadChunk(e){let t={"X-Session-ID":e.sessionId,"X-Offset":String(e.offset)};return e.sha256&&(t[`X-Chunk-SHA256`]=e.sha256),(await this.client.dispatch(`system:blobs:blob:chunk`,{arguments:{ns:this.ns},headers:t,payload:e.data,bodyType:`blob`,signal:e.signal})).data.data.total}async completeUpload(e){return W((await this.client.dispatch(`system:blobs:blob:complete`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e.sessionId},modifiers:e.overwrite?{overwrite:`true`}:void 0})).data.data)}async progress(e){return(await this.client.dispatch(`system:blobs:blob:progress`,{arguments:{ns:this.ns},modifiers:{session_id:e}})).data.data}async abort(e){await this.client.dispatch(`system:blobs:blob:abort`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e}})}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}}},q=class{client;uploadPersistence;apiPrefix;constructor(e,t=`/api`,n){this.client=e,this.uploadPersistence=n,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.routeUrl(`system:blobs:blob:download`,{ns:e,key:t})}namespace(e){return new K(this.client,e,this.uploadPersistence)}},J=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 w(this.client,e)}},Y=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:notifications:notification:list`)).data?.data??[]}async markRead(e){await this.client.dispatch(`system:notifications:notification:read`,{arguments:{notification_id:e}})}async markAllRead(){await this.client.dispatch(`system:notifications:read:all`)}async countUnread(){return(await this.client.dispatch(`system:notifications:unread:count`)).data?.data?.count??0}},X=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:schedules:schedule:create`,{payload:e})).data?.data?.id??``}async list(){return(await this.client.dispatch(`system:schedules:schedule:list`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:schedules:schedule:get`,{arguments:{id:e}})).data?.data??null}async update(e,t){await this.client.dispatch(`system:schedules:schedule:update`,{arguments:{id:e},payload:t})}async delete(e){await this.client.dispatch(`system:schedules:schedule:delete`,{arguments:{id:e}})}},Z=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:settings:list`)).data?.data??[]}async get(e){try{return(await this.client.dispatch(`system:settings:get`,{arguments:{key:e}})).data?.data}catch{return}}async set(e,t){await this.client.dispatch(`system:settings:set`,{arguments:{key:e},payload:{value:t}})}async delete(e){await this.client.dispatch(`system:settings:delete`,{arguments:{key:e}})}},Q=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`)}},$=class{store;client;auth;users;keys;policies;rules;logs;collections;blobs;capabilities;notifications;schedules;settings;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`,r=()=>{t.clear(),this.onAuthStateChanged?.()};this.tokenProvider=t,e.transport instanceof b?(e.transport.configure(e.baseUrl,n,t),e.transport.setOnUnauthorized(r),this.client=e.transport):this.client=e.transport??new g(e.baseUrl,n,r),this.auth=new T(this.client,t),this.users=new E(this.client),this.keys=new D(this.client),this.policies=new A(this.client),this.rules=new j(this.client),this.logs=new M(this.client,e.baseUrl,n),this.collections=new J(this.client),this.blobs=new q(this.client,n,e.uploadPersistence),this.capabilities=new Q(this.client),this.notifications=new Y(this.client),this.schedules=new X(this.client),this.settings=new Z(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}async authenticated(){if(this.tokenProvider.identity()===null)return!1;try{return await this.client.dispatch(`system:core:heartbeat`,{notifyAuthStateChange:!1}),!0}catch{return!1}}heartbeatTimer;defaultHeartbeatInterval=300*1e3;startHeartbeat(e){this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval,n=()=>{this.heartbeatTimer=setTimeout(async()=>{await this.#e(),n()},t)};n()}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0)}async#e(){try{await this.client.dispatch(`system:core:heartbeat`)}catch{}}collection(e){return this.collections.documents(e)}ready(){return this.client.ready()}};function ee(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{B as AimdController,K as BlobNamespace,T as HestiaAuth,q as HestiaBlobClient,$ as HestiaClient,w as HestiaCollection,J as HestiaCollections,D as HestiaKeyStore,M as HestiaLogs,_ as HestiaNetworkClient,Y as HestiaNotificationStore,k as HestiaOperations,A as HestiaPolicies,h as HestiaResponse,j as HestiaRules,X as HestiaScheduleStore,Z as HestiaSettingStore,E as HestiaUsers,g as HttpTransport,H as ResumableUpload,V as UploadJobStore,U as UploadQueue,b as WailsTransport,ee as createArrayPager,C as createPagedController,R as getMissingRanges,p as internalError,d as notFound,l as parseErrorBody,f as permissionDenied,u 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;function v(){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}}function y(){throw new n({code:`HTTP_UNAVAILABLE`,message:`WailsTransport needs baseUrl and identityProvider for path-based requests. Use dispatch() instead.`})}var b=class{baseUrl=``;apiPrefix=``;init=new i({throws:!0});config;http;onUnauthorized;constructor(e){this.config=e,this.baseUrl=e?.baseUrl??``,this.apiPrefix=e?.apiPrefix??`/api`,this.onUnauthorized=e?.onUnauthorized,e?.baseUrl&&(this.http=new g(e.baseUrl,this.apiPrefix,()=>this.onUnauthorized?.()))}setOnUnauthorized(e,t){this.onUnauthorized=e,this.http||=new g(this.baseUrl||`http://wails.local`,this.apiPrefix,()=>this.onUnauthorized?.())}configure(e,t,n){this.baseUrl=e,this.apiPrefix=t,this.http||=new g(e,t,()=>this.onUnauthorized?.())}resolveService(){if(this.config)try{return window.go?.[this.config.pkg]?.[this.config.struct]??null}catch{return null}return v()}base(){return this.baseUrl}prefix(){return this.apiPrefix}routeUrl(e,t){if(!this.http)throw y();return this.http.routeUrl(e,t)}async ready(e=1e4){await 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){if(await this.ready(),this.http&&(t?.bodyType===`blob`||t?.bodyType===`stream`))return this.http.dispatch(e,t);let r=t?.notifyAuthStateChange??!0,a=t?.payload??null,o={...t?.modifiers??{}};t?.headers?.[`Content-Type`]&&(o.content_type=t.headers[`Content-Type`]);let s=this.resolveService();if(s?.Dispatch){let c;try{c=await s.Dispatch({name:e,arguments:t?.arguments??{},modifiers:o,payload:a})}catch(t){throw console.error(`[WailsTransport] dispatch "${e}" failed:`,t?.message??t),t instanceof n?t:new n({code:`DISPATCH_ERROR`,message:t?.message??String(t)})}if(c.status>=400){let t=c.data?.error,a=t?.code??`UNKNOWN`,o=t?.message??`dispatch returned status ${c.status}`;throw console.error(`[WailsTransport] dispatch "${e}" error [${a}]: ${o}`),c.status===401&&r&&(this.init=new i({throws:!0}),this.onUnauthorized?.()),new n({code:a,message:o})}return new h(c.data,c.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){if(await this.ready(),!this.http)throw y();return this.http.check(e,t,n)}async get(e,t){if(await this.ready(),!this.http)throw y();return this.http.get(e,t)}async post(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.post(e,t,n)}async patch(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.patch(e,t,n)}async put(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.put(e,t,n)}async delete(e,t,n){if(await this.ready(),!this.http)throw y();return this.http.delete(e,t,n)}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 x=globalThis.requestIdleCallback?.bind(globalThis)??((e,t)=>{let n=performance.now(),r={didTimeout:!1,timeRemaining:()=>Math.max(0,50-(performance.now()-n))};return setTimeout(()=>e(r),t?.timeout==null?0:Math.min(t.timeout,0))}),S={data:[],loading:!0,page:{number:1,size:20,count:0,total:0,pages:1}};function C(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()=>{x(()=>{x(async()=>{try{let n=await i(f(e));await t.set({[d]:n})}catch(e){await t.set({[d]:{...S,error:e}})}finally{await t.set({[d]:{loading:!1}})}})})}))})),m=t.select(e=>e[d]),h=m.subscribe(()=>{});return{page:()=>m.get()??S,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 w=class{client;collectionName;defaultLimit;pagerOptions={};pager;constructor(e,t,n=50){this.client=e,this.collectionName=t,this.defaultLimit=n,this.pager=C(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}},T=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 await this.provider.setIdentity(n.data.data.user),n.data.data}async register(e,t,n){return(await this.client.dispatch(`system:users:user:create`,{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}})}},E=class{client;pagerOptions={};pager;constructor(e){this.client=e,this.pager=C(`users`,new o({}),this.pagerOptions,e=>this.find(e))}name(){return`users`}async find(e){let t=await this.client.dispatch(`system:collections: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({data:e}){if(!e)throw Error(`User creation requires email/password/name`);return(await this.client.dispatch(`system:users:user:create`,{payload:e})).data.data}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}})}},D=class{client;pager;constructor(e){this.client=e,this.pager=C(`_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}};function O(e){let t=e;return{...e,_id_:t._id_??e.name,_metadata_:t._metadata_??{checksum:``,created:``,updated:``,version:1}}}var k=class{client;constructor(e){this.client=e}async list(){let e=(await this.client.dispatch(`system:policies:binding:list`)).data?.data?.bindings??[];return{data:e.map(e=>O(e)),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:binding:get`,{arguments:{name:e}});return t.data?.data?O(t.data.data):void 0}catch(e){if(e?.code===`SYNC-001-NF`||e?.code===`NOT_FOUND`)return;throw e}}},A=class{client;pager;constructor(e){this.client=e,this.pager=C(`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??[];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){let t=(await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[];return{data:t,loading:!1,page:{number:1,size:t.length,count:t.length,total:t.length,pages:1},error:null}}async read(e){try{return((await this.client.dispatch(`system:policies:policy:list`)).data?.data?.policies??[]).find(t=>t._id_===e||t.operation===e||t.id===e)||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={rule:e.data.rule??``,rateLimit:e.data.rateLimit,throttle:e.data.throttle};return(await this.client.dispatch(`system:policies:policy:create`,{arguments:{name:t},payload:n})).data.data}async update(e){let t=e.options;if(!t)throw Error(`Operation name is required for update`);let n={};return e.data.rule!==void 0&&(n.rule=e.data.rule),e.data.enabled!==void 0&&(n.enabled=e.data.enabled),e.data.rateLimit!==void 0&&(n.rateLimit=e.data.rateLimit),e.data.throttle!==void 0&&(n.throttle=e.data.throttle),(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:t},payload:n})).data.data}async setEnabled(e,t){return(await this.client.dispatch(`system:policies:policy:update`,{arguments:{name:e},payload:{enabled:t}})).data.data}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}},j=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`)}},M=class{client;baseUrl;pagerOptions={};pager;apiPrefix;constructor(e,t,n=`/api`){this.client=e,this.baseUrl=t,this.apiPrefix=n,this.pager=C(`_audit_log_`,new o({}),this.pagerOptions,e=>this.find(e))}async find(e){let t=await this.client.post(`/system/collections/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`}};const N=.3;function P(e){return new Promise(t=>setTimeout(t,e))}async function F(e){let t=await crypto.subtle.digest(`SHA-256`,e),n=new Uint8Array(t),r=``;for(let e of n)r+=e.toString(16).padStart(2,`0`);return r}function I(e,t,n){return e.slice(t,n)}function L(){return typeof crypto<`u`&&`randomUUID`in crypto?crypto.randomUUID():`upload_`+Date.now()+`_`+Math.random().toString(36).slice(2)}function R(e,t){let n=[],r=0;for(let t of e)t.start>r&&n.push({start:r,end:t.start}),t.end>r&&(r=t.end);return r<t&&n.push({start:r,end:t}),n}function z(e,t){let n=0,r=e.length?e[0].start:0;function i(){for(;n<e.length&&r>=e[n].end;)n++,n<e.length&&(r=e[n].start)}return{hasMore(){return i(),n<e.length},next(){if(i(),n>=e.length)return null;let a=Math.min(r+t,e[n].end),o={start:r,end:a};return r=a,o}}}var B=class{maxConcurrency;consecutiveSuccesses=0;lastBackoff=0;throughputEstimate;constructor(e,t=262144){this.maxConcurrency=e,this.throughputEstimate=t}estThroughput(){return this.throughputEstimate}recordThroughput(e){this.throughputEstimate=this.throughputEstimate*(1-N)+e*N}recordSuccess(){this.consecutiveSuccesses++,this.consecutiveSuccesses>=3&&(this.consecutiveSuccesses=0,this.maxConcurrency=Math.min(6,this.maxConcurrency+1))}recordFailure(){let e=Date.now();e-this.lastBackoff<2500||(this.lastBackoff=e,this.consecutiveSuccesses=0,this.maxConcurrency=Math.max(1,Math.floor(this.maxConcurrency/2)))}},V=class{backing;state={jobs:{}};instanceId=L();ready;constructor(e){this.backing=e,this.ready=this.hydrate()}async hydrate(){if(!this.backing)return;let e=await this.backing.get();e&&(this.state=e)}async save(e){await this.ready,this.state={jobs:{...this.state.jobs,[e.id]:e}},await this.backing?.set(this.instanceId,this.state)}async load(){if(await this.ready,this.backing){let e=await this.backing.get();e&&(this.state=e)}return Object.values(this.state.jobs)}async remove(e){await this.ready;let t={...this.state.jobs};delete t[e],this.state={jobs:t},await this.backing?.set(this.instanceId,this.state)}},H=class{id;status=`queued`;blockSize=0;sessionId=null;uploaded=0;hashed=0;hashTotal=0;bytesPerSecond=0;etaSeconds=0;fingerprint=``;error=null;onStatusChange;get done(){return this.attempt}total;key;file;options;transport;persistence;aimd;startedAt=Date.now();blockHashes=[];pauseRequested=!1;cancelRequested=!1;abortControllers=new Set;running=!1;lastProgressTime=0;lastProgressBytes=0;speedSamples=[];lastReportAt=0;attempt;resolveDone;rejectDone;constructor(e,t,n,r,i,a){this.transport=e,this.file=t,this.key=n,this.options=r,this.persistence=i,this.id=a?.id??L(),this.total=a?.size??t.size,this.blockSize=a?.blockSize??0,this.sessionId=a?.sessionId??null,this.blockHashes=a?.blockHashes??[],this.fingerprint=a?.fingerprint??``,this.uploaded=a?.uploadedBytes??0,this.status=a?`paused`:`queued`,this.aimd=new B(Math.max(1,r.concurrency??4)),this.newAttempt(),r.signal&&(r.signal.aborted?queueMicrotask(()=>void this.cancel()):r.signal.addEventListener(`abort`,()=>void this.cancel(),{once:!0}))}newAttempt(){this.attempt=new Promise((e,t)=>{this.resolveDone=e,this.rejectDone=t})}start(){this.status===`queued`&&(this.pauseRequested=!1,this.cancelRequested=!1,this.run())}resume(){(this.status===`paused`||this.status===`error`)&&(this.status===`error`&&this.newAttempt(),this.error=null,this.pauseRequested=!1,this.cancelRequested=!1,this.run())}retry(){this.resume()}pause(){if(this.status!==`completed`&&this.status!==`cancelled`){this.pauseRequested=!0;for(let e of this.abortControllers)e.abort();this.running||(this.setStatus(`paused`),this.report(),this.persist())}}async cancel(){if(this.status!==`completed`&&this.status!==`cancelled`){this.cancelRequested=!0;for(let e of this.abortControllers)e.abort();if(this.sessionId)try{await this.transport.abort(this.sessionId)}catch{}await this.persistence?.remove(this.id),this.running||(this.setStatus(`cancelled`),this.report(),this.resolveDone(void 0))}}async run(){if(!(this.running||this.status===`completed`||this.status===`cancelled`)){this.running=!0;try{if(this.blockSize===0&&(this.blockSize=this.chooseBlockSize(),await this.persist()),!this.sessionId){let e=await this.transport.beginUpload({key:this.key,size:this.total,contentType:this.options.contentType||this.file.type,blockSize:this.blockSize,overwrite:this.options.overwrite});this.sessionId=e.session_id,this.blockHashes.length===0&&e.block_size>0&&(this.blockSize=e.block_size),await this.persist()}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.blockHashes.length===0&&this.blockSize>0&&(this.setStatus(`hashing`),await this.hashBlocks()),this.pauseRequested){this.setStatus(`paused`),await this.persist();return}if(this.cancelRequested){this.finishCancelled();return}for(this.setStatus(`uploading`);!this.cancelRequested&&!this.pauseRequested;){if(!this.sessionId)throw Error(`upload session missing`);let e=await this.transport.progress(this.sessionId);if(this.uploaded=e.total,this.report(),this.uploaded>=this.total)break;let t=R(e.ranges??[],this.total);if(t.length===0)break;let n=await this.runUploadPool(t);if(n.cancelled)break;if(n.paused){this.setStatus(`paused`),this.report(),await this.persist();return}}if(this.cancelRequested){this.finishCancelled();return}if(!this.sessionId)throw Error(`upload session missing`);this.setStatus(`completing`),this.report();let e=await this.transport.completeUpload({sessionId:this.sessionId,overwrite:this.options.overwrite});this.uploaded=this.total,this.setStatus(`completed`),this.report(),await this.persistence?.remove(this.id),this.resolveDone(e)}catch(e){if(this.cancelRequested){this.finishCancelled();return}if(this.pauseRequested){this.setStatus(`paused`),await this.persist();return}this.error=e instanceof Error?e:Error(String(e)),this.setStatus(`error`),this.report(),await this.persist(),this.rejectDone(this.error)}finally{this.running=!1}}}finishCancelled(){this.setStatus(`cancelled`),this.report(),this.persistence?.remove(this.id),this.resolveDone(void 0)}chooseBlockSize(){let e=this.options.blockSize??8388608;return this.total<=0?0:Math.min(e,this.total)}async hashBlocks(){let e=this.blockSize,t=Math.ceil(this.total/e);this.blockHashes=Array(t),this.hashTotal=this.total,this.hashed=0;let n=performance.now();for(let r=0;r<t;r++){if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);for(;this.pauseRequested&&!this.cancelRequested;)await P(200);if(this.cancelRequested)throw Error(`Pre-hashing cancelled`);let t=r*e,i=Math.min(t+e,this.total),a=await I(this.file,t,i).arrayBuffer();this.blockHashes[r]=await F(a),this.hashed=i,this.report();let o=performance.now();o-n>12&&(await P(0),n=o)}let r=this.blockHashes.join(``);this.fingerprint=await F(new TextEncoder().encode(r)),await this.persist()}runUploadPool(e){return new Promise(t=>{let n=z(e,this.blockSize),r=!1,i=null,a=!1,o=0,s=()=>{r||o>0||(r=!0,i?(this.failPool(i),t({paused:!1,cancelled:!1})):t({paused:a&&!this.cancelRequested,cancelled:this.cancelRequested}))},c=()=>{o++,(async()=>{for(;!this.cancelRequested;){if(this.pauseRequested){a=!0;break}if(i||o>this.aimd.maxConcurrency)break;let e=n.next();if(!e)break;let t=await this.uploadOneChunk(e);if(!t.success){t.aborted?this.pauseRequested&&(a=!0):i=Error(`Chunk failed at ${e.start}`);break}}})().finally(()=>{o--,!this.cancelRequested&&!this.pauseRequested&&!i&&o<this.aimd.maxConcurrency&&n.hasMore()&&c(),s()})},l=Math.max(1,this.aimd.maxConcurrency),u=0;for(let e=0;e<l&&n.hasMore();e++)c(),u++;u===0&&s()})}failPool(e){this.status!==`completed`&&this.status!==`cancelled`&&(this.error=e,this.setStatus(`error`),this.report(),this.persist(),this.rejectDone(this.error))}async uploadOneChunk(e){let t=I(this.file,e.start,e.end);if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let n=Math.floor(e.start/this.blockSize),r=this.blockHashes[n],i=Math.max(0,this.options.retries??3),a=e.end-e.start;for(let n=1;n<=i+1;n++){if(this.cancelRequested||this.pauseRequested)return{success:!1,aborted:!0};let o=new AbortController;this.abortControllers.add(o);let s=Math.max(this.aimd.estThroughput(),32*1024),c=Math.max(6e3,a/s*1e3*3),l=setTimeout(()=>o.abort(),c),u=performance.now();try{if(!this.sessionId)throw Error(`upload session missing`);let n=await this.transport.uploadChunk({sessionId:this.sessionId,offset:e.start,data:t,sha256:r,signal:o.signal});clearTimeout(l),this.abortControllers.delete(o);let i=(performance.now()-u)/1e3;return this.aimd.recordSuccess(),this.onChunkUploaded(a,i,n),{success:!0,aborted:!1}}catch(e){if(clearTimeout(l),this.abortControllers.delete(o),this.cancelRequested||this.pauseRequested&&e instanceof DOMException&&e.name===`AbortError`)return{success:!1,aborted:!0};this.aimd.recordFailure(),n<=i&&await P(1500*2**(n-1))}}return{success:!1,aborted:!1}}onChunkUploaded(e,t,n){t>.05&&this.aimd.recordThroughput(e/t),this.uploaded=n;let r=Date.now();if(!this.lastProgressTime)this.lastProgressTime=r,this.lastProgressBytes=n;else if(r-this.lastProgressTime>1e3){let e=n-this.lastProgressBytes,t=(r-this.lastProgressTime)/1e3;if(t>0){let n=e/t;this.speedSamples.push(n),this.speedSamples.length>5&&this.speedSamples.shift()}this.lastProgressTime=r,this.lastProgressBytes=n}let i=this.speedSamples.length>0?this.speedSamples.reduce((e,t)=>e+t,0)/this.speedSamples.length:0;this.bytesPerSecond=i;let a=this.total-this.uploaded;this.etaSeconds=i>0&&a>0?a/i:0,this.report()}report(){let e=performance.now();if(this.status===`uploading`&&e-this.lastReportAt<80)return;this.lastReportAt=e;let t=this.status===`hashing`?`hash`:`upload`,n=t===`hash`?this.hashTotal>0?this.hashed/this.hashTotal:0:this.total>0?this.uploaded/this.total:1;this.options.onProgress?.({phase:t,hashed:this.hashed,hashTotal:this.hashTotal,uploaded:this.uploaded,total:this.total,percent:Math.min(1,n),bytesPerSecond:this.bytesPerSecond,etaSeconds:this.etaSeconds,fingerprint:this.fingerprint||void 0})}snapshot(){return{id:this.id,key:this.key,name:this.file.name,size:this.total,type:this.file.type,file:this.file,sessionId:this.sessionId,blockSize:this.blockSize,blockHashes:this.blockHashes,fingerprint:this.fingerprint,uploadedBytes:this.uploaded,status:this.status,error:this.error?this.error.message:null}}async persist(){if(this.persistence)try{await this.persistence.save(this.snapshot())}catch{}}setStatus(e){this.status!==e&&(this.status=e,this.onStatusChange?.(e))}},U=class{jobs=new Map;queue=[];active=0;runningJobs=new WeakSet;maxConcurrent;persistence;transport;ns;constructor(e,t,n={}){this.transport=e,this.ns=t,this.maxConcurrent=Math.max(1,n.maxConcurrent??3),this.persistence=n.persistence}enqueue(e,t){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);let r=new H(this.transport,e,n,t,this.persistence);return r.onStatusChange=e=>{if(e===`queued`)return;let t=e===`hashing`||e===`uploading`||e===`completing`,n=e===`paused`||e===`completed`||e===`error`||e===`cancelled`;if(t&&!this.runningJobs.has(r)?(this.runningJobs.add(r),this.active++,this.pump()):n&&this.runningJobs.has(r)&&(this.runningJobs.delete(r),this.active=Math.max(0,this.active-1),this.pump()),e===`cancelled`||e===`completed`){let e=this.queue.indexOf(r.id);e!==-1&&this.queue.splice(e,1)}},this.jobs.set(r.id,r),this.queue.push(r.id),this.pump(),r}pump(){for(;this.active<this.maxConcurrent&&this.queue.length>0;){let e=this.queue.shift();if(!e)continue;let t=this.jobs.get(e);t&&(this.runningJobs.add(t),this.active++,t.start())}}restore(e){return(this.persistence?this.persistence.load():Promise.resolve([]))instanceof Promise,[]}async restoreAsync(e){if(!this.persistence)return[];let t=await this.persistence.load(),n=[];for(let r of t){let t=r.file??e?.(r);if(!t)continue;let i=new H(this.transport,t,r.key,{key:r.key,contentType:r.type,overwrite:!1},this.persistence,r);this.jobs.set(i.id,i),n.push(i)}return n}pause(e){let t=this.jobs.get(e);if(t){if(t.status===`queued`){let t=this.queue.indexOf(e);t!==-1&&this.queue.splice(t,1)}t.pause()}}resume(e){this.jobs.get(e)?.resume()}retry(e){this.jobs.get(e)?.retry()}async cancel(e){let t=this.jobs.get(e);if(!t)return;let n=this.queue.indexOf(e);n!==-1&&this.queue.splice(n,1),await t.cancel()}pauseAll(){for(let e of this.jobs.values())(e.status===`uploading`||e.status===`hashing`||e.status===`queued`)&&e.pause()}resumeAll(){for(let e of this.jobs.values())(e.status===`paused`||e.status===`error`)&&e.resume()}clearCompleted(){for(let[e,t]of Array.from(this.jobs))(t.status===`completed`||t.status===`cancelled`)&&this.jobs.delete(e)}all(){return Array.from(this.jobs.values())}summary(){let e=this.all().filter(e=>[`uploading`,`hashing`,`queued`,`completing`].includes(e.status)),t=this.all().filter(e=>e.status===`paused`),n=this.all().filter(e=>e.status===`completed`),r=this.all().filter(e=>e.status===`cancelled`),i=this.all().filter(e=>e.status===`error`),a=0,o=0,s=0;for(let t of e)a+=t.total,o+=t.uploaded,s+=t.bytesPerSecond;let c=Math.max(0,a-o),l=s>0?c/s:0;return{active:e.length,paused:t.length,done:n.length,cancelled:r.length,failed:i.length,totalBytes:a,uploadedBytes:o,bytesPerSecond:s,etaSeconds:l}}};function W(e){return{_id_:e.key,_metadata_:{checksum:``,created:e.created_at,updated:e.updated_at??e.created_at,version:1},...e}}function G(e){return{number:1,size:e.length,count:e.length,total:e.length,pages:1}}var K=class{client;ns;persistence;pagerOptions={};pager;prefixFilter=``;_queue;constructor(e,t,n){this.client=e,this.ns=t,this.persistence=n,this.pager=C(`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(W),loading:!1,page:G(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?W(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 W((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=e.options?.threshold??16777216;if(!e.options?.forceStaged&&e.file.size<=n)return this.uploadDirect(e.file,t,e.options);let r=this.createUpload(e.file,e.options);return r.start(),r.done}createUpload(e,t={}){let n=t.key;if(!n)throw Error(`options.key is required for blob upload`);return new H(this,e,n,t,this.persistence)}queue(e){return this._queue||=new U(this,this.ns,e),this._queue}async uploadDirect(e,t,n){let r={},i=n?.contentType||e.type;return i&&(r[`Content-Type`]=i),W((await this.client.dispatch(`system:blobs:blob:upload`,{arguments:{ns:this.ns,key:t},modifiers:n?.overwrite?{overwrite:`true`}:void 0,payload:e,headers:r,bodyType:`blob`})).data.data)}async beginUpload(e){return(await this.client.dispatch(`system:blobs:blob:begin`,{arguments:{ns:this.ns},modifiers:e.overwrite?{overwrite:`true`}:void 0,payload:{key:e.key,size:e.size,content_type:e.contentType,block_size:e.blockSize}})).data.data}async uploadChunk(e){let t={"X-Session-ID":e.sessionId,"X-Offset":String(e.offset)};return e.sha256&&(t[`X-Chunk-SHA256`]=e.sha256),(await this.client.dispatch(`system:blobs:blob:chunk`,{arguments:{ns:this.ns},headers:t,payload:e.data,bodyType:`blob`,signal:e.signal})).data.data.total}async completeUpload(e){return W((await this.client.dispatch(`system:blobs:blob:complete`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e.sessionId},modifiers:e.overwrite?{overwrite:`true`}:void 0})).data.data)}async progress(e){return(await this.client.dispatch(`system:blobs:blob:progress`,{arguments:{ns:this.ns},modifiers:{session_id:e}})).data.data}async abort(e){await this.client.dispatch(`system:blobs:blob:abort`,{arguments:{ns:this.ns},headers:{"X-Session-ID":e}})}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}}},q=class{client;uploadPersistence;apiPrefix;constructor(e,t=`/api`,n){this.client=e,this.uploadPersistence=n,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`,{arguments:{ns:e.ns},payload:{display_name:e.display_name}})).data.data}async deleteNamespace(e){await this.client.dispatch(`system:blobs:namespace:delete`,{arguments:{ns:e}})}blob(e,t){return this.client.routeUrl(`system:blobs:blob:download`,{ns:e,key:t})}namespace(e){return new K(this.client,e,this.uploadPersistence)}},J=class{client;constructor(e){this.client=e}async find(e){let t=(await this.client.dispatch(`system:collections:collection: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){try{let t=await this.client.dispatch(`system:collections:collection:get`,{arguments:{name:e}});return t.data?t.data.data:void 0}catch(e){if(e?.code===`SYNC-001-NF`)return;throw e}}async create(e){let t=e.data.schema??e.data;return(await this.client.dispatch(`system:collections:collection:create`,{payload:t})).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 w(this.client,e)}},Y=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:notifications:notification:list`)).data?.data??[]}async markRead(e){await this.client.dispatch(`system:notifications:notification:read`,{arguments:{notification_id:e}})}async markAllRead(){await this.client.dispatch(`system:notifications:read:all`)}async countUnread(){return(await this.client.dispatch(`system:notifications:unread:count`)).data?.data?.count??0}},X=class{client;constructor(e){this.client=e}async create(e){return(await this.client.dispatch(`system:schedules:schedule:create`,{payload:e})).data?.data?.id??``}async list(){return(await this.client.dispatch(`system:schedules:schedule:list`)).data?.data??[]}async get(e){return(await this.client.dispatch(`system:schedules:schedule:get`,{arguments:{id:e}})).data?.data??null}async update(e,t){await this.client.dispatch(`system:schedules:schedule:update`,{arguments:{id:e},payload:t})}async delete(e){await this.client.dispatch(`system:schedules:schedule:delete`,{arguments:{id:e}})}},Z=class{client;constructor(e){this.client=e}async list(){return(await this.client.dispatch(`system:settings:list`)).data?.data??[]}async get(e){try{return(await this.client.dispatch(`system:settings:get`,{arguments:{key:e}})).data?.data}catch{return}}async set(e,t){await this.client.dispatch(`system:settings:set`,{arguments:{key:e},payload:{value:t}})}async delete(e){await this.client.dispatch(`system:settings:delete`,{arguments:{key:e}})}},Q=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`)}},$=class{store;client;auth;users;keys;policies;rules;logs;collections;blobs;core;notifications;schedules;settings;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`,r=()=>{t.clear(),this.onAuthStateChanged?.()};this.tokenProvider=t,e.transport instanceof b?(e.transport.configure(e.baseUrl,n,t),e.transport.setOnUnauthorized(r),this.client=e.transport):this.client=e.transport??new g(e.baseUrl,n,r),this.auth=new T(this.client,t),this.users=new E(this.client),this.keys=new D(this.client),this.policies=new A(this.client),this.rules=new j(this.client),this.logs=new M(this.client,e.baseUrl,n),this.collections=new J(this.client),this.blobs=new q(this.client,n,e.uploadPersistence),this.core=new Q(this.client),this.notifications=new Y(this.client),this.schedules=new X(this.client),this.settings=new Z(this.client)}onAuthStateChange(e){this.onAuthStateChanged=e}async authenticated(){if(this.tokenProvider.identity()===null)return!1;try{return await this.client.dispatch(`system:core:heartbeat`,{notifyAuthStateChange:!1}),!0}catch{return!1}}heartbeatTimer;defaultHeartbeatInterval=300*1e3;startHeartbeat(e){this.stopHeartbeat();let t=e??this.defaultHeartbeatInterval,n=()=>{this.heartbeatTimer=setTimeout(async()=>{await this.#e(),n()},t)};n()}stopHeartbeat(){this.heartbeatTimer!==void 0&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=void 0)}async#e(){try{await this.client.dispatch(`system:core:heartbeat`)}catch{}}collection(e){return this.collections.documents(e)}ready(){return this.client.ready()}};function ee(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{B as AimdController,K as BlobNamespace,T as HestiaAuth,q as HestiaBlobClient,$ as HestiaClient,w as HestiaCollection,J as HestiaCollections,Q as HestiaCore,D as HestiaKeyStore,M as HestiaLogs,_ as HestiaNetworkClient,Y as HestiaNotificationStore,k as HestiaOperations,A as HestiaPolicies,h as HestiaResponse,j as HestiaRules,X as HestiaScheduleStore,Z as HestiaSettingStore,E as HestiaUsers,g as HttpTransport,H as ResumableUpload,V as UploadJobStore,U as UploadQueue,b as WailsTransport,ee as createArrayPager,C as createPagedController,R as getMissingRanges,p as internalError,d as notFound,l as parseErrorBody,f as permissionDenied,u as toSystemError};
|
package/package.json
CHANGED