@murumets-ee/settings 0.1.5 → 0.2.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/dist/admin.d.mts +72 -0
- package/dist/admin.d.mts.map +1 -0
- package/dist/admin.mjs +2 -0
- package/dist/admin.mjs.map +1 -0
- package/dist/client-factory-f4nNDWaD.mjs +2 -0
- package/dist/client-factory-f4nNDWaD.mjs.map +1 -0
- package/dist/index.d.mts +224 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -0
- package/dist/plugin.d.mts +7 -0
- package/dist/plugin.d.mts.map +1 -0
- package/dist/plugin.mjs +2 -0
- package/dist/plugin.mjs.map +1 -0
- package/dist/schema.d.mts +318 -0
- package/dist/schema.d.mts.map +1 -0
- package/dist/schema.mjs +2 -0
- package/dist/schema.mjs.map +1 -0
- package/dist/view-state.d.mts +48 -0
- package/dist/view-state.d.mts.map +1 -0
- package/dist/view-state.mjs +2 -0
- package/dist/view-state.mjs.map +1 -0
- package/package.json +17 -17
- package/dist/admin.d.ts +0 -100
- package/dist/admin.js +0 -1
- package/dist/chunk-E3K4GXDC.js +0 -1
- package/dist/client-factory-OGWK5MKO.js +0 -1
- package/dist/index.d.ts +0 -291
- package/dist/index.js +0 -1
- package/dist/plugin.d.ts +0 -22
- package/dist/plugin.js +0 -24
- package/dist/schema.d.ts +0 -316
- package/dist/schema.js +0 -1
- package/dist/view-state.d.ts +0 -68
- package/dist/view-state.js +0 -1
package/dist/admin.d.mts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { AdminRoute } from "@murumets-ee/core";
|
|
2
|
+
import { ZodType } from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/types.d.ts
|
|
5
|
+
interface BaseSettingConfig {
|
|
6
|
+
/** Human-readable label for admin UI */
|
|
7
|
+
label?: string;
|
|
8
|
+
/** Description / help text */
|
|
9
|
+
description?: string;
|
|
10
|
+
/** If true, this setting can have per-locale values (mirrors entity translatable pattern) */
|
|
11
|
+
translatable?: boolean;
|
|
12
|
+
}
|
|
13
|
+
interface TextSettingConfig extends BaseSettingConfig {
|
|
14
|
+
type: 'text';
|
|
15
|
+
default?: string;
|
|
16
|
+
maxLength?: number;
|
|
17
|
+
minLength?: number;
|
|
18
|
+
pattern?: RegExp;
|
|
19
|
+
}
|
|
20
|
+
interface NumberSettingConfig extends BaseSettingConfig {
|
|
21
|
+
type: 'number';
|
|
22
|
+
default?: number;
|
|
23
|
+
min?: number;
|
|
24
|
+
max?: number;
|
|
25
|
+
integer?: boolean;
|
|
26
|
+
}
|
|
27
|
+
interface BooleanSettingConfig extends BaseSettingConfig {
|
|
28
|
+
type: 'boolean';
|
|
29
|
+
default?: boolean;
|
|
30
|
+
}
|
|
31
|
+
interface SelectSettingConfig<O extends readonly string[] = readonly string[]> extends BaseSettingConfig {
|
|
32
|
+
type: 'select';
|
|
33
|
+
options: O;
|
|
34
|
+
default?: O[number];
|
|
35
|
+
}
|
|
36
|
+
interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {
|
|
37
|
+
type: 'json';
|
|
38
|
+
default?: T;
|
|
39
|
+
/** Optional Zod schema for validation. If provided, values are validated on set. */
|
|
40
|
+
schema?: ZodType<T>;
|
|
41
|
+
}
|
|
42
|
+
interface MediaSettingConfig extends BaseSettingConfig {
|
|
43
|
+
type: 'media';
|
|
44
|
+
accept?: string[];
|
|
45
|
+
}
|
|
46
|
+
type SettingConfig = TextSettingConfig | NumberSettingConfig | BooleanSettingConfig | SelectSettingConfig | JsonSettingConfig | MediaSettingConfig;
|
|
47
|
+
type SettingScope = 'global' | 'team' | 'user';
|
|
48
|
+
interface SettingsDefinition<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {
|
|
49
|
+
/** Unique namespace for this settings group */
|
|
50
|
+
namespace: string;
|
|
51
|
+
/** Default scope for these settings */
|
|
52
|
+
scope: SettingScope;
|
|
53
|
+
/** Setting schema (the shape) */
|
|
54
|
+
schema: S;
|
|
55
|
+
/** Human-readable label for admin UI */
|
|
56
|
+
label?: string;
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
59
|
+
//#region src/admin/routes.d.ts
|
|
60
|
+
/**
|
|
61
|
+
* Create admin API routes for settings management.
|
|
62
|
+
*
|
|
63
|
+
* Routes:
|
|
64
|
+
* - `GET /api/admin/settings` — Get all settings (query: `?locale=`)
|
|
65
|
+
* - `PATCH /api/admin/settings` — Update settings (JSON body: `{ values, locale? }`)
|
|
66
|
+
*
|
|
67
|
+
* @param definition - The settings definition (created by defineSettings)
|
|
68
|
+
*/
|
|
69
|
+
declare function settingsRoutes<S extends Record<string, SettingConfig>>(definition: SettingsDefinition<S>): AdminRoute;
|
|
70
|
+
//#endregion
|
|
71
|
+
export { settingsRoutes };
|
|
72
|
+
//# sourceMappingURL=admin.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admin.d.mts","names":[],"sources":["../src/types.ts","../src/admin/routes.ts"],"mappings":";;;;UAgBiB,iBAAA;EAMH;EAJZ,KAAA;EAOe;EALf,WAAA;;EAEA,YAAA;AAAA;AAAA,UAGe,iBAAA,SAA0B,iBAAA;EACzC,IAAA;EACA,OAAA;EACA,SAAA;EACA,SAAA;EACA,OAAA,GAAU,MAAA;AAAA;AAAA,UAGK,mBAAA,SAA4B,iBAAA;EAC3C,IAAA;EACA,OAAA;EACA,GAAA;EACA,GAAA;EACA,OAAA;AAAA;AAAA,UAGe,oBAAA,SAA6B,iBAAA;EAC5C,IAAA;EACA,OAAA;AAAA;AAAA,UAGe,mBAAA,0DACP,iBAAA;EACR,IAAA;EACA,OAAA,EAAS,CAAA;EACT,OAAA,GAAU,CAAA;AAAA;AAAA,UAGK,iBAAA,sBAAuC,iBAAA;EACtD,IAAA;EACA,OAAA,GAAU,CAAA;EAZV;EAcA,MAAA,GAAS,OAAA,CAAQ,CAAA;AAAA;AAAA,UAGF,kBAAA,SAA2B,iBAAA;EAC1C,IAAA;EACA,MAAA;AAAA;AAAA,KAGU,aAAA,GACR,iBAAA,GACA,mBAAA,GACA,oBAAA,GACA,mBAAA,GACA,iBAAA,GACA,kBAAA;AAAA,KAgDQ,YAAA;AAAA,UAYK,kBAAA,WACL,MAAA,SAAe,aAAA,IAAiB,MAAA,SAAe,aAAA;EA/ExB;EAkFjC,SAAA;EAjFA;EAmFA,KAAA,EAAO,YAAA;EAlFG;EAoFV,MAAA,EAAQ,CAAA;EAlFC;EAoFT,KAAA;AAAA;;;;;;;AA5GF;;;;;iBCoBgB,cAAA,WAAyB,MAAA,SAAe,aAAA,EAAA,CACtD,UAAA,EAAY,kBAAA,CAAmB,CAAA,IAC9B,UAAA"}
|
package/dist/admin.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function t(t,n){return e({error:t},n)}function n(n){let r=null;function i(){return r||=(async()=>{let{getApp:e}=await import(`@murumets-ee/core`),{createSettingsClient:t}=await import(`./client-factory-f4nNDWaD.mjs`);return t(n,{app:e()})})(),r}async function a(t,n){let r=await i(),a=new URL(t.url).searchParams.get(`locale`)??void 0;return e(await r.getAll(a?{locale:a}:void 0))}async function o(r,{user:a,audit:o}){let s=await i(),{values:c,locale:l}=await r.json();return!c||typeof c!=`object`?t(`Body must contain "values" object`,400):(await s.setMany(c,l?{locale:l}:void 0),o?.({action:`settings.update`,entityType:`settings`,userId:a.id,userName:a.name,changes:{fields:c},metadata:{namespace:n.namespace,...l?{locale:l}:{}}}),e({success:!0}))}return{prefix:`settings`,resource:`settings`,actions:[`view`,`update`],handlers:{GET:a,PATCH:o}}}export{n as settingsRoutes};
|
|
2
|
+
//# sourceMappingURL=admin.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admin.mjs","names":[],"sources":["../src/admin/routes.ts"],"sourcesContent":["/**\n * Settings admin routes for the centralized admin API handler.\n *\n * Provides get/update operations for typed settings.\n * All auth, CSRF, and role checks are handled by the parent handler.\n * Settings mutations require admin role (not editor).\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { settingsRoutes } from '@murumets-ee/settings/admin'\n * import { siteSettings } from '@/settings/site'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [Article],\n * routes: [settingsRoutes(siteSettings)],\n * })\n * ```\n */\n\nimport type { AdminRoute, AuditLogFn, AuthUser } from '@murumets-ee/core'\nimport type { SettingsClient } from '../client.js'\nimport type { SettingConfig, SettingsDefinition } from '../types.js'\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction json(data: unknown, status = 200) {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction errorJson(message: string, status: number) {\n return json({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create admin API routes for settings management.\n *\n * Routes:\n * - `GET /api/admin/settings` — Get all settings (query: `?locale=`)\n * - `PATCH /api/admin/settings` — Update settings (JSON body: `{ values, locale? }`)\n *\n * @param definition - The settings definition (created by defineSettings)\n */\nexport function settingsRoutes<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n): AdminRoute {\n let clientPromise: Promise<SettingsClient<S>> | null = null\n\n function getClient(): Promise<SettingsClient<S>> {\n if (!clientPromise) {\n clientPromise = (async () => {\n const { getApp } = await import('@murumets-ee/core')\n const { createSettingsClient } = await import('../client-factory.js')\n\n const app = getApp()\n return createSettingsClient(definition, { app })\n })()\n }\n return clientPromise\n }\n\n async function handleGet(\n req: Request,\n _ctx: { segments: string[]; user: AuthUser; audit?: AuditLogFn },\n ): Promise<Response> {\n const client = await getClient()\n const url = new URL(req.url)\n const locale = url.searchParams.get('locale') ?? undefined\n const values = await client.getAll(locale ? { locale } : undefined)\n return json(values)\n }\n\n async function handlePatch(\n req: Request,\n { user, audit }: { segments: string[]; user: AuthUser; audit?: AuditLogFn },\n ): Promise<Response> {\n const client = await getClient()\n const body = await req.json()\n\n const { values, locale } = body as { values: Record<string, unknown>; locale?: string }\n if (!values || typeof values !== 'object') {\n return errorJson('Body must contain \"values\" object', 400)\n }\n\n await client.setMany(\n values as Parameters<typeof client.setMany>[0],\n locale ? { locale } : undefined,\n )\n\n audit?.({\n action: 'settings.update',\n entityType: 'settings',\n userId: user.id,\n userName: user.name,\n changes: { fields: values },\n metadata: {\n namespace: definition.namespace,\n ...(locale ? { locale } : {}),\n },\n })\n\n return json({ success: true })\n }\n\n return {\n prefix: 'settings',\n resource: 'settings',\n actions: ['view', 'update'],\n handlers: {\n GET: handleGet,\n PATCH: handlePatch,\n },\n }\n}\n"],"mappings":"AA6BA,SAAS,EAAK,EAAe,EAAS,IAAK,CACzC,OAAO,IAAI,SAAS,KAAK,UAAU,EAAK,CAAE,CACxC,SACA,QAAS,CAAE,eAAgB,mBAAoB,CAChD,CAAC,CAGJ,SAAS,EAAU,EAAiB,EAAgB,CAClD,OAAO,EAAK,CAAE,MAAO,EAAS,CAAE,EAAO,CAgBzC,SAAgB,EACd,EACY,CACZ,IAAI,EAAmD,KAEvD,SAAS,GAAwC,CAU/C,MATA,CACE,KAAiB,SAAY,CAC3B,GAAM,CAAE,UAAW,MAAM,OAAO,qBAC1B,CAAE,wBAAyB,MAAM,OAAO,iCAG9C,OAAO,EAAqB,EAAY,CAAE,IAD9B,GAAQ,CAC2B,CAAC,IAC9C,CAEC,EAGT,eAAe,EACb,EACA,EACmB,CACnB,IAAM,EAAS,MAAM,GAAW,CAE1B,EADM,IAAI,IAAI,EAAI,IAAI,CACT,aAAa,IAAI,SAAS,EAAI,IAAA,GAEjD,OAAO,EADQ,MAAM,EAAO,OAAO,EAAS,CAAE,SAAQ,CAAG,IAAA,GAAU,CAChD,CAGrB,eAAe,EACb,EACA,CAAE,OAAM,SACW,CACnB,IAAM,EAAS,MAAM,GAAW,CAG1B,CAAE,SAAQ,UAFH,MAAM,EAAI,MAAM,CAwB7B,MArBI,CAAC,GAAU,OAAO,GAAW,SACxB,EAAU,oCAAqC,IAAI,EAG5D,MAAM,EAAO,QACX,EACA,EAAS,CAAE,SAAQ,CAAG,IAAA,GACvB,CAED,IAAQ,CACN,OAAQ,kBACR,WAAY,WACZ,OAAQ,EAAK,GACb,SAAU,EAAK,KACf,QAAS,CAAE,OAAQ,EAAQ,CAC3B,SAAU,CACR,UAAW,EAAW,UACtB,GAAI,EAAS,CAAE,SAAQ,CAAG,EAAE,CAC7B,CACF,CAAC,CAEK,EAAK,CAAE,QAAS,GAAM,CAAC,EAGhC,MAAO,CACL,OAAQ,WACR,SAAU,WACV,QAAS,CAAC,OAAQ,SAAS,CAC3B,SAAU,CACR,IAAK,EACL,MAAO,EACR,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{getApp as e}from"@murumets-ee/core";import{and as t,eq as n,or as r}from"drizzle-orm";import{jsonb as i,pgTable as a,timestamp as o,unique as s,uuid as c,varchar as l}from"drizzle-orm/pg-core";import{z as u}from"zod";const d=a(`toolkit_settings`,{id:c(`id`).primaryKey().defaultRandom(),namespace:l(`namespace`,{length:100}).notNull(),scope:l(`scope`,{length:20}).notNull().default(`global`),scopeId:l(`scope_id`,{length:100}).notNull().default(`__global__`),key:l(`key`,{length:255}).notNull(),locale:l(`locale`,{length:10}).notNull().default(`_default`),value:i(`value`),updatedAt:o(`updated_at`,{withTimezone:!0}).notNull().defaultNow(),updatedBy:c(`updated_by`)},e=>({uniqueSetting:s().on(e.namespace,e.scope,e.scopeId,e.key,e.locale)}));a(`toolkit_view_state`,{id:c(`id`).primaryKey().defaultRandom(),userId:c(`user_id`).notNull(),viewKey:l(`view_key`,{length:255}).notNull(),state:i(`state`).notNull(),expiresAt:o(`expires_at`,{withTimezone:!0}),updatedAt:o(`updated_at`,{withTimezone:!0}).notNull().defaultNow()},e=>({uniqueUserView:s().on(e.userId,e.viewKey)}));const f=`_default`;function p(e){switch(e.type){case`text`:{let t=u.string();return e.maxLength&&(t=t.max(e.maxLength)),e.minLength&&(t=t.min(e.minLength)),e.pattern&&(t=t.regex(e.pattern)),t}case`number`:{let t=u.number();return e.integer&&(t=t.int()),e.min!==void 0&&(t=t.min(e.min)),e.max!==void 0&&(t=t.max(e.max)),t}case`boolean`:return u.boolean();case`select`:return u.enum(e.options);case`json`:return e.schema??u.unknown();case`media`:return u.string().uuid();default:return u.unknown()}}function m(e){let t={};for(let[n,r]of Object.entries(e.schema)){let e=p(r);`default`in r&&r.default!==void 0||(e=e.nullable()),t[n]=e}return t}var h=class{definition;db;logger;scope;scopeId;validators;constructor(e,t){if(typeof window<`u`)throw Error(`SettingsClient cannot be used in browser code.`);if(this.definition=e,this.db=t.db,this.logger=t.logger,this.scope=t.scope??e.scope,this.scopeId=t.scopeId??`__global__`,(this.scope===`team`||this.scope===`user`)&&!t.scopeId)throw Error(`scopeId is required for ${this.scope}-scoped settings (namespace: ${e.namespace})`);this.validators=m(e)}async get(e,i){let a=this.definition.schema[e],o=a?.translatable&&i?.locale?i.locale:null;if(this.logger?.debug({namespace:this.definition.namespace,key:e,locale:o},`Getting setting`),o){let i=await this.db.select({locale:d.locale,value:d.value}).from(d).where(t(...this.baseWhere(),n(d.key,e),r(n(d.locale,o),n(d.locale,f)))),a=i.find(e=>e.locale===o),s=i.find(e=>e.locale===f),c=a??s;if(c&&c.value!==void 0&&c.value!==null)return c.value}else{let t=await this.db.select({value:d.value}).from(d).where(this.whereClause(e)).limit(1);if(t.length>0&&t[0].value!==void 0&&t[0].value!==null)return t[0].value}return a&&`default`in a&&a.default!==void 0?a.default:null}async getAll(e){let i=e?.locale??null;this.logger?.debug({namespace:this.definition.namespace,locale:i},`Getting all settings`);let a;a=i?await this.db.select({key:d.key,locale:d.locale,value:d.value}).from(d).where(t(...this.baseWhere(),r(n(d.locale,f),n(d.locale,i)))):await this.db.select({key:d.key,locale:d.locale,value:d.value}).from(d).where(t(...this.baseWhere(),n(d.locale,f)));let o=new Map;for(let e of a){let t=o.get(e.key)??{};e.locale===`_default`?t.default=e.value:t.locale=e.value,o.set(e.key,t)}let s={};for(let[e,t]of Object.entries(this.definition.schema)){let n=o.get(e),r;t.translatable&&i&&n?.locale!==void 0&&n?.locale!==null?r=n.locale:n?.default!==void 0&&n?.default!==null&&(r=n.default),r===void 0?`default`in t&&t.default!==void 0?s[e]=t.default:s[e]=null:s[e]=r}return s}async set(e,t,n){let r=this.resolveLocale(e,n);if(this.logger?.info({namespace:this.definition.namespace,key:e,locale:r},`Setting value`),!(e in this.definition.schema))throw Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let i=this.validators[e];i&&i.parse(t),await this.upsert(e,t,r)}async setMany(e,t){this.logger?.info({namespace:this.definition.namespace,keys:Object.keys(e),locale:t?.locale},`Setting multiple values`);for(let[t,n]of Object.entries(e)){if(!(t in this.definition.schema))throw Error(`Unknown setting key '${t}' in namespace '${this.definition.namespace}'`);let e=this.validators[t];e&&n!==void 0&&e.parse(n)}await this.db.transaction(async n=>{for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let e=this.resolveLocale(r,t);await n.insert(d).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:r,locale:e,value:i,updatedAt:new Date}).onConflictDoUpdate({target:[d.namespace,d.scope,d.scopeId,d.key,d.locale],set:{value:i,updatedAt:new Date}})}})}async delete(e,t){let n=this.resolveLocale(e,t);this.logger?.info({namespace:this.definition.namespace,key:e,locale:n},`Deleting setting`),await this.db.delete(d).where(this.whereClause(e,n))}async has(e,t){let n=this.resolveLocale(e,t);return(await this.db.select({key:d.key}).from(d).where(this.whereClause(e,n)).limit(1)).length>0}resolveLocale(e,t){return this.definition.schema[e]?.translatable&&t?.locale?t.locale:f}baseWhere(){return[n(d.namespace,this.definition.namespace),n(d.scope,this.scope),n(d.scopeId,this.scopeId)]}whereClause(e,r=f){return t(...this.baseWhere(),n(d.key,e),n(d.locale,r))}async upsert(e,t,n){await this.db.insert(d).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:e,locale:n,value:t,updatedAt:new Date}).onConflictDoUpdate({target:[d.namespace,d.scope,d.scopeId,d.key,d.locale],set:{value:t,updatedAt:new Date}})}};function g(t,n){let r=n?.app??e();return new h(t,{db:r.db.readWrite,logger:r.logger.child({settings:t.namespace}),scope:n?.scope,scopeId:n?.scopeId})}export{g as createSettingsClient};
|
|
2
|
+
//# sourceMappingURL=client-factory-f4nNDWaD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-factory-f4nNDWaD.mjs","names":[],"sources":["../src/schema.ts","../src/types.ts","../src/validation.ts","../src/client.ts","../src/client-factory.ts"],"sourcesContent":["/**\n * Drizzle schema for settings tables.\n *\n * Two tables:\n * - toolkit_settings: typed key-value settings grouped by namespace and scope\n * - toolkit_view_state: schemaless user-scoped JSON blobs with optional TTL\n *\n * Usage in drizzle.config.ts:\n * ```typescript\n * import type { Config } from 'drizzle-kit'\n * export default {\n * schema: ['./generated/schema.ts', '@murumets-ee/settings/schema'],\n * // ...\n * } satisfies Config\n * ```\n */\n\nimport { jsonb, pgTable, timestamp, unique, uuid, varchar } from 'drizzle-orm/pg-core'\n\n/**\n * Typed settings table.\n *\n * Stores key-value pairs grouped by namespace and scoped\n * to global, team, or user contexts.\n *\n * scopeId uses '__global__' sentinel for global scope to avoid\n * PostgreSQL's NULL != NULL behavior in unique constraints.\n */\nexport const toolkitSettings = pgTable(\n 'toolkit_settings',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n namespace: varchar('namespace', { length: 100 }).notNull(),\n scope: varchar('scope', { length: 20 }).notNull().default('global'),\n scopeId: varchar('scope_id', { length: 100 }).notNull().default('__global__'),\n key: varchar('key', { length: 255 }).notNull(),\n locale: varchar('locale', { length: 10 }).notNull().default('_default'),\n value: jsonb('value'),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n updatedBy: uuid('updated_by'),\n },\n (table) => ({\n uniqueSetting: unique().on(\n table.namespace,\n table.scope,\n table.scopeId,\n table.key,\n table.locale,\n ),\n }),\n)\n\n/**\n * View state table.\n *\n * Stores schemaless user-scoped JSON blobs for persisting\n * UI state (table filters, column order, etc.) with optional TTL.\n */\nexport const toolkitViewState = pgTable(\n 'toolkit_view_state',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n userId: uuid('user_id').notNull(),\n viewKey: varchar('view_key', { length: 255 }).notNull(),\n state: jsonb('state').notNull(),\n expiresAt: timestamp('expires_at', { withTimezone: true }),\n updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),\n },\n (table) => ({\n uniqueUserView: unique().on(table.userId, table.viewKey),\n }),\n)\n","/**\n * Setting configuration types and compile-time type inference.\n *\n * Design mirrors the entity field system:\n * - Config interfaces define what each setting type accepts\n * - SettingToTS maps a single config to its TypeScript type\n * - InferSettingValue adds null awareness based on `default` presence\n * - InferSettingsMap maps an entire schema to a typed record\n */\n\nimport type { ZodType } from 'zod'\n\n// ---------------------------------------------------------------\n// 1. Setting config interfaces\n// ---------------------------------------------------------------\n\nexport interface BaseSettingConfig {\n /** Human-readable label for admin UI */\n label?: string\n /** Description / help text */\n description?: string\n /** If true, this setting can have per-locale values (mirrors entity translatable pattern) */\n translatable?: boolean\n}\n\nexport interface TextSettingConfig extends BaseSettingConfig {\n type: 'text'\n default?: string\n maxLength?: number\n minLength?: number\n pattern?: RegExp\n}\n\nexport interface NumberSettingConfig extends BaseSettingConfig {\n type: 'number'\n default?: number\n min?: number\n max?: number\n integer?: boolean\n}\n\nexport interface BooleanSettingConfig extends BaseSettingConfig {\n type: 'boolean'\n default?: boolean\n}\n\nexport interface SelectSettingConfig<O extends readonly string[] = readonly string[]>\n extends BaseSettingConfig {\n type: 'select'\n options: O\n default?: O[number]\n}\n\nexport interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {\n type: 'json'\n default?: T\n /** Optional Zod schema for validation. If provided, values are validated on set. */\n schema?: ZodType<T>\n}\n\nexport interface MediaSettingConfig extends BaseSettingConfig {\n type: 'media'\n accept?: string[]\n}\n\nexport type SettingConfig =\n | TextSettingConfig\n | NumberSettingConfig\n | BooleanSettingConfig\n | SelectSettingConfig\n | JsonSettingConfig\n | MediaSettingConfig\n\n// ---------------------------------------------------------------\n// 2. Setting-to-TypeScript mapping (single setting)\n// ---------------------------------------------------------------\n\n/**\n * Maps a single SettingConfig to its TypeScript output type.\n * Each branch is a shallow comparison — no recursion.\n */\nexport type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig\n ? string\n : S extends NumberSettingConfig\n ? number\n : S extends BooleanSettingConfig\n ? boolean\n : S extends SelectSettingConfig<infer O>\n ? O[number]\n : S extends JsonSettingConfig<infer T>\n ? T\n : S extends MediaSettingConfig\n ? string\n : never\n\n// ---------------------------------------------------------------\n// 3. Null awareness: settings with defaults always return value\n// ---------------------------------------------------------------\n\n/**\n * If a setting has a `default`, get() never returns null.\n * Without a default, it returns T | null.\n */\nexport type InferSettingValue<S extends SettingConfig> = S extends { default: unknown }\n ? SettingToTS<S>\n : SettingToTS<S> | null\n\n// ---------------------------------------------------------------\n// 4. Full settings map type (what getAll() returns)\n// ---------------------------------------------------------------\n\nexport type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {\n [K in keyof Schema]: InferSettingValue<Schema[K]>\n}\n\n// ---------------------------------------------------------------\n// 5. Scope types\n// ---------------------------------------------------------------\n\nexport type SettingScope = 'global' | 'team' | 'user'\n\n/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */\nexport const GLOBAL_SCOPE_ID = '__global__'\n\n/** Sentinel value for locale column when no locale is specified (base/default value) */\nexport const DEFAULT_LOCALE = '_default'\n\n// ---------------------------------------------------------------\n// 6. Settings definition (returned by defineSettings)\n// ---------------------------------------------------------------\n\nexport interface SettingsDefinition<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n /** Unique namespace for this settings group */\n namespace: string\n /** Default scope for these settings */\n scope: SettingScope\n /** Setting schema (the shape) */\n schema: S\n /** Human-readable label for admin UI */\n label?: string\n}\n","/**\n * Generate Zod validation schemas from setting config definitions.\n * Validates values before writing to the database.\n */\n\nimport { z } from 'zod'\nimport type { SettingConfig, SettingsDefinition } from './types.js'\n\n/**\n * Convert a single setting config to a Zod schema.\n */\nexport function settingToZod(config: SettingConfig): z.ZodType {\n switch (config.type) {\n case 'text': {\n let schema: z.ZodString = z.string()\n if (config.maxLength) schema = schema.max(config.maxLength)\n if (config.minLength) schema = schema.min(config.minLength)\n if (config.pattern) schema = schema.regex(config.pattern)\n return schema\n }\n\n case 'number': {\n let schema: z.ZodNumber = z.number()\n if (config.integer) schema = schema.int()\n if (config.min !== undefined) schema = schema.min(config.min)\n if (config.max !== undefined) schema = schema.max(config.max)\n return schema\n }\n\n case 'boolean':\n return z.boolean()\n\n case 'select':\n return z.enum(config.options as [string, ...string[]])\n\n case 'json':\n return config.schema ?? z.unknown()\n\n case 'media':\n return z.string().uuid()\n\n default:\n return z.unknown()\n }\n}\n\n/**\n * Generate a validation map for all settings in a definition.\n * Returns a Record<key, ZodType> for validating individual set() calls.\n *\n * Settings without a default are nullable (matching InferSettingValue),\n * so their validators accept null.\n */\nexport function generateSettingValidators(\n definition: SettingsDefinition,\n): Record<string, z.ZodType> {\n const validators: Record<string, z.ZodType> = {}\n for (const [key, config] of Object.entries(definition.schema)) {\n let schema = settingToZod(config)\n const hasDefault = 'default' in config && config.default !== undefined\n if (!hasDefault) {\n schema = schema.nullable()\n }\n validators[key] = schema\n }\n return validators\n}\n","/**\n * SettingsClient — typed CRUD for key-value settings.\n *\n * Server-only. Uses read-write DB connection.\n * Validates values against the setting schema on set().\n *\n * Supports per-locale values for settings marked `translatable: true`.\n * Non-translatable settings always use the `__default__` locale.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n *\n * // Default locale\n * const name = await settings.get('siteName') // string (has default)\n *\n * // Locale-specific (only for translatable settings)\n * const nameEt = await settings.get('siteName', { locale: 'et' })\n *\n * await settings.set('siteName', 'Mänguväljak', { locale: 'et' })\n * ```\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { and, eq, or } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettings } from './schema.js'\nimport type {\n InferSettingsMap,\n InferSettingValue,\n SettingConfig,\n SettingScope,\n SettingsDefinition,\n} from './types.js'\nimport { DEFAULT_LOCALE, GLOBAL_SCOPE_ID } from './types.js'\nimport { generateSettingValidators } from './validation.js'\n\nexport interface SettingsClientConfig {\n /** Database client (read-write) */\n db: PostgresJsDatabase\n /** Logger instance */\n logger?: Logger\n /** Override scope (defaults to definition's scope) */\n scope?: SettingScope\n /** Scope ID (required for team/user scope, defaults to '__global__' for global) */\n scopeId?: string\n}\n\nexport interface LocaleOption {\n /** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */\n locale?: string\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private db: PostgresJsDatabase\n private logger?: Logger\n private scope: SettingScope\n private scopeId: string\n private validators: Record<string, ZodType>\n\n constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig) {\n if (typeof window !== 'undefined') {\n throw new Error('SettingsClient cannot be used in browser code.')\n }\n\n this.definition = definition\n this.db = config.db\n this.logger = config.logger\n this.scope = config.scope ?? definition.scope\n this.scopeId = config.scopeId ?? GLOBAL_SCOPE_ID\n\n if ((this.scope === 'team' || this.scope === 'user') && !config.scopeId) {\n throw new Error(\n `scopeId is required for ${this.scope}-scoped settings (namespace: ${definition.namespace})`,\n )\n }\n\n this.validators = generateSettingValidators(definition)\n }\n\n /**\n * Get a single setting value.\n *\n * For translatable settings with a locale, tries locale-specific value first,\n * then falls back to the default value, then the schema default, then null.\n */\n async get<K extends string & keyof S>(\n key: K,\n options?: LocaleOption,\n ): Promise<InferSettingValue<S[K]>> {\n const config = this.definition.schema[key]\n const locale = config?.translatable && options?.locale ? options.locale : null\n\n this.logger?.debug({ namespace: this.definition.namespace, key, locale }, 'Getting setting')\n\n if (locale) {\n // Fetch both locale-specific and default in one query\n const rows = await this.db\n .select({ locale: toolkitSettings.locale, value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n or(eq(toolkitSettings.locale, locale), eq(toolkitSettings.locale, DEFAULT_LOCALE)),\n ),\n )\n\n // Prefer locale-specific, fall back to default\n const localeRow = rows.find((r) => r.locale === locale)\n const defaultRow = rows.find((r) => r.locale === DEFAULT_LOCALE)\n const row = localeRow ?? defaultRow\n\n if (row && row.value !== undefined && row.value !== null) {\n return row.value as InferSettingValue<S[K]>\n }\n } else {\n const rows = await this.db\n .select({ value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(this.whereClause(key))\n .limit(1)\n\n if (rows.length > 0 && rows[0].value !== undefined && rows[0].value !== null) {\n return rows[0].value as InferSettingValue<S[K]>\n }\n }\n\n if (config && 'default' in config && config.default !== undefined) {\n return config.default as InferSettingValue<S[K]>\n }\n\n return null as InferSettingValue<S[K]>\n }\n\n /**\n * Get all settings for this namespace/scope as a typed object.\n * Missing values are filled from schema defaults.\n *\n * When locale is specified, translatable settings prefer the locale-specific\n * value over the default value.\n */\n async getAll(options?: LocaleOption): Promise<InferSettingsMap<S>> {\n const locale = options?.locale ?? null\n\n this.logger?.debug({ namespace: this.definition.namespace, locale }, 'Getting all settings')\n\n let rows: { key: string; locale: string; value: unknown }[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n or(eq(toolkitSettings.locale, DEFAULT_LOCALE), eq(toolkitSettings.locale, locale)),\n ),\n )\n } else {\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(and(...this.baseWhere(), eq(toolkitSettings.locale, DEFAULT_LOCALE)))\n }\n\n // Build lookup: key → { default: value, locale: value }\n const stored = new Map<string, { default?: unknown; locale?: unknown }>()\n for (const row of rows) {\n const entry = stored.get(row.key) ?? {}\n if (row.locale === DEFAULT_LOCALE) {\n entry.default = row.value\n } else {\n entry.locale = row.value\n }\n stored.set(row.key, entry)\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, config] of Object.entries(this.definition.schema)) {\n const entry = stored.get(key)\n\n // For translatable settings with locale, prefer locale-specific value\n let value: unknown\n if (config.translatable && locale && entry?.locale !== undefined && entry?.locale !== null) {\n value = entry.locale\n } else if (entry?.default !== undefined && entry?.default !== null) {\n value = entry.default\n }\n\n if (value !== undefined) {\n result[key] = value\n } else if ('default' in config && config.default !== undefined) {\n result[key] = config.default\n } else {\n result[key] = null\n }\n }\n\n return result as InferSettingsMap<S>\n }\n\n /**\n * Set a single setting value.\n * Validates against the schema before writing.\n *\n * Pass `{ locale }` to write a locale-specific value (only for translatable settings).\n */\n async set<K extends string & keyof S>(\n key: K,\n value: InferSettingValue<S[K]>,\n options?: LocaleOption,\n ): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Setting value')\n\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n\n const validator = this.validators[key]\n if (validator) {\n validator.parse(value)\n }\n\n await this.upsert(key, value as unknown, locale)\n }\n\n /**\n * Set multiple settings at once (validated individually).\n * Writes in a transaction — all or nothing.\n *\n * Pass `{ locale }` to write locale-specific values for translatable settings.\n * Non-translatable settings in the values will always write to the default locale.\n */\n async setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void> {\n this.logger?.info(\n { namespace: this.definition.namespace, keys: Object.keys(values), locale: options?.locale },\n 'Setting multiple values',\n )\n\n // Validate all first (fail fast)\n for (const [key, value] of Object.entries(values)) {\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n const validator = this.validators[key]\n if (validator && value !== undefined) {\n validator.parse(value)\n }\n }\n\n await this.db.transaction(async (tx) => {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n const locale = this.resolveLocale(key, options)\n await tx\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value: value as unknown,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value: value as unknown,\n updatedAt: new Date(),\n },\n })\n }\n })\n }\n\n /**\n * Delete a setting (resets to default on next get).\n * Pass `{ locale }` to delete only the locale-specific value.\n */\n async delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Deleting setting')\n\n await this.db.delete(toolkitSettings).where(this.whereClause(key, locale))\n }\n\n /**\n * Check if a setting has a stored value (not relying on default).\n */\n async has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean> {\n const locale = this.resolveLocale(key, options)\n\n const rows = await this.db\n .select({ key: toolkitSettings.key })\n .from(toolkitSettings)\n .where(this.whereClause(key, locale))\n .limit(1)\n\n return rows.length > 0\n }\n\n // ---------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------\n\n /**\n * Resolve which locale to use for a given key.\n * Non-translatable settings always use DEFAULT_LOCALE.\n * Translatable settings use the requested locale or DEFAULT_LOCALE.\n */\n private resolveLocale(key: string, options?: LocaleOption): string {\n const config = this.definition.schema[key as keyof S] as SettingConfig | undefined\n if (config?.translatable && options?.locale) {\n return options.locale\n }\n return DEFAULT_LOCALE\n }\n\n /** Base where conditions: namespace + scope + scopeId */\n private baseWhere() {\n return [\n eq(toolkitSettings.namespace, this.definition.namespace),\n eq(toolkitSettings.scope, this.scope),\n eq(toolkitSettings.scopeId, this.scopeId),\n ] as const\n }\n\n /** Full where clause for a specific key + locale */\n private whereClause(key: string, locale: string = DEFAULT_LOCALE) {\n return and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n eq(toolkitSettings.locale, locale),\n )!\n }\n\n /** Upsert a single setting row */\n private async upsert(key: string, value: unknown, locale: string) {\n await this.db\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value,\n updatedAt: new Date(),\n },\n })\n }\n}\n","/**\n * Factory function for creating typed SettingsClient instances.\n *\n * Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { SettingsClient } from './client.js'\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport interface CreateSettingsClientOptions {\n /** Override the toolkit app (defaults to getApp()) */\n app?: ToolkitApp\n /** Override scope from definition */\n scope?: SettingScope\n /** Scope ID for team/user scoped settings */\n scopeId?: string\n}\n\n/**\n * Create a typed SettingsClient.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n * const name = await settings.get('siteName') // string\n * ```\n */\nexport function createSettingsClient<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n options?: CreateSettingsClientOptions,\n): SettingsClient<S> {\n const app = options?.app ?? getApp()\n\n return new SettingsClient(definition, {\n db: app.db.readWrite,\n logger: app.logger.child({ settings: definition.namespace }),\n scope: options?.scope,\n scopeId: options?.scopeId,\n })\n}\n"],"mappings":"gOA4BA,MAAa,EAAkB,EAC7B,mBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,UAAW,EAAQ,YAAa,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC1D,MAAO,EAAQ,QAAS,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,SAAS,CACnE,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAAC,QAAQ,aAAa,CAC7E,IAAK,EAAQ,MAAO,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CAC9C,OAAQ,EAAQ,SAAU,CAAE,OAAQ,GAAI,CAAC,CAAC,SAAS,CAAC,QAAQ,WAAW,CACvE,MAAO,EAAM,QAAQ,CACrB,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAAC,SAAS,CAAC,YAAY,CACjF,UAAW,EAAK,aAAa,CAC9B,CACA,IAAW,CACV,cAAe,GAAQ,CAAC,GACtB,EAAM,UACN,EAAM,MACN,EAAM,QACN,EAAM,IACN,EAAM,OACP,CACF,EACF,CAQ+B,EAC9B,qBACA,CACE,GAAI,EAAK,KAAK,CAAC,YAAY,CAAC,eAAe,CAC3C,OAAQ,EAAK,UAAU,CAAC,SAAS,CACjC,QAAS,EAAQ,WAAY,CAAE,OAAQ,IAAK,CAAC,CAAC,SAAS,CACvD,MAAO,EAAM,QAAQ,CAAC,SAAS,CAC/B,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAC1D,UAAW,EAAU,aAAc,CAAE,aAAc,GAAM,CAAC,CAAC,SAAS,CAAC,YAAY,CAClF,CACA,IAAW,CACV,eAAgB,GAA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GAAS,KAAO,GAAQ,CAEpC,OAAO,IAAI,EAAe,EAAY,CACpC,GAAI,EAAI,GAAG,UACX,OAAQ,EAAI,OAAO,MAAM,CAAE,SAAU,EAAW,UAAW,CAAC,CAC5D,MAAO,GAAS,MAChB,QAAS,GAAS,QACnB,CAAC"}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { ZodType } from "zod";
|
|
2
|
+
import { Logger, ToolkitApp } from "@murumets-ee/core";
|
|
3
|
+
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
4
|
+
|
|
5
|
+
//#region src/types.d.ts
|
|
6
|
+
interface BaseSettingConfig {
|
|
7
|
+
/** Human-readable label for admin UI */
|
|
8
|
+
label?: string;
|
|
9
|
+
/** Description / help text */
|
|
10
|
+
description?: string;
|
|
11
|
+
/** If true, this setting can have per-locale values (mirrors entity translatable pattern) */
|
|
12
|
+
translatable?: boolean;
|
|
13
|
+
}
|
|
14
|
+
interface TextSettingConfig extends BaseSettingConfig {
|
|
15
|
+
type: 'text';
|
|
16
|
+
default?: string;
|
|
17
|
+
maxLength?: number;
|
|
18
|
+
minLength?: number;
|
|
19
|
+
pattern?: RegExp;
|
|
20
|
+
}
|
|
21
|
+
interface NumberSettingConfig extends BaseSettingConfig {
|
|
22
|
+
type: 'number';
|
|
23
|
+
default?: number;
|
|
24
|
+
min?: number;
|
|
25
|
+
max?: number;
|
|
26
|
+
integer?: boolean;
|
|
27
|
+
}
|
|
28
|
+
interface BooleanSettingConfig extends BaseSettingConfig {
|
|
29
|
+
type: 'boolean';
|
|
30
|
+
default?: boolean;
|
|
31
|
+
}
|
|
32
|
+
interface SelectSettingConfig<O extends readonly string[] = readonly string[]> extends BaseSettingConfig {
|
|
33
|
+
type: 'select';
|
|
34
|
+
options: O;
|
|
35
|
+
default?: O[number];
|
|
36
|
+
}
|
|
37
|
+
interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {
|
|
38
|
+
type: 'json';
|
|
39
|
+
default?: T;
|
|
40
|
+
/** Optional Zod schema for validation. If provided, values are validated on set. */
|
|
41
|
+
schema?: ZodType<T>;
|
|
42
|
+
}
|
|
43
|
+
interface MediaSettingConfig extends BaseSettingConfig {
|
|
44
|
+
type: 'media';
|
|
45
|
+
accept?: string[];
|
|
46
|
+
}
|
|
47
|
+
type SettingConfig = TextSettingConfig | NumberSettingConfig | BooleanSettingConfig | SelectSettingConfig | JsonSettingConfig | MediaSettingConfig;
|
|
48
|
+
/**
|
|
49
|
+
* Maps a single SettingConfig to its TypeScript output type.
|
|
50
|
+
* Each branch is a shallow comparison — no recursion.
|
|
51
|
+
*/
|
|
52
|
+
type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig ? string : S extends NumberSettingConfig ? number : S extends BooleanSettingConfig ? boolean : S extends SelectSettingConfig<infer O> ? O[number] : S extends JsonSettingConfig<infer T> ? T : S extends MediaSettingConfig ? string : never;
|
|
53
|
+
/**
|
|
54
|
+
* If a setting has a `default`, get() never returns null.
|
|
55
|
+
* Without a default, it returns T | null.
|
|
56
|
+
*/
|
|
57
|
+
type InferSettingValue<S extends SettingConfig> = S extends {
|
|
58
|
+
default: unknown;
|
|
59
|
+
} ? SettingToTS<S> : SettingToTS<S> | null;
|
|
60
|
+
type InferSettingsMap<Schema extends Record<string, SettingConfig>> = { [K in keyof Schema]: InferSettingValue<Schema[K]> };
|
|
61
|
+
type SettingScope = 'global' | 'team' | 'user';
|
|
62
|
+
/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */
|
|
63
|
+
declare const GLOBAL_SCOPE_ID = "__global__";
|
|
64
|
+
/** Sentinel value for locale column when no locale is specified (base/default value) */
|
|
65
|
+
declare const DEFAULT_LOCALE = "_default";
|
|
66
|
+
interface SettingsDefinition<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {
|
|
67
|
+
/** Unique namespace for this settings group */
|
|
68
|
+
namespace: string;
|
|
69
|
+
/** Default scope for these settings */
|
|
70
|
+
scope: SettingScope;
|
|
71
|
+
/** Setting schema (the shape) */
|
|
72
|
+
schema: S;
|
|
73
|
+
/** Human-readable label for admin UI */
|
|
74
|
+
label?: string;
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
//#region src/builders.d.ts
|
|
78
|
+
declare const setting: {
|
|
79
|
+
/**
|
|
80
|
+
* Text setting (string value)
|
|
81
|
+
*/
|
|
82
|
+
text: <const C extends Partial<Omit<TextSettingConfig, "type">> = {}>(config?: C) => TextSettingConfig & C;
|
|
83
|
+
/**
|
|
84
|
+
* Number setting
|
|
85
|
+
*/
|
|
86
|
+
number: <const C extends Partial<Omit<NumberSettingConfig, "type">> = {}>(config?: C) => NumberSettingConfig & C;
|
|
87
|
+
/**
|
|
88
|
+
* Boolean setting
|
|
89
|
+
*/
|
|
90
|
+
boolean: <const C extends Partial<Omit<BooleanSettingConfig, "type">> = {}>(config?: C) => BooleanSettingConfig & C;
|
|
91
|
+
/**
|
|
92
|
+
* Select setting (enum from options tuple)
|
|
93
|
+
* Preserves literal option types for type inference.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* setting.select({ options: ['light', 'dark', 'system'] as const, default: 'system' })
|
|
97
|
+
* // inferred type: 'light' | 'dark' | 'system'
|
|
98
|
+
*/
|
|
99
|
+
select: <const O extends readonly string[], const C extends Partial<Omit<SelectSettingConfig, "type" | "options">> = {}>(config: {
|
|
100
|
+
options: O;
|
|
101
|
+
} & C) => SelectSettingConfig<O> & C;
|
|
102
|
+
/**
|
|
103
|
+
* JSON setting (arbitrary typed JSON)
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* setting.json<{ twitter?: string; github?: string }>()
|
|
107
|
+
* setting.json<string[]>({ default: [] })
|
|
108
|
+
*/
|
|
109
|
+
json: <T = unknown, const C extends Partial<Omit<JsonSettingConfig<T>, "type">> = {}>(config?: C) => JsonSettingConfig<T> & C;
|
|
110
|
+
/**
|
|
111
|
+
* Media setting (stores media ID as string UUID)
|
|
112
|
+
*/
|
|
113
|
+
media: <const C extends Partial<Omit<MediaSettingConfig, "type">> = {}>(config?: C) => MediaSettingConfig & C;
|
|
114
|
+
};
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/client.d.ts
|
|
117
|
+
interface SettingsClientConfig {
|
|
118
|
+
/** Database client (read-write) */
|
|
119
|
+
db: PostgresJsDatabase;
|
|
120
|
+
/** Logger instance */
|
|
121
|
+
logger?: Logger;
|
|
122
|
+
/** Override scope (defaults to definition's scope) */
|
|
123
|
+
scope?: SettingScope;
|
|
124
|
+
/** Scope ID (required for team/user scope, defaults to '__global__' for global) */
|
|
125
|
+
scopeId?: string;
|
|
126
|
+
}
|
|
127
|
+
interface LocaleOption {
|
|
128
|
+
/** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */
|
|
129
|
+
locale?: string;
|
|
130
|
+
}
|
|
131
|
+
declare class SettingsClient<S extends Record<string, SettingConfig> = Record<string, SettingConfig>> {
|
|
132
|
+
private definition;
|
|
133
|
+
private db;
|
|
134
|
+
private logger?;
|
|
135
|
+
private scope;
|
|
136
|
+
private scopeId;
|
|
137
|
+
private validators;
|
|
138
|
+
constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig);
|
|
139
|
+
/**
|
|
140
|
+
* Get a single setting value.
|
|
141
|
+
*
|
|
142
|
+
* For translatable settings with a locale, tries locale-specific value first,
|
|
143
|
+
* then falls back to the default value, then the schema default, then null.
|
|
144
|
+
*/
|
|
145
|
+
get<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<InferSettingValue<S[K]>>;
|
|
146
|
+
/**
|
|
147
|
+
* Get all settings for this namespace/scope as a typed object.
|
|
148
|
+
* Missing values are filled from schema defaults.
|
|
149
|
+
*
|
|
150
|
+
* When locale is specified, translatable settings prefer the locale-specific
|
|
151
|
+
* value over the default value.
|
|
152
|
+
*/
|
|
153
|
+
getAll(options?: LocaleOption): Promise<InferSettingsMap<S>>;
|
|
154
|
+
/**
|
|
155
|
+
* Set a single setting value.
|
|
156
|
+
* Validates against the schema before writing.
|
|
157
|
+
*
|
|
158
|
+
* Pass `{ locale }` to write a locale-specific value (only for translatable settings).
|
|
159
|
+
*/
|
|
160
|
+
set<K extends string & keyof S>(key: K, value: InferSettingValue<S[K]>, options?: LocaleOption): Promise<void>;
|
|
161
|
+
/**
|
|
162
|
+
* Set multiple settings at once (validated individually).
|
|
163
|
+
* Writes in a transaction — all or nothing.
|
|
164
|
+
*
|
|
165
|
+
* Pass `{ locale }` to write locale-specific values for translatable settings.
|
|
166
|
+
* Non-translatable settings in the values will always write to the default locale.
|
|
167
|
+
*/
|
|
168
|
+
setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void>;
|
|
169
|
+
/**
|
|
170
|
+
* Delete a setting (resets to default on next get).
|
|
171
|
+
* Pass `{ locale }` to delete only the locale-specific value.
|
|
172
|
+
*/
|
|
173
|
+
delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void>;
|
|
174
|
+
/**
|
|
175
|
+
* Check if a setting has a stored value (not relying on default).
|
|
176
|
+
*/
|
|
177
|
+
has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean>;
|
|
178
|
+
/**
|
|
179
|
+
* Resolve which locale to use for a given key.
|
|
180
|
+
* Non-translatable settings always use DEFAULT_LOCALE.
|
|
181
|
+
* Translatable settings use the requested locale or DEFAULT_LOCALE.
|
|
182
|
+
*/
|
|
183
|
+
private resolveLocale;
|
|
184
|
+
/** Base where conditions: namespace + scope + scopeId */
|
|
185
|
+
private baseWhere;
|
|
186
|
+
/** Full where clause for a specific key + locale */
|
|
187
|
+
private whereClause;
|
|
188
|
+
/** Upsert a single setting row */
|
|
189
|
+
private upsert;
|
|
190
|
+
}
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region src/client-factory.d.ts
|
|
193
|
+
interface CreateSettingsClientOptions {
|
|
194
|
+
/** Override the toolkit app (defaults to getApp()) */
|
|
195
|
+
app?: ToolkitApp;
|
|
196
|
+
/** Override scope from definition */
|
|
197
|
+
scope?: SettingScope;
|
|
198
|
+
/** Scope ID for team/user scoped settings */
|
|
199
|
+
scopeId?: string;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Create a typed SettingsClient.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* ```typescript
|
|
206
|
+
* import { createSettingsClient } from '@murumets-ee/settings'
|
|
207
|
+
* import { siteSettings } from './settings/site'
|
|
208
|
+
*
|
|
209
|
+
* const settings = createSettingsClient(siteSettings)
|
|
210
|
+
* const name = await settings.get('siteName') // string
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
declare function createSettingsClient<S extends Record<string, SettingConfig>>(definition: SettingsDefinition<S>, options?: CreateSettingsClientOptions): SettingsClient<S>;
|
|
214
|
+
//#endregion
|
|
215
|
+
//#region src/define-settings.d.ts
|
|
216
|
+
declare function defineSettings<const S extends Record<string, SettingConfig>>(definition: {
|
|
217
|
+
namespace: string;
|
|
218
|
+
scope: SettingScope;
|
|
219
|
+
schema: S;
|
|
220
|
+
label?: string;
|
|
221
|
+
}): SettingsDefinition<S>;
|
|
222
|
+
//#endregion
|
|
223
|
+
export { type BaseSettingConfig, type BooleanSettingConfig, type CreateSettingsClientOptions, DEFAULT_LOCALE, GLOBAL_SCOPE_ID, type InferSettingValue, type InferSettingsMap, type JsonSettingConfig, type LocaleOption, type MediaSettingConfig, type NumberSettingConfig, type SelectSettingConfig, type SettingConfig, type SettingScope, type SettingToTS, SettingsClient, type SettingsClientConfig, type SettingsDefinition, type TextSettingConfig, createSettingsClient, defineSettings, setting };
|
|
224
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/builders.ts","../src/client.ts","../src/client-factory.ts","../src/define-settings.ts"],"mappings":";;;;;UAgBiB,iBAAA;EAIf;EAFA,KAAA;EAIY;EAFZ,WAAA;EAKe;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CAAA"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{toolkitSettings as e}from"./schema.mjs";import"server-only";import{and as t,eq as n,or as r}from"drizzle-orm";import{z as i}from"zod";import{getApp as a}from"@murumets-ee/core";const o={text:e=>({type:`text`,...e}),number:e=>({type:`number`,...e}),boolean:e=>({type:`boolean`,...e}),select:e=>({type:`select`,...e}),json:e=>({type:`json`,...e}),media:e=>({type:`media`,...e})},s=`__global__`,c=`_default`;function l(e){switch(e.type){case`text`:{let t=i.string();return e.maxLength&&(t=t.max(e.maxLength)),e.minLength&&(t=t.min(e.minLength)),e.pattern&&(t=t.regex(e.pattern)),t}case`number`:{let t=i.number();return e.integer&&(t=t.int()),e.min!==void 0&&(t=t.min(e.min)),e.max!==void 0&&(t=t.max(e.max)),t}case`boolean`:return i.boolean();case`select`:return i.enum(e.options);case`json`:return e.schema??i.unknown();case`media`:return i.string().uuid();default:return i.unknown()}}function u(e){let t={};for(let[n,r]of Object.entries(e.schema)){let e=l(r);`default`in r&&r.default!==void 0||(e=e.nullable()),t[n]=e}return t}var d=class{definition;db;logger;scope;scopeId;validators;constructor(e,t){if(typeof window<`u`)throw Error(`SettingsClient cannot be used in browser code.`);if(this.definition=e,this.db=t.db,this.logger=t.logger,this.scope=t.scope??e.scope,this.scopeId=t.scopeId??`__global__`,(this.scope===`team`||this.scope===`user`)&&!t.scopeId)throw Error(`scopeId is required for ${this.scope}-scoped settings (namespace: ${e.namespace})`);this.validators=u(e)}async get(i,a){let o=this.definition.schema[i],s=o?.translatable&&a?.locale?a.locale:null;if(this.logger?.debug({namespace:this.definition.namespace,key:i,locale:s},`Getting setting`),s){let a=await this.db.select({locale:e.locale,value:e.value}).from(e).where(t(...this.baseWhere(),n(e.key,i),r(n(e.locale,s),n(e.locale,c)))),o=a.find(e=>e.locale===s),l=a.find(e=>e.locale===c),u=o??l;if(u&&u.value!==void 0&&u.value!==null)return u.value}else{let t=await this.db.select({value:e.value}).from(e).where(this.whereClause(i)).limit(1);if(t.length>0&&t[0].value!==void 0&&t[0].value!==null)return t[0].value}return o&&`default`in o&&o.default!==void 0?o.default:null}async getAll(i){let a=i?.locale??null;this.logger?.debug({namespace:this.definition.namespace,locale:a},`Getting all settings`);let o;o=a?await this.db.select({key:e.key,locale:e.locale,value:e.value}).from(e).where(t(...this.baseWhere(),r(n(e.locale,c),n(e.locale,a)))):await this.db.select({key:e.key,locale:e.locale,value:e.value}).from(e).where(t(...this.baseWhere(),n(e.locale,c)));let s=new Map;for(let e of o){let t=s.get(e.key)??{};e.locale===`_default`?t.default=e.value:t.locale=e.value,s.set(e.key,t)}let l={};for(let[e,t]of Object.entries(this.definition.schema)){let n=s.get(e),r;t.translatable&&a&&n?.locale!==void 0&&n?.locale!==null?r=n.locale:n?.default!==void 0&&n?.default!==null&&(r=n.default),r===void 0?`default`in t&&t.default!==void 0?l[e]=t.default:l[e]=null:l[e]=r}return l}async set(e,t,n){let r=this.resolveLocale(e,n);if(this.logger?.info({namespace:this.definition.namespace,key:e,locale:r},`Setting value`),!(e in this.definition.schema))throw Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let i=this.validators[e];i&&i.parse(t),await this.upsert(e,t,r)}async setMany(t,n){this.logger?.info({namespace:this.definition.namespace,keys:Object.keys(t),locale:n?.locale},`Setting multiple values`);for(let[e,n]of Object.entries(t)){if(!(e in this.definition.schema))throw Error(`Unknown setting key '${e}' in namespace '${this.definition.namespace}'`);let t=this.validators[e];t&&n!==void 0&&t.parse(n)}await this.db.transaction(async r=>{for(let[i,a]of Object.entries(t)){if(a===void 0)continue;let t=this.resolveLocale(i,n);await r.insert(e).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:i,locale:t,value:a,updatedAt:new Date}).onConflictDoUpdate({target:[e.namespace,e.scope,e.scopeId,e.key,e.locale],set:{value:a,updatedAt:new Date}})}})}async delete(t,n){let r=this.resolveLocale(t,n);this.logger?.info({namespace:this.definition.namespace,key:t,locale:r},`Deleting setting`),await this.db.delete(e).where(this.whereClause(t,r))}async has(t,n){let r=this.resolveLocale(t,n);return(await this.db.select({key:e.key}).from(e).where(this.whereClause(t,r)).limit(1)).length>0}resolveLocale(e,t){return this.definition.schema[e]?.translatable&&t?.locale?t.locale:c}baseWhere(){return[n(e.namespace,this.definition.namespace),n(e.scope,this.scope),n(e.scopeId,this.scopeId)]}whereClause(r,i=c){return t(...this.baseWhere(),n(e.key,r),n(e.locale,i))}async upsert(t,n,r){await this.db.insert(e).values({namespace:this.definition.namespace,scope:this.scope,scopeId:this.scopeId,key:t,locale:r,value:n,updatedAt:new Date}).onConflictDoUpdate({target:[e.namespace,e.scope,e.scopeId,e.key,e.locale],set:{value:n,updatedAt:new Date}})}};function f(e,t){let n=t?.app??a();return new d(e,{db:n.db.readWrite,logger:n.logger.child({settings:e.namespace}),scope:t?.scope,scopeId:t?.scopeId})}function p(e){if(!e.namespace)throw Error(`Settings namespace is required`);if(!e.schema||Object.keys(e.schema).length===0)throw Error(`Settings schema must have at least one setting`);return e}export{c as DEFAULT_LOCALE,s as GLOBAL_SCOPE_ID,d as SettingsClient,f as createSettingsClient,p as defineSettings,o as setting};
|
|
2
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/builders.ts","../src/types.ts","../src/validation.ts","../src/client.ts","../src/client-factory.ts","../src/define-settings.ts"],"sourcesContent":["/**\n * Fluent API for building setting definitions.\n *\n * Each builder uses a `const` generic parameter on the config to preserve\n * literal types (e.g., `default: 'My Site'` stays literal, not `string`).\n * This enables compile-time type inference in the settings system.\n *\n * Pattern matches packages/entity/src/fields/builders.ts exactly.\n */\n\nimport type {\n BooleanSettingConfig,\n JsonSettingConfig,\n MediaSettingConfig,\n NumberSettingConfig,\n SelectSettingConfig,\n TextSettingConfig,\n} from './types.js'\n\nexport const setting = {\n /**\n * Text setting (string value)\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n text: <const C extends Partial<Omit<TextSettingConfig, 'type'>> = {}>(\n config?: C,\n ): TextSettingConfig & C => ({ type: 'text', ...config }) as TextSettingConfig & C,\n\n /**\n * Number setting\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n number: <const C extends Partial<Omit<NumberSettingConfig, 'type'>> = {}>(\n config?: C,\n ): NumberSettingConfig & C => ({ type: 'number', ...config }) as NumberSettingConfig & C,\n\n /**\n * Boolean setting\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n boolean: <const C extends Partial<Omit<BooleanSettingConfig, 'type'>> = {}>(\n config?: C,\n ): BooleanSettingConfig & C => ({ type: 'boolean', ...config }) as BooleanSettingConfig & C,\n\n /**\n * Select setting (enum from options tuple)\n * Preserves literal option types for type inference.\n *\n * @example\n * setting.select({ options: ['light', 'dark', 'system'] as const, default: 'system' })\n * // inferred type: 'light' | 'dark' | 'system'\n */\n select: <\n const O extends readonly string[],\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n const C extends Partial<Omit<SelectSettingConfig, 'type' | 'options'>> = {},\n >(\n config: { options: O } & C,\n ): SelectSettingConfig<O> & C => ({ type: 'select', ...config }) as SelectSettingConfig<O> & C,\n\n /**\n * JSON setting (arbitrary typed JSON)\n *\n * @example\n * setting.json<{ twitter?: string; github?: string }>()\n * setting.json<string[]>({ default: [] })\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n json: <T = unknown, const C extends Partial<Omit<JsonSettingConfig<T>, 'type'>> = {}>(\n config?: C,\n ): JsonSettingConfig<T> & C => ({ type: 'json', ...config }) as JsonSettingConfig<T> & C,\n\n /**\n * Media setting (stores media ID as string UUID)\n */\n // biome-ignore lint/complexity/noBannedTypes: {} is correct as empty generic default\n media: <const C extends Partial<Omit<MediaSettingConfig, 'type'>> = {}>(\n config?: C,\n ): MediaSettingConfig & C => ({ type: 'media', ...config }) as MediaSettingConfig & C,\n}\n","/**\n * Setting configuration types and compile-time type inference.\n *\n * Design mirrors the entity field system:\n * - Config interfaces define what each setting type accepts\n * - SettingToTS maps a single config to its TypeScript type\n * - InferSettingValue adds null awareness based on `default` presence\n * - InferSettingsMap maps an entire schema to a typed record\n */\n\nimport type { ZodType } from 'zod'\n\n// ---------------------------------------------------------------\n// 1. Setting config interfaces\n// ---------------------------------------------------------------\n\nexport interface BaseSettingConfig {\n /** Human-readable label for admin UI */\n label?: string\n /** Description / help text */\n description?: string\n /** If true, this setting can have per-locale values (mirrors entity translatable pattern) */\n translatable?: boolean\n}\n\nexport interface TextSettingConfig extends BaseSettingConfig {\n type: 'text'\n default?: string\n maxLength?: number\n minLength?: number\n pattern?: RegExp\n}\n\nexport interface NumberSettingConfig extends BaseSettingConfig {\n type: 'number'\n default?: number\n min?: number\n max?: number\n integer?: boolean\n}\n\nexport interface BooleanSettingConfig extends BaseSettingConfig {\n type: 'boolean'\n default?: boolean\n}\n\nexport interface SelectSettingConfig<O extends readonly string[] = readonly string[]>\n extends BaseSettingConfig {\n type: 'select'\n options: O\n default?: O[number]\n}\n\nexport interface JsonSettingConfig<T = unknown> extends BaseSettingConfig {\n type: 'json'\n default?: T\n /** Optional Zod schema for validation. If provided, values are validated on set. */\n schema?: ZodType<T>\n}\n\nexport interface MediaSettingConfig extends BaseSettingConfig {\n type: 'media'\n accept?: string[]\n}\n\nexport type SettingConfig =\n | TextSettingConfig\n | NumberSettingConfig\n | BooleanSettingConfig\n | SelectSettingConfig\n | JsonSettingConfig\n | MediaSettingConfig\n\n// ---------------------------------------------------------------\n// 2. Setting-to-TypeScript mapping (single setting)\n// ---------------------------------------------------------------\n\n/**\n * Maps a single SettingConfig to its TypeScript output type.\n * Each branch is a shallow comparison — no recursion.\n */\nexport type SettingToTS<S extends SettingConfig> = S extends TextSettingConfig\n ? string\n : S extends NumberSettingConfig\n ? number\n : S extends BooleanSettingConfig\n ? boolean\n : S extends SelectSettingConfig<infer O>\n ? O[number]\n : S extends JsonSettingConfig<infer T>\n ? T\n : S extends MediaSettingConfig\n ? string\n : never\n\n// ---------------------------------------------------------------\n// 3. Null awareness: settings with defaults always return value\n// ---------------------------------------------------------------\n\n/**\n * If a setting has a `default`, get() never returns null.\n * Without a default, it returns T | null.\n */\nexport type InferSettingValue<S extends SettingConfig> = S extends { default: unknown }\n ? SettingToTS<S>\n : SettingToTS<S> | null\n\n// ---------------------------------------------------------------\n// 4. Full settings map type (what getAll() returns)\n// ---------------------------------------------------------------\n\nexport type InferSettingsMap<Schema extends Record<string, SettingConfig>> = {\n [K in keyof Schema]: InferSettingValue<Schema[K]>\n}\n\n// ---------------------------------------------------------------\n// 5. Scope types\n// ---------------------------------------------------------------\n\nexport type SettingScope = 'global' | 'team' | 'user'\n\n/** Sentinel value for global scope_id (avoids NULL uniqueness issues) */\nexport const GLOBAL_SCOPE_ID = '__global__'\n\n/** Sentinel value for locale column when no locale is specified (base/default value) */\nexport const DEFAULT_LOCALE = '_default'\n\n// ---------------------------------------------------------------\n// 6. Settings definition (returned by defineSettings)\n// ---------------------------------------------------------------\n\nexport interface SettingsDefinition<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n /** Unique namespace for this settings group */\n namespace: string\n /** Default scope for these settings */\n scope: SettingScope\n /** Setting schema (the shape) */\n schema: S\n /** Human-readable label for admin UI */\n label?: string\n}\n","/**\n * Generate Zod validation schemas from setting config definitions.\n * Validates values before writing to the database.\n */\n\nimport { z } from 'zod'\nimport type { SettingConfig, SettingsDefinition } from './types.js'\n\n/**\n * Convert a single setting config to a Zod schema.\n */\nexport function settingToZod(config: SettingConfig): z.ZodType {\n switch (config.type) {\n case 'text': {\n let schema: z.ZodString = z.string()\n if (config.maxLength) schema = schema.max(config.maxLength)\n if (config.minLength) schema = schema.min(config.minLength)\n if (config.pattern) schema = schema.regex(config.pattern)\n return schema\n }\n\n case 'number': {\n let schema: z.ZodNumber = z.number()\n if (config.integer) schema = schema.int()\n if (config.min !== undefined) schema = schema.min(config.min)\n if (config.max !== undefined) schema = schema.max(config.max)\n return schema\n }\n\n case 'boolean':\n return z.boolean()\n\n case 'select':\n return z.enum(config.options as [string, ...string[]])\n\n case 'json':\n return config.schema ?? z.unknown()\n\n case 'media':\n return z.string().uuid()\n\n default:\n return z.unknown()\n }\n}\n\n/**\n * Generate a validation map for all settings in a definition.\n * Returns a Record<key, ZodType> for validating individual set() calls.\n *\n * Settings without a default are nullable (matching InferSettingValue),\n * so their validators accept null.\n */\nexport function generateSettingValidators(\n definition: SettingsDefinition,\n): Record<string, z.ZodType> {\n const validators: Record<string, z.ZodType> = {}\n for (const [key, config] of Object.entries(definition.schema)) {\n let schema = settingToZod(config)\n const hasDefault = 'default' in config && config.default !== undefined\n if (!hasDefault) {\n schema = schema.nullable()\n }\n validators[key] = schema\n }\n return validators\n}\n","/**\n * SettingsClient — typed CRUD for key-value settings.\n *\n * Server-only. Uses read-write DB connection.\n * Validates values against the setting schema on set().\n *\n * Supports per-locale values for settings marked `translatable: true`.\n * Non-translatable settings always use the `__default__` locale.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n *\n * // Default locale\n * const name = await settings.get('siteName') // string (has default)\n *\n * // Locale-specific (only for translatable settings)\n * const nameEt = await settings.get('siteName', { locale: 'et' })\n *\n * await settings.set('siteName', 'Mänguväljak', { locale: 'et' })\n * ```\n */\n\nimport type { Logger } from '@murumets-ee/core'\nimport { and, eq, or } from 'drizzle-orm'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { ZodType } from 'zod'\nimport { toolkitSettings } from './schema.js'\nimport type {\n InferSettingsMap,\n InferSettingValue,\n SettingConfig,\n SettingScope,\n SettingsDefinition,\n} from './types.js'\nimport { DEFAULT_LOCALE, GLOBAL_SCOPE_ID } from './types.js'\nimport { generateSettingValidators } from './validation.js'\n\nexport interface SettingsClientConfig {\n /** Database client (read-write) */\n db: PostgresJsDatabase\n /** Logger instance */\n logger?: Logger\n /** Override scope (defaults to definition's scope) */\n scope?: SettingScope\n /** Scope ID (required for team/user scope, defaults to '__global__' for global) */\n scopeId?: string\n}\n\nexport interface LocaleOption {\n /** Locale code for translatable settings (e.g. 'et', 'ru'). Ignored for non-translatable settings. */\n locale?: string\n}\n\nexport class SettingsClient<\n S extends Record<string, SettingConfig> = Record<string, SettingConfig>,\n> {\n private definition: SettingsDefinition<S>\n private db: PostgresJsDatabase\n private logger?: Logger\n private scope: SettingScope\n private scopeId: string\n private validators: Record<string, ZodType>\n\n constructor(definition: SettingsDefinition<S>, config: SettingsClientConfig) {\n if (typeof window !== 'undefined') {\n throw new Error('SettingsClient cannot be used in browser code.')\n }\n\n this.definition = definition\n this.db = config.db\n this.logger = config.logger\n this.scope = config.scope ?? definition.scope\n this.scopeId = config.scopeId ?? GLOBAL_SCOPE_ID\n\n if ((this.scope === 'team' || this.scope === 'user') && !config.scopeId) {\n throw new Error(\n `scopeId is required for ${this.scope}-scoped settings (namespace: ${definition.namespace})`,\n )\n }\n\n this.validators = generateSettingValidators(definition)\n }\n\n /**\n * Get a single setting value.\n *\n * For translatable settings with a locale, tries locale-specific value first,\n * then falls back to the default value, then the schema default, then null.\n */\n async get<K extends string & keyof S>(\n key: K,\n options?: LocaleOption,\n ): Promise<InferSettingValue<S[K]>> {\n const config = this.definition.schema[key]\n const locale = config?.translatable && options?.locale ? options.locale : null\n\n this.logger?.debug({ namespace: this.definition.namespace, key, locale }, 'Getting setting')\n\n if (locale) {\n // Fetch both locale-specific and default in one query\n const rows = await this.db\n .select({ locale: toolkitSettings.locale, value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n or(eq(toolkitSettings.locale, locale), eq(toolkitSettings.locale, DEFAULT_LOCALE)),\n ),\n )\n\n // Prefer locale-specific, fall back to default\n const localeRow = rows.find((r) => r.locale === locale)\n const defaultRow = rows.find((r) => r.locale === DEFAULT_LOCALE)\n const row = localeRow ?? defaultRow\n\n if (row && row.value !== undefined && row.value !== null) {\n return row.value as InferSettingValue<S[K]>\n }\n } else {\n const rows = await this.db\n .select({ value: toolkitSettings.value })\n .from(toolkitSettings)\n .where(this.whereClause(key))\n .limit(1)\n\n if (rows.length > 0 && rows[0].value !== undefined && rows[0].value !== null) {\n return rows[0].value as InferSettingValue<S[K]>\n }\n }\n\n if (config && 'default' in config && config.default !== undefined) {\n return config.default as InferSettingValue<S[K]>\n }\n\n return null as InferSettingValue<S[K]>\n }\n\n /**\n * Get all settings for this namespace/scope as a typed object.\n * Missing values are filled from schema defaults.\n *\n * When locale is specified, translatable settings prefer the locale-specific\n * value over the default value.\n */\n async getAll(options?: LocaleOption): Promise<InferSettingsMap<S>> {\n const locale = options?.locale ?? null\n\n this.logger?.debug({ namespace: this.definition.namespace, locale }, 'Getting all settings')\n\n let rows: { key: string; locale: string; value: unknown }[]\n\n if (locale) {\n // Fetch both default and locale-specific rows\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(\n and(\n ...this.baseWhere(),\n or(eq(toolkitSettings.locale, DEFAULT_LOCALE), eq(toolkitSettings.locale, locale)),\n ),\n )\n } else {\n rows = await this.db\n .select({\n key: toolkitSettings.key,\n locale: toolkitSettings.locale,\n value: toolkitSettings.value,\n })\n .from(toolkitSettings)\n .where(and(...this.baseWhere(), eq(toolkitSettings.locale, DEFAULT_LOCALE)))\n }\n\n // Build lookup: key → { default: value, locale: value }\n const stored = new Map<string, { default?: unknown; locale?: unknown }>()\n for (const row of rows) {\n const entry = stored.get(row.key) ?? {}\n if (row.locale === DEFAULT_LOCALE) {\n entry.default = row.value\n } else {\n entry.locale = row.value\n }\n stored.set(row.key, entry)\n }\n\n const result: Record<string, unknown> = {}\n for (const [key, config] of Object.entries(this.definition.schema)) {\n const entry = stored.get(key)\n\n // For translatable settings with locale, prefer locale-specific value\n let value: unknown\n if (config.translatable && locale && entry?.locale !== undefined && entry?.locale !== null) {\n value = entry.locale\n } else if (entry?.default !== undefined && entry?.default !== null) {\n value = entry.default\n }\n\n if (value !== undefined) {\n result[key] = value\n } else if ('default' in config && config.default !== undefined) {\n result[key] = config.default\n } else {\n result[key] = null\n }\n }\n\n return result as InferSettingsMap<S>\n }\n\n /**\n * Set a single setting value.\n * Validates against the schema before writing.\n *\n * Pass `{ locale }` to write a locale-specific value (only for translatable settings).\n */\n async set<K extends string & keyof S>(\n key: K,\n value: InferSettingValue<S[K]>,\n options?: LocaleOption,\n ): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Setting value')\n\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n\n const validator = this.validators[key]\n if (validator) {\n validator.parse(value)\n }\n\n await this.upsert(key, value as unknown, locale)\n }\n\n /**\n * Set multiple settings at once (validated individually).\n * Writes in a transaction — all or nothing.\n *\n * Pass `{ locale }` to write locale-specific values for translatable settings.\n * Non-translatable settings in the values will always write to the default locale.\n */\n async setMany(values: Partial<InferSettingsMap<S>>, options?: LocaleOption): Promise<void> {\n this.logger?.info(\n { namespace: this.definition.namespace, keys: Object.keys(values), locale: options?.locale },\n 'Setting multiple values',\n )\n\n // Validate all first (fail fast)\n for (const [key, value] of Object.entries(values)) {\n if (!(key in this.definition.schema)) {\n throw new Error(`Unknown setting key '${key}' in namespace '${this.definition.namespace}'`)\n }\n const validator = this.validators[key]\n if (validator && value !== undefined) {\n validator.parse(value)\n }\n }\n\n await this.db.transaction(async (tx) => {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue\n const locale = this.resolveLocale(key, options)\n await tx\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value: value as unknown,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value: value as unknown,\n updatedAt: new Date(),\n },\n })\n }\n })\n }\n\n /**\n * Delete a setting (resets to default on next get).\n * Pass `{ locale }` to delete only the locale-specific value.\n */\n async delete<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<void> {\n const locale = this.resolveLocale(key, options)\n\n this.logger?.info({ namespace: this.definition.namespace, key, locale }, 'Deleting setting')\n\n await this.db.delete(toolkitSettings).where(this.whereClause(key, locale))\n }\n\n /**\n * Check if a setting has a stored value (not relying on default).\n */\n async has<K extends string & keyof S>(key: K, options?: LocaleOption): Promise<boolean> {\n const locale = this.resolveLocale(key, options)\n\n const rows = await this.db\n .select({ key: toolkitSettings.key })\n .from(toolkitSettings)\n .where(this.whereClause(key, locale))\n .limit(1)\n\n return rows.length > 0\n }\n\n // ---------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------\n\n /**\n * Resolve which locale to use for a given key.\n * Non-translatable settings always use DEFAULT_LOCALE.\n * Translatable settings use the requested locale or DEFAULT_LOCALE.\n */\n private resolveLocale(key: string, options?: LocaleOption): string {\n const config = this.definition.schema[key as keyof S] as SettingConfig | undefined\n if (config?.translatable && options?.locale) {\n return options.locale\n }\n return DEFAULT_LOCALE\n }\n\n /** Base where conditions: namespace + scope + scopeId */\n private baseWhere() {\n return [\n eq(toolkitSettings.namespace, this.definition.namespace),\n eq(toolkitSettings.scope, this.scope),\n eq(toolkitSettings.scopeId, this.scopeId),\n ] as const\n }\n\n /** Full where clause for a specific key + locale */\n private whereClause(key: string, locale: string = DEFAULT_LOCALE) {\n return and(\n ...this.baseWhere(),\n eq(toolkitSettings.key, key),\n eq(toolkitSettings.locale, locale),\n )!\n }\n\n /** Upsert a single setting row */\n private async upsert(key: string, value: unknown, locale: string) {\n await this.db\n .insert(toolkitSettings)\n .values({\n namespace: this.definition.namespace,\n scope: this.scope,\n scopeId: this.scopeId,\n key,\n locale,\n value,\n updatedAt: new Date(),\n })\n .onConflictDoUpdate({\n target: [\n toolkitSettings.namespace,\n toolkitSettings.scope,\n toolkitSettings.scopeId,\n toolkitSettings.key,\n toolkitSettings.locale,\n ],\n set: {\n value,\n updatedAt: new Date(),\n },\n })\n }\n}\n","/**\n * Factory function for creating typed SettingsClient instances.\n *\n * Follows the createAdminClient(entity, app?) pattern from @murumets-ee/core.\n */\n\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { getApp } from '@murumets-ee/core'\nimport { SettingsClient } from './client.js'\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport interface CreateSettingsClientOptions {\n /** Override the toolkit app (defaults to getApp()) */\n app?: ToolkitApp\n /** Override scope from definition */\n scope?: SettingScope\n /** Scope ID for team/user scoped settings */\n scopeId?: string\n}\n\n/**\n * Create a typed SettingsClient.\n *\n * @example\n * ```typescript\n * import { createSettingsClient } from '@murumets-ee/settings'\n * import { siteSettings } from './settings/site'\n *\n * const settings = createSettingsClient(siteSettings)\n * const name = await settings.get('siteName') // string\n * ```\n */\nexport function createSettingsClient<S extends Record<string, SettingConfig>>(\n definition: SettingsDefinition<S>,\n options?: CreateSettingsClientOptions,\n): SettingsClient<S> {\n const app = options?.app ?? getApp()\n\n return new SettingsClient(definition, {\n db: app.db.readWrite,\n logger: app.logger.child({ settings: definition.namespace }),\n scope: options?.scope,\n scopeId: options?.scopeId,\n })\n}\n","/**\n * Define a typed settings group.\n *\n * @example\n * ```typescript\n * import { defineSettings, setting } from '@murumets-ee/settings'\n *\n * export const siteSettings = defineSettings({\n * namespace: 'site',\n * scope: 'global',\n * schema: {\n * siteName: setting.text({ default: 'My Site' }),\n * logo: setting.media(),\n * maintenance: setting.boolean({ default: false }),\n * },\n * })\n * ```\n */\n\nimport type { SettingConfig, SettingScope, SettingsDefinition } from './types.js'\n\nexport function defineSettings<const S extends Record<string, SettingConfig>>(definition: {\n namespace: string\n scope: SettingScope\n schema: S\n label?: string\n}): SettingsDefinition<S> {\n if (!definition.namespace) {\n throw new Error('Settings namespace is required')\n }\n if (!definition.schema || Object.keys(definition.schema).length === 0) {\n throw new Error('Settings schema must have at least one setting')\n }\n return definition\n}\n"],"mappings":"wLAmBA,MAAa,EAAU,CAKrB,KACE,IAC2B,CAAE,KAAM,OAAQ,GAAG,EAAQ,EAMxD,OACE,IAC6B,CAAE,KAAM,SAAU,GAAG,EAAQ,EAM5D,QACE,IAC8B,CAAE,KAAM,UAAW,GAAG,EAAQ,EAU9D,OAKE,IACgC,CAAE,KAAM,SAAU,GAAG,EAAQ,EAU/D,KACE,IAC8B,CAAE,KAAM,OAAQ,GAAG,EAAQ,EAM3D,MACE,IAC4B,CAAE,KAAM,QAAS,GAAG,EAAQ,EAC3D,CC2CY,EAAkB,aAGlB,EAAiB,WClH9B,SAAgB,EAAa,EAAkC,CAC7D,OAAQ,EAAO,KAAf,CACE,IAAK,OAAQ,CACX,IAAI,EAAsB,EAAE,QAAQ,CAIpC,OAHI,EAAO,YAAW,EAAS,EAAO,IAAI,EAAO,UAAU,EACvD,EAAO,YAAW,EAAS,EAAO,IAAI,EAAO,UAAU,EACvD,EAAO,UAAS,EAAS,EAAO,MAAM,EAAO,QAAQ,EAClD,EAGT,IAAK,SAAU,CACb,IAAI,EAAsB,EAAE,QAAQ,CAIpC,OAHI,EAAO,UAAS,EAAS,EAAO,KAAK,EACrC,EAAO,MAAQ,IAAA,KAAW,EAAS,EAAO,IAAI,EAAO,IAAI,EACzD,EAAO,MAAQ,IAAA,KAAW,EAAS,EAAO,IAAI,EAAO,IAAI,EACtD,EAGT,IAAK,UACH,OAAO,EAAE,SAAS,CAEpB,IAAK,SACH,OAAO,EAAE,KAAK,EAAO,QAAiC,CAExD,IAAK,OACH,OAAO,EAAO,QAAU,EAAE,SAAS,CAErC,IAAK,QACH,OAAO,EAAE,QAAQ,CAAC,MAAM,CAE1B,QACE,OAAO,EAAE,SAAS,EAWxB,SAAgB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B,EAAG,EAAgB,IAAK,EAAI,CAC5B,EAAG,EAAgB,OAAQ,EAAO,CACnC,CAIH,MAAc,OAAO,EAAa,EAAgB,EAAgB,CAChE,MAAM,KAAK,GACR,OAAO,EAAgB,CACvB,OAAO,CACN,UAAW,KAAK,WAAW,UAC3B,MAAO,KAAK,MACZ,QAAS,KAAK,QACd,MACA,SACA,QACA,UAAW,IAAI,KAChB,CAAC,CACD,mBAAmB,CAClB,OAAQ,CACN,EAAgB,UAChB,EAAgB,MAChB,EAAgB,QAChB,EAAgB,IAChB,EAAgB,OACjB,CACD,IAAK,CACH,QACA,UAAW,IAAI,KAChB,CACF,CAAC,GCpWR,SAAgB,EACd,EACA,EACmB,CACnB,IAAM,EAAM,GAAS,KAAO,GAAQ,CAEpC,OAAO,IAAI,EAAe,EAAY,CACpC,GAAI,EAAI,GAAG,UACX,OAAQ,EAAI,OAAO,MAAM,CAAE,SAAU,EAAW,UAAW,CAAC,CAC5D,MAAO,GAAS,MAChB,QAAS,GAAS,QACnB,CAAC,CCtBJ,SAAgB,EAA8D,EAKpD,CACxB,GAAI,CAAC,EAAW,UACd,MAAU,MAAM,iCAAiC,CAEnD,GAAI,CAAC,EAAW,QAAU,OAAO,KAAK,EAAW,OAAO,CAAC,SAAW,EAClE,MAAU,MAAM,iDAAiD,CAEnE,OAAO"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.d.mts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;iBAoBgB,QAAA,CAAA,GAAY,MAAA"}
|
package/dist/plugin.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{toolkitSettings as e,toolkitViewState as t}from"./schema.mjs";function n(){return{name:`@murumets-ee/settings`,tables:{toolkitSettings:e,toolkitViewState:t},init:async n=>{let{schemaRegistry:r}=await import(`@murumets-ee/db`);r.has(`toolkit_settings`)||r.register(`toolkit_settings`,e),r.has(`toolkit_view_state`)||r.register(`toolkit_view_state`,t),n.logger.info(`Settings plugin initialized`)}}}export{n as settings};
|
|
2
|
+
//# sourceMappingURL=plugin.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.mjs","names":[],"sources":["../src/plugin.ts"],"sourcesContent":["/**\n * Settings plugin for @murumets-ee/core.\n *\n * Registers the settings Drizzle tables with the schema registry\n * so they can be discovered for migrations and queries.\n *\n * @example\n * ```typescript\n * import { defineConfig } from '@murumets-ee/core'\n * import { settings } from '@murumets-ee/settings/plugin'\n *\n * export default defineConfig({\n * plugins: [settings()],\n * })\n * ```\n */\n\nimport type { Plugin } from '@murumets-ee/core'\nimport { toolkitSettings, toolkitViewState } from './schema.js'\n\nexport function settings(): Plugin {\n return {\n name: '@murumets-ee/settings',\n tables: { toolkitSettings, toolkitViewState },\n init: async (app) => {\n const { schemaRegistry } = await import('@murumets-ee/db')\n\n if (!schemaRegistry.has('toolkit_settings')) {\n schemaRegistry.register('toolkit_settings', toolkitSettings)\n }\n if (!schemaRegistry.has('toolkit_view_state')) {\n schemaRegistry.register('toolkit_view_state', toolkitViewState)\n }\n\n app.logger.info('Settings plugin initialized')\n },\n }\n}\n"],"mappings":"qEAoBA,SAAgB,GAAmB,CACjC,MAAO,CACL,KAAM,wBACN,OAAQ,CAAE,kBAAiB,mBAAkB,CAC7C,KAAM,KAAO,IAAQ,CACnB,GAAM,CAAE,kBAAmB,MAAM,OAAO,mBAEnC,EAAe,IAAI,mBAAmB,EACzC,EAAe,SAAS,mBAAoB,EAAgB,CAEzD,EAAe,IAAI,qBAAqB,EAC3C,EAAe,SAAS,qBAAsB,EAAiB,CAGjE,EAAI,OAAO,KAAK,8BAA8B,EAEjD"}
|