Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cf-bindings-proxy

Package Overview
Dependencies
Maintainers
1
Versions
61
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cf-bindings-proxy - npm Package Compare versions

Comparing version 0.4.1 to 0.5.0-50ff06b

58

cli/template/_worker.js

@@ -1,29 +0,49 @@

import { prepareDataForProxy as l, transformData as p } from "../../transform.js";
const c = async (e, n) => n.reduce(async (a, { prop: r, args: i }) => (await a)[r](
import { prepareDataForProxy as y, transformData as d } from "../../transform.js";
const i = async (n, s) => s.reduce(async (t, { prop: e, args: f }) => (await t)[e](
...await Promise.all(
i.map(async (s) => Array.isArray(s.data) ? Promise.all(
s.data.map((t) => "__bindingId" in t ? c(e, t.__calls) : t)
) : s.transform ? p(s.data, s.transform) : s.data)
f.map(async (o) => Array.isArray(o.data) ? Promise.all(
o.data.map((a) => "__bindingId" in a ? i(n, a.__calls) : a)
) : o.transform ? d(o.data, o.transform) : o.data)
)
), Promise.resolve(e)), u = {
async fetch(e, n) {
if (e.method !== "POST")
), Promise.resolve(n)), m = {
async fetch(n, s) {
if (n.method !== "POST")
return new Response("Method not allowed", { status: 405 });
try {
const { __original_call: a, __bindingId: r, __calls: i } = await e.json(), s = a ? await c(n[a.__bindingId], a.__calls) : n[r], t = await c(s, i), o = { success: !0, data: t };
if (o.success) {
const d = await l(t, { data: t });
o.transform = d.transform, o.data = d.data;
const { __original_call: t, __bindingId: e, __calls: f } = await n.json(), o = t ? await i(s[t.__bindingId], t.__calls) : s[e], a = await i(o, f), r = { success: !0, data: a, functions: {} };
if (r.success) {
const c = await y(a, { data: a });
if (r.transform = c.transform, r.data = c.data, a && typeof a == "object" && !Array.isArray(a)) {
if ("arrayBuffer" in a && typeof a.arrayBuffer == "function") {
const u = await a.arrayBuffer();
r.functions.arrayBuffer = await y(u, {
data: u
});
}
"blob" in a && typeof a.blob == "function" && (r.functions.blob = {
takeDataFrom: "arrayBuffer",
transform: { from: "buffer", to: "blob" }
}), "text" in a && typeof a.text == "function" && (r.functions.text = {
takeDataFrom: "arrayBuffer",
transform: { from: "buffer", to: "text" }
}), "json" in a && typeof a.json == "function" && (r.functions.json = {
takeDataFrom: "arrayBuffer",
transform: { from: "buffer", to: "json" }
}), "body" in a && typeof a.body == "object" && (r.functions.body = {
takeDataFrom: "arrayBuffer",
asAccessor: !0
});
}
}
return new Response(JSON.stringify(o), {
return new Response(JSON.stringify(r), {
status: 200,
headers: { "Content-Type": "application/json" }
});
} catch (a) {
console.error(a);
const r = JSON.stringify({
} catch (t) {
console.error(t);
const e = JSON.stringify({
success: !1,
data: a instanceof Error ? a.message : "Failed to access binding"
data: t instanceof Error ? t.message : "Failed to access binding"
});
return new Response(r, {
return new Response(e, {
status: 500,

@@ -36,4 +56,4 @@ headers: { "Content-Type": "application/json" }

export {
u as default
m as default
};
//# sourceMappingURL=_worker.js.map
{
"name": "cf-bindings-proxy",
"version": "0.4.1",
"description": "Experimental proxy for interfacing with bindings in projects targeting Cloudflare Pages",
"license": "MIT",
"author": "James",
"type": "module",
"bin": "./cli/index.js",
"exports": {
".": {
"import": "./index.js",
"require": "./index.cjs"
}
},
"publishConfig": {
"directory": "dist"
},
"repository": {
"type": "git",
"url": "https://github.com/james-elicx/cf-bindings-proxy"
},
"bugs": {
"url": "https://github.com/james-elicx/cf-bindings-proxy/issues"
},
"homepage": "https://github.com/james-elicx/cf-bindings-proxy#readme",
"scripts": {
"dev": "node ./cli/index.js",
"build": "vite build && node ./scripts/build.js",
"build:watch": "npm run build --watch",
"lint": "eslint \"./**/*.{cjs,js,jsx,ts,tsx}\"",
"prettier": "prettier --ignore-unknown --ignore-path=.gitignore --check .",
"prettier:format": "prettier --ignore-unknown --ignore-path=.gitignore --write .",
"tsc": "tsc --noEmit",
"test": "vitest run",
"test:kill": "rm -rf .wrangler; sudo kill -9 `sudo lsof -i :8799 -t`",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"alter-version": "node ./scripts/alter-version.js",
"release": "changeset publish"
},
"devDependencies": {
"@changesets/cli": "^2.26.2",
"@cloudflare/workers-types": "^4.20230814.0",
"@tsconfig/strictest": "^2.0.1",
"@types/node": "^20.3.3",
"eslint": "^8.41.0",
"eslint-config-ixn": "^1.4.2",
"kysely": "^0.26.1",
"kysely-d1": "^0.3.0",
"nodemon": "^2.0.22",
"prettier": "^2.8.8",
"typescript": "^5.0.4",
"vite": "^4.3.5",
"vite-plugin-dts": "^2.3.0",
"vite-plugin-externalize-deps": "^0.6.0",
"vitest": "^0.31.0",
"vitest-environment-miniflare": "^2.14.0",
"wrangler": "^3.6.0"
},
"peerDependencies": {
"@cloudflare/workers-types": ">=4",
"wrangler": ">=3.0.0"
}
"name": "cf-bindings-proxy",
"version": "0.5.0-50ff06b",
"description": "Experimental proxy for interfacing with bindings in projects targeting Cloudflare Pages",
"license": "MIT",
"author": "James",
"type": "module",
"bin": "./cli/index.js",
"exports": {
".": {
"import": "./index.js",
"require": "./index.cjs"
}
},
"publishConfig": {
"directory": "dist"
},
"repository": {
"type": "git",
"url": "https://github.com/james-elicx/cf-bindings-proxy"
},
"bugs": {
"url": "https://github.com/james-elicx/cf-bindings-proxy/issues"
},
"homepage": "https://github.com/james-elicx/cf-bindings-proxy#readme",
"scripts": {
"dev": "node ./cli/index.js",
"build": "vite build && node ./scripts/build.js",
"build:watch": "npm run build --watch",
"lint": "eslint \"./**/*.{cjs,js,jsx,ts,tsx}\"",
"prettier": "prettier --ignore-unknown --ignore-path=.gitignore --check .",
"prettier:format": "prettier --ignore-unknown --ignore-path=.gitignore --write .",
"tsc": "tsc --noEmit",
"test": "vitest run",
"test:kill": "rm -rf .wrangler; sudo kill -9 `sudo lsof -i :8799 -t`",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"alter-version": "node ./scripts/alter-version.js",
"release": "changeset publish"
},
"devDependencies": {
"@changesets/cli": "^2.26.2",
"@cloudflare/workers-types": "^4.20230814.0",
"@tsconfig/strictest": "^2.0.1",
"@types/node": "^20.3.3",
"eslint": "^8.41.0",
"eslint-config-ixn": "^1.4.2",
"kysely": "^0.26.1",
"kysely-d1": "^0.3.0",
"nodemon": "^2.0.22",
"prettier": "^2.8.8",
"typescript": "^5.0.4",
"vite": "^4.3.5",
"vite-plugin-dts": "^2.3.0",
"vite-plugin-externalize-deps": "^0.6.0",
"vitest": "^0.31.0",
"vitest-environment-miniflare": "^2.14.0",
"wrangler": "^3.6.0"
},
"peerDependencies": {
"@cloudflare/workers-types": ">=4",
"wrangler": ">=3.0.0"
},
"versionMetadata": {
"type": "BETA"
}
}

@@ -0,1 +1,2 @@

import type { FunctionInfo, Functions, ParseType, TransformRule } from './transform';
export type BindingResponse = {

@@ -5,18 +6,16 @@ success: false;

transform?: never;
functions?: never;
} | {
success: true;
data: unknown;
transform?: {
from: string;
to: string;
transform?: TransformRule;
functions: {
[key in Functions]?: FunctionInfo;
};
};
export type PropertyCall = {
export type PropertyCall<Transform extends TransformRule | undefined = TransformRule | undefined> = {
prop: string;
args: {
data: unknown | BindingRequest[];
transform?: {
from: string;
to: string;
};
data: (Transform extends TransformRule ? ParseType<Transform['from']> : unknown) | BindingRequest[];
transform?: Transform;
}[];

@@ -23,0 +22,0 @@ };

@@ -1,16 +0,16 @@

import { transformData as u, prepareDataForProxy as _ } from "./transform.js";
const f = async (r) => ({
...r,
import { transformData as g, transformFunctionInfo as b, prepareDataForProxy as w } from "./transform.js";
const x = async (o) => ({
...o,
__calls: await Promise.all(
r.__calls.map(async (o) => ({
...o,
args: await Promise.all(o.args.map((n) => _(n.data, n)))
o.__calls.map(async (a) => ({
...a,
args: await Promise.all(a.args.map((n) => w(n.data, n)))
}))
)
}), s = async (r) => {
const o = await f(r);
let n;
}), d = async (o) => {
const a = await x(o), n = JSON.stringify(a);
let i;
try {
n = await fetch("http://127.0.0.1:8799", {
body: JSON.stringify(o),
i = await fetch("http://127.0.0.1:8799", {
body: n,
method: "POST",

@@ -23,38 +23,71 @@ cache: "no-store",

}
const { success: c, data: t, transform: i } = await n.json();
if (!c)
throw new Error(t || "Bad response from binding proxy");
return i ? u(t, i) : t;
}, y = (r, o, n) => new Proxy(n, {
get(c, t) {
if (!n || ["then", Symbol.iterator, Symbol.toStringTag].includes(t))
const { success: e, data: r, transform: t, functions: s } = await i.json();
if (!e)
throw new Error(r || "Bad response from binding proxy");
const c = t ? g(r, t) : r;
if (s && c && typeof c == "object" && !Array.isArray(c))
for (const [f, u] of Object.entries(s)) {
const l = await b(u, s);
if (u.asAccessor) {
const y = typeof l == "function" && !(l instanceof Blob) ? await l() : l;
if (f === "body") {
const _ = new ReadableStream({
start(h) {
h.enqueue(y), h.close();
}
});
Object.defineProperties(c, {
body: {
get() {
return _;
}
},
bodyUsed: {
get() {
return _.locked;
}
}
});
} else
Object.defineProperty(c, f, {
get() {
return y;
}
});
} else
c[f] = l;
}
return c;
}, p = (o, a, n) => new Proxy(n, {
get(i, e) {
if (!n || ["then", Symbol.iterator, Symbol.toStringTag].includes(e))
return;
if (t in n || ["error", "results"].includes(t))
return n[t];
if (Array.isArray(n) && typeof t == "string" && !Number.isNaN(Number(t)))
return n[Number(t)];
if (["toJSON"].includes(t))
if (e in n || ["error", "results"].includes(e))
return n[e];
if (Array.isArray(n) && typeof e == "string" && !Number.isNaN(Number(e)))
return n[Number(e)];
if (["toJSON"].includes(e))
return n;
if (t === "writeHttpMetadata" && n && typeof n == "object") {
const e = n.httpMetadata || {};
return (a) => {
e.cacheControl && a.set("cache-control", e.cacheControl), e.cacheExpiry && a.set("expires", e.cacheExpiry.toUTCString()), e.contentDisposition && a.set("content-disposition", e.contentDisposition), e.contentEncoding && a.set("content-encoding", e.contentEncoding), e.contentLanguage && a.set("content-language", e.contentLanguage), e.contentType && a.set("content-type", e.contentType);
if (e === "writeHttpMetadata" && n && typeof n == "object") {
const t = n.httpMetadata || {};
return (s) => {
t.cacheControl && s.set("cache-control", t.cacheControl), t.cacheExpiry && s.set("expires", t.cacheExpiry.toUTCString()), t.contentDisposition && s.set("content-disposition", t.contentDisposition), t.contentEncoding && s.set("content-encoding", t.contentEncoding), t.contentLanguage && s.set("content-language", t.contentLanguage), t.contentType && s.set("content-type", t.contentType);
};
}
const i = l(r, !0);
return i.__original_call = o, async (...e) => (i.__calls.push({ prop: t, args: e.map((a) => ({ data: a })) }), s(i));
const r = m(o, !0);
return r.__original_call = a, async (...t) => (r.__calls.push({ prop: e, args: t.map((s) => ({ data: s })) }), d(r));
}
}), h = (r) => ["prepare"].includes(r) ? ["first", "run", "all", "raw"] : [], l = (r, o = !1) => new Proxy({ __bindingId: r, __calls: [], __chainUntil: [] }, {
get(n, c) {
if (typeof c == "string" && c.startsWith("__"))
return n[c];
if (c !== "toJSON" && !o && !(n.__calls.length === 0 && c === "then")) {
if (n.__chainUntil.length || (n.__chainUntil = h(c)), n.__chainUntil.length && !n.__chainUntil.includes(c)) {
const t = l(r);
return t.__chainUntil = n.__chainUntil, t.__calls = n.__calls, (...i) => (n.__calls.push({ prop: c, args: i.map((e) => ({ data: e })) }), t);
}), P = (o) => ["prepare"].includes(o) ? ["first", "run", "all", "raw"] : [], m = (o, a = !1) => new Proxy({ __bindingId: o, __calls: [], __chainUntil: [] }, {
get(n, i) {
if (typeof i == "string" && i.startsWith("__"))
return n[i];
if (i !== "toJSON" && !a && !(n.__calls.length === 0 && i === "then")) {
if (n.__chainUntil.length || (n.__chainUntil = P(i)), n.__chainUntil.length && !n.__chainUntil.includes(i)) {
const e = m(o);
return e.__chainUntil = n.__chainUntil, e.__calls = n.__calls, (...r) => (n.__calls.push({ prop: i, args: r.map((t) => ({ data: t })) }), e);
}
return async (...t) => {
n.__calls.push({ prop: c, args: t.map((e) => ({ data: e })) });
const i = await s(n);
return typeof i != "object" || !i ? i : y(r, n, i);
return async (...e) => {
n.__calls.push({ prop: i, args: e.map((t) => ({ data: t })) });
const r = await d(n);
return typeof r != "object" || !r || Array.isArray(r) ? r : p(o, n, r);
};

@@ -65,4 +98,4 @@ }

export {
l as createBindingProxy
m as createBindingProxy
};
//# sourceMappingURL=proxy.js.map

@@ -100,2 +100,6 @@ <p align="center">

- [x] writeHttpMetadata
- [x] _value type_: ArrayBuffer
- [x] _value type_: string
- [x] _value type_: Blob
- [x] _value type_: ReadableStream
- [x] get

@@ -107,4 +111,4 @@ - [x] writeHttpMetadata

- [x] blob
- [ ] body
- [ ] bodyUsed
- [x] body
- [x] bodyUsed
- [x] head

@@ -115,3 +119,3 @@ - [x] writeHttpMetadata

- [x] delete
- [ ] createMultipartUpload
- [ ] resumeMultipartUpload
- [ ] createMultipartUpload (needs more tests)
- [ ] resumeMultipartUpload (needs more tests)
import type { PropertyCall } from './proxy';
export type TransformDataType = 'buffer' | 'blob' | 'stream' | 'base64' | 'text' | 'json';
export type TransformRawType = ArrayBuffer | Blob | string | NonNullable<object>;
type ParseTransformFrom<T extends TransformDataType> = T extends 'buffer' ? Extract<TransformDataType, 'base64' | 'text' | 'json'> : T extends 'blob' ? Extract<TransformDataType, 'base64'> : T extends 'stream' ? Extract<TransformDataType, 'base64'> : T extends 'base64' ? Extract<TransformDataType, 'buffer' | 'blob' | 'stream'> : never;
export type TransformRule<From extends TransformDataType = TransformDataType, To extends ParseTransformFrom<From> = ParseTransformFrom<From>> = {
from: From;
to: To;
};
export type ParseType<T extends TransformDataType> = T extends 'buffer' ? ArrayBuffer : T extends 'blob' ? Blob : T extends 'stream' ? ReadableStream : T extends 'base64' | 'text' ? string : T extends 'json' ? NonNullable<object> : never;
export type Functions = 'arrayBuffer' | 'blob' | 'json' | 'text' | 'body';
export type FunctionInfo<DataTransformRule extends TransformRule | undefined = TransformRule | undefined, Data = DataTransformRule extends TransformRule ? ParseType<DataTransformRule['to']> : undefined> = ({
data: Data;
takeDataFrom?: never;
} | {
data?: never;
takeDataFrom: Functions;
}) & {
transform?: DataTransformRule;
asAccessor?: boolean;
};
/**

@@ -9,6 +28,3 @@ * Transforms data from one format to another.

*/
export declare const transformData: (data: unknown, transform: {
from: string;
to: string;
}) => Promise<unknown>;
export declare const transformData: <From extends TransformDataType, To extends ParseTransformFrom<From>>(data: ParseType<From>, transform: TransformRule<From, To>) => Promise<ParseType<To>>;
/**

@@ -22,3 +38,10 @@ * Prepares the argument's data to be sent over HTTP via the binding proxy.

type PropertyCallArg = PropertyCall['args'][0];
export declare const transformFunctionInfo: <Fn extends FunctionInfo<TransformRule<TransformDataType, "buffer" | "blob" | "stream" | "base64" | "text" | "json"> | undefined, string | object | ArrayBuffer | Blob | ReadableStream<any> | undefined>>({ data, takeDataFrom, transform }: Fn, fns: {
blob?: FunctionInfo<TransformRule<TransformDataType, "buffer" | "blob" | "stream" | "base64" | "text" | "json"> | undefined, string | object | ArrayBuffer | Blob | ReadableStream<any> | undefined> | undefined;
text?: FunctionInfo<TransformRule<TransformDataType, "buffer" | "blob" | "stream" | "base64" | "text" | "json"> | undefined, string | object | ArrayBuffer | Blob | ReadableStream<any> | undefined> | undefined;
json?: FunctionInfo<TransformRule<TransformDataType, "buffer" | "blob" | "stream" | "base64" | "text" | "json"> | undefined, string | object | ArrayBuffer | Blob | ReadableStream<any> | undefined> | undefined;
arrayBuffer?: FunctionInfo<TransformRule<TransformDataType, "buffer" | "blob" | "stream" | "base64" | "text" | "json"> | undefined, string | object | ArrayBuffer | Blob | ReadableStream<any> | undefined> | undefined;
body?: FunctionInfo<TransformRule<TransformDataType, "buffer" | "blob" | "stream" | "base64" | "text" | "json"> | undefined, string | object | ArrayBuffer | Blob | ReadableStream<any> | undefined> | undefined;
}) => Promise<TransformRawType | (() => TransformRawType | Promise<TransformRawType>)>;
export {};
//# sourceMappingURL=transform.d.ts.map

@@ -1,31 +0,79 @@

const o = async (r, e) => {
if (e.from === "buffer" && e.to === "base64") {
const f = new Uint8Array(r);
let t = "";
for (let b = 0; b < f.byteLength; b++)
t += String.fromCharCode(f[b]);
return btoa(t);
const f = async (e, t) => {
switch (t.from) {
case "buffer": {
if (t.to === "blob")
return new Blob([e]);
if (t.to === "base64") {
const n = new Uint8Array(e);
let o = "";
for (let b = 0; b < n.byteLength; b++)
o += String.fromCharCode(n[b]);
return btoa(o);
}
const r = new TextDecoder().decode(e);
if (t.to === "text")
return r;
if (t.to === "json")
return JSON.parse(r);
break;
}
case "blob": {
if (t.to === "base64") {
const r = await e.arrayBuffer();
return f(r, { from: "buffer", to: "base64" });
}
break;
}
case "stream": {
if (t.to === "base64") {
const r = await e.getReader().read();
return f(r.value, {
from: "buffer",
to: "base64"
});
}
break;
}
case "base64": {
if (t.to === "buffer")
return Uint8Array.from(atob(e), (r) => r.charCodeAt(0)).buffer;
if (t.to === "blob") {
const r = await f(e, {
from: "base64",
to: "buffer"
});
return new Blob([r]);
}
if (t.to === "stream") {
const r = await f(e, {
from: "base64",
to: "buffer"
}), { readable: n, writable: o } = new FixedLengthStream(r.byteLength), b = o.getWriter();
return b.write(r), b.close(), n;
}
break;
}
}
if (e.from === "base64" && e.to === "buffer")
return Uint8Array.from(atob(r), (f) => f.charCodeAt(0)).buffer;
if (e.from === "blob" && e.to === "base64") {
const f = await r.arrayBuffer();
return o(f, { from: "buffer", to: "base64" });
}
if (e.from === "base64" && e.to === "blob") {
const f = await o(r, { from: "base64", to: "buffer" });
return new Blob([f]);
}
return r;
}, n = async (r, e) => r instanceof ArrayBuffer ? {
return e;
}, i = async (e, t) => e instanceof ArrayBuffer ? {
transform: { from: "base64", to: "buffer" },
data: await o(r, { from: "buffer", to: "base64" })
} : r instanceof Blob ? {
data: await f(e, { from: "buffer", to: "base64" })
} : e instanceof Blob ? {
transform: { from: "base64", to: "blob" },
data: await o(r, { from: "blob", to: "base64" })
} : e;
data: await f(e, { from: "blob", to: "base64" })
} : e !== null && typeof e == "object" && "getReader" in e && typeof e.getReader == "function" ? {
transform: { from: "base64", to: "stream" },
data: await f(e, { from: "stream", to: "base64" })
} : t, a = async ({ data: e, takeDataFrom: t, transform: r }, n) => {
const o = t ? await a(n[t], n) : e;
return o && r ? async () => {
const s = typeof o == "function" && !(o instanceof Blob) ? await Promise.resolve(o()) : o;
return Promise.resolve(f(s, r));
} : o ?? e;
};
export {
n as prepareDataForProxy,
o as transformData
i as prepareDataForProxy,
f as transformData,
a as transformFunctionInfo
};
//# sourceMappingURL=transform.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc