@mark1russell7/market 0.1.5 → 0.1.6
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/README.md +24 -0
- package/build/index.js +1 -1
- package/build/plan.d.ts +104 -1
- package/build/plan.d.ts.map +1 -1
- package/build/plan.js +109 -36
- package/build/plan.js.map +1 -1
- package/build/{records-hK1UCmpm.js → records-DU5uvTYJ.js} +35 -2
- package/build/records-DU5uvTYJ.js.map +1 -0
- package/package.json +2 -2
- package/build/records-hK1UCmpm.js.map +0 -1
package/README.md
CHANGED
|
@@ -112,6 +112,30 @@ const plan = planBuys(need, observations);
|
|
|
112
112
|
plan.front.map((choice) => [choice.price.value, choice.values["minutes"]]); // [[120, 20], [200, 50], [280, 80], [420, 100]]
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
+
## A buy order under a budget
|
|
116
|
+
|
|
117
|
+
A buy order chooses units of products, one unit at a time, under a budget. Each step buys the unit with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`. The module knows no topic: the caller gives the value of a choice as a function.
|
|
118
|
+
|
|
119
|
+
- `buyCandidates(wants, observations, { currency, conditions })` gives a candidate for each product with a usable offer. The price is the cost of one unit with its shipping, from the in-stock offer with the lowest cost. Each unit is one order, so the price is an upper limit of the cost of more units. `unpriced` names each product with no usable offer.
|
|
120
|
+
- `orderBuys(candidates, { budget, stages, goal, start })` gives the order. Each stage has a name and a value function. A stage starts from the units of the stage before it, with the money that is left.
|
|
121
|
+
- **The value.** A value is a list of numbers, the most important number first. Thus a gain on the first number comes before each gain on the second number. With `goal: "min"`, a smaller value is better, as for a shortfall.
|
|
122
|
+
- **The stops.** A stage stops at `budget` when no unit fits the money that is left. It stops at `units` when each product is at its `max`. It stops at `no-gain` when no unit has a gain.
|
|
123
|
+
- **The bound.** With gains that do not increase as the order grows, the order holds at least `(1 - 1/e) / 2` of the best value. When two products give more together than apart, set `lazy` to `false`.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { orderBuys, type BuyCandidate } from "@mark1russell7/market/plan";
|
|
127
|
+
|
|
128
|
+
const candidates: BuyCandidate[] = [
|
|
129
|
+
{ product: "JUG", price: 4, max: 10, quote: "a:1" },
|
|
130
|
+
{ product: "CAN", price: 1, max: 10, quote: "a:2" },
|
|
131
|
+
];
|
|
132
|
+
// The days short of a target: water first, then food. A jug gives 4/3 days, and a can gives 1 day.
|
|
133
|
+
const short = (target: number) => (units: Readonly<Record<string, number>>) => [Math.max(0, target - ((units["JUG"] ?? 0) * 4) / 3), Math.max(0, target - (units["CAN"] ?? 0))];
|
|
134
|
+
const order = orderBuys(candidates, { budget: 15, goal: "min", stages: [{ name: "2 days", value: short(2) }, { name: "5 days", value: short(5) }] });
|
|
135
|
+
order.units; // { JUG: 3, CAN: 3 }
|
|
136
|
+
order.stages.map((stage) => stage.spent); // [10, 5]
|
|
137
|
+
```
|
|
138
|
+
|
|
115
139
|
## Metered prices
|
|
116
140
|
|
|
117
141
|
A cloud resource has a metered price: a price for each unit of an amount that the provider meters. A metered amount is a `time` (the hours of a machine), a `data-time` (stored data in GiB-months), a `data` (a transfer) or a `count` (requests).
|
package/build/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as matchKeys, E as foldCode, O as gtinCheckDigit, S as offersPart, T as unitPriceFor, _ 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, k as parseGtin, 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 costOf, x as offersOfPart, y as bestOffer } from "./records-DU5uvTYJ.js";
|
|
2
2
|
import { UnitError, canonicalUnit, convertExact, convertible, parseUnit, quantity, rationals, valueIn } from "@mark1russell7/quantity";
|
|
3
3
|
import { quantitySchema } from "@mark1russell7/quantity/schema";
|
|
4
4
|
import { z } from "zod";
|
package/build/plan.d.ts
CHANGED
|
@@ -1,7 +1,109 @@
|
|
|
1
1
|
import { a as PartWant, p as Condition, r as Observation } from "./offers-CVUAcRHs.js";
|
|
2
2
|
import { Quantity } from "@mark1russell7/quantity";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
import { Objective, SweepCounts } from "@mark1russell7/strategy-search";
|
|
4
|
+
import { Goal, GreedyStop, Objective, Selection, SweepCounts } from "@mark1russell7/strategy-search";
|
|
5
|
+
/** One product that a buyer wants: its key, the part that the offers must match, and the largest count of its units. */
|
|
6
|
+
interface ProductWant {
|
|
7
|
+
readonly product: string;
|
|
8
|
+
readonly want: PartWant;
|
|
9
|
+
/** The largest count of units to buy. The default is 1. */
|
|
10
|
+
readonly max?: number | undefined;
|
|
11
|
+
}
|
|
12
|
+
/** One candidate of a buy order: a product, the price of one unit, the largest count of units and the offer. */
|
|
13
|
+
interface BuyCandidate {
|
|
14
|
+
readonly product: string;
|
|
15
|
+
/** The cost of one unit with its shipping, in the currency of the order. */
|
|
16
|
+
readonly price: number;
|
|
17
|
+
readonly max: number;
|
|
18
|
+
/** The `id` of the offer of the price. */
|
|
19
|
+
readonly quote: string;
|
|
20
|
+
}
|
|
21
|
+
/** The candidates of a buy order, and the products that have no usable offer. */
|
|
22
|
+
interface BuyCandidates {
|
|
23
|
+
readonly currency: string;
|
|
24
|
+
readonly candidates: readonly BuyCandidate[];
|
|
25
|
+
readonly unpriced: readonly {
|
|
26
|
+
readonly product: string;
|
|
27
|
+
readonly why: string;
|
|
28
|
+
}[];
|
|
29
|
+
}
|
|
30
|
+
/** The options of the candidates: the currency and the conditions that the buyer accepts. */
|
|
31
|
+
interface CandidateOptions {
|
|
32
|
+
/** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */
|
|
33
|
+
readonly currency: string;
|
|
34
|
+
/** The conditions that the buyer accepts. The default is `new` only. */
|
|
35
|
+
readonly conditions?: readonly Condition[] | undefined;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its
|
|
39
|
+
* shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an
|
|
40
|
+
* upper limit of the cost of more units.
|
|
41
|
+
*
|
|
42
|
+
* @param wants - The products, in the order of the result
|
|
43
|
+
* @param observations - The observations of the offers
|
|
44
|
+
* @param options - The currency and the conditions
|
|
45
|
+
* @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`
|
|
46
|
+
*/
|
|
47
|
+
export declare function buyCandidates(wants: readonly ProductWant[], observations: readonly Observation[], options: CandidateOptions): BuyCandidates;
|
|
48
|
+
/** One stage of a buy order: its name and the value of a choice, the most important number first. */
|
|
49
|
+
interface OrderStage {
|
|
50
|
+
readonly name: string;
|
|
51
|
+
/** The value of the units of each product. It is a pure function. */
|
|
52
|
+
readonly value: (units: Selection) => readonly number[];
|
|
53
|
+
}
|
|
54
|
+
/** The options of a buy order. */
|
|
55
|
+
interface OrderOptions {
|
|
56
|
+
/** The money of the order, in the currency of the candidates. */
|
|
57
|
+
readonly budget: number;
|
|
58
|
+
/** The stages, in order. Each stage starts from the units of the stage before it, with the money that is left. */
|
|
59
|
+
readonly stages: readonly OrderStage[];
|
|
60
|
+
/** The goal of each number of a value. Use `min` for a shortfall. The default is `max`. */
|
|
61
|
+
readonly goal?: Goal | undefined;
|
|
62
|
+
/** The units that the buyer has before the order. Their cost is not in the budget. */
|
|
63
|
+
readonly start?: Selection | undefined;
|
|
64
|
+
/** With `false`, each step evaluates each product again. Use it when two products give more together than apart. */
|
|
65
|
+
readonly lazy?: boolean | undefined;
|
|
66
|
+
}
|
|
67
|
+
/** One purchase of a buy order: one unit of a product, its offer and its cost, and its gain in its stage. */
|
|
68
|
+
interface OrderBuy {
|
|
69
|
+
readonly stage: string;
|
|
70
|
+
readonly product: string;
|
|
71
|
+
readonly quote: string;
|
|
72
|
+
readonly cost: number;
|
|
73
|
+
readonly gain: readonly number[];
|
|
74
|
+
}
|
|
75
|
+
/** The result of one stage: the value before and after it, the money that it spends and the reason that it stops. */
|
|
76
|
+
interface OrderStageResult {
|
|
77
|
+
readonly name: string;
|
|
78
|
+
readonly method: "greedy" | "single";
|
|
79
|
+
readonly before: readonly number[];
|
|
80
|
+
readonly after: readonly number[];
|
|
81
|
+
readonly spent: number;
|
|
82
|
+
readonly stop: GreedyStop;
|
|
83
|
+
readonly evaluations: number;
|
|
84
|
+
}
|
|
85
|
+
/** A buy order: the purchases in the order of the choice, the units of each product, and the result of each stage. */
|
|
86
|
+
interface BuyOrder {
|
|
87
|
+
readonly budget: number;
|
|
88
|
+
readonly spent: number;
|
|
89
|
+
readonly buys: readonly OrderBuy[];
|
|
90
|
+
/** The units of each product after the order, with the units of `start`. */
|
|
91
|
+
readonly units: Selection;
|
|
92
|
+
readonly stages: readonly OrderStageResult[];
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the
|
|
96
|
+
* product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.
|
|
97
|
+
*
|
|
98
|
+
* - A stage starts from the units of the stage before it, and it spends only the money that is left.
|
|
99
|
+
* - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: "single"`).
|
|
100
|
+
*
|
|
101
|
+
* @param candidates - The candidates, from `buyCandidates`
|
|
102
|
+
* @param options - The budget, the stages, the goal and the start
|
|
103
|
+
* @returns The buy order
|
|
104
|
+
* @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length
|
|
105
|
+
*/
|
|
106
|
+
export declare function orderBuys(candidates: readonly BuyCandidate[], options: OrderOptions): BuyOrder;
|
|
5
107
|
/** The format name of a need record. */
|
|
6
108
|
export declare const NEED_FORMAT = "buy-need/1";
|
|
7
109
|
/** The format name of a plan record. */
|
|
@@ -148,4 +250,5 @@ export interface PlanOptions {
|
|
|
148
250
|
* The function also throws a RangeError when strategy-search refuses the options.
|
|
149
251
|
*/
|
|
150
252
|
export declare function planBuys(need: BuyNeed, observations: readonly Observation[], options?: PlanOptions): BuyPlan;
|
|
253
|
+
export type { BuyCandidate, BuyCandidates, BuyOrder, CandidateOptions, OrderBuy, OrderOptions, OrderStage, OrderStageResult, ProductWant };
|
|
151
254
|
//# sourceMappingURL=plan.d.ts.map
|
package/build/plan.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.d.ts","names":[],"sources":["../src/plan.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"plan.d.ts","names":[],"sources":["../src/order.ts","../src/plan.ts"],"mappings":";;;;;UAYiB;WACN;WACA,MAAM;;WAEN;;;UAIM;WACN;;WAEA;WACA;;WAEA;;;UAIM;WACN;WACA,qBAAqB;WACrB;aAA8B;aAA0B;;;;UAIlD;;WAEN;;WAEA,sBAAsB;;;;;;;;;;;;wBAajB,cAAc,gBAAgB,eAAe,uBAAuB,eAAe,SAAS,mBAAmB;;UAiB9G;WACN;;WAEA,QAAQ,OAAO;;;UAIT;;WAEN;;WAEA,iBAAiB;;WAEjB,OAAO;;WAEP,QAAQ;;WAER;;;UAIM;WACN;WACA;WACA;WACA;WACA;;;UAIM;WACN;WACA;WACA;WACA;WACA;WACA,MAAM;WACN;;;UAIM;WACN;WACA;WACA,eAAe;;WAEf,OAAO;WACP,iBAAiB;;;;;;;;;;;;;;wBAeZ,UAAU,qBAAqB,gBAAgB,SAAS,eAAe;;qBCpH1E;;qBAGA;;qBAGA;;qBAGA;;qBAGA;;YAMD;;iBAGK;WACN;WACA,MAAM;;WAEN,QAAQ,SAAS,eAAe;;;iBAI1B;WACN;WACA;;;iBAIM;WACN;WACA,gBAAgB;WAChB,QAAQ;;;;;;iBAOF;WACN;;WAEA;WACA;;WAEA;WACA;WACA;;;iBAIM;WACN;;WAEA;;;iBAIM;WACN,eAAe;WACf;;WAEA;;WAEA,sBAAsB;;WAEtB,SAAS,SAAS,eAAe;WACjC,gBAAgB;WAChB,oBAAoB;WACpB,iBAAiB;;;qBASf,eAAe,EAAE,QAAQ;;;;;;wBAuDtB,aAAa,MAAM;;iBAuDlB;WACN;WACA;WACA;WACA;WACA,MAAM;;;iBAIA;WACN;;WAEA,OAAO;WACP,QAAQ,SAAS;WACjB,gBAAgB;;;iBAIV;;WAEN;WACA;WACA;;;iBAIM;WACN;WACA;WACA;;;iBAIM;WACN,eAAe;;WAEf;WACA;;WAEA;;WAEA;;WAEA;WACA,qBAAqB;WACrB,QAAQ;;WAER,gBAAgB;;WAEhB,iBAAiB;;WAEjB,mBAAmB;;;iBAMb;;WAEN;;WAEA;;WAEA;;;;;;;;;;;;;;;;wBA2BK,SAAS,MAAM,SAAS,uBAAuB,eAAe,UAAS,cAAmB"}
|
package/build/plan.js
CHANGED
|
@@ -1,10 +1,116 @@
|
|
|
1
|
-
import { n as CONDITIONS, v as textSchema, x as offersOfPart
|
|
1
|
+
import { C as priceOf, n as CONDITIONS, v as textSchema, x as offersOfPart } from "./records-DU5uvTYJ.js";
|
|
2
2
|
import { compare, sum, valueIn } from "@mark1russell7/quantity";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
import { evolve, frontOf, sweep } from "@mark1russell7/strategy-search";
|
|
4
|
+
import { evolve, frontOf, greedy, sweep } from "@mark1russell7/strategy-search";
|
|
5
5
|
import { STRATEGY_SPACE_SCHEMA, spaceSize } from "@mark1russell7/strategy-space";
|
|
6
6
|
import { compile, isFieldName, parse, space } from "@mark1russell7/vex";
|
|
7
7
|
import { BoolDomain, NumDomain, TextDomain } from "@mark1russell7/vex-domains";
|
|
8
|
+
// src/order.ts
|
|
9
|
+
/**
|
|
10
|
+
* This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its
|
|
11
|
+
* shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an
|
|
12
|
+
* upper limit of the cost of more units.
|
|
13
|
+
*
|
|
14
|
+
* @param wants - The products, in the order of the result
|
|
15
|
+
* @param observations - The observations of the offers
|
|
16
|
+
* @param options - The currency and the conditions
|
|
17
|
+
* @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`
|
|
18
|
+
*/
|
|
19
|
+
function buyCandidates(wants, observations, options) {
|
|
20
|
+
const seen = /* @__PURE__ */ new Set();
|
|
21
|
+
const candidates = [];
|
|
22
|
+
const unpriced = [];
|
|
23
|
+
for (const want of wants) {
|
|
24
|
+
if (seen.has(want.product)) throw new RangeError(`The product ${want.product} is twice in the wants.`);
|
|
25
|
+
seen.add(want.product);
|
|
26
|
+
const max = want.max ?? 1;
|
|
27
|
+
if (!(Number.isSafeInteger(max) && max >= 0)) throw new RangeError(`The max of the product ${want.product} is ${String(max)}. It must be a whole number of 0 or more.`);
|
|
28
|
+
const priced = priceOf(offersOfPart(observations, want.want), 1, options);
|
|
29
|
+
if (priced.ok) candidates.push({
|
|
30
|
+
product: want.product,
|
|
31
|
+
price: valueIn(priced.cost, options.currency),
|
|
32
|
+
max,
|
|
33
|
+
quote: priced.offerId
|
|
34
|
+
});
|
|
35
|
+
else unpriced.push({
|
|
36
|
+
product: want.product,
|
|
37
|
+
why: priced.why
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
currency: options.currency,
|
|
42
|
+
candidates,
|
|
43
|
+
unpriced
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the
|
|
48
|
+
* product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.
|
|
49
|
+
*
|
|
50
|
+
* - A stage starts from the units of the stage before it, and it spends only the money that is left.
|
|
51
|
+
* - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: "single"`).
|
|
52
|
+
*
|
|
53
|
+
* @param candidates - The candidates, from `buyCandidates`
|
|
54
|
+
* @param options - The budget, the stages, the goal and the start
|
|
55
|
+
* @returns The buy order
|
|
56
|
+
* @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length
|
|
57
|
+
*/
|
|
58
|
+
function orderBuys(candidates, options) {
|
|
59
|
+
if (options.stages.length === 0) throw new RangeError("The order has no stage.");
|
|
60
|
+
if (!(Number.isFinite(options.budget) && options.budget >= 0)) throw new RangeError(`The budget is ${String(options.budget)}. It must be a finite number of 0 or more.`);
|
|
61
|
+
const byProduct = new Map(candidates.map((candidate) => [candidate.product, candidate]));
|
|
62
|
+
const items = candidates.map((candidate) => ({
|
|
63
|
+
id: candidate.product,
|
|
64
|
+
cost: candidate.price,
|
|
65
|
+
max: candidate.max
|
|
66
|
+
}));
|
|
67
|
+
const start = options.start ?? {};
|
|
68
|
+
let units = start;
|
|
69
|
+
let left = options.budget;
|
|
70
|
+
let spent = 0;
|
|
71
|
+
const buys = [];
|
|
72
|
+
const stages = [];
|
|
73
|
+
for (const stage of options.stages) {
|
|
74
|
+
const open = items.map((item) => ({
|
|
75
|
+
...item,
|
|
76
|
+
max: item.max - ((units[item.id] ?? 0) - (start[item.id] ?? 0))
|
|
77
|
+
}));
|
|
78
|
+
const run = greedy({
|
|
79
|
+
items: open,
|
|
80
|
+
budget: Math.max(0, left),
|
|
81
|
+
value: stage.value,
|
|
82
|
+
start: units,
|
|
83
|
+
...options.goal === void 0 ? {} : { goal: options.goal },
|
|
84
|
+
...options.lazy === void 0 ? {} : { lazy: options.lazy }
|
|
85
|
+
});
|
|
86
|
+
for (const pick of run.picks) buys.push({
|
|
87
|
+
stage: stage.name,
|
|
88
|
+
product: pick.id,
|
|
89
|
+
quote: byProduct.get(pick.id)?.quote ?? "",
|
|
90
|
+
cost: pick.cost,
|
|
91
|
+
gain: pick.gain
|
|
92
|
+
});
|
|
93
|
+
units = run.selection;
|
|
94
|
+
left -= run.spent;
|
|
95
|
+
spent += run.spent;
|
|
96
|
+
stages.push({
|
|
97
|
+
name: stage.name,
|
|
98
|
+
method: run.method,
|
|
99
|
+
before: run.before,
|
|
100
|
+
after: run.after,
|
|
101
|
+
spent: run.spent,
|
|
102
|
+
stop: run.stop,
|
|
103
|
+
evaluations: run.evaluations
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
budget: options.budget,
|
|
108
|
+
spent,
|
|
109
|
+
buys,
|
|
110
|
+
units,
|
|
111
|
+
stages
|
|
112
|
+
};
|
|
113
|
+
}
|
|
8
114
|
// src/plan.ts
|
|
9
115
|
/** The format name of a need record. */
|
|
10
116
|
const NEED_FORMAT = "buy-need/1";
|
|
@@ -141,39 +247,6 @@ function needProblems(need) {
|
|
|
141
247
|
return problems;
|
|
142
248
|
}
|
|
143
249
|
/**
|
|
144
|
-
* This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the
|
|
145
|
-
* shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.
|
|
146
|
-
*/
|
|
147
|
-
function priceOf(observations, count, need) {
|
|
148
|
-
const choice = bestOffer(observations, {
|
|
149
|
-
currency: need.currency,
|
|
150
|
-
count,
|
|
151
|
-
...need.conditions === void 0 ? {} : { conditions: need.conditions }
|
|
152
|
-
});
|
|
153
|
-
let pick;
|
|
154
|
-
for (const offer of choice.offers) {
|
|
155
|
-
const cost = offer.cost;
|
|
156
|
-
if (offer.inStock && cost !== null && (pick === void 0 || compare(cost, pick.cost) < 0)) pick = {
|
|
157
|
-
...offer,
|
|
158
|
-
cost
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
if (pick !== void 0) return {
|
|
162
|
-
ok: true,
|
|
163
|
-
offerId: pick.observation.offer.id,
|
|
164
|
-
cost: pick.cost
|
|
165
|
-
};
|
|
166
|
-
if (choice.offers.length > 0) return {
|
|
167
|
-
ok: false,
|
|
168
|
-
why: `No offer of ${String(count)} units is in stock with a known cost.`
|
|
169
|
-
};
|
|
170
|
-
const first = choice.skipped[0];
|
|
171
|
-
return {
|
|
172
|
-
ok: false,
|
|
173
|
-
why: first === void 0 ? "No offer matches the part." : `No offer is usable. The first offer that the choice skipped: ${first.why}`
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
250
|
* This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy
|
|
178
251
|
* space. Each part with a usable offer is an option of its stage, with a param `count`. The price of a basket is the sum
|
|
179
252
|
* of the cost of each item.
|
|
@@ -435,6 +508,6 @@ function breaksOf(rows, firstWhy) {
|
|
|
435
508
|
why: firstWhy.get(name) ?? ""
|
|
436
509
|
}));
|
|
437
510
|
}
|
|
438
|
-
export { NEED_FORMAT, NEED_KEY, PLAN_EVALUATIONS, PLAN_FORMAT, SLOT_FIELDS, buyNeedSchema, needProblems, planBuys };
|
|
511
|
+
export { NEED_FORMAT, NEED_KEY, PLAN_EVALUATIONS, PLAN_FORMAT, SLOT_FIELDS, buyCandidates, buyNeedSchema, needProblems, orderBuys, planBuys };
|
|
439
512
|
|
|
440
513
|
//# sourceMappingURL=plan.js.map
|
package/build/plan.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","names":[],"sources":["../src/plan.ts"],"sourcesContent":["import { compare, sum, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { evolve, frontOf, sweep, type EvaluationRow, type Measure, type Objective, type SweepCounts } from \"@mark1russell7/strategy-search\";\nimport { spaceSize, STRATEGY_SPACE_SCHEMA, type SpaceParam, type StrategyConfig, type StrategySpace } from \"@mark1russell7/strategy-space\";\nimport { compile, isFieldName, parse, space, type AnyDomain, type Program } from \"@mark1russell7/vex\";\nimport { BoolDomain, NumDomain, TextDomain } from \"@mark1russell7/vex-domains\";\nimport { z } from \"zod\";\nimport { bestOffer, offersOfPart, type Observation, type OfferChoice, type PartWant } from \"./offers.ts\";\nimport { CONDITIONS, textSchema, type Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy plan. A need names the slots of a purchase, the parts that can fill each slot, and\n * the measures and the rules of a basket as Vex programs. The plan searches the baskets with strategy-search, and it\n * gives the front of the price against the measures. The module knows no part class: the facts of each part and the\n * programs come from the need. Each function of this module is a calculation with no effect.\n */\n\n/** The format name of a need record. */\nexport const NEED_FORMAT = \"buy-need/1\";\n\n/** The format name of a plan record. */\nexport const PLAN_FORMAT = \"buy-plan/1\";\n\n/** The key of the inputs of a need in the space of a basket. A slot cannot have this name. */\nexport const NEED_KEY = \"need\";\n\n/** The fields that the plan writes in the record of each slot. A fact of a part cannot have one of these names. */\nexport const SLOT_FIELDS = [\"slot\", \"part\", \"count\", \"cost\"] as const;\n\n/** The largest count of evaluations of a plan, when the options do not give a count. */\nexport const PLAN_EVALUATIONS = 2000;\n\n/** The domains of the programs of a need: numbers, booleans and texts. */\nconst DOMAINS: readonly AnyDomain[] = [NumDomain, BoolDomain, TextDomain];\n\n/** A fact of a part, or an input of a need: a number, a text or a boolean. */\nexport type Fact = number | string | boolean;\n\n/** One part that can fill a slot: its key in the slot, the part that the offers must match, and its facts. */\nexport interface NeedPart {\n readonly key: string;\n readonly want: PartWant;\n /** The facts of the part that the programs read, for example its watts. */\n readonly facts?: Readonly<Record<string, Fact>> | undefined;\n}\n\n/** The count of units of a slot. With `min` 0, a basket can leave the slot empty. */\nexport interface SlotCount {\n readonly min: number;\n readonly max: number;\n}\n\n/** One slot of a need: its name, the parts that can fill it, and the count of its units. The default count is 1. */\nexport interface NeedSlot {\n readonly name: string;\n readonly parts: readonly NeedPart[];\n readonly count?: SlotCount | undefined;\n}\n\n/**\n * One measure of a basket: a Vex program that gives a number. With `goal`, the measure is an objective of the search.\n * A value below `min` or above `max` breaks the basket.\n */\nexport interface NeedMeasure {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n readonly goal?: \"min\" | \"max\" | undefined;\n /** The unit of the values, as text for a reader. */\n readonly unit?: string | undefined;\n readonly min?: number | undefined;\n readonly max?: number | undefined;\n}\n\n/** One rule of a basket: a Vex program that gives `true` when the basket keeps the rule. */\nexport interface NeedRule {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n}\n\n/** This record is a need: the currency and the conditions of the offers, the inputs, the slots, the measures and the rules. */\nexport interface BuyNeed {\n readonly format: typeof NEED_FORMAT;\n readonly id: string;\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n /** The inputs that the programs read at the key `need`, for example the load in watts. */\n readonly inputs?: Readonly<Record<string, Fact>> | undefined;\n readonly slots: readonly NeedSlot[];\n readonly measures?: readonly NeedMeasure[] | undefined;\n readonly rules?: readonly NeedRule[] | undefined;\n}\n\nconst factSchema: z.ZodType<Fact> = z.union([z.number().refine(Number.isFinite, \"The number is not finite.\"), z.string(), z.boolean()]);\nconst factsSchema: z.ZodType<Readonly<Record<string, Fact>>> = z.record(textSchema, factSchema);\nconst wantSchema: z.ZodType<PartWant> = z.strictObject({ brands: z.array(textSchema).min(1), partNumbers: z.array(textSchema).min(1) });\nconst wholeSchema = z.number().int().nonnegative();\n\n/** This schema accepts the form of a need. `needProblems` examines the names, the counts and the programs. */\nexport const buyNeedSchema: z.ZodType<BuyNeed> = z.strictObject({\n format: z.literal(NEED_FORMAT),\n id: textSchema,\n currency: textSchema,\n conditions: z.array(z.enum(CONDITIONS)).min(1).optional(),\n inputs: factsSchema.optional(),\n slots: z\n .array(\n z.strictObject({\n name: textSchema,\n parts: z.array(z.strictObject({ key: textSchema, want: wantSchema, facts: factsSchema.optional() })).min(1),\n count: z.strictObject({ min: wholeSchema, max: wholeSchema }).optional(),\n }),\n )\n .min(1),\n measures: z\n .array(\n z.strictObject({\n name: textSchema,\n program: z.unknown(),\n goal: z.enum([\"min\", \"max\"]).optional(),\n unit: textSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n )\n .optional(),\n rules: z.array(z.strictObject({ name: textSchema, program: z.unknown() })).optional(),\n});\n\n/** This function gives the count of a slot, with the default 1 to 1. */\nfunction countOf(slot: NeedSlot): SlotCount {\n return slot.count ?? { min: 1, max: 1 };\n}\n\n/** This function reads a program of a need. It gives the expression, or the reason that the program is not valid. */\nfunction readProgram(program: unknown): { readonly ok: true; readonly program: Program } | { readonly ok: false; readonly why: string } {\n const text = program === undefined ? undefined : JSON.stringify(program);\n if (text === undefined) return { ok: false, why: \"The program is missing.\" };\n const read = parse(text, DOMAINS);\n return read.ok ? { ok: true, program: compile(read.value, { domains: DOMAINS }) } : { ok: false, why: read.error.message };\n}\n\n/** This function compiles a program that `needProblems` accepts. */\nfunction programOf(program: unknown): Program {\n const read = readProgram(program);\n if (!read.ok) throw new RangeError(read.why);\n return read.program;\n}\n\n/**\n * This function gives the problems of a need. Two slots, parts, measures or rules with one name are a problem. A bad\n * count is a problem. The slot name `need` and the measure name `price` are problems. A fact with the name of a field\n * of a slot is a problem. A program that is not valid is a problem.\n */\nexport function needProblems(need: BuyNeed): string[] {\n const problems: string[] = [];\n const twice = (names: readonly string[], what: string): void => {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) problems.push(`Two ${what} have the name ${name}.`);\n seen.add(name);\n }\n };\n twice(\n need.slots.map((slot) => slot.name),\n \"slots\",\n );\n for (const name of Object.keys(need.inputs ?? {})) if (!isFieldName(name)) problems.push(`The input ${name} is not a name of a field.`);\n for (const slot of need.slots) {\n if (slot.name === NEED_KEY) problems.push(`The slot ${NEED_KEY} has the name of the inputs.`);\n else if (!isFieldName(slot.name)) problems.push(`The slot ${slot.name} is not a name of a field.`);\n twice(\n slot.parts.map((part) => part.key),\n `parts of the slot ${slot.name}`,\n );\n const { min, max } = countOf(slot);\n if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min < 0 || max < 1 || min > max)\n problems.push(`The count of the slot ${slot.name} is ${String(min)} to ${String(max)}. It must be whole numbers, with a maximum of 1 or more and not below the minimum.`);\n for (const part of slot.parts) {\n for (const name of Object.keys(part.facts ?? {})) {\n if ((SLOT_FIELDS as readonly string[]).includes(name)) problems.push(`The part ${part.key} of the slot ${slot.name} has the fact ${name}, which is a field of the slot.`);\n else if (!isFieldName(name)) problems.push(`The fact ${name} of the part ${part.key} is not a name of a field.`);\n }\n }\n }\n const measures = need.measures ?? [];\n const rules = need.rules ?? [];\n twice(\n measures.map((measure) => measure.name),\n \"measures\",\n );\n twice(\n rules.map((rule) => rule.name),\n \"rules\",\n );\n for (const measure of measures) {\n if (measure.name === \"price\") problems.push(\"A measure has the name price, which is the objective of the cost.\");\n if (measure.min !== undefined && measure.max !== undefined && measure.min > measure.max) problems.push(`The measure ${measure.name} has a minimum above its maximum.`);\n const read = readProgram(measure.program);\n if (!read.ok) problems.push(`The program of the measure ${measure.name} is not valid: ${read.why}`);\n }\n for (const rule of rules) {\n const read = readProgram(rule.program);\n if (!read.ok) problems.push(`The program of the rule ${rule.name} is not valid: ${read.why}`);\n }\n return problems;\n}\n\n/** This record is one item of a basket: the slot, the part, the count, the offer to buy and the cost with the shipping. */\nexport interface BuyItem {\n readonly slot: string;\n readonly part: string;\n readonly count: number;\n readonly offerId: string;\n readonly cost: Quantity;\n}\n\n/** This record is one basket of the front: its config id, its price, the value of each measure and its items. */\nexport interface BuyChoice {\n readonly config: string;\n /** The sum of the cost of each item. Each item is one order, with its own shipping. */\n readonly price: Quantity;\n readonly values: Readonly<Record<string, number>>;\n readonly items: readonly BuyItem[];\n}\n\n/** This record counts the baskets that break one constraint, with the reason of the first such basket. */\nexport interface BuyBreak {\n /** The constraint: `price:<slot>`, `measure:<name>`, `limit:<name>` or `rule:<name>`. */\n readonly name: string;\n readonly count: number;\n readonly why: string;\n}\n\n/** This record is a part that no basket can have, because no offer of the part is usable at a count of its slot. */\nexport interface UnpricedPart {\n readonly slot: string;\n readonly part: string;\n readonly why: string;\n}\n\n/** This record is a buy plan: the method of the search, its counts, the front of the baskets and the reasons of the breaks. */\nexport interface BuyPlan {\n readonly format: typeof PLAN_FORMAT;\n /** The id of the need. */\n readonly need: string;\n readonly currency: string;\n /** `grid` evaluates each basket. `evolve` is a genetic search. `none` tells that a slot that must have a part has no part with an offer. */\n readonly method: \"grid\" | \"evolve\" | \"none\";\n /** The seed of a genetic search, or null. */\n readonly seed: number | null;\n /** The id of the run of strategy-search, or null for `none`. */\n readonly run: string | null;\n readonly objectives: readonly Objective[];\n readonly counts: SweepCounts;\n /** The baskets on the Pareto front, from the lowest price. Equal prices go in the order of the config id. */\n readonly front: readonly BuyChoice[];\n /** The constraints that the evaluated baskets break, in the order of their names. */\n readonly breaks: readonly BuyBreak[];\n /** The parts with no usable offer, in the order of the slots and of their parts. */\n readonly unpriced: readonly UnpricedPart[];\n}\n\n/** These options change the search of a plan. */\nexport interface PlanOptions {\n /** The largest count of evaluations. A space with no more baskets gets a grid of each basket. The default is `PLAN_EVALUATIONS`. */\n readonly evaluations?: number | undefined;\n /** The seed of a genetic search. The default is the id of the need. */\n readonly seed?: number | string | undefined;\n /** The count of the baskets of a generation of a genetic search. The default is the default of strategy-search. */\n readonly population?: number | undefined;\n}\n\n/** The offer to buy for one count of a part, or the reason that no offer is usable. */\ntype Priced = { readonly ok: true; readonly offerId: string; readonly cost: Quantity } | { readonly ok: false; readonly why: string };\n\n/** The breaks, the values and the items of one basket. */\ninterface Assessed {\n readonly breaks: readonly { readonly name: string; readonly why: string }[];\n readonly values: Readonly<Record<string, number>>;\n readonly price: Quantity | null;\n readonly items: readonly BuyItem[];\n}\n\n/**\n * This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the\n * shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.\n */\nfunction priceOf(observations: readonly Observation[], count: number, need: BuyNeed): Priced {\n const choice = bestOffer(observations, { currency: need.currency, count, ...(need.conditions === undefined ? {} : { conditions: need.conditions }) });\n let pick: (OfferChoice & { readonly cost: Quantity }) | undefined;\n for (const offer of choice.offers) {\n const cost = offer.cost;\n if (offer.inStock && cost !== null && (pick === undefined || compare(cost, pick.cost) < 0)) pick = { ...offer, cost };\n }\n if (pick !== undefined) return { ok: true, offerId: pick.observation.offer.id, cost: pick.cost };\n if (choice.offers.length > 0) return { ok: false, why: `No offer of ${String(count)} units is in stock with a known cost.` };\n const first = choice.skipped[0];\n return { ok: false, why: first === undefined ? \"No offer matches the part.\" : `No offer is usable. The first offer that the choice skipped: ${first.why}` };\n}\n\n/**\n * This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy\n * space. Each part with a usable offer is an option of its stage, with a param `count`. The price of a basket is the sum\n * of the cost of each item.\n *\n * Each measure and each rule is a Vex program that evaluates at the key `need` of a record space. The key `need` has\n * the inputs. The key of each slot has the facts of its part, `slot`, `part`, `count` and `cost`. A slot with no part\n * has only `slot`, the count 0 and the cost 0. Thus the axis `others` gives the slots.\n *\n * A space with no more baskets than `evaluations` gets a grid of each basket, and a larger space gets a genetic search.\n *\n * @throws RangeError when the need or its currency is not valid, or when `evaluations` is not a whole number of 1 or more.\n * The function also throws a RangeError when strategy-search refuses the options.\n */\nexport function planBuys(need: BuyNeed, observations: readonly Observation[], options: PlanOptions = {}): BuyPlan {\n const shape = buyNeedSchema.safeParse(need);\n if (!shape.success) throw new RangeError(`The need is not valid: ${shape.error.issues.map((issue) => `${issue.path.join(\".\")}: ${issue.message}`).join(\" \")}`);\n const problems = needProblems(need);\n if (problems.length > 0) throw new RangeError(`The need is not valid: ${problems.join(\" \")}`);\n const evaluations = options.evaluations ?? PLAN_EVALUATIONS;\n if (!Number.isSafeInteger(evaluations) || evaluations < 1) throw new RangeError(`The count of evaluations ${String(evaluations)} is not a whole number of 1 or more.`);\n\n const measures = (need.measures ?? []).map((measure) => ({ measure, program: programOf(measure.program) }));\n const rules = (need.rules ?? []).map((rule) => ({ rule, program: programOf(rule.program) }));\n const objectives: Objective[] = [\n { name: \"price\", goal: \"min\", unit: need.currency },\n ...measures.flatMap(({ measure }) => (measure.goal === undefined ? [] : [measure.unit === undefined ? { name: measure.name, goal: measure.goal } : { name: measure.name, goal: measure.goal, unit: measure.unit }])),\n ];\n\n // The price of each count of each part, once. A part with no usable offer at any count is not an option.\n const prices = new Map<string, Map<number, Priced>>();\n const unpriced: UnpricedPart[] = [];\n const stages: StrategySpace[\"stages\"][number][] = [];\n let blocked = false;\n for (const slot of need.slots) {\n const { min, max } = countOf(slot);\n const low = Math.max(1, min);\n const params: SpaceParam[] = max > low ? [{ name: \"count\", kind: \"int\", min: low, max, default: low }] : [];\n const usable: string[] = [];\n for (const part of slot.parts) {\n const offers = offersOfPart(observations, part.want);\n const byCount = new Map<number, Priced>();\n for (let count = low; count <= max; count++) byCount.set(count, priceOf(offers, count, need));\n prices.set(`${slot.name}\\u0000${part.key}`, byCount);\n const first = byCount.get(low);\n if ([...byCount.values()].some((priced) => priced.ok)) usable.push(part.key);\n else unpriced.push({ slot: slot.name, part: part.key, why: first === undefined || first.ok ? \"No offer is usable.\" : first.why });\n }\n if (usable.length > 0) stages.push({ name: slot.name, options: usable.map((id) => ({ id, params })), ...(min === 0 ? { optional: true } : {}) });\n else if (min > 0) blocked = true;\n }\n const none: BuyPlan = { format: PLAN_FORMAT, need: need.id, currency: need.currency, method: \"none\", seed: null, run: null, objectives, counts: { feasible: 0, breaks: 0, unread: 0, front: 0 }, front: [], breaks: [], unpriced };\n if (blocked || stages.length === 0) return none;\n\n const strategySpace: StrategySpace = { schema: STRATEGY_SPACE_SCHEMA, engine: \"buy-plan\", version: \"1\", stages };\n\n const assess = (config: StrategyConfig): Assessed => {\n const breaks: { name: string; why: string }[] = [];\n const items: BuyItem[] = [];\n const records: Record<string, Readonly<Record<string, Fact>>> = { [NEED_KEY]: need.inputs ?? {} };\n for (const slot of need.slots) {\n const choice = config.stages[slot.name] ?? null;\n if (choice === null) {\n records[slot.name] = { slot: slot.name, count: 0, cost: 0 };\n continue;\n }\n const part = slot.parts.find((each) => each.key === choice.option) as NeedPart;\n const count = Number(choice.params?.[\"count\"] ?? Math.max(1, countOf(slot).min));\n const priced = prices.get(`${slot.name}\\u0000${part.key}`)?.get(count) ?? { ok: false, why: `The count ${String(count)} is not a count of the slot.` };\n if (!priced.ok) {\n breaks.push({ name: `price:${slot.name}`, why: `The part ${part.key} of the slot ${slot.name}: ${priced.why}` });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: 0 };\n continue;\n }\n items.push({ slot: slot.name, part: part.key, count, offerId: priced.offerId, cost: priced.cost });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: valueIn(priced.cost, need.currency) };\n }\n const price = breaks.length > 0 ? null : sum(items.map((item) => item.cost), need.currency);\n const values: Record<string, number> = price === null ? {} : { price: valueIn(price, need.currency) };\n const basket = space.record(records);\n for (const { measure, program } of measures) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `measure:${measure.name}`, why: result.error.message });\n else if (typeof result.value !== \"number\" || !Number.isFinite(result.value)) breaks.push({ name: `measure:${measure.name}`, why: `The value ${String(result.value)} is not a finite number.` });\n else {\n values[measure.name] = result.value;\n if (measure.min !== undefined && result.value < measure.min) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is below the minimum ${String(measure.min)}.` });\n if (measure.max !== undefined && result.value > measure.max) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is above the maximum ${String(measure.max)}.` });\n }\n }\n for (const { rule, program } of rules) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `rule:${rule.name}`, why: result.error.message });\n else if (result.value !== true) breaks.push({ name: `rule:${rule.name}`, why: result.value === false ? \"The basket breaks the rule.\" : `The value ${String(result.value)} is not a boolean.` });\n }\n return { breaks, values, price, items };\n };\n\n // The reason of the first basket that breaks each constraint.\n const firstWhy = new Map<string, string>();\n const evaluate = (config: StrategyConfig): Measure => {\n const assessed = assess(config);\n for (const { name, why } of assessed.breaks) if (!firstWhy.has(name)) firstWhy.set(name, why);\n return { breaks: [...new Set(assessed.breaks.map((each) => each.name))], values: assessed.values };\n };\n\n const levels = Math.max(1, ...need.slots.map((slot) => countOf(slot).max - Math.max(1, countOf(slot).min) + 1));\n const grid = spaceSize(strategySpace, { levels }).base <= BigInt(evaluations);\n const evaluator = `buy-need:${need.id}`;\n const run = grid\n ? sweep(strategySpace, { objectives, evaluate, enumerate: { mode: \"grid\", levels, limit: evaluations }, evaluator })\n : evolve(strategySpace, {\n objectives,\n evaluate,\n seed: options.seed ?? need.id,\n evaluations,\n ...(options.population === undefined ? {} : { population: options.population }),\n evaluator,\n });\n\n const front = frontOf(run)\n .map(({ row, config }): BuyChoice => {\n const assessed = assess(config);\n const values = Object.fromEntries(Object.entries(assessed.values).filter(([name]) => name !== \"price\"));\n return { config: row.config, price: assessed.price as Quantity, values, items: assessed.items };\n })\n .sort((a, b) => compare(a.price, b.price) || (a.config < b.config ? -1 : a.config > b.config ? 1 : 0));\n return {\n ...none,\n method: grid ? \"grid\" : \"evolve\",\n seed: run.seed,\n run: run.run,\n counts: run.counts,\n front,\n breaks: breaksOf(run.rows, firstWhy),\n unpriced,\n };\n}\n\n/** This function counts the rows that break each constraint, in the order of the names. */\nfunction breaksOf(rows: readonly EvaluationRow[], firstWhy: ReadonlyMap<string, string>): BuyBreak[] {\n const counts = new Map<string, number>();\n for (const row of rows) for (const name of row.breaks) counts.set(name, (counts.get(name) ?? 0) + 1);\n return [...counts.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([name, count]) => ({ name, count, why: firstWhy.get(name) ?? \"\" }));\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAa,cAAc;;AAG3B,MAAa,cAAc;;AAG3B,MAAa,WAAW;;AAGxB,MAAa,cAAc;CAAC;CAAQ;CAAQ;CAAS;AAAM;;AAG3D,MAAa,mBAAmB;;AAGhC,MAAM,UAAgC;CAAC;CAAW;CAAY;AAAU;AA+DxE,MAAM,aAA8B,EAAE,MAAM;CAAC,EAAE,OAAO,CAAC,CAAC,OAAO,OAAO,UAAU,2BAA2B;CAAG,EAAE,OAAO;CAAG,EAAE,QAAQ;AAAC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AAmD;CACnG,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,OAAO,MAAM,KAAK,MAAM,QAAQ,IAAI,QAAQ,OAAO,IAAI,OAAO,OAAO,IAAI,IAAI,KAAK,KAAK,CAAC;CACnG,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,MAAM,YAAY;EAAE;EAAM;EAAO,KAAK,SAAS,IAAI,IAAI,KAAK;CAAG,EAAE;AAC5E"}
|
|
1
|
+
{"version":3,"file":"plan.js","names":[],"sources":["../src/order.ts","../src/plan.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport { greedy, type Goal, type GreedyStop, type Selection } from \"@mark1russell7/strategy-search\";\nimport { offersOfPart, priceOf, type Observation, type PartWant } from \"./offers.ts\";\nimport type { Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy order: the purchases that give the most value for each unit of money under a budget.\n * The candidates come from the offers. The order is a budgeted greedy choice of strategy-search, in stages, for\n * example a first target and then a second target. The module knows no topic: the caller gives the value of a choice.\n */\n\n/** One product that a buyer wants: its key, the part that the offers must match, and the largest count of its units. */\nexport interface ProductWant {\n readonly product: string;\n readonly want: PartWant;\n /** The largest count of units to buy. The default is 1. */\n readonly max?: number | undefined;\n}\n\n/** One candidate of a buy order: a product, the price of one unit, the largest count of units and the offer. */\nexport interface BuyCandidate {\n readonly product: string;\n /** The cost of one unit with its shipping, in the currency of the order. */\n readonly price: number;\n readonly max: number;\n /** The `id` of the offer of the price. */\n readonly quote: string;\n}\n\n/** The candidates of a buy order, and the products that have no usable offer. */\nexport interface BuyCandidates {\n readonly currency: string;\n readonly candidates: readonly BuyCandidate[];\n readonly unpriced: readonly { readonly product: string; readonly why: string }[];\n}\n\n/** The options of the candidates: the currency and the conditions that the buyer accepts. */\nexport interface CandidateOptions {\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n}\n\n/**\n * This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its\n * shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an\n * upper limit of the cost of more units.\n *\n * @param wants - The products, in the order of the result\n * @param observations - The observations of the offers\n * @param options - The currency and the conditions\n * @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`\n */\nexport function buyCandidates(wants: readonly ProductWant[], observations: readonly Observation[], options: CandidateOptions): BuyCandidates {\n const seen = new Set<string>();\n const candidates: BuyCandidate[] = [];\n const unpriced: { product: string; why: string }[] = [];\n for (const want of wants) {\n if (seen.has(want.product)) throw new RangeError(`The product ${want.product} is twice in the wants.`);\n seen.add(want.product);\n const max = want.max ?? 1;\n if (!(Number.isSafeInteger(max) && max >= 0)) throw new RangeError(`The max of the product ${want.product} is ${String(max)}. It must be a whole number of 0 or more.`);\n const priced = priceOf(offersOfPart(observations, want.want), 1, options);\n if (priced.ok) candidates.push({ product: want.product, price: valueIn(priced.cost, options.currency), max, quote: priced.offerId });\n else unpriced.push({ product: want.product, why: priced.why });\n }\n return { currency: options.currency, candidates, unpriced };\n}\n\n/** One stage of a buy order: its name and the value of a choice, the most important number first. */\nexport interface OrderStage {\n readonly name: string;\n /** The value of the units of each product. It is a pure function. */\n readonly value: (units: Selection) => readonly number[];\n}\n\n/** The options of a buy order. */\nexport interface OrderOptions {\n /** The money of the order, in the currency of the candidates. */\n readonly budget: number;\n /** The stages, in order. Each stage starts from the units of the stage before it, with the money that is left. */\n readonly stages: readonly OrderStage[];\n /** The goal of each number of a value. Use `min` for a shortfall. The default is `max`. */\n readonly goal?: Goal | undefined;\n /** The units that the buyer has before the order. Their cost is not in the budget. */\n readonly start?: Selection | undefined;\n /** With `false`, each step evaluates each product again. Use it when two products give more together than apart. */\n readonly lazy?: boolean | undefined;\n}\n\n/** One purchase of a buy order: one unit of a product, its offer and its cost, and its gain in its stage. */\nexport interface OrderBuy {\n readonly stage: string;\n readonly product: string;\n readonly quote: string;\n readonly cost: number;\n readonly gain: readonly number[];\n}\n\n/** The result of one stage: the value before and after it, the money that it spends and the reason that it stops. */\nexport interface OrderStageResult {\n readonly name: string;\n readonly method: \"greedy\" | \"single\";\n readonly before: readonly number[];\n readonly after: readonly number[];\n readonly spent: number;\n readonly stop: GreedyStop;\n readonly evaluations: number;\n}\n\n/** A buy order: the purchases in the order of the choice, the units of each product, and the result of each stage. */\nexport interface BuyOrder {\n readonly budget: number;\n readonly spent: number;\n readonly buys: readonly OrderBuy[];\n /** The units of each product after the order, with the units of `start`. */\n readonly units: Selection;\n readonly stages: readonly OrderStageResult[];\n}\n\n/**\n * This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the\n * product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.\n *\n * - A stage starts from the units of the stage before it, and it spends only the money that is left.\n * - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: \"single\"`).\n *\n * @param candidates - The candidates, from `buyCandidates`\n * @param options - The budget, the stages, the goal and the start\n * @returns The buy order\n * @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length\n */\nexport function orderBuys(candidates: readonly BuyCandidate[], options: OrderOptions): BuyOrder {\n if (options.stages.length === 0) throw new RangeError(\"The order has no stage.\");\n if (!(Number.isFinite(options.budget) && options.budget >= 0)) throw new RangeError(`The budget is ${String(options.budget)}. It must be a finite number of 0 or more.`);\n const byProduct = new Map(candidates.map((candidate) => [candidate.product, candidate]));\n const items = candidates.map((candidate) => ({ id: candidate.product, cost: candidate.price, max: candidate.max }));\n const start: Selection = options.start ?? {};\n let units: Selection = start;\n let left = options.budget;\n let spent = 0;\n const buys: OrderBuy[] = [];\n const stages: OrderStageResult[] = [];\n for (const stage of options.stages) {\n // The max of each item is what is left after the stages before.\n const open = items.map((item) => ({ ...item, max: item.max - ((units[item.id] ?? 0) - (start[item.id] ?? 0)) }));\n const run = greedy({\n items: open,\n budget: Math.max(0, left),\n value: stage.value,\n start: units,\n ...(options.goal === undefined ? {} : { goal: options.goal }),\n ...(options.lazy === undefined ? {} : { lazy: options.lazy }),\n });\n for (const pick of run.picks) buys.push({ stage: stage.name, product: pick.id, quote: byProduct.get(pick.id)?.quote ?? \"\", cost: pick.cost, gain: pick.gain });\n units = run.selection;\n left -= run.spent;\n spent += run.spent;\n stages.push({ name: stage.name, method: run.method, before: run.before, after: run.after, spent: run.spent, stop: run.stop, evaluations: run.evaluations });\n }\n return { budget: options.budget, spent, buys, units, stages };\n}\n","import { compare, sum, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { evolve, frontOf, sweep, type EvaluationRow, type Measure, type Objective, type SweepCounts } from \"@mark1russell7/strategy-search\";\nimport { spaceSize, STRATEGY_SPACE_SCHEMA, type SpaceParam, type StrategyConfig, type StrategySpace } from \"@mark1russell7/strategy-space\";\nimport { compile, isFieldName, parse, space, type AnyDomain, type Program } from \"@mark1russell7/vex\";\nimport { BoolDomain, NumDomain, TextDomain } from \"@mark1russell7/vex-domains\";\nimport { z } from \"zod\";\nimport { offersOfPart, priceOf, type Observation, type PartWant, type Priced } from \"./offers.ts\";\nimport { CONDITIONS, textSchema, type Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy plan. A need names the slots of a purchase, the parts that can fill each slot, and\n * the measures and the rules of a basket as Vex programs. The plan searches the baskets with strategy-search, and it\n * gives the front of the price against the measures. The module knows no part class: the facts of each part and the\n * programs come from the need. Each function of this module is a calculation with no effect.\n */\n\n/** The format name of a need record. */\nexport const NEED_FORMAT = \"buy-need/1\";\n\n/** The format name of a plan record. */\nexport const PLAN_FORMAT = \"buy-plan/1\";\n\n/** The key of the inputs of a need in the space of a basket. A slot cannot have this name. */\nexport const NEED_KEY = \"need\";\n\n/** The fields that the plan writes in the record of each slot. A fact of a part cannot have one of these names. */\nexport const SLOT_FIELDS = [\"slot\", \"part\", \"count\", \"cost\"] as const;\n\n/** The largest count of evaluations of a plan, when the options do not give a count. */\nexport const PLAN_EVALUATIONS = 2000;\n\n/** The domains of the programs of a need: numbers, booleans and texts. */\nconst DOMAINS: readonly AnyDomain[] = [NumDomain, BoolDomain, TextDomain];\n\n/** A fact of a part, or an input of a need: a number, a text or a boolean. */\nexport type Fact = number | string | boolean;\n\n/** One part that can fill a slot: its key in the slot, the part that the offers must match, and its facts. */\nexport interface NeedPart {\n readonly key: string;\n readonly want: PartWant;\n /** The facts of the part that the programs read, for example its watts. */\n readonly facts?: Readonly<Record<string, Fact>> | undefined;\n}\n\n/** The count of units of a slot. With `min` 0, a basket can leave the slot empty. */\nexport interface SlotCount {\n readonly min: number;\n readonly max: number;\n}\n\n/** One slot of a need: its name, the parts that can fill it, and the count of its units. The default count is 1. */\nexport interface NeedSlot {\n readonly name: string;\n readonly parts: readonly NeedPart[];\n readonly count?: SlotCount | undefined;\n}\n\n/**\n * One measure of a basket: a Vex program that gives a number. With `goal`, the measure is an objective of the search.\n * A value below `min` or above `max` breaks the basket.\n */\nexport interface NeedMeasure {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n readonly goal?: \"min\" | \"max\" | undefined;\n /** The unit of the values, as text for a reader. */\n readonly unit?: string | undefined;\n readonly min?: number | undefined;\n readonly max?: number | undefined;\n}\n\n/** One rule of a basket: a Vex program that gives `true` when the basket keeps the rule. */\nexport interface NeedRule {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n}\n\n/** This record is a need: the currency and the conditions of the offers, the inputs, the slots, the measures and the rules. */\nexport interface BuyNeed {\n readonly format: typeof NEED_FORMAT;\n readonly id: string;\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n /** The inputs that the programs read at the key `need`, for example the load in watts. */\n readonly inputs?: Readonly<Record<string, Fact>> | undefined;\n readonly slots: readonly NeedSlot[];\n readonly measures?: readonly NeedMeasure[] | undefined;\n readonly rules?: readonly NeedRule[] | undefined;\n}\n\nconst factSchema: z.ZodType<Fact> = z.union([z.number().refine(Number.isFinite, \"The number is not finite.\"), z.string(), z.boolean()]);\nconst factsSchema: z.ZodType<Readonly<Record<string, Fact>>> = z.record(textSchema, factSchema);\nconst wantSchema: z.ZodType<PartWant> = z.strictObject({ brands: z.array(textSchema).min(1), partNumbers: z.array(textSchema).min(1) });\nconst wholeSchema = z.number().int().nonnegative();\n\n/** This schema accepts the form of a need. `needProblems` examines the names, the counts and the programs. */\nexport const buyNeedSchema: z.ZodType<BuyNeed> = z.strictObject({\n format: z.literal(NEED_FORMAT),\n id: textSchema,\n currency: textSchema,\n conditions: z.array(z.enum(CONDITIONS)).min(1).optional(),\n inputs: factsSchema.optional(),\n slots: z\n .array(\n z.strictObject({\n name: textSchema,\n parts: z.array(z.strictObject({ key: textSchema, want: wantSchema, facts: factsSchema.optional() })).min(1),\n count: z.strictObject({ min: wholeSchema, max: wholeSchema }).optional(),\n }),\n )\n .min(1),\n measures: z\n .array(\n z.strictObject({\n name: textSchema,\n program: z.unknown(),\n goal: z.enum([\"min\", \"max\"]).optional(),\n unit: textSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n )\n .optional(),\n rules: z.array(z.strictObject({ name: textSchema, program: z.unknown() })).optional(),\n});\n\n/** This function gives the count of a slot, with the default 1 to 1. */\nfunction countOf(slot: NeedSlot): SlotCount {\n return slot.count ?? { min: 1, max: 1 };\n}\n\n/** This function reads a program of a need. It gives the expression, or the reason that the program is not valid. */\nfunction readProgram(program: unknown): { readonly ok: true; readonly program: Program } | { readonly ok: false; readonly why: string } {\n const text = program === undefined ? undefined : JSON.stringify(program);\n if (text === undefined) return { ok: false, why: \"The program is missing.\" };\n const read = parse(text, DOMAINS);\n return read.ok ? { ok: true, program: compile(read.value, { domains: DOMAINS }) } : { ok: false, why: read.error.message };\n}\n\n/** This function compiles a program that `needProblems` accepts. */\nfunction programOf(program: unknown): Program {\n const read = readProgram(program);\n if (!read.ok) throw new RangeError(read.why);\n return read.program;\n}\n\n/**\n * This function gives the problems of a need. Two slots, parts, measures or rules with one name are a problem. A bad\n * count is a problem. The slot name `need` and the measure name `price` are problems. A fact with the name of a field\n * of a slot is a problem. A program that is not valid is a problem.\n */\nexport function needProblems(need: BuyNeed): string[] {\n const problems: string[] = [];\n const twice = (names: readonly string[], what: string): void => {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) problems.push(`Two ${what} have the name ${name}.`);\n seen.add(name);\n }\n };\n twice(\n need.slots.map((slot) => slot.name),\n \"slots\",\n );\n for (const name of Object.keys(need.inputs ?? {})) if (!isFieldName(name)) problems.push(`The input ${name} is not a name of a field.`);\n for (const slot of need.slots) {\n if (slot.name === NEED_KEY) problems.push(`The slot ${NEED_KEY} has the name of the inputs.`);\n else if (!isFieldName(slot.name)) problems.push(`The slot ${slot.name} is not a name of a field.`);\n twice(\n slot.parts.map((part) => part.key),\n `parts of the slot ${slot.name}`,\n );\n const { min, max } = countOf(slot);\n if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min < 0 || max < 1 || min > max)\n problems.push(`The count of the slot ${slot.name} is ${String(min)} to ${String(max)}. It must be whole numbers, with a maximum of 1 or more and not below the minimum.`);\n for (const part of slot.parts) {\n for (const name of Object.keys(part.facts ?? {})) {\n if ((SLOT_FIELDS as readonly string[]).includes(name)) problems.push(`The part ${part.key} of the slot ${slot.name} has the fact ${name}, which is a field of the slot.`);\n else if (!isFieldName(name)) problems.push(`The fact ${name} of the part ${part.key} is not a name of a field.`);\n }\n }\n }\n const measures = need.measures ?? [];\n const rules = need.rules ?? [];\n twice(\n measures.map((measure) => measure.name),\n \"measures\",\n );\n twice(\n rules.map((rule) => rule.name),\n \"rules\",\n );\n for (const measure of measures) {\n if (measure.name === \"price\") problems.push(\"A measure has the name price, which is the objective of the cost.\");\n if (measure.min !== undefined && measure.max !== undefined && measure.min > measure.max) problems.push(`The measure ${measure.name} has a minimum above its maximum.`);\n const read = readProgram(measure.program);\n if (!read.ok) problems.push(`The program of the measure ${measure.name} is not valid: ${read.why}`);\n }\n for (const rule of rules) {\n const read = readProgram(rule.program);\n if (!read.ok) problems.push(`The program of the rule ${rule.name} is not valid: ${read.why}`);\n }\n return problems;\n}\n\n/** This record is one item of a basket: the slot, the part, the count, the offer to buy and the cost with the shipping. */\nexport interface BuyItem {\n readonly slot: string;\n readonly part: string;\n readonly count: number;\n readonly offerId: string;\n readonly cost: Quantity;\n}\n\n/** This record is one basket of the front: its config id, its price, the value of each measure and its items. */\nexport interface BuyChoice {\n readonly config: string;\n /** The sum of the cost of each item. Each item is one order, with its own shipping. */\n readonly price: Quantity;\n readonly values: Readonly<Record<string, number>>;\n readonly items: readonly BuyItem[];\n}\n\n/** This record counts the baskets that break one constraint, with the reason of the first such basket. */\nexport interface BuyBreak {\n /** The constraint: `price:<slot>`, `measure:<name>`, `limit:<name>` or `rule:<name>`. */\n readonly name: string;\n readonly count: number;\n readonly why: string;\n}\n\n/** This record is a part that no basket can have, because no offer of the part is usable at a count of its slot. */\nexport interface UnpricedPart {\n readonly slot: string;\n readonly part: string;\n readonly why: string;\n}\n\n/** This record is a buy plan: the method of the search, its counts, the front of the baskets and the reasons of the breaks. */\nexport interface BuyPlan {\n readonly format: typeof PLAN_FORMAT;\n /** The id of the need. */\n readonly need: string;\n readonly currency: string;\n /** `grid` evaluates each basket. `evolve` is a genetic search. `none` tells that a slot that must have a part has no part with an offer. */\n readonly method: \"grid\" | \"evolve\" | \"none\";\n /** The seed of a genetic search, or null. */\n readonly seed: number | null;\n /** The id of the run of strategy-search, or null for `none`. */\n readonly run: string | null;\n readonly objectives: readonly Objective[];\n readonly counts: SweepCounts;\n /** The baskets on the Pareto front, from the lowest price. Equal prices go in the order of the config id. */\n readonly front: readonly BuyChoice[];\n /** The constraints that the evaluated baskets break, in the order of their names. */\n readonly breaks: readonly BuyBreak[];\n /** The parts with no usable offer, in the order of the slots and of their parts. */\n readonly unpriced: readonly UnpricedPart[];\n}\n\nexport { buyCandidates, orderBuys, type BuyCandidate, type BuyCandidates, type BuyOrder, type CandidateOptions, type OrderBuy, type OrderOptions, type OrderStage, type OrderStageResult, type ProductWant } from \"./order.ts\";\n\n/** These options change the search of a plan. */\nexport interface PlanOptions {\n /** The largest count of evaluations. A space with no more baskets gets a grid of each basket. The default is `PLAN_EVALUATIONS`. */\n readonly evaluations?: number | undefined;\n /** The seed of a genetic search. The default is the id of the need. */\n readonly seed?: number | string | undefined;\n /** The count of the baskets of a generation of a genetic search. The default is the default of strategy-search. */\n readonly population?: number | undefined;\n}\n\n\n/** The breaks, the values and the items of one basket. */\ninterface Assessed {\n readonly breaks: readonly { readonly name: string; readonly why: string }[];\n readonly values: Readonly<Record<string, number>>;\n readonly price: Quantity | null;\n readonly items: readonly BuyItem[];\n}\n\n\n/**\n * This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy\n * space. Each part with a usable offer is an option of its stage, with a param `count`. The price of a basket is the sum\n * of the cost of each item.\n *\n * Each measure and each rule is a Vex program that evaluates at the key `need` of a record space. The key `need` has\n * the inputs. The key of each slot has the facts of its part, `slot`, `part`, `count` and `cost`. A slot with no part\n * has only `slot`, the count 0 and the cost 0. Thus the axis `others` gives the slots.\n *\n * A space with no more baskets than `evaluations` gets a grid of each basket, and a larger space gets a genetic search.\n *\n * @throws RangeError when the need or its currency is not valid, or when `evaluations` is not a whole number of 1 or more.\n * The function also throws a RangeError when strategy-search refuses the options.\n */\nexport function planBuys(need: BuyNeed, observations: readonly Observation[], options: PlanOptions = {}): BuyPlan {\n const shape = buyNeedSchema.safeParse(need);\n if (!shape.success) throw new RangeError(`The need is not valid: ${shape.error.issues.map((issue) => `${issue.path.join(\".\")}: ${issue.message}`).join(\" \")}`);\n const problems = needProblems(need);\n if (problems.length > 0) throw new RangeError(`The need is not valid: ${problems.join(\" \")}`);\n const evaluations = options.evaluations ?? PLAN_EVALUATIONS;\n if (!Number.isSafeInteger(evaluations) || evaluations < 1) throw new RangeError(`The count of evaluations ${String(evaluations)} is not a whole number of 1 or more.`);\n\n const measures = (need.measures ?? []).map((measure) => ({ measure, program: programOf(measure.program) }));\n const rules = (need.rules ?? []).map((rule) => ({ rule, program: programOf(rule.program) }));\n const objectives: Objective[] = [\n { name: \"price\", goal: \"min\", unit: need.currency },\n ...measures.flatMap(({ measure }) => (measure.goal === undefined ? [] : [measure.unit === undefined ? { name: measure.name, goal: measure.goal } : { name: measure.name, goal: measure.goal, unit: measure.unit }])),\n ];\n\n // The price of each count of each part, once. A part with no usable offer at any count is not an option.\n const prices = new Map<string, Map<number, Priced>>();\n const unpriced: UnpricedPart[] = [];\n const stages: StrategySpace[\"stages\"][number][] = [];\n let blocked = false;\n for (const slot of need.slots) {\n const { min, max } = countOf(slot);\n const low = Math.max(1, min);\n const params: SpaceParam[] = max > low ? [{ name: \"count\", kind: \"int\", min: low, max, default: low }] : [];\n const usable: string[] = [];\n for (const part of slot.parts) {\n const offers = offersOfPart(observations, part.want);\n const byCount = new Map<number, Priced>();\n for (let count = low; count <= max; count++) byCount.set(count, priceOf(offers, count, need));\n prices.set(`${slot.name}\\u0000${part.key}`, byCount);\n const first = byCount.get(low);\n if ([...byCount.values()].some((priced) => priced.ok)) usable.push(part.key);\n else unpriced.push({ slot: slot.name, part: part.key, why: first === undefined || first.ok ? \"No offer is usable.\" : first.why });\n }\n if (usable.length > 0) stages.push({ name: slot.name, options: usable.map((id) => ({ id, params })), ...(min === 0 ? { optional: true } : {}) });\n else if (min > 0) blocked = true;\n }\n const none: BuyPlan = { format: PLAN_FORMAT, need: need.id, currency: need.currency, method: \"none\", seed: null, run: null, objectives, counts: { feasible: 0, breaks: 0, unread: 0, front: 0 }, front: [], breaks: [], unpriced };\n if (blocked || stages.length === 0) return none;\n\n const strategySpace: StrategySpace = { schema: STRATEGY_SPACE_SCHEMA, engine: \"buy-plan\", version: \"1\", stages };\n\n const assess = (config: StrategyConfig): Assessed => {\n const breaks: { name: string; why: string }[] = [];\n const items: BuyItem[] = [];\n const records: Record<string, Readonly<Record<string, Fact>>> = { [NEED_KEY]: need.inputs ?? {} };\n for (const slot of need.slots) {\n const choice = config.stages[slot.name] ?? null;\n if (choice === null) {\n records[slot.name] = { slot: slot.name, count: 0, cost: 0 };\n continue;\n }\n const part = slot.parts.find((each) => each.key === choice.option) as NeedPart;\n const count = Number(choice.params?.[\"count\"] ?? Math.max(1, countOf(slot).min));\n const priced = prices.get(`${slot.name}\\u0000${part.key}`)?.get(count) ?? { ok: false, why: `The count ${String(count)} is not a count of the slot.` };\n if (!priced.ok) {\n breaks.push({ name: `price:${slot.name}`, why: `The part ${part.key} of the slot ${slot.name}: ${priced.why}` });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: 0 };\n continue;\n }\n items.push({ slot: slot.name, part: part.key, count, offerId: priced.offerId, cost: priced.cost });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: valueIn(priced.cost, need.currency) };\n }\n const price = breaks.length > 0 ? null : sum(items.map((item) => item.cost), need.currency);\n const values: Record<string, number> = price === null ? {} : { price: valueIn(price, need.currency) };\n const basket = space.record(records);\n for (const { measure, program } of measures) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `measure:${measure.name}`, why: result.error.message });\n else if (typeof result.value !== \"number\" || !Number.isFinite(result.value)) breaks.push({ name: `measure:${measure.name}`, why: `The value ${String(result.value)} is not a finite number.` });\n else {\n values[measure.name] = result.value;\n if (measure.min !== undefined && result.value < measure.min) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is below the minimum ${String(measure.min)}.` });\n if (measure.max !== undefined && result.value > measure.max) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is above the maximum ${String(measure.max)}.` });\n }\n }\n for (const { rule, program } of rules) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `rule:${rule.name}`, why: result.error.message });\n else if (result.value !== true) breaks.push({ name: `rule:${rule.name}`, why: result.value === false ? \"The basket breaks the rule.\" : `The value ${String(result.value)} is not a boolean.` });\n }\n return { breaks, values, price, items };\n };\n\n // The reason of the first basket that breaks each constraint.\n const firstWhy = new Map<string, string>();\n const evaluate = (config: StrategyConfig): Measure => {\n const assessed = assess(config);\n for (const { name, why } of assessed.breaks) if (!firstWhy.has(name)) firstWhy.set(name, why);\n return { breaks: [...new Set(assessed.breaks.map((each) => each.name))], values: assessed.values };\n };\n\n const levels = Math.max(1, ...need.slots.map((slot) => countOf(slot).max - Math.max(1, countOf(slot).min) + 1));\n const grid = spaceSize(strategySpace, { levels }).base <= BigInt(evaluations);\n const evaluator = `buy-need:${need.id}`;\n const run = grid\n ? sweep(strategySpace, { objectives, evaluate, enumerate: { mode: \"grid\", levels, limit: evaluations }, evaluator })\n : evolve(strategySpace, {\n objectives,\n evaluate,\n seed: options.seed ?? need.id,\n evaluations,\n ...(options.population === undefined ? {} : { population: options.population }),\n evaluator,\n });\n\n const front = frontOf(run)\n .map(({ row, config }): BuyChoice => {\n const assessed = assess(config);\n const values = Object.fromEntries(Object.entries(assessed.values).filter(([name]) => name !== \"price\"));\n return { config: row.config, price: assessed.price as Quantity, values, items: assessed.items };\n })\n .sort((a, b) => compare(a.price, b.price) || (a.config < b.config ? -1 : a.config > b.config ? 1 : 0));\n return {\n ...none,\n method: grid ? \"grid\" : \"evolve\",\n seed: run.seed,\n run: run.run,\n counts: run.counts,\n front,\n breaks: breaksOf(run.rows, firstWhy),\n unpriced,\n };\n}\n\n/** This function counts the rows that break each constraint, in the order of the names. */\nfunction breaksOf(rows: readonly EvaluationRow[], firstWhy: ReadonlyMap<string, string>): BuyBreak[] {\n const counts = new Map<string, number>();\n for (const row of rows) for (const name of row.breaks) counts.set(name, (counts.get(name) ?? 0) + 1);\n return [...counts.entries()]\n .sort(([a], [b]) => (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 : 0;
|
|
196
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the
|
|
199
|
+
* shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.
|
|
200
|
+
*/
|
|
201
|
+
function priceOf(observations, count, need) {
|
|
202
|
+
const choice = bestOffer(observations, {
|
|
203
|
+
currency: need.currency,
|
|
204
|
+
count,
|
|
205
|
+
...need.conditions === void 0 ? {} : { conditions: need.conditions }
|
|
206
|
+
});
|
|
207
|
+
let pick;
|
|
208
|
+
for (const offer of choice.offers) {
|
|
209
|
+
const cost = offer.cost;
|
|
210
|
+
if (offer.inStock && cost !== null && (pick === void 0 || compare(cost, pick.cost) < 0)) pick = {
|
|
211
|
+
...offer,
|
|
212
|
+
cost
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
if (pick !== void 0) return {
|
|
216
|
+
ok: true,
|
|
217
|
+
offerId: pick.observation.offer.id,
|
|
218
|
+
cost: pick.cost
|
|
219
|
+
};
|
|
220
|
+
if (choice.offers.length > 0) return {
|
|
221
|
+
ok: false,
|
|
222
|
+
why: `No offer of ${String(count)} units is in stock with a known cost.`
|
|
223
|
+
};
|
|
224
|
+
const first = choice.skipped[0];
|
|
225
|
+
return {
|
|
226
|
+
ok: false,
|
|
227
|
+
why: first === void 0 ? "No offer matches the part." : `No offer is usable. The first offer that the choice skipped: ${first.why}`
|
|
228
|
+
};
|
|
229
|
+
}
|
|
197
230
|
// src/records.ts
|
|
198
231
|
/**
|
|
199
232
|
* The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
|
|
@@ -341,6 +374,6 @@ const priceReadingSchema = z.strictObject({
|
|
|
341
374
|
path: ["available"]
|
|
342
375
|
});
|
|
343
376
|
});
|
|
344
|
-
export {
|
|
377
|
+
export { priceOf as C, matchKeys as D, foldCode as E, gtinCheckDigit as O, offersPart as S, unitPriceFor as T, specSchema as _, instantSchema as a, latestObservations as b, offerSchema as c, priceReadingSchema as d, productSchema as f, sourceSchema as g, sourceOfOffer as h, gtinSchema as i, parseGtin as k, partNumberSchema as l, shippingSchema as m, CONDITIONS as n, moneySchema as o, sellerSchema as p, FORMATS as r, offerId as s, AVAILABILITIES as t, priceBreakSchema as u, textSchema as v, costOf as w, offersOfPart as x, bestOffer as y };
|
|
345
378
|
|
|
346
|
-
//# sourceMappingURL=records-
|
|
379
|
+
//# sourceMappingURL=records-DU5uvTYJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"records-DU5uvTYJ.js","names":[],"sources":["../src/gtin.ts","../src/identifiers.ts","../src/price.ts","../src/offers.ts","../src/records.ts"],"sourcesContent":["/**\n * This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.\n * The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.\n */\n\nconst LENGTHS: ReadonlySet<number> = new Set([8, 12, 13, 14]);\n\n/**\n * This function gives the check digit of the digits of a GTIN without its last digit.\n *\n * @throws RangeError when the text has a character that is not a digit, or no character.\n */\nexport function gtinCheckDigit(body: string): number {\n if (!/^\\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);\n let total = 0;\n for (let i = 0; i < body.length; i += 1) {\n const digit = body.charCodeAt(body.length - 1 - i) - 48;\n total += i % 2 === 0 ? digit * 3 : digit;\n }\n return (10 - (total % 10)) % 10;\n}\n\n/**\n * This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.\n * It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.\n */\nexport function parseGtin(text: string): string | null {\n const digits = text.replace(/[\\s-]/g, \"\");\n if (!/^\\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;\n if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;\n return digits.padStart(14, \"0\");\n}\n","import { parseGtin } from \"./gtin.ts\";\n\n/** A part number of a maker: the brand, and the number that the maker gives to the part. */\nexport interface PartNumber {\n readonly brand: string;\n readonly partNumber: string;\n}\n\n/** The identifiers of a product or of an offer. */\nexport interface Identifiers {\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n}\n\n/**\n * This function folds a brand or a part number for a comparison. The result has only capital letters A to Z\n * and digits. Thus `MZ-V8V1T0B/AM` and `mzv8v1t0bam` fold to one text.\n */\nexport function foldCode(text: string): string {\n return text.normalize(\"NFKD\").toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n}\n\n/**\n * This function gives the match keys of a record, sorted and with no copy. A key is `gtin:` with the GTIN-14,\n * or `part:` with the folded brand and part number. Two records with a key in common name one product.\n * The function ignores a GTIN that is not valid, and a part number whose brand or number folds to no text.\n */\nexport function matchKeys(identifiers: Identifiers): string[] {\n const keys = new Set<string>();\n for (const text of identifiers.gtins) {\n const gtin = parseGtin(text);\n if (gtin !== null) keys.add(`gtin:${gtin}`);\n }\n for (const { brand, partNumber } of identifiers.partNumbers) {\n const folded = [foldCode(brand), foldCode(partNumber)];\n if (folded.every((part) => part !== \"\")) keys.add(`part:${folded.join(\"/\")}`);\n }\n return [...keys].sort();\n}\n","import { add, scale, type Quantity } from \"@mark1russell7/quantity\";\nimport type { PriceReading } from \"./records.ts\";\n\n/**\n * This function gives the unit price for an order of `count` units. The price of the largest break at or\n * below the count applies, or the price of the reading when no break applies.\n *\n * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.\n */\nexport function unitPriceFor(reading: PriceReading, count: number): Quantity {\n const minimum = reading.minimumQuantity ?? 1;\n if (!Number.isSafeInteger(count) || count < minimum) {\n throw new RangeError(`The count ${count} is not a whole number of ${minimum} or more.`);\n }\n let price: Quantity = reading.price;\n for (const entry of reading.priceBreaks ?? []) if (entry.quantity <= count) price = entry.unitPrice;\n return price;\n}\n\n/**\n * This function gives the cost of an order of `count` units with its shipping, or null when the shipping\n * cost is not known. The cost is exact, and the function does not round it to the cent.\n *\n * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.\n */\nexport function costOf(reading: PriceReading, count: number): Quantity | null {\n const goods = scale(unitPriceFor(reading, count), count);\n switch (reading.shipping.kind) {\n case \"free\":\n return goods;\n case \"fixed\":\n return add(goods, reading.shipping.cost);\n default:\n return null;\n }\n}\n","import { compare, convert, convertible, kindOf, scale, UnitError, type Quantity } from \"@mark1russell7/quantity\";\nimport { foldCode } from \"./identifiers.ts\";\nimport { costOf, unitPriceFor } from \"./price.ts\";\nimport type { Condition, Offer, PriceReading } from \"./records.ts\";\n\n/** One offer of a source, and its price reading at one instant. */\nexport interface Observation {\n readonly offer: Offer;\n readonly reading: PriceReading;\n}\n\n/**\n * This record names a part that a buyer wants: the names of its maker, and its part numbers. A seller can write\n * the brand of one maker in more than one form, so the want has a list of names.\n */\nexport interface PartWant {\n /** The names of the maker, as the sellers write the brand. */\n readonly brands: readonly string[];\n /** The part numbers of the maker. A part number of an offer matches when it starts with one of them, after the fold. */\n readonly partNumbers: readonly string[];\n}\n\n/**\n * This function tells if an offer is an offer of the part. One part number of the offer must have a brand of the\n * want and start with a part number of the want. `foldCode` folds each text before the comparison. A part number\n * of another maker does not match: many makers use short numbers like `A1383`.\n */\nexport function offersPart(offer: Pick<Offer, \"partNumbers\">, want: PartWant): boolean {\n const brands = new Set(want.brands.map(foldCode).filter((brand) => brand !== \"\"));\n const parts = want.partNumbers.map(foldCode).filter((part) => part !== \"\");\n return offer.partNumbers.some(({ brand, partNumber }) => {\n const folded = foldCode(partNumber);\n return brands.has(foldCode(brand)) && parts.some((part) => folded.startsWith(part));\n });\n}\n\n/**\n * This function gives the latest observation of each offer, in the order of the offer ids. When two readings of\n * one offer have the same instant, the later one in the list applies.\n */\nexport function latestObservations(observations: readonly Observation[]): Observation[] {\n const latest = new Map<string, Observation>();\n for (const each of observations) {\n const seen = latest.get(each.offer.id);\n if (seen === undefined || Date.parse(seen.reading.at) <= Date.parse(each.reading.at)) latest.set(each.offer.id, each);\n }\n return [...latest.values()].sort((a, b) => order(a.offer.id, b.offer.id));\n}\n\n/** This function gives the latest observation of each offer of the part, in the order of the offer ids. */\nexport function offersOfPart(observations: readonly Observation[], want: PartWant): Observation[] {\n return latestObservations(observations.filter((each) => offersPart(each.offer, want)));\n}\n\n/** This record is one offer that a buyer can choose, with the price of an order in the currency of the buyer. */\nexport interface OfferChoice {\n readonly observation: Observation;\n /** The unit price for the count, times the count. */\n readonly goods: Quantity;\n /** The goods and the shipping, or null when the shipping cost is not known. */\n readonly cost: Quantity | null;\n /** True when the availability is `in-stock` or `low-stock`. */\n readonly inStock: boolean;\n}\n\n/** These options change the choice of an offer. */\nexport interface BestOfferOptions {\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. An offer with a price in another currency is skipped. */\n readonly currency: string;\n /** The count of units of the order. The default is 1. */\n readonly count?: number;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[];\n}\n\n/** This record is the choice of an offer: the best offer, each offer in the order of the price, and each skipped offer. */\nexport interface BestOffer {\n /** The offer with the lowest price that is in stock, or else the offer with the lowest price, or null with no offer. */\n readonly best: OfferChoice | null;\n /** The offers, from the lowest price of the goods. Equal prices go in the order of the cost, then of the offer id. */\n readonly offers: readonly OfferChoice[];\n /** The offers that the choice skipped, each with the reason. */\n readonly skipped: readonly { readonly offerId: string; readonly why: string }[];\n}\n\n/**\n * This function chooses the offer to buy from the latest observation of each offer. It skips an offer with a\n * condition that the buyer does not accept, a price in another currency, or a minimum above the count.\n *\n * @throws RangeError when the count is not a whole number of 1 or more, or when the currency is not a unit of money.\n */\nexport function bestOffer(observations: readonly Observation[], options: BestOfferOptions): BestOffer {\n const { currency, count = 1, conditions = [\"new\"] } = options;\n if (!Number.isSafeInteger(count) || count < 1) throw new RangeError(`The count ${count} is not a whole number of 1 or more.`);\n if (!isMoney(currency)) throw new RangeError(`The currency ${currency} is not a unit of money of @mark1russell7/quantity.`);\n const accepted = new Set<Condition>(conditions);\n const offers: OfferChoice[] = [];\n const skipped: { offerId: string; why: string }[] = [];\n for (const observation of latestObservations(observations)) {\n const { offer, reading } = observation;\n const minimum = reading.minimumQuantity ?? 1;\n if (!accepted.has(offer.condition)) skipped.push({ offerId: offer.id, why: `The condition ${offer.condition} is not a condition that the buyer accepts.` });\n else if (!converts(reading.price.unit, currency)) skipped.push({ offerId: offer.id, why: `The price is in ${reading.price.unit}, not in ${currency}.` });\n else if (count < minimum) skipped.push({ offerId: offer.id, why: `The minimum order is ${minimum} units, more than the count ${count}.` });\n else {\n const goods = convert(scale(unitPriceFor(reading, count), count), currency);\n // A shipping cost in another currency is not known in the currency of the buyer.\n const shipping = reading.shipping.kind !== \"fixed\" || converts(reading.shipping.cost.unit, currency);\n const total = shipping ? costOf(reading, count) : null;\n const cost = total === null ? null : convert(total, currency);\n const inStock = reading.availability === \"in-stock\" || reading.availability === \"low-stock\";\n offers.push({ observation, goods, cost, inStock });\n }\n }\n offers.sort((a, b) => compare(a.goods, b.goods) || byCost(a.cost, b.cost) || order(a.observation.offer.id, b.observation.offer.id));\n const best = offers.find((choice) => choice.inStock) ?? offers[0] ?? null;\n return { best, offers, skipped };\n}\n\n/** This function tells if a unit is a unit of money that the quantity package knows. */\nfunction isMoney(unit: string): boolean {\n try {\n return kindOf(unit) === \"money\";\n } catch (error) {\n if (error instanceof UnitError) return false;\n throw error;\n }\n}\n\n/** 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. */\nfunction converts(from: string, to: string): boolean {\n try {\n return convertible(from, to);\n } catch (error) {\n if (error instanceof UnitError) return false;\n throw error;\n }\n}\n\n/** This function orders two costs. A known cost comes before a cost that is not known. */\nfunction byCost(a: Quantity | null, b: Quantity | null): number {\n if (a === null || b === null) return a === b ? 0 : a === null ? 1 : -1;\n return compare(a, b);\n}\n\n/** This function orders two texts by their code units, so the order does not depend on the locale. */\nfunction order(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** The offer to buy for one count of a part, or the reason that no offer is usable. */\nexport type Priced = { readonly ok: true; readonly offerId: string; readonly cost: Quantity } | { readonly ok: false; readonly why: string };\n\n/**\n * This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the\n * shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.\n */\nexport function priceOf(observations: readonly Observation[], count: number, need: { readonly currency: string; readonly conditions?: readonly Condition[] | undefined }): Priced {\n const choice = bestOffer(observations, { currency: need.currency, count, ...(need.conditions === undefined ? {} : { conditions: need.conditions }) });\n let pick: (OfferChoice & { readonly cost: Quantity }) | undefined;\n for (const offer of choice.offers) {\n const cost = offer.cost;\n if (offer.inStock && cost !== null && (pick === undefined || compare(cost, pick.cost) < 0)) pick = { ...offer, cost };\n }\n if (pick !== undefined) return { ok: true, offerId: pick.observation.offer.id, cost: pick.cost };\n if (choice.offers.length > 0) return { ok: false, why: `No offer of ${String(count)} units is in stock with a known cost.` };\n const first = choice.skipped[0];\n return { ok: false, why: first === undefined ? \"No offer matches the part.\" : `No offer is usable. The first offer that the choice skipped: ${first.why}` };\n}\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { parseGtin } from \"./gtin.ts\";\nimport type { PartNumber } from \"./identifiers.ts\";\n\n/**\n * The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in\n * the field `grade` of the offer.\n */\nexport const CONDITIONS = [\"new\", \"open-box\", \"refurbished\", \"used\", \"for-parts\", \"unknown\"] as const;\n/** The condition of an offer. */\nexport type Condition = (typeof CONDITIONS)[number];\n\n/** The states of the stock of an offer at the time of a reading. */\nexport const AVAILABILITIES = [\"in-stock\", \"low-stock\", \"out-of-stock\", \"preorder\", \"unknown\"] as const;\n/** The state of the stock of an offer. */\nexport type Availability = (typeof AVAILABILITIES)[number];\n\n/** The buying formats of an offer. In an auction, the price of a reading is the current bid. */\nexport const FORMATS = [\"fixed-price\", \"auction\"] as const;\n/** The buying format of an offer. */\nexport type Format = (typeof FORMATS)[number];\n\n/** One specification of a product as text. */\nexport interface Spec {\n readonly name: string;\n readonly value: string;\n}\n\n/** The feedback of a seller: the percent of good feedback, and the count of the feedback. */\nexport interface Rating {\n readonly percent: number;\n readonly count: number;\n}\n\n/** A seller of an offer. A source gives some of these fields, or none. */\nexport interface Seller {\n readonly id?: string | undefined;\n readonly name?: string | undefined;\n readonly rating?: Rating | undefined;\n}\n\n/** A product of the catalog: one thing that a person can buy, with its identifiers and its specifications. */\nexport interface Product {\n readonly id: string;\n readonly title: string;\n readonly brand?: string | undefined;\n readonly category?: readonly string[] | undefined;\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n readonly specs: readonly Spec[];\n}\n\n/** An offer of a seller: one product at one seller, with the identifiers that the source gives. */\nexport interface Offer {\n readonly id: string;\n readonly source: string;\n readonly sourceId: string;\n readonly productId?: string | undefined;\n readonly title: string;\n readonly url?: string | undefined;\n readonly seller: Seller;\n readonly condition: Condition;\n readonly grade?: string | undefined;\n readonly format: Format;\n readonly endsAt?: string | undefined;\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n readonly specs: readonly Spec[];\n}\n\n/** The shipping of a reading. A calculated cost depends on the address of the buyer. */\nexport type Shipping =\n | { readonly kind: \"free\" }\n | { readonly kind: \"fixed\"; readonly cost: Quantity }\n | { readonly kind: \"calculated\" }\n | { readonly kind: \"unknown\" };\n\n/** A price break of a reading: the unit price for an order of `quantity` units or more. */\nexport interface PriceBreak {\n readonly quantity: number;\n readonly unitPrice: Quantity;\n}\n\n/** A price reading: the state of one offer at one instant. */\nexport interface PriceReading {\n readonly offerId: string;\n readonly at: string;\n readonly price: Quantity;\n readonly listPrice?: Quantity | undefined;\n readonly shipping: Shipping;\n readonly availability: Availability;\n readonly available?: number | undefined;\n readonly minimumQuantity?: number | undefined;\n readonly priceBreaks?: readonly PriceBreak[] | undefined;\n}\n\n/** This schema accepts a text with a character that is not a space, and with no space at an end. */\nexport const textSchema: z.ZodType<string> = z\n .string()\n .refine((text) => text !== \"\" && text === text.trim(), \"The text is empty, or it has a space at an end.\");\n\n/** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */\nexport const sourceSchema: z.ZodType<string> = z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/, \"The name of a source has small letters, digits and hyphens, with a letter first.\");\n\n/** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */\nexport const gtinSchema: z.ZodType<string> = z\n .string()\n .refine((text) => /^\\d{14}$/.test(text) && parseGtin(text) === text, \"The GTIN is not a GTIN-14 with a correct check digit.\");\n\n/** This schema accepts an amount of money of zero or more, for example `{ \"value\": 129.99, \"unit\": \"USD\" }`. */\nexport const moneySchema: z.ZodType<Quantity, Quantity> = quantitySchema(\"money\", { nonnegative: true });\n\n/** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */\nexport const instantSchema: z.ZodType<string> = z.iso.datetime();\n\n/** This schema accepts a part number of a maker. */\nexport const partNumberSchema: z.ZodType<PartNumber> = z.strictObject({ brand: textSchema, partNumber: textSchema });\n\n/** This schema accepts one specification as text, for example `{ \"name\": \"Capacity\", \"value\": \"1 TB\" }`. */\nexport const specSchema: z.ZodType<Spec> = z.strictObject({ name: textSchema, value: textSchema });\n\n/** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */\nexport const sellerSchema: z.ZodType<Seller> = z.strictObject({\n id: textSchema.optional(),\n name: textSchema.optional(),\n rating: z.strictObject({ percent: z.number().min(0).max(100), count: z.int().nonnegative() }).optional(),\n});\n\n/** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */\nexport const productSchema: z.ZodType<Product> = z.strictObject({\n id: textSchema,\n title: textSchema,\n brand: textSchema.optional(),\n category: z.array(textSchema).optional(),\n gtins: z.array(gtinSchema),\n partNumbers: z.array(partNumberSchema),\n specs: z.array(specSchema),\n});\n\n/** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */\nexport function offerId(source: string, sourceId: string): string {\n return `${source}:${sourceId}`;\n}\n\n/** This function gives the name of the source of an offer id: the text before the first colon. */\nexport function sourceOfOffer(id: string): string {\n const colon = id.indexOf(\":\");\n if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);\n return id.slice(0, colon);\n}\n\n/**\n * This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.\n * `productId` names the product of the catalog after a match.\n */\nexport const offerSchema: z.ZodType<Offer> = z\n .strictObject({\n id: textSchema,\n source: sourceSchema,\n sourceId: textSchema,\n productId: textSchema.optional(),\n title: textSchema,\n url: z.url({ protocol: /^https$/ }).optional(),\n seller: sellerSchema,\n condition: z.enum(CONDITIONS),\n grade: textSchema.optional(),\n format: z.enum(FORMATS),\n endsAt: instantSchema.optional(),\n gtins: z.array(gtinSchema),\n partNumbers: z.array(partNumberSchema),\n specs: z.array(specSchema),\n })\n .refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {\n message: \"The id of an offer is its source and its source id, with a colon between them.\",\n path: [\"id\"],\n });\n\n/** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */\nexport const shippingSchema: z.ZodType<Shipping> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"free\") }),\n z.strictObject({ kind: z.literal(\"fixed\"), cost: moneySchema }),\n z.strictObject({ kind: z.literal(\"calculated\") }),\n z.strictObject({ kind: z.literal(\"unknown\") }),\n]);\n\n/** This schema accepts a price break: the unit price for an order of `quantity` units or more. */\nexport const priceBreakSchema: z.ZodType<PriceBreak> = z.strictObject({ quantity: z.int().min(2), unitPrice: moneySchema });\n\n/**\n * This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an\n * order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more\n * than the minimum.\n */\nexport const priceReadingSchema: z.ZodType<PriceReading> = z\n .strictObject({\n offerId: textSchema,\n at: instantSchema,\n price: moneySchema,\n listPrice: moneySchema.optional(),\n shipping: shippingSchema,\n availability: z.enum(AVAILABILITIES),\n available: z.int().nonnegative().optional(),\n minimumQuantity: z.int().min(1).optional(),\n priceBreaks: z.array(priceBreakSchema).optional(),\n })\n .superRefine((reading, context) => {\n let last = reading.minimumQuantity ?? 1;\n for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {\n if (entry.quantity <= last) {\n context.addIssue({\n code: \"custom\",\n message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,\n path: [\"priceBreaks\", index, \"quantity\"],\n });\n }\n last = Math.max(last, entry.quantity);\n }\n const { availability, available } = reading;\n if (available === undefined || availability === \"unknown\" || availability === \"preorder\") return;\n if ((availability === \"out-of-stock\") !== (available === 0)) {\n context.addIssue({\n code: \"custom\",\n message: `The availability ${availability} does not agree with the count ${available}.`,\n path: [\"available\"],\n });\n }\n });\n"],"mappings":";;;;;;;;AAKA,MAAM,0BAA+B,IAAI,IAAI;CAAC;CAAG;CAAI;CAAI;AAAE,CAAC;;;;;;AAO5D,SAAgB,eAAe,MAAsB;CACnD,IAAI,CAAC,QAAQ,KAAK,IAAI,GAAG,MAAM,IAAI,WAAW,YAAY,KAAK,UAAU,IAAI,EAAE,4BAA4B;CAC3G,IAAI,QAAQ;CACZ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;EACvC,MAAM,QAAQ,KAAK,WAAW,KAAK,SAAS,IAAI,CAAC,IAAI;EACrD,SAAS,IAAI,MAAM,IAAI,QAAQ,IAAI;CACrC;CACA,QAAQ,KAAM,QAAQ,MAAO;AAC/B;;;;;AAMA,SAAgB,UAAU,MAA6B;CACrD,MAAM,SAAS,KAAK,QAAQ,UAAU,EAAE;CACxC,IAAI,CAAC,QAAQ,KAAK,MAAM,KAAK,CAAC,QAAQ,IAAI,OAAO,MAAM,KAAK,OAAO,KAAK,MAAM,GAAG,OAAO;CACxF,IAAI,eAAe,OAAO,MAAM,GAAG,EAAE,CAAC,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;CACP,WAAW,YAAY,SAAS;CAChC,UAAU;CACV,cAAc,EAAE,KAAK,cAAc;CACnC,WAAW,EAAE,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS;CAC1C,iBAAiB,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;CACzC,aAAa,EAAE,MAAM,gBAAgB,CAAC,CAAC,SAAS;AAClD,CAAC,CAAC,CACD,aAAa,SAAS,YAAY;CACjC,IAAI,OAAO,QAAQ,mBAAmB;CACtC,KAAK,MAAM,CAAC,OAAO,WAAW,QAAQ,eAAe,CAAC,EAAA,CAAG,QAAQ,GAAG;EAClE,IAAI,MAAM,YAAY,MACpB,QAAQ,SAAS;GACf,MAAM;GACN,SAAS,aAAa,MAAM,oBAAoB,MAAM,SAAS,2BAA2B,KAAK;GAC/F,MAAM;IAAC;IAAe;IAAO;GAAU;EACzC,CAAC;EAEH,OAAO,KAAK,IAAI,MAAM,MAAM,QAAQ;CACtC;CACA,MAAM,EAAE,cAAc,cAAc;CACpC,IAAI,cAAc,KAAA,KAAa,iBAAiB,aAAa,iBAAiB,YAAY;CAC1F,IAAK,iBAAiB,oBAAqB,cAAc,IACvD,QAAQ,SAAS;EACf,MAAM;EACN,SAAS,oBAAoB,aAAa,iCAAiC,UAAU;EACrF,MAAM,CAAC,WAAW;CACpB,CAAC;AAEL,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/market",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.6",
|
|
5
5
|
"description": "The records of a market: a product, an offer of a seller and a price reading, with their checks, the GTIN check, match keys, the cost of an order, the storage rules of a source, the best offer of a part, a board of current prices within the terms of each source, a buy plan: the Pareto front of the baskets of a need, and metered prices of cloud resources with tiers, free amounts, terms and their cost.",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"repository": {
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"@mark1russell7/quantity": "^0.4.0",
|
|
49
|
-
"@mark1russell7/strategy-search": "^0.1.
|
|
49
|
+
"@mark1russell7/strategy-search": "^0.1.2",
|
|
50
50
|
"@mark1russell7/strategy-space": "^0.1.0",
|
|
51
51
|
"@mark1russell7/vex": "^0.19.1",
|
|
52
52
|
"@mark1russell7/vex-domains": "^0.19.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"records-hK1UCmpm.js","names":[],"sources":["../src/gtin.ts","../src/identifiers.ts","../src/price.ts","../src/offers.ts","../src/records.ts"],"sourcesContent":["/**\n * This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.\n * The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.\n */\n\nconst LENGTHS: ReadonlySet<number> = new Set([8, 12, 13, 14]);\n\n/**\n * This function gives the check digit of the digits of a GTIN without its last digit.\n *\n * @throws RangeError when the text has a character that is not a digit, or no character.\n */\nexport function gtinCheckDigit(body: string): number {\n if (!/^\\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);\n let total = 0;\n for (let i = 0; i < body.length; i += 1) {\n const digit = body.charCodeAt(body.length - 1 - i) - 48;\n total += i % 2 === 0 ? digit * 3 : digit;\n }\n return (10 - (total % 10)) % 10;\n}\n\n/**\n * This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.\n * It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.\n */\nexport function parseGtin(text: string): string | null {\n const digits = text.replace(/[\\s-]/g, \"\");\n if (!/^\\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;\n if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;\n return digits.padStart(14, \"0\");\n}\n","import { parseGtin } from \"./gtin.ts\";\n\n/** A part number of a maker: the brand, and the number that the maker gives to the part. */\nexport interface PartNumber {\n readonly brand: string;\n readonly partNumber: string;\n}\n\n/** The identifiers of a product or of an offer. */\nexport interface Identifiers {\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n}\n\n/**\n * This function folds a brand or a part number for a comparison. The result has only capital letters A to Z\n * and digits. Thus `MZ-V8V1T0B/AM` and `mzv8v1t0bam` fold to one text.\n */\nexport function foldCode(text: string): string {\n return text.normalize(\"NFKD\").toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n}\n\n/**\n * This function gives the match keys of a record, sorted and with no copy. A key is `gtin:` with the GTIN-14,\n * or `part:` with the folded brand and part number. Two records with a key in common name one product.\n * The function ignores a GTIN that is not valid, and a part number whose brand or number folds to no text.\n */\nexport function matchKeys(identifiers: Identifiers): string[] {\n const keys = new Set<string>();\n for (const text of identifiers.gtins) {\n const gtin = parseGtin(text);\n if (gtin !== null) keys.add(`gtin:${gtin}`);\n }\n for (const { brand, partNumber } of identifiers.partNumbers) {\n const folded = [foldCode(brand), foldCode(partNumber)];\n if (folded.every((part) => part !== \"\")) keys.add(`part:${folded.join(\"/\")}`);\n }\n return [...keys].sort();\n}\n","import { add, scale, type Quantity } from \"@mark1russell7/quantity\";\nimport type { PriceReading } from \"./records.ts\";\n\n/**\n * This function gives the unit price for an order of `count` units. The price of the largest break at or\n * below the count applies, or the price of the reading when no break applies.\n *\n * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.\n */\nexport function unitPriceFor(reading: PriceReading, count: number): Quantity {\n const minimum = reading.minimumQuantity ?? 1;\n if (!Number.isSafeInteger(count) || count < minimum) {\n throw new RangeError(`The count ${count} is not a whole number of ${minimum} or more.`);\n }\n let price: Quantity = reading.price;\n for (const entry of reading.priceBreaks ?? []) if (entry.quantity <= count) price = entry.unitPrice;\n return price;\n}\n\n/**\n * This function gives the cost of an order of `count` units with its shipping, or null when the shipping\n * cost is not known. The cost is exact, and the function does not round it to the cent.\n *\n * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.\n */\nexport function costOf(reading: PriceReading, count: number): Quantity | null {\n const goods = scale(unitPriceFor(reading, count), count);\n switch (reading.shipping.kind) {\n case \"free\":\n return goods;\n case \"fixed\":\n return add(goods, reading.shipping.cost);\n default:\n return null;\n }\n}\n","import { compare, convert, convertible, kindOf, scale, UnitError, type Quantity } from \"@mark1russell7/quantity\";\nimport { foldCode } from \"./identifiers.ts\";\nimport { costOf, unitPriceFor } from \"./price.ts\";\nimport type { Condition, Offer, PriceReading } from \"./records.ts\";\n\n/** One offer of a source, and its price reading at one instant. */\nexport interface Observation {\n readonly offer: Offer;\n readonly reading: PriceReading;\n}\n\n/**\n * This record names a part that a buyer wants: the names of its maker, and its part numbers. A seller can write\n * the brand of one maker in more than one form, so the want has a list of names.\n */\nexport interface PartWant {\n /** The names of the maker, as the sellers write the brand. */\n readonly brands: readonly string[];\n /** The part numbers of the maker. A part number of an offer matches when it starts with one of them, after the fold. */\n readonly partNumbers: readonly string[];\n}\n\n/**\n * This function tells if an offer is an offer of the part. One part number of the offer must have a brand of the\n * want and start with a part number of the want. `foldCode` folds each text before the comparison. A part number\n * of another maker does not match: many makers use short numbers like `A1383`.\n */\nexport function offersPart(offer: Pick<Offer, \"partNumbers\">, want: PartWant): boolean {\n const brands = new Set(want.brands.map(foldCode).filter((brand) => brand !== \"\"));\n const parts = want.partNumbers.map(foldCode).filter((part) => part !== \"\");\n return offer.partNumbers.some(({ brand, partNumber }) => {\n const folded = foldCode(partNumber);\n return brands.has(foldCode(brand)) && parts.some((part) => folded.startsWith(part));\n });\n}\n\n/**\n * This function gives the latest observation of each offer, in the order of the offer ids. When two readings of\n * one offer have the same instant, the later one in the list applies.\n */\nexport function latestObservations(observations: readonly Observation[]): Observation[] {\n const latest = new Map<string, Observation>();\n for (const each of observations) {\n const seen = latest.get(each.offer.id);\n if (seen === undefined || Date.parse(seen.reading.at) <= Date.parse(each.reading.at)) latest.set(each.offer.id, each);\n }\n return [...latest.values()].sort((a, b) => order(a.offer.id, b.offer.id));\n}\n\n/** This function gives the latest observation of each offer of the part, in the order of the offer ids. */\nexport function offersOfPart(observations: readonly Observation[], want: PartWant): Observation[] {\n return latestObservations(observations.filter((each) => offersPart(each.offer, want)));\n}\n\n/** This record is one offer that a buyer can choose, with the price of an order in the currency of the buyer. */\nexport interface OfferChoice {\n readonly observation: Observation;\n /** The unit price for the count, times the count. */\n readonly goods: Quantity;\n /** The goods and the shipping, or null when the shipping cost is not known. */\n readonly cost: Quantity | null;\n /** True when the availability is `in-stock` or `low-stock`. */\n readonly inStock: boolean;\n}\n\n/** These options change the choice of an offer. */\nexport interface BestOfferOptions {\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. An offer with a price in another currency is skipped. */\n readonly currency: string;\n /** The count of units of the order. The default is 1. */\n readonly count?: number;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[];\n}\n\n/** This record is the choice of an offer: the best offer, each offer in the order of the price, and each skipped offer. */\nexport interface BestOffer {\n /** The offer with the lowest price that is in stock, or else the offer with the lowest price, or null with no offer. */\n readonly best: OfferChoice | null;\n /** The offers, from the lowest price of the goods. Equal prices go in the order of the cost, then of the offer id. */\n readonly offers: readonly OfferChoice[];\n /** The offers that the choice skipped, each with the reason. */\n readonly skipped: readonly { readonly offerId: string; readonly why: string }[];\n}\n\n/**\n * This function chooses the offer to buy from the latest observation of each offer. It skips an offer with a\n * condition that the buyer does not accept, a price in another currency, or a minimum above the count.\n *\n * @throws RangeError when the count is not a whole number of 1 or more, or when the currency is not a unit of money.\n */\nexport function bestOffer(observations: readonly Observation[], options: BestOfferOptions): BestOffer {\n const { currency, count = 1, conditions = [\"new\"] } = options;\n if (!Number.isSafeInteger(count) || count < 1) throw new RangeError(`The count ${count} is not a whole number of 1 or more.`);\n if (!isMoney(currency)) throw new RangeError(`The currency ${currency} is not a unit of money of @mark1russell7/quantity.`);\n const accepted = new Set<Condition>(conditions);\n const offers: OfferChoice[] = [];\n const skipped: { offerId: string; why: string }[] = [];\n for (const observation of latestObservations(observations)) {\n const { offer, reading } = observation;\n const minimum = reading.minimumQuantity ?? 1;\n if (!accepted.has(offer.condition)) skipped.push({ offerId: offer.id, why: `The condition ${offer.condition} is not a condition that the buyer accepts.` });\n else if (!converts(reading.price.unit, currency)) skipped.push({ offerId: offer.id, why: `The price is in ${reading.price.unit}, not in ${currency}.` });\n else if (count < minimum) skipped.push({ offerId: offer.id, why: `The minimum order is ${minimum} units, more than the count ${count}.` });\n else {\n const goods = convert(scale(unitPriceFor(reading, count), count), currency);\n // A shipping cost in another currency is not known in the currency of the buyer.\n const shipping = reading.shipping.kind !== \"fixed\" || converts(reading.shipping.cost.unit, currency);\n const total = shipping ? costOf(reading, count) : null;\n const cost = total === null ? null : convert(total, currency);\n const inStock = reading.availability === \"in-stock\" || reading.availability === \"low-stock\";\n offers.push({ observation, goods, cost, inStock });\n }\n }\n offers.sort((a, b) => compare(a.goods, b.goods) || byCost(a.cost, b.cost) || order(a.observation.offer.id, b.observation.offer.id));\n const best = offers.find((choice) => choice.inStock) ?? offers[0] ?? null;\n return { best, offers, skipped };\n}\n\n/** This function tells if a unit is a unit of money that the quantity package knows. */\nfunction isMoney(unit: string): boolean {\n try {\n return kindOf(unit) === \"money\";\n } catch (error) {\n if (error instanceof UnitError) return false;\n throw error;\n }\n}\n\n/** 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. */\nfunction converts(from: string, to: string): boolean {\n try {\n return convertible(from, to);\n } catch (error) {\n if (error instanceof UnitError) return false;\n throw error;\n }\n}\n\n/** This function orders two costs. A known cost comes before a cost that is not known. */\nfunction byCost(a: Quantity | null, b: Quantity | null): number {\n if (a === null || b === null) return a === b ? 0 : a === null ? 1 : -1;\n return compare(a, b);\n}\n\n/** This function orders two texts by their code units, so the order does not depend on the locale. */\nfunction order(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","import type { Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { parseGtin } from \"./gtin.ts\";\nimport type { PartNumber } from \"./identifiers.ts\";\n\n/**\n * The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in\n * the field `grade` of the offer.\n */\nexport const CONDITIONS = [\"new\", \"open-box\", \"refurbished\", \"used\", \"for-parts\", \"unknown\"] as const;\n/** The condition of an offer. */\nexport type Condition = (typeof CONDITIONS)[number];\n\n/** The states of the stock of an offer at the time of a reading. */\nexport const AVAILABILITIES = [\"in-stock\", \"low-stock\", \"out-of-stock\", \"preorder\", \"unknown\"] as const;\n/** The state of the stock of an offer. */\nexport type Availability = (typeof AVAILABILITIES)[number];\n\n/** The buying formats of an offer. In an auction, the price of a reading is the current bid. */\nexport const FORMATS = [\"fixed-price\", \"auction\"] as const;\n/** The buying format of an offer. */\nexport type Format = (typeof FORMATS)[number];\n\n/** One specification of a product as text. */\nexport interface Spec {\n readonly name: string;\n readonly value: string;\n}\n\n/** The feedback of a seller: the percent of good feedback, and the count of the feedback. */\nexport interface Rating {\n readonly percent: number;\n readonly count: number;\n}\n\n/** A seller of an offer. A source gives some of these fields, or none. */\nexport interface Seller {\n readonly id?: string | undefined;\n readonly name?: string | undefined;\n readonly rating?: Rating | undefined;\n}\n\n/** A product of the catalog: one thing that a person can buy, with its identifiers and its specifications. */\nexport interface Product {\n readonly id: string;\n readonly title: string;\n readonly brand?: string | undefined;\n readonly category?: readonly string[] | undefined;\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n readonly specs: readonly Spec[];\n}\n\n/** An offer of a seller: one product at one seller, with the identifiers that the source gives. */\nexport interface Offer {\n readonly id: string;\n readonly source: string;\n readonly sourceId: string;\n readonly productId?: string | undefined;\n readonly title: string;\n readonly url?: string | undefined;\n readonly seller: Seller;\n readonly condition: Condition;\n readonly grade?: string | undefined;\n readonly format: Format;\n readonly endsAt?: string | undefined;\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n readonly specs: readonly Spec[];\n}\n\n/** The shipping of a reading. A calculated cost depends on the address of the buyer. */\nexport type Shipping =\n | { readonly kind: \"free\" }\n | { readonly kind: \"fixed\"; readonly cost: Quantity }\n | { readonly kind: \"calculated\" }\n | { readonly kind: \"unknown\" };\n\n/** A price break of a reading: the unit price for an order of `quantity` units or more. */\nexport interface PriceBreak {\n readonly quantity: number;\n readonly unitPrice: Quantity;\n}\n\n/** A price reading: the state of one offer at one instant. */\nexport interface PriceReading {\n readonly offerId: string;\n readonly at: string;\n readonly price: Quantity;\n readonly listPrice?: Quantity | undefined;\n readonly shipping: Shipping;\n readonly availability: Availability;\n readonly available?: number | undefined;\n readonly minimumQuantity?: number | undefined;\n readonly priceBreaks?: readonly PriceBreak[] | undefined;\n}\n\n/** This schema accepts a text with a character that is not a space, and with no space at an end. */\nexport const textSchema: z.ZodType<string> = z\n .string()\n .refine((text) => text !== \"\" && text === text.trim(), \"The text is empty, or it has a space at an end.\");\n\n/** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */\nexport const sourceSchema: z.ZodType<string> = z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/, \"The name of a source has small letters, digits and hyphens, with a letter first.\");\n\n/** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */\nexport const gtinSchema: z.ZodType<string> = z\n .string()\n .refine((text) => /^\\d{14}$/.test(text) && parseGtin(text) === text, \"The GTIN is not a GTIN-14 with a correct check digit.\");\n\n/** This schema accepts an amount of money of zero or more, for example `{ \"value\": 129.99, \"unit\": \"USD\" }`. */\nexport const moneySchema: z.ZodType<Quantity, Quantity> = quantitySchema(\"money\", { nonnegative: true });\n\n/** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */\nexport const instantSchema: z.ZodType<string> = z.iso.datetime();\n\n/** This schema accepts a part number of a maker. */\nexport const partNumberSchema: z.ZodType<PartNumber> = z.strictObject({ brand: textSchema, partNumber: textSchema });\n\n/** This schema accepts one specification as text, for example `{ \"name\": \"Capacity\", \"value\": \"1 TB\" }`. */\nexport const specSchema: z.ZodType<Spec> = z.strictObject({ name: textSchema, value: textSchema });\n\n/** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */\nexport const sellerSchema: z.ZodType<Seller> = z.strictObject({\n id: textSchema.optional(),\n name: textSchema.optional(),\n rating: z.strictObject({ percent: z.number().min(0).max(100), count: z.int().nonnegative() }).optional(),\n});\n\n/** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */\nexport const productSchema: z.ZodType<Product> = z.strictObject({\n id: textSchema,\n title: textSchema,\n brand: textSchema.optional(),\n category: z.array(textSchema).optional(),\n gtins: z.array(gtinSchema),\n partNumbers: z.array(partNumberSchema),\n specs: z.array(specSchema),\n});\n\n/** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */\nexport function offerId(source: string, sourceId: string): string {\n return `${source}:${sourceId}`;\n}\n\n/** This function gives the name of the source of an offer id: the text before the first colon. */\nexport function sourceOfOffer(id: string): string {\n const colon = id.indexOf(\":\");\n if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);\n return id.slice(0, colon);\n}\n\n/**\n * This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.\n * `productId` names the product of the catalog after a match.\n */\nexport const offerSchema: z.ZodType<Offer> = z\n .strictObject({\n id: textSchema,\n source: sourceSchema,\n sourceId: textSchema,\n productId: textSchema.optional(),\n title: textSchema,\n url: z.url({ protocol: /^https$/ }).optional(),\n seller: sellerSchema,\n condition: z.enum(CONDITIONS),\n grade: textSchema.optional(),\n format: z.enum(FORMATS),\n endsAt: instantSchema.optional(),\n gtins: z.array(gtinSchema),\n partNumbers: z.array(partNumberSchema),\n specs: z.array(specSchema),\n })\n .refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {\n message: \"The id of an offer is its source and its source id, with a colon between them.\",\n path: [\"id\"],\n });\n\n/** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */\nexport const shippingSchema: z.ZodType<Shipping> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"free\") }),\n z.strictObject({ kind: z.literal(\"fixed\"), cost: moneySchema }),\n z.strictObject({ kind: z.literal(\"calculated\") }),\n z.strictObject({ kind: z.literal(\"unknown\") }),\n]);\n\n/** This schema accepts a price break: the unit price for an order of `quantity` units or more. */\nexport const priceBreakSchema: z.ZodType<PriceBreak> = z.strictObject({ quantity: z.int().min(2), unitPrice: moneySchema });\n\n/**\n * This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an\n * order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more\n * than the minimum.\n */\nexport const priceReadingSchema: z.ZodType<PriceReading> = z\n .strictObject({\n offerId: textSchema,\n at: instantSchema,\n price: moneySchema,\n listPrice: moneySchema.optional(),\n shipping: shippingSchema,\n availability: z.enum(AVAILABILITIES),\n available: z.int().nonnegative().optional(),\n minimumQuantity: z.int().min(1).optional(),\n priceBreaks: z.array(priceBreakSchema).optional(),\n })\n .superRefine((reading, context) => {\n let last = reading.minimumQuantity ?? 1;\n for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {\n if (entry.quantity <= last) {\n context.addIssue({\n code: \"custom\",\n message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,\n path: [\"priceBreaks\", index, \"quantity\"],\n });\n }\n last = Math.max(last, entry.quantity);\n }\n const { availability, available } = reading;\n if (available === undefined || availability === \"unknown\" || availability === \"preorder\") return;\n if ((availability === \"out-of-stock\") !== (available === 0)) {\n context.addIssue({\n code: \"custom\",\n message: `The availability ${availability} does not agree with the count ${available}.`,\n path: [\"available\"],\n });\n }\n });\n"],"mappings":";;;;;;;;AAKA,MAAM,0BAA+B,IAAI,IAAI;CAAC;CAAG;CAAI;CAAI;AAAE,CAAC;;;;;;AAO5D,SAAgB,eAAe,MAAsB;CACnD,IAAI,C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