@agentpost-tools/resourceshark-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,288 @@
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
+ var ResourcesharkApiError = class 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 search.set(key, String(value));
111
+ }
112
+ const query = search.toString();
113
+ const url = `${base}${path}${query ? `?${query}` : ""}`;
114
+ const headers = new Headers(options.headers);
115
+ if (!headers.has("accept")) headers.set("accept", "application/json");
116
+ const token = opts?.token ?? options.token;
117
+ if (token) headers.set("authorization", `Bearer ${token}`);
118
+ if (opts?.idempotencyKey !== void 0) headers.set("idempotency-key", opts.idempotencyKey);
119
+ if (opts?.ifMatch !== void 0) headers.set("if-match", String(opts.ifMatch));
120
+ const { body } = parts;
121
+ if (body !== void 0) headers.set("content-type", "application/json");
122
+ const response = await doFetch(url, {
123
+ method,
124
+ headers,
125
+ body: body === void 0 ? void 0 : JSON.stringify(body)
126
+ });
127
+ const text = await response.text();
128
+ let parsed;
129
+ if (text) try {
130
+ parsed = JSON.parse(text);
131
+ } catch {
132
+ parsed = void 0;
133
+ }
134
+ if (response.ok) return parsed;
135
+ const error = readError(parsed);
136
+ if (error) throw new ResourcesharkApiError(response.status, error.code, error.message, error.details, error.docs, isErrorClass(error.class) ? error.class : void 0);
137
+ throw new ResourcesharkApiError(response.status, "unknown", `${method} ${path} failed with ${response.status}`);
138
+ }
139
+ return {
140
+ config: {
141
+ get: (opts) => send("config.get", {}, opts),
142
+ put: (body, opts) => send("config.put", { body }, opts)
143
+ },
144
+ resources: {
145
+ create: (body, opts) => send("resources.create", { body }, opts),
146
+ list: (query) => send("resources.list", { query }),
147
+ get: (id) => send("resources.get", { params: { id } }),
148
+ patch: (id, body, opts) => send("resources.patch", {
149
+ params: { id },
150
+ body
151
+ }, opts),
152
+ archive: (id, opts) => send("resources.archive", { params: { id } }, opts)
153
+ },
154
+ places: {
155
+ create: (body) => send("places.create", { body }),
156
+ list: (query) => send("places.list", { query }),
157
+ patch: (id, body) => send("places.patch", {
158
+ params: { id },
159
+ body
160
+ })
161
+ },
162
+ instances: {
163
+ create: (resourceId, body) => send("instances.create", {
164
+ params: { id: resourceId },
165
+ body
166
+ }),
167
+ list: (resourceId, query) => send("instances.list", {
168
+ params: { id: resourceId },
169
+ query
170
+ }),
171
+ patch: (resourceId, iid, body) => send("instances.patch", {
172
+ params: {
173
+ id: resourceId,
174
+ iid
175
+ },
176
+ body
177
+ })
178
+ },
179
+ freeInstances: { list: (resourceId, query) => send("freeInstances.list", {
180
+ params: { id: resourceId },
181
+ query
182
+ }) },
183
+ supply: {
184
+ create: (body, opts) => send("supply.create", { body }, opts),
185
+ list: (query) => send("supply.list", { query }),
186
+ get: (id) => send("supply.get", { params: { id } }),
187
+ reverse: (id, body, opts) => send("supply.reverse", {
188
+ params: { id },
189
+ body
190
+ }, opts)
191
+ },
192
+ batches: {
193
+ create: (body) => send("batches.create", { body }),
194
+ list: (query) => send("batches.list", { query }),
195
+ get: (id) => send("batches.get", { params: { id } }),
196
+ patch: (id, body, opts) => send("batches.patch", {
197
+ params: { id },
198
+ body
199
+ }, opts)
200
+ },
201
+ claims: {
202
+ consume: (body, opts) => send("claims.consume", { body }, opts),
203
+ settle: (body, opts) => send("claims.settle", { body }, opts),
204
+ list: (query) => send("claims.list", { query }),
205
+ get: (id) => send("claims.get", { params: { id } })
206
+ },
207
+ holds: {
208
+ create: (body, opts) => send("holds.create", { body }, opts),
209
+ list: (query) => send("holds.list", { query }),
210
+ get: (id) => send("holds.get", { params: { id } }),
211
+ extend: (id, body, opts) => send("holds.extend", {
212
+ params: { id },
213
+ body
214
+ }, opts),
215
+ commit: (id, body, opts) => send("holds.commit", {
216
+ params: { id },
217
+ body
218
+ }, opts),
219
+ release: (id, opts) => send("holds.release", { params: { id } }, opts),
220
+ cancel: (id, body, opts) => send("holds.cancel", {
221
+ params: { id },
222
+ body
223
+ }, opts),
224
+ reschedule: (body, opts) => send("holds.reschedule", { body }, opts)
225
+ },
226
+ availability: { query: (body) => send("availability.query", { body }) },
227
+ balances: { get: (resourceId, query) => send("balances.get", {
228
+ params: { id: resourceId },
229
+ query
230
+ }) },
231
+ holderBalances: {
232
+ list: (holderRef, query) => send("holderBalances.list", {
233
+ params: { ref: holderRef },
234
+ query
235
+ }),
236
+ get: (holderRef, resourceId, query) => send("holderBalances.get", {
237
+ params: {
238
+ ref: holderRef,
239
+ resourceId
240
+ },
241
+ query
242
+ })
243
+ },
244
+ schedules: {
245
+ put: (resourceId, body, opts) => send("schedules.put", {
246
+ params: { id: resourceId },
247
+ body
248
+ }, opts),
249
+ get: (resourceId) => send("schedules.get", { params: { id: resourceId } })
250
+ },
251
+ exceptions: {
252
+ create: (resourceId, body, opts) => send("exceptions.create", {
253
+ params: { id: resourceId },
254
+ body
255
+ }, opts),
256
+ list: (resourceId, query) => send("exceptions.list", {
257
+ params: { id: resourceId },
258
+ query
259
+ }),
260
+ patch: (resourceId, eid, body, opts) => send("exceptions.patch", {
261
+ params: {
262
+ id: resourceId,
263
+ eid
264
+ },
265
+ body
266
+ }, opts),
267
+ delete: (resourceId, eid, opts) => send("exceptions.delete", { params: {
268
+ id: resourceId,
269
+ eid
270
+ } }, opts)
271
+ },
272
+ slots: { list: (query) => send("slots.list", { query }) },
273
+ transfers: { create: (body, opts) => send("transfers.create", { body }, opts) },
274
+ counts: { create: (body, opts) => send("counts.create", { body }, opts) },
275
+ adjustments: { create: (body, opts) => send("adjustments.create", { body }, opts) },
276
+ transformations: {
277
+ create: (body, opts) => send("transformations.create", { body }, opts),
278
+ get: (id) => send("transformations.get", { params: { id } })
279
+ },
280
+ movements: {
281
+ list: (query) => send("movements.list", { query }),
282
+ get: (id) => send("movements.get", { params: { id } })
283
+ },
284
+ reports: { totals: (query) => send("reports.totals", { query }) },
285
+ events: { read: (query) => send("events.read", { query }) }
286
+ };
287
+ }
288
+ export { readError as a, isErrorBody as i, ResourcesharkApiError as n, createClient as r, HOSTED_BASE_URL as t };
@@ -0,0 +1,384 @@
1
+ // src/workflows/errors.ts
2
+ /** A failure the workflow or a transport finds itself, before any request. */
3
+ var WorkflowFailure = class extends Error {
4
+ code;
5
+ details;
6
+ constructor(code, message, details) {
7
+ super(message);
8
+ this.name = "WorkflowFailure";
9
+ this.code = code;
10
+ this.details = details;
11
+ }
12
+ };
13
+ /**
14
+ * The workflow's error for anything a transport threw. An error with a
15
+ * numeric `status` and a string `code`, such as `ResourcesharkApiError` or
16
+ * the endpoint transport's own, is an answer; anything else never reached
17
+ * an answer, and is a `network_error`.
18
+ */
19
+ function toWorkflowError(error) {
20
+ if (error instanceof WorkflowFailure) return {
21
+ code: error.code,
22
+ message: error.message,
23
+ ...error.details === void 0 ? {} : { details: error.details }
24
+ };
25
+ if (isAnswer(error)) {
26
+ const { errorClass, docs, details } = error;
27
+ return {
28
+ code: error.code,
29
+ message: error.message,
30
+ status: error.status,
31
+ ...typeof errorClass === "string" ? { errorClass } : {},
32
+ ...typeof docs === "string" ? { docs } : {},
33
+ ...details === void 0 ? {} : { details }
34
+ };
35
+ }
36
+ return {
37
+ code: "network_error",
38
+ message: error instanceof Error ? error.message : String(error)
39
+ };
40
+ }
41
+ function isAnswer(error) {
42
+ return error instanceof Error && typeof error.status === "number" && typeof error.code === "string";
43
+ }
44
+ const record = (value) => typeof value === "object" && value !== null ? value : void 0;
45
+ /** The short lines of `insufficient_supply`, `exhausted_until_supply` (with its `nextSupplyAt`), or `assignment_infeasible`. */
46
+ function shortOf(error) {
47
+ if (error.code !== "insufficient_supply" && error.code !== "exhausted_until_supply" && error.code !== "assignment_infeasible") return void 0;
48
+ const details = record(error.details);
49
+ const lines = Array.isArray(details?.lines) ? details.lines : [];
50
+ const next = details?.nextSupplyAt;
51
+ return {
52
+ lines,
53
+ ...typeof next === "string" ? { nextSupplyAt: next } : {}
54
+ };
55
+ }
56
+ /** What `hold_expired` carries: when the hold ran out, and on a commit, each line's availability. */
57
+ function expiredOf(error) {
58
+ if (error.code !== "hold_expired") return void 0;
59
+ const details = record(error.details);
60
+ if (!details || typeof details.expiresAt !== "string") return void 0;
61
+ return details;
62
+ }
63
+ /** What `hold_resolved` carries: how the hold first ended. */
64
+ function resolvedOf(error) {
65
+ if (error.code !== "hold_resolved") return void 0;
66
+ const details = record(error.details);
67
+ if (!details || typeof details.status !== "string") return void 0;
68
+ return details;
69
+ }
70
+ // src/workflows/transport.ts
71
+ const holderCheck = (line, resource, index, input) => {
72
+ if (!resource.scope.holders || line.scope?.holderRef !== void 0) return line;
73
+ if (input.holderRef === void 0) throw new WorkflowFailure("holder_required", `line ${index} is on resource ${resource.id}, which is held per holder: name scope.holderRef on the line, or holderRef on the hold`, {
74
+ line: index,
75
+ resourceId: resource.id,
76
+ field: "scope.holderRef"
77
+ });
78
+ return {
79
+ ...line,
80
+ scope: {
81
+ ...line.scope,
82
+ holderRef: input.holderRef
83
+ }
84
+ };
85
+ };
86
+ const placeCheck = (line, resource, index) => {
87
+ if (!resource.scope.places || line.scope?.placeId !== void 0) return line;
88
+ throw new WorkflowFailure("place_required", `line ${index} is on resource ${resource.id}, which is kept by place: name scope.placeId on the line`, {
89
+ line: index,
90
+ resourceId: resource.id,
91
+ field: "scope.placeId"
92
+ });
93
+ };
94
+ const LINE_CHECKS = [holderCheck, placeCheck];
95
+ function required(value, field, example) {
96
+ if (typeof value === "string" && value.trim() !== "") return;
97
+ throw new WorkflowFailure("invalid_request", `${field} is required, such as ${example}; the workflow has no default`, { field });
98
+ }
99
+ /**
100
+ * Secret-key transport. Before a hold it reads each line's resource
101
+ * (`resources.get`) and:
102
+ * - copies `holderRef` into `scope.holderRef` on each line of a resource
103
+ * with `scope.holders`, or fails `holder_required` naming the line when
104
+ * neither is given;
105
+ * - fails `place_required` naming the line when a resource with
106
+ * `scope.places` has no `scope.placeId`.
107
+ * A missing `ttl`, `sourceKey`, or line fails `invalid_request` before any
108
+ * request, as the service would. `serverNow` is this process's clock.
109
+ */
110
+ function apiTransport(client, options = {}) {
111
+ const cacheMs = options.resourceCacheMs ?? 0;
112
+ const cache = /* @__PURE__ */ new Map();
113
+ const serverNow = () => (/* @__PURE__ */ new Date()).toISOString();
114
+ function resourceOf(id) {
115
+ const at = Date.now();
116
+ const hit = cache.get(id);
117
+ if (cacheMs > 0 && hit && at - hit.at < cacheMs) return hit.resource;
118
+ const resource = client.resources.get(id).then(({ resource }) => resource);
119
+ if (cacheMs > 0) {
120
+ const entry = {
121
+ at,
122
+ resource
123
+ };
124
+ cache.set(id, entry);
125
+ resource.catch(() => {
126
+ if (cache.get(id) === entry) cache.delete(id);
127
+ });
128
+ }
129
+ return resource;
130
+ }
131
+ async function checkedLines(input) {
132
+ const ids = [...new Set(input.lines.map((line) => line.resourceId))];
133
+ const read = await Promise.all(ids.map(resourceOf));
134
+ const resources = new Map(ids.map((id, i) => [id, read[i]]));
135
+ return input.lines.map((line, index) => LINE_CHECKS.reduce((checked, check) => check(checked, resources.get(line.resourceId), index, input), line));
136
+ }
137
+ return {
138
+ async slots(q) {
139
+ const { slots } = await client.slots.list(q);
140
+ return {
141
+ slots,
142
+ serverNow: serverNow()
143
+ };
144
+ },
145
+ async place(input, attemptKey) {
146
+ if (!Array.isArray(input?.lines) || input.lines.length === 0) throw new WorkflowFailure("invalid_request", "a hold needs at least one line", { field: "lines" });
147
+ required(input.ttl, "ttl", "\"15m\"");
148
+ required(input.sourceKey, "sourceKey", "\"checkout:chk_123\"");
149
+ const body = {
150
+ lines: await checkedLines(input),
151
+ ttl: input.ttl,
152
+ sourceKey: input.sourceKey,
153
+ ...input.holderRef === void 0 ? {} : { holderRef: input.holderRef },
154
+ ...input.label === void 0 ? {} : { label: input.label },
155
+ ...input.reference === void 0 ? {} : { reference: input.reference }
156
+ };
157
+ const { hold } = await client.holds.create(body, { idempotencyKey: attemptKey });
158
+ return {
159
+ hold,
160
+ serverNow: serverNow()
161
+ };
162
+ },
163
+ async extend(holdId, input, attemptKey) {
164
+ required(input?.ttl, "ttl", "\"15m\"");
165
+ const { hold } = await client.holds.extend(holdId, { ttl: input.ttl }, { idempotencyKey: attemptKey });
166
+ return {
167
+ hold,
168
+ serverNow: serverNow()
169
+ };
170
+ },
171
+ async release(holdId, attemptKey) {
172
+ const { hold } = await client.holds.release(holdId, { idempotencyKey: attemptKey });
173
+ return {
174
+ hold,
175
+ serverNow: serverNow()
176
+ };
177
+ },
178
+ async commit(holdId, input, attemptKey) {
179
+ const answer = await client.holds.commit(holdId, commitBody(input), { idempotencyKey: attemptKey });
180
+ return {
181
+ hold: answer.hold,
182
+ movements: answer.movements,
183
+ ...answer.duplicate ? { duplicate: true } : {},
184
+ serverNow: serverNow()
185
+ };
186
+ },
187
+ buy(lines, input) {
188
+ return client.claims.consume({
189
+ lines,
190
+ evidence: input.evidence,
191
+ sourceKey: input.sourceKey
192
+ }, { idempotencyKey: input.idempotencyKey });
193
+ }
194
+ };
195
+ }
196
+ /** The commit request as the API reads it, with no field the app left out. */
197
+ function commitBody(input) {
198
+ return {
199
+ evidence: input.evidence,
200
+ sourceKey: input.sourceKey,
201
+ ...input.lines === void 0 ? {} : { lines: input.lines }
202
+ };
203
+ }
204
+ /** An error answer from the customer's endpoint, in the same shape the client gives. */
205
+ var EndpointError = class extends Error {
206
+ status;
207
+ code;
208
+ errorClass;
209
+ details;
210
+ docs;
211
+ constructor(status, code, message, extra = {}) {
212
+ super(message);
213
+ this.name = "EndpointError";
214
+ this.status = status;
215
+ this.code = code;
216
+ if (extra.errorClass !== void 0) this.errorClass = extra.errorClass;
217
+ if (extra.details !== void 0) this.details = extra.details;
218
+ if (extra.docs !== void 0) this.docs = extra.docs;
219
+ }
220
+ };
221
+ /**
222
+ * Browser transport to the customer's endpoint: `GET /slots`, `POST
223
+ * /holds`, `POST /holds/:id/extend`, `/release`, and `/commit` under
224
+ * `url`, each POST with the attempt key as its `Idempotency-Key`. Place,
225
+ * Extend, and Commit are the app's own shapes, sent as `{ input }`. An
226
+ * expired commit's `buy` is null here: a late payment is taken on the
227
+ * server, with `commitHold`.
228
+ */
229
+ function endpointTransport(options) {
230
+ const base = options.url.replace(/\/+$/, "");
231
+ const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
232
+ async function call(method, path, attemptKey, body) {
233
+ const headers = {
234
+ accept: "application/json",
235
+ ...await options.headers?.()
236
+ };
237
+ if (attemptKey !== void 0) headers["idempotency-key"] = attemptKey;
238
+ if (body !== void 0) headers["content-type"] = "application/json";
239
+ const response = await doFetch(`${base}${path}`, {
240
+ method,
241
+ headers,
242
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
243
+ });
244
+ const text = await response.text();
245
+ let parsed;
246
+ try {
247
+ parsed = text ? JSON.parse(text) : void 0;
248
+ } catch {
249
+ parsed = void 0;
250
+ }
251
+ if (!response.ok) throw errorOf(response.status, parsed, method, path);
252
+ if (typeof parsed !== "object" || parsed === null) throw new EndpointError(response.status, "unknown", `${method} ${path} answered ${response.status} without a JSON body`);
253
+ return parsed;
254
+ }
255
+ const holdPath = (holdId, action) => `/holds/${encodeURIComponent(holdId)}/${action}`;
256
+ return {
257
+ slots(q) {
258
+ const search = new URLSearchParams();
259
+ for (const [key, value] of Object.entries(q)) if (value !== void 0 && value !== null) search.set(key, String(value));
260
+ return call("GET", `/slots?${search}`);
261
+ },
262
+ place(input, attemptKey) {
263
+ return call("POST", "/holds", attemptKey, { input });
264
+ },
265
+ extend(holdId, input, attemptKey) {
266
+ return call("POST", holdPath(holdId, "extend"), attemptKey, { input });
267
+ },
268
+ release(holdId, attemptKey) {
269
+ return call("POST", holdPath(holdId, "release"), attemptKey);
270
+ },
271
+ commit(holdId, input, attemptKey) {
272
+ return call("POST", holdPath(holdId, "commit"), attemptKey, { input });
273
+ }
274
+ };
275
+ }
276
+ function errorOf(status, body, method, path) {
277
+ const error = body?.error;
278
+ if (typeof error !== "object" || error === null || typeof error.code !== "string") return new EndpointError(status, "unknown", `${method} ${path.split("?")[0]} failed with ${status}`);
279
+ return new EndpointError(status, error.code, typeof error.message === "string" ? error.message : error.code, {
280
+ ...typeof error.class === "string" ? { errorClass: error.class } : {},
281
+ ...error.details === void 0 ? {} : { details: error.details },
282
+ ...typeof error.docs === "string" ? { docs: error.docs } : {}
283
+ });
284
+ }
285
+ // src/workflows/commit.ts
286
+ /** The expired lines, each with the span of the hold line it names. Null when `hold_expired` carried no lines. */
287
+ function expiredLines(details, hold) {
288
+ if (!details.lines) return null;
289
+ const spans = new Map((hold?.lines ?? []).flatMap((line) => line.span ? [[line.claimId, line.span]] : []));
290
+ return details.lines.map((line) => {
291
+ const span = spans.get(line.claimId);
292
+ return {
293
+ claimId: line.claimId,
294
+ resourceId: line.resourceId,
295
+ scope: line.scope,
296
+ ...span ? { span } : {},
297
+ quantity: line.quantity,
298
+ available: line.available,
299
+ enough: line.available >= line.quantity
300
+ };
301
+ });
302
+ }
303
+ /**
304
+ * The outcome of an expired commit. `buy` is offered when `consume` is,
305
+ * and some line asked for more than nothing; it consumes those lines with
306
+ * their scopes whole and the hold lines' spans.
307
+ */
308
+ function expiredOutcome(details, lines, consume) {
309
+ const claimLines = (lines ?? []).filter(({ quantity }) => quantity > 0).map((line) => ({
310
+ resourceId: line.resourceId,
311
+ scope: line.scope,
312
+ quantity: line.quantity,
313
+ ...line.span ? { span: line.span } : {}
314
+ }));
315
+ return {
316
+ status: "expired",
317
+ expiresAt: details.expiresAt,
318
+ lines,
319
+ allFit: lines !== null && lines.every(({ enough }) => enough),
320
+ buy: consume && claimLines.length > 0 ? (input) => buyWith(consume, claimLines, input) : null
321
+ };
322
+ }
323
+ async function buyWith(consume, lines, input) {
324
+ try {
325
+ return {
326
+ status: "bought",
327
+ response: await consume(lines, input)
328
+ };
329
+ } catch (caught) {
330
+ const error = toWorkflowError(caught);
331
+ const short = shortOf(error);
332
+ if (short) return {
333
+ status: "short",
334
+ ...short
335
+ };
336
+ return {
337
+ status: "failed",
338
+ error
339
+ };
340
+ }
341
+ }
342
+ /**
343
+ * The server-side commit, for the app's payment handler: the same outcome
344
+ * as the workflow's, with `buy` set. On `hold_expired` with lines, it reads
345
+ * the hold for its lines' spans; if that read fails, `buy` is null.
346
+ */
347
+ async function commitHold(client, holdId, input, options) {
348
+ try {
349
+ const answer = await client.holds.commit(holdId, commitBody(input), { idempotencyKey: options.idempotencyKey });
350
+ return {
351
+ status: "committed",
352
+ hold: answer.hold,
353
+ movements: answer.movements,
354
+ ...answer.duplicate ? { duplicate: true } : {}
355
+ };
356
+ } catch (caught) {
357
+ const error = toWorkflowError(caught);
358
+ const expired = expiredOf(error);
359
+ if (expired) {
360
+ let hold = null;
361
+ if (expired.lines?.length) try {
362
+ hold = (await client.holds.get(holdId)).hold;
363
+ } catch {
364
+ hold = null;
365
+ }
366
+ const consume = hold ? (lines, buy) => client.claims.consume({
367
+ lines,
368
+ evidence: buy.evidence,
369
+ sourceKey: buy.sourceKey
370
+ }, { idempotencyKey: buy.idempotencyKey }) : null;
371
+ return expiredOutcome(expired, expiredLines(expired, hold), consume);
372
+ }
373
+ const resolution = resolvedOf(error);
374
+ if (resolution) return {
375
+ status: "resolved",
376
+ resolution
377
+ };
378
+ return {
379
+ status: "failed",
380
+ error
381
+ };
382
+ }
383
+ }
384
+ export { endpointTransport as a, resolvedOf as c, apiTransport as i, shortOf as l, expiredLines as n, WorkflowFailure as o, expiredOutcome as r, expiredOf as s, commitHold as t, toWorkflowError as u };