@secret-momo/github-db 1.2.0 → 3.0.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/README.md +76 -1
- package/docs/architecture.md +8 -2
- package/docs/caller-api-design.md +1 -0
- package/docs/requirements.md +18 -3
- package/docs/testing.md +4 -3
- package/lib/index.d.ts +46 -6
- package/lib/index.js +7 -6
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -167,6 +167,80 @@ const deletedBatch = await todos.deleteManyById([inserted[0]!.id, 'missing']);
|
|
|
167
167
|
|
|
168
168
|
批量写入用相近的请求数处理整批记录。需要写入多条记录时,优先使用 `insertMany`、`updateManyById` 或 `deleteManyById`。
|
|
169
169
|
|
|
170
|
+
## 独立文件 API
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
const files = client.getDB('app').files;
|
|
174
|
+
const created = await files.create(new Uint8Array([0, 255, 128]));
|
|
175
|
+
const saved = await files.read(created.id); // bytes、sha、byteLength、commitSha
|
|
176
|
+
await files.replace(created.id, new Uint8Array([1, 2]), {
|
|
177
|
+
expectedSha: saved.sha,
|
|
178
|
+
});
|
|
179
|
+
const entries = await files.list(); // 按 ID 排序,不下载文件内容
|
|
180
|
+
await files.delete(created.id);
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
文件存于 `<db>/.github-db-files/<uuid>`,与表独立。只保存原始字节;图片的 MIME、文件名及记录关联由调用方保存。单文件写入上限为 10,000,000 字节,空文件可用。`replace` 可用 `expectedSha` 防止覆盖较新版本;`delete` 也支持同一选项,文件不存在时返回 false。发布结果不明时错误详情包含 `id` 和 `commitSha`,应核验后再重试。替换或删除不会清理 Git 历史中的旧内容。
|
|
184
|
+
|
|
185
|
+
`.github-db-files` 是 2.0.0 起的保留目录。升级前若有同名表,须先在 Git 中将整个表目录改名,SDK 不会自动迁移或覆盖它;`listTables()` 不列出这个保留名。请勿在保留目录手动放入其他内容:符合 UUID 命名的普通 blob 会被当作文件资源。
|
|
186
|
+
|
|
187
|
+
### 在网页中显示图片
|
|
188
|
+
|
|
189
|
+
SDK 仅支持 Node.js/Bun,且读取私有仓库需要 GitHub token。因此在服务端调用 SDK,再通过自己应用中需要鉴权的图片接口返回字节;不要把 GitHub token 放进前端。上传时把文件 ID 和经过校验的 MIME 一起保存在业务记录中,例如:
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
import type { RecordBase } from '@secret-momo/github-db';
|
|
193
|
+
|
|
194
|
+
interface Photo extends RecordBase {
|
|
195
|
+
fileId: string;
|
|
196
|
+
mimeType: 'image/png' | 'image/jpeg' | 'image/webp';
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const photos = db.getRecordTable<Photo>('photos');
|
|
200
|
+
const uploaded = await db.files.create(imageBytes); // imageBytes: Uint8Array
|
|
201
|
+
const photo = await photos.insert({
|
|
202
|
+
fileId: uploaded.id,
|
|
203
|
+
mimeType: 'image/png',
|
|
204
|
+
});
|
|
205
|
+
// 前端保存 photo.id,用它请求自己的图片接口。
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
下面是该接口的核心逻辑。`recordId` 来自路由参数;调用前应完成用户鉴权,并按业务规则检查其是否有权读取这条记录。`res` 是 Node.js 的 `ServerResponse`:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import type { ServerResponse } from 'node:http';
|
|
212
|
+
|
|
213
|
+
async function sendPhoto(recordId: string, res: ServerResponse) {
|
|
214
|
+
const photo = await photos.findById(recordId);
|
|
215
|
+
if (!photo) {
|
|
216
|
+
res.writeHead(404).end();
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const { bytes } = await db.files.read(photo.fileId);
|
|
221
|
+
res.writeHead(200, {
|
|
222
|
+
'Content-Type': photo.mimeType,
|
|
223
|
+
'Content-Length': bytes.byteLength,
|
|
224
|
+
'Cache-Control': 'private, no-store',
|
|
225
|
+
'X-Content-Type-Options': 'nosniff',
|
|
226
|
+
});
|
|
227
|
+
res.end(bytes);
|
|
228
|
+
}
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
前端拿到业务记录的 `photo.id` 后,把自己应用的接口地址赋给图片元素;该路由调用上面的 `sendPhoto`:
|
|
232
|
+
|
|
233
|
+
```html
|
|
234
|
+
<img id="photo" alt="照片" />
|
|
235
|
+
<script>
|
|
236
|
+
const photoId = '业务记录中的 photo.id';
|
|
237
|
+
document.querySelector('#photo').src =
|
|
238
|
+
`/api/photos/${encodeURIComponent(photoId)}`;
|
|
239
|
+
</script>
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
这种方式适用于浏览器会随同源图片请求自动发送登录 Cookie 的应用。如果鉴权依赖必须手动设置的 `Authorization` header,`<img>` 无法附带该 header;改用 `fetch` 获取图片响应,执行 `URL.createObjectURL(await response.blob())` 后赋给 `img.src`,不用时调用 `URL.revokeObjectURL(url)`。文件 ID 本身不是可直接放进 `src` 的 URL。
|
|
243
|
+
|
|
170
244
|
## 底层字符串 API
|
|
171
245
|
|
|
172
246
|
底层只要求每行是 JSON 对象,不要求业务 id 或记录时间字段,也不解析为业务类型:
|
|
@@ -235,6 +309,7 @@ await todos.findAll({ status: 'pending' }, { signal: controller.signal });
|
|
|
235
309
|
写入在发布 PATCH 尚未发送时被取消返回 ABORTED,超时返回 TIMEOUT;SDK 已取得并验证 commitSha 时会附带该 SHA,SHA 尚未取得时不保证该字段。reason 为 BEFORE_PUBLICATION 的已知 commit 取消不会发送 PATCH;取消或超时可能留下未发布的 Git 对象。发布 PATCH 已投递后若结果不确定,返回 WRITE_RESULT_UNKNOWN 并携带尝试 commitSha。
|
|
236
310
|
|
|
237
311
|
- INVALID_INPUT / INVALID_RECORD / DUPLICATE_ID:非法输入、存储记录违反约束或重复主键。
|
|
312
|
+
- FILE_TOO_LARGE:文件写入超过 10,000,000 原始字节。
|
|
238
313
|
- INVALID_METADATA / INVALID_JSONL / INVALID_UTF8:表完整性或文件格式错误。
|
|
239
314
|
- NOT_FOUND / CONFLICT:目标不存在、版本不匹配或发布被拒绝;CONFLICT 的 reason 区分 VERSION_MISMATCH 与 PUBLISH_REJECTED。
|
|
240
315
|
- HTTP_ERROR / NETWORK_ERROR / ABORTED / TIMEOUT:传输及取消错误;3xx 保留 REDIRECT 原因,不跟随。
|
|
@@ -250,7 +325,7 @@ bun run check
|
|
|
250
325
|
bun run test:live # .env 中配置 GITHUB_TOKEN、GITHUB_OWNER、GITHUB_REPO、GITHUB_DB_NAME
|
|
251
326
|
```
|
|
252
327
|
|
|
253
|
-
完整 check 包含类型检查、lint、格式、Bun 单元及原生 HTTP 测试、逐文件行/函数至少 90% 覆盖率、构建、Node 本地 HTTP 和 npm 包的 NodeNext 类型消费测试。test:live
|
|
328
|
+
完整 check 包含类型检查、lint、格式、Bun 单元及原生 HTTP 测试、逐文件行/函数至少 90% 覆盖率、构建、Node 本地 HTTP 和 npm 包的 NodeNext 类型消费测试。test:live 在配置的真实测试仓库创建本轮临时分支,覆盖单表、多张独立表、CRUD、文件 API、空文件及大于 1 MB 的文件;结束时删除该分支并验证引用不存在。GitHub 服务器可能暂时保留不可达对象,删除分支不等于物理清除 blob。
|
|
254
329
|
|
|
255
330
|
构建只输出压缩的 `lib/index.js` 和合并的 `lib/index.d.ts`,无 map。源码内部引用省略扩展名。npm publish 自动执行完整检查,检查包含构建;npm pack 也自动构建,无需人工额外运行 build。
|
|
256
331
|
|
package/docs/architecture.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# GitHub 数据库 SDK 架构
|
|
2
2
|
|
|
3
|
-
当前设计:单表存储、底层字符串 API
|
|
3
|
+
当前设计:单表存储、底层字符串 API、类型化记录 API 与独立文件资源。规范见 [requirements](requirements.md),记录接口见 [record-api-design](record-api-design.md)。
|
|
4
4
|
|
|
5
5
|
## 1. 分层与源码
|
|
6
6
|
|
|
@@ -9,8 +9,10 @@ flowchart TD
|
|
|
9
9
|
Client[GitHubDBClient] --> DB[GitHubDatabase]
|
|
10
10
|
DB --> Raw[GitHubTable:JSONL 字符串]
|
|
11
11
|
DB --> Records[GitHubRecordTable:类型化 CRUD]
|
|
12
|
+
DB --> Files[GitHubFiles:独立二进制文件]
|
|
12
13
|
Raw --> Storage[TableStorage:完整性与快照内提交]
|
|
13
14
|
Records --> Storage
|
|
15
|
+
Files --> Repo
|
|
14
16
|
Records --> Codec[记录 JSON 校验 / 主键 / 条件匹配]
|
|
15
17
|
Storage --> Repo[GitRepository:快照、队列、原子发布]
|
|
16
18
|
Repo --> Tree[GitTreeReader:路径与树缓存]
|
|
@@ -26,6 +28,8 @@ src/
|
|
|
26
28
|
│ ├── database.ts # 底层/高层表工厂
|
|
27
29
|
│ ├── table.ts # 字符串 API 与不透明版本
|
|
28
30
|
│ └── options.ts # 操作选项/取消校验
|
|
31
|
+
├── files/
|
|
32
|
+
│ └── files.ts # 二进制文件 CRUD、SHA 条件与命名空间校验
|
|
29
33
|
├── records/
|
|
30
34
|
│ ├── table.ts # CRUD、条件匹配、读改写编排
|
|
31
35
|
│ ├── codec.ts # JSONL 记录与系统字段/重复校验
|
|
@@ -49,6 +53,8 @@ src/
|
|
|
49
53
|
|
|
50
54
|
底层 getTable 字符串 API 与高层 getRecordTable<T> 记录 API 保持独立入口,不合并为带可选业务类型的句柄。底层只要求 JSONL 对象,高层要求显式类型、主键和系统时间;独立入口明确两层契约并便于类型校验。两种表句柄操作相同文件、共享 repository 队列和 TableStorage,不复制 meta 校验或 Git 提交流程。协议层不依赖业务表格式。获取句柄无网络请求,每张表固定 `<db>/<table>/meta.json` 与 `data.jsonl`。
|
|
51
55
|
|
|
56
|
+
`db.files` 使用独立的 `<db>/.github-db-files/<uuid>` 目录,不进入表的 JSONL/元信息流程。它复用 GitRepository 的快照、实例队列、blob 创建与非强制发布;原始 blob 读取按字节返回并校验 SHA,表读取仍严格解码 UTF-8。删除通过 Git tree 的 `sha: null` 发布。list 读取目录 tree 的文件大小,不下载文件内容。目录若已被表或其他非文件资源占用,拒绝文件操作。
|
|
57
|
+
|
|
52
58
|
## 2. 固定快照与表状态
|
|
53
59
|
|
|
54
60
|
分支发现由 client 共享,一个等待者取消不取消其他等待者;失败清除发现 Promise,允许后续再尝试。GET ref 固定 commitSha,GET commit 获取 treeSha。逐层非递归 GET trees,快照内按 SHA 缓存 Promise,拒绝截断树、非目录父路径和非普通文件。
|
|
@@ -103,7 +109,7 @@ batchItems 检查普通密集数组与属性描述符,避免执行访问器,
|
|
|
103
109
|
|
|
104
110
|
## 6. 传输与错误
|
|
105
111
|
|
|
106
|
-
内部 request 方法统一处理请求发送、HTTP
|
|
112
|
+
内部 request 方法统一处理请求发送、HTTP 分类、取消和响应读取,使用响应类型区分 JSON、Git tree、原始文本和字节;tree 的 size 在 JSON 原始数字舍入前校验,不影响其他 JSON 响应。该组织方式不改变取消、投递状态、编码及发布确定性分类的正确性要求。
|
|
107
113
|
|
|
108
114
|
HTTP 请求保留 endpoint 前缀和 GitHub path。GitHub 管理 header 与代理 header 同时发送,不跟随重定向。所有后续 URL/提交使用的 Git SHA 先验证为 40 位小写十六进制。
|
|
109
115
|
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
- `db.getTable(name)`:底层 UTF-8 JSONL 字符串接口,支持 read/write/getMeta。
|
|
6
6
|
- `db.getRecordTable<T>(name)`:高层记录接口,支持 insert/find/findById/findAll/updateById/deleteById,以及 insertMany/updateManyById/deleteManyById,必须显式指定包含 RecordBase 的完整业务类型。
|
|
7
|
+
- `db.files`:独立文件接口,支持 create/read/replace/delete/list;原始字节存于 `<db>/.github-db-files/<uuid>`。文件与表共享写队列,但文件与记录分别提交,不提供联合事务;详见[需求文档第 8 节](requirements.md#8-独立文件-api)。
|
|
7
8
|
|
|
8
9
|
两个入口使用相同表布局及共享写队列,便于不同调用需求;底层写入的数据只有满足记录约束时才能由高层消费。系统字段由 SDK 管理,业务字段编译期类型由调用方提供。
|
|
9
10
|
|
package/docs/requirements.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# GitHub 数据库 SDK 需求
|
|
2
2
|
|
|
3
|
-
当前规范:单表 JSONL
|
|
3
|
+
当前规范:单表 JSONL 存储、类型化 CRUD 与独立文件资源。调用用法见 [README](../README.md),高层接口设计见 [record-api-design](record-api-design.md)。
|
|
4
4
|
|
|
5
5
|
## 1. 环境与连接
|
|
6
6
|
|
|
@@ -17,9 +17,12 @@ endpoint 保留路径前缀后拼接 GitHub API path。所有请求、包括 raw
|
|
|
17
17
|
```text
|
|
18
18
|
<db>/<table>/meta.json
|
|
19
19
|
<db>/<table>/data.jsonl
|
|
20
|
+
<db>/.github-db-files/<uuid>
|
|
20
21
|
```
|
|
21
22
|
|
|
22
|
-
名称是非空、可辨识、合法 Unicode 的单个路径段,拒绝分隔符、控制/格式字符、已知空白字形、`.`、`..` 和大小写不敏感的 `.git`;允许普通 Unicode、简单 emoji
|
|
23
|
+
名称是非空、可辨识、合法 Unicode 的单个路径段,拒绝分隔符、控制/格式字符、已知空白字形、`.`、`..` 和大小写不敏感的 `.git`;允许普通 Unicode、简单 emoji 与其他点名称。表名 `.github-db-files` 保留给同一 DB 的独立文件目录;现有同名表不会被文件 API 覆盖,访问该文件目录时报明确的命名空间冲突。
|
|
24
|
+
|
|
25
|
+
升级前已有的同名表不能通过当前 SDK 的表工厂访问,也不会出现在 `listTables()`;仓库管理者须先在 Git 中把整个 `<db>/.github-db-files` 表目录改名为其他合法表名,再使用 SDK。SDK 不自动迁移或删除该目录。
|
|
23
26
|
|
|
24
27
|
名称校验采用统一的控制/格式字符禁用规则,因此不支持含 ZWJ 的组合 emoji 或含 ZWNJ 的语词;不做字体相关的视觉识别,也不保证穷举所有不可见字形。`.github`、`a..b` 等合法点名称允许使用,不扩大为全部点前缀或含点名称禁用。
|
|
25
28
|
|
|
@@ -85,8 +88,20 @@ force=false 发布拒绝竞争提交,不强制覆盖、不自动重试。外
|
|
|
85
88
|
|
|
86
89
|
## 7. 验收
|
|
87
90
|
|
|
88
|
-
每次代码变更后必须完整 bun run check 通过,产品运行时源码逐文件行覆盖率、函数覆盖率均至少 90%。单元、Bun/Node 原生 HTTP、实际 npm 包消费及 TypeScript 正反例共同验证;显式 test:live 读取 .env
|
|
91
|
+
每次代码变更后必须完整 bun run check 通过,产品运行时源码逐文件行覆盖率、函数覆盖率均至少 90%。单元、Bun/Node 原生 HTTP、实际 npm 包消费及 TypeScript 正反例共同验证;显式 test:live 读取 .env,在本轮临时分支验证真实单表、多表与独立文件 API,结束时删除并核验该分支引用。
|
|
89
92
|
|
|
90
93
|
规模定位为低频、小规模,不承诺无限容量或高频轮询性能。查询整表下载后在内存过滤,写入整表替换;不提供流式读取、远端行级追加或索引。有效超限旧文件允许读取和缩小,不代表无限容量支持。
|
|
91
94
|
|
|
92
95
|
替换、清空或删除记录只影响最新提交,旧内容仍可在可达 Git 历史读取。Git 提交链是存储、原子发布和恢复模型的一部分;SDK 不自动重写或清除历史,历史清理由仓库管理者处理,不能把逻辑删除理解为历史内容已彻底删除。
|
|
96
|
+
|
|
97
|
+
## 8. 独立文件 API
|
|
98
|
+
|
|
99
|
+
`db.files` 提供 `create(bytes)`、`read(id)`、`replace(id, bytes, { expectedSha? })`、`delete(id, { expectedSha? })`、`list()`。文件存于 `<db>/.github-db-files/<uuid>`,ID 由 SDK 生成且在 DB 内使用;只保存原始字节,不保存 MIME、原始文件名或业务标签。调用方可将 ID 与 MIME 保存在记录中,文件和记录分别提交,不承诺跨资源原子性。
|
|
100
|
+
|
|
101
|
+
输入为 `Uint8Array`,SDK 入队前复制。写入原始字节最多 10,000,000 字节,超限报 FILE_TOO_LARGE;空文件允许。read 返回字节、Git blob SHA、字节数和固定快照 commit SHA,并校验下载字节的 SHA。list 只读取树,返回按 ID 排序的 ID、SHA、字节数;不存在的文件目录返回空数组。有效的历史超限文件仍可读,但更新须符合当前上限。
|
|
102
|
+
|
|
103
|
+
replace 对不存在的 ID 报 NOT_FOUND;delete 对不存在的 ID 返回 false 且不提交。可选 expectedSha 要求匹配当前 blob SHA,否则报 CONFLICT/VERSION_MISMATCH;省略表示修改最新文件,跨 client 发布仍采用非强制 ref 更新。发布结果未知时报 WRITE_RESULT_UNKNOWN,除 commitSha 外附带文件 ID 供调用方核验,不自动重试。删除和替换不会清除旧 Git 对象或历史。
|
|
104
|
+
|
|
105
|
+
文件目录仅支持由 SDK 生成的普通文件条目。若目录被现有表或其他内容占用,操作报错,不静默覆盖。定位为每个 DB 约 1,000 个低频、小文件;不提供公开永久 URL、流式上传、Git LFS、文件与记录的联合事务或仓库总容量保证。
|
|
106
|
+
|
|
107
|
+
文件条目没有独立的归属标记;目录内符合 v4 UUID 名称和普通 blob 模式的条目按文件资源处理,无法区分它是 SDK 创建还是外部写入。仓库管理者不应把其他内容放入保留目录。
|
package/docs/testing.md
CHANGED
|
@@ -19,6 +19,7 @@ Bun LCOV 行/函数统计不能证明所有分支真实执行;已知插桩局
|
|
|
19
19
|
| transport.test.ts | endpoint、双层鉴权、默认/显式请求超时、配置、HTTP、Git 响应、取消及发布确定性 |
|
|
20
20
|
| review-regressions.test.ts / round-two.test.ts | 元信息数字保真、安全整数、SHA、结构化错误、分支发现与历史回归 |
|
|
21
21
|
| records.test.ts | CRUD、AND 等值、系统字段、主键、队列、跨 client 竞争及两层共享 |
|
|
22
|
+
| files.test.ts | 独立文件的二进制往返、容量边界、跨 realm/遮蔽属性输入、SHA 条件、保留目录、树条目 size 缺失或非法、跨 client 竞争、共享队列、取消、调用时复制和未知发布 |
|
|
22
23
|
| batch-records.test.ts | 同表批量原子发布、单次 revision/请求流程、顺序、错误位置、重复/缺失 ID、空操作、输入复制、512 层包装边界、容量/旧表缩小、队列与未知发布 |
|
|
23
24
|
| records-validation.test.ts | JSON 可存储性、坏记录、输入复制、数字精度与容量 |
|
|
24
25
|
| review-latest.test.ts | 512 层边界、深层旧数据结构化错误、发布前取消状态及 Unicode 键隔离 |
|
|
@@ -31,13 +32,13 @@ FakeGitHub 用真实 Git blob SHA、不可变 commit/tree、分支 head 以及
|
|
|
31
32
|
|
|
32
33
|
## 3. 真实 GitHub
|
|
33
34
|
|
|
34
|
-
仅显式 `bun run test:live` 写远端。`.env` 配置 GITHUB_TOKEN、GITHUB_OWNER、GITHUB_REPO、GITHUB_DB_NAME
|
|
35
|
+
仅显式 `bun run test:live` 写远端。`.env` 配置 GITHUB_TOKEN、GITHUB_OWNER、GITHUB_REPO、GITHUB_DB_NAME,不提交凭据、不输出值。仓库默认分支必须已有提交;测试从该提交创建本轮唯一临时分支,不写默认分支。
|
|
35
36
|
|
|
36
37
|
第三方 relay 验收同时配置 `GITHUB_RELAY_ENDPOINT` 和 `GITHUB_RELAY_TOKEN`,缺少任意一项时立即失败。SDK、独立 Git Data 核验及清理请求均通过该 endpoint,并在 GitHub Bearer 鉴权之外发送 `x-cfgr-token`。两项均未配置时直连 GitHub。
|
|
37
38
|
|
|
38
|
-
每次生成唯一表名前缀,独立 Git Data 请求核验初始不存在、同次提交的 meta/data 和最新单表布局。覆盖底层单表、多个独立表、条件版本、零字节文件、大于 1 MB 的 raw blob,以及高层自动/指定 id、重复拒绝、AND 查询、更新、删除、并发新增、同表批量增改删的单次提交/revision
|
|
39
|
+
每次生成唯一表名前缀,独立 Git Data 请求核验初始不存在、同次提交的 meta/data 和最新单表布局。覆盖底层单表、多个独立表、条件版本、零字节文件、大于 1 MB 的 raw blob,以及高层自动/指定 id、重复拒绝、AND 查询、更新、删除、并发新增、同表批量增改删的单次提交/revision、失败原子性与跨表隔离。独立文件用例使用本轮已有的小表 blob 和空 blob 做创建、读取、条件替换、列举、删除,核对相同 SHA,避免为文件用例生成新的独有 blob。
|
|
39
40
|
|
|
40
|
-
|
|
41
|
+
结束时删除本轮临时分支并核验 ref 返回 404,不删除其他分支或重写历史;清理失败指出本轮分支名。这样测试提交不会进入默认分支可达历史,但 GitHub 可能暂时保留不可达 Git 对象。普通 REST API 不能保证服务器立即物理回收 blob;要彻底清除远端对象需 GitHub 服务端垃圾回收,测试不得声称已验证这一点。
|
|
41
42
|
|
|
42
43
|
## 4. 平台与构建
|
|
43
44
|
|
package/lib/index.d.ts
CHANGED
|
@@ -14,6 +14,24 @@ interface ClientOptions {
|
|
|
14
14
|
interface ReadOptions {
|
|
15
15
|
signal?: AbortSignal;
|
|
16
16
|
}
|
|
17
|
+
interface FileWriteOptions extends ReadOptions {
|
|
18
|
+
/** Omit to use the latest file; otherwise require this exact Git blob SHA. */
|
|
19
|
+
expectedSha?: string;
|
|
20
|
+
}
|
|
21
|
+
interface FileEntry {
|
|
22
|
+
id: string;
|
|
23
|
+
sha: string;
|
|
24
|
+
byteLength: number;
|
|
25
|
+
}
|
|
26
|
+
interface FileReadResult extends FileEntry {
|
|
27
|
+
bytes: Uint8Array;
|
|
28
|
+
/** HEAD commit of the read snapshot, not the commit that originally wrote this file. */
|
|
29
|
+
commitSha: string;
|
|
30
|
+
}
|
|
31
|
+
interface FileWriteResult extends FileEntry {
|
|
32
|
+
/** Commit created by this file write. */
|
|
33
|
+
commitSha: string;
|
|
34
|
+
}
|
|
17
35
|
interface TableMeta {
|
|
18
36
|
/** Metadata format version, not the write counter. */
|
|
19
37
|
version: 1;
|
|
@@ -46,6 +64,7 @@ interface TableReadResult extends TableWriteResult {
|
|
|
46
64
|
content: string;
|
|
47
65
|
}
|
|
48
66
|
|
|
67
|
+
type ResponseKind = 'json' | 'tree' | 'text' | 'bytes';
|
|
49
68
|
/** GitHub-compatible HTTP transport, including configuration and response handling. */
|
|
50
69
|
declare class GitHubTransport {
|
|
51
70
|
private readonly endpoint;
|
|
@@ -54,8 +73,9 @@ declare class GitHubTransport {
|
|
|
54
73
|
private readonly fetcher;
|
|
55
74
|
private readonly timeout;
|
|
56
75
|
constructor(options: ClientOptions);
|
|
57
|
-
request(path: string, method: string, body: unknown,
|
|
76
|
+
request(path: string, method: string, body: unknown, kind: ResponseKind, signal?: AbortSignal): Promise<unknown>;
|
|
58
77
|
json(path: string, method?: string, body?: unknown, signal?: AbortSignal): Promise<Record<string, unknown>>;
|
|
78
|
+
tree(path: string, signal?: AbortSignal): Promise<Record<string, unknown>>;
|
|
59
79
|
scope(branch: string | undefined): string;
|
|
60
80
|
}
|
|
61
81
|
|
|
@@ -64,6 +84,7 @@ interface GitEntry {
|
|
|
64
84
|
sha: string;
|
|
65
85
|
type: string;
|
|
66
86
|
mode: string;
|
|
87
|
+
size?: number;
|
|
67
88
|
}
|
|
68
89
|
interface GitSnapshot {
|
|
69
90
|
commitSha: string;
|
|
@@ -76,7 +97,7 @@ type Change = {
|
|
|
76
97
|
} & ({
|
|
77
98
|
content: string;
|
|
78
99
|
} | {
|
|
79
|
-
sha: string;
|
|
100
|
+
sha: string | null;
|
|
80
101
|
});
|
|
81
102
|
|
|
82
103
|
/** Resolve regular files and directories within one immutable Git snapshot. */
|
|
@@ -103,13 +124,30 @@ declare class GitRepository {
|
|
|
103
124
|
/** Version-token scope; snapshot() resolves the effective branch before use. */
|
|
104
125
|
scope(): string;
|
|
105
126
|
content(entry: GitEntry, signal?: AbortSignal): Promise<string>;
|
|
127
|
+
bytes(entry: GitEntry, signal?: AbortSignal): Promise<Uint8Array>;
|
|
106
128
|
enqueue<T>(operation: () => Promise<T>): Promise<T>;
|
|
107
|
-
createBlob(content: string, signal?: AbortSignal): Promise<string>;
|
|
129
|
+
createBlob(content: string | Uint8Array, signal?: AbortSignal): Promise<string>;
|
|
108
130
|
commit(snapshot: GitSnapshot, changes: Change[], message: string, signal?: AbortSignal): Promise<{
|
|
109
131
|
commitSha: string;
|
|
110
132
|
}>;
|
|
111
133
|
}
|
|
112
134
|
|
|
135
|
+
/** Raw bytes stored independently of tables and records. */
|
|
136
|
+
declare class GitHubFiles {
|
|
137
|
+
private readonly repository;
|
|
138
|
+
private readonly root;
|
|
139
|
+
constructor(repository: GitRepository, dbName: string);
|
|
140
|
+
private context;
|
|
141
|
+
private entries;
|
|
142
|
+
private message;
|
|
143
|
+
private publish;
|
|
144
|
+
create(content: Uint8Array, options?: ReadOptions): Promise<FileWriteResult>;
|
|
145
|
+
read(id: string, options?: ReadOptions): Promise<FileReadResult>;
|
|
146
|
+
replace(id: string, content: Uint8Array, options?: FileWriteOptions): Promise<FileWriteResult>;
|
|
147
|
+
delete(id: string, options?: FileWriteOptions): Promise<boolean>;
|
|
148
|
+
list(options?: ReadOptions): Promise<FileEntry[]>;
|
|
149
|
+
}
|
|
150
|
+
|
|
113
151
|
/** Include these SDK-managed fields in the caller's record interface. */
|
|
114
152
|
interface RecordBase {
|
|
115
153
|
id: string;
|
|
@@ -172,6 +210,7 @@ declare class GitHubTable {
|
|
|
172
210
|
declare class GitHubDatabase {
|
|
173
211
|
private readonly repository;
|
|
174
212
|
readonly name: string;
|
|
213
|
+
readonly files: GitHubFiles;
|
|
175
214
|
constructor(repository: GitRepository, name: string);
|
|
176
215
|
/** List table names in one snapshot, without downloading metadata or data. */
|
|
177
216
|
listTables(options?: ReadOptions): Promise<string[]>;
|
|
@@ -193,12 +232,13 @@ declare class GitHubDBClient {
|
|
|
193
232
|
getDB(name: string): GitHubDatabase;
|
|
194
233
|
}
|
|
195
234
|
|
|
196
|
-
type GitHubDBErrorCode = 'INVALID_INPUT' | 'INVALID_UTF8' | 'INVALID_JSONL' | 'TABLE_TOO_LARGE' | 'INVALID_RECORD' | 'DUPLICATE_ID' | 'INVALID_RESPONSE' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'ABORTED' | 'TIMEOUT' | 'NOT_FOUND' | 'INVALID_METADATA' | 'CONFLICT' | 'WRITE_RESULT_UNKNOWN';
|
|
235
|
+
type GitHubDBErrorCode = 'INVALID_INPUT' | 'INVALID_UTF8' | 'INVALID_JSONL' | 'TABLE_TOO_LARGE' | 'FILE_TOO_LARGE' | 'INVALID_RECORD' | 'DUPLICATE_ID' | 'INVALID_RESPONSE' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'ABORTED' | 'TIMEOUT' | 'NOT_FOUND' | 'INVALID_METADATA' | 'CONFLICT' | 'WRITE_RESULT_UNKNOWN';
|
|
197
236
|
interface ErrorDetails {
|
|
198
237
|
/** Stable machine-readable cause; code remains the broad category. */
|
|
199
238
|
reason?: string;
|
|
200
239
|
path?: string;
|
|
201
240
|
table?: string;
|
|
241
|
+
id?: string;
|
|
202
242
|
field?: string;
|
|
203
243
|
/** True once fetch is invoked; does not prove that the server received a request. */
|
|
204
244
|
dispatched?: boolean;
|
|
@@ -217,5 +257,5 @@ declare class GitHubDBError extends Error {
|
|
|
217
257
|
constructor(code: GitHubDBErrorCode, message: string, details?: ErrorDetails);
|
|
218
258
|
}
|
|
219
259
|
|
|
220
|
-
export { GitHubDBClient, GitHubDBError, GitHubDatabase, GitHubRecordTable, GitHubTable };
|
|
221
|
-
export type { ClientOptions, ErrorDetails, GitHubDBErrorCode, ReadOptions, RecordBase, RecordInsert, RecordUpdate, RecordWhere, RecordWriteOptions, TableMeta, TableMetaResult, TableReadResult, TableVersion, TableWriteOptions, TableWriteResult };
|
|
260
|
+
export { GitHubDBClient, GitHubDBError, GitHubDatabase, GitHubFiles, GitHubRecordTable, GitHubTable };
|
|
261
|
+
export type { ClientOptions, ErrorDetails, FileEntry, FileReadResult, FileWriteOptions, FileWriteResult, GitHubDBErrorCode, ReadOptions, RecordBase, RecordInsert, RecordUpdate, RecordWhere, RecordWriteOptions, TableMeta, TableMetaResult, TableReadResult, TableVersion, TableWriteOptions, TableWriteResult };
|
package/lib/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import{createHash as M,randomUUID as H}from"node:crypto";import{isDeepStrictEqual as Q}from"node:util";import{Buffer as _}from"node:buffer";class c extends Error{constructor(t,e,n={}){super(e),this.code=t,this.details=n}code;details;name="GitHubDBError"}function T(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function B(a){if(!T(a))throw new c("INVALID_INPUT","Options must be an object.")}function E(a){if(a!==void 0&&!(a instanceof AbortSignal))throw new c("INVALID_INPUT","signal must be an AbortSignal.")}function Z(a){if(typeof a!="string"||!a.isWellFormed())throw new c("INVALID_INPUT","Content must be a well-formed Unicode string.")}function $(a){return typeof a=="string"&&!!a.trim()&&a.isWellFormed()&&a!=="."&&a!==".."&&a.toLowerCase()!==".git"&&!/[/\\\p{Cc}\p{Cf}\u115F\u1160\u3164\u2800\uFFA0]/u.test(a)}function D(a){if(!$(a))throw new c("INVALID_INPUT","Names must be nonempty, unambiguous path segments.");return a}function m(a){B(a);const t=a.signal;return E(t),t}const tt=1e7;function et(a){let t=!1,e=!1;for(let n=0;n<a.length;n++){const r=a[n];if(!t){r==='"'&&(t=!0);continue}if(r==="\\"){if(a[++n]==="u"){const s=Number.parseInt(a.slice(n+1,n+5),16);if(n+=4,s>=55296&&s<=56319){if(e)return!0;e=!0}else if(s>=56320&&s<=57343){if(!e)return!0;e=!1}else if(e)return!0}else if(e)return!0}else if(r==='"'){if(e)return!0;t=!1}else if(e)return!0}return!1}function L(a,t=!0){Z(a);const e=_.byteLength(a,"utf8");if(t&&e>tt)throw new c("TABLE_TOO_LARGE","Table exceeds 10,000,000 UTF-8 bytes.");if(a==="")return{recordCount:0,byteLength:0};const n=a.split(`
|
|
2
|
-
`);n.at(-1)===""&&n.pop();for(const[r,s]of n.entries()){let i;try{i=JSON.parse(s)}catch{throw new c("INVALID_JSONL","Every record line must be valid JSON.",{lineNumber:r+1})}if(et(s))throw new c("INVALID_JSONL","JSONL contains invalid Unicode.",{lineNumber:r+1,reason:"INVALID_UNICODE"});if(!T(i))throw new c("INVALID_JSONL","Every record must be a JSON object.",{lineNumber:r+1})}return{recordCount:n.length,byteLength:e}}function O(a){if(!T(a))throw new c("INVALID_RESPONSE","Expected a GitHub response object.");return a}function w(a){if(typeof a!="string"||!/^[a-f0-9]{40}$/.test(a))throw new c("INVALID_RESPONSE","Expected a 40-character lowercase Git SHA.");return a}function P(a){if(typeof a!="string"||!a||!a.isWellFormed())throw new c("INVALID_RESPONSE","Expected a nonempty well-formed GitHub response field.");return a}function rt(a){if(typeof a!="string"||!a.trim()||!a.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(a))throw new c("INVALID_RESPONSE","Expected a valid well-formed GitHub branch name.");return a}const nt=3e4;function at(a,t){try{if(a===null||typeof a!="object")return;const e=a,n=e.status,r=e.ok,s=e.headers,i=e.json,o=e.arrayBuffer;if(typeof n!="number"||!Number.isInteger(n)||n<100||n>599||typeof r!="boolean"||r!==(n>=200&&n<300)||s===null||typeof s!="object")return;const d=s.get;if(typeof d!="function"||typeof i!="function"||typeof o!="function")return;const u=d.call(s,"x-github-request-id"),h=d.call(s,"retry-after");return u!==null&&typeof u!="string"||h!==null&&typeof h!="string"?void 0:{ok:r,json:i.bind(a),arrayBuffer:o.bind(a),details:{dispatched:t,status:n,requestId:u??void 0,retryAfter:h??void 0}}}catch{return}}function v(a,t,e){const n=Promise.resolve(a);return t?new Promise((r,s)=>{let i=!1;const o=()=>t.removeEventListener("abort",d),d=()=>{i||(i=!0,o(),s(e()))};t.addEventListener("abort",d,{once:!0}),n.then(u=>{i||(i=!0,o(),r(u))},u=>{i||(i=!0,o(),s(u))}),t.aborted&&d()}):n}function ot(a){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(a);if(!t)return!1;const e=Number(t[1]),n=Number(t[2]),r=Number(t[3]);if(n<1||n>12)return!1;const s=[31,e%4===0&&(e%100!==0||e%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return r>=1&&r<=s[n-1]}class st{endpoint;prefix;headers;fetcher;timeout;constructor(t){B(t);for(const r of[t.token,t.owner,t.repo])if(typeof r!="string"||!r.trim())throw new c("INVALID_INPUT","token, owner and repo are required.");if(D(t.owner),D(t.repo),t.branch!==void 0&&(typeof t.branch!="string"||!t.branch.trim()||!t.branch.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(t.branch)))throw new c("INVALID_INPUT","branch must be nonempty, well-formed Unicode without control or format characters.");let e;try{e=new URL(t.endpoint??"https://api.github.com")}catch{throw new c("INVALID_INPUT","endpoint must be an absolute HTTP(S) URL.")}const n=["localhost","127.0.0.1","[::1]"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new c("INVALID_INPUT","endpoint must use HTTPS; plain HTTP is allowed only for localhost.");if(e.search||e.hash||e.username||e.password)throw new c("INVALID_INPUT","endpoint cannot contain credentials, query or fragment.");if(t.timeout!==void 0&&(!Number.isSafeInteger(t.timeout)||t.timeout<=0||t.timeout>2147483647))throw new c("INVALID_INPUT","timeout must be between 1 and 2,147,483,647 milliseconds.");if(t.apiVersion!==void 0&&(typeof t.apiVersion!="string"||!ot(t.apiVersion)))throw new c("INVALID_INPUT","apiVersion must have YYYY-MM-DD format.");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new c("INVALID_INPUT","fetch must be a function.");this.endpoint=e.href.replace(/\/+$/,""),this.prefix=`/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`;try{this.headers=new Headers(t.headers)}catch{throw new c("INVALID_INPUT","Custom headers are not valid HTTP header values.")}for(const r of["authorization","accept","content-type","x-github-api-version"])if(this.headers.has(r))throw new c("INVALID_INPUT",`Custom headers cannot override ${r}.`);try{this.headers.set("Authorization",`Bearer ${t.token}`)}catch{throw new c("INVALID_INPUT","token is not a valid HTTP header value.")}this.headers.set("X-GitHub-Api-Version",t.apiVersion??"2026-03-10"),this.fetcher=t.fetch??globalThis.fetch,this.timeout=t.timeout??nt}async request(t,e,n,r,s){E(s);let i=!1;const o=new Headers(this.headers);o.set("Accept",r?"application/vnd.github.raw+json":"application/vnd.github+json"),n!==void 0&&o.set("Content-Type","application/json");const d=AbortSignal.timeout(this.timeout),u=s?AbortSignal.any([s,d]):d,h=e==="POST"&&t==="/git/commits",l=u,p=()=>h&&s?.aborted===!0,f=()=>new c(s?.aborted?"ABORTED":"TIMEOUT",s?.aborted?"Request was cancelled.":"Request timed out.",{dispatched:i});if(u?.aborted)throw f();let b;try{i=!0;const N=this.fetcher(`${this.endpoint}${this.prefix}${t}`,{method:e,headers:o,body:n===void 0?void 0:JSON.stringify(n),redirect:"manual",signal:u});b=await v(N,l,f)}catch{throw u?.aborted?f():new c("NETWORK_ERROR","GitHub request failed.",{dispatched:i})}if(u?.aborted&&!p())throw f();const g=at(b,i);if(!g)throw new c("INVALID_RESPONSE","fetch must return a valid Response.",{dispatched:i});const{details:y}=g;if(!g.ok)throw new c("HTTP_ERROR",`GitHub request returned HTTP ${y.status}.`,{...y,...y.status>=300&&y.status<400?{reason:"REDIRECT"}:{}});try{if(!r){const X=await v(g.json(),l,f);if(u?.aborted&&!p())throw f();return X}const N=await v(g.arrayBuffer(),l,f);let C;try{C=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(N)}catch{throw new c("INVALID_UTF8","File content is not valid UTF-8.",y)}if(u?.aborted)throw f();return C}catch(N){throw u?.aborted?f():N instanceof c?N:new c("INVALID_RESPONSE","Could not read the GitHub response.",y)}}async json(t,e="GET",n,r){return O(await this.request(t,e,n,!1,r))}scope(t){return JSON.stringify([this.endpoint,this.prefix,t])}}function it(a){const t=P(a);if(t.includes("/"))throw new c("INVALID_RESPONSE","GitHub returned an invalid tree entry path.");return t}class ct{constructor(t){this.transport=t}transport;tree(t,e,n){let r=t.trees.get(e);return r||(r=this.transport.json(`/git/trees/${e}`,"GET",void 0,n).then(s=>{if(s.truncated!==!1||!Array.isArray(s.tree))throw new c("INVALID_RESPONSE","GitHub returned an incomplete tree.");return s.tree.map(i=>{const o=O(i);return{path:it(o.path),sha:w(o.sha),type:P(o.type),mode:P(o.mode)}})}),t.trees.set(e,r)),r}async resolve(t,e,n){const r=e.split("/");let s=t.treeSha;for(let i=0;i<r.length;i++){const o=(await this.tree(t,s,n)).find(d=>d.path===r[i]);if(!o)return;if(i===r.length-1)return o;if(o.type!=="tree")throw new c("INVALID_METADATA","A parent path is not a directory.",{path:r.slice(0,i+1).join("/"),reason:"PATH_NOT_DIRECTORY"});s=o.sha}}async find(t,e,n){const r=await this.resolve(t,e,n);if(r&&(r.type!=="blob"||!["100644","100755"].includes(r.mode)))throw new c("INVALID_METADATA","Path must reference a regular file.",{path:e,reason:"NOT_REGULAR_FILE"});return r}async directory(t,e,n){const r=await this.resolve(t,e,n);if(r){if(r.type!=="tree")throw new c("INVALID_METADATA","Path must reference a directory.",{path:e,reason:"PATH_NOT_DIRECTORY"});return this.tree(t,r.sha,n)}}}function R(a){const t=_.from(a,"utf8");return M("sha1").update(`blob ${t.byteLength}\0`).update(t).digest("hex")}class ht{transport;endpoint;files;branchName;branchLookup;queue=Promise.resolve();constructor(t){this.transport=new st(t),this.endpoint=t.endpoint??"https://api.github.com",this.files=new ct(this.transport),this.branchName=t.branch}async branch(t){if(t?.aborted)throw new c("ABORTED","Request was cancelled.",{dispatched:!1});if(this.branchName!==void 0)return this.branchName;if(this.branchLookup??=this.transport.json("").then(n=>(this.branchName=rt(n.default_branch),this.branchName)).finally(()=>{this.branchLookup=void 0}),!t)return this.branchLookup;const e=this.branchLookup;if(t.aborted)throw e.catch(()=>{}),new c("ABORTED","Request was cancelled.",{dispatched:!0});return new Promise((n,r)=>{const s=()=>r(new c("ABORTED","Request was cancelled.",{dispatched:!0}));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))})}async snapshot(t){E(t);const e=await this.branch(t),n=await this.transport.json(`/git/ref/heads/${encodeURIComponent(e)}`,"GET",void 0,t),r=w(O(n.object).sha),s=await this.transport.json(`/git/commits/${r}`,"GET",void 0,t);return{commitSha:r,treeSha:w(O(s.tree).sha),trees:new Map}}scope(){return this.transport.scope(this.branchName)}async content(t,e){return await this.transport.request(`/git/blobs/${t.sha}`,"GET",void 0,!0,e)}enqueue(t){const e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}async createBlob(t,e){const n=await this.transport.json("/git/blobs","POST",{content:_.from(t,"utf8").toString("base64"),encoding:"base64"},e),r=w(n.sha);if(r!==R(t))throw new c("INVALID_RESPONSE","GitHub returned a blob SHA that does not match content.");return r}async commit(t,e,n,r){const s=await Promise.all(e.map(async h=>({path:h.path,mode:h.mode??"100644",type:"blob",sha:"sha"in h?h.sha:await this.createBlob(h.content,r)}))),i=await this.transport.json("/git/trees","POST",{base_tree:t.treeSha,tree:s},r),o=await this.transport.json("/git/commits","POST",{tree:w(i.sha),parents:[t.commitSha],message:n},r),d=w(o.sha),u=await this.branch();if(r?.aborted)throw new c("ABORTED","Write was cancelled before publication.",{dispatched:!0,reason:"BEFORE_PUBLICATION",commitSha:d});try{const h=await this.transport.json(`/git/refs/heads/${encodeURIComponent(u)}`,"PATCH",{sha:d,force:!1},r);if(w(O(h.object).sha)!==d)throw new c("INVALID_RESPONSE","Unexpected published commit.")}catch(h){if(h instanceof c){if(h.details.dispatched===!1)throw h;if(h.code==="HTTP_ERROR"&&h.details.status!==void 0&&h.details.status<500)throw h.details.status===409||h.details.status===422?new c("CONFLICT","GitHub rejected publication; inspect the cause before retrying.",{...h.details,reason:"PUBLISH_REJECTED"}):h}throw new c("WRITE_RESULT_UNKNOWN","Publication may have succeeded; verify before retrying.",{dispatched:!0,...h instanceof c?h.details:{},commitSha:d})}return{commitSha:d}}}const dt=512;function J(a,t,e){if(a>dt)throw new c(t,"JSON nesting exceeds 512 object/array containers.",{...e,reason:"TOO_DEEP"})}function F(a,t,e){let n=0,r=!1;for(let s=0;s<a.length;s++){const i=a[s];r&&i==="\\"?s++:i==='"'?r=!r:r||(i==="{"||i==="["?J(++n,t,e):(i==="}"||i==="]")&&n--)}}function G(a){const t=/^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(a),e=t[3]??"",n=(t[2]+e).replace(/^0+/,""),r=n.replace(/0+$/,"");return{sign:n?t[1]:"",digits:r,exponent:n?BigInt(t[4]??0)-BigInt(e.length)+BigInt(n.length-r.length):0n}}const S=JSON;function ut(a){const{digits:t,exponent:e}=G(a);return!t||e>=0n}function V(a,t,e){const n=a[t],r=S.isRawJSON(n)?Number(n.rawJSON):n;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||Object.is(r,-0)||S.isRawJSON(n)&&!ut(n.rawJSON))throw new c("INVALID_METADATA","Metadata field must be a nonnegative safe integer.",{...e,reason:"INVALID_FIELD",field:t});return a[t]=r,r}function lt(a,t){F(a,"INVALID_METADATA",t);let e;try{e=S.parse(a,(n,r,s)=>typeof r=="number"&&JSON.stringify(r)!==s.source?S.rawJSON(s.source):r)}catch{throw new c("INVALID_METADATA","meta.json must contain valid JSON.",{...t,reason:"INVALID_JSON"})}if(!T(e))throw new c("INVALID_METADATA","meta.json must contain an object.",{...t,reason:"INVALID_FIELD"});if(V(e,"version",t)!==1)throw new c("INVALID_METADATA","Unsupported metadata format version.",{...t,reason:"UNSUPPORTED_VERSION",field:"version"});for(const n of["createdAt","updatedAt","recordCount","byteLength"])V(e,n,t);if(V(e,"revision",t)===0||typeof e.dataSha!="string"||!/^[a-f0-9]{40}$/.test(e.dataSha))throw new c("INVALID_METADATA","Table revision or dataSha is invalid.",{...t,reason:"INVALID_FIELD",field:"revision/dataSha"});return e}function ft(a){return JSON.stringify(a,null,2)+`
|
|
3
|
-
`
|
|
1
|
+
import{createHash as J,randomUUID as v}from"node:crypto";import{Buffer as S}from"node:buffer";import{isDeepStrictEqual as ot}from"node:util";class i extends Error{constructor(t,e,n={}){super(e),this.code=t,this.details=n}code;details;name="GitHubDBError"}function O(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}function G(s){if(!O(s))throw new i("INVALID_INPUT","Options must be an object.")}function R(s){if(s!==void 0&&!(s instanceof AbortSignal))throw new i("INVALID_INPUT","signal must be an AbortSignal.")}function it(s){if(typeof s!="string"||!s.isWellFormed())throw new i("INVALID_INPUT","Content must be a well-formed Unicode string.")}function q(s){return typeof s=="string"&&!!s.trim()&&s.isWellFormed()&&s!=="."&&s!==".."&&s.toLowerCase()!==".git"&&!/[/\\\p{Cc}\p{Cf}\u115F\u1160\u3164\u2800\uFFA0]/u.test(s)}function g(s){if(!q(s))throw new i("INVALID_INPUT","Names must be nonempty, unambiguous path segments.");return s}function p(s){G(s);const t=s.signal;return R(t),t}function T(s){if(!O(s))throw new i("INVALID_RESPONSE","Expected a GitHub response object.");return s}function y(s){if(typeof s!="string"||!/^[a-f0-9]{40}$/.test(s))throw new i("INVALID_RESPONSE","Expected a 40-character lowercase Git SHA.");return s}function U(s){if(typeof s!="string"||!s||!s.isWellFormed())throw new i("INVALID_RESPONSE","Expected a nonempty well-formed GitHub response field.");return s}function ct(s){if(typeof s!="string"||!s.trim()||!s.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(s))throw new i("INVALID_RESPONSE","Expected a valid well-formed GitHub branch name.");return s}const ht=512;function k(s,t,e){if(s>ht)throw new i(t,"JSON nesting exceeds 512 object/array containers.",{...e,reason:"TOO_DEEP"})}function W(s,t,e){let n=0,r=!1;for(let o=0;o<s.length;o++){const c=s[o];r&&c==="\\"?o++:c==='"'?r=!r:r||(c==="{"||c==="["?k(++n,t,e):(c==="}"||c==="]")&&n--)}}function V(s){const t=/^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(s),e=t[3]??"",n=(t[2]+e).replace(/^0+/,""),r=n.replace(/0+$/,"");return{sign:n?t[1]:"",digits:r,exponent:n?BigInt(t[4]??0)-BigInt(e.length)+BigInt(n.length-r.length):0n}}const dt=3e4,ut=JSON;function lt(s){return ut.parse(s,(t,e,n)=>{if(t!=="size"||typeof e!="number")return e;const{exponent:r}=V(n.source);return n.source.startsWith("-")||r<0n?void 0:e})}function ft(s,t){try{if(s===null||typeof s!="object")return;const e=s,n=e.status,r=e.ok,o=e.headers,c=e.json,a=e.arrayBuffer;if(typeof n!="number"||!Number.isInteger(n)||n<100||n>599||typeof r!="boolean"||r!==(n>=200&&n<300)||o===null||typeof o!="object")return;const d=o.get;if(typeof d!="function"||typeof c!="function"||typeof a!="function")return;const u=d.call(o,"x-github-request-id"),h=d.call(o,"retry-after");return u!==null&&typeof u!="string"||h!==null&&typeof h!="string"?void 0:{ok:r,json:c.bind(s),arrayBuffer:a.bind(s),details:{dispatched:t,status:n,requestId:u??void 0,retryAfter:h??void 0}}}catch{return}}function L(s,t,e){const n=Promise.resolve(s);return t?new Promise((r,o)=>{let c=!1;const a=()=>t.removeEventListener("abort",d),d=()=>{c||(c=!0,a(),o(e()))};t.addEventListener("abort",d,{once:!0}),n.then(u=>{c||(c=!0,a(),r(u))},u=>{c||(c=!0,a(),o(u))}),t.aborted&&d()}):n}function pt(s){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(s);if(!t)return!1;const e=Number(t[1]),n=Number(t[2]),r=Number(t[3]);if(n<1||n>12)return!1;const o=[31,e%4===0&&(e%100!==0||e%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return r>=1&&r<=o[n-1]}class wt{endpoint;prefix;headers;fetcher;timeout;constructor(t){G(t);for(const r of[t.token,t.owner,t.repo])if(typeof r!="string"||!r.trim())throw new i("INVALID_INPUT","token, owner and repo are required.");if(g(t.owner),g(t.repo),t.branch!==void 0&&(typeof t.branch!="string"||!t.branch.trim()||!t.branch.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(t.branch)))throw new i("INVALID_INPUT","branch must be nonempty, well-formed Unicode without control or format characters.");let e;try{e=new URL(t.endpoint??"https://api.github.com")}catch{throw new i("INVALID_INPUT","endpoint must be an absolute HTTP(S) URL.")}const n=["localhost","127.0.0.1","[::1]"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new i("INVALID_INPUT","endpoint must use HTTPS; plain HTTP is allowed only for localhost.");if(e.search||e.hash||e.username||e.password)throw new i("INVALID_INPUT","endpoint cannot contain credentials, query or fragment.");if(t.timeout!==void 0&&(!Number.isSafeInteger(t.timeout)||t.timeout<=0||t.timeout>2147483647))throw new i("INVALID_INPUT","timeout must be between 1 and 2,147,483,647 milliseconds.");if(t.apiVersion!==void 0&&(typeof t.apiVersion!="string"||!pt(t.apiVersion)))throw new i("INVALID_INPUT","apiVersion must have YYYY-MM-DD format.");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new i("INVALID_INPUT","fetch must be a function.");this.endpoint=e.href.replace(/\/+$/,""),this.prefix=`/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`;try{this.headers=new Headers(t.headers)}catch{throw new i("INVALID_INPUT","Custom headers are not valid HTTP header values.")}for(const r of["authorization","accept","content-type","x-github-api-version"])if(this.headers.has(r))throw new i("INVALID_INPUT",`Custom headers cannot override ${r}.`);try{this.headers.set("Authorization",`Bearer ${t.token}`)}catch{throw new i("INVALID_INPUT","token is not a valid HTTP header value.")}this.headers.set("X-GitHub-Api-Version",t.apiVersion??"2026-03-10"),this.fetcher=t.fetch??globalThis.fetch,this.timeout=t.timeout??dt}async request(t,e,n,r,o){R(o);let c=!1;const a=new Headers(this.headers),d=r==="text"||r==="bytes";a.set("Accept",d?"application/vnd.github.raw+json":"application/vnd.github+json"),n!==void 0&&a.set("Content-Type","application/json");const u=AbortSignal.timeout(this.timeout),h=o?AbortSignal.any([o,u]):u,l=e==="POST"&&t==="/git/commits",w=h,m=()=>l&&o?.aborted===!0,f=()=>new i(o?.aborted?"ABORTED":"TIMEOUT",o?.aborted?"Request was cancelled.":"Request timed out.",{dispatched:c});if(h?.aborted)throw f();let H;try{c=!0;const I=this.fetcher(`${this.endpoint}${this.prefix}${t}`,{method:e,headers:a,body:n===void 0?void 0:JSON.stringify(n),redirect:"manual",signal:h});H=await L(I,w,f)}catch{throw h?.aborted?f():new i("NETWORK_ERROR","GitHub request failed.",{dispatched:c})}if(h?.aborted&&!m())throw f();const N=ft(H,c);if(!N)throw new i("INVALID_RESPONSE","fetch must return a valid Response.",{dispatched:c});const{details:A}=N;if(!N.ok)throw new i("HTTP_ERROR",`GitHub request returned HTTP ${A.status}.`,{...A,...A.status>=300&&A.status<400?{reason:"REDIRECT"}:{}});try{if(r==="json"||r==="tree"){const at=r==="tree"?lt(new TextDecoder("utf-8",{fatal:!0}).decode(await L(N.arrayBuffer(),w,f))):await L(N.json(),w,f);if(h?.aborted&&!m())throw f();return at}const I=await L(N.arrayBuffer(),w,f);if(h?.aborted)throw f();if(r==="bytes")return new Uint8Array(I);let B;try{B=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(I)}catch{throw new i("INVALID_UTF8","File content is not valid UTF-8.",A)}if(h?.aborted)throw f();return B}catch(I){throw h?.aborted?f():I instanceof i?I:new i("INVALID_RESPONSE","Could not read the GitHub response.",A)}}async json(t,e="GET",n,r){return T(await this.request(t,e,n,"json",r))}async tree(t,e){return T(await this.request(t,"GET",void 0,"tree",e))}scope(t){return JSON.stringify([this.endpoint,this.prefix,t])}}function mt(s){const t=U(s);if(t.includes("/"))throw new i("INVALID_RESPONSE","GitHub returned an invalid tree entry path.");return t}class It{constructor(t){this.transport=t}transport;tree(t,e,n){let r=t.trees.get(e);return r||(r=this.transport.tree(`/git/trees/${e}`,n).then(o=>{if(o.truncated!==!1||!Array.isArray(o.tree))throw new i("INVALID_RESPONSE","GitHub returned an incomplete tree.");return o.tree.map(c=>{const a=T(c);return{path:mt(a.path),sha:y(a.sha),type:U(a.type),mode:U(a.mode),size:typeof a.size=="number"?a.size:void 0}})}),t.trees.set(e,r)),r}async resolve(t,e,n){const r=e.split("/");let o=t.treeSha;for(let c=0;c<r.length;c++){const a=(await this.tree(t,o,n)).find(d=>d.path===r[c]);if(!a)return;if(c===r.length-1)return a;if(a.type!=="tree")throw new i("INVALID_METADATA","A parent path is not a directory.",{path:r.slice(0,c+1).join("/"),reason:"PATH_NOT_DIRECTORY"});o=a.sha}}async find(t,e,n){const r=await this.resolve(t,e,n);if(r&&(r.type!=="blob"||!["100644","100755"].includes(r.mode)))throw new i("INVALID_METADATA","Path must reference a regular file.",{path:e,reason:"NOT_REGULAR_FILE"});return r}async directory(t,e,n){const r=await this.resolve(t,e,n);if(r){if(r.type!=="tree")throw new i("INVALID_METADATA","Path must reference a directory.",{path:e,reason:"PATH_NOT_DIRECTORY"});return this.tree(t,r.sha,n)}}}function _(s){const t=typeof s=="string"?S.from(s,"utf8"):s;return J("sha1").update(`blob ${t.byteLength}\0`).update(t).digest("hex")}class yt{transport;endpoint;files;branchName;branchLookup;queue=Promise.resolve();constructor(t){this.transport=new wt(t),this.endpoint=t.endpoint??"https://api.github.com",this.files=new It(this.transport),this.branchName=t.branch}async branch(t){if(t?.aborted)throw new i("ABORTED","Request was cancelled.",{dispatched:!1});if(this.branchName!==void 0)return this.branchName;if(this.branchLookup??=this.transport.json("").then(n=>(this.branchName=ct(n.default_branch),this.branchName)).finally(()=>{this.branchLookup=void 0}),!t)return this.branchLookup;const e=this.branchLookup;if(t.aborted)throw e.catch(()=>{}),new i("ABORTED","Request was cancelled.",{dispatched:!0});return new Promise((n,r)=>{const o=()=>r(new i("ABORTED","Request was cancelled.",{dispatched:!0}));t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o))})}async snapshot(t){R(t);const e=await this.branch(t),n=await this.transport.json(`/git/ref/heads/${encodeURIComponent(e)}`,"GET",void 0,t),r=y(T(n.object).sha),o=await this.transport.json(`/git/commits/${r}`,"GET",void 0,t);return{commitSha:r,treeSha:y(T(o.tree).sha),trees:new Map}}scope(){return this.transport.scope(this.branchName)}async content(t,e){return await this.transport.request(`/git/blobs/${t.sha}`,"GET",void 0,"text",e)}async bytes(t,e){return await this.transport.request(`/git/blobs/${t.sha}`,"GET",void 0,"bytes",e)}enqueue(t){const e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}async createBlob(t,e){const n=typeof t=="string"?S.from(t,"utf8"):t,r=await this.transport.json("/git/blobs","POST",{content:S.from(n.buffer,n.byteOffset,n.byteLength).toString("base64"),encoding:"base64"},e),o=y(r.sha);if(o!==_(n))throw new i("INVALID_RESPONSE","GitHub returned a blob SHA that does not match content.");return o}async commit(t,e,n,r){const o=await Promise.all(e.map(async h=>({path:h.path,mode:h.mode??"100644",type:"blob",sha:"sha"in h?h.sha:await this.createBlob(h.content,r)}))),c=await this.transport.json("/git/trees","POST",{base_tree:t.treeSha,tree:o},r),a=await this.transport.json("/git/commits","POST",{tree:y(c.sha),parents:[t.commitSha],message:n},r),d=y(a.sha),u=await this.branch();if(r?.aborted)throw new i("ABORTED","Write was cancelled before publication.",{dispatched:!0,reason:"BEFORE_PUBLICATION",commitSha:d});try{const h=await this.transport.json(`/git/refs/heads/${encodeURIComponent(u)}`,"PATCH",{sha:d,force:!1},r);if(y(T(h.object).sha)!==d)throw new i("INVALID_RESPONSE","Unexpected published commit.")}catch(h){if(h instanceof i){if(h.details.dispatched===!1)throw h;if(h.code==="HTTP_ERROR"&&h.details.status!==void 0&&h.details.status<500)throw h.details.status===409||h.details.status===422?new i("CONFLICT","GitHub rejected publication; inspect the cause before retrying.",{...h.details,reason:"PUBLISH_REJECTED"}):h}throw new i("WRITE_RESULT_UNKNOWN","Publication may have succeeded; verify before retrying.",{dispatched:!0,...h instanceof i?h.details:{},commitSha:d})}return{commitSha:d}}}const E=".github-db-files",bt=1e7,z=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,Y=Object.getPrototypeOf(Uint8Array.prototype),Nt=Object.getOwnPropertyDescriptor(Y,"byteLength").get,At=Object.getOwnPropertyDescriptor(Y,Symbol.toStringTag).get;function x(s){if(typeof s!="string"||!z.test(s))throw new i("INVALID_INPUT","File ID must be a lowercase UUID.");return s}function K(s,t){if(At.call(s)!=="Uint8Array")throw new i("INVALID_INPUT","File content must be a Uint8Array.");const e=Nt.call(s);if(e>bt)throw new i("FILE_TOO_LARGE","File exceeds the 10,000,000-byte limit.",t);const n=new Uint8Array(e);return Uint8Array.prototype.set.call(n,s),n}function X(s){const t=s.expectedSha;if(t!==void 0&&(typeof t!="string"||!/^[a-f0-9]{40}$/.test(t)))throw new i("INVALID_INPUT","expectedSha must be a Git blob SHA.");return t}class Q{constructor(t,e){this.repository=t,g(e),this.root=`${e}/${E}`}repository;root;context(t){return{id:t,path:`${this.root}/${t}`}}async entries(t,e){const n=await this.repository.files.directory(t,this.root,e)??[];for(const r of n)if(r.type!=="blob"||!["100644","100755"].includes(r.mode)||!z.test(r.path))throw new i("INVALID_METADATA","File directory contains an unexpected entry.",{path:`${this.root}/${r.path}`,reason:"FILE_NAMESPACE_COLLISION"});return n}message(t,e){return[`github-db: ${t} ${JSON.stringify(`${this.root}/${e}`)}`,"","client: @secret-momo/github-db",`endpoint: ${this.repository.endpoint}`].join(`
|
|
2
|
+
`)}async publish(t,e,n,r,o,c){try{return(await this.repository.commit(t,[{path:`${this.root}/${e}`,sha:n,mode:c}],this.message(r,e),o)).commitSha}catch(a){throw a instanceof i?new i(a.code,a.message,{...a.details,...this.context(e)}):a}}async create(t,e={}){const n=p(e),r=K(t),o=v();return this.repository.enqueue(async()=>{const c=await this.repository.snapshot(n);if((await this.entries(c,n)).some(u=>u.path===o))throw new i("CONFLICT","Generated file ID already exists.",{...this.context(o),reason:"FILE_ID_COLLISION"});const a=await this.repository.createBlob(r,n),d=await this.publish(c,o,a,"createFile",n);return{id:o,sha:a,byteLength:r.byteLength,commitSha:d}})}async read(t,e={}){x(t);const n=p(e),r=await this.repository.snapshot(n),o=(await this.entries(r,n)).find(a=>a.path===t);if(!o)throw new i("NOT_FOUND","File does not exist.",{...this.context(t),reason:"FILE_NOT_FOUND"});let c;try{c=await this.repository.bytes(o,n)}catch(a){throw a instanceof i?new i(a.code,a.message,{...a.details,...this.context(t)}):a}if(_(c)!==o.sha)throw new i("INVALID_METADATA","File SHA does not match its content.",{...this.context(t),reason:"FILE_SHA_MISMATCH"});return{id:t,bytes:c,sha:o.sha,byteLength:c.byteLength,commitSha:r.commitSha}}async replace(t,e,n={}){x(t);const r=p(n),o=X(n),c=K(e,this.context(t));return this.repository.enqueue(async()=>{const a=await this.repository.snapshot(r),d=(await this.entries(a,r)).find(l=>l.path===t);if(!d)throw new i("NOT_FOUND","File does not exist.",{...this.context(t),reason:"FILE_NOT_FOUND"});if(o!==void 0&&d.sha!==o)throw new i("CONFLICT","File SHA does not match expectedSha.",{...this.context(t),reason:"VERSION_MISMATCH"});const u=await this.repository.createBlob(c,r),h=await this.publish(a,t,u,"replaceFile",r,d.mode);return{id:t,sha:u,byteLength:c.byteLength,commitSha:h}})}async delete(t,e={}){x(t);const n=p(e),r=X(e);return this.repository.enqueue(async()=>{const o=await this.repository.snapshot(n),c=(await this.entries(o,n)).find(a=>a.path===t);if(!c)return!1;if(r!==void 0&&c.sha!==r)throw new i("CONFLICT","File SHA does not match expectedSha.",{...this.context(t),reason:"VERSION_MISMATCH"});return await this.publish(o,t,null,"deleteFile",n),!0})}async list(t={}){const e=p(t),n=await this.repository.snapshot(e);return(await this.entries(n,e)).map(r=>{const o=r.size;if(o===void 0||!Number.isSafeInteger(o)||o<0)throw new i("INVALID_RESPONSE","GitHub omitted a valid file size.",this.context(r.path));return{id:r.path,sha:r.sha,byteLength:o}}).sort((r,o)=>r.id.localeCompare(o.id))}}const gt=1e7;function Tt(s){let t=!1,e=!1;for(let n=0;n<s.length;n++){const r=s[n];if(!t){r==='"'&&(t=!0);continue}if(r==="\\"){if(s[++n]==="u"){const o=Number.parseInt(s.slice(n+1,n+5),16);if(n+=4,o>=55296&&o<=56319){if(e)return!0;e=!0}else if(o>=56320&&o<=57343){if(!e)return!0;e=!1}else if(e)return!0}else if(e)return!0}else if(r==='"'){if(e)return!0;t=!1}else if(e)return!0}return!1}function C(s,t=!0){it(s);const e=S.byteLength(s,"utf8");if(t&&e>gt)throw new i("TABLE_TOO_LARGE","Table exceeds 10,000,000 UTF-8 bytes.");if(s==="")return{recordCount:0,byteLength:0};const n=s.split(`
|
|
3
|
+
`);n.at(-1)===""&&n.pop();for(const[r,o]of n.entries()){let c;try{c=JSON.parse(o)}catch{throw new i("INVALID_JSONL","Every record line must be valid JSON.",{lineNumber:r+1})}if(Tt(o))throw new i("INVALID_JSONL","JSONL contains invalid Unicode.",{lineNumber:r+1,reason:"INVALID_UNICODE"});if(!O(c))throw new i("INVALID_JSONL","Every record must be a JSON object.",{lineNumber:r+1})}return{recordCount:n.length,byteLength:e}}const P=JSON;function Dt(s){const{digits:t,exponent:e}=V(s);return!t||e>=0n}function j(s,t,e){const n=s[t],r=P.isRawJSON(n)?Number(n.rawJSON):n;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||Object.is(r,-0)||P.isRawJSON(n)&&!Dt(n.rawJSON))throw new i("INVALID_METADATA","Metadata field must be a nonnegative safe integer.",{...e,reason:"INVALID_FIELD",field:t});return s[t]=r,r}function Ot(s,t){W(s,"INVALID_METADATA",t);let e;try{e=P.parse(s,(n,r,o)=>typeof r=="number"&&JSON.stringify(r)!==o.source?P.rawJSON(o.source):r)}catch{throw new i("INVALID_METADATA","meta.json must contain valid JSON.",{...t,reason:"INVALID_JSON"})}if(!O(e))throw new i("INVALID_METADATA","meta.json must contain an object.",{...t,reason:"INVALID_FIELD"});if(j(e,"version",t)!==1)throw new i("INVALID_METADATA","Unsupported metadata format version.",{...t,reason:"UNSUPPORTED_VERSION",field:"version"});for(const n of["createdAt","updatedAt","recordCount","byteLength"])j(e,n,t);if(j(e,"revision",t)===0||typeof e.dataSha!="string"||!/^[a-f0-9]{40}$/.test(e.dataSha))throw new i("INVALID_METADATA","Table revision or dataSha is invalid.",{...t,reason:"INVALID_FIELD",field:"revision/dataSha"});return e}function St(s){return JSON.stringify(s,null,2)+`
|
|
4
|
+
`}class Z{constructor(t,e,n){this.repository=t,this.name=n,g(e),g(n),this.root=`${e}/${n}`,this.metaPath=`${this.root}/meta.json`,this.dataPath=`${this.root}/data.jsonl`}repository;name;root;metaPath;dataPath;context(t=this.metaPath){return{path:t,table:this.name}}async metadata(t,e){const n=await this.repository.files.find(t,this.metaPath,e);if(!n){if((await this.repository.files.directory(t,this.root,e))?.length)throw new i("INVALID_METADATA","Existing table is missing meta.json.",{...this.context(),reason:"MISSING_METADATA"});return}const r=await this.repository.content(n,e);if(_(r)!==n.sha)throw new i("INVALID_METADATA","meta.json SHA does not match its content.",{...this.context(),reason:"META_SHA_MISMATCH"});return{meta:Ot(r,this.context()),entry:n}}async state(t,e){const[n,r]=await Promise.all([this.metadata(t,e),this.repository.files.find(t,this.dataPath,e)]);if(!n)return{metadata:n,data:r};if(!r)throw new i("INVALID_METADATA","Table is missing data.jsonl.",{...this.context(),path:this.dataPath,reason:"MISSING_DATA"});return{metadata:n,data:r}}async validatedContent(t,e){if(!t.metadata)return"";const{meta:n}=t.metadata;if(n.dataSha!==t.data.sha)throw new i("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const r=await this.repository.content(t.data,e);if(_(r)!==t.data.sha)throw new i("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const o=C(r,!1);if(o.recordCount!==n.recordCount||o.byteLength!==n.byteLength)throw new i("INVALID_METADATA","Statistics do not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"STATISTICS_MISMATCH"});return r}async write(t,e,n,r,o,c){const a=Date.now(),d=(e.metadata?.meta.revision??0)+1;if(!Number.isSafeInteger(d))throw new i("INVALID_METADATA","Table revision cannot be incremented safely.",{...this.context(),reason:"REVISION_OVERFLOW",field:"revision"});const u=await this.repository.createBlob(n,c),h={...e.metadata?.meta,version:1,createdAt:e.metadata?.meta.createdAt??a,updatedAt:a,...r,revision:d,dataSha:u},l=await this.repository.commit(t,[{path:this.dataPath,sha:u,mode:e.data?.mode},{path:this.metaPath,content:St(h),mode:e.metadata?.entry.mode}],`github-db: ${o} ${JSON.stringify(this.root)}
|
|
4
5
|
|
|
5
6
|
client: @secret-momo/github-db
|
|
6
|
-
endpoint: ${this.repository.endpoint}`,
|
|
7
|
-
`);e.at(-1)===""&&e.pop();const n=new Set;return e.map((r,
|
|
7
|
+
endpoint: ${this.repository.endpoint}`,c);return{meta:h,commitSha:l.commitSha}}}function b(s,t="INVALID_INPUT",e={},n=1){const r=()=>{throw new i(t,"Expected a plain JSON object with only serializable values.",{...e,reason:"NOT_JSON"})},o=new Set,c=(a,d,u)=>{if(a===null||typeof a=="boolean")return;if(typeof a=="string"){a.isWellFormed()||r();return}if(typeof a=="number"){Number.isFinite(a)||r();return}if(typeof a!="object")return r();k(d,t,{...e,field:u});const h=Array.isArray(a),l=Object.getPrototypeOf(a);((h?l!==Array.prototype:l!==Object.prototype&&l!==null)||o.has(a))&&r(),o.add(a);const w=Reflect.ownKeys(a);h&&w.length!==a.length+1&&r();for(const m of w){if(h&&m==="length")continue;if(typeof m!="string"||!m.isWellFormed())return r();h&&(!/^(0|[1-9]\d*)$/.test(m)||Number(m)>=a.length)&&r();const f=Object.getOwnPropertyDescriptor(a,m);(!f.enumerable||!("value"in f))&&r(),c(f.value,d+1,`${u}.${m}`)}o.delete(a)};try{return O(s)?(c(s,n,"$"),JSON.parse(JSON.stringify(s))):r()}catch(a){if(a instanceof i)throw a;return r()}}function F(s,t){const e=n=>{throw new i("INVALID_INPUT","Expected a plain dense array of batch inputs.",{reason:"NOT_JSON",...n===void 0?{}:{itemIndex:n}})};try{if(!Array.isArray(s)||Object.getPrototypeOf(s)!==Array.prototype||Reflect.ownKeys(s).length!==s.length+1)return e();const n=[];for(let r=0;r<s.length;r++){const o=Object.getOwnPropertyDescriptor(s,String(r));(!o?.enumerable||!("value"in o))&&e(r),n.push(t(o.value,r))}return n}catch(n){if(n instanceof i)throw n;return e()}}function D(s,t="INVALID_INPUT",e={}){if(typeof s!="string"||!s.trim()||!s.isWellFormed())throw new i(t,"id must be a nonempty, well-formed string.",{...e,reason:"INVALID_ID",field:"id"})}function tt(s){const{sign:t,digits:e,exponent:n}=V(s);return e?`${t}${e}e${n}`:"0"}const Lt=JSON.parse;function et(s,t){if(!s)return[];const e=s.split(`
|
|
8
|
+
`);e.at(-1)===""&&e.pop();const n=new Set;return e.map((r,o)=>{const c={...t,lineNumber:o+1};W(r,"INVALID_RECORD",c);const a=Lt(r,(u,h,l)=>{if(typeof h=="number"&&(!Number.isFinite(h)||tt(l.source)!==tt(JSON.stringify(h))))throw new i("INVALID_RECORD","Record number cannot round-trip without losing precision.",{...t,lineNumber:o+1,reason:"NUMERIC_PRECISION"});return h}),d=b(a,"INVALID_RECORD",c);D(d.id,"INVALID_RECORD",c);for(const u of["createdAt","updatedAt"]){const h=a[u];if(typeof h!="number"||!Number.isSafeInteger(h)||h<0||Object.is(h,-0))throw new i("INVALID_RECORD","Record timestamps must be nonnegative safe integers.",{...c,reason:"INVALID_TIMESTAMP",field:u})}if(n.has(d.id))throw new i("DUPLICATE_ID","Duplicate id in table data.",{...c,reason:"DUPLICATE_ID",field:"id"});return n.add(d.id),{record:d,source:r}})}function _t(s){return s.length?s.map(t=>t.source).join(`
|
|
8
9
|
`)+`
|
|
9
|
-
`:""}function
|
|
10
|
+
`:""}function M(s,t,e,n){if(D(s,"INVALID_INPUT",{itemIndex:e}),t.has(s))throw new i(n,"Batch inputs contain a duplicate id.",{reason:"DUPLICATE_ID",field:"id",itemIndex:e});return t.add(s),s}function $(s){const t=p(s);if(t?.aborted)throw new i("ABORTED","Request was cancelled.",{dispatched:!1});return t}class rt{constructor(t,e,n){this.repository=t,this.dbName=e,this.name=n,this.storage=new Z(t,e,n)}repository;dbName;name;storage;async findAll(t={},e={}){const n=p(e),r=b(t),o=await this.repository.snapshot(n),c=await this.storage.state(o,n);return et(await this.storage.validatedContent(c,n),this.storage.context(this.storage.dataPath)).filter(({record:a})=>Object.entries(r).every(([d,u])=>Object.hasOwn(a,d)&&ot(a[d],u))).map(({record:a})=>a)}async find(t={},e={}){return(await this.findAll(t,e))[0]??null}async findById(t,e={}){return D(t),this.find({id:t},e)}async insert(t,e={}){const n=b(t);if(Object.hasOwn(n,"createdAt")||Object.hasOwn(n,"updatedAt"))throw new i("INVALID_INPUT","Record timestamps are managed by the SDK.");const r=Object.hasOwn(n,"id")?n.id:v();return D(r),this.mutate("insert",o=>{if(o.some(({record:d})=>d.id===r))throw new i("DUPLICATE_ID","id already exists in this table.",{...this.storage.context(this.storage.dataPath),reason:"DUPLICATE_ID",field:"id"});const c=Date.now(),a={...n,id:r,createdAt:c,updatedAt:c};return o.push({record:a,source:JSON.stringify(a)}),{result:a,write:!0}},e)}async updateById(t,e,n={}){D(t);const r=b(e);if(!Object.keys(r).length||["id","createdAt","updatedAt"].some(o=>Object.hasOwn(r,o)))throw new i("INVALID_INPUT","Update requires business fields and cannot change system fields.");return this.mutate("update",o=>{const c=o.find(({record:d})=>d.id===t);if(!c)throw new i("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND"});const a={...c.record,...r,updatedAt:Date.now()};return c.record=a,c.source=JSON.stringify(a),{result:a,write:!0}},n)}async insertMany(t,e={}){const n=$(e),r=new Set,o=F(t,(c,a)=>{const d=b(c,"INVALID_INPUT",{itemIndex:a});if(Object.hasOwn(d,"createdAt")||Object.hasOwn(d,"updatedAt"))throw new i("INVALID_INPUT","Record timestamps are managed by the SDK.",{itemIndex:a});const u=M(Object.hasOwn(d,"id")?d.id:v(),r,a,"DUPLICATE_ID");return{...d,id:u}});return o.length?this.mutate("insertMany",c=>{const a=new Set(c.map(({record:h})=>h.id));for(const[h,l]of o.entries())if(a.has(l.id))throw new i("DUPLICATE_ID","id already exists in this table.",{...this.storage.context(this.storage.dataPath),reason:"DUPLICATE_ID",field:"id",itemIndex:h});const d=Date.now(),u=o.map(h=>({...h,createdAt:d,updatedAt:d}));for(const h of u)c.push({record:h,source:JSON.stringify(h)});return{result:u,write:!0}},{signal:n}):[]}async updateManyById(t,e={}){const n=$(e),r=new Set,o=F(t,(c,a)=>{const d=b(c,"INVALID_INPUT",{itemIndex:a},0);if(Object.keys(d).length!==2||!Object.hasOwn(d,"id")||!Object.hasOwn(d,"patch"))throw new i("INVALID_INPUT","Update entries require only id and patch.",{itemIndex:a});const u=M(d.id,r,a,"INVALID_INPUT"),h=b(d.patch,"INVALID_INPUT",{itemIndex:a});if(!Object.keys(h).length||["id","createdAt","updatedAt"].some(l=>Object.hasOwn(h,l)))throw new i("INVALID_INPUT","Update requires business fields and cannot change system fields.",{itemIndex:a});return{id:u,patch:h}});return o.length?this.mutate("updateManyById",c=>{const a=new Map(c.map(u=>[u.record.id,u]));for(const[u,h]of o.entries())if(!a.has(h.id))throw new i("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND",itemIndex:u});const d=Date.now();return{result:o.map(({id:u,patch:h})=>{const l=a.get(u),w={...l.record,...h,updatedAt:d};return l.record=w,l.source=JSON.stringify(w),w}),write:!0}},{signal:n}):[]}async deleteManyById(t,e={}){const n=$(e),r=new Set,o=F(t,(c,a)=>M(c,r,a,"INVALID_INPUT"));return o.length?this.mutate("deleteManyById",c=>{const a=new Set(c.map(({record:h})=>h.id)),d=o.map(h=>a.has(h));if(!d.some(Boolean))return{result:d,write:!1};let u=0;for(const h of c)r.has(h.record.id)||(c[u++]=h);return c.length=u,{result:d,write:!0}},{signal:n}):[]}async deleteById(t,e={}){return D(t),this.mutate("delete",n=>{const r=n.findIndex(({record:o})=>o.id===t);return r<0?{result:!1,write:!1}:(n.splice(r,1),{result:!0,write:!0})},e)}async mutate(t,e,n){const r=p(n);return this.repository.enqueue(async()=>{const o=await this.repository.snapshot(r),c=await this.storage.state(o,r),a=et(await this.storage.validatedContent(c,r),this.storage.context(this.storage.dataPath)),d=e(a);if(d.write){const u=_t(a);await this.storage.write(o,c,u,C(u),t,r)}return d.result})}}class nt{constructor(t,e,n){this.repository=t,this.dbName=e,this.name=n,this.storage=new Z(t,e,n)}repository;dbName;name;storage;version(t,e){return J("sha256").update(JSON.stringify([this.repository.scope(),this.dbName,this.name,t.revision,e])).digest("hex")}async read(t={}){const e=p(t),n=await this.repository.snapshot(e),r=await this.storage.state(n,e);if(!r.metadata)throw new i("NOT_FOUND","Table does not exist.",{...this.storage.context(),path:this.storage.dataPath,reason:"TABLE_NOT_FOUND"});return{content:await this.storage.validatedContent(r,e),meta:r.metadata.meta,version:this.version(r.metadata.meta,r.data.sha),commitSha:n.commitSha}}async write(t,e={}){const n=p(e),r=e.expectedVersion;if(r!=null&&(typeof r!="string"||!/^[a-f0-9]{64}$/.test(r)))throw new i("INVALID_INPUT","expectedVersion must be an opaque table version or null.");const o=C(t);return this.repository.enqueue(async()=>{const c=await this.repository.snapshot(n),a=await this.storage.state(c,n),d=a.metadata?this.version(a.metadata.meta,a.data.sha):null;if(r!==void 0&&r!==d)throw new i("CONFLICT","Table version does not match expectedVersion.",{...this.storage.context(),path:this.storage.dataPath,reason:"VERSION_MISMATCH"});await this.storage.validatedContent(a,n);const u=await this.storage.write(c,a,t,o,"write",n);return{...u,version:this.version(u.meta,u.meta.dataSha)}})}async getMeta(t={}){const e=p(t),n=await this.repository.snapshot(e),r=await this.storage.metadata(n,e);if(!r)throw new i("NOT_FOUND","Table does not exist.",{...this.storage.context(),reason:"TABLE_NOT_FOUND"});return{meta:r.meta,commitSha:n.commitSha}}}class st{constructor(t,e){this.repository=t,this.name=e,g(e),this.files=new Q(t,e)}repository;name;files;async listTables(t={}){const e=p(t),n=await this.repository.snapshot(e),r=(await this.repository.files.directory(n,this.name,e)??[]).filter(a=>a.type==="tree"&&a.path!==E&&q(a.path)),o=new Array(r.length);let c=0;return await Promise.all(Array.from({length:Math.min(8,r.length)},async()=>{for(;c<r.length;){const a=c++,d=r[a],u=await this.repository.files.directory(n,`${this.name}/${d.path}`,e),h=new Set(u?.filter(l=>l.type==="blob"&&["100644","100755"].includes(l.mode)).map(l=>l.path));o[a]=h.has("meta.json")&&h.has("data.jsonl")?d.path:void 0}})),o.filter(a=>a!==void 0).sort()}getTable(t){if(t===E)throw new i("INVALID_INPUT","This name is reserved for files.");return new nt(this.repository,this.name,t)}getRecordTable(t){if(t===E)throw new i("INVALID_INPUT","This name is reserved for files.");return new rt(this.repository,this.name,t)}}class Et{repository;constructor(t){this.repository=new yt(t)}getDB(t){return new st(this.repository,t)}}export{Et as GitHubDBClient,i as GitHubDBError,st as GitHubDatabase,Q as GitHubFiles,rt as GitHubRecordTable,nt as GitHubTable};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@secret-momo/github-db",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "A lightweight wrapper that turns a GitHub repository into a simple database.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"packageManager": "bun@1.4.2",
|
|
@@ -63,19 +63,19 @@
|
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
65
|
"@eslint/js": "10.0.1",
|
|
66
|
-
"@types/bun": "1.4.
|
|
67
|
-
"eslint": "10.
|
|
66
|
+
"@types/bun": "1.4.3",
|
|
67
|
+
"eslint": "10.13.0",
|
|
68
68
|
"eslint-plugin-import-x": "4.17.1",
|
|
69
69
|
"eslint-plugin-unused-imports": "4.4.1",
|
|
70
70
|
"husky": "9.1.7",
|
|
71
71
|
"jiti": "2.7.0",
|
|
72
72
|
"lint-staged": "17.6.0",
|
|
73
|
-
"prettier": "3.9.
|
|
74
|
-
"rollup": "4.64.
|
|
73
|
+
"prettier": "3.9.10",
|
|
74
|
+
"rollup": "4.64.10",
|
|
75
75
|
"rollup-plugin-dts": "6.5.1",
|
|
76
76
|
"rollup-plugin-esbuild": "6.2.1",
|
|
77
77
|
"typescript": "6.0.3",
|
|
78
|
-
"typescript-eslint": "8.
|
|
78
|
+
"typescript-eslint": "8.72.0"
|
|
79
79
|
},
|
|
80
80
|
"license": "MIT"
|
|
81
81
|
}
|