@webority/web-core 0.149.0 → 0.152.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 +114 -6
- package/dist/api/baseUrl.js +1 -1
- package/dist/api/blobErrorBody.js +1 -0
- package/dist/api/contractCaller.js +1 -0
- package/dist/api/crossTabRefreshLock.js +1 -1
- package/dist/api/designSample.js +1 -1
- package/dist/api/downloadFile.js +1 -0
- package/dist/api/idempotencyKey.js +1 -0
- package/dist/api/index.js +1 -1
- package/dist/api/minAppVersion.js +1 -1
- package/dist/api/requestDefaults.js +1 -1
- package/dist/api/retry.js +1 -1
- package/dist/api/tokenRefresh.js +1 -1
- package/dist/api/userClient.js +1 -1
- package/dist/api/workspaceChanged.js +1 -1
- package/dist/api-contract/dist/call.js +1 -0
- package/dist/appInsights/appInsights.js +1 -0
- package/dist/appInsights/index.js +1 -0
- package/dist/auth/authStore.js +1 -1
- package/dist/auth/jwt.js +1 -1
- package/dist/errors/extractApiError.js +2 -2
- package/dist/errors/index.js +1 -1
- package/dist/errors/parseResponse.js +1 -0
- package/dist/errors/requestPlatform.js +1 -0
- package/dist/formatters/currency.js +1 -1
- package/dist/formatters/formatConfig.js +1 -1
- package/dist/formatters/house.js +1 -1
- package/dist/index.js +1 -1
- package/dist/india/gstStates.js +1 -0
- package/dist/india/index.js +1 -1
- package/dist/logger/logger.js +2 -2
- package/dist/logger/redact.js +1 -1
- package/dist/network/networkStatus.js +1 -1
- package/dist/query/apiBaseQuery.js +1 -1
- package/dist/query/createAppApi.js +1 -1
- package/dist/query/dataState.js +1 -0
- package/dist/query/entityVersion.js +1 -0
- package/dist/query/index.js +1 -1
- package/dist/query/listQuery.js +1 -1
- package/dist/query/paging.js +1 -1
- package/dist/query/tags.js +1 -1
- package/dist/query/useListQuery.js +1 -1
- package/dist/redux/errorToastMiddleware.js +1 -1
- package/dist/redux/rootReducer.js +1 -1
- package/dist/router/chunkReload.js +1 -1
- package/dist/router/index.js +1 -1
- package/dist/router/returnTo.js +1 -1
- package/dist/router/routeTable.js +1 -0
- package/dist/storage/index.js +1 -1
- package/dist/types/api/blobErrorBody.d.ts +9 -0
- package/dist/types/api/contractCaller.d.ts +11 -0
- package/dist/types/api/downloadFile.d.ts +19 -0
- package/dist/types/api/idempotencyKey.d.ts +1 -0
- package/dist/types/api/index.d.ts +7 -0
- package/dist/types/api/tokenRefresh.d.ts +2 -1
- package/dist/types/appInsights/appInsights.d.ts +33 -0
- package/dist/types/appInsights/index.d.ts +3 -0
- package/dist/types/auth/authStore.d.ts +2 -1
- package/dist/types/auth/jwt.d.ts +11 -8
- package/dist/types/errors/extractApiError.d.ts +6 -15
- package/dist/types/errors/index.d.ts +2 -0
- package/dist/types/errors/parseResponse.d.ts +19 -0
- package/dist/types/errors/requestPlatform.d.ts +5 -0
- package/dist/types/formatters/formatConfig.d.ts +8 -6
- package/dist/types/formatters/house.d.ts +19 -20
- package/dist/types/formatters/intlCache.d.ts +1 -3
- package/dist/types/india/gstStates.d.ts +7 -0
- package/dist/types/india/gstStates.g.d.ts +1 -1
- package/dist/types/india/index.d.ts +1 -0
- package/dist/types/initUserAuth.d.ts +2 -1
- package/dist/types/logger/redact.d.ts +3 -1
- package/dist/types/query/apiBaseQuery.d.ts +10 -1
- package/dist/types/query/dataState.d.ts +81 -0
- package/dist/types/query/entityVersion.d.ts +46 -0
- package/dist/types/query/index.d.ts +4 -0
- package/dist/types/query/listQuery.d.ts +3 -3
- package/dist/types/query/paging.d.ts +3 -1
- package/dist/types/query/useListQuery.d.ts +10 -6
- package/dist/types/redux/index.d.ts +1 -1
- package/dist/types/redux/rootReducer.d.ts +7 -2
- package/dist/types/router/chunkReload.d.ts +5 -2
- package/dist/types/router/index.d.ts +2 -0
- package/dist/types/router/routeTable.d.ts +66 -0
- package/dist/types/storage/index.d.ts +10 -8
- package/dist/versionCheck/deployedBuild.js +1 -1
- package/dist/vite/index.js +1 -1
- package/package.json +21 -5
package/README.md
CHANGED
|
@@ -14,6 +14,7 @@ store.
|
|
|
14
14
|
| Module | What it holds |
|
|
15
15
|
| --- | --- |
|
|
16
16
|
| `api` | `publicClient`, `userClient`, `initUserAuth`, single-flight token refresh, a cross-tab refresh lock, retry of safe requests, the client headers and the minimum-version header reader |
|
|
17
|
+
| `appInsights` | `initAppInsights`, imported from the subpath `@webority/web-core/appInsights`: starts Application Insights with one fixed policy (role and version on every item, correlation headers to the API host only, sign-in codes and tokens scrubbed from addresses, only failed or slow dependencies sent, no cookies until consent) and makes it the `Logger`'s remote sink. Needs the optional peer `@microsoft/applicationinsights-web`; an empty connection string or a test run starts nothing |
|
|
17
18
|
| `auth` | the token store (`getToken`, `storeToken`, `removeToken`), the synchronous `hasSession`, the session user, `clearSession` and `addSessionEndedListener`, `hasSessionEndedInTab`, JWT helpers, "keep me signed in" |
|
|
18
19
|
| `config` | `setConfig`, `getConfig`, `getConfigValue`: base URL, version, commit, build number, log settings, request timeout, retry count |
|
|
19
20
|
| `errors` | `extractApiError`: any thrown value to `{ code, message, fieldErrors, status, offline, traceId, diagnostic }`, with `code` `'network'`, `'timeout'` or `'offline'` when no answer arrived (`offline` is true for all three, and `'offline'` only when the browser reports no network); `apiErrorMessage(error, fallback)`; `isNoResponse` |
|
|
@@ -22,10 +23,10 @@ store.
|
|
|
22
23
|
| `logger` | levelled `Logger` with secret redaction, and `Logger.requestFailed` for a failed service call |
|
|
23
24
|
| `network` | `useNetworkStatus` and the online/offline listener |
|
|
24
25
|
| `query` | the RTK Query base query over `userClient`, the `createAppApi` preset, paged-list and tag helpers |
|
|
25
|
-
| `redux` | `errorToastMiddleware`, `createRootReducer` with `resetState` (clears every slice on sign-out), the serializable-check paths |
|
|
26
|
+
| `redux` | `errorToastMiddleware`, `createRootReducer` with `resetState` (clears every slice on sign-out; `resetState({ keep: ["account", "api"] })` keeps the named slices for that one reset, such as a workspace switch, and throws on a name that is no slice), the serializable-check paths. A slice that must land somewhere other than its initial state after a reset (a profile resolved as signed out, not loading) answers `resetState` in its own `extraReducers` |
|
|
26
27
|
| `router` | loader guards (`requireAuth`, `publicOnly`, `requirePermission`, `withGuards`), element guards (`RequireAuth`, `PublicOnly`, `RequirePermission`), chunk-reload retry with its shared window (`hasRecentlyReloaded`, `markReloaded`), route error classification |
|
|
27
28
|
| `static` | `staticUrl(key)`: the versioned address of an authored static file (a video, a sample document) listed in the `staticAssets.assets` object of the one deployable carrying `staticAssets` in the repo's `.webority/infra/deployables.json` |
|
|
28
|
-
| `storage` | `Storage` (async, the same API as mobile) and `syncStorage` (synchronous, web only) over `localStorage` |
|
|
29
|
+
| `storage` | `Storage` (async, the same API as mobile) and `syncStorage` / `syncSessionStorage` (synchronous, web only) over `localStorage` / `sessionStorage` |
|
|
29
30
|
| `versionCheck` | `useVersionCheck` and `installReloadOnNavigate`: tells the portal a newer build is live |
|
|
30
31
|
| `vite` | `weborityStatic`, a Vite plugin that compiles the `staticAssets` list of `.webority/infra/deployables.json` for `staticUrl` and can point the build's hashed files at a static host. Node only: import it in `vite.config`, never in app code |
|
|
31
32
|
|
|
@@ -246,6 +247,37 @@ function LeaveList() {
|
|
|
246
247
|
|
|
247
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.
|
|
248
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
|
+
|
|
249
281
|
## Formatters
|
|
250
282
|
|
|
251
283
|
Called with no options, the house formatters print (zone IST, locale en-IN, empty `-`):
|
|
@@ -280,8 +312,11 @@ Called with no options, the house formatters print (zone IST, locale en-IN, empt
|
|
|
280
312
|
|
|
281
313
|
`Storage` is async, the same API as mobile-core's, for code shared with an app. `syncStorage` is
|
|
282
314
|
web only: `getItem`, `setItem`, `removeItem`, `getJson`, `setJson` straight on `localStorage`, for a
|
|
283
|
-
preference a first render cannot wait for.
|
|
284
|
-
|
|
315
|
+
preference a first render cannot wait for. `syncSessionStorage` is the same API on `sessionStorage`,
|
|
316
|
+
for state that ends with the tab. None of them throws: a blocked store reads as empty and a
|
|
317
|
+
write returns `false`. Both `getJson(key, parse)` take a parse function that checks the stored
|
|
318
|
+
JSON and returns the caller's type; `getSessionUser(parse)` and `decodeJWT(token, parse?)` read the
|
|
319
|
+
same way.
|
|
285
320
|
|
|
286
321
|
## Static assets
|
|
287
322
|
|
|
@@ -298,8 +333,8 @@ staticUrl("samples/report.pdf"); // "/samples/report.pdf?v=0123456789ab"
|
|
|
298
333
|
throws on a key that is not in the list. A same-origin `authoredOrigin` of `"/"` gives `/samples/...`.
|
|
299
334
|
The list is compiled into the bundle by the Vite plugin:
|
|
300
335
|
|
|
301
|
-
```
|
|
302
|
-
// vite.config.
|
|
336
|
+
```ts
|
|
337
|
+
// vite.config.ts
|
|
303
338
|
import { weborityStatic } from "@webority/web-core/vite";
|
|
304
339
|
|
|
305
340
|
export default defineConfig({
|
|
@@ -360,6 +395,61 @@ Vite 7 and earlier `esbuild: { pure: ["Logger.debug"] }`. This matches the call
|
|
|
360
395
|
already filtered by `logLevel`. On the web, track the matched route pattern with `trackScreen`, never the
|
|
361
396
|
concrete URL.
|
|
362
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
|
+
|
|
363
453
|
## Design sample
|
|
364
454
|
|
|
365
455
|
A Canvas compare opens a staging page with a `designSample` key in its address, and a person can open
|
|
@@ -379,6 +469,24 @@ the mode on, so the two checks are independent.
|
|
|
379
469
|
The design sample exists on the web only; `@webority/mobile-core` has no counterpart. This package stays
|
|
380
470
|
TypeScript, a recorded deviation from `react.md`, which asks for JavaScript.
|
|
381
471
|
|
|
472
|
+
## Contract caller
|
|
473
|
+
|
|
474
|
+
`createContractCaller` builds one typed caller from a generated contract (`@webority/api-contract`).
|
|
475
|
+
It takes the client and the contract's `operations` map, and calls an operation by its id with the
|
|
476
|
+
request the contract types for it. The reply is the response type of that operation.
|
|
477
|
+
|
|
478
|
+
```ts
|
|
479
|
+
import { createContractCaller, userClient } from "@webority/web-core";
|
|
480
|
+
import { operations, type Operations } from "./api/contract";
|
|
481
|
+
|
|
482
|
+
const call = createContractCaller<Operations>(userClient, operations);
|
|
483
|
+
|
|
484
|
+
const page = await call("Standards_List", { query: { page: 1 } }, { signal, timeout: 10000 });
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
The caller adds no catch: a failure reaches the caller as the client's curated error. `signal` and
|
|
488
|
+
`timeout` are optional and go to the request as they are.
|
|
489
|
+
|
|
382
490
|
## Develop
|
|
383
491
|
|
|
384
492
|
```bash
|
package/dist/api/baseUrl.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getConfigValue as e}from"../config/index.js";var t=t=>{t.interceptors.request.use(t=>(t.baseURL
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=async e=>{if(typeof e!=`object`||!e||!(`response`in e))return;let t=e.response;if(typeof t!=`object`||!t||!(`data`in t))return;let n=t.data;if(typeof Blob>`u`||!(n instanceof Blob))return;let r=n.type.includes(`json`);if(!r&&!n.type.startsWith(`text/`))return;let i=await n.text();if(!r)t.data=i;else try{t.data=JSON.parse(i)}catch{t.data=i}};export{e as readBlobErrorBody};
|
|
@@ -0,0 +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,...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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`webority.token-refresh`,t=`${e}.lease`,n=1e4,r=3e3,i=150,a=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=()=>{let e=localStorage.getItem(t);if(!e)return null;try{let t=JSON.parse(e);return
|
|
1
|
+
var e=`webority.token-refresh`,t=`${e}.lease`,n=1e4,r=3e3,i=150,a=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,o=e=>typeof e==`object`&&!!e&&`id`in e&&`expiresAt`in e&&typeof e.id==`string`&&typeof e.expiresAt==`number`,s=()=>{let e=localStorage.getItem(t);if(!e)return null;try{let t=JSON.parse(e);return o(t)&&t.expiresAt>Date.now()?t:null}catch{return null}},c=e=>{localStorage.setItem(t,JSON.stringify({id:e,expiresAt:Date.now()+n}))},l=e=>!s()&&(c(e),s()?.id===e),u=()=>typeof BroadcastChannel>`u`?null:new BroadcastChannel(e),d=e=>new Promise(t=>{let n=()=>{clearInterval(a),e?.removeEventListener(`message`,r),t()},r=()=>n(),a=setInterval(()=>{s()||n()},i);e?.addEventListener(`message`,r)}),f=async e=>{let n=a();try{s()}catch{return e()}let i=u();try{for(;!l(n);)await d(i);let a=setInterval(()=>{s()?.id===n&&c(n)},r);try{return await e()}finally{clearInterval(a),s()?.id===n&&localStorage.removeItem(t),i?.postMessage({type:`released`})}}finally{i?.close()}},p=async t=>{let n=typeof navigator>`u`?void 0:navigator.locks;return n&&typeof n.request==`function`?await n.request(e,{mode:`exclusive`},()=>t()):f(t)};export{e as REFRESH_LOCK_NAME,p as withCrossTabRefreshLock};
|
package/dist/api/designSample.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getConfigValue as e}from"../config/index.js";var
|
|
1
|
+
import{getConfigValue as e}from"../config/index.js";import{syncSessionStorage as t}from"../storage/index.js";var n=`designSample`,r=`Design-Sample`,i=`webority.designSample`,a=!1,o=()=>{if(e(`environment`)===`Production`)return null;if(!a){a=!0;let e=new URLSearchParams(window.location.search).get(n);e&&t.setItem(i,e)}return t.getItem(i)},s=e=>{e.interceptors.request.use(e=>{let t=o();return t&&!e.headers.has(`Design-Sample`)&&e.headers.set(r,t),e})};export{r as DESIGN_SAMPLE_HEADER,n as DESIGN_SAMPLE_QUERY_KEY,i as DESIGN_SAMPLE_STORAGE_KEY,s as applyDesignSample,o as readDesignSampleTicket};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{extractApiError as e}from"../errors/extractApiError.js";import{readBlobErrorBody as t}from"./blobErrorBody.js";var n=/filename="((?:[^"\\]|\\.)*)"/i,r=/filename=([^;]+)/i,i=/filename\*=([^']*)'[^']*'([^;]+)/i,a=/%(?![0-9A-Fa-f]{2})/,o=/(?:%[0-9A-Fa-f]{2})+/g,s=e=>{if(a.test(e))return null;let t=!1,n=e.replace(o,e=>{let n=Uint8Array.from(e.slice(1).split(`%`),e=>Number.parseInt(e,16)),r=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}).decode(n);return new TextEncoder().encode(r).join(`,`)!==n.join(`,`)&&(t=!0),r});return t?null:n},c=e=>{let t=i.exec(e)?.[2]?.trim(),a=t?s(t):null;return a===null?(n.exec(e)?.[1]?.replace(/\\(.)/g,`$1`)??r.exec(e)?.[1]?.trim())||null:a},l=async(n,r)=>{let i,a;try{let e=await n.request({...r,responseType:`blob`});i=e.data,a=e.headers[`content-disposition`]}catch(n){throw await t(n),e(n)}if(!(i instanceof Blob))throw Error(`downloadFile: "${r.url??``}" answered without a file body.`);return{blob:i,fileName:typeof a==`string`?c(a):null}};export{c as contentDispositionFileName,l as downloadFile};
|
|
@@ -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{ACCOUNT_ID_HEADER as
|
|
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{Logger as e}from"../logger/logger.js";var t=`Min-App-Version`,n=null,r=/* @__PURE__ */ new Set,i=()=>n,a=e=>(r.add(e),n!==null&&e(n),()=>{r.delete(e)}),o=e=>{if(!e
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";var t=`Min-App-Version`,n=null,r=/* @__PURE__ */ new Set,i=()=>n,a=e=>(r.add(e),n!==null&&e(n),()=>{r.delete(e)}),o=e=>typeof e==`object`&&!!e,s=e=>{if(!o(e))return;let n=e.get;return typeof n==`function`?n.call(e,t):e[t.toLowerCase()]},c=i=>{let a=s(i);if(a==null||a===``)return;let o=String(a).trim();if(!/^\d+$/.test(o)){e.warn(`[minAppVersion] ignored a non-integer ${t}: ${o}`);return}let c=Number.parseInt(o,10);if(c!==n){n=c;for(let t of[...r])try{t(c)}catch(t){e.error(`[minAppVersion] a listener threw`,t)}}},l=e=>{e.interceptors.response.use(e=>(c(e.headers),e),e=>(c(o(e)&&o(e.response)?e.response.headers:void 0),Promise.reject(e)))};export{t as MIN_APP_VERSION_HEADER,a as addMinAppVersionListener,i as getMinAppVersion,l as readMinAppVersion};
|
|
@@ -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
|
|
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};
|
package/dist/api/retry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getConfigValue as e}from"../config/index.js";import{isWorkspaceChangedResponse as t}from"./workspaceChanged.js";import n from"axios";var r=`Idempotency-Key`,i=e=>typeof e==`number`&&(e===429||e>=500&&e<=599),a=/* @__PURE__ */ new Set([`get`,`head`,`options`,`put`,`delete`]),o=/* @__PURE__ */ new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`ENETUNREACH`,`EHOSTUNREACH`]),s=e=>!e.response&&typeof e.code==`string`&&o.has(e.code),c=3e4,l=e=>{let t=e.response;if(!t)return null;let n=t.headers
|
|
1
|
+
import{getConfigValue as e}from"../config/index.js";import{isWorkspaceChangedResponse as t}from"./workspaceChanged.js";import n from"axios";var r=`Idempotency-Key`,i=e=>typeof e==`number`&&(e===429||e>=500&&e<=599),a=/* @__PURE__ */ new Set([`get`,`head`,`options`,`put`,`delete`]),o=/* @__PURE__ */ new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`ENETUNREACH`,`EHOSTUNREACH`]),s=e=>!e.response&&typeof e.code==`string`&&o.has(e.code),c=3e4,l=e=>typeof e==`object`&&!!e,u=(e,t)=>{if(!l(e))return;let n=e.get;return typeof n==`function`?n.call(e,t):e[t]},d=e=>{let t=e.response;if(!t)return null;let n=u(t.headers,`retry-after`),r=Number(n);return n!=null&&Number.isFinite(r)&&r>0?r*1e3:null},f=e=>{let t=u(e?.headers,r);return typeof t==`string`&&t!==``},p=e=>{if(n.isCancel(e)||e.code===`ERR_CANCELED`)return!1;if(s(e))return!0;let t=(e.config?.method??`get`).toLowerCase(),r=a.has(t),o=e.response?.status;if(o===void 0)return r;if(!i(o))return!1;let l=d(e);return l!==null&&l>c?!1:r||(o===429||o===503)&&f(e.config)},m={retryDelayMs:e=>e<=1?0:Math.random()*Math.min(3e4,1e3*2**e),shouldRetry:p,onRetry:()=>void 0},h=(e,t)=>new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener?.(`abort`,r),n(!0)},e);t?.addEventListener?.(`abort`,r,{once:!0})}),g=(r,i={})=>{r.interceptors.response.use(void 0,async a=>{if(!n.isAxiosError(a))return Promise.reject(a);let o=a,s=o.config;if(!s||s.retry===!1)return Promise.reject(a);let c=typeof s.retry==`object`?s.retry:{},l={...m,retries:e(`retries`),...i,...c},u=(s.__retryAttempt??0)+1;return t(o)||u>l.retries||!l.shouldRetry(o)||s.signal?.aborted||(s.__retryAttempt=u,s.transformRequest=[e=>e],l.onRetry(u,o),!await h(d(o)??l.retryDelayMs(u),s.signal))?Promise.reject(a):r.request(s)})};export{r as IDEMPOTENCY_KEY_HEADER,g as attachRetry,s as isNeverSentError,p as isRetryableFailure,i as isRetryableStatus,d as retryAfterMs};
|
package/dist/api/tokenRefresh.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACCESS_TOKEN_KEY as e,REFRESH_TOKEN_KEY as t,clearSession as n,getToken as r,storeToken as i}from"../auth/authStore.js";import{Logger as a}from"../logger/logger.js";import{withCrossTabRefreshLock as o}from"./crossTabRefreshLock.js";import s from"./publicClient.js";import c from"axios";var l=`session_revoked`,u=`session_expired`,d=class e extends Error{constructor(t){super(t),this.name=`SessionEndedError`,Object.setPrototypeOf(this,e.prototype)}},f,p,m=e=>{f=e},h=e=>{p=e},g=null,_=[],v=(e,t=null)=>{_.forEach(({resolve:n,reject:r})=>{e?r(e):t!==null&&n(t)}),_=[]},y=()=>{g=null,v(new d(`[@webority/web-core] Session ended`))},b=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,x=()=>{if(!f||!p)throw Error(`User package store is not initialized. Call initUserAuth first.`);return{store:f,auth:p}},S=()=>p?.accountId,C=()=>p?.refresh.path,w=async()=>{let e=x();await e.store.dispatch(e.auth.logout())},T=async(e,t,r)=>{await n(e,{code:t,detail:r}),await w()},E=e=>{let t=e&&typeof e==`object
|
|
1
|
+
import{ACCESS_TOKEN_KEY as e,REFRESH_TOKEN_KEY as t,clearSession as n,getToken as r,storeToken as i}from"../auth/authStore.js";import{Logger as a}from"../logger/logger.js";import{withCrossTabRefreshLock as o}from"./crossTabRefreshLock.js";import s from"./publicClient.js";import c from"axios";var l=`session_revoked`,u=`session_expired`,d=class e extends Error{constructor(t){super(t),this.name=`SessionEndedError`,Object.setPrototypeOf(this,e.prototype)}},f,p,m=e=>{f=e??void 0},h=e=>{p=e},g=null,_=[],v=(e,t=null)=>{_.forEach(({resolve:n,reject:r})=>{e?r(e):t!==null&&n(t)}),_=[]},y=()=>{g=null,v(new d(`[@webority/web-core] Session ended`))},b=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,x=()=>{if(!f||!p)throw Error(`User package store is not initialized. Call initUserAuth first.`);return{store:f,auth:p}},S=()=>p?.accountId,C=()=>p?.refresh.path,w=async()=>{let e=x();await e.store.dispatch(e.auth.logout())},T=async(e,t,r)=>{await n(e,{code:t,detail:r}),await w()},E=e=>{let t=e&&typeof e==`object`&&`code`in e?e.code:void 0;return t===`session_revoked`||t===`session_expired`?t:null},D=e=>{let t=e&&typeof e==`object`&&`detail`in e?e.detail:void 0;return typeof t==`string`&&t!==``&&E(e)!==null?t:null},O=e=>{if(!c.isAxiosError(e)||!e.response)return null;let t=e.response.data,n=t&&typeof t==`object`&&`code`in t?t.code:void 0;return typeof n==`string`&&p?.endSessionOn?.includes(n)?n:null},k=()=>g!==null,A=0,j=Promise.resolve(),M=null,N=()=>{A===0&&(j=new Promise(e=>{M=e})),A+=1;let e=!1;return()=>{e||(e=!0,--A,A===0&&(M?.(),M=null))}},P=()=>A===0?Promise.resolve():j,F=class e extends Error{constructor(t){super(`A session-replacing response carried no tokens: ${t}`),this.name=`ReplacementTokensMissingError`,Object.setPrototypeOf(this,e.prototype)}},I=async n=>{let r;try{r=(p?.refresh.readTokens??G)(n)}catch(e){throw new F(b(e))}await i(e,r.accessToken,r.accessTokenExpiry),await i(t,r.refreshToken,r.refreshTokenExpiry)},L=async e=>{let t=(await r(`accessToken`))?.token??null;return t!==null&&t!==e?t:null},R=()=>new Promise((e,t)=>{_.push({resolve:e,reject:t})}),z=e=>e instanceof d||c.isAxiosError(e)&&(e.response?.status===400||e.response?.status===401),B=e=>!c.isAxiosError(e)||e.response?.status!==401?null:E(e.response.data),V=e=>!c.isAxiosError(e)||e.response?.status!==401?null:D(e.response.data),H=e=>z(e)||O(e)!==null,U=e=>c.isAxiosError(e)?E(e.response?.data)??`status ${e.response?.status}`:b(e),W=(e,t)=>{if(typeof e!=`string`||e===``)throw Error(`The refresh response has no "${t}".`);return e},G=e=>{if(typeof e!=`object`||!e)throw Error(`The refresh response is not an object.`);return{accessToken:W(`accessToken`in e?e.accessToken:void 0,`accessToken`),accessTokenExpiry:W(`accessTokenExpiration`in e?e.accessTokenExpiration:void 0,`accessTokenExpiration`),refreshToken:W(`refreshToken`in e?e.refreshToken:void 0,`refreshToken`),refreshTokenExpiry:W(`refreshTokenExpiration`in e?e.refreshTokenExpiration:void 0,`refreshTokenExpiration`)}},K=async n=>{await P();let o=await r(t);if(!o?.token)throw new d(`No refresh token available`);if(Date.parse(o.expiry)<=Date.now())throw new d(`Refresh token expired`);let c={accessToken:(await r(`accessToken`))?.token??null,refreshToken:o.token},l=n.body?await n.body(c):c,u=n.headers?await n.headers():void 0;a.info(`Refreshing the access token`);let{data:f}=await s.post(n.path,l,{...u?{headers:u}:{},skipErrorLog:!0}),p=(n.readTokens??G)(f);await P();let m=(await r(`refreshToken`))?.token===o.token?null:await r(e);return m?.token?(a.info(`Keeping the session that replaced this one during the refresh`),m.token):(await i(e,p.accessToken,p.accessTokenExpiry),await i(t,p.refreshToken,p.refreshTokenExpiry),a.info(`Access token refreshed`),p.accessToken)},q=3e4,J=async(t,n)=>{let i=await r(e);return i?.token&&i.token!==n&&Date.parse(i.expiry)>Date.now()+q?(a.info(`Adopting the access token another tab refreshed`),i.token):K(t)},Y=()=>{if(g)return g;let e=(async()=>{let e=null;try{let{refresh:t}=x().auth;e=(await r(`accessToken`))?.token??null;let n=await o(()=>J(t,e));return v(null,n),n}catch(t){if(z(t)){await P();let t=null;try{t=await L(e)}catch(e){a.error(`Reading the stored token after a failed refresh failed:`,b(e))}if(t)return a.info(`The session was replaced during the refresh; continuing with the new one`),v(null,t),t}let n=O(t);if(n!==null)throw a.info(`Session ended, the refresh was refused: ${n}`),v(t,null),await T(`terminated`,n,D(c.isAxiosError(t)?t.response?.data:void 0)),t;let r=z(t);if(r)a.info(`Session ended, the refresh was refused:`,U(t));else{let e=c.isAxiosError(t)?t.response?.data:void 0;a.error(`Token refresh failed:`,e??b(t))}throw v(t,null),r&&await T(`rejected`,B(t),V(t)),t}})().finally(()=>{g===e&&(g=null)});return g=e,e};export{u as SESSION_EXPIRED_CODE,l as SESSION_REVOKED_CODE,d as SessionEndedError,N as beginSessionReplacement,L as currentTokenIfReplaced,w as dispatchLogout,T as endSessionAndLogout,O as endSessionCodeOf,S as getAccountIdProvider,b as getErrorMessage,C as getRefreshPath,m as injectStore,h as injectUserAuth,k as isRefreshInFlight,H as isSessionEnd,R as queueBehindRefresh,Y as refreshAccessToken,y as resetRefreshState,E as sessionCodeOf,D as sessionDetailOf,I as storeReplacementSession,P as waitForSessionReplacement};
|
package/dist/api/userClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACCESS_TOKEN_KEY as e,getToken as t}from"../auth/authStore.js";import{Logger as n}from"../logger/logger.js";import{getLastKnownNetworkStatus as r}from"../network/networkStatus.js";import{applyConfiguredBaseUrl as i}from"./baseUrl.js";import{applyClientHeaders as a,readAccountId as o,stampAccountId as s}from"./clientHeaders.js";import{applyDesignSample as c}from"./designSample.js";import{readMinAppVersion as l}from"./minAppVersion.js";import{sendFormDataAsMultipart as u}from"./multipart.js";import{applyRequestDefaults as d}from"./requestDefaults.js";import{responseBodyText as f}from"./responseBodyText.js";import{attachRetry as p}from"./retry.js";import{SESSION_EXPIRED_CODE as m,SESSION_REVOKED_CODE as h,SessionEndedError as g,beginSessionReplacement as _,currentTokenIfReplaced as v,endSessionAndLogout as y,endSessionCodeOf as b,getAccountIdProvider as x,getErrorMessage as S,getRefreshPath as C,injectStore as w,injectUserAuth as T,isRefreshInFlight as E,isSessionEnd as D,queueBehindRefresh as O,refreshAccessToken as k,resetRefreshState as A,sessionCodeOf as j,sessionDetailOf as M,storeReplacementSession as N,waitForSessionReplacement as P}from"./tokenRefresh.js";import{WorkspaceChangedError as F,isWorkspaceChangedResponse as I,workspaceChangedFromResponse as L}from"./workspaceChanged.js";import R,{AxiosHeaders as z}from"axios";var B=class e extends Error{constructor(t=`Request blocked: device is offline`){super(t),this.name=`RequestOfflineError`,Object.setPrototypeOf(this,e.prototype)}},V=class e extends Error{constructor(){super(`No access token available`),this.name=`NoAccessTokenError`,Object.setPrototypeOf(this,e.prototype)}},H=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},U=e=>{let t=e.headers instanceof z?e.headers.get(`Authorization`):void 0;return typeof t==`string`&&t.startsWith(`Bearer `)?t.slice(7):null},
|
|
1
|
+
import{ACCESS_TOKEN_KEY as e,getToken as t}from"../auth/authStore.js";import{Logger as n}from"../logger/logger.js";import{getLastKnownNetworkStatus as r}from"../network/networkStatus.js";import{applyConfiguredBaseUrl as i}from"./baseUrl.js";import{applyClientHeaders as a,readAccountId as o,stampAccountId as s}from"./clientHeaders.js";import{applyDesignSample as c}from"./designSample.js";import{readMinAppVersion as l}from"./minAppVersion.js";import{sendFormDataAsMultipart as u}from"./multipart.js";import{applyRequestDefaults as d}from"./requestDefaults.js";import{responseBodyText as f}from"./responseBodyText.js";import{attachRetry as p}from"./retry.js";import{SESSION_EXPIRED_CODE as m,SESSION_REVOKED_CODE as h,SessionEndedError as g,beginSessionReplacement as _,currentTokenIfReplaced as v,endSessionAndLogout as y,endSessionCodeOf as b,getAccountIdProvider as x,getErrorMessage as S,getRefreshPath as C,injectStore as w,injectUserAuth as T,isRefreshInFlight as E,isSessionEnd as D,queueBehindRefresh as O,refreshAccessToken as k,resetRefreshState as A,sessionCodeOf as j,sessionDetailOf as M,storeReplacementSession as N,waitForSessionReplacement as P}from"./tokenRefresh.js";import{WorkspaceChangedError as F,isWorkspaceChangedResponse as I,workspaceChangedFromResponse as L}from"./workspaceChanged.js";import R,{AxiosHeaders as z}from"axios";var B=class e extends Error{constructor(t=`Request blocked: device is offline`){super(t),this.name=`RequestOfflineError`,Object.setPrototypeOf(this,e.prototype)}},V=class e extends Error{constructor(){super(`No access token available`),this.name=`NoAccessTokenError`,Object.setPrototypeOf(this,e.prototype)}},H=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},U=e=>R.isAxiosError(e)||e instanceof F?e.config:void 0,W=e=>{let t=e.headers instanceof z?e.headers.get(`Authorization`):void 0;return typeof t==`string`&&t.startsWith(`Bearer `)?t.slice(7):null},G=R.create({headers:{"Content-Type":`application/json`}});l(G),p(G);var K=(e,t)=>{e.headers=z.from(e.headers).set(`Authorization`,`Bearer ${t}`)},q=e=>{let t=C();return!!t&&!!e?.includes(t)};i(G),d(G),u(G),a(G),c(G),G.interceptors.request.use(async i=>{let a=i;if(H(a),(await r()).isConnected===!1)return n.warn(`Request blocked: browser is offline. URL: ${i.url}`),Promise.reject(new B);try{if(q(i.url))return i;await s(a,x());let r=await t(e);if(!r?.token)throw new V;let o=Date.now();return Date.parse(r.expiry)<=o+3e4?(n.info(`Access token expired or about to expire, refreshing before request`),K(i,await k())):K(i,r.token),i.replacesSession&&(a._endReplacement=_()),i}catch(e){return e instanceof V?n.info(`Request not sent: signed out. URL: ${i.url}`):D(e)||n.error(`Failed to attach token:`,S(e)),Promise.reject(e)}},e=>(n.error(`Request error:`,S(e)),Promise.reject(e))),G.interceptors.response.use(async e=>{let t=e.config;if(t._endReplacement)try{await N(e.data)}finally{H(t)}return e},async e=>{if(H(U(e)),R.isCancel(e)||e instanceof B||e instanceof V||e instanceof g||e instanceof F)return Promise.reject(e);if(!R.isAxiosError(e))return n.error(`Non-axios error in response interceptor: ${S(e)}`),Promise.reject(e);let t=e,r=t.config;if(!t.response)return r?.skipErrorLog||n.error(`Network error or no response from server: ${t.message}, URL: ${r?.url}`),Promise.reject(e);if(I(t))return n.info(`Request refused: the workspace changed after it was made. URL: ${r?.url}`),Promise.reject(L(t));if(q(r?.url))return Promise.reject(e);if(t.response.status===401&&r&&!r._replayedWithCurrentToken&&!r.replacesSession&&(await P(),await v(W(r))))return(r._accountId??null)===await o(x())?(n.info(`Session changed while the request was in flight; sending it again. URL: ${r.url}`),r._replayedWithCurrentToken=!0,G(r)):(n.info(`Session moved to another workspace while the request was in flight; not sending it again. URL: ${r.url}`),Promise.reject(new F(void 0,{config:r,cause:e})));let i=b(t);if(i!==null)return n.warn(`Session ended by ${i}, logging out. URL: ${r?.url}`),A(),await y(`terminated`,i,M(t.response?.data)),Promise.reject(e);if(t.response.status===401&&r&&!r._retry){let i=j(t.response.data);if(i!==null)return n.warn(`Session ${i}, logging out without refresh. URL: ${r.url}`),A(),await y(`terminated`,i,M(t.response.data)),Promise.reject(e);if(n.warn(`Unauthorized URL: ${r.url}`),r._retry=!0,E())return O().then(e=>(n.info(`Retrying request after token refresh:`,r.url),K(r,e),G(r))).catch(e=>(!D(e)&&!(e instanceof F)&&n.error(`Failed to retry request after token refresh:`,S(e)),Promise.reject(e)));try{return K(r,await k()),G(r)}catch(e){return Promise.reject(e)}}if(!r?.skipErrorLog){let e=`Response error: ${f(t.response?.data,t.message)}, URL: ${r?.url}, Status: ${t.response.status}`;r?.expectedStatuses?.includes(t.response.status)?n.debug(e):n.error(e)}return Promise.reject(e)});export{B as RequestOfflineError,m as SESSION_EXPIRED_CODE,h as SESSION_REVOKED_CODE,G as default,w as injectStore,T as injectUserAuth,A as resetRefreshState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`workspace_changed`,t=e=>
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},t=/\{([^{}]+)\}/g;function n(n,r){let i=n.path.replace(t,(t,i)=>{let a=r.path?.[i],o=a===void 0?``:String(a);if(o===``)throw new e(`${n.method} ${n.path} needs a non-empty path value for "${i}"`);if(o===`.`||o===`..`)throw new e(`${n.method} ${n.path} needs a path value for "${i}" other than "." or ".."`);return encodeURIComponent(o)});return{method:n.method,url:i,params:r.query,headers:r.headers,data:r.body,responseType:n.replyKind===`blob`?`blob`:`json`}}export{e as ContractCallError,n as buildContractRequest};
|
|
@@ -0,0 +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===``||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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{initAppInsights}from"./appInsights.js";
|
package/dist/auth/authStore.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger as e}from"../logger/logger.js";import{getJWTExpiry as t}from"./jwt.js";var n=`accessToken`,r=`refreshToken`,i=`sessionUser`,a=2592e6,o=/* @__PURE__ */ new Set([n,r,i]),s=null,c=()=>globalThis.localStorage,l=()=>globalThis.sessionStorage,u=(e,t)=>{try{return e().getItem(t)}catch{return null}},d=(e,t)=>{try{e().removeItem(t)}catch{}},f=()=>s===null?u(c,`refreshToken`)!==null||u(c,`accessToken`)!==null:s,p=()=>f()?c:l,m=()=>f()?l:c,h=t=>{let n=s;s=t;let r=p(),i=m();for(let t of o){let a=u(i,t);if(a!==null)try{r().setItem(t,a),d(i,t)}catch(r){throw s=n,e.error(`[authStore] could not move "${t}" to the chosen store`,r),r}}},g=/* @__PURE__ */ new Set,_=`sessionEnded`,v=()=>u(l,_)!==null,y=(t,n)=>{try{l().setItem(_,t)}catch{}for(let r of[...g])try{r(t,n)}catch(t){e.error(`[authStore] a session-ended listener threw`,t)}},b=e=>{if(e.storageArea!==c())return;let t=e.key===`refreshToken`&&e.oldValue!==null&&e.newValue===null;(e.key===null||t)&&u(l,`refreshToken`)===null&&y(`otherTab`,{code:null,detail:null})},x=e=>(g.size===0&&typeof window<`u`&&window.addEventListener(`storage`,b),g.add(e),()=>{g.delete(e),g.size===0&&typeof window<`u`&&window.removeEventListener(`storage`,b)}),S=async(t,n,r)=>{try{p()().setItem(t,JSON.stringify({token:n,expiry:r})),d(m(),t),d(l,_)}catch(n){throw e.error(`Error storing token for key: ${t}`,n),n}},C=e=>{try{let t=JSON.parse(e);return t
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";import{getJWTExpiry as t}from"./jwt.js";var n=`accessToken`,r=`refreshToken`,i=`sessionUser`,a=2592e6,o=/* @__PURE__ */ new Set([n,r,i]),s=null,c=()=>globalThis.localStorage,l=()=>globalThis.sessionStorage,u=(e,t)=>{try{return e().getItem(t)}catch{return null}},d=(e,t)=>{try{e().removeItem(t)}catch{}},f=()=>s===null?u(c,`refreshToken`)!==null||u(c,`accessToken`)!==null:s,p=()=>f()?c:l,m=()=>f()?l:c,h=t=>{let n=s;s=t;let r=p(),i=m();for(let t of o){let a=u(i,t);if(a!==null)try{r().setItem(t,a),d(i,t)}catch(r){throw s=n,e.error(`[authStore] could not move "${t}" to the chosen store`,r),r}}},g=/* @__PURE__ */ new Set,_=`sessionEnded`,v=()=>u(l,_)!==null,y=(t,n)=>{try{l().setItem(_,t)}catch{}for(let r of[...g])try{r(t,n)}catch(t){e.error(`[authStore] a session-ended listener threw`,t)}},b=e=>{if(e.storageArea!==c())return;let t=e.key===`refreshToken`&&e.oldValue!==null&&e.newValue===null;(e.key===null||t)&&u(l,`refreshToken`)===null&&y(`otherTab`,{code:null,detail:null})},x=e=>(g.size===0&&typeof window<`u`&&window.addEventListener(`storage`,b),g.add(e),()=>{g.delete(e),g.size===0&&typeof window<`u`&&window.removeEventListener(`storage`,b)}),S=async(t,n,r)=>{try{p()().setItem(t,JSON.stringify({token:n,expiry:r})),d(m(),t),d(l,_)}catch(n){throw e.error(`Error storing token for key: ${t}`,n),n}},C=e=>typeof e==`object`&&!!e&&`token`in e&&typeof e.token==`string`&&`expiry`in e&&typeof e.expiry==`string`,w=e=>{try{let t=JSON.parse(e);return C(t)?t:null}catch{return null}},T=e=>u(l,e)??u(c,e),E=async t=>{let n=T(t);return n===null&&M(t)&&R()&&(n=T(t)),n===null?null:w(n)||(e.warn(`Stored credentials for key "${t}" are not a valid token; clearing them.`),M(t)?await z(`corrupt`,!0):await O(t),null)},D=()=>{T(`refreshToken`)===null&&T(`accessToken`)===null&&R();let e=T(r);if(e!==null&&w(e)!==null)return!0;let t=T(n),i=t===null?null:w(t);if(i===null)return!1;let a=Date.parse(i.expiry);return Number.isNaN(a)||a>Date.now()},O=async e=>{d(c,e),d(l,e)},k=async t=>{try{p()().setItem(i,JSON.stringify(t)),d(m(),i)}catch(t){throw e.error(`Error storing the session user`,t),t}},A=async t=>{let n=T(i);if(n===null)return null;let r;try{r=JSON.parse(n)}catch{return e.warn(`The stored session user is not valid JSON; clearing it.`),await j(),null}return r===null?null:t(r)},j=async()=>{d(c,i),d(l,i)},M=e=>e===`accessToken`||e===`refreshToken`,N=null,P=!1,F=e=>{N=e,P=!1},I=e=>{let t=w(e);if(t)return t;let n=e;try{let t=JSON.parse(e);typeof t==`string`&&(n=t)}catch{}return n.trim()===``?null:{token:n,expiry:null}},L=e=>e.split(`.`).length===3?t(e)?.toISOString()??null:null,R=()=>{if(!N||P)return!1;P=!0;let t=N,a=[c,l].every(e=>u(e,`accessToken`)===null&&u(e,`refreshToken`)===null),o=!1;for(let s of[c,l]){let l=u(s,t.accessToken),f=u(s,t.refreshToken),p=t.sessionUser?u(s,t.sessionUser):null,m=!1;if(a&&!o&&(l!==null||f!==null))try{let t=l===null?null:I(l),a=f===null?null:I(f);if(t){let e=t.expiry??L(t.token)??(/* @__PURE__ */ new Date()).toISOString();s().setItem(n,JSON.stringify({token:t.token,expiry:e}))}if(a){let e=a.expiry??L(a.token)??new Date(Date.now()+2592e6).toISOString();s().setItem(r,JSON.stringify({token:a.token,expiry:e}))}p!==null&&s().setItem(i,p),o=t!==null||a!==null,o&&e.breadcrumb(`[authStore] moved a session from the legacy token keys`,{store:s===c?`localStorage`:`sessionStorage`})}catch(t){m=!0,d(s,n),d(s,r),e.error(`[authStore] could not move the session from the legacy token keys`,t)}if(!m)for(let e of[t.accessToken,t.refreshToken,t.sessionUser])e&&d(s,e)}return o},z=async(e,t,i=null,a=null)=>{let o=t||await E(`accessToken`)!==null||await E(`refreshToken`)!==null;await O(n),await O(r),await j(),s=null,(o||t)&&y(e,{code:i,detail:a})},B=async(e=`signedOut`,t={})=>z(e,!1,t.code??null,t.detail??null);export{n as ACCESS_TOKEN_KEY,a as LEGACY_REFRESH_TOKEN_LIFETIME_MS,r as REFRESH_TOKEN_KEY,i as SESSION_USER_KEY,x as addSessionEndedListener,B as clearSession,f as getKeepSignedIn,A as getSessionUser,E as getToken,D as hasSession,v as hasSessionEndedInTab,j as removeSessionUser,O as removeToken,h as setKeepSignedIn,F as setLegacyTokenKeys,k as storeSessionUser,S as storeToken};
|
package/dist/auth/jwt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger as e}from"../logger/logger.js";var t=e=>(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=e=>{try{return decodeURIComponent(e.split(``).map(e=>`%${e.charCodeAt(0).toString(16).padStart(2,`0`)}`).join(``))}catch{return e}},r=r=>{if(!
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";var t=e=>(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=e=>{try{return decodeURIComponent(e.split(``).map(e=>`%${e.charCodeAt(0).toString(16).padStart(2,`0`)}`).join(``))}catch{return e}},r=e=>typeof e==`object`&&!!e&&!Array.isArray(e),i=e=>typeof e==`string`,a=e=>typeof e==`number`,o=e=>i(e)||Array.isArray(e)&&e.every(i),s=(t,n,r)=>n===void 0||r(n)?!0:(e.warn(`[jwt] decodeJWT: claim "${t}" has the wrong type`),!1),c=e=>{let{sub:t,exp:n,iat:r,nbf:c,iss:l,aud:u,...d}=e;return!s(`sub`,t,i)||!s(`exp`,n,a)||!s(`iat`,r,a)||!s(`nbf`,c,a)||!s(`iss`,l,i)||!s(`aud`,u,o)?null:{sub:t,exp:n,iat:r,nbf:c,iss:l,aud:u,...d}},l=i=>{if(!i||typeof i!=`string`)return null;let a=i.split(`.`),o=a.length===3?a[1]:void 0;if(o===void 0)return e.warn(`[jwt] decodeJWT: token is not a valid JWT (expected 3 segments)`),null;let s;try{let e=n(atob(t(o)));s=JSON.parse(e)}catch(t){return e.warn(`[jwt] decodeJWT failed to parse payload`,t),null}return r(s)?c(s):(e.warn(`[jwt] decodeJWT: payload is not a JSON object`),null)};function u(e,t){let n=l(e);return n===null||t===void 0?n:t(n)}var d=(e,t=30)=>{let n=u(e);if(!n||typeof n.exp!=`number`)return!0;let r=Math.floor(Date.now()/1e3);return n.exp<=r+t},f=e=>{let t=u(e);return!t||typeof t.exp!=`number`?null:/* @__PURE__ */ new Date(t.exp*1e3)};export{u as decodeJWT,f as getJWTExpiry,d as isJWTExpired};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
at `)
|
|
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;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/errors/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import{CONTRACT_ERROR_CODE as e,NETWORK_CODE as t,OFFLINE_CODE as n,OFFLINE_MESSAGE as r,REQUEST_CANCELED_CODE as i,SERVER_FAILURE_MESSAGE as a,TIMEOUT_CODE as o,TIMEOUT_MESSAGE as s,UNEXPECTED_MESSAGE as c,UNREACHABLE_MESSAGE as l,apiErrorMessage as u,extractApiError as d,isApiError as f,isNoResponse as p,toFieldPath as m}from"./extractApiError.js";import{parseResponse as h}from"./parseResponse.js";export{e as CONTRACT_ERROR_CODE,t as NETWORK_CODE,n as OFFLINE_CODE,r as OFFLINE_MESSAGE,i as REQUEST_CANCELED_CODE,a as SERVER_FAILURE_MESSAGE,o as TIMEOUT_CODE,s as TIMEOUT_MESSAGE,c as UNEXPECTED_MESSAGE,l as UNREACHABLE_MESSAGE,u as apiErrorMessage,d as extractApiError,f as isApiError,p as isNoResponse,h as parseResponse,m as toFieldPath};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";var t=`The server returned unexpected data. Please try again.`;function n(n,r,i){let a=n.safeParse(r);if(a.success)return a.data;throw e.error(`[contract] ${i} response failed validation`,a.error.issues),Object.assign(/* @__PURE__ */ Error(t),{isContractError:!0})}export{n as parseResponse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return typeof navigator<`u`&&navigator.onLine===!1}export{e as isOfflineFailure};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{configuredLocale as e,getFormatterConfig as t,isFormatterConfigured as n,numberSeparators as r,styledNumber as i}from"./formatConfig.js";import{numberFormat as a}from"./intlCache.js";var o=()=>typeof Intl<`u`&&typeof Intl.NumberFormat==`function`,s=(e,t)=>{let{decimal:n,group:i}=r()??{decimal:`.`,group:`,`},a=e<0?`-`:``,[o
|
|
1
|
+
import{configuredLocale as e,getFormatterConfig as t,isFormatterConfigured as n,numberSeparators as r,styledNumber as i}from"./formatConfig.js";import{numberFormat as a}from"./intlCache.js";var o=()=>typeof Intl<`u`&&typeof Intl.NumberFormat==`function`,s=(e,t)=>{let{decimal:n,group:i}=r()??{decimal:`.`,group:`,`},a=e<0?`-`:``,[o=`0`,s=``]=Math.abs(e).toFixed(t).split(`.`),c=o.length>3?o.slice(-3):o,l=o.length>3?o.slice(0,-3):``;return a+(l?l.replace(/\B(?=(\d{2})+(?!\d))/g,i)+i+c:c)+(s?`${n}${s}`:``)},c=e=>{if(e==null||typeof e==`string`&&e.trim()===``)return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},l=(e,t)=>a(e,{style:`currency`,currency:t}).resolvedOptions().maximumFractionDigits??2,u=(r,u)=>{let{currency:d,locale:f=e()??`en-IN`,minimumFractionDigits:p,maximumFractionDigits:m,stripSymbol:h=!1,empty:g=n(`locale`)||n(`empty`)?t().empty:``,..._}=u;if(!d)throw TypeError(`[@webority/web-core] formatCurrency needs options.currency, an ISO 4217 code such as "INR".`);let v=c(r);if(v===null)return g;if(o())try{let e=m??l(f,d),t=p??(Number.isInteger(v)?0:e),n=i(a(f,{..._,style:`currency`,currency:d,minimumFractionDigits:t,maximumFractionDigits:Math.max(t,e)}),v);return h?n.replace(/[^\d,.\s\-+]/g,``).trim():n}catch(e){throw RangeError(`formatCurrency: currency "${d}" or locale "${f}" is not valid: ${e instanceof Error?e.message:String(e)}`)}let y=s(v,p??(Number.isInteger(v)?0:2));return h?y:d===`INR`?`₹${y}`:`${d} ${y}`};export{u as formatCurrency};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e={zone:`IST`,locale:`en-IN`,empty:`-`},t={PointWithCommaGroups:{decimal:`.`,group:`,`},CommaWithPointGroups:{decimal:`,`,group:`.`},CommaWithSpaceGroups:{decimal:`,`,group:`\xA0`},PointWithSpaceGroups:{decimal:`.`,group:`\xA0`}},n=[`DayMonthNameYear`,`DayMonthYear`,`MonthDayYear`,`YearMonthDay`],r={...e},
|
|
1
|
+
var e={zone:`IST`,locale:`en-IN`,empty:`-`},t={PointWithCommaGroups:{decimal:`.`,group:`,`},CommaWithPointGroups:{decimal:`,`,group:`.`},CommaWithSpaceGroups:{decimal:`,`,group:`\xA0`},PointWithSpaceGroups:{decimal:`.`,group:`\xA0`}},n=[`DayMonthNameYear`,`DayMonthYear`,`MonthDayYear`,`YearMonthDay`],r=e=>{if(e===`IST`||e===`viewer`||e===`UTC`)return!0;try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e}),!0}catch(e){if(e instanceof RangeError)return!1;throw e}},i=[`zone`,`locale`,`empty`,`numberStyle`,`dateOrder`],a=e=>i.some(t=>t===e),o={...e},s=/* @__PURE__ */ new Set,c=c=>{if(c===void 0)o={...e},s=/* @__PURE__ */ new Set;else{if(c.zone!==void 0&&!r(c.zone))throw RangeError(`Unknown zone "${c.zone}"; expected IST, viewer, UTC or an IANA zone name.`);if(c.numberStyle!==void 0&&!Object.hasOwn(t,c.numberStyle))throw RangeError(`Unknown number style "${c.numberStyle}"; expected one of ${Object.keys(t).join(`, `)}.`);if(c.dateOrder!==void 0&&!n.includes(c.dateOrder))throw RangeError(`Unknown date order "${c.dateOrder}"; expected one of ${n.join(`, `)}.`);for(let e of Object.keys(c)){if(!a(e))throw RangeError(`Unknown setting "${e}"; expected one of ${i.join(`, `)}.`);let t=c[e];t!==void 0&&(o={...o,[e]:t},s.add(e))}}},l=()=>({...o}),u=e=>s.has(e),d=()=>s.has(`locale`)?o.locale:null,f=e=>/-IN(?:-|$)/i.test(e)?`indian`:`international`,p=()=>o.numberStyle===void 0?null:t[o.numberStyle],m=/* @__PURE__ */ new Map,h=e=>{let t=new Intl.NumberFormat(e,{useGrouping:!1}),n=/* @__PURE__ */ new Set;for(let e=0;e<=9;e++)n.add(t.format(e));return n},g=(e,t)=>{let n=[],r=[],i=!1;for(let a of e)t.has(a)?(r.length>0&&(n.push(r),r=[]),i=!0):i&&r.push(a);return n},_=e=>{let t=m.get(e);if(t!==void 0)return t;let n=h(e),r=new Intl.NumberFormat(e,{useGrouping:!0,minimumFractionDigits:1,maximumFractionDigits:1}).format(11111.5),i=g(Array.from(r),n),a={digits:n,decimal:i.at(-1)??null,group:i.length>=2?i.at(0)??null:null};return m.set(e,a),a},v=(e,t,n)=>{let r=t>=0?e.at(t):void 0;return r!==void 0&&n.has(r)},y=(e,t,n)=>{let r=Array.from(e),i=``,a=0;for(;a<r.length;){let e=n.find(({mark:e})=>v(r,a-1,t)&&e.every((e,t)=>r[a+t]===e)&&v(r,a+e.length,t));e===void 0?(i+=r[a],a+=1):(i+=e.to,a+=e.mark.length)}return i},b=(e,t)=>{let n=p();if(n===null)return e.format(t);let{digits:r,decimal:i,group:a}=_(e.resolvedOptions().locale),o=[];return i!==null&&o.push({mark:i,to:n.decimal}),a!==null&&o.push({mark:a,to:n.group}),y(e.format(t),r,o)};export{c as configureFormatters,d as configuredLocale,l as getFormatterConfig,f as groupingForLocale,u as isFormatterConfigured,p as numberSeparators,b as styledNumber};
|
package/dist/formatters/house.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{configuredLocale as e,getFormatterConfig as t,groupingForLocale as n,numberSeparators as r,styledNumber as i}from"./formatConfig.js";import{dateTimeFormat as a,numberFormat as o,relativeTimeFormat as s}from"./intlCache.js";var c=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],l=330,u=[`IST`,`Asia/Kolkata`,`Asia/Calcutta`],d=/^\d{4}-\d{2}-\d{2}$/,f=e=>e<10?`0${e}`:`${e}`,p=e=>e??t().empty,m=e=>{if(e==null||e===``)return null;let t=e instanceof Date?e:new Date(typeof e==`string`?e.trim():e);return Number.isNaN(t.getTime())?null:t},h=e=>typeof e==`string`&&d.test(e.trim()),g=e=>{if(e===0)return`GMT`;let t=e>0?`+`:`-`,n=Math.abs(e),r=n%60;return`GMT${t}${Math.floor(n/60)}${r===0?``:`:${f(r)}`}`},_=(e,t,n)=>{let r=new Date(e.getTime()+t*6e4);return{year:r.getUTCFullYear(),month:r.getUTCMonth(),day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),label:n}},v=(e,t)=>{let n=a(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,hour12:!1}).formatToParts(e),r=e=>Number.parseInt(n.find(t=>t.type===e)?.value??``,10),i=r(`year`),o=r(`month`)-1,s=r(`day`),c=r(`hour`)%24,l=r(`minute`);return{year:i,month:o,day:s,hour:c,minute:l,label:g(Math.round((Date.UTC(i,o,s,c,l)-Math.floor(e.getTime()/6e4)*6e4)/6e4))}},y=(e,t)=>u.includes(t)?_(e,l,`IST`):t===`UTC`?_(e,0,`UTC`):t===`viewer`?{year:e.getFullYear(),month:e.getMonth(),day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),label:g(-e.getTimezoneOffset())}:v(e,t),b=e=>e.hourCycle??12,x=e=>`${f(e.day)}-${c[e.month]}-${e.year}`,S=(e,t)=>{let n=f(e.day),r=f(e.month+1),i=String(e.year).padStart(4,`0`);return t===`DayMonthYear`?`${n}/${r}/${i}`:t===`MonthDayYear`?`${r}/${n}/${i}`:`${i}-${r}-${n}`},C=(e,t)=>t===24?`${f(e.hour)}:${f(e.minute)}`:`${e.hour%12||12}:${f(e.minute)} ${e.hour<12?`AM`:`PM`}`,w=(e,t)=>t??!u.includes(e),T=(e,t,n,r)=>w(n,r)?`${e} ${t.label}`:e,E=e=>{if(e!==`viewer`)return u.includes(e)?`Asia/Kolkata`:e},D=(e,t,n)=>{let r=a(t,{day:`2-digit`,month:`short`,year:`numeric`,timeZone:n}).formatToParts(e),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`day`)}-${i(`month`).replace(`.`,``)}-${i(`year`)}`},O=(n,r)=>{let i=t().dateOrder??`DayMonthNameYear`;if(i!==`DayMonthNameYear`)return S(y(n,r),i);let a=e();return a?D(n,a,E(r)):x(y(n,r))},k=(e,t,n,r)=>a(t,{hour:`2-digit`,minute:`2-digit`,timeZone:E(n),timeZoneName:w(n,r.zoneLabel)?`short`:void 0,hourCycle:r.hourCycle===void 0?void 0:r.hourCycle===24?`h23`:`h12`}).format(e),A=(e,n={})=>{let r=m(e);return r?O(r,h(e)?`UTC`:n.zone??t().zone):p(n.empty)},ee=(n,r={})=>{let i=m(n);if(!i)return p(r.empty);let a=r.zone??t().zone,o=e();if(o)return k(i,o,a,r);let s=y(i,a);return T(C(s,b(r)),s,a,r.zoneLabel)},te=(n,r={})=>{let i=m(n);if(!i)return p(r.empty);let a=r.zone??t().zone,o=e();if(o)return`${O(i,a)}, ${k(i,o,a,r)}`;let s=y(i,a);return T(`${O(i,a)}, ${C(s,b(r))}`,s,a,r.zoneLabel)},j=1e3,M=60*j,N=60*M,P=24*N,F=7*P,I=30*P,L=365*P,R=[[`year`,L],[`month`,I],[`day`,P],[`hour`,N],[`minute`,M]],z=(n,r={})=>{let i=m(n),a=m(r.now??Date.now());if(!i||!a)return p(r.empty);let o=i.getTime()-a.getTime(),c=Math.abs(o),l=Intl.RelativeTimeFormat,u=e();if((u!==null||r.intl===!0)&&typeof l==`function`){let e=s(l,u??t().locale),[n,r]=R.find(([,e])=>c>=e)??[`second`,j];return e.format(Math.round(o/r),n)}if(c<M)return`just now`;let[d,f]=c<N?[`minute`,M]:c<P?[`hour`,N]:c<F?[`day`,P]:c<I?[`week`,F]:c<L?[`month`,I]:[`year`,L],h=Math.floor(c/f),g=`${h} ${d}${h===1?``:`s`}`;return o<0?`${g} ago`:`in ${g}`},B=e=>{if(e==null||typeof e==`string`&&e.trim()===``)return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},V=e=>Math.min(20,Math.max(0,Math.trunc(e))),H=(e,t)=>/e/i.test(String(e))?e*10**t:Number(`${e}e${t}`),U=()=>r()??{decimal:`.`,group:`,`},W=(e,t,n)=>t===`none`||e.length<=3?e:t===`international`?e.replace(/\B(?=(\d{3})+(?!\d))/g,n):`${e.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,n)}${n}${e.slice(-3)}`,G=()=>typeof Intl<`u`&&typeof Intl.NumberFormat==`function`,K=(e,t)=>{if(G())return o(`en-US`,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t}).format(e);let n=Math.min(t,15);return H(Math.round(H(e,n)),-n).toFixed(n)},q=(e,t,n,r)=>{let i=Math.max(V(n),V(t)),a=V(t),o=K(Math.abs(e),i),[s=`0`,c=``]=o.split(`.`),l=c.padEnd(a,`0`);for(;l.length>a&&l.endsWith(`0`);)l=l.slice(0,-1);let u=U(),d=W(s,r,u.group)+(l?`${u.decimal}${l}`:``);return e<0&&/[1-9]/.test(o)?`-${d}`:d},J=/* @__PURE__ */ new Set([`grouping`,`minimumFractionDigits`,`maximumFractionDigits`,`locale`,`empty`,`scale`]),Y=e=>{if(!Object.entries(e).some(([e,t])=>t!==void 0&&!J.has(e)))return null;let{grouping:t,locale:n,empty:r,scale:i,...a}=e;return t===`none`&&a.useGrouping===void 0?{...a,useGrouping:!1}:a},X=e=>e.locale??t().locale,Z=t=>{let n=e();return n===null||t.grouping===`indian`||t.grouping===`international`?null:t.locale??n},Q=(e,t)=>{let n=V(e);return{minimumFractionDigits:n,maximumFractionDigits:Math.max(n,V(t))}},$=e=>e===`none`?{useGrouping:!1}:{},ne=(e,t={})=>{let r=B(e);if(r===null)return p(t.empty);let a=Y(t);if(a)return i(o(X(t),a),r);let s=Z(t);return s?i(o(s,{...Q(t.minimumFractionDigits??0,t.maximumFractionDigits??3),...$(t.grouping)}),r):q(r,t.minimumFractionDigits??0,t.maximumFractionDigits??3,t.grouping??n(X(t)))},re=(e,t={})=>{let r=B(e);if(r===null)return p(t.empty);let a=Y(t);if(a){let e=t.scale===`percent`?H(r,-2):r;return i(o(X(t),{style:`percent`,...a}),e)}let s=Z(t);if(s){let e=t.scale===`percent`?H(r,-2):r;return i(o(s,{style:`percent`,...Q(t.minimumFractionDigits??0,t.maximumFractionDigits??t.minimumFractionDigits??0),...$(t.grouping)}),e)}return`${q(t.scale===`percent`?r:H(r,2),t.minimumFractionDigits??0,t.maximumFractionDigits??t.minimumFractionDigits??0,t.grouping??n(X(t)))}%`},ie={INR:`₹`,USD:`$`,EUR:`€`,GBP:`£`},ae={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3},oe=(e,t)=>{if(!t?.currency)throw TypeError(`formatMinor needs options.currency, an ISO 4217 code such as "INR".`);let n=B(e);if(n===null)return p(t.empty);let r=t.currency.toUpperCase(),a=ae[r]??2,s=Math.round(Math.abs(n)),c=String(s).padStart(a+1,`0`),l=c.slice(0,c.length-a),u=c.slice(c.length-a);t.dropZeroDecimals&&/^0*$/.test(u)&&(u=``);let d=Z({grouping:t.grouping});if(d)try{let e=Number(`${n<0&&s!==0?`-`:``}${l}.${c.slice(c.length-a)||`0`}`);return i(o(d,{...t.symbol===!1?{}:{style:`currency`,currency:r},...Q(u?a:0,a),...$(t.grouping)}),e)}catch(e){throw e instanceof RangeError?RangeError(`formatMinor rejected currency "${r}" or locale "${d}": ${e.message}`,{cause:e}):e}let f=t.grouping??(r===`INR`?`indian`:`international`),m=U(),h=W(l,f,m.group)+(u?`${m.decimal}${u}`:``),g=n<0&&s!==0?`-`:``;if(t.symbol===!1)return`${g}${h}`;let _=ie[r];return _?`${g}${_}${h}`:`${g}${r} ${h}`};export{A as formatDate,te as formatDateTime,oe as formatMinor,ne as formatNumber,re as formatPercent,z as formatRelative,ee as formatTime};
|
|
1
|
+
import{configuredLocale as e,getFormatterConfig as t,groupingForLocale as n,numberSeparators as r,styledNumber as i}from"./formatConfig.js";import{dateTimeFormat as a,numberFormat as o,relativeTimeFormat as s}from"./intlCache.js";var c=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],l=330,u=[`IST`,`Asia/Kolkata`,`Asia/Calcutta`],d=/^\d{4}-\d{2}-\d{2}$/,f=e=>e<10?`0${e}`:`${e}`,p=e=>e??t().empty,m=e=>{if(e==null||e===``)return null;let t=e instanceof Date?e:new Date(typeof e==`string`?e.trim():e);return Number.isNaN(t.getTime())?null:t},h=e=>typeof e==`string`&&d.test(e.trim()),g=e=>{if(e===0)return`GMT`;let t=e>0?`+`:`-`,n=Math.abs(e),r=n%60;return`GMT${t}${Math.floor(n/60)}${r===0?``:`:${f(r)}`}`},_=(e,t,n)=>{let r=new Date(e.getTime()+t*6e4);return{year:r.getUTCFullYear(),month:r.getUTCMonth(),day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),label:n}},v=(e,t)=>{let n=a(`en-US`,{timeZone:t,year:`numeric`,month:`numeric`,day:`numeric`,hour:`numeric`,minute:`numeric`,hour12:!1}).formatToParts(e),r=e=>Number.parseInt(n.find(t=>t.type===e)?.value??``,10),i=r(`year`),o=r(`month`)-1,s=r(`day`),c=r(`hour`)%24,l=r(`minute`);return{year:i,month:o,day:s,hour:c,minute:l,label:g(Math.round((Date.UTC(i,o,s,c,l)-Math.floor(e.getTime()/6e4)*6e4)/6e4))}},y=(e,t)=>u.includes(t)?_(e,l,`IST`):t===`UTC`?_(e,0,`UTC`):t===`viewer`?{year:e.getFullYear(),month:e.getMonth(),day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),label:g(-e.getTimezoneOffset())}:v(e,t),b=e=>e.hourCycle??12,x=e=>`${f(e.day)}-${c[e.month]}-${e.year}`,S=(e,t)=>{let n=f(e.day),r=f(e.month+1),i=String(e.year).padStart(4,`0`);return t===`DayMonthYear`?`${n}/${r}/${i}`:t===`MonthDayYear`?`${r}/${n}/${i}`:`${i}-${r}-${n}`},C=(e,t)=>t===24?`${f(e.hour)}:${f(e.minute)}`:`${e.hour%12||12}:${f(e.minute)} ${e.hour<12?`AM`:`PM`}`,w=(e,t)=>t??!u.includes(e),T=(e,t,n,r)=>w(n,r)?`${e} ${t.label}`:e,E=e=>{if(e!==`viewer`)return u.includes(e)?`Asia/Kolkata`:e},D=(e,t,n)=>{let r=a(t,{day:`2-digit`,month:`short`,year:`numeric`,timeZone:n}).formatToParts(e),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`day`)}-${i(`month`).replace(`.`,``)}-${i(`year`)}`},O=(n,r)=>{let i=t().dateOrder??`DayMonthNameYear`;if(i!==`DayMonthNameYear`)return S(y(n,r),i);let a=e();return a?D(n,a,E(r)):x(y(n,r))},k=(e,t,n,r)=>a(t,{hour:`2-digit`,minute:`2-digit`,timeZone:E(n),timeZoneName:w(n,r.zoneLabel)?`short`:void 0,hourCycle:r.hourCycle===void 0?void 0:r.hourCycle===24?`h23`:`h12`}).format(e),A=(e,n={})=>{let r=m(e);return r?O(r,h(e)?`UTC`:n.zone??t().zone):p(n.empty)},ee=(n,r={})=>{let i=m(n);if(!i)return p(r.empty);let a=r.zone??t().zone,o=e();if(o)return k(i,o,a,r);let s=y(i,a);return T(C(s,b(r)),s,a,r.zoneLabel)},te=(n,r={})=>{let i=m(n);if(!i)return p(r.empty);let a=r.zone??t().zone,o=e();if(o)return`${O(i,a)}, ${k(i,o,a,r)}`;let s=y(i,a);return T(`${O(i,a)}, ${C(s,b(r))}`,s,a,r.zoneLabel)},j=1e3,M=60*j,N=60*M,P=24*N,F=7*P,I=30*P,L=365*P,R=[[`year`,L],[`month`,I],[`day`,P],[`hour`,N],[`minute`,M]],z=(n,r={})=>{let i=m(n),a=m(r.now??Date.now());if(!i||!a)return p(r.empty);let o=i.getTime()-a.getTime(),c=Math.abs(o),l=typeof Intl.RelativeTimeFormat==`function`?Intl.RelativeTimeFormat:void 0,u=e();if((u!==null||r.intl===!0)&&typeof l==`function`){let e=s(l,u??t().locale),[n,r]=R.find(([,e])=>c>=e)??[`second`,j];return e.format(Math.round(o/r),n)}if(c<M)return`just now`;let[d,f]=c<N?[`minute`,M]:c<P?[`hour`,N]:c<F?[`day`,P]:c<I?[`week`,F]:c<L?[`month`,I]:[`year`,L],h=Math.floor(c/f),g=`${h} ${d}${h===1?``:`s`}`;return o<0?`${g} ago`:`in ${g}`},B=e=>{if(e==null||typeof e==`string`&&e.trim()===``)return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},V=e=>Math.min(20,Math.max(0,Math.trunc(e))),H=(e,t)=>/e/i.test(String(e))?e*10**t:Number(`${e}e${t}`),U=()=>r()??{decimal:`.`,group:`,`},W=(e,t,n)=>t===`none`||e.length<=3?e:t===`international`?e.replace(/\B(?=(\d{3})+(?!\d))/g,n):`${e.slice(0,-3).replace(/\B(?=(\d{2})+(?!\d))/g,n)}${n}${e.slice(-3)}`,G=()=>typeof Intl<`u`&&typeof Intl.NumberFormat==`function`,K=(e,t)=>{if(G())return o(`en-US`,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t}).format(e);let n=Math.min(t,15);return H(Math.round(H(e,n)),-n).toFixed(n)},q=(e,t,n,r)=>{let i=Math.max(V(n),V(t)),a=V(t),o=K(Math.abs(e),i),[s=`0`,c=``]=o.split(`.`),l=c.padEnd(a,`0`);for(;l.length>a&&l.endsWith(`0`);)l=l.slice(0,-1);let u=U(),d=W(s,r,u.group)+(l?`${u.decimal}${l}`:``);return e<0&&/[1-9]/.test(o)?`-${d}`:d},J=/* @__PURE__ */ new Set([`grouping`,`minimumFractionDigits`,`maximumFractionDigits`,`locale`,`empty`,`scale`]),Y=e=>{if(!Object.entries(e).some(([e,t])=>t!==void 0&&!J.has(e)))return null;let{grouping:t,locale:n,empty:r,scale:i,...a}=e;return t===`none`&&a.useGrouping===void 0?{...a,useGrouping:!1}:a},X=e=>e.locale??t().locale,Z=t=>{let n=e();return n===null||t.grouping===`indian`||t.grouping===`international`?null:t.locale??n},Q=(e,t)=>{let n=V(e);return{minimumFractionDigits:n,maximumFractionDigits:Math.max(n,V(t))}},$=e=>e===`none`?{useGrouping:!1}:{},ne=(e,t={})=>{let r=B(e);if(r===null)return p(t.empty);let a=Y(t);if(a)return i(o(X(t),a),r);let s=Z(t);return s?i(o(s,{...Q(t.minimumFractionDigits??0,t.maximumFractionDigits??3),...$(t.grouping)}),r):q(r,t.minimumFractionDigits??0,t.maximumFractionDigits??3,t.grouping??n(X(t)))},re=(e,t={})=>{let r=B(e);if(r===null)return p(t.empty);let a=Y(t);if(a){let e=t.scale===`percent`?H(r,-2):r;return i(o(X(t),{style:`percent`,...a}),e)}let s=Z(t);if(s){let e=t.scale===`percent`?H(r,-2):r;return i(o(s,{style:`percent`,...Q(t.minimumFractionDigits??0,t.maximumFractionDigits??t.minimumFractionDigits??0),...$(t.grouping)}),e)}return`${q(t.scale===`percent`?r:H(r,2),t.minimumFractionDigits??0,t.maximumFractionDigits??t.minimumFractionDigits??0,t.grouping??n(X(t)))}%`},ie={INR:`₹`,USD:`$`,EUR:`€`,GBP:`£`},ae={JPY:0,KRW:0,VND:0,BHD:3,JOD:3,KWD:3,OMR:3,TND:3},oe=(e,t)=>{if(!t?.currency)throw TypeError(`formatMinor needs options.currency, an ISO 4217 code such as "INR".`);let n=B(e);if(n===null)return p(t.empty);let r=t.currency.toUpperCase(),a=ae[r]??2,s=Math.round(Math.abs(n)),c=String(s).padStart(a+1,`0`),l=c.slice(0,c.length-a),u=c.slice(c.length-a);t.dropZeroDecimals&&/^0*$/.test(u)&&(u=``);let d=Z({grouping:t.grouping});if(d)try{let e=Number(`${n<0&&s!==0?`-`:``}${l}.${c.slice(c.length-a)||`0`}`);return i(o(d,{...t.symbol===!1?{}:{style:`currency`,currency:r},...Q(u?a:0,a),...$(t.grouping)}),e)}catch(e){throw e instanceof RangeError?RangeError(`formatMinor rejected currency "${r}" or locale "${d}": ${e.message}`,{cause:e}):e}let f=t.grouping??(r===`INR`?`indian`:`international`),m=U(),h=W(l,f,m.group)+(u?`${m.decimal}${u}`:``),g=n<0&&s!==0?`-`:``;if(t.symbol===!1)return`${g}${h}`;let _=ie[r];return _?`${g}${_}${h}`:`${g}${r} ${h}`};export{A as formatDate,te as formatDateTime,oe as formatMinor,ne as formatNumber,re as formatPercent,z as formatRelative,ee as formatTime};
|
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{DESIGN_SAMPLE_HEADER as
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{gstinState as e}from"./gstin.js";import{findGstState as t,gstStateByName as n}from"./gstStates.g.js";var r=n=>{let r=e(n);if(r===null)return null;if(r.status!==`Retired`||r.replacedByCode===void 0)return r;let i=t(r.replacedByCode);if(i===null)throw RangeError(`The GST state table names ${r.replacedByCode} as the successor of ${r.code} but has no such row.`);return i},i=e=>{if(typeof e!=`string`||e.trim()===``)return null;let r=e.lastIndexOf(` (`);return r>0&&e.endsWith(`)`)?t(e.slice(r+2,-1))??n(e.slice(0,r)):n(e)},a=e=>`${e.name} (${e.code})`;export{r as currentStateForGstin,i as gstStateFromPlaceOfSupply,a as placeOfSupplyLabel};
|
package/dist/india/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{aadhaarLastFour as e,isAadhaar as t,maskAadhaar as n,normalizeAadhaar as r}from"./aadhaar.js";import{currentFinancialYear as i,financialYearLabel as a,financialYearOf as o,parseFinancialYear as s,recentFinancialYears as c}from"./financialYear.js";import{gstinHolderPan as l,gstinProblem as u,gstinState as d,gstinStateCode as f,isGstin as p,normalizeGstin as m,sanitizeGstinInput as h}from"./gstin.js";import{
|
|
1
|
+
import{aadhaarLastFour as e,isAadhaar as t,maskAadhaar as n,normalizeAadhaar as r}from"./aadhaar.js";import{currentFinancialYear as i,financialYearLabel as a,financialYearOf as o,parseFinancialYear as s,recentFinancialYears as c}from"./financialYear.js";import{gstinHolderPan as l,gstinProblem as u,gstinState as d,gstinStateCode as f,isGstin as p,normalizeGstin as m,sanitizeGstinInput as h}from"./gstin.js";import{currentStateForGstin as g,gstStateFromPlaceOfSupply as _,placeOfSupplyLabel as v}from"./gstStates.js";import{isIfsc as y,normalizeIfsc as b}from"./ifsc.js";import{formatIndianMobile as x,isIndianMobile as S,normalizeIndianMobile as C}from"./indianMobile.js";import{istDateOf as w,istDayBoundsUtc as T,istToday as E}from"./indiaTime.js";import{PAISE_PER_RUPEE as D,formatPaise as O,formatRupees as k,paiseFromRupees as A}from"./paise.js";import{isPan as j,maskPan as M,normalizePan as N}from"./pan.js";import{isPincode as P,normalizePincode as F}from"./pincode.js";export{D as PAISE_PER_RUPEE,e as aadhaarLastFour,i as currentFinancialYear,g as currentStateForGstin,a as financialYearLabel,o as financialYearOf,x as formatIndianMobile,O as formatPaise,k as formatRupees,_ as gstStateFromPlaceOfSupply,l as gstinHolderPan,u as gstinProblem,d as gstinState,f as gstinStateCode,t as isAadhaar,p as isGstin,y as isIfsc,S as isIndianMobile,j as isPan,P as isPincode,w as istDateOf,T as istDayBoundsUtc,E as istToday,n as maskAadhaar,M as maskPan,r as normalizeAadhaar,m as normalizeGstin,b as normalizeIfsc,C as normalizeIndianMobile,N as normalizePan,F as normalizePincode,A as paiseFromRupees,s as parseFinancialYear,v as placeOfSupplyLabel,c as recentFinancialYears,h as sanitizeGstinInput};
|