@selfhelp/shared 1.21.5 → 1.21.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -141,7 +141,7 @@ function isPreviewBridgeMessage(value) {
141
141
  case PREVIEW_BRIDGE_MESSAGE.READY:
142
142
  return record.source === "web" || record.source === "mobile";
143
143
  case PREVIEW_BRIDGE_MESSAGE.NAVIGATED:
144
- return (record.source === "web" || record.source === "mobile") && (typeof record.keyword === "string" || record.keyword === null) && typeof record.href === "string";
144
+ return (record.source === "web" || record.source === "mobile") && (typeof record.keyword === "string" || record.keyword === null) && typeof record.href === "string" && (record.path === void 0 || record.path === null || typeof record.path === "string");
145
145
  case PREVIEW_BRIDGE_MESSAGE.NAVIGATE:
146
146
  return (typeof record.keyword === "string" || record.keyword === null) && (record.path === void 0 || record.path === null || typeof record.path === "string");
147
147
  case PREVIEW_BRIDGE_MESSAGE.SET_PREFERENCES:
@@ -415,11 +415,12 @@ var ENDPOINTS = {
415
415
  BY_KEYWORD: (keyword) => `${API_VERSION_PREFIX}/pages/by-keyword/${encodeURIComponent(keyword)}`,
416
416
  BY_ID: (pageId) => `${API_VERSION_PREFIX}/pages/${pageId}`,
417
417
  /**
418
- * DB-driven public path resolution (issue #30): maps a full public URL
419
- * path (e.g. `/reset/42/abc`, `/team/7`) to a page payload + route
420
- * params. `path` is sent URL-encoded as a query parameter.
418
+ * Static resolve route (no query). Always pair with
419
+ * {@link buildPagesResolveUrl} / {@link buildPagesResolvePath} so
420
+ * `path`, `language_id`, and `preview` are encoded identically across
421
+ * SSR, browser, and mobile.
421
422
  */
422
- RESOLVE: (path) => `${API_VERSION_PREFIX}/pages/resolve?path=${encodeURIComponent(path)}`
423
+ RESOLVE_ROUTE: `${API_VERSION_PREFIX}/pages/resolve`
423
424
  },
424
425
  NAVIGATION: {
425
426
  GET: `${API_VERSION_PREFIX}/navigation`,
@@ -441,6 +442,37 @@ var CLIENT_TYPE_WEB = "web";
441
442
  var CLIENT_TYPE_MOBILE = "mobile";
442
443
  var CLIENT_TYPE_MOBILE_AND_WEB = "mobile_and_web";
443
444
 
445
+ // src/api/pagesResolve.ts
446
+ function normalizePagesResolvePath(rawPath) {
447
+ const withoutOrigin = rawPath.includes("://") ? (() => {
448
+ try {
449
+ return new URL(rawPath).pathname;
450
+ } catch {
451
+ return rawPath;
452
+ }
453
+ })() : rawPath;
454
+ const pathOnly = withoutOrigin.split("#")[0].split("?")[0];
455
+ const withSlash = pathOnly.startsWith("/") ? pathOnly : `/${pathOnly}`;
456
+ return withSlash.replace(/\/+$/, "") || "/";
457
+ }
458
+ function buildPagesResolveQuery(params) {
459
+ const search = new URLSearchParams();
460
+ search.set("path", normalizePagesResolvePath(params.path));
461
+ if (params.languageId != null && Number.isFinite(params.languageId) && params.languageId > 0) {
462
+ search.set("language_id", String(params.languageId));
463
+ }
464
+ if (params.preview) {
465
+ search.set("preview", "true");
466
+ }
467
+ return search.toString();
468
+ }
469
+ function buildPagesResolvePath(params) {
470
+ return `/pages/resolve?${buildPagesResolveQuery(params)}`;
471
+ }
472
+ function buildPagesResolveUrl(params) {
473
+ return `${API_VERSION_PREFIX}${buildPagesResolvePath(params)}`;
474
+ }
475
+
444
476
  // src/theme/tokens.ts
445
477
  var FONT_SIZE_PX = {
446
478
  xs: 12,
@@ -1604,6 +1636,118 @@ function serializeFieldsMapLabels(labels) {
1604
1636
  return JSON.stringify(clean);
1605
1637
  }
1606
1638
 
1639
+ // src/content/formRecordPrefill.ts
1640
+ var FORM_RECORD_PREFILL_SKIP_FIELDS = /* @__PURE__ */ new Set([
1641
+ "record_id",
1642
+ "entry_date",
1643
+ "id_users",
1644
+ "user_name",
1645
+ "user_code",
1646
+ "id_actionTriggerTypes",
1647
+ "triggerType",
1648
+ "id_languages",
1649
+ "language_locale",
1650
+ "language_name"
1651
+ ]);
1652
+ function isTranslatableChild(children, fieldName) {
1653
+ if (!Array.isArray(children)) {
1654
+ return false;
1655
+ }
1656
+ const child = children.find((item) => item?.name?.content === fieldName);
1657
+ return child?.translatable?.content === "1";
1658
+ }
1659
+ function asScalarString(value) {
1660
+ if (value === null || value === void 0) {
1661
+ return null;
1662
+ }
1663
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1664
+ return String(value);
1665
+ }
1666
+ return null;
1667
+ }
1668
+ function parseFormRecordPrefill(section) {
1669
+ const sectionDataArray = section?.section_data;
1670
+ if (!Array.isArray(sectionDataArray) || sectionDataArray.length === 0) {
1671
+ return { recordId: null, values: {} };
1672
+ }
1673
+ const recordGroups = {};
1674
+ for (const row of sectionDataArray) {
1675
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
1676
+ continue;
1677
+ }
1678
+ const record = row;
1679
+ const rawRecordId = record.record_id;
1680
+ const recordId = typeof rawRecordId === "number" ? rawRecordId : typeof rawRecordId === "string" && rawRecordId.trim() !== "" && Number.isFinite(Number(rawRecordId)) ? Number(rawRecordId) : null;
1681
+ if (recordId === null) {
1682
+ continue;
1683
+ }
1684
+ if (!recordGroups[recordId]) {
1685
+ recordGroups[recordId] = {};
1686
+ }
1687
+ const languageId = typeof record.id_languages === "number" ? record.id_languages : typeof record.id_languages === "string" && Number.isFinite(Number(record.id_languages)) ? Number(record.id_languages) : void 0;
1688
+ for (const [fieldName, fieldValue] of Object.entries(record)) {
1689
+ if (FORM_RECORD_PREFILL_SKIP_FIELDS.has(fieldName)) {
1690
+ continue;
1691
+ }
1692
+ const value = asScalarString(fieldValue);
1693
+ if (value === null) {
1694
+ continue;
1695
+ }
1696
+ const translatable = isTranslatableChild(section.children, fieldName);
1697
+ if (translatable) {
1698
+ if (languageId === 1) {
1699
+ if (!recordGroups[recordId][fieldName]) {
1700
+ recordGroups[recordId][fieldName] = value;
1701
+ }
1702
+ } else if (typeof languageId === "number") {
1703
+ const current = recordGroups[recordId][fieldName];
1704
+ if (typeof current === "string" || !current) {
1705
+ recordGroups[recordId][fieldName] = [{ language_id: languageId, value }];
1706
+ } else {
1707
+ const langValues = current;
1708
+ const existingIndex = langValues.findIndex((v) => v.language_id === languageId);
1709
+ if (existingIndex >= 0) {
1710
+ langValues[existingIndex] = { language_id: languageId, value };
1711
+ } else {
1712
+ langValues.push({ language_id: languageId, value });
1713
+ }
1714
+ }
1715
+ }
1716
+ } else if (languageId === 1 || !recordGroups[recordId][fieldName]) {
1717
+ recordGroups[recordId][fieldName] = value;
1718
+ }
1719
+ }
1720
+ }
1721
+ const firstRecordId = Object.keys(recordGroups)[0];
1722
+ if (!firstRecordId) {
1723
+ return { recordId: null, values: {} };
1724
+ }
1725
+ const id = Number(firstRecordId);
1726
+ return { recordId: id, values: recordGroups[id] ?? {} };
1727
+ }
1728
+ function flattenFormRecordPrefillValues(values, languageId) {
1729
+ const out = {};
1730
+ for (const [key, value] of Object.entries(values)) {
1731
+ if (typeof value === "string") {
1732
+ out[key] = value;
1733
+ continue;
1734
+ }
1735
+ if (!Array.isArray(value) || value.length === 0) {
1736
+ continue;
1737
+ }
1738
+ if (languageId != null) {
1739
+ const match = value.find((entry) => entry.language_id === languageId);
1740
+ if (match) {
1741
+ out[key] = match.value;
1742
+ continue;
1743
+ }
1744
+ }
1745
+ const nonIndependent = value.find((entry) => entry.language_id !== 1);
1746
+ out[key] = (nonIndependent ?? value[0]).value;
1747
+ }
1748
+ return out;
1749
+ }
1750
+
1607
1751
  // src/navigation/headerPreset.ts
1608
1752
  var WEB_HEADER_PRESET_VALUES = [
1609
1753
  "simple",
@@ -2455,6 +2599,7 @@ export {
2455
2599
  ENDPOINTS,
2456
2600
  FIELDS_MAP_STYLE_CONFIG,
2457
2601
  FONT_SIZE_PX,
2602
+ FORM_RECORD_PREFILL_SKIP_FIELDS,
2458
2603
  FULL_RADIUS_PX,
2459
2604
  HEADER_CLIENT_TYPE,
2460
2605
  LINE_HEIGHT,
@@ -2486,6 +2631,9 @@ export {
2486
2631
  _resetPluginStyleRegistry,
2487
2632
  arePreviewPreferencesEqual,
2488
2633
  buildConditionContext,
2634
+ buildPagesResolvePath,
2635
+ buildPagesResolveQuery,
2636
+ buildPagesResolveUrl,
2489
2637
  buildPublicPathFromRoute,
2490
2638
  clampMenuItemsAtDepth,
2491
2639
  classifyClass,
@@ -2500,6 +2648,7 @@ export {
2500
2648
  findPageRefInNavigationPayload,
2501
2649
  findRemap,
2502
2650
  flattenFooterItems,
2651
+ flattenFormRecordPrefillValues,
2503
2652
  flattenMenuItems,
2504
2653
  flattenNavigationMenuItems,
2505
2654
  footerColumnItems,
@@ -2554,11 +2703,13 @@ export {
2554
2703
  matchesMobilePath,
2555
2704
  matchesWebPath,
2556
2705
  mergeHeaderLayers,
2706
+ normalizePagesResolvePath,
2557
2707
  pageUrlToMobileRoute,
2558
2708
  parseDimensionToReactNative,
2559
2709
  parseDimensionToWeb,
2560
2710
  parseFieldsMapCatalog,
2561
2711
  parseFieldsMapLabels,
2712
+ parseFormRecordPrefill,
2562
2713
  parseInlineRich,
2563
2714
  parseOptionCatalog,
2564
2715
  parseOptionCodes,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selfhelp/shared",
3
- "version": "1.21.5",
3
+ "version": "1.21.6",
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",
@@ -5,6 +5,12 @@
5
5
 
6
6
  import { describe, expect, it } from 'vitest';
7
7
  import { API_VERSION_PREFIX, ENDPOINTS } from '../endpoints';
8
+ import {
9
+ buildPagesResolvePath,
10
+ buildPagesResolveQuery,
11
+ buildPagesResolveUrl,
12
+ normalizePagesResolvePath,
13
+ } from '../pagesResolve';
8
14
  import type {
9
15
  IForgotPasswordRequest,
10
16
  IResetPasswordRequest,
@@ -45,24 +51,43 @@ describe('ENDPOINTS.AUTH password recovery', () => {
45
51
  });
46
52
 
47
53
  /**
48
- * Contract coverage for the DB-driven public path resolver (issue #30). The web
49
- * frontend SSR layer and the mobile app both build the resolve request from
50
- * `ENDPOINTS.PAGES.RESOLVE`, so a wrong/missing path silently breaks every
51
- * parameterized public URL (`/reset/{user_id}/{token}`, `/team/{record_id}`).
54
+ * Canonical resolve contract: SSR, browser, and mobile must produce the same
55
+ * query encoding for path / language_id / preview.
52
56
  */
53
- describe('ENDPOINTS.PAGES.RESOLVE (DB-driven routing)', () => {
54
- it('builds the resolve endpoint with the path as a URL-encoded query param', () => {
55
- expect(ENDPOINTS.PAGES.RESOLVE('/team/7')).toBe(
57
+ describe('buildPagesResolve* (DB-driven routing)', () => {
58
+ it('exposes the static resolve route constant', () => {
59
+ expect(ENDPOINTS.PAGES.RESOLVE_ROUTE).toBe(`${API_VERSION_PREFIX}/pages/resolve`);
60
+ });
61
+
62
+ it('normalizes paths before encoding', () => {
63
+ expect(normalizePagesResolvePath('/team/7/')).toBe('/team/7');
64
+ expect(normalizePagesResolvePath('team/7')).toBe('/team/7');
65
+ expect(normalizePagesResolvePath('/')).toBe('/');
66
+ expect(normalizePagesResolvePath('/reset/42/abc?x=1#y')).toBe('/reset/42/abc');
67
+ });
68
+
69
+ it('builds identical BFF and full URLs for path-only resolve', () => {
70
+ const params = { path: '/team/7' };
71
+ expect(buildPagesResolveQuery(params)).toBe('path=%2Fteam%2F7');
72
+ expect(buildPagesResolvePath(params)).toBe('/pages/resolve?path=%2Fteam%2F7');
73
+ expect(buildPagesResolveUrl(params)).toBe(
56
74
  `${API_VERSION_PREFIX}/pages/resolve?path=%2Fteam%2F7`,
57
75
  );
58
76
  });
59
77
 
60
- it('encodes reset/validate token paths so slashes survive transport', () => {
61
- expect(ENDPOINTS.PAGES.RESOLVE('/reset/42/abc.def~1')).toBe(
62
- `${API_VERSION_PREFIX}/pages/resolve?path=%2Freset%2F42%2Fabc.def~1`,
78
+ it('includes language_id and preview=true when requested', () => {
79
+ const params = { path: '/reset/42/abc.def~1', languageId: 2, preview: true };
80
+ expect(buildPagesResolveQuery(params)).toBe(
81
+ 'path=%2Freset%2F42%2Fabc.def%7E1&language_id=2&preview=true',
63
82
  );
64
- expect(ENDPOINTS.PAGES.RESOLVE('/')).toBe(
65
- `${API_VERSION_PREFIX}/pages/resolve?path=%2F`,
83
+ expect(buildPagesResolveUrl(params)).toBe(
84
+ `${API_VERSION_PREFIX}/pages/resolve?path=%2Freset%2F42%2Fabc.def%7E1&language_id=2&preview=true`,
66
85
  );
67
86
  });
87
+
88
+ it('omits language_id when absent or non-positive', () => {
89
+ expect(buildPagesResolveQuery({ path: '/', languageId: null })).toBe('path=%2F');
90
+ expect(buildPagesResolveQuery({ path: '/', languageId: 0 })).toBe('path=%2F');
91
+ expect(buildPagesResolveQuery({ path: '/', preview: false })).toBe('path=%2F');
92
+ });
68
93
  });
@@ -41,12 +41,12 @@ export const ENDPOINTS = {
41
41
  `${API_VERSION_PREFIX}/pages/by-keyword/${encodeURIComponent(keyword)}`,
42
42
  BY_ID: (pageId: number): string => `${API_VERSION_PREFIX}/pages/${pageId}`,
43
43
  /**
44
- * DB-driven public path resolution (issue #30): maps a full public URL
45
- * path (e.g. `/reset/42/abc`, `/team/7`) to a page payload + route
46
- * params. `path` is sent URL-encoded as a query parameter.
44
+ * Static resolve route (no query). Always pair with
45
+ * {@link buildPagesResolveUrl} / {@link buildPagesResolvePath} so
46
+ * `path`, `language_id`, and `preview` are encoded identically across
47
+ * SSR, browser, and mobile.
47
48
  */
48
- RESOLVE: (path: string): string =>
49
- `${API_VERSION_PREFIX}/pages/resolve?path=${encodeURIComponent(path)}`,
49
+ RESOLVE_ROUTE: `${API_VERSION_PREFIX}/pages/resolve`,
50
50
  },
51
51
  NAVIGATION: {
52
52
  GET: `${API_VERSION_PREFIX}/navigation`,
package/src/api/index.ts CHANGED
@@ -3,3 +3,4 @@ SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
3
  SPDX-License-Identifier: MPL-2.0
4
4
  */
5
5
  export * from './endpoints';
6
+ export * from './pagesResolve';
@@ -0,0 +1,78 @@
1
+ /*
2
+ * SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ * SPDX-License-Identifier: MPL-2.0
4
+ */
5
+
6
+ /**
7
+ * Canonical public page resolve contract (issue #30).
8
+ *
9
+ * Frontend SSR, frontend browser client, and mobile MUST build resolve
10
+ * requests through these helpers so path / language_id / preview encoding
11
+ * cannot drift between clients.
12
+ */
13
+
14
+ import { API_VERSION_PREFIX } from './endpoints';
15
+
16
+ /** Inputs accepted by `GET /pages/resolve`. */
17
+ export interface IPagesResolveParams {
18
+ /** Public URL path, e.g. `/team/7`, `/reset/42/abc`, `/`. */
19
+ path: string;
20
+ /** Optional language id query param. */
21
+ languageId?: number | null;
22
+ /**
23
+ * When true, request unpublished draft content. Backend requires an
24
+ * authenticated caller (`preview=true`).
25
+ */
26
+ preview?: boolean;
27
+ }
28
+
29
+ /**
30
+ * Normalize a public path for the resolve query: strip origin fragments /
31
+ * search, ensure a leading slash, collapse a trailing slash (except root).
32
+ */
33
+ export function normalizePagesResolvePath(rawPath: string): string {
34
+ const withoutOrigin = rawPath.includes('://')
35
+ ? (() => {
36
+ try {
37
+ return new URL(rawPath).pathname;
38
+ } catch {
39
+ return rawPath;
40
+ }
41
+ })()
42
+ : rawPath;
43
+ const pathOnly = withoutOrigin.split('#')[0].split('?')[0];
44
+ const withSlash = pathOnly.startsWith('/') ? pathOnly : `/${pathOnly}`;
45
+ return withSlash.replace(/\/+$/, '') || '/';
46
+ }
47
+
48
+ /**
49
+ * Build the query string for `/pages/resolve` (no leading `?`).
50
+ * Always includes `path`; optionally `language_id` and `preview=true`.
51
+ */
52
+ export function buildPagesResolveQuery(params: IPagesResolveParams): string {
53
+ const search = new URLSearchParams();
54
+ search.set('path', normalizePagesResolvePath(params.path));
55
+ if (params.languageId != null && Number.isFinite(params.languageId) && params.languageId > 0) {
56
+ search.set('language_id', String(params.languageId));
57
+ }
58
+ if (params.preview) {
59
+ search.set('preview', 'true');
60
+ }
61
+ return search.toString();
62
+ }
63
+
64
+ /**
65
+ * BFF-relative resolve path used by the Next.js frontend
66
+ * (`/pages/resolve?path=…`).
67
+ */
68
+ export function buildPagesResolvePath(params: IPagesResolveParams): string {
69
+ return `/pages/resolve?${buildPagesResolveQuery(params)}`;
70
+ }
71
+
72
+ /**
73
+ * Full Symfony path including `/cms-api/v1` — used by mobile and any
74
+ * direct-to-backend client.
75
+ */
76
+ export function buildPagesResolveUrl(params: IPagesResolveParams): string {
77
+ return `${API_VERSION_PREFIX}${buildPagesResolvePath(params)}`;
78
+ }
@@ -0,0 +1,104 @@
1
+ /*
2
+ * SPDX-FileCopyrightText: 2026 Humdek, University of Bern
3
+ * SPDX-License-Identifier: MPL-2.0
4
+ */
5
+
6
+ import { describe, expect, it } from 'vitest';
7
+ import {
8
+ flattenFormRecordPrefillValues,
9
+ parseFormRecordPrefill,
10
+ } from '../formRecordPrefill';
11
+
12
+ describe('parseFormRecordPrefill', () => {
13
+ it('returns empty create state when section_data is missing', () => {
14
+ expect(parseFormRecordPrefill({})).toEqual({ recordId: null, values: {} });
15
+ expect(parseFormRecordPrefill({ section_data: null })).toEqual({
16
+ recordId: null,
17
+ values: {},
18
+ });
19
+ expect(parseFormRecordPrefill({ section_data: [] })).toEqual({
20
+ recordId: null,
21
+ values: {},
22
+ });
23
+ });
24
+
25
+ it('flattens the first hydrated record and skips metadata fields', () => {
26
+ const result = parseFormRecordPrefill({
27
+ section_data: [
28
+ {
29
+ record_id: 12,
30
+ id_users: 3,
31
+ user_name: 'qa.user',
32
+ id_languages: 1,
33
+ title: 'Hello',
34
+ body: 'World',
35
+ },
36
+ ],
37
+ children: [
38
+ { name: { content: 'title' }, translatable: { content: '0' } },
39
+ { name: { content: 'body' }, translatable: { content: '0' } },
40
+ ],
41
+ });
42
+ expect(result).toEqual({
43
+ recordId: 12,
44
+ values: { title: 'Hello', body: 'World' },
45
+ });
46
+ });
47
+
48
+ it('accumulates per-language values for translatable fields', () => {
49
+ const result = parseFormRecordPrefill({
50
+ section_data: [
51
+ { record_id: 5, id_languages: 1, bio: 'Independent seed' },
52
+ { record_id: 5, id_languages: 2, bio: 'DE bio' },
53
+ { record_id: 5, id_languages: 3, bio: 'EN bio' },
54
+ ],
55
+ children: [{ name: { content: 'bio' }, translatable: { content: '1' } }],
56
+ });
57
+ expect(result.recordId).toBe(5);
58
+ expect(result.values.bio).toEqual([
59
+ { language_id: 2, value: 'DE bio' },
60
+ { language_id: 3, value: 'EN bio' },
61
+ ]);
62
+ });
63
+
64
+ it('ignores malformed rows and nested non-scalar field values', () => {
65
+ const result = parseFormRecordPrefill({
66
+ section_data: [
67
+ null,
68
+ 'skip',
69
+ { record_id: 'nope', title: 'x' },
70
+ { record_id: 9, id_languages: 1, title: 'ok', nested: { a: 1 }, list: [1, 2] },
71
+ ],
72
+ children: [{ name: { content: 'title' }, translatable: { content: '0' } }],
73
+ });
74
+ expect(result).toEqual({ recordId: 9, values: { title: 'ok' } });
75
+ });
76
+
77
+ it('accepts numeric string record_id from JSON payloads', () => {
78
+ const result = parseFormRecordPrefill({
79
+ section_data: [{ record_id: '42', id_languages: 1, name: 'Ada' }],
80
+ children: [{ name: { content: 'name' }, translatable: { content: '0' } }],
81
+ });
82
+ expect(result).toEqual({ recordId: 42, values: { name: 'Ada' } });
83
+ });
84
+ });
85
+
86
+ describe('flattenFormRecordPrefillValues', () => {
87
+ it('prefers the requested language, else first public language', () => {
88
+ const values = {
89
+ bio: [
90
+ { language_id: 2, value: 'DE' },
91
+ { language_id: 3, value: 'EN' },
92
+ ],
93
+ title: 'plain',
94
+ };
95
+ expect(flattenFormRecordPrefillValues(values, 3)).toEqual({
96
+ bio: 'EN',
97
+ title: 'plain',
98
+ });
99
+ expect(flattenFormRecordPrefillValues(values)).toEqual({
100
+ bio: 'DE',
101
+ title: 'plain',
102
+ });
103
+ });
104
+ });