@wordpress/api-fetch 7.32.0 → 7.32.1-next.47f435fc9.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 (49) hide show
  1. package/build/index.js +112 -145
  2. package/build/index.js.map +7 -1
  3. package/build/middlewares/fetch-all-middleware.js +48 -81
  4. package/build/middlewares/fetch-all-middleware.js.map +7 -1
  5. package/build/middlewares/http-v1.js +29 -38
  6. package/build/middlewares/http-v1.js.map +7 -1
  7. package/build/middlewares/media-upload.js +43 -49
  8. package/build/middlewares/media-upload.js.map +7 -1
  9. package/build/middlewares/namespace-endpoint.js +27 -14
  10. package/build/middlewares/namespace-endpoint.js.map +7 -1
  11. package/build/middlewares/nonce.js +26 -23
  12. package/build/middlewares/nonce.js.map +7 -1
  13. package/build/middlewares/preloading.js +63 -60
  14. package/build/middlewares/preloading.js.map +7 -1
  15. package/build/middlewares/root-url.js +42 -27
  16. package/build/middlewares/root-url.js.map +7 -1
  17. package/build/middlewares/theme-preview.js +49 -38
  18. package/build/middlewares/theme-preview.js.map +7 -1
  19. package/build/middlewares/user-locale.js +28 -23
  20. package/build/middlewares/user-locale.js.map +7 -1
  21. package/build/types.js +16 -5
  22. package/build/types.js.map +7 -1
  23. package/build/utils/response.js +31 -39
  24. package/build/utils/response.js.map +7 -1
  25. package/build-module/index.js +76 -121
  26. package/build-module/index.js.map +7 -1
  27. package/build-module/middlewares/fetch-all-middleware.js +16 -71
  28. package/build-module/middlewares/fetch-all-middleware.js.map +7 -1
  29. package/build-module/middlewares/http-v1.js +11 -34
  30. package/build-module/middlewares/http-v1.js.map +7 -1
  31. package/build-module/middlewares/media-upload.js +27 -43
  32. package/build-module/middlewares/media-upload.js.map +7 -1
  33. package/build-module/middlewares/namespace-endpoint.js +9 -10
  34. package/build-module/middlewares/namespace-endpoint.js.map +7 -1
  35. package/build-module/middlewares/nonce.js +8 -19
  36. package/build-module/middlewares/nonce.js.map +7 -1
  37. package/build-module/middlewares/preloading.js +43 -54
  38. package/build-module/middlewares/preloading.js.map +7 -1
  39. package/build-module/middlewares/root-url.js +14 -23
  40. package/build-module/middlewares/root-url.js.map +7 -1
  41. package/build-module/middlewares/theme-preview.js +29 -31
  42. package/build-module/middlewares/theme-preview.js.map +7 -1
  43. package/build-module/middlewares/user-locale.js +10 -19
  44. package/build-module/middlewares/user-locale.js.map +7 -1
  45. package/build-module/types.js +1 -2
  46. package/build-module/types.js.map +7 -1
  47. package/build-module/utils/response.js +10 -36
  48. package/build-module/utils/response.js.map +7 -1
  49. package/package.json +13 -5
package/build/index.js CHANGED
@@ -1,172 +1,135 @@
1
1
  "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- var _exportNames = {};
8
- exports.default = void 0;
9
- var _i18n = require("@wordpress/i18n");
10
- var _nonce = _interopRequireDefault(require("./middlewares/nonce"));
11
- var _rootUrl = _interopRequireDefault(require("./middlewares/root-url"));
12
- var _preloading = _interopRequireDefault(require("./middlewares/preloading"));
13
- var _fetchAllMiddleware = _interopRequireDefault(require("./middlewares/fetch-all-middleware"));
14
- var _namespaceEndpoint = _interopRequireDefault(require("./middlewares/namespace-endpoint"));
15
- var _httpV = _interopRequireDefault(require("./middlewares/http-v1"));
16
- var _userLocale = _interopRequireDefault(require("./middlewares/user-locale"));
17
- var _mediaUpload = _interopRequireDefault(require("./middlewares/media-upload"));
18
- var _themePreview = _interopRequireDefault(require("./middlewares/theme-preview"));
19
- var _response = require("./utils/response");
20
- var _types = require("./types");
21
- Object.keys(_types).forEach(function (key) {
22
- if (key === "default" || key === "__esModule") return;
23
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
24
- if (key in exports && exports[key] === _types[key]) return;
25
- Object.defineProperty(exports, key, {
26
- enumerable: true,
27
- get: function () {
28
- return _types[key];
29
- }
30
- });
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var index_exports = {};
31
+ __export(index_exports, {
32
+ default: () => index_default
31
33
  });
32
- /**
33
- * WordPress dependencies
34
- */
35
-
36
- /**
37
- * Internal dependencies
38
- */
39
-
40
- /**
41
- * Default set of header values which should be sent with every request unless
42
- * explicitly provided through apiFetch options.
43
- */
34
+ module.exports = __toCommonJS(index_exports);
35
+ var import_i18n = require("@wordpress/i18n");
36
+ var import_nonce = __toESM(require("./middlewares/nonce"));
37
+ var import_root_url = __toESM(require("./middlewares/root-url"));
38
+ var import_preloading = __toESM(require("./middlewares/preloading"));
39
+ var import_fetch_all_middleware = __toESM(require("./middlewares/fetch-all-middleware"));
40
+ var import_namespace_endpoint = __toESM(require("./middlewares/namespace-endpoint"));
41
+ var import_http_v1 = __toESM(require("./middlewares/http-v1"));
42
+ var import_user_locale = __toESM(require("./middlewares/user-locale"));
43
+ var import_media_upload = __toESM(require("./middlewares/media-upload"));
44
+ var import_theme_preview = __toESM(require("./middlewares/theme-preview"));
45
+ var import_response = require("./utils/response");
46
+ __reExport(index_exports, require("./types"), module.exports);
44
47
  const DEFAULT_HEADERS = {
45
48
  // The backend uses the Accept header as a condition for considering an
46
49
  // incoming request as a REST request.
47
50
  //
48
51
  // See: https://core.trac.wordpress.org/ticket/44534
49
- Accept: 'application/json, */*;q=0.1'
52
+ Accept: "application/json, */*;q=0.1"
50
53
  };
51
-
52
- /**
53
- * Default set of fetch option values which should be sent with every request
54
- * unless explicitly provided through apiFetch options.
55
- */
56
54
  const DEFAULT_OPTIONS = {
57
- credentials: 'include'
55
+ credentials: "include"
58
56
  };
59
- const middlewares = [_userLocale.default, _namespaceEndpoint.default, _httpV.default, _fetchAllMiddleware.default];
60
-
61
- /**
62
- * Register a middleware
63
- *
64
- * @param middleware
65
- */
57
+ const middlewares = [
58
+ import_user_locale.default,
59
+ import_namespace_endpoint.default,
60
+ import_http_v1.default,
61
+ import_fetch_all_middleware.default
62
+ ];
66
63
  function registerMiddleware(middleware) {
67
64
  middlewares.unshift(middleware);
68
65
  }
69
- const defaultFetchHandler = nextOptions => {
70
- const {
71
- url,
72
- path,
73
- data,
74
- parse = true,
75
- ...remainingOptions
76
- } = nextOptions;
77
- let {
78
- body,
79
- headers
80
- } = nextOptions;
81
-
82
- // Merge explicitly-provided headers with default values.
83
- headers = {
84
- ...DEFAULT_HEADERS,
85
- ...headers
86
- };
87
-
88
- // The `data` property is a shorthand for sending a JSON body.
66
+ const defaultFetchHandler = (nextOptions) => {
67
+ const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
68
+ let { body, headers } = nextOptions;
69
+ headers = { ...DEFAULT_HEADERS, ...headers };
89
70
  if (data) {
90
71
  body = JSON.stringify(data);
91
- headers['Content-Type'] = 'application/json';
72
+ headers["Content-Type"] = "application/json";
92
73
  }
93
74
  const responsePromise = globalThis.fetch(
94
- // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
95
- url || path || window.location.href, {
96
- ...DEFAULT_OPTIONS,
97
- ...remainingOptions,
98
- body,
99
- headers
100
- });
101
- return responsePromise.then(response => {
102
- // If the response is not 2xx, still parse the response body as JSON
103
- // but throw the JSON as error.
104
- if (!response.ok) {
105
- return (0, _response.parseAndThrowError)(response, parse);
75
+ // Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
76
+ url || path || window.location.href,
77
+ {
78
+ ...DEFAULT_OPTIONS,
79
+ ...remainingOptions,
80
+ body,
81
+ headers
106
82
  }
107
- return (0, _response.parseResponseAndNormalizeError)(response, parse);
108
- }, err => {
109
- // Re-throw AbortError for the users to handle it themselves.
110
- if (err && err.name === 'AbortError') {
111
- throw err;
112
- }
113
-
114
- // If the browser reports being offline, we'll just assume that
115
- // this is why the request failed.
116
- if (!globalThis.navigator.onLine) {
83
+ );
84
+ return responsePromise.then(
85
+ (response) => {
86
+ if (!response.ok) {
87
+ return (0, import_response.parseAndThrowError)(response, parse);
88
+ }
89
+ return (0, import_response.parseResponseAndNormalizeError)(response, parse);
90
+ },
91
+ (err) => {
92
+ if (err && err.name === "AbortError") {
93
+ throw err;
94
+ }
95
+ if (!globalThis.navigator.onLine) {
96
+ throw {
97
+ code: "offline_error",
98
+ message: (0, import_i18n.__)(
99
+ "Unable to connect. Please check your Internet connection."
100
+ )
101
+ };
102
+ }
117
103
  throw {
118
- code: 'offline_error',
119
- message: (0, _i18n.__)('Unable to connect. Please check your Internet connection.')
104
+ code: "fetch_error",
105
+ message: (0, import_i18n.__)(
106
+ "Could not get a valid response from the server."
107
+ )
120
108
  };
121
109
  }
122
-
123
- // Hard to diagnose further due to how Window.fetch reports errors.
124
- throw {
125
- code: 'fetch_error',
126
- message: (0, _i18n.__)('Could not get a valid response from the server.')
127
- };
128
- });
110
+ );
129
111
  };
130
112
  let fetchHandler = defaultFetchHandler;
131
-
132
- /**
133
- * Defines a custom fetch handler for making the requests that will override
134
- * the default one using window.fetch
135
- *
136
- * @param newFetchHandler The new fetch handler
137
- */
138
113
  function setFetchHandler(newFetchHandler) {
139
114
  fetchHandler = newFetchHandler;
140
115
  }
141
- /**
142
- * Fetch
143
- *
144
- * @param options The options for the fetch.
145
- * @return A promise representing the request processed via the registered middlewares.
146
- */
147
- const apiFetch = options => {
148
- // creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
149
- // converting `middlewares = [ m1, m2, m3 ]` into:
150
- // ```
151
- // opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
152
- // ```
153
- const enhancedHandler = middlewares.reduceRight((next, middleware) => {
154
- return workingOptions => middleware(workingOptions, next);
155
- }, fetchHandler);
156
- return enhancedHandler(options).catch(error => {
157
- if (error.code !== 'rest_cookie_invalid_nonce') {
116
+ const apiFetch = (options) => {
117
+ const enhancedHandler = middlewares.reduceRight(
118
+ (next, middleware) => {
119
+ return (workingOptions) => middleware(workingOptions, next);
120
+ },
121
+ fetchHandler
122
+ );
123
+ return enhancedHandler(options).catch((error) => {
124
+ if (error.code !== "rest_cookie_invalid_nonce") {
158
125
  return Promise.reject(error);
159
126
  }
160
-
161
- // If the nonce is invalid, refresh it and try again.
162
- return globalThis.fetch(apiFetch.nonceEndpoint).then(response => {
163
- // If the nonce refresh fails, it means we failed to recover from the original
164
- // `rest_cookie_invalid_nonce` error and that it's time to finally re-throw it.
127
+ return globalThis.fetch(apiFetch.nonceEndpoint).then((response) => {
165
128
  if (!response.ok) {
166
129
  return Promise.reject(error);
167
130
  }
168
131
  return response.text();
169
- }).then(text => {
132
+ }).then((text) => {
170
133
  apiFetch.nonceMiddleware.nonce = text;
171
134
  return apiFetch(options);
172
135
  });
@@ -174,11 +137,15 @@ const apiFetch = options => {
174
137
  };
175
138
  apiFetch.use = registerMiddleware;
176
139
  apiFetch.setFetchHandler = setFetchHandler;
177
- apiFetch.createNonceMiddleware = _nonce.default;
178
- apiFetch.createPreloadingMiddleware = _preloading.default;
179
- apiFetch.createRootURLMiddleware = _rootUrl.default;
180
- apiFetch.fetchAllMiddleware = _fetchAllMiddleware.default;
181
- apiFetch.mediaUploadMiddleware = _mediaUpload.default;
182
- apiFetch.createThemePreviewMiddleware = _themePreview.default;
183
- var _default = exports.default = apiFetch;
184
- //# sourceMappingURL=index.js.map
140
+ apiFetch.createNonceMiddleware = import_nonce.default;
141
+ apiFetch.createPreloadingMiddleware = import_preloading.default;
142
+ apiFetch.createRootURLMiddleware = import_root_url.default;
143
+ apiFetch.fetchAllMiddleware = import_fetch_all_middleware.default;
144
+ apiFetch.mediaUploadMiddleware = import_media_upload.default;
145
+ apiFetch.createThemePreviewMiddleware = import_theme_preview.default;
146
+ var index_default = apiFetch;
147
+ // Annotate the CommonJS export names for ESM import in node:
148
+ 0 && (module.exports = {
149
+ ...require("./types")
150
+ });
151
+ //# sourceMappingURL=index.js.map
@@ -1 +1,7 @@
1
- {"version":3,"names":["_i18n","require","_nonce","_interopRequireDefault","_rootUrl","_preloading","_fetchAllMiddleware","_namespaceEndpoint","_httpV","_userLocale","_mediaUpload","_themePreview","_response","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","DEFAULT_HEADERS","Accept","DEFAULT_OPTIONS","credentials","middlewares","userLocaleMiddleware","namespaceEndpointMiddleware","httpV1Middleware","fetchAllMiddleware","registerMiddleware","middleware","unshift","defaultFetchHandler","nextOptions","url","path","data","parse","remainingOptions","body","headers","JSON","stringify","responsePromise","globalThis","fetch","window","location","href","then","response","ok","parseAndThrowError","parseResponseAndNormalizeError","err","name","navigator","onLine","code","message","__","fetchHandler","setFetchHandler","newFetchHandler","apiFetch","options","enhancedHandler","reduceRight","next","workingOptions","catch","error","Promise","reject","nonceEndpoint","text","nonceMiddleware","nonce","use","createNonceMiddleware","createPreloadingMiddleware","createRootURLMiddleware","mediaUploadMiddleware","createThemePreviewMiddleware","_default","default"],"sources":["@wordpress/api-fetch/src/index.ts"],"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';\nimport type {\n\tAPIFetchMiddleware,\n\tAPIFetchOptions,\n\tFetchHandler,\n} from './types';\n\n/**\n * Default set of header values which should be sent with every request unless\n * explicitly provided through apiFetch options.\n */\nconst DEFAULT_HEADERS: APIFetchOptions[ '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 */\nconst DEFAULT_OPTIONS: APIFetchOptions = {\n\tcredentials: 'include',\n};\n\nconst middlewares: Array< APIFetchMiddleware > = [\n\tuserLocaleMiddleware,\n\tnamespaceEndpointMiddleware,\n\thttpV1Middleware,\n\tfetchAllMiddleware,\n];\n\n/**\n * Register a middleware\n *\n * @param middleware\n */\nfunction registerMiddleware( middleware: APIFetchMiddleware ) {\n\tmiddlewares.unshift( middleware );\n}\n\nconst defaultFetchHandler: FetchHandler = ( 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 = globalThis.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( response ) => {\n\t\t\t// If the response is not 2xx, still parse the response body as JSON\n\t\t\t// but throw the JSON as error.\n\t\t\tif ( ! response.ok ) {\n\t\t\t\treturn parseAndThrowError( response, parse );\n\t\t\t}\n\n\t\t\treturn parseResponseAndNormalizeError( response, parse );\n\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// If the browser reports being offline, we'll just assume that\n\t\t\t// this is why the request failed.\n\t\t\tif ( ! globalThis.navigator.onLine ) {\n\t\t\t\tthrow {\n\t\t\t\t\tcode: 'offline_error',\n\t\t\t\t\tmessage: __(\n\t\t\t\t\t\t'Unable to connect. Please check your Internet connection.'\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Hard to diagnose further due to how Window.fetch reports errors.\n\t\t\tthrow {\n\t\t\t\tcode: 'fetch_error',\n\t\t\t\tmessage: __(\n\t\t\t\t\t'Could not get a valid response from the server.'\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t);\n};\n\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 newFetchHandler The new fetch handler\n */\nfunction setFetchHandler( newFetchHandler: FetchHandler ) {\n\tfetchHandler = newFetchHandler;\n}\n\ninterface apiFetch {\n\t< T, Parse extends boolean = true >(\n\t\toptions: APIFetchOptions< Parse >\n\t): Promise< Parse extends true ? T : Response >;\n\tnonceEndpoint?: string;\n\tnonceMiddleware?: ReturnType< typeof createNonceMiddleware >;\n\tuse: ( middleware: APIFetchMiddleware ) => void;\n\tsetFetchHandler: ( newFetchHandler: FetchHandler ) => void;\n\tcreateNonceMiddleware: typeof createNonceMiddleware;\n\tcreatePreloadingMiddleware: typeof createPreloadingMiddleware;\n\tcreateRootURLMiddleware: typeof createRootURLMiddleware;\n\tfetchAllMiddleware: typeof fetchAllMiddleware;\n\tmediaUploadMiddleware: typeof mediaUploadMiddleware;\n\tcreateThemePreviewMiddleware: typeof createThemePreviewMiddleware;\n}\n\n/**\n * Fetch\n *\n * @param options The options for the fetch.\n * @return A promise representing the request processed via the registered middlewares.\n */\nconst apiFetch: 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< FetchHandler >(\n\t\t( 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 globalThis\n\t\t\t.fetch( apiFetch.nonceEndpoint! )\n\t\t\t.then( ( response ) => {\n\t\t\t\t// If the nonce refresh fails, it means we failed to recover from the original\n\t\t\t\t// `rest_cookie_invalid_nonce` error and that it's time to finally re-throw it.\n\t\t\t\tif ( ! response.ok ) {\n\t\t\t\t\treturn Promise.reject( error );\n\t\t\t\t}\n\n\t\t\t\treturn response.text();\n\t\t\t} )\n\t\t\t.then( ( text ) => {\n\t\t\t\tapiFetch.nonceMiddleware!.nonce = text;\n\t\t\t\treturn apiFetch( options );\n\t\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;\nexport * from './types';\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;AA8LA,IAAAY,MAAA,GAAAZ,OAAA;AAAAa,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,M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OAAO3B,UAAU,CACfC,KAAK,CAAEmB,QAAQ,CAACU,aAAe,CAAC,CAChCzB,IAAI,CAAIC,QAAQ,IAAM;MACtB;MACA;MACA,IAAK,CAAEA,QAAQ,CAACC,EAAE,EAAG;QACpB,OAAOqB,OAAO,CAACC,MAAM,CAAEF,KAAM,CAAC;MAC/B;MAEA,OAAOrB,QAAQ,CAACyB,IAAI,CAAC,CAAC;IACvB,CAAE,CAAC,CACF1B,IAAI,CAAI0B,IAAI,IAAM;MAClBX,QAAQ,CAACY,eAAe,CAAEC,KAAK,GAAGF,IAAI;MACtC,OAAOX,QAAQ,CAAEC,OAAQ,CAAC;IAC3B,CAAE,CAAC;EACL,CAAE,CAAC;AACJ,CAAC;AAEDD,QAAQ,CAACc,GAAG,GAAGjD,kBAAkB;AACjCmC,QAAQ,CAACF,eAAe,GAAGA,eAAe;AAE1CE,QAAQ,CAACe,qBAAqB,GAAGA,cAAqB;AACtDf,QAAQ,CAACgB,0BAA0B,GAAGA,mBAA0B;AAChEhB,QAAQ,CAACiB,uBAAuB,GAAGA,gBAAuB;AAC1DjB,QAAQ,CAACpC,kBAAkB,GAAGA,2BAAkB;AAChDoC,QAAQ,CAACkB,qBAAqB,GAAGA,oBAAqB;AACtDlB,QAAQ,CAACmB,4BAA4B,GAAGA,qBAA4B;AAAC,IAAAC,QAAA,GAAApE,OAAA,CAAAqE,OAAA,GAEtDrB,QAAQ","ignoreList":[]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "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';\nimport type {\n\tAPIFetchMiddleware,\n\tAPIFetchOptions,\n\tFetchHandler,\n} from './types';\n\n/**\n * Default set of header values which should be sent with every request unless\n * explicitly provided through apiFetch options.\n */\nconst DEFAULT_HEADERS: APIFetchOptions[ '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 */\nconst DEFAULT_OPTIONS: APIFetchOptions = {\n\tcredentials: 'include',\n};\n\nconst middlewares: Array< APIFetchMiddleware > = [\n\tuserLocaleMiddleware,\n\tnamespaceEndpointMiddleware,\n\thttpV1Middleware,\n\tfetchAllMiddleware,\n];\n\n/**\n * Register a middleware\n *\n * @param middleware\n */\nfunction registerMiddleware( middleware: APIFetchMiddleware ) {\n\tmiddlewares.unshift( middleware );\n}\n\nconst defaultFetchHandler: FetchHandler = ( 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 = globalThis.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( response ) => {\n\t\t\t// If the response is not 2xx, still parse the response body as JSON\n\t\t\t// but throw the JSON as error.\n\t\t\tif ( ! response.ok ) {\n\t\t\t\treturn parseAndThrowError( response, parse );\n\t\t\t}\n\n\t\t\treturn parseResponseAndNormalizeError( response, parse );\n\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// If the browser reports being offline, we'll just assume that\n\t\t\t// this is why the request failed.\n\t\t\tif ( ! globalThis.navigator.onLine ) {\n\t\t\t\tthrow {\n\t\t\t\t\tcode: 'offline_error',\n\t\t\t\t\tmessage: __(\n\t\t\t\t\t\t'Unable to connect. Please check your Internet connection.'\n\t\t\t\t\t),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Hard to diagnose further due to how Window.fetch reports errors.\n\t\t\tthrow {\n\t\t\t\tcode: 'fetch_error',\n\t\t\t\tmessage: __(\n\t\t\t\t\t'Could not get a valid response from the server.'\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t);\n};\n\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 newFetchHandler The new fetch handler\n */\nfunction setFetchHandler( newFetchHandler: FetchHandler ) {\n\tfetchHandler = newFetchHandler;\n}\n\ninterface apiFetch {\n\t< T, Parse extends boolean = true >(\n\t\toptions: APIFetchOptions< Parse >\n\t): Promise< Parse extends true ? T : Response >;\n\tnonceEndpoint?: string;\n\tnonceMiddleware?: ReturnType< typeof createNonceMiddleware >;\n\tuse: ( middleware: APIFetchMiddleware ) => void;\n\tsetFetchHandler: ( newFetchHandler: FetchHandler ) => void;\n\tcreateNonceMiddleware: typeof createNonceMiddleware;\n\tcreatePreloadingMiddleware: typeof createPreloadingMiddleware;\n\tcreateRootURLMiddleware: typeof createRootURLMiddleware;\n\tfetchAllMiddleware: typeof fetchAllMiddleware;\n\tmediaUploadMiddleware: typeof mediaUploadMiddleware;\n\tcreateThemePreviewMiddleware: typeof createThemePreviewMiddleware;\n}\n\n/**\n * Fetch\n *\n * @param options The options for the fetch.\n * @return A promise representing the request processed via the registered middlewares.\n */\nconst apiFetch: 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< FetchHandler >(\n\t\t( 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 globalThis\n\t\t\t.fetch( apiFetch.nonceEndpoint! )\n\t\t\t.then( ( response ) => {\n\t\t\t\t// If the nonce refresh fails, it means we failed to recover from the original\n\t\t\t\t// `rest_cookie_invalid_nonce` error and that it's time to finally re-throw it.\n\t\t\t\tif ( ! response.ok ) {\n\t\t\t\t\treturn Promise.reject( error );\n\t\t\t\t}\n\n\t\t\t\treturn response.text();\n\t\t\t} )\n\t\t\t.then( ( text ) => {\n\t\t\t\tapiFetch.nonceMiddleware!.nonce = text;\n\t\t\t\treturn apiFetch( options );\n\t\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;\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leware", "createPreloadingMiddleware", "createRootURLMiddleware", "mediaUploadMiddleware", "createThemePreviewMiddleware"]
7
+ }
@@ -1,50 +1,45 @@
1
1
  "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var fetch_all_middleware_exports = {};
30
+ __export(fetch_all_middleware_exports, {
31
+ default: () => fetch_all_middleware_default
6
32
  });
7
- exports.default = void 0;
8
- var _url = require("@wordpress/url");
9
- var _ = _interopRequireDefault(require(".."));
10
- /**
11
- * WordPress dependencies
12
- */
13
-
14
- /**
15
- * Internal dependencies
16
- */
17
-
18
- /**
19
- * Apply query arguments to both URL and Path, whichever is present.
20
- *
21
- * @param {APIFetchOptions} props The request options
22
- * @param {Record< string, string | number >} queryArgs
23
- * @return The request with the modified query args
24
- */
25
- const modifyQuery = ({
26
- path,
27
- url,
28
- ...options
29
- }, queryArgs) => ({
33
+ module.exports = __toCommonJS(fetch_all_middleware_exports);
34
+ var import_url = require("@wordpress/url");
35
+ var import__ = __toESM(require(".."));
36
+ const modifyQuery = ({ path, url, ...options }, queryArgs) => ({
30
37
  ...options,
31
- url: url && (0, _url.addQueryArgs)(url, queryArgs),
32
- path: path && (0, _url.addQueryArgs)(path, queryArgs)
38
+ url: url && (0, import_url.addQueryArgs)(url, queryArgs),
39
+ path: path && (0, import_url.addQueryArgs)(path, queryArgs)
33
40
  });
34
-
35
- /**
36
- * Duplicates parsing functionality from apiFetch.
37
- *
38
- * @param response
39
- * @return Parsed response json.
40
- */
41
- const parseResponse = response => response.json ? response.json() : Promise.reject(response);
42
-
43
- /**
44
- * @param linkHeader
45
- * @return The parsed link header.
46
- */
47
- const parseLinkHeader = linkHeader => {
41
+ const parseResponse = (response) => response.json ? response.json() : Promise.reject(response);
42
+ const parseLinkHeader = (linkHeader) => {
48
43
  if (!linkHeader) {
49
44
  return {};
50
45
  }
@@ -53,47 +48,23 @@ const parseLinkHeader = linkHeader => {
53
48
  next: match[1]
54
49
  } : {};
55
50
  };
56
-
57
- /**
58
- * @param response
59
- * @return The next page URL.
60
- */
61
- const getNextPageUrl = response => {
62
- const {
63
- next
64
- } = parseLinkHeader(response.headers.get('link'));
51
+ const getNextPageUrl = (response) => {
52
+ const { next } = parseLinkHeader(response.headers.get("link"));
65
53
  return next;
66
54
  };
67
-
68
- /**
69
- * @param options
70
- * @return True if the request contains an unbounded query.
71
- */
72
- const requestContainsUnboundedQuery = options => {
73
- const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
74
- const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
55
+ const requestContainsUnboundedQuery = (options) => {
56
+ const pathIsUnbounded = !!options.path && options.path.indexOf("per_page=-1") !== -1;
57
+ const urlIsUnbounded = !!options.url && options.url.indexOf("per_page=-1") !== -1;
75
58
  return pathIsUnbounded || urlIsUnbounded;
76
59
  };
77
-
78
- /**
79
- * The REST API enforces an upper limit on the per_page option. To handle large
80
- * collections, apiFetch consumers can pass `per_page=-1`; this middleware will
81
- * then recursively assemble a full response array from all available pages.
82
- * @param options
83
- * @param next
84
- */
85
60
  const fetchAllMiddleware = async (options, next) => {
86
61
  if (options.parse === false) {
87
- // If a consumer has opted out of parsing, do not apply middleware.
88
62
  return next(options);
89
63
  }
90
64
  if (!requestContainsUnboundedQuery(options)) {
91
- // If neither url nor path is requesting all items, do not apply middleware.
92
65
  return next(options);
93
66
  }
94
-
95
- // Retrieve requested page of results.
96
- const response = await (0, _.default)({
67
+ const response = await (0, import__.default)({
97
68
  ...modifyQuery(options, {
98
69
  per_page: 100
99
70
  }),
@@ -102,22 +73,18 @@ const fetchAllMiddleware = async (options, next) => {
102
73
  });
103
74
  const results = await parseResponse(response);
104
75
  if (!Array.isArray(results)) {
105
- // We have no reliable way of merging non-array results.
106
76
  return results;
107
77
  }
108
78
  let nextPage = getNextPageUrl(response);
109
79
  if (!nextPage) {
110
- // There are no further pages to request.
111
80
  return results;
112
81
  }
113
-
114
- // Iteratively fetch all remaining pages until no "next" header is found.
115
82
  let mergedResults = [].concat(results);
116
83
  while (nextPage) {
117
- const nextResponse = await (0, _.default)({
84
+ const nextResponse = await (0, import__.default)({
118
85
  ...options,
119
86
  // Ensure the URL for the next page is used instead of any provided path.
120
- path: undefined,
87
+ path: void 0,
121
88
  url: nextPage,
122
89
  // Ensure we still get headers so we can identify the next page.
123
90
  parse: false
@@ -128,5 +95,5 @@ const fetchAllMiddleware = async (options, next) => {
128
95
  }
129
96
  return mergedResults;
130
97
  };
131
- var _default = exports.default = fetchAllMiddleware;
132
- //# sourceMappingURL=fetch-all-middleware.js.map
98
+ var fetch_all_middleware_default = fetchAllMiddleware;
99
+ //# sourceMappingURL=fetch-all-middleware.js.map
@@ -1 +1,7 @@
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.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs } from '@wordpress/url';\n\n/**\n * Internal dependencies\n */\nimport apiFetch from '..';\nimport type { APIFetchMiddleware, APIFetchOptions } from '../types';\n\n/**\n * Apply query arguments to both URL and Path, whichever is present.\n *\n * @param {APIFetchOptions} props The request options\n * @param {Record< string, string | number >} queryArgs\n * @return The request with the modified query args\n */\nconst modifyQuery = (\n\t{ path, url, ...options }: APIFetchOptions,\n\tqueryArgs: Record< string, string | number >\n): APIFetchOptions => ( {\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\n * @return Parsed response json.\n */\nconst parseResponse = ( response: Response ) =>\n\tresponse.json ? response.json() : Promise.reject( response );\n\n/**\n * @param linkHeader\n * @return The parsed link header.\n */\nconst parseLinkHeader = ( linkHeader: string | null ) => {\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\n * @return The next page URL.\n */\nconst getNextPageUrl = ( response: Response ) => {\n\tconst { next } = parseLinkHeader( response.headers.get( 'link' ) );\n\treturn next;\n};\n\n/**\n * @param options\n * @return True if the request contains an unbounded query.\n */\nconst requestContainsUnboundedQuery = ( options: APIFetchOptions ) => {\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 * @param options\n * @param next\n */\nconst fetchAllMiddleware: APIFetchMiddleware = 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 = ( [] as Array< 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;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMG,WAAW,GAAGA,CACnB;EAAEC,IAAI;EAAEC,GAAG;EAAE,GAAGC;AAAyB,CAAC,EAC1CC,SAA4C,MACrB;EACvB,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,QAAkB,IACzCA,QAAQ,CAACC,IAAI,GAAGD,QAAQ,CAACC,IAAI,CAAC,CAAC,GAAGC,OAAO,CAACC,MAAM,CAAEH,QAAS,CAAC;;AAE7D;AACA;AACA;AACA;AACA,MAAMI,eAAe,GAAKC,UAAyB,IAAM;EACxD,IAAK,CAAEA,UAAU,EAAG;IACnB,OAAO,CAAC,CAAC;EACV;EACA,MAAMC,KAAK,GAAGD,UAAU,CAACC,KAAK,CAAE,uBAAwB,CAAC;EACzD,OAAOA,KAAK,GACT;IACAC,IAAI,EAAED,KAAK,CAAE,CAAC;EACd,CAAC,GACD,CAAC,CAAC;AACN,CAAC;;AAED;AACA;AACA;AACA;AACA,MAAME,cAAc,GAAKR,QAAkB,IAAM;EAChD,MAAM;IAAEO;EAAK,CAAC,GAAGH,eAAe,CAAEJ,QAAQ,CAACS,OAAO,CAACC,GAAG,CAAE,MAAO,CAAE,CAAC;EAClE,OAAOH,IAAI;AACZ,CAAC;;AAED;AACA;AACA;AACA;AACA,MAAMI,6BAA6B,GAAKf,OAAwB,I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rB,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,GAAAC,OAAA,CAAAC,OAAA,GAEaf,kBAAkB","ignoreList":[]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/middlewares/fetch-all-middleware.ts"],
4
+ "sourcesContent": ["/**\n * WordPress dependencies\n */\nimport { addQueryArgs } from '@wordpress/url';\n\n/**\n * Internal dependencies\n */\nimport apiFetch from '..';\nimport type { APIFetchMiddleware, APIFetchOptions } from '../types';\n\n/**\n * Apply query arguments to both URL and Path, whichever is present.\n *\n * @param {APIFetchOptions} props The request options\n * @param {Record< string, string | number >} queryArgs\n * @return The request with the modified query args\n */\nconst modifyQuery = (\n\t{ path, url, ...options }: APIFetchOptions,\n\tqueryArgs: Record< string, string | number >\n): APIFetchOptions => ( {\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\n * @return Parsed response json.\n */\nconst parseResponse = ( response: Response ) =>\n\tresponse.json ? response.json() : Promise.reject( response );\n\n/**\n * @param linkHeader\n * @return The parsed link header.\n */\nconst parseLinkHeader = ( linkHeader: string | null ) => {\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\n * @return The next page URL.\n */\nconst getNextPageUrl = ( response: Response ) => {\n\tconst { next } = parseLinkHeader( response.headers.get( 'link' ) );\n\treturn next;\n};\n\n/**\n * @param options\n * @return True if the request contains an unbounded query.\n */\nconst requestContainsUnboundedQuery = ( options: APIFetchOptions ) => {\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 * @param options\n * @param next\n */\nconst fetchAllMiddleware: APIFetchMiddleware = 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 = ( [] as Array< 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"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,iBAA6B;AAK7B,eAAqB;AAUrB,MAAM,cAAc,CACnB,EAAE,MAAM,KAAK,GAAG,QAAQ,GACxB,eACuB;AAAA,EACvB,GAAG;AAAA,EACH,KAAK,WAAO,yBAAc,KAAK,SAAU;AAAA,EACzC,MAAM,YAAQ,yBAAc,MAAM,SAAU;AAC7C;AAQA,MAAM,gBAAgB,CAAE,aACvB,SAAS,OAAO,SAAS,KAAK,IAAI,QAAQ,OAAQ,QAAS;AAM5D,MAAM,kBAAkB,CAAE,eAA+B;AACxD,MAAK,CAAE,YAAa;AACnB,WAAO,CAAC;AAAA,EACT;AACA,QAAM,QAAQ,WAAW,MAAO,uBAAwB;AACxD,SAAO,QACJ;AAAA,IACA,MAAM,MAAO,CAAE;AAAA,EACf,IACA,CAAC;AACL;AAMA,MAAM,iBAAiB,CAAE,aAAwB;AAChD,QAAM,EAAE,KAAK,IAAI,gBAAiB,SAAS,QAAQ,IAAK,MAAO,CAAE;AACjE,SAAO;AACR;AAMA,MAAM,gCAAgC,CAAE,YAA8B;AACrE,QAAM,kBACL,CAAC,CAAE,QAAQ,QAAQ,QAAQ,KAAK,QAAS,aAAc,MAAM;AAC9D,QAAM,iBACL,CAAC,CAAE,QAAQ,OAAO,QAAQ,IAAI,QAAS,aAAc,MAAM;AAC5D,SAAO,mBAAmB;AAC3B;AASA,MAAM,qBAAyC,OAAQ,SAAS,SAAU;AACzE,MAAK,QAAQ,UAAU,OAAQ;AAE9B,WAAO,KAAM,OAAQ;AAAA,EACtB;AACA,MAAK,CAAE,8BAA+B,OAAQ,GAAI;AAEjD,WAAO,KAAM,OAAQ;AAAA,EACtB;AAGA,QAAM,WAAW,UAAM,SAAAA,SAAU;AAAA,IAChC,GAAG,YAAa,SAAS;AAAA,MACxB,UAAU;AAAA,IACX,CAAE;AAAA;AAAA,IAEF,OAAO;AAAA,EACR,CAAE;AAEF,QAAM,UAAU,MAAM,cAAe,QAAS;AAE9C,MAAK,CAAE,MAAM,QAAS,OAAQ,GAAI;AAEjC,WAAO;AAAA,EACR;AAEA,MAAI,WAAW,eAAgB,QAAS;AAExC,MAAK,CAAE,UAAW;AAEjB,WAAO;AAAA,EACR;AAGA,MAAI,gBAAkB,CAAC,EAAoB,OAAQ,OAAQ;AAC3D,SAAQ,UAAW;AAClB,UAAM,eAAe,UAAM,SAAAA,SAAU;AAAA,MACpC,GAAG;AAAA;AAAA,MAEH,MAAM;AAAA,MACN,KAAK;AAAA;AAAA,MAEL,OAAO;AAAA,IACR,CAAE;AACF,UAAM,cAAc,MAAM,cAAe,YAAa;AACtD,oBAAgB,cAAc,OAAQ,WAAY;AAClD,eAAW,eAAgB,YAAa;AAAA,EACzC;AACA,SAAO;AACR;AAEA,IAAO,+BAAQ;",
6
+ "names": ["apiFetch"]
7
+ }
@@ -1,51 +1,42 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var http_v1_exports = {};
20
+ __export(http_v1_exports, {
21
+ default: () => http_v1_default
5
22
  });
6
- exports.default = void 0;
7
- /**
8
- * Internal dependencies
9
- */
10
-
11
- /**
12
- * Set of HTTP methods which are eligible to be overridden.
13
- */
14
- const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
15
-
16
- /**
17
- * Default request method.
18
- *
19
- * "A request has an associated method (a method). Unless stated otherwise it
20
- * is `GET`."
21
- *
22
- * @see https://fetch.spec.whatwg.org/#requests
23
- */
24
- const DEFAULT_METHOD = 'GET';
25
-
26
- /**
27
- * API Fetch middleware which overrides the request method for HTTP v1
28
- * compatibility leveraging the REST API X-HTTP-Method-Override header.
29
- *
30
- * @param options
31
- * @param next
32
- */
23
+ module.exports = __toCommonJS(http_v1_exports);
24
+ const OVERRIDE_METHODS = /* @__PURE__ */ new Set(["PATCH", "PUT", "DELETE"]);
25
+ const DEFAULT_METHOD = "GET";
33
26
  const httpV1Middleware = (options, next) => {
34
- const {
35
- method = DEFAULT_METHOD
36
- } = options;
27
+ const { method = DEFAULT_METHOD } = options;
37
28
  if (OVERRIDE_METHODS.has(method.toUpperCase())) {
38
29
  options = {
39
30
  ...options,
40
31
  headers: {
41
32
  ...options.headers,
42
- 'X-HTTP-Method-Override': method,
43
- 'Content-Type': 'application/json'
33
+ "X-HTTP-Method-Override": method,
34
+ "Content-Type": "application/json"
44
35
  },
45
- method: 'POST'
36
+ method: "POST"
46
37
  };
47
38
  }
48
39
  return next(options);
49
40
  };
50
- var _default = exports.default = httpV1Middleware;
51
- //# sourceMappingURL=http-v1.js.map
41
+ var http_v1_default = httpV1Middleware;
42
+ //# sourceMappingURL=http-v1.js.map