@flatfile/listener 0.3.19-rc4 → 0.3.19-rc6
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.browser.cjs +695 -0
- package/dist/index.browser.mjs +683 -0
- package/dist/index.cjs +116 -7230
- package/dist/index.d.ts +292 -7
- package/dist/index.js +119 -7224
- package/dist/index.mjs +2 -7105
- package/dist/index.mjs.map +1 -0
- package/package.json +10 -3
- package/dist/event-drivers/Browser.d.ts +0 -18
- package/dist/event-drivers/Browser.d.ts.map +0 -1
- package/dist/event-drivers/FlatfileVirtualMachine.d.ts +0 -18
- package/dist/event-drivers/FlatfileVirtualMachine.d.ts.map +0 -1
- package/dist/event-drivers/Webhook.d.ts +0 -1
- package/dist/event-drivers/Webhook.d.ts.map +0 -1
- package/dist/event-drivers/_EventDriver.d.ts +0 -18
- package/dist/event-drivers/_EventDriver.d.ts.map +0 -1
- package/dist/event-drivers/index.d.ts +0 -4
- package/dist/event-drivers/index.d.ts.map +0 -1
- package/dist/events/authenticated.client.d.ts +0 -15
- package/dist/events/authenticated.client.d.ts.map +0 -1
- package/dist/events/cache.d.ts +0 -8
- package/dist/events/cache.d.ts.map +0 -1
- package/dist/events/event.handler.d.ts +0 -91
- package/dist/events/event.handler.d.ts.map +0 -1
- package/dist/events/event.handler.spec.d.ts +0 -2
- package/dist/events/event.handler.spec.d.ts.map +0 -1
- package/dist/events/flatfile.event.d.ts +0 -69
- package/dist/events/flatfile.event.d.ts.map +0 -1
- package/dist/events/glob.match.d.ts +0 -19
- package/dist/events/glob.match.d.ts.map +0 -1
- package/dist/events/glob.match.spec.d.ts +0 -2
- package/dist/events/glob.match.spec.d.ts.map +0 -1
- package/dist/events/index.d.ts +0 -4
- package/dist/events/index.d.ts.map +0 -1
- package/dist/flatfile.listener.d.ts +0 -63
- package/dist/flatfile.listener.d.ts.map +0 -1
- package/dist/flatfile.listener.spec.d.ts +0 -2
- package/dist/flatfile.listener.spec.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/plugins/index.d.ts +0 -1
- package/dist/plugins/index.d.ts.map +0 -1
- package/dist/plugins/useConfigure.d.ts +0 -1
- package/dist/plugins/useConfigure.d.ts.map +0 -1
- package/dist/utils/helpers.d.ts +0 -2
- package/dist/utils/helpers.d.ts.map +0 -1
|
@@ -0,0 +1,695 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var fetch = require('node-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 gzipHeaders = compressRequestBody
|
|
304
|
+
? { 'Content-Encoding': 'gzip', 'Content-Length': data.length.toString() }
|
|
305
|
+
: {};
|
|
306
|
+
await this.fetch(this.src.dataUrl, {
|
|
307
|
+
method: 'PUT',
|
|
308
|
+
headers: gzipHeaders,
|
|
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;
|