eventsourcingdb 1.2.2 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -422,7 +422,29 @@ controller.abort();
422
422
  To list a specific event type, call the `readEventType` function with the event type as an argument. The function returns the detailed event type, which includes the schema:
423
423
 
424
424
  ```typescript
425
- eventType = await client.readEventType("io.eventsourcingdb.library.book-acquired")
425
+ eventType = await client.readEventType("io.eventsourcingdb.library.book-acquired");
426
+ ```
427
+
428
+ ### Verifying an Event's Hash
429
+
430
+ To verify the integrity of an event, call the `verifyHash` function on the event instance. This recomputes the event's hash locally and compares it to the hash stored in the event. If the hashes differ, the function returns an error:
431
+
432
+ ```typescript
433
+ event.VerifyHash();
434
+ ```
435
+
436
+ *Note that this only verifies the hash. If you also want to verify the signature, you can skip this step and call `verifySignature` directly, which performs a hash verification internally.*
437
+
438
+ ### Verifying an Event's Signature
439
+
440
+ To verify the authenticity of an event, call the `verifySignature` function on the event instance. This requires the public key that matches the private key used for signing on the server.
441
+
442
+ The function first verifies the event's hash, and then checks the signature. If any verification step fails, it returns an error:
443
+
444
+ ```typescript
445
+ const verificationKey = // an ed25519 public key
446
+
447
+ event.verifySignature(verificationKey);
426
448
  ```
427
449
 
428
450
  ### Using Testcontainers
@@ -465,6 +487,22 @@ const container = new Container()
465
487
  .withApiToken('secret');
466
488
  ```
467
489
 
490
+ If you want to sign events, call the `withSigningKey` function. This generates a new signing and verification key pair inside the container:
491
+
492
+ ```typescript
493
+ const container = new Container()
494
+ .withSigningKey();
495
+ ```
496
+
497
+ You can retrieve the private key (for signing) and the public key (for verifying signatures) once the container has been started:
498
+
499
+ ```typescript
500
+ const signingKey = container.getSigningKey();
501
+ const verificationKey = container.getVerificationKey();
502
+ ```
503
+
504
+ The `signingKey` can be used when configuring the container to sign outgoing events. The `verificationKey` can be passed to `verifySignature` when verifying events read from the database.
505
+
468
506
  #### Configuring the Client Manually
469
507
 
470
508
  In case you need to set up the client yourself, use the following functions to get details on the container:
package/dist/index.d.mts CHANGED
@@ -1,4 +1,7 @@
1
- interface Event {
1
+ import crypto from 'node:crypto';
2
+
3
+ declare class Event {
4
+ #private;
2
5
  specversion: string;
3
6
  id: string;
4
7
  time: Date;
@@ -11,6 +14,25 @@ interface Event {
11
14
  predecessorhash: string;
12
15
  traceparent?: string;
13
16
  tracestate?: string;
17
+ signature: string | null;
18
+ constructor({ specversion, id, time, timeFromServer, source, subject, type, datacontenttype, data, hash, predecessorhash, traceparent, tracestate, signature, }: {
19
+ specversion: string;
20
+ id: string;
21
+ time: Date;
22
+ timeFromServer: string;
23
+ source: string;
24
+ subject: string;
25
+ type: string;
26
+ datacontenttype: string;
27
+ data: Record<string, unknown>;
28
+ hash: string;
29
+ predecessorhash: string;
30
+ traceparent?: string;
31
+ tracestate?: string;
32
+ signature: string | null;
33
+ });
34
+ verifyHash(): void;
35
+ verifySignature(verificationKey: crypto.KeyObject): void;
14
36
  }
15
37
 
16
38
  interface EventCandidate {
@@ -101,19 +123,24 @@ declare class Container {
101
123
  #private;
102
124
  withImageTag(tag: string): this;
103
125
  withApiToken(token: string): this;
126
+ withSigningKey(): this;
104
127
  withPort(port: number): this;
105
128
  start(): Promise<void>;
106
129
  getHost(): string;
107
130
  getMappedPort(): number;
108
131
  getBaseUrl(): URL;
109
132
  getApiToken(): string;
133
+ getSigningKey(): crypto.KeyObject;
134
+ getVerificationKey(): crypto.KeyObject;
110
135
  isRunning(): boolean;
111
136
  stop(): Promise<void>;
112
137
  getClient(): Client;
113
138
  }
114
139
 
140
+ declare const isEventQlQueryTrue: (query: string) => Precondition;
141
+
115
142
  declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
116
143
 
117
144
  declare const isSubjectPristine: (subject: string) => Precondition;
118
145
 
119
- export { Client, Container, type Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isSubjectOnEventId, isSubjectPristine };
146
+ export { Client, Container, Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPristine };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
- interface Event {
1
+ import crypto from 'node:crypto';
2
+
3
+ declare class Event {
4
+ #private;
2
5
  specversion: string;
3
6
  id: string;
4
7
  time: Date;
@@ -11,6 +14,25 @@ interface Event {
11
14
  predecessorhash: string;
12
15
  traceparent?: string;
13
16
  tracestate?: string;
17
+ signature: string | null;
18
+ constructor({ specversion, id, time, timeFromServer, source, subject, type, datacontenttype, data, hash, predecessorhash, traceparent, tracestate, signature, }: {
19
+ specversion: string;
20
+ id: string;
21
+ time: Date;
22
+ timeFromServer: string;
23
+ source: string;
24
+ subject: string;
25
+ type: string;
26
+ datacontenttype: string;
27
+ data: Record<string, unknown>;
28
+ hash: string;
29
+ predecessorhash: string;
30
+ traceparent?: string;
31
+ tracestate?: string;
32
+ signature: string | null;
33
+ });
34
+ verifyHash(): void;
35
+ verifySignature(verificationKey: crypto.KeyObject): void;
14
36
  }
15
37
 
16
38
  interface EventCandidate {
@@ -101,19 +123,24 @@ declare class Container {
101
123
  #private;
102
124
  withImageTag(tag: string): this;
103
125
  withApiToken(token: string): this;
126
+ withSigningKey(): this;
104
127
  withPort(port: number): this;
105
128
  start(): Promise<void>;
106
129
  getHost(): string;
107
130
  getMappedPort(): number;
108
131
  getBaseUrl(): URL;
109
132
  getApiToken(): string;
133
+ getSigningKey(): crypto.KeyObject;
134
+ getVerificationKey(): crypto.KeyObject;
110
135
  isRunning(): boolean;
111
136
  stop(): Promise<void>;
112
137
  getClient(): Client;
113
138
  }
114
139
 
140
+ declare const isEventQlQueryTrue: (query: string) => Precondition;
141
+
115
142
  declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
116
143
 
117
144
  declare const isSubjectPristine: (subject: string) => Precondition;
118
145
 
119
- export { Client, Container, type Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isSubjectOnEventId, isSubjectPristine };
146
+ export { Client, Container, Event, type EventCandidate, type EventType, type ObserveEventsOptions, type Precondition, type ReadEventsOptions, isEventQlQueryTrue, isSubjectOnEventId, isSubjectPristine };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var E=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var F=(r,t)=>{for(var e in t)E(r,e,{get:t[e],enumerable:!0})},L=(r,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of k(t))!$.call(r,i)&&i!==e&&E(r,i,{get:()=>t[i],enumerable:!(o=x(t,i))||o.enumerable});return r};var R=r=>L(E({},"__esModule",{value:!0}),r);var M={};F(M,{Client:()=>y,Container:()=>b,isSubjectOnEventId:()=>O,isSubjectPristine:()=>C});module.exports=R(M);var v=r=>({...r,time:new Date(r.time)});var c=(r,t)=>{if(typeof t!=typeof r)return!1;if(t===null||r===null)return t===null&&r===null;if(typeof t=="object"){if(Array.isArray(t)||Array.isArray(r))return!1;let e=t,o=r;for(let i of Object.keys(e))if(!(i in o)||!c(o[i],e[i]))return!1;return!0}return!0};var H={specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"},S=r=>c(r,H);var l=async function*(r,t){let e=r.getReader(),o=new TextDecoder("utf-8"),i="",p=()=>{e.cancel().catch(()=>{})};if(t.aborted){await e.cancel().catch(()=>{});return}t.addEventListener("abort",p);try{for(;!t.aborted;){let{done:d,value:u}=await e.read();if(d)break;i+=o.decode(u,{stream:!0});let a;for(;a=i.indexOf(`
2
- `),a!==-1;){let n=i.slice(0,a).trim();i=i.slice(a+1),n&&(yield JSON.parse(n))}}}finally{t.removeEventListener("abort",p),await e.cancel().catch(()=>{})}};var B={type:"event",payload:{specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"}},g=r=>!(!c(r,B)||r.type!=="event");var I={type:"error",payload:{error:"string"}},m=r=>!(!c(r,I)||r.type!=="error");var N={type:"eventType",payload:{eventType:"string",isPhantom:!0}},T=r=>!(!c(r,N)||r.type!=="eventType");var J={type:"heartbeat"},h=r=>!(!c(r,J)||r.type!=="heartbeat");var z={type:"row"},j=r=>!(!c(r,z)||r.type!=="row"||!("payload"in r));var U={type:"subject",payload:{subject:"string"}},A=r=>!(!c(r,U)||r.type!=="subject");var y=class{#o;#e;#t(t){return new URL(t,this.#o).toString()}constructor(t,e){this.#o=t,this.#e=e}async ping(){let t=this.#t("/api/v1/ping"),e=await fetch(t,{method:"get"});if(e.status!==200)throw new Error(`Failed to ping, got HTTP status code '${e.status}', expected '200'.`);let o=await e.json();if(!c(o,{type:"string"}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.ping-received")throw new Error("Failed to ping.")}async verifyApiToken(){let t=this.#t("/api/v1/verify-api-token"),e=await fetch(t,{method:"post",headers:{authorization:`Bearer ${this.#e}`}});if(e.status!==200)throw new Error(`Failed to verify API token, got HTTP status code '${e.status}', expected '200'.`);let o=await e.json();if(!c(o,{type:"string"}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.api-token-verified")throw new Error("Failed to verify API token.")}async writeEvents(t,e=[]){let o=this.#t("/api/v1/write-events"),i=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({events:t,preconditions:e})});if(i.status!==200)throw new Error(`Failed to write events, got HTTP status code '${i.status}', expected '200'.`);let p=await i.json();if(!Array.isArray(p))throw new Error("Failed to parse response.");return p.map(u=>{if(!S(u))throw new Error("Failed to parse response item.");return v(u)})}readEvents(t,e,o){let i=this.#t("/api/v1/read-events"),p=this.#e;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,n;if(o&&!o.aborted){let s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),n=()=>o.removeEventListener("abort",s)}try{let s=await fetch(i,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:e}),signal:u});if(s.status!==200)throw new Error(`Failed to read events, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to read events.");for await(let f of l(s.body,u)){if(m(f))throw new Error(`${f.payload.error}.`);if(g(f)){yield v(f.payload);continue}throw new Error("Failed to read events.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{n&&n(),a&&d.abort()}})()}runEventQlQuery(t,e){let o=this.#t("/api/v1/run-eventql-query"),i=this.#e;return(async function*(){let p=new AbortController,d=e??p.signal,u=!e,a;if(e&&!e.aborted){let n=()=>p.abort();e.addEventListener("abort",n,{once:!0}),a=()=>e.removeEventListener("abort",n)}try{let n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({query:t}),signal:d});if(n.status!==200)throw new Error(`Failed to run EventQL query, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to run EventQL query.");for await(let s of l(n.body,d))if(!h(s)){if(m(s))throw new Error(`${s.payload.error}.`);if(j(s)){yield s.payload;continue}throw new Error("Failed to run EventQL query.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{a&&a(),u&&p.abort()}})()}observeEvents(t,e,o){let i=this.#t("/api/v1/observe-events"),p=this.#e;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,n;if(o&&!o.aborted){let s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),n=()=>o.removeEventListener("abort",s)}try{let s=await fetch(i,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:e}),signal:u});if(s.status!==200)throw new Error(`Failed to observe events, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to observe events.");for await(let f of l(s.body,u))if(!h(f)){if(m(f))throw new Error(`${f.payload.error}.`);if(g(f)){yield v(f.payload);continue}throw new Error("Failed to observe events.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{n&&n(),a&&d.abort()}})()}async registerEventSchema(t,e){let o=this.#t("/api/v1/register-event-schema"),i=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({eventType:t,schema:e})});if(i.status!==200)throw new Error(`Failed to register event schema, got HTTP status code '${i.status}', expected '200'.`)}readSubjects(t,e){let o=this.#t("/api/v1/read-subjects"),i=this.#e;return(async function*(){let p=new AbortController,d=e??p.signal,u=!e,a;if(e&&!e.aborted){let n=()=>p.abort();e.addEventListener("abort",n,{once:!0}),a=()=>e.removeEventListener("abort",n)}try{let n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:t}),signal:d});if(n.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to read subjects.");for await(let s of l(n.body,d)){if(m(s))throw new Error(`${s.payload.error}.`);if(A(s)){yield s.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{a&&a(),u&&p.abort()}})()}async readEventType(t){let e=this.#t("/api/v1/read-event-type"),o=await fetch(e,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({eventType:t})});if(o.status!==200)throw new Error(`Failed to read event type, got HTTP status code '${o.status}', expected '200'.`);let i=await o.json();if(!c(i,{eventType:"string",isPhantom:!0}))throw new Error("Failed to parse response.");return i}readEventTypes(t){let e=this.#t("/api/v1/read-event-types"),o=this.#e;return(async function*(){let i=new AbortController,p=t??i.signal,d=!t,u;if(t&&!t.aborted){let a=()=>i.abort();t.addEventListener("abort",a,{once:!0}),u=()=>t.removeEventListener("abort",a)}try{let a=await fetch(e,{method:"post",headers:{authorization:`Bearer ${o}`},signal:p});if(a.status!==200)throw new Error(`Failed to read event types, got HTTP status code '${a.status}', expected '200'.`);if(!a.body)throw new Error("Failed to read event types.");for await(let n of l(a.body,p))if(!h(n)){if(m(n))throw new Error(`${n.payload.error}.`);if(T(n)){yield n.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{u&&u(),d&&i.abort()}})()}};var w=require("testcontainers");var b=class{#o="thenativeweb/eventsourcingdb";#e="latest";#t=3e3;#n="secret";#r;withImageTag(t){return this.#e=t,this}withApiToken(t){return this.#n=t,this}withPort(t){return this.#t=t,this}async start(){this.#r=await new w.GenericContainer(`${this.#o}:${this.#e}`).withExposedPorts(this.#t).withCommand(["run","--api-token",this.#n,"--data-directory-temporary","--http-enabled","--https-enabled=false"]).withWaitStrategy(w.Wait.forHttp("/api/v1/ping",this.#t).withStartupTimeout(1e4)).start()}getHost(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getHost()}getMappedPort(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getMappedPort(this.#t)}getBaseUrl(){if(this.#r===void 0)throw new Error("Container must be running.");let t=this.getHost(),e=this.getMappedPort();return new URL(`http://${t}:${e}`)}getApiToken(){return this.#n}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new y(this.getBaseUrl(),this.getApiToken())}};var O=(r,t)=>({type:"isSubjectOnEventId",payload:{subject:r,eventId:t}});var C=r=>({type:"isSubjectPristine",payload:{subject:r}});0&&(module.exports={Client,Container,isSubjectOnEventId,isSubjectPristine});
1
+ "use strict";var J=Object.create;var g=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,M=Object.prototype.hasOwnProperty;var q=(e,t)=>{for(var r in t)g(e,r,{get:t[r],enumerable:!0})},$=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of z(t))!M.call(e,n)&&n!==r&&g(e,n,{get:()=>t[n],enumerable:!(o=Q(t,n))||o.enumerable});return e};var R=(e,t,r)=>(r=e!=null?J(D(e)):{},$(t||!e||!e.__esModule?g(r,"default",{value:e,enumerable:!0}):r,e)),V=e=>$(g({},"__esModule",{value:!0}),e);var W={};q(W,{Client:()=>v,Container:()=>O,isEventQlQueryTrue:()=>K,isSubjectOnEventId:()=>N,isSubjectPristine:()=>U});module.exports=V(W);var w=R(require("crypto")),E=class{specversion;id;time;#o;source;subject;type;datacontenttype;data;hash;predecessorhash;traceparent;tracestate;signature;constructor({specversion:t,id:r,time:o,timeFromServer:n,source:c,subject:d,type:u,datacontenttype:a,data:i,hash:s,predecessorhash:f,traceparent:x,tracestate:G,signature:I}){this.specversion=t,this.id=r,this.time=o,this.#o=n,this.source=c,this.subject=d,this.type=u,this.datacontenttype=a,this.data=i,this.hash=s,this.predecessorhash=f,this.traceparent=x,this.tracestate=G,this.signature=I}verifyHash(){let t=`${this.specversion}|${this.id}|${this.predecessorhash}|${this.#o}|${this.source}|${this.subject}|${this.type}|${this.datacontenttype}`,r=w.default.createHash("sha256").update(t).digest("hex"),o=w.default.createHash("sha256").update(JSON.stringify(this.data)).digest("hex");if(w.default.createHash("sha256").update(`${r}${o}`).digest("hex")!==this.hash)throw new Error("Failed to verify hash.")}verifySignature(t){if(this.signature===null)throw new Error("Signature must not be null.");this.verifyHash();let r="esdb:signature:v1:";if(!this.signature.startsWith(r))throw new Error(`Signature must start with '${r}'`);let o=this.signature.slice(r.length),n=Buffer.from(o,"hex"),c=Buffer.from(this.hash,"utf8");if(!w.default.verify(null,c,t,n))throw new Error("Signature verification failed.")}};var S=e=>new E({specversion:e.specversion,id:e.id,time:new Date(e.time),timeFromServer:e.time,source:e.source,subject:e.subject,type:e.type,datacontenttype:e.datacontenttype,data:e.data,hash:e.hash,predecessorhash:e.predecessorhash,traceparent:e.traceparent,tracestate:e.tracestate,signature:e.signature});var y=e=>!(e===null||typeof e!="object"||Array.isArray(e));var h=(e,t)=>{if(!y(e))return!1;for(let r of Object.keys(t)){let o=t[r],n=e[r];if(typeof o=="function"){if(!o(n))return!1;continue}if(!y(n)||!h(n,o))return!1}return!0};var p=e=>typeof e=="string";var T=e=>e===null||typeof e=="string";var m=e=>e===void 0||typeof e=="string";var F=e=>h(e,{specversion:p,id:p,time:p,source:p,subject:p,type:p,datacontenttype:p,data:y,hash:p,predecessorhash:p,traceparent:m,tracestate:m,signature:T});var l=async function*(e,t){let r=e.getReader(),o=new TextDecoder("utf-8"),n="",c=()=>{r.cancel().catch(()=>{})};if(t.aborted){await r.cancel().catch(()=>{});return}t.addEventListener("abort",c);try{for(;!t.aborted;){let{done:d,value:u}=await r.read();if(d)break;n+=o.decode(u,{stream:!0});let a;for(;a=n.indexOf(`
2
+ `),a!==-1;){let i=n.slice(0,a).trim();n=n.slice(a+1),i&&(yield JSON.parse(i))}}}finally{t.removeEventListener("abort",c),await r.cancel().catch(()=>{})}};var C=e=>h(e,{type:t=>t==="event",payload:{specversion:p,id:p,time:p,source:p,subject:p,type:p,datacontenttype:p,data:y,hash:p,predecessorhash:p,traceparent:m,tracestate:m,signature:T}});var b=e=>h(e,{type:t=>t==="error",payload:{error:p}});var j=e=>typeof e=="boolean";var H=e=>h(e,{type:t=>t==="eventType",payload:{eventType:p,isPhantom:j}});var A=e=>h(e,{type:t=>t==="heartbeat"});var B=e=>h(e,{type:t=>t==="row",payload:y});var L=e=>h(e,{type:t=>t==="subject",payload:{subject:p}});var v=class{#o;#e;#t(t){return new URL(t,this.#o).toString()}constructor(t,r){this.#o=t,this.#e=r}async ping(){let t=this.#t("/api/v1/ping"),r=await fetch(t,{method:"get"});if(r.status!==200)throw new Error(`Failed to ping, got HTTP status code '${r.status}', expected '200'.`);let o=await r.json();if(!h(o,{type:p}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.ping-received")throw new Error("Failed to ping.")}async verifyApiToken(){let t=this.#t("/api/v1/verify-api-token"),r=await fetch(t,{method:"post",headers:{authorization:`Bearer ${this.#e}`}});if(r.status!==200)throw new Error(`Failed to verify API token, got HTTP status code '${r.status}', expected '200'.`);let o=await r.json();if(!h(o,{type:p}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.api-token-verified")throw new Error("Failed to verify API token.")}async writeEvents(t,r=[]){let o=this.#t("/api/v1/write-events"),n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({events:t,preconditions:r})});if(n.status!==200)throw new Error(`Failed to write events, got HTTP status code '${n.status}', expected '200'.`);let c=await n.json();if(!Array.isArray(c))throw new Error("Failed to parse response.");return c.map(u=>{if(!F(u))throw new Error("Failed to parse response item.");return S(u)})}readEvents(t,r,o){let n=this.#t("/api/v1/read-events"),c=this.#e;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,i;if(o&&!o.aborted){let s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),i=()=>o.removeEventListener("abort",s)}try{let s=await fetch(n,{method:"post",headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:r}),signal:u});if(s.status!==200)throw new Error(`Failed to read events, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to read events.");for await(let f of l(s.body,u)){if(b(f))throw new Error(`${f.payload.error}.`);if(C(f)){yield S(f.payload);continue}throw new Error("Failed to read events.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{i&&i(),a&&d.abort()}})()}runEventQlQuery(t,r){let o=this.#t("/api/v1/run-eventql-query"),n=this.#e;return(async function*(){let c=new AbortController,d=r??c.signal,u=!r,a;if(r&&!r.aborted){let i=()=>c.abort();r.addEventListener("abort",i,{once:!0}),a=()=>r.removeEventListener("abort",i)}try{let i=await fetch(o,{method:"post",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({query:t}),signal:d});if(i.status!==200)throw new Error(`Failed to run EventQL query, got HTTP status code '${i.status}', expected '200'.`);if(!i.body)throw new Error("Failed to run EventQL query.");for await(let s of l(i.body,d))if(!A(s)){if(b(s))throw new Error(`${s.payload.error}.`);if(B(s)){yield s.payload;continue}throw new Error("Failed to run EventQL query.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{a&&a(),u&&c.abort()}})()}observeEvents(t,r,o){let n=this.#t("/api/v1/observe-events"),c=this.#e;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,i;if(o&&!o.aborted){let s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),i=()=>o.removeEventListener("abort",s)}try{let s=await fetch(n,{method:"post",headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:r}),signal:u});if(s.status!==200)throw new Error(`Failed to observe events, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to observe events.");for await(let f of l(s.body,u))if(!A(f)){if(b(f))throw new Error(`${f.payload.error}.`);if(C(f)){yield S(f.payload);continue}throw new Error("Failed to observe events.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{i&&i(),a&&d.abort()}})()}async registerEventSchema(t,r){let o=this.#t("/api/v1/register-event-schema"),n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({eventType:t,schema:r})});if(n.status!==200)throw new Error(`Failed to register event schema, got HTTP status code '${n.status}', expected '200'.`)}readSubjects(t,r){let o=this.#t("/api/v1/read-subjects"),n=this.#e;return(async function*(){let c=new AbortController,d=r??c.signal,u=!r,a;if(r&&!r.aborted){let i=()=>c.abort();r.addEventListener("abort",i,{once:!0}),a=()=>r.removeEventListener("abort",i)}try{let i=await fetch(o,{method:"post",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:t}),signal:d});if(i.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${i.status}', expected '200'.`);if(!i.body)throw new Error("Failed to read subjects.");for await(let s of l(i.body,d)){if(b(s))throw new Error(`${s.payload.error}.`);if(L(s)){yield s.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{a&&a(),u&&c.abort()}})()}async readEventType(t){let r=this.#t("/api/v1/read-event-type"),o=await fetch(r,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({eventType:t})});if(o.status!==200)throw new Error(`Failed to read event type, got HTTP status code '${o.status}', expected '200'.`);let n=await o.json();if(!h(n,{eventType:p,isPhantom:j}))throw new Error("Failed to parse response.");return n}readEventTypes(t){let r=this.#t("/api/v1/read-event-types"),o=this.#e;return(async function*(){let n=new AbortController,c=t??n.signal,d=!t,u;if(t&&!t.aborted){let a=()=>n.abort();t.addEventListener("abort",a,{once:!0}),u=()=>t.removeEventListener("abort",a)}try{let a=await fetch(r,{method:"post",headers:{authorization:`Bearer ${o}`},signal:c});if(a.status!==200)throw new Error(`Failed to read event types, got HTTP status code '${a.status}', expected '200'.`);if(!a.body)throw new Error("Failed to read event types.");for await(let i of l(a.body,c))if(!A(i)){if(b(i))throw new Error(`${i.payload.error}.`);if(H(i)){yield i.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{u&&u(),d&&n.abort()}})()}};var P=R(require("crypto")),k=require("testcontainers");var O=class{#o="thenativeweb/eventsourcingdb";#e="latest";#t=3e3;#i="secret";#n;#r;withImageTag(t){return this.#e=t,this}withApiToken(t){return this.#i=t,this}withSigningKey(){let{privateKey:t}=P.default.generateKeyPairSync("ed25519");return this.#n=t,this}withPort(t){return this.#t=t,this}async start(){let t=["run","--api-token",this.#i,"--data-directory-temporary","--http-enabled","--https-enabled=false"],r=[];this.#n!==void 0&&(t.push("--signing-key-file"),t.push("/etc/esdb/signing-key.pem"),r.push({content:this.#n.export({format:"pem",type:"pkcs8"}),target:"/etc/esdb/signing-key.pem",mode:511})),this.#r=await new k.GenericContainer(`${this.#o}:${this.#e}`).withExposedPorts(this.#t).withCommand(t).withCopyContentToContainer(r).withWaitStrategy(k.Wait.forHttp("/api/v1/ping",this.#t).withStartupTimeout(1e4)).start()}getHost(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getHost()}getMappedPort(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getMappedPort(this.#t)}getBaseUrl(){if(this.#r===void 0)throw new Error("Container must be running.");let t=this.getHost(),r=this.getMappedPort();return new URL(`http://${t}:${r}`)}getApiToken(){return this.#i}getSigningKey(){if(this.#n===void 0)throw new Error("Signing key not set.");return this.#n}getVerificationKey(){if(this.#n===void 0)throw new Error("Signing key not set.");return P.default.createPublicKey(this.#n)}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new v(this.getBaseUrl(),this.getApiToken())}};var K=e=>({type:"isEventQlQueryTrue",payload:{query:e}});var N=(e,t)=>({type:"isSubjectOnEventId",payload:{subject:e,eventId:t}});var U=e=>({type:"isSubjectPristine",payload:{subject:e}});0&&(module.exports={Client,Container,isEventQlQueryTrue,isSubjectOnEventId,isSubjectPristine});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var v=n=>({...n,time:new Date(n.time)});var c=(n,t)=>{if(typeof t!=typeof n)return!1;if(t===null||n===null)return t===null&&n===null;if(typeof t=="object"){if(Array.isArray(t)||Array.isArray(n))return!1;let e=t,o=n;for(let s of Object.keys(e))if(!(s in o)||!c(o[s],e[s]))return!1;return!0}return!0};var A={specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"},E=n=>c(n,A);var l=async function*(n,t){let e=n.getReader(),o=new TextDecoder("utf-8"),s="",p=()=>{e.cancel().catch(()=>{})};if(t.aborted){await e.cancel().catch(()=>{});return}t.addEventListener("abort",p);try{for(;!t.aborted;){let{done:d,value:u}=await e.read();if(d)break;s+=o.decode(u,{stream:!0});let a;for(;a=s.indexOf(`
2
- `),a!==-1;){let r=s.slice(0,a).trim();s=s.slice(a+1),r&&(yield JSON.parse(r))}}}finally{t.removeEventListener("abort",p),await e.cancel().catch(()=>{})}};var O={type:"event",payload:{specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"}},b=n=>!(!c(n,O)||n.type!=="event");var C={type:"error",payload:{error:"string"}},m=n=>!(!c(n,C)||n.type!=="error");var P={type:"eventType",payload:{eventType:"string",isPhantom:!0}},g=n=>!(!c(n,P)||n.type!=="eventType");var x={type:"heartbeat"},h=n=>!(!c(n,x)||n.type!=="heartbeat");var k={type:"row"},S=n=>!(!c(n,k)||n.type!=="row"||!("payload"in n));var $={type:"subject",payload:{subject:"string"}},T=n=>!(!c(n,$)||n.type!=="subject");var y=class{#o;#e;#t(t){return new URL(t,this.#o).toString()}constructor(t,e){this.#o=t,this.#e=e}async ping(){let t=this.#t("/api/v1/ping"),e=await fetch(t,{method:"get"});if(e.status!==200)throw new Error(`Failed to ping, got HTTP status code '${e.status}', expected '200'.`);let o=await e.json();if(!c(o,{type:"string"}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.ping-received")throw new Error("Failed to ping.")}async verifyApiToken(){let t=this.#t("/api/v1/verify-api-token"),e=await fetch(t,{method:"post",headers:{authorization:`Bearer ${this.#e}`}});if(e.status!==200)throw new Error(`Failed to verify API token, got HTTP status code '${e.status}', expected '200'.`);let o=await e.json();if(!c(o,{type:"string"}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.api-token-verified")throw new Error("Failed to verify API token.")}async writeEvents(t,e=[]){let o=this.#t("/api/v1/write-events"),s=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({events:t,preconditions:e})});if(s.status!==200)throw new Error(`Failed to write events, got HTTP status code '${s.status}', expected '200'.`);let p=await s.json();if(!Array.isArray(p))throw new Error("Failed to parse response.");return p.map(u=>{if(!E(u))throw new Error("Failed to parse response item.");return v(u)})}readEvents(t,e,o){let s=this.#t("/api/v1/read-events"),p=this.#e;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,r;if(o&&!o.aborted){let i=()=>d.abort();o.addEventListener("abort",i,{once:!0}),r=()=>o.removeEventListener("abort",i)}try{let i=await fetch(s,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:e}),signal:u});if(i.status!==200)throw new Error(`Failed to read events, got HTTP status code '${i.status}', expected '200'.`);if(!i.body)throw new Error("Failed to read events.");for await(let f of l(i.body,u)){if(m(f))throw new Error(`${f.payload.error}.`);if(b(f)){yield v(f.payload);continue}throw new Error("Failed to read events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{r&&r(),a&&d.abort()}})()}runEventQlQuery(t,e){let o=this.#t("/api/v1/run-eventql-query"),s=this.#e;return(async function*(){let p=new AbortController,d=e??p.signal,u=!e,a;if(e&&!e.aborted){let r=()=>p.abort();e.addEventListener("abort",r,{once:!0}),a=()=>e.removeEventListener("abort",r)}try{let r=await fetch(o,{method:"post",headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},body:JSON.stringify({query:t}),signal:d});if(r.status!==200)throw new Error(`Failed to run EventQL query, got HTTP status code '${r.status}', expected '200'.`);if(!r.body)throw new Error("Failed to run EventQL query.");for await(let i of l(r.body,d))if(!h(i)){if(m(i))throw new Error(`${i.payload.error}.`);if(S(i)){yield i.payload;continue}throw new Error("Failed to run EventQL query.")}}catch(r){if(r instanceof DOMException&&r.name==="AbortError")return;throw r}finally{a&&a(),u&&p.abort()}})()}observeEvents(t,e,o){let s=this.#t("/api/v1/observe-events"),p=this.#e;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,r;if(o&&!o.aborted){let i=()=>d.abort();o.addEventListener("abort",i,{once:!0}),r=()=>o.removeEventListener("abort",i)}try{let i=await fetch(s,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:e}),signal:u});if(i.status!==200)throw new Error(`Failed to observe events, got HTTP status code '${i.status}', expected '200'.`);if(!i.body)throw new Error("Failed to observe events.");for await(let f of l(i.body,u))if(!h(f)){if(m(f))throw new Error(`${f.payload.error}.`);if(b(f)){yield v(f.payload);continue}throw new Error("Failed to observe events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{r&&r(),a&&d.abort()}})()}async registerEventSchema(t,e){let o=this.#t("/api/v1/register-event-schema"),s=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({eventType:t,schema:e})});if(s.status!==200)throw new Error(`Failed to register event schema, got HTTP status code '${s.status}', expected '200'.`)}readSubjects(t,e){let o=this.#t("/api/v1/read-subjects"),s=this.#e;return(async function*(){let p=new AbortController,d=e??p.signal,u=!e,a;if(e&&!e.aborted){let r=()=>p.abort();e.addEventListener("abort",r,{once:!0}),a=()=>e.removeEventListener("abort",r)}try{let r=await fetch(o,{method:"post",headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:t}),signal:d});if(r.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${r.status}', expected '200'.`);if(!r.body)throw new Error("Failed to read subjects.");for await(let i of l(r.body,d)){if(m(i))throw new Error(`${i.payload.error}.`);if(T(i)){yield i.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(r){if(r instanceof DOMException&&r.name==="AbortError")return;throw r}finally{a&&a(),u&&p.abort()}})()}async readEventType(t){let e=this.#t("/api/v1/read-event-type"),o=await fetch(e,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({eventType:t})});if(o.status!==200)throw new Error(`Failed to read event type, got HTTP status code '${o.status}', expected '200'.`);let s=await o.json();if(!c(s,{eventType:"string",isPhantom:!0}))throw new Error("Failed to parse response.");return s}readEventTypes(t){let e=this.#t("/api/v1/read-event-types"),o=this.#e;return(async function*(){let s=new AbortController,p=t??s.signal,d=!t,u;if(t&&!t.aborted){let a=()=>s.abort();t.addEventListener("abort",a,{once:!0}),u=()=>t.removeEventListener("abort",a)}try{let a=await fetch(e,{method:"post",headers:{authorization:`Bearer ${o}`},signal:p});if(a.status!==200)throw new Error(`Failed to read event types, got HTTP status code '${a.status}', expected '200'.`);if(!a.body)throw new Error("Failed to read event types.");for await(let r of l(a.body,p))if(!h(r)){if(m(r))throw new Error(`${r.payload.error}.`);if(g(r)){yield r.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{u&&u(),d&&s.abort()}})()}};import{GenericContainer as F,Wait as L}from"testcontainers";var w=class{#o="thenativeweb/eventsourcingdb";#e="latest";#t=3e3;#n="secret";#r;withImageTag(t){return this.#e=t,this}withApiToken(t){return this.#n=t,this}withPort(t){return this.#t=t,this}async start(){this.#r=await new F(`${this.#o}:${this.#e}`).withExposedPorts(this.#t).withCommand(["run","--api-token",this.#n,"--data-directory-temporary","--http-enabled","--https-enabled=false"]).withWaitStrategy(L.forHttp("/api/v1/ping",this.#t).withStartupTimeout(1e4)).start()}getHost(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getHost()}getMappedPort(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getMappedPort(this.#t)}getBaseUrl(){if(this.#r===void 0)throw new Error("Container must be running.");let t=this.getHost(),e=this.getMappedPort();return new URL(`http://${t}:${e}`)}getApiToken(){return this.#n}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new y(this.getBaseUrl(),this.getApiToken())}};var R=(n,t)=>({type:"isSubjectOnEventId",payload:{subject:n,eventId:t}});var H=n=>({type:"isSubjectPristine",payload:{subject:n}});export{y as Client,w as Container,R as isSubjectOnEventId,H as isSubjectPristine};
1
+ import w from"crypto";var g=class{specversion;id;time;#o;source;subject;type;datacontenttype;data;hash;predecessorhash;traceparent;tracestate;signature;constructor({specversion:t,id:r,time:o,timeFromServer:i,source:c,subject:d,type:u,datacontenttype:a,data:n,hash:s,predecessorhash:f,traceparent:A,tracestate:F,signature:H}){this.specversion=t,this.id=r,this.time=o,this.#o=i,this.source=c,this.subject=d,this.type=u,this.datacontenttype=a,this.data=n,this.hash=s,this.predecessorhash=f,this.traceparent=A,this.tracestate=F,this.signature=H}verifyHash(){let t=`${this.specversion}|${this.id}|${this.predecessorhash}|${this.#o}|${this.source}|${this.subject}|${this.type}|${this.datacontenttype}`,r=w.createHash("sha256").update(t).digest("hex"),o=w.createHash("sha256").update(JSON.stringify(this.data)).digest("hex");if(w.createHash("sha256").update(`${r}${o}`).digest("hex")!==this.hash)throw new Error("Failed to verify hash.")}verifySignature(t){if(this.signature===null)throw new Error("Signature must not be null.");this.verifyHash();let r="esdb:signature:v1:";if(!this.signature.startsWith(r))throw new Error(`Signature must start with '${r}'`);let o=this.signature.slice(r.length),i=Buffer.from(o,"hex"),c=Buffer.from(this.hash,"utf8");if(!w.verify(null,c,t,i))throw new Error("Signature verification failed.")}};var E=e=>new g({specversion:e.specversion,id:e.id,time:new Date(e.time),timeFromServer:e.time,source:e.source,subject:e.subject,type:e.type,datacontenttype:e.datacontenttype,data:e.data,hash:e.hash,predecessorhash:e.predecessorhash,traceparent:e.traceparent,tracestate:e.tracestate,signature:e.signature});var y=e=>!(e===null||typeof e!="object"||Array.isArray(e));var h=(e,t)=>{if(!y(e))return!1;for(let r of Object.keys(t)){let o=t[r],i=e[r];if(typeof o=="function"){if(!o(i))return!1;continue}if(!y(i)||!h(i,o))return!1}return!0};var p=e=>typeof e=="string";var S=e=>e===null||typeof e=="string";var m=e=>e===void 0||typeof e=="string";var x=e=>h(e,{specversion:p,id:p,time:p,source:p,subject:p,type:p,datacontenttype:p,data:y,hash:p,predecessorhash:p,traceparent:m,tracestate:m,signature:S});var l=async function*(e,t){let r=e.getReader(),o=new TextDecoder("utf-8"),i="",c=()=>{r.cancel().catch(()=>{})};if(t.aborted){await r.cancel().catch(()=>{});return}t.addEventListener("abort",c);try{for(;!t.aborted;){let{done:d,value:u}=await r.read();if(d)break;i+=o.decode(u,{stream:!0});let a;for(;a=i.indexOf(`
2
+ `),a!==-1;){let n=i.slice(0,a).trim();i=i.slice(a+1),n&&(yield JSON.parse(n))}}}finally{t.removeEventListener("abort",c),await r.cancel().catch(()=>{})}};var O=e=>h(e,{type:t=>t==="event",payload:{specversion:p,id:p,time:p,source:p,subject:p,type:p,datacontenttype:p,data:y,hash:p,predecessorhash:p,traceparent:m,tracestate:m,signature:S}});var b=e=>h(e,{type:t=>t==="error",payload:{error:p}});var T=e=>typeof e=="boolean";var C=e=>h(e,{type:t=>t==="eventType",payload:{eventType:p,isPhantom:T}});var j=e=>h(e,{type:t=>t==="heartbeat"});var P=e=>h(e,{type:t=>t==="row",payload:y});var $=e=>h(e,{type:t=>t==="subject",payload:{subject:p}});var v=class{#o;#e;#t(t){return new URL(t,this.#o).toString()}constructor(t,r){this.#o=t,this.#e=r}async ping(){let t=this.#t("/api/v1/ping"),r=await fetch(t,{method:"get"});if(r.status!==200)throw new Error(`Failed to ping, got HTTP status code '${r.status}', expected '200'.`);let o=await r.json();if(!h(o,{type:p}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.ping-received")throw new Error("Failed to ping.")}async verifyApiToken(){let t=this.#t("/api/v1/verify-api-token"),r=await fetch(t,{method:"post",headers:{authorization:`Bearer ${this.#e}`}});if(r.status!==200)throw new Error(`Failed to verify API token, got HTTP status code '${r.status}', expected '200'.`);let o=await r.json();if(!h(o,{type:p}))throw new Error("Failed to parse response.");if(o.type!=="io.eventsourcingdb.api.api-token-verified")throw new Error("Failed to verify API token.")}async writeEvents(t,r=[]){let o=this.#t("/api/v1/write-events"),i=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({events:t,preconditions:r})});if(i.status!==200)throw new Error(`Failed to write events, got HTTP status code '${i.status}', expected '200'.`);let c=await i.json();if(!Array.isArray(c))throw new Error("Failed to parse response.");return c.map(u=>{if(!x(u))throw new Error("Failed to parse response item.");return E(u)})}readEvents(t,r,o){let i=this.#t("/api/v1/read-events"),c=this.#e;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,n;if(o&&!o.aborted){let s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),n=()=>o.removeEventListener("abort",s)}try{let s=await fetch(i,{method:"post",headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:r}),signal:u});if(s.status!==200)throw new Error(`Failed to read events, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to read events.");for await(let f of l(s.body,u)){if(b(f))throw new Error(`${f.payload.error}.`);if(O(f)){yield E(f.payload);continue}throw new Error("Failed to read events.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{n&&n(),a&&d.abort()}})()}runEventQlQuery(t,r){let o=this.#t("/api/v1/run-eventql-query"),i=this.#e;return(async function*(){let c=new AbortController,d=r??c.signal,u=!r,a;if(r&&!r.aborted){let n=()=>c.abort();r.addEventListener("abort",n,{once:!0}),a=()=>r.removeEventListener("abort",n)}try{let n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({query:t}),signal:d});if(n.status!==200)throw new Error(`Failed to run EventQL query, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to run EventQL query.");for await(let s of l(n.body,d))if(!j(s)){if(b(s))throw new Error(`${s.payload.error}.`);if(P(s)){yield s.payload;continue}throw new Error("Failed to run EventQL query.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{a&&a(),u&&c.abort()}})()}observeEvents(t,r,o){let i=this.#t("/api/v1/observe-events"),c=this.#e;return(async function*(){let d=new AbortController,u=o??d.signal,a=!o,n;if(o&&!o.aborted){let s=()=>d.abort();o.addEventListener("abort",s,{once:!0}),n=()=>o.removeEventListener("abort",s)}try{let s=await fetch(i,{method:"post",headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:r}),signal:u});if(s.status!==200)throw new Error(`Failed to observe events, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to observe events.");for await(let f of l(s.body,u))if(!j(f)){if(b(f))throw new Error(`${f.payload.error}.`);if(O(f)){yield E(f.payload);continue}throw new Error("Failed to observe events.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{n&&n(),a&&d.abort()}})()}async registerEventSchema(t,r){let o=this.#t("/api/v1/register-event-schema"),i=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({eventType:t,schema:r})});if(i.status!==200)throw new Error(`Failed to register event schema, got HTTP status code '${i.status}', expected '200'.`)}readSubjects(t,r){let o=this.#t("/api/v1/read-subjects"),i=this.#e;return(async function*(){let c=new AbortController,d=r??c.signal,u=!r,a;if(r&&!r.aborted){let n=()=>c.abort();r.addEventListener("abort",n,{once:!0}),a=()=>r.removeEventListener("abort",n)}try{let n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:t}),signal:d});if(n.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to read subjects.");for await(let s of l(n.body,d)){if(b(s))throw new Error(`${s.payload.error}.`);if($(s)){yield s.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{a&&a(),u&&c.abort()}})()}async readEventType(t){let r=this.#t("/api/v1/read-event-type"),o=await fetch(r,{method:"post",headers:{authorization:`Bearer ${this.#e}`,"content-type":"application/json"},body:JSON.stringify({eventType:t})});if(o.status!==200)throw new Error(`Failed to read event type, got HTTP status code '${o.status}', expected '200'.`);let i=await o.json();if(!h(i,{eventType:p,isPhantom:T}))throw new Error("Failed to parse response.");return i}readEventTypes(t){let r=this.#t("/api/v1/read-event-types"),o=this.#e;return(async function*(){let i=new AbortController,c=t??i.signal,d=!t,u;if(t&&!t.aborted){let a=()=>i.abort();t.addEventListener("abort",a,{once:!0}),u=()=>t.removeEventListener("abort",a)}try{let a=await fetch(r,{method:"post",headers:{authorization:`Bearer ${o}`},signal:c});if(a.status!==200)throw new Error(`Failed to read event types, got HTTP status code '${a.status}', expected '200'.`);if(!a.body)throw new Error("Failed to read event types.");for await(let n of l(a.body,c))if(!j(n)){if(b(n))throw new Error(`${n.payload.error}.`);if(C(n)){yield n.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{u&&u(),d&&i.abort()}})()}};import R from"crypto";import{GenericContainer as B,Wait as L}from"testcontainers";var k=class{#o="thenativeweb/eventsourcingdb";#e="latest";#t=3e3;#i="secret";#n;#r;withImageTag(t){return this.#e=t,this}withApiToken(t){return this.#i=t,this}withSigningKey(){let{privateKey:t}=R.generateKeyPairSync("ed25519");return this.#n=t,this}withPort(t){return this.#t=t,this}async start(){let t=["run","--api-token",this.#i,"--data-directory-temporary","--http-enabled","--https-enabled=false"],r=[];this.#n!==void 0&&(t.push("--signing-key-file"),t.push("/etc/esdb/signing-key.pem"),r.push({content:this.#n.export({format:"pem",type:"pkcs8"}),target:"/etc/esdb/signing-key.pem",mode:511})),this.#r=await new B(`${this.#o}:${this.#e}`).withExposedPorts(this.#t).withCommand(t).withCopyContentToContainer(r).withWaitStrategy(L.forHttp("/api/v1/ping",this.#t).withStartupTimeout(1e4)).start()}getHost(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getHost()}getMappedPort(){if(this.#r===void 0)throw new Error("Container must be running.");return this.#r.getMappedPort(this.#t)}getBaseUrl(){if(this.#r===void 0)throw new Error("Container must be running.");let t=this.getHost(),r=this.getMappedPort();return new URL(`http://${t}:${r}`)}getApiToken(){return this.#i}getSigningKey(){if(this.#n===void 0)throw new Error("Signing key not set.");return this.#n}getVerificationKey(){if(this.#n===void 0)throw new Error("Signing key not set.");return R.createPublicKey(this.#n)}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new v(this.getBaseUrl(),this.getApiToken())}};var K=e=>({type:"isEventQlQueryTrue",payload:{query:e}});var N=(e,t)=>({type:"isSubjectOnEventId",payload:{subject:e,eventId:t}});var U=e=>({type:"isSubjectPristine",payload:{subject:e}});export{v as Client,k as Container,K as isEventQlQueryTrue,N as isSubjectOnEventId,U as isSubjectPristine};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eventsourcingdb",
3
- "version": "1.2.2",
3
+ "version": "1.3.1",
4
4
  "description": "The official JavaScript client SDK for EventSourcingDB.",
5
5
  "author": {
6
6
  "name": "the native web GmbH",
@@ -17,15 +17,15 @@
17
17
  "testcontainers": "11.5.1"
18
18
  },
19
19
  "devDependencies": {
20
- "@biomejs/biome": "2.2.2",
21
- "@types/node": "24.3.0",
20
+ "@biomejs/biome": "2.2.4",
21
+ "@types/node": "24.4.0",
22
22
  "get-port": "7.1.0",
23
23
  "tsup": "8.5.0",
24
24
  "tsx": "4.20.5",
25
25
  "typescript": "5.9.2"
26
26
  },
27
27
  "scripts": {
28
- "analyze": "npx biome check --error-on-warnings .",
28
+ "analyze": "npx tsc --noEmit && npx biome check --error-on-warnings .",
29
29
  "build": "npx tsc --noEmit && npx tsup --clean --dts --format cjs,esm --minify --out-dir=./dist/ ./src/index.ts",
30
30
  "format": "npx biome check --write .",
31
31
  "qa": "npm run analyze && npm run test",