@xeplr/ui-utils 1.1.10 → 1.1.11

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
@@ -152,7 +152,8 @@ export default function SelectCompany() {
152
152
  | `toggleBranch`, `decorateTree` | `(open, parentKey, key) → open`, `(nodes, open) → nodes` | Which branch of a settings tree is open at each level; `open` is `{ [parentKey]: key }`, the root's parent `''` |
153
153
  | `filterGridRows`, `sortGridRows` | `(rows, query, fields)`, `(rows, field, 'asc'\|'desc')` | Grid search and sort. An array field matches if any entry matches. |
154
154
  | `sanitizeTargetName`, `buildInitialMappings`, `checksFor` | `(name) → string`, `({ parts?, originalName?, checks? }) → [{ part, target, include, fixes }]`, `(inspectResult, part) → checks[]` | Data import mapping |
155
- | `configureUpload`, `uploadFile` | `({ url, headers, getHeaders })`, `(files, { url, fieldName, extraData, onProgress }) → Promise` | Multipart upload over XHR |
155
+ | `configureUpload`, `uploadFile` | `({ url, headers, getHeaders, renew })`, `(files, { url, fieldName, extraData, onProgress }) → Promise` | Multipart upload over XHR. **Give `renew`** (`async () => boolean`, e.g. `@xeplr/ui-account`'s `renewSession`): on a 401 the upload renews the sign-in once and sends the file again. Without it, a token that ran out while the person sat on the page failed the upload with "token expired" while every other request renewed. |
156
+ | `signedFetch`, `renewSignIn` | `(url, init) → Response`, `() → boolean` | `fetch` with the upload headers and the same one renewal on a 401 — what the Imports page's JSON calls use |
156
157
  | `attachProgressSource`, `progressSourceAttached`, `subscribeToProgress`, `describeProgress`, `describeComplete` | `(subscribe)`, `() → boolean`, `(key, handler) → unsubscribe`, `(data, noun?)`, `(data, noun?)` | The progress event source and its sentences |
157
158
 
158
159
  ### Imperative helpers, theme, data
@@ -297,7 +298,7 @@ The search type shows a ✕ only when there is text, and clearing calls `onChang
297
298
  ```jsx
298
299
  import { configureUpload, FileUploadPage } from '@xeplr/ui-utils'
299
300
 
300
- configureUpload({ url: '/uploads', getHeaders: () => ({ Authorization: 'Bearer ' + getToken() }) })
301
+ configureUpload({ url: '/uploads', getHeaders: () => ({ Authorization: 'Bearer ' + getToken() }), renew: renewSession })
301
302
 
302
303
  <FileUploadPage allowedTypes={['image/*', 'application/pdf']} maxSize={10 * 1024 * 1024} maxFiles={3}
303
304
  onSuccess={(res) => raiseSnackbar('Uploaded', { design: 'success' })} />
@@ -320,7 +321,7 @@ configureUpload({ url: '/uploads', getHeaders: () => ({ Authorization: 'Bearer '
320
321
  The whole import feature, against [`@xeplr/imports`](https://www.npmjs.com/package/@xeplr/imports)' routes. An app that mounts that router adds one route here and nothing else:
321
322
 
322
323
  ```jsx
323
- configureUpload({ url: API_BASE + '/imports/files', getHeaders }) // once, at startup — the headers every call carries
324
+ configureUpload({ url: API_BASE + '/imports/files', getHeaders, renew: renewSession }) // once, at startup — the headers every call carries, and how an expired sign-in renews
324
325
  <Route path="/upload" element={<ImportsPage basePath={API_BASE + '/imports'} />} />
325
326
  ```
326
327
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xeplr/ui-utils",
3
- "version": "1.1.10",
3
+ "version": "1.1.11",
4
4
  "description": "UI utility components: file upload with progress, snackbar, static data (countries/states)",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -7,6 +7,31 @@ export function configureUpload(config = {}) {
7
7
  if (config.url) _config.url = config.url;
8
8
  if (config.headers) _config.headers = config.headers;
9
9
  if (config.getHeaders) _config.getHeaders = config.getHeaders;
10
+ // renew: async () => boolean — get a fresh sign-in token (the app's own
11
+ // refresh, e.g. @xeplr/ui-account's renewSession). Without it an upload sent
12
+ // with an expired token just failed with "token expired", while every other
13
+ // request in the app renewed and carried on.
14
+ if (config.renew) _config.renew = config.renew;
15
+ }
16
+
17
+ /** Ask the app for a fresh token, once. true when it got one. */
18
+ export async function renewSignIn() {
19
+ if (typeof _config.renew !== 'function') return false;
20
+ try { return Boolean(await _config.renew()); } catch (e) { return false; }
21
+ }
22
+
23
+ /**
24
+ * fetch with the upload headers, renewing the sign-in once on a 401 and
25
+ * asking again — the same rule the app's own authFetch follows. `init.headers`
26
+ * are added on top of the upload headers.
27
+ */
28
+ export async function signedFetch(url, init) {
29
+ var opts = init || {};
30
+ var send = function() {
31
+ return fetch(url, Object.assign({}, opts, { headers: Object.assign(uploadHeaders(), opts.headers || {}) }));
32
+ };
33
+ var res = await send();
34
+ return (await renewAndRetry(res.status, false, send)) || res;
10
35
  }
11
36
 
12
37
  /**
@@ -19,6 +44,16 @@ export function uploadHeaders() {
19
44
  return Object.assign({}, _config.getHeaders ? _config.getHeaders() : _config.headers);
20
45
  }
21
46
 
47
+ /**
48
+ * After a request answered `status`: when it was a 401 not yet retried, renew
49
+ * the sign-in once and `retry()` — its promise; otherwise null (keep the
50
+ * answer). Shared by signedFetch and uploadFile, so both follow one rule.
51
+ */
52
+ export function renewAndRetry(status, retried, retry) {
53
+ if (status !== 401 || retried) return null;
54
+ return renewSignIn().then(function(ok) { return ok ? retry() : null; });
55
+ }
56
+
22
57
  /**
23
58
  * Upload files to the server.
24
59
  * @param {File[]} files - Files to upload
@@ -65,6 +100,9 @@ export function uploadFile(files, options = {}) {
65
100
  }
66
101
 
67
102
  xhr.onload = function() {
103
+ // A token that ran out while the page sat open: renew once, send again.
104
+ var again = renewAndRetry(xhr.status, options.renewed, function() { return uploadFile(files, Object.assign({}, options, { renewed: true })); });
105
+ if (again) return again.then(function(r) { return r === null ? reject(new Error('Upload failed: sign-in expired')) : resolve(r); }, reject);
68
106
  try {
69
107
  var response = JSON.parse(xhr.responseText);
70
108
  if (xhr.status >= 200 && xhr.status < 300) {
@@ -5,7 +5,7 @@
5
5
  // '/imports', or '/api/imports' behind a proxy prefix. Requests carry the
6
6
  // headers configureUpload was given (uploadHeaders): sign-in and tenancy.
7
7
 
8
- import { uploadFile, uploadHeaders } from '../fileUpload/uploadFile.js';
8
+ import { uploadFile, signedFetch } from '../fileUpload/uploadFile.js';
9
9
 
10
10
  /**
11
11
  * How a picked file is sent: the app's own `upload` when it gives one —
@@ -28,9 +28,9 @@ export function createImportsApi(basePath) {
28
28
  var base = String(basePath || '/imports').replace(/\/+$/, '');
29
29
 
30
30
  async function call(method, path, body) {
31
- var headers = uploadHeaders();
32
- if (body) headers['content-type'] = 'application/json';
33
- var res = await fetch(base + path, { method: method, headers: headers, body: body ? JSON.stringify(body) : undefined });
31
+ var headers = body ? { 'content-type': 'application/json' } : {};
32
+ // signedFetch: the upload headers, and one renewal of an expired sign-in.
33
+ var res = await signedFetch(base + path, { method: method, headers: headers, body: body ? JSON.stringify(body) : undefined });
34
34
  var data = await res.json().catch(function() { return {}; });
35
35
  if (!res.ok) throw new Error(data.error || ('The request failed (' + res.status + ')'));
36
36
  return data;
@@ -51,7 +51,7 @@ export function createImportsApi(basePath) {
51
51
  remove: function(id) { return call('POST', '/history/' + encodeURIComponent(id) + '/delete'); },
52
52
  /** The dropped rows as a file: { blob, name } — saving it is the page's job. */
53
53
  droppedFile: async function(id) {
54
- var res = await fetch(base + '/history/' + encodeURIComponent(id) + '/dropped/file', { headers: uploadHeaders() });
54
+ var res = await signedFetch(base + '/history/' + encodeURIComponent(id) + '/dropped/file');
55
55
  if (!res.ok) {
56
56
  var data = await res.json().catch(function() { return {}; });
57
57
  throw new Error(data.error || ('The download failed (' + res.status + ')'));
package/src/index.js CHANGED
@@ -67,7 +67,7 @@ export { useImportsController } from './imports/useImportsController.js';
67
67
  export { IMPORTS_RULES } from './imports/validateDesign.js';
68
68
  export { ImportsSample } from './imports/designs/index.js';
69
69
  export { ImportsPage } from './imports/pages.jsx';
70
- export { uploadHeaders } from './fileUpload/uploadFile.js';
70
+ export { uploadHeaders, signedFetch, renewSignIn, renewAndRetry } from './fileUpload/uploadFile.js';
71
71
 
72
72
  // NumberField — model
73
73
  export {