@flowcore/pathways 0.7.0 → 0.9.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +95 -0
  3. package/esm/pathways/builder.d.ts +45 -6
  4. package/esm/pathways/builder.d.ts.map +1 -1
  5. package/esm/pathways/builder.js +106 -43
  6. package/esm/pathways/index.d.ts +2 -0
  7. package/esm/pathways/index.d.ts.map +1 -1
  8. package/esm/pathways/index.js +2 -0
  9. package/esm/pathways/kv/kv-adapter.d.ts +59 -2
  10. package/esm/pathways/kv/kv-adapter.d.ts.map +1 -1
  11. package/esm/pathways/kv/kv-adapter.js +31 -1
  12. package/esm/pathways/postgres/postgres-pathway-state.d.ts +131 -1
  13. package/esm/pathways/postgres/postgres-pathway-state.d.ts.map +1 -1
  14. package/esm/pathways/postgres/postgres-pathway-state.js +131 -1
  15. package/esm/pathways/session-pathway.d.ts +99 -0
  16. package/esm/pathways/session-pathway.d.ts.map +1 -0
  17. package/esm/pathways/session-pathway.js +138 -0
  18. package/esm/pathways/types.d.ts +5 -0
  19. package/esm/pathways/types.d.ts.map +1 -1
  20. package/esm/router/index.d.ts +83 -2
  21. package/esm/router/index.d.ts.map +1 -1
  22. package/esm/router/index.js +83 -2
  23. package/package.json +1 -1
  24. package/script/pathways/builder.d.ts +45 -6
  25. package/script/pathways/builder.d.ts.map +1 -1
  26. package/script/pathways/builder.js +106 -43
  27. package/script/pathways/index.d.ts +2 -0
  28. package/script/pathways/index.d.ts.map +1 -1
  29. package/script/pathways/index.js +2 -0
  30. package/script/pathways/kv/kv-adapter.d.ts +59 -2
  31. package/script/pathways/kv/kv-adapter.d.ts.map +1 -1
  32. package/script/pathways/kv/kv-adapter.js +31 -1
  33. package/script/pathways/postgres/postgres-pathway-state.d.ts +131 -1
  34. package/script/pathways/postgres/postgres-pathway-state.d.ts.map +1 -1
  35. package/script/pathways/postgres/postgres-pathway-state.js +131 -1
  36. package/script/pathways/session-pathway.d.ts +99 -0
  37. package/script/pathways/session-pathway.d.ts.map +1 -0
  38. package/script/pathways/session-pathway.js +142 -0
  39. package/script/pathways/types.d.ts +5 -0
  40. package/script/pathways/types.d.ts.map +1 -1
  41. package/script/router/index.d.ts +83 -2
  42. package/script/router/index.d.ts.map +1 -1
  43. package/script/router/index.js +83 -2
@@ -53,6 +53,47 @@ export type PostgresPathwayStateConfig = PostgresPathwayStateConnectionStringCon
53
53
  *
54
54
  * This class provides persistent storage of pathway state using a PostgreSQL database,
55
55
  * which allows for state to be shared across multiple instances of the application.
56
+ *
57
+ * Key features:
58
+ * - Persistent storage of pathway processing state across application restarts
59
+ * - Automatic table and index creation
60
+ * - Configurable TTL (time-to-live) for processed events
61
+ * - Automatic cleanup of expired records
62
+ * - Support for horizontal scaling across multiple instances
63
+ * - Connection pooling for efficient database usage
64
+ *
65
+ * Use cases:
66
+ * - Production deployments that require durability and persistence
67
+ * - Distributed systems where multiple instances process events
68
+ * - Applications with high reliability requirements
69
+ * - Scenarios where in-memory state is insufficient
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * // Create PostgreSQL pathway state with connection string
74
+ * const postgresState = createPostgresPathwayState({
75
+ * connectionString: "postgres://user:password@localhost:5432/mydb",
76
+ * tableName: "event_processing_state", // Optional
77
+ * ttlMs: 24 * 60 * 60 * 1000 // 24 hours (optional)
78
+ * });
79
+ *
80
+ * // Or with individual parameters
81
+ * const postgresState = createPostgresPathwayState({
82
+ * host: "localhost",
83
+ * port: 5432,
84
+ * user: "postgres",
85
+ * password: "postgres",
86
+ * database: "mydb",
87
+ * ssl: false,
88
+ * tableName: "event_processing_state", // Optional
89
+ * ttlMs: 30 * 60 * 1000 // 30 minutes (optional)
90
+ * });
91
+ *
92
+ * // Use with PathwaysBuilder
93
+ * const pathways = new PathwaysBuilder({
94
+ * // ... other config
95
+ * }).withPathwayState(postgresState);
96
+ * ```
56
97
  */
57
98
  export declare class PostgresPathwayState implements PathwayState {
58
99
  private config;
@@ -102,15 +143,66 @@ export declare class PostgresPathwayState implements PathwayState {
102
143
  /**
103
144
  * Checks if an event has already been processed
104
145
  *
146
+ * This method checks the PostgreSQL database to determine if an event with the given ID
147
+ * has been marked as processed. If the event exists in the database and is marked as processed,
148
+ * the method returns true.
149
+ *
150
+ * Before performing the check, this method also triggers cleanup of expired event records
151
+ * to maintain database performance.
152
+ *
105
153
  * @param {string} eventId - The ID of the event to check
106
154
  * @returns {Promise<boolean>} True if the event has been processed, false otherwise
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * // Check if an event has been processed
159
+ * const processed = await postgresState.isProcessed("event-123");
160
+ * if (processed) {
161
+ * console.log("Event has already been processed, skipping");
162
+ * } else {
163
+ * console.log("Processing event for the first time");
164
+ * // Process the event
165
+ * await processEvent(event);
166
+ * // Mark as processed
167
+ * await postgresState.setProcessed("event-123");
168
+ * }
169
+ * ```
107
170
  */
108
171
  isProcessed(eventId: string): Promise<boolean>;
109
172
  /**
110
173
  * Marks an event as processed
111
174
  *
175
+ * This method inserts or updates a record in the PostgreSQL database to mark an event
176
+ * as processed. If the event already exists in the database, the record is updated;
177
+ * otherwise, a new record is created.
178
+ *
179
+ * Each processed event is stored with an expiration timestamp based on the configured TTL.
180
+ * After this time elapses, the record may be automatically removed during cleanup operations.
181
+ *
112
182
  * @param {string} eventId - The ID of the event to mark as processed
113
183
  * @returns {Promise<void>}
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * // Process an event and mark it as processed
188
+ * async function handleEvent(event) {
189
+ * // Check if already processed to implement idempotency
190
+ * if (await postgresState.isProcessed(event.id)) {
191
+ * return; // Skip already processed events
192
+ * }
193
+ *
194
+ * try {
195
+ * // Process the event
196
+ * await processEvent(event);
197
+ *
198
+ * // Mark as processed after successful processing
199
+ * await postgresState.setProcessed(event.id);
200
+ * } catch (error) {
201
+ * console.error("Failed to process event:", error);
202
+ * // Not marking as processed, so it can be retried
203
+ * }
204
+ * }
205
+ * ```
114
206
  */
115
207
  setProcessed(eventId: string): Promise<void>;
116
208
  /**
@@ -130,8 +222,46 @@ export declare class PostgresPathwayState implements PathwayState {
130
222
  /**
131
223
  * Creates a new PostgreSQL pathway state instance
132
224
  *
133
- * @param config The PostgreSQL configuration
225
+ * This is a factory function that simplifies the creation of PostgresPathwayState instances.
226
+ * It accepts either a connection string or individual connection parameters, along with
227
+ * optional configuration for table name and TTL.
228
+ *
229
+ * The PostgresPathwayState is lazily initialized, meaning the database connection and
230
+ * table creation only happen when the first operation is performed. This makes it safe
231
+ * to create instances early in the application lifecycle.
232
+ *
233
+ * @param config The PostgreSQL configuration (connection string or parameters)
134
234
  * @returns A new PostgresPathwayState instance
235
+ *
236
+ * @example
237
+ * ```typescript
238
+ * // With connection string
239
+ * const state = createPostgresPathwayState({
240
+ * connectionString: "postgres://user:pass@localhost:5432/db?sslmode=require"
241
+ * });
242
+ *
243
+ * // With individual parameters
244
+ * const state = createPostgresPathwayState({
245
+ * host: "localhost",
246
+ * port: 5432,
247
+ * user: "postgres",
248
+ * password: "secret",
249
+ * database: "events_db",
250
+ * ssl: true
251
+ * });
252
+ *
253
+ * // With custom table name and TTL
254
+ * const state = createPostgresPathwayState({
255
+ * connectionString: "postgres://user:pass@localhost:5432/db",
256
+ * tableName: "my_custom_event_state",
257
+ * ttlMs: 7 * 24 * 60 * 60 * 1000 // 1 week
258
+ * });
259
+ *
260
+ * // Use with PathwaysBuilder
261
+ * const pathways = new PathwaysBuilder({
262
+ * // Other config
263
+ * }).withPathwayState(state);
264
+ * ```
135
265
  */
136
266
  export declare function createPostgresPathwayState(config: PostgresPathwayStateConfig): PostgresPathwayState;
137
267
  //# sourceMappingURL=postgres-pathway-state.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-pathway-state.d.ts","sourceRoot":"","sources":["../../../src/pathways/postgres/postgres-pathway-state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAIhD;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AQ,CAAkB;IAElC;;;OAGG;IACH,OAAO,CAAC,SAAS,CAAS;IAE1B;;;OAGG;IACH,OAAO,CAAC,KAAK,CAAS;IAEtB;;;OAGG;IACH,OAAO,CAAC,WAAW,CAAS;IAE5B;;;;OAIG;gBACiB,MAAM,EAAE,0BAA0B;IAMtD;;;;;OAKG;YACW,UAAU;IA0CxB;;;;;OAKG;IACG,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAcpD;;;;;OAKG;IACG,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAelD;;;;;OAKG;YACW,cAAc;IAQ5B;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAK7B;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,0BAA0B,GAAG,oBAAoB,CAGnG"}
1
+ {"version":3,"file":"postgres-pathway-state.d.ts","sourceRoot":"","sources":["../../../src/pathways/postgres/postgres-pathway-state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAIhD;;GAEG;AACH,MAAM,WAAW,0CAA0C;IACzD,gHAAgH;IAChH,gBAAgB,EAAE,MAAM,CAAC;IAEzB,yEAAyE;IACzE,IAAI,CAAC,EAAE,KAAK,CAAC;IACb,IAAI,CAAC,EAAE,KAAK,CAAC;IACb,IAAI,CAAC,EAAE,KAAK,CAAC;IACb,QAAQ,CAAC,EAAE,KAAK,CAAC;IACjB,QAAQ,CAAC,EAAE,KAAK,CAAC;IACjB,GAAG,CAAC,EAAE,KAAK,CAAC;IAEZ,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,oCAAoC;IACnD,uDAAuD;IACvD,gBAAgB,CAAC,EAAE,KAAK,CAA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;;OAKG;YACW,cAAc;IAQ5B;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAK7B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,0BAA0B,GAAG,oBAAoB,CAGnG"}
@@ -4,6 +4,47 @@ import { createPostgresAdapter } from "./postgres-adapter.js";
4
4
  *
5
5
  * This class provides persistent storage of pathway state using a PostgreSQL database,
6
6
  * which allows for state to be shared across multiple instances of the application.
7
+ *
8
+ * Key features:
9
+ * - Persistent storage of pathway processing state across application restarts
10
+ * - Automatic table and index creation
11
+ * - Configurable TTL (time-to-live) for processed events
12
+ * - Automatic cleanup of expired records
13
+ * - Support for horizontal scaling across multiple instances
14
+ * - Connection pooling for efficient database usage
15
+ *
16
+ * Use cases:
17
+ * - Production deployments that require durability and persistence
18
+ * - Distributed systems where multiple instances process events
19
+ * - Applications with high reliability requirements
20
+ * - Scenarios where in-memory state is insufficient
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * // Create PostgreSQL pathway state with connection string
25
+ * const postgresState = createPostgresPathwayState({
26
+ * connectionString: "postgres://user:password@localhost:5432/mydb",
27
+ * tableName: "event_processing_state", // Optional
28
+ * ttlMs: 24 * 60 * 60 * 1000 // 24 hours (optional)
29
+ * });
30
+ *
31
+ * // Or with individual parameters
32
+ * const postgresState = createPostgresPathwayState({
33
+ * host: "localhost",
34
+ * port: 5432,
35
+ * user: "postgres",
36
+ * password: "postgres",
37
+ * database: "mydb",
38
+ * ssl: false,
39
+ * tableName: "event_processing_state", // Optional
40
+ * ttlMs: 30 * 60 * 1000 // 30 minutes (optional)
41
+ * });
42
+ *
43
+ * // Use with PathwaysBuilder
44
+ * const pathways = new PathwaysBuilder({
45
+ * // ... other config
46
+ * }).withPathwayState(postgresState);
47
+ * ```
7
48
  */
8
49
  export class PostgresPathwayState {
9
50
  /**
@@ -109,8 +150,30 @@ export class PostgresPathwayState {
109
150
  /**
110
151
  * Checks if an event has already been processed
111
152
  *
153
+ * This method checks the PostgreSQL database to determine if an event with the given ID
154
+ * has been marked as processed. If the event exists in the database and is marked as processed,
155
+ * the method returns true.
156
+ *
157
+ * Before performing the check, this method also triggers cleanup of expired event records
158
+ * to maintain database performance.
159
+ *
112
160
  * @param {string} eventId - The ID of the event to check
113
161
  * @returns {Promise<boolean>} True if the event has been processed, false otherwise
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * // Check if an event has been processed
166
+ * const processed = await postgresState.isProcessed("event-123");
167
+ * if (processed) {
168
+ * console.log("Event has already been processed, skipping");
169
+ * } else {
170
+ * console.log("Processing event for the first time");
171
+ * // Process the event
172
+ * await processEvent(event);
173
+ * // Mark as processed
174
+ * await postgresState.setProcessed("event-123");
175
+ * }
176
+ * ```
114
177
  */
115
178
  async isProcessed(eventId) {
116
179
  await this.initialize();
@@ -125,8 +188,37 @@ export class PostgresPathwayState {
125
188
  /**
126
189
  * Marks an event as processed
127
190
  *
191
+ * This method inserts or updates a record in the PostgreSQL database to mark an event
192
+ * as processed. If the event already exists in the database, the record is updated;
193
+ * otherwise, a new record is created.
194
+ *
195
+ * Each processed event is stored with an expiration timestamp based on the configured TTL.
196
+ * After this time elapses, the record may be automatically removed during cleanup operations.
197
+ *
128
198
  * @param {string} eventId - The ID of the event to mark as processed
129
199
  * @returns {Promise<void>}
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * // Process an event and mark it as processed
204
+ * async function handleEvent(event) {
205
+ * // Check if already processed to implement idempotency
206
+ * if (await postgresState.isProcessed(event.id)) {
207
+ * return; // Skip already processed events
208
+ * }
209
+ *
210
+ * try {
211
+ * // Process the event
212
+ * await processEvent(event);
213
+ *
214
+ * // Mark as processed after successful processing
215
+ * await postgresState.setProcessed(event.id);
216
+ * } catch (error) {
217
+ * console.error("Failed to process event:", error);
218
+ * // Not marking as processed, so it can be retried
219
+ * }
220
+ * }
221
+ * ```
130
222
  */
131
223
  async setProcessed(eventId) {
132
224
  await this.initialize();
@@ -188,8 +280,46 @@ Object.defineProperty(PostgresPathwayState, "DEFAULT_TABLE_NAME", {
188
280
  /**
189
281
  * Creates a new PostgreSQL pathway state instance
190
282
  *
191
- * @param config The PostgreSQL configuration
283
+ * This is a factory function that simplifies the creation of PostgresPathwayState instances.
284
+ * It accepts either a connection string or individual connection parameters, along with
285
+ * optional configuration for table name and TTL.
286
+ *
287
+ * The PostgresPathwayState is lazily initialized, meaning the database connection and
288
+ * table creation only happen when the first operation is performed. This makes it safe
289
+ * to create instances early in the application lifecycle.
290
+ *
291
+ * @param config The PostgreSQL configuration (connection string or parameters)
192
292
  * @returns A new PostgresPathwayState instance
293
+ *
294
+ * @example
295
+ * ```typescript
296
+ * // With connection string
297
+ * const state = createPostgresPathwayState({
298
+ * connectionString: "postgres://user:pass@localhost:5432/db?sslmode=require"
299
+ * });
300
+ *
301
+ * // With individual parameters
302
+ * const state = createPostgresPathwayState({
303
+ * host: "localhost",
304
+ * port: 5432,
305
+ * user: "postgres",
306
+ * password: "secret",
307
+ * database: "events_db",
308
+ * ssl: true
309
+ * });
310
+ *
311
+ * // With custom table name and TTL
312
+ * const state = createPostgresPathwayState({
313
+ * connectionString: "postgres://user:pass@localhost:5432/db",
314
+ * tableName: "my_custom_event_state",
315
+ * ttlMs: 7 * 24 * 60 * 60 * 1000 // 1 week
316
+ * });
317
+ *
318
+ * // Use with PathwaysBuilder
319
+ * const pathways = new PathwaysBuilder({
320
+ * // Other config
321
+ * }).withPathwayState(state);
322
+ * ```
193
323
  */
194
324
  export function createPostgresPathwayState(config) {
195
325
  const state = new PostgresPathwayState(config);
@@ -0,0 +1,99 @@
1
+ import type { PathwaysBuilder, UserIdResolver } from "./builder.js";
2
+ import type { EventMetadata, PathwayWriteOptions } from "./types.js";
3
+ /**
4
+ * SessionPathwayBuilder wraps a PathwaysBuilder instance and automatically
5
+ * associates a session ID with all pathway writes.
6
+ *
7
+ * This provides a convenient way to track operations within a user session
8
+ * by automatically including the session ID in metadata.
9
+ *
10
+ * Key features:
11
+ * - Automatic session ID generation if none is provided
12
+ * - Cross-platform UUID generation (works in Deno, Bun, and Node.js)
13
+ * - Simple API for accessing the current session ID
14
+ * - Convenient integration with session-specific user resolvers
15
+ * - Automatic inclusion of session ID in all write operations
16
+ * - Support for overriding the session ID on specific writes
17
+ *
18
+ * Use cases:
19
+ * - Tracking user actions across multiple pathway writes
20
+ * - Connecting related events in a single user session
21
+ * - Supporting multi-user environments where different users' operations need to be tracked separately
22
+ * - Building user activity logs with session grouping
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * // Create a session pathway with auto-generated ID
27
+ * const session = new SessionPathwayBuilder(pathwaysBuilder);
28
+ *
29
+ * // Get the auto-generated session ID
30
+ * const sessionId = session.getSessionId();
31
+ *
32
+ * // Register a user resolver for this session
33
+ * session.withUserResolver(async () => getCurrentUserId());
34
+ *
35
+ * // Write events with session context
36
+ * await session.write("order/placed", orderData);
37
+ * await session.write("user/action", actionData);
38
+ *
39
+ * // All events will be associated with the same session ID
40
+ * ```
41
+ */
42
+ export declare class SessionPathwayBuilder<TPathway extends Record<string, unknown> = {}, TWritablePaths extends keyof TPathway = never> {
43
+ private readonly pathwaysBuilder;
44
+ private readonly sessionId;
45
+ /**
46
+ * Creates a new SessionPathwayBuilder
47
+ *
48
+ * @param pathwaysBuilder The configured PathwaysBuilder instance to wrap
49
+ * @param sessionId Optional session ID to associate with all operations. If not provided, one will be generated automatically.
50
+ */
51
+ constructor(pathwaysBuilder: PathwaysBuilder<TPathway, TWritablePaths>, sessionId?: string);
52
+ /**
53
+ * Gets the current session ID
54
+ *
55
+ * @returns The session ID associated with this instance
56
+ */
57
+ getSessionId(): string;
58
+ /**
59
+ * Registers a user resolver for this session
60
+ *
61
+ * This is a convenience method that calls `pathwaysBuilder.withSessionUserResolver`
62
+ * with the current session ID, allowing you to set up a resolver specific to this session
63
+ * without having to manually pass the session ID.
64
+ *
65
+ * The resolver will be called whenever events are written through this session,
66
+ * and the resolved user ID will be included in the event metadata.
67
+ *
68
+ * @param resolver The function that resolves to the user ID for this session
69
+ * @returns The SessionPathwayBuilder instance for chaining
70
+ *
71
+ * @throws Error if the underlying PathwaysBuilder does not have session user resolvers configured
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * const session = new SessionPathwayBuilder(pathwaysBuilder);
76
+ *
77
+ * // Register a user resolver for this session
78
+ * session.withUserResolver(async () => {
79
+ * // Get the user ID associated with this session
80
+ * return getUserIdFromSession();
81
+ * });
82
+ *
83
+ * // When writing events, the user ID will be automatically included
84
+ * await session.write("user/action", actionData);
85
+ * ```
86
+ */
87
+ withUserResolver(resolver: UserIdResolver): this;
88
+ /**
89
+ * Writes data to a pathway, proxying to the underlying PathwaysBuilder
90
+ *
91
+ * @param path The pathway to write to
92
+ * @param data The data to write
93
+ * @param metadata Optional metadata to include with the event
94
+ * @param options Optional write options
95
+ * @returns A promise that resolves to the event ID(s)
96
+ */
97
+ write<TPath extends TWritablePaths>(path: TPath, data: TPathway[TPath], metadata?: EventMetadata, options?: PathwayWriteOptions): Promise<string | string[]>;
98
+ }
99
+ //# sourceMappingURL=session-pathway.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-pathway.d.ts","sourceRoot":"","sources":["../../src/pathways/session-pathway.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAqBrE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,qBAAa,qBAAqB,CAEhC,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,EAAE,EAC7C,cAAc,SAAS,MAAM,QAAQ,GAAG,KAAK;IAE7C,OAAO,CAAC,QAAQ,CAAC,eAAe,CAA4C;IAC5E,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IAEnC;;;;;OAKG;gBAED,eAAe,EAAE,eAAe,CAAC,QAAQ,EAAE,cAAc,CAAC,EAC1D,SAAS,CAAC,EAAE,MAAM;IAMpB;;;;OAIG;IACH,YAAY,IAAI,MAAM;IAItB;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,gBAAgB,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI;IAKhD;;;;;;;;OAQG;IACG,KAAK,CAAC,KAAK,SAAS,cAAc,EACtC,IAAI,EAAE,KAAK,EACX,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,EACrB,QAAQ,CAAC,EAAE,aAAa,EACxB,OAAO,CAAC,EAAE,mBAAmB,GAC5B,OAAO,CAAC,MAAM,GAAG,MAAM,EAAE,CAAC;CAU9B"}
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Generates a UUID v4 in a cross-platform compatible way (Deno, Bun, Node.js)
3
+ * @returns A random UUID v4 string
4
+ */
5
+ function generateUUID() {
6
+ // Check for Deno or browser crypto.randomUUID support
7
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) {
8
+ return crypto.randomUUID();
9
+ }
10
+ // Fallback to manual UUID generation (compatible with all platforms)
11
+ // Implementation based on RFC4122 version 4
12
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
13
+ const r = Math.random() * 16 | 0;
14
+ const v = c === 'x' ? r : (r & 0x3 | 0x8);
15
+ return v.toString(16);
16
+ });
17
+ }
18
+ /**
19
+ * SessionPathwayBuilder wraps a PathwaysBuilder instance and automatically
20
+ * associates a session ID with all pathway writes.
21
+ *
22
+ * This provides a convenient way to track operations within a user session
23
+ * by automatically including the session ID in metadata.
24
+ *
25
+ * Key features:
26
+ * - Automatic session ID generation if none is provided
27
+ * - Cross-platform UUID generation (works in Deno, Bun, and Node.js)
28
+ * - Simple API for accessing the current session ID
29
+ * - Convenient integration with session-specific user resolvers
30
+ * - Automatic inclusion of session ID in all write operations
31
+ * - Support for overriding the session ID on specific writes
32
+ *
33
+ * Use cases:
34
+ * - Tracking user actions across multiple pathway writes
35
+ * - Connecting related events in a single user session
36
+ * - Supporting multi-user environments where different users' operations need to be tracked separately
37
+ * - Building user activity logs with session grouping
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * // Create a session pathway with auto-generated ID
42
+ * const session = new SessionPathwayBuilder(pathwaysBuilder);
43
+ *
44
+ * // Get the auto-generated session ID
45
+ * const sessionId = session.getSessionId();
46
+ *
47
+ * // Register a user resolver for this session
48
+ * session.withUserResolver(async () => getCurrentUserId());
49
+ *
50
+ * // Write events with session context
51
+ * await session.write("order/placed", orderData);
52
+ * await session.write("user/action", actionData);
53
+ *
54
+ * // All events will be associated with the same session ID
55
+ * ```
56
+ */
57
+ export class SessionPathwayBuilder {
58
+ /**
59
+ * Creates a new SessionPathwayBuilder
60
+ *
61
+ * @param pathwaysBuilder The configured PathwaysBuilder instance to wrap
62
+ * @param sessionId Optional session ID to associate with all operations. If not provided, one will be generated automatically.
63
+ */
64
+ constructor(pathwaysBuilder, sessionId) {
65
+ Object.defineProperty(this, "pathwaysBuilder", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: void 0
70
+ });
71
+ Object.defineProperty(this, "sessionId", {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: void 0
76
+ });
77
+ this.pathwaysBuilder = pathwaysBuilder;
78
+ this.sessionId = sessionId ?? generateUUID();
79
+ }
80
+ /**
81
+ * Gets the current session ID
82
+ *
83
+ * @returns The session ID associated with this instance
84
+ */
85
+ getSessionId() {
86
+ return this.sessionId;
87
+ }
88
+ /**
89
+ * Registers a user resolver for this session
90
+ *
91
+ * This is a convenience method that calls `pathwaysBuilder.withSessionUserResolver`
92
+ * with the current session ID, allowing you to set up a resolver specific to this session
93
+ * without having to manually pass the session ID.
94
+ *
95
+ * The resolver will be called whenever events are written through this session,
96
+ * and the resolved user ID will be included in the event metadata.
97
+ *
98
+ * @param resolver The function that resolves to the user ID for this session
99
+ * @returns The SessionPathwayBuilder instance for chaining
100
+ *
101
+ * @throws Error if the underlying PathwaysBuilder does not have session user resolvers configured
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const session = new SessionPathwayBuilder(pathwaysBuilder);
106
+ *
107
+ * // Register a user resolver for this session
108
+ * session.withUserResolver(async () => {
109
+ * // Get the user ID associated with this session
110
+ * return getUserIdFromSession();
111
+ * });
112
+ *
113
+ * // When writing events, the user ID will be automatically included
114
+ * await session.write("user/action", actionData);
115
+ * ```
116
+ */
117
+ withUserResolver(resolver) {
118
+ this.pathwaysBuilder.withSessionUserResolver(this.sessionId, resolver);
119
+ return this;
120
+ }
121
+ /**
122
+ * Writes data to a pathway, proxying to the underlying PathwaysBuilder
123
+ *
124
+ * @param path The pathway to write to
125
+ * @param data The data to write
126
+ * @param metadata Optional metadata to include with the event
127
+ * @param options Optional write options
128
+ * @returns A promise that resolves to the event ID(s)
129
+ */
130
+ async write(path, data, metadata, options) {
131
+ // Create new options object with session ID
132
+ const finalOptions = options ? { ...options } : {};
133
+ // Always include the session ID in the options
134
+ finalOptions.sessionId = options?.sessionId ?? this.sessionId;
135
+ // The PathwaysBuilder will handle session-specific user resolvers
136
+ return await this.pathwaysBuilder.write(path, data, metadata, finalOptions);
137
+ }
138
+ }
@@ -132,6 +132,11 @@ export type PathwayWriteOptions = WebhookSendOptions & {
132
132
  * @default "user"
133
133
  */
134
134
  auditMode?: "user" | "system";
135
+ /**
136
+ * Session ID for this write operation
137
+ * Used to associate the operation with a specific session
138
+ */
139
+ sessionId?: string;
135
140
  };
136
141
  export {};
137
142
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/pathways/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAA;AAChD,OAAO,KAAK,EAAE,eAAe,EAAE,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