@selfhelp/shared 1.3.2 → 1.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.
@@ -1,5 +1,5 @@
1
1
  // src/plugin-sdk/version.ts
2
- var PLUGIN_API_VERSION = "1.2";
2
+ var PLUGIN_API_VERSION = "0.1.0";
3
3
  var SEMVER_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
4
4
  function parseSemver(version) {
5
5
  const match = SEMVER_REGEX.exec(version);
@@ -127,6 +127,9 @@ function assertPluginVersionSemantics(prevVersion, nextVersion, options) {
127
127
  }
128
128
  }
129
129
 
130
+ // src/plugin-sdk/registry.ts
131
+ var PLUGIN_REGISTRY_CHANNELS = ["stable", "beta", "nightly", "test"];
132
+
130
133
  // src/registry/styles.registry.ts
131
134
  var BASE_STYLE_REGISTRY = {
132
135
  // ===== auth =====
@@ -467,6 +470,7 @@ var PLUGIN_RUNTIME_IMPORT_MAP = Object.freeze(
467
470
  );
468
471
  export {
469
472
  PLUGIN_API_VERSION,
473
+ PLUGIN_REGISTRY_CHANNELS,
470
474
  PLUGIN_RUNTIME_GLOBAL_KEY,
471
475
  PLUGIN_RUNTIME_IMPORT_MAP,
472
476
  PLUGIN_RUNTIME_SHIM_BASE_PATH,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selfhelp/shared",
3
- "version": "1.3.2",
3
+ "version": "1.4.0",
4
4
  "description": "Shared TypeScript package for SelfHelp web frontend and mobile app: style registry, types, API contracts, Mantine theme tokens, condition + interpolation engines, CMS class allow-list.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -59,7 +59,7 @@
59
59
  "test": "vitest run --passWithNoTests",
60
60
  "test:coverage": "vitest run --coverage",
61
61
  "test:changed": "vitest run --changed --passWithNoTests",
62
- "test:release": "npm run headers:check && npm run typecheck && npm run check:schemas && npm run test:coverage && npm run build",
62
+ "test:release": "npm run headers:check && npm run typecheck && npm run test:coverage && npm run build",
63
63
  "check:schemas": "node scripts/check-schema-parity.mjs",
64
64
  "prepublishOnly": "npm run build",
65
65
  "headers:check": "license-check-and-add check -f license-check-and-add-config.json",
@@ -51,10 +51,12 @@ export type {
51
51
 
52
52
  export type {
53
53
  IPluginRegistry,
54
- IPluginRegistryEntry,
55
- IPluginRegistryVersionEntry,
54
+ IRegistryReleaseRef,
55
+ IRegistrySignatureBlock,
56
+ IPluginRelease,
56
57
  TPluginRegistryChannel,
57
58
  } from './registry';
59
+ export { PLUGIN_REGISTRY_CHANNELS } from './registry';
58
60
 
59
61
  export type {
60
62
  IPluginLock,
@@ -3,103 +3,139 @@ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
3
  SPDX-License-Identifier: MPL-2.0
4
4
  */
5
5
  /**
6
- * TypeScript mirror of `registry.json` served by a plugin registry.
7
- * The host installer fetches registries (public and private), merges
8
- * per-channel metadata, and shows update availability + changelogs in
9
- * the admin UI.
6
+ * TypeScript mirror of the UNIFIED `registry.json` served by a SelfHelp plugin
7
+ * registry.
8
+ *
9
+ * The registry is a single catalogue consumed by BOTH installers: the SelfHelp
10
+ * Manager (core/frontend/scheduler/worker Docker releases) and the CMS/backend
11
+ * (plugin releases). Every component array is a list of release REFS
12
+ * (`{id, version, channel, releaseUrl}`) pointing at standalone signed release
13
+ * documents; a plugin with several published versions appears as several refs, so
14
+ * the host can resolve the newest COMPATIBLE version per plugin.
15
+ *
16
+ * Mirrors the backend JSON Schemas in the sibling repo
17
+ * (`sh-selfhelp_backend/docs/plugins/plugin-registry.schema.json` +
18
+ * `config/schemas/registry/plugin-release.schema.json`) and the SelfHelp Manager
19
+ * Zod schema. Keep all three in sync (see AGENTS.md).
10
20
  */
11
21
 
12
- export type TPluginRegistryChannel = 'stable' | 'beta' | 'alpha' | 'nightly';
22
+ /**
23
+ * Registry channels, kept in parity with the canonical `ReleaseChannel` set
24
+ * (`stable | beta | nightly | test`) used by the unified distribution registry
25
+ * wire schema, the SelfHelp Manager, and the backend. Exposed as a runtime tuple
26
+ * so the cross-repo parity test can assert the sets match.
27
+ */
28
+ export const PLUGIN_REGISTRY_CHANNELS = ['stable', 'beta', 'nightly', 'test'] as const;
29
+ export type TPluginRegistryChannel = (typeof PLUGIN_REGISTRY_CHANNELS)[number];
13
30
 
14
- export interface IPluginRegistryVersionEntry {
15
- /** SemVer version. */
31
+ /**
32
+ * One published (component, version) entry in the unified index. Identical shape
33
+ * for plugins and the platform components (core/frontend/scheduler/worker) — the
34
+ * `releaseUrl` resolves (against the index `baseUrl`) to the signed release
35
+ * document validated by `plugin-release.schema.json` / `core-release.schema.json`.
36
+ */
37
+ export interface IRegistryReleaseRef {
38
+ /** Component id (e.g. `sh2-shp-survey-js`, `selfhelp-core`). */
39
+ id: string;
40
+ /** SemVer version of this release. */
16
41
  version: string;
17
42
  /** Channel this version was published to. */
18
43
  channel: TPluginRegistryChannel;
19
- /** ISO datetime the version was published. */
20
- publishedAt: string;
21
- /** Whether this version is a breaking change vs the previous one. */
22
- breaking?: boolean;
23
- /** Whether the host installer should block this version. */
44
+ /** Absolute or `baseUrl`-relative URL of the signed release document. */
45
+ releaseUrl: string;
46
+ /** When true the host installer must not offer this version. */
24
47
  blocked?: boolean;
25
- /** Optional reason for `blocked: true`. */
26
- blockedReason?: string;
27
- /** Composer / npm tarball or git source URL. */
28
- sources: {
29
- backend?: { type: 'composer' | 'git'; package?: string; ref?: string; url?: string };
30
- frontend?: { type: 'npm' | 'git'; package?: string; url?: string };
31
- mobile?: { type: 'npm' | 'git'; package?: string; url?: string };
32
- };
33
- /** SHA-256 checksum of the published artifact. */
34
- checksumSha256: string;
35
- /** Optional Ed25519 signature, base64. */
36
- signatureEd25519?: string;
37
- /** Compatibility metadata mirrored from the manifest. */
38
- compatibility: {
39
- selfhelp: string;
40
- php?: string;
41
- node?: string;
42
- react?: string;
43
- reactNative?: string;
44
- expoSdk?: string;
45
- pluginApiVersion: string;
46
- };
47
- /** Plain-text changelog. Markdown supported. */
48
- changelog?: string;
49
- /** Mirror of `dependencies` from the manifest, for resolver-only consumption. */
50
- dependencies?: { pluginId: string; version: string; required: boolean }[];
51
48
  }
52
49
 
53
- export interface IPluginRegistryEntry {
54
- /** Plugin id (e.g. `sh2-shp-survey-js`). */
50
+ /** Ed25519 signature block carried by every signed release document. */
51
+ export interface IRegistrySignatureBlock {
52
+ /** Base64 detached Ed25519 signature of the canonical payload. */
53
+ signature: string;
54
+ /** Publisher key identifier, resolved against the trusted-keys file. */
55
+ keyId: string;
56
+ /** Optional inline canonical payload (omitted when the verifier recomputes it). */
57
+ signedPayload?: string;
58
+ /** Optional SHA-256 of the canonical payload (`sha256:` prefix allowed). */
59
+ signedPayloadSha256?: string;
60
+ }
61
+
62
+ /**
63
+ * A standalone signed plugin release document (the target of a `plugins[]` ref).
64
+ *
65
+ * Mirrors `plugin-release.schema.json`. The release expresses compatibility on
66
+ * two axes (`compatibility.core` + `compatibility.pluginApi`); the author-facing
67
+ * `plugin.json` manifest keeps `compatibility.selfhelp` + `pluginApiVersion`,
68
+ * which the publish tooling maps onto these ranges.
69
+ */
70
+ export interface IPluginRelease {
71
+ /** Discriminator — always `selfhelp-plugin-release`. */
72
+ kind: 'selfhelp-plugin-release';
73
+ /** Plugin id (matches the ref in the index). */
55
74
  id: string;
56
- /** Display name. */
57
- name: string;
58
- /** Short description. */
59
- description?: string;
60
- /** Homepage / repo URL. */
61
- homepage?: string;
62
- /** Trust level published by the registry. */
63
- trustLevel: 'official' | 'reviewed' | 'untrusted';
64
- /** Available versions. */
65
- versions: IPluginRegistryVersionEntry[];
66
- /** Optional public icon URL. */
67
- iconUrl?: string;
68
- /** Optional categories. */
69
- categories?: string[];
75
+ /** SemVer version (matches the ref in the index). */
76
+ version: string;
77
+ /** Channel (matches the ref in the index). */
78
+ channel: TPluginRegistryChannel;
79
+ /** True when the manifest declared `security.trustLevel: "official"`. */
80
+ official: boolean;
81
+ /** Compatibility ranges the host must satisfy. */
82
+ compatibility: {
83
+ /** Semver range of SelfHelp core versions this plugin runs on. */
84
+ core: string;
85
+ /** Semver range of host plugin-API versions this plugin runs on. */
86
+ pluginApi: string;
87
+ };
88
+ /** Optional other-plugin requirements consumed by the resolver. */
89
+ dependencies?: {
90
+ plugins?: { id: string; range: string }[];
91
+ };
92
+ /** The install artifact + canonical manifest the host fetches. */
93
+ artifacts: {
94
+ /** URL of the full `plugin.json` snapshot. */
95
+ manifestUrl: string;
96
+ /** URL of the signed `.shplugin` archive the backend downloads. */
97
+ archiveUrl: string;
98
+ /** SHA-256 of the `.shplugin` (`sha256:` prefix allowed). */
99
+ sha256: string;
100
+ };
101
+ /** Ed25519 signature block. */
102
+ security: IRegistrySignatureBlock;
103
+ /** When true the host installer must not offer this version. */
104
+ blocked?: boolean;
70
105
  }
71
106
 
72
107
  /**
73
- * Registry root document.
108
+ * Unified registry root document (`registry.json`).
74
109
  *
75
- * Mirrors `plugin-registry.schema.json` in the host repository. The
76
- * canonical schema requires `schemaVersion` (a string enum, currently
77
- * `'1.0'`) and `plugins`. The publisher/base-url metadata is optional
78
- * but always emitted by `scripts/publish-to-registry.mjs`.
110
+ * Mirrors `plugin-registry.schema.json` in the host repository. Required:
111
+ * `schemaVersion`, `requiresManager`, `baseUrl`, and the five release-ref arrays
112
+ * `core` / `frontend` / `scheduler` / `worker` / `plugins`.
79
113
  */
80
114
  export interface IPluginRegistry {
81
- /** Canonical registry schema version. Currently fixed at `'1.0'`. */
82
- schemaVersion: '1.0';
115
+ /** Canonical registry schema version. */
116
+ schemaVersion: string;
117
+ /** Semver range of SelfHelp Manager versions that can consume this registry. */
118
+ requiresManager: string;
83
119
  /** ISO timestamp this registry was published. */
84
120
  publishedAt?: string;
85
- /**
86
- * Public base URL where this registry is served (with trailing
87
- * slash). Plugin publishers join this to relative
88
- * `artifacts/<id>-<version>/...` paths to produce the absolute
89
- * `runtime.entrypointUrl` / `runtime.stylesheetUrl` that gets
90
- * signed and shipped in each plugin entry.
91
- */
92
- baseUrl?: string;
121
+ /** Base URL used to resolve relative `releaseUrl` / artifact paths (with trailing slash). */
122
+ baseUrl: string;
93
123
  /** Publisher metadata shown in the admin UI. */
94
124
  publisher?: { name: string; url?: string };
95
- /** Optional registry display name (legacy helper, not in canonical schema). */
96
- name?: string;
97
- /** Registry homepage / maintainer URL (legacy helper, not in canonical schema). */
98
- homepage?: string;
99
- /** Public key used to verify per-version signatures (legacy helper, not in canonical schema). */
100
- trustKey?: { algo: 'ed25519'; publicKeyId: string; publicKey: string };
101
- /** Channels this registry exposes (legacy helper, not in canonical schema). */
102
- channels?: TPluginRegistryChannel[];
103
- /** Listed plugins. */
104
- plugins: IPluginRegistryEntry[];
125
+ /** SelfHelp core Docker release refs (Manager-installed). */
126
+ core: IRegistryReleaseRef[];
127
+ /** SelfHelp frontend Docker release refs (Manager-installed). */
128
+ frontend: IRegistryReleaseRef[];
129
+ /** Scheduled-jobs-runner release refs (Manager-installed). */
130
+ scheduler: IRegistryReleaseRef[];
131
+ /** Messenger-worker release refs (Manager-installed). */
132
+ worker: IRegistryReleaseRef[];
133
+ /** Plugin release refs (CMS-installed) — multi-version, one ref per published version. */
134
+ plugins: IRegistryReleaseRef[];
135
+ /** Optional path to the security advisory feed. */
136
+ advisoriesUrl?: string;
137
+ /** Optional path to the cross-component compatibility feed. */
138
+ compatibilityUrl?: string;
139
+ /** Optional path to the public trusted-keys file. */
140
+ trustedKeysUrl?: string;
105
141
  }
@@ -14,7 +14,7 @@ SPDX-License-Identifier: MPL-2.0
14
14
  *
15
15
  * Independent from the npm `version` of `@selfhelp/shared`.
16
16
  */
17
- export const PLUGIN_API_VERSION = '1.2' as const;
17
+ export const PLUGIN_API_VERSION = '0.1.0' as const;
18
18
 
19
19
  export interface ISemver {
20
20
  major: number;
@@ -0,0 +1,74 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Release-channel enum parity across the SelfHelp distribution stack.
7
+ *
8
+ * The `channel` field of a registry release ref is a cross-repo contract: it is
9
+ * defined by the registry wire schema (`sh2-plugin-registry/registry.schema.json`),
10
+ * validated by the SelfHelp Manager (`@shm/schemas`), consumed by the backend
11
+ * (`RegistryReleaseRef::CHANNELS`), and mirrored here in `@selfhelp/shared` for
12
+ * the frontend/mobile/plugin consumers. They MUST all agree. This test pins the
13
+ * canonical set and — when the sibling repos are checked out in the dev layout —
14
+ * asserts the registry schema and the manager schema enumerate exactly the same
15
+ * channels, so drift (e.g. a stray `alpha`/`test`) fails fast.
16
+ */
17
+ import { existsSync, readFileSync } from 'node:fs';
18
+ import path from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { describe, expect, it } from 'vitest';
21
+ import { RELEASE_CHANNELS } from '../distribution';
22
+ import { PLUGIN_REGISTRY_CHANNELS } from '../../plugin-sdk/registry';
23
+
24
+ const here = path.dirname(fileURLToPath(import.meta.url));
25
+ const repoParent = path.resolve(here, '../../../..');
26
+
27
+ /** The single canonical channel set every repo must enumerate. */
28
+ const CANONICAL = ['stable', 'beta', 'nightly', 'test'];
29
+
30
+ /** Recursively collect every `channel.enum` array in a JSON-schema object. */
31
+ function collectChannelEnums(node: unknown, out: string[][]): void {
32
+ if (Array.isArray(node)) {
33
+ for (const item of node) collectChannelEnums(item, out);
34
+ return;
35
+ }
36
+ if (node && typeof node === 'object') {
37
+ const obj = node as Record<string, unknown>;
38
+ const channel = obj.channel;
39
+ if (channel && typeof channel === 'object') {
40
+ const e = (channel as Record<string, unknown>).enum;
41
+ if (Array.isArray(e)) out.push(e.map((v) => String(v)));
42
+ }
43
+ for (const value of Object.values(obj)) collectChannelEnums(value, out);
44
+ }
45
+ }
46
+
47
+ describe('release-channel enum parity', () => {
48
+ it('the shared distribution + plugin-sdk channel sets are the canonical set', () => {
49
+ expect([...RELEASE_CHANNELS]).toEqual(CANONICAL);
50
+ // The plugin-sdk registry channel set must match the distribution set
51
+ // exactly (no stray `alpha`, includes the staging `test` channel).
52
+ expect([...PLUGIN_REGISTRY_CHANNELS]).toEqual([...RELEASE_CHANNELS]);
53
+ });
54
+
55
+ const registrySchemaPath = path.join(repoParent, 'plugins', 'sh2-plugin-registry', 'registry.schema.json');
56
+ it.runIf(existsSync(registrySchemaPath))('matches the registry wire schema channel enum', () => {
57
+ const schema = JSON.parse(readFileSync(registrySchemaPath, 'utf8')) as unknown;
58
+ const enums: string[][] = [];
59
+ collectChannelEnums(schema, enums);
60
+ expect(enums.length).toBeGreaterThan(0);
61
+ for (const e of enums) expect([...e].sort()).toEqual([...CANONICAL].sort());
62
+ });
63
+
64
+ const managerSchemasPath = path.join(repoParent, 'sh-manager', 'packages', 'schemas', 'src', 'json-schemas.ts');
65
+ it.runIf(existsSync(managerSchemasPath))('matches the SelfHelp Manager schema channel enum', () => {
66
+ const src = readFileSync(managerSchemasPath, 'utf8');
67
+ const matches = [...src.matchAll(/channel:\s*\{\s*enum:\s*(\[[^\]]*\])/g)];
68
+ expect(matches.length).toBeGreaterThan(0);
69
+ for (const m of matches) {
70
+ const arr = JSON.parse(m[1]!.replace(/'/g, '"')) as string[];
71
+ expect([...arr].sort()).toEqual([...CANONICAL].sort());
72
+ }
73
+ });
74
+ });
@@ -0,0 +1,168 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { describe, expect, it } from 'vitest';
9
+ import type {
10
+ AdvisoryFeed,
11
+ CompatibilityRules,
12
+ CoreRelease,
13
+ PluginRelease,
14
+ RegistryIndex,
15
+ } from '../distribution';
16
+
17
+ const here = path.dirname(fileURLToPath(import.meta.url));
18
+ // In the SelfHelp multi-repo dev layout the manager is a sibling checkout. Its
19
+ // example fixtures are the authoritative source for the distribution contracts,
20
+ // so we assert the shared types stay in parity against them.
21
+ const managerExamples = path.resolve(here, '../../../../sh-manager/packages/schemas/examples');
22
+ const hasManager = existsSync(managerExamples);
23
+
24
+ function readExample(name: string): Record<string, unknown> {
25
+ return JSON.parse(readFileSync(path.join(managerExamples, name), 'utf8')) as Record<string, unknown>;
26
+ }
27
+
28
+ /** Top-level required/optional keys + discriminant for each shared contract. */
29
+ const SPEC: Record<string, { required: string[]; optional?: string[]; kind?: string }> = {
30
+ 'registry-index.json': {
31
+ required: ['schemaVersion', 'requiresManager', 'publishedAt', 'baseUrl', 'publisher', 'core', 'frontend', 'scheduler', 'worker', 'plugins'],
32
+ optional: ['advisoriesUrl', 'compatibilityUrl', 'trustedKeysUrl'],
33
+ },
34
+ 'core-release.json': {
35
+ kind: 'selfhelp-core-release',
36
+ required: ['kind', 'id', 'version', 'channel', 'releasedAt', 'minimumDirectUpgradeFrom', 'pluginApiVersion', 'backend', 'worker', 'scheduler', 'frontendCompatibility', 'database', 'security'],
37
+ optional: ['runtime', 'artifacts', 'blocked'],
38
+ },
39
+ 'frontend-release.json': {
40
+ kind: 'selfhelp-frontend-release',
41
+ required: ['kind', 'id', 'version', 'channel', 'image', 'digest', 'backendCompatibility', 'security'],
42
+ optional: ['builtFrom', 'blocked'],
43
+ },
44
+ 'scheduler-release.json': {
45
+ kind: 'selfhelp-scheduler-release',
46
+ required: ['kind', 'id', 'version', 'channel', 'image', 'digest', 'backendCompatibility', 'security'],
47
+ optional: ['builtFrom', 'blocked'],
48
+ },
49
+ 'worker-release.json': {
50
+ kind: 'selfhelp-worker-release',
51
+ required: ['kind', 'id', 'version', 'channel', 'image', 'digest', 'backendCompatibility', 'security'],
52
+ optional: ['builtFrom', 'blocked'],
53
+ },
54
+ 'instance-manifest.json': {
55
+ required: ['manifestVersion', 'instanceId', 'displayName', 'domain', 'mode', 'createdAt', 'updatedAt', 'registry', 'versions', 'images', 'routing', 'installedPlugins'],
56
+ optional: ['resources'],
57
+ },
58
+ 'instance-lock.json': {
59
+ required: ['lockfileVersion', 'generatedAt', 'registry', 'core', 'services', 'plugins'],
60
+ optional: ['operationId'],
61
+ },
62
+ 'server-inventory.json': {
63
+ required: ['inventoryVersion', 'serverId', 'manager', 'proxy', 'instances'],
64
+ },
65
+ 'backup-manifest.json': {
66
+ required: ['backupManifestVersion', 'backupId', 'instanceId', 'createdAt', 'mode', 'selfhelpVersion', 'migrationVersion', 'plugins', 'includedAreas', 'files'],
67
+ },
68
+ 'update-preflight.json': {
69
+ required: ['preflightVersion', 'status', 'instanceId', 'currentVersion', 'targetVersion', 'checks', 'options', 'database', 'rollback'],
70
+ },
71
+ 'trusted-keys.json': {
72
+ required: ['schemaVersion', 'keys'],
73
+ },
74
+ };
75
+
76
+ describe.runIf(hasManager)('distribution contract parity with manager fixtures', () => {
77
+ for (const [file, spec] of Object.entries(SPEC)) {
78
+ it(`shared type stays in parity with ${file}`, () => {
79
+ const obj = readExample(file);
80
+ // Forward parity: every shared-required key is emitted by the manager.
81
+ for (const k of spec.required) expect(obj, `missing required key "${k}"`).toHaveProperty(k);
82
+ // Reverse parity: the manager never emits a key the shared type lacks.
83
+ const allowed = [...spec.required, ...(spec.optional ?? [])];
84
+ for (const k of Object.keys(obj)) {
85
+ expect(allowed, `manager fixture key "${k}" is missing from the shared type`).toContain(k);
86
+ }
87
+ if (spec.kind) expect(obj.kind).toBe(spec.kind);
88
+ });
89
+ }
90
+ });
91
+
92
+ // Always-on compile-time parity: the fixture-less contracts must remain usable.
93
+ describe('distribution contracts compile and are usable', () => {
94
+ it('types a registry index and core release', () => {
95
+ const index: RegistryIndex = {
96
+ schemaVersion: '1.0',
97
+ requiresManager: '>=0.1.0',
98
+ publishedAt: '2026-06-05T12:00:00Z',
99
+ baseUrl: 'https://example/',
100
+ publisher: { name: 'SelfHelp', url: 'https://example/' },
101
+ core: [{ id: 'selfhelp-core-0.1.0', version: '0.1.0', channel: 'stable', releaseUrl: 'releases/core/x.json' }],
102
+ frontend: [],
103
+ scheduler: [],
104
+ worker: [],
105
+ plugins: [],
106
+ };
107
+ const core: CoreRelease = {
108
+ kind: 'selfhelp-core-release',
109
+ id: 'selfhelp-core-0.1.0',
110
+ version: '0.1.0',
111
+ channel: 'stable',
112
+ releasedAt: '2026-06-01T00:00:00Z',
113
+ minimumDirectUpgradeFrom: '0.1.0',
114
+ pluginApiVersion: '0.1.0',
115
+ backend: { image: 'b', digest: 'sha256:1' },
116
+ worker: { image: 'w', digest: 'sha256:2' },
117
+ scheduler: { image: 's', digest: 'sha256:3' },
118
+ frontendCompatibility: { requiredFrontendRange: '>=0.1.0 <0.2.0' },
119
+ database: { migrationRange: 'A..B', destructive: false, requiresBackup: true, manualConfirmationRequired: false },
120
+ security: { signature: 'sig', keyId: 'selfhelp-official-2026' },
121
+ };
122
+ expect(index.core[0]?.version).toBe('0.1.0');
123
+ expect(core.kind).toBe('selfhelp-core-release');
124
+ // Plan invariant: no automatic rollback is promised after destructive migrations.
125
+ });
126
+
127
+ it('types a plugin release, advisory feed, and compatibility rules (no manager fixture)', () => {
128
+ const plugin: PluginRelease = {
129
+ kind: 'selfhelp-plugin-release',
130
+ id: 'surveyjs',
131
+ version: '0.1.0',
132
+ channel: 'stable',
133
+ official: true,
134
+ compatibility: { core: '>=0.1.0 <0.2.0', pluginApi: '0.1.0' },
135
+ artifacts: { manifestUrl: 'm', archiveUrl: 'a', sha256: 'sha256:0' },
136
+ security: { signature: 'sig', keyId: 'selfhelp-official-2026' },
137
+ };
138
+ const advisories: AdvisoryFeed = {
139
+ schemaVersion: '1.0',
140
+ advisories: [
141
+ {
142
+ id: 'SH-2026-0001',
143
+ severity: 'high',
144
+ affected: [{ kind: 'core', versions: '<0.1.1' }],
145
+ fixed: [{ kind: 'core', version: '0.1.1' }],
146
+ recommendedAction: 'Update to 0.1.1.',
147
+ blocked: true,
148
+ },
149
+ ],
150
+ };
151
+ const compatibility: CompatibilityRules = {
152
+ schemaVersion: '1.0',
153
+ rules: [
154
+ {
155
+ selfhelp: '>=0.1.0 <0.2.0',
156
+ runtime: {
157
+ mysql: { supportedVersions: '8.x', recommendedImage: 'mysql:8.4' },
158
+ redis: { supportedVersions: '7.x', recommendedImage: 'redis:7.2' },
159
+ mercure: { supportedVersions: '0.x', recommendedImage: 'dunglas/mercure:0.18' },
160
+ },
161
+ },
162
+ ],
163
+ };
164
+ expect(plugin.official).toBe(true);
165
+ expect(advisories.advisories[0]?.blocked).toBe(true);
166
+ expect(compatibility.rules[0]?.runtime.mysql.recommendedImage).toBe('mysql:8.4');
167
+ });
168
+ });
@@ -0,0 +1,107 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ /**
6
+ * Standardized compatibility-error SHAPE parity across the SelfHelp stack
7
+ * (#51 / #53 / #49).
8
+ *
9
+ * `ICompatibilityError` is a cross-repo contract: the SAME object is emitted by
10
+ * the backend (`CompatibilityError::toArray()`), consumed by the frontend
11
+ * (`IPluginCompatibilityError`) and the SelfHelp Manager (`@shm/resolver`
12
+ * `CompatibilityError`), and mirrored here in `@selfhelp/shared`. They MUST all
13
+ * enumerate the SAME fields so a core-update preflight and a plugin
14
+ * install/update render identical compat info. This test pins the canonical set
15
+ * and — when the sibling Manager repo is checked out in the dev layout —
16
+ * asserts the Manager's `CompatibilityError` interface enumerates exactly the
17
+ * same fields, so drift fails fast.
18
+ */
19
+ import { existsSync, readFileSync } from 'node:fs';
20
+ import path from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { describe, expect, it } from 'vitest';
23
+ import type { ICompatibilityError, IUpdatePreflightCheck } from '../system';
24
+
25
+ /** The exact keys `CompatibilityError::toArray()` (backend) emits. Snake_case wire contract. */
26
+ const CANONICAL_KEYS = [
27
+ 'blocking',
28
+ 'component',
29
+ 'component_id',
30
+ 'current_version',
31
+ 'message',
32
+ 'required_range',
33
+ 'target_version',
34
+ ] as const;
35
+
36
+ const here = path.dirname(fileURLToPath(import.meta.url));
37
+ // here = sh-selfhelp_shared/src/types/api/__tests__ -> five up = the repo parent.
38
+ const repoParent = path.resolve(here, '../../../../..');
39
+
40
+ /** Extract the field names declared in a TS `export interface <name> { ... }` block. */
41
+ function interfaceFields(source: string, name: string): string[] {
42
+ const start = source.indexOf(`export interface ${name}`);
43
+ if (start < 0) return [];
44
+ const open = source.indexOf('{', start);
45
+ const close = source.indexOf('}', open);
46
+ if (open < 0 || close < 0) return [];
47
+ const body = source.slice(open + 1, close);
48
+ const fields: string[] = [];
49
+ for (const rawLine of body.split('\n')) {
50
+ const line = rawLine.trim();
51
+ if (line === '' || line.startsWith('//') || line.startsWith('*') || line.startsWith('/*')) continue;
52
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)\??\s*:/.exec(line);
53
+ if (m) fields.push(m[1]!);
54
+ }
55
+ return fields;
56
+ }
57
+
58
+ describe('compatibility-error shape parity', () => {
59
+ it('ICompatibilityError enumerates exactly the canonical compatibility-error keys', () => {
60
+ // Typed literal: `tsc` rejects any added/renamed/removed field.
61
+ const error: ICompatibilityError = {
62
+ component: 'plugin',
63
+ component_id: 'sh2-shp-survey-js',
64
+ current_version: '0.1.0',
65
+ target_version: '0.2.0',
66
+ required_range: '>=0.1.0 <0.2.0',
67
+ blocking: true,
68
+ message: 'Plugin sh2-shp-survey-js is not compatible with SelfHelp 0.2.0.',
69
+ };
70
+ expect(Object.keys(error).sort()).toEqual([...CANONICAL_KEYS]);
71
+ });
72
+
73
+ it('an ICompatibilityError projects onto an IUpdatePreflightCheck (preflight mirrors the same fields)', () => {
74
+ const error: ICompatibilityError = {
75
+ component: 'plugin',
76
+ component_id: 'sh2-shp-survey-js',
77
+ current_version: '0.1.0',
78
+ target_version: '0.2.0',
79
+ required_range: '>=0.1.0 <0.2.0',
80
+ blocking: true,
81
+ message: 'incompatible',
82
+ };
83
+ // Same compat fields appear on a preflight check; null version fields
84
+ // project to undefined (a check omits them rather than carrying null).
85
+ const check: Pick<
86
+ IUpdatePreflightCheck,
87
+ 'component' | 'component_id' | 'current_version' | 'target_version' | 'required_range' | 'blocking' | 'message'
88
+ > = {
89
+ component: error.component,
90
+ component_id: error.component_id,
91
+ current_version: error.current_version ?? undefined,
92
+ target_version: error.target_version ?? undefined,
93
+ required_range: error.required_range,
94
+ blocking: error.blocking,
95
+ message: error.message,
96
+ };
97
+ expect(check.component_id).toBe('sh2-shp-survey-js');
98
+ });
99
+
100
+ const managerResolver = path.join(repoParent, 'sh-manager', 'packages', 'resolver', 'src', 'plugins.ts');
101
+ it.runIf(existsSync(managerResolver))('matches the SelfHelp Manager CompatibilityError interface', () => {
102
+ const source = readFileSync(managerResolver, 'utf8');
103
+ const fields = interfaceFields(source, 'CompatibilityError');
104
+ expect(fields.length).toBeGreaterThan(0);
105
+ expect([...fields].sort()).toEqual([...CANONICAL_KEYS]);
106
+ });
107
+ });