@secret-momo/github-db 0.3.0 → 1.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 +2 -2
- package/docs/architecture.md +2 -2
- package/docs/requirements.md +2 -2
- package/lib/index.js +5 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -27,7 +27,7 @@ const client = new GitHubDBClient({
|
|
|
27
27
|
token: process.env.GITHUB_TOKEN!,
|
|
28
28
|
owner: 'your-owner',
|
|
29
29
|
repo: 'your-repo',
|
|
30
|
-
// branch: 'main', //
|
|
30
|
+
// branch: 'main', // 省略时发现并缓存默认分支;空/全空白值非法
|
|
31
31
|
// timeout: 30_000, // 每个请求的超时毫秒数
|
|
32
32
|
});
|
|
33
33
|
const db = client.getDB('workbench');
|
|
@@ -193,7 +193,7 @@ await todos.findAll({ status: 'pending' }, { signal: controller.signal });
|
|
|
193
193
|
|
|
194
194
|
错误为 GitHubDBError,提供 code 与 details,包括 reason、path、table、field、lineNumber 和可用的 HTTP 诊断字段。dispatched 仅表示调用了 fetch,不证明服务器已收到请求。
|
|
195
195
|
|
|
196
|
-
|
|
196
|
+
写入在发布 PATCH 尚未发送时被取消返回 ABORTED,超时返回 TIMEOUT;SDK 已取得并验证 commitSha 时会附带该 SHA,SHA 尚未取得时不保证该字段。reason 为 BEFORE_PUBLICATION 的已知 commit 取消不会发送 PATCH;取消或超时可能留下未发布的 Git 对象。发布 PATCH 已投递后若结果不确定,返回 WRITE_RESULT_UNKNOWN 并携带尝试 commitSha。
|
|
197
197
|
|
|
198
198
|
- INVALID_INPUT / INVALID_RECORD / DUPLICATE_ID:非法输入、存储记录违反约束或重复主键。
|
|
199
199
|
- INVALID_METADATA / INVALID_JSONL / INVALID_UTF8:表完整性或文件格式错误。
|
package/docs/architecture.md
CHANGED
|
@@ -99,9 +99,9 @@ insert/update/delete 都在 repository 队列内固定快照、验证全表、
|
|
|
99
99
|
|
|
100
100
|
HTTP 请求保留 endpoint 前缀和 GitHub path。GitHub 管理 header 与代理 header 同时发送,不跟随重定向。所有后续 URL/提交使用的 Git SHA 先验证为 40 位小写十六进制。
|
|
101
101
|
|
|
102
|
-
每次请求合并 caller signal 与 timeout,原始数据按 UTF-8 fatal 解码。错误不回显上游正文,保留状态、requestId、retryAfter、dispatched。仅发布 PATCH 的 409/422 归类 CONFLICT/PUBLISH_REJECTED;其他阶段保留 HTTP_ERROR。发布后非确定响应归 WRITE_RESULT_UNKNOWN,并附 commitSha
|
|
102
|
+
每次请求合并 caller signal 与 timeout,原始数据按 UTF-8 fatal 解码。错误不回显上游正文,保留状态、requestId、retryAfter、dispatched。仅发布 PATCH 的 409/422 归类 CONFLICT/PUBLISH_REJECTED;其他阶段保留 HTTP_ERROR。发布后非确定响应归 WRITE_RESULT_UNKNOWN,并附 commitSha;发布 PATCH 未发送时 caller 取消为 ABORTED、超时为 TIMEOUT,已取得并验证的 commit SHA 可附带,未知 SHA 不保证;投递前取消保持已知 SHA 时的 BEFORE_PUBLICATION 语义。
|
|
103
103
|
|
|
104
|
-
创建
|
|
104
|
+
创建 Git 对象或 tree 后,取消/超时可能留下未发布对象;SDK 不继续发布、不自动重试。发布 PATCH 已投递后的取消、超时或异常继续归 WRITE_RESULT_UNKNOWN,并携带尝试 commitSha。
|
|
105
105
|
|
|
106
106
|
## 7. 构建与验证
|
|
107
107
|
|
package/docs/requirements.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
## 1. 环境与连接
|
|
6
6
|
|
|
7
|
-
TypeScript ESM npm SDK,支持 Node.js 24+ 与 Bun。运行与开发环境仅支持 macOS 和 Linux,不支持 Windows。client 配置 token、owner、repo,可选 branch、endpoint、headers、timeout、fetch、apiVersion
|
|
7
|
+
TypeScript ESM npm SDK,支持 Node.js 24+ 与 Bun。运行与开发环境仅支持 macOS 和 Linux,不支持 Windows。client 配置 token、owner、repo,可选 branch、endpoint、headers、timeout、fetch、apiVersion。branch 省略时发现并缓存默认分支;显式 branch 必须是非空字符串,空字符串或全空白字符串报 INVALID_INPUT,分支值不做 trim 或 Unicode 归一化。仓库与目标分支必须人工保证已有至少一次提交,SDK 不初始化空仓库或创建分支。
|
|
8
8
|
|
|
9
9
|
交付仅提供 ESM import 入口,不提供 CommonJS require/default 入口或 CJS 产物。支持从 npm registry 安装发布包,或在本地构建后使用;不支持直接安装 Git URL 依赖。
|
|
10
10
|
|
|
@@ -72,7 +72,7 @@ force=false 发布拒绝竞争提交,不强制覆盖、不自动重试。外
|
|
|
72
72
|
|
|
73
73
|
所有操作支持 AbortSignal。提交信息由 SDK 自动生成,不接受调用方指定,固定为 `github-db: <operation> "<db>/<table>"`,表路径使用 JSON 字符串转义。operation 对应公开 API,为 write、insert、update 或 delete;首次建表沿用调用操作,删除最后一条记录仍为 delete。消息不包含记录内容、ID、时间戳或 SHA。调用入口复制选项与 CRUD 输入,排队期间调用方修改不影响本次操作。错误包含 code 与结构化诊断,不回显上游秘密正文;dispatched 仅表示调用 fetch。
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
发布 PATCH 尚未发送时,caller 取消返回 ABORTED,超时返回 TIMEOUT;SDK 已取得并验证 commit SHA 时可附带该 SHA,其中已知 commit 的发布前 caller 取消包含 reason=BEFORE_PUBLICATION 和 commitSha,SHA 尚未取得时不保证该字段。取消或超时可能留下未发布的 Git 对象,但 SDK 不继续发布。发布 PATCH 已投递后的取消、超时或异常返回 WRITE_RESULT_UNKNOWN,并携带尝试 commitSha。
|
|
76
76
|
|
|
77
77
|
## 7. 验收
|
|
78
78
|
|
package/lib/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`);a.at(-1)===""&&a.pop();for(const[r,i]of a.entries()){let n;try{n=JSON.parse(i)}catch{throw new o("INVALID_JSONL","Every record line must be valid JSON.",{lineNumber:r+1})}if(!b(n))throw new o("INVALID_JSONL","Every record must be a JSON object.",{lineNumber:r+1})}return{recordCount:a.length,byteLength:e}}const q=512;function v(s,t,e){if(s>q)throw new o(t,"JSON nesting exceeds 512 object/array containers.",{...e,reason:"TOO_DEEP"})}function P(s,t,e){let a=0,r=!1;for(let i=0;i<s.length;i++){const n=s[i];r&&n==="\\"?i++:n==='"'?r=!r:r||(n==="{"||n==="["?v(++a,t,e):(n==="}"||n==="]")&&a--)}}function V(s){const t=/^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(s),e=t[3]??"",a=(t[2]+e).replace(/^0+/,""),r=a.replace(/0+$/,"");return{sign:a?t[1]:"",digits:r,exponent:a?BigInt(t[4]??0)-BigInt(e.length)+BigInt(a.length-r.length):0n}}const g=JSON;function k(s){const{digits:t,exponent:e}=V(s);return!t||e>=0n}function E(s,t,e){const a=s[t],r=g.isRawJSON(a)?Number(a.rawJSON):a;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||Object.is(r,-0)||g.isRawJSON(a)&&!k(a.rawJSON))throw new o("INVALID_METADATA","Metadata field must be a nonnegative safe integer.",{...e,reason:"INVALID_FIELD",field:t});return s[t]=r,r}function W(s,t){P(s,"INVALID_METADATA",t);let e;try{e=g.parse(s,(a,r,i)=>typeof r=="number"&&JSON.stringify(r)!==i.source?g.rawJSON(i.source):r)}catch{throw new o("INVALID_METADATA","meta.json must contain valid JSON.",{...t,reason:"INVALID_JSON"})}if(!b(e))throw new o("INVALID_METADATA","meta.json must contain an object.",{...t,reason:"INVALID_FIELD"});if(E(e,"version",t)!==1)throw new o("INVALID_METADATA","Unsupported metadata format version.",{...t,reason:"UNSUPPORTED_VERSION",field:"version"});for(const a of["createdAt","updatedAt","recordCount","byteLength"])E(e,a,t);if(E(e,"revision",t)===0||typeof e.dataSha!="string"||!/^[a-f0-9]{40}$/.test(e.dataSha))throw new o("INVALID_METADATA","Table revision or dataSha is invalid.",{...t,reason:"INVALID_FIELD",field:"revision/dataSha"});return e}function Y(s){return JSON.stringify(s,null,2)+`
|
|
3
|
-
`}class
|
|
4
|
-
`);e.at(-1)===""&&e.pop();const
|
|
1
|
+
import{createHash as C,randomUUID as z}from"node:crypto";import{isDeepStrictEqual as K}from"node:util";import{Buffer as E}from"node:buffer";class i extends Error{constructor(t,e,r={}){super(e),this.code=t,this.details=r}code;details;name="GitHubDBError"}function g(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function x(n){if(!g(n))throw new i("INVALID_INPUT","Options must be an object.")}function _(n){if(n!==void 0&&!(n instanceof AbortSignal))throw new i("INVALID_INPUT","signal must be an AbortSignal.")}function X(n){if(typeof n!="string"||!n.isWellFormed())throw new i("INVALID_INPUT","Content must be a well-formed Unicode string.")}function H(n){return typeof n=="string"&&!!n.trim()&&n.isWellFormed()&&n!=="."&&n!==".."&&n.toLowerCase()!==".git"&&!/[/\\\p{Cc}\p{Cf}\u115F\u1160\u3164\u2800\uFFA0]/u.test(n)}function N(n){if(!H(n))throw new i("INVALID_INPUT","Names must be nonempty, unambiguous path segments.");return n}function A(n){x(n);const t=n.signal;return _(t),t}const Q=1e7;function Z(n){let t=!1,e=!1;for(let r=0;r<n.length;r++){const a=n[r];if(!t){a==='"'&&(t=!0);continue}if(a==="\\"){if(n[++r]==="u"&&/^[0-9a-fA-F]{4}$/.test(n.slice(r+1,r+5))){const s=Number.parseInt(n.slice(r+1,r+5),16);if(r+=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(a==='"'){if(e)return!0;t=!1}else if(e)return!0}return e}function L(n,t=!0){X(n);const e=E.byteLength(n,"utf8");if(t&&e>Q)throw new i("TABLE_TOO_LARGE","Table exceeds 10,000,000 UTF-8 bytes.");if(n==="")return{recordCount:0,byteLength:0};const r=n.split(`
|
|
2
|
+
`);r.at(-1)===""&&r.pop();for(const[a,s]of r.entries()){let o;try{o=JSON.parse(s)}catch{throw new i("INVALID_JSONL","Every record line must be valid JSON.",{lineNumber:a+1})}if(Z(s))throw new i("INVALID_JSONL","JSONL contains invalid Unicode.",{lineNumber:a+1,reason:"INVALID_UNICODE"});if(!g(o))throw new i("INVALID_JSONL","Every record must be a JSON object.",{lineNumber:a+1})}return{recordCount:r.length,byteLength:e}}function T(n){if(!g(n))throw new i("INVALID_RESPONSE","Expected a GitHub response object.");return n}function w(n){if(typeof n!="string"||!/^[a-f0-9]{40}$/.test(n))throw new i("INVALID_RESPONSE","Expected a 40-character lowercase Git SHA.");return n}function v(n){if(typeof n!="string"||!n||!n.isWellFormed())throw new i("INVALID_RESPONSE","Expected a nonempty well-formed GitHub response field.");return n}function tt(n){if(typeof n!="string"||!n.trim()||!n.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(n))throw new i("INVALID_RESPONSE","Expected a valid well-formed GitHub branch name.");return n}function et(n,t){try{if(n===null||typeof n!="object")return;const e=n,r=e.status,a=e.ok,s=e.headers,o=e.json,c=e.arrayBuffer;if(typeof r!="number"||!Number.isInteger(r)||r<100||r>599||typeof a!="boolean"||a!==(r>=200&&r<300)||s===null||typeof s!="object")return;const d=s.get;if(typeof d!="function"||typeof o!="function"||typeof c!="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:a,json:o.bind(n),arrayBuffer:c.bind(n),details:{dispatched:t,status:r,requestId:u??void 0,retryAfter:h??void 0}}}catch{return}}function P(n,t,e){const r=Promise.resolve(n);return t?new Promise((a,s)=>{let o=!1;const c=()=>t.removeEventListener("abort",d),d=()=>{o||(o=!0,c(),s(e()))};t.addEventListener("abort",d,{once:!0}),r.then(u=>{o||(o=!0,c(),a(u))},u=>{o||(o=!0,c(),s(u))}),t.aborted&&d()}):r}function rt(n){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(!t)return!1;const e=Number(t[1]),r=Number(t[2]),a=Number(t[3]);if(r<1||r>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 a>=1&&a<=s[r-1]}class at{endpoint;prefix;headers;fetcher;timeout;constructor(t){x(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(N(t.owner),N(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.")}if(!["https:","http:"].includes(e.protocol)||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"||!rt(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}async request(t,e,r,a,s){_(s);let o=!1;const c=new Headers(this.headers);c.set("Accept",a?"application/vnd.github.raw+json":"application/vnd.github+json"),r!==void 0&&c.set("Content-Type","application/json");const d=s?[s]:[],u=this.timeout===void 0?void 0:AbortSignal.timeout(this.timeout);u&&d.push(u);const h=d.length?AbortSignal.any(d):void 0,p=e==="POST"&&t==="/git/commits",f=h,m=()=>p&&s?.aborted===!0,l=()=>new i(s?.aborted?"ABORTED":"TIMEOUT",s?.aborted?"Request was cancelled.":"Request timed out.",{dispatched:o});if(h?.aborted)throw l();let U;try{o=!0;const I=this.fetcher(`${this.endpoint}${this.prefix}${t}`,{method:e,headers:c,body:r===void 0?void 0:JSON.stringify(r),redirect:"manual",signal:h});U=await P(I,f,l)}catch{throw h?.aborted?l():new i("NETWORK_ERROR","GitHub request failed.",{dispatched:o})}if(h?.aborted&&!m())throw l();const y=et(U,o);if(!y)throw new i("INVALID_RESPONSE","fetch must return a valid Response.",{dispatched:o});const{details:b}=y;if(!y.ok)throw new i("HTTP_ERROR",`GitHub request returned HTTP ${b.status}.`,{...b,...b.status>=300&&b.status<400?{reason:"REDIRECT"}:{}});try{if(!a){const Y=await P(y.json(),f,l);if(h?.aborted&&!m())throw l();return Y}const I=await P(y.arrayBuffer(),f,l);let j;try{j=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(I)}catch{throw new i("INVALID_UTF8","File content is not valid UTF-8.",b)}if(h?.aborted&&!m())throw l();return j}catch(I){throw h?.aborted?l():I instanceof i?I:new i("INVALID_RESPONSE","Could not read the GitHub response.",b)}}async json(t,e="GET",r,a){return T(await this.request(t,e,r,!1,a))}scope(t){return JSON.stringify([this.endpoint,this.prefix,t])}}function nt(n){if(typeof n!="string")throw new i("INVALID_INPUT","Path must be a string.");return n.split("/").forEach(N),n}function ot(n){const t=v(n);if(t.includes("/"))throw new i("INVALID_RESPONSE","GitHub returned an invalid tree entry path.");return t}class st{constructor(t){this.transport=t}transport;tree(t,e,r){let a=t.trees.get(e);return a||(a=this.transport.json(`/git/trees/${e}`,"GET",void 0,r).then(s=>{if(s.truncated!==!1||!Array.isArray(s.tree))throw new i("INVALID_RESPONSE","GitHub returned an incomplete tree.");return s.tree.map(o=>{const c=T(o);return{path:ot(c.path),sha:w(c.sha),type:v(c.type),mode:v(c.mode)}})}),t.trees.set(e,a)),a}async resolve(t,e,r){const a=nt(e).split("/");let s=t.treeSha;for(let o=0;o<a.length;o++){const c=(await this.tree(t,s,r)).find(d=>d.path===a[o]);if(!c)return;if(o===a.length-1)return c;if(c.type!=="tree")throw new i("INVALID_METADATA","A parent path is not a directory.",{path:a.slice(0,o+1).join("/"),reason:"PATH_NOT_DIRECTORY"});s=c.sha}}async find(t,e,r){const a=await this.resolve(t,e,r);if(a&&(a.type!=="blob"||!["100644","100755"].includes(a.mode)))throw new i("INVALID_METADATA","Path must reference a regular file.",{path:e,reason:"NOT_REGULAR_FILE"});return a}async directory(t,e,r){const a=await this.resolve(t,e,r);if(a){if(a.type!=="tree")throw new i("INVALID_METADATA","Path must reference a directory.",{path:e,reason:"PATH_NOT_DIRECTORY"});return this.tree(t,a.sha,r)}}}function R(n){const t=E.from(n,"utf8");return C("sha1").update(`blob ${t.byteLength}\0`).update(t).digest("hex")}class it{transport;files;branchName;branchLookup;queue=Promise.resolve();constructor(t){this.transport=new at(t),this.files=new st(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(r=>(this.branchName=tt(r.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((r,a)=>{const s=()=>a(new i("ABORTED","Request was cancelled.",{dispatched:!0}));t.addEventListener("abort",s,{once:!0}),e.then(r,a).finally(()=>t.removeEventListener("abort",s))})}async snapshot(t){_(t);const e=await this.branch(t),r=await this.transport.json(`/git/ref/heads/${encodeURIComponent(e)}`,"GET",void 0,t),a=w(T(r.object).sha),s=await this.transport.json(`/git/commits/${a}`,"GET",void 0,t);return{commitSha:a,treeSha:w(T(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 r=await this.transport.json("/git/blobs","POST",{content:E.from(t,"utf8").toString("base64"),encoding:"base64"},e),a=w(r.sha);if(a!==R(t))throw new i("INVALID_RESPONSE","GitHub returned a blob SHA that does not match content.");return a}async commit(t,e,r,a){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,a)}))),o=await this.transport.json("/git/trees","POST",{base_tree:t.treeSha,tree:s},a),c=await this.transport.json("/git/commits","POST",{tree:w(o.sha),parents:[t.commitSha],message:r},a),d=w(c.sha),u=await this.branch();if(a?.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},a);if(w(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 ct=512;function M(n,t,e){if(n>ct)throw new i(t,"JSON nesting exceeds 512 object/array containers.",{...e,reason:"TOO_DEEP"})}function $(n,t,e){let r=0,a=!1;for(let s=0;s<n.length;s++){const o=n[s];a&&o==="\\"?s++:o==='"'?a=!a:a||(o==="{"||o==="["?M(++r,t,e):(o==="}"||o==="]")&&r--)}}function J(n){const t=/^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(n),e=t[3]??"",r=(t[2]+e).replace(/^0+/,""),a=r.replace(/0+$/,"");return{sign:r?t[1]:"",digits:a,exponent:r?BigInt(t[4]??0)-BigInt(e.length)+BigInt(r.length-a.length):0n}}const S=JSON;function ht(n){const{digits:t,exponent:e}=J(n);return!t||e>=0n}function V(n,t,e){const r=n[t],a=S.isRawJSON(r)?Number(r.rawJSON):r;if(typeof a!="number"||!Number.isSafeInteger(a)||a<0||Object.is(a,-0)||S.isRawJSON(r)&&!ht(r.rawJSON))throw new i("INVALID_METADATA","Metadata field must be a nonnegative safe integer.",{...e,reason:"INVALID_FIELD",field:t});return n[t]=a,a}function dt(n,t){$(n,"INVALID_METADATA",t);let e;try{e=S.parse(n,(r,a,s)=>typeof a=="number"&&JSON.stringify(a)!==s.source?S.rawJSON(s.source):a)}catch{throw new i("INVALID_METADATA","meta.json must contain valid JSON.",{...t,reason:"INVALID_JSON"})}if(!g(e))throw new i("INVALID_METADATA","meta.json must contain an object.",{...t,reason:"INVALID_FIELD"});if(V(e,"version",t)!==1)throw new i("INVALID_METADATA","Unsupported metadata format version.",{...t,reason:"UNSUPPORTED_VERSION",field:"version"});for(const r of["createdAt","updatedAt","recordCount","byteLength"])V(e,r,t);if(V(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 ut(n){return JSON.stringify(n,null,2)+`
|
|
3
|
+
`}class B{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,N(e),N(r),this.root=`${e}/${r}`,this.metaPath=`${this.root}/meta.json`,this.dataPath=`${this.root}/data.jsonl`}repository;dbName;name;root;metaPath;dataPath;context(t=this.metaPath){return{path:t,table:this.name}}async metadata(t,e){const r=await this.repository.files.find(t,this.metaPath,e);if(!r){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 a=await this.repository.content(r,e);if(R(a)!==r.sha)throw new i("INVALID_METADATA","meta.json SHA does not match its content.",{...this.context(),reason:"META_SHA_MISMATCH"});return{meta:dt(a,this.context()),entry:r}}async state(t,e){const[r,a]=await Promise.all([this.metadata(t,e),this.repository.files.find(t,this.dataPath,e)]);if(r&&!a)throw new i("INVALID_METADATA","Table is missing data.jsonl.",{...this.context(),path:this.dataPath,reason:"MISSING_DATA"});return{metadata:r,data:a}}async validatedContent(t,e){if(!t.metadata||!t.data)return"";const{meta:r}=t.metadata;if(r.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 a=await this.repository.content(t.data,e);if(R(a)!==t.data.sha)throw new i("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const s=L(a,!1);if(s.recordCount!==r.recordCount||s.byteLength!==r.byteLength)throw new i("INVALID_METADATA","Statistics do not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"STATISTICS_MISMATCH"});return a}async write(t,e,r,a,s,o){const c=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(r,o),h={...e.metadata?.meta,version:1,createdAt:e.metadata?.meta.createdAt??c,updatedAt:c,...a,revision:d,dataSha:u},p=await this.repository.commit(t,[{path:this.dataPath,sha:u,mode:e.data?.mode},{path:this.metaPath,content:ut(h),mode:e.metadata?.entry.mode}],`github-db: ${s} ${JSON.stringify(this.root)}`,o);return{meta:h,commitSha:p.commitSha}}}function O(n,t="INVALID_INPUT",e={}){const r=()=>{throw new i(t,"Expected a plain JSON object with only serializable values.",{...e,reason:"NOT_JSON"})},a=new Set,s=(o,c,d)=>{if(o===null||typeof o=="boolean")return;if(typeof o=="string"){o.isWellFormed()||r();return}if(typeof o=="number"){Number.isFinite(o)||r();return}if(typeof o!="object"||o===null)return r();M(c,t,{...e,field:d});const u=Array.isArray(o),h=Object.getPrototypeOf(o);((u?h!==Array.prototype:h!==Object.prototype&&h!==null)||a.has(o))&&r(),a.add(o);const p=Reflect.ownKeys(o);u&&p.length!==o.length+1&&r();for(const f of p){if(u&&f==="length")continue;if(typeof f!="string"||!f.isWellFormed())return r();u&&(!/^(0|[1-9]\d*)$/.test(f)||Number(f)>=o.length)&&r();const m=Object.getOwnPropertyDescriptor(o,f);(!m.enumerable||!("value"in m))&&r(),s(m.value,c+1,`${d}.${f}`)}a.delete(o)};try{return g(n)?(s(n,1,"$"),JSON.parse(JSON.stringify(n))):r()}catch(o){if(o instanceof i)throw o;return r()}}function D(n,t="INVALID_INPUT",e={}){if(typeof n!="string"||!n.trim()||!n.isWellFormed())throw new i(t,"id must be a nonempty, well-formed string.",{...e,reason:"INVALID_ID",field:"id"})}function F(n){const{sign:t,digits:e,exponent:r}=J(n);return e?`${t}${e}e${r}`:"0"}const ft=JSON.parse;function G(n,t){if(!n)return[];const e=n.split(`
|
|
4
|
+
`);e.at(-1)===""&&e.pop();const r=new Set;return e.map((a,s)=>{const o={...t,lineNumber:s+1};$(a,"INVALID_RECORD",o);let c;try{c=ft(a,(u,h,p)=>{if(typeof h=="number"&&(!Number.isFinite(h)||F(p.source)!==F(JSON.stringify(h))))throw new i("INVALID_RECORD","Record number cannot round-trip without losing precision.",{...t,lineNumber:s+1,reason:"NUMERIC_PRECISION"});return h})}catch(u){throw u instanceof i?u:new i("INVALID_RECORD","Record line could not be parsed.",{...o,reason:"UNPARSABLE"})}const d=O(c,"INVALID_RECORD",o);D(d.id,"INVALID_RECORD",o);for(const u of["createdAt","updatedAt"]){const h=c[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.",{...o,reason:"INVALID_TIMESTAMP",field:u})}if(r.has(d.id))throw new i("DUPLICATE_ID","Duplicate id in table data.",{...o,reason:"DUPLICATE_ID",field:"id"});return r.add(d.id),{record:d,source:a}})}function lt(n){return n.length?n.map(t=>t.source).join(`
|
|
5
5
|
`)+`
|
|
6
|
-
`:""}class x{constructor(t,e,a){this.repository=t,this.dbName=e,this.name=a,this.storage=new U(t,e,a)}repository;dbName;name;storage;async findAll(t={},e={}){const a=I(e),r=T(t),i=await this.repository.snapshot(a),n=await this.storage.state(i,a);return j(await this.storage.validatedContent(n,a),this.storage.context(this.storage.dataPath)).filter(({record:h})=>Object.entries(r).every(([d,u])=>Object.hasOwn(h,d)&&B(h[d],u))).map(({record:h})=>h)}async find(t={},e={}){return(await this.findAll(t,e))[0]??null}async findById(t,e={}){return N(t),this.find({id:t},e)}async insert(t,e={}){const a=T(t);if(Object.hasOwn(a,"createdAt")||Object.hasOwn(a,"updatedAt"))throw new o("INVALID_INPUT","Record timestamps are managed by the SDK.");const r=Object.hasOwn(a,"id")?a.id:H();return N(r),this.mutate("insert",i=>{if(i.some(({record:d})=>d.id===r))throw new o("DUPLICATE_ID","id already exists in this table.",{...this.storage.context(this.storage.dataPath),reason:"DUPLICATE_ID",field:"id"});const n=Date.now(),h={...a,id:r,createdAt:n,updatedAt:n};return i.push({record:h,source:JSON.stringify(h)}),{result:h,write:!0}},e)}async updateById(t,e,a={}){N(t);const r=T(e);if(!Object.keys(r).length||["id","createdAt","updatedAt"].some(i=>Object.hasOwn(r,i)))throw new o("INVALID_INPUT","Update requires business fields and cannot change system fields.");return this.mutate("update",i=>{const n=i.find(({record:d})=>d.id===t);if(!n)throw new o("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND"});const h={...n.record,...r,updatedAt:Date.now()};return n.record=h,n.source=JSON.stringify(h),{result:h,write:!0}},a)}async deleteById(t,e={}){return N(t),this.mutate("delete",a=>{const r=a.findIndex(({record:i})=>i.id===t);return r<0?{result:!1,write:!1}:(a.splice(r,1),{result:!0,write:!0})},e)}async mutate(t,e,a){const r=I(a);return this.repository.enqueue(async()=>{const i=await this.repository.snapshot(r),n=await this.storage.state(i,r),h=j(await this.storage.validatedContent(n,r),this.storage.context(this.storage.dataPath)),d=e(h);if(d.write){const u=K(h);await this.storage.write(i,n,u,S(u),t,r)}return d.result})}}class ${constructor(t,e,a){this.repository=t,this.dbName=e,this.name=a,this.storage=new U(t,e,a)}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=I(t),a=await this.repository.snapshot(e),r=await this.storage.state(a,e);if(!r.metadata||!r.data)throw new o("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:a.commitSha}}async write(t,e={}){const a=I(e),r=e.expectedVersion;if(r!=null&&(typeof r!="string"||!/^[a-f0-9]{64}$/.test(r)))throw new o("INVALID_INPUT","expectedVersion must be an opaque table version or null.");const i=S(t);return this.repository.enqueue(async()=>{const n=await this.repository.snapshot(a),h=await this.storage.state(n,a),d=h.metadata&&h.data?this.version(h.metadata.meta,h.data.sha):null;if(r!==void 0&&r!==d)throw new o("CONFLICT","Table version does not match expectedVersion.",{...this.storage.context(),path:this.storage.dataPath,reason:"VERSION_MISMATCH"});await this.storage.validatedContent(h,a);const u=await this.storage.write(n,h,t,i,"write",a);return{...u,version:this.version(u.meta,u.meta.dataSha)}})}async getMeta(t={}){const e=I(t),a=await this.repository.snapshot(e),r=await this.storage.metadata(a,e);if(!r)throw new o("NOT_FOUND","Table does not exist.",{...this.storage.context(),reason:"TABLE_NOT_FOUND"});return{meta:r.meta,commitSha:a.commitSha}}}class M{constructor(t,e){this.repository=t,this.name=e,w(e)}repository;name;async listTables(t={}){const e=I(t),a=await this.repository.snapshot(e),r=await this.repository.files.directory(a,this.name,e);return(await Promise.all((r??[]).filter(i=>i.type==="tree"&&R(i.path)).map(async i=>{const n=await this.repository.files.directory(a,`${this.name}/${i.path}`,e),h=new Set(n?.filter(d=>d.type==="blob"&&["100644","100755"].includes(d.mode)).map(d=>d.path));return h.has("meta.json")&&h.has("data.jsonl")?i.path:void 0}))).filter(i=>i!==void 0).sort()}getTable(t){return new $(this.repository,this.name,t)}getRecordTable(t){return new x(this.repository,this.name,t)}}function y(s){if(!b(s))throw new o("INVALID_RESPONSE","Expected a GitHub response object.");return s}function m(s){if(typeof s!="string"||!/^[a-f0-9]{40}$/.test(s))throw new o("INVALID_RESPONSE","Expected a 40-character lowercase Git SHA.");return s}function D(s){if(typeof s!="string"||!s)throw new o("INVALID_RESPONSE","Expected a nonempty GitHub response field.");return s}class X{endpoint;prefix;headers;fetcher;timeout;constructor(t){L(t);for(const a of[t.token,t.owner,t.repo])if(typeof a!="string"||!a.trim())throw new o("INVALID_INPUT","token, owner and repo are required.");if(w(t.owner),w(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 o("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 o("INVALID_INPUT","endpoint must be an absolute HTTP(S) URL.")}if(!["https:","http:"].includes(e.protocol)||e.search||e.hash||e.username||e.password)throw new o("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 o("INVALID_INPUT","timeout must be between 1 and 2,147,483,647 milliseconds.");if(t.apiVersion!==void 0&&(typeof t.apiVersion!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(t.apiVersion)))throw new o("INVALID_INPUT","apiVersion must have YYYY-MM-DD format.");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new o("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 o("INVALID_INPUT","Custom headers are not valid HTTP header values.")}for(const a of["authorization","accept","content-type","x-github-api-version"])if(this.headers.has(a))throw new o("INVALID_INPUT",`Custom headers cannot override ${a}.`);try{this.headers.set("Authorization",`Bearer ${t.token}`)}catch{throw new o("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}async request(t,e,a,r,i){O(i);let n=!1;const h=new Headers(this.headers);h.set("Accept",r?"application/vnd.github.raw+json":"application/vnd.github+json"),a!==void 0&&h.set("Content-Type","application/json");const d=i?[i]:[],u=this.timeout===void 0?void 0:AbortSignal.timeout(this.timeout);u&&d.push(u);const c=d.length?AbortSignal.any(d):void 0,p=()=>new o(i?.aborted?"ABORTED":"TIMEOUT",i?.aborted?"Request was cancelled.":"Request timed out.",{dispatched:n});if(c?.aborted)throw p();let l;try{n=!0,l=await this.fetcher(`${this.endpoint}${this.prefix}${t}`,{method:e,headers:h,body:a===void 0?void 0:JSON.stringify(a),redirect:"manual",signal:c})}catch{throw c?.aborted?p():new o("NETWORK_ERROR","GitHub request failed.",{dispatched:n})}if(!(l instanceof Response))throw new o("INVALID_RESPONSE","fetch must return a Response.",{dispatched:n});const f={dispatched:n,status:l.status,requestId:l.headers.get("x-github-request-id")??void 0,retryAfter:l.headers.get("retry-after")??void 0};if(!l.ok)throw new o("HTTP_ERROR",`GitHub request returned HTTP ${l.status}.`,{...f,...l.status>=300&&l.status<400?{reason:"REDIRECT"}:{}});try{if(!r)return await l.json();const A=await l.arrayBuffer();try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(A)}catch{throw new o("INVALID_UTF8","File content is not valid UTF-8.",f)}}catch(A){throw c?.aborted?p():A instanceof o?A:new o("INVALID_RESPONSE","Could not read the GitHub response.",f)}}async json(t,e="GET",a,r){return y(await this.request(t,e,a,!1,r))}scope(t){return JSON.stringify([this.endpoint,this.prefix,t])}}function Q(s){if(typeof s!="string")throw new o("INVALID_INPUT","Path must be a string.");return s.split("/").forEach(w),s}class Z{constructor(t){this.transport=t}transport;tree(t,e,a){let r=t.trees.get(e);return r||(r=this.transport.json(`/git/trees/${e}`,"GET",void 0,a).then(i=>{if(i.truncated!==!1||!Array.isArray(i.tree))throw new o("INVALID_RESPONSE","GitHub returned an incomplete tree.");return i.tree.map(n=>{const h=y(n);return{path:D(h.path),sha:m(h.sha),type:D(h.type),mode:D(h.mode)}})}),t.trees.set(e,r)),r}async resolve(t,e,a){const r=Q(e).split("/");let i=t.treeSha;for(let n=0;n<r.length;n++){const h=(await this.tree(t,i,a)).find(d=>d.path===r[n]);if(!h)return;if(n===r.length-1)return h;if(h.type!=="tree")throw new o("INVALID_METADATA","A parent path is not a directory.",{path:r.slice(0,n+1).join("/"),reason:"PATH_NOT_DIRECTORY"});i=h.sha}}async find(t,e,a){const r=await this.resolve(t,e,a);if(r&&(r.type!=="blob"||!["100644","100755"].includes(r.mode)))throw new o("INVALID_METADATA","Path must reference a regular file.",{path:e,reason:"NOT_REGULAR_FILE"});return r}async directory(t,e,a){const r=await this.resolve(t,e,a);if(r){if(r.type!=="tree")throw new o("INVALID_METADATA","Path must reference a directory.",{path:e,reason:"PATH_NOT_DIRECTORY"});return this.tree(t,r.sha,a)}}}class tt{transport;files;branchName;branchLookup;queue=Promise.resolve();constructor(t){this.transport=new X(t),this.files=new Z(this.transport),this.branchName=t.branch}async branch(t){if(t?.aborted)throw new o("ABORTED","Request was cancelled.",{dispatched:!1});if(this.branchName!==void 0)return this.branchName;if(this.branchLookup??=this.transport.json("").then(a=>(this.branchName=D(a.default_branch),this.branchName)).finally(()=>{this.branchLookup=void 0}),!t)return this.branchLookup;const e=this.branchLookup;if(t.aborted)throw e.catch(()=>{}),new o("ABORTED","Request was cancelled.",{dispatched:!0});return new Promise((a,r)=>{const i=()=>r(new o("ABORTED","Request was cancelled.",{dispatched:!0}));t.addEventListener("abort",i,{once:!0}),e.then(a,r).finally(()=>t.removeEventListener("abort",i))})}async snapshot(t){O(t);const e=await this.branch(t),a=await this.transport.json(`/git/ref/heads/${encodeURIComponent(e)}`,"GET",void 0,t),r=m(y(a.object).sha),i=await this.transport.json(`/git/commits/${r}`,"GET",void 0,t);return{commitSha:r,treeSha:m(y(i.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 a=await this.transport.json("/git/blobs","POST",{content:_.from(t,"utf8").toString("base64"),encoding:"base64"},e);return m(a.sha)}async commit(t,e,a,r){const i=await Promise.all(e.map(async c=>({path:c.path,mode:c.mode??"100644",type:"blob",sha:"sha"in c?c.sha:await this.createBlob(c.content,r)}))),n=await this.transport.json("/git/trees","POST",{base_tree:t.treeSha,tree:i},r),h=await this.transport.json("/git/commits","POST",{tree:m(n.sha),parents:[t.commitSha],message:a},r),d=m(h.sha),u=await this.branch();if(r?.aborted)throw new o("ABORTED","Write was cancelled before publication.",{dispatched:!0,reason:"BEFORE_PUBLICATION",commitSha:d});try{const c=await this.transport.json(`/git/refs/heads/${encodeURIComponent(u)}`,"PATCH",{sha:d,force:!1},r);if(m(y(c.object).sha)!==d)throw new o("INVALID_RESPONSE","Unexpected published commit.")}catch(c){if(c instanceof o){if(c.details.dispatched===!1)throw c;if(c.code==="HTTP_ERROR"&&c.details.status!==void 0&&c.details.status<500)throw c.details.status===409||c.details.status===422?new o("CONFLICT","GitHub rejected publication; inspect the cause before retrying.",{...c.details,reason:"PUBLISH_REJECTED"}):c}throw new o("WRITE_RESULT_UNKNOWN","Publication may have succeeded; verify before retrying.",{dispatched:!0,...c instanceof o?c.details:{},commitSha:d})}return{commitSha:d}}}class et{repository;constructor(t){this.repository=new tt(t)}getDB(t){return new M(this.repository,t)}}export{et as GitHubDBClient,o as GitHubDBError,M as GitHubDatabase,x as GitHubRecordTable,$ as GitHubTable};
|
|
6
|
+
`:""}class q{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,this.storage=new B(t,e,r)}repository;dbName;name;storage;async findAll(t={},e={}){const r=A(e),a=O(t),s=await this.repository.snapshot(r),o=await this.storage.state(s,r);return G(await this.storage.validatedContent(o,r),this.storage.context(this.storage.dataPath)).filter(({record:c})=>Object.entries(a).every(([d,u])=>Object.hasOwn(c,d)&&K(c[d],u))).map(({record:c})=>c)}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 r=O(t);if(Object.hasOwn(r,"createdAt")||Object.hasOwn(r,"updatedAt"))throw new i("INVALID_INPUT","Record timestamps are managed by the SDK.");const a=Object.hasOwn(r,"id")?r.id:z();return D(a),this.mutate("insert",s=>{if(s.some(({record:d})=>d.id===a))throw new i("DUPLICATE_ID","id already exists in this table.",{...this.storage.context(this.storage.dataPath),reason:"DUPLICATE_ID",field:"id"});const o=Date.now(),c={...r,id:a,createdAt:o,updatedAt:o};return s.push({record:c,source:JSON.stringify(c)}),{result:c,write:!0}},e)}async updateById(t,e,r={}){D(t);const a=O(e);if(!Object.keys(a).length||["id","createdAt","updatedAt"].some(s=>Object.hasOwn(a,s)))throw new i("INVALID_INPUT","Update requires business fields and cannot change system fields.");return this.mutate("update",s=>{const o=s.find(({record:d})=>d.id===t);if(!o)throw new i("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND"});const c={...o.record,...a,updatedAt:Date.now()};return o.record=c,o.source=JSON.stringify(c),{result:c,write:!0}},r)}async deleteById(t,e={}){return D(t),this.mutate("delete",r=>{const a=r.findIndex(({record:s})=>s.id===t);return a<0?{result:!1,write:!1}:(r.splice(a,1),{result:!0,write:!0})},e)}async mutate(t,e,r){const a=A(r);return this.repository.enqueue(async()=>{const s=await this.repository.snapshot(a),o=await this.storage.state(s,a),c=G(await this.storage.validatedContent(o,a),this.storage.context(this.storage.dataPath)),d=e(c);if(d.write){const u=lt(c);await this.storage.write(s,o,u,L(u),t,a)}return d.result})}}class k{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,this.storage=new B(t,e,r)}repository;dbName;name;storage;version(t,e){return C("sha256").update(JSON.stringify([this.repository.scope(),this.dbName,this.name,t.revision,e])).digest("hex")}async read(t={}){const e=A(t),r=await this.repository.snapshot(e),a=await this.storage.state(r,e);if(!a.metadata||!a.data)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(a,e),meta:a.metadata.meta,version:this.version(a.metadata.meta,a.data.sha),commitSha:r.commitSha}}async write(t,e={}){const r=A(e),a=e.expectedVersion;if(a!=null&&(typeof a!="string"||!/^[a-f0-9]{64}$/.test(a)))throw new i("INVALID_INPUT","expectedVersion must be an opaque table version or null.");const s=L(t);return this.repository.enqueue(async()=>{const o=await this.repository.snapshot(r),c=await this.storage.state(o,r),d=c.metadata&&c.data?this.version(c.metadata.meta,c.data.sha):null;if(a!==void 0&&a!==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(c,r);const u=await this.storage.write(o,c,t,s,"write",r);return{...u,version:this.version(u.meta,u.meta.dataSha)}})}async getMeta(t={}){const e=A(t),r=await this.repository.snapshot(e),a=await this.storage.metadata(r,e);if(!a)throw new i("NOT_FOUND","Table does not exist.",{...this.storage.context(),reason:"TABLE_NOT_FOUND"});return{meta:a.meta,commitSha:r.commitSha}}}class W{constructor(t,e){this.repository=t,this.name=e,N(e)}repository;name;async listTables(t={}){const e=A(t),r=await this.repository.snapshot(e),a=await this.repository.files.directory(r,this.name,e);return(await Promise.all((a??[]).filter(s=>s.type==="tree"&&H(s.path)).map(async s=>{const o=await this.repository.files.directory(r,`${this.name}/${s.path}`,e),c=new Set(o?.filter(d=>d.type==="blob"&&["100644","100755"].includes(d.mode)).map(d=>d.path));return c.has("meta.json")&&c.has("data.jsonl")?s.path:void 0}))).filter(s=>s!==void 0).sort()}getTable(t){return new k(this.repository,this.name,t)}getRecordTable(t){return new q(this.repository,this.name,t)}}class pt{repository;constructor(t){this.repository=new it(t)}getDB(t){return new W(this.repository,t)}}export{pt as GitHubDBClient,i as GitHubDBError,W as GitHubDatabase,q as GitHubRecordTable,k as GitHubTable};
|