@selfhelp/shared 1.0.3 → 1.0.4

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.
@@ -0,0 +1,209 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * SDK contract version. Plugins declare which API they target in
7
+ * `plugin.json` under `pluginApiVersion`. The host installer compares
8
+ * declarations against this constant.
9
+ *
10
+ * Versioning rules:
11
+ * - patch (1.0.0 -> 1.0.1) — additive SDK fix, no contract change.
12
+ * - minor (1.0.x -> 1.1.0) — additive SDK feature.
13
+ * - major (1.x -> 2.0) — breaking SDK change.
14
+ *
15
+ * Independent from the npm `version` of `@selfhelp/shared`.
16
+ */
17
+ export const PLUGIN_API_VERSION = '1.0' as const;
18
+
19
+ export interface ISemver {
20
+ major: number;
21
+ minor: number;
22
+ patch: number;
23
+ prerelease?: string;
24
+ }
25
+
26
+ const SEMVER_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
27
+
28
+ export function parseSemver(version: string): ISemver {
29
+ const match = SEMVER_REGEX.exec(version);
30
+ if (!match) {
31
+ throw new Error(`[plugin-sdk] not a valid semver: '${version}'.`);
32
+ }
33
+ return {
34
+ major: Number(match[1]),
35
+ minor: Number(match[2]),
36
+ patch: Number(match[3]),
37
+ prerelease: match[4],
38
+ };
39
+ }
40
+
41
+ export function compareSemver(a: string, b: string): number {
42
+ const pa = parseSemver(a);
43
+ const pb = parseSemver(b);
44
+ if (pa.major !== pb.major) return pa.major - pb.major;
45
+ if (pa.minor !== pb.minor) return pa.minor - pb.minor;
46
+ if (pa.patch !== pb.patch) return pa.patch - pb.patch;
47
+ if (pa.prerelease && pb.prerelease) return pa.prerelease.localeCompare(pb.prerelease);
48
+ if (pa.prerelease) return -1;
49
+ if (pb.prerelease) return 1;
50
+ return 0;
51
+ }
52
+
53
+ /**
54
+ * Very small npm-style range matcher supporting `=`, `>=`, `<=`, `>`,
55
+ * `<`, `^`, `~`, and the simple multi-clause syntax used by
56
+ * `plugin.json` compatibility fields. Not a full semver implementation;
57
+ * the backend uses Composer's resolver for actual install-time checks.
58
+ */
59
+ export function satisfiesSemverRange(version: string, range: string): boolean {
60
+ const v = parseSemver(version);
61
+ return range
62
+ .split('||')
63
+ .some((clause) => clause
64
+ .trim()
65
+ .split(/\s+/)
66
+ .every((part) => matchSingle(v, part.trim())));
67
+ }
68
+
69
+ function matchSingle(v: ISemver, part: string): boolean {
70
+ if (!part) return true;
71
+ if (part === '*' || part === 'x') return true;
72
+ if (part.startsWith('^')) {
73
+ const target = parseSemver(part.slice(1));
74
+ if (target.major === 0) {
75
+ if (target.minor === 0) return v.major === 0 && v.minor === 0 && v.patch === target.patch;
76
+ return v.major === 0 && v.minor === target.minor && (v.patch > target.patch || (v.patch === target.patch && !v.prerelease));
77
+ }
78
+ return v.major === target.major && compareSemverObj(v, target) >= 0;
79
+ }
80
+ if (part.startsWith('~')) {
81
+ const target = parseSemver(part.slice(1));
82
+ return v.major === target.major && v.minor === target.minor && v.patch >= target.patch;
83
+ }
84
+ if (part.startsWith('>=')) return compareSemverObj(v, parseSemver(part.slice(2).trim())) >= 0;
85
+ if (part.startsWith('<=')) return compareSemverObj(v, parseSemver(part.slice(2).trim())) <= 0;
86
+ if (part.startsWith('>')) return compareSemverObj(v, parseSemver(part.slice(1).trim())) > 0;
87
+ if (part.startsWith('<')) return compareSemverObj(v, parseSemver(part.slice(1).trim())) < 0;
88
+ if (part.startsWith('=')) return compareSemverObj(v, parseSemver(part.slice(1).trim())) === 0;
89
+ return compareSemverObj(v, parseSemver(part)) === 0;
90
+ }
91
+
92
+ function compareSemverObj(a: ISemver, b: ISemver): number {
93
+ if (a.major !== b.major) return a.major - b.major;
94
+ if (a.minor !== b.minor) return a.minor - b.minor;
95
+ if (a.patch !== b.patch) return a.patch - b.patch;
96
+ if (a.prerelease && b.prerelease) return a.prerelease.localeCompare(b.prerelease);
97
+ if (a.prerelease) return -1;
98
+ if (b.prerelease) return 1;
99
+ return 0;
100
+ }
101
+
102
+ /**
103
+ * Non-throwing version of {@see assertPluginApiVersion} — returns true
104
+ * when the plugin's declared `pluginApiVersion` is compatible with the
105
+ * host SDK. Used by the frontend `PluginRuntime` so an incompatible
106
+ * plugin is skipped (and logged) instead of crashing the host shell.
107
+ */
108
+ export function isPluginApiCompatible(required: string, host: string = PLUGIN_API_VERSION): boolean {
109
+ const [reqMajor, reqMinor] = required.split('.').map((p) => Number(p));
110
+ const [hostMajor, hostMinor] = host.split('.').map((p) => Number(p));
111
+ if (Number.isNaN(reqMajor) || Number.isNaN(reqMinor) || Number.isNaN(hostMajor) || Number.isNaN(hostMinor)) {
112
+ return false;
113
+ }
114
+ if (hostMajor !== reqMajor) return false;
115
+ return hostMinor >= reqMinor;
116
+ }
117
+
118
+ /**
119
+ * Throw if the plugin's required `pluginApiVersion` is not compatible
120
+ * with this SDK's `PLUGIN_API_VERSION`. SDK promises:
121
+ * - same major required.
122
+ * - host minor >= plugin's required minor.
123
+ */
124
+ export function assertPluginApiVersion(required: string): void {
125
+ const [reqMajor, reqMinor] = required.split('.').map((p) => Number(p));
126
+ const [hostMajor, hostMinor] = PLUGIN_API_VERSION.split('.').map((p) => Number(p));
127
+ if (Number.isNaN(reqMajor) || Number.isNaN(reqMinor)) {
128
+ throw new Error(`[plugin-sdk] invalid pluginApiVersion '${required}'.`);
129
+ }
130
+ if (hostMajor !== reqMajor) {
131
+ throw new Error(
132
+ `[plugin-sdk] incompatible pluginApiVersion: plugin wants '${required}' but host is '${PLUGIN_API_VERSION}'.`,
133
+ );
134
+ }
135
+ if (hostMinor < reqMinor) {
136
+ throw new Error(
137
+ `[plugin-sdk] host SDK too old for plugin: plugin wants '${required}', host is '${PLUGIN_API_VERSION}'.`,
138
+ );
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Throw if the running CMS version is not in the plugin's declared
144
+ * compatibility range.
145
+ */
146
+ export function assertCmsCompatibility(cmsVersion: string, range: string): void {
147
+ if (!satisfiesSemverRange(cmsVersion, range)) {
148
+ throw new Error(
149
+ `[plugin-sdk] CMS version '${cmsVersion}' does not satisfy plugin compatibility range '${range}'.`,
150
+ );
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Enforce the plugin version-semantics rule:
156
+ * - patch (1.0.0 -> 1.0.1) -- no DB change, no migration shipped.
157
+ * - minor (1.0.x -> 1.1.0) -- always carries a DB change/migration.
158
+ * - major (1.x -> 2.x) -- breaking change.
159
+ *
160
+ * The host installer + plugin CI call this with the lock-file `version`
161
+ * and the candidate `version` to verify that what is being shipped
162
+ * matches the semver bump.
163
+ */
164
+ export function assertPluginVersionSemantics(
165
+ prevVersion: string | undefined,
166
+ nextVersion: string,
167
+ options: { hasMigration: boolean },
168
+ ): void {
169
+ const next = parseSemver(nextVersion);
170
+
171
+ if (!prevVersion) {
172
+ // first install — any version, but if hasMigration=false and
173
+ // it claims to be 0.0.x we cannot really verify the rule.
174
+ return;
175
+ }
176
+
177
+ const prev = parseSemver(prevVersion);
178
+
179
+ const bumpedMajor = next.major > prev.major;
180
+ const bumpedMinor = next.minor > prev.minor && next.major === prev.major;
181
+ const bumpedPatch = next.patch > prev.patch && next.minor === prev.minor && next.major === prev.major;
182
+
183
+ if (bumpedMajor) {
184
+ // breaking — migration optional but allowed.
185
+ return;
186
+ }
187
+ if (bumpedMinor) {
188
+ if (!options.hasMigration) {
189
+ throw new Error(
190
+ `[plugin-sdk] plugin minor bump (${prevVersion} -> ${nextVersion}) must ship a DB migration.`,
191
+ );
192
+ }
193
+ return;
194
+ }
195
+ if (bumpedPatch) {
196
+ if (options.hasMigration) {
197
+ throw new Error(
198
+ `[plugin-sdk] plugin patch bump (${prevVersion} -> ${nextVersion}) must not ship a DB migration.`,
199
+ );
200
+ }
201
+ return;
202
+ }
203
+
204
+ if (compareSemver(nextVersion, prevVersion) <= 0) {
205
+ throw new Error(
206
+ `[plugin-sdk] plugin version did not increase: prev '${prevVersion}', next '${nextVersion}'.`,
207
+ );
208
+ }
209
+ }
@@ -3,35 +3,92 @@ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
3
  SPDX-License-Identifier: MPL-2.0
4
4
  */
5
5
  import type { TStyleName } from '../types/styles/unknown';
6
- import { STYLE_REGISTRY } from './styles.registry';
6
+ import {
7
+ BASE_STYLE_REGISTRY,
8
+ getMergedStyleRegistry,
9
+ getPluginStyleRegistry,
10
+ type IPluginStyleRegistryEntry,
11
+ type IStyleRegistryEntry,
12
+ } from './styles.registry';
7
13
 
8
14
  export * from './styles.registry';
9
15
 
16
+ /**
17
+ * Open style-name type: a core `TStyleName` literal OR any plugin style
18
+ * name. The `string & {}` keeps autocomplete for core names while still
19
+ * accepting plugin keys at type level.
20
+ */
21
+ export type TAnyStyleName = TStyleName | (string & {});
22
+
10
23
  /**
11
24
  * Helper for renderers: produces a typed map shape that requires every
12
- * registry key to be implemented. Pass this to your dispatcher and let
13
- * TypeScript enforce 100% style coverage.
25
+ * core registry key to be implemented. Pass this to your dispatcher and
26
+ * let TypeScript enforce 100% style coverage for core styles. Plugin
27
+ * styles are dispatched through a separate `IPluginStyleImplMap`.
14
28
  *
15
29
  * type IStyleImpls = TStyleImplMap<React.FC<{ style: TStyle }>>;
16
30
  *
17
- * `keyof TStyleImplMap<...>` is exactly the union of style names.
31
+ * `keyof TStyleImplMap<...>` is exactly the union of *core* style names.
18
32
  */
19
33
  export type TStyleImplMap<TImpl> = {
20
34
  readonly [K in TStyleName]: TImpl;
21
35
  };
22
36
 
23
37
  /**
24
- * Get an entry from the registry safely. Returns undefined if the
25
- * style_name isn't registered (the renderer should fall back to
26
- * UnknownStyle).
38
+ * Runtime-extensible map: plugin-contributed style implementations
39
+ * keyed by plugin style name. Renderers merge this with their
40
+ * `TStyleImplMap<TImpl>` at boot.
41
+ */
42
+ export type TPluginStyleImplMap<TImpl> = Record<string, TImpl>;
43
+
44
+ /**
45
+ * Get an entry from the **core** registry. Returns undefined if the
46
+ * `style_name` is not a known core style. Use `getRegistryEntryAny()`
47
+ * to also resolve plugin styles.
48
+ */
49
+ export function getRegistryEntry(name: string): IStyleRegistryEntry | undefined {
50
+ if (Object.prototype.hasOwnProperty.call(BASE_STYLE_REGISTRY, name)) {
51
+ return (BASE_STYLE_REGISTRY as Record<string, IStyleRegistryEntry>)[name];
52
+ }
53
+ return undefined;
54
+ }
55
+
56
+ /**
57
+ * Get an entry from either the core or the plugin registry. Returns
58
+ * undefined if the `style_name` is not registered (the renderer should
59
+ * fall back to `UnknownStyle`).
27
60
  */
28
- export function getRegistryEntry(name: string): (typeof STYLE_REGISTRY)[TStyleName] | undefined {
29
- return (STYLE_REGISTRY as Record<string, (typeof STYLE_REGISTRY)[TStyleName]>)[name];
61
+ export function getRegistryEntryAny(
62
+ name: string,
63
+ ): IStyleRegistryEntry | IPluginStyleRegistryEntry | undefined {
64
+ const merged = getMergedStyleRegistry();
65
+ return merged[name];
30
66
  }
31
67
 
32
68
  /**
33
- * Type guard to narrow a string to TStyleName.
69
+ * Type guard to narrow a string to `TStyleName` (core styles only).
34
70
  */
35
71
  export function isKnownStyleName(name: string): name is TStyleName {
36
- return Object.prototype.hasOwnProperty.call(STYLE_REGISTRY, name);
72
+ return Object.prototype.hasOwnProperty.call(BASE_STYLE_REGISTRY, name);
37
73
  }
74
+
75
+ /**
76
+ * Type guard for any registered style — core or plugin.
77
+ */
78
+ export function isRegisteredStyleName(name: string): boolean {
79
+ if (Object.prototype.hasOwnProperty.call(BASE_STYLE_REGISTRY, name)) {
80
+ return true;
81
+ }
82
+ return Object.prototype.hasOwnProperty.call(getPluginStyleRegistry(), name);
83
+ }
84
+
85
+ /**
86
+ * For a known plugin style, return the owning `pluginId`. Useful for
87
+ * mobile to construct the "Open on web" fallback link when the plugin
88
+ * style is not bundled in the current build.
89
+ */
90
+ export function getStylePluginId(name: string): string | undefined {
91
+ const plugin = getPluginStyleRegistry()[name];
92
+ return plugin?.pluginId;
93
+ }
94
+
@@ -3,16 +3,33 @@ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
3
  SPDX-License-Identifier: MPL-2.0
4
4
  */
5
5
  /**
6
- * STYLE_REGISTRY — single source of truth for every supported user-facing
7
- * style. Both the web and mobile renderers import this map and TypeScript
8
- * forces them to provide an implementation for each key (see
9
- * `createStyleImplMap` in `index.ts`).
6
+ * Style registry — the runtime catalog of every CMS style the SelfHelp
7
+ * ecosystem can render.
10
8
  *
11
- * Adding a new style:
9
+ * It has two halves:
10
+ *
11
+ * `BASE_STYLE_REGISTRY` — closed, compile-time-constant catalog of core
12
+ * styles shipped by this package. Used to derive the `TStyleName`
13
+ * union and to give renderers compile-time coverage of every core
14
+ * style.
15
+ *
16
+ * `PLUGIN_STYLE_REGISTRY` — runtime-mutable map populated by plugin
17
+ * packages through `extendStyleRegistry()` at boot. Plugin entries
18
+ * are tagged with their `pluginId` so the renderer can show
19
+ * "Open on web" fallbacks for backend-declared styles that the
20
+ * current build does not bundle.
21
+ *
22
+ * Adding a *core* style:
12
23
  * 1. Add the per-style interface in `src/types/styles/<group>.ts`.
13
24
  * 2. Extend `TStyle` in `src/types/styles/unknown.ts`.
14
- * 3. Add the entry below.
25
+ * 3. Add the entry to `BASE_STYLE_REGISTRY` below.
15
26
  * 4. Both apps will fail to compile until they add an impl.
27
+ *
28
+ * Adding a *plugin* style:
29
+ * The plugin's `definePlugin()` call goes through
30
+ * `@selfhelp/shared/plugin-sdk`, which routes the entries to
31
+ * `extendStyleRegistry()` internally. Do not edit this file for plugin
32
+ * styles.
16
33
  */
17
34
 
18
35
  import type { TStyleName } from '../types/styles/unknown';
@@ -28,7 +45,8 @@ export interface IStyleRegistryEntry {
28
45
  | 'media'
29
46
  | 'interactive'
30
47
  | 'forms'
31
- | 'composite';
48
+ | 'composite'
49
+ | 'plugin';
32
50
  /**
33
51
  * Whether the style is intended for end-user pages. Mobile renders
34
52
  * only `frontendOnly: true` styles. Today every entry below is true;
@@ -44,10 +62,21 @@ export interface IStyleRegistryEntry {
44
62
  }
45
63
 
46
64
  /**
47
- * Single-source registry. Keys here drive `TStyleName` (declared in
65
+ * Plugin-contributed registry entry. Same shape as the base entry plus
66
+ * the owning `pluginId`, used by renderers to decide on fallbacks.
67
+ */
68
+ export interface IPluginStyleRegistryEntry extends IStyleRegistryEntry {
69
+ /** Plugin that registered this style (e.g. `sh2-shp-survey-js`). */
70
+ pluginId: string;
71
+ /** Source plugin package version, useful for diagnostics. */
72
+ pluginVersion?: string;
73
+ }
74
+
75
+ /**
76
+ * Compile-time core registry. Keys here drive `TStyleName` (declared in
48
77
  * `types/styles/unknown.ts`); both files must stay in sync.
49
78
  */
50
- export const STYLE_REGISTRY = {
79
+ export const BASE_STYLE_REGISTRY = {
51
80
  // ===== auth =====
52
81
  login: { description: 'User login form', category: 'auth', frontendOnly: true, canHaveChildren: false },
53
82
  register: { description: 'User registration form', category: 'auth', frontendOnly: true, canHaveChildren: false },
@@ -145,14 +174,122 @@ export const STYLE_REGISTRY = {
145
174
  loop: { description: 'Loop / repeater over backend-provided rows', category: 'composite', frontendOnly: true, canHaveChildren: true },
146
175
  } as const satisfies Record<string, IStyleRegistryEntry>;
147
176
 
148
- export type TStyleRegistryKey = keyof typeof STYLE_REGISTRY;
177
+ /**
178
+ * Backward-compatible alias for the core registry. Pre-plugin code
179
+ * imported `STYLE_REGISTRY`; that import still works and still resolves
180
+ * to the closed core map. Plugin-aware code should call
181
+ * `getMergedStyleRegistry()` to see plugin entries too.
182
+ */
183
+ export const STYLE_REGISTRY = BASE_STYLE_REGISTRY;
184
+
185
+ export type TStyleRegistryKey = keyof typeof BASE_STYLE_REGISTRY;
149
186
 
150
187
  /**
151
- * Compile-time guard: every key in the registry must be a valid TStyleName,
152
- * and every TStyleName must be a registry key.
188
+ * Compile-time guard: every key in the core registry must be a valid
189
+ * core TStyleName, and every core TStyleName must be a core registry
190
+ * key. Plugin styles intentionally bypass this check (they live in
191
+ * `PLUGIN_STYLE_REGISTRY`).
153
192
  */
154
193
  export type _AssertRegistryMatchesStyleName = TStyleName extends TStyleRegistryKey
155
194
  ? TStyleRegistryKey extends TStyleName
156
195
  ? true
157
196
  : never
158
197
  : never;
198
+
199
+ // ===== plugin registry =====
200
+
201
+ const PLUGIN_STYLE_REGISTRY: Record<string, IPluginStyleRegistryEntry> = {};
202
+
203
+ /** Plugins that have already registered, used to detect double registration. */
204
+ const REGISTERED_PLUGIN_KEYS = new Map<string, Set<string>>();
205
+
206
+ /**
207
+ * Register additional CMS styles contributed by a plugin. Called from
208
+ * `definePlugin()` inside `@selfhelp/shared/plugin-sdk`; plugins should
209
+ * not call this directly.
210
+ *
211
+ * Rules:
212
+ * - Plugin style names must not collide with `BASE_STYLE_REGISTRY`.
213
+ * - Plugin style names must not collide with any other plugin's
214
+ * already-registered styles.
215
+ * - Returns a disposer that removes the entries (used by uninstall
216
+ * and tests).
217
+ */
218
+ export function extendStyleRegistry(
219
+ entries: Record<string, IStyleRegistryEntry>,
220
+ options: { pluginId: string; pluginVersion?: string },
221
+ ): () => void {
222
+ const { pluginId, pluginVersion } = options;
223
+ const ownedKeys = REGISTERED_PLUGIN_KEYS.get(pluginId) ?? new Set<string>();
224
+ const addedKeys: string[] = [];
225
+
226
+ for (const [name, entry] of Object.entries(entries)) {
227
+ if (Object.prototype.hasOwnProperty.call(BASE_STYLE_REGISTRY, name)) {
228
+ throw new Error(
229
+ `[shared/registry] plugin '${pluginId}' tried to register core style '${name}'.`,
230
+ );
231
+ }
232
+ const existing = PLUGIN_STYLE_REGISTRY[name];
233
+ if (existing && existing.pluginId !== pluginId) {
234
+ throw new Error(
235
+ `[shared/registry] plugin '${pluginId}' tried to register style '${name}' already owned by '${existing.pluginId}'.`,
236
+ );
237
+ }
238
+ PLUGIN_STYLE_REGISTRY[name] = {
239
+ ...entry,
240
+ pluginId,
241
+ pluginVersion,
242
+ };
243
+ ownedKeys.add(name);
244
+ addedKeys.push(name);
245
+ }
246
+
247
+ REGISTERED_PLUGIN_KEYS.set(pluginId, ownedKeys);
248
+
249
+ return function dispose() {
250
+ for (const key of addedKeys) {
251
+ const existing = PLUGIN_STYLE_REGISTRY[key];
252
+ if (existing && existing.pluginId === pluginId) {
253
+ delete PLUGIN_STYLE_REGISTRY[key];
254
+ ownedKeys.delete(key);
255
+ }
256
+ }
257
+ if (ownedKeys.size === 0) {
258
+ REGISTERED_PLUGIN_KEYS.delete(pluginId);
259
+ }
260
+ };
261
+ }
262
+
263
+ /**
264
+ * Live merged registry: core entries plus plugin-contributed entries.
265
+ * Plugin entries override nothing — collisions throw in
266
+ * `extendStyleRegistry` — so this map is safe to consume directly.
267
+ */
268
+ export function getMergedStyleRegistry(): Record<string, IStyleRegistryEntry | IPluginStyleRegistryEntry> {
269
+ return {
270
+ ...BASE_STYLE_REGISTRY,
271
+ ...PLUGIN_STYLE_REGISTRY,
272
+ };
273
+ }
274
+
275
+ /**
276
+ * Return only the plugin half of the registry. Useful for the renderer
277
+ * to decide which styles need a fallback ("Open on web" on mobile) and
278
+ * which `pluginId` they belong to.
279
+ */
280
+ export function getPluginStyleRegistry(): Record<string, IPluginStyleRegistryEntry> {
281
+ return { ...PLUGIN_STYLE_REGISTRY };
282
+ }
283
+
284
+ /**
285
+ * Test-only helper: wipe every plugin contribution. Not exported from
286
+ * the package root; available through the plugin SDK testing module.
287
+ *
288
+ * @internal
289
+ */
290
+ export function _resetPluginStyleRegistry(): void {
291
+ for (const key of Object.keys(PLUGIN_STYLE_REGISTRY)) {
292
+ delete PLUGIN_STYLE_REGISTRY[key];
293
+ }
294
+ REGISTERED_PLUGIN_KEYS.clear();
295
+ }