@vibes.diy/api-sql 0.0.0-smoke-85ffc167-1775073098

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,539 @@
1
+ # vibes.diy API
2
+
3
+ WebSocket-based API for vibes.diy chat persistence and app deployment. Supports both HTTP POST and WebSocket connections using the same handler via the Evento event-driven framework.
4
+
5
+ ## Package Structure
6
+
7
+ ```
8
+ api/
9
+ ├── types/ @vibes.diy/api-types SHARED (client + server)
10
+ │ ├── msg-types.ts Request/response types, VibeFile, MsgBase envelope, arktype schemas
11
+ │ ├── types.ts FileSystemItem with transform support
12
+ │ └── vibes-diy-serv-ctx.ts Server context for wrapper/iframe rendering
13
+
14
+ ├── pkg/ @vibes.diy/api-pkg SHARED (client + server)
15
+ │ ├── api.ts VibesDiyApiIface interface (3 methods)
16
+ │ ├── encoder.ts Evento encoders: ReqRes, W3CWebSocket, Combined
17
+ │ ├── index.ts Re-exports
18
+ │ └── react/ React components (client only in practice)
19
+
20
+ ├── impl/ @vibes.diy/api-impl CLIENT
21
+ │ └── index.ts VibeDiyApi class (WebSocket client, WIP - no reconnection)
22
+
23
+ ├── svc/ @vibes.diy/api-svc SERVER (Cloudflare Workers)
24
+ │ ├── cf-serve.ts Cloudflare Worker entry point (HTTP + WebSocket)
25
+ │ ├── create-handler.ts Evento pipeline setup with all handlers
26
+ │ ├── check-auth.ts Auth middleware (clerk, device-id verification)
27
+ │ ├── unwrap-msg-base.ts MsgBase envelope unwrapping for validation
28
+ │ ├── api.ts VibesApiSQLCtx type + VibesFPApiParameters
29
+ │ ├── entry-point-utils.ts URL construction for deployed apps
30
+ │ │
31
+ │ ├── public/ Public API handlers (Evento handlers)
32
+ │ │ ├── ensure-app-slug-item.ts App deployment with CID-based storage
33
+ │ │ ├── ensure-chat-context.ts Chat session creation/retrieval
34
+ │ │ ├── append-chat-section.ts Message persistence with seq numbers
35
+ │ │ └── serv-entry-point.ts Serves deployed app HTML
36
+ │ │
37
+ │ ├── intern/ Internal helpers
38
+ │ │ ├── ensure-slug-binding.ts User/app slug management (random-words)
39
+ │ │ ├── ensure-storage.ts CID calculation (SHA-256 + base58btc)
40
+ │ │ ├── import-map.ts ESM import map generation (esm.sh)
41
+ │ │ ├── render-vibes.tsx HTML rendering with import map injection
42
+ │ │ └── write-apps.ts App record creation with transforms (sucrase, acorn)
43
+ │ │
44
+ │ └── sql/
45
+ │ └── vibes-diy-api-schema.ts Drizzle schema (D1)
46
+
47
+ └── tests/ @vibes.diy/api-test
48
+ └── api.test.ts
49
+ ```
50
+
51
+ ## Package Summary
52
+
53
+ | Package | Runs On | Purpose |
54
+ | ---------------------- | ------- | --------------------------------------- |
55
+ | `@vibes.diy/api-types` | Both | arktype schemas, request/response types |
56
+ | `@vibes.diy/api-pkg` | Both | Interface + encoders (shared contract) |
57
+ | `@vibes.diy/api-impl` | Client | `VibeDiyApi` WebSocket client class |
58
+ | `@vibes.diy/api-svc` | Server | Cloudflare Worker handlers, D1/Drizzle |
59
+
60
+ ## Architecture
61
+
62
+ ### Message Envelope
63
+
64
+ All requests are wrapped in a `MsgBase` envelope:
65
+
66
+ ```typescript
67
+ interface MsgBase {
68
+ tid: string; // Transaction ID for request/response correlation
69
+ src: string; // Source identifier
70
+ dst: string; // Destination identifier
71
+ ttl: number; // Time-to-live
72
+ payload: unknown; // The actual request/response
73
+ }
74
+ ```
75
+
76
+ ### Evento Pipeline
77
+
78
+ The server uses Evento (from `@adviser/cement`) for request routing. Handlers are registered in order:
79
+
80
+ 1. **CORS preflight** - Handles OPTIONS requests
81
+ 2. **servEntryPoint** - Serves deployed app HTML (hostname routing: `{appSlug}--{userSlug}.{host}/~{fsId}~/`)
82
+ 3. **Request logging** - Logs incoming POST/PUT requests, rejects other methods with 503
83
+ 4. **ensureAppSlugItem** - App deployment handler
84
+ 5. **ensureChatContext** - Chat session handler
85
+ 6. **appendChatSection** - Message persistence handler
86
+ 7. **Not-found handler** - Returns 501 for unmatched requests (semantically "Not Implemented")
87
+ 8. **Error handler** - Catches and formats errors as 500
88
+
89
+ Each handler has `validate` (arktype schema check) and `handle` (business logic) phases. Some handlers also have a `post` phase for cleanup/logging.
90
+
91
+ ## Data Flow
92
+
93
+ ```
94
+ Client (browser) Server (CF Worker)
95
+ ───────────────── ──────────────────
96
+ VibeDiyApi.ensureAppSlug() → cf-serve.ts
97
+ ↓ ↓
98
+ WebSocket.send(MsgBox<Req>) → WebSocketPair upgrade
99
+
100
+ CombinedEventoEnDecoder.encode()
101
+
102
+ Evento.trigger() with handlers
103
+
104
+ unwrapMsgBase() → extract payload
105
+
106
+ checkAuth() → verify token
107
+
108
+ handler.handle() → business logic
109
+
110
+ D1 queries (Drizzle ORM)
111
+
112
+ MsgBox<Res> ← SendResponseProvider.send()
113
+ ```
114
+
115
+ ## API Methods
116
+
117
+ ### `ensureAppSlug()`
118
+
119
+ Deploy an app with a filesystem. Process:
120
+
121
+ 1. Verify auth token (clerk/device-id)
122
+ 2. Create or retrieve user slug binding
123
+ 3. Create or retrieve app slug binding
124
+ 4. Calculate CIDs for all file contents
125
+ 5. Store assets in D1 `Assets` table
126
+ 6. Apply transforms (jsx-to-js, import map generation)
127
+ 7. Create `Apps` record with filesystem manifest
128
+ 8. Return `entryPointUrl` for iframe loading
129
+
130
+ ### `ensureChatContext()`
131
+
132
+ Create or retrieve a chat session:
133
+
134
+ 1. If `contextId` provided, verify it exists and belongs to user
135
+ 2. Otherwise, generate new contextId (12-char ID)
136
+ 3. Insert into `ChatContexts` table
137
+ 4. Return `contextId`
138
+
139
+ ### `appendChatSection()`
140
+
141
+ Add messages to a chat context:
142
+
143
+ 1. Verify context exists and belongs to user
144
+ 2. Get max `seq` for context, increment
145
+ 3. Insert into `ChatSections` with `origin` ('user' or 'llm')
146
+ 4. Blocks use `BlockMsgs | PromptMsg` types from `@vibes.diy/call-ai-v2`
147
+ 5. Return `seq` number
148
+
149
+ ## CI/CD
150
+
151
+ The API is bundled into the main vibes.diy Cloudflare Worker (not a separate deployment).
152
+
153
+ ### Workflow
154
+
155
+ `.github/workflows/vibes-diy-deploy.yaml`
156
+
157
+ **Triggers:**
158
+
159
+ - Push to `vibes.diy/**/*` paths
160
+ - Tags: `vibes-diy@*`
161
+ - Manual dispatch
162
+
163
+ ### Environments
164
+
165
+ | Trigger | Environment | Domain |
166
+ | ----------------------- | ----------- | ------------------------ |
167
+ | Tag `vibes-diy@s*` | staging | `*.dev-v2.vibesdiy.net` |
168
+ | Tag `vibes-diy@p*` | production | `*.prod-v2.vibesdiy.net` |
169
+ | Path push or other tags | dev | `*.dev-v2.vibesdiy.net` |
170
+
171
+ ### Deploy Steps
172
+
173
+ Deployment is handled by the GitHub Action (`vibes.diy/actions/deploy`). The action runs:
174
+
175
+ ```bash
176
+ pnpm run build # Build React app + bundle worker
177
+ pnpm run drizzle:d1-remote # Run D1 migrations
178
+ core-cli writeEnv | wrangler secret bulk # Push secrets
179
+ pnpm run deploy:${ENV} # wrangler deploy
180
+ ```
181
+
182
+ Do not run these manually - push a tag or merge to trigger the workflow.
183
+
184
+ ### Infrastructure
185
+
186
+ | Resource | Binding | Purpose |
187
+ | ------------- | -------- | ----------------------------- |
188
+ | D1 Database | `DB` | Chat contexts, sections, apps |
189
+ | Static Assets | `ASSETS` | React app build |
190
+
191
+ ### Server Context (VibesApiSQLCtx)
192
+
193
+ All handlers receive a shared context via `ctx.ctx.getOrThrow<VibesApiSQLCtx>("vibesApiCtx")`:
194
+
195
+ ```typescript
196
+ interface VibesApiSQLCtx {
197
+ sthis: SuperThis; // Fireproof utilities (logger, nextId, env)
198
+ db: VibesSqlite; // Drizzle DB instance
199
+ tokenApi: Record<string, FPApiToken>; // Auth verifiers by type
200
+ deviceCA: DeviceIdCAIf; // Device ID certificate authority
201
+ logger: Logger; // Structured logger
202
+ params: VibesFPApiParameters; // Service configuration
203
+ cache: CfCacheIf; // Cloudflare cache API
204
+ fetchPkgVersion(pkg): Promise<string | undefined>; // npm registry lookup
205
+ waitUntil<T>(promise): void; // CF worker lifecycle
206
+ ensureStorage(...items): Promise<Result<StorageResult[]>>; // Asset storage
207
+ }
208
+ ```
209
+
210
+ ### D1 Schema
211
+
212
+ Defined in `svc/sql/vibes-diy-api-schema.ts` using Drizzle ORM.
213
+
214
+ **Assets** - Binary content storage (could move to R2)
215
+ | Column | Type | Description |
216
+ |--------|------|-------------|
217
+ | `assetId` | text PK | CID of content |
218
+ | `content` | blob | Actual content |
219
+ | `created` | text | ISO timestamp |
220
+
221
+ **UserSlugBindings** - Maps users to their human-friendly slugs
222
+ | Column | Type | Description |
223
+ |--------|------|-------------|
224
+ | `userId` | text | User identifier |
225
+ | `userSlug` | text | Human-friendly user slug (unique) |
226
+ | `created` | text | ISO timestamp |
227
+
228
+ Primary key: `(userSlug, userId)`. Unique index on `userSlug`.
229
+
230
+ **AppSlugBindings** - Maps apps to slugs within a user's namespace
231
+ | Column | Type | Description |
232
+ |--------|------|-------------|
233
+ | `userSlug` | text FK | References UserSlugBindings.userSlug |
234
+ | `appSlug` | text | Human-friendly app slug |
235
+ | `created` | text | ISO timestamp |
236
+
237
+ Primary key: `(appSlug, userSlug)`.
238
+
239
+ **Apps** - Deployed app versions with filesystem and environment
240
+ | Column | Type | Description |
241
+ |--------|------|-------------|
242
+ | `appSlug` | text | App identifier |
243
+ | `userId` | text | Owner |
244
+ | `userSlug` | text | Owner's slug |
245
+ | `releaseSeq` | int | Incremented on each deployment |
246
+ | `fsId` | text | CID of filesystem manifest |
247
+ | `env` | json | Environment variables (VibesEnv) |
248
+ | `fileSystem` | json | Array of FileSystemItem with transforms |
249
+ | `mode` | text | 'production' or 'dev' |
250
+ | `created` | text | ISO timestamp |
251
+
252
+ Primary key: `(appSlug, userId, releaseSeq)`. Indexes on `fsId` and `created`.
253
+
254
+ **ChatContexts** - Chat session containers
255
+ | Column | Type | Description |
256
+ |--------|------|-------------|
257
+ | `contextId` | text PK | UUID v4 |
258
+ | `userId` | text | Owner |
259
+ | `created` | text | ISO timestamp |
260
+
261
+ **ChatSections** - Individual messages/blocks within a chat
262
+ | Column | Type | Description |
263
+ |--------|------|-------------|
264
+ | `contextId` | text FK | References ChatContexts.contextId |
265
+ | `seq` | int | Section sequence number (0-indexed, auto-incremented) |
266
+ | `origin` | text | 'user' or 'llm' |
267
+ | `blocks` | json | Array of BlockMsgs or PromptMsg from call-ai-v2 |
268
+ | `created` | text | ISO timestamp |
269
+
270
+ Primary key: `(seq, contextId)`.
271
+
272
+ ### Environment Variables
273
+
274
+ **Required:**
275
+ | Variable | Purpose |
276
+ |----------|---------|
277
+ | `CLOUD_SESSION_TOKEN_PUBLIC` | Public key for cloud session tokens |
278
+ | `CLERK_PUBLISHABLE_KEY` | Clerk auth verification |
279
+ | `DEVICE_ID_CA_PRIV_KEY` | Device ID certificate authority private key |
280
+ | `DEVICE_ID_CA_CERT` | Device ID certificate authority cert |
281
+ | `FP_VERSION` | Fireproof version for import maps |
282
+ | `VIBES_SVC_HOSTNAME_BASE` | Base hostname for deployed apps (e.g., `vibes.app`) |
283
+
284
+ **Optional (with defaults):**
285
+ | Variable | Default | Purpose |
286
+ |----------|---------|---------|
287
+ | `VIBES_SVC_PROTOCOL` | `https` | Protocol for deployed apps |
288
+ | `MAX_APP_SLUG_PER_USER_ID` | `10` | Max app slugs per user |
289
+ | `MAX_USER_SLUG_PER_USER_ID` | `10` | Max user slugs per user |
290
+ | `MAX_APPS_PER_USER_ID` | `50` | Max app deployments per user |
291
+
292
+ ## Message Types
293
+
294
+ ### VibeFile (for deployment)
295
+
296
+ Six variants for different content types:
297
+
298
+ | Type | Content | Use Case |
299
+ | ------------------- | ------------------------------------ | ------------------------------ |
300
+ | `code-block` | Inline string, `lang: 'jsx' \| 'js'` | JSX/JS source code |
301
+ | `code-ref` | `refId` reference | Code stored elsewhere |
302
+ | `str-asset-block` | Inline string | CSS, JSON, text files |
303
+ | `str-asset-ref` | `refId` reference | String assets stored elsewhere |
304
+ | `uint8-asset-block` | `Uint8Array` | Images, fonts, binaries |
305
+ | `uint8-asset-ref` | `refId` reference | Binary assets stored elsewhere |
306
+
307
+ All file types share base properties:
308
+
309
+ ```typescript
310
+ {
311
+ filename: string; // Must start with /, no //, /../, /./
312
+ entryPoint?: boolean; // Last one wins, marks app entry
313
+ mimetype?: string; // Derived from filename if not set
314
+ }
315
+ ```
316
+
317
+ ### FileSystemItem (stored result)
318
+
319
+ After processing, files become `FileSystemItem`:
320
+
321
+ ```typescript
322
+ {
323
+ fileName: string;
324
+ mimeType: string;
325
+ assetId: string; // CID of content
326
+ assetURI: string; // sql://Assets.assetId, s3://..., r2://...
327
+ entryPoint?: boolean;
328
+ size: number;
329
+ transform?: {
330
+ type: 'jsx-to-js' | 'imports' | 'import-map' | 'transformed';
331
+ // ... transform-specific fields
332
+ }
333
+ }
334
+ ```
335
+
336
+ ### Auth Types
337
+
338
+ ```typescript
339
+ type DashAuthType = {
340
+ type: "clerk" | "device-id";
341
+ token: string;
342
+ };
343
+ ```
344
+
345
+ Auth is verified via `tokenApi` which supports:
346
+
347
+ - **clerk** - Clerk JWT verification using `CLERK_PUB_JWT_KEY` / `CLERK_PUB_JWT_URL` env vars
348
+ - **device-id** - Device certificate verification using `DEVICE_ID_CA_*` keys
349
+
350
+ ## Client Usage
351
+
352
+ > [!WARNING]
353
+ > The client (`@vibes.diy/api-impl`) is currently a work-in-progress. While it can send requests over WebSocket, the response correlation logic (matching server responses to requests via `tid`) is not yet fully implemented. It is currently primarily used for testing with direct handler calls.
354
+
355
+ The client is currently used in tests. The main vibes.diy app doesn't use it yet - integration is in progress.
356
+
357
+ ### Creating a Client
358
+
359
+ ```typescript
360
+ import { VibeDiyApi } from "@vibes.diy/api-impl";
361
+ import { Result } from "@adviser/cement";
362
+
363
+ const api = new VibeDiyApi({
364
+ apiUrl: "wss://api.vibes.diy/v1/ws", // Default if omitted
365
+ getToken: async () => {
366
+ // Return auth token (Clerk or device-id)
367
+ return Result.Ok({ type: "clerk", token: clerkToken });
368
+ },
369
+ timeoutMs: 10000, // Default: 10s request timeout
370
+ });
371
+ ```
372
+
373
+ The client uses `KeyedResolvOnce` for connection pooling - multiple `VibeDiyApi` instances with the same `apiUrl` share a WebSocket connection. (See `impl/index.ts` for custom message routing options via the `msg` config.)
374
+
375
+ ### Deploying an App
376
+
377
+ ```typescript
378
+ const res = await api.ensureAppSlug({
379
+ mode: "dev", // 'dev' or 'production'
380
+ appSlug: "my-app", // optional, server generates 3-word slug
381
+ userSlug: "my-user", // optional, server generates 3-word slug
382
+ env: { API_KEY: "..." }, // optional, passed to app runtime
383
+ fileSystem: [
384
+ {
385
+ type: "code-block",
386
+ lang: "jsx",
387
+ filename: "/App.jsx", // Must start with /, becomes entry point
388
+ entryPoint: true,
389
+ content: "export default function App() { return <div>Hello</div>; }",
390
+ },
391
+ ],
392
+ });
393
+
394
+ if (res.isOk()) {
395
+ const { entryPointUrl, fsId, userSlug, appSlug, fileSystem } = res.Ok();
396
+ // entryPointUrl -> https://{appSlug}--{userSlug}.{hostnameBase}/~{fsId}~/
397
+ // e.g. https://my-app--my-user.vibes.app/~zABC123~/
398
+ // fsId -> CID of filesystem manifest
399
+ // fileSystem -> Array<FileSystemItem> with assetIds and transforms
400
+ }
401
+ ```
402
+
403
+ **Response includes:**
404
+
405
+ - `entryPointUrl` - URL to load in iframe (constructed from `VIBES_SVC_*` config)
406
+ - `wrapperUrl` - URL for wrapper page with auth handoff
407
+ - `fsId` - CID of the filesystem manifest
408
+ - `fileSystem` - Processed `FileSystemItem[]` with CIDs and transforms applied
409
+
410
+ ### Chat Context Management
411
+
412
+ ```typescript
413
+ // Create a new chat context (server generates contextId)
414
+ const ctx = await api.ensureChatContext({});
415
+
416
+ // Or retrieve/create with a specific contextId
417
+ const ctx = await api.ensureChatContext({ contextId: "my-context-id" });
418
+
419
+ if (ctx.isOk()) {
420
+ const { contextId } = ctx.Ok();
421
+
422
+ // Append a user message
423
+ const userRes = await api.appendChatSection({
424
+ contextId,
425
+ origin: "user", // 'user' | 'llm'
426
+ blocks: [
427
+ // BlockMsgs or PromptMsg from @vibes.diy/call-ai-v2
428
+ {
429
+ type: "prompt.txt",
430
+ streamId: "stream-1",
431
+ request: { model: "gpt-4", messages: [{ role: "user", content: "Hello" }] },
432
+ timestamp: new Date(),
433
+ },
434
+ ],
435
+ });
436
+ // userRes.Ok().seq -> 0 (first section)
437
+
438
+ // Append LLM response
439
+ const llmRes = await api.appendChatSection({
440
+ contextId,
441
+ origin: "llm",
442
+ blocks: sectionBlocks, // BlockMsgs from call-ai sections stream
443
+ });
444
+ // llmRes.Ok().seq -> 1 (second section)
445
+ }
446
+ ```
447
+
448
+ **Note:** Context ownership is enforced - you can only append to contexts created by your userId.
449
+
450
+ ### Testing
451
+
452
+ Tests use a local handler directly rather than WebSocket. See `api/tests/api.test.ts` for the full setup including:
453
+
454
+ - Creating a local D1/libsql database
455
+ - Setting up test device-id auth
456
+ - Calling the handler directly
457
+
458
+ Note: The test passes an ad-hoc `fetch` property via TypeScript structural typing, but this isn't part of the official `VibeDiyApiParam` interface. A proper `fetch` override may be added in the future.
459
+
460
+ ## Running Tests
461
+
462
+ ```bash
463
+ cd vibes.diy/api/tests
464
+ pnpm test
465
+ ```
466
+
467
+ ## Implementation Details
468
+
469
+ ### URL Structure
470
+
471
+ Deployed apps are served via hostname-based routing:
472
+
473
+ ```
474
+ https://{appSlug}--{userSlug}.{hostnameBase}/~{fsId}~/
475
+ └────────────────────┘ └──────────┘ └──────┘
476
+ hostname base domain version path
477
+ ```
478
+
479
+ Example: `https://my-app--fuzzy-purple-elephant.vibes.app/~z4PhNX7vuL~/`
480
+
481
+ The `extractHostToBindings()` function parses:
482
+
483
+ - Hostname pattern: `{appSlug}--{userSlug}.{rest}`
484
+ - Path pattern: `/~{fsId}~/` (fsId starts with `z`, 8+ chars)
485
+ - If no fsId in path, serves latest production release
486
+
487
+ ### Slug Generation
488
+
489
+ When `appSlug` or `userSlug` are not provided, the server generates 3-word slugs using the `random-words` package:
490
+
491
+ ```typescript
492
+ generate({ exactly: 1, wordsPerString: 3, separator: "-" });
493
+ // → "fuzzy-purple-elephant"
494
+ ```
495
+
496
+ Up to 5 attempts are made to find a unique slug before failing.
497
+
498
+ ### Transform Pipeline
499
+
500
+ The `write-apps.ts` module applies transforms to uploaded files:
501
+
502
+ 1. **JSX → JS** (`sucrase` with automatic JSX runtime)
503
+ - Input: `code-block` with `lang: "jsx"`
504
+ - Output: `/~~transformed~~/{cid}` with `transform: { type: "transformed", action: "jsx-to-js" }`
505
+
506
+ 2. **Import Extraction** (`acorn` parser)
507
+ - Parses all JS files for `import`/`export` statements
508
+ - Extracts bare specifiers (e.g., `react`, `@fireproof/core`)
509
+
510
+ 3. **Import Map Generation**
511
+ - Unknown packages → npm registry lookup for version → `esm.sh` URL
512
+ - Predefined mappings for React 19.2.1, Fireproof, Clerk, etc.
513
+ - Output: `/~~calculated~~/import-map.json` with `transform: { type: "import-map" }`
514
+
515
+ ### fsId Calculation
516
+
517
+ The `fsId` is a deterministic CID computed from:
518
+
519
+ ```typescript
520
+ hash(sortedFilenames + mimetypes + contentCIDs + sortedEnvJSON);
521
+ ```
522
+
523
+ Same files + same env = same fsId (enables deduplication).
524
+
525
+ ### Asset Caching
526
+
527
+ `serv-entry-point.ts` uses two-tier Cloudflare caching:
528
+
529
+ 1. **Global cache** by CID: `assetCacheUrl/{assetId}`
530
+ 2. **Path cache** by request URL
531
+
532
+ On cache miss: D1 query → populate both caches via `waitUntil()`.
533
+
534
+ ### App Eviction
535
+
536
+ When a user exceeds `MAX_APPS_PER_USER_ID`:
537
+
538
+ - Oldest `dev` mode apps are evicted first (10% of total + 1)
539
+ - `production` apps are preserved
package/index.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { D1Database } from "@cloudflare/workers-types";
2
+ import { VibesSqlite } from "./tables.js";
3
+ export * from "./tables.js";
4
+ export * as pg from "./vibes-diy-api-schema-pg.js";
5
+ export * as sqlite from "./vibes-diy-api-schema-sqlite.js";
6
+ export * from "./sql-peer.js";
7
+ export declare function cfDrizzle<T extends VibesSqlite>(env: {
8
+ DB_FLAVOUR?: string;
9
+ NEON_DATABASE_URL?: string;
10
+ }, d1: D1Database, ctxDrizzle?: T): {
11
+ db: T;
12
+ };
package/index.js ADDED
@@ -0,0 +1,17 @@
1
+ import { toDBFlavour } from "./tables.js";
2
+ export * from "./tables.js";
3
+ export * as pg from "./vibes-diy-api-schema-pg.js";
4
+ export * as sqlite from "./vibes-diy-api-schema-sqlite.js";
5
+ export * from "./sql-peer.js";
6
+ import { drizzle as drizzleD1 } from "drizzle-orm/d1";
7
+ import { drizzle as drizzleNeon } from "drizzle-orm/neon-serverless";
8
+ import { Pool } from "@neondatabase/serverless";
9
+ export function cfDrizzle(env, d1, ctxDrizzle) {
10
+ if (ctxDrizzle)
11
+ return { db: ctxDrizzle };
12
+ if (toDBFlavour(env.DB_FLAVOUR) === "pg" && env.NEON_DATABASE_URL) {
13
+ return { db: drizzleNeon(new Pool({ connectionString: env.NEON_DATABASE_URL })) };
14
+ }
15
+ return { db: drizzleD1(d1) };
16
+ }
17
+ //# sourceMappingURL=index.js.map
package/index.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../jsr/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAe,MAAM,aAAa,CAAC;AAEvD,cAAc,aAAa,CAAC;AAC5B,OAAO,KAAK,EAAE,MAAM,8BAA8B,CAAC;AACnD,OAAO,KAAK,MAAM,MAAM,kCAAkC,CAAC;AAC3D,cAAc,eAAe,CAAC;AAE9B,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AAEhD,MAAM,UAAU,SAAS,CACvB,GAGC,EACD,EAAc,EACd,UAAc;IAEd,IAAI,UAAU;QAAE,OAAO,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC;IAC1C,IAAI,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,IAAI,IAAI,GAAG,CAAC,iBAAiB,EAAE,CAAC;QAClE,OAAO,EAAE,EAAE,EAAE,WAAW,CAAC,IAAI,IAAI,CAAC,EAAE,gBAAgB,EAAE,GAAG,CAAC,iBAAiB,EAAE,CAAC,CAAiB,EAAE,CAAC;IACpG,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,SAAS,CAAC,EAAE,CAAiB,EAAE,CAAC;AAC/C,CAAC"}
package/package.json ADDED
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "@vibes.diy/api-sql",
3
+ "version": "0.0.0-smoke-85ffc167-1775073098",
4
+ "type": "module",
5
+ "scripts": {
6
+ "build": "core-cli tsc"
7
+ },
8
+ "dependencies": {
9
+ "@adviser/cement": "~0.5.34",
10
+ "@cloudflare/workers-types": "~4.20260317.1",
11
+ "@fireproof/core-protocols-dashboard": "~0.24.15",
12
+ "@fireproof/core-runtime": "~0.24.15",
13
+ "@fireproof/core-types-base": "~0.24.15",
14
+ "@fireproof/core-types-protocols-dashboard": "~0.24.15",
15
+ "@libsql/client": "~0.17.0",
16
+ "@neondatabase/serverless": "~1.0.2",
17
+ "@noble/hashes": "~2.0.1",
18
+ "@vibes.diy/api-pkg": "0.0.0-smoke-85ffc167-1775073098",
19
+ "@vibes.diy/api-types": "0.0.0-smoke-85ffc167-1775073098",
20
+ "@vibes.diy/call-ai-v2": "0.0.0-smoke-85ffc167-1775073098",
21
+ "arktype": "~2.2.0",
22
+ "drizzle-orm": "~0.45.1",
23
+ "multiformats": "~13.4.2",
24
+ "ws": "~8.20.0"
25
+ }
26
+ }
package/sql-peer.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { Option, URI, Result } from "@adviser/cement";
2
+ import { FetchResult } from "@vibes.diy/api-types";
3
+ import { DBFlavour, VibesApiTables, VibesSqlite } from "./tables.js";
4
+ import { Cider, PeerFetch, PeerStreamWithCommit, PeerWithCommit, StoragePeer } from "@vibes.diy/api-pkg";
5
+ export declare class SQLPeer implements PeerWithCommit {
6
+ readonly db: VibesSqlite;
7
+ readonly assets: VibesApiTables["assets"];
8
+ readonly cider: Cider;
9
+ readonly cutoffSize: number;
10
+ readonly flavour: DBFlavour;
11
+ constructor(flavour: DBFlavour, db: VibesSqlite, assets: VibesApiTables["assets"], cider: Cider, cutoffSize: number);
12
+ begin(): Promise<Result<PeerStreamWithCommit>>;
13
+ }
14
+ export declare class SQLPeerFetch implements PeerFetch {
15
+ readonly db: VibesSqlite;
16
+ readonly assets: VibesApiTables["assets"];
17
+ readonly flavour: DBFlavour;
18
+ constructor(flavour: DBFlavour, db: VibesSqlite, assets: VibesApiTables["assets"]);
19
+ fetch(url: URI): Promise<Option<FetchResult>>;
20
+ }
21
+ export interface CreateSQLPeerParams {
22
+ flavour: DBFlavour;
23
+ db: VibesSqlite;
24
+ assets: VibesApiTables["assets"];
25
+ }
26
+ export declare function createSQLPeer(params: CreateSQLPeerParams): StoragePeer;