@wordpress/api-fetch 6.35.0 → 6.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/build/index.js +26 -43
  3. package/build/index.js.map +1 -1
  4. package/build/middlewares/fetch-all-middleware.js +16 -32
  5. package/build/middlewares/fetch-all-middleware.js.map +1 -1
  6. package/build/middlewares/http-v1.js +6 -8
  7. package/build/middlewares/http-v1.js.map +1 -1
  8. package/build/middlewares/media-upload.js +4 -14
  9. package/build/middlewares/media-upload.js.map +1 -1
  10. package/build/middlewares/namespace-endpoint.js +2 -6
  11. package/build/middlewares/namespace-endpoint.js.map +1 -1
  12. package/build/middlewares/nonce.js +7 -8
  13. package/build/middlewares/nonce.js.map +1 -1
  14. package/build/middlewares/preloading.js +5 -14
  15. package/build/middlewares/preloading.js.map +1 -1
  16. package/build/middlewares/root-url.js +4 -11
  17. package/build/middlewares/root-url.js.map +1 -1
  18. package/build/middlewares/theme-preview.js +0 -5
  19. package/build/middlewares/theme-preview.js.map +1 -1
  20. package/build/middlewares/user-locale.js +0 -5
  21. package/build/middlewares/user-locale.js.map +1 -1
  22. package/build/types.js.map +1 -1
  23. package/build/utils/response.js +3 -14
  24. package/build/utils/response.js.map +1 -1
  25. package/build-module/index.js +28 -32
  26. package/build-module/index.js.map +1 -1
  27. package/build-module/middlewares/fetch-all-middleware.js +18 -30
  28. package/build-module/middlewares/fetch-all-middleware.js.map +1 -1
  29. package/build-module/middlewares/http-v1.js +6 -7
  30. package/build-module/middlewares/http-v1.js.map +1 -1
  31. package/build-module/middlewares/media-upload.js +6 -13
  32. package/build-module/middlewares/media-upload.js.map +1 -1
  33. package/build-module/middlewares/namespace-endpoint.js +2 -5
  34. package/build-module/middlewares/namespace-endpoint.js.map +1 -1
  35. package/build-module/middlewares/nonce.js +7 -7
  36. package/build-module/middlewares/nonce.js.map +1 -1
  37. package/build-module/middlewares/preloading.js +6 -13
  38. package/build-module/middlewares/preloading.js.map +1 -1
  39. package/build-module/middlewares/root-url.js +5 -9
  40. package/build-module/middlewares/root-url.js.map +1 -1
  41. package/build-module/middlewares/theme-preview.js +1 -4
  42. package/build-module/middlewares/theme-preview.js.map +1 -1
  43. package/build-module/middlewares/user-locale.js +1 -4
  44. package/build-module/middlewares/user-locale.js.map +1 -1
  45. package/build-module/types.js.map +1 -1
  46. package/build-module/utils/response.js +4 -11
  47. package/build-module/utils/response.js.map +1 -1
  48. package/build-types/index.d.ts +6 -6
  49. package/build-types/index.d.ts.map +1 -1
  50. package/package.json +4 -4
  51. package/tsconfig.tsbuildinfo +1 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 6.37.0 (2023-08-16)
6
+
7
+ ## 6.36.0 (2023-08-10)
8
+
5
9
  ## 6.35.0 (2023-07-20)
6
10
 
7
11
  ## 6.34.0 (2023-07-05)
package/build/index.js CHANGED
@@ -1,34 +1,21 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  Object.defineProperty(exports, "__esModule", {
6
5
  value: true
7
6
  });
8
7
  exports.default = void 0;
9
-
10
8
  var _i18n = require("@wordpress/i18n");
11
-
12
9
  var _nonce = _interopRequireDefault(require("./middlewares/nonce"));
13
-
14
10
  var _rootUrl = _interopRequireDefault(require("./middlewares/root-url"));
15
-
16
11
  var _preloading = _interopRequireDefault(require("./middlewares/preloading"));
17
-
18
12
  var _fetchAllMiddleware = _interopRequireDefault(require("./middlewares/fetch-all-middleware"));
19
-
20
13
  var _namespaceEndpoint = _interopRequireDefault(require("./middlewares/namespace-endpoint"));
21
-
22
14
  var _httpV = _interopRequireDefault(require("./middlewares/http-v1"));
23
-
24
15
  var _userLocale = _interopRequireDefault(require("./middlewares/user-locale"));
25
-
26
16
  var _mediaUpload = _interopRequireDefault(require("./middlewares/media-upload"));
27
-
28
17
  var _themePreview = _interopRequireDefault(require("./middlewares/theme-preview"));
29
-
30
18
  var _response = require("./utils/response");
31
-
32
19
  /**
33
20
  * WordPress dependencies
34
21
  */
@@ -50,34 +37,34 @@ const DEFAULT_HEADERS = {
50
37
  // See: https://core.trac.wordpress.org/ticket/44534
51
38
  Accept: 'application/json, */*;q=0.1'
52
39
  };
40
+
53
41
  /**
54
42
  * Default set of fetch option values which should be sent with every request
55
43
  * unless explicitly provided through apiFetch options.
56
44
  *
57
45
  * @type {Object}
58
46
  */
59
-
60
47
  const DEFAULT_OPTIONS = {
61
48
  credentials: 'include'
62
49
  };
63
- /** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
64
50
 
51
+ /** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
65
52
  /** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
66
53
 
67
54
  /**
68
55
  * @type {import('./types').APIFetchMiddleware[]}
69
56
  */
70
-
71
57
  const middlewares = [_userLocale.default, _namespaceEndpoint.default, _httpV.default, _fetchAllMiddleware.default];
58
+
72
59
  /**
73
60
  * Register a middleware
74
61
  *
75
62
  * @param {import('./types').APIFetchMiddleware} middleware
76
63
  */
77
-
78
64
  function registerMiddleware(middleware) {
79
65
  middlewares.unshift(middleware);
80
66
  }
67
+
81
68
  /**
82
69
  * Checks the status of a response, throwing the Response as an error if
83
70
  * it is outside the 200 range.
@@ -85,22 +72,18 @@ function registerMiddleware(middleware) {
85
72
  * @param {Response} response
86
73
  * @return {Response} The response if the status is in the 200 range.
87
74
  */
88
-
89
-
90
75
  const checkStatus = response => {
91
76
  if (response.status >= 200 && response.status < 300) {
92
77
  return response;
93
78
  }
94
-
95
79
  throw response;
96
80
  };
81
+
97
82
  /** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
98
83
 
99
84
  /**
100
85
  * @type {FetchHandler}
101
86
  */
102
-
103
-
104
87
  const defaultFetchHandler = nextOptions => {
105
88
  const {
106
89
  url,
@@ -112,19 +95,23 @@ const defaultFetchHandler = nextOptions => {
112
95
  let {
113
96
  body,
114
97
  headers
115
- } = nextOptions; // Merge explicitly-provided headers with default values.
98
+ } = nextOptions;
116
99
 
117
- headers = { ...DEFAULT_HEADERS,
100
+ // Merge explicitly-provided headers with default values.
101
+ headers = {
102
+ ...DEFAULT_HEADERS,
118
103
  ...headers
119
- }; // The `data` property is a shorthand for sending a JSON body.
104
+ };
120
105
 
106
+ // The `data` property is a shorthand for sending a JSON body.
121
107
  if (data) {
122
108
  body = JSON.stringify(data);
123
109
  headers['Content-Type'] = 'application/json';
124
110
  }
125
-
126
- const responsePromise = window.fetch( // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
127
- url || path || window.location.href, { ...DEFAULT_OPTIONS,
111
+ const responsePromise = window.fetch(
112
+ // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
113
+ url || path || window.location.href, {
114
+ ...DEFAULT_OPTIONS,
128
115
  ...remainingOptions,
129
116
  body,
130
117
  headers
@@ -133,55 +120,52 @@ const defaultFetchHandler = nextOptions => {
133
120
  // Re-throw AbortError for the users to handle it themselves.
134
121
  if (err && err.name === 'AbortError') {
135
122
  throw err;
136
- } // Otherwise, there is most likely no network connection.
137
- // Unfortunately the message might depend on the browser.
138
-
123
+ }
139
124
 
125
+ // Otherwise, there is most likely no network connection.
126
+ // Unfortunately the message might depend on the browser.
140
127
  throw {
141
128
  code: 'fetch_error',
142
129
  message: (0, _i18n.__)('You are probably offline.')
143
130
  };
144
131
  });
145
132
  };
146
- /** @type {FetchHandler} */
147
-
148
133
 
134
+ /** @type {FetchHandler} */
149
135
  let fetchHandler = defaultFetchHandler;
136
+
150
137
  /**
151
138
  * Defines a custom fetch handler for making the requests that will override
152
139
  * the default one using window.fetch
153
140
  *
154
141
  * @param {FetchHandler} newFetchHandler The new fetch handler
155
142
  */
156
-
157
143
  function setFetchHandler(newFetchHandler) {
158
144
  fetchHandler = newFetchHandler;
159
145
  }
146
+
160
147
  /**
161
148
  * @template T
162
149
  * @param {import('./types').APIFetchOptions} options
163
150
  * @return {Promise<T>} A promise representing the request processed via the registered middlewares.
164
151
  */
165
-
166
-
167
152
  function apiFetch(options) {
168
153
  // creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
169
154
  // converting `middlewares = [ m1, m2, m3 ]` into:
170
155
  // ```
171
156
  // opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
172
157
  // ```
173
- const enhancedHandler = middlewares.reduceRight((
174
- /** @type {FetchHandler} */
175
- next, middleware) => {
158
+ const enhancedHandler = middlewares.reduceRight(( /** @type {FetchHandler} */next, middleware) => {
176
159
  return workingOptions => middleware(workingOptions, next);
177
160
  }, fetchHandler);
178
161
  return enhancedHandler(options).catch(error => {
179
162
  if (error.code !== 'rest_cookie_invalid_nonce') {
180
163
  return Promise.reject(error);
181
- } // If the nonce is invalid, refresh it and try again.
164
+ }
182
165
 
183
-
184
- return window // @ts-ignore
166
+ // If the nonce is invalid, refresh it and try again.
167
+ return window
168
+ // @ts-ignore
185
169
  .fetch(apiFetch.nonceEndpoint).then(checkStatus).then(data => data.text()).then(text => {
186
170
  // @ts-ignore
187
171
  apiFetch.nonceMiddleware.nonce = text;
@@ -189,7 +173,6 @@ function apiFetch(options) {
189
173
  });
190
174
  });
191
175
  }
192
-
193
176
  apiFetch.use = registerMiddleware;
194
177
  apiFetch.setFetchHandler = setFetchHandler;
195
178
  apiFetch.createNonceMiddleware = _nonce.default;
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/api-fetch/src/index.js"],"names":["DEFAULT_HEADERS","Accept","DEFAULT_OPTIONS","credentials","middlewares","userLocaleMiddleware","namespaceEndpointMiddleware","httpV1Middleware","fetchAllMiddleware","registerMiddleware","middleware","unshift","checkStatus","response","status","defaultFetchHandler","nextOptions","url","path","data","parse","remainingOptions","body","headers","JSON","stringify","responsePromise","window","fetch","location","href","then","value","Promise","resolve","catch","err","name","code","message","fetchHandler","setFetchHandler","newFetchHandler","apiFetch","options","enhancedHandler","reduceRight","next","workingOptions","error","reject","nonceEndpoint","text","nonceMiddleware","nonce","use","createNonceMiddleware","createPreloadingMiddleware","createRootURLMiddleware","mediaUploadMiddleware","createThemePreviewMiddleware"],"mappings":";;;;;;;;;AAGA;;AAKA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAjBA;AACA;AACA;;AAGA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,eAAe,GAAG;AACvB;AACA;AACA;AACA;AACAC,EAAAA,MAAM,EAAE;AALe,CAAxB;AAQA;AACA;AACA;AACA;AACA;AACA;;AACA,MAAMC,eAAe,GAAG;AACvBC,EAAAA,WAAW,EAAE;AADU,CAAxB;AAIA;;AACA;;AAEA;AACA;AACA;;AACA,MAAMC,WAAW,GAAG,CACnBC,mBADmB,EAEnBC,0BAFmB,EAGnBC,cAHmB,EAInBC,2BAJmB,CAApB;AAOA;AACA;AACA;AACA;AACA;;AACA,SAASC,kBAAT,CAA6BC,UAA7B,EAA0C;AACzCN,EAAAA,WAAW,CAACO,OAAZ,CAAqBD,UAArB;AACA;AAED;AACA;AACA;AACA;AACA;AACA;AACA;;;AACA,MAAME,WAAW,GAAKC,QAAF,IAAgB;AACnC,MAAKA,QAAQ,CAACC,MAAT,IAAmB,GAAnB,IAA0BD,QAAQ,CAACC,MAAT,GAAkB,GAAjD,EAAuD;AACtD,WAAOD,QAAP;AACA;;AAED,QAAMA,QAAN;AACA,CAND;AAQA;;AAEA;AACA;AACA;;;AACA,MAAME,mBAAmB,GAAKC,WAAF,IAAmB;AAC9C,QAAM;AAAEC,IAAAA,GAAF;AAAOC,IAAAA,IAAP;AAAaC,IAAAA,IAAb;AAAmBC,IAAAA,KAAK,GAAG,IAA3B;AAAiC,OAAGC;AAApC,MAAyDL,WAA/D;AACA,MAAI;AAAEM,IAAAA,IAAF;AAAQC,IAAAA;AAAR,MAAoBP,WAAx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AACA;AACA;AACA;AACA;AACA,QAAMC,eAAe,GAAGzC,WAAW,CAAC0C,WAAZ,CACvB;AAAE;AAA4BC,EAAAA,IAA9B,EAAoCrC,UAApC,KAAoD;AACnD,WAASsC,cAAF,IAAsBtC,UAAU,CAAEsC,cAAF,EAAkBD,IAAlB,CAAvC;AACA,GAHsB,EAIvBP,YAJuB,CAAxB;AAOA,SAAOK,eAAe,CAAED,OAAF,CAAf,CAA2BT,KAA3B,CAAoCc,KAAF,IAAa;AACrD,QAAKA,KAAK,CAACX,IAAN,KAAe,2BAApB,EAAkD;AACjD,aAAOL,OAAO,CAACiB,MAAR,CAAgBD,KAAhB,CAAP;AACA,KAHoD,CAKrD;;;AACA,WACCtB,MAAM,CACL;AADK,KAEJC,KAFF,CAESe,QAAQ,CAACQ,aAFlB,EAGEpB,IAHF,CAGQnB,WAHR,EAIEmB,IAJF,CAIUZ,IAAF,IAAYA,IAAI,CAACiC,IAAL,EAJpB,EAKErB,IALF,CAKUqB,IAAF,IAAY;AAClB;AACAT,MAAAA,QAAQ,CAACU,eAAT,CAAyBC,KAAzB,GAAiCF,IAAjC;AACA,aAAOT,QAAQ,CAAEC,OAAF,CAAf;AACA,KATF,CADD;AAYA,GAlBM,CAAP;AAmBA;;AAEDD,QAAQ,CAACY,GAAT,GAAe9C,kBAAf;AACAkC,QAAQ,CAACF,eAAT,GAA2BA,eAA3B;AAEAE,QAAQ,CAACa,qBAAT,GAAiCA,cAAjC;AACAb,QAAQ,CAACc,0BAAT,GAAsCA,mBAAtC;AACAd,QAAQ,CAACe,uBAAT,GAAmCA,gBAAnC;AACAf,QAAQ,CAACnC,kBAAT,GAA8BA,2BAA9B;AACAmC,QAAQ,CAACgB,qBAAT,GAAiCA,oBAAjC;AACAhB,QAAQ,CAACiB,4BAAT,GAAwCA,qBAAxC;eAEejB,Q","sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport createNonceMiddleware from './middlewares/nonce';\nimport createRootURLMiddleware from './middlewares/root-url';\nimport createPreloadingMiddleware from './middlewares/preloading';\nimport fetchAllMiddleware from './middlewares/fetch-all-middleware';\nimport namespaceEndpointMiddleware from './middlewares/namespace-endpoint';\nimport httpV1Middleware from './middlewares/http-v1';\nimport userLocaleMiddleware from './middlewares/user-locale';\nimport mediaUploadMiddleware from './middlewares/media-upload';\nimport createThemePreviewMiddleware from './middlewares/theme-preview';\nimport {\n\tparseResponseAndNormalizeError,\n\tparseAndThrowError,\n} from './utils/response';\n\n/**\n * Default set of header values which should be sent with every request unless\n * explicitly provided through apiFetch options.\n *\n * @type {Record<string, string>}\n */\nconst DEFAULT_HEADERS = {\n\t// The backend uses the Accept header as a condition for considering an\n\t// incoming request as a REST request.\n\t//\n\t// See: https://core.trac.wordpress.org/ticket/44534\n\tAccept: 'application/json, */*;q=0.1',\n};\n\n/**\n * Default set of fetch option values which should be sent with every request\n * unless explicitly provided through apiFetch options.\n *\n * @type {Object}\n */\nconst DEFAULT_OPTIONS = {\n\tcredentials: 'include',\n};\n\n/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */\n/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */\n\n/**\n * @type {import('./types').APIFetchMiddleware[]}\n */\nconst middlewares = [\n\tuserLocaleMiddleware,\n\tnamespaceEndpointMiddleware,\n\thttpV1Middleware,\n\tfetchAllMiddleware,\n];\n\n/**\n * Register a middleware\n *\n * @param {import('./types').APIFetchMiddleware} middleware\n */\nfunction registerMiddleware( middleware ) {\n\tmiddlewares.unshift( middleware );\n}\n\n/**\n * Checks the status of a response, throwing the Response as an error if\n * it is outside the 200 range.\n *\n * @param {Response} response\n * @return {Response} The response if the status is in the 200 range.\n */\nconst checkStatus = ( response ) => {\n\tif ( response.status >= 200 && response.status < 300 ) {\n\t\treturn response;\n\t}\n\n\tthrow response;\n};\n\n/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/\n\n/**\n * @type {FetchHandler}\n */\nconst defaultFetchHandler = ( nextOptions ) => {\n\tconst { url, path, data, parse = true, ...remainingOptions } = nextOptions;\n\tlet { body, headers } = nextOptions;\n\n\t// Merge explicitly-provided headers with default values.\n\theaders = { ...DEFAULT_HEADERS, ...headers };\n\n\t// The `data` property is a shorthand for sending a JSON body.\n\tif ( data ) {\n\t\tbody = JSON.stringify( data );\n\t\theaders[ 'Content-Type' ] = 'application/json';\n\t}\n\n\tconst responsePromise = window.fetch(\n\t\t// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.\n\t\turl || path || window.location.href,\n\t\t{\n\t\t\t...DEFAULT_OPTIONS,\n\t\t\t...remainingOptions,\n\t\t\tbody,\n\t\t\theaders,\n\t\t}\n\t);\n\n\treturn responsePromise.then(\n\t\t( value ) =>\n\t\t\tPromise.resolve( value )\n\t\t\t\t.then( checkStatus )\n\t\t\t\t.catch( ( response ) => parseAndThrowError( response, parse ) )\n\t\t\t\t.then( ( response ) =>\n\t\t\t\t\tparseResponseAndNormalizeError( response, parse )\n\t\t\t\t),\n\t\t( err ) => {\n\t\t\t// Re-throw AbortError for the users to handle it themselves.\n\t\t\tif ( err && err.name === 'AbortError' ) {\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\t// Otherwise, there is most likely no network connection.\n\t\t\t// Unfortunately the message might depend on the browser.\n\t\t\tthrow {\n\t\t\t\tcode: 'fetch_error',\n\t\t\t\tmessage: __( 'You are probably offline.' ),\n\t\t\t};\n\t\t}\n\t);\n};\n\n/** @type {FetchHandler} */\nlet fetchHandler = defaultFetchHandler;\n\n/**\n * Defines a custom fetch handler for making the requests that will override\n * the default one using window.fetch\n *\n * @param {FetchHandler} newFetchHandler The new fetch handler\n */\nfunction setFetchHandler( newFetchHandler ) {\n\tfetchHandler = newFetchHandler;\n}\n\n/**\n * @template T\n * @param {import('./types').APIFetchOptions} options\n * @return {Promise<T>} A promise representing the request processed via the registered middlewares.\n */\nfunction apiFetch( options ) {\n\t// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,\n\t// converting `middlewares = [ m1, m2, m3 ]` into:\n\t// ```\n\t// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );\n\t// ```\n\tconst enhancedHandler = middlewares.reduceRight(\n\t\t( /** @type {FetchHandler} */ next, middleware ) => {\n\t\t\treturn ( workingOptions ) => middleware( workingOptions, next );\n\t\t},\n\t\tfetchHandler\n\t);\n\n\treturn enhancedHandler( options ).catch( ( error ) => {\n\t\tif ( error.code !== 'rest_cookie_invalid_nonce' ) {\n\t\t\treturn Promise.reject( error );\n\t\t}\n\n\t\t// If the nonce is invalid, refresh it and try again.\n\t\treturn (\n\t\t\twindow\n\t\t\t\t// @ts-ignore\n\t\t\t\t.fetch( apiFetch.nonceEndpoint )\n\t\t\t\t.then( checkStatus )\n\t\t\t\t.then( ( data ) => data.text() )\n\t\t\t\t.then( ( text ) => {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tapiFetch.nonceMiddleware.nonce = text;\n\t\t\t\t\treturn apiFetch( options );\n\t\t\t\t} )\n\t\t);\n\t} );\n}\n\napiFetch.use = registerMiddleware;\napiFetch.setFetchHandler = setFetchHandler;\n\napiFetch.createNonceMiddleware = createNonceMiddleware;\napiFetch.createPreloadingMiddleware = createPreloadingMiddleware;\napiFetch.createRootURLMiddleware = createRootURLMiddleware;\napiFetch.fetchAllMiddleware = fetchAllMiddleware;\napiFetch.mediaUploadMiddleware = mediaUploadMiddleware;\napiFetch.createThemePreviewMiddleware = createThemePreviewMiddleware;\n\nexport default apiFetch;\n"]}
1
+ {"version":3,"names":["_i18n","require","_nonce","_interopRequireDefault","_rootUrl","_preloading","_fetchAllMiddleware","_namespaceEndpoint","_httpV","_userLocale","_mediaUpload","_themePreview","_response","DEFAULT_HEADERS","Accept","DEFAULT_OPTIONS","credentials","middlewares","userLocaleMiddleware","namespaceEndpointMiddleware","httpV1Middleware","fetchAllMiddleware","registerMiddleware","middleware","unshift","checkStatus","response","status","defaultFetchHandler","nextOptions","url","path","data","parse","remainingOptions","body","headers","JSON","stringify","responsePromise","window","fetch","location","href","then","value","Promise","resolve","catch","parseAndThrowError","parseResponseAndNormalizeError","err","name","code","message","__","fetchHandler","setFetchHandler","newFetchHandler","apiFetch","options","enhancedHandler","reduceRight","next","workingOptions","error","reject","nonceEndpoint","text","nonceMiddleware","nonce","use","createNonceMiddleware","createPreloadingMiddleware","createRootURLMiddleware","mediaUploadMiddleware","createThemePreviewMiddleware","_default","exports","default"],"sources":["@wordpress/api-fetch/src/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport createNonceMiddleware from './middlewares/nonce';\nimport createRootURLMiddleware from './middlewares/root-url';\nimport createPreloadingMiddleware from './middlewares/preloading';\nimport fetchAllMiddleware from './middlewares/fetch-all-middleware';\nimport namespaceEndpointMiddleware from './middlewares/namespace-endpoint';\nimport httpV1Middleware from './middlewares/http-v1';\nimport userLocaleMiddleware from './middlewares/user-locale';\nimport mediaUploadMiddleware from './middlewares/media-upload';\nimport createThemePreviewMiddleware from './middlewares/theme-preview';\nimport {\n\tparseResponseAndNormalizeError,\n\tparseAndThrowError,\n} from './utils/response';\n\n/**\n * Default set of header values which should be sent with every request unless\n * explicitly provided through apiFetch options.\n *\n * @type {Record<string, string>}\n */\nconst DEFAULT_HEADERS = {\n\t// The backend uses the Accept header as a condition for considering an\n\t// incoming request as a REST request.\n\t//\n\t// See: https://core.trac.wordpress.org/ticket/44534\n\tAccept: 'application/json, */*;q=0.1',\n};\n\n/**\n * Default set of fetch option values which should be sent with every request\n * unless explicitly provided through apiFetch options.\n *\n * @type {Object}\n */\nconst DEFAULT_OPTIONS = {\n\tcredentials: 'include',\n};\n\n/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */\n/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */\n\n/**\n * @type {import('./types').APIFetchMiddleware[]}\n */\nconst middlewares = [\n\tuserLocaleMiddleware,\n\tnamespaceEndpointMiddleware,\n\thttpV1Middleware,\n\tfetchAllMiddleware,\n];\n\n/**\n * Register a middleware\n *\n * @param {import('./types').APIFetchMiddleware} middleware\n */\nfunction registerMiddleware( middleware ) {\n\tmiddlewares.unshift( middleware );\n}\n\n/**\n * Checks the status of a response, throwing the Response as an error if\n * it is outside the 200 range.\n *\n * @param {Response} response\n * @return {Response} The response if the status is in the 200 range.\n */\nconst checkStatus = ( response ) => {\n\tif ( response.status >= 200 && response.status < 300 ) {\n\t\treturn response;\n\t}\n\n\tthrow response;\n};\n\n/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/\n\n/**\n * @type {FetchHandler}\n */\nconst defaultFetchHandler = ( nextOptions ) => {\n\tconst { url, path, data, parse = true, ...remainingOptions } = nextOptions;\n\tlet { body, headers } = nextOptions;\n\n\t// Merge explicitly-provided headers with default values.\n\theaders = { ...DEFAULT_HEADERS, ...headers };\n\n\t// The `data` property is a shorthand for sending a JSON body.\n\tif ( data ) {\n\t\tbody = JSON.stringify( data );\n\t\theaders[ 'Content-Type' ] = 'application/json';\n\t}\n\n\tconst responsePromise = window.fetch(\n\t\t// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.\n\t\turl || path || window.location.href,\n\t\t{\n\t\t\t...DEFAULT_OPTIONS,\n\t\t\t...remainingOptions,\n\t\t\tbody,\n\t\t\theaders,\n\t\t}\n\t);\n\n\treturn responsePromise.then(\n\t\t( value ) =>\n\t\t\tPromise.resolve( value )\n\t\t\t\t.then( checkStatus )\n\t\t\t\t.catch( ( response ) => parseAndThrowError( response, parse ) )\n\t\t\t\t.then( ( response ) =>\n\t\t\t\t\tparseResponseAndNormalizeError( response, parse )\n\t\t\t\t),\n\t\t( err ) => {\n\t\t\t// Re-throw AbortError for the users to handle it themselves.\n\t\t\tif ( err && err.name === 'AbortError' ) {\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\t// Otherwise, there is most likely no network connection.\n\t\t\t// Unfortunately the message might depend on the browser.\n\t\t\tthrow {\n\t\t\t\tcode: 'fetch_error',\n\t\t\t\tmessage: __( 'You are probably offline.' ),\n\t\t\t};\n\t\t}\n\t);\n};\n\n/** @type {FetchHandler} */\nlet fetchHandler = defaultFetchHandler;\n\n/**\n * Defines a custom fetch handler for making the requests that will override\n * the default one using window.fetch\n *\n * @param {FetchHandler} newFetchHandler The new fetch handler\n */\nfunction setFetchHandler( newFetchHandler ) {\n\tfetchHandler = newFetchHandler;\n}\n\n/**\n * @template T\n * @param {import('./types').APIFetchOptions} options\n * @return {Promise<T>} A promise representing the request processed via the registered middlewares.\n */\nfunction apiFetch( options ) {\n\t// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,\n\t// converting `middlewares = [ m1, m2, m3 ]` into:\n\t// ```\n\t// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );\n\t// ```\n\tconst enhancedHandler = middlewares.reduceRight(\n\t\t( /** @type {FetchHandler} */ next, middleware ) => {\n\t\t\treturn ( workingOptions ) => middleware( workingOptions, next );\n\t\t},\n\t\tfetchHandler\n\t);\n\n\treturn enhancedHandler( options ).catch( ( error ) => {\n\t\tif ( error.code !== 'rest_cookie_invalid_nonce' ) {\n\t\t\treturn Promise.reject( error );\n\t\t}\n\n\t\t// If the nonce is invalid, refresh it and try again.\n\t\treturn (\n\t\t\twindow\n\t\t\t\t// @ts-ignore\n\t\t\t\t.fetch( apiFetch.nonceEndpoint )\n\t\t\t\t.then( checkStatus )\n\t\t\t\t.then( ( data ) => data.text() )\n\t\t\t\t.then( ( text ) => {\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tapiFetch.nonceMiddleware.nonce = text;\n\t\t\t\t\treturn apiFetch( options );\n\t\t\t\t} )\n\t\t);\n\t} );\n}\n\napiFetch.use = registerMiddleware;\napiFetch.setFetchHandler = setFetchHandler;\n\napiFetch.createNonceMiddleware = createNonceMiddleware;\napiFetch.createPreloadingMiddleware = createPreloadingMiddleware;\napiFetch.createRootURLMiddleware = createRootURLMiddleware;\napiFetch.fetchAllMiddleware = fetchAllMiddleware;\napiFetch.mediaUploadMiddleware = mediaUploadMiddleware;\napiFetch.createThemePreviewMiddleware = createThemePreviewMiddleware;\n\nexport default apiFetch;\n"],"mappings":";;;;;;;AAGA,IAAAA,KAAA,GAAAC,OAAA;AAKA,IAAAC,MAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,QAAA,GAAAD,sBAAA,CAAAF,OAAA;AACA,IAAAI,WAAA,GAAAF,sBAAA,CAAAF,OAAA;AACA,IAAAK,mBAAA,GAAAH,sBAAA,CAAAF,OAAA;AACA,IAAAM,kBAAA,GAAAJ,sBAAA,CAAAF,OAAA;AACA,IAAAO,MAAA,GAAAL,sBAAA,CAAAF,OAAA;AACA,IAAAQ,WAAA,GAAAN,sBAAA,CAAAF,OAAA;AACA,IAAAS,YAAA,GAAAP,sBAAA,CAAAF,OAAA;AACA,IAAAU,aAAA,GAAAR,sBAAA,CAAAF,OAAA;AACA,IAAAW,SAAA,GAAAX,OAAA;AAjBA;AACA;AACA;;AAGA;AACA;AACA;;AAeA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMY,eAAe,GAAG;EACvB;EACA;EACA;EACA;EACAC,MAAM,EAAE;AACT,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,eAAe,GAAG;EACvBC,WAAW,EAAE;AACd,CAAC;;AAED;AACA;;AAEA;AACA;AACA;AACA,MAAMC,WAAW,GAAG,CACnBC,mBAAoB,EACpBC,0BAA2B,EAC3BC,cAAgB,EAChBC,2BAAkB,CAClB;;AAED;AACA;AACA;AACA;AACA;AACA,SAASC,kBAAkBA,CAAEC,UAAU,EAAG;EACzCN,WAAW,CAACO,OAAO,CAAED,UAAW,CAAC;AAClC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAME,WAAW,GAAKC,QAAQ,IAAM;EACnC,IAAKA,QAAQ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AAGA,mBAA0B;AAChEd,QAAQ,CAACe,uBAAuB,GAAGA,gBAAuB;AAC1Df,QAAQ,CAACtC,kBAAkB,GAAGA,2BAAkB;AAChDsC,QAAQ,CAACgB,qBAAqB,GAAGA,oBAAqB;AACtDhB,QAAQ,CAACiB,4BAA4B,GAAGA,qBAA4B;AAAC,IAAAC,QAAA,GAEtDlB,QAAQ;AAAAmB,OAAA,CAAAC,OAAA,GAAAF,QAAA"}
@@ -1,16 +1,12 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  Object.defineProperty(exports, "__esModule", {
6
5
  value: true
7
6
  });
8
7
  exports.default = void 0;
9
-
10
8
  var _url = require("@wordpress/url");
11
-
12
9
  var _ = _interopRequireDefault(require(".."));
13
-
14
10
  /**
15
11
  * WordPress dependencies
16
12
  */
@@ -30,58 +26,55 @@ const modifyQuery = ({
30
26
  path,
31
27
  url,
32
28
  ...options
33
- }, queryArgs) => ({ ...options,
29
+ }, queryArgs) => ({
30
+ ...options,
34
31
  url: url && (0, _url.addQueryArgs)(url, queryArgs),
35
32
  path: path && (0, _url.addQueryArgs)(path, queryArgs)
36
33
  });
34
+
37
35
  /**
38
36
  * Duplicates parsing functionality from apiFetch.
39
37
  *
40
38
  * @param {Response} response
41
39
  * @return {Promise<any>} Parsed response json.
42
40
  */
43
-
44
-
45
41
  const parseResponse = response => response.json ? response.json() : Promise.reject(response);
42
+
46
43
  /**
47
44
  * @param {string | null} linkHeader
48
45
  * @return {{ next?: string }} The parsed link header.
49
46
  */
50
-
51
-
52
47
  const parseLinkHeader = linkHeader => {
53
48
  if (!linkHeader) {
54
49
  return {};
55
50
  }
56
-
57
51
  const match = linkHeader.match(/<([^>]+)>; rel="next"/);
58
52
  return match ? {
59
53
  next: match[1]
60
54
  } : {};
61
55
  };
56
+
62
57
  /**
63
58
  * @param {Response} response
64
59
  * @return {string | undefined} The next page URL.
65
60
  */
66
-
67
-
68
61
  const getNextPageUrl = response => {
69
62
  const {
70
63
  next
71
64
  } = parseLinkHeader(response.headers.get('link'));
72
65
  return next;
73
66
  };
67
+
74
68
  /**
75
69
  * @param {import('../types').APIFetchOptions} options
76
70
  * @return {boolean} True if the request contains an unbounded query.
77
71
  */
78
-
79
-
80
72
  const requestContainsUnboundedQuery = options => {
81
73
  const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
82
74
  const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
83
75
  return pathIsUnbounded || urlIsUnbounded;
84
76
  };
77
+
85
78
  /**
86
79
  * The REST API enforces an upper limit on the per_page option. To handle large
87
80
  * collections, apiFetch consumers can pass `per_page=-1`; this middleware will
@@ -89,47 +82,40 @@ const requestContainsUnboundedQuery = options => {
89
82
  *
90
83
  * @type {import('../types').APIFetchMiddleware}
91
84
  */
92
-
93
-
94
85
  const fetchAllMiddleware = async (options, next) => {
95
86
  if (options.parse === false) {
96
87
  // If a consumer has opted out of parsing, do not apply middleware.
97
88
  return next(options);
98
89
  }
99
-
100
90
  if (!requestContainsUnboundedQuery(options)) {
101
91
  // If neither url nor path is requesting all items, do not apply middleware.
102
92
  return next(options);
103
- } // Retrieve requested page of results.
104
-
93
+ }
105
94
 
106
- const response = await (0, _.default)({ ...modifyQuery(options, {
95
+ // Retrieve requested page of results.
96
+ const response = await (0, _.default)({
97
+ ...modifyQuery(options, {
107
98
  per_page: 100
108
99
  }),
109
100
  // Ensure headers are returned for page 1.
110
101
  parse: false
111
102
  });
112
103
  const results = await parseResponse(response);
113
-
114
104
  if (!Array.isArray(results)) {
115
105
  // We have no reliable way of merging non-array results.
116
106
  return results;
117
107
  }
118
-
119
108
  let nextPage = getNextPageUrl(response);
120
-
121
109
  if (!nextPage) {
122
110
  // There are no further pages to request.
123
111
  return results;
124
- } // Iteratively fetch all remaining pages until no "next" header is found.
125
-
126
-
127
- let mergedResults =
128
- /** @type {any[]} */
129
- [].concat(results);
112
+ }
130
113
 
114
+ // Iteratively fetch all remaining pages until no "next" header is found.
115
+ let mergedResults = /** @type {any[]} */[].concat(results);
131
116
  while (nextPage) {
132
- const nextResponse = await (0, _.default)({ ...options,
117
+ const nextResponse = await (0, _.default)({
118
+ ...options,
133
119
  // Ensure the URL for the next page is used instead of any provided path.
134
120
  path: undefined,
135
121
  url: nextPage,
@@ -140,10 +126,8 @@ const fetchAllMiddleware = async (options, next) => {
140
126
  mergedResults = mergedResults.concat(nextResults);
141
127
  nextPage = getNextPageUrl(nextResponse);
142
128
  }
143
-
144
129
  return mergedResults;
145
130
  };
146
-
147
131
  var _default = fetchAllMiddleware;
148
132
  exports.default = _default;
149
133
  //# sourceMappingURL=fetch-all-middleware.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/fetch-all-middleware.js"],"names":["modifyQuery","path","url","options","queryArgs","parseResponse","response","json","Promise","reject","parseLinkHeader","linkHeader","match","next","getNextPageUrl","headers","get","requestContainsUnboundedQuery","pathIsUnbounded","indexOf","urlIsUnbounded","fetchAllMiddleware","parse","per_page","results","Array","isArray","nextPage","mergedResults","concat","nextResponse","undefined","nextResults"],"mappings":";;;;;;;;;AAGA;;AAKA;;AARA;AACA;AACA;;AAGA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,WAAW,GAAG,CAAE;AAAEC,EAAAA,IAAF;AAAQC,EAAAA,GAAR;AAAa,KAAGC;AAAhB,CAAF,EAA6BC,SAA7B,MAA8C,EACjE,GAAGD,OAD8D;AAEjED,EAAAA,GAAG,EAAEA,GAAG,IAAI,uBAAcA,GAAd,EAAmBE,SAAnB,CAFqD;AAGjEH,EAAAA,IAAI,EAAEA,IAAI,IAAI,uBAAcA,IAAd,EAAoBG,SAApB;AAHmD,CAA9C,CAApB;AAMA;AACA;AACA;AACA;AACA;AACA;;;AACA,MAAMC,aAAa,GAAKC,QAAF,IACrBA,QAAQ,CAACC,IAAT,GAAgBD,QAAQ,C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GARoD,CAUrD;;;AACA,QAAMG,QAAQ,GAAG,MAAM,eAAU,EAChC,GAAGN,WAAW,CAAEG,OAAF,EAAW;AACxBoB,MAAAA,QAAQ,EAAE;AADc,KAAX,CADkB;AAIhC;AACAD,IAAAA,KAAK,EAAE;AALyB,GAAV,CAAvB;AAQA,QAAME,OAAO,GAAG,MAAMnB,aAAa,CAAEC,QAAF,CAAnC;;AAEA,MAAK,CAAEmB,KAAK,CAACC,OAAN,CAAeF,OAAf,CAAP,EAAkC;AACjC;AACA,WAAOA,OAAP;AACA;;AAED,MAAIG,QAAQ,GAAGb,cAAc,CAAER,QAAF,CAA7B;;AAEA,MAAK,CAAEqB,QAAP,EAAkB;AACjB;AACA,WAAOH,OAAP;AACA,GA/BoD,CAiCrD;;;AACA,MAAII,aAAa;AAAG;AAAuB,IAAF,CAAOC,MAAP,CAAeL,OAAf,CAAzC;;AACA,SAAQG,QAAR,EAAmB;AAClB,UAAMG,YAAY,GAAG,MAAM,eAAU,EACpC,GAAG3B,OADiC;AAEpC;AACAF,MAAAA,IAAI,EAAE8B,SAH8B;AAIpC7B,MAAAA,GAAG,EAAEyB,QAJ+B;AAKpC;AACAL,MAAAA,KAAK,EAAE;AAN6B,KAAV,CAA3B;AAQA,UAAMU,WAAW,GAAG,MAAM3B,aAAa,CAAEyB,YAAF,CAAvC;AACAF,IAAAA,aAAa,GAAGA,aAAa,CAACC,MAAd,CAAsBG,WAAtB,CAAhB;AACAL,IAAAA,QAAQ,GAAGb,cAAc,CAAEgB,YAAF,CAAzB;AACA;;AACD,SAAOF,aAAP;AACA,CAjDD;;eAmDeP,kB","sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs } from '@wordpress/url';\n\n/**\n * Internal dependencies\n */\nimport apiFetch from '..';\n\n/**\n * Apply query arguments to both URL and Path, whichever is present.\n *\n * @param {import('../types').APIFetchOptions} props\n * @param {Record<string, string | number>} queryArgs\n * @return {import('../types').APIFetchOptions} The request with the modified query args\n */\nconst modifyQuery = ( { path, url, ...options }, queryArgs ) => ( {\n\t...options,\n\turl: url && addQueryArgs( url, queryArgs ),\n\tpath: path && addQueryArgs( path, queryArgs ),\n} );\n\n/**\n * Duplicates parsing functionality from apiFetch.\n *\n * @param {Response} response\n * @return {Promise<any>} Parsed response json.\n */\nconst parseResponse = ( response ) =>\n\tresponse.json ? response.json() : Promise.reject( response );\n\n/**\n * @param {string | null} linkHeader\n * @return {{ next?: string }} The parsed link header.\n */\nconst parseLinkHeader = ( linkHeader ) => {\n\tif ( ! linkHeader ) {\n\t\treturn {};\n\t}\n\tconst match = linkHeader.match( /<([^>]+)>; rel=\"next\"/ );\n\treturn match\n\t\t? {\n\t\t\t\tnext: match[ 1 ],\n\t\t }\n\t\t: {};\n};\n\n/**\n * @param {Response} response\n * @return {string | undefined} The next page URL.\n */\nconst getNextPageUrl = ( response ) => {\n\tconst { next } = parseLinkHeader( response.headers.get( 'link' ) );\n\treturn next;\n};\n\n/**\n * @param {import('../types').APIFetchOptions} options\n * @return {boolean} True if the request contains an unbounded query.\n */\nconst requestContainsUnboundedQuery = ( options ) => {\n\tconst pathIsUnbounded =\n\t\t!! options.path && options.path.indexOf( 'per_page=-1' ) !== -1;\n\tconst urlIsUnbounded =\n\t\t!! options.url && options.url.indexOf( 'per_page=-1' ) !== -1;\n\treturn pathIsUnbounded || urlIsUnbounded;\n};\n\n/**\n * The REST API enforces an upper limit on the per_page option. To handle large\n * collections, apiFetch consumers can pass `per_page=-1`; this middleware will\n * then recursively assemble a full response array from all available pages.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst fetchAllMiddleware = async ( options, next ) => {\n\tif ( options.parse === false ) {\n\t\t// If a consumer has opted out of parsing, do not apply middleware.\n\t\treturn next( options );\n\t}\n\tif ( ! requestContainsUnboundedQuery( options ) ) {\n\t\t// If neither url nor path is requesting all items, do not apply middleware.\n\t\treturn next( options );\n\t}\n\n\t// Retrieve requested page of results.\n\tconst response = await apiFetch( {\n\t\t...modifyQuery( options, {\n\t\t\tper_page: 100,\n\t\t} ),\n\t\t// Ensure headers are returned for page 1.\n\t\tparse: false,\n\t} );\n\n\tconst results = await parseResponse( response );\n\n\tif ( ! Array.isArray( results ) ) {\n\t\t// We have no reliable way of merging non-array results.\n\t\treturn results;\n\t}\n\n\tlet nextPage = getNextPageUrl( response );\n\n\tif ( ! nextPage ) {\n\t\t// There are no further pages to request.\n\t\treturn results;\n\t}\n\n\t// Iteratively fetch all remaining pages until no \"next\" header is found.\n\tlet mergedResults = /** @type {any[]} */ ( [] ).concat( results );\n\twhile ( nextPage ) {\n\t\tconst nextResponse = await apiFetch( {\n\t\t\t...options,\n\t\t\t// Ensure the URL for the next page is used instead of any provided path.\n\t\t\tpath: undefined,\n\t\t\turl: nextPage,\n\t\t\t// Ensure we still get headers so we can identify the next page.\n\t\t\tparse: false,\n\t\t} );\n\t\tconst nextResults = await parseResponse( nextResponse );\n\t\tmergedResults = mergedResults.concat( nextResults );\n\t\tnextPage = getNextPageUrl( nextResponse );\n\t}\n\treturn mergedResults;\n};\n\nexport default fetchAllMiddleware;\n"]}
1
+ {"version":3,"names":["_url","require","_","_interopRequireDefault","modifyQuery","path","url","options","queryArgs","addQueryArgs","parseResponse","response","json","Promise","reject","parseLinkHeader","linkHeader","match","next","getNextPageUrl","headers","get","requestContainsUnboundedQuery","pathIsUnbounded","indexOf","urlIsUnbounded","fetchAllMiddleware","parse","apiFetch","per_page","results","Array","isArray","nextPage","mergedResults","concat","nextResponse","undefined","nextResults","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/fetch-all-middleware.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs } from '@wordpress/url';\n\n/**\n * Internal dependencies\n */\nimport apiFetch from '..';\n\n/**\n * Apply query arguments to both URL and Path, whichever is present.\n *\n * @param {import('../types').APIFetchOptions} props\n * @param {Record<string, string | number>} queryArgs\n * @return {import('../types').APIFetchOptions} The request with the modified query args\n */\nconst modifyQuery = ( { path, url, ...options }, queryArgs ) => ( {\n\t...options,\n\turl: url && addQueryArgs( url, queryArgs ),\n\tpath: path && addQueryArgs( path, queryArgs ),\n} );\n\n/**\n * Duplicates parsing functionality from apiFetch.\n *\n * @param {Response} response\n * @return {Promise<any>} Parsed response json.\n */\nconst parseResponse = ( response ) =>\n\tresponse.json ? response.json() : Promise.reject( response );\n\n/**\n * @param {string | null} linkHeader\n * @return {{ next?: string }} The parsed link header.\n */\nconst parseLinkHeader = ( linkHeader ) => {\n\tif ( ! linkHeader ) {\n\t\treturn {};\n\t}\n\tconst match = linkHeader.match( /<([^>]+)>; rel=\"next\"/ );\n\treturn match\n\t\t? {\n\t\t\t\tnext: match[ 1 ],\n\t\t }\n\t\t: {};\n};\n\n/**\n * @param {Response} response\n * @return {string | undefined} The next page URL.\n */\nconst getNextPageUrl = ( response ) => {\n\tconst { next } = parseLinkHeader( response.headers.get( 'link' ) );\n\treturn next;\n};\n\n/**\n * @param {import('../types').APIFetchOptions} options\n * @return {boolean} True if the request contains an unbounded query.\n */\nconst requestContainsUnboundedQuery = ( options ) => {\n\tconst pathIsUnbounded =\n\t\t!! options.path && options.path.indexOf( 'per_page=-1' ) !== -1;\n\tconst urlIsUnbounded =\n\t\t!! options.url && options.url.indexOf( 'per_page=-1' ) !== -1;\n\treturn pathIsUnbounded || urlIsUnbounded;\n};\n\n/**\n * The REST API enforces an upper limit on the per_page option. To handle large\n * collections, apiFetch consumers can pass `per_page=-1`; this middleware will\n * then recursively assemble a full response array from all available pages.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst fetchAllMiddleware = async ( options, next ) => {\n\tif ( options.parse === false ) {\n\t\t// If a consumer has opted out of parsing, do not apply middleware.\n\t\treturn next( options );\n\t}\n\tif ( ! requestContainsUnboundedQuery( options ) ) {\n\t\t// If neither url nor path is requesting all items, do not apply middleware.\n\t\treturn next( options );\n\t}\n\n\t// Retrieve requested page of results.\n\tconst response = await apiFetch( {\n\t\t...modifyQuery( options, {\n\t\t\tper_page: 100,\n\t\t} ),\n\t\t// Ensure headers are returned for page 1.\n\t\tparse: false,\n\t} );\n\n\tconst results = await parseResponse( response );\n\n\tif ( ! Array.isArray( results ) ) {\n\t\t// We have no reliable way of merging non-array results.\n\t\treturn results;\n\t}\n\n\tlet nextPage = getNextPageUrl( response );\n\n\tif ( ! nextPage ) {\n\t\t// There are no further pages to request.\n\t\treturn results;\n\t}\n\n\t// Iteratively fetch all remaining pages until no \"next\" header is found.\n\tlet mergedResults = /** @type {any[]} */ ( [] ).concat( results );\n\twhile ( nextPage ) {\n\t\tconst nextResponse = await apiFetch( {\n\t\t\t...options,\n\t\t\t// Ensure the URL for the next page is used instead of any provided path.\n\t\t\tpath: undefined,\n\t\t\turl: nextPage,\n\t\t\t// Ensure we still get headers so we can identify the next page.\n\t\t\tparse: false,\n\t\t} );\n\t\tconst nextResults = await parseResponse( nextResponse );\n\t\tmergedResults = mergedResults.concat( nextResults );\n\t\tnextPage = getNextPageUrl( nextResponse );\n\t}\n\treturn mergedResults;\n};\n\nexport default fetchAllMiddleware;\n"],"mappings":";;;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAKA,IAAAC,CAAA,GAAAC,sBAAA,CAAAF,OAAA;AARA;AACA;AACA;;AAGA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMG,WAAW,GAAGA,CAAE;EAAEC,IAAI;EAAEC,GAAG;EAAE,GAAGC;AAAQ,CAAC,EAAEC,SAAS,MAAQ;EACjE,GAAGD,OAAO;EACVD,GAAG,EAAEA,GAAG,IAAI,IAAAG,iBAAY,EAAEH,GAAG,EAAEE,SAAU,CAAC;EAC1CH,IAAI,EAAEA,IAAI,IAAI,IAAAI,iBAAY,EAAEJ,IAAI,EAAEG,SAAU;AAC7C,CAAC,CAAE;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA,MAAME,aAAa,GAAKC,QAAQ,IAC/BA,QAAQ,CAACC,IAAI,GAAGD,QAAQ,CAACC,IAAI,CAAC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AQ,GAAG,MAAM,IAAAiB,SAAQ,EAAE;IAChC,GAAGxB,WAAW,CAAEG,OAAO,EAAE;MACxBsB,QAAQ,EAAE;IACX,CAAE,CAAC;IACH;IACAF,KAAK,EAAE;EACR,CAAE,CAAC;EAEH,MAAMG,OAAO,GAAG,MAAMpB,aAAa,CAAEC,QAAS,CAAC;EAE/C,IAAK,CAAEoB,KAAK,CAACC,OAAO,CAAEF,OAAQ,CAAC,EAAG;IACjC;IACA,OAAOA,OAAO;EACf;EAEA,IAAIG,QAAQ,GAAGd,cAAc,CAAER,QAAS,CAAC;EAEzC,IAAK,CAAEsB,QAAQ,EAAG;IACjB;IACA,OAAOH,OAAO;EACf;;EAEA;EACA,IAAII,aAAa,GAAG,oBAAuB,EAAE,CAAGC,MAAM,CAAEL,OAAQ,CAAC;EACjE,OAAQG,QAAQ,EAAG;IAClB,MAAMG,YAAY,GAAG,MAAM,IAAAR,SAAQ,EAAE;MACpC,GAAGrB,OAAO;MACV;MACAF,IAAI,EAAEgC,SAAS;MACf/B,GAAG,EAAE2B,QAAQ;MACb;MACAN,KAAK,EAAE;IACR,CAAE,CAAC;IACH,MAAMW,WAAW,GAAG,MAAM5B,aAAa,CAAE0B,YAAa,CAAC;IACvDF,aAAa,GAAGA,aAAa,CAACC,MAAM,CAAEG,WAAY,CAAC;IACnDL,QAAQ,GAAGd,cAAc,CAAEiB,YAAa,CAAC;EAC1C;EACA,OAAOF,aAAa;AACrB,CAAC;AAAC,IAAAK,QAAA,GAEab,kBAAkB;AAAAc,OAAA,CAAAC,OAAA,GAAAF,QAAA"}
@@ -4,13 +4,13 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
-
8
7
  /**
9
8
  * Set of HTTP methods which are eligible to be overridden.
10
9
  *
11
10
  * @type {Set<string>}
12
11
  */
13
12
  const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
13
+
14
14
  /**
15
15
  * Default request method.
16
16
  *
@@ -21,33 +21,31 @@ const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
21
21
  *
22
22
  * @type {string}
23
23
  */
24
-
25
24
  const DEFAULT_METHOD = 'GET';
25
+
26
26
  /**
27
27
  * API Fetch middleware which overrides the request method for HTTP v1
28
28
  * compatibility leveraging the REST API X-HTTP-Method-Override header.
29
29
  *
30
30
  * @type {import('../types').APIFetchMiddleware}
31
31
  */
32
-
33
32
  const httpV1Middleware = (options, next) => {
34
33
  const {
35
34
  method = DEFAULT_METHOD
36
35
  } = options;
37
-
38
36
  if (OVERRIDE_METHODS.has(method.toUpperCase())) {
39
- options = { ...options,
40
- headers: { ...options.headers,
37
+ options = {
38
+ ...options,
39
+ headers: {
40
+ ...options.headers,
41
41
  'X-HTTP-Method-Override': method,
42
42
  'Content-Type': 'application/json'
43
43
  },
44
44
  method: 'POST'
45
45
  };
46
46
  }
47
-
48
47
  return next(options);
49
48
  };
50
-
51
49
  var _default = httpV1Middleware;
52
50
  exports.default = _default;
53
51
  //# sourceMappingURL=http-v1.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/http-v1.js"],"names":["OVERRIDE_METHODS","Set","DEFAULT_METHOD","httpV1Middleware","options","next","method","has","toUpperCase","headers"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,MAAMA,gBAAgB,GAAG,IAAIC,GAAJ,CAAS,CAAE,OAAF,EAAW,KAAX,EAAkB,QAAlB,CAAT,CAAzB;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,MAAMC,cAAc,GAAG,KAAvB;AAEA;AACA;AACA;AACA;AACA;AACA;;AACA,MAAMC,gBAAgB,GAAG,CAAEC,OAAF,EAAWC,IAAX,KAAqB;AAC7C,QAAM;AAAEC,IAAAA,MAAM,GAAGJ;AAAX,MAA8BE,OAApC;;AACA,MAAKJ,gBAAgB,CAACO,GAAjB,CAAsBD,MAAM,CAACE,WAAP,EAAtB,CAAL,EAAoD;AACnDJ,IAAAA,OAAO,GAAG,EACT,GAAGA,OADM;AAETK,MAAAA,OAAO,EAAE,EACR,GAAGL,OAAO,CAACK,OADH;AAER,kCAA0BH,MAFlB;AAGR,wBAAgB;AAHR,OAFA;AAOTA,MAAAA,MAAM,EAAE;AAPC,KAAV;AASA;;AAED,SAAOD,IAAI,CAAED,OAAF,CAAX;AACA,CAfD;;eAiBeD,gB","sourcesContent":["/**\n * Set of HTTP methods which are eligible to be overridden.\n *\n * @type {Set<string>}\n */\nconst OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] );\n\n/**\n * Default request method.\n *\n * \"A request has an associated method (a method). Unless stated otherwise it\n * is `GET`.\"\n *\n * @see https://fetch.spec.whatwg.org/#requests\n *\n * @type {string}\n */\nconst DEFAULT_METHOD = 'GET';\n\n/**\n * API Fetch middleware which overrides the request method for HTTP v1\n * compatibility leveraging the REST API X-HTTP-Method-Override header.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst httpV1Middleware = ( options, next ) => {\n\tconst { method = DEFAULT_METHOD } = options;\n\tif ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) {\n\t\toptions = {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...options.headers,\n\t\t\t\t'X-HTTP-Method-Override': method,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t},\n\t\t\tmethod: 'POST',\n\t\t};\n\t}\n\n\treturn next( options );\n};\n\nexport default httpV1Middleware;\n"]}
1
+ {"version":3,"names":["OVERRIDE_METHODS","Set","DEFAULT_METHOD","httpV1Middleware","options","next","method","has","toUpperCase","headers","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/http-v1.js"],"sourcesContent":["/**\n * Set of HTTP methods which are eligible to be overridden.\n *\n * @type {Set<string>}\n */\nconst OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] );\n\n/**\n * Default request method.\n *\n * \"A request has an associated method (a method). Unless stated otherwise it\n * is `GET`.\"\n *\n * @see https://fetch.spec.whatwg.org/#requests\n *\n * @type {string}\n */\nconst DEFAULT_METHOD = 'GET';\n\n/**\n * API Fetch middleware which overrides the request method for HTTP v1\n * compatibility leveraging the REST API X-HTTP-Method-Override header.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst httpV1Middleware = ( options, next ) => {\n\tconst { method = DEFAULT_METHOD } = options;\n\tif ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) {\n\t\toptions = {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...options.headers,\n\t\t\t\t'X-HTTP-Method-Override': method,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t},\n\t\t\tmethod: 'POST',\n\t\t};\n\t}\n\n\treturn next( options );\n};\n\nexport default httpV1Middleware;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,MAAMA,gBAAgB,GAAG,IAAIC,GAAG,CAAE,CAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAG,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,cAAc,GAAG,KAAK;;AAE5B;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,gBAAgB,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC7C,MAAM;IAAEC,MAAM,GAAGJ;EAAe,CAAC,GAAGE,OAAO;EAC3C,IAAKJ,gBAAgB,CAACO,GAAG,CAAED,MAAM,CAACE,WAAW,CAAC,CAAE,CAAC,EAAG;IACnDJ,OAAO,GAAG;MACT,GAAGA,OAAO;MACVK,OAAO,EAAE;QACR,GAAGL,OAAO,CAACK,OAAO;QAClB,wBAAwB,EAAEH,MAAM;QAChC,cAAc,EAAE;MACjB,CAAC;MACDA,MAAM,EAAE;IACT,CAAC;EACF;EAEA,OAAOD,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAAC,IAAAM,QAAA,GAEaP,gBAAgB;AAAAQ,OAAA,CAAAC,OAAA,GAAAF,QAAA"}
@@ -4,11 +4,8 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
-
8
7
  var _i18n = require("@wordpress/i18n");
9
-
10
8
  var _response = require("../utils/response");
11
-
12
9
  /**
13
10
  * WordPress dependencies
14
11
  */
@@ -26,25 +23,23 @@ function isMediaUploadRequest(options) {
26
23
  const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
27
24
  return isMediaEndpoint && isCreateMethod;
28
25
  }
26
+
29
27
  /**
30
28
  * Middleware handling media upload failures and retries.
31
29
  *
32
30
  * @type {import('../types').APIFetchMiddleware}
33
31
  */
34
-
35
-
36
32
  const mediaUploadMiddleware = (options, next) => {
37
33
  if (!isMediaUploadRequest(options)) {
38
34
  return next(options);
39
35
  }
40
-
41
36
  let retries = 0;
42
37
  const maxRetries = 5;
38
+
43
39
  /**
44
40
  * @param {string} attachmentId
45
41
  * @return {Promise<any>} Processed post response.
46
42
  */
47
-
48
43
  const postProcess = attachmentId => {
49
44
  retries++;
50
45
  return next({
@@ -58,7 +53,6 @@ const mediaUploadMiddleware = (options, next) => {
58
53
  if (retries < maxRetries) {
59
54
  return postProcess(attachmentId);
60
55
  }
61
-
62
56
  next({
63
57
  path: `/wp/v2/media/${attachmentId}?force=true`,
64
58
  method: 'DELETE'
@@ -66,12 +60,11 @@ const mediaUploadMiddleware = (options, next) => {
66
60
  return Promise.reject();
67
61
  });
68
62
  };
69
-
70
- return next({ ...options,
63
+ return next({
64
+ ...options,
71
65
  parse: false
72
66
  }).catch(response => {
73
67
  const attachmentId = response.headers.get('x-wp-upload-attachment-id');
74
-
75
68
  if (response.status >= 500 && response.status < 600 && attachmentId) {
76
69
  return postProcess(attachmentId).catch(() => {
77
70
  if (options.parse !== false) {
@@ -80,15 +73,12 @@ const mediaUploadMiddleware = (options, next) => {
80
73
  message: (0, _i18n.__)('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
81
74
  });
82
75
  }
83
-
84
76
  return Promise.reject(response);
85
77
  });
86
78
  }
87
-
88
79
  return (0, _response.parseAndThrowError)(response, options.parse);
89
80
  }).then(response => (0, _response.parseResponseAndNormalizeError)(response, options.parse));
90
81
  };
91
-
92
82
  var _default = mediaUploadMiddleware;
93
83
  exports.default = _default;
94
84
  //# sourceMappingURL=media-upload.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/media-upload.js"],"names":["isMediaUploadRequest","options","isCreateMethod","method","isMediaEndpoint","path","indexOf","url","mediaUploadMiddleware","next","retries","maxRetries","postProcess","attachmentId","data","action","parse","catch","Promise","reject","response","headers","get","status","code","message","then"],"mappings":";;;;;;;AAGA;;AAKA;;AARA;AACA;AACA;;AAGA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA,SAASA,oBAAT,CAA+BC,OAA/B,EAAyC;AACxC,QAAMC,cAAc,GAAG,CAAC,CAAED,OAAO,CAACE,MAAX,IAAqBF,OAAO,CAACE,MAAR,KAAmB,MAA/D;AACA,QAAMC,eAAe,GAClB,CAAC,CAAEH,OAAO,CAACI,IAAX,IAAmBJ,OAAO,CAACI,IAAR,CAAaC,OAAb,CAAsB,cAAtB,MAA2C,CAAC,CAAjE,IACE,CAAC,CAAEL,OAAO,CAACM,GAAX,IAAkBN,OAAO,CAACM,GAAR,CAAYD,OAAZ,CAAqB,cAArB,MAA0C,CAAC,CAFhE;AAIA,SAAOF,eAAe,IAAIF,cAA1B;AACA;AAED;AACA;AACA;AACA;AACA;;;AACA,MAAMM,qBAAqB,GAAG,CAAEP,OAAF,EAAWQ,IAAX,KAAqB;AAClD,MAAK,CAAET,oBAAoB,CAAEC,OAAF,CAA3B,EAAyC;AACxC,WAAOQ,IAAI,CAAER,OAAF,CAAX;AACA;;AAED,MAAIS,OAAO,GAAG,CAAd;AACA,QAAMC,UAAU,GAAG,CAAnB;AAEA;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;;AACD,WAAO,kCAAoBA,QAApB,EAA8BnB,OAAO,CAACe,KAAtC,CAAP;AACA,GAxBK,EAyBLU,IAzBK,CAyBGN,QAAF,IACN,8CAAgCA,QAAhC,EAA0CnB,OAAO,CAACe,KAAlD,CA1BK,CAAP;AA4BA,CA5DD;;eA8DeR,qB","sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport {\n\tparseAndThrowError,\n\tparseResponseAndNormalizeError,\n} from '../utils/response';\n\n/**\n * @param {import('../types').APIFetchOptions} options\n * @return {boolean} True if the request is for media upload.\n */\nfunction isMediaUploadRequest( options ) {\n\tconst isCreateMethod = !! options.method && options.method === 'POST';\n\tconst isMediaEndpoint =\n\t\t( !! options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||\n\t\t( !! options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );\n\n\treturn isMediaEndpoint && isCreateMethod;\n}\n\n/**\n * Middleware handling media upload failures and retries.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst mediaUploadMiddleware = ( options, next ) => {\n\tif ( ! isMediaUploadRequest( options ) ) {\n\t\treturn next( options );\n\t}\n\n\tlet retries = 0;\n\tconst maxRetries = 5;\n\n\t/**\n\t * @param {string} attachmentId\n\t * @return {Promise<any>} Processed post response.\n\t */\n\tconst postProcess = ( attachmentId ) => {\n\t\tretries++;\n\t\treturn next( {\n\t\t\tpath: `/wp/v2/media/${ attachmentId }/post-process`,\n\t\t\tmethod: 'POST',\n\t\t\tdata: { action: 'create-image-subsizes' },\n\t\t\tparse: false,\n\t\t} ).catch( () => {\n\t\t\tif ( retries < maxRetries ) {\n\t\t\t\treturn postProcess( attachmentId );\n\t\t\t}\n\t\t\tnext( {\n\t\t\t\tpath: `/wp/v2/media/${ attachmentId }?force=true`,\n\t\t\t\tmethod: 'DELETE',\n\t\t\t} );\n\n\t\t\treturn Promise.reject();\n\t\t} );\n\t};\n\n\treturn next( { ...options, parse: false } )\n\t\t.catch( ( response ) => {\n\t\t\tconst attachmentId = response.headers.get(\n\t\t\t\t'x-wp-upload-attachment-id'\n\t\t\t);\n\t\t\tif (\n\t\t\t\tresponse.status >= 500 &&\n\t\t\t\tresponse.status < 600 &&\n\t\t\t\tattachmentId\n\t\t\t) {\n\t\t\t\treturn postProcess( attachmentId ).catch( () => {\n\t\t\t\t\tif ( options.parse !== false ) {\n\t\t\t\t\t\treturn Promise.reject( {\n\t\t\t\t\t\t\tcode: 'post_process',\n\t\t\t\t\t\t\tmessage: __(\n\t\t\t\t\t\t\t\t'Media upload failed. If this is a photo or a large image, please scale it down and try again.'\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Promise.reject( response );\n\t\t\t\t} );\n\t\t\t}\n\t\t\treturn parseAndThrowError( response, options.parse );\n\t\t} )\n\t\t.then( ( response ) =>\n\t\t\tparseResponseAndNormalizeError( response, options.parse )\n\t\t);\n};\n\nexport default mediaUploadMiddleware;\n"]}
1
+ {"version":3,"names":["_i18n","require","_response","isMediaUploadRequest","options","isCreateMethod","method","isMediaEndpoint","path","indexOf","url","mediaUploadMiddleware","next","retries","maxRetries","postProcess","attachmentId","data","action","parse","catch","Promise","reject","response","headers","get","status","code","message","__","parseAndThrowError","then","parseResponseAndNormalizeError","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/media-upload.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport {\n\tparseAndThrowError,\n\tparseResponseAndNormalizeError,\n} from '../utils/response';\n\n/**\n * @param {import('../types').APIFetchOptions} options\n * @return {boolean} True if the request is for media upload.\n */\nfunction isMediaUploadRequest( options ) {\n\tconst isCreateMethod = !! options.method && options.method === 'POST';\n\tconst isMediaEndpoint =\n\t\t( !! options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||\n\t\t( !! options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );\n\n\treturn isMediaEndpoint && isCreateMethod;\n}\n\n/**\n * Middleware handling media upload failures and retries.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst mediaUploadMiddleware = ( options, next ) => {\n\tif ( ! isMediaUploadRequest( options ) ) {\n\t\treturn next( options );\n\t}\n\n\tlet retries = 0;\n\tconst maxRetries = 5;\n\n\t/**\n\t * @param {string} attachmentId\n\t * @return {Promise<any>} Processed post response.\n\t */\n\tconst postProcess = ( attachmentId ) => {\n\t\tretries++;\n\t\treturn next( {\n\t\t\tpath: `/wp/v2/media/${ attachmentId }/post-process`,\n\t\t\tmethod: 'POST',\n\t\t\tdata: { action: 'create-image-subsizes' },\n\t\t\tparse: false,\n\t\t} ).catch( () => {\n\t\t\tif ( retries < maxRetries ) {\n\t\t\t\treturn postProcess( attachmentId );\n\t\t\t}\n\t\t\tnext( {\n\t\t\t\tpath: `/wp/v2/media/${ attachmentId }?force=true`,\n\t\t\t\tmethod: 'DELETE',\n\t\t\t} );\n\n\t\t\treturn Promise.reject();\n\t\t} );\n\t};\n\n\treturn next( { ...options, parse: false } )\n\t\t.catch( ( response ) => {\n\t\t\tconst attachmentId = response.headers.get(\n\t\t\t\t'x-wp-upload-attachment-id'\n\t\t\t);\n\t\t\tif (\n\t\t\t\tresponse.status >= 500 &&\n\t\t\t\tresponse.status < 600 &&\n\t\t\t\tattachmentId\n\t\t\t) {\n\t\t\t\treturn postProcess( attachmentId ).catch( () => {\n\t\t\t\t\tif ( options.parse !== false ) {\n\t\t\t\t\t\treturn Promise.reject( {\n\t\t\t\t\t\t\tcode: 'post_process',\n\t\t\t\t\t\t\tmessage: __(\n\t\t\t\t\t\t\t\t'Media upload failed. If this is a photo or a large image, please scale it down and try again.'\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Promise.reject( response );\n\t\t\t\t} );\n\t\t\t}\n\t\t\treturn parseAndThrowError( response, options.parse );\n\t\t} )\n\t\t.then( ( response ) =>\n\t\t\tparseResponseAndNormalizeError( response, options.parse )\n\t\t);\n};\n\nexport default mediaUploadMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,KAAA,GAAAC,OAAA;AAKA,IAAAC,SAAA,GAAAD,OAAA;AARA;AACA;AACA;;AAGA;AACA;AACA;;AAMA;AACA;AACA;AACA;AACA,SAASE,oBAAoBA,CAAEC,OAAO,EAAG;EACxC,MAAMC,cAAc,GAAG,CAAC,CAAED,OAAO,CAACE,MAAM,IAAIF,OAAO,CAACE,MAAM,KAAK,MAAM;EACrE,MAAMC,eAAe,GAClB,CAAC,CAAEH,OAAO,CAACI,IAAI,IAAIJ,OAAO,CAACI,IAAI,CAACC,OAAO,CAAE,cAAe,CAAC,KAAK,CAAC,CAAC,IAChE,CAAC,CAAEL,OAAO,CAACM,GAAG,IAAIN,OAAO,CAACM,GAAG,CAACD,OAAO,CAAE,cAAe,CAAC,KAAK,CAAC,CAAG;EAEnE,OAAOF,eAAe,IAAIF,cAAc;AACzC;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAMM,qBAAqB,GAAGA,CAAEP,OAAO,EAAEQ,IAAI,KAAM;EAClD,IAAK,CAAET,oBAAoB,CAAEC,OAAQ,CAAC,EAAG;IACxC,OAAOQ,IAAI,CAAER,OAAQ,CAAC;EACvB;EAEA,IAAIS,OAAO,GAAG,CAAC;EACf,MAAMC,UAAU,GAAG,CAAC;;EAEpB;AACD;AACA;AACA;EACC,MAAMC,WAAW,GAAKC,YAAY,IAAM;IACvCH,OAAO,EAAE;IACT,OAAOD,IAAI,CAAE;MACZJ,IAAI,EAAG,gBAAgBQ,YAAc,eAAc;MACnDV,MAAM,EAAE,MAAM;MACdW,IAAI,EAAE;QAAEC,MAAM,EAAE;MAAwB,CAAC;MACzCC,KAAK,EAAE;IACR,CAAE,CAAC,CAACC,KAAK,CAAE,MAAM;MAChB,IAAKP,OAAO,GAAGC,UAAU,EAAG;QAC3B,OAAOC,WAAW,CAAEC,YAAa,CAAC;MACnC;MACAJ,IAAI,CAAE;QACLJ,IAAI,EAAG,gBAAgBQ,YAAc,aAAY;QACjDV,MAAM,EAAE;MACT,CAAE,CAAC;MAEH,OAAOe,OAAO,CAACC,MAAM,CAAC,CAAC;IACxB,CAAE,CAAC;EACJ,CAAC;EAED,OAAOV,IAAI,CAAE;IAAE,GAAGR,OAAO;IAAEe,KAAK,EAAE;EAAM,CAAE,CAAC,CACzCC,KAAK,CAAIG,QAAQ,IAAM;IACvB,MAAMP,YAAY,GAAGO,QAAQ,CAACC,OAAO,CAACC,GAAG,CACxC,2BACD,CAAC;IACD,IACCF,QAAQ,CAACG,MAAM,IAAI,GAAG,IACtBH,QAAQ,CAACG,MAAM,GAAG,GAAG,IACrBV,YAAY,EACX;MACD,OAAOD,WAAW,CAAEC,YAAa,CAAC,CAACI,KAAK,CAAE,MAAM;QAC/C,IAAKhB,OAAO,CAACe,KAAK,KAAK,KAAK,EAAG;UAC9B,OAAOE,OAAO,CAACC,MAAM,CAAE;YACtBK,IAAI,EAAE,cAAc;YACpBC,OAAO,EAAE,IAAAC,QAAE,EACV,+FACD;UACD,CAAE,CAAC;QACJ;QAEA,OAAOR,OAAO,CAACC,MAAM,CAAEC,QAAS,CAAC;MAClC,CAAE,CAAC;IACJ;IACA,OAAO,IAAAO,4BAAkB,EAAEP,QAAQ,EAAEnB,OAAO,CAACe,KAAM,CAAC;EACrD,CAAE,CAAC,CACFY,IAAI,CAAIR,QAAQ,IAChB,IAAAS,wCAA8B,EAAET,QAAQ,EAAEnB,OAAO,CAACe,KAAM,CACzD,CAAC;AACH,CAAC;AAAC,IAAAc,QAAA,GAEatB,qBAAqB;AAAAuB,OAAA,CAAAC,OAAA,GAAAF,QAAA"}
@@ -4,32 +4,28 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
-
8
7
  /**
9
8
  * @type {import('../types').APIFetchMiddleware}
10
9
  */
11
10
  const namespaceAndEndpointMiddleware = (options, next) => {
12
11
  let path = options.path;
13
12
  let namespaceTrimmed, endpointTrimmed;
14
-
15
13
  if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
16
14
  namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
17
15
  endpointTrimmed = options.endpoint.replace(/^\//, '');
18
-
19
16
  if (endpointTrimmed) {
20
17
  path = namespaceTrimmed + '/' + endpointTrimmed;
21
18
  } else {
22
19
  path = namespaceTrimmed;
23
20
  }
24
21
  }
25
-
26
22
  delete options.namespace;
27
23
  delete options.endpoint;
28
- return next({ ...options,
24
+ return next({
25
+ ...options,
29
26
  path
30
27
  });
31
28
  };
32
-
33
29
  var _default = namespaceAndEndpointMiddleware;
34
30
  exports.default = _default;
35
31
  //# sourceMappingURL=namespace-endpoint.js.map