@bino0216/nitro-cloudflare-dev 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Pooya Parsa <pooya@pi0.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # Cloudflare Platform for Nitro and Nuxt
2
+
3
+ This proof of concept module enables access to the Cloudflare runtime platform in the development server of [Nitro](https://nitro.unjs.io) and [Nuxt](https://nuxt.com) using the [new `getPlatformProxy` API](https://github.com/cloudflare/workers-sdk/pull/5002) exposed by [wrangler](https://developers.cloudflare.com/workers/wrangler/) and [miniflare](https://miniflare.dev/)
4
+
5
+ > [!NOTE]
6
+ > Nitro plans to introduce a new method to allow native dev presets, meaning you can natively run [miniflare](https://miniflare.dev/) as your development server without this module or a proxy in the future!
7
+
8
+ ## Usage
9
+
10
+ First, install `nitro-cloudflare-dev` and `wrangler` packages as a dev dependency: ([unjs/nypm](https://nypm.unjs.io) will automatically detect your package manager!)
11
+
12
+ ```sh
13
+ npx nypm@latest add -D wrangler nitro-cloudflare-dev
14
+ ```
15
+
16
+ For **Nuxt** update `nuxt.config.ts`:
17
+
18
+ ```js
19
+ export default defineNuxtConfig({
20
+ modules: ["nitro-cloudflare-dev"],
21
+ });
22
+ ```
23
+
24
+ For **Nitro** update `nitro.config.ts`:
25
+
26
+ ```js
27
+ import nitroCloudflareBindings from "nitro-cloudflare-dev";
28
+
29
+ export default defineNitroConfig({
30
+ modules: [nitroCloudflareBindings],
31
+ });
32
+ ```
33
+
34
+ ## Configuration and persistence
35
+
36
+ This module automatically finds the closest [`wrangler.toml`](https://developers.cloudflare.com/workers/wrangler/configuration/) file for configuration.
37
+
38
+ Data is persisted `.wrangler/state/v3` directory. On first use of the module, it will be automatically added to the `.gitignore` file.
39
+
40
+ You can configure additional options using `cloudflareDev: { }` in `nitro.config` or `nitro: { cloudflareDev: {} }` in `nuxt.config`.
41
+
42
+ ### Available options
43
+
44
+ - `persistDir`: Sets the persist dir (default `.wrangler/state/v3`).
45
+ - `configPath`: Sets a custom path for `wrangler.toml` file.
46
+ - `silent`: Hide initial banner.
47
+ - `environment`: Sets specific environment (useful for multi-environment configurations)
48
+
49
+ ## Development
50
+
51
+ - Clone this repository
52
+ - Install the latest LTS version of [Node.js](https://nodejs.org/en/)
53
+ - Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
54
+ - Install dependencies using `pnpm install`
55
+ - Build in stub mode using `pnpm build --stub`
56
+ - Run Nitro playground using `pnpm dev:nitro` or Nuxt playground using `pnpm dev:nuxt`
57
+
58
+ ## License
59
+
60
+ [MIT](./LICENSE)
@@ -0,0 +1,41 @@
1
+ import { PlatformProxy } from 'wrangler';
2
+
3
+ declare module "h3" {
4
+ interface H3EventContext {
5
+ cf: PlatformProxy["cf"];
6
+ cloudflare: {
7
+ request: Request & {
8
+ cf: PlatformProxy["cf"];
9
+ };
10
+ env: PlatformProxy["env"];
11
+ context: PlatformProxy["ctx"];
12
+ };
13
+ }
14
+ }
15
+
16
+ interface RemoteBinding {
17
+ type: "r2" | "kv" | "d1";
18
+ name: string;
19
+ bucketName?: string;
20
+ databaseId?: string;
21
+ namespaceId?: string;
22
+ }
23
+ interface CloudflareDevOptions {
24
+ configPath?: string;
25
+ environment?: string;
26
+ persistDir?: string;
27
+ silent?: boolean;
28
+ remote?: {
29
+ accountId?: string;
30
+ apiToken?: string;
31
+ };
32
+ }
33
+ declare module "nitropack" {
34
+ interface NitroOptions {
35
+ cloudflareDev?: CloudflareDevOptions;
36
+ }
37
+ }
38
+ declare function nitroCloudflareDev(arg1: unknown, arg2: unknown): void;
39
+
40
+ export { nitroCloudflareDev as default };
41
+ export type { CloudflareDevOptions, RemoteBinding };
@@ -0,0 +1,41 @@
1
+ import { PlatformProxy } from 'wrangler';
2
+
3
+ declare module "h3" {
4
+ interface H3EventContext {
5
+ cf: PlatformProxy["cf"];
6
+ cloudflare: {
7
+ request: Request & {
8
+ cf: PlatformProxy["cf"];
9
+ };
10
+ env: PlatformProxy["env"];
11
+ context: PlatformProxy["ctx"];
12
+ };
13
+ }
14
+ }
15
+
16
+ interface RemoteBinding {
17
+ type: "r2" | "kv" | "d1";
18
+ name: string;
19
+ bucketName?: string;
20
+ databaseId?: string;
21
+ namespaceId?: string;
22
+ }
23
+ interface CloudflareDevOptions {
24
+ configPath?: string;
25
+ environment?: string;
26
+ persistDir?: string;
27
+ silent?: boolean;
28
+ remote?: {
29
+ accountId?: string;
30
+ apiToken?: string;
31
+ };
32
+ }
33
+ declare module "nitropack" {
34
+ interface NitroOptions {
35
+ cloudflareDev?: CloudflareDevOptions;
36
+ }
37
+ }
38
+ declare function nitroCloudflareDev(arg1: unknown, arg2: unknown): void;
39
+
40
+ export { nitroCloudflareDev as default };
41
+ export type { CloudflareDevOptions, RemoteBinding };
package/dist/index.mjs ADDED
@@ -0,0 +1,202 @@
1
+ import { resolve, relative } from 'node:path';
2
+ import { promises } from 'node:fs';
3
+ import { fileURLToPath } from 'mlly';
4
+ import { consola } from 'consola';
5
+ import { colorize } from 'consola/utils';
6
+ import { findFile } from 'pkg-types';
7
+
8
+ function parseTomlBindings(content, key) {
9
+ const results = [];
10
+ const inlineMatch = content.match(new RegExp(`${key}\\s*=\\s*\\[([\\s\\S]*?)\\](?=\\n[a-z_]|\\n*$)`, "i"));
11
+ if (inlineMatch) {
12
+ const arrayContent = inlineMatch[1];
13
+ const objectMatches = arrayContent.match(/\{[^}]+\}/g);
14
+ if (objectMatches) {
15
+ for (const obj of objectMatches) {
16
+ const item = {};
17
+ const pairs = obj.match(/(\w+)\s*=\s*(?:"([^"]+)"|'([^']+)'|(\w+))/g);
18
+ if (pairs) {
19
+ for (const pair of pairs) {
20
+ const match = pair.match(/(\w+)\s*=\s*(?:"([^"]+)"|'([^']+)'|(\w+))/);
21
+ if (match) {
22
+ const k = match[1];
23
+ const v = match[2] || match[3] || match[4];
24
+ item[k] = v === "true" ? true : v === "false" ? false : v;
25
+ }
26
+ }
27
+ }
28
+ results.push(item);
29
+ }
30
+ }
31
+ }
32
+ const blockRegex = new RegExp(`\\[\\[${key}\\]\\]([\\s\\S]*?)(?=\\[\\[|$)`, "g");
33
+ let blockMatch;
34
+ while ((blockMatch = blockRegex.exec(content)) !== null) {
35
+ const block = blockMatch[1];
36
+ const item = {};
37
+ const lines = block.split("\n");
38
+ for (const line of lines) {
39
+ const match = line.match(/^(\w+)\s*=\s*(?:"([^"]+)"|'([^']+)'|(\w+))/);
40
+ if (match) {
41
+ const k = match[1];
42
+ const v = match[2] || match[3] || match[4];
43
+ item[k] = v === "true" ? true : v === "false" ? false : v;
44
+ }
45
+ }
46
+ if (Object.keys(item).length > 0) {
47
+ results.push(item);
48
+ }
49
+ }
50
+ return results;
51
+ }
52
+ async function parseWranglerConfig(configPath) {
53
+ const remoteBindings = [];
54
+ const content = await promises.readFile(configPath, "utf8");
55
+ if (configPath.endsWith(".toml")) {
56
+ const r2Bindings = parseTomlBindings(content, "r2_buckets");
57
+ for (const item of r2Bindings) {
58
+ if (item.remote === true && typeof item.binding === "string") {
59
+ remoteBindings.push({
60
+ type: "r2",
61
+ name: item.binding,
62
+ bucketName: typeof item.bucket_name === "string" ? item.bucket_name : void 0
63
+ });
64
+ }
65
+ }
66
+ const kvBindings = parseTomlBindings(content, "kv_namespaces");
67
+ for (const item of kvBindings) {
68
+ if (item.remote === true && typeof item.binding === "string") {
69
+ remoteBindings.push({
70
+ type: "kv",
71
+ name: item.binding,
72
+ namespaceId: typeof item.id === "string" ? item.id : void 0
73
+ });
74
+ }
75
+ }
76
+ const d1Bindings = parseTomlBindings(content, "d1_databases");
77
+ for (const item of d1Bindings) {
78
+ if (item.remote === true && typeof item.binding === "string") {
79
+ remoteBindings.push({
80
+ type: "d1",
81
+ name: item.binding,
82
+ databaseId: typeof item.database_id === "string" ? item.database_id : void 0
83
+ });
84
+ }
85
+ }
86
+ } else {
87
+ const jsonContent = content.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
88
+ const config = JSON.parse(jsonContent);
89
+ if (config.r2_buckets) {
90
+ for (const bucket of config.r2_buckets) {
91
+ if (bucket.remote === true) {
92
+ remoteBindings.push({
93
+ type: "r2",
94
+ name: bucket.binding,
95
+ bucketName: bucket.bucket_name
96
+ });
97
+ }
98
+ }
99
+ }
100
+ if (config.kv_namespaces) {
101
+ for (const kv of config.kv_namespaces) {
102
+ if (kv.remote === true) {
103
+ remoteBindings.push({
104
+ type: "kv",
105
+ name: kv.binding,
106
+ namespaceId: kv.id
107
+ });
108
+ }
109
+ }
110
+ }
111
+ if (config.d1_databases) {
112
+ for (const d1 of config.d1_databases) {
113
+ if (d1.remote === true) {
114
+ remoteBindings.push({
115
+ type: "d1",
116
+ name: d1.binding,
117
+ databaseId: d1.database_id
118
+ });
119
+ }
120
+ }
121
+ }
122
+ }
123
+ return remoteBindings;
124
+ }
125
+ async function nitroModule(nitro) {
126
+ if (!nitro.options.dev) {
127
+ return;
128
+ }
129
+ let configPath = nitro.options.cloudflareDev?.configPath;
130
+ if (!configPath) {
131
+ configPath = await findFile(
132
+ ["wrangler.json", "wrangler.jsonc", "wrangler.toml"],
133
+ {
134
+ startingFrom: nitro.options.srcDir
135
+ }
136
+ ).catch(() => void 0);
137
+ }
138
+ let remoteBindings = [];
139
+ if (configPath) {
140
+ remoteBindings = await parseWranglerConfig(configPath).catch(() => []);
141
+ }
142
+ const persistDir = resolve(
143
+ nitro.options.rootDir,
144
+ nitro.options.cloudflareDev?.persistDir || ".wrangler/state/v3"
145
+ );
146
+ const gitIgnorePath = await findFile(".gitignore", {
147
+ startingFrom: nitro.options.rootDir
148
+ }).catch(() => void 0);
149
+ let addedToGitIgnore = false;
150
+ if (gitIgnorePath && persistDir === ".wrangler/state/v3") {
151
+ const gitIgnore = await promises.readFile(gitIgnorePath, "utf8");
152
+ if (!gitIgnore.includes(".wrangler/state/v3")) {
153
+ await promises.writeFile(gitIgnorePath, gitIgnore + "\n.wrangler/state/v3\n").catch(() => {
154
+ });
155
+ addedToGitIgnore = true;
156
+ }
157
+ }
158
+ if (!nitro.options.cloudflareDev?.silent) {
159
+ const remoteInfo = remoteBindings.length > 0 ? `
160
+ Remote bindings: ${remoteBindings.map((b) => `${b.name} (${b.type})`).join(", ")}` : "";
161
+ consola.box(
162
+ [
163
+ "\u{1F525} Cloudflare context bindings enabled for dev server",
164
+ "",
165
+ `Config path: \`${configPath ? relative(".", configPath) : colorize("yellow", "cannot find `wrangler.json`, `wrangler.jsonc`, or `wrangler.toml`")}\``,
166
+ `Persist dir: \`${relative(".", persistDir)}\` ${addedToGitIgnore ? colorize("green", "(added to `.gitignore`)") : ""}`,
167
+ remoteInfo
168
+ ].join("\n")
169
+ );
170
+ }
171
+ nitro.options.runtimeConfig.wrangler = {
172
+ ...nitro.options.runtimeConfig.wrangler,
173
+ configPath,
174
+ persistDir,
175
+ environment: nitro.options.cloudflareDev?.environment,
176
+ remoteBindings,
177
+ remoteCredentials: {
178
+ accountId: nitro.options.cloudflareDev?.remote?.accountId || process.env.CF_ACCOUNT_ID,
179
+ apiToken: nitro.options.cloudflareDev?.remote?.apiToken || process.env.CF_API_TOKEN
180
+ }
181
+ };
182
+ nitro.options.externals.inline = nitro.options.externals.inline || [];
183
+ nitro.options.externals.inline.push(
184
+ fileURLToPath(new URL("runtime/", import.meta.url))
185
+ );
186
+ nitro.options.plugins = nitro.options.plugins || [];
187
+ nitro.options.plugins.push(
188
+ fileURLToPath(new URL("runtime/plugin.dev", import.meta.url))
189
+ );
190
+ }
191
+ function nitroCloudflareDev(arg1, arg2) {
192
+ if (arg2?.options?.nitro) {
193
+ arg2.hooks.hookOnce("nitro:config", (nitroConfig) => {
194
+ nitroConfig.modules = nitroConfig.modules || [];
195
+ nitroConfig.modules.push(nitroModule);
196
+ });
197
+ } else {
198
+ nitroModule(arg1);
199
+ }
200
+ }
201
+
202
+ export { nitroCloudflareDev as default };
@@ -0,0 +1,3 @@
1
+ import type { NitroAppPlugin } from "nitropack";
2
+ declare const _default: NitroAppPlugin;
3
+ export default _default;
@@ -0,0 +1,111 @@
1
+ import { useRuntimeConfig, getRequestURL } from "#imports";
2
+ const _proxy = _getPlatformProxy().catch((error) => {
3
+ console.error("Failed to initialize wrangler bindings proxy", error);
4
+ return _createStubProxy();
5
+ }).then((proxy) => {
6
+ globalThis.__env__ = proxy.env;
7
+ return proxy;
8
+ });
9
+ globalThis.__env__ = _proxy.then((proxy) => proxy.env);
10
+ export default (function(nitroApp) {
11
+ nitroApp.hooks.hook("request", async (event) => {
12
+ const proxy = await _proxy;
13
+ event.context.cf = proxy.cf;
14
+ event.context.waitUntil = proxy.ctx.waitUntil.bind(proxy.ctx);
15
+ const request = new Request(getRequestURL(event));
16
+ request.cf = proxy.cf;
17
+ event.context.cloudflare = {
18
+ ...event.context.cloudflare,
19
+ request,
20
+ env: proxy.env,
21
+ context: proxy.ctx
22
+ };
23
+ event.node.req.__unenv__ = {
24
+ ...event.node.req.__unenv__,
25
+ waitUntil: event.context.waitUntil
26
+ };
27
+ });
28
+ nitroApp.hooks._hooks.request.unshift(nitroApp.hooks._hooks.request.pop());
29
+ nitroApp.hooks.hook("close", () => {
30
+ return _proxy?.then((proxy) => proxy.dispose);
31
+ });
32
+ });
33
+ async function _getPlatformProxy() {
34
+ const runtimeConfig = useRuntimeConfig();
35
+ const { remoteBindings, remoteCredentials } = runtimeConfig.wrangler;
36
+ const _pkg = "wrangler";
37
+ const { getPlatformProxy } = await import(_pkg).catch(() => {
38
+ throw new Error(
39
+ "Package `wrangler` not found, please install it with: `npx nypm@latest add -D wrangler`"
40
+ );
41
+ });
42
+ const proxyOptions = {
43
+ configPath: runtimeConfig.wrangler.configPath,
44
+ persist: { path: runtimeConfig.wrangler.persistDir }
45
+ };
46
+ if (runtimeConfig.wrangler.environment) {
47
+ proxyOptions.environment = runtimeConfig.wrangler.environment;
48
+ }
49
+ const proxy = await getPlatformProxy(proxyOptions);
50
+ if (remoteBindings.length > 0 && remoteCredentials.accountId && remoteCredentials.apiToken) {
51
+ const { getBindings } = await import("openwrangler");
52
+ const openBindings = getBindings({
53
+ accountId: remoteCredentials.accountId,
54
+ apiToken: remoteCredentials.apiToken
55
+ });
56
+ for (const binding of remoteBindings) {
57
+ switch (binding.type) {
58
+ case "r2": {
59
+ proxy.env[binding.name] = openBindings.r2;
60
+ break;
61
+ }
62
+ case "kv": {
63
+ proxy.env[binding.name] = openBindings.kv;
64
+ break;
65
+ }
66
+ case "d1": {
67
+ proxy.env[binding.name] = openBindings.d1;
68
+ break;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ return proxy;
74
+ }
75
+ function _createStubProxy() {
76
+ return {
77
+ env: {},
78
+ cf: {},
79
+ ctx: {
80
+ waitUntil() {
81
+ },
82
+ passThroughOnException() {
83
+ },
84
+ props: {}
85
+ },
86
+ caches: {
87
+ open() {
88
+ const result = Promise.resolve(new _CacheStub());
89
+ return result;
90
+ },
91
+ get default() {
92
+ return new _CacheStub();
93
+ }
94
+ },
95
+ dispose: () => Promise.resolve()
96
+ };
97
+ }
98
+ class _CacheStub {
99
+ delete() {
100
+ const result = Promise.resolve(false);
101
+ return result;
102
+ }
103
+ match() {
104
+ const result = Promise.resolve(void 0);
105
+ return result;
106
+ }
107
+ put() {
108
+ const result = Promise.resolve();
109
+ return result;
110
+ }
111
+ }
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@bino0216/nitro-cloudflare-dev",
3
+ "private": false,
4
+ "version": "0.2.2",
5
+ "description": "POC module to enable access to the Cloudflare runtime bindings in development server of Nitro and Nuxt",
6
+ "repository": "pi0/nitro-cloudflare-dev",
7
+ "license": "MIT",
8
+ "sideEffects": false,
9
+ "type": "module",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.mjs"
14
+ },
15
+ "./dist/runtime/*": {
16
+ "types": "./dist/runtime/*.d.ts",
17
+ "default": "./dist/runtime/*.mjs"
18
+ }
19
+ },
20
+ "main": "./dist/index.mjs",
21
+ "types": "./dist/index.d.ts",
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "resolutions": {
26
+ "@binochoi/nitro-cloudflare-dev": "workspace:*"
27
+ },
28
+ "dependencies": {
29
+ "consola": "^3.4.0",
30
+ "mlly": "^1.7.4",
31
+ "pkg-types": "^2.1.0",
32
+ "openwrangler": "0.0.1"
33
+ },
34
+ "devDependencies": {
35
+ "@cloudflare/workers-types": "^4.20250303.0",
36
+ "@types/node": "^22.13.9",
37
+ "changelogen": "^0.6.1",
38
+ "eslint": "^9.21.0",
39
+ "eslint-config-unjs": "^0.4.2",
40
+ "h3": "^1.15.1",
41
+ "jiti": "^2.4.2",
42
+ "miniflare": "^3.20250224.0",
43
+ "nitropack": "^2.11.2",
44
+ "nuxt": "^3.15.4",
45
+ "prettier": "^3.5.3",
46
+ "typescript": "^5.8.2",
47
+ "unbuild": "^3.5.0",
48
+ "wrangler": "^3.113.0"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "scripts": {
54
+ "build": "unbuild",
55
+ "dev:nitro": "pnpm run -C examples/nitro dev",
56
+ "dev:nuxt": "pnpm run -C examples/nuxt dev",
57
+ "lint": "eslint --cache . && prettier -c src",
58
+ "lint:fix": "eslint --cache . --fix && prettier -c src -w",
59
+ "release": "pnpm test && pnpm build && changelogen --release && npm publish && git push --follow-tags",
60
+ "test": "pnpm lint && pnpm test:types",
61
+ "test:types": "tsc --noEmit --skipLibCheck"
62
+ }
63
+ }