@kubun/mutation 0.8.0 → 0.8.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/lib/apply.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { type Validator } from '@enkaku/schema';
2
- import type { WritableDB } from '@kubun/db';
3
2
  import { HLC } from '@kubun/hlc';
4
- import type { ChangeDocumentMutation, DocumentData, DocumentMutation, DocumentNode, SetDocumentMutation } from '@kubun/protocol';
3
+ import type { DocumentModelID } from '@kubun/id';
4
+ import { DocumentID } from '@kubun/id';
5
+ import type { ChangeDocumentMutation, DocumentData, DocumentModel, DocumentMutation, DocumentNode, SetDocumentMutation } from '@kubun/protocol';
5
6
  export type DocumentValidator = Validator<DocumentData>;
6
7
  export type ValidatorsRecord = Record<string, Promise<DocumentValidator>>;
7
8
  export type AccessChecker = (doc: {
@@ -10,8 +11,30 @@ export type AccessChecker = (doc: {
10
11
  owner: string;
11
12
  data: DocumentData | null;
12
13
  }, permissionType: 'read' | 'write') => Promise<boolean>;
14
+ /**
15
+ * Minimal database interface required by mutation operations.
16
+ * This decouples @kubun/mutation from the full KubunDB/store API,
17
+ * allowing it to work with any implementation that provides these methods.
18
+ */
19
+ export type MutationDB = {
20
+ getDocument(id: DocumentID): Promise<DocumentNode | null>;
21
+ getDocumentModel(id: DocumentModelID | string): Promise<DocumentModel>;
22
+ createDocument(params: {
23
+ id: DocumentID;
24
+ owner: string;
25
+ data: DocumentData | null;
26
+ unique: Uint8Array;
27
+ }): Promise<DocumentNode>;
28
+ saveDocument(params: {
29
+ id: DocumentID;
30
+ existing: DocumentNode;
31
+ data: DocumentData | null;
32
+ }): Promise<DocumentNode>;
33
+ getFieldHLCs(documentID: string): Promise<Record<string, string> | null>;
34
+ updateFieldHLCs(docID: DocumentID, fieldHLCs: Record<string, string>): Promise<void>;
35
+ };
13
36
  export type MutationContext = {
14
- db: WritableDB;
37
+ store: MutationDB;
15
38
  validators: ValidatorsRecord;
16
39
  accessChecker?: AccessChecker;
17
40
  hlc?: HLC;
package/lib/apply.js CHANGED
@@ -1 +1 @@
1
- import{fromB64 as t}from"@enkaku/codec";import{applyPatches as e}from"@enkaku/patch";import{asType as a,createValidator as r}from"@enkaku/schema";import{HLC as i}from"@kubun/hlc";import{DocumentID as n}from"@kubun/id";export function getDocumentValidator(t,e){return null==t.validators[e]&&(t.validators[e]=t.db.getDocumentModel(e).then(t=>r({...t.schema,$id:e}))),t.validators[e]}function o(t,e,a){let r=i.parse(t),n=Date.now(),o=r.wallTime-n;if(o>e)throw Error(`HLC timestamp too far in the future: ${o}ms drift exceeds ${e}ms limit`);a&&a.receive(r)}export function getTopLevelField(t){let e=t.indexOf("/",1);return -1===e?t:t.slice(0,e)}export async function applyChangeMutation(t,r){let i=n.fromString(r.sub),l=i.toString(),u=await t.db.getDocument(i);if(null==u)throw Error(`Document not found: ${l}`);if(r.iss!==u.owner)throw Error("Invalid mutation issuer");if(t.accessChecker&&!await t.accessChecker(u,"write"))throw Error(`Access denied: cannot write document ${l}`);null!=t.maxDriftMS&&o(r.hlc,t.maxDriftMS,t.hlc);let c=i.model.toString(),s=await t.db.getFieldHLCs(l)??{};if(1===r.patch.length&&"replace"===r.patch[0].op&&"/"===r.patch[0].path&&null===r.patch[0].value){let e={...s,"/":r.hlc},a=Object.entries(e).every(([t,e])=>"/"===t||r.hlc>=e);return(await t.db.updateFieldHLCs(i,e),a)?await t.db.saveDocument({id:i,existing:u,data:null}):u}if(null!=s["/"]&&null===u.data)return u;let d=await getDocumentValidator(t,c),h=new Map;for(let t of r.patch){let e=getTopLevelField(t.path),a=h.get(e);null!=a?a.push(t):h.set(e,[t])}let m={...s},p=[];for(let[t,e]of h){let a=s[t];(null==a||r.hlc>a)&&(p.push(...e),m[t]=r.hlc)}if(0===p.length)return u;let f=structuredClone(u.data??{});e(f,p,!1),await t.db.updateFieldHLCs(i,m);let w=a(d,f);return await t.db.saveDocument({id:i,existing:u,data:w})}export async function applySetMutation(e,r){let i=r.aud??r.iss;if(r.iss!==i)throw Error("Invalid mutation issuer");let l=n.fromString(r.sub),u=l.toString(),c=l.model.toString();null!=e.maxDriftMS&&o(r.hlc,e.maxDriftMS,e.hlc);let[s,d]=await Promise.all([e.db.getDocument(l),getDocumentValidator(e,c)]),h=a(d,r.data),m={};for(let t of Object.keys(h))m[`/${t}`]=r.hlc;if(null===s){let a=await e.db.createDocument({id:l,owner:i,data:h,unique:t(r.unq)});return await e.db.updateFieldHLCs(l,m),a}if(s.owner!==i)throw Error(`Cannot change owner from ${s.owner} to ${i} in document: ${l.toString()}`);if(e.accessChecker&&!await e.accessChecker(s,"write"))throw Error(`Access denied: cannot write document ${l.toString()}`);let p=await e.db.getFieldHLCs(u)??{},f={...s.data??{}},w={...p},g=!1;for(let[t,e]of Object.entries(h)){let a=`/${t}`,i=p[a];(null==i||r.hlc>i)&&(f[t]=e,w[a]=r.hlc,g=!0)}if(!g)return s;await e.db.updateFieldHLCs(l,w);let b=a(d,f);return await e.db.saveDocument({id:l,existing:s,data:b})}export async function applyMutation(t,e){switch(e.typ){case"change":return await applyChangeMutation(t,e);case"set":return await applySetMutation(t,e);default:throw Error("Unsupported mutation type")}}
1
+ import{fromB64 as t}from"@enkaku/codec";import{applyPatches as e}from"@enkaku/patch";import{asType as r,createValidator as a}from"@enkaku/schema";import{HLC as o}from"@kubun/hlc";import{DocumentID as i}from"@kubun/id";export function getDocumentValidator(t,e){return null==t.validators[e]&&(t.validators[e]=t.store.getDocumentModel(e).then(t=>a({...t.schema,$id:e}))),t.validators[e]}function n(t,e,r){let a=o.parse(t),i=Date.now(),n=a.wallTime-i;if(n>e)throw Error(`HLC timestamp too far in the future: ${n}ms drift exceeds ${e}ms limit`);r&&r.receive(a)}export function getTopLevelField(t){let e=t.indexOf("/",1);return -1===e?t:t.slice(0,e)}export async function applyChangeMutation(t,a){let o=i.fromString(a.sub),l=o.toString(),u=await t.store.getDocument(o);if(null==u)throw Error(`Document not found: ${l}`);if(a.iss!==u.owner)throw Error("Invalid mutation issuer");if(t.accessChecker&&!await t.accessChecker(u,"write"))throw Error(`Access denied: cannot write document ${l}`);null!=t.maxDriftMS&&n(a.hlc,t.maxDriftMS,t.hlc);let c=o.model.toString(),s=await t.store.getFieldHLCs(l)??{};if(1===a.patch.length&&"replace"===a.patch[0].op&&"/"===a.patch[0].path&&null===a.patch[0].value){let e={...s,"/":a.hlc},r=Object.entries(e).every(([t,e])=>"/"===t||a.hlc>=e);return(await t.store.updateFieldHLCs(o,e),r)?await t.store.saveDocument({id:o,existing:u,data:null}):u}if(null!=s["/"]&&null===u.data)return u;let d=await getDocumentValidator(t,c),h=new Map;for(let t of a.patch){let e=getTopLevelField(t.path),r=h.get(e);null!=r?r.push(t):h.set(e,[t])}let m={...s},p=[];for(let[t,e]of h){let r=s[t];(null==r||a.hlc>r)&&(p.push(...e),m[t]=a.hlc)}if(0===p.length)return u;let f=structuredClone(u.data??{});e(f,p,!1),await t.store.updateFieldHLCs(o,m);let w=r(d,f);return await t.store.saveDocument({id:o,existing:u,data:w})}export async function applySetMutation(e,a){let o=a.aud??a.iss;if(a.iss!==o)throw Error("Invalid mutation issuer");let l=i.fromString(a.sub),u=l.toString(),c=l.model.toString();null!=e.maxDriftMS&&n(a.hlc,e.maxDriftMS,e.hlc);let[s,d]=await Promise.all([e.store.getDocument(l),getDocumentValidator(e,c)]),h=r(d,a.data),m={};for(let t of Object.keys(h))m[`/${t}`]=a.hlc;if(null===s){let r=await e.store.createDocument({id:l,owner:o,data:h,unique:t(a.unq)});return await e.store.updateFieldHLCs(l,m),r}if(s.owner!==o)throw Error(`Cannot change owner from ${s.owner} to ${o} in document: ${l.toString()}`);if(e.accessChecker&&!await e.accessChecker(s,"write"))throw Error(`Access denied: cannot write document ${l.toString()}`);let p=await e.store.getFieldHLCs(u)??{},f={...s.data??{}},w={...p},g=!1;for(let[t,e]of Object.entries(h)){let r=`/${t}`,o=p[r];(null==o||a.hlc>o)&&(f[t]=e,w[r]=a.hlc,g=!0)}if(!g)return s;await e.store.updateFieldHLCs(l,w);let D=r(d,f);return await e.store.saveDocument({id:l,existing:s,data:D})}export async function applyMutation(t,e){switch(e.typ){case"change":return await applyChangeMutation(t,e);case"set":return await applySetMutation(t,e);default:throw Error("Unsupported mutation type")}}
package/lib/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { HLC, type HLCTimestamp } from '@kubun/hlc';
2
- export type { DocumentValidator, MutationContext, ValidatorsRecord } from './apply.js';
2
+ export type { DocumentValidator, MutationContext, MutationDB, ValidatorsRecord } from './apply.js';
3
3
  export { applyChangeMutation, applyMutation, applySetMutation, getTopLevelField } from './apply.js';
4
4
  export type { CreateChangeMutationParams, CreateRemoveMutationParams, CreateSetMutationParams, } from './create.js';
5
5
  export { createChangeMutation, createRemoveMutation, createSetMutation } from './create.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubun/mutation",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "license": "see LICENSE.md",
5
5
  "keywords": [],
6
6
  "type": "module",
@@ -23,8 +23,7 @@
23
23
  "@kubun/id": "^0.8.0"
24
24
  },
25
25
  "devDependencies": {
26
- "@kubun/graphql": "^0.8.0",
27
- "@kubun/db": "^0.8.0",
26
+ "@kubun/graphql": "^0.8.1",
28
27
  "@kubun/protocol": "^0.8.0"
29
28
  },
30
29
  "scripts": {