@webority/web-core 0.157.0 → 0.158.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -268,7 +268,7 @@ if (!result.saved) {
268
268
 
269
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
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.
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. `save` may reject with an `ApiError` or with the raw axios error a service call throws: both re-read on a 412, and any other failure is rethrown as it came.
272
272
 
273
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
274
 
@@ -1 +1 @@
1
- import{buildContractRequest as e}from"../api-contract/dist/call.js";var t=(t,n)=>async(r,i,a)=>{let o=e(n[r],i);return(await t.request({method:o.method,url:o.url,...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},...a?.retry!==void 0&&{retry:a.retry}})).data};export{t as createContractCaller};
1
+ import{buildContractRequest as e,contractReply as t}from"../api-contract/dist/call.js";var n=(n,r)=>async(i,a,o)=>{let s=e(r[i],a,o),c=await n.request({method:s.method,url:s.url,...s.headers!==void 0&&{headers:s.headers},data:s.data,responseType:s.responseType,...s.skipErrorLog!==void 0&&{skipErrorLog:s.skipErrorLog},...s.expectedStatuses!==void 0&&{expectedStatuses:s.expectedStatuses},...o?.signal!==void 0&&{signal:o.signal},...o?.timeout!==void 0&&{timeout:o.timeout},...o?.retry!==void 0&&{retry:o.retry}});return t(r[i],c.status,c.data)};export{n as createContractCaller};
@@ -1 +1 @@
1
- var e=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},t=/\{([^{}]+)\}/g,n=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e));function r(e){let t=[];for(let[r,i]of Object.entries(e??{})){if(i==null)continue;let e=encodeURIComponent(r);for(let r of Array.isArray(i)?i:[i])r!=null&&t.push(`${e}=${n(r)}`)}return t.join(`&`)}function i(n,i){let a=n.path.replace(t,(t,r)=>{let a=i.path?.[r],o=a===void 0?``:String(a);if(o===``)throw new e(`${n.method} ${n.path} needs a non-empty path value for "${r}"`);if(o===`.`||o===`..`)throw new e(`${n.method} ${n.path} needs a path value for "${r}" other than "." or ".."`);return encodeURIComponent(o)}),o=r(i.query);return{method:n.method,url:o===``?a:`${a}?${o}`,headers:i.headers,data:i.body,responseType:n.replyKind===`blob`?`blob`:`json`}}export{e as ContractCallError,i as buildContractRequest};
1
+ var e=class extends Error{constructor(e){super(e),this.name=`ContractCallError`}},t=/\{([^{}]+)\}/g,n=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e));function r(e){let t=[];for(let[r,i]of Object.entries(e??{})){if(i==null)continue;let e=encodeURIComponent(r);for(let r of Array.isArray(i)?i:[i])r!=null&&t.push(`${e}=${n(r)}`)}return t.join(`&`)}var i=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,a=[`content-type`,`content-length`],o=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function s(t,n,r){if(r===void 0)return n;if(!o(r))throw new e(`${t} needs call headers as an object of header names to string values`);let s=new Set(Object.keys(n??{}).map(e=>e.toLowerCase())),c={...n};for(let[n,o]of Object.entries(r)){if(!i.test(n))throw new e(`${t} has a call header named "${n}", which is not a valid header name`);let r=n.toLowerCase();if(a.includes(r))throw new e(`${t} sets "${n}" as a call header; the body decides it`);if(s.has(r))throw new e(`${t} sets "${n}" twice; set a header the contract declares on the request's headers only`);if(typeof o!=`string`||/[\r\n\0]/.test(o))throw new e(`${t} needs call header "${n}" as a string with no line break`);s.add(r),c[n]=o}return c}function c(t,n){let r=n?.skipErrorLog,i=n?.expectedStatuses;if(r!==void 0&&typeof r!=`boolean`)throw new e(`${t} needs skipErrorLog as true or false`);if(i===void 0)return{skipErrorLog:r,expectedStatuses:void 0};if(!Array.isArray(i)||i.length===0)throw new e(`${t} needs expectedStatuses as a non-empty list of failure statuses`);for(let n of i)if(!Number.isInteger(n)||n<400||n>599)throw new e(`${t} lists ${String(n)} in expectedStatuses; only a failure status from 400 to 599 is expected`);if(new Set(i).size!==i.length)throw new e(`${t} lists a status twice in expectedStatuses`);if(r===!0)throw new e(`${t} sets skipErrorLog and expectedStatuses; skipErrorLog already keeps every failure out of the log`);return{skipErrorLog:r,expectedStatuses:i}}function l(e,t,n){return e.replyKind===`none`||t===204||t===205?void 0:n}function u(n,i,a){let o=`${n.method} ${n.path}`,l=n.path.replace(t,(t,n)=>{let r=i.path?.[n],a=r===void 0?``:String(r);if(a===``)throw new e(`${o} needs a non-empty path value for "${n}"`);if(a===`.`||a===`..`)throw new e(`${o} needs a path value for "${n}" other than "." or ".."`);return encodeURIComponent(a)}),u=r(i.query);return{method:n.method,url:u===``?l:`${l}?${u}`,headers:s(o,i.headers,a?.headers),data:i.body,responseType:n.replyKind===`blob`?`blob`:`json`,...c(o,a)}}export{e as ContractCallError,u as buildContractRequest,l as contractReply};
@@ -1,2 +1,2 @@
1
1
  import{isOfflineFailure as e}from"./requestPlatform.js";var t=`Something went wrong on our side. Please try again in a moment.`,n=`You appear to be offline. Check your connection and try again.`,r=`We couldn't reach the server. Check your connection and try again.`,i=`That took too long to respond. Check your connection and try again.`,a=`Something went wrong. Please try again.`,o=`request_canceled`,s=`contract_error`,c=`timeout`,l=`network`,u=`offline`,d=300,f=`internal_error`,p=e=>`Request failed (${e})`,m={401:{code:`unauthorized`,sentence:`Please sign in to continue.`},403:{code:`forbidden`,sentence:`You do not have access to this.`}},h=e=>typeof e==`object`&&!!e&&!Array.isArray(e),g=e=>typeof e==`string`&&e.trim().length>0?e:null,_=(e,t)=>{let n=m[e];if(n===void 0||t===null||t.code!==n.code)return null;let r=g(t.detail);return r===null||r===n.sentence?n.sentence:null},v=e=>e.length>d||/^\s*</.test(e)||e.includes(`
2
- at `)||/(Exception|StackTrace):/.test(e)||/\b(System|Microsoft)\.[A-Za-z]+\.[A-Za-z]/.test(e),y=e=>{let t=g(e);return t!==null&&!v(t)?t:null},b=e=>e.replace(/^\$\.?/,``).split(`.`).map(e=>e.charAt(0).toLowerCase()+e.slice(1)).join(`.`),x=e=>{if(Array.isArray(e)){for(let t of e){let e=g(t);if(e!==null)return e}return null}return g(e)},S=(e,t,n)=>{let r=b(t);r===``?e.form??=n:r in e.fields||(e.fields[r]=n)},C=e=>{let t={fields:{},form:null};if(Array.isArray(e)){for(let n of e){if(!h(n))continue;let e=g(n.message);e!==null&&S(t,typeof n.field==`string`?n.field:``,e)}return t}if(!h(e))return t;for(let[n,r]of Object.entries(e)){let e=x(r);e!==null&&S(t,n,e)}return t},w=e=>h(e)&&typeof e.message==`string`&&typeof e.status==`number`&&typeof e.offline==`boolean`&&h(e.fieldErrors),T=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,...e}),E=e=>{let t=h(e.config)?e.config.headers:void 0;if(!h(t))return null;let n=typeof t.get==`function`?t.get(`traceparent`):t.traceparent??t.Traceparent;return(typeof n==`string`?/^00-([0-9a-f]{32})-[0-9a-f]{16}-[0-9a-f]{2}$/.exec(n):null)?.[1]??null},D=t=>{let s=g(t.code),d=g(t.name),f=g(t.message),p=E(t);return d===`CanceledError`||s===`ERR_CANCELED`?T({code:o,message:a,traceId:p,diagnostic:f}):s===`ECONNABORTED`||s===`ETIMEDOUT`?T({code:c,message:i,offline:!0,traceId:p,diagnostic:f}):d===`RequestOfflineError`||s===`ERR_NETWORK`||f===`Network Error`||f===`Network request failed`?e(t)?T({code:u,message:n,offline:!0,traceId:p,diagnostic:f}):T({code:l,message:r,offline:!0,traceId:p,diagnostic:f}):T({message:a,traceId:p,diagnostic:f})};function O(e){if(w(e))return e;if(typeof e==`string`)return T({message:y(e)??`Something went wrong. Please try again.`,diagnostic:e||null});if(!h(e))return T({message:a,diagnostic:e==null?null:String(e)});if(e.isContractError===!0)return T({code:s,message:y(e.message)??`Something went wrong. Please try again.`,diagnostic:g(e.message)});let t=h(e.response)?e.response:null,n=typeof t?.status==`number`?t.status:typeof e.status==`number`?e.status:0,r=t?t.data:e.body;if(n===0&&r==null)return D(e);let i=h(r)?r:null,{fields:o,form:c}=C(i?.errors),l=g(i?.code),u=g(i?.traceId)??E(e),d=g(i?.detail)??g(i?.title)??g(r)??g(e.message),m;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};
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)&&h(e.extensions),T=e=>({code:null,fieldErrors:{},status:0,offline:!1,traceId:null,diagnostic:null,extensions:{},...e}),E=/* @__PURE__ */ new Set([`type`,`title`,`status`,`detail`,`instance`,`code`,`errors`,`traceId`]),D=e=>e===null?{}:Object.fromEntries(Object.entries(e).filter(([e])=>!E.has(e))),O=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},k=t=>{let s=g(t.code),d=g(t.name),f=g(t.message),p=O(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 A(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 k(e);let i=h(r)?r:null,{fields:o,form:c}=C(i?.errors),l=g(i?.code),u=g(i?.traceId)??O(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,extensions:D(i),...b===null?{}:{requestUrl:b},...x===null?{}:{accountId:x}})}var j=e=>A(e).offline;function M(e,t){let n=A(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,M as apiErrorMessage,A as extractApiError,w as isApiError,j as isNoResponse,b as toFieldPath};
@@ -1 +1 @@
1
- import{extractApiError as e}from"../errors/extractApiError.js";import{Logger as t}from"../logger/logger.js";import n from"axios";var r=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e)),i=e=>{if(!(typeof e!=`string`||e.startsWith(`W/`)))return/^"([^"]*)"$/.exec(e)?.[1]},a=e=>`"${e}"`,o=e=>{let t={};if(e.ifMatch&&(t[`If-Match`]=a(e.ifMatch)),e.idempotencyKey&&(t[`Idempotency-Key`]=e.idempotencyKey),Object.keys(t).length===0)return e.headers;let n=Object.keys(t).map(e=>e.toLowerCase()),r=Object.entries(e.headers??{}).filter(([e])=>!n.includes(e.toLowerCase()));return{...Object.fromEntries(r),...t}},s=`precondition_failed`,c=e=>e.status===412?{...e,code:s}:e,l=e=>t=>{let n=[];for(let[i,a]of Object.entries(t)){if(a==null)continue;let t=encodeURIComponent(i);if(!Array.isArray(a))n.push(`${t}=${r(a)}`);else if(e===`comma`)n.push(`${t}=${a.map(r).join(`,`)}`);else{let i=e===`brackets`?`${t}[]`:t;for(let e of a)n.push(`${i}=${r(e)}`)}}return n.join(`&`)},u=({client:r,publicClient:a})=>async(s,{signal:u},d)=>{let f=typeof s==`string`?{url:s}:s,p=f.silent??d?.silent??!1,m=f.expectedStatuses??d?.expectedStatuses,h=f.paramsFormat??d?.paramsFormat,g=f.public?a:r;if(!g)throw Error(`createApiBaseQuery: "${f.url}" is marked public but no publicClient was passed.`);let _=o(f),v={url:f.url,method:f.method??`GET`,data:f.data,params:f.params,...h&&{paramsSerializer:l(h)},..._!==void 0&&{headers:_},...f.responseType!==void 0&&{responseType:f.responseType},...f.timeout!==void 0&&{timeout:f.timeout},signal:u,skipErrorLog:!0};try{let e=await g.request(v),t=i(e.headers?.etag);return{data:e.data,meta:{silent:p,status:e.status,...t!==void 0&&{entityTag:t}}}}catch(r){let a=c(e(r)),o=n.isCancel(r);o||t.requestFailed(r,{...m&&{expectedStatuses:m}});let s=n.isAxiosError(r)?i(r.response?.headers?.etag):void 0;return{error:a,meta:{silent:p||o,status:a.status,...m&&{expectedStatuses:m},...s!==void 0&&{entityTag:s}}}}};export{u as createApiBaseQuery,a as ifMatchValue,i as strongEntityTag};
1
+ import{extractApiError as e}from"../errors/extractApiError.js";import{Logger as t}from"../logger/logger.js";import n from"axios";var r=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t)||t<0)throw Error(`createApiBaseQuery: "${e}" sets extraOptions.maxRetries to ${String(t)}; it must be a whole number of 0 or more.`);return t},i=e=>e instanceof Date?encodeURIComponent(e.toISOString()):encodeURIComponent(typeof e==`object`?JSON.stringify(e):String(e)),a=e=>{if(!(typeof e!=`string`||e.startsWith(`W/`)))return/^"([^"]*)"$/.exec(e)?.[1]},o=e=>`"${e}"`,s=e=>{let t={};if(e.ifMatch&&(t[`If-Match`]=o(e.ifMatch)),e.idempotencyKey&&(t[`Idempotency-Key`]=e.idempotencyKey),Object.keys(t).length===0)return e.headers;let n=Object.keys(t).map(e=>e.toLowerCase()),r=Object.entries(e.headers??{}).filter(([e])=>!n.includes(e.toLowerCase()));return{...Object.fromEntries(r),...t}},c=`precondition_failed`,l=e=>e.status===412?{...e,code:c}:e,u=e=>t=>{let n=[];for(let[r,a]of Object.entries(t)){if(a==null)continue;let t=encodeURIComponent(r);if(!Array.isArray(a))n.push(`${t}=${i(a)}`);else if(e===`comma`)n.push(`${t}=${a.map(i).join(`,`)}`);else{let r=e===`brackets`?`${t}[]`:t;for(let e of a)n.push(`${r}=${i(e)}`)}}return n.join(`&`)},d=({client:i,publicClient:o})=>async(c,{signal:d},f)=>{let p=typeof c==`string`?{url:c}:c,m=p.silent??f?.silent??!1,h=p.expectedStatuses??f?.expectedStatuses,g=p.paramsFormat??f?.paramsFormat,_=f?.maxRetries===void 0?void 0:r(p.url,f.maxRetries),v=p.public?o:i;if(!v)throw Error(`createApiBaseQuery: "${p.url}" is marked public but no publicClient was passed.`);let y=s(p),b={url:p.url,method:p.method??`GET`,data:p.data,params:p.params,...g&&{paramsSerializer:u(g)},...y!==void 0&&{headers:y},...p.responseType!==void 0&&{responseType:p.responseType},...p.timeout!==void 0&&{timeout:p.timeout},..._!==void 0&&{retry:{retries:_}},signal:d,skipErrorLog:!0};try{let e=await v.request(b),t=a(e.headers?.etag);return{data:e.data,meta:{silent:m,status:e.status,...t!==void 0&&{entityTag:t}}}}catch(r){let i=l(e(r)),o=n.isCancel(r);o||t.requestFailed(r,{...h&&{expectedStatuses:h}});let s=n.isAxiosError(r)?a(r.response?.headers?.etag):void 0;return{error:i,meta:{silent:m||o,status:i.status,...h&&{expectedStatuses:h},...s!==void 0&&{entityTag:s}}}}};export{d as createApiBaseQuery,o as ifMatchValue,a as strongEntityTag};
@@ -1 +1 @@
1
- import{isApiError as e}from"../errors/extractApiError.js";import{ifMatchValue as t,strongEntityTag as n}from"./apiBaseQuery.js";var r=(e,t)=>{let n=typeof e==`object`&&e&&`version`in e?e.version:void 0;return typeof n==`string`&&n!==``?n:t===void 0||t===``?void 0:t},i=(e,n)=>{let r=Object.entries({...n?.headers}).filter(([e])=>e.toLowerCase()!==`if-match`);return{...n,headers:{...Object.fromEntries(r),"If-Match":t(e)}}},a=e=>{let t=e.headers;if(typeof t==`object`&&t&&`etag`in t)return n(t.etag)},o=t=>e(t)&&t.status===412,s=async({record:e,entityTag:t,form:n,toForm:i,read:a,save:s})=>{let c=r(e,t);if(c===void 0)throw Error(`saveWithVersion: the record has no version to send as If-Match`);try{return await s(n,c),{saved:!0}}catch(t){if(!o(t))throw t;let c=await a(),l=r(c.record,c.entityTag);if(JSON.stringify(i(c.record))!==JSON.stringify(i(e))||l===void 0)return{saved:!1,error:t,fresh:c.record};try{return await s(n,l),{saved:!0}}catch(e){if(!o(e))throw e;return{saved:!1,error:e,fresh:c.record}}}};export{a as entityTagOf,s as saveWithVersion,r as versionOf,i as withIfMatch};
1
+ import{extractApiError as e}from"../errors/extractApiError.js";import{ifMatchValue as t,strongEntityTag as n}from"./apiBaseQuery.js";var r=(e,t)=>{let n=typeof e==`object`&&e&&`version`in e?e.version:void 0;return typeof n==`string`&&n!==``?n:t===void 0||t===``?void 0:t},i=(e,n)=>{let r=Object.entries({...n?.headers}).filter(([e])=>e.toLowerCase()!==`if-match`);return{...n,headers:{...Object.fromEntries(r),"If-Match":t(e)}}},a=e=>{let t=e.headers;if(typeof t==`object`&&t&&`etag`in t)return n(t.etag)},o=t=>{let n=e(t);return n.status===412?n:void 0},s=async({record:e,entityTag:t,form:n,toForm:i,read:a,save:s})=>{let c=r(e,t);if(c===void 0)throw Error(`saveWithVersion: the record has no version to send as If-Match`);try{return await s(n,c),{saved:!0}}catch(t){let c=o(t);if(c===void 0)throw t;let l=await a(),u=r(l.record,l.entityTag);if(JSON.stringify(i(l.record))!==JSON.stringify(i(e))||u===void 0)return{saved:!1,error:c,fresh:l.record};try{return await s(n,u),{saved:!0}}catch(e){let t=o(e);if(t===void 0)throw e;return{saved:!1,error:t,fresh:l.record}}}};export{a as entityTagOf,s as saveWithVersion,r as versionOf,i as withIfMatch};
@@ -1,7 +1,11 @@
1
- import { type OperationEntry, type OperationShape } from "@webority/api-contract/call";
1
+ import { type ContractCallOptions, type OperationEntry, type OperationShape } from "@webority/api-contract/call";
2
2
  import type { AxiosInstance, AxiosRequestConfig } from "axios";
3
- /** Per-call options: an abort signal, a timeout, and the client's retry override (`false`, or a policy such as `{ retries: 1 }`). */
4
- export type ContractCallConfig = Pick<AxiosRequestConfig, "signal" | "timeout" | "retry">;
3
+ /**
4
+ * Per-call options: an abort signal, a timeout, the client's retry override (`false`, or a policy such as `{ retries: 1 }`),
5
+ * call headers the contract does not declare, `skipErrorLog` and `expectedStatuses`. buildContractRequest validates the
6
+ * headers and the two error options, and throws ContractCallError on an invalid value before anything is sent.
7
+ */
8
+ export type ContractCallConfig = Pick<AxiosRequestConfig, "signal" | "timeout" | "retry"> & ContractCallOptions;
5
9
  /** Calls one operation of a generated contract by its id; resolves to the reply the contract types for it. */
6
10
  export type ContractCaller<TOperations extends {
7
11
  readonly [K in keyof TOperations]: OperationShape;
@@ -13,6 +13,12 @@ export interface ApiError {
13
13
  traceId: string | null;
14
14
  /** What the server or runtime actually said. For the logger, never for the screen. */
15
15
  diagnostic: string | null;
16
+ /**
17
+ * Every member of the problem body other than `type`, `title`, `status`, `detail`, `instance`,
18
+ * `code`, `errors` and `traceId`, as the server sent it. Empty when the body had none or no answer
19
+ * arrived. Read a documented member through a type guard; never render one.
20
+ */
21
+ extensions: Readonly<Record<string, unknown>>;
16
22
  /** The request address the failed call was sent to. For the logger and the caller, never the screen. */
17
23
  requestUrl?: string | undefined;
18
24
  /** The Account-Id the failed call was sent with. For the logger and the caller, never the screen. */
@@ -40,6 +40,11 @@ export interface ApiExtraOptions {
40
40
  silent?: boolean;
41
41
  expectedStatuses?: number[];
42
42
  paramsFormat?: ParamsFormat;
43
+ /**
44
+ * How many times the client resends a failed call that its retry rule allows, in place of the
45
+ * client's `retries` setting; `0` sends it once. RTK Query's own `retry()` reads the same name.
46
+ */
47
+ maxRetries?: number;
43
48
  }
44
49
  export declare const strongEntityTag: (value: unknown) => string | undefined;
45
50
  /** The `If-Match` header value for a version: the version in quotes, as an ETag is sent. */
@@ -27,7 +27,7 @@ export interface SaveWithVersionOptions<R, F> {
27
27
  toForm: (record: R) => F;
28
28
  /** Reads the record as the server holds it now. */
29
29
  read: () => Promise<VersionedRead<R>>;
30
- /** Sends `form` with `version` as If-Match. Rejects with the ApiError of a failed reply. */
30
+ /** Sends `form` with `version` as If-Match. Rejects with the failed reply: an ApiError, or the raw axios error a service call throws. */
31
31
  save: (form: F, version: string) => Promise<void>;
32
32
  }
33
33
  export type SaveWithVersionResult<R> = {
@@ -1,4 +1,4 @@
1
- import type { Middleware, MiddlewareAPI, UnknownAction } from "@reduxjs/toolkit";
1
+ import type { Middleware, MiddlewareAPI, ThunkDispatch, UnknownAction } from "@reduxjs/toolkit";
2
2
  import { type ApiError } from "../errors/extractApiError";
3
3
  /**
4
4
  * Toasts every rejected thunk and every failed RTK Query call, so no screen has to remember
@@ -32,11 +32,13 @@ import { type ApiError } from "../errors/extractApiError";
32
32
  export type ShowErrorToast = (message: string, error: ApiError) => void;
33
33
  /** What `onRejected` decides for one rejection: `'toast'`, `'silent'`, or nothing for the default rules. */
34
34
  export type RejectionDecision = "toast" | "silent" | undefined;
35
+ /** The store's dispatch as the middleware sees it: plain actions and thunks. */
36
+ type StoreDispatch = ThunkDispatch<unknown, unknown, UnknownAction>;
35
37
  /**
36
38
  * The product's hook into every rejection the middleware sees. `api` is the store's
37
- * `dispatch` and `getState`, for a side effect that reads or updates state.
39
+ * `dispatch` and `getState`, for a side effect that reads or updates state; its dispatch takes thunks.
38
40
  */
39
- export type OnRejected = (action: UnknownAction, error: ApiError, api: MiddlewareAPI) => RejectionDecision;
41
+ export type OnRejected = (action: UnknownAction, error: ApiError, api: MiddlewareAPI<StoreDispatch>) => RejectionDecision;
40
42
  export interface ErrorToastOptions {
41
43
  showToast: ShowErrorToast;
42
44
  /** Server `code` values a screen answers in its own way (a paywall, a terms gate). */
@@ -51,5 +53,5 @@ export interface ErrorToastOptions {
51
53
  type Dict = Record<string, unknown>;
52
54
  /** Is this a rejected createAsyncThunk or RTK Query action that asked not to be toasted? */
53
55
  export declare const isSilentRejection: (meta: Dict) => boolean;
54
- export declare function errorToastMiddleware(options: ErrorToastOptions): Middleware;
56
+ export declare function errorToastMiddleware(options: ErrorToastOptions): Middleware<object, unknown, StoreDispatch>;
55
57
  export {};
@@ -1 +1 @@
1
- import{addMinAppVersionListener as e,getMinAppVersion as t}from"../api/minAppVersion.js";import{getConfigValue as n}from"../config/index.js";import{Logger as r}from"../logger/logger.js";import{isBuildBelowMinimum as i,parseBuildNumber as a}from"./buildNumber.js";import{addDeployedBuildListener as o,getNewerDeployedBuild as s,startDeployedBuildCheck as c}from"./deployedBuild.js";import{useMemo as l,useSyncExternalStore as u}from"react";var d=t=>{let n=e(()=>t()),r=o(t);return()=>{n(),r()}},f=()=>`${t()??``}|${s()??``}`,p=e=>{if(e===null)return!1;let t=a(n(`appBuild`));return t===null?(r.error(`[VersionCheck] the build number is not configured. Call setConfig({ appBuild: <integer> }) at startup with the build number the deploy stamps into the bundle.`),!1):i(t,e)},m=()=>p(t())||s()!==null,h=()=>{let e=u(d,f,f);return l(()=>({updateAvailable:p(t())||s()!==null}),[e])},g=`webority.versionCheck.reloadedFor`,_=e=>{try{return window.sessionStorage.getItem(e)}catch{return null}},v=(e,t)=>{try{window.sessionStorage.setItem(e,t)}catch(e){if(!(e instanceof DOMException))throw e}},y=(e,{reload:n=()=>window.location.reload()}={})=>{let i=e.state.location.key;return e.subscribe(e=>{let a=e.location.key;if(a===i)return;i=a;let o=t(),c=s(),l;if(p(o))l=String(o);else if(c!==null)l=`build:${c}`;else return;_(g)===l?r.warn(`[VersionCheck] still on the old bundle after a reload for ${l}`):(v(g,l),n())})};export{o as addDeployedBuildListener,s as getNewerDeployedBuild,y as installReloadOnNavigate,i as isBuildBelowMinimum,m as isUpdateAvailable,a as parseBuildNumber,c as startDeployedBuildCheck,h as useVersionCheck};
1
+ import{addMinAppVersionListener as e,getMinAppVersion as t}from"../api/minAppVersion.js";import{getConfigValue as n}from"../config/index.js";import{Logger as r}from"../logger/logger.js";import{isBuildBelowMinimum as i,parseBuildNumber as a}from"./buildNumber.js";import{addDeployedBuildListener as o,getNewerDeployedBuild as s,startDeployedBuildCheck as c}from"./deployedBuild.js";import{useMemo as l,useSyncExternalStore as u}from"react";var d=t=>{let n=e(()=>t()),r=o(t);return()=>{n(),r()}},f=()=>`${t()??``}|${s()??``}`,p=e=>{if(e===null)return!1;let t=a(n(`appBuild`));return t===null?(r.error(`[VersionCheck] the build number is not configured. Call setConfig({ appBuild: <integer> }) at startup with the build number the deploy stamps into the bundle.`),!1):i(t,e)},m=()=>p(t())||s()!==null,h=()=>{u(d,f,f);let e=t(),n=s();return l(()=>({updateAvailable:p(e)||n!==null}),[e,n])},g=`webority.versionCheck.reloadedFor`,_=e=>{try{return window.sessionStorage.getItem(e)}catch{return null}},v=(e,t)=>{try{window.sessionStorage.setItem(e,t)}catch(e){if(!(e instanceof DOMException))throw e}},y=(e,{reload:n=()=>window.location.reload()}={})=>{let i=e.state.location.key;return e.subscribe(e=>{let a=e.location.key;if(a===i)return;i=a;let o=t(),c=s(),l;if(p(o))l=String(o);else if(c!==null)l=`build:${c}`;else return;_(g)===l?r.warn(`[VersionCheck] still on the old bundle after a reload for ${l}`):(v(g,l),n())})};export{o as addDeployedBuildListener,s as getNewerDeployedBuild,y as installReloadOnNavigate,i as isBuildBelowMinimum,m as isUpdateAvailable,a as parseBuildNumber,c as startDeployedBuildCheck,h as useVersionCheck};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/web-core",
3
- "version": "0.157.0",
3
+ "version": "0.158.0",
4
4
  "description": "Platform layer for Webority React web portals: HTTP clients with single-flight token refresh, auth store, API error extraction, RTK Query base query, logger, formatters, storage, version check and route guards. No UI.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -98,7 +98,7 @@
98
98
  },
99
99
  "sideEffects": false,
100
100
  "dependencies": {
101
- "@webority/api-contract": "0.157.0"
101
+ "@webority/api-contract": "0.158.0"
102
102
  },
103
103
  "peerDependencies": {
104
104
  "@microsoft/applicationinsights-web": "^3.4.5",
@@ -120,7 +120,7 @@
120
120
  "@types/node": "25.6.0",
121
121
  "@types/react": "^19.3.0",
122
122
  "@vitest/coverage-v8": "5.1.0",
123
- "@webority/biome-config": "0.157.0",
123
+ "@webority/biome-config": "0.158.0",
124
124
  "axios": "^1.18.0",
125
125
  "jsdom": "30.1.1",
126
126
  "react": "^19.3.1",