@xh/hoist 89.1.0 → 89.3.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/build/types/cmp/grid/GridModel.d.ts +6 -0
  3. package/build/types/cmp/viewmanager/ViewManagerModel.d.ts +4 -2
  4. package/build/types/core/XH.d.ts +2 -1
  5. package/build/types/core/persist/PersistenceProvider.d.ts +3 -0
  6. package/build/types/desktop/cmp/dash/DashViewSpec.d.ts +2 -1
  7. package/build/types/desktop/cmp/dash/canvas/impl/DashCanvasContextMenu.d.ts +1 -1
  8. package/build/types/desktop/cmp/dash/canvas/widgetchooser/DashCanvasWidgetChooser.d.ts +3 -2
  9. package/build/types/desktop/cmp/dash/container/impl/DashContainerContextMenu.d.ts +1 -1
  10. package/build/types/desktop/cmp/dash/impl/DashUtils.d.ts +35 -0
  11. package/build/types/desktop/cmp/tab/dynamic/DynamicTabSwitcherModel.d.ts +1 -2
  12. package/build/types/svc/FetchService.d.ts +24 -2
  13. package/cmp/grid/Grid.ts +2 -2
  14. package/cmp/grid/GridModel.ts +14 -1
  15. package/cmp/grid/columns/Column.ts +2 -1
  16. package/cmp/viewmanager/ViewManagerModel.ts +25 -7
  17. package/core/XH.ts +8 -3
  18. package/core/persist/PersistenceProvider.ts +15 -1
  19. package/desktop/cmp/dash/DashViewSpec.ts +2 -1
  20. package/desktop/cmp/dash/README.md +6 -5
  21. package/desktop/cmp/dash/canvas/impl/DashCanvasContextMenu.ts +1 -1
  22. package/desktop/cmp/dash/canvas/impl/utils.ts +16 -51
  23. package/desktop/cmp/dash/canvas/widgetchooser/DashCanvasWidgetChooser.ts +37 -54
  24. package/desktop/cmp/dash/container/impl/DashContainerContextMenu.ts +8 -39
  25. package/desktop/cmp/dash/impl/DashUtils.ts +90 -0
  26. package/desktop/cmp/grid/impl/colchooser/ColChooser.scss +3 -6
  27. package/desktop/cmp/tab/TabSwitcher.ts +4 -6
  28. package/desktop/cmp/tab/dynamic/DynamicTabSwitcher.ts +4 -5
  29. package/desktop/cmp/tab/dynamic/DynamicTabSwitcherModel.ts +2 -7
  30. package/docs/build-and-publish.md +21 -11
  31. package/docs/doc-registry.json +1 -1
  32. package/docs/lifecycle-models-and-services.md +2 -1
  33. package/docs/persistence.md +2 -0
  34. package/docs/telemetry.md +29 -0
  35. package/package.json +1 -1
  36. package/svc/FetchService.ts +87 -32
  37. package/svc/README.md +9 -4
  38. package/svc/impl/NdjsonResultImpl.ts +17 -12
  39. package/build/types/desktop/cmp/tab/impl/TabContextMenuItems.d.ts +0 -4
  40. package/desktop/cmp/tab/impl/TabContextMenuItems.ts +0 -23
@@ -31,6 +31,7 @@ export interface FetchServiceDefaults {
31
31
  autoGenCorrelationIds?: boolean | ((opts: FetchOptions) => boolean);
32
32
  correlationIdHeaderKey?: string;
33
33
  genCorrelationId?: () => string;
34
+ propagateTrace?: boolean | ((opts: FetchOptions) => boolean);
34
35
  }
35
36
 
36
37
  /**
@@ -48,6 +49,8 @@ export interface FetchServiceDefaults {
48
49
  * - Configurable timeouts (default 30s) via {@link FetchOptions.timeout}
49
50
  * - Auto-abort of duplicate in-flight requests via {@link FetchOptions.autoAbortKey}
50
51
  * - Optional correlation IDs for request tracking (see `defaults.autoGenCorrelationIds`)
52
+ * - W3C `traceparent` headers when tracing is enabled, sent by default only to the app's own
53
+ * server (see `defaults.propagateTrace` and {@link FetchOptions.propagateTrace})
51
54
  * - Request/response interceptors via {@link addInterceptor}
52
55
  * - Default headers for all requests via {@link addDefaultHeaders}
53
56
  * - Rich exception handling with HTTP status, server messages, and trace IDs
@@ -63,9 +66,25 @@ export class FetchService extends HoistService {
63
66
  static defaults: FetchServiceDefaults = {
64
67
  autoGenCorrelationIds: false,
65
68
  correlationIdHeaderKey: 'X-Correlation-ID',
66
- genCorrelationId: () => FetchService.defaultIdGenerator.rnd()
69
+ genCorrelationId: () => FetchService.defaultIdGenerator.rnd(),
70
+ propagateTrace: opts => FetchService.isHoistServerUrl(opts.url)
67
71
  };
68
72
 
73
+ /**
74
+ * Does a request url target the app's own server? True for relative and root-relative urls,
75
+ * and for absolute urls on the origin of the page or of {@link XH.baseUrl}.
76
+ */
77
+ static isHoistServerUrl(url: string): boolean {
78
+ if (!url?.includes('//')) return true;
79
+ try {
80
+ const {origin} = window.location,
81
+ target = new URL(url, origin).origin;
82
+ return target === origin || target === new URL(XH.baseUrl, origin).origin;
83
+ } catch {
84
+ return false;
85
+ }
86
+ }
87
+
69
88
  NO_JSON_RESPONSES = [StatusCodes.NO_CONTENT, StatusCodes.RESET_CONTENT];
70
89
 
71
90
  /**
@@ -194,18 +213,23 @@ export class FetchService extends HoistService {
194
213
  // The runner will manage the lifecycle, but we won't await it here -- return
195
214
  // the result straight away. Also stifle telemetry exception. Stream already produces them.
196
215
  let ret: NdjsonResultImpl;
216
+ const aborter = new AbortController();
197
217
  runner
198
218
  .run(async innerCtx => {
199
219
  ret = new NdjsonResultImpl(
200
- this.fetchInternalAsync(opts, innerCtx, true),
220
+ this.fetchInternalAsync(opts, innerCtx, aborter),
201
221
  opts,
202
222
  this.getInterner(opts.internStrings),
203
223
  (cause, response) =>
204
- cause?.name === 'AbortError'
224
+ this.isAborted(opts, aborter)
205
225
  ? this.abortedException(opts, innerCtx, cause)
206
226
  : this.streamFailedException(opts, innerCtx, response, cause)
207
227
  );
208
- await ret.whenCompleteAsync();
228
+ try {
229
+ await ret.whenCompleteAsync();
230
+ } finally {
231
+ this.releaseAutoAbortKey(opts.autoAbortKey, aborter);
232
+ }
209
233
  })
210
234
  .catch(noop);
211
235
  return ret;
@@ -292,15 +316,17 @@ export class FetchService extends HoistService {
292
316
  private static readonly defaultIdGenerator = new ShortUniqueId({length: 16});
293
317
 
294
318
  /**
295
- * @param forStreaming - true when called by fetchNdjson, which applies its own span and
296
- * track across the full stream lifetime - suppresses both here.
319
+ * @param streamAborter - aborter for a stream, set by fetchNdjson. It applies its own span and
320
+ * track across the full stream lifetime - suppresses both here - and releases any
321
+ * autoAbortKey once the stream completes.
297
322
  */
298
323
  private async fetchInternalAsync(
299
324
  opts: FetchOptions,
300
325
  ctx?: CallContextLike,
301
- forStreaming: boolean = false
326
+ streamAborter: AbortController = null
302
327
  ): Promise<any> {
303
328
  ctx ??= {};
329
+ const forStreaming = !!streamAborter;
304
330
 
305
331
  let spanConfig = forStreaming ? null : this.createSpanConfig(opts),
306
332
  runner = spanConfig ? this.runner(ctx).span(spanConfig) : this.runner(ctx),
@@ -308,7 +334,7 @@ export class FetchService extends HoistService {
308
334
  opts = this.withCorrelationId(opts);
309
335
  opts = this.withTraceId(opts, ctx.span);
310
336
  return this.withResolvedHeadersAsync(opts, ctx.span).then(opts =>
311
- this.managedFetchAsync(opts, ctx)
337
+ this.managedFetchAsync(opts, ctx, streamAborter)
312
338
  );
313
339
  });
314
340
 
@@ -383,7 +409,7 @@ export class FetchService extends HoistService {
383
409
  'Content-Type': isForm ? 'application/x-www-form-urlencoded' : 'text/plain',
384
410
  ...defaultHeaders,
385
411
  ...(opts.asJson ? {Accept: 'application/json'} : {}),
386
- ...(span
412
+ ...(span && this.shouldPropagateTrace(opts)
387
413
  ? {traceparent: formatTraceparent(span.traceId, span.spanId, span.sampled)}
388
414
  : {}),
389
415
  ...opts.headers
@@ -403,15 +429,25 @@ export class FetchService extends HoistService {
403
429
  return {...opts, method, headers};
404
430
  }
405
431
 
406
- private async managedFetchAsync(opts: FetchOptions, callCtx: CallContext): Promise<any> {
432
+ private shouldPropagateTrace(opts: FetchOptions): boolean {
433
+ if (!isNil(opts.propagateTrace)) return opts.propagateTrace;
434
+ const {propagateTrace} = FetchService.defaults;
435
+ return isFunction(propagateTrace) ? propagateTrace(opts) : propagateTrace;
436
+ }
437
+
438
+ private async managedFetchAsync(
439
+ opts: FetchOptions,
440
+ callCtx: CallContext,
441
+ streamAborter: AbortController
442
+ ): Promise<any> {
407
443
  // Prepare auto-aborter
408
444
  const {autoAborters, defaultTimeout} = this,
409
445
  {autoAbortKey, timeout = defaultTimeout} = opts,
410
- aborter = new AbortController();
446
+ aborter = streamAborter ?? new AbortController();
411
447
 
412
448
  // autoAbortKey handling. Abort anything running under this key, and mark this run
413
449
  if (autoAbortKey) {
414
- autoAborters[autoAbortKey]?.abort();
450
+ this.abort(autoAbortKey);
415
451
  autoAborters[autoAbortKey] = aborter;
416
452
  }
417
453
 
@@ -430,17 +466,24 @@ export class FetchService extends HoistService {
430
466
  throw this.timeoutException(opts, callCtx, e, msg);
431
467
  }
432
468
 
433
- if (!e.isHoistException) {
434
- // Just two other cases where we expect this to *throw* -- Typically we get a fail status
435
- throw e.name === 'AbortError'
436
- ? this.abortedException(opts, callCtx, e)
437
- : this.serverUnavailableException(opts, callCtx, e);
438
- }
439
- throw e;
469
+ if (this.isAborted(opts, aborter)) throw this.abortedException(opts, callCtx, e);
470
+ if (e.isHoistException) throw e;
471
+
472
+ // Any other error means the server could not be reached.
473
+ throw this.serverUnavailableException(opts, callCtx, e);
440
474
  } finally {
441
- if (autoAborters[autoAbortKey] === aborter) {
442
- delete autoAborters[autoAbortKey];
443
- }
475
+ if (!streamAborter) this.releaseAutoAbortKey(autoAbortKey, aborter);
476
+ }
477
+ }
478
+
479
+ // Fetch listens to both signals, joined - check each, as a custom abort reason is no AbortError.
480
+ private isAborted(opts: FetchOptions, aborter: AbortController): boolean {
481
+ return aborter.signal.aborted || !!opts.fetchOpts?.signal?.aborted;
482
+ }
483
+
484
+ private releaseAutoAbortKey(autoAbortKey: string, aborter: AbortController) {
485
+ if (autoAbortKey && this.autoAborters[autoAbortKey] === aborter) {
486
+ delete this.autoAborters[autoAbortKey];
444
487
  }
445
488
  }
446
489
 
@@ -453,16 +496,17 @@ export class FetchService extends HoistService {
453
496
  let {url, method, headers, body, params} = opts;
454
497
  url = this.resolveUrl(url);
455
498
 
456
- // 2) Prepare options for fetch API
457
- const fetchOpts: RequestInit = {
458
- signal: aborter.signal,
459
- credentials: 'include',
460
- redirect: 'follow',
461
- headers: new Headers(omitBy(headers, isNil)),
462
- method,
463
- body,
464
- ...opts.fetchOpts
465
- };
499
+ // 2) Prepare options for fetch API. Join any caller signal with ours, so either aborts.
500
+ const {signal, ...callerFetchOpts} = opts.fetchOpts ?? {},
501
+ fetchOpts: RequestInit = {
502
+ credentials: 'include',
503
+ redirect: 'follow',
504
+ headers: new Headers(omitBy(headers, isNil)),
505
+ method,
506
+ body,
507
+ ...callerFetchOpts,
508
+ signal: signal ? AbortSignal.any([aborter.signal, signal]) : aborter.signal
509
+ };
466
510
 
467
511
  // 3) Preprocess and apply params
468
512
  if (params) {
@@ -860,6 +904,17 @@ export interface FetchOptions {
860
904
  */
861
905
  correlationId?: string | boolean;
862
906
 
907
+ /**
908
+ * True to send a W3C `traceparent` header with this request, false to omit it. Applies only
909
+ * when tracing is enabled. The request still records a client span either way, but only a
910
+ * server that receives the header can join the trace. Defaults to
911
+ * `FetchService.defaults.propagateTrace`, which sends the header only to the app's own server.
912
+ *
913
+ * Note `traceparent` is not a CORS-safelisted header. A cross-origin server must list it in
914
+ * `Access-Control-Allow-Headers`, or the browser blocks the request.
915
+ */
916
+ propagateTrace?: boolean;
917
+
863
918
  /**
864
919
  * Parameters to encode and append as a query string, or send with the request body
865
920
  * (for POSTs/PUTs sending form-url-encoded).
package/svc/README.md CHANGED
@@ -100,6 +100,7 @@ Managed HTTP requests with enhancements over the native Fetch API.
100
100
 
101
101
  **Key Features:**
102
102
  - Automatic correlation IDs for request tracking
103
+ - W3C `traceparent` headers on requests to the app's own server, when tracing is enabled
103
104
  - Configurable timeouts (default 30 seconds)
104
105
  - Auto-abort of duplicate requests via `autoAbortKey`
105
106
  - Request/response interceptors
@@ -135,20 +136,24 @@ override async doLoadAsync(loadSpec: LoadSpec) {
135
136
  | `params` | object | Query string parameters |
136
137
  | `headers` | object | Additional headers |
137
138
  | `timeout` | number | Timeout in ms (default 30000) |
138
- | `autoAbortKey` | string | Cancel previous requests with same key |
139
+ | `autoAbortKey` | string | Cancel previous requests with same key. For `fetchNdjson`, covers the whole stream |
140
+ | `fetchOpts` | object | Options for the native `fetch()`. A `signal` here also aborts the request, alongside Hoist's own |
141
+ | `propagateTrace` | boolean | Send a `traceparent` header when tracing is enabled. Overrides `FetchService.defaults.propagateTrace` |
139
142
  | `loadSpec` | LoadSpec | Metadata for tracking |
140
143
  | `span` | Span | Parent span for tracing. Typically supplied via a `Runner` chain (`runner.fetchJson(...)`) rather than set directly |
141
144
 
142
145
  **App-Level Defaults (`FetchService.defaults`):**
143
146
 
144
- FetchService exposes a `static defaults` object for correlation ID configuration. Best configured
145
- in the app's `Bootstrap` module to ensure settings are active from the very first request.
147
+ FetchService exposes a `static defaults` object for correlation ID and trace header configuration.
148
+ Best configured in the app's `Bootstrap` module to ensure settings are active from the very first
149
+ request.
146
150
 
147
151
  | Property | Type | Default | Description |
148
152
  |----------|------|---------|-------------|
149
153
  | `autoGenCorrelationIds` | `boolean \| function` | `false` | Auto-generate correlation IDs. Set `true` or a `(opts) => boolean` function for per-request control |
150
154
  | `genCorrelationId` | `() => string` | 16-char random string | Custom ID generator function |
151
155
  | `correlationIdHeaderKey` | `string` | `'X-Correlation-ID'` | HTTP header name for correlation IDs |
156
+ | `propagateTrace` | `boolean \| function` | App's own server only | Send a `traceparent` header when tracing is enabled. Set `true` for all requests, or a `(opts) => boolean` function. See [Trace headers on fetch requests](../docs/telemetry.md#trace-headers-on-fetch-requests) |
152
157
 
153
158
  ```typescript
154
159
  // In Bootstrap module
@@ -321,7 +326,7 @@ category while all other entries continue to require INFO or above.
321
326
  > tracing, metrics, and activity tracking.
322
327
 
323
328
  Client-side distributed tracing — creates spans for user actions and fetch calls, injects
324
- `traceparent` headers on outgoing requests, and batches completed spans for export to the
329
+ `traceparent` headers on requests to the app's own server, and batches completed spans for export to the
325
330
  Hoist server. Exceptions thrown during traced operations include a `traceId` for correlation
326
331
  with server-side traces. Controlled by the `xhTraceConfig` soft config. Requires hoist-core 37+.
327
332
 
@@ -119,19 +119,24 @@ export class NdjsonResultImpl implements NdjsonResult {
119
119
  decoder = new TextDecoder();
120
120
  let buffer = '';
121
121
 
122
- while (true) {
123
- const {done, value} = await reader.read();
124
- if (done) break;
125
-
126
- buffer += decoder.decode(value, {stream: true});
127
- const lines = buffer.split('\n');
128
- buffer = lines.pop(); // retain any partial trailing line for the next chunk
129
- for (const line of lines) {
130
- if (!line) continue;
131
- const record = JSON.parse(line);
132
- interner?.intern(record);
133
- yield record;
122
+ try {
123
+ while (true) {
124
+ const {done, value} = await reader.read();
125
+ if (done) break;
126
+
127
+ buffer += decoder.decode(value, {stream: true});
128
+ const lines = buffer.split('\n');
129
+ buffer = lines.pop(); // retain any partial trailing line for the next chunk
130
+ for (const line of lines) {
131
+ if (!line) continue;
132
+ const record = JSON.parse(line);
133
+ interner?.intern(record);
134
+ yield record;
135
+ }
134
136
  }
137
+ } finally {
138
+ // Close the connection if the consumer exits early or a line fails to parse.
139
+ reader.cancel().catch(noop);
135
140
  }
136
141
 
137
142
  buffer += decoder.decode();
@@ -1,4 +0,0 @@
1
- import { TabSwitcherMenuContext } from '@xh/hoist/cmp/tab';
2
- import { type MenuItemLike, MenuToken } from '@xh/hoist/core';
3
- /** @internal */
4
- export declare function getContextMenuItem(item: MenuItemLike<MenuToken, TabSwitcherMenuContext>, context: TabSwitcherMenuContext): MenuItemLike<MenuToken, TabSwitcherMenuContext>;
@@ -1,23 +0,0 @@
1
- /*
2
- * This file belongs to Hoist, an application development toolkit
3
- * developed by Extremely Heavy Industries (www.xh.io | info@xh.io)
4
- *
5
- * Copyright © 2026 Extremely Heavy Industries Inc.
6
- */
7
- import {TabSwitcherMenuContext} from '@xh/hoist/cmp/tab';
8
- import {isMenuHeading, isMenuItem, type MenuItemLike, MenuToken} from '@xh/hoist/core';
9
- import {bindMenuHeadingContext} from '@xh/hoist/cmp/menu/impl/Menus';
10
-
11
- /** @internal */
12
- export function getContextMenuItem(
13
- item: MenuItemLike<MenuToken, TabSwitcherMenuContext>,
14
- context: TabSwitcherMenuContext
15
- ): MenuItemLike<MenuToken, TabSwitcherMenuContext> {
16
- if (isMenuHeading(item)) return bindMenuHeadingContext(item, context);
17
- if (!isMenuItem(item)) return item;
18
- const ret = {...item};
19
- if (item.actionFn) ret.actionFn = e => item.actionFn(e, context);
20
- if (item.prepareFn) ret.prepareFn = e => item.prepareFn(e, context);
21
- if (item.items) ret.items = item.items.map(it => this.buildMenuItem(it, context));
22
- return ret;
23
- }