@flatfile/listener 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,695 +1 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var fetch = require('cross-fetch');
6
- var pako = require('pako');
7
- var wildMatch = require('wildcard-match');
8
- var flat = require('flat');
9
-
10
- // src/index.ts
11
- var CrossEnvConfig = class {
12
- /**
13
- * Get a config value from either the environment or any registry overrides
14
- * @param prop
15
- */
16
- static get(prop) {
17
- return this.safeEnvLookup(prop);
18
- }
19
- /**
20
- * Set a value explicitly
21
- *
22
- * @param key
23
- * @param value
24
- */
25
- static set(key, value) {
26
- return this._overrides.set(key, value);
27
- }
28
- /**
29
- * Alias a key to another key if helpful. This is useful if you have different naming
30
- * constructs for different environments.
31
- *
32
- * @param from
33
- * @param to
34
- */
35
- static alias(from, to) {
36
- return this._aliases.set(from, to);
37
- }
38
- /**
39
- * Helpful if you've decided to store settings in another object and want to
40
- * make that available here. For example in client-side implementations you may reserve
41
- * a window.FLATFILE_CONFIG object to store settings.
42
- *
43
- * @param obj
44
- */
45
- static attachConfigRegistry(obj) {
46
- this._registry = obj;
47
- }
48
- /**
49
- * Use this to provide an override getter for config values. This is useful
50
- * if you need to dynamically look up values. Overrides will still take precedence.
51
- *
52
- * @param cb
53
- */
54
- static attachConfigFactory(cb) {
55
- this._factory = cb;
56
- }
57
- static reset() {
58
- this._overrides = /* @__PURE__ */ new Map();
59
- this._registry = void 0;
60
- this._factory = void 0;
61
- }
62
- /**
63
- * Internal function for traversing the possible environment sources for a value
64
- *
65
- * @param prop
66
- * @private
67
- */
68
- static safeEnvLookup(prop) {
69
- let values = [];
70
- if (this._overrides.get(prop)) {
71
- values.push(this._overrides.get(prop));
72
- }
73
- if (typeof this._registry === "object") {
74
- values.push(this._registry[prop]);
75
- }
76
- if (typeof this._factory === "function") {
77
- values.push(this._factory(prop));
78
- }
79
- if (typeof process === "object" && typeof process.env === "object") {
80
- values.push(process.env[prop]);
81
- }
82
- values.push(...this.checkForBrowserVariables(prop));
83
- const foundValue = values.find((v) => v !== void 0);
84
- if (foundValue !== void 0) {
85
- return foundValue;
86
- }
87
- const alias = this._aliases.get(prop);
88
- if (alias) {
89
- return this.safeEnvLookup(alias);
90
- }
91
- return void 0;
92
- }
93
- /**
94
- * Internal function for checking for stored variables in a browser-like environment
95
- *
96
- * @param prop
97
- * @private
98
- */
99
- static checkForBrowserVariables(prop) {
100
- let values = [];
101
- if (typeof window === "object") {
102
- const windowValue = window[`CROSSENV_${prop}`];
103
- if (windowValue !== void 0) {
104
- values.push(windowValue);
105
- }
106
- if (typeof sessionStorage === "object") {
107
- const storedValue = sessionStorage.getItem(`CROSSENV_${prop}`);
108
- if (storedValue !== null) {
109
- values.push(storedValue);
110
- }
111
- }
112
- }
113
- return values;
114
- }
115
- };
116
- CrossEnvConfig._overrides = /* @__PURE__ */ new Map();
117
- /**
118
- * A map of aliases that can be used to look up config values.
119
- *
120
- * @private
121
- */
122
- CrossEnvConfig._aliases = /* @__PURE__ */ new Map();
123
-
124
- const ensureSingleTrailingSlash = (url) => {
125
- // Remove all trailing slashes
126
- while (url.endsWith('/')) {
127
- url = url.slice(0, -1);
128
- }
129
- // Append one slash
130
- return url + '/';
131
- };
132
-
133
- class AuthenticatedClient {
134
- constructor(accessToken, apiUrl) {
135
- const FLATFILE_API_URL = CrossEnvConfig.get('AGENT_INTERNAL_URL') || 'http://localhost:3000';
136
- const bearerToken = CrossEnvConfig.get('FLATFILE_BEARER_TOKEN');
137
- this._accessToken = accessToken || bearerToken || '...';
138
- this._apiUrl =
139
- apiUrl || FLATFILE_API_URL
140
- ? ensureSingleTrailingSlash(apiUrl || FLATFILE_API_URL)
141
- : undefined;
142
- }
143
- async fetch(url, options) {
144
- const headers = {
145
- Authorization: `Bearer ${this._accessToken}`,
146
- 'x-disable-hooks': 'true',
147
- 'Content-Type': 'application/json',
148
- ...options?.headers,
149
- };
150
- const fetchUrl = this._apiUrl + url;
151
- const fetchOptions = {
152
- method: options?.method || 'GET',
153
- headers,
154
- body: options?.data,
155
- };
156
- try {
157
- const response = await fetch(fetchUrl, fetchOptions);
158
- if (response.status >= 200 && response.status <= 399) {
159
- const contentType = response.headers.get('content-type');
160
- if (contentType && contentType.includes('application/json')) {
161
- const responseData = (await response.json());
162
- return responseData.data;
163
- }
164
- else {
165
- const responseData = await response.text();
166
- return responseData;
167
- }
168
- }
169
- else {
170
- throw new Error(`HTTP error! Status: ${response.status}`);
171
- }
172
- }
173
- catch (err) {
174
- console.log('event.fetch error: ', err);
175
- }
176
- }
177
- /**
178
- *
179
- * @deprecated use @flatfile/cross-env-config instead
180
- */
181
- setVariables({ accessToken, apiUrl, }) {
182
- this._accessToken = accessToken;
183
- this._apiUrl = apiUrl;
184
- }
185
- }
186
-
187
- class EventCache {
188
- constructor() {
189
- this.eventCache = new Map();
190
- }
191
- async init(key, callback) {
192
- if (this.eventCache.get(key)) {
193
- return this.eventCache.get(key);
194
- }
195
- else {
196
- const result = await callback();
197
- this.eventCache.set(key, result);
198
- return result;
199
- }
200
- }
201
- async set(key, callback) {
202
- if (this.eventCache.get(key)) {
203
- const result = await callback();
204
- this.eventCache.set(key, result);
205
- return result;
206
- }
207
- else {
208
- throw new Error('Cache key not found');
209
- }
210
- }
211
- get(key) {
212
- if (this.eventCache.get(key)) {
213
- return this.eventCache.get(key);
214
- }
215
- else {
216
- throw new Error('Cache key not found');
217
- }
218
- }
219
- delete(key) {
220
- if (!key) {
221
- this.eventCache.clear();
222
- }
223
- else if (this.eventCache.get(key)) {
224
- if (Array.isArray(key)) {
225
- key.forEach((k) => this.eventCache.delete(k));
226
- }
227
- else {
228
- this.eventCache.delete(key);
229
- }
230
- }
231
- else {
232
- throw new Error('Cache key not found');
233
- }
234
- }
235
- }
236
-
237
- class FlatfileEvent extends AuthenticatedClient {
238
- constructor(src, accessToken, apiUrl) {
239
- super(accessToken, apiUrl);
240
- this.src = src;
241
- this.afterAllCallbacks = new Map();
242
- this.cache = new EventCache();
243
- this.domain = src.domain;
244
- this.topic = src.topic;
245
- this.context = src.context; // -> [us0_acc_ihjh8943h9w, space_id, workbook_id]
246
- this.payload = src.payload;
247
- this.target = src.target || '';
248
- this.origin = src.origin || {};
249
- this.action = src.context?.actionName || '';
250
- this.namespace = src.namespaces || [];
251
- this.createdAt = src.createdAt || undefined;
252
- const data = async (options) => this.fetchData(options);
253
- data.then = (onfulfilled, onrejected) => {
254
- return this.data().then(onfulfilled, onrejected);
255
- };
256
- this.data = data;
257
- }
258
- /**
259
- * Should return either event body if expanded already or fetch data from the
260
- * signed dataURL
261
- */
262
- async fetchData(options) {
263
- const dataUrl = new URLSearchParams(this.src.dataUrl);
264
- if (options) {
265
- for (const [key, values] of Object.entries(options)) {
266
- if (Array.isArray(values)) {
267
- for (const value of values) {
268
- dataUrl.append(key, value);
269
- }
270
- }
271
- else {
272
- dataUrl.append(key, values);
273
- }
274
- }
275
- }
276
- const decodedURL = decodeURIComponent(dataUrl.toString());
277
- if (decodedURL) {
278
- return this.fetch(decodedURL);
279
- }
280
- else {
281
- return this.payload;
282
- }
283
- }
284
- afterAll(callback, cacheKey) {
285
- const key = cacheKey || callback.toString();
286
- if (!this.afterAllCallbacks.get(key)) {
287
- this.afterAllCallbacks.set(key, callback);
288
- }
289
- }
290
- async update(records, compressRequestBody = true) {
291
- if (!this.src.dataUrl) {
292
- throw new Error('Cannot set data on an event without a dataUrl');
293
- }
294
- // TODO: do we need to remove source from the messages array?
295
- records.map((record) => {
296
- record.messages?.map((message) => {
297
- delete message.source;
298
- });
299
- });
300
- const data = compressRequestBody
301
- ? pako.gzip(JSON.stringify(records))
302
- : records;
303
- const headers = compressRequestBody
304
- ? { 'Content-Encoding': 'gzip', 'Content-Length': data.length.toString() }
305
- : {};
306
- await this.fetch(this.src.dataUrl, {
307
- method: 'PUT',
308
- headers: headers,
309
- data,
310
- });
311
- }
312
- /**
313
- * Fetch the Secrets as indicated by this event context
314
- *
315
- * @param key - The name of the secret to fetch
316
- * @param options - (Optional) environmentId and spaceId to override event context
317
- *
318
- * @returns The value of the secret (usually a credential or token)
319
- */
320
- async secrets(key, options) {
321
- // Allow options overrides, then take from context, else are absent
322
- const environmentId = options?.environmentId || this.context.environmentId || '';
323
- const spaceId = options?.spaceId || this.context.spaceId || '';
324
- if (!environmentId) {
325
- throw new Error('environmentId is required to fetch secrets');
326
- }
327
- let getSecrets = `v1/secrets?environmentId=${environmentId}`;
328
- if (spaceId) {
329
- getSecrets += `&spaceId=${spaceId}`;
330
- }
331
- const secretCacheKey = `secrets:${environmentId}${spaceId && `:${spaceId}`}`;
332
- const secrets = await this.cache.init(secretCacheKey, async () => {
333
- const secretsResponse = await this.fetch(getSecrets);
334
- const SecretMap = new Map();
335
- secretsResponse?.forEach((secret) => {
336
- SecretMap.set(secret.name, secret.value);
337
- });
338
- return SecretMap;
339
- });
340
- const value = secrets.get(key);
341
- if (!value) {
342
- throw new Error(`Secret ${key} not found`);
343
- }
344
- return value;
345
- }
346
- }
347
-
348
- /**
349
- * Glob style matching of a value
350
- *
351
- * @param val
352
- * @param filter
353
- */
354
- function glob(val, filter) {
355
- if (!val || typeof val !== 'string') {
356
- return false;
357
- }
358
- return wildMatch(filter || '**', ':')(val);
359
- }
360
- /**
361
- * Glob style matching of values in an object
362
- *
363
- * @param object
364
- * @param filterObject
365
- */
366
- function objectMatches(object, filterObject) {
367
- const cleanFilter = !filterObject || typeof filterObject !== 'object'
368
- ? { '**': filterObject }
369
- : filterObject;
370
- if (typeof object !== 'object') {
371
- throw new Error('You cannot filter a non-object');
372
- }
373
- let denied = false;
374
- const filter = flat(cleanFilter, { safe: true });
375
- const flattened = flat(object, { safe: true });
376
- // all filters MUST resolve true
377
- for (const keyPattern in filter) {
378
- const keys = filterKeys(flattened, keyPattern);
379
- const valuePattern = (Array.isArray(filter[keyPattern])
380
- ? filter[keyPattern]
381
- : [filter[keyPattern]]);
382
- // only one filter must match
383
- denied || (denied = !keys.some((key) => {
384
- const value = flattened[key];
385
- return valuePattern.some((match) => globOrMatch(value, match));
386
- }));
387
- }
388
- return !denied;
389
- }
390
- /**
391
- * Glob keys of an object and return the narrowed set
392
- *
393
- * @param object
394
- * @param glob
395
- */
396
- function filterKeys(object, glob) {
397
- glob = glob.includes('*') || glob.includes('.') ? glob : `**.${glob}`;
398
- const matcher = wildMatch(glob, '.');
399
- return Object.keys(object).filter((key) => matcher(key));
400
- }
401
- function globOrMatch(val, filter) {
402
- if (val === undefined || val === null) {
403
- return filter === null;
404
- }
405
- if (Array.isArray(val)) {
406
- return val.some((v) => globOrMatch(v, filter));
407
- }
408
- if (typeof filter === 'string') {
409
- return glob(val.toString(), filter);
410
- }
411
- // otherwise do a simple comparison
412
- return val === filter;
413
- }
414
-
415
- /**
416
- * EventHandler is a Flatfile flavored implementation of EventTarget
417
- */
418
- class EventHandler extends AuthenticatedClient {
419
- constructor(filter, accessToken, apiUrl) {
420
- super(accessToken, apiUrl);
421
- /**
422
- * Cache of registered listeners on this instance
423
- * @private
424
- */
425
- this.listeners = [];
426
- /**
427
- * Cache of registered child nodes for this listener. These nodes will
428
- * only receive events that pass the parent filter.
429
- *
430
- * @private
431
- */
432
- this.nodes = [];
433
- if (filter) {
434
- this.filterQuery = filter;
435
- }
436
- }
437
- on(query, ...rest) {
438
- let filter = {};
439
- const callback = rest.pop();
440
- if (rest.length) {
441
- filter = rest.shift();
442
- }
443
- this.listeners.push([query, filter, callback]);
444
- return this;
445
- }
446
- /**
447
- * Add child nodes to send this event to as well
448
- *
449
- * @param node
450
- */
451
- addNode(node) {
452
- this.nodes.push(node);
453
- return this;
454
- }
455
- /**
456
- * Dispatch an event and resolve the promise once it has completed (or
457
- * errored
458
- *
459
- * @todo - is there a right order in which to resolve event listeners?
460
- * Should it matter?
461
- *
462
- * @param event
463
- */
464
- async dispatchEvent(event) {
465
- if (!event)
466
- return;
467
- const eventPayload = event.src ? event.src : event;
468
- event = new FlatfileEvent(eventPayload, this._accessToken, this._apiUrl);
469
- await this.trigger(event, true);
470
- for (const [_key, cb] of event.afterAllCallbacks) {
471
- await cb(event);
472
- }
473
- event.cache.delete();
474
- }
475
- /**
476
- * @deprecated legacy shim for receiving events from the VM layer
477
- * @alias dispatchEvent
478
- * @param event
479
- */
480
- async routeEvent(event) {
481
- return this.dispatchEvent(event);
482
- }
483
- /**
484
- * Actually trigger the event listeners on this particular target
485
- *
486
- * @note It is safer for now to run this in series to avoid IO locks and
487
- * potential race conditions and uncaught errors
488
- *
489
- * @param event
490
- * @param recursive
491
- */
492
- async trigger(event, recursive = false) {
493
- const listeners = this.getListeners(event, recursive);
494
- for (const cb of listeners) {
495
- await cb.callback(event);
496
- }
497
- }
498
- /**
499
- * Get any listeners from this target subscribing to this event
500
- *
501
- * @param event
502
- * @param recursive
503
- */
504
- getListeners(event, recursive = false) {
505
- // never return any listeners if the event doesn't match the filter
506
- // event recursion should not occur either
507
- if (!this.matchEvent(event, this.filterQuery)) {
508
- return [];
509
- }
510
- // look at listeners registered here
511
- const listeners = this.listeners
512
- .filter(([query, filter]) => {
513
- const globbed = glob(event.topic, query);
514
- const matched = this.matchEvent(event, filter);
515
- return globbed && matched;
516
- })
517
- .map(([query, filter, callback]) => ({ query, filter, callback }));
518
- return !recursive
519
- ? listeners
520
- : [
521
- ...listeners,
522
- ...this.nodes.flatMap((n) => n.getListeners(event, true)),
523
- ];
524
- }
525
- /**
526
- * Attach more event listeners using a callback function. Used most
527
- * frequently for plugins.
528
- *
529
- * @param fn
530
- */
531
- use(fn) {
532
- fn(this);
533
- return this;
534
- }
535
- /**
536
- * Filter an event out based on glob filter object
537
- *
538
- * @param event
539
- * @param filter
540
- */
541
- matchEvent(event, filter) {
542
- return filter ? objectMatches(event, filter) : true;
543
- }
544
- }
545
-
546
- /**
547
- * The Flatfile Listener
548
- *
549
- * The Flatfile PubSub Client is just a simple event subscriber. It can
550
- * receive events from any PubSub driver. The default drivers are:
551
- *
552
- * - Webhook (for simply processing events sent to URL)
553
- * - Websocket (for subscribing real time on an HTTP2 connection)
554
- * - Serverless (for stateless invocations via AWS Lambda or similar)
555
- *
556
- * Once an event is received, it is routed to any awaiting listeners which
557
- * are added with `addEventListener()` or its alias `on()`.
558
- *
559
- * Flatfile events follow a standard structure and event listeners can use
560
- * any of the following syntaxes to react to events within Flatfile.
561
- *
562
- * // listen to an event
563
- * addEventListener('entity:topic')
564
- *
565
- * // listen to an event on a specific namespace
566
- * addEventListener('entity:topic@namespace')
567
- *
568
- * // listen to a specific context on a namespace
569
- * addEventListener('entity:topic@namespace?context=us_sp_89234oihsdo')
570
- *
571
- * // filter by any
572
- * addEventListener('entity:topic@namespace?')
573
- *
574
- */
575
- class FlatfileListener extends EventHandler {
576
- /**
577
- * Subscribe to events only within a certain namespace.
578
- *
579
- * @param namespace
580
- * @param cb
581
- */
582
- namespace(namespaces, cb) {
583
- return this.filter({ namespaces }, cb);
584
- }
585
- /**
586
- * Filter by namespace
587
- *
588
- * @param filter
589
- * @param cb
590
- */
591
- filter(filter, cb) {
592
- const client = new this.constructor(filter);
593
- this.addNode(client);
594
- cb?.(client);
595
- return client;
596
- }
597
- /**
598
- * Start subscribing to events
599
- *
600
- * @param cb
601
- */
602
- static create(cb) {
603
- const client = new this();
604
- cb(client);
605
- return client;
606
- }
607
- /**
608
- * Mount this client using an acceptable Event Driver
609
- */
610
- mount(driver) {
611
- driver.mountEventHandler(this);
612
- return this;
613
- }
614
- }
615
-
616
- class EventDriver {
617
- get handler() {
618
- if (!this._handler) {
619
- throw new Error('handler not registered yet');
620
- }
621
- return this._handler;
622
- }
623
- /**
624
- * Mount an event handler
625
- *
626
- * @param handler
627
- */
628
- mountEventHandler(handler) {
629
- this._handler = handler;
630
- return this;
631
- }
632
- /**
633
- * Dispatch an event
634
- *
635
- * @param e
636
- */
637
- dispatchEvent(e) {
638
- this.handler.dispatchEvent(e);
639
- return this;
640
- }
641
- }
642
-
643
- class Browser extends EventDriver {
644
- constructor({ apiUrl, accessToken, environmentId, }) {
645
- super();
646
- this._apiUrl = apiUrl;
647
- this._accessToken = accessToken;
648
- this._environmentId = environmentId || '';
649
- }
650
- mountEventHandler(handler) {
651
- handler.setVariables({
652
- accessToken: this._accessToken,
653
- apiUrl: this._apiUrl,
654
- });
655
- this._handler = handler;
656
- return this;
657
- }
658
- }
659
-
660
- /**
661
- * Flatfile's Virtual Machine is stateless / serverless. So when a new event
662
- * is handled, it will just call `handle(event)`.
663
- */
664
- class FlatfileVirtualMachine extends EventDriver {
665
- /**
666
- * This method is triggered from within the Flatfile Core VM Runner. This
667
- * EventDriver does not have to listen for events because this method will
668
- * be invoked as necessary.
669
- *
670
- * @param event
671
- */
672
- handle(event) {
673
- this.dispatchEvent(event);
674
- }
675
- mountEventHandler(handler) {
676
- this._handler = handler;
677
- return this;
678
- }
679
- }
680
-
681
- /**
682
- * Backwards compatibility
683
- */
684
- class Client extends FlatfileListener {
685
- }
686
-
687
- exports.AuthenticatedClient = AuthenticatedClient;
688
- exports.Browser = Browser;
689
- exports.Client = Client;
690
- exports.EventDriver = EventDriver;
691
- exports.EventHandler = EventHandler;
692
- exports.FlatfileEvent = FlatfileEvent;
693
- exports.FlatfileListener = FlatfileListener;
694
- exports.FlatfileVirtualMachine = FlatfileVirtualMachine;
695
- exports.default = FlatfileListener;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("cross-fetch"),e=require("pako"),s=require("wildcard-match"),r=require("flat"),n=class{static get(t){return this.safeEnvLookup(t)}static set(t,e){return this._overrides.set(t,e)}static alias(t,e){return this._aliases.set(t,e)}static attachConfigRegistry(t){this._registry=t}static attachConfigFactory(t){this._factory=t}static reset(){this._overrides=new Map,this._registry=void 0,this._factory=void 0}static safeEnvLookup(t){let e=[];this._overrides.get(t)&&e.push(this._overrides.get(t)),"object"==typeof this._registry&&e.push(this._registry[t]),"function"==typeof this._factory&&e.push(this._factory(t)),"object"==typeof process&&"object"==typeof process.env&&e.push(process.env[t]),e.push(...this.checkForBrowserVariables(t));const s=e.find((t=>void 0!==t));if(void 0!==s)return s;const r=this._aliases.get(t);return r?this.safeEnvLookup(r):void 0}static checkForBrowserVariables(t){let e=[];if("object"==typeof window){const s=window[`CROSSENV_${t}`];if(void 0!==s&&e.push(s),"object"==typeof sessionStorage){const s=sessionStorage.getItem(`CROSSENV_${t}`);null!==s&&e.push(s)}}return e}};n._overrides=new Map,n._aliases=new Map;class i{constructor(t,e){const s=n.get("AGENT_INTERNAL_URL")||"http://localhost:3000",r=n.get("FLATFILE_BEARER_TOKEN");this._accessToken=t||r||"...",this._apiUrl=e||s?(t=>{for(;t.endsWith("/");)t=t.slice(0,-1);return t+"/"})(e||s):void 0}async fetch(e,s){const r={Authorization:`Bearer ${this._accessToken}`,"x-disable-hooks":"true","Content-Type":"application/json",...s?.headers},n=this._apiUrl+e,i={method:s?.method||"GET",headers:r,body:s?.data};try{const e=await t(n,i);if(e.status>=200&&e.status<=399){const t=e.headers.get("content-type");if(t&&t.includes("application/json")){return(await e.json()).data}return await e.text()}throw new Error(`HTTP error! Status: ${e.status}`)}catch(t){console.log("event.fetch error: ",t)}}setVariables({accessToken:t,apiUrl:e}){this._accessToken=t,this._apiUrl=e}}class a{constructor(){this.eventCache=new Map}async init(t,e){if(this.eventCache.get(t))return this.eventCache.get(t);{const s=await e();return this.eventCache.set(t,s),s}}async set(t,e){if(this.eventCache.get(t)){const s=await e();return this.eventCache.set(t,s),s}throw new Error("Cache key not found")}get(t){if(this.eventCache.get(t))return this.eventCache.get(t);throw new Error("Cache key not found")}delete(t){if(t){if(!this.eventCache.get(t))throw new Error("Cache key not found");Array.isArray(t)?t.forEach((t=>this.eventCache.delete(t))):this.eventCache.delete(t)}else this.eventCache.clear()}}class o extends i{constructor(t,e,s){super(e,s),this.src=t,this.afterAllCallbacks=new Map,this.cache=new a,this.domain=t.domain,this.topic=t.topic,this.context=t.context,this.payload=t.payload,this.target=t.target||"",this.origin=t.origin||{},this.action=t.context?.actionName||"",this.namespace=t.namespaces||[],this.createdAt=t.createdAt||void 0;const r=async t=>this.fetchData(t);r.then=(t,e)=>this.data().then(t,e),this.data=r}async fetchData(t){const e=new URLSearchParams(this.src.dataUrl);if(t)for(const[s,r]of Object.entries(t))if(Array.isArray(r))for(const t of r)e.append(s,t);else e.append(s,r);const s=decodeURIComponent(e.toString());return s?this.fetch(s):this.payload}afterAll(t,e){const s=e||t.toString();this.afterAllCallbacks.get(s)||this.afterAllCallbacks.set(s,t)}async update(t,s=!0){if(!this.src.dataUrl)throw new Error("Cannot set data on an event without a dataUrl");t.map((t=>{t.messages?.map((t=>{delete t.source}))}));const r=s?e.gzip(JSON.stringify(t)):t,n=s?{"Content-Encoding":"gzip","Content-Length":r.length.toString()}:{};await this.fetch(this.src.dataUrl,{method:"PUT",headers:n,data:r})}async secrets(t,e){const s=e?.environmentId||this.context.environmentId||"",r=e?.spaceId||this.context.spaceId||"";if(!s)throw new Error("environmentId is required to fetch secrets");let n=`v1/secrets?environmentId=${s}`;r&&(n+=`&spaceId=${r}`);const i=`secrets:${s}${r&&`:${r}`}`,a=(await this.cache.init(i,(async()=>{const t=await this.fetch(n),e=new Map;return t?.forEach((t=>{e.set(t.name,t.value)})),e}))).get(t);if(!a)throw new Error(`Secret ${t} not found`);return a}}function c(t,e){return!(!t||"string"!=typeof t)&&s(e||"**",":")(t)}function h(t,e){e=e.includes("*")||e.includes(".")?e:`**.${e}`;const r=s(e,".");return Object.keys(t).filter((t=>r(t)))}function l(t,e){return null==t?null===e:Array.isArray(t)?t.some((t=>l(t,e))):"string"==typeof e?c(t.toString(),e):t===e}class d extends i{constructor(t,e,s){super(e,s),this.listeners=[],this.nodes=[],t&&(this.filterQuery=t)}on(t,...e){let s={};const r=e.pop();return e.length&&(s=e.shift()),this.listeners.push([t,s,r]),this}addNode(t){return this.nodes.push(t),this}async dispatchEvent(t){if(!t)return;const e=t.src?t.src:t;t=new o(e,this._accessToken,this._apiUrl),await this.trigger(t,!0);for(const[e,s]of t.afterAllCallbacks)await s(t);t.cache.delete()}async routeEvent(t){return this.dispatchEvent(t)}async trigger(t,e=!1){const s=this.getListeners(t,e);for(const e of s)await e.callback(t)}getListeners(t,e=!1){if(!this.matchEvent(t,this.filterQuery))return[];const s=this.listeners.filter((([e,s])=>{const r=c(t.topic,e),n=this.matchEvent(t,s);return r&&n})).map((([t,e,s])=>({query:t,filter:e,callback:s})));return e?[...s,...this.nodes.flatMap((e=>e.getListeners(t,!0)))]:s}use(t){return t(this),this}matchEvent(t,e){return!e||function(t,e){const s=e&&"object"==typeof e?e:{"**":e};if("object"!=typeof t)throw new Error("You cannot filter a non-object");let n=!1;const i=r(s,{safe:!0}),a=r(t,{safe:!0});for(const t in i){const e=h(a,t),s=Array.isArray(i[t])?i[t]:[i[t]];n||(n=!e.some((t=>{const e=a[t];return s.some((t=>l(e,t)))})))}return!n}(t,e)}}class u extends d{namespace(t,e){return this.filter({namespaces:t},e)}filter(t,e){const s=new this.constructor(t);return this.addNode(s),e?.(s),s}static create(t){const e=new this;return t(e),e}mount(t){return t.mountEventHandler(this),this}}class p{get handler(){if(!this._handler)throw new Error("handler not registered yet");return this._handler}mountEventHandler(t){return this._handler=t,this}dispatchEvent(t){return this.handler.dispatchEvent(t),this}}exports.AuthenticatedClient=i,exports.Browser=class extends p{constructor({apiUrl:t,accessToken:e,environmentId:s}){super(),this._apiUrl=t,this._accessToken=e,this._environmentId=s||""}mountEventHandler(t){return t.setVariables({accessToken:this._accessToken,apiUrl:this._apiUrl}),this._handler=t,this}},exports.Client=class extends u{},exports.EventDriver=p,exports.EventHandler=d,exports.FlatfileEvent=o,exports.FlatfileListener=u,exports.FlatfileVirtualMachine=class extends p{handle(t){this.dispatchEvent(t)}mountEventHandler(t){return this._handler=t,this}},exports.default=u;