@krizaka/settings 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -2
- package/dist/index.d.ts +158 -3
- package/dist/index.js +193 -7
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -3,13 +3,41 @@
|
|
|
3
3
|
A product's configuration as **data**: a typed registry of settings (flags, integers, choices, subsets, bilingual texts), resolved **user → workspace → global → default**, changed by an administrator without a redeploy, **every change leaving an audit line** (who, what, when, before, after). A JSON-safe description of the registry is what an admin screen draws from.
|
|
4
4
|
|
|
5
5
|
```ts
|
|
6
|
-
import { defineSettings, flag, integer,
|
|
6
|
+
import { defineSettings, flag, integer, dbSettings, settingsMigration, GLOBAL, WORKSPACE_SCOPES } from "@krizaka/settings";
|
|
7
7
|
|
|
8
8
|
const settings = defineSettings({ "features.apiKeys": flag("features", true, WORKSPACE_SCOPES), "limits.maxFileMb": integer("limits", 10, { min: 1, max: 10, unit: "MB" }) } as const);
|
|
9
9
|
await db.query(settingsMigration()); // once, in your migrations (idempotent)
|
|
10
|
-
const service =
|
|
10
|
+
const service = dbSettings(settings, { query, workspaceOf, clock: () => performance.now() });
|
|
11
11
|
await service.get("features.apiKeys", { userId }); // typed: boolean
|
|
12
12
|
await service.set({ id: adminId, label: email }, GLOBAL, "features.apiKeys", false, now);
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
What stays in the product: its registry (the keys, groups, defaults), the checks it makes at its own boundary (« the server refuses what is off »), who may be an administrator, the HTTP routes. The clock is passed in; nothing here reads it.
|
|
16
|
+
|
|
17
|
+
## Prices — the catalogue (ADR-009)
|
|
18
|
+
|
|
19
|
+
A product's prices are data too: a typed **catalogue** of entries (`product.plan`, unit, amount in cents or « on quote », **CAD**,
|
|
20
|
+
**before taxes**, availability `public` · `internal` · `founder-limited` · `preparing`, named limits). The product's former pricing
|
|
21
|
+
module becomes the **seed**; its administrator changes an entry by **scheduling a version from a date** (now or later, never the
|
|
22
|
+
past), and every change writes an audit line in `settings_audit` (`price.<product>.<plan>`). A subscription records the version it
|
|
23
|
+
was sold at (`versionId`) and keeps it.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { AVAILABILITY, definePrices, findTypedPrices, priceCatalogue, pricesMigration, priceStore, publicCatalogue, UNIT } from "@krizaka/settings";
|
|
27
|
+
|
|
28
|
+
const prices = definePrices([
|
|
29
|
+
{ product: "akinaza", plan: "starter", unit: UNIT.month, amountCents: 4500, availability: AVAILABILITY.founderLimited, limits: { founderCap: 20 } },
|
|
30
|
+
{ product: "akinaza", plan: "scale", unit: UNIT.month, amountCents: 9900, availability: AVAILABILITY.preparing },
|
|
31
|
+
]);
|
|
32
|
+
await db.query(pricesMigration()); // once, in your migrations (idempotent; includes the settings' tables)
|
|
33
|
+
const catalogue = priceCatalogue(prices, priceStore({ query }));
|
|
34
|
+
const shown = publicCatalogue(await catalogue.catalogue(now)); // a public page: never internal, « en préparation » without a figure
|
|
35
|
+
await catalogue.schedule({ id: adminId, label: email }, "akinaza.starter", { amountCents: 4900 }, effectiveFrom, now);
|
|
36
|
+
const sold = await catalogue.version(subscription.priceVersionId); // the price it was sold at, forever
|
|
37
|
+
expect(findTypedPrices(messages)).toEqual([]); // a product's test: no amount typed in a message
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`describePrices(catalogue, now)` is the JSON-safe description an admin screen draws (with what is already scheduled);
|
|
41
|
+
`memoryPriceStore()` serves tests. The amount reaches the processor through `@krizaka/payments`, by the entry's key.
|
|
42
|
+
|
|
43
|
+
> `postgresSettings` was the first name of `dbSettings`; it stays as a `@deprecated` alias for one minor and leaves in the next major.
|
package/dist/index.d.ts
CHANGED
|
@@ -89,6 +89,91 @@ declare const describeSettings: <R extends Registry>(settings: SettingsDefinitio
|
|
|
89
89
|
*/
|
|
90
90
|
declare function settingsMigration(): string;
|
|
91
91
|
|
|
92
|
+
/**
|
|
93
|
+
* A product's prices as DATA (ADR-009, krizaka/.github#253): a typed catalogue of entries — product, plan, unit, amount, CAD, before
|
|
94
|
+
* taxes, availability, named limits — whose seed is the product's former pricing module. An administrator changes an entry by
|
|
95
|
+
* scheduling a new version from a date; a subscription keeps the version it was sold at. Public pages read the catalogue only.
|
|
96
|
+
*/
|
|
97
|
+
declare const UNIT: {
|
|
98
|
+
readonly month: "month";
|
|
99
|
+
readonly year: "year";
|
|
100
|
+
readonly once: "once";
|
|
101
|
+
readonly document: "document";
|
|
102
|
+
readonly order: "order";
|
|
103
|
+
readonly pack: "pack";
|
|
104
|
+
readonly hour: "hour";
|
|
105
|
+
};
|
|
106
|
+
type Unit = (typeof UNIT)[keyof typeof UNIT];
|
|
107
|
+
/** Who may see an entry: everyone with its figure, nobody outside, the first customers only (a cap in `limits`), or « en préparation » (no figure). */
|
|
108
|
+
declare const AVAILABILITY: {
|
|
109
|
+
readonly public: "public";
|
|
110
|
+
readonly internal: "internal";
|
|
111
|
+
readonly founderLimited: "founder-limited";
|
|
112
|
+
readonly preparing: "preparing";
|
|
113
|
+
};
|
|
114
|
+
type Availability = (typeof AVAILABILITY)[keyof typeof AVAILABILITY];
|
|
115
|
+
/** What a version of an entry holds. Every price is in Canadian dollars, shown before GST and QST (the processor adds them). */
|
|
116
|
+
declare const priceSchema: z.ZodObject<{
|
|
117
|
+
unit: z.ZodEnum<{
|
|
118
|
+
month: "month";
|
|
119
|
+
year: "year";
|
|
120
|
+
once: "once";
|
|
121
|
+
document: "document";
|
|
122
|
+
order: "order";
|
|
123
|
+
pack: "pack";
|
|
124
|
+
hour: "hour";
|
|
125
|
+
}>;
|
|
126
|
+
amountCents: z.ZodNullable<z.ZodNumber>;
|
|
127
|
+
currency: z.ZodLiteral<"CAD">;
|
|
128
|
+
taxes: z.ZodLiteral<"plus-taxes">;
|
|
129
|
+
availability: z.ZodEnum<{
|
|
130
|
+
public: "public";
|
|
131
|
+
internal: "internal";
|
|
132
|
+
"founder-limited": "founder-limited";
|
|
133
|
+
preparing: "preparing";
|
|
134
|
+
}>;
|
|
135
|
+
limits: z.ZodRecord<z.ZodString, z.ZodNumber>;
|
|
136
|
+
}, z.core.$strict>;
|
|
137
|
+
type Price = z.infer<typeof priceSchema>;
|
|
138
|
+
interface PriceSeed {
|
|
139
|
+
product: string;
|
|
140
|
+
plan: string;
|
|
141
|
+
unit: Unit;
|
|
142
|
+
amountCents: number | null;
|
|
143
|
+
availability: Availability;
|
|
144
|
+
limits?: Record<string, number>;
|
|
145
|
+
}
|
|
146
|
+
/** An entry as read at a date: its key, the version in force and from when. */
|
|
147
|
+
interface PriceEntry extends Price {
|
|
148
|
+
key: string;
|
|
149
|
+
product: string;
|
|
150
|
+
plan: string;
|
|
151
|
+
versionId: string;
|
|
152
|
+
effectiveFrom: Date;
|
|
153
|
+
}
|
|
154
|
+
declare class PriceError extends Error {
|
|
155
|
+
readonly status: number;
|
|
156
|
+
readonly code: "UNKNOWN_PRICE" | "BAD_VALUE" | "BAD_DATE";
|
|
157
|
+
constructor(status: number, code: "UNKNOWN_PRICE" | "BAD_VALUE" | "BAD_DATE", message: string);
|
|
158
|
+
}
|
|
159
|
+
/** The seed version of an entry: its id and the date it is in force from (always). */
|
|
160
|
+
declare const seedVersionId: (key: string) => string;
|
|
161
|
+
declare const SEED_FROM: Date;
|
|
162
|
+
/** The catalogue's definition: its keys and their defaults, each validated (a bad seed fails at start, never on a page). */
|
|
163
|
+
declare function definePrices(seed: readonly PriceSeed[]): {
|
|
164
|
+
keys: string[];
|
|
165
|
+
isKey: (key: string) => boolean;
|
|
166
|
+
defaultOf: (key: string) => Price;
|
|
167
|
+
};
|
|
168
|
+
type PricesDefinition = ReturnType<typeof definePrices>;
|
|
169
|
+
/** What a public page shows: never an internal entry; an entry in preparation without its figure or its limits. */
|
|
170
|
+
interface PublicPrice extends Omit<PriceEntry, "effectiveFrom"> {
|
|
171
|
+
effectiveFrom: string;
|
|
172
|
+
}
|
|
173
|
+
declare const publicCatalogue: (entries: readonly PriceEntry[]) => PublicPrice[];
|
|
174
|
+
/** The paths of every message that types an amount — a product's « every price comes from the catalogue » test fails on any. */
|
|
175
|
+
declare function findTypedPrices(messages: unknown, path?: string[]): string[];
|
|
176
|
+
|
|
92
177
|
/** What each scope has set for one key (absent = not overridden there). */
|
|
93
178
|
type Layers = Partial<Record<Scope, unknown>>;
|
|
94
179
|
interface Resolved<T = unknown> {
|
|
@@ -146,7 +231,7 @@ interface SettingsService<R extends Registry> {
|
|
|
146
231
|
limit?: number;
|
|
147
232
|
}): Promise<AuditEntry[]>;
|
|
148
233
|
}
|
|
149
|
-
interface
|
|
234
|
+
interface DbSettingsDeps<R extends Registry> {
|
|
150
235
|
query: Query;
|
|
151
236
|
/** The workspace a user belongs to (null while the product has no workspaces). */
|
|
152
237
|
workspaceOf?: (userId: string) => Promise<string | null>;
|
|
@@ -158,7 +243,77 @@ interface PostgresSettingsDeps<R extends Registry> {
|
|
|
158
243
|
clock?: () => number;
|
|
159
244
|
}
|
|
160
245
|
/** The adapter over the product's PostgreSQL (`app_settings`, `settings_audit`; see `settingsMigration`). */
|
|
161
|
-
declare function
|
|
246
|
+
declare function dbSettings<R extends Registry>(settings: SettingsDefinition<R>, deps: DbSettingsDeps<R>): SettingsService<R>;
|
|
247
|
+
/** @deprecated The old name of `dbSettings` (a name says what a thing does, not the technology). Removed in the next major. */
|
|
248
|
+
declare const postgresSettings: typeof dbSettings;
|
|
249
|
+
/** @deprecated The old name of `DbSettingsDeps`. Removed in the next major. */
|
|
250
|
+
type PostgresSettingsDeps<R extends Registry> = DbSettingsDeps<R>;
|
|
251
|
+
|
|
252
|
+
/** A version an administrator scheduled: the price in force from `effectiveFrom`, and the one it replaced at that date. */
|
|
253
|
+
interface StoredPriceVersion {
|
|
254
|
+
id: string;
|
|
255
|
+
key: string;
|
|
256
|
+
price: Price;
|
|
257
|
+
before: Price;
|
|
258
|
+
effectiveFrom: Date;
|
|
259
|
+
createdAt: Date;
|
|
260
|
+
actorLabel: string;
|
|
261
|
+
}
|
|
262
|
+
/** Where the versions live (the product's database, or memory in tests). Versions are only ever added. */
|
|
263
|
+
interface PriceStore {
|
|
264
|
+
/** Every version of a key, oldest scheduled first. */
|
|
265
|
+
versions(key: string): Promise<StoredPriceVersion[]>;
|
|
266
|
+
version(id: string): Promise<StoredPriceVersion | null>;
|
|
267
|
+
/** Adds a version and its audit line, atomically. */
|
|
268
|
+
insert(version: Omit<StoredPriceVersion, "id">, actor: Actor): Promise<StoredPriceVersion>;
|
|
269
|
+
}
|
|
270
|
+
interface PriceHistoryLine {
|
|
271
|
+
versionId: string;
|
|
272
|
+
at: string;
|
|
273
|
+
actorLabel: string;
|
|
274
|
+
effectiveFrom: string;
|
|
275
|
+
before: Price | null;
|
|
276
|
+
after: Price;
|
|
277
|
+
}
|
|
278
|
+
/** The catalogue a product reads and its administrator edits. */
|
|
279
|
+
interface PriceCatalogue {
|
|
280
|
+
/** The entry in force at a date (a page passes now; an invoice passes the subscription's date). */
|
|
281
|
+
entry(key: string, at: Date): Promise<PriceEntry>;
|
|
282
|
+
catalogue(at: Date): Promise<PriceEntry[]>;
|
|
283
|
+
/** The version a subscription was sold at, forever; null for an id that is not one. */
|
|
284
|
+
version(id: string): Promise<PriceEntry | null>;
|
|
285
|
+
/** A change from a date (now or later, never the past): a new version over the one in force then. */
|
|
286
|
+
schedule(actor: Actor, key: string, change: Partial<Price>, effectiveFrom: Date, now: Date): Promise<PriceEntry>;
|
|
287
|
+
/** Every change of a key, newest first, ending with the seed. */
|
|
288
|
+
history(key: string): Promise<PriceHistoryLine[]>;
|
|
289
|
+
/** The versions scheduled after a date. */
|
|
290
|
+
upcoming(key: string, at: Date): Promise<PriceEntry[]>;
|
|
291
|
+
}
|
|
292
|
+
declare function priceCatalogue(prices: PricesDefinition, store: PriceStore): PriceCatalogue;
|
|
293
|
+
/** Versions in memory: for tests and for a product's first steps. */
|
|
294
|
+
declare function memoryPriceStore(): PriceStore;
|
|
295
|
+
/** The catalogue as the admin screen draws it: JSON-safe, with the enumerations its fields offer and what is already scheduled. */
|
|
296
|
+
interface PricesDescription {
|
|
297
|
+
units: Unit[];
|
|
298
|
+
availabilities: Availability[];
|
|
299
|
+
entries: (Omit<PriceEntry, "effectiveFrom"> & {
|
|
300
|
+
effectiveFrom: string;
|
|
301
|
+
upcoming: (Price & {
|
|
302
|
+
versionId: string;
|
|
303
|
+
effectiveFrom: string;
|
|
304
|
+
})[];
|
|
305
|
+
})[];
|
|
306
|
+
}
|
|
307
|
+
declare function describePrices(catalogue: PriceCatalogue, at: Date): Promise<PricesDescription>;
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The price versions in the product's PostgreSQL (`price_versions`), each insert writing its audit line in `settings_audit`
|
|
311
|
+
* (key `price.<product>.<plan>`) in the same statement. Rows are only ever added: a version once sold is never rewritten.
|
|
312
|
+
*/
|
|
313
|
+
declare function pricesMigration(): string;
|
|
314
|
+
declare function priceStore({ query }: {
|
|
315
|
+
query: Query;
|
|
316
|
+
}): PriceStore;
|
|
162
317
|
|
|
163
318
|
/**
|
|
164
319
|
* A deployment that was configured by environment before settings existed keeps behaving the same: at server start, each legacy value
|
|
@@ -167,4 +322,4 @@ declare function postgresSettings<R extends Registry>(settings: SettingsDefiniti
|
|
|
167
322
|
*/
|
|
168
323
|
declare function seedLegacySettings<R extends Registry>(settings: SettingsDefinition<R>, service: SettingsService<R>, legacy: Partial<Record<KeyOf<R>, unknown>>, now: Date): Promise<KeyOf<R>[]>;
|
|
169
324
|
|
|
170
|
-
export { ALL_SCOPES, type Actor, type AuditEntry, type Context, type Def, GLOBAL, GLOBAL_ONLY, KIND, type KeyOf, type Kind, type Layers, type PostgresSettingsDeps, type Query, type Registry, type Resolved, SCOPE, SCOPES_BY_SPECIFICITY, type Scope, type ScopeRef, type SettingDescription, type SettingsDefinition, SettingsError, type SettingsService, type ValueOf, WORKSPACE_SCOPES, bilingual, choice, defineSettings, describeSettings, flag, integer, postgresSettings, resolveValue, seedLegacySettings, settingsMigration, subset };
|
|
325
|
+
export { ALL_SCOPES, AVAILABILITY, type Actor, type AuditEntry, type Availability, type Context, type DbSettingsDeps, type Def, GLOBAL, GLOBAL_ONLY, KIND, type KeyOf, type Kind, type Layers, type PostgresSettingsDeps, type Price, type PriceCatalogue, type PriceEntry, PriceError, type PriceHistoryLine, type PriceSeed, type PriceStore, type PricesDefinition, type PricesDescription, type PublicPrice, type Query, type Registry, type Resolved, SCOPE, SCOPES_BY_SPECIFICITY, SEED_FROM, type Scope, type ScopeRef, type SettingDescription, type SettingsDefinition, SettingsError, type SettingsService, type StoredPriceVersion, UNIT, type Unit, type ValueOf, WORKSPACE_SCOPES, bilingual, choice, dbSettings, definePrices, defineSettings, describePrices, describeSettings, findTypedPrices, flag, integer, memoryPriceStore, postgresSettings, priceCatalogue, priceSchema, priceStore, pricesMigration, publicCatalogue, resolveValue, seedLegacySettings, seedVersionId, settingsMigration, subset };
|
package/dist/index.js
CHANGED
|
@@ -32,19 +32,189 @@ CREATE INDEX IF NOT EXISTS settings_audit_key ON settings_audit(key, id DESC);
|
|
|
32
32
|
`;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
// src/
|
|
35
|
+
// src/prices.ts
|
|
36
36
|
import { z } from "zod";
|
|
37
|
+
var UNIT = { month: "month", year: "year", once: "once", document: "document", order: "order", pack: "pack", hour: "hour" };
|
|
38
|
+
var UNITS = Object.values(UNIT);
|
|
39
|
+
var AVAILABILITY = { public: "public", internal: "internal", founderLimited: "founder-limited", preparing: "preparing" };
|
|
40
|
+
var AVAILABILITIES = Object.values(AVAILABILITY);
|
|
41
|
+
var ID = /^[a-z][a-zA-Z0-9-]{0,39}$/;
|
|
42
|
+
var LIMIT = /^[a-z][a-zA-Z0-9]{0,39}$/;
|
|
43
|
+
var MAX_CENTS = 1e8;
|
|
44
|
+
var priceSchema = z.object({
|
|
45
|
+
unit: z.enum(UNITS),
|
|
46
|
+
/** Integer cents; `null` is « on quote ». */
|
|
47
|
+
amountCents: z.number().int().min(0).max(MAX_CENTS).nullable(),
|
|
48
|
+
currency: z.literal("CAD"),
|
|
49
|
+
taxes: z.literal("plus-taxes"),
|
|
50
|
+
availability: z.enum(AVAILABILITIES),
|
|
51
|
+
/** Named integers the product reads: `included`, `overageCents`, `founderCap`, `feeBps`, `feeCapCents`… */
|
|
52
|
+
limits: z.record(z.string().regex(LIMIT), z.number().int().min(0).max(MAX_CENTS))
|
|
53
|
+
}).strict().refine((p) => p.amountCents !== null || p.availability !== AVAILABILITY.public && p.availability !== AVAILABILITY.founderLimited, { message: "An entry on sale has a figure" });
|
|
54
|
+
var PriceError = class extends Error {
|
|
55
|
+
constructor(status, code, message) {
|
|
56
|
+
super(message);
|
|
57
|
+
this.status = status;
|
|
58
|
+
this.code = code;
|
|
59
|
+
this.name = "PriceError";
|
|
60
|
+
}
|
|
61
|
+
status;
|
|
62
|
+
code;
|
|
63
|
+
};
|
|
64
|
+
var seedVersionId = (key) => `seed:${key}`;
|
|
65
|
+
var SEED_FROM = /* @__PURE__ */ new Date(0);
|
|
66
|
+
function definePrices(seed) {
|
|
67
|
+
const defaults = /* @__PURE__ */ new Map();
|
|
68
|
+
for (const s of seed) {
|
|
69
|
+
if (!ID.test(s.product) || !ID.test(s.plan)) throw new PriceError(400, "BAD_VALUE", `Not a product or plan id: ${s.product}.${s.plan}`);
|
|
70
|
+
const key = `${s.product}.${s.plan}`;
|
|
71
|
+
if (defaults.has(key)) throw new PriceError(400, "BAD_VALUE", `Twice in the seed: ${key}`);
|
|
72
|
+
const parsed = priceSchema.safeParse({ unit: s.unit, amountCents: s.amountCents, currency: "CAD", taxes: "plus-taxes", availability: s.availability, limits: s.limits ?? {} });
|
|
73
|
+
if (!parsed.success) throw new PriceError(400, "BAD_VALUE", `Not a valid price for ${key}`);
|
|
74
|
+
defaults.set(key, parsed.data);
|
|
75
|
+
}
|
|
76
|
+
const keys = [...defaults.keys()];
|
|
77
|
+
const isKey = (key) => defaults.has(key);
|
|
78
|
+
const defaultOf = (key) => {
|
|
79
|
+
const d = defaults.get(key);
|
|
80
|
+
if (!d) throw new PriceError(404, "UNKNOWN_PRICE", `No such price: ${key}`);
|
|
81
|
+
return d;
|
|
82
|
+
};
|
|
83
|
+
return { keys, isKey, defaultOf };
|
|
84
|
+
}
|
|
85
|
+
var publicCatalogue = (entries) => entries.filter((e) => e.availability !== AVAILABILITY.internal).map((e) => ({ ...e, effectiveFrom: e.effectiveFrom.toISOString(), ...e.availability === AVAILABILITY.preparing ? { amountCents: null, limits: {} } : {} }));
|
|
86
|
+
var TYPED_PRICE = /\d(?:[\d\s\u00a0\u202f.,]*\d)?\s?(?:\$|CAD\b|USD\b|€)|\$\s?\d/u;
|
|
87
|
+
function findTypedPrices(messages, path = []) {
|
|
88
|
+
if (typeof messages === "string") return TYPED_PRICE.test(messages) ? [path.join(".")] : [];
|
|
89
|
+
if (Array.isArray(messages)) return messages.flatMap((m, i) => findTypedPrices(m, [...path, String(i)]));
|
|
90
|
+
if (messages && typeof messages === "object") return Object.entries(messages).flatMap(([k, v]) => findTypedPrices(v, [...path, k]));
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/price-catalogue.ts
|
|
95
|
+
var split = (key) => {
|
|
96
|
+
const dot = key.indexOf(".");
|
|
97
|
+
return { product: key.slice(0, dot), plan: key.slice(dot + 1) };
|
|
98
|
+
};
|
|
99
|
+
var toEntry = (key, price, versionId, effectiveFrom) => ({ key, ...split(key), ...price, versionId, effectiveFrom });
|
|
100
|
+
var fromStored = (v) => toEntry(v.key, v.price, v.id, v.effectiveFrom);
|
|
101
|
+
var inForce = (versions, at) => versions.filter((v) => v.effectiveFrom <= at).reduce((best, v) => !best || v.effectiveFrom >= best.effectiveFrom ? v : best, void 0);
|
|
102
|
+
function priceCatalogue(prices, store) {
|
|
103
|
+
const known = (key) => {
|
|
104
|
+
if (!prices.isKey(key)) throw new PriceError(404, "UNKNOWN_PRICE", `No such price: ${key}`);
|
|
105
|
+
return key;
|
|
106
|
+
};
|
|
107
|
+
async function entry(key, at) {
|
|
108
|
+
const v = inForce(await store.versions(known(key)), at);
|
|
109
|
+
return v ? fromStored(v) : toEntry(key, prices.defaultOf(key), seedVersionId(key), SEED_FROM);
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
entry,
|
|
113
|
+
catalogue: (at) => Promise.all(prices.keys.map((k) => entry(k, at))),
|
|
114
|
+
async version(id) {
|
|
115
|
+
if (id.startsWith("seed:")) {
|
|
116
|
+
const key = id.slice("seed:".length);
|
|
117
|
+
return prices.isKey(key) ? toEntry(key, prices.defaultOf(key), id, SEED_FROM) : null;
|
|
118
|
+
}
|
|
119
|
+
const v = /^\d{1,18}$/.test(id) ? await store.version(id) : null;
|
|
120
|
+
return v ? fromStored(v) : null;
|
|
121
|
+
},
|
|
122
|
+
async schedule(actor, key, change, effectiveFrom, now) {
|
|
123
|
+
known(key);
|
|
124
|
+
if (!(effectiveFrom instanceof Date) || Number.isNaN(effectiveFrom.getTime()) || effectiveFrom < now) throw new PriceError(400, "BAD_DATE", "A price changes from now or later, never in the past");
|
|
125
|
+
const current = await entry(key, effectiveFrom);
|
|
126
|
+
const { key: _k, product: _p, plan: _pl, versionId: _v, effectiveFrom: _e, ...before } = current;
|
|
127
|
+
const parsed = priceSchema.safeParse({ ...before, ...change });
|
|
128
|
+
if (!parsed.success) throw new PriceError(400, "BAD_VALUE", `Not a valid price for ${key}`);
|
|
129
|
+
return fromStored(await store.insert({ key, price: parsed.data, before, effectiveFrom, createdAt: now, actorLabel: actor.label }, actor));
|
|
130
|
+
},
|
|
131
|
+
async history(key) {
|
|
132
|
+
const versions = await store.versions(known(key));
|
|
133
|
+
const lines = versions.map((v) => ({ versionId: v.id, at: v.createdAt.toISOString(), actorLabel: v.actorLabel, effectiveFrom: v.effectiveFrom.toISOString(), before: v.before, after: v.price }));
|
|
134
|
+
const seed = { versionId: seedVersionId(key), at: SEED_FROM.toISOString(), actorLabel: "seed", effectiveFrom: SEED_FROM.toISOString(), before: null, after: prices.defaultOf(key) };
|
|
135
|
+
return [...lines.reverse(), seed];
|
|
136
|
+
},
|
|
137
|
+
async upcoming(key, at) {
|
|
138
|
+
return (await store.versions(known(key))).filter((v) => v.effectiveFrom > at).map(fromStored);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
function memoryPriceStore() {
|
|
143
|
+
const rows = [];
|
|
144
|
+
return {
|
|
145
|
+
versions: async (key) => rows.filter((r) => r.key === key),
|
|
146
|
+
version: async (id) => rows.find((r) => r.id === id) ?? null,
|
|
147
|
+
async insert(version) {
|
|
148
|
+
const row = { ...version, id: String(rows.length + 1) };
|
|
149
|
+
rows.push(row);
|
|
150
|
+
return row;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
async function describePrices(catalogue, at) {
|
|
155
|
+
const iso = (e) => ({ ...e, effectiveFrom: e.effectiveFrom.toISOString() });
|
|
156
|
+
const entries = await Promise.all(
|
|
157
|
+
(await catalogue.catalogue(at)).map(async (e) => ({ ...iso(e), upcoming: (await catalogue.upcoming(e.key, at)).map(({ key: _k, product: _p, plan: _pl, ...v }) => iso(v)) }))
|
|
158
|
+
);
|
|
159
|
+
return { units: Object.values(UNIT), availabilities: Object.values(AVAILABILITY), entries };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/prices-persistence.ts
|
|
163
|
+
function pricesMigration() {
|
|
164
|
+
return `${settingsMigration()}
|
|
165
|
+
CREATE TABLE IF NOT EXISTS price_versions (
|
|
166
|
+
id bigserial PRIMARY KEY,
|
|
167
|
+
key text NOT NULL CHECK (key ~ '^[a-z][a-zA-Z0-9-]{0,39}[.][a-z][a-zA-Z0-9-]{0,39}$'),
|
|
168
|
+
price jsonb NOT NULL,
|
|
169
|
+
before jsonb NOT NULL,
|
|
170
|
+
effective_from timestamptz NOT NULL,
|
|
171
|
+
created_at timestamptz NOT NULL,
|
|
172
|
+
actor_id uuid,
|
|
173
|
+
actor_label text NOT NULL
|
|
174
|
+
);
|
|
175
|
+
CREATE INDEX IF NOT EXISTS price_versions_key ON price_versions(key, id);
|
|
176
|
+
`;
|
|
177
|
+
}
|
|
178
|
+
var COLUMNS = "id, key, price, before, effective_from, created_at, actor_label";
|
|
179
|
+
var fromRow = (r) => ({ id: String(r.id), key: r.key, price: r.price, before: r.before, effectiveFrom: r.effective_from, createdAt: r.created_at, actorLabel: r.actor_label });
|
|
180
|
+
function priceStore({ query }) {
|
|
181
|
+
return {
|
|
182
|
+
async versions(key) {
|
|
183
|
+
return (await query(`SELECT ${COLUMNS} FROM price_versions WHERE key = $1 ORDER BY id`, [key])).map(fromRow);
|
|
184
|
+
},
|
|
185
|
+
async version(id) {
|
|
186
|
+
const row = (await query(`SELECT ${COLUMNS} FROM price_versions WHERE id = $1`, [id]))[0];
|
|
187
|
+
return row ? fromRow(row) : null;
|
|
188
|
+
},
|
|
189
|
+
async insert(v, actor) {
|
|
190
|
+
const rows = await query(
|
|
191
|
+
`WITH v AS (
|
|
192
|
+
INSERT INTO price_versions (key, price, before, effective_from, created_at, actor_id, actor_label) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING ${COLUMNS}
|
|
193
|
+
), a AS (
|
|
194
|
+
INSERT INTO settings_audit (at, actor_id, actor_label, scope, scope_id, key, before, after)
|
|
195
|
+
SELECT $5, $6, $7, 'global', '', 'price.' || $1, $3, jsonb_set($2::jsonb, '{effectiveFrom}', to_jsonb($4::timestamptz)) FROM v
|
|
196
|
+
)
|
|
197
|
+
SELECT ${COLUMNS} FROM v`,
|
|
198
|
+
[v.key, JSON.stringify(v.price), JSON.stringify(v.before), v.effectiveFrom, v.createdAt, actor.id, actor.label]
|
|
199
|
+
);
|
|
200
|
+
return fromRow(rows[0]);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// src/registry.ts
|
|
206
|
+
import { z as z2 } from "zod";
|
|
37
207
|
var SCOPE = { global: "global", workspace: "workspace", user: "user" };
|
|
38
208
|
var SCOPES_BY_SPECIFICITY = [SCOPE.user, SCOPE.workspace, SCOPE.global];
|
|
39
209
|
var KIND = { flag: "flag", integer: "integer", choice: "choice", bilingual: "bilingual", subset: "subset" };
|
|
40
210
|
var ALL_SCOPES = [SCOPE.global, SCOPE.workspace, SCOPE.user];
|
|
41
211
|
var WORKSPACE_SCOPES = [SCOPE.global, SCOPE.workspace];
|
|
42
212
|
var GLOBAL_ONLY = [SCOPE.global];
|
|
43
|
-
var flag = (group, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.flag, schema:
|
|
44
|
-
var integer = (group, value, bounds, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.integer, schema:
|
|
45
|
-
var choice = (group, choices, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.choice, schema:
|
|
46
|
-
var subset = (group, choices, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.subset, schema:
|
|
47
|
-
var bilingual = (group, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.bilingual, schema:
|
|
213
|
+
var flag = (group, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.flag, schema: z2.boolean(), default: value, scopes });
|
|
214
|
+
var integer = (group, value, bounds, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.integer, schema: z2.number().int().min(bounds.min).max(bounds.max), default: value, scopes, ...bounds });
|
|
215
|
+
var choice = (group, choices, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.choice, schema: z2.enum(choices), default: value, scopes, choices });
|
|
216
|
+
var subset = (group, choices, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.subset, schema: z2.array(z2.enum(choices)).min(1), default: value, scopes, choices });
|
|
217
|
+
var bilingual = (group, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.bilingual, schema: z2.object({ fr: z2.string().trim().min(1).max(500), en: z2.string().trim().min(1).max(500) }), default: value, scopes });
|
|
48
218
|
function defineSettings(registry) {
|
|
49
219
|
const keys = Object.keys(registry);
|
|
50
220
|
const defOf = (key) => registry[key];
|
|
@@ -78,7 +248,7 @@ var SettingsError = class extends Error {
|
|
|
78
248
|
code;
|
|
79
249
|
};
|
|
80
250
|
var cacheKey = (s) => `${s.scope}:${s.id}`;
|
|
81
|
-
function
|
|
251
|
+
function dbSettings(settings, deps) {
|
|
82
252
|
const { query } = deps;
|
|
83
253
|
const cacheMs = deps.cacheMs ?? 5e3;
|
|
84
254
|
const clock = deps.clock ?? (() => 0);
|
|
@@ -144,6 +314,7 @@ function postgresSettings(settings, deps) {
|
|
|
144
314
|
}
|
|
145
315
|
};
|
|
146
316
|
}
|
|
317
|
+
var postgresSettings = dbSettings;
|
|
147
318
|
|
|
148
319
|
// src/seed.ts
|
|
149
320
|
async function seedLegacySettings(settings, service, legacy, now) {
|
|
@@ -158,22 +329,37 @@ async function seedLegacySettings(settings, service, legacy, now) {
|
|
|
158
329
|
}
|
|
159
330
|
export {
|
|
160
331
|
ALL_SCOPES,
|
|
332
|
+
AVAILABILITY,
|
|
161
333
|
GLOBAL,
|
|
162
334
|
GLOBAL_ONLY,
|
|
163
335
|
KIND,
|
|
336
|
+
PriceError,
|
|
164
337
|
SCOPE,
|
|
165
338
|
SCOPES_BY_SPECIFICITY,
|
|
339
|
+
SEED_FROM,
|
|
166
340
|
SettingsError,
|
|
341
|
+
UNIT,
|
|
167
342
|
WORKSPACE_SCOPES,
|
|
168
343
|
bilingual,
|
|
169
344
|
choice,
|
|
345
|
+
dbSettings,
|
|
346
|
+
definePrices,
|
|
170
347
|
defineSettings,
|
|
348
|
+
describePrices,
|
|
171
349
|
describeSettings,
|
|
350
|
+
findTypedPrices,
|
|
172
351
|
flag,
|
|
173
352
|
integer,
|
|
353
|
+
memoryPriceStore,
|
|
174
354
|
postgresSettings,
|
|
355
|
+
priceCatalogue,
|
|
356
|
+
priceSchema,
|
|
357
|
+
priceStore,
|
|
358
|
+
pricesMigration,
|
|
359
|
+
publicCatalogue,
|
|
175
360
|
resolveValue,
|
|
176
361
|
seedLegacySettings,
|
|
362
|
+
seedVersionId,
|
|
177
363
|
settingsMigration,
|
|
178
364
|
subset
|
|
179
365
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/describe.ts","../src/migration.ts","../src/registry.ts","../src/resolve.ts","../src/service.ts","../src/seed.ts"],"sourcesContent":["import type { KeyOf, Kind, Registry, Scope, SettingsDefinition } from \"./registry\";\n\n/** A setting as an administration screen draws it: JSON-safe (no schema), so it can cross to the browser. */\nexport interface SettingDescription<K extends string = string> {\n key: K;\n group: string;\n kind: Kind;\n default: unknown;\n scopes: readonly Scope[];\n min?: number;\n max?: number;\n unit?: string;\n choices?: readonly string[];\n}\n\nexport const describeSettings = <R extends Registry>(settings: SettingsDefinition<R>): SettingDescription<KeyOf<R>>[] =>\n settings.keys.map((key) => {\n const { group, kind, default: dflt, scopes, min, max, unit, choices } = settings.defOf(key);\n return { key, group, kind, default: dflt, scopes, min, max, unit, choices };\n });\n","/**\n * The tables of the settings: the overrides (global, for a workspace, for one user — the most specific wins) and the audit of every\n * change (who, what, when, before, after). Idempotent, safe on a database that already has them.\n */\nexport function settingsMigration(): string {\n return `\nCREATE TABLE IF NOT EXISTS app_settings (\n scope text NOT NULL CHECK (scope IN ('global', 'workspace', 'user')),\n scope_id text NOT NULL DEFAULT '',\n key text NOT NULL CHECK (key ~ '^[a-zA-Z0-9.]{1,80}$'),\n value jsonb NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now(),\n updated_by uuid,\n PRIMARY KEY (scope, scope_id, key),\n CHECK ((scope = 'global') = (scope_id = ''))\n);\nCREATE TABLE IF NOT EXISTS settings_audit (\n id bigserial PRIMARY KEY,\n at timestamptz NOT NULL DEFAULT now(),\n actor_id uuid,\n actor_label text NOT NULL,\n scope text NOT NULL,\n scope_id text NOT NULL DEFAULT '',\n key text NOT NULL,\n before jsonb,\n after jsonb\n);\nCREATE INDEX IF NOT EXISTS settings_audit_key ON settings_audit(key, id DESC);\n`;\n}\n","import { z } from \"zod\";\n\n/**\n * A product's settings as a typed registry: its key, its type, its default and the scopes it can be overridden at. Settings are DATA in\n * the database, changed by an administrator without a redeploy; the registry is the one place that says what exists, so the admin\n * forms, the validation and the checks at the server boundary all read the same list.\n */\nexport const SCOPE = { global: \"global\", workspace: \"workspace\", user: \"user\" } as const;\nexport type Scope = (typeof SCOPE)[keyof typeof SCOPE];\n/** The order a value is looked up in: the most specific wins (user, then workspace, then global). */\nexport const SCOPES_BY_SPECIFICITY = [SCOPE.user, SCOPE.workspace, SCOPE.global] as const;\n\nexport const KIND = { flag: \"flag\", integer: \"integer\", choice: \"choice\", bilingual: \"bilingual\", subset: \"subset\" } as const;\nexport type Kind = (typeof KIND)[keyof typeof KIND];\n\nexport interface Def<T = unknown> {\n /** The admin screen the setting belongs to (the product names its own groups). */\n group: string;\n kind: Kind;\n schema: z.ZodType<T>;\n default: T;\n scopes: readonly Scope[];\n /** For a number: its bounds and unit; for a choice or a subset: the values. */\n min?: number;\n max?: number;\n unit?: string;\n choices?: readonly string[];\n}\n\nexport const ALL_SCOPES: readonly Scope[] = [SCOPE.global, SCOPE.workspace, SCOPE.user];\nexport const WORKSPACE_SCOPES: readonly Scope[] = [SCOPE.global, SCOPE.workspace];\nexport const GLOBAL_ONLY: readonly Scope[] = [SCOPE.global];\n\nexport const flag = (group: string, value: boolean, scopes: readonly Scope[] = GLOBAL_ONLY): Def<boolean> => ({ group, kind: KIND.flag, schema: z.boolean(), default: value, scopes });\nexport const integer = (group: string, value: number, bounds: { min: number; max: number; unit?: string }, scopes: readonly Scope[] = GLOBAL_ONLY): Def<number> => ({ group, kind: KIND.integer, schema: z.number().int().min(bounds.min).max(bounds.max), default: value, scopes, ...bounds });\nexport const choice = <const C extends readonly [string, ...string[]]>(group: string, choices: C, value: C[number], scopes: readonly Scope[] = GLOBAL_ONLY): Def<C[number]> => ({ group, kind: KIND.choice, schema: z.enum(choices), default: value, scopes, choices });\nexport const subset = <const C extends readonly [string, ...string[]]>(group: string, choices: C, value: C[number][], scopes: readonly Scope[] = GLOBAL_ONLY): Def<C[number][]> => ({ group, kind: KIND.subset, schema: z.array(z.enum(choices)).min(1), default: value, scopes, choices });\nexport const bilingual = (group: string, value: { fr: string; en: string }, scopes: readonly Scope[] = GLOBAL_ONLY): Def<{ fr: string; en: string }> => ({ group, kind: KIND.bilingual, schema: z.object({ fr: z.string().trim().min(1).max(500), en: z.string().trim().min(1).max(500) }), default: value, scopes });\n\n/** A registry: keys to definitions (write it `as const satisfies Registry` to keep the keys and the value types). */\nexport type Registry = Record<string, Def<never> | Def<boolean> | Def<number> | Def<string> | Def<string[]> | Def<{ fr: string; en: string }>>;\nexport type KeyOf<R extends Registry> = keyof R & string;\nexport type ValueOf<R extends Registry, K extends KeyOf<R>> = z.infer<R[K][\"schema\"]>;\n\n/** The tools over one registry: what is a key, its definition, the keys of a group. */\nexport function defineSettings<R extends Registry>(registry: R) {\n const keys = Object.keys(registry) as KeyOf<R>[];\n const defOf = (key: KeyOf<R>): Def => registry[key] as unknown as Def;\n return {\n registry,\n keys,\n isKey: (key: string): key is KeyOf<R> => Object.hasOwn(registry, key),\n defOf,\n keysOfGroup: (group: string): KeyOf<R>[] => keys.filter((k) => defOf(k).group === group),\n };\n}\nexport type SettingsDefinition<R extends Registry> = ReturnType<typeof defineSettings<R>>;\n","import { type Def, type Scope,SCOPES_BY_SPECIFICITY } from \"./registry\";\n\n/** What each scope has set for one key (absent = not overridden there). */\nexport type Layers = Partial<Record<Scope, unknown>>;\nexport interface Resolved<T = unknown> {\n value: T;\n /** Where the value comes from: the scope that set it, or `default`. */\n source: Scope | \"default\";\n}\n\n/** The effective value: user, then workspace, then global, then the default. A scope the setting cannot be set at is never read. */\nexport function resolveValue(def: Def, layers: Layers, fallback?: unknown): Resolved {\n for (const scope of SCOPES_BY_SPECIFICITY) {\n if (def.scopes.includes(scope) && layers[scope] !== undefined) return { value: layers[scope], source: scope };\n }\n return { value: fallback !== undefined ? fallback : def.default, source: \"default\" };\n}\n","import { type KeyOf, type Registry, SCOPE, type Scope, type SettingsDefinition, type ValueOf } from \"./registry\";\nimport { type Layers, type Resolved, resolveValue } from \"./resolve\";\n\n/** A SQL executor: the rows of a statement and its parameters (the product's pool). */\nexport type Query = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;\n\nexport interface ScopeRef {\n scope: Scope;\n /** The workspace or user the override belongs to; empty for the global scope. */\n id: string;\n}\nexport const GLOBAL: ScopeRef = { scope: SCOPE.global, id: \"\" };\n\nexport interface Actor {\n id: string | null;\n label: string;\n}\nexport interface Context {\n userId?: string | null;\n /** A workspace named directly (an admin previewing it); else it is looked up from the user. */\n workspaceId?: string | null;\n}\nexport interface AuditEntry {\n id: number;\n at: string;\n actorLabel: string;\n scope: Scope;\n scopeId: string;\n key: string;\n before: unknown;\n after: unknown;\n}\n\nexport class SettingsError extends Error {\n constructor(\n readonly status: number,\n readonly code: \"UNKNOWN_SETTING\" | \"BAD_VALUE\" | \"BAD_SCOPE\",\n message: string,\n ) {\n super(message);\n this.name = \"SettingsError\";\n }\n}\n\n/** The service: the app asks for a setting (user, then workspace, then global, then the default); an administrator changes it, every change leaving an audit line. */\nexport interface SettingsService<R extends Registry> {\n get<K extends KeyOf<R>>(key: K, context?: Context): Promise<ValueOf<R, K>>;\n /** Every setting, resolved for a context, with where each value comes from. */\n snapshot(context?: Context): Promise<Record<KeyOf<R>, Resolved>>;\n /** What is overridden at one scope (the rest follows the scope above). */\n overrides(scope: ScopeRef): Promise<Partial<Record<KeyOf<R>, unknown>>>;\n set(actor: Actor, scope: ScopeRef, key: string, value: unknown, now: Date): Promise<void>;\n /** Back to the default: removes the override at that scope. */\n reset(actor: Actor, scope: ScopeRef, key: string, now: Date): Promise<void>;\n history(options?: { key?: string; limit?: number }): Promise<AuditEntry[]>;\n}\n\nexport interface PostgresSettingsDeps<R extends Registry> {\n query: Query;\n /** The workspace a user belongs to (null while the product has no workspaces). */\n workspaceOf?: (userId: string) => Promise<string | null>;\n /** Defaults that depend on the deployment (a legacy environment switch): they replace the registry's default, never an override. */\n defaults?: Partial<Record<KeyOf<R>, unknown>>;\n /** How long a read is served from memory (other instances see a change within it; this one at once). */\n cacheMs?: number;\n /** A monotonic clock for the cache, in milliseconds (never the wall clock). */\n clock?: () => number;\n}\n\nconst cacheKey = (s: ScopeRef) => `${s.scope}:${s.id}`;\n\n/** The adapter over the product's PostgreSQL (`app_settings`, `settings_audit`; see `settingsMigration`). */\nexport function postgresSettings<R extends Registry>(settings: SettingsDefinition<R>, deps: PostgresSettingsDeps<R>): SettingsService<R> {\n const { query } = deps;\n const cacheMs = deps.cacheMs ?? 5000;\n const clock = deps.clock ?? (() => 0);\n const cache = new Map<string, { at: number; values: Partial<Record<KeyOf<R>, unknown>> }>();\n\n async function load(scope: ScopeRef): Promise<Partial<Record<KeyOf<R>, unknown>>> {\n const hit = cache.get(cacheKey(scope));\n if (hit && clock() - hit.at < cacheMs) return hit.values;\n const rows = await query<{ key: string; value: unknown }>(\"SELECT key, value FROM app_settings WHERE scope = $1 AND scope_id = $2\", [scope.scope, scope.id]);\n const values: Partial<Record<KeyOf<R>, unknown>> = {};\n const into = values as Record<string, unknown>;\n for (const r of rows) if (settings.isKey(r.key)) into[r.key] = r.value;\n cache.set(cacheKey(scope), { at: clock(), values });\n return values;\n }\n\n async function layersFor(context: Context): Promise<Record<Scope, Partial<Record<KeyOf<R>, unknown>>>> {\n const workspaceId = context.workspaceId ?? (context.userId && deps.workspaceOf ? await deps.workspaceOf(context.userId) : null);\n const [user, workspace, global] = await Promise.all([context.userId ? load({ scope: SCOPE.user, id: context.userId }) : {}, workspaceId ? load({ scope: SCOPE.workspace, id: workspaceId }) : {}, load(GLOBAL)]);\n return { user, workspace, global };\n }\n\n function validate(scope: ScopeRef, key: string, value?: unknown): KeyOf<R> {\n if (!settings.isKey(key)) throw new SettingsError(404, \"UNKNOWN_SETTING\", `No such setting: ${key}`);\n const def = settings.defOf(key);\n if (!def.scopes.includes(scope.scope)) throw new SettingsError(400, \"BAD_SCOPE\", `${key} cannot be set at the ${scope.scope} level`);\n if (scope.scope !== SCOPE.global && !scope.id) throw new SettingsError(400, \"BAD_SCOPE\", \"A workspace or a user is required\");\n if (value !== undefined && !def.schema.safeParse(value).success) throw new SettingsError(400, \"BAD_VALUE\", `Not a valid value for ${key}`);\n return key;\n }\n\n const record = (actor: Actor, scope: ScopeRef, key: string, before: unknown, after: unknown, now: Date) =>\n query(\"INSERT INTO settings_audit (at, actor_id, actor_label, scope, scope_id, key, before, after) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\", [now, actor.id, actor.label, scope.scope, scope.id, key, JSON.stringify(before ?? null), JSON.stringify(after ?? null)]);\n\n const layersOf = (layers: Record<Scope, Partial<Record<KeyOf<R>, unknown>>>, key: KeyOf<R>): Layers => ({ user: layers.user[key], workspace: layers.workspace[key], global: layers.global[key] });\n\n return {\n async get(key, context = {}) {\n return resolveValue(settings.defOf(key), layersOf(await layersFor(context), key), deps.defaults?.[key]).value as never;\n },\n\n async snapshot(context = {}) {\n const layers = await layersFor(context);\n return Object.fromEntries(settings.keys.map((k) => [k, resolveValue(settings.defOf(k), layersOf(layers, k), deps.defaults?.[k])])) as Record<KeyOf<R>, Resolved>;\n },\n\n overrides: (scope) => load(scope),\n\n async set(actor, scope, key, value, now) {\n const k = validate(scope, key, value ?? null);\n const parsed = settings.defOf(k).schema.parse(value);\n const before = (await query<{ value: unknown }>(\"SELECT value FROM app_settings WHERE scope = $1 AND scope_id = $2 AND key = $3\", [scope.scope, scope.id, k]))[0]?.value;\n await query(\n `INSERT INTO app_settings (scope, scope_id, key, value, updated_at, updated_by) VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (scope, scope_id, key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,\n [scope.scope, scope.id, k, JSON.stringify(parsed), now, actor.id],\n );\n await record(actor, scope, k, before, parsed, now);\n cache.clear();\n },\n\n async reset(actor, scope, key, now) {\n const k = validate(scope, key);\n const rows = await query<{ value: unknown }>(\"DELETE FROM app_settings WHERE scope = $1 AND scope_id = $2 AND key = $3 RETURNING value\", [scope.scope, scope.id, k]);\n if (rows.length) await record(actor, scope, k, rows[0]!.value, null, now);\n cache.clear();\n },\n\n async history({ key, limit = 100 } = {}) {\n const rows = await query<{ id: string; at: Date; actor_label: string; scope: Scope; scope_id: string; key: string; before: unknown; after: unknown }>(\n \"SELECT id, at, actor_label, scope, scope_id, key, before, after FROM settings_audit WHERE ($1::text IS NULL OR key = $1) ORDER BY id DESC LIMIT $2\",\n [key ?? null, limit],\n );\n return rows.map((r) => ({ id: Number(r.id), at: r.at.toISOString(), actorLabel: r.actor_label, scope: r.scope, scopeId: r.scope_id, key: r.key, before: r.before, after: r.after }));\n },\n };\n}\n","import { type KeyOf, type Registry, SCOPE, type SettingsDefinition } from \"./registry\";\nimport { GLOBAL, type SettingsService } from \"./service\";\n\n/**\n * A deployment that was configured by environment before settings existed keeps behaving the same: at server start, each legacy value\n * that differs from the registry's default is written ONCE as a global setting — and only when nobody has set it since. From then on\n * the administration owns it; the environment is never read again. `legacy` maps a setting key to its legacy value.\n */\nexport async function seedLegacySettings<R extends Registry>(settings: SettingsDefinition<R>, service: SettingsService<R>, legacy: Partial<Record<KeyOf<R>, unknown>>, now: Date): Promise<KeyOf<R>[]> {\n const seeded: KeyOf<R>[] = [];\n const existing = await service.overrides(GLOBAL);\n for (const key of Object.keys(legacy) as KeyOf<R>[]) {\n if (existing[key] !== undefined || legacy[key] === settings.defOf(key).default) continue;\n await service.set({ id: null, label: \"server start (legacy environment)\" }, { scope: SCOPE.global, id: \"\" }, key, legacy[key], now);\n seeded.push(key);\n }\n return seeded;\n}\n"],"mappings":";AAeO,IAAM,mBAAmB,CAAqB,aACnD,SAAS,KAAK,IAAI,CAAC,QAAQ;AACzB,QAAM,EAAE,OAAO,MAAM,SAAS,MAAM,QAAQ,KAAK,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CAAC;AAC5B,QAAM,WAAW,MAAM,QAAQ,UAAU,MAAM;AAC/C,aAAW,OAAO,OAAO,KAAK,MAAM,GAAiB;AACnD,QAAI,SAAS,GAAG,MAAM,UAAa,OAAO,GAAG,MAAM,SAAS,MAAM,GAAG,EAAE,QAAS;AAChF,UAAM,QAAQ,IAAI,EAAE,IAAI,MAAM,OAAO,oCAAoC,GAAG,EAAE,OAAO,MAAM,QAAQ,IAAI,GAAG,GAAG,KAAK,OAAO,GAAG,GAAG,GAAG;AAClI,WAAO,KAAK,GAAG;AAAA,EACjB;AACA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/describe.ts","../src/migration.ts","../src/prices.ts","../src/price-catalogue.ts","../src/prices-persistence.ts","../src/registry.ts","../src/resolve.ts","../src/service.ts","../src/seed.ts"],"sourcesContent":["import type { KeyOf, Kind, Registry, Scope, SettingsDefinition } from \"./registry\";\n\n/** A setting as an administration screen draws it: JSON-safe (no schema), so it can cross to the browser. */\nexport interface SettingDescription<K extends string = string> {\n key: K;\n group: string;\n kind: Kind;\n default: unknown;\n scopes: readonly Scope[];\n min?: number;\n max?: number;\n unit?: string;\n choices?: readonly string[];\n}\n\nexport const describeSettings = <R extends Registry>(settings: SettingsDefinition<R>): SettingDescription<KeyOf<R>>[] =>\n settings.keys.map((key) => {\n const { group, kind, default: dflt, scopes, min, max, unit, choices } = settings.defOf(key);\n return { key, group, kind, default: dflt, scopes, min, max, unit, choices };\n });\n","/**\n * The tables of the settings: the overrides (global, for a workspace, for one user — the most specific wins) and the audit of every\n * change (who, what, when, before, after). Idempotent, safe on a database that already has them.\n */\nexport function settingsMigration(): string {\n return `\nCREATE TABLE IF NOT EXISTS app_settings (\n scope text NOT NULL CHECK (scope IN ('global', 'workspace', 'user')),\n scope_id text NOT NULL DEFAULT '',\n key text NOT NULL CHECK (key ~ '^[a-zA-Z0-9.]{1,80}$'),\n value jsonb NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now(),\n updated_by uuid,\n PRIMARY KEY (scope, scope_id, key),\n CHECK ((scope = 'global') = (scope_id = ''))\n);\nCREATE TABLE IF NOT EXISTS settings_audit (\n id bigserial PRIMARY KEY,\n at timestamptz NOT NULL DEFAULT now(),\n actor_id uuid,\n actor_label text NOT NULL,\n scope text NOT NULL,\n scope_id text NOT NULL DEFAULT '',\n key text NOT NULL,\n before jsonb,\n after jsonb\n);\nCREATE INDEX IF NOT EXISTS settings_audit_key ON settings_audit(key, id DESC);\n`;\n}\n","import { z } from \"zod\";\n\n/**\n * A product's prices as DATA (ADR-009, krizaka/.github#253): a typed catalogue of entries — product, plan, unit, amount, CAD, before\n * taxes, availability, named limits — whose seed is the product's former pricing module. An administrator changes an entry by\n * scheduling a new version from a date; a subscription keeps the version it was sold at. Public pages read the catalogue only.\n */\nexport const UNIT = { month: \"month\", year: \"year\", once: \"once\", document: \"document\", order: \"order\", pack: \"pack\", hour: \"hour\" } as const;\nexport type Unit = (typeof UNIT)[keyof typeof UNIT];\nconst UNITS = Object.values(UNIT) as [Unit, ...Unit[]];\n\n/** Who may see an entry: everyone with its figure, nobody outside, the first customers only (a cap in `limits`), or « en préparation » (no figure). */\nexport const AVAILABILITY = { public: \"public\", internal: \"internal\", founderLimited: \"founder-limited\", preparing: \"preparing\" } as const;\nexport type Availability = (typeof AVAILABILITY)[keyof typeof AVAILABILITY];\nconst AVAILABILITIES = Object.values(AVAILABILITY) as [Availability, ...Availability[]];\n\nconst ID = /^[a-z][a-zA-Z0-9-]{0,39}$/;\nconst LIMIT = /^[a-z][a-zA-Z0-9]{0,39}$/;\n// @fixed: a sanity bound on one price (one million dollars, in cents), not a business parameter\nconst MAX_CENTS = 100_000_000;\n\n/** What a version of an entry holds. Every price is in Canadian dollars, shown before GST and QST (the processor adds them). */\nexport const priceSchema = z\n .object({\n unit: z.enum(UNITS),\n /** Integer cents; `null` is « on quote ». */\n amountCents: z.number().int().min(0).max(MAX_CENTS).nullable(),\n currency: z.literal(\"CAD\"),\n taxes: z.literal(\"plus-taxes\"),\n availability: z.enum(AVAILABILITIES),\n /** Named integers the product reads: `included`, `overageCents`, `founderCap`, `feeBps`, `feeCapCents`… */\n limits: z.record(z.string().regex(LIMIT), z.number().int().min(0).max(MAX_CENTS)),\n })\n .strict()\n .refine((p) => p.amountCents !== null || (p.availability !== AVAILABILITY.public && p.availability !== AVAILABILITY.founderLimited), { message: \"An entry on sale has a figure\" });\nexport type Price = z.infer<typeof priceSchema>;\n\nexport interface PriceSeed {\n product: string;\n plan: string;\n unit: Unit;\n amountCents: number | null;\n availability: Availability;\n limits?: Record<string, number>;\n}\n\n/** An entry as read at a date: its key, the version in force and from when. */\nexport interface PriceEntry extends Price {\n key: string;\n product: string;\n plan: string;\n versionId: string;\n effectiveFrom: Date;\n}\n\nexport class PriceError extends Error {\n constructor(\n readonly status: number,\n readonly code: \"UNKNOWN_PRICE\" | \"BAD_VALUE\" | \"BAD_DATE\",\n message: string,\n ) {\n super(message);\n this.name = \"PriceError\";\n }\n}\n\n/** The seed version of an entry: its id and the date it is in force from (always). */\nexport const seedVersionId = (key: string) => `seed:${key}`;\nexport const SEED_FROM = new Date(0);\n\n/** The catalogue's definition: its keys and their defaults, each validated (a bad seed fails at start, never on a page). */\nexport function definePrices(seed: readonly PriceSeed[]) {\n const defaults = new Map<string, Price>();\n for (const s of seed) {\n if (!ID.test(s.product) || !ID.test(s.plan)) throw new PriceError(400, \"BAD_VALUE\", `Not a product or plan id: ${s.product}.${s.plan}`);\n const key = `${s.product}.${s.plan}`;\n if (defaults.has(key)) throw new PriceError(400, \"BAD_VALUE\", `Twice in the seed: ${key}`);\n const parsed = priceSchema.safeParse({ unit: s.unit, amountCents: s.amountCents, currency: \"CAD\", taxes: \"plus-taxes\", availability: s.availability, limits: s.limits ?? {} });\n if (!parsed.success) throw new PriceError(400, \"BAD_VALUE\", `Not a valid price for ${key}`);\n defaults.set(key, parsed.data);\n }\n const keys = [...defaults.keys()];\n const isKey = (key: string) => defaults.has(key);\n const defaultOf = (key: string): Price => {\n const d = defaults.get(key);\n if (!d) throw new PriceError(404, \"UNKNOWN_PRICE\", `No such price: ${key}`);\n return d;\n };\n return { keys, isKey, defaultOf };\n}\nexport type PricesDefinition = ReturnType<typeof definePrices>;\n\n/** What a public page shows: never an internal entry; an entry in preparation without its figure or its limits. */\nexport interface PublicPrice extends Omit<PriceEntry, \"effectiveFrom\"> {\n effectiveFrom: string;\n}\nexport const publicCatalogue = (entries: readonly PriceEntry[]): PublicPrice[] =>\n entries\n .filter((e) => e.availability !== AVAILABILITY.internal)\n .map((e) => ({ ...e, effectiveFrom: e.effectiveFrom.toISOString(), ...(e.availability === AVAILABILITY.preparing ? { amountCents: null, limits: {} } : {}) }));\n\n/** An amount with a currency sign or code, before or after it (French and English writing, any thousands separator). */\nconst TYPED_PRICE = /\\d(?:[\\d\\s\\u00a0\\u202f.,]*\\d)?\\s?(?:\\$|CAD\\b|USD\\b|€)|\\$\\s?\\d/u;\n\n/** The paths of every message that types an amount — a product's « every price comes from the catalogue » test fails on any. */\nexport function findTypedPrices(messages: unknown, path: string[] = []): string[] {\n if (typeof messages === \"string\") return TYPED_PRICE.test(messages) ? [path.join(\".\")] : [];\n if (Array.isArray(messages)) return messages.flatMap((m, i) => findTypedPrices(m, [...path, String(i)]));\n if (messages && typeof messages === \"object\") return Object.entries(messages).flatMap(([k, v]) => findTypedPrices(v, [...path, k]));\n return [];\n}\n","import { AVAILABILITY, type Availability, type Price, type PriceEntry, PriceError, priceSchema, type PricesDefinition, SEED_FROM, seedVersionId, UNIT, type Unit } from \"./prices\";\nimport type { Actor } from \"./service\";\n\n/** A version an administrator scheduled: the price in force from `effectiveFrom`, and the one it replaced at that date. */\nexport interface StoredPriceVersion {\n id: string;\n key: string;\n price: Price;\n before: Price;\n effectiveFrom: Date;\n createdAt: Date;\n actorLabel: string;\n}\n\n/** Where the versions live (the product's database, or memory in tests). Versions are only ever added. */\nexport interface PriceStore {\n /** Every version of a key, oldest scheduled first. */\n versions(key: string): Promise<StoredPriceVersion[]>;\n version(id: string): Promise<StoredPriceVersion | null>;\n /** Adds a version and its audit line, atomically. */\n insert(version: Omit<StoredPriceVersion, \"id\">, actor: Actor): Promise<StoredPriceVersion>;\n}\n\nexport interface PriceHistoryLine {\n versionId: string;\n at: string;\n actorLabel: string;\n effectiveFrom: string;\n before: Price | null;\n after: Price;\n}\n\n/** The catalogue a product reads and its administrator edits. */\nexport interface PriceCatalogue {\n /** The entry in force at a date (a page passes now; an invoice passes the subscription's date). */\n entry(key: string, at: Date): Promise<PriceEntry>;\n catalogue(at: Date): Promise<PriceEntry[]>;\n /** The version a subscription was sold at, forever; null for an id that is not one. */\n version(id: string): Promise<PriceEntry | null>;\n /** A change from a date (now or later, never the past): a new version over the one in force then. */\n schedule(actor: Actor, key: string, change: Partial<Price>, effectiveFrom: Date, now: Date): Promise<PriceEntry>;\n /** Every change of a key, newest first, ending with the seed. */\n history(key: string): Promise<PriceHistoryLine[]>;\n /** The versions scheduled after a date. */\n upcoming(key: string, at: Date): Promise<PriceEntry[]>;\n}\n\nconst split = (key: string) => {\n const dot = key.indexOf(\".\");\n return { product: key.slice(0, dot), plan: key.slice(dot + 1) };\n};\nconst toEntry = (key: string, price: Price, versionId: string, effectiveFrom: Date): PriceEntry => ({ key, ...split(key), ...price, versionId, effectiveFrom });\nconst fromStored = (v: StoredPriceVersion) => toEntry(v.key, v.price, v.id, v.effectiveFrom);\n/** In force at `at`: the latest date not after it; for the same date, the last scheduled. */\nconst inForce = (versions: StoredPriceVersion[], at: Date) => versions.filter((v) => v.effectiveFrom <= at).reduce<StoredPriceVersion | undefined>((best, v) => (!best || v.effectiveFrom >= best.effectiveFrom ? v : best), undefined);\n\nexport function priceCatalogue(prices: PricesDefinition, store: PriceStore): PriceCatalogue {\n const known = (key: string) => {\n if (!prices.isKey(key)) throw new PriceError(404, \"UNKNOWN_PRICE\", `No such price: ${key}`);\n return key;\n };\n async function entry(key: string, at: Date): Promise<PriceEntry> {\n const v = inForce(await store.versions(known(key)), at);\n return v ? fromStored(v) : toEntry(key, prices.defaultOf(key), seedVersionId(key), SEED_FROM);\n }\n return {\n entry,\n catalogue: (at) => Promise.all(prices.keys.map((k) => entry(k, at))),\n\n async version(id) {\n if (id.startsWith(\"seed:\")) {\n const key = id.slice(\"seed:\".length);\n return prices.isKey(key) ? toEntry(key, prices.defaultOf(key), id, SEED_FROM) : null;\n }\n const v = /^\\d{1,18}$/.test(id) ? await store.version(id) : null;\n return v ? fromStored(v) : null;\n },\n\n async schedule(actor, key, change, effectiveFrom, now) {\n known(key);\n if (!(effectiveFrom instanceof Date) || Number.isNaN(effectiveFrom.getTime()) || effectiveFrom < now) throw new PriceError(400, \"BAD_DATE\", \"A price changes from now or later, never in the past\");\n const current = await entry(key, effectiveFrom);\n const { key: _k, product: _p, plan: _pl, versionId: _v, effectiveFrom: _e, ...before } = current;\n const parsed = priceSchema.safeParse({ ...before, ...change });\n if (!parsed.success) throw new PriceError(400, \"BAD_VALUE\", `Not a valid price for ${key}`);\n return fromStored(await store.insert({ key, price: parsed.data, before, effectiveFrom, createdAt: now, actorLabel: actor.label }, actor));\n },\n\n async history(key) {\n const versions = await store.versions(known(key));\n const lines = versions.map((v) => ({ versionId: v.id, at: v.createdAt.toISOString(), actorLabel: v.actorLabel, effectiveFrom: v.effectiveFrom.toISOString(), before: v.before, after: v.price }));\n const seed = { versionId: seedVersionId(key), at: SEED_FROM.toISOString(), actorLabel: \"seed\", effectiveFrom: SEED_FROM.toISOString(), before: null, after: prices.defaultOf(key) };\n return [...lines.reverse(), seed];\n },\n\n async upcoming(key, at) {\n return (await store.versions(known(key))).filter((v) => v.effectiveFrom > at).map(fromStored);\n },\n };\n}\n\n/** Versions in memory: for tests and for a product's first steps. */\nexport function memoryPriceStore(): PriceStore {\n const rows: StoredPriceVersion[] = [];\n return {\n versions: async (key) => rows.filter((r) => r.key === key),\n version: async (id) => rows.find((r) => r.id === id) ?? null,\n async insert(version) {\n const row = { ...version, id: String(rows.length + 1) };\n rows.push(row);\n return row;\n },\n };\n}\n\n/** The catalogue as the admin screen draws it: JSON-safe, with the enumerations its fields offer and what is already scheduled. */\nexport interface PricesDescription {\n units: Unit[];\n availabilities: Availability[];\n entries: (Omit<PriceEntry, \"effectiveFrom\"> & { effectiveFrom: string; upcoming: (Price & { versionId: string; effectiveFrom: string })[] })[];\n}\nexport async function describePrices(catalogue: PriceCatalogue, at: Date): Promise<PricesDescription> {\n const iso = <T extends { effectiveFrom: Date }>(e: T) => ({ ...e, effectiveFrom: e.effectiveFrom.toISOString() });\n const entries = await Promise.all(\n (await catalogue.catalogue(at)).map(async (e) => ({ ...iso(e), upcoming: (await catalogue.upcoming(e.key, at)).map(({ key: _k, product: _p, plan: _pl, ...v }) => iso(v)) })),\n );\n return { units: Object.values(UNIT), availabilities: Object.values(AVAILABILITY), entries };\n}\n","import { settingsMigration } from \"./migration\";\nimport type { PriceStore, StoredPriceVersion } from \"./price-catalogue\";\nimport type { Price } from \"./prices\";\nimport type { Query } from \"./service\";\n\n/**\n * The price versions in the product's PostgreSQL (`price_versions`), each insert writing its audit line in `settings_audit`\n * (key `price.<product>.<plan>`) in the same statement. Rows are only ever added: a version once sold is never rewritten.\n */\nexport function pricesMigration(): string {\n return `${settingsMigration()}\nCREATE TABLE IF NOT EXISTS price_versions (\n id bigserial PRIMARY KEY,\n key text NOT NULL CHECK (key ~ '^[a-z][a-zA-Z0-9-]{0,39}[.][a-z][a-zA-Z0-9-]{0,39}$'),\n price jsonb NOT NULL,\n before jsonb NOT NULL,\n effective_from timestamptz NOT NULL,\n created_at timestamptz NOT NULL,\n actor_id uuid,\n actor_label text NOT NULL\n);\nCREATE INDEX IF NOT EXISTS price_versions_key ON price_versions(key, id);\n`;\n}\n\ninterface Row {\n id: string;\n key: string;\n price: Price;\n before: Price;\n effective_from: Date;\n created_at: Date;\n actor_label: string;\n}\nconst COLUMNS = \"id, key, price, before, effective_from, created_at, actor_label\";\nconst fromRow = (r: Row): StoredPriceVersion => ({ id: String(r.id), key: r.key, price: r.price, before: r.before, effectiveFrom: r.effective_from, createdAt: r.created_at, actorLabel: r.actor_label });\n\nexport function priceStore({ query }: { query: Query }): PriceStore {\n return {\n async versions(key) {\n return (await query<Row>(`SELECT ${COLUMNS} FROM price_versions WHERE key = $1 ORDER BY id`, [key])).map(fromRow);\n },\n async version(id) {\n const row = (await query<Row>(`SELECT ${COLUMNS} FROM price_versions WHERE id = $1`, [id]))[0];\n return row ? fromRow(row) : null;\n },\n async insert(v, actor) {\n const rows = await query<Row>(\n `WITH v AS (\n INSERT INTO price_versions (key, price, before, effective_from, created_at, actor_id, actor_label) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING ${COLUMNS}\n ), a AS (\n INSERT INTO settings_audit (at, actor_id, actor_label, scope, scope_id, key, before, after)\n SELECT $5, $6, $7, 'global', '', 'price.' || $1, $3, jsonb_set($2::jsonb, '{effectiveFrom}', to_jsonb($4::timestamptz)) FROM v\n )\n SELECT ${COLUMNS} FROM v`,\n [v.key, JSON.stringify(v.price), JSON.stringify(v.before), v.effectiveFrom, v.createdAt, actor.id, actor.label],\n );\n return fromRow(rows[0]!);\n },\n };\n}\n","import { z } from \"zod\";\n\n/**\n * A product's settings as a typed registry: its key, its type, its default and the scopes it can be overridden at. Settings are DATA in\n * the database, changed by an administrator without a redeploy; the registry is the one place that says what exists, so the admin\n * forms, the validation and the checks at the server boundary all read the same list.\n */\nexport const SCOPE = { global: \"global\", workspace: \"workspace\", user: \"user\" } as const;\nexport type Scope = (typeof SCOPE)[keyof typeof SCOPE];\n/** The order a value is looked up in: the most specific wins (user, then workspace, then global). */\nexport const SCOPES_BY_SPECIFICITY = [SCOPE.user, SCOPE.workspace, SCOPE.global] as const;\n\nexport const KIND = { flag: \"flag\", integer: \"integer\", choice: \"choice\", bilingual: \"bilingual\", subset: \"subset\" } as const;\nexport type Kind = (typeof KIND)[keyof typeof KIND];\n\nexport interface Def<T = unknown> {\n /** The admin screen the setting belongs to (the product names its own groups). */\n group: string;\n kind: Kind;\n schema: z.ZodType<T>;\n default: T;\n scopes: readonly Scope[];\n /** For a number: its bounds and unit; for a choice or a subset: the values. */\n min?: number;\n max?: number;\n unit?: string;\n choices?: readonly string[];\n}\n\nexport const ALL_SCOPES: readonly Scope[] = [SCOPE.global, SCOPE.workspace, SCOPE.user];\nexport const WORKSPACE_SCOPES: readonly Scope[] = [SCOPE.global, SCOPE.workspace];\nexport const GLOBAL_ONLY: readonly Scope[] = [SCOPE.global];\n\nexport const flag = (group: string, value: boolean, scopes: readonly Scope[] = GLOBAL_ONLY): Def<boolean> => ({ group, kind: KIND.flag, schema: z.boolean(), default: value, scopes });\nexport const integer = (group: string, value: number, bounds: { min: number; max: number; unit?: string }, scopes: readonly Scope[] = GLOBAL_ONLY): Def<number> => ({ group, kind: KIND.integer, schema: z.number().int().min(bounds.min).max(bounds.max), default: value, scopes, ...bounds });\nexport const choice = <const C extends readonly [string, ...string[]]>(group: string, choices: C, value: C[number], scopes: readonly Scope[] = GLOBAL_ONLY): Def<C[number]> => ({ group, kind: KIND.choice, schema: z.enum(choices), default: value, scopes, choices });\nexport const subset = <const C extends readonly [string, ...string[]]>(group: string, choices: C, value: C[number][], scopes: readonly Scope[] = GLOBAL_ONLY): Def<C[number][]> => ({ group, kind: KIND.subset, schema: z.array(z.enum(choices)).min(1), default: value, scopes, choices });\nexport const bilingual = (group: string, value: { fr: string; en: string }, scopes: readonly Scope[] = GLOBAL_ONLY): Def<{ fr: string; en: string }> => ({ group, kind: KIND.bilingual, schema: z.object({ fr: z.string().trim().min(1).max(500), en: z.string().trim().min(1).max(500) }), default: value, scopes });\n\n/** A registry: keys to definitions (write it `as const satisfies Registry` to keep the keys and the value types). */\nexport type Registry = Record<string, Def<never> | Def<boolean> | Def<number> | Def<string> | Def<string[]> | Def<{ fr: string; en: string }>>;\nexport type KeyOf<R extends Registry> = keyof R & string;\nexport type ValueOf<R extends Registry, K extends KeyOf<R>> = z.infer<R[K][\"schema\"]>;\n\n/** The tools over one registry: what is a key, its definition, the keys of a group. */\nexport function defineSettings<R extends Registry>(registry: R) {\n const keys = Object.keys(registry) as KeyOf<R>[];\n const defOf = (key: KeyOf<R>): Def => registry[key] as unknown as Def;\n return {\n registry,\n keys,\n isKey: (key: string): key is KeyOf<R> => Object.hasOwn(registry, key),\n defOf,\n keysOfGroup: (group: string): KeyOf<R>[] => keys.filter((k) => defOf(k).group === group),\n };\n}\nexport type SettingsDefinition<R extends Registry> = ReturnType<typeof defineSettings<R>>;\n","import { type Def, type Scope,SCOPES_BY_SPECIFICITY } from \"./registry\";\n\n/** What each scope has set for one key (absent = not overridden there). */\nexport type Layers = Partial<Record<Scope, unknown>>;\nexport interface Resolved<T = unknown> {\n value: T;\n /** Where the value comes from: the scope that set it, or `default`. */\n source: Scope | \"default\";\n}\n\n/** The effective value: user, then workspace, then global, then the default. A scope the setting cannot be set at is never read. */\nexport function resolveValue(def: Def, layers: Layers, fallback?: unknown): Resolved {\n for (const scope of SCOPES_BY_SPECIFICITY) {\n if (def.scopes.includes(scope) && layers[scope] !== undefined) return { value: layers[scope], source: scope };\n }\n return { value: fallback !== undefined ? fallback : def.default, source: \"default\" };\n}\n","import { type KeyOf, type Registry, SCOPE, type Scope, type SettingsDefinition, type ValueOf } from \"./registry\";\nimport { type Layers, type Resolved, resolveValue } from \"./resolve\";\n\n/** A SQL executor: the rows of a statement and its parameters (the product's pool). */\nexport type Query = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;\n\nexport interface ScopeRef {\n scope: Scope;\n /** The workspace or user the override belongs to; empty for the global scope. */\n id: string;\n}\nexport const GLOBAL: ScopeRef = { scope: SCOPE.global, id: \"\" };\n\nexport interface Actor {\n id: string | null;\n label: string;\n}\nexport interface Context {\n userId?: string | null;\n /** A workspace named directly (an admin previewing it); else it is looked up from the user. */\n workspaceId?: string | null;\n}\nexport interface AuditEntry {\n id: number;\n at: string;\n actorLabel: string;\n scope: Scope;\n scopeId: string;\n key: string;\n before: unknown;\n after: unknown;\n}\n\nexport class SettingsError extends Error {\n constructor(\n readonly status: number,\n readonly code: \"UNKNOWN_SETTING\" | \"BAD_VALUE\" | \"BAD_SCOPE\",\n message: string,\n ) {\n super(message);\n this.name = \"SettingsError\";\n }\n}\n\n/** The service: the app asks for a setting (user, then workspace, then global, then the default); an administrator changes it, every change leaving an audit line. */\nexport interface SettingsService<R extends Registry> {\n get<K extends KeyOf<R>>(key: K, context?: Context): Promise<ValueOf<R, K>>;\n /** Every setting, resolved for a context, with where each value comes from. */\n snapshot(context?: Context): Promise<Record<KeyOf<R>, Resolved>>;\n /** What is overridden at one scope (the rest follows the scope above). */\n overrides(scope: ScopeRef): Promise<Partial<Record<KeyOf<R>, unknown>>>;\n set(actor: Actor, scope: ScopeRef, key: string, value: unknown, now: Date): Promise<void>;\n /** Back to the default: removes the override at that scope. */\n reset(actor: Actor, scope: ScopeRef, key: string, now: Date): Promise<void>;\n history(options?: { key?: string; limit?: number }): Promise<AuditEntry[]>;\n}\n\nexport interface DbSettingsDeps<R extends Registry> {\n query: Query;\n /** The workspace a user belongs to (null while the product has no workspaces). */\n workspaceOf?: (userId: string) => Promise<string | null>;\n /** Defaults that depend on the deployment (a legacy environment switch): they replace the registry's default, never an override. */\n defaults?: Partial<Record<KeyOf<R>, unknown>>;\n /** How long a read is served from memory (other instances see a change within it; this one at once). */\n cacheMs?: number;\n /** A monotonic clock for the cache, in milliseconds (never the wall clock). */\n clock?: () => number;\n}\n\nconst cacheKey = (s: ScopeRef) => `${s.scope}:${s.id}`;\n\n/** The adapter over the product's PostgreSQL (`app_settings`, `settings_audit`; see `settingsMigration`). */\nexport function dbSettings<R extends Registry>(settings: SettingsDefinition<R>, deps: DbSettingsDeps<R>): SettingsService<R> {\n const { query } = deps;\n const cacheMs = deps.cacheMs ?? 5000;\n const clock = deps.clock ?? (() => 0);\n const cache = new Map<string, { at: number; values: Partial<Record<KeyOf<R>, unknown>> }>();\n\n async function load(scope: ScopeRef): Promise<Partial<Record<KeyOf<R>, unknown>>> {\n const hit = cache.get(cacheKey(scope));\n if (hit && clock() - hit.at < cacheMs) return hit.values;\n const rows = await query<{ key: string; value: unknown }>(\"SELECT key, value FROM app_settings WHERE scope = $1 AND scope_id = $2\", [scope.scope, scope.id]);\n const values: Partial<Record<KeyOf<R>, unknown>> = {};\n const into = values as Record<string, unknown>;\n for (const r of rows) if (settings.isKey(r.key)) into[r.key] = r.value;\n cache.set(cacheKey(scope), { at: clock(), values });\n return values;\n }\n\n async function layersFor(context: Context): Promise<Record<Scope, Partial<Record<KeyOf<R>, unknown>>>> {\n const workspaceId = context.workspaceId ?? (context.userId && deps.workspaceOf ? await deps.workspaceOf(context.userId) : null);\n const [user, workspace, global] = await Promise.all([context.userId ? load({ scope: SCOPE.user, id: context.userId }) : {}, workspaceId ? load({ scope: SCOPE.workspace, id: workspaceId }) : {}, load(GLOBAL)]);\n return { user, workspace, global };\n }\n\n function validate(scope: ScopeRef, key: string, value?: unknown): KeyOf<R> {\n if (!settings.isKey(key)) throw new SettingsError(404, \"UNKNOWN_SETTING\", `No such setting: ${key}`);\n const def = settings.defOf(key);\n if (!def.scopes.includes(scope.scope)) throw new SettingsError(400, \"BAD_SCOPE\", `${key} cannot be set at the ${scope.scope} level`);\n if (scope.scope !== SCOPE.global && !scope.id) throw new SettingsError(400, \"BAD_SCOPE\", \"A workspace or a user is required\");\n if (value !== undefined && !def.schema.safeParse(value).success) throw new SettingsError(400, \"BAD_VALUE\", `Not a valid value for ${key}`);\n return key;\n }\n\n const record = (actor: Actor, scope: ScopeRef, key: string, before: unknown, after: unknown, now: Date) =>\n query(\"INSERT INTO settings_audit (at, actor_id, actor_label, scope, scope_id, key, before, after) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\", [now, actor.id, actor.label, scope.scope, scope.id, key, JSON.stringify(before ?? null), JSON.stringify(after ?? null)]);\n\n const layersOf = (layers: Record<Scope, Partial<Record<KeyOf<R>, unknown>>>, key: KeyOf<R>): Layers => ({ user: layers.user[key], workspace: layers.workspace[key], global: layers.global[key] });\n\n return {\n async get(key, context = {}) {\n return resolveValue(settings.defOf(key), layersOf(await layersFor(context), key), deps.defaults?.[key]).value as never;\n },\n\n async snapshot(context = {}) {\n const layers = await layersFor(context);\n return Object.fromEntries(settings.keys.map((k) => [k, resolveValue(settings.defOf(k), layersOf(layers, k), deps.defaults?.[k])])) as Record<KeyOf<R>, Resolved>;\n },\n\n overrides: (scope) => load(scope),\n\n async set(actor, scope, key, value, now) {\n const k = validate(scope, key, value ?? null);\n const parsed = settings.defOf(k).schema.parse(value);\n const before = (await query<{ value: unknown }>(\"SELECT value FROM app_settings WHERE scope = $1 AND scope_id = $2 AND key = $3\", [scope.scope, scope.id, k]))[0]?.value;\n await query(\n `INSERT INTO app_settings (scope, scope_id, key, value, updated_at, updated_by) VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (scope, scope_id, key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,\n [scope.scope, scope.id, k, JSON.stringify(parsed), now, actor.id],\n );\n await record(actor, scope, k, before, parsed, now);\n cache.clear();\n },\n\n async reset(actor, scope, key, now) {\n const k = validate(scope, key);\n const rows = await query<{ value: unknown }>(\"DELETE FROM app_settings WHERE scope = $1 AND scope_id = $2 AND key = $3 RETURNING value\", [scope.scope, scope.id, k]);\n if (rows.length) await record(actor, scope, k, rows[0]!.value, null, now);\n cache.clear();\n },\n\n async history({ key, limit = 100 } = {}) {\n const rows = await query<{ id: string; at: Date; actor_label: string; scope: Scope; scope_id: string; key: string; before: unknown; after: unknown }>(\n \"SELECT id, at, actor_label, scope, scope_id, key, before, after FROM settings_audit WHERE ($1::text IS NULL OR key = $1) ORDER BY id DESC LIMIT $2\",\n [key ?? null, limit],\n );\n return rows.map((r) => ({ id: Number(r.id), at: r.at.toISOString(), actorLabel: r.actor_label, scope: r.scope, scopeId: r.scope_id, key: r.key, before: r.before, after: r.after }));\n },\n };\n}\n\n/** @deprecated The old name of `dbSettings` (a name says what a thing does, not the technology). Removed in the next major. */\nexport const postgresSettings = dbSettings;\n/** @deprecated The old name of `DbSettingsDeps`. Removed in the next major. */\nexport type PostgresSettingsDeps<R extends Registry> = DbSettingsDeps<R>;\n","import { type KeyOf, type Registry, SCOPE, type SettingsDefinition } from \"./registry\";\nimport { GLOBAL, type SettingsService } from \"./service\";\n\n/**\n * A deployment that was configured by environment before settings existed keeps behaving the same: at server start, each legacy value\n * that differs from the registry's default is written ONCE as a global setting — and only when nobody has set it since. From then on\n * the administration owns it; the environment is never read again. `legacy` maps a setting key to its legacy value.\n */\nexport async function seedLegacySettings<R extends Registry>(settings: SettingsDefinition<R>, service: SettingsService<R>, legacy: Partial<Record<KeyOf<R>, unknown>>, now: Date): Promise<KeyOf<R>[]> {\n const seeded: KeyOf<R>[] = [];\n const existing = await service.overrides(GLOBAL);\n for (const key of Object.keys(legacy) as KeyOf<R>[]) {\n if (existing[key] !== undefined || legacy[key] === settings.defOf(key).default) continue;\n await service.set({ id: null, label: \"server start (legacy environment)\" }, { scope: SCOPE.global, id: \"\" }, key, legacy[key], now);\n seeded.push(key);\n }\n return seeded;\n}\n"],"mappings":";AAeO,IAAM,mBAAmB,CAAqB,aACnD,SAAS,KAAK,IAAI,CAAC,QAAQ;AACzB,QAAM,EAAE,OAAO,MAAM,SAAS,MAAM,QAAQ,KAAK,KAAK,MAAM,QAAQ,IAAI,SAAS,MAAM,GAAG;AAC1F,SAAO,EAAE,KAAK,OAAO,MAAM,SAAS,MAAM,QAAQ,KAAK,KAAK,MAAM,QAAQ;AAC5E,CAAC;;;ACfI,SAAS,oBAA4B;AAC1C,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBT;;;AC7BA,SAAS,SAAS;AAOX,IAAM,OAAO,EAAE,OAAO,SAAS,MAAM,QAAQ,MAAM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,GAAG,GAAG;AAClI,WAAO,KAAK,GAAG;AAAA,EACjB;AACA,SAAO;AACT;","names":["z"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@krizaka/settings",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "A Krizaka product's configuration as data: a typed registry (flags, integers, choices, subsets, bilingual texts), resolved user over workspace over global over default, changed by an administrator with an audit line for every change, and the JSON-safe description an admin screen draws from. PostgreSQL adapter and migration included; no framework, no wall clock.",
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "A Krizaka product's configuration as data: a typed registry (flags, integers, choices, subsets, bilingual texts), resolved user over workspace over global over default, changed by an administrator with an audit line for every change, the price catalogue (CAD, before taxes, availability, limits) in dated versions a subscription keeps, and the JSON-safe description an admin screen draws from. PostgreSQL adapter and migration included; no framework, no wall clock.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"krizaka",
|
|
7
7
|
"settings",
|
|
@@ -40,7 +40,6 @@
|
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@krizaka/config": "^0.7.0",
|
|
44
43
|
"@types/node": "^22.10.0",
|
|
45
44
|
"@types/pg": "^8.23.1",
|
|
46
45
|
"eslint": "^9.39.0",
|
|
@@ -48,7 +47,8 @@
|
|
|
48
47
|
"tsup": "^8.5.0",
|
|
49
48
|
"typescript": "^5.9.3",
|
|
50
49
|
"vitest": "^4.1.11",
|
|
51
|
-
"zod": "^4.6.7"
|
|
50
|
+
"zod": "^4.6.7",
|
|
51
|
+
"@krizaka/config": "^0.8.0"
|
|
52
52
|
},
|
|
53
53
|
"peerDependencies": {
|
|
54
54
|
"zod": ">=3.23"
|