@decodo/sdk-ts 4.0.0 → 4.1.0
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/README.md +56 -4
- package/build/cjs/index.cjs +5557 -191
- package/build/cjs/index.d.cts +174 -2
- package/build/esm/api/flows.d.ts +52 -0
- package/build/esm/api/flows.js +301 -0
- package/build/esm/api/limits.d.ts +6 -0
- package/build/esm/api/limits.js +36 -0
- package/build/esm/api/results.d.ts +2 -0
- package/build/esm/api/results.js +87 -0
- package/build/esm/api/tools.d.ts +6 -0
- package/build/esm/api/tools.js +185 -0
- package/build/esm/api/web-scraping-api.d.ts +2 -0
- package/build/esm/api/web-scraping-api.js +3 -0
- package/build/esm/errors.d.ts +10 -0
- package/build/esm/errors.js +20 -0
- package/build/esm/generated/flows.d.ts +3 -0
- package/build/esm/generated/flows.js +4633 -0
- package/build/esm/index.d.ts +8 -2
- package/build/esm/index.js +5 -1
- package/build/esm/schema/bundled-schema.d.ts +7 -2
- package/build/esm/schema/bundled-schema.js +14 -0
- package/build/esm/schema/remote-schema.d.ts +7 -2
- package/build/esm/schema/remote-schema.js +75 -14
- package/build/esm/schema/types.d.ts +95 -1
- package/package.json +1 -1
package/build/cjs/index.d.cts
CHANGED
|
@@ -587,6 +587,93 @@ export type RemoteSchemaLoadOptions = {
|
|
|
587
587
|
cachePath?: string;
|
|
588
588
|
ttlMs?: number;
|
|
589
589
|
};
|
|
590
|
+
export type IrOperation = {
|
|
591
|
+
method: string;
|
|
592
|
+
path: string;
|
|
593
|
+
requestSchema?: JSONSchema4;
|
|
594
|
+
};
|
|
595
|
+
export type IrCallFlow = {
|
|
596
|
+
pattern: "call";
|
|
597
|
+
run: string;
|
|
598
|
+
};
|
|
599
|
+
export type IrJobFlow = {
|
|
600
|
+
pattern: "job";
|
|
601
|
+
start: string;
|
|
602
|
+
status: string;
|
|
603
|
+
results: string;
|
|
604
|
+
cancel?: string;
|
|
605
|
+
idField: string;
|
|
606
|
+
statusField: string;
|
|
607
|
+
pendingStatuses: string[];
|
|
608
|
+
failedStatuses: string[];
|
|
609
|
+
resultsQuery?: Record<string, string>;
|
|
610
|
+
pagination?: {
|
|
611
|
+
itemsField: string;
|
|
612
|
+
nextUrlField: string;
|
|
613
|
+
};
|
|
614
|
+
pollSeconds?: number;
|
|
615
|
+
};
|
|
616
|
+
export type IrBatchFlow = {
|
|
617
|
+
pattern: "batch";
|
|
618
|
+
start: string;
|
|
619
|
+
itemsField: string;
|
|
620
|
+
job: string;
|
|
621
|
+
};
|
|
622
|
+
export type IrFlow = IrCallFlow | IrJobFlow | IrBatchFlow;
|
|
623
|
+
export type IrKeyCheck = {
|
|
624
|
+
flow: string;
|
|
625
|
+
params: Record<string, unknown>;
|
|
626
|
+
};
|
|
627
|
+
export type IrResultFailure = {
|
|
628
|
+
path: string;
|
|
629
|
+
equals?: string | number | boolean;
|
|
630
|
+
atLeast?: number;
|
|
631
|
+
message?: string;
|
|
632
|
+
code?: string;
|
|
633
|
+
retryable?: true;
|
|
634
|
+
};
|
|
635
|
+
export type IrResult = {
|
|
636
|
+
failures?: IrResultFailure[];
|
|
637
|
+
from?: string;
|
|
638
|
+
fields?: Record<string, string>;
|
|
639
|
+
omit?: string[];
|
|
640
|
+
required?: string[];
|
|
641
|
+
};
|
|
642
|
+
export type IrSurfaceLimits = {
|
|
643
|
+
maxResultChars?: number;
|
|
644
|
+
maxTextChars?: number;
|
|
645
|
+
maxItems?: number;
|
|
646
|
+
maxListValues?: number;
|
|
647
|
+
waitSeconds?: number;
|
|
648
|
+
};
|
|
649
|
+
export type IrSurfaceTool = {
|
|
650
|
+
name: string;
|
|
651
|
+
title?: string;
|
|
652
|
+
description: string;
|
|
653
|
+
group?: string;
|
|
654
|
+
flow: string;
|
|
655
|
+
step?: "start" | "status" | "results" | "cancel";
|
|
656
|
+
result?: IrResult;
|
|
657
|
+
limits?: IrSurfaceLimits;
|
|
658
|
+
target?: string;
|
|
659
|
+
fields?: string[];
|
|
660
|
+
required?: string[];
|
|
661
|
+
fixed?: Record<string, unknown>;
|
|
662
|
+
defaults?: Record<string, unknown>;
|
|
663
|
+
choices?: Record<string, Array<string | number | boolean>>;
|
|
664
|
+
maximums?: Record<string, number>;
|
|
665
|
+
minimums?: Record<string, number>;
|
|
666
|
+
descriptions?: Record<string, string>;
|
|
667
|
+
};
|
|
668
|
+
export type IrSurface = {
|
|
669
|
+
tools: IrSurfaceTool[];
|
|
670
|
+
};
|
|
671
|
+
export type IrFlowSections = {
|
|
672
|
+
operations: Record<string, IrOperation>;
|
|
673
|
+
flows: Record<string, IrFlow>;
|
|
674
|
+
surfaces: Record<string, IrSurface>;
|
|
675
|
+
keyCheck?: IrKeyCheck;
|
|
676
|
+
};
|
|
590
677
|
export type DecodoSchema = {
|
|
591
678
|
getRequestSchema: (target: string) => z.ZodType | undefined;
|
|
592
679
|
listTargets: () => string[];
|
|
@@ -595,6 +682,61 @@ export type DecodoSchema = {
|
|
|
595
682
|
getSharedParameters: () => Record<string, unknown>;
|
|
596
683
|
readonly version?: string;
|
|
597
684
|
};
|
|
685
|
+
export type FlowSchema = DecodoSchema & {
|
|
686
|
+
getOperation: (operation: string) => IrOperation | undefined;
|
|
687
|
+
getFlow: (flow: string) => IrFlow | undefined;
|
|
688
|
+
getSurface: (client: string) => IrSurface | undefined;
|
|
689
|
+
getKeyCheck: () => IrKeyCheck | undefined;
|
|
690
|
+
};
|
|
691
|
+
export type FlowOfPattern = {
|
|
692
|
+
call: IrCallFlow;
|
|
693
|
+
job: IrJobFlow;
|
|
694
|
+
batch: IrBatchFlow;
|
|
695
|
+
};
|
|
696
|
+
export type WaitOptions = {
|
|
697
|
+
pollInterval?: number;
|
|
698
|
+
timeout?: number;
|
|
699
|
+
};
|
|
700
|
+
export type JobResultsOptions = {
|
|
701
|
+
maxItems?: number;
|
|
702
|
+
};
|
|
703
|
+
export type JobResultsPageOptions = {
|
|
704
|
+
cursor?: string;
|
|
705
|
+
maxItems?: number;
|
|
706
|
+
};
|
|
707
|
+
export type JobResultsPage = {
|
|
708
|
+
items: unknown[];
|
|
709
|
+
nextCursor?: string;
|
|
710
|
+
};
|
|
711
|
+
export type JobStatus = Record<string, unknown>;
|
|
712
|
+
export declare class Flows {
|
|
713
|
+
private readonly http;
|
|
714
|
+
private readonly schema;
|
|
715
|
+
private readonly available;
|
|
716
|
+
private readonly validators;
|
|
717
|
+
constructor(http: HttpClient, schema: DecodoSchema, { available }: {
|
|
718
|
+
available: boolean;
|
|
719
|
+
});
|
|
720
|
+
get flowSchema(): FlowSchema;
|
|
721
|
+
describe(flow: string): IrFlow;
|
|
722
|
+
describe<P extends IrFlow["pattern"]>(flow: string, pattern: P): FlowOfPattern[P];
|
|
723
|
+
checkKey(): Promise<void>;
|
|
724
|
+
call(flow: string, params: Record<string, unknown>): Promise<unknown>;
|
|
725
|
+
start(flow: string, params: Record<string, unknown>): Promise<JobStatus>;
|
|
726
|
+
startBatch(flow: string, params: Record<string, unknown>): Promise<JobStatus[]>;
|
|
727
|
+
status(flow: string, jobId: string): Promise<JobStatus>;
|
|
728
|
+
isPending(flow: string, status: JobStatus): boolean;
|
|
729
|
+
hasFailed(flow: string, status: JobStatus): boolean;
|
|
730
|
+
wait(flow: string, jobId: string, { pollInterval, timeout }?: WaitOptions): Promise<JobStatus>;
|
|
731
|
+
results(flow: string, jobId: string, { maxItems }?: JobResultsOptions): Promise<unknown>;
|
|
732
|
+
resultsPage(flow: string, jobId: string, { cursor, maxItems }?: JobResultsPageOptions): Promise<JobResultsPage>;
|
|
733
|
+
cancel(flow: string, jobId: string): Promise<JobStatus>;
|
|
734
|
+
private pollInterval;
|
|
735
|
+
private operation;
|
|
736
|
+
private send;
|
|
737
|
+
private validate;
|
|
738
|
+
private validatorFor;
|
|
739
|
+
}
|
|
598
740
|
/**
|
|
599
741
|
* Fields other than these are dropped before the upstream call.
|
|
600
742
|
*/
|
|
@@ -1016,6 +1158,7 @@ export type WebScrapingApiRoutes = {
|
|
|
1016
1158
|
dataApi?: typeof dataApiEndpoints;
|
|
1017
1159
|
};
|
|
1018
1160
|
export declare class WebScrapingApi {
|
|
1161
|
+
readonly flows: Flows;
|
|
1019
1162
|
private readonly http;
|
|
1020
1163
|
private readonly schemas;
|
|
1021
1164
|
private readonly routes;
|
|
@@ -1057,21 +1200,36 @@ export declare class DecodoClient {
|
|
|
1057
1200
|
readonly webScrapingApi: WebScrapingApi;
|
|
1058
1201
|
constructor(config: DecodoConfig);
|
|
1059
1202
|
}
|
|
1060
|
-
export
|
|
1203
|
+
export type LimitedResult = {
|
|
1204
|
+
text: string;
|
|
1205
|
+
truncated: boolean;
|
|
1206
|
+
};
|
|
1207
|
+
export declare const limitResult: (limits: IrSurfaceLimits | undefined, value: unknown) => LimitedResult;
|
|
1208
|
+
export declare const readResult: (rule: IrResult | undefined, response: unknown) => unknown;
|
|
1209
|
+
export declare const buildToolInputSchema: (schema: FlowSchema, tool: IrSurfaceTool) => JSONSchema4;
|
|
1210
|
+
export declare const buildToolRequest: (tool: IrSurfaceTool, args: Record<string, unknown>) => Record<string, unknown>;
|
|
1211
|
+
export declare const runTool: (flows: Flows, tool: IrSurfaceTool, args: Record<string, unknown>) => Promise<unknown>;
|
|
1212
|
+
export declare class BundledSchema implements FlowSchema {
|
|
1061
1213
|
static readonly shared: BundledSchema;
|
|
1214
|
+
readonly version = "2.7.0";
|
|
1062
1215
|
getRequestSchema(target: string): import("zod").ZodObject<import("zod/v4/core").$ZodLooseShape, import("zod/v4/core").$strip>;
|
|
1063
1216
|
listTargets(): string[];
|
|
1064
1217
|
getTargetMeta(target: string): TargetMeta;
|
|
1065
1218
|
getTargetParameterSchema(target: string): JSONSchema4 | undefined;
|
|
1066
1219
|
getSharedParameters(): Record<string, unknown>;
|
|
1220
|
+
getOperation(operation: string): IrOperation | undefined;
|
|
1221
|
+
getFlow(flow: string): IrFlow | undefined;
|
|
1222
|
+
getSurface(client: string): IrSurface | undefined;
|
|
1223
|
+
getKeyCheck(): IrKeyCheck | undefined;
|
|
1067
1224
|
}
|
|
1068
|
-
export declare class RemoteSchema implements
|
|
1225
|
+
export declare class RemoteSchema implements FlowSchema {
|
|
1069
1226
|
readonly version: string;
|
|
1070
1227
|
private readonly schemas;
|
|
1071
1228
|
private readonly meta;
|
|
1072
1229
|
private readonly parameterSchemas;
|
|
1073
1230
|
private readonly sharedParameters;
|
|
1074
1231
|
private readonly targetKeys;
|
|
1232
|
+
private readonly flowSections;
|
|
1075
1233
|
private constructor();
|
|
1076
1234
|
static load(config?: RemoteSchemaLoadOptions): Promise<RemoteSchema>;
|
|
1077
1235
|
getRequestSchema(target: string): z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>> | undefined;
|
|
@@ -1079,6 +1237,10 @@ export declare class RemoteSchema implements DecodoSchema {
|
|
|
1079
1237
|
getTargetMeta(target: string): TargetMeta | undefined;
|
|
1080
1238
|
getTargetParameterSchema(target: string): JSONSchema4 | undefined;
|
|
1081
1239
|
getSharedParameters(): Record<string, unknown>;
|
|
1240
|
+
getOperation(operation: string): IrOperation | undefined;
|
|
1241
|
+
getFlow(flow: string): IrFlow | undefined;
|
|
1242
|
+
getSurface(client: string): IrSurface | undefined;
|
|
1243
|
+
getKeyCheck(): IrKeyCheck | undefined;
|
|
1082
1244
|
}
|
|
1083
1245
|
export declare const requestSchemas: Record<Target, z.ZodObject>;
|
|
1084
1246
|
export type ParameterMeta = {
|
|
@@ -1110,5 +1272,15 @@ export declare class ValidationError extends DecodoError {
|
|
|
1110
1272
|
export declare class TimeoutError extends Error {
|
|
1111
1273
|
constructor(message?: string);
|
|
1112
1274
|
}
|
|
1275
|
+
export declare class ResultError extends Error {
|
|
1276
|
+
readonly code: string;
|
|
1277
|
+
readonly retryable: boolean;
|
|
1278
|
+
constructor(message: string, code: string, retryable?: boolean);
|
|
1279
|
+
}
|
|
1280
|
+
export declare class JobTimeoutError extends TimeoutError {
|
|
1281
|
+
readonly flow: string;
|
|
1282
|
+
readonly jobId: string;
|
|
1283
|
+
constructor(flow: string, jobId: string, timeoutMs: number);
|
|
1284
|
+
}
|
|
1113
1285
|
|
|
1114
1286
|
export {};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { HttpClient } from '../http.js';
|
|
2
|
+
import type { DecodoSchema, FlowSchema, IrBatchFlow, IrCallFlow, IrFlow, IrJobFlow } from '../schema/types.js';
|
|
3
|
+
type FlowOfPattern = {
|
|
4
|
+
call: IrCallFlow;
|
|
5
|
+
job: IrJobFlow;
|
|
6
|
+
batch: IrBatchFlow;
|
|
7
|
+
};
|
|
8
|
+
export type WaitOptions = {
|
|
9
|
+
pollInterval?: number;
|
|
10
|
+
timeout?: number;
|
|
11
|
+
};
|
|
12
|
+
export type JobResultsOptions = {
|
|
13
|
+
maxItems?: number;
|
|
14
|
+
};
|
|
15
|
+
export type JobResultsPageOptions = {
|
|
16
|
+
cursor?: string;
|
|
17
|
+
maxItems?: number;
|
|
18
|
+
};
|
|
19
|
+
export type JobResultsPage = {
|
|
20
|
+
items: unknown[];
|
|
21
|
+
nextCursor?: string;
|
|
22
|
+
};
|
|
23
|
+
type JobStatus = Record<string, unknown>;
|
|
24
|
+
export declare class Flows {
|
|
25
|
+
private readonly http;
|
|
26
|
+
private readonly schema;
|
|
27
|
+
private readonly available;
|
|
28
|
+
private readonly validators;
|
|
29
|
+
constructor(http: HttpClient, schema: DecodoSchema, { available }: {
|
|
30
|
+
available: boolean;
|
|
31
|
+
});
|
|
32
|
+
get flowSchema(): FlowSchema;
|
|
33
|
+
describe(flow: string): IrFlow;
|
|
34
|
+
describe<P extends IrFlow['pattern']>(flow: string, pattern: P): FlowOfPattern[P];
|
|
35
|
+
checkKey(): Promise<void>;
|
|
36
|
+
call(flow: string, params: Record<string, unknown>): Promise<unknown>;
|
|
37
|
+
start(flow: string, params: Record<string, unknown>): Promise<JobStatus>;
|
|
38
|
+
startBatch(flow: string, params: Record<string, unknown>): Promise<JobStatus[]>;
|
|
39
|
+
status(flow: string, jobId: string): Promise<JobStatus>;
|
|
40
|
+
isPending(flow: string, status: JobStatus): boolean;
|
|
41
|
+
hasFailed(flow: string, status: JobStatus): boolean;
|
|
42
|
+
wait(flow: string, jobId: string, { pollInterval, timeout }?: WaitOptions): Promise<JobStatus>;
|
|
43
|
+
results(flow: string, jobId: string, { maxItems }?: JobResultsOptions): Promise<unknown>;
|
|
44
|
+
resultsPage(flow: string, jobId: string, { cursor, maxItems }?: JobResultsPageOptions): Promise<JobResultsPage>;
|
|
45
|
+
cancel(flow: string, jobId: string): Promise<JobStatus>;
|
|
46
|
+
private pollInterval;
|
|
47
|
+
private operation;
|
|
48
|
+
private send;
|
|
49
|
+
private validate;
|
|
50
|
+
private validatorFor;
|
|
51
|
+
}
|
|
52
|
+
export {};
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import * as z from 'zod';
|
|
2
|
+
import { prettifyError } from 'zod';
|
|
3
|
+
import { AuthenticationError, DecodoError, JobTimeoutError, RateLimitError, ValidationError, } from '../errors.js';
|
|
4
|
+
const DEFAULT_POLL_INTERVAL_MS = 5_000;
|
|
5
|
+
const FLOWS_SINCE = [2, 6, 0];
|
|
6
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
7
|
+
const localPath = (path) => {
|
|
8
|
+
if (typeof path !== 'string' ||
|
|
9
|
+
!path.startsWith('/') ||
|
|
10
|
+
path.startsWith('//') ||
|
|
11
|
+
path.includes('\\')) {
|
|
12
|
+
throw new Error('The schema gave a request path that is not a path on the API host.');
|
|
13
|
+
}
|
|
14
|
+
return path;
|
|
15
|
+
};
|
|
16
|
+
const isOlderThanFlows = (version) => {
|
|
17
|
+
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version ?? '');
|
|
18
|
+
if (!match) {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
for (let i = 0; i < 3; i += 1) {
|
|
22
|
+
const part = Number(match[i + 1]);
|
|
23
|
+
if (part !== FLOWS_SINCE[i]) {
|
|
24
|
+
return part < FLOWS_SINCE[i];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return false;
|
|
28
|
+
};
|
|
29
|
+
const isFlowSchema = (schema) => typeof schema.getFlow === 'function' &&
|
|
30
|
+
typeof schema.getOperation === 'function' &&
|
|
31
|
+
!isOlderThanFlows(schema.version);
|
|
32
|
+
const INVALID_CURSOR = 'Invalid cursor: pass the nextCursor from the previous results call.';
|
|
33
|
+
const encodeCursor = (position) => Buffer.from(JSON.stringify(position)).toString('base64url');
|
|
34
|
+
const decodeCursor = (cursor, jobId) => {
|
|
35
|
+
let position;
|
|
36
|
+
try {
|
|
37
|
+
position = JSON.parse(Buffer.from(cursor, 'base64url').toString());
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
throw new Error(INVALID_CURSOR);
|
|
41
|
+
}
|
|
42
|
+
const { page, skip } = (position ?? {});
|
|
43
|
+
if (!Number.isInteger(skip) ||
|
|
44
|
+
skip < 0 ||
|
|
45
|
+
(page !== undefined &&
|
|
46
|
+
(typeof page !== 'string' || !page.includes(encodeURIComponent(jobId))))) {
|
|
47
|
+
throw new Error(INVALID_CURSOR);
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
page: page === undefined ? undefined : localPath(page),
|
|
51
|
+
skip: skip,
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
export class Flows {
|
|
55
|
+
http;
|
|
56
|
+
schema;
|
|
57
|
+
available;
|
|
58
|
+
validators = new Map();
|
|
59
|
+
constructor(http, schema, { available }) {
|
|
60
|
+
this.http = http;
|
|
61
|
+
this.schema = schema;
|
|
62
|
+
this.available = available;
|
|
63
|
+
}
|
|
64
|
+
get flowSchema() {
|
|
65
|
+
if (!this.available) {
|
|
66
|
+
throw new Error('Flows require an API key. Configure webScrapingApi with apiKey instead of token.');
|
|
67
|
+
}
|
|
68
|
+
if (!isFlowSchema(this.schema)) {
|
|
69
|
+
throw new Error('The schema in use has no flows; they need Decodo IR 2.6.0 or newer.');
|
|
70
|
+
}
|
|
71
|
+
return this.schema;
|
|
72
|
+
}
|
|
73
|
+
describe(flow, pattern) {
|
|
74
|
+
const found = this.flowSchema.getFlow(flow);
|
|
75
|
+
if (!found) {
|
|
76
|
+
throw new Error(`Unknown flow "${flow}".`);
|
|
77
|
+
}
|
|
78
|
+
if (pattern !== undefined && found.pattern !== pattern) {
|
|
79
|
+
throw new Error(`Flow "${flow}" is a ${found.pattern} flow, not a ${pattern} flow.`);
|
|
80
|
+
}
|
|
81
|
+
return found;
|
|
82
|
+
}
|
|
83
|
+
async checkKey() {
|
|
84
|
+
const check = this.flowSchema.getKeyCheck();
|
|
85
|
+
if (!check) {
|
|
86
|
+
throw new Error('The schema in use has no key check; it needs Decodo IR 2.6.0 or newer.');
|
|
87
|
+
}
|
|
88
|
+
const run = this.describe(check.flow, 'call').run;
|
|
89
|
+
this.validate(run, this.operation(run), check.params);
|
|
90
|
+
try {
|
|
91
|
+
await this.call(check.flow, check.params);
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
if (err instanceof AuthenticationError || err instanceof RateLimitError) {
|
|
95
|
+
throw err;
|
|
96
|
+
}
|
|
97
|
+
if (err instanceof DecodoError) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
call(flow, params) {
|
|
104
|
+
return this.send(this.describe(flow, 'call').run, { body: params });
|
|
105
|
+
}
|
|
106
|
+
async start(flow, params) {
|
|
107
|
+
return (await this.send(this.describe(flow, 'job').start, {
|
|
108
|
+
body: params,
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
async startBatch(flow, params) {
|
|
112
|
+
const described = this.describe(flow, 'batch');
|
|
113
|
+
const response = (await this.send(described.start, { body: params }));
|
|
114
|
+
const items = response?.[described.itemsField];
|
|
115
|
+
return Array.isArray(items) ? items : [];
|
|
116
|
+
}
|
|
117
|
+
async status(flow, jobId) {
|
|
118
|
+
return (await this.send(this.describe(flow, 'job').status, {
|
|
119
|
+
jobId,
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
isPending(flow, status) {
|
|
123
|
+
const described = this.describe(flow, 'job');
|
|
124
|
+
return described.pendingStatuses.includes(status[described.statusField]);
|
|
125
|
+
}
|
|
126
|
+
hasFailed(flow, status) {
|
|
127
|
+
const described = this.describe(flow, 'job');
|
|
128
|
+
return described.failedStatuses.includes(status[described.statusField]);
|
|
129
|
+
}
|
|
130
|
+
async wait(flow, jobId, { pollInterval, timeout } = {}) {
|
|
131
|
+
const interval = pollInterval ?? this.pollInterval(flow);
|
|
132
|
+
if (!(interval > 0)) {
|
|
133
|
+
throw new Error('pollInterval must be a positive number of milliseconds.');
|
|
134
|
+
}
|
|
135
|
+
const deadline = timeout === undefined ? undefined : Date.now() + timeout;
|
|
136
|
+
for (;;) {
|
|
137
|
+
const status = await this.status(flow, jobId);
|
|
138
|
+
if (!this.isPending(flow, status)) {
|
|
139
|
+
return status;
|
|
140
|
+
}
|
|
141
|
+
if (deadline === undefined) {
|
|
142
|
+
await sleep(interval);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const remaining = deadline - Date.now();
|
|
146
|
+
if (remaining <= 0) {
|
|
147
|
+
throw new JobTimeoutError(flow, jobId, timeout ?? 0);
|
|
148
|
+
}
|
|
149
|
+
await sleep(Math.min(interval, remaining));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async results(flow, jobId, { maxItems } = {}) {
|
|
153
|
+
const described = this.describe(flow, 'job');
|
|
154
|
+
let body = (await this.send(described.results, {
|
|
155
|
+
jobId,
|
|
156
|
+
query: described.resultsQuery,
|
|
157
|
+
}));
|
|
158
|
+
const { pagination } = described;
|
|
159
|
+
if (!pagination) {
|
|
160
|
+
return body;
|
|
161
|
+
}
|
|
162
|
+
const itemsOf = (page) => {
|
|
163
|
+
const items = page?.[pagination.itemsField];
|
|
164
|
+
return Array.isArray(items) ? items : [];
|
|
165
|
+
};
|
|
166
|
+
const items = itemsOf(body);
|
|
167
|
+
while (maxItems === undefined || items.length < maxItems) {
|
|
168
|
+
const next = body?.[pagination.nextUrlField];
|
|
169
|
+
if (typeof next !== 'string' || !next) {
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
172
|
+
const url = new URL(next);
|
|
173
|
+
body = await this.http.get(`${localPath(url.pathname)}${url.search}`);
|
|
174
|
+
items.push(...itemsOf(body));
|
|
175
|
+
}
|
|
176
|
+
return maxItems === undefined ? items : items.slice(0, maxItems);
|
|
177
|
+
}
|
|
178
|
+
async resultsPage(flow, jobId, { cursor, maxItems } = {}) {
|
|
179
|
+
const described = this.describe(flow, 'job');
|
|
180
|
+
const { pagination } = described;
|
|
181
|
+
if (!pagination) {
|
|
182
|
+
throw new Error(`Flow "${flow}" returns its results in one response.`);
|
|
183
|
+
}
|
|
184
|
+
if (maxItems !== undefined &&
|
|
185
|
+
!(Number.isInteger(maxItems) && maxItems > 0)) {
|
|
186
|
+
throw new Error('maxItems must be a whole number above 0.');
|
|
187
|
+
}
|
|
188
|
+
const itemsOf = (page) => {
|
|
189
|
+
const found = page?.[pagination.itemsField];
|
|
190
|
+
return Array.isArray(found) ? found : [];
|
|
191
|
+
};
|
|
192
|
+
const nextPageOf = (page) => {
|
|
193
|
+
const next = page?.[pagination.nextUrlField];
|
|
194
|
+
if (typeof next !== 'string' || !next) {
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
const url = new URL(next);
|
|
198
|
+
return `${localPath(url.pathname)}${url.search}`;
|
|
199
|
+
};
|
|
200
|
+
let position = cursor ? decodeCursor(cursor, jobId) : { skip: 0 };
|
|
201
|
+
const items = [];
|
|
202
|
+
for (;;) {
|
|
203
|
+
const body = (position.page === undefined
|
|
204
|
+
? await this.send(described.results, {
|
|
205
|
+
jobId,
|
|
206
|
+
query: described.resultsQuery,
|
|
207
|
+
})
|
|
208
|
+
: await this.http.get(position.page));
|
|
209
|
+
const pageItems = itemsOf(body).slice(position.skip);
|
|
210
|
+
const room = maxItems === undefined ? pageItems.length : maxItems - items.length;
|
|
211
|
+
items.push(...pageItems.slice(0, room));
|
|
212
|
+
if (room < pageItems.length) {
|
|
213
|
+
return {
|
|
214
|
+
items,
|
|
215
|
+
nextCursor: encodeCursor({
|
|
216
|
+
page: position.page,
|
|
217
|
+
skip: position.skip + room,
|
|
218
|
+
}),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
const next = nextPageOf(body);
|
|
222
|
+
if (!next) {
|
|
223
|
+
return { items };
|
|
224
|
+
}
|
|
225
|
+
position = { page: next, skip: 0 };
|
|
226
|
+
if (maxItems === undefined || items.length >= maxItems) {
|
|
227
|
+
return { items, nextCursor: encodeCursor(position) };
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
async cancel(flow, jobId) {
|
|
232
|
+
const endpoint = this.describe(flow, 'job').cancel;
|
|
233
|
+
if (!endpoint) {
|
|
234
|
+
throw new Error(`Flow "${flow}" cannot be cancelled.`);
|
|
235
|
+
}
|
|
236
|
+
return (await this.send(endpoint, { jobId }));
|
|
237
|
+
}
|
|
238
|
+
pollInterval(flow) {
|
|
239
|
+
const seconds = this.describe(flow, 'job').pollSeconds;
|
|
240
|
+
return typeof seconds === 'number' && seconds > 0
|
|
241
|
+
? seconds * 1000
|
|
242
|
+
: DEFAULT_POLL_INTERVAL_MS;
|
|
243
|
+
}
|
|
244
|
+
operation(name) {
|
|
245
|
+
const found = this.flowSchema.getOperation(name);
|
|
246
|
+
if (!found) {
|
|
247
|
+
throw new Error(`The schema has no operation "${name}".`);
|
|
248
|
+
}
|
|
249
|
+
return found;
|
|
250
|
+
}
|
|
251
|
+
async send(operationName, { body, jobId, query, }) {
|
|
252
|
+
const operation = this.operation(operationName);
|
|
253
|
+
let path = localPath(operation.path);
|
|
254
|
+
if (jobId !== undefined) {
|
|
255
|
+
const placeholder = /\{[^}]+\}/;
|
|
256
|
+
if (!jobId || !placeholder.test(path)) {
|
|
257
|
+
throw new Error(`Operation "${operationName}" needs a job id and a path with a place for it.`);
|
|
258
|
+
}
|
|
259
|
+
path = path.replace(placeholder, encodeURIComponent(jobId));
|
|
260
|
+
}
|
|
261
|
+
if (query && Object.keys(query).length > 0) {
|
|
262
|
+
path = `${path}?${new URLSearchParams(query).toString()}`;
|
|
263
|
+
}
|
|
264
|
+
if (body !== undefined) {
|
|
265
|
+
this.validate(operationName, operation, body);
|
|
266
|
+
}
|
|
267
|
+
return this.http.request(operation.method, path, body);
|
|
268
|
+
}
|
|
269
|
+
validate(name, operation, body) {
|
|
270
|
+
const validator = this.validatorFor(name, operation, body);
|
|
271
|
+
if (!validator) {
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const parsed = validator.safeParse(body);
|
|
275
|
+
if (!parsed.success) {
|
|
276
|
+
throw new ValidationError(prettifyError(parsed.error));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
validatorFor(name, operation, body) {
|
|
280
|
+
const ownSchema = operation.requestSchema;
|
|
281
|
+
if (!ownSchema?.properties && typeof body.target === 'string') {
|
|
282
|
+
return this.schema.getRequestSchema(body.target);
|
|
283
|
+
}
|
|
284
|
+
if (!ownSchema) {
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
if (!this.validators.has(name)) {
|
|
288
|
+
this.validators.set(name, toZod(name, ownSchema));
|
|
289
|
+
}
|
|
290
|
+
return this.validators.get(name);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const toZod = (name, schema) => {
|
|
294
|
+
try {
|
|
295
|
+
return z.fromJSONSchema(schema);
|
|
296
|
+
}
|
|
297
|
+
catch (err) {
|
|
298
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
299
|
+
throw new Error(`The schema's request schema for operation "${name}" is not valid JSON Schema: ${reason}`);
|
|
300
|
+
}
|
|
301
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2
|
+
const capValues = (value, limits, cut, topLevel) => {
|
|
3
|
+
if (typeof value === 'string') {
|
|
4
|
+
if (limits.maxTextChars !== undefined &&
|
|
5
|
+
value.length > limits.maxTextChars) {
|
|
6
|
+
cut.truncated = true;
|
|
7
|
+
return value.slice(0, limits.maxTextChars);
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
if (Array.isArray(value)) {
|
|
12
|
+
const cap = topLevel ? limits.maxItems : limits.maxListValues;
|
|
13
|
+
const kept = cap !== undefined && value.length > cap ? value.slice(0, cap) : value;
|
|
14
|
+
if (kept.length < value.length) {
|
|
15
|
+
cut.truncated = true;
|
|
16
|
+
}
|
|
17
|
+
return kept.map((item) => capValues(item, limits, cut, false));
|
|
18
|
+
}
|
|
19
|
+
if (isRecord(value)) {
|
|
20
|
+
return Object.fromEntries(Object.entries(value).map(([name, item]) => [
|
|
21
|
+
name,
|
|
22
|
+
capValues(item, limits, cut, false),
|
|
23
|
+
]));
|
|
24
|
+
}
|
|
25
|
+
return value;
|
|
26
|
+
};
|
|
27
|
+
export const limitResult = (limits, value) => {
|
|
28
|
+
const cut = { truncated: false };
|
|
29
|
+
const capped = limits ? capValues(value, limits, cut, true) : value;
|
|
30
|
+
const text = typeof capped === 'string' ? capped : (JSON.stringify(capped) ?? '');
|
|
31
|
+
const maxResultChars = limits?.maxResultChars;
|
|
32
|
+
if (maxResultChars !== undefined && text.length > maxResultChars) {
|
|
33
|
+
return { text: text.slice(0, maxResultChars), truncated: true };
|
|
34
|
+
}
|
|
35
|
+
return { text, truncated: cut.truncated };
|
|
36
|
+
};
|