eventsourcingdb 0.10.5 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,8 @@ EventSourcingDB enables you to build and operate event-driven applications with
6
6
 
7
7
  For more information on EventSourcingDB, see its [official documentation](https://docs.eventsourcingdb.io/).
8
8
 
9
+ This client SDK includes support for [Testcontainers](https://testcontainers.com/) to spin up EventSourcingDB instances in integration tests. For details, see [Using Testcontainers](#using-testcontainers).
10
+
9
11
  ## Getting Started
10
12
 
11
13
  Import the `Client` class and create an instance by providing the URL of your EventSourcingDB instance and the API token to use:
@@ -170,7 +172,7 @@ for await (const event of client.readEvents('/books/42', {
170
172
 
171
173
  If you need to abort reading use `break` or `return` within the `await for` loop. However, this only works if there is currently an iteration going on.
172
174
 
173
- To abort reading independently of that, hand over an abort signal as third parameter when calling `readEvents`, and abort the appropriate `AbortController`:
175
+ To abort reading independently of that, hand over an abort signal as third argument when calling `readEvents`, and abort the appropriate `AbortController`:
174
176
 
175
177
  ```typescript
176
178
  const controller = new AbortController();
@@ -254,7 +256,7 @@ for await (const event of client.observeEvents('/books/42', {
254
256
 
255
257
  If you need to abort observing use `break` or `return` within the `await for` loop. However, this only works if there is currently an iteration going on.
256
258
 
257
- To abort observing independently of that, hand over an abort signal as third parameter when calling `observeEvents`, and abort the appropriate `AbortController`:
259
+ To abort observing independently of that, hand over an abort signal as third argument when calling `observeEvents`, and abort the appropriate `AbortController`:
258
260
 
259
261
  ```typescript
260
262
  const controller = new AbortController();
@@ -269,3 +271,139 @@ for await (const event of client.observeEvents('/books/42', {
269
271
  // observing to end.
270
272
  controller.abort();
271
273
  ```
274
+
275
+ ### Registering an Event Schema
276
+
277
+ To register an event schema, call the `registerEventSchema` function and hand over an event type and the desired schema:
278
+
279
+ ```typescript
280
+ await client.registerEventSchema('io.eventsourcingdb.library.book-acquired', {
281
+ type: 'object',
282
+ properties: {
283
+ title: { type: 'string' },
284
+ author: { type: 'string' },
285
+ isbn: { type: 'string' }
286
+ },
287
+ required: [
288
+ 'title',
289
+ 'author',
290
+ 'isbn'
291
+ ],
292
+ additionalProperties: false
293
+ });
294
+ ```
295
+
296
+ ### Listing Subjects
297
+
298
+ To list all subjects, call the `readSubjects` function with `/` as the base subject. The function returns an asynchronous iterator, which you can use e.g. inside a `for await` loop:
299
+
300
+ ```typescript
301
+ for await (const subject of client.readSubjects('/')) {
302
+ // ...
303
+ }
304
+ ```
305
+
306
+ If you only want to list subjects within a specific branch, provide the desired base subject instead:
307
+
308
+ ```typescript
309
+ for await (const subject of client.readSubjects('/books')) {
310
+ // ...
311
+ }
312
+ ```
313
+
314
+ #### Aborting Listing
315
+
316
+ If you need to abort listing use `break` or `return` within the `await for` loop. However, this only works if there is currently an iteration going on.
317
+
318
+ To abort listing independently of that, hand over an abort signal as second argument when calling `readSubjects`, and abort the appropriate `AbortController`:
319
+
320
+ ```typescript
321
+ const controller = new AbortController();
322
+
323
+ for await (const subject of client.readSubjects(
324
+ '/', controller.signal)
325
+ ) {
326
+ // ...
327
+ }
328
+
329
+ // Somewhere else, abort the controller, which will cause
330
+ // reading to end.
331
+ controller.abort();
332
+ ```
333
+
334
+ ### Listing Event Types
335
+
336
+ To list all event types, call the `readEventTypes` function. The function returns an asynchronous iterator, which you can use e.g. inside a `for await` loop:
337
+
338
+ ```typescript
339
+ for await (const eventType of client.readEventTypes()) {
340
+ // ...
341
+ }
342
+ ```
343
+
344
+ #### Aborting Listing
345
+
346
+ If you need to abort listing use `break` or `return` within the `await for` loop. However, this only works if there is currently an iteration going on.
347
+
348
+ To abort listing independently of that, hand over an abort signal as argument when calling `readEventTypes`, and abort the appropriate `AbortController`:
349
+
350
+ ```typescript
351
+ const controller = new AbortController();
352
+
353
+ for await (const eventType of client.readEventTypes()) {
354
+ // ...
355
+ }
356
+
357
+ // Somewhere else, abort the controller, which will cause
358
+ // reading to end.
359
+ controller.abort();
360
+ ```
361
+
362
+ ### Using Testcontainers
363
+
364
+ Import the `EventSourcingDbContainer` class, create an instance, call the `start` function to run a test container, get a client, run your test code, and finally call the `stop` function to stop the test container:
365
+
366
+ ```typescript
367
+ import { EventSourcingDbContainer } from 'eventsourcingdb';
368
+
369
+ const container = new EventSourcingDbContainer();
370
+ await container.start();
371
+
372
+ const client = container.getClient();
373
+
374
+ // ...
375
+
376
+ await container.stop();
377
+ ```
378
+
379
+ To check if the test container is running, call the `isRunning` function:
380
+
381
+ ```typescript
382
+ const isRunning = container.isRunning();
383
+ ```
384
+
385
+ #### Configuring the Container Instance
386
+
387
+ By default, `EventSourcingDbContainer` uses the `latest` tag of the official EventSourcingDB Docker image. To change that, call the `withImageTag` function:
388
+
389
+ ```typescript
390
+ const container = new EventSourcingDbContainer()
391
+ .withImageTag('1.0.0');
392
+ ```
393
+
394
+ Similarly, you can configure the port to use and the API token. Call the `withPort` or the `withApiToken` function respectively:
395
+
396
+ ```typescript
397
+ const container = new EventSourcingDbContainer()
398
+ .withPort(4000)
399
+ .withApiToken('secret');
400
+ ```
401
+
402
+ #### Configuring the Client Manually
403
+
404
+ In case you need to set up the client yourself, use the following functions to get details on the container:
405
+
406
+ - `getHost()` returns the host name.
407
+ - `getMappedPort()` returns the port.
408
+ - `getBaseUrl()` returns the full URL of the container.
409
+ - `getApiToken()` returns the API token.
package/dist/index.d.mts CHANGED
@@ -89,8 +89,23 @@ declare class Client {
89
89
  readEventTypes(signal?: AbortSignal): AsyncGenerator<EventType, void, void>;
90
90
  }
91
91
 
92
+ declare class EventSourcingDbContainer {
93
+ #private;
94
+ withImageTag(tag: string): this;
95
+ withApiToken(token: string): this;
96
+ withPort(port: number): this;
97
+ start(): Promise<void>;
98
+ getHost(): string;
99
+ getMappedPort(): number;
100
+ getBaseUrl(): URL;
101
+ getApiToken(): string;
102
+ isRunning(): boolean;
103
+ stop(): Promise<void>;
104
+ getClient(): Client;
105
+ }
106
+
92
107
  declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
93
108
 
94
109
  declare const isSubjectPristine: (subject: string) => Precondition;
95
110
 
96
- export { Client, type Event, type EventCandidate, type EventType, type ObserveEventsOptions, type ReadEventsOptions, isSubjectOnEventId, isSubjectPristine };
111
+ export { Client, type Event, type EventCandidate, EventSourcingDbContainer, type EventType, type ObserveEventsOptions, type ReadEventsOptions, isSubjectOnEventId, isSubjectPristine };
package/dist/index.d.ts CHANGED
@@ -89,8 +89,23 @@ declare class Client {
89
89
  readEventTypes(signal?: AbortSignal): AsyncGenerator<EventType, void, void>;
90
90
  }
91
91
 
92
+ declare class EventSourcingDbContainer {
93
+ #private;
94
+ withImageTag(tag: string): this;
95
+ withApiToken(token: string): this;
96
+ withPort(port: number): this;
97
+ start(): Promise<void>;
98
+ getHost(): string;
99
+ getMappedPort(): number;
100
+ getBaseUrl(): URL;
101
+ getApiToken(): string;
102
+ isRunning(): boolean;
103
+ stop(): Promise<void>;
104
+ getClient(): Client;
105
+ }
106
+
92
107
  declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
93
108
 
94
109
  declare const isSubjectPristine: (subject: string) => Precondition;
95
110
 
96
- export { Client, type Event, type EventCandidate, type EventType, type ObserveEventsOptions, type ReadEventsOptions, isSubjectOnEventId, isSubjectPristine };
111
+ export { Client, type Event, type EventCandidate, EventSourcingDbContainer, type EventType, type ObserveEventsOptions, type ReadEventsOptions, isSubjectOnEventId, isSubjectPristine };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var h=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var P=(e,t)=>{for(var r in t)h(e,r,{get:t[r],enumerable:!0})},k=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of C(t))!x.call(e,n)&&n!==r&&h(e,n,{get:()=>t[n],enumerable:!(o=O(t,n))||o.enumerable});return e};var F=e=>k(h({},"__esModule",{value:!0}),e);var J={};P(J,{Client:()=>b,isSubjectOnEventId:()=>j,isSubjectPristine:()=>T});module.exports=F(J);var m=e=>({...e,time:new Date(e.time)});var d=(e,t)=>{if(typeof t!=typeof e)return!1;if(t===null||e===null)return t===null&&e===null;if(typeof t=="object"){if(Array.isArray(t)||Array.isArray(e))return!1;let r=t,o=e;for(let n of Object.keys(r))if(!(n in o)||!d(o[n],r[n]))return!1;return!0}return!0};var $={specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"},w=e=>d(e,$);var v=async function*(e,t){let r=e.getReader(),o=new TextDecoder("utf-8"),n="",p=()=>{r.cancel().catch(()=>{})};if(t.aborted){await r.cancel().catch(()=>{});return}t.addEventListener("abort",p);try{for(;!t.aborted;){let{done:u,value:c}=await r.read();if(u)break;n+=o.decode(c,{stream:!0});let a;for(;a=n.indexOf(`
2
- `),a!==-1;){let s=n.slice(0,a).trim();n=n.slice(a+1),s&&(yield JSON.parse(s))}}}finally{t.removeEventListener("abort",p),await r.cancel().catch(()=>{})}};var L={type:"event",payload:{specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"}},E=e=>!(!d(e,L)||e.type!=="event");var R={type:"error",payload:{error:"string"}},l=e=>!(!d(e,R)||e.type!=="error");var H={type:"eventType",payload:{eventType:"string",isPhantom:!0}},S=e=>!(!d(e,H)||e.type!=="eventType");var B={type:"heartbeat"},y=e=>!(!d(e,B)||e.type!=="heartbeat");var I={type:"subject",payload:{subject:"string"}},g=e=>!(!d(e,I)||e.type!=="subject");var b=class{#r;#t;#e(t){return new URL(t,this.#r).toString()}constructor(t,r){this.#r=t,this.#t=r}async ping(){let t=this.#e("/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(!d(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.#e("/api/v1/verify-api-token"),r=await fetch(t,{method:"post",headers:{authorization:`Bearer ${this.#t}`}});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(!d(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,r=[]){let o=this.#e("/api/v1/write-events"),n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"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 p=await n.json();if(!Array.isArray(p))throw new Error("Failed to parse response.");return p.map(c=>{if(!w(c))throw new Error("Failed to parse response item.");return m(c)})}readEvents(t,r,o){let n=this.#e("/api/v1/read-events"),p=this.#t;return async function*(){let u=new AbortController,c=o??u.signal,a=!o,s;if(o&&!o.aborted){let i=()=>u.abort();o.addEventListener("abort",i,{once:!0}),s=()=>o.removeEventListener("abort",i)}try{let i=await fetch(n,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:r}),signal:c});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 v(i.body,c))if(!y(f)){if(l(f))throw new Error(`${f.payload.error}.`);if(E(f)){yield m(f.payload);continue}throw new Error("Failed to read events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{s&&s(),a&&u.abort()}}()}observeEvents(t,r,o){let n=this.#e("/api/v1/observe-events"),p=this.#t;return async function*(){let u=new AbortController,c=o??u.signal,a=!o,s;if(o&&!o.aborted){let i=()=>u.abort();o.addEventListener("abort",i,{once:!0}),s=()=>o.removeEventListener("abort",i)}try{let i=await fetch(n,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:r}),signal:c});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 v(i.body,c))if(!y(f)){if(l(f))throw new Error(`${f.payload.error}.`);if(E(f)){yield m(f.payload);continue}throw new Error("Failed to observe events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{s&&s(),a&&u.abort()}}()}async registerEventSchema(t,r){let o=this.#e("/api/v1/register-event-schema"),n=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"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.#e("/api/v1/read-subjects"),n=this.#t;return async function*(){let p=new AbortController,u=r??p.signal,c=!r,a;if(r&&!r.aborted){let s=()=>p.abort();r.addEventListener("abort",s,{once:!0}),a=()=>r.removeEventListener("abort",s)}try{let s=await fetch(o,{method:"post",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:t}),signal:u});if(s.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to read subjects.");for await(let i of v(s.body,u))if(!y(i)){if(l(i))throw new Error(`${i.payload.error}.`);if(g(i)){yield i.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{a&&a(),c&&p.abort()}}()}readEventTypes(t){let r=this.#e("/api/v1/read-event-types"),o=this.#t;return async function*(){let n=new AbortController,p=t??n.signal,u=!t,c;if(t&&!t.aborted){let a=()=>n.abort();t.addEventListener("abort",a,{once:!0}),c=()=>t.removeEventListener("abort",a)}try{let a=await fetch(r,{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 s of v(a.body,p))if(!y(s)){if(l(s))throw new Error(`${s.payload.error}.`);if(S(s)){yield s.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{c&&c(),u&&n.abort()}}()}};var j=(e,t)=>({type:"isSubjectOnEventId",payload:{subject:e,eventId:t}});var T=e=>({type:"isSubjectPristine",payload:{subject:e}});0&&(module.exports={Client,isSubjectOnEventId,isSubjectPristine});
1
+ "use strict";var w=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var $=(e,t)=>{for(var r in t)w(e,r,{get:t[r],enumerable:!0})},F=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of k(t))!x.call(e,n)&&n!==r&&w(e,n,{get:()=>t[n],enumerable:!(o=P(t,n))||o.enumerable});return e};var L=e=>F(w({},"__esModule",{value:!0}),e);var J={};$(J,{Client:()=>l,EventSourcingDbContainer:()=>b,isSubjectOnEventId:()=>A,isSubjectPristine:()=>O});module.exports=L(J);var y=e=>({...e,time:new Date(e.time)});var d=(e,t)=>{if(typeof t!=typeof e)return!1;if(t===null||e===null)return t===null&&e===null;if(typeof t=="object"){if(Array.isArray(t)||Array.isArray(e))return!1;let r=t,o=e;for(let n of Object.keys(r))if(!(n in o)||!d(o[n],r[n]))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=e=>d(e,H);var m=async function*(e,t){let r=e.getReader(),o=new TextDecoder("utf-8"),n="",p=()=>{r.cancel().catch(()=>{})};if(t.aborted){await r.cancel().catch(()=>{});return}t.addEventListener("abort",p);try{for(;!t.aborted;){let{done:u,value:c}=await r.read();if(u)break;n+=o.decode(c,{stream:!0});let a;for(;a=n.indexOf(`
2
+ `),a!==-1;){let s=n.slice(0,a).trim();n=n.slice(a+1),s&&(yield JSON.parse(s))}}}finally{t.removeEventListener("abort",p),await r.cancel().catch(()=>{})}};var R={type:"event",payload:{specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"}},g=e=>!(!d(e,R)||e.type!=="event");var B={type:"error",payload:{error:"string"}},v=e=>!(!d(e,B)||e.type!=="error");var I={type:"eventType",payload:{eventType:"string",isPhantom:!0}},T=e=>!(!d(e,I)||e.type!=="eventType");var N={type:"heartbeat"},h=e=>!(!d(e,N)||e.type!=="heartbeat");var U={type:"subject",payload:{subject:"string"}},j=e=>!(!d(e,U)||e.type!=="subject");var l=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(!d(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"),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(!d(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,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 p=await n.json();if(!Array.isArray(p))throw new Error("Failed to parse response.");return p.map(c=>{if(!S(c))throw new Error("Failed to parse response item.");return y(c)})}readEvents(t,r,o){let n=this.#t("/api/v1/read-events"),p=this.#e;return async function*(){let u=new AbortController,c=o??u.signal,a=!o,s;if(o&&!o.aborted){let i=()=>u.abort();o.addEventListener("abort",i,{once:!0}),s=()=>o.removeEventListener("abort",i)}try{let i=await fetch(n,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:r}),signal:c});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 m(i.body,c))if(!h(f)){if(v(f))throw new Error(`${f.payload.error}.`);if(g(f)){yield y(f.payload);continue}throw new Error("Failed to read events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{s&&s(),a&&u.abort()}}()}observeEvents(t,r,o){let n=this.#t("/api/v1/observe-events"),p=this.#e;return async function*(){let u=new AbortController,c=o??u.signal,a=!o,s;if(o&&!o.aborted){let i=()=>u.abort();o.addEventListener("abort",i,{once:!0}),s=()=>o.removeEventListener("abort",i)}try{let i=await fetch(n,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:r}),signal:c});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 m(i.body,c))if(!h(f)){if(v(f))throw new Error(`${f.payload.error}.`);if(g(f)){yield y(f.payload);continue}throw new Error("Failed to observe events.")}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;throw i}finally{s&&s(),a&&u.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 p=new AbortController,u=r??p.signal,c=!r,a;if(r&&!r.aborted){let s=()=>p.abort();r.addEventListener("abort",s,{once:!0}),a=()=>r.removeEventListener("abort",s)}try{let s=await fetch(o,{method:"post",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:t}),signal:u});if(s.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to read subjects.");for await(let i of m(s.body,u))if(!h(i)){if(v(i))throw new Error(`${i.payload.error}.`);if(j(i)){yield i.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{a&&a(),c&&p.abort()}}()}readEventTypes(t){let r=this.#t("/api/v1/read-event-types"),o=this.#e;return async function*(){let n=new AbortController,p=t??n.signal,u=!t,c;if(t&&!t.aborted){let a=()=>n.abort();t.addEventListener("abort",a,{once:!0}),c=()=>t.removeEventListener("abort",a)}try{let a=await fetch(r,{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 s of m(a.body,p))if(!h(s)){if(v(s))throw new Error(`${s.payload.error}.`);if(T(s)){yield s.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{c&&c(),u&&n.abort()}}()}};var E=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 E.GenericContainer(`${this.#o}:${this.#e}`).withExposedPorts(this.#t).withCommand(["run","--api-token",this.#n,"--data-directory-temporary","--http-enabled","--https-enabled=false"]).withWaitStrategy(E.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.#n}isRunning(){return this.#r!==void 0}async stop(){this.#r!==void 0&&(await this.#r.stop(),this.#r=void 0)}getClient(){return new l(this.getBaseUrl(),this.getApiToken())}};var A=(e,t)=>({type:"isSubjectOnEventId",payload:{subject:e,eventId:t}});var O=e=>({type:"isSubjectPristine",payload:{subject:e}});0&&(module.exports={Client,EventSourcingDbContainer,isSubjectOnEventId,isSubjectPristine});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var m=r=>({...r,time:new Date(r.time)});var d=(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)||!d(o[i],e[i]))return!1;return!0}return!0};var j={specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"},E=r=>d(r,j);var v=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:u,value:c}=await e.read();if(u)break;i+=o.decode(c,{stream:!0});let a;for(;a=i.indexOf(`
2
- `),a!==-1;){let s=i.slice(0,a).trim();i=i.slice(a+1),s&&(yield JSON.parse(s))}}}finally{t.removeEventListener("abort",p),await e.cancel().catch(()=>{})}};var T={type:"event",payload:{specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"}},b=r=>!(!d(r,T)||r.type!=="event");var A={type:"error",payload:{error:"string"}},l=r=>!(!d(r,A)||r.type!=="error");var O={type:"eventType",payload:{eventType:"string",isPhantom:!0}},w=r=>!(!d(r,O)||r.type!=="eventType");var C={type:"heartbeat"},y=r=>!(!d(r,C)||r.type!=="heartbeat");var x={type:"subject",payload:{subject:"string"}},S=r=>!(!d(r,x)||r.type!=="subject");var h=class{#r;#t;#e(t){return new URL(t,this.#r).toString()}constructor(t,e){this.#r=t,this.#t=e}async ping(){let t=this.#e("/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(!d(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.#e("/api/v1/verify-api-token"),e=await fetch(t,{method:"post",headers:{authorization:`Bearer ${this.#t}`}});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(!d(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.#e("/api/v1/write-events"),i=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"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(c=>{if(!E(c))throw new Error("Failed to parse response item.");return m(c)})}readEvents(t,e,o){let i=this.#e("/api/v1/read-events"),p=this.#t;return async function*(){let u=new AbortController,c=o??u.signal,a=!o,s;if(o&&!o.aborted){let n=()=>u.abort();o.addEventListener("abort",n,{once:!0}),s=()=>o.removeEventListener("abort",n)}try{let n=await fetch(i,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:e}),signal:c});if(n.status!==200)throw new Error(`Failed to read events, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to read events.");for await(let f of v(n.body,c))if(!y(f)){if(l(f))throw new Error(`${f.payload.error}.`);if(b(f)){yield m(f.payload);continue}throw new Error("Failed to read events.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{s&&s(),a&&u.abort()}}()}observeEvents(t,e,o){let i=this.#e("/api/v1/observe-events"),p=this.#t;return async function*(){let u=new AbortController,c=o??u.signal,a=!o,s;if(o&&!o.aborted){let n=()=>u.abort();o.addEventListener("abort",n,{once:!0}),s=()=>o.removeEventListener("abort",n)}try{let n=await fetch(i,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:e}),signal:c});if(n.status!==200)throw new Error(`Failed to observe events, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to observe events.");for await(let f of v(n.body,c))if(!y(f)){if(l(f))throw new Error(`${f.payload.error}.`);if(b(f)){yield m(f.payload);continue}throw new Error("Failed to observe events.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{s&&s(),a&&u.abort()}}()}async registerEventSchema(t,e){let o=this.#e("/api/v1/register-event-schema"),i=await fetch(o,{method:"post",headers:{authorization:`Bearer ${this.#t}`,"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.#e("/api/v1/read-subjects"),i=this.#t;return async function*(){let p=new AbortController,u=e??p.signal,c=!e,a;if(e&&!e.aborted){let s=()=>p.abort();e.addEventListener("abort",s,{once:!0}),a=()=>e.removeEventListener("abort",s)}try{let s=await fetch(o,{method:"post",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:t}),signal:u});if(s.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to read subjects.");for await(let n of v(s.body,u))if(!y(n)){if(l(n))throw new Error(`${n.payload.error}.`);if(S(n)){yield n.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{a&&a(),c&&p.abort()}}()}readEventTypes(t){let e=this.#e("/api/v1/read-event-types"),o=this.#t;return async function*(){let i=new AbortController,p=t??i.signal,u=!t,c;if(t&&!t.aborted){let a=()=>i.abort();t.addEventListener("abort",a,{once:!0}),c=()=>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 s of v(a.body,p))if(!y(s)){if(l(s))throw new Error(`${s.payload.error}.`);if(w(s)){yield s.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{c&&c(),u&&i.abort()}}()}};var P=(r,t)=>({type:"isSubjectOnEventId",payload:{subject:r,eventId:t}});var k=r=>({type:"isSubjectPristine",payload:{subject:r}});export{h as Client,P as isSubjectOnEventId,k as isSubjectPristine};
1
+ var y=r=>({...r,time:new Date(r.time)});var d=(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)||!d(o[i],e[i]))return!1;return!0}return!0};var j={specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"},w=r=>d(r,j);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:u,value:c}=await e.read();if(u)break;i+=o.decode(c,{stream:!0});let a;for(;a=i.indexOf(`
2
+ `),a!==-1;){let s=i.slice(0,a).trim();i=i.slice(a+1),s&&(yield JSON.parse(s))}}}finally{t.removeEventListener("abort",p),await e.cancel().catch(()=>{})}};var A={type:"event",payload:{specversion:"string",id:"string",time:"string",source:"string",subject:"string",type:"string",datacontenttype:"string",data:{},hash:"string",predecessorhash:"string"}},b=r=>!(!d(r,A)||r.type!=="event");var O={type:"error",payload:{error:"string"}},m=r=>!(!d(r,O)||r.type!=="error");var C={type:"eventType",payload:{eventType:"string",isPhantom:!0}},g=r=>!(!d(r,C)||r.type!=="eventType");var P={type:"heartbeat"},v=r=>!(!d(r,P)||r.type!=="heartbeat");var k={type:"subject",payload:{subject:"string"}},S=r=>!(!d(r,k)||r.type!=="subject");var h=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(!d(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(!d(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(c=>{if(!w(c))throw new Error("Failed to parse response item.");return y(c)})}readEvents(t,e,o){let i=this.#t("/api/v1/read-events"),p=this.#e;return async function*(){let u=new AbortController,c=o??u.signal,a=!o,s;if(o&&!o.aborted){let n=()=>u.abort();o.addEventListener("abort",n,{once:!0}),s=()=>o.removeEventListener("abort",n)}try{let n=await fetch(i,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:e}),signal:c});if(n.status!==200)throw new Error(`Failed to read events, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to read events.");for await(let f of l(n.body,c))if(!v(f)){if(m(f))throw new Error(`${f.payload.error}.`);if(b(f)){yield y(f.payload);continue}throw new Error("Failed to read events.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{s&&s(),a&&u.abort()}}()}observeEvents(t,e,o){let i=this.#t("/api/v1/observe-events"),p=this.#e;return async function*(){let u=new AbortController,c=o??u.signal,a=!o,s;if(o&&!o.aborted){let n=()=>u.abort();o.addEventListener("abort",n,{once:!0}),s=()=>o.removeEventListener("abort",n)}try{let n=await fetch(i,{method:"post",headers:{authorization:`Bearer ${p}`,"content-type":"application/json"},body:JSON.stringify({subject:t,options:e}),signal:c});if(n.status!==200)throw new Error(`Failed to observe events, got HTTP status code '${n.status}', expected '200'.`);if(!n.body)throw new Error("Failed to observe events.");for await(let f of l(n.body,c))if(!v(f)){if(m(f))throw new Error(`${f.payload.error}.`);if(b(f)){yield y(f.payload);continue}throw new Error("Failed to observe events.")}}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;throw n}finally{s&&s(),a&&u.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,u=e??p.signal,c=!e,a;if(e&&!e.aborted){let s=()=>p.abort();e.addEventListener("abort",s,{once:!0}),a=()=>e.removeEventListener("abort",s)}try{let s=await fetch(o,{method:"post",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({baseSubject:t}),signal:u});if(s.status!==200)throw new Error(`Failed to read subjects, got HTTP status code '${s.status}', expected '200'.`);if(!s.body)throw new Error("Failed to read subjects.");for await(let n of l(s.body,u))if(!v(n)){if(m(n))throw new Error(`${n.payload.error}.`);if(S(n)){yield n.payload.subject;continue}throw new Error("Failed to read subjects.")}}catch(s){if(s instanceof DOMException&&s.name==="AbortError")return;throw s}finally{a&&a(),c&&p.abort()}}()}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,u=!t,c;if(t&&!t.aborted){let a=()=>i.abort();t.addEventListener("abort",a,{once:!0}),c=()=>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 s of l(a.body,p))if(!v(s)){if(m(s))throw new Error(`${s.payload.error}.`);if(g(s)){yield s.payload;continue}throw new Error("Failed to read event types.")}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return;throw a}finally{c&&c(),u&&i.abort()}}()}};import{GenericContainer as x,Wait as $}from"testcontainers";var E=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 x(`${this.#o}:${this.#e}`).withExposedPorts(this.#t).withCommand(["run","--api-token",this.#n,"--data-directory-temporary","--http-enabled","--https-enabled=false"]).withWaitStrategy($.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 h(this.getBaseUrl(),this.getApiToken())}};var F=(r,t)=>({type:"isSubjectOnEventId",payload:{subject:r,eventId:t}});var L=r=>({type:"isSubjectPristine",payload:{subject:r}});export{h as Client,E as EventSourcingDbContainer,F as isSubjectOnEventId,L as isSubjectPristine};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eventsourcingdb",
3
- "version": "0.10.5",
3
+ "version": "0.11.0",
4
4
  "description": "The official JavaScript client SDK for EventSourcingDB.",
5
5
  "author": {
6
6
  "name": "the native web GmbH",
@@ -43,5 +43,8 @@
43
43
  "event sourcing",
44
44
  "event store",
45
45
  "cqrs"
46
- ]
46
+ ],
47
+ "dependencies": {
48
+ "testcontainers": "10.24.2"
49
+ }
47
50
  }