@flatfile/listener 0.3.1 → 0.3.3

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/dist/index.d.ts CHANGED
@@ -114,14 +114,16 @@ declare class EventHandler extends AuthenticatedClient {
114
114
  * potential race conditions and uncaught errors
115
115
  *
116
116
  * @param event
117
+ * @param recursive
117
118
  */
118
- trigger(event: FlatfileEvent): Promise<void>;
119
+ trigger(event: FlatfileEvent, recursive?: boolean): Promise<void>;
119
120
  /**
120
121
  * Get any listeners from this target subscribing to this event
121
122
  *
122
123
  * @param event
124
+ * @param recursive
123
125
  */
124
- getListeners(event: FlatfileEvent): EventCallback[];
126
+ getListeners(event: FlatfileEvent, recursive?: boolean): Listener[];
125
127
  /**
126
128
  * Attach more event listeners using a callback function. Used most
127
129
  * frequently for plugins.
@@ -139,6 +141,11 @@ declare class EventHandler extends AuthenticatedClient {
139
141
  }
140
142
  type EventFilter = Record<string, Arrayable<string>>;
141
143
  type Arrayable<T> = T | Array<T>;
144
+ type Listener = {
145
+ query: string | string[];
146
+ filter: any;
147
+ callback: EventCallback;
148
+ };
142
149
 
143
150
  declare abstract class EventDriver {
144
151
  _handler?: EventHandler;
@@ -253,4 +260,4 @@ declare class FlatfileVirtualMachine extends EventDriver {
253
260
  declare class Client extends FlatfileListener {
254
261
  }
255
262
 
256
- export { Arrayable, AuthenticatedClient, Browser, Client, EventCallback, EventDriver, EventFilter, EventHandler, FlatfileEvent, FlatfileListener, FlatfileVirtualMachine };
263
+ export { Arrayable, AuthenticatedClient, Browser, Client, EventCallback, EventDriver, EventFilter, EventHandler, FlatfileEvent, FlatfileListener, FlatfileVirtualMachine, Listener };
package/dist/index.js CHANGED
@@ -457,13 +457,7 @@ var EventHandler = class extends AuthenticatedClient {
457
457
  });
458
458
  }
459
459
  }
460
- if (!this.matchEvent(event, this.filterQuery)) {
461
- return;
462
- }
463
- await this.trigger(event);
464
- for (const node of this.nodes) {
465
- await node.dispatchEvent(event);
466
- }
460
+ await this.trigger(event, true);
467
461
  await event.afterAllCallbacks.forEach(async (cb) => cb(event));
468
462
  event.cache.delete();
469
463
  }
@@ -482,24 +476,33 @@ var EventHandler = class extends AuthenticatedClient {
482
476
  * potential race conditions and uncaught errors
483
477
  *
484
478
  * @param event
479
+ * @param recursive
485
480
  */
486
- async trigger(event) {
487
- const listeners = this.getListeners(event);
481
+ async trigger(event, recursive = false) {
482
+ const listeners = this.getListeners(event, recursive);
488
483
  for (const cb of listeners) {
489
- await cb(event);
484
+ await cb.callback(event);
490
485
  }
491
486
  }
492
487
  /**
493
488
  * Get any listeners from this target subscribing to this event
494
489
  *
495
490
  * @param event
491
+ * @param recursive
496
492
  */
497
- getListeners(event) {
498
- return this.listeners.filter(([query, filter]) => {
493
+ getListeners(event, recursive = false) {
494
+ if (!this.matchEvent(event, this.filterQuery)) {
495
+ return [];
496
+ }
497
+ const listeners = this.listeners.filter(([query, filter]) => {
499
498
  const globbed = glob(event.topic, query);
500
499
  const matched = this.matchEvent(event, filter);
501
500
  return globbed && matched;
502
- }).map(([_q, _ctx, cb]) => cb);
501
+ }).map(([query, filter, callback]) => ({ query, filter, callback }));
502
+ return !recursive ? listeners : [
503
+ ...listeners,
504
+ ...this.nodes.flatMap((n) => n.getListeners(event, true))
505
+ ];
503
506
  }
504
507
  /**
505
508
  * Attach more event listeners using a callback function. Used most
package/dist/index.mjs CHANGED
@@ -414,13 +414,7 @@ var EventHandler = class extends AuthenticatedClient {
414
414
  });
415
415
  }
416
416
  }
417
- if (!this.matchEvent(event, this.filterQuery)) {
418
- return;
419
- }
420
- await this.trigger(event);
421
- for (const node of this.nodes) {
422
- await node.dispatchEvent(event);
423
- }
417
+ await this.trigger(event, true);
424
418
  await event.afterAllCallbacks.forEach(async (cb) => cb(event));
425
419
  event.cache.delete();
426
420
  }
@@ -439,24 +433,33 @@ var EventHandler = class extends AuthenticatedClient {
439
433
  * potential race conditions and uncaught errors
440
434
  *
441
435
  * @param event
436
+ * @param recursive
442
437
  */
443
- async trigger(event) {
444
- const listeners = this.getListeners(event);
438
+ async trigger(event, recursive = false) {
439
+ const listeners = this.getListeners(event, recursive);
445
440
  for (const cb of listeners) {
446
- await cb(event);
441
+ await cb.callback(event);
447
442
  }
448
443
  }
449
444
  /**
450
445
  * Get any listeners from this target subscribing to this event
451
446
  *
452
447
  * @param event
448
+ * @param recursive
453
449
  */
454
- getListeners(event) {
455
- return this.listeners.filter(([query, filter]) => {
450
+ getListeners(event, recursive = false) {
451
+ if (!this.matchEvent(event, this.filterQuery)) {
452
+ return [];
453
+ }
454
+ const listeners = this.listeners.filter(([query, filter]) => {
456
455
  const globbed = glob(event.topic, query);
457
456
  const matched = this.matchEvent(event, filter);
458
457
  return globbed && matched;
459
- }).map(([_q, _ctx, cb]) => cb);
458
+ }).map(([query, filter, callback]) => ({ query, filter, callback }));
459
+ return !recursive ? listeners : [
460
+ ...listeners,
461
+ ...this.nodes.flatMap((n) => n.getListeners(event, true))
462
+ ];
460
463
  }
461
464
  /**
462
465
  * Attach more event listeners using a callback function. Used most
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flatfile/listener",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "A PubSub Listener for configuring and using Flatfile",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -12,6 +12,9 @@
12
12
  "poll": "tsup src/dev.ts --format esm,cjs --watch --dts --onSuccess \"node dist/dev.js\"",
13
13
  "test": "jest --passWithNoTests"
14
14
  },
15
+ "files": [
16
+ "dist/**"
17
+ ],
15
18
  "license": "MIT",
16
19
  "devDependencies": {
17
20
  "@flatfile/eslint-config-platform-sdk": "*",
package/.eslintrc.js DELETED
@@ -1,4 +0,0 @@
1
- export default {
2
- root: true,
3
- extends: ['@flatfile/eslint-config-platform-sdk'],
4
- }
@@ -1,17 +0,0 @@
1
-
2
- > @flatfile/listener@0.3.1 build
3
- > tsup src/index.ts --format esm,cjs --dts
4
-
5
- CLI Building entry: src/index.ts
6
- CLI Using tsconfig: tsconfig.json
7
- CLI tsup v6.7.0
8
- CLI Target: es2020
9
- ESM Build start
10
- CJS Build start
11
- CJS dist/index.js 17.81 KB
12
- CJS ⚡️ Build success in 142ms
13
- ESM dist/index.mjs 15.87 KB
14
- ESM ⚡️ Build success in 144ms
15
- DTS Build start
16
- DTS ⚡️ Build success in 2435ms
17
- DTS dist/index.d.ts 7.14 KB
package/CHANGELOG.md DELETED
@@ -1,107 +0,0 @@
1
- # @flatfile/listener
2
-
3
- ## 0.3.1
4
-
5
- ### Patch Changes
6
-
7
- - 9ca9443: Event Cache Cleanup
8
-
9
- ## 0.3.0
10
-
11
- ### Minor Changes
12
-
13
- - 2a30e13: Add cross-env library for accessing environment variables
14
-
15
- ## 0.2.0
16
-
17
- ### Minor Changes
18
-
19
- - 637342b: Remove @flatfile/api from listener
20
-
21
- ## 0.1.2
22
-
23
- ### Patch Changes
24
-
25
- - 22d2466: Pull last 5 seconds of events in Polling Driver
26
-
27
- ## 0.1.1
28
-
29
- ### Patch Changes
30
-
31
- - 356c35d: Minor CI improvements and backwards compatible rename of Client to FlatfileListener
32
-
33
- ## 0.1.0
34
-
35
- ### Minor Changes
36
-
37
- - 4d88069: Adds a major improvement to event filtering, allowing you to grep the key path and defaulting to matching any key in the object
38
-
39
- ## 0.0.10
40
-
41
- ### Patch Changes
42
-
43
- - 4807720: removes unused node dependencies
44
- - 82e80e3: Add in x-disable-hooks header
45
-
46
- ## 0.0.9
47
-
48
- ### Patch Changes
49
-
50
- - 46357d9: flatfile deploy and develop
51
-
52
- ## 0.0.8
53
-
54
- ### Patch Changes
55
-
56
- - 74852f3: Adds Event Cache
57
- - 65aea7a: Adds conditional fetchApi variable to authenticated client to allow for client-side use
58
-
59
- ## 0.0.7
60
-
61
- ### Patch Changes
62
-
63
- - Updated dependencies [72447b1]
64
- - @flatfile/hooks@1.3.0
65
-
66
- ## 0.0.6
67
-
68
- ### Patch Changes
69
-
70
- - 4039970: Adds 'x-disable-hooks': 'true' to event payload to x
71
-
72
- ## 0.0.5
73
-
74
- ### Patch Changes
75
-
76
- - 55f9fff: Update API version and use configless space creation in listener example.
77
- - Updated dependencies [55f9fff]
78
- - @flatfile/schema@0.2.15
79
-
80
- ## 0.0.4
81
-
82
- ### Patch Changes
83
-
84
- - 8ed4e8c: Bumps API version and adds support for record metadata to @flatfile/hooks.
85
- - Updated dependencies [8ed4e8c]
86
- - @flatfile/schema@0.2.14
87
- - @flatfile/hooks@1.2.4
88
-
89
- ## 0.0.3
90
-
91
- ### Patch Changes
92
-
93
- - c946831: Updates to use the dataUrl for getting records
94
-
95
- ## 0.0.2
96
-
97
- ### Patch Changes
98
-
99
- - 2e25be3: Update packages with updated @flatfile/api
100
- - Updated dependencies [2e25be3]
101
- - @flatfile/schema@0.2.13
102
-
103
- ## 0.0.1
104
-
105
- ### Patch Changes
106
-
107
- - 4b918a2: Adds the new @flatfile/listener package
package/jest.config.js DELETED
@@ -1,3 +0,0 @@
1
- module.exports = {
2
- preset: '@flatfile/jest-preset-platform-sdk',
3
- }
@@ -1,37 +0,0 @@
1
- import { EventDriver } from './_EventDriver'
2
- import { EventHandler } from '../events'
3
-
4
- export class Browser extends EventDriver {
5
- public _accessToken?: string
6
- public _apiUrl?: string
7
- public _environmentId?: string
8
-
9
- constructor({
10
- apiUrl,
11
- accessToken,
12
- environmentId,
13
- }: {
14
- apiUrl: string
15
- accessToken: string
16
- environmentId?: string
17
- /**
18
- * @deprecated
19
- */
20
- fetchApi: any
21
- }) {
22
- super()
23
- this._apiUrl = apiUrl
24
- this._accessToken = accessToken
25
- this._environmentId = environmentId || ''
26
- }
27
-
28
- mountEventHandler(handler: EventHandler): this {
29
- handler.setVariables({
30
- accessToken: this._accessToken,
31
- apiUrl: this._apiUrl,
32
- })
33
-
34
- this._handler = handler
35
- return this
36
- }
37
- }
@@ -1,25 +0,0 @@
1
- import { EventDriver } from './_EventDriver'
2
- import { EventHandler, FlatfileEvent } from '../events'
3
-
4
- /**
5
- * Flatfile's Virtual Machine is stateless / serverless. So when a new event
6
- * is handled, it will just call `handle(event)`.
7
- */
8
- export class FlatfileVirtualMachine extends EventDriver {
9
- /**
10
- * This method is triggered from within the Flatfile Core VM Runner. This
11
- * EventDriver does not have to listen for events because this method will
12
- * be invoked as necessary.
13
- *
14
- * @param event
15
- */
16
-
17
- handle(event: FlatfileEvent) {
18
- this.dispatchEvent(event)
19
- }
20
-
21
- mountEventHandler(handler: EventHandler): this {
22
- this._handler = handler
23
- return this
24
- }
25
- }
File without changes
@@ -1,32 +0,0 @@
1
- import { EventHandler } from '../events'
2
-
3
- export abstract class EventDriver {
4
- _handler?: EventHandler
5
-
6
- public get handler(): EventHandler {
7
- if (!this._handler) {
8
- throw new Error('handler not registered yet')
9
- }
10
- return this._handler
11
- }
12
-
13
- /**
14
- * Mount an event handler
15
- *
16
- * @param handler
17
- */
18
- mountEventHandler(handler: EventHandler): this {
19
- this._handler = handler
20
- return this
21
- }
22
-
23
- /**
24
- * Dispatch an event
25
- *
26
- * @param e
27
- */
28
- dispatchEvent(e: any): this {
29
- this.handler.dispatchEvent(e)
30
- return this
31
- }
32
- }
@@ -1,3 +0,0 @@
1
- export * from './Browser'
2
- export * from './FlatfileVirtualMachine'
3
- export * from './_EventDriver'
@@ -1,44 +0,0 @@
1
- import { CrossEnvConfig } from '@flatfile/cross-env-config'
2
- import axios from 'axios'
3
-
4
- export class AuthenticatedClient {
5
- public _accessToken?: string
6
- public _apiUrl?: string
7
-
8
- constructor(accessToken?: string, apiUrl?: string) {
9
- const FLATFILE_API_URL =
10
- CrossEnvConfig.get('AGENT_INTERNAL_URL') || 'http://localhost:3000'
11
- const bearerToken = CrossEnvConfig.get('FLATFILE_BEARER_TOKEN')
12
-
13
- this._accessToken = accessToken || bearerToken || '...'
14
-
15
- this._apiUrl = apiUrl || FLATFILE_API_URL
16
- }
17
-
18
- fetch(url: string) {
19
- const headers = {
20
- Authorization: `Bearer ${this._accessToken}`,
21
- 'x-disable-hooks': 'true',
22
- }
23
- const fetchUrl = this._apiUrl + '/' + url
24
-
25
- return axios
26
- .get(fetchUrl, { headers })
27
- .then((resp: any) => resp.data.data)
28
- .catch((err: any) => {})
29
- }
30
- /**
31
- *
32
- * @deprecated use @flatfile/cross-env-config instead
33
- */
34
- public setVariables({
35
- accessToken,
36
- apiUrl,
37
- }: {
38
- accessToken?: string
39
- apiUrl?: string
40
- }) {
41
- this._accessToken = accessToken
42
- this._apiUrl = apiUrl
43
- }
44
- }
@@ -1,45 +0,0 @@
1
- export class EventCache {
2
- private eventCache: Map<any, any> = new Map()
3
-
4
- async init<T>(key: string, callback: () => Promise<T>): Promise<T> {
5
- if (this.eventCache.get(key)) {
6
- return this.eventCache.get(key)
7
- } else {
8
- const result = await callback()
9
- this.eventCache.set(key, result)
10
- return result
11
- }
12
- }
13
-
14
- async set<T>(key: string, callback: () => Promise<T>): Promise<T> {
15
- if (this.eventCache.get(key)) {
16
- const result = await callback()
17
- this.eventCache.set(key, result)
18
- return result
19
- } else {
20
- throw new Error('Cache key not found')
21
- }
22
- }
23
-
24
- get<T>(key: string): T {
25
- if (this.eventCache.get(key)) {
26
- return this.eventCache.get(key)
27
- } else {
28
- throw new Error('Cache key not found')
29
- }
30
- }
31
-
32
- delete(key?: string | string[]): void {
33
- if (!key) {
34
- this.eventCache.clear()
35
- } else if (this.eventCache.get(key)) {
36
- if (Array.isArray(key)) {
37
- key.forEach((k) => this.eventCache.delete(k))
38
- } else {
39
- this.eventCache.delete(key)
40
- }
41
- } else {
42
- throw new Error('Cache key not found')
43
- }
44
- }
45
- }
@@ -1,89 +0,0 @@
1
- import { EventHandler } from './event.handler'
2
-
3
- describe('EventHandler', () => {
4
- let testFn: jest.Mock
5
-
6
- beforeEach(() => {
7
- testFn = jest.fn()
8
- })
9
-
10
- describe('triggering', () => {
11
- test('triggers basic event listeners', () => {
12
- const handler = new EventHandler().on('foo', testFn)
13
-
14
- handler.dispatchEvent({ topic: 'foo' })
15
- expect(testFn).toHaveBeenCalledTimes(1)
16
- })
17
-
18
- test('triggers namespaced event listeners', () => {
19
- const handler = new EventHandler().on('records:created', testFn)
20
-
21
- handler.dispatchEvent({ topic: 'records:created' })
22
- expect(testFn).toHaveBeenCalled()
23
- })
24
-
25
- test('triggers event listener for array of events', () => {
26
- const handler = new EventHandler().on(
27
- ['records:created', 'records:updated'],
28
- testFn
29
- )
30
-
31
- handler.dispatchEvent({ topic: 'records:created' })
32
- handler.dispatchEvent({ topic: 'records:updated' })
33
- expect(testFn).toHaveBeenCalledTimes(2)
34
- })
35
-
36
- test('triggers event listener for wildcard query of events', () => {
37
- const handler = new EventHandler().on('records:*', testFn)
38
-
39
- handler.dispatchEvent({ topic: 'records:created' })
40
- handler.dispatchEvent({ topic: 'records:updated' })
41
- handler.dispatchEvent({ topic: 'records:deleted' })
42
- expect(testFn).toHaveBeenCalledTimes(3)
43
- })
44
- })
45
-
46
- describe('filtering', () => {
47
- test('trigger only when filter match - on listener', () => {
48
- const handler = new EventHandler().on(
49
- 'records:created',
50
- { domain: 'foo' },
51
- testFn
52
- )
53
-
54
- handler.dispatchEvent({ topic: 'records:created' })
55
- handler.dispatchEvent({ topic: 'records:created', domain: 'foo' })
56
- expect(testFn).toHaveBeenCalledTimes(1)
57
- })
58
-
59
- test('trigger only when filter match - on scope', () => {
60
- const handler = new EventHandler({ domain: 'foo' }).on(
61
- 'records:created',
62
- testFn
63
- )
64
-
65
- handler.dispatchEvent({ topic: 'records:created' })
66
- handler.dispatchEvent({ topic: 'records:created', domain: 'foo' })
67
- expect(testFn).toHaveBeenCalledTimes(1)
68
- })
69
- })
70
-
71
- describe('child node', () => {
72
- test('trigger a listener on a child node', async () => {
73
- const handler = new EventHandler().addNode(
74
- new EventHandler().on('records:created', testFn)
75
- )
76
- await handler.dispatchEvent({ topic: 'records:created' })
77
- expect(testFn).toHaveBeenCalledTimes(1)
78
- })
79
-
80
- test('trigger only when filter match - on scope', async () => {
81
- const handler = new EventHandler().addNode(
82
- new EventHandler({ domain: 'foo' }).on('records:created', testFn)
83
- )
84
- await handler.dispatchEvent({ topic: 'records:created' })
85
- await handler.dispatchEvent({ topic: 'records:created', domain: 'foo' })
86
- expect(testFn).toHaveBeenCalledTimes(1)
87
- })
88
- })
89
- })