@zuiio/supabase 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +21 -0
  2. package/dist/api-response.d.ts +25 -0
  3. package/dist/api-response.d.ts.map +1 -0
  4. package/{src/api-response.ts → dist/api-response.js} +8 -16
  5. package/dist/api-response.js.map +1 -0
  6. package/dist/auth.d.ts +27 -0
  7. package/dist/auth.d.ts.map +1 -0
  8. package/dist/auth.js +55 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/errors.d.ts +7 -0
  11. package/dist/errors.d.ts.map +1 -0
  12. package/dist/errors.js +36 -0
  13. package/dist/errors.js.map +1 -0
  14. package/dist/index.d.ts +7 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +7 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/query.d.ts +30 -0
  19. package/dist/query.d.ts.map +1 -0
  20. package/dist/query.js +74 -0
  21. package/dist/query.js.map +1 -0
  22. package/dist/r2-storage.d.ts +24 -0
  23. package/dist/r2-storage.d.ts.map +1 -0
  24. package/dist/r2-storage.js +78 -0
  25. package/dist/r2-storage.js.map +1 -0
  26. package/dist/storage.d.ts +20 -0
  27. package/dist/storage.d.ts.map +1 -0
  28. package/dist/storage.js +38 -0
  29. package/dist/storage.js.map +1 -0
  30. package/dist/turnstile.d.ts +13 -0
  31. package/dist/turnstile.d.ts.map +1 -0
  32. package/dist/turnstile.js +45 -0
  33. package/dist/turnstile.js.map +1 -0
  34. package/dist/with-batch.d.ts +69 -0
  35. package/dist/with-batch.d.ts.map +1 -0
  36. package/dist/with-batch.js +130 -0
  37. package/dist/with-batch.js.map +1 -0
  38. package/{src/with-org-branch-filter.ts → dist/with-org-branch-filter.d.ts} +2 -4
  39. package/dist/with-org-branch-filter.d.ts.map +1 -0
  40. package/dist/with-org-branch-filter.js +22 -0
  41. package/dist/with-org-branch-filter.js.map +1 -0
  42. package/{src/with-org-scope.ts → dist/with-org-scope.d.ts} +2 -4
  43. package/dist/with-org-scope.d.ts.map +1 -0
  44. package/dist/with-org-scope.js +26 -0
  45. package/dist/with-org-scope.js.map +1 -0
  46. package/dist/with-pagination.d.ts +17 -0
  47. package/dist/with-pagination.d.ts.map +1 -0
  48. package/{src/with-pagination.ts → dist/with-pagination.js} +7 -10
  49. package/dist/with-pagination.js.map +1 -0
  50. package/dist/workers-ai.d.ts +33 -0
  51. package/dist/workers-ai.d.ts.map +1 -0
  52. package/dist/workers-ai.js +114 -0
  53. package/dist/workers-ai.js.map +1 -0
  54. package/package.json +54 -18
  55. package/AGENTS.md +0 -84
  56. package/src/auth.ts +0 -86
  57. package/src/errors.ts +0 -42
  58. package/src/index.ts +0 -7
  59. package/src/query.ts +0 -108
  60. package/src/r2-storage.ts +0 -98
  61. package/src/storage.ts +0 -68
  62. package/src/turnstile.ts +0 -61
  63. package/src/with-batch.ts +0 -172
  64. package/src/workers-ai.ts +0 -172
  65. package/tsconfig.json +0 -7
package/src/with-batch.ts DELETED
@@ -1,172 +0,0 @@
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
- }
package/src/workers-ai.ts DELETED
@@ -1,172 +0,0 @@
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
- }
package/tsconfig.json DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "extends": "../config/tsconfig.base.json",
3
- "compilerOptions": {
4
- "outDir": "./dist"
5
- },
6
- "include": ["src"]
7
- }