@secret-momo/github-db 0.3.0 → 1.0.1

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 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
- 写入已创建 Git 对象、但在发布前取消时,返回 ABORTED,dispatched 为 true,reason 为 BEFORE_PUBLICATION,并提供已创建的 commitSha;此时没有发送发布 PATCH,表内容未更新。
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:表完整性或文件格式错误。
@@ -71,7 +71,7 @@ JSONL 读取和校验在内存持有完整字符串,CRUD 下载全表后查询
71
71
 
72
72
  输入校验返回的 recordCount/byteLength 直接传入 TableStorage.write,避免对同一新内容重复扫描。高层对修改后的 JSONL 计算一次统计后使用同一持久化入口。
73
73
 
74
- 底层 write 和高层 CRUD 在内部传递固定操作类型,TableStorage.write 统一生成 `github-db: <operation> "<db>/<table>"` 提交信息,使用 JSON.stringify 转义表路径。GitRepository 只接收生成后的消息,不推断业务操作。
74
+ 底层 write 和高层 CRUD 在内部传递固定操作类型,TableStorage.write 统一生成提交信息:subject 为 `github-db: <operation> "<db>/<table>"`,使用 JSON.stringify 转义表路径;body 包含包名与 GitRepository 配置的 endpoint 原文。GitRepository 只接收生成后的消息,不推断业务操作。
75
75
 
76
76
  TableStorage.write 使用已有快照及已检查状态创建 data blob,得到 SHA;递增表 revision,设置统计和毫秒时间,创建 meta blob。GitRepository 创建基于原 tree 的增量 tree、以固定 commit 为 parent 的新 commit,最后非强制 PATCH ref。一张表的两个文件同时发布,无关文件保持原样。
77
77
 
@@ -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;投递前取消保持 ABORTED。
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
- 创建 commit 后再取消不会发布 PATCH,但已有对象创建请求,因此 ABORTED 带 dispatched=true、reason=BEFORE_PUBLICATION 及 commitSha。
104
+ 创建 Git 对象或 tree 后,取消/超时可能留下未发布对象;SDK 不继续发布、不自动重试。发布 PATCH 已投递后的取消、超时或异常继续归 WRITE_RESULT_UNKNOWN,并携带尝试 commitSha。
105
105
 
106
106
  ## 7. 构建与验证
107
107
 
@@ -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。仓库与目标分支必须人工保证已有至少一次提交,SDK 不初始化空仓库或创建分支。
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
 
@@ -70,9 +70,9 @@ TS 负责业务类型的编译期校验。运行时验证普通 JSON 对象、
70
70
 
71
71
  force=false 发布拒绝竞争提交,不强制覆盖、不自动重试。外部 force reset/ABA 不在严格 CAS 保证内,不增加针对外部强制历史操作的锁或协调服务;正常非强制并发下仍必须防止丢记录、漏检重复及覆盖其他表。提交前失败不产生可见半更新;发布后网络、取消、超时、5xx 或异常响应可能已经成功,报 WRITE_RESULT_UNKNOWN,携带尝试 commitSha。
72
72
 
73
- 所有操作支持 AbortSignal。提交信息由 SDK 自动生成,不接受调用方指定,固定为 `github-db: <operation> "<db>/<table>"`,表路径使用 JSON 字符串转义。operation 对应公开 API,为 write、insert、update 或 delete;首次建表沿用调用操作,删除最后一条记录仍为 delete。消息不包含记录内容、ID、时间戳或 SHA。调用入口复制选项与 CRUD 输入,排队期间调用方修改不影响本次操作。错误包含 code 与结构化诊断,不回显上游秘密正文;dispatched 仅表示调用 fetch。
73
+ 所有操作支持 AbortSignal。提交信息由 SDK 自动生成,不接受调用方指定;subject 固定为 `github-db: <operation> "<db>/<table>"`,表路径使用 JSON 字符串转义。body 包含 `client: @secret-momo/github-db` 与 `endpoint: <configured endpoint>`,原样保留调用方指定的 endpoint;未配置 endpoint 时使用 `https://api.github.com`。operation 对应公开 API,为 write、insert、update 或 delete;首次建表沿用调用操作,删除最后一条记录仍为 delete。消息不包含记录内容、ID、时间戳或 SHA。调用入口复制选项与 CRUD 输入,排队期间调用方修改不影响本次操作。错误包含 code 与结构化诊断,不回显上游秘密正文;dispatched 仅表示调用 fetch。
74
74
 
75
- 创建 Git 对象后、发布前的取消返回 ABORTED,details 为 dispatched=true、reason=BEFORE_PUBLICATION 和 commitSha;没有发送 PATCH。与发布后结果不确定的 WRITE_RESULT_UNKNOWN 区分。
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.d.ts CHANGED
@@ -92,6 +92,7 @@ declare class GitTreeReader {
92
92
  /** Internal Git adapter for table snapshots and atomic metadata/data publication. */
93
93
  declare class GitRepository {
94
94
  private readonly transport;
95
+ readonly endpoint: string;
95
96
  readonly files: GitTreeReader;
96
97
  private branchName;
97
98
  private branchLookup;
package/lib/index.js CHANGED
@@ -1,6 +1,9 @@
1
- import{randomUUID as H,createHash as J}from"node:crypto";import{isDeepStrictEqual as B}from"node:util";import{Buffer as _}from"node:buffer";class o extends Error{constructor(t,e,a={}){super(e),this.code=t,this.details=a}code;details;name="GitHubDBError"}function b(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}function L(s){if(!b(s))throw new o("INVALID_INPUT","Options must be an object.")}function O(s){if(s!==void 0&&!(s instanceof AbortSignal))throw new o("INVALID_INPUT","signal must be an AbortSignal.")}function F(s){if(typeof s!="string"||!s.isWellFormed())throw new o("INVALID_INPUT","Content must be a well-formed Unicode string.")}function R(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 w(s){if(!R(s))throw new o("INVALID_INPUT","Names must be nonempty, unambiguous path segments.");return s}function I(s){L(s);const t=s.signal;return O(t),t}const G=1e7;function S(s,t=!0){F(s);const e=_.byteLength(s,"utf8");if(t&&e>G)throw new o("TABLE_TOO_LARGE","Table exceeds 10,000,000 UTF-8 bytes.");if(s==="")return{recordCount:0,byteLength:0};const a=s.split(`
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 U{constructor(t,e,a){this.repository=t,this.dbName=e,this.name=a,w(e),w(a),this.root=`${e}/${a}`,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 a=await this.repository.files.find(t,this.metaPath,e);if(!a){if((await this.repository.files.directory(t,this.root,e))?.length)throw new o("INVALID_METADATA","Existing table is missing meta.json.",{...this.context(),reason:"MISSING_METADATA"});return}return{meta:W(await this.repository.content(a,e),this.context()),entry:a}}async state(t,e){const[a,r]=await Promise.all([this.metadata(t,e),this.repository.files.find(t,this.dataPath,e)]);if(a&&!r)throw new o("INVALID_METADATA","Table is missing data.jsonl.",{...this.context(),path:this.dataPath,reason:"MISSING_DATA"});return{metadata:a,data:r}}async validatedContent(t,e){if(!t.metadata||!t.data)return"";const{meta:a}=t.metadata;if(a.dataSha!==t.data.sha)throw new o("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),i=S(r,!1);if(i.recordCount!==a.recordCount||i.byteLength!==a.byteLength)throw new o("INVALID_METADATA","Statistics do not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"STATISTICS_MISMATCH"});return r}async write(t,e,a,r,i,n){const h=Date.now(),d=(e.metadata?.meta.revision??0)+1;if(!Number.isSafeInteger(d))throw new o("INVALID_METADATA","Table revision cannot be incremented safely.",{...this.context(),reason:"REVISION_OVERFLOW",field:"revision"});const u=await this.repository.createBlob(a,n),c={...e.metadata?.meta,version:1,createdAt:e.metadata?.meta.createdAt??h,updatedAt:h,...r,revision:d,dataSha:u},p=await this.repository.commit(t,[{path:this.dataPath,sha:u,mode:e.data?.mode},{path:this.metaPath,content:Y(c),mode:e.metadata?.entry.mode}],`github-db: ${i} ${JSON.stringify(this.root)}`,n);return{meta:c,commitSha:p.commitSha}}}function T(s,t="INVALID_INPUT",e={}){const a=()=>{throw new o(t,"Expected a plain JSON object with only serializable values.",{...e,reason:"NOT_JSON"})},r=new Set,i=(n,h,d)=>{if(n===null||typeof n=="boolean")return;if(typeof n=="string"){n.isWellFormed()||a();return}if(typeof n=="number"){Number.isFinite(n)||a();return}if(typeof n!="object"||n===null)return a();v(h,t,{...e,field:d});const u=Array.isArray(n),c=Object.getPrototypeOf(n);((u?c!==Array.prototype:c!==Object.prototype&&c!==null)||r.has(n))&&a(),r.add(n);const p=Reflect.ownKeys(n);u&&p.length!==n.length+1&&a();for(const l of p){if(u&&l==="length")continue;if(typeof l!="string"||!l.isWellFormed())return a();u&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=n.length)&&a();const f=Object.getOwnPropertyDescriptor(n,l);(!f.enumerable||!("value"in f))&&a(),i(f.value,h+1,`${d}.${l}`)}r.delete(n)};try{return b(s)?(i(s,1,"$"),JSON.parse(JSON.stringify(s))):a()}catch(n){if(n instanceof o)throw n;return a()}}function N(s,t="INVALID_INPUT",e={}){if(typeof s!="string"||!s.trim()||!s.isWellFormed())throw new o(t,"id must be a nonempty, well-formed string.",{...e,reason:"INVALID_ID",field:"id"})}function C(s){const{sign:t,digits:e,exponent:a}=V(s);return e?`${t}${e}e${a}`:"0"}const z=JSON.parse;function j(s,t){if(!s)return[];const e=s.split(`
4
- `);e.at(-1)===""&&e.pop();const a=new Set;return e.map((r,i)=>{const n={...t,lineNumber:i+1};P(r,"INVALID_RECORD",n);let h;try{h=z(r,(u,c,p)=>{if(typeof c=="number"&&(!Number.isFinite(c)||C(p.source)!==C(JSON.stringify(c))))throw new o("INVALID_RECORD","Record number cannot round-trip without losing precision.",{...t,lineNumber:i+1,reason:"NUMERIC_PRECISION"});return c})}catch(u){throw u instanceof o?u:new o("INVALID_RECORD","Record line could not be parsed.",{...n,reason:"UNPARSABLE"})}const d=T(h,"INVALID_RECORD",n);N(d.id,"INVALID_RECORD",n);for(const u of["createdAt","updatedAt"]){const c=h[u];if(typeof c!="number"||!Number.isSafeInteger(c)||c<0||Object.is(c,-0))throw new o("INVALID_RECORD","Record timestamps must be nonnegative safe integers.",{...n,reason:"INVALID_TIMESTAMP",field:u})}if(a.has(d.id))throw new o("DUPLICATE_ID","Duplicate id in table data.",{...n,reason:"DUPLICATE_ID",field:"id"});return a.add(d.id),{record:d,source:r}})}function K(s){return s.length?s.map(t=>t.source).join(`
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(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function x(a){if(!g(a))throw new i("INVALID_INPUT","Options must be an object.")}function _(a){if(a!==void 0&&!(a instanceof AbortSignal))throw new i("INVALID_INPUT","signal must be an AbortSignal.")}function X(a){if(typeof a!="string"||!a.isWellFormed())throw new i("INVALID_INPUT","Content must be a well-formed Unicode string.")}function H(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 N(a){if(!H(a))throw new i("INVALID_INPUT","Names must be nonempty, unambiguous path segments.");return a}function A(a){x(a);const t=a.signal;return _(t),t}const Q=1e7;function Z(a){let t=!1,e=!1;for(let r=0;r<a.length;r++){const n=a[r];if(!t){n==='"'&&(t=!0);continue}if(n==="\\"){if(a[++r]==="u"&&/^[0-9a-fA-F]{4}$/.test(a.slice(r+1,r+5))){const s=Number.parseInt(a.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(n==='"'){if(e)return!0;t=!1}else if(e)return!0}return e}function L(a,t=!0){X(a);const e=E.byteLength(a,"utf8");if(t&&e>Q)throw new i("TABLE_TOO_LARGE","Table exceeds 10,000,000 UTF-8 bytes.");if(a==="")return{recordCount:0,byteLength:0};const r=a.split(`
2
+ `);r.at(-1)===""&&r.pop();for(const[n,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:n+1})}if(Z(s))throw new i("INVALID_JSONL","JSONL contains invalid Unicode.",{lineNumber:n+1,reason:"INVALID_UNICODE"});if(!g(o))throw new i("INVALID_JSONL","Every record must be a JSON object.",{lineNumber:n+1})}return{recordCount:r.length,byteLength:e}}function T(a){if(!g(a))throw new i("INVALID_RESPONSE","Expected a GitHub response object.");return a}function w(a){if(typeof a!="string"||!/^[a-f0-9]{40}$/.test(a))throw new i("INVALID_RESPONSE","Expected a 40-character lowercase Git SHA.");return a}function v(a){if(typeof a!="string"||!a||!a.isWellFormed())throw new i("INVALID_RESPONSE","Expected a nonempty well-formed GitHub response field.");return a}function tt(a){if(typeof a!="string"||!a.trim()||!a.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(a))throw new i("INVALID_RESPONSE","Expected a valid well-formed GitHub branch name.");return a}function et(a,t){try{if(a===null||typeof a!="object")return;const e=a,r=e.status,n=e.ok,s=e.headers,o=e.json,c=e.arrayBuffer;if(typeof r!="number"||!Number.isInteger(r)||r<100||r>599||typeof n!="boolean"||n!==(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:n,json:o.bind(a),arrayBuffer:c.bind(a),details:{dispatched:t,status:r,requestId:u??void 0,retryAfter:h??void 0}}}catch{return}}function P(a,t,e){const r=Promise.resolve(a);return t?new Promise((n,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(),n(u))},u=>{o||(o=!0,c(),s(u))}),t.aborted&&d()}):r}function rt(a){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(a);if(!t)return!1;const e=Number(t[1]),r=Number(t[2]),n=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 n>=1&&n<=s[r-1]}class nt{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,n,s){_(s);let o=!1;const c=new Headers(this.headers);c.set("Accept",n?"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",l=h,m=()=>p&&s?.aborted===!0,f=()=>new i(s?.aborted?"ABORTED":"TIMEOUT",s?.aborted?"Request was cancelled.":"Request timed out.",{dispatched:o});if(h?.aborted)throw f();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,l,f)}catch{throw h?.aborted?f():new i("NETWORK_ERROR","GitHub request failed.",{dispatched:o})}if(h?.aborted&&!m())throw f();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(!n){const Y=await P(y.json(),l,f);if(h?.aborted&&!m())throw f();return Y}const I=await P(y.arrayBuffer(),l,f);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 f();return j}catch(I){throw h?.aborted?f():I instanceof i?I:new i("INVALID_RESPONSE","Could not read the GitHub response.",b)}}async json(t,e="GET",r,n){return T(await this.request(t,e,r,!1,n))}scope(t){return JSON.stringify([this.endpoint,this.prefix,t])}}function at(a){if(typeof a!="string")throw new i("INVALID_INPUT","Path must be a string.");return a.split("/").forEach(N),a}function ot(a){const t=v(a);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 n=t.trees.get(e);return n||(n=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,n)),n}async resolve(t,e,r){const n=at(e).split("/");let s=t.treeSha;for(let o=0;o<n.length;o++){const c=(await this.tree(t,s,r)).find(d=>d.path===n[o]);if(!c)return;if(o===n.length-1)return c;if(c.type!=="tree")throw new i("INVALID_METADATA","A parent path is not a directory.",{path:n.slice(0,o+1).join("/"),reason:"PATH_NOT_DIRECTORY"});s=c.sha}}async find(t,e,r){const n=await this.resolve(t,e,r);if(n&&(n.type!=="blob"||!["100644","100755"].includes(n.mode)))throw new i("INVALID_METADATA","Path must reference a regular file.",{path:e,reason:"NOT_REGULAR_FILE"});return n}async directory(t,e,r){const n=await this.resolve(t,e,r);if(n){if(n.type!=="tree")throw new i("INVALID_METADATA","Path must reference a directory.",{path:e,reason:"PATH_NOT_DIRECTORY"});return this.tree(t,n.sha,r)}}}function R(a){const t=E.from(a,"utf8");return C("sha1").update(`blob ${t.byteLength}\0`).update(t).digest("hex")}class it{transport;endpoint;files;branchName;branchLookup;queue=Promise.resolve();constructor(t){this.transport=new nt(t),this.endpoint=t.endpoint??"https://api.github.com",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,n)=>{const s=()=>n(new i("ABORTED","Request was cancelled.",{dispatched:!0}));t.addEventListener("abort",s,{once:!0}),e.then(r,n).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),n=w(T(r.object).sha),s=await this.transport.json(`/git/commits/${n}`,"GET",void 0,t);return{commitSha:n,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),n=w(r.sha);if(n!==R(t))throw new i("INVALID_RESPONSE","GitHub returned a blob SHA that does not match content.");return n}async commit(t,e,r,n){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,n)}))),o=await this.transport.json("/git/trees","POST",{base_tree:t.treeSha,tree:s},n),c=await this.transport.json("/git/commits","POST",{tree:w(o.sha),parents:[t.commitSha],message:r},n),d=w(c.sha),u=await this.branch();if(n?.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},n);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(a,t,e){if(a>ct)throw new i(t,"JSON nesting exceeds 512 object/array containers.",{...e,reason:"TOO_DEEP"})}function $(a,t,e){let r=0,n=!1;for(let s=0;s<a.length;s++){const o=a[s];n&&o==="\\"?s++:o==='"'?n=!n:n||(o==="{"||o==="["?M(++r,t,e):(o==="}"||o==="]")&&r--)}}function J(a){const t=/^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(a),e=t[3]??"",r=(t[2]+e).replace(/^0+/,""),n=r.replace(/0+$/,"");return{sign:r?t[1]:"",digits:n,exponent:r?BigInt(t[4]??0)-BigInt(e.length)+BigInt(r.length-n.length):0n}}const S=JSON;function ht(a){const{digits:t,exponent:e}=J(a);return!t||e>=0n}function V(a,t,e){const r=a[t],n=S.isRawJSON(r)?Number(r.rawJSON):r;if(typeof n!="number"||!Number.isSafeInteger(n)||n<0||Object.is(n,-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 a[t]=n,n}function dt(a,t){$(a,"INVALID_METADATA",t);let e;try{e=S.parse(a,(r,n,s)=>typeof n=="number"&&JSON.stringify(n)!==s.source?S.rawJSON(s.source):n)}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(a){return JSON.stringify(a,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 n=await this.repository.content(r,e);if(R(n)!==r.sha)throw new i("INVALID_METADATA","meta.json SHA does not match its content.",{...this.context(),reason:"META_SHA_MISMATCH"});return{meta:dt(n,this.context()),entry:r}}async state(t,e){const[r,n]=await Promise.all([this.metadata(t,e),this.repository.files.find(t,this.dataPath,e)]);if(r&&!n)throw new i("INVALID_METADATA","Table is missing data.jsonl.",{...this.context(),path:this.dataPath,reason:"MISSING_DATA"});return{metadata:r,data:n}}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 n=await this.repository.content(t.data,e);if(R(n)!==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(n,!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 n}async write(t,e,r,n,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,...n,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)}
4
+
5
+ client: @secret-momo/github-db
6
+ endpoint: ${this.repository.endpoint}`,o);return{meta:h,commitSha:p.commitSha}}}function O(a,t="INVALID_INPUT",e={}){const r=()=>{throw new i(t,"Expected a plain JSON object with only serializable values.",{...e,reason:"NOT_JSON"})},n=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)||n.has(o))&&r(),n.add(o);const p=Reflect.ownKeys(o);u&&p.length!==o.length+1&&r();for(const l of p){if(u&&l==="length")continue;if(typeof l!="string"||!l.isWellFormed())return r();u&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=o.length)&&r();const m=Object.getOwnPropertyDescriptor(o,l);(!m.enumerable||!("value"in m))&&r(),s(m.value,c+1,`${d}.${l}`)}n.delete(o)};try{return g(a)?(s(a,1,"$"),JSON.parse(JSON.stringify(a))):r()}catch(o){if(o instanceof i)throw o;return r()}}function D(a,t="INVALID_INPUT",e={}){if(typeof a!="string"||!a.trim()||!a.isWellFormed())throw new i(t,"id must be a nonempty, well-formed string.",{...e,reason:"INVALID_ID",field:"id"})}function F(a){const{sign:t,digits:e,exponent:r}=J(a);return e?`${t}${e}e${r}`:"0"}const lt=JSON.parse;function G(a,t){if(!a)return[];const e=a.split(`
7
+ `);e.at(-1)===""&&e.pop();const r=new Set;return e.map((n,s)=>{const o={...t,lineNumber:s+1};$(n,"INVALID_RECORD",o);let c;try{c=lt(n,(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:n}})}function ft(a){return a.length?a.map(t=>t.source).join(`
5
8
  `)+`
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};
9
+ `:""}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),n=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(n).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 n=Object.hasOwn(r,"id")?r.id:z();return D(n),this.mutate("insert",s=>{if(s.some(({record:d})=>d.id===n))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:n,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 n=O(e);if(!Object.keys(n).length||["id","createdAt","updatedAt"].some(s=>Object.hasOwn(n,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,...n,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 n=r.findIndex(({record:s})=>s.id===t);return n<0?{result:!1,write:!1}:(r.splice(n,1),{result:!0,write:!0})},e)}async mutate(t,e,r){const n=A(r);return this.repository.enqueue(async()=>{const s=await this.repository.snapshot(n),o=await this.storage.state(s,n),c=G(await this.storage.validatedContent(o,n),this.storage.context(this.storage.dataPath)),d=e(c);if(d.write){const u=ft(c);await this.storage.write(s,o,u,L(u),t,n)}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),n=await this.storage.state(r,e);if(!n.metadata||!n.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(n,e),meta:n.metadata.meta,version:this.version(n.metadata.meta,n.data.sha),commitSha:r.commitSha}}async write(t,e={}){const r=A(e),n=e.expectedVersion;if(n!=null&&(typeof n!="string"||!/^[a-f0-9]{64}$/.test(n)))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(n!==void 0&&n!==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),n=await this.storage.metadata(r,e);if(!n)throw new i("NOT_FOUND","Table does not exist.",{...this.storage.context(),reason:"TABLE_NOT_FOUND"});return{meta:n.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),n=await this.repository.files.directory(r,this.name,e);return(await Promise.all((n??[]).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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@secret-momo/github-db",
3
- "version": "0.3.0",
3
+ "version": "1.0.1",
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",