@mark1russell7/market 0.1.4 → 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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/terms.ts","../src/board.ts"],"sourcesContent":["import { valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { sourceSchema, textSchema } from \"./records.ts\";\n\n/** The storage rule of a source, from its terms. */\nexport type Retention =\n | { readonly kind: \"keep\" }\n | { readonly kind: \"max-age\"; readonly age: Quantity }\n | { readonly kind: \"no-store\" };\n\n/** The rules of the terms of one source. */\nexport interface SourceTerms {\n readonly source: string;\n readonly retention: Retention;\n readonly deleteWhenEnded: boolean;\n readonly priceModel: boolean;\n readonly clause: string;\n}\n\n/**\n * This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the\n * time. With `max-age`, a store keeps a reading for `age` at most. With `no-store`, a reading serves one request.\n */\nexport const retentionSchema: z.ZodType<Retention> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"keep\") }),\n z.strictObject({ kind: z.literal(\"max-age\"), age: quantitySchema(\"time\", { positive: true }) }),\n z.strictObject({ kind: z.literal(\"no-store\") }),\n]);\n\n/**\n * This schema accepts the rules of the terms of one source. `deleteWhenEnded` deletes the readings of an offer\n * when the offer ends. `priceModel` permits a trend or a forecast of prices. `clause` names the text of the terms.\n */\nexport const sourceTermsSchema: z.ZodType<SourceTerms> = z.strictObject({\n source: sourceSchema,\n retention: retentionSchema,\n deleteWhenEnded: z.boolean(),\n priceModel: z.boolean(),\n clause: textSchema,\n});\n\n/**\n * This function gives the last instant at which a store keeps a reading, or null when the terms set no\n * limit. For a source with `no-store`, the instant is the instant of the reading.\n */\nexport function keepUntil(terms: SourceTerms, reading: { readonly at: string }): string | null {\n const { retention } = terms;\n if (retention.kind === \"keep\") return null;\n const at = Date.parse(reading.at);\n if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(reading.at)} is not an instant.`);\n if (retention.kind === \"no-store\") return new Date(at).toISOString();\n return new Date(at + Math.floor(valueIn(retention.age, \"ms\"))).toISOString();\n}\n\n/**\n * This function tells if a store keeps a reading at the instant `now`. A store keeps no reading of a source with\n * `no-store`, and no reading of an ended offer when the terms delete them.\n */\nexport function isKept(terms: SourceTerms, reading: { readonly at: string }, now: string, ended = false): boolean {\n if (ended && terms.deleteWhenEnded) return false;\n if (terms.retention.kind === \"no-store\") return false;\n const until = keepUntil(terms, reading);\n if (until === null) return true;\n const instant = Date.parse(now);\n if (Number.isNaN(instant)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);\n return instant <= Date.parse(until);\n}\n\n/** This function tells if the terms permit a stored history of the readings of a source. */\nexport function permitsHistory(terms: SourceTerms): boolean {\n return terms.retention.kind === \"keep\" && !terms.deleteWhenEnded;\n}\n\n/** This function tells if the terms permit a trend of the prices of a source: a history and a model of prices. */\nexport function permitsTrend(terms: SourceTerms): boolean {\n return permitsHistory(terms) && terms.priceModel;\n}\n","import { valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { latestObservations, type Observation } from \"./offers.ts\";\nimport { instantSchema, offerSchema, priceReadingSchema, sourceSchema, textSchema } from \"./records.ts\";\nimport { isKept, keepUntil, type SourceTerms } from \"./terms.ts\";\n\n/*\n * This module calculates a board of current prices. A watch reads its sources on a schedule. The board keeps the\n * last read of each entry of the watch, within the terms of each source. Each function of this module is a\n * calculation with no effect. A host does the reads and writes the board.\n */\n\n/** The format name of a board record. */\nexport const BOARD_FORMAT = \"price-board/1\";\n\n/** This schema accepts an observation: an offer, and a reading of that offer. */\nexport const observationSchema: z.ZodType<Observation> = z\n .strictObject({ offer: offerSchema, reading: priceReadingSchema })\n .refine((each) => each.reading.offerId === each.offer.id, { message: \"The reading is not a reading of the offer.\" });\n\n/** This record is the last read of one entry of a watch: the name of the entry, the instant, and the observations. */\nexport interface BoardRead {\n readonly name: string;\n readonly at: string;\n readonly observations: readonly Observation[];\n}\n\n/** This record is a board: the instant of its last settle, and the last read of each entry, in the order of the names. */\nexport interface Board {\n readonly format: typeof BOARD_FORMAT;\n readonly at: string;\n readonly reads: readonly BoardRead[];\n}\n\n/** This schema accepts the read of an entry. The read has one observation of each offer at most. */\nexport const boardReadSchema: z.ZodType<BoardRead> = z\n .strictObject({ name: textSchema, at: instantSchema, observations: z.array(observationSchema) })\n .refine((read) => new Set(read.observations.map((each) => each.offer.id)).size === read.observations.length, {\n message: \"The read has two observations of one offer.\",\n });\n\n/** This schema accepts a board. The board has one read of each entry at most. */\nexport const boardSchema: z.ZodType<Board> = z\n .strictObject({ format: z.literal(BOARD_FORMAT), at: instantSchema, reads: z.array(boardReadSchema) })\n .refine((board) => new Set(board.reads.map((each) => each.name)).size === board.reads.length, {\n message: \"The board has two reads of one entry.\",\n });\n\n/** This record is an offer that the store does not keep, with the reason. */\nexport interface Dropped {\n readonly offerId: string;\n readonly why: string;\n}\n\n/** These options give the rules of a store: the terms of each source, the instant, and the offers that ended. */\nexport interface KeepOptions {\n /** The terms of the sources. A store keeps no reading of a source without terms. */\n readonly terms: readonly SourceTerms[];\n /** The instant of the decision. */\n readonly now: string;\n /** The ids of the offers that ended, as their sources tell. An offer with `endsAt` at or before `now` also ended. */\n readonly ended?: readonly string[] | undefined;\n}\n\n/** This record is the decision of a store: the observations that it keeps, and each offer that it drops. */\nexport interface Kept {\n /** The latest observation of each kept offer, in the order of the offer ids. */\n readonly kept: readonly Observation[];\n /** Each dropped offer, in the order of the offer ids. */\n readonly dropped: readonly Dropped[];\n}\n\n/** This function gives the terms of each source by its name. Two terms of one source are a problem of the input. */\nfunction termsBySource(terms: readonly SourceTerms[]): ReadonlyMap<string, SourceTerms> {\n const map = new Map<string, SourceTerms>();\n for (const each of terms) {\n if (map.has(each.source)) throw new RangeError(`The terms of the source ${each.source} are in the list two times.`);\n map.set(each.source, each);\n }\n return map;\n}\n\n/** This function gives the text of an amount of time, for example `6 h`. */\nconst timeText = (age: Quantity): string => `${age.value} ${age.unit}`;\n\n/**\n * This function decides which observations a store keeps. It takes the latest observation of each offer. It keeps\n * an observation while the terms of its source permit it, and while its offer has not ended. A current price is\n * a price that a buyer can pay, so the store drops an ended offer for each source.\n *\n * `settleBoard` applies this function to each read of a board.\n *\n * @throws RangeError when `now` is not an instant, or when the terms have two entries for one source.\n */\nexport function keepObservations(observations: readonly Observation[], options: KeepOptions): Kept {\n const terms = termsBySource(options.terms);\n const now = Date.parse(options.now);\n if (Number.isNaN(now)) throw new RangeError(`The instant ${JSON.stringify(options.now)} is not an instant.`);\n const ended = new Set(options.ended ?? []);\n const kept: Observation[] = [];\n const dropped: Dropped[] = [];\n for (const observation of latestObservations(observations)) {\n const { offer, reading } = observation;\n const rules = terms.get(offer.source);\n const endsAt = offer.endsAt === undefined ? Number.NaN : Date.parse(offer.endsAt);\n const over = ended.has(offer.id) || endsAt <= now;\n if (rules === undefined) dropped.push({ offerId: offer.id, why: `The terms of the source ${offer.source} are not known, so a store keeps no reading of it.` });\n else if (rules.retention.kind === \"no-store\") dropped.push({ offerId: offer.id, why: `The terms of ${offer.source} permit no store: a reading serves one request.` });\n else if (over) {\n const rule = rules.deleteWhenEnded ? `, and the terms of ${offer.source} delete its readings` : \"\";\n dropped.push({ offerId: offer.id, why: `The offer ended${rule}.` });\n } else if (!isKept(rules, reading, options.now)) {\n const age = rules.retention.kind === \"max-age\" ? timeText(rules.retention.age) : \"\";\n dropped.push({ offerId: offer.id, why: `The reading of ${reading.at} passed the limit of ${age} of the terms of ${offer.source} at ${keepUntil(rules, reading)}.` });\n } else kept.push(observation);\n }\n return { kept, dropped };\n}\n\n/** These options give the rules of a settle: the rules of a store, and the names of the entries of the watch. */\nexport interface SettleOptions extends KeepOptions {\n /** The names of the entries of the watch. The board drops the read of each other name. With no list, it keeps each read. */\n readonly names?: readonly string[] | undefined;\n}\n\n/** This record is an offer that the board drops, with the name of the entry of its read. */\nexport interface BoardDrop extends Dropped {\n readonly entry: string;\n}\n\n/** This record is the result of a settle: the new board, and each offer that it dropped. */\nexport interface Settled {\n readonly board: Board;\n readonly dropped: readonly BoardDrop[];\n}\n\nconst byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/**\n * This function settles a board at `now`. A new read replaces the last read of its entry, so an offer that the new\n * read does not give leaves the read. Then `keepObservations` applies the terms to each read. The board drops the\n * read of an entry that the watch does not have. Write the new board in place of the old board.\n *\n * @param read - A new read of an entry, or none to settle the board alone\n * @throws RangeError when `now` is not an instant, or when the terms have two entries for one source.\n */\nexport function settleBoard(board: Board, options: SettleOptions, read?: BoardRead): Settled {\n const names = options.names === undefined ? undefined : new Set(options.names);\n const reads = new Map(board.reads.map((each) => [each.name, each]));\n if (read !== undefined) reads.set(read.name, read);\n const settled: BoardRead[] = [];\n const dropped: BoardDrop[] = [];\n for (const name of [...reads.keys()].sort(byText)) {\n const each = reads.get(name);\n if (each === undefined) continue;\n if (names !== undefined && !names.has(name)) {\n for (const gone of latestObservations(each.observations)) dropped.push({ entry: name, offerId: gone.offer.id, why: `The watch has no entry ${name}.` });\n continue;\n }\n const decision = keepObservations(each.observations, options);\n settled.push({ name, at: each.at, observations: decision.kept });\n for (const drop of decision.dropped) dropped.push({ entry: name, ...drop });\n }\n return { board: { format: BOARD_FORMAT, at: options.now, reads: settled }, dropped };\n}\n\n/**\n * This function gives the current observations of a board at `now`. Each is the latest observation of an offer over\n * the reads, while the terms of its source permit it. Give them to `offersOfPart` and `bestOffer`.\n */\nexport function boardObservations(board: Board, options: KeepOptions): Observation[] {\n return [...keepObservations(board.reads.flatMap((each) => each.observations), options).kept];\n}\n\n/** This function gives the instant of the last read of each entry of a board, by name, for `planReads`. */\nexport function lastReads(board: Board): Record<string, string> {\n return Object.fromEntries(board.reads.map((each) => [each.name, each.at]));\n}\n\n/** This record is one entry of a watch: a read of one source that repeats. */\nexport interface WatchEntry {\n /** The name of the entry. Each entry of a watch has its own name. */\n readonly name: string;\n /** The source of the read. */\n readonly source: string;\n /** The time from one read of the entry to the next, a time of `@mark1russell7/quantity`. */\n readonly every: Quantity;\n}\n\n/** This schema accepts an entry of a watch. */\nexport const watchEntrySchema: z.ZodType<WatchEntry> = z.strictObject({\n name: textSchema,\n source: sourceSchema,\n every: quantitySchema(\"time\", { positive: true }),\n});\n\n/** These options give the rules of a schedule: the terms of each source, and the slack of the loop. */\nexport interface ScheduleOptions {\n /** The terms of the sources. */\n readonly terms: readonly SourceTerms[];\n /**\n * The longest time from the instant of a due read to the instant that its reading is on the board. It is the\n * time between two passes of the loop, plus the longest pass.\n */\n readonly slack: Quantity;\n}\n\n/** This record is the interval of an entry, in milliseconds, or the reason that the entry has no interval. */\nexport type ReadInterval = { readonly ok: true; readonly ms: number } | { readonly ok: false; readonly why: string };\n\n/**\n * This function gives the time from one read of an entry to the next, in milliseconds. A reading of a source with\n * the limit `L` stays on the board until `L` after the read. The next reading arrives `slack` after the next read\n * is due, at most. Thus the interval is the shorter of `every` and `L - slack`. Then the board has a current\n * reading of the entry at each instant after its first read.\n */\nexport function readInterval(entry: WatchEntry, options: ScheduleOptions): ReadInterval {\n const terms = termsBySource(options.terms).get(entry.source);\n const every = valueIn(entry.every, \"ms\");\n if (!(every > 0)) return { ok: false, why: `The time every of the entry ${entry.name} is not more than 0.` };\n if (terms === undefined) return { ok: false, why: `The terms of the source ${entry.source} of the entry ${entry.name} are not known.` };\n const { retention } = terms;\n if (retention.kind === \"no-store\") return { ok: false, why: `The terms of ${entry.source} permit no store, so a watch cannot keep the prices of the entry ${entry.name}. Read the source for each request.` };\n if (retention.kind === \"keep\") return { ok: true, ms: every };\n const room = valueIn(retention.age, \"ms\") - valueIn(options.slack, \"ms\");\n if (!(room > 0)) return { ok: false, why: `The slack ${timeText(options.slack)} is not less than the limit ${timeText(retention.age)} of the terms of ${entry.source}, so the board has gaps in the prices of the entry ${entry.name}.` };\n return { ok: true, ms: Math.min(every, room) };\n}\n\n/** This function gives the problems of a watch: an entry with no interval, and two entries with one name. */\nexport function watchProblems(entries: readonly WatchEntry[], options: ScheduleOptions): string[] {\n const problems: string[] = [];\n const names = new Set<string>();\n for (const entry of entries) {\n if (names.has(entry.name)) problems.push(`Two entries have the name ${entry.name}.`);\n names.add(entry.name);\n const interval = readInterval(entry, options);\n if (!interval.ok) problems.push(interval.why);\n }\n return problems;\n}\n\n/** This record is the plan of one pass of a watch: the due entries, and the instant of the next due read. */\nexport interface ReadPlan {\n /** The names of the due entries, in the order of the entries. An entry with no read is due. */\n readonly due: readonly string[];\n /**\n * The names of the due entries, the entry that is due for the longest time first. An entry with no read comes\n * first. Entries that became due at the same instant keep the order of the entries. Read the entries in this order.\n * Then each due entry comes before the next read of a later due entry.\n */\n readonly queue: readonly string[];\n /** The first instant after `now` that an entry is due, or null when no entry has an interval. */\n readonly next: string | null;\n}\n\n/**\n * This function plans one pass of a watch. An entry is due when it has no last read, or when its interval has\n * passed since its last read. An entry with no interval is not due at any time. `watchProblems` gives its reason.\n *\n * @param last - The instant of the last read of each entry, by name\n * @throws RangeError when `now` or a last read is not an instant.\n */\nexport function planReads(entries: readonly WatchEntry[], last: Readonly<Record<string, string>>, now: string, options: ScheduleOptions): ReadPlan {\n const at = Date.parse(now);\n if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);\n const due: string[] = [];\n const since: { readonly name: string; readonly at: number }[] = [];\n let next = Number.POSITIVE_INFINITY;\n for (const entry of entries) {\n const interval = readInterval(entry, options);\n if (!interval.ok) continue;\n const before = Object.hasOwn(last, entry.name) ? last[entry.name] : undefined;\n const read = before === undefined ? Number.NaN : Date.parse(before);\n if (before !== undefined && Number.isNaN(read)) throw new RangeError(`The last read ${JSON.stringify(before)} of the entry ${entry.name} is not an instant.`);\n const isDue = Number.isNaN(read) || read + interval.ms <= at;\n if (isDue) {\n due.push(entry.name);\n since.push({ name: entry.name, at: Number.isNaN(read) ? Number.NEGATIVE_INFINITY : read + interval.ms });\n }\n // A planned read happens at `now`, so the next read of a due entry is one interval after `now`.\n next = Math.min(next, (isDue ? at : read) + interval.ms);\n }\n // The sort of an array is stable, so equal instants keep the order of the entries.\n const queue = since.sort((a, b) => a.at - b.at).map((each) => each.name);\n return { due, queue, next: Number.isFinite(next) ? new Date(next).toISOString() : null };\n}\n"],"mappings":";;;;;;;;;AAwBA,MAAa,kBAAwC,EAAE,mBAAmB,QAAQ;CAChF,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,MAAM,EAAE,CAAC;CAC1C,EAAE,aAAa;EAAE,MAAM,EAAE,QAAQ,SAAS;EAAG,KAAK,eAAe,QAAQ,EAAE,UAAU,KAAK,CAAC;CAAE,CAAC;CAC9F,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,UAAU,EAAE,CAAC;AAChD,CAAC;;;;;AAMD,MAAa,oBAA4C,EAAE,aAAa;CACtE,QAAQ;CACR,WAAW;CACX,iBAAiB,EAAE,QAAQ;CAC3B,YAAY,EAAE,QAAQ;CACtB,QAAQ;AACV,CAAC;;;;;AAMD,SAAgB,UAAU,OAAoB,SAAiD;CAC7F,MAAM,EAAE,cAAc;CACtB,IAAI,UAAU,SAAS,QAAQ,OAAO;CACtC,MAAM,KAAK,KAAK,MAAM,QAAQ,EAAE;CAChC,IAAI,OAAO,MAAM,EAAE,GAAG,MAAM,IAAI,WAAW,eAAe,KAAK,UAAU,QAAQ,EAAE,EAAE,oBAAoB;CACzG,IAAI,UAAU,SAAS,YAAY,OAAO,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;CACnE,OAAO,IAAI,KAAK,KAAK,KAAK,MAAM,QAAQ,UAAU,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,YAAY;AAC7E;;;;;AAMA,SAAgB,OAAO,OAAoB,SAAkC,KAAa,QAAQ,OAAgB;CAChH,IAAI,SAAS,MAAM,iBAAiB,O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IAAI,OAAO;GACT,IAAI,KAAK,MAAM,IAAI;GACnB,MAAM,KAAK;IAAE,MAAM,MAAM;IAAM,IAAI,OAAO,MAAM,IAAI,IAAI,OAAO,oBAAoB,OAAO,SAAS;GAAG,CAAC;EACzG;EAEA,OAAO,KAAK,IAAI,OAAO,QAAQ,KAAK,QAAQ,SAAS,EAAE;CACzD;CAGA,OAAO;EAAE;EAAK,OADA,MAAM,MAAM,GAAG,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,KAAK,IACjD;EAAG,MAAM,OAAO,SAAS,IAAI,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC,YAAY,IAAI;CAAK;AACzF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/terms.ts","../src/board.ts","../src/metered.ts"],"sourcesContent":["import { valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { sourceSchema, textSchema } from \"./records.ts\";\n\n/** The storage rule of a source, from its terms. */\nexport type Retention =\n | { readonly kind: \"keep\" }\n | { readonly kind: \"max-age\"; readonly age: Quantity }\n | { readonly kind: \"no-store\" };\n\n/** The rules of the terms of one source. */\nexport interface SourceTerms {\n readonly source: string;\n readonly retention: Retention;\n readonly deleteWhenEnded: boolean;\n readonly priceModel: boolean;\n readonly clause: string;\n}\n\n/**\n * This schema accepts the storage rule of a source, from its terms. With `keep`, the terms set no limit on the\n * time. With `max-age`, a store keeps a reading for `age` at most. With `no-store`, a reading serves one request.\n */\nexport const retentionSchema: z.ZodType<Retention> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"keep\") }),\n z.strictObject({ kind: z.literal(\"max-age\"), age: quantitySchema(\"time\", { positive: true }) }),\n z.strictObject({ kind: z.literal(\"no-store\") }),\n]);\n\n/**\n * This schema accepts the rules of the terms of one source. `deleteWhenEnded` deletes the readings of an offer\n * when the offer ends. `priceModel` permits a trend or a forecast of prices. `clause` names the text of the terms.\n */\nexport const sourceTermsSchema: z.ZodType<SourceTerms> = z.strictObject({\n source: sourceSchema,\n retention: retentionSchema,\n deleteWhenEnded: z.boolean(),\n priceModel: z.boolean(),\n clause: textSchema,\n});\n\n/**\n * This function gives the last instant at which a store keeps a reading, or null when the terms set no\n * limit. For a source with `no-store`, the instant is the instant of the reading.\n */\nexport function keepUntil(terms: SourceTerms, reading: { readonly at: string }): string | null {\n const { retention } = terms;\n if (retention.kind === \"keep\") return null;\n const at = Date.parse(reading.at);\n if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(reading.at)} is not an instant.`);\n if (retention.kind === \"no-store\") return new Date(at).toISOString();\n return new Date(at + Math.floor(valueIn(retention.age, \"ms\"))).toISOString();\n}\n\n/**\n * This function tells if a store keeps a reading at the instant `now`. A store keeps no reading of a source with\n * `no-store`, and no reading of an ended offer when the terms delete them.\n */\nexport function isKept(terms: SourceTerms, reading: { readonly at: string }, now: string, ended = false): boolean {\n if (ended && terms.deleteWhenEnded) return false;\n if (terms.retention.kind === \"no-store\") return false;\n const until = keepUntil(terms, reading);\n if (until === null) return true;\n const instant = Date.parse(now);\n if (Number.isNaN(instant)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);\n return instant <= Date.parse(until);\n}\n\n/** This function tells if the terms permit a stored history of the readings of a source. */\nexport function permitsHistory(terms: SourceTerms): boolean {\n return terms.retention.kind === \"keep\" && !terms.deleteWhenEnded;\n}\n\n/** This function tells if the terms permit a trend of the prices of a source: a history and a model of prices. */\nexport function permitsTrend(terms: SourceTerms): boolean {\n return permitsHistory(terms) && terms.priceModel;\n}\n","import { valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { latestObservations, type Observation } from \"./offers.ts\";\nimport { instantSchema, offerSchema, priceReadingSchema, sourceSchema, textSchema } from \"./records.ts\";\nimport { isKept, keepUntil, type SourceTerms } from \"./terms.ts\";\n\n/*\n * This module calculates a board of current prices. A watch reads its sources on a schedule. The board keeps the\n * last read of each entry of the watch, within the terms of each source. Each function of this module is a\n * calculation with no effect. A host does the reads and writes the board.\n */\n\n/** The format name of a board record. */\nexport const BOARD_FORMAT = \"price-board/1\";\n\n/** This schema accepts an observation: an offer, and a reading of that offer. */\nexport const observationSchema: z.ZodType<Observation> = z\n .strictObject({ offer: offerSchema, reading: priceReadingSchema })\n .refine((each) => each.reading.offerId === each.offer.id, { message: \"The reading is not a reading of the offer.\" });\n\n/** This record is the last read of one entry of a watch: the name of the entry, the instant, and the observations. */\nexport interface BoardRead {\n readonly name: string;\n readonly at: string;\n readonly observations: readonly Observation[];\n}\n\n/** This record is a board: the instant of its last settle, and the last read of each entry, in the order of the names. */\nexport interface Board {\n readonly format: typeof BOARD_FORMAT;\n readonly at: string;\n readonly reads: readonly BoardRead[];\n}\n\n/** This schema accepts the read of an entry. The read has one observation of each offer at most. */\nexport const boardReadSchema: z.ZodType<BoardRead> = z\n .strictObject({ name: textSchema, at: instantSchema, observations: z.array(observationSchema) })\n .refine((read) => new Set(read.observations.map((each) => each.offer.id)).size === read.observations.length, {\n message: \"The read has two observations of one offer.\",\n });\n\n/** This schema accepts a board. The board has one read of each entry at most. */\nexport const boardSchema: z.ZodType<Board> = z\n .strictObject({ format: z.literal(BOARD_FORMAT), at: instantSchema, reads: z.array(boardReadSchema) })\n .refine((board) => new Set(board.reads.map((each) => each.name)).size === board.reads.length, {\n message: \"The board has two reads of one entry.\",\n });\n\n/** This record is an offer that the store does not keep, with the reason. */\nexport interface Dropped {\n readonly offerId: string;\n readonly why: string;\n}\n\n/** These options give the rules of a store: the terms of each source, the instant, and the offers that ended. */\nexport interface KeepOptions {\n /** The terms of the sources. A store keeps no reading of a source without terms. */\n readonly terms: readonly SourceTerms[];\n /** The instant of the decision. */\n readonly now: string;\n /** The ids of the offers that ended, as their sources tell. An offer with `endsAt` at or before `now` also ended. */\n readonly ended?: readonly string[] | undefined;\n}\n\n/** This record is the decision of a store: the observations that it keeps, and each offer that it drops. */\nexport interface Kept {\n /** The latest observation of each kept offer, in the order of the offer ids. */\n readonly kept: readonly Observation[];\n /** Each dropped offer, in the order of the offer ids. */\n readonly dropped: readonly Dropped[];\n}\n\n/** This function gives the terms of each source by its name. Two terms of one source are a problem of the input. */\nfunction termsBySource(terms: readonly SourceTerms[]): ReadonlyMap<string, SourceTerms> {\n const map = new Map<string, SourceTerms>();\n for (const each of terms) {\n if (map.has(each.source)) throw new RangeError(`The terms of the source ${each.source} are in the list two times.`);\n map.set(each.source, each);\n }\n return map;\n}\n\n/** This function gives the text of an amount of time, for example `6 h`. */\nconst timeText = (age: Quantity): string => `${age.value} ${age.unit}`;\n\n/**\n * This function decides which observations a store keeps. It takes the latest observation of each offer. It keeps\n * an observation while the terms of its source permit it, and while its offer has not ended. A current price is\n * a price that a buyer can pay, so the store drops an ended offer for each source.\n *\n * `settleBoard` applies this function to each read of a board.\n *\n * @throws RangeError when `now` is not an instant, or when the terms have two entries for one source.\n */\nexport function keepObservations(observations: readonly Observation[], options: KeepOptions): Kept {\n const terms = termsBySource(options.terms);\n const now = Date.parse(options.now);\n if (Number.isNaN(now)) throw new RangeError(`The instant ${JSON.stringify(options.now)} is not an instant.`);\n const ended = new Set(options.ended ?? []);\n const kept: Observation[] = [];\n const dropped: Dropped[] = [];\n for (const observation of latestObservations(observations)) {\n const { offer, reading } = observation;\n const rules = terms.get(offer.source);\n const endsAt = offer.endsAt === undefined ? Number.NaN : Date.parse(offer.endsAt);\n const over = ended.has(offer.id) || endsAt <= now;\n if (rules === undefined) dropped.push({ offerId: offer.id, why: `The terms of the source ${offer.source} are not known, so a store keeps no reading of it.` });\n else if (rules.retention.kind === \"no-store\") dropped.push({ offerId: offer.id, why: `The terms of ${offer.source} permit no store: a reading serves one request.` });\n else if (over) {\n const rule = rules.deleteWhenEnded ? `, and the terms of ${offer.source} delete its readings` : \"\";\n dropped.push({ offerId: offer.id, why: `The offer ended${rule}.` });\n } else if (!isKept(rules, reading, options.now)) {\n const age = rules.retention.kind === \"max-age\" ? timeText(rules.retention.age) : \"\";\n dropped.push({ offerId: offer.id, why: `The reading of ${reading.at} passed the limit of ${age} of the terms of ${offer.source} at ${keepUntil(rules, reading)}.` });\n } else kept.push(observation);\n }\n return { kept, dropped };\n}\n\n/** These options give the rules of a settle: the rules of a store, and the names of the entries of the watch. */\nexport interface SettleOptions extends KeepOptions {\n /** The names of the entries of the watch. The board drops the read of each other name. With no list, it keeps each read. */\n readonly names?: readonly string[] | undefined;\n}\n\n/** This record is an offer that the board drops, with the name of the entry of its read. */\nexport interface BoardDrop extends Dropped {\n readonly entry: string;\n}\n\n/** This record is the result of a settle: the new board, and each offer that it dropped. */\nexport interface Settled {\n readonly board: Board;\n readonly dropped: readonly BoardDrop[];\n}\n\nconst byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n/**\n * This function settles a board at `now`. A new read replaces the last read of its entry, so an offer that the new\n * read does not give leaves the read. Then `keepObservations` applies the terms to each read. The board drops the\n * read of an entry that the watch does not have. Write the new board in place of the old board.\n *\n * @param read - A new read of an entry, or none to settle the board alone\n * @throws RangeError when `now` is not an instant, or when the terms have two entries for one source.\n */\nexport function settleBoard(board: Board, options: SettleOptions, read?: BoardRead): Settled {\n const names = options.names === undefined ? undefined : new Set(options.names);\n const reads = new Map(board.reads.map((each) => [each.name, each]));\n if (read !== undefined) reads.set(read.name, read);\n const settled: BoardRead[] = [];\n const dropped: BoardDrop[] = [];\n for (const name of [...reads.keys()].sort(byText)) {\n const each = reads.get(name);\n if (each === undefined) continue;\n if (names !== undefined && !names.has(name)) {\n for (const gone of latestObservations(each.observations)) dropped.push({ entry: name, offerId: gone.offer.id, why: `The watch has no entry ${name}.` });\n continue;\n }\n const decision = keepObservations(each.observations, options);\n settled.push({ name, at: each.at, observations: decision.kept });\n for (const drop of decision.dropped) dropped.push({ entry: name, ...drop });\n }\n return { board: { format: BOARD_FORMAT, at: options.now, reads: settled }, dropped };\n}\n\n/**\n * This function gives the current observations of a board at `now`. Each is the latest observation of an offer over\n * the reads, while the terms of its source permit it. Give them to `offersOfPart` and `bestOffer`.\n */\nexport function boardObservations(board: Board, options: KeepOptions): Observation[] {\n return [...keepObservations(board.reads.flatMap((each) => each.observations), options).kept];\n}\n\n/** This function gives the instant of the last read of each entry of a board, by name, for `planReads`. */\nexport function lastReads(board: Board): Record<string, string> {\n return Object.fromEntries(board.reads.map((each) => [each.name, each.at]));\n}\n\n/** This record is one entry of a watch: a read of one source that repeats. */\nexport interface WatchEntry {\n /** The name of the entry. Each entry of a watch has its own name. */\n readonly name: string;\n /** The source of the read. */\n readonly source: string;\n /** The time from one read of the entry to the next, a time of `@mark1russell7/quantity`. */\n readonly every: Quantity;\n}\n\n/** This schema accepts an entry of a watch. */\nexport const watchEntrySchema: z.ZodType<WatchEntry> = z.strictObject({\n name: textSchema,\n source: sourceSchema,\n every: quantitySchema(\"time\", { positive: true }),\n});\n\n/** These options give the rules of a schedule: the terms of each source, and the slack of the loop. */\nexport interface ScheduleOptions {\n /** The terms of the sources. */\n readonly terms: readonly SourceTerms[];\n /**\n * The longest time from the instant of a due read to the instant that its reading is on the board. It is the\n * time between two passes of the loop, plus the longest pass.\n */\n readonly slack: Quantity;\n}\n\n/** This record is the interval of an entry, in milliseconds, or the reason that the entry has no interval. */\nexport type ReadInterval = { readonly ok: true; readonly ms: number } | { readonly ok: false; readonly why: string };\n\n/**\n * This function gives the time from one read of an entry to the next, in milliseconds. A reading of a source with\n * the limit `L` stays on the board until `L` after the read. The next reading arrives `slack` after the next read\n * is due, at most. Thus the interval is the shorter of `every` and `L - slack`. Then the board has a current\n * reading of the entry at each instant after its first read.\n */\nexport function readInterval(entry: WatchEntry, options: ScheduleOptions): ReadInterval {\n const terms = termsBySource(options.terms).get(entry.source);\n const every = valueIn(entry.every, \"ms\");\n if (!(every > 0)) return { ok: false, why: `The time every of the entry ${entry.name} is not more than 0.` };\n if (terms === undefined) return { ok: false, why: `The terms of the source ${entry.source} of the entry ${entry.name} are not known.` };\n const { retention } = terms;\n if (retention.kind === \"no-store\") return { ok: false, why: `The terms of ${entry.source} permit no store, so a watch cannot keep the prices of the entry ${entry.name}. Read the source for each request.` };\n if (retention.kind === \"keep\") return { ok: true, ms: every };\n const room = valueIn(retention.age, \"ms\") - valueIn(options.slack, \"ms\");\n if (!(room > 0)) return { ok: false, why: `The slack ${timeText(options.slack)} is not less than the limit ${timeText(retention.age)} of the terms of ${entry.source}, so the board has gaps in the prices of the entry ${entry.name}.` };\n return { ok: true, ms: Math.min(every, room) };\n}\n\n/** This function gives the problems of a watch: an entry with no interval, and two entries with one name. */\nexport function watchProblems(entries: readonly WatchEntry[], options: ScheduleOptions): string[] {\n const problems: string[] = [];\n const names = new Set<string>();\n for (const entry of entries) {\n if (names.has(entry.name)) problems.push(`Two entries have the name ${entry.name}.`);\n names.add(entry.name);\n const interval = readInterval(entry, options);\n if (!interval.ok) problems.push(interval.why);\n }\n return problems;\n}\n\n/** This record is the plan of one pass of a watch: the due entries, and the instant of the next due read. */\nexport interface ReadPlan {\n /** The names of the due entries, in the order of the entries. An entry with no read is due. */\n readonly due: readonly string[];\n /**\n * The names of the due entries, the entry that is due for the longest time first. An entry with no read comes\n * first. Entries that became due at the same instant keep the order of the entries. Read the entries in this order.\n * Then each due entry comes before the next read of a later due entry.\n */\n readonly queue: readonly string[];\n /** The first instant after `now` that an entry is due, or null when no entry has an interval. */\n readonly next: string | null;\n}\n\n/**\n * This function plans one pass of a watch. An entry is due when it has no last read, or when its interval has\n * passed since its last read. An entry with no interval is not due at any time. `watchProblems` gives its reason.\n *\n * @param last - The instant of the last read of each entry, by name\n * @throws RangeError when `now` or a last read is not an instant.\n */\nexport function planReads(entries: readonly WatchEntry[], last: Readonly<Record<string, string>>, now: string, options: ScheduleOptions): ReadPlan {\n const at = Date.parse(now);\n if (Number.isNaN(at)) throw new RangeError(`The instant ${JSON.stringify(now)} is not an instant.`);\n const due: string[] = [];\n const since: { readonly name: string; readonly at: number }[] = [];\n let next = Number.POSITIVE_INFINITY;\n for (const entry of entries) {\n const interval = readInterval(entry, options);\n if (!interval.ok) continue;\n const before = Object.hasOwn(last, entry.name) ? last[entry.name] : undefined;\n const read = before === undefined ? Number.NaN : Date.parse(before);\n if (before !== undefined && Number.isNaN(read)) throw new RangeError(`The last read ${JSON.stringify(before)} of the entry ${entry.name} is not an instant.`);\n const isDue = Number.isNaN(read) || read + interval.ms <= at;\n if (isDue) {\n due.push(entry.name);\n since.push({ name: entry.name, at: Number.isNaN(read) ? Number.NEGATIVE_INFINITY : read + interval.ms });\n }\n // A planned read happens at `now`, so the next read of a due entry is one interval after `now`.\n next = Math.min(next, (isDue ? at : read) + interval.ms);\n }\n // The sort of an array is stable, so equal instants keep the order of the entries.\n const queue = since.sort((a, b) => a.at - b.at).map((each) => each.name);\n return { due, queue, next: Number.isFinite(next) ? new Date(next).toISOString() : null };\n}\n","import {\n canonicalUnit,\n convertExact,\n convertible,\n parseUnit,\n quantity,\n rationals,\n UnitError,\n type Quantity,\n type Rational,\n} from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { instantSchema, moneySchema, offerId, sourceSchema, specSchema, textSchema, type Spec } from \"./records.ts\";\n\n/*\n * This module has the metered prices of a market. A provider meters an amount, for example the hours of a machine,\n * the stored data of each month, the data that goes out, or the requests. A metered price is a price for each unit\n * of that amount, in tiers, with a free amount for each billing period and a term.\n */\n\n/**\n * The kinds of a metered amount: a time (the hours of a machine), data times time (stored data), data (a transfer)\n * and a count (requests).\n */\nexport const METERED_KINDS = [\"time\", \"data-time\", \"data\", \"count\"] as const;\n/** The kind of a metered amount. */\nexport type MeteredKind = (typeof METERED_KINDS)[number];\n\n/**\n * The scopes of a free amount. With `account`, all the usage of the account in all regions shares one free amount.\n * With `region`, each region has its own free amount. With `resource`, each resource has its own free amount.\n */\nexport const FREE_SCOPES = [\"account\", \"region\", \"resource\"] as const;\n/** The scope of a free amount: the usage that shares it. */\nexport type FreeScope = (typeof FREE_SCOPES)[number];\n\n/** The location of a metered offer: the provider, and its region and zone, as the provider names them. */\nexport interface Location {\n readonly provider: string;\n readonly region: string;\n readonly zone?: string | undefined;\n}\n\n/**\n * The term of a metered price. A `spot` price is also a preemptible price: the provider can end the use at any time,\n * after the `notice`. A `committed` price binds the buyer for its `length`.\n */\nexport type PriceTerm =\n | { readonly kind: \"on-demand\" }\n | { readonly kind: \"spot\"; readonly notice?: Quantity | undefined }\n | { readonly kind: \"committed\"; readonly length: Quantity };\n\n/** A metered offer: one resource of a provider in one location, on one term, with the identifiers that the source gives. */\nexport interface MeteredOffer {\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 location: Location;\n readonly term: PriceTerm;\n readonly specs: readonly Spec[];\n}\n\n/** A tier of a meter: the price for each unit of the usage from `from` to the start of the next tier, in one period. */\nexport interface Tier {\n readonly from: Quantity;\n readonly unitPrice: Quantity;\n}\n\n/** A free amount of a meter for each period, and the scope that shares it. */\nexport interface FreeAmount {\n readonly amount: Quantity;\n readonly scope: FreeScope;\n}\n\n/** A meter of a metered reading: the tiers of the price of one metered amount, and its free amount. */\nexport interface Meter {\n readonly name: string;\n readonly tiers: readonly Tier[];\n readonly free?: FreeAmount | undefined;\n}\n\n/** A metered reading: the metered prices of one offer at one instant. */\nexport interface MeteredReading {\n readonly offerId: string;\n readonly at: string;\n readonly period: Quantity;\n readonly meters: readonly Meter[];\n readonly upfront?: Quantity | undefined;\n}\n\n/** One metered offer of a source, and its metered reading at one instant. */\nexport interface MeteredObservation {\n readonly offer: MeteredOffer;\n readonly reading: MeteredReading;\n}\n\n/** The usage of each meter in one period, by the name of the meter. */\nexport type MeteredUsage = Readonly<Record<string, Quantity>>;\n\n/** These options change the cost of a metered offer. */\nexport interface MeteredCostOptions {\n /**\n * The part of the free amount of each meter that other usage in its scope used in the same period. The keys are\n * the names of the meters. The default is none.\n */\n readonly freeUsed?: MeteredUsage | undefined;\n}\n\n/** The cost of the usage of one meter in one period. */\nexport interface MeterCost {\n readonly name: string;\n readonly cost: Quantity;\n}\n\n/** The cost of a metered offer for one period. */\nexport interface MeteredCost {\n /** The cost of each meter, in the order of the meters of the reading. */\n readonly meters: readonly MeterCost[];\n /** The part of the upfront money of a committed term for one period, or zero. */\n readonly upfront: Quantity;\n /** The sum of the cost of each meter and the part of the upfront money. */\n readonly total: Quantity;\n}\n\n/** The parts of the unit of a metered price: its unit of money, and the kind of its metered amount. */\ninterface PriceParts {\n readonly money: string;\n readonly kind: MeteredKind;\n}\n\n/** This function gives the kind of a metered amount from the exponents of its data and its time, or undefined. */\nfunction kindOfExponents(data: number, time: number): MeteredKind | undefined {\n if (data === 0 && time === 0) return \"count\";\n if (data === 0 && time === 1) return \"time\";\n if (data === 1 && time === 0) return \"data\";\n if (data === 1 && time === 1) return \"data-time\";\n return undefined;\n}\n\n/** This function reads the unit of a metered price. It gives the parts of the unit, or the problem as a text. */\nfunction readPriceUnit(unit: string): PriceParts | string {\n const refused = `The unit ${unit} is not a price for each unit of a metered amount, for example USD/h.`;\n let parsed: ReturnType<typeof parseUnit>;\n try {\n parsed = parseUnit(unit);\n } catch (error) {\n if (error instanceof UnitError) return refused;\n throw error;\n }\n const above = parsed.components.filter((component) => component.exponent > 0);\n const [money] = above;\n const atom = money?.atom;\n const isMoney = atom !== undefined && Object.keys(atom.vector).length === 1 && atom.vector.money === 1;\n const below = parsed.components.some((component) => component.exponent < 0);\n if (above.length !== 1 || money?.exponent !== 1 || money.annotation !== undefined || !isMoney || !below) return refused;\n const { money: units = 0, data = 0, time = 0, ...others } = parsed.vector;\n const kind = Object.values(others).every((exponent) => exponent === 0) && units === 1 ? kindOfExponents(-data, -time) : undefined;\n return kind === undefined ? refused : { money: atom.symbol, kind };\n}\n\n/** This function gives the unit of a price for each unit of an amount, for example `USD/(GiB·mo)` for `GiB·mo`. */\nfunction priceUnitFor(money: string, amountUnit: string): string | undefined {\n try {\n return canonicalUnit(`${money}/${amountUnit}`);\n } catch (error) {\n if (error instanceof UnitError) return undefined;\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 gives the start of each tier in one unit, or undefined when a start does not convert to it. */\nfunction startsOf(tiers: readonly Tier[], unit: string): Rational[] | undefined {\n try {\n return tiers.map((tier) => convertExact(rationals.fromNumber(tier.from.value), tier.from.unit, unit));\n } catch (error) {\n if (error instanceof UnitError || error instanceof RangeError) return undefined;\n throw error;\n }\n}\n\n/** This function tells if a unit of an amount measures the metered amount of a unit of price. */\nfunction measures(amountUnit: string, priceUnit: string, money: string): boolean {\n const unit = priceUnitFor(money, amountUnit);\n return unit !== undefined && converts(unit, priceUnit);\n}\n\n/**\n * This function gives the kind of the metered amount of the unit of a metered price, for example `time` for `USD/h`\n * and `data-time` for `USD/(GiB·mo)`.\n *\n * @throws RangeError when the unit is not a price for each unit of a metered amount.\n */\nexport function meteredKindOf(unit: string): MeteredKind {\n const parts = readPriceUnit(unit);\n if (typeof parts === \"string\") throw new RangeError(parts);\n return parts.kind;\n}\n\n/**\n * This schema accepts the location of a metered offer. The name of the provider has small letters, digits and\n * hyphens, as the name of a source. The region and the zone are the ids of the provider.\n */\nexport const locationSchema: z.ZodType<Location> = z.strictObject({\n provider: sourceSchema,\n region: textSchema,\n zone: textSchema.optional(),\n});\n\n/**\n * This schema accepts the term of a metered price. A `spot` term can have the notice before the provider ends the\n * use. A `committed` term has its length.\n */\nexport const priceTermSchema: z.ZodType<PriceTerm> = z.discriminatedUnion(\"kind\", [\n z.strictObject({ kind: z.literal(\"on-demand\") }),\n z.strictObject({ kind: z.literal(\"spot\"), notice: quantitySchema(\"time\", { nonnegative: true }).optional() }),\n z.strictObject({ kind: z.literal(\"committed\"), length: quantitySchema(\"time\", { positive: true }) }),\n]);\n\n/**\n * This schema accepts a metered offer: one resource of a provider in one location, on one term. The id is the\n * source and the source id, with a colon between them.\n */\nexport const meteredOfferSchema: z.ZodType<MeteredOffer> = 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 location: locationSchema,\n term: priceTermSchema,\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/**\n * This schema accepts a metered price of zero or more: an amount of money for each unit of a metered amount, for\n * example `{ \"value\": 0.0116, \"unit\": \"USD/h\" }`.\n */\nexport const meteredPriceSchema: z.ZodType<Quantity, Quantity> = quantitySchema(undefined, { nonnegative: true }).superRefine(\n (price, context) => {\n const parts = readPriceUnit(price.unit);\n if (typeof parts === \"string\") context.addIssue({ code: \"custom\", message: parts });\n },\n);\n\n/** This schema accepts a tier: the start of its usage, and its price for each unit. The start measures the metered amount of the price. */\nexport const tierSchema: z.ZodType<Tier> = z\n .strictObject({ from: quantitySchema(undefined, { nonnegative: true }), unitPrice: meteredPriceSchema })\n .superRefine((tier, context) => {\n const parts = readPriceUnit(tier.unitPrice.unit);\n if (typeof parts === \"string\" || measures(tier.from.unit, tier.unitPrice.unit, parts.money)) return;\n context.addIssue({\n code: \"custom\",\n message: `The start ${tier.from.unit} does not measure the metered amount of the price ${tier.unitPrice.unit}.`,\n path: [\"from\"],\n });\n });\n\n/** This schema accepts a free amount of more than zero for each period, and its scope. */\nexport const freeAmountSchema: z.ZodType<FreeAmount> = z.strictObject({\n amount: quantitySchema(undefined, { positive: true }),\n scope: z.enum(FREE_SCOPES),\n});\n\n/**\n * This schema accepts a meter. The first tier starts at zero, and the starts increase. The prices of the tiers and\n * the free amount measure one metered amount.\n */\nexport const meterSchema: z.ZodType<Meter> = z\n .strictObject({ name: textSchema, tiers: z.array(tierSchema).min(1), free: freeAmountSchema.optional() })\n .superRefine((meter, context) => {\n const [first] = meter.tiers;\n if (first === undefined) return;\n const parts = readPriceUnit(first.unitPrice.unit);\n if (typeof parts === \"string\") return;\n let units = true;\n for (const [index, tier] of meter.tiers.entries()) {\n if (converts(tier.unitPrice.unit, first.unitPrice.unit) && measures(tier.from.unit, first.unitPrice.unit, parts.money)) continue;\n units = false;\n context.addIssue({\n code: \"custom\",\n message: `The tier ${index} does not measure the metered amount of the price ${first.unitPrice.unit}.`,\n path: [\"tiers\", index],\n });\n }\n if (meter.free !== undefined && !measures(meter.free.amount.unit, first.unitPrice.unit, parts.money)) {\n context.addIssue({\n code: \"custom\",\n message: `The free amount ${meter.free.amount.unit} does not measure the metered amount of the price ${first.unitPrice.unit}.`,\n path: [\"free\", \"amount\"],\n });\n }\n if (!units) return;\n const starts = startsOf(meter.tiers, first.from.unit);\n if (starts === undefined) return;\n if (rationals.sign(starts[0] ?? rationals.ZERO) !== 0) {\n context.addIssue({ code: \"custom\", message: \"The first tier does not start at zero.\", path: [\"tiers\", 0, \"from\"] });\n }\n for (let index = 1; index < starts.length; index += 1) {\n if (rationals.cmp(starts[index] ?? rationals.ZERO, starts[index - 1] ?? rationals.ZERO) > 0) continue;\n context.addIssue({\n code: \"custom\",\n message: `The tier ${index} does not start after the tier ${index - 1}.`,\n path: [\"tiers\", index, \"from\"],\n });\n }\n });\n\n/**\n * This schema accepts a metered reading: the metered prices of one offer at one instant. The tiers and the free\n * amounts count the usage of one `period`. Each meter has its own name.\n */\nexport const meteredReadingSchema: z.ZodType<MeteredReading> = z\n .strictObject({\n offerId: textSchema,\n at: instantSchema,\n period: quantitySchema(\"time\", { positive: true }),\n meters: z.array(meterSchema).min(1),\n upfront: moneySchema.optional(),\n })\n .refine((reading) => new Set(reading.meters.map((meter) => meter.name)).size === reading.meters.length, {\n message: \"The reading has two meters with one name.\",\n path: [\"meters\"],\n });\n\n/** This schema accepts a metered observation: an offer, and a reading of that offer. Only a committed term has upfront money. */\nexport const meteredObservationSchema: z.ZodType<MeteredObservation> = z\n .strictObject({ offer: meteredOfferSchema, reading: meteredReadingSchema })\n .superRefine((each, context) => {\n if (each.reading.offerId !== each.offer.id) {\n context.addIssue({ code: \"custom\", message: \"The reading is not a reading of the offer.\", path: [\"reading\", \"offerId\"] });\n }\n if (each.reading.upfront !== undefined && each.offer.term.kind !== \"committed\") {\n context.addIssue({\n code: \"custom\",\n message: `The term ${each.offer.term.kind} has no upfront money.`,\n path: [\"reading\", \"upfront\"],\n });\n }\n });\n\n/** This function gives the value of an amount in a unit, as an exact rational. */\nfunction exactIn(amount: Quantity, unit: string): Rational {\n return convertExact(rationals.fromNumber(amount.value), amount.unit, unit);\n}\n\n/** This function gives the larger of two rationals. */\nfunction larger(a: Rational, b: Rational): Rational {\n return rationals.cmp(a, b) >= 0 ? a : b;\n}\n\n/** This function gives the smaller of two rationals. */\nfunction smaller(a: Rational, b: Rational): Rational {\n return rationals.cmp(a, b) <= 0 ? a : b;\n}\n\n/** This function examines an amount of usage of a meter, and gives its value in its own unit. */\nfunction usageValue(meter: Meter, amount: Quantity, priceUnit: string, money: string, what: string): Rational {\n if (!Number.isFinite(amount.value) || amount.value < 0) {\n throw new RangeError(`The ${what} of the meter ${meter.name} is ${amount.value}, not an amount of zero or more.`);\n }\n if (!measures(amount.unit, priceUnit, money)) {\n throw new RangeError(`The ${what} of the meter ${meter.name} is in ${amount.unit}, which does not measure the price ${priceUnit}.`);\n }\n return rationals.fromNumber(amount.value);\n}\n\n/**\n * This function gives the exact cost of the usage of one meter, in the unit of money of its first tier. The free\n * amount comes off the usage first. The tiers then count the rest of the usage from zero.\n */\nfunction costOfMeter(meter: Meter, used: Quantity | undefined, freeUsed: Quantity | undefined): { money: string; cost: Rational } {\n const [first] = meter.tiers;\n if (first === undefined) throw new RangeError(`The meter ${meter.name} has no tier.`);\n const parts = readPriceUnit(first.unitPrice.unit);\n if (typeof parts === \"string\") throw new RangeError(parts);\n const { money } = parts;\n if (used === undefined) return { money, cost: rationals.ZERO };\n const amount = usageValue(meter, used, first.unitPrice.unit, money, \"usage\");\n const unit = used.unit;\n const perUnit = priceUnitFor(money, unit);\n if (perUnit === undefined) throw new RangeError(`The usage of the meter ${meter.name} is in ${unit}, which has no price unit.`);\n let free: Rational = rationals.ZERO;\n if (meter.free !== undefined) free = exactIn(meter.free.amount, unit);\n if (freeUsed !== undefined) {\n usageValue(meter, freeUsed, first.unitPrice.unit, money, \"used free amount\");\n free = larger(rationals.ZERO, rationals.sub(free, exactIn(freeUsed, unit)));\n }\n const billed = larger(rationals.ZERO, rationals.sub(amount, free));\n let cost: Rational = rationals.ZERO;\n for (const [index, tier] of meter.tiers.entries()) {\n const start = exactIn(tier.from, unit);\n const next = meter.tiers[index + 1];\n const end = next === undefined ? billed : smaller(billed, exactIn(next.from, unit));\n if (rationals.cmp(end, start) <= 0) continue;\n cost = rationals.add(cost, rationals.mul(rationals.sub(end, start), exactIn(tier.unitPrice, perUnit)));\n }\n return { money, cost };\n}\n\n/**\n * This function gives the cost of a metered offer for one period, from the usage of each meter in that period. A\n * meter with no usage costs zero. The free amount of a meter comes off its usage first, less `freeUsed`. The tiers\n * then count the rest of the usage from zero. A committed term adds its upfront money times the period over the length.\n *\n * The arithmetic is exact, and the function does not round the cost to the cent. Each value is the nearest number to\n * the exact cost. The function converts the units with the exact factors of `@mark1russell7/quantity`.\n *\n * @throws RangeError when the usage names a meter that the reading does not have. It also throws when an amount\n * of usage is negative, or does not measure the metered amount of its meter.\n */\nexport function meteredCost(observation: MeteredObservation, usage: MeteredUsage, options: MeteredCostOptions = {}): MeteredCost {\n const { offer, reading } = observation;\n const { freeUsed = {} } = options;\n const names = new Set(reading.meters.map((meter) => meter.name));\n for (const name of [...Object.keys(usage), ...Object.keys(freeUsed)]) {\n if (!names.has(name)) throw new RangeError(`The reading of ${reading.offerId} has no meter ${name}.`);\n }\n const at = (record: MeteredUsage, name: string): Quantity | undefined => (Object.hasOwn(record, name) ? record[name] : undefined);\n const costs = reading.meters.map((meter) => ({ name: meter.name, ...costOfMeter(meter, at(usage, meter.name), at(freeUsed, meter.name)) }));\n const unit = costs[0]?.money;\n if (unit === undefined) throw new RangeError(`The reading of ${reading.offerId} has no meter.`);\n let total: Rational = rationals.ZERO;\n for (const each of costs) total = rationals.add(total, convertExact(each.cost, each.money, unit));\n const meters = costs.map((each): MeterCost => ({ name: each.name, cost: quantity(rationals.toNumber(each.cost), each.money) }));\n let upfront: Rational = rationals.ZERO;\n if (offer.term.kind === \"committed\" && reading.upfront !== undefined) {\n const { length } = offer.term;\n const share = rationals.div(exactIn(reading.period, length.unit), rationals.fromNumber(length.value));\n upfront = rationals.mul(exactIn(reading.upfront, unit), share);\n }\n total = rationals.add(total, upfront);\n return { meters, upfront: quantity(rationals.toNumber(upfront), unit), total: quantity(rationals.toNumber(total), unit) };\n}\n"],"mappings":";;;;;;;;;AAwBA,MAAa,kBAAwC,EAAE,mBAAmB,QAAQ;CAChF,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,MAAM,EAAE,CAAC;CAC1C,EAAE,aAAa;EAAE,MAAM,EAAE,QAAQ,SAAS;EAAG,KAAK,eAAe,QAAQ,EAAE,UAAU,KAAK,CAAC;CAAE,CAAC;CAC9F,EAAE,aAAa,EAAE,MAAM,EAAE,QAAQ,UAAU,EAAE,CAAC;AAChD,CAAC;;;;;AAMD,MAAa,oBAA4C,EAAE,aAAa;CACtE,QAAQ;CACR,WAAW;CACX,iBAAiB,EAAE,QAAQ;CAC3B,YAAY,EAAE,QAAQ;CACtB,QAAQ;AACV,CAAC;;;;;AAMD,SAAgB,UAAU,OAAoB,SAAiD;CAC7F,MAAM,EAAE,cAAc;CACtB,IAAI,UAAU,SAAS,QAAQ,OAAO;CACtC,MAAM,KAAK,KAAK,MAAM,QAAQ,EAAE;CAChC,IAAI,OAAO,MAAM,EAAE,GAAG,MAAM,IAAI,WAAW,eAAe,KAAK,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,QAAQ,QAAQ,SAAS,IAAI,GAAG,KAAK;CAC/D;CACA,QAAQ,UAAU,IAAI,OAAO,OAAO;CACpC,OAAO;EAAE;EAAQ,SAAS,SAAS,UAAU,SAAS,OAAO,GAAG,IAAI;EAAG,OAAO,SAAS,UAAU,SAAS,KAAK,GAAG,IAAI;CAAE;AAC1H"}
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
@@ -1 +1 @@
1
- {"version":3,"file":"plan.d.ts","names":[],"sources":["../src/plan.ts"],"mappings":";;;;;qBAiBa;;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;;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;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, y as bestOffer } from "./records-hK1UCmpm.js";
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