wrangler 0.0.0-e60dc909 → 0.0.0-e61dba50

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 (292) hide show
  1. package/README.md +12 -14
  2. package/bin/wrangler.js +14 -75
  3. package/package.json +218 -194
  4. package/templates/__tests__/tsconfig.json +1 -1
  5. package/templates/checked-fetch.js +19 -6
  6. package/templates/facade.d.ts +4 -1
  7. package/templates/gitignore +1 -0
  8. package/templates/init-tests/test-vitest-new-worker.js +1 -1
  9. package/templates/init-tests/test-vitest-new-worker.ts +1 -1
  10. package/templates/middleware/common.ts +9 -4
  11. package/templates/middleware/loader-modules.ts +67 -13
  12. package/templates/middleware/loader-sw.ts +6 -10
  13. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  14. package/templates/middleware/middleware-miniflare3-json-error.ts +18 -5
  15. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  16. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  17. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  18. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  19. package/templates/modules-watch-stub.js +4 -0
  20. package/templates/new-worker-scheduled.ts +1 -1
  21. package/templates/new-worker.ts +4 -1
  22. package/templates/pages-dev-pipeline.ts +2 -1
  23. package/templates/pages-dev-util.ts +4 -1
  24. package/templates/pages-shim.ts +0 -3
  25. package/templates/pages-template-plugin.ts +19 -5
  26. package/templates/pages-template-worker.ts +11 -2
  27. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  28. package/templates/startDevWorker/ProxyWorker.ts +252 -0
  29. package/templates/tsconfig.init.json +1 -2
  30. package/templates/tsconfig.json +1 -1
  31. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  32. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  33. package/wrangler-dist/ProxyWorker.js +186 -0
  34. package/wrangler-dist/ProxyWorker.js.map +6 -0
  35. package/wrangler-dist/cli.d.ts +23451 -507
  36. package/wrangler-dist/cli.js +137801 -113177
  37. package/wrangler-dist/wasm-sync.wasm +0 -0
  38. package/import_meta_url.js +0 -3
  39. package/miniflare-config-stubs/.env.empty +0 -0
  40. package/miniflare-config-stubs/package.empty.json +0 -1
  41. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  42. package/miniflare-dist/index.mjs +0 -6364
  43. package/src/__tests__/access.test.ts +0 -25
  44. package/src/__tests__/api-dev.test.ts +0 -238
  45. package/src/__tests__/api-devregistry.test.js +0 -64
  46. package/src/__tests__/api.test.ts +0 -80
  47. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  48. package/src/__tests__/config-cache.test.ts +0 -42
  49. package/src/__tests__/configuration.test.ts +0 -4163
  50. package/src/__tests__/d1/d1.test.ts +0 -123
  51. package/src/__tests__/d1/splitter.test.ts +0 -255
  52. package/src/__tests__/delete.test.ts +0 -266
  53. package/src/__tests__/deployments.test.ts +0 -105
  54. package/src/__tests__/dev.test.tsx +0 -1586
  55. package/src/__tests__/generate.test.ts +0 -238
  56. package/src/__tests__/get-host-from-url.test.ts +0 -16
  57. package/src/__tests__/guess-worker-format.test.ts +0 -85
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-auth-domain.ts +0 -20
  62. package/src/__tests__/helpers/mock-bin.ts +0 -36
  63. package/src/__tests__/helpers/mock-cfetch.ts +0 -278
  64. package/src/__tests__/helpers/mock-console.ts +0 -106
  65. package/src/__tests__/helpers/mock-dialogs.ts +0 -137
  66. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  67. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  68. package/src/__tests__/helpers/mock-istty.ts +0 -74
  69. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  70. package/src/__tests__/helpers/mock-kv.ts +0 -33
  71. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -271
  72. package/src/__tests__/helpers/mock-process.ts +0 -34
  73. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  74. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  75. package/src/__tests__/helpers/msw/blob-worker.cjs +0 -19
  76. package/src/__tests__/helpers/msw/handlers/access.ts +0 -13
  77. package/src/__tests__/helpers/msw/handlers/deployments.ts +0 -59
  78. package/src/__tests__/helpers/msw/handlers/namespaces.ts +0 -104
  79. package/src/__tests__/helpers/msw/handlers/oauth.ts +0 -31
  80. package/src/__tests__/helpers/msw/handlers/r2.ts +0 -80
  81. package/src/__tests__/helpers/msw/handlers/script.ts +0 -75
  82. package/src/__tests__/helpers/msw/handlers/user.ts +0 -63
  83. package/src/__tests__/helpers/msw/handlers/zones.ts +0 -22
  84. package/src/__tests__/helpers/msw/index.ts +0 -21
  85. package/src/__tests__/helpers/msw/read-file-sync.js +0 -61
  86. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  87. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  88. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +0 -1
  89. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +0 -5
  90. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +0 -1
  91. package/src/__tests__/helpers/worker-scripts/parent-worker.js +0 -8
  92. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +0 -5
  93. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  94. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  95. package/src/__tests__/https-options.test.ts +0 -163
  96. package/src/__tests__/index.test.ts +0 -268
  97. package/src/__tests__/init.test.ts +0 -3175
  98. package/src/__tests__/jest.setup.ts +0 -198
  99. package/src/__tests__/kv.test.ts +0 -1788
  100. package/src/__tests__/logger.test.ts +0 -141
  101. package/src/__tests__/logout.test.ts +0 -47
  102. package/src/__tests__/metrics.test.ts +0 -493
  103. package/src/__tests__/middleware.scheduled.test.ts +0 -145
  104. package/src/__tests__/middleware.test.ts +0 -750
  105. package/src/__tests__/package-manager.test.ts +0 -353
  106. package/src/__tests__/pages-deployment-tail.test.ts +0 -884
  107. package/src/__tests__/pages.test.ts +0 -2899
  108. package/src/__tests__/parse.test.ts +0 -330
  109. package/src/__tests__/paths.test.ts +0 -39
  110. package/src/__tests__/publish.test.ts +0 -7769
  111. package/src/__tests__/pubsub.test.ts +0 -490
  112. package/src/__tests__/queues.test.ts +0 -522
  113. package/src/__tests__/r2.test.ts +0 -393
  114. package/src/__tests__/route.test.ts +0 -45
  115. package/src/__tests__/secret.test.ts +0 -701
  116. package/src/__tests__/tail.test.ts +0 -905
  117. package/src/__tests__/test-old-node-version.js +0 -31
  118. package/src/__tests__/tsconfig-sanity.ts +0 -12
  119. package/src/__tests__/tsconfig.json +0 -8
  120. package/src/__tests__/tsconfig.tsbuildinfo +0 -1
  121. package/src/__tests__/type-generation.test.ts +0 -233
  122. package/src/__tests__/user.test.ts +0 -129
  123. package/src/__tests__/utils-collectKeyValues.test.ts +0 -47
  124. package/src/__tests__/validate-dev-props.test.ts +0 -56
  125. package/src/__tests__/version.test.ts +0 -35
  126. package/src/__tests__/whoami.test.tsx +0 -183
  127. package/src/__tests__/worker-namespace.test.ts +0 -326
  128. package/src/abort.d.ts +0 -3
  129. package/src/api/dev.ts +0 -247
  130. package/src/api/index.ts +0 -2
  131. package/src/bundle-reporter.ts +0 -68
  132. package/src/bundle.ts +0 -823
  133. package/src/cfetch/index.ts +0 -158
  134. package/src/cfetch/internal.ts +0 -261
  135. package/src/cli.ts +0 -28
  136. package/src/config/README.md +0 -107
  137. package/src/config/config.ts +0 -275
  138. package/src/config/diagnostics.ts +0 -80
  139. package/src/config/environment.ts +0 -577
  140. package/src/config/index.ts +0 -358
  141. package/src/config/validation-helpers.ts +0 -597
  142. package/src/config/validation.ts +0 -2151
  143. package/src/config-cache.ts +0 -85
  144. package/src/create-worker-preview.ts +0 -282
  145. package/src/create-worker-upload-form.ts +0 -325
  146. package/src/d1/backups.tsx +0 -223
  147. package/src/d1/constants.ts +0 -2
  148. package/src/d1/create.tsx +0 -63
  149. package/src/d1/delete.ts +0 -56
  150. package/src/d1/execute.tsx +0 -323
  151. package/src/d1/formatTimeAgo.ts +0 -14
  152. package/src/d1/index.ts +0 -101
  153. package/src/d1/list.tsx +0 -48
  154. package/src/d1/migrations/apply.tsx +0 -197
  155. package/src/d1/migrations/create.tsx +0 -77
  156. package/src/d1/migrations/helpers.ts +0 -147
  157. package/src/d1/migrations/index.ts +0 -3
  158. package/src/d1/migrations/list.tsx +0 -79
  159. package/src/d1/migrations/options.ts +0 -18
  160. package/src/d1/options.ts +0 -22
  161. package/src/d1/splitter.ts +0 -161
  162. package/src/d1/types.ts +0 -24
  163. package/src/d1/utils.ts +0 -48
  164. package/src/delete.ts +0 -103
  165. package/src/deployments.ts +0 -83
  166. package/src/deprecated/index.ts +0 -145
  167. package/src/dev/dev-vars.ts +0 -39
  168. package/src/dev/dev.tsx +0 -614
  169. package/src/dev/get-local-persistence-path.ts +0 -31
  170. package/src/dev/local.tsx +0 -932
  171. package/src/dev/remote.tsx +0 -630
  172. package/src/dev/start-server.ts +0 -543
  173. package/src/dev/use-esbuild.ts +0 -204
  174. package/src/dev/validate-dev-props.ts +0 -31
  175. package/src/dev-registry.ts +0 -201
  176. package/src/dev.tsx +0 -949
  177. package/src/dialogs.ts +0 -136
  178. package/src/dispatch-namespace.ts +0 -207
  179. package/src/docs/index.ts +0 -97
  180. package/src/durable.ts +0 -102
  181. package/src/entry.ts +0 -329
  182. package/src/environment-variables/factory.ts +0 -88
  183. package/src/environment-variables/misc-variables.ts +0 -30
  184. package/src/errors.ts +0 -11
  185. package/src/generate/index.ts +0 -300
  186. package/src/git-client.ts +0 -135
  187. package/src/global-wrangler-config-path.ts +0 -26
  188. package/src/https-options.ts +0 -127
  189. package/src/index.ts +0 -694
  190. package/src/init.ts +0 -1024
  191. package/src/inspect.ts +0 -767
  192. package/src/intl-polyfill.d.ts +0 -139
  193. package/src/is-ci.ts +0 -14
  194. package/src/is-interactive.ts +0 -16
  195. package/src/jest.d.ts +0 -4
  196. package/src/kv/helpers.ts +0 -430
  197. package/src/kv/index.ts +0 -596
  198. package/src/logger.ts +0 -104
  199. package/src/metrics/index.ts +0 -5
  200. package/src/metrics/metrics-config.ts +0 -239
  201. package/src/metrics/metrics-dispatcher.ts +0 -96
  202. package/src/metrics/metrics-usage-headers.ts +0 -24
  203. package/src/metrics/send-event.ts +0 -97
  204. package/src/miniflare-cli/README.md +0 -30
  205. package/src/miniflare-cli/assets.ts +0 -250
  206. package/src/miniflare-cli/index.ts +0 -210
  207. package/src/miniflare-cli/request-context.ts +0 -40
  208. package/src/miniflare-cli/tsconfig.json +0 -9
  209. package/src/miniflare-cli/tsconfig.tsbuildinfo +0 -1
  210. package/src/miniflare-cli/types.ts +0 -11
  211. package/src/module-collection.ts +0 -267
  212. package/src/open-in-browser.ts +0 -17
  213. package/src/package-manager.ts +0 -219
  214. package/src/pages/build.ts +0 -270
  215. package/src/pages/constants.ts +0 -18
  216. package/src/pages/deployment-tails.ts +0 -284
  217. package/src/pages/deployments.tsx +0 -84
  218. package/src/pages/dev.ts +0 -711
  219. package/src/pages/errors.ts +0 -66
  220. package/src/pages/functions/buildPlugin.ts +0 -107
  221. package/src/pages/functions/buildWorker.ts +0 -166
  222. package/src/pages/functions/filepath-routing.test.ts +0 -234
  223. package/src/pages/functions/filepath-routing.ts +0 -189
  224. package/src/pages/functions/identifiers.ts +0 -78
  225. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  226. package/src/pages/functions/routes-consolidation.ts +0 -73
  227. package/src/pages/functions/routes-transformation.test.ts +0 -282
  228. package/src/pages/functions/routes-transformation.ts +0 -115
  229. package/src/pages/functions/routes-validation.test.ts +0 -403
  230. package/src/pages/functions/routes-validation.ts +0 -202
  231. package/src/pages/functions/routes.ts +0 -151
  232. package/src/pages/functions/tsconfig.json +0 -8
  233. package/src/pages/functions/tsconfig.tsbuildinfo +0 -1
  234. package/src/pages/functions.ts +0 -82
  235. package/src/pages/hash.ts +0 -13
  236. package/src/pages/index.ts +0 -102
  237. package/src/pages/projects.tsx +0 -167
  238. package/src/pages/prompt-select-project.tsx +0 -31
  239. package/src/pages/publish.tsx +0 -462
  240. package/src/pages/types.ts +0 -41
  241. package/src/pages/upload.tsx +0 -447
  242. package/src/pages/utils.ts +0 -23
  243. package/src/parse.ts +0 -286
  244. package/src/paths.ts +0 -71
  245. package/src/proxy.ts +0 -694
  246. package/src/publish/index.ts +0 -270
  247. package/src/publish/publish.ts +0 -1038
  248. package/src/pubsub/index.ts +0 -286
  249. package/src/pubsub/pubsub-commands.ts +0 -624
  250. package/src/queues/cli/commands/consumer/add.ts +0 -71
  251. package/src/queues/cli/commands/consumer/index.ts +0 -22
  252. package/src/queues/cli/commands/consumer/remove.ts +0 -38
  253. package/src/queues/cli/commands/create.ts +0 -25
  254. package/src/queues/cli/commands/delete.ts +0 -26
  255. package/src/queues/cli/commands/index.ts +0 -36
  256. package/src/queues/cli/commands/list.ts +0 -25
  257. package/src/queues/client.ts +0 -135
  258. package/src/queues/utils.ts +0 -18
  259. package/src/r2/constants.ts +0 -4
  260. package/src/r2/helpers.ts +0 -131
  261. package/src/r2/index.ts +0 -289
  262. package/src/routes.ts +0 -140
  263. package/src/secret/index.ts +0 -379
  264. package/src/selfsigned.d.ts +0 -29
  265. package/src/sites.ts +0 -372
  266. package/src/tail/createTail.ts +0 -379
  267. package/src/tail/filters.ts +0 -277
  268. package/src/tail/index.ts +0 -213
  269. package/src/tail/printing.ts +0 -107
  270. package/src/tsconfig-sanity.ts +0 -16
  271. package/src/type-generation.ts +0 -181
  272. package/src/update-check.ts +0 -19
  273. package/src/user/access.ts +0 -68
  274. package/src/user/auth-variables.ts +0 -113
  275. package/src/user/choose-account.tsx +0 -39
  276. package/src/user/generate-auth-url.ts +0 -33
  277. package/src/user/generate-random-state.ts +0 -16
  278. package/src/user/index.ts +0 -2
  279. package/src/user/user.ts +0 -1232
  280. package/src/utils/collectKeyValues.ts +0 -14
  281. package/src/whoami.ts +0 -135
  282. package/src/worker.ts +0 -251
  283. package/src/yargs-types.ts +0 -24
  284. package/src/zones.ts +0 -191
  285. package/templates/__tests__/tsconfig.tsbuildinfo +0 -1
  286. package/templates/d1-beta-facade.js +0 -241
  287. package/templates/first-party-worker-module-facade.ts +0 -19
  288. package/templates/format-dev-errors.ts +0 -33
  289. package/templates/serve-static-assets.ts +0 -65
  290. package/templates/service-bindings-module-facade.js +0 -54
  291. package/templates/service-bindings-sw-facade.js +0 -42
  292. package/templates/tsconfig.tsbuildinfo +0 -1
@@ -1,1788 +0,0 @@
1
- import { writeFileSync } from "node:fs";
2
- import { rest } from "msw";
3
- import { mockAccountId, mockApiToken } from "./helpers/mock-account-id";
4
- import { mockConsoleMethods } from "./helpers/mock-console";
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";
9
- import { runInTempDir } from "./helpers/run-in-tmp";
10
- import { runWrangler } from "./helpers/run-wrangler";
11
- import type {
12
- KeyValue,
13
- KVNamespaceInfo,
14
- NamespaceKeyInfo,
15
- } from "../kv/helpers";
16
- describe("wrangler", () => {
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
- });
1680
- });
1681
-
1682
- function writeWranglerConfig() {
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;
1788
- }