@krizaka/settings 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,15 @@
1
- # Temporary Holding Version
1
+ # @krizaka/settings
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+
5
+ ```ts
6
+ import { defineSettings, flag, integer, postgresSettings, settingsMigration, GLOBAL, WORKSPACE_SCOPES } from "@krizaka/settings";
7
+
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
+ await db.query(settingsMigration()); // once, in your migrations (idempotent)
10
+ const service = postgresSettings(settings, { query, workspaceOf, clock: () => performance.now() });
11
+ await service.get("features.apiKeys", { userId }); // typed: boolean
12
+ await service.set({ id: adminId, label: email }, GLOBAL, "features.apiKeys", false, now);
13
+ ```
14
+
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.
@@ -0,0 +1,170 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * 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
5
+ * the database, changed by an administrator without a redeploy; the registry is the one place that says what exists, so the admin
6
+ * forms, the validation and the checks at the server boundary all read the same list.
7
+ */
8
+ declare const SCOPE: {
9
+ readonly global: "global";
10
+ readonly workspace: "workspace";
11
+ readonly user: "user";
12
+ };
13
+ type Scope = (typeof SCOPE)[keyof typeof SCOPE];
14
+ /** The order a value is looked up in: the most specific wins (user, then workspace, then global). */
15
+ declare const SCOPES_BY_SPECIFICITY: readonly ["user", "workspace", "global"];
16
+ declare const KIND: {
17
+ readonly flag: "flag";
18
+ readonly integer: "integer";
19
+ readonly choice: "choice";
20
+ readonly bilingual: "bilingual";
21
+ readonly subset: "subset";
22
+ };
23
+ type Kind = (typeof KIND)[keyof typeof KIND];
24
+ interface Def<T = unknown> {
25
+ /** The admin screen the setting belongs to (the product names its own groups). */
26
+ group: string;
27
+ kind: Kind;
28
+ schema: z.ZodType<T>;
29
+ default: T;
30
+ scopes: readonly Scope[];
31
+ /** For a number: its bounds and unit; for a choice or a subset: the values. */
32
+ min?: number;
33
+ max?: number;
34
+ unit?: string;
35
+ choices?: readonly string[];
36
+ }
37
+ declare const ALL_SCOPES: readonly Scope[];
38
+ declare const WORKSPACE_SCOPES: readonly Scope[];
39
+ declare const GLOBAL_ONLY: readonly Scope[];
40
+ declare const flag: (group: string, value: boolean, scopes?: readonly Scope[]) => Def<boolean>;
41
+ declare const integer: (group: string, value: number, bounds: {
42
+ min: number;
43
+ max: number;
44
+ unit?: string;
45
+ }, scopes?: readonly Scope[]) => Def<number>;
46
+ declare const choice: <const C extends readonly [string, ...string[]]>(group: string, choices: C, value: C[number], scopes?: readonly Scope[]) => Def<C[number]>;
47
+ declare const subset: <const C extends readonly [string, ...string[]]>(group: string, choices: C, value: C[number][], scopes?: readonly Scope[]) => Def<C[number][]>;
48
+ declare const bilingual: (group: string, value: {
49
+ fr: string;
50
+ en: string;
51
+ }, scopes?: readonly Scope[]) => Def<{
52
+ fr: string;
53
+ en: string;
54
+ }>;
55
+ /** A registry: keys to definitions (write it `as const satisfies Registry` to keep the keys and the value types). */
56
+ type Registry = Record<string, Def<never> | Def<boolean> | Def<number> | Def<string> | Def<string[]> | Def<{
57
+ fr: string;
58
+ en: string;
59
+ }>>;
60
+ type KeyOf<R extends Registry> = keyof R & string;
61
+ type ValueOf<R extends Registry, K extends KeyOf<R>> = z.infer<R[K]["schema"]>;
62
+ /** The tools over one registry: what is a key, its definition, the keys of a group. */
63
+ declare function defineSettings<R extends Registry>(registry: R): {
64
+ registry: R;
65
+ keys: KeyOf<R>[];
66
+ isKey: (key: string) => key is KeyOf<R>;
67
+ defOf: (key: KeyOf<R>) => Def;
68
+ keysOfGroup: (group: string) => KeyOf<R>[];
69
+ };
70
+ type SettingsDefinition<R extends Registry> = ReturnType<typeof defineSettings<R>>;
71
+
72
+ /** A setting as an administration screen draws it: JSON-safe (no schema), so it can cross to the browser. */
73
+ interface SettingDescription<K extends string = string> {
74
+ key: K;
75
+ group: string;
76
+ kind: Kind;
77
+ default: unknown;
78
+ scopes: readonly Scope[];
79
+ min?: number;
80
+ max?: number;
81
+ unit?: string;
82
+ choices?: readonly string[];
83
+ }
84
+ declare const describeSettings: <R extends Registry>(settings: SettingsDefinition<R>) => SettingDescription<KeyOf<R>>[];
85
+
86
+ /**
87
+ * The tables of the settings: the overrides (global, for a workspace, for one user — the most specific wins) and the audit of every
88
+ * change (who, what, when, before, after). Idempotent, safe on a database that already has them.
89
+ */
90
+ declare function settingsMigration(): string;
91
+
92
+ /** What each scope has set for one key (absent = not overridden there). */
93
+ type Layers = Partial<Record<Scope, unknown>>;
94
+ interface Resolved<T = unknown> {
95
+ value: T;
96
+ /** Where the value comes from: the scope that set it, or `default`. */
97
+ source: Scope | "default";
98
+ }
99
+ /** The effective value: user, then workspace, then global, then the default. A scope the setting cannot be set at is never read. */
100
+ declare function resolveValue(def: Def, layers: Layers, fallback?: unknown): Resolved;
101
+
102
+ /** A SQL executor: the rows of a statement and its parameters (the product's pool). */
103
+ type Query = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;
104
+ interface ScopeRef {
105
+ scope: Scope;
106
+ /** The workspace or user the override belongs to; empty for the global scope. */
107
+ id: string;
108
+ }
109
+ declare const GLOBAL: ScopeRef;
110
+ interface Actor {
111
+ id: string | null;
112
+ label: string;
113
+ }
114
+ interface Context {
115
+ userId?: string | null;
116
+ /** A workspace named directly (an admin previewing it); else it is looked up from the user. */
117
+ workspaceId?: string | null;
118
+ }
119
+ interface AuditEntry {
120
+ id: number;
121
+ at: string;
122
+ actorLabel: string;
123
+ scope: Scope;
124
+ scopeId: string;
125
+ key: string;
126
+ before: unknown;
127
+ after: unknown;
128
+ }
129
+ declare class SettingsError extends Error {
130
+ readonly status: number;
131
+ readonly code: "UNKNOWN_SETTING" | "BAD_VALUE" | "BAD_SCOPE";
132
+ constructor(status: number, code: "UNKNOWN_SETTING" | "BAD_VALUE" | "BAD_SCOPE", message: string);
133
+ }
134
+ /** 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. */
135
+ interface SettingsService<R extends Registry> {
136
+ get<K extends KeyOf<R>>(key: K, context?: Context): Promise<ValueOf<R, K>>;
137
+ /** Every setting, resolved for a context, with where each value comes from. */
138
+ snapshot(context?: Context): Promise<Record<KeyOf<R>, Resolved>>;
139
+ /** What is overridden at one scope (the rest follows the scope above). */
140
+ overrides(scope: ScopeRef): Promise<Partial<Record<KeyOf<R>, unknown>>>;
141
+ set(actor: Actor, scope: ScopeRef, key: string, value: unknown, now: Date): Promise<void>;
142
+ /** Back to the default: removes the override at that scope. */
143
+ reset(actor: Actor, scope: ScopeRef, key: string, now: Date): Promise<void>;
144
+ history(options?: {
145
+ key?: string;
146
+ limit?: number;
147
+ }): Promise<AuditEntry[]>;
148
+ }
149
+ interface PostgresSettingsDeps<R extends Registry> {
150
+ query: Query;
151
+ /** The workspace a user belongs to (null while the product has no workspaces). */
152
+ workspaceOf?: (userId: string) => Promise<string | null>;
153
+ /** Defaults that depend on the deployment (a legacy environment switch): they replace the registry's default, never an override. */
154
+ defaults?: Partial<Record<KeyOf<R>, unknown>>;
155
+ /** How long a read is served from memory (other instances see a change within it; this one at once). */
156
+ cacheMs?: number;
157
+ /** A monotonic clock for the cache, in milliseconds (never the wall clock). */
158
+ clock?: () => number;
159
+ }
160
+ /** The adapter over the product's PostgreSQL (`app_settings`, `settings_audit`; see `settingsMigration`). */
161
+ declare function postgresSettings<R extends Registry>(settings: SettingsDefinition<R>, deps: PostgresSettingsDeps<R>): SettingsService<R>;
162
+
163
+ /**
164
+ * A deployment that was configured by environment before settings existed keeps behaving the same: at server start, each legacy value
165
+ * 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
166
+ * the administration owns it; the environment is never read again. `legacy` maps a setting key to its legacy value.
167
+ */
168
+ declare function seedLegacySettings<R extends Registry>(settings: SettingsDefinition<R>, service: SettingsService<R>, legacy: Partial<Record<KeyOf<R>, unknown>>, now: Date): Promise<KeyOf<R>[]>;
169
+
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 };
package/dist/index.js ADDED
@@ -0,0 +1,180 @@
1
+ // src/describe.ts
2
+ var describeSettings = (settings) => settings.keys.map((key) => {
3
+ const { group, kind, default: dflt, scopes, min, max, unit, choices } = settings.defOf(key);
4
+ return { key, group, kind, default: dflt, scopes, min, max, unit, choices };
5
+ });
6
+
7
+ // src/migration.ts
8
+ function settingsMigration() {
9
+ return `
10
+ CREATE TABLE IF NOT EXISTS app_settings (
11
+ scope text NOT NULL CHECK (scope IN ('global', 'workspace', 'user')),
12
+ scope_id text NOT NULL DEFAULT '',
13
+ key text NOT NULL CHECK (key ~ '^[a-zA-Z0-9.]{1,80}$'),
14
+ value jsonb NOT NULL,
15
+ updated_at timestamptz NOT NULL DEFAULT now(),
16
+ updated_by uuid,
17
+ PRIMARY KEY (scope, scope_id, key),
18
+ CHECK ((scope = 'global') = (scope_id = ''))
19
+ );
20
+ CREATE TABLE IF NOT EXISTS settings_audit (
21
+ id bigserial PRIMARY KEY,
22
+ at timestamptz NOT NULL DEFAULT now(),
23
+ actor_id uuid,
24
+ actor_label text NOT NULL,
25
+ scope text NOT NULL,
26
+ scope_id text NOT NULL DEFAULT '',
27
+ key text NOT NULL,
28
+ before jsonb,
29
+ after jsonb
30
+ );
31
+ CREATE INDEX IF NOT EXISTS settings_audit_key ON settings_audit(key, id DESC);
32
+ `;
33
+ }
34
+
35
+ // src/registry.ts
36
+ import { z } from "zod";
37
+ var SCOPE = { global: "global", workspace: "workspace", user: "user" };
38
+ var SCOPES_BY_SPECIFICITY = [SCOPE.user, SCOPE.workspace, SCOPE.global];
39
+ var KIND = { flag: "flag", integer: "integer", choice: "choice", bilingual: "bilingual", subset: "subset" };
40
+ var ALL_SCOPES = [SCOPE.global, SCOPE.workspace, SCOPE.user];
41
+ var WORKSPACE_SCOPES = [SCOPE.global, SCOPE.workspace];
42
+ var GLOBAL_ONLY = [SCOPE.global];
43
+ var flag = (group, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.flag, schema: z.boolean(), default: value, scopes });
44
+ var integer = (group, value, bounds, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.integer, schema: z.number().int().min(bounds.min).max(bounds.max), default: value, scopes, ...bounds });
45
+ var choice = (group, choices, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.choice, schema: z.enum(choices), default: value, scopes, choices });
46
+ var subset = (group, choices, value, scopes = GLOBAL_ONLY) => ({ group, kind: KIND.subset, schema: z.array(z.enum(choices)).min(1), default: value, scopes, choices });
47
+ var bilingual = (group, value, scopes = GLOBAL_ONLY) => ({ 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 });
48
+ function defineSettings(registry) {
49
+ const keys = Object.keys(registry);
50
+ const defOf = (key) => registry[key];
51
+ return {
52
+ registry,
53
+ keys,
54
+ isKey: (key) => Object.hasOwn(registry, key),
55
+ defOf,
56
+ keysOfGroup: (group) => keys.filter((k) => defOf(k).group === group)
57
+ };
58
+ }
59
+
60
+ // src/resolve.ts
61
+ function resolveValue(def, layers, fallback) {
62
+ for (const scope of SCOPES_BY_SPECIFICITY) {
63
+ if (def.scopes.includes(scope) && layers[scope] !== void 0) return { value: layers[scope], source: scope };
64
+ }
65
+ return { value: fallback !== void 0 ? fallback : def.default, source: "default" };
66
+ }
67
+
68
+ // src/service.ts
69
+ var GLOBAL = { scope: SCOPE.global, id: "" };
70
+ var SettingsError = class extends Error {
71
+ constructor(status, code, message) {
72
+ super(message);
73
+ this.status = status;
74
+ this.code = code;
75
+ this.name = "SettingsError";
76
+ }
77
+ status;
78
+ code;
79
+ };
80
+ var cacheKey = (s) => `${s.scope}:${s.id}`;
81
+ function postgresSettings(settings, deps) {
82
+ const { query } = deps;
83
+ const cacheMs = deps.cacheMs ?? 5e3;
84
+ const clock = deps.clock ?? (() => 0);
85
+ const cache = /* @__PURE__ */ new Map();
86
+ async function load(scope) {
87
+ const hit = cache.get(cacheKey(scope));
88
+ if (hit && clock() - hit.at < cacheMs) return hit.values;
89
+ const rows = await query("SELECT key, value FROM app_settings WHERE scope = $1 AND scope_id = $2", [scope.scope, scope.id]);
90
+ const values = {};
91
+ const into = values;
92
+ for (const r of rows) if (settings.isKey(r.key)) into[r.key] = r.value;
93
+ cache.set(cacheKey(scope), { at: clock(), values });
94
+ return values;
95
+ }
96
+ async function layersFor(context) {
97
+ const workspaceId = context.workspaceId ?? (context.userId && deps.workspaceOf ? await deps.workspaceOf(context.userId) : null);
98
+ 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)]);
99
+ return { user, workspace, global };
100
+ }
101
+ function validate(scope, key, value) {
102
+ if (!settings.isKey(key)) throw new SettingsError(404, "UNKNOWN_SETTING", `No such setting: ${key}`);
103
+ const def = settings.defOf(key);
104
+ if (!def.scopes.includes(scope.scope)) throw new SettingsError(400, "BAD_SCOPE", `${key} cannot be set at the ${scope.scope} level`);
105
+ if (scope.scope !== SCOPE.global && !scope.id) throw new SettingsError(400, "BAD_SCOPE", "A workspace or a user is required");
106
+ if (value !== void 0 && !def.schema.safeParse(value).success) throw new SettingsError(400, "BAD_VALUE", `Not a valid value for ${key}`);
107
+ return key;
108
+ }
109
+ const record = (actor, scope, key, before, after, now) => 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)]);
110
+ const layersOf = (layers, key) => ({ user: layers.user[key], workspace: layers.workspace[key], global: layers.global[key] });
111
+ return {
112
+ async get(key, context = {}) {
113
+ return resolveValue(settings.defOf(key), layersOf(await layersFor(context), key), deps.defaults?.[key]).value;
114
+ },
115
+ async snapshot(context = {}) {
116
+ const layers = await layersFor(context);
117
+ return Object.fromEntries(settings.keys.map((k) => [k, resolveValue(settings.defOf(k), layersOf(layers, k), deps.defaults?.[k])]));
118
+ },
119
+ overrides: (scope) => load(scope),
120
+ async set(actor, scope, key, value, now) {
121
+ const k = validate(scope, key, value ?? null);
122
+ const parsed = settings.defOf(k).schema.parse(value);
123
+ const before = (await query("SELECT value FROM app_settings WHERE scope = $1 AND scope_id = $2 AND key = $3", [scope.scope, scope.id, k]))[0]?.value;
124
+ await query(
125
+ `INSERT INTO app_settings (scope, scope_id, key, value, updated_at, updated_by) VALUES ($1, $2, $3, $4, $5, $6)
126
+ ON CONFLICT (scope, scope_id, key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
127
+ [scope.scope, scope.id, k, JSON.stringify(parsed), now, actor.id]
128
+ );
129
+ await record(actor, scope, k, before, parsed, now);
130
+ cache.clear();
131
+ },
132
+ async reset(actor, scope, key, now) {
133
+ const k = validate(scope, key);
134
+ const rows = await query("DELETE FROM app_settings WHERE scope = $1 AND scope_id = $2 AND key = $3 RETURNING value", [scope.scope, scope.id, k]);
135
+ if (rows.length) await record(actor, scope, k, rows[0].value, null, now);
136
+ cache.clear();
137
+ },
138
+ async history({ key, limit = 100 } = {}) {
139
+ const rows = await query(
140
+ "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",
141
+ [key ?? null, limit]
142
+ );
143
+ 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 }));
144
+ }
145
+ };
146
+ }
147
+
148
+ // src/seed.ts
149
+ async function seedLegacySettings(settings, service, legacy, now) {
150
+ const seeded = [];
151
+ const existing = await service.overrides(GLOBAL);
152
+ for (const key of Object.keys(legacy)) {
153
+ if (existing[key] !== void 0 || legacy[key] === settings.defOf(key).default) continue;
154
+ await service.set({ id: null, label: "server start (legacy environment)" }, { scope: SCOPE.global, id: "" }, key, legacy[key], now);
155
+ seeded.push(key);
156
+ }
157
+ return seeded;
158
+ }
159
+ export {
160
+ ALL_SCOPES,
161
+ GLOBAL,
162
+ GLOBAL_ONLY,
163
+ KIND,
164
+ SCOPE,
165
+ SCOPES_BY_SPECIFICITY,
166
+ SettingsError,
167
+ WORKSPACE_SCOPES,
168
+ bilingual,
169
+ choice,
170
+ defineSettings,
171
+ describeSettings,
172
+ flag,
173
+ integer,
174
+ postgresSettings,
175
+ resolveValue,
176
+ seedLegacySettings,
177
+ settingsMigration,
178
+ subset
179
+ };
180
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,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;A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,QAAQ,IAAI,GAAG,GAAG,KAAK,OAAO,GAAG,GAAG,GAAG;AAClI,WAAO,KAAK,GAAG;AAAA,EACjB;AACA,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@krizaka/settings",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.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.",
5
+ "keywords": [
6
+ "krizaka",
7
+ "settings",
8
+ "feature-flags",
9
+ "configuration",
10
+ "audit"
11
+ ],
12
+ "homepage": "https://github.com/krizaka/krizaka-ts/tree/main/packages/settings",
13
+ "bugs": "https://github.com/krizaka/krizaka-ts/issues",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/krizaka/krizaka-ts.git",
17
+ "directory": "packages/settings"
18
+ },
19
+ "license": "Apache-2.0",
20
+ "author": "Krizaka (https://www.krizaka.com)",
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "sideEffects": false,
38
+ "engines": {
39
+ "node": ">=22"
40
+ },
41
+ "dependencies": {},
42
+ "devDependencies": {
43
+ "@krizaka/config": "^0.7.0",
44
+ "@types/node": "^22.10.0",
45
+ "@types/pg": "^8.23.1",
46
+ "eslint": "^9.39.0",
47
+ "pg": "^8.23.1",
48
+ "tsup": "^8.5.0",
49
+ "typescript": "^5.9.3",
50
+ "vitest": "^4.1.11",
51
+ "zod": "^4.6.7"
52
+ },
53
+ "peerDependencies": {
54
+ "zod": ">=3.23"
55
+ },
56
+ "scripts": {
57
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsup",
58
+ "lint": "eslint . --max-warnings 0 && tsc --noEmit",
59
+ "typecheck": "tsc --noEmit",
60
+ "test": "vitest run",
61
+ "check": "pnpm run lint && pnpm run test && pnpm run build"
62
+ }
6
63
  }