@lifi/composer-sdk 0.8.1 → 0.9.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 +3 -2
- package/dist/_virtual/_rolldown/runtime.cjs +33 -0
- package/dist/_virtual/_rolldown/runtime.js +13 -0
- package/dist/authoring/FlowBuilderCore.cjs +102 -120
- package/dist/authoring/FlowBuilderCore.cjs.map +1 -1
- package/dist/authoring/FlowBuilderCore.d.cts +58 -61
- package/dist/authoring/FlowBuilderCore.d.ts +58 -61
- package/dist/authoring/FlowBuilderCore.js +99 -97
- package/dist/authoring/FlowBuilderCore.js.map +1 -1
- package/dist/authoring/handles.cjs +25 -40
- package/dist/authoring/handles.cjs.map +1 -1
- package/dist/authoring/handles.d.cts +33 -34
- package/dist/authoring/handles.d.ts +33 -34
- package/dist/authoring/handles.js +21 -13
- package/dist/authoring/handles.js.map +1 -1
- package/dist/authoring/raw.cjs +85 -44
- package/dist/authoring/raw.cjs.map +1 -1
- package/dist/authoring/raw.d.cts +8 -8
- package/dist/authoring/raw.d.ts +8 -8
- package/dist/authoring/raw.js +83 -19
- package/dist/authoring/raw.js.map +1 -1
- package/dist/authoring/signatureArgs.cjs +81 -103
- package/dist/authoring/signatureArgs.cjs.map +1 -1
- package/dist/authoring/signatureArgs.d.cts +63 -64
- package/dist/authoring/signatureArgs.d.ts +63 -64
- package/dist/authoring/signatureArgs.js +76 -75
- package/dist/authoring/signatureArgs.js.map +1 -1
- package/dist/client.cjs +172 -220
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +131 -131
- package/dist/client.d.ts +131 -131
- package/dist/client.js +165 -198
- package/dist/client.js.map +1 -1
- package/dist/discovery.cjs +0 -17
- package/dist/discovery.d.cts +57 -56
- package/dist/discovery.d.ts +57 -56
- package/dist/discovery.js +1 -1
- package/dist/errors.cjs +211 -159
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +84 -84
- package/dist/errors.d.ts +84 -84
- package/dist/errors.js +201 -120
- package/dist/errors.js.map +1 -1
- package/dist/generated/config.generated.cjs +0 -17
- package/dist/generated/config.generated.d.cts +804 -936
- package/dist/generated/config.generated.d.ts +804 -936
- package/dist/generated/config.generated.js +1 -1
- package/dist/generated/guards.generated.cjs +25 -35
- package/dist/generated/guards.generated.cjs.map +1 -1
- package/dist/generated/guards.generated.d.cts +20 -4
- package/dist/generated/guards.generated.d.ts +20 -4
- package/dist/generated/guards.generated.js +19 -11
- package/dist/generated/guards.generated.js.map +1 -1
- package/dist/generated/materialisers.generated.cjs +25 -35
- package/dist/generated/materialisers.generated.cjs.map +1 -1
- package/dist/generated/materialisers.generated.d.cts +17 -4
- package/dist/generated/materialisers.generated.d.ts +17 -4
- package/dist/generated/materialisers.generated.js +19 -11
- package/dist/generated/materialisers.generated.js.map +1 -1
- package/dist/generated/operations.generated.cjs +236 -277
- package/dist/generated/operations.generated.cjs.map +1 -1
- package/dist/generated/operations.generated.d.cts +719 -708
- package/dist/generated/operations.generated.d.ts +719 -708
- package/dist/generated/operations.generated.js +235 -256
- package/dist/generated/operations.generated.js.map +1 -1
- package/dist/generated/preconditions.generated.cjs +25 -35
- package/dist/generated/preconditions.generated.cjs.map +1 -1
- package/dist/generated/preconditions.generated.d.cts +17 -4
- package/dist/generated/preconditions.generated.d.ts +17 -4
- package/dist/generated/preconditions.generated.js +19 -11
- package/dist/generated/preconditions.generated.js.map +1 -1
- package/dist/index.cjs +131 -97
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +29 -43
- package/dist/index.d.ts +29 -43
- package/dist/index.js +96 -45
- package/dist/index.js.map +1 -1
- package/dist/outputs.cjs +11 -32
- package/dist/outputs.cjs.map +1 -1
- package/dist/outputs.d.cts +5 -5
- package/dist/outputs.d.ts +5 -5
- package/dist/outputs.js +10 -8
- package/dist/outputs.js.map +1 -1
- package/dist/raw.cjs +21 -33
- package/dist/raw.cjs.map +1 -1
- package/dist/raw.d.cts +8 -4
- package/dist/raw.d.ts +8 -4
- package/dist/raw.js +12 -7
- package/dist/raw.js.map +1 -1
- package/dist/reachability.cjs +82 -112
- package/dist/reachability.cjs.map +1 -1
- package/dist/reachability.d.cts +33 -59
- package/dist/reachability.d.ts +33 -59
- package/dist/reachability.js +81 -88
- package/dist/reachability.js.map +1 -1
- package/dist/resources.cjs +47 -32
- package/dist/resources.cjs.map +1 -1
- package/dist/resources.d.cts +50 -3
- package/dist/resources.d.ts +50 -3
- package/dist/resources.js +42 -9
- package/dist/resources.js.map +1 -1
- package/dist/responseSchemas.cjs +99 -111
- package/dist/responseSchemas.cjs.map +1 -1
- package/dist/responseSchemas.d.cts +34 -34
- package/dist/responseSchemas.d.ts +34 -34
- package/dist/responseSchemas.js +85 -66
- package/dist/responseSchemas.js.map +1 -1
- package/dist/routeAmount.cjs +61 -31
- package/dist/routeAmount.cjs.map +1 -1
- package/dist/routeAmount.d.cts +52 -2
- package/dist/routeAmount.d.ts +52 -2
- package/dist/routeAmount.js +56 -8
- package/dist/routeAmount.js.map +1 -1
- package/dist/run/inputs.cjs +56 -48
- package/dist/run/inputs.cjs.map +1 -1
- package/dist/run/inputs.d.cts +70 -74
- package/dist/run/inputs.d.ts +70 -74
- package/dist/run/inputs.js +54 -23
- package/dist/run/inputs.js.map +1 -1
- package/dist/run/simulate.cjs +38 -43
- package/dist/run/simulate.cjs.map +1 -1
- package/dist/run/simulate.d.cts +36 -36
- package/dist/run/simulate.d.ts +36 -36
- package/dist/run/simulate.js +37 -19
- package/dist/run/simulate.js.map +1 -1
- package/dist/sdk.cjs +55 -66
- package/dist/sdk.cjs.map +1 -1
- package/dist/sdk.d.cts +108 -111
- package/dist/sdk.d.ts +108 -111
- package/dist/sdk.js +52 -44
- package/dist/sdk.js.map +1 -1
- package/dist/types.cjs +0 -17
- package/dist/types.d.cts +22 -22
- package/dist/types.d.ts +22 -22
- package/dist/types.js +1 -1
- package/package.json +4 -4
- package/src/client.ts +2 -2
- package/src/examples/aaveClaimRewards.ts +2 -1
- package/src/examples/emitCustomEvent.ts +1 -2
- package/src/examples/run.ts +1 -1
- package/src/examples/transferTokens.ts +21 -17
- package/src/generated/config.generated.ts +20 -9
- package/src/generated/operations.generated.ts +28 -5
- package/dist/discovery.cjs.map +0 -1
- package/dist/discovery.js.map +0 -1
- package/dist/generated/config.generated.cjs.map +0 -1
- package/dist/generated/config.generated.js.map +0 -1
- package/dist/guards.generated-CDCgYGZo.d.cts +0 -24
- package/dist/guards.generated-CdYcs4h0.d.ts +0 -24
- package/dist/materialisers.generated-BMkBQgWZ.d.ts +0 -24
- package/dist/materialisers.generated-BWq5oePO.d.cts +0 -24
- package/dist/preconditions.generated-DblS13Wq.d.cts +0 -24
- package/dist/preconditions.generated-U7YpVh30.d.ts +0 -24
- package/dist/raw-BvRghN3r.d.ts +0 -20
- package/dist/raw-s1rer8X3.d.cts +0 -20
- package/dist/resources-BKlFxjo8.d.cts +0 -56
- package/dist/resources-CYis1_DS.d.ts +0 -56
- package/dist/routeAmount-DdbJYJyM.d.cts +0 -55
- package/dist/routeAmount-DdbJYJyM.d.ts +0 -55
- package/dist/types.cjs.map +0 -1
- package/dist/types.js.map +0 -1
package/dist/client.js
CHANGED
|
@@ -1,231 +1,198 @@
|
|
|
1
|
-
import {
|
|
2
|
-
checkCompatibility,
|
|
3
|
-
COMPOSE_VERSION_HEADER,
|
|
4
|
-
COMPOSER_SDK_VERSION_HEADER,
|
|
5
|
-
parseVersion
|
|
6
|
-
} from "@lifi/compose-spec";
|
|
1
|
+
import { parseCompilePartialEnvelope, parseSimulateResult } from "./responseSchemas.js";
|
|
7
2
|
import { ComposeError, errorFromHttpResponse } from "./errors.js";
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
} from "./responseSchemas.js";
|
|
12
|
-
const SDK_VERSION = true ? "0.8.1" : "dev";
|
|
3
|
+
import { COMPOSER_SDK_VERSION_HEADER, COMPOSE_VERSION_HEADER, checkCompatibility, parseVersion } from "@lifi/compose-spec";
|
|
4
|
+
//#region src/client.ts
|
|
5
|
+
const SDK_VERSION = "0.9.0";
|
|
13
6
|
const SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);
|
|
7
|
+
/**
|
|
8
|
+
* `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.
|
|
9
|
+
*
|
|
10
|
+
* The compose wire carries token amounts as decimal strings, and `bigint` has
|
|
11
|
+
* no JSON representation, so every payload this client sends goes through it.
|
|
12
|
+
* Exported so the example harness prints a request exactly as it is sent.
|
|
13
|
+
*/
|
|
14
14
|
const bigintReplacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
|
|
15
15
|
const isNonNullObject = (v) => typeof v === "object" && v !== null;
|
|
16
16
|
const INTEGER_STRING = /^\d+$/;
|
|
17
17
|
const decodeAmount = (value, path, url) => {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"UNKNOWN_ERROR",
|
|
21
|
-
`Malformed compose response: ${path} is ${value === void 0 ? "absent" : "not an integer string"}`,
|
|
22
|
-
{ url }
|
|
23
|
-
);
|
|
24
|
-
}
|
|
25
|
-
return BigInt(value);
|
|
18
|
+
if (typeof value !== "string" || !INTEGER_STRING.test(value)) throw new ComposeError("UNKNOWN_ERROR", `Malformed compose response: ${path} is ${value === void 0 ? "absent" : "not an integer string"}`, { url });
|
|
19
|
+
return BigInt(value);
|
|
26
20
|
};
|
|
27
|
-
const malformed = (path, what, url) => new ComposeError(
|
|
28
|
-
"UNKNOWN_ERROR",
|
|
29
|
-
`Malformed compose response: ${path} ${what}`,
|
|
30
|
-
{ url }
|
|
31
|
-
);
|
|
21
|
+
const malformed = (path, what, url) => new ComposeError("UNKNOWN_ERROR", `Malformed compose response: ${path} ${what}`, { url });
|
|
32
22
|
const decodeAmountLeaf = (amount, field, path, url) => {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);
|
|
23
|
+
const leaf = amount[field];
|
|
24
|
+
if (leaf === void 0) return;
|
|
25
|
+
if (!isNonNullObject(leaf)) throw malformed(`${path}.${field}`, "is not an object", url);
|
|
26
|
+
leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);
|
|
39
27
|
};
|
|
40
28
|
const decodeOutputs = (data, url) => {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
if (!isNonNullObject(entry)) {
|
|
52
|
-
throw malformed(`outputs.${key}`, "is not an object", url);
|
|
53
|
-
}
|
|
54
|
-
const amount = entry.amount;
|
|
55
|
-
if (!isNonNullObject(amount)) {
|
|
56
|
-
throw malformed(
|
|
57
|
-
`outputs.${key}.amount`,
|
|
58
|
-
amount === void 0 ? "is absent" : "is not an object",
|
|
59
|
-
url
|
|
60
|
-
);
|
|
61
|
-
}
|
|
62
|
-
decodeAmountLeaf(amount, "estimate", `outputs.${key}.amount`, url);
|
|
63
|
-
decodeAmountLeaf(amount, "minimum", `outputs.${key}.amount`, url);
|
|
64
|
-
}
|
|
29
|
+
const outputs = data.outputs;
|
|
30
|
+
if (!isNonNullObject(outputs)) throw malformed("outputs", outputs === void 0 ? "is absent" : "is not an object", url);
|
|
31
|
+
for (const key of Object.keys(outputs)) {
|
|
32
|
+
const entry = outputs[key];
|
|
33
|
+
if (!isNonNullObject(entry)) throw malformed(`outputs.${key}`, "is not an object", url);
|
|
34
|
+
const amount = entry.amount;
|
|
35
|
+
if (!isNonNullObject(amount)) throw malformed(`outputs.${key}.amount`, amount === void 0 ? "is absent" : "is not an object", url);
|
|
36
|
+
decodeAmountLeaf(amount, "estimate", `outputs.${key}.amount`, url);
|
|
37
|
+
decodeAmountLeaf(amount, "minimum", `outputs.${key}.amount`, url);
|
|
38
|
+
}
|
|
65
39
|
};
|
|
66
40
|
const decodeWireAmounts = (data, url) => {
|
|
67
|
-
|
|
68
|
-
|
|
41
|
+
if (!isNonNullObject(data)) return;
|
|
42
|
+
decodeOutputs(data, url);
|
|
69
43
|
};
|
|
70
44
|
const parseBody = async (res, url) => {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
url
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
return body.data;
|
|
45
|
+
const body = await res.json().catch((_) => null);
|
|
46
|
+
if (!isNonNullObject(body) || !("data" in body)) throw new ComposeError("UNKNOWN_ERROR", "Unexpected response format", { url });
|
|
47
|
+
return body.data;
|
|
78
48
|
};
|
|
79
49
|
const parseCompileSuccessBody = async (res, url) => {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
50
|
+
const data = await parseBody(res, url);
|
|
51
|
+
decodeWireAmounts(data, url);
|
|
52
|
+
return {
|
|
53
|
+
...data,
|
|
54
|
+
status: "success"
|
|
55
|
+
};
|
|
83
56
|
};
|
|
84
57
|
const parsePartialBody = async (res, url) => {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
decodeWireAmounts(data, url);
|
|
96
|
-
return { ...data, status: "partial", error: envelope.error };
|
|
58
|
+
const body = await res.json().catch((_) => null);
|
|
59
|
+
const envelope = parseCompilePartialEnvelope(body);
|
|
60
|
+
if (envelope === null) throw new ComposeError("UNKNOWN_ERROR", "Unexpected partial response format", { url });
|
|
61
|
+
const data = envelope.data;
|
|
62
|
+
decodeWireAmounts(data, url);
|
|
63
|
+
return {
|
|
64
|
+
...data,
|
|
65
|
+
status: "partial",
|
|
66
|
+
error: envelope.error
|
|
67
|
+
};
|
|
97
68
|
};
|
|
98
69
|
const parseSimulateBody = async (res, url) => {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
"UNKNOWN_ERROR",
|
|
104
|
-
"Unexpected simulate response format",
|
|
105
|
-
{ url }
|
|
106
|
-
);
|
|
107
|
-
}
|
|
108
|
-
return result;
|
|
70
|
+
const body = await res.json().catch((_) => null);
|
|
71
|
+
const result = parseSimulateResult(body);
|
|
72
|
+
if (result === null) throw new ComposeError("UNKNOWN_ERROR", "Unexpected simulate response format", { url });
|
|
73
|
+
return result;
|
|
109
74
|
};
|
|
110
75
|
const assertServerVersion = (res, url) => {
|
|
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
|
-
status: res.status,
|
|
138
|
-
url,
|
|
139
|
-
kind: "server_outdated",
|
|
140
|
-
serverOutdated: versions
|
|
141
|
-
}
|
|
142
|
-
);
|
|
76
|
+
const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);
|
|
77
|
+
if (serverVersion === null || SDK_VERSION_TRIPLE === void 0) return;
|
|
78
|
+
const serverTriple = parseVersion(serverVersion);
|
|
79
|
+
if (serverTriple === void 0) return;
|
|
80
|
+
const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);
|
|
81
|
+
if (compatibility === "compatible") return;
|
|
82
|
+
const versions = {
|
|
83
|
+
sdkVersion: SDK_VERSION,
|
|
84
|
+
serverVersion
|
|
85
|
+
};
|
|
86
|
+
if (compatibility === "sdk_outdated") throw new ComposeError("VALIDATION_ERROR", `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`, {
|
|
87
|
+
status: res.status,
|
|
88
|
+
url,
|
|
89
|
+
kind: "sdk_outdated",
|
|
90
|
+
sdkOutdated: {
|
|
91
|
+
...versions,
|
|
92
|
+
minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
throw new ComposeError("VALIDATION_ERROR", `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`, {
|
|
96
|
+
status: res.status,
|
|
97
|
+
url,
|
|
98
|
+
kind: "server_outdated",
|
|
99
|
+
serverOutdated: versions
|
|
100
|
+
});
|
|
143
101
|
};
|
|
144
|
-
const requestInit = (baseHeaders, init) => init.method === "GET" ? {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
102
|
+
const requestInit = (baseHeaders, init) => init.method === "GET" ? {
|
|
103
|
+
method: "GET",
|
|
104
|
+
headers: { ...baseHeaders }
|
|
105
|
+
} : {
|
|
106
|
+
method: "POST",
|
|
107
|
+
headers: {
|
|
108
|
+
...baseHeaders,
|
|
109
|
+
"Content-Type": "application/json"
|
|
110
|
+
},
|
|
111
|
+
body: JSON.stringify(init.body, bigintReplacer)
|
|
148
112
|
};
|
|
149
113
|
const send = async ({ fetchFn, baseHeaders }, url, init) => {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
114
|
+
try {
|
|
115
|
+
return await fetchFn(url, requestInit(baseHeaders, init));
|
|
116
|
+
} catch (err) {
|
|
117
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
118
|
+
throw new ComposeError("NETWORK_ERROR", message, { cause: err });
|
|
119
|
+
}
|
|
156
120
|
};
|
|
157
121
|
const postCompile = async (transport, url, request) => {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
122
|
+
const res = await send(transport, url, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
body: request
|
|
125
|
+
});
|
|
126
|
+
assertServerVersion(res, url);
|
|
127
|
+
if (res.status === 206) return await parsePartialBody(res, url);
|
|
128
|
+
if (!res.ok) {
|
|
129
|
+
const body = await res.text();
|
|
130
|
+
throw errorFromHttpResponse(res.status, body, url);
|
|
131
|
+
}
|
|
132
|
+
return await parseCompileSuccessBody(res, url);
|
|
168
133
|
};
|
|
169
134
|
const getJson = async (transport, url) => {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
135
|
+
const res = await send(transport, url, { method: "GET" });
|
|
136
|
+
if (!res.ok) {
|
|
137
|
+
const body = await res.text();
|
|
138
|
+
throw errorFromHttpResponse(res.status, body, url);
|
|
139
|
+
}
|
|
140
|
+
return await parseBody(res, url);
|
|
176
141
|
};
|
|
142
|
+
/**
|
|
143
|
+
* Creates a low-level Compose API client.
|
|
144
|
+
*
|
|
145
|
+
* @param options - Client configuration including the API base URL.
|
|
146
|
+
* @returns A {@link ComposeClient} instance.
|
|
147
|
+
*/
|
|
177
148
|
const createComposeClient = (options) => {
|
|
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
|
-
throw errorFromHttpResponse(res.status, body, url);
|
|
224
|
-
};
|
|
225
|
-
return { getManifest, getChains, compile, route, getZapPacks, simulate };
|
|
226
|
-
};
|
|
227
|
-
export {
|
|
228
|
-
bigintReplacer,
|
|
229
|
-
createComposeClient
|
|
149
|
+
if (!options.baseUrl || !/^https?:\/\//i.test(options.baseUrl)) throw new ComposeError("VALIDATION_ERROR", `Invalid baseUrl: expected an HTTP(S) URL, got "${options.baseUrl}"`);
|
|
150
|
+
const trimmedApiKey = options.apiKey?.trim() || void 0;
|
|
151
|
+
if (!trimmedApiKey) throw new ComposeError("VALIDATION_ERROR", "apiKey is required: pass a LI.FI API key to createComposeSdk().");
|
|
152
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
153
|
+
const base = options.baseUrl.replace(/\/$/, "");
|
|
154
|
+
const transport = {
|
|
155
|
+
fetchFn,
|
|
156
|
+
baseHeaders: {
|
|
157
|
+
Accept: "application/json",
|
|
158
|
+
[COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,
|
|
159
|
+
"x-lifi-api-key": trimmedApiKey
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
const getManifest = async () => getJson(transport, `${base}/compose/manifest`);
|
|
163
|
+
const getChains = async () => getJson(transport, `${base}/chains`);
|
|
164
|
+
const compile = async (request) => postCompile(transport, `${base}/compose`, request);
|
|
165
|
+
const route = async (request) => postCompile(transport, `${base}/compose/route`, request);
|
|
166
|
+
const getZapPacks = async (options) => {
|
|
167
|
+
const params = new URLSearchParams();
|
|
168
|
+
if (options?.protocols !== void 0) {
|
|
169
|
+
const raw = options.protocols;
|
|
170
|
+
const list = typeof raw === "string" ? raw : raw.join(",");
|
|
171
|
+
params.set("protocols", list);
|
|
172
|
+
}
|
|
173
|
+
const qs = params.toString();
|
|
174
|
+
return getJson(transport, `${base}/compose/zap-packs${qs ? `?${qs}` : ""}`);
|
|
175
|
+
};
|
|
176
|
+
const simulate = async (request) => {
|
|
177
|
+
const url = `${base}/simulate`;
|
|
178
|
+
const res = await send(transport, url, {
|
|
179
|
+
method: "POST",
|
|
180
|
+
body: request
|
|
181
|
+
});
|
|
182
|
+
if (res.status === 200 || res.status === 422) return await parseSimulateBody(res, url);
|
|
183
|
+
const body = await res.text();
|
|
184
|
+
throw errorFromHttpResponse(res.status, body, url);
|
|
185
|
+
};
|
|
186
|
+
return {
|
|
187
|
+
getManifest,
|
|
188
|
+
getChains,
|
|
189
|
+
compile,
|
|
190
|
+
route,
|
|
191
|
+
getZapPacks,
|
|
192
|
+
simulate
|
|
193
|
+
};
|
|
230
194
|
};
|
|
195
|
+
//#endregion
|
|
196
|
+
export { bigintReplacer, createComposeClient };
|
|
197
|
+
|
|
231
198
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\nimport {\n parseCompilePartialEnvelope,\n parseSimulateResult,\n} from './responseSchemas.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsup (via `define` in tsup.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `COMPOSER_SDK_VERSION_HEADER` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsup substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\n readonly apiKey: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * The server plans a short chain of catalog edges for the pair (a position\n * entry or exit, a wrap or unwrap, a mint or burn), optionally opened by a\n * `lifi.swap`. {@link getZapPacks} lists the single edges; the pairs the\n * planner connects are their closure up to the hop budget, which\n * {@link buildReachability} computes locally. A pair the planner cannot\n * connect is rejected with `kind: 'no_route_error'`.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every terminal output comes back\n * `delivery.when: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `outputs[*].delivery.when` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when the planner cannot connect the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n /**\n * Simulates a raw, pre-encoded transaction against `POST /simulate` and\n * reports how the watched balances change and how much inner-call gas it\n * burns.\n *\n * The result is a discriminated union on `status`:\n * - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.\n * - `'revert'` — the simulation ran but the transaction reverted on-chain. A\n * revert is a *successful simulation*, not a transport error, so it is\n * returned (HTTP 200) rather than thrown — mirroring how {@link compile}\n * returns `status: 'partial'` on a simulated revert.\n * - `'error'` — the request was well-formed but the simulation could not be\n * set up or run (HTTP 422); `message` is intentionally generic.\n *\n * `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)\n * are serialised to decimal strings automatically.\n *\n * @param request - The raw transaction plus funding `requirements` and the\n * `trackedBalances` to watch.\n * @returns A {@link SimulateResult} (`ok` / `revert` / `error`).\n * @throws {@link ComposeError} on network failures, HTTP 400 (malformed\n * input), 401/403 (auth), 404, 429, and 5xx.\n */\n readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;\n}\n\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (value: unknown, path: string, url: string): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// The two records this seam reads out of a compile-family response body. Each\n// is `unknown` because the seam is what establishes its shape: it validates\n// every field before writing a decoded `bigint` back over the wire string.\ninterface WireAmountBody {\n outputs?: unknown;\n}\n\n// One `Amount` as it arrives: each leaf is `unknown` until this seam has\n// checked it, and is overwritten in place with the decoded `bigint`.\ninterface WireAmount {\n estimate?: unknown;\n minimum?: unknown;\n}\n\nconst malformed = (path: string, what: string, url: string): ComposeError =>\n new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} ${what}`,\n { url },\n );\n\n// Decode one `Estimate` / `Minimum` leaf in place: `{ basis, value }` with\n// `value` a decimal string on the wire and a `bigint` on `Amount`.\nconst decodeAmountLeaf = (\n amount: WireAmount,\n field: 'estimate' | 'minimum',\n path: string,\n url: string,\n): void => {\n const leaf = amount[field];\n if (leaf === undefined) return;\n if (!isNonNullObject(leaf)) {\n throw malformed(`${path}.${field}`, 'is not an object', url);\n }\n leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);\n};\n\n// `outputs` is REQUIRED on every compile-family body and is the record a\n// caller reads amounts from, so its structure is checked here — the body is\n// cast, not schema-parsed — before each `value` leaf becomes a `bigint`.\nconst decodeOutputs = (data: WireAmountBody, url: string): void => {\n const outputs = data.outputs;\n if (!isNonNullObject(outputs)) {\n throw malformed(\n 'outputs',\n outputs === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n for (const key of Object.keys(outputs)) {\n const entry = outputs[key];\n if (!isNonNullObject(entry)) {\n throw malformed(`outputs.${key}`, 'is not an object', url);\n }\n const amount = entry.amount;\n if (!isNonNullObject(amount)) {\n throw malformed(\n `outputs.${key}.amount`,\n amount === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n decodeAmountLeaf(amount, 'estimate', `outputs.${key}.amount`, url);\n decodeAmountLeaf(amount, 'minimum', `outputs.${key}.amount`, url);\n }\n};\n\n// THE decode seam for a compile-family response body: every amount the wire\n// renders as a decimal string becomes the `bigint` its declared type promises.\n// The amount record is handled here so the body is narrowed once — a\n// non-object body is not this function's error to raise, since the enveloping\n// parse already rejected it.\nconst decodeWireAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n decodeOutputs(data, url);\n};\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n decodeWireAmounts(data, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n const envelope = parseCompilePartialEnvelope(body);\n if (envelope === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n // `data` is validated as an object by the schema; compose-spec owns its full\n // shape as a hand-authored type, so we narrow it here rather than re-declaring\n // that type as a schema. `error` is fully validated — no cast needed.\n const data = envelope.data as ComposeCompilePartialData;\n decodeWireAmounts(data, url);\n return { ...data, status: 'partial' as const, error: envelope.error };\n};\n\n// `/simulate` is un-enveloped: the discriminated body (`{ status, ... }`) is at\n// the top level, NOT wrapped in `{ data }` like `/compose`. So this reads the\n// body directly and validates it against the simulate union rather than reusing\n// `parseBody`.\nconst parseSimulateBody = async (\n res: Response,\n url: string,\n): Promise<SimulateResult> => {\n const body = await res.json().catch((_) => null);\n const result = parseSimulateResult(body);\n if (result === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected simulate response format',\n { url },\n );\n }\n return result;\n};\n// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n};\n\n// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\n // Only 200 (carries `ok`/`revert`) and 422 (carries the `error` member of\n // the union) have a discriminated body. 422 is deliberately intercepted\n // here (not thrown as VALIDATION_ERROR) so callers get one exhaustive\n // `switch (result.status)`. Every other status is a transport error and is\n // thrown — including HTTP 400 (malformed input, no `status` body) and any\n // unexpected 2xx.\n if (res.status === 200 || res.status === 422) {\n return await parseSimulateBody(res, url);\n }\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n };\n\n return { getManifest, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":"AAUA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,cAAc,6BAA6B;AACpD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AASP,MAAM,cACJ,OAAyC,UAAkB;AAE7D,MAAM,qBAAqB,aAAa,WAAW;AA2J5C,MAAM,iBAAiB,CAAC,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,kBAAkB,CAAC,MACvB,OAAO,MAAM,YAAY,MAAM;AAGjC,MAAM,iBAAiB;AAEvB,MAAM,eAAe,CAAC,OAAgB,MAAc,QAAwB;AAC1E,MAAI,OAAO,UAAU,YAAY,CAAC,eAAe,KAAK,KAAK,GAAG;AAC5D,UAAM,IAAI;AAAA,MACR;AAAA,MACA,+BAA+B,IAAI,OACjC,UAAU,SAAY,WAAW,uBACnC;AAAA,MACA,EAAE,IAAI;AAAA,IACR;AAAA,EACF;AACA,SAAO,OAAO,KAAK;AACrB;AAgBA,MAAM,YAAY,CAAC,MAAc,MAAc,QAC7C,IAAI;AAAA,EACF;AAAA,EACA,+BAA+B,IAAI,IAAI,IAAI;AAAA,EAC3C,EAAE,IAAI;AACR;AAIF,MAAM,mBAAmB,CACvB,QACA,OACA,MACA,QACS;AACT,QAAM,OAAO,OAAO,KAAK;AACzB,MAAI,SAAS,OAAW;AACxB,MAAI,CAAC,gBAAgB,IAAI,GAAG;AAC1B,UAAM,UAAU,GAAG,IAAI,IAAI,KAAK,IAAI,oBAAoB,GAAG;AAAA,EAC7D;AACA,OAAK,QAAQ,aAAa,KAAK,OAAO,GAAG,IAAI,IAAI,KAAK,UAAU,GAAG;AACrE;AAKA,MAAM,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AI,EAAE,KAAK,EAAE;AAAA,IAChD;AAAA,EACF;AAEA,QAAM,WAAW,OACf,YAC4B;AAC5B,UAAM,MAAM,GAAG,IAAI;AACnB,UAAM,MAAM,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ,QAAQ,MAAM,QAAQ,CAAC;AAOxE,QAAI,IAAI,WAAW,OAAO,IAAI,WAAW,KAAK;AAC5C,aAAO,MAAM,kBAAkB,KAAK,GAAG;AAAA,IACzC;AACA,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAM,sBAAsB,IAAI,QAAQ,MAAM,GAAG;AAAA,EACnD;AAEA,SAAO,EAAE,aAAa,WAAW,SAAS,OAAO,aAAa,SAAS;AACzE;","names":["options"]}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["import type {\n ComposeCompilePartialData,\n ComposeCompileRequest,\n ComposeCompileResult,\n ComposeCompileSuccessData,\n ComposeManifest,\n ComposeRouteRequest,\n SimulateRequest,\n SimulateResult,\n} from '@lifi/compose-spec';\nimport {\n checkCompatibility,\n COMPOSE_VERSION_HEADER,\n COMPOSER_SDK_VERSION_HEADER,\n parseVersion,\n} from '@lifi/compose-spec';\n\nimport type {\n ChainSummary,\n GetZapPacksOptions,\n ZapPackOverview,\n} from './discovery.js';\nimport { ComposeError, errorFromHttpResponse } from './errors.js';\nimport {\n parseCompilePartialEnvelope,\n parseSimulateResult,\n} from './responseSchemas.js';\n\n// __SDK_VERSION__ is a compile-time constant injected by tsdown (via `define` in tsdown.config.ts)\n// and by vitest (via `define` in vitest.config.ts). Both read the version from package.json\n// at build/test time and replace this identifier with the literal string value.\n// It is sent as the `COMPOSER_SDK_VERSION_HEADER` request header so the server can identify the caller.\n// Falls back to 'dev' when running via tsx without tsdown substitution (e.g. the example harness).\ndeclare const __SDK_VERSION__: string;\n\nconst SDK_VERSION: string =\n typeof __SDK_VERSION__ !== 'undefined' ? __SDK_VERSION__ : 'dev';\n// `undefined` for the `dev` sentinel, which disables the response version check.\nconst SDK_VERSION_TRIPLE = parseVersion(SDK_VERSION);\n\n/**\n * Configuration for creating a low-level Compose API client.\n */\nexport interface ComposeClientOptions {\n /** Base URL of the Compose API. */\n readonly baseUrl: string;\n /** Optional custom `fetch` implementation. Defaults to `globalThis.fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n /** LI.FI API key, sent as the `x-lifi-api-key` header on every request. Required — the Compose API rejects unauthenticated requests. */\n readonly apiKey: string;\n}\n\n/**\n * Low-level HTTP client for the Compose API.\n *\n * Handles request serialization, SDK version headers, and error mapping.\n * Prefer using {@link ComposeSdk} for the full builder experience. Use this\n * directly when you need to decouple request building from submission — e.g.\n * build via `sdk.request()` then submit via `client.compile()` with custom\n * retry logic or request inspection.\n */\nexport interface ComposeClient {\n /**\n * Fetches the server's operation manifest describing all supported operations,\n * guards, materialisers, and preconditions.\n * @returns The manifest document.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly getManifest: () => Promise<ComposeManifest>;\n /**\n * Fetches the chains the Compose API supports, ascending by `chainId`.\n *\n * A chain is listed once the server confirms the VM contract is deployed on\n * it — the same condition {@link compile}, {@link route} and\n * {@link simulate} validate against. A chain absent from this list is\n * rejected outright by those endpoints.\n *\n * The converse does not hold: a listed chain can still have no routing edge\n * for a given token pair, which {@link route} reports as `no_route_error`.\n * Use {@link getZapPacks} to enumerate the pairs that do route.\n *\n * Each entry carries a display `name` alongside its `chainId`. The name is a\n * deployment-maintained label — render it, but key on `chainId`.\n *\n * The list tracks the server's chain registry, which refreshes periodically.\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @returns The supported chains, ascending by `chainId`.\n * @throws {@link ComposeError} on network or server errors.\n */\n readonly getChains: () => Promise<readonly ChainSummary[]>;\n /**\n * Submits a compile request and returns the result.\n *\n * When the caller passes `simulationPolicy: 'allow-revert'` and the transaction\n * reverts in simulation, the server responds with HTTP 206 and the SDK returns a\n * partial result (`status: 'partial'`) instead of throwing. The partial result\n * includes the transaction (without `gasLimit`) and revert diagnostics.\n *\n * @param request - The full compile request including flow and run inputs.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors.\n */\n readonly compile: (\n request: ComposeCompileRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Compiles a token pair into a submit-ready transaction via\n * `POST /compose/route`.\n *\n * A convenience path that skips flow authoring: the server builds a one-node\n * zap flow with a `directDeposit` input from the `fromToken` / `toToken`\n * pair and runs it through the same pipeline as {@link compile}. The\n * response is therefore the same discriminated result — HTTP 206 under\n * `simulationPolicy: 'allow-revert'` yields `status: 'partial'` rather than\n * throwing, exactly as it does for {@link compile}.\n *\n * The server plans a short chain of catalog edges for the pair (a position\n * entry or exit, a wrap or unwrap, a mint or burn), optionally opened by a\n * `lifi.swap`. {@link getZapPacks} lists the single edges; the pairs the\n * planner connects are their closure up to the hop budget, which\n * {@link buildReachability} computes locally. A pair the planner cannot\n * connect is rejected with `kind: 'no_route_error'`.\n *\n * Only synchronous edges are considered unless the request sets\n * `allowAsyncRoutes: true`, so by default every terminal output comes back\n * `delivery.when: 'now'` and a pair reachable only after settlement is a\n * `no_route_error`. Opting in adds the `lifi.zapAsync` fallback, which still\n * loses to a synchronous edge when the pair has one; read\n * `outputs[*].delivery.when` to see which representation you got.\n *\n * Use {@link compile} for what the server does not author for you: several\n * chained operations, splits, explicit preconditions, or per-op guards.\n *\n * `bigint` amounts in `amount` are serialised to decimal strings\n * automatically.\n *\n * @param request - The from/to token pair, amount, signer, and route options.\n * @returns A discriminated result: `status: 'success'` or `status: 'partial'`.\n * @throws {@link ComposeError} on network, validation, or server errors —\n * including `NOT_FOUND` (HTTP 404) when the planner cannot connect the pair.\n */\n readonly route: (\n request: ComposeRouteRequest,\n ) => Promise<ComposeCompileResult>;\n /**\n * Fetches the available routing edges grouped by protocol.\n *\n * The edge catalog is dynamic — it reflects the current state of the\n * backend's routing snapshot (protocols, chains, token blacklists).\n * Results are not cached by the SDK; callers should cache as appropriate.\n *\n * @param options - Optional filter to restrict results to specific protocols.\n * @returns An array of {@link ZapPackOverview} objects, one per protocol.\n * @throws {@link ComposeError} on network or server errors (503 when the\n * routing catalog is not yet initialized).\n */\n readonly getZapPacks: (\n options?: GetZapPacksOptions,\n ) => Promise<readonly ZapPackOverview[]>;\n /**\n * Simulates a raw, pre-encoded transaction against `POST /simulate` and\n * reports how the watched balances change and how much inner-call gas it\n * burns.\n *\n * The result is a discriminated union on `status`:\n * - `'ok'` — the simulation ran successfully; `deltas`/`gasUsed` are populated.\n * - `'revert'` — the simulation ran but the transaction reverted on-chain. A\n * revert is a *successful simulation*, not a transport error, so it is\n * returned (HTTP 200) rather than thrown — mirroring how {@link compile}\n * returns `status: 'partial'` on a simulated revert.\n * - `'error'` — the request was well-formed but the simulation could not be\n * set up or run (HTTP 422); `message` is intentionally generic.\n *\n * `bigint` amounts in the request (`value`, requirement `balance`/`allowance`)\n * are serialised to decimal strings automatically.\n *\n * @param request - The raw transaction plus funding `requirements` and the\n * `trackedBalances` to watch.\n * @returns A {@link SimulateResult} (`ok` / `revert` / `error`).\n * @throws {@link ComposeError} on network failures, HTTP 400 (malformed\n * input), 401/403 (auth), 404, 429, and 5xx.\n */\n readonly simulate: (request: SimulateRequest) => Promise<SimulateResult>;\n}\n\n/**\n * `JSON.stringify` replacer that renders `bigint` amounts as decimal strings.\n *\n * The compose wire carries token amounts as decimal strings, and `bigint` has\n * no JSON representation, so every payload this client sends goes through it.\n * Exported so the example harness prints a request exactly as it is sent.\n */\nexport const bigintReplacer = (_key: string, value: unknown): unknown =>\n typeof value === 'bigint' ? value.toString() : value;\n\nconst isNonNullObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null;\n\n// Non-negative decimal integer string, as the server sends token amounts.\nconst INTEGER_STRING = /^\\d+$/;\n\nconst decodeAmount = (value: unknown, path: string, url: string): bigint => {\n if (typeof value !== 'string' || !INTEGER_STRING.test(value)) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} is ${\n value === undefined ? 'absent' : 'not an integer string'\n }`,\n { url },\n );\n }\n return BigInt(value);\n};\n\n// The two records this seam reads out of a compile-family response body. Each\n// is `unknown` because the seam is what establishes its shape: it validates\n// every field before writing a decoded `bigint` back over the wire string.\ninterface WireAmountBody {\n outputs?: unknown;\n}\n\n// One `Amount` as it arrives: each leaf is `unknown` until this seam has\n// checked it, and is overwritten in place with the decoded `bigint`.\ninterface WireAmount {\n estimate?: unknown;\n minimum?: unknown;\n}\n\nconst malformed = (path: string, what: string, url: string): ComposeError =>\n new ComposeError(\n 'UNKNOWN_ERROR',\n `Malformed compose response: ${path} ${what}`,\n { url },\n );\n\n// Decode one `Estimate` / `Minimum` leaf in place: `{ basis, value }` with\n// `value` a decimal string on the wire and a `bigint` on `Amount`.\nconst decodeAmountLeaf = (\n amount: WireAmount,\n field: 'estimate' | 'minimum',\n path: string,\n url: string,\n): void => {\n const leaf = amount[field];\n if (leaf === undefined) return;\n if (!isNonNullObject(leaf)) {\n throw malformed(`${path}.${field}`, 'is not an object', url);\n }\n leaf.value = decodeAmount(leaf.value, `${path}.${field}.value`, url);\n};\n\n// `outputs` is REQUIRED on every compile-family body and is the record a\n// caller reads amounts from, so its structure is checked here — the body is\n// cast, not schema-parsed — before each `value` leaf becomes a `bigint`.\nconst decodeOutputs = (data: WireAmountBody, url: string): void => {\n const outputs = data.outputs;\n if (!isNonNullObject(outputs)) {\n throw malformed(\n 'outputs',\n outputs === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n for (const key of Object.keys(outputs)) {\n const entry = outputs[key];\n if (!isNonNullObject(entry)) {\n throw malformed(`outputs.${key}`, 'is not an object', url);\n }\n const amount = entry.amount;\n if (!isNonNullObject(amount)) {\n throw malformed(\n `outputs.${key}.amount`,\n amount === undefined ? 'is absent' : 'is not an object',\n url,\n );\n }\n decodeAmountLeaf(amount, 'estimate', `outputs.${key}.amount`, url);\n decodeAmountLeaf(amount, 'minimum', `outputs.${key}.amount`, url);\n }\n};\n\n// THE decode seam for a compile-family response body: every amount the wire\n// renders as a decimal string becomes the `bigint` its declared type promises.\n// The amount record is handled here so the body is narrowed once — a\n// non-object body is not this function's error to raise, since the enveloping\n// parse already rejected it.\nconst decodeWireAmounts = (data: unknown, url: string): void => {\n if (!isNonNullObject(data)) return;\n decodeOutputs(data, url);\n};\n\nconst parseBody = async <T>(res: Response, url: string): Promise<T> => {\n const body = await res.json().catch((_) => null);\n if (!isNonNullObject(body) || !('data' in body)) {\n throw new ComposeError('UNKNOWN_ERROR', 'Unexpected response format', {\n url,\n });\n }\n return body.data as T;\n};\n\nconst parseCompileSuccessBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const data = await parseBody<ComposeCompileSuccessData>(res, url);\n decodeWireAmounts(data, url);\n return { ...data, status: 'success' as const };\n};\n\nconst parsePartialBody = async (\n res: Response,\n url: string,\n): Promise<ComposeCompileResult> => {\n const body = await res.json().catch((_) => null);\n const envelope = parseCompilePartialEnvelope(body);\n if (envelope === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected partial response format',\n { url },\n );\n }\n // `data` is validated as an object by the schema; compose-spec owns its full\n // shape as a hand-authored type, so we narrow it here rather than re-declaring\n // that type as a schema. `error` is fully validated — no cast needed.\n const data = envelope.data as ComposeCompilePartialData;\n decodeWireAmounts(data, url);\n return { ...data, status: 'partial' as const, error: envelope.error };\n};\n\n// `/simulate` is un-enveloped: the discriminated body (`{ status, ... }`) is at\n// the top level, NOT wrapped in `{ data }` like `/compose`. So this reads the\n// body directly and validates it against the simulate union rather than reusing\n// `parseBody`.\nconst parseSimulateBody = async (\n res: Response,\n url: string,\n): Promise<SimulateResult> => {\n const body = await res.json().catch((_) => null);\n const result = parseSimulateResult(body);\n if (result === null) {\n throw new ComposeError(\n 'UNKNOWN_ERROR',\n 'Unexpected simulate response format',\n { url },\n );\n }\n return result;\n};\n// `POST /compose` and `POST /compose/route` differ only in path and request\n// shape: both return the enveloped success data on 200 and the partial\n// envelope on 206, so they share one transport.\ntype ComposeTransport = {\n readonly fetchFn: typeof fetch;\n readonly baseHeaders: Record<string, string>;\n};\n\n// A patch bump is additive and a minor bump is breaking, so a 200 from a\n// backend behind this SDK cannot be trusted: the newer flow this SDK authored\n// may have compiled under the server's older semantics without raising an\n// error. This covers the deploy window where the SDK is published to npm ahead\n// of the backend rollout. Only the compile-family POSTs are checked; discovery\n// GETs stay reachable from a mismatched SDK, as on the server. An absent header\n// (a pre-gate backend, a header-stripping proxy) is accepted, mirroring the\n// server's pass-through of a compile that carries no version header.\nconst assertServerVersion = (res: Response, url: string): void => {\n const serverVersion = res.headers.get(COMPOSE_VERSION_HEADER);\n if (serverVersion === null || SDK_VERSION_TRIPLE === undefined) return;\n const serverTriple = parseVersion(serverVersion);\n if (serverTriple === undefined) return;\n\n const compatibility = checkCompatibility(SDK_VERSION_TRIPLE, serverTriple);\n if (compatibility === 'compatible') return;\n\n const versions = { sdkVersion: SDK_VERSION, serverVersion };\n if (compatibility === 'sdk_outdated') {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} is older than the compose contract served at ${url} (${serverVersion}); upgrade @lifi/composer-sdk and @lifi/compose-spec`,\n {\n status: res.status,\n url,\n kind: 'sdk_outdated',\n sdkOutdated: {\n ...versions,\n minimumSdkVersion: `${serverTriple.major}.${serverTriple.minor}.0`,\n },\n },\n );\n }\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `composer-sdk ${SDK_VERSION} targets a newer compose contract than the server at ${url} serves (${serverVersion}); pin @lifi/composer-sdk and @lifi/compose-spec to ${serverVersion} or wait for the server rollout`,\n {\n status: res.status,\n url,\n kind: 'server_outdated',\n serverOutdated: versions,\n },\n );\n};\n\ntype SendInit =\n | { readonly method: 'GET' }\n | { readonly method: 'POST'; readonly body: unknown };\n\n// GETs on this API carry no body; POSTs carry a JSON one with `bigint` amounts\n// rendered as decimal strings.\nconst requestInit = (\n baseHeaders: Record<string, string>,\n init: SendInit,\n): RequestInit =>\n init.method === 'GET'\n ? { method: 'GET', headers: { ...baseHeaders } }\n : {\n method: 'POST',\n headers: { ...baseHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(init.body, bigintReplacer),\n };\n\n// One fetch path for every route: maps transport failures to `NETWORK_ERROR`.\n// The response version check is not here — only the compile-family POSTs gate\n// on it (see `postCompile`); discovery GETs and `/simulate` are ungated.\nconst send = async (\n { fetchFn, baseHeaders }: ComposeTransport,\n url: string,\n init: SendInit,\n): Promise<Response> => {\n try {\n return await fetchFn(url, requestInit(baseHeaders, init));\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ComposeError('NETWORK_ERROR', message, { cause: err });\n }\n};\n\nconst postCompile = async (\n transport: ComposeTransport,\n url: string,\n request: ComposeCompileRequest | ComposeRouteRequest,\n): Promise<ComposeCompileResult> => {\n const res = await send(transport, url, { method: 'POST', body: request });\n assertServerVersion(res, url);\n if (res.status === 206) {\n return await parsePartialBody(res, url);\n }\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseCompileSuccessBody(res, url);\n};\n\n// Every enveloped GET on this API behaves identically: no body, no query\n// semantics of its own, `{ data }` on success, an error envelope otherwise.\nconst getJson = async <T>(\n transport: ComposeTransport,\n url: string,\n): Promise<T> => {\n const res = await send(transport, url, { method: 'GET' });\n if (!res.ok) {\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n }\n return await parseBody<T>(res, url);\n};\n\n/**\n * Creates a low-level Compose API client.\n *\n * @param options - Client configuration including the API base URL.\n * @returns A {@link ComposeClient} instance.\n */\nexport const createComposeClient = (\n options: ComposeClientOptions,\n): ComposeClient => {\n if (!options.baseUrl || !/^https?:\\/\\//i.test(options.baseUrl)) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n `Invalid baseUrl: expected an HTTP(S) URL, got \"${options.baseUrl}\"`,\n );\n }\n const trimmedApiKey = options.apiKey?.trim() || undefined;\n if (!trimmedApiKey) {\n throw new ComposeError(\n 'VALIDATION_ERROR',\n 'apiKey is required: pass a LI.FI API key to createComposeSdk().',\n );\n }\n const fetchFn = options.fetch ?? globalThis.fetch;\n const base = options.baseUrl.replace(/\\/$/, '');\n\n const baseHeaders: Record<string, string> = {\n Accept: 'application/json',\n [COMPOSER_SDK_VERSION_HEADER]: SDK_VERSION,\n 'x-lifi-api-key': trimmedApiKey,\n };\n const transport: ComposeTransport = { fetchFn, baseHeaders };\n\n const getManifest = async (): Promise<ComposeManifest> =>\n getJson<ComposeManifest>(transport, `${base}/compose/manifest`);\n\n const getChains = async (): Promise<readonly ChainSummary[]> =>\n getJson<readonly ChainSummary[]>(transport, `${base}/chains`);\n\n const compile = async (\n request: ComposeCompileRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose`, request);\n\n const route = async (\n request: ComposeRouteRequest,\n ): Promise<ComposeCompileResult> =>\n postCompile(transport, `${base}/compose/route`, request);\n\n const getZapPacks = async (\n options?: GetZapPacksOptions,\n ): Promise<readonly ZapPackOverview[]> => {\n const params = new URLSearchParams();\n if (options?.protocols !== undefined) {\n // Backend expects a single comma-separated value, not repeated keys.\n const raw = options.protocols;\n const list = typeof raw === 'string' ? raw : raw.join(',');\n params.set('protocols', list);\n }\n const qs = params.toString();\n return getJson<readonly ZapPackOverview[]>(\n transport,\n `${base}/compose/zap-packs${qs ? `?${qs}` : ''}`,\n );\n };\n\n const simulate = async (\n request: SimulateRequest,\n ): Promise<SimulateResult> => {\n const url = `${base}/simulate`;\n const res = await send(transport, url, { method: 'POST', body: request });\n // Only 200 (carries `ok`/`revert`) and 422 (carries the `error` member of\n // the union) have a discriminated body. 422 is deliberately intercepted\n // here (not thrown as VALIDATION_ERROR) so callers get one exhaustive\n // `switch (result.status)`. Every other status is a transport error and is\n // thrown — including HTTP 400 (malformed input, no `status` body) and any\n // unexpected 2xx.\n if (res.status === 200 || res.status === 422) {\n return await parseSimulateBody(res, url);\n }\n const body = await res.text();\n throw errorFromHttpResponse(res.status, body, url);\n };\n\n return { getManifest, getChains, compile, route, getZapPacks, simulate };\n};\n"],"mappings":";;;;AAmCA,MAAM,cAAA;AAGN,MAAM,qBAAqB,aAAa,WAAW;;;;;;;;AA2JnD,MAAa,kBAAkB,MAAc,UAC3C,OAAO,UAAU,WAAW,MAAM,SAAS,IAAI;AAEjD,MAAM,mBAAmB,MACvB,OAAO,MAAM,YAAY,MAAM;AAGjC,MAAM,iBAAiB;AAEvB,MAAM,gBAAgB,OAAgB,MAAc,QAAwB;CAC1E,IAAI,OAAO,UAAU,YAAY,CAAC,eAAe,KAAK,KAAK,GACzD,MAAM,IAAI,aACR,iBACA,+BAA+B,KAAK,MAClC,UAAU,KAAA,IAAY,WAAW,2BAEnC,EAAE,IAAI,CACR;CAEF,OAAO,OAAO,KAAK;AACrB;AAgBA,MAAM,aAAa,MAAc,MAAc,QAC7C,IAAI,aACF,iBACA,+BAA+B,KAAK,GAAG,QACvC,EAAE,IAAI,CACR;AAIF,MAAM,oBACJ,QACA,OACA,MACA,QACS;CACT,MAAM,OAAO,OAAO;CACpB,IAAI,SAAS,KAAA,GAAW;CACxB,IAAI,CAAC,gBAAgB,IAAI,GACvB,MAAM,UAAU,GAAG,KAAK,GAAG,SAAS,oBAAoB,GAAG;CAE7D,KAAK,QAAQ,aAAa,KAAK,OAAO,GAAG,KAAK,GAAG,MAAM,SAAS,GAAG;AACrE;AAKA,MAAM,iBAAiB,MAAsB,QAAsB;CACjE,MAAM,UAAU,KAAK;CACrB,IAAI,CAAC,gBAAgB,OAAO,GAC1B,MAAM,UACJ,WACA,YAAY,KAAA,IAAY,cAAc,oBACtC,GACF;CAEF,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,GAAG;EACtC,MAAM,QAAQ,QAAQ;EACtB,IAAI,CAAC,gBAAgB,KAAK,GACxB,MAAM,UAAU,WAAW,OAAO,oBAAoB,GAAG;EAE3D,MAAM,SAA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OAAO;CAEnD,MAAM,QAAQ,OACZ,YAEA,YAAY,WAAW,GAAG,KAAK,iBAAiB,OAAO;CAEzD,MAAM,cAAc,OAClB,YACwC;EACxC,MAAM,SAAS,IAAI,gBAAgB;EACnC,IAAI,SAAS,cAAc,KAAA,GAAW;GAEpC,MAAM,MAAM,QAAQ;GACpB,MAAM,OAAO,OAAO,QAAQ,WAAW,MAAM,IAAI,KAAK,GAAG;GACzD,OAAO,IAAI,aAAa,IAAI;EAC9B;EACA,MAAM,KAAK,OAAO,SAAS;EAC3B,OAAO,QACL,WACA,GAAG,KAAK,oBAAoB,KAAK,IAAI,OAAO,IAC9C;CACF;CAEA,MAAM,WAAW,OACf,YAC4B;EAC5B,MAAM,MAAM,GAAG,KAAK;EACpB,MAAM,MAAM,MAAM,KAAK,WAAW,KAAK;GAAE,QAAQ;GAAQ,MAAM;EAAQ,CAAC;EAOxE,IAAI,IAAI,WAAW,OAAO,IAAI,WAAW,KACvC,OAAO,MAAM,kBAAkB,KAAK,GAAG;EAEzC,MAAM,OAAO,MAAM,IAAI,KAAK;EAC5B,MAAM,sBAAsB,IAAI,QAAQ,MAAM,GAAG;CACnD;CAEA,OAAO;EAAE;EAAa;EAAW;EAAS;EAAO;EAAa;CAAS;AACzE"}
|
package/dist/discovery.cjs
CHANGED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __copyProps = (to, from, except, desc) => {
|
|
7
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
|
-
for (let key of __getOwnPropNames(from))
|
|
9
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
10
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
11
|
-
}
|
|
12
|
-
return to;
|
|
13
|
-
};
|
|
14
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
15
|
-
var discovery_exports = {};
|
|
16
|
-
module.exports = __toCommonJS(discovery_exports);
|
|
17
|
-
//# sourceMappingURL=discovery.cjs.map
|