forked from interval/interval-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
477 lines (424 loc) · 12.1 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
import { z } from 'zod'
import fetch from 'cross-fetch'
import Routes from './classes/Routes'
import IOError from './classes/IOError'
import Logger, { LogLevel } from './classes/Logger'
import Page from './classes/Page'
import {
NOTIFY,
ClientSchema,
HostSchema,
ICE_CONFIG,
IceConfig,
ENQUEUE_ACTION,
DEQUEUE_ACTION,
} from './internalRpcSchema'
import { DuplexRPCHandlers } from './classes/DuplexRPCClient'
import { NotConnectedError, TimeoutError } from './classes/ISocket'
import { SerializableRecord } from './ioSchema'
import type {
ActionCtx,
ActionLogFn,
IO,
IntervalActionHandler,
IntervalActionStore,
NotifyConfig,
IntervalRouteDefinitions,
IntervalPageStore,
PageCtx,
IntervalActionDefinition,
IntervalErrorHandler,
} from './types'
import IntervalError from './classes/IntervalError'
import IntervalClient, {
DEFAULT_WEBSOCKET_ENDPOINT,
getHttpEndpoint,
actionLocalStorage,
pageLocalStorage,
} from './classes/IntervalClient'
import Action from './classes/Action'
import { BasicLayout } from './classes/Layout'
import { Evt } from 'evt'
import superjson from './utils/superjson'
export type {
ActionCtx,
ActionLogFn,
IO,
IntervalActionHandler,
IntervalActionDefinition,
IntervalActionStore,
}
export interface InternalConfig {
apiKey?: string
routes?: IntervalRouteDefinitions
routesDirectory?: string
// TODO: Mark as deprecated soon, remove soon afterward
actions?: Record<string, IntervalActionDefinition>
// TODO: Mark as deprecated soon, remove soon afterward
groups?: Record<string, Page>
endpoint?: string
logLevel?: LogLevel
retryIntervalMs?: number
retryChunkIntervalMs?: number
pingIntervalMs?: number
connectTimeoutMs?: number
sendTimeoutMs?: number
pingTimeoutMs?: number
maxResendAttempts?: number
completeHttpRequestDelayMs?: number
closeUnresponsiveConnectionTimeoutMs?: number
reinitializeBatchTimeoutMs?: number
onError?: IntervalErrorHandler
verboseMessageLogs?: boolean
/* @internal */ getClientHandlers?: () =>
| DuplexRPCHandlers<ClientSchema>
| undefined
/* @internal */ setHostHandlers?: (
handlers: DuplexRPCHandlers<HostSchema>
) => void
}
export interface QueuedAction {
id: string
assignee?: string
params?: SerializableRecord
}
export function getActionStore(): IntervalActionStore {
if (!actionLocalStorage) {
throw new IntervalError(
'Global io and ctx objects are only available in a Node.js context.'
)
}
const store = actionLocalStorage.getStore()
if (!store) {
throw new IntervalError(
'Global io and ctx objects can only be used inside a Page or Action.'
)
}
return store
}
export function getPageStore(): IntervalPageStore {
if (!pageLocalStorage) {
throw new IntervalError(
'Global io and ctx objects are only available in a Node.js context.'
)
}
const store = pageLocalStorage.getStore()
if (!store) {
throw new IntervalError(
'Global io and ctx objects can only be used inside a Page or Action.'
)
}
return store
}
export function getSomeStore(): IntervalActionStore | IntervalPageStore {
try {
return getPageStore()
} catch (err) {
return getActionStore()
}
}
// prettier-ignore
export const io: IO = {
get group() { return getActionStore().io.group },
get confirm() { return getActionStore().io.confirm },
get confirmIdentity() { return getActionStore().io.confirmIdentity },
get search() { return getActionStore().io.search },
get input() { return getActionStore().io.input },
get select() { return getActionStore().io.select },
get display() {
try {
return getPageStore().display
} catch (err) {
return getActionStore().io.display
}
},
get experimental() { return getActionStore().io.experimental },
}
// prettier-ignore
export const ctx: ActionCtx & PageCtx = {
get user() { return getSomeStore().ctx.user },
get params() { return getSomeStore().ctx.params },
get environment() { return getSomeStore().ctx.environment },
get loading() { return getSomeStore().ctx.loading },
get log() { return getActionStore().ctx.log },
get organization() { return getSomeStore().ctx.organization },
get action() { return getActionStore().ctx.action },
get page() { return getPageStore().ctx.page },
get notify() { return getActionStore().ctx.notify },
get redirect() { return getSomeStore().ctx.redirect },
}
export default class Interval {
config: InternalConfig
#logger: Logger
#client: IntervalClient | undefined
#apiKey: string | undefined
#httpEndpoint: string
#groupChangeCtx = Evt.newCtx()
routes: Routes
constructor(config: InternalConfig) {
this.config = config
this.#apiKey = config.apiKey
this.#logger = new Logger(config.logLevel)
this.#httpEndpoint = getHttpEndpoint(
config.endpoint ?? DEFAULT_WEBSOCKET_ENDPOINT
)
this.routes = new Routes(
this,
this.#httpEndpoint,
this.#logger,
this.#groupChangeCtx,
this.#apiKey
)
const routes = {
...this.config.actions,
...this.config.groups,
...this.config.routes,
}
if (routes) {
for (const group of Object.values(routes)) {
if (group instanceof Page) {
group.onChange.attach(this.#groupChangeCtx, () => {
this.client?.handleActionsChange(this.config)
})
}
}
}
}
// TODO: Mark as deprecated soon, remove soon afterward
get actions(): Routes {
return this.routes
}
protected get apiKey(): string | undefined {
return this.#apiKey
}
protected get httpEndpoint(): string {
return this.#httpEndpoint
}
get #log() {
return this.#logger
}
protected get log() {
return this.#logger
}
get isConnected(): boolean {
return this.#client?.isConnected ?? false
}
/**
* Establish the persistent connection to Interval.
*/
async listen() {
if (!this.#client) {
this.#client = new IntervalClient(this, this.config)
}
return this.#client.listen()
}
async ping(): Promise<boolean> {
if (!this.#client) throw new NotConnectedError()
return this.#client.ping()
}
/**
* Immediately terminate the connection to interval, terminating any actions currently in progress.
*/
immediatelyClose() {
return this.#client?.immediatelyClose()
}
/**
* Safely close the connection to Interval, preventing new actions from being launched and closing the persistent connection afterward. Resolves when the connection is successfully safely closed.
*/
async safelyClose(): Promise<void> {
return this.#client?.safelyClose()
}
/* @internal */ get client() {
return this.#client
}
async fetchIceConfig(): Promise<IceConfig> {
const response = await fetch(`${this.#httpEndpoint}/api/ice-config`, {
method: 'GET',
headers: {
Authorization: `Bearer ${this.#apiKey}`,
},
}).then(r => r.json())
const parsed = ICE_CONFIG.parse(response)
return parsed
}
/**
* Sends a custom notification to Interval users via email or Slack. To send Slack notifications, you'll need to connect your Slack workspace to the Interval app in your organization settings.
*
* **Usage:**
*
* ```typescript
* await ctx.notify({
* message: "A charge of $500 was refunded",
* title: "Refund over threshold",
* delivery: [
* {
* to: "#interval-notifications",
* method: "SLACK",
* },
* {
* to: "[email protected]",
* },
* ],
* });
* ```
*/
async notify(config: NotifyConfig): Promise<void> {
if (
!config.transactionId &&
(this.#client?.environment === 'development' ||
(!this.#client?.environment && !this.#apiKey?.startsWith('live_')))
) {
this.#log.warn(
'Calls to notify() outside of a transaction currently have no effect when Interval is instantiated with a development API key. Please use a live key to send notifications.'
)
}
const clientHandlers = this.config.getClientHandlers?.()
if (clientHandlers) {
clientHandlers.NOTIFY({
...config,
transactionId: config.transactionId ?? 'demo',
deliveries: config.delivery || [
{
method: 'EMAIL',
to: '[email protected]',
},
],
})
return
}
let body: z.infer<(typeof NOTIFY)['inputs']>
try {
body = NOTIFY.inputs.parse({
...config,
deliveryInstructions: config.delivery,
createdAt: new Date().toISOString(),
})
} catch (err) {
this.#logger.debug(err)
throw new IntervalError('Invalid input.')
}
const response = await fetch(`${this.#httpEndpoint}/api/notify`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.#apiKey}`,
},
body: JSON.stringify(body),
})
.then(r => r.json())
.then(r => NOTIFY.returns.parseAsync(r))
.catch(err => {
this.#logger.debug(err)
throw new IntervalError('Received invalid API response.')
})
if (response.type === 'error') {
throw new IntervalError(
`There was a problem sending the notification: ${response.message}`
)
}
}
#getQueueAddress(path: string): string {
if (path.startsWith('/')) {
path = path.substring(1)
}
return `${this.#httpEndpoint}/api/actions/${path}`
}
/**
* Enqueue an action to be completed, with an optional `assignee` email to assign the action to, and optional `params` which will be passed to the action as `ctx.params`. Assigned actions will be displayed in users' dashboards as a task list.
*/
async enqueue(
slug: string,
{ assignee, params }: Pick<QueuedAction, 'assignee' | 'params'> = {}
): Promise<QueuedAction> {
let body: z.infer<(typeof ENQUEUE_ACTION)['inputs']>
try {
const { json, meta } = params
? superjson.serialize(params)
: { json: undefined, meta: undefined }
body = ENQUEUE_ACTION.inputs.parse({
assignee,
slug,
params: json,
paramsMeta: meta,
})
} catch (err) {
this.#logger.debug(err)
throw new IntervalError('Invalid input.')
}
const response = await fetch(this.#getQueueAddress('enqueue'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.#apiKey}`,
},
body: JSON.stringify(body),
})
.then(r => r.json())
.then(r => ENQUEUE_ACTION.returns.parseAsync(r))
.catch(err => {
this.#logger.debug(err)
throw new IntervalError('Received invalid API response.')
})
if (response.type === 'error') {
throw new IntervalError(
`There was a problem enqueuing the action: ${response.message}`
)
}
return {
id: response.id,
assignee,
params,
}
}
/**
* Dequeue a previously assigned action which was created with `interval.enqueue()`.
*/
async dequeue(id: string): Promise<QueuedAction> {
let body: z.infer<(typeof DEQUEUE_ACTION)['inputs']>
try {
body = DEQUEUE_ACTION.inputs.parse({
id,
})
} catch (err) {
this.#logger.debug(err)
throw new IntervalError('Invalid input.')
}
const response = await fetch(this.#getQueueAddress('dequeue'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.#apiKey}`,
},
body: JSON.stringify(body),
})
.then(r => r.json())
.then(r => DEQUEUE_ACTION.returns.parseAsync(r))
.catch(err => {
this.#logger.debug(err)
throw new IntervalError('Received invalid API response.')
})
if (response.type === 'error') {
throw new IntervalError(
`There was a problem enqueuing the action: ${response.message}`
)
}
let { type, params, paramsMeta, ...rest } = response
if (paramsMeta && params) {
params = superjson.deserialize({ json: params, meta: paramsMeta })
}
return {
...rest,
params,
}
}
}
export {
Interval,
IOError,
IntervalError,
NotConnectedError,
TimeoutError,
Action,
Page,
BasicLayout as Layout,
}