@openmarketsai/connect-node 0.4.0 → 0.5.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/LICENSE +201 -0
- package/NOTICE +5 -0
- package/README.md +33 -1
- package/dist/index.cjs +74 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +132 -2
- package/dist/index.d.ts +132 -2
- package/dist/index.js +74 -3
- package/dist/index.js.map +1 -1
- package/package.json +23 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -93,7 +93,39 @@ deliveries older than 5 minutes are rejected.
|
|
|
93
93
|
| `orders.list(id)` | `GET /flow/v1/auth/orders` (act-as) |
|
|
94
94
|
| `orders.buy(orders, { actAs })` | `POST /flow/v1/auth/orders/buy` (act-as) |
|
|
95
95
|
| `data.leagues()` / `contestLiquidity(id)` | `GET /flow/v1/leagues`, `…/contests/:id/liquidity` |
|
|
96
|
-
| `
|
|
96
|
+
| `ai.invoke(params, { actAs })` | `POST /flow/v1/ai/inferences` + polls `GET …/:id` |
|
|
97
|
+
| `ai.inferences.create / get` | the same, one request at a time |
|
|
98
|
+
| `ai.providers({ actAs })` | `GET /flow/v1/ai/providers` |
|
|
99
|
+
| `request(method, path, opts)` | escape hatch (`opts.actAs` sets the header, `opts.idempotencyKey` sends `Idempotency-Key`) |
|
|
100
|
+
| `requestPage(path, opts)` / `requestAll(path, opts)` | list endpoints with their `next_cursor` — one page, or every page |
|
|
101
|
+
|
|
102
|
+
## AI Connect — run models on your user's own key
|
|
103
|
+
|
|
104
|
+
Turn it on for your org with `ai_providers: ['anthropic', 'openai']` in your Connect
|
|
105
|
+
config. Your users then see an **AI models** section in the hosted flow, where they
|
|
106
|
+
paste their own Anthropic or OpenAI API key. You never see the key.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
const r = await om.ai.invoke<{ pick: 'home' | 'away'; confidence: number }>({
|
|
110
|
+
provider: 'anthropic',
|
|
111
|
+
model: 'claude-opus-5',
|
|
112
|
+
system: 'You pick sides. Answer only in the schema.',
|
|
113
|
+
messages: [{ role: 'user', content: JSON.stringify(snapshot) }],
|
|
114
|
+
output_schema: { schema: PICK_SCHEMA },
|
|
115
|
+
}, { actAs: 'user-123' })
|
|
116
|
+
|
|
117
|
+
if (r.stop_reason === 'refusal') { /* not an answer */ }
|
|
118
|
+
r.output?.pick // parsed, schema-shaped
|
|
119
|
+
r.billing // 'byok' — calls on the user's key are NEVER charged by OpenMarkets
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
`billing` defaults to `'auto'`: the user's own key when they linked and shared it,
|
|
123
|
+
otherwise OpenMarkets-hosted models charged in reasoning credits. Send
|
|
124
|
+
`billing: 'byok'` to guarantee a call is never charged (it fails with
|
|
125
|
+
`409 ai_provider_not_linked` instead of falling back).
|
|
126
|
+
|
|
127
|
+
Long calls return 202 server-side; `invoke` polls for you and throws
|
|
128
|
+
`AiInferenceFailedError` if the call fails.
|
|
97
129
|
|
|
98
130
|
## Errors
|
|
99
131
|
|
package/dist/index.cjs
CHANGED
|
@@ -62,13 +62,20 @@ function constructWebhookEvent(secret, rawBody, signatureHeader, opts = {}) {
|
|
|
62
62
|
throw new WebhookSignatureError("Webhook body is not valid JSON");
|
|
63
63
|
}
|
|
64
64
|
}
|
|
65
|
+
var AiInferenceFailedError = class extends Error {
|
|
66
|
+
constructor(inference) {
|
|
67
|
+
super(inference.error?.message ?? "The inference failed");
|
|
68
|
+
this.name = "AiInferenceFailedError";
|
|
69
|
+
this.inference = inference;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
65
72
|
function createClient(options) {
|
|
66
73
|
if (!options.apiKey) throw new Error("createClient: apiKey is required");
|
|
67
74
|
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
68
75
|
const doFetch = options.fetch ?? globalThis.fetch;
|
|
69
76
|
if (!doFetch) throw new Error("No fetch available \u2014 pass options.fetch (Node < 18)");
|
|
70
77
|
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
71
|
-
async function
|
|
78
|
+
async function send(method, path, opts = {}) {
|
|
72
79
|
const url = new URL(baseUrl + path);
|
|
73
80
|
for (const [k, v] of Object.entries(opts.query ?? {})) {
|
|
74
81
|
if (v !== void 0) url.searchParams.set(k, String(v));
|
|
@@ -79,6 +86,7 @@ function createClient(options) {
|
|
|
79
86
|
};
|
|
80
87
|
if (opts.body !== void 0) headers["Content-Type"] = "application/json";
|
|
81
88
|
if (opts.actAs) headers["X-OpenMarkets-Account"] = opts.actAs;
|
|
89
|
+
if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
|
|
82
90
|
const ctrl = new AbortController();
|
|
83
91
|
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
84
92
|
let res;
|
|
@@ -109,7 +117,56 @@ function createClient(options) {
|
|
|
109
117
|
err?.details
|
|
110
118
|
);
|
|
111
119
|
}
|
|
112
|
-
return envelope
|
|
120
|
+
return envelope ?? {};
|
|
121
|
+
}
|
|
122
|
+
async function request(method, path, opts = {}) {
|
|
123
|
+
return (await send(method, path, opts)).data ?? void 0;
|
|
124
|
+
}
|
|
125
|
+
async function requestPage(path, opts = {}) {
|
|
126
|
+
const env = await send("GET", path, opts);
|
|
127
|
+
return {
|
|
128
|
+
data: env.data ?? [],
|
|
129
|
+
next_cursor: env.pagination?.next_cursor ?? null,
|
|
130
|
+
has_more: env.pagination?.has_more ?? !!env.pagination?.next_cursor
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
async function requestAll(path, opts = {}) {
|
|
134
|
+
const { maxPages = 50, ...rest } = opts;
|
|
135
|
+
const out = [];
|
|
136
|
+
let cursor;
|
|
137
|
+
for (let page = 0; page < maxPages; page++) {
|
|
138
|
+
const p = await requestPage(path, { ...rest, query: { ...rest.query ?? {}, cursor } });
|
|
139
|
+
out.push(...p.data);
|
|
140
|
+
if (!p.next_cursor) break;
|
|
141
|
+
cursor = p.next_cursor;
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
async function invoke(params, opts = {}) {
|
|
146
|
+
const deadline = Date.now() + (opts.timeoutMs ?? 6e5);
|
|
147
|
+
const pollMs = opts.pollIntervalMs ?? 2e3;
|
|
148
|
+
let inf = await request("POST", "/flow/v1/ai/inferences", {
|
|
149
|
+
body: params,
|
|
150
|
+
actAs: opts.actAs,
|
|
151
|
+
idempotencyKey: crypto__default.default.randomUUID()
|
|
152
|
+
});
|
|
153
|
+
while (inf.status === "running") {
|
|
154
|
+
if (Date.now() > deadline) {
|
|
155
|
+
throw new OpenMarketsError(
|
|
156
|
+
408,
|
|
157
|
+
"poll_timeout",
|
|
158
|
+
`Inference ${inf.inference_id} is still running; poll ai.inferences.get() to collect it`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
162
|
+
inf = await request(
|
|
163
|
+
"GET",
|
|
164
|
+
`/flow/v1/ai/inferences/${encodeURIComponent(inf.inference_id)}`,
|
|
165
|
+
{ actAs: opts.actAs }
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
if (inf.status === "failed") throw new AiInferenceFailedError(inf);
|
|
169
|
+
return inf;
|
|
113
170
|
}
|
|
114
171
|
function requireSecret() {
|
|
115
172
|
if (!options.webhookSecret) {
|
|
@@ -119,6 +176,8 @@ function createClient(options) {
|
|
|
119
176
|
}
|
|
120
177
|
return {
|
|
121
178
|
request,
|
|
179
|
+
requestPage,
|
|
180
|
+
requestAll,
|
|
122
181
|
connect: {
|
|
123
182
|
users: {
|
|
124
183
|
provision: (params) => request("POST", "/flow/v1/connect/users", { body: params }),
|
|
@@ -160,10 +219,23 @@ function createClient(options) {
|
|
|
160
219
|
data: {
|
|
161
220
|
leagues: () => request("GET", "/flow/v1/leagues"),
|
|
162
221
|
contestLiquidity: (contestId) => request("GET", `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`)
|
|
222
|
+
},
|
|
223
|
+
ai: {
|
|
224
|
+
invoke,
|
|
225
|
+
inferences: {
|
|
226
|
+
create: (params, opts = {}) => request("POST", "/flow/v1/ai/inferences", {
|
|
227
|
+
body: params,
|
|
228
|
+
actAs: opts.actAs,
|
|
229
|
+
idempotencyKey: opts.idempotencyKey
|
|
230
|
+
}),
|
|
231
|
+
get: (inferenceId, opts = {}) => request("GET", `/flow/v1/ai/inferences/${encodeURIComponent(inferenceId)}`, { actAs: opts.actAs })
|
|
232
|
+
},
|
|
233
|
+
providers: (opts = {}) => request("GET", "/flow/v1/ai/providers", { actAs: opts.actAs })
|
|
163
234
|
}
|
|
164
235
|
};
|
|
165
236
|
}
|
|
166
237
|
|
|
238
|
+
exports.AiInferenceFailedError = AiInferenceFailedError;
|
|
167
239
|
exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
|
|
168
240
|
exports.OpenMarketsError = OpenMarketsError;
|
|
169
241
|
exports.WebhookSignatureError = WebhookSignatureError;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":["crypto"],"mappings":";;;;;;;;;AAkBO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAIxC,WAAA,CAAY,MAAA,EAAgB,IAAA,EAAc,OAAA,EAAiB,OAAA,EAAmC;AAC1F,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,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index.cjs","sourcesContent":["/**\n * @openmarketsai/connect-node\n *\n * Server SDK for OpenMarkets Connect. A thin, typed wrapper over the Flow API:\n * provision your users, mint hosted link sessions, verify webhook deliveries,\n * read on a user's behalf, and execute orders on their account.\n *\n * import { createClient } from '@openmarketsai/connect-node'\n * const om = createClient({ apiKey: process.env.OM_API_KEY! })\n *\n * await om.connect.users.provision({ external_user_id: 'user-123' })\n * const { token } = await om.connect.linkSessions.create({ external_user_id: 'user-123' })\n * await om.orders.buy([leg], { actAs: 'user-123' })\n *\n * Pairs with @openmarketsai/connect-web (the in-app launcher).\n */\nimport crypto from 'node:crypto'\n\nexport const DEFAULT_BASE_URL = 'https://api.openmarkets.ai'\n\n// ──────────────────────────────────────────────────────────────────────────\n// Errors\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Thrown when the API returns a non-2xx response. Mirrors the Flow error envelope. */\nexport class OpenMarketsError extends Error {\n readonly status: number\n readonly code: string\n readonly details?: Record<string, unknown>\n constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'OpenMarketsError'\n this.status = status\n this.code = code\n this.details = details\n }\n}\n\n/** Thrown by `constructWebhookEvent` when a signature is missing, stale, or invalid. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WebhookSignatureError'\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Webhook verification (matches src/utils/webhook-signature.ts byte-for-byte)\n//\n// Header: X-OpenMarkets-Signature: t=<unix_seconds>,v1=<hex hmac>\n// Signed string: `${t}.${rawBody}`, HMAC-SHA256 with your whsec_ secret.\n// IMPORTANT: verify over the EXACT raw request body, not a re-serialized object.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type ConnectWebhookEventType =\n | 'user.partners_connected'\n | 'user.permissions_changed'\n | (string & {})\n\nexport interface ConnectWebhookEvent {\n type: ConnectWebhookEventType\n [key: string]: unknown\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature timestamp, in seconds. Default 300 (5 min). 0 disables. */\n toleranceSec?: number\n /** Injectable clock for testing. */\n nowSec?: number\n}\n\nfunction toRaw(body: string | Buffer): string {\n return typeof body === 'string' ? body : body.toString('utf8')\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n const parts = header.split(',').reduce<Record<string, string>>((acc, kv) => {\n const idx = kv.indexOf('=')\n if (idx > 0) acc[kv.slice(0, idx).trim()] = kv.slice(idx + 1).trim()\n return acc\n }, {})\n const t = Number(parts.t)\n if (!parts.v1 || !isFinite(t)) return null\n return { t, v1: parts.v1 }\n}\n\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'hex')\n const bb = Buffer.from(b, 'hex')\n if (ab.length === 0 || ab.length !== bb.length) return false\n return crypto.timingSafeEqual(ab, bb)\n}\n\n/** Verify a webhook signature. Returns false on any failure (never throws). */\nexport function verifyWebhookSignature(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return false\n const toleranceSec = opts.toleranceSec ?? 300\n const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000)\n if (toleranceSec > 0 && Math.abs(nowSec - parsed.t) > toleranceSec) return false\n const expected = crypto\n .createHmac('sha256', secret)\n .update(`${parsed.t}.${toRaw(rawBody)}`)\n .digest('hex')\n return timingSafeEqualHex(expected, parsed.v1)\n}\n\n/** Verify the signature and return the parsed event, or throw `WebhookSignatureError`. */\nexport function constructWebhookEvent(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): ConnectWebhookEvent {\n if (!verifyWebhookSignature(secret, rawBody, signatureHeader, opts)) {\n throw new WebhookSignatureError('Invalid or expired webhook signature')\n }\n try {\n return JSON.parse(toRaw(rawBody)) as ConnectWebhookEvent\n } catch {\n throw new WebhookSignatureError('Webhook body is not valid JSON')\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Client\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface OpenMarketsClientOptions {\n /** Your Connect org API key. Sent as `X-API-Key`. */\n apiKey: string\n /** API base URL. Defaults to https://api.openmarkets.ai. */\n baseUrl?: string\n /** Your webhook signing secret (`whsec_…`), enabling `client.webhooks.*`. */\n webhookSecret?: string\n /** Custom fetch (defaults to global fetch; Node 18+). */\n fetch?: typeof fetch\n /** Per-request timeout in ms. Default 30000. */\n timeoutMs?: number\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */\n actAs?: string\n}\n\n// Inputs (snake_case to match the API — buy legs map 1:1 from liquidity entries).\nexport interface ProvisionUserParams {\n external_user_id: string\n email?: string\n name?: string\n}\nexport type LinkSessionMode = 'connect' | 'manage'\nexport interface CreateLinkSessionParams {\n external_user_id: string\n return_url?: string\n mode?: LinkSessionMode\n allowed_partners?: string[]\n /** Pick a specific org Connect config; omit to use the org's default (if any). */\n connect_config_id?: string\n}\nexport interface BuyOrder {\n /** What to buy — set exactly one of position_hash or liquidity_hash. */\n position_hash?: string\n liquidity_hash?: string\n /** Size — set exactly one of amount or shares. */\n amount?: number // stake, notional USD\n shares?: number // contract count (each pays $1 on win)\n /** Price ceiling, 0..1 exclusive — won't fill above this. */\n max_price: number\n /** Optional — pin a venue; omit to route to the best price. */\n partner_id?: string\n /** Optional — 'real' (default) or 'paper' (practice book). */\n mode?: 'real' | 'paper'\n}\n\n// Outputs (light — partners can pass a type param for stricter typing).\n/**\n * `POST /flow/v1/connect/users`. Idempotent — safe to call on every login.\n *\n * `om_account_id` is the field an integration actually needs (it addresses the\n * user in later calls) and was previously absent, so it typed as `unknown` via\n * the index signature.\n */\nexport interface ProvisionResult {\n /** Our id for this user. Pass as `actAs` when trading on their behalf. */\n om_account_id: string\n external_user_id: string\n /** false when the user already existed. */\n created: boolean\n [key: string]: unknown\n}\n/**\n * The response of `POST /flow/v1/connect/link-sessions`.\n *\n * These names are the API's, verified against the route rather than assumed:\n * it returns `link_token`, NOT `token`. The previous declaration named `token`,\n * `external_user_id` and `mode` — none of which the endpoint sends — so the one\n * field an integration actually needs type-checked as a string and arrived\n * `undefined`, opening the hosted flow with `token=undefined`. The index\n * signature below is what kept that quiet; keep these names in step with\n * `CreateLinkSessionResult` in LinkSessionOrchestrator.\n */\nexport interface LinkSession {\n link_session_id: string\n /** Single-use, expires in 15 minutes. Hand to `createConnect().open()`. */\n link_token: string\n /** The hosted flow URL, for redirect mode or a native in-app browser. */\n hosted_url: string\n expires_at: string\n [key: string]: unknown\n}\n/**\n * The status of one leg, mirroring `flowLegStatus` in the API.\n *\n * ALL FIVE values are reachable. This union previously listed only three, so a\n * `switch` written against the SDK's types compiled clean and silently fell\n * through for a resting or pending order — an order that IS live, sitting on a\n * venue book, treated as if it had never been placed. Any change here must\n * follow the API, not the other way round.\n */\nexport type BuyLegStatus =\n /** Filled or partially filled. */\n | 'completed'\n /** Live on the venue's book, unfilled. Not a failure — check back. */\n | 'resting'\n /** Accepted by the venue, fill not yet confirmed (async venues). */\n | 'pending'\n /** The venue or a pre-trade gate rejected it. */\n | 'failed'\n /** No viable venue was found; nothing was sent. */\n | 'rejected'\n\n/**\n * What an organization's END USERS see and may do in the hosted flow. Mirrors\n * `ConnectConfigBody` server-side.\n *\n * A `null` field means \"no restriction / use the default\" throughout, so an\n * organization with no config behaves exactly as Connect did before configs\n * existed. Read that as permissive, not as unset.\n */\nexport interface ConnectConfig {\n version: number\n /** Partner ids or names offered in the picker. null = every venue we support. */\n venue_allowlist: string[] | null\n /** Surface the OpenMarkets practice book as a credential-less venue. */\n offer_internal_book: boolean\n /**\n * Currencies users may trade. `['ATLAS']` is practice-only and is ENFORCED\n * on every order path, not merely hidden in the UI — users can still link\n * venues, read balances and sync history; only real-money orders are\n * refused.\n */\n allowed_currencies: string[]\n /** DERIVED from allowed_currencies server-side. Sending it has no effect. */\n allow_real_money: boolean\n /** Permissions the user is asked to grant. null = all of them. */\n available_scopes: ConnectScope[] | null\n branding: { display_name?: string; logo_url?: string; primary_color?: string } | null\n allowed_return_urls: string[] | null\n default_link_mode: LinkSessionMode\n [key: string]: unknown\n}\n\n/** Permissions an end user grants per connected venue. */\nexport type ConnectScope = 'history:read' | 'trade:execute' | 'balance:read'\n\nexport interface ConnectConfigResult {\n /** null when the organization has never saved one — `config` is the defaults. */\n connect_config_id: string | null\n config: ConnectConfig\n /**\n * Present on update: how many EXISTING users the change was applied to.\n * A funding-mode change reaches users already provisioned, not just future\n * ones, so this reports what actually happened.\n */\n reconcile?: { scanned: number; reconciled: number; failed: number } | null\n}\n\nexport interface BuyResult {\n results: Array<{\n index: number\n status: BuyLegStatus\n /** NULL when the leg was rejected before routing — no decision was made. */\n sor_decision_id: string | null\n filled_notional: number\n filled_shares: number\n /** The un-buyable remainder of the requested stake. */\n unfilled_notional: number\n avg_price: number | null\n rejected_reason: string | null\n venues: Array<{\n partner_id: string\n success: boolean\n router_order_id: string | null\n error: string | null\n }>\n }>\n}\n\ninterface FlowEnvelope<T> {\n data?: T\n error?: { code: string; message: string; details?: Record<string, unknown> }\n}\n\nexport interface OpenMarketsClient {\n /** Generic typed request — escape hatch for endpoints without a helper. */\n request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>\n connect: {\n users: {\n provision(params: ProvisionUserParams): Promise<ProvisionResult>\n get<T = unknown>(externalUserId: string): Promise<T>\n getPolicy<T = unknown>(externalUserId: string): Promise<T>\n }\n linkSessions: {\n create(params: CreateLinkSessionParams): Promise<LinkSession>\n get<T = unknown>(linkSessionId: string): Promise<T>\n }\n /**\n * The organization's Connect config — which venues appear, whether real\n * money is allowed, and how the hosted flow is branded.\n *\n * Requires a PLAYER JWT with workspace admin, not an API key: this is\n * account governance rather than a data-API capability. `update` sends a\n * whole body (it is normalized server-side), so read, change, write.\n */\n configs: {\n get(workspaceId: string): Promise<ConnectConfigResult>\n update(workspaceId: string, config: Partial<ConnectConfig>): Promise<ConnectConfigResult>\n }\n webhooks: {\n getConfig<T = unknown>(): Promise<T>\n /** Verify a delivery using the configured `webhookSecret`. */\n verify(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): boolean\n /** Verify + parse, or throw. Uses the configured `webhookSecret`. */\n constructEvent(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): ConnectWebhookEvent\n }\n }\n account: {\n partners<T = unknown>(externalUserId: string): Promise<T>\n balances<T = unknown>(externalUserId: string): Promise<T>\n }\n orders: {\n list<T = unknown>(externalUserId: string): Promise<T>\n buy(orders: BuyOrder[], opts: { actAs: string }): Promise<BuyResult>\n }\n data: {\n leagues<T = unknown>(): Promise<T>\n contestLiquidity<T = unknown>(contestId: string): Promise<T>\n }\n}\n\nexport function createClient(options: OpenMarketsClientOptions): OpenMarketsClient {\n if (!options.apiKey) throw new Error('createClient: apiKey is required')\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const doFetch = options.fetch ?? globalThis.fetch\n if (!doFetch) throw new Error('No fetch available — pass options.fetch (Node < 18)')\n const timeoutMs = options.timeoutMs ?? 30_000\n\n async function request<T = unknown>(\n method: HttpMethod,\n path: string,\n opts: RequestOptions = {},\n ): Promise<T> {\n const url = new URL(baseUrl + path)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v))\n }\n const headers: Record<string, string> = {\n 'X-API-Key': options.apiKey,\n Accept: 'application/json',\n }\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json'\n if (opts.actAs) headers['X-OpenMarkets-Account'] = opts.actAs\n\n const ctrl = new AbortController()\n const timer = setTimeout(() => ctrl.abort(), timeoutMs)\n let res: Response\n try {\n res = await doFetch(url.toString(), {\n method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n\n let envelope: FlowEnvelope<T> | undefined\n const text = await res.text()\n if (text) {\n try {\n envelope = JSON.parse(text) as FlowEnvelope<T>\n } catch {\n /* non-JSON body */\n }\n }\n\n if (!res.ok) {\n const err = envelope?.error\n throw new OpenMarketsError(\n res.status,\n err?.code ?? 'http_error',\n err?.message ?? `Request failed with status ${res.status}`,\n err?.details,\n )\n }\n return (envelope?.data ?? (undefined as unknown)) as T\n }\n\n function requireSecret(): string {\n if (!options.webhookSecret) {\n throw new Error('webhookSecret was not provided to createClient()')\n }\n return options.webhookSecret\n }\n\n return {\n request,\n connect: {\n users: {\n provision: (params) =>\n request<ProvisionResult>('POST', '/flow/v1/connect/users', { body: params }),\n get: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}`),\n getPolicy: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}/policy`),\n },\n linkSessions: {\n create: (params) =>\n request<LinkSession>('POST', '/flow/v1/connect/link-sessions', { body: params }),\n get: (linkSessionId) =>\n request('GET', `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`),\n },\n configs: {\n get: (workspaceId: string) =>\n request<ConnectConfigResult>(\n 'GET', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n ),\n update: (workspaceId: string, config: Partial<ConnectConfig>) =>\n request<ConnectConfigResult>(\n 'PUT', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n { body: { config } },\n ),\n },\n webhooks: {\n getConfig: () => request('GET', '/flow/v1/connect/webhook-config'),\n verify: (rawBody, sig, opts) =>\n verifyWebhookSignature(requireSecret(), rawBody, sig, opts),\n constructEvent: (rawBody, sig, opts) =>\n constructWebhookEvent(requireSecret(), rawBody, sig, opts),\n },\n },\n account: {\n partners: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/partners', { actAs: externalUserId }),\n balances: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/balances', { actAs: externalUserId }),\n },\n orders: {\n list: (externalUserId) =>\n request('GET', '/flow/v1/auth/orders', { actAs: externalUserId }),\n buy: (orders, opts) =>\n request<BuyResult>('POST', '/flow/v1/auth/orders/buy', {\n body: { orders },\n actAs: opts.actAs,\n }),\n },\n data: {\n leagues: () => request('GET', '/flow/v1/leagues'),\n contestLiquidity: (contestId) =>\n request('GET', `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`),\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":["crypto"],"mappings":";;;;;;;;;AAmBO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAIxC,WAAA,CAAY,MAAA,EAAgB,IAAA,EAAc,OAAA,EAAiB,OAAA,EAAmC;AAC1F,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACnB;AACJ;AAGO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC7C,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EAChB;AACJ;AA4BA,SAAS,MAAM,IAAA,EAA+B;AAC1C,EAAA,OAAO,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,IAAA,CAAK,SAAS,MAAM,CAAA;AACjE;AAEA,SAAS,qBAAqB,MAAA,EAAkD;AAC5E,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,CAAM,GAAG,EAAE,MAAA,CAA+B,CAAC,KAA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A0B,kBAAA,CAAmB,WAAW,CAAC,CAAA,CAAA,EAAI,EAAE,KAAA,EAAO,IAAA,CAAK,OAAO;AAAA,OACzG;AAAA,MACA,SAAA,EAAW,CAAC,IAAA,GAAO,EAAC,KAAM,OAAA,CAAQ,KAAA,EAAO,uBAAA,EAAyB,EAAE,KAAA,EAAO,IAAA,CAAK,KAAA,EAAO;AAAA;AAC3F,GACJ;AACJ","file":"index.cjs","sourcesContent":["/**\n * @openmarketsai/connect-node\n *\n * Server SDK for OpenMarkets Connect. A thin, typed wrapper over the Flow API:\n * provision your users, mint hosted link sessions, verify webhook deliveries,\n * read on a user's behalf, and execute orders on their account.\n *\n * import { createClient } from '@openmarketsai/connect-node'\n * const om = createClient({ apiKey: process.env.OM_API_KEY! })\n *\n * await om.connect.users.provision({ external_user_id: 'user-123' })\n * const { token } = await om.connect.linkSessions.create({ external_user_id: 'user-123' })\n * await om.orders.buy([leg], { actAs: 'user-123' })\n * const r = await om.ai.invoke({ provider: 'anthropic', model: 'claude-opus-5', messages }, { actAs: 'user-123' })\n *\n * Pairs with @openmarketsai/connect-web (the in-app launcher).\n */\nimport crypto from 'node:crypto'\n\nexport const DEFAULT_BASE_URL = 'https://api.openmarkets.ai'\n\n// ──────────────────────────────────────────────────────────────────────────\n// Errors\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Thrown when the API returns a non-2xx response. Mirrors the Flow error envelope. */\nexport class OpenMarketsError extends Error {\n readonly status: number\n readonly code: string\n readonly details?: Record<string, unknown>\n constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'OpenMarketsError'\n this.status = status\n this.code = code\n this.details = details\n }\n}\n\n/** Thrown by `constructWebhookEvent` when a signature is missing, stale, or invalid. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WebhookSignatureError'\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Webhook verification (matches src/utils/webhook-signature.ts byte-for-byte)\n//\n// Header: X-OpenMarkets-Signature: t=<unix_seconds>,v1=<hex hmac>\n// Signed string: `${t}.${rawBody}`, HMAC-SHA256 with your whsec_ secret.\n// IMPORTANT: verify over the EXACT raw request body, not a re-serialized object.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type ConnectWebhookEventType =\n | 'user.partners_connected'\n | 'user.permissions_changed'\n | 'user.history_synced'\n | (string & {})\n\nexport interface ConnectWebhookEvent {\n type: ConnectWebhookEventType\n [key: string]: unknown\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature timestamp, in seconds. Default 300 (5 min). 0 disables. */\n toleranceSec?: number\n /** Injectable clock for testing. */\n nowSec?: number\n}\n\nfunction toRaw(body: string | Buffer): string {\n return typeof body === 'string' ? body : body.toString('utf8')\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n const parts = header.split(',').reduce<Record<string, string>>((acc, kv) => {\n const idx = kv.indexOf('=')\n if (idx > 0) acc[kv.slice(0, idx).trim()] = kv.slice(idx + 1).trim()\n return acc\n }, {})\n const t = Number(parts.t)\n if (!parts.v1 || !isFinite(t)) return null\n return { t, v1: parts.v1 }\n}\n\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'hex')\n const bb = Buffer.from(b, 'hex')\n if (ab.length === 0 || ab.length !== bb.length) return false\n return crypto.timingSafeEqual(ab, bb)\n}\n\n/** Verify a webhook signature. Returns false on any failure (never throws). */\nexport function verifyWebhookSignature(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return false\n const toleranceSec = opts.toleranceSec ?? 300\n const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000)\n if (toleranceSec > 0 && Math.abs(nowSec - parsed.t) > toleranceSec) return false\n const expected = crypto\n .createHmac('sha256', secret)\n .update(`${parsed.t}.${toRaw(rawBody)}`)\n .digest('hex')\n return timingSafeEqualHex(expected, parsed.v1)\n}\n\n/** Verify the signature and return the parsed event, or throw `WebhookSignatureError`. */\nexport function constructWebhookEvent(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): ConnectWebhookEvent {\n if (!verifyWebhookSignature(secret, rawBody, signatureHeader, opts)) {\n throw new WebhookSignatureError('Invalid or expired webhook signature')\n }\n try {\n return JSON.parse(toRaw(rawBody)) as ConnectWebhookEvent\n } catch {\n throw new WebhookSignatureError('Webhook body is not valid JSON')\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Client\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface OpenMarketsClientOptions {\n /** Your Connect org API key. Sent as `X-API-Key`. */\n apiKey: string\n /** API base URL. Defaults to https://api.openmarkets.ai. */\n baseUrl?: string\n /** Your webhook signing secret (`whsec_…`), enabling `client.webhooks.*`. */\n webhookSecret?: string\n /** Custom fetch (defaults to global fetch; Node 18+). */\n fetch?: typeof fetch\n /** Per-request timeout in ms. Default 30000. */\n timeoutMs?: number\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */\n actAs?: string\n /** Sent as `Idempotency-Key`: a retried POST replays instead of repeating. */\n idempotencyKey?: string\n}\n\n// Inputs (snake_case to match the API — buy legs map 1:1 from liquidity entries).\nexport interface ProvisionUserParams {\n external_user_id: string\n email?: string\n name?: string\n}\nexport type LinkSessionMode = 'connect' | 'manage'\nexport interface CreateLinkSessionParams {\n external_user_id: string\n return_url?: string\n mode?: LinkSessionMode\n allowed_partners?: string[]\n /** Pick a specific org Connect config; omit to use the org's default (if any). */\n connect_config_id?: string\n}\nexport interface BuyOrder {\n /** What to buy — set exactly one of position_hash or liquidity_hash. */\n position_hash?: string\n liquidity_hash?: string\n /** Size — set exactly one of amount or shares. */\n amount?: number // stake, notional USD\n shares?: number // contract count (each pays $1 on win)\n /** Price ceiling, 0..1 exclusive — won't fill above this. */\n max_price: number\n /** Optional — pin a venue; omit to route to the best price. */\n partner_id?: string\n /** Optional — 'real' (default) or 'paper' (practice book). */\n mode?: 'real' | 'paper'\n}\n\n// Outputs (light — partners can pass a type param for stricter typing).\n/**\n * `POST /flow/v1/connect/users`. Idempotent — safe to call on every login.\n *\n * `om_account_id` is the field an integration actually needs (it addresses the\n * user in later calls) and was previously absent, so it typed as `unknown` via\n * the index signature.\n */\nexport interface ProvisionResult {\n /** Our id for this user. Pass as `actAs` when trading on their behalf. */\n om_account_id: string\n external_user_id: string\n /** false when the user already existed. */\n created: boolean\n [key: string]: unknown\n}\n/**\n * The response of `POST /flow/v1/connect/link-sessions`.\n *\n * These names are the API's, verified against the route rather than assumed:\n * it returns `link_token`, NOT `token`. The previous declaration named `token`,\n * `external_user_id` and `mode` — none of which the endpoint sends — so the one\n * field an integration actually needs type-checked as a string and arrived\n * `undefined`, opening the hosted flow with `token=undefined`. The index\n * signature below is what kept that quiet; keep these names in step with\n * `CreateLinkSessionResult` in LinkSessionOrchestrator.\n */\nexport interface LinkSession {\n link_session_id: string\n /** Single-use, expires in 15 minutes. Hand to `createConnect().open()`. */\n link_token: string\n /** The hosted flow URL, for redirect mode or a native in-app browser. */\n hosted_url: string\n expires_at: string\n [key: string]: unknown\n}\n/**\n * The status of one leg, mirroring `flowLegStatus` in the API.\n *\n * ALL FIVE values are reachable. This union previously listed only three, so a\n * `switch` written against the SDK's types compiled clean and silently fell\n * through for a resting or pending order — an order that IS live, sitting on a\n * venue book, treated as if it had never been placed. Any change here must\n * follow the API, not the other way round.\n */\nexport type BuyLegStatus =\n /** Filled or partially filled. */\n | 'completed'\n /** Live on the venue's book, unfilled. Not a failure — check back. */\n | 'resting'\n /** Accepted by the venue, fill not yet confirmed (async venues). */\n | 'pending'\n /** The venue or a pre-trade gate rejected it. */\n | 'failed'\n /** No viable venue was found; nothing was sent. */\n | 'rejected'\n\n/**\n * What an organization's END USERS see and may do in the hosted flow. Mirrors\n * `ConnectConfigBody` server-side.\n *\n * A `null` field means \"no restriction / use the default\" throughout, so an\n * organization with no config behaves exactly as Connect did before configs\n * existed. Read that as permissive, not as unset.\n */\nexport interface ConnectConfig {\n version: number\n /** Partner ids or names offered in the picker. null = every venue we support. */\n venue_allowlist: string[] | null\n /** Surface the OpenMarkets practice book as a credential-less venue. */\n offer_internal_book: boolean\n /**\n * Currencies users may trade. `['ATLAS']` is practice-only and is ENFORCED\n * on every order path, not merely hidden in the UI — users can still link\n * venues, read balances and sync history; only real-money orders are\n * refused.\n */\n allowed_currencies: string[]\n /** DERIVED from allowed_currencies server-side. Sending it has no effect. */\n allow_real_money: boolean\n /** Permissions the user is asked to grant. null = all of them. */\n available_scopes: ConnectScope[] | null\n branding: { display_name?: string; logo_url?: string; primary_color?: string } | null\n allowed_return_urls: string[] | null\n default_link_mode: LinkSessionMode\n /**\n * AI providers whose keys your users may link (AI Connect). OPT-IN: empty\n * means the hosted flow offers none — unlike venue_allowlist, where null\n * means everything.\n */\n ai_providers?: AiProvider[]\n [key: string]: unknown\n}\n\n/** Permissions an end user grants per connected venue. */\nexport type ConnectScope = 'history:read' | 'trade:execute' | 'balance:read'\n\nexport interface ConnectConfigResult {\n /** null when the organization has never saved one — `config` is the defaults. */\n connect_config_id: string | null\n config: ConnectConfig\n /**\n * Present on update: how many EXISTING users the change was applied to.\n * A funding-mode change reaches users already provisioned, not just future\n * ones, so this reports what actually happened.\n */\n reconcile?: { scanned: number; reconciled: number; failed: number } | null\n}\n\nexport interface BuyResult {\n results: Array<{\n index: number\n status: BuyLegStatus\n /** NULL when the leg was rejected before routing — no decision was made. */\n sor_decision_id: string | null\n filled_notional: number\n filled_shares: number\n /** The un-buyable remainder of the requested stake. */\n unfilled_notional: number\n avg_price: number | null\n rejected_reason: string | null\n venues: Array<{\n partner_id: string\n success: boolean\n router_order_id: string | null\n error: string | null\n }>\n }>\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// AI Connect — run models on a user's OWN linked key (never charged by\n// OpenMarkets) or on OpenMarkets' key (charged in reasoning credits).\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type AiProvider = 'anthropic' | 'openai'\n/** 'auto' (default): the user's own key when linked and shared, else managed. */\nexport type AiBilling = 'auto' | 'byok' | 'managed'\nexport type AiStopReason = 'end' | 'max_tokens' | 'stop_sequence' | 'refusal' | 'tool_use' | 'paused' | 'context_exceeded'\n\nexport interface AiInferenceParams {\n provider: AiProvider\n /** The provider's own model id, passed through verbatim (e.g. 'claude-opus-5'). */\n model: string\n system?: string\n messages: Array<{ role: 'user' | 'assistant'; content: string }>\n /** 1..21000. Default 8192. */\n max_tokens?: number\n /** Only sent when set — several current models reject any explicit value. */\n temperature?: number\n /** Constrain the answer to a JSON schema; the parsed object arrives as `output`. */\n output_schema?: { name?: string; schema: Record<string, unknown>; strict?: boolean }\n billing?: AiBilling\n /** Seconds the server holds the request before answering 202 (0..25). */\n wait_seconds?: number\n /** Your own bookkeeping labels, returned on the result. */\n metadata?: Record<string, string>\n}\n\nexport interface AiInference<TOutput = unknown> {\n inference_id: string\n status: 'running' | 'succeeded' | 'failed'\n provider: AiProvider\n model: string\n /** The model the provider says actually served the call. */\n served_model: string | null\n /** 'byok' calls are never charged by OpenMarkets. */\n billing: 'byok' | 'managed'\n output_text: string | null\n /** Parsed JSON when `output_schema` was sent and the answer parsed; else null. */\n output: TOutput | null\n /** Check this before trusting `output` — a refusal is not an answer. */\n stop_reason: AiStopReason | null\n usage: { input_tokens: number; output_tokens: number; credits_charged: number }\n error: { code: string; message: string } | null\n metadata: Record<string, string> | null\n latency_ms: number | null\n created_at: string\n completed_at: string | null\n}\n\nexport interface AiProviderConnection {\n provider: AiProvider\n label: string\n key_hint: string\n credential_status: 'pending' | 'connected' | 'failed'\n /** Whether the user shares the key with your app. */\n invoke_granted: boolean\n monthly_token_cap: number | null\n last_used_at: string | null\n connected_at: string\n}\n\nexport interface AiInvokeOptions {\n /** Run on this Connect user's account (their linked key). */\n actAs?: string\n /** Give up polling after this many ms (the call keeps running server-side). Default 600000. */\n timeoutMs?: number\n /** Delay between polls once the server has answered 202. Default 2000. */\n pollIntervalMs?: number\n}\n\n/** Thrown by `ai.invoke` when the inference finished in `failed`. */\nexport class AiInferenceFailedError extends Error {\n readonly inference: AiInference\n constructor(inference: AiInference) {\n super(inference.error?.message ?? 'The inference failed')\n this.name = 'AiInferenceFailedError'\n this.inference = inference\n }\n}\n\ninterface FlowEnvelope<T> {\n data?: T\n pagination?: { next_cursor?: string | null; has_more?: boolean }\n error?: { code: string; message: string; details?: Record<string, unknown> }\n}\n\n/** One page of a list endpoint, with the cursor `request()` drops. */\nexport interface Page<T> {\n data: T[]\n /** Pass back as `query.cursor` for the next page; null on the last page. */\n next_cursor: string | null\n has_more: boolean\n}\n\nexport interface OpenMarketsClient {\n /** Generic typed request — escape hatch for endpoints without a helper. */\n request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>\n /**\n * GET one page of a list endpoint. `request()` returns only `data`, so a list's\n * `pagination.next_cursor` was unreachable through the SDK — found by the model\n * arena, which could not page through `/contests` or `/auth/orders`.\n */\n requestPage<T = unknown>(path: string, opts?: Omit<RequestOptions, 'body'>): Promise<Page<T>>\n /** Every item of a list endpoint, following cursors (stops after `maxPages`, default 50). */\n requestAll<T = unknown>(path: string, opts?: Omit<RequestOptions, 'body'> & { maxPages?: number }): Promise<T[]>\n connect: {\n users: {\n provision(params: ProvisionUserParams): Promise<ProvisionResult>\n get<T = unknown>(externalUserId: string): Promise<T>\n getPolicy<T = unknown>(externalUserId: string): Promise<T>\n }\n linkSessions: {\n create(params: CreateLinkSessionParams): Promise<LinkSession>\n get<T = unknown>(linkSessionId: string): Promise<T>\n }\n /**\n * The organization's Connect config — which venues appear, whether real\n * money is allowed, and how the hosted flow is branded.\n *\n * Requires a PLAYER JWT with workspace admin, not an API key: this is\n * account governance rather than a data-API capability. `update` sends a\n * whole body (it is normalized server-side), so read, change, write.\n */\n configs: {\n get(workspaceId: string): Promise<ConnectConfigResult>\n update(workspaceId: string, config: Partial<ConnectConfig>): Promise<ConnectConfigResult>\n }\n webhooks: {\n getConfig<T = unknown>(): Promise<T>\n /** Verify a delivery using the configured `webhookSecret`. */\n verify(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): boolean\n /** Verify + parse, or throw. Uses the configured `webhookSecret`. */\n constructEvent(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): ConnectWebhookEvent\n }\n }\n account: {\n partners<T = unknown>(externalUserId: string): Promise<T>\n balances<T = unknown>(externalUserId: string): Promise<T>\n }\n orders: {\n list<T = unknown>(externalUserId: string): Promise<T>\n buy(orders: BuyOrder[], opts: { actAs: string }): Promise<BuyResult>\n }\n data: {\n leagues<T = unknown>(): Promise<T>\n contestLiquidity<T = unknown>(contestId: string): Promise<T>\n }\n ai: {\n /**\n * Run a model and wait for the result — polls through a 202 for you.\n * Throws `AiInferenceFailedError` when the call fails, `OpenMarketsError`\n * when it is refused up front (e.g. 409 ai_provider_not_linked).\n */\n invoke<TOutput = unknown>(params: AiInferenceParams, opts?: AiInvokeOptions): Promise<AiInference<TOutput>>\n inferences: {\n /** One request; may return `status: 'running'` (poll with `get`). */\n create<TOutput = unknown>(params: AiInferenceParams, opts?: { actAs?: string; idempotencyKey?: string }): Promise<AiInference<TOutput>>\n get<TOutput = unknown>(inferenceId: string, opts?: { actAs?: string }): Promise<AiInference<TOutput>>\n }\n /** Which AI providers the user has linked (never the key itself). */\n providers(opts?: { actAs?: string }): Promise<{ providers: AiProviderConnection[] }>\n }\n}\n\nexport function createClient(options: OpenMarketsClientOptions): OpenMarketsClient {\n if (!options.apiKey) throw new Error('createClient: apiKey is required')\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const doFetch = options.fetch ?? globalThis.fetch\n if (!doFetch) throw new Error('No fetch available — pass options.fetch (Node < 18)')\n const timeoutMs = options.timeoutMs ?? 30_000\n\n async function send<T>(method: HttpMethod, path: string, opts: RequestOptions = {}): Promise<FlowEnvelope<T>> {\n const url = new URL(baseUrl + path)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v))\n }\n const headers: Record<string, string> = {\n 'X-API-Key': options.apiKey,\n Accept: 'application/json',\n }\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json'\n if (opts.actAs) headers['X-OpenMarkets-Account'] = opts.actAs\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n\n const ctrl = new AbortController()\n const timer = setTimeout(() => ctrl.abort(), timeoutMs)\n let res: Response\n try {\n res = await doFetch(url.toString(), {\n method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n\n let envelope: FlowEnvelope<T> | undefined\n const text = await res.text()\n if (text) {\n try {\n envelope = JSON.parse(text) as FlowEnvelope<T>\n } catch {\n /* non-JSON body */\n }\n }\n\n if (!res.ok) {\n const err = envelope?.error\n throw new OpenMarketsError(\n res.status,\n err?.code ?? 'http_error',\n err?.message ?? `Request failed with status ${res.status}`,\n err?.details,\n )\n }\n return envelope ?? {}\n }\n\n async function request<T = unknown>(method: HttpMethod, path: string, opts: RequestOptions = {}): Promise<T> {\n return ((await send<T>(method, path, opts)).data ?? (undefined as unknown)) as T\n }\n\n async function requestPage<T = unknown>(path: string, opts: Omit<RequestOptions, 'body'> = {}): Promise<Page<T>> {\n const env = await send<T[]>('GET', path, opts)\n return {\n data: env.data ?? [],\n next_cursor: env.pagination?.next_cursor ?? null,\n has_more: env.pagination?.has_more ?? !!env.pagination?.next_cursor,\n }\n }\n\n async function requestAll<T = unknown>(\n path: string,\n opts: Omit<RequestOptions, 'body'> & { maxPages?: number } = {},\n ): Promise<T[]> {\n const { maxPages = 50, ...rest } = opts\n const out: T[] = []\n let cursor: string | undefined\n for (let page = 0; page < maxPages; page++) {\n const p = await requestPage<T>(path, { ...rest, query: { ...(rest.query ?? {}), cursor } })\n out.push(...p.data)\n if (!p.next_cursor) break\n cursor = p.next_cursor\n }\n return out\n }\n\n async function invoke<TOutput>(params: AiInferenceParams, opts: AiInvokeOptions = {}): Promise<AiInference<TOutput>> {\n const deadline = Date.now() + (opts.timeoutMs ?? 600_000)\n const pollMs = opts.pollIntervalMs ?? 2_000\n // One key per logical call: if the POST is retried after a network drop,\n // the server replays it instead of running (and charging for) it twice.\n let inf = await request<AiInference<TOutput>>('POST', '/flow/v1/ai/inferences', {\n body: params,\n actAs: opts.actAs,\n idempotencyKey: crypto.randomUUID(),\n })\n while (inf.status === 'running') {\n if (Date.now() > deadline) {\n throw new OpenMarketsError(408, 'poll_timeout',\n `Inference ${inf.inference_id} is still running; poll ai.inferences.get() to collect it`)\n }\n await new Promise((r) => setTimeout(r, pollMs))\n inf = await request<AiInference<TOutput>>(\n 'GET', `/flow/v1/ai/inferences/${encodeURIComponent(inf.inference_id)}`, { actAs: opts.actAs },\n )\n }\n if (inf.status === 'failed') throw new AiInferenceFailedError(inf as AiInference)\n return inf\n }\n\n function requireSecret(): string {\n if (!options.webhookSecret) {\n throw new Error('webhookSecret was not provided to createClient()')\n }\n return options.webhookSecret\n }\n\n return {\n request,\n requestPage,\n requestAll,\n connect: {\n users: {\n provision: (params) =>\n request<ProvisionResult>('POST', '/flow/v1/connect/users', { body: params }),\n get: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}`),\n getPolicy: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}/policy`),\n },\n linkSessions: {\n create: (params) =>\n request<LinkSession>('POST', '/flow/v1/connect/link-sessions', { body: params }),\n get: (linkSessionId) =>\n request('GET', `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`),\n },\n configs: {\n get: (workspaceId: string) =>\n request<ConnectConfigResult>(\n 'GET', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n ),\n update: (workspaceId: string, config: Partial<ConnectConfig>) =>\n request<ConnectConfigResult>(\n 'PUT', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n { body: { config } },\n ),\n },\n webhooks: {\n getConfig: () => request('GET', '/flow/v1/connect/webhook-config'),\n verify: (rawBody, sig, opts) =>\n verifyWebhookSignature(requireSecret(), rawBody, sig, opts),\n constructEvent: (rawBody, sig, opts) =>\n constructWebhookEvent(requireSecret(), rawBody, sig, opts),\n },\n },\n account: {\n partners: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/partners', { actAs: externalUserId }),\n balances: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/balances', { actAs: externalUserId }),\n },\n orders: {\n list: (externalUserId) =>\n request('GET', '/flow/v1/auth/orders', { actAs: externalUserId }),\n buy: (orders, opts) =>\n request<BuyResult>('POST', '/flow/v1/auth/orders/buy', {\n body: { orders },\n actAs: opts.actAs,\n }),\n },\n data: {\n leagues: () => request('GET', '/flow/v1/leagues'),\n contestLiquidity: (contestId) =>\n request('GET', `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`),\n },\n ai: {\n invoke,\n inferences: {\n create: (params, opts = {}) =>\n request('POST', '/flow/v1/ai/inferences', {\n body: params,\n actAs: opts.actAs,\n idempotencyKey: opts.idempotencyKey,\n }),\n get: (inferenceId, opts = {}) =>\n request('GET', `/flow/v1/ai/inferences/${encodeURIComponent(inferenceId)}`, { actAs: opts.actAs }),\n },\n providers: (opts = {}) => request('GET', '/flow/v1/ai/providers', { actAs: opts.actAs }),\n },\n }\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -10,7 +10,7 @@ declare class OpenMarketsError extends Error {
|
|
|
10
10
|
declare class WebhookSignatureError extends Error {
|
|
11
11
|
constructor(message: string);
|
|
12
12
|
}
|
|
13
|
-
type ConnectWebhookEventType = 'user.partners_connected' | 'user.permissions_changed' | (string & {});
|
|
13
|
+
type ConnectWebhookEventType = 'user.partners_connected' | 'user.permissions_changed' | 'user.history_synced' | (string & {});
|
|
14
14
|
interface ConnectWebhookEvent {
|
|
15
15
|
type: ConnectWebhookEventType;
|
|
16
16
|
[key: string]: unknown;
|
|
@@ -43,6 +43,8 @@ interface RequestOptions {
|
|
|
43
43
|
body?: unknown;
|
|
44
44
|
/** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */
|
|
45
45
|
actAs?: string;
|
|
46
|
+
/** Sent as `Idempotency-Key`: a retried POST replays instead of repeating. */
|
|
47
|
+
idempotencyKey?: string;
|
|
46
48
|
}
|
|
47
49
|
interface ProvisionUserParams {
|
|
48
50
|
external_user_id: string;
|
|
@@ -159,6 +161,12 @@ interface ConnectConfig {
|
|
|
159
161
|
} | null;
|
|
160
162
|
allowed_return_urls: string[] | null;
|
|
161
163
|
default_link_mode: LinkSessionMode;
|
|
164
|
+
/**
|
|
165
|
+
* AI providers whose keys your users may link (AI Connect). OPT-IN: empty
|
|
166
|
+
* means the hosted flow offers none — unlike venue_allowlist, where null
|
|
167
|
+
* means everything.
|
|
168
|
+
*/
|
|
169
|
+
ai_providers?: AiProvider[];
|
|
162
170
|
[key: string]: unknown;
|
|
163
171
|
}
|
|
164
172
|
/** Permissions an end user grants per connected venue. */
|
|
@@ -198,9 +206,107 @@ interface BuyResult {
|
|
|
198
206
|
}>;
|
|
199
207
|
}>;
|
|
200
208
|
}
|
|
209
|
+
type AiProvider = 'anthropic' | 'openai';
|
|
210
|
+
/** 'auto' (default): the user's own key when linked and shared, else managed. */
|
|
211
|
+
type AiBilling = 'auto' | 'byok' | 'managed';
|
|
212
|
+
type AiStopReason = 'end' | 'max_tokens' | 'stop_sequence' | 'refusal' | 'tool_use' | 'paused' | 'context_exceeded';
|
|
213
|
+
interface AiInferenceParams {
|
|
214
|
+
provider: AiProvider;
|
|
215
|
+
/** The provider's own model id, passed through verbatim (e.g. 'claude-opus-5'). */
|
|
216
|
+
model: string;
|
|
217
|
+
system?: string;
|
|
218
|
+
messages: Array<{
|
|
219
|
+
role: 'user' | 'assistant';
|
|
220
|
+
content: string;
|
|
221
|
+
}>;
|
|
222
|
+
/** 1..21000. Default 8192. */
|
|
223
|
+
max_tokens?: number;
|
|
224
|
+
/** Only sent when set — several current models reject any explicit value. */
|
|
225
|
+
temperature?: number;
|
|
226
|
+
/** Constrain the answer to a JSON schema; the parsed object arrives as `output`. */
|
|
227
|
+
output_schema?: {
|
|
228
|
+
name?: string;
|
|
229
|
+
schema: Record<string, unknown>;
|
|
230
|
+
strict?: boolean;
|
|
231
|
+
};
|
|
232
|
+
billing?: AiBilling;
|
|
233
|
+
/** Seconds the server holds the request before answering 202 (0..25). */
|
|
234
|
+
wait_seconds?: number;
|
|
235
|
+
/** Your own bookkeeping labels, returned on the result. */
|
|
236
|
+
metadata?: Record<string, string>;
|
|
237
|
+
}
|
|
238
|
+
interface AiInference<TOutput = unknown> {
|
|
239
|
+
inference_id: string;
|
|
240
|
+
status: 'running' | 'succeeded' | 'failed';
|
|
241
|
+
provider: AiProvider;
|
|
242
|
+
model: string;
|
|
243
|
+
/** The model the provider says actually served the call. */
|
|
244
|
+
served_model: string | null;
|
|
245
|
+
/** 'byok' calls are never charged by OpenMarkets. */
|
|
246
|
+
billing: 'byok' | 'managed';
|
|
247
|
+
output_text: string | null;
|
|
248
|
+
/** Parsed JSON when `output_schema` was sent and the answer parsed; else null. */
|
|
249
|
+
output: TOutput | null;
|
|
250
|
+
/** Check this before trusting `output` — a refusal is not an answer. */
|
|
251
|
+
stop_reason: AiStopReason | null;
|
|
252
|
+
usage: {
|
|
253
|
+
input_tokens: number;
|
|
254
|
+
output_tokens: number;
|
|
255
|
+
credits_charged: number;
|
|
256
|
+
};
|
|
257
|
+
error: {
|
|
258
|
+
code: string;
|
|
259
|
+
message: string;
|
|
260
|
+
} | null;
|
|
261
|
+
metadata: Record<string, string> | null;
|
|
262
|
+
latency_ms: number | null;
|
|
263
|
+
created_at: string;
|
|
264
|
+
completed_at: string | null;
|
|
265
|
+
}
|
|
266
|
+
interface AiProviderConnection {
|
|
267
|
+
provider: AiProvider;
|
|
268
|
+
label: string;
|
|
269
|
+
key_hint: string;
|
|
270
|
+
credential_status: 'pending' | 'connected' | 'failed';
|
|
271
|
+
/** Whether the user shares the key with your app. */
|
|
272
|
+
invoke_granted: boolean;
|
|
273
|
+
monthly_token_cap: number | null;
|
|
274
|
+
last_used_at: string | null;
|
|
275
|
+
connected_at: string;
|
|
276
|
+
}
|
|
277
|
+
interface AiInvokeOptions {
|
|
278
|
+
/** Run on this Connect user's account (their linked key). */
|
|
279
|
+
actAs?: string;
|
|
280
|
+
/** Give up polling after this many ms (the call keeps running server-side). Default 600000. */
|
|
281
|
+
timeoutMs?: number;
|
|
282
|
+
/** Delay between polls once the server has answered 202. Default 2000. */
|
|
283
|
+
pollIntervalMs?: number;
|
|
284
|
+
}
|
|
285
|
+
/** Thrown by `ai.invoke` when the inference finished in `failed`. */
|
|
286
|
+
declare class AiInferenceFailedError extends Error {
|
|
287
|
+
readonly inference: AiInference;
|
|
288
|
+
constructor(inference: AiInference);
|
|
289
|
+
}
|
|
290
|
+
/** One page of a list endpoint, with the cursor `request()` drops. */
|
|
291
|
+
interface Page<T> {
|
|
292
|
+
data: T[];
|
|
293
|
+
/** Pass back as `query.cursor` for the next page; null on the last page. */
|
|
294
|
+
next_cursor: string | null;
|
|
295
|
+
has_more: boolean;
|
|
296
|
+
}
|
|
201
297
|
interface OpenMarketsClient {
|
|
202
298
|
/** Generic typed request — escape hatch for endpoints without a helper. */
|
|
203
299
|
request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>;
|
|
300
|
+
/**
|
|
301
|
+
* GET one page of a list endpoint. `request()` returns only `data`, so a list's
|
|
302
|
+
* `pagination.next_cursor` was unreachable through the SDK — found by the model
|
|
303
|
+
* arena, which could not page through `/contests` or `/auth/orders`.
|
|
304
|
+
*/
|
|
305
|
+
requestPage<T = unknown>(path: string, opts?: Omit<RequestOptions, 'body'>): Promise<Page<T>>;
|
|
306
|
+
/** Every item of a list endpoint, following cursors (stops after `maxPages`, default 50). */
|
|
307
|
+
requestAll<T = unknown>(path: string, opts?: Omit<RequestOptions, 'body'> & {
|
|
308
|
+
maxPages?: number;
|
|
309
|
+
}): Promise<T[]>;
|
|
204
310
|
connect: {
|
|
205
311
|
users: {
|
|
206
312
|
provision(params: ProvisionUserParams): Promise<ProvisionResult>;
|
|
@@ -245,7 +351,31 @@ interface OpenMarketsClient {
|
|
|
245
351
|
leagues<T = unknown>(): Promise<T>;
|
|
246
352
|
contestLiquidity<T = unknown>(contestId: string): Promise<T>;
|
|
247
353
|
};
|
|
354
|
+
ai: {
|
|
355
|
+
/**
|
|
356
|
+
* Run a model and wait for the result — polls through a 202 for you.
|
|
357
|
+
* Throws `AiInferenceFailedError` when the call fails, `OpenMarketsError`
|
|
358
|
+
* when it is refused up front (e.g. 409 ai_provider_not_linked).
|
|
359
|
+
*/
|
|
360
|
+
invoke<TOutput = unknown>(params: AiInferenceParams, opts?: AiInvokeOptions): Promise<AiInference<TOutput>>;
|
|
361
|
+
inferences: {
|
|
362
|
+
/** One request; may return `status: 'running'` (poll with `get`). */
|
|
363
|
+
create<TOutput = unknown>(params: AiInferenceParams, opts?: {
|
|
364
|
+
actAs?: string;
|
|
365
|
+
idempotencyKey?: string;
|
|
366
|
+
}): Promise<AiInference<TOutput>>;
|
|
367
|
+
get<TOutput = unknown>(inferenceId: string, opts?: {
|
|
368
|
+
actAs?: string;
|
|
369
|
+
}): Promise<AiInference<TOutput>>;
|
|
370
|
+
};
|
|
371
|
+
/** Which AI providers the user has linked (never the key itself). */
|
|
372
|
+
providers(opts?: {
|
|
373
|
+
actAs?: string;
|
|
374
|
+
}): Promise<{
|
|
375
|
+
providers: AiProviderConnection[];
|
|
376
|
+
}>;
|
|
377
|
+
};
|
|
248
378
|
}
|
|
249
379
|
declare function createClient(options: OpenMarketsClientOptions): OpenMarketsClient;
|
|
250
380
|
|
|
251
|
-
export { type BuyLegStatus, type BuyOrder, type BuyResult, type ConnectConfig, type ConnectConfigResult, type ConnectScope, type ConnectWebhookEvent, type ConnectWebhookEventType, type CreateLinkSessionParams, DEFAULT_BASE_URL, type HttpMethod, type LinkSession, type LinkSessionMode, type OpenMarketsClient, type OpenMarketsClientOptions, OpenMarketsError, type ProvisionResult, type ProvisionUserParams, type RequestOptions, type VerifyWebhookOptions, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
|
381
|
+
export { type AiBilling, type AiInference, AiInferenceFailedError, type AiInferenceParams, type AiInvokeOptions, type AiProvider, type AiProviderConnection, type AiStopReason, type BuyLegStatus, type BuyOrder, type BuyResult, type ConnectConfig, type ConnectConfigResult, type ConnectScope, type ConnectWebhookEvent, type ConnectWebhookEventType, type CreateLinkSessionParams, DEFAULT_BASE_URL, type HttpMethod, type LinkSession, type LinkSessionMode, type OpenMarketsClient, type OpenMarketsClientOptions, OpenMarketsError, type Page, type ProvisionResult, type ProvisionUserParams, type RequestOptions, type VerifyWebhookOptions, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ declare class OpenMarketsError extends Error {
|
|
|
10
10
|
declare class WebhookSignatureError extends Error {
|
|
11
11
|
constructor(message: string);
|
|
12
12
|
}
|
|
13
|
-
type ConnectWebhookEventType = 'user.partners_connected' | 'user.permissions_changed' | (string & {});
|
|
13
|
+
type ConnectWebhookEventType = 'user.partners_connected' | 'user.permissions_changed' | 'user.history_synced' | (string & {});
|
|
14
14
|
interface ConnectWebhookEvent {
|
|
15
15
|
type: ConnectWebhookEventType;
|
|
16
16
|
[key: string]: unknown;
|
|
@@ -43,6 +43,8 @@ interface RequestOptions {
|
|
|
43
43
|
body?: unknown;
|
|
44
44
|
/** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */
|
|
45
45
|
actAs?: string;
|
|
46
|
+
/** Sent as `Idempotency-Key`: a retried POST replays instead of repeating. */
|
|
47
|
+
idempotencyKey?: string;
|
|
46
48
|
}
|
|
47
49
|
interface ProvisionUserParams {
|
|
48
50
|
external_user_id: string;
|
|
@@ -159,6 +161,12 @@ interface ConnectConfig {
|
|
|
159
161
|
} | null;
|
|
160
162
|
allowed_return_urls: string[] | null;
|
|
161
163
|
default_link_mode: LinkSessionMode;
|
|
164
|
+
/**
|
|
165
|
+
* AI providers whose keys your users may link (AI Connect). OPT-IN: empty
|
|
166
|
+
* means the hosted flow offers none — unlike venue_allowlist, where null
|
|
167
|
+
* means everything.
|
|
168
|
+
*/
|
|
169
|
+
ai_providers?: AiProvider[];
|
|
162
170
|
[key: string]: unknown;
|
|
163
171
|
}
|
|
164
172
|
/** Permissions an end user grants per connected venue. */
|
|
@@ -198,9 +206,107 @@ interface BuyResult {
|
|
|
198
206
|
}>;
|
|
199
207
|
}>;
|
|
200
208
|
}
|
|
209
|
+
type AiProvider = 'anthropic' | 'openai';
|
|
210
|
+
/** 'auto' (default): the user's own key when linked and shared, else managed. */
|
|
211
|
+
type AiBilling = 'auto' | 'byok' | 'managed';
|
|
212
|
+
type AiStopReason = 'end' | 'max_tokens' | 'stop_sequence' | 'refusal' | 'tool_use' | 'paused' | 'context_exceeded';
|
|
213
|
+
interface AiInferenceParams {
|
|
214
|
+
provider: AiProvider;
|
|
215
|
+
/** The provider's own model id, passed through verbatim (e.g. 'claude-opus-5'). */
|
|
216
|
+
model: string;
|
|
217
|
+
system?: string;
|
|
218
|
+
messages: Array<{
|
|
219
|
+
role: 'user' | 'assistant';
|
|
220
|
+
content: string;
|
|
221
|
+
}>;
|
|
222
|
+
/** 1..21000. Default 8192. */
|
|
223
|
+
max_tokens?: number;
|
|
224
|
+
/** Only sent when set — several current models reject any explicit value. */
|
|
225
|
+
temperature?: number;
|
|
226
|
+
/** Constrain the answer to a JSON schema; the parsed object arrives as `output`. */
|
|
227
|
+
output_schema?: {
|
|
228
|
+
name?: string;
|
|
229
|
+
schema: Record<string, unknown>;
|
|
230
|
+
strict?: boolean;
|
|
231
|
+
};
|
|
232
|
+
billing?: AiBilling;
|
|
233
|
+
/** Seconds the server holds the request before answering 202 (0..25). */
|
|
234
|
+
wait_seconds?: number;
|
|
235
|
+
/** Your own bookkeeping labels, returned on the result. */
|
|
236
|
+
metadata?: Record<string, string>;
|
|
237
|
+
}
|
|
238
|
+
interface AiInference<TOutput = unknown> {
|
|
239
|
+
inference_id: string;
|
|
240
|
+
status: 'running' | 'succeeded' | 'failed';
|
|
241
|
+
provider: AiProvider;
|
|
242
|
+
model: string;
|
|
243
|
+
/** The model the provider says actually served the call. */
|
|
244
|
+
served_model: string | null;
|
|
245
|
+
/** 'byok' calls are never charged by OpenMarkets. */
|
|
246
|
+
billing: 'byok' | 'managed';
|
|
247
|
+
output_text: string | null;
|
|
248
|
+
/** Parsed JSON when `output_schema` was sent and the answer parsed; else null. */
|
|
249
|
+
output: TOutput | null;
|
|
250
|
+
/** Check this before trusting `output` — a refusal is not an answer. */
|
|
251
|
+
stop_reason: AiStopReason | null;
|
|
252
|
+
usage: {
|
|
253
|
+
input_tokens: number;
|
|
254
|
+
output_tokens: number;
|
|
255
|
+
credits_charged: number;
|
|
256
|
+
};
|
|
257
|
+
error: {
|
|
258
|
+
code: string;
|
|
259
|
+
message: string;
|
|
260
|
+
} | null;
|
|
261
|
+
metadata: Record<string, string> | null;
|
|
262
|
+
latency_ms: number | null;
|
|
263
|
+
created_at: string;
|
|
264
|
+
completed_at: string | null;
|
|
265
|
+
}
|
|
266
|
+
interface AiProviderConnection {
|
|
267
|
+
provider: AiProvider;
|
|
268
|
+
label: string;
|
|
269
|
+
key_hint: string;
|
|
270
|
+
credential_status: 'pending' | 'connected' | 'failed';
|
|
271
|
+
/** Whether the user shares the key with your app. */
|
|
272
|
+
invoke_granted: boolean;
|
|
273
|
+
monthly_token_cap: number | null;
|
|
274
|
+
last_used_at: string | null;
|
|
275
|
+
connected_at: string;
|
|
276
|
+
}
|
|
277
|
+
interface AiInvokeOptions {
|
|
278
|
+
/** Run on this Connect user's account (their linked key). */
|
|
279
|
+
actAs?: string;
|
|
280
|
+
/** Give up polling after this many ms (the call keeps running server-side). Default 600000. */
|
|
281
|
+
timeoutMs?: number;
|
|
282
|
+
/** Delay between polls once the server has answered 202. Default 2000. */
|
|
283
|
+
pollIntervalMs?: number;
|
|
284
|
+
}
|
|
285
|
+
/** Thrown by `ai.invoke` when the inference finished in `failed`. */
|
|
286
|
+
declare class AiInferenceFailedError extends Error {
|
|
287
|
+
readonly inference: AiInference;
|
|
288
|
+
constructor(inference: AiInference);
|
|
289
|
+
}
|
|
290
|
+
/** One page of a list endpoint, with the cursor `request()` drops. */
|
|
291
|
+
interface Page<T> {
|
|
292
|
+
data: T[];
|
|
293
|
+
/** Pass back as `query.cursor` for the next page; null on the last page. */
|
|
294
|
+
next_cursor: string | null;
|
|
295
|
+
has_more: boolean;
|
|
296
|
+
}
|
|
201
297
|
interface OpenMarketsClient {
|
|
202
298
|
/** Generic typed request — escape hatch for endpoints without a helper. */
|
|
203
299
|
request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>;
|
|
300
|
+
/**
|
|
301
|
+
* GET one page of a list endpoint. `request()` returns only `data`, so a list's
|
|
302
|
+
* `pagination.next_cursor` was unreachable through the SDK — found by the model
|
|
303
|
+
* arena, which could not page through `/contests` or `/auth/orders`.
|
|
304
|
+
*/
|
|
305
|
+
requestPage<T = unknown>(path: string, opts?: Omit<RequestOptions, 'body'>): Promise<Page<T>>;
|
|
306
|
+
/** Every item of a list endpoint, following cursors (stops after `maxPages`, default 50). */
|
|
307
|
+
requestAll<T = unknown>(path: string, opts?: Omit<RequestOptions, 'body'> & {
|
|
308
|
+
maxPages?: number;
|
|
309
|
+
}): Promise<T[]>;
|
|
204
310
|
connect: {
|
|
205
311
|
users: {
|
|
206
312
|
provision(params: ProvisionUserParams): Promise<ProvisionResult>;
|
|
@@ -245,7 +351,31 @@ interface OpenMarketsClient {
|
|
|
245
351
|
leagues<T = unknown>(): Promise<T>;
|
|
246
352
|
contestLiquidity<T = unknown>(contestId: string): Promise<T>;
|
|
247
353
|
};
|
|
354
|
+
ai: {
|
|
355
|
+
/**
|
|
356
|
+
* Run a model and wait for the result — polls through a 202 for you.
|
|
357
|
+
* Throws `AiInferenceFailedError` when the call fails, `OpenMarketsError`
|
|
358
|
+
* when it is refused up front (e.g. 409 ai_provider_not_linked).
|
|
359
|
+
*/
|
|
360
|
+
invoke<TOutput = unknown>(params: AiInferenceParams, opts?: AiInvokeOptions): Promise<AiInference<TOutput>>;
|
|
361
|
+
inferences: {
|
|
362
|
+
/** One request; may return `status: 'running'` (poll with `get`). */
|
|
363
|
+
create<TOutput = unknown>(params: AiInferenceParams, opts?: {
|
|
364
|
+
actAs?: string;
|
|
365
|
+
idempotencyKey?: string;
|
|
366
|
+
}): Promise<AiInference<TOutput>>;
|
|
367
|
+
get<TOutput = unknown>(inferenceId: string, opts?: {
|
|
368
|
+
actAs?: string;
|
|
369
|
+
}): Promise<AiInference<TOutput>>;
|
|
370
|
+
};
|
|
371
|
+
/** Which AI providers the user has linked (never the key itself). */
|
|
372
|
+
providers(opts?: {
|
|
373
|
+
actAs?: string;
|
|
374
|
+
}): Promise<{
|
|
375
|
+
providers: AiProviderConnection[];
|
|
376
|
+
}>;
|
|
377
|
+
};
|
|
248
378
|
}
|
|
249
379
|
declare function createClient(options: OpenMarketsClientOptions): OpenMarketsClient;
|
|
250
380
|
|
|
251
|
-
export { type BuyLegStatus, type BuyOrder, type BuyResult, type ConnectConfig, type ConnectConfigResult, type ConnectScope, type ConnectWebhookEvent, type ConnectWebhookEventType, type CreateLinkSessionParams, DEFAULT_BASE_URL, type HttpMethod, type LinkSession, type LinkSessionMode, type OpenMarketsClient, type OpenMarketsClientOptions, OpenMarketsError, type ProvisionResult, type ProvisionUserParams, type RequestOptions, type VerifyWebhookOptions, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
|
381
|
+
export { type AiBilling, type AiInference, AiInferenceFailedError, type AiInferenceParams, type AiInvokeOptions, type AiProvider, type AiProviderConnection, type AiStopReason, type BuyLegStatus, type BuyOrder, type BuyResult, type ConnectConfig, type ConnectConfigResult, type ConnectScope, type ConnectWebhookEvent, type ConnectWebhookEventType, type CreateLinkSessionParams, DEFAULT_BASE_URL, type HttpMethod, type LinkSession, type LinkSessionMode, type OpenMarketsClient, type OpenMarketsClientOptions, OpenMarketsError, type Page, type ProvisionResult, type ProvisionUserParams, type RequestOptions, type VerifyWebhookOptions, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
package/dist/index.js
CHANGED
|
@@ -56,13 +56,20 @@ function constructWebhookEvent(secret, rawBody, signatureHeader, opts = {}) {
|
|
|
56
56
|
throw new WebhookSignatureError("Webhook body is not valid JSON");
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
+
var AiInferenceFailedError = class extends Error {
|
|
60
|
+
constructor(inference) {
|
|
61
|
+
super(inference.error?.message ?? "The inference failed");
|
|
62
|
+
this.name = "AiInferenceFailedError";
|
|
63
|
+
this.inference = inference;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
59
66
|
function createClient(options) {
|
|
60
67
|
if (!options.apiKey) throw new Error("createClient: apiKey is required");
|
|
61
68
|
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
62
69
|
const doFetch = options.fetch ?? globalThis.fetch;
|
|
63
70
|
if (!doFetch) throw new Error("No fetch available \u2014 pass options.fetch (Node < 18)");
|
|
64
71
|
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
65
|
-
async function
|
|
72
|
+
async function send(method, path, opts = {}) {
|
|
66
73
|
const url = new URL(baseUrl + path);
|
|
67
74
|
for (const [k, v] of Object.entries(opts.query ?? {})) {
|
|
68
75
|
if (v !== void 0) url.searchParams.set(k, String(v));
|
|
@@ -73,6 +80,7 @@ function createClient(options) {
|
|
|
73
80
|
};
|
|
74
81
|
if (opts.body !== void 0) headers["Content-Type"] = "application/json";
|
|
75
82
|
if (opts.actAs) headers["X-OpenMarkets-Account"] = opts.actAs;
|
|
83
|
+
if (opts.idempotencyKey) headers["Idempotency-Key"] = opts.idempotencyKey;
|
|
76
84
|
const ctrl = new AbortController();
|
|
77
85
|
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
78
86
|
let res;
|
|
@@ -103,7 +111,56 @@ function createClient(options) {
|
|
|
103
111
|
err?.details
|
|
104
112
|
);
|
|
105
113
|
}
|
|
106
|
-
return envelope
|
|
114
|
+
return envelope ?? {};
|
|
115
|
+
}
|
|
116
|
+
async function request(method, path, opts = {}) {
|
|
117
|
+
return (await send(method, path, opts)).data ?? void 0;
|
|
118
|
+
}
|
|
119
|
+
async function requestPage(path, opts = {}) {
|
|
120
|
+
const env = await send("GET", path, opts);
|
|
121
|
+
return {
|
|
122
|
+
data: env.data ?? [],
|
|
123
|
+
next_cursor: env.pagination?.next_cursor ?? null,
|
|
124
|
+
has_more: env.pagination?.has_more ?? !!env.pagination?.next_cursor
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
async function requestAll(path, opts = {}) {
|
|
128
|
+
const { maxPages = 50, ...rest } = opts;
|
|
129
|
+
const out = [];
|
|
130
|
+
let cursor;
|
|
131
|
+
for (let page = 0; page < maxPages; page++) {
|
|
132
|
+
const p = await requestPage(path, { ...rest, query: { ...rest.query ?? {}, cursor } });
|
|
133
|
+
out.push(...p.data);
|
|
134
|
+
if (!p.next_cursor) break;
|
|
135
|
+
cursor = p.next_cursor;
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
async function invoke(params, opts = {}) {
|
|
140
|
+
const deadline = Date.now() + (opts.timeoutMs ?? 6e5);
|
|
141
|
+
const pollMs = opts.pollIntervalMs ?? 2e3;
|
|
142
|
+
let inf = await request("POST", "/flow/v1/ai/inferences", {
|
|
143
|
+
body: params,
|
|
144
|
+
actAs: opts.actAs,
|
|
145
|
+
idempotencyKey: crypto.randomUUID()
|
|
146
|
+
});
|
|
147
|
+
while (inf.status === "running") {
|
|
148
|
+
if (Date.now() > deadline) {
|
|
149
|
+
throw new OpenMarketsError(
|
|
150
|
+
408,
|
|
151
|
+
"poll_timeout",
|
|
152
|
+
`Inference ${inf.inference_id} is still running; poll ai.inferences.get() to collect it`
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
156
|
+
inf = await request(
|
|
157
|
+
"GET",
|
|
158
|
+
`/flow/v1/ai/inferences/${encodeURIComponent(inf.inference_id)}`,
|
|
159
|
+
{ actAs: opts.actAs }
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
if (inf.status === "failed") throw new AiInferenceFailedError(inf);
|
|
163
|
+
return inf;
|
|
107
164
|
}
|
|
108
165
|
function requireSecret() {
|
|
109
166
|
if (!options.webhookSecret) {
|
|
@@ -113,6 +170,8 @@ function createClient(options) {
|
|
|
113
170
|
}
|
|
114
171
|
return {
|
|
115
172
|
request,
|
|
173
|
+
requestPage,
|
|
174
|
+
requestAll,
|
|
116
175
|
connect: {
|
|
117
176
|
users: {
|
|
118
177
|
provision: (params) => request("POST", "/flow/v1/connect/users", { body: params }),
|
|
@@ -154,10 +213,22 @@ function createClient(options) {
|
|
|
154
213
|
data: {
|
|
155
214
|
leagues: () => request("GET", "/flow/v1/leagues"),
|
|
156
215
|
contestLiquidity: (contestId) => request("GET", `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`)
|
|
216
|
+
},
|
|
217
|
+
ai: {
|
|
218
|
+
invoke,
|
|
219
|
+
inferences: {
|
|
220
|
+
create: (params, opts = {}) => request("POST", "/flow/v1/ai/inferences", {
|
|
221
|
+
body: params,
|
|
222
|
+
actAs: opts.actAs,
|
|
223
|
+
idempotencyKey: opts.idempotencyKey
|
|
224
|
+
}),
|
|
225
|
+
get: (inferenceId, opts = {}) => request("GET", `/flow/v1/ai/inferences/${encodeURIComponent(inferenceId)}`, { actAs: opts.actAs })
|
|
226
|
+
},
|
|
227
|
+
providers: (opts = {}) => request("GET", "/flow/v1/ai/providers", { actAs: opts.actAs })
|
|
157
228
|
}
|
|
158
229
|
};
|
|
159
230
|
}
|
|
160
231
|
|
|
161
|
-
export { DEFAULT_BASE_URL, OpenMarketsError, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
|
232
|
+
export { AiInferenceFailedError, DEFAULT_BASE_URL, OpenMarketsError, WebhookSignatureError, constructWebhookEvent, createClient, verifyWebhookSignature };
|
|
162
233
|
//# sourceMappingURL=index.js.map
|
|
163
234
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAkBO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAIxC,WAAA,CAAY,MAAA,EAAgB,IAAA,EAAc,OAAA,EAAiB,OAAA,EAAmC;AAC1F,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACnB;AACJ;AAGO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC7C,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,uBAAA;AAAA,EAChB;AACJ;AA2BA,SAAS,MAAM,IAAA,EAA+B;AAC1C,EAAA,OAAO,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,GAAO,IAAA,CAAK,SAAS,MAAM,CAAA;AACjE;AAEA,SAAS,qBAAqB,M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AA,CAAQ,OAAO,gCAAA,EAAkC,EAAE,KAAA,EAAO,cAAA,EAAgB,CAAA;AAAA,MAC9E,QAAA,EAAU,CAAC,cAAA,KACP,OAAA,CAAQ,OAAO,gCAAA,EAAkC,EAAE,KAAA,EAAO,cAAA,EAAgB;AAAA,KAClF;AAAA,IACA,MAAA,EAAQ;AAAA,MACJ,IAAA,EAAM,CAAC,cAAA,KACH,OAAA,CAAQ,OAAO,sBAAA,EAAwB,EAAE,KAAA,EAAO,cAAA,EAAgB,CAAA;AAAA,MACpE,KAAK,CAAC,MAAA,EAAQ,IAAA,KACV,OAAA,CAAmB,QAAQ,0BAAA,EAA4B;AAAA,QACnD,IAAA,EAAM,EAAE,MAAA,EAAO;AAAA,QACf,OAAO,IAAA,CAAK;AAAA,OACf;AAAA,KACT;AAAA,IACA,IAAA,EAAM;AAAA,MACF,OAAA,EAAS,MAAM,OAAA,CAAQ,KAAA,EAAO,kBAAkB,CAAA;AAAA,MAChD,gBAAA,EAAkB,CAAC,SAAA,KACf,OAAA,CAAQ,OAAO,CAAA,kBAAA,EAAqB,kBAAA,CAAmB,SAAS,CAAC,CAAA,UAAA,CAAY;AAAA;AACrF,GACJ;AACJ","file":"index.js","sourcesContent":["/**\n * @openmarketsai/connect-node\n *\n * Server SDK for OpenMarkets Connect. A thin, typed wrapper over the Flow API:\n * provision your users, mint hosted link sessions, verify webhook deliveries,\n * read on a user's behalf, and execute orders on their account.\n *\n * import { createClient } from '@openmarketsai/connect-node'\n * const om = createClient({ apiKey: process.env.OM_API_KEY! })\n *\n * await om.connect.users.provision({ external_user_id: 'user-123' })\n * const { token } = await om.connect.linkSessions.create({ external_user_id: 'user-123' })\n * await om.orders.buy([leg], { actAs: 'user-123' })\n *\n * Pairs with @openmarketsai/connect-web (the in-app launcher).\n */\nimport crypto from 'node:crypto'\n\nexport const DEFAULT_BASE_URL = 'https://api.openmarkets.ai'\n\n// ──────────────────────────────────────────────────────────────────────────\n// Errors\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Thrown when the API returns a non-2xx response. Mirrors the Flow error envelope. */\nexport class OpenMarketsError extends Error {\n readonly status: number\n readonly code: string\n readonly details?: Record<string, unknown>\n constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'OpenMarketsError'\n this.status = status\n this.code = code\n this.details = details\n }\n}\n\n/** Thrown by `constructWebhookEvent` when a signature is missing, stale, or invalid. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WebhookSignatureError'\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Webhook verification (matches src/utils/webhook-signature.ts byte-for-byte)\n//\n// Header: X-OpenMarkets-Signature: t=<unix_seconds>,v1=<hex hmac>\n// Signed string: `${t}.${rawBody}`, HMAC-SHA256 with your whsec_ secret.\n// IMPORTANT: verify over the EXACT raw request body, not a re-serialized object.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type ConnectWebhookEventType =\n | 'user.partners_connected'\n | 'user.permissions_changed'\n | (string & {})\n\nexport interface ConnectWebhookEvent {\n type: ConnectWebhookEventType\n [key: string]: unknown\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature timestamp, in seconds. Default 300 (5 min). 0 disables. */\n toleranceSec?: number\n /** Injectable clock for testing. */\n nowSec?: number\n}\n\nfunction toRaw(body: string | Buffer): string {\n return typeof body === 'string' ? body : body.toString('utf8')\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n const parts = header.split(',').reduce<Record<string, string>>((acc, kv) => {\n const idx = kv.indexOf('=')\n if (idx > 0) acc[kv.slice(0, idx).trim()] = kv.slice(idx + 1).trim()\n return acc\n }, {})\n const t = Number(parts.t)\n if (!parts.v1 || !isFinite(t)) return null\n return { t, v1: parts.v1 }\n}\n\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'hex')\n const bb = Buffer.from(b, 'hex')\n if (ab.length === 0 || ab.length !== bb.length) return false\n return crypto.timingSafeEqual(ab, bb)\n}\n\n/** Verify a webhook signature. Returns false on any failure (never throws). */\nexport function verifyWebhookSignature(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return false\n const toleranceSec = opts.toleranceSec ?? 300\n const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000)\n if (toleranceSec > 0 && Math.abs(nowSec - parsed.t) > toleranceSec) return false\n const expected = crypto\n .createHmac('sha256', secret)\n .update(`${parsed.t}.${toRaw(rawBody)}`)\n .digest('hex')\n return timingSafeEqualHex(expected, parsed.v1)\n}\n\n/** Verify the signature and return the parsed event, or throw `WebhookSignatureError`. */\nexport function constructWebhookEvent(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): ConnectWebhookEvent {\n if (!verifyWebhookSignature(secret, rawBody, signatureHeader, opts)) {\n throw new WebhookSignatureError('Invalid or expired webhook signature')\n }\n try {\n return JSON.parse(toRaw(rawBody)) as ConnectWebhookEvent\n } catch {\n throw new WebhookSignatureError('Webhook body is not valid JSON')\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Client\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface OpenMarketsClientOptions {\n /** Your Connect org API key. Sent as `X-API-Key`. */\n apiKey: string\n /** API base URL. Defaults to https://api.openmarkets.ai. */\n baseUrl?: string\n /** Your webhook signing secret (`whsec_…`), enabling `client.webhooks.*`. */\n webhookSecret?: string\n /** Custom fetch (defaults to global fetch; Node 18+). */\n fetch?: typeof fetch\n /** Per-request timeout in ms. Default 30000. */\n timeoutMs?: number\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */\n actAs?: string\n}\n\n// Inputs (snake_case to match the API — buy legs map 1:1 from liquidity entries).\nexport interface ProvisionUserParams {\n external_user_id: string\n email?: string\n name?: string\n}\nexport type LinkSessionMode = 'connect' | 'manage'\nexport interface CreateLinkSessionParams {\n external_user_id: string\n return_url?: string\n mode?: LinkSessionMode\n allowed_partners?: string[]\n /** Pick a specific org Connect config; omit to use the org's default (if any). */\n connect_config_id?: string\n}\nexport interface BuyOrder {\n /** What to buy — set exactly one of position_hash or liquidity_hash. */\n position_hash?: string\n liquidity_hash?: string\n /** Size — set exactly one of amount or shares. */\n amount?: number // stake, notional USD\n shares?: number // contract count (each pays $1 on win)\n /** Price ceiling, 0..1 exclusive — won't fill above this. */\n max_price: number\n /** Optional — pin a venue; omit to route to the best price. */\n partner_id?: string\n /** Optional — 'real' (default) or 'paper' (practice book). */\n mode?: 'real' | 'paper'\n}\n\n// Outputs (light — partners can pass a type param for stricter typing).\n/**\n * `POST /flow/v1/connect/users`. Idempotent — safe to call on every login.\n *\n * `om_account_id` is the field an integration actually needs (it addresses the\n * user in later calls) and was previously absent, so it typed as `unknown` via\n * the index signature.\n */\nexport interface ProvisionResult {\n /** Our id for this user. Pass as `actAs` when trading on their behalf. */\n om_account_id: string\n external_user_id: string\n /** false when the user already existed. */\n created: boolean\n [key: string]: unknown\n}\n/**\n * The response of `POST /flow/v1/connect/link-sessions`.\n *\n * These names are the API's, verified against the route rather than assumed:\n * it returns `link_token`, NOT `token`. The previous declaration named `token`,\n * `external_user_id` and `mode` — none of which the endpoint sends — so the one\n * field an integration actually needs type-checked as a string and arrived\n * `undefined`, opening the hosted flow with `token=undefined`. The index\n * signature below is what kept that quiet; keep these names in step with\n * `CreateLinkSessionResult` in LinkSessionOrchestrator.\n */\nexport interface LinkSession {\n link_session_id: string\n /** Single-use, expires in 15 minutes. Hand to `createConnect().open()`. */\n link_token: string\n /** The hosted flow URL, for redirect mode or a native in-app browser. */\n hosted_url: string\n expires_at: string\n [key: string]: unknown\n}\n/**\n * The status of one leg, mirroring `flowLegStatus` in the API.\n *\n * ALL FIVE values are reachable. This union previously listed only three, so a\n * `switch` written against the SDK's types compiled clean and silently fell\n * through for a resting or pending order — an order that IS live, sitting on a\n * venue book, treated as if it had never been placed. Any change here must\n * follow the API, not the other way round.\n */\nexport type BuyLegStatus =\n /** Filled or partially filled. */\n | 'completed'\n /** Live on the venue's book, unfilled. Not a failure — check back. */\n | 'resting'\n /** Accepted by the venue, fill not yet confirmed (async venues). */\n | 'pending'\n /** The venue or a pre-trade gate rejected it. */\n | 'failed'\n /** No viable venue was found; nothing was sent. */\n | 'rejected'\n\n/**\n * What an organization's END USERS see and may do in the hosted flow. Mirrors\n * `ConnectConfigBody` server-side.\n *\n * A `null` field means \"no restriction / use the default\" throughout, so an\n * organization with no config behaves exactly as Connect did before configs\n * existed. Read that as permissive, not as unset.\n */\nexport interface ConnectConfig {\n version: number\n /** Partner ids or names offered in the picker. null = every venue we support. */\n venue_allowlist: string[] | null\n /** Surface the OpenMarkets practice book as a credential-less venue. */\n offer_internal_book: boolean\n /**\n * Currencies users may trade. `['ATLAS']` is practice-only and is ENFORCED\n * on every order path, not merely hidden in the UI — users can still link\n * venues, read balances and sync history; only real-money orders are\n * refused.\n */\n allowed_currencies: string[]\n /** DERIVED from allowed_currencies server-side. Sending it has no effect. */\n allow_real_money: boolean\n /** Permissions the user is asked to grant. null = all of them. */\n available_scopes: ConnectScope[] | null\n branding: { display_name?: string; logo_url?: string; primary_color?: string } | null\n allowed_return_urls: string[] | null\n default_link_mode: LinkSessionMode\n [key: string]: unknown\n}\n\n/** Permissions an end user grants per connected venue. */\nexport type ConnectScope = 'history:read' | 'trade:execute' | 'balance:read'\n\nexport interface ConnectConfigResult {\n /** null when the organization has never saved one — `config` is the defaults. */\n connect_config_id: string | null\n config: ConnectConfig\n /**\n * Present on update: how many EXISTING users the change was applied to.\n * A funding-mode change reaches users already provisioned, not just future\n * ones, so this reports what actually happened.\n */\n reconcile?: { scanned: number; reconciled: number; failed: number } | null\n}\n\nexport interface BuyResult {\n results: Array<{\n index: number\n status: BuyLegStatus\n /** NULL when the leg was rejected before routing — no decision was made. */\n sor_decision_id: string | null\n filled_notional: number\n filled_shares: number\n /** The un-buyable remainder of the requested stake. */\n unfilled_notional: number\n avg_price: number | null\n rejected_reason: string | null\n venues: Array<{\n partner_id: string\n success: boolean\n router_order_id: string | null\n error: string | null\n }>\n }>\n}\n\ninterface FlowEnvelope<T> {\n data?: T\n error?: { code: string; message: string; details?: Record<string, unknown> }\n}\n\nexport interface OpenMarketsClient {\n /** Generic typed request — escape hatch for endpoints without a helper. */\n request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>\n connect: {\n users: {\n provision(params: ProvisionUserParams): Promise<ProvisionResult>\n get<T = unknown>(externalUserId: string): Promise<T>\n getPolicy<T = unknown>(externalUserId: string): Promise<T>\n }\n linkSessions: {\n create(params: CreateLinkSessionParams): Promise<LinkSession>\n get<T = unknown>(linkSessionId: string): Promise<T>\n }\n /**\n * The organization's Connect config — which venues appear, whether real\n * money is allowed, and how the hosted flow is branded.\n *\n * Requires a PLAYER JWT with workspace admin, not an API key: this is\n * account governance rather than a data-API capability. `update` sends a\n * whole body (it is normalized server-side), so read, change, write.\n */\n configs: {\n get(workspaceId: string): Promise<ConnectConfigResult>\n update(workspaceId: string, config: Partial<ConnectConfig>): Promise<ConnectConfigResult>\n }\n webhooks: {\n getConfig<T = unknown>(): Promise<T>\n /** Verify a delivery using the configured `webhookSecret`. */\n verify(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): boolean\n /** Verify + parse, or throw. Uses the configured `webhookSecret`. */\n constructEvent(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): ConnectWebhookEvent\n }\n }\n account: {\n partners<T = unknown>(externalUserId: string): Promise<T>\n balances<T = unknown>(externalUserId: string): Promise<T>\n }\n orders: {\n list<T = unknown>(externalUserId: string): Promise<T>\n buy(orders: BuyOrder[], opts: { actAs: string }): Promise<BuyResult>\n }\n data: {\n leagues<T = unknown>(): Promise<T>\n contestLiquidity<T = unknown>(contestId: string): Promise<T>\n }\n}\n\nexport function createClient(options: OpenMarketsClientOptions): OpenMarketsClient {\n if (!options.apiKey) throw new Error('createClient: apiKey is required')\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const doFetch = options.fetch ?? globalThis.fetch\n if (!doFetch) throw new Error('No fetch available — pass options.fetch (Node < 18)')\n const timeoutMs = options.timeoutMs ?? 30_000\n\n async function request<T = unknown>(\n method: HttpMethod,\n path: string,\n opts: RequestOptions = {},\n ): Promise<T> {\n const url = new URL(baseUrl + path)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v))\n }\n const headers: Record<string, string> = {\n 'X-API-Key': options.apiKey,\n Accept: 'application/json',\n }\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json'\n if (opts.actAs) headers['X-OpenMarkets-Account'] = opts.actAs\n\n const ctrl = new AbortController()\n const timer = setTimeout(() => ctrl.abort(), timeoutMs)\n let res: Response\n try {\n res = await doFetch(url.toString(), {\n method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n\n let envelope: FlowEnvelope<T> | undefined\n const text = await res.text()\n if (text) {\n try {\n envelope = JSON.parse(text) as FlowEnvelope<T>\n } catch {\n /* non-JSON body */\n }\n }\n\n if (!res.ok) {\n const err = envelope?.error\n throw new OpenMarketsError(\n res.status,\n err?.code ?? 'http_error',\n err?.message ?? `Request failed with status ${res.status}`,\n err?.details,\n )\n }\n return (envelope?.data ?? (undefined as unknown)) as T\n }\n\n function requireSecret(): string {\n if (!options.webhookSecret) {\n throw new Error('webhookSecret was not provided to createClient()')\n }\n return options.webhookSecret\n }\n\n return {\n request,\n connect: {\n users: {\n provision: (params) =>\n request<ProvisionResult>('POST', '/flow/v1/connect/users', { body: params }),\n get: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}`),\n getPolicy: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}/policy`),\n },\n linkSessions: {\n create: (params) =>\n request<LinkSession>('POST', '/flow/v1/connect/link-sessions', { body: params }),\n get: (linkSessionId) =>\n request('GET', `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`),\n },\n configs: {\n get: (workspaceId: string) =>\n request<ConnectConfigResult>(\n 'GET', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n ),\n update: (workspaceId: string, config: Partial<ConnectConfig>) =>\n request<ConnectConfigResult>(\n 'PUT', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n { body: { config } },\n ),\n },\n webhooks: {\n getConfig: () => request('GET', '/flow/v1/connect/webhook-config'),\n verify: (rawBody, sig, opts) =>\n verifyWebhookSignature(requireSecret(), rawBody, sig, opts),\n constructEvent: (rawBody, sig, opts) =>\n constructWebhookEvent(requireSecret(), rawBody, sig, opts),\n },\n },\n account: {\n partners: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/partners', { actAs: externalUserId }),\n balances: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/balances', { actAs: externalUserId }),\n },\n orders: {\n list: (externalUserId) =>\n request('GET', '/flow/v1/auth/orders', { actAs: externalUserId }),\n buy: (orders, opts) =>\n request<BuyResult>('POST', '/flow/v1/auth/orders/buy', {\n body: { orders },\n actAs: opts.actAs,\n }),\n },\n data: {\n leagues: () => request('GET', '/flow/v1/leagues'),\n contestLiquidity: (contestId) =>\n request('GET', `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`),\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;AAmBO,IAAM,gBAAA,GAAmB;AAOzB,IAAM,gBAAA,GAAN,cAA+B,KA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AmB,QAAQ,0BAAA,EAA4B;AAAA,QACnD,IAAA,EAAM,EAAE,MAAA,EAAO;AAAA,QACf,OAAO,IAAA,CAAK;AAAA,OACf;AAAA,KACT;AAAA,IACA,IAAA,EAAM;AAAA,MACF,OAAA,EAAS,MAAM,OAAA,CAAQ,KAAA,EAAO,kBAAkB,CAAA;AAAA,MAChD,gBAAA,EAAkB,CAAC,SAAA,KACf,OAAA,CAAQ,OAAO,CAAA,kBAAA,EAAqB,kBAAA,CAAmB,SAAS,CAAC,CAAA,UAAA,CAAY;AAAA,KACrF;AAAA,IACA,EAAA,EAAI;AAAA,MACA,MAAA;AAAA,MACA,UAAA,EAAY;AAAA,QACR,MAAA,EAAQ,CAAC,MAAA,EAAQ,IAAA,GAAO,EAAC,KACrB,OAAA,CAAQ,QAAQ,wBAAA,EAA0B;AAAA,UACtC,IAAA,EAAM,MAAA;AAAA,UACN,OAAO,IAAA,CAAK,KAAA;AAAA,UACZ,gBAAgB,IAAA,CAAK;AAAA,SACxB,CAAA;AAAA,QACL,KAAK,CAAC,WAAA,EAAa,IAAA,GAAO,OACtB,OAAA,CAAQ,KAAA,EAAO,CAAA,uBAAA,EAA0B,kBAAA,CAAmB,WAAW,CAAC,CAAA,CAAA,EAAI,EAAE,KAAA,EAAO,IAAA,CAAK,OAAO;AAAA,OACzG;AAAA,MACA,SAAA,EAAW,CAAC,IAAA,GAAO,EAAC,KAAM,OAAA,CAAQ,KAAA,EAAO,uBAAA,EAAyB,EAAE,KAAA,EAAO,IAAA,CAAK,KAAA,EAAO;AAAA;AAC3F,GACJ;AACJ","file":"index.js","sourcesContent":["/**\n * @openmarketsai/connect-node\n *\n * Server SDK for OpenMarkets Connect. A thin, typed wrapper over the Flow API:\n * provision your users, mint hosted link sessions, verify webhook deliveries,\n * read on a user's behalf, and execute orders on their account.\n *\n * import { createClient } from '@openmarketsai/connect-node'\n * const om = createClient({ apiKey: process.env.OM_API_KEY! })\n *\n * await om.connect.users.provision({ external_user_id: 'user-123' })\n * const { token } = await om.connect.linkSessions.create({ external_user_id: 'user-123' })\n * await om.orders.buy([leg], { actAs: 'user-123' })\n * const r = await om.ai.invoke({ provider: 'anthropic', model: 'claude-opus-5', messages }, { actAs: 'user-123' })\n *\n * Pairs with @openmarketsai/connect-web (the in-app launcher).\n */\nimport crypto from 'node:crypto'\n\nexport const DEFAULT_BASE_URL = 'https://api.openmarkets.ai'\n\n// ──────────────────────────────────────────────────────────────────────────\n// Errors\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Thrown when the API returns a non-2xx response. Mirrors the Flow error envelope. */\nexport class OpenMarketsError extends Error {\n readonly status: number\n readonly code: string\n readonly details?: Record<string, unknown>\n constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {\n super(message)\n this.name = 'OpenMarketsError'\n this.status = status\n this.code = code\n this.details = details\n }\n}\n\n/** Thrown by `constructWebhookEvent` when a signature is missing, stale, or invalid. */\nexport class WebhookSignatureError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WebhookSignatureError'\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Webhook verification (matches src/utils/webhook-signature.ts byte-for-byte)\n//\n// Header: X-OpenMarkets-Signature: t=<unix_seconds>,v1=<hex hmac>\n// Signed string: `${t}.${rawBody}`, HMAC-SHA256 with your whsec_ secret.\n// IMPORTANT: verify over the EXACT raw request body, not a re-serialized object.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type ConnectWebhookEventType =\n | 'user.partners_connected'\n | 'user.permissions_changed'\n | 'user.history_synced'\n | (string & {})\n\nexport interface ConnectWebhookEvent {\n type: ConnectWebhookEventType\n [key: string]: unknown\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature timestamp, in seconds. Default 300 (5 min). 0 disables. */\n toleranceSec?: number\n /** Injectable clock for testing. */\n nowSec?: number\n}\n\nfunction toRaw(body: string | Buffer): string {\n return typeof body === 'string' ? body : body.toString('utf8')\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n const parts = header.split(',').reduce<Record<string, string>>((acc, kv) => {\n const idx = kv.indexOf('=')\n if (idx > 0) acc[kv.slice(0, idx).trim()] = kv.slice(idx + 1).trim()\n return acc\n }, {})\n const t = Number(parts.t)\n if (!parts.v1 || !isFinite(t)) return null\n return { t, v1: parts.v1 }\n}\n\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'hex')\n const bb = Buffer.from(b, 'hex')\n if (ab.length === 0 || ab.length !== bb.length) return false\n return crypto.timingSafeEqual(ab, bb)\n}\n\n/** Verify a webhook signature. Returns false on any failure (never throws). */\nexport function verifyWebhookSignature(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): boolean {\n if (!secret || !signatureHeader) return false\n const parsed = parseSignatureHeader(signatureHeader)\n if (!parsed) return false\n const toleranceSec = opts.toleranceSec ?? 300\n const nowSec = opts.nowSec ?? Math.floor(Date.now() / 1000)\n if (toleranceSec > 0 && Math.abs(nowSec - parsed.t) > toleranceSec) return false\n const expected = crypto\n .createHmac('sha256', secret)\n .update(`${parsed.t}.${toRaw(rawBody)}`)\n .digest('hex')\n return timingSafeEqualHex(expected, parsed.v1)\n}\n\n/** Verify the signature and return the parsed event, or throw `WebhookSignatureError`. */\nexport function constructWebhookEvent(\n secret: string,\n rawBody: string | Buffer,\n signatureHeader: string | null | undefined,\n opts: VerifyWebhookOptions = {},\n): ConnectWebhookEvent {\n if (!verifyWebhookSignature(secret, rawBody, signatureHeader, opts)) {\n throw new WebhookSignatureError('Invalid or expired webhook signature')\n }\n try {\n return JSON.parse(toRaw(rawBody)) as ConnectWebhookEvent\n } catch {\n throw new WebhookSignatureError('Webhook body is not valid JSON')\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Client\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface OpenMarketsClientOptions {\n /** Your Connect org API key. Sent as `X-API-Key`. */\n apiKey: string\n /** API base URL. Defaults to https://api.openmarkets.ai. */\n baseUrl?: string\n /** Your webhook signing secret (`whsec_…`), enabling `client.webhooks.*`. */\n webhookSecret?: string\n /** Custom fetch (defaults to global fetch; Node 18+). */\n fetch?: typeof fetch\n /** Per-request timeout in ms. Default 30000. */\n timeoutMs?: number\n}\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'\n\nexport interface RequestOptions {\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /** Act on this user's behalf — sets the `X-OpenMarkets-Account` header. */\n actAs?: string\n /** Sent as `Idempotency-Key`: a retried POST replays instead of repeating. */\n idempotencyKey?: string\n}\n\n// Inputs (snake_case to match the API — buy legs map 1:1 from liquidity entries).\nexport interface ProvisionUserParams {\n external_user_id: string\n email?: string\n name?: string\n}\nexport type LinkSessionMode = 'connect' | 'manage'\nexport interface CreateLinkSessionParams {\n external_user_id: string\n return_url?: string\n mode?: LinkSessionMode\n allowed_partners?: string[]\n /** Pick a specific org Connect config; omit to use the org's default (if any). */\n connect_config_id?: string\n}\nexport interface BuyOrder {\n /** What to buy — set exactly one of position_hash or liquidity_hash. */\n position_hash?: string\n liquidity_hash?: string\n /** Size — set exactly one of amount or shares. */\n amount?: number // stake, notional USD\n shares?: number // contract count (each pays $1 on win)\n /** Price ceiling, 0..1 exclusive — won't fill above this. */\n max_price: number\n /** Optional — pin a venue; omit to route to the best price. */\n partner_id?: string\n /** Optional — 'real' (default) or 'paper' (practice book). */\n mode?: 'real' | 'paper'\n}\n\n// Outputs (light — partners can pass a type param for stricter typing).\n/**\n * `POST /flow/v1/connect/users`. Idempotent — safe to call on every login.\n *\n * `om_account_id` is the field an integration actually needs (it addresses the\n * user in later calls) and was previously absent, so it typed as `unknown` via\n * the index signature.\n */\nexport interface ProvisionResult {\n /** Our id for this user. Pass as `actAs` when trading on their behalf. */\n om_account_id: string\n external_user_id: string\n /** false when the user already existed. */\n created: boolean\n [key: string]: unknown\n}\n/**\n * The response of `POST /flow/v1/connect/link-sessions`.\n *\n * These names are the API's, verified against the route rather than assumed:\n * it returns `link_token`, NOT `token`. The previous declaration named `token`,\n * `external_user_id` and `mode` — none of which the endpoint sends — so the one\n * field an integration actually needs type-checked as a string and arrived\n * `undefined`, opening the hosted flow with `token=undefined`. The index\n * signature below is what kept that quiet; keep these names in step with\n * `CreateLinkSessionResult` in LinkSessionOrchestrator.\n */\nexport interface LinkSession {\n link_session_id: string\n /** Single-use, expires in 15 minutes. Hand to `createConnect().open()`. */\n link_token: string\n /** The hosted flow URL, for redirect mode or a native in-app browser. */\n hosted_url: string\n expires_at: string\n [key: string]: unknown\n}\n/**\n * The status of one leg, mirroring `flowLegStatus` in the API.\n *\n * ALL FIVE values are reachable. This union previously listed only three, so a\n * `switch` written against the SDK's types compiled clean and silently fell\n * through for a resting or pending order — an order that IS live, sitting on a\n * venue book, treated as if it had never been placed. Any change here must\n * follow the API, not the other way round.\n */\nexport type BuyLegStatus =\n /** Filled or partially filled. */\n | 'completed'\n /** Live on the venue's book, unfilled. Not a failure — check back. */\n | 'resting'\n /** Accepted by the venue, fill not yet confirmed (async venues). */\n | 'pending'\n /** The venue or a pre-trade gate rejected it. */\n | 'failed'\n /** No viable venue was found; nothing was sent. */\n | 'rejected'\n\n/**\n * What an organization's END USERS see and may do in the hosted flow. Mirrors\n * `ConnectConfigBody` server-side.\n *\n * A `null` field means \"no restriction / use the default\" throughout, so an\n * organization with no config behaves exactly as Connect did before configs\n * existed. Read that as permissive, not as unset.\n */\nexport interface ConnectConfig {\n version: number\n /** Partner ids or names offered in the picker. null = every venue we support. */\n venue_allowlist: string[] | null\n /** Surface the OpenMarkets practice book as a credential-less venue. */\n offer_internal_book: boolean\n /**\n * Currencies users may trade. `['ATLAS']` is practice-only and is ENFORCED\n * on every order path, not merely hidden in the UI — users can still link\n * venues, read balances and sync history; only real-money orders are\n * refused.\n */\n allowed_currencies: string[]\n /** DERIVED from allowed_currencies server-side. Sending it has no effect. */\n allow_real_money: boolean\n /** Permissions the user is asked to grant. null = all of them. */\n available_scopes: ConnectScope[] | null\n branding: { display_name?: string; logo_url?: string; primary_color?: string } | null\n allowed_return_urls: string[] | null\n default_link_mode: LinkSessionMode\n /**\n * AI providers whose keys your users may link (AI Connect). OPT-IN: empty\n * means the hosted flow offers none — unlike venue_allowlist, where null\n * means everything.\n */\n ai_providers?: AiProvider[]\n [key: string]: unknown\n}\n\n/** Permissions an end user grants per connected venue. */\nexport type ConnectScope = 'history:read' | 'trade:execute' | 'balance:read'\n\nexport interface ConnectConfigResult {\n /** null when the organization has never saved one — `config` is the defaults. */\n connect_config_id: string | null\n config: ConnectConfig\n /**\n * Present on update: how many EXISTING users the change was applied to.\n * A funding-mode change reaches users already provisioned, not just future\n * ones, so this reports what actually happened.\n */\n reconcile?: { scanned: number; reconciled: number; failed: number } | null\n}\n\nexport interface BuyResult {\n results: Array<{\n index: number\n status: BuyLegStatus\n /** NULL when the leg was rejected before routing — no decision was made. */\n sor_decision_id: string | null\n filled_notional: number\n filled_shares: number\n /** The un-buyable remainder of the requested stake. */\n unfilled_notional: number\n avg_price: number | null\n rejected_reason: string | null\n venues: Array<{\n partner_id: string\n success: boolean\n router_order_id: string | null\n error: string | null\n }>\n }>\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// AI Connect — run models on a user's OWN linked key (never charged by\n// OpenMarkets) or on OpenMarkets' key (charged in reasoning credits).\n// ──────────────────────────────────────────────────────────────────────────\n\nexport type AiProvider = 'anthropic' | 'openai'\n/** 'auto' (default): the user's own key when linked and shared, else managed. */\nexport type AiBilling = 'auto' | 'byok' | 'managed'\nexport type AiStopReason = 'end' | 'max_tokens' | 'stop_sequence' | 'refusal' | 'tool_use' | 'paused' | 'context_exceeded'\n\nexport interface AiInferenceParams {\n provider: AiProvider\n /** The provider's own model id, passed through verbatim (e.g. 'claude-opus-5'). */\n model: string\n system?: string\n messages: Array<{ role: 'user' | 'assistant'; content: string }>\n /** 1..21000. Default 8192. */\n max_tokens?: number\n /** Only sent when set — several current models reject any explicit value. */\n temperature?: number\n /** Constrain the answer to a JSON schema; the parsed object arrives as `output`. */\n output_schema?: { name?: string; schema: Record<string, unknown>; strict?: boolean }\n billing?: AiBilling\n /** Seconds the server holds the request before answering 202 (0..25). */\n wait_seconds?: number\n /** Your own bookkeeping labels, returned on the result. */\n metadata?: Record<string, string>\n}\n\nexport interface AiInference<TOutput = unknown> {\n inference_id: string\n status: 'running' | 'succeeded' | 'failed'\n provider: AiProvider\n model: string\n /** The model the provider says actually served the call. */\n served_model: string | null\n /** 'byok' calls are never charged by OpenMarkets. */\n billing: 'byok' | 'managed'\n output_text: string | null\n /** Parsed JSON when `output_schema` was sent and the answer parsed; else null. */\n output: TOutput | null\n /** Check this before trusting `output` — a refusal is not an answer. */\n stop_reason: AiStopReason | null\n usage: { input_tokens: number; output_tokens: number; credits_charged: number }\n error: { code: string; message: string } | null\n metadata: Record<string, string> | null\n latency_ms: number | null\n created_at: string\n completed_at: string | null\n}\n\nexport interface AiProviderConnection {\n provider: AiProvider\n label: string\n key_hint: string\n credential_status: 'pending' | 'connected' | 'failed'\n /** Whether the user shares the key with your app. */\n invoke_granted: boolean\n monthly_token_cap: number | null\n last_used_at: string | null\n connected_at: string\n}\n\nexport interface AiInvokeOptions {\n /** Run on this Connect user's account (their linked key). */\n actAs?: string\n /** Give up polling after this many ms (the call keeps running server-side). Default 600000. */\n timeoutMs?: number\n /** Delay between polls once the server has answered 202. Default 2000. */\n pollIntervalMs?: number\n}\n\n/** Thrown by `ai.invoke` when the inference finished in `failed`. */\nexport class AiInferenceFailedError extends Error {\n readonly inference: AiInference\n constructor(inference: AiInference) {\n super(inference.error?.message ?? 'The inference failed')\n this.name = 'AiInferenceFailedError'\n this.inference = inference\n }\n}\n\ninterface FlowEnvelope<T> {\n data?: T\n pagination?: { next_cursor?: string | null; has_more?: boolean }\n error?: { code: string; message: string; details?: Record<string, unknown> }\n}\n\n/** One page of a list endpoint, with the cursor `request()` drops. */\nexport interface Page<T> {\n data: T[]\n /** Pass back as `query.cursor` for the next page; null on the last page. */\n next_cursor: string | null\n has_more: boolean\n}\n\nexport interface OpenMarketsClient {\n /** Generic typed request — escape hatch for endpoints without a helper. */\n request<T = unknown>(method: HttpMethod, path: string, opts?: RequestOptions): Promise<T>\n /**\n * GET one page of a list endpoint. `request()` returns only `data`, so a list's\n * `pagination.next_cursor` was unreachable through the SDK — found by the model\n * arena, which could not page through `/contests` or `/auth/orders`.\n */\n requestPage<T = unknown>(path: string, opts?: Omit<RequestOptions, 'body'>): Promise<Page<T>>\n /** Every item of a list endpoint, following cursors (stops after `maxPages`, default 50). */\n requestAll<T = unknown>(path: string, opts?: Omit<RequestOptions, 'body'> & { maxPages?: number }): Promise<T[]>\n connect: {\n users: {\n provision(params: ProvisionUserParams): Promise<ProvisionResult>\n get<T = unknown>(externalUserId: string): Promise<T>\n getPolicy<T = unknown>(externalUserId: string): Promise<T>\n }\n linkSessions: {\n create(params: CreateLinkSessionParams): Promise<LinkSession>\n get<T = unknown>(linkSessionId: string): Promise<T>\n }\n /**\n * The organization's Connect config — which venues appear, whether real\n * money is allowed, and how the hosted flow is branded.\n *\n * Requires a PLAYER JWT with workspace admin, not an API key: this is\n * account governance rather than a data-API capability. `update` sends a\n * whole body (it is normalized server-side), so read, change, write.\n */\n configs: {\n get(workspaceId: string): Promise<ConnectConfigResult>\n update(workspaceId: string, config: Partial<ConnectConfig>): Promise<ConnectConfigResult>\n }\n webhooks: {\n getConfig<T = unknown>(): Promise<T>\n /** Verify a delivery using the configured `webhookSecret`. */\n verify(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): boolean\n /** Verify + parse, or throw. Uses the configured `webhookSecret`. */\n constructEvent(rawBody: string | Buffer, signatureHeader: string | null | undefined, opts?: VerifyWebhookOptions): ConnectWebhookEvent\n }\n }\n account: {\n partners<T = unknown>(externalUserId: string): Promise<T>\n balances<T = unknown>(externalUserId: string): Promise<T>\n }\n orders: {\n list<T = unknown>(externalUserId: string): Promise<T>\n buy(orders: BuyOrder[], opts: { actAs: string }): Promise<BuyResult>\n }\n data: {\n leagues<T = unknown>(): Promise<T>\n contestLiquidity<T = unknown>(contestId: string): Promise<T>\n }\n ai: {\n /**\n * Run a model and wait for the result — polls through a 202 for you.\n * Throws `AiInferenceFailedError` when the call fails, `OpenMarketsError`\n * when it is refused up front (e.g. 409 ai_provider_not_linked).\n */\n invoke<TOutput = unknown>(params: AiInferenceParams, opts?: AiInvokeOptions): Promise<AiInference<TOutput>>\n inferences: {\n /** One request; may return `status: 'running'` (poll with `get`). */\n create<TOutput = unknown>(params: AiInferenceParams, opts?: { actAs?: string; idempotencyKey?: string }): Promise<AiInference<TOutput>>\n get<TOutput = unknown>(inferenceId: string, opts?: { actAs?: string }): Promise<AiInference<TOutput>>\n }\n /** Which AI providers the user has linked (never the key itself). */\n providers(opts?: { actAs?: string }): Promise<{ providers: AiProviderConnection[] }>\n }\n}\n\nexport function createClient(options: OpenMarketsClientOptions): OpenMarketsClient {\n if (!options.apiKey) throw new Error('createClient: apiKey is required')\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n const doFetch = options.fetch ?? globalThis.fetch\n if (!doFetch) throw new Error('No fetch available — pass options.fetch (Node < 18)')\n const timeoutMs = options.timeoutMs ?? 30_000\n\n async function send<T>(method: HttpMethod, path: string, opts: RequestOptions = {}): Promise<FlowEnvelope<T>> {\n const url = new URL(baseUrl + path)\n for (const [k, v] of Object.entries(opts.query ?? {})) {\n if (v !== undefined) url.searchParams.set(k, String(v))\n }\n const headers: Record<string, string> = {\n 'X-API-Key': options.apiKey,\n Accept: 'application/json',\n }\n if (opts.body !== undefined) headers['Content-Type'] = 'application/json'\n if (opts.actAs) headers['X-OpenMarkets-Account'] = opts.actAs\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n\n const ctrl = new AbortController()\n const timer = setTimeout(() => ctrl.abort(), timeoutMs)\n let res: Response\n try {\n res = await doFetch(url.toString(), {\n method,\n headers,\n body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,\n signal: ctrl.signal,\n })\n } finally {\n clearTimeout(timer)\n }\n\n let envelope: FlowEnvelope<T> | undefined\n const text = await res.text()\n if (text) {\n try {\n envelope = JSON.parse(text) as FlowEnvelope<T>\n } catch {\n /* non-JSON body */\n }\n }\n\n if (!res.ok) {\n const err = envelope?.error\n throw new OpenMarketsError(\n res.status,\n err?.code ?? 'http_error',\n err?.message ?? `Request failed with status ${res.status}`,\n err?.details,\n )\n }\n return envelope ?? {}\n }\n\n async function request<T = unknown>(method: HttpMethod, path: string, opts: RequestOptions = {}): Promise<T> {\n return ((await send<T>(method, path, opts)).data ?? (undefined as unknown)) as T\n }\n\n async function requestPage<T = unknown>(path: string, opts: Omit<RequestOptions, 'body'> = {}): Promise<Page<T>> {\n const env = await send<T[]>('GET', path, opts)\n return {\n data: env.data ?? [],\n next_cursor: env.pagination?.next_cursor ?? null,\n has_more: env.pagination?.has_more ?? !!env.pagination?.next_cursor,\n }\n }\n\n async function requestAll<T = unknown>(\n path: string,\n opts: Omit<RequestOptions, 'body'> & { maxPages?: number } = {},\n ): Promise<T[]> {\n const { maxPages = 50, ...rest } = opts\n const out: T[] = []\n let cursor: string | undefined\n for (let page = 0; page < maxPages; page++) {\n const p = await requestPage<T>(path, { ...rest, query: { ...(rest.query ?? {}), cursor } })\n out.push(...p.data)\n if (!p.next_cursor) break\n cursor = p.next_cursor\n }\n return out\n }\n\n async function invoke<TOutput>(params: AiInferenceParams, opts: AiInvokeOptions = {}): Promise<AiInference<TOutput>> {\n const deadline = Date.now() + (opts.timeoutMs ?? 600_000)\n const pollMs = opts.pollIntervalMs ?? 2_000\n // One key per logical call: if the POST is retried after a network drop,\n // the server replays it instead of running (and charging for) it twice.\n let inf = await request<AiInference<TOutput>>('POST', '/flow/v1/ai/inferences', {\n body: params,\n actAs: opts.actAs,\n idempotencyKey: crypto.randomUUID(),\n })\n while (inf.status === 'running') {\n if (Date.now() > deadline) {\n throw new OpenMarketsError(408, 'poll_timeout',\n `Inference ${inf.inference_id} is still running; poll ai.inferences.get() to collect it`)\n }\n await new Promise((r) => setTimeout(r, pollMs))\n inf = await request<AiInference<TOutput>>(\n 'GET', `/flow/v1/ai/inferences/${encodeURIComponent(inf.inference_id)}`, { actAs: opts.actAs },\n )\n }\n if (inf.status === 'failed') throw new AiInferenceFailedError(inf as AiInference)\n return inf\n }\n\n function requireSecret(): string {\n if (!options.webhookSecret) {\n throw new Error('webhookSecret was not provided to createClient()')\n }\n return options.webhookSecret\n }\n\n return {\n request,\n requestPage,\n requestAll,\n connect: {\n users: {\n provision: (params) =>\n request<ProvisionResult>('POST', '/flow/v1/connect/users', { body: params }),\n get: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}`),\n getPolicy: (externalUserId) =>\n request('GET', `/flow/v1/connect/users/${encodeURIComponent(externalUserId)}/policy`),\n },\n linkSessions: {\n create: (params) =>\n request<LinkSession>('POST', '/flow/v1/connect/link-sessions', { body: params }),\n get: (linkSessionId) =>\n request('GET', `/flow/v1/connect/link-sessions/${encodeURIComponent(linkSessionId)}`),\n },\n configs: {\n get: (workspaceId: string) =>\n request<ConnectConfigResult>(\n 'GET', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n ),\n update: (workspaceId: string, config: Partial<ConnectConfig>) =>\n request<ConnectConfigResult>(\n 'PUT', `/flow/v1/workspaces/${encodeURIComponent(workspaceId)}/connect-config`,\n { body: { config } },\n ),\n },\n webhooks: {\n getConfig: () => request('GET', '/flow/v1/connect/webhook-config'),\n verify: (rawBody, sig, opts) =>\n verifyWebhookSignature(requireSecret(), rawBody, sig, opts),\n constructEvent: (rawBody, sig, opts) =>\n constructWebhookEvent(requireSecret(), rawBody, sig, opts),\n },\n },\n account: {\n partners: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/partners', { actAs: externalUserId }),\n balances: (externalUserId) =>\n request('GET', '/flow/v1/auth/account/balances', { actAs: externalUserId }),\n },\n orders: {\n list: (externalUserId) =>\n request('GET', '/flow/v1/auth/orders', { actAs: externalUserId }),\n buy: (orders, opts) =>\n request<BuyResult>('POST', '/flow/v1/auth/orders/buy', {\n body: { orders },\n actAs: opts.actAs,\n }),\n },\n data: {\n leagues: () => request('GET', '/flow/v1/leagues'),\n contestLiquidity: (contestId) =>\n request('GET', `/flow/v1/contests/${encodeURIComponent(contestId)}/liquidity`),\n },\n ai: {\n invoke,\n inferences: {\n create: (params, opts = {}) =>\n request('POST', '/flow/v1/ai/inferences', {\n body: params,\n actAs: opts.actAs,\n idempotencyKey: opts.idempotencyKey,\n }),\n get: (inferenceId, opts = {}) =>\n request('GET', `/flow/v1/ai/inferences/${encodeURIComponent(inferenceId)}`, { actAs: opts.actAs }),\n },\n providers: (opts = {}) => request('GET', '/flow/v1/ai/providers', { actAs: opts.actAs }),\n },\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openmarketsai/connect-node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Server SDK for OpenMarkets Connect
|
|
5
|
-
"license": "
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Server SDK for OpenMarkets Connect \u2014 provision users, mint link sessions, verify webhooks, and execute on a user's behalf.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"sideEffects": false,
|
|
8
|
-
"files": [
|
|
8
|
+
"files": [
|
|
9
|
+
"dist",
|
|
10
|
+
"README.md",
|
|
11
|
+
"LICENSE",
|
|
12
|
+
"NOTICE"
|
|
13
|
+
],
|
|
9
14
|
"main": "./dist/index.cjs",
|
|
10
15
|
"module": "./dist/index.js",
|
|
11
16
|
"types": "./dist/index.d.ts",
|
|
@@ -22,7 +27,13 @@
|
|
|
22
27
|
"dev": "tsup --watch",
|
|
23
28
|
"type-check": "tsc --noEmit"
|
|
24
29
|
},
|
|
25
|
-
"keywords": [
|
|
30
|
+
"keywords": [
|
|
31
|
+
"openmarkets",
|
|
32
|
+
"connect",
|
|
33
|
+
"prediction-markets",
|
|
34
|
+
"sdk",
|
|
35
|
+
"server"
|
|
36
|
+
],
|
|
26
37
|
"engines": {
|
|
27
38
|
"node": ">=18"
|
|
28
39
|
},
|
|
@@ -33,5 +44,11 @@
|
|
|
33
44
|
},
|
|
34
45
|
"publishConfig": {
|
|
35
46
|
"access": "public"
|
|
36
|
-
}
|
|
47
|
+
},
|
|
48
|
+
"homepage": "https://app.openmarkets.ai/developers",
|
|
49
|
+
"bugs": {
|
|
50
|
+
"url": "https://app.openmarkets.ai/developers",
|
|
51
|
+
"email": "james@openmarkets.ai"
|
|
52
|
+
},
|
|
53
|
+
"author": "OpenMarkets"
|
|
37
54
|
}
|