insite-config 2.3.3 → 2.4.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 +1 -1
- package/README.md +94 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/package.json +46 -32
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -1,13 +1,103 @@
|
|
|
1
|
-
#
|
|
1
|
+
# insite-config
|
|
2
|
+
|
|
3
|
+
Runtime configuration storage backed by MongoDB. Define a schema with defaults, read and update values in memory, persist to a `config` collection. Changes sync automatically via MongoDB change streams.
|
|
4
|
+
|
|
5
|
+
Part of [inSite](../../README.md) — requires [insite-db](../db/README.md). MongoDB must support change streams (replica set or sharded cluster).
|
|
2
6
|
|
|
3
7
|
## Installation
|
|
4
8
|
|
|
5
9
|
```sh
|
|
6
|
-
|
|
10
|
+
npm install insite-config
|
|
7
11
|
```
|
|
8
12
|
|
|
9
|
-
Or
|
|
13
|
+
Or:
|
|
10
14
|
|
|
11
15
|
```sh
|
|
12
|
-
|
|
16
|
+
bun add insite-config
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { connect } from "insite-db";
|
|
23
|
+
import { init as initConfig } from "insite-config";
|
|
24
|
+
|
|
25
|
+
const schema = {
|
|
26
|
+
theme: { dark: false },
|
|
27
|
+
api: { rateLimit: 100 }
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const { collections } = await connect({ url: "...", name: "myapp" });
|
|
31
|
+
const config = await initConfig(collections, schema);
|
|
32
|
+
|
|
33
|
+
console.log(config.theme.dark); // false
|
|
34
|
+
await config.update("theme", { dark: true });
|
|
13
35
|
```
|
|
36
|
+
|
|
37
|
+
## API Reference
|
|
38
|
+
|
|
39
|
+
### Exports
|
|
40
|
+
|
|
41
|
+
| Export | Type | Description |
|
|
42
|
+
|--------|------|-------------|
|
|
43
|
+
| `init` | function | Initializes config instance |
|
|
44
|
+
| `UnknownConfigItemError` | class | Thrown when config item ID not in schema |
|
|
45
|
+
| `Schema` | type | `Record<string, Record<string, boolean \| number \| string \| null>>` |
|
|
46
|
+
| `Config<S>` | type | Config object returned by `init()` |
|
|
47
|
+
| `Listener<CI>` | type | `(this: CI, updatedFields, prevFields) => void \| Promise<void>` |
|
|
48
|
+
| `ConfigItemID<S>` | type | String union of config item IDs |
|
|
49
|
+
| `Updates<CI>` | type | `Partial<Omit<CI, "_u">>` |
|
|
50
|
+
| `CollectionOptions` | type | Extends insite-db CollectionOptions; `fullDocument` and `watch` fixed |
|
|
51
|
+
|
|
52
|
+
### init(collections, schema, collectionOptions?)
|
|
53
|
+
|
|
54
|
+
**Parameters:**
|
|
55
|
+
|
|
56
|
+
| Name | Type | Description |
|
|
57
|
+
|------|------|-------------|
|
|
58
|
+
| `collections` | `Collections` | From [insite-db](../db/README.md) `connect()` |
|
|
59
|
+
| `schema` | `Schema` | Object mapping config item IDs to default field values |
|
|
60
|
+
| `collectionOptions` | `CollectionOptions` | Optional. Passed to `collections.ensure()` for `config` |
|
|
61
|
+
|
|
62
|
+
**Returns:** `Promise<Config<S>>`. Singleton — subsequent calls return same instance.
|
|
63
|
+
|
|
64
|
+
### UnknownConfigItemError
|
|
65
|
+
|
|
66
|
+
Extends `Error`. `name`: `"UnknownConfigItemError"`
|
|
67
|
+
|
|
68
|
+
### Config<S>
|
|
69
|
+
|
|
70
|
+
**Indexed access:** `config[id]` — readonly config item (includes internal `_u` field)
|
|
71
|
+
|
|
72
|
+
**Methods:**
|
|
73
|
+
|
|
74
|
+
| Method | Signature | Description |
|
|
75
|
+
|--------|------------|-------------|
|
|
76
|
+
| `addListener` / `on` | `(id, listener, immediately?) => void` | Subscribe to updates. `immediately: true` calls listener once with current state |
|
|
77
|
+
| `removeListener` / `off` | `(id, listener) => void` | Unsubscribe |
|
|
78
|
+
| `update` | `(id, updates) => Promise<ConfigItem>` | Apply partial updates |
|
|
79
|
+
|
|
80
|
+
## Usage Examples
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const theme = config.theme;
|
|
84
|
+
const isDark = theme.dark;
|
|
85
|
+
|
|
86
|
+
await config.update("api", { rateLimit: 200 });
|
|
87
|
+
|
|
88
|
+
config.addListener("theme", (updated, prev) => {
|
|
89
|
+
console.log("theme changed:", updated, prev);
|
|
90
|
+
}, true);
|
|
91
|
+
config.removeListener("theme", listener);
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
**Notes:** Singleton; schema changes — removed items deleted from DB, new items created with defaults; conflict resolution via `updatedAt`.
|
|
95
|
+
|
|
96
|
+
## Related
|
|
97
|
+
|
|
98
|
+
- [insite-db](../db/README.md) — provides Collections
|
|
99
|
+
- [insite-server](../server/README.md) — uses config
|
|
100
|
+
|
|
101
|
+
## License
|
|
102
|
+
|
|
103
|
+
MIT
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import{isEmpty as g,pick as D,typeSafeObjectEntries as b,typeSafeObjectFromEntries as O}from"@nesvet/n";var m=Symbol("updatedAt");var c=class extends Error{constructor(p){super(`Unknown Config item "${p}"`)}name="UnknownConfigItemError"},C;async function j(I,p,w){if(!C){let f=new Map,l=await I.ensure("config",w),s={addListener(e,o,n){let t=this[e];if(t)n&&o.call(t,t,{...t}),f.get(t)?.add(o)??f.set(t,new Set([o]));else throw new c(e)},removeListener(e,o){let n=this[e];if(n)f.get(n)?.delete(o);else throw new c(e)},async update(e,{[m]:o,...n}){let t=this[e];if("_u"in n&&delete n["_u"],t){if(!g(n)&&(!o||t["_u"]<o)){let i={};for(let[a,d]of Object.entries(n))a in t&&t[a]!==d&&(i[a]=d);if(!g(i)){o||(Object.assign(i,{_u:Date.now()}),l.updateOne({_id:e},{$set:i}));let a=D(t,Object.keys(i));Object.assign(t,i);for(let d of f.get(t)??[])await d.call(t,i,a)}}return t}throw new c(e)}};s.on=s.addListener,s.off=s.removeListener,C=s;let y=new Map((await l.find().toArray()).map(({_id:e,...o})=>[e,o])),u=new Map,S=Date.now();for(let[e,o]of Object.entries(p)){let n=y.get(e),t={...O(b(o).map(([i,a])=>[i,n?.[i]??a])),_u:n?.["_u"]??S};s[e]=t,u.set(e,t)}await l.bulkWrite([...[...u].map(([e,o])=>({replaceOne:{filter:{_id:e},replacement:{_id:e,...o},upsert:!0}})),...[...y.keys()].filter(e=>!p[e]).map(e=>({deleteOne:{filter:{_id:e}}}))]),l.onChange(e=>{switch(e.operationType){case"update":case"replace":{let{_id:o,["_u"]:n=Date.now(),...t}=e.operationType==="replace"?e.fullDocument:e.updateDescription.updatedFields;s.update(e.documentKey._id,{...t,[m]:n})}}})}return C}export{c as UnknownConfigItemError,j as init};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["
|
|
4
|
-
"sourcesContent": ["export function noop() { /**/ }\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\ntype Value<T> = PromiseLike<T> | T;\ntype Resolve<T> = (value: Value<T>) => void;\ntype Reject = (reason?: any) => void;\n\ntype Options = {\n\tsignal?: AbortSignal;\n\ttimeout?: number;\n};\n\nconst nativesMap = new WeakMap<StatefulPromise<any>, { resolve: Resolve<any>; reject: Reject }>();\n\n\nexport class StatefulPromise<T> extends Promise<T> {\n\tconstructor(\n\t\texecutor?: (resolve: Resolve<T>, reject: Reject) => void,\n\t\toptions?: Options\n\t) {\n\t\tlet nativeResolve: Resolve<T>;\n\t\tlet nativeReject: Reject;\n\t\t\n\t\tsuper((resolve, reject) => {\n\t\t\tnativeResolve = resolve;\n\t\t\tnativeReject = reject;\n\t\t\t\n\t\t});\n\t\t\n\t\tnativesMap.set(this, { resolve: nativeResolve!, reject: nativeReject! });\n\t\t\n\t\tif (options?.signal)\n\t\t\tif (options.signal.aborted)\n\t\t\t\tthis.reject(new DOMException(\"Aborted\", \"AbortError\"));\n\t\t\telse {\n\t\t\t\tconst abortListener = () => this.reject(new DOMException(\"Aborted\", \"AbortError\"));\n\t\t\t\t\n\t\t\t\toptions.signal.addEventListener(\"abort\", abortListener);\n\t\t\t\t\n\t\t\t\tthis.finally(() => options.signal?.removeEventListener(\"abort\", abortListener));\n\t\t\t}\n\t\t\n\t\tif (typeof options?.timeout === \"number\" && Number.isFinite(options.timeout)) {\n\t\t\tconst timeout = setTimeout(() => this.reject(new DOMException(\"Timeout exceeded\", \"TimeoutError\")), options.timeout);\n\t\t\t\n\t\t\tthis.finally(() => clearTimeout(timeout));\n\t\t}\n\t\t\n\t\texecutor?.(this.resolve, this.reject);\n\t\t\n\t}\n\t\n\tisPending = true;\n\tisFulfilled = false;\n\tisRejected = false;\n\t\n\tstate: \"fulfilled\" | \"pending\" | \"rejected\" = \"pending\";\n\t\n\tresult?: T | unknown;\n\t\n\treadonly resolve = (value: Value<T>) => {\n\t\t\n\t\tif (this.isPending) {\n\t\t\tthis.isPending = false;\n\t\t\tthis.isFulfilled = true;\n\t\t\tthis.state = \"fulfilled\";\n\t\t\tthis.result = value;\n\t\t\t\n\t\t\tconst native = nativesMap.get(this);\n\t\t\t\n\t\t\tif (native) {\n\t\t\t\tnative.resolve.call(this, value);\n\t\t\t\tnativesMap.delete(this);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\treadonly reject = (reason?: any) => {\n\t\t\n\t\tif (this.isPending) {\n\t\t\tthis.isPending = false;\n\t\t\tthis.isRejected = true;\n\t\t\tthis.state = \"rejected\";\n\t\t\tthis.result = reason;\n\t\t\t\n\t\t\tconst native = nativesMap.get(this);\n\t\t\t\n\t\t\tif (native) {\n\t\t\t\tnative.reject.call(this, reason);\n\t\t\t\tnativesMap.delete(this);\n\t\t\t}\n\t\t}\n\t\t\n\t};\n\t\n\t\n\tstatic resolved<U>(value: U): StatefulPromise<U> {\n\t\treturn new StatefulPromise<U>(resolve => resolve(value));\n\t}\n\t\n\tstatic rejected(reason: unknown): StatefulPromise<never> {\n\t\treturn new StatefulPromise((_, reject) => reject(reason));\n\t}\n\t\n}\n", "import { noop } from \"./noop.js\";\nimport { StatefulPromise } from \"./StatefulPromise.js\";\n\n\ntype Callback = (...args: any[]) => unknown;// eslint-disable-line @typescript-eslint/no-explicit-any\ntype FunctionOrBoolean = (() => unknown) | boolean;\ntype Options = { leading?: FunctionOrBoolean; maxWait?: number; trailing?: FunctionOrBoolean };\n\ntype DebouncedFunction<C extends Callback> = {\n\t(this: ThisParameterType<C>, ...args: Parameters<C>): Promise<Awaited<ReturnType<C>>>;\n};\n\nexport type Debounced<C extends Callback, R extends ReturnType<C>> = DebouncedFunction<C> & {\n\tcallback: C;\n\tpromise: StatefulPromise<R>;\n\tresolve: (value: R) => void;\n\treject: (reason?: unknown) => void;\n\trun(): Promise<R>;\n\tclear(shouldRun?: boolean): Promise<void>;\n};\n\n\nexport function debounce<C extends Callback, R extends ReturnType<C>>(callback: C, limit = 0, options: Options = {}) {\n\tlet { leading = false, trailing = true } = options;\n\tconst { maxWait = Infinity } = options;\n\t\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\tlet maxWaitTimeout: ReturnType<typeof setTimeout> | undefined;\n\tlet end: number | undefined;\n\tlet context: ThisParameterType<C>;\n\tlet args: unknown[];\n\tlet initial: FunctionOrBoolean;\n\tlet final: FunctionOrBoolean;\n\tlet result: R;\n\t\n\tconst expired = async () => {\n\t\t\n\t\tconst n = Date.now();\n\t\t\n\t\tif (n >= end!) {\n\t\t\ttimeout = undefined;\n\t\t\tend = undefined;\n\t\t\t\n\t\t\tclearTimeout(maxWaitTimeout);\n\t\t\tmaxWaitTimeout = undefined;\n\t\t\t\n\t\t\tif (typeof final == \"function\")\n\t\t\t\tawait final();\n\t\t\t\n\t\t\tdebounced.resolve(result);\n\t\t\t\n\t\t\tinitial = leading;\n\t\t} else {\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = setTimeout(expired, end! - n);\n\t\t}\n\t\t\n\t};\n\t\n\tconst maxWaitExpired = Number.isFinite(maxWait) ? () => {\n\t\t\n\t\tif (final === run)\n\t\t\tfinal = false;\n\t\t\n\t\trun();\n\t\t\n\t\tmaxWaitTimeout = setTimeout(maxWaitExpired as TimerHandler, maxWait);\n\t\t\n\t} : null;\n\t\n\tasync function run() {\n\t\ttry {\n\t\t\tresult = await callback.apply(context, args) as R;\n\t\t\t\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tdebounced.reject(error);\n\t\t\t\n\t\t\tthrow error;\n\t\t}\n\t}\n\t\n\tif (leading && typeof leading == \"boolean\")\n\t\tleading = run;\n\tinitial = leading;\n\t\n\tif (trailing && typeof trailing == \"boolean\")\n\t\ttrailing = run;\n\tfinal = trailing;\n\t\n\tconst debounced: Debounced<C, R> = Object.assign(function (..._args) {\n\t\targs = _args;\n\t\tcontext = this;// eslint-disable-line no-invalid-this\n\t\t\n\t\tend = Date.now() + limit;\n\t\tfinal = trailing;\n\t\t\n\t\tif (!debounced.promise.isPending)\n\t\t\tdebounced.promise = new StatefulPromise<R>((resolve, reject) => {\n\t\t\t\tdebounced.resolve = resolve;\n\t\t\t\tdebounced.reject = reject;\n\t\t\t\t\n\t\t\t\tif (typeof initial == \"function\") {\n\t\t\t\t\tinitial();\n\t\t\t\t\t\n\t\t\t\t\tinitial = false;\n\t\t\t\t\t\n\t\t\t\t\tif (final === run)\n\t\t\t\t\t\tfinal = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!timeout) {\n\t\t\t\t\ttimeout = setTimeout(expired, limit);\n\t\t\t\t\t\n\t\t\t\t\tif (maxWaitExpired)\n\t\t\t\t\t\tmaxWaitTimeout = setTimeout(maxWaitExpired, maxWait);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t});\n\t\t\n\t\treturn debounced.promise;\n\t} as DebouncedFunction<C>, {\n\t\tcallback,\n\t\tpromise: StatefulPromise.resolved(undefined as unknown as R),\n\t\tresolve: noop,\n\t\treject: noop,\n\t\trun,\n\t\tclear: async (shouldRun?: boolean) => {\n\t\t\t\n\t\t\tclearTimeout(timeout);\n\t\t\ttimeout = undefined;\n\t\t\t\n\t\t\tclearTimeout(maxWaitTimeout);\n\t\t\tmaxWaitTimeout = undefined;\n\t\t\t\n\t\t\tdebounced.resolve(shouldRun ? await run() : result);\n\t\t\t\n\t\t}\n\t});\n\t\n\treturn debounced;\n}\n\n\ndebounce.noop = Object.assign(() => { /**/ }, {\n\tcallback: noop,\n\tpromise: StatefulPromise.resolved(undefined), // eslint-disable-line unicorn/no-useless-undefined\n\tresolve: noop,\n\treject: noop,\n\trun: noop,\n\tclear: noop\n}) as Debounced<() => void, void>;\n\n\nexport function throttle(callback: Callback, limit?: number, options?: Options) {\n\treturn debounce(callback, limit, {\n\t\tmaxWait: limit,\n\t\tleading: true,\n\t\ttrailing: true,\n\t\t...options\n\t});\n}\n", "export function isEmpty(object: object) {\n\tfor (const _ in object)// eslint-disable-line guard-for-in, no-unreachable-loop\n\t\treturn false;\n\t\n\treturn true;\n}\n", "export function howmuch(number: [] | number, one: string, two: string, five: boolean | string, shouldPrintNumber = true) {\n\tif (Array.isArray(number))\n\t\tnumber = number.length;\n\t\n\tif (typeof five != \"string\") {\n\t\tshouldPrintNumber = five ?? true;\n\t\tfive = two;\n\t}\n\t\n\t\n\treturn (shouldPrintNumber ? `${number}\u00A0` : \"\") + howmuch.raw(number, one, two, five);\n}\n\nhowmuch.raw = (number: number, one: string, two: string, five = two) => {\n\tnumber = Math.abs(number);\n\tconst u = number % 10;\n\tconst d = number % 100;\n\t\n\treturn (\n\t\t(u === 1 && d !== 11) ?\n\t\t\tone :\n\t\t\t((u >= 2 && u <= 4) && !(d >= 12 && d <= 15)) ?\n\t\t\t\ttwo :\n\t\t\t\tfive\n\t);\n};\n", "export function pick<O extends object, K extends keyof O>(object: O, keys: K[]) {\n\t\n\tconst picked: Partial<Pick<O, K>> = {};\n\t\n\tfor (const key of keys)\n\t\tif (key in object)\n\t\t\tpicked[key] = object[key];\n\t\n\treturn picked as Pick<O, K>;\n}\n", "export function typeSafeObjectEntries<T extends Record<PropertyKey, unknown>>(obj: T) {\n\treturn Object.entries(obj) as { [K in keyof T]: [K, T[K]] }[keyof T][];\n}\n", "export function typeSafeObjectFromEntries<const T extends ReadonlyArray<readonly [PropertyKey, unknown]>>(entries: T) {\n\treturn Object.fromEntries(entries) as { [K in T[number] as K[0]]: K[1] };\n}\n", "export const updatedAtKey = \"_u\";\nexport const updatedAtSymbol = Symbol(\"updatedAt\");\n", "import {\n\tisEmpty,\n\tpick,\n\ttypeSafeObjectEntries,\n\ttypeSafeObjectFromEntries\n} from \"@nesvet/n\";\nimport type { Collections } from \"insite-db\";\nimport { updatedAtKey, updatedAtSymbol } from \"./symbols\";\nimport type {\n\tCollectionOptions,\n\tConfig,\n\tConfigItemID,\n\tListener,\n\tSchema,\n\tUpdates\n} from \"./types\";\n\n\nexport class UnknownConfigItemError extends Error {\n\tconstructor(_id: string) {\n\t\tsuper(`Unknown Config item \"${_id}\"`);\n\t\t\n\t}\n\t\n\tname = \"UnknownConfigItemError\";\n\t\n}\n\n\nlet initedConfig: Config<Schema>;\n\nexport async function init<S extends Schema>(collections: Collections, schema: S, collectionOptions?: CollectionOptions) {\n\t\n\tif (!initedConfig) {\n\t\ttype ID = ConfigItemID<S>;\n\t\ttype CI = Config<S>[ID];\n\t\t\n\t\tconst updateListeners = new Map<CI, Set<Listener<CI>>>();\n\t\t\n\t\ttype CIDoc = CI & { _id: ID };\n\t\tconst collection = await collections.ensure<CIDoc>(\"config\", collectionOptions);\n\t\t\n\t\tconst config: Config<S> = {\n\t\t\t\n\t\t\taddListener(_id, listener: Listener<CI>, immediately) {\n\t\t\t\tconst item = this[_id];\n\t\t\t\t\n\t\t\t\tif (item) {\n\t\t\t\t\tif (immediately)\n\t\t\t\t\t\tvoid listener.call(item, item, { ...item });\n\t\t\t\t\t\n\t\t\t\t\tupdateListeners.get(item)?.add(listener) ??\n\t\t\t\t\tupdateListeners.set(item, new Set([ listener ]));\n\t\t\t\t} else\n\t\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t},\n\t\t\t\n\t\t\tremoveListener(_id, listener: Listener<CI>) {\n\t\t\t\tconst item = this[_id];\n\t\t\t\t\n\t\t\t\tif (item)\n\t\t\t\t\tupdateListeners.get(item)?.delete(listener);\n\t\t\t\telse\n\t\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t},\n\t\t\t\n\t\t\tasync update(_id, { [updatedAtSymbol]: updatedAt, ...updates }) {\n\t\t\t\tconst item = this[_id] as CI;\n\t\t\t\t\n\t\t\t\tif (updatedAtKey in updates)\n\t\t\t\t\tdelete updates[updatedAtKey];\n\t\t\t\t\n\t\t\t\tif (item) {\n\t\t\t\t\tif (!isEmpty(updates) && (!updatedAt || item[updatedAtKey] < updatedAt)) {\n\t\t\t\t\t\tconst updatedFields: Partial<CI> = {};\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (const [ key, value ] of Object.entries(updates) as [ keyof CI, CI[keyof CI] ][])\n\t\t\t\t\t\t\tif (key in item && item[key] !== value)\n\t\t\t\t\t\t\t\tupdatedFields[key] = value;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!isEmpty(updatedFields)) {\n\t\t\t\t\t\t\tif (!updatedAt) {\n\t\t\t\t\t\t\t\tObject.assign(updatedFields, { [updatedAtKey]: Date.now() });\n\t\t\t\t\t\t\t\tvoid collection.updateOne({ _id }, { $set: updatedFields as Partial<CIDoc> });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tconst prevFields = pick(item, Object.keys(updatedFields)) as Partial<CI>;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tObject.assign(item, updatedFields);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (const listener of updateListeners.get(item) ?? [])\n\t\t\t\t\t\t\t\tawait listener.call(item, updatedFields, prevFields);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\treturn item;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t}\n\t\t\t\n\t\t} as Config<S>;\n\t\t\n\t\tconfig.on = config.addListener;\n\t\tconfig.off = config.removeListener;\n\t\t\n\t\tinitedConfig = config;// eslint-disable-line require-atomic-updates\n\t\t\n\t\t\n\t\tconst collectionMap = new Map((await collection.find().toArray()).map(({ _id, ...props }) => [ _id as ID, props as CI ]));\n\t\t\n\t\tconst itemsMap = new Map<ID, CI>();\n\t\t\n\t\tconst initialUpdatedAt = Date.now();\n\t\t\n\t\tfor (const [ _id, props ] of Object.entries(schema) as [ID, S[keyof S]][]) {\n\t\t\tconst collectionItem = collectionMap.get(_id);\n\t\t\t\n\t\t\tconst item = {\n\t\t\t\t...typeSafeObjectFromEntries(\n\t\t\t\t\ttypeSafeObjectEntries(props).map(([ key, value ]) =>\n\t\t\t\t\t\t[ key, collectionItem?.[key] ?? value ]\n\t\t\t\t\t)\n\t\t\t\t),\n\t\t\t\t[updatedAtKey]: collectionItem?.[updatedAtKey] ?? initialUpdatedAt\n\t\t\t} as CI;\n\t\t\t\n\t\t\tconfig[_id] = item;\n\t\t\t\n\t\t\titemsMap.set(_id, item);\n\t\t}\n\t\t\n\t\t\n\t\tawait collection.bulkWrite([\n\t\t\t...[ ...itemsMap ].map(([ _id, item ]) => ({ replaceOne: { filter: { _id }, replacement: { _id, ...item }, upsert: true } })),\n\t\t\t...[ ...collectionMap.keys() ].filter(_id => !schema[_id]).map(_id => ({ deleteOne: { filter: { _id } } }))\n\t\t]);\n\t\t\n\t\tcollection.onChange(next => {\n\t\t\tswitch (next.operationType) {\n\t\t\t\tcase \"update\":\n\t\t\t\tcase \"replace\": {\n\t\t\t\t\tconst {\n\t\t\t\t\t\t_id: _,\n\t\t\t\t\t\t[updatedAtKey]: updatedAt = Date.now(),\n\t\t\t\t\t\t...restProps\n\t\t\t\t\t} = next.operationType === \"replace\" ? next.fullDocument : next.updateDescription.updatedFields!;\n\t\t\t\t\t\n\t\t\t\t\tvoid config.update(next.documentKey._id as unknown as ID, {\n\t\t\t\t\t\t...restProps,\n\t\t\t\t\t\t[updatedAtSymbol]: updatedAt\n\t\t\t\t\t} as Updates<CI>);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t});\n\t\t\n\t}\n\t\n\treturn initedConfig as Config<S>;\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["
|
|
3
|
+
"sources": ["../src/init.ts", "../src/symbols.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n\tisEmpty,\n\tpick,\n\ttypeSafeObjectEntries,\n\ttypeSafeObjectFromEntries\n} from \"@nesvet/n\";\nimport type { Collections } from \"insite-db\";\nimport { updatedAtKey, updatedAtSymbol } from \"./symbols\";\nimport type {\n\tCollectionOptions,\n\tConfig,\n\tConfigItemID,\n\tListener,\n\tSchema,\n\tUpdates\n} from \"./types\";\n\n\nexport class UnknownConfigItemError extends Error {\n\tconstructor(_id: string) {\n\t\tsuper(`Unknown Config item \"${_id}\"`);\n\t\t\n\t}\n\t\n\tname = \"UnknownConfigItemError\";\n\t\n}\n\n\nlet initedConfig: Config<Schema>;\n\nexport async function init<S extends Schema>(collections: Collections, schema: S, collectionOptions?: CollectionOptions) {\n\t\n\tif (!initedConfig) {\n\t\ttype ID = ConfigItemID<S>;\n\t\ttype CI = Config<S>[ID];\n\t\t\n\t\tconst updateListeners = new Map<CI, Set<Listener<CI>>>();\n\t\t\n\t\ttype CIDoc = CI & { _id: ID };\n\t\tconst collection = await collections.ensure<CIDoc>(\"config\", collectionOptions);\n\t\t\n\t\tconst config: Config<S> = {\n\t\t\t\n\t\t\taddListener(_id, listener: Listener<CI>, immediately) {\n\t\t\t\tconst item = this[_id];\n\t\t\t\t\n\t\t\t\tif (item) {\n\t\t\t\t\tif (immediately)\n\t\t\t\t\t\tvoid listener.call(item, item, { ...item });\n\t\t\t\t\t\n\t\t\t\t\tupdateListeners.get(item)?.add(listener) ??\n\t\t\t\t\tupdateListeners.set(item, new Set([ listener ]));\n\t\t\t\t} else\n\t\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t},\n\t\t\t\n\t\t\tremoveListener(_id, listener: Listener<CI>) {\n\t\t\t\tconst item = this[_id];\n\t\t\t\t\n\t\t\t\tif (item)\n\t\t\t\t\tupdateListeners.get(item)?.delete(listener);\n\t\t\t\telse\n\t\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t},\n\t\t\t\n\t\t\tasync update(_id, { [updatedAtSymbol]: updatedAt, ...updates }) {\n\t\t\t\tconst item = this[_id] as CI;\n\t\t\t\t\n\t\t\t\tif (updatedAtKey in updates)\n\t\t\t\t\tdelete updates[updatedAtKey];\n\t\t\t\t\n\t\t\t\tif (item) {\n\t\t\t\t\tif (!isEmpty(updates) && (!updatedAt || item[updatedAtKey] < updatedAt)) {\n\t\t\t\t\t\tconst updatedFields: Partial<CI> = {};\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (const [ key, value ] of Object.entries(updates) as [ keyof CI, CI[keyof CI] ][])\n\t\t\t\t\t\t\tif (key in item && item[key] !== value)\n\t\t\t\t\t\t\t\tupdatedFields[key] = value;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!isEmpty(updatedFields)) {\n\t\t\t\t\t\t\tif (!updatedAt) {\n\t\t\t\t\t\t\t\tObject.assign(updatedFields, { [updatedAtKey]: Date.now() });\n\t\t\t\t\t\t\t\tvoid collection.updateOne({ _id }, { $set: updatedFields as Partial<CIDoc> });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tconst prevFields = pick(item, Object.keys(updatedFields)) as Partial<CI>;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tObject.assign(item, updatedFields);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (const listener of updateListeners.get(item) ?? [])\n\t\t\t\t\t\t\t\tawait listener.call(item, updatedFields, prevFields);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\treturn item;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrow new UnknownConfigItemError(_id);\n\t\t\t}\n\t\t\t\n\t\t} as Config<S>;\n\t\t\n\t\tconfig.on = config.addListener;\n\t\tconfig.off = config.removeListener;\n\t\t\n\t\tinitedConfig = config;// eslint-disable-line require-atomic-updates\n\t\t\n\t\t\n\t\tconst collectionMap = new Map((await collection.find().toArray()).map(({ _id, ...props }) => [ _id as ID, props as CI ]));\n\t\t\n\t\tconst itemsMap = new Map<ID, CI>();\n\t\t\n\t\tconst initialUpdatedAt = Date.now();\n\t\t\n\t\tfor (const [ _id, props ] of Object.entries(schema) as [ID, S[keyof S]][]) {\n\t\t\tconst collectionItem = collectionMap.get(_id);\n\t\t\t\n\t\t\tconst item = {\n\t\t\t\t...typeSafeObjectFromEntries(\n\t\t\t\t\ttypeSafeObjectEntries(props).map(([ key, value ]) =>\n\t\t\t\t\t\t[ key, collectionItem?.[key] ?? value ]\n\t\t\t\t\t)\n\t\t\t\t),\n\t\t\t\t[updatedAtKey]: collectionItem?.[updatedAtKey] ?? initialUpdatedAt\n\t\t\t} as CI;\n\t\t\t\n\t\t\tconfig[_id] = item;\n\t\t\t\n\t\t\titemsMap.set(_id, item);\n\t\t}\n\t\t\n\t\t\n\t\tawait collection.bulkWrite([\n\t\t\t...[ ...itemsMap ].map(([ _id, item ]) => ({ replaceOne: { filter: { _id }, replacement: { _id, ...item }, upsert: true } })),\n\t\t\t...[ ...collectionMap.keys() ].filter(_id => !schema[_id]).map(_id => ({ deleteOne: { filter: { _id } } }))\n\t\t]);\n\t\t\n\t\tcollection.onChange(next => {\n\t\t\tswitch (next.operationType) {\n\t\t\t\tcase \"update\":\n\t\t\t\tcase \"replace\": {\n\t\t\t\t\tconst {\n\t\t\t\t\t\t_id: _,\n\t\t\t\t\t\t[updatedAtKey]: updatedAt = Date.now(),\n\t\t\t\t\t\t...restProps\n\t\t\t\t\t} = next.operationType === \"replace\" ? next.fullDocument : next.updateDescription.updatedFields!;\n\t\t\t\t\t\n\t\t\t\t\tvoid config.update(next.documentKey._id as unknown as ID, {\n\t\t\t\t\t\t...restProps,\n\t\t\t\t\t\t[updatedAtSymbol]: updatedAt\n\t\t\t\t\t} as Updates<CI>);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t});\n\t\t\n\t}\n\t\n\treturn initedConfig as Config<S>;\n}\n", "export const updatedAtKey = \"_u\";\nexport const updatedAtSymbol = Symbol(\"updatedAt\");\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["isEmpty", "pick", "typeSafeObjectEntries", "typeSafeObjectFromEntries", "updatedAtSymbol", "UnknownConfigItemError", "_id", "initedConfig", "init", "collections", "schema", "collectionOptions", "updateListeners", "collection", "config", "listener", "immediately", "item", "updatedAtSymbol", "updatedAt", "updates", "isEmpty", "updatedFields", "key", "value", "prevFields", "pick", "collectionMap", "props", "itemsMap", "initialUpdatedAt", "collectionItem", "typeSafeObjectFromEntries", "typeSafeObjectEntries", "next", "_", "restProps"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,34 +1,48 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
2
|
+
"name": "insite-config",
|
|
3
|
+
"version": "2.4.0",
|
|
4
|
+
"description": "Configuration loader for inSite server",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"insite",
|
|
7
|
+
"config",
|
|
8
|
+
"server"
|
|
9
|
+
],
|
|
10
|
+
"homepage": "https://github.com/nesvet/insite#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/nesvet/insite/issues"
|
|
13
|
+
},
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "https://github.com/nesvet/insite.git",
|
|
17
|
+
"directory": "packages/config"
|
|
18
|
+
},
|
|
19
|
+
"funding": {
|
|
20
|
+
"type": "patreon",
|
|
21
|
+
"url": "https://www.patreon.com/nesvet"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"author": "Eugene Nesvetaev <dev@nesvet.dev> (https://nesvet.dev/)",
|
|
25
|
+
"type": "module",
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"module": "./dist/index.js",
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"README.md",
|
|
31
|
+
"LICENSE"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "bun .conveyer.js",
|
|
35
|
+
"postbuild": "tsc -p .",
|
|
36
|
+
"clean": "rm -rf dist",
|
|
37
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
38
|
+
"typecheck": "tsc --noEmit"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@nesvet/n": "^1.2.1",
|
|
42
|
+
"insite-db": "^2.4.0"
|
|
43
|
+
},
|
|
44
|
+
"packageManager": "bun@1.3.9",
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=20.0.0"
|
|
47
|
+
}
|
|
34
48
|
}
|