asma-core-helpers 0.41.2 → 0.42.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.
@@ -0,0 +1,40 @@
1
+ export interface TableSettingsKeyOptions {
2
+ /**
3
+ * A short, stable name for a view of the same table, for example `ME` or `RECIPIENT`. It is kept only if
4
+ * it matches [A-Za-z0-9-]{0,32}; anything else becomes ''.
5
+ *
6
+ * It must be an opaque name chosen by the app, never a patient, questionnaire, answer or record id, and
7
+ * never free text (AC 12 of ASMA-8597: keys hold no record data). The pattern checks the shape only: a
8
+ * numeric string or another short id of up to 32 characters passes, because the helper cannot tell it from
9
+ * a name; a non-string number and a 36-character UUID do not.
10
+ */
11
+ context?: string;
12
+ }
13
+ /**
14
+ * Storage key for a table's saved settings: `${tableId}_${userId}_${customerId}_${context}`, the format
15
+ * asma-app-directory's `generateUniqKey` already uses. Returns `undefined` until both the signed-in user
16
+ * and the tenant are known, or when `tableId` is not a valid id, so a table shows its defaults and saves
17
+ * nothing instead of writing a `…_undefined_…` key.
18
+ *
19
+ * Naming rule for new table ids: `<app>.<table>` in lowercase kebab-case, for example
20
+ * `directory.my-participants`. Name the table, never a header label, a position or a record id.
21
+ *
22
+ * @param tableId A stable, opaque name for the table. It must never be a patient, questionnaire, answer or
23
+ * record id, or anything built from one (AC 12 of ASMA-8597: keys hold no record data). The helper does not
24
+ * guard against this: a UUID-shaped id passes. Keeping such ids out of keys is the job of the key inventory
25
+ * in ASMA-8698 (AC 3) and of each app's own migration to this helper.
26
+ * @param options `context` is the same kind of name, see {@link TableSettingsKeyOptions}.
27
+ *
28
+ * The helper never reads the URL: pass the app's current context (for example its `user_context` value)
29
+ * as `options.context`. A key contains only the table id, the opaque user and tenant ids and the sanitized
30
+ * context, never names or record data.
31
+ */
32
+ export declare function getTableSettingsKey(tableId: string, options?: TableSettingsKeyOptions): string | undefined;
33
+ /**
34
+ * Calls `listener` after `jwt_changed`, `logout_event` and every history change, and returns the function
35
+ * that unsubscribes from all three. History is included because an app's context usually comes from the
36
+ * URL. The listener only signals; read the key again with `getTableSettingsKey`. Made for
37
+ * `useSyncExternalStore(onTableSettingsKeyChange, () => getTableSettingsKey(id, { context }))`.
38
+ */
39
+ export declare function onTableSettingsKeyChange(listener: () => void): () => void;
40
+ //# sourceMappingURL=tableSettingsKey.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tableSettingsKey.d.ts","sourceRoot":"","sources":["../../src/helpers/tableSettingsKey.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,uBAAuB;IACpC;;;;;;;;OAQG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACnB;AA8BD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,uBAAuB,GAAG,MAAM,GAAG,SAAS,CAY1G;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAUzE"}
@@ -0,0 +1,73 @@
1
+ import { subscribeToHistory } from '../g-definitions.js';
2
+ import { registerCallbackOnSrvAuthEvents } from './generateSrvAuthBindings.js';
3
+ import { realWindow } from './getSubdomain.js';
4
+ /**
5
+ * `<app>.<table>` for new ids; legacy ids such as `UsersTable` pass too. Rejects spaces, `:`, `/` and non-ASCII.
6
+ * It checks the shape only, so a UUID-shaped id passes; see the `tableId` rule on `getTableSettingsKey`.
7
+ */
8
+ const TABLE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
9
+ const CONTEXT_PATTERN = /^[A-Za-z0-9-]{0,32}$/;
10
+ function readUserAndCustomerId() {
11
+ try {
12
+ const metadata = realWindow.__ASMA__SHELL__?.auth_bindings?.getMetadata();
13
+ // The shell fills these from a server response, so check them at runtime, whatever the types promise.
14
+ const userId = metadata?.user_id;
15
+ const customerId = metadata?.customer_id;
16
+ if (typeof userId !== 'string' || userId === '' || typeof customerId !== 'string' || customerId === '') {
17
+ return undefined;
18
+ }
19
+ return { userId, customerId };
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ }
25
+ function sanitizeContext(context) {
26
+ return typeof context === 'string' && CONTEXT_PATTERN.test(context) ? context : '';
27
+ }
28
+ /**
29
+ * Storage key for a table's saved settings: `${tableId}_${userId}_${customerId}_${context}`, the format
30
+ * asma-app-directory's `generateUniqKey` already uses. Returns `undefined` until both the signed-in user
31
+ * and the tenant are known, or when `tableId` is not a valid id, so a table shows its defaults and saves
32
+ * nothing instead of writing a `…_undefined_…` key.
33
+ *
34
+ * Naming rule for new table ids: `<app>.<table>` in lowercase kebab-case, for example
35
+ * `directory.my-participants`. Name the table, never a header label, a position or a record id.
36
+ *
37
+ * @param tableId A stable, opaque name for the table. It must never be a patient, questionnaire, answer or
38
+ * record id, or anything built from one (AC 12 of ASMA-8597: keys hold no record data). The helper does not
39
+ * guard against this: a UUID-shaped id passes. Keeping such ids out of keys is the job of the key inventory
40
+ * in ASMA-8698 (AC 3) and of each app's own migration to this helper.
41
+ * @param options `context` is the same kind of name, see {@link TableSettingsKeyOptions}.
42
+ *
43
+ * The helper never reads the URL: pass the app's current context (for example its `user_context` value)
44
+ * as `options.context`. A key contains only the table id, the opaque user and tenant ids and the sanitized
45
+ * context, never names or record data.
46
+ */
47
+ export function getTableSettingsKey(tableId, options) {
48
+ if (typeof tableId !== 'string' || !TABLE_ID_PATTERN.test(tableId)) {
49
+ return undefined;
50
+ }
51
+ const ids = readUserAndCustomerId();
52
+ if (!ids) {
53
+ return undefined;
54
+ }
55
+ return `${tableId}_${ids.userId}_${ids.customerId}_${sanitizeContext(options?.context)}`;
56
+ }
57
+ /**
58
+ * Calls `listener` after `jwt_changed`, `logout_event` and every history change, and returns the function
59
+ * that unsubscribes from all three. History is included because an app's context usually comes from the
60
+ * URL. The listener only signals; read the key again with `getTableSettingsKey`. Made for
61
+ * `useSyncExternalStore(onTableSettingsKeyChange, () => getTableSettingsKey(id, { context }))`.
62
+ */
63
+ export function onTableSettingsKeyChange(listener) {
64
+ const jwtChanged = registerCallbackOnSrvAuthEvents('jwt_changed', () => listener());
65
+ const loggedOut = registerCallbackOnSrvAuthEvents('logout_event', () => listener());
66
+ const unsubscribeHistory = subscribeToHistory(() => listener());
67
+ return () => {
68
+ jwtChanged.unregister();
69
+ loggedOut.unregister();
70
+ unsubscribeHistory();
71
+ };
72
+ }
73
+ //# sourceMappingURL=tableSettingsKey.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tableSettingsKey.js","sourceRoot":"","sources":["../../src/helpers/tableSettingsKey.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AACxD,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAA;AAC9E,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAe9C;;;GAGG;AACH,MAAM,gBAAgB,GAAG,mCAAmC,CAAA;AAC5D,MAAM,eAAe,GAAG,sBAAsB,CAAA;AAE9C,SAAS,qBAAqB;IAC1B,IAAI,CAAC;QACD,MAAM,QAAQ,GAAG,UAAU,CAAC,eAAe,EAAE,aAAa,EAAE,WAAW,EAAE,CAAA;QACzE,sGAAsG;QACtG,MAAM,MAAM,GAAY,QAAQ,EAAE,OAAO,CAAA;QACzC,MAAM,UAAU,GAAY,QAAQ,EAAE,WAAW,CAAA;QAEjD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,EAAE,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,KAAK,EAAE,EAAE,CAAC;YACrG,OAAO,SAAS,CAAA;QACpB,CAAC;QAED,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,CAAA;IACjC,CAAC;IAAC,MAAM,CAAC;QACL,OAAO,SAAS,CAAA;IACpB,CAAC;AACL,CAAC;AAED,SAAS,eAAe,CAAC,OAAgB;IACrC,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAA;AACtF,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAe,EAAE,OAAiC;IAClF,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACjE,OAAO,SAAS,CAAA;IACpB,CAAC;IAED,MAAM,GAAG,GAAG,qBAAqB,EAAE,CAAA;IAEnC,IAAI,CAAC,GAAG,EAAE,CAAC;QACP,OAAO,SAAS,CAAA;IACpB,CAAC;IAED,OAAO,GAAG,OAAO,IAAI,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,UAAU,IAAI,eAAe,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,CAAA;AAC5F,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CAAC,QAAoB;IACzD,MAAM,UAAU,GAAG,+BAA+B,CAAC,aAAa,EAAE,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAA;IACnF,MAAM,SAAS,GAAG,+BAA+B,CAAC,cAAc,EAAE,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAA;IACnF,MAAM,kBAAkB,GAAG,kBAAkB,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAA;IAE/D,OAAO,GAAG,EAAE;QACR,UAAU,CAAC,UAAU,EAAE,CAAA;QACvB,SAAS,CAAC,UAAU,EAAE,CAAA;QACtB,kBAAkB,EAAE,CAAA;IACxB,CAAC,CAAA;AACL,CAAC"}
package/lib/index.d.ts CHANGED
@@ -27,6 +27,7 @@ export * from './helpers/initASMAAppVitals.js';
27
27
  export * from './helpers/registerOpenReplay.js';
28
28
  export * from './helpers/urlParams.helpers.js';
29
29
  export * from './helpers/sectionPath.helpers.js';
30
+ export * from './helpers/tableSettingsKey.js';
30
31
  export * from './helpers/openReplayObject.js';
31
32
  export * from './helpers/sha256.js';
32
33
  export * from './helpers/requestIdleCallback.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kCAAkC,CAAA;AAChD,cAAc,oCAAoC,CAAA;AAClD,cAAc,mCAAmC,CAAA;AACjD,cAAc,mCAAmC,CAAA;AACjD,cAAc,wBAAwB,CAAA;AACtC,cAAc,uBAAuB,CAAA;AACrC,cAAc,yBAAyB,CAAA;AACvC,cAAc,uBAAuB,CAAA;AACrC,cAAc,qBAAqB,CAAA;AACnC,cAAc,mDAAmD,CAAA;AACjE,cAAc,iCAAiC,CAAA;AAE/C,cAAc,kCAAkC,CAAA;AAChD,cAAc,uBAAuB,CAAA;AACrC,cAAc,+BAA+B,CAAA;AAC7C,cAAc,wCAAwC,CAAA;AACtD,cAAc,sCAAsC,CAAA;AACpD,cAAc,4CAA4C,CAAA;AAC1D,cAAc,2BAA2B,CAAA;AACzC,cAAc,2CAA2C,CAAA;AACzD,cAAc,6BAA6B,CAAA;AAC3C,cAAc,yCAAyC,CAAA;AACvD,cAAc,+BAA+B,CAAA;AAC7C,cAAc,2BAA2B,CAAA;AACzC,cAAc,yBAAyB,CAAA;AACvC,cAAc,2CAA2C,CAAA;AACzD,cAAc,gCAAgC,CAAA;AAC9C,cAAc,iCAAiC,CAAA;AAC/C,cAAc,gCAAgC,CAAA;AAC9C,cAAc,kCAAkC,CAAA;AAChD,cAAc,+BAA+B,CAAA;AAE7C,cAAc,qBAAqB,CAAA;AACnC,cAAc,kCAAkC,CAAA;AAEhD,cAAc,oBAAoB,CAAA;AAElC,cAAc,sBAAsB,CAAA;AAEpC,cAAc,uBAAuB,CAAA;AAErC,cAAc,oBAAoB,CAAA;AAElC,cAAc,8CAA8C,CAAA;AAC5D,cAAc,+CAA+C,CAAA;AAC7D,cAAc,mCA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AC7C,cAAc,+BAA+B,CAAA;AAE7C,cAAc,qBAAqB,CAAA;AACnC,cAAc,kCAAkC,CAAA;AAEhD,cAAc,oBAAoB,CAAA;AAElC,cAAc,sBAAsB,CAAA;AAEpC,cAAc,uBAAuB,CAAA;AAErC,cAAc,oBAAoB,CAAA;AAElC,cAAc,8CAA8C,CAAA;AAC5D,cAAc,+CAA+C,CAAA;AAC7D,cAAc,mCAAmC,CAAA;AACjD,cAAc,qBAAqB,CAAA;AACnC,cAAc,uCAAuC,CAAA;AACrD,cAAc,gCAAgC,CAAA;AAC9C,cAAc,kCAAkC,CAAA;AAEhD,OAAO,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAA;AAC9E,YAAY,EAAE,8BAA8B,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAA;AAC5G,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAA;AACzF,YAAY,EAAE,4BAA4B,EAAE,MAAM,oCAAoC,CAAA"}
package/lib/index.js CHANGED
@@ -27,6 +27,7 @@ export * from './helpers/initASMAAppVitals.js';
27
27
  export * from './helpers/registerOpenReplay.js';
28
28
  export * from './helpers/urlParams.helpers.js';
29
29
  export * from './helpers/sectionPath.helpers.js';
30
+ export * from './helpers/tableSettingsKey.js';
30
31
  export * from './helpers/openReplayObject.js';
31
32
  //export * from './helpers/openReplayConfigs.js'
32
33
  export * from './helpers/sha256.js';
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kCAAkC,CAAA;AAChD,cAAc,oCAAoC,CAAA;AAClD,cAAc,mCAAmC,CAAA;AACjD,cAAc,mCAAmC,CAAA;AACjD,cAAc,wBAAwB,CAAA;AACtC,cAAc,uBAAuB,CAAA;AACrC,cAAc,yBAAyB,CAAA;AACvC,cAAc,uBAAuB,CAAA;AACrC,cAAc,qBAAqB,CAAA;AACnC,cAAc,m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
2
  "name": "asma-core-helpers",
3
- "version": "0.41.2",
3
+ "version": "0.42.0",
4
4
  "description": "Core helper utilities for ASMA applications",
5
5
  "files": [
6
6
  "lib/**/*",
@@ -52,7 +52,7 @@
52
52
  "devDependencies": {
53
53
  "@openreplay/tracker": "^16.4.10",
54
54
  "asma-qiankun-react-loader": "^0.8.2",
55
- "asma-types": "^2.14.0",
55
+ "asma-types": "^2.15.1",
56
56
  "history": "^5.3.0",
57
57
  "jsdom": "^27.0.0",
58
58
  "lefthook": "^2.1.1",
@@ -0,0 +1,348 @@
1
+ import assert from 'node:assert/strict'
2
+ import { after, afterEach, before, describe, it } from 'node:test'
3
+
4
+ import { JSDOM } from 'jsdom'
5
+
6
+ // The helper pulls in the shell bindings and `g-definitions`, and importing them loads the whole barrel, which
7
+ // reads `window` and `localStorage` at import time. A jsdom window is installed as the global first and the
8
+ // modules are imported dynamically afterwards, like `generateEnvConfigsBindings.test.ts` does. The real event
9
+ // bus and the real shared `history` are used, so the subscription tests exercise the actual wiring.
10
+ const dom = new JSDOM('', { url: 'https://dev.adopus.no/users?user_context=ME', pretendToBeVisual: true })
11
+ const GLOBAL_NAMES = ['window', 'document', 'localStorage', 'location'] as const
12
+
13
+ type Metadata = { user_id?: unknown; customer_id?: unknown }
14
+ type Shell = { auth_bindings?: { getMetadata: () => Metadata | undefined } }
15
+
16
+ const USER = '0b1c8f9e-1111-4111-8111-111111111111'
17
+ const OTHER_USER = '0b1c8f9e-2222-4222-8222-222222222222'
18
+ const TENANT = '7d3a5c10-3333-4333-8333-333333333333'
19
+ const OTHER_TENANT = '7d3a5c10-4444-4444-8444-444444444444'
20
+ const PILOT_ID = 'directory.my-participants'
21
+
22
+ let helper: typeof import('./tableSettingsKey.ts')
23
+ let authBindings: typeof import('./generateSrvAuthBindings.ts')
24
+ let definitions: typeof import('../g-definitions.ts')
25
+ let urlParams: typeof import('./urlParams.helpers.tsx')
26
+ let originalShell: Shell
27
+
28
+ const win = () => dom.window as unknown as { __ASMA__SHELL__?: Shell }
29
+
30
+ function setMetadata(metadata: Metadata | undefined) {
31
+ originalShell.auth_bindings = { getMetadata: () => metadata }
32
+ }
33
+
34
+ function signedIn(overrides: Metadata = {}) {
35
+ setMetadata({ user_id: USER, customer_id: TENANT, ...overrides })
36
+ }
37
+
38
+ /** Verbatim format of asma-app-directory `src/helpers/generateUniqKey.ts` at 677b3bca, with its three inputs
39
+ * (user id, tenant id and `getUserContextParam()`) passed in. */
40
+ const appDirectoryGenerateUniqKey = (key: string, userId: string, customerId: string, context: string) =>
41
+ `${key}_${userId}_${customerId}_${context}`
42
+
43
+ /** The snapshot function P3 gives `useSyncExternalStore`: it re-reads `user_context` itself on every call. */
44
+ function pilotSnapshot() {
45
+ const param: unknown = urlParams.getParamByName('user_context' as never)
46
+ return helper.getTableSettingsKey(PILOT_ID, { context: typeof param === 'string' ? param : '' })
47
+ }
48
+
49
+ function countCalls() {
50
+ const state = { calls: 0 }
51
+ const unsubscribe = helper.onTableSettingsKeyChange(() => {
52
+ state.calls += 1
53
+ })
54
+ return { state, unsubscribe }
55
+ }
56
+
57
+ before(async () => {
58
+ const globals = globalThis as Record<string, unknown>
59
+ for (const name of GLOBAL_NAMES) {
60
+ Object.defineProperty(globals, name, {
61
+ value: (dom.window as unknown as Record<string, unknown>)[name],
62
+ configurable: true,
63
+ writable: true,
64
+ })
65
+ }
66
+
67
+ helper = await import('./tableSettingsKey.ts')
68
+ authBindings = await import('./generateSrvAuthBindings.ts')
69
+ definitions = await import('../g-definitions.ts')
70
+ urlParams = await import('./urlParams.helpers.tsx')
71
+
72
+ originalShell = win().__ASMA__SHELL__ as Shell
73
+ })
74
+
75
+ afterEach(() => {
76
+ win().__ASMA__SHELL__ = originalShell
77
+ delete originalShell.auth_bindings
78
+ definitions.history.replace('/users?user_context=ME')
79
+ })
80
+
81
+ after(() => {
82
+ for (const name of GLOBAL_NAMES) {
83
+ delete (globalThis as Record<string, unknown>)[name]
84
+ }
85
+ })
86
+
87
+ describe('getTableSettingsKey', () => {
88
+ it('U-G01: both ids known → ${tableId}_${userId}_${customerId}_${context}', () => {
89
+ signedIn()
90
+
91
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), `${PILOT_ID}_${USER}_${TENANT}_ME`)
92
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'RECIPIENT' }), `${PILOT_ID}_${USER}_${TENANT}_RECIPIENT`)
93
+ assert.equal(helper.getTableSettingsKey(PILOT_ID), `${PILOT_ID}_${USER}_${TENANT}_`)
94
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, {}), `${PILOT_ID}_${USER}_${TENANT}_`)
95
+ })
96
+
97
+ it('U-G02: user id missing or empty → undefined', () => {
98
+ signedIn({ user_id: undefined })
99
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
100
+
101
+ signedIn({ user_id: '' })
102
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
103
+
104
+ signedIn({ user_id: null })
105
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
106
+
107
+ setMetadata({ customer_id: TENANT })
108
+ assert.equal(helper.getTableSettingsKey(PILOT_ID), undefined)
109
+ })
110
+
111
+ it('U-G03: tenant missing or empty → undefined', () => {
112
+ signedIn({ customer_id: undefined })
113
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
114
+
115
+ signedIn({ customer_id: '' })
116
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
117
+
118
+ signedIn({ customer_id: null })
119
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
120
+
121
+ setMetadata({ user_id: USER })
122
+ assert.equal(helper.getTableSettingsKey(PILOT_ID), undefined)
123
+ })
124
+
125
+ it('U-G04: no auth bindings on the window → undefined, no throw', () => {
126
+ // The shell object exists but has no bindings yet.
127
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
128
+
129
+ // The bindings exist, but the srvAuth response has not carried metadata yet.
130
+ setMetadata(undefined)
131
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
132
+
133
+ // No shell object at all.
134
+ win().__ASMA__SHELL__ = undefined
135
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
136
+
137
+ // A binding that throws, and a binding without `getMetadata`.
138
+ win().__ASMA__SHELL__ = {
139
+ auth_bindings: {
140
+ getMetadata: () => {
141
+ throw new Error('bindings are not ready')
142
+ },
143
+ },
144
+ }
145
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
146
+
147
+ win().__ASMA__SHELL__ = { auth_bindings: {} as never }
148
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME' }), undefined)
149
+ })
150
+
151
+ it("U-G05: context outside [A-Za-z0-9-]{0,32} → ''", () => {
152
+ signedIn()
153
+ const emptyContextKey = `${PILOT_ID}_${USER}_${TENANT}_`
154
+ const rejected: unknown[] = [
155
+ 'free text',
156
+ 'ME,RECIPIENT',
157
+ 'ME_RECIPIENT',
158
+ 'user_context=ME',
159
+ '?user_context=ME&lang=no',
160
+ // Path-like and separator-like characters stay out of a key: no `.`, `:`, `/` or `\`.
161
+ 'ME.RECIPIENT',
162
+ 'ME:X',
163
+ 'a/b',
164
+ '.',
165
+ ':',
166
+ '/',
167
+ '..',
168
+ 'ME\\X',
169
+ 'ME\n',
170
+ 'ÆØÅ',
171
+ 'x'.repeat(33),
172
+ ['ME'],
173
+ ['ME', 'RECIPIENT'],
174
+ 42,
175
+ null,
176
+ undefined,
177
+ '',
178
+ ]
179
+
180
+ for (const context of rejected) {
181
+ assert.equal(
182
+ helper.getTableSettingsKey(PILOT_ID, { context: context as string }),
183
+ emptyContextKey,
184
+ `context ${JSON.stringify(context)} must become ''`,
185
+ )
186
+ }
187
+
188
+ assert.equal(helper.getTableSettingsKey(PILOT_ID, { context: 'ME-2' }), `${PILOT_ID}_${USER}_${TENANT}_ME-2`)
189
+ assert.equal(
190
+ helper.getTableSettingsKey(PILOT_ID, { context: 'x'.repeat(32) }),
191
+ `${PILOT_ID}_${USER}_${TENANT}_${'x'.repeat(32)}`,
192
+ )
193
+ })
194
+
195
+ it('U-G06: table ids with spaces, ":", "/", non-ASCII or over 100 characters → undefined', () => {
196
+ signedIn()
197
+ const rejected: unknown[] = [
198
+ 'my table',
199
+ 'a:b',
200
+ 'a/b',
201
+ 'Tabell æøå',
202
+ 'Столбец',
203
+ 'a'.repeat(101),
204
+ '',
205
+ '.hidden',
206
+ '-dash',
207
+ '_underscore',
208
+ 'a\n',
209
+ null,
210
+ 42,
211
+ ]
212
+
213
+ for (const tableId of rejected) {
214
+ assert.equal(
215
+ helper.getTableSettingsKey(tableId as string, { context: 'ME' }),
216
+ undefined,
217
+ `table id ${JSON.stringify(tableId)} must be rejected`,
218
+ )
219
+ }
220
+
221
+ assert.equal(helper.getTableSettingsKey('a'.repeat(100)), `${'a'.repeat(100)}_${USER}_${TENANT}_`)
222
+ })
223
+
224
+ it('U-G07: directory.my-participants and legacy UsersTable are accepted', () => {
225
+ signedIn()
226
+
227
+ assert.equal(helper.getTableSettingsKey('directory.my-participants'), `directory.my-participants_${USER}_${TENANT}_`)
228
+ assert.equal(helper.getTableSettingsKey('UsersTable'), `UsersTable_${USER}_${TENANT}_`)
229
+ assert.equal(helper.getTableSettingsKey('mvLogsTableKey'), `mvLogsTableKey_${USER}_${TENANT}_`)
230
+ })
231
+
232
+ it('U-G08: output equals asma-app-directory generateUniqKey for the same metadata and context', () => {
233
+ signedIn()
234
+
235
+ for (const context of ['ME', 'RECIPIENT', '']) {
236
+ for (const tableId of [PILOT_ID, 'UsersTable']) {
237
+ assert.equal(
238
+ helper.getTableSettingsKey(tableId, { context }),
239
+ appDirectoryGenerateUniqKey(tableId, USER, TENANT, context),
240
+ )
241
+ }
242
+ }
243
+ })
244
+
245
+ it('U-G09: two table ids give different keys for the same user (AC 6)', () => {
246
+ signedIn()
247
+
248
+ const first = helper.getTableSettingsKey('directory.my-participants', { context: 'ME' })
249
+ const second = helper.getTableSettingsKey('directory.all-participants', { context: 'ME' })
250
+
251
+ assert.ok(first && second)
252
+ assert.notEqual(first, second)
253
+ })
254
+
255
+ it('U-G10: two users or two tenants give different keys for the same table (AC 5)', () => {
256
+ signedIn()
257
+ const base = helper.getTableSettingsKey(PILOT_ID, { context: 'ME' })
258
+
259
+ signedIn({ user_id: OTHER_USER })
260
+ const otherUser = helper.getTableSettingsKey(PILOT_ID, { context: 'ME' })
261
+
262
+ signedIn({ customer_id: OTHER_TENANT })
263
+ const otherTenant = helper.getTableSettingsKey(PILOT_ID, { context: 'ME' })
264
+
265
+ assert.ok(base && otherUser && otherTenant)
266
+ assert.equal(new Set([base, otherUser, otherTenant]).size, 3)
267
+ })
268
+ })
269
+
270
+ describe('onTableSettingsKeyChange', () => {
271
+ it('U-G11: calls the listener on jwt_changed and logout_event, and not on subscribe', () => {
272
+ const { state, unsubscribe } = countCalls()
273
+
274
+ try {
275
+ assert.equal(state.calls, 0)
276
+
277
+ authBindings.dispatchSrvAuthEvents('jwt_changed', undefined, false)
278
+ assert.equal(state.calls, 1)
279
+
280
+ authBindings.dispatchSrvAuthEvents('logout_event', {}, false)
281
+ assert.equal(state.calls, 2)
282
+ } finally {
283
+ unsubscribe()
284
+ }
285
+ })
286
+
287
+ it('U-G12: the unsubscribe function stops further calls from all three sources', () => {
288
+ const stays = countCalls()
289
+ const leaves = countCalls()
290
+
291
+ try {
292
+ authBindings.dispatchSrvAuthEvents('jwt_changed', undefined, false)
293
+ authBindings.dispatchSrvAuthEvents('logout_event', {}, false)
294
+ definitions.history.push('/users?user_context=RECIPIENT')
295
+ assert.equal(leaves.state.calls, 3, 'each of the three sources reaches a live listener')
296
+
297
+ leaves.unsubscribe()
298
+
299
+ authBindings.dispatchSrvAuthEvents('jwt_changed', undefined, false)
300
+ authBindings.dispatchSrvAuthEvents('logout_event', {}, false)
301
+ definitions.history.push('/users?user_context=ME')
302
+ assert.equal(leaves.state.calls, 3, 'no call after unsubscribe')
303
+ assert.equal(stays.state.calls, 6, 'another subscriber is unaffected')
304
+ } finally {
305
+ leaves.unsubscribe()
306
+ stays.unsubscribe()
307
+ }
308
+ })
309
+
310
+ it('U-G13: a context-only change fires the listener with no jwt or logout event (R1-01)', () => {
311
+ signedIn()
312
+ definitions.history.replace('/users?user_context=ME')
313
+ const { state, unsubscribe } = countCalls()
314
+
315
+ try {
316
+ assert.equal(pilotSnapshot(), `${PILOT_ID}_${USER}_${TENANT}_ME`)
317
+
318
+ definitions.history.push('/users?user_context=RECIPIENT')
319
+
320
+ assert.equal(state.calls, 1)
321
+ assert.equal(pilotSnapshot(), `${PILOT_ID}_${USER}_${TENANT}_RECIPIENT`)
322
+ // The helper itself never reads the URL: without the `context` argument the segment stays empty.
323
+ assert.equal(helper.getTableSettingsKey(PILOT_ID), `${PILOT_ID}_${USER}_${TENANT}_`)
324
+ } finally {
325
+ unsubscribe()
326
+ }
327
+ })
328
+
329
+ it('U-G14: a history change that leaves user_context alone fires the listener but not the key (R2-02)', () => {
330
+ signedIn()
331
+ definitions.history.replace('/users?user_context=ME')
332
+ const { state, unsubscribe } = countCalls()
333
+
334
+ try {
335
+ const before = pilotSnapshot()
336
+
337
+ definitions.history.push('/users?user_context=ME&lang=no')
338
+
339
+ const after = pilotSnapshot()
340
+ assert.equal(state.calls, 1)
341
+ assert.equal(before, `${PILOT_ID}_${USER}_${TENANT}_ME`)
342
+ assert.equal(after, `${PILOT_ID}_${USER}_${TENANT}_ME`)
343
+ assert.ok(Object.is(before, after), 'useSyncExternalStore sees no key change')
344
+ } finally {
345
+ unsubscribe()
346
+ }
347
+ })
348
+ })
@@ -0,0 +1,95 @@
1
+ import { subscribeToHistory } from '../g-definitions.js'
2
+ import { registerCallbackOnSrvAuthEvents } from './generateSrvAuthBindings.js'
3
+ import { realWindow } from './getSubdomain.js'
4
+
5
+ export interface TableSettingsKeyOptions {
6
+ /**
7
+ * A short, stable name for a view of the same table, for example `ME` or `RECIPIENT`. It is kept only if
8
+ * it matches [A-Za-z0-9-]{0,32}; anything else becomes ''.
9
+ *
10
+ * It must be an opaque name chosen by the app, never a patient, questionnaire, answer or record id, and
11
+ * never free text (AC 12 of ASMA-8597: keys hold no record data). The pattern checks the shape only: a
12
+ * numeric string or another short id of up to 32 characters passes, because the helper cannot tell it from
13
+ * a name; a non-string number and a 36-character UUID do not.
14
+ */
15
+ context?: string
16
+ }
17
+
18
+ /**
19
+ * `<app>.<table>` for new ids; legacy ids such as `UsersTable` pass too. Rejects spaces, `:`, `/` and non-ASCII.
20
+ * It checks the shape only, so a UUID-shaped id passes; see the `tableId` rule on `getTableSettingsKey`.
21
+ */
22
+ const TABLE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/
23
+ const CONTEXT_PATTERN = /^[A-Za-z0-9-]{0,32}$/
24
+
25
+ function readUserAndCustomerId(): { userId: string; customerId: string } | undefined {
26
+ try {
27
+ const metadata = realWindow.__ASMA__SHELL__?.auth_bindings?.getMetadata()
28
+ // The shell fills these from a server response, so check them at runtime, whatever the types promise.
29
+ const userId: unknown = metadata?.user_id
30
+ const customerId: unknown = metadata?.customer_id
31
+
32
+ if (typeof userId !== 'string' || userId === '' || typeof customerId !== 'string' || customerId === '') {
33
+ return undefined
34
+ }
35
+
36
+ return { userId, customerId }
37
+ } catch {
38
+ return undefined
39
+ }
40
+ }
41
+
42
+ function sanitizeContext(context: unknown): string {
43
+ return typeof context === 'string' && CONTEXT_PATTERN.test(context) ? context : ''
44
+ }
45
+
46
+ /**
47
+ * Storage key for a table's saved settings: `${tableId}_${userId}_${customerId}_${context}`, the format
48
+ * asma-app-directory's `generateUniqKey` already uses. Returns `undefined` until both the signed-in user
49
+ * and the tenant are known, or when `tableId` is not a valid id, so a table shows its defaults and saves
50
+ * nothing instead of writing a `…_undefined_…` key.
51
+ *
52
+ * Naming rule for new table ids: `<app>.<table>` in lowercase kebab-case, for example
53
+ * `directory.my-participants`. Name the table, never a header label, a position or a record id.
54
+ *
55
+ * @param tableId A stable, opaque name for the table. It must never be a patient, questionnaire, answer or
56
+ * record id, or anything built from one (AC 12 of ASMA-8597: keys hold no record data). The helper does not
57
+ * guard against this: a UUID-shaped id passes. Keeping such ids out of keys is the job of the key inventory
58
+ * in ASMA-8698 (AC 3) and of each app's own migration to this helper.
59
+ * @param options `context` is the same kind of name, see {@link TableSettingsKeyOptions}.
60
+ *
61
+ * The helper never reads the URL: pass the app's current context (for example its `user_context` value)
62
+ * as `options.context`. A key contains only the table id, the opaque user and tenant ids and the sanitized
63
+ * context, never names or record data.
64
+ */
65
+ export function getTableSettingsKey(tableId: string, options?: TableSettingsKeyOptions): string | undefined {
66
+ if (typeof tableId !== 'string' || !TABLE_ID_PATTERN.test(tableId)) {
67
+ return undefined
68
+ }
69
+
70
+ const ids = readUserAndCustomerId()
71
+
72
+ if (!ids) {
73
+ return undefined
74
+ }
75
+
76
+ return `${tableId}_${ids.userId}_${ids.customerId}_${sanitizeContext(options?.context)}`
77
+ }
78
+
79
+ /**
80
+ * Calls `listener` after `jwt_changed`, `logout_event` and every history change, and returns the function
81
+ * that unsubscribes from all three. History is included because an app's context usually comes from the
82
+ * URL. The listener only signals; read the key again with `getTableSettingsKey`. Made for
83
+ * `useSyncExternalStore(onTableSettingsKeyChange, () => getTableSettingsKey(id, { context }))`.
84
+ */
85
+ export function onTableSettingsKeyChange(listener: () => void): () => void {
86
+ const jwtChanged = registerCallbackOnSrvAuthEvents('jwt_changed', () => listener())
87
+ const loggedOut = registerCallbackOnSrvAuthEvents('logout_event', () => listener())
88
+ const unsubscribeHistory = subscribeToHistory(() => listener())
89
+
90
+ return () => {
91
+ jwtChanged.unregister()
92
+ loggedOut.unregister()
93
+ unsubscribeHistory()
94
+ }
95
+ }
package/src/index.ts CHANGED
@@ -28,6 +28,7 @@ export * from './helpers/initASMAAppVitals.js'
28
28
  export * from './helpers/registerOpenReplay.js'
29
29
  export * from './helpers/urlParams.helpers.js'
30
30
  export * from './helpers/sectionPath.helpers.js'
31
+ export * from './helpers/tableSettingsKey.js'
31
32
  export * from './helpers/openReplayObject.js'
32
33
  //export * from './helpers/openReplayConfigs.js'
33
34
  export * from './helpers/sha256.js'