@xh/hoist 88.0.0 → 88.1.1

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.
Files changed (29) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/appcontainer/AppStateModel.ts +8 -7
  3. package/build/types/appcontainer/AppStateModel.d.ts +0 -4
  4. package/build/types/cmp/store/StoreFilterField.d.ts +11 -9
  5. package/build/types/cmp/store/impl/StoreFilterFieldImplModel.d.ts +10 -2
  6. package/build/types/cmp/zoneGrid/ZoneGridModel.d.ts +6 -1
  7. package/build/types/desktop/cmp/grid/find/GridFindField.d.ts +11 -7
  8. package/build/types/desktop/cmp/grid/find/impl/GridFindFieldImplModel.d.ts +5 -1
  9. package/build/types/security/BaseOAuthClient.d.ts +10 -3
  10. package/build/types/security/Types.d.ts +5 -0
  11. package/build/types/security/msal/MsalClient.d.ts +2 -3
  12. package/cmp/store/StoreFilterField.ts +11 -9
  13. package/cmp/store/impl/StoreFilterFieldImplModel.ts +56 -27
  14. package/cmp/zoneGrid/ZoneGridModel.ts +22 -1
  15. package/desktop/cmp/dash/container/DashContainerModel.ts +12 -10
  16. package/desktop/cmp/form/FormField.ts +25 -8
  17. package/desktop/cmp/grid/find/GridFindField.ts +12 -8
  18. package/desktop/cmp/grid/find/impl/GridFindFieldImplModel.ts +59 -35
  19. package/docs/codemod/v88/codemod-add-accessor.mjs +1 -1
  20. package/docs/codemod/v88/codemod-mobx7-rename.mjs +3 -3
  21. package/docs/codemod/v88/codemod-remove-makeObservable.mjs +1 -1
  22. package/docs/upgrade-notes/v88-upgrade-notes.md +23 -4
  23. package/package.json +1 -1
  24. package/public/preflight.js +3 -1
  25. package/security/BaseOAuthClient.ts +17 -3
  26. package/security/README.md +4 -0
  27. package/security/Types.ts +6 -0
  28. package/security/authzero/AuthZeroClient.ts +11 -5
  29. package/security/msal/MsalClient.ts +8 -6
@@ -34,7 +34,17 @@ import {
34
34
  useOnUnmount
35
35
  } from '@xh/hoist/utils/react';
36
36
  import classNames from 'classnames';
37
- import {first, isBoolean, isDate, isEmpty, isFinite, isNil, isUndefined, kebabCase} from 'lodash';
37
+ import {
38
+ first,
39
+ isDate,
40
+ isEmpty,
41
+ isFinite,
42
+ isNil,
43
+ isObjectLike,
44
+ isString,
45
+ isUndefined,
46
+ kebabCase
47
+ } from 'lodash';
38
48
  import {
39
49
  Children,
40
50
  cloneElement,
@@ -380,17 +390,24 @@ const editableChild = hoistCmp.factory<FieldModel>({
380
390
  // Helper Functions
381
391
  //---------------------------------
382
392
  export function defaultReadonlyRenderer(value: any): ReactNode {
393
+ // First try type-specific formatting
383
394
  if (isLocalDate(value)) return fmtDate(value);
384
395
  if (isDate(value)) return fmtDateTime(value);
385
396
  if (isFinite(value)) return fmtNumber(value);
386
- if (isBoolean(value)) return value.toString();
387
-
388
- // format JSON, but fail and ignore on plain text
389
- try {
390
- value = fmtJson(value);
391
- } catch (e) {}
397
+ if (isObjectLike(value)) return fmtJson(value);
398
+
399
+ // ... pretty printing json strings as well.
400
+ if (isString(value)) {
401
+ const trimmed = value.trim();
402
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
403
+ try {
404
+ value = fmtJson(trimmed);
405
+ } catch {}
406
+ }
407
+ }
392
408
 
393
- return span(value != null ? value.toString() : null);
409
+ // Otherwise just fall back to string rendering
410
+ return span(value?.toString());
394
411
  }
395
412
 
396
413
  const blockChildren = ['CodeInput', 'JsonInput', 'Select', 'TextInput'];
@@ -5,6 +5,7 @@
5
5
  * Copyright © 2026 Extremely Heavy Industries Inc.
6
6
  */
7
7
  import type {GridModel} from '@xh/hoist/cmp/grid';
8
+ import type {ZoneGridModel} from '@xh/hoist/cmp/zoneGrid';
8
9
  import {hbox, span, vbox} from '@xh/hoist/cmp/layout';
9
10
  import {hoistCmp, LayoutProps, useLocalModel} from '@xh/hoist/core';
10
11
  import type {FilterMatchMode} from '@xh/hoist/data';
@@ -19,10 +20,12 @@ import {GridFindFieldImplModel} from './impl/GridFindFieldImplModel';
19
20
 
20
21
  export interface GridFindFieldProps extends TextInputProps, LayoutProps {
21
22
  /**
22
- * GridModel whose data this control should search. This component will, by default, use the
23
- * fields for all *visible* columns when matching, as well as any groupBy field.
23
+ * GridModel or ZoneGridModel whose data this control should search. When given a GridModel,
24
+ * this component will, by default, use the fields for all *visible* columns when matching, as
25
+ * well as any groupBy field. When given a ZoneGridModel, it uses the fields currently mapped
26
+ * to any of its zones.
24
27
  */
25
- gridModel?: GridModel;
28
+ gridModel?: GridModel | ZoneGridModel;
26
29
 
27
30
  /** Mode to use when searching (default 'startWord'). */
28
31
  matchMode?: FilterMatchMode;
@@ -47,10 +50,11 @@ export interface GridFindFieldProps extends TextInputProps, LayoutProps {
47
50
  * the entered search term based on simple word-boundary matching of its value to the value of
48
51
  * configured fields on a record. If any field values match, the record itself is considered a match.
49
52
  *
50
- * This component is designed to be bound to a GridModel via `gridModel` prop. (If not configured to
51
- * bind to a specific GridModel, this component will bind by default to the nearest GridModel found
52
- * in context.) Binding in this way allows the component to auto-generate the fields in the store to
53
- * be searched by the field and to automatically select the results in the Grid.
53
+ * This component is designed to be bound to a GridModel or ZoneGridModel via its `gridModel` prop.
54
+ * If not configured, it binds by default to the nearest GridModel or ZoneGridModel found in
55
+ * context. Binding in this way allows the component to
56
+ * auto-generate the fields in the store to be searched by the field and to automatically select
57
+ * the results in the Grid.
54
58
  *
55
59
  * Fields to be searched can be automatically determined from the bound Grid's Store, and/or
56
60
  * customized via the include/excludeFields props. See prop comments for details.
@@ -66,7 +70,7 @@ export const [GridFindField, gridFindField] = hoistCmp.withFactory<GridFindField
66
70
  const impl = useLocalModel(GridFindFieldImplModel);
67
71
 
68
72
  return hbox({
69
- width: 180,
73
+ width: 240,
70
74
  className,
71
75
  ...layoutProps,
72
76
  items: [
@@ -4,13 +4,14 @@
4
4
  *
5
5
  * Copyright © 2026 Extremely Heavy Industries Inc.
6
6
  */
7
- import {GridModel} from '@xh/hoist/cmp/grid';
7
+ import {Column, GridModel} from '@xh/hoist/cmp/grid';
8
+ import {ZoneGridModel} from '@xh/hoist/cmp/zoneGrid';
8
9
  import {HoistModel} from '@xh/hoist/core';
9
10
  import type {FilterMatchMode, StoreRecord} from '@xh/hoist/data';
10
11
  import {getFilterRegex} from '@xh/hoist/data';
11
12
  import {TextInputModel} from '@xh/hoist/desktop/cmp/input';
12
13
  import {action, bindable, computed, observableRef, compareStructural} from '@xh/hoist/mobx';
13
- import {stripTags, withDefault} from '@xh/hoist/utils/js';
14
+ import {stripTags} from '@xh/hoist/utils/js';
14
15
  import {createObservableRef} from '@xh/hoist/utils/react';
15
16
  import {
16
17
  filter,
@@ -58,7 +59,7 @@ export class GridFindFieldImplModel extends HoistModel {
58
59
 
59
60
  get selectedIdx(): number {
60
61
  if (!this.count) return null;
61
- const matchIdx = this.results.indexOf(this.gridModel.selectedId);
62
+ const matchIdx = this.results.indexOf(this.innerGridModel.selectedId);
62
63
  return matchIdx > -1 ? matchIdx : null;
63
64
  }
64
65
 
@@ -83,21 +84,26 @@ export class GridFindFieldImplModel extends HoistModel {
83
84
  return !isNil(this.results) && !isEmpty(this.results);
84
85
  }
85
86
 
87
+ /** GridModel or ZoneGridModel to search - from props, or the nearest found in context. */
86
88
  @computed
87
- get gridModel(): GridModel {
88
- const ret = withDefault(this.componentProps.gridModel, this.lookupModel(GridModel));
89
- if (!ret) {
90
- this.logError("No GridModel available. Provide via a 'gridModel' prop, or context.");
91
- } else if (!ret.selModel?.isEnabled) {
92
- this.logError('GridFindField must be bound to GridModel with selection enabled.');
93
- }
94
- return ret;
89
+ get boundModel(): GridModel | ZoneGridModel {
90
+ return (
91
+ this.componentProps.gridModel ??
92
+ this.lookupModel(it => it instanceof GridModel || it instanceof ZoneGridModel)
93
+ );
95
94
  }
96
95
 
97
96
  //------------------------------------------------------------------
98
97
  // Trampoline value to grid
99
98
  //------------------------------------------------------------------
100
99
  override onLinked() {
100
+ const {boundModel} = this;
101
+ if (!boundModel) {
102
+ this.logError("No GridModel available. Provide via a 'gridModel' prop, or context.");
103
+ } else if (!boundModel.selModel?.isEnabled) {
104
+ this.logError('GridFindField must be bound to GridModel with selection enabled.');
105
+ }
106
+
101
107
  this.addReaction(
102
108
  {
103
109
  track: () => this.query,
@@ -105,16 +111,20 @@ export class GridFindFieldImplModel extends HoistModel {
105
111
  debounce: this.queryBuffer
106
112
  },
107
113
  {
108
- track: () => [
109
- this.gridModel?.store.records,
110
- this.gridModel?.columns,
111
- this.gridModel?.sortBy,
112
- this.gridModel?.groupBy
113
- ],
114
+ track: () => {
115
+ const {innerGridModel} = this;
116
+ return [
117
+ innerGridModel?.store.records,
118
+ innerGridModel?.sortBy,
119
+ innerGridModel?.groupBy,
120
+ ...this.getSearchColumns()
121
+ ];
122
+ },
114
123
  run: () => {
115
124
  this._records = null;
116
125
  if (this.hasQuery) this.updateResults();
117
126
  },
127
+ equals: 'shallow',
118
128
  debounce: this.queryBuffer
119
129
  },
120
130
  {
@@ -126,28 +136,28 @@ export class GridFindFieldImplModel extends HoistModel {
126
136
  }
127
137
 
128
138
  selectPrev() {
129
- const {hasResults, results, selectedIdx, gridModel} = this;
139
+ const {hasResults, results, selectedIdx, innerGridModel} = this;
130
140
  if (!hasResults) return;
131
141
  const endIdx = results.length - 1;
132
142
  if (!isFinite(selectedIdx)) {
133
- gridModel.selectAsync(results[endIdx]);
143
+ innerGridModel.selectAsync(results[endIdx]);
134
144
  return;
135
145
  }
136
146
 
137
147
  const idx = (selectedIdx - 1) % results.length;
138
- gridModel.selectAsync(results[idx < 0 ? endIdx : idx]);
148
+ innerGridModel.selectAsync(results[idx < 0 ? endIdx : idx]);
139
149
  }
140
150
 
141
151
  selectNext() {
142
- const {hasResults, results, selectedIdx, gridModel} = this;
152
+ const {hasResults, results, selectedIdx, innerGridModel} = this;
143
153
  if (!hasResults) return;
144
154
  if (!isFinite(selectedIdx)) {
145
- gridModel.selectAsync(results[0]);
155
+ innerGridModel.selectAsync(results[0]);
146
156
  return;
147
157
  }
148
158
 
149
159
  const idx = (selectedIdx + 1) % results.length;
150
- gridModel.selectAsync(results[idx]);
160
+ innerGridModel.selectAsync(results[idx]);
151
161
  }
152
162
 
153
163
  //------------------------
@@ -156,7 +166,7 @@ export class GridFindFieldImplModel extends HoistModel {
156
166
  @action
157
167
  private updateResults(autoSelect = false) {
158
168
  // Track ids of matching records
159
- const {query, gridModel} = this,
169
+ const {query, innerGridModel} = this,
160
170
  activeFields = this.getActiveFields();
161
171
 
162
172
  if (!query || isEmpty(activeFields)) {
@@ -175,19 +185,19 @@ export class GridFindFieldImplModel extends HoistModel {
175
185
 
176
186
  // Auto-select first matching result
177
187
  if (autoSelect && this.hasResults && !isFinite(this.selectedIdx)) {
178
- gridModel?.selectAsync(this.results[0]);
188
+ innerGridModel?.selectAsync(this.results[0]);
179
189
  }
180
190
  }
181
191
 
182
192
  private getRecords(): StoreRecord[] {
183
- return (this._records ??= this.gridModel.getSortedRecords());
193
+ return (this._records ??= this.innerGridModel.getSortedRecords());
184
194
  }
185
195
 
186
196
  private getActiveFields(): string[] {
187
- const {gridModel, includeFields, excludeFields} = this,
188
- visibleCols = gridModel.getVisibleLeafColumns();
197
+ const {innerGridModel, includeFields, excludeFields} = this,
198
+ searchCols = this.getSearchColumns();
189
199
 
190
- let ret = ['id', ...gridModel.store.fieldNames];
200
+ let ret = ['id', ...innerGridModel.store.fieldNames];
191
201
  if (includeFields) ret = intersection(ret, includeFields);
192
202
  if (excludeFields) ret = without(ret, ...excludeFields);
193
203
 
@@ -196,7 +206,7 @@ export class GridFindFieldImplModel extends HoistModel {
196
206
  // as first-class fields and displays them w/o the need for renderers, we want to
197
207
  // include them here. (But only if their "root" is in the field list derived from the
198
208
  // Store and any given include/excludeField configs.)
199
- visibleCols.forEach(col => {
209
+ searchCols.forEach(col => {
200
210
  const {fieldPath} = col;
201
211
  if (!isArray(fieldPath)) return;
202
212
 
@@ -213,7 +223,7 @@ export class GridFindFieldImplModel extends HoistModel {
213
223
  // keyed to groupBy, so query results stay stable across regrouping (see #4070).
214
224
  ret = ret.filter(f => {
215
225
  return (
216
- (includeFields && includeFields.includes(f)) || visibleCols.find(c => c.field === f)
226
+ (includeFields && includeFields.includes(f)) || searchCols.find(c => c.field === f)
217
227
  );
218
228
  });
219
229
 
@@ -221,13 +231,13 @@ export class GridFindFieldImplModel extends HoistModel {
221
231
  }
222
232
 
223
233
  private getValGetters(fieldName: string) {
224
- const {gridModel} = this,
225
- {store} = gridModel,
234
+ const {innerGridModel} = this,
235
+ {store} = innerGridModel,
226
236
  field = store.getField(fieldName);
227
237
 
228
238
  // See corresponding method in StoreFilterFieldImplModel for notes on this implementation.
229
239
  if (field?.type === 'date' || field?.type === 'localDate') {
230
- const cols = filter(gridModel.getVisibleLeafColumns(), {field: fieldName});
240
+ const cols = filter(this.getSearchColumns(), {field: fieldName});
231
241
  if (!cols) return [];
232
242
 
233
243
  return cols.map(column => {
@@ -237,7 +247,7 @@ export class GridFindFieldImplModel extends HoistModel {
237
247
  record,
238
248
  field: fieldName,
239
249
  column,
240
- gridModel,
250
+ gridModel: innerGridModel,
241
251
  store,
242
252
  agParams: null
243
253
  },
@@ -254,4 +264,18 @@ export class GridFindFieldImplModel extends HoistModel {
254
264
  ? (rec: StoreRecord) => get(rec.data, fieldName)
255
265
  : (rec: StoreRecord) => rec.data[fieldName];
256
266
  }
267
+
268
+ private get innerGridModel(): GridModel {
269
+ const {boundModel} = this;
270
+ return boundModel instanceof ZoneGridModel ? boundModel.gridModel : boundModel;
271
+ }
272
+
273
+ // See corresponding method in StoreFilterFieldImplModel.
274
+ private getSearchColumns(): Column[] {
275
+ const {boundModel} = this;
276
+ if (!boundModel) return [];
277
+ return boundModel instanceof ZoneGridModel
278
+ ? boundModel.getMappedColumns()
279
+ : boundModel.getVisibleLeafColumns();
280
+ }
257
281
  }
@@ -139,6 +139,6 @@ async function processFile(filePath) {
139
139
  formACount += localFormA;
140
140
  formBCount += localFormB;
141
141
  if (!DRY) await fs.writeFile(filePath, content);
142
- console.log(` ${path.relative(REPO_ROOT, filePath)} — form A=${localFormA}, form B=${localFormB}`);
142
+ console.log(` ${path.relative(process.cwd(), filePath)} — form A=${localFormA}, form B=${localFormB}`);
143
143
  }
144
144
  }
@@ -127,13 +127,13 @@ async function processFile(filePath) {
127
127
  `import {${names.join(', ')}} from '${m[2]}';` +
128
128
  content.slice(m.index + m[0].length);
129
129
  } else if (Object.values(RENAMES).some(to => new RegExp(`\\b${to}\\b`).test(content))) {
130
- console.log(` WARN no mobx import found to update: ${path.relative(REPO_ROOT, filePath)}`);
130
+ console.log(` WARN no mobx import found to update: ${path.relative(process.cwd(), filePath)}`);
131
131
  }
132
132
 
133
133
  filesChanged++;
134
134
  renameCount += localCount;
135
135
  if (!DRY) await fs.writeFile(filePath, content);
136
- console.log(` ${path.relative(REPO_ROOT, filePath)} — ${localCount} renamed`);
136
+ console.log(` ${path.relative(process.cwd(), filePath)} — ${localCount} renamed`);
137
137
  }
138
138
 
139
139
  /** Move names imported from 'mobx' onto '@xh/hoist/mobx', merging into an existing Hoist import. */
@@ -157,7 +157,7 @@ function redirectMobxImport(content, filePath) {
157
157
  if (kept.length) {
158
158
  console.log(
159
159
  ` WARN not re-exported by @xh/hoist/mobx, left on 'mobx': ${kept.join(', ')} ` +
160
- `(${path.relative(REPO_ROOT, filePath)})`
160
+ `(${path.relative(process.cwd(), filePath)})`
161
161
  );
162
162
  }
163
163
  if (!moved.length) {
@@ -128,7 +128,7 @@ async function processFile(filePath) {
128
128
  importsTrimmed += trimmedImports;
129
129
  if (!DRY) await fs.writeFile(filePath, modified);
130
130
  console.log(
131
- ` ${path.relative(REPO_ROOT, filePath)} — calls=${removedCalls}, ctors=${removedConstructors}, imports=${trimmedImports}`
131
+ ` ${path.relative(process.cwd(), filePath)} — calls=${removedCalls}, ctors=${removedConstructors}, imports=${trimmedImports}`
132
132
  );
133
133
  }
134
134
  }
@@ -214,6 +214,11 @@ in-place upgrade can leave older copies of packages that Hoist now requires at a
214
214
  `@codemirror/state` and `@codemirror/view` in particular - and `tsc` then fails inside Hoist's
215
215
  `CodeInput` with conflicting types.
216
216
 
217
+ If an AI agent runs the upgrade with the hoist-react MCP server, restart the server now. In Claude
218
+ Code, reconnect with `/mcp` or restart the session. The server reads the installed `@xh/hoist`
219
+ version only when it starts, so until then it answers with v87 docs and types. The `hoist-docs`
220
+ and `hoist-ts` CLI tools read the installed version on each call and need no restart.
221
+
217
222
  See the [dev-utils migration guide](https://github.com/xh/hoist-dev-utils/blob/develop/README.md#migrating-from-v15-webpack)
218
223
  for the full option reference, and Toolbox's
219
224
  [`rsbuild.config.mjs`](https://github.com/xh/toolbox/blob/develop/client-app/rsbuild.config.mjs)
@@ -321,19 +326,33 @@ codemods do not reorder decorators, and a reversed pair fails silently: `Persist
321
326
  logs an error to the console and the field simply stops persisting, with no type error.
322
327
 
323
328
  ```bash
324
- grep -rn "@persist @bindable\|@persist @observable\|@persist$" client-app/src/
329
+ # Reversed on one line: `@persist @bindable ...`, `@persist.with({...}) @observable ...`
330
+ grep -rnE '@persist(\.with\(.*\))?\s+@(bindable|observable)' client-app/src/
331
+
332
+ # Reversed across lines: prints the MobX decorator line under a leading `@persist`
333
+ grep -rnE -A1 '^\s*@persist(\.with\(.*\))?\s*(//.*)?$' client-app/src/ | grep -E '^\S+-[0-9]+-\s*@(bindable|observable)'
325
334
  ```
326
335
 
336
+ The stacked form, with `@persist.with({...})` on its own line above `@bindable`, is easy to miss
337
+ in review. The second command finds it.
338
+
327
339
  Before:
328
340
 
329
341
  ```typescript
330
342
  @persist @bindable accessor showInactive = false;
343
+
344
+ @persist.with({path: 'gridState'})
345
+ @bindable accessor gridState = null;
331
346
  ```
332
347
 
333
348
  After:
334
349
 
335
350
  ```typescript
336
351
  @bindable @persist accessor showInactive = false;
352
+
353
+ @bindable
354
+ @persist.with({path: 'gridState'})
355
+ accessor gridState = null;
337
356
  ```
338
357
 
339
358
  **Audit enumeration of model instances.** `accessor` fields are prototype getter/setters, not own
@@ -457,7 +476,7 @@ All of these were deprecated in v86 or earlier. Search for each and replace as s
457
476
 
458
477
  ```bash
459
478
  grep -rn "withSpan\|mergePersistOptions\|PopoverFilterChooser\|LogSource" client-app/src/
460
- grep -rn "boolCheckCol\|numberCol\|fileExtCol\|dateCol\|timeCol\|dateTimeCol\|compactDateCol\|localDateCol" client-app/src/
479
+ grep -rnw "boolCheckCol\|numberCol\|fileExtCol\|dateCol\|timeCol\|dateTimeCol\|compactDateCol\|localDateCol" client-app/src/
461
480
  grep -rn -A4 "XH.fetch" client-app/src/ | grep "span:\|loadSpec:"
462
481
  ```
463
482
 
@@ -574,8 +593,8 @@ After completing all steps:
574
593
  - [ ] `pnpm lint` / `yarn lint` / `npm run lint` passes (or only pre-existing warnings remain)
575
594
  - [ ] `grep -rn "makeObservable\|experimentalDecorators" client-app/src client-app/tsconfig.json`
576
595
  returns nothing
577
- - [ ] `grep -rn "@persist @bindable\|@persist @observable\|@persist$" client-app/src/` returns
578
- nothing (`@persist` is last, including the stacked one-decorator-per-line form)
596
+ - [ ] Both `@persist` ordering greps from Step 4 return nothing (`@persist` comes after the MobX
597
+ decorator, on one line or stacked)
579
598
  - [ ] Dev server starts with `rsbuild dev`; production build succeeds and CI passes its version
580
599
  and build tag through `XH_APP_VERSION` / `XH_APP_BUILD`
581
600
  - [ ] Application loads without console errors, including no AG Grid theme-conflict warning
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xh/hoist",
3
- "version": "88.0.0",
3
+ "version": "88.1.1",
4
4
  "description": "Hoist add-on for building and deploying React Applications.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,5 +1,7 @@
1
- // Start load timer as early as possible - read later in XH.trackLoad().
1
+ // Record load info as early as possible - read later in AppStateModel.trackLoad().
2
2
  window._xhLoadTimestamp = Date.now();
3
+ window._xhWasHidden = document.visibilityState === 'hidden';
4
+ document.addEventListener('visibilitychange', function () {window._xhWasHidden = true});
3
5
 
4
6
  // Check browser compatibility with features / syntax we can't polyfill. Currently Mobx 5+ has
5
7
  // a hard requirement for Proxy (test w/string access for max safety), which effectively filters
@@ -6,12 +6,12 @@
6
6
  */
7
7
  import {br, fragment} from '@xh/hoist/cmp/layout';
8
8
  import {isHoistException} from '@xh/hoist/exception';
9
- import {HoistBase, managed, XH} from '@xh/hoist/core';
9
+ import {CallContextLike, HoistBase, managed, XH} from '@xh/hoist/core';
10
10
  import {Icon} from '@xh/hoist/icon';
11
11
  import {action} from '@xh/hoist/mobx';
12
12
  import {never, wait} from '@xh/hoist/promise';
13
13
  import {Token} from '@xh/hoist/security/Token';
14
- import {AccessTokenSpec, TokenMap} from './Types';
14
+ import {AccessTokenSpec, AuthMethod, TokenMap} from './Types';
15
15
  import {Timer} from '@xh/hoist/utils/async';
16
16
  import {MINUTES, olderThan, ONE_MINUTE, SECONDS} from '@xh/hoist/utils/datetime';
17
17
  import {isJSON, logError, throwIf} from '@xh/hoist/utils/js';
@@ -126,6 +126,9 @@ export abstract class BaseOAuthClient<
126
126
  /** Specification for Access Tokens */
127
127
  protected accessSpecs: Record<string, S>;
128
128
 
129
+ /** Method of last successful authentication for this client, if any. */
130
+ lastAuthMethod: AuthMethod = null;
131
+
129
132
  @managed private timer: Timer;
130
133
  private lastRefreshAttempt: number;
131
134
  private TIMER_INTERVAL = 2 * SECONDS;
@@ -155,10 +158,14 @@ export abstract class BaseOAuthClient<
155
158
 
156
159
  /**
157
160
  * Main entry point for this object.
161
+ *
162
+ * @param ctx - tracing context, typically the one supplied to
163
+ * {@link HoistAuthModel.completeAuthAsync}.
158
164
  */
159
- async initAsync(): Promise<void> {
165
+ async initAsync(ctx?: CallContextLike): Promise<void> {
160
166
  try {
161
167
  const tokens = await this.doInitAsync();
168
+ ctx?.span?.setTag('xh.auth.method', this.lastAuthMethod);
162
169
  this.logDebug('Successfully initialized with following tokens:');
163
170
  this.logTokensDebug(tokens);
164
171
  if (this.config.autoRefreshSecs > 0) {
@@ -254,6 +261,12 @@ export abstract class BaseOAuthClient<
254
261
  //---------------------------------------
255
262
  // Implementation
256
263
  //---------------------------------------
264
+ /** Record the path by which authentication completed. Call from `doInitAsync` and login impls. */
265
+ protected noteAuthComplete(authMethod: AuthMethod) {
266
+ this.lastAuthMethod = authMethod;
267
+ this.logInfo(`Authenticated user '${this.getSelectedUsername()}' via ${authMethod}`);
268
+ }
269
+
257
270
  protected get redirectUrl() {
258
271
  const url = this.config.redirectUrl;
259
272
  return url === 'APP_BASE_URL' ? this.baseUrl : url;
@@ -458,6 +471,7 @@ export abstract class BaseOAuthClient<
458
471
  this.lastRelogin = XH.appContainerModel.lastRelogin = {started, completed};
459
472
  })
460
473
  .then(() => {
474
+ this.noteAuthComplete('loginPopup');
461
475
  XH.track({
462
476
  category: 'App',
463
477
  message: 'Interactive reauthentication succeeded',
@@ -49,6 +49,10 @@ The abstract `BaseOAuthClient` manages the core OAuth lifecycle:
49
49
  6. **Logout** (`logoutAsync`) — Clears state and delegates to provider logout
50
50
  7. **Redirect state** — Captures and restores URL routing state across redirect flows
51
51
 
52
+ After init, `lastAuthMethod` reports which path succeeded: `acquireSilent`, `ssoSilent` (MSAL only),
53
+ `loginPopup`, or `loginRedirect`. Pass the ctx from `completeAuthAsync()` to `initAsync(ctx)` to
54
+ also record it as an `xh.auth.method` tag on the `xh.client.auth` span.
55
+
52
56
  ### BaseOAuthClientConfig
53
57
 
54
58
  | Config | Type | Description |
package/security/Types.ts CHANGED
@@ -22,3 +22,9 @@ export interface AccessTokenSpec {
22
22
  }
23
23
 
24
24
  export type TokenMap = Record<string, Token>;
25
+
26
+ /**
27
+ * Path by which an OAuth client completed authentication. Not every client uses every path -
28
+ * e.g. only `MsalClient` supports `ssoSilent`.
29
+ */
30
+ export type AuthMethod = 'acquireSilent' | 'ssoSilent' | 'loginPopup' | 'loginRedirect';
@@ -79,7 +79,9 @@ export class AuthZeroClient extends BaseOAuthClient<AuthZeroClientConfig, AuthZe
79
79
  const {appState} = await client.handleRedirectCallback();
80
80
  this.restoreRedirectState(appState);
81
81
  await this.noteUserAuthenticatedAsync();
82
- return this.fetchAllTokensAsync({eagerOnly: true});
82
+ const ret = await this.fetchAllTokensAsync({eagerOnly: true});
83
+ this.noteAuthComplete('loginRedirect');
84
+ return ret;
83
85
  }
84
86
 
85
87
  // 1) If we are logged in, try to just reload tokens silently. This is the happy path on
@@ -87,18 +89,22 @@ export class AuthZeroClient extends BaseOAuthClient<AuthZeroClientConfig, AuthZe
87
89
  if (await client.isAuthenticated()) {
88
90
  try {
89
91
  this.logDebug('Attempting silent token load.');
90
- return await this.fetchAllTokensAsync({eagerOnly: true});
92
+ const ret = await this.fetchAllTokensAsync({eagerOnly: true});
93
+ this.noteAuthComplete('acquireSilent');
94
+ return ret;
91
95
  } catch (e) {
92
96
  this.logDebug('Failed to load tokens on init, fall back to login', e.message ?? e);
93
97
  }
94
98
  }
95
99
 
96
- // 2) otherwise full-login
100
+ // 2) otherwise full login.
97
101
  this.logDebug('Logging in');
98
102
  await this.loginAsync();
99
103
 
100
- // 3) return tokens
101
- return this.fetchAllTokensAsync({eagerOnly: true});
104
+ // 2a) ... and a redirect never returns above, so this was a popup.
105
+ const ret = await this.fetchAllTokensAsync({eagerOnly: true});
106
+ this.noteAuthComplete('loginPopup');
107
+ return ret;
102
108
  }
103
109
 
104
110
  protected override async doLoginRedirectAsync(): Promise<void> {
@@ -21,7 +21,7 @@ import {logDebug, logError, logInfo, logWarn, mergeDeep, throwIf} from '@xh/hois
21
21
  import {withFormattedTimestamps} from '@xh/hoist/format';
22
22
  import {flatMap, union, uniq} from 'lodash';
23
23
  import {BaseOAuthClient, BaseOAuthClientConfig} from '../BaseOAuthClient';
24
- import {AccessTokenSpec, TokenMap} from '../Types';
24
+ import {AccessTokenSpec, AuthMethod, TokenMap} from '../Types';
25
25
 
26
26
  /**
27
27
  * Configuration for a {@link MsalClient} - the Microsoft Entra ID (Azure AD) OAuth client.
@@ -207,7 +207,11 @@ export class MsalClient extends BaseOAuthClient<MsalClientConfig, MsalTokenSpec>
207
207
  // user involvement but will require at least a redirect or cursory auto-closing popup.
208
208
  this.logDebug('Attempting Login');
209
209
  await this.loginAsync();
210
- return this.fetchAllTokensAsync({eagerOnly: true});
210
+
211
+ // 3a) ... and a redirect never returns above, so this was a popup.
212
+ const ret = await this.fetchAllTokensAsync({eagerOnly: true});
213
+ this.noteAuthComplete('loginPopup');
214
+ return ret;
211
215
  }
212
216
 
213
217
  protected override async doLoginPopupAsync(): Promise<void> {
@@ -217,7 +221,6 @@ export class MsalClient extends BaseOAuthClient<MsalClientConfig, MsalTokenSpec>
217
221
  overrideInteractionInProgress: true
218
222
  });
219
223
  this.setAccount(ret.account);
220
- this.noteAuthComplete('loginPopup');
221
224
  } catch (e) {
222
225
  if (e.errorCode === 'popup_window_error' || e.errorCode === 'empty_window_error') {
223
226
  throw XH.exception({
@@ -455,9 +458,9 @@ export class MsalClient extends BaseOAuthClient<MsalClientConfig, MsalTokenSpec>
455
458
  this.logDebug('Target account identified:', account.username);
456
459
  }
457
460
 
458
- private noteAuthComplete(authMethod: AuthMethod) {
461
+ protected override noteAuthComplete(authMethod: AuthMethod) {
462
+ super.noteAuthComplete(authMethod);
459
463
  if (this.telemetry) this.telemetry.authMethod = authMethod;
460
- this.logInfo(`Authenticated user '${this.account.username}' via ${authMethod}`);
461
464
  }
462
465
 
463
466
  private authRequestCore(): AuthRequestCore {
@@ -483,7 +486,6 @@ type AuthRequestCore = Pick<
483
486
  CommonAuthorizationUrlRequest,
484
487
  'domainHint' | 'scopes' | 'extraScopesToConsent' | 'account' | 'loginHint' | 'redirectUri'
485
488
  >;
486
- type AuthMethod = 'acquireSilent' | 'ssoSilent' | 'loginPopup' | 'loginRedirect';
487
489
 
488
490
  /**
489
491
  * Telemetry produced by this client (if enabled) + included in {@link ClientHealthService}