@wordpress/api-fetch 5.2.2-next.5df0cd52b7.0 → 5.2.5

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/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 5.2.5 (2021-11-07)
6
+
7
+ ### Internal
8
+
9
+ - Removed `getStablePath` function. Please use `normalizePath` from `@wordpress/url` package instead ([#35992](https://github.com/WordPress/gutenberg/pull/35992)).``
10
+
5
11
  ## 5.2.0 (2021-07-21)
6
12
 
7
13
  ### New feature
package/README.md CHANGED
@@ -10,7 +10,7 @@ Install the module
10
10
  npm install @wordpress/api-fetch --save
11
11
  ```
12
12
 
13
- _This package assumes that your code will run in an **ES2015+** environment. If you're using an environment that has limited or no support for ES2015+ such as IE browsers then using [core-js](https://github.com/zloirock/core-js) will add polyfills for these methods._
13
+ _This package assumes that your code will run in an **ES2015+** environment. If you're using an environment that has limited or no support for such language features and APIs, you should include [the polyfill shipped in `@wordpress/babel-preset-default`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/babel-preset-default#polyfill) in your code._
14
14
 
15
15
  ## Usage
16
16
 
@@ -56,28 +56,28 @@ Shorthand to be used in place of `body`, accepts an object value to be stringifi
56
56
 
57
57
  ### Aborting a request
58
58
 
59
- Aborting a request can be achieved through the use of [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) in the same way as you would when using the native `fetch` API.
59
+ Aborting a request can be achieved through the use of [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) in the same way as you would when using the native `fetch` API.
60
60
 
61
61
  For legacy browsers that don't support `AbortController`, you can either:
62
62
 
63
- * Provide your own polyfill of `AbortController` if you still want it to be abortable.
64
- * Ignore it as shown in the example below.
63
+ - Provide your own polyfill of `AbortController` if you still want it to be abortable.
64
+ - Ignore it as shown in the example below.
65
65
 
66
66
  **Example**
67
67
 
68
68
  ```js
69
- const controller = typeof AbortController === 'undefined'
70
- ? undefined
71
- : new AbortController();
69
+ const controller =
70
+ typeof AbortController === 'undefined' ? undefined : new AbortController();
72
71
 
73
- apiFetch( { path: '/wp/v2/posts', signal: controller?.signal } )
74
- .catch( ( error ) => {
72
+ apiFetch( { path: '/wp/v2/posts', signal: controller?.signal } ).catch(
73
+ ( error ) => {
75
74
  // If the browser doesn't support AbortController then the code below will never log.
76
75
  // However, in most cases this should be fine as it can be considered to be a progressive enhancement.
77
76
  if ( error.name === 'AbortError' ) {
78
77
  console.log( 'Request has been aborted' );
79
78
  }
80
- } );
79
+ }
80
+ );
81
81
 
82
82
  controller?.abort();
83
83
  ```
@@ -17,15 +17,24 @@ var _response = require("../utils/response");
17
17
  * Internal dependencies
18
18
  */
19
19
 
20
+ /**
21
+ * @param {import('../types').APIFetchOptions} options
22
+ * @return {boolean} True if the request is for media upload.
23
+ */
24
+ function isMediaUploadRequest(options) {
25
+ const isCreateMethod = !!options.method && options.method === 'POST';
26
+ const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
27
+ return isMediaEndpoint && isCreateMethod;
28
+ }
20
29
  /**
21
30
  * Middleware handling media upload failures and retries.
22
31
  *
23
32
  * @type {import('../types').APIFetchMiddleware}
24
33
  */
25
- const mediaUploadMiddleware = (options, next) => {
26
- const isMediaUploadRequest = options.path && options.path.indexOf('/wp/v2/media') !== -1 || options.url && options.url.indexOf('/wp/v2/media') !== -1;
27
34
 
28
- if (!isMediaUploadRequest) {
35
+
36
+ const mediaUploadMiddleware = (options, next) => {
37
+ if (!isMediaUploadRequest(options)) {
29
38
  return next(options);
30
39
  }
31
40
 
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/media-upload.js"],"names":["mediaUploadMiddleware","options","next","isMediaUploadRequest","path","indexOf","url","retries","maxRetries","postProcess","attachmentId","method","data","action","parse","catch","Promise","reject","response","headers","get","status","code","message","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AMR,YAAY,GAAGQ,QAAQ,CAACC,OAAT,CAAiBC,GAAjB,CACpB,2BADoB,CAArB;;AAGA,QACCF,QAAQ,CAACG,MAAT,IAAmB,GAAnB,IACAH,QAAQ,CAACG,MAAT,GAAkB,GADlB,IAEAX,YAHD,EAIE;AACD,aAAOD,WAAW,CAAEC,YAAF,CAAX,CAA4BK,KAA5B,CAAmC,MAAM;AAC/C,YAAKd,OAAO,CAACa,KAAR,KAAkB,KAAvB,EAA+B;AAC9B,iBAAOE,OAAO,CAACC,MAAR,CAAgB;AACtBK,YAAAA,IAAI,EAAE,cADgB;AAEtBC,YAAAA,OAAO,EAAE,cACR,+FADQ;AAFa,WAAhB,CAAP;AAMA;;AAED,eAAOP,OAAO,CAACC,MAAR,CAAgBC,QAAhB,CAAP;AACA,OAXM,CAAP;AAYA;;AACD,WAAO,kCAAoBA,QAApB,EAA8BjB,OAAO,CAACa,KAAtC,CAAP;AACA,GAxBK,EAyBLU,IAzBK,CAyBGN,QAAF,IACN,8CAAgCA,QAAhC,EAA0CjB,OAAO,CAACa,KAAlD,CA1BK,CAAP;AA4BA,CA/DD;;eAiEed,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 * Middleware handling media upload failures and retries.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst mediaUploadMiddleware = ( options, next ) => {\n\tconst isMediaUploadRequest =\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\tif ( ! isMediaUploadRequest ) {\n\t\treturn next( options );\n\t}\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,"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;;A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KA,aAAOe,OAAO,CAACC,MAAR,EAAP;AACA,KAfM,CAAP;AAgBA,GAlBD;;AAoBA,SAAOV,IAAI,CAAE,EAAE,GAAGR,OAAL;AAAce,IAAAA,KAAK,EAAE;AAArB,GAAF,CAAJ,CACLC,KADK,CACIG,QAAF,IAAgB;AACvB,UAAMP,YAAY,GAAGO,QAAQ,CAACC,OAAT,CAAiBC,GAAjB,CACpB,2BADoB,CAArB;;AAGA,QACCF,QAAQ,CAACG,MAAT,IAAmB,GAAnB,IACAH,QAAQ,CAACG,MAAT,GAAkB,GADlB,IAEAV,YAHD,EAIE;AACD,aAAOD,WAAW,CAAEC,YAAF,CAAX,CAA4BI,KAA5B,CAAmC,MAAM;AAC/C,YAAKhB,OAAO,CAACe,KAAR,KAAkB,KAAvB,EAA+B;AAC9B,iBAAOE,OAAO,CAACC,MAAR,CAAgB;AACtBK,YAAAA,IAAI,EAAE,cADgB;AAEtBC,YAAAA,OAAO,EAAE,cACR,+FADQ;AAFa,WAAhB,CAAP;AAMA;;AAED,eAAOP,OAAO,CAACC,MAAR,CAAgBC,QAAhB,CAAP;AACA,OAXM,CAAP;AAYA;;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"]}
@@ -3,44 +3,21 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.getStablePath = getStablePath;
7
6
  exports.default = void 0;
8
7
 
8
+ var _url = require("@wordpress/url");
9
+
9
10
  /**
10
- * Given a path, returns a normalized path where equal query parameter values
11
- * will be treated as identical, regardless of order they appear in the original
12
- * text.
13
- *
14
- * @param {string} path Original path.
15
- *
16
- * @return {string} Normalized path.
11
+ * WordPress dependencies
17
12
  */
18
- function getStablePath(path) {
19
- const splitted = path.split('?');
20
- const query = splitted[1];
21
- const base = splitted[0];
22
-
23
- if (!query) {
24
- return base;
25
- } // 'b=1&c=2&a=5'
26
-
27
13
 
28
- return base + '?' + query // [ 'b=1', 'c=2', 'a=5' ]
29
- .split('&') // [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ]
30
- .map(entry => entry.split('=')) // [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ]
31
- .sort((a, b) => a[0].localeCompare(b[0])) // [ 'a=5', 'b=1', 'c=2' ]
32
- .map(pair => pair.join('=')) // 'a=5&b=1&c=2'
33
- .join('&');
34
- }
35
14
  /**
36
15
  * @param {Record<string, any>} preloadedData
37
16
  * @return {import('../types').APIFetchMiddleware} Preloading middleware.
38
17
  */
39
-
40
-
41
18
  function createPreloadingMiddleware(preloadedData) {
42
19
  const cache = Object.keys(preloadedData).reduce((result, path) => {
43
- result[getStablePath(path)] = preloadedData[path];
20
+ result[(0, _url.normalizePath)(path)] = preloadedData[path];
44
21
  return result;
45
22
  },
46
23
  /** @type {Record<string, any>} */
@@ -49,13 +26,24 @@ function createPreloadingMiddleware(preloadedData) {
49
26
  const {
50
27
  parse = true
51
28
  } = options;
29
+ /** @type {string | void} */
52
30
 
53
- if (typeof options.path === 'string') {
31
+ let rawPath = options.path;
32
+
33
+ if (!rawPath && options.url) {
34
+ const pathFromQuery = (0, _url.getQueryArg)(options.url, 'rest_route');
35
+
36
+ if (typeof pathFromQuery === 'string') {
37
+ rawPath = pathFromQuery;
38
+ }
39
+ }
40
+
41
+ if (typeof rawPath === 'string') {
54
42
  const method = options.method || 'GET';
55
- const path = getStablePath(options.path);
43
+ const path = (0, _url.normalizePath)(rawPath);
56
44
 
57
45
  if ('GET' === method && cache[path]) {
58
- const cacheData = cache[path]; // Unsetting the cache key ensures that the data is only preloaded a single time
46
+ const cacheData = cache[path]; // Unsetting the cache key ensures that the data is only used a single time
59
47
 
60
48
  delete cache[path];
61
49
  return Promise.resolve(parse ? cacheData.body : new window.Response(JSON.stringify(cacheData.body), {
@@ -64,7 +52,10 @@ function createPreloadingMiddleware(preloadedData) {
64
52
  headers: cacheData.headers
65
53
  }));
66
54
  } else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
67
- return Promise.resolve(parse ? cache[method][path].body : cache[method][path]);
55
+ const cacheData = cache[method][path]; // Unsetting the cache key ensures that the data is only used a single time
56
+
57
+ delete cache[method][path];
58
+ return Promise.resolve(parse ? cacheData.body : cacheData);
68
59
  }
69
60
  }
70
61
 
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/preloading.js"],"names":["getStablePath","path","splitted","split","query","base","map","entry","sort","a","b","localeCompare","pair","join","createPreloadingMiddleware","preloadedData","cache","Object","keys","reduce","result","options","next","parse","method","cacheData","Promise","resolve","body","window","Response","JSON","stringify","status","statusText","headers"],"mappings":";;;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASA,aAAT,CAAwBC,IAAxB,EAA+B;AACrC,QAAMC,QAAQ,GAAGD,IAAI,CAACE,KAAL,CAAY,GAAZ,CAAjB;AACA,QAAMC,KAAK,GAAGF,QAAQ,CAAE,CAAF,CAAtB;AACA,QAAMG,IAAI,GAAGH,QAAQ,CA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AGT,KAAK,CAAEf,IAAF,CAAvB,CADwC,CAGxC;;AACA,eAAOe,KAAK,CAAEf,IAAF,CAAZ;AAEA,eAAOyB,OAAO,CAACC,OAAR,CACNJ,KAAK,GACFE,SAAS,CAACG,IADR,GAEF,IAAIC,MAAM,CAACC,QAAX,CACAC,IAAI,CAACC,SAAL,CAAgBP,SAAS,CAACG,IAA1B,CADA,EAEA;AACCK,UAAAA,MAAM,EAAE,GADT;AAECC,UAAAA,UAAU,EAAE,IAFb;AAGCC,UAAAA,OAAO,EAAEV,SAAS,CAACU;AAHpB,SAFA,CAHG,CAAP;AAYA,OAlBD,MAkBO,IACN,cAAcX,MAAd,IACAR,KAAK,CAAEQ,MAAF,CADL,IAEAR,KAAK,CAAEQ,MAAF,CAAL,CAAiBvB,IAAjB,CAHM,EAIL;AACD,eAAOyB,OAAO,CAACC,OAAR,CACNJ,KAAK,GACFP,KAAK,CAAEQ,MAAF,CAAL,CAAiBvB,IAAjB,EAAwB2B,IADtB,GAEFZ,KAAK,CAAEQ,MAAF,CAAL,CAAiBvB,IAAjB,CAHG,CAAP;AAKA;AACD;;AAED,WAAOqB,IAAI,CAAED,OAAF,CAAX;AACA,GAtCD;AAuCA;;eAEcP,0B","sourcesContent":["/**\n * Given a path, returns a normalized path where equal query parameter values\n * will be treated as identical, regardless of order they appear in the original\n * text.\n *\n * @param {string} path Original path.\n *\n * @return {string} Normalized path.\n */\nexport function getStablePath( path ) {\n\tconst splitted = path.split( '?' );\n\tconst query = splitted[ 1 ];\n\tconst base = splitted[ 0 ];\n\tif ( ! query ) {\n\t\treturn base;\n\t}\n\n\t// 'b=1&c=2&a=5'\n\treturn (\n\t\tbase +\n\t\t'?' +\n\t\tquery\n\t\t\t// [ 'b=1', 'c=2', 'a=5' ]\n\t\t\t.split( '&' )\n\t\t\t// [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ]\n\t\t\t.map( ( entry ) => entry.split( '=' ) )\n\t\t\t// [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ]\n\t\t\t.sort( ( a, b ) => a[ 0 ].localeCompare( b[ 0 ] ) )\n\t\t\t// [ 'a=5', 'b=1', 'c=2' ]\n\t\t\t.map( ( pair ) => pair.join( '=' ) )\n\t\t\t// 'a=5&b=1&c=2'\n\t\t\t.join( '&' )\n\t);\n}\n\n/**\n * @param {Record<string, any>} preloadedData\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nfunction createPreloadingMiddleware( preloadedData ) {\n\tconst cache = Object.keys( preloadedData ).reduce( ( result, path ) => {\n\t\tresult[ getStablePath( path ) ] = preloadedData[ path ];\n\t\treturn result;\n\t}, /** @type {Record<string, any>} */ ( {} ) );\n\n\treturn ( options, next ) => {\n\t\tconst { parse = true } = options;\n\t\tif ( typeof options.path === 'string' ) {\n\t\t\tconst method = options.method || 'GET';\n\t\t\tconst path = getStablePath( options.path );\n\n\t\t\tif ( 'GET' === method && cache[ path ] ) {\n\t\t\t\tconst cacheData = cache[ path ];\n\n\t\t\t\t// Unsetting the cache key ensures that the data is only preloaded a single time\n\t\t\t\tdelete cache[ path ];\n\n\t\t\t\treturn Promise.resolve(\n\t\t\t\t\tparse\n\t\t\t\t\t\t? cacheData.body\n\t\t\t\t\t\t: new window.Response(\n\t\t\t\t\t\t\t\tJSON.stringify( cacheData.body ),\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\t\t\tstatusText: 'OK',\n\t\t\t\t\t\t\t\t\theaders: cacheData.headers,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t )\n\t\t\t\t);\n\t\t\t} else if (\n\t\t\t\t'OPTIONS' === method &&\n\t\t\t\tcache[ method ] &&\n\t\t\t\tcache[ method ][ path ]\n\t\t\t) {\n\t\t\t\treturn Promise.resolve(\n\t\t\t\t\tparse\n\t\t\t\t\t\t? cache[ method ][ path ].body\n\t\t\t\t\t\t: cache[ method ][ path ]\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn next( options );\n\t};\n}\n\nexport default createPreloadingMiddleware;\n"]}
1
+ {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/preloading.js"],"names":["createPreloadingMiddleware","preloadedData","cache","Object","keys","reduce","result","path","options","next","parse","rawPath","url","pathFromQuery","method","cacheData","Promise","resolve","body","window","Response","JSON","stringify","status","statusText","headers"],"mappings":";;;;;;;AAGA;;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA,SAASA,0BAAT,CAAqCC,aAArC,EAAqD;AACpD,QAAMC,KAAK,GAAGC,MAAM,CAACC,IAAP,CAAaH,aAAb,EAA6BI,MAA7B,CAAqC,CAAEC,MAAF,EAAUC,IAAV,KAAoB;AACtED,IAAAA,MAAM,CAAE,wBAAeC,IAAf,CAAF,CAAN,GAAkCN,aAAa,CAAEM,IAAF,CAA/C;AACA,WAAOD,MAAP;AACA,GAHa;AAGX;AAAqC,IAH1B,CAAd;AAKA,SAAO,CAAEE,OAAF,EAAWC,IAAX,KAAqB;AAC3B,UAAM;AAAEC,MAAAA,KAAK,GAAG;AAAV,QAAmBF,OAAzB;AACA;;AACA,QAAIG,OAAO,GAAGH,OAAO,CAACD,IAAtB;;AACA,QAAK,CAAEI,OAAF,IAAaH,OAAO,CAACI,GAA1B,EAAgC;AAC/B,YAAMC,aAAa,GAAG,sBAAaL,OAAO,CAACI,GAArB,EAA0B,YAA1B,CAAtB;;AACA,UAAK,OAAOC,aAAP,KAAyB,QAA9B,EAAyC;AACxCF,QAAAA,OAAO,GAAGE,aAAV;AACA;AACD;;AACD,QAAK,OAAOF,OAAP,KAAmB,QAAxB,EAAmC;AAClC,YAAMG,MAAM,GAAGN,OAAO,CAACM,MAAR,IAAkB,KAAjC;AACA,YAAMP,IAAI,GAAG,wBAAeI,OAAf,CAAb;;AAEA,UAAK,UAAUG,MAAV,IAAoBZ,KAAK,CAAEK,IAAF,CAA9B,EAAyC;AACxC,cAAMQ,SAAS,GAAGb,KAAK,CAAEK,IAAF,CAAvB,CADwC,CAGxC;;AACA,eAAOL,KAAK,CAAEK,IAAF,CAAZ;AAEA,eAAOS,OAAO,CAACC,OAAR,CACNP,KAAK,GACFK,SAAS,CAACG,IADR,GAEF,IAAIC,MAAM,CAACC,QAAX,CACAC,IAAI,CAACC,SAAL,CAAgBP,SAAS,CAACG,IAA1B,CADA,EAEA;AACCK,UAAAA,MAAM,EAAE,GADT;AAECC,UAAAA,UAAU,EAAE,IAFb;AAGCC,UAAAA,OAAO,EAAEV,SAAS,CAACU;AAHpB,SAFA,CAHG,CAAP;AAYA,OAlBD,MAkBO,IACN,cAAcX,MAAd,IACAZ,KAAK,CAAEY,MAAF,CADL,IAEAZ,KAAK,CAAEY,MAAF,CAAL,CAAiBP,IAAjB,CAHM,EAIL;AACD,cAAMQ,SAAS,GAAGb,KAAK,CAAEY,MAAF,CAAL,CAAiBP,IAAjB,CAAlB,CADC,CAGD;;AACA,eAAOL,KAAK,CAAEY,MAAF,CAAL,CAAiBP,IAAjB,CAAP;AAEA,eAAOS,OAAO,CAACC,OAAR,CAAiBP,KAAK,GAAGK,SAAS,CAACG,IAAb,GAAoBH,SAA1C,CAAP;AACA;AACD;;AAED,WAAON,IAAI,CAAED,OAAF,CAAX;AACA,GA/CD;AAgDA;;eAEcR,0B","sourcesContent":["/**\n * WordPress dependencies\n */\nimport { getQueryArg, normalizePath } from '@wordpress/url';\n\n/**\n * @param {Record<string, any>} preloadedData\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nfunction createPreloadingMiddleware( preloadedData ) {\n\tconst cache = Object.keys( preloadedData ).reduce( ( result, path ) => {\n\t\tresult[ normalizePath( path ) ] = preloadedData[ path ];\n\t\treturn result;\n\t}, /** @type {Record<string, any>} */ ( {} ) );\n\n\treturn ( options, next ) => {\n\t\tconst { parse = true } = options;\n\t\t/** @type {string | void} */\n\t\tlet rawPath = options.path;\n\t\tif ( ! rawPath && options.url ) {\n\t\t\tconst pathFromQuery = getQueryArg( options.url, 'rest_route' );\n\t\t\tif ( typeof pathFromQuery === 'string' ) {\n\t\t\t\trawPath = pathFromQuery;\n\t\t\t}\n\t\t}\n\t\tif ( typeof rawPath === 'string' ) {\n\t\t\tconst method = options.method || 'GET';\n\t\t\tconst path = normalizePath( rawPath );\n\n\t\t\tif ( 'GET' === method && cache[ path ] ) {\n\t\t\t\tconst cacheData = cache[ path ];\n\n\t\t\t\t// Unsetting the cache key ensures that the data is only used a single time\n\t\t\t\tdelete cache[ path ];\n\n\t\t\t\treturn Promise.resolve(\n\t\t\t\t\tparse\n\t\t\t\t\t\t? cacheData.body\n\t\t\t\t\t\t: new window.Response(\n\t\t\t\t\t\t\t\tJSON.stringify( cacheData.body ),\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\t\t\tstatusText: 'OK',\n\t\t\t\t\t\t\t\t\theaders: cacheData.headers,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t )\n\t\t\t\t);\n\t\t\t} else if (\n\t\t\t\t'OPTIONS' === method &&\n\t\t\t\tcache[ method ] &&\n\t\t\t\tcache[ method ][ path ]\n\t\t\t) {\n\t\t\t\tconst cacheData = cache[ method ][ path ];\n\n\t\t\t\t// Unsetting the cache key ensures that the data is only used a single time\n\t\t\t\tdelete cache[ method ][ path ];\n\n\t\t\t\treturn Promise.resolve( parse ? cacheData.body : cacheData );\n\t\t\t}\n\t\t}\n\n\t\treturn next( options );\n\t};\n}\n\nexport default createPreloadingMiddleware;\n"]}
@@ -7,16 +7,25 @@ import { __ } from '@wordpress/i18n';
7
7
  */
8
8
 
9
9
  import { parseAndThrowError, parseResponseAndNormalizeError } from '../utils/response';
10
+ /**
11
+ * @param {import('../types').APIFetchOptions} options
12
+ * @return {boolean} True if the request is for media upload.
13
+ */
14
+
15
+ function isMediaUploadRequest(options) {
16
+ const isCreateMethod = !!options.method && options.method === 'POST';
17
+ const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
18
+ return isMediaEndpoint && isCreateMethod;
19
+ }
10
20
  /**
11
21
  * Middleware handling media upload failures and retries.
12
22
  *
13
23
  * @type {import('../types').APIFetchMiddleware}
14
24
  */
15
25
 
16
- const mediaUploadMiddleware = (options, next) => {
17
- const isMediaUploadRequest = options.path && options.path.indexOf('/wp/v2/media') !== -1 || options.url && options.url.indexOf('/wp/v2/media') !== -1;
18
26
 
19
- if (!isMediaUploadRequest) {
27
+ const mediaUploadMiddleware = (options, next) => {
28
+ if (!isMediaUploadRequest(options)) {
20
29
  return next(options);
21
30
  }
22
31
 
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/media-upload.js"],"names":["__","parseAndThrowError","parseResponseAndNormalizeError","mediaUploadMiddleware","options","next","isMediaUploadRequest","path","indexOf","url","retries","maxRetries","postProcess","attachmentId","method","data","action","parse","catch","Promise","reject","response","headers","get","status","code","message","then"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,EAAT,QAAmB,iBAAnB;AAEA;AACA;AACA;;AACA,SACCC,kBADD,EAECC,8BAFD,QAGO,mBAHP;AAKA;AACA;AACA;AACA;AACA;;AACA,MAAMC,qBAAqB,GAAG,CAAEC,OAAF,EAAWC,IAAX,KAAqB;AAClD,QAAMC,oBAAoB,GACvBF,OAAO,CAACG,IAAR,IAAgBH,OAAO,CAACG,IAAR,CAAaC,OAAb,CAAsB,cAAtB,MAA2C,CAAC,CAA9D,IACEJ,OAAO,CAACK,GAAR,IAAeL,OAAO,CAACK,GAAR,CAAYD,OAAZ,CAAqB,cAArB,MAA0C,CAAC,CAF7D;;AAIA,MAAK,CAAEF,oBAAP,EAA8B;AAC7B,WAAOD,IAAI,CAAED,OAAF,CAAX;AACA;;AACD,MAAIM,OAAO,GAAG,CAAd;AACA,QAAMC,UAAU,GAAG,CAAnB;AAEA;AACD;AACA;AACA;;AACC,QAAMC,WAAW,GAAKC,YAAF,I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,OAAO,CAACa,KAApB,CAAzB;AACA,GAxBK,EAyBLU,IAzBK,CAyBGN,QAAF,IACNnB,8BAA8B,CAAEmB,QAAF,EAAYjB,OAAO,CAACa,KAApB,CA1BzB,CAAP;AA4BA,CA/DD;;AAiEA,eAAed,qBAAf","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 * Middleware handling media upload failures and retries.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst mediaUploadMiddleware = ( options, next ) => {\n\tconst isMediaUploadRequest =\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\tif ( ! isMediaUploadRequest ) {\n\t\treturn next( options );\n\t}\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,"sources":["@wordpress/api-fetch/src/middlewares/media-upload.js"],"names":["__","parseAndThrowError","parseResponseAndNormalizeError","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":"AAAA;AACA;AACA;AACA,SAASA,EAAT,QAAmB,iBAAnB;AAEA;AACA;AACA;;AACA,SACCC,kBADD,EAECC,8BAFD,QAGO,mBAHP;AAKA;AACA;AACA;AACA;;AACA,SAASC,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,cAA1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YAAKhB,OAAO,CAACe,KAAR,KAAkB,KAAvB,EAA+B;AAC9B,iBAAOE,OAAO,CAACC,MAAR,CAAgB;AACtBK,YAAAA,IAAI,EAAE,cADgB;AAEtBC,YAAAA,OAAO,EAAE5B,EAAE,CACV,+FADU;AAFW,WAAhB,CAAP;AAMA;;AAED,eAAOqB,OAAO,CAACC,MAAR,CAAgBC,QAAhB,CAAP;AACA,OAXM,CAAP;AAYA;;AACD,WAAOtB,kBAAkB,CAAEsB,QAAF,EAAYnB,OAAO,CAACe,KAApB,CAAzB;AACA,GAxBK,EAyBLU,IAzBK,CAyBGN,QAAF,IACNrB,8BAA8B,CAAEqB,QAAF,EAAYnB,OAAO,CAACe,KAApB,CA1BzB,CAAP;AA4BA,CA5DD;;AA8DA,eAAeR,qBAAf","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,29 +1,7 @@
1
1
  /**
2
- * Given a path, returns a normalized path where equal query parameter values
3
- * will be treated as identical, regardless of order they appear in the original
4
- * text.
5
- *
6
- * @param {string} path Original path.
7
- *
8
- * @return {string} Normalized path.
2
+ * WordPress dependencies
9
3
  */
10
- export function getStablePath(path) {
11
- const splitted = path.split('?');
12
- const query = splitted[1];
13
- const base = splitted[0];
14
-
15
- if (!query) {
16
- return base;
17
- } // 'b=1&c=2&a=5'
18
-
19
-
20
- return base + '?' + query // [ 'b=1', 'c=2', 'a=5' ]
21
- .split('&') // [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ]
22
- .map(entry => entry.split('=')) // [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ]
23
- .sort((a, b) => a[0].localeCompare(b[0])) // [ 'a=5', 'b=1', 'c=2' ]
24
- .map(pair => pair.join('=')) // 'a=5&b=1&c=2'
25
- .join('&');
26
- }
4
+ import { getQueryArg, normalizePath } from '@wordpress/url';
27
5
  /**
28
6
  * @param {Record<string, any>} preloadedData
29
7
  * @return {import('../types').APIFetchMiddleware} Preloading middleware.
@@ -31,7 +9,7 @@ export function getStablePath(path) {
31
9
 
32
10
  function createPreloadingMiddleware(preloadedData) {
33
11
  const cache = Object.keys(preloadedData).reduce((result, path) => {
34
- result[getStablePath(path)] = preloadedData[path];
12
+ result[normalizePath(path)] = preloadedData[path];
35
13
  return result;
36
14
  },
37
15
  /** @type {Record<string, any>} */
@@ -40,13 +18,24 @@ function createPreloadingMiddleware(preloadedData) {
40
18
  const {
41
19
  parse = true
42
20
  } = options;
21
+ /** @type {string | void} */
22
+
23
+ let rawPath = options.path;
43
24
 
44
- if (typeof options.path === 'string') {
25
+ if (!rawPath && options.url) {
26
+ const pathFromQuery = getQueryArg(options.url, 'rest_route');
27
+
28
+ if (typeof pathFromQuery === 'string') {
29
+ rawPath = pathFromQuery;
30
+ }
31
+ }
32
+
33
+ if (typeof rawPath === 'string') {
45
34
  const method = options.method || 'GET';
46
- const path = getStablePath(options.path);
35
+ const path = normalizePath(rawPath);
47
36
 
48
37
  if ('GET' === method && cache[path]) {
49
- const cacheData = cache[path]; // Unsetting the cache key ensures that the data is only preloaded a single time
38
+ const cacheData = cache[path]; // Unsetting the cache key ensures that the data is only used a single time
50
39
 
51
40
  delete cache[path];
52
41
  return Promise.resolve(parse ? cacheData.body : new window.Response(JSON.stringify(cacheData.body), {
@@ -55,7 +44,10 @@ function createPreloadingMiddleware(preloadedData) {
55
44
  headers: cacheData.headers
56
45
  }));
57
46
  } else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
58
- return Promise.resolve(parse ? cache[method][path].body : cache[method][path]);
47
+ const cacheData = cache[method][path]; // Unsetting the cache key ensures that the data is only used a single time
48
+
49
+ delete cache[method][path];
50
+ return Promise.resolve(parse ? cacheData.body : cacheData);
59
51
  }
60
52
  }
61
53
 
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/preloading.js"],"names":["getStablePath","path","splitted","split","query","base","map","entry","sort","a","b","localeCompare","pair","join","createPreloadingMiddleware","preloadedData","cache","Object","keys","reduce","result","options","next","parse","method","cacheData","Promise","resolve","body","window","Response","JSON","stringify","status","statusText","headers"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASA,aAAT,CAAwBC,IAAxB,EAA+B;AACrC,QAAMC,QAAQ,GAAGD,IAAI,CAACE,KAAL,CAAY,GAAZ,CAAjB;AACA,QAAMC,KAAK,GAAGF,QAAQ,CAAE,CAAF,CAAtB;AACA,QAAMG,IAAI,GAAGH,QAAQ,CAAE,CAAF,CAArB;;AACA,MAAK,CAAEE,KAAP,EAAe;AACd,WAAOC,IAAP;AACA,GANoC,CAQrC;;;AACA,SACCA,IAAI,GACJ,GADA,GAEAD,KAAK,CACJ;AADI,GAEHD,KAFF,CAES,GAFT,EAGC;AAHD,GAIEG,GAJF,CAISC,KAAF,IAAaA,KAAK,CAACJ,KAAN,CAAa,GAAb,CAJpB,EAKC;AALD,GAMEK,IANF,CAMQ,CAAEC,CAAF,EAAKC,CAAL,KAAYD,CAAC,CAAE,CAAF,CAAD,CAAOE,aAAP,CAAsBD,CAAC,CAAE,CAAF,CAAvB,CANpB,EAOC;AAPD,GAQEJ,GARF,CAQSM,IAAF,IAAYA,IAAI,CAACC,IAAL,CAAW,GAAX,CARnB,EASC;AATD,GAUEA,IAVF,CAUQ,GAVR,CAHD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,eAAOyB,OAAO,CAACC,OAAR,CACNJ,KAAK,GACFP,KAAK,CAAEQ,MAAF,CAAL,CAAiBvB,IAAjB,EAAwB2B,IADtB,GAEFZ,KAAK,CAAEQ,MAAF,CAAL,CAAiBvB,IAAjB,CAHG,CAAP;AAKA;AACD;;AAED,WAAOqB,IAAI,CAAED,OAAF,CAAX;AACA,GAtCD;AAuCA;;AAED,eAAeP,0BAAf","sourcesContent":["/**\n * Given a path, returns a normalized path where equal query parameter values\n * will be treated as identical, regardless of order they appear in the original\n * text.\n *\n * @param {string} path Original path.\n *\n * @return {string} Normalized path.\n */\nexport function getStablePath( path ) {\n\tconst splitted = path.split( '?' );\n\tconst query = splitted[ 1 ];\n\tconst base = splitted[ 0 ];\n\tif ( ! query ) {\n\t\treturn base;\n\t}\n\n\t// 'b=1&c=2&a=5'\n\treturn (\n\t\tbase +\n\t\t'?' +\n\t\tquery\n\t\t\t// [ 'b=1', 'c=2', 'a=5' ]\n\t\t\t.split( '&' )\n\t\t\t// [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ]\n\t\t\t.map( ( entry ) => entry.split( '=' ) )\n\t\t\t// [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ]\n\t\t\t.sort( ( a, b ) => a[ 0 ].localeCompare( b[ 0 ] ) )\n\t\t\t// [ 'a=5', 'b=1', 'c=2' ]\n\t\t\t.map( ( pair ) => pair.join( '=' ) )\n\t\t\t// 'a=5&b=1&c=2'\n\t\t\t.join( '&' )\n\t);\n}\n\n/**\n * @param {Record<string, any>} preloadedData\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nfunction createPreloadingMiddleware( preloadedData ) {\n\tconst cache = Object.keys( preloadedData ).reduce( ( result, path ) => {\n\t\tresult[ getStablePath( path ) ] = preloadedData[ path ];\n\t\treturn result;\n\t}, /** @type {Record<string, any>} */ ( {} ) );\n\n\treturn ( options, next ) => {\n\t\tconst { parse = true } = options;\n\t\tif ( typeof options.path === 'string' ) {\n\t\t\tconst method = options.method || 'GET';\n\t\t\tconst path = getStablePath( options.path );\n\n\t\t\tif ( 'GET' === method && cache[ path ] ) {\n\t\t\t\tconst cacheData = cache[ path ];\n\n\t\t\t\t// Unsetting the cache key ensures that the data is only preloaded a single time\n\t\t\t\tdelete cache[ path ];\n\n\t\t\t\treturn Promise.resolve(\n\t\t\t\t\tparse\n\t\t\t\t\t\t? cacheData.body\n\t\t\t\t\t\t: new window.Response(\n\t\t\t\t\t\t\t\tJSON.stringify( cacheData.body ),\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\t\t\tstatusText: 'OK',\n\t\t\t\t\t\t\t\t\theaders: cacheData.headers,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t )\n\t\t\t\t);\n\t\t\t} else if (\n\t\t\t\t'OPTIONS' === method &&\n\t\t\t\tcache[ method ] &&\n\t\t\t\tcache[ method ][ path ]\n\t\t\t) {\n\t\t\t\treturn Promise.resolve(\n\t\t\t\t\tparse\n\t\t\t\t\t\t? cache[ method ][ path ].body\n\t\t\t\t\t\t: cache[ method ][ path ]\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn next( options );\n\t};\n}\n\nexport default createPreloadingMiddleware;\n"]}
1
+ {"version":3,"sources":["@wordpress/api-fetch/src/middlewares/preloading.js"],"names":["getQueryArg","normalizePath","createPreloadingMiddleware","preloadedData","cache","Object","keys","reduce","result","path","options","next","parse","rawPath","url","pathFromQuery","method","cacheData","Promise","resolve","body","window","Response","JSON","stringify","status","statusText","headers"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,WAAT,EAAsBC,aAAtB,QAA2C,gBAA3C;AAEA;AACA;AACA;AACA;;AACA,SAASC,0BAAT,CAAqCC,aAArC,EAAqD;AACpD,QAAMC,KAAK,GAAGC,MAAM,CAACC,IAAP,CAAaH,aAAb,EAA6BI,MAA7B,CAAqC,CAAEC,MAAF,EAAUC,IAAV,KAAo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Z,KAAK,CAAEY,MAAF,CAAL,CAAiBP,IAAjB,CAHM,EAIL;AACD,cAAMQ,SAAS,GAAGb,KAAK,CAAEY,MAAF,CAAL,CAAiBP,IAAjB,CAAlB,CADC,CAGD;;AACA,eAAOL,KAAK,CAAEY,MAAF,CAAL,CAAiBP,IAAjB,CAAP;AAEA,eAAOS,OAAO,CAACC,OAAR,CAAiBP,KAAK,GAAGK,SAAS,CAACG,IAAb,GAAoBH,SAA1C,CAAP;AACA;AACD;;AAED,WAAON,IAAI,CAAED,OAAF,CAAX;AACA,GA/CD;AAgDA;;AAED,eAAeR,0BAAf","sourcesContent":["/**\n * WordPress dependencies\n */\nimport { getQueryArg, normalizePath } from '@wordpress/url';\n\n/**\n * @param {Record<string, any>} preloadedData\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nfunction createPreloadingMiddleware( preloadedData ) {\n\tconst cache = Object.keys( preloadedData ).reduce( ( result, path ) => {\n\t\tresult[ normalizePath( path ) ] = preloadedData[ path ];\n\t\treturn result;\n\t}, /** @type {Record<string, any>} */ ( {} ) );\n\n\treturn ( options, next ) => {\n\t\tconst { parse = true } = options;\n\t\t/** @type {string | void} */\n\t\tlet rawPath = options.path;\n\t\tif ( ! rawPath && options.url ) {\n\t\t\tconst pathFromQuery = getQueryArg( options.url, 'rest_route' );\n\t\t\tif ( typeof pathFromQuery === 'string' ) {\n\t\t\t\trawPath = pathFromQuery;\n\t\t\t}\n\t\t}\n\t\tif ( typeof rawPath === 'string' ) {\n\t\t\tconst method = options.method || 'GET';\n\t\t\tconst path = normalizePath( rawPath );\n\n\t\t\tif ( 'GET' === method && cache[ path ] ) {\n\t\t\t\tconst cacheData = cache[ path ];\n\n\t\t\t\t// Unsetting the cache key ensures that the data is only used a single time\n\t\t\t\tdelete cache[ path ];\n\n\t\t\t\treturn Promise.resolve(\n\t\t\t\t\tparse\n\t\t\t\t\t\t? cacheData.body\n\t\t\t\t\t\t: new window.Response(\n\t\t\t\t\t\t\t\tJSON.stringify( cacheData.body ),\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\t\t\tstatusText: 'OK',\n\t\t\t\t\t\t\t\t\theaders: cacheData.headers,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t )\n\t\t\t\t);\n\t\t\t} else if (\n\t\t\t\t'OPTIONS' === method &&\n\t\t\t\tcache[ method ] &&\n\t\t\t\tcache[ method ][ path ]\n\t\t\t) {\n\t\t\t\tconst cacheData = cache[ method ][ path ];\n\n\t\t\t\t// Unsetting the cache key ensures that the data is only used a single time\n\t\t\t\tdelete cache[ method ][ path ];\n\n\t\t\t\treturn Promise.resolve( parse ? cacheData.body : cacheData );\n\t\t\t}\n\t\t}\n\n\t\treturn next( options );\n\t};\n}\n\nexport default createPreloadingMiddleware;\n"]}
@@ -1,6 +1,6 @@
1
1
  export default apiFetch;
2
- export type APIFetchMiddleware = (options: import("./types").APIFetchOptions, next: (nextOptions: import("./types").APIFetchOptions) => Promise<any>) => Promise<any>;
3
- export type APIFetchOptions = import("./types").APIFetchOptions;
2
+ export type APIFetchMiddleware = import('./types').APIFetchMiddleware;
3
+ export type APIFetchOptions = import('./types').APIFetchOptions;
4
4
  export type FetchHandler = (options: import('./types').APIFetchOptions) => Promise<any>;
5
5
  /**
6
6
  * @template T
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":";;;qCAkFwB,OAAO,SAAS,EAAE,eAAe,KAAK,QAAQ,GAAG,CAAC;AAkE1E;;;;GAIG;AACH,sCAHW,OAAO,SAAS,EAAE,eAAe,cAmC3C;;;;;;;;;;AA/HD;;;;GAIG;AACH,gDAFW,OAAO,SAAS,EAAE,kBAAkB,QAI9C;AAyED;;;;;GAKG;AACH,kDAFW,YAAY,QAItB"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":";iCA6Cc,OAAO,SAAS,EAAE,kBAAkB;8BACpC,OAAO,SAAS,EAAE,eAAe;qCAoCvB,OAAO,SAAS,EAAE,eAAe,KAAK,QAAQ,GAAG,CAAC;AAkE1E;;;;GAIG;AACH,sCAHW,OAAO,SAAS,EAAE,eAAe,cAmC3C;;;;;;;;;;AA/HD;;;;GAIG;AACH,gDAFW,OAAO,SAAS,EAAE,kBAAkB,QAI9C;AAyED;;;;;GAKG;AACH,kDAFW,YAAY,QAItB"}
@@ -1 +1 @@
1
- {"version":3,"file":"media-upload.d.ts","sourceRoot":"","sources":["../../src/middlewares/media-upload.js"],"names":[],"mappings":";AAaA;;;;GAIG;AACH,qCAFU,OAAO,UAAU,EAAE,kBAAkB,CAiE7C"}
1
+ {"version":3,"file":"media-upload.d.ts","sourceRoot":"","sources":["../../src/middlewares/media-upload.js"],"names":[],"mappings":";AA0BA;;;;GAIG;AACH,qCAFU,OAAO,UAAU,EAAE,kBAAkB,CA8D7C"}
@@ -1,13 +1,3 @@
1
- /**
2
- * Given a path, returns a normalized path where equal query parameter values
3
- * will be treated as identical, regardless of order they appear in the original
4
- * text.
5
- *
6
- * @param {string} path Original path.
7
- *
8
- * @return {string} Normalized path.
9
- */
10
- export function getStablePath(path: string): string;
11
1
  export default createPreloadingMiddleware;
12
2
  /**
13
3
  * @param {Record<string, any>} preloadedData
@@ -1 +1 @@
1
- {"version":3,"file":"preloading.d.ts","sourceRoot":"","sources":["../../src/middlewares/preloading.js"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,oCAJW,MAAM,GAEL,MAAM,CA0BjB;;AAED;;;GAGG;AACH,2DAHW,OAAO,MAAM,EAAE,GAAG,CAAC,GAClB,OAAO,UAAU,EAAE,kBAAkB,CA+ChD"}
1
+ {"version":3,"file":"preloading.d.ts","sourceRoot":"","sources":["../../src/middlewares/preloading.js"],"names":[],"mappings":";AAKA;;;GAGG;AACH,2DAHW,OAAO,MAAM,EAAE,GAAG,CAAC,GAClB,OAAO,UAAU,EAAE,kBAAkB,CAwDhD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wordpress/api-fetch",
3
- "version": "5.2.2-next.5df0cd52b7.0",
3
+ "version": "5.2.5",
4
4
  "description": "Utility to make WordPress REST API requests.",
5
5
  "author": "The WordPress Contributors",
6
6
  "license": "GPL-2.0-or-later",
@@ -28,11 +28,11 @@
28
28
  "types": "build-types",
29
29
  "dependencies": {
30
30
  "@babel/runtime": "^7.13.10",
31
- "@wordpress/i18n": "^4.2.2-next.5df0cd52b7.0",
32
- "@wordpress/url": "^3.2.2-next.5df0cd52b7.0"
31
+ "@wordpress/i18n": "^4.2.3",
32
+ "@wordpress/url": "^3.3.0"
33
33
  },
34
34
  "publishConfig": {
35
35
  "access": "public"
36
36
  },
37
- "gitHead": "558d577d12bec15f05e694eb49a094836d885cca"
37
+ "gitHead": "393c2b5533837fd637e998d23f0124c081a10df0"
38
38
  }
@@ -11,19 +11,29 @@ import {
11
11
  parseResponseAndNormalizeError,
12
12
  } from '../utils/response';
13
13
 
14
+ /**
15
+ * @param {import('../types').APIFetchOptions} options
16
+ * @return {boolean} True if the request is for media upload.
17
+ */
18
+ function isMediaUploadRequest( options ) {
19
+ const isCreateMethod = !! options.method && options.method === 'POST';
20
+ const isMediaEndpoint =
21
+ ( !! options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||
22
+ ( !! options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );
23
+
24
+ return isMediaEndpoint && isCreateMethod;
25
+ }
26
+
14
27
  /**
15
28
  * Middleware handling media upload failures and retries.
16
29
  *
17
30
  * @type {import('../types').APIFetchMiddleware}
18
31
  */
19
32
  const mediaUploadMiddleware = ( options, next ) => {
20
- const isMediaUploadRequest =
21
- ( options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||
22
- ( options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );
23
-
24
- if ( ! isMediaUploadRequest ) {
33
+ if ( ! isMediaUploadRequest( options ) ) {
25
34
  return next( options );
26
35
  }
36
+
27
37
  let retries = 0;
28
38
  const maxRetries = 5;
29
39
 
@@ -1,37 +1,7 @@
1
1
  /**
2
- * Given a path, returns a normalized path where equal query parameter values
3
- * will be treated as identical, regardless of order they appear in the original
4
- * text.
5
- *
6
- * @param {string} path Original path.
7
- *
8
- * @return {string} Normalized path.
2
+ * WordPress dependencies
9
3
  */
10
- export function getStablePath( path ) {
11
- const splitted = path.split( '?' );
12
- const query = splitted[ 1 ];
13
- const base = splitted[ 0 ];
14
- if ( ! query ) {
15
- return base;
16
- }
17
-
18
- // 'b=1&c=2&a=5'
19
- return (
20
- base +
21
- '?' +
22
- query
23
- // [ 'b=1', 'c=2', 'a=5' ]
24
- .split( '&' )
25
- // [ [ 'b, '1' ], [ 'c', '2' ], [ 'a', '5' ] ]
26
- .map( ( entry ) => entry.split( '=' ) )
27
- // [ [ 'a', '5' ], [ 'b, '1' ], [ 'c', '2' ] ]
28
- .sort( ( a, b ) => a[ 0 ].localeCompare( b[ 0 ] ) )
29
- // [ 'a=5', 'b=1', 'c=2' ]
30
- .map( ( pair ) => pair.join( '=' ) )
31
- // 'a=5&b=1&c=2'
32
- .join( '&' )
33
- );
34
- }
4
+ import { getQueryArg, normalizePath } from '@wordpress/url';
35
5
 
36
6
  /**
37
7
  * @param {Record<string, any>} preloadedData
@@ -39,20 +9,28 @@ export function getStablePath( path ) {
39
9
  */
40
10
  function createPreloadingMiddleware( preloadedData ) {
41
11
  const cache = Object.keys( preloadedData ).reduce( ( result, path ) => {
42
- result[ getStablePath( path ) ] = preloadedData[ path ];
12
+ result[ normalizePath( path ) ] = preloadedData[ path ];
43
13
  return result;
44
14
  }, /** @type {Record<string, any>} */ ( {} ) );
45
15
 
46
16
  return ( options, next ) => {
47
17
  const { parse = true } = options;
48
- if ( typeof options.path === 'string' ) {
18
+ /** @type {string | void} */
19
+ let rawPath = options.path;
20
+ if ( ! rawPath && options.url ) {
21
+ const pathFromQuery = getQueryArg( options.url, 'rest_route' );
22
+ if ( typeof pathFromQuery === 'string' ) {
23
+ rawPath = pathFromQuery;
24
+ }
25
+ }
26
+ if ( typeof rawPath === 'string' ) {
49
27
  const method = options.method || 'GET';
50
- const path = getStablePath( options.path );
28
+ const path = normalizePath( rawPath );
51
29
 
52
30
  if ( 'GET' === method && cache[ path ] ) {
53
31
  const cacheData = cache[ path ];
54
32
 
55
- // Unsetting the cache key ensures that the data is only preloaded a single time
33
+ // Unsetting the cache key ensures that the data is only used a single time
56
34
  delete cache[ path ];
57
35
 
58
36
  return Promise.resolve(
@@ -72,11 +50,12 @@ function createPreloadingMiddleware( preloadedData ) {
72
50
  cache[ method ] &&
73
51
  cache[ method ][ path ]
74
52
  ) {
75
- return Promise.resolve(
76
- parse
77
- ? cache[ method ][ path ].body
78
- : cache[ method ][ path ]
79
- );
53
+ const cacheData = cache[ method ][ path ];
54
+
55
+ // Unsetting the cache key ensures that the data is only used a single time
56
+ delete cache[ method ][ path ];
57
+
58
+ return Promise.resolve( parse ? cacheData.body : cacheData );
80
59
  }
81
60
  }
82
61
 
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Internal dependencies
3
+ */
4
+ import mediaUploadMiddleware from '../media-upload';
5
+
6
+ describe( 'Media Upload Middleware', () => {
7
+ it( 'should defer to the next middleware with the same options', () => {
8
+ expect.hasAssertions();
9
+
10
+ const originalOptions = { path: '/wp/v2/media' };
11
+ const next = ( options ) => {
12
+ expect( options ).toBe( originalOptions );
13
+ };
14
+
15
+ mediaUploadMiddleware( originalOptions, next );
16
+ } );
17
+
18
+ it( 'should change options not to parse', () => {
19
+ expect.hasAssertions();
20
+
21
+ const requestOptions = { method: 'POST', path: '/wp/v2/media' };
22
+ const next = ( options ) => {
23
+ expect( options.parse ).toBe( false );
24
+
25
+ return Promise.resolve( {
26
+ status: 200,
27
+ json() {
28
+ return Promise.resolve( [ 'item' ] );
29
+ },
30
+ } );
31
+ };
32
+
33
+ mediaUploadMiddleware( requestOptions, next );
34
+ } );
35
+ } );