@secret-momo/cf-bridge 0.0.0-stage → 0.1.0
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 +21 -0
- package/README.md +130 -2
- package/dist/client.d.ts +15 -0
- package/dist/client.js +22 -0
- package/dist/d1.d.ts +7 -0
- package/dist/d1.js +22 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/kv.d.ts +15 -0
- package/dist/kv.js +17 -0
- package/dist/r2.d.ts +14 -0
- package/dist/r2.js +29 -0
- package/dist/transport.d.ts +19 -0
- package/dist/transport.js +110 -0
- package/dist/types.d.ts +67 -0
- package/dist/types.js +1 -0
- package/package.json +54 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 secretmomo
|
|
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
CHANGED
|
@@ -1,3 +1,131 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @secret-momo/cf-bridge
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
这是 cf-bridge Worker 的 TypeScript SDK,用于访问 D1、R2 和 KV。
|
|
4
|
+
SDK 运行时需要 Node.js 20.3 或更高版本;仓库开发和测试使用 Node.js 26.12.1。
|
|
5
|
+
这是 SDK 选择的运行时支持范围,并非 `AbortSignal.any` 最早可用版本的声明。Node.js 18.17 虽已包含该 API,SDK 不承诺 Node.js 18 的兼容性。
|
|
6
|
+
|
|
7
|
+
## 安装
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @secret-momo/cf-bridge
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## 创建客户端
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createBridgeClient } from '@secret-momo/cf-bridge';
|
|
17
|
+
|
|
18
|
+
const bridge = createBridgeClient({
|
|
19
|
+
baseUrl: 'https://cf-bridge.binarykang.workers.dev',
|
|
20
|
+
apiToken: process.env.CF_BRIDGE_API_TOKEN!,
|
|
21
|
+
timeoutMs: 30_000,
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`apiToken` 会作为每次请求的 `x-api-token` 请求头发送。请将令牌保存在服务端环境中,不要放进浏览器代码。
|
|
26
|
+
SDK 拒绝所有 HTTP 重定向(包括同源重定向),请将 `baseUrl` 配置为最终接口地址;注入的自定义 `fetch` 也需要遵守 `redirect: 'error'` 选项。
|
|
27
|
+
请求默认在等待响应头超过 30 秒时取消;可通过 `timeoutMs` 调整,设为 `0` 则关闭。该计时包括上传请求体和等待服务端处理的时间;收到响应头后会清除计时器,后续下载或 JSON 响应体读取不受此超时限制。上传大对象或执行较慢的批量 SQL 时,请按需调整。
|
|
28
|
+
客户端的 `signal` 可统一取消请求,每个方法的最后一个参数也接受 `{ signal }`;两者均可中断后续响应体读取。传入依赖 `this` 的自定义 `fetch` 方法时,请先绑定所属对象,例如 `fetch: api.fetch.bind(api)`。
|
|
29
|
+
|
|
30
|
+
SDK 默认不为响应体读取设置截止时间。若需要限制包含下载在内的整个请求,请显式传入有截止时间的 `signal`;以下信号从创建起 5 分钟后取消,响应头仍受客户端 `timeoutMs` 约束:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
const download = await bridge.r2.get('big.bin', {
|
|
34
|
+
signal: AbortSignal.timeout(5 * 60_000),
|
|
35
|
+
});
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## D1
|
|
39
|
+
|
|
40
|
+
`default`、`v2ex` 和 `nexus` 是可选的数据库名称。使用 `execute` 执行单条建表、修改表或写入语句,使用 `query` 获取查询结果;动态值通过 `params` 绑定。
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
await bridge.d1.execute('default', {
|
|
44
|
+
sql: 'CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT)',
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
await bridge.d1.execute('default', {
|
|
48
|
+
sql: 'INSERT INTO notes (text) VALUES (?)',
|
|
49
|
+
params: ['你好'],
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
const { results, meta } = await bridge.d1.query<{ id: number; text: string }>('default', {
|
|
53
|
+
sql: 'SELECT id, text FROM notes WHERE text = ?',
|
|
54
|
+
params: ['你好'],
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
多条语句使用 `batch`。同一批次中的语句会按顺序在一个事务中执行,失败时回滚。
|
|
59
|
+
|
|
60
|
+
布尔参数写入 D1 时保存为整数 `1` 或 `0`,读取时返回数字。当前网关不支持通过 JSON 参数写入 BLOB。执行语句的 `results` 字段可能为 `null`;查询方法的 `results` 始终是数组。
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
const batchResults = await bridge.d1.batch('v2ex', [
|
|
64
|
+
{ sql: 'CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name TEXT)' },
|
|
65
|
+
{ sql: 'INSERT INTO items (name) VALUES (?)', params: ['示例'] },
|
|
66
|
+
]);
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## R2
|
|
70
|
+
|
|
71
|
+
`put` 直接上传二进制内容;第三个参数可设置对象的内容类型。`get` 返回标准 `Response`,可以读取响应头并按需消费字节流。
|
|
72
|
+
|
|
73
|
+
`put` 当前只写入对象内容和 `Content-Type`,不写入自定义元数据。`list({ include: ['customMetadata'] })` 可读取同一存储桶中已有的自定义元数据,例如由其他工具写入的元数据。
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
await bridge.r2.put('docs/hello.txt', new Blob(['你好']), 'text/plain');
|
|
77
|
+
|
|
78
|
+
const response = await bridge.r2.get('docs/hello.txt');
|
|
79
|
+
const text = await response.text();
|
|
80
|
+
const contentType = response.headers.get('content-type');
|
|
81
|
+
|
|
82
|
+
const page = await bridge.r2.list({ prefix: 'docs/', limit: 100 });
|
|
83
|
+
const folders = await bridge.r2.list({
|
|
84
|
+
prefix: 'docs/',
|
|
85
|
+
delimiter: '/',
|
|
86
|
+
include: ['httpMetadata'],
|
|
87
|
+
});
|
|
88
|
+
const nextPage = page.cursor
|
|
89
|
+
? await bridge.r2.list({ prefix: 'docs/', cursor: page.cursor, limit: 100 })
|
|
90
|
+
: null;
|
|
91
|
+
|
|
92
|
+
await bridge.r2.delete('docs/hello.txt');
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## KV
|
|
96
|
+
|
|
97
|
+
KV 存储字符串。若要保存对象,请自行进行 JSON 序列化和解析。写入时可指定过期秒数 `expirationTtl` 和 JSON 元数据。KV 采用最终一致性,不适合依赖即时读取结果的协调逻辑。
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
await bridge.kv.put('settings:theme', JSON.stringify({ theme: 'dark' }), {
|
|
101
|
+
expirationTtl: 3600,
|
|
102
|
+
metadata: { owner: 'app' },
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const entry = await bridge.kv.get('settings:theme');
|
|
106
|
+
const settings = JSON.parse(entry.value);
|
|
107
|
+
const metadata = entry.metadata;
|
|
108
|
+
|
|
109
|
+
const page = await bridge.kv.list({ prefix: 'settings:', limit: 100 });
|
|
110
|
+
const nextPage = page.cursor
|
|
111
|
+
? await bridge.kv.list({ prefix: 'settings:', cursor: page.cursor, limit: 100 })
|
|
112
|
+
: null;
|
|
113
|
+
|
|
114
|
+
await bridge.kv.delete('settings:theme');
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## 错误处理
|
|
118
|
+
|
|
119
|
+
除成功的 R2 下载外,SDK 会取出统一响应中的 `data` 并返回。请求失败时抛出 `BridgeError`,其中包含 HTTP 状态码 `status`、业务码 `code` 和错误信息 `message`。
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import { BridgeError } from '@secret-momo/cf-bridge';
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
await bridge.kv.get('missing');
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error instanceof BridgeError && error.status === 404) {
|
|
128
|
+
// 键不存在
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
```
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createD1Client } from './d1.js';
|
|
2
|
+
import { createKvClient } from './kv.js';
|
|
3
|
+
import { createR2Client } from './r2.js';
|
|
4
|
+
import type { BridgeClientOptions, RequestOptions } from './types.js';
|
|
5
|
+
export declare class BridgeClient {
|
|
6
|
+
readonly d1: ReturnType<typeof createD1Client>;
|
|
7
|
+
readonly r2: ReturnType<typeof createR2Client>;
|
|
8
|
+
readonly kv: ReturnType<typeof createKvClient>;
|
|
9
|
+
private readonly transport;
|
|
10
|
+
constructor(options: BridgeClientOptions);
|
|
11
|
+
health(options?: RequestOptions): Promise<{
|
|
12
|
+
status: string;
|
|
13
|
+
}>;
|
|
14
|
+
}
|
|
15
|
+
export declare function createBridgeClient(options: BridgeClientOptions): BridgeClient;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { createD1Client } from './d1.js';
|
|
2
|
+
import { createKvClient } from './kv.js';
|
|
3
|
+
import { createR2Client } from './r2.js';
|
|
4
|
+
import { Transport } from './transport.js';
|
|
5
|
+
export class BridgeClient {
|
|
6
|
+
d1;
|
|
7
|
+
r2;
|
|
8
|
+
kv;
|
|
9
|
+
transport;
|
|
10
|
+
constructor(options) {
|
|
11
|
+
this.transport = new Transport(options);
|
|
12
|
+
this.d1 = createD1Client(this.transport);
|
|
13
|
+
this.r2 = createR2Client(this.transport);
|
|
14
|
+
this.kv = createKvClient(this.transport);
|
|
15
|
+
}
|
|
16
|
+
health(options = {}) {
|
|
17
|
+
return this.transport.json('/v1/health', options);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function createBridgeClient(options) {
|
|
21
|
+
return new BridgeClient(options);
|
|
22
|
+
}
|
package/dist/d1.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { D1QueryResult, D1Result, DatabaseName, RequestOptions, SqlStatement } from './types.js';
|
|
2
|
+
import type { Transport } from './transport.js';
|
|
3
|
+
export declare function createD1Client(transport: Transport): {
|
|
4
|
+
query: <Row = Record<string, unknown>>(database: DatabaseName, statement: SqlStatement, options?: RequestOptions) => Promise<D1QueryResult<Row>>;
|
|
5
|
+
execute: (database: DatabaseName, statement: SqlStatement, options?: RequestOptions) => Promise<D1Result>;
|
|
6
|
+
batch: (database: DatabaseName, statements: SqlStatement[], options?: RequestOptions) => Promise<D1Result[]>;
|
|
7
|
+
};
|
package/dist/d1.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export function createD1Client(transport) {
|
|
2
|
+
return {
|
|
3
|
+
query: (database, statement, options = {}) => transport.json(`/v1/d1/${database}/query`, {
|
|
4
|
+
...options,
|
|
5
|
+
method: 'POST',
|
|
6
|
+
body: JSON.stringify(statement),
|
|
7
|
+
headers: { 'content-type': 'application/json' },
|
|
8
|
+
}),
|
|
9
|
+
execute: (database, statement, options = {}) => transport.json(`/v1/d1/${database}/execute`, {
|
|
10
|
+
...options,
|
|
11
|
+
method: 'POST',
|
|
12
|
+
body: JSON.stringify(statement),
|
|
13
|
+
headers: { 'content-type': 'application/json' },
|
|
14
|
+
}),
|
|
15
|
+
batch: (database, statements, options = {}) => transport.json(`/v1/d1/${database}/batch`, {
|
|
16
|
+
...options,
|
|
17
|
+
method: 'POST',
|
|
18
|
+
body: JSON.stringify({ statements }),
|
|
19
|
+
headers: { 'content-type': 'application/json' },
|
|
20
|
+
}),
|
|
21
|
+
};
|
|
22
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { BridgeClient, createBridgeClient } from './client.js';
|
|
2
|
+
export { BridgeError } from './transport.js';
|
|
3
|
+
export type { ApiEnvelope, BridgeClientOptions, D1QueryResult, D1Result, DatabaseName, KvListResult, KvPutOptions, ListOptions, R2ListOptions, R2ListResult, R2ObjectInfo, SqlStatement, SqlValue, RequestOptions, } from './types.js';
|
package/dist/index.js
ADDED
package/dist/kv.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { KvListResult, KvPutOptions, ListOptions, RequestOptions } from './types.js';
|
|
2
|
+
import { type Transport } from './transport.js';
|
|
3
|
+
export declare function createKvClient(transport: Transport): {
|
|
4
|
+
list: (options?: ListOptions, requestOptions?: RequestOptions) => Promise<KvListResult>;
|
|
5
|
+
get: (key: string, options?: RequestOptions) => Promise<{
|
|
6
|
+
value: string;
|
|
7
|
+
metadata: Record<string, unknown> | null;
|
|
8
|
+
}>;
|
|
9
|
+
put: (key: string, value: string, options?: KvPutOptions, requestOptions?: RequestOptions) => Promise<{
|
|
10
|
+
key: string;
|
|
11
|
+
}>;
|
|
12
|
+
delete: (key: string, options?: RequestOptions) => Promise<{
|
|
13
|
+
key: string;
|
|
14
|
+
}>;
|
|
15
|
+
};
|
package/dist/kv.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { withQuery } from './transport.js';
|
|
2
|
+
export function createKvClient(transport) {
|
|
3
|
+
return {
|
|
4
|
+
list: (options = {}, requestOptions = {}) => transport.json(withQuery('/v1/kv/keys', options), requestOptions),
|
|
5
|
+
get: (key, options = {}) => transport.json(withQuery('/v1/kv/value', { key }), options),
|
|
6
|
+
put: (key, value, options = {}, requestOptions = {}) => transport.json(withQuery('/v1/kv/value', { key }), {
|
|
7
|
+
...requestOptions,
|
|
8
|
+
method: 'PUT',
|
|
9
|
+
body: JSON.stringify({ value, ...options }),
|
|
10
|
+
headers: { 'content-type': 'application/json' },
|
|
11
|
+
}),
|
|
12
|
+
delete: (key, options = {}) => transport.json(withQuery('/v1/kv/value', { key }), {
|
|
13
|
+
...options,
|
|
14
|
+
method: 'DELETE',
|
|
15
|
+
}),
|
|
16
|
+
};
|
|
17
|
+
}
|
package/dist/r2.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { R2ListOptions, R2ListResult, RequestOptions } from './types.js';
|
|
2
|
+
import { type Transport } from './transport.js';
|
|
3
|
+
export declare function createR2Client(transport: Transport): {
|
|
4
|
+
list: (options?: R2ListOptions, requestOptions?: RequestOptions) => Promise<R2ListResult>;
|
|
5
|
+
get: (key: string, options?: RequestOptions) => Promise<Response>;
|
|
6
|
+
put: (key: string, value: BodyInit, contentType?: string, options?: RequestOptions) => Promise<{
|
|
7
|
+
key: string;
|
|
8
|
+
etag: string;
|
|
9
|
+
size: number;
|
|
10
|
+
}>;
|
|
11
|
+
delete: (key: string, options?: RequestOptions) => Promise<{
|
|
12
|
+
key: string;
|
|
13
|
+
}>;
|
|
14
|
+
};
|
package/dist/r2.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { withQuery } from './transport.js';
|
|
2
|
+
export function createR2Client(transport) {
|
|
3
|
+
return {
|
|
4
|
+
list: (options = {}, requestOptions = {}) => {
|
|
5
|
+
const path = withQuery('/v1/r2/objects', {
|
|
6
|
+
prefix: options.prefix,
|
|
7
|
+
cursor: options.cursor,
|
|
8
|
+
limit: options.limit,
|
|
9
|
+
delimiter: options.delimiter,
|
|
10
|
+
});
|
|
11
|
+
const params = new URLSearchParams();
|
|
12
|
+
for (const value of options.include ?? [])
|
|
13
|
+
params.append('include', value);
|
|
14
|
+
const suffix = params.toString();
|
|
15
|
+
return transport.json(suffix ? `${path}${path.includes('?') ? '&' : '?'}${suffix}` : path, requestOptions);
|
|
16
|
+
},
|
|
17
|
+
get: (key, options = {}) => transport.binary(withQuery('/v1/r2/object', { key }), options),
|
|
18
|
+
put: (key, value, contentType, options = {}) => transport.json(withQuery('/v1/r2/object', { key }), {
|
|
19
|
+
...options,
|
|
20
|
+
method: 'PUT',
|
|
21
|
+
body: value,
|
|
22
|
+
headers: contentType ? { 'content-type': contentType } : undefined,
|
|
23
|
+
}),
|
|
24
|
+
delete: (key, options = {}) => transport.json(withQuery('/v1/r2/object', { key }), {
|
|
25
|
+
...options,
|
|
26
|
+
method: 'DELETE',
|
|
27
|
+
}),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { BridgeClientOptions } from './types.js';
|
|
2
|
+
export declare class BridgeError extends Error {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly code: number;
|
|
5
|
+
constructor(status: number, code: number, message: string);
|
|
6
|
+
}
|
|
7
|
+
export declare function withQuery(path: string, query: Record<string, string | number | undefined>): string;
|
|
8
|
+
export declare class Transport {
|
|
9
|
+
private readonly baseUrl;
|
|
10
|
+
private readonly apiToken;
|
|
11
|
+
private readonly fetcher;
|
|
12
|
+
private readonly timeoutMs;
|
|
13
|
+
private readonly signal?;
|
|
14
|
+
constructor(options: BridgeClientOptions);
|
|
15
|
+
json<T>(path: string, init?: RequestInit): Promise<T>;
|
|
16
|
+
binary(path: string, init?: RequestInit): Promise<Response>;
|
|
17
|
+
private readError;
|
|
18
|
+
private fetchResponse;
|
|
19
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
export class BridgeError extends Error {
|
|
2
|
+
status;
|
|
3
|
+
code;
|
|
4
|
+
constructor(status, code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'BridgeError';
|
|
7
|
+
this.status = status;
|
|
8
|
+
this.code = code;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export function withQuery(path, query) {
|
|
12
|
+
const params = new URLSearchParams();
|
|
13
|
+
for (const [key, value] of Object.entries(query)) {
|
|
14
|
+
if (value !== undefined)
|
|
15
|
+
params.set(key, String(value));
|
|
16
|
+
}
|
|
17
|
+
const suffix = params.toString();
|
|
18
|
+
return suffix ? `${path}?${suffix}` : path;
|
|
19
|
+
}
|
|
20
|
+
export class Transport {
|
|
21
|
+
baseUrl;
|
|
22
|
+
apiToken;
|
|
23
|
+
fetcher;
|
|
24
|
+
timeoutMs;
|
|
25
|
+
signal;
|
|
26
|
+
constructor(options) {
|
|
27
|
+
if (!options.baseUrl || !options.apiToken) {
|
|
28
|
+
throw new TypeError('baseUrl and apiToken are required');
|
|
29
|
+
}
|
|
30
|
+
let url;
|
|
31
|
+
try {
|
|
32
|
+
url = new URL(options.baseUrl);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new TypeError('baseUrl must be a valid URL');
|
|
36
|
+
}
|
|
37
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
38
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) ||
|
|
39
|
+
url.username ||
|
|
40
|
+
url.password ||
|
|
41
|
+
url.search ||
|
|
42
|
+
url.hash) {
|
|
43
|
+
throw new TypeError('baseUrl must use HTTPS, except for local development');
|
|
44
|
+
}
|
|
45
|
+
this.baseUrl = url.href.replace(/\/+$/, '');
|
|
46
|
+
this.apiToken = options.apiToken;
|
|
47
|
+
if (options.timeoutMs !== undefined &&
|
|
48
|
+
(!Number.isSafeInteger(options.timeoutMs) ||
|
|
49
|
+
options.timeoutMs < 0 ||
|
|
50
|
+
options.timeoutMs > 2_147_483_647)) {
|
|
51
|
+
throw new TypeError('timeoutMs must be an integer from 0 to 2147483647');
|
|
52
|
+
}
|
|
53
|
+
this.timeoutMs = options.timeoutMs ?? 30_000;
|
|
54
|
+
this.signal = options.signal;
|
|
55
|
+
this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
56
|
+
}
|
|
57
|
+
async json(path, init) {
|
|
58
|
+
const response = await this.fetchResponse(path, init);
|
|
59
|
+
if (!response.ok)
|
|
60
|
+
throw await this.readError(response);
|
|
61
|
+
const envelope = (await response.json());
|
|
62
|
+
if (envelope.code !== 0) {
|
|
63
|
+
throw new BridgeError(response.status, envelope.code, envelope.message);
|
|
64
|
+
}
|
|
65
|
+
return envelope.data;
|
|
66
|
+
}
|
|
67
|
+
async binary(path, init) {
|
|
68
|
+
const response = await this.fetchResponse(path, init);
|
|
69
|
+
if (!response.ok)
|
|
70
|
+
throw await this.readError(response);
|
|
71
|
+
return response;
|
|
72
|
+
}
|
|
73
|
+
async readError(response) {
|
|
74
|
+
try {
|
|
75
|
+
const envelope = await response.json();
|
|
76
|
+
if (envelope &&
|
|
77
|
+
typeof envelope === 'object' &&
|
|
78
|
+
'code' in envelope &&
|
|
79
|
+
typeof envelope.code === 'number' &&
|
|
80
|
+
'message' in envelope &&
|
|
81
|
+
typeof envelope.message === 'string') {
|
|
82
|
+
return new BridgeError(response.status, envelope.code, envelope.message);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
// Edge or proxy errors may not use the API's JSON envelope.
|
|
87
|
+
}
|
|
88
|
+
return new BridgeError(response.status, response.status, `HTTP ${response.status}`);
|
|
89
|
+
}
|
|
90
|
+
async fetchResponse(path, init = {}) {
|
|
91
|
+
const headers = new Headers(init.headers);
|
|
92
|
+
headers.set('x-api-token', this.apiToken);
|
|
93
|
+
// Custom API token headers must never be forwarded by automatic redirects.
|
|
94
|
+
const request = { ...init, headers, redirect: 'error' };
|
|
95
|
+
const timeout = new AbortController();
|
|
96
|
+
request.signal = AbortSignal.any([init.signal, this.signal, timeout.signal].filter((signal) => signal !== undefined && signal !== null));
|
|
97
|
+
if (init.body instanceof ReadableStream)
|
|
98
|
+
request.duplex = 'half';
|
|
99
|
+
const timer = this.timeoutMs === 0
|
|
100
|
+
? undefined
|
|
101
|
+
: setTimeout(() => timeout.abort(new DOMException('Timed out waiting for response headers', 'TimeoutError')), this.timeoutMs);
|
|
102
|
+
const fetcher = this.fetcher;
|
|
103
|
+
try {
|
|
104
|
+
return await fetcher(`${this.baseUrl}${path}`, request);
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export type DatabaseName = 'default' | 'v2ex' | 'nexus';
|
|
2
|
+
export type SqlValue = string | number | boolean | null;
|
|
3
|
+
export type SqlStatement = {
|
|
4
|
+
sql: string;
|
|
5
|
+
params?: SqlValue[];
|
|
6
|
+
};
|
|
7
|
+
export type ApiEnvelope<T> = {
|
|
8
|
+
code: number;
|
|
9
|
+
data: T;
|
|
10
|
+
message: string;
|
|
11
|
+
};
|
|
12
|
+
export type ListOptions = {
|
|
13
|
+
prefix?: string;
|
|
14
|
+
cursor?: string;
|
|
15
|
+
limit?: number;
|
|
16
|
+
};
|
|
17
|
+
export type RequestOptions = {
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
};
|
|
20
|
+
export type R2ListOptions = ListOptions & {
|
|
21
|
+
delimiter?: string;
|
|
22
|
+
include?: Array<'httpMetadata' | 'customMetadata'>;
|
|
23
|
+
};
|
|
24
|
+
export type KvPutOptions = {
|
|
25
|
+
expirationTtl?: number;
|
|
26
|
+
metadata?: Record<string, unknown>;
|
|
27
|
+
};
|
|
28
|
+
export type D1Result<Row = Record<string, unknown>> = {
|
|
29
|
+
success: boolean;
|
|
30
|
+
results: Row[] | null;
|
|
31
|
+
meta: Record<string, unknown>;
|
|
32
|
+
};
|
|
33
|
+
export type D1QueryResult<Row = Record<string, unknown>> = {
|
|
34
|
+
results: Row[];
|
|
35
|
+
meta: Record<string, unknown>;
|
|
36
|
+
};
|
|
37
|
+
export type R2ObjectInfo = {
|
|
38
|
+
key: string;
|
|
39
|
+
size: number;
|
|
40
|
+
etag: string;
|
|
41
|
+
uploaded: string;
|
|
42
|
+
httpMetadata?: Record<string, unknown>;
|
|
43
|
+
customMetadata?: Record<string, string>;
|
|
44
|
+
};
|
|
45
|
+
export type R2ListResult = {
|
|
46
|
+
objects: R2ObjectInfo[];
|
|
47
|
+
truncated: boolean;
|
|
48
|
+
cursor?: string;
|
|
49
|
+
delimitedPrefixes?: string[];
|
|
50
|
+
};
|
|
51
|
+
export type KvListResult = {
|
|
52
|
+
keys: Array<{
|
|
53
|
+
name: string;
|
|
54
|
+
expiration?: number;
|
|
55
|
+
metadata?: Record<string, unknown>;
|
|
56
|
+
}>;
|
|
57
|
+
list_complete: boolean;
|
|
58
|
+
cursor?: string;
|
|
59
|
+
};
|
|
60
|
+
export type BridgeClientOptions = {
|
|
61
|
+
baseUrl: string;
|
|
62
|
+
apiToken: string;
|
|
63
|
+
fetch?: typeof globalThis.fetch;
|
|
64
|
+
/** Timeout until response headers arrive; 0 disables it. Defaults to 30 seconds. */
|
|
65
|
+
timeoutMs?: number;
|
|
66
|
+
signal?: AbortSignal;
|
|
67
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@secret-momo/cf-bridge",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TypeScript SDK for the cf-bridge Cloudflare Worker",
|
|
5
|
+
"homepage": "https://github.com/secretmomo/cf-bridge/tree/main/packages/sdk",
|
|
6
|
+
"bugs": {
|
|
7
|
+
"url": "https://github.com/secretmomo/cf-bridge/issues"
|
|
8
|
+
},
|
|
9
|
+
"keywords": [
|
|
10
|
+
"cloudflare",
|
|
11
|
+
"workers",
|
|
12
|
+
"d1",
|
|
13
|
+
"r2",
|
|
14
|
+
"kv",
|
|
15
|
+
"sdk",
|
|
16
|
+
"gateway"
|
|
17
|
+
],
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"type": "module",
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=20.3"
|
|
22
|
+
},
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"sideEffects": false,
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public",
|
|
39
|
+
"registry": "https://registry.npmjs.org/"
|
|
40
|
+
},
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "git+https://github.com/secretmomo/cf-bridge.git",
|
|
44
|
+
"directory": "packages/sdk"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"publint": "0.3.25",
|
|
48
|
+
"rimraf": "6.1.3",
|
|
49
|
+
"typescript": "6.0.3"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "rimraf dist && tsc -p tsconfig.build.json",
|
|
53
|
+
"test": "pnpm build && tsc --noEmit -p tsconfig.test.json && node --experimental-test-coverage --test-coverage-include-all --test-coverage-include='dist/*.js' --test-coverage-lines=90 --test-coverage-branches=90 --test-coverage-functions=90 --test src/*.test.ts",
|
|
54
|
+
"lint:package": "publint --strict",
|
|
55
|
+
"typecheck": "tsc --noEmit"
|
|
56
|
+
}
|
|
6
57
|
}
|