wrangler 0.0.0-e1b8ac4 → 0.0.0-e1c2f5b9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (295) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +170 -62
  3. package/miniflare-dist/index.mjs +1499 -21
  4. package/package.json +193 -156
  5. package/src/__tests__/access.test.ts +25 -0
  6. package/src/__tests__/api-dev.test.ts +238 -0
  7. package/src/__tests__/api-devregistry.test.js +64 -0
  8. package/src/__tests__/api.test.ts +80 -0
  9. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  10. package/src/__tests__/config-cache.test.ts +30 -24
  11. package/src/__tests__/configuration.test.ts +4152 -3537
  12. package/src/__tests__/d1.test.ts +123 -0
  13. package/src/__tests__/delete.test.ts +263 -0
  14. package/src/__tests__/deployments.test.ts +105 -0
  15. package/src/__tests__/dev.test.tsx +1559 -1028
  16. package/src/__tests__/dialogs.test.tsx +40 -0
  17. package/src/__tests__/generate.test.ts +235 -0
  18. package/src/__tests__/get-host-from-url.test.ts +16 -0
  19. package/src/__tests__/guess-worker-format.test.ts +68 -68
  20. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  21. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  22. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  23. package/src/__tests__/helpers/mock-bin.ts +20 -20
  24. package/src/__tests__/helpers/mock-cfetch.ts +165 -99
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +94 -94
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  28. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  29. package/src/__tests__/helpers/mock-istty.ts +65 -18
  30. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  31. package/src/__tests__/helpers/mock-kv.ts +27 -27
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +244 -228
  33. package/src/__tests__/helpers/mock-process.ts +23 -13
  34. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  35. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  36. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  37. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  38. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  39. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  40. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  41. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  42. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  43. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  44. package/src/__tests__/helpers/msw/index.ts +21 -0
  45. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  46. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  47. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  48. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  52. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  53. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  54. package/src/__tests__/https-options.test.ts +142 -109
  55. package/src/__tests__/index.test.ts +245 -234
  56. package/src/__tests__/init.test.ts +3027 -1925
  57. package/src/__tests__/jest.setup.ts +157 -61
  58. package/src/__tests__/kv.test.ts +1773 -1507
  59. package/src/__tests__/logger.test.ts +96 -96
  60. package/src/__tests__/logout.test.ts +47 -0
  61. package/src/__tests__/metrics.test.ts +495 -0
  62. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  63. package/src/__tests__/middleware.test.ts +750 -0
  64. package/src/__tests__/package-manager.test.ts +303 -303
  65. package/src/__tests__/pages-deployment-tail.test.ts +884 -0
  66. package/src/__tests__/pages.test.ts +2424 -735
  67. package/src/__tests__/parse.test.ts +252 -252
  68. package/src/__tests__/paths.test.ts +39 -0
  69. package/src/__tests__/publish.test.ts +7621 -5798
  70. package/src/__tests__/pubsub.test.ts +490 -0
  71. package/src/__tests__/queues.test.ts +522 -0
  72. package/src/__tests__/r2.test.ts +388 -228
  73. package/src/__tests__/route.test.ts +18 -18
  74. package/src/__tests__/secret.test.ts +673 -460
  75. package/src/__tests__/tail.test.ts +776 -567
  76. package/src/__tests__/test-old-node-version.js +31 -0
  77. package/src/__tests__/tsconfig-sanity.ts +12 -0
  78. package/src/__tests__/tsconfig.json +8 -0
  79. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  80. package/src/__tests__/type-generation.test.ts +233 -0
  81. package/src/__tests__/user.test.ts +117 -120
  82. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  83. package/src/__tests__/validate-dev-props.test.ts +56 -0
  84. package/src/__tests__/version.test.ts +35 -0
  85. package/src/__tests__/whoami.test.tsx +264 -125
  86. package/src/__tests__/worker-namespace.test.ts +326 -0
  87. package/src/abort.d.ts +1 -1
  88. package/src/api/dev.ts +218 -0
  89. package/src/api/index.ts +2 -0
  90. package/src/bundle-reporter.tsx +68 -0
  91. package/src/bundle.ts +785 -166
  92. package/src/cfetch/index.ts +120 -83
  93. package/src/cfetch/internal.ts +211 -92
  94. package/src/cli.ts +23 -8
  95. package/src/config/config.ts +236 -204
  96. package/src/config/diagnostics.ts +61 -61
  97. package/src/config/environment.ts +514 -357
  98. package/src/config/index.ts +326 -193
  99. package/src/config/validation-helpers.ts +379 -366
  100. package/src/config/validation.ts +1973 -1402
  101. package/src/config-cache.ts +81 -41
  102. package/src/create-worker-preview.ts +239 -142
  103. package/src/create-worker-upload-form.ts +309 -238
  104. package/src/d1/backups.tsx +223 -0
  105. package/src/d1/constants.ts +2 -0
  106. package/src/d1/create.tsx +63 -0
  107. package/src/d1/delete.tsx +56 -0
  108. package/src/d1/execute.tsx +352 -0
  109. package/src/d1/formatTimeAgo.ts +14 -0
  110. package/src/d1/index.ts +101 -0
  111. package/src/d1/list.tsx +48 -0
  112. package/src/d1/migrations/apply.tsx +196 -0
  113. package/src/d1/migrations/create.tsx +77 -0
  114. package/src/d1/migrations/helpers.ts +147 -0
  115. package/src/d1/migrations/index.tsx +3 -0
  116. package/src/d1/migrations/list.tsx +79 -0
  117. package/src/d1/migrations/options.ts +18 -0
  118. package/src/d1/options.ts +22 -0
  119. package/src/d1/types.tsx +24 -0
  120. package/src/d1/utils.ts +48 -0
  121. package/src/delete.ts +108 -0
  122. package/src/deployments.ts +83 -0
  123. package/src/deprecated/index.ts +145 -0
  124. package/src/dev/dev-vars.ts +20 -17
  125. package/src/dev/dev.tsx +544 -329
  126. package/src/dev/get-local-persistence-path.tsx +31 -0
  127. package/src/dev/local.tsx +912 -301
  128. package/src/dev/remote.tsx +591 -230
  129. package/src/dev/start-server.ts +543 -0
  130. package/src/dev/use-esbuild.ts +183 -91
  131. package/src/dev/validate-dev-props.ts +31 -0
  132. package/src/dev-registry.tsx +201 -0
  133. package/src/dev.tsx +949 -0
  134. package/src/dialogs.tsx +132 -99
  135. package/src/dispatch-namespace.ts +207 -0
  136. package/src/docs/index.ts +97 -0
  137. package/src/durable.ts +87 -87
  138. package/src/entry.ts +235 -228
  139. package/src/environment-variables/factory.ts +88 -0
  140. package/src/environment-variables/misc-variables.ts +30 -0
  141. package/src/errors.ts +6 -6
  142. package/src/generate/index.ts +300 -0
  143. package/src/git-client.ts +135 -0
  144. package/src/global-wrangler-config-path.ts +26 -0
  145. package/src/https-options.ts +84 -80
  146. package/src/index.tsx +637 -2850
  147. package/src/init.ts +1025 -0
  148. package/src/inspect.ts +698 -593
  149. package/src/intl-polyfill.d.ts +123 -123
  150. package/src/is-ci.ts +14 -0
  151. package/src/is-interactive.ts +16 -0
  152. package/src/jest.d.ts +4 -0
  153. package/src/kv/helpers.ts +430 -0
  154. package/src/kv/index.ts +596 -0
  155. package/src/logger.ts +64 -45
  156. package/src/metrics/index.ts +5 -0
  157. package/src/metrics/metrics-config.ts +239 -0
  158. package/src/metrics/metrics-dispatcher.ts +96 -0
  159. package/src/metrics/metrics-usage-headers.ts +24 -0
  160. package/src/metrics/send-event.ts +97 -0
  161. package/src/miniflare-cli/assets.ts +250 -0
  162. package/src/miniflare-cli/index.ts +202 -33
  163. package/src/miniflare-cli/request-context.ts +18 -18
  164. package/src/miniflare-cli/tsconfig.json +9 -0
  165. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  166. package/src/miniflare-cli/types.ts +11 -0
  167. package/src/module-collection.ts +221 -212
  168. package/src/open-in-browser.ts +4 -4
  169. package/src/package-manager.ts +173 -128
  170. package/src/pages/build.tsx +270 -0
  171. package/src/pages/constants.ts +18 -0
  172. package/src/pages/deployment-tails.tsx +284 -0
  173. package/src/pages/deployments.tsx +84 -0
  174. package/src/pages/dev.tsx +710 -0
  175. package/src/pages/errors.ts +66 -0
  176. package/src/pages/functions/buildPlugin.ts +107 -0
  177. package/src/pages/functions/buildWorker.ts +166 -0
  178. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  179. package/src/pages/functions/filepath-routing.ts +189 -0
  180. package/src/pages/functions/identifiers.ts +78 -0
  181. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  182. package/src/pages/functions/routes-consolidation.ts +73 -0
  183. package/src/pages/functions/routes-transformation.test.ts +282 -0
  184. package/src/pages/functions/routes-transformation.ts +115 -0
  185. package/src/pages/functions/routes-validation.test.ts +403 -0
  186. package/src/pages/functions/routes-validation.ts +202 -0
  187. package/src/pages/functions/routes.ts +151 -0
  188. package/src/pages/functions/tsconfig.json +8 -0
  189. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  190. package/src/pages/functions.tsx +82 -0
  191. package/src/pages/hash.tsx +13 -0
  192. package/src/pages/index.tsx +102 -0
  193. package/src/pages/projects.tsx +169 -0
  194. package/src/pages/prompt-select-project.tsx +31 -0
  195. package/src/pages/publish.tsx +461 -0
  196. package/src/pages/types.ts +41 -0
  197. package/src/pages/upload.tsx +447 -0
  198. package/src/pages/utils.ts +23 -0
  199. package/src/parse.ts +202 -138
  200. package/src/paths.ts +53 -8
  201. package/src/proxy.ts +623 -405
  202. package/src/publish/index.ts +270 -0
  203. package/src/publish/publish.ts +1036 -0
  204. package/src/pubsub/index.ts +286 -0
  205. package/src/pubsub/pubsub-commands.tsx +624 -0
  206. package/src/queues/cli/commands/consumer/add.ts +71 -0
  207. package/src/queues/cli/commands/consumer/index.ts +22 -0
  208. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  209. package/src/queues/cli/commands/create.ts +25 -0
  210. package/src/queues/cli/commands/delete.ts +26 -0
  211. package/src/queues/cli/commands/index.ts +36 -0
  212. package/src/queues/cli/commands/list.ts +25 -0
  213. package/src/queues/client.ts +135 -0
  214. package/src/queues/utils.ts +18 -0
  215. package/src/r2/constants.ts +4 -0
  216. package/src/r2/helpers.ts +131 -0
  217. package/src/r2/index.ts +289 -0
  218. package/src/routes.ts +140 -0
  219. package/src/secret/index.ts +379 -0
  220. package/src/selfsigned.d.ts +23 -23
  221. package/src/sites.tsx +258 -254
  222. package/src/tail/createTail.ts +379 -0
  223. package/src/tail/filters.ts +108 -110
  224. package/src/tail/index.ts +211 -296
  225. package/src/tail/printing.ts +86 -46
  226. package/src/tsconfig-sanity.ts +16 -0
  227. package/src/type-generation.ts +181 -0
  228. package/src/update-check.ts +11 -11
  229. package/src/user/access.ts +68 -0
  230. package/src/user/auth-variables.ts +113 -0
  231. package/src/user/choose-account.tsx +69 -0
  232. package/src/user/generate-auth-url.ts +33 -0
  233. package/src/user/generate-random-state.ts +16 -0
  234. package/src/user/index.ts +2 -0
  235. package/src/user/user.tsx +1238 -0
  236. package/src/utils/collectKeyValues.ts +14 -0
  237. package/src/whoami.tsx +141 -43
  238. package/src/worker.ts +177 -107
  239. package/src/yargs-types.ts +24 -0
  240. package/src/zones.ts +158 -40
  241. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  242. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  243. package/templates/__tests__/tsconfig.json +8 -0
  244. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  245. package/templates/checked-fetch.js +17 -0
  246. package/templates/d1-beta-facade.js +205 -0
  247. package/templates/facade.d.ts +14 -0
  248. package/templates/first-party-worker-module-facade.ts +19 -0
  249. package/templates/format-dev-errors.ts +33 -0
  250. package/templates/init-tests/test-jest-new-worker.js +23 -0
  251. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  252. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  253. package/templates/middleware/common.ts +62 -0
  254. package/templates/middleware/loader-modules.ts +82 -0
  255. package/templates/middleware/loader-sw.ts +233 -0
  256. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  257. package/templates/middleware/middleware-pretty-error.ts +40 -0
  258. package/templates/middleware/middleware-scheduled.ts +15 -0
  259. package/templates/new-worker-scheduled.js +3 -3
  260. package/templates/new-worker-scheduled.ts +15 -15
  261. package/templates/new-worker.js +3 -3
  262. package/templates/new-worker.ts +15 -15
  263. package/templates/no-op-worker.js +10 -0
  264. package/templates/pages-dev-pipeline.ts +31 -0
  265. package/templates/pages-dev-util.ts +52 -0
  266. package/templates/pages-shim.ts +12 -0
  267. package/templates/pages-template-plugin.ts +171 -0
  268. package/templates/pages-template-worker.ts +189 -0
  269. package/templates/serve-static-assets.ts +65 -0
  270. package/templates/service-bindings-module-facade.js +54 -0
  271. package/templates/service-bindings-sw-facade.js +42 -0
  272. package/templates/tsconfig-sanity.ts +11 -0
  273. package/templates/tsconfig.init.json +106 -0
  274. package/templates/tsconfig.json +6 -103
  275. package/templates/tsconfig.tsbuildinfo +1 -0
  276. package/wrangler-dist/cli.d.ts +906 -0
  277. package/wrangler-dist/cli.js +147920 -108883
  278. package/pages/functions/buildPlugin.ts +0 -105
  279. package/pages/functions/buildWorker.ts +0 -151
  280. package/pages/functions/filepath-routing.ts +0 -189
  281. package/pages/functions/identifiers.ts +0 -78
  282. package/pages/functions/routes.ts +0 -156
  283. package/pages/functions/template-plugin.ts +0 -147
  284. package/pages/functions/template-worker.ts +0 -143
  285. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  286. package/src/environment-variables.ts +0 -35
  287. package/src/generate-auth-url.ts +0 -33
  288. package/src/generate-random-state.ts +0 -16
  289. package/src/kv.ts +0 -408
  290. package/src/miniflare-cli/enum-keys.ts +0 -17
  291. package/src/pages.tsx +0 -2093
  292. package/src/publish.ts +0 -726
  293. package/src/r2.ts +0 -50
  294. package/src/user.tsx +0 -1202
  295. package/templates/static-asset-facade.js +0 -43
@@ -1,1520 +1,1786 @@
1
1
  import { writeFileSync } from "node:fs";
2
- import { Headers } from "undici";
2
+ import { rest } from "msw";
3
3
  import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
4
- import {
5
- setMockResponse,
6
- unsetAllMocks,
7
- unsetMockFetchKVGetValues,
8
- setMockFetchKVGetValue,
9
- } from "./helpers/mock-cfetch";
10
4
  import { mockConsoleMethods } from "./helpers/mock-console";
11
5
  import { clearConfirmMocks, mockConfirm } from "./helpers/mock-dialogs";
12
- import { mockKeyListRequest } from "./helpers/mock-kv";
6
+ import { useMockIsTTY } from "./helpers/mock-istty";
13
7
  import { mockProcess } from "./helpers/mock-process";
8
+ import { msw } from "./helpers/msw";
14
9
  import { runInTempDir } from "./helpers/run-in-tmp";
15
10
  import { runWrangler } from "./helpers/run-wrangler";
16
- import type { KeyValue, KVNamespaceInfo, NamespaceKeyInfo } from "../kv";
11
+ import type {
12
+ KeyValue,
13
+ KVNamespaceInfo,
14
+ NamespaceKeyInfo,
15
+ } from "../kv/helpers";
17
16
 
18
17
  describe("wrangler", () => {
19
- mockAccountId();
20
- mockApiToken();
21
- runInTempDir();
22
- const std = mockConsoleMethods();
23
- const proc = mockProcess();
24
-
25
- afterEach(() => {
26
- unsetAllMocks();
27
- clearConfirmMocks();
28
- });
29
-
30
- describe("kv:namespace", () => {
31
- describe("create", () => {
32
- function mockCreateRequest(expectedTitle: string) {
33
- setMockResponse(
34
- "/accounts/:accountId/storage/kv/namespaces",
35
- "POST",
36
- ([_url, accountId], { body }) => {
37
- expect(accountId).toEqual("some-account-id");
38
- const title = JSON.parse(body as string).title;
39
- expect(title).toEqual(expectedTitle);
40
- return { id: "some-namespace-id" };
41
- }
42
- );
43
- }
44
-
45
- it("should error if no namespace is given", async () => {
46
- await expect(
47
- runWrangler("kv:namespace create")
48
- ).rejects.toThrowErrorMatchingInlineSnapshot(
49
- `"Not enough non-option arguments: got 0, need at least 1"`
50
- );
51
- expect(std.out).toMatchInlineSnapshot(`
52
- "
53
- wrangler kv:namespace create <namespace>
54
-
55
- Create a new namespace
56
-
57
- Positionals:
58
- namespace The name of the new namespace [string] [required]
59
-
60
- Flags:
61
- -c, --config Path to .toml configuration file [string]
62
- -h, --help Show help [boolean]
63
- -v, --version Show version number [boolean]
64
-
65
- Options:
66
- -e, --env Perform on a specific environment [string]
67
- --preview Interact with a preview namespace [boolean]"
68
- `);
69
- expect(std.err).toMatchInlineSnapshot(`
70
- "X [ERROR] Not enough non-option arguments: got 0, need at least 1
71
-
72
- "
73
- `);
74
- });
75
-
76
- it("should error if the namespace to create contains spaces", async () => {
77
- await expect(
78
- runWrangler("kv:namespace create abc def ghi")
79
- ).rejects.toThrowErrorMatchingInlineSnapshot(
80
- `"Unknown arguments: def, ghi"`
81
- );
82
- expect(std.out).toMatchInlineSnapshot(`
83
- "
84
- wrangler kv:namespace create <namespace>
85
-
86
- Create a new namespace
87
-
88
- Positionals:
89
- namespace The name of the new namespace [string] [required]
90
-
91
- Flags:
92
- -c, --config Path to .toml configuration file [string]
93
- -h, --help Show help [boolean]
94
- -v, --version Show version number [boolean]
95
-
96
- Options:
97
- -e, --env Perform on a specific environment [string]
98
- --preview Interact with a preview namespace [boolean]"
99
- `);
100
- expect(std.err).toMatchInlineSnapshot(`
101
- "X [ERROR] Unknown arguments: def, ghi
102
-
103
- "
104
- `);
105
- });
106
-
107
- it("should error if the namespace to create is not valid", async () => {
108
- await expect(
109
- runWrangler("kv:namespace create abc-def")
110
- ).rejects.toThrowErrorMatchingInlineSnapshot(
111
- `"The namespace binding name \\"abc-def\\" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number."`
112
- );
113
-
114
- expect(std.out).toMatchInlineSnapshot(`
115
- "
116
- wrangler kv:namespace create <namespace>
117
-
118
- Create a new namespace
119
-
120
- Positionals:
121
- namespace The name of the new namespace [string] [required]
122
-
123
- Flags:
124
- -c, --config Path to .toml configuration file [string]
125
- -h, --help Show help [boolean]
126
- -v, --version Show version number [boolean]
127
-
128
- Options:
129
- -e, --env Perform on a specific environment [string]
130
- --preview Interact with a preview namespace [boolean]"
131
- `);
132
- expect(std.err).toMatchInlineSnapshot(`
133
- "X [ERROR] The namespace binding name \\"abc-def\\" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.
134
-
135
- "
136
- `);
137
- });
138
-
139
- it("should create a namespace", async () => {
140
- mockCreateRequest("worker-UnitTestNamespace");
141
- await runWrangler("kv:namespace create UnitTestNamespace");
142
- expect(std.out).toMatchInlineSnapshot(`
143
- "🌀 Creating namespace with title \\"worker-UnitTestNamespace\\"
144
- ✨ Success!
145
- Add the following to your configuration file in your kv_namespaces array:
146
- { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
147
- `);
148
- });
149
-
150
- it("should create a preview namespace if configured to do so", async () => {
151
- mockCreateRequest("worker-UnitTestNamespace_preview");
152
- await runWrangler("kv:namespace create UnitTestNamespace --preview");
153
- expect(std.out).toMatchInlineSnapshot(`
154
- "🌀 Creating namespace with title \\"worker-UnitTestNamespace_preview\\"
155
- ✨ Success!
156
- Add the following to your configuration file in your kv_namespaces array:
157
- { binding = \\"UnitTestNamespace\\", preview_id = \\"some-namespace-id\\" }"
158
- `);
159
- });
160
-
161
- it("should create a namespace using configured worker name", async () => {
162
- writeFileSync("./wrangler.toml", 'name = "other-worker"', "utf-8");
163
- mockCreateRequest("other-worker-UnitTestNamespace");
164
- await runWrangler("kv:namespace create UnitTestNamespace");
165
- expect(std.out).toMatchInlineSnapshot(`
166
- "🌀 Creating namespace with title \\"other-worker-UnitTestNamespace\\"
167
- ✨ Success!
168
- Add the following to your configuration file in your kv_namespaces array:
169
- { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
170
- `);
171
- });
172
-
173
- it("should create a namespace in an environment if configured to do so", async () => {
174
- mockCreateRequest("worker-customEnv-UnitTestNamespace");
175
- await runWrangler(
176
- "kv:namespace create UnitTestNamespace --env customEnv"
177
- );
178
- expect(std.out).toMatchInlineSnapshot(`
179
- "🌀 Creating namespace with title \\"worker-customEnv-UnitTestNamespace\\"
180
- ✨ Success!
181
- Add the following to your configuration file in your kv_namespaces array under [env.customEnv]:
182
- { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
183
- `);
184
- });
185
- });
186
-
187
- describe("list", () => {
188
- function mockListRequest(namespaces: unknown[]) {
189
- const requests = { count: 0 };
190
- setMockResponse(
191
- "/accounts/:accountId/storage/kv/namespaces",
192
- ([_url, accountId], init, query) => {
193
- requests.count++;
194
- expect(accountId).toEqual("some-account-id");
195
- expect(query.get("per_page")).toEqual("100");
196
- expect(query.get("order")).toEqual("title");
197
- expect(query.get("direction")).toEqual("asc");
198
- expect(query.get("page")).toEqual(`${requests.count}`);
199
- expect(init).toEqual({});
200
- const pageSize = Number(query.get("per_page"));
201
- const page = Number(query.get("page"));
202
- return namespaces.slice((page - 1) * pageSize, page * pageSize);
203
- }
204
- );
205
- return requests;
206
- }
207
-
208
- it("should list namespaces", async () => {
209
- const kvNamespaces: KVNamespaceInfo[] = [
210
- { title: "title-1", id: "id-1" },
211
- { title: "title-2", id: "id-2" },
212
- ];
213
- mockListRequest(kvNamespaces);
214
- await runWrangler("kv:namespace list");
215
-
216
- expect(std.err).toMatchInlineSnapshot(`""`);
217
- const namespaces = JSON.parse(std.out);
218
- expect(namespaces).toEqual(kvNamespaces);
219
- });
220
-
221
- it("should make multiple requests for paginated results", async () => {
222
- // Create a lot of mock namespaces, so that the fetch requests will be paginated
223
- const kvNamespaces: KVNamespaceInfo[] = [];
224
- for (let i = 0; i < 550; i++) {
225
- kvNamespaces.push({ title: "title-" + i, id: "id-" + i });
226
- }
227
- const requests = mockListRequest(kvNamespaces);
228
- await runWrangler("kv:namespace list");
229
- const namespaces = JSON.parse(std.out);
230
- expect(namespaces).toEqual(kvNamespaces);
231
- expect(requests.count).toEqual(6);
232
- });
233
- });
234
-
235
- describe("delete", () => {
236
- function mockDeleteRequest(expectedNamespaceId: string) {
237
- const requests = { count: 0 };
238
- setMockResponse(
239
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId",
240
- "DELETE",
241
- ([_url, accountId, namespaceId]) => {
242
- requests.count++;
243
- expect(accountId).toEqual("some-account-id");
244
- expect(namespaceId).toEqual(expectedNamespaceId);
245
- return null;
246
- }
247
- );
248
- return requests;
249
- }
250
-
251
- it("should delete a namespace specified by id", async () => {
252
- const requests = mockDeleteRequest("some-namespace-id");
253
- await runWrangler(
254
- `kv:namespace delete --namespace-id some-namespace-id`
255
- );
256
- expect(requests.count).toEqual(1);
257
- });
258
-
259
- it("should delete a namespace specified by binding name", async () => {
260
- writeWranglerConfig();
261
- const requests = mockDeleteRequest("bound-id");
262
- await runWrangler(
263
- `kv:namespace delete --binding someBinding --preview false`
264
- );
265
- expect(requests.count).toEqual(1);
266
- });
267
-
268
- it("should delete a preview namespace specified by binding name", async () => {
269
- writeWranglerConfig();
270
- const requests = mockDeleteRequest("preview-bound-id");
271
- await runWrangler(
272
- `kv:namespace delete --binding someBinding --preview`
273
- );
274
- expect(requests.count).toEqual(1);
275
- });
276
-
277
- it("should error if a given binding name is not in the configured kv namespaces", async () => {
278
- writeWranglerConfig();
279
- await expect(runWrangler("kv:namespace delete --binding otherBinding"))
280
- .rejects.toThrowErrorMatchingInlineSnapshot(`
281
- "Not able to delete namespace.
282
- A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."
283
- `);
284
- expect(std.err).toMatchInlineSnapshot(`
285
- "X [ERROR] Not able to delete namespace.
286
-
287
- A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
288
-
289
- "
290
- `);
291
- });
292
-
293
- it("should delete a namespace specified by binding name in a given environment", async () => {
294
- writeWranglerConfig();
295
- const requests = mockDeleteRequest("env-bound-id");
296
- await runWrangler(
297
- "kv:namespace delete --binding someBinding --env some-environment --preview false"
298
- );
299
-
300
- expect(std.out).toMatchInlineSnapshot(`""`);
301
- expect(std.err).toMatchInlineSnapshot(`""`);
302
- expect(requests.count).toEqual(1);
303
- });
304
-
305
- it("should delete a preview namespace specified by binding name in a given environment", async () => {
306
- writeWranglerConfig();
307
- const requests = mockDeleteRequest("preview-env-bound-id");
308
- await runWrangler(
309
- `kv:namespace delete --binding someBinding --env some-environment --preview`
310
- );
311
- expect(requests.count).toEqual(1);
312
- });
313
- });
314
- });
315
-
316
- describe("kv:key", () => {
317
- describe("put", () => {
318
- function mockKeyPutRequest(
319
- expectedNamespaceId: string,
320
- expectedKV: KeyValue
321
- ) {
322
- const requests = { count: 0 };
323
- setMockResponse(
324
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key",
325
- "PUT",
326
- ([_url, accountId, namespaceId, key], { body }, query) => {
327
- requests.count++;
328
- expect(accountId).toEqual("some-account-id");
329
- expect(namespaceId).toEqual(expectedNamespaceId);
330
- expect(key).toEqual(expectedKV.key);
331
- expect(body).toEqual(expectedKV.value);
332
- if (expectedKV.expiration !== undefined) {
333
- expect(query.get("expiration")).toEqual(
334
- `${expectedKV.expiration}`
335
- );
336
- } else {
337
- expect(query.has("expiration")).toBe(false);
338
- }
339
- if (expectedKV.expiration_ttl) {
340
- expect(query.get("expiration_ttl")).toEqual(
341
- `${expectedKV.expiration_ttl}`
342
- );
343
- } else {
344
- expect(query.has("expiration_ttl")).toBe(false);
345
- }
346
- return null;
347
- }
348
- );
349
- return requests;
350
- }
351
-
352
- it("should put a key in a given namespace specified by namespace-id", async () => {
353
- const requests = mockKeyPutRequest("some-namespace-id", {
354
- key: "my-key",
355
- value: "my-value",
356
- });
357
-
358
- await runWrangler(
359
- "kv:key put my-key my-value --namespace-id some-namespace-id"
360
- );
361
-
362
- expect(requests.count).toEqual(1);
363
- expect(std.out).toMatchInlineSnapshot(
364
- `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace some-namespace-id."`
365
- );
366
- expect(std.err).toMatchInlineSnapshot(`""`);
367
- });
368
-
369
- it("should encode the key in the api request to put a value", async () => {
370
- const requests = mockKeyPutRequest("DS9", {
371
- key: "%2Fmy-key",
372
- value: "my-value",
373
- });
374
-
375
- await runWrangler("kv:key put /my-key my-value --namespace-id DS9");
376
-
377
- expect(requests.count).toEqual(1);
378
- expect(std.out).toMatchInlineSnapshot(
379
- `"Writing the value \\"my-value\\" to key \\"/my-key\\" on namespace DS9."`
380
- );
381
- expect(std.err).toMatchInlineSnapshot(`""`);
382
- });
383
-
384
- it("should put a key in a given namespace specified by binding", async () => {
385
- writeWranglerConfig();
386
- const requests = mockKeyPutRequest("bound-id", {
387
- key: "my-key",
388
- value: "my-value",
389
- });
390
- await runWrangler(
391
- "kv:key put my-key my-value --binding someBinding --preview false"
392
- );
393
-
394
- expect(std.out).toMatchInlineSnapshot(
395
- `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace bound-id."`
396
- );
397
- expect(std.err).toMatchInlineSnapshot(`""`);
398
- expect(requests.count).toEqual(1);
399
- });
400
-
401
- it("should put a key in a given preview namespace specified by binding", async () => {
402
- writeWranglerConfig();
403
- const requests = mockKeyPutRequest("preview-bound-id", {
404
- key: "my-key",
405
- value: "my-value",
406
- });
407
-
408
- await runWrangler(
409
- "kv:key put my-key my-value --binding someBinding --preview"
410
- );
411
-
412
- expect(std.out).toMatchInlineSnapshot(
413
- `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace preview-bound-id."`
414
- );
415
- expect(std.err).toMatchInlineSnapshot(`""`);
416
- expect(requests.count).toEqual(1);
417
- });
418
-
419
- it("should add expiration and ttl properties when putting a key", async () => {
420
- const requests = mockKeyPutRequest("some-namespace-id", {
421
- key: "my-key",
422
- value: "my-value",
423
- expiration: 10,
424
- expiration_ttl: 20,
425
- });
426
- await runWrangler(
427
- "kv:key put my-key my-value --namespace-id some-namespace-id --expiration 10 --ttl 20"
428
- );
429
- expect(requests.count).toEqual(1);
430
- expect(std.out).toMatchInlineSnapshot(
431
- `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace some-namespace-id."`
432
- );
433
- expect(std.err).toMatchInlineSnapshot(`""`);
434
- });
435
-
436
- it("should put a key to the specified environment in a given namespace", async () => {
437
- writeWranglerConfig();
438
- const requests = mockKeyPutRequest("env-bound-id", {
439
- key: "my-key",
440
- value: "my-value",
441
- });
442
- await runWrangler(
443
- "kv:key put my-key my-value --binding someBinding --env some-environment --preview false"
444
- );
445
- expect(std.out).toMatchInlineSnapshot(
446
- `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace env-bound-id."`
447
- );
448
- expect(std.err).toMatchInlineSnapshot(`""`);
449
- expect(requests.count).toEqual(1);
450
- });
451
-
452
- it("should put a key with a value loaded from a given path", async () => {
453
- const buf = Buffer.from("file-contents", "utf-8");
454
- writeFileSync("foo.txt", buf);
455
- const requests = mockKeyPutRequest("some-namespace-id", {
456
- key: "my-key",
457
- value: buf,
458
- });
459
- await runWrangler(
460
- "kv:key put my-key --namespace-id some-namespace-id --path foo.txt"
461
- );
462
- expect(std.out).toMatchInlineSnapshot(
463
- `"Writing the contents of foo.txt to the key \\"my-key\\" on namespace some-namespace-id."`
464
- );
465
- expect(std.err).toMatchInlineSnapshot(`""`);
466
- expect(requests.count).toEqual(1);
467
- });
468
-
469
- it("should put a key with a binary value loaded from a given path", async () => {
470
- const buf = Buffer.from(
471
- "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAiSURBVHgB7coxEQAACMPAgH/PgAM6dGwu49fA/deIBXrgAj2cAhIFT4QxAAAAAElFTkSuQmCC",
472
- "base64"
473
- );
474
- writeFileSync("test.png", buf);
475
- const requests = mockKeyPutRequest("another-namespace-id", {
476
- key: "my-key",
477
- value: buf,
478
- });
479
- await runWrangler(
480
- "kv:key put my-key --namespace-id another-namespace-id --path test.png"
481
- );
482
- expect(std.out).toMatchInlineSnapshot(
483
- `"Writing the contents of test.png to the key \\"my-key\\" on namespace another-namespace-id."`
484
- );
485
- expect(std.err).toMatchInlineSnapshot(`""`);
486
- expect(requests.count).toEqual(1);
487
- });
488
-
489
- it("should error if no key is provided", async () => {
490
- await expect(
491
- runWrangler("kv:key put")
492
- ).rejects.toThrowErrorMatchingInlineSnapshot(
493
- `"Not enough non-option arguments: got 0, need at least 1"`
494
- );
495
-
496
- expect(std.out).toMatchInlineSnapshot(`
497
- "
498
- wrangler kv:key put <key> [value]
499
-
500
- Writes a single key/value pair to the given namespace.
501
-
502
- Positionals:
503
- key The key to write to [string] [required]
504
- value The value to write [string]
505
-
506
- Flags:
507
- -c, --config Path to .toml configuration file [string]
508
- -h, --help Show help [boolean]
509
- -v, --version Show version number [boolean]
510
-
511
- Options:
512
- --binding The binding of the namespace to write to [string]
513
- --namespace-id The id of the namespace to write to [string]
514
- -e, --env Perform on a specific environment [string]
515
- --preview Interact with a preview namespace [boolean]
516
- --ttl Time for which the entries should be visible [number]
517
- --expiration Time since the UNIX epoch after which the entry expires [number]
518
- --path Read value from the file at a given path [string]"
519
- `);
520
- expect(std.err).toMatchInlineSnapshot(`
521
- "X [ERROR] Not enough non-option arguments: got 0, need at least 1
522
-
523
- "
524
- `);
525
- });
526
-
527
- it("should error if no binding nor namespace is provided", async () => {
528
- await expect(
529
- runWrangler("kv:key put foo bar")
530
- ).rejects.toThrowErrorMatchingInlineSnapshot(
531
- `"Exactly one of the arguments binding and namespace-id is required"`
532
- );
533
-
534
- expect(std.out).toMatchInlineSnapshot(`
535
- "
536
- wrangler kv:key put <key> [value]
537
-
538
- Writes a single key/value pair to the given namespace.
539
-
540
- Positionals:
541
- key The key to write to [string] [required]
542
- value The value to write [string]
543
-
544
- Flags:
545
- -c, --config Path to .toml configuration file [string]
546
- -h, --help Show help [boolean]
547
- -v, --version Show version number [boolean]
548
-
549
- Options:
550
- --binding The binding of the namespace to write to [string]
551
- --namespace-id The id of the namespace to write to [string]
552
- -e, --env Perform on a specific environment [string]
553
- --preview Interact with a preview namespace [boolean]
554
- --ttl Time for which the entries should be visible [number]
555
- --expiration Time since the UNIX epoch after which the entry expires [number]
556
- --path Read value from the file at a given path [string]"
557
- `);
558
- expect(std.err).toMatchInlineSnapshot(`
559
- "X [ERROR] Exactly one of the arguments binding and namespace-id is required
560
-
561
- "
562
- `);
563
- });
564
-
565
- it("should error if both binding and namespace is provided", async () => {
566
- await expect(
567
- runWrangler("kv:key put foo bar --binding x --namespace-id y")
568
- ).rejects.toThrowErrorMatchingInlineSnapshot(
569
- `"Arguments binding and namespace-id are mutually exclusive"`
570
- );
571
-
572
- expect(std.out).toMatchInlineSnapshot(`
573
- "
574
- wrangler kv:key put <key> [value]
575
-
576
- Writes a single key/value pair to the given namespace.
577
-
578
- Positionals:
579
- key The key to write to [string] [required]
580
- value The value to write [string]
581
-
582
- Flags:
583
- -c, --config Path to .toml configuration file [string]
584
- -h, --help Show help [boolean]
585
- -v, --version Show version number [boolean]
586
-
587
- Options:
588
- --binding The binding of the namespace to write to [string]
589
- --namespace-id The id of the namespace to write to [string]
590
- -e, --env Perform on a specific environment [string]
591
- --preview Interact with a preview namespace [boolean]
592
- --ttl Time for which the entries should be visible [number]
593
- --expiration Time since the UNIX epoch after which the entry expires [number]
594
- --path Read value from the file at a given path [string]"
595
- `);
596
- expect(std.err).toMatchInlineSnapshot(`
597
- "X [ERROR] Arguments binding and namespace-id are mutually exclusive
598
-
599
- "
600
- `);
601
- });
602
-
603
- it("should error if no value nor path is provided", async () => {
604
- await expect(
605
- runWrangler("kv:key put key --namespace-id 12345")
606
- ).rejects.toThrowErrorMatchingInlineSnapshot(
607
- `"Exactly one of the arguments value and path is required"`
608
- );
609
-
610
- expect(std.out).toMatchInlineSnapshot(`
611
- "
612
- wrangler kv:key put <key> [value]
613
-
614
- Writes a single key/value pair to the given namespace.
615
-
616
- Positionals:
617
- key The key to write to [string] [required]
618
- value The value to write [string]
619
-
620
- Flags:
621
- -c, --config Path to .toml configuration file [string]
622
- -h, --help Show help [boolean]
623
- -v, --version Show version number [boolean]
624
-
625
- Options:
626
- --binding The binding of the namespace to write to [string]
627
- --namespace-id The id of the namespace to write to [string]
628
- -e, --env Perform on a specific environment [string]
629
- --preview Interact with a preview namespace [boolean]
630
- --ttl Time for which the entries should be visible [number]
631
- --expiration Time since the UNIX epoch after which the entry expires [number]
632
- --path Read value from the file at a given path [string]"
633
- `);
634
- expect(std.err).toMatchInlineSnapshot(`
635
- "X [ERROR] Exactly one of the arguments value and path is required
636
-
637
- "
638
- `);
639
- });
640
-
641
- it("should error if both value and path is provided", async () => {
642
- await expect(
643
- runWrangler("kv:key put key value --path xyz --namespace-id 12345")
644
- ).rejects.toThrowErrorMatchingInlineSnapshot(
645
- `"Arguments value and path are mutually exclusive"`
646
- );
647
-
648
- expect(std.out).toMatchInlineSnapshot(`
649
- "
650
- wrangler kv:key put <key> [value]
651
-
652
- Writes a single key/value pair to the given namespace.
653
-
654
- Positionals:
655
- key The key to write to [string] [required]
656
- value The value to write [string]
657
-
658
- Flags:
659
- -c, --config Path to .toml configuration file [string]
660
- -h, --help Show help [boolean]
661
- -v, --version Show version number [boolean]
662
-
663
- Options:
664
- --binding The binding of the namespace to write to [string]
665
- --namespace-id The id of the namespace to write to [string]
666
- -e, --env Perform on a specific environment [string]
667
- --preview Interact with a preview namespace [boolean]
668
- --ttl Time for which the entries should be visible [number]
669
- --expiration Time since the UNIX epoch after which the entry expires [number]
670
- --path Read value from the file at a given path [string]"
671
- `);
672
- expect(std.err).toMatchInlineSnapshot(`
673
- "X [ERROR] Arguments value and path are mutually exclusive
674
-
675
- "
676
- `);
677
- });
678
-
679
- it("should error if a given binding name is not in the configured kv namespaces", async () => {
680
- writeWranglerConfig();
681
- await expect(
682
- runWrangler("kv:key put key value --binding otherBinding")
683
- ).rejects.toThrowErrorMatchingInlineSnapshot(
684
- `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
685
- );
686
-
687
- expect(std.out).toMatchInlineSnapshot(`
688
- "
689
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
690
- `);
691
- expect(std.err).toMatchInlineSnapshot(`
692
- "X [ERROR] A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
693
-
694
- "
695
- `);
696
- });
697
-
698
- it("should error if a given binding has both preview and non-preview and --preview is not specified", async () => {
699
- writeWranglerConfig();
700
- const requests = mockKeyPutRequest("preview-bound-id", {
701
- key: "my-key",
702
- value: "my-value",
703
- });
704
- await expect(
705
- runWrangler("kv:key put my-key my-value --binding someBinding")
706
- ).rejects.toThrowErrorMatchingInlineSnapshot(
707
- `"someBinding has both a namespace ID and a preview ID. Specify \\"--preview\\" or \\"--preview false\\" to avoid writing data to the wrong namespace."`
708
- );
709
- expect(std.out).toMatchInlineSnapshot(`
710
- "
711
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
712
- `);
713
- expect(std.err).toMatchInlineSnapshot(`
714
- "X [ERROR] someBinding has both a namespace ID and a preview ID. Specify \\"--preview\\" or \\"--preview false\\" to avoid writing data to the wrong namespace.
715
-
716
- "
717
- `);
718
- expect(requests.count).toEqual(0);
719
- });
720
- });
721
-
722
- describe("list", () => {
723
- it("should list the keys of a namespace specified by namespace-id", async () => {
724
- const keys = [
725
- { name: "key-1" },
726
- { name: "key-2", expiration: 123456789 },
727
- { name: "key-3", expiration_ttl: 666 },
728
- ];
729
- mockKeyListRequest("some-namespace-id", keys);
730
- await runWrangler("kv:key list --namespace-id some-namespace-id");
731
- expect(std.err).toMatchInlineSnapshot(`""`);
732
- expect(std.out).toMatchInlineSnapshot(`
733
- "[
734
- {
735
- \\"name\\": \\"key-1\\"
736
- },
737
- {
738
- \\"name\\": \\"key-2\\",
739
- \\"expiration\\": 123456789
740
- },
741
- {
742
- \\"name\\": \\"key-3\\",
743
- \\"expiration_ttl\\": 666
744
- }
745
- ]"
746
- `);
747
- });
748
-
749
- it("should list the keys of a namespace specified by binding", async () => {
750
- writeWranglerConfig();
751
- const keys = [{ name: "key-1" }, { name: "key-2" }, { name: "key-3" }];
752
- mockKeyListRequest("bound-id", keys);
753
-
754
- await runWrangler("kv:key list --binding someBinding");
755
- expect(std.err).toMatchInlineSnapshot(`""`);
756
- expect(std.out).toMatchInlineSnapshot(`
757
- "[
758
- {
759
- \\"name\\": \\"key-1\\"
760
- },
761
- {
762
- \\"name\\": \\"key-2\\"
763
- },
764
- {
765
- \\"name\\": \\"key-3\\"
766
- }
767
- ]"
768
- `);
769
- });
770
-
771
- it("should list the keys of a preview namespace specified by binding", async () => {
772
- writeWranglerConfig();
773
- const keys = [{ name: "key-1" }, { name: "key-2" }, { name: "key-3" }];
774
- mockKeyListRequest("preview-bound-id", keys);
775
- await runWrangler("kv:key list --binding someBinding --preview");
776
- expect(std.err).toMatchInlineSnapshot(`""`);
777
- expect(std.out).toMatchInlineSnapshot(`
778
- "[
779
- {
780
- \\"name\\": \\"key-1\\"
781
- },
782
- {
783
- \\"name\\": \\"key-2\\"
784
- },
785
- {
786
- \\"name\\": \\"key-3\\"
787
- }
788
- ]"
789
- `);
790
- });
791
-
792
- it("should list the keys of a namespace specified by binding, in a given environment", async () => {
793
- writeWranglerConfig();
794
- const keys = [{ name: "key-1" }, { name: "key-2" }, { name: "key-3" }];
795
- mockKeyListRequest("env-bound-id", keys);
796
- await runWrangler(
797
- "kv:key list --binding someBinding --env some-environment"
798
- );
799
- expect(std.err).toMatchInlineSnapshot(`""`);
800
- expect(std.out).toMatchInlineSnapshot(`
801
- "[
802
- {
803
- \\"name\\": \\"key-1\\"
804
- },
805
- {
806
- \\"name\\": \\"key-2\\"
807
- },
808
- {
809
- \\"name\\": \\"key-3\\"
810
- }
811
- ]"
812
- `);
813
- });
814
-
815
- it("should list the keys of a preview namespace specified by binding, in a given environment", async () => {
816
- writeWranglerConfig();
817
- const keys = [{ name: "key-1" }, { name: "key-2" }, { name: "key-3" }];
818
- mockKeyListRequest("preview-env-bound-id", keys);
819
- await runWrangler(
820
- "kv:key list --binding someBinding --preview --env some-environment"
821
- );
822
- expect(std.err).toMatchInlineSnapshot(`""`);
823
- expect(std.out).toMatchInlineSnapshot(`
824
- "[
825
- {
826
- \\"name\\": \\"key-1\\"
827
- },
828
- {
829
- \\"name\\": \\"key-2\\"
830
- },
831
- {
832
- \\"name\\": \\"key-3\\"
833
- }
834
- ]"
835
- `);
836
- });
837
-
838
- // We'll run the next test with variations on the cursor
839
- // that's returned on cloudflare's API after all results
840
- // have been drained.
841
- for (const blankCursorValue of [undefined, null, ""] as [
842
- undefined,
843
- null,
844
- ""
845
- ]) {
846
- describe(`cursor - ${blankCursorValue}`, () => {
847
- it("should make multiple requests for paginated results", async () => {
848
- // Create a lot of mock keys, so that the fetch requests will be paginated
849
- const keys: NamespaceKeyInfo[] = [];
850
- for (let i = 0; i < 550; i++) {
851
- keys.push({ name: "key-" + i });
852
- }
853
- // Ask for the keys in pages of size 100.
854
- const requests = mockKeyListRequest(
855
- "some-namespace-id",
856
- keys,
857
- 100,
858
- blankCursorValue
859
- );
860
- await runWrangler("kv:key list --namespace-id some-namespace-id");
861
- expect(std.err).toMatchInlineSnapshot(`""`);
862
- expect(JSON.parse(std.out)).toEqual(keys);
863
- expect(requests.count).toEqual(6);
864
- });
865
- });
866
- }
867
-
868
- it("should error if a given binding name is not in the configured kv namespaces", async () => {
869
- writeWranglerConfig();
870
- await expect(
871
- runWrangler("kv:key list --binding otherBinding")
872
- ).rejects.toThrowErrorMatchingInlineSnapshot(
873
- `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
874
- );
875
- expect(std.err).toMatchInlineSnapshot(`
876
- "X [ERROR] A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
877
-
878
- "
879
- `);
880
- expect(std.out).toMatchInlineSnapshot(`
881
- "
882
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
883
- `);
884
- });
885
- });
886
-
887
- describe("get", () => {
888
- afterEach(() => {
889
- unsetMockFetchKVGetValues();
890
- });
891
-
892
- it("should get a key in a given namespace specified by namespace-id", async () => {
893
- setMockFetchKVGetValue(
894
- "some-account-id",
895
- "some-namespace-id",
896
- "my-key",
897
- "my-value"
898
- );
899
- await runWrangler("kv:key get my-key --namespace-id some-namespace-id");
900
- expect(proc.write).toEqual(Buffer.from("my-value"));
901
- expect(std.err).toMatchInlineSnapshot(`""`);
902
- });
903
-
904
- it("should get a binary file by key in a given namespace specified by namespace-id", async () => {
905
- const buf = Buffer.from(
906
- "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAiSURBVHgB7coxEQAACMPAgH/PgAM6dGwu49fA/deIBXrgAj2cAhIFT4QxAAAAAElFTkSuQmCC",
907
- "base64"
908
- );
909
- setMockFetchKVGetValue(
910
- "some-account-id",
911
- "some-namespace-id",
912
- "my-key",
913
- buf
914
- );
915
- await runWrangler("kv:key get my-key --namespace-id some-namespace-id");
916
- expect(proc.write).toEqual(buf);
917
- expect(std.err).toMatchInlineSnapshot(`""`);
918
- });
919
-
920
- it("should get a key in a given namespace specified by binding", async () => {
921
- writeWranglerConfig();
922
- setMockFetchKVGetValue(
923
- "some-account-id",
924
- "bound-id",
925
- "my-key",
926
- "my-value"
927
- );
928
- await runWrangler(
929
- "kv:key get my-key --binding someBinding --preview false"
930
- );
931
- expect(proc.write).toEqual(Buffer.from("my-value"));
932
- expect(std.err).toMatchInlineSnapshot(`""`);
933
- });
934
-
935
- it("should get a key in a given preview namespace specified by binding", async () => {
936
- writeWranglerConfig();
937
- setMockFetchKVGetValue(
938
- "some-account-id",
939
- "preview-bound-id",
940
- "my-key",
941
- "my-value"
942
- );
943
- await runWrangler("kv:key get my-key --binding someBinding --preview");
944
- expect(proc.write).toEqual(Buffer.from("my-value"));
945
- expect(std.err).toMatchInlineSnapshot(`""`);
946
- });
947
-
948
- it("should get a key for the specified environment in a given namespace", async () => {
949
- writeWranglerConfig();
950
- setMockFetchKVGetValue(
951
- "some-account-id",
952
- "env-bound-id",
953
- "my-key",
954
- "my-value"
955
- );
956
- await runWrangler(
957
- "kv:key get my-key --binding someBinding --env some-environment --preview false"
958
- );
959
- expect(proc.write).toEqual(Buffer.from("my-value"));
960
- expect(std.err).toMatchInlineSnapshot(`""`);
961
- });
962
-
963
- it("should encode the key in the api request to get a value", async () => {
964
- setMockFetchKVGetValue(
965
- "some-account-id",
966
- "some-namespace-id",
967
- "%2Fmy%2Ckey",
968
- "my-value"
969
- );
970
- await runWrangler(
971
- "kv:key get /my,key --namespace-id some-namespace-id"
972
- );
973
- expect(proc.write).toEqual(Buffer.from("my-value"));
974
- expect(std.err).toMatchInlineSnapshot(`""`);
975
- });
976
-
977
- it("should error if no key is provided", async () => {
978
- await expect(
979
- runWrangler("kv:key get")
980
- ).rejects.toThrowErrorMatchingInlineSnapshot(
981
- `"Not enough non-option arguments: got 0, need at least 1"`
982
- );
983
- expect(std.out).toMatchInlineSnapshot(`
984
- "
985
- wrangler kv:key get <key>
986
-
987
- Reads a single value by key from the given namespace.
988
-
989
- Positionals:
990
- key The key value to get. [string] [required]
991
-
992
- Flags:
993
- -c, --config Path to .toml configuration file [string]
994
- -h, --help Show help [boolean]
995
- -v, --version Show version number [boolean]
996
-
997
- Options:
998
- --binding The name of the namespace to get from [string]
999
- --namespace-id The id of the namespace to get from [string]
1000
- -e, --env Perform on a specific environment [string]
1001
- --preview Interact with a preview namespace [boolean] [default: false]"
1002
- `);
1003
- expect(std.err).toMatchInlineSnapshot(`
1004
- "X [ERROR] Not enough non-option arguments: got 0, need at least 1
1005
-
1006
- "
1007
- `);
1008
- });
1009
-
1010
- it("should error if no binding nor namespace is provided", async () => {
1011
- await expect(
1012
- runWrangler("kv:key get foo")
1013
- ).rejects.toThrowErrorMatchingInlineSnapshot(
1014
- `"Exactly one of the arguments binding and namespace-id is required"`
1015
- );
1016
- expect(std.out).toMatchInlineSnapshot(`
1017
- "
1018
- wrangler kv:key get <key>
1019
-
1020
- Reads a single value by key from the given namespace.
1021
-
1022
- Positionals:
1023
- key The key value to get. [string] [required]
1024
-
1025
- Flags:
1026
- -c, --config Path to .toml configuration file [string]
1027
- -h, --help Show help [boolean]
1028
- -v, --version Show version number [boolean]
1029
-
1030
- Options:
1031
- --binding The name of the namespace to get from [string]
1032
- --namespace-id The id of the namespace to get from [string]
1033
- -e, --env Perform on a specific environment [string]
1034
- --preview Interact with a preview namespace [boolean] [default: false]"
1035
- `);
1036
- expect(std.err).toMatchInlineSnapshot(`
1037
- "X [ERROR] Exactly one of the arguments binding and namespace-id is required
1038
-
1039
- "
1040
- `);
1041
- });
1042
-
1043
- it("should error if both binding and namespace is provided", async () => {
1044
- await expect(
1045
- runWrangler("kv:key get foo --binding x --namespace-id y")
1046
- ).rejects.toThrowErrorMatchingInlineSnapshot(
1047
- `"Arguments binding and namespace-id are mutually exclusive"`
1048
- );
1049
-
1050
- expect(std.out).toMatchInlineSnapshot(`
1051
- "
1052
- wrangler kv:key get <key>
1053
-
1054
- Reads a single value by key from the given namespace.
1055
-
1056
- Positionals:
1057
- key The key value to get. [string] [required]
1058
-
1059
- Flags:
1060
- -c, --config Path to .toml configuration file [string]
1061
- -h, --help Show help [boolean]
1062
- -v, --version Show version number [boolean]
1063
-
1064
- Options:
1065
- --binding The name of the namespace to get from [string]
1066
- --namespace-id The id of the namespace to get from [string]
1067
- -e, --env Perform on a specific environment [string]
1068
- --preview Interact with a preview namespace [boolean] [default: false]"
1069
- `);
1070
- expect(std.err).toMatchInlineSnapshot(`
1071
- "X [ERROR] Arguments binding and namespace-id are mutually exclusive
1072
-
1073
- "
1074
- `);
1075
- });
1076
-
1077
- it("should error if a given binding name is not in the configured kv namespaces", async () => {
1078
- writeWranglerConfig();
1079
- await expect(
1080
- runWrangler("kv:key get key --binding otherBinding")
1081
- ).rejects.toThrowErrorMatchingInlineSnapshot(
1082
- `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
1083
- );
1084
- expect(std.out).toMatchInlineSnapshot(`
1085
- "
1086
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1087
- `);
1088
- expect(std.err).toMatchInlineSnapshot(`
1089
- "X [ERROR] A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
1090
-
1091
- "
1092
- `);
1093
- });
1094
- });
1095
-
1096
- describe("delete", () => {
1097
- function mockDeleteRequest(
1098
- expectedNamespaceId: string,
1099
- expectedKey: string
1100
- ) {
1101
- const requests = { count: 0 };
1102
- setMockResponse(
1103
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key",
1104
- "DELETE",
1105
- ([_url, accountId, namespaceId, key]) => {
1106
- requests.count++;
1107
- expect(accountId).toEqual("some-account-id");
1108
- expect(namespaceId).toEqual(expectedNamespaceId);
1109
- expect(key).toEqual(expectedKey);
1110
- return null;
1111
- }
1112
- );
1113
- return requests;
1114
- }
1115
-
1116
- it("should delete a key in a namespace specified by id", async () => {
1117
- const requests = mockDeleteRequest("some-namespace-id", "someKey");
1118
- await runWrangler(
1119
- `kv:key delete --namespace-id some-namespace-id someKey`
1120
- );
1121
- expect(requests.count).toEqual(1);
1122
- });
1123
-
1124
- it("should encode the key in the api request to delete a value", async () => {
1125
- const requests = mockDeleteRequest("voyager", "%2FNCC-74656");
1126
- await runWrangler(`kv:key delete --namespace-id voyager /NCC-74656`);
1127
- expect(requests.count).toEqual(1);
1128
- expect(std.out).toMatchInlineSnapshot(
1129
- `"Deleting the key \\"/NCC-74656\\" on namespace voyager."`
1130
- );
1131
- expect(std.err).toMatchInlineSnapshot(`""`);
1132
- });
1133
-
1134
- it("should delete a key in a namespace specified by binding name", async () => {
1135
- writeWranglerConfig();
1136
- const requests = mockDeleteRequest("bound-id", "someKey");
1137
- await runWrangler(
1138
- `kv:key delete --binding someBinding --preview false someKey`
1139
- );
1140
- expect(requests.count).toEqual(1);
1141
- });
1142
-
1143
- it("should delete a key in a preview namespace specified by binding name", async () => {
1144
- writeWranglerConfig();
1145
- const requests = mockDeleteRequest("preview-bound-id", "someKey");
1146
- await runWrangler(
1147
- `kv:key delete --binding someBinding --preview someKey`
1148
- );
1149
- expect(requests.count).toEqual(1);
1150
- });
1151
-
1152
- it("should error if a given binding name is not in the configured kv namespaces", async () => {
1153
- writeWranglerConfig();
1154
- await expect(
1155
- runWrangler(`kv:key delete --binding otherBinding someKey`)
1156
- ).rejects.toThrowErrorMatchingInlineSnapshot(
1157
- `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
1158
- );
1159
-
1160
- expect(std.err).toMatchInlineSnapshot(`
1161
- "X [ERROR] A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
1162
-
1163
- "
1164
- `);
1165
- });
1166
-
1167
- it("should delete a key in a namespace specified by binding name in a given environment", async () => {
1168
- writeWranglerConfig();
1169
- const requests = mockDeleteRequest("env-bound-id", "someKey");
1170
- await runWrangler(
1171
- `kv:key delete --binding someBinding --env some-environment --preview false someKey`
1172
- );
1173
- expect(std.out).toMatchInlineSnapshot(
1174
- `"Deleting the key \\"someKey\\" on namespace env-bound-id."`
1175
- );
1176
- expect(std.err).toMatchInlineSnapshot(`""`);
1177
- expect(requests.count).toEqual(1);
1178
- });
1179
-
1180
- it("should delete a key in a preview namespace specified by binding name in a given environment", async () => {
1181
- writeWranglerConfig();
1182
- const requests = mockDeleteRequest("preview-env-bound-id", "someKey");
1183
- await runWrangler(
1184
- `kv:key delete --binding someBinding --env some-environment --preview someKey`
1185
- );
1186
- expect(requests.count).toEqual(1);
1187
- });
1188
- });
1189
- });
1190
-
1191
- describe("kv:bulk", () => {
1192
- describe("put", () => {
1193
- function mockPutRequest(
1194
- expectedNamespaceId: string,
1195
- expectedKeyValues: KeyValue[]
1196
- ) {
1197
- const requests = { count: 0 };
1198
- setMockResponse(
1199
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId/bulk",
1200
- "PUT",
1201
- ([_url, accountId, namespaceId], { body }) => {
1202
- requests.count++;
1203
- expect(accountId).toEqual("some-account-id");
1204
- expect(namespaceId).toEqual(expectedNamespaceId);
1205
- expect(JSON.parse(body as string)).toEqual(
1206
- expectedKeyValues.slice(
1207
- (requests.count - 1) * 5000,
1208
- requests.count * 5000
1209
- )
1210
- );
1211
- return null;
1212
- }
1213
- );
1214
- return requests;
1215
- }
1216
-
1217
- it("should put the key-values parsed from a file", async () => {
1218
- const keyValues: KeyValue[] = [
1219
- { key: "someKey1", value: "someValue1" },
1220
- { key: "ns:someKey2", value: "123", base64: true },
1221
- { key: "someKey3", value: "someValue3", expiration: 100 },
1222
- { key: "someKey4", value: "someValue4", expiration_ttl: 500 },
1223
- ];
1224
- writeFileSync("./keys.json", JSON.stringify(keyValues));
1225
- const requests = mockPutRequest("some-namespace-id", keyValues);
1226
- await runWrangler(
1227
- `kv:bulk put --namespace-id some-namespace-id keys.json`
1228
- );
1229
- expect(requests.count).toEqual(1);
1230
- expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1231
- expect(std.warn).toMatchInlineSnapshot(`""`);
1232
- expect(std.err).toMatchInlineSnapshot(`""`);
1233
- });
1234
-
1235
- it("should put the key-values in batches of 5000 parsed from a file", async () => {
1236
- const keyValues: KeyValue[] = new Array(12000).fill({
1237
- key: "someKey1",
1238
- value: "someValue1",
1239
- });
1240
- writeFileSync("./keys.json", JSON.stringify(keyValues));
1241
- const requests = mockPutRequest("some-namespace-id", keyValues);
1242
- await runWrangler(
1243
- `kv:bulk put --namespace-id some-namespace-id keys.json`
1244
- );
1245
- expect(requests.count).toEqual(3);
1246
- expect(std.out).toMatchInlineSnapshot(`
1247
- "Uploaded 0% (0 out of 12,000)
1248
- Uploaded 41% (5,000 out of 12,000)
1249
- Uploaded 83% (10,000 out of 12,000)
1250
- Uploaded 100% (12,000 out of 12,000)
1251
- Success!"
1252
- `);
1253
- expect(std.warn).toMatchInlineSnapshot(`""`);
1254
- expect(std.err).toMatchInlineSnapshot(`""`);
1255
- });
1256
-
1257
- it("should error if the file is not a JSON array", async () => {
1258
- const keyValues = { key: "someKey1", value: "someValue1" };
1259
- writeFileSync("./keys.json", JSON.stringify(keyValues));
1260
- await expect(
1261
- runWrangler(`kv:bulk put --namespace-id some-namespace-id keys.json`)
1262
- ).rejects.toThrowErrorMatchingInlineSnapshot(`
1263
- "Unexpected JSON input from \\"keys.json\\".
1264
- Expected an array of key-value objects but got type \\"object\\"."
1265
- `);
1266
- expect(std.out).toMatchInlineSnapshot(`
1267
- "
1268
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1269
- `);
1270
- expect(std.warn).toMatchInlineSnapshot(`""`);
1271
- });
1272
-
1273
- it("should error if the array contains items that are not key-value objects", async () => {
1274
- const keyValues = [
1275
- 123,
1276
- "a string",
1277
- { key: "someKey" },
1278
- { value: "someValue" },
1279
- // add a valid object here to make sure it's not included
1280
- { key: "someKey1", value: "someValue1" },
1281
- // this one will only add a warning
1282
- { key: "someKey1", value: "someValue1", invalid: true },
1283
- // back to the invalid ones
1284
- { key: 123, value: "somevalue" },
1285
- { key: "somekey", value: 123 },
1286
- { key: "someKey1", value: "someValue1", expiration: "string" },
1287
- { key: "someKey1", value: "someValue1", expiration_ttl: "string" },
1288
- {
1289
- key: 123,
1290
- value: {
1291
- a: {
1292
- nested: "object",
1293
- },
1294
- },
1295
- },
1296
- { key: "someKey1", value: "someValue1", metadata: 123 },
1297
- { key: "someKey1", value: "someValue1", base64: "string" },
1298
- ];
1299
- writeFileSync("./keys.json", JSON.stringify(keyValues));
1300
- await expect(
1301
- runWrangler(`kv:bulk put --namespace-id some-namespace-id keys.json`)
1302
- ).rejects.toThrowErrorMatchingInlineSnapshot(`
1303
- "Unexpected JSON input from \\"keys.json\\".
1304
- Each item in the array should be an object that matches:
1305
-
1306
- interface KeyValue {
1307
- key: string;
1308
- value: string;
1309
- expiration?: number;
1310
- expiration_ttl?: number;
1311
- metadata?: object;
1312
- base64?: boolean;
1313
- }
1314
-
1315
- The item at index 0 is 123
1316
- The item at index 1 is \\"a string\\"
1317
- The item at index 2 is {\\"key\\":\\"someKey\\"}
1318
- The item at index 3 is {\\"value\\":\\"someValue\\"}
1319
- The item at index 6 is {\\"key\\":123,\\"value\\":\\"somevalue\\"}
1320
- The item at index 7 is {\\"key\\":\\"somekey\\",\\"value\\":123}
1321
- The item at index 8 is {\\"key\\":\\"someKey1\\",\\"value\\":\\"someValue1\\",\\"expiration\\":\\"string\\"}
1322
- The item at index 9 is {\\"key\\":\\"someKey1\\",\\"value\\":\\"someValue1\\",\\"expiration_ttl\\":\\"string\\"}
1323
- The item at index 10 is {\\"key\\":123,\\"value\\":{\\"a\\":{\\"nested\\":\\"object\\"}}}
1324
- The item at index 11 is {\\"key\\":\\"someKey1\\",\\"value\\":\\"someValue1\\",\\"metadata\\":123}
1325
- The item at index 12 is {\\"key\\":\\"someKey1\\",\\"value\\":\\"someValue1\\",\\"base64\\":\\"string\\"}"
1326
- `);
1327
-
1328
- expect(std.out).toMatchInlineSnapshot(`
1329
- "
1330
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1331
- `);
1332
- expect(std.warn).toMatchInlineSnapshot(`
1333
- "▲ [WARNING] Unexpected key-value properties in \\"keys.json\\".
1334
-
1335
- The item at index 5 contains unexpected properties: [\\"invalid\\"].
1336
-
1337
- "
1338
- `);
1339
- });
1340
- });
1341
-
1342
- describe("delete", () => {
1343
- function mockDeleteRequest(
1344
- expectedNamespaceId: string,
1345
- expectedKeys: string[]
1346
- ) {
1347
- const requests = { count: 0 };
1348
- setMockResponse(
1349
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId/bulk",
1350
- "DELETE",
1351
- ([_url, accountId, namespaceId], { headers, body }) => {
1352
- requests.count++;
1353
- expect(accountId).toEqual("some-account-id");
1354
- expect(namespaceId).toEqual(expectedNamespaceId);
1355
- expect(new Headers(headers ?? []).get("Content-Type")).toEqual(
1356
- "application/json"
1357
- );
1358
- expect(JSON.parse(body as string)).toEqual(
1359
- expectedKeys.slice(
1360
- (requests.count - 1) * 5000,
1361
- requests.count * 5000
1362
- )
1363
- );
1364
- return null;
1365
- }
1366
- );
1367
- return requests;
1368
- }
1369
-
1370
- it("should delete the keys parsed from a file", async () => {
1371
- const keys = ["someKey1", "ns:someKey2"];
1372
- writeFileSync("./keys.json", JSON.stringify(keys));
1373
- mockConfirm({
1374
- text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1375
- result: true,
1376
- });
1377
- const requests = mockDeleteRequest("some-namespace-id", keys);
1378
- await runWrangler(
1379
- `kv:bulk delete --namespace-id some-namespace-id keys.json`
1380
- );
1381
- expect(requests.count).toEqual(1);
1382
- expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1383
- expect(std.warn).toMatchInlineSnapshot(`""`);
1384
- expect(std.err).toMatchInlineSnapshot(`""`);
1385
- });
1386
-
1387
- it("should delete the keys in batches of 5000 parsed from a file", async () => {
1388
- const keys = new Array(12000).fill("some-key");
1389
- writeFileSync("./keys.json", JSON.stringify(keys));
1390
- mockConfirm({
1391
- text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1392
- result: true,
1393
- });
1394
- const requests = mockDeleteRequest("some-namespace-id", keys);
1395
- await runWrangler(
1396
- `kv:bulk delete --namespace-id some-namespace-id keys.json`
1397
- );
1398
- expect(requests.count).toEqual(3);
1399
- expect(std.out).toMatchInlineSnapshot(`
1400
- "Deleted 0% (0 out of 12,000)
1401
- Deleted 41% (5,000 out of 12,000)
1402
- Deleted 83% (10,000 out of 12,000)
1403
- Deleted 100% (12,000 out of 12,000)
1404
- Success!"
1405
- `);
1406
- expect(std.warn).toMatchInlineSnapshot(`""`);
1407
- expect(std.err).toMatchInlineSnapshot(`""`);
1408
- });
1409
-
1410
- it("should not delete the keys if the user confirms no", async () => {
1411
- const keys = ["someKey1", "ns:someKey2"];
1412
- writeFileSync("./keys.json", JSON.stringify(keys));
1413
- mockConfirm({
1414
- text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1415
- result: false,
1416
- });
1417
- await runWrangler(
1418
- `kv:bulk delete --namespace-id some-namespace-id keys.json`
1419
- );
1420
- expect(std.out).toMatchInlineSnapshot(
1421
- `"Not deleting keys read from \\"keys.json\\"."`
1422
- );
1423
- expect(std.warn).toMatchInlineSnapshot(`""`);
1424
- expect(std.err).toMatchInlineSnapshot(`""`);
1425
- });
1426
-
1427
- it("should delete the keys without asking if --force is provided", async () => {
1428
- const keys = ["someKey1", "ns:someKey2"];
1429
- writeFileSync("./keys.json", JSON.stringify(keys));
1430
- const requests = mockDeleteRequest("some-namespace-id", keys);
1431
- await runWrangler(
1432
- `kv:bulk delete --namespace-id some-namespace-id keys.json --force`
1433
- );
1434
- expect(requests.count).toEqual(1);
1435
- expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1436
- expect(std.warn).toMatchInlineSnapshot(`""`);
1437
- expect(std.err).toMatchInlineSnapshot(`""`);
1438
- });
1439
-
1440
- it("should delete the keys without asking if -f is provided", async () => {
1441
- const keys = ["someKey1", "ns:someKey2"];
1442
- writeFileSync("./keys.json", JSON.stringify(keys));
1443
- const requests = mockDeleteRequest("some-namespace-id", keys);
1444
- await runWrangler(
1445
- `kv:bulk delete --namespace-id some-namespace-id keys.json -f`
1446
- );
1447
- expect(requests.count).toEqual(1);
1448
- expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1449
- expect(std.warn).toMatchInlineSnapshot(`""`);
1450
- expect(std.err).toMatchInlineSnapshot(`""`);
1451
- });
1452
-
1453
- it("should error if the file is not a JSON array", async () => {
1454
- const keys = 12354;
1455
- writeFileSync("./keys.json", JSON.stringify(keys));
1456
- mockConfirm({
1457
- text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1458
- result: true,
1459
- });
1460
- await expect(
1461
- runWrangler(
1462
- `kv:bulk delete --namespace-id some-namespace-id keys.json`
1463
- )
1464
- ).rejects.toThrowErrorMatchingInlineSnapshot(`
1465
- "Unexpected JSON input from \\"keys.json\\".
1466
- Expected an array of strings but got:
1467
- 12354"
1468
- `);
1469
- expect(std.out).toMatchInlineSnapshot(`
1470
- "
1471
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1472
- `);
1473
- expect(std.warn).toMatchInlineSnapshot(`""`);
1474
- });
1475
-
1476
- it("should error if the file contains non-string items", async () => {
1477
- const keys = ["good", 12354, { key: "someKey" }, null];
1478
- writeFileSync("./keys.json", JSON.stringify(keys));
1479
- mockConfirm({
1480
- text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1481
- result: true,
1482
- });
1483
- await expect(
1484
- runWrangler(
1485
- `kv:bulk delete --namespace-id some-namespace-id keys.json`
1486
- )
1487
- ).rejects.toThrowErrorMatchingInlineSnapshot(`
1488
- "Unexpected JSON input from \\"keys.json\\".
1489
- Expected an array of strings.
1490
- The item at index 1 is type: \\"number\\" - 12354
1491
- The item at index 2 is type: \\"object\\" - {\\"key\\":\\"someKey\\"}
1492
- The item at index 3 is type: \\"object\\" - null"
1493
- `);
1494
- expect(std.out).toMatchInlineSnapshot(`
1495
- "
1496
- If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1497
- `);
1498
- expect(std.warn).toMatchInlineSnapshot(`""`);
1499
- });
1500
- });
1501
- });
18
+ mockAccountId();
19
+ mockApiToken();
20
+ runInTempDir();
21
+
22
+ const std = mockConsoleMethods();
23
+ const proc = mockProcess();
24
+
25
+ afterEach(() => {
26
+ clearConfirmMocks();
27
+ });
28
+ describe("kv:namespace", () => {
29
+ describe("create", () => {
30
+ function mockCreateRequest(expectedTitle: string) {
31
+ msw.use(
32
+ rest.post(
33
+ "*/accounts/:accountId/storage/kv/namespaces",
34
+ async (req, res, ctx) => {
35
+ expect(req.params.accountId).toEqual("some-account-id");
36
+ const title = (await req.json()).title as string;
37
+ expect(title).toEqual(expectedTitle);
38
+ return res.once(
39
+ ctx.status(200),
40
+ ctx.json(createFetchResult({ id: "some-namespace-id" }))
41
+ );
42
+ }
43
+ )
44
+ );
45
+ }
46
+
47
+ it("should error if no namespace is given", async () => {
48
+ await expect(
49
+ runWrangler("kv:namespace create")
50
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
51
+ `"Not enough non-option arguments: got 0, need at least 1"`
52
+ );
53
+ expect(std.out).toMatchInlineSnapshot(`
54
+ "
55
+ wrangler kv:namespace create <namespace>
56
+
57
+ Create a new namespace
58
+
59
+ Positionals:
60
+ namespace The name of the new namespace [string] [required]
61
+
62
+ Flags:
63
+ -c, --config Path to .toml configuration file [string]
64
+ -e, --env Environment to use for operations and .env files [string]
65
+ -h, --help Show help [boolean]
66
+ -v, --version Show version number [boolean]
67
+
68
+ Options:
69
+ --preview Interact with a preview namespace [boolean]"
70
+ `);
71
+ expect(std.err).toMatchInlineSnapshot(`
72
+ "X [ERROR] Not enough non-option arguments: got 0, need at least 1
73
+
74
+ "
75
+ `);
76
+ });
77
+
78
+ it("should error if the namespace to create contains spaces", async () => {
79
+ await expect(
80
+ runWrangler("kv:namespace create abc def ghi")
81
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
82
+ `"Unknown arguments: def, ghi"`
83
+ );
84
+ expect(std.out).toMatchInlineSnapshot(`
85
+ "
86
+ wrangler kv:namespace create <namespace>
87
+
88
+ Create a new namespace
89
+
90
+ Positionals:
91
+ namespace The name of the new namespace [string] [required]
92
+
93
+ Flags:
94
+ -c, --config Path to .toml configuration file [string]
95
+ -e, --env Environment to use for operations and .env files [string]
96
+ -h, --help Show help [boolean]
97
+ -v, --version Show version number [boolean]
98
+
99
+ Options:
100
+ --preview Interact with a preview namespace [boolean]"
101
+ `);
102
+ expect(std.err).toMatchInlineSnapshot(`
103
+ "X [ERROR] Unknown arguments: def, ghi
104
+
105
+ "
106
+ `);
107
+ });
108
+
109
+ it("should error if the namespace to create is not valid", async () => {
110
+ await expect(
111
+ runWrangler("kv:namespace create abc-def")
112
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
113
+ `"The namespace binding name \\"abc-def\\" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number."`
114
+ );
115
+
116
+ expect(std.out).toMatchInlineSnapshot(`
117
+ "
118
+ wrangler kv:namespace create <namespace>
119
+
120
+ Create a new namespace
121
+
122
+ Positionals:
123
+ namespace The name of the new namespace [string] [required]
124
+
125
+ Flags:
126
+ -c, --config Path to .toml configuration file [string]
127
+ -e, --env Environment to use for operations and .env files [string]
128
+ -h, --help Show help [boolean]
129
+ -v, --version Show version number [boolean]
130
+
131
+ Options:
132
+ --preview Interact with a preview namespace [boolean]"
133
+ `);
134
+ expect(std.err).toMatchInlineSnapshot(`
135
+ "X [ERROR] The namespace binding name \\"abc-def\\" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.
136
+
137
+ "
138
+ `);
139
+ });
140
+
141
+ it("should create a namespace", async () => {
142
+ mockCreateRequest("worker-UnitTestNamespace");
143
+ await runWrangler("kv:namespace create UnitTestNamespace");
144
+ expect(std.out).toMatchInlineSnapshot(`
145
+ "🌀 Creating namespace with title \\"worker-UnitTestNamespace\\"
146
+ ✨ Success!
147
+ Add the following to your configuration file in your kv_namespaces array:
148
+ { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
149
+ `);
150
+ });
151
+
152
+ it("should create a preview namespace if configured to do so", async () => {
153
+ mockCreateRequest("worker-UnitTestNamespace_preview");
154
+ await runWrangler("kv:namespace create UnitTestNamespace --preview");
155
+ expect(std.out).toMatchInlineSnapshot(`
156
+ "🌀 Creating namespace with title \\"worker-UnitTestNamespace_preview\\"
157
+ ✨ Success!
158
+ Add the following to your configuration file in your kv_namespaces array:
159
+ { binding = \\"UnitTestNamespace\\", preview_id = \\"some-namespace-id\\" }"
160
+ `);
161
+ });
162
+
163
+ it("should create a namespace using configured worker name", async () => {
164
+ writeFileSync("./wrangler.toml", 'name = "other-worker"', "utf-8");
165
+ mockCreateRequest("other-worker-UnitTestNamespace");
166
+ await runWrangler("kv:namespace create UnitTestNamespace");
167
+ expect(std.out).toMatchInlineSnapshot(`
168
+ "🌀 Creating namespace with title \\"other-worker-UnitTestNamespace\\"
169
+ ✨ Success!
170
+ Add the following to your configuration file in your kv_namespaces array:
171
+ { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
172
+ `);
173
+ });
174
+
175
+ it("should create a namespace in an environment if configured to do so", async () => {
176
+ mockCreateRequest("worker-customEnv-UnitTestNamespace");
177
+ await runWrangler(
178
+ "kv:namespace create UnitTestNamespace --env customEnv"
179
+ );
180
+ expect(std.out).toMatchInlineSnapshot(`
181
+ "🌀 Creating namespace with title \\"worker-customEnv-UnitTestNamespace\\"
182
+ ✨ Success!
183
+ Add the following to your configuration file in your kv_namespaces array under [env.customEnv]:
184
+ { binding = \\"UnitTestNamespace\\", id = \\"some-namespace-id\\" }"
185
+ `);
186
+ });
187
+ });
188
+
189
+ describe("list", () => {
190
+ function mockListRequest(namespaces: KVNamespaceInfo[]) {
191
+ const requests = { count: 0 };
192
+ msw.use(
193
+ rest.get(
194
+ "*/accounts/:accountId/storage/kv/namespaces",
195
+ async (req, res, ctx) => {
196
+ requests.count++;
197
+ expect(req.params.accountId).toEqual("some-account-id");
198
+ expect(req.url.searchParams.get("per_page")).toEqual("100");
199
+ expect(req.url.searchParams.get("order")).toEqual("title");
200
+ expect(req.url.searchParams.get("direction")).toEqual("asc");
201
+ expect(req.url.searchParams.get("page")).toEqual(
202
+ `${requests.count}`
203
+ );
204
+
205
+ const pageSize = Number(req.url.searchParams.get("per_page"));
206
+ const page = Number(req.url.searchParams.get("page"));
207
+ return res(
208
+ ctx.json(
209
+ createFetchResult(
210
+ namespaces.slice((page - 1) * pageSize, page * pageSize)
211
+ )
212
+ )
213
+ );
214
+ }
215
+ )
216
+ );
217
+ return requests;
218
+ }
219
+
220
+ it("should list namespaces", async () => {
221
+ const kvNamespaces: KVNamespaceInfo[] = [
222
+ { title: "title-1", id: "id-1" },
223
+ { title: "title-2", id: "id-2" },
224
+ ];
225
+ mockListRequest(kvNamespaces);
226
+ await runWrangler("kv:namespace list");
227
+
228
+ expect(std.err).toMatchInlineSnapshot(`""`);
229
+ expect(JSON.parse(std.out)).toEqual(kvNamespaces);
230
+ });
231
+
232
+ it("should make multiple requests for paginated results", async () => {
233
+ // Create a lot of mock namespaces, so that the fetch requests will be paginated
234
+ const kvNamespaces: KVNamespaceInfo[] = [];
235
+ for (let i = 0; i < 550; i++) {
236
+ kvNamespaces.push({ title: "title-" + i, id: "id-" + i });
237
+ }
238
+ const requests = mockListRequest(kvNamespaces);
239
+ await runWrangler("kv:namespace list");
240
+
241
+ expect(JSON.parse(std.out)).toEqual(kvNamespaces);
242
+ expect(requests.count).toEqual(6);
243
+ });
244
+ });
245
+
246
+ describe("delete", () => {
247
+ function mockDeleteRequest(expectedNamespaceId: string) {
248
+ const requests = { count: 0 };
249
+ msw.use(
250
+ rest.delete(
251
+ "*/accounts/:accountId/storage/kv/namespaces/:namespaceId",
252
+ (req, res, ctx) => {
253
+ requests.count++;
254
+ expect(req.params.accountId).toEqual("some-account-id");
255
+ expect(req.params.namespaceId).toEqual(expectedNamespaceId);
256
+ return res(ctx.status(200), ctx.json(createFetchResult(null)));
257
+ }
258
+ )
259
+ );
260
+ return requests;
261
+ }
262
+
263
+ it("should delete a namespace specified by id", async () => {
264
+ const requests = mockDeleteRequest("some-namespace-id");
265
+ await runWrangler(
266
+ `kv:namespace delete --namespace-id some-namespace-id`
267
+ );
268
+ expect(requests.count).toEqual(1);
269
+ });
270
+
271
+ it("should delete a namespace specified by binding name", async () => {
272
+ writeWranglerConfig();
273
+ const requests = mockDeleteRequest("bound-id");
274
+ await runWrangler(
275
+ `kv:namespace delete --binding someBinding --preview false`
276
+ );
277
+ expect(requests.count).toEqual(1);
278
+ });
279
+
280
+ it("should delete a preview namespace specified by binding name", async () => {
281
+ writeWranglerConfig();
282
+ const requests = mockDeleteRequest("preview-bound-id");
283
+ await runWrangler(
284
+ `kv:namespace delete --binding someBinding --preview`
285
+ );
286
+ expect(requests.count).toEqual(1);
287
+ });
288
+
289
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
290
+ writeWranglerConfig();
291
+ await expect(runWrangler("kv:namespace delete --binding otherBinding"))
292
+ .rejects.toThrowErrorMatchingInlineSnapshot(`
293
+ "Not able to delete namespace.
294
+ A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."
295
+ `);
296
+ expect(std.err).toMatchInlineSnapshot(`
297
+ "X [ERROR] Not able to delete namespace.
298
+
299
+ A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
300
+
301
+ "
302
+ `);
303
+ });
304
+
305
+ it("should delete a namespace specified by binding name in a given environment", async () => {
306
+ writeWranglerConfig();
307
+ const requests = mockDeleteRequest("env-bound-id");
308
+ await runWrangler(
309
+ "kv:namespace delete --binding someBinding --env some-environment --preview false"
310
+ );
311
+
312
+ expect(std.out).toMatchInlineSnapshot(`
313
+ "Deleting KV namespace env-bound-id.
314
+ Deleted KV namespace env-bound-id."
315
+ `);
316
+ expect(std.err).toMatchInlineSnapshot(`""`);
317
+ expect(requests.count).toEqual(1);
318
+ });
319
+
320
+ it("should delete a preview namespace specified by binding name in a given environment", async () => {
321
+ writeWranglerConfig();
322
+ const requests = mockDeleteRequest("preview-env-bound-id");
323
+ await runWrangler(
324
+ `kv:namespace delete --binding someBinding --env some-environment --preview`
325
+ );
326
+ expect(requests.count).toEqual(1);
327
+ });
328
+ });
329
+ });
330
+
331
+ describe("kv:key", () => {
332
+ describe("put", () => {
333
+ function mockKeyPutRequest(
334
+ expectedNamespaceId: string,
335
+ expectedKV: KeyValue
336
+ ) {
337
+ const requests = { count: 0 };
338
+ msw.use(
339
+ rest.put(
340
+ "*/accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key",
341
+ (req, res, ctx) => {
342
+ requests.count++;
343
+ const { accountId, namespaceId, key } = req.params;
344
+ expect(accountId).toEqual("some-account-id");
345
+ expect(namespaceId).toEqual(expectedNamespaceId);
346
+ expect(encodeURIComponent(key as string)).toEqual(expectedKV.key);
347
+ // if (expectedKV.metadata) {
348
+ // expect(body).toBeInstanceOf(FormData);
349
+ // expect((body as FormData).get("value")).toEqual(
350
+ // expectedKV.value
351
+ // );
352
+ // expect((body as FormData).get("metadata")).toEqual(
353
+ // JSON.stringify(expectedKV.metadata)
354
+ // );
355
+ // } else {
356
+ // expect(body).toEqual(expectedKV.value);
357
+ // }
358
+ if (expectedKV.expiration !== undefined) {
359
+ expect(req.url.searchParams.get("expiration")).toEqual(
360
+ `${expectedKV.expiration}`
361
+ );
362
+ } else {
363
+ expect(req.url.searchParams.has("expiration")).toBe(false);
364
+ }
365
+ if (expectedKV.expiration_ttl) {
366
+ expect(req.url.searchParams.get("expiration_ttl")).toEqual(
367
+ `${expectedKV.expiration_ttl}`
368
+ );
369
+ } else {
370
+ expect(req.url.searchParams.has("expiration_ttl")).toBe(false);
371
+ }
372
+ return res(ctx.status(200), ctx.json(createFetchResult(null)));
373
+ }
374
+ )
375
+ );
376
+ return requests;
377
+ }
378
+
379
+ it("should put a key in a given namespace specified by namespace-id", async () => {
380
+ const requests = mockKeyPutRequest("some-namespace-id", {
381
+ key: "my-key",
382
+ value: "my-value",
383
+ });
384
+
385
+ await runWrangler(
386
+ "kv:key put my-key my-value --namespace-id some-namespace-id"
387
+ );
388
+
389
+ expect(requests.count).toEqual(1);
390
+ expect(std.out).toMatchInlineSnapshot(
391
+ `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace some-namespace-id."`
392
+ );
393
+ expect(std.err).toMatchInlineSnapshot(`""`);
394
+ });
395
+
396
+ it("should encode the key in the api request to put a value", async () => {
397
+ const requests = mockKeyPutRequest("DS9", {
398
+ key: "%2Fmy-key",
399
+ value: "my-value",
400
+ });
401
+
402
+ await runWrangler("kv:key put /my-key my-value --namespace-id DS9");
403
+
404
+ expect(requests.count).toEqual(1);
405
+ expect(std.out).toMatchInlineSnapshot(
406
+ `"Writing the value \\"my-value\\" to key \\"/my-key\\" on namespace DS9."`
407
+ );
408
+ expect(std.err).toMatchInlineSnapshot(`""`);
409
+ });
410
+
411
+ it("should put a key in a given namespace specified by binding", async () => {
412
+ writeWranglerConfig();
413
+ const requests = mockKeyPutRequest("bound-id", {
414
+ key: "my-key",
415
+ value: "my-value",
416
+ });
417
+ await runWrangler(
418
+ "kv:key put my-key my-value --binding someBinding --preview false"
419
+ );
420
+
421
+ expect(std.out).toMatchInlineSnapshot(
422
+ `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace bound-id."`
423
+ );
424
+ expect(std.err).toMatchInlineSnapshot(`""`);
425
+ expect(requests.count).toEqual(1);
426
+ });
427
+
428
+ it("should put a key in a given preview namespace specified by binding", async () => {
429
+ writeWranglerConfig();
430
+ const requests = mockKeyPutRequest("preview-bound-id", {
431
+ key: "my-key",
432
+ value: "my-value",
433
+ });
434
+
435
+ await runWrangler(
436
+ "kv:key put my-key my-value --binding someBinding --preview"
437
+ );
438
+
439
+ expect(std.out).toMatchInlineSnapshot(
440
+ `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace preview-bound-id."`
441
+ );
442
+ expect(std.err).toMatchInlineSnapshot(`""`);
443
+ expect(requests.count).toEqual(1);
444
+ });
445
+
446
+ it("should add expiration and ttl properties when putting a key", async () => {
447
+ const requests = mockKeyPutRequest("some-namespace-id", {
448
+ key: "my-key",
449
+ value: "my-value",
450
+ expiration: 10,
451
+ expiration_ttl: 20,
452
+ });
453
+ await runWrangler(
454
+ "kv:key put my-key my-value --namespace-id some-namespace-id --expiration 10 --ttl 20"
455
+ );
456
+ expect(requests.count).toEqual(1);
457
+ expect(std.out).toMatchInlineSnapshot(
458
+ `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace some-namespace-id."`
459
+ );
460
+ expect(std.err).toMatchInlineSnapshot(`""`);
461
+ });
462
+
463
+ it("should put a key to the specified environment in a given namespace", async () => {
464
+ writeWranglerConfig();
465
+ const requests = mockKeyPutRequest("env-bound-id", {
466
+ key: "my-key",
467
+ value: "my-value",
468
+ });
469
+ await runWrangler(
470
+ "kv:key put my-key my-value --binding someBinding --env some-environment --preview false"
471
+ );
472
+ expect(std.out).toMatchInlineSnapshot(
473
+ `"Writing the value \\"my-value\\" to key \\"my-key\\" on namespace env-bound-id."`
474
+ );
475
+ expect(std.err).toMatchInlineSnapshot(`""`);
476
+ expect(requests.count).toEqual(1);
477
+ });
478
+
479
+ it("should put a key with a value loaded from a given path", async () => {
480
+ const buf = Buffer.from("file-contents", "utf-8");
481
+ writeFileSync("foo.txt", buf);
482
+ const requests = mockKeyPutRequest("some-namespace-id", {
483
+ key: "my-key",
484
+ value: buf,
485
+ });
486
+ await runWrangler(
487
+ "kv:key put my-key --namespace-id some-namespace-id --path foo.txt"
488
+ );
489
+ expect(std.out).toMatchInlineSnapshot(
490
+ `"Writing the contents of foo.txt to the key \\"my-key\\" on namespace some-namespace-id."`
491
+ );
492
+ expect(std.err).toMatchInlineSnapshot(`""`);
493
+ expect(requests.count).toEqual(1);
494
+ });
495
+
496
+ it("should put a key with a binary value loaded from a given path", async () => {
497
+ const buf = Buffer.from(
498
+ "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAiSURBVHgB7coxEQAACMPAgH/PgAM6dGwu49fA/deIBXrgAj2cAhIFT4QxAAAAAElFTkSuQmCC",
499
+ "base64"
500
+ );
501
+ writeFileSync("test.png", buf);
502
+ const requests = mockKeyPutRequest("another-namespace-id", {
503
+ key: "my-key",
504
+ value: buf,
505
+ });
506
+ await runWrangler(
507
+ "kv:key put my-key --namespace-id another-namespace-id --path test.png"
508
+ );
509
+ expect(std.out).toMatchInlineSnapshot(
510
+ `"Writing the contents of test.png to the key \\"my-key\\" on namespace another-namespace-id."`
511
+ );
512
+ expect(std.err).toMatchInlineSnapshot(`""`);
513
+ expect(requests.count).toEqual(1);
514
+ });
515
+
516
+ it("should put a key with metadata", async () => {
517
+ const requests = mockKeyPutRequest("some-namespace-id", {
518
+ key: "dKey",
519
+ value: "dVal",
520
+ metadata: {
521
+ mKey: "mValue",
522
+ },
523
+ });
524
+ await runWrangler(
525
+ `kv:key put dKey dVal --namespace-id some-namespace-id --metadata {"mKey":"mValue"}`
526
+ );
527
+ expect(requests.count).toEqual(1);
528
+ expect(std.out).toMatchInlineSnapshot(
529
+ `"Writing the value \\"dVal\\" to key \\"dKey\\" on namespace some-namespace-id with metadata \\"{\\"mKey\\":\\"mValue\\"}\\"."`
530
+ );
531
+ expect(std.err).toMatchInlineSnapshot(`""`);
532
+ });
533
+
534
+ it("should error if no key is provided", async () => {
535
+ await expect(
536
+ runWrangler("kv:key put")
537
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
538
+ `"Not enough non-option arguments: got 0, need at least 1"`
539
+ );
540
+
541
+ expect(std.out).toMatchInlineSnapshot(`
542
+ "
543
+ wrangler kv:key put <key> [value]
544
+
545
+ Writes a single key/value pair to the given namespace.
546
+
547
+ Positionals:
548
+ key The key to write to [string] [required]
549
+ value The value to write [string]
550
+
551
+ Flags:
552
+ -c, --config Path to .toml configuration file [string]
553
+ -e, --env Environment to use for operations and .env files [string]
554
+ -h, --help Show help [boolean]
555
+ -v, --version Show version number [boolean]
556
+
557
+ Options:
558
+ --binding The binding of the namespace to write to [string]
559
+ --namespace-id The id of the namespace to write to [string]
560
+ --preview Interact with a preview namespace [boolean]
561
+ --ttl Time for which the entries should be visible [number]
562
+ --expiration Time since the UNIX epoch after which the entry expires [number]
563
+ --metadata Arbitrary JSON that is associated with a key [string]
564
+ --path Read value from the file at a given path [string]"
565
+ `);
566
+ expect(std.err).toMatchInlineSnapshot(`
567
+ "X [ERROR] Not enough non-option arguments: got 0, need at least 1
568
+
569
+ "
570
+ `);
571
+ });
572
+
573
+ it("should error if no binding nor namespace is provided", async () => {
574
+ await expect(
575
+ runWrangler("kv:key put foo bar")
576
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
577
+ `"Exactly one of the arguments binding and namespace-id is required"`
578
+ );
579
+
580
+ expect(std.out).toMatchInlineSnapshot(`
581
+ "
582
+ wrangler kv:key put <key> [value]
583
+
584
+ Writes a single key/value pair to the given namespace.
585
+
586
+ Positionals:
587
+ key The key to write to [string] [required]
588
+ value The value to write [string]
589
+
590
+ Flags:
591
+ -c, --config Path to .toml configuration file [string]
592
+ -e, --env Environment to use for operations and .env files [string]
593
+ -h, --help Show help [boolean]
594
+ -v, --version Show version number [boolean]
595
+
596
+ Options:
597
+ --binding The binding of the namespace to write to [string]
598
+ --namespace-id The id of the namespace to write to [string]
599
+ --preview Interact with a preview namespace [boolean]
600
+ --ttl Time for which the entries should be visible [number]
601
+ --expiration Time since the UNIX epoch after which the entry expires [number]
602
+ --metadata Arbitrary JSON that is associated with a key [string]
603
+ --path Read value from the file at a given path [string]"
604
+ `);
605
+ expect(std.err).toMatchInlineSnapshot(`
606
+ "X [ERROR] Exactly one of the arguments binding and namespace-id is required
607
+
608
+ "
609
+ `);
610
+ });
611
+
612
+ it("should error if both binding and namespace is provided", async () => {
613
+ await expect(
614
+ runWrangler("kv:key put foo bar --binding x --namespace-id y")
615
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
616
+ `"Arguments binding and namespace-id are mutually exclusive"`
617
+ );
618
+
619
+ expect(std.out).toMatchInlineSnapshot(`
620
+ "
621
+ wrangler kv:key put <key> [value]
622
+
623
+ Writes a single key/value pair to the given namespace.
624
+
625
+ Positionals:
626
+ key The key to write to [string] [required]
627
+ value The value to write [string]
628
+
629
+ Flags:
630
+ -c, --config Path to .toml configuration file [string]
631
+ -e, --env Environment to use for operations and .env files [string]
632
+ -h, --help Show help [boolean]
633
+ -v, --version Show version number [boolean]
634
+
635
+ Options:
636
+ --binding The binding of the namespace to write to [string]
637
+ --namespace-id The id of the namespace to write to [string]
638
+ --preview Interact with a preview namespace [boolean]
639
+ --ttl Time for which the entries should be visible [number]
640
+ --expiration Time since the UNIX epoch after which the entry expires [number]
641
+ --metadata Arbitrary JSON that is associated with a key [string]
642
+ --path Read value from the file at a given path [string]"
643
+ `);
644
+ expect(std.err).toMatchInlineSnapshot(`
645
+ "X [ERROR] Arguments binding and namespace-id are mutually exclusive
646
+
647
+ "
648
+ `);
649
+ });
650
+
651
+ it("should error if no value nor path is provided", async () => {
652
+ await expect(
653
+ runWrangler("kv:key put key --namespace-id 12345")
654
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
655
+ `"Exactly one of the arguments value and path is required"`
656
+ );
657
+
658
+ expect(std.out).toMatchInlineSnapshot(`
659
+ "
660
+ wrangler kv:key put <key> [value]
661
+
662
+ Writes a single key/value pair to the given namespace.
663
+
664
+ Positionals:
665
+ key The key to write to [string] [required]
666
+ value The value to write [string]
667
+
668
+ Flags:
669
+ -c, --config Path to .toml configuration file [string]
670
+ -e, --env Environment to use for operations and .env files [string]
671
+ -h, --help Show help [boolean]
672
+ -v, --version Show version number [boolean]
673
+
674
+ Options:
675
+ --binding The binding of the namespace to write to [string]
676
+ --namespace-id The id of the namespace to write to [string]
677
+ --preview Interact with a preview namespace [boolean]
678
+ --ttl Time for which the entries should be visible [number]
679
+ --expiration Time since the UNIX epoch after which the entry expires [number]
680
+ --metadata Arbitrary JSON that is associated with a key [string]
681
+ --path Read value from the file at a given path [string]"
682
+ `);
683
+ expect(std.err).toMatchInlineSnapshot(`
684
+ "X [ERROR] Exactly one of the arguments value and path is required
685
+
686
+ "
687
+ `);
688
+ });
689
+
690
+ it("should error if both value and path is provided", async () => {
691
+ await expect(
692
+ runWrangler("kv:key put key value --path xyz --namespace-id 12345")
693
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
694
+ `"Arguments value and path are mutually exclusive"`
695
+ );
696
+
697
+ expect(std.out).toMatchInlineSnapshot(`
698
+ "
699
+ wrangler kv:key put <key> [value]
700
+
701
+ Writes a single key/value pair to the given namespace.
702
+
703
+ Positionals:
704
+ key The key to write to [string] [required]
705
+ value The value to write [string]
706
+
707
+ Flags:
708
+ -c, --config Path to .toml configuration file [string]
709
+ -e, --env Environment to use for operations and .env files [string]
710
+ -h, --help Show help [boolean]
711
+ -v, --version Show version number [boolean]
712
+
713
+ Options:
714
+ --binding The binding of the namespace to write to [string]
715
+ --namespace-id The id of the namespace to write to [string]
716
+ --preview Interact with a preview namespace [boolean]
717
+ --ttl Time for which the entries should be visible [number]
718
+ --expiration Time since the UNIX epoch after which the entry expires [number]
719
+ --metadata Arbitrary JSON that is associated with a key [string]
720
+ --path Read value from the file at a given path [string]"
721
+ `);
722
+ expect(std.err).toMatchInlineSnapshot(`
723
+ "X [ERROR] Arguments value and path are mutually exclusive
724
+
725
+ "
726
+ `);
727
+ });
728
+
729
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
730
+ writeWranglerConfig();
731
+ await expect(
732
+ runWrangler("kv:key put key value --binding otherBinding")
733
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
734
+ `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
735
+ );
736
+
737
+ expect(std.out).toMatchInlineSnapshot(`
738
+ "
739
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
740
+ `);
741
+ expect(std.err).toMatchInlineSnapshot(`
742
+ "X [ERROR] A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
743
+
744
+ "
745
+ `);
746
+ });
747
+
748
+ it("should error if a given binding has both preview and non-preview and --preview is not specified", async () => {
749
+ writeWranglerConfig();
750
+ const requests = mockKeyPutRequest("preview-bound-id", {
751
+ key: "my-key",
752
+ value: "my-value",
753
+ });
754
+ await expect(
755
+ runWrangler("kv:key put my-key my-value --binding someBinding")
756
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
757
+ `"someBinding has both a namespace ID and a preview ID. Specify \\"--preview\\" or \\"--preview false\\" to avoid writing data to the wrong namespace."`
758
+ );
759
+ expect(std.out).toMatchInlineSnapshot(`
760
+ "
761
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
762
+ `);
763
+ expect(std.err).toMatchInlineSnapshot(`
764
+ "X [ERROR] someBinding has both a namespace ID and a preview ID. Specify \\"--preview\\" or \\"--preview false\\" to avoid writing data to the wrong namespace.
765
+
766
+ "
767
+ `);
768
+ expect(requests.count).toEqual(0);
769
+ });
770
+ });
771
+
772
+ describe("list", () => {
773
+ it("should list the keys of a namespace specified by namespace-id", async () => {
774
+ const keys = [
775
+ { name: "key-1" },
776
+ { name: "key-2", expiration: 123456789 },
777
+ { name: "key-3", expiration_ttl: 666 },
778
+ ];
779
+ mockKeyListRequest("some-namespace-id", keys);
780
+ await runWrangler("kv:key list --namespace-id some-namespace-id");
781
+ expect(std.err).toMatchInlineSnapshot(`""`);
782
+ expect(std.out).toMatchInlineSnapshot(`
783
+ "[
784
+ {
785
+ \\"name\\": \\"key-1\\"
786
+ },
787
+ {
788
+ \\"name\\": \\"key-2\\",
789
+ \\"expiration\\": 123456789
790
+ },
791
+ {
792
+ \\"name\\": \\"key-3\\",
793
+ \\"expiration_ttl\\": 666
794
+ }
795
+ ]"
796
+ `);
797
+ });
798
+
799
+ it("should list the keys of a namespace specified by binding", async () => {
800
+ writeWranglerConfig();
801
+ const keys = [{ name: "key-1" }, { name: "key-2" }, { name: "key-3" }];
802
+ mockKeyListRequest("bound-id", keys);
803
+
804
+ await runWrangler("kv:key list --binding someBinding");
805
+ expect(std.err).toMatchInlineSnapshot(`""`);
806
+ expect(std.out).toMatchInlineSnapshot(`
807
+ "[
808
+ {
809
+ \\"name\\": \\"key-1\\"
810
+ },
811
+ {
812
+ \\"name\\": \\"key-2\\"
813
+ },
814
+ {
815
+ \\"name\\": \\"key-3\\"
816
+ }
817
+ ]"
818
+ `);
819
+ });
820
+
821
+ it("should list the keys of a preview namespace specified by binding", async () => {
822
+ writeWranglerConfig();
823
+ const keys = [{ name: "key-1" }, { name: "key-2" }, { name: "key-3" }];
824
+ mockKeyListRequest("preview-bound-id", keys);
825
+ await runWrangler("kv:key list --binding someBinding --preview");
826
+ expect(std.err).toMatchInlineSnapshot(`""`);
827
+ expect(std.out).toMatchInlineSnapshot(`
828
+ "[
829
+ {
830
+ \\"name\\": \\"key-1\\"
831
+ },
832
+ {
833
+ \\"name\\": \\"key-2\\"
834
+ },
835
+ {
836
+ \\"name\\": \\"key-3\\"
837
+ }
838
+ ]"
839
+ `);
840
+ });
841
+
842
+ it("should list the keys of a namespace specified by binding, in a given environment", async () => {
843
+ writeWranglerConfig();
844
+ const keys = [{ name: "key-1" }, { name: "key-2" }, { name: "key-3" }];
845
+ mockKeyListRequest("env-bound-id", keys);
846
+ await runWrangler(
847
+ "kv:key list --binding someBinding --env some-environment"
848
+ );
849
+ expect(std.err).toMatchInlineSnapshot(`""`);
850
+ expect(std.out).toMatchInlineSnapshot(`
851
+ "[
852
+ {
853
+ \\"name\\": \\"key-1\\"
854
+ },
855
+ {
856
+ \\"name\\": \\"key-2\\"
857
+ },
858
+ {
859
+ \\"name\\": \\"key-3\\"
860
+ }
861
+ ]"
862
+ `);
863
+ });
864
+
865
+ it("should list the keys of a preview namespace specified by binding, in a given environment", async () => {
866
+ writeWranglerConfig();
867
+ const keys = [{ name: "key-1" }, { name: "key-2" }, { name: "key-3" }];
868
+ mockKeyListRequest("preview-env-bound-id", keys);
869
+ await runWrangler(
870
+ "kv:key list --binding someBinding --preview --env some-environment"
871
+ );
872
+ expect(std.err).toMatchInlineSnapshot(`""`);
873
+ expect(std.out).toMatchInlineSnapshot(`
874
+ "[
875
+ {
876
+ \\"name\\": \\"key-1\\"
877
+ },
878
+ {
879
+ \\"name\\": \\"key-2\\"
880
+ },
881
+ {
882
+ \\"name\\": \\"key-3\\"
883
+ }
884
+ ]"
885
+ `);
886
+ });
887
+
888
+ // We'll run the next test with variations on the cursor
889
+ // that's returned on cloudflare's API after all results
890
+ // have been drained.
891
+ for (const blankCursorValue of [undefined, null, ""] as [
892
+ undefined,
893
+ null,
894
+ ""
895
+ ]) {
896
+ describe(`cursor - ${blankCursorValue}`, () => {
897
+ it("should make multiple requests for paginated results", async () => {
898
+ // Create a lot of mock keys, so that the fetch requests will be paginated
899
+ const keys: NamespaceKeyInfo[] = [];
900
+ for (let i = 0; i < 550; i++) {
901
+ keys.push({ name: "key-" + i });
902
+ }
903
+ // Ask for the keys in pages of size 100.
904
+ const requests = mockKeyListRequest(
905
+ "some-namespace-id",
906
+ keys,
907
+ 100,
908
+ blankCursorValue
909
+ );
910
+ await runWrangler("kv:key list --namespace-id some-namespace-id");
911
+ expect(std.err).toMatchInlineSnapshot(`""`);
912
+ expect(JSON.parse(std.out)).toEqual(keys);
913
+ expect(requests.count).toEqual(6);
914
+ });
915
+ });
916
+ }
917
+
918
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
919
+ writeWranglerConfig();
920
+ await expect(
921
+ runWrangler("kv:key list --binding otherBinding")
922
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
923
+ `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
924
+ );
925
+ expect(std.err).toMatchInlineSnapshot(`
926
+ "X [ERROR] A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
927
+
928
+ "
929
+ `);
930
+ expect(std.out).toMatchInlineSnapshot(`
931
+ "
932
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
933
+ `);
934
+ });
935
+ });
936
+
937
+ describe("get", () => {
938
+ it("should get a key in a given namespace specified by namespace-id", async () => {
939
+ setMockFetchKVGetValue(
940
+ "some-account-id",
941
+ "some-namespace-id",
942
+ "my-key",
943
+ "my-value"
944
+ );
945
+
946
+ await runWrangler("kv:key get my-key --namespace-id some-namespace-id");
947
+
948
+ expect(proc.write).toEqual(Buffer.from("my-value"));
949
+ expect(std.err).toMatchInlineSnapshot(`""`);
950
+ });
951
+
952
+ it("should get a key and decode the value from the response as a utf8 string if the `--text` flag is passed", async () => {
953
+ setMockFetchKVGetValue(
954
+ "some-account-id",
955
+ "some-namespace-id",
956
+ "my-key",
957
+ "my-value"
958
+ );
959
+ await runWrangler(
960
+ "kv:key get my-key --text --namespace-id some-namespace-id"
961
+ );
962
+ expect(proc.write).not.toEqual(Buffer.from("my-value"));
963
+ expect(std).toMatchInlineSnapshot(`
964
+ Object {
965
+ "debug": "",
966
+ "err": "",
967
+ "out": "my-value",
968
+ "warn": "",
969
+ }
970
+ `);
971
+ });
972
+
973
+ it("should get a binary and decode as utf8 text, resulting in improper decoding", async () => {
974
+ const buf = Buffer.from(
975
+ "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAiSURBVHgB7coxEQAACMPAgH/PgAM6dGwu49fA/deIBXrgAj2cAhIFT4QxAAAAAElFTkSuQmCC",
976
+ "base64"
977
+ );
978
+ setMockFetchKVGetValue(
979
+ "some-account-id",
980
+ "some-namespace-id",
981
+ "my-key",
982
+ buf
983
+ );
984
+ await runWrangler(
985
+ "kv:key get my-key --text --namespace-id some-namespace-id"
986
+ );
987
+ expect(proc.write).not.toEqual(buf);
988
+ expect(JSON.stringify(std)).toMatchInlineSnapshot(
989
+ `"{\\"debug\\":\\"\\",\\"out\\":\\"�PNG\\\\n\\\\u001a\\\\n\\\\u0000\\\\u0000\\\\u0000\\\\rIHDR\\\\u0000\\\\u0000\\\\u0000\\\\n\\\\u0000\\\\u0000\\\\u0000\\\\n\\\\b\\\\u0006\\\\u0000\\\\u0000\\\\u0000�2Ͻ\\\\u0000\\\\u0000\\\\u0000\\\\tpHYs\\\\u0000\\\\u0000\\\\u000b\\\\u0013\\\\u0000\\\\u0000\\\\u000b\\\\u0013\\\\u0001\\\\u0000��\\\\u0018\\\\u0000\\\\u0000\\\\u0000\\\\u0001sRGB\\\\u0000��\\\\u001c�\\\\u0000\\\\u0000\\\\u0000\\\\u0004gAMA\\\\u0000\\\\u0000��\\\\u000b�a\\\\u0005\\\\u0000\\\\u0000\\\\u0000\\\\\\"IDATx\\\\u0001��1\\\\u0011\\\\u0000\\\\u0000\\\\b���π\\\\u0003:tl.����׈\\\\u0005z�\\\\u0002=�\\\\u0002\\\\u0012\\\\u0005O�1\\\\u0000\\\\u0000\\\\u0000\\\\u0000IEND�B\`�\\",\\"err\\":\\"\\",\\"warn\\":\\"\\"}"`
990
+ );
991
+ });
992
+
993
+ it("should get a binary file by key in a given namespace specified by namespace-id", async () => {
994
+ const buf = Buffer.from(
995
+ "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAiSURBVHgB7coxEQAACMPAgH/PgAM6dGwu49fA/deIBXrgAj2cAhIFT4QxAAAAAElFTkSuQmCC",
996
+ "base64"
997
+ );
998
+ setMockFetchKVGetValue(
999
+ "some-account-id",
1000
+ "some-namespace-id",
1001
+ "my-key",
1002
+ buf
1003
+ );
1004
+ await runWrangler("kv:key get my-key --namespace-id some-namespace-id");
1005
+ expect(proc.write).toEqual(buf);
1006
+ expect(std.err).toMatchInlineSnapshot(`""`);
1007
+ });
1008
+
1009
+ it("should get a key in a given namespace specified by binding", async () => {
1010
+ writeWranglerConfig();
1011
+ setMockFetchKVGetValue(
1012
+ "some-account-id",
1013
+ "bound-id",
1014
+ "my-key",
1015
+ "my-value"
1016
+ );
1017
+ await runWrangler(
1018
+ "kv:key get my-key --binding someBinding --preview false"
1019
+ );
1020
+ expect(proc.write).toEqual(Buffer.from("my-value"));
1021
+ expect(std.err).toMatchInlineSnapshot(`""`);
1022
+ });
1023
+
1024
+ it("should get a key in a given preview namespace specified by binding", async () => {
1025
+ writeWranglerConfig();
1026
+ setMockFetchKVGetValue(
1027
+ "some-account-id",
1028
+ "preview-bound-id",
1029
+ "my-key",
1030
+ "my-value"
1031
+ );
1032
+ await runWrangler("kv:key get my-key --binding someBinding --preview");
1033
+ expect(proc.write).toEqual(Buffer.from("my-value"));
1034
+ expect(std.err).toMatchInlineSnapshot(`""`);
1035
+ });
1036
+
1037
+ it("should get a key for the specified environment in a given namespace", async () => {
1038
+ writeWranglerConfig();
1039
+ setMockFetchKVGetValue(
1040
+ "some-account-id",
1041
+ "env-bound-id",
1042
+ "my-key",
1043
+ "my-value"
1044
+ );
1045
+ await runWrangler(
1046
+ "kv:key get my-key --binding someBinding --env some-environment --preview false"
1047
+ );
1048
+ expect(proc.write).toEqual(Buffer.from("my-value"));
1049
+ expect(std.err).toMatchInlineSnapshot(`""`);
1050
+ });
1051
+
1052
+ it("should encode the key in the api request to get a value", async () => {
1053
+ setMockFetchKVGetValue(
1054
+ "some-account-id",
1055
+ "some-namespace-id",
1056
+ "%2Fmy%2Ckey", // expect the key /my,key to be encoded
1057
+ "my-value"
1058
+ );
1059
+
1060
+ await runWrangler(
1061
+ "kv:key get /my,key --namespace-id some-namespace-id"
1062
+ );
1063
+ expect(proc.write).toEqual(Buffer.from("my-value"));
1064
+ expect(std.err).toMatchInlineSnapshot(`""`);
1065
+ });
1066
+
1067
+ it("should error if no key is provided", async () => {
1068
+ await expect(
1069
+ runWrangler("kv:key get")
1070
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1071
+ `"Not enough non-option arguments: got 0, need at least 1"`
1072
+ );
1073
+ expect(std.out).toMatchInlineSnapshot(`
1074
+ "
1075
+ wrangler kv:key get <key>
1076
+
1077
+ Reads a single value by key from the given namespace.
1078
+
1079
+ Positionals:
1080
+ key The key value to get. [string] [required]
1081
+
1082
+ Flags:
1083
+ -c, --config Path to .toml configuration file [string]
1084
+ -e, --env Environment to use for operations and .env files [string]
1085
+ -h, --help Show help [boolean]
1086
+ -v, --version Show version number [boolean]
1087
+
1088
+ Options:
1089
+ --binding The name of the namespace to get from [string]
1090
+ --namespace-id The id of the namespace to get from [string]
1091
+ --preview Interact with a preview namespace [boolean] [default: false]
1092
+ --text Decode the returned value as a utf8 string [boolean] [default: false]"
1093
+ `);
1094
+ expect(std.err).toMatchInlineSnapshot(`
1095
+ "X [ERROR] Not enough non-option arguments: got 0, need at least 1
1096
+
1097
+ "
1098
+ `);
1099
+ });
1100
+
1101
+ it("should error if no binding nor namespace is provided", async () => {
1102
+ await expect(
1103
+ runWrangler("kv:key get foo")
1104
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1105
+ `"Exactly one of the arguments binding and namespace-id is required"`
1106
+ );
1107
+ expect(std.out).toMatchInlineSnapshot(`
1108
+ "
1109
+ wrangler kv:key get <key>
1110
+
1111
+ Reads a single value by key from the given namespace.
1112
+
1113
+ Positionals:
1114
+ key The key value to get. [string] [required]
1115
+
1116
+ Flags:
1117
+ -c, --config Path to .toml configuration file [string]
1118
+ -e, --env Environment to use for operations and .env files [string]
1119
+ -h, --help Show help [boolean]
1120
+ -v, --version Show version number [boolean]
1121
+
1122
+ Options:
1123
+ --binding The name of the namespace to get from [string]
1124
+ --namespace-id The id of the namespace to get from [string]
1125
+ --preview Interact with a preview namespace [boolean] [default: false]
1126
+ --text Decode the returned value as a utf8 string [boolean] [default: false]"
1127
+ `);
1128
+ expect(std.err).toMatchInlineSnapshot(`
1129
+ "X [ERROR] Exactly one of the arguments binding and namespace-id is required
1130
+
1131
+ "
1132
+ `);
1133
+ });
1134
+
1135
+ it("should error if both binding and namespace is provided", async () => {
1136
+ await expect(
1137
+ runWrangler("kv:key get foo --binding x --namespace-id y")
1138
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1139
+ `"Arguments binding and namespace-id are mutually exclusive"`
1140
+ );
1141
+
1142
+ expect(std.out).toMatchInlineSnapshot(`
1143
+ "
1144
+ wrangler kv:key get <key>
1145
+
1146
+ Reads a single value by key from the given namespace.
1147
+
1148
+ Positionals:
1149
+ key The key value to get. [string] [required]
1150
+
1151
+ Flags:
1152
+ -c, --config Path to .toml configuration file [string]
1153
+ -e, --env Environment to use for operations and .env files [string]
1154
+ -h, --help Show help [boolean]
1155
+ -v, --version Show version number [boolean]
1156
+
1157
+ Options:
1158
+ --binding The name of the namespace to get from [string]
1159
+ --namespace-id The id of the namespace to get from [string]
1160
+ --preview Interact with a preview namespace [boolean] [default: false]
1161
+ --text Decode the returned value as a utf8 string [boolean] [default: false]"
1162
+ `);
1163
+ expect(std.err).toMatchInlineSnapshot(`
1164
+ "X [ERROR] Arguments binding and namespace-id are mutually exclusive
1165
+
1166
+ "
1167
+ `);
1168
+ });
1169
+
1170
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
1171
+ writeWranglerConfig();
1172
+ await expect(
1173
+ runWrangler("kv:key get key --binding otherBinding")
1174
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1175
+ `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
1176
+ );
1177
+ expect(std.out).toMatchInlineSnapshot(`
1178
+ "
1179
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1180
+ `);
1181
+ expect(std.err).toMatchInlineSnapshot(`
1182
+ "X [ERROR] A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
1183
+
1184
+ "
1185
+ `);
1186
+ });
1187
+
1188
+ describe("non-interactive", () => {
1189
+ const { setIsTTY } = useMockIsTTY();
1190
+ mockAccountId({ accountId: null });
1191
+
1192
+ it("should error if there are multiple accounts available but not interactive on stdin", async () => {
1193
+ mockGetMemberships([
1194
+ { id: "xxx", account: { id: "1", name: "one" } },
1195
+ { id: "yyy", account: { id: "2", name: "two" } },
1196
+ ]);
1197
+ setIsTTY({ stdin: false, stdout: true });
1198
+ await expect(runWrangler("kv:key get key --namespace-id=xxxx"))
1199
+ .rejects.toThrowErrorMatchingInlineSnapshot(`
1200
+ "More than one account available but unable to select one in non-interactive mode.
1201
+ Please set the appropriate \`account_id\` in your \`wrangler.toml\` file.
1202
+ Available accounts are (\\"<name>\\" - \\"<id>\\"):
1203
+ \\"one\\" - \\"1\\")
1204
+ \\"two\\" - \\"2\\")"
1205
+ `);
1206
+ });
1207
+
1208
+ it("should error if there are multiple accounts available but not interactive on stdout", async () => {
1209
+ mockGetMemberships([
1210
+ { id: "xxx", account: { id: "1", name: "one" } },
1211
+ { id: "yyy", account: { id: "2", name: "two" } },
1212
+ ]);
1213
+ setIsTTY({ stdin: true, stdout: false });
1214
+ await expect(runWrangler("kv:key get key --namespace-id=xxxx"))
1215
+ .rejects.toThrowErrorMatchingInlineSnapshot(`
1216
+ "More than one account available but unable to select one in non-interactive mode.
1217
+ Please set the appropriate \`account_id\` in your \`wrangler.toml\` file.
1218
+ Available accounts are (\\"<name>\\" - \\"<id>\\"):
1219
+ \\"one\\" - \\"1\\")
1220
+ \\"two\\" - \\"2\\")"
1221
+ `);
1222
+ });
1223
+
1224
+ it("should recommend using a configuration if unable to fetch memberships", async () => {
1225
+ msw.use(
1226
+ rest.get("*/memberships", (req, res, ctx) => {
1227
+ return res.once(
1228
+ ctx.status(200),
1229
+ ctx.json(
1230
+ createFetchResult(null, false, [
1231
+ {
1232
+ code: 9109,
1233
+ message: "Uauthorized to access requested resource",
1234
+ },
1235
+ ])
1236
+ )
1237
+ );
1238
+ })
1239
+ );
1240
+ await expect(runWrangler("kv:key get key --namespace-id=xxxx"))
1241
+ .rejects.toThrowErrorMatchingInlineSnapshot(`
1242
+ "Failed to automatically retrieve account IDs for the logged in user.
1243
+ You may have incorrect permissions on your API token. You can skip this account check by adding an \`account_id\` in your \`wrangler.toml\`, or by setting the value of CLOUDFLARE_ACCOUNT_ID\\""
1244
+ `);
1245
+ });
1246
+
1247
+ it("should error if there are multiple accounts available but not interactive at all", async () => {
1248
+ mockGetMemberships([
1249
+ { id: "xxx", account: { id: "1", name: "one" } },
1250
+ { id: "yyy", account: { id: "2", name: "two" } },
1251
+ ]);
1252
+ setIsTTY(false);
1253
+ await expect(runWrangler("kv:key get key --namespace-id=xxxx"))
1254
+ .rejects.toThrowErrorMatchingInlineSnapshot(`
1255
+ "More than one account available but unable to select one in non-interactive mode.
1256
+ Please set the appropriate \`account_id\` in your \`wrangler.toml\` file.
1257
+ Available accounts are (\\"<name>\\" - \\"<id>\\"):
1258
+ \\"one\\" - \\"1\\")
1259
+ \\"two\\" - \\"2\\")"
1260
+ `);
1261
+ });
1262
+ });
1263
+ });
1264
+
1265
+ describe("delete", () => {
1266
+ function mockDeleteRequest(
1267
+ expectedNamespaceId: string,
1268
+ expectedKey: string
1269
+ ) {
1270
+ const requests = { count: 0 };
1271
+ msw.use(
1272
+ rest.delete(
1273
+ "*/accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key",
1274
+ (req, res, ctx) => {
1275
+ requests.count++;
1276
+ expect(req.params.accountId).toEqual("some-account-id");
1277
+ expect(req.params.namespaceId).toEqual(expectedNamespaceId);
1278
+ expect(req.params.key).toEqual(expectedKey);
1279
+ return res.once(
1280
+ ctx.status(200),
1281
+ ctx.json(createFetchResult(null))
1282
+ );
1283
+ }
1284
+ )
1285
+ );
1286
+ return requests;
1287
+ }
1288
+
1289
+ it("should delete a key in a namespace specified by id", async () => {
1290
+ const requests = mockDeleteRequest("some-namespace-id", "someKey");
1291
+ await runWrangler(
1292
+ `kv:key delete --namespace-id some-namespace-id someKey`
1293
+ );
1294
+ expect(requests.count).toEqual(1);
1295
+ });
1296
+
1297
+ it("should encode the key in the api request to delete a value", async () => {
1298
+ const requests = mockDeleteRequest("voyager", "/NCC-74656");
1299
+ await runWrangler(`kv:key delete --namespace-id voyager /NCC-74656`);
1300
+
1301
+ expect(requests.count).toEqual(1);
1302
+ expect(std.out).toMatchInlineSnapshot(
1303
+ `"Deleting the key \\"/NCC-74656\\" on namespace voyager."`
1304
+ );
1305
+ expect(std.err).toMatchInlineSnapshot(`""`);
1306
+ });
1307
+
1308
+ it("should delete a key in a namespace specified by binding name", async () => {
1309
+ writeWranglerConfig();
1310
+ const requests = mockDeleteRequest("bound-id", "someKey");
1311
+ await runWrangler(
1312
+ `kv:key delete --binding someBinding --preview false someKey`
1313
+ );
1314
+ expect(requests.count).toEqual(1);
1315
+ });
1316
+
1317
+ it("should delete a key in a preview namespace specified by binding name", async () => {
1318
+ writeWranglerConfig();
1319
+ const requests = mockDeleteRequest("preview-bound-id", "someKey");
1320
+ await runWrangler(
1321
+ `kv:key delete --binding someBinding --preview someKey`
1322
+ );
1323
+ expect(requests.count).toEqual(1);
1324
+ });
1325
+
1326
+ it("should error if a given binding name is not in the configured kv namespaces", async () => {
1327
+ writeWranglerConfig();
1328
+ await expect(
1329
+ runWrangler(`kv:key delete --binding otherBinding someKey`)
1330
+ ).rejects.toThrowErrorMatchingInlineSnapshot(
1331
+ `"A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\"."`
1332
+ );
1333
+
1334
+ expect(std.err).toMatchInlineSnapshot(`
1335
+ "X [ERROR] A namespace with binding name \\"otherBinding\\" was not found in the configured \\"kv_namespaces\\".
1336
+
1337
+ "
1338
+ `);
1339
+ });
1340
+
1341
+ it("should delete a key in a namespace specified by binding name in a given environment", async () => {
1342
+ writeWranglerConfig();
1343
+ const requests = mockDeleteRequest("env-bound-id", "someKey");
1344
+ await runWrangler(
1345
+ `kv:key delete --binding someBinding --env some-environment --preview false someKey`
1346
+ );
1347
+ expect(std.out).toMatchInlineSnapshot(
1348
+ `"Deleting the key \\"someKey\\" on namespace env-bound-id."`
1349
+ );
1350
+ expect(std.err).toMatchInlineSnapshot(`""`);
1351
+ expect(requests.count).toEqual(1);
1352
+ });
1353
+
1354
+ it("should delete a key in a preview namespace specified by binding name in a given environment", async () => {
1355
+ writeWranglerConfig();
1356
+ const requests = mockDeleteRequest("preview-env-bound-id", "someKey");
1357
+ await runWrangler(
1358
+ `kv:key delete --binding someBinding --env some-environment --preview someKey`
1359
+ );
1360
+ expect(requests.count).toEqual(1);
1361
+ });
1362
+ });
1363
+ });
1364
+
1365
+ describe("kv:bulk", () => {
1366
+ describe("put", () => {
1367
+ function mockPutRequest(
1368
+ expectedNamespaceId: string,
1369
+ expectedKeyValues: KeyValue[]
1370
+ ) {
1371
+ const requests = { count: 0 };
1372
+ msw.use(
1373
+ rest.put(
1374
+ "*/accounts/:accountId/storage/kv/namespaces/:namespaceId/bulk",
1375
+ async (req, res, ctx) => {
1376
+ requests.count++;
1377
+ expect(req.params.accountId).toEqual("some-account-id");
1378
+ expect(req.params.namespaceId).toEqual(expectedNamespaceId);
1379
+ expect(await req.json()).toEqual(
1380
+ expectedKeyValues.slice(
1381
+ (requests.count - 1) * 5000,
1382
+ requests.count * 5000
1383
+ )
1384
+ );
1385
+ return res(ctx.status(200), ctx.json(createFetchResult(null)));
1386
+ }
1387
+ )
1388
+ );
1389
+ return requests;
1390
+ }
1391
+
1392
+ it("should put the key-values parsed from a file", async () => {
1393
+ const keyValues: KeyValue[] = [
1394
+ { key: "someKey1", value: "someValue1" },
1395
+ { key: "ns:someKey2", value: "123", base64: true },
1396
+ { key: "someKey3", value: "someValue3", expiration: 100 },
1397
+ { key: "someKey4", value: "someValue4", expiration_ttl: 500 },
1398
+ ];
1399
+ writeFileSync("./keys.json", JSON.stringify(keyValues));
1400
+ const requests = mockPutRequest("some-namespace-id", keyValues);
1401
+ await runWrangler(
1402
+ `kv:bulk put --namespace-id some-namespace-id keys.json`
1403
+ );
1404
+ expect(requests.count).toEqual(1);
1405
+ expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1406
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1407
+ expect(std.err).toMatchInlineSnapshot(`""`);
1408
+ });
1409
+
1410
+ it("should put the key-values in batches of 5000 parsed from a file", async () => {
1411
+ const keyValues: KeyValue[] = new Array(12000).fill({
1412
+ key: "someKey1",
1413
+ value: "someValue1",
1414
+ });
1415
+ writeFileSync("./keys.json", JSON.stringify(keyValues));
1416
+ const requests = mockPutRequest("some-namespace-id", keyValues);
1417
+ await runWrangler(
1418
+ `kv:bulk put --namespace-id some-namespace-id keys.json`
1419
+ );
1420
+ expect(requests.count).toEqual(3);
1421
+ expect(std.out).toMatchInlineSnapshot(`
1422
+ "Uploaded 0% (0 out of 12,000)
1423
+ Uploaded 41% (5,000 out of 12,000)
1424
+ Uploaded 83% (10,000 out of 12,000)
1425
+ Uploaded 100% (12,000 out of 12,000)
1426
+ Success!"
1427
+ `);
1428
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1429
+ expect(std.err).toMatchInlineSnapshot(`""`);
1430
+ });
1431
+
1432
+ it("should error if the file is not a JSON array", async () => {
1433
+ const keyValues = { key: "someKey1", value: "someValue1" };
1434
+ writeFileSync("./keys.json", JSON.stringify(keyValues));
1435
+ await expect(
1436
+ runWrangler(`kv:bulk put --namespace-id some-namespace-id keys.json`)
1437
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`
1438
+ "Unexpected JSON input from \\"keys.json\\".
1439
+ Expected an array of key-value objects but got type \\"object\\"."
1440
+ `);
1441
+ expect(std.out).toMatchInlineSnapshot(`
1442
+ "
1443
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1444
+ `);
1445
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1446
+ });
1447
+
1448
+ it("should error if the array contains items that are not key-value objects", async () => {
1449
+ const keyValues = [
1450
+ 123,
1451
+ "a string",
1452
+ { key: "someKey" },
1453
+ { value: "someValue" },
1454
+ // add a valid object here to make sure it's not included
1455
+ { key: "someKey1", value: "someValue1" },
1456
+ // this one will only add a warning
1457
+ { key: "someKey1", value: "someValue1", invalid: true },
1458
+ // back to the invalid ones
1459
+ { key: 123, value: "somevalue" },
1460
+ { key: "somekey", value: 123 },
1461
+ { key: "someKey1", value: "someValue1", expiration: "string" },
1462
+ { key: "someKey1", value: "someValue1", expiration_ttl: "string" },
1463
+ {
1464
+ key: 123,
1465
+ value: {
1466
+ a: {
1467
+ nested: "object",
1468
+ },
1469
+ },
1470
+ },
1471
+ { key: "someKey1", value: "someValue1", metadata: 123 },
1472
+ { key: "someKey1", value: "someValue1", base64: "string" },
1473
+ ];
1474
+ writeFileSync("./keys.json", JSON.stringify(keyValues));
1475
+ await expect(
1476
+ runWrangler(`kv:bulk put --namespace-id some-namespace-id keys.json`)
1477
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`
1478
+ "Unexpected JSON input from \\"keys.json\\".
1479
+ Each item in the array should be an object that matches:
1480
+
1481
+ interface KeyValue {
1482
+ key: string;
1483
+ value: string;
1484
+ expiration?: number;
1485
+ expiration_ttl?: number;
1486
+ metadata?: object;
1487
+ base64?: boolean;
1488
+ }
1489
+
1490
+ The item at index 0 is 123
1491
+ The item at index 1 is \\"a string\\"
1492
+ The item at index 2 is {\\"key\\":\\"someKey\\"}
1493
+ The item at index 3 is {\\"value\\":\\"someValue\\"}
1494
+ The item at index 6 is {\\"key\\":123,\\"value\\":\\"somevalue\\"}
1495
+ The item at index 7 is {\\"key\\":\\"somekey\\",\\"value\\":123}
1496
+ The item at index 8 is {\\"key\\":\\"someKey1\\",\\"value\\":\\"someValue1\\",\\"expiration\\":\\"string\\"}
1497
+ The item at index 9 is {\\"key\\":\\"someKey1\\",\\"value\\":\\"someValue1\\",\\"expiration_ttl\\":\\"string\\"}
1498
+ The item at index 10 is {\\"key\\":123,\\"value\\":{\\"a\\":{\\"nested\\":\\"object\\"}}}
1499
+ The item at index 11 is {\\"key\\":\\"someKey1\\",\\"value\\":\\"someValue1\\",\\"metadata\\":123}
1500
+ The item at index 12 is {\\"key\\":\\"someKey1\\",\\"value\\":\\"someValue1\\",\\"base64\\":\\"string\\"}"
1501
+ `);
1502
+
1503
+ expect(std.out).toMatchInlineSnapshot(`
1504
+ "
1505
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1506
+ `);
1507
+ expect(std.warn).toMatchInlineSnapshot(`
1508
+ "▲ [WARNING] Unexpected key-value properties in \\"keys.json\\".
1509
+
1510
+ The item at index 5 contains unexpected properties: [\\"invalid\\"].
1511
+
1512
+ "
1513
+ `);
1514
+ });
1515
+ });
1516
+
1517
+ describe("delete", () => {
1518
+ function mockDeleteRequest(
1519
+ expectedNamespaceId: string,
1520
+ expectedKeys: string[]
1521
+ ) {
1522
+ const requests = { count: 0 };
1523
+ msw.use(
1524
+ rest.delete(
1525
+ "*/accounts/:accountId/storage/kv/namespaces/:namespaceId/bulk",
1526
+ async (req, res, ctx) => {
1527
+ requests.count++;
1528
+ expect(req.params.accountId).toEqual("some-account-id");
1529
+ expect(req.params.namespaceId).toEqual(expectedNamespaceId);
1530
+ expect(req.headers.get("Content-Type")).toEqual(
1531
+ "application/json"
1532
+ );
1533
+ expect(await req.json()).toEqual(
1534
+ expectedKeys.slice(
1535
+ (requests.count - 1) * 5000,
1536
+ requests.count * 5000
1537
+ )
1538
+ );
1539
+ return res(ctx.status(200), ctx.json(createFetchResult(null)));
1540
+ }
1541
+ )
1542
+ );
1543
+ return requests;
1544
+ }
1545
+
1546
+ it("should delete the keys parsed from a file", async () => {
1547
+ const keys = ["someKey1", "ns:someKey2"];
1548
+ writeFileSync("./keys.json", JSON.stringify(keys));
1549
+ mockConfirm({
1550
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1551
+ result: true,
1552
+ });
1553
+ const requests = mockDeleteRequest("some-namespace-id", keys);
1554
+ await runWrangler(
1555
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1556
+ );
1557
+ expect(requests.count).toEqual(1);
1558
+ expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1559
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1560
+ expect(std.err).toMatchInlineSnapshot(`""`);
1561
+ });
1562
+
1563
+ it("should delete the keys in batches of 5000 parsed from a file", async () => {
1564
+ const keys = new Array(12000).fill("some-key");
1565
+ writeFileSync("./keys.json", JSON.stringify(keys));
1566
+ mockConfirm({
1567
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1568
+ result: true,
1569
+ });
1570
+ const requests = mockDeleteRequest("some-namespace-id", keys);
1571
+ await runWrangler(
1572
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1573
+ );
1574
+ expect(requests.count).toEqual(3);
1575
+ expect(std.out).toMatchInlineSnapshot(`
1576
+ "Deleted 0% (0 out of 12,000)
1577
+ Deleted 41% (5,000 out of 12,000)
1578
+ Deleted 83% (10,000 out of 12,000)
1579
+ Deleted 100% (12,000 out of 12,000)
1580
+ Success!"
1581
+ `);
1582
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1583
+ expect(std.err).toMatchInlineSnapshot(`""`);
1584
+ });
1585
+
1586
+ it("should not delete the keys if the user confirms no", async () => {
1587
+ const keys = ["someKey1", "ns:someKey2"];
1588
+ writeFileSync("./keys.json", JSON.stringify(keys));
1589
+ mockConfirm({
1590
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1591
+ result: false,
1592
+ });
1593
+ await runWrangler(
1594
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1595
+ );
1596
+ expect(std.out).toMatchInlineSnapshot(
1597
+ `"Not deleting keys read from \\"keys.json\\"."`
1598
+ );
1599
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1600
+ expect(std.err).toMatchInlineSnapshot(`""`);
1601
+ });
1602
+
1603
+ it("should delete the keys without asking if --force is provided", async () => {
1604
+ const keys = ["someKey1", "ns:someKey2"];
1605
+ writeFileSync("./keys.json", JSON.stringify(keys));
1606
+ const requests = mockDeleteRequest("some-namespace-id", keys);
1607
+ await runWrangler(
1608
+ `kv:bulk delete --namespace-id some-namespace-id keys.json --force`
1609
+ );
1610
+ expect(requests.count).toEqual(1);
1611
+ expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1612
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1613
+ expect(std.err).toMatchInlineSnapshot(`""`);
1614
+ });
1615
+
1616
+ it("should delete the keys without asking if -f is provided", async () => {
1617
+ const keys = ["someKey1", "ns:someKey2"];
1618
+ writeFileSync("./keys.json", JSON.stringify(keys));
1619
+ const requests = mockDeleteRequest("some-namespace-id", keys);
1620
+ await runWrangler(
1621
+ `kv:bulk delete --namespace-id some-namespace-id keys.json -f`
1622
+ );
1623
+ expect(requests.count).toEqual(1);
1624
+ expect(std.out).toMatchInlineSnapshot(`"Success!"`);
1625
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1626
+ expect(std.err).toMatchInlineSnapshot(`""`);
1627
+ });
1628
+
1629
+ it("should error if the file is not a JSON array", async () => {
1630
+ const keys = 12354;
1631
+ writeFileSync("./keys.json", JSON.stringify(keys));
1632
+ mockConfirm({
1633
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1634
+ result: true,
1635
+ });
1636
+ await expect(
1637
+ runWrangler(
1638
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1639
+ )
1640
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`
1641
+ "Unexpected JSON input from \\"keys.json\\".
1642
+ Expected an array of strings but got:
1643
+ 12354"
1644
+ `);
1645
+ expect(std.out).toMatchInlineSnapshot(`
1646
+ "
1647
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1648
+ `);
1649
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1650
+ });
1651
+
1652
+ it("should error if the file contains non-string items", async () => {
1653
+ const keys = ["good", 12354, { key: "someKey" }, null];
1654
+ writeFileSync("./keys.json", JSON.stringify(keys));
1655
+ mockConfirm({
1656
+ text: `Are you sure you want to delete all the keys read from "keys.json" from kv-namespace with id "some-namespace-id"?`,
1657
+ result: true,
1658
+ });
1659
+ await expect(
1660
+ runWrangler(
1661
+ `kv:bulk delete --namespace-id some-namespace-id keys.json`
1662
+ )
1663
+ ).rejects.toThrowErrorMatchingInlineSnapshot(`
1664
+ "Unexpected JSON input from \\"keys.json\\".
1665
+ Expected an array of strings.
1666
+ The item at index 1 is type: \\"number\\" - 12354
1667
+ The item at index 2 is type: \\"object\\" - {\\"key\\":\\"someKey\\"}
1668
+ The item at index 3 is type: \\"object\\" - null"
1669
+ `);
1670
+ expect(std.out).toMatchInlineSnapshot(`
1671
+ "
1672
+ If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new/choose"
1673
+ `);
1674
+ expect(std.warn).toMatchInlineSnapshot(`""`);
1675
+ });
1676
+ });
1677
+ });
1502
1678
  });
1503
1679
 
1504
1680
  function writeWranglerConfig() {
1505
- writeFileSync(
1506
- "./wrangler.toml",
1507
- [
1508
- 'name = "other-worker"',
1509
- "kv_namespaces = [",
1510
- ' { binding = "someBinding", id = "bound-id", preview_id = "preview-bound-id" }',
1511
- "]",
1512
- "",
1513
- "[env.some-environment]",
1514
- "kv_namespaces = [",
1515
- ' { binding = "someBinding", id = "env-bound-id", preview_id = "preview-env-bound-id" }',
1516
- "]",
1517
- ].join("\n"),
1518
- "utf-8"
1519
- );
1681
+ writeFileSync(
1682
+ "./wrangler.toml",
1683
+ [
1684
+ 'name = "other-worker"',
1685
+ "kv_namespaces = [",
1686
+ ' { binding = "someBinding", id = "bound-id", preview_id = "preview-bound-id" }',
1687
+ "]",
1688
+ "",
1689
+ "[env.some-environment]",
1690
+ "kv_namespaces = [",
1691
+ ' { binding = "someBinding", id = "env-bound-id", preview_id = "preview-env-bound-id" }',
1692
+ "]",
1693
+ ].join("\n"),
1694
+ "utf-8"
1695
+ );
1696
+ }
1697
+
1698
+ function setMockFetchKVGetValue(
1699
+ accountId: string,
1700
+ namespaceId: string,
1701
+ key: string,
1702
+ value: string | Buffer
1703
+ ) {
1704
+ msw.use(
1705
+ rest.get(
1706
+ "*/accounts/:accountId/storage/kv/namespaces/:namespaceId/values/:key",
1707
+ (req, res, ctx) => {
1708
+ console.dir(req.params);
1709
+ expect(req.params.accountId).toEqual(accountId);
1710
+ expect(req.params.namespaceId).toEqual(namespaceId);
1711
+ // Getting the key from params decodes it so we need to grab the encoded key from the URL
1712
+ expect(req.url.toString().split("/").pop()).toBe(key);
1713
+
1714
+ return res.once(ctx.status(200), ctx.body(value));
1715
+ }
1716
+ )
1717
+ );
1718
+ }
1719
+
1720
+ function createFetchResult(
1721
+ result: unknown,
1722
+ success = true,
1723
+ errors: { code: number; message: string }[] = []
1724
+ ) {
1725
+ return {
1726
+ success,
1727
+ errors,
1728
+ messages: [],
1729
+ result,
1730
+ };
1731
+ }
1732
+
1733
+ function mockGetMemberships(
1734
+ accounts: { id: string; account: { id: string; name: string } }[]
1735
+ ) {
1736
+ msw.use(
1737
+ rest.get("*/memberships", (req, res, ctx) => {
1738
+ return res.once(ctx.json(createFetchResult(accounts)));
1739
+ })
1740
+ );
1741
+ }
1742
+
1743
+ function mockKeyListRequest(
1744
+ expectedNamespaceId: string,
1745
+ expectedKeys: NamespaceKeyInfo[],
1746
+ keysPerRequest = 1000,
1747
+ blankCursorValue: "" | undefined | null = undefined
1748
+ ) {
1749
+ const requests = { count: 0 };
1750
+ // See https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
1751
+ msw.use(
1752
+ rest.get(
1753
+ "*/accounts/:accountId/storage/kv/namespaces/:namespaceId/keys",
1754
+ (req, res, ctx) => {
1755
+ requests.count++;
1756
+ let result;
1757
+ let cursor;
1758
+
1759
+ expect(req.params.accountId).toEqual("some-account-id");
1760
+ expect(req.params.namespaceId).toEqual(expectedNamespaceId);
1761
+
1762
+ if (expectedKeys.length <= keysPerRequest) {
1763
+ result = expectedKeys;
1764
+ } else {
1765
+ const start =
1766
+ parseInt(req.url.searchParams.get("cursor") ?? "0") || 0;
1767
+ const end = start + keysPerRequest;
1768
+ cursor = end < expectedKeys.length ? end : blankCursorValue;
1769
+ result = expectedKeys.slice(start, end);
1770
+ }
1771
+ return res(
1772
+ ctx.json({
1773
+ success: true,
1774
+ errors: [],
1775
+ messages: [],
1776
+ result,
1777
+ result_info: {
1778
+ cursor,
1779
+ },
1780
+ })
1781
+ );
1782
+ }
1783
+ )
1784
+ );
1785
+ return requests;
1520
1786
  }