@selfhelp/shared 1.2.2 → 1.2.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,298 @@
1
+ // src/plugin-sdk/version.ts
2
+ var SEMVER_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
3
+ function parseSemver(version) {
4
+ const match = SEMVER_REGEX.exec(version);
5
+ if (!match) {
6
+ throw new Error(`[plugin-sdk] not a valid semver: '${version}'.`);
7
+ }
8
+ return {
9
+ major: Number(match[1]),
10
+ minor: Number(match[2]),
11
+ patch: Number(match[3]),
12
+ prerelease: match[4]
13
+ };
14
+ }
15
+
16
+ // src/testing/index.ts
17
+ var CERTIFICATION_KIT_VERSION = "1.0.0";
18
+ var CERTIFICATION_CHECKS = [
19
+ "manifest-valid",
20
+ "capabilities-vs-trust-level",
21
+ "compatibility-shape",
22
+ "lookup-ownership",
23
+ "db-naming"
24
+ ];
25
+ var KNOWN_CAPABILITIES = /* @__PURE__ */ new Set([
26
+ "backendBundle",
27
+ "databaseMigrations",
28
+ "readUsers",
29
+ "writeUsers",
30
+ "deleteUsers",
31
+ "readDataTables",
32
+ "writeDataTables",
33
+ "deleteDataTables",
34
+ "externalNetworkAccess",
35
+ "scheduledJobs",
36
+ "publicCallbacks",
37
+ "adminPages",
38
+ "frontendStyles",
39
+ "mobileStyles",
40
+ "realtimePublish",
41
+ "fileUploads",
42
+ "secretAccess",
43
+ "lookupExtend",
44
+ "lookupOwnGroup"
45
+ ]);
46
+ var UNTRUSTED_FORBIDDEN_CAPABILITIES = [
47
+ "backendBundle",
48
+ "databaseMigrations",
49
+ "scheduledJobs",
50
+ "readUsers",
51
+ "writeUsers",
52
+ "deleteUsers",
53
+ "readDataTables",
54
+ "writeDataTables",
55
+ "deleteDataTables",
56
+ "secretAccess",
57
+ "externalNetworkAccess"
58
+ ];
59
+ var COMPATIBILITY_KEYS = ["selfhelp", "php", "node", "react", "reactNative", "expoSdk"];
60
+ var OWNED_TABLE_PATTERN = /^[a-z][a-z0-9_]*$/;
61
+ var OWNED_PREFIX_PATTERN = /^[a-z][a-z0-9_]*_$/;
62
+ var PLUGIN_ID_PATTERN = /^[a-z][a-z0-9-]*$/;
63
+ var PLUGIN_API_VERSION_PATTERN = /^\d+\.\d+$/;
64
+ var RANGE_TOKEN_PATTERN = /^(\*|x|(\^|~|>=|<=|>|<|=)?\d+(\.\d+)?(\.\d+)?(-[0-9A-Za-z.-]+)?)$/;
65
+ function makeResult(name, errors) {
66
+ return { name, passed: errors.length === 0, errors };
67
+ }
68
+ function isValidRange(range) {
69
+ const clauses = range.split("||").map((c) => c.trim()).filter((c) => c !== "");
70
+ if (clauses.length === 0) {
71
+ return false;
72
+ }
73
+ return clauses.every(
74
+ (clause) => clause.split(/\s+/).filter((t) => t !== "").every((token) => RANGE_TOKEN_PATTERN.test(token))
75
+ );
76
+ }
77
+ function asCapabilityList(manifest) {
78
+ const caps = manifest.security?.capabilities;
79
+ return Array.isArray(caps) ? caps.map((c) => String(c)) : [];
80
+ }
81
+ function checkManifestValid(manifest) {
82
+ const errors = [];
83
+ if (!manifest.id || typeof manifest.id !== "string") {
84
+ errors.push("id is required.");
85
+ } else if (!PLUGIN_ID_PATTERN.test(manifest.id)) {
86
+ errors.push(`id '${manifest.id}' must match ${PLUGIN_ID_PATTERN}.`);
87
+ }
88
+ if (!manifest.name || typeof manifest.name !== "string") {
89
+ errors.push("name is required.");
90
+ }
91
+ if (!manifest.version || typeof manifest.version !== "string") {
92
+ errors.push("version is required.");
93
+ } else {
94
+ try {
95
+ parseSemver(manifest.version);
96
+ } catch {
97
+ errors.push(`version '${manifest.version}' is not valid semver.`);
98
+ }
99
+ }
100
+ if (!manifest.pluginApiVersion || typeof manifest.pluginApiVersion !== "string") {
101
+ errors.push("pluginApiVersion is required.");
102
+ } else if (!PLUGIN_API_VERSION_PATTERN.test(manifest.pluginApiVersion)) {
103
+ errors.push(`pluginApiVersion '${manifest.pluginApiVersion}' must look like '<major>.<minor>'.`);
104
+ }
105
+ if (!manifest.compatibility || typeof manifest.compatibility !== "object") {
106
+ errors.push("compatibility is required.");
107
+ }
108
+ if (!manifest.security || typeof manifest.security !== "object") {
109
+ errors.push("security is required.");
110
+ } else {
111
+ if (!manifest.security.trustLevel) {
112
+ errors.push("security.trustLevel is required.");
113
+ }
114
+ if (!Array.isArray(manifest.security.capabilities)) {
115
+ errors.push("security.capabilities must be an array.");
116
+ }
117
+ }
118
+ return makeResult("manifest-valid", errors);
119
+ }
120
+ function checkCapabilitiesVsTrustLevel(manifest) {
121
+ const errors = [];
122
+ const caps = asCapabilityList(manifest);
123
+ const capSet = new Set(caps);
124
+ const trustLevel = manifest.security?.trustLevel;
125
+ for (const cap of caps) {
126
+ if (!KNOWN_CAPABILITIES.has(cap)) {
127
+ errors.push(`unknown capability '${cap}'.`);
128
+ }
129
+ }
130
+ if (trustLevel === "untrusted") {
131
+ for (const cap of UNTRUSTED_FORBIDDEN_CAPABILITIES) {
132
+ if (capSet.has(cap)) {
133
+ errors.push(`untrusted plugins may not declare capability '${cap}'.`);
134
+ }
135
+ }
136
+ }
137
+ const require2 = (condition, capability, surface) => {
138
+ if (condition && !capSet.has(capability)) {
139
+ errors.push(`${surface} requires the '${capability}' capability.`);
140
+ }
141
+ };
142
+ require2(Boolean(manifest.backend?.bundleClass), "backendBundle", "declaring a backend bundle");
143
+ require2(Boolean(manifest.backend?.migrationsNamespace), "databaseMigrations", "declaring a migrations namespace");
144
+ require2((manifest.scheduledJobs?.length ?? 0) > 0, "scheduledJobs", "declaring scheduled jobs");
145
+ require2((manifest.adminPages?.length ?? 0) > 0, "adminPages", "declaring admin pages");
146
+ require2((manifest.realtimeTopics?.length ?? 0) > 0, "realtimePublish", "declaring realtime topics");
147
+ if ((manifest.styles?.length ?? 0) > 0 && !capSet.has("frontendStyles") && !capSet.has("mobileStyles")) {
148
+ errors.push("declaring styles requires the 'frontendStyles' or 'mobileStyles' capability.");
149
+ }
150
+ for (const ext of manifest.lookups?.extends ?? []) {
151
+ if (ext.ownership === "plugin_owned") {
152
+ require2(true, "lookupOwnGroup", `owning lookup group '${ext.typeCode}'`);
153
+ } else if (ext.ownership === "plugin_extendable") {
154
+ require2(true, "lookupExtend", `extending lookup group '${ext.typeCode}'`);
155
+ }
156
+ }
157
+ require2((manifest.dataAccess?.write?.length ?? 0) > 0, "writeDataTables", "declaring data-table writes");
158
+ require2((manifest.dataAccess?.delete?.length ?? 0) > 0, "deleteDataTables", "declaring data-table deletes");
159
+ return makeResult("capabilities-vs-trust-level", errors);
160
+ }
161
+ function checkCompatibilityShape(manifest) {
162
+ const errors = [];
163
+ const compatibility = manifest.compatibility;
164
+ if (!compatibility || typeof compatibility !== "object") {
165
+ return makeResult("compatibility-shape", ["compatibility is required."]);
166
+ }
167
+ const selfhelp = compatibility.selfhelp;
168
+ if (typeof selfhelp !== "string") {
169
+ errors.push(
170
+ "compatibility.selfhelp must be a SemVer range string (single-range shape), not an object or missing."
171
+ );
172
+ } else if (selfhelp.trim() === "" || !isValidRange(selfhelp)) {
173
+ errors.push(`compatibility.selfhelp '${selfhelp}' is not a valid SemVer range.`);
174
+ }
175
+ for (const key of Object.keys(compatibility)) {
176
+ if (!COMPATIBILITY_KEYS.includes(key)) {
177
+ errors.push(`compatibility has unknown key '${key}'.`);
178
+ continue;
179
+ }
180
+ if (key === "selfhelp") {
181
+ continue;
182
+ }
183
+ const value = compatibility[key];
184
+ if (typeof value !== "string" || !isValidRange(value)) {
185
+ errors.push(`compatibility.${key} must be a valid SemVer range string.`);
186
+ }
187
+ }
188
+ return makeResult("compatibility-shape", errors);
189
+ }
190
+ function checkLookupOwnership(manifest) {
191
+ const errors = [];
192
+ for (const ext of manifest.lookups?.extends ?? []) {
193
+ const label = ext.typeCode || "<missing typeCode>";
194
+ if (!ext.typeCode) {
195
+ errors.push("lookup extension is missing typeCode.");
196
+ }
197
+ if (ext.ownership !== "plugin_owned" && ext.ownership !== "plugin_extendable") {
198
+ errors.push(`lookup '${label}' has invalid ownership '${String(ext.ownership)}'.`);
199
+ }
200
+ if (!Array.isArray(ext.entries) || ext.entries.length === 0) {
201
+ errors.push(`lookup '${label}' must declare at least one entry.`);
202
+ continue;
203
+ }
204
+ for (const entry of ext.entries) {
205
+ if (!entry.code || !entry.value) {
206
+ errors.push(`lookup '${label}' has an entry missing code/value.`);
207
+ }
208
+ }
209
+ }
210
+ return makeResult("lookup-ownership", errors);
211
+ }
212
+ function checkDbNaming(manifest) {
213
+ const errors = [];
214
+ const dataAccess = manifest.dataAccess;
215
+ for (const table of dataAccess?.ownedTables ?? []) {
216
+ if (!OWNED_TABLE_PATTERN.test(table)) {
217
+ errors.push(`owned table '${table}' must be lowercase_snake_case (${OWNED_TABLE_PATTERN}).`);
218
+ }
219
+ }
220
+ const prefix = dataAccess?.ownedDataTablePrefix;
221
+ if (prefix !== void 0 && prefix !== "" && !OWNED_PREFIX_PATTERN.test(prefix)) {
222
+ errors.push(`ownedDataTablePrefix '${prefix}' must be lowercase_snake_case ending in '_' (${OWNED_PREFIX_PATTERN}).`);
223
+ }
224
+ return makeResult("db-naming", errors);
225
+ }
226
+ function runCertificationChecks(manifest) {
227
+ return [
228
+ checkManifestValid(manifest),
229
+ checkCapabilitiesVsTrustLevel(manifest),
230
+ checkCompatibilityShape(manifest),
231
+ checkLookupOwnership(manifest),
232
+ checkDbNaming(manifest)
233
+ ];
234
+ }
235
+ function definePluginCertification(config) {
236
+ if (!config.pluginId || config.pluginId.trim() === "") {
237
+ throw new Error("definePluginCertification: pluginId is required.");
238
+ }
239
+ return {
240
+ pluginId: config.pluginId,
241
+ kitVersion: CERTIFICATION_KIT_VERSION,
242
+ config,
243
+ checks: CERTIFICATION_CHECKS,
244
+ run(manifest) {
245
+ const results = runCertificationChecks(manifest);
246
+ return {
247
+ pluginId: config.pluginId,
248
+ kitVersion: CERTIFICATION_KIT_VERSION,
249
+ passed: results.every((r) => r.passed),
250
+ results
251
+ };
252
+ }
253
+ };
254
+ }
255
+ function mockMercureHub() {
256
+ const updates = [];
257
+ return {
258
+ updates,
259
+ publish(topic, data = null) {
260
+ updates.push({ topic, data });
261
+ },
262
+ publishedTopics() {
263
+ return [...new Set(updates.map((u) => u.topic))];
264
+ },
265
+ countForTopic(topic) {
266
+ return updates.filter((u) => u.topic === topic).length;
267
+ },
268
+ reset() {
269
+ updates.length = 0;
270
+ }
271
+ };
272
+ }
273
+ function seedFromLockFile(lockJson) {
274
+ const plugins = [];
275
+ if (lockJson && typeof lockJson === "object" && "plugins" in lockJson) {
276
+ const raw = lockJson.plugins;
277
+ if (raw && typeof raw === "object") {
278
+ for (const [pluginId, entry] of Object.entries(raw)) {
279
+ const version = entry && typeof entry === "object" && "version" in entry ? String(entry.version) : "0.0.0";
280
+ plugins.push({ pluginId, version });
281
+ }
282
+ }
283
+ }
284
+ return { plugins };
285
+ }
286
+ export {
287
+ CERTIFICATION_CHECKS,
288
+ CERTIFICATION_KIT_VERSION,
289
+ checkCapabilitiesVsTrustLevel,
290
+ checkCompatibilityShape,
291
+ checkDbNaming,
292
+ checkLookupOwnership,
293
+ checkManifestValid,
294
+ definePluginCertification,
295
+ mockMercureHub,
296
+ runCertificationChecks,
297
+ seedFromLockFile
298
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selfhelp/shared",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
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",
@@ -38,6 +38,11 @@
38
38
  "types": "./dist/plugin-sdk/index.d.ts",
39
39
  "import": "./dist/plugin-sdk/index.mjs",
40
40
  "require": "./dist/plugin-sdk/index.js"
41
+ },
42
+ "./testing": {
43
+ "types": "./dist/testing/index.d.ts",
44
+ "import": "./dist/testing/index.mjs",
45
+ "require": "./dist/testing/index.js"
41
46
  }
42
47
  },
43
48
  "files": [
@@ -47,11 +52,14 @@
47
52
  "CHANGELOG.md"
48
53
  ],
49
54
  "scripts": {
50
- "build": "tsup src/index.ts src/registry/index.ts src/theme/index.ts src/theme/tailwind.ts src/plugin-sdk/index.ts --format cjs,esm --dts --clean --no-splitting",
51
- "dev": "tsup src/index.ts src/registry/index.ts src/theme/index.ts src/theme/tailwind.ts src/plugin-sdk/index.ts --format cjs,esm --dts --watch --no-splitting",
55
+ "build": "tsup src/index.ts src/registry/index.ts src/theme/index.ts src/theme/tailwind.ts src/plugin-sdk/index.ts src/testing/index.ts --format cjs,esm --dts --clean --no-splitting",
56
+ "dev": "tsup src/index.ts src/registry/index.ts src/theme/index.ts src/theme/tailwind.ts src/plugin-sdk/index.ts src/testing/index.ts --format cjs,esm --dts --watch --no-splitting",
52
57
  "lint": "eslint . --ext .ts",
53
58
  "typecheck": "tsc --noEmit",
54
59
  "test": "vitest run --passWithNoTests",
60
+ "test:coverage": "vitest run --coverage",
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",
55
63
  "check:schemas": "node scripts/check-schema-parity.mjs",
56
64
  "prepublishOnly": "npm run build",
57
65
  "headers:check": "license-check-and-add check -f license-check-and-add-config.json",
@@ -75,6 +83,7 @@
75
83
  "@types/react": "^19.2.15",
76
84
  "@typescript-eslint/eslint-plugin": "^8.0.0",
77
85
  "@typescript-eslint/parser": "^8.0.0",
86
+ "@vitest/coverage-istanbul": "^2.1.9",
78
87
  "eslint": "^9.18.0",
79
88
  "license-check-and-add": "^4.0.5",
80
89
  "react": "^19.2.6",
@@ -24,6 +24,7 @@ export const ENDPOINTS = {
24
24
  UPDATE_NAME: `${API_VERSION_PREFIX}/auth/user/name`,
25
25
  UPDATE_PASSWORD: `${API_VERSION_PREFIX}/auth/user/password`,
26
26
  UPDATE_TIMEZONE: `${API_VERSION_PREFIX}/auth/user/timezone`,
27
+ UPDATE_COMMUNICATION_PREFERENCES: `${API_VERSION_PREFIX}/auth/user/communication-preferences`,
27
28
  DELETE_ACCOUNT: `${API_VERSION_PREFIX}/auth/user/account`,
28
29
  VALIDATE_TOKEN: (userId: number, token: string): string =>
29
30
  `${API_VERSION_PREFIX}/validate/${userId}/${token}`,
@@ -0,0 +1,61 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ import { describe, it, expect } from 'vitest';
6
+ import { resolveAssetUrl, resolveAssetSources } from '../resolveAssetUrl';
7
+
8
+ describe('resolveAssetUrl', () => {
9
+ const base = 'https://api.example.com';
10
+
11
+ it('prefixes a root-relative path with the base url', () => {
12
+ expect(resolveAssetUrl('/assets/img/foo.png', base)).toBe('https://api.example.com/assets/img/foo.png');
13
+ });
14
+
15
+ it('adds a leading slash for paths that lack one', () => {
16
+ expect(resolveAssetUrl('assets/foo.png', base)).toBe('https://api.example.com/assets/foo.png');
17
+ });
18
+
19
+ it('strips trailing slashes from the base url', () => {
20
+ expect(resolveAssetUrl('/foo.png', 'https://api.example.com/')).toBe('https://api.example.com/foo.png');
21
+ });
22
+
23
+ it('passes absolute http(s) urls through unchanged', () => {
24
+ expect(resolveAssetUrl('https://cdn.example.com/foo.png', base)).toBe('https://cdn.example.com/foo.png');
25
+ });
26
+
27
+ it('passes protocol-relative urls through unchanged', () => {
28
+ expect(resolveAssetUrl('//cdn.example.com/foo.png', base)).toBe('//cdn.example.com/foo.png');
29
+ });
30
+
31
+ it('passes data/blob/file uris through unchanged', () => {
32
+ expect(resolveAssetUrl('data:image/png;base64,AAAA', base)).toBe('data:image/png;base64,AAAA');
33
+ expect(resolveAssetUrl('blob:abc', base)).toBe('blob:abc');
34
+ });
35
+
36
+ it('returns an empty string for null/undefined/empty input', () => {
37
+ expect(resolveAssetUrl(null, base)).toBe('');
38
+ expect(resolveAssetUrl(undefined, base)).toBe('');
39
+ expect(resolveAssetUrl('', base)).toBe('');
40
+ });
41
+ });
42
+
43
+ describe('resolveAssetSources', () => {
44
+ it('resolves the src of each source and keeps other fields', () => {
45
+ const resolved = resolveAssetSources(
46
+ [
47
+ { src: '/a.mp4', type: 'video/mp4' },
48
+ { src: 'https://cdn/b.webm', type: 'video/webm' },
49
+ ],
50
+ 'https://api.example.com',
51
+ );
52
+ expect(resolved).toEqual([
53
+ { src: 'https://api.example.com/a.mp4', type: 'video/mp4' },
54
+ { src: 'https://cdn/b.webm', type: 'video/webm' },
55
+ ]);
56
+ });
57
+
58
+ it('returns an empty array for undefined sources', () => {
59
+ expect(resolveAssetSources(undefined, 'https://api.example.com')).toEqual([]);
60
+ });
61
+ });
@@ -0,0 +1,63 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ import { describe, it, expect, vi } from 'vitest';
6
+ import { classifyClass, classifyClassString, type TClassDecision } from '../classify';
7
+
8
+ describe('classifyClass (css_mobile classifier)', () => {
9
+ it('allows literal classes from the allow-list', () => {
10
+ expect(classifyClass('flex')).toEqual({ kind: 'allow', className: 'flex' });
11
+ expect(classifyClass('rounded')).toEqual({ kind: 'allow', className: 'rounded' });
12
+ });
13
+
14
+ it('allows pattern classes (spacing / color scale)', () => {
15
+ expect(classifyClass('mt-md').kind).toBe('allow');
16
+ expect(classifyClass('text-blue-6').kind).toBe('allow');
17
+ expect(classifyClass('p-4').kind).toBe('allow');
18
+ });
19
+
20
+ it('allows arbitrary value classes (Uniwind handles them)', () => {
21
+ expect(classifyClass('w-[120px]')).toEqual({ kind: 'allow', className: 'w-[120px]' });
22
+ });
23
+
24
+ it('remaps legacy aliases before the allow-list check', () => {
25
+ expect(classifyClass('mantine-fw')).toMatchObject({ kind: 'remap', from: 'mantine-fw', to: 'w-full' });
26
+ });
27
+
28
+ it('drops classes remapped to null (no mobile equivalent)', () => {
29
+ expect(classifyClass('cursor-pointer').kind).toBe('drop');
30
+ expect(classifyClass('hover:underline').kind).toBe('drop');
31
+ });
32
+
33
+ it('drops classes outside the allow-list', () => {
34
+ expect(classifyClass('grid-cols-7').kind).toBe('drop');
35
+ expect(classifyClass('').kind).toBe('drop');
36
+ });
37
+ });
38
+
39
+ describe('classifyClassString', () => {
40
+ it('returns only allowed/remapped classes and warns on drops + remaps', () => {
41
+ const warnings: TClassDecision[] = [];
42
+ const out = classifyClassString(
43
+ 'flex mt-md mantine-fw cursor-pointer grid-cols-7 w-[120px]',
44
+ (d) => warnings.push(d),
45
+ );
46
+
47
+ expect(out).toEqual(['flex', 'mt-md', 'w-full', 'w-[120px]']);
48
+ // cursor-pointer (drop) + grid-cols-7 (drop) + mantine-fw (remap) = 3 warnings.
49
+ expect(warnings).toHaveLength(3);
50
+ });
51
+
52
+ it('returns an empty array for null/undefined/empty input', () => {
53
+ expect(classifyClassString(null)).toEqual([]);
54
+ expect(classifyClassString(undefined)).toEqual([]);
55
+ expect(classifyClassString('')).toEqual([]);
56
+ });
57
+
58
+ it('does not call onWarn for a fully-allowed class string', () => {
59
+ const onWarn = vi.fn();
60
+ expect(classifyClassString('flex mt-md', onWarn)).toEqual(['flex', 'mt-md']);
61
+ expect(onWarn).not.toHaveBeenCalled();
62
+ });
63
+ });
@@ -0,0 +1,54 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ import { describe, it, expect } from 'vitest';
6
+ import { buildConditionContext, evaluateCondition } from '../evaluate';
7
+
8
+ describe('evaluateCondition', () => {
9
+ const ctx = buildConditionContext('web');
10
+
11
+ it('treats a null/empty/whitespace condition as visible (no condition)', () => {
12
+ expect(evaluateCondition(null, ctx).visible).toBe(true);
13
+ expect(evaluateCondition('', ctx).visible).toBe(true);
14
+ expect(evaluateCondition(' ', ctx).visible).toBe(true);
15
+ });
16
+
17
+ it('evaluates a true JSON-Logic rule to visible', () => {
18
+ expect(evaluateCondition('{"==":[1,1]}', ctx).visible).toBe(true);
19
+ });
20
+
21
+ it('evaluates a false JSON-Logic rule to not visible', () => {
22
+ expect(evaluateCondition('{"==":[1,2]}', ctx).visible).toBe(false);
23
+ });
24
+
25
+ it('resolves context variables (platform) from the condition context', () => {
26
+ const rule = '{"==":[{"var":"platform"},"web"]}';
27
+ expect(evaluateCondition(rule, buildConditionContext('web')).visible).toBe(true);
28
+ expect(evaluateCondition(rule, buildConditionContext('mobile')).visible).toBe(false);
29
+ });
30
+
31
+ it('treats invalid JSON as not visible (fail closed, never throws)', () => {
32
+ expect(evaluateCondition('{not json', ctx).visible).toBe(false);
33
+ });
34
+
35
+ it('exposes a debug payload with the error when withDebug is set', () => {
36
+ const result = evaluateCondition('{not json', ctx, { withDebug: true });
37
+ expect(result.visible).toBe(false);
38
+ expect(result.debug?.error).toContain('Invalid JSON');
39
+ expect(result.debug?.condition).toBe('{not json');
40
+ });
41
+ });
42
+
43
+ describe('buildConditionContext', () => {
44
+ it('builds deterministic date/time vars from a fixed "now" and includes the platform', () => {
45
+ const now = new Date(2026, 4, 22, 9, 5, 3); // 2026-05-22 09:05:03 (month is 0-based)
46
+ const ctx = buildConditionContext('mobile', { custom: 'x' }, now);
47
+
48
+ expect(ctx.platform).toBe('mobile');
49
+ expect(ctx.current_date).toBe('2026-05-22');
50
+ expect(ctx.current_time).toBe('09:05:03');
51
+ expect(ctx.current_datetime).toBe('2026-05-22 09:05:03');
52
+ expect(ctx.custom).toBe('x');
53
+ });
54
+ });
@@ -0,0 +1,41 @@
1
+ /*
2
+ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ SPDX-License-Identifier: MPL-2.0
4
+ */
5
+ import { describe, it, expect } from 'vitest';
6
+ import { replaceCalcedValues } from '../replaceCalcedValues';
7
+
8
+ describe('replaceCalcedValues', () => {
9
+ it('replaces a single {{name}} placeholder with its value', () => {
10
+ expect(replaceCalcedValues('Hello {{name}}!', { name: 'Ada' })).toBe('Hello Ada!');
11
+ });
12
+
13
+ it('replaces the double-brace {{{{name}}}} form (backend regex parity)', () => {
14
+ expect(replaceCalcedValues('{{{{score}}}}', { score: 42 })).toBe('42');
15
+ });
16
+
17
+ it('coerces number and boolean values to strings', () => {
18
+ expect(replaceCalcedValues('{{count}}/{{active}}', { count: 3, active: true })).toBe('3/true');
19
+ });
20
+
21
+ it('leaves unknown placeholders intact so editors notice them', () => {
22
+ expect(replaceCalcedValues('Hi {{missing}}', { name: 'Ada' })).toBe('Hi {{missing}}');
23
+ });
24
+
25
+ it('leaves the placeholder intact when the value is null or undefined', () => {
26
+ expect(replaceCalcedValues('{{a}}{{b}}', { a: null, b: undefined })).toBe('{{a}}{{b}}');
27
+ });
28
+
29
+ it('returns an empty string for null/undefined input (never renders "undefined")', () => {
30
+ expect(replaceCalcedValues(null, {})).toBe('');
31
+ expect(replaceCalcedValues(undefined, {})).toBe('');
32
+ });
33
+
34
+ it('trims whitespace inside the braces before lookup', () => {
35
+ expect(replaceCalcedValues('{{ name }}', { name: 'Ada' })).toBe('Ada');
36
+ });
37
+
38
+ it('replaces multiple placeholders in one pass', () => {
39
+ expect(replaceCalcedValues('{{a}} and {{b}}', { a: 'x', b: 'y' })).toBe('x and y');
40
+ });
41
+ });
@@ -93,6 +93,16 @@ export interface IPluginManifestSecurity {
93
93
  }
94
94
 
95
95
  export interface IPluginManifestDataAccess {
96
+ /**
97
+ * Dedicated tables the plugin owns (created by its migrations). Must be
98
+ * `lowercase_snake_case` (schema pattern `^[a-z][a-z0-9_]*$`).
99
+ */
100
+ ownedTables?: string[];
101
+ /**
102
+ * Prefix for CMS `data_tables` rows the plugin creates at runtime. Must be
103
+ * `lowercase_snake_case` ending in `_` (schema pattern `^[a-z][a-z0-9_]*_$`).
104
+ */
105
+ ownedDataTablePrefix?: string;
96
106
  /**
97
107
  * Tables the plugin reads. May be `dataTable:*` for any plugin-owned
98
108
  * data table, `lookup:<typeCode>` for lookup reads, `dataTable:my`