@kenaidb/sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/dist/index.cjs +5 -0
- package/dist/index.d.cts +123 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +5 -0
- package/package.json +57 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kenai DB
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,92 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kenaidb/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official TypeScript / Node.js SDK for **Kenai DB** — the AI-Native Document Database.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @kenaidb/sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Works with both **ESM** (`import`) and **CommonJS** (`require`) in Node 18+, Bun, Deno, and modern runtimes.
|
|
12
|
+
|
|
13
|
+
## Quick Start
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { KenaiClient, KenaiError, KenaiProvider, z } from "@kenaidb/sdk";
|
|
17
|
+
|
|
18
|
+
const db = await KenaiClient.connect(process.env.KENAI_URI!, {
|
|
19
|
+
apiKey: process.env.KENAI_API_KEY!,
|
|
20
|
+
// Optional: omit if using your cluster's Cloud-configured default BYOM provider
|
|
21
|
+
byom: {
|
|
22
|
+
provider: KenaiProvider.Google,
|
|
23
|
+
model: "gemini-3.8-flash",
|
|
24
|
+
apiKey: process.env.GEMINI_API_KEY!,
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const OrderSchema = z.object({
|
|
29
|
+
customer: z.string().describe("Full customer name"),
|
|
30
|
+
item: z.string().describe("Product name and variant"),
|
|
31
|
+
qty: z.number().describe("Units ordered"),
|
|
32
|
+
destination: z.string().describe("Delivery address"),
|
|
33
|
+
status: z.enum(["pending", "paid", "shipped", "cancelled"]),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const Orders = db.model("orders", OrderSchema);
|
|
37
|
+
|
|
38
|
+
// Subscribe to background hydration & DLQ events
|
|
39
|
+
const unsubscribe = Orders.on("hydrated", (doc) => {
|
|
40
|
+
console.log("Hydrated:", doc._id, doc.customer);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// 1. Insert raw unstructured text (<5ms async stub by default, or mode: "sync")
|
|
44
|
+
const { _id } = await Orders.insert(
|
|
45
|
+
"Sarah wants 3 blue hoodies delivered to Lekki Phase 1. Paid already.",
|
|
46
|
+
{ idempotencyKey: "msg_01J9XYZ" } // Optional: prevents duplicate rows & model calls on retries
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
// Attach a PDF, image, or audio file via options.file (never collides with schema fields)
|
|
50
|
+
await Orders.insert("Vendor invoice from accounting", {
|
|
51
|
+
mode: "sync",
|
|
52
|
+
file: {
|
|
53
|
+
url: "https://cdn.example.com/invoices/inv-2026-884.pdf",
|
|
54
|
+
mimeType: "application/pdf",
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Block until hydration completes when needed
|
|
59
|
+
const ready = await Orders.waitForHydration(_id);
|
|
60
|
+
|
|
61
|
+
// 2. Update with natural language, structured fields, or a revised file
|
|
62
|
+
await Orders.update({ _id }, "Change destination to Victoria Island and bump qty to 5");
|
|
63
|
+
|
|
64
|
+
// 3. Regular indexed query (0 LLM calls)
|
|
65
|
+
const paid = await Orders.find({ status: "paid", qty: { $gte: 3 } })
|
|
66
|
+
.sort({ qty: -1 })
|
|
67
|
+
.limit(20);
|
|
68
|
+
|
|
69
|
+
// 4. Optional natural-language or LLM-powered semantic query
|
|
70
|
+
const nl = await Orders.find("paid orders with 3+ items going to Victoria Island");
|
|
71
|
+
const semantic = await Orders.find("urgent or high-value orders", { mode: "llm" });
|
|
72
|
+
|
|
73
|
+
// 5. Outbound Webhooks & DLQ Replay
|
|
74
|
+
await Orders.registerWebhook({
|
|
75
|
+
url: "https://api.yourapp.com/webhooks/kenai",
|
|
76
|
+
events: ["hydrated", "dlq"],
|
|
77
|
+
secret: process.env.KENAI_WEBHOOK_SECRET,
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
const failedDocs = await Orders.getDlq();
|
|
81
|
+
if (failedDocs.length > 0) {
|
|
82
|
+
await Orders.replayDlq();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// 6. Delete & aggregate
|
|
86
|
+
await Orders.delete({ status: "cancelled" });
|
|
87
|
+
const totals = await Orders.aggregate([
|
|
88
|
+
{ $group: { _id: "$status", count: { $sum: 1 } } },
|
|
89
|
+
]);
|
|
90
|
+
|
|
91
|
+
unsubscribe();
|
|
92
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";var y=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var D=Object.prototype.hasOwnProperty;var O=(o,e)=>{for(var n in e)y(o,n,{get:e[n],enumerable:!0})},W=(o,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of $(e))!D.call(o,i)&&i!==n&&y(o,i,{get:()=>e[i],enumerable:!(t=U(e,i))||t.enumerable});return o};var j=o=>W(y({},"__esModule",{value:!0}),o);var I={};O(I,{KenaiClient:()=>b,KenaiError:()=>l,KenaiModel:()=>h,KenaiProvider:()=>m,z:()=>f.z});module.exports=j(I);var f=require("zod");var g=require("zod"),m;(function(o){o.Google="google",o.OpenAI="openai",o.Anthropic="anthropic",o.OpenRouter="openrouter"})(m||(m={}));function w(o,e){let n=g.z.toJSONSchema(o,{target:"draft-2020-12",unrepresentable:"any"});return e&&!n.title&&(n.title=e),n}var l=class extends Error{statusCode;details;constructor(e,n=500,t){super(e),this.name="KenaiError",this.statusCode=n,this.details=t}},p=class{constructor(e){this.executor=e}executor;n;t;o;i;sort(e){return this.n=e,this}limit(e){return this.t=e,this}skip(e){return this.o=e,this}select(e){return this.i=e,this}then(e,n){return this.executor({sort:this.n,limit:this.t,skip:this.o,select:this.i}).then(e,n)}},h=class{constructor(e,n,t){this.client=e;this.collectionName=n;this.jsonSchema=w(t,n)}client;collectionName;jsonSchema;getJsonSchema(){return this.jsonSchema}async syncSchema(){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/schema`,"PUT",{jsonSchema:this.jsonSchema})}async insert(e,n={}){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/insert`,"POST",{input:e,file:n.file,mode:n.mode??"async",idempotencyKey:n.idempotencyKey,webhookUrl:n.webhookUrl,webhookSecret:n.webhookSecret,jsonSchema:this.jsonSchema,byom:this.client.byom})}async insertMany(e,n={}){return(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/insertMany`,"POST",{inputs:e,files:n.files,idempotencyKeys:n.idempotencyKeys,mode:n.mode??"async",webhookUrl:n.webhookUrl,webhookSecret:n.webhookSecret,jsonSchema:this.jsonSchema,byom:this.client.byom})).documents}async update(e,n,t={}){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/update`,"POST",{filter:e,patch:n,file:t.file,mode:t.mode??"async",idempotencyKey:t.idempotencyKey,webhookUrl:t.webhookUrl,webhookSecret:t.webhookSecret,jsonSchema:this.jsonSchema,byom:this.client.byom})}async updateMany(e,n,t={}){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/updateMany`,"POST",{filter:e,patch:n,file:t.file,mode:t.mode??"async",idempotencyKey:t.idempotencyKey,webhookUrl:t.webhookUrl,webhookSecret:t.webhookSecret,jsonSchema:this.jsonSchema,byom:this.client.byom})}find(e={},n={}){let t=typeof e=="string";return new p(async i=>(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/find`,"POST",{filter:t?{}:e,naturalLanguage:t?e:void 0,mode:t?n.mode??"nl":"native",...i,jsonSchema:t?this.jsonSchema:void 0,byom:t?this.client.byom:void 0})).documents)}async findOne(e={},n={}){return typeof e=="string"?(await this.find(e,n).limit(1))[0]??null:(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/findOne`,"POST",{filter:e})).document}async delete(e){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/delete`,"POST",{filter:e,many:!1})}async deleteMany(e){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/delete`,"POST",{filter:e,many:!0})}async aggregate(e){return(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/aggregate`,"POST",{pipeline:e})).results}async waitForHydration(e,n=15e3){return this.client.e(`/v1/documents/${encodeURIComponent(e)}/wait?timeoutMs=${n}`,"GET")}on(e,n,t){let i=new AbortController,r=`${this.client.baseUrl}/v1/collections/${encodeURIComponent(this.collectionName)}/events`,c={Accept:"text/event-stream"};return this.client.apiKey&&(c.Authorization=`Bearer ${this.client.apiKey}`),(async()=>{try{let s=await fetch(r,{method:"GET",headers:c,signal:i.signal});if(!s.ok||!s.body)throw new l(`Failed to open event stream (${s.status})`,s.status);let R=s.body.getReader(),S=new TextDecoder,d="";for(;;){let{done:K,value:v}=await R.read();if(K)break;d+=S.decode(v,{stream:!0});let T=d.split(`
|
|
2
|
+
|
|
3
|
+
`);d=T.pop()??"";for(let C of T){let P=C.split(`
|
|
4
|
+
`),k="message",u=[];for(let a of P)a.startsWith("event:")?k=a.slice(6).trim():a.startsWith("data:")&&u.push(a.slice(5).trim());if(k===e&&u.length>0)try{let a=JSON.parse(u.join(`
|
|
5
|
+
`));n(a)}catch{}}}}catch(s){if(i.signal.aborted)return;t?.(s instanceof Error?s:new Error(String(s)))}})(),()=>i.abort()}async getDlq(){return(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/dlq`,"GET")).documents}async replayDlq(){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/dlq/replay`,"POST",{byom:this.client.byom,jsonSchema:this.jsonSchema})}async registerWebhook(e){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/webhooks`,"POST",e)}async listWebhooks(){return(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/webhooks`,"GET")).webhooks}async deleteWebhook(e){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/webhooks/${encodeURIComponent(e)}`,"DELETE")}},b=class o{baseUrl;byom;apiKey;constructor(e,n={}){this.baseUrl=o.normalizeUri(e),this.byom=n.byom,this.apiKey=n.apiKey}static normalizeUri(e){let n=e.trim();n.startsWith("kenai+srv://")?n=`https://${n.slice(12)}`:n.startsWith("kenai://")&&(n=`http://${n.slice(8)}`);try{let t=new URL(n);return`${t.protocol}//${t.host}`}catch{return n.replace(/\/+$/,"")}}static async connect(e,n={}){let t=new o(e,n);return await t.e("/v1/health","GET"),t}model(e,n){return new h(this,e,n)}async e(e,n,t){let i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);let r=await fetch(`${this.baseUrl}${e}`,{method:n,headers:i,body:t!==void 0?JSON.stringify(t):void 0}),c=await r.json().catch(()=>null);if(!r.ok)throw new l(c?.message||`Kenai DB request failed (${r.status} ${r.statusText})`,r.status,c);return c}};0&&(module.exports={KenaiClient,KenaiError,KenaiModel,KenaiProvider,z});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export { z } from 'zod';
|
|
3
|
+
import { WebhookEventType, ReadMode, WriteMode, KenaiFileInput, ByomConfig, JsonSchemaObject, SyncSchemaResult, KenaiDocument, CreateWebhookRequest, KenaiWebhook } from '@kenaidb/schema';
|
|
4
|
+
export { ByomConfig, ByomProvider, CreateWebhookRequest, DocumentStatus, JsonSchemaObject, KenaiDocument, KenaiDocumentMeta, KenaiFileInput, KenaiProvider, KenaiWebhook, KenaiWebhookPayload, ReadMode, SchemaDiff, SyncSchemaResult, WebhookEventType, WriteMode } from '@kenaidb/schema';
|
|
5
|
+
|
|
6
|
+
declare class KenaiError extends Error {
|
|
7
|
+
readonly statusCode: number;
|
|
8
|
+
readonly details?: unknown;
|
|
9
|
+
constructor(message: string, statusCode?: number, details?: unknown);
|
|
10
|
+
}
|
|
11
|
+
interface KenaiConnectOptions {
|
|
12
|
+
/** Optional Bring Your Own Model override (if not using Cloud-configured default BYOM) */
|
|
13
|
+
byom?: ByomConfig;
|
|
14
|
+
/** Scoped cluster API key (kdb_live_...) */
|
|
15
|
+
apiKey?: string;
|
|
16
|
+
}
|
|
17
|
+
interface WriteOptions {
|
|
18
|
+
mode?: WriteMode;
|
|
19
|
+
/** Attach a PDF, image, or audio file via URL or base64 (kept separate from document schema fields) */
|
|
20
|
+
file?: KenaiFileInput;
|
|
21
|
+
/** Optional idempotency key to prevent duplicate writes and model calls on webhook or network retries */
|
|
22
|
+
idempotencyKey?: string;
|
|
23
|
+
/** Optional per-write outbound webhook URL notified when this write hydrates or moves to DLQ */
|
|
24
|
+
webhookUrl?: string;
|
|
25
|
+
/** Optional HMAC-SHA256 signing secret for the per-write webhookUrl */
|
|
26
|
+
webhookSecret?: string;
|
|
27
|
+
}
|
|
28
|
+
interface InsertManyOptions {
|
|
29
|
+
mode?: WriteMode;
|
|
30
|
+
/** Optional per-item file attachments aligned by index with inputs[] */
|
|
31
|
+
files?: Array<KenaiFileInput | null | undefined>;
|
|
32
|
+
/** Optional per-item idempotency keys aligned by index with inputs[] */
|
|
33
|
+
idempotencyKeys?: Array<string | null | undefined>;
|
|
34
|
+
/** Optional per-write outbound webhook URL notified for each item */
|
|
35
|
+
webhookUrl?: string;
|
|
36
|
+
/** Optional HMAC-SHA256 signing secret for the per-write webhookUrl */
|
|
37
|
+
webhookSecret?: string;
|
|
38
|
+
}
|
|
39
|
+
interface FindOptions {
|
|
40
|
+
mode?: ReadMode;
|
|
41
|
+
}
|
|
42
|
+
type CollectionEventType = WebhookEventType;
|
|
43
|
+
type UnsubscribeFn = () => void;
|
|
44
|
+
declare class KenaiQueryBuilder<T extends Record<string, unknown>> implements PromiseLike<KenaiDocument<T>[]> {
|
|
45
|
+
private readonly executor;
|
|
46
|
+
private _sort?;
|
|
47
|
+
private _limit?;
|
|
48
|
+
private _skip?;
|
|
49
|
+
private _select?;
|
|
50
|
+
constructor(executor: (modifiers: {
|
|
51
|
+
sort?: Record<string, 1 | -1>;
|
|
52
|
+
limit?: number;
|
|
53
|
+
skip?: number;
|
|
54
|
+
select?: Record<string, 0 | 1>;
|
|
55
|
+
}) => Promise<KenaiDocument<T>[]>);
|
|
56
|
+
sort(spec: Record<string, 1 | -1>): this;
|
|
57
|
+
limit(n: number): this;
|
|
58
|
+
skip(n: number): this;
|
|
59
|
+
select(projection: Record<string, 0 | 1>): this;
|
|
60
|
+
then<TResult1 = KenaiDocument<T>[], TResult2 = never>(onfulfilled?: ((value: KenaiDocument<T>[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
61
|
+
}
|
|
62
|
+
declare class KenaiModel<T extends Record<string, unknown>> {
|
|
63
|
+
private readonly client;
|
|
64
|
+
readonly collectionName: string;
|
|
65
|
+
private readonly jsonSchema;
|
|
66
|
+
constructor(client: KenaiClient, collectionName: string, schema: z.ZodType<T>);
|
|
67
|
+
getJsonSchema(): JsonSchemaObject;
|
|
68
|
+
syncSchema(): Promise<SyncSchemaResult>;
|
|
69
|
+
insert(input: string | T | null, options?: WriteOptions): Promise<KenaiDocument<T>>;
|
|
70
|
+
insertMany(inputs: Array<string | T | null>, options?: InsertManyOptions): Promise<KenaiDocument<T>[]>;
|
|
71
|
+
update(filter: Record<string, unknown>, patch: string | Partial<T> | null, options?: WriteOptions): Promise<{
|
|
72
|
+
matchedCount: number;
|
|
73
|
+
documents: KenaiDocument<T>[];
|
|
74
|
+
}>;
|
|
75
|
+
updateMany(filter: Record<string, unknown>, patch: string | Partial<T> | null, options?: WriteOptions): Promise<{
|
|
76
|
+
matchedCount: number;
|
|
77
|
+
documents: KenaiDocument<T>[];
|
|
78
|
+
}>;
|
|
79
|
+
find(filterOrNaturalLanguage?: Record<string, unknown> | string, options?: FindOptions): KenaiQueryBuilder<T>;
|
|
80
|
+
findOne(filterOrNaturalLanguage?: Record<string, unknown> | string, options?: FindOptions): Promise<KenaiDocument<T> | null>;
|
|
81
|
+
delete(filter: Record<string, unknown>): Promise<{
|
|
82
|
+
deletedCount: number;
|
|
83
|
+
}>;
|
|
84
|
+
deleteMany(filter: Record<string, unknown>): Promise<{
|
|
85
|
+
deletedCount: number;
|
|
86
|
+
}>;
|
|
87
|
+
aggregate<R = Record<string, unknown>>(pipeline: Array<Record<string, unknown>>): Promise<R[]>;
|
|
88
|
+
waitForHydration(docId: string, timeoutMs?: number): Promise<KenaiDocument<T>>;
|
|
89
|
+
/**
|
|
90
|
+
* Subscribe to real-time "hydrated" or "dlq" events for this collection over SSE.
|
|
91
|
+
* Works in Node 18+, Bun, Deno, Edge, and browsers with full Authorization header support.
|
|
92
|
+
* Returns an unsubscribe function to close the stream cleanly.
|
|
93
|
+
*/
|
|
94
|
+
on(event: CollectionEventType, callback: (doc: KenaiDocument<T>) => void, onError?: (err: Error) => void): UnsubscribeFn;
|
|
95
|
+
getDlq(): Promise<KenaiDocument<T>[]>;
|
|
96
|
+
replayDlq(): Promise<{
|
|
97
|
+
replayedCount: number;
|
|
98
|
+
documents: KenaiDocument<T>[];
|
|
99
|
+
}>;
|
|
100
|
+
/**
|
|
101
|
+
* Register an outbound webhook URL for this collection.
|
|
102
|
+
* Kenai DB will send signed POST notifications whenever a document hydrates or enters DLQ.
|
|
103
|
+
*/
|
|
104
|
+
registerWebhook(config: CreateWebhookRequest): Promise<KenaiWebhook>;
|
|
105
|
+
/** List all registered outbound webhooks for this collection. */
|
|
106
|
+
listWebhooks(): Promise<KenaiWebhook[]>;
|
|
107
|
+
/** Remove a registered outbound webhook by its ID. */
|
|
108
|
+
deleteWebhook(webhookId: string): Promise<{
|
|
109
|
+
deleted: boolean;
|
|
110
|
+
}>;
|
|
111
|
+
}
|
|
112
|
+
declare class KenaiClient {
|
|
113
|
+
readonly baseUrl: string;
|
|
114
|
+
readonly byom?: ByomConfig;
|
|
115
|
+
readonly apiKey?: string;
|
|
116
|
+
private constructor();
|
|
117
|
+
static normalizeUri(uri: string): string;
|
|
118
|
+
static connect(uri: string, options?: KenaiConnectOptions): Promise<KenaiClient>;
|
|
119
|
+
model<T extends Record<string, unknown>>(collectionName: string, schema: z.ZodType<T>): KenaiModel<T>;
|
|
120
|
+
_request<R = unknown>(path: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', body?: unknown): Promise<R>;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export { type CollectionEventType, type FindOptions, type InsertManyOptions, KenaiClient, type KenaiConnectOptions, KenaiError, KenaiModel, type UnsubscribeFn, type WriteOptions };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export { z } from 'zod';
|
|
3
|
+
import { WebhookEventType, ReadMode, WriteMode, KenaiFileInput, ByomConfig, JsonSchemaObject, SyncSchemaResult, KenaiDocument, CreateWebhookRequest, KenaiWebhook } from '@kenaidb/schema';
|
|
4
|
+
export { ByomConfig, ByomProvider, CreateWebhookRequest, DocumentStatus, JsonSchemaObject, KenaiDocument, KenaiDocumentMeta, KenaiFileInput, KenaiProvider, KenaiWebhook, KenaiWebhookPayload, ReadMode, SchemaDiff, SyncSchemaResult, WebhookEventType, WriteMode } from '@kenaidb/schema';
|
|
5
|
+
|
|
6
|
+
declare class KenaiError extends Error {
|
|
7
|
+
readonly statusCode: number;
|
|
8
|
+
readonly details?: unknown;
|
|
9
|
+
constructor(message: string, statusCode?: number, details?: unknown);
|
|
10
|
+
}
|
|
11
|
+
interface KenaiConnectOptions {
|
|
12
|
+
/** Optional Bring Your Own Model override (if not using Cloud-configured default BYOM) */
|
|
13
|
+
byom?: ByomConfig;
|
|
14
|
+
/** Scoped cluster API key (kdb_live_...) */
|
|
15
|
+
apiKey?: string;
|
|
16
|
+
}
|
|
17
|
+
interface WriteOptions {
|
|
18
|
+
mode?: WriteMode;
|
|
19
|
+
/** Attach a PDF, image, or audio file via URL or base64 (kept separate from document schema fields) */
|
|
20
|
+
file?: KenaiFileInput;
|
|
21
|
+
/** Optional idempotency key to prevent duplicate writes and model calls on webhook or network retries */
|
|
22
|
+
idempotencyKey?: string;
|
|
23
|
+
/** Optional per-write outbound webhook URL notified when this write hydrates or moves to DLQ */
|
|
24
|
+
webhookUrl?: string;
|
|
25
|
+
/** Optional HMAC-SHA256 signing secret for the per-write webhookUrl */
|
|
26
|
+
webhookSecret?: string;
|
|
27
|
+
}
|
|
28
|
+
interface InsertManyOptions {
|
|
29
|
+
mode?: WriteMode;
|
|
30
|
+
/** Optional per-item file attachments aligned by index with inputs[] */
|
|
31
|
+
files?: Array<KenaiFileInput | null | undefined>;
|
|
32
|
+
/** Optional per-item idempotency keys aligned by index with inputs[] */
|
|
33
|
+
idempotencyKeys?: Array<string | null | undefined>;
|
|
34
|
+
/** Optional per-write outbound webhook URL notified for each item */
|
|
35
|
+
webhookUrl?: string;
|
|
36
|
+
/** Optional HMAC-SHA256 signing secret for the per-write webhookUrl */
|
|
37
|
+
webhookSecret?: string;
|
|
38
|
+
}
|
|
39
|
+
interface FindOptions {
|
|
40
|
+
mode?: ReadMode;
|
|
41
|
+
}
|
|
42
|
+
type CollectionEventType = WebhookEventType;
|
|
43
|
+
type UnsubscribeFn = () => void;
|
|
44
|
+
declare class KenaiQueryBuilder<T extends Record<string, unknown>> implements PromiseLike<KenaiDocument<T>[]> {
|
|
45
|
+
private readonly executor;
|
|
46
|
+
private _sort?;
|
|
47
|
+
private _limit?;
|
|
48
|
+
private _skip?;
|
|
49
|
+
private _select?;
|
|
50
|
+
constructor(executor: (modifiers: {
|
|
51
|
+
sort?: Record<string, 1 | -1>;
|
|
52
|
+
limit?: number;
|
|
53
|
+
skip?: number;
|
|
54
|
+
select?: Record<string, 0 | 1>;
|
|
55
|
+
}) => Promise<KenaiDocument<T>[]>);
|
|
56
|
+
sort(spec: Record<string, 1 | -1>): this;
|
|
57
|
+
limit(n: number): this;
|
|
58
|
+
skip(n: number): this;
|
|
59
|
+
select(projection: Record<string, 0 | 1>): this;
|
|
60
|
+
then<TResult1 = KenaiDocument<T>[], TResult2 = never>(onfulfilled?: ((value: KenaiDocument<T>[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
|
61
|
+
}
|
|
62
|
+
declare class KenaiModel<T extends Record<string, unknown>> {
|
|
63
|
+
private readonly client;
|
|
64
|
+
readonly collectionName: string;
|
|
65
|
+
private readonly jsonSchema;
|
|
66
|
+
constructor(client: KenaiClient, collectionName: string, schema: z.ZodType<T>);
|
|
67
|
+
getJsonSchema(): JsonSchemaObject;
|
|
68
|
+
syncSchema(): Promise<SyncSchemaResult>;
|
|
69
|
+
insert(input: string | T | null, options?: WriteOptions): Promise<KenaiDocument<T>>;
|
|
70
|
+
insertMany(inputs: Array<string | T | null>, options?: InsertManyOptions): Promise<KenaiDocument<T>[]>;
|
|
71
|
+
update(filter: Record<string, unknown>, patch: string | Partial<T> | null, options?: WriteOptions): Promise<{
|
|
72
|
+
matchedCount: number;
|
|
73
|
+
documents: KenaiDocument<T>[];
|
|
74
|
+
}>;
|
|
75
|
+
updateMany(filter: Record<string, unknown>, patch: string | Partial<T> | null, options?: WriteOptions): Promise<{
|
|
76
|
+
matchedCount: number;
|
|
77
|
+
documents: KenaiDocument<T>[];
|
|
78
|
+
}>;
|
|
79
|
+
find(filterOrNaturalLanguage?: Record<string, unknown> | string, options?: FindOptions): KenaiQueryBuilder<T>;
|
|
80
|
+
findOne(filterOrNaturalLanguage?: Record<string, unknown> | string, options?: FindOptions): Promise<KenaiDocument<T> | null>;
|
|
81
|
+
delete(filter: Record<string, unknown>): Promise<{
|
|
82
|
+
deletedCount: number;
|
|
83
|
+
}>;
|
|
84
|
+
deleteMany(filter: Record<string, unknown>): Promise<{
|
|
85
|
+
deletedCount: number;
|
|
86
|
+
}>;
|
|
87
|
+
aggregate<R = Record<string, unknown>>(pipeline: Array<Record<string, unknown>>): Promise<R[]>;
|
|
88
|
+
waitForHydration(docId: string, timeoutMs?: number): Promise<KenaiDocument<T>>;
|
|
89
|
+
/**
|
|
90
|
+
* Subscribe to real-time "hydrated" or "dlq" events for this collection over SSE.
|
|
91
|
+
* Works in Node 18+, Bun, Deno, Edge, and browsers with full Authorization header support.
|
|
92
|
+
* Returns an unsubscribe function to close the stream cleanly.
|
|
93
|
+
*/
|
|
94
|
+
on(event: CollectionEventType, callback: (doc: KenaiDocument<T>) => void, onError?: (err: Error) => void): UnsubscribeFn;
|
|
95
|
+
getDlq(): Promise<KenaiDocument<T>[]>;
|
|
96
|
+
replayDlq(): Promise<{
|
|
97
|
+
replayedCount: number;
|
|
98
|
+
documents: KenaiDocument<T>[];
|
|
99
|
+
}>;
|
|
100
|
+
/**
|
|
101
|
+
* Register an outbound webhook URL for this collection.
|
|
102
|
+
* Kenai DB will send signed POST notifications whenever a document hydrates or enters DLQ.
|
|
103
|
+
*/
|
|
104
|
+
registerWebhook(config: CreateWebhookRequest): Promise<KenaiWebhook>;
|
|
105
|
+
/** List all registered outbound webhooks for this collection. */
|
|
106
|
+
listWebhooks(): Promise<KenaiWebhook[]>;
|
|
107
|
+
/** Remove a registered outbound webhook by its ID. */
|
|
108
|
+
deleteWebhook(webhookId: string): Promise<{
|
|
109
|
+
deleted: boolean;
|
|
110
|
+
}>;
|
|
111
|
+
}
|
|
112
|
+
declare class KenaiClient {
|
|
113
|
+
readonly baseUrl: string;
|
|
114
|
+
readonly byom?: ByomConfig;
|
|
115
|
+
readonly apiKey?: string;
|
|
116
|
+
private constructor();
|
|
117
|
+
static normalizeUri(uri: string): string;
|
|
118
|
+
static connect(uri: string, options?: KenaiConnectOptions): Promise<KenaiClient>;
|
|
119
|
+
model<T extends Record<string, unknown>>(collectionName: string, schema: z.ZodType<T>): KenaiModel<T>;
|
|
120
|
+
_request<R = unknown>(path: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', body?: unknown): Promise<R>;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export { type CollectionEventType, type FindOptions, type InsertManyOptions, KenaiClient, type KenaiConnectOptions, KenaiError, KenaiModel, type UnsubscribeFn, type WriteOptions };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{z as $}from"zod";import{z as v}from"zod";var d;(function(o){o.Google="google",o.OpenAI="openai",o.Anthropic="anthropic",o.OpenRouter="openrouter"})(d||(d={}));function T(o,e){let n=v.toJSONSchema(o,{target:"draft-2020-12",unrepresentable:"any"});return e&&!n.title&&(n.title=e),n}var l=class extends Error{statusCode;details;constructor(e,n=500,t){super(e),this.name="KenaiError",this.statusCode=n,this.details=t}},u=class{constructor(e){this.executor=e}executor;n;t;o;i;sort(e){return this.n=e,this}limit(e){return this.t=e,this}skip(e){return this.o=e,this}select(e){return this.i=e,this}then(e,n){return this.executor({sort:this.n,limit:this.t,skip:this.o,select:this.i}).then(e,n)}},y=class{constructor(e,n,t){this.client=e;this.collectionName=n;this.jsonSchema=T(t,n)}client;collectionName;jsonSchema;getJsonSchema(){return this.jsonSchema}async syncSchema(){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/schema`,"PUT",{jsonSchema:this.jsonSchema})}async insert(e,n={}){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/insert`,"POST",{input:e,file:n.file,mode:n.mode??"async",idempotencyKey:n.idempotencyKey,webhookUrl:n.webhookUrl,webhookSecret:n.webhookSecret,jsonSchema:this.jsonSchema,byom:this.client.byom})}async insertMany(e,n={}){return(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/insertMany`,"POST",{inputs:e,files:n.files,idempotencyKeys:n.idempotencyKeys,mode:n.mode??"async",webhookUrl:n.webhookUrl,webhookSecret:n.webhookSecret,jsonSchema:this.jsonSchema,byom:this.client.byom})).documents}async update(e,n,t={}){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/update`,"POST",{filter:e,patch:n,file:t.file,mode:t.mode??"async",idempotencyKey:t.idempotencyKey,webhookUrl:t.webhookUrl,webhookSecret:t.webhookSecret,jsonSchema:this.jsonSchema,byom:this.client.byom})}async updateMany(e,n,t={}){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/updateMany`,"POST",{filter:e,patch:n,file:t.file,mode:t.mode??"async",idempotencyKey:t.idempotencyKey,webhookUrl:t.webhookUrl,webhookSecret:t.webhookSecret,jsonSchema:this.jsonSchema,byom:this.client.byom})}find(e={},n={}){let t=typeof e=="string";return new u(async i=>(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/find`,"POST",{filter:t?{}:e,naturalLanguage:t?e:void 0,mode:t?n.mode??"nl":"native",...i,jsonSchema:t?this.jsonSchema:void 0,byom:t?this.client.byom:void 0})).documents)}async findOne(e={},n={}){return typeof e=="string"?(await this.find(e,n).limit(1))[0]??null:(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/findOne`,"POST",{filter:e})).document}async delete(e){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/delete`,"POST",{filter:e,many:!1})}async deleteMany(e){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/delete`,"POST",{filter:e,many:!0})}async aggregate(e){return(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/aggregate`,"POST",{pipeline:e})).results}async waitForHydration(e,n=15e3){return this.client.e(`/v1/documents/${encodeURIComponent(e)}/wait?timeoutMs=${n}`,"GET")}on(e,n,t){let i=new AbortController,r=`${this.client.baseUrl}/v1/collections/${encodeURIComponent(this.collectionName)}/events`,c={Accept:"text/event-stream"};return this.client.apiKey&&(c.Authorization=`Bearer ${this.client.apiKey}`),(async()=>{try{let s=await fetch(r,{method:"GET",headers:c,signal:i.signal});if(!s.ok||!s.body)throw new l(`Failed to open event stream (${s.status})`,s.status);let g=s.body.getReader(),w=new TextDecoder,m="";for(;;){let{done:f,value:R}=await g.read();if(f)break;m+=w.decode(R,{stream:!0});let p=m.split(`
|
|
2
|
+
|
|
3
|
+
`);m=p.pop()??"";for(let S of p){let K=S.split(`
|
|
4
|
+
`),b="message",h=[];for(let a of K)a.startsWith("event:")?b=a.slice(6).trim():a.startsWith("data:")&&h.push(a.slice(5).trim());if(b===e&&h.length>0)try{let a=JSON.parse(h.join(`
|
|
5
|
+
`));n(a)}catch{}}}}catch(s){if(i.signal.aborted)return;t?.(s instanceof Error?s:new Error(String(s)))}})(),()=>i.abort()}async getDlq(){return(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/dlq`,"GET")).documents}async replayDlq(){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/dlq/replay`,"POST",{byom:this.client.byom,jsonSchema:this.jsonSchema})}async registerWebhook(e){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/webhooks`,"POST",e)}async listWebhooks(){return(await this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/webhooks`,"GET")).webhooks}async deleteWebhook(e){return this.client.e(`/v1/collections/${encodeURIComponent(this.collectionName)}/webhooks/${encodeURIComponent(e)}`,"DELETE")}},k=class o{baseUrl;byom;apiKey;constructor(e,n={}){this.baseUrl=o.normalizeUri(e),this.byom=n.byom,this.apiKey=n.apiKey}static normalizeUri(e){let n=e.trim();n.startsWith("kenai+srv://")?n=`https://${n.slice(12)}`:n.startsWith("kenai://")&&(n=`http://${n.slice(8)}`);try{let t=new URL(n);return`${t.protocol}//${t.host}`}catch{return n.replace(/\/+$/,"")}}static async connect(e,n={}){let t=new o(e,n);return await t.e("/v1/health","GET"),t}model(e,n){return new y(this,e,n)}async e(e,n,t){let i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);let r=await fetch(`${this.baseUrl}${e}`,{method:n,headers:i,body:t!==void 0?JSON.stringify(t):void 0}),c=await r.json().catch(()=>null);if(!r.ok)throw new l(c?.message||`Kenai DB request failed (${r.status} ${r.statusText})`,r.status,c);return c}};export{k as KenaiClient,l as KenaiError,y as KenaiModel,d as KenaiProvider,$ as z};
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kenaidb/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Official TypeScript/Node.js SDK for Kenai DB — the AI-Native Document Database",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"kenaidb",
|
|
8
|
+
"ai-database",
|
|
9
|
+
"document-database",
|
|
10
|
+
"nosql",
|
|
11
|
+
"zod",
|
|
12
|
+
"llm",
|
|
13
|
+
"structured-extraction",
|
|
14
|
+
"byom"
|
|
15
|
+
],
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/Kenykore/kenai.git",
|
|
20
|
+
"directory": "packages/sdk-ts"
|
|
21
|
+
},
|
|
22
|
+
"homepage": "https://kenaidb.com",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/Kenykore/kenai/issues"
|
|
25
|
+
},
|
|
26
|
+
"type": "module",
|
|
27
|
+
"main": "./dist/index.cjs",
|
|
28
|
+
"module": "./dist/index.js",
|
|
29
|
+
"types": "./dist/index.d.ts",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js",
|
|
34
|
+
"require": "./dist/index.cjs"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"README.md",
|
|
40
|
+
"LICENSE"
|
|
41
|
+
],
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsup",
|
|
47
|
+
"test": "node --test dist-test/sdk.test.js",
|
|
48
|
+
"test:run": "npm run build && tsc -p tsconfig.test.json && node --test dist-test/sdk.test.js"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"zod": "^4.3.6"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@kenaidb/schema": "*",
|
|
55
|
+
"@types/node": "^22.10.7",
|
|
56
|
+
"tsup": "^8.4.0",
|
|
57
|
+
"typescript": "~5.9.3"
|
|
58
|
+
}
|
|
59
|
+
}
|