@wordpress/api-fetch 7.31.1-next.f56bd8138.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.
- package/CHANGELOG.md +2 -0
- package/build/index.js +112 -145
- package/build/index.js.map +7 -1
- package/build/middlewares/fetch-all-middleware.js +48 -81
- package/build/middlewares/fetch-all-middleware.js.map +7 -1
- package/build/middlewares/http-v1.js +29 -38
- package/build/middlewares/http-v1.js.map +7 -1
- package/build/middlewares/media-upload.js +43 -49
- package/build/middlewares/media-upload.js.map +7 -1
- package/build/middlewares/namespace-endpoint.js +27 -14
- package/build/middlewares/namespace-endpoint.js.map +7 -1
- package/build/middlewares/nonce.js +26 -23
- package/build/middlewares/nonce.js.map +7 -1
- package/build/middlewares/preloading.js +63 -60
- package/build/middlewares/preloading.js.map +7 -1
- package/build/middlewares/root-url.js +42 -27
- package/build/middlewares/root-url.js.map +7 -1
- package/build/middlewares/theme-preview.js +49 -38
- package/build/middlewares/theme-preview.js.map +7 -1
- package/build/middlewares/user-locale.js +28 -23
- package/build/middlewares/user-locale.js.map +7 -1
- package/build/types.js +16 -5
- package/build/types.js.map +7 -1
- package/build/utils/response.js +31 -39
- package/build/utils/response.js.map +7 -1
- package/build-module/index.js +76 -121
- package/build-module/index.js.map +7 -1
- package/build-module/middlewares/fetch-all-middleware.js +16 -71
- package/build-module/middlewares/fetch-all-middleware.js.map +7 -1
- package/build-module/middlewares/http-v1.js +11 -34
- package/build-module/middlewares/http-v1.js.map +7 -1
- package/build-module/middlewares/media-upload.js +27 -43
- package/build-module/middlewares/media-upload.js.map +7 -1
- package/build-module/middlewares/namespace-endpoint.js +9 -10
- package/build-module/middlewares/namespace-endpoint.js.map +7 -1
- package/build-module/middlewares/nonce.js +8 -19
- package/build-module/middlewares/nonce.js.map +7 -1
- package/build-module/middlewares/preloading.js +43 -54
- package/build-module/middlewares/preloading.js.map +7 -1
- package/build-module/middlewares/root-url.js +14 -23
- package/build-module/middlewares/root-url.js.map +7 -1
- package/build-module/middlewares/theme-preview.js +29 -31
- package/build-module/middlewares/theme-preview.js.map +7 -1
- package/build-module/middlewares/user-locale.js +10 -19
- package/build-module/middlewares/user-locale.js.map +7 -1
- package/build-module/types.js +1 -2
- package/build-module/types.js.map +7 -1
- package/build-module/utils/response.js +10 -36
- package/build-module/utils/response.js.map +7 -1
- package/package.json +13 -5
package/build-module/index.js
CHANGED
|
@@ -1,151 +1,103 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
import
|
|
10
|
-
import
|
|
11
|
-
import
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
import userLocaleMiddleware from './middlewares/user-locale';
|
|
16
|
-
import mediaUploadMiddleware from './middlewares/media-upload';
|
|
17
|
-
import createThemePreviewMiddleware from './middlewares/theme-preview';
|
|
18
|
-
import { parseResponseAndNormalizeError, parseAndThrowError } from './utils/response';
|
|
19
|
-
/**
|
|
20
|
-
* Default set of header values which should be sent with every request unless
|
|
21
|
-
* explicitly provided through apiFetch options.
|
|
22
|
-
*/
|
|
1
|
+
import { __ } from "@wordpress/i18n";
|
|
2
|
+
import createNonceMiddleware from "./middlewares/nonce";
|
|
3
|
+
import createRootURLMiddleware from "./middlewares/root-url";
|
|
4
|
+
import createPreloadingMiddleware from "./middlewares/preloading";
|
|
5
|
+
import fetchAllMiddleware from "./middlewares/fetch-all-middleware";
|
|
6
|
+
import namespaceEndpointMiddleware from "./middlewares/namespace-endpoint";
|
|
7
|
+
import httpV1Middleware from "./middlewares/http-v1";
|
|
8
|
+
import userLocaleMiddleware from "./middlewares/user-locale";
|
|
9
|
+
import mediaUploadMiddleware from "./middlewares/media-upload";
|
|
10
|
+
import createThemePreviewMiddleware from "./middlewares/theme-preview";
|
|
11
|
+
import {
|
|
12
|
+
parseResponseAndNormalizeError,
|
|
13
|
+
parseAndThrowError
|
|
14
|
+
} from "./utils/response";
|
|
23
15
|
const DEFAULT_HEADERS = {
|
|
24
16
|
// The backend uses the Accept header as a condition for considering an
|
|
25
17
|
// incoming request as a REST request.
|
|
26
18
|
//
|
|
27
19
|
// See: https://core.trac.wordpress.org/ticket/44534
|
|
28
|
-
Accept:
|
|
20
|
+
Accept: "application/json, */*;q=0.1"
|
|
29
21
|
};
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Default set of fetch option values which should be sent with every request
|
|
33
|
-
* unless explicitly provided through apiFetch options.
|
|
34
|
-
*/
|
|
35
22
|
const DEFAULT_OPTIONS = {
|
|
36
|
-
credentials:
|
|
23
|
+
credentials: "include"
|
|
37
24
|
};
|
|
38
|
-
const middlewares = [
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
*/
|
|
25
|
+
const middlewares = [
|
|
26
|
+
userLocaleMiddleware,
|
|
27
|
+
namespaceEndpointMiddleware,
|
|
28
|
+
httpV1Middleware,
|
|
29
|
+
fetchAllMiddleware
|
|
30
|
+
];
|
|
45
31
|
function registerMiddleware(middleware) {
|
|
46
32
|
middlewares.unshift(middleware);
|
|
47
33
|
}
|
|
48
|
-
const defaultFetchHandler = nextOptions => {
|
|
49
|
-
const {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
data,
|
|
53
|
-
parse = true,
|
|
54
|
-
...remainingOptions
|
|
55
|
-
} = nextOptions;
|
|
56
|
-
let {
|
|
57
|
-
body,
|
|
58
|
-
headers
|
|
59
|
-
} = nextOptions;
|
|
60
|
-
|
|
61
|
-
// Merge explicitly-provided headers with default values.
|
|
62
|
-
headers = {
|
|
63
|
-
...DEFAULT_HEADERS,
|
|
64
|
-
...headers
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
// The `data` property is a shorthand for sending a JSON body.
|
|
34
|
+
const defaultFetchHandler = (nextOptions) => {
|
|
35
|
+
const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
|
|
36
|
+
let { body, headers } = nextOptions;
|
|
37
|
+
headers = { ...DEFAULT_HEADERS, ...headers };
|
|
68
38
|
if (data) {
|
|
69
39
|
body = JSON.stringify(data);
|
|
70
|
-
headers[
|
|
40
|
+
headers["Content-Type"] = "application/json";
|
|
71
41
|
}
|
|
72
42
|
const responsePromise = globalThis.fetch(
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
return responsePromise.then(response => {
|
|
81
|
-
// If the response is not 2xx, still parse the response body as JSON
|
|
82
|
-
// but throw the JSON as error.
|
|
83
|
-
if (!response.ok) {
|
|
84
|
-
return parseAndThrowError(response, parse);
|
|
85
|
-
}
|
|
86
|
-
return parseResponseAndNormalizeError(response, parse);
|
|
87
|
-
}, err => {
|
|
88
|
-
// Re-throw AbortError for the users to handle it themselves.
|
|
89
|
-
if (err && err.name === 'AbortError') {
|
|
90
|
-
throw err;
|
|
43
|
+
// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
|
|
44
|
+
url || path || window.location.href,
|
|
45
|
+
{
|
|
46
|
+
...DEFAULT_OPTIONS,
|
|
47
|
+
...remainingOptions,
|
|
48
|
+
body,
|
|
49
|
+
headers
|
|
91
50
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
51
|
+
);
|
|
52
|
+
return responsePromise.then(
|
|
53
|
+
(response) => {
|
|
54
|
+
if (!response.ok) {
|
|
55
|
+
return parseAndThrowError(response, parse);
|
|
56
|
+
}
|
|
57
|
+
return parseResponseAndNormalizeError(response, parse);
|
|
58
|
+
},
|
|
59
|
+
(err) => {
|
|
60
|
+
if (err && err.name === "AbortError") {
|
|
61
|
+
throw err;
|
|
62
|
+
}
|
|
63
|
+
if (!globalThis.navigator.onLine) {
|
|
64
|
+
throw {
|
|
65
|
+
code: "offline_error",
|
|
66
|
+
message: __(
|
|
67
|
+
"Unable to connect. Please check your Internet connection."
|
|
68
|
+
)
|
|
69
|
+
};
|
|
70
|
+
}
|
|
96
71
|
throw {
|
|
97
|
-
code:
|
|
98
|
-
message: __(
|
|
72
|
+
code: "fetch_error",
|
|
73
|
+
message: __(
|
|
74
|
+
"Could not get a valid response from the server."
|
|
75
|
+
)
|
|
99
76
|
};
|
|
100
77
|
}
|
|
101
|
-
|
|
102
|
-
// Hard to diagnose further due to how Window.fetch reports errors.
|
|
103
|
-
throw {
|
|
104
|
-
code: 'fetch_error',
|
|
105
|
-
message: __('Could not get a valid response from the server.')
|
|
106
|
-
};
|
|
107
|
-
});
|
|
78
|
+
);
|
|
108
79
|
};
|
|
109
80
|
let fetchHandler = defaultFetchHandler;
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Defines a custom fetch handler for making the requests that will override
|
|
113
|
-
* the default one using window.fetch
|
|
114
|
-
*
|
|
115
|
-
* @param newFetchHandler The new fetch handler
|
|
116
|
-
*/
|
|
117
81
|
function setFetchHandler(newFetchHandler) {
|
|
118
82
|
fetchHandler = newFetchHandler;
|
|
119
83
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
// ```
|
|
130
|
-
// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
|
|
131
|
-
// ```
|
|
132
|
-
const enhancedHandler = middlewares.reduceRight((next, middleware) => {
|
|
133
|
-
return workingOptions => middleware(workingOptions, next);
|
|
134
|
-
}, fetchHandler);
|
|
135
|
-
return enhancedHandler(options).catch(error => {
|
|
136
|
-
if (error.code !== 'rest_cookie_invalid_nonce') {
|
|
84
|
+
const apiFetch = (options) => {
|
|
85
|
+
const enhancedHandler = middlewares.reduceRight(
|
|
86
|
+
(next, middleware) => {
|
|
87
|
+
return (workingOptions) => middleware(workingOptions, next);
|
|
88
|
+
},
|
|
89
|
+
fetchHandler
|
|
90
|
+
);
|
|
91
|
+
return enhancedHandler(options).catch((error) => {
|
|
92
|
+
if (error.code !== "rest_cookie_invalid_nonce") {
|
|
137
93
|
return Promise.reject(error);
|
|
138
94
|
}
|
|
139
|
-
|
|
140
|
-
// If the nonce is invalid, refresh it and try again.
|
|
141
|
-
return globalThis.fetch(apiFetch.nonceEndpoint).then(response => {
|
|
142
|
-
// If the nonce refresh fails, it means we failed to recover from the original
|
|
143
|
-
// `rest_cookie_invalid_nonce` error and that it's time to finally re-throw it.
|
|
95
|
+
return globalThis.fetch(apiFetch.nonceEndpoint).then((response) => {
|
|
144
96
|
if (!response.ok) {
|
|
145
97
|
return Promise.reject(error);
|
|
146
98
|
}
|
|
147
99
|
return response.text();
|
|
148
|
-
}).then(text => {
|
|
100
|
+
}).then((text) => {
|
|
149
101
|
apiFetch.nonceMiddleware.nonce = text;
|
|
150
102
|
return apiFetch(options);
|
|
151
103
|
});
|
|
@@ -159,6 +111,9 @@ apiFetch.createRootURLMiddleware = createRootURLMiddleware;
|
|
|
159
111
|
apiFetch.fetchAllMiddleware = fetchAllMiddleware;
|
|
160
112
|
apiFetch.mediaUploadMiddleware = mediaUploadMiddleware;
|
|
161
113
|
apiFetch.createThemePreviewMiddleware = createThemePreviewMiddleware;
|
|
162
|
-
|
|
163
|
-
export * from
|
|
164
|
-
|
|
114
|
+
var index_default = apiFetch;
|
|
115
|
+
export * from "./types";
|
|
116
|
+
export {
|
|
117
|
+
index_default as default
|
|
118
|
+
};
|
|
119
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{"version":3,"names":["__","createNonceMiddleware","createRootURLMiddleware","createPreloadingMiddleware","fetchAllMiddleware","namespaceEndpointMiddleware","httpV1Middleware","userLocaleMiddleware","mediaUploadMiddleware","createThemePreviewMiddleware","parseResponseAndNormalizeError","parseAndThrowError","DEFAULT_HEADERS","Accept","DEFAULT_OPTIONS","credentials","middlewares","registerMiddleware","middleware","unshift","defaultFetchHandler","nextOptions","url","path","data","parse","remainingOptions","body","headers","JSON","stringify","responsePromise","globalThis","fetch","window","location","href","then","response","ok","err","name","navigator","onLine","code","message","fetchHandler","setFetchHandler","newFetchHandler","apiFetch","options","enhancedHandler","reduceRight","next","workingOptions","catch","error","Promise","reject","nonceEndpoint","text","nonceMiddleware","nonce","use"],"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":"AAAA;AACA;AACA;AACA,SAASA,EAAE,QAAQ,iBAAiB;;AAEpC;AACA;AACA;AACA,OAAOC,qBAAqB,MAAM,qBAAqB;AACvD,OAAOC,uBAAuB,MAAM,wBAAwB;AAC5D,OAAOC,0BAA0B,MAAM,0BAA0B;AACjE,OAAOC,kBAAkB,MAAM,oCAAoC;AACnE,OAAOC,2BAA2B,MAAM,kCAAkC;AAC1E,OAAOC,gBAAgB,MAAM,uBAAuB;AACpD,OAAOC,oBAAoB,MAAM,2BAA2B;AAC5D,OAAOC,qBAAqB,MAAM,4BAA4B;AAC9D,OAAOC,4BAA4B,MAAM,6BAA6B;AACtE,SACCC,8BAA8B,EAC9BC,kBAAkB,QACZ,kBAAkB;AAOzB;AACA;AACA;AACA;AACA,MAAMC,eAA6C,GAAG;EACrD;EACA;EACA;EACA;EACAC,MAAM,EAAE;AACT,CAAC;;AAED;AACA;AACA;AACA;AACA,MAAMC,eAAgC,GAAG;EACxCC,WAAW,EAAE;AACd,CAAC;AAED,MAAMC,WAA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3B,CAAE,CAAC;EACL,CAAE,CAAC;AACJ,CAAC;AAEDD,QAAQ,CAACc,GAAG,GAAG9C,kBAAkB;AACjCgC,QAAQ,CAACF,eAAe,GAAGA,eAAe;AAE1CE,QAAQ,CAAChD,qBAAqB,GAAGA,qBAAqB;AACtDgD,QAAQ,CAAC9C,0BAA0B,GAAGA,0BAA0B;AAChE8C,QAAQ,CAAC/C,uBAAuB,GAAGA,uBAAuB;AAC1D+C,QAAQ,CAAC7C,kBAAkB,GAAGA,kBAAkB;AAChD6C,QAAQ,CAACzC,qBAAqB,GAAGA,qBAAqB;AACtDyC,QAAQ,CAACxC,4BAA4B,GAAGA,4BAA4B;AAEpE,eAAewC,QAAQ;AACvB,cAAc,SAAS","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;\n\nexport default apiFetch;\nexport * from './types';\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,UAAU;AAKnB,OAAO,2BAA2B;AAClC,OAAO,6BAA6B;AACpC,OAAO,gCAAgC;AACvC,OAAO,wBAAwB;AAC/B,OAAO,iCAAiC;AACxC,OAAO,sBAAsB;AAC7B,OAAO,0BAA0B;AACjC,OAAO,2BAA2B;AAClC,OAAO,kCAAkC;AACzC;AAAA,EACC;AAAA,EACA;AAAA,OACM;AAWP,MAAM,kBAAgD;AAAA;AAAA;AAAA;AAAA;AAAA,EAKrD,QAAQ;AACT;AAMA,MAAM,kBAAmC;AAAA,E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E,mBAAoB,WAAY,gBAAgB,IAAK;AAAA,IAC/D;AAAA,IACA;AAAA,EACD;AAEA,SAAO,gBAAiB,OAAQ,EAAE,MAAO,CAAE,UAAW;AACrD,QAAK,MAAM,SAAS,6BAA8B;AACjD,aAAO,QAAQ,OAAQ,KAAM;AAAA,IAC9B;AAGA,WAAO,WACL,MAAO,SAAS,aAAe,EAC/B,KAAM,CAAE,aAAc;AAGtB,UAAK,CAAE,SAAS,IAAK;AACpB,eAAO,QAAQ,OAAQ,KAAM;AAAA,MAC9B;AAEA,aAAO,SAAS,KAAK;AAAA,IACtB,CAAE,EACD,KAAM,CAAE,SAAU;AAClB,eAAS,gBAAiB,QAAQ;AAClC,aAAO,SAAU,OAAQ;AAAA,IAC1B,CAAE;AAAA,EACJ,CAAE;AACH;AAEA,SAAS,MAAM;AACf,SAAS,kBAAkB;AAE3B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,wBAAwB;AACjC,SAAS,+BAA+B;AAExC,IAAO,gBAAQ;AACf,cAAc;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,42 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import { addQueryArgs } from '@wordpress/url';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Internal dependencies
|
|
8
|
-
*/
|
|
9
|
-
import apiFetch from '..';
|
|
10
|
-
/**
|
|
11
|
-
* Apply query arguments to both URL and Path, whichever is present.
|
|
12
|
-
*
|
|
13
|
-
* @param {APIFetchOptions} props The request options
|
|
14
|
-
* @param {Record< string, string | number >} queryArgs
|
|
15
|
-
* @return The request with the modified query args
|
|
16
|
-
*/
|
|
17
|
-
const modifyQuery = ({
|
|
18
|
-
path,
|
|
19
|
-
url,
|
|
20
|
-
...options
|
|
21
|
-
}, queryArgs) => ({
|
|
1
|
+
import { addQueryArgs } from "@wordpress/url";
|
|
2
|
+
import apiFetch from "..";
|
|
3
|
+
const modifyQuery = ({ path, url, ...options }, queryArgs) => ({
|
|
22
4
|
...options,
|
|
23
5
|
url: url && addQueryArgs(url, queryArgs),
|
|
24
6
|
path: path && addQueryArgs(path, queryArgs)
|
|
25
7
|
});
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
* Duplicates parsing functionality from apiFetch.
|
|
29
|
-
*
|
|
30
|
-
* @param response
|
|
31
|
-
* @return Parsed response json.
|
|
32
|
-
*/
|
|
33
|
-
const parseResponse = response => response.json ? response.json() : Promise.reject(response);
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* @param linkHeader
|
|
37
|
-
* @return The parsed link header.
|
|
38
|
-
*/
|
|
39
|
-
const parseLinkHeader = linkHeader => {
|
|
8
|
+
const parseResponse = (response) => response.json ? response.json() : Promise.reject(response);
|
|
9
|
+
const parseLinkHeader = (linkHeader) => {
|
|
40
10
|
if (!linkHeader) {
|
|
41
11
|
return {};
|
|
42
12
|
}
|
|
@@ -45,46 +15,22 @@ const parseLinkHeader = linkHeader => {
|
|
|
45
15
|
next: match[1]
|
|
46
16
|
} : {};
|
|
47
17
|
};
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
* @param response
|
|
51
|
-
* @return The next page URL.
|
|
52
|
-
*/
|
|
53
|
-
const getNextPageUrl = response => {
|
|
54
|
-
const {
|
|
55
|
-
next
|
|
56
|
-
} = parseLinkHeader(response.headers.get('link'));
|
|
18
|
+
const getNextPageUrl = (response) => {
|
|
19
|
+
const { next } = parseLinkHeader(response.headers.get("link"));
|
|
57
20
|
return next;
|
|
58
21
|
};
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
* @return True if the request contains an unbounded query.
|
|
63
|
-
*/
|
|
64
|
-
const requestContainsUnboundedQuery = options => {
|
|
65
|
-
const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
|
|
66
|
-
const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
|
|
22
|
+
const requestContainsUnboundedQuery = (options) => {
|
|
23
|
+
const pathIsUnbounded = !!options.path && options.path.indexOf("per_page=-1") !== -1;
|
|
24
|
+
const urlIsUnbounded = !!options.url && options.url.indexOf("per_page=-1") !== -1;
|
|
67
25
|
return pathIsUnbounded || urlIsUnbounded;
|
|
68
26
|
};
|
|
69
|
-
|
|
70
|
-
/**
|
|
71
|
-
* The REST API enforces an upper limit on the per_page option. To handle large
|
|
72
|
-
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
|
|
73
|
-
* then recursively assemble a full response array from all available pages.
|
|
74
|
-
* @param options
|
|
75
|
-
* @param next
|
|
76
|
-
*/
|
|
77
27
|
const fetchAllMiddleware = async (options, next) => {
|
|
78
28
|
if (options.parse === false) {
|
|
79
|
-
// If a consumer has opted out of parsing, do not apply middleware.
|
|
80
29
|
return next(options);
|
|
81
30
|
}
|
|
82
31
|
if (!requestContainsUnboundedQuery(options)) {
|
|
83
|
-
// If neither url nor path is requesting all items, do not apply middleware.
|
|
84
32
|
return next(options);
|
|
85
33
|
}
|
|
86
|
-
|
|
87
|
-
// Retrieve requested page of results.
|
|
88
34
|
const response = await apiFetch({
|
|
89
35
|
...modifyQuery(options, {
|
|
90
36
|
per_page: 100
|
|
@@ -94,22 +40,18 @@ const fetchAllMiddleware = async (options, next) => {
|
|
|
94
40
|
});
|
|
95
41
|
const results = await parseResponse(response);
|
|
96
42
|
if (!Array.isArray(results)) {
|
|
97
|
-
// We have no reliable way of merging non-array results.
|
|
98
43
|
return results;
|
|
99
44
|
}
|
|
100
45
|
let nextPage = getNextPageUrl(response);
|
|
101
46
|
if (!nextPage) {
|
|
102
|
-
// There are no further pages to request.
|
|
103
47
|
return results;
|
|
104
48
|
}
|
|
105
|
-
|
|
106
|
-
// Iteratively fetch all remaining pages until no "next" header is found.
|
|
107
49
|
let mergedResults = [].concat(results);
|
|
108
50
|
while (nextPage) {
|
|
109
51
|
const nextResponse = await apiFetch({
|
|
110
52
|
...options,
|
|
111
53
|
// Ensure the URL for the next page is used instead of any provided path.
|
|
112
|
-
path:
|
|
54
|
+
path: void 0,
|
|
113
55
|
url: nextPage,
|
|
114
56
|
// Ensure we still get headers so we can identify the next page.
|
|
115
57
|
parse: false
|
|
@@ -120,5 +62,8 @@ const fetchAllMiddleware = async (options, next) => {
|
|
|
120
62
|
}
|
|
121
63
|
return mergedResults;
|
|
122
64
|
};
|
|
123
|
-
|
|
124
|
-
|
|
65
|
+
var fetch_all_middleware_default = fetchAllMiddleware;
|
|
66
|
+
export {
|
|
67
|
+
fetch_all_middleware_default as default
|
|
68
|
+
};
|
|
69
|
+
//# sourceMappingURL=fetch-all-middleware.js.map
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
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": "AAGA,SAAS,oBAAoB;AAK7B,OAAO,cAAc;AAUrB,MAAM,cAAc,CACnB,EAAE,MAAM,KAAK,GAAG,QAAQ,GACxB,eACuB;AAAA,EACvB,GAAG;AAAA,EACH,KAAK,OAAO,aAAc,KAAK,SAAU;AAAA,EACzC,MAAM,QAAQ,aAAc,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,MAAM,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,MAAM,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": []
|
|
7
|
+
}
|
|
@@ -1,45 +1,22 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Set of HTTP methods which are eligible to be overridden.
|
|
7
|
-
*/
|
|
8
|
-
const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Default request method.
|
|
12
|
-
*
|
|
13
|
-
* "A request has an associated method (a method). Unless stated otherwise it
|
|
14
|
-
* is `GET`."
|
|
15
|
-
*
|
|
16
|
-
* @see https://fetch.spec.whatwg.org/#requests
|
|
17
|
-
*/
|
|
18
|
-
const DEFAULT_METHOD = 'GET';
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* API Fetch middleware which overrides the request method for HTTP v1
|
|
22
|
-
* compatibility leveraging the REST API X-HTTP-Method-Override header.
|
|
23
|
-
*
|
|
24
|
-
* @param options
|
|
25
|
-
* @param next
|
|
26
|
-
*/
|
|
1
|
+
const OVERRIDE_METHODS = /* @__PURE__ */ new Set(["PATCH", "PUT", "DELETE"]);
|
|
2
|
+
const DEFAULT_METHOD = "GET";
|
|
27
3
|
const httpV1Middleware = (options, next) => {
|
|
28
|
-
const {
|
|
29
|
-
method = DEFAULT_METHOD
|
|
30
|
-
} = options;
|
|
4
|
+
const { method = DEFAULT_METHOD } = options;
|
|
31
5
|
if (OVERRIDE_METHODS.has(method.toUpperCase())) {
|
|
32
6
|
options = {
|
|
33
7
|
...options,
|
|
34
8
|
headers: {
|
|
35
9
|
...options.headers,
|
|
36
|
-
|
|
37
|
-
|
|
10
|
+
"X-HTTP-Method-Override": method,
|
|
11
|
+
"Content-Type": "application/json"
|
|
38
12
|
},
|
|
39
|
-
method:
|
|
13
|
+
method: "POST"
|
|
40
14
|
};
|
|
41
15
|
}
|
|
42
16
|
return next(options);
|
|
43
17
|
};
|
|
44
|
-
|
|
45
|
-
|
|
18
|
+
var http_v1_default = httpV1Middleware;
|
|
19
|
+
export {
|
|
20
|
+
http_v1_default as default
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=http-v1.js.map
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/middlewares/http-v1.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Internal dependencies\n */\nimport type { APIFetchMiddleware } from '../types';\n\n/**\n * Set of HTTP methods which are eligible to be overridden.\n */\nconst OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] );\n\n/**\n * Default request method.\n *\n * \"A request has an associated method (a method). Unless stated otherwise it\n * is `GET`.\"\n *\n * @see https://fetch.spec.whatwg.org/#requests\n */\nconst DEFAULT_METHOD = 'GET';\n\n/**\n * API Fetch middleware which overrides the request method for HTTP v1\n * compatibility leveraging the REST API X-HTTP-Method-Override header.\n *\n * @param options\n * @param next\n */\nconst httpV1Middleware: APIFetchMiddleware = ( options, next ) => {\n\tconst { method = DEFAULT_METHOD } = options;\n\tif ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) {\n\t\toptions = {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...options.headers,\n\t\t\t\t'X-HTTP-Method-Override': method,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t},\n\t\t\tmethod: 'POST',\n\t\t};\n\t}\n\n\treturn next( options );\n};\n\nexport default httpV1Middleware;\n"],
|
|
5
|
+
"mappings": "AAQA,MAAM,mBAAmB,oBAAI,IAAK,CAAE,SAAS,OAAO,QAAS,CAAE;AAU/D,MAAM,iBAAiB;AASvB,MAAM,mBAAuC,CAAE,SAAS,SAAU;AACjE,QAAM,EAAE,SAAS,eAAe,IAAI;AACpC,MAAK,iBAAiB,IAAK,OAAO,YAAY,CAAE,GAAI;AACnD,cAAU;AAAA,MACT,GAAG;AAAA,MACH,SAAS;AAAA,QACR,GAAG,QAAQ;AAAA,QACX,0BAA0B;AAAA,QAC1B,gBAAgB;AAAA,MACjB;AAAA,MACA,QAAQ;AAAA,IACT;AAAA,EACD;AAEA,SAAO,KAAM,OAAQ;AACtB;AAEA,IAAO,kBAAQ;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,46 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Internal dependencies
|
|
8
|
-
*/
|
|
9
|
-
import { parseAndThrowError, parseResponseAndNormalizeError } from '../utils/response';
|
|
10
|
-
/**
|
|
11
|
-
* @param options
|
|
12
|
-
* @return True if the request is for media upload.
|
|
13
|
-
*/
|
|
1
|
+
import { __ } from "@wordpress/i18n";
|
|
2
|
+
import {
|
|
3
|
+
parseAndThrowError,
|
|
4
|
+
parseResponseAndNormalizeError
|
|
5
|
+
} from "../utils/response";
|
|
14
6
|
function isMediaUploadRequest(options) {
|
|
15
|
-
const isCreateMethod = !!options.method && options.method ===
|
|
16
|
-
const isMediaEndpoint = !!options.path && options.path.indexOf(
|
|
7
|
+
const isCreateMethod = !!options.method && options.method === "POST";
|
|
8
|
+
const isMediaEndpoint = !!options.path && options.path.indexOf("/wp/v2/media") !== -1 || !!options.url && options.url.indexOf("/wp/v2/media") !== -1;
|
|
17
9
|
return isMediaEndpoint && isCreateMethod;
|
|
18
10
|
}
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Middleware handling media upload failures and retries.
|
|
22
|
-
* @param options
|
|
23
|
-
* @param next
|
|
24
|
-
*/
|
|
25
11
|
const mediaUploadMiddleware = (options, next) => {
|
|
26
12
|
if (!isMediaUploadRequest(options)) {
|
|
27
13
|
return next(options);
|
|
28
14
|
}
|
|
29
15
|
let retries = 0;
|
|
30
16
|
const maxRetries = 5;
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* @param attachmentId
|
|
34
|
-
* @return Processed post response.
|
|
35
|
-
*/
|
|
36
|
-
const postProcess = attachmentId => {
|
|
17
|
+
const postProcess = (attachmentId) => {
|
|
37
18
|
retries++;
|
|
38
19
|
return next({
|
|
39
20
|
path: `/wp/v2/media/${attachmentId}/post-process`,
|
|
40
|
-
method:
|
|
41
|
-
data: {
|
|
42
|
-
action: 'create-image-subsizes'
|
|
43
|
-
},
|
|
21
|
+
method: "POST",
|
|
22
|
+
data: { action: "create-image-subsizes" },
|
|
44
23
|
parse: false
|
|
45
24
|
}).catch(() => {
|
|
46
25
|
if (retries < maxRetries) {
|
|
@@ -48,33 +27,38 @@ const mediaUploadMiddleware = (options, next) => {
|
|
|
48
27
|
}
|
|
49
28
|
next({
|
|
50
29
|
path: `/wp/v2/media/${attachmentId}?force=true`,
|
|
51
|
-
method:
|
|
30
|
+
method: "DELETE"
|
|
52
31
|
});
|
|
53
32
|
return Promise.reject();
|
|
54
33
|
});
|
|
55
34
|
};
|
|
56
|
-
return next({
|
|
57
|
-
...options,
|
|
58
|
-
parse: false
|
|
59
|
-
}).catch(response => {
|
|
60
|
-
// `response` could actually be an error thrown by `defaultFetchHandler`.
|
|
35
|
+
return next({ ...options, parse: false }).catch((response) => {
|
|
61
36
|
if (!(response instanceof globalThis.Response)) {
|
|
62
37
|
return Promise.reject(response);
|
|
63
38
|
}
|
|
64
|
-
const attachmentId = response.headers.get(
|
|
39
|
+
const attachmentId = response.headers.get(
|
|
40
|
+
"x-wp-upload-attachment-id"
|
|
41
|
+
);
|
|
65
42
|
if (response.status >= 500 && response.status < 600 && attachmentId) {
|
|
66
43
|
return postProcess(attachmentId).catch(() => {
|
|
67
44
|
if (options.parse !== false) {
|
|
68
45
|
return Promise.reject({
|
|
69
|
-
code:
|
|
70
|
-
message: __(
|
|
46
|
+
code: "post_process",
|
|
47
|
+
message: __(
|
|
48
|
+
"Media upload failed. If this is a photo or a large image, please scale it down and try again."
|
|
49
|
+
)
|
|
71
50
|
});
|
|
72
51
|
}
|
|
73
52
|
return Promise.reject(response);
|
|
74
53
|
});
|
|
75
54
|
}
|
|
76
55
|
return parseAndThrowError(response, options.parse);
|
|
77
|
-
}).then(
|
|
56
|
+
}).then(
|
|
57
|
+
(response) => parseResponseAndNormalizeError(response, options.parse)
|
|
58
|
+
);
|
|
78
59
|
};
|
|
79
|
-
|
|
80
|
-
|
|
60
|
+
var media_upload_default = mediaUploadMiddleware;
|
|
61
|
+
export {
|
|
62
|
+
media_upload_default as default
|
|
63
|
+
};
|
|
64
|
+
//# sourceMappingURL=media-upload.js.map
|