eventsourcingdb 0.9.1 → 0.10.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
@@ -1,3 +1,3 @@
1
1
  # eventsourcingdb
2
2
 
3
- eventsourcingdb is the official client for EventSourcingDB.
3
+ The official JavaScript client SDK for EventSourcingDB.
package/dist/index.d.mts CHANGED
@@ -1,103 +1,58 @@
1
- import { Readable } from 'node:stream';
2
- import { ResponseType, AxiosResponse } from 'axios';
3
-
4
- declare class CustomError extends Error {
5
- }
6
-
7
- declare class CancelationError extends CustomError {
8
- }
9
-
10
- interface ClientConfiguration {
11
- baseUrl: string;
12
- timeoutMilliseconds: number;
13
- accessToken: string;
14
- protocolVersion: string;
15
- }
16
-
17
- interface ClientOptions {
18
- timeoutMilliseconds?: number;
19
- accessToken: string;
20
- protocolVersion?: string;
21
- }
22
-
23
- type UnknownObject = Partial<Record<string, unknown>>;
24
-
25
- declare class EventCandidate {
26
- readonly data: Record<string, unknown>;
27
- readonly source: string;
28
- readonly subject: string;
29
- readonly type: string;
30
- readonly traceParent?: string;
31
- readonly traceState?: string;
32
- constructor(source: string, subject: string, type: string, data: UnknownObject, traceParent?: string, traceState?: string);
33
- validate(): void;
34
- toJSON(): Record<string, unknown>;
35
- }
36
-
37
- declare class EventContext {
38
- readonly source: string;
39
- readonly subject: string;
40
- readonly type: string;
41
- readonly specVersion: string;
42
- readonly id: string;
43
- readonly time: Date;
44
- readonly dataContentType: string;
45
- readonly predecessorHash: string;
46
- readonly traceParent?: string;
47
- readonly traceState?: string;
48
- protected constructor(source: string, subject: string, type: string, specVersion: string, id: string, time: Date, dataContentType: string, predecessorHash: string, traceParent?: string, traceState?: string);
49
- static parse(unknownObject: UnknownObject): EventContext;
50
- toJSON(): Record<string, unknown>;
51
- toString(): string;
52
- }
53
-
54
- declare class Event extends EventContext {
55
- readonly data: Record<string, unknown>;
56
- private constructor();
57
- static parse(unknownObject: UnknownObject): Event;
58
- toJSON(): Record<string, unknown>;
59
- }
60
-
61
- interface StoreItem {
62
- event: Event;
1
+ interface Event {
2
+ specversion: string;
3
+ id: string;
4
+ time: Date;
5
+ source: string;
6
+ subject: string;
7
+ type: string;
8
+ datacontenttype: string;
9
+ data: Record<string, unknown>;
63
10
  hash: string;
11
+ predecessorhash: string;
12
+ traceparent?: string;
13
+ tracestate?: string;
64
14
  }
65
15
 
66
- interface ObserveEventsOptions {
67
- recursive: boolean;
68
- lowerBoundId?: string;
69
- fromLatestEvent?: ObserveFromLatestEvent;
70
- }
71
- interface ObserveFromLatestEvent {
16
+ interface EventCandidate {
17
+ source: string;
72
18
  subject: string;
73
19
  type: string;
74
- ifEventIsMissing: 'read-everything' | 'wait-for-event';
20
+ data: Record<string, unknown>;
21
+ traceparent?: string;
22
+ tracestate?: string;
75
23
  }
76
24
 
77
25
  interface EventType {
78
26
  eventType: string;
79
27
  isPhantom: boolean;
80
- schema?: string;
28
+ schema?: Record<string, unknown>;
81
29
  }
82
30
 
83
- interface ReadEventsOptions {
84
- recursive: boolean;
85
- order?: Order;
86
- lowerBoundId?: string;
87
- upperBoundId?: string;
88
- fromLatestEvent?: ReadFromLatestEvent;
31
+ type BoundType = 'inclusive' | 'exclusive';
32
+ interface Bound {
33
+ id: string;
34
+ type: BoundType;
89
35
  }
90
- type Order = 'chronological' | 'antichronological';
91
- interface ReadFromLatestEvent {
36
+
37
+ type ObserveIfEventIsMissing = 'read-everything' | 'wait-for-event';
38
+ interface ObserveFromLatestEvent {
92
39
  subject: string;
93
40
  type: string;
94
- ifEventIsMissing: 'read-nothing' | 'read-everything';
41
+ ifEventIsMissing: ObserveIfEventIsMissing;
95
42
  }
96
-
97
- interface ReadSubjectsOptions {
98
- baseSubject: string;
43
+ interface ObserveEventsOptions {
44
+ recursive: boolean;
45
+ lowerBound?: Bound;
46
+ fromLatestEvent?: ObserveFromLatestEvent;
99
47
  }
100
48
 
49
+ interface IsSubjectPristinePrecondition {
50
+ subject: string;
51
+ }
52
+ interface IsSubjectOnEventIdPrecondition {
53
+ subject: string;
54
+ eventId: string;
55
+ }
101
56
  type Precondition = {
102
57
  type: 'isSubjectPristine';
103
58
  payload: IsSubjectPristinePrecondition;
@@ -105,57 +60,37 @@ type Precondition = {
105
60
  type: 'isSubjectOnEventId';
106
61
  payload: IsSubjectOnEventIdPrecondition;
107
62
  };
108
- interface IsSubjectPristinePrecondition {
109
- subject: string;
110
- }
111
- interface IsSubjectOnEventIdPrecondition {
63
+
64
+ type Order = 'chronological' | 'antichronological';
65
+ type ReadIfEventIsMissing = 'read-nothing' | 'read-everything';
66
+ interface ReadFromLatestEvent {
112
67
  subject: string;
113
- eventId: string;
68
+ type: string;
69
+ ifEventIsMissing: ReadIfEventIsMissing;
114
70
  }
115
- declare const isSubjectPristine: (payload: IsSubjectPristinePrecondition) => Precondition;
116
- declare const isSubjectOnEventId: (payload: IsSubjectOnEventIdPrecondition) => Precondition;
117
-
118
- type ResponseDataType<TResponseType extends ResponseType> = TResponseType extends 'arraybuffer' ? ArrayBuffer : TResponseType extends 'blob' ? Blob : TResponseType extends 'document' ? unknown : TResponseType extends 'json' ? unknown : TResponseType extends 'text' ? string : TResponseType extends 'stream' ? Readable : never;
119
- type Response<TResponseType extends ResponseType> = AxiosResponse<ResponseDataType<TResponseType>, unknown>;
120
- declare class HttpClient {
121
- private readonly databaseClient;
122
- constructor(dbClient: Client);
123
- private getDefaultRequestConfig;
124
- private static setContentType;
125
- private static setAuthorization;
126
- private static setResponseType;
127
- validateProtocolVersion(httpStatusCode: number, headers: Record<string, unknown>): void;
128
- post<TResponseType extends ResponseType>(options: {
129
- path: string;
130
- responseType: TResponseType;
131
- requestBody: string;
132
- abortController?: AbortController;
133
- }): Promise<Response<TResponseType>>;
134
- get<TResponseType extends ResponseType>(options: {
135
- path: string;
136
- responseType: TResponseType;
137
- abortController?: AbortController;
138
- withAuthorization?: boolean;
139
- }): Promise<Response<TResponseType>>;
71
+ interface ReadEventsOptions {
72
+ recursive: boolean;
73
+ order?: Order;
74
+ lowerBound?: Bound;
75
+ upperBound?: Bound;
76
+ fromLatestEvent?: ReadFromLatestEvent;
140
77
  }
141
78
 
142
79
  declare class Client {
143
- readonly configuration: ClientConfiguration;
144
- readonly httpClient: HttpClient;
145
- constructor(baseUrl: string, options: ClientOptions);
146
- observeEvents(abortController: AbortController, subject: string, options: ObserveEventsOptions): AsyncGenerator<StoreItem, void, void>;
80
+ #private;
81
+ constructor(url: URL, apiToken: string);
147
82
  ping(): Promise<void>;
148
- readEvents(abortController: AbortController, subject: string, options: ReadEventsOptions): AsyncGenerator<StoreItem, void, void>;
149
- readEventTypes(abortController: AbortController): AsyncGenerator<EventType, void, void>;
150
- readSubjects(abortController: AbortController, options: ReadSubjectsOptions): AsyncGenerator<string, void, void>;
151
- registerEventSchema(eventType: string, schema: string | object): Promise<void>;
152
- writeEvents(eventCandidates: EventCandidate[], preconditions?: Precondition[]): Promise<EventContext[]>;
83
+ verifyApiToken(): Promise<void>;
84
+ writeEvents(events: EventCandidate[], preconditions?: Precondition[]): Promise<Event[]>;
85
+ readEvents(subject: string, options: ReadEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
86
+ observeEvents(subject: string, options: ObserveEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
87
+ registerEventSchema(eventType: string, schema: Record<string, unknown>): Promise<void>;
88
+ readSubjects(baseSubject: string, signal?: AbortSignal): AsyncGenerator<string, void, void>;
89
+ readEventTypes(signal?: AbortSignal): AsyncGenerator<EventType, void, void>;
153
90
  }
154
91
 
155
- declare class Source {
156
- readonly source: string;
157
- constructor(source: string);
158
- newEvent(subject: string, type: string, data: UnknownObject, traceParent?: string, traceState?: string): EventCandidate;
159
- }
92
+ declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
93
+
94
+ declare const isSubjectPristine: (subject: string) => Precondition;
160
95
 
161
- export { CancelationError, Client, type ClientConfiguration, Event, EventCandidate, type ObserveEventsOptions, type ObserveFromLatestEvent, type Precondition, type ReadEventsOptions, type ReadFromLatestEvent, type ReadSubjectsOptions, Source, type StoreItem, isSubjectOnEventId, isSubjectPristine };
96
+ export { Client, type Event, type EventCandidate, type EventType, type ObserveEventsOptions, type ReadEventsOptions, isSubjectOnEventId, isSubjectPristine };
package/dist/index.d.ts CHANGED
@@ -1,103 +1,58 @@
1
- import { Readable } from 'node:stream';
2
- import { ResponseType, AxiosResponse } from 'axios';
3
-
4
- declare class CustomError extends Error {
5
- }
6
-
7
- declare class CancelationError extends CustomError {
8
- }
9
-
10
- interface ClientConfiguration {
11
- baseUrl: string;
12
- timeoutMilliseconds: number;
13
- accessToken: string;
14
- protocolVersion: string;
15
- }
16
-
17
- interface ClientOptions {
18
- timeoutMilliseconds?: number;
19
- accessToken: string;
20
- protocolVersion?: string;
21
- }
22
-
23
- type UnknownObject = Partial<Record<string, unknown>>;
24
-
25
- declare class EventCandidate {
26
- readonly data: Record<string, unknown>;
27
- readonly source: string;
28
- readonly subject: string;
29
- readonly type: string;
30
- readonly traceParent?: string;
31
- readonly traceState?: string;
32
- constructor(source: string, subject: string, type: string, data: UnknownObject, traceParent?: string, traceState?: string);
33
- validate(): void;
34
- toJSON(): Record<string, unknown>;
35
- }
36
-
37
- declare class EventContext {
38
- readonly source: string;
39
- readonly subject: string;
40
- readonly type: string;
41
- readonly specVersion: string;
42
- readonly id: string;
43
- readonly time: Date;
44
- readonly dataContentType: string;
45
- readonly predecessorHash: string;
46
- readonly traceParent?: string;
47
- readonly traceState?: string;
48
- protected constructor(source: string, subject: string, type: string, specVersion: string, id: string, time: Date, dataContentType: string, predecessorHash: string, traceParent?: string, traceState?: string);
49
- static parse(unknownObject: UnknownObject): EventContext;
50
- toJSON(): Record<string, unknown>;
51
- toString(): string;
52
- }
53
-
54
- declare class Event extends EventContext {
55
- readonly data: Record<string, unknown>;
56
- private constructor();
57
- static parse(unknownObject: UnknownObject): Event;
58
- toJSON(): Record<string, unknown>;
59
- }
60
-
61
- interface StoreItem {
62
- event: Event;
1
+ interface Event {
2
+ specversion: string;
3
+ id: string;
4
+ time: Date;
5
+ source: string;
6
+ subject: string;
7
+ type: string;
8
+ datacontenttype: string;
9
+ data: Record<string, unknown>;
63
10
  hash: string;
11
+ predecessorhash: string;
12
+ traceparent?: string;
13
+ tracestate?: string;
64
14
  }
65
15
 
66
- interface ObserveEventsOptions {
67
- recursive: boolean;
68
- lowerBoundId?: string;
69
- fromLatestEvent?: ObserveFromLatestEvent;
70
- }
71
- interface ObserveFromLatestEvent {
16
+ interface EventCandidate {
17
+ source: string;
72
18
  subject: string;
73
19
  type: string;
74
- ifEventIsMissing: 'read-everything' | 'wait-for-event';
20
+ data: Record<string, unknown>;
21
+ traceparent?: string;
22
+ tracestate?: string;
75
23
  }
76
24
 
77
25
  interface EventType {
78
26
  eventType: string;
79
27
  isPhantom: boolean;
80
- schema?: string;
28
+ schema?: Record<string, unknown>;
81
29
  }
82
30
 
83
- interface ReadEventsOptions {
84
- recursive: boolean;
85
- order?: Order;
86
- lowerBoundId?: string;
87
- upperBoundId?: string;
88
- fromLatestEvent?: ReadFromLatestEvent;
31
+ type BoundType = 'inclusive' | 'exclusive';
32
+ interface Bound {
33
+ id: string;
34
+ type: BoundType;
89
35
  }
90
- type Order = 'chronological' | 'antichronological';
91
- interface ReadFromLatestEvent {
36
+
37
+ type ObserveIfEventIsMissing = 'read-everything' | 'wait-for-event';
38
+ interface ObserveFromLatestEvent {
92
39
  subject: string;
93
40
  type: string;
94
- ifEventIsMissing: 'read-nothing' | 'read-everything';
41
+ ifEventIsMissing: ObserveIfEventIsMissing;
95
42
  }
96
-
97
- interface ReadSubjectsOptions {
98
- baseSubject: string;
43
+ interface ObserveEventsOptions {
44
+ recursive: boolean;
45
+ lowerBound?: Bound;
46
+ fromLatestEvent?: ObserveFromLatestEvent;
99
47
  }
100
48
 
49
+ interface IsSubjectPristinePrecondition {
50
+ subject: string;
51
+ }
52
+ interface IsSubjectOnEventIdPrecondition {
53
+ subject: string;
54
+ eventId: string;
55
+ }
101
56
  type Precondition = {
102
57
  type: 'isSubjectPristine';
103
58
  payload: IsSubjectPristinePrecondition;
@@ -105,57 +60,37 @@ type Precondition = {
105
60
  type: 'isSubjectOnEventId';
106
61
  payload: IsSubjectOnEventIdPrecondition;
107
62
  };
108
- interface IsSubjectPristinePrecondition {
109
- subject: string;
110
- }
111
- interface IsSubjectOnEventIdPrecondition {
63
+
64
+ type Order = 'chronological' | 'antichronological';
65
+ type ReadIfEventIsMissing = 'read-nothing' | 'read-everything';
66
+ interface ReadFromLatestEvent {
112
67
  subject: string;
113
- eventId: string;
68
+ type: string;
69
+ ifEventIsMissing: ReadIfEventIsMissing;
114
70
  }
115
- declare const isSubjectPristine: (payload: IsSubjectPristinePrecondition) => Precondition;
116
- declare const isSubjectOnEventId: (payload: IsSubjectOnEventIdPrecondition) => Precondition;
117
-
118
- type ResponseDataType<TResponseType extends ResponseType> = TResponseType extends 'arraybuffer' ? ArrayBuffer : TResponseType extends 'blob' ? Blob : TResponseType extends 'document' ? unknown : TResponseType extends 'json' ? unknown : TResponseType extends 'text' ? string : TResponseType extends 'stream' ? Readable : never;
119
- type Response<TResponseType extends ResponseType> = AxiosResponse<ResponseDataType<TResponseType>, unknown>;
120
- declare class HttpClient {
121
- private readonly databaseClient;
122
- constructor(dbClient: Client);
123
- private getDefaultRequestConfig;
124
- private static setContentType;
125
- private static setAuthorization;
126
- private static setResponseType;
127
- validateProtocolVersion(httpStatusCode: number, headers: Record<string, unknown>): void;
128
- post<TResponseType extends ResponseType>(options: {
129
- path: string;
130
- responseType: TResponseType;
131
- requestBody: string;
132
- abortController?: AbortController;
133
- }): Promise<Response<TResponseType>>;
134
- get<TResponseType extends ResponseType>(options: {
135
- path: string;
136
- responseType: TResponseType;
137
- abortController?: AbortController;
138
- withAuthorization?: boolean;
139
- }): Promise<Response<TResponseType>>;
71
+ interface ReadEventsOptions {
72
+ recursive: boolean;
73
+ order?: Order;
74
+ lowerBound?: Bound;
75
+ upperBound?: Bound;
76
+ fromLatestEvent?: ReadFromLatestEvent;
140
77
  }
141
78
 
142
79
  declare class Client {
143
- readonly configuration: ClientConfiguration;
144
- readonly httpClient: HttpClient;
145
- constructor(baseUrl: string, options: ClientOptions);
146
- observeEvents(abortController: AbortController, subject: string, options: ObserveEventsOptions): AsyncGenerator<StoreItem, void, void>;
80
+ #private;
81
+ constructor(url: URL, apiToken: string);
147
82
  ping(): Promise<void>;
148
- readEvents(abortController: AbortController, subject: string, options: ReadEventsOptions): AsyncGenerator<StoreItem, void, void>;
149
- readEventTypes(abortController: AbortController): AsyncGenerator<EventType, void, void>;
150
- readSubjects(abortController: AbortController, options: ReadSubjectsOptions): AsyncGenerator<string, void, void>;
151
- registerEventSchema(eventType: string, schema: string | object): Promise<void>;
152
- writeEvents(eventCandidates: EventCandidate[], preconditions?: Precondition[]): Promise<EventContext[]>;
83
+ verifyApiToken(): Promise<void>;
84
+ writeEvents(events: EventCandidate[], preconditions?: Precondition[]): Promise<Event[]>;
85
+ readEvents(subject: string, options: ReadEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
86
+ observeEvents(subject: string, options: ObserveEventsOptions, signal?: AbortSignal): AsyncGenerator<Event, void, void>;
87
+ registerEventSchema(eventType: string, schema: Record<string, unknown>): Promise<void>;
88
+ readSubjects(baseSubject: string, signal?: AbortSignal): AsyncGenerator<string, void, void>;
89
+ readEventTypes(signal?: AbortSignal): AsyncGenerator<EventType, void, void>;
153
90
  }
154
91
 
155
- declare class Source {
156
- readonly source: string;
157
- constructor(source: string);
158
- newEvent(subject: string, type: string, data: UnknownObject, traceParent?: string, traceState?: string): EventCandidate;
159
- }
92
+ declare const isSubjectOnEventId: (subject: string, eventId: string) => Precondition;
93
+
94
+ declare const isSubjectPristine: (subject: string) => Precondition;
160
95
 
161
- export { CancelationError, Client, type ClientConfiguration, Event, EventCandidate, type ObserveEventsOptions, type ObserveFromLatestEvent, type Precondition, type ReadEventsOptions, type ReadFromLatestEvent, type ReadSubjectsOptions, Source, type StoreItem, isSubjectOnEventId, isSubjectPristine };
96
+ export { Client, type Event, type EventCandidate, type EventType, type ObserveEventsOptions, type ReadEventsOptions, isSubjectOnEventId, isSubjectPristine };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ut=Object.create;var O=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var yt=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var wt=(r,t)=>{for(var e in t)O(r,e,{get:t[e],enumerable:!0})},L=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vt(t))!ht.call(r,n)&&n!==e&&O(r,n,{get:()=>t[n],enumerable:!(s=lt(t,n))||s.enumerable});return r};var J=(r,t,e)=>(e=r!=null?ut(yt(r)):{},L(t||!r||!r.__esModule?O(e,"default",{value:r,enumerable:!0}):e,r)),gt=r=>L(O({},"__esModule",{value:!0}),r);var St={};wt(St,{CancelationError:()=>h,Client:()=>F,Event:()=>w,EventCandidate:()=>j,Source:()=>N,isSubjectOnEventId:()=>mt,isSubjectPristine:()=>dt});module.exports=gt(St);var d=class extends Error{};var h=class extends d{};var q=r=>({baseUrl:r,timeoutMilliseconds:1e4,accessToken:"",protocolVersion:"1.0.0"});var $=require("http-status-codes");var l=r=>typeof r=="object"&&!Array.isArray(r)&&r!==null;var a=class extends d{};var k="[0-9A-Za-z_-]+",bt=new RegExp(`^/(${k}/)*(${k}/?)?$`,"u"),v=r=>{if(!bt.test(r))throw new a(`Failed to validate subject: '${r}' must be an absolute, slash-separated path.`)};var Et=/^[0-9A-Za-z_-]{2,}\.(?:[0-9A-Za-z_-]+\.)+[0-9A-Za-z_-]+$/u,y=r=>{if(!Et.test(r))throw new a(`Failed to validate type: '${r}' must be a reverse domain name.`)};var E=class r{source;subject;type;specVersion;id;time;dataContentType;predecessorHash;traceParent;traceState;constructor(t,e,s,n,p,o,i,R,D,U){this.source=t,this.subject=e,this.type=s,this.specVersion=n,this.id=p,this.time=o,this.dataContentType=i,this.predecessorHash=R,this.traceParent=D,this.traceState=U}static parse(t){if(typeof t.source!="string")throw new a(`Failed to parse source '${t.source}' to string.`);if(typeof t.subject!="string")throw new a(`Failed to parse subject '${t.subject}' to string.`);if(v(t.subject),typeof t.type!="string")throw new a(`Failed to parse type '${t.type}' to string.`);if(y(t.type),typeof t.specversion!="string")throw new a(`Failed to parse specVersion '${t.specversion}' to string.`);if(typeof t.id!="string")throw new a(`Failed to parse id '${t.id}' to string.`);if(typeof t.time!="string")throw new a(`Failed to parse time '${t.time}' to Date.`);let e=new Date(t.time);if(e.toString()==="Invalid Date")throw new a(`Failed to parse time '${t.time}' to Date.`);if(typeof t.datacontenttype!="string")throw new a(`Failed to parse dataContentType '${t.datacontenttype}' to string.`);if(typeof t.predecessorhash!="string")throw new a(`Failed to parse predecessorHash '${t.predecessorhash}' to string.`);if(t.traceparent!==void 0&&typeof t.traceparent!="string")throw new a(`Failed to parse traceparent '${t.traceparent}' to string.`);if(t.tracestate!==void 0&&typeof t.tracestate!="string")throw new a(`Failed to parse tracestate '${t.tracestate}' to string.`);return new r(t.source,t.subject,t.type,t.specversion,t.id,e,t.datacontenttype,t.predecessorhash,t.traceparent,t.tracestate)}toJSON(){return{specversion:this.specVersion,id:this.id,time:this.time.toISOString(),source:this.source,subject:this.subject,type:this.type,datacontenttype:this.dataContentType,predecessorhash:this.predecessorHash,traceparent:this.traceParent,tracestate:this.traceState}}toString(){return JSON.stringify(this)}};var w=class r extends E{data;constructor(t,e,s,n,p,o,i,R,D,U,ft){super(e,s,n,p,o,i,R,D,U,ft),this.data=t}static parse(t){let e=E.parse(t);if(!l(t.data))throw new Error(`Failed to parse data '${t.data}' to object.`);return new r(t.data,e.source,e.subject,e.type,e.specVersion,e.id,e.time,e.dataContentType,e.predecessorHash,e.traceParent,e.traceState)}toJSON(){return{...super.toJSON(),data:this.data}}};var f=class extends d{constructor(t){super(`Internal error occurred: ${t}`)}};var u=class extends d{constructor(t,e){super(`Parameter '${t}' is invalid: ${e}`)}};var c=class extends d{constructor(t){super(`Server error occurred: ${t}`)}};var H=r=>typeof r=="object"&&typeof r.then=="function";function m(r,t){try{let e=r();return H(e)?e.catch(s=>{let n;s instanceof Error?n=s:n=new f(s);try{let p=t(n);return H(p)?p.then(()=>Promise.reject(new f("onError did not throw."))).catch(o=>{let i;return o instanceof Error?i=o:i=new f(o),Promise.reject(i)}):Promise.reject(n)}catch(p){let o;return p instanceof Error?o=p:o=new f(p),Promise.reject(o)}}):e}catch(e){throw e instanceof Error&&t(e),new f(e)}}var G=require("axios"),M=J(require("stream-to-async-iterator"));var z=require("string_decoder"),I=class{textBuffer;decoder;constructor(t){this.textBuffer="",this.decoder=new z.StringDecoder(t)}write(t){this.textBuffer+=this.decoder.write(t);let e=[],s=0;for(let n=0;n<this.textBuffer.length;n++){if(this.textBuffer[n]!==`
2
- `)continue;let o=this.textBuffer.slice(s,n);s=n+1,e.push(o)}return this.textBuffer=this.textBuffer.slice(s),e}};var g=async function*(r){let t=new I("utf-8");try{for await(let e of new M.default(r)){let s=t.write(e);for(let n of s)yield JSON.parse(n)}}catch(e){throw e instanceof G.CanceledError?new h:new c("Failed to read response.")}};var C=r=>l(r)&&r.type==="heartbeat";var P=r=>{if(!l(r)||r.type!=="item")return!1;let{payload:t}=r;return l(t)&&l(t.event)&&typeof t.hash=="string"};var b=r=>{if(!l(r)||r.type!=="error")return!1;let{payload:t}=r;return l(t)&&typeof t.error=="string"};var Ct=/^\d+$/u,T=r=>Ct.test(r);var K=r=>{if(r.lowerBoundId!==void 0&&!T(r.lowerBoundId))throw new a("ObserveEventsOptions are invalid: lowerBoundId must be 0 or greater.");if(r.lowerBoundId!==void 0&&r.fromLatestEvent!==void 0)throw new a("ObserveEventsOptions are invalid: lowerBoundId and fromLatestEvent are mutually exclusive.");let{fromLatestEvent:t}=r;t!==void 0&&m(()=>{v(t.subject),y(t.type)},e=>{throw new a(`ObserveEventsOptions are invalid: Failed to validate 'fromLatestEvent': ${e.message}`)})};var Z=async function*(r,t,e,s){await m(()=>v(e),i=>{if(i instanceof a)throw new u("subject",i.message)}),await m(()=>{K(s)},i=>{if(i instanceof a)throw new u("options",i.message)});let n=m(()=>JSON.stringify({subject:e,options:s}),()=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),p=await m(async()=>r.httpClient.post({path:"/api/observe-events",requestBody:n,responseType:"stream",abortController:t}),i=>{throw i instanceof d?i:new f(i)});if(p.status!==$.StatusCodes.OK)throw new c(`Unexpected response status: ${p.status} ${(0,$.getReasonPhrase)(p.status)}.`);let o=p.data;for await(let i of g(o))if(!C(i)){if(b(i))throw new c(`${i.payload.error}.`);if(P(i)){yield{event:w.parse(i.payload.event),hash:i.payload.hash};continue}throw new c(`Failed to observe events, an unexpected stream item was received: '${JSON.stringify(i)}'.`)}};var X=async r=>{if((await m(async()=>r.httpClient.get({path:"/api/ping",responseType:"text",withAuthorization:!1}),e=>{if(e instanceof d)throw e;new f(e)})).data!=="OK")throw new c("Received unexpected response.")};var _=require("http-status-codes");var Y=r=>!(!l(r)||r.type!=="eventType");var Q=async function*(r,t){let e=await m(async()=>r.httpClient.post({path:"/api/read-event-types",requestBody:"",responseType:"stream",abortController:t}),n=>{throw n instanceof d?n:new f(n)});if(e.status!==_.StatusCodes.OK)throw new c(`Unexpected response status: ${e.status} ${e.statusText}.`);let s=e.data;for await(let n of g(s))if(!C(n)){if(b(n))throw new c(`${n.payload.error}.`);if(Y(n)){yield n.payload;continue}throw new c(`Failed to read events, an unexpected stream item was received: '${JSON.stringify(n)}'.`)}};var tt=require("http-status-codes");var W=r=>{if(r.lowerBoundId!==void 0&&!T(r.lowerBoundId))throw new a("ReadEventsOptions are invalid: lowerBoundId must be 0 or greater.");if(r.upperBoundId!==void 0&&!T(r.upperBoundId))throw new a("ReadEventsOptions are invalid: upperBoundId must be 0 or greater.");if(r.fromLatestEvent!==void 0){if(r.lowerBoundId!==void 0)throw new a("ReadEventsOptions are invalid: lowerBoundId and fromLatestEvent are mutually exclusive.");let{fromLatestEvent:t}=r;m(()=>{v(t.subject),y(t.type)},e=>{throw new a(`ReadEventsOptions are invalid: Failed to validate 'fromLatestEvent': ${e.message}`)})}};var et=async function*(r,t,e,s){m(()=>v(e),i=>{if(i instanceof a)throw new u("subject",i.message)}),m(()=>{W(s)},i=>{if(i instanceof a)throw new u("options",i.message)});let n=m(()=>JSON.stringify({subject:e,options:s}),()=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),p=await m(async()=>r.httpClient.post({path:"/api/read-events",requestBody:n,responseType:"stream",abortController:t}),i=>{throw i instanceof d?i:new f(i)});if(p.status!==tt.StatusCodes.OK)throw new c(`Unexpected response status: ${p.status} ${p.statusText}.`);let o=p.data;for await(let i of g(o))if(!C(i)){if(b(i))throw new c(`${i.payload.error}.`);if(P(i)){yield{event:w.parse(i.payload.event),hash:i.payload.hash};continue}throw new c(`Failed to read events, an unexpected stream item was received: '${JSON.stringify(i)}'.`)}};var A=require("http-status-codes");var rt=r=>{v(r.baseSubject)};var ot=r=>{if(!l(r)||r.type!=="subject")return!1;let{payload:t}=r;return l(t)&&typeof t.subject=="string"};var nt=async function*(r,t,e){await m(()=>{rt(e)},o=>{if(o instanceof a)throw new u("options",o.message)});let s=m(()=>JSON.stringify(e),o=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),n=await m(async()=>r.httpClient.post({path:"/api/read-subjects",requestBody:s,responseType:"stream",abortController:t}),o=>{throw o instanceof d?o:new f(o)});if(n.status!==A.StatusCodes.OK)throw new c(`Unexpected response status: ${n.status} ${(0,A.getReasonPhrase)(n.status)}.`);let p=n.data;for await(let o of g(p)){if(b(o))throw new c(o.payload.error);if(ot(o)){yield o.payload.subject;continue}throw new c(`Failed to read subjects, an unexpected stream item was received: '${JSON.stringify(o)}'.`)}};var st=require("http-status-codes");var it=async(r,t,e)=>{m(()=>y(t),o=>{if(o instanceof a)throw new u("eventType",o.message)});let s=e;typeof e=="object"&&(s=JSON.stringify(e));let n=JSON.stringify({eventType:t,schema:s}),p=await m(async()=>r.httpClient.post({path:"/api/register-event-schema",requestBody:n,responseType:"text"}),o=>{throw o instanceof d?o:new f(o)});if(p.status!==st.StatusCodes.OK)throw new c(`Unexpected response status: ${p.status} ${p.statusText}: ${p.data}.`)};var at=require("http-status-codes");var pt=async(r,t,e)=>{if(t.length===0)throw new u("eventCandidates","eventCandidates must contain at least one EventCandidate.");for(let o of t)m(()=>{o.validate()},i=>{if(i instanceof a)throw new u("eventCandidates",i.message)});let s=JSON.stringify({events:t,preconditions:e}),n=await m(async()=>r.httpClient.post({path:"/api/write-events",requestBody:s,responseType:"json"}),o=>{throw o instanceof d?o:new f(o)});if(n.status!==at.StatusCodes.OK)throw new c(`Unexpected response status: ${n.status} ${n.statusText}.`);if(!Array.isArray(n.data))throw new c(`Failed to parse response '${n.data}' to array.`);let p=n.data;return m(()=>p.map(o=>E.parse(o)),o=>{throw o instanceof a?new c(o.message):new f(o)})};var x=require("axios"),V=J(require("axios")),ct=require("http-status-codes");var S=class extends d{constructor(t){super(`Client error occurred: ${t}`)}};var B=class r{databaseClient;constructor(t){this.databaseClient=t}getDefaultRequestConfig(t=!0){let e={baseURL:this.databaseClient.configuration.baseUrl,timeout:this.databaseClient.configuration.timeoutMilliseconds,headers:{"X-EventSourcingDB-Protocol-Version":this.databaseClient.configuration.protocolVersion},validateStatus:()=>!0};return t&&this.databaseClient.configuration.accessToken!==void 0&&(e=r.setAuthorization(e,this.databaseClient.configuration.accessToken)),e}static setContentType(t,e){return{...t,headers:{...t.headers,"Content-Type":e}}}static setAuthorization(t,e){return{...t,headers:{...t.headers,authorization:`Bearer ${e}`}}}static setResponseType(t,e){return{...t,responseType:e}}validateProtocolVersion(t,e){if(t!==ct.StatusCodes.UNPROCESSABLE_ENTITY)return;let s=e["x-eventsourcingdb-protocol-version"];throw s===void 0&&(s="unknown version"),new S(`Protocol version mismatch, server '${s}', client '${this.databaseClient.configuration.protocolVersion}.'`)}async post(t){let e=this.getDefaultRequestConfig();e=r.setContentType(e,"application/json"),e=r.setResponseType(e,t.responseType);let s=V.default.create(e),p=(t.abortController??new AbortController).signal;try{let o=await s.post(t.path,t.requestBody,{signal:p});if(o.status>=500&&o.status<600)throw new c(`Request failed with status code '${o.status}'.`);if(this.validateProtocolVersion(o.status,o.headers),o.status>=400&&o.status<500)throw new S(`Request failed with status code '${o.status}'.`);return o}catch(o){throw o instanceof d?o:o instanceof x.CanceledError?new h:o instanceof x.AxiosError?o.request!==void 0?new c("No response received."):new f("Failed to setup request."):new f(o)}}async get(t){let e=this.getDefaultRequestConfig(t.withAuthorization);e=r.setResponseType(e,t.responseType);let s=V.default.create(e),p=(t.abortController??new AbortController).signal;try{let o=await s.get(t.path,{signal:p});if(o.status>=500&&o.status<600)throw new c(`Request failed with status code '${o.status}'.`);if(this.validateProtocolVersion(o.status,o.headers),o.status>=400&&o.status<500)throw new S(`Request failed with status code '${o.status}'.`);return this.validateProtocolVersion(o.status,o.headers),o}catch(o){throw o instanceof d?o:o instanceof x.CanceledError?new h:o instanceof x.AxiosError?o.request!==void 0?new c("No response received."):new f("Failed to setup request."):new f(o)}}};var F=class{configuration;httpClient;constructor(t,e){this.configuration={...q(t),...e},this.httpClient=new B(this)}observeEvents(t,e,s){return Z(this,t,e,s)}async ping(){await X(this)}readEvents(t,e,s){return et(this,t,e,s)}readEventTypes(t){return Q(this,t)}readSubjects(t,e){return nt(this,t,e)}async registerEventSchema(t,e){return await it(this,t,e)}async writeEvents(t,e=[]){return await pt(this,t,e)}};var j=class{data;source;subject;type;traceParent;traceState;constructor(t,e,s,n,p,o){this.data=n,this.source=t,this.subject=e,this.type=s,this.traceParent=p,this.traceState=o}validate(){if(v(this.subject),y(this.type),this.traceState!==void 0&&this.traceParent===void 0)throw new a("Failed to validate trace state: trace parent must be set if trace state is set.")}toJSON(){return{data:this.data,source:this.source,subject:this.subject,type:this.type,traceparent:this.traceParent,tracestate:this.traceState}}};var N=class{source;constructor(t){this.source=t}newEvent(t,e,s,n,p){return new j(this.source,t,e,s,n,p)}};var dt=r=>({type:"isSubjectPristine",payload:r}),mt=r=>({type:"isSubjectOnEventId",payload:r});0&&(module.exports={CancelationError,Client,Event,EventCandidate,Source,isSubjectOnEventId,isSubjectPristine});
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});
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var d=class extends Error{};var h=class extends d{};var F=r=>({baseUrl:r,timeoutMilliseconds:1e4,accessToken:"",protocolVersion:"1.0.0"});import{StatusCodes as st,getReasonPhrase as it}from"http-status-codes";var l=r=>typeof r=="object"&&!Array.isArray(r)&&r!==null;var a=class extends d{};var N="[0-9A-Za-z_-]+",W=new RegExp(`^/(${N}/)*(${N}/?)?$`,"u"),v=r=>{if(!W.test(r))throw new a(`Failed to validate subject: '${r}' must be an absolute, slash-separated path.`)};var tt=/^[0-9A-Za-z_-]{2,}\.(?:[0-9A-Za-z_-]+\.)+[0-9A-Za-z_-]+$/u,y=r=>{if(!tt.test(r))throw new a(`Failed to validate type: '${r}' must be a reverse domain name.`)};var b=class r{source;subject;type;specVersion;id;time;dataContentType;predecessorHash;traceParent;traceState;constructor(t,e,i,n,p,o,s,x,P,$){this.source=t,this.subject=e,this.type=i,this.specVersion=n,this.id=p,this.time=o,this.dataContentType=s,this.predecessorHash=x,this.traceParent=P,this.traceState=$}static parse(t){if(typeof t.source!="string")throw new a(`Failed to parse source '${t.source}' to string.`);if(typeof t.subject!="string")throw new a(`Failed to parse subject '${t.subject}' to string.`);if(v(t.subject),typeof t.type!="string")throw new a(`Failed to parse type '${t.type}' to string.`);if(y(t.type),typeof t.specversion!="string")throw new a(`Failed to parse specVersion '${t.specversion}' to string.`);if(typeof t.id!="string")throw new a(`Failed to parse id '${t.id}' to string.`);if(typeof t.time!="string")throw new a(`Failed to parse time '${t.time}' to Date.`);let e=new Date(t.time);if(e.toString()==="Invalid Date")throw new a(`Failed to parse time '${t.time}' to Date.`);if(typeof t.datacontenttype!="string")throw new a(`Failed to parse dataContentType '${t.datacontenttype}' to string.`);if(typeof t.predecessorhash!="string")throw new a(`Failed to parse predecessorHash '${t.predecessorhash}' to string.`);if(t.traceparent!==void 0&&typeof t.traceparent!="string")throw new a(`Failed to parse traceparent '${t.traceparent}' to string.`);if(t.tracestate!==void 0&&typeof t.tracestate!="string")throw new a(`Failed to parse tracestate '${t.tracestate}' to string.`);return new r(t.source,t.subject,t.type,t.specversion,t.id,e,t.datacontenttype,t.predecessorhash,t.traceparent,t.tracestate)}toJSON(){return{specversion:this.specVersion,id:this.id,time:this.time.toISOString(),source:this.source,subject:this.subject,type:this.type,datacontenttype:this.dataContentType,predecessorhash:this.predecessorHash,traceparent:this.traceParent,tracestate:this.traceState}}toString(){return JSON.stringify(this)}};var E=class r extends b{data;constructor(t,e,i,n,p,o,s,x,P,$,Q){super(e,i,n,p,o,s,x,P,$,Q),this.data=t}static parse(t){let e=b.parse(t);if(!l(t.data))throw new Error(`Failed to parse data '${t.data}' to object.`);return new r(t.data,e.source,e.subject,e.type,e.specVersion,e.id,e.time,e.dataContentType,e.predecessorHash,e.traceParent,e.traceState)}toJSON(){return{...super.toJSON(),data:this.data}}};var f=class extends d{constructor(t){super(`Internal error occurred: ${t}`)}};var u=class extends d{constructor(t,e){super(`Parameter '${t}' is invalid: ${e}`)}};var c=class extends d{constructor(t){super(`Server error occurred: ${t}`)}};var D=r=>typeof r=="object"&&typeof r.then=="function";function m(r,t){try{let e=r();return D(e)?e.catch(i=>{let n;i instanceof Error?n=i:n=new f(i);try{let p=t(n);return D(p)?p.then(()=>Promise.reject(new f("onError did not throw."))).catch(o=>{let s;return o instanceof Error?s=o:s=new f(o),Promise.reject(s)}):Promise.reject(n)}catch(p){let o;return p instanceof Error?o=p:o=new f(p),Promise.reject(o)}}):e}catch(e){throw e instanceof Error&&t(e),new f(e)}}import{CanceledError as rt}from"axios";import ot from"stream-to-async-iterator";import{StringDecoder as et}from"node:string_decoder";var T=class{textBuffer;decoder;constructor(t){this.textBuffer="",this.decoder=new et(t)}write(t){this.textBuffer+=this.decoder.write(t);let e=[],i=0;for(let n=0;n<this.textBuffer.length;n++){if(this.textBuffer[n]!==`
2
- `)continue;let o=this.textBuffer.slice(i,n);i=n+1,e.push(o)}return this.textBuffer=this.textBuffer.slice(i),e}};var w=async function*(r){let t=new T("utf-8");try{for await(let e of new ot(r)){let i=t.write(e);for(let n of i)yield JSON.parse(n)}}catch(e){throw e instanceof rt?new h:new c("Failed to read response.")}};var C=r=>l(r)&&r.type==="heartbeat";var O=r=>{if(!l(r)||r.type!=="item")return!1;let{payload:t}=r;return l(t)&&l(t.event)&&typeof t.hash=="string"};var g=r=>{if(!l(r)||r.type!=="error")return!1;let{payload:t}=r;return l(t)&&typeof t.error=="string"};var nt=/^\d+$/u,j=r=>nt.test(r);var U=r=>{if(r.lowerBoundId!==void 0&&!j(r.lowerBoundId))throw new a("ObserveEventsOptions are invalid: lowerBoundId must be 0 or greater.");if(r.lowerBoundId!==void 0&&r.fromLatestEvent!==void 0)throw new a("ObserveEventsOptions are invalid: lowerBoundId and fromLatestEvent are mutually exclusive.");let{fromLatestEvent:t}=r;t!==void 0&&m(()=>{v(t.subject),y(t.type)},e=>{throw new a(`ObserveEventsOptions are invalid: Failed to validate 'fromLatestEvent': ${e.message}`)})};var V=async function*(r,t,e,i){await m(()=>v(e),s=>{if(s instanceof a)throw new u("subject",s.message)}),await m(()=>{U(i)},s=>{if(s instanceof a)throw new u("options",s.message)});let n=m(()=>JSON.stringify({subject:e,options:i}),()=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),p=await m(async()=>r.httpClient.post({path:"/api/observe-events",requestBody:n,responseType:"stream",abortController:t}),s=>{throw s instanceof d?s:new f(s)});if(p.status!==st.OK)throw new c(`Unexpected response status: ${p.status} ${it(p.status)}.`);let o=p.data;for await(let s of w(o))if(!C(s)){if(g(s))throw new c(`${s.payload.error}.`);if(O(s)){yield{event:E.parse(s.payload.event),hash:s.payload.hash};continue}throw new c(`Failed to observe events, an unexpected stream item was received: '${JSON.stringify(s)}'.`)}};var L=async r=>{if((await m(async()=>r.httpClient.get({path:"/api/ping",responseType:"text",withAuthorization:!1}),e=>{if(e instanceof d)throw e;new f(e)})).data!=="OK")throw new c("Received unexpected response.")};import{StatusCodes as at}from"http-status-codes";var J=r=>!(!l(r)||r.type!=="eventType");var q=async function*(r,t){let e=await m(async()=>r.httpClient.post({path:"/api/read-event-types",requestBody:"",responseType:"stream",abortController:t}),n=>{throw n instanceof d?n:new f(n)});if(e.status!==at.OK)throw new c(`Unexpected response status: ${e.status} ${e.statusText}.`);let i=e.data;for await(let n of w(i))if(!C(n)){if(g(n))throw new c(`${n.payload.error}.`);if(J(n)){yield n.payload;continue}throw new c(`Failed to read events, an unexpected stream item was received: '${JSON.stringify(n)}'.`)}};import{StatusCodes as pt}from"http-status-codes";var k=r=>{if(r.lowerBoundId!==void 0&&!j(r.lowerBoundId))throw new a("ReadEventsOptions are invalid: lowerBoundId must be 0 or greater.");if(r.upperBoundId!==void 0&&!j(r.upperBoundId))throw new a("ReadEventsOptions are invalid: upperBoundId must be 0 or greater.");if(r.fromLatestEvent!==void 0){if(r.lowerBoundId!==void 0)throw new a("ReadEventsOptions are invalid: lowerBoundId and fromLatestEvent are mutually exclusive.");let{fromLatestEvent:t}=r;m(()=>{v(t.subject),y(t.type)},e=>{throw new a(`ReadEventsOptions are invalid: Failed to validate 'fromLatestEvent': ${e.message}`)})}};var H=async function*(r,t,e,i){m(()=>v(e),s=>{if(s instanceof a)throw new u("subject",s.message)}),m(()=>{k(i)},s=>{if(s instanceof a)throw new u("options",s.message)});let n=m(()=>JSON.stringify({subject:e,options:i}),()=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),p=await m(async()=>r.httpClient.post({path:"/api/read-events",requestBody:n,responseType:"stream",abortController:t}),s=>{throw s instanceof d?s:new f(s)});if(p.status!==pt.OK)throw new c(`Unexpected response status: ${p.status} ${p.statusText}.`);let o=p.data;for await(let s of w(o))if(!C(s)){if(g(s))throw new c(`${s.payload.error}.`);if(O(s)){yield{event:E.parse(s.payload.event),hash:s.payload.hash};continue}throw new c(`Failed to read events, an unexpected stream item was received: '${JSON.stringify(s)}'.`)}};import{StatusCodes as ct,getReasonPhrase as dt}from"http-status-codes";var z=r=>{v(r.baseSubject)};var G=r=>{if(!l(r)||r.type!=="subject")return!1;let{payload:t}=r;return l(t)&&typeof t.subject=="string"};var M=async function*(r,t,e){await m(()=>{z(e)},o=>{if(o instanceof a)throw new u("options",o.message)});let i=m(()=>JSON.stringify(e),o=>{throw new u("options","Parameter contains values that cannot be marshaled.")}),n=await m(async()=>r.httpClient.post({path:"/api/read-subjects",requestBody:i,responseType:"stream",abortController:t}),o=>{throw o instanceof d?o:new f(o)});if(n.status!==ct.OK)throw new c(`Unexpected response status: ${n.status} ${dt(n.status)}.`);let p=n.data;for await(let o of w(p)){if(g(o))throw new c(o.payload.error);if(G(o)){yield o.payload.subject;continue}throw new c(`Failed to read subjects, an unexpected stream item was received: '${JSON.stringify(o)}'.`)}};import{StatusCodes as mt}from"http-status-codes";var K=async(r,t,e)=>{m(()=>y(t),o=>{if(o instanceof a)throw new u("eventType",o.message)});let i=e;typeof e=="object"&&(i=JSON.stringify(e));let n=JSON.stringify({eventType:t,schema:i}),p=await m(async()=>r.httpClient.post({path:"/api/register-event-schema",requestBody:n,responseType:"text"}),o=>{throw o instanceof d?o:new f(o)});if(p.status!==mt.OK)throw new c(`Unexpected response status: ${p.status} ${p.statusText}: ${p.data}.`)};import{StatusCodes as ft}from"http-status-codes";var Z=async(r,t,e)=>{if(t.length===0)throw new u("eventCandidates","eventCandidates must contain at least one EventCandidate.");for(let o of t)m(()=>{o.validate()},s=>{if(s instanceof a)throw new u("eventCandidates",s.message)});let i=JSON.stringify({events:t,preconditions:e}),n=await m(async()=>r.httpClient.post({path:"/api/write-events",requestBody:i,responseType:"json"}),o=>{throw o instanceof d?o:new f(o)});if(n.status!==ft.OK)throw new c(`Unexpected response status: ${n.status} ${n.statusText}.`);if(!Array.isArray(n.data))throw new c(`Failed to parse response '${n.data}' to array.`);let p=n.data;return m(()=>p.map(o=>b.parse(o)),o=>{throw o instanceof a?new c(o.message):new f(o)})};import{AxiosError as X,CanceledError as Y}from"axios";import _ from"axios";import{StatusCodes as ut}from"http-status-codes";var S=class extends d{constructor(t){super(`Client error occurred: ${t}`)}};var I=class r{databaseClient;constructor(t){this.databaseClient=t}getDefaultRequestConfig(t=!0){let e={baseURL:this.databaseClient.configuration.baseUrl,timeout:this.databaseClient.configuration.timeoutMilliseconds,headers:{"X-EventSourcingDB-Protocol-Version":this.databaseClient.configuration.protocolVersion},validateStatus:()=>!0};return t&&this.databaseClient.configuration.accessToken!==void 0&&(e=r.setAuthorization(e,this.databaseClient.configuration.accessToken)),e}static setContentType(t,e){return{...t,headers:{...t.headers,"Content-Type":e}}}static setAuthorization(t,e){return{...t,headers:{...t.headers,authorization:`Bearer ${e}`}}}static setResponseType(t,e){return{...t,responseType:e}}validateProtocolVersion(t,e){if(t!==ut.UNPROCESSABLE_ENTITY)return;let i=e["x-eventsourcingdb-protocol-version"];throw i===void 0&&(i="unknown version"),new S(`Protocol version mismatch, server '${i}', client '${this.databaseClient.configuration.protocolVersion}.'`)}async post(t){let e=this.getDefaultRequestConfig();e=r.setContentType(e,"application/json"),e=r.setResponseType(e,t.responseType);let i=_.create(e),p=(t.abortController??new AbortController).signal;try{let o=await i.post(t.path,t.requestBody,{signal:p});if(o.status>=500&&o.status<600)throw new c(`Request failed with status code '${o.status}'.`);if(this.validateProtocolVersion(o.status,o.headers),o.status>=400&&o.status<500)throw new S(`Request failed with status code '${o.status}'.`);return o}catch(o){throw o instanceof d?o:o instanceof Y?new h:o instanceof X?o.request!==void 0?new c("No response received."):new f("Failed to setup request."):new f(o)}}async get(t){let e=this.getDefaultRequestConfig(t.withAuthorization);e=r.setResponseType(e,t.responseType);let i=_.create(e),p=(t.abortController??new AbortController).signal;try{let o=await i.get(t.path,{signal:p});if(o.status>=500&&o.status<600)throw new c(`Request failed with status code '${o.status}'.`);if(this.validateProtocolVersion(o.status,o.headers),o.status>=400&&o.status<500)throw new S(`Request failed with status code '${o.status}'.`);return this.validateProtocolVersion(o.status,o.headers),o}catch(o){throw o instanceof d?o:o instanceof Y?new h:o instanceof X?o.request!==void 0?new c("No response received."):new f("Failed to setup request."):new f(o)}}};var A=class{configuration;httpClient;constructor(t,e){this.configuration={...F(t),...e},this.httpClient=new I(this)}observeEvents(t,e,i){return V(this,t,e,i)}async ping(){await L(this)}readEvents(t,e,i){return H(this,t,e,i)}readEventTypes(t){return q(this,t)}readSubjects(t,e){return M(this,t,e)}async registerEventSchema(t,e){return await K(this,t,e)}async writeEvents(t,e=[]){return await Z(this,t,e)}};var R=class{data;source;subject;type;traceParent;traceState;constructor(t,e,i,n,p,o){this.data=n,this.source=t,this.subject=e,this.type=i,this.traceParent=p,this.traceState=o}validate(){if(v(this.subject),y(this.type),this.traceState!==void 0&&this.traceParent===void 0)throw new a("Failed to validate trace state: trace parent must be set if trace state is set.")}toJSON(){return{data:this.data,source:this.source,subject:this.subject,type:this.type,traceparent:this.traceParent,tracestate:this.traceState}}};var B=class{source;constructor(t){this.source=t}newEvent(t,e,i,n,p){return new R(this.source,t,e,i,n,p)}};var lt=r=>({type:"isSubjectPristine",payload:r}),vt=r=>({type:"isSubjectOnEventId",payload:r});export{h as CancelationError,A as Client,E as Event,R as EventCandidate,B as Source,vt as isSubjectOnEventId,lt as isSubjectPristine};
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};
package/package.json CHANGED
@@ -1,13 +1,11 @@
1
1
  {
2
2
  "name": "eventsourcingdb",
3
- "version": "0.9.1",
4
- "description": "eventsourcingdb is the official client for EventSourcingDB.",
5
- "contributors": [
6
- {
7
- "name": "the native web GmbH",
8
- "email": "hello@thenativeweb.io"
9
- }
10
- ],
3
+ "version": "0.10.0",
4
+ "description": "The official JavaScript client SDK for EventSourcingDB.",
5
+ "author": {
6
+ "name": "the native web GmbH",
7
+ "email": "hello@thenativeweb.io"
8
+ },
11
9
  "exports": {
12
10
  ".": {
13
11
  "import": "./dist/index.mjs",
@@ -15,34 +13,35 @@
15
13
  }
16
14
  },
17
15
  "types": "./dist/index.d.ts",
18
- "dependencies": {
19
- "axios": "1.8.4",
20
- "http-status-codes": "2.3.0",
21
- "stream-to-async-iterator": "1.0.0"
22
- },
23
16
  "devDependencies": {
24
17
  "@biomejs/biome": "1.9.4",
25
- "@types/express": "5.0.1",
26
18
  "@types/node": "22.14.0",
27
- "@types/shelljs": "0.8.15",
28
- "express": "5.1.0",
29
- "shelljs": "0.9.2",
19
+ "get-port": "7.1.0",
30
20
  "tsup": "8.4.0",
31
21
  "tsx": "4.19.3",
32
- "typescript": "5.8.2"
22
+ "typescript": "5.8.3"
33
23
  },
34
24
  "scripts": {
35
- "analyze": "npx biome check .",
25
+ "analyze": "npx biome check --error-on-warnings .",
36
26
  "build": "npx tsc --noEmit && npx tsup --clean --dts --format cjs,esm --minify --out-dir=./dist/ ./src/index.ts",
37
27
  "format": "npx biome format --write .",
38
28
  "qa": "npm run analyze && npm run test",
39
29
  "test": "npm run test:unit && npm run test:integration",
40
- "test:unit": "node --test --import tsx \"./test/unit/**/*.ts\"",
41
- "test:integration": "node --test --import tsx \"./test/integration/**/*.ts\""
30
+ "test:unit": "node --test --import tsx \"./src/**/*.test.ts\"",
31
+ "test:integration": "node --test --import tsx \"./test/**/*.test.ts\""
42
32
  },
43
33
  "repository": {
44
34
  "type": "git",
45
35
  "url": "git://github.com/thenativeweb/eventsourcingdb-client-javascript.git"
46
36
  },
47
- "license": "MIT"
37
+ "license": "MIT",
38
+ "keywords": [
39
+ "eventsourcingdb",
40
+ "esdb",
41
+ "event",
42
+ "events",
43
+ "event sourcing",
44
+ "event store",
45
+ "cqrs"
46
+ ]
48
47
  }