@flatfile/listener 0.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.
package/jest.config.js ADDED
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ preset: '@flatfile/jest-preset-platform-sdk',
3
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@flatfile/listener",
3
+ "version": "0.0.1",
4
+ "description": "A PubSub Listener for configuring and using Flatfile",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsup src/index.ts --format esm,cjs --dts",
10
+ "dev": "tsup src/index.ts --format esm,cjs --dts --watch",
11
+ "poll": "tsup src/dev.ts --format esm,cjs --watch --dts --onSuccess \"node dist/dev.js\""
12
+ },
13
+ "license": "MIT",
14
+ "devDependencies": {
15
+ "@flatfile/api": "^0.0.12",
16
+ "@flatfile/blueprint": "^0.0.5",
17
+ "@flatfile/eslint-config-platform-sdk": "*",
18
+ "@flatfile/jest-preset-platform-sdk": "*",
19
+ "@flatfile/ts-config-platform-sdk": "*",
20
+ "@flatfile/configure": "*",
21
+ "@types/async": "^3.2.15",
22
+ "@types/jest": "^28.1.4",
23
+ "async": "^3.2.4",
24
+ "eslint": "^8.19.0",
25
+ "jest": "^28.1.2",
26
+ "ts-jest": "^28.0.8",
27
+ "tslib": "^2.4.1",
28
+ "tsup": "^6.1.3",
29
+ "typescript": "^4.7.4"
30
+ },
31
+ "dependencies": {
32
+ "node-fetch": "2.6.7",
33
+ "@flatfile/hooks": "1.2.3",
34
+ "@flatfile/orm": "0.1.0",
35
+ "@flatfile/schema": "0.2.12",
36
+ "axios": "^1.2.1",
37
+ "case-anything": "^2.1.10",
38
+ "date-fns": "^2.29.1",
39
+ "xlsx": "^0.18.5"
40
+ }
41
+ }
@@ -0,0 +1,82 @@
1
+ import { Client } from './Client'
2
+
3
+ describe('Client', () => {
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 client = Client.create((c) => {
13
+ c.on('foo', testFn)
14
+ })
15
+ client.dispatchEvent({ topic: 'foo' })
16
+ expect(testFn).toHaveBeenCalledTimes(1)
17
+ })
18
+
19
+ test('triggers namespaced event listeners', () => {
20
+ const client = Client.create((c) => {
21
+ c.on('records:created', testFn)
22
+ })
23
+ client.dispatchEvent({ topic: 'records:created' })
24
+ expect(testFn).toHaveBeenCalled()
25
+ })
26
+
27
+ test('triggers event listener for array of events', () => {
28
+ const client = Client.create((c) => {
29
+ c.on(['records:created', 'records:updated'], testFn)
30
+ })
31
+ client.dispatchEvent({ topic: 'records:created' })
32
+ client.dispatchEvent({ topic: 'records:updated' })
33
+ expect(testFn).toHaveBeenCalledTimes(2)
34
+ })
35
+
36
+ test('triggers event listener for wildcard query of events', () => {
37
+ const client = Client.create((c) => {
38
+ c.on('records:*', testFn)
39
+ })
40
+ client.dispatchEvent({ topic: 'records:created' })
41
+ client.dispatchEvent({ topic: 'records:updated' })
42
+ client.dispatchEvent({ topic: 'records:deleted' })
43
+ expect(testFn).toHaveBeenCalledTimes(3)
44
+ })
45
+ })
46
+
47
+ describe('filtering', () => {
48
+ test('trigger only when filter match - on listener', async () => {
49
+ const client = Client.create((c) => {
50
+ c.on('records:created', { domain: 'foo' }, testFn)
51
+ })
52
+ await client.dispatchEvent({ topic: 'records:created' })
53
+ await client.dispatchEvent({ topic: 'records:created', domain: 'foo' })
54
+ expect(testFn).toHaveBeenCalledTimes(1)
55
+ })
56
+
57
+ test('trigger only when filter match - on scope', async () => {
58
+ const client = Client.create((c) => {
59
+ c.filter({ domain: 'foo' }, (f) => {
60
+ f.on('records:created', testFn)
61
+ })
62
+ })
63
+ await client.dispatchEvent({ topic: 'records:created' })
64
+ await client.dispatchEvent({ topic: 'records:created', domain: 'foo' })
65
+ expect(testFn).toHaveBeenCalledTimes(1)
66
+ })
67
+
68
+ test('multiple layers of filtering', async () => {
69
+ const client = Client.create((c) => {
70
+ c.filter({ domain: 'foo:*' })
71
+ .filter({ domain: 'foo:bar' })
72
+ .use((f) => {
73
+ f.on('records:created', testFn)
74
+ })
75
+ })
76
+ await client.dispatchEvent({ topic: 'records:created' })
77
+ await client.dispatchEvent({ topic: 'records:created', domain: 'foo:bar' })
78
+ await client.dispatchEvent({ topic: 'records:created', domain: 'foo:baz' })
79
+ expect(testFn).toHaveBeenCalledTimes(1)
80
+ })
81
+ })
82
+ })
package/src/Client.ts ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The Client
3
+ *
4
+ * The Flatfile PubSub Client is just a simple event subscriber. It can
5
+ * receive events from any PubSub driver. The default drivers are:
6
+ *
7
+ * - Webhook (for simply processing events sent to URL)
8
+ * - Websocket (for subscribing real time on an HTTP2 connection)
9
+ * - Serverless (for stateless invocations via AWS Lambda or similar)
10
+ *
11
+ * Once an event is received, it is routed to any awaiting listeners which
12
+ * are added with `addEventListener()` or its alias `on()`.
13
+ *
14
+ * Flatfile events follow a standard structure and event listeners can use
15
+ * any of the following syntaxes to react to events within Flatfile.
16
+ *
17
+ * // listen to an event
18
+ * addEventListener('entity:topic')
19
+ *
20
+ * // listen to an event on a specific namespace
21
+ * addEventListener('entity:topic@namespace')
22
+ *
23
+ * // listen to a specific context on a namespace
24
+ * addEventListener('entity:topic@namespace?context=us_sp_89234oihsdo')
25
+ *
26
+ * // filter by any
27
+ * addEventListener('entity:topic@namespace?')
28
+ *
29
+ */
30
+
31
+ import { EventFilter, EventHandler } from './events'
32
+ import { EventDriver } from './event-drivers/_EventDriver'
33
+
34
+ export class Client extends EventHandler {
35
+ /**
36
+ * Subscribe to events only within a certain namespace.
37
+ *
38
+ * @param namespace
39
+ * @param cb
40
+ */
41
+ namespace(namespace: string | string[], cb?: SubFn) {
42
+ return this.filter({ namespace }, cb)
43
+ }
44
+
45
+ /**
46
+ * Filter by namespace
47
+ *
48
+ * @param filter
49
+ * @param cb
50
+ */
51
+ filter(filter: EventFilter, cb?: SubFn) {
52
+ const client = new Client(filter)
53
+ this.addNode(client)
54
+ cb?.(client)
55
+ return client
56
+ }
57
+
58
+ setupFunctions: Array<(...args: any[]) => void> = []
59
+ public beforeMount(cb: SubFn) {
60
+ this.setupFunctions.push(cb)
61
+ }
62
+
63
+ /**
64
+ * Start subscribing to events
65
+ *
66
+ * @param cb
67
+ */
68
+ public static create(cb: SubFn): Client {
69
+ const client = new Client()
70
+ client.beforeMount(() => cb(client))
71
+ return client
72
+ }
73
+
74
+ /**
75
+ * Mount this client using an acceptable Event Driver
76
+ */
77
+ mount(driver: EventDriver) {
78
+ this.setupFunctions.forEach((f) => f())
79
+ driver.mountEventHandler(this)
80
+ return this
81
+ }
82
+ }
83
+
84
+ type SubFn = (client: Client) => void
package/src/dev.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { PollingEventDriver } from './event-drivers/Polling'
2
+ import testClient from './examples/Local'
3
+
4
+ const environmentId = process.env.ENVIROMENT_ID || 'dev_env_1234567890'
5
+
6
+ const pollDriver = new PollingEventDriver({
7
+ interval: 1000,
8
+ environmentId,
9
+ })
10
+
11
+ testClient.mount(pollDriver)
12
+
13
+ pollDriver.start()
File without changes
@@ -0,0 +1,19 @@
1
+ import { EventDriver } from './_EventDriver'
2
+ import { 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
+ handle(event: FlatfileEvent) {
17
+ this.dispatchEvent(event)
18
+ }
19
+ }
@@ -0,0 +1,35 @@
1
+ import { EventDriver } from './_EventDriver'
2
+
3
+ export class PollingEventDriver extends EventDriver {
4
+ constructor(private options: { interval: number; environmentId: string }) {
5
+ super()
6
+ }
7
+
8
+ start() {
9
+ let lastTimestamp = new Date()
10
+ setInterval(() => {
11
+ this.handler.api
12
+ .getEvents({
13
+ since: lastTimestamp,
14
+ environmentId: this.options.environmentId,
15
+ })
16
+ .then((res) => {
17
+ process.stdout.cursorTo(0)
18
+ process.stdout.clearLine(1)
19
+ process.stdout.write(
20
+ `→ checked events at ${lastTimestamp.toISOString()} — ${
21
+ res.data?.length || 0
22
+ } found\n`
23
+ )
24
+ res.data?.forEach((e) => {
25
+ this.dispatchEvent(e)
26
+ })
27
+ })
28
+ .catch(console.error)
29
+
30
+ lastTimestamp = new Date()
31
+ }, this.options.interval)
32
+ }
33
+
34
+ shutdown() {}
35
+ }
File without changes
@@ -0,0 +1,32 @@
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
+ }
@@ -0,0 +1,2 @@
1
+ export * from './Polling'
2
+ export * from './FlatfileVirtualMachine'
@@ -0,0 +1,27 @@
1
+ import { Configuration, DefaultApi } from '@flatfile/api'
2
+ // TODO: We will need to make this conditional depending on if it's in the NodeVM or the Browser
3
+ import fetch from 'node-fetch'
4
+
5
+ const FLATFILE_API_URL =
6
+ process.env.FLATFILE_API_URL || 'http://localhost:3000'
7
+
8
+ export class AuthenticatedClient {
9
+ private _api?: DefaultApi
10
+
11
+ get api(): DefaultApi {
12
+ if (this._api) {
13
+ return this._api
14
+ }
15
+
16
+ const ClientConfig = new Configuration({
17
+ basePath: `${FLATFILE_API_URL}/v1`,
18
+ fetchApi: fetch,
19
+ accessToken: process.env.FLATFILE_BEARER_TOKEN,
20
+ headers: {
21
+ Authorization: `Bearer ${process.env.FLATFILE_BEARER_TOKEN || '...'}`,
22
+ },
23
+ })
24
+
25
+ return new DefaultApi(ClientConfig)
26
+ }
27
+ }
@@ -0,0 +1,89 @@
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
+ })
@@ -0,0 +1,166 @@
1
+ import { AuthenticatedClient } from './authenticated.client'
2
+ import { EventCallback, FlatfileEvent } from './flatfile.event'
3
+ import { glob, objectMatches } from './glob.match'
4
+ import { Event as ApiEvent } from '@flatfile/api'
5
+
6
+ /**
7
+ * EventHandler is a Flatfile flavored implementation of EventTarget
8
+ */
9
+ export class EventHandler extends AuthenticatedClient {
10
+ /**
11
+ * Apply a filter to the values of an event
12
+ */
13
+ public readonly filterQuery?: EventFilter
14
+
15
+ /**
16
+ * Cache of registered listeners on this instance
17
+ * @private
18
+ */
19
+ private listeners: [string | string[], EventFilter, EventCallback][] = []
20
+
21
+ constructor(filter?: EventFilter) {
22
+ super()
23
+
24
+ if (filter) {
25
+ this.filterQuery = filter
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Cache of registered child nodes for this listener. These nodes will
31
+ * only receive events that pass the parent filter.
32
+ *
33
+ * @private
34
+ */
35
+ private nodes: EventHandler[] = []
36
+
37
+ /**
38
+ * Register a subscriber for events that match this path
39
+ */
40
+ on(query: Arrayable<string>, callback: EventCallback): this
41
+ on(
42
+ query: Arrayable<string>,
43
+ filter: EventFilter,
44
+ callback: EventCallback
45
+ ): this
46
+ on(
47
+ query: Arrayable<string>,
48
+ ...rest: [EventCallback] | [EventFilter, EventCallback]
49
+ ): this {
50
+ let filter: EventFilter = {}
51
+ const callback: EventCallback = rest.pop() as EventCallback
52
+
53
+ if (rest.length) {
54
+ filter = rest.shift() as EventFilter
55
+ }
56
+
57
+ this.listeners.push([query, filter, callback])
58
+
59
+ return this
60
+ }
61
+
62
+ /**
63
+ * Add child nodes to send this event to as well
64
+ *
65
+ * @param node
66
+ */
67
+ addNode(node: EventHandler): this {
68
+ this.nodes.push(node)
69
+ return this
70
+ }
71
+
72
+ /**
73
+ * Dispatch an event and resolve the promise once it has completed (or
74
+ * errored
75
+ *
76
+ * @todo - is there a right order in which to resolve event listeners?
77
+ * Should it matter?
78
+ *
79
+ * @param event
80
+ */
81
+ async dispatchEvent(event: FlatfileEvent | ApiEvent | any): Promise<void> {
82
+ // TODO: validate the json payload as a valid Flatfile event
83
+ // TODO: handle authentication token && API URL so they don't get overwritten here
84
+ if (!(event instanceof FlatfileEvent)) {
85
+ event = new FlatfileEvent(event)
86
+ }
87
+
88
+ if (!this.matchEvent(event, this.filterQuery)) {
89
+ return
90
+ }
91
+
92
+ await this.trigger(event)
93
+
94
+ // dispatch the event on any registered children first
95
+ for (const node of this.nodes) {
96
+ await node.dispatchEvent(event)
97
+ }
98
+ }
99
+
100
+ /**
101
+ * @deprecated legacy shim for receiving events from the VM layer
102
+ * @alias dispatchEvent
103
+ * @param event
104
+ */
105
+ async routeEvent(event: ApiEvent) {
106
+ return this.dispatchEvent(event)
107
+ }
108
+
109
+ /**
110
+ * Actually trigger the event listeners on this particular target
111
+ *
112
+ * @note It is safer for now to run this in series to avoid IO locks and
113
+ * potential race conditions and uncaught errors
114
+ *
115
+ * @param event
116
+ */
117
+ async trigger(event: FlatfileEvent): Promise<void> {
118
+ const listeners = this.getListeners(event)
119
+ for (const cb of listeners) {
120
+ await cb(event)
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Get any listeners from this target subscribing to this event
126
+ *
127
+ * @param event
128
+ */
129
+ public getListeners(event: FlatfileEvent): EventCallback[] {
130
+ return this.listeners
131
+ .filter(([query, filter]) => {
132
+ const globbed = glob(event.topic, query)
133
+ const matched = this.matchEvent(event, filter)
134
+ return globbed && matched
135
+ })
136
+ .map(([_q, _ctx, cb]) => cb)
137
+ }
138
+
139
+ /**
140
+ * Attach more event listeners using a callback function. Used most
141
+ * frequently for plugins.
142
+ *
143
+ * @param fn
144
+ */
145
+ use(fn: (handler: this) => void) {
146
+ fn(this)
147
+ return this
148
+ }
149
+
150
+ /**
151
+ * Filter an event out based on glob filter object
152
+ *
153
+ * @param event
154
+ * @param filter
155
+ */
156
+ public matchEvent(
157
+ event: FlatfileEvent,
158
+ filter: EventFilter | undefined
159
+ ): boolean {
160
+ return filter ? objectMatches(event, filter) : true
161
+ }
162
+ }
163
+
164
+ export type EventFilter = Record<string, Arrayable<string>>
165
+
166
+ export type Arrayable<T> = T | Array<T>
@@ -0,0 +1,80 @@
1
+ import { AuthenticatedClient } from './authenticated.client'
2
+ import { Event } from '@flatfile/api'
3
+
4
+ export class FlatfileEvent extends AuthenticatedClient {
5
+ /**
6
+ * Event ID from the API
7
+ *
8
+ * @example us0_ev_82hgidh9skd
9
+ * @readonly
10
+ *
11
+ */
12
+ public readonly id?: string
13
+
14
+ /**
15
+ * Topic the event was produced on
16
+ *
17
+ * @example workbook:created
18
+ * @readonly
19
+ */
20
+ public readonly topic: string
21
+ public readonly domain: string
22
+ public readonly target: string
23
+ public readonly context: any
24
+ public readonly payload: any
25
+
26
+ constructor(private readonly src: Event) {
27
+ super()
28
+ this.domain = src.domain
29
+ this.topic = src.topic
30
+ this.context = src.context // -> [us0_acc_ihjh8943h9w, space_id, workbook_id]
31
+ this.payload = src.payload
32
+ this.target = src.target || ''
33
+ }
34
+
35
+ /**
36
+ * Should return either event body if expanded already or fetch data from the
37
+ * signed callback URL
38
+ *
39
+ * @todo this should work with the included callback URL
40
+ */
41
+ get data(): Promise<any> {
42
+ const { workbookId, sheetId, versionId } = this.context
43
+
44
+ if (workbookId && sheetId) {
45
+ return this.api
46
+ .getRecords({
47
+ workbookId,
48
+ sheetId,
49
+ versionId,
50
+ includeCounts: false,
51
+ })
52
+ .then((res) => res.data)
53
+ } else {
54
+ return this.payload
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Fetch the actual body of each context item referenced
60
+ * @param _contexts
61
+ * @todo implement when our Event context payload becomes IDs
62
+ */
63
+ // expand(..._contexts: string[]) {
64
+ // await ev.expand('acccount', 'space')
65
+ // ev.account
66
+ // -> accounts.getAccount('id')
67
+ // }
68
+
69
+ /**
70
+ * Respond with an ack progress updates
71
+ * @param _progress
72
+ * @todo later
73
+ */
74
+ // ack(_progress: number = 100) {
75
+ // // call ack API with error
76
+ // // only on ackable events
77
+ // }
78
+ }
79
+
80
+ export type EventCallback = (evt: FlatfileEvent) => void