wrangler 0.0.0-e64812e → 0.0.0-e6c9c5c0

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