@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,171 @@
1
+ import { B as ErrorClass, F as ConsumeResponse, Ht as Quantity, Kt as ResourceId, O as ClaimId, Ot as Movement, Qt as RetainedHold, R as Duration, Ut as Ref, W as Evidence, an as ShortLine, et as FiniteSpan, k as ClaimLine, nn as Scope, nt as Hold, o as ResourcesharkClient, on as Slot, pt as HoldResolvedDetails, sn as SlotsQuery, ut as HoldId } from "./client-C-4s_6Qp.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 };
@@ -0,0 +1,108 @@
1
+ import { At as MovementReason, En as Unit, Ht as Quantity, Kt as ResourceId, Mt as MovementSums, R as Duration, W as Evidence, _n as SupplyReverseResponse, a as ResourcesharkApiError, bn as TotalsReport, fn as SupplyId, hn as SupplyResponse, ln as SupplyCreateInput, m as Attributes, nn as Scope, o as ResourcesharkClient, on as Slot, vn as TotalsBalance } from "../client-C-4s_6Qp.js";
2
+ type Cadence = {
3
+ every: 'month';
4
+ count: number;
5
+ timeZone: string;
6
+ dayOverflow: 'clamp' | 'roll';
7
+ } | {
8
+ every: 'day';
9
+ count: number;
10
+ timeZone: string;
11
+ } | {
12
+ every: 'duration';
13
+ length: Duration;
14
+ };
15
+ interface Period {
16
+ index: number;
17
+ start: string;
18
+ end: string;
19
+ }
20
+ interface SupplyRule {
21
+ resourceId: ResourceId;
22
+ scope: Scope;
23
+ quantity: Quantity;
24
+ kind: 'added';
25
+ cadence: Cadence;
26
+ from: string;
27
+ periods: number;
28
+ expires: boolean;
29
+ evidence(p: Period): Evidence;
30
+ sourceKey(p: Period): string;
31
+ attributes?(p: Period): Attributes;
32
+ drawOrder?: number;
33
+ }
34
+ /**
35
+ * Creates half-open periods from the anchor. Calendar dates and times without
36
+ * offsets use the cadence's zone. An elapsed cadence starts at the given
37
+ * instant, with a date alone read as UTC midnight.
38
+ */
39
+ export declare function supplyPeriods(rule: SupplyRule): {
40
+ period: Period;
41
+ entry: SupplyCreateInput;
42
+ }[];
43
+ /** Posts periods in order, stopping at the first failed write. */
44
+ export declare function postSupplyPeriods(client: ResourcesharkClient, entries: {
45
+ entry: SupplyCreateInput;
46
+ }[], o: {
47
+ idempotencyKey(entry: SupplyCreateInput): string;
48
+ }): Promise<SupplyResponse[]>;
49
+ interface TotalsSum {
50
+ unit: Unit;
51
+ resourceIds: ResourceId[];
52
+ balance: TotalsBalance | null;
53
+ movements: MovementSums;
54
+ chosen?: Quantity;
55
+ bucketed: ResourceId[];
56
+ }
57
+ /** Sums each combination of unit code and precision independently. */
58
+ export declare function sumTotals(report: TotalsReport, o: {
59
+ resourceIds?: ResourceId[];
60
+ reasons?: MovementReason[];
61
+ }): TotalsSum[];
62
+ /** Sums the rows for each grouping value, including the unnamed group. */
63
+ export declare function sumGroups(report: TotalsReport, o: {
64
+ resourceIds?: ResourceId[];
65
+ }): Map<string | null, TotalsSum[]>;
66
+ export declare function periodLength(report: TotalsReport): {
67
+ ms: number;
68
+ days: number;
69
+ } | null;
70
+ export declare function hasEnough(line: {
71
+ quantity: Quantity;
72
+ available: Quantity;
73
+ }): boolean;
74
+ export declare function shortBy(line: {
75
+ quantity: Quantity;
76
+ available: Quantity;
77
+ }): Quantity;
78
+ type TakeBackOutcome = {
79
+ status: 'taken';
80
+ asked: Quantity;
81
+ taken: Quantity;
82
+ response: SupplyReverseResponse;
83
+ } | {
84
+ status: 'nothing_left';
85
+ } | {
86
+ status: 'failed';
87
+ error: ResourcesharkApiError;
88
+ };
89
+ /** Retries a short reversal with the quantity the service says is available. */
90
+ export declare function takeBackUpTo(client: ResourcesharkClient, supplyId: SupplyId, input: {
91
+ quantity: Quantity;
92
+ evidence: Evidence;
93
+ sourceKey: string;
94
+ idempotencyKey: string;
95
+ attempts?: number;
96
+ }): Promise<TakeBackOutcome>;
97
+ export declare function slotIn(slot: Slot, timeZone: string): {
98
+ date: string;
99
+ time: string;
100
+ offsetMinutes: number;
101
+ endDate: string;
102
+ endTime: string;
103
+ };
104
+ export declare function formatSlot(slot: Slot, o: {
105
+ timeZone: string;
106
+ locale?: string;
107
+ } & Intl.DateTimeFormatOptions): string;
108
+ export type { Cadence, Period, SupplyRule, TakeBackOutcome, TotalsSum };
@@ -0,0 +1,299 @@
1
+ import { n as ResourcesharkApiError } from "../client-D2ya4ahY.js";
2
+ import { i as shortLines } from "../refusals-D39vDFy2.js";
3
+ // src/helpers/zone.ts
4
+ function requireTimeZone(timeZone) {
5
+ if (typeof timeZone !== "string") throw new TypeError("timeZone is required");
6
+ return timeZone;
7
+ }
8
+ function wallClock(timeZone) {
9
+ return new Intl.DateTimeFormat("en-US", {
10
+ timeZone: requireTimeZone(timeZone),
11
+ calendar: "iso8601",
12
+ numberingSystem: "latn",
13
+ hourCycle: "h23",
14
+ era: "short",
15
+ year: "numeric",
16
+ month: "2-digit",
17
+ day: "2-digit",
18
+ hour: "2-digit",
19
+ minute: "2-digit",
20
+ second: "2-digit"
21
+ });
22
+ }
23
+ /** A local wall-clock reading stored as a UTC date for calendar arithmetic. */
24
+ function wallTime(formatter, instant) {
25
+ const parts = Object.fromEntries(formatter.formatToParts(instant).map(({ type, value }) => [type, value]));
26
+ const year = Number(parts.year);
27
+ const local = new Date(instant);
28
+ local.setUTCFullYear(parts.era === "BC" ? 1 - year : year, Number(parts.month) - 1, Number(parts.day));
29
+ local.setUTCHours(Number(parts.hour), Number(parts.minute), Number(parts.second));
30
+ return local;
31
+ }
32
+ function slotIn(slot, timeZone) {
33
+ const formatter = wallClock(timeZone);
34
+ const start = Date.parse(slot.start);
35
+ const localStart = wallTime(formatter, start);
36
+ const [date, time] = localStart.toISOString().split("T");
37
+ const [endDate, endTime] = wallTime(formatter, Date.parse(slot.end)).toISOString().split("T");
38
+ return {
39
+ date,
40
+ time: time.slice(0, 5),
41
+ offsetMinutes: (localStart.getTime() - start) / 6e4,
42
+ endDate,
43
+ endTime: endTime.slice(0, 5)
44
+ };
45
+ }
46
+ function formatSlot(slot, o) {
47
+ const { timeZone, locale, ...options } = o;
48
+ const format = Object.keys(options).length === 0 ? {
49
+ dateStyle: "medium",
50
+ timeStyle: "short"
51
+ } : options;
52
+ return new Intl.DateTimeFormat(locale, {
53
+ ...format,
54
+ timeZone: requireTimeZone(timeZone)
55
+ }).formatRange(new Date(slot.start), new Date(slot.end));
56
+ }
57
+ // src/helpers/supply-periods.ts
58
+ const DAY_MS = 864e5;
59
+ const DURATION_UNITS = {
60
+ ms: 1,
61
+ s: 1e3,
62
+ m: 6e4,
63
+ h: 36e5,
64
+ d: DAY_MS
65
+ };
66
+ const ANCHOR = /^(\d{4}-\d{2}-\d{2})(?:(T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)(Z|[+-]\d{2}:\d{2})?)?$/;
67
+ function elapsedMs(length) {
68
+ const match = /^(\d+)(ms|s|m|h|d)$/.exec(length);
69
+ const ms = match ? Number(match[1]) * DURATION_UNITS[match[2]] : NaN;
70
+ if (!Number.isSafeInteger(ms) || ms <= 0 || ms > 1e6 * DAY_MS) throw new RangeError("length must be a positive duration of at most 1000000d");
71
+ return ms;
72
+ }
73
+ /** Repeated times use the earlier instant. Skipped times move forward by the gap. */
74
+ function zonedInstant(formatter, local) {
75
+ const before = local - DAY_MS;
76
+ const after = local + DAY_MS;
77
+ const earlierOffset = wallTime(formatter, before).getTime() - before;
78
+ const laterOffset = wallTime(formatter, after).getTime() - after;
79
+ return [local - earlierOffset, local - laterOffset].sort((a, b) => a - b).find((candidate) => wallTime(formatter, candidate).getTime() === local) ?? local - earlierOffset;
80
+ }
81
+ function boundaryFor({ cadence, from }) {
82
+ const match = ANCHOR.exec(from);
83
+ if (!match) throw new RangeError("from must be an ISO date or timestamp");
84
+ const [, date, time, offset] = match;
85
+ const local = offset === void 0;
86
+ const wall = /* @__PURE__ */ new Date(`${date}${time ?? "T00:00"}Z`);
87
+ const start = local ? wall.getTime() : Date.parse(from);
88
+ if (!Number.isFinite(start) || !Number.isFinite(wall.getTime()) || wall.toISOString().slice(0, 10) !== date) throw new RangeError("from must be a valid date or timestamp");
89
+ if (cadence.every === "duration") {
90
+ if (local && time !== void 0) throw new RangeError("from must include an offset for an elapsed duration");
91
+ const ms = elapsedMs(cadence.length);
92
+ return (index) => start + index * ms;
93
+ }
94
+ if (!Number.isSafeInteger(cadence.count) || cadence.count < 1) throw new RangeError("cadence count must be a positive whole number");
95
+ if (cadence.every === "month" && cadence.dayOverflow !== "clamp" && cadence.dayOverflow !== "roll") throw new RangeError("dayOverflow must be clamp or roll");
96
+ const formatter = wallClock(cadence.timeZone);
97
+ const anchor = local ? wall : wallTime(formatter, start);
98
+ return (index) => {
99
+ if (index === 0 && !local) return start;
100
+ const date = new Date(anchor);
101
+ if (cadence.every === "day") date.setUTCDate(anchor.getUTCDate() + index * cadence.count);
102
+ else {
103
+ const month = anchor.getUTCMonth() + index * cadence.count;
104
+ if (cadence.dayOverflow === "clamp") {
105
+ const last = new Date(anchor);
106
+ last.setUTCMonth(month + 1, 0);
107
+ date.setUTCMonth(month, Math.min(anchor.getUTCDate(), last.getUTCDate()));
108
+ } else date.setUTCMonth(month);
109
+ }
110
+ return zonedInstant(formatter, date.getTime());
111
+ };
112
+ }
113
+ /**
114
+ * Creates half-open periods from the anchor. Calendar dates and times without
115
+ * offsets use the cadence's zone. An elapsed cadence starts at the given
116
+ * instant, with a date alone read as UTC midnight.
117
+ */
118
+ function supplyPeriods(rule) {
119
+ const { periods, resourceId, scope, quantity, kind, expires, drawOrder } = rule;
120
+ if (!Number.isInteger(periods) || periods < 1 || periods > 120) throw new RangeError("periods must be a whole number from 1 to 120");
121
+ if (typeof expires !== "boolean") throw new TypeError("expires must be true or false");
122
+ const boundary = boundaryFor(rule);
123
+ const sourceKeys = /* @__PURE__ */ new Set();
124
+ let start = boundary(0);
125
+ return Array.from({ length: periods }, (_, index) => {
126
+ const end = boundary(index + 1);
127
+ if (end <= start) throw new RangeError("each period must end after it starts");
128
+ const period = {
129
+ index,
130
+ start: new Date(start).toISOString(),
131
+ end: new Date(end).toISOString()
132
+ };
133
+ const sourceKey = rule.sourceKey(period);
134
+ const key = sourceKey.trim();
135
+ if (sourceKeys.has(key)) throw new RangeError("each period must have a unique sourceKey");
136
+ sourceKeys.add(key);
137
+ const attributes = rule.attributes?.(period);
138
+ const entry = {
139
+ resourceId,
140
+ scope,
141
+ quantity,
142
+ kind,
143
+ validFrom: period.start,
144
+ ...expires ? { expiresAt: period.end } : {},
145
+ ...drawOrder === void 0 ? {} : { drawOrder },
146
+ ...attributes === void 0 ? {} : { attributes },
147
+ evidence: rule.evidence(period),
148
+ sourceKey
149
+ };
150
+ start = end;
151
+ return {
152
+ period,
153
+ entry
154
+ };
155
+ });
156
+ }
157
+ /** Posts periods in order, stopping at the first failed write. */
158
+ async function postSupplyPeriods(client, entries, o) {
159
+ const responses = [];
160
+ for (const { entry } of entries) responses.push(await client.supply.create(entry, { idempotencyKey: o.idempotencyKey(entry) }));
161
+ return responses;
162
+ }
163
+ // src/helpers/enough.ts
164
+ /** Converts an integer result back to a wire quantity without rounding it. */
165
+ function asQuantity(value) {
166
+ const quantity = Number(value);
167
+ if (!Number.isSafeInteger(quantity)) throw new RangeError("quantity is outside the safe integer range");
168
+ return quantity;
169
+ }
170
+ function difference({ quantity, available }) {
171
+ if (!Number.isSafeInteger(quantity) || !Number.isSafeInteger(available)) throw new RangeError("quantity and available must be whole base units");
172
+ return BigInt(quantity) - BigInt(available);
173
+ }
174
+ function hasEnough(line) {
175
+ return difference(line) <= 0n;
176
+ }
177
+ function shortBy(line) {
178
+ const short = difference(line);
179
+ return short > 0n ? asQuantity(short) : 0;
180
+ }
181
+ // src/helpers/totals.ts
182
+ function sumUnit(rows, reasons) {
183
+ const resourceIds = [];
184
+ const bucketed = [];
185
+ const movements = /* @__PURE__ */ new Map();
186
+ let onHand = 0n;
187
+ let held = 0n;
188
+ let available = 0n;
189
+ for (const row of rows) {
190
+ resourceIds.push(row.resourceId);
191
+ if (row.balance === null) bucketed.push(row.resourceId);
192
+ else {
193
+ onHand += BigInt(row.balance.onHand);
194
+ held += BigInt(row.balance.held);
195
+ available += BigInt(row.balance.available);
196
+ }
197
+ for (const [reason, amount] of Object.entries(row.movements ?? {})) movements.set(reason, (movements.get(reason) ?? 0n) + BigInt(amount));
198
+ }
199
+ const result = {
200
+ unit: rows[0].unit,
201
+ resourceIds,
202
+ balance: bucketed.length === rows.length ? null : {
203
+ onHand: asQuantity(onHand),
204
+ held: asQuantity(held),
205
+ available: asQuantity(available)
206
+ },
207
+ movements: Object.fromEntries(Array.from(movements, ([reason, amount]) => [reason, asQuantity(amount)])),
208
+ bucketed
209
+ };
210
+ if (reasons !== void 0) {
211
+ let chosen = 0n;
212
+ for (const reason of reasons) chosen += movements.get(reason) ?? 0n;
213
+ result.chosen = asQuantity(chosen);
214
+ }
215
+ return result;
216
+ }
217
+ function sumRows(rows, reasons) {
218
+ const byUnit = /* @__PURE__ */ new Map();
219
+ for (const row of rows) {
220
+ const key = JSON.stringify([row.unit.code, row.unit.precision]);
221
+ const group = byUnit.get(key);
222
+ if (group) group.push(row);
223
+ else byUnit.set(key, [row]);
224
+ }
225
+ const chosen = reasons === void 0 ? void 0 : new Set(reasons);
226
+ return Array.from(byUnit.values(), (group) => sumUnit(group, chosen));
227
+ }
228
+ function selectedResources(report, resourceIds) {
229
+ if (resourceIds === void 0) return report.resources;
230
+ const ids = new Set(resourceIds);
231
+ return report.resources.filter(({ resourceId }) => ids.has(resourceId));
232
+ }
233
+ /** Sums each combination of unit code and precision independently. */
234
+ function sumTotals(report, o) {
235
+ return sumRows(selectedResources(report, o.resourceIds), o.reasons);
236
+ }
237
+ /** Sums the rows for each grouping value, including the unnamed group. */
238
+ function sumGroups(report, o) {
239
+ const groups = /* @__PURE__ */ new Map();
240
+ for (const { resourceId, unit, groups: resourceGroups } of selectedResources(report, o.resourceIds)) for (const { value, balance, movements } of resourceGroups ?? []) {
241
+ const row = {
242
+ resourceId,
243
+ unit,
244
+ balance,
245
+ movements
246
+ };
247
+ const group = groups.get(value);
248
+ if (group) group.push(row);
249
+ else groups.set(value, [row]);
250
+ }
251
+ return new Map(Array.from(groups, ([value, rows]) => [value, sumRows(rows)]));
252
+ }
253
+ function periodLength(report) {
254
+ const { from, to } = report;
255
+ if (from === void 0 || to === void 0) return null;
256
+ const ms = Date.parse(to) - Date.parse(from);
257
+ return {
258
+ ms,
259
+ days: ms / 864e5
260
+ };
261
+ }
262
+ // src/helpers/take-back.ts
263
+ /** Retries a short reversal with the quantity the service says is available. */
264
+ async function takeBackUpTo(client, supplyId, input) {
265
+ const { quantity: asked, evidence, sourceKey, idempotencyKey, attempts = 3 } = input;
266
+ if (!Number.isSafeInteger(attempts) || attempts < 1) throw new RangeError("attempts must be a positive whole number");
267
+ let quantity = asked;
268
+ for (let attempt = 0;; attempt += 1) try {
269
+ const response = await client.supply.reverse(supplyId, {
270
+ quantity,
271
+ evidence,
272
+ sourceKey
273
+ }, { idempotencyKey: attempt === 0 ? idempotencyKey : `${idempotencyKey}:${attempt}` });
274
+ return {
275
+ status: "taken",
276
+ asked,
277
+ taken: response.taken,
278
+ response
279
+ };
280
+ } catch (error) {
281
+ if (!(error instanceof ResourcesharkApiError)) throw error;
282
+ if (error.code !== "insufficient_supply") return {
283
+ status: "failed",
284
+ error
285
+ };
286
+ const available = shortLines(error)?.[0]?.available;
287
+ if (typeof available !== "number" || !Number.isSafeInteger(available) || available < 0 || available >= quantity) return {
288
+ status: "failed",
289
+ error
290
+ };
291
+ if (available === 0) return { status: "nothing_left" };
292
+ if (attempt + 1 >= attempts) return {
293
+ status: "failed",
294
+ error
295
+ };
296
+ quantity = available;
297
+ }
298
+ }
299
+ export { formatSlot, hasEnough, periodLength, postSupplyPeriods, shortBy, slotIn, sumGroups, sumTotals, supplyPeriods, takeBackUpTo };
@@ -0,0 +1,10 @@
1
+ import { $ as ExhaustedUntilSupplyDetails, $t as SchedulePut, A as ClaimResponse, At as MovementReason, B as ErrorClass, Bt as PlacesPage, C as BatchResponse, Cn as TransformationCreate, Ct as InstancePatch, D as Claim, Dt as InsufficientSupplyDetails, E as ChangeEvent, En as Unit, Et as InstancesQuery, F as ConsumeResponse, Ft as Place, G as ExceptionCreate, Gt as ResourceCreate, H as EventsPage, Ht as Quantity, I as CountCreate, It as PlaceCreate, J as ExceptionId, Jt as ResourceResponse, K as ExceptionCreateResponse, Kt as ResourceId, L as CountResponse, Lt as PlaceId, M as ClaimsQuery, Mt as MovementSums, N as ConfigResponse, Nt as MovementsPage, O as ClaimId, Ot as Movement, P as ConsumeRequest, Pt as MovementsQuery, Q as ExceptionsQuery, Qt as RetainedHold, R as Duration, Rt as PlacePatch, S as BatchPatch, Sn as TransferResponse, St as InstanceId, T as BatchesQuery, Tn as TransformationResponse, Tt as InstancesPage, U as EventsQuery, Ut as Ref, V as ErrorCode, Vt as PlacesQuery, W as Evidence, Wt as Resource, X as ExceptionResponse, Xt as ResourcesQuery, Y as ExceptionPatch, Yt as ResourcesPage, Z as ExceptionsList, Zt as ResourcesharkConfig, _ as BalanceQuery, _n as SupplyReverseResponse, _t as HolderBalancesQuery, a as ResourcesharkApiError, an as ShortLine, at as HoldCommit, b as BatchCreate, bn as TotalsReport, bt as Instance, c as WriteOptions, cn as SlotsResponse, ct as HoldExpiredDetails, d as AdjustmentCreate, dn as SupplyGetResponse, dt as HoldReschedule, en as ScheduleResponse, et as FiniteSpan, f as AdjustmentResponse, fn as SupplyId, ft as HoldRescheduleResponse, g as AvailabilityResponse, gn as SupplyReverse, gt as HolderBalancesPage, h as AvailabilityRequest, hn as SupplyResponse, ht as HolderBalanceResponse, i as ResourcesQueryInput, in as SettleResponse, it as HoldCancelResponse, j as ClaimsPage, jt as MovementResponse, k as ClaimLine, kt as MovementId, l as createClient, ln as SupplyCreateInput, lt as HoldExtend, m as Attributes, mn as SupplyQuery, mt as HoldResponse, n as ClientOptions, nn as Scope, nt as Hold, o as ResourcesharkClient, on as Slot, ot as HoldCommitResponse, p as AssignmentInfeasibleDetails, pn as SupplyPage, pt as HoldResolvedDetails, q as ExceptionDeleteResponse, qt as ResourcePatch, r as HOSTED_BASE_URL, rn as SettleRequest, rt as HoldCancel, s as VersionedOptions, sn as SlotsQuery, st as HoldCreate, t as CallOptions, tn as ScheduleSaveResponse, tt as FreeInstancesQuery, u as isErrorBody, un as SupplyEntry, ut as HoldId, v as BalanceResponse, vn as TotalsBalance, vt as HoldsPage, w as BatchesPage, wn as TransformationId, wt as InstanceResponse, x as BatchId, xn as TransferCreate, xt as InstanceCreate, y as Batch, yn as TotalsQuery, yt as HoldsQueryInput, z as ErrorBody, zt as PlaceResponse } from "./client-C-4s_6Qp.js";
2
+ /** The lines a refusal couldn't cover, short of supply or naming a unit that isn't free, as the service reported them. */
3
+ export declare function shortLines(e: unknown): ShortLine[] | undefined;
4
+ /** The earliest next supply time reported by an exhausted scope. */
5
+ export declare function nextSupplyAt(e: unknown): string | undefined;
6
+ /** The expiry and any availability details returned for a hold that ran out. */
7
+ export declare function expiredHold(e: unknown): HoldExpiredDetails | undefined;
8
+ /** The first outcome of a hold the service had already resolved. */
9
+ export declare function resolvedHold(e: unknown): HoldResolvedDetails | undefined;
10
+ export { type AdjustmentCreate, type AdjustmentResponse, type AssignmentInfeasibleDetails, type Attributes, type AvailabilityRequest, type AvailabilityResponse, type BalanceQuery, type BalanceResponse, type Batch, type BatchCreate, type BatchId, type BatchPatch, type BatchResponse, type BatchesPage, type BatchesQuery, type CallOptions, type ChangeEvent, type Claim, type ClaimId, type ClaimLine, type ClaimResponse, type ClaimsPage, type ClaimsQuery, type ClientOptions, type ConfigResponse, type ConsumeRequest, type ConsumeResponse, type CountCreate, type CountResponse, type Duration, type ErrorBody, type ErrorClass, type ErrorCode, type EventsPage, type EventsQuery, type Evidence, type ExceptionCreate, type ExceptionCreateResponse, type ExceptionDeleteResponse, type ExceptionId, type ExceptionPatch, type ExceptionResponse, type ExceptionsList, type ExceptionsQuery, type ExhaustedUntilSupplyDetails, type FiniteSpan, type FreeInstancesQuery, HOSTED_BASE_URL, type Hold, type HoldCancel, type HoldCancelResponse, type HoldCommit, type HoldCommitResponse, type HoldCreate, type HoldExpiredDetails, type HoldExtend, type HoldId, type HoldReschedule, type HoldRescheduleResponse, type HoldResolvedDetails, type HoldResponse, type HolderBalanceResponse, type HolderBalancesPage, type HolderBalancesQuery, type HoldsPage, type HoldsQueryInput, type Instance, type InstanceCreate, type InstanceId, type InstancePatch, type InstanceResponse, type InstancesPage, type InstancesQuery, type InsufficientSupplyDetails, type Movement, type MovementId, type MovementReason, type MovementResponse, type MovementSums, type MovementsPage, type MovementsQuery, type Place, type PlaceCreate, type PlaceId, type PlacePatch, type PlaceResponse, type PlacesPage, type PlacesQuery, type Quantity, type Ref, type Resource, type ResourceCreate, type ResourceId, type ResourcePatch, type ResourceResponse, type ResourcesPage, type ResourcesQuery, type ResourcesQueryInput, ResourcesharkApiError, type ResourcesharkClient, type ResourcesharkConfig, type RetainedHold, type SchedulePut, type ScheduleResponse, type ScheduleSaveResponse, type Scope, type SettleRequest, type SettleResponse, type ShortLine, type Slot, type SlotsQuery, type SlotsResponse, type SupplyCreateInput, type SupplyEntry, type SupplyGetResponse, type SupplyId, type SupplyPage, type SupplyQuery, type SupplyResponse, type SupplyReverse, type SupplyReverseResponse, type TotalsBalance, type TotalsQuery, type TotalsReport, type TransferCreate, type TransferResponse, type TransformationCreate, type TransformationId, type TransformationResponse, type Unit, type VersionedOptions, type WriteOptions, createClient, isErrorBody };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { i as isErrorBody, n as ResourcesharkApiError, r as createClient, t as HOSTED_BASE_URL } from "./client-D2ya4ahY.js";
2
+ import { i as shortLines, n as nextSupplyAt, r as resolvedHold, t as expiredHold } from "./refusals-D39vDFy2.js";
3
+ export { HOSTED_BASE_URL, ResourcesharkApiError, createClient, expiredHold, isErrorBody, nextSupplyAt, resolvedHold, shortLines };
@@ -0,0 +1,27 @@
1
+ import { a as readError, n as ResourcesharkApiError } from "./client-D2ya4ahY.js";
2
+ // src/refusals.ts
3
+ function refusalDetails(value, ...codes) {
4
+ const error = value instanceof ResourcesharkApiError ? value : readError(value);
5
+ return error && codes.some((code) => code === error.code) ? error.details : void 0;
6
+ }
7
+ /** The lines a refusal couldn't cover, short of supply or naming a unit that isn't free, as the service reported them. */
8
+ function shortLines(e) {
9
+ const details = refusalDetails(e, "insufficient_supply", "exhausted_until_supply", "assignment_infeasible");
10
+ return Array.isArray(details?.lines) ? details.lines : void 0;
11
+ }
12
+ /** The earliest next supply time reported by an exhausted scope. */
13
+ function nextSupplyAt(e) {
14
+ const details = refusalDetails(e, "exhausted_until_supply");
15
+ return typeof details?.nextSupplyAt === "string" ? details.nextSupplyAt : void 0;
16
+ }
17
+ /** The expiry and any availability details returned for a hold that ran out. */
18
+ function expiredHold(e) {
19
+ const details = refusalDetails(e, "hold_expired");
20
+ return typeof details?.holdId === "string" && typeof details.expiresAt === "string" ? details : void 0;
21
+ }
22
+ /** The first outcome of a hold the service had already resolved. */
23
+ function resolvedHold(e) {
24
+ const details = refusalDetails(e, "hold_resolved");
25
+ return typeof details?.holdId === "string" && typeof details.status === "string" && typeof details.resolution?.at === "string" ? details : void 0;
26
+ }
27
+ export { shortLines as i, nextSupplyAt as n, resolvedHold as r, expiredHold as t };