@mark1russell7/market 0.1.8 → 0.1.9

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/average.ts","../src/terms.ts","../src/board.ts","../src/metered.ts"],"sourcesContent":["import { parseUnit, UnitError, type Quantity } from \"@mark1russell7/quantity\";\nimport { quantitySchema } from \"@mark1russell7/quantity/schema\";\nimport { z } from \"zod\";\nimport { instantSchema, sourceSchema, textSchema } from \"./records.ts\";\n\n/*\n * This module has the average prices of a market. An average price is not an offer of a seller. It is the mean price\n * of one item in one area and one month, from an official statistic, for example the average prices of the Consumer\n * Price Index. A buyer uses it as the price of a product that has no offer, and as a check of the price of an offer.\n */\n\n/** The average price of one item in one area and one month, from one series of a source. */\nexport interface AveragePrice {\n /** The id `source:series:period`. `averagePriceId` gives it. */\n readonly id: string;\n readonly source: string;\n /** The id of the series in the source, for example `APU0000701312`. */\n readonly series: string;\n /** The item of the series, as the source names it. */\n readonly item: string;\n /** The area of the series, as the source names it, for example `U.S. city average`. */\n readonly area: string;\n /** The month of the price, in the form `YYYY-MM`. */\n readonly period: string;\n /** The price for each unit of the item, for example `{ \"value\": 1.101, \"unit\": \"USD/lb\" }`. */\n readonly price: Quantity;\n /** The instant of the read of the source. */\n readonly at: string;\n /** The footnotes of the source for this price, for example a preliminary value. */\n readonly footnotes?: readonly string[] | undefined;\n}\n\n/** This function gives the id of an average price: the source, the series and the month, with colons. */\nexport function averagePriceId(source: string, series: string, period: string): string {\n return `${source}:${series}:${period}`;\n}\n\n/**\n * This function reads the unit of a price for each unit of an amount of an item. The unit has one unit of money\n * above. Below, it has a unit of an amount that is not money and not a pure time, for example `USD/lb`, `USD/L` or `USD/kWh`.\n * A count below must have an annotation, for example `USD/{each}`. Thus `USD/%` and `USD/h` are not prices of an item.\n */\nfunction unitPriceProblem(unit: string): string | undefined {\n const refused = `The unit ${unit} is not a price for each unit of an amount, for example USD/lb.`;\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 vector = money?.atom?.vector;\n const isMoney = vector !== undefined && Object.keys(vector).length === 1 && vector.money === 1;\n if (above.length !== 1 || money?.exponent !== 1 || money.annotation !== undefined || !isMoney) return refused;\n const below = parsed.components.filter((component) => component.exponent < 0);\n const amountOf = (component: (typeof below)[number]): boolean => {\n const dimensions = component.atom?.vector;\n if (dimensions === undefined) return component.annotation !== undefined;\n const names = Object.keys(dimensions);\n const pureTime = names.length === 1 && names[0] === \"time\";\n return names.length > 0 && !names.includes(\"money\") && !pureTime;\n };\n if (below.length === 0 || !below.every(amountOf)) return refused;\n return undefined;\n}\n\n/** This schema accepts a price of more than 0 for each unit of an amount, for example `{ \"value\": 1.101, \"unit\": \"USD/lb\" }`. */\nexport const unitPriceSchema: z.ZodType<Quantity, Quantity> = quantitySchema(undefined, { positive: true }).superRefine((price, context) => {\n const problem = unitPriceProblem(price.unit);\n if (problem !== undefined) context.addIssue({ code: \"custom\", message: problem });\n});\n\n/** This schema accepts a month in the form `YYYY-MM`, from `0001-01` to `9999-12`. */\nexport const monthSchema: z.ZodType<string> = z.string().regex(/^(?!0000)\\d{4}-(0[1-9]|1[0-2])$/, \"The month is not in the form YYYY-MM.\");\n\n/** This schema accepts an average price. Its id must be the id of its source, its series and its month. */\nexport const averagePriceSchema: z.ZodType<AveragePrice> = z\n .strictObject({\n id: textSchema,\n source: sourceSchema,\n series: textSchema,\n item: textSchema,\n area: textSchema,\n period: monthSchema,\n price: unitPriceSchema,\n at: instantSchema,\n footnotes: z.array(textSchema).optional(),\n })\n .refine((record) => record.id === averagePriceId(record.source, record.series, record.period), {\n message: \"The id is not the id of the source, the series and the month.\",\n path: [\"id\"],\n });\n\n/**\n * This function gives the last average price of each series, by its month. A later read of the same month replaces\n * an earlier one, because a source can revise a value.\n *\n * @param prices - The average prices, from one or more reads\n * @returns One price for each series, in the order of the series ids\n */\nexport function latestAverages(prices: readonly AveragePrice[]): readonly AveragePrice[] {\n const last = new Map<string, AveragePrice>();\n for (const price of prices) {\n const key = `${price.source}:${price.series}`;\n const held = last.get(key);\n if (held === undefined || price.period > held.period || (price.period === held.period && price.at > held.at)) last.set(key, price);\n }\n return [...last.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, price]) => price);\n}\n","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":";;;;;;AAiCA,SAAgB,eAAe,QAAgB,QAAgB,QAAwB;CACrF,OAAO,GAAG,OAAO,GAAG,OAAO,GAAG;AAChC;;;;;;AAOA,SAAS,iBAAiB,MAAkC;CAC1D,MAAM,UAAU,YAAY,KAAK;CACjC,IAAI;CACJ,IAAI;EACF,SAAS,UAAU,IAAI;CACzB,SAAS,OAAO;EACd,IAAI,iBAAiB,WAAW,OAAO;EACvC,MAAM;CACR;CACA,MAAM,QAAQ,OAAO,WAAW,QAAQ,cAAc,UAAU,WAAW,CAAC;CAC5E,MAAM,CAAC,SAAS;CAChB,MAAM,SAAS,OAAO,MAAM;CAC5B,MAAM,UAAU,WAAW,KAAA,KAAa,OAAO,KAAK,MAAM,CAAC,CAAC,WAAW,KAAK,OAAO,UAAU;CAC7F,IAAI,MAAM,WAAW,KAAK,OAAO,aAAa,KAAK,MAAM,eAAe,KAAA,KAAa,CAAC,SAAS,OAAO;CACtG,MAAM,QAAQ,OAAO,WAAW,QAAQ,cAAc,UAAU,WAAW,CAAC;CAC5E,MAAM,YAAY,cAA+C;EAC/D,MAAM,aAAa,UAAU,MAAM;EACnC,IAAI,eAAe,KAAA,GAAW,OAAO,UAAU,eAAe,KAAA;EAC9D,MAAM,QAAQ,OAAO,KAAK,UAAU;EACpC,MAAM,WAAW,MAAM,WAAW,KAAK,MAAM,OAAO;EACpD,OAAO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G,GAAG,UAAU,MAAM,IAAI,CAAC;CAAE,EAAE;CAC1I,MAAM,OAAO,MAAM,EAAE,EAAE;CACvB,IAAI,SAAS,KAAA,GAAW,MAAM,IAAI,WAAW,kBAAkB,QAAQ,QAAQ,eAAe;CAC9F,IAAI,QAAkB,UAAU;CAChC,KAAK,MAAM,QAAQ,OAAO,QAAQ,UAAU,IAAI,OAAO,aAAa,KAAK,MAAM,KAAK,OAAO,IAAI,CAAC;CAChG,MAAM,SAAS,MAAM,KAAK,UAAqB;EAAE,MAAM,KAAK;EAAM,MAAM,SAAS,UAAU,SAAS,KAAK,IAAI,GAAG,KAAK,KAAK;CAAE,EAAE;CAC9H,IAAI,UAAoB,UAAU;CAClC,IAAI,MAAM,KAAK,SAAS,eAAe,QAAQ,YAAY,KAAA,GAAW;EACpE,MAAM,EAAE,WAAW,MAAM;EACzB,MAAM,QAAQ,UAAU,IAAI,QAAQ,QAAQ,QAAQ,OAAO,IAAI,GAAG,UAAU,WAAW,OAAO,KAAK,CAAC;EACpG,UAAU,UAAU,IAAI,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"}
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,CAA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,QAAQ,UAAU,IAAI,OAAO,aAAa,KAAK,MAAM,KAAK,OAAO,IAAI,CAAC;CAChG,MAAM,SAAS,MAAM,KAAK,UAAqB;EAAE,MAAM,KAAK;EAAM,MAAM,SAAS,UAAU,SAAS,KAAK,IAAI,GAAG,KAAK,KAAK;CAAE,EAAE;CAC9H,IAAI,UAAoB,UAAU;CAClC,IAAI,MAAM,KAAK,SAAS,eAAe,QAAQ,YAAY,KAAA,GAAW;EACpE,MAAM,EAAE,WAAW,MAAM;EACzB,MAAM,QAAQ,UAAU,IAAI,QAAQ,QAAQ,QAAQ,OAAO,IAAI,GAAG,UAAU,WAAW,OAAO,KAAK,CAAC;EACpG,UAAU,UAAU,IAAI,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"}
@@ -1,188 +1,5 @@
1
+ import { b as parseGtin } from "./records-W6sPyhTQ.js";
1
2
  import { UnitError, add, compare, convert, convertible, kindOf, scale } from "@mark1russell7/quantity";
2
- import { quantitySchema } from "@mark1russell7/quantity/schema";
3
- import { z } from "zod";
4
- // src/gtin.ts
5
- /**
6
- * This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.
7
- * The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.
8
- */
9
- const LENGTHS = /* @__PURE__ */ new Set([
10
- 8,
11
- 12,
12
- 13,
13
- 14
14
- ]);
15
- /**
16
- * This function gives the check digit of the digits of a GTIN without its last digit.
17
- *
18
- * @throws RangeError when the text has a character that is not a digit, or no character.
19
- */
20
- function gtinCheckDigit(body) {
21
- if (!/^\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);
22
- let total = 0;
23
- for (let i = 0; i < body.length; i += 1) {
24
- const digit = body.charCodeAt(body.length - 1 - i) - 48;
25
- total += i % 2 === 0 ? digit * 3 : digit;
26
- }
27
- return (10 - total % 10) % 10;
28
- }
29
- /**
30
- * This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.
31
- * It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.
32
- */
33
- function parseGtin(text) {
34
- const digits = text.replace(/[\s-]/g, "");
35
- if (!/^\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;
36
- if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;
37
- return digits.padStart(14, "0");
38
- }
39
- // src/records.ts
40
- /**
41
- * The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
42
- * the field `grade` of the offer.
43
- */
44
- const CONDITIONS = [
45
- "new",
46
- "open-box",
47
- "refurbished",
48
- "used",
49
- "for-parts",
50
- "unknown"
51
- ];
52
- /** The states of the stock of an offer at the time of a reading. */
53
- const AVAILABILITIES = [
54
- "in-stock",
55
- "low-stock",
56
- "out-of-stock",
57
- "preorder",
58
- "unknown"
59
- ];
60
- /** The buying formats of an offer. In an auction, the price of a reading is the current bid. */
61
- const FORMATS = ["fixed-price", "auction"];
62
- /** This schema accepts a text with a character that is not a space, and with no space at an end. */
63
- const textSchema = z.string().refine((text) => text !== "" && text === text.trim(), "The text is empty, or it has a space at an end.");
64
- /** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */
65
- const sourceSchema = z.string().regex(/^[a-z][a-z0-9-]*$/, "The name of a source has small letters, digits and hyphens, with a letter first.");
66
- /** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */
67
- const gtinSchema = z.string().refine((text) => /^\d{14}$/.test(text) && parseGtin(text) === text, "The GTIN is not a GTIN-14 with a correct check digit.");
68
- /** This schema accepts an amount of money of zero or more, for example `{ "value": 129.99, "unit": "USD" }`. */
69
- const moneySchema = quantitySchema("money", { nonnegative: true });
70
- /** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */
71
- const instantSchema = z.iso.datetime();
72
- /** This schema accepts a part number of a maker. */
73
- const partNumberSchema = z.strictObject({
74
- brand: textSchema,
75
- partNumber: textSchema
76
- });
77
- /** This schema accepts one specification as text, for example `{ "name": "Capacity", "value": "1 TB" }`. */
78
- const specSchema = z.strictObject({
79
- name: textSchema,
80
- value: textSchema
81
- });
82
- /** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */
83
- const sellerSchema = z.strictObject({
84
- id: textSchema.optional(),
85
- name: textSchema.optional(),
86
- rating: z.strictObject({
87
- percent: z.number().min(0).max(100),
88
- count: z.int().nonnegative()
89
- }).optional()
90
- });
91
- /** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */
92
- const productSchema = z.strictObject({
93
- id: textSchema,
94
- title: textSchema,
95
- brand: textSchema.optional(),
96
- category: z.array(textSchema).optional(),
97
- gtins: z.array(gtinSchema),
98
- partNumbers: z.array(partNumberSchema),
99
- specs: z.array(specSchema)
100
- });
101
- /** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */
102
- function offerId(source, sourceId) {
103
- return `${source}:${sourceId}`;
104
- }
105
- /** This function gives the name of the source of an offer id: the text before the first colon. */
106
- function sourceOfOffer(id) {
107
- const colon = id.indexOf(":");
108
- if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);
109
- return id.slice(0, colon);
110
- }
111
- /**
112
- * This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.
113
- * `productId` names the product of the catalog after a match.
114
- */
115
- const offerSchema = z.strictObject({
116
- id: textSchema,
117
- source: sourceSchema,
118
- sourceId: textSchema,
119
- productId: textSchema.optional(),
120
- title: textSchema,
121
- url: z.url({ protocol: /^https$/ }).optional(),
122
- seller: sellerSchema,
123
- condition: z.enum(CONDITIONS),
124
- grade: textSchema.optional(),
125
- format: z.enum(FORMATS),
126
- endsAt: instantSchema.optional(),
127
- gtins: z.array(gtinSchema),
128
- partNumbers: z.array(partNumberSchema),
129
- specs: z.array(specSchema)
130
- }).refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {
131
- message: "The id of an offer is its source and its source id, with a colon between them.",
132
- path: ["id"]
133
- });
134
- /** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */
135
- const shippingSchema = z.discriminatedUnion("kind", [
136
- z.strictObject({ kind: z.literal("free") }),
137
- z.strictObject({
138
- kind: z.literal("fixed"),
139
- cost: moneySchema
140
- }),
141
- z.strictObject({ kind: z.literal("calculated") }),
142
- z.strictObject({ kind: z.literal("unknown") })
143
- ]);
144
- /** This schema accepts a price break: the unit price for an order of `quantity` units or more. */
145
- const priceBreakSchema = z.strictObject({
146
- quantity: z.int().min(2),
147
- unitPrice: moneySchema
148
- });
149
- /**
150
- * This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an
151
- * order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more
152
- * than the minimum.
153
- */
154
- const priceReadingSchema = z.strictObject({
155
- offerId: textSchema,
156
- at: instantSchema,
157
- price: moneySchema,
158
- listPrice: moneySchema.optional(),
159
- shipping: shippingSchema,
160
- availability: z.enum(AVAILABILITIES),
161
- available: z.int().nonnegative().optional(),
162
- minimumQuantity: z.int().min(1).optional(),
163
- priceBreaks: z.array(priceBreakSchema).optional()
164
- }).superRefine((reading, context) => {
165
- let last = reading.minimumQuantity ?? 1;
166
- for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {
167
- if (entry.quantity <= last) context.addIssue({
168
- code: "custom",
169
- message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,
170
- path: [
171
- "priceBreaks",
172
- index,
173
- "quantity"
174
- ]
175
- });
176
- last = Math.max(last, entry.quantity);
177
- }
178
- const { availability, available } = reading;
179
- if (available === void 0 || availability === "unknown" || availability === "preorder") return;
180
- if (availability === "out-of-stock" !== (available === 0)) context.addIssue({
181
- code: "custom",
182
- message: `The availability ${availability} does not agree with the count ${available}.`,
183
- path: ["available"]
184
- });
185
- });
186
3
  // src/identifiers.ts
187
4
  /**
188
5
  * This function folds a brand or a part number for a comparison. The result has only capital letters A to Z
@@ -374,6 +191,6 @@ function priceOf(observations, count, need) {
374
191
  why: first === void 0 ? "No offer matches the part." : `No offer is usable. The first offer that the choice skipped: ${first.why}`
375
192
  };
376
193
  }
377
- export { shippingSchema as C, textSchema as D, specSchema as E, gtinCheckDigit as O, sellerSchema as S, sourceSchema as T, offerSchema as _, priceOf as a, priceReadingSchema as b, foldCode as c, CONDITIONS as d, FORMATS as f, offerId as g, moneySchema as h, offersPart as i, parseGtin as k, matchKeys as l, instantSchema as m, latestObservations as n, costOf as o, gtinSchema as p, offersOfPart as r, unitPriceFor as s, bestOffer as t, AVAILABILITIES as u, partNumberSchema as v, sourceOfOffer as w, productSchema as x, priceBreakSchema as y };
194
+ export { priceOf as a, foldCode as c, offersPart as i, matchKeys as l, latestObservations as n, costOf as o, offersOfPart as r, unitPriceFor as s, bestOffer as t };
378
195
 
379
- //# sourceMappingURL=offers-B_8DqLSA.js.map
196
+ //# sourceMappingURL=offers-h_HvMkH_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"offers-h_HvMkH_.js","names":[],"sources":["../src/identifiers.ts","../src/price.ts","../src/offers.ts"],"sourcesContent":["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"],"mappings":";;;;;;;AAkBA,SAAgB,SAAS,MAAsB;CAC7C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,cAAc,EAAE;AACtE;;;;;;AAOA,SAAgB,UAAU,aAAoC;CAC5D,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,QAAQ,YAAY,OAAO;EACpC,MAAM,OAAO,UAAU,IAAI;EAC3B,IAAI,SAAS,MAAM,KAAK,IAAI,QAAQ,MAAM;CAC5C;CACA,KAAK,MAAM,EAAE,OAAO,gBAAgB,YAAY,aAAa;EAC3D,MAAM,SAAS,CAAC,SAAS,KAAK,GAAG,SAAS,UAAU,CAAC;EACrD,IAAI,OAAO,OAAO,SAAS,SAAS,EAAE,GAAG,KAAK,IAAI,QAAQ,OAAO,KAAK,GAAG,GAAG;CAC9E;CACA,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,KAAK;AACxB;;;;;;;;AC7BA,SAAgB,aAAa,SAAuB,OAAyB;CAC3E,MAAM,UAAU,QAAQ,mBAAmB;CAC3C,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,SAC1C,MAAM,IAAI,WAAW,aAAa,MAAM,4BAA4B,QAAQ,UAAU;CAExF,IAAI,QAAkB,QAAQ;CAC9B,KAAK,MAAM,SAAS,QAAQ,eAAe,CAAC,GAAG,IAAI,MAAM,YAAY,OAAO,QAAQ,MAAM;CAC1F,OAA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AAK;CAC/F,IAAI,OAAO,OAAO,SAAS,GAAG,OAAO;EAAE,IAAI;EAAO,KAAK,eAAe,OAAO,KAAK,EAAE;CAAuC;CAC3H,MAAM,QAAQ,OAAO,QAAQ;CAC7B,OAAO;EAAE,IAAI;EAAO,KAAK,UAAU,KAAA,IAAY,+BAA+B,gEAAgE,MAAM;CAAM;AAC5J"}
package/build/plan.js CHANGED
@@ -1,4 +1,5 @@
1
- import { D as textSchema, a as priceOf, d as CONDITIONS, r as offersOfPart } from "./offers-B_8DqLSA.js";
1
+ import { a as priceOf, r as offersOfPart } from "./offers-h_HvMkH_.js";
2
+ import { n as CONDITIONS, v as textSchema } from "./records-W6sPyhTQ.js";
2
3
  import { compare, sum, valueIn } from "@mark1russell7/quantity";
3
4
  import { z } from "zod";
4
5
  import { evolve, frontOf, greedy, sweep } from "@mark1russell7/strategy-search";