@mark1russell7/market 0.1.3 → 0.1.5

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/build/index.js CHANGED
@@ -1,346 +1,7 @@
1
- import { UnitError, add, compare, convert, convertible, kindOf, scale, valueIn } from "@mark1russell7/quantity";
1
+ import { C as costOf, D as gtinCheckDigit, E as matchKeys, O as parseGtin, S as offersPart, T as foldCode, _ as specSchema, a as instantSchema, b as latestObservations, c as offerSchema, d as priceReadingSchema, f as productSchema, g as sourceSchema, h as sourceOfOffer, i as gtinSchema, l as partNumberSchema, m as shippingSchema, n as CONDITIONS, o as moneySchema, p as sellerSchema, r as FORMATS, s as offerId, t as AVAILABILITIES, u as priceBreakSchema, v as textSchema, w as unitPriceFor, x as offersOfPart, y as bestOffer } from "./records-hK1UCmpm.js";
2
+ import { UnitError, canonicalUnit, convertExact, convertible, parseUnit, quantity, rationals, valueIn } from "@mark1russell7/quantity";
2
3
  import { quantitySchema } from "@mark1russell7/quantity/schema";
3
4
  import { z } from "zod";
4
- // src/gtin.ts
5
- /**
6
- * This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.
7
- * The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.
8
- */
9
- const LENGTHS = /* @__PURE__ */ new Set([
10
- 8,
11
- 12,
12
- 13,
13
- 14
14
- ]);
15
- /**
16
- * This function gives the check digit of the digits of a GTIN without its last digit.
17
- *
18
- * @throws RangeError when the text has a character that is not a digit, or no character.
19
- */
20
- function gtinCheckDigit(body) {
21
- if (!/^\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);
22
- let total = 0;
23
- for (let i = 0; i < body.length; i += 1) {
24
- const digit = body.charCodeAt(body.length - 1 - i) - 48;
25
- total += i % 2 === 0 ? digit * 3 : digit;
26
- }
27
- return (10 - total % 10) % 10;
28
- }
29
- /**
30
- * This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.
31
- * It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.
32
- */
33
- function parseGtin(text) {
34
- const digits = text.replace(/[\s-]/g, "");
35
- if (!/^\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;
36
- if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;
37
- return digits.padStart(14, "0");
38
- }
39
- // src/identifiers.ts
40
- /**
41
- * This function folds a brand or a part number for a comparison. The result has only capital letters A to Z
42
- * and digits. Thus `MZ-V8V1T0B/AM` and `mzv8v1t0bam` fold to one text.
43
- */
44
- function foldCode(text) {
45
- return text.normalize("NFKD").toUpperCase().replace(/[^A-Z0-9]/g, "");
46
- }
47
- /**
48
- * This function gives the match keys of a record, sorted and with no copy. A key is `gtin:` with the GTIN-14,
49
- * or `part:` with the folded brand and part number. Two records with a key in common name one product.
50
- * The function ignores a GTIN that is not valid, and a part number whose brand or number folds to no text.
51
- */
52
- function matchKeys(identifiers) {
53
- const keys = /* @__PURE__ */ new Set();
54
- for (const text of identifiers.gtins) {
55
- const gtin = parseGtin(text);
56
- if (gtin !== null) keys.add(`gtin:${gtin}`);
57
- }
58
- for (const { brand, partNumber } of identifiers.partNumbers) {
59
- const folded = [foldCode(brand), foldCode(partNumber)];
60
- if (folded.every((part) => part !== "")) keys.add(`part:${folded.join("/")}`);
61
- }
62
- return [...keys].sort();
63
- }
64
- // src/price.ts
65
- /**
66
- * This function gives the unit price for an order of `count` units. The price of the largest break at or
67
- * below the count applies, or the price of the reading when no break applies.
68
- *
69
- * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
70
- */
71
- function unitPriceFor(reading, count) {
72
- const minimum = reading.minimumQuantity ?? 1;
73
- if (!Number.isSafeInteger(count) || count < minimum) throw new RangeError(`The count ${count} is not a whole number of ${minimum} or more.`);
74
- let price = reading.price;
75
- for (const entry of reading.priceBreaks ?? []) if (entry.quantity <= count) price = entry.unitPrice;
76
- return price;
77
- }
78
- /**
79
- * This function gives the cost of an order of `count` units with its shipping, or null when the shipping
80
- * cost is not known. The cost is exact, and the function does not round it to the cent.
81
- *
82
- * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
83
- */
84
- function costOf(reading, count) {
85
- const goods = scale(unitPriceFor(reading, count), count);
86
- switch (reading.shipping.kind) {
87
- case "free": return goods;
88
- case "fixed": return add(goods, reading.shipping.cost);
89
- default: return null;
90
- }
91
- }
92
- // src/offers.ts
93
- /**
94
- * This function tells if an offer is an offer of the part. One part number of the offer must have a brand of the
95
- * want and start with a part number of the want. `foldCode` folds each text before the comparison. A part number
96
- * of another maker does not match: many makers use short numbers like `A1383`.
97
- */
98
- function offersPart(offer, want) {
99
- const brands = new Set(want.brands.map(foldCode).filter((brand) => brand !== ""));
100
- const parts = want.partNumbers.map(foldCode).filter((part) => part !== "");
101
- return offer.partNumbers.some(({ brand, partNumber }) => {
102
- const folded = foldCode(partNumber);
103
- return brands.has(foldCode(brand)) && parts.some((part) => folded.startsWith(part));
104
- });
105
- }
106
- /**
107
- * This function gives the latest observation of each offer, in the order of the offer ids. When two readings of
108
- * one offer have the same instant, the later one in the list applies.
109
- */
110
- function latestObservations(observations) {
111
- const latest = /* @__PURE__ */ new Map();
112
- for (const each of observations) {
113
- const seen = latest.get(each.offer.id);
114
- if (seen === void 0 || Date.parse(seen.reading.at) <= Date.parse(each.reading.at)) latest.set(each.offer.id, each);
115
- }
116
- return [...latest.values()].sort((a, b) => order(a.offer.id, b.offer.id));
117
- }
118
- /** This function gives the latest observation of each offer of the part, in the order of the offer ids. */
119
- function offersOfPart(observations, want) {
120
- return latestObservations(observations.filter((each) => offersPart(each.offer, want)));
121
- }
122
- /**
123
- * This function chooses the offer to buy from the latest observation of each offer. It skips an offer with a
124
- * condition that the buyer does not accept, a price in another currency, or a minimum above the count.
125
- *
126
- * @throws RangeError when the count is not a whole number of 1 or more, or when the currency is not a unit of money.
127
- */
128
- function bestOffer(observations, options) {
129
- const { currency, count = 1, conditions = ["new"] } = options;
130
- if (!Number.isSafeInteger(count) || count < 1) throw new RangeError(`The count ${count} is not a whole number of 1 or more.`);
131
- if (!isMoney(currency)) throw new RangeError(`The currency ${currency} is not a unit of money of @mark1russell7/quantity.`);
132
- const accepted = new Set(conditions);
133
- const offers = [];
134
- const skipped = [];
135
- for (const observation of latestObservations(observations)) {
136
- const { offer, reading } = observation;
137
- const minimum = reading.minimumQuantity ?? 1;
138
- if (!accepted.has(offer.condition)) skipped.push({
139
- offerId: offer.id,
140
- why: `The condition ${offer.condition} is not a condition that the buyer accepts.`
141
- });
142
- else if (!converts(reading.price.unit, currency)) skipped.push({
143
- offerId: offer.id,
144
- why: `The price is in ${reading.price.unit}, not in ${currency}.`
145
- });
146
- else if (count < minimum) skipped.push({
147
- offerId: offer.id,
148
- why: `The minimum order is ${minimum} units, more than the count ${count}.`
149
- });
150
- else {
151
- const goods = convert(scale(unitPriceFor(reading, count), count), currency);
152
- const total = reading.shipping.kind !== "fixed" || converts(reading.shipping.cost.unit, currency) ? costOf(reading, count) : null;
153
- const cost = total === null ? null : convert(total, currency);
154
- const inStock = reading.availability === "in-stock" || reading.availability === "low-stock";
155
- offers.push({
156
- observation,
157
- goods,
158
- cost,
159
- inStock
160
- });
161
- }
162
- }
163
- offers.sort((a, b) => compare(a.goods, b.goods) || byCost(a.cost, b.cost) || order(a.observation.offer.id, b.observation.offer.id));
164
- return {
165
- best: offers.find((choice) => choice.inStock) ?? offers[0] ?? null,
166
- offers,
167
- skipped
168
- };
169
- }
170
- /** This function tells if a unit is a unit of money that the quantity package knows. */
171
- function isMoney(unit) {
172
- try {
173
- return kindOf(unit) === "money";
174
- } catch (error) {
175
- if (error instanceof UnitError) return false;
176
- throw error;
177
- }
178
- }
179
- /** This function tells if an amount in one unit converts to another unit. A unit that the quantity package does not know does not convert. */
180
- function converts(from, to) {
181
- try {
182
- return convertible(from, to);
183
- } catch (error) {
184
- if (error instanceof UnitError) return false;
185
- throw error;
186
- }
187
- }
188
- /** This function orders two costs. A known cost comes before a cost that is not known. */
189
- function byCost(a, b) {
190
- if (a === null || b === null) return a === b ? 0 : a === null ? 1 : -1;
191
- return compare(a, b);
192
- }
193
- /** This function orders two texts by their code units, so the order does not depend on the locale. */
194
- function order(a, b) {
195
- return a < b ? -1 : a > b ? 1 : 0;
196
- }
197
- // src/records.ts
198
- /**
199
- * The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
200
- * the field `grade` of the offer.
201
- */
202
- const CONDITIONS = [
203
- "new",
204
- "open-box",
205
- "refurbished",
206
- "used",
207
- "for-parts",
208
- "unknown"
209
- ];
210
- /** The states of the stock of an offer at the time of a reading. */
211
- const AVAILABILITIES = [
212
- "in-stock",
213
- "low-stock",
214
- "out-of-stock",
215
- "preorder",
216
- "unknown"
217
- ];
218
- /** The buying formats of an offer. In an auction, the price of a reading is the current bid. */
219
- const FORMATS = ["fixed-price", "auction"];
220
- /** This schema accepts a text with a character that is not a space, and with no space at an end. */
221
- const textSchema = z.string().refine((text) => text !== "" && text === text.trim(), "The text is empty, or it has a space at an end.");
222
- /** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */
223
- const sourceSchema = z.string().regex(/^[a-z][a-z0-9-]*$/, "The name of a source has small letters, digits and hyphens, with a letter first.");
224
- /** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */
225
- const gtinSchema = z.string().refine((text) => /^\d{14}$/.test(text) && parseGtin(text) === text, "The GTIN is not a GTIN-14 with a correct check digit.");
226
- /** This schema accepts an amount of money of zero or more, for example `{ "value": 129.99, "unit": "USD" }`. */
227
- const moneySchema = quantitySchema("money", { nonnegative: true });
228
- /** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */
229
- const instantSchema = z.iso.datetime();
230
- /** This schema accepts a part number of a maker. */
231
- const partNumberSchema = z.strictObject({
232
- brand: textSchema,
233
- partNumber: textSchema
234
- });
235
- /** This schema accepts one specification as text, for example `{ "name": "Capacity", "value": "1 TB" }`. */
236
- const specSchema = z.strictObject({
237
- name: textSchema,
238
- value: textSchema
239
- });
240
- /** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */
241
- const sellerSchema = z.strictObject({
242
- id: textSchema.optional(),
243
- name: textSchema.optional(),
244
- rating: z.strictObject({
245
- percent: z.number().min(0).max(100),
246
- count: z.int().nonnegative()
247
- }).optional()
248
- });
249
- /** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */
250
- const productSchema = z.strictObject({
251
- id: textSchema,
252
- title: textSchema,
253
- brand: textSchema.optional(),
254
- category: z.array(textSchema).optional(),
255
- gtins: z.array(gtinSchema),
256
- partNumbers: z.array(partNumberSchema),
257
- specs: z.array(specSchema)
258
- });
259
- /** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */
260
- function offerId(source, sourceId) {
261
- return `${source}:${sourceId}`;
262
- }
263
- /** This function gives the name of the source of an offer id: the text before the first colon. */
264
- function sourceOfOffer(id) {
265
- const colon = id.indexOf(":");
266
- if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);
267
- return id.slice(0, colon);
268
- }
269
- /**
270
- * This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.
271
- * `productId` names the product of the catalog after a match.
272
- */
273
- const offerSchema = z.strictObject({
274
- id: textSchema,
275
- source: sourceSchema,
276
- sourceId: textSchema,
277
- productId: textSchema.optional(),
278
- title: textSchema,
279
- url: z.url({ protocol: /^https$/ }).optional(),
280
- seller: sellerSchema,
281
- condition: z.enum(CONDITIONS),
282
- grade: textSchema.optional(),
283
- format: z.enum(FORMATS),
284
- endsAt: instantSchema.optional(),
285
- gtins: z.array(gtinSchema),
286
- partNumbers: z.array(partNumberSchema),
287
- specs: z.array(specSchema)
288
- }).refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {
289
- message: "The id of an offer is its source and its source id, with a colon between them.",
290
- path: ["id"]
291
- });
292
- /** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */
293
- const shippingSchema = z.discriminatedUnion("kind", [
294
- z.strictObject({ kind: z.literal("free") }),
295
- z.strictObject({
296
- kind: z.literal("fixed"),
297
- cost: moneySchema
298
- }),
299
- z.strictObject({ kind: z.literal("calculated") }),
300
- z.strictObject({ kind: z.literal("unknown") })
301
- ]);
302
- /** This schema accepts a price break: the unit price for an order of `quantity` units or more. */
303
- const priceBreakSchema = z.strictObject({
304
- quantity: z.int().min(2),
305
- unitPrice: moneySchema
306
- });
307
- /**
308
- * This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an
309
- * order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more
310
- * than the minimum.
311
- */
312
- const priceReadingSchema = z.strictObject({
313
- offerId: textSchema,
314
- at: instantSchema,
315
- price: moneySchema,
316
- listPrice: moneySchema.optional(),
317
- shipping: shippingSchema,
318
- availability: z.enum(AVAILABILITIES),
319
- available: z.int().nonnegative().optional(),
320
- minimumQuantity: z.int().min(1).optional(),
321
- priceBreaks: z.array(priceBreakSchema).optional()
322
- }).superRefine((reading, context) => {
323
- let last = reading.minimumQuantity ?? 1;
324
- for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {
325
- if (entry.quantity <= last) context.addIssue({
326
- code: "custom",
327
- message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,
328
- path: [
329
- "priceBreaks",
330
- index,
331
- "quantity"
332
- ]
333
- });
334
- last = Math.max(last, entry.quantity);
335
- }
336
- const { availability, available } = reading;
337
- if (available === void 0 || availability === "unknown" || availability === "preorder") return;
338
- if (availability === "out-of-stock" !== (available === 0)) context.addIssue({
339
- code: "custom",
340
- message: `The availability ${availability} does not agree with the count ${available}.`,
341
- path: ["available"]
342
- });
343
- });
344
5
  // src/terms.ts
345
6
  /**
346
7
  * This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the
@@ -623,6 +284,351 @@ function planReads(entries, last, now, options) {
623
284
  next: Number.isFinite(next) ? new Date(next).toISOString() : null
624
285
  };
625
286
  }
626
- export { AVAILABILITIES, BOARD_FORMAT, CONDITIONS, FORMATS, bestOffer, boardObservations, boardReadSchema, boardSchema, costOf, foldCode, gtinCheckDigit, gtinSchema, instantSchema, isKept, keepObservations, keepUntil, lastReads, latestObservations, matchKeys, moneySchema, observationSchema, offerId, offerSchema, offersOfPart, offersPart, parseGtin, partNumberSchema, permitsHistory, permitsTrend, planReads, priceBreakSchema, priceReadingSchema, productSchema, readInterval, retentionSchema, sellerSchema, settleBoard, shippingSchema, sourceOfOffer, sourceSchema, sourceTermsSchema, specSchema, textSchema, unitPriceFor, watchEntrySchema, watchProblems };
287
+ // src/metered.ts
288
+ /**
289
+ * The kinds of a metered amount: a time (the hours of a machine), data times time (stored data), data (a transfer)
290
+ * and a count (requests).
291
+ */
292
+ const METERED_KINDS = [
293
+ "time",
294
+ "data-time",
295
+ "data",
296
+ "count"
297
+ ];
298
+ /**
299
+ * The scopes of a free amount. With `account`, all the usage of the account in all regions shares one free amount.
300
+ * With `region`, each region has its own free amount. With `resource`, each resource has its own free amount.
301
+ */
302
+ const FREE_SCOPES = [
303
+ "account",
304
+ "region",
305
+ "resource"
306
+ ];
307
+ /** This function gives the kind of a metered amount from the exponents of its data and its time, or undefined. */
308
+ function kindOfExponents(data, time) {
309
+ if (data === 0 && time === 0) return "count";
310
+ if (data === 0 && time === 1) return "time";
311
+ if (data === 1 && time === 0) return "data";
312
+ if (data === 1 && time === 1) return "data-time";
313
+ }
314
+ /** This function reads the unit of a metered price. It gives the parts of the unit, or the problem as a text. */
315
+ function readPriceUnit(unit) {
316
+ const refused = `The unit ${unit} is not a price for each unit of a metered amount, for example USD/h.`;
317
+ let parsed;
318
+ try {
319
+ parsed = parseUnit(unit);
320
+ } catch (error) {
321
+ if (error instanceof UnitError) return refused;
322
+ throw error;
323
+ }
324
+ const above = parsed.components.filter((component) => component.exponent > 0);
325
+ const [money] = above;
326
+ const atom = money?.atom;
327
+ const isMoney = atom !== void 0 && Object.keys(atom.vector).length === 1 && atom.vector.money === 1;
328
+ const below = parsed.components.some((component) => component.exponent < 0);
329
+ if (above.length !== 1 || money?.exponent !== 1 || money.annotation !== void 0 || !isMoney || !below) return refused;
330
+ const { money: units = 0, data = 0, time = 0, ...others } = parsed.vector;
331
+ const kind = Object.values(others).every((exponent) => exponent === 0) && units === 1 ? kindOfExponents(-data, -time) : void 0;
332
+ return kind === void 0 ? refused : {
333
+ money: atom.symbol,
334
+ kind
335
+ };
336
+ }
337
+ /** This function gives the unit of a price for each unit of an amount, for example `USD/(GiB·mo)` for `GiB·mo`. */
338
+ function priceUnitFor(money, amountUnit) {
339
+ try {
340
+ return canonicalUnit(`${money}/${amountUnit}`);
341
+ } catch (error) {
342
+ if (error instanceof UnitError) return void 0;
343
+ throw error;
344
+ }
345
+ }
346
+ /** This function tells if an amount in one unit converts to another unit. A unit that the quantity package does not know does not convert. */
347
+ function converts(from, to) {
348
+ try {
349
+ return convertible(from, to);
350
+ } catch (error) {
351
+ if (error instanceof UnitError) return false;
352
+ throw error;
353
+ }
354
+ }
355
+ /** This function gives the start of each tier in one unit, or undefined when a start does not convert to it. */
356
+ function startsOf(tiers, unit) {
357
+ try {
358
+ return tiers.map((tier) => convertExact(rationals.fromNumber(tier.from.value), tier.from.unit, unit));
359
+ } catch (error) {
360
+ if (error instanceof UnitError || error instanceof RangeError) return void 0;
361
+ throw error;
362
+ }
363
+ }
364
+ /** This function tells if a unit of an amount measures the metered amount of a unit of price. */
365
+ function measures(amountUnit, priceUnit, money) {
366
+ const unit = priceUnitFor(money, amountUnit);
367
+ return unit !== void 0 && converts(unit, priceUnit);
368
+ }
369
+ /**
370
+ * This function gives the kind of the metered amount of the unit of a metered price, for example `time` for `USD/h`
371
+ * and `data-time` for `USD/(GiB·mo)`.
372
+ *
373
+ * @throws RangeError when the unit is not a price for each unit of a metered amount.
374
+ */
375
+ function meteredKindOf(unit) {
376
+ const parts = readPriceUnit(unit);
377
+ if (typeof parts === "string") throw new RangeError(parts);
378
+ return parts.kind;
379
+ }
380
+ /**
381
+ * This schema accepts the location of a metered offer. The name of the provider has small letters, digits and
382
+ * hyphens, as the name of a source. The region and the zone are the ids of the provider.
383
+ */
384
+ const locationSchema = z.strictObject({
385
+ provider: sourceSchema,
386
+ region: textSchema,
387
+ zone: textSchema.optional()
388
+ });
389
+ /**
390
+ * This schema accepts the term of a metered price. A `spot` term can have the notice before the provider ends the
391
+ * use. A `committed` term has its length.
392
+ */
393
+ const priceTermSchema = z.discriminatedUnion("kind", [
394
+ z.strictObject({ kind: z.literal("on-demand") }),
395
+ z.strictObject({
396
+ kind: z.literal("spot"),
397
+ notice: quantitySchema("time", { nonnegative: true }).optional()
398
+ }),
399
+ z.strictObject({
400
+ kind: z.literal("committed"),
401
+ length: quantitySchema("time", { positive: true })
402
+ })
403
+ ]);
404
+ /**
405
+ * This schema accepts a metered offer: one resource of a provider in one location, on one term. The id is the
406
+ * source and the source id, with a colon between them.
407
+ */
408
+ const meteredOfferSchema = z.strictObject({
409
+ id: textSchema,
410
+ source: sourceSchema,
411
+ sourceId: textSchema,
412
+ productId: textSchema.optional(),
413
+ title: textSchema,
414
+ url: z.url({ protocol: /^https$/ }).optional(),
415
+ location: locationSchema,
416
+ term: priceTermSchema,
417
+ specs: z.array(specSchema)
418
+ }).refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {
419
+ message: "The id of an offer is its source and its source id, with a colon between them.",
420
+ path: ["id"]
421
+ });
422
+ /**
423
+ * This schema accepts a metered price of zero or more: an amount of money for each unit of a metered amount, for
424
+ * example `{ "value": 0.0116, "unit": "USD/h" }`.
425
+ */
426
+ const meteredPriceSchema = quantitySchema(void 0, { nonnegative: true }).superRefine((price, context) => {
427
+ const parts = readPriceUnit(price.unit);
428
+ if (typeof parts === "string") context.addIssue({
429
+ code: "custom",
430
+ message: parts
431
+ });
432
+ });
433
+ /** This schema accepts a tier: the start of its usage, and its price for each unit. The start measures the metered amount of the price. */
434
+ const tierSchema = z.strictObject({
435
+ from: quantitySchema(void 0, { nonnegative: true }),
436
+ unitPrice: meteredPriceSchema
437
+ }).superRefine((tier, context) => {
438
+ const parts = readPriceUnit(tier.unitPrice.unit);
439
+ if (typeof parts === "string" || measures(tier.from.unit, tier.unitPrice.unit, parts.money)) return;
440
+ context.addIssue({
441
+ code: "custom",
442
+ message: `The start ${tier.from.unit} does not measure the metered amount of the price ${tier.unitPrice.unit}.`,
443
+ path: ["from"]
444
+ });
445
+ });
446
+ /** This schema accepts a free amount of more than zero for each period, and its scope. */
447
+ const freeAmountSchema = z.strictObject({
448
+ amount: quantitySchema(void 0, { positive: true }),
449
+ scope: z.enum(FREE_SCOPES)
450
+ });
451
+ /**
452
+ * This schema accepts a meter. The first tier starts at zero, and the starts increase. The prices of the tiers and
453
+ * the free amount measure one metered amount.
454
+ */
455
+ const meterSchema = z.strictObject({
456
+ name: textSchema,
457
+ tiers: z.array(tierSchema).min(1),
458
+ free: freeAmountSchema.optional()
459
+ }).superRefine((meter, context) => {
460
+ const [first] = meter.tiers;
461
+ if (first === void 0) return;
462
+ const parts = readPriceUnit(first.unitPrice.unit);
463
+ if (typeof parts === "string") return;
464
+ let units = true;
465
+ for (const [index, tier] of meter.tiers.entries()) {
466
+ if (converts(tier.unitPrice.unit, first.unitPrice.unit) && measures(tier.from.unit, first.unitPrice.unit, parts.money)) continue;
467
+ units = false;
468
+ context.addIssue({
469
+ code: "custom",
470
+ message: `The tier ${index} does not measure the metered amount of the price ${first.unitPrice.unit}.`,
471
+ path: ["tiers", index]
472
+ });
473
+ }
474
+ if (meter.free !== void 0 && !measures(meter.free.amount.unit, first.unitPrice.unit, parts.money)) context.addIssue({
475
+ code: "custom",
476
+ message: `The free amount ${meter.free.amount.unit} does not measure the metered amount of the price ${first.unitPrice.unit}.`,
477
+ path: ["free", "amount"]
478
+ });
479
+ if (!units) return;
480
+ const starts = startsOf(meter.tiers, first.from.unit);
481
+ if (starts === void 0) return;
482
+ if (rationals.sign(starts[0] ?? rationals.ZERO) !== 0) context.addIssue({
483
+ code: "custom",
484
+ message: "The first tier does not start at zero.",
485
+ path: [
486
+ "tiers",
487
+ 0,
488
+ "from"
489
+ ]
490
+ });
491
+ for (let index = 1; index < starts.length; index += 1) {
492
+ if (rationals.cmp(starts[index] ?? rationals.ZERO, starts[index - 1] ?? rationals.ZERO) > 0) continue;
493
+ context.addIssue({
494
+ code: "custom",
495
+ message: `The tier ${index} does not start after the tier ${index - 1}.`,
496
+ path: [
497
+ "tiers",
498
+ index,
499
+ "from"
500
+ ]
501
+ });
502
+ }
503
+ });
504
+ /**
505
+ * This schema accepts a metered reading: the metered prices of one offer at one instant. The tiers and the free
506
+ * amounts count the usage of one `period`. Each meter has its own name.
507
+ */
508
+ const meteredReadingSchema = z.strictObject({
509
+ offerId: textSchema,
510
+ at: instantSchema,
511
+ period: quantitySchema("time", { positive: true }),
512
+ meters: z.array(meterSchema).min(1),
513
+ upfront: moneySchema.optional()
514
+ }).refine((reading) => new Set(reading.meters.map((meter) => meter.name)).size === reading.meters.length, {
515
+ message: "The reading has two meters with one name.",
516
+ path: ["meters"]
517
+ });
518
+ /** This schema accepts a metered observation: an offer, and a reading of that offer. Only a committed term has upfront money. */
519
+ const meteredObservationSchema = z.strictObject({
520
+ offer: meteredOfferSchema,
521
+ reading: meteredReadingSchema
522
+ }).superRefine((each, context) => {
523
+ if (each.reading.offerId !== each.offer.id) context.addIssue({
524
+ code: "custom",
525
+ message: "The reading is not a reading of the offer.",
526
+ path: ["reading", "offerId"]
527
+ });
528
+ if (each.reading.upfront !== void 0 && each.offer.term.kind !== "committed") context.addIssue({
529
+ code: "custom",
530
+ message: `The term ${each.offer.term.kind} has no upfront money.`,
531
+ path: ["reading", "upfront"]
532
+ });
533
+ });
534
+ /** This function gives the value of an amount in a unit, as an exact rational. */
535
+ function exactIn(amount, unit) {
536
+ return convertExact(rationals.fromNumber(amount.value), amount.unit, unit);
537
+ }
538
+ /** This function gives the larger of two rationals. */
539
+ function larger(a, b) {
540
+ return rationals.cmp(a, b) >= 0 ? a : b;
541
+ }
542
+ /** This function gives the smaller of two rationals. */
543
+ function smaller(a, b) {
544
+ return rationals.cmp(a, b) <= 0 ? a : b;
545
+ }
546
+ /** This function examines an amount of usage of a meter, and gives its value in its own unit. */
547
+ function usageValue(meter, amount, priceUnit, money, what) {
548
+ if (!Number.isFinite(amount.value) || amount.value < 0) throw new RangeError(`The ${what} of the meter ${meter.name} is ${amount.value}, not an amount of zero or more.`);
549
+ if (!measures(amount.unit, priceUnit, money)) throw new RangeError(`The ${what} of the meter ${meter.name} is in ${amount.unit}, which does not measure the price ${priceUnit}.`);
550
+ return rationals.fromNumber(amount.value);
551
+ }
552
+ /**
553
+ * This function gives the exact cost of the usage of one meter, in the unit of money of its first tier. The free
554
+ * amount comes off the usage first. The tiers then count the rest of the usage from zero.
555
+ */
556
+ function costOfMeter(meter, used, freeUsed) {
557
+ const [first] = meter.tiers;
558
+ if (first === void 0) throw new RangeError(`The meter ${meter.name} has no tier.`);
559
+ const parts = readPriceUnit(first.unitPrice.unit);
560
+ if (typeof parts === "string") throw new RangeError(parts);
561
+ const { money } = parts;
562
+ if (used === void 0) return {
563
+ money,
564
+ cost: rationals.ZERO
565
+ };
566
+ const amount = usageValue(meter, used, first.unitPrice.unit, money, "usage");
567
+ const unit = used.unit;
568
+ const perUnit = priceUnitFor(money, unit);
569
+ if (perUnit === void 0) throw new RangeError(`The usage of the meter ${meter.name} is in ${unit}, which has no price unit.`);
570
+ let free = rationals.ZERO;
571
+ if (meter.free !== void 0) free = exactIn(meter.free.amount, unit);
572
+ if (freeUsed !== void 0) {
573
+ usageValue(meter, freeUsed, first.unitPrice.unit, money, "used free amount");
574
+ free = larger(rationals.ZERO, rationals.sub(free, exactIn(freeUsed, unit)));
575
+ }
576
+ const billed = larger(rationals.ZERO, rationals.sub(amount, free));
577
+ let cost = rationals.ZERO;
578
+ for (const [index, tier] of meter.tiers.entries()) {
579
+ const start = exactIn(tier.from, unit);
580
+ const next = meter.tiers[index + 1];
581
+ const end = next === void 0 ? billed : smaller(billed, exactIn(next.from, unit));
582
+ if (rationals.cmp(end, start) <= 0) continue;
583
+ cost = rationals.add(cost, rationals.mul(rationals.sub(end, start), exactIn(tier.unitPrice, perUnit)));
584
+ }
585
+ return {
586
+ money,
587
+ cost
588
+ };
589
+ }
590
+ /**
591
+ * This function gives the cost of a metered offer for one period, from the usage of each meter in that period. A
592
+ * meter with no usage costs zero. The free amount of a meter comes off its usage first, less `freeUsed`. The tiers
593
+ * then count the rest of the usage from zero. A committed term adds its upfront money times the period over the length.
594
+ *
595
+ * The arithmetic is exact, and the function does not round the cost to the cent. Each value is the nearest number to
596
+ * the exact cost. The function converts the units with the exact factors of `@mark1russell7/quantity`.
597
+ *
598
+ * @throws RangeError when the usage names a meter that the reading does not have. It also throws when an amount
599
+ * of usage is negative, or does not measure the metered amount of its meter.
600
+ */
601
+ function meteredCost(observation, usage, options = {}) {
602
+ const { offer, reading } = observation;
603
+ const { freeUsed = {} } = options;
604
+ const names = new Set(reading.meters.map((meter) => meter.name));
605
+ for (const name of [...Object.keys(usage), ...Object.keys(freeUsed)]) if (!names.has(name)) throw new RangeError(`The reading of ${reading.offerId} has no meter ${name}.`);
606
+ const at = (record, name) => Object.hasOwn(record, name) ? record[name] : void 0;
607
+ const costs = reading.meters.map((meter) => ({
608
+ name: meter.name,
609
+ ...costOfMeter(meter, at(usage, meter.name), at(freeUsed, meter.name))
610
+ }));
611
+ const unit = costs[0]?.money;
612
+ if (unit === void 0) throw new RangeError(`The reading of ${reading.offerId} has no meter.`);
613
+ let total = rationals.ZERO;
614
+ for (const each of costs) total = rationals.add(total, convertExact(each.cost, each.money, unit));
615
+ const meters = costs.map((each) => ({
616
+ name: each.name,
617
+ cost: quantity(rationals.toNumber(each.cost), each.money)
618
+ }));
619
+ let upfront = rationals.ZERO;
620
+ if (offer.term.kind === "committed" && reading.upfront !== void 0) {
621
+ const { length } = offer.term;
622
+ const share = rationals.div(exactIn(reading.period, length.unit), rationals.fromNumber(length.value));
623
+ upfront = rationals.mul(exactIn(reading.upfront, unit), share);
624
+ }
625
+ total = rationals.add(total, upfront);
626
+ return {
627
+ meters,
628
+ upfront: quantity(rationals.toNumber(upfront), unit),
629
+ total: quantity(rationals.toNumber(total), unit)
630
+ };
631
+ }
632
+ export { AVAILABILITIES, BOARD_FORMAT, CONDITIONS, FORMATS, FREE_SCOPES, METERED_KINDS, bestOffer, boardObservations, boardReadSchema, boardSchema, costOf, foldCode, freeAmountSchema, gtinCheckDigit, gtinSchema, instantSchema, isKept, keepObservations, keepUntil, lastReads, latestObservations, locationSchema, matchKeys, meterSchema, meteredCost, meteredKindOf, meteredObservationSchema, meteredOfferSchema, meteredPriceSchema, meteredReadingSchema, moneySchema, observationSchema, offerId, offerSchema, offersOfPart, offersPart, parseGtin, partNumberSchema, permitsHistory, permitsTrend, planReads, priceBreakSchema, priceReadingSchema, priceTermSchema, productSchema, readInterval, retentionSchema, sellerSchema, settleBoard, shippingSchema, sourceOfOffer, sourceSchema, sourceTermsSchema, specSchema, textSchema, tierSchema, unitPriceFor, watchEntrySchema, watchProblems };
627
633
 
628
634
  //# sourceMappingURL=index.js.map