@webority/web-core 0.150.0 → 0.153.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.
package/README.md CHANGED
@@ -247,6 +247,37 @@ function LeaveList() {
247
247
 
248
248
  `tableProps` feeds `AppDataTable` and `paginationProps` feeds its pager. The server answers `{ items, page, pageSize, totalCount, totalPages }`, and the hook takes the page size from that answer when the URL names none.
249
249
 
250
+ ## Versioned saves
251
+
252
+ A record another writer can change carries a `version`. A list item holds it in its `version` string. A single record's read sends it as a strong `ETag`, and the screen passes that ETag as `entityTag`. `versionOf(record, entityTag)` returns the version a write sends back.
253
+
254
+ ```ts
255
+ import { saveWithVersion } from "@webority/web-core";
256
+
257
+ const result = await saveWithVersion({
258
+ record: leave,
259
+ form: values,
260
+ toForm: (record) => ({ start: record.start, end: record.end, reason: record.reason }),
261
+ read: async () => ({ record: await fetchLeave(leave.id) }),
262
+ save: (form, version) => updateLeave({ id: leave.id, body: form, version }).unwrap(),
263
+ });
264
+ if (!result.saved) {
265
+ reset(toForm(result.fresh));
266
+ }
267
+ ```
268
+
269
+ The message to show is `result.error.message` (the server's text), shown through the shared error path. The endpoint maps `version` to `ifMatch`.
270
+
271
+ A stale save re-reads the record once and saves again only when the server's copy of the form fields is unchanged. A second stale answer is returned. The retry is safe only when the save writes just the fields `toForm` covers, so a field a background job changed is never overwritten.
272
+
273
+ An axios service built outside RTK Query uses the same two rules: `withIfMatch(version, cfg)` returns `cfg` with the quoted `If-Match` header the base query sends, and `entityTagOf(response)` returns the strong ETag of a read (undefined for a weak or missing one), ready for `versionOf`.
274
+
275
+ ```ts
276
+ const response = await userClient.get(`/leaves/${id}`);
277
+ const entityTag = entityTagOf(response);
278
+ await userClient.put(`/leaves/${id}`, body, withIfMatch(versionOf(response.data, entityTag)));
279
+ ```
280
+
250
281
  ## Formatters
251
282
 
252
283
  Called with no options, the house formatters print (zone IST, locale en-IN, empty `-`):
@@ -364,6 +395,61 @@ Vite 7 and earlier `esbuild: { pure: ["Logger.debug"] }`. This matches the call
364
395
  already filtered by `logLevel`. On the web, track the matched route pattern with `trackScreen`, never the
365
396
  concrete URL.
366
397
 
398
+ ## Application Insights
399
+
400
+ `initAppInsights`, from `@webority/web-core/appInsights`, starts Application Insights and makes it one
401
+ of the `Logger`'s remote sinks. It takes these options:
402
+
403
+ - `connectionString`: the Application Insights connection string. An empty string turns telemetry off.
404
+ - `cloudRole`: the role name queries partition by, before the environment suffix.
405
+ - `environment`: the environment name. Any value other than an empty string or `Production` adds a
406
+ lower-case suffix to the role.
407
+ - `version`: the build version stamped on every item as `ai.application.ver`.
408
+ - `apiBaseUrl`: the URL of the API, absolute or relative to the page (`"/api"` resolves against the
409
+ page's origin). Its host gets correlation headers, and the browser does not send its successful
410
+ calls a second time. A value that is not a URL throws.
411
+ - `extensions`: extra SDK plugins, such as the React plugin.
412
+ - `initializers`: the app's own telemetry initializers. They run after the library's, before the first
413
+ page view. Returning `false` drops the item.
414
+ - `slowDependencyMs`: a dependency this many milliseconds or slower is kept even when it succeeds.
415
+ Default 500.
416
+ - `sinks`: extra remote loggers (`RemoteLogger` objects) that get every log line, error, user and
417
+ attribute beside Application Insights.
418
+
419
+ An empty connection string, or a test run, starts nothing and returns `null`.
420
+
421
+ Some behaviour has no option. The library fixes it, and a product cannot change it from
422
+ `initAppInsights`:
423
+
424
+ - Redaction: the query keys `token`, `code`, `email`, `access_token`, `id_token`, `state`,
425
+ `session_state`, `password`, `search`, `q` and `query` are removed from every address, whatever their
426
+ case. The fragment is dropped. The address fields `uri`, `refUri` and `url`, and the text fields
427
+ `name`, `data` and `message`, are scrubbed the same way. A query value that is itself an address is
428
+ scrubbed too.
429
+ - Auto-collectors: page views on route changes are on, page visit timing is off, AJAX dependency
430
+ tracking is on, and CORS correlation is on. Request and response header tracking is off, and the
431
+ `unload` listeners are disabled. Cookies stay off until the consent manager turns them on.
432
+ - Dependency policy: no metrics. A dependency is sent only when it failed or was slow.
433
+
434
+ ### Keeping your own error sink
435
+
436
+ A product can keep its own error log beside Application Insights. Pass the sink in `sinks`:
437
+
438
+ ```ts
439
+ import { initAppInsights } from "@webority/web-core/appInsights";
440
+ import type { RemoteLogger } from "@webority/web-core";
441
+
442
+ const apiErrorLogSink: RemoteLogger = {
443
+ recordError: (error, context) => postToApiErrorLog(error, context),
444
+ };
445
+
446
+ initAppInsights({ connectionString, cloudRole, environment, version, apiBaseUrl, sinks: [apiErrorLogSink] });
447
+ ```
448
+
449
+ Each sink gets every log line, error, user and attribute. A sink that throws does not stop the others.
450
+ Do not call `setRemoteLogger` yourself after `initAppInsights`. It replaces the fan-out, so Application
451
+ Insights and the other sinks stop receiving.
452
+
367
453
  ## Design sample
368
454
 
369
455
  A Canvas compare opens a staging page with a `designSample` key in its address, and a person can open
@@ -1 +1 @@
1
- import{getConfigValue as e}from"../config/index.js";var t=t=>{t.interceptors.request.use(t=>(t.baseURL||=e(`baseUrl`)??void 0,t))};export{t as applyConfiguredBaseUrl};
1
+ import{getConfigValue as e}from"../config/index.js";var t=t=>{t.interceptors.request.use(t=>{if(!t.baseURL){let n=e(`baseUrl`)??void 0;n!==void 0&&(t.baseURL=n)}return t})};export{t as applyConfiguredBaseUrl};
@@ -1 +1 @@
1
- import{buildContractRequest as e}from"../api-contract/dist/call.js";var t=(t,n)=>async(r,i,a)=>{let o=e(n[r],i);return(await t.request({method:o.method,url:o.url,params:o.params,headers:o.headers,data:o.data,responseType:o.responseType,signal:a?.signal,timeout:a?.timeout})).data};export{t as createContractCaller};
1
+ import{buildContractRequest as e}from"../api-contract/dist/call.js";var t=(t,n)=>async(r,i,a)=>{let o=e(n[r],i);return(await t.request({method:o.method,url:o.url,params:o.params,...o.headers!==void 0&&{headers:o.headers},data:o.data,responseType:o.responseType,...a?.signal!==void 0&&{signal:a.signal},...a?.timeout!==void 0&&{timeout:a.timeout}})).data};export{t as createContractCaller};
@@ -0,0 +1 @@
1
+ var e=()=>globalThis.crypto,t=()=>{let t=/* @__PURE__ */ new Uint8Array(16),n=e();if(typeof n?.getRandomValues==`function`)n.getRandomValues(t);else for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t},n=e=>{let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20,32)}`},r=()=>{let r=e();return typeof r?.randomUUID==`function`?r.randomUUID():n(Array.from(t(),(e,t)=>t===6?e&15|64:t===8?e&63|128:e))};export{r as newIdempotencyKey};
package/dist/api/index.js CHANGED
@@ -1 +1 @@
1
- import{initUserAuth as e}from"../initUserAuth.js";import{readBlobErrorBody as t}from"./blobErrorBody.js";import{ACCOUNT_ID_HEADER as n,CLIENT_BUILD_HEADER as r,CLIENT_KIND as i,CLIENT_KIND_HEADER as a,getClientBuild as o}from"./clientHeaders.js";import{createContractCaller as s}from"./contractCaller.js";import{REFRESH_LOCK_NAME as c,withCrossTabRefreshLock as l}from"./crossTabRefreshLock.js";import{DESIGN_SAMPLE_HEADER as u,DESIGN_SAMPLE_QUERY_KEY as d,DESIGN_SAMPLE_STORAGE_KEY as f,applyDesignSample as p,readDesignSampleTicket as m}from"./designSample.js";import{contentDispositionFileName as h,downloadFile as g}from"./downloadFile.js";import{MIN_APP_VERSION_HEADER as _,addMinAppVersionListener as v,getMinAppVersion as y}from"./minAppVersion.js";import b from"./publicClient.js";import{TRACEPARENT_HEADER as x,applyRequestDefaults as S,newTraceparent as C}from"./requestDefaults.js";import{IDEMPOTENCY_KEY_HEADER as w,attachRetry as T,isNeverSentError as E,isRetryableFailure as D,isRetryableStatus as O,retryAfterMs as k}from"./retry.js";import{SESSION_EXPIRED_CODE as A,SESSION_REVOKED_CODE as j,injectStore as M,injectUserAuth as N,refreshAccessToken as P,resetRefreshState as F}from"./tokenRefresh.js";import I,{RequestOfflineError as L}from"./userClient.js";import{WORKSPACE_CHANGED_CODE as R,WorkspaceChangedError as z,isWorkspaceChangedError as B}from"./workspaceChanged.js";export{n as ACCOUNT_ID_HEADER,r as CLIENT_BUILD_HEADER,i as CLIENT_KIND,a as CLIENT_KIND_HEADER,u as DESIGN_SAMPLE_HEADER,d as DESIGN_SAMPLE_QUERY_KEY,f as DESIGN_SAMPLE_STORAGE_KEY,w as IDEMPOTENCY_KEY_HEADER,_ as MIN_APP_VERSION_HEADER,c as REFRESH_LOCK_NAME,L as RequestOfflineError,A as SESSION_EXPIRED_CODE,j as SESSION_REVOKED_CODE,x as TRACEPARENT_HEADER,R as WORKSPACE_CHANGED_CODE,z as WorkspaceChangedError,v as addMinAppVersionListener,p as applyDesignSample,S as applyRequestDefaults,T as attachRetry,h as contentDispositionFileName,s as createContractCaller,g as downloadFile,o as getClientBuild,y as getMinAppVersion,e as initUserAuth,M as injectStore,N as injectUserAuth,E as isNeverSentError,D as isRetryableFailure,O as isRetryableStatus,B as isWorkspaceChangedError,C as newTraceparent,b as publicClient,t as readBlobErrorBody,m as readDesignSampleTicket,P as refreshAccessToken,F as resetRefreshState,k as retryAfterMs,I as userClient,l as withCrossTabRefreshLock};
1
+ import{initUserAuth as e}from"../initUserAuth.js";import{readBlobErrorBody as t}from"./blobErrorBody.js";import{ACCOUNT_ID_HEADER as n,CLIENT_BUILD_HEADER as r,CLIENT_KIND as i,CLIENT_KIND_HEADER as a,getClientBuild as o}from"./clientHeaders.js";import{createContractCaller as s}from"./contractCaller.js";import{REFRESH_LOCK_NAME as c,withCrossTabRefreshLock as l}from"./crossTabRefreshLock.js";import{DESIGN_SAMPLE_HEADER as u,DESIGN_SAMPLE_QUERY_KEY as d,DESIGN_SAMPLE_STORAGE_KEY as f,applyDesignSample as p,readDesignSampleTicket as m}from"./designSample.js";import{contentDispositionFileName as h,downloadFile as g}from"./downloadFile.js";import{newIdempotencyKey as _}from"./idempotencyKey.js";import{MIN_APP_VERSION_HEADER as v,addMinAppVersionListener as y,getMinAppVersion as b}from"./minAppVersion.js";import x from"./publicClient.js";import{TRACEPARENT_HEADER as S,applyRequestDefaults as C,newTraceparent as w}from"./requestDefaults.js";import{IDEMPOTENCY_KEY_HEADER as T,attachRetry as E,isNeverSentError as D,isRetryableFailure as O,isRetryableStatus as k,retryAfterMs as A}from"./retry.js";import{SESSION_EXPIRED_CODE as j,SESSION_REVOKED_CODE as M,injectStore as N,injectUserAuth as P,refreshAccessToken as F,resetRefreshState as I}from"./tokenRefresh.js";import L,{RequestOfflineError as R}from"./userClient.js";import{WORKSPACE_CHANGED_CODE as z,WorkspaceChangedError as B,isWorkspaceChangedError as V}from"./workspaceChanged.js";export{n as ACCOUNT_ID_HEADER,r as CLIENT_BUILD_HEADER,i as CLIENT_KIND,a as CLIENT_KIND_HEADER,u as DESIGN_SAMPLE_HEADER,d as DESIGN_SAMPLE_QUERY_KEY,f as DESIGN_SAMPLE_STORAGE_KEY,T as IDEMPOTENCY_KEY_HEADER,v as MIN_APP_VERSION_HEADER,c as REFRESH_LOCK_NAME,R as RequestOfflineError,j as SESSION_EXPIRED_CODE,M as SESSION_REVOKED_CODE,S as TRACEPARENT_HEADER,z as WORKSPACE_CHANGED_CODE,B as WorkspaceChangedError,y as addMinAppVersionListener,p as applyDesignSample,C as applyRequestDefaults,E as attachRetry,h as contentDispositionFileName,s as createContractCaller,g as downloadFile,o as getClientBuild,b as getMinAppVersion,e as initUserAuth,N as injectStore,P as injectUserAuth,D as isNeverSentError,O as isRetryableFailure,k as isRetryableStatus,V as isWorkspaceChangedError,_ as newIdempotencyKey,w as newTraceparent,x as publicClient,t as readBlobErrorBody,m as readDesignSampleTicket,F as refreshAccessToken,I as resetRefreshState,A as retryAfterMs,L as userClient,l as withCrossTabRefreshLock};
@@ -1 +1 @@
1
- import{getConfigValue as e}from"../config/index.js";var t=`traceparent`,n=e=>{let t=globalThis.crypto,n=new Uint8Array(e);if(typeof t?.getRandomValues==`function`)t.getRandomValues(n);else for(let e=0;e<n.length;e+=1)n[e]=Math.floor(Math.random()*256);return n.every(e=>e===0)&&(n[n.length-1]=1),Array.from(n,e=>e.toString(16).padStart(2,`0`)).join(``)},r=()=>{let e=n(16);return{header:`00-${e}-${n(8)}-01`,traceId:e}},i=n=>{n.defaults.timeout=void 0,n.interceptors.request.use(n=>(n.timeout===void 0&&(n.timeout=e(`timeoutMs`)),n.headers.has(`traceparent`)||n.headers.set(t,r().header),n))};export{t as TRACEPARENT_HEADER,i as applyRequestDefaults,r as newTraceparent};
1
+ import{getConfigValue as e}from"../config/index.js";var t=`traceparent`,n=e=>{let t=globalThis.crypto,n=new Uint8Array(e);if(typeof t?.getRandomValues==`function`)t.getRandomValues(n);else for(let e=0;e<n.length;e+=1)n[e]=Math.floor(Math.random()*256);return n.every(e=>e===0)&&(n[n.length-1]=1),Array.from(n,e=>e.toString(16).padStart(2,`0`)).join(``)},r=()=>{let e=n(16);return{header:`00-${e}-${n(8)}-01`,traceId:e}},i=n=>{delete n.defaults.timeout,n.interceptors.request.use(n=>(n.timeout===void 0&&(n.timeout=e(`timeoutMs`)),n.headers.has(`traceparent`)||n.headers.set(t,r().header),n))};export{t as TRACEPARENT_HEADER,i as applyRequestDefaults,r as newTraceparent};
@@ -1 +1 @@
1
- var e=`workspace_changed`,t=e=>typeof e==`object`&&!!e&&!Array.isArray(e),n=e=>t(e)?e:null,r=class t extends Error{code=e;response;config;cause;constructor(e=`This was started in another workspace. Switch back to it and try again.`,n={}){super(e),this.name=`WorkspaceChangedError`,this.response=n.response??{status:409,data:{code:`workspace_changed`,detail:e},headers:{}},this.config=n.config,this.cause=n.cause,Object.setPrototypeOf(this,t.prototype)}},i=e=>e instanceof r||typeof e==`object`&&!!e&&(`name`in e&&e.name===`WorkspaceChangedError`||`code`in e&&e.code===`workspace_changed`),a=e=>e.response?.status===409&&n(e.response.data)?.code===`workspace_changed`,o=e=>{let t=n(e.response?.data)?.detail;return new r(typeof t==`string`&&t.trim()!==``?t:void 0,{response:e.response,config:e.config,cause:e})};export{e as WORKSPACE_CHANGED_CODE,r as WorkspaceChangedError,i as isWorkspaceChangedError,a as isWorkspaceChangedResponse,o as workspaceChangedFromResponse};
1
+ var e=`workspace_changed`,t=e=>typeof e==`object`&&!!e&&!Array.isArray(e),n=e=>t(e)?e:null,r=class t extends Error{code=e;response;config;cause;constructor(e=`This was started in another workspace. Switch back to it and try again.`,n={}){super(e),this.name=`WorkspaceChangedError`,this.response=n.response??{status:409,data:{code:`workspace_changed`,detail:e},headers:{}},n.config!==void 0&&(this.config=n.config),this.cause=n.cause,Object.setPrototypeOf(this,t.prototype)}},i=e=>e instanceof r||typeof e==`object`&&!!e&&(`name`in e&&e.name===`WorkspaceChangedError`||`code`in e&&e.code===`workspace_changed`),a=e=>e.response?.status===409&&n(e.response.data)?.code===`workspace_changed`,o=e=>{let t=n(e.response?.data)?.detail;return new r(typeof t==`string`&&t.trim()!==``?t:void 0,{...e.response!==void 0&&{response:e.response},...e.config!==void 0&&{config:e.config},cause:e})};export{e as WORKSPACE_CHANGED_CODE,r as WorkspaceChangedError,i as isWorkspaceChangedError,a as isWorkspaceChangedResponse,o as workspaceChangedFromResponse};
@@ -1 +1 @@
1
- import{setRemoteLogger as e}from"../logger/logger.js";import{ApplicationInsights as t,SeverityLevel as n}from"@microsoft/applicationinsights-web";var r=500,i=/^(?:(\d+)\.)?(\d+):(\d+):(\d+(?:\.\d+)?)$/,a={info:n.Information,warn:n.Warning,error:n.Error},o=/* @__PURE__ */ new Map;function s(n){if(n.connectionString===``||c())return null;let i;try{i=new URL(n.apiBaseUrl).hostname}catch{throw Error(`initAppInsights: apiBaseUrl must be an absolute URL`)}let s=n.environment===``||n.environment===`Production`?n.cloudRole:`${n.cloudRole}-${n.environment.toLowerCase()}`,l=n.slowDependencyMs??r,d=new t({config:{connectionString:n.connectionString,extensions:n.extensions??[],enableAutoRouteTracking:!0,disableAjaxTracking:!1,autoTrackPageVisitTime:!1,enableCorsCorrelation:!0,enableRequestHeaderTracking:!1,enableResponseHeaderTracking:!1,correlationHeaderDomains:[i],disableCookiesUsage:!0,disablePageUnloadEvents:[`unload`]}});d.loadAppInsights(),d.addTelemetryInitializer(e=>{e.tags=e.tags??{},e.tags[`ai.cloud.role`]=s,e.tags[`ai.application.ver`]=n.version}),d.addTelemetryInitializer(C),d.addTelemetryInitializer(S),d.addTelemetryInitializer(e=>u(e,l)),d.addDependencyInitializer(e=>f(e,i));for(let e of n.initializers??[])d.addTelemetryInitializer(e);return w(d),e({log:(e,t)=>{e!==`debug`&&d.trackTrace({message:t,severityLevel:a[e]})},recordError:(e,t)=>{d.trackException({exception:e instanceof Error?e:Error(String(e))},t)},setUser:e=>{typeof e==`string`?d.setAuthenticatedUserContext(e):d.clearAuthenticatedUserContext()},setAttribute:(e,t)=>{o.set(e,t)}}),d}function c(){let e=Reflect.get(globalThis,`process`),t=typeof e==`object`&&e&&`env`in e?e.env:void 0;return typeof t==`object`&&!!t&&`VITEST`in t&&!!t.VITEST}function l(e){if(typeof e==`number`)return e;let t=typeof e==`string`?i.exec(e):null;if(!t)return;let[,n=`0`,r,a,o]=t;return(((Number(n)*24+Number(r))*60+Number(a))*60+Number(o))*1e3}function u(e,t=r){if(e.baseType===`MetricData`)return!1;if(e.baseType!==`RemoteDependencyData`||e.baseData?.success!==!0)return!0;let n=l(e.baseData.duration);return n===void 0||n>=t}function d(e){if(typeof e!=`string`||e===``)return``;try{return new URL(e.includes(`://`)?e:`https://${e}`).hostname}catch{return``}}function f({item:e},t){let n=Number(e?.responseCode);return n>0&&n<400?d(e.target)!==t:!0}var p=/* @__PURE__ */ new Set([`token`,`code`,`email`,`access_token`,`id_token`,`state`,`session_state`,`password`,`search`,`q`,`query`]),m=[`uri`,`refUri`,`url`],h=[`name`,`data`,`message`],g=/^(\/|https?:\/\/)/i;function _(e){if(typeof e!=`string`||e===``)return e;let t=e.indexOf(`#`),n=t===-1?e:e.slice(0,t),r=n.indexOf(`?`);if(r===-1)return n;let i=new URLSearchParams;for(let[e,t]of new URLSearchParams(n.slice(r+1)))p.has(e.toLowerCase())||i.append(e,g.test(t)?_(t):t);let a=i.toString();return a?`${n.slice(0,r)}?${a}`:n.slice(0,r)}var v=/[^\s"'<>]+/g,y=/https?:\/\/./i;function b(e){let t=e.search(y),n=e.indexOf(`/`),r=n!==-1&&n<e.lastIndexOf(`?`)?n:-1,i=t===-1?r:r===-1?t:Math.min(t,r);return i===-1?e:e.slice(0,i)+_(e.slice(i))}function x(e){return e.replace(v,e=>b(e))}function S(e){for(let t of[e.baseData,e.baseData?.properties,e.data])if(t){for(let e of m)typeof t[e]==`string`&&(t[e]=_(t[e]));for(let e of h)typeof t[e]==`string`&&(t[e]=x(t[e]))}}function C(e){e.data=e.data??{};for(let[t,n]of o)n===null?delete e.data[t]:e.data[t]=n}function w(e){window.history.state?.idx!=null&&e.trackPageView()}export{s as initAppInsights,u as keepFailedOrSlowDependency,x as scrubText,_ as scrubUrl};
1
+ import{setRemoteLogger as e}from"../logger/logger.js";import{ApplicationInsights as t,SeverityLevel as n}from"@microsoft/applicationinsights-web";var r=500,i=/^(?:(\d+)\.)?(\d+):(\d+):(\d+(?:\.\d+)?)$/,a={info:n.Information,warn:n.Warning,error:n.Error},o=/* @__PURE__ */ new Map;function s(n){if(n.connectionString===``||l())return null;let i;try{i=new URL(n.apiBaseUrl,window.location.href).hostname}catch{throw Error(`initAppInsights: apiBaseUrl must be a URL, absolute or relative to the page`)}let s=n.environment===``||n.environment===`Production`?n.cloudRole:`${n.cloudRole}-${n.environment.toLowerCase()}`,u=n.slowDependencyMs??r,f=new t({config:{connectionString:n.connectionString,extensions:n.extensions??[],enableAutoRouteTracking:!0,disableAjaxTracking:!1,autoTrackPageVisitTime:!1,enableCorsCorrelation:!0,enableRequestHeaderTracking:!1,enableResponseHeaderTracking:!1,correlationHeaderDomains:[i],disableCookiesUsage:!0,disablePageUnloadEvents:[`unload`]}});f.loadAppInsights(),f.addTelemetryInitializer(e=>{e.tags=e.tags??{},e.tags[`ai.cloud.role`]=s,e.tags[`ai.application.ver`]=n.version}),f.addTelemetryInitializer(w),f.addTelemetryInitializer(C),f.addTelemetryInitializer(e=>d(e,u)),f.addDependencyInitializer(e=>p(e,i));for(let e of n.initializers??[])f.addTelemetryInitializer(e);return T(f),e(c([{log:(e,t)=>{e!==`debug`&&f.trackTrace({message:t,severityLevel:a[e]})},recordError:(e,t)=>{f.trackException({exception:e instanceof Error?e:Error(String(e))},t)},setUser:e=>{typeof e==`string`?f.setAuthenticatedUserContext(e):f.clearAuthenticatedUserContext()},setAttribute:(e,t)=>{o.set(e,t)}},...n.sinks??[]])),f}function c(e){let t=t=>{for(let n of e)try{t(n)}catch{}};return{breadcrumb:(e,n)=>t(t=>t.breadcrumb?.(e,n)),recordError:(e,n)=>t(t=>t.recordError?.(e,n)),setUser:(e,n)=>t(t=>t.setUser?.(e,n)),setAttribute:(e,n)=>t(t=>t.setAttribute?.(e,n)),log:(e,n,r)=>t(t=>t.log?.(e,n,r))}}function l(){let e=globalThis,t=`process`in e?e.process:void 0,n=typeof t==`object`&&t&&`env`in t?t.env:void 0;return typeof n==`object`&&!!n&&`VITEST`in n&&!!n.VITEST}function u(e){if(typeof e==`number`)return e;let t=typeof e==`string`?i.exec(e):null;if(!t)return;let[,n=`0`,r,a,o]=t;return(((Number(n)*24+Number(r))*60+Number(a))*60+Number(o))*1e3}function d(e,t=r){if(e.baseType===`MetricData`)return!1;if(e.baseType!==`RemoteDependencyData`||e.baseData?.success!==!0)return!0;let n=u(e.baseData.duration);return n===void 0||n>=t}function f(e){if(typeof e!=`string`||e===``)return``;try{return new URL(e.includes(`://`)?e:`https://${e}`).hostname}catch{return``}}function p({item:e},t){let n=Number(e?.responseCode);return n>0&&n<400?f(e.target)!==t:!0}var m=/* @__PURE__ */ new Set([`token`,`code`,`email`,`access_token`,`id_token`,`state`,`session_state`,`password`,`search`,`q`,`query`]),h=[`uri`,`refUri`,`url`],g=[`name`,`data`,`message`],_=/^(\/|https?:\/\/)/i;function v(e){if(typeof e!=`string`||e===``)return e;let t=e.indexOf(`#`),n=t===-1?e:e.slice(0,t),r=n.indexOf(`?`);if(r===-1)return n;let i=new URLSearchParams;for(let[e,t]of new URLSearchParams(n.slice(r+1)))m.has(e.toLowerCase())||i.append(e,_.test(t)?v(t):t);let a=i.toString();return a?`${n.slice(0,r)}?${a}`:n.slice(0,r)}var y=/[^\s"'<>]+/g,b=/https?:\/\/./i;function x(e){let t=e.search(b),n=e.indexOf(`/`),r=n!==-1&&n<e.lastIndexOf(`?`)?n:-1,i=t===-1?r:r===-1?t:Math.min(t,r);return i===-1?e:e.slice(0,i)+v(e.slice(i))}function S(e){return e.replace(y,e=>x(e))}function C(e){for(let t of[e.baseData,e.baseData?.properties,e.data])if(t){for(let e of h)typeof t[e]==`string`&&(t[e]=v(t[e]));for(let e of g)typeof t[e]==`string`&&(t[e]=S(t[e]))}}function w(e){e.data=e.data??{};for(let[t,n]of o)n===null?delete e.data[t]:e.data[t]=n}function T(e){window.history.state?.idx!=null&&e.trackPageView()}export{s as initAppInsights,d as keepFailedOrSlowDependency,S as scrubText,v as scrubUrl};
@@ -1,2 +1,2 @@
1
1
  import{isOfflineFailure as e}from"./requestPlatform.js";var t=`Something went wrong on our side. Please try again in a moment.`,n=`You appear to be offline. Check your connection and try again.`,r=`We couldn't reach the server. Check your connection and try again.`,i=`That took too long to respond. Check your connection and try again.`,a=`Something went wrong. Please try again.`,o=`request_canceled`,s=`contract_error`,c=`timeout`,l=`network`,u=`offline`,d=300,f=`internal_error`,p=e=>`Request failed (${e})`,m={401:{code:`unauthorized`,sentence:`Please sign in to continue.`},403:{code:`forbidden`,sentence:`You do not have access to this.`}},h=e=>typeof e==`object`&&!!e&&!Array.isArray(e),g=e=>typeof e==`string`&&e.trim().length>0?e:null,_=(e,t)=>{let n=m[e];if(n===void 0||t===null||t.code!==n.code)return null;let r=g(t.detail);return r===null||r===n.sentence?n.sentence:null},v=e=>e.length>d||/^\s*</.test(e)||e.includes(`
2
- at `)||/(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),y=e=>{let t=g(e);return t!==null&&!v(t)?t:null},b=e=>e.replace(/^\$\.?/,``).split(`.`).map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(`.`),x=e=>{if(Array.isArray(e)){for(let t of e){let e=g(t);if(e!==null)return e}return null}return g(e)},S=(e,t,n)=>{let r=b(t);r===``?e.form??=n:r in e.fields||(e.fields[r]=n)},C=e=>{let t={fields:{},form:null};if(Array.isArray(e)){for(let n of e){if(!h(n))continue;let e=g(n.message);e!==null&&S(t,typeof n.field==`string`?n.field:``,e)}return t}if(!h(e))return t;for(let[n,r]of Object.entries(e)){let e=x(r);e!==null&&S(t,n,e)}return t},w=e=>h(e)&&typeof e.message==`string`&&typeof e.status==`number`&&typeof e.offline==`boolean`&&h(e.fieldErrors),T=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),E=e=>{let t=h(e.config)?e.config.headers:void 0;if(!h(t))return null;let n=typeof t.get==`function`?t.get(`traceparent`):t.traceparent??t.Traceparent;return(typeof n==`string`?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null)?.[1]??null},D=t=>{let s=g(t.code),d=g(t.name),f=g(t.message),p=E(t);return d===`CanceledError`||s===`ERR_CANCELED`?T({code:o,message:a,traceId:p,diagnostic:f}):s===`ECONNABORTED`||s===`ETIMEDOUT`?T({code:c,message:i,offline:!0,traceId:p,diagnostic:f}):d===`RequestOfflineError`||s===`ERR_NETWORK`||f===`Network Error`||f===`Network request failed`?e(t)?T({code:u,message:n,offline:!0,traceId:p,diagnostic:f}):T({code:l,message:r,offline:!0,traceId:p,diagnostic:f}):T({message:a,traceId:p,diagnostic:f})};function O(e){if(w(e))return e;if(typeof e==`string`)return T({message:y(e)??`Something went wrong. Please try again.`,diagnostic:e||null});if(!h(e))return T({message:a,diagnostic:e==null?null:String(e)});if(e.isContractError===!0)return T({code:s,message:y(e.message)??`Something went wrong. Please try again.`,diagnostic:g(e.message)});let t=h(e.response)?e.response:null,n=typeof t?.status==`number`?t.status:typeof e.status==`number`?e.status:0,r=t?t.data:e.body;if(n===0&&r==null)return D(e);let i=h(r)?r:null,{fields:o,form:c}=C(i?.errors),l=g(i?.code),u=g(i?.traceId)??E(e),d=g(i?.detail)??g(i?.title)??g(r)??g(e.message),m;return m=n>=500?(l!==null&&l!==f?y(i?.detail):null)??`Something went wrong on our side. Please try again in a moment.`:_(n,i)??y(Object.values(o)[0])??y(c)??y(i?.detail)??y(i?.title)??y(r)??(n?p(n):`Something went wrong. Please try again.`),T({code:l,message:m,fieldErrors:o,status:n,traceId:u,diagnostic:d})}var k=e=>O(e).offline;function A(e,t){let n=O(e);return n.offline||t!==null&&!t||n.status>=500&&n.message!==`Something went wrong on our side. Please try again in a moment.`?n.message:n.status>=500||n.code===`request_canceled`||n.message===`Something went wrong. Please try again.`||n.message===p(n.status)?t??null:n.message}export{s as CONTRACT_ERROR_CODE,l as NETWORK_CODE,u as OFFLINE_CODE,n as OFFLINE_MESSAGE,o as REQUEST_CANCELED_CODE,t as SERVER_FAILURE_MESSAGE,c as TIMEOUT_CODE,i as TIMEOUT_MESSAGE,a as UNEXPECTED_MESSAGE,r as UNREACHABLE_MESSAGE,A as apiErrorMessage,O as extractApiError,w as isApiError,k as isNoResponse,b as toFieldPath};
2
+ at `)||/(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),y=e=>{let t=g(e);return t!==null&&!v(t)?t:null},b=e=>e.replace(/^\$\.?/,``).split(`.`).map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(`.`),x=e=>{if(Array.isArray(e)){for(let t of e){let e=g(t);if(e!==null)return e}return null}return g(e)},S=(e,t,n)=>{let r=b(t);r===``?e.form??=n:r in e.fields||(e.fields[r]=n)},C=e=>{let t={fields:{},form:null};if(Array.isArray(e)){for(let n of e){if(!h(n))continue;let e=g(n.message);e!==null&&S(t,typeof n.field==`string`?n.field:``,e)}return t}if(!h(e))return t;for(let[n,r]of Object.entries(e)){let e=x(r);e!==null&&S(t,n,e)}return t},w=e=>h(e)&&typeof e.message==`string`&&typeof e.status==`number`&&typeof e.offline==`boolean`&&h(e.fieldErrors),T=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),E=e=>{let t=h(e.config)?e.config.headers:void 0;if(!h(t))return null;let n=typeof t.get==`function`?t.get(`traceparent`):t.traceparent??t.Traceparent;return(typeof n==`string`?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null)?.[1]??null},D=t=>{let s=g(t.code),d=g(t.name),f=g(t.message),p=E(t);return d===`CanceledError`||s===`ERR_CANCELED`?T({code:o,message:a,traceId:p,diagnostic:f}):s===`ECONNABORTED`||s===`ETIMEDOUT`?T({code:c,message:i,offline:!0,traceId:p,diagnostic:f}):d===`RequestOfflineError`||s===`ERR_NETWORK`||f===`Network Error`||f===`Network request failed`?e(t)?T({code:u,message:n,offline:!0,traceId:p,diagnostic:f}):T({code:l,message:r,offline:!0,traceId:p,diagnostic:f}):T({message:a,traceId:p,diagnostic:f})};function O(e){if(w(e))return e;if(typeof e==`string`)return T({message:y(e)??`Something went wrong. Please try again.`,diagnostic:e||null});if(!h(e))return T({message:a,diagnostic:e==null?null:String(e)});if(e.isContractError===!0)return T({code:s,message:y(e.message)??`Something went wrong. Please try again.`,diagnostic:g(e.message)});let t=h(e.response)?e.response:null,n=typeof t?.status==`number`?t.status:typeof e.status==`number`?e.status:0,r=t?t.data:e.body;if(n===0&&r==null)return D(e);let i=h(r)?r:null,{fields:o,form:c}=C(i?.errors),l=g(i?.code),u=g(i?.traceId)??E(e),d=g(i?.detail)??g(i?.title)??g(r)??g(e.message),m;m=n>=500?(l!==null&&l!==f?y(i?.detail):null)??`Something went wrong on our side. Please try again in a moment.`:_(n,i)??y(Object.values(o)[0])??y(c)??y(i?.detail)??y(i?.title)??y(r)??(n?p(n):`Something went wrong. Please try again.`);let v=h(e.config)?e.config:null,b=v===null?null:g(v.url),x=v!==null&&`_accountId`in v?g(v._accountId):null;return T({code:l,message:m,fieldErrors:o,status:n,traceId:u,diagnostic:d,...b===null?{}:{requestUrl:b},...x===null?{}:{accountId:x}})}var k=e=>O(e).offline;function A(e,t){let n=O(e);return n.offline||t!==null&&!t||n.status>=500&&n.message!==`Something went wrong on our side. Please try again in a moment.`?n.message:n.status>=500||n.code===`request_canceled`||n.message===`Something went wrong. Please try again.`||n.message===p(n.status)?t??null:n.message}export{s as CONTRACT_ERROR_CODE,l as NETWORK_CODE,u as OFFLINE_CODE,n as OFFLINE_MESSAGE,o as REQUEST_CANCELED_CODE,t as SERVER_FAILURE_MESSAGE,c as TIMEOUT_CODE,i as TIMEOUT_MESSAGE,a as UNEXPECTED_MESSAGE,r as UNREACHABLE_MESSAGE,A as apiErrorMessage,O as extractApiError,w as isApiError,k as isNoResponse,b as toFieldPath};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_BUILD_CHECK_INTERVAL_MS as e,DEFAULT_LOG_LEVEL as t,DEFAULT_RETRIES as n,DEFAULT_TIMEOUT_MS as r,DEFAULT_VERSION_URL as i,getConfig as a,getConfigValue as o,resetConfig as s,setConfig as c}from"./config/index.js";import{TRACEPARENT_HEADER as l,applyRequestDefaults as u,newTraceparent as d}from"./api/requestDefaults.js";import{Logger as f,configureLogger as p,getDeviceContext as m,setDeviceContext as h,setRemoteLogger as g}from"./logger/logger.js";import{decodeJWT as _,getJWTExpiry as v,isJWTExpired as y}from"./auth/jwt.js";import{ACCESS_TOKEN_KEY as b,LEGACY_REFRESH_TOKEN_LIFETIME_MS as x,REFRESH_TOKEN_KEY as S,SESSION_USER_KEY as C,addSessionEndedListener as w,clearSession as T,getKeepSignedIn as E,getSessionUser as D,getToken as O,hasSession as k,hasSessionEndedInTab as A,removeSessionUser as j,removeToken as M,setKeepSignedIn as N,setLegacyTokenKeys as P,storeSessionUser as F,storeToken as I}from"./auth/authStore.js";import{addNetworkStatusListener as L,getNetworkStatus as R,setNetworkStatusImplementation as z,useNetworkStatus as B}from"./network/networkStatus.js";import{ACCOUNT_ID_HEADER as V,CLIENT_BUILD_HEADER as H,CLIENT_KIND as U,CLIENT_KIND_HEADER as W,getClientBuild as G}from"./api/clientHeaders.js";import{initWebority as K}from"./initSDK.js";import{DESIGN_SAMPLE_HEADER as q,DESIGN_SAMPLE_QUERY_KEY as J,DESIGN_SAMPLE_STORAGE_KEY as Y,applyDesignSample as X,readDesignSampleTicket as Z}from"./api/designSample.js";import{MIN_APP_VERSION_HEADER as Q,addMinAppVersionListener as $,getMinAppVersion as ee}from"./api/minAppVersion.js";import{WORKSPACE_CHANGED_CODE as te,WorkspaceChangedError as ne,isWorkspaceChangedError as re}from"./api/workspaceChanged.js";import{IDEMPOTENCY_KEY_HEADER as ie,attachRetry as ae,isNeverSentError as oe,isRetryableFailure as se,isRetryableStatus as ce,retryAfterMs as le}from"./api/retry.js";import{REFRESH_LOCK_NAME as ue,withCrossTabRefreshLock as de}from"./api/crossTabRefreshLock.js";import fe from"./api/publicClient.js";import{SESSION_EXPIRED_CODE as pe,SESSION_REVOKED_CODE as me,injectStore as he,injectUserAuth as ge,refreshAccessToken as _e,resetRefreshState as ve}from"./api/tokenRefresh.js";import ye,{RequestOfflineError as be}from"./api/userClient.js";import{initUserAuth as xe}from"./initUserAuth.js";import{readBlobErrorBody as Se}from"./api/blobErrorBody.js";import{createContractCaller as Ce}from"./api/contractCaller.js";import{CONTRACT_ERROR_CODE as we,NETWORK_CODE as Te,OFFLINE_CODE as Ee,OFFLINE_MESSAGE as De,REQUEST_CANCELED_CODE as Oe,SERVER_FAILURE_MESSAGE as ke,TIMEOUT_CODE as Ae,TIMEOUT_MESSAGE as je,UNEXPECTED_MESSAGE as Me,UNREACHABLE_MESSAGE as Ne,apiErrorMessage as Pe,extractApiError as Fe,isApiError as Ie,isNoResponse as Le,toFieldPath as Re}from"./errors/extractApiError.js";import{parseResponse as ze}from"./errors/parseResponse.js";import{contentDispositionFileName as Be,downloadFile as Ve}from"./api/downloadFile.js";import{configureFormatters as He,getFormatterConfig as Ue}from"./formatters/formatConfig.js";import{formatCurrency as We}from"./formatters/currency.js";import{addDays as Ge}from"./formatters/dateMath.js";import{formatDate as Ke,formatDateTime as qe,formatMinor as Je,formatNumber as Ye,formatPercent as Xe,formatRelative as Ze,formatTime as Qe}from"./formatters/house.js";import{staticUrl as $e}from"./static/index.js";import{createApiBaseQuery as et}from"./query/apiBaseQuery.js";import{APP_API_DEFAULTS as tt,createAppApi as nt}from"./query/createAppApi.js";import{useDataState as rt}from"./query/dataState.js";import{setupApiListeners as it}from"./query/listeners.js";import{LIST_QUERY_RESERVED as at,SEARCH_PARAM as ot,buildListQuery as st,emptyFacetValue as ct,isFacetActive as lt,listQueryParamNames as ut,parseListQuery as dt}from"./query/listQuery.js";import{getNextPageParam as ft,getPreviousPageParam as pt,hasNextPage as mt,hasPreviousPage as ht}from"./query/paging.js";import{LIST_TAG_ID as gt,itemTag as _t,listTag as vt,providesList as yt,providesPagedList as bt}from"./query/tags.js";import{useListQuery as xt}from"./query/useListQuery.js";import{errorToastMiddleware as St,isSilentRejection as Ct}from"./redux/errorToastMiddleware.js";import{createRootReducer as wt,resetState as Tt}from"./redux/rootReducer.js";import{SERIALIZABLE_IGNORED_ACTION_PATHS as Et}from"./redux/serializableCheck.js";import{hasRecentlyReloaded as Dt,importWithReload as Ot,isChunkLoadError as kt,lazyWithReload as At,markReloaded as jt}from"./router/chunkReload.js";import{classifyRouteError as Mt,useRouteErrorReport as Nt}from"./router/routeError.js";import{ErrorBoundary as Pt}from"./router/ErrorBoundary.js";import{hasPermission as Ft}from"./router/permissions.js";import{RETURN_TO_PARAM as It,buildLoginPath as Lt,getReturnTo as Rt,toSafeReturnTo as zt}from"./router/returnTo.js";import{PublicOnly as Bt,RequireAuth as Vt,RequirePermission as Ht}from"./router/guards.js";import{publicOnly as Ut,requireAuth as Wt,requirePermission as Gt,withGuards as Kt}from"./router/loaders.js";import{defineRouteTable as qt}from"./router/routeTable.js";import{Storage as Jt,isStorageAvailable as Yt,setStorageImplementation as Xt,syncSessionStorage as Zt,syncStorage as Qt}from"./storage/index.js";import{isBuildBelowMinimum as $t,parseBuildNumber as en}from"./versionCheck/buildNumber.js";import{addDeployedBuildListener as tn,getNewerDeployedBuild as nn,startDeployedBuildCheck as rn}from"./versionCheck/deployedBuild.js";import{installReloadOnNavigate as an,isUpdateAvailable as on,useVersionCheck as sn}from"./versionCheck/index.js";export{b as ACCESS_TOKEN_KEY,V as ACCOUNT_ID_HEADER,tt as APP_API_DEFAULTS,H as CLIENT_BUILD_HEADER,U as CLIENT_KIND,W as CLIENT_KIND_HEADER,we as CONTRACT_ERROR_CODE,e as DEFAULT_BUILD_CHECK_INTERVAL_MS,t as DEFAULT_LOG_LEVEL,n as DEFAULT_RETRIES,r as DEFAULT_TIMEOUT_MS,i as DEFAULT_VERSION_URL,q as DESIGN_SAMPLE_HEADER,J as DESIGN_SAMPLE_QUERY_KEY,Y as DESIGN_SAMPLE_STORAGE_KEY,Pt as ErrorBoundary,ie as IDEMPOTENCY_KEY_HEADER,x as LEGACY_REFRESH_TOKEN_LIFETIME_MS,at as LIST_QUERY_RESERVED,gt as LIST_TAG_ID,f as Logger,Q as MIN_APP_VERSION_HEADER,Te as NETWORK_CODE,Ee as OFFLINE_CODE,De as OFFLINE_MESSAGE,Bt as PublicOnly,ue as REFRESH_LOCK_NAME,S as REFRESH_TOKEN_KEY,Oe as REQUEST_CANCELED_CODE,It as RETURN_TO_PARAM,be as RequestOfflineError,Vt as RequireAuth,Ht as RequirePermission,ot as SEARCH_PARAM,Et as SERIALIZABLE_IGNORED_ACTION_PATHS,ke as SERVER_FAILURE_MESSAGE,pe as SESSION_EXPIRED_CODE,me as SESSION_REVOKED_CODE,C as SESSION_USER_KEY,Jt as Storage,Ae as TIMEOUT_CODE,je as TIMEOUT_MESSAGE,l as TRACEPARENT_HEADER,Me as UNEXPECTED_MESSAGE,Ne as UNREACHABLE_MESSAGE,te as WORKSPACE_CHANGED_CODE,ne as WorkspaceChangedError,Ge as addDays,tn as addDeployedBuildListener,$ as addMinAppVersionListener,L as addNetworkStatusListener,w as addSessionEndedListener,Pe as apiErrorMessage,X as applyDesignSample,u as applyRequestDefaults,ae as attachRetry,st as buildListQuery,Lt as buildLoginPath,Mt as classifyRouteError,T as clearSession,He as configureFormatters,p as configureLogger,Be as contentDispositionFileName,et as createApiBaseQuery,nt as createAppApi,Ce as createContractCaller,wt as createRootReducer,_ as decodeJWT,qt as defineRouteTable,Ve as downloadFile,ct as emptyFacetValue,St as errorToastMiddleware,Fe as extractApiError,We as formatCurrency,Ke as formatDate,qe as formatDateTime,Je as formatMinor,Ye as formatNumber,Xe as formatPercent,Ze as formatRelative,Qe as formatTime,G as getClientBuild,a as getConfig,o as getConfigValue,m as getDeviceContext,Ue as getFormatterConfig,v as getJWTExpiry,E as getKeepSignedIn,ee as getMinAppVersion,R as getNetworkStatus,nn as getNewerDeployedBuild,ft as getNextPageParam,pt as getPreviousPageParam,Rt as getReturnTo,D as getSessionUser,O as getToken,mt as hasNextPage,Ft as hasPermission,ht as hasPreviousPage,Dt as hasRecentlyReloaded,k as hasSession,A as hasSessionEndedInTab,Ot as importWithReload,xe as initUserAuth,K as initWebority,he as injectStore,ge as injectUserAuth,an as installReloadOnNavigate,Ie as isApiError,$t as isBuildBelowMinimum,kt as isChunkLoadError,lt as isFacetActive,y as isJWTExpired,oe as isNeverSentError,Le as isNoResponse,se as isRetryableFailure,ce as isRetryableStatus,Ct as isSilentRejection,Yt as isStorageAvailable,on as isUpdateAvailable,re as isWorkspaceChangedError,_t as itemTag,At as lazyWithReload,ut as listQueryParamNames,vt as listTag,jt as markReloaded,d as newTraceparent,en as parseBuildNumber,dt as parseListQuery,ze as parseResponse,yt as providesList,bt as providesPagedList,fe as publicClient,Ut as publicOnly,Se as readBlobErrorBody,Z as readDesignSampleTicket,_e as refreshAccessToken,j as removeSessionUser,M as removeToken,Wt as requireAuth,Gt as requirePermission,s as resetConfig,ve as resetRefreshState,Tt as resetState,le as retryAfterMs,c as setConfig,h as setDeviceContext,N as setKeepSignedIn,P as setLegacyTokenKeys,z as setNetworkStatusImplementation,g as setRemoteLogger,Xt as setStorageImplementation,it as setupApiListeners,rn as startDeployedBuildCheck,$e as staticUrl,F as storeSessionUser,I as storeToken,Zt as syncSessionStorage,Qt as syncStorage,Re as toFieldPath,zt as toSafeReturnTo,rt as useDataState,xt as useListQuery,B as useNetworkStatus,Nt as useRouteErrorReport,sn as useVersionCheck,ye as userClient,de as withCrossTabRefreshLock,Kt as withGuards};
1
+ import{DEFAULT_BUILD_CHECK_INTERVAL_MS as e,DEFAULT_LOG_LEVEL as t,DEFAULT_RETRIES as n,DEFAULT_TIMEOUT_MS as r,DEFAULT_VERSION_URL as i,getConfig as a,getConfigValue as o,resetConfig as s,setConfig as c}from"./config/index.js";import{TRACEPARENT_HEADER as l,applyRequestDefaults as u,newTraceparent as d}from"./api/requestDefaults.js";import{Logger as f,configureLogger as p,getDeviceContext as m,setDeviceContext as h,setRemoteLogger as g}from"./logger/logger.js";import{decodeJWT as _,getJWTExpiry as v,isJWTExpired as y}from"./auth/jwt.js";import{ACCESS_TOKEN_KEY as b,LEGACY_REFRESH_TOKEN_LIFETIME_MS as x,REFRESH_TOKEN_KEY as S,SESSION_USER_KEY as C,addSessionEndedListener as w,clearSession as T,getKeepSignedIn as E,getSessionUser as D,getToken as O,hasSession as k,hasSessionEndedInTab as A,removeSessionUser as j,removeToken as M,setKeepSignedIn as N,setLegacyTokenKeys as P,storeSessionUser as F,storeToken as I}from"./auth/authStore.js";import{addNetworkStatusListener as L,getNetworkStatus as R,setNetworkStatusImplementation as z,useNetworkStatus as B}from"./network/networkStatus.js";import{ACCOUNT_ID_HEADER as V,CLIENT_BUILD_HEADER as H,CLIENT_KIND as U,CLIENT_KIND_HEADER as W,getClientBuild as G}from"./api/clientHeaders.js";import{initWebority as K}from"./initSDK.js";import{DESIGN_SAMPLE_HEADER as q,DESIGN_SAMPLE_QUERY_KEY as J,DESIGN_SAMPLE_STORAGE_KEY as Y,applyDesignSample as X,readDesignSampleTicket as Z}from"./api/designSample.js";import{MIN_APP_VERSION_HEADER as Q,addMinAppVersionListener as $,getMinAppVersion as ee}from"./api/minAppVersion.js";import{WORKSPACE_CHANGED_CODE as te,WorkspaceChangedError as ne,isWorkspaceChangedError as re}from"./api/workspaceChanged.js";import{IDEMPOTENCY_KEY_HEADER as ie,attachRetry as ae,isNeverSentError as oe,isRetryableFailure as se,isRetryableStatus as ce,retryAfterMs as le}from"./api/retry.js";import{REFRESH_LOCK_NAME as ue,withCrossTabRefreshLock as de}from"./api/crossTabRefreshLock.js";import fe from"./api/publicClient.js";import{SESSION_EXPIRED_CODE as pe,SESSION_REVOKED_CODE as me,injectStore as he,injectUserAuth as ge,refreshAccessToken as _e,resetRefreshState as ve}from"./api/tokenRefresh.js";import ye,{RequestOfflineError as be}from"./api/userClient.js";import{initUserAuth as xe}from"./initUserAuth.js";import{readBlobErrorBody as Se}from"./api/blobErrorBody.js";import{createContractCaller as Ce}from"./api/contractCaller.js";import{CONTRACT_ERROR_CODE as we,NETWORK_CODE as Te,OFFLINE_CODE as Ee,OFFLINE_MESSAGE as De,REQUEST_CANCELED_CODE as Oe,SERVER_FAILURE_MESSAGE as ke,TIMEOUT_CODE as Ae,TIMEOUT_MESSAGE as je,UNEXPECTED_MESSAGE as Me,UNREACHABLE_MESSAGE as Ne,apiErrorMessage as Pe,extractApiError as Fe,isApiError as Ie,isNoResponse as Le,toFieldPath as Re}from"./errors/extractApiError.js";import{parseResponse as ze}from"./errors/parseResponse.js";import{contentDispositionFileName as Be,downloadFile as Ve}from"./api/downloadFile.js";import{newIdempotencyKey as He}from"./api/idempotencyKey.js";import{configureFormatters as Ue,getFormatterConfig as We}from"./formatters/formatConfig.js";import{formatCurrency as Ge}from"./formatters/currency.js";import{addDays as Ke}from"./formatters/dateMath.js";import{formatDate as qe,formatDateTime as Je,formatMinor as Ye,formatNumber as Xe,formatPercent as Ze,formatRelative as Qe,formatTime as $e}from"./formatters/house.js";import{staticUrl as et}from"./static/index.js";import{createApiBaseQuery as tt}from"./query/apiBaseQuery.js";import{APP_API_DEFAULTS as nt,createAppApi as rt}from"./query/createAppApi.js";import{useDataState as it,useInfiniteDataState as at}from"./query/dataState.js";import{entityTagOf as ot,saveWithVersion as st,versionOf as ct,withIfMatch as lt}from"./query/entityVersion.js";import{setupApiListeners as ut}from"./query/listeners.js";import{LIST_QUERY_RESERVED as dt,SEARCH_PARAM as ft,buildListQuery as pt,emptyFacetValue as mt,isFacetActive as ht,listQueryParamNames as gt,parseListQuery as _t}from"./query/listQuery.js";import{getNextPageParam as vt,getPreviousPageParam as yt,hasNextPage as bt,hasPreviousPage as xt}from"./query/paging.js";import{LIST_TAG_ID as St,itemTag as Ct,listTag as wt,providesList as Tt,providesPagedList as Et}from"./query/tags.js";import{useListQuery as Dt}from"./query/useListQuery.js";import{errorToastMiddleware as Ot,isSilentRejection as kt}from"./redux/errorToastMiddleware.js";import{createRootReducer as At,resetState as jt}from"./redux/rootReducer.js";import{SERIALIZABLE_IGNORED_ACTION_PATHS as Mt}from"./redux/serializableCheck.js";import{hasRecentlyReloaded as Nt,importWithReload as Pt,isChunkLoadError as Ft,lazyWithReload as It,markReloaded as Lt}from"./router/chunkReload.js";import{classifyRouteError as Rt,useRouteErrorReport as zt}from"./router/routeError.js";import{ErrorBoundary as Bt}from"./router/ErrorBoundary.js";import{hasPermission as Vt}from"./router/permissions.js";import{RETURN_TO_PARAM as Ht,buildLoginPath as Ut,getReturnTo as Wt,toSafeReturnTo as Gt}from"./router/returnTo.js";import{PublicOnly as Kt,RequireAuth as qt,RequirePermission as Jt}from"./router/guards.js";import{publicOnly as Yt,requireAuth as Xt,requirePermission as Zt,withGuards as Qt}from"./router/loaders.js";import{defineRouteTable as $t}from"./router/routeTable.js";import{Storage as en,isStorageAvailable as tn,setStorageImplementation as nn,syncSessionStorage as rn,syncStorage as an}from"./storage/index.js";import{isBuildBelowMinimum as on,parseBuildNumber as sn}from"./versionCheck/buildNumber.js";import{addDeployedBuildListener as cn,getNewerDeployedBuild as ln,startDeployedBuildCheck as un}from"./versionCheck/deployedBuild.js";import{installReloadOnNavigate as dn,isUpdateAvailable as fn,useVersionCheck as pn}from"./versionCheck/index.js";export{b as ACCESS_TOKEN_KEY,V as ACCOUNT_ID_HEADER,nt as APP_API_DEFAULTS,H as CLIENT_BUILD_HEADER,U as CLIENT_KIND,W as CLIENT_KIND_HEADER,we as CONTRACT_ERROR_CODE,e as DEFAULT_BUILD_CHECK_INTERVAL_MS,t as DEFAULT_LOG_LEVEL,n as DEFAULT_RETRIES,r as DEFAULT_TIMEOUT_MS,i as DEFAULT_VERSION_URL,q as DESIGN_SAMPLE_HEADER,J as DESIGN_SAMPLE_QUERY_KEY,Y as DESIGN_SAMPLE_STORAGE_KEY,Bt as ErrorBoundary,ie as IDEMPOTENCY_KEY_HEADER,x as LEGACY_REFRESH_TOKEN_LIFETIME_MS,dt as LIST_QUERY_RESERVED,St as LIST_TAG_ID,f as Logger,Q as MIN_APP_VERSION_HEADER,Te as NETWORK_CODE,Ee as OFFLINE_CODE,De as OFFLINE_MESSAGE,Kt as PublicOnly,ue as REFRESH_LOCK_NAME,S as REFRESH_TOKEN_KEY,Oe as REQUEST_CANCELED_CODE,Ht as RETURN_TO_PARAM,be as RequestOfflineError,qt as RequireAuth,Jt as RequirePermission,ft as SEARCH_PARAM,Mt as SERIALIZABLE_IGNORED_ACTION_PATHS,ke as SERVER_FAILURE_MESSAGE,pe as SESSION_EXPIRED_CODE,me as SESSION_REVOKED_CODE,C as SESSION_USER_KEY,en as Storage,Ae as TIMEOUT_CODE,je as TIMEOUT_MESSAGE,l as TRACEPARENT_HEADER,Me as UNEXPECTED_MESSAGE,Ne as UNREACHABLE_MESSAGE,te as WORKSPACE_CHANGED_CODE,ne as WorkspaceChangedError,Ke as addDays,cn as addDeployedBuildListener,$ as addMinAppVersionListener,L as addNetworkStatusListener,w as addSessionEndedListener,Pe as apiErrorMessage,X as applyDesignSample,u as applyRequestDefaults,ae as attachRetry,pt as buildListQuery,Ut as buildLoginPath,Rt as classifyRouteError,T as clearSession,Ue as configureFormatters,p as configureLogger,Be as contentDispositionFileName,tt as createApiBaseQuery,rt as createAppApi,Ce as createContractCaller,At as createRootReducer,_ as decodeJWT,$t as defineRouteTable,Ve as downloadFile,mt as emptyFacetValue,ot as entityTagOf,Ot as errorToastMiddleware,Fe as extractApiError,Ge as formatCurrency,qe as formatDate,Je as formatDateTime,Ye as formatMinor,Xe as formatNumber,Ze as formatPercent,Qe as formatRelative,$e as formatTime,G as getClientBuild,a as getConfig,o as getConfigValue,m as getDeviceContext,We as getFormatterConfig,v as getJWTExpiry,E as getKeepSignedIn,ee as getMinAppVersion,R as getNetworkStatus,ln as getNewerDeployedBuild,vt as getNextPageParam,yt as getPreviousPageParam,Wt as getReturnTo,D as getSessionUser,O as getToken,bt as hasNextPage,Vt as hasPermission,xt as hasPreviousPage,Nt as hasRecentlyReloaded,k as hasSession,A as hasSessionEndedInTab,Pt as importWithReload,xe as initUserAuth,K as initWebority,he as injectStore,ge as injectUserAuth,dn as installReloadOnNavigate,Ie as isApiError,on as isBuildBelowMinimum,Ft as isChunkLoadError,ht as isFacetActive,y as isJWTExpired,oe as isNeverSentError,Le as isNoResponse,se as isRetryableFailure,ce as isRetryableStatus,kt as isSilentRejection,tn as isStorageAvailable,fn as isUpdateAvailable,re as isWorkspaceChangedError,Ct as itemTag,It as lazyWithReload,gt as listQueryParamNames,wt as listTag,Lt as markReloaded,He as newIdempotencyKey,d as newTraceparent,sn as parseBuildNumber,_t as parseListQuery,ze as parseResponse,Tt as providesList,Et as providesPagedList,fe as publicClient,Yt as publicOnly,Se as readBlobErrorBody,Z as readDesignSampleTicket,_e as refreshAccessToken,j as removeSessionUser,M as removeToken,Xt as requireAuth,Zt as requirePermission,s as resetConfig,ve as resetRefreshState,jt as resetState,le as retryAfterMs,st as saveWithVersion,c as setConfig,h as setDeviceContext,N as setKeepSignedIn,P as setLegacyTokenKeys,z as setNetworkStatusImplementation,g as setRemoteLogger,nn as setStorageImplementation,ut as setupApiListeners,un as startDeployedBuildCheck,et as staticUrl,F as storeSessionUser,I as storeToken,rn as syncSessionStorage,an as syncStorage,Re as toFieldPath,Gt as toSafeReturnTo,it as useDataState,at as useInfiniteDataState,Dt as useListQuery,B as useNetworkStatus,zt as useRouteErrorReport,pn as useVersionCheck,ye as userClient,ct as versionOf,de as withCrossTabRefreshLock,Qt as withGuards,lt as withIfMatch};
@@ -1 +1 @@
1
- import{extractApiError as e}from"../errors/extractApiError.js";import{Logger as t}from"../logger/logger.js";import n from"axios";var r=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e)),i=e=>t=>{let n=[];for(let[i,a]of Object.entries(t)){if(a==null)continue;let t=encodeURIComponent(i);if(!Array.isArray(a))n.push(`${t}=${r(a)}`);else if(e===`comma`)n.push(`${t}=${a.map(r).join(`,`)}`);else{let i=e===`brackets`?`${t}[]`:t;for(let e of a)n.push(`${i}=${r(e)}`)}}return n.join(`&`)},a=({client:r,publicClient:a})=>async(o,{signal:s},c)=>{let l=typeof o==`string`?{url:o}:o,u=l.silent??c?.silent??!1,d=l.expectedStatuses??c?.expectedStatuses,f=l.paramsFormat??c?.paramsFormat,p=l.public?a:r;if(!p)throw Error(`createApiBaseQuery: "${l.url}" is marked public but no publicClient was passed.`);let m={url:l.url,method:l.method??`GET`,data:l.data,params:l.params,paramsSerializer:f?i(f):void 0,headers:l.headers,responseType:l.responseType,timeout:l.timeout,signal:s,skipErrorLog:!0};try{let e=await p.request(m);return{data:e.data,meta:{silent:u,status:e.status}}}catch(r){let i=e(r),a=n.isCancel(r);return a||t.requestFailed(r,{expectedStatuses:d}),{error:i,meta:{silent:u||a,status:i.status,...d&&{expectedStatuses:d}}}}};export{a as createApiBaseQuery};
1
+ import{extractApiError as e}from"../errors/extractApiError.js";import{Logger as t}from"../logger/logger.js";import n from"axios";var r=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e)),i=e=>{if(!(typeof e!=`string`||e.startsWith(`W/`)))return/^"([^"]*)"$/.exec(e)?.[1]},a=e=>`"${e}"`,o=e=>{let t={};if(e.ifMatch&&(t[`If-Match`]=a(e.ifMatch)),e.idempotencyKey&&(t[`Idempotency-Key`]=e.idempotencyKey),Object.keys(t).length===0)return e.headers;let n=Object.keys(t).map(e=>e.toLowerCase()),r=Object.entries(e.headers??{}).filter(([e])=>!n.includes(e.toLowerCase()));return{...Object.fromEntries(r),...t}},s=`precondition_failed`,c=e=>e.status===412?{...e,code:s}:e,l=e=>t=>{let n=[];for(let[i,a]of Object.entries(t)){if(a==null)continue;let t=encodeURIComponent(i);if(!Array.isArray(a))n.push(`${t}=${r(a)}`);else if(e===`comma`)n.push(`${t}=${a.map(r).join(`,`)}`);else{let i=e===`brackets`?`${t}[]`:t;for(let e of a)n.push(`${i}=${r(e)}`)}}return n.join(`&`)},u=({client:r,publicClient:a})=>async(s,{signal:u},d)=>{let f=typeof s==`string`?{url:s}:s,p=f.silent??d?.silent??!1,m=f.expectedStatuses??d?.expectedStatuses,h=f.paramsFormat??d?.paramsFormat,g=f.public?a:r;if(!g)throw Error(`createApiBaseQuery: "${f.url}" is marked public but no publicClient was passed.`);let _=o(f),v={url:f.url,method:f.method??`GET`,data:f.data,params:f.params,...h&&{paramsSerializer:l(h)},..._!==void 0&&{headers:_},...f.responseType!==void 0&&{responseType:f.responseType},...f.timeout!==void 0&&{timeout:f.timeout},signal:u,skipErrorLog:!0};try{let e=await g.request(v),t=i(e.headers.etag);return{data:e.data,meta:{silent:p,status:e.status,...t!==void 0&&{entityTag:t}}}}catch(r){let a=c(e(r)),o=n.isCancel(r);o||t.requestFailed(r,{...m&&{expectedStatuses:m}});let s=n.isAxiosError(r)?i(r.response?.headers.etag):void 0;return{error:a,meta:{silent:p||o,status:a.status,...m&&{expectedStatuses:m},...s!==void 0&&{entityTag:s}}}}};export{u as createApiBaseQuery,a as ifMatchValue,i as strongEntityTag};
@@ -1 +1 @@
1
- import{extractApiError as e}from"../errors/extractApiError.js";import{useMemo as t}from"react";function n(n,i){let{currentData:a,error:o,isFetching:s,refetch:c}=n,l=i?.isEmpty??r;return t(()=>{let t=()=>{c()};return a===void 0?o===void 0?{status:`loading`}:{status:`error`,error:e(o),retry:t}:l(a)?{status:`empty`,refreshing:s,refresh:t}:{status:`data`,data:a,refreshing:s,refresh:t}},[a,o,s,c,l])}var r=e=>Array.isArray(e)?e.length===0:typeof e==`object`&&e&&`items`in e&&Array.isArray(e.items)?e.items.length===0:!1;export{n as useDataState};
1
+ import{extractApiError as e}from"../errors/extractApiError.js";import{useMemo as t}from"react";function n(n,i){let{currentData:a,error:o,isFetching:s,isUninitialized:c,refetch:l,fulfilledTimeStamp:u}=n,d=i?.keepPreviousData===!0?n.data:void 0,f=i?.isEmpty??r;return t(()=>{let t=()=>{l()},n=e=>f(e)?{status:`empty`,refreshing:s,refresh:t,fulfilledTimeStamp:u}:{status:`data`,data:e,refreshing:s,refresh:t,fulfilledTimeStamp:u};return a===void 0?o===void 0?c===!0?{status:`idle`}:d===void 0?{status:`loading`}:n(d):{status:`error`,error:e(o),retry:t}:n(a)},[a,d,o,s,c,l,f,u])}var r=e=>Array.isArray(e)?e.length===0:typeof e==`object`&&e&&`items`in e&&Array.isArray(e.items)?e.items.length===0:!1;function i(n){let{currentData:r,error:i,isFetching:a,isFetchingNextPage:o,hasNextPage:s,isError:c,isUninitialized:l,refetch:u,fetchNextPage:d,fulfilledTimeStamp:f}=n,p=t(()=>(r?.pages??[]).flatMap(e=>e.items),[r]);return{state:t(()=>{let t=()=>{u()};if(r===void 0)return i===void 0?l===!0?{status:`idle`}:{status:`loading`}:{status:`error`,error:e(i),retry:t};let n=a&&!o;return p.length===0?{status:`empty`,refreshing:n,refresh:t,fulfilledTimeStamp:f}:{status:`data`,data:p,refreshing:n,refresh:t,fulfilledTimeStamp:f}},[r,i,a,o,l,p,u,f]),paging:t(()=>({hasMore:s,loadingMore:o,errorMore:c?e(i):null,loadMore:()=>{s&&!o&&!c&&d()},retryMore:()=>{c&&d()}}),[s,o,c,i,d])}}export{n as useDataState,i as useInfiniteDataState};
@@ -0,0 +1 @@
1
+ import{isApiError as e}from"../errors/extractApiError.js";import{ifMatchValue as t,strongEntityTag as n}from"./apiBaseQuery.js";var r=(e,t)=>{let n=typeof e==`object`&&e&&`version`in e?e.version:void 0;return typeof n==`string`&&n!==``?n:t===void 0||t===``?void 0:t},i=(e,n)=>{let r=Object.entries({...n?.headers}).filter(([e])=>e.toLowerCase()!==`if-match`);return{...n,headers:{...Object.fromEntries(r),"If-Match":t(e)}}},a=e=>{let t=e.headers;if(typeof t==`object`&&t&&`etag`in t)return n(t.etag)},o=t=>e(t)&&t.status===412,s=async({record:e,entityTag:t,form:n,toForm:i,read:a,save:s})=>{let c=r(e,t);if(c===void 0)throw Error(`saveWithVersion: the record has no version to send as If-Match`);try{return await s(n,c),{saved:!0}}catch(t){if(!o(t))throw t;let c=await a(),l=r(c.record,c.entityTag);if(JSON.stringify(i(c.record))!==JSON.stringify(i(e))||l===void 0)return{saved:!1,error:t,fresh:c.record};try{return await s(n,l),{saved:!0}}catch(e){if(!o(e))throw e;return{saved:!1,error:e,fresh:c.record}}}};export{a as entityTagOf,s as saveWithVersion,r as versionOf,i as withIfMatch};
@@ -1 +1 @@
1
- import{createApiBaseQuery as e}from"./apiBaseQuery.js";import{APP_API_DEFAULTS as t,createAppApi as n}from"./createAppApi.js";import{useDataState as r}from"./dataState.js";import{setupApiListeners as i}from"./listeners.js";import{LIST_QUERY_RESERVED as a,SEARCH_PARAM as o,buildListQuery as s,emptyFacetValue as c,isFacetActive as l,listQueryParamNames as u,parseListQuery as d}from"./listQuery.js";import{getNextPageParam as f,getPreviousPageParam as p,hasNextPage as m,hasPreviousPage as h}from"./paging.js";import{LIST_TAG_ID as g,itemTag as _,listTag as v,providesList as y,providesPagedList as b}from"./tags.js";import{useListQuery as x}from"./useListQuery.js";export{t as APP_API_DEFAULTS,a as LIST_QUERY_RESERVED,g as LIST_TAG_ID,o as SEARCH_PARAM,s as buildListQuery,e as createApiBaseQuery,n as createAppApi,c as emptyFacetValue,f as getNextPageParam,p as getPreviousPageParam,m as hasNextPage,h as hasPreviousPage,l as isFacetActive,_ as itemTag,u as listQueryParamNames,v as listTag,d as parseListQuery,y as providesList,b as providesPagedList,i as setupApiListeners,r as useDataState,x as useListQuery};
1
+ import{createApiBaseQuery as e}from"./apiBaseQuery.js";import{APP_API_DEFAULTS as t,createAppApi as n}from"./createAppApi.js";import{useDataState as r,useInfiniteDataState as i}from"./dataState.js";import{entityTagOf as a,saveWithVersion as o,versionOf as s,withIfMatch as c}from"./entityVersion.js";import{setupApiListeners as l}from"./listeners.js";import{LIST_QUERY_RESERVED as u,SEARCH_PARAM as d,buildListQuery as f,emptyFacetValue as p,isFacetActive as m,listQueryParamNames as h,parseListQuery as g}from"./listQuery.js";import{getNextPageParam as _,getPreviousPageParam as v,hasNextPage as y,hasPreviousPage as b}from"./paging.js";import{LIST_TAG_ID as x,itemTag as S,listTag as C,providesList as w,providesPagedList as T}from"./tags.js";import{useListQuery as E}from"./useListQuery.js";export{t as APP_API_DEFAULTS,u as LIST_QUERY_RESERVED,x as LIST_TAG_ID,d as SEARCH_PARAM,f as buildListQuery,e as createApiBaseQuery,n as createAppApi,p as emptyFacetValue,a as entityTagOf,_ as getNextPageParam,v as getPreviousPageParam,y as hasNextPage,b as hasPreviousPage,m as isFacetActive,S as itemTag,h as listQueryParamNames,C as listTag,g as parseListQuery,w as providesList,T as providesPagedList,o as saveWithVersion,l as setupApiListeners,r as useDataState,i as useInfiniteDataState,E as useListQuery,s as versionOf,c as withIfMatch};
@@ -1 +1 @@
1
- var e=e=>e.page<e.totalPages,t=e=>e.page>1,n=t=>e(t)?t.page+1:void 0,r=e=>t(e)?e.page-1:void 0;export{n as getNextPageParam,r as getPreviousPageParam,e as hasNextPage,t as hasPreviousPage};
1
+ var e=e=>e.page<e.totalPages||e.totalCountCapped&&e.items.length>=e.pageSize,t=e=>e.page>1,n=t=>e(t)?t.page+1:void 0,r=e=>t(e)?e.page-1:void 0;export{n as getNextPageParam,r as getPreviousPageParam,e as hasNextPage,t as hasPreviousPage};
@@ -1 +1 @@
1
- import{extractApiError as e}from"../errors/extractApiError.js";import{buildListQuery as t,isFacetActive as n,listQueryParamNames as r,parseListQuery as i}from"./listQuery.js";import{useCallback as a,useEffect as o,useMemo as s,useRef as c,useState as l}from"react";import{useSearchParams as u}from"react-router";var d=300,f=20,p=`No results match these filters.`,m=[];function h(e,t,n){let a=r(t),o=[...e.keys()].some(e=>a.has(e)),s=i(e,{facets:t,defaults:{page:n.page,pageSize:n.pageSize,sortBy:n.sortBy,sortOrder:n.sortOrder,filters:n.filters}});return{page:s.page,pageSize:s.pageSize,sortBy:s.sortBy,sortOrder:s.sortOrder,search:o?s.search:n.search??``,filters:s.filters}}function g(e){return t({page:e.page,pageSize:e.pageSize,sortBy:e.sortBy,sortOrder:e.sortOrder,search:e.search,filters:e.filters})}function _(t){let{fetchPage:r,facets:i=[],defaults:_={},debounceMs:v=d,onRefreshError:y}=t,[b,x]=u(),S=h(b,i,_),[C,w]=l(S.search),[T,E]=l(),D=c(T);D.current=T;let[O,k]=l(),[A,j]=l(!0),[M,N]=l(0),P={...S,search:C},F=c(P);F.current=P;let I=c(r);I.current=r;let L=c(y);L.current=y;let R=`${g(P)}#${M}`,z=c(R);z.current=R,o(()=>{if(S.search===C)return;let e=setTimeout(()=>w(S.search),v);return()=>clearTimeout(e)},[S.search,C,v]),o(()=>{let t=new AbortController,n=()=>t.signal.aborted||z.current!==R;return j(!0),new Promise(e=>{e(I.current(F.current,{signal:t.signal}))}).then(e=>{n()||(E(e),k(void 0),j(!1))},t=>{n()||(D.current!==void 0&&L.current?.(e(t)),k({reason:t}),j(!1))}),()=>t.abort()},[R]);let B=(e,t)=>{x(g(e),{replace:!0}),t&&w(e.search)},V=e=>B({...S,page:e},!0),H=e=>B({...S,pageSize:e},!0),U=e=>B({...S,page:1,search:e},!1),W=(e,t)=>B({...S,page:1,filters:{...S.filters,[e]:t}},!0),G=(e,t=`asc`)=>B({...S,page:1,sortBy:e,sortOrder:t},!0),K=e=>G(e,e===S.sortBy&&S.sortOrder===`asc`?`desc`:`asc`),q=()=>{let e=h(new URLSearchParams,i,_);x(new URLSearchParams,{replace:!0}),w(e.search)},J=a(()=>N(e=>e+1),[]),Y=S.search!==``||i.some(e=>n(e,S.filters[e.key])),X=T?.totalCount??0,Z=T?.totalPages??0,Q=s(()=>T===void 0?O===void 0||A?{status:`loading`}:{status:`error`,error:e(O.reason),retry:J}:T.items.length===0?{status:`empty`,refreshing:A,refresh:J}:{status:`data`,data:T,refreshing:A,refresh:J},[T,O,A,J]);return{query:S,rows:T?.items??m,state:Q,totalCount:X,totalPages:Z,setFilter:W,setSearch:U,setSort:G,setPage:V,setPageSize:H,reset:q,tableProps:{rows:T?.items??m,sort:S.sortBy?{key:S.sortBy,dir:S.sortOrder}:void 0,onSort:K,loading:A,emptyFiltered:Y?p:void 0,sourceCount:Y?Math.max(X,1):X},paginationProps:{page:S.page,totalPages:Z,pageSize:S.pageSize??T?.pageSize??f,onPageChange:V,onPageSizeChange:H}}}export{_ as useListQuery};
1
+ import{extractApiError as e}from"../errors/extractApiError.js";import{buildListQuery as t,isFacetActive as n,listQueryParamNames as r,parseListQuery as i}from"./listQuery.js";import{useCallback as a,useEffect as o,useMemo as s,useRef as c,useState as l}from"react";import{useSearchParams as u}from"react-router";var d=300,f=20,p=`No results match these filters.`,m=[];function h(e,t,n){let a=r(t),o=[...e.keys()].some(e=>a.has(e)),s=i(e,{facets:t,defaults:n});return{page:s.page,...s.pageSize!==void 0&&{pageSize:s.pageSize},...s.sortBy!==void 0&&{sortBy:s.sortBy},sortOrder:s.sortOrder,search:o?s.search:n.search??``,filters:s.filters}}function g(e){return t({page:e.page,...e.pageSize!==void 0&&{pageSize:e.pageSize},...e.sortBy!==void 0&&{sortBy:e.sortBy},sortOrder:e.sortOrder,search:e.search,filters:e.filters})}function _(t){let{fetchPage:r,facets:i=[],defaults:_={},debounceMs:v=d,onRefreshError:y}=t,[b,x]=u(),S=h(b,i,_),[C,w]=l(S.search),[T,E]=l(),D=c(T);D.current=T;let[O,k]=l(),[A,j]=l(!0),[M,N]=l(0),P={...S,search:C},F=c(P);F.current=P;let I=c(r);I.current=r;let L=c(y);L.current=y;let R=`${g(P)}#${M}`,z=c(R);z.current=R,o(()=>{if(S.search===C)return;let e=setTimeout(()=>w(S.search),v);return()=>clearTimeout(e)},[S.search,C,v]),o(()=>{let t=new AbortController,n=()=>t.signal.aborted||z.current!==R;return j(!0),new Promise(e=>{e(I.current(F.current,{signal:t.signal}))}).then(e=>{n()||(E(e),k(void 0),j(!1))},t=>{n()||(D.current!==void 0&&L.current?.(e(t)),k({reason:t}),j(!1))}),()=>t.abort()},[R]);let B=(e,t)=>{x(g(e),{replace:!0}),t&&w(e.search)},V=e=>B({...S,page:e},!0),H=e=>B({...S,pageSize:e},!0),U=e=>B({...S,page:1,search:e},!1),W=(e,t)=>B({...S,page:1,filters:{...S.filters,[e]:t}},!0),G=(e,t=`asc`)=>B({...S,page:1,sortBy:e,sortOrder:t},!0),K=e=>G(e,e===S.sortBy&&S.sortOrder===`asc`?`desc`:`asc`),q=()=>{let e=h(new URLSearchParams,i,_);x(new URLSearchParams,{replace:!0}),w(e.search)},J=a(()=>N(e=>e+1),[]),Y=S.search!==``||i.some(e=>n(e,S.filters[e.key])),X=T?.totalCount??0,Z=T?.totalPages??0,Q=T?.totalCountCapped===!0,$=s(()=>T===void 0?O===void 0||A?{status:`loading`}:{status:`error`,error:e(O.reason),retry:J}:T.items.length===0?{status:`empty`,refreshing:A,refresh:J}:{status:`data`,data:T,refreshing:A,refresh:J},[T,O,A,J]);return{query:S,rows:T?.items??m,state:$,totalCount:X,totalPages:Z,totalCountCapped:Q,setFilter:W,setSearch:U,setSort:G,setPage:V,setPageSize:H,reset:q,tableProps:{rows:T?.items??m,...S.sortBy?{sort:{key:S.sortBy,dir:S.sortOrder}}:{},onSort:K,loading:A,...Y?{emptyFiltered:p}:{},sourceCount:Y?Math.max(X,1):X},paginationProps:{page:S.page,totalPages:Z,pageSize:S.pageSize??T?.pageSize??f,onPageChange:V,onPageSizeChange:H}}}export{_ as useListQuery};
@@ -0,0 +1 @@
1
+ export declare const newIdempotencyKey: () => string;
@@ -10,6 +10,7 @@ export { REFRESH_LOCK_NAME, withCrossTabRefreshLock } from "./crossTabRefreshLoc
10
10
  export { applyDesignSample, DESIGN_SAMPLE_HEADER, DESIGN_SAMPLE_QUERY_KEY, DESIGN_SAMPLE_STORAGE_KEY, readDesignSampleTicket, } from "./designSample";
11
11
  export type { DownloadedFile, DownloadRequest } from "./downloadFile";
12
12
  export { contentDispositionFileName, downloadFile } from "./downloadFile";
13
+ export { newIdempotencyKey } from "./idempotencyKey";
13
14
  export type { MinAppVersionListener } from "./minAppVersion";
14
15
  export { addMinAppVersionListener, getMinAppVersion, MIN_APP_VERSION_HEADER } from "./minAppVersion";
15
16
  export { default as publicClient } from "./publicClient";
@@ -1,4 +1,5 @@
1
1
  import { ApplicationInsights, type ITelemetryItem, type ITelemetryPlugin } from "@microsoft/applicationinsights-web";
2
+ import { type RemoteLogger } from "../logger";
2
3
  export interface AppInsightsOptions {
3
4
  /** The Application Insights connection string. An empty string turns telemetry off. */
4
5
  connectionString: string;
@@ -8,10 +9,12 @@ export interface AppInsightsOptions {
8
9
  environment: string;
9
10
  /** The build version stamped on every item as ai.application.ver. */
10
11
  version: string;
11
- /** The absolute URL of the API. Its host gets correlation headers, and its successful calls are not sent twice. */
12
+ /** The URL of the API, absolute or a path resolved against the page. Its host gets correlation headers, and its successful calls are not sent twice. */
12
13
  apiBaseUrl: string;
13
14
  /** Extra SDK plugins, such as the React plugin. */
14
15
  extensions?: ITelemetryPlugin[] | undefined;
16
+ /** More remote loggers that receive every log line, error, user and attribute beside Application Insights, such as a product's own error log. */
17
+ sinks?: readonly RemoteLogger[] | undefined;
15
18
  /** The app's own telemetry initializers, registered after the library's and before the first page view, so every item carries them. Returning false drops the item. */
16
19
  initializers?: readonly TelemetryInitializer[] | undefined;
17
20
  /** A dependency this many milliseconds or slower is kept even when it succeeds. Default 500. */
@@ -13,6 +13,10 @@ export interface ApiError {
13
13
  traceId: string | null;
14
14
  /** What the server or runtime actually said. For the logger, never for the screen. */
15
15
  diagnostic: string | null;
16
+ /** The request address the failed call was sent to. For the logger and the caller, never the screen. */
17
+ requestUrl?: string | undefined;
18
+ /** The Account-Id the failed call was sent with. For the logger and the caller, never the screen. */
19
+ accountId?: string | undefined;
16
20
  }
17
21
  export declare const SERVER_FAILURE_MESSAGE = "Something went wrong on our side. Please try again in a moment.";
18
22
  export declare const OFFLINE_MESSAGE = "You appear to be offline. Check your connection and try again.";
@@ -29,6 +29,10 @@ export interface ApiRequest {
29
29
  expectedStatuses?: number[];
30
30
  paramsFormat?: ParamsFormat;
31
31
  public?: boolean;
32
+ /** Sent as `If-Match: "<value>"`; the version read from `meta.entityTag`. */
33
+ ifMatch?: string;
34
+ /** Sent as `Idempotency-Key`; from `AppForm`'s submit context. */
35
+ idempotencyKey?: string;
32
36
  }
33
37
  export type ApiQueryArgs = string | ApiRequest;
34
38
  /** Per-endpoint options, set as the endpoint's `extraOptions`. */
@@ -37,6 +41,9 @@ export interface ApiExtraOptions {
37
41
  expectedStatuses?: number[];
38
42
  paramsFormat?: ParamsFormat;
39
43
  }
44
+ export declare const strongEntityTag: (value: unknown) => string | undefined;
45
+ /** The `If-Match` header value for a version: the version in quotes, as an ETag is sent. */
46
+ export declare const ifMatchValue: (version: string) => string;
40
47
  /**
41
48
  * Returned as the base query's `meta`, which RTK Query copies onto the
42
49
  * fulfilled and rejected actions as `action.meta.baseQueryMeta`. The toast
@@ -49,6 +56,8 @@ export interface ApiBaseQueryMeta {
49
56
  expectedStatuses?: number[];
50
57
  /** The HTTP status, or 0 when no response arrived. */
51
58
  status: number;
59
+ /** The strong ETag of the response, without quotes; undefined when none was sent. */
60
+ entityTag?: string;
52
61
  }
53
62
  export interface ApiBaseQueryOptions {
54
63
  /** The signed-in client every call uses by default (`userClient`). */
@@ -1,6 +1,9 @@
1
1
  import { type ApiError } from "../errors";
2
+ import type { PagedDataObject } from "./paging";
2
3
  /** What a screen can be showing for one request. A closed set: the block draws every member. */
3
4
  export type DataState<T> = {
5
+ readonly status: "idle";
6
+ } | {
4
7
  readonly status: "loading";
5
8
  } | {
6
9
  readonly status: "error";
@@ -10,29 +13,69 @@ export type DataState<T> = {
10
13
  readonly status: "empty";
11
14
  readonly refreshing: boolean;
12
15
  readonly refresh: () => void;
16
+ readonly fulfilledTimeStamp?: number | undefined;
13
17
  } | {
14
18
  readonly status: "data";
15
19
  readonly data: T;
16
20
  readonly refreshing: boolean;
17
21
  readonly refresh: () => void;
22
+ readonly fulfilledTimeStamp?: number | undefined;
18
23
  };
19
24
  /** The members of an RTK Query hook result that useDataState reads. */
20
25
  export interface QueryResultLike<T> {
21
26
  readonly currentData?: T | undefined;
27
+ /** The last result for any arguments; read only with keepPreviousData. */
28
+ readonly data?: T | undefined;
22
29
  readonly error?: unknown;
23
30
  readonly isFetching: boolean;
31
+ /** True while the query has never started, which for an RTK Query hook means it is skipped. */
32
+ readonly isUninitialized?: boolean | undefined;
33
+ readonly fulfilledTimeStamp?: number | undefined;
24
34
  readonly refetch: () => unknown;
25
35
  }
26
36
  export interface DataStateOptions<T> {
27
37
  /** Default: an array of length 0, or a PagedDataObject whose items has length 0. Anything else is never empty. */
28
38
  readonly isEmpty?: (data: T) => boolean;
39
+ /** Default false. True keeps the last result on screen, refreshing, while a query with new arguments loads. */
40
+ readonly keepPreviousData?: boolean;
29
41
  }
30
42
  /**
31
43
  * Rules, in order:
32
- * 1. currentData is not undefined: "empty" when isEmpty says so, else "data"; refreshing is isFetching; refresh is refetch.
44
+ * 1. currentData is not undefined: "empty" when isEmpty says so, else "data"; refreshing is isFetching; refresh is refetch;
45
+ * fulfilledTimeStamp is passed through.
33
46
  * A failed refetch that still holds currentData stays here (the toast middleware reports it).
34
47
  * 2. error is set: "error", with error passed through extractApiError and retry calling refetch.
35
- * 3. otherwise "loading" (first load, a skipped query, an argument that changed).
36
- * The returned object is memoized on currentData, error, isFetching and refetch.
48
+ * It wins over a kept previous result, so a failed new query never shows the old arguments' rows as its answer.
49
+ * 3. isUninitialized is true: "idle", the query is skipped and the block draws nothing.
50
+ * 4. keepPreviousData is on and data is not undefined: rule 1 applied to data, with refreshing true while isFetching.
51
+ * 5. otherwise "loading" (first load, an argument that changed).
52
+ * The returned object is memoized on its inputs.
37
53
  */
38
54
  export declare function useDataState<T>(result: QueryResultLike<T>, options?: DataStateOptions<T>): DataState<T>;
55
+ export interface PagedListPaging {
56
+ hasMore: boolean;
57
+ loadingMore: boolean;
58
+ errorMore: ApiError | null;
59
+ loadMore: () => void;
60
+ retryMore: () => void;
61
+ }
62
+ export interface InfiniteQueryResultLike<T> {
63
+ readonly currentData?: {
64
+ readonly pages: readonly PagedDataObject<T>[];
65
+ } | undefined;
66
+ readonly error?: unknown;
67
+ readonly isFetching: boolean;
68
+ readonly isFetchingNextPage: boolean;
69
+ readonly hasNextPage: boolean;
70
+ readonly isError: boolean;
71
+ /** True while the query has never started, which for an RTK Query hook means it is skipped. */
72
+ readonly isUninitialized?: boolean | undefined;
73
+ readonly fulfilledTimeStamp?: number | undefined;
74
+ readonly refetch: () => unknown;
75
+ readonly fetchNextPage: () => unknown;
76
+ }
77
+ /** state: every loaded page's items in order, "empty" when there are none. paging: what the paged list footer reads. */
78
+ export declare function useInfiniteDataState<T>(result: InfiniteQueryResultLike<T>): {
79
+ readonly state: DataState<readonly T[]>;
80
+ readonly paging: PagedListPaging;
81
+ };
@@ -0,0 +1,46 @@
1
+ import type { AxiosRequestConfig } from "axios";
2
+ import { type ApiError } from "../errors";
3
+ /**
4
+ * The version a write sends back as `If-Match`: the record's own `version` string (a list item, or the
5
+ * body of a single record), else the strong ETag of the read that loaded it.
6
+ */
7
+ export declare const versionOf: (record: unknown, entityTag?: string | undefined) => string | undefined;
8
+ /** A copy of `cfg` that sends `version` as `If-Match`, replacing an `If-Match` under any casing; `cfg` itself is not changed. */
9
+ export declare const withIfMatch: (version: string, cfg?: AxiosRequestConfig) => AxiosRequestConfig;
10
+ /** The strong ETag of a response's `etag` header, without quotes; undefined when there is none or it is weak. */
11
+ export declare const entityTagOf: (response: {
12
+ headers: unknown;
13
+ }) => string | undefined;
14
+ /** A record as the server holds it now, with the ETag of the read that returned it when the caller has one. */
15
+ export interface VersionedRead<R> {
16
+ record: R;
17
+ entityTag?: string | undefined;
18
+ }
19
+ export interface SaveWithVersionOptions<R, F> {
20
+ /** The record the form opened with. */
21
+ record: R;
22
+ /** Its ETag, when the screen read it from the response meta. */
23
+ entityTag?: string | undefined;
24
+ /** The values the form holds now. */
25
+ form: F;
26
+ /** The fields the form shows and sends, read from a record. */
27
+ toForm: (record: R) => F;
28
+ /** Reads the record as the server holds it now. */
29
+ read: () => Promise<VersionedRead<R>>;
30
+ /** Sends `form` with `version` as If-Match. Rejects with the ApiError of a failed reply. */
31
+ save: (form: F, version: string) => Promise<void>;
32
+ }
33
+ export type SaveWithVersionResult<R> = {
34
+ saved: true;
35
+ } | {
36
+ saved: false;
37
+ error: ApiError;
38
+ fresh: R;
39
+ };
40
+ /**
41
+ * Saves a record guarded by its version. A 412 re-reads the record once. When the fields the form covers
42
+ * are unchanged on the server, it saves the form again with the fresh version and reports success. Otherwise
43
+ * it returns the stale error and the fresh record: the caller shows the message and resets the form to
44
+ * `toForm(fresh)`. A second 412 is returned, never retried. Any other failure is rethrown.
45
+ */
46
+ export declare const saveWithVersion: <R, F>({ record, entityTag, form, toForm, read, save, }: SaveWithVersionOptions<R, F>) => Promise<SaveWithVersionResult<R>>;
@@ -1,8 +1,10 @@
1
1
  export type { ApiBaseQuery, ApiBaseQueryMeta, ApiBaseQueryOptions, ApiExtraOptions, ApiQueryArgs, ApiRequest, } from "./apiBaseQuery";
2
2
  export { createApiBaseQuery } from "./apiBaseQuery";
3
3
  export { APP_API_DEFAULTS, createAppApi } from "./createAppApi";
4
- export type { DataState, DataStateOptions, QueryResultLike } from "./dataState";
5
- export { useDataState } from "./dataState";
4
+ export type { DataState, DataStateOptions, InfiniteQueryResultLike, PagedListPaging, QueryResultLike } from "./dataState";
5
+ export { useDataState, useInfiniteDataState } from "./dataState";
6
+ export type { SaveWithVersionOptions, SaveWithVersionResult, VersionedRead } from "./entityVersion";
7
+ export { entityTagOf, saveWithVersion, versionOf, withIfMatch } from "./entityVersion";
6
8
  export { setupApiListeners } from "./listeners";
7
9
  export type { Facet, FacetKey, FacetType, ListQueryInput, ParsedListQuery, ParseListQueryOptions } from "./listQuery";
8
10
  export { buildListQuery, emptyFacetValue, isFacetActive, LIST_QUERY_RESERVED, listQueryParamNames, parseListQuery, SEARCH_PARAM, } from "./listQuery";
@@ -7,7 +7,7 @@ export interface Facet {
7
7
  options?: {
8
8
  value: string;
9
9
  label: string;
10
- }[];
10
+ }[] | undefined;
11
11
  }
12
12
  /** The part of a facet the URL needs; a full Facet is assignable. */
13
13
  export type FacetKey = Pick<Facet, "key" | "type">;
@@ -3,7 +3,7 @@
3
3
  * `PagedListRequest` (`page` 1-based, `pageSize`, `sortBy`, `sortOrder`, `search`)
4
4
  * plus the endpoint's filters, and the response is `PagedDataObject<T>`. The
5
5
  * server defaults a missing page to 1 and a missing size to 20, and cuts a size
6
- * over 100 to 100.
6
+ * over 100 to 100. A capped answer carries the cap as `totalCount`.
7
7
  */
8
8
  export interface PagedDataObject<T> {
9
9
  items: T[];
@@ -11,6 +11,8 @@ export interface PagedDataObject<T> {
11
11
  pageSize: number;
12
12
  totalCount: number;
13
13
  totalPages: number;
14
+ /** True when `totalCount` is the server's cap, so the real total is at least that. */
15
+ totalCountCapped: boolean;
14
16
  }
15
17
  export type SortOrder = "asc" | "desc";
16
18
  export interface PagedListRequest {
@@ -27,6 +27,8 @@ export interface UseListQueryResult<TRow> {
27
27
  state: DataState<PagedDataObject<TRow>>;
28
28
  totalCount: number;
29
29
  totalPages: number;
30
+ /** True when totalCount is the server's cap: show it with a trailing plus. */
31
+ totalCountCapped: boolean;
30
32
  setFilter(key: string, value: ListFilterValue): void;
31
33
  setSearch(text: string): void;
32
34
  setSort(sortBy: string, sortOrder?: SortOrder): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/web-core",
3
- "version": "0.150.0",
3
+ "version": "0.153.0",
4
4
  "description": "Platform layer for Webority React web portals: HTTP clients with single-flight token refresh, auth store, API error extraction, RTK Query base query, logger, formatters, storage, version check and route guards. No UI.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -98,7 +98,7 @@
98
98
  },
99
99
  "sideEffects": false,
100
100
  "dependencies": {
101
- "@webority/api-contract": "0.150.0"
101
+ "@webority/api-contract": "0.153.0"
102
102
  },
103
103
  "peerDependencies": {
104
104
  "@microsoft/applicationinsights-web": "^3.4.5",
@@ -120,6 +120,7 @@
120
120
  "@types/node": "25.6.0",
121
121
  "@types/react": "^19.3.0",
122
122
  "@vitest/coverage-v8": "5.1.0",
123
+ "@webority/biome-config": "0.153.0",
123
124
  "axios": "^1.18.0",
124
125
  "jsdom": "30.1.1",
125
126
  "react": "^19.3.1",