@marktiderman/genesis-config 0.0.0-stage → 0.10.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +461 -2
  3. package/dist/blocks.d.ts +473 -0
  4. package/dist/blocks.js +5 -0
  5. package/dist/blocks.js.map +1 -0
  6. package/dist/chunk-B6WRD3WF.js +6 -0
  7. package/dist/chunk-B6WRD3WF.js.map +1 -0
  8. package/dist/chunk-HIOKZIZP.js +218 -0
  9. package/dist/chunk-HIOKZIZP.js.map +1 -0
  10. package/dist/chunk-M7IY6LUN.js +123 -0
  11. package/dist/chunk-M7IY6LUN.js.map +1 -0
  12. package/dist/chunk-OW46SL2G.js +10 -0
  13. package/dist/chunk-OW46SL2G.js.map +1 -0
  14. package/dist/chunk-SEFG2QV6.js +413 -0
  15. package/dist/chunk-SEFG2QV6.js.map +1 -0
  16. package/dist/chunk-UD7SPYZH.js +354 -0
  17. package/dist/chunk-UD7SPYZH.js.map +1 -0
  18. package/dist/chunk-VYUX7VAX.js +52 -0
  19. package/dist/chunk-VYUX7VAX.js.map +1 -0
  20. package/dist/chunk-Y7NUBTWA.js +494 -0
  21. package/dist/chunk-Y7NUBTWA.js.map +1 -0
  22. package/dist/gate-CNTkn-Fv.d.ts +202 -0
  23. package/dist/gate-react.d.ts +48 -0
  24. package/dist/gate-react.js +37 -0
  25. package/dist/gate-react.js.map +1 -0
  26. package/dist/gate.d.ts +18 -0
  27. package/dist/gate.js +5 -0
  28. package/dist/gate.js.map +1 -0
  29. package/dist/index.d.ts +128 -0
  30. package/dist/index.js +9 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/model-uON71G4u.d.ts +437 -0
  33. package/dist/node.d.ts +159 -0
  34. package/dist/node.js +486 -0
  35. package/dist/node.js.map +1 -0
  36. package/dist/packages-CWhdXtzS.d.ts +203 -0
  37. package/dist/platforms-NR0liM8L.d.ts +10 -0
  38. package/dist/react.d.ts +60 -0
  39. package/dist/react.js +236 -0
  40. package/dist/react.js.map +1 -0
  41. package/dist/settings-protocol.d.ts +515 -0
  42. package/dist/settings-protocol.js +4 -0
  43. package/dist/settings-protocol.js.map +1 -0
  44. package/dist/settings-react.d.ts +143 -0
  45. package/dist/settings-react.js +943 -0
  46. package/dist/settings-react.js.map +1 -0
  47. package/dist/settings.d.ts +373 -0
  48. package/dist/settings.js +3 -0
  49. package/dist/settings.js.map +1 -0
  50. package/dist/types-D4hs16bJ.d.ts +39 -0
  51. package/package.json +141 -4
@@ -0,0 +1,218 @@
1
+ import { SETTINGS_LAYERS } from './chunk-UD7SPYZH.js';
2
+
3
+ // src/settings-protocol.ts
4
+ var SETTINGS_PROTOCOL_VERSION = 1;
5
+ var SECRET_STORES = ["vault", "edge", "server-env", "ci"];
6
+ function canSetSecret(capabilities, store) {
7
+ const s = capabilities.setSecrets;
8
+ return typeof s === "boolean" ? s : s?.[store] === true;
9
+ }
10
+ var NO_SETTINGS_CAPABILITIES = Object.freeze({
11
+ writeFiles: false,
12
+ writeDatabase: false,
13
+ setSecrets: false,
14
+ runCli: false,
15
+ agent: false,
16
+ proposeChanges: false
17
+ });
18
+ var APP_HOST_CAPABILITIES = Object.freeze({
19
+ ...NO_SETTINGS_CAPABILITIES,
20
+ writeDatabase: true,
21
+ setSecrets: Object.freeze({ vault: true })
22
+ });
23
+ function intersectCapabilities(a, b) {
24
+ if (!b) return { ...a };
25
+ const both = (x, y) => x === true && y !== false;
26
+ let setSecrets;
27
+ if (typeof a.setSecrets === "boolean" && (b.setSecrets === void 0 || typeof b.setSecrets === "boolean")) {
28
+ setSecrets = both(a.setSecrets, b.setSecrets);
29
+ } else {
30
+ const out = {};
31
+ for (const store of SECRET_STORES) {
32
+ const allowed = canSetSecret(a, store) && (b.setSecrets === void 0 || canSetSecret({ setSecrets: b.setSecrets }, store));
33
+ if (allowed) out[store] = true;
34
+ }
35
+ const count = Object.keys(out).length;
36
+ setSecrets = count === 0 ? false : count === SECRET_STORES.length ? true : out;
37
+ }
38
+ return {
39
+ writeFiles: both(a.writeFiles, b.writeFiles),
40
+ writeDatabase: both(a.writeDatabase, b.writeDatabase),
41
+ setSecrets,
42
+ runCli: both(a.runCli, b.runCli),
43
+ agent: both(a.agent, b.agent),
44
+ proposeChanges: both(a.proposeChanges === true, b.proposeChanges)
45
+ };
46
+ }
47
+ var SETTINGS_OPS = ["state", "setValue", "clearValue", "plan", "apply", "upgrades", "audit", "propose", "setSecret"];
48
+ var SettingsProtocolError = class extends Error {
49
+ code;
50
+ status;
51
+ details;
52
+ constructor(code, message, status = 0, details) {
53
+ super(message);
54
+ this.name = "SettingsProtocolError";
55
+ this.code = code;
56
+ this.status = status;
57
+ if (details) this.details = details;
58
+ }
59
+ };
60
+ var ERROR_CODES = ["bad_request", "unauthenticated", "forbidden", "unsupported", "locked", "stale_plan", "not_found", "version", "error"];
61
+ function codeForStatus(status) {
62
+ if (status === 400 || status === 422) return "bad_request";
63
+ if (status === 401) return "unauthenticated";
64
+ if (status === 403) return "forbidden";
65
+ if (status === 404) return "not_found";
66
+ if (status === 409) return "stale_plan";
67
+ return "error";
68
+ }
69
+ var SETTINGS_CLIENT_MESSAGES = {
70
+ signIn: "Sign in to change settings.",
71
+ unreachable: (detail) => `The settings host couldn't be reached (${detail}).`,
72
+ timedOut: (seconds) => `The settings host didn't answer within ${seconds} seconds.`,
73
+ notJson: (status) => `The settings host answered ${status} without JSON.`,
74
+ badJson: (status) => `The settings host answered ${status} with JSON it couldn't read.`,
75
+ notObject: "The settings host answered with something other than an object.",
76
+ status: (status) => `The settings host answered ${status}.`,
77
+ badState: (what) => `The settings host's state is missing ${what}.`
78
+ };
79
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
80
+ function stateProblem(v) {
81
+ for (const key of ["catalogue", "findings", "secrets"]) if (!Array.isArray(v[key])) return key;
82
+ if (!isObject(v.capabilities)) return "capabilities";
83
+ if (!isObject(v.app)) return "app";
84
+ const resolved = v.resolved;
85
+ if (!isObject(resolved) || !isObject(resolved.values) || !isObject(resolved.sources)) return "resolved";
86
+ if (v.layers !== void 0 && !isObject(v.layers)) return "layers";
87
+ return null;
88
+ }
89
+ function createSettingsClient(fetchFn, options) {
90
+ const m = { ...SETTINGS_CLIENT_MESSAGES, ...options.messages };
91
+ const timeoutMs = options.timeoutMs ?? 3e4;
92
+ async function call(body) {
93
+ const token = typeof options.token === "function" ? await options.token() : options.token;
94
+ if (!token) throw new SettingsProtocolError("unauthenticated", m.signIn);
95
+ const controller = new AbortController();
96
+ let timedOut = false;
97
+ const timer = setTimeout(() => {
98
+ timedOut = true;
99
+ controller.abort();
100
+ }, timeoutMs);
101
+ let response;
102
+ let text;
103
+ try {
104
+ response = await fetchFn(options.baseUrl, {
105
+ method: "POST",
106
+ headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${token}` },
107
+ body: JSON.stringify({ v: SETTINGS_PROTOCOL_VERSION, ...body }),
108
+ signal: controller.signal,
109
+ // The bearer token is the only credential: no cookies, so no cross-site request forgery.
110
+ credentials: "omit"
111
+ });
112
+ text = await response.text();
113
+ } catch (error) {
114
+ if (timedOut) throw new SettingsProtocolError("error", m.timedOut(Math.round(timeoutMs / 1e3)));
115
+ throw new SettingsProtocolError("error", m.unreachable(error instanceof Error ? error.message : String(error)));
116
+ } finally {
117
+ clearTimeout(timer);
118
+ }
119
+ const type = response.headers.get("content-type") ?? "";
120
+ if (!/^application\/(?:[\w.+-]+\+)?json\b/i.test(type)) {
121
+ throw new SettingsProtocolError(response.ok ? "error" : codeForStatus(response.status), m.notJson(response.status), response.status);
122
+ }
123
+ let payload;
124
+ try {
125
+ payload = JSON.parse(text);
126
+ } catch {
127
+ throw new SettingsProtocolError("error", m.badJson(response.status), response.status);
128
+ }
129
+ if (!response.ok) {
130
+ const error = payload?.error;
131
+ const code = error && ERROR_CODES.includes(error.code) ? error.code : codeForStatus(response.status);
132
+ const message = typeof error?.message === "string" ? error.message : m.status(response.status);
133
+ throw new SettingsProtocolError(code, message, response.status, error?.details);
134
+ }
135
+ if (!isObject(payload)) throw new SettingsProtocolError("error", m.notObject, response.status);
136
+ return payload;
137
+ }
138
+ return {
139
+ async state(params) {
140
+ const state = await call({ op: "state", ...params?.auditLimit !== void 0 ? { audit: { limit: params.auditLimit } } : {} });
141
+ const missing = stateProblem(state);
142
+ if (missing) throw new SettingsProtocolError("error", m.badState(missing));
143
+ return { ...state, layers: state.layers ?? {} };
144
+ },
145
+ async setValue({ key, value, locked, layer }) {
146
+ await call({ op: "setValue", key, value, layer, ...locked !== void 0 ? { locked } : {} });
147
+ },
148
+ async clearValue({ key, layer }) {
149
+ await call({ op: "clearValue", key, layer });
150
+ },
151
+ plan: async (fixId) => (await call({ op: "plan", fixId })).plan,
152
+ apply: async (fixId, expect) => (await call({ op: "apply", fixId, expect })).result,
153
+ upgrades: (params) => call({ op: "upgrades", ...params?.refresh ? { refresh: true } : {} }),
154
+ audit: (params) => call({ op: "audit", ...params?.cursor !== void 0 ? { cursor: params.cursor } : {}, ...params?.limit !== void 0 ? { limit: params.limit } : {} }),
155
+ propose: ({ key, value, locked }) => call({ op: "propose", key, value, ...locked !== void 0 ? { locked } : {} }),
156
+ async setSecret({ name, value }) {
157
+ await call({ op: "setSecret", name, store: "vault", value });
158
+ }
159
+ };
160
+ }
161
+ var LAYER_INDEX = new Map(SETTINGS_LAYERS.map((layer, i) => [layer, i]));
162
+ function settingWritability(def, source, capabilities) {
163
+ const layers = [];
164
+ const refused = {};
165
+ for (const layer of ["file", "database"]) {
166
+ if (layer === "database" && def.applies === "build") {
167
+ refused[layer] = "build";
168
+ continue;
169
+ }
170
+ if (!(layer === "file" ? capabilities.writeFiles : capabilities.writeDatabase)) {
171
+ refused[layer] = "capability";
172
+ continue;
173
+ }
174
+ const lockedBy = source?.lockedBy;
175
+ if (lockedBy && (LAYER_INDEX.get(lockedBy) ?? 0) < (LAYER_INDEX.get(layer) ?? 0)) {
176
+ refused[layer] = "locked";
177
+ continue;
178
+ }
179
+ layers.push(layer);
180
+ }
181
+ return { layers, refused };
182
+ }
183
+ function settingFileSnippet(key, value, locked) {
184
+ const entry = locked ? { value, locked: true } : value;
185
+ return JSON.stringify({ settings: { [key]: entry } }, null, 2);
186
+ }
187
+ function preferredWriteLayer(writable, source) {
188
+ if (source?.layer === "database" && writable.layers.includes("database")) return "database";
189
+ return writable.layers.includes("file") ? "file" : writable.layers[0];
190
+ }
191
+ function secretNames(catalogue, secrets) {
192
+ const names = /* @__PURE__ */ new Set();
193
+ for (const s of secrets) names.add(s.name);
194
+ for (const def of catalogue) if (def.secret) names.add(def.secret.name);
195
+ return names;
196
+ }
197
+ function auditValuesVisible(entry, catalogue, names) {
198
+ if (entry.action !== "set" && entry.action !== "clear") return false;
199
+ if (names.has(entry.subject)) return false;
200
+ const def = catalogue.find((d) => d.key === entry.subject);
201
+ return def !== void 0 && def.secret === void 0;
202
+ }
203
+ function safeHref(href) {
204
+ if (typeof href !== "string") return void 0;
205
+ const h = href.trim();
206
+ if (!h || /[\u0000-\u001F\u007F]/.test(h)) return void 0;
207
+ if (/^(?:\/(?![/\\])|\.\.?\/|#|\?)/.test(h)) return h;
208
+ try {
209
+ const url = new URL(h);
210
+ return url.protocol === "http:" || url.protocol === "https:" ? h : void 0;
211
+ } catch {
212
+ return void 0;
213
+ }
214
+ }
215
+
216
+ export { APP_HOST_CAPABILITIES, NO_SETTINGS_CAPABILITIES, SETTINGS_CLIENT_MESSAGES, SETTINGS_OPS, SETTINGS_PROTOCOL_VERSION, SettingsProtocolError, auditValuesVisible, canSetSecret, createSettingsClient, intersectCapabilities, preferredWriteLayer, safeHref, secretNames, settingFileSnippet, settingWritability };
217
+ //# sourceMappingURL=chunk-HIOKZIZP.js.map
218
+ //# sourceMappingURL=chunk-HIOKZIZP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/settings-protocol.ts"],"names":[],"mappings":";;;AA8BO,IAAM,yBAAA,GAA4B;AA6BzC,IAAM,a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.js","sourcesContent":["/**\n * `@marktiderman/genesis-config/settings-protocol`: the wire between the Settings screen and the\n * host that serves it. One UI, two hosts (config-layer §4):\n *\n * - the **CLI host** (`genesis setup`, the localhost wizard) reads and writes the files, and the\n * database through the developer's linked project;\n * - the **app host** (the platform-admin Settings screen) writes the database layer only.\n *\n * One endpoint, `POST`, JSON in and out, a bearer token in a header (never a cookie), every request\n * `{ v, op, … }`. What a host can do is its {@link SettingsCapabilities}; the screen hides or\n * disables every write the host can't do, and the host refuses it anyway.\n *\n * Secrets travel by name and status only: no type here has a field for a secret's value.\n *\n * No zod, React, Node built-ins or DOM globals beyond `fetch`'s types: it ships to browsers, the\n * CLI and edge functions alike.\n *\n * @stability Beta\n */\nimport {\n SETTINGS_LAYERS,\n type ResolvedSettings,\n type SecretStore,\n type SettingDef,\n type SettingsLayer,\n type SettingsLayerValues,\n type SettingsPreset,\n} from \"./settings\";\n\n/** Bumped on any incompatible change; a host rejects other versions with `version`. @stability Beta */\nexport const SETTINGS_PROTOCOL_VERSION = 1;\n\n/**\n * What the host serving the screen can do. The screen shows a write only when its capability is\n * true; the host checks again.\n *\n * - `writeFiles`: genesis.config.json and the app's files (the CLI host).\n * - `writeDatabase`: the `genesis_settings` table (both hosts).\n * - `setSecrets`: put a secret in its store, per store (`{ vault: true }`), or `true` for every\n * store. The CLI host sets them through the developer's own CLIs; the app host may set and\n * rotate Vault secrets only (`setSecret`, write-only), when it says so.\n * - `runCli`: run `supabase`, `gh`, `eas` and the package manager (the CLI host).\n * - `agent`: \"Fix with Claude\" (the CLI host, when the Agent SDK is installed).\n * - `proposeChanges`: open a pull request for a file-layer change (`propose`). Optional; off when absent.\n *\n * @stability Beta\n */\nexport interface SettingsCapabilities {\n writeFiles: boolean;\n writeDatabase: boolean;\n setSecrets: boolean | SecretStoreCapabilities;\n runCli: boolean;\n agent: boolean;\n proposeChanges?: boolean;\n}\n\n/** Which secret stores a host can write. A store left out can't be written. @stability Beta */\nexport type SecretStoreCapabilities = { readonly [S in SecretStore]?: boolean };\n\nconst SECRET_STORES: readonly SecretStore[] = [\"vault\", \"edge\", \"server-env\", \"ci\"];\n\n/** Whether the host can write a secret in this store. @stability Beta */\nexport function canSetSecret(capabilities: Pick<SettingsCapabilities, \"setSecrets\">, store: SecretStore): boolean {\n const s = capabilities.setSecrets;\n return typeof s === \"boolean\" ? s : s?.[store] === true;\n}\n\n/** Nothing: a read-only screen. @stability Beta */\nexport const NO_SETTINGS_CAPABILITIES: Readonly<SettingsCapabilities> = Object.freeze({\n writeFiles: false,\n writeDatabase: false,\n setSecrets: false,\n runCli: false,\n agent: false,\n proposeChanges: false,\n});\n\n/**\n * The most the app host may do: the database layer, and Vault secrets when the host reports it can.\n * Pass it as the screen's `capabilities` prop: it is a mask, so Vault is offered only when the host\n * itself says `setSecrets: { vault: true }`.\n *\n * @stability Beta\n */\nexport const APP_HOST_CAPABILITIES: Readonly<SettingsCapabilities> = Object.freeze({\n ...NO_SETTINGS_CAPABILITIES,\n writeDatabase: true,\n setSecrets: Object.freeze({ vault: true }),\n});\n\n/**\n * Both sets at once: a write is allowed only when both allow it. The screen narrows the host's\n * capabilities with its own `capabilities` prop this way; a prop can never widen what the host\n * reports. A key the prop leaves out doesn't narrow; only `false` does.\n *\n * @stability Beta\n */\nexport function intersectCapabilities(a: SettingsCapabilities, b?: Partial<SettingsCapabilities>): SettingsCapabilities {\n if (!b) return { ...a };\n const both = (x: boolean, y: boolean | undefined) => x === true && y !== false;\n let setSecrets: SettingsCapabilities[\"setSecrets\"];\n if (typeof a.setSecrets === \"boolean\" && (b.setSecrets === undefined || typeof b.setSecrets === \"boolean\")) {\n setSecrets = both(a.setSecrets, b.setSecrets);\n } else {\n const out: { [S in SecretStore]?: boolean } = {};\n for (const store of SECRET_STORES) {\n const allowed = canSetSecret(a, store) && (b.setSecrets === undefined || canSetSecret({ setSecrets: b.setSecrets }, store));\n if (allowed) out[store] = true;\n }\n const count = Object.keys(out).length;\n // No store left is `false` (an empty object would read as truthy); every store is `true`.\n setSecrets = count === 0 ? false : count === SECRET_STORES.length ? true : out;\n }\n return {\n writeFiles: both(a.writeFiles, b.writeFiles),\n writeDatabase: both(a.writeDatabase, b.writeDatabase),\n setSecrets,\n runCli: both(a.runCli, b.runCli),\n agent: both(a.agent, b.agent),\n proposeChanges: both(a.proposeChanges === true, b.proposeChanges),\n };\n}\n\n/** Which host is serving: the localhost wizard or the app's own screen. @stability Beta */\nexport type SettingsHost = \"cli\" | \"app\";\n\n/** What the screen shows about the app. @stability Beta */\nexport interface SettingsAppFacts {\n name: string;\n slug?: string;\n host: SettingsHost;\n preset: SettingsPreset;\n /** The installed `@marktiderman/genesis-*` release, when known. */\n genesisVersion?: string;\n platforms?: readonly (\"web\" | \"ios\" | \"android\")[];\n}\n\n/**\n * How a finding is fixed. `auto`: planned and applied by Genesis. `guided`: a setup step the\n * person walks through. `manual`: instructions only.\n *\n * @stability Beta\n */\nexport type SettingsFixKind = \"auto\" | \"guided\" | \"manual\";\n\n/** A finding's fix, by reference (the plan is made on request, never sent with the state). @stability Beta */\nexport interface SettingsFixRef {\n /** The fix id `plan` and `apply` take, e.g. `upgrade.release`, or `manual:<rule>`. */\n id: string;\n kind: SettingsFixKind;\n title?: string;\n /** A guided fix's setup step id (`genesis setup --step <id>`). */\n step?: string;\n /** Where a guided step opens, when the host has a page for it. */\n href?: string;\n /** A manual fix's instructions (plain text, may hold several lines). */\n instructions?: string;\n /**\n * An automatic fix that writes the database layer and nothing else (no files, no commands, no\n * secrets): the app host can apply it with `writeDatabase`.\n */\n databaseOnly?: boolean;\n}\n\n/** @stability Beta */\nexport type SettingsFindingLevel = \"error\" | \"warn\" | \"info\";\n\n/** One doctor finding. @stability Beta */\nexport interface SettingsFinding {\n /** Stable within one `state`: the screen keys rows and test ids on it. */\n id: string;\n rule: string;\n level: SettingsFindingLevel;\n message: string;\n file?: string;\n line?: number;\n /** The setting key or package the finding is about. */\n subject?: string;\n fix?: SettingsFixRef;\n}\n\n/** @stability Beta */\nexport type SecretState = \"set\" | \"missing\" | \"unknown\";\n\n/** One secret the app needs, by name: never its value. @stability Beta */\nexport interface SettingsSecretStatus {\n name: string;\n store: SecretStore;\n status: SecretState;\n /** ISO time it was last set, when the store says. */\n lastRotated?: string;\n /** The setting keys (or block functions) that need it. */\n neededBy: readonly string[];\n}\n\n/** How far a package is behind its latest release. @stability Beta */\nexport type UpgradeDistance = \"current\" | \"patch\" | \"minor\" | \"major\" | \"unknown\";\n\n/** @stability Beta */\nexport interface SettingsPackageUpgrade {\n name: string;\n current: string;\n latest?: string;\n distance: UpgradeDistance;\n /** An advisory affects the installed version. */\n advisory?: boolean;\n /** The changelog lines that matter to this app. */\n notes?: string;\n notesUrl?: string;\n}\n\n/** @stability Beta */\nexport interface SettingsUpgrades {\n packages: readonly SettingsPackageUpgrade[];\n /** ISO time of the registry check. */\n checkedAt?: string;\n /** The check used its cache: the network was off. */\n offline?: boolean;\n /** The upgrade fix (`upgrade.release`), when there is something to upgrade. */\n fix?: SettingsFixRef;\n}\n\n/** @stability Beta */\nexport type SettingsAuditAction = \"set\" | \"clear\" | \"fix\" | \"upgrade\" | \"secret\";\n\n/** One change in the history. Secrets appear by name only. @stability Beta */\nexport interface SettingsAuditEntry {\n id: string;\n /** ISO time. */\n at: string;\n /** Who made it: an email, a user id or `cli`. */\n actor?: string;\n action: SettingsAuditAction;\n /** The setting key, fix id, package or secret name. */\n subject: string;\n layer?: SettingsLayer;\n before?: unknown;\n after?: unknown;\n locked?: boolean;\n summary?: string;\n}\n\n/** A page of the history, newest first. @stability Beta */\nexport interface SettingsAuditPage {\n entries: readonly SettingsAuditEntry[];\n /** Pass to `audit` for the next page; absent on the last. */\n next?: string;\n}\n\n/**\n * What `state` returns: everything the screen draws.\n *\n * `layers` are the raw file and database layers (what each holds for a key, and whether it is\n * locked there), so the screen can tell \"set here\" from \"inherited\", and offer to clear a layer's\n * own value.\n *\n * @stability Beta\n */\nexport interface SettingsState {\n app: SettingsAppFacts;\n /** The catalogue's keys (`SettingDef`, serialised). */\n catalogue: readonly SettingDef[];\n resolved: ResolvedSettings;\n layers: { file?: SettingsLayerValues; database?: SettingsLayerValues };\n findings: readonly SettingsFinding[];\n secrets: readonly SettingsSecretStatus[];\n capabilities: SettingsCapabilities;\n upgrades?: SettingsUpgrades;\n audit?: SettingsAuditPage;\n}\n\n/** A file a fix writes. `diff` is unified, for the screen; the host keeps the content. @stability Beta */\nexport interface SettingsPlanFile {\n path: string;\n why: string;\n diff?: string;\n /** The file is new. */\n created?: boolean;\n}\n\n/** A command a fix runs. Secrets reach a command on stdin, never in `args`. @stability Beta */\nexport interface SettingsPlanCommand {\n tool: string;\n args: readonly string[];\n why: string;\n}\n\n/**\n * A fix's plan, as the screen shows it before anything is written. `hash` goes back to `apply` as\n * `expect`: the host re-plans and refuses (`stale_plan`) when anything changed in between.\n *\n * @stability Beta\n */\nexport interface SettingsPlan {\n fixId: string;\n summary: string;\n hash: string;\n files: readonly SettingsPlanFile[];\n commands: readonly SettingsPlanCommand[];\n /** The secrets it needs, by name. */\n secrets: readonly string[];\n /** The settings layers it writes (a fix that only seeds `genesis_settings` writes `database`). */\n layers?: readonly SettingsWriteLayer[];\n /** Steps the person does by hand after it. */\n manual?: string;\n}\n\n/** What `apply` returns. @stability Beta */\nexport interface SettingsApplyResult {\n fixId: string;\n /** The fix's own check passed after it ran. */\n verified: boolean;\n message?: string;\n /** A pull request it opened (the upgrade fix). */\n pullRequestUrl?: string;\n}\n\n/** What `propose` returns: a pull request, or the change to make by hand. @stability Beta */\nexport interface SettingsProposal {\n pullRequestUrl?: string;\n /** The genesis.config.json fragment to commit. */\n snippet: string;\n}\n\n/** The layers a person can write from the screen. @stability Beta */\nexport type SettingsWriteLayer = \"file\" | \"database\";\n\n/**\n * Every request. `audit` takes a cursor from the last page; `upgrades` with `refresh` skips the\n * host's cache.\n *\n * @stability Beta\n */\nexport type SettingsRequest =\n | { op: \"state\"; audit?: { limit?: number } }\n | { op: \"setValue\"; key: string; value: unknown; locked?: boolean; layer: SettingsWriteLayer }\n | { op: \"clearValue\"; key: string; layer: SettingsWriteLayer }\n | { op: \"plan\"; fixId: string }\n | { op: \"apply\"; fixId: string; expect: string }\n | { op: \"upgrades\"; refresh?: boolean }\n | { op: \"audit\"; cursor?: string; limit?: number }\n | { op: \"propose\"; key: string; value: unknown; locked?: boolean }\n | { op: \"setSecret\"; name: string; store: \"vault\"; value: string };\n\n/** A request on the wire. @stability Beta */\nexport type SettingsWireRequest = SettingsRequest & { v: number };\n\n/** The ops, for a host's router. @stability Beta */\nexport const SETTINGS_OPS = [\"state\", \"setValue\", \"clearValue\", \"plan\", \"apply\", \"upgrades\", \"audit\", \"propose\", \"setSecret\"] as const;\n/** @stability Beta */\nexport type SettingsOp = (typeof SETTINGS_OPS)[number];\n\n/** What each op answers. @stability Beta */\nexport interface SettingsResponses {\n state: SettingsState;\n setValue: { ok: true };\n clearValue: { ok: true };\n plan: { plan: SettingsPlan };\n apply: { result: SettingsApplyResult };\n upgrades: SettingsUpgrades;\n audit: SettingsAuditPage;\n propose: SettingsProposal;\n setSecret: { ok: true };\n}\n\n/**\n * Why a request failed.\n *\n * - `bad_request`: the body or a value is wrong (`details` may name the key).\n * - `unauthenticated` / `forbidden`: no token, or not a platform admin.\n * - `unsupported`: the host can't do it (a capability it doesn't have), or doesn't know the op: a\n * host answers an op it doesn't know (one a newer screen sends) with `unsupported`, never `bad_request`.\n * - `locked`: a lower layer locked the key.\n * - `stale_plan`: `apply`'s `expect` no longer matches a fresh plan; plan again.\n * - `not_found`: no such key or fix.\n * - `version`: a protocol version the host doesn't speak.\n * - `error`: anything else.\n *\n * @stability Beta\n */\nexport type SettingsErrorCode =\n | \"bad_request\"\n | \"unauthenticated\"\n | \"forbidden\"\n | \"unsupported\"\n | \"locked\"\n | \"stale_plan\"\n | \"not_found\"\n | \"version\"\n | \"error\";\n\n/** The body of a failed response. @stability Beta */\nexport interface SettingsErrorResponse {\n error: { code: SettingsErrorCode; message: string; details?: { [key: string]: unknown } };\n}\n\n/** A failed request, as the client throws it. @stability Beta */\nexport class SettingsProtocolError extends Error {\n readonly code: SettingsErrorCode;\n readonly status: number;\n readonly details?: { [key: string]: unknown };\n constructor(code: SettingsErrorCode, message: string, status = 0, details?: { [key: string]: unknown }) {\n super(message);\n this.name = \"SettingsProtocolError\";\n this.code = code;\n this.status = status;\n if (details) this.details = details;\n }\n}\n\nconst ERROR_CODES: readonly SettingsErrorCode[] = [\"bad_request\", \"unauthenticated\", \"forbidden\", \"unsupported\", \"locked\", \"stale_plan\", \"not_found\", \"version\", \"error\"];\n\nfunction codeForStatus(status: number): SettingsErrorCode {\n if (status === 400 || status === 422) return \"bad_request\";\n if (status === 401) return \"unauthenticated\";\n if (status === 403) return \"forbidden\";\n if (status === 404) return \"not_found\";\n if (status === 409) return \"stale_plan\";\n return \"error\";\n}\n\n/** The Settings screen's view of its host. A fake one is a plain object. @stability Beta */\nexport interface SettingsClient {\n state(params?: { auditLimit?: number }): Promise<SettingsState>;\n setValue(params: { key: string; value: unknown; locked?: boolean; layer: SettingsWriteLayer }): Promise<void>;\n clearValue(params: { key: string; layer: SettingsWriteLayer }): Promise<void>;\n plan(fixId: string): Promise<SettingsPlan>;\n apply(fixId: string, expect: string): Promise<SettingsApplyResult>;\n upgrades(params?: { refresh?: boolean }): Promise<SettingsUpgrades>;\n audit(params?: { cursor?: string; limit?: number }): Promise<SettingsAuditPage>;\n propose(params: { key: string; value: unknown; locked?: boolean }): Promise<SettingsProposal>;\n /**\n * Set or rotate a Vault secret. Write-only: the host stores it and never returns it, and the\n * screen forgets it once sent. Optional: a host without it can't set secrets from the screen.\n */\n setSecret?(params: { name: string; store: \"vault\"; value: string }): Promise<void>;\n}\n\n/** The client's own error messages, for a translation. @stability Beta */\nexport interface SettingsClientMessages {\n signIn: string;\n unreachable: (detail: string) => string;\n timedOut: (seconds: number) => string;\n notJson: (status: number) => string;\n badJson: (status: number) => string;\n notObject: string;\n status: (status: number) => string;\n badState: (what: string) => string;\n}\n\n/** @stability Beta */\nexport const SETTINGS_CLIENT_MESSAGES: SettingsClientMessages = {\n signIn: \"Sign in to change settings.\",\n unreachable: (detail) => `The settings host couldn't be reached (${detail}).`,\n timedOut: (seconds) => `The settings host didn't answer within ${seconds} seconds.`,\n notJson: (status) => `The settings host answered ${status} without JSON.`,\n badJson: (status) => `The settings host answered ${status} with JSON it couldn't read.`,\n notObject: \"The settings host answered with something other than an object.\",\n status: (status) => `The settings host answered ${status}.`,\n badState: (what) => `The settings host's state is missing ${what}.`,\n};\n\n/** @stability Beta */\nexport interface SettingsClientOptions {\n /** The endpoint the host serves, e.g. `/api/genesis/settings` or the wizard's `http://127.0.0.1:4400/api`. */\n baseUrl: string;\n /** The bearer token, or a function that returns it (the wizard's session token, the admin's access token). */\n token: string | (() => string | null | Promise<string | null>);\n /** Give up on a request after this long. Default 30 000 ms. */\n timeoutMs?: number;\n /** The client's error messages. */\n messages?: Partial<SettingsClientMessages>;\n}\n\ntype FetchLike = (\n input: string,\n init: { method: string; headers: Record<string, string>; body: string; signal: AbortSignal; credentials: \"omit\" },\n) => Promise<Pick<Response, \"ok\" | \"status\" | \"headers\" | \"text\">>;\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/** What a state must hold for the screen to draw it; the first thing missing, or null. */\nfunction stateProblem(v: Record<string, unknown>): string | null {\n for (const key of [\"catalogue\", \"findings\", \"secrets\"] as const) if (!Array.isArray(v[key])) return key;\n if (!isObject(v.capabilities)) return \"capabilities\";\n if (!isObject(v.app)) return \"app\";\n const resolved = v.resolved;\n if (!isObject(resolved) || !isObject(resolved.values) || !isObject(resolved.sources)) return \"resolved\";\n if (v.layers !== undefined && !isObject(v.layers)) return \"layers\";\n return null;\n}\n\n/**\n * A {@link SettingsClient} over `fetch`. JSON only: a response that isn't JSON is an error, so a\n * login page or a proxy's HTML never reaches the screen as data.\n *\n * ```ts\n * const client = createSettingsClient(fetch, { baseUrl: \"/api/genesis/settings\", token: () => session.access_token });\n * ```\n *\n * @stability Beta\n */\nexport function createSettingsClient(fetchFn: FetchLike, options: SettingsClientOptions): SettingsClient {\n const m: SettingsClientMessages = { ...SETTINGS_CLIENT_MESSAGES, ...options.messages };\n const timeoutMs = options.timeoutMs ?? 30_000;\n\n async function call<O extends SettingsOp>(body: Extract<SettingsRequest, { op: O }>): Promise<SettingsResponses[O]> {\n const token = typeof options.token === \"function\" ? await options.token() : options.token;\n if (!token) throw new SettingsProtocolError(\"unauthenticated\", m.signIn);\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n let response: Awaited<ReturnType<FetchLike>>;\n let text: string;\n try {\n response = await fetchFn(options.baseUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", authorization: `Bearer ${token}` },\n body: JSON.stringify({ v: SETTINGS_PROTOCOL_VERSION, ...body }),\n signal: controller.signal,\n // The bearer token is the only credential: no cookies, so no cross-site request forgery.\n credentials: \"omit\",\n });\n text = await response.text();\n } catch (error) {\n if (timedOut) throw new SettingsProtocolError(\"error\", m.timedOut(Math.round(timeoutMs / 1000)));\n throw new SettingsProtocolError(\"error\", m.unreachable(error instanceof Error ? error.message : String(error)));\n } finally {\n clearTimeout(timer);\n }\n const type = response.headers.get(\"content-type\") ?? \"\";\n if (!/^application\\/(?:[\\w.+-]+\\+)?json\\b/i.test(type)) {\n throw new SettingsProtocolError(response.ok ? \"error\" : codeForStatus(response.status), m.notJson(response.status), response.status);\n }\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch {\n throw new SettingsProtocolError(\"error\", m.badJson(response.status), response.status);\n }\n if (!response.ok) {\n const error = (payload as Partial<SettingsErrorResponse> | null)?.error;\n const code = error && ERROR_CODES.includes(error.code) ? error.code : codeForStatus(response.status);\n const message = typeof error?.message === \"string\" ? error.message : m.status(response.status);\n throw new SettingsProtocolError(code, message, response.status, error?.details);\n }\n if (!isObject(payload)) throw new SettingsProtocolError(\"error\", m.notObject, response.status);\n return payload as SettingsResponses[O];\n }\n\n return {\n async state(params) {\n const state = await call({ op: \"state\", ...(params?.auditLimit !== undefined ? { audit: { limit: params.auditLimit } } : {}) });\n const missing = stateProblem(state as unknown as Record<string, unknown>);\n if (missing) throw new SettingsProtocolError(\"error\", m.badState(missing));\n return { ...state, layers: state.layers ?? {} };\n },\n async setValue({ key, value, locked, layer }) {\n await call({ op: \"setValue\", key, value, layer, ...(locked !== undefined ? { locked } : {}) });\n },\n async clearValue({ key, layer }) {\n await call({ op: \"clearValue\", key, layer });\n },\n plan: async (fixId) => (await call({ op: \"plan\", fixId })).plan,\n apply: async (fixId, expect) => (await call({ op: \"apply\", fixId, expect })).result,\n upgrades: (params) => call({ op: \"upgrades\", ...(params?.refresh ? { refresh: true } : {}) }),\n audit: (params) => call({ op: \"audit\", ...(params?.cursor !== undefined ? { cursor: params.cursor } : {}), ...(params?.limit !== undefined ? { limit: params.limit } : {}) }),\n propose: ({ key, value, locked }) => call({ op: \"propose\", key, value, ...(locked !== undefined ? { locked } : {}) }),\n async setSecret({ name, value }) {\n await call({ op: \"setSecret\", name, store: \"vault\", value });\n },\n };\n}\n\n/** Why a key can't be written in a layer from this screen. @stability Beta */\nexport type SettingWriteRefusal =\n | \"build\"\n | \"capability\"\n | \"locked\";\n\n/** Where a key can be written from this screen, or why it can't. @stability Beta */\nexport interface SettingWritability {\n /** The layers the screen may write, low to high. Empty when it can write none. */\n layers: SettingsWriteLayer[];\n /** Why a layer is missing: the host can't write it, the key applies at build, or a lower layer locked it. */\n refused: Partial<Record<SettingsWriteLayer, SettingWriteRefusal>>;\n}\n\nconst LAYER_INDEX = new Map<SettingsLayer, number>(SETTINGS_LAYERS.map((layer, i) => [layer, i]));\n\n/**\n * The write rules, in one place, for the screen and a host's handler alike:\n *\n * - a key that applies at build time is written only in the file layer;\n * - the file layer needs `writeFiles`, the database layer `writeDatabase`;\n * - a key locked by a layer below the target can't be changed there (the lock's own layer can).\n *\n * The app host (`writeDatabase` only) therefore writes runtime keys in the database layer and\n * shows build keys read-only, with \"change in repo\".\n *\n * @stability Beta\n */\nexport function settingWritability(def: Pick<SettingDef, \"applies\">, source: { lockedBy?: SettingsLayer } | undefined, capabilities: SettingsCapabilities): SettingWritability {\n const layers: SettingsWriteLayer[] = [];\n const refused: SettingWritability[\"refused\"] = {};\n for (const layer of [\"file\", \"database\"] as const) {\n if (layer === \"database\" && def.applies === \"build\") {\n refused[layer] = \"build\";\n continue;\n }\n if (!(layer === \"file\" ? capabilities.writeFiles : capabilities.writeDatabase)) {\n refused[layer] = \"capability\";\n continue;\n }\n const lockedBy = source?.lockedBy;\n if (lockedBy && (LAYER_INDEX.get(lockedBy) ?? 0) < (LAYER_INDEX.get(layer) ?? 0)) {\n refused[layer] = \"locked\";\n continue;\n }\n layers.push(layer);\n }\n return { layers, refused };\n}\n\n/**\n * The genesis.config.json fragment for one key: its value, or `{ value, locked: true }`. What\n * \"change in repo\" shows, and what `propose` commits.\n *\n * @stability Beta\n */\nexport function settingFileSnippet(key: string, value: unknown, locked?: boolean): string {\n const entry = locked ? { value, locked: true } : value;\n return JSON.stringify({ settings: { [key]: entry } }, null, 2);\n}\n\n/**\n * The layer the screen writes by default: the database when the value already comes from there\n * (and the screen can write it), else the file layer when it can (reviewed like code), else the\n * database. Otherwise, writing the database from the CLI host is an explicit choice.\n *\n * @stability Beta\n */\nexport function preferredWriteLayer(writable: Pick<SettingWritability, \"layers\">, source?: { layer: SettingsLayer }): SettingsWriteLayer | undefined {\n if (source?.layer === \"database\" && writable.layers.includes(\"database\")) return \"database\";\n return writable.layers.includes(\"file\") ? \"file\" : writable.layers[0];\n}\n\n/** Every secret name the app knows: the state's secrets and each catalogue key's `needs`. @stability Beta */\nexport function secretNames(catalogue: readonly Pick<SettingDef, \"secret\">[], secrets: readonly Pick<SettingsSecretStatus, \"name\">[]): Set<string> {\n const names = new Set<string>();\n for (const s of secrets) names.add(s.name);\n for (const def of catalogue) if (def.secret) names.add(def.secret.name);\n return names;\n}\n\n/**\n * Whether an audit entry's `before` and `after` may be drawn: only for a `set` or `clear` of a\n * catalogue key that needs no secret and isn't itself a secret's name. Everything else (a fix, an\n * upgrade, a secret, a subject the catalogue doesn't know) shows its subject and summary only, so\n * a value a host forgot to redact never reaches the screen through the history.\n *\n * @stability Beta\n */\nexport function auditValuesVisible(\n entry: Pick<SettingsAuditEntry, \"action\" | \"subject\">,\n catalogue: readonly Pick<SettingDef, \"key\" | \"secret\">[],\n names: ReadonlySet<string>,\n): boolean {\n if (entry.action !== \"set\" && entry.action !== \"clear\") return false;\n if (names.has(entry.subject)) return false;\n const def = catalogue.find((d) => d.key === entry.subject);\n return def !== undefined && def.secret === undefined;\n}\n\n/**\n * A link the screen may follow: `http:`, `https:` or a path on the same site (`/…`, `./…`, `../…`,\n * `#…`, `?…`), never `javascript:`, `data:` or a protocol-relative `//host`. Undefined otherwise.\n *\n * @stability Beta\n */\nexport function safeHref(href: string | undefined): string | undefined {\n if (typeof href !== \"string\") return undefined;\n const h = href.trim();\n // A browser drops tabs and newlines in a URL, so `/\\t/evil.test` would become `//evil.test`.\n if (!h || /[\\u0000-\\u001F\\u007F]/.test(h)) return undefined;\n if (/^(?:\\/(?![/\\\\])|\\.\\.?\\/|#|\\?)/.test(h)) return h;\n try {\n const url = new URL(h);\n return url.protocol === \"http:\" || url.protocol === \"https:\" ? h : undefined;\n } catch {\n return undefined;\n }\n}\n"]}
@@ -0,0 +1,123 @@
1
+ import { statusOn } from './chunk-OW46SL2G.js';
2
+
3
+ // src/gate.ts
4
+ var SHIPPED_STATUSES = [
5
+ "beta",
6
+ "live",
7
+ "deprecated"
8
+ ];
9
+ var GATING_KINDS = ["release", "permission"];
10
+ function toTest(set, name) {
11
+ if (set === void 0) return () => false;
12
+ if (typeof set === "function") return set;
13
+ if (typeof set === "string")
14
+ throw new TypeError(
15
+ `GateContext.${name} must be a list, a Set or a function, not a string`
16
+ );
17
+ if (Array.isArray(set)) {
18
+ const ids = new Set(set);
19
+ return (id) => ids.has(id);
20
+ }
21
+ if (set instanceof Set) return (id) => set.has(id);
22
+ throw new TypeError(
23
+ `GateContext.${name} must be a list, a Set or a function`
24
+ );
25
+ }
26
+ function flagValue(flags, name) {
27
+ if (!flags) return void 0;
28
+ if (typeof flags === "function") return flags(name);
29
+ return Object.hasOwn(flags, name) ? flags[name] : void 0;
30
+ }
31
+ function prepare(registry, context) {
32
+ return {
33
+ registry,
34
+ context,
35
+ entitled: toTest(context.entitlements, "entitlements"),
36
+ off: toTest(context.off, "off"),
37
+ settingsOff: toTest(context.settingsOff, "settingsOff")
38
+ };
39
+ }
40
+ function answer(prepared, id, seen = /* @__PURE__ */ new Set()) {
41
+ const { registry, context, entitled, off, settingsOff } = prepared;
42
+ const def = Object.hasOwn(registry.features, id) ? registry.features[id] : void 0;
43
+ if (!def) return { on: false, reason: "unknown" };
44
+ if (!SHIPPED_STATUSES.includes(def.status))
45
+ return { on: false, reason: "status" };
46
+ const here = statusOn(def, context.platform);
47
+ if (!here || !SHIPPED_STATUSES.includes(here))
48
+ return { on: false, reason: "platform" };
49
+ for (const need of def.requires ?? []) {
50
+ if (need === id || seen.has(need) || !Object.hasOwn(registry.features, need)) continue;
51
+ const parent = answer(prepared, need, /* @__PURE__ */ new Set([...seen, id]));
52
+ if (!parent.on) return { ...parent, via: parent.via ?? need };
53
+ }
54
+ if (settingsOff(id)) return { on: false, reason: "setting" };
55
+ if (off(id)) return { on: false, reason: "tenant" };
56
+ for (const [name, flag] of Object.entries(registry.flags ?? {})) {
57
+ if (flag.feature !== id || !GATING_KINDS.includes(flag.kind) || typeof flag.default !== "boolean")
58
+ continue;
59
+ if ((flagValue(context.flags, name) ?? flag.default) !== true)
60
+ return { on: false, reason: "flag", flag: name };
61
+ }
62
+ const access = def.access ?? "all";
63
+ if (access !== "all" && !entitled(id))
64
+ return { on: false, reason: "entitlement", unlock: { plan: access.plan } };
65
+ return { on: true };
66
+ }
67
+ function featureOn(registry, context, id) {
68
+ return answer(prepare(registry, context), id);
69
+ }
70
+ function gateSnapshot(registry, context, options = {}) {
71
+ const prepared = prepare(registry, context);
72
+ const ids = options.ids === void 0 ? Object.keys(registry.features).filter(
73
+ (id) => SHIPPED_STATUSES.includes(registry.features[id].status)
74
+ ) : Array.from(options.ids);
75
+ const answers = {};
76
+ for (const id of ids) {
77
+ const { flag: _flag, ...rest } = answer(prepared, id);
78
+ answers[id] = rest;
79
+ }
80
+ return {
81
+ answers,
82
+ at: (options.at ?? /* @__PURE__ */ new Date()).toISOString(),
83
+ ...options.version === void 0 ? {} : { version: options.version }
84
+ };
85
+ }
86
+ function isSnapshotStale(snapshot, maxAgeMs, now = /* @__PURE__ */ new Date()) {
87
+ const at = Date.parse(snapshot?.at);
88
+ return Number.isNaN(at) || Math.abs(now.getTime() - at) > maxAgeMs;
89
+ }
90
+ function fromSnapshot(snapshot, id) {
91
+ const answers = snapshot?.answers;
92
+ return (answers && Object.hasOwn(answers, id) ? answers[id] : void 0) ?? { on: false, reason: "unknown" };
93
+ }
94
+ var FeatureOff = class extends Error {
95
+ feature;
96
+ reason;
97
+ unlock;
98
+ /** The required feature that turned it off, when one did. */
99
+ via;
100
+ constructor(feature, answer2) {
101
+ const through = answer2.via ? ` (through ${answer2.via})` : "";
102
+ super(
103
+ answer2.reason === "entitlement" && answer2.unlock ? `${feature} needs the ${answer2.unlock.plan} plan${through}` : `${feature} is off (${answer2.reason ?? "unknown"}${answer2.via ? ` via ${answer2.via}` : ""})`
104
+ );
105
+ this.name = "FeatureOff";
106
+ this.feature = feature;
107
+ this.reason = answer2.reason ?? "unknown";
108
+ if (answer2.unlock) this.unlock = answer2.unlock;
109
+ if (answer2.via) this.via = answer2.via;
110
+ }
111
+ /** The HTTP status for this refusal: 402 when a plan unlocks it, else 403. */
112
+ get status() {
113
+ return this.reason === "entitlement" ? 402 : 403;
114
+ }
115
+ };
116
+ function requireFeature(registry, context, id) {
117
+ const result = featureOn(registry, context, id);
118
+ if (!result.on) throw new FeatureOff(id, result);
119
+ }
120
+
121
+ export { FeatureOff, SHIPPED_STATUSES, featureOn, fromSnapshot, gateSnapshot, isSnapshotStale, requireFeature };
122
+ //# sourceMappingURL=chunk-M7IY6LUN.js.map
123
+ //# sourceMappingURL=chunk-M7IY6LUN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gate.ts"],"names":["answer"],"mappings":";;;AA2CO,IAAM,gBAAA,GAA6C;AAAA,EACxD,MAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF;AAoFA,IAAM,YAAA,GAAoC,CAAC,SAAA,EAAW,YAAY,CAAA;AAIlE,SAAS,MAAA,CAAO,KAAwB,IAAA,EAAoB;AAC1D,EAAA,IAAI,GAAA,KAAQ,MAAA,EAAW,OAAO,MAAM,KAAA;AACpC,EAAA,IAAI,OAAO,GAAA,KAAQ,UAAA,EAAY,OAAO,GAAA;AACtC,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA;AACjB,IAAA,MAAM,IAAI,SAAA;AAAA,MACR,eAAe,IAAI,CAAA,kDAAA;AAAA,KACrB;AACF,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,GAAG,CAAA,EAAG;AACtB,IAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAY,GAAG,CAAA;AAC/B,IAAA,OAAO,CAAC,EAAA,KAAO,GAAA,CAAI,GAAA,CAAI,EAAE,CAAA;AAAA,EAC3B;AACA,EAAA,IAAI,eAAe,GAAA,EAAK,OAAO,CAAC,EAAA,KAAO,GAAA,CAAI,IAAI,EAAE,CAAA;AACjD,EAAA,MAAM,IAAI,SAAA;AAAA,IACR,eAAe,IAAI,CAAA,oCAAA;AAAA,GACrB;AACF;AAEA,SAAS,SAAA,CACP,OACA,IAAA,EACuB;AACvB,EAAA,IAAI,CAAC,OAAO,OAAO,MAAA;AACnB,EAAA,IAAI,OAAO,KAAA,KAAU,UAAA,EAAY,OAAO,MAAM,IAAI,CAAA;AAClD,EAAA,OAAO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AG,CAAA,CAAA,GAAK,EAAE,CAAA,CAAA;AAAA,KAC/F;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,YAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,MAAA,GAASA,QAAO,MAAA,IAAU,SAAA;AAC/B,IAAA,IAAIA,OAAAA,CAAO,MAAA,EAAQ,IAAA,CAAK,MAAA,GAASA,OAAAA,CAAO,MAAA;AACxC,IAAA,IAAIA,OAAAA,CAAO,GAAA,EAAK,IAAA,CAAK,GAAA,GAAMA,OAAAA,CAAO,GAAA;AAAA,EACpC;AAAA;AAAA,EAGA,IAAI,MAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,MAAA,KAAW,aAAA,GAAgB,GAAA,GAAM,GAAA;AAAA,EAC/C;AACF;AAYO,SAAS,cAAA,CACd,QAAA,EACA,OAAA,EACA,EAAA,EACM;AACN,EAAA,MAAM,MAAA,GAAS,SAAA,CAAU,QAAA,EAAU,OAAA,EAAS,EAAE,CAAA;AAC9C,EAAA,IAAI,CAAC,MAAA,CAAO,EAAA,QAAU,IAAI,UAAA,CAAW,IAAI,MAAM,CAAA;AACjD","file":"chunk-M7IY6LUN.js","sourcesContent":["/**\n * The feature gate: one answer to \"is this feature on here?\" for UI, server\n * code, agents and (for status and entitlement) the database.\n *\n * Checks run in a fixed order and the first \"no\" wins:\n *\n * 1. status the feature has shipped (beta, live or deprecated)\n * 2. platform it has shipped on this platform\n * 3. setting no setting switched it off (genesis-config settings, withSettings)\n * 4. tenant the tenant has not switched it off\n * 5. flag each of its boolean release or permission flags is true\n * 6. entitlement a paid feature (`access: { plan }`) has an active entitlement\n *\n * A feature that `requires` other features in the registry (a module's parts\n * require the module) is also off while any of them is off: after its own\n * status and platform, each required feature is asked the same way, and the\n * first \"no\" comes back with `via` naming it. So switching a module off, or not\n * paying for it, turns off every part with it, and the upsell names the module's\n * plan.\n *\n * Entitlement is last on purpose: an \"upgrade to unlock\" answer is only given\n * when paying is the one thing missing, so an upsell never promises a feature\n * that a switch or a flag would still keep off.\n *\n * The registry comes from code (features.ts and flags.json). Everything that\n * changes at runtime (entitlements, switches, flag values) comes in through\n * {@link GateContext}, read once per request or session on the server. Role\n * and row rights are not the gate's business: \"may this person\" stays with\n * roles and row security.\n *\n * No zod, React, Node built-ins or DOM globals here: this file ships to\n * browsers, extension service workers, phones and edge functions.\n */\nimport type {\n FeatureAccess,\n FeatureStatus,\n FlagKind,\n FlagValue,\n} from \"./types\";\nimport { statusOn } from \"./status\";\nimport type { FeaturePlatform } from \"./platforms\";\n\n/** The statuses in which a feature is on. A deprecated feature still works until it is retired. @stability Beta */\nexport const SHIPPED_STATUSES: readonly FeatureStatus[] = [\n \"beta\",\n \"live\",\n \"deprecated\",\n];\n\n/**\n * Why a feature is off: the first check that said no. `unknown` is an id that\n * isn't in the registry (or not in a snapshot).\n *\n * @stability Beta\n */\nexport type GateReason =\n \"unknown\" | \"status\" | \"platform\" | \"setting\" | \"tenant\" | \"flag\" | \"entitlement\";\n\n/**\n * The gate's answer for one feature. `unlock` is set when the reason is\n * `entitlement`: the plan that turns it on, so the UI can show an upgrade\n * instead of hiding the feature.\n *\n * @stability Beta\n */\nexport interface GateAnswer {\n on: boolean;\n reason?: GateReason;\n unlock?: { plan: string };\n /** The flag that turned it off, when the reason is `flag`. Server side only: snapshots leave it out. */\n flag?: string;\n /** The required feature that turned it off (a module its part needs), when the \"no\" came from one. */\n via?: string;\n}\n\n/** The fields of a feature the gate reads. A `FeatureDef` fits. @stability Beta */\nexport interface GateFeature {\n status: FeatureStatus;\n apps: readonly string[];\n platforms?: Partial<Record<FeaturePlatform, FeatureStatus>>;\n access?: FeatureAccess;\n /** Ids this feature needs; those in the registry must be on too. */\n requires?: readonly string[];\n}\n\n/** The fields of a flag the gate reads. A `FlagDef` fits. @stability Beta */\nexport interface GateFlag {\n feature: string;\n kind: FlagKind;\n default: FlagValue;\n}\n\n/** What the gate decides from: the registry, as code defines it. @stability Beta */\nexport interface GateRegistry {\n features: { readonly [id: string]: GateFeature };\n flags?: { readonly [name: string]: GateFlag };\n}\n\n/**\n * A set of ids: a list, a Set or a test. Not any iterable: an iterator would\n * be used up by the first feature asked, and a bare string would count as its\n * characters.\n *\n * @stability Beta\n */\nexport type IdSet =\n readonly string[] | ReadonlySet<string> | ((id: string) => boolean);\n\n/**\n * Where and for whom the gate is asked: the platform, plus the tenant's\n * runtime state. Leave out what the app doesn't have: no `entitlements` means\n * no paid feature is on, no `off` means no switch is off, no `flags` means\n * every flag has its default.\n *\n * @stability Beta\n */\nexport interface GateContext {\n platform: FeaturePlatform;\n /** Feature ids with an active entitlement: the tenant's, and the viewer's own (a person grant). */\n entitlements?: IdSet;\n /** Feature ids the tenant switched off. */\n off?: IdSet;\n /** Feature ids a setting switched off (`withSettings` fills it): answered with reason `setting`. */\n settingsOff?: IdSet;\n /** Flag values for this tenant, by flag name. A missing flag has its default. */\n flags?:\n | { readonly [name: string]: FlagValue | undefined }\n | ((name: string) => FlagValue | undefined);\n}\n\n/** Flag kinds that can turn a feature off. Experiments and ops flags pick a variant; they don't gate. */\nconst GATING_KINDS: readonly FlagKind[] = [\"release\", \"permission\"];\n\ntype Test = (id: string) => boolean;\n\nfunction toTest(set: IdSet | undefined, name: string): Test {\n if (set === undefined) return () => false;\n if (typeof set === \"function\") return set;\n if (typeof set === \"string\")\n throw new TypeError(\n `GateContext.${name} must be a list, a Set or a function, not a string`,\n );\n if (Array.isArray(set)) {\n const ids = new Set<string>(set);\n return (id) => ids.has(id);\n }\n if (set instanceof Set) return (id) => set.has(id);\n throw new TypeError(\n `GateContext.${name} must be a list, a Set or a function`,\n );\n}\n\nfunction flagValue(\n flags: GateContext[\"flags\"],\n name: string,\n): FlagValue | undefined {\n if (!flags) return undefined;\n if (typeof flags === \"function\") return flags(name);\n return Object.hasOwn(flags, name) ? flags[name] : undefined;\n}\n\ninterface Prepared {\n registry: GateRegistry;\n context: GateContext;\n entitled: Test;\n off: Test;\n settingsOff: Test;\n}\n\nfunction prepare(registry: GateRegistry, context: GateContext): Prepared {\n return {\n registry,\n context,\n entitled: toTest(context.entitlements, \"entitlements\"),\n off: toTest(context.off, \"off\"),\n settingsOff: toTest(context.settingsOff, \"settingsOff\"),\n };\n}\n\nfunction answer(prepared: Prepared, id: string, seen: ReadonlySet<string> = new Set()): GateAnswer {\n const { registry, context, entitled, off, settingsOff } = prepared;\n const def = Object.hasOwn(registry.features, id)\n ? registry.features[id]\n : undefined;\n if (!def) return { on: false, reason: \"unknown\" };\n if (!SHIPPED_STATUSES.includes(def.status))\n return { on: false, reason: \"status\" };\n const here = statusOn(def, context.platform);\n if (!here || !SHIPPED_STATUSES.includes(here))\n return { on: false, reason: \"platform\" };\n // What it requires must be on too: a module's parts go off with the module.\n // Ids outside the registry (blocks, infrastructure) don't gate; a cycle is cut.\n for (const need of def.requires ?? []) {\n if (need === id || seen.has(need) || !Object.hasOwn(registry.features, need)) continue;\n const parent = answer(prepared, need, new Set([...seen, id]));\n if (!parent.on) return { ...parent, via: parent.via ?? need };\n }\n if (settingsOff(id)) return { on: false, reason: \"setting\" };\n if (off(id)) return { on: false, reason: \"tenant\" };\n for (const [name, flag] of Object.entries(registry.flags ?? {})) {\n if (\n flag.feature !== id ||\n !GATING_KINDS.includes(flag.kind) ||\n typeof flag.default !== \"boolean\"\n )\n continue;\n // On only when exactly true: a malformed value (\"false\", 0, null) keeps the feature off.\n if ((flagValue(context.flags, name) ?? flag.default) !== true)\n return { on: false, reason: \"flag\", flag: name };\n }\n const access = def.access ?? \"all\";\n if (access !== \"all\" && !entitled(id))\n return { on: false, reason: \"entitlement\", unlock: { plan: access.plan } };\n return { on: true };\n}\n\n/**\n * Is feature `id` on for this context? Returns the first check that said no\n * as `reason`, and for a paid feature the plan that unlocks it. An unknown id\n * is off with reason `unknown`; it never throws for one.\n *\n * ```ts\n * const answer = featureOn({ features, flags }, { platform: \"web\", entitlements, off }, \"form-webhook-delivery\");\n * // { on: false, reason: \"entitlement\", unlock: { plan: \"pro\" } }\n * ```\n *\n * @stability Beta\n */\nexport function featureOn(\n registry: GateRegistry,\n context: GateContext,\n id: string,\n): GateAnswer {\n return answer(prepare(registry, context), id);\n}\n\n/**\n * Every shipped feature's answer for one context: what a server hands a\n * client, so the client never decides on its own. Plain JSON, safe to store\n * (an extension's session storage, a cache) and to compare by `version`.\n *\n * It lists only features that have shipped somewhere (beta, live or\n * deprecated) and leaves out flag names; anything missing reads as off.\n *\n * @stability Beta\n */\nexport interface GateSnapshot {\n /** The answers, by feature id. */\n readonly answers: { readonly [id: string]: GateAnswer };\n /** When the server made it (ISO 8601). Refresh after your own time limit. */\n readonly at: string;\n /** The registry version it was made from, when known (the build's version). */\n readonly version?: string | number;\n}\n\n/** @stability Beta */\nexport interface GateSnapshotOptions {\n /** Answer for these features only. */\n ids?: Iterable<string>;\n /** The registry version, carried into the snapshot. */\n version?: string | number;\n /** The time to stamp (default now). */\n at?: Date;\n}\n\n/** @stability Beta */\nexport function gateSnapshot(\n registry: GateRegistry,\n context: GateContext,\n options: GateSnapshotOptions = {},\n): GateSnapshot {\n const prepared = prepare(registry, context);\n const ids =\n options.ids === undefined\n ? Object.keys(registry.features).filter((id) =>\n SHIPPED_STATUSES.includes(registry.features[id]!.status),\n )\n : Array.from(options.ids);\n const answers: Record<string, GateAnswer> = {};\n for (const id of ids) {\n const { flag: _flag, ...rest } = answer(prepared, id);\n answers[id] = rest;\n }\n return {\n answers,\n at: (options.at ?? new Date()).toISOString(),\n ...(options.version === undefined ? {} : { version: options.version }),\n };\n}\n\n/**\n * Whether a snapshot is older than `maxAgeMs`: refresh it then. A client\n * (an extension worker, a tab left open) keeps a snapshot, replaces it when it\n * is stale, after sign-in or a tenant switch, and right after a refusal.\n *\n * @stability Beta\n */\nexport function isSnapshotStale(snapshot: GateSnapshot, maxAgeMs: number, now: Date = new Date()): boolean {\n const at = Date.parse(snapshot?.at);\n // Too old, unreadable, or dated in the future (a wrong clock or a forged copy): refresh.\n return Number.isNaN(at) || Math.abs(now.getTime() - at) > maxAgeMs;\n}\n\n/** One feature's answer from a snapshot. An id missing from it is off, as an unknown feature. @stability Beta */\nexport function fromSnapshot(snapshot: GateSnapshot, id: string): GateAnswer {\n // A stored snapshot may be from an older shape, or damaged: missing answers mean off.\n const answers: GateSnapshot[\"answers\"] | undefined = snapshot?.answers;\n return (answers && Object.hasOwn(answers, id) ? answers[id] : undefined) ?? { on: false, reason: \"unknown\" };\n}\n\n/**\n * Thrown by {@link requireFeature} when a feature is off. Servers map it to a\n * refusal that carries the reason (HTTP 403, or 402 for `entitlement`).\n *\n * @stability Beta\n */\nexport class FeatureOff extends Error {\n readonly feature: string;\n readonly reason: GateReason;\n readonly unlock?: { plan: string };\n /** The required feature that turned it off, when one did. */\n readonly via?: string;\n constructor(feature: string, answer: GateAnswer) {\n const through = answer.via ? ` (through ${answer.via})` : \"\";\n super(\n answer.reason === \"entitlement\" && answer.unlock\n ? `${feature} needs the ${answer.unlock.plan} plan${through}`\n : `${feature} is off (${answer.reason ?? \"unknown\"}${answer.via ? ` via ${answer.via}` : \"\"})`,\n );\n this.name = \"FeatureOff\";\n this.feature = feature;\n this.reason = answer.reason ?? \"unknown\";\n if (answer.unlock) this.unlock = answer.unlock;\n if (answer.via) this.via = answer.via;\n }\n\n /** The HTTP status for this refusal: 402 when a plan unlocks it, else 403. */\n get status(): 402 | 403 {\n return this.reason === \"entitlement\" ? 402 : 403;\n }\n}\n\n/**\n * Refuse unless the feature is on: call it at the top of every server\n * function and route that belongs to a feature.\n *\n * ```ts\n * requireFeature({ features, flags }, await gateContext(tenant), \"form-webhook-delivery\");\n * ```\n *\n * @stability Beta\n */\nexport function requireFeature(\n registry: GateRegistry,\n context: GateContext,\n id: string,\n): void {\n const result = featureOn(registry, context, id);\n if (!result.on) throw new FeatureOff(id, result);\n}\n"]}
@@ -0,0 +1,10 @@
1
+ // src/status.ts
2
+ function statusOn(def, platform) {
3
+ if (def.platforms) return def.platforms[platform];
4
+ const apps = def.apps.map((a) => a === "node" ? "server" : a);
5
+ return apps.includes(platform) ? def.status : void 0;
6
+ }
7
+
8
+ export { statusOn };
9
+ //# sourceMappingURL=chunk-OW46SL2G.js.map
10
+ //# sourceMappingURL=chunk-OW46SL2G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/status.ts"],"names":[],"mappings":";AASO,SAAS,QAAA,CACd,KAKA,QAAA,EAC2B;AAC3B,EAAA,IAAI,GAAA,CAAI,SAAA,EAAW,OAAO,GAAA,CAAI,UAAU,QAAQ,CAAA;AAEhD,EAAA,MAAM,IAAA,GAAO,IAAI,IAAA,CAAK,GAAA,CAAI,CAAC,CAAA,KAAO,CAAA,KAAM,MAAA,GAAS,QAAA,GAAW,CAAE,CAAA;AAC9D,EAAA,OAAO,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,GAAI,IAAI,MAAA,GAAS,MAAA;AAChD","file":"chunk-OW46SL2G.js","sourcesContent":["import type { FeatureStatus } from \"./types\";\nimport type { FeaturePlatform } from \"./platforms\";\n\n/**\n * A feature's status on one platform, or undefined when it isn't there.\n * Zod-free so the gate can use it on phones and in browsers.\n *\n * @stability Beta\n */\nexport function statusOn(\n def: {\n status: FeatureStatus;\n apps: readonly string[];\n platforms?: Partial<Record<FeaturePlatform, FeatureStatus>>;\n },\n platform: FeaturePlatform,\n): FeatureStatus | undefined {\n if (def.platforms) return def.platforms[platform];\n // Registries often call the server \"node\" in `apps`.\n const apps = def.apps.map((a) => (a === \"node\" ? \"server\" : a));\n return apps.includes(platform) ? def.status : undefined;\n}\n"]}