@agentpost-tools/resourceshark-sdk 0.0.0-stage → 0.2.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.
@@ -0,0 +1,289 @@
1
+ // src/routes.ts
2
+ const ROUTES = {
3
+ "config.get": ["GET", "/config"],
4
+ "config.put": ["PUT", "/config"],
5
+ "resources.create": ["POST", "/resources"],
6
+ "resources.list": ["GET", "/resources"],
7
+ "resources.get": ["GET", "/resources/:id"],
8
+ "resources.patch": ["PATCH", "/resources/:id"],
9
+ "resources.archive": ["POST", "/resources/:id/archive"],
10
+ "places.create": ["POST", "/places"],
11
+ "places.list": ["GET", "/places"],
12
+ "places.patch": ["PATCH", "/places/:id"],
13
+ "instances.create": ["POST", "/resources/:id/instances"],
14
+ "instances.list": ["GET", "/resources/:id/instances"],
15
+ "instances.patch": ["PATCH", "/resources/:id/instances/:iid"],
16
+ "freeInstances.list": ["GET", "/resources/:id/free-instances"],
17
+ "supply.create": ["POST", "/supply"],
18
+ "supply.list": ["GET", "/supply"],
19
+ "supply.get": ["GET", "/supply/:id"],
20
+ "supply.reverse": ["POST", "/supply/:id/reverse"],
21
+ "batches.create": ["POST", "/batches"],
22
+ "batches.list": ["GET", "/batches"],
23
+ "batches.get": ["GET", "/batches/:id"],
24
+ "batches.patch": ["PATCH", "/batches/:id"],
25
+ "claims.consume": ["POST", "/consume"],
26
+ "claims.settle": ["POST", "/settle"],
27
+ "claims.list": ["GET", "/claims"],
28
+ "claims.get": ["GET", "/claims/:id"],
29
+ "holds.create": ["POST", "/holds"],
30
+ "holds.list": ["GET", "/holds"],
31
+ "holds.get": ["GET", "/holds/:id"],
32
+ "holds.extend": ["POST", "/holds/:id/extend"],
33
+ "holds.commit": ["POST", "/holds/:id/commit"],
34
+ "holds.release": ["POST", "/holds/:id/release"],
35
+ "holds.cancel": ["POST", "/holds/:id/cancel"],
36
+ "holds.reschedule": ["POST", "/reschedule"],
37
+ "availability.query": ["POST", "/availability"],
38
+ "balances.get": ["GET", "/resources/:id/balance"],
39
+ "holderBalances.list": ["GET", "/holders/:ref/balances"],
40
+ "holderBalances.get": ["GET", "/holders/:ref/balances/:resourceId"],
41
+ "schedules.put": ["PUT", "/resources/:id/schedule"],
42
+ "schedules.get": ["GET", "/resources/:id/schedule"],
43
+ "exceptions.create": ["POST", "/resources/:id/exceptions"],
44
+ "exceptions.list": ["GET", "/resources/:id/exceptions"],
45
+ "exceptions.patch": ["PATCH", "/resources/:id/exceptions/:eid"],
46
+ "exceptions.delete": ["DELETE", "/resources/:id/exceptions/:eid"],
47
+ "slots.list": ["GET", "/slots"],
48
+ "transfers.create": ["POST", "/transfers"],
49
+ "counts.create": ["POST", "/counts"],
50
+ "adjustments.create": ["POST", "/adjustments"],
51
+ "transformations.create": ["POST", "/transformations"],
52
+ "transformations.get": ["GET", "/transformations/:id"],
53
+ "movements.list": ["GET", "/movements"],
54
+ "movements.get": ["GET", "/movements/:id"],
55
+ "reports.totals": ["GET", "/reports/totals"],
56
+ "events.read": ["GET", "/events"]
57
+ };
58
+ // src/client.ts
59
+ const HOSTED_BASE_URL = "https://api.agentpost.tools/v1/resources";
60
+ const ResourcesharkApiError = class ResourcesharkApiError extends Error {
61
+ status;
62
+ code;
63
+ errorClass;
64
+ details;
65
+ docs;
66
+ constructor(status, code, message, details, docs, errorClass) {
67
+ super(message);
68
+ this.name = "ResourcesharkApiError";
69
+ this.status = status;
70
+ this.code = code;
71
+ this.errorClass = errorClass;
72
+ this.details = details;
73
+ this.docs = docs;
74
+ }
75
+ };
76
+ function readError(value) {
77
+ if (typeof value !== "object" || value === null || !("error" in value)) return void 0;
78
+ const { error } = value;
79
+ if (typeof error !== "object" || error === null || !("code" in error) || typeof error.code !== "string" || !("message" in error) || typeof error.message !== "string") return void 0;
80
+ return {
81
+ code: error.code,
82
+ message: error.message,
83
+ class: "class" in error ? error.class : void 0,
84
+ details: "details" in error ? error.details : void 0,
85
+ docs: "docs" in error && typeof error.docs === "string" ? error.docs : void 0
86
+ };
87
+ }
88
+ function isErrorClass(value) {
89
+ return value === "retry_later" || value === "exhausted" || value === "change_the_request";
90
+ }
91
+ /** True when a response has the service's standard error body. */
92
+ function isErrorBody(value) {
93
+ const error = readError(value);
94
+ return error !== void 0 && isErrorClass(error.class) && error.docs !== void 0;
95
+ }
96
+ function createClient(options = {}) {
97
+ const base = (options.baseUrl ?? "https://api.agentpost.tools/v1/resources").replace(/\/$/, "");
98
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
99
+ async function send(operationId, parts, opts) {
100
+ const [method, pattern] = ROUTES[operationId];
101
+ const path = pattern.replace(/:(\w+)/g, (_, name) => {
102
+ const value = parts.params?.[name];
103
+ if (value === void 0) throw new Error(`${operationId} needs the path parameter ${name}`);
104
+ return encodeURIComponent(value);
105
+ });
106
+ const search = new URLSearchParams();
107
+ for (const [key, value] of Object.entries(parts.query ?? {})) {
108
+ if (value === void 0 || value === null) continue;
109
+ if (key === "attributes") for (const [name, attribute] of Object.entries(value)) search.set(`attribute.${name}`, String(attribute));
110
+ else if (Array.isArray(value)) search.set(key, value.join(","));
111
+ else search.set(key, String(value));
112
+ }
113
+ const query = search.toString();
114
+ const url = `${base}${path}${query ? `?${query}` : ""}`;
115
+ const headers = new Headers(options.headers);
116
+ if (!headers.has("accept")) headers.set("accept", "application/json");
117
+ const token = opts?.token ?? options.token;
118
+ if (token) headers.set("authorization", `Bearer ${token}`);
119
+ if (opts?.idempotencyKey !== void 0) headers.set("idempotency-key", opts.idempotencyKey);
120
+ if (opts?.ifMatch !== void 0) headers.set("if-match", String(opts.ifMatch));
121
+ const { body } = parts;
122
+ if (body !== void 0) headers.set("content-type", "application/json");
123
+ const response = await doFetch(url, {
124
+ method,
125
+ headers,
126
+ body: body === void 0 ? void 0 : JSON.stringify(body)
127
+ });
128
+ const text = await response.text();
129
+ let parsed;
130
+ if (text) try {
131
+ parsed = JSON.parse(text);
132
+ } catch {
133
+ parsed = void 0;
134
+ }
135
+ if (response.ok) return parsed;
136
+ const error = readError(parsed);
137
+ if (error) throw new ResourcesharkApiError(response.status, error.code, error.message, error.details, error.docs, isErrorClass(error.class) ? error.class : void 0);
138
+ throw new ResourcesharkApiError(response.status, "unknown", `${method} ${path} failed with ${response.status}`);
139
+ }
140
+ return {
141
+ config: {
142
+ get: (opts) => send("config.get", {}, opts),
143
+ put: (body, opts) => send("config.put", { body }, opts)
144
+ },
145
+ resources: {
146
+ create: (body, opts) => send("resources.create", { body }, opts),
147
+ list: (query) => send("resources.list", { query }),
148
+ get: (id) => send("resources.get", { params: { id } }),
149
+ patch: (id, body, opts) => send("resources.patch", {
150
+ params: { id },
151
+ body
152
+ }, opts),
153
+ archive: (id, opts) => send("resources.archive", { params: { id } }, opts)
154
+ },
155
+ places: {
156
+ create: (body) => send("places.create", { body }),
157
+ list: (query) => send("places.list", { query }),
158
+ patch: (id, body) => send("places.patch", {
159
+ params: { id },
160
+ body
161
+ })
162
+ },
163
+ instances: {
164
+ create: (resourceId, body) => send("instances.create", {
165
+ params: { id: resourceId },
166
+ body
167
+ }),
168
+ list: (resourceId, query) => send("instances.list", {
169
+ params: { id: resourceId },
170
+ query
171
+ }),
172
+ patch: (resourceId, iid, body) => send("instances.patch", {
173
+ params: {
174
+ id: resourceId,
175
+ iid
176
+ },
177
+ body
178
+ })
179
+ },
180
+ freeInstances: { list: (resourceId, query) => send("freeInstances.list", {
181
+ params: { id: resourceId },
182
+ query
183
+ }) },
184
+ supply: {
185
+ create: (body, opts) => send("supply.create", { body }, opts),
186
+ list: (query) => send("supply.list", { query }),
187
+ get: (id) => send("supply.get", { params: { id } }),
188
+ reverse: (id, body, opts) => send("supply.reverse", {
189
+ params: { id },
190
+ body
191
+ }, opts)
192
+ },
193
+ batches: {
194
+ create: (body) => send("batches.create", { body }),
195
+ list: (query) => send("batches.list", { query }),
196
+ get: (id) => send("batches.get", { params: { id } }),
197
+ patch: (id, body, opts) => send("batches.patch", {
198
+ params: { id },
199
+ body
200
+ }, opts)
201
+ },
202
+ claims: {
203
+ consume: (body, opts) => send("claims.consume", { body }, opts),
204
+ settle: (body, opts) => send("claims.settle", { body }, opts),
205
+ list: (query) => send("claims.list", { query }),
206
+ get: (id) => send("claims.get", { params: { id } })
207
+ },
208
+ holds: {
209
+ create: (body, opts) => send("holds.create", { body }, opts),
210
+ list: (query) => send("holds.list", { query }),
211
+ get: (id) => send("holds.get", { params: { id } }),
212
+ extend: (id, body, opts) => send("holds.extend", {
213
+ params: { id },
214
+ body
215
+ }, opts),
216
+ commit: (id, body, opts) => send("holds.commit", {
217
+ params: { id },
218
+ body
219
+ }, opts),
220
+ release: (id, opts) => send("holds.release", { params: { id } }, opts),
221
+ cancel: (id, body, opts) => send("holds.cancel", {
222
+ params: { id },
223
+ body
224
+ }, opts),
225
+ reschedule: (body, opts) => send("holds.reschedule", { body }, opts)
226
+ },
227
+ availability: { query: (body) => send("availability.query", { body }) },
228
+ balances: { get: (resourceId, query) => send("balances.get", {
229
+ params: { id: resourceId },
230
+ query
231
+ }) },
232
+ holderBalances: {
233
+ list: (holderRef, query) => send("holderBalances.list", {
234
+ params: { ref: holderRef },
235
+ query
236
+ }),
237
+ get: (holderRef, resourceId, query) => send("holderBalances.get", {
238
+ params: {
239
+ ref: holderRef,
240
+ resourceId
241
+ },
242
+ query
243
+ })
244
+ },
245
+ schedules: {
246
+ put: (resourceId, body, opts) => send("schedules.put", {
247
+ params: { id: resourceId },
248
+ body
249
+ }, opts),
250
+ get: (resourceId) => send("schedules.get", { params: { id: resourceId } })
251
+ },
252
+ exceptions: {
253
+ create: (resourceId, body, opts) => send("exceptions.create", {
254
+ params: { id: resourceId },
255
+ body
256
+ }, opts),
257
+ list: (resourceId, query) => send("exceptions.list", {
258
+ params: { id: resourceId },
259
+ query
260
+ }),
261
+ patch: (resourceId, eid, body, opts) => send("exceptions.patch", {
262
+ params: {
263
+ id: resourceId,
264
+ eid
265
+ },
266
+ body
267
+ }, opts),
268
+ delete: (resourceId, eid, opts) => send("exceptions.delete", { params: {
269
+ id: resourceId,
270
+ eid
271
+ } }, opts)
272
+ },
273
+ slots: { list: (query) => send("slots.list", { query }) },
274
+ transfers: { create: (body, opts) => send("transfers.create", { body }, opts) },
275
+ counts: { create: (body, opts) => send("counts.create", { body }, opts) },
276
+ adjustments: { create: (body, opts) => send("adjustments.create", { body }, opts) },
277
+ transformations: {
278
+ create: (body, opts) => send("transformations.create", { body }, opts),
279
+ get: (id) => send("transformations.get", { params: { id } })
280
+ },
281
+ movements: {
282
+ list: (query) => send("movements.list", { query }),
283
+ get: (id) => send("movements.get", { params: { id } })
284
+ },
285
+ reports: { totals: (query) => send("reports.totals", { query }) },
286
+ events: { read: (query) => send("events.read", { query }) }
287
+ };
288
+ }
289
+ export { readError as a, isErrorBody as i, ResourcesharkApiError as n, createClient as r, HOSTED_BASE_URL as t };
@@ -0,0 +1,171 @@
1
+ import { H as Duration, Jt as Quantity, M as ClaimLine, Pt as Movement, Qt as ResourceId, R as ConsumeResponse, W as ErrorClass, Y as Evidence, Yt as Ref, at as FiniteSpan, cn as Scope, fn as ShortLine, ht as HoldId, in as RetainedHold, j as ClaimId, l as ResourcesharkClient, mn as SlotsQuery, pn as Slot, st as Hold, vt as HoldResolvedDetails } from "./client-DEn-MdAz.js";
2
+ /** How the workflow reaches the service: directly with a secret key, or through the customer's endpoint. */
3
+ interface HoldTransport<Place, Extend, Commit> {
4
+ slots(q: SlotsQuery): Promise<{
5
+ slots: Slot[];
6
+ serverNow: string;
7
+ }>;
8
+ /** A repeated `sourceKey` answers with the hold it first placed, which may be resolved, or a `RetainedHold`. */
9
+ place(input: Place, attemptKey: string): Promise<{
10
+ hold: Hold | RetainedHold;
11
+ serverNow: string;
12
+ }>;
13
+ extend(holdId: HoldId, input: Extend, attemptKey: string): Promise<{
14
+ hold: Hold | RetainedHold;
15
+ serverNow: string;
16
+ }>;
17
+ release(holdId: HoldId, attemptKey: string): Promise<{
18
+ hold: Hold | RetainedHold;
19
+ serverNow: string;
20
+ }>;
21
+ commit(holdId: HoldId, input: Commit, attemptKey: string): Promise<{
22
+ hold: Hold | RetainedHold;
23
+ movements: Movement[];
24
+ duplicate?: true;
25
+ serverNow: string;
26
+ }>;
27
+ /**
28
+ * A separate consume of the given lines, behind an expired commit's
29
+ * `buy`. Only a transport that holds a secret key has it; without it,
30
+ * `buy` is null.
31
+ */
32
+ buy?(lines: ClaimLine[], input: BuyInput): Promise<ConsumeResponse>;
33
+ }
34
+ /** The app's hold request. `ttl` and `sourceKey` are required; no default exists anywhere. */
35
+ interface PlaceInput {
36
+ /** A line on a resource kept by place must carry `scope.placeId`. */
37
+ lines: ClaimLine[];
38
+ /** How long to hold, such as "15m". */
39
+ ttl: Duration;
40
+ /** Whom it holds for. Copied into `scope.holderRef` on each line of a resource held per holder that names none. */
41
+ holderRef?: Ref;
42
+ label?: Ref;
43
+ reference?: Evidence;
44
+ sourceKey: string;
45
+ }
46
+ interface ExtendInput {
47
+ /** How long to hold from now, such as "15m". */
48
+ ttl: Duration;
49
+ }
50
+ /** Omit `lines` (or send []) to take every line; a nonempty list must name every line. */
51
+ interface CommitInput {
52
+ evidence: Evidence;
53
+ sourceKey: string;
54
+ lines?: {
55
+ claimId: ClaimId;
56
+ quantity: Quantity;
57
+ }[];
58
+ }
59
+ /** A separate consume of the same lines (spans taken from the hold's lines). The app picks the keys; reusing the commit's sourceKey is allowed. */
60
+ interface BuyInput {
61
+ evidence: Evidence;
62
+ sourceKey: string;
63
+ idempotencyKey: string;
64
+ }
65
+ interface ApiTransportOptions {
66
+ /** How long a resource read before a hold is reused, in ms. Default 0: read every time. */
67
+ resourceCacheMs?: number;
68
+ }
69
+ /**
70
+ * Secret-key transport. Before a hold it reads each line's resource
71
+ * (`resources.get`) and:
72
+ * - copies `holderRef` into `scope.holderRef` on each line of a resource
73
+ * with `scope.holders`, or fails `holder_required` naming the line when
74
+ * neither is given;
75
+ * - fails `place_required` naming the line when a resource with
76
+ * `scope.places` has no `scope.placeId`.
77
+ * A missing `ttl`, `sourceKey`, or line fails `invalid_request` before any
78
+ * request, as the service would. `serverNow` is this process's clock.
79
+ */
80
+ declare function apiTransport(client: ResourcesharkClient, options?: ApiTransportOptions): HoldTransport<PlaceInput, ExtendInput, CommitInput>;
81
+ interface EndpointTransportOptions {
82
+ /** The prefix the app mounted its hold endpoint at, such as `/api/booking`. */
83
+ url: string;
84
+ fetch?: typeof fetch;
85
+ /** Headers for every request, such as the signed-in user's session. */
86
+ headers?: () => Record<string, string> | Promise<Record<string, string>>;
87
+ }
88
+ /**
89
+ * Browser transport to the customer's endpoint: `GET /slots`, `POST
90
+ * /holds`, `POST /holds/:id/extend`, `/release`, and `/commit` under
91
+ * `url`, each POST with the attempt key as its `Idempotency-Key`. Place,
92
+ * Extend, and Commit are the app's own shapes, sent as `{ input }`. An
93
+ * expired commit's `buy` is null here: a late payment is taken on the
94
+ * server, with `commitHold`.
95
+ */
96
+ declare function endpointTransport<Place, Extend = void, Commit = void>(options: EndpointTransportOptions): HoldTransport<Place, Extend, Commit>;
97
+ interface WorkflowError {
98
+ /**
99
+ * What went wrong, to choose the words on screen by: one of
100
+ * resourceshark's error codes (such as `insufficient_supply` or
101
+ * `hold_expired`), a code from the customer's endpoint, `unknown` when an
102
+ * answer wasn't the standard error shape, or one of the workflow's own:
103
+ * `network_error`, `busy`, `no_hold`, `hold_open`, `holder_required`,
104
+ * `place_required`, or `invalid_request` for a request the workflow
105
+ * refuses before sending, as the service would.
106
+ */
107
+ code: string;
108
+ /** For agents reading the answer, not for the screen. */
109
+ message: string;
110
+ /** The HTTP status, when the API or the endpoint answered. */
111
+ status?: number;
112
+ /** The code's class, from the answer: `retry_later`, `exhausted`, or `change_the_request`. */
113
+ errorClass?: ErrorClass;
114
+ /** The page that explains the code. */
115
+ docs?: string;
116
+ details?: unknown;
117
+ }
118
+ /** One line of an expired hold: what the commit asked to take, and what is available now. */
119
+ interface ExpiredLine {
120
+ claimId: ClaimId;
121
+ resourceId: ResourceId;
122
+ /** The line's scope, whole. */
123
+ scope: Scope;
124
+ /** The hold line's span, on a resource counted in buckets. */
125
+ span?: FiniteSpan;
126
+ quantity: Quantity;
127
+ available: Quantity;
128
+ /** Whether `available` covers `quantity`. */
129
+ enough: boolean;
130
+ }
131
+ type CommitOutcome = {
132
+ status: 'committed';
133
+ hold: Hold | RetainedHold;
134
+ movements: Movement[];
135
+ duplicate?: true;
136
+ } | {
137
+ status: 'expired';
138
+ expiresAt: string;
139
+ /** Null when retention removed the hold's lines. */
140
+ lines: ExpiredLine[] | null;
141
+ /** Whether every line has enough available now. */
142
+ allFit: boolean;
143
+ /** A separate consume of the same lines, for the app to call if it decides to. Null through `endpointTransport`, or with no lines to take. */
144
+ buy: ((input: BuyInput) => Promise<BuyOutcome>) | null;
145
+ } | {
146
+ status: 'resolved';
147
+ resolution: HoldResolvedDetails;
148
+ } | {
149
+ status: 'failed';
150
+ error: WorkflowError;
151
+ };
152
+ type BuyOutcome = {
153
+ status: 'bought';
154
+ response: ConsumeResponse;
155
+ } | {
156
+ status: 'short';
157
+ lines: ShortLine[];
158
+ nextSupplyAt?: string;
159
+ } | {
160
+ status: 'failed';
161
+ error: WorkflowError;
162
+ };
163
+ /**
164
+ * The server-side commit, for the app's payment handler: the same outcome
165
+ * as the workflow's, with `buy` set. On `hold_expired` with lines, it reads
166
+ * the hold for its lines' spans; if that read fails, `buy` is null.
167
+ */
168
+ declare function commitHold(client: ResourcesharkClient, holdId: HoldId, input: CommitInput, options: {
169
+ idempotencyKey: string;
170
+ }): Promise<CommitOutcome>;
171
+ export { WorkflowError as a, CommitInput as c, HoldTransport as d, PlaceInput as f, commitHold as i, EndpointTransportOptions as l, endpointTransport as m, CommitOutcome as n, ApiTransportOptions as o, apiTransport as p, ExpiredLine as r, BuyInput as s, BuyOutcome as t, ExtendInput as u };