@zuiio/supabase 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/AGENTS.md +84 -0
- package/package.json +27 -0
- package/src/api-response.ts +41 -0
- package/src/auth.ts +86 -0
- package/src/errors.ts +42 -0
- package/src/index.ts +7 -0
- package/src/query.ts +108 -0
- package/src/r2-storage.ts +98 -0
- package/src/storage.ts +68 -0
- package/src/turnstile.ts +61 -0
- package/src/with-batch.ts +172 -0
- package/src/with-org-branch-filter.ts +20 -0
- package/src/with-org-scope.ts +24 -0
- package/src/with-pagination.ts +26 -0
- package/src/workers-ai.ts +172 -0
- package/tsconfig.json +7 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# @zuiio/supabase
|
|
2
|
+
|
|
3
|
+
Supabase utilities for server-side operations. Provides auth helpers, query wrappers, storage utilities, and error handling.
|
|
4
|
+
|
|
5
|
+
## Exports
|
|
6
|
+
|
|
7
|
+
| Module | Description |
|
|
8
|
+
|--------|-------------|
|
|
9
|
+
| `auth` | Server-side auth helpers (getSession, getUser, etc.) |
|
|
10
|
+
| `errors` | Supabase error handling and sanitization |
|
|
11
|
+
| `query` | Query helpers (withDbCapture, paginate, etc.) |
|
|
12
|
+
| `storage` | Storage upload/download helpers |
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
### Server auth
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { getSession, getUser } from "@zuiio/supabase/auth";
|
|
20
|
+
|
|
21
|
+
// Get current session (server-side)
|
|
22
|
+
const session = await getSession(supabase);
|
|
23
|
+
|
|
24
|
+
// Get current user (throws if not authenticated)
|
|
25
|
+
const user = await getUser(supabase);
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Error handling
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { sanitizeDbError, isRLSError } from "@zuiio/supabase/errors";
|
|
32
|
+
|
|
33
|
+
const { data, error } = await supabase.from("table").select("*");
|
|
34
|
+
|
|
35
|
+
if (error) {
|
|
36
|
+
// Sanitize for user-facing messages
|
|
37
|
+
const message = sanitizeDbError(error);
|
|
38
|
+
// "Датаны алдаа" (not raw PostgREST error)
|
|
39
|
+
|
|
40
|
+
// Check if it's an RLS error
|
|
41
|
+
if (isRLSError(error)) {
|
|
42
|
+
// Handle permission denied
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Query helpers
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { withDbCapture } from "@zuiio/supabase/query";
|
|
51
|
+
|
|
52
|
+
// Auto-capture Supabase errors (best practice)
|
|
53
|
+
const { data, error } = await withDbCapture("getProfile",
|
|
54
|
+
supabase.from("profiles").select("*").single()
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
// Error is logged to Sentry automatically
|
|
58
|
+
// No need for manual capture() calls
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Storage
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { uploadImage, downloadFile } from "@zuiio/supabase/storage";
|
|
65
|
+
|
|
66
|
+
// Upload with automatic optimization
|
|
67
|
+
const url = await uploadImage(supabase, "avatars", file, {
|
|
68
|
+
maxWidth: 800,
|
|
69
|
+
quality: 0.8,
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// Download file
|
|
73
|
+
const blob = await downloadFile(supabase, "documents", "file.pdf");
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Dependencies
|
|
77
|
+
|
|
78
|
+
- `@supabase/supabase-js` — Supabase client
|
|
79
|
+
|
|
80
|
+
## Notes
|
|
81
|
+
|
|
82
|
+
- Server-side only — use `@zuiio/auth` for client-side auth
|
|
83
|
+
- Always use `withDbCapture()` for queries — catches silent RLS errors
|
|
84
|
+
- `sanitizeDbError()` returns Mongolian error messages
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zuiio/supabase",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": "./src/index.ts",
|
|
7
|
+
"./auth": "./src/auth.ts",
|
|
8
|
+
"./errors": "./src/errors.ts",
|
|
9
|
+
"./query": "./src/query.ts",
|
|
10
|
+
"./storage": "./src/storage.ts",
|
|
11
|
+
"./turnstile": "./src/turnstile.ts",
|
|
12
|
+
"./r2-storage": "./src/r2-storage.ts",
|
|
13
|
+
"./workers-ai": "./src/workers-ai.ts"
|
|
14
|
+
},
|
|
15
|
+
"peerDependencies": {
|
|
16
|
+
"@supabase/supabase-js": "^2"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@supabase/supabase-js": "^2",
|
|
20
|
+
"@zuiio/config": "workspace:*",
|
|
21
|
+
"typescript": "^5"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@aws-sdk/client-s3": "^3.1081.0",
|
|
25
|
+
"@aws-sdk/s3-request-presigner": "^3.1081.0"
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard API response helpers using the standard `Response` API.
|
|
3
|
+
*
|
|
4
|
+
* Framework-agnostic — works with Next.js, Bun, Deno, and any
|
|
5
|
+
* runtime that supports `Response.json()`.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { ok, created, noContent, apiError } from "@zuiio/supabase";
|
|
10
|
+
*
|
|
11
|
+
* export async function GET() {
|
|
12
|
+
* const data = await getItems();
|
|
13
|
+
* return ok(data);
|
|
14
|
+
* }
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** 200 OK — returns `{ data }` */
|
|
19
|
+
export function ok<T>(data: T, init?: ResponseInit) {
|
|
20
|
+
return Response.json({ data }, init);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 201 Created — returns `{ data }` */
|
|
24
|
+
export function created<T>(data: T) {
|
|
25
|
+
return Response.json({ data }, { status: 201 });
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 204 No Content — empty body */
|
|
29
|
+
export function noContent() {
|
|
30
|
+
return new Response(null, { status: 204 });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Structured API error response */
|
|
34
|
+
export function apiError(
|
|
35
|
+
code: string,
|
|
36
|
+
message: string,
|
|
37
|
+
status: number,
|
|
38
|
+
headers?: HeadersInit,
|
|
39
|
+
) {
|
|
40
|
+
return Response.json({ error: { code, message } }, { status, headers });
|
|
41
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { SupabaseClient, User } from "@supabase/supabase-js";
|
|
2
|
+
|
|
3
|
+
export class AuthRequiredError extends Error {
|
|
4
|
+
constructor() {
|
|
5
|
+
super("Нэвтрэх шаардлагатай");
|
|
6
|
+
this.name = "AuthRequiredError";
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class ForbiddenError extends Error {
|
|
11
|
+
constructor(message = "Хандах эрх байхгүй") {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "ForbiddenError";
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Get the current user or throw AuthRequiredError. */
|
|
18
|
+
export async function withAuth(supabase: SupabaseClient): Promise<User> {
|
|
19
|
+
const {
|
|
20
|
+
data: { user },
|
|
21
|
+
error,
|
|
22
|
+
} = await supabase.auth.getUser();
|
|
23
|
+
if (error || !user) throw new AuthRequiredError();
|
|
24
|
+
return user;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Get current session or null — non-throwing. */
|
|
28
|
+
export async function getSession(supabase: SupabaseClient) {
|
|
29
|
+
const {
|
|
30
|
+
data: { session },
|
|
31
|
+
} = await supabase.auth.getSession();
|
|
32
|
+
return session;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Get user ID or null without throwing. */
|
|
36
|
+
export async function getUserId(
|
|
37
|
+
supabase: SupabaseClient,
|
|
38
|
+
): Promise<string | null> {
|
|
39
|
+
const {
|
|
40
|
+
data: { user },
|
|
41
|
+
} = await supabase.auth.getUser();
|
|
42
|
+
return user?.id ?? null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Check if the current user belongs to an org.
|
|
47
|
+
* Assumes a table named `org_members` with columns `org_id`, `user_id`, `role`.
|
|
48
|
+
* Pass your own table/column names via options if your schema differs.
|
|
49
|
+
*/
|
|
50
|
+
export async function getOrgRole(
|
|
51
|
+
supabase: SupabaseClient,
|
|
52
|
+
orgId: string,
|
|
53
|
+
userId: string,
|
|
54
|
+
opts?: {
|
|
55
|
+
table?: string;
|
|
56
|
+
orgCol?: string;
|
|
57
|
+
userCol?: string;
|
|
58
|
+
roleCol?: string;
|
|
59
|
+
},
|
|
60
|
+
): Promise<string | null> {
|
|
61
|
+
const table = opts?.table ?? "org_members";
|
|
62
|
+
const orgCol = opts?.orgCol ?? "org_id";
|
|
63
|
+
const userCol = opts?.userCol ?? "user_id";
|
|
64
|
+
const roleCol = opts?.roleCol ?? "role";
|
|
65
|
+
|
|
66
|
+
const { data } = await supabase
|
|
67
|
+
.from(table)
|
|
68
|
+
.select(roleCol)
|
|
69
|
+
.eq(orgCol, orgId)
|
|
70
|
+
.eq(userCol, userId)
|
|
71
|
+
.single();
|
|
72
|
+
|
|
73
|
+
return (data as Record<string, string> | null)?.[roleCol] ?? null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Require org membership — throws ForbiddenError if not a member. */
|
|
77
|
+
export async function requireOrgMember(
|
|
78
|
+
supabase: SupabaseClient,
|
|
79
|
+
orgId: string,
|
|
80
|
+
userId: string,
|
|
81
|
+
opts?: Parameters<typeof getOrgRole>[3],
|
|
82
|
+
): Promise<string> {
|
|
83
|
+
const role = await getOrgRole(supabase, orgId, userId, opts);
|
|
84
|
+
if (!role) throw new ForbiddenError();
|
|
85
|
+
return role;
|
|
86
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { AuthError, PostgrestError } from "@supabase/supabase-js";
|
|
2
|
+
|
|
3
|
+
const POSTGREST_MESSAGES: Record<string, string> = {
|
|
4
|
+
"42501": "Хандах эрх байхгүй",
|
|
5
|
+
"23503": "Холбоотой өгөгдөл байна — устгах боломжгүй",
|
|
6
|
+
"23505": "Энэ утга аль хэдийн бүртгэлтэй байна",
|
|
7
|
+
PGRST116: "Өгөгдөл олдсонгүй",
|
|
8
|
+
PGRST204: "Хүсэлтийн баганын нэр буруу байна",
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export function parseRLSError(error: PostgrestError): string {
|
|
12
|
+
return POSTGREST_MESSAGES[error.code] ?? error.message;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function parseAuthError(error: AuthError): string {
|
|
16
|
+
const msg = error.message.toLowerCase();
|
|
17
|
+
if (msg.includes("invalid login credentials"))
|
|
18
|
+
return "Нэвтрэх нэр эсвэл нууц үг буруу байна";
|
|
19
|
+
if (msg.includes("email not confirmed"))
|
|
20
|
+
return "И-мэйл хаягаа баталгаажуулна уу";
|
|
21
|
+
if (msg.includes("user already registered"))
|
|
22
|
+
return "Энэ и-мэйл хаяг аль хэдийн бүртгэлтэй байна";
|
|
23
|
+
if (msg.includes("password should be at least"))
|
|
24
|
+
return "Нууц үг хамгийн багадаа 6 тэмдэгт байх ёстой";
|
|
25
|
+
if (msg.includes("email rate limit exceeded"))
|
|
26
|
+
return "Хэт олон оролдлого хийгдлээ. Түр хүлээнэ үү";
|
|
27
|
+
if (msg.includes("token has expired"))
|
|
28
|
+
return "Холбоос хугацаа дууссан байна. Дахин оролдоно уу";
|
|
29
|
+
return error.message;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function isRLSError(error: PostgrestError): boolean {
|
|
33
|
+
return error.code === "42501";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function isUniqueViolation(error: PostgrestError): boolean {
|
|
37
|
+
return error.code === "23505";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function isForeignKeyViolation(error: PostgrestError): boolean {
|
|
41
|
+
return error.code === "23503";
|
|
42
|
+
}
|
package/src/index.ts
ADDED
package/src/query.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
+
|
|
3
|
+
export interface ListOptions {
|
|
4
|
+
/** Column to order by (default: "created_at") */
|
|
5
|
+
orderBy?: string;
|
|
6
|
+
ascending?: boolean;
|
|
7
|
+
/** Supabase .range() args — use paginate() from @zer/core */
|
|
8
|
+
from?: number;
|
|
9
|
+
to?: number;
|
|
10
|
+
/** Column equality filters, e.g. { org_id: "abc", status: "active" } */
|
|
11
|
+
filters?: Record<string, unknown>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface QueryResult<T> {
|
|
15
|
+
data: T[];
|
|
16
|
+
count: number | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Generic CRUD factory — pass your Supabase client + table name, get typed list/get/create/update/remove.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* const products = createSimpleQuery<Product>(supabase, "products");
|
|
24
|
+
* const { data } = await products.list({ filters: { org_id: orgId } });
|
|
25
|
+
*/
|
|
26
|
+
export function createSimpleQuery<T extends Record<string, unknown>>(
|
|
27
|
+
supabase: SupabaseClient,
|
|
28
|
+
table: string,
|
|
29
|
+
) {
|
|
30
|
+
return {
|
|
31
|
+
async list(opts: ListOptions = {}): Promise<QueryResult<T>> {
|
|
32
|
+
const {
|
|
33
|
+
orderBy = "created_at",
|
|
34
|
+
ascending = false,
|
|
35
|
+
from,
|
|
36
|
+
to,
|
|
37
|
+
filters,
|
|
38
|
+
} = opts;
|
|
39
|
+
|
|
40
|
+
let q = supabase
|
|
41
|
+
.from(table)
|
|
42
|
+
.select("*", { count: "exact" })
|
|
43
|
+
.order(orderBy, { ascending });
|
|
44
|
+
|
|
45
|
+
if (filters) {
|
|
46
|
+
for (const [col, val] of Object.entries(filters)) {
|
|
47
|
+
if (val !== undefined && val !== null) {
|
|
48
|
+
q = q.eq(col, val);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (from !== undefined && to !== undefined) {
|
|
54
|
+
q = q.range(from, to);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const { data, error, count } = await q;
|
|
58
|
+
if (error) throw error;
|
|
59
|
+
return { data: (data ?? []) as T[], count };
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
async getById(id: string): Promise<T | null> {
|
|
63
|
+
const { data, error } = await supabase
|
|
64
|
+
.from(table)
|
|
65
|
+
.select("*")
|
|
66
|
+
.eq("id", id)
|
|
67
|
+
.single();
|
|
68
|
+
if (error) {
|
|
69
|
+
if (error.code === "PGRST116") return null;
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
return data as T;
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
async create(
|
|
76
|
+
record: Omit<T, "id" | "created_at" | "updated_at">,
|
|
77
|
+
): Promise<T> {
|
|
78
|
+
const { data, error } = await supabase
|
|
79
|
+
.from(table)
|
|
80
|
+
// biome-ignore lint/suspicious/noExplicitAny: Supabase generic mismatch with Omit<T,...>
|
|
81
|
+
.insert(record as any)
|
|
82
|
+
.select()
|
|
83
|
+
.single();
|
|
84
|
+
if (error) throw error;
|
|
85
|
+
return data as T;
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
async update(
|
|
89
|
+
id: string,
|
|
90
|
+
record: Partial<Omit<T, "id" | "created_at">>,
|
|
91
|
+
): Promise<T> {
|
|
92
|
+
const { data, error } = await supabase
|
|
93
|
+
.from(table)
|
|
94
|
+
// biome-ignore lint/suspicious/noExplicitAny: Supabase generic mismatch with Partial<Omit<T,...>>
|
|
95
|
+
.update(record as any)
|
|
96
|
+
.eq("id", id)
|
|
97
|
+
.select()
|
|
98
|
+
.single();
|
|
99
|
+
if (error) throw error;
|
|
100
|
+
return data as T;
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
async remove(id: string): Promise<void> {
|
|
104
|
+
const { error } = await supabase.from(table).delete().eq("id", id);
|
|
105
|
+
if (error) throw error;
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { GetObjectCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
|
2
|
+
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Cloudflare R2 client — S3-compatible object storage with zero egress fees.
|
|
6
|
+
*
|
|
7
|
+
* Env vars required:
|
|
8
|
+
* R2_ACCOUNT_ID — Cloudflare account ID
|
|
9
|
+
* R2_ACCESS_KEY_ID — R2 API token access key ID
|
|
10
|
+
* R2_SECRET_ACCESS_KEY — R2 API token secret
|
|
11
|
+
* R2_BUCKET — Default bucket name (optional, can override per call)
|
|
12
|
+
* R2_PUBLIC_DOMAIN — Custom domain or r2.dev pub token (optional)
|
|
13
|
+
*/
|
|
14
|
+
function getR2Client(): S3Client {
|
|
15
|
+
const accountId = process.env.R2_ACCOUNT_ID;
|
|
16
|
+
const accessKeyId = process.env.R2_ACCESS_KEY_ID;
|
|
17
|
+
const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;
|
|
18
|
+
|
|
19
|
+
if (!accountId || !accessKeyId || !secretAccessKey) {
|
|
20
|
+
throw new Error(
|
|
21
|
+
"R2 not configured. Set R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, and R2_SECRET_ACCESS_KEY.",
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return new S3Client({
|
|
26
|
+
region: "auto",
|
|
27
|
+
endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
|
|
28
|
+
credentials: { accessKeyId, secretAccessKey },
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function getDefaultBucket(): string {
|
|
33
|
+
const bucket = process.env.R2_BUCKET;
|
|
34
|
+
if (!bucket) throw new Error("R2_BUCKET not configured.");
|
|
35
|
+
return bucket;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Upload a file to R2 and return its public URL.
|
|
40
|
+
*/
|
|
41
|
+
export async function uploadToR2(
|
|
42
|
+
key: string,
|
|
43
|
+
body: Buffer | Uint8Array | ReadableStream,
|
|
44
|
+
opts: { bucket?: string; contentType?: string } = {},
|
|
45
|
+
): Promise<string> {
|
|
46
|
+
const client = getR2Client();
|
|
47
|
+
const bucket = opts.bucket ?? getDefaultBucket();
|
|
48
|
+
|
|
49
|
+
await client.send(
|
|
50
|
+
new PutObjectCommand({
|
|
51
|
+
Bucket: bucket,
|
|
52
|
+
Key: key,
|
|
53
|
+
Body: body,
|
|
54
|
+
ContentType: opts.contentType,
|
|
55
|
+
}),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
return getR2PublicUrl(key, bucket);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Generate a presigned URL for reading a private file (expires in seconds).
|
|
63
|
+
*/
|
|
64
|
+
export async function getR2SignedUrl(
|
|
65
|
+
key: string,
|
|
66
|
+
opts: { bucket?: string; expiresIn?: number } = {},
|
|
67
|
+
): Promise<string> {
|
|
68
|
+
const client = getR2Client();
|
|
69
|
+
const bucket = opts.bucket ?? getDefaultBucket();
|
|
70
|
+
const expiresIn = opts.expiresIn ?? 3600;
|
|
71
|
+
|
|
72
|
+
const command = new GetObjectCommand({ Bucket: bucket, Key: key });
|
|
73
|
+
return getSignedUrl(client, command, { expiresIn });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Build a public URL for an R2 object.
|
|
78
|
+
* Uses R2_PUBLIC_DOMAIN env var if set, otherwise falls back to r2.dev.
|
|
79
|
+
*/
|
|
80
|
+
export function getR2PublicUrl(key: string, bucket?: string): string {
|
|
81
|
+
const publicDomain = process.env.R2_PUBLIC_DOMAIN;
|
|
82
|
+
if (publicDomain) {
|
|
83
|
+
return `https://${publicDomain}/${key}`;
|
|
84
|
+
}
|
|
85
|
+
const b = bucket ?? getDefaultBucket();
|
|
86
|
+
// R2 dev subdomain pattern: pub-<token>.r2.dev/<key>
|
|
87
|
+
// User should set R2_PUBLIC_DOMAIN for production
|
|
88
|
+
return `https://${b}.r2.dev/${key}`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Build a deterministic storage path: `{prefix}/{uuid}.{ext}`
|
|
93
|
+
*/
|
|
94
|
+
export function buildR2Path(prefix: string, filename: string): string {
|
|
95
|
+
const ext = filename.split(".").pop() ?? "bin";
|
|
96
|
+
const uuid = crypto.randomUUID();
|
|
97
|
+
return `${prefix}/${uuid}.${ext}`;
|
|
98
|
+
}
|
package/src/storage.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
2
|
+
|
|
3
|
+
export interface UploadOptions {
|
|
4
|
+
/** Replace existing file at path (default: true) */
|
|
5
|
+
upsert?: boolean;
|
|
6
|
+
contentType?: string;
|
|
7
|
+
/** Cache-Control header (default: "3600") */
|
|
8
|
+
cacheControl?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Upload a file and return its public URL.
|
|
13
|
+
* Works in browser, React Native (use FormData/Blob), and Node (use Buffer/ArrayBuffer).
|
|
14
|
+
*/
|
|
15
|
+
export async function uploadFile(
|
|
16
|
+
supabase: SupabaseClient,
|
|
17
|
+
bucket: string,
|
|
18
|
+
path: string,
|
|
19
|
+
file: File | Blob | ArrayBuffer | FormData,
|
|
20
|
+
opts: UploadOptions = {},
|
|
21
|
+
): Promise<string> {
|
|
22
|
+
const { upsert = true, contentType, cacheControl = "3600" } = opts;
|
|
23
|
+
|
|
24
|
+
const { error } = await supabase.storage.from(bucket).upload(path, file, {
|
|
25
|
+
upsert,
|
|
26
|
+
contentType,
|
|
27
|
+
cacheControl,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
if (error) throw error;
|
|
31
|
+
|
|
32
|
+
const {
|
|
33
|
+
data: { publicUrl },
|
|
34
|
+
} = supabase.storage.from(bucket).getPublicUrl(path);
|
|
35
|
+
|
|
36
|
+
return publicUrl;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Remove one or more files from a bucket. */
|
|
40
|
+
export async function removeFiles(
|
|
41
|
+
supabase: SupabaseClient,
|
|
42
|
+
bucket: string,
|
|
43
|
+
paths: string[],
|
|
44
|
+
): Promise<void> {
|
|
45
|
+
const { error } = await supabase.storage.from(bucket).remove(paths);
|
|
46
|
+
if (error) throw error;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Get a signed (temporary) URL for a private file. */
|
|
50
|
+
export async function getSignedUrl(
|
|
51
|
+
supabase: SupabaseClient,
|
|
52
|
+
bucket: string,
|
|
53
|
+
path: string,
|
|
54
|
+
expiresInSeconds = 3600,
|
|
55
|
+
): Promise<string> {
|
|
56
|
+
const { data, error } = await supabase.storage
|
|
57
|
+
.from(bucket)
|
|
58
|
+
.createSignedUrl(path, expiresInSeconds);
|
|
59
|
+
if (error) throw error;
|
|
60
|
+
return data.signedUrl;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Build a deterministic storage path: `{prefix}/{uuid}.{ext}` */
|
|
64
|
+
export function buildStoragePath(prefix: string, filename: string): string {
|
|
65
|
+
const ext = filename.split(".").pop() ?? "bin";
|
|
66
|
+
const uuid = crypto.randomUUID();
|
|
67
|
+
return `${prefix}/${uuid}.${ext}`;
|
|
68
|
+
}
|
package/src/turnstile.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validate a Cloudflare Turnstile token server-side.
|
|
3
|
+
* Call this in server actions / API routes after the client submits the form.
|
|
4
|
+
*
|
|
5
|
+
* @param token - The `cf-turnstile-response` value from the hidden form field
|
|
6
|
+
* @param remoteIp - Optional: the user's IP for extra validation
|
|
7
|
+
* @returns `{ success: true }` or `{ success: false, error: string }`
|
|
8
|
+
*/
|
|
9
|
+
export async function validateTurnstile(
|
|
10
|
+
token: string | null | undefined,
|
|
11
|
+
remoteIp?: string,
|
|
12
|
+
): Promise<{ success: boolean; error?: string }> {
|
|
13
|
+
// Always skip in development — the widget isn't rendered there
|
|
14
|
+
if (process.env.NODE_ENV === "development") {
|
|
15
|
+
return { success: true };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const secretKey = process.env.CLOUDFLARE_TURNSTILE_SECRET_KEY;
|
|
19
|
+
if (!secretKey) {
|
|
20
|
+
if (!token) {
|
|
21
|
+
return { success: false, error: "Missing Turnstile token" };
|
|
22
|
+
}
|
|
23
|
+
return { success: false, error: "Bot protection not configured" };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (!token) {
|
|
27
|
+
return { success: false, error: "Missing Turnstile token" };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const formData = new URLSearchParams();
|
|
31
|
+
formData.append("secret", secretKey);
|
|
32
|
+
formData.append("response", token);
|
|
33
|
+
if (remoteIp) {
|
|
34
|
+
formData.append("remoteip", remoteIp);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
const res = await fetch(
|
|
39
|
+
"https://challenges.cloudflare.com/turnstile/v0/siteverify",
|
|
40
|
+
{
|
|
41
|
+
method: "POST",
|
|
42
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
43
|
+
body: formData.toString(),
|
|
44
|
+
},
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
const result = (await res.json()) as {
|
|
48
|
+
success: boolean;
|
|
49
|
+
"error-codes"?: string[];
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
if (!result.success) {
|
|
53
|
+
return { success: false, error: "Bot verification failed" };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return { success: true };
|
|
57
|
+
} catch {
|
|
58
|
+
// Fail open on network errors to avoid locking out users
|
|
59
|
+
return { success: true };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batch upsert helper — reliable bulk operations with chunking,
|
|
3
|
+
* conflict handling, and per-row error visibility.
|
|
4
|
+
*
|
|
5
|
+
* Supabase pitfalls it addresses:
|
|
6
|
+
* - Missing UNIQUE constraint → upsert silently inserts duplicates
|
|
7
|
+
* (throws here instead of silently corrupting data)
|
|
8
|
+
* - Oversized batches → auto-chunks into safe request sizes
|
|
9
|
+
* - Immutable field reset → use checkThenUpsert to preserve fields
|
|
10
|
+
* during recalculation operations
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const DEFAULT_CHUNK_SIZE = 50;
|
|
14
|
+
|
|
15
|
+
export interface BatchUpsertOptions {
|
|
16
|
+
/** Column(s) for ON CONFLICT resolution (required for upsert) */
|
|
17
|
+
onConflict?: string;
|
|
18
|
+
/** Ignore duplicate rows instead of updating them */
|
|
19
|
+
ignoreDuplicates?: boolean;
|
|
20
|
+
/** Max rows per API call (default: 50) */
|
|
21
|
+
chunkSize?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface BatchResult {
|
|
25
|
+
inserted: number;
|
|
26
|
+
errors: Array<{ index: number; row: unknown; error: string }>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function chunkArray<T>(arr: T[], size: number): T[][] {
|
|
30
|
+
const chunks: T[][] = [];
|
|
31
|
+
for (let i = 0; i < arr.length; i += size) {
|
|
32
|
+
chunks.push(arr.slice(i, i + size));
|
|
33
|
+
}
|
|
34
|
+
return chunks;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Upserts rows in chunks, collecting per-row errors so a partial
|
|
39
|
+
* failure doesn't lose the entire batch.
|
|
40
|
+
*
|
|
41
|
+
* Requires `onConflict` to be set (throws if omitted) — this prevents
|
|
42
|
+
* the silent duplicate-insertion pitfall.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* const result = await batchUpsert(
|
|
46
|
+
* supabase,
|
|
47
|
+
* "inventory_movements",
|
|
48
|
+
* movements,
|
|
49
|
+
* { onConflict: "id" },
|
|
50
|
+
* );
|
|
51
|
+
*/
|
|
52
|
+
export async function batchUpsert<T extends Record<string, unknown>>(
|
|
53
|
+
supabase: { from: (table: string) => any },
|
|
54
|
+
table: string,
|
|
55
|
+
rows: T[],
|
|
56
|
+
options?: BatchUpsertOptions,
|
|
57
|
+
): Promise<BatchResult> {
|
|
58
|
+
if (!options?.onConflict) {
|
|
59
|
+
throw new Error(
|
|
60
|
+
"batchUpsert: `onConflict` is required. " +
|
|
61
|
+
"Without it, upsert silently inserts duplicates when the UNIQUE constraint is missing. " +
|
|
62
|
+
"Set onConflict to the column(s) that define uniqueness for this table.",
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (rows.length === 0) {
|
|
67
|
+
return { inserted: 0, errors: [] };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const chunkSize = options?.chunkSize ?? DEFAULT_CHUNK_SIZE;
|
|
71
|
+
const chunks = chunkArray(rows, chunkSize);
|
|
72
|
+
let inserted = 0;
|
|
73
|
+
const errors: BatchResult["errors"] = [];
|
|
74
|
+
|
|
75
|
+
for (const chunk of chunks) {
|
|
76
|
+
try {
|
|
77
|
+
const query = supabase
|
|
78
|
+
.from(table)
|
|
79
|
+
.upsert(chunk, {
|
|
80
|
+
onConflict: options.onConflict,
|
|
81
|
+
ignoreDuplicates: options.ignoreDuplicates ?? false,
|
|
82
|
+
})
|
|
83
|
+
.select();
|
|
84
|
+
|
|
85
|
+
const { error } = await query;
|
|
86
|
+
|
|
87
|
+
if (error) {
|
|
88
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
89
|
+
errors.push({
|
|
90
|
+
index: inserted + i,
|
|
91
|
+
row: chunk[i],
|
|
92
|
+
error: error.message,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
} else {
|
|
96
|
+
inserted += chunk.length;
|
|
97
|
+
}
|
|
98
|
+
} catch (err) {
|
|
99
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
100
|
+
for (let i = 0; i < chunk.length; i++) {
|
|
101
|
+
errors.push({
|
|
102
|
+
index: inserted + i,
|
|
103
|
+
row: chunk[i],
|
|
104
|
+
error: message,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return { inserted, errors };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Check-then-upsert pattern for recalculation operations where
|
|
115
|
+
* certain fields (status, immutable timestamps) must be preserved.
|
|
116
|
+
*
|
|
117
|
+
* Reads existing rows matching the conflict keys, merges the incoming
|
|
118
|
+
* data with preserved fields, then upserts.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* const result = await checkThenUpsert(
|
|
122
|
+
* supabase,
|
|
123
|
+
* "payroll_records",
|
|
124
|
+
* recalculatedRows,
|
|
125
|
+
* { onConflict: "id", preserve: ["status", "paid_at"] },
|
|
126
|
+
* );
|
|
127
|
+
*/
|
|
128
|
+
export async function checkThenUpsert<T extends Record<string, unknown>>(
|
|
129
|
+
supabase: { from: (table: string) => any },
|
|
130
|
+
table: string,
|
|
131
|
+
rows: T[],
|
|
132
|
+
options: BatchUpsertOptions & {
|
|
133
|
+
/** Fields to preserve from existing rows instead of overwriting */
|
|
134
|
+
preserve: string[];
|
|
135
|
+
/** Column to use for querying existing rows (default: "id") */
|
|
136
|
+
lookupKey?: string;
|
|
137
|
+
},
|
|
138
|
+
): Promise<BatchResult> {
|
|
139
|
+
const lookupKey = options.lookupKey ?? "id";
|
|
140
|
+
const ids = rows
|
|
141
|
+
.map((r) => r[lookupKey])
|
|
142
|
+
.filter((id): id is string | number => id != null);
|
|
143
|
+
|
|
144
|
+
const existingMap = new Map<string | number, Record<string, unknown>>();
|
|
145
|
+
if (ids.length > 0) {
|
|
146
|
+
const { data: existing } = await supabase
|
|
147
|
+
.from(table)
|
|
148
|
+
.select(`*`)
|
|
149
|
+
.in(lookupKey, ids);
|
|
150
|
+
|
|
151
|
+
if (existing) {
|
|
152
|
+
for (const row of existing) {
|
|
153
|
+
existingMap.set(row[lookupKey] as string | number, row);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const merged = rows.map((row) => {
|
|
159
|
+
const existing = existingMap.get(row[lookupKey] as string | number);
|
|
160
|
+
if (!existing) return row;
|
|
161
|
+
|
|
162
|
+
const result = { ...row } as Record<string, unknown>;
|
|
163
|
+
for (const field of options.preserve) {
|
|
164
|
+
if (field in existing) {
|
|
165
|
+
result[field] = existing[field];
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return result as T;
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
return batchUpsert(supabase, table, merged, options);
|
|
172
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conditionally applies a branch_id filter to any Supabase query builder.
|
|
3
|
+
* Handles the `"all"` sentinel internally — treats it the same as
|
|
4
|
+
* `null`/`undefined` (no-op). Callers never need to normalize `"all"`
|
|
5
|
+
* before calling this function.
|
|
6
|
+
*
|
|
7
|
+
* @param query - Any Supabase query builder
|
|
8
|
+
* @param branchId - Branch ID to filter by, or `"all"`/`null`/`undefined` for no filter
|
|
9
|
+
* @returns The same query (possibly with `.eq("branch_id", branchId)` applied)
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const { data } = await withBranchFilter(
|
|
13
|
+
* supabase.from("work_orders").select("id").eq("organization_id", orgId),
|
|
14
|
+
* branchId,
|
|
15
|
+
* );
|
|
16
|
+
*/
|
|
17
|
+
export function withBranchFilter<T>(query: T, branchId?: string | null): T {
|
|
18
|
+
if (!branchId || branchId === "all") return query;
|
|
19
|
+
return (query as any).eq("branch_id", branchId) as T;
|
|
20
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Applies an organization_id filter to any Supabase query builder.
|
|
3
|
+
*
|
|
4
|
+
* Safe to chain — no-op when orgId is empty/null.
|
|
5
|
+
*
|
|
6
|
+
* @param query - Any Supabase query builder
|
|
7
|
+
* @param orgId - Organization ID to filter by (empty/null skips the filter)
|
|
8
|
+
* @returns The same query with `.eq("organization_id", orgId)` applied
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* const { data } = await withOrgScope(
|
|
12
|
+
* supabase.from("work_orders").select("*"),
|
|
13
|
+
* orgId,
|
|
14
|
+
* );
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* // Chained with withBranchFilter
|
|
18
|
+
* const q = withOrgScope(supabase.from("work_orders").select("*"), orgId);
|
|
19
|
+
* const { data } = await withBranchFilter(q, branchId);
|
|
20
|
+
*/
|
|
21
|
+
export function withOrgScope<T>(query: T, orgId?: string | null): T {
|
|
22
|
+
if (!orgId) return query;
|
|
23
|
+
return (query as any).eq("organization_id", orgId) as T;
|
|
24
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Applies pagination (range/limit) to any Supabase query builder.
|
|
3
|
+
*
|
|
4
|
+
* @param query - Any Supabase query builder
|
|
5
|
+
* @param page - 1-based page number (default: 1)
|
|
6
|
+
* @param pageSize - Items per page (default: 20, max: 1000)
|
|
7
|
+
* @returns The same query with `.range()` applied
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const { data } = await withPagination(
|
|
11
|
+
* supabase.from("work_orders").select("*").eq("organization_id", orgId),
|
|
12
|
+
* 2, // page
|
|
13
|
+
* 25, // pageSize
|
|
14
|
+
* );
|
|
15
|
+
*/
|
|
16
|
+
export function withPagination<T>(
|
|
17
|
+
query: T,
|
|
18
|
+
page?: number,
|
|
19
|
+
pageSize?: number,
|
|
20
|
+
): T {
|
|
21
|
+
const p = Math.max(1, page ?? 1);
|
|
22
|
+
const ps = Math.min(Math.max(1, pageSize ?? 20), 1000);
|
|
23
|
+
const from = (p - 1) * ps;
|
|
24
|
+
const to = from + ps - 1;
|
|
25
|
+
return (query as any).range(from, to) as T;
|
|
26
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare Workers AI client — free edge inference (10K Neurons/day).
|
|
3
|
+
*
|
|
4
|
+
* Env vars required:
|
|
5
|
+
* CF_ACCOUNT_ID — Cloudflare account ID
|
|
6
|
+
* CF_AI_API_TOKEN — API token with Workers AI:Read permission
|
|
7
|
+
*
|
|
8
|
+
* Available models (examples):
|
|
9
|
+
* Text: @cf/meta/llama-3.1-8b-instruct-fp8-fast
|
|
10
|
+
* Embedding: @cf/baai/bge-base-en-v1.5
|
|
11
|
+
* Image: @cf/black-forest-labs/FLUX-1-schnell
|
|
12
|
+
* Audio: @cf/openai/whisper
|
|
13
|
+
*
|
|
14
|
+
* Full catalog: https://developers.cloudflare.com/workers-ai/models/
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
interface WorkersAIConfig {
|
|
18
|
+
accountId?: string;
|
|
19
|
+
apiToken?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface ChatMessage {
|
|
23
|
+
role: "system" | "user" | "assistant";
|
|
24
|
+
content: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface ChatCompletionResponse {
|
|
28
|
+
result: { response: string };
|
|
29
|
+
success: boolean;
|
|
30
|
+
errors: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface StreamChunk {
|
|
34
|
+
response?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function getConfig(): Required<WorkersAIConfig> {
|
|
38
|
+
const accountId = process.env.CF_ACCOUNT_ID;
|
|
39
|
+
const apiToken = process.env.CF_AI_API_TOKEN;
|
|
40
|
+
|
|
41
|
+
if (!accountId || !apiToken) {
|
|
42
|
+
throw new Error("Workers AI not configured. Set CF_ACCOUNT_ID and CF_AI_API_TOKEN.");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return { accountId, apiToken };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Run a non-streaming text completion.
|
|
50
|
+
*/
|
|
51
|
+
export async function workersAIComplete(
|
|
52
|
+
model: string,
|
|
53
|
+
messages: ChatMessage[],
|
|
54
|
+
): Promise<string> {
|
|
55
|
+
const { accountId, apiToken } = getConfig();
|
|
56
|
+
|
|
57
|
+
const res = await fetch(
|
|
58
|
+
`https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${model}`,
|
|
59
|
+
{
|
|
60
|
+
method: "POST",
|
|
61
|
+
headers: {
|
|
62
|
+
Authorization: `Bearer ${apiToken}`,
|
|
63
|
+
"Content-Type": "application/json",
|
|
64
|
+
},
|
|
65
|
+
body: JSON.stringify({ messages }),
|
|
66
|
+
},
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
if (!res.ok) {
|
|
70
|
+
const text = await res.text();
|
|
71
|
+
throw new Error(`Workers AI error ${res.status}: ${text}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const data = (await res.json()) as ChatCompletionResponse;
|
|
75
|
+
if (!data.success) {
|
|
76
|
+
throw new Error(`Workers AI failed: ${data.errors.join(", ")}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return data.result.response;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Run a streaming text completion — returns an async iterable of text chunks.
|
|
84
|
+
*/
|
|
85
|
+
export async function workersAIStream(
|
|
86
|
+
model: string,
|
|
87
|
+
messages: ChatMessage[],
|
|
88
|
+
): Promise<ReadableStream<string>> {
|
|
89
|
+
const { accountId, apiToken } = getConfig();
|
|
90
|
+
|
|
91
|
+
const res = await fetch(
|
|
92
|
+
`https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${model}`,
|
|
93
|
+
{
|
|
94
|
+
method: "POST",
|
|
95
|
+
headers: {
|
|
96
|
+
Authorization: `Bearer ${apiToken}`,
|
|
97
|
+
"Content-Type": "application/json",
|
|
98
|
+
},
|
|
99
|
+
body: JSON.stringify({ messages, stream: true }),
|
|
100
|
+
},
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
if (!res.ok) {
|
|
104
|
+
const text = await res.text();
|
|
105
|
+
throw new Error(`Workers AI error ${res.status}: ${text}`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const reader = res.body!.getReader();
|
|
109
|
+
const decoder = new TextDecoder();
|
|
110
|
+
|
|
111
|
+
return new ReadableStream({
|
|
112
|
+
async pull(controller) {
|
|
113
|
+
const { done, value } = await reader.read();
|
|
114
|
+
if (done) {
|
|
115
|
+
controller.close();
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const text = decoder.decode(value, { stream: true });
|
|
120
|
+
// NDJSON: each line is a JSON object
|
|
121
|
+
for (const line of text.split("\n")) {
|
|
122
|
+
if (!line.trim()) continue;
|
|
123
|
+
try {
|
|
124
|
+
const chunk = JSON.parse(line) as StreamChunk;
|
|
125
|
+
if (chunk.response) {
|
|
126
|
+
controller.enqueue(chunk.response);
|
|
127
|
+
}
|
|
128
|
+
} catch {
|
|
129
|
+
// skip malformed lines
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Generate embeddings for text (useful for semantic search).
|
|
138
|
+
*/
|
|
139
|
+
export async function workersAIEmbed(
|
|
140
|
+
model: string,
|
|
141
|
+
texts: string[],
|
|
142
|
+
): Promise<number[][]> {
|
|
143
|
+
const { accountId, apiToken } = getConfig();
|
|
144
|
+
|
|
145
|
+
const res = await fetch(
|
|
146
|
+
`https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/${model}`,
|
|
147
|
+
{
|
|
148
|
+
method: "POST",
|
|
149
|
+
headers: {
|
|
150
|
+
Authorization: `Bearer ${apiToken}`,
|
|
151
|
+
"Content-Type": "application/json",
|
|
152
|
+
},
|
|
153
|
+
body: JSON.stringify({ text: texts }),
|
|
154
|
+
},
|
|
155
|
+
);
|
|
156
|
+
|
|
157
|
+
if (!res.ok) {
|
|
158
|
+
const text = await res.text();
|
|
159
|
+
throw new Error(`Workers AI embed error ${res.status}: ${text}`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const data = (await res.json()) as {
|
|
163
|
+
result: { data: number[][] };
|
|
164
|
+
success: boolean;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
if (!data.success) {
|
|
168
|
+
throw new Error("Workers AI embedding failed");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return data.result.data;
|
|
172
|
+
}
|