@secret-momo/github-db 1.0.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.
@@ -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
 
@@ -70,7 +70,7 @@ 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
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
 
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{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(`
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 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};
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": "1.0.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",