forked from coda/packs-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
1979 lines (1856 loc) · 72.6 KB
/
api.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {ArraySchema} from './schema';
import type {ArrayType} from './api_types';
import type {BooleanSchema} from './schema';
import type {CommonPackFormulaDef} from './api_types';
import {ConnectionRequirement} from './api_types';
import type {ExecutionContext} from './api_types';
import type {FetchRequest} from './api_types';
import type {Identity} from './schema';
import type {NumberHintTypes} from './schema';
import type {NumberSchema} from './schema';
import type {ObjectSchema} from './schema';
import type {ObjectSchemaDefinition} from './schema';
import type {ObjectSchemaDefinitionType} from './schema';
import type {PackFormulaResult} from './api_types';
import type {ParamArgs} from './api_types';
import type {ParamDef} from './api_types';
import type {ParamDefs} from './api_types';
import type {ParamValues} from './api_types';
import type {ParameterType} from './api_types';
import {ParameterTypeInputMap} from './api_types';
import type {ParameterTypeMap} from './api_types';
import type {RequestHandlerTemplate} from './handler_templates';
import type {ResponseHandlerTemplate} from './handler_templates';
import type {Schema} from './schema';
import type {SchemaType} from './schema';
import type {StringHintTypes} from './schema';
import type {StringSchema} from './schema';
import type {SyncExecutionContext} from './api_types';
import {Type} from './api_types';
import type {TypeMap} from './api_types';
import type {TypeOf} from './api_types';
import type {UnionType} from './api_types';
import type {UpdateSyncExecutionContext} from './api_types';
import {ValueType} from './schema';
import {booleanArray} from './api_types';
import {dateArray} from './api_types';
import {deepCopy} from './helpers/object_utils';
import {ensureUnreachable} from './helpers/ensure';
import {fileArray} from './api_types';
import {generateObjectResponseHandler} from './handler_templates';
import {generateRequestHandler} from './handler_templates';
import {htmlArray} from './api_types';
import {imageArray} from './api_types';
import {isPromise} from './helpers/object_utils';
import {makeObjectSchema} from './schema';
import {normalizeSchema} from './schema';
import {numberArray} from './api_types';
import {objectSchemaHelper} from './helpers/migration';
import {stringArray} from './api_types';
export {ExecutionContext};
export {FetchRequest} from './api_types';
/**
* An error whose message will be shown to the end user in the UI when it occurs.
* If an error is encountered in a formula and you want to describe the error
* to the end user, throw a UserVisibleError with a user-friendly message
* and the Coda UI will display the message.
*
* @example
* ```
* if (!url.startsWith("https://")) {
* throw new coda.UserVisibleError("Please provide a valid url.");
* }
* ```
*
* @see
* - [Handling errors - User-visible errors](https://coda.io/packs/build/latest/guides/advanced/errors/#user-visible-errors)
*/
export class UserVisibleError extends Error {
/** @hidden */
readonly isUserVisible = true;
/** @hidden */
readonly internalError: Error | undefined;
/**
* Use to construct a user-visible error.
*/
constructor(message?: string, internalError?: Error) {
super(message);
this.internalError = internalError;
}
}
/**
* The raw HTTP response from a {@link StatusCodeError}.
*/
export interface StatusCodeErrorResponse {
/** The raw body of the HTTP error response. */
body?: any;
/** The headers from the HTTP error response. Many header values are redacted by Coda. */
headers?: {[key: string]: string | string[] | undefined};
}
// StatusCodeError is a simple version of StatusCodeError in request-promise to keep backwards compatibility.
// This tries to replicate its exact structure, massaging as necessary to handle the various transforms
// in our stack.
//
// https://github.com/request/promise-core/blob/master/lib/errors.js#L22
/**
* An error that will be thrown by {@link Fetcher.fetch} when the fetcher response has an
* HTTP status code of 400 or greater.
*
* This class largely models the `StatusCodeError` from the (now deprecated) `request-promise` library,
* which has a quirky structure.
*
* @example
* ```ts
* let response;
* try {
* response = await context.fetcher.fetch({
* method: "GET",
* // Open this URL in your browser to see what the data looks like.
* url: "https://api.artic.edu/api/v1/artworks/123",
* });
* } catch (error) {
* // If the request failed because the server returned a 300+ status code.
* if (coda.StatusCodeError.isStatusCodeError(error)) {
* // Cast the error as a StatusCodeError, for better intellisense.
* let statusError = error as coda.StatusCodeError;
* // If the API returned an error message in the body, show it to the user.
* let message = statusError.body?.detail;
* if (message) {
* throw new coda.UserVisibleError(message);
* }
* }
* // The request failed for some other reason. Re-throw the error so that it
* // bubbles up.
* throw error;
* }
* ```
*
* @see [Fetching remote data - Errors](https://coda.io/packs/build/latest/guides/basics/fetcher/#errors)
*/
export class StatusCodeError extends Error {
/**
* The name of the error, for identification purposes.
*/
override name: string = 'StatusCodeError';
/**
* The HTTP status code, e.g. `404`.
*/
statusCode: number;
/**
* The parsed body of the HTTP response.
*/
body: any;
/**
* Alias for {@link body}.
*/
error: any;
/**
* The original fetcher request used to make this HTTP request.
*/
options: FetchRequest;
/**
* The raw HTTP response, including headers.
*/
response: StatusCodeErrorResponse;
/** @hidden */
constructor(statusCode: number, body: any, options: FetchRequest, response: StatusCodeErrorResponse) {
super(`${statusCode} - ${JSON.stringify(body)}`);
this.statusCode = statusCode;
this.body = body;
this.error = body;
this.options = options;
let responseBody = response?.body;
if (typeof responseBody === 'object') {
// "request-promise"'s error.response.body is always the original, unparsed response body,
// while our fetcher service may attempt a JSON.parse for any response body and alter the behavior.
// Here we attempt to restore the original response body for a few v1 packs compatibility.
responseBody = JSON.stringify(responseBody);
}
this.response = {...response, body: responseBody};
}
/** Returns if the error is an instance of StatusCodeError. Note that `instanceof` may not work. */
static isStatusCodeError(err: any): err is StatusCodeError {
return 'name' in err && err.name === StatusCodeError.name;
}
}
/**
* Throw this error if the user needs to re-authenticate to gain OAuth scopes that have been added
* to the pack since their connection was created, or scopes that are specific to a certain formula.
* This is useful because Coda will always attempt to execute a formula even if a user has not yet
* re-authenticated with all relevant scopes.
*
* You don't *always* need to throw this specific error, as Coda will interpret a 403 (Forbidden)
* status code error as a MissingScopesError when the user's connection was made without all
* currently relevant scopes. This error exists because that default behavior is insufficient if
* the OAuth service does not set a 403 status code (the OAuth spec doesn't specifically require
* them to, after all).
*
* @example
* ```ts
* try {
* let response = context.fetcher.fetch({
* // ...
* });
* } catch (error) {
* // Determine if the error is due to missing scopes.
* if (error.statusCode == 400 && error.body?.message.includes("permission")) {
* throw new coda.MissingScopesError();
* }
* // Else handle or throw the error as normal.
* }
* ```
*
* @see
* - [Guide: Authenticating using OAuth](https://coda.io/packs/build/latest/guides/basics/authentication/oauth2/#triggering-a-prompt)
*/
export class MissingScopesError extends Error {
/**
* The name of the error, for identification purposes.
*/
override name: string = 'MissingScopesError';
/** @hidden */
constructor(message?: string) {
super(message || 'Additional permissions are required');
}
/** Returns if the error is an instance of MissingScopesError. Note that `instanceof` may not work. */
static isMissingScopesError(err: any): err is MissingScopesError {
return 'name' in err && err.name === MissingScopesError.name;
}
}
/**
* The result of defining a sync table. Should not be necessary to use directly,
* instead, define sync tables using {@link makeSyncTable}.
*/
export interface SyncTableDef<
K extends string,
L extends string,
ParamDefsT extends ParamDefs,
SchemaT extends ObjectSchema<K, L>,
> {
/** See {@link SyncTableOptions.name} */
name: string;
/** See {@link SyncTableOptions.description} */
description?: string;
/** See {@link SyncTableOptions.schema} */
schema: SchemaT;
/**
* The `identityName` is persisted for all sync tables so that a dynamic schema
* can be annotated with an identity automatically.
*
* See {@link SyncTableOptions.identityName} for more details.
*/
identityName: string;
/** See {@link SyncTableOptions.formula} */
getter: SyncFormula<K, L, ParamDefsT, SchemaT>;
/** See {@link DynamicOptions.getSchema} */
getSchema?: MetadataFormula;
/** See {@link DynamicOptions.entityName} */
entityName?: string;
/** See {@link DynamicOptions.defaultAddDynamicColumns} */
defaultAddDynamicColumns?: boolean;
}
/**
* Type definition for a Dynamic Sync Table. Should not be necessary to use directly,
* instead, define dynamic sync tables using {@link makeDynamicSyncTable}.
*/
export interface DynamicSyncTableDef<
K extends string,
L extends string,
ParamDefsT extends ParamDefs,
SchemaT extends ObjectSchema<K, L>,
> extends SyncTableDef<K, L, ParamDefsT, SchemaT> {
/** Identifies this sync table as dynamic. */
isDynamic: true;
/** See {@link DynamicSyncTableOptions.getSchema} */
getSchema: MetadataFormula;
/** See {@link DynamicSyncTableOptions.getName} */
getName: MetadataFormula;
/** See {@link DynamicSyncTableOptions.getDisplayUrl} */
getDisplayUrl: MetadataFormula;
/** See {@link DynamicSyncTableOptions.listDynamicUrls} */
listDynamicUrls?: MetadataFormula;
}
/**
* Container for arbitrary data about which page of data to retrieve in this sync invocation.
*
* Sync formulas fetch one reasonable size "page" of data per invocation such that the formula
* can be invoked quickly. The end result of a sync is the concatenation of the results from
* each individual invocation.
*
* To instruct Coda to fetch a subsequent result page, return a `Continuation` that
* describes which page of results to fetch next. The continuation will be passed verbatim
* as an input to the subsequent invocation of the sync formula.
*
* The contents of this object are entirely up to the pack author.
*
* Examples:
*
* ```
* {nextPage: 3}
* ```
*
* ```
* {nextPageUrl: 'https://someapi.com/api/items?pageToken=asdf123'}
* ```
*/
export interface Continuation {
[key: string]: string | number | {[key: string]: string | number};
}
/**
* Type definition for the formula that implements a sync table.
* Should not be necessary to use directly, see {@link makeSyncTable}
* for defining a sync table.
*/
export type GenericSyncFormula = SyncFormula<any, any, ParamDefs, any>;
/**
* Type definition for the return value of a sync table.
* Should not be necessary to use directly, see {@link makeSyncTable}
* for defining a sync table.
*/
export type GenericSyncFormulaResult = SyncFormulaResult<any, any, any>;
/**
* Type definition for a static (non-dynamic) sync table.
* Should not be necessary to use directly, see {@link makeSyncTable}
* for defining a sync table.
*/
export type GenericSyncTable = SyncTableDef<any, any, ParamDefs, any>;
/**
* Type definition for a dynamic sync table.
* Should not be necessary to use directly, see {@link makeDynamicSyncTable}
* for defining a sync table.
*/
export type GenericDynamicSyncTable = DynamicSyncTableDef<any, any, ParamDefs, any>;
/**
* Union of type definitions for sync tables..
* Should not be necessary to use directly, see {@link makeSyncTable} or {@link makeDynamicSyncTable}
* for defining a sync table.
*/
export type SyncTable = GenericSyncTable | GenericDynamicSyncTable;
/**
* Helper to determine if an error is considered user-visible and can be shown in the UI.
* See {@link UserVisibleError}.
* @param error Any error object.
*/
export function isUserVisibleError(error: Error): error is UserVisibleError {
return 'isUserVisible' in error && (error as any).isUserVisible;
}
export function isDynamicSyncTable(syncTable: SyncTable): syncTable is GenericDynamicSyncTable {
return 'isDynamic' in syncTable;
}
export function wrapMetadataFunction(
fnOrFormula: MetadataFormula | MetadataFunction | undefined,
): MetadataFormula | undefined {
return typeof fnOrFormula === 'function' ? makeMetadataFormula(fnOrFormula) : fnOrFormula;
}
function transformToArraySchema<ResultT extends PackFormulaResult>(schema?: any): ResultT {
if (schema?.type === ValueType.Array) {
return schema;
} else {
return {
type: ValueType.Array,
items: schema,
} as ResultT;
}
}
export function wrapGetSchema(getSchema: MetadataFormula | undefined): MetadataFormula | undefined {
if (!getSchema) {
return;
}
return {
...getSchema,
execute<ParamsT extends [ParamDef<Type.string>, ParamDef<Type.string>], ResultT extends PackFormulaResult>(
params: ParamValues<ParamsT>,
context: ExecutionContext,
): Promise<ResultT> | ResultT {
const schema = getSchema.execute(params, context);
if (isPromise<ResultT>(schema)) {
return schema.then(value => transformToArraySchema(value));
} else {
return transformToArraySchema(schema);
}
},
};
}
/**
* List of ParameterTypes that support autocomplete.
*/
export type AutocompleteParameterTypes =
| ParameterType.Number
| ParameterType.String
| ParameterType.StringArray
| ParameterType.SparseStringArray;
/**
* Mapping of autocomplete-enabled ParameterTypes to the underlying Type that should be returned
* by the autocomplete parameter.
*/
export interface AutocompleteParameterTypeMapping {
[ParameterType.Number]: Type.number;
[ParameterType.String]: Type.string;
[ParameterType.StringArray]: Type.string;
[ParameterType.SparseStringArray]: Type.string;
}
/** Options you can specify when defining a parameter using {@link makeParameter}. */
export type ParameterOptions<T extends ParameterType> = Omit<ParamDef<ParameterTypeMap[T]>, 'type' | 'autocomplete'> & {
type: T;
autocomplete?: T extends AutocompleteParameterTypes
? MetadataFormulaDef | Array<TypeMap[AutocompleteParameterTypeMapping[T]] | SimpleAutocompleteOption<T>>
: undefined;
};
/**
* Equivalent to {@link ParamDef}. A helper type to generate a param def based
* on the inputs to {@link makeParameter}.
*/
export type ParamDefFromOptionsUnion<T extends ParameterType, O extends ParameterOptions<T>> = Omit<
O,
'type' | 'autocomplete'
> & {
type: O extends ParameterOptions<infer S> ? ParameterTypeMap[S] : never;
autocomplete: MetadataFormula;
};
/**
* Create a definition for a parameter for a formula or sync.
*
* @example
* ```
* makeParameter({type: ParameterType.String, name: 'myParam', description: 'My description'});
* ```
*
* @example
* ```
* makeParameter({type: ParameterType.StringArray, name: 'myArrayParam', description: 'My description'});
* ```
*/
export function makeParameter<T extends ParameterType, O extends ParameterOptions<T>>(
paramDefinition: O,
): ParamDefFromOptionsUnion<T, O> {
const {type, autocomplete: autocompleteDefOrItems, ...rest} = paramDefinition;
const actualType = ParameterTypeInputMap[type];
let autocomplete: MetadataFormula | undefined;
if (Array.isArray(autocompleteDefOrItems)) {
const autocompleteDef = makeSimpleAutocompleteMetadataFormula(autocompleteDefOrItems);
autocomplete = wrapMetadataFunction(autocompleteDef);
} else {
autocomplete = wrapMetadataFunction(autocompleteDefOrItems);
}
return Object.freeze({...rest, autocomplete, type: actualType}) as ParamDefFromOptionsUnion<T, O>;
}
// Other parameter helpers below here are obsolete given the above generate parameter makers.
/** @deprecated */
export function makeStringParameter(
name: string,
description: string,
args: ParamArgs<Type.string> = {},
): ParamDef<Type.string> {
return Object.freeze({...args, name, description, type: Type.string as Type.string});
}
/** @deprecated */
export function makeStringArrayParameter(
name: string,
description: string,
args: ParamArgs<ArrayType<Type.string>> = {},
): ParamDef<ArrayType<Type.string>> {
return Object.freeze({...args, name, description, type: stringArray});
}
/** @deprecated */
export function makeNumericParameter(
name: string,
description: string,
args: ParamArgs<Type.number> = {},
): ParamDef<Type.number> {
return Object.freeze({...args, name, description, type: Type.number as Type.number});
}
/** @deprecated */
export function makeNumericArrayParameter(
name: string,
description: string,
args: ParamArgs<ArrayType<Type.number>> = {},
): ParamDef<ArrayType<Type.number>> {
return Object.freeze({...args, name, description, type: numberArray});
}
/** @deprecated */
export function makeBooleanParameter(
name: string,
description: string,
args: ParamArgs<Type.boolean> = {},
): ParamDef<Type.boolean> {
return Object.freeze({...args, name, description, type: Type.boolean as Type.boolean});
}
/** @deprecated */
export function makeBooleanArrayParameter(
name: string,
description: string,
args: ParamArgs<ArrayType<Type.boolean>> = {},
): ParamDef<ArrayType<Type.boolean>> {
return Object.freeze({...args, name, description, type: booleanArray});
}
/** @deprecated */
export function makeDateParameter(
name: string,
description: string,
args: ParamArgs<Type.date> = {},
): ParamDef<Type.date> {
return Object.freeze({...args, name, description, type: Type.date as Type.date});
}
/** @deprecated */
export function makeDateArrayParameter(
name: string,
description: string,
args: ParamArgs<ArrayType<Type.date>> = {},
): ParamDef<ArrayType<Type.date>> {
return Object.freeze({...args, name, description, type: dateArray});
}
/** @deprecated */
export function makeHtmlParameter(
name: string,
description: string,
args: ParamArgs<Type.html> = {},
): ParamDef<Type.html> {
return Object.freeze({...args, name, description, type: Type.html as Type.html});
}
/** @deprecated */
export function makeHtmlArrayParameter(
name: string,
description: string,
args: ParamArgs<ArrayType<Type.html>> = {},
): ParamDef<ArrayType<Type.html>> {
return Object.freeze({...args, name, description, type: htmlArray});
}
/** @deprecated */
export function makeImageParameter(
name: string,
description: string,
args: ParamArgs<Type.image> = {},
): ParamDef<Type.image> {
return Object.freeze({...args, name, description, type: Type.image as Type.image});
}
/** @deprecated */
export function makeImageArrayParameter(
name: string,
description: string,
args: ParamArgs<ArrayType<Type.image>> = {},
): ParamDef<ArrayType<Type.image>> {
return Object.freeze({...args, name, description, type: imageArray});
}
/** @deprecated */
export function makeFileParameter(
name: string,
description: string,
args: ParamArgs<Type.file> = {},
): ParamDef<Type.file> {
return Object.freeze({...args, name, description, type: Type.file as Type.file});
}
/** @deprecated */
export function makeFileArrayParameter(
name: string,
description: string,
args: ParamArgs<ArrayType<Type.file>> = {},
): ParamDef<ArrayType<Type.file>> {
return Object.freeze({...args, name, description, type: fileArray});
}
/** @deprecated */
export function makeUserVisibleError(msg: string): UserVisibleError {
return new UserVisibleError(msg);
}
/** @deprecated */
export function check(condition: boolean, msg: string) {
if (!condition) {
throw makeUserVisibleError(msg);
}
}
/**
* Base type for the inputs for creating a pack formula.
*/
export interface PackFormulaDef<ParamsT extends ParamDefs, ResultT extends PackFormulaResult>
extends CommonPackFormulaDef<ParamsT> {
/** The JavaScript function that implements this formula */
execute(params: ParamValues<ParamsT>, context: ExecutionContext): Promise<ResultT> | ResultT;
}
export interface StringFormulaDefLegacy<ParamsT extends ParamDefs> extends CommonPackFormulaDef<ParamsT> {
execute(params: ParamValues<ParamsT>, context: ExecutionContext): Promise<string> | string;
response?: {
schema: StringSchema;
};
}
export interface ObjectResultFormulaDef<ParamsT extends ParamDefs, SchemaT extends Schema>
extends PackFormulaDef<ParamsT, object | object[]> {
execute(params: ParamValues<ParamsT>, context: ExecutionContext): Promise<object> | object;
response?: ResponseHandlerTemplate<SchemaT>;
}
/**
* Inputs to declaratively define a formula that returns a list of objects.
* That is, a formula that doesn't require code, which like an {@link EmptyFormulaDef} uses
* a {@link RequestHandlerTemplate} to describe the request to be made, but also includes a
* {@link ResponseHandlerTemplate} to describe the schema of the returned objects.
* These take the place of implementing a JavaScript `execute` function.
*
* This type is generally not used directly, but describes the inputs to {@link makeTranslateObjectFormula}.
*/
export interface ObjectArrayFormulaDef<ParamsT extends ParamDefs, SchemaT extends Schema>
extends Omit<PackFormulaDef<ParamsT, SchemaType<SchemaT>>, 'execute'> {
/** A definition of the request and any parameter transformations to make in order to implement this formula. */
request: RequestHandlerTemplate;
/** A definition of the schema for the object list returned by this function. */
response: ResponseHandlerTemplate<SchemaT>;
}
/**
* Inputs to define an "empty" formula, that is, a formula that uses a {@link RequestHandlerTemplate}
* to define an implementation for the formula rather than implementing an actual `execute` function
* in JavaScript. An empty formula returns a string. To return a list of objects, see
* {@link ObjectArrayFormulaDef}.
*
* This type is generally not used directly, but describes the inputs to {@link makeEmptyFormula}.
*/
export interface EmptyFormulaDef<ParamsT extends ParamDefs> extends Omit<PackFormulaDef<ParamsT, string>, 'execute'> {
/** A definition of the request and any parameter transformations to make in order to implement this formula. */
request: RequestHandlerTemplate;
}
/** The base class for pack formula descriptors. Subclasses vary based on the return type of the formula. */
export type BaseFormula<ParamDefsT extends ParamDefs, ResultT extends PackFormulaResult> = PackFormulaDef<
ParamDefsT,
ResultT
> & {
resultType: TypeOf<ResultT>;
};
/** A pack formula that returns a number. */
export type NumericPackFormula<ParamDefsT extends ParamDefs> = BaseFormula<ParamDefsT, number> & {
schema?: NumberSchema;
};
/** A pack formula that returns a boolean. */
export type BooleanPackFormula<ParamDefsT extends ParamDefs> = BaseFormula<ParamDefsT, boolean> & {
schema?: BooleanSchema;
};
/** A pack formula that returns a string. */
export type StringPackFormula<ParamDefsT extends ParamDefs> = BaseFormula<ParamDefsT, SchemaType<StringSchema>> & {
schema?: StringSchema;
};
/** A pack formula that returns a JavaScript object. */
export type ObjectPackFormula<ParamDefsT extends ParamDefs, SchemaT extends Schema> = Omit<
BaseFormula<ParamDefsT, SchemaType<SchemaT>>,
'execute'
> & {
schema?: SchemaT;
// object formula execute result property key will be normalized.
execute(params: ParamValues<ParamDefsT>, context: ExecutionContext): Promise<object> | object;
};
// can't use a map (e.g. ResultTypeToFormulaTypeMap<ParamDefs, SchemaT>[ResultT]) here since
// ParamDefsT isn't propagated correctly.
/**
* A pack formula, complete with metadata about the formula like its name, description, and parameters,
* as well as the implementation of that formula.
*
* This is the type for an actual user-facing formula, rather than other formula-shaped resources within a
* pack, like an autocomplete metadata formula or a sync getter formula.
*/
export type Formula<
ParamDefsT extends ParamDefs = ParamDefs,
ResultT extends ValueType = ValueType,
SchemaT extends Schema = Schema,
> = ResultT extends ValueType.String
? StringPackFormula<ParamDefsT>
: ResultT extends ValueType.Number
? NumericPackFormula<ParamDefsT>
: ResultT extends ValueType.Boolean
? BooleanPackFormula<ParamDefsT>
: ResultT extends ValueType.Array
? ObjectPackFormula<ParamDefsT, ArraySchema<SchemaT>>
: ObjectPackFormula<ParamDefsT, SchemaT>;
type V2PackFormula<ParamDefsT extends ParamDefs, SchemaT extends Schema = Schema> =
| StringPackFormula<ParamDefsT>
| NumericPackFormula<ParamDefsT>
| BooleanPackFormula<ParamDefsT>
| ObjectPackFormula<ParamDefsT, ArraySchema<SchemaT>>
| ObjectPackFormula<ParamDefsT, SchemaT>;
/**
* The union of types that represent formula definitions, including standard formula definitions,
* metadata formulas, and the formulas that implement sync tables.
*
* It should be very uncommon to need to use this type, it is most common in meta analysis of the
* contents of a pack for for Coda internal use.
*/
export type TypedPackFormula = Formula | GenericSyncFormula;
export type TypedObjectPackFormula = ObjectPackFormula<ParamDefs, Schema>;
/** @hidden */
export type PackFormulaMetadata = Omit<TypedPackFormula, 'execute' | 'executeUpdate'>;
/** @hidden */
export type ObjectPackFormulaMetadata = Omit<TypedObjectPackFormula, 'execute'>;
export function isObjectPackFormula(fn: PackFormulaMetadata): fn is ObjectPackFormulaMetadata {
return fn.resultType === Type.object;
}
export function isStringPackFormula(fn: BaseFormula<ParamDefs, any>): fn is StringPackFormula<ParamDefs> {
return fn.resultType === Type.string;
}
export function isSyncPackFormula(fn: BaseFormula<ParamDefs, any>): fn is GenericSyncFormula {
return Boolean((fn as GenericSyncFormula).isSyncFormula);
}
/**
* The return value from the formula that implements a sync table. Each sync formula invocation
* returns one reasonable size page of results. The formula may also return a continuation, indicating
* that the sync formula should be invoked again to get a next page of results. Sync functions
* are called repeatedly until there is no continuation returned.
*/
export interface SyncFormulaResult<K extends string, L extends string, SchemaT extends ObjectSchemaDefinition<K, L>> {
/** The list of results from this page. */
result: Array<ObjectSchemaDefinitionType<K, L, SchemaT>>;
/**
* A marker indicating where the next sync formula invocation should pick up to get the next page of results.
* The contents of this object are entirely of your choosing. Sync formulas are called repeatedly
* until there is no continuation returned.
*/
continuation?: Continuation;
}
/**
* Type definition for the parameter used to pass in a batch of updates to a sync table update function.
* @hidden
*/
export interface SyncUpdate<K extends string, L extends string, SchemaT extends ObjectSchemaDefinition<K, L>> {
previousValue: ObjectSchemaDefinitionType<K, L, SchemaT>;
newValue: ObjectSchemaDefinitionType<K, L, SchemaT>;
updatedFields: string[];
}
/**
* Generic type definition for the parameter used to pass in updates to a sync table update function.
* @hidden
*/
export type GenericSyncUpdate = SyncUpdate<any, any, any>;
/**
* Type definition for a single update result returned by a sync table update function.
* @hidden
*/
export interface SyncUpdateSingleResult<
K extends string,
L extends string,
SchemaT extends ObjectSchemaDefinition<K, L>,
> {
newValue?: ObjectSchemaDefinitionType<K, L, SchemaT>;
error?: Error;
}
/**
* Generic type definition for a single update result returned by a sync table update function.
* @hidden
*/
export type GenericSyncUpdateSingleResult = SyncUpdateSingleResult<any, any, any>;
/**
* Type definition for the batched result returned by a sync table update function.
* @hidden
*/
export interface SyncUpdateResult<K extends string, L extends string, SchemaT extends ObjectSchemaDefinition<K, L>> {
result: Array<SyncUpdateSingleResult<K, L, SchemaT>>;
}
/**
* Generic type definition for the result returned by a sync table update function.
* @hidden
*/
export type GenericSyncUpdateResult = SyncUpdateResult<any, any, any>;
/**
* Inputs for creating the formula that implements a sync table.
*/
export interface SyncFormulaDef<
K extends string,
L extends string,
ParamDefsT extends ParamDefs,
SchemaT extends ObjectSchemaDefinition<K, L>,
> extends CommonPackFormulaDef<ParamDefsT> {
/**
* The JavaScript function that implements this sync.
*
* This function takes in parameters and a sync context which may have a continuation
* from a previous invocation, and fetches and returns one page of results, as well
* as another continuation if there are more result to fetch.
*/
execute(params: ParamValues<ParamDefsT>, context: SyncExecutionContext): Promise<SyncFormulaResult<K, L, SchemaT>>;
/**
* If the table supports object updates, the maximum number of objects that will be sent to the pack
* in a single batch. Defaults to 1 if not specified.
*/
/** @hidden */
maxUpdateBatchSize?: number;
/**
* The JavaScript function that implements this sync update if the table supports updates.
*
* This function takes in parameters, updated sync table objects, and a sync context,
* and is responsible for pushing those updated objects to the external system then returning
* the new state of each object.
*/
/** @hidden */
executeUpdate?(
params: ParamValues<ParamDefsT>,
updates: Array<SyncUpdate<K, L, SchemaT>>,
context: UpdateSyncExecutionContext,
): Promise<SyncUpdateResult<K, L, SchemaT>>;
}
/**
* The result of defining the formula that implements a sync table.
*
* There is no need to use this type directly. You provide a {@link SyncFormulaDef} as an
* input to {@link makeSyncTable} which outputs definitions of this type.
*/
export type SyncFormula<
K extends string,
L extends string,
ParamDefsT extends ParamDefs,
SchemaT extends ObjectSchema<K, L>,
> = SyncFormulaDef<K, L, ParamDefsT, SchemaT> & {
resultType: TypeOf<SchemaType<SchemaT>>;
isSyncFormula: true;
schema?: ArraySchema;
supportsUpdates?: boolean;
};
/**
* @deprecated
*
* Helper for returning the definition of a formula that returns a number. Adds result type information
* to a generic formula definition.
*
* @param definition The definition of a formula that returns a number.
*/
export function makeNumericFormula<ParamDefsT extends ParamDefs>(
definition: PackFormulaDef<ParamDefsT, number>,
): NumericPackFormula<ParamDefsT> {
return Object.assign({}, definition, {resultType: Type.number as Type.number}) as NumericPackFormula<ParamDefsT>;
}
/**
* @deprecated
*
* Helper for returning the definition of a formula that returns a string. Adds result type information
* to a generic formula definition.
*
* @param definition The definition of a formula that returns a string.
*/
export function makeStringFormula<ParamDefsT extends ParamDefs>(
definition: StringFormulaDefLegacy<ParamDefsT>,
): StringPackFormula<ParamDefsT> {
const {response} = definition;
return Object.assign({}, definition, {
resultType: Type.string as Type.string,
...(response && {schema: response.schema}),
}) as StringPackFormula<ParamDefsT>;
}
/**
* Creates a formula definition.
*
* You must indicate the kind of value that this formula returns (string, number, boolean, array, or object)
* using the `resultType` field.
*
* Formulas always return basic types, but you may optionally give a type hint using
* `codaType` to tell Coda how to interpret a given value. For example, you can return
* a string that represents a date, but use `codaType: ValueType.Date` to tell Coda
* to interpret as a date in a document.
*
* If your formula returns an object, you must provide a `schema` property that describes
* the structure of the object. See {@link makeObjectSchema} for how to construct an object schema.
*
* If your formula returns a list (array), you must provide an `items` property that describes
* what the elements of the array are. This could be a simple schema like `{type: ValueType.String}`
* indicating that the array elements are all just strings, or it could be an object schema
* created using {@link makeObjectSchema} if the elements are objects.
*
* @example
* ```
* makeFormula({resultType: ValueType.String, name: 'Hello', ...});
* ```
*
* @example
* ```
* makeFormula({resultType: ValueType.String, codaType: ValueType.Html, name: 'HelloHtml', ...});
* ```
*
* @example
* ```
* makeFormula({resultType: ValueType.Array, items: {type: ValueType.String}, name: 'HelloStringArray', ...});
* ```
*
* @example
* ```
* makeFormula({
* resultType: ValueType.Object,
* schema: makeObjectSchema({type: ValueType.Object, properties: {...}}),
* name: 'HelloObject',
* ...
* });
* ```
*
* @example
* ```
* makeFormula({
* resultType: ValueType.Array,
* items: makeObjectSchema({type: ValueType.Object, properties: {...}}),
* name: 'HelloObjectArray',
* ...
* });
* ```
*/
export function makeFormula<ParamDefsT extends ParamDefs, ResultT extends ValueType, SchemaT extends Schema = Schema>(
fullDefinition: FormulaDefinition<ParamDefsT, ResultT, SchemaT>,
): Formula<ParamDefsT, ResultT, SchemaT> {
let formula: V2PackFormula<ParamDefsT, SchemaT>;
switch (fullDefinition.resultType) {
case ValueType.String: {
// very strange ts knows that fullDefinition.codaType is StringHintTypes but doesn't know if
// fullDefinition is StringFormulaDefV2.
const def: StringFormulaDef<ParamDefsT> & {codaType?: StringHintTypes; formulaSchema?: StringSchema} = {
...fullDefinition,
codaType: 'codaType' in fullDefinition ? fullDefinition.codaType : undefined,
formulaSchema: 'schema' in fullDefinition ? fullDefinition.schema : undefined,
};
const {onError: _, resultType: unused, codaType, formulaSchema, ...rest} = def;
const stringFormula: StringPackFormula<ParamDefsT> = {
...rest,
resultType: Type.string,
schema: formulaSchema || (codaType ? {type: ValueType.String, codaType} : undefined),
};
formula = stringFormula;
break;
}
case ValueType.Number: {
const def: NumericFormulaDef<ParamDefsT> & {codaType?: NumberHintTypes; formulaSchema?: NumberSchema} = {
...fullDefinition,
codaType: 'codaType' in fullDefinition ? fullDefinition.codaType : undefined,
formulaSchema: 'schema' in fullDefinition ? fullDefinition.schema : undefined,
};
const {onError: _, resultType: unused, codaType, formulaSchema, ...rest} = def;
const numericFormula: NumericPackFormula<ParamDefsT> = {
...rest,
resultType: Type.number,
schema: formulaSchema || (codaType ? {type: ValueType.Number, codaType} : undefined),
};
formula = numericFormula;
break;
}
case ValueType.Boolean: {
const {onError: _, resultType: unused, ...rest} = fullDefinition as BooleanFormulaDef<ParamDefsT>;
const booleanFormula: BooleanPackFormula<ParamDefsT> = {
...rest,
resultType: Type.boolean,
};
formula = booleanFormula;