Spaces:
Configuration error
Configuration error
Lee Thanh
commited on
Commit
•
5641073
1
Parent(s):
174012d
Upload 3012 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +2 -0
- index.js +27 -0
- node_modules/@cloudflare/kv-asset-handler/LICENSE_APACHE +176 -0
- node_modules/@cloudflare/kv-asset-handler/LICENSE_MIT +25 -0
- node_modules/@cloudflare/kv-asset-handler/README.md +329 -0
- node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts +36 -0
- node_modules/@cloudflare/kv-asset-handler/dist/index.js +267 -0
- node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts +14 -0
- node_modules/@cloudflare/kv-asset-handler/dist/mocks.js +146 -0
- node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.d.ts +1 -0
- node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.js +22 -0
- node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +1 -0
- node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +446 -0
- node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +1 -0
- node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +34 -0
- node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +1 -0
- node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +34 -0
- node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts +28 -0
- node_modules/@cloudflare/kv-asset-handler/dist/types.js +31 -0
- node_modules/@cloudflare/kv-asset-handler/package.json +52 -0
- node_modules/@cloudflare/kv-asset-handler/src/index.ts +312 -0
- node_modules/@cloudflare/kv-asset-handler/src/mocks.ts +148 -0
- node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV-optional.ts +24 -0
- node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +488 -0
- node_modules/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +37 -0
- node_modules/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +44 -0
- node_modules/@cloudflare/kv-asset-handler/src/types.ts +43 -0
- node_modules/@cloudflare/workerd-linux-64/README.md +6 -0
- node_modules/@cloudflare/workerd-linux-64/bin/workerd +3 -0
- node_modules/@cloudflare/workerd-linux-64/package.json +17 -0
- node_modules/@cypress/request-promise/.circleci/config.yml +46 -0
- node_modules/@cypress/request-promise/LICENSE +15 -0
- node_modules/@cypress/request-promise/README.md +760 -0
- node_modules/@cypress/request-promise/errors.js +3 -0
- node_modules/@cypress/request-promise/lib/rp.js +52 -0
- node_modules/@cypress/request-promise/package.json +61 -0
- node_modules/@cypress/request/LICENSE +55 -0
- node_modules/@cypress/request/README.md +1032 -0
- node_modules/@cypress/request/index.js +155 -0
- node_modules/@cypress/request/lib/auth.js +167 -0
- node_modules/@cypress/request/lib/cookies.js +38 -0
- node_modules/@cypress/request/lib/getProxyFromURI.js +79 -0
- node_modules/@cypress/request/lib/har.js +200 -0
- node_modules/@cypress/request/lib/hawk.js +89 -0
- node_modules/@cypress/request/lib/helpers.js +66 -0
- node_modules/@cypress/request/lib/multipart.js +112 -0
- node_modules/@cypress/request/lib/querystring.js +50 -0
- node_modules/@cypress/request/lib/redirect.js +179 -0
- node_modules/@cypress/request/lib/tunnel.js +175 -0
- node_modules/@cypress/request/package.json +84 -0
.gitattributes
CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
node_modules/@cloudflare/workerd-linux-64/bin/workerd filter=lfs diff=lfs merge=lfs -text
|
37 |
+
node_modules/workerd/bin/workerd filter=lfs diff=lfs merge=lfs -text
|
index.js
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const TelegramBot = require('node-telegram-bot-api');
|
2 |
+
const axios = require('axios');
|
3 |
+
|
4 |
+
const telegramToken = '6610438736:AAFNPlGGY_SfuINu3dXThuyMFSOkoy1BpAg';
|
5 |
+
const cloudflareToken = 'NB-sxyNA3JSyhezy2fUnTnXc3Pf7i8X17BJfBwLx';
|
6 |
+
|
7 |
+
const bot = new TelegramBot(telegramToken, {polling: true});
|
8 |
+
|
9 |
+
console.log('Loaded success..')
|
10 |
+
|
11 |
+
bot.on('message', (msg) => {
|
12 |
+
const chatId = msg.chat.id;
|
13 |
+
const userMessage = msg.text;
|
14 |
+
|
15 |
+
axios.post('https://api.cloudflare.com/client/v4/accounts/d888e02cee618e93b19cd9e7717da715/ai/run/@cf/meta/llama-2-7b-chat-int8', {
|
16 |
+
prompt: userMessage
|
17 |
+
}, {
|
18 |
+
headers: {
|
19 |
+
'Authorization': `Bearer ${cloudflareToken}`
|
20 |
+
}
|
21 |
+
}).then(response => {
|
22 |
+
const aiResponse = response.data.result.response;
|
23 |
+
bot.sendMessage(chatId, aiResponse);
|
24 |
+
}).catch(error => {
|
25 |
+
console.error(error);
|
26 |
+
});
|
27 |
+
});
|
node_modules/@cloudflare/kv-asset-handler/LICENSE_APACHE
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
node_modules/@cloudflare/kv-asset-handler/LICENSE_MIT
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2018 Ashley Williams <[email protected]>
|
2 |
+
|
3 |
+
Permission is hereby granted, free of charge, to any
|
4 |
+
person obtaining a copy of this software and associated
|
5 |
+
documentation files (the "Software"), to deal in the
|
6 |
+
Software without restriction, including without
|
7 |
+
limitation the rights to use, copy, modify, merge,
|
8 |
+
publish, distribute, sublicense, and/or sell copies of
|
9 |
+
the Software, and to permit persons to whom the Software
|
10 |
+
is furnished to do so, subject to the following
|
11 |
+
conditions:
|
12 |
+
|
13 |
+
The above copyright notice and this permission notice
|
14 |
+
shall be included in all copies or substantial portions
|
15 |
+
of the Software.
|
16 |
+
|
17 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
18 |
+
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
19 |
+
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
20 |
+
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
21 |
+
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
22 |
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
23 |
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
24 |
+
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
25 |
+
DEALINGS IN THE SOFTWARE.
|
node_modules/@cloudflare/kv-asset-handler/README.md
ADDED
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# @cloudflare/kv-asset-handler
|
2 |
+
|
3 |
+
[![npm](https://img.shields.io/npm/v/@cloudflare/kv-asset-handler.svg)](https://www.npmjs.com/package/@cloudflare/kv-asset-handler)
|
4 |
+
[![Run npm tests](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/test.yml)
|
5 |
+
[![Lint Markdown](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml/badge.svg)](https://github.com/cloudflare/kv-asset-handler/actions/workflows/lint.yml)
|
6 |
+
|
7 |
+
`kv-asset-handler` is an open-source library for managing the retrieval of static assets from [Workers KV](https://developers.cloudflare.com/workers/runtime-apis/kv) inside of a [Cloudflare Workers](https://workers.dev) function. `kv-asset-handler` is designed for use with [Workers Sites](https://developers.cloudflare.com/workers/platform/sites), a feature included in [Wrangler](https://github.com/cloudflare/wrangler), our command-line tool for deploying Workers projects.
|
8 |
+
|
9 |
+
`kv-asset-handler` runs as part of a Cloudflare Workers function, so it allows you to customize _how_ and _when_ your static assets are loaded, as well as customize how those assets behave before they're sent to the client.
|
10 |
+
|
11 |
+
Most users and sites will not need these customizations, and just want to serve their statically built applications. For that simple use-case, you can check out [Cloudflare Pages](https://pages.cloudflare.com), our batteries-included approach to deploying static sites on Cloudflare's edge network. Workers Sites was designed as a precursor to Cloudflare Pages, so check out Pages if you just want to deploy your static site without any special customizations!
|
12 |
+
|
13 |
+
For users who _do_ want to customize their assets, and want to build complex experiences on top of their static assets, `kv-asset-handler` (and the default [Workers Sites template](https://github.com/cloudflare/worker-sites-template), which is provided for use with Wrangler + Workers Sites) allows you to customize caching behavior, headers, and anything else about how your Workers function loads the static assets for your site stored in Workers KV.
|
14 |
+
|
15 |
+
The Cloudflare Workers Discord server is an active place where Workers users get help, share feedback, and collaborate on making our platform better. The `#workers-sites` channel in particular is a great place to chat about `kv-asset-handler`, and building cool experiences for your users using these tools! If you have questions, want to share what you're working on, or give feedback, [join us in Discord and say hello](https://discord.gg/cloudflaredev)!
|
16 |
+
|
17 |
+
- [Installation](#installation)
|
18 |
+
- [Usage](#usage)
|
19 |
+
- [`getAssetFromKV`](#-getassetfromkv)
|
20 |
+
- [Example](#example)
|
21 |
+
* [Return](#return)
|
22 |
+
* [Optional Arguments](#optional-arguments)
|
23 |
+
- [`mapRequestToAsset`](#-maprequesttoasset)
|
24 |
+
- [Example](#example-1)
|
25 |
+
- [`cacheControl`](#-cachecontrol)
|
26 |
+
- [`browserTTL`](#browserttl)
|
27 |
+
- [`edgeTTL`](#edgettl)
|
28 |
+
- [`bypassCache`](#bypasscache)
|
29 |
+
- [`ASSET_NAMESPACE` (required for ES Modules)](#asset_namespace-required-for-es-modules)
|
30 |
+
- [`ASSET_MANIFEST` (required for ES Modules)](#asset_manifest-required-for-es-modules)
|
31 |
+
|
32 |
+
* [Helper functions](#helper-functions)
|
33 |
+
- [`mapRequestToAsset`](#maprequesttoasset-1)
|
34 |
+
- [`serveSinglePageApp`](#servesinglepageapp)
|
35 |
+
* [Cache revalidation and etags](#cache-revalidation-and-etags)
|
36 |
+
|
37 |
+
## Installation
|
38 |
+
|
39 |
+
Add this package to your `package.json` by running this in the root of your
|
40 |
+
project's directory:
|
41 |
+
|
42 |
+
```
|
43 |
+
npm i @cloudflare/kv-asset-handler
|
44 |
+
```
|
45 |
+
|
46 |
+
## Usage
|
47 |
+
|
48 |
+
This package was designed to work with [Worker Sites](https://workers.cloudflare.com/sites).
|
49 |
+
|
50 |
+
## `getAssetFromKV`
|
51 |
+
|
52 |
+
getAssetFromKV(Evt) => Promise<Response>
|
53 |
+
|
54 |
+
`getAssetFromKV` is an async function that takes an `Evt` object (containing a `Request` and a [`waitUntil`](https://developers.cloudflare.com/workers/runtime-apis/fetch-event#waituntil)) and returns a `Response` object if the request matches an asset in KV, otherwise it will throw a `KVError`.
|
55 |
+
|
56 |
+
#### Example
|
57 |
+
|
58 |
+
This example checks for the existence of a value in KV, and returns it if it's there, and returns a 404 if it is not. It also serves index.html from `/`.
|
59 |
+
|
60 |
+
### Return
|
61 |
+
|
62 |
+
`getAssetFromKV` returns a `Promise<Response>` with `Response` being the body of the asset requested.
|
63 |
+
|
64 |
+
Known errors to be thrown are:
|
65 |
+
|
66 |
+
- MethodNotAllowedError
|
67 |
+
- NotFoundError
|
68 |
+
- InternalError
|
69 |
+
|
70 |
+
#### ES Modules
|
71 |
+
|
72 |
+
```js
|
73 |
+
import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler'
|
74 |
+
import manifestJSON from '__STATIC_CONTENT_MANIFEST'
|
75 |
+
const assetManifest = JSON.parse(manifestJSON)
|
76 |
+
|
77 |
+
export default {
|
78 |
+
async fetch(request, env, ctx) {
|
79 |
+
if (request.url.includes('/docs')) {
|
80 |
+
try {
|
81 |
+
return await getAssetFromKV(
|
82 |
+
{
|
83 |
+
request,
|
84 |
+
waitUntil(promise) {
|
85 |
+
return ctx.waitUntil(promise)
|
86 |
+
},
|
87 |
+
},
|
88 |
+
{
|
89 |
+
ASSET_NAMESPACE: env.__STATIC_CONTENT,
|
90 |
+
ASSET_MANIFEST: assetManifest,
|
91 |
+
},
|
92 |
+
)
|
93 |
+
} catch (e) {
|
94 |
+
if (e instanceof NotFoundError) {
|
95 |
+
// ...
|
96 |
+
} else if (e instanceof MethodNotAllowedError) {
|
97 |
+
// ...
|
98 |
+
} else {
|
99 |
+
return new Response('An unexpected error occurred', { status: 500 })
|
100 |
+
}
|
101 |
+
}
|
102 |
+
} else return fetch(request)
|
103 |
+
},
|
104 |
+
}
|
105 |
+
```
|
106 |
+
|
107 |
+
#### Service Worker
|
108 |
+
|
109 |
+
```js
|
110 |
+
import { getAssetFromKV, NotFoundError, MethodNotAllowedError } from '@cloudflare/kv-asset-handler'
|
111 |
+
|
112 |
+
addEventListener('fetch', (event) => {
|
113 |
+
event.respondWith(handleEvent(event))
|
114 |
+
})
|
115 |
+
|
116 |
+
async function handleEvent(event) {
|
117 |
+
if (event.request.url.includes('/docs')) {
|
118 |
+
try {
|
119 |
+
return await getAssetFromKV(event)
|
120 |
+
} catch (e) {
|
121 |
+
if (e instanceof NotFoundError) {
|
122 |
+
// ...
|
123 |
+
} else if (e instanceof MethodNotAllowedError) {
|
124 |
+
// ...
|
125 |
+
} else {
|
126 |
+
return new Response('An unexpected error occurred', { status: 500 })
|
127 |
+
}
|
128 |
+
}
|
129 |
+
} else return fetch(event.request)
|
130 |
+
}
|
131 |
+
```
|
132 |
+
|
133 |
+
### Optional Arguments
|
134 |
+
|
135 |
+
You can customize the behavior of `getAssetFromKV` by passing the following properties as an object into the second argument.
|
136 |
+
|
137 |
+
```
|
138 |
+
getAssetFromKV(event, { mapRequestToAsset: ... })
|
139 |
+
```
|
140 |
+
|
141 |
+
#### `mapRequestToAsset`
|
142 |
+
|
143 |
+
mapRequestToAsset(Request) => Request
|
144 |
+
|
145 |
+
Maps the incoming request to the value that will be looked up in Cloudflare's KV
|
146 |
+
|
147 |
+
By default, mapRequestToAsset is set to the exported function [`mapRequestToAsset`](#maprequesttoasset-1). This works for most static site generators, but you can customize this behavior by passing your own function as `mapRequestToAsset`. The function should take a `Request` object as its only argument, and return a new `Request` object with an updated path to be looked up in the asset manifest/KV.
|
148 |
+
|
149 |
+
For SPA mapping pass in the [`serveSinglePageApp`](#servesinglepageapp) function
|
150 |
+
|
151 |
+
#### Example
|
152 |
+
|
153 |
+
Strip `/docs` from any incoming request before looking up an asset in Cloudflare's KV.
|
154 |
+
|
155 |
+
```js
|
156 |
+
import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler'
|
157 |
+
...
|
158 |
+
const customKeyModifier = request => {
|
159 |
+
let url = request.url
|
160 |
+
//custom key mapping optional
|
161 |
+
url = url.replace('/docs', '').replace(/^\/+/, '')
|
162 |
+
return mapRequestToAsset(new Request(url, request))
|
163 |
+
}
|
164 |
+
let asset = await getAssetFromKV(event, { mapRequestToAsset: customKeyModifier })
|
165 |
+
```
|
166 |
+
|
167 |
+
#### `cacheControl`
|
168 |
+
|
169 |
+
type: object
|
170 |
+
|
171 |
+
`cacheControl` allows you to configure options for both the Cloudflare Cache accessed by your Worker, and the browser cache headers sent along with your Workers' responses. The default values are as follows:
|
172 |
+
|
173 |
+
```javascript
|
174 |
+
let cacheControl = {
|
175 |
+
browserTTL: null, // do not set cache control ttl on responses
|
176 |
+
edgeTTL: 2 * 60 * 60 * 24, // 2 days
|
177 |
+
bypassCache: false, // do not bypass Cloudflare's cache
|
178 |
+
}
|
179 |
+
```
|
180 |
+
|
181 |
+
##### `browserTTL`
|
182 |
+
|
183 |
+
type: number | null
|
184 |
+
nullable: true
|
185 |
+
|
186 |
+
Sets the `Cache-Control: max-age` header on the response returned from the Worker. By default set to `null` which will not add the header at all.
|
187 |
+
|
188 |
+
##### `edgeTTL`
|
189 |
+
|
190 |
+
type: number | null
|
191 |
+
nullable: true
|
192 |
+
|
193 |
+
Sets the `Cache-Control: max-age` header on the response used as the edge cache key. By default set to 2 days (`2 * 60 * 60 * 24`). When null will not cache on the edge at all.
|
194 |
+
|
195 |
+
##### `bypassCache`
|
196 |
+
|
197 |
+
type: boolean
|
198 |
+
|
199 |
+
Determines whether to cache requests on Cloudflare's edge cache. By default set to `false` (recommended for production builds). Useful for development when you need to eliminate the cache's effect on testing.
|
200 |
+
|
201 |
+
#### `ASSET_NAMESPACE` (required for ES Modules)
|
202 |
+
|
203 |
+
type: KV Namespace Binding
|
204 |
+
|
205 |
+
The binding name to the KV Namespace populated with key/value entries of files for the Worker to serve. By default, Workers Sites uses a [binding to a Workers KV Namespace](https://developers.cloudflare.com/workers/reference/storage/api/#namespaces) named `__STATIC_CONTENT`.
|
206 |
+
|
207 |
+
It is further assumed that this namespace consists of static assets such as HTML, CSS, JavaScript, or image files, keyed off of a relative path that roughly matches the assumed URL pathname of the incoming request.
|
208 |
+
|
209 |
+
In ES Modules format, this argument is required, and can be gotten from `env`.
|
210 |
+
|
211 |
+
##### ES Module
|
212 |
+
|
213 |
+
```js
|
214 |
+
return getAssetFromKV(
|
215 |
+
{
|
216 |
+
request,
|
217 |
+
waitUntil(promise) {
|
218 |
+
return ctx.waitUntil(promise)
|
219 |
+
},
|
220 |
+
},
|
221 |
+
{
|
222 |
+
ASSET_NAMESPACE: env.__STATIC_CONTENT,
|
223 |
+
},
|
224 |
+
)
|
225 |
+
```
|
226 |
+
|
227 |
+
##### Service Worker
|
228 |
+
|
229 |
+
```
|
230 |
+
return getAssetFromKV(event, { ASSET_NAMESPACE: MY_NAMESPACE })
|
231 |
+
```
|
232 |
+
|
233 |
+
#### `ASSET_MANIFEST` (required for ES Modules)
|
234 |
+
|
235 |
+
type: text blob (JSON formatted) or object
|
236 |
+
|
237 |
+
The mapping of requested file path to the key stored on Cloudflare.
|
238 |
+
|
239 |
+
Workers Sites with Wrangler bundles up a text blob that maps request paths to content-hashed keys that are generated by Wrangler as a cache-busting measure. If this option/binding is not present, the function will fallback to using the raw pathname to look up your asset in KV. If, for whatever reason, you have rolled your own implementation of this, you can include your own by passing a stringified JSON object where the keys are expected paths, and the values are the expected keys in your KV namespace.
|
240 |
+
|
241 |
+
In ES Modules format, this argument is required, and can be imported.
|
242 |
+
|
243 |
+
##### ES Module
|
244 |
+
|
245 |
+
```js
|
246 |
+
import manifestJSON from '__STATIC_CONTENT_MANIFEST'
|
247 |
+
let manifest = JSON.parse(manifestJSON)
|
248 |
+
manifest['index.html'] = 'index.special.html'
|
249 |
+
|
250 |
+
return getAssetFromKV(
|
251 |
+
{
|
252 |
+
request,
|
253 |
+
waitUntil(promise) {
|
254 |
+
return ctx.waitUntil(promise)
|
255 |
+
},
|
256 |
+
},
|
257 |
+
{
|
258 |
+
ASSET_MANIFEST: manifest,
|
259 |
+
// ...
|
260 |
+
},
|
261 |
+
)
|
262 |
+
```
|
263 |
+
|
264 |
+
##### Service Worker
|
265 |
+
|
266 |
+
```
|
267 |
+
let assetManifest = { "index.html": "index.special.html" }
|
268 |
+
return getAssetFromKV(event, { ASSET_MANIFEST: assetManifest })
|
269 |
+
```
|
270 |
+
|
271 |
+
#### `defaultMimeType` (optional)
|
272 |
+
|
273 |
+
type: string
|
274 |
+
|
275 |
+
This is the mime type that will be used for files with unrecognized or missing extensions. The default value is `'text/plain'`.
|
276 |
+
|
277 |
+
If you are serving a static site and would like to use extensionless HTML files instead of index.html files, set this to `'text/html'`.
|
278 |
+
|
279 |
+
#### `defaultDocument` (optional)
|
280 |
+
|
281 |
+
type: string
|
282 |
+
|
283 |
+
This is the default document that will be concatenated for requests ends in `'/'` or without a valid mime type like `'/about'` or `'/about.me'`. The default value is `'index.html'`.
|
284 |
+
|
285 |
+
# Helper functions
|
286 |
+
|
287 |
+
## `mapRequestToAsset`
|
288 |
+
|
289 |
+
mapRequestToAsset(Request) => Request
|
290 |
+
|
291 |
+
The default function for mapping incoming requests to keys in Cloudflare's KV.
|
292 |
+
|
293 |
+
Takes any path that ends in `/` or evaluates to an HTML file and appends `index.html` or `/index.html` for lookup in your Workers KV namespace.
|
294 |
+
|
295 |
+
## `serveSinglePageApp`
|
296 |
+
|
297 |
+
serveSinglePageApp(Request) => Request
|
298 |
+
|
299 |
+
A custom handler for mapping requests to a single root: `index.html`. The most common use case is single-page applications - frameworks with in-app routing - such as React Router, VueJS, etc. It takes zero arguments.
|
300 |
+
|
301 |
+
```js
|
302 |
+
import { getAssetFromKV, serveSinglePageApp } from '@cloudflare/kv-asset-handler'
|
303 |
+
...
|
304 |
+
let asset = await getAssetFromKV(event, { mapRequestToAsset: serveSinglePageApp })
|
305 |
+
```
|
306 |
+
|
307 |
+
# Cache revalidation and etags
|
308 |
+
|
309 |
+
All responses served from cache (including those with `cf-cache-status: MISS`) include an `etag` response header that identifies the version of the resource. The `etag` value is identical to the path key used in the `ASSET_MANIFEST`. It is updated each time an asset changes and looks like this: `etag: <filename>.<hash of file contents>.<extension>` (ex. `etag: index.54321.html`).
|
310 |
+
|
311 |
+
Resources served with an `etag` allow browsers to use the `if-none-match` request header to make conditional requests for that resource in the future. This has two major benefits:
|
312 |
+
|
313 |
+
- When a request's `if-none-match` value matches the `etag` of the resource in Cloudflare cache, Cloudflare will send a `304 Not Modified` response without a body, saving bandwidth.
|
314 |
+
- Changes to a file on the server are immediately reflected in the browser - even when the cache control directive `max-age` is unexpired.
|
315 |
+
|
316 |
+
#### Disable the `etag`
|
317 |
+
|
318 |
+
To turn `etags` **off**, you must bypass cache:
|
319 |
+
|
320 |
+
```js
|
321 |
+
/* Turn etags off */
|
322 |
+
let cacheControl = {
|
323 |
+
bypassCache: true,
|
324 |
+
}
|
325 |
+
```
|
326 |
+
|
327 |
+
#### Syntax and comparison context
|
328 |
+
|
329 |
+
`kv-asset-handler` sets and evaluates etags as [strong validators](https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests#Strong_validation). To preserve `etag` integrity, the format of the value deviates from the [RFC2616 recommendation to enclose the `etag` with quotation marks](https://tools.ietf.org/html/rfc2616#section-3.11). This is intentional. Cloudflare cache applies the `W/` prefix to all `etags` that use quoted-strings -- a process that converts the `etag` to a "weak validator" when served to a client.
|
node_modules/@cloudflare/kv-asset-handler/dist/index.d.ts
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError } from './types';
|
2 |
+
declare global {
|
3 |
+
var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string;
|
4 |
+
}
|
5 |
+
/**
|
6 |
+
* maps the path of incoming request to the request pathKey to look up
|
7 |
+
* in bucket and in cache
|
8 |
+
* e.g. for a path '/' returns '/index.html' which serves
|
9 |
+
* the content of bucket/index.html
|
10 |
+
* @param {Request} request incoming request
|
11 |
+
*/
|
12 |
+
declare const mapRequestToAsset: (request: Request, options?: Partial<Options>) => Request;
|
13 |
+
/**
|
14 |
+
* maps the path of incoming request to /index.html if it evaluates to
|
15 |
+
* any HTML file.
|
16 |
+
* @param {Request} request incoming request
|
17 |
+
*/
|
18 |
+
declare function serveSinglePageApp(request: Request, options?: Partial<Options>): Request;
|
19 |
+
/**
|
20 |
+
* takes the path of the incoming request, gathers the appropriate content from KV, and returns
|
21 |
+
* the response
|
22 |
+
*
|
23 |
+
* @param {FetchEvent} event the fetch event of the triggered request
|
24 |
+
* @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options
|
25 |
+
* @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser
|
26 |
+
* @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up
|
27 |
+
* @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references
|
28 |
+
* @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV
|
29 |
+
* */
|
30 |
+
declare type Evt = {
|
31 |
+
request: Request;
|
32 |
+
waitUntil: (promise: Promise<any>) => void;
|
33 |
+
};
|
34 |
+
declare const getAssetFromKV: (event: Evt, options?: Partial<Options>) => Promise<Response>;
|
35 |
+
export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp };
|
36 |
+
export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError };
|
node_modules/@cloudflare/kv-asset-handler/dist/index.js
ADDED
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"use strict";
|
2 |
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3 |
+
exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.serveSinglePageApp = exports.mapRequestToAsset = exports.getAssetFromKV = void 0;
|
4 |
+
const mime = require("mime");
|
5 |
+
const types_1 = require("./types");
|
6 |
+
Object.defineProperty(exports, "MethodNotAllowedError", { enumerable: true, get: function () { return types_1.MethodNotAllowedError; } });
|
7 |
+
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return types_1.NotFoundError; } });
|
8 |
+
Object.defineProperty(exports, "InternalError", { enumerable: true, get: function () { return types_1.InternalError; } });
|
9 |
+
const defaultCacheControl = {
|
10 |
+
browserTTL: null,
|
11 |
+
edgeTTL: 2 * 60 * 60 * 24,
|
12 |
+
bypassCache: false, // do not bypass Cloudflare's cache
|
13 |
+
};
|
14 |
+
const parseStringAsObject = (maybeString) => typeof maybeString === 'string' ? JSON.parse(maybeString) : maybeString;
|
15 |
+
const getAssetFromKVDefaultOptions = {
|
16 |
+
ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined,
|
17 |
+
ASSET_MANIFEST: typeof __STATIC_CONTENT_MANIFEST !== 'undefined'
|
18 |
+
? parseStringAsObject(__STATIC_CONTENT_MANIFEST)
|
19 |
+
: {},
|
20 |
+
cacheControl: defaultCacheControl,
|
21 |
+
defaultMimeType: 'text/plain',
|
22 |
+
defaultDocument: 'index.html',
|
23 |
+
pathIsEncoded: false,
|
24 |
+
};
|
25 |
+
function assignOptions(options) {
|
26 |
+
// Assign any missing options passed in to the default
|
27 |
+
// options.mapRequestToAsset is handled manually later
|
28 |
+
return Object.assign({}, getAssetFromKVDefaultOptions, options);
|
29 |
+
}
|
30 |
+
/**
|
31 |
+
* maps the path of incoming request to the request pathKey to look up
|
32 |
+
* in bucket and in cache
|
33 |
+
* e.g. for a path '/' returns '/index.html' which serves
|
34 |
+
* the content of bucket/index.html
|
35 |
+
* @param {Request} request incoming request
|
36 |
+
*/
|
37 |
+
const mapRequestToAsset = (request, options) => {
|
38 |
+
options = assignOptions(options);
|
39 |
+
const parsedUrl = new URL(request.url);
|
40 |
+
let pathname = parsedUrl.pathname;
|
41 |
+
if (pathname.endsWith('/')) {
|
42 |
+
// If path looks like a directory append options.defaultDocument
|
43 |
+
// e.g. If path is /about/ -> /about/index.html
|
44 |
+
pathname = pathname.concat(options.defaultDocument);
|
45 |
+
}
|
46 |
+
else if (!mime.getType(pathname)) {
|
47 |
+
// If path doesn't look like valid content
|
48 |
+
// e.g. /about.me -> /about.me/index.html
|
49 |
+
pathname = pathname.concat('/' + options.defaultDocument);
|
50 |
+
}
|
51 |
+
parsedUrl.pathname = pathname;
|
52 |
+
return new Request(parsedUrl.toString(), request);
|
53 |
+
};
|
54 |
+
exports.mapRequestToAsset = mapRequestToAsset;
|
55 |
+
/**
|
56 |
+
* maps the path of incoming request to /index.html if it evaluates to
|
57 |
+
* any HTML file.
|
58 |
+
* @param {Request} request incoming request
|
59 |
+
*/
|
60 |
+
function serveSinglePageApp(request, options) {
|
61 |
+
options = assignOptions(options);
|
62 |
+
// First apply the default handler, which already has logic to detect
|
63 |
+
// paths that should map to HTML files.
|
64 |
+
request = mapRequestToAsset(request, options);
|
65 |
+
const parsedUrl = new URL(request.url);
|
66 |
+
// Detect if the default handler decided to map to
|
67 |
+
// a HTML file in some specific directory.
|
68 |
+
if (parsedUrl.pathname.endsWith('.html')) {
|
69 |
+
// If expected HTML file was missing, just return the root index.html (or options.defaultDocument)
|
70 |
+
return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request);
|
71 |
+
}
|
72 |
+
else {
|
73 |
+
// The default handler decided this is not an HTML page. It's probably
|
74 |
+
// an image, CSS, or JS file. Leave it as-is.
|
75 |
+
return request;
|
76 |
+
}
|
77 |
+
}
|
78 |
+
exports.serveSinglePageApp = serveSinglePageApp;
|
79 |
+
const getAssetFromKV = async (event, options) => {
|
80 |
+
options = assignOptions(options);
|
81 |
+
const request = event.request;
|
82 |
+
const ASSET_NAMESPACE = options.ASSET_NAMESPACE;
|
83 |
+
const ASSET_MANIFEST = parseStringAsObject(options.ASSET_MANIFEST);
|
84 |
+
if (typeof ASSET_NAMESPACE === 'undefined') {
|
85 |
+
throw new types_1.InternalError(`there is no KV namespace bound to the script`);
|
86 |
+
}
|
87 |
+
const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, ''); // strip any preceding /'s
|
88 |
+
let pathIsEncoded = options.pathIsEncoded;
|
89 |
+
let requestKey;
|
90 |
+
// if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions
|
91 |
+
// otherwise handle request as normal, with default mapRequestToAsset below
|
92 |
+
if (options.mapRequestToAsset) {
|
93 |
+
requestKey = options.mapRequestToAsset(request);
|
94 |
+
}
|
95 |
+
else if (ASSET_MANIFEST[rawPathKey]) {
|
96 |
+
requestKey = request;
|
97 |
+
}
|
98 |
+
else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) {
|
99 |
+
pathIsEncoded = true;
|
100 |
+
requestKey = request;
|
101 |
+
}
|
102 |
+
else {
|
103 |
+
const mappedRequest = mapRequestToAsset(request);
|
104 |
+
const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, '');
|
105 |
+
if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) {
|
106 |
+
pathIsEncoded = true;
|
107 |
+
requestKey = mappedRequest;
|
108 |
+
}
|
109 |
+
else {
|
110 |
+
// use default mapRequestToAsset
|
111 |
+
requestKey = mapRequestToAsset(request, options);
|
112 |
+
}
|
113 |
+
}
|
114 |
+
const SUPPORTED_METHODS = ['GET', 'HEAD'];
|
115 |
+
if (!SUPPORTED_METHODS.includes(requestKey.method)) {
|
116 |
+
throw new types_1.MethodNotAllowedError(`${requestKey.method} is not a valid request method`);
|
117 |
+
}
|
118 |
+
const parsedUrl = new URL(requestKey.url);
|
119 |
+
const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname; // decode percentage encoded path only when necessary
|
120 |
+
// pathKey is the file path to look up in the manifest
|
121 |
+
let pathKey = pathname.replace(/^\/+/, ''); // remove prepended /
|
122 |
+
// @ts-ignore
|
123 |
+
const cache = caches.default;
|
124 |
+
let mimeType = mime.getType(pathKey) || options.defaultMimeType;
|
125 |
+
if (mimeType.startsWith('text') || mimeType === 'application/javascript') {
|
126 |
+
mimeType += '; charset=utf-8';
|
127 |
+
}
|
128 |
+
let shouldEdgeCache = false; // false if storing in KV by raw file path i.e. no hash
|
129 |
+
// check manifest for map from file path to hash
|
130 |
+
if (typeof ASSET_MANIFEST !== 'undefined') {
|
131 |
+
if (ASSET_MANIFEST[pathKey]) {
|
132 |
+
pathKey = ASSET_MANIFEST[pathKey];
|
133 |
+
// if path key is in asset manifest, we can assume it contains a content hash and can be cached
|
134 |
+
shouldEdgeCache = true;
|
135 |
+
}
|
136 |
+
}
|
137 |
+
// TODO this excludes search params from cache, investigate ideal behavior
|
138 |
+
let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request);
|
139 |
+
// if argument passed in for cacheControl is a function then
|
140 |
+
// evaluate that function. otherwise return the Object passed in
|
141 |
+
// or default Object
|
142 |
+
const evalCacheOpts = (() => {
|
143 |
+
switch (typeof options.cacheControl) {
|
144 |
+
case 'function':
|
145 |
+
return options.cacheControl(request);
|
146 |
+
case 'object':
|
147 |
+
return options.cacheControl;
|
148 |
+
default:
|
149 |
+
return defaultCacheControl;
|
150 |
+
}
|
151 |
+
})();
|
152 |
+
// formats the etag depending on the response context. if the entityId
|
153 |
+
// is invalid, returns an empty string (instead of null) to prevent the
|
154 |
+
// the potentially disastrous scenario where the value of the Etag resp
|
155 |
+
// header is "null". Could be modified in future to base64 encode etc
|
156 |
+
const formatETag = (entityId = pathKey, validatorType = 'strong') => {
|
157 |
+
if (!entityId) {
|
158 |
+
return '';
|
159 |
+
}
|
160 |
+
switch (validatorType) {
|
161 |
+
case 'weak':
|
162 |
+
if (!entityId.startsWith('W/')) {
|
163 |
+
return `W/${entityId}`;
|
164 |
+
}
|
165 |
+
return entityId;
|
166 |
+
case 'strong':
|
167 |
+
if (entityId.startsWith(`W/"`)) {
|
168 |
+
entityId = entityId.replace('W/', '');
|
169 |
+
}
|
170 |
+
if (!entityId.endsWith(`"`)) {
|
171 |
+
entityId = `"${entityId}"`;
|
172 |
+
}
|
173 |
+
return entityId;
|
174 |
+
default:
|
175 |
+
return '';
|
176 |
+
}
|
177 |
+
};
|
178 |
+
options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts);
|
179 |
+
// override shouldEdgeCache if options say to bypassCache
|
180 |
+
if (options.cacheControl.bypassCache ||
|
181 |
+
options.cacheControl.edgeTTL === null ||
|
182 |
+
request.method == 'HEAD') {
|
183 |
+
shouldEdgeCache = false;
|
184 |
+
}
|
185 |
+
// only set max-age if explicitly passed in a number as an arg
|
186 |
+
const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number';
|
187 |
+
let response = null;
|
188 |
+
if (shouldEdgeCache) {
|
189 |
+
response = await cache.match(cacheKey);
|
190 |
+
}
|
191 |
+
if (response) {
|
192 |
+
if (response.status > 300 && response.status < 400) {
|
193 |
+
if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) {
|
194 |
+
// Body exists and environment supports readable streams
|
195 |
+
response.body.cancel();
|
196 |
+
}
|
197 |
+
else {
|
198 |
+
// Environment doesnt support readable streams, or null repsonse body. Nothing to do
|
199 |
+
}
|
200 |
+
response = new Response(null, response);
|
201 |
+
}
|
202 |
+
else {
|
203 |
+
// fixes #165
|
204 |
+
let opts = {
|
205 |
+
headers: new Headers(response.headers),
|
206 |
+
status: 0,
|
207 |
+
statusText: '',
|
208 |
+
};
|
209 |
+
opts.headers.set('cf-cache-status', 'HIT');
|
210 |
+
if (response.status) {
|
211 |
+
opts.status = response.status;
|
212 |
+
opts.statusText = response.statusText;
|
213 |
+
}
|
214 |
+
else if (opts.headers.has('Content-Range')) {
|
215 |
+
opts.status = 206;
|
216 |
+
opts.statusText = 'Partial Content';
|
217 |
+
}
|
218 |
+
else {
|
219 |
+
opts.status = 200;
|
220 |
+
opts.statusText = 'OK';
|
221 |
+
}
|
222 |
+
response = new Response(response.body, opts);
|
223 |
+
}
|
224 |
+
}
|
225 |
+
else {
|
226 |
+
const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer');
|
227 |
+
if (body === null) {
|
228 |
+
throw new types_1.NotFoundError(`could not find ${pathKey} in your content namespace`);
|
229 |
+
}
|
230 |
+
response = new Response(body);
|
231 |
+
if (shouldEdgeCache) {
|
232 |
+
response.headers.set('Accept-Ranges', 'bytes');
|
233 |
+
response.headers.set('Content-Length', body.length);
|
234 |
+
// set etag before cache insertion
|
235 |
+
if (!response.headers.has('etag')) {
|
236 |
+
response.headers.set('etag', formatETag(pathKey, 'strong'));
|
237 |
+
}
|
238 |
+
// determine Cloudflare cache behavior
|
239 |
+
response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`);
|
240 |
+
event.waitUntil(cache.put(cacheKey, response.clone()));
|
241 |
+
response.headers.set('CF-Cache-Status', 'MISS');
|
242 |
+
}
|
243 |
+
}
|
244 |
+
response.headers.set('Content-Type', mimeType);
|
245 |
+
if (response.status === 304) {
|
246 |
+
let etag = formatETag(response.headers.get('etag'), 'strong');
|
247 |
+
let ifNoneMatch = cacheKey.headers.get('if-none-match');
|
248 |
+
let proxyCacheStatus = response.headers.get('CF-Cache-Status');
|
249 |
+
if (etag) {
|
250 |
+
if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') {
|
251 |
+
response.headers.set('CF-Cache-Status', 'EXPIRED');
|
252 |
+
}
|
253 |
+
else {
|
254 |
+
response.headers.set('CF-Cache-Status', 'REVALIDATED');
|
255 |
+
}
|
256 |
+
response.headers.set('etag', formatETag(etag, 'weak'));
|
257 |
+
}
|
258 |
+
}
|
259 |
+
if (shouldSetBrowserCache) {
|
260 |
+
response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`);
|
261 |
+
}
|
262 |
+
else {
|
263 |
+
response.headers.delete('Cache-Control');
|
264 |
+
}
|
265 |
+
return response;
|
266 |
+
};
|
267 |
+
exports.getAssetFromKV = getAssetFromKV;
|
node_modules/@cloudflare/kv-asset-handler/dist/mocks.d.ts
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
export declare const getEvent: (request: Request) => any;
|
2 |
+
export declare const mockKV: (store: any) => {
|
3 |
+
get: (path: string) => any;
|
4 |
+
};
|
5 |
+
export declare const mockManifest: () => string;
|
6 |
+
export declare const mockCaches: () => {
|
7 |
+
default: {
|
8 |
+
match(key: any): Promise<any>;
|
9 |
+
put(key: any, val: Response): Promise<void>;
|
10 |
+
};
|
11 |
+
};
|
12 |
+
export declare function mockRequestScope(): void;
|
13 |
+
export declare function mockGlobalScope(): void;
|
14 |
+
export declare const sleep: (milliseconds: number) => Promise<unknown>;
|
node_modules/@cloudflare/kv-asset-handler/dist/mocks.js
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"use strict";
|
2 |
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3 |
+
exports.sleep = exports.mockGlobalScope = exports.mockRequestScope = exports.mockCaches = exports.mockManifest = exports.mockKV = exports.getEvent = void 0;
|
4 |
+
const makeServiceWorkerEnv = require('service-worker-mock');
|
5 |
+
const HASH = '123HASHBROWN';
|
6 |
+
const getEvent = (request) => {
|
7 |
+
const waitUntil = async (callback) => {
|
8 |
+
await callback;
|
9 |
+
};
|
10 |
+
return {
|
11 |
+
request,
|
12 |
+
waitUntil,
|
13 |
+
};
|
14 |
+
};
|
15 |
+
exports.getEvent = getEvent;
|
16 |
+
const store = {
|
17 |
+
'key1.123HASHBROWN.txt': 'val1',
|
18 |
+
'key1.123HASHBROWN.png': 'val1',
|
19 |
+
'index.123HASHBROWN.html': 'index.html',
|
20 |
+
'cache.123HASHBROWN.html': 'cache me if you can',
|
21 |
+
'测试.123HASHBROWN.html': 'My filename is non-ascii',
|
22 |
+
'%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded',
|
23 |
+
'%2F.123HASHBROWN.html': 'user percent encoded',
|
24 |
+
'你好.123HASHBROWN.html': 'I shouldnt be served',
|
25 |
+
'%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important',
|
26 |
+
'nohash.txt': 'no hash but still got some result',
|
27 |
+
'sub/blah.123HASHBROWN.png': 'picturedis',
|
28 |
+
'sub/index.123HASHBROWN.html': 'picturedis',
|
29 |
+
'client.123HASHBROWN': 'important file',
|
30 |
+
'client.123HASHBROWN/index.html': 'Im here but serve my big bro above',
|
31 |
+
'image.123HASHBROWN.png': 'imagepng',
|
32 |
+
'image.123HASHBROWN.webp': 'imagewebp',
|
33 |
+
'你好/index.123HASHBROWN.html': 'My path is non-ascii',
|
34 |
+
};
|
35 |
+
const mockKV = (store) => {
|
36 |
+
return {
|
37 |
+
get: (path) => store[path] || null,
|
38 |
+
};
|
39 |
+
};
|
40 |
+
exports.mockKV = mockKV;
|
41 |
+
const mockManifest = () => {
|
42 |
+
return JSON.stringify({
|
43 |
+
'key1.txt': `key1.${HASH}.txt`,
|
44 |
+
'key1.png': `key1.${HASH}.png`,
|
45 |
+
'cache.html': `cache.${HASH}.html`,
|
46 |
+
'测试.html': `测试.${HASH}.html`,
|
47 |
+
'你好.html': `你好.${HASH}.html`,
|
48 |
+
'%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`,
|
49 |
+
'%2F.html': `%2F.${HASH}.html`,
|
50 |
+
'%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`,
|
51 |
+
'index.html': `index.${HASH}.html`,
|
52 |
+
'sub/blah.png': `sub/blah.${HASH}.png`,
|
53 |
+
'sub/index.html': `sub/index.${HASH}.html`,
|
54 |
+
client: `client.${HASH}`,
|
55 |
+
'client/index.html': `client.${HASH}`,
|
56 |
+
'image.png': `image.${HASH}.png`,
|
57 |
+
'image.webp': `image.${HASH}.webp`,
|
58 |
+
'你好/index.html': `你好/index.${HASH}.html`,
|
59 |
+
});
|
60 |
+
};
|
61 |
+
exports.mockManifest = mockManifest;
|
62 |
+
let cacheStore = new Map();
|
63 |
+
const mockCaches = () => {
|
64 |
+
return {
|
65 |
+
default: {
|
66 |
+
async match(key) {
|
67 |
+
let cacheKey = {
|
68 |
+
url: key.url,
|
69 |
+
headers: {},
|
70 |
+
};
|
71 |
+
let response;
|
72 |
+
if (key.headers.has('if-none-match')) {
|
73 |
+
let makeStrongEtag = key.headers.get('if-none-match').replace('W/', '');
|
74 |
+
Reflect.set(cacheKey.headers, 'etag', makeStrongEtag);
|
75 |
+
response = cacheStore.get(JSON.stringify(cacheKey));
|
76 |
+
}
|
77 |
+
else {
|
78 |
+
// if client doesn't send if-none-match, we need to iterate through these keys
|
79 |
+
// and just test the URL
|
80 |
+
const activeCacheKeys = Array.from(cacheStore.keys());
|
81 |
+
for (const cacheStoreKey of activeCacheKeys) {
|
82 |
+
if (JSON.parse(cacheStoreKey).url === key.url) {
|
83 |
+
response = cacheStore.get(cacheStoreKey);
|
84 |
+
}
|
85 |
+
}
|
86 |
+
}
|
87 |
+
// TODO: write test to accomodate for rare scenarios with where range requests accomodate etags
|
88 |
+
if (response && !key.headers.has('if-none-match')) {
|
89 |
+
// this appears overly verbose, but is necessary to document edge cache behavior
|
90 |
+
// The Range request header triggers the response header Content-Range ...
|
91 |
+
const range = key.headers.get('range');
|
92 |
+
if (range) {
|
93 |
+
response.headers.set('content-range', `bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`);
|
94 |
+
}
|
95 |
+
// ... which we are using in this repository to set status 206
|
96 |
+
if (response.headers.has('content-range')) {
|
97 |
+
response.status = 206;
|
98 |
+
}
|
99 |
+
else {
|
100 |
+
response.status = 200;
|
101 |
+
}
|
102 |
+
let etag = response.headers.get('etag');
|
103 |
+
if (etag && !etag.includes('W/')) {
|
104 |
+
response.headers.set('etag', `W/${etag}`);
|
105 |
+
}
|
106 |
+
}
|
107 |
+
return response;
|
108 |
+
},
|
109 |
+
async put(key, val) {
|
110 |
+
let headers = new Headers(val.headers);
|
111 |
+
let url = new URL(key.url);
|
112 |
+
let resWithBody = new Response(val.body, { headers, status: 200 });
|
113 |
+
let resNoBody = new Response(null, { headers, status: 304 });
|
114 |
+
let cacheKey = {
|
115 |
+
url: key.url,
|
116 |
+
headers: {
|
117 |
+
etag: `"${url.pathname.replace('/', '')}"`,
|
118 |
+
},
|
119 |
+
};
|
120 |
+
cacheStore.set(JSON.stringify(cacheKey), resNoBody);
|
121 |
+
cacheKey.headers = {};
|
122 |
+
cacheStore.set(JSON.stringify(cacheKey), resWithBody);
|
123 |
+
return;
|
124 |
+
},
|
125 |
+
},
|
126 |
+
};
|
127 |
+
};
|
128 |
+
exports.mockCaches = mockCaches;
|
129 |
+
// mocks functionality used inside worker request
|
130 |
+
function mockRequestScope() {
|
131 |
+
Object.assign(global, makeServiceWorkerEnv());
|
132 |
+
Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() });
|
133 |
+
Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) });
|
134 |
+
Object.assign(global, { caches: (0, exports.mockCaches)() });
|
135 |
+
}
|
136 |
+
exports.mockRequestScope = mockRequestScope;
|
137 |
+
// mocks functionality used on global isolate scope. such as the KV namespace bind
|
138 |
+
function mockGlobalScope() {
|
139 |
+
Object.assign(global, { __STATIC_CONTENT_MANIFEST: (0, exports.mockManifest)() });
|
140 |
+
Object.assign(global, { __STATIC_CONTENT: (0, exports.mockKV)(store) });
|
141 |
+
}
|
142 |
+
exports.mockGlobalScope = mockGlobalScope;
|
143 |
+
const sleep = (milliseconds) => {
|
144 |
+
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
145 |
+
};
|
146 |
+
exports.sleep = sleep;
|
node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.d.ts
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
export {};
|
node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV-optional.js
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"use strict";
|
2 |
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3 |
+
const ava_1 = require("ava");
|
4 |
+
const mocks_1 = require("../mocks");
|
5 |
+
(0, mocks_1.mockGlobalScope)();
|
6 |
+
// manually reset manifest global, to test optional behaviour
|
7 |
+
Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined });
|
8 |
+
const index_1 = require("../index");
|
9 |
+
(0, ava_1.default)('getAssetFromKV return correct val from KV without manifest', async (t) => {
|
10 |
+
(0, mocks_1.mockRequestScope)();
|
11 |
+
// manually reset manifest global, to test optional behaviour
|
12 |
+
Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined });
|
13 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.123HASHBROWN.txt'));
|
14 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
15 |
+
if (res) {
|
16 |
+
t.is(await res.text(), 'val1');
|
17 |
+
t.true(res.headers.get('content-type').includes('text'));
|
18 |
+
}
|
19 |
+
else {
|
20 |
+
t.fail('Response was undefined');
|
21 |
+
}
|
22 |
+
});
|
node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
export {};
|
node_modules/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js
ADDED
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"use strict";
|
2 |
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3 |
+
const ava_1 = require("ava");
|
4 |
+
const mocks_1 = require("../mocks");
|
5 |
+
(0, mocks_1.mockGlobalScope)();
|
6 |
+
const index_1 = require("../index");
|
7 |
+
(0, ava_1.default)('getAssetFromKV return correct val from KV and default caching', async (t) => {
|
8 |
+
(0, mocks_1.mockRequestScope)();
|
9 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.txt'));
|
10 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
11 |
+
if (res) {
|
12 |
+
t.is(res.headers.get('cache-control'), null);
|
13 |
+
t.is(res.headers.get('cf-cache-status'), 'MISS');
|
14 |
+
t.is(await res.text(), 'val1');
|
15 |
+
t.true(res.headers.get('content-type').includes('text'));
|
16 |
+
}
|
17 |
+
else {
|
18 |
+
t.fail('Response was undefined');
|
19 |
+
}
|
20 |
+
});
|
21 |
+
(0, ava_1.default)('getAssetFromKV evaluated the file matching the extensionless path first /client/ -> client', async (t) => {
|
22 |
+
(0, mocks_1.mockRequestScope)();
|
23 |
+
const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client/`));
|
24 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
25 |
+
t.is(await res.text(), 'important file');
|
26 |
+
t.true(res.headers.get('content-type').includes('text'));
|
27 |
+
});
|
28 |
+
(0, ava_1.default)('getAssetFromKV evaluated the file matching the extensionless path first /client -> client', async (t) => {
|
29 |
+
(0, mocks_1.mockRequestScope)();
|
30 |
+
const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client`));
|
31 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
32 |
+
t.is(await res.text(), 'important file');
|
33 |
+
t.true(res.headers.get('content-type').includes('text'));
|
34 |
+
});
|
35 |
+
(0, ava_1.default)('getAssetFromKV if not in asset manifest still returns nohash.txt', async (t) => {
|
36 |
+
(0, mocks_1.mockRequestScope)();
|
37 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/nohash.txt'));
|
38 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
39 |
+
if (res) {
|
40 |
+
t.is(await res.text(), 'no hash but still got some result');
|
41 |
+
t.true(res.headers.get('content-type').includes('text'));
|
42 |
+
}
|
43 |
+
else {
|
44 |
+
t.fail('Response was undefined');
|
45 |
+
}
|
46 |
+
});
|
47 |
+
(0, ava_1.default)('getAssetFromKV if no asset manifest /client -> client fails', async (t) => {
|
48 |
+
(0, mocks_1.mockRequestScope)();
|
49 |
+
const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/client`));
|
50 |
+
const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_MANIFEST: {} }));
|
51 |
+
t.is(error.status, 404);
|
52 |
+
});
|
53 |
+
(0, ava_1.default)('getAssetFromKV if sub/ -> sub/index.html served', async (t) => {
|
54 |
+
(0, mocks_1.mockRequestScope)();
|
55 |
+
const event = (0, mocks_1.getEvent)(new Request(`https://foo.com/sub`));
|
56 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
57 |
+
if (res) {
|
58 |
+
t.is(await res.text(), 'picturedis');
|
59 |
+
}
|
60 |
+
else {
|
61 |
+
t.fail('Response was undefined');
|
62 |
+
}
|
63 |
+
});
|
64 |
+
(0, ava_1.default)('getAssetFromKV gets index.html by default for / requests', async (t) => {
|
65 |
+
(0, mocks_1.mockRequestScope)();
|
66 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
|
67 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
68 |
+
if (res) {
|
69 |
+
t.is(await res.text(), 'index.html');
|
70 |
+
t.true(res.headers.get('content-type').includes('html'));
|
71 |
+
}
|
72 |
+
else {
|
73 |
+
t.fail('Response was undefined');
|
74 |
+
}
|
75 |
+
});
|
76 |
+
(0, ava_1.default)('getAssetFromKV non ASCII path support', async (t) => {
|
77 |
+
(0, mocks_1.mockRequestScope)();
|
78 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/测试.html'));
|
79 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
80 |
+
if (res) {
|
81 |
+
t.is(await res.text(), 'My filename is non-ascii');
|
82 |
+
}
|
83 |
+
else {
|
84 |
+
t.fail('Response was undefined');
|
85 |
+
}
|
86 |
+
});
|
87 |
+
(0, ava_1.default)('getAssetFromKV supports browser percent encoded URLs', async (t) => {
|
88 |
+
(0, mocks_1.mockRequestScope)();
|
89 |
+
const event = (0, mocks_1.getEvent)(new Request('https://example.com/%not-really-percent-encoded.html'));
|
90 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
91 |
+
if (res) {
|
92 |
+
t.is(await res.text(), 'browser percent encoded');
|
93 |
+
}
|
94 |
+
else {
|
95 |
+
t.fail('Response was undefined');
|
96 |
+
}
|
97 |
+
});
|
98 |
+
(0, ava_1.default)('getAssetFromKV supports user percent encoded URLs', async (t) => {
|
99 |
+
(0, mocks_1.mockRequestScope)();
|
100 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/%2F.html'));
|
101 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
102 |
+
if (res) {
|
103 |
+
t.is(await res.text(), 'user percent encoded');
|
104 |
+
}
|
105 |
+
else {
|
106 |
+
t.fail('Response was undefined');
|
107 |
+
}
|
108 |
+
});
|
109 |
+
(0, ava_1.default)('getAssetFromKV only decode URL when necessary', async (t) => {
|
110 |
+
(0, mocks_1.mockRequestScope)();
|
111 |
+
const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD.html'));
|
112 |
+
const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/你好.html'));
|
113 |
+
const res1 = await (0, index_1.getAssetFromKV)(event1);
|
114 |
+
const res2 = await (0, index_1.getAssetFromKV)(event2);
|
115 |
+
if (res1 && res2) {
|
116 |
+
t.is(await res1.text(), 'Im important');
|
117 |
+
t.is(await res2.text(), 'Im important');
|
118 |
+
}
|
119 |
+
else {
|
120 |
+
t.fail('Response was undefined');
|
121 |
+
}
|
122 |
+
});
|
123 |
+
(0, ava_1.default)('getAssetFromKV Support for user decode url path', async (t) => {
|
124 |
+
(0, mocks_1.mockRequestScope)();
|
125 |
+
const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD/'));
|
126 |
+
const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/你好/'));
|
127 |
+
const res1 = await (0, index_1.getAssetFromKV)(event1);
|
128 |
+
const res2 = await (0, index_1.getAssetFromKV)(event2);
|
129 |
+
if (res1 && res2) {
|
130 |
+
t.is(await res1.text(), 'My path is non-ascii');
|
131 |
+
t.is(await res2.text(), 'My path is non-ascii');
|
132 |
+
}
|
133 |
+
else {
|
134 |
+
t.fail('Response was undefined');
|
135 |
+
}
|
136 |
+
});
|
137 |
+
(0, ava_1.default)('getAssetFromKV custom key modifier', async (t) => {
|
138 |
+
(0, mocks_1.mockRequestScope)();
|
139 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/docs/sub/blah.png'));
|
140 |
+
const customRequestMapper = (request) => {
|
141 |
+
let defaultModifiedRequest = (0, index_1.mapRequestToAsset)(request);
|
142 |
+
let url = new URL(defaultModifiedRequest.url);
|
143 |
+
url.pathname = url.pathname.replace('/docs', '');
|
144 |
+
return new Request(url.toString(), request);
|
145 |
+
};
|
146 |
+
const res = await (0, index_1.getAssetFromKV)(event, { mapRequestToAsset: customRequestMapper });
|
147 |
+
if (res) {
|
148 |
+
t.is(await res.text(), 'picturedis');
|
149 |
+
}
|
150 |
+
else {
|
151 |
+
t.fail('Response was undefined');
|
152 |
+
}
|
153 |
+
});
|
154 |
+
(0, ava_1.default)('getAssetFromKV request override with existing manifest file', async (t) => {
|
155 |
+
// see https://github.com/cloudflare/kv-asset-handler/pull/159 for more info
|
156 |
+
(0, mocks_1.mockRequestScope)();
|
157 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/image.png')); // real file in manifest
|
158 |
+
const customRequestMapper = (request) => {
|
159 |
+
let defaultModifiedRequest = (0, index_1.mapRequestToAsset)(request);
|
160 |
+
let url = new URL(defaultModifiedRequest.url);
|
161 |
+
url.pathname = '/image.webp'; // other different file in manifest
|
162 |
+
return new Request(url.toString(), request);
|
163 |
+
};
|
164 |
+
const res = await (0, index_1.getAssetFromKV)(event, { mapRequestToAsset: customRequestMapper });
|
165 |
+
if (res) {
|
166 |
+
t.is(await res.text(), 'imagewebp');
|
167 |
+
}
|
168 |
+
else {
|
169 |
+
t.fail('Response was undefined');
|
170 |
+
}
|
171 |
+
});
|
172 |
+
(0, ava_1.default)('getAssetFromKV when setting browser caching', async (t) => {
|
173 |
+
(0, mocks_1.mockRequestScope)();
|
174 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
|
175 |
+
const res = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: 22 } });
|
176 |
+
if (res) {
|
177 |
+
t.is(res.headers.get('cache-control'), 'max-age=22');
|
178 |
+
}
|
179 |
+
else {
|
180 |
+
t.fail('Response was undefined');
|
181 |
+
}
|
182 |
+
});
|
183 |
+
(0, ava_1.default)('getAssetFromKV when setting custom cache setting', async (t) => {
|
184 |
+
(0, mocks_1.mockRequestScope)();
|
185 |
+
const event1 = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
|
186 |
+
const event2 = (0, mocks_1.getEvent)(new Request('https://blah.com/key1.png?blah=34'));
|
187 |
+
const cacheOnlyPngs = (req) => {
|
188 |
+
if (new URL(req.url).pathname.endsWith('.png'))
|
189 |
+
return {
|
190 |
+
browserTTL: 720,
|
191 |
+
edgeTTL: 720,
|
192 |
+
};
|
193 |
+
else
|
194 |
+
return {
|
195 |
+
bypassCache: true,
|
196 |
+
};
|
197 |
+
};
|
198 |
+
const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: cacheOnlyPngs });
|
199 |
+
const res2 = await (0, index_1.getAssetFromKV)(event2, { cacheControl: cacheOnlyPngs });
|
200 |
+
if (res1 && res2) {
|
201 |
+
t.is(res1.headers.get('cache-control'), null);
|
202 |
+
t.true(res2.headers.get('content-type').includes('png'));
|
203 |
+
t.is(res2.headers.get('cache-control'), 'max-age=720');
|
204 |
+
t.is(res2.headers.get('cf-cache-status'), 'MISS');
|
205 |
+
}
|
206 |
+
else {
|
207 |
+
t.fail('Response was undefined');
|
208 |
+
}
|
209 |
+
});
|
210 |
+
(0, ava_1.default)('getAssetFromKV caches on two sequential requests', async (t) => {
|
211 |
+
(0, mocks_1.mockRequestScope)();
|
212 |
+
const resourceKey = 'cache.html';
|
213 |
+
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
|
214 |
+
const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
|
215 |
+
const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, {
|
216 |
+
headers: {
|
217 |
+
'if-none-match': `"${resourceVersion}"`,
|
218 |
+
},
|
219 |
+
}));
|
220 |
+
const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720, browserTTL: 720 } });
|
221 |
+
await (0, mocks_1.sleep)(1);
|
222 |
+
const res2 = await (0, index_1.getAssetFromKV)(event2);
|
223 |
+
if (res1 && res2) {
|
224 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS');
|
225 |
+
t.is(res1.headers.get('cache-control'), 'max-age=720');
|
226 |
+
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED');
|
227 |
+
}
|
228 |
+
else {
|
229 |
+
t.fail('Response was undefined');
|
230 |
+
}
|
231 |
+
});
|
232 |
+
(0, ava_1.default)('getAssetFromKV does not store max-age on two sequential requests', async (t) => {
|
233 |
+
(0, mocks_1.mockRequestScope)();
|
234 |
+
const resourceKey = 'cache.html';
|
235 |
+
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
|
236 |
+
const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
|
237 |
+
const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, {
|
238 |
+
headers: {
|
239 |
+
'if-none-match': `"${resourceVersion}"`,
|
240 |
+
},
|
241 |
+
}));
|
242 |
+
const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } });
|
243 |
+
await (0, mocks_1.sleep)(100);
|
244 |
+
const res2 = await (0, index_1.getAssetFromKV)(event2);
|
245 |
+
if (res1 && res2) {
|
246 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS');
|
247 |
+
t.is(res1.headers.get('cache-control'), null);
|
248 |
+
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED');
|
249 |
+
t.is(res2.headers.get('cache-control'), null);
|
250 |
+
}
|
251 |
+
else {
|
252 |
+
t.fail('Response was undefined');
|
253 |
+
}
|
254 |
+
});
|
255 |
+
(0, ava_1.default)('getAssetFromKV does not cache on Cloudflare when bypass cache set', async (t) => {
|
256 |
+
(0, mocks_1.mockRequestScope)();
|
257 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
|
258 |
+
const res = await (0, index_1.getAssetFromKV)(event, { cacheControl: { bypassCache: true } });
|
259 |
+
if (res) {
|
260 |
+
t.is(res.headers.get('cache-control'), null);
|
261 |
+
t.is(res.headers.get('cf-cache-status'), null);
|
262 |
+
}
|
263 |
+
else {
|
264 |
+
t.fail('Response was undefined');
|
265 |
+
}
|
266 |
+
});
|
267 |
+
(0, ava_1.default)('getAssetFromKV with no trailing slash on root', async (t) => {
|
268 |
+
(0, mocks_1.mockRequestScope)();
|
269 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com'));
|
270 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
271 |
+
if (res) {
|
272 |
+
t.is(await res.text(), 'index.html');
|
273 |
+
}
|
274 |
+
else {
|
275 |
+
t.fail('Response was undefined');
|
276 |
+
}
|
277 |
+
});
|
278 |
+
(0, ava_1.default)('getAssetFromKV with no trailing slash on a subdirectory', async (t) => {
|
279 |
+
(0, mocks_1.mockRequestScope)();
|
280 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/sub/blah.png'));
|
281 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
282 |
+
if (res) {
|
283 |
+
t.is(await res.text(), 'picturedis');
|
284 |
+
}
|
285 |
+
else {
|
286 |
+
t.fail('Response was undefined');
|
287 |
+
}
|
288 |
+
});
|
289 |
+
(0, ava_1.default)('getAssetFromKV no result throws an error', async (t) => {
|
290 |
+
(0, mocks_1.mockRequestScope)();
|
291 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/random'));
|
292 |
+
const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event));
|
293 |
+
t.is(error.status, 404);
|
294 |
+
});
|
295 |
+
(0, ava_1.default)('getAssetFromKV TTls set to null should not cache on browser or edge', async (t) => {
|
296 |
+
(0, mocks_1.mockRequestScope)();
|
297 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
|
298 |
+
const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: null, edgeTTL: null } });
|
299 |
+
await (0, mocks_1.sleep)(100);
|
300 |
+
const res2 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { browserTTL: null, edgeTTL: null } });
|
301 |
+
if (res1 && res2) {
|
302 |
+
t.is(res1.headers.get('cf-cache-status'), null);
|
303 |
+
t.is(res1.headers.get('cache-control'), null);
|
304 |
+
t.is(res2.headers.get('cf-cache-status'), null);
|
305 |
+
t.is(res2.headers.get('cache-control'), null);
|
306 |
+
}
|
307 |
+
else {
|
308 |
+
t.fail('Response was undefined');
|
309 |
+
}
|
310 |
+
});
|
311 |
+
(0, ava_1.default)('getAssetFromKV passing in a custom NAMESPACE serves correct asset', async (t) => {
|
312 |
+
(0, mocks_1.mockRequestScope)();
|
313 |
+
let CUSTOM_NAMESPACE = (0, mocks_1.mockKV)({
|
314 |
+
'key1.123HASHBROWN.txt': 'val1',
|
315 |
+
});
|
316 |
+
Object.assign(global, { CUSTOM_NAMESPACE });
|
317 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
|
318 |
+
const res = await (0, index_1.getAssetFromKV)(event);
|
319 |
+
if (res) {
|
320 |
+
t.is(await res.text(), 'index.html');
|
321 |
+
t.true(res.headers.get('content-type').includes('html'));
|
322 |
+
}
|
323 |
+
else {
|
324 |
+
t.fail('Response was undefined');
|
325 |
+
}
|
326 |
+
});
|
327 |
+
(0, ava_1.default)('getAssetFromKV when custom namespace without the asset should fail', async (t) => {
|
328 |
+
(0, mocks_1.mockRequestScope)();
|
329 |
+
let CUSTOM_NAMESPACE = (0, mocks_1.mockKV)({
|
330 |
+
'key5.123HASHBROWN.txt': 'customvalu',
|
331 |
+
});
|
332 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com'));
|
333 |
+
const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_NAMESPACE: CUSTOM_NAMESPACE }));
|
334 |
+
t.is(error.status, 404);
|
335 |
+
});
|
336 |
+
(0, ava_1.default)('getAssetFromKV when namespace not bound fails', async (t) => {
|
337 |
+
(0, mocks_1.mockRequestScope)();
|
338 |
+
var MY_CUSTOM_NAMESPACE = undefined;
|
339 |
+
Object.assign(global, { MY_CUSTOM_NAMESPACE });
|
340 |
+
const event = (0, mocks_1.getEvent)(new Request('https://blah.com/'));
|
341 |
+
const error = await t.throwsAsync((0, index_1.getAssetFromKV)(event, { ASSET_NAMESPACE: MY_CUSTOM_NAMESPACE }));
|
342 |
+
t.is(error.status, 500);
|
343 |
+
});
|
344 |
+
(0, ava_1.default)('getAssetFromKV when if-none-match === active resource version, should revalidate', async (t) => {
|
345 |
+
(0, mocks_1.mockRequestScope)();
|
346 |
+
const resourceKey = 'key1.png';
|
347 |
+
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
|
348 |
+
const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
|
349 |
+
const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, {
|
350 |
+
headers: {
|
351 |
+
'if-none-match': `W/"${resourceVersion}"`,
|
352 |
+
},
|
353 |
+
}));
|
354 |
+
const res1 = await (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } });
|
355 |
+
await (0, mocks_1.sleep)(100);
|
356 |
+
const res2 = await (0, index_1.getAssetFromKV)(event2);
|
357 |
+
if (res1 && res2) {
|
358 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS');
|
359 |
+
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED');
|
360 |
+
}
|
361 |
+
else {
|
362 |
+
t.fail('Response was undefined');
|
363 |
+
}
|
364 |
+
});
|
365 |
+
(0, ava_1.default)('getAssetFromKV when if-none-match equals etag of stale resource then should bypass cache', async (t) => {
|
366 |
+
(0, mocks_1.mockRequestScope)();
|
367 |
+
const resourceKey = 'key1.png';
|
368 |
+
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
|
369 |
+
const req1 = new Request(`https://blah.com/${resourceKey}`, {
|
370 |
+
headers: {
|
371 |
+
'if-none-match': `"${resourceVersion}"`,
|
372 |
+
},
|
373 |
+
});
|
374 |
+
const req2 = new Request(`https://blah.com/${resourceKey}`, {
|
375 |
+
headers: {
|
376 |
+
'if-none-match': `"${resourceVersion}-another-version"`,
|
377 |
+
},
|
378 |
+
});
|
379 |
+
const event = (0, mocks_1.getEvent)(req1);
|
380 |
+
const event2 = (0, mocks_1.getEvent)(req2);
|
381 |
+
const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } });
|
382 |
+
const res2 = await (0, index_1.getAssetFromKV)(event);
|
383 |
+
const res3 = await (0, index_1.getAssetFromKV)(event2);
|
384 |
+
if (res1 && res2 && res3) {
|
385 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS');
|
386 |
+
t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`);
|
387 |
+
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED');
|
388 |
+
t.not(res3.headers.get('etag'), req2.headers.get('if-none-match'));
|
389 |
+
t.is(res3.headers.get('cf-cache-status'), 'MISS');
|
390 |
+
}
|
391 |
+
else {
|
392 |
+
t.fail('Response was undefined');
|
393 |
+
}
|
394 |
+
});
|
395 |
+
(0, ava_1.default)('getAssetFromKV when resource in cache, etag should be weakened before returned to eyeball', async (t) => {
|
396 |
+
(0, mocks_1.mockRequestScope)();
|
397 |
+
const resourceKey = 'key1.png';
|
398 |
+
const resourceVersion = JSON.parse((0, mocks_1.mockManifest)())[resourceKey];
|
399 |
+
const req1 = new Request(`https://blah.com/${resourceKey}`, {
|
400 |
+
headers: {
|
401 |
+
'if-none-match': `"${resourceVersion}"`,
|
402 |
+
},
|
403 |
+
});
|
404 |
+
const event = (0, mocks_1.getEvent)(req1);
|
405 |
+
const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } });
|
406 |
+
const res2 = await (0, index_1.getAssetFromKV)(event);
|
407 |
+
if (res1 && res2) {
|
408 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS');
|
409 |
+
t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`);
|
410 |
+
}
|
411 |
+
else {
|
412 |
+
t.fail('Response was undefined');
|
413 |
+
}
|
414 |
+
});
|
415 |
+
(0, ava_1.default)('getAssetFromKV if-none-match not sent but resource in cache, should return cache hit 200 OK', async (t) => {
|
416 |
+
const resourceKey = 'cache.html';
|
417 |
+
const event = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
|
418 |
+
const res1 = await (0, index_1.getAssetFromKV)(event, { cacheControl: { edgeTTL: 720 } });
|
419 |
+
await (0, mocks_1.sleep)(1);
|
420 |
+
const res2 = await (0, index_1.getAssetFromKV)(event);
|
421 |
+
if (res1 && res2) {
|
422 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS');
|
423 |
+
t.is(res1.headers.get('cache-control'), null);
|
424 |
+
t.is(res2.status, 200);
|
425 |
+
t.is(res2.headers.get('cf-cache-status'), 'HIT');
|
426 |
+
}
|
427 |
+
else {
|
428 |
+
t.fail('Response was undefined');
|
429 |
+
}
|
430 |
+
});
|
431 |
+
(0, ava_1.default)('getAssetFromKV if range request submitted and resource in cache, request fulfilled', async (t) => {
|
432 |
+
const resourceKey = 'cache.html';
|
433 |
+
const event1 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`));
|
434 |
+
const event2 = (0, mocks_1.getEvent)(new Request(`https://blah.com/${resourceKey}`, { headers: { range: 'bytes=0-10' } }));
|
435 |
+
const res1 = (0, index_1.getAssetFromKV)(event1, { cacheControl: { edgeTTL: 720 } });
|
436 |
+
await res1;
|
437 |
+
await (0, mocks_1.sleep)(2);
|
438 |
+
const res2 = await (0, index_1.getAssetFromKV)(event2);
|
439 |
+
if (res2.headers.has('content-range')) {
|
440 |
+
t.is(res2.status, 206);
|
441 |
+
}
|
442 |
+
else {
|
443 |
+
t.fail('Response was undefined');
|
444 |
+
}
|
445 |
+
});
|
446 |
+
ava_1.default.todo('getAssetFromKV when body not empty, should invoke .cancel()');
|
node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
export {};
|
node_modules/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"use strict";
|
2 |
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3 |
+
const ava_1 = require("ava");
|
4 |
+
const mocks_1 = require("../mocks");
|
5 |
+
(0, mocks_1.mockGlobalScope)();
|
6 |
+
const index_1 = require("../index");
|
7 |
+
(0, ava_1.default)('mapRequestToAsset() correctly changes /about -> /about/index.html', async (t) => {
|
8 |
+
(0, mocks_1.mockRequestScope)();
|
9 |
+
let path = '/about';
|
10 |
+
let request = new Request(`https://foo.com${path}`);
|
11 |
+
let newRequest = (0, index_1.mapRequestToAsset)(request);
|
12 |
+
t.is(newRequest.url, request.url + '/index.html');
|
13 |
+
});
|
14 |
+
(0, ava_1.default)('mapRequestToAsset() correctly changes /about/ -> /about/index.html', async (t) => {
|
15 |
+
(0, mocks_1.mockRequestScope)();
|
16 |
+
let path = '/about/';
|
17 |
+
let request = new Request(`https://foo.com${path}`);
|
18 |
+
let newRequest = (0, index_1.mapRequestToAsset)(request);
|
19 |
+
t.is(newRequest.url, request.url + 'index.html');
|
20 |
+
});
|
21 |
+
(0, ava_1.default)('mapRequestToAsset() correctly changes /about.me/ -> /about.me/index.html', async (t) => {
|
22 |
+
(0, mocks_1.mockRequestScope)();
|
23 |
+
let path = '/about.me/';
|
24 |
+
let request = new Request(`https://foo.com${path}`);
|
25 |
+
let newRequest = (0, index_1.mapRequestToAsset)(request);
|
26 |
+
t.is(newRequest.url, request.url + 'index.html');
|
27 |
+
});
|
28 |
+
(0, ava_1.default)('mapRequestToAsset() correctly changes /about -> /about/default.html', async (t) => {
|
29 |
+
(0, mocks_1.mockRequestScope)();
|
30 |
+
let path = '/about';
|
31 |
+
let request = new Request(`https://foo.com${path}`);
|
32 |
+
let newRequest = (0, index_1.mapRequestToAsset)(request, { defaultDocument: 'default.html' });
|
33 |
+
t.is(newRequest.url, request.url + '/default.html');
|
34 |
+
});
|
node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
export {};
|
node_modules/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"use strict";
|
2 |
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3 |
+
const ava_1 = require("ava");
|
4 |
+
const mocks_1 = require("../mocks");
|
5 |
+
(0, mocks_1.mockGlobalScope)();
|
6 |
+
const index_1 = require("../index");
|
7 |
+
function testRequest(path) {
|
8 |
+
(0, mocks_1.mockRequestScope)();
|
9 |
+
let url = new URL('https://example.com');
|
10 |
+
url.pathname = path;
|
11 |
+
let request = new Request(url.toString());
|
12 |
+
return request;
|
13 |
+
}
|
14 |
+
(0, ava_1.default)('serveSinglePageApp returns root asset path when request path ends in .html', async (t) => {
|
15 |
+
let path = '/foo/thing.html';
|
16 |
+
let request = testRequest(path);
|
17 |
+
let expected_request = testRequest('/index.html');
|
18 |
+
let actual_request = (0, index_1.serveSinglePageApp)(request);
|
19 |
+
t.deepEqual(expected_request, actual_request);
|
20 |
+
});
|
21 |
+
(0, ava_1.default)('serveSinglePageApp returns root asset path when request path does not have extension', async (t) => {
|
22 |
+
let path = '/foo/thing';
|
23 |
+
let request = testRequest(path);
|
24 |
+
let expected_request = testRequest('/index.html');
|
25 |
+
let actual_request = (0, index_1.serveSinglePageApp)(request);
|
26 |
+
t.deepEqual(expected_request, actual_request);
|
27 |
+
});
|
28 |
+
(0, ava_1.default)('serveSinglePageApp returns requested asset when request path has non-html extension', async (t) => {
|
29 |
+
let path = '/foo/thing.js';
|
30 |
+
let request = testRequest(path);
|
31 |
+
let expected_request = request;
|
32 |
+
let actual_request = (0, index_1.serveSinglePageApp)(request);
|
33 |
+
t.deepEqual(expected_request, actual_request);
|
34 |
+
});
|
node_modules/@cloudflare/kv-asset-handler/dist/types.d.ts
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
export declare type CacheControl = {
|
2 |
+
browserTTL: number;
|
3 |
+
edgeTTL: number;
|
4 |
+
bypassCache: boolean;
|
5 |
+
};
|
6 |
+
export declare type AssetManifestType = Record<string, string>;
|
7 |
+
export declare type Options = {
|
8 |
+
cacheControl: ((req: Request) => Partial<CacheControl>) | Partial<CacheControl>;
|
9 |
+
ASSET_NAMESPACE: any;
|
10 |
+
ASSET_MANIFEST: AssetManifestType | string;
|
11 |
+
mapRequestToAsset?: (req: Request, options?: Partial<Options>) => Request;
|
12 |
+
defaultMimeType: string;
|
13 |
+
defaultDocument: string;
|
14 |
+
pathIsEncoded: boolean;
|
15 |
+
};
|
16 |
+
export declare class KVError extends Error {
|
17 |
+
constructor(message?: string, status?: number);
|
18 |
+
status: number;
|
19 |
+
}
|
20 |
+
export declare class MethodNotAllowedError extends KVError {
|
21 |
+
constructor(message?: string, status?: number);
|
22 |
+
}
|
23 |
+
export declare class NotFoundError extends KVError {
|
24 |
+
constructor(message?: string, status?: number);
|
25 |
+
}
|
26 |
+
export declare class InternalError extends KVError {
|
27 |
+
constructor(message?: string, status?: number);
|
28 |
+
}
|
node_modules/@cloudflare/kv-asset-handler/dist/types.js
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"use strict";
|
2 |
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3 |
+
exports.InternalError = exports.NotFoundError = exports.MethodNotAllowedError = exports.KVError = void 0;
|
4 |
+
class KVError extends Error {
|
5 |
+
constructor(message, status = 500) {
|
6 |
+
super(message);
|
7 |
+
// see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
|
8 |
+
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
|
9 |
+
this.name = KVError.name; // stack traces display correctly now
|
10 |
+
this.status = status;
|
11 |
+
}
|
12 |
+
}
|
13 |
+
exports.KVError = KVError;
|
14 |
+
class MethodNotAllowedError extends KVError {
|
15 |
+
constructor(message = `Not a valid request method`, status = 405) {
|
16 |
+
super(message, status);
|
17 |
+
}
|
18 |
+
}
|
19 |
+
exports.MethodNotAllowedError = MethodNotAllowedError;
|
20 |
+
class NotFoundError extends KVError {
|
21 |
+
constructor(message = `Not Found`, status = 404) {
|
22 |
+
super(message, status);
|
23 |
+
}
|
24 |
+
}
|
25 |
+
exports.NotFoundError = NotFoundError;
|
26 |
+
class InternalError extends KVError {
|
27 |
+
constructor(message = `Internal Error in KV Asset Handler`, status = 500) {
|
28 |
+
super(message, status);
|
29 |
+
}
|
30 |
+
}
|
31 |
+
exports.InternalError = InternalError;
|
node_modules/@cloudflare/kv-asset-handler/package.json
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name": "@cloudflare/kv-asset-handler",
|
3 |
+
"version": "0.2.0",
|
4 |
+
"description": "Routes requests to KV assets",
|
5 |
+
"main": "dist/index.js",
|
6 |
+
"types": "dist/index.d.ts",
|
7 |
+
"scripts": {
|
8 |
+
"prepack": "npm run build",
|
9 |
+
"build": "tsc -d",
|
10 |
+
"format": "prettier --write \"**/*.{js,ts,json,md}\"",
|
11 |
+
"pretest": "npm run build",
|
12 |
+
"lint:code": "prettier --check \"**/*.{js,ts,json,md}\"",
|
13 |
+
"lint:markdown": "markdownlint \"**/*.md\" --ignore node_modules",
|
14 |
+
"test": "ava dist/test/*.js --verbose"
|
15 |
+
},
|
16 |
+
"repository": {
|
17 |
+
"type": "git",
|
18 |
+
"url": "git+https://github.com/cloudflare/kv-asset-handler.git"
|
19 |
+
},
|
20 |
+
"keywords": [
|
21 |
+
"kv",
|
22 |
+
"cloudflare",
|
23 |
+
"workers",
|
24 |
+
"wrangler",
|
25 |
+
"assets"
|
26 |
+
],
|
27 |
+
"files": [
|
28 |
+
"src",
|
29 |
+
"dist",
|
30 |
+
"LICENSE_APACHE",
|
31 |
+
"LICENSE_MIT"
|
32 |
+
],
|
33 |
+
"author": "[email protected]",
|
34 |
+
"license": "MIT OR Apache-2.0",
|
35 |
+
"bugs": {
|
36 |
+
"url": "https://github.com/cloudflare/kv-asset-handler/issues"
|
37 |
+
},
|
38 |
+
"homepage": "https://github.com/cloudflare/kv-asset-handler#readme",
|
39 |
+
"dependencies": {
|
40 |
+
"mime": "^3.0.0"
|
41 |
+
},
|
42 |
+
"devDependencies": {
|
43 |
+
"@ava/typescript": "^3.0.0",
|
44 |
+
"@cloudflare/workers-types": "^3.0.0",
|
45 |
+
"@types/mime": "^2.0.3",
|
46 |
+
"@types/node": "^15.14.9",
|
47 |
+
"ava": "^3.15.0",
|
48 |
+
"prettier": "^2.4.1",
|
49 |
+
"service-worker-mock": "^2.0.5",
|
50 |
+
"typescript": "^4.4.4"
|
51 |
+
}
|
52 |
+
}
|
node_modules/@cloudflare/kv-asset-handler/src/index.ts
ADDED
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import * as mime from 'mime'
|
2 |
+
import {
|
3 |
+
Options,
|
4 |
+
CacheControl,
|
5 |
+
MethodNotAllowedError,
|
6 |
+
NotFoundError,
|
7 |
+
InternalError,
|
8 |
+
AssetManifestType,
|
9 |
+
} from './types'
|
10 |
+
|
11 |
+
declare global {
|
12 |
+
var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: string
|
13 |
+
}
|
14 |
+
|
15 |
+
const defaultCacheControl: CacheControl = {
|
16 |
+
browserTTL: null,
|
17 |
+
edgeTTL: 2 * 60 * 60 * 24, // 2 days
|
18 |
+
bypassCache: false, // do not bypass Cloudflare's cache
|
19 |
+
}
|
20 |
+
|
21 |
+
const parseStringAsObject = <T>(maybeString: string | T): T =>
|
22 |
+
typeof maybeString === 'string' ? (JSON.parse(maybeString) as T) : maybeString
|
23 |
+
|
24 |
+
const getAssetFromKVDefaultOptions: Partial<Options> = {
|
25 |
+
ASSET_NAMESPACE: typeof __STATIC_CONTENT !== 'undefined' ? __STATIC_CONTENT : undefined,
|
26 |
+
ASSET_MANIFEST:
|
27 |
+
typeof __STATIC_CONTENT_MANIFEST !== 'undefined'
|
28 |
+
? parseStringAsObject<AssetManifestType>(__STATIC_CONTENT_MANIFEST)
|
29 |
+
: {},
|
30 |
+
cacheControl: defaultCacheControl,
|
31 |
+
defaultMimeType: 'text/plain',
|
32 |
+
defaultDocument: 'index.html',
|
33 |
+
pathIsEncoded: false,
|
34 |
+
}
|
35 |
+
|
36 |
+
function assignOptions(options?: Partial<Options>): Options {
|
37 |
+
// Assign any missing options passed in to the default
|
38 |
+
// options.mapRequestToAsset is handled manually later
|
39 |
+
return <Options>Object.assign({}, getAssetFromKVDefaultOptions, options)
|
40 |
+
}
|
41 |
+
|
42 |
+
/**
|
43 |
+
* maps the path of incoming request to the request pathKey to look up
|
44 |
+
* in bucket and in cache
|
45 |
+
* e.g. for a path '/' returns '/index.html' which serves
|
46 |
+
* the content of bucket/index.html
|
47 |
+
* @param {Request} request incoming request
|
48 |
+
*/
|
49 |
+
const mapRequestToAsset = (request: Request, options?: Partial<Options>) => {
|
50 |
+
options = assignOptions(options)
|
51 |
+
|
52 |
+
const parsedUrl = new URL(request.url)
|
53 |
+
let pathname = parsedUrl.pathname
|
54 |
+
|
55 |
+
if (pathname.endsWith('/')) {
|
56 |
+
// If path looks like a directory append options.defaultDocument
|
57 |
+
// e.g. If path is /about/ -> /about/index.html
|
58 |
+
pathname = pathname.concat(options.defaultDocument)
|
59 |
+
} else if (!mime.getType(pathname)) {
|
60 |
+
// If path doesn't look like valid content
|
61 |
+
// e.g. /about.me -> /about.me/index.html
|
62 |
+
pathname = pathname.concat('/' + options.defaultDocument)
|
63 |
+
}
|
64 |
+
|
65 |
+
parsedUrl.pathname = pathname
|
66 |
+
return new Request(parsedUrl.toString(), request)
|
67 |
+
}
|
68 |
+
|
69 |
+
/**
|
70 |
+
* maps the path of incoming request to /index.html if it evaluates to
|
71 |
+
* any HTML file.
|
72 |
+
* @param {Request} request incoming request
|
73 |
+
*/
|
74 |
+
function serveSinglePageApp(request: Request, options?: Partial<Options>): Request {
|
75 |
+
options = assignOptions(options)
|
76 |
+
|
77 |
+
// First apply the default handler, which already has logic to detect
|
78 |
+
// paths that should map to HTML files.
|
79 |
+
request = mapRequestToAsset(request, options)
|
80 |
+
|
81 |
+
const parsedUrl = new URL(request.url)
|
82 |
+
|
83 |
+
// Detect if the default handler decided to map to
|
84 |
+
// a HTML file in some specific directory.
|
85 |
+
if (parsedUrl.pathname.endsWith('.html')) {
|
86 |
+
// If expected HTML file was missing, just return the root index.html (or options.defaultDocument)
|
87 |
+
return new Request(`${parsedUrl.origin}/${options.defaultDocument}`, request)
|
88 |
+
} else {
|
89 |
+
// The default handler decided this is not an HTML page. It's probably
|
90 |
+
// an image, CSS, or JS file. Leave it as-is.
|
91 |
+
return request
|
92 |
+
}
|
93 |
+
}
|
94 |
+
|
95 |
+
/**
|
96 |
+
* takes the path of the incoming request, gathers the appropriate content from KV, and returns
|
97 |
+
* the response
|
98 |
+
*
|
99 |
+
* @param {FetchEvent} event the fetch event of the triggered request
|
100 |
+
* @param {{mapRequestToAsset: (string: Request) => Request, cacheControl: {bypassCache:boolean, edgeTTL: number, browserTTL:number}, ASSET_NAMESPACE: any, ASSET_MANIFEST:any}} [options] configurable options
|
101 |
+
* @param {CacheControl} [options.cacheControl] determine how to cache on Cloudflare and the browser
|
102 |
+
* @param {typeof(options.mapRequestToAsset)} [options.mapRequestToAsset] maps the path of incoming request to the request pathKey to look up
|
103 |
+
* @param {Object | string} [options.ASSET_NAMESPACE] the binding to the namespace that script references
|
104 |
+
* @param {any} [options.ASSET_MANIFEST] the map of the key to cache and store in KV
|
105 |
+
* */
|
106 |
+
|
107 |
+
type Evt = {
|
108 |
+
request: Request
|
109 |
+
waitUntil: (promise: Promise<any>) => void
|
110 |
+
}
|
111 |
+
|
112 |
+
const getAssetFromKV = async (event: Evt, options?: Partial<Options>): Promise<Response> => {
|
113 |
+
options = assignOptions(options)
|
114 |
+
|
115 |
+
const request = event.request
|
116 |
+
const ASSET_NAMESPACE = options.ASSET_NAMESPACE
|
117 |
+
const ASSET_MANIFEST = parseStringAsObject<AssetManifestType>(options.ASSET_MANIFEST)
|
118 |
+
|
119 |
+
if (typeof ASSET_NAMESPACE === 'undefined') {
|
120 |
+
throw new InternalError(`there is no KV namespace bound to the script`)
|
121 |
+
}
|
122 |
+
|
123 |
+
const rawPathKey = new URL(request.url).pathname.replace(/^\/+/, '') // strip any preceding /'s
|
124 |
+
let pathIsEncoded = options.pathIsEncoded
|
125 |
+
let requestKey
|
126 |
+
// if options.mapRequestToAsset is explicitly passed in, always use it and assume user has own intentions
|
127 |
+
// otherwise handle request as normal, with default mapRequestToAsset below
|
128 |
+
if (options.mapRequestToAsset) {
|
129 |
+
requestKey = options.mapRequestToAsset(request)
|
130 |
+
} else if (ASSET_MANIFEST[rawPathKey]) {
|
131 |
+
requestKey = request
|
132 |
+
} else if (ASSET_MANIFEST[decodeURIComponent(rawPathKey)]) {
|
133 |
+
pathIsEncoded = true
|
134 |
+
requestKey = request
|
135 |
+
} else {
|
136 |
+
const mappedRequest = mapRequestToAsset(request)
|
137 |
+
const mappedRawPathKey = new URL(mappedRequest.url).pathname.replace(/^\/+/, '')
|
138 |
+
if (ASSET_MANIFEST[decodeURIComponent(mappedRawPathKey)]) {
|
139 |
+
pathIsEncoded = true
|
140 |
+
requestKey = mappedRequest
|
141 |
+
} else {
|
142 |
+
// use default mapRequestToAsset
|
143 |
+
requestKey = mapRequestToAsset(request, options)
|
144 |
+
}
|
145 |
+
}
|
146 |
+
|
147 |
+
const SUPPORTED_METHODS = ['GET', 'HEAD']
|
148 |
+
if (!SUPPORTED_METHODS.includes(requestKey.method)) {
|
149 |
+
throw new MethodNotAllowedError(`${requestKey.method} is not a valid request method`)
|
150 |
+
}
|
151 |
+
|
152 |
+
const parsedUrl = new URL(requestKey.url)
|
153 |
+
const pathname = pathIsEncoded ? decodeURIComponent(parsedUrl.pathname) : parsedUrl.pathname // decode percentage encoded path only when necessary
|
154 |
+
|
155 |
+
// pathKey is the file path to look up in the manifest
|
156 |
+
let pathKey = pathname.replace(/^\/+/, '') // remove prepended /
|
157 |
+
|
158 |
+
// @ts-ignore
|
159 |
+
const cache = caches.default
|
160 |
+
let mimeType = mime.getType(pathKey) || options.defaultMimeType
|
161 |
+
if (mimeType.startsWith('text') || mimeType === 'application/javascript') {
|
162 |
+
mimeType += '; charset=utf-8'
|
163 |
+
}
|
164 |
+
|
165 |
+
let shouldEdgeCache = false // false if storing in KV by raw file path i.e. no hash
|
166 |
+
// check manifest for map from file path to hash
|
167 |
+
if (typeof ASSET_MANIFEST !== 'undefined') {
|
168 |
+
if (ASSET_MANIFEST[pathKey]) {
|
169 |
+
pathKey = ASSET_MANIFEST[pathKey]
|
170 |
+
// if path key is in asset manifest, we can assume it contains a content hash and can be cached
|
171 |
+
shouldEdgeCache = true
|
172 |
+
}
|
173 |
+
}
|
174 |
+
|
175 |
+
// TODO this excludes search params from cache, investigate ideal behavior
|
176 |
+
let cacheKey = new Request(`${parsedUrl.origin}/${pathKey}`, request)
|
177 |
+
|
178 |
+
// if argument passed in for cacheControl is a function then
|
179 |
+
// evaluate that function. otherwise return the Object passed in
|
180 |
+
// or default Object
|
181 |
+
const evalCacheOpts = (() => {
|
182 |
+
switch (typeof options.cacheControl) {
|
183 |
+
case 'function':
|
184 |
+
return options.cacheControl(request)
|
185 |
+
case 'object':
|
186 |
+
return options.cacheControl
|
187 |
+
default:
|
188 |
+
return defaultCacheControl
|
189 |
+
}
|
190 |
+
})()
|
191 |
+
|
192 |
+
// formats the etag depending on the response context. if the entityId
|
193 |
+
// is invalid, returns an empty string (instead of null) to prevent the
|
194 |
+
// the potentially disastrous scenario where the value of the Etag resp
|
195 |
+
// header is "null". Could be modified in future to base64 encode etc
|
196 |
+
const formatETag = (entityId: any = pathKey, validatorType: string = 'strong') => {
|
197 |
+
if (!entityId) {
|
198 |
+
return ''
|
199 |
+
}
|
200 |
+
switch (validatorType) {
|
201 |
+
case 'weak':
|
202 |
+
if (!entityId.startsWith('W/')) {
|
203 |
+
return `W/${entityId}`
|
204 |
+
}
|
205 |
+
return entityId
|
206 |
+
case 'strong':
|
207 |
+
if (entityId.startsWith(`W/"`)) {
|
208 |
+
entityId = entityId.replace('W/', '')
|
209 |
+
}
|
210 |
+
if (!entityId.endsWith(`"`)) {
|
211 |
+
entityId = `"${entityId}"`
|
212 |
+
}
|
213 |
+
return entityId
|
214 |
+
default:
|
215 |
+
return ''
|
216 |
+
}
|
217 |
+
}
|
218 |
+
|
219 |
+
options.cacheControl = Object.assign({}, defaultCacheControl, evalCacheOpts)
|
220 |
+
|
221 |
+
// override shouldEdgeCache if options say to bypassCache
|
222 |
+
if (
|
223 |
+
options.cacheControl.bypassCache ||
|
224 |
+
options.cacheControl.edgeTTL === null ||
|
225 |
+
request.method == 'HEAD'
|
226 |
+
) {
|
227 |
+
shouldEdgeCache = false
|
228 |
+
}
|
229 |
+
// only set max-age if explicitly passed in a number as an arg
|
230 |
+
const shouldSetBrowserCache = typeof options.cacheControl.browserTTL === 'number'
|
231 |
+
|
232 |
+
let response = null
|
233 |
+
if (shouldEdgeCache) {
|
234 |
+
response = await cache.match(cacheKey)
|
235 |
+
}
|
236 |
+
|
237 |
+
if (response) {
|
238 |
+
if (response.status > 300 && response.status < 400) {
|
239 |
+
if (response.body && 'cancel' in Object.getPrototypeOf(response.body)) {
|
240 |
+
// Body exists and environment supports readable streams
|
241 |
+
response.body.cancel()
|
242 |
+
} else {
|
243 |
+
// Environment doesnt support readable streams, or null repsonse body. Nothing to do
|
244 |
+
}
|
245 |
+
response = new Response(null, response)
|
246 |
+
} else {
|
247 |
+
// fixes #165
|
248 |
+
let opts = {
|
249 |
+
headers: new Headers(response.headers),
|
250 |
+
status: 0,
|
251 |
+
statusText: '',
|
252 |
+
}
|
253 |
+
|
254 |
+
opts.headers.set('cf-cache-status', 'HIT')
|
255 |
+
|
256 |
+
if (response.status) {
|
257 |
+
opts.status = response.status
|
258 |
+
opts.statusText = response.statusText
|
259 |
+
} else if (opts.headers.has('Content-Range')) {
|
260 |
+
opts.status = 206
|
261 |
+
opts.statusText = 'Partial Content'
|
262 |
+
} else {
|
263 |
+
opts.status = 200
|
264 |
+
opts.statusText = 'OK'
|
265 |
+
}
|
266 |
+
response = new Response(response.body, opts)
|
267 |
+
}
|
268 |
+
} else {
|
269 |
+
const body = await ASSET_NAMESPACE.get(pathKey, 'arrayBuffer')
|
270 |
+
if (body === null) {
|
271 |
+
throw new NotFoundError(`could not find ${pathKey} in your content namespace`)
|
272 |
+
}
|
273 |
+
response = new Response(body)
|
274 |
+
|
275 |
+
if (shouldEdgeCache) {
|
276 |
+
response.headers.set('Accept-Ranges', 'bytes')
|
277 |
+
response.headers.set('Content-Length', body.length)
|
278 |
+
// set etag before cache insertion
|
279 |
+
if (!response.headers.has('etag')) {
|
280 |
+
response.headers.set('etag', formatETag(pathKey, 'strong'))
|
281 |
+
}
|
282 |
+
// determine Cloudflare cache behavior
|
283 |
+
response.headers.set('Cache-Control', `max-age=${options.cacheControl.edgeTTL}`)
|
284 |
+
event.waitUntil(cache.put(cacheKey, response.clone()))
|
285 |
+
response.headers.set('CF-Cache-Status', 'MISS')
|
286 |
+
}
|
287 |
+
}
|
288 |
+
response.headers.set('Content-Type', mimeType)
|
289 |
+
|
290 |
+
if (response.status === 304) {
|
291 |
+
let etag = formatETag(response.headers.get('etag'), 'strong')
|
292 |
+
let ifNoneMatch = cacheKey.headers.get('if-none-match')
|
293 |
+
let proxyCacheStatus = response.headers.get('CF-Cache-Status')
|
294 |
+
if (etag) {
|
295 |
+
if (ifNoneMatch && ifNoneMatch === etag && proxyCacheStatus === 'MISS') {
|
296 |
+
response.headers.set('CF-Cache-Status', 'EXPIRED')
|
297 |
+
} else {
|
298 |
+
response.headers.set('CF-Cache-Status', 'REVALIDATED')
|
299 |
+
}
|
300 |
+
response.headers.set('etag', formatETag(etag, 'weak'))
|
301 |
+
}
|
302 |
+
}
|
303 |
+
if (shouldSetBrowserCache) {
|
304 |
+
response.headers.set('Cache-Control', `max-age=${options.cacheControl.browserTTL}`)
|
305 |
+
} else {
|
306 |
+
response.headers.delete('Cache-Control')
|
307 |
+
}
|
308 |
+
return response
|
309 |
+
}
|
310 |
+
|
311 |
+
export { getAssetFromKV, mapRequestToAsset, serveSinglePageApp }
|
312 |
+
export { Options, CacheControl, MethodNotAllowedError, NotFoundError, InternalError }
|
node_modules/@cloudflare/kv-asset-handler/src/mocks.ts
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const makeServiceWorkerEnv = require('service-worker-mock')
|
2 |
+
|
3 |
+
const HASH = '123HASHBROWN'
|
4 |
+
|
5 |
+
export const getEvent = (request: Request): any => {
|
6 |
+
const waitUntil = async (callback: any) => {
|
7 |
+
await callback
|
8 |
+
}
|
9 |
+
return {
|
10 |
+
request,
|
11 |
+
waitUntil,
|
12 |
+
}
|
13 |
+
}
|
14 |
+
const store: any = {
|
15 |
+
'key1.123HASHBROWN.txt': 'val1',
|
16 |
+
'key1.123HASHBROWN.png': 'val1',
|
17 |
+
'index.123HASHBROWN.html': 'index.html',
|
18 |
+
'cache.123HASHBROWN.html': 'cache me if you can',
|
19 |
+
'测试.123HASHBROWN.html': 'My filename is non-ascii',
|
20 |
+
'%not-really-percent-encoded.123HASHBROWN.html': 'browser percent encoded',
|
21 |
+
'%2F.123HASHBROWN.html': 'user percent encoded',
|
22 |
+
'你好.123HASHBROWN.html': 'I shouldnt be served',
|
23 |
+
'%E4%BD%A0%E5%A5%BD.123HASHBROWN.html': 'Im important',
|
24 |
+
'nohash.txt': 'no hash but still got some result',
|
25 |
+
'sub/blah.123HASHBROWN.png': 'picturedis',
|
26 |
+
'sub/index.123HASHBROWN.html': 'picturedis',
|
27 |
+
'client.123HASHBROWN': 'important file',
|
28 |
+
'client.123HASHBROWN/index.html': 'Im here but serve my big bro above',
|
29 |
+
'image.123HASHBROWN.png': 'imagepng',
|
30 |
+
'image.123HASHBROWN.webp': 'imagewebp',
|
31 |
+
'你好/index.123HASHBROWN.html': 'My path is non-ascii',
|
32 |
+
}
|
33 |
+
export const mockKV = (store: any) => {
|
34 |
+
return {
|
35 |
+
get: (path: string) => store[path] || null,
|
36 |
+
}
|
37 |
+
}
|
38 |
+
|
39 |
+
export const mockManifest = () => {
|
40 |
+
return JSON.stringify({
|
41 |
+
'key1.txt': `key1.${HASH}.txt`,
|
42 |
+
'key1.png': `key1.${HASH}.png`,
|
43 |
+
'cache.html': `cache.${HASH}.html`,
|
44 |
+
'测试.html': `测试.${HASH}.html`,
|
45 |
+
'你好.html': `你好.${HASH}.html`,
|
46 |
+
'%not-really-percent-encoded.html': `%not-really-percent-encoded.${HASH}.html`,
|
47 |
+
'%2F.html': `%2F.${HASH}.html`,
|
48 |
+
'%E4%BD%A0%E5%A5%BD.html': `%E4%BD%A0%E5%A5%BD.${HASH}.html`,
|
49 |
+
'index.html': `index.${HASH}.html`,
|
50 |
+
'sub/blah.png': `sub/blah.${HASH}.png`,
|
51 |
+
'sub/index.html': `sub/index.${HASH}.html`,
|
52 |
+
client: `client.${HASH}`,
|
53 |
+
'client/index.html': `client.${HASH}`,
|
54 |
+
'image.png': `image.${HASH}.png`,
|
55 |
+
'image.webp': `image.${HASH}.webp`,
|
56 |
+
'你好/index.html': `你好/index.${HASH}.html`,
|
57 |
+
})
|
58 |
+
}
|
59 |
+
|
60 |
+
let cacheStore: any = new Map()
|
61 |
+
interface CacheKey {
|
62 |
+
url: object
|
63 |
+
headers: object
|
64 |
+
}
|
65 |
+
export const mockCaches = () => {
|
66 |
+
return {
|
67 |
+
default: {
|
68 |
+
async match(key: any) {
|
69 |
+
let cacheKey: CacheKey = {
|
70 |
+
url: key.url,
|
71 |
+
headers: {},
|
72 |
+
}
|
73 |
+
let response
|
74 |
+
if (key.headers.has('if-none-match')) {
|
75 |
+
let makeStrongEtag = key.headers.get('if-none-match').replace('W/', '')
|
76 |
+
Reflect.set(cacheKey.headers, 'etag', makeStrongEtag)
|
77 |
+
response = cacheStore.get(JSON.stringify(cacheKey))
|
78 |
+
} else {
|
79 |
+
// if client doesn't send if-none-match, we need to iterate through these keys
|
80 |
+
// and just test the URL
|
81 |
+
const activeCacheKeys: Array<string> = Array.from(cacheStore.keys())
|
82 |
+
for (const cacheStoreKey of activeCacheKeys) {
|
83 |
+
if (JSON.parse(cacheStoreKey).url === key.url) {
|
84 |
+
response = cacheStore.get(cacheStoreKey)
|
85 |
+
}
|
86 |
+
}
|
87 |
+
}
|
88 |
+
// TODO: write test to accomodate for rare scenarios with where range requests accomodate etags
|
89 |
+
if (response && !key.headers.has('if-none-match')) {
|
90 |
+
// this appears overly verbose, but is necessary to document edge cache behavior
|
91 |
+
// The Range request header triggers the response header Content-Range ...
|
92 |
+
const range = key.headers.get('range')
|
93 |
+
if (range) {
|
94 |
+
response.headers.set(
|
95 |
+
'content-range',
|
96 |
+
`bytes ${range.split('=').pop()}/${response.headers.get('content-length')}`,
|
97 |
+
)
|
98 |
+
}
|
99 |
+
// ... which we are using in this repository to set status 206
|
100 |
+
if (response.headers.has('content-range')) {
|
101 |
+
response.status = 206
|
102 |
+
} else {
|
103 |
+
response.status = 200
|
104 |
+
}
|
105 |
+
let etag = response.headers.get('etag')
|
106 |
+
if (etag && !etag.includes('W/')) {
|
107 |
+
response.headers.set('etag', `W/${etag}`)
|
108 |
+
}
|
109 |
+
}
|
110 |
+
return response
|
111 |
+
},
|
112 |
+
async put(key: any, val: Response) {
|
113 |
+
let headers = new Headers(val.headers)
|
114 |
+
let url = new URL(key.url)
|
115 |
+
let resWithBody = new Response(val.body, { headers, status: 200 })
|
116 |
+
let resNoBody = new Response(null, { headers, status: 304 })
|
117 |
+
let cacheKey: CacheKey = {
|
118 |
+
url: key.url,
|
119 |
+
headers: {
|
120 |
+
etag: `"${url.pathname.replace('/', '')}"`,
|
121 |
+
},
|
122 |
+
}
|
123 |
+
cacheStore.set(JSON.stringify(cacheKey), resNoBody)
|
124 |
+
cacheKey.headers = {}
|
125 |
+
cacheStore.set(JSON.stringify(cacheKey), resWithBody)
|
126 |
+
return
|
127 |
+
},
|
128 |
+
},
|
129 |
+
}
|
130 |
+
}
|
131 |
+
|
132 |
+
// mocks functionality used inside worker request
|
133 |
+
export function mockRequestScope() {
|
134 |
+
Object.assign(global, makeServiceWorkerEnv())
|
135 |
+
Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() })
|
136 |
+
Object.assign(global, { __STATIC_CONTENT: mockKV(store) })
|
137 |
+
Object.assign(global, { caches: mockCaches() })
|
138 |
+
}
|
139 |
+
|
140 |
+
// mocks functionality used on global isolate scope. such as the KV namespace bind
|
141 |
+
export function mockGlobalScope() {
|
142 |
+
Object.assign(global, { __STATIC_CONTENT_MANIFEST: mockManifest() })
|
143 |
+
Object.assign(global, { __STATIC_CONTENT: mockKV(store) })
|
144 |
+
}
|
145 |
+
|
146 |
+
export const sleep = (milliseconds: number) => {
|
147 |
+
return new Promise((resolve) => setTimeout(resolve, milliseconds))
|
148 |
+
}
|
node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV-optional.ts
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import test from 'ava'
|
2 |
+
import { mockRequestScope, mockGlobalScope, getEvent, sleep, mockKV, mockManifest } from '../mocks'
|
3 |
+
mockGlobalScope()
|
4 |
+
|
5 |
+
// manually reset manifest global, to test optional behaviour
|
6 |
+
Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined })
|
7 |
+
|
8 |
+
import { getAssetFromKV, mapRequestToAsset } from '../index'
|
9 |
+
|
10 |
+
test('getAssetFromKV return correct val from KV without manifest', async (t) => {
|
11 |
+
mockRequestScope()
|
12 |
+
// manually reset manifest global, to test optional behaviour
|
13 |
+
Object.assign(global, { __STATIC_CONTENT_MANIFEST: undefined })
|
14 |
+
|
15 |
+
const event = getEvent(new Request('https://blah.com/key1.123HASHBROWN.txt'))
|
16 |
+
const res = await getAssetFromKV(event)
|
17 |
+
|
18 |
+
if (res) {
|
19 |
+
t.is(await res.text(), 'val1')
|
20 |
+
t.true(res.headers.get('content-type').includes('text'))
|
21 |
+
} else {
|
22 |
+
t.fail('Response was undefined')
|
23 |
+
}
|
24 |
+
})
|
node_modules/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts
ADDED
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import test from 'ava'
|
2 |
+
import { mockRequestScope, mockGlobalScope, getEvent, sleep, mockKV, mockManifest } from '../mocks'
|
3 |
+
mockGlobalScope()
|
4 |
+
|
5 |
+
import { getAssetFromKV, mapRequestToAsset } from '../index'
|
6 |
+
import { KVError } from '../types'
|
7 |
+
|
8 |
+
test('getAssetFromKV return correct val from KV and default caching', async (t) => {
|
9 |
+
mockRequestScope()
|
10 |
+
const event = getEvent(new Request('https://blah.com/key1.txt'))
|
11 |
+
const res = await getAssetFromKV(event)
|
12 |
+
|
13 |
+
if (res) {
|
14 |
+
t.is(res.headers.get('cache-control'), null)
|
15 |
+
t.is(res.headers.get('cf-cache-status'), 'MISS')
|
16 |
+
t.is(await res.text(), 'val1')
|
17 |
+
t.true(res.headers.get('content-type').includes('text'))
|
18 |
+
} else {
|
19 |
+
t.fail('Response was undefined')
|
20 |
+
}
|
21 |
+
})
|
22 |
+
test('getAssetFromKV evaluated the file matching the extensionless path first /client/ -> client', async (t) => {
|
23 |
+
mockRequestScope()
|
24 |
+
const event = getEvent(new Request(`https://foo.com/client/`))
|
25 |
+
const res = await getAssetFromKV(event)
|
26 |
+
t.is(await res.text(), 'important file')
|
27 |
+
t.true(res.headers.get('content-type').includes('text'))
|
28 |
+
})
|
29 |
+
test('getAssetFromKV evaluated the file matching the extensionless path first /client -> client', async (t) => {
|
30 |
+
mockRequestScope()
|
31 |
+
const event = getEvent(new Request(`https://foo.com/client`))
|
32 |
+
const res = await getAssetFromKV(event)
|
33 |
+
t.is(await res.text(), 'important file')
|
34 |
+
t.true(res.headers.get('content-type').includes('text'))
|
35 |
+
})
|
36 |
+
|
37 |
+
test('getAssetFromKV if not in asset manifest still returns nohash.txt', async (t) => {
|
38 |
+
mockRequestScope()
|
39 |
+
const event = getEvent(new Request('https://blah.com/nohash.txt'))
|
40 |
+
const res = await getAssetFromKV(event)
|
41 |
+
|
42 |
+
if (res) {
|
43 |
+
t.is(await res.text(), 'no hash but still got some result')
|
44 |
+
t.true(res.headers.get('content-type').includes('text'))
|
45 |
+
} else {
|
46 |
+
t.fail('Response was undefined')
|
47 |
+
}
|
48 |
+
})
|
49 |
+
|
50 |
+
test('getAssetFromKV if no asset manifest /client -> client fails', async (t) => {
|
51 |
+
mockRequestScope()
|
52 |
+
const event = getEvent(new Request(`https://foo.com/client`))
|
53 |
+
const error: KVError = await t.throwsAsync(getAssetFromKV(event, { ASSET_MANIFEST: {} }))
|
54 |
+
t.is(error.status, 404)
|
55 |
+
})
|
56 |
+
|
57 |
+
test('getAssetFromKV if sub/ -> sub/index.html served', async (t) => {
|
58 |
+
mockRequestScope()
|
59 |
+
const event = getEvent(new Request(`https://foo.com/sub`))
|
60 |
+
const res = await getAssetFromKV(event)
|
61 |
+
if (res) {
|
62 |
+
t.is(await res.text(), 'picturedis')
|
63 |
+
} else {
|
64 |
+
t.fail('Response was undefined')
|
65 |
+
}
|
66 |
+
})
|
67 |
+
|
68 |
+
test('getAssetFromKV gets index.html by default for / requests', async (t) => {
|
69 |
+
mockRequestScope()
|
70 |
+
const event = getEvent(new Request('https://blah.com/'))
|
71 |
+
const res = await getAssetFromKV(event)
|
72 |
+
|
73 |
+
if (res) {
|
74 |
+
t.is(await res.text(), 'index.html')
|
75 |
+
t.true(res.headers.get('content-type').includes('html'))
|
76 |
+
} else {
|
77 |
+
t.fail('Response was undefined')
|
78 |
+
}
|
79 |
+
})
|
80 |
+
|
81 |
+
test('getAssetFromKV non ASCII path support', async (t) => {
|
82 |
+
mockRequestScope()
|
83 |
+
const event = getEvent(new Request('https://blah.com/测试.html'))
|
84 |
+
const res = await getAssetFromKV(event)
|
85 |
+
|
86 |
+
if (res) {
|
87 |
+
t.is(await res.text(), 'My filename is non-ascii')
|
88 |
+
} else {
|
89 |
+
t.fail('Response was undefined')
|
90 |
+
}
|
91 |
+
})
|
92 |
+
|
93 |
+
test('getAssetFromKV supports browser percent encoded URLs', async (t) => {
|
94 |
+
mockRequestScope()
|
95 |
+
const event = getEvent(new Request('https://example.com/%not-really-percent-encoded.html'))
|
96 |
+
const res = await getAssetFromKV(event)
|
97 |
+
|
98 |
+
if (res) {
|
99 |
+
t.is(await res.text(), 'browser percent encoded')
|
100 |
+
} else {
|
101 |
+
t.fail('Response was undefined')
|
102 |
+
}
|
103 |
+
})
|
104 |
+
|
105 |
+
test('getAssetFromKV supports user percent encoded URLs', async (t) => {
|
106 |
+
mockRequestScope()
|
107 |
+
const event = getEvent(new Request('https://blah.com/%2F.html'))
|
108 |
+
const res = await getAssetFromKV(event)
|
109 |
+
|
110 |
+
if (res) {
|
111 |
+
t.is(await res.text(), 'user percent encoded')
|
112 |
+
} else {
|
113 |
+
t.fail('Response was undefined')
|
114 |
+
}
|
115 |
+
})
|
116 |
+
|
117 |
+
test('getAssetFromKV only decode URL when necessary', async (t) => {
|
118 |
+
mockRequestScope()
|
119 |
+
const event1 = getEvent(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD.html'))
|
120 |
+
const event2 = getEvent(new Request('https://blah.com/你好.html'))
|
121 |
+
const res1 = await getAssetFromKV(event1)
|
122 |
+
const res2 = await getAssetFromKV(event2)
|
123 |
+
|
124 |
+
if (res1 && res2) {
|
125 |
+
t.is(await res1.text(), 'Im important')
|
126 |
+
t.is(await res2.text(), 'Im important')
|
127 |
+
} else {
|
128 |
+
t.fail('Response was undefined')
|
129 |
+
}
|
130 |
+
})
|
131 |
+
|
132 |
+
test('getAssetFromKV Support for user decode url path', async (t) => {
|
133 |
+
mockRequestScope()
|
134 |
+
const event1 = getEvent(new Request('https://blah.com/%E4%BD%A0%E5%A5%BD/'))
|
135 |
+
const event2 = getEvent(new Request('https://blah.com/你好/'))
|
136 |
+
const res1 = await getAssetFromKV(event1)
|
137 |
+
const res2 = await getAssetFromKV(event2)
|
138 |
+
|
139 |
+
if (res1 && res2) {
|
140 |
+
t.is(await res1.text(), 'My path is non-ascii')
|
141 |
+
t.is(await res2.text(), 'My path is non-ascii')
|
142 |
+
} else {
|
143 |
+
t.fail('Response was undefined')
|
144 |
+
}
|
145 |
+
})
|
146 |
+
|
147 |
+
test('getAssetFromKV custom key modifier', async (t) => {
|
148 |
+
mockRequestScope()
|
149 |
+
const event = getEvent(new Request('https://blah.com/docs/sub/blah.png'))
|
150 |
+
|
151 |
+
const customRequestMapper = (request: Request) => {
|
152 |
+
let defaultModifiedRequest = mapRequestToAsset(request)
|
153 |
+
|
154 |
+
let url = new URL(defaultModifiedRequest.url)
|
155 |
+
url.pathname = url.pathname.replace('/docs', '')
|
156 |
+
return new Request(url.toString(), request)
|
157 |
+
}
|
158 |
+
|
159 |
+
const res = await getAssetFromKV(event, { mapRequestToAsset: customRequestMapper })
|
160 |
+
|
161 |
+
if (res) {
|
162 |
+
t.is(await res.text(), 'picturedis')
|
163 |
+
} else {
|
164 |
+
t.fail('Response was undefined')
|
165 |
+
}
|
166 |
+
})
|
167 |
+
|
168 |
+
test('getAssetFromKV request override with existing manifest file', async (t) => {
|
169 |
+
// see https://github.com/cloudflare/kv-asset-handler/pull/159 for more info
|
170 |
+
mockRequestScope()
|
171 |
+
const event = getEvent(new Request('https://blah.com/image.png')) // real file in manifest
|
172 |
+
|
173 |
+
const customRequestMapper = (request: Request) => {
|
174 |
+
let defaultModifiedRequest = mapRequestToAsset(request)
|
175 |
+
|
176 |
+
let url = new URL(defaultModifiedRequest.url)
|
177 |
+
url.pathname = '/image.webp' // other different file in manifest
|
178 |
+
return new Request(url.toString(), request)
|
179 |
+
}
|
180 |
+
|
181 |
+
const res = await getAssetFromKV(event, { mapRequestToAsset: customRequestMapper })
|
182 |
+
|
183 |
+
if (res) {
|
184 |
+
t.is(await res.text(), 'imagewebp')
|
185 |
+
} else {
|
186 |
+
t.fail('Response was undefined')
|
187 |
+
}
|
188 |
+
})
|
189 |
+
|
190 |
+
test('getAssetFromKV when setting browser caching', async (t) => {
|
191 |
+
mockRequestScope()
|
192 |
+
const event = getEvent(new Request('https://blah.com/'))
|
193 |
+
|
194 |
+
const res = await getAssetFromKV(event, { cacheControl: { browserTTL: 22 } })
|
195 |
+
|
196 |
+
if (res) {
|
197 |
+
t.is(res.headers.get('cache-control'), 'max-age=22')
|
198 |
+
} else {
|
199 |
+
t.fail('Response was undefined')
|
200 |
+
}
|
201 |
+
})
|
202 |
+
|
203 |
+
test('getAssetFromKV when setting custom cache setting', async (t) => {
|
204 |
+
mockRequestScope()
|
205 |
+
const event1 = getEvent(new Request('https://blah.com/'))
|
206 |
+
const event2 = getEvent(new Request('https://blah.com/key1.png?blah=34'))
|
207 |
+
const cacheOnlyPngs = (req: Request) => {
|
208 |
+
if (new URL(req.url).pathname.endsWith('.png'))
|
209 |
+
return {
|
210 |
+
browserTTL: 720,
|
211 |
+
edgeTTL: 720,
|
212 |
+
}
|
213 |
+
else
|
214 |
+
return {
|
215 |
+
bypassCache: true,
|
216 |
+
}
|
217 |
+
}
|
218 |
+
|
219 |
+
const res1 = await getAssetFromKV(event1, { cacheControl: cacheOnlyPngs })
|
220 |
+
const res2 = await getAssetFromKV(event2, { cacheControl: cacheOnlyPngs })
|
221 |
+
|
222 |
+
if (res1 && res2) {
|
223 |
+
t.is(res1.headers.get('cache-control'), null)
|
224 |
+
t.true(res2.headers.get('content-type').includes('png'))
|
225 |
+
t.is(res2.headers.get('cache-control'), 'max-age=720')
|
226 |
+
t.is(res2.headers.get('cf-cache-status'), 'MISS')
|
227 |
+
} else {
|
228 |
+
t.fail('Response was undefined')
|
229 |
+
}
|
230 |
+
})
|
231 |
+
test('getAssetFromKV caches on two sequential requests', async (t) => {
|
232 |
+
mockRequestScope()
|
233 |
+
const resourceKey = 'cache.html'
|
234 |
+
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
|
235 |
+
const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`))
|
236 |
+
const event2 = getEvent(
|
237 |
+
new Request(`https://blah.com/${resourceKey}`, {
|
238 |
+
headers: {
|
239 |
+
'if-none-match': `"${resourceVersion}"`,
|
240 |
+
},
|
241 |
+
}),
|
242 |
+
)
|
243 |
+
|
244 |
+
const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720, browserTTL: 720 } })
|
245 |
+
await sleep(1)
|
246 |
+
const res2 = await getAssetFromKV(event2)
|
247 |
+
|
248 |
+
if (res1 && res2) {
|
249 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS')
|
250 |
+
t.is(res1.headers.get('cache-control'), 'max-age=720')
|
251 |
+
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED')
|
252 |
+
} else {
|
253 |
+
t.fail('Response was undefined')
|
254 |
+
}
|
255 |
+
})
|
256 |
+
test('getAssetFromKV does not store max-age on two sequential requests', async (t) => {
|
257 |
+
mockRequestScope()
|
258 |
+
const resourceKey = 'cache.html'
|
259 |
+
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
|
260 |
+
const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`))
|
261 |
+
const event2 = getEvent(
|
262 |
+
new Request(`https://blah.com/${resourceKey}`, {
|
263 |
+
headers: {
|
264 |
+
'if-none-match': `"${resourceVersion}"`,
|
265 |
+
},
|
266 |
+
}),
|
267 |
+
)
|
268 |
+
|
269 |
+
const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } })
|
270 |
+
await sleep(100)
|
271 |
+
const res2 = await getAssetFromKV(event2)
|
272 |
+
|
273 |
+
if (res1 && res2) {
|
274 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS')
|
275 |
+
t.is(res1.headers.get('cache-control'), null)
|
276 |
+
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED')
|
277 |
+
t.is(res2.headers.get('cache-control'), null)
|
278 |
+
} else {
|
279 |
+
t.fail('Response was undefined')
|
280 |
+
}
|
281 |
+
})
|
282 |
+
|
283 |
+
test('getAssetFromKV does not cache on Cloudflare when bypass cache set', async (t) => {
|
284 |
+
mockRequestScope()
|
285 |
+
const event = getEvent(new Request('https://blah.com/'))
|
286 |
+
|
287 |
+
const res = await getAssetFromKV(event, { cacheControl: { bypassCache: true } })
|
288 |
+
|
289 |
+
if (res) {
|
290 |
+
t.is(res.headers.get('cache-control'), null)
|
291 |
+
t.is(res.headers.get('cf-cache-status'), null)
|
292 |
+
} else {
|
293 |
+
t.fail('Response was undefined')
|
294 |
+
}
|
295 |
+
})
|
296 |
+
|
297 |
+
test('getAssetFromKV with no trailing slash on root', async (t) => {
|
298 |
+
mockRequestScope()
|
299 |
+
const event = getEvent(new Request('https://blah.com'))
|
300 |
+
const res = await getAssetFromKV(event)
|
301 |
+
if (res) {
|
302 |
+
t.is(await res.text(), 'index.html')
|
303 |
+
} else {
|
304 |
+
t.fail('Response was undefined')
|
305 |
+
}
|
306 |
+
})
|
307 |
+
|
308 |
+
test('getAssetFromKV with no trailing slash on a subdirectory', async (t) => {
|
309 |
+
mockRequestScope()
|
310 |
+
const event = getEvent(new Request('https://blah.com/sub/blah.png'))
|
311 |
+
const res = await getAssetFromKV(event)
|
312 |
+
if (res) {
|
313 |
+
t.is(await res.text(), 'picturedis')
|
314 |
+
} else {
|
315 |
+
t.fail('Response was undefined')
|
316 |
+
}
|
317 |
+
})
|
318 |
+
|
319 |
+
test('getAssetFromKV no result throws an error', async (t) => {
|
320 |
+
mockRequestScope()
|
321 |
+
const event = getEvent(new Request('https://blah.com/random'))
|
322 |
+
const error: KVError = await t.throwsAsync(getAssetFromKV(event))
|
323 |
+
t.is(error.status, 404)
|
324 |
+
})
|
325 |
+
test('getAssetFromKV TTls set to null should not cache on browser or edge', async (t) => {
|
326 |
+
mockRequestScope()
|
327 |
+
const event = getEvent(new Request('https://blah.com/'))
|
328 |
+
|
329 |
+
const res1 = await getAssetFromKV(event, { cacheControl: { browserTTL: null, edgeTTL: null } })
|
330 |
+
await sleep(100)
|
331 |
+
const res2 = await getAssetFromKV(event, { cacheControl: { browserTTL: null, edgeTTL: null } })
|
332 |
+
|
333 |
+
if (res1 && res2) {
|
334 |
+
t.is(res1.headers.get('cf-cache-status'), null)
|
335 |
+
t.is(res1.headers.get('cache-control'), null)
|
336 |
+
t.is(res2.headers.get('cf-cache-status'), null)
|
337 |
+
t.is(res2.headers.get('cache-control'), null)
|
338 |
+
} else {
|
339 |
+
t.fail('Response was undefined')
|
340 |
+
}
|
341 |
+
})
|
342 |
+
test('getAssetFromKV passing in a custom NAMESPACE serves correct asset', async (t) => {
|
343 |
+
mockRequestScope()
|
344 |
+
let CUSTOM_NAMESPACE = mockKV({
|
345 |
+
'key1.123HASHBROWN.txt': 'val1',
|
346 |
+
})
|
347 |
+
Object.assign(global, { CUSTOM_NAMESPACE })
|
348 |
+
const event = getEvent(new Request('https://blah.com/'))
|
349 |
+
const res = await getAssetFromKV(event)
|
350 |
+
if (res) {
|
351 |
+
t.is(await res.text(), 'index.html')
|
352 |
+
t.true(res.headers.get('content-type').includes('html'))
|
353 |
+
} else {
|
354 |
+
t.fail('Response was undefined')
|
355 |
+
}
|
356 |
+
})
|
357 |
+
test('getAssetFromKV when custom namespace without the asset should fail', async (t) => {
|
358 |
+
mockRequestScope()
|
359 |
+
let CUSTOM_NAMESPACE = mockKV({
|
360 |
+
'key5.123HASHBROWN.txt': 'customvalu',
|
361 |
+
})
|
362 |
+
|
363 |
+
const event = getEvent(new Request('https://blah.com'))
|
364 |
+
const error: KVError = await t.throwsAsync(
|
365 |
+
getAssetFromKV(event, { ASSET_NAMESPACE: CUSTOM_NAMESPACE }),
|
366 |
+
)
|
367 |
+
t.is(error.status, 404)
|
368 |
+
})
|
369 |
+
test('getAssetFromKV when namespace not bound fails', async (t) => {
|
370 |
+
mockRequestScope()
|
371 |
+
var MY_CUSTOM_NAMESPACE = undefined
|
372 |
+
Object.assign(global, { MY_CUSTOM_NAMESPACE })
|
373 |
+
|
374 |
+
const event = getEvent(new Request('https://blah.com/'))
|
375 |
+
const error: KVError = await t.throwsAsync(
|
376 |
+
getAssetFromKV(event, { ASSET_NAMESPACE: MY_CUSTOM_NAMESPACE }),
|
377 |
+
)
|
378 |
+
t.is(error.status, 500)
|
379 |
+
})
|
380 |
+
|
381 |
+
test('getAssetFromKV when if-none-match === active resource version, should revalidate', async (t) => {
|
382 |
+
mockRequestScope()
|
383 |
+
const resourceKey = 'key1.png'
|
384 |
+
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
|
385 |
+
const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`))
|
386 |
+
const event2 = getEvent(
|
387 |
+
new Request(`https://blah.com/${resourceKey}`, {
|
388 |
+
headers: {
|
389 |
+
'if-none-match': `W/"${resourceVersion}"`,
|
390 |
+
},
|
391 |
+
}),
|
392 |
+
)
|
393 |
+
|
394 |
+
const res1 = await getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } })
|
395 |
+
await sleep(100)
|
396 |
+
const res2 = await getAssetFromKV(event2)
|
397 |
+
|
398 |
+
if (res1 && res2) {
|
399 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS')
|
400 |
+
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED')
|
401 |
+
} else {
|
402 |
+
t.fail('Response was undefined')
|
403 |
+
}
|
404 |
+
})
|
405 |
+
|
406 |
+
test('getAssetFromKV when if-none-match equals etag of stale resource then should bypass cache', async (t) => {
|
407 |
+
mockRequestScope()
|
408 |
+
const resourceKey = 'key1.png'
|
409 |
+
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
|
410 |
+
const req1 = new Request(`https://blah.com/${resourceKey}`, {
|
411 |
+
headers: {
|
412 |
+
'if-none-match': `"${resourceVersion}"`,
|
413 |
+
},
|
414 |
+
})
|
415 |
+
const req2 = new Request(`https://blah.com/${resourceKey}`, {
|
416 |
+
headers: {
|
417 |
+
'if-none-match': `"${resourceVersion}-another-version"`,
|
418 |
+
},
|
419 |
+
})
|
420 |
+
const event = getEvent(req1)
|
421 |
+
const event2 = getEvent(req2)
|
422 |
+
const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } })
|
423 |
+
const res2 = await getAssetFromKV(event)
|
424 |
+
const res3 = await getAssetFromKV(event2)
|
425 |
+
if (res1 && res2 && res3) {
|
426 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS')
|
427 |
+
t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`)
|
428 |
+
t.is(res2.headers.get('cf-cache-status'), 'REVALIDATED')
|
429 |
+
t.not(res3.headers.get('etag'), req2.headers.get('if-none-match'))
|
430 |
+
t.is(res3.headers.get('cf-cache-status'), 'MISS')
|
431 |
+
} else {
|
432 |
+
t.fail('Response was undefined')
|
433 |
+
}
|
434 |
+
})
|
435 |
+
test('getAssetFromKV when resource in cache, etag should be weakened before returned to eyeball', async (t) => {
|
436 |
+
mockRequestScope()
|
437 |
+
const resourceKey = 'key1.png'
|
438 |
+
const resourceVersion = JSON.parse(mockManifest())[resourceKey]
|
439 |
+
const req1 = new Request(`https://blah.com/${resourceKey}`, {
|
440 |
+
headers: {
|
441 |
+
'if-none-match': `"${resourceVersion}"`,
|
442 |
+
},
|
443 |
+
})
|
444 |
+
const event = getEvent(req1)
|
445 |
+
const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } })
|
446 |
+
const res2 = await getAssetFromKV(event)
|
447 |
+
if (res1 && res2) {
|
448 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS')
|
449 |
+
t.is(res2.headers.get('etag'), `W/${req1.headers.get('if-none-match')}`)
|
450 |
+
} else {
|
451 |
+
t.fail('Response was undefined')
|
452 |
+
}
|
453 |
+
})
|
454 |
+
|
455 |
+
test('getAssetFromKV if-none-match not sent but resource in cache, should return cache hit 200 OK', async (t) => {
|
456 |
+
const resourceKey = 'cache.html'
|
457 |
+
const event = getEvent(new Request(`https://blah.com/${resourceKey}`))
|
458 |
+
const res1 = await getAssetFromKV(event, { cacheControl: { edgeTTL: 720 } })
|
459 |
+
await sleep(1)
|
460 |
+
const res2 = await getAssetFromKV(event)
|
461 |
+
if (res1 && res2) {
|
462 |
+
t.is(res1.headers.get('cf-cache-status'), 'MISS')
|
463 |
+
t.is(res1.headers.get('cache-control'), null)
|
464 |
+
t.is(res2.status, 200)
|
465 |
+
t.is(res2.headers.get('cf-cache-status'), 'HIT')
|
466 |
+
} else {
|
467 |
+
t.fail('Response was undefined')
|
468 |
+
}
|
469 |
+
})
|
470 |
+
|
471 |
+
test('getAssetFromKV if range request submitted and resource in cache, request fulfilled', async (t) => {
|
472 |
+
const resourceKey = 'cache.html'
|
473 |
+
const event1 = getEvent(new Request(`https://blah.com/${resourceKey}`))
|
474 |
+
const event2 = getEvent(
|
475 |
+
new Request(`https://blah.com/${resourceKey}`, { headers: { range: 'bytes=0-10' } }),
|
476 |
+
)
|
477 |
+
const res1 = getAssetFromKV(event1, { cacheControl: { edgeTTL: 720 } })
|
478 |
+
await res1
|
479 |
+
await sleep(2)
|
480 |
+
const res2 = await getAssetFromKV(event2)
|
481 |
+
if (res2.headers.has('content-range')) {
|
482 |
+
t.is(res2.status, 206)
|
483 |
+
} else {
|
484 |
+
t.fail('Response was undefined')
|
485 |
+
}
|
486 |
+
})
|
487 |
+
|
488 |
+
test.todo('getAssetFromKV when body not empty, should invoke .cancel()')
|
node_modules/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import test from 'ava'
|
2 |
+
import { mockRequestScope, mockGlobalScope } from '../mocks'
|
3 |
+
mockGlobalScope()
|
4 |
+
|
5 |
+
import { mapRequestToAsset } from '../index'
|
6 |
+
|
7 |
+
test('mapRequestToAsset() correctly changes /about -> /about/index.html', async (t) => {
|
8 |
+
mockRequestScope()
|
9 |
+
let path = '/about'
|
10 |
+
let request = new Request(`https://foo.com${path}`)
|
11 |
+
let newRequest = mapRequestToAsset(request)
|
12 |
+
t.is(newRequest.url, request.url + '/index.html')
|
13 |
+
})
|
14 |
+
|
15 |
+
test('mapRequestToAsset() correctly changes /about/ -> /about/index.html', async (t) => {
|
16 |
+
mockRequestScope()
|
17 |
+
let path = '/about/'
|
18 |
+
let request = new Request(`https://foo.com${path}`)
|
19 |
+
let newRequest = mapRequestToAsset(request)
|
20 |
+
t.is(newRequest.url, request.url + 'index.html')
|
21 |
+
})
|
22 |
+
|
23 |
+
test('mapRequestToAsset() correctly changes /about.me/ -> /about.me/index.html', async (t) => {
|
24 |
+
mockRequestScope()
|
25 |
+
let path = '/about.me/'
|
26 |
+
let request = new Request(`https://foo.com${path}`)
|
27 |
+
let newRequest = mapRequestToAsset(request)
|
28 |
+
t.is(newRequest.url, request.url + 'index.html')
|
29 |
+
})
|
30 |
+
|
31 |
+
test('mapRequestToAsset() correctly changes /about -> /about/default.html', async (t) => {
|
32 |
+
mockRequestScope()
|
33 |
+
let path = '/about'
|
34 |
+
let request = new Request(`https://foo.com${path}`)
|
35 |
+
let newRequest = mapRequestToAsset(request, { defaultDocument: 'default.html' })
|
36 |
+
t.is(newRequest.url, request.url + '/default.html')
|
37 |
+
})
|
node_modules/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import test from 'ava'
|
2 |
+
import { mockRequestScope, mockGlobalScope } from '../mocks'
|
3 |
+
mockGlobalScope()
|
4 |
+
|
5 |
+
import { serveSinglePageApp } from '../index'
|
6 |
+
|
7 |
+
function testRequest(path: string) {
|
8 |
+
mockRequestScope()
|
9 |
+
let url = new URL('https://example.com')
|
10 |
+
url.pathname = path
|
11 |
+
let request = new Request(url.toString())
|
12 |
+
|
13 |
+
return request
|
14 |
+
}
|
15 |
+
|
16 |
+
test('serveSinglePageApp returns root asset path when request path ends in .html', async (t) => {
|
17 |
+
let path = '/foo/thing.html'
|
18 |
+
let request = testRequest(path)
|
19 |
+
|
20 |
+
let expected_request = testRequest('/index.html')
|
21 |
+
let actual_request = serveSinglePageApp(request)
|
22 |
+
|
23 |
+
t.deepEqual(expected_request, actual_request)
|
24 |
+
})
|
25 |
+
|
26 |
+
test('serveSinglePageApp returns root asset path when request path does not have extension', async (t) => {
|
27 |
+
let path = '/foo/thing'
|
28 |
+
let request = testRequest(path)
|
29 |
+
|
30 |
+
let expected_request = testRequest('/index.html')
|
31 |
+
let actual_request = serveSinglePageApp(request)
|
32 |
+
|
33 |
+
t.deepEqual(expected_request, actual_request)
|
34 |
+
})
|
35 |
+
|
36 |
+
test('serveSinglePageApp returns requested asset when request path has non-html extension', async (t) => {
|
37 |
+
let path = '/foo/thing.js'
|
38 |
+
let request = testRequest(path)
|
39 |
+
|
40 |
+
let expected_request = request
|
41 |
+
let actual_request = serveSinglePageApp(request)
|
42 |
+
|
43 |
+
t.deepEqual(expected_request, actual_request)
|
44 |
+
})
|
node_modules/@cloudflare/kv-asset-handler/src/types.ts
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
export type CacheControl = {
|
2 |
+
browserTTL: number
|
3 |
+
edgeTTL: number
|
4 |
+
bypassCache: boolean
|
5 |
+
}
|
6 |
+
|
7 |
+
export type AssetManifestType = Record<string, string>
|
8 |
+
|
9 |
+
export type Options = {
|
10 |
+
cacheControl: ((req: Request) => Partial<CacheControl>) | Partial<CacheControl>
|
11 |
+
ASSET_NAMESPACE: any
|
12 |
+
ASSET_MANIFEST: AssetManifestType | string
|
13 |
+
mapRequestToAsset?: (req: Request, options?: Partial<Options>) => Request
|
14 |
+
defaultMimeType: string
|
15 |
+
defaultDocument: string
|
16 |
+
pathIsEncoded: boolean
|
17 |
+
}
|
18 |
+
|
19 |
+
export class KVError extends Error {
|
20 |
+
constructor(message?: string, status: number = 500) {
|
21 |
+
super(message)
|
22 |
+
// see: typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html
|
23 |
+
Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain
|
24 |
+
this.name = KVError.name // stack traces display correctly now
|
25 |
+
this.status = status
|
26 |
+
}
|
27 |
+
status: number
|
28 |
+
}
|
29 |
+
export class MethodNotAllowedError extends KVError {
|
30 |
+
constructor(message: string = `Not a valid request method`, status: number = 405) {
|
31 |
+
super(message, status)
|
32 |
+
}
|
33 |
+
}
|
34 |
+
export class NotFoundError extends KVError {
|
35 |
+
constructor(message: string = `Not Found`, status: number = 404) {
|
36 |
+
super(message, status)
|
37 |
+
}
|
38 |
+
}
|
39 |
+
export class InternalError extends KVError {
|
40 |
+
constructor(message: string = `Internal Error in KV Asset Handler`, status: number = 500) {
|
41 |
+
super(message, status)
|
42 |
+
}
|
43 |
+
}
|
node_modules/@cloudflare/workerd-linux-64/README.md
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 👷 `workerd` for Linux 64-bit, Cloudflare's JavaScript/Wasm Runtime
|
2 |
+
|
3 |
+
`workerd` is a JavaScript / Wasm server runtime based on the same code that powers
|
4 |
+
[Cloudflare Workers](https://workers.dev).
|
5 |
+
|
6 |
+
See https://github.com/cloudflare/workerd for details.
|
node_modules/@cloudflare/workerd-linux-64/bin/workerd
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:38e89c01a468df1cd48bfdc6eb9ac9eacb4c07d106fb5fa88ac13a1fdce6910e
|
3 |
+
size 88115856
|
node_modules/@cloudflare/workerd-linux-64/package.json
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name": "@cloudflare/workerd-linux-64",
|
3 |
+
"description": "👷 workerd for Linux 64-bit, Cloudflare's JavaScript/Wasm Runtime",
|
4 |
+
"repository": "https://github.com/cloudflare/workerd",
|
5 |
+
"license": "Apache-2.0",
|
6 |
+
"preferUnplugged": false,
|
7 |
+
"engines": {
|
8 |
+
"node": ">=16"
|
9 |
+
},
|
10 |
+
"os": [
|
11 |
+
"linux"
|
12 |
+
],
|
13 |
+
"cpu": [
|
14 |
+
"x64"
|
15 |
+
],
|
16 |
+
"version": "1.20231030.0"
|
17 |
+
}
|
node_modules/@cypress/request-promise/.circleci/config.yml
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
version: 2.1
|
2 |
+
jobs:
|
3 |
+
test:
|
4 |
+
docker:
|
5 |
+
- image: circleci/node:11.5.0
|
6 |
+
working_directory: ~/repo
|
7 |
+
steps:
|
8 |
+
- checkout
|
9 |
+
|
10 |
+
- restore_cache:
|
11 |
+
keys:
|
12 |
+
- v1-dependencies-{{ checksum "package.json" }}
|
13 |
+
- v1-dependencies-
|
14 |
+
- run: yarn install
|
15 |
+
- save_cache:
|
16 |
+
paths:
|
17 |
+
- node_modules
|
18 |
+
key: v1-dependencies-{{ checksum "package.json" }}
|
19 |
+
- run: yarn test
|
20 |
+
|
21 |
+
release:
|
22 |
+
docker:
|
23 |
+
- image: cimg/node:18.12.1
|
24 |
+
steps:
|
25 |
+
- checkout
|
26 |
+
- restore_cache:
|
27 |
+
keys:
|
28 |
+
- v1-dependencies-{{ checksum "package.json" }}
|
29 |
+
- v1-dependencies-
|
30 |
+
- run: yarn install
|
31 |
+
- run: npx semantic-release
|
32 |
+
|
33 |
+
workflows:
|
34 |
+
version: 2.1
|
35 |
+
test_and_release:
|
36 |
+
jobs:
|
37 |
+
- test
|
38 |
+
- release:
|
39 |
+
context:
|
40 |
+
- test-runner:npm-release
|
41 |
+
requires:
|
42 |
+
- test
|
43 |
+
filters:
|
44 |
+
branches:
|
45 |
+
only:
|
46 |
+
- master
|
node_modules/@cypress/request-promise/LICENSE
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ISC License
|
2 |
+
|
3 |
+
Copyright (c) 2019, Nicolai Kamenzky, Ty Abonil, and contributors
|
4 |
+
|
5 |
+
Permission to use, copy, modify, and/or distribute this software for any
|
6 |
+
purpose with or without fee is hereby granted, provided that the above
|
7 |
+
copyright notice and this permission notice appear in all copies.
|
8 |
+
|
9 |
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
10 |
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
11 |
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
12 |
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
13 |
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
14 |
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
15 |
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
node_modules/@cypress/request-promise/README.md
ADDED
@@ -0,0 +1,760 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<a href="http://promisesaplus.com/">
|
2 |
+
<img src="https://promises-aplus.github.io/promises-spec/assets/logo-small.png" align="right" alt="Promises/A+ logo" />
|
3 |
+
</a>
|
4 |
+
|
5 |
+
# Request-Promise
|
6 |
+
|
7 |
+
[![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square&maxAge=2592000)](https://gitter.im/request/request-promise?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
8 |
+
[![Build Status](https://img.shields.io/travis/request/request-promise/master.svg?style=flat-square&maxAge=2592000)](https://travis-ci.org/request/request-promise)
|
9 |
+
[![Coverage Status](https://img.shields.io/coveralls/request/request-promise.svg?style=flat-square&maxAge=2592000)](https://coveralls.io/r/request/request-promise)
|
10 |
+
[![Dependency Status](https://img.shields.io/david/request/request-promise.svg?style=flat-square&maxAge=2592000)](https://david-dm.org/request/request-promise)
|
11 |
+
[![Known Vulnerabilities](https://snyk.io/test/npm/request-promise/badge.svg?style=flat-square&maxAge=2592000)](https://snyk.io/test/npm/request-promise)
|
12 |
+
|
13 |
+
# Deprecated!
|
14 |
+
|
15 |
+
As of Feb 11th 2020, [`request`](https://github.com/request/request) is fully deprecated. No new changes are expected to land. In fact, none have landed for some time. This package is also deprecated because it depends on `request`.
|
16 |
+
|
17 |
+
Fyi, here is the [reasoning of `request`'s deprecation](https://github.com/request/request/issues/3142) and a [list of alternative libraries](https://github.com/request/request/issues/3143).
|
18 |
+
|
19 |
+
---
|
20 |
+
|
21 |
+
The simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
|
22 |
+
|
23 |
+
[Request](https://github.com/request/request) and [Bluebird](https://github.com/petkaantonov/bluebird) are pretty awesome, but I found myself using the same design pattern. Request-Promise adds a Bluebird-powered `.then(...)` method to Request call objects. By default, http response codes other than 2xx will cause the promise to be rejected. This can be overwritten by setting `options.simple = false`.
|
24 |
+
|
25 |
+
Also check out the new libraries that are **very similar to `request-promise` v4**:
|
26 |
+
- [`request-promise-native`](https://github.com/request/request-promise-native) v1 – Does not depend on Bluebird and uses native ES6 promises instead.
|
27 |
+
- [`request-promise-any`](https://github.com/request/request-promise-any) v1 – Allows you to register any Promise library supported by [`any-promise`](https://www.npmjs.com/package/any-promise).
|
28 |
+
|
29 |
+
---
|
30 |
+
|
31 |
+
## Migration from v3 to v4
|
32 |
+
|
33 |
+
1. `request` became a peer dependency. Thus make sure that `request` is installed into your project as a direct dependency. (`npm install --save request`)
|
34 |
+
2. Continuation Local Storage is no longer supported. However, you [can get back the support](https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage) by using `request-promise-any`.
|
35 |
+
3. When you migrated your `transform` function to v3 and had to add `if (!(/^2/.test('' + response.statusCode))) { return resolveWithFullResponse ? response : body; }` you may now set the option `transform2xxOnly = true` instead.
|
36 |
+
|
37 |
+
## Migration from v2 to v3
|
38 |
+
|
39 |
+
1. The handling of the `transform` function got overhauled. This has two effects:
|
40 |
+
- `StatusCodeError.response` is the transformed instead of the original response now. This error is thrown for non-2xx responses when `options.simple` is `true` (default). Please update your `transform` functions to also cover the transformation of non-2xx responses. To get the old behavior you may add `if (!(/^2/.test('' + response.statusCode))) { return resolveWithFullResponse ? response : body; }` to the first line of your `transform` functions that are used for requests with `options.simple === true`. However, you may prefer updating your `transform` functions to being able to transform 2xx as well as non-2xx responses because this decouples their implementation from the use of the `simple` option when doing requests.
|
41 |
+
- If a transform operation throws an error, the request will be rejected with a `TransformError`. Its `cause` attribute contains the error thrown by the transform operation. Previously, the request was rejected directly with the error thrown by the transform operation. Wrapping it into a `TransformError` makes the error handling easier.
|
42 |
+
|
43 |
+
2. Bluebird got updated from v2 to v3. This won't make a difference for most use cases. However, if you use advanced Promise chains starting with the Promise returned by Request-Promise, please check [Bluebird's new features and changes](http://bluebirdjs.com/docs/new-in-bluebird-3.html).
|
44 |
+
|
45 |
+
---
|
46 |
+
|
47 |
+
## Installation
|
48 |
+
|
49 |
+
This module is installed via npm:
|
50 |
+
|
51 |
+
```
|
52 |
+
npm install --save request
|
53 |
+
npm install --save request-promise
|
54 |
+
```
|
55 |
+
|
56 |
+
`request` is defined as a peer-dependency and thus has to be installed separately.
|
57 |
+
|
58 |
+
## Cheat Sheet
|
59 |
+
|
60 |
+
``` js
|
61 |
+
var rp = require('request-promise');
|
62 |
+
```
|
63 |
+
|
64 |
+
Since `request-promise` wraps around `request` everything that works with `request` also works with `request-promise`. Also check out the [`request` docs](https://github.com/request/request) for more examples.
|
65 |
+
|
66 |
+
### Crawl a webpage
|
67 |
+
|
68 |
+
``` js
|
69 |
+
rp('http://www.google.com')
|
70 |
+
.then(function (htmlString) {
|
71 |
+
// Process html...
|
72 |
+
})
|
73 |
+
.catch(function (err) {
|
74 |
+
// Crawling failed...
|
75 |
+
});
|
76 |
+
```
|
77 |
+
|
78 |
+
### Crawl a webpage better
|
79 |
+
|
80 |
+
``` js
|
81 |
+
var cheerio = require('cheerio'); // Basically jQuery for node.js
|
82 |
+
|
83 |
+
var options = {
|
84 |
+
uri: 'http://www.google.com',
|
85 |
+
transform: function (body) {
|
86 |
+
return cheerio.load(body);
|
87 |
+
}
|
88 |
+
};
|
89 |
+
|
90 |
+
rp(options)
|
91 |
+
.then(function ($) {
|
92 |
+
// Process html like you would with jQuery...
|
93 |
+
})
|
94 |
+
.catch(function (err) {
|
95 |
+
// Crawling failed or Cheerio choked...
|
96 |
+
});
|
97 |
+
```
|
98 |
+
|
99 |
+
### GET something from a JSON REST API
|
100 |
+
|
101 |
+
``` js
|
102 |
+
var options = {
|
103 |
+
uri: 'https://api.github.com/user/repos',
|
104 |
+
qs: {
|
105 |
+
access_token: 'xxxxx xxxxx' // -> uri + '?access_token=xxxxx%20xxxxx'
|
106 |
+
},
|
107 |
+
headers: {
|
108 |
+
'User-Agent': 'Request-Promise'
|
109 |
+
},
|
110 |
+
json: true // Automatically parses the JSON string in the response
|
111 |
+
};
|
112 |
+
|
113 |
+
rp(options)
|
114 |
+
.then(function (repos) {
|
115 |
+
console.log('User has %d repos', repos.length);
|
116 |
+
})
|
117 |
+
.catch(function (err) {
|
118 |
+
// API call failed...
|
119 |
+
});
|
120 |
+
```
|
121 |
+
|
122 |
+
### POST data to a JSON REST API
|
123 |
+
|
124 |
+
Set `option.body` to your data and `json: true` to encode the body as JSON. See below for HTML forms.
|
125 |
+
|
126 |
+
``` js
|
127 |
+
var options = {
|
128 |
+
method: 'POST',
|
129 |
+
uri: 'http://api.posttestserver.com/post',
|
130 |
+
body: {
|
131 |
+
some: 'payload'
|
132 |
+
},
|
133 |
+
json: true // Automatically stringifies the body to JSON
|
134 |
+
};
|
135 |
+
|
136 |
+
rp(options)
|
137 |
+
.then(function (parsedBody) {
|
138 |
+
// POST succeeded...
|
139 |
+
})
|
140 |
+
.catch(function (err) {
|
141 |
+
// POST failed...
|
142 |
+
});
|
143 |
+
```
|
144 |
+
|
145 |
+
### POST like HTML forms do
|
146 |
+
|
147 |
+
Pass your data to `options.form` to encode the body the same way as HTML forms do:
|
148 |
+
|
149 |
+
``` js
|
150 |
+
var options = {
|
151 |
+
method: 'POST',
|
152 |
+
uri: 'http://posttestserver.com/post.php',
|
153 |
+
form: {
|
154 |
+
// Like <input type="text" name="name">
|
155 |
+
name: 'Josh'
|
156 |
+
},
|
157 |
+
headers: {
|
158 |
+
/* 'content-type': 'application/x-www-form-urlencoded' */ // Is set automatically
|
159 |
+
}
|
160 |
+
};
|
161 |
+
|
162 |
+
rp(options)
|
163 |
+
.then(function (body) {
|
164 |
+
// POST succeeded...
|
165 |
+
})
|
166 |
+
.catch(function (err) {
|
167 |
+
// POST failed...
|
168 |
+
});
|
169 |
+
```
|
170 |
+
|
171 |
+
If you want to include a file upload then use `options.formData`:
|
172 |
+
|
173 |
+
``` js
|
174 |
+
var options = {
|
175 |
+
method: 'POST',
|
176 |
+
uri: 'http://posttestserver.com/post.php',
|
177 |
+
formData: {
|
178 |
+
// Like <input type="text" name="name">
|
179 |
+
name: 'Jenn',
|
180 |
+
// Like <input type="file" name="file">
|
181 |
+
file: {
|
182 |
+
value: fs.createReadStream('test/test.jpg'),
|
183 |
+
options: {
|
184 |
+
filename: 'test.jpg',
|
185 |
+
contentType: 'image/jpg'
|
186 |
+
}
|
187 |
+
}
|
188 |
+
},
|
189 |
+
headers: {
|
190 |
+
/* 'content-type': 'multipart/form-data' */ // Is set automatically
|
191 |
+
}
|
192 |
+
};
|
193 |
+
|
194 |
+
rp(options)
|
195 |
+
.then(function (body) {
|
196 |
+
// POST succeeded...
|
197 |
+
})
|
198 |
+
.catch(function (err) {
|
199 |
+
// POST failed...
|
200 |
+
});
|
201 |
+
```
|
202 |
+
|
203 |
+
### Include a cookie
|
204 |
+
|
205 |
+
``` js
|
206 |
+
var tough = require('tough-cookie');
|
207 |
+
|
208 |
+
// Easy creation of the cookie - see tough-cookie docs for details
|
209 |
+
let cookie = new tough.Cookie({
|
210 |
+
key: "some_key",
|
211 |
+
value: "some_value",
|
212 |
+
domain: 'api.mydomain.com',
|
213 |
+
httpOnly: true,
|
214 |
+
maxAge: 31536000
|
215 |
+
});
|
216 |
+
|
217 |
+
// Put cookie in an jar which can be used across multiple requests
|
218 |
+
var cookiejar = rp.jar();
|
219 |
+
cookiejar.setCookie(cookie, 'https://api.mydomain.com');
|
220 |
+
// ...all requests to https://api.mydomain.com will include the cookie
|
221 |
+
|
222 |
+
var options = {
|
223 |
+
uri: 'https://api.mydomain.com/...',
|
224 |
+
jar: cookiejar // Tells rp to include cookies in jar that match uri
|
225 |
+
};
|
226 |
+
|
227 |
+
rp(options)
|
228 |
+
.then(function (body) {
|
229 |
+
// Request succeeded...
|
230 |
+
})
|
231 |
+
.catch(function (err) {
|
232 |
+
// Request failed...
|
233 |
+
});
|
234 |
+
```
|
235 |
+
|
236 |
+
### Get the full response instead of just the body
|
237 |
+
|
238 |
+
``` js
|
239 |
+
var options = {
|
240 |
+
method: 'DELETE',
|
241 |
+
uri: 'http://my-server/path/to/resource/1234',
|
242 |
+
resolveWithFullResponse: true // <--- <--- <--- <---
|
243 |
+
};
|
244 |
+
|
245 |
+
rp(options)
|
246 |
+
.then(function (response) {
|
247 |
+
console.log("DELETE succeeded with status %d", response.statusCode);
|
248 |
+
})
|
249 |
+
.catch(function (err) {
|
250 |
+
// Delete failed...
|
251 |
+
});
|
252 |
+
```
|
253 |
+
|
254 |
+
### Get a rejection only if the request failed for technical reasons
|
255 |
+
|
256 |
+
``` js
|
257 |
+
var options = {
|
258 |
+
uri: 'http://www.google.com/this-page-does-not-exist.html',
|
259 |
+
simple: false // <--- <--- <--- <---
|
260 |
+
};
|
261 |
+
|
262 |
+
rp(options)
|
263 |
+
.then(function (body) {
|
264 |
+
// Request succeeded but might as well be a 404
|
265 |
+
// Usually combined with resolveWithFullResponse = true to check response.statusCode
|
266 |
+
})
|
267 |
+
.catch(function (err) {
|
268 |
+
// Request failed due to technical reasons...
|
269 |
+
});
|
270 |
+
```
|
271 |
+
|
272 |
+
---
|
273 |
+
|
274 |
+
**For more options checkout the [Request docs](https://github.com/request/request#requestoptions-callback).**
|
275 |
+
|
276 |
+
---
|
277 |
+
|
278 |
+
## API in Detail
|
279 |
+
|
280 |
+
Consider Request-Promise being:
|
281 |
+
|
282 |
+
- A Request object
|
283 |
+
- With an [identical API](https://github.com/request/request): `require('request-promise') == require('request')` so to say
|
284 |
+
- However, **STREAMING THE RESPONSE** (e.g. `.pipe(...)`) is **DISCOURAGED** because Request-Promise would grow the memory footprint for large requests unnecessarily high. Use the original Request library for that. You can use both libraries in the same project.
|
285 |
+
- Plus some methods on a request call object:
|
286 |
+
- `rp(...).then(...)` or e.g. `rp.post(...).then(...)` which turn `rp(...)` and `rp.post(...)` into promises
|
287 |
+
- `rp(...).catch(...)` or e.g. `rp.del(...).catch(...)` which is the same method as provided by Bluebird promises
|
288 |
+
- Errors that the `request` library would pass to the callback are wrapped by `request-promise` and then passed to the catch handler. See [code example](https://github.com/request/request-promise#thenonfulfilled-onrejected) below.
|
289 |
+
- `rp(...).finally(...)` or e.g. `rp.put(...).finally(...)` which is the same method as provided by Bluebird promises
|
290 |
+
- `rp(...).cancel()` or e.g. `rp.get(...).cancel()` which cancels the request
|
291 |
+
- `rp(...).promise()` or e.g. `rp.head(...).promise()` which returns the underlying promise so you can access the full [Bluebird API](https://github.com/petkaantonov/bluebird/blob/master/API.md)
|
292 |
+
- Plus some additional options:
|
293 |
+
- `simple = true` which is a boolean to set whether status codes other than 2xx should also reject the promise
|
294 |
+
- `resolveWithFullResponse = false` which is a boolean to set whether the promise should be resolved with the full response or just the response body
|
295 |
+
- `transform` which takes a function to transform the response into a custom value with which the promise is resolved
|
296 |
+
- `transform2xxOnly = false` which is a boolean to set whether the transform function is applied to all responses or only to those with a 2xx status code
|
297 |
+
|
298 |
+
The objects returned by request calls like `rp(...)` or e.g. `rp.post(...)` are regular Promises/A+ compliant promises and can be assimilated by any compatible promise library.
|
299 |
+
|
300 |
+
The methods `.then(...)`, `.catch(...)`, and `.finally(...)` - which you can call on the request call objects - return a full-fledged Bluebird promise. That means you have the full [Bluebird API](https://github.com/petkaantonov/bluebird/blob/master/API.md) available for further chaining. E.g.: `rp(...).then(...).spread(...)` If, however, you need a method other than `.then(...)`, `.catch(...)`, or `.finally(...)` to be **FIRST** in the chain, use `.promise()`: `rp(...).promise().bind(...).then(...)`
|
301 |
+
|
302 |
+
### .then(onFulfilled, onRejected)
|
303 |
+
|
304 |
+
``` js
|
305 |
+
// As a Request user you would write:
|
306 |
+
var request = require('request');
|
307 |
+
|
308 |
+
request('http://google.com', function (err, response, body) {
|
309 |
+
if (err) {
|
310 |
+
handleError({ error: err, response: response, ... });
|
311 |
+
} else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx
|
312 |
+
handleError({ error: body, response: response, ... });
|
313 |
+
} else {
|
314 |
+
process(body);
|
315 |
+
}
|
316 |
+
});
|
317 |
+
|
318 |
+
// As a Request-Promise user you can now write the equivalent code:
|
319 |
+
var rp = require('request-promise');
|
320 |
+
|
321 |
+
rp('http://google.com')
|
322 |
+
.then(process, handleError);
|
323 |
+
```
|
324 |
+
|
325 |
+
``` js
|
326 |
+
// The same is available for all http method shortcuts:
|
327 |
+
request.post('http://example.com/api', function (err, response, body) { ... });
|
328 |
+
rp.post('http://example.com/api').then(...);
|
329 |
+
```
|
330 |
+
|
331 |
+
### .catch(onRejected)
|
332 |
+
|
333 |
+
``` js
|
334 |
+
rp('http://google.com')
|
335 |
+
.catch(handleError);
|
336 |
+
|
337 |
+
// ... is syntactical sugar for:
|
338 |
+
|
339 |
+
rp('http://google.com')
|
340 |
+
.then(null, handleError);
|
341 |
+
|
342 |
+
|
343 |
+
// However, this:
|
344 |
+
rp('http://google.com')
|
345 |
+
.then(process)
|
346 |
+
.catch(handleError);
|
347 |
+
|
348 |
+
// ... is safer than:
|
349 |
+
rp('http://google.com')
|
350 |
+
.then(process, handleError);
|
351 |
+
```
|
352 |
+
|
353 |
+
For more info on `.then(process).catch(handleError)` versus `.then(process, handleError)`, see Bluebird docs on [promise anti-patterns](http://bluebirdjs.com/docs/anti-patterns.html#the-.then).
|
354 |
+
|
355 |
+
### .finally(onFinished)
|
356 |
+
|
357 |
+
``` js
|
358 |
+
rp('http://google.com')
|
359 |
+
.finally(function () {
|
360 |
+
// This is called after the request finishes either successful or not successful.
|
361 |
+
});
|
362 |
+
```
|
363 |
+
|
364 |
+
### .cancel()
|
365 |
+
|
366 |
+
This method cancels the request using [Bluebird's cancellation feature](http://bluebirdjs.com/docs/api/cancellation.html).
|
367 |
+
|
368 |
+
When `.cancel()` is called:
|
369 |
+
|
370 |
+
- the promise will neither be resolved nor rejected and
|
371 |
+
- the request is [aborted](https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_request_abort).
|
372 |
+
|
373 |
+
### .promise() - For advanced use cases
|
374 |
+
|
375 |
+
In order to not pollute the Request call objects with the methods of the underlying Bluebird promise, only `.then(...)`, `.catch(...)`, and `.finally(...)` were exposed to cover most use cases. The effect is that any methods of a Bluebird promise other than `.then(...)`, `.catch(...)`, or `.finally(...)` cannot be used as the **FIRST** method in the promise chain:
|
376 |
+
|
377 |
+
``` js
|
378 |
+
// This works:
|
379 |
+
rp('http://google.com').then(function () { ... });
|
380 |
+
rp('http://google.com').catch(function () { ... });
|
381 |
+
|
382 |
+
// This works as well since additional methods are only used AFTER the FIRST call in the chain:
|
383 |
+
rp('http://google.com').then(function () { ... }).spread(function () { ... });
|
384 |
+
rp('http://google.com').catch(function () { ... }).error(function () { ... });
|
385 |
+
|
386 |
+
// Using additional methods as the FIRST call in the chain does not work:
|
387 |
+
// rp('http://google.com').bind(this).then(function () { ... });
|
388 |
+
|
389 |
+
// Use .promise() in these cases:
|
390 |
+
rp('http://google.com').promise().bind(this).then(function () { ... });
|
391 |
+
```
|
392 |
+
|
393 |
+
### Fulfilled promises and the `resolveWithFullResponse` option
|
394 |
+
|
395 |
+
``` js
|
396 |
+
// Per default the body is passed to the fulfillment handler:
|
397 |
+
rp('http://google.com')
|
398 |
+
.then(function (body) {
|
399 |
+
// Process the html of the Google web page...
|
400 |
+
});
|
401 |
+
|
402 |
+
// The resolveWithFullResponse options allows to pass the full response:
|
403 |
+
rp({ uri: 'http://google.com', resolveWithFullResponse: true })
|
404 |
+
.then(function (response) {
|
405 |
+
// Access response.statusCode, response.body etc.
|
406 |
+
});
|
407 |
+
|
408 |
+
```
|
409 |
+
|
410 |
+
### Rejected promises and the `simple` option
|
411 |
+
|
412 |
+
``` js
|
413 |
+
// The rejection handler is called with a reason object...
|
414 |
+
rp('http://google.com')
|
415 |
+
.catch(function (reason) {
|
416 |
+
// Handle failed request...
|
417 |
+
});
|
418 |
+
|
419 |
+
// ... and would be equivalent to this Request-only implementation:
|
420 |
+
var options = { uri: 'http://google.com' };
|
421 |
+
|
422 |
+
request(options, function (err, response, body) {
|
423 |
+
var reason;
|
424 |
+
if (err) {
|
425 |
+
reason = {
|
426 |
+
cause: err,
|
427 |
+
error: err,
|
428 |
+
options: options,
|
429 |
+
response: response
|
430 |
+
};
|
431 |
+
} else if (!(/^2/.test('' + response.statusCode))) { // Status Codes other than 2xx
|
432 |
+
reason = {
|
433 |
+
statusCode: response.statusCode,
|
434 |
+
error: body,
|
435 |
+
options: options,
|
436 |
+
response: response
|
437 |
+
};
|
438 |
+
}
|
439 |
+
|
440 |
+
if (reason) {
|
441 |
+
// Handle failed request...
|
442 |
+
}
|
443 |
+
});
|
444 |
+
|
445 |
+
|
446 |
+
// If you pass the simple option as false...
|
447 |
+
rp({ uri: 'http://google.com', simple: false })
|
448 |
+
.catch(function (reason) {
|
449 |
+
// Handle failed request...
|
450 |
+
});
|
451 |
+
|
452 |
+
// ... the equivalent Request-only code would be:
|
453 |
+
request(options, function (err, response, body) {
|
454 |
+
if (err) {
|
455 |
+
var reason = {
|
456 |
+
cause: err,
|
457 |
+
error: err,
|
458 |
+
options: options,
|
459 |
+
response: response
|
460 |
+
};
|
461 |
+
// Handle failed request...
|
462 |
+
}
|
463 |
+
});
|
464 |
+
// E.g. a 404 would now fulfill the promise.
|
465 |
+
// Combine it with resolveWithFullResponse = true to check the status code in the fulfillment handler.
|
466 |
+
```
|
467 |
+
|
468 |
+
With version 0.4 the reason objects became Error objects with identical properties to ensure backwards compatibility. These new Error types allow targeted catch blocks:
|
469 |
+
|
470 |
+
``` js
|
471 |
+
var errors = require('request-promise/errors');
|
472 |
+
|
473 |
+
rp('http://google.com')
|
474 |
+
.catch(errors.StatusCodeError, function (reason) {
|
475 |
+
// The server responded with a status codes other than 2xx.
|
476 |
+
// Check reason.statusCode
|
477 |
+
})
|
478 |
+
.catch(errors.RequestError, function (reason) {
|
479 |
+
// The request failed due to technical reasons.
|
480 |
+
// reason.cause is the Error object Request would pass into a callback.
|
481 |
+
});
|
482 |
+
```
|
483 |
+
|
484 |
+
### The `transform` function
|
485 |
+
|
486 |
+
You can pass a function to `options.transform` to generate a custom fulfillment value when the promise gets resolved.
|
487 |
+
|
488 |
+
``` js
|
489 |
+
// Just for fun you could reverse the response body:
|
490 |
+
var options = {
|
491 |
+
uri: 'http://google.com',
|
492 |
+
transform: function (body, response, resolveWithFullResponse) {
|
493 |
+
return body.split('').reverse().join('');
|
494 |
+
}
|
495 |
+
};
|
496 |
+
|
497 |
+
rp(options)
|
498 |
+
.then(function (reversedBody) {
|
499 |
+
// ;D
|
500 |
+
});
|
501 |
+
|
502 |
+
|
503 |
+
// However, you could also do something useful:
|
504 |
+
var $ = require('cheerio'); // Basically jQuery for node.js
|
505 |
+
|
506 |
+
function autoParse(body, response, resolveWithFullResponse) {
|
507 |
+
// FIXME: The content type string could contain additional values like the charset.
|
508 |
+
// Consider using the `content-type` library for a robust comparison.
|
509 |
+
if (response.headers['content-type'] === 'application/json') {
|
510 |
+
return JSON.parse(body);
|
511 |
+
} else if (response.headers['content-type'] === 'text/html') {
|
512 |
+
return $.load(body);
|
513 |
+
} else {
|
514 |
+
return body;
|
515 |
+
}
|
516 |
+
}
|
517 |
+
|
518 |
+
options.transform = autoParse;
|
519 |
+
|
520 |
+
rp(options)
|
521 |
+
.then(function (autoParsedBody) {
|
522 |
+
// :)
|
523 |
+
});
|
524 |
+
|
525 |
+
|
526 |
+
// You can go one step further and set the transform as the default:
|
527 |
+
var rpap = rp.defaults({ transform: autoParse });
|
528 |
+
|
529 |
+
rpap('http://google.com')
|
530 |
+
.then(function (autoParsedBody) {
|
531 |
+
// :)
|
532 |
+
});
|
533 |
+
|
534 |
+
rpap('http://echojs.com')
|
535 |
+
.then(function (autoParsedBody) {
|
536 |
+
// =)
|
537 |
+
});
|
538 |
+
```
|
539 |
+
|
540 |
+
The third `resolveWithFullResponse` parameter of the transform function is equivalent to the option passed with the request. This allows to distinguish whether just the transformed body or the whole response shall be returned by the transform function:
|
541 |
+
|
542 |
+
``` js
|
543 |
+
function reverseBody(body, response, resolveWithFullResponse) {
|
544 |
+
response.body = response.body.split('').reverse().join('');
|
545 |
+
return resolveWithFullResponse ? response : response.body;
|
546 |
+
}
|
547 |
+
```
|
548 |
+
|
549 |
+
As of Request-Promise v3 the transform function is ALWAYS executed for non-2xx responses. When `options.simple` is set to `true` (default) then non-2xx responses are rejected with a `StatusCodeError`. In this case the error contains the transformed response:
|
550 |
+
|
551 |
+
``` js
|
552 |
+
var options = {
|
553 |
+
uri: 'http://the-server.com/will-return/404',
|
554 |
+
simple: true,
|
555 |
+
transform: function (body, response, resolveWithFullResponse) { /* ... */ }
|
556 |
+
};
|
557 |
+
|
558 |
+
rp(options)
|
559 |
+
.catch(errors.StatusCodeError, function (reason) {
|
560 |
+
// reason.response is the transformed response
|
561 |
+
});
|
562 |
+
```
|
563 |
+
|
564 |
+
You may set `options.transform2xxOnly = true` to only execute the transform function for responses with a 2xx status code. For other status codes – independent of any other settings, e.g. `options.simple` – the transform function is not executed.
|
565 |
+
|
566 |
+
#### Error handling
|
567 |
+
|
568 |
+
If the transform operation fails (throws an error) the request will be rejected with a `TransformError`:
|
569 |
+
|
570 |
+
``` js
|
571 |
+
var errors = require('request-promise/errors');
|
572 |
+
|
573 |
+
var options = {
|
574 |
+
uri: 'http://google.com',
|
575 |
+
transform: function (body, response, resolveWithFullResponse) {
|
576 |
+
throw new Error('Transform failed!');
|
577 |
+
}
|
578 |
+
};
|
579 |
+
|
580 |
+
rp(options)
|
581 |
+
.catch(errors.TransformError, function (reason) {
|
582 |
+
console.log(reason.cause.message); // => Transform failed!
|
583 |
+
// reason.response is the original response for which the transform operation failed
|
584 |
+
});
|
585 |
+
```
|
586 |
+
|
587 |
+
## Experimental Support for Continuation Local Storage
|
588 |
+
|
589 |
+
Continuation Local Storage is no longer supported. However, you [can get back the support](https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage) by using `request-promise-any`.
|
590 |
+
|
591 |
+
## Debugging
|
592 |
+
|
593 |
+
The ways to debug the operation of Request-Promise are the same [as described](https://github.com/request/request#debugging) for Request. These are:
|
594 |
+
|
595 |
+
1. Launch the node process like `NODE_DEBUG=request node script.js` (`lib,request,otherlib` works too).
|
596 |
+
2. Set `require('request-promise').debug = true` at any time (this does the same thing as #1).
|
597 |
+
3. Use the [request-debug module](https://github.com/nylen/request-debug) to view request and response headers and bodies. Instrument Request-Promise with `require('request-debug')(rp);`.
|
598 |
+
|
599 |
+
## Mocking Request-Promise
|
600 |
+
|
601 |
+
Usually you want to mock the whole request function which is returned by `require('request-promise')`. This is not possible by using a mocking library like [sinon.js](http://sinonjs.org) alone. What you need is a library that ties into the module loader and makes sure that your mock is returned whenever the tested code is calling `require('request-promise')`. [Mockery](https://github.com/mfncooper/mockery) is one of such libraries.
|
602 |
+
|
603 |
+
@florianschmidt1994 kindly shared his solution:
|
604 |
+
```javascript
|
605 |
+
before(function (done) {
|
606 |
+
|
607 |
+
var filename = "fileForResponse";
|
608 |
+
mockery.enable({
|
609 |
+
warnOnReplace: false,
|
610 |
+
warnOnUnregistered: false,
|
611 |
+
useCleanCache: true
|
612 |
+
});
|
613 |
+
|
614 |
+
mockery.registerMock('request-promise', function () {
|
615 |
+
var response = fs.readFileSync(__dirname + '/data/' + filename, 'utf8');
|
616 |
+
return Bluebird.resolve(response.trim());
|
617 |
+
});
|
618 |
+
|
619 |
+
done();
|
620 |
+
});
|
621 |
+
|
622 |
+
after(function (done) {
|
623 |
+
mockery.disable();
|
624 |
+
mockery.deregisterAll();
|
625 |
+
done();
|
626 |
+
});
|
627 |
+
|
628 |
+
describe('custom test case', function () {
|
629 |
+
// Test some function/module/... which uses request-promise
|
630 |
+
// and it will always receive the predefined "fileForResponse" as data, e.g.:
|
631 |
+
var rp = require('request-promise');
|
632 |
+
rp(...).then(function(data) {
|
633 |
+
// ➞ data is what is in fileForResponse
|
634 |
+
});
|
635 |
+
});
|
636 |
+
```
|
637 |
+
|
638 |
+
Based on that you may now build a more sophisticated mock. [Sinon.js](http://sinonjs.org) may be of help as well.
|
639 |
+
|
640 |
+
## Contributing
|
641 |
+
|
642 |
+
To set up your development environment:
|
643 |
+
|
644 |
+
1. clone the repo to your desktop,
|
645 |
+
2. in the shell `cd` to the main folder,
|
646 |
+
3. hit `npm install`,
|
647 |
+
4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and
|
648 |
+
5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.)
|
649 |
+
|
650 |
+
`gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`.
|
651 |
+
|
652 |
+
If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation.
|
653 |
+
|
654 |
+
## Change History
|
655 |
+
|
656 |
+
- v4.2.5 (2019-11-03)
|
657 |
+
- Security fix: bumped `request-promise-core` which bumps `lodash` to `^4.17.15`. See [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm).
|
658 |
+
*(Thanks to @rishabh-chowdhary for reporting this in pull request [#326](https://github.com/request/request-promise/pull/326).)*
|
659 |
+
- v4.2.4 (2019-02-14)
|
660 |
+
- Corrected mistakenly set `tough-cookie` version, now `^2.3.3`
|
661 |
+
*(Thanks to @evocateur for pointing this out.)*
|
662 |
+
- If you installed `[email protected]` please make sure after the upgrade that `request` and `request-promise` use the same physical copy of `tough-cookie`.
|
663 |
+
- v4.2.3 (2019-02-14)
|
664 |
+
- Using stricter `tough-cookie@~2.3.3` to avoid installing `tough-cookie@3` which introduces breaking changes
|
665 |
+
*(Thanks to @aomdoa for pull request [#299](https://github.com/request/request-promise/pull/299))*
|
666 |
+
- Security fix: bumped `lodash` to `^4.17.11`, see [vulnerabilty reports](https://snyk.io/vuln/search?q=lodash&type=npm)
|
667 |
+
- v4.2.2 (2017-09-22)
|
668 |
+
- Upgraded `tough-cookie` to a version without regex DoS vulnerability
|
669 |
+
*(Thanks to @rouanw for [pull request #226](https://github.com/request/request-promise/pull/226))*
|
670 |
+
- v4.2.1 (2017-05-07)
|
671 |
+
- Fix that allows to use `tough-cookie` for cookie creation
|
672 |
+
*(Thanks to @ScottyMJacobson for reporting [issue #183](https://github.com/request/request-promise/issues/183))*
|
673 |
+
- Added [cookie handling example](https://github.com/request/request-promise#include-a-cookie) to the cheat sheet
|
674 |
+
*(Thanks to @chovy and @ProfessorTom for [asking for it](https://github.com/request/request-promise/issues/79))*
|
675 |
+
- v4.2.0 (2017-03-16)
|
676 |
+
- Updated `bluebird` to v3.5
|
677 |
+
*(Thanks to @acinader for [pull request #181](https://github.com/request/request-promise/pull/181))*
|
678 |
+
- v4.1.1 (2016-08-08)
|
679 |
+
- Renamed internally used package `@request/promise-core` to `request-promise-core` because there where [too](https://github.com/request/request-promise/issues/137) [many](https://github.com/request/request-promise/issues/141) issues with the scoped package name
|
680 |
+
*(Thanks to @cabrinoob, @crazy4groovy, @dsandor, @KpjComp, @lorenwest, @Reisyukaku, @tehChromic, @todd for providing helpful information.)*
|
681 |
+
- v4.1.0 (2016-07-30)
|
682 |
+
- Added cancellation support
|
683 |
+
*(Thanks to @not-an-aardvark for [pull request #123](https://github.com/request/request-promise/pull/123))*
|
684 |
+
- v4.0.2 (2016-07-18)
|
685 |
+
- Fix for using with module bundlers like Webpack and Browserify
|
686 |
+
- v4.0.1 (2016-07-17)
|
687 |
+
- Fixed `@request/promise-core` version for safer versioning
|
688 |
+
- v4.0.0 (2016-07-15)
|
689 |
+
- **Breaking Change**: `request` is declared as a peer dependency which has to be installed separately by the user now
|
690 |
+
- **Breaking Change**: Dropped support for Continuation Local Storage since [`request-promise-any`](https://github.com/request/request-promise-any) can be [used](https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage) for that now
|
691 |
+
- Introduced the `transform2xxOnly` option to ease the breaking change regarding the new `transform` handling in v3.0.0
|
692 |
+
*(Thanks to @stevage for pointing out the effect of the breaking change in [issue #131](https://github.com/request/request-promise/issues/131))*
|
693 |
+
- Resolved issues [#65](https://github.com/request/request-promise/issues/65) and [#71](https://github.com/request/request-promise/issues/71) by publishing nearly identical libraries to support other Promise implementations: [`request-promise-native`](https://github.com/request/request-promise-native) and [`request-promise-any`](https://github.com/request/request-promise-any)
|
694 |
+
*(Thanks to @benjamingr, @eilgin, @gillesdemey, @hildjj, @iggycoloma, @jonathanong, @knpwrs, @MarkHerhold, @massimocode, @mikeal, @niftylettuce, @raitucarp, @sherdeadlock, @tonylukasavage, and @vgoloviznin for the valuable discussions!)*
|
695 |
+
- Relicensed this library with the ISC license
|
696 |
+
- v3.0.0 (2016-04-16)
|
697 |
+
- **Breaking Change**: Overhauled the handling of the `transform` function
|
698 |
+
*(Thanks to @Limess for explaining the need in [issue #86](https://github.com/request/request-promise/issues/86))*
|
699 |
+
- **Breaking Change**: Updated `bluebird` to v3
|
700 |
+
*(Thanks to @BrandonSmith for [pull request #103](https://github.com/request/request-promise/pull/103))*
|
701 |
+
- Improved `StatusCodeError.message`
|
702 |
+
- Updated `lodash` to v4.6
|
703 |
+
- Improved README in regard to `.catch(...)` best practice
|
704 |
+
*(Thanks to @RebootJeff for [pull request #98](https://github.com/request/request-promise/pull/98))*
|
705 |
+
- v2.0.1 (2016-02-17)
|
706 |
+
- Updated `lodash` to v4
|
707 |
+
*(Thanks to @ratson for [pull request #94](https://github.com/request/request-promise/pull/94))*
|
708 |
+
- v2.0.0 (2016-01-12)
|
709 |
+
- **Breaking Change**: Removed explicit `cls-bluebird` dependency which has to be installed by the user now
|
710 |
+
*(Thanks to @hildjj for his [pull request #75](https://github.com/request/request-promise/pull/75))*
|
711 |
+
- `npm shrinkwrap` now works for `npm@3` users who don't use `continuation-local-storage`
|
712 |
+
*(Thanks to @toboid and @rstacruz for reporting the issue in [issue #70](https://github.com/request/request-promise/issues/70) and [issue #82](https://github.com/request/request-promise/issues/82))*
|
713 |
+
- v1.0.2 (2015-10-22)
|
714 |
+
- Removed `continuation-local-storage` from peer dependencies as it was unnecessary
|
715 |
+
*(Thanks to @mrhyde for working on a better solution discussed in [issue #70](https://github.com/request/request-promise/issues/70))*
|
716 |
+
- v1.0.1 (2015-10-14)
|
717 |
+
- Fixed a npm warning by marking `continuation-local-storage` as a peer dependency
|
718 |
+
- v1.0.0 (2015-10-11)
|
719 |
+
- **Breaking Change**: Some errors that were previously thrown synchronously - e.g. for wrong input parameters - are now passed to the rejected promise instead
|
720 |
+
*(Thanks to @josnidhin for suggesting that in [issue #43](https://github.com/request/request-promise/issues/43))*
|
721 |
+
- **Breaking Change**: Request-Promise does not load its own Bluebird prototype anymore. If you use Bluebird in your project and altered the prototype then Request-Promise may use your altered Bluebird prototype internally.
|
722 |
+
- For HEAD requests the headers instead of an empty body is returned (unless `resolveWithFullResponse = true` is used)
|
723 |
+
*(Thanks to @zcei for proposing the change in [issue #58](https://github.com/request/request-promise/issues/58))*
|
724 |
+
- Extended `transform` function by a third `resolveWithFullResponse` parameter
|
725 |
+
- Added experimental support for continuation local storage
|
726 |
+
*(Thanks to @silverbp preparing this in [issue #64](https://github.com/request/request-promise/issues/64))*
|
727 |
+
- Added node.js 4 to the Travis CI build
|
728 |
+
- Updated the README
|
729 |
+
*(Thanks to many people for their feedback in issues [#55](https://github.com/request/request-promise/issues/55) and [#59](https://github.com/request/request-promise/issues/59))*
|
730 |
+
- v0.4.3 (2015-07-27)
|
731 |
+
- Reduced overhead by just requiring used lodash functions instead of the whole lodash library
|
732 |
+
*(Thanks to @luanmuniz for [pull request #54](https://github.com/request/request-promise/pull/54))*
|
733 |
+
- Updated dependencies
|
734 |
+
- v0.4.2 (2015-04-12)
|
735 |
+
- Updated dependencies
|
736 |
+
- v0.4.1 (2015-03-20)
|
737 |
+
- Improved Error types to work in browsers without v8 engine
|
738 |
+
*(Thanks to @nodiis for [pull request #40](https://github.com/request/request-promise/pull/40))*
|
739 |
+
- v0.4.0 (2015-02-08)
|
740 |
+
- Introduced Error types used for the reject reasons (See last part [this section](#rejected-promises-and-the-simple-option))
|
741 |
+
*(Thanks to @jakecraige for starting the discussion in [issue #38](https://github.com/request/request-promise/issues/38))*
|
742 |
+
- **Minor Breaking Change:** The reject reason objects became actual Error objects. However, `typeof reason === 'object'` still holds true and the error objects have the same properties as the previous reason objects. If the reject handler only accesses the properties on the reason object - which is usually the case - no migration is required.
|
743 |
+
- Added io.js and node.js 0.12 to the Travis CI build
|
744 |
+
- v0.3.3 (2015-01-19)
|
745 |
+
- Fixed handling possibly unhandled rejections to work with the latest version of Bluebird
|
746 |
+
*(Thanks to @slang800 for reporting this in [issue #36](https://github.com/request/request-promise/issues/36))*
|
747 |
+
- v0.3.2 (2014-11-17)
|
748 |
+
- Exposed `.finally(...)` to allow using it as the first method in the promise chain
|
749 |
+
*(Thanks to @hjpbarcelos for his [pull request #28](https://github.com/request/request-promise/pull/28))*
|
750 |
+
- v0.3.1 (2014-11-11)
|
751 |
+
- Added the `.promise()` method for advanced Bluebird API usage
|
752 |
+
*(Thanks to @devo-tox for his feedback in [issue #27](https://github.com/request/request-promise/issues/27))*
|
753 |
+
- v0.3.0 (2014-11-10)
|
754 |
+
- Carefully rewritten from scratch to make Request-Promise a drop-in replacement for Request
|
755 |
+
|
756 |
+
## License (ISC)
|
757 |
+
|
758 |
+
In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license.
|
759 |
+
|
760 |
+
See the [LICENSE file](LICENSE) for details.
|
node_modules/@cypress/request-promise/errors.js
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
'use strict';
|
2 |
+
|
3 |
+
module.exports = require('request-promise-core/errors');
|
node_modules/@cypress/request-promise/lib/rp.js
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict';
|
2 |
+
|
3 |
+
var Bluebird = require('bluebird').getNewLibraryCopy(),
|
4 |
+
configure = require('request-promise-core/configure/request2'),
|
5 |
+
stealthyRequire = require('stealthy-require');
|
6 |
+
|
7 |
+
try {
|
8 |
+
|
9 |
+
// Load Request freshly - so that users can require an unaltered request instance!
|
10 |
+
var request = stealthyRequire(require.cache, function () {
|
11 |
+
return require('@cypress/request');
|
12 |
+
},
|
13 |
+
function () {
|
14 |
+
require('tough-cookie');
|
15 |
+
}, module);
|
16 |
+
|
17 |
+
} catch (err) {
|
18 |
+
/* istanbul ignore next */
|
19 |
+
var EOL = require('os').EOL;
|
20 |
+
/* istanbul ignore next */
|
21 |
+
console.error(EOL + '###' + EOL + '### The "request" library is not installed automatically anymore.' + EOL + '### But is a dependency of "request-promise".' + EOL + '### Please install it with:' + EOL + '### npm install request --save' + EOL + '###' + EOL);
|
22 |
+
/* istanbul ignore next */
|
23 |
+
throw err;
|
24 |
+
}
|
25 |
+
|
26 |
+
Bluebird.config({cancellation: true});
|
27 |
+
|
28 |
+
configure({
|
29 |
+
request: request,
|
30 |
+
PromiseImpl: Bluebird,
|
31 |
+
expose: [
|
32 |
+
'then',
|
33 |
+
'catch',
|
34 |
+
'finally',
|
35 |
+
'cancel',
|
36 |
+
'promise'
|
37 |
+
// Would you like to expose more Bluebird methods? Try e.g. `rp(...).promise().tap(...)` first. `.promise()` returns the full-fledged Bluebird promise.
|
38 |
+
],
|
39 |
+
constructorMixin: function (resolve, reject, onCancel) {
|
40 |
+
var self = this;
|
41 |
+
onCancel(function () {
|
42 |
+
self.abort();
|
43 |
+
});
|
44 |
+
}
|
45 |
+
});
|
46 |
+
|
47 |
+
request.bindCLS = function RP$bindCLS() {
|
48 |
+
throw new Error('CLS support was dropped. To get it back read: https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage');
|
49 |
+
};
|
50 |
+
|
51 |
+
|
52 |
+
module.exports = request;
|
node_modules/@cypress/request-promise/package.json
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name": "@cypress/request-promise",
|
3 |
+
"version": "5.0.0",
|
4 |
+
"description": "Cypress's fork of the simplified HTTP request client 'request' with Promise support. Powered by Bluebird.",
|
5 |
+
"keywords": [
|
6 |
+
"xhr",
|
7 |
+
"http",
|
8 |
+
"https",
|
9 |
+
"promise",
|
10 |
+
"request",
|
11 |
+
"then",
|
12 |
+
"thenable",
|
13 |
+
"bluebird"
|
14 |
+
],
|
15 |
+
"main": "./lib/rp.js",
|
16 |
+
"scripts": {
|
17 |
+
"test": "./node_modules/.bin/gulp ci",
|
18 |
+
"test-publish": "./node_modules/.bin/gulp ci-no-cov",
|
19 |
+
"publish-please": "publish-please"
|
20 |
+
},
|
21 |
+
"repository": {
|
22 |
+
"type": "git",
|
23 |
+
"url": "git+https://github.com/cypress-io/request-promise.git"
|
24 |
+
},
|
25 |
+
"author": "Nicolai Kamenzky (https://github.com/analog-nico)",
|
26 |
+
"license": "ISC",
|
27 |
+
"bugs": {
|
28 |
+
"url": "https://github.com/cypress-io/request-promise/issues"
|
29 |
+
},
|
30 |
+
"homepage": "https://github.com/cypress-io/request-promise#readme",
|
31 |
+
"engines": {
|
32 |
+
"node": ">=0.10.0"
|
33 |
+
},
|
34 |
+
"dependencies": {
|
35 |
+
"request-promise-core": "1.1.3",
|
36 |
+
"bluebird": "^3.5.0",
|
37 |
+
"stealthy-require": "^1.1.1",
|
38 |
+
"tough-cookie": "^4.1.3"
|
39 |
+
},
|
40 |
+
"peerDependencies": {
|
41 |
+
"@cypress/request": "^3.0.0"
|
42 |
+
},
|
43 |
+
"devDependencies": {
|
44 |
+
"body-parser": "~1.15.2",
|
45 |
+
"chai": "~3.5.0",
|
46 |
+
"chalk": "~1.1.3",
|
47 |
+
"gulp": "~3.9.1",
|
48 |
+
"gulp-coveralls": "~0.1.4",
|
49 |
+
"gulp-eslint": "~2.1.0",
|
50 |
+
"gulp-istanbul": "~1.0.0",
|
51 |
+
"gulp-mocha": "~2.2.0",
|
52 |
+
"lodash": "~4.13.1",
|
53 |
+
"publish-please": "~2.1.4",
|
54 |
+
"@cypress/request": "^3.0.0",
|
55 |
+
"rimraf": "~2.5.3",
|
56 |
+
"run-sequence": "~1.2.2"
|
57 |
+
},
|
58 |
+
"resolutions": {
|
59 |
+
"chalk": "~1.1.3"
|
60 |
+
}
|
61 |
+
}
|
node_modules/@cypress/request/LICENSE
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
|
3 |
+
Version 2.0, January 2004
|
4 |
+
|
5 |
+
http://www.apache.org/licenses/
|
6 |
+
|
7 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
8 |
+
|
9 |
+
1. Definitions.
|
10 |
+
|
11 |
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
12 |
+
|
13 |
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
16 |
+
|
17 |
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
18 |
+
|
19 |
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
20 |
+
|
21 |
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
22 |
+
|
23 |
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
24 |
+
|
25 |
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
26 |
+
|
27 |
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
28 |
+
|
29 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
30 |
+
|
31 |
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
32 |
+
|
33 |
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
34 |
+
|
35 |
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
36 |
+
|
37 |
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
38 |
+
|
39 |
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
40 |
+
|
41 |
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
42 |
+
|
43 |
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
44 |
+
|
45 |
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
46 |
+
|
47 |
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
48 |
+
|
49 |
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
50 |
+
|
51 |
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
52 |
+
|
53 |
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
54 |
+
|
55 |
+
END OF TERMS AND CONDITIONS
|
node_modules/@cypress/request/README.md
ADDED
@@ -0,0 +1,1032 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
# @cypress/request - Simplified HTTP client
|
3 |
+
|
4 |
+
[![npm package](https://nodei.co/npm/@cypress/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/@cypress/request/)
|
5 |
+
|
6 |
+
**This is a fork of [`request`](https://github.com/request/request) for use in [Cypress](https://github.com/cypress-io/cypress).**
|
7 |
+
|
8 |
+
## Super simple to use
|
9 |
+
|
10 |
+
Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
|
11 |
+
|
12 |
+
```js
|
13 |
+
const request = require('@cypress/request');
|
14 |
+
request('http://www.google.com', function (error, response, body) {
|
15 |
+
console.error('error:', error); // Print the error if one occurred
|
16 |
+
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
|
17 |
+
console.log('body:', body); // Print the HTML for the Google homepage.
|
18 |
+
});
|
19 |
+
```
|
20 |
+
|
21 |
+
|
22 |
+
## Table of contents
|
23 |
+
|
24 |
+
- [Streaming](#streaming)
|
25 |
+
- [Promises & Async/Await](#promises--asyncawait)
|
26 |
+
- [Forms](#forms)
|
27 |
+
- [HTTP Authentication](#http-authentication)
|
28 |
+
- [Custom HTTP Headers](#custom-http-headers)
|
29 |
+
- [Proxies](#proxies)
|
30 |
+
- [Unix Domain Sockets](#unix-domain-sockets)
|
31 |
+
- [TLS/SSL Protocol](#tlsssl-protocol)
|
32 |
+
- [Support for HAR 1.2](#support-for-har-12)
|
33 |
+
- [**All Available Options**](#requestoptions-callback)
|
34 |
+
|
35 |
+
Request also offers [convenience methods](#convenience-methods) like
|
36 |
+
`request.defaults` and `request.post`, and there are
|
37 |
+
lots of [usage examples](#examples) and several
|
38 |
+
[debugging techniques](#debugging).
|
39 |
+
|
40 |
+
|
41 |
+
---
|
42 |
+
|
43 |
+
|
44 |
+
## Streaming
|
45 |
+
|
46 |
+
You can stream any response to a file stream.
|
47 |
+
|
48 |
+
```js
|
49 |
+
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
|
50 |
+
```
|
51 |
+
|
52 |
+
You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case `application/json`) and use the proper `content-type` in the PUT request (if the headers don’t already provide one).
|
53 |
+
|
54 |
+
```js
|
55 |
+
fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
|
56 |
+
```
|
57 |
+
|
58 |
+
Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.
|
59 |
+
|
60 |
+
```js
|
61 |
+
request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
|
62 |
+
```
|
63 |
+
|
64 |
+
Request emits a "response" event when a response is received. The `response` argument will be an instance of [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
|
65 |
+
|
66 |
+
```js
|
67 |
+
request
|
68 |
+
.get('http://google.com/img.png')
|
69 |
+
.on('response', function(response) {
|
70 |
+
console.log(response.statusCode) // 200
|
71 |
+
console.log(response.headers['content-type']) // 'image/png'
|
72 |
+
})
|
73 |
+
.pipe(request.put('http://mysite.com/img.png'))
|
74 |
+
```
|
75 |
+
|
76 |
+
To easily handle errors when streaming requests, listen to the `error` event before piping:
|
77 |
+
|
78 |
+
```js
|
79 |
+
request
|
80 |
+
.get('http://mysite.com/doodle.png')
|
81 |
+
.on('error', function(err) {
|
82 |
+
console.error(err)
|
83 |
+
})
|
84 |
+
.pipe(fs.createWriteStream('doodle.png'))
|
85 |
+
```
|
86 |
+
|
87 |
+
Now let’s get fancy.
|
88 |
+
|
89 |
+
```js
|
90 |
+
http.createServer(function (req, resp) {
|
91 |
+
if (req.url === '/doodle.png') {
|
92 |
+
if (req.method === 'PUT') {
|
93 |
+
req.pipe(request.put('http://mysite.com/doodle.png'))
|
94 |
+
} else if (req.method === 'GET' || req.method === 'HEAD') {
|
95 |
+
request.get('http://mysite.com/doodle.png').pipe(resp)
|
96 |
+
}
|
97 |
+
}
|
98 |
+
})
|
99 |
+
```
|
100 |
+
|
101 |
+
You can also `pipe()` from `http.ServerRequest` instances, as well as to `http.ServerResponse` instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do:
|
102 |
+
|
103 |
+
```js
|
104 |
+
http.createServer(function (req, resp) {
|
105 |
+
if (req.url === '/doodle.png') {
|
106 |
+
const x = request('http://mysite.com/doodle.png')
|
107 |
+
req.pipe(x)
|
108 |
+
x.pipe(resp)
|
109 |
+
}
|
110 |
+
})
|
111 |
+
```
|
112 |
+
|
113 |
+
And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)
|
114 |
+
|
115 |
+
```js
|
116 |
+
req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
|
117 |
+
```
|
118 |
+
|
119 |
+
Also, none of this new functionality conflicts with requests previous features, it just expands them.
|
120 |
+
|
121 |
+
```js
|
122 |
+
const r = request.defaults({'proxy':'http://localproxy.com'})
|
123 |
+
|
124 |
+
http.createServer(function (req, resp) {
|
125 |
+
if (req.url === '/doodle.png') {
|
126 |
+
r.get('http://google.com/doodle.png').pipe(resp)
|
127 |
+
}
|
128 |
+
})
|
129 |
+
```
|
130 |
+
|
131 |
+
You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
|
132 |
+
|
133 |
+
[back to top](#table-of-contents)
|
134 |
+
|
135 |
+
|
136 |
+
---
|
137 |
+
|
138 |
+
|
139 |
+
## Promises & Async/Await
|
140 |
+
|
141 |
+
`request` supports both streaming and callback interfaces natively. If you'd like `request` to return a Promise instead, you can use an alternative interface wrapper for `request`. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use `async`/`await` in ES2017.
|
142 |
+
|
143 |
+
Several alternative interfaces are provided by the request team, including:
|
144 |
+
- [`request-promise`](https://github.com/cypress-io/request-promise) (uses [Bluebird](https://github.com/petkaantonov/bluebird) Promises)
|
145 |
+
- [`request-promise-native`](https://github.com/cypress-io/request-promise-native) (uses native Promises)
|
146 |
+
- [`request-promise-any`](https://github.com/cypress-io/request-promise-any) (uses [any-promise](https://www.npmjs.com/package/any-promise) Promises)
|
147 |
+
|
148 |
+
Also, [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original), which is available from Node.js v8.0 can be used to convert a regular function that takes a callback to return a promise instead.
|
149 |
+
|
150 |
+
|
151 |
+
[back to top](#table-of-contents)
|
152 |
+
|
153 |
+
|
154 |
+
---
|
155 |
+
|
156 |
+
|
157 |
+
## Forms
|
158 |
+
|
159 |
+
`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
|
160 |
+
|
161 |
+
|
162 |
+
#### application/x-www-form-urlencoded (URL-Encoded Forms)
|
163 |
+
|
164 |
+
URL-encoded forms are simple.
|
165 |
+
|
166 |
+
```js
|
167 |
+
request.post('http://service.com/upload', {form:{key:'value'}})
|
168 |
+
// or
|
169 |
+
request.post('http://service.com/upload').form({key:'value'})
|
170 |
+
// or
|
171 |
+
request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
|
172 |
+
```
|
173 |
+
|
174 |
+
|
175 |
+
#### multipart/form-data (Multipart Form Uploads)
|
176 |
+
|
177 |
+
For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option.
|
178 |
+
|
179 |
+
|
180 |
+
```js
|
181 |
+
const formData = {
|
182 |
+
// Pass a simple key-value pair
|
183 |
+
my_field: 'my_value',
|
184 |
+
// Pass data via Buffers
|
185 |
+
my_buffer: Buffer.from([1, 2, 3]),
|
186 |
+
// Pass data via Streams
|
187 |
+
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
|
188 |
+
// Pass multiple values /w an Array
|
189 |
+
attachments: [
|
190 |
+
fs.createReadStream(__dirname + '/attachment1.jpg'),
|
191 |
+
fs.createReadStream(__dirname + '/attachment2.jpg')
|
192 |
+
],
|
193 |
+
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
|
194 |
+
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
|
195 |
+
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
|
196 |
+
custom_file: {
|
197 |
+
value: fs.createReadStream('/dev/urandom'),
|
198 |
+
options: {
|
199 |
+
filename: 'topsecret.jpg',
|
200 |
+
contentType: 'image/jpeg'
|
201 |
+
}
|
202 |
+
}
|
203 |
+
};
|
204 |
+
request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
|
205 |
+
if (err) {
|
206 |
+
return console.error('upload failed:', err);
|
207 |
+
}
|
208 |
+
console.log('Upload successful! Server responded with:', body);
|
209 |
+
});
|
210 |
+
```
|
211 |
+
|
212 |
+
For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.)
|
213 |
+
|
214 |
+
```js
|
215 |
+
// NOTE: Advanced use-case, for normal use see 'formData' usage above
|
216 |
+
const r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
|
217 |
+
const form = r.form();
|
218 |
+
form.append('my_field', 'my_value');
|
219 |
+
form.append('my_buffer', Buffer.from([1, 2, 3]));
|
220 |
+
form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
|
221 |
+
```
|
222 |
+
See the [form-data README](https://github.com/form-data/form-data) for more information & examples.
|
223 |
+
|
224 |
+
|
225 |
+
#### multipart/related
|
226 |
+
|
227 |
+
Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a `multipart/related` request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them as `true` to your request options.
|
228 |
+
|
229 |
+
```js
|
230 |
+
request({
|
231 |
+
method: 'PUT',
|
232 |
+
preambleCRLF: true,
|
233 |
+
postambleCRLF: true,
|
234 |
+
uri: 'http://service.com/upload',
|
235 |
+
multipart: [
|
236 |
+
{
|
237 |
+
'content-type': 'application/json',
|
238 |
+
body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
|
239 |
+
},
|
240 |
+
{ body: 'I am an attachment' },
|
241 |
+
{ body: fs.createReadStream('image.png') }
|
242 |
+
],
|
243 |
+
// alternatively pass an object containing additional options
|
244 |
+
multipart: {
|
245 |
+
chunked: false,
|
246 |
+
data: [
|
247 |
+
{
|
248 |
+
'content-type': 'application/json',
|
249 |
+
body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
|
250 |
+
},
|
251 |
+
{ body: 'I am an attachment' }
|
252 |
+
]
|
253 |
+
}
|
254 |
+
},
|
255 |
+
function (error, response, body) {
|
256 |
+
if (error) {
|
257 |
+
return console.error('upload failed:', error);
|
258 |
+
}
|
259 |
+
console.log('Upload successful! Server responded with:', body);
|
260 |
+
})
|
261 |
+
```
|
262 |
+
|
263 |
+
[back to top](#table-of-contents)
|
264 |
+
|
265 |
+
|
266 |
+
---
|
267 |
+
|
268 |
+
|
269 |
+
## HTTP Authentication
|
270 |
+
|
271 |
+
```js
|
272 |
+
request.get('http://some.server.com/').auth('username', 'password', false);
|
273 |
+
// or
|
274 |
+
request.get('http://some.server.com/', {
|
275 |
+
'auth': {
|
276 |
+
'user': 'username',
|
277 |
+
'pass': 'password',
|
278 |
+
'sendImmediately': false
|
279 |
+
}
|
280 |
+
});
|
281 |
+
// or
|
282 |
+
request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
|
283 |
+
// or
|
284 |
+
request.get('http://some.server.com/', {
|
285 |
+
'auth': {
|
286 |
+
'bearer': 'bearerToken'
|
287 |
+
}
|
288 |
+
});
|
289 |
+
```
|
290 |
+
|
291 |
+
If passed as an option, `auth` should be a hash containing values:
|
292 |
+
|
293 |
+
- `user` || `username`
|
294 |
+
- `pass` || `password`
|
295 |
+
- `sendImmediately` (optional)
|
296 |
+
- `bearer` (optional)
|
297 |
+
|
298 |
+
The method form takes parameters
|
299 |
+
`auth(username, password, sendImmediately, bearer)`.
|
300 |
+
|
301 |
+
`sendImmediately` defaults to `true`, which causes a basic or bearer
|
302 |
+
authentication header to be sent. If `sendImmediately` is `false`, then
|
303 |
+
`request` will retry with a proper authentication header after receiving a
|
304 |
+
`401` response from the server (which must contain a `WWW-Authenticate` header
|
305 |
+
indicating the required authentication method).
|
306 |
+
|
307 |
+
Note that you can also specify basic authentication using the URL itself, as
|
308 |
+
detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the
|
309 |
+
`user:password` before the host with an `@` sign:
|
310 |
+
|
311 |
+
```js
|
312 |
+
const username = 'username',
|
313 |
+
password = 'password',
|
314 |
+
url = 'http://' + username + ':' + password + '@some.server.com';
|
315 |
+
|
316 |
+
request({url}, function (error, response, body) {
|
317 |
+
// Do more stuff with 'body' here
|
318 |
+
});
|
319 |
+
```
|
320 |
+
|
321 |
+
Digest authentication is supported, but it only works with `sendImmediately`
|
322 |
+
set to `false`; otherwise `request` will send basic authentication on the
|
323 |
+
initial request, which will probably cause the request to fail.
|
324 |
+
|
325 |
+
Bearer authentication is supported, and is activated when the `bearer` value is
|
326 |
+
available. The value may be either a `String` or a `Function` returning a
|
327 |
+
`String`. Using a function to supply the bearer token is particularly useful if
|
328 |
+
used in conjunction with `defaults` to allow a single function to supply the
|
329 |
+
last known token at the time of sending a request, or to compute one on the fly.
|
330 |
+
|
331 |
+
[back to top](#table-of-contents)
|
332 |
+
|
333 |
+
|
334 |
+
---
|
335 |
+
|
336 |
+
|
337 |
+
## Custom HTTP Headers
|
338 |
+
|
339 |
+
HTTP Headers, such as `User-Agent`, can be set in the `options` object.
|
340 |
+
In the example below, we call the github API to find out the number
|
341 |
+
of stars and forks for the request repository. This requires a
|
342 |
+
custom `User-Agent` header as well as https.
|
343 |
+
|
344 |
+
```js
|
345 |
+
const request = require('request');
|
346 |
+
|
347 |
+
const options = {
|
348 |
+
url: 'https://api.github.com/repos/cypress-io/request',
|
349 |
+
headers: {
|
350 |
+
'User-Agent': 'request'
|
351 |
+
}
|
352 |
+
};
|
353 |
+
|
354 |
+
function callback(error, response, body) {
|
355 |
+
if (!error && response.statusCode == 200) {
|
356 |
+
const info = JSON.parse(body);
|
357 |
+
console.log(info.stargazers_count + " Stars");
|
358 |
+
console.log(info.forks_count + " Forks");
|
359 |
+
}
|
360 |
+
}
|
361 |
+
|
362 |
+
request(options, callback);
|
363 |
+
```
|
364 |
+
|
365 |
+
[back to top](#table-of-contents)
|
366 |
+
|
367 |
+
|
368 |
+
---
|
369 |
+
|
370 |
+
## Proxies
|
371 |
+
|
372 |
+
If you specify a `proxy` option, then the request (and any subsequent
|
373 |
+
redirects) will be sent via a connection to the proxy server.
|
374 |
+
|
375 |
+
If your endpoint is an `https` url, and you are using a proxy, then
|
376 |
+
request will send a `CONNECT` request to the proxy server *first*, and
|
377 |
+
then use the supplied connection to connect to the endpoint.
|
378 |
+
|
379 |
+
That is, first it will make a request like:
|
380 |
+
|
381 |
+
```
|
382 |
+
HTTP/1.1 CONNECT endpoint-server.com:80
|
383 |
+
Host: proxy-server.com
|
384 |
+
User-Agent: whatever user agent you specify
|
385 |
+
```
|
386 |
+
|
387 |
+
and then the proxy server make a TCP connection to `endpoint-server`
|
388 |
+
on port `80`, and return a response that looks like:
|
389 |
+
|
390 |
+
```
|
391 |
+
HTTP/1.1 200 OK
|
392 |
+
```
|
393 |
+
|
394 |
+
At this point, the connection is left open, and the client is
|
395 |
+
communicating directly with the `endpoint-server.com` machine.
|
396 |
+
|
397 |
+
See [the wikipedia page on HTTP Tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel)
|
398 |
+
for more information.
|
399 |
+
|
400 |
+
By default, when proxying `http` traffic, request will simply make a
|
401 |
+
standard proxied `http` request. This is done by making the `url`
|
402 |
+
section of the initial line of the request a fully qualified url to
|
403 |
+
the endpoint.
|
404 |
+
|
405 |
+
For example, it will make a single request that looks like:
|
406 |
+
|
407 |
+
```
|
408 |
+
HTTP/1.1 GET http://endpoint-server.com/some-url
|
409 |
+
Host: proxy-server.com
|
410 |
+
Other-Headers: all go here
|
411 |
+
|
412 |
+
request body or whatever
|
413 |
+
```
|
414 |
+
|
415 |
+
Because a pure "http over http" tunnel offers no additional security
|
416 |
+
or other features, it is generally simpler to go with a
|
417 |
+
straightforward HTTP proxy in this case. However, if you would like
|
418 |
+
to force a tunneling proxy, you may set the `tunnel` option to `true`.
|
419 |
+
|
420 |
+
You can also make a standard proxied `http` request by explicitly setting
|
421 |
+
`tunnel : false`, but **note that this will allow the proxy to see the traffic
|
422 |
+
to/from the destination server**.
|
423 |
+
|
424 |
+
If you are using a tunneling proxy, you may set the
|
425 |
+
`proxyHeaderWhiteList` to share certain headers with the proxy.
|
426 |
+
|
427 |
+
You can also set the `proxyHeaderExclusiveList` to share certain
|
428 |
+
headers only with the proxy and not with destination host.
|
429 |
+
|
430 |
+
By default, this set is:
|
431 |
+
|
432 |
+
```
|
433 |
+
accept
|
434 |
+
accept-charset
|
435 |
+
accept-encoding
|
436 |
+
accept-language
|
437 |
+
accept-ranges
|
438 |
+
cache-control
|
439 |
+
content-encoding
|
440 |
+
content-language
|
441 |
+
content-length
|
442 |
+
content-location
|
443 |
+
content-md5
|
444 |
+
content-range
|
445 |
+
content-type
|
446 |
+
connection
|
447 |
+
date
|
448 |
+
expect
|
449 |
+
max-forwards
|
450 |
+
pragma
|
451 |
+
proxy-authorization
|
452 |
+
referer
|
453 |
+
te
|
454 |
+
transfer-encoding
|
455 |
+
user-agent
|
456 |
+
via
|
457 |
+
```
|
458 |
+
|
459 |
+
Note that, when using a tunneling proxy, the `proxy-authorization`
|
460 |
+
header and any headers from custom `proxyHeaderExclusiveList` are
|
461 |
+
*never* sent to the endpoint server, but only to the proxy server.
|
462 |
+
|
463 |
+
|
464 |
+
### Controlling proxy behaviour using environment variables
|
465 |
+
|
466 |
+
The following environment variables are respected by `request`:
|
467 |
+
|
468 |
+
* `HTTP_PROXY` / `http_proxy`
|
469 |
+
* `HTTPS_PROXY` / `https_proxy`
|
470 |
+
* `NO_PROXY` / `no_proxy`
|
471 |
+
|
472 |
+
When `HTTP_PROXY` / `http_proxy` are set, they will be used to proxy non-SSL requests that do not have an explicit `proxy` configuration option present. Similarly, `HTTPS_PROXY` / `https_proxy` will be respected for SSL requests that do not have an explicit `proxy` configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the `proxy` configuration option. Furthermore, the `proxy` configuration option can be explicitly set to false / null to opt out of proxying altogether for that request.
|
473 |
+
|
474 |
+
`request` is also aware of the `NO_PROXY`/`no_proxy` environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to `*` to opt out of the implicit proxy configuration of the other environment variables.
|
475 |
+
|
476 |
+
Here's some examples of valid `no_proxy` values:
|
477 |
+
|
478 |
+
* `google.com` - don't proxy HTTP/HTTPS requests to Google.
|
479 |
+
* `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google.
|
480 |
+
* `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo!
|
481 |
+
* `*` - ignore `https_proxy`/`http_proxy` environment variables altogether.
|
482 |
+
|
483 |
+
[back to top](#table-of-contents)
|
484 |
+
|
485 |
+
|
486 |
+
---
|
487 |
+
|
488 |
+
|
489 |
+
## UNIX Domain Sockets
|
490 |
+
|
491 |
+
`request` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme:
|
492 |
+
|
493 |
+
```js
|
494 |
+
/* Pattern */ 'http://unix:SOCKET:PATH'
|
495 |
+
/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
|
496 |
+
```
|
497 |
+
|
498 |
+
Note: The `SOCKET` path is assumed to be absolute to the root of the host file system.
|
499 |
+
|
500 |
+
[back to top](#table-of-contents)
|
501 |
+
|
502 |
+
|
503 |
+
---
|
504 |
+
|
505 |
+
|
506 |
+
## TLS/SSL Protocol
|
507 |
+
|
508 |
+
TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be
|
509 |
+
set directly in `options` object, in the `agentOptions` property of the `options` object, or even in `https.globalAgent.options`. Keep in mind that, although `agentOptions` allows for a slightly wider range of configurations, the recommended way is via `options` object directly, as using `agentOptions` or `https.globalAgent.options` would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent).
|
510 |
+
|
511 |
+
```js
|
512 |
+
const fs = require('fs')
|
513 |
+
, path = require('path')
|
514 |
+
, certFile = path.resolve(__dirname, 'ssl/client.crt')
|
515 |
+
, keyFile = path.resolve(__dirname, 'ssl/client.key')
|
516 |
+
, caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
|
517 |
+
, request = require('request');
|
518 |
+
|
519 |
+
const options = {
|
520 |
+
url: 'https://api.some-server.com/',
|
521 |
+
cert: fs.readFileSync(certFile),
|
522 |
+
key: fs.readFileSync(keyFile),
|
523 |
+
passphrase: 'password',
|
524 |
+
ca: fs.readFileSync(caFile)
|
525 |
+
};
|
526 |
+
|
527 |
+
request.get(options);
|
528 |
+
```
|
529 |
+
|
530 |
+
### Using `options.agentOptions`
|
531 |
+
|
532 |
+
In the example below, we call an API that requires client side SSL certificate
|
533 |
+
(in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:
|
534 |
+
|
535 |
+
```js
|
536 |
+
const fs = require('fs')
|
537 |
+
, path = require('path')
|
538 |
+
, certFile = path.resolve(__dirname, 'ssl/client.crt')
|
539 |
+
, keyFile = path.resolve(__dirname, 'ssl/client.key')
|
540 |
+
, request = require('request');
|
541 |
+
|
542 |
+
const options = {
|
543 |
+
url: 'https://api.some-server.com/',
|
544 |
+
agentOptions: {
|
545 |
+
cert: fs.readFileSync(certFile),
|
546 |
+
key: fs.readFileSync(keyFile),
|
547 |
+
// Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format:
|
548 |
+
// pfx: fs.readFileSync(pfxFilePath),
|
549 |
+
passphrase: 'password',
|
550 |
+
securityOptions: 'SSL_OP_NO_SSLv3'
|
551 |
+
}
|
552 |
+
};
|
553 |
+
|
554 |
+
request.get(options);
|
555 |
+
```
|
556 |
+
|
557 |
+
It is able to force using SSLv3 only by specifying `secureProtocol`:
|
558 |
+
|
559 |
+
```js
|
560 |
+
request.get({
|
561 |
+
url: 'https://api.some-server.com/',
|
562 |
+
agentOptions: {
|
563 |
+
secureProtocol: 'SSLv3_method'
|
564 |
+
}
|
565 |
+
});
|
566 |
+
```
|
567 |
+
|
568 |
+
It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs).
|
569 |
+
This can be useful, for example, when using self-signed certificates.
|
570 |
+
To require a different root certificate, you can specify the signing CA by adding the contents of the CA's certificate file to the `agentOptions`.
|
571 |
+
The certificate the domain presents must be signed by the root certificate specified:
|
572 |
+
|
573 |
+
```js
|
574 |
+
request.get({
|
575 |
+
url: 'https://api.some-server.com/',
|
576 |
+
agentOptions: {
|
577 |
+
ca: fs.readFileSync('ca.cert.pem')
|
578 |
+
}
|
579 |
+
});
|
580 |
+
```
|
581 |
+
|
582 |
+
The `ca` value can be an array of certificates, in the event you have a private or internal corporate public-key infrastructure hierarchy. For example, if you want to connect to https://api.some-server.com which presents a key chain consisting of:
|
583 |
+
1. its own public key, which is signed by:
|
584 |
+
2. an intermediate "Corp Issuing Server", that is in turn signed by:
|
585 |
+
3. a root CA "Corp Root CA";
|
586 |
+
|
587 |
+
you can configure your request as follows:
|
588 |
+
|
589 |
+
```js
|
590 |
+
request.get({
|
591 |
+
url: 'https://api.some-server.com/',
|
592 |
+
agentOptions: {
|
593 |
+
ca: [
|
594 |
+
fs.readFileSync('Corp Issuing Server.pem'),
|
595 |
+
fs.readFileSync('Corp Root CA.pem')
|
596 |
+
]
|
597 |
+
}
|
598 |
+
});
|
599 |
+
```
|
600 |
+
|
601 |
+
[back to top](#table-of-contents)
|
602 |
+
|
603 |
+
|
604 |
+
---
|
605 |
+
|
606 |
+
## Support for HAR 1.2
|
607 |
+
|
608 |
+
The `options.har` property will override the values: `url`, `method`, `qs`, `headers`, `form`, `formData`, `body`, `json`, as well as construct multipart data and read files from disk when `request.postData.params[].fileName` is present without a matching `value`.
|
609 |
+
|
610 |
+
A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.
|
611 |
+
|
612 |
+
```js
|
613 |
+
const request = require('request')
|
614 |
+
request({
|
615 |
+
// will be ignored
|
616 |
+
method: 'GET',
|
617 |
+
uri: 'http://www.google.com',
|
618 |
+
|
619 |
+
// HTTP Archive Request Object
|
620 |
+
har: {
|
621 |
+
url: 'http://www.mockbin.com/har',
|
622 |
+
method: 'POST',
|
623 |
+
headers: [
|
624 |
+
{
|
625 |
+
name: 'content-type',
|
626 |
+
value: 'application/x-www-form-urlencoded'
|
627 |
+
}
|
628 |
+
],
|
629 |
+
postData: {
|
630 |
+
mimeType: 'application/x-www-form-urlencoded',
|
631 |
+
params: [
|
632 |
+
{
|
633 |
+
name: 'foo',
|
634 |
+
value: 'bar'
|
635 |
+
},
|
636 |
+
{
|
637 |
+
name: 'hello',
|
638 |
+
value: 'world'
|
639 |
+
}
|
640 |
+
]
|
641 |
+
}
|
642 |
+
}
|
643 |
+
})
|
644 |
+
|
645 |
+
// a POST request will be sent to http://www.mockbin.com
|
646 |
+
// with body an application/x-www-form-urlencoded body:
|
647 |
+
// foo=bar&hello=world
|
648 |
+
```
|
649 |
+
|
650 |
+
[back to top](#table-of-contents)
|
651 |
+
|
652 |
+
|
653 |
+
---
|
654 |
+
|
655 |
+
## request(options, callback)
|
656 |
+
|
657 |
+
The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional.
|
658 |
+
|
659 |
+
- `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()`
|
660 |
+
- `baseUrl` - fully qualified uri string used as the base url. Most useful with `request.defaults`, for example when you want to do many requests to the same domain. If `baseUrl` is `https://example.com/api/`, then requesting `/end/point?test=true` will fetch `https://example.com/api/end/point?test=true`. When `baseUrl` is given, `uri` must also be a string.
|
661 |
+
- `method` - http method (default: `"GET"`)
|
662 |
+
- `headers` - http headers (default: `{}`)
|
663 |
+
|
664 |
+
---
|
665 |
+
|
666 |
+
- `qs` - object containing querystring values to be appended to the `uri`
|
667 |
+
- `qsParseOptions` - object containing options to pass to the [qs.parse](https://github.com/hapijs/qs#parsing-objects) method. Alternatively pass options to the [querystring.parse](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_parse_str_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`
|
668 |
+
- `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`. For example, to change the way arrays are converted to query strings using the `qs` module pass the `arrayFormat` option with one of `indices|brackets|repeat`
|
669 |
+
- `useQuerystring` - if true, use `querystring` to stringify and parse
|
670 |
+
querystrings, otherwise use `qs` (default: `false`). Set this option to
|
671 |
+
`true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the
|
672 |
+
default `foo[0]=bar&foo[1]=baz`.
|
673 |
+
|
674 |
+
---
|
675 |
+
|
676 |
+
- `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer`, `String` or `ReadStream`. If `json` is `true`, then `body` must be a JSON-serializable object.
|
677 |
+
- `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded` header. When passed no options, a `FormData` instance is returned (and is piped to request). See "Forms" section above.
|
678 |
+
- `formData` - data to pass for a `multipart/form-data` request. See
|
679 |
+
[Forms](#forms) section above.
|
680 |
+
- `multipart` - array of objects which contain their own headers and `body`
|
681 |
+
attributes. Sends a `multipart/related` request. See [Forms](#forms) section
|
682 |
+
above.
|
683 |
+
- Alternatively you can pass in an object `{chunked: false, data: []}` where
|
684 |
+
`chunked` is used to specify whether the request is sent in
|
685 |
+
[chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding)
|
686 |
+
In non-chunked requests, data items with body streams are not allowed.
|
687 |
+
- `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request.
|
688 |
+
- `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request.
|
689 |
+
- `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
|
690 |
+
- `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body.
|
691 |
+
- `jsonReplacer` - a [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that will be passed to `JSON.stringify()` when stringifying a JSON request body.
|
692 |
+
|
693 |
+
---
|
694 |
+
|
695 |
+
- `auth` - a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
|
696 |
+
- `hawk` - options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
|
697 |
+
- `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`, and optionally `session` (note that this only works for services that require session as part of the canonical string). Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. If you are using SigV4, you can also include a `service` property that specifies the service name. **Note:** you need to `npm install aws4` first.
|
698 |
+
- `httpSignature` - options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
|
699 |
+
|
700 |
+
---
|
701 |
+
|
702 |
+
- `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`). This property can also be implemented as function which gets `response` object as the first argument.
|
703 |
+
- *(synchronous usage)* It should return `true` if redirects should continue or `false` otherwise. If it returns a url string, the destination of the redirect will be overridden.
|
704 |
+
- *(async callback usage)* If the function has two arguments, it will be treated as an asynchronous function and will be passed a callback as the second argument. Invoke the callback with an error (`null` if no error) and the boolean/url result as the second.
|
705 |
+
- *(async promise usage)* Return a promise that resolves to the boolean/url result.
|
706 |
+
- `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`)
|
707 |
+
- `followOriginalHttpMethod` - by default we redirect to HTTP method GET. you can enable this property to redirect to the original HTTP method (default: `false`)
|
708 |
+
- `maxRedirects` - the maximum number of redirects to follow (default: `10`)
|
709 |
+
- `removeRefererHeader` - removes the referer header when a redirect happens (default: `false`). **Note:** if true, referer header set in the initial request is preserved during redirect chain.
|
710 |
+
- `allowInsecureRedirect` - allows cross-protocol redirects (HTTP to HTTPS and vice versa). **Warning:** may lead to bypassing anti SSRF filters (default: `false`)
|
711 |
+
|
712 |
+
---
|
713 |
+
|
714 |
+
- `encoding` - encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.)
|
715 |
+
- `gzip` - if `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below.
|
716 |
+
- `jar` - if `true`, remember cookies for future use (or define your custom cookie jar; see examples section)
|
717 |
+
|
718 |
+
---
|
719 |
+
|
720 |
+
- `agent` - `http(s).Agent` instance to use
|
721 |
+
- `agentClass` - alternatively specify your agent's class name
|
722 |
+
- `agentOptions` - and pass its options. **Note:** for HTTPS see [tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) and the [documentation above](#using-optionsagentoptions).
|
723 |
+
- `forever` - set to `true` to use the [forever-agent](https://github.com/request/forever-agent) **Note:** Defaults to `http(s).Agent({keepAlive:true})` in node 0.12+
|
724 |
+
- `pool` - an object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified.
|
725 |
+
- A `maxSockets` property can also be provided on the `pool` object to set the max number of sockets for all agents created (ex: `pool: {maxSockets: Infinity}`).
|
726 |
+
- Note that if you are sending multiple requests in a loop and creating
|
727 |
+
multiple new `pool` objects, `maxSockets` will not work as intended. To
|
728 |
+
work around this, either use [`request.defaults`](#requestdefaultsoptions)
|
729 |
+
with your pool options or create the pool object with the `maxSockets`
|
730 |
+
property outside of the loop.
|
731 |
+
- `timeout` - integer containing number of milliseconds, controls two timeouts.
|
732 |
+
- **Read timeout**: Time to wait for a server to send response headers (and start the response body) before aborting the request.
|
733 |
+
- **Connection timeout**: Sets the socket to timeout after `timeout` milliseconds of inactivity. Note that increasing the timeout beyond the OS-wide TCP connection timeout will not have any effect ([the default in Linux can be anywhere from 20-120 seconds][linux-timeout])
|
734 |
+
|
735 |
+
[linux-timeout]: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout
|
736 |
+
|
737 |
+
---
|
738 |
+
|
739 |
+
- `localAddress` - local interface to bind for network connections.
|
740 |
+
- `proxy` - an HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)
|
741 |
+
- `strictSSL` - if `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
|
742 |
+
- `tunnel` - controls the behavior of
|
743 |
+
[HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling)
|
744 |
+
as follows:
|
745 |
+
- `undefined` (default) - `true` if the destination is `https`, `false` otherwise
|
746 |
+
- `true` - always tunnel to the destination by making a `CONNECT` request to
|
747 |
+
the proxy
|
748 |
+
- `false` - request the destination as a `GET` request.
|
749 |
+
- `proxyHeaderWhiteList` - a whitelist of headers to send to a
|
750 |
+
tunneling proxy.
|
751 |
+
- `proxyHeaderExclusiveList` - a whitelist of headers to send
|
752 |
+
exclusively to a tunneling proxy and not to destination.
|
753 |
+
|
754 |
+
---
|
755 |
+
|
756 |
+
- `time` - if `true`, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object:
|
757 |
+
- `elapsedTime` Duration of the entire request/response in milliseconds (*deprecated*).
|
758 |
+
- `responseStartTime` Timestamp when the response began (in Unix Epoch milliseconds) (*deprecated*).
|
759 |
+
- `timingStart` Timestamp of the start of the request (in Unix Epoch milliseconds).
|
760 |
+
- `timings` Contains event timestamps in millisecond resolution relative to `timingStart`. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
|
761 |
+
- `socket` Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_socket) module's `socket` event fires. This happens when the socket is assigned to the request.
|
762 |
+
- `lookup` Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_lookup) module's `lookup` event fires. This happens when the DNS has been resolved.
|
763 |
+
- `connect`: Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_connect) module's `connect` event fires. This happens when the server acknowledges the TCP connection.
|
764 |
+
- `response`: Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_response) module's `response` event fires. This happens when the first bytes are received from the server.
|
765 |
+
- `end`: Relative timestamp when the last bytes of the response are received.
|
766 |
+
- `timingPhases` Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
|
767 |
+
- `wait`: Duration of socket initialization (`timings.socket`)
|
768 |
+
- `dns`: Duration of DNS lookup (`timings.lookup` - `timings.socket`)
|
769 |
+
- `tcp`: Duration of TCP connection (`timings.connect` - `timings.socket`)
|
770 |
+
- `firstByte`: Duration of HTTP server response (`timings.response` - `timings.connect`)
|
771 |
+
- `download`: Duration of HTTP download (`timings.end` - `timings.response`)
|
772 |
+
- `total`: Duration entire HTTP round-trip (`timings.end`)
|
773 |
+
|
774 |
+
- `har` - a [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-12) for details)*
|
775 |
+
- `callback` - alternatively pass the request's callback in the options object
|
776 |
+
|
777 |
+
The callback argument gets 3 arguments:
|
778 |
+
|
779 |
+
1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object)
|
780 |
+
2. An [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) object (Response object)
|
781 |
+
3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied)
|
782 |
+
|
783 |
+
[back to top](#table-of-contents)
|
784 |
+
|
785 |
+
|
786 |
+
---
|
787 |
+
|
788 |
+
## Convenience methods
|
789 |
+
|
790 |
+
There are also shorthand methods for different HTTP METHODs and some other conveniences.
|
791 |
+
|
792 |
+
|
793 |
+
### request.defaults(options)
|
794 |
+
|
795 |
+
This method **returns a wrapper** around the normal request API that defaults
|
796 |
+
to whatever options you pass to it.
|
797 |
+
|
798 |
+
**Note:** `request.defaults()` **does not** modify the global request API;
|
799 |
+
instead, it **returns a wrapper** that has your default settings applied to it.
|
800 |
+
|
801 |
+
**Note:** You can call `.defaults()` on the wrapper that is returned from
|
802 |
+
`request.defaults` to add/override defaults that were previously defaulted.
|
803 |
+
|
804 |
+
For example:
|
805 |
+
```js
|
806 |
+
//requests using baseRequest() will set the 'x-token' header
|
807 |
+
const baseRequest = request.defaults({
|
808 |
+
headers: {'x-token': 'my-token'}
|
809 |
+
})
|
810 |
+
|
811 |
+
//requests using specialRequest() will include the 'x-token' header set in
|
812 |
+
//baseRequest and will also include the 'special' header
|
813 |
+
const specialRequest = baseRequest.defaults({
|
814 |
+
headers: {special: 'special value'}
|
815 |
+
})
|
816 |
+
```
|
817 |
+
|
818 |
+
### request.METHOD()
|
819 |
+
|
820 |
+
These HTTP method convenience functions act just like `request()` but with a default method already set for you:
|
821 |
+
|
822 |
+
- *request.get()*: Defaults to `method: "GET"`.
|
823 |
+
- *request.post()*: Defaults to `method: "POST"`.
|
824 |
+
- *request.put()*: Defaults to `method: "PUT"`.
|
825 |
+
- *request.patch()*: Defaults to `method: "PATCH"`.
|
826 |
+
- *request.del() / request.delete()*: Defaults to `method: "DELETE"`.
|
827 |
+
- *request.head()*: Defaults to `method: "HEAD"`.
|
828 |
+
- *request.options()*: Defaults to `method: "OPTIONS"`.
|
829 |
+
|
830 |
+
### request.cookie()
|
831 |
+
|
832 |
+
Function that creates a new cookie.
|
833 |
+
|
834 |
+
```js
|
835 |
+
request.cookie('key1=value1')
|
836 |
+
```
|
837 |
+
### request.jar()
|
838 |
+
|
839 |
+
Function that creates a new cookie jar.
|
840 |
+
|
841 |
+
```js
|
842 |
+
request.jar()
|
843 |
+
```
|
844 |
+
|
845 |
+
### response.caseless.get('header-name')
|
846 |
+
|
847 |
+
Function that returns the specified response header field using a [case-insensitive match](https://tools.ietf.org/html/rfc7230#section-3.2)
|
848 |
+
|
849 |
+
```js
|
850 |
+
request('http://www.google.com', function (error, response, body) {
|
851 |
+
// print the Content-Type header even if the server returned it as 'content-type' (lowercase)
|
852 |
+
console.log('Content-Type is:', response.caseless.get('Content-Type'));
|
853 |
+
});
|
854 |
+
```
|
855 |
+
|
856 |
+
[back to top](#table-of-contents)
|
857 |
+
|
858 |
+
|
859 |
+
---
|
860 |
+
|
861 |
+
|
862 |
+
## Debugging
|
863 |
+
|
864 |
+
There are at least three ways to debug the operation of `request`:
|
865 |
+
|
866 |
+
1. Launch the node process like `NODE_DEBUG=request node script.js`
|
867 |
+
(`lib,request,otherlib` works too).
|
868 |
+
|
869 |
+
2. Set `require('request').debug = true` at any time (this does the same thing
|
870 |
+
as #1).
|
871 |
+
|
872 |
+
3. Use the [request-debug module](https://github.com/cypress-io/request-debug) to
|
873 |
+
view request and response headers and bodies.
|
874 |
+
|
875 |
+
[back to top](#table-of-contents)
|
876 |
+
|
877 |
+
|
878 |
+
---
|
879 |
+
|
880 |
+
## Timeouts
|
881 |
+
|
882 |
+
Most requests to external servers should have a timeout attached, in case the
|
883 |
+
server is not responding in a timely manner. Without a timeout, your code may
|
884 |
+
have a socket open/consume resources for minutes or more.
|
885 |
+
|
886 |
+
There are two main types of timeouts: **connection timeouts** and **read
|
887 |
+
timeouts**. A connect timeout occurs if the timeout is hit while your client is
|
888 |
+
attempting to establish a connection to a remote machine (corresponding to the
|
889 |
+
[connect() call][connect] on the socket). A read timeout occurs any time the
|
890 |
+
server is too slow to send back a part of the response.
|
891 |
+
|
892 |
+
These two situations have widely different implications for what went wrong
|
893 |
+
with the request, so it's useful to be able to distinguish them. You can detect
|
894 |
+
timeout errors by checking `err.code` for an 'ETIMEDOUT' value. Further, you
|
895 |
+
can detect whether the timeout was a connection timeout by checking if the
|
896 |
+
`err.connect` property is set to `true`.
|
897 |
+
|
898 |
+
```js
|
899 |
+
request.get('http://10.255.255.1', {timeout: 1500}, function(err) {
|
900 |
+
console.log(err.code === 'ETIMEDOUT');
|
901 |
+
// Set to `true` if the timeout was a connection timeout, `false` or
|
902 |
+
// `undefined` otherwise.
|
903 |
+
console.log(err.connect === true);
|
904 |
+
process.exit(0);
|
905 |
+
});
|
906 |
+
```
|
907 |
+
|
908 |
+
[connect]: http://linux.die.net/man/2/connect
|
909 |
+
|
910 |
+
## Examples:
|
911 |
+
|
912 |
+
```js
|
913 |
+
const request = require('request')
|
914 |
+
, rand = Math.floor(Math.random()*100000000).toString()
|
915 |
+
;
|
916 |
+
request(
|
917 |
+
{ method: 'PUT'
|
918 |
+
, uri: 'http://mikeal.iriscouch.com/testjs/' + rand
|
919 |
+
, multipart:
|
920 |
+
[ { 'content-type': 'application/json'
|
921 |
+
, body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
|
922 |
+
}
|
923 |
+
, { body: 'I am an attachment' }
|
924 |
+
]
|
925 |
+
}
|
926 |
+
, function (error, response, body) {
|
927 |
+
if(response.statusCode == 201){
|
928 |
+
console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
|
929 |
+
} else {
|
930 |
+
console.log('error: '+ response.statusCode)
|
931 |
+
console.log(body)
|
932 |
+
}
|
933 |
+
}
|
934 |
+
)
|
935 |
+
```
|
936 |
+
|
937 |
+
For backwards-compatibility, response compression is not supported by default.
|
938 |
+
To accept gzip-compressed responses, set the `gzip` option to `true`. Note
|
939 |
+
that the body data passed through `request` is automatically decompressed
|
940 |
+
while the response object is unmodified and will contain compressed data if
|
941 |
+
the server sent a compressed response.
|
942 |
+
|
943 |
+
```js
|
944 |
+
const request = require('request')
|
945 |
+
request(
|
946 |
+
{ method: 'GET'
|
947 |
+
, uri: 'http://www.google.com'
|
948 |
+
, gzip: true
|
949 |
+
}
|
950 |
+
, function (error, response, body) {
|
951 |
+
// body is the decompressed response body
|
952 |
+
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
|
953 |
+
console.log('the decoded data is: ' + body)
|
954 |
+
}
|
955 |
+
)
|
956 |
+
.on('data', function(data) {
|
957 |
+
// decompressed data as it is received
|
958 |
+
console.log('decoded chunk: ' + data)
|
959 |
+
})
|
960 |
+
.on('response', function(response) {
|
961 |
+
// unmodified http.IncomingMessage object
|
962 |
+
response.on('data', function(data) {
|
963 |
+
// compressed data as it is received
|
964 |
+
console.log('received ' + data.length + ' bytes of compressed data')
|
965 |
+
})
|
966 |
+
})
|
967 |
+
```
|
968 |
+
|
969 |
+
Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set `jar` to `true` (either in `defaults` or `options`).
|
970 |
+
|
971 |
+
```js
|
972 |
+
const request = request.defaults({jar: true})
|
973 |
+
request('http://www.google.com', function () {
|
974 |
+
request('http://images.google.com')
|
975 |
+
})
|
976 |
+
```
|
977 |
+
|
978 |
+
To use a custom cookie jar (instead of `request`’s global cookie jar), set `jar` to an instance of `request.jar()` (either in `defaults` or `options`)
|
979 |
+
|
980 |
+
```js
|
981 |
+
const j = request.jar()
|
982 |
+
const request = request.defaults({jar:j})
|
983 |
+
request('http://www.google.com', function () {
|
984 |
+
request('http://images.google.com')
|
985 |
+
})
|
986 |
+
```
|
987 |
+
|
988 |
+
OR
|
989 |
+
|
990 |
+
```js
|
991 |
+
const j = request.jar();
|
992 |
+
const cookie = request.cookie('key1=value1');
|
993 |
+
const url = 'http://www.google.com';
|
994 |
+
j.setCookie(cookie, url);
|
995 |
+
request({url: url, jar: j}, function () {
|
996 |
+
request('http://images.google.com')
|
997 |
+
})
|
998 |
+
```
|
999 |
+
|
1000 |
+
To use a custom cookie store (such as a
|
1001 |
+
[`FileCookieStore`](https://github.com/mitsuru/tough-cookie-filestore)
|
1002 |
+
which supports saving to and restoring from JSON files), pass it as a parameter
|
1003 |
+
to `request.jar()`:
|
1004 |
+
|
1005 |
+
```js
|
1006 |
+
const FileCookieStore = require('tough-cookie-filestore');
|
1007 |
+
// NOTE - currently the 'cookies.json' file must already exist!
|
1008 |
+
const j = request.jar(new FileCookieStore('cookies.json'));
|
1009 |
+
request = request.defaults({ jar : j })
|
1010 |
+
request('http://www.google.com', function() {
|
1011 |
+
request('http://images.google.com')
|
1012 |
+
})
|
1013 |
+
```
|
1014 |
+
|
1015 |
+
The cookie store must be a
|
1016 |
+
[`tough-cookie`](https://github.com/SalesforceEng/tough-cookie)
|
1017 |
+
store and it must support synchronous operations; see the
|
1018 |
+
[`CookieStore` API docs](https://github.com/SalesforceEng/tough-cookie#api)
|
1019 |
+
for details.
|
1020 |
+
|
1021 |
+
To inspect your cookie jar after a request:
|
1022 |
+
|
1023 |
+
```js
|
1024 |
+
const j = request.jar()
|
1025 |
+
request({url: 'http://www.google.com', jar: j}, function () {
|
1026 |
+
const cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..."
|
1027 |
+
const cookies = j.getCookies(url);
|
1028 |
+
// [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...]
|
1029 |
+
})
|
1030 |
+
```
|
1031 |
+
|
1032 |
+
[back to top](#table-of-contents)
|
node_modules/@cypress/request/index.js
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010-2012 Mikeal Rogers
|
2 |
+
//
|
3 |
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
// you may not use this file except in compliance with the License.
|
5 |
+
// You may obtain a copy of the License at
|
6 |
+
//
|
7 |
+
// http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
//
|
9 |
+
// Unless required by applicable law or agreed to in writing, software
|
10 |
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
// See the License for the specific language governing permissions and
|
13 |
+
// limitations under the License.
|
14 |
+
|
15 |
+
'use strict'
|
16 |
+
|
17 |
+
var extend = require('extend')
|
18 |
+
var cookies = require('./lib/cookies')
|
19 |
+
var helpers = require('./lib/helpers')
|
20 |
+
|
21 |
+
var paramsHaveRequestBody = helpers.paramsHaveRequestBody
|
22 |
+
|
23 |
+
// organize params for patch, post, put, head, del
|
24 |
+
function initParams (uri, options, callback) {
|
25 |
+
if (typeof options === 'function') {
|
26 |
+
callback = options
|
27 |
+
}
|
28 |
+
|
29 |
+
var params = {}
|
30 |
+
if (options !== null && typeof options === 'object') {
|
31 |
+
extend(params, options, {uri: uri})
|
32 |
+
} else if (typeof uri === 'string') {
|
33 |
+
extend(params, {uri: uri})
|
34 |
+
} else {
|
35 |
+
extend(params, uri)
|
36 |
+
}
|
37 |
+
|
38 |
+
params.callback = callback || params.callback
|
39 |
+
return params
|
40 |
+
}
|
41 |
+
|
42 |
+
function request (uri, options, callback) {
|
43 |
+
if (typeof uri === 'undefined') {
|
44 |
+
throw new Error('undefined is not a valid uri or options object.')
|
45 |
+
}
|
46 |
+
|
47 |
+
var params = initParams(uri, options, callback)
|
48 |
+
|
49 |
+
if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
|
50 |
+
throw new Error('HTTP HEAD requests MUST NOT include a request body.')
|
51 |
+
}
|
52 |
+
|
53 |
+
return new request.Request(params)
|
54 |
+
}
|
55 |
+
|
56 |
+
function verbFunc (verb) {
|
57 |
+
var method = verb.toUpperCase()
|
58 |
+
return function (uri, options, callback) {
|
59 |
+
var params = initParams(uri, options, callback)
|
60 |
+
params.method = method
|
61 |
+
return request(params, params.callback)
|
62 |
+
}
|
63 |
+
}
|
64 |
+
|
65 |
+
// define like this to please codeintel/intellisense IDEs
|
66 |
+
request.get = verbFunc('get')
|
67 |
+
request.head = verbFunc('head')
|
68 |
+
request.options = verbFunc('options')
|
69 |
+
request.post = verbFunc('post')
|
70 |
+
request.put = verbFunc('put')
|
71 |
+
request.patch = verbFunc('patch')
|
72 |
+
request.del = verbFunc('delete')
|
73 |
+
request['delete'] = verbFunc('delete')
|
74 |
+
|
75 |
+
request.jar = function (store) {
|
76 |
+
return cookies.jar(store)
|
77 |
+
}
|
78 |
+
|
79 |
+
request.cookie = function (str) {
|
80 |
+
return cookies.parse(str)
|
81 |
+
}
|
82 |
+
|
83 |
+
function wrapRequestMethod (method, options, requester, verb) {
|
84 |
+
return function (uri, opts, callback) {
|
85 |
+
var params = initParams(uri, opts, callback)
|
86 |
+
|
87 |
+
var target = {}
|
88 |
+
extend(true, target, options, params)
|
89 |
+
|
90 |
+
target.pool = params.pool || options.pool
|
91 |
+
|
92 |
+
if (verb) {
|
93 |
+
target.method = verb.toUpperCase()
|
94 |
+
}
|
95 |
+
|
96 |
+
if (typeof requester === 'function') {
|
97 |
+
method = requester
|
98 |
+
}
|
99 |
+
|
100 |
+
return method(target, target.callback)
|
101 |
+
}
|
102 |
+
}
|
103 |
+
|
104 |
+
request.defaults = function (options, requester) {
|
105 |
+
var self = this
|
106 |
+
|
107 |
+
options = options || {}
|
108 |
+
|
109 |
+
if (typeof options === 'function') {
|
110 |
+
requester = options
|
111 |
+
options = {}
|
112 |
+
}
|
113 |
+
|
114 |
+
var defaults = wrapRequestMethod(self, options, requester)
|
115 |
+
|
116 |
+
var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
|
117 |
+
verbs.forEach(function (verb) {
|
118 |
+
defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
|
119 |
+
})
|
120 |
+
|
121 |
+
defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
|
122 |
+
defaults.jar = self.jar
|
123 |
+
defaults.defaults = self.defaults
|
124 |
+
return defaults
|
125 |
+
}
|
126 |
+
|
127 |
+
request.forever = function (agentOptions, optionsArg) {
|
128 |
+
var options = {}
|
129 |
+
if (optionsArg) {
|
130 |
+
extend(options, optionsArg)
|
131 |
+
}
|
132 |
+
if (agentOptions) {
|
133 |
+
options.agentOptions = agentOptions
|
134 |
+
}
|
135 |
+
|
136 |
+
options.forever = true
|
137 |
+
return request.defaults(options)
|
138 |
+
}
|
139 |
+
|
140 |
+
// Exports
|
141 |
+
|
142 |
+
module.exports = request
|
143 |
+
request.Request = require('./request')
|
144 |
+
request.initParams = initParams
|
145 |
+
|
146 |
+
// Backwards compatibility for request.debug
|
147 |
+
Object.defineProperty(request, 'debug', {
|
148 |
+
enumerable: true,
|
149 |
+
get: function () {
|
150 |
+
return request.Request.debug
|
151 |
+
},
|
152 |
+
set: function (debug) {
|
153 |
+
request.Request.debug = debug
|
154 |
+
}
|
155 |
+
})
|
node_modules/@cypress/request/lib/auth.js
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var caseless = require('caseless')
|
4 |
+
var { v4: uuid } = require('uuid')
|
5 |
+
var helpers = require('./helpers')
|
6 |
+
|
7 |
+
var md5 = helpers.md5
|
8 |
+
var toBase64 = helpers.toBase64
|
9 |
+
|
10 |
+
function Auth (request) {
|
11 |
+
// define all public properties here
|
12 |
+
this.request = request
|
13 |
+
this.hasAuth = false
|
14 |
+
this.sentAuth = false
|
15 |
+
this.bearerToken = null
|
16 |
+
this.user = null
|
17 |
+
this.pass = null
|
18 |
+
}
|
19 |
+
|
20 |
+
Auth.prototype.basic = function (user, pass, sendImmediately) {
|
21 |
+
var self = this
|
22 |
+
if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
|
23 |
+
self.request.emit('error', new Error('auth() received invalid user or password'))
|
24 |
+
}
|
25 |
+
self.user = user
|
26 |
+
self.pass = pass
|
27 |
+
self.hasAuth = true
|
28 |
+
var header = user + ':' + (pass || '')
|
29 |
+
if (sendImmediately || typeof sendImmediately === 'undefined') {
|
30 |
+
var authHeader = 'Basic ' + toBase64(header)
|
31 |
+
self.sentAuth = true
|
32 |
+
return authHeader
|
33 |
+
}
|
34 |
+
}
|
35 |
+
|
36 |
+
Auth.prototype.bearer = function (bearer, sendImmediately) {
|
37 |
+
var self = this
|
38 |
+
self.bearerToken = bearer
|
39 |
+
self.hasAuth = true
|
40 |
+
if (sendImmediately || typeof sendImmediately === 'undefined') {
|
41 |
+
if (typeof bearer === 'function') {
|
42 |
+
bearer = bearer()
|
43 |
+
}
|
44 |
+
var authHeader = 'Bearer ' + (bearer || '')
|
45 |
+
self.sentAuth = true
|
46 |
+
return authHeader
|
47 |
+
}
|
48 |
+
}
|
49 |
+
|
50 |
+
Auth.prototype.digest = function (method, path, authHeader) {
|
51 |
+
// TODO: More complete implementation of RFC 2617.
|
52 |
+
// - handle challenge.domain
|
53 |
+
// - support qop="auth-int" only
|
54 |
+
// - handle Authentication-Info (not necessarily?)
|
55 |
+
// - check challenge.stale (not necessarily?)
|
56 |
+
// - increase nc (not necessarily?)
|
57 |
+
// For reference:
|
58 |
+
// http://tools.ietf.org/html/rfc2617#section-3
|
59 |
+
// https://github.com/bagder/curl/blob/master/lib/http_digest.c
|
60 |
+
|
61 |
+
var self = this
|
62 |
+
|
63 |
+
var challenge = {}
|
64 |
+
var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
|
65 |
+
while (true) {
|
66 |
+
var match = re.exec(authHeader)
|
67 |
+
if (!match) {
|
68 |
+
break
|
69 |
+
}
|
70 |
+
challenge[match[1]] = match[2] || match[3]
|
71 |
+
}
|
72 |
+
|
73 |
+
/**
|
74 |
+
* RFC 2617: handle both MD5 and MD5-sess algorithms.
|
75 |
+
*
|
76 |
+
* If the algorithm directive's value is "MD5" or unspecified, then HA1 is
|
77 |
+
* HA1=MD5(username:realm:password)
|
78 |
+
* If the algorithm directive's value is "MD5-sess", then HA1 is
|
79 |
+
* HA1=MD5(MD5(username:realm:password):nonce:cnonce)
|
80 |
+
*/
|
81 |
+
var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
|
82 |
+
var ha1 = md5(user + ':' + realm + ':' + pass)
|
83 |
+
if (algorithm && algorithm.toLowerCase() === 'md5-sess') {
|
84 |
+
return md5(ha1 + ':' + nonce + ':' + cnonce)
|
85 |
+
} else {
|
86 |
+
return ha1
|
87 |
+
}
|
88 |
+
}
|
89 |
+
|
90 |
+
var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
|
91 |
+
var nc = qop && '00000001'
|
92 |
+
var cnonce = qop && uuid().replace(/-/g, '')
|
93 |
+
var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce)
|
94 |
+
var ha2 = md5(method + ':' + path)
|
95 |
+
var digestResponse = qop
|
96 |
+
? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
|
97 |
+
: md5(ha1 + ':' + challenge.nonce + ':' + ha2)
|
98 |
+
var authValues = {
|
99 |
+
username: self.user,
|
100 |
+
realm: challenge.realm,
|
101 |
+
nonce: challenge.nonce,
|
102 |
+
uri: path,
|
103 |
+
qop: qop,
|
104 |
+
response: digestResponse,
|
105 |
+
nc: nc,
|
106 |
+
cnonce: cnonce,
|
107 |
+
algorithm: challenge.algorithm,
|
108 |
+
opaque: challenge.opaque
|
109 |
+
}
|
110 |
+
|
111 |
+
authHeader = []
|
112 |
+
for (var k in authValues) {
|
113 |
+
if (authValues[k]) {
|
114 |
+
if (k === 'qop' || k === 'nc' || k === 'algorithm') {
|
115 |
+
authHeader.push(k + '=' + authValues[k])
|
116 |
+
} else {
|
117 |
+
authHeader.push(k + '="' + authValues[k] + '"')
|
118 |
+
}
|
119 |
+
}
|
120 |
+
}
|
121 |
+
authHeader = 'Digest ' + authHeader.join(', ')
|
122 |
+
self.sentAuth = true
|
123 |
+
return authHeader
|
124 |
+
}
|
125 |
+
|
126 |
+
Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
|
127 |
+
var self = this
|
128 |
+
var request = self.request
|
129 |
+
|
130 |
+
var authHeader
|
131 |
+
if (bearer === undefined && user === undefined) {
|
132 |
+
self.request.emit('error', new Error('no auth mechanism defined'))
|
133 |
+
} else if (bearer !== undefined) {
|
134 |
+
authHeader = self.bearer(bearer, sendImmediately)
|
135 |
+
} else {
|
136 |
+
authHeader = self.basic(user, pass, sendImmediately)
|
137 |
+
}
|
138 |
+
if (authHeader) {
|
139 |
+
request.setHeader('authorization', authHeader)
|
140 |
+
}
|
141 |
+
}
|
142 |
+
|
143 |
+
Auth.prototype.onResponse = function (response) {
|
144 |
+
var self = this
|
145 |
+
var request = self.request
|
146 |
+
|
147 |
+
if (!self.hasAuth || self.sentAuth) { return null }
|
148 |
+
|
149 |
+
var c = caseless(response.headers)
|
150 |
+
|
151 |
+
var authHeader = c.get('www-authenticate')
|
152 |
+
var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
|
153 |
+
request.debug('reauth', authVerb)
|
154 |
+
|
155 |
+
switch (authVerb) {
|
156 |
+
case 'basic':
|
157 |
+
return self.basic(self.user, self.pass, true)
|
158 |
+
|
159 |
+
case 'bearer':
|
160 |
+
return self.bearer(self.bearerToken, true)
|
161 |
+
|
162 |
+
case 'digest':
|
163 |
+
return self.digest(request.method, request.path, authHeader)
|
164 |
+
}
|
165 |
+
}
|
166 |
+
|
167 |
+
exports.Auth = Auth
|
node_modules/@cypress/request/lib/cookies.js
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var tough = require('tough-cookie')
|
4 |
+
|
5 |
+
var Cookie = tough.Cookie
|
6 |
+
var CookieJar = tough.CookieJar
|
7 |
+
|
8 |
+
exports.parse = function (str) {
|
9 |
+
if (str && str.uri) {
|
10 |
+
str = str.uri
|
11 |
+
}
|
12 |
+
if (typeof str !== 'string') {
|
13 |
+
throw new Error('The cookie function only accepts STRING as param')
|
14 |
+
}
|
15 |
+
return Cookie.parse(str, {loose: true})
|
16 |
+
}
|
17 |
+
|
18 |
+
// Adapt the sometimes-Async api of tough.CookieJar to our requirements
|
19 |
+
function RequestJar (store) {
|
20 |
+
var self = this
|
21 |
+
self._jar = new CookieJar(store, {looseMode: true})
|
22 |
+
}
|
23 |
+
RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
|
24 |
+
var self = this
|
25 |
+
return self._jar.setCookieSync(cookieOrStr, uri, options || {})
|
26 |
+
}
|
27 |
+
RequestJar.prototype.getCookieString = function (uri) {
|
28 |
+
var self = this
|
29 |
+
return self._jar.getCookieStringSync(uri)
|
30 |
+
}
|
31 |
+
RequestJar.prototype.getCookies = function (uri) {
|
32 |
+
var self = this
|
33 |
+
return self._jar.getCookiesSync(uri)
|
34 |
+
}
|
35 |
+
|
36 |
+
exports.jar = function (store) {
|
37 |
+
return new RequestJar(store)
|
38 |
+
}
|
node_modules/@cypress/request/lib/getProxyFromURI.js
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
function formatHostname (hostname) {
|
4 |
+
// canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
|
5 |
+
return hostname.replace(/^\.*/, '.').toLowerCase()
|
6 |
+
}
|
7 |
+
|
8 |
+
function parseNoProxyZone (zone) {
|
9 |
+
zone = zone.trim().toLowerCase()
|
10 |
+
|
11 |
+
var zoneParts = zone.split(':', 2)
|
12 |
+
var zoneHost = formatHostname(zoneParts[0])
|
13 |
+
var zonePort = zoneParts[1]
|
14 |
+
var hasPort = zone.indexOf(':') > -1
|
15 |
+
|
16 |
+
return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
|
17 |
+
}
|
18 |
+
|
19 |
+
function uriInNoProxy (uri, noProxy) {
|
20 |
+
var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
|
21 |
+
var hostname = formatHostname(uri.hostname)
|
22 |
+
var noProxyList = noProxy.split(',')
|
23 |
+
|
24 |
+
// iterate through the noProxyList until it finds a match.
|
25 |
+
return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
|
26 |
+
var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
|
27 |
+
var hostnameMatched = (
|
28 |
+
isMatchedAt > -1 &&
|
29 |
+
(isMatchedAt === hostname.length - noProxyZone.hostname.length)
|
30 |
+
)
|
31 |
+
|
32 |
+
if (noProxyZone.hasPort) {
|
33 |
+
return (port === noProxyZone.port) && hostnameMatched
|
34 |
+
}
|
35 |
+
|
36 |
+
return hostnameMatched
|
37 |
+
})
|
38 |
+
}
|
39 |
+
|
40 |
+
function getProxyFromURI (uri) {
|
41 |
+
// Decide the proper request proxy to use based on the request URI object and the
|
42 |
+
// environmental variables (NO_PROXY, HTTP_PROXY, etc.)
|
43 |
+
// respect NO_PROXY environment variables (see: https://lynx.invisible-island.net/lynx2.8.7/breakout/lynx_help/keystrokes/environments.html)
|
44 |
+
|
45 |
+
var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
|
46 |
+
|
47 |
+
// if the noProxy is a wildcard then return null
|
48 |
+
|
49 |
+
if (noProxy === '*') {
|
50 |
+
return null
|
51 |
+
}
|
52 |
+
|
53 |
+
// if the noProxy is not empty and the uri is found return null
|
54 |
+
|
55 |
+
if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
|
56 |
+
return null
|
57 |
+
}
|
58 |
+
|
59 |
+
// Check for HTTP or HTTPS Proxy in environment Else default to null
|
60 |
+
|
61 |
+
if (uri.protocol === 'http:') {
|
62 |
+
return process.env.HTTP_PROXY ||
|
63 |
+
process.env.http_proxy || null
|
64 |
+
}
|
65 |
+
|
66 |
+
if (uri.protocol === 'https:') {
|
67 |
+
return process.env.HTTPS_PROXY ||
|
68 |
+
process.env.https_proxy ||
|
69 |
+
process.env.HTTP_PROXY ||
|
70 |
+
process.env.http_proxy || null
|
71 |
+
}
|
72 |
+
|
73 |
+
// if none of that works, return null
|
74 |
+
// (What uri protocol are you using then?)
|
75 |
+
|
76 |
+
return null
|
77 |
+
}
|
78 |
+
|
79 |
+
module.exports = getProxyFromURI
|
node_modules/@cypress/request/lib/har.js
ADDED
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var fs = require('fs')
|
4 |
+
var qs = require('querystring')
|
5 |
+
var extend = require('extend')
|
6 |
+
|
7 |
+
function Har (request) {
|
8 |
+
this.request = request
|
9 |
+
}
|
10 |
+
|
11 |
+
Har.prototype.reducer = function (obj, pair) {
|
12 |
+
// new property ?
|
13 |
+
if (obj[pair.name] === undefined) {
|
14 |
+
obj[pair.name] = pair.value
|
15 |
+
return obj
|
16 |
+
}
|
17 |
+
|
18 |
+
// existing? convert to array
|
19 |
+
var arr = [
|
20 |
+
obj[pair.name],
|
21 |
+
pair.value
|
22 |
+
]
|
23 |
+
|
24 |
+
obj[pair.name] = arr
|
25 |
+
|
26 |
+
return obj
|
27 |
+
}
|
28 |
+
|
29 |
+
Har.prototype.prep = function (data) {
|
30 |
+
// construct utility properties
|
31 |
+
data.queryObj = {}
|
32 |
+
data.headersObj = {}
|
33 |
+
data.postData.jsonObj = false
|
34 |
+
data.postData.paramsObj = false
|
35 |
+
|
36 |
+
// construct query objects
|
37 |
+
if (data.queryString && data.queryString.length) {
|
38 |
+
data.queryObj = data.queryString.reduce(this.reducer, {})
|
39 |
+
}
|
40 |
+
|
41 |
+
// construct headers objects
|
42 |
+
if (data.headers && data.headers.length) {
|
43 |
+
// loweCase header keys
|
44 |
+
data.headersObj = data.headers.reduceRight(function (headers, header) {
|
45 |
+
headers[header.name] = header.value
|
46 |
+
return headers
|
47 |
+
}, {})
|
48 |
+
}
|
49 |
+
|
50 |
+
// construct Cookie header
|
51 |
+
if (data.cookies && data.cookies.length) {
|
52 |
+
var cookies = data.cookies.map(function (cookie) {
|
53 |
+
return cookie.name + '=' + cookie.value
|
54 |
+
})
|
55 |
+
|
56 |
+
if (cookies.length) {
|
57 |
+
data.headersObj.cookie = cookies.join('; ')
|
58 |
+
}
|
59 |
+
}
|
60 |
+
|
61 |
+
// prep body
|
62 |
+
function some (arr) {
|
63 |
+
return arr.some(function (type) {
|
64 |
+
return data.postData.mimeType.indexOf(type) === 0
|
65 |
+
})
|
66 |
+
}
|
67 |
+
|
68 |
+
if (some([
|
69 |
+
'multipart/mixed',
|
70 |
+
'multipart/related',
|
71 |
+
'multipart/form-data',
|
72 |
+
'multipart/alternative'])) {
|
73 |
+
// reset values
|
74 |
+
data.postData.mimeType = 'multipart/form-data'
|
75 |
+
} else if (some([
|
76 |
+
'application/x-www-form-urlencoded'])) {
|
77 |
+
if (!data.postData.params) {
|
78 |
+
data.postData.text = ''
|
79 |
+
} else {
|
80 |
+
data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
|
81 |
+
|
82 |
+
// always overwrite
|
83 |
+
data.postData.text = qs.stringify(data.postData.paramsObj)
|
84 |
+
}
|
85 |
+
} else if (some([
|
86 |
+
'text/json',
|
87 |
+
'text/x-json',
|
88 |
+
'application/json',
|
89 |
+
'application/x-json'])) {
|
90 |
+
data.postData.mimeType = 'application/json'
|
91 |
+
|
92 |
+
if (data.postData.text) {
|
93 |
+
try {
|
94 |
+
data.postData.jsonObj = JSON.parse(data.postData.text)
|
95 |
+
} catch (e) {
|
96 |
+
this.request.debug(e)
|
97 |
+
|
98 |
+
// force back to text/plain
|
99 |
+
data.postData.mimeType = 'text/plain'
|
100 |
+
}
|
101 |
+
}
|
102 |
+
}
|
103 |
+
|
104 |
+
return data
|
105 |
+
}
|
106 |
+
|
107 |
+
Har.prototype.options = function (options) {
|
108 |
+
// skip if no har property defined
|
109 |
+
if (!options.har) {
|
110 |
+
return options
|
111 |
+
}
|
112 |
+
|
113 |
+
var har = {}
|
114 |
+
extend(har, options.har)
|
115 |
+
|
116 |
+
// only process the first entry
|
117 |
+
if (har.log && har.log.entries) {
|
118 |
+
har = har.log.entries[0]
|
119 |
+
}
|
120 |
+
|
121 |
+
// add optional properties to make validation successful
|
122 |
+
har.url = har.url || options.url || options.uri || options.baseUrl || '/'
|
123 |
+
har.httpVersion = har.httpVersion || 'HTTP/1.1'
|
124 |
+
har.queryString = har.queryString || []
|
125 |
+
har.headers = har.headers || []
|
126 |
+
har.cookies = har.cookies || []
|
127 |
+
har.postData = har.postData || {}
|
128 |
+
har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
|
129 |
+
|
130 |
+
har.bodySize = 0
|
131 |
+
har.headersSize = 0
|
132 |
+
har.postData.size = 0
|
133 |
+
|
134 |
+
// clean up and get some utility properties
|
135 |
+
var req = this.prep(har)
|
136 |
+
|
137 |
+
// construct new options
|
138 |
+
if (req.url) {
|
139 |
+
options.url = req.url
|
140 |
+
}
|
141 |
+
|
142 |
+
if (req.method) {
|
143 |
+
options.method = req.method
|
144 |
+
}
|
145 |
+
|
146 |
+
if (Object.keys(req.queryObj).length) {
|
147 |
+
options.qs = req.queryObj
|
148 |
+
}
|
149 |
+
|
150 |
+
if (Object.keys(req.headersObj).length) {
|
151 |
+
options.headers = req.headersObj
|
152 |
+
}
|
153 |
+
|
154 |
+
function test (type) {
|
155 |
+
return req.postData.mimeType.indexOf(type) === 0
|
156 |
+
}
|
157 |
+
if (test('application/x-www-form-urlencoded')) {
|
158 |
+
options.form = req.postData.paramsObj
|
159 |
+
} else if (test('application/json')) {
|
160 |
+
if (req.postData.jsonObj) {
|
161 |
+
options.body = req.postData.jsonObj
|
162 |
+
options.json = true
|
163 |
+
}
|
164 |
+
} else if (test('multipart/form-data')) {
|
165 |
+
options.formData = {}
|
166 |
+
|
167 |
+
req.postData.params.forEach(function (param) {
|
168 |
+
var attachment = {}
|
169 |
+
|
170 |
+
if (!param.fileName && !param.contentType) {
|
171 |
+
options.formData[param.name] = param.value
|
172 |
+
return
|
173 |
+
}
|
174 |
+
|
175 |
+
// attempt to read from disk!
|
176 |
+
if (param.fileName && !param.value) {
|
177 |
+
attachment.value = fs.createReadStream(param.fileName)
|
178 |
+
} else if (param.value) {
|
179 |
+
attachment.value = param.value
|
180 |
+
}
|
181 |
+
|
182 |
+
if (param.fileName) {
|
183 |
+
attachment.options = {
|
184 |
+
filename: param.fileName,
|
185 |
+
contentType: param.contentType ? param.contentType : null
|
186 |
+
}
|
187 |
+
}
|
188 |
+
|
189 |
+
options.formData[param.name] = attachment
|
190 |
+
})
|
191 |
+
} else {
|
192 |
+
if (req.postData.text) {
|
193 |
+
options.body = req.postData.text
|
194 |
+
}
|
195 |
+
}
|
196 |
+
|
197 |
+
return options
|
198 |
+
}
|
199 |
+
|
200 |
+
exports.Har = Har
|
node_modules/@cypress/request/lib/hawk.js
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var crypto = require('crypto')
|
4 |
+
|
5 |
+
function randomString (size) {
|
6 |
+
var bits = (size + 1) * 6
|
7 |
+
var buffer = crypto.randomBytes(Math.ceil(bits / 8))
|
8 |
+
var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
|
9 |
+
return string.slice(0, size)
|
10 |
+
}
|
11 |
+
|
12 |
+
function calculatePayloadHash (payload, algorithm, contentType) {
|
13 |
+
var hash = crypto.createHash(algorithm)
|
14 |
+
hash.update('hawk.1.payload\n')
|
15 |
+
hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n')
|
16 |
+
hash.update(payload || '')
|
17 |
+
hash.update('\n')
|
18 |
+
return hash.digest('base64')
|
19 |
+
}
|
20 |
+
|
21 |
+
exports.calculateMac = function (credentials, opts) {
|
22 |
+
var normalized = 'hawk.1.header\n' +
|
23 |
+
opts.ts + '\n' +
|
24 |
+
opts.nonce + '\n' +
|
25 |
+
(opts.method || '').toUpperCase() + '\n' +
|
26 |
+
opts.resource + '\n' +
|
27 |
+
opts.host.toLowerCase() + '\n' +
|
28 |
+
opts.port + '\n' +
|
29 |
+
(opts.hash || '') + '\n'
|
30 |
+
|
31 |
+
if (opts.ext) {
|
32 |
+
normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n')
|
33 |
+
}
|
34 |
+
|
35 |
+
normalized = normalized + '\n'
|
36 |
+
|
37 |
+
if (opts.app) {
|
38 |
+
normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n'
|
39 |
+
}
|
40 |
+
|
41 |
+
var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized)
|
42 |
+
var digest = hmac.digest('base64')
|
43 |
+
return digest
|
44 |
+
}
|
45 |
+
|
46 |
+
exports.header = function (uri, method, opts) {
|
47 |
+
var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000)
|
48 |
+
var credentials = opts.credentials
|
49 |
+
if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
|
50 |
+
return ''
|
51 |
+
}
|
52 |
+
|
53 |
+
if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) {
|
54 |
+
return ''
|
55 |
+
}
|
56 |
+
|
57 |
+
var artifacts = {
|
58 |
+
ts: timestamp,
|
59 |
+
nonce: opts.nonce || randomString(6),
|
60 |
+
method: method,
|
61 |
+
resource: uri.pathname + (uri.search || ''),
|
62 |
+
host: uri.hostname,
|
63 |
+
port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
|
64 |
+
hash: opts.hash,
|
65 |
+
ext: opts.ext,
|
66 |
+
app: opts.app,
|
67 |
+
dlg: opts.dlg
|
68 |
+
}
|
69 |
+
|
70 |
+
if (!artifacts.hash && (opts.payload || opts.payload === '')) {
|
71 |
+
artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType)
|
72 |
+
}
|
73 |
+
|
74 |
+
var mac = exports.calculateMac(credentials, artifacts)
|
75 |
+
|
76 |
+
var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''
|
77 |
+
var header = 'Hawk id="' + credentials.id +
|
78 |
+
'", ts="' + artifacts.ts +
|
79 |
+
'", nonce="' + artifacts.nonce +
|
80 |
+
(artifacts.hash ? '", hash="' + artifacts.hash : '') +
|
81 |
+
(hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') +
|
82 |
+
'", mac="' + mac + '"'
|
83 |
+
|
84 |
+
if (artifacts.app) {
|
85 |
+
header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'
|
86 |
+
}
|
87 |
+
|
88 |
+
return header
|
89 |
+
}
|
node_modules/@cypress/request/lib/helpers.js
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var jsonSafeStringify = require('json-stringify-safe')
|
4 |
+
var crypto = require('crypto')
|
5 |
+
var Buffer = require('safe-buffer').Buffer
|
6 |
+
|
7 |
+
var defer = typeof setImmediate === 'undefined'
|
8 |
+
? process.nextTick
|
9 |
+
: setImmediate
|
10 |
+
|
11 |
+
function paramsHaveRequestBody (params) {
|
12 |
+
return (
|
13 |
+
params.body ||
|
14 |
+
params.requestBodyStream ||
|
15 |
+
(params.json && typeof params.json !== 'boolean') ||
|
16 |
+
params.multipart
|
17 |
+
)
|
18 |
+
}
|
19 |
+
|
20 |
+
function safeStringify (obj, replacer) {
|
21 |
+
var ret
|
22 |
+
try {
|
23 |
+
ret = JSON.stringify(obj, replacer)
|
24 |
+
} catch (e) {
|
25 |
+
ret = jsonSafeStringify(obj, replacer)
|
26 |
+
}
|
27 |
+
return ret
|
28 |
+
}
|
29 |
+
|
30 |
+
function md5 (str) {
|
31 |
+
return crypto.createHash('md5').update(str).digest('hex')
|
32 |
+
}
|
33 |
+
|
34 |
+
function isReadStream (rs) {
|
35 |
+
return rs.readable && rs.path && rs.mode
|
36 |
+
}
|
37 |
+
|
38 |
+
function toBase64 (str) {
|
39 |
+
return Buffer.from(str || '', 'utf8').toString('base64')
|
40 |
+
}
|
41 |
+
|
42 |
+
function copy (obj) {
|
43 |
+
var o = {}
|
44 |
+
Object.keys(obj).forEach(function (i) {
|
45 |
+
o[i] = obj[i]
|
46 |
+
})
|
47 |
+
return o
|
48 |
+
}
|
49 |
+
|
50 |
+
function version () {
|
51 |
+
var numbers = process.version.replace('v', '').split('.')
|
52 |
+
return {
|
53 |
+
major: parseInt(numbers[0], 10),
|
54 |
+
minor: parseInt(numbers[1], 10),
|
55 |
+
patch: parseInt(numbers[2], 10)
|
56 |
+
}
|
57 |
+
}
|
58 |
+
|
59 |
+
exports.paramsHaveRequestBody = paramsHaveRequestBody
|
60 |
+
exports.safeStringify = safeStringify
|
61 |
+
exports.md5 = md5
|
62 |
+
exports.isReadStream = isReadStream
|
63 |
+
exports.toBase64 = toBase64
|
64 |
+
exports.copy = copy
|
65 |
+
exports.version = version
|
66 |
+
exports.defer = defer
|
node_modules/@cypress/request/lib/multipart.js
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var { v4: uuid } = require('uuid')
|
4 |
+
var CombinedStream = require('combined-stream')
|
5 |
+
var isstream = require('isstream')
|
6 |
+
var Buffer = require('safe-buffer').Buffer
|
7 |
+
|
8 |
+
function Multipart (request) {
|
9 |
+
this.request = request
|
10 |
+
this.boundary = uuid()
|
11 |
+
this.chunked = false
|
12 |
+
this.body = null
|
13 |
+
}
|
14 |
+
|
15 |
+
Multipart.prototype.isChunked = function (options) {
|
16 |
+
var self = this
|
17 |
+
var chunked = false
|
18 |
+
var parts = options.data || options
|
19 |
+
|
20 |
+
if (!parts.forEach) {
|
21 |
+
self.request.emit('error', new Error('Argument error, options.multipart.'))
|
22 |
+
}
|
23 |
+
|
24 |
+
if (options.chunked !== undefined) {
|
25 |
+
chunked = options.chunked
|
26 |
+
}
|
27 |
+
|
28 |
+
if (self.request.getHeader('transfer-encoding') === 'chunked') {
|
29 |
+
chunked = true
|
30 |
+
}
|
31 |
+
|
32 |
+
if (!chunked) {
|
33 |
+
parts.forEach(function (part) {
|
34 |
+
if (typeof part.body === 'undefined') {
|
35 |
+
self.request.emit('error', new Error('Body attribute missing in multipart.'))
|
36 |
+
}
|
37 |
+
if (isstream(part.body)) {
|
38 |
+
chunked = true
|
39 |
+
}
|
40 |
+
})
|
41 |
+
}
|
42 |
+
|
43 |
+
return chunked
|
44 |
+
}
|
45 |
+
|
46 |
+
Multipart.prototype.setHeaders = function (chunked) {
|
47 |
+
var self = this
|
48 |
+
|
49 |
+
if (chunked && !self.request.hasHeader('transfer-encoding')) {
|
50 |
+
self.request.setHeader('transfer-encoding', 'chunked')
|
51 |
+
}
|
52 |
+
|
53 |
+
var header = self.request.getHeader('content-type')
|
54 |
+
|
55 |
+
if (!header || header.indexOf('multipart') === -1) {
|
56 |
+
self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
|
57 |
+
} else {
|
58 |
+
if (header.indexOf('boundary') !== -1) {
|
59 |
+
self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
|
60 |
+
} else {
|
61 |
+
self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
|
62 |
+
}
|
63 |
+
}
|
64 |
+
}
|
65 |
+
|
66 |
+
Multipart.prototype.build = function (parts, chunked) {
|
67 |
+
var self = this
|
68 |
+
var body = chunked ? new CombinedStream() : []
|
69 |
+
|
70 |
+
function add (part) {
|
71 |
+
if (typeof part === 'number') {
|
72 |
+
part = part.toString()
|
73 |
+
}
|
74 |
+
return chunked ? body.append(part) : body.push(Buffer.from(part))
|
75 |
+
}
|
76 |
+
|
77 |
+
if (self.request.preambleCRLF) {
|
78 |
+
add('\r\n')
|
79 |
+
}
|
80 |
+
|
81 |
+
parts.forEach(function (part) {
|
82 |
+
var preamble = '--' + self.boundary + '\r\n'
|
83 |
+
Object.keys(part).forEach(function (key) {
|
84 |
+
if (key === 'body') { return }
|
85 |
+
preamble += key + ': ' + part[key] + '\r\n'
|
86 |
+
})
|
87 |
+
preamble += '\r\n'
|
88 |
+
add(preamble)
|
89 |
+
add(part.body)
|
90 |
+
add('\r\n')
|
91 |
+
})
|
92 |
+
add('--' + self.boundary + '--')
|
93 |
+
|
94 |
+
if (self.request.postambleCRLF) {
|
95 |
+
add('\r\n')
|
96 |
+
}
|
97 |
+
|
98 |
+
return body
|
99 |
+
}
|
100 |
+
|
101 |
+
Multipart.prototype.onRequest = function (options) {
|
102 |
+
var self = this
|
103 |
+
|
104 |
+
var chunked = self.isChunked(options)
|
105 |
+
var parts = options.data || options
|
106 |
+
|
107 |
+
self.setHeaders(chunked)
|
108 |
+
self.chunked = chunked
|
109 |
+
self.body = self.build(parts, chunked)
|
110 |
+
}
|
111 |
+
|
112 |
+
exports.Multipart = Multipart
|
node_modules/@cypress/request/lib/querystring.js
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var qs = require('qs')
|
4 |
+
var querystring = require('querystring')
|
5 |
+
|
6 |
+
function Querystring (request) {
|
7 |
+
this.request = request
|
8 |
+
this.lib = null
|
9 |
+
this.useQuerystring = null
|
10 |
+
this.parseOptions = null
|
11 |
+
this.stringifyOptions = null
|
12 |
+
}
|
13 |
+
|
14 |
+
Querystring.prototype.init = function (options) {
|
15 |
+
if (this.lib) { return }
|
16 |
+
|
17 |
+
this.useQuerystring = options.useQuerystring
|
18 |
+
this.lib = (this.useQuerystring ? querystring : qs)
|
19 |
+
|
20 |
+
this.parseOptions = options.qsParseOptions || {}
|
21 |
+
this.stringifyOptions = options.qsStringifyOptions || {}
|
22 |
+
}
|
23 |
+
|
24 |
+
Querystring.prototype.stringify = function (obj) {
|
25 |
+
return (this.useQuerystring)
|
26 |
+
? this.rfc3986(this.lib.stringify(obj,
|
27 |
+
this.stringifyOptions.sep || null,
|
28 |
+
this.stringifyOptions.eq || null,
|
29 |
+
this.stringifyOptions))
|
30 |
+
: this.lib.stringify(obj, this.stringifyOptions)
|
31 |
+
}
|
32 |
+
|
33 |
+
Querystring.prototype.parse = function (str) {
|
34 |
+
return (this.useQuerystring)
|
35 |
+
? this.lib.parse(str,
|
36 |
+
this.parseOptions.sep || null,
|
37 |
+
this.parseOptions.eq || null,
|
38 |
+
this.parseOptions)
|
39 |
+
: this.lib.parse(str, this.parseOptions)
|
40 |
+
}
|
41 |
+
|
42 |
+
Querystring.prototype.rfc3986 = function (str) {
|
43 |
+
return str.replace(/[!'()*]/g, function (c) {
|
44 |
+
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
|
45 |
+
})
|
46 |
+
}
|
47 |
+
|
48 |
+
Querystring.prototype.unescape = querystring.unescape
|
49 |
+
|
50 |
+
exports.Querystring = Querystring
|
node_modules/@cypress/request/lib/redirect.js
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var url = require('url')
|
4 |
+
var isUrl = /^https?:/
|
5 |
+
|
6 |
+
function Redirect (request) {
|
7 |
+
this.request = request
|
8 |
+
this.followRedirect = true
|
9 |
+
this.followRedirects = true
|
10 |
+
this.followAllRedirects = false
|
11 |
+
this.followOriginalHttpMethod = false
|
12 |
+
this.allowRedirect = function () { return true }
|
13 |
+
this.maxRedirects = 10
|
14 |
+
this.redirects = []
|
15 |
+
this.redirectsFollowed = 0
|
16 |
+
this.removeRefererHeader = false
|
17 |
+
this.allowInsecureRedirect = false
|
18 |
+
}
|
19 |
+
|
20 |
+
Redirect.prototype.onRequest = function (options) {
|
21 |
+
var self = this
|
22 |
+
|
23 |
+
if (options.maxRedirects !== undefined) {
|
24 |
+
self.maxRedirects = options.maxRedirects
|
25 |
+
}
|
26 |
+
if (typeof options.followRedirect === 'function') {
|
27 |
+
self.allowRedirect = options.followRedirect
|
28 |
+
}
|
29 |
+
if (options.followRedirect !== undefined) {
|
30 |
+
self.followRedirects = !!options.followRedirect
|
31 |
+
}
|
32 |
+
if (options.followAllRedirects !== undefined) {
|
33 |
+
self.followAllRedirects = options.followAllRedirects
|
34 |
+
}
|
35 |
+
if (self.followRedirects || self.followAllRedirects) {
|
36 |
+
self.redirects = self.redirects || []
|
37 |
+
}
|
38 |
+
if (options.removeRefererHeader !== undefined) {
|
39 |
+
self.removeRefererHeader = options.removeRefererHeader
|
40 |
+
}
|
41 |
+
if (options.followOriginalHttpMethod !== undefined) {
|
42 |
+
self.followOriginalHttpMethod = options.followOriginalHttpMethod
|
43 |
+
}
|
44 |
+
if (options.allowInsecureRedirect !== undefined) {
|
45 |
+
self.allowInsecureRedirect = options.allowInsecureRedirect
|
46 |
+
}
|
47 |
+
}
|
48 |
+
|
49 |
+
Redirect.prototype.redirectTo = function (response) {
|
50 |
+
var self = this
|
51 |
+
var request = self.request
|
52 |
+
|
53 |
+
var redirectTo = null
|
54 |
+
if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
|
55 |
+
var location = response.caseless.get('location')
|
56 |
+
request.debug('redirect', location)
|
57 |
+
|
58 |
+
if (self.followAllRedirects) {
|
59 |
+
redirectTo = location
|
60 |
+
} else if (self.followRedirects) {
|
61 |
+
switch (request.method) {
|
62 |
+
case 'PATCH':
|
63 |
+
case 'PUT':
|
64 |
+
case 'POST':
|
65 |
+
case 'DELETE':
|
66 |
+
// Do not follow redirects
|
67 |
+
break
|
68 |
+
default:
|
69 |
+
redirectTo = location
|
70 |
+
break
|
71 |
+
}
|
72 |
+
}
|
73 |
+
} else if (response.statusCode === 401) {
|
74 |
+
var authHeader = request._auth.onResponse(response)
|
75 |
+
if (authHeader) {
|
76 |
+
request.setHeader('authorization', authHeader)
|
77 |
+
redirectTo = request.uri
|
78 |
+
}
|
79 |
+
}
|
80 |
+
return redirectTo
|
81 |
+
}
|
82 |
+
|
83 |
+
Redirect.prototype.onResponse = function (response, callback) {
|
84 |
+
var self = this
|
85 |
+
var request = self.request
|
86 |
+
|
87 |
+
var redirectTo = self.redirectTo(response)
|
88 |
+
if (!redirectTo) return callback(null, false)
|
89 |
+
|
90 |
+
function processRedirect (shouldRedirect) {
|
91 |
+
if (!shouldRedirect) return callback(null, false)
|
92 |
+
if (typeof shouldRedirect === 'string') {
|
93 |
+
// overridden redirect url
|
94 |
+
request.debug('redirect overridden', redirectTo)
|
95 |
+
redirectTo = shouldRedirect
|
96 |
+
}
|
97 |
+
|
98 |
+
request.debug('redirect to', redirectTo)
|
99 |
+
|
100 |
+
// ignore any potential response body. it cannot possibly be useful
|
101 |
+
// to us at this point.
|
102 |
+
// response.resume should be defined, but check anyway before calling. Workaround for browserify.
|
103 |
+
if (response.resume) {
|
104 |
+
response.resume()
|
105 |
+
}
|
106 |
+
|
107 |
+
if (self.redirectsFollowed >= self.maxRedirects) {
|
108 |
+
return callback(new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
|
109 |
+
}
|
110 |
+
self.redirectsFollowed += 1
|
111 |
+
|
112 |
+
if (!isUrl.test(redirectTo)) {
|
113 |
+
redirectTo = url.resolve(request.uri.href, redirectTo)
|
114 |
+
}
|
115 |
+
|
116 |
+
var uriPrev = request.uri
|
117 |
+
request.uri = url.parse(redirectTo)
|
118 |
+
|
119 |
+
// handle the case where we change protocol from https to http or vice versa
|
120 |
+
if (request.uri.protocol !== uriPrev.protocol && self.allowInsecureRedirect) {
|
121 |
+
delete request.agent
|
122 |
+
}
|
123 |
+
|
124 |
+
self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })
|
125 |
+
|
126 |
+
if (self.followAllRedirects && request.method !== 'HEAD' &&
|
127 |
+
response.statusCode !== 401 && response.statusCode !== 307) {
|
128 |
+
request.method = self.followOriginalHttpMethod ? request.method : 'GET'
|
129 |
+
}
|
130 |
+
// request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
|
131 |
+
delete request.src
|
132 |
+
delete request.req
|
133 |
+
delete request._started
|
134 |
+
if (response.statusCode !== 401 && response.statusCode !== 307) {
|
135 |
+
// Remove parameters from the previous response, unless this is the second request
|
136 |
+
// for a server that requires digest authentication.
|
137 |
+
delete request.body
|
138 |
+
delete request._form
|
139 |
+
if (request.headers) {
|
140 |
+
request.removeHeader('host')
|
141 |
+
request.removeHeader('content-type')
|
142 |
+
request.removeHeader('content-length')
|
143 |
+
if (request.uri.hostname !== request.originalHost.split(':')[0]) {
|
144 |
+
// Remove authorization if changing hostnames (but not if just
|
145 |
+
// changing ports or protocols). This matches the behavior of curl:
|
146 |
+
// https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
|
147 |
+
request.removeHeader('authorization')
|
148 |
+
}
|
149 |
+
}
|
150 |
+
}
|
151 |
+
|
152 |
+
if (!self.removeRefererHeader) {
|
153 |
+
request.setHeader('referer', uriPrev.href)
|
154 |
+
}
|
155 |
+
|
156 |
+
request.emit('redirect')
|
157 |
+
request.init()
|
158 |
+
callback(null, true)
|
159 |
+
}
|
160 |
+
|
161 |
+
// test allowRedirect arity; if has more than one argument,
|
162 |
+
// assume it's asynchronous via a callback
|
163 |
+
if (self.allowRedirect.length > 1) {
|
164 |
+
return self.allowRedirect.call(request, response, function (err, result) {
|
165 |
+
if (err) return callback(err)
|
166 |
+
processRedirect(result)
|
167 |
+
})
|
168 |
+
}
|
169 |
+
|
170 |
+
var allowsRedirect = self.allowRedirect.call(request, response)
|
171 |
+
if (allowsRedirect && allowsRedirect.then) {
|
172 |
+
return allowsRedirect.then(processRedirect, callback)
|
173 |
+
}
|
174 |
+
|
175 |
+
// treat as a regular boolean
|
176 |
+
processRedirect(allowsRedirect)
|
177 |
+
}
|
178 |
+
|
179 |
+
exports.Redirect = Redirect
|
node_modules/@cypress/request/lib/tunnel.js
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'use strict'
|
2 |
+
|
3 |
+
var url = require('url')
|
4 |
+
var tunnel = require('tunnel-agent')
|
5 |
+
|
6 |
+
var defaultProxyHeaderWhiteList = [
|
7 |
+
'accept',
|
8 |
+
'accept-charset',
|
9 |
+
'accept-encoding',
|
10 |
+
'accept-language',
|
11 |
+
'accept-ranges',
|
12 |
+
'cache-control',
|
13 |
+
'content-encoding',
|
14 |
+
'content-language',
|
15 |
+
'content-location',
|
16 |
+
'content-md5',
|
17 |
+
'content-range',
|
18 |
+
'content-type',
|
19 |
+
'connection',
|
20 |
+
'date',
|
21 |
+
'expect',
|
22 |
+
'max-forwards',
|
23 |
+
'pragma',
|
24 |
+
'referer',
|
25 |
+
'te',
|
26 |
+
'user-agent',
|
27 |
+
'via'
|
28 |
+
]
|
29 |
+
|
30 |
+
var defaultProxyHeaderExclusiveList = [
|
31 |
+
'proxy-authorization'
|
32 |
+
]
|
33 |
+
|
34 |
+
function constructProxyHost (uriObject) {
|
35 |
+
var port = uriObject.port
|
36 |
+
var protocol = uriObject.protocol
|
37 |
+
var proxyHost = uriObject.hostname + ':'
|
38 |
+
|
39 |
+
if (port) {
|
40 |
+
proxyHost += port
|
41 |
+
} else if (protocol === 'https:') {
|
42 |
+
proxyHost += '443'
|
43 |
+
} else {
|
44 |
+
proxyHost += '80'
|
45 |
+
}
|
46 |
+
|
47 |
+
return proxyHost
|
48 |
+
}
|
49 |
+
|
50 |
+
function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) {
|
51 |
+
var whiteList = proxyHeaderWhiteList
|
52 |
+
.reduce(function (set, header) {
|
53 |
+
set[header.toLowerCase()] = true
|
54 |
+
return set
|
55 |
+
}, {})
|
56 |
+
|
57 |
+
return Object.keys(headers)
|
58 |
+
.filter(function (header) {
|
59 |
+
return whiteList[header.toLowerCase()]
|
60 |
+
})
|
61 |
+
.reduce(function (set, header) {
|
62 |
+
set[header] = headers[header]
|
63 |
+
return set
|
64 |
+
}, {})
|
65 |
+
}
|
66 |
+
|
67 |
+
function constructTunnelOptions (request, proxyHeaders) {
|
68 |
+
var proxy = request.proxy
|
69 |
+
|
70 |
+
var tunnelOptions = {
|
71 |
+
proxy: {
|
72 |
+
host: proxy.hostname,
|
73 |
+
port: +proxy.port,
|
74 |
+
proxyAuth: proxy.auth,
|
75 |
+
headers: proxyHeaders
|
76 |
+
},
|
77 |
+
headers: request.headers,
|
78 |
+
ca: request.ca,
|
79 |
+
cert: request.cert,
|
80 |
+
key: request.key,
|
81 |
+
passphrase: request.passphrase,
|
82 |
+
pfx: request.pfx,
|
83 |
+
ciphers: request.ciphers,
|
84 |
+
rejectUnauthorized: request.rejectUnauthorized,
|
85 |
+
secureOptions: request.secureOptions,
|
86 |
+
secureProtocol: request.secureProtocol
|
87 |
+
}
|
88 |
+
|
89 |
+
return tunnelOptions
|
90 |
+
}
|
91 |
+
|
92 |
+
function constructTunnelFnName (uri, proxy) {
|
93 |
+
var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
|
94 |
+
var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
|
95 |
+
return [uriProtocol, proxyProtocol].join('Over')
|
96 |
+
}
|
97 |
+
|
98 |
+
function getTunnelFn (request) {
|
99 |
+
var uri = request.uri
|
100 |
+
var proxy = request.proxy
|
101 |
+
var tunnelFnName = constructTunnelFnName(uri, proxy)
|
102 |
+
return tunnel[tunnelFnName]
|
103 |
+
}
|
104 |
+
|
105 |
+
function Tunnel (request) {
|
106 |
+
this.request = request
|
107 |
+
this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
|
108 |
+
this.proxyHeaderExclusiveList = []
|
109 |
+
if (typeof request.tunnel !== 'undefined') {
|
110 |
+
this.tunnelOverride = request.tunnel
|
111 |
+
}
|
112 |
+
}
|
113 |
+
|
114 |
+
Tunnel.prototype.isEnabled = function () {
|
115 |
+
var self = this
|
116 |
+
var request = self.request
|
117 |
+
// Tunnel HTTPS by default. Allow the user to override this setting.
|
118 |
+
|
119 |
+
// If self.tunnelOverride is set (the user specified a value), use it.
|
120 |
+
if (typeof self.tunnelOverride !== 'undefined') {
|
121 |
+
return self.tunnelOverride
|
122 |
+
}
|
123 |
+
|
124 |
+
// If the destination is HTTPS, tunnel.
|
125 |
+
if (request.uri.protocol === 'https:') {
|
126 |
+
return true
|
127 |
+
}
|
128 |
+
|
129 |
+
// Otherwise, do not use tunnel.
|
130 |
+
return false
|
131 |
+
}
|
132 |
+
|
133 |
+
Tunnel.prototype.setup = function (options) {
|
134 |
+
var self = this
|
135 |
+
var request = self.request
|
136 |
+
|
137 |
+
options = options || {}
|
138 |
+
|
139 |
+
if (typeof request.proxy === 'string') {
|
140 |
+
request.proxy = url.parse(request.proxy)
|
141 |
+
}
|
142 |
+
|
143 |
+
if (!request.proxy || !request.tunnel) {
|
144 |
+
return false
|
145 |
+
}
|
146 |
+
|
147 |
+
// Setup Proxy Header Exclusive List and White List
|
148 |
+
if (options.proxyHeaderWhiteList) {
|
149 |
+
self.proxyHeaderWhiteList = options.proxyHeaderWhiteList
|
150 |
+
}
|
151 |
+
if (options.proxyHeaderExclusiveList) {
|
152 |
+
self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList
|
153 |
+
}
|
154 |
+
|
155 |
+
var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
|
156 |
+
var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
|
157 |
+
|
158 |
+
// Setup Proxy Headers and Proxy Headers Host
|
159 |
+
// Only send the Proxy White Listed Header names
|
160 |
+
var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList)
|
161 |
+
proxyHeaders.host = constructProxyHost(request.uri)
|
162 |
+
|
163 |
+
proxyHeaderExclusiveList.forEach(request.removeHeader, request)
|
164 |
+
|
165 |
+
// Set Agent from Tunnel Data
|
166 |
+
var tunnelFn = getTunnelFn(request)
|
167 |
+
var tunnelOptions = constructTunnelOptions(request, proxyHeaders)
|
168 |
+
request.agent = tunnelFn(tunnelOptions)
|
169 |
+
|
170 |
+
return true
|
171 |
+
}
|
172 |
+
|
173 |
+
Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList
|
174 |
+
Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList
|
175 |
+
exports.Tunnel = Tunnel
|
node_modules/@cypress/request/package.json
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name": "@cypress/request",
|
3 |
+
"description": "Cypress's fork of a simplified HTTP request client.",
|
4 |
+
"keywords": [
|
5 |
+
"http",
|
6 |
+
"simple",
|
7 |
+
"util",
|
8 |
+
"utility"
|
9 |
+
],
|
10 |
+
"version": "3.0.1",
|
11 |
+
"author": "Mikeal Rogers <[email protected]>",
|
12 |
+
"repository": {
|
13 |
+
"type": "git",
|
14 |
+
"url": "https://github.com/cypress-io/request.git"
|
15 |
+
},
|
16 |
+
"bugs": {
|
17 |
+
"url": "http://github.com/cypress-io/request/issues"
|
18 |
+
},
|
19 |
+
"license": "Apache-2.0",
|
20 |
+
"engines": {
|
21 |
+
"node": ">= 6"
|
22 |
+
},
|
23 |
+
"main": "index.js",
|
24 |
+
"files": [
|
25 |
+
"lib/",
|
26 |
+
"index.js",
|
27 |
+
"request.js"
|
28 |
+
],
|
29 |
+
"dependencies": {
|
30 |
+
"aws-sign2": "~0.7.0",
|
31 |
+
"aws4": "^1.8.0",
|
32 |
+
"caseless": "~0.12.0",
|
33 |
+
"combined-stream": "~1.0.6",
|
34 |
+
"extend": "~3.0.2",
|
35 |
+
"forever-agent": "~0.6.1",
|
36 |
+
"form-data": "~2.3.2",
|
37 |
+
"http-signature": "~1.3.6",
|
38 |
+
"is-typedarray": "~1.0.0",
|
39 |
+
"isstream": "~0.1.2",
|
40 |
+
"json-stringify-safe": "~5.0.1",
|
41 |
+
"mime-types": "~2.1.19",
|
42 |
+
"performance-now": "^2.1.0",
|
43 |
+
"qs": "6.10.4",
|
44 |
+
"safe-buffer": "^5.1.2",
|
45 |
+
"tough-cookie": "^4.1.3",
|
46 |
+
"tunnel-agent": "^0.6.0",
|
47 |
+
"uuid": "^8.3.2"
|
48 |
+
},
|
49 |
+
"scripts": {
|
50 |
+
"test": "npm run lint && npm run test-ci && npm run test-browser",
|
51 |
+
"test-ci": "tap --no-check-coverage tests/test-*.js",
|
52 |
+
"test-cov": "nyc --reporter=lcov tape tests/test-*.js",
|
53 |
+
"test-browser": "echo 'Skipping browser tests.' || node tests/browser/start.js",
|
54 |
+
"lint": "standard"
|
55 |
+
},
|
56 |
+
"devDependencies": {
|
57 |
+
"bluebird": "^3.2.1",
|
58 |
+
"browserify": "^13.0.1",
|
59 |
+
"browserify-istanbul": "^2.0.0",
|
60 |
+
"buffer-equal": "^1.0.0",
|
61 |
+
"codecov": "^3.0.4",
|
62 |
+
"coveralls": "^3.0.2",
|
63 |
+
"function-bind": "^1.0.2",
|
64 |
+
"karma": "^3.0.0",
|
65 |
+
"karma-browserify": "^5.0.1",
|
66 |
+
"karma-cli": "^2.0.0",
|
67 |
+
"karma-coverage": "^2.0.3",
|
68 |
+
"karma-phantomjs-launcher": "^1.0.0",
|
69 |
+
"karma-tap": "^4.2.0",
|
70 |
+
"nyc": "^15.1.0",
|
71 |
+
"phantomjs-prebuilt": "^2.1.3",
|
72 |
+
"rimraf": "^2.2.8",
|
73 |
+
"server-destroy": "^1.0.1",
|
74 |
+
"standard": "^9.0.0",
|
75 |
+
"tap": "^15.1.5",
|
76 |
+
"tape": "^4.6.0"
|
77 |
+
},
|
78 |
+
"greenkeeper": {
|
79 |
+
"ignore": [
|
80 |
+
"hawk",
|
81 |
+
"har-validator"
|
82 |
+
]
|
83 |
+
}
|
84 |
+
}
|