clefbase 1.4.1 → 1.5.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.
@@ -0,0 +1,209 @@
1
+ import { HttpClient } from "./http";
2
+ import type { FunctionRuntime, FunctionTrigger, FunctionTriggerType, FunctionDef, FunctionExecution, FunctionsConfig, FunctionStats, DeployFunctionOptions, HttpsCallableResult } from "./types";
3
+ export type { FunctionRuntime, FunctionTrigger, FunctionTriggerType, FunctionDef, FunctionExecution, FunctionsConfig, FunctionStats, DeployFunctionOptions, HttpsCallableResult, };
4
+ /**
5
+ * Thrown by all Functions SDK methods when the server returns an error
6
+ * or the function itself errors / times out.
7
+ *
8
+ * @example
9
+ * import { FunctionsError } from "clefbase";
10
+ *
11
+ * try {
12
+ * const { data } = await fns.call("myFunction", payload);
13
+ * } catch (err) {
14
+ * if (err instanceof FunctionsError) {
15
+ * console.error("HTTP status:", err.httpStatus); // e.g. 500
16
+ * console.error("Message:", err.message);
17
+ * }
18
+ * }
19
+ */
20
+ export declare class FunctionsError extends Error {
21
+ /** HTTP status code returned by the server, if available */
22
+ readonly httpStatus?: number | undefined;
23
+ constructor(message: string,
24
+ /** HTTP status code returned by the server, if available */
25
+ httpStatus?: number | undefined);
26
+ }
27
+ /**
28
+ * Create a strongly-typed callable reference to an HTTP-triggered function.
29
+ * Store it once and call it as many times as needed.
30
+ *
31
+ * @example
32
+ * const add = httpsCallable<{ a: number; b: number }, { sum: number }>(fns, "addNumbers");
33
+ * const { data, durationMs } = await add({ a: 3, b: 4 });
34
+ * console.log(data.sum); // 7
35
+ * console.log(durationMs); // e.g. 42
36
+ */
37
+ export declare function httpsCallable<TInput = unknown, TOutput = unknown>(fns: ClefbaseFunctions, name: string): (data?: TInput) => Promise<HttpsCallableResult<TOutput>>;
38
+ /**
39
+ * Call an HTTP-triggered function in one shot — no need to create a callable ref.
40
+ * Equivalent to `httpsCallable(fns, name)(data)`.
41
+ *
42
+ * @example
43
+ * const { data } = await callFunction(fns, "resizeImage", { url: "https://..." });
44
+ */
45
+ export declare function callFunction<TInput = unknown, TOutput = unknown>(fns: ClefbaseFunctions, name: string, data?: TInput): Promise<HttpsCallableResult<TOutput>>;
46
+ /**
47
+ * Deploy (or redeploy) a function from source code.
48
+ * Equivalent to `fns.deploy(options)`.
49
+ *
50
+ * @example
51
+ * await deployFunction(fns, {
52
+ * name: "greetUser",
53
+ * runtime: "node",
54
+ * trigger: { type: "http" },
55
+ * source: `export async function handler(ctx) { return { hi: ctx.data.name }; }`,
56
+ * });
57
+ */
58
+ export declare function deployFunction(fns: ClefbaseFunctions, options: DeployFunctionOptions): Promise<FunctionDef>;
59
+ /**
60
+ * Delete a deployed function by name.
61
+ * Equivalent to `fns.delete(name)`.
62
+ */
63
+ export declare function deleteFunction(fns: ClefbaseFunctions, name: string): Promise<{
64
+ deleted: boolean;
65
+ name: string;
66
+ }>;
67
+ /**
68
+ * List all functions deployed to this project.
69
+ * Equivalent to `fns.list()`.
70
+ */
71
+ export declare function listFunctions(fns: ClefbaseFunctions): Promise<FunctionDef[]>;
72
+ /**
73
+ * Fetch execution history for a function.
74
+ * Equivalent to `fns.executions(name, limit)`.
75
+ */
76
+ export declare function getFunctionExecutions(fns: ClefbaseFunctions, name: string, limit?: number): Promise<FunctionExecution[]>;
77
+ /**
78
+ * Attach a user auth token so that HTTP function calls include the caller's
79
+ * identity in `ctx.auth` inside the function.
80
+ *
81
+ * Obtain the token from `auth.signIn()` or `auth.signUp()`.
82
+ * Pass `null` to remove a previously set token (e.g. after sign-out).
83
+ *
84
+ * @example
85
+ * import { getAuth, getFunctions, setAuthToken, callFunction } from "clefbase";
86
+ *
87
+ * const auth = getAuth(app);
88
+ * const fns = getFunctions(app);
89
+ *
90
+ * const { token } = await auth.signIn("alice@example.com", "password123");
91
+ * setAuthToken(app, token);
92
+ *
93
+ * // ctx.auth.uid / ctx.auth.email are now available inside the function
94
+ * const { data } = await callFunction(fns, "getUserProfile");
95
+ *
96
+ * // On sign-out:
97
+ * await auth.signOut();
98
+ * setAuthToken(app, null);
99
+ */
100
+ export declare function setAuthToken(app: {
101
+ authToken?: string;
102
+ }, token: string | null): void;
103
+ /**
104
+ * Deploy a function from a source file on disk. **Node.js / CLI environments only.**
105
+ *
106
+ * Reads the file at `filePath` and calls `fns.deploy()` with the source.
107
+ * Runtime is NOT auto-detected from the file extension — pass it explicitly so
108
+ * you can deploy `.ts` files as Node.js without a separate transpile step.
109
+ *
110
+ * @example
111
+ * // Deploy a TypeScript file as a Node.js function
112
+ * await deployFromFile(fns, {
113
+ * name: "processOrder",
114
+ * runtime: "node",
115
+ * trigger: { type: "http" },
116
+ * filePath: "./src/functions/processOrder.ts",
117
+ * env: { STRIPE_KEY: process.env.STRIPE_KEY! },
118
+ * });
119
+ *
120
+ * // Deploy a Python file
121
+ * await deployFromFile(fns, {
122
+ * name: "analyzeSentiment",
123
+ * runtime: "python",
124
+ * trigger: { type: "http" },
125
+ * filePath: "./fns/analyze_sentiment.py",
126
+ * timeoutMs: 60_000,
127
+ * });
128
+ */
129
+ export declare function deployFromFile(fns: ClefbaseFunctions, options: Omit<DeployFunctionOptions, "source"> & {
130
+ filePath: string;
131
+ }): Promise<FunctionDef>;
132
+ /**
133
+ * Clefbase Functions service — obtained via `getFunctions(app)`.
134
+ *
135
+ * You can use instance methods directly OR the equivalent top-level
136
+ * convenience functions (`httpsCallable`, `callFunction`, `deployFunction`,
137
+ * `deployFromFile`, `setAuthToken`, etc.) — both styles are supported.
138
+ *
139
+ * @example
140
+ * import { initClefbase, getFunctions, httpsCallable, setAuthToken } from "clefbase";
141
+ *
142
+ * const app = initClefbase({ serverUrl, projectId, apiKey, adminSecret: "" });
143
+ * const fns = getFunctions(app);
144
+ *
145
+ * // ── Deploy ──────────────────────────────────────────────────────────────
146
+ * await fns.deploy({
147
+ * name: "greetUser",
148
+ * runtime: "node",
149
+ * trigger: { type: "http" },
150
+ * source: `export async function handler(ctx) { return { hi: ctx.data.name }; }`,
151
+ * });
152
+ *
153
+ * // ── Typed callable ──────────────────────────────────────────────────────
154
+ * const greet = httpsCallable<{ name: string }, { hi: string }>(fns, "greetUser");
155
+ * const { data } = await greet({ name: "Alice" });
156
+ *
157
+ * // ── Auth-aware call ─────────────────────────────────────────────────────
158
+ * const { token } = await getAuth(app).signIn("alice@example.com", "pw");
159
+ * setAuthToken(app, token);
160
+ * await fns.call("secureFunction"); // ctx.auth.uid is now set
161
+ */
162
+ export declare class ClefbaseFunctions {
163
+ private readonly _http;
164
+ /** @internal */
165
+ constructor(_http: HttpClient);
166
+ /**
167
+ * Initialise Functions for this project if not already done.
168
+ * `deploy()` calls this automatically, so you rarely need it directly.
169
+ */
170
+ initProject(opts?: {
171
+ maxConcurrentExecutions?: number;
172
+ defaultTimeoutMs?: number;
173
+ }): Promise<FunctionsConfig>;
174
+ /**
175
+ * Deploy (or redeploy) a function from source code.
176
+ *
177
+ * Redeploying with the same `name` updates the function in-place.
178
+ * Scheduled functions are re-armed with the new cron expression automatically.
179
+ */
180
+ deploy(options: DeployFunctionOptions): Promise<FunctionDef>;
181
+ /**
182
+ * List all functions deployed to this project.
183
+ * Source code is not included in the response.
184
+ */
185
+ list(): Promise<FunctionDef[]>;
186
+ /**
187
+ * Delete a deployed function by name.
188
+ * Scheduled functions are de-registered from the cron timer immediately.
189
+ */
190
+ delete(name: string): Promise<{
191
+ deleted: boolean;
192
+ name: string;
193
+ }>;
194
+ /**
195
+ * Call an HTTP-triggered function and return its result.
196
+ *
197
+ * Throws a `FunctionsError` on function error, timeout, or not-found.
198
+ * For a reusable typed reference, use `httpsCallable()` instead.
199
+ */
200
+ call<TInput = unknown, TOutput = unknown>(name: string, data?: TInput): Promise<HttpsCallableResult<TOutput>>;
201
+ /**
202
+ * Fetch execution history for a specific function.
203
+ *
204
+ * @param name Function name
205
+ * @param limit Max results to return (default: 20, max: 100)
206
+ */
207
+ executions(name: string, limit?: number): Promise<FunctionExecution[]>;
208
+ }
209
+ //# sourceMappingURL=functions.d.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AAC,WAAW,EAAE,CAAC;IAMpC;;;OAGG;IACG,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAQvE;;;;;OAKG;IACG,IAAI,CAAC,MAAM,GAAG,OAAO,EAAE,OAAO,GAAG,OAAO,EAC5C,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC;IAgBxC;;;;;OAKG;IACG,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,SAAK,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC;CAKzE"}
@@ -0,0 +1,307 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ClefbaseFunctions = exports.FunctionsError = void 0;
37
+ exports.httpsCallable = httpsCallable;
38
+ exports.callFunction = callFunction;
39
+ exports.deployFunction = deployFunction;
40
+ exports.deleteFunction = deleteFunction;
41
+ exports.listFunctions = listFunctions;
42
+ exports.getFunctionExecutions = getFunctionExecutions;
43
+ exports.setAuthToken = setAuthToken;
44
+ exports.deployFromFile = deployFromFile;
45
+ const types_1 = require("./types");
46
+ // ─── FunctionsError ───────────────────────────────────────────────────────────
47
+ /**
48
+ * Thrown by all Functions SDK methods when the server returns an error
49
+ * or the function itself errors / times out.
50
+ *
51
+ * @example
52
+ * import { FunctionsError } from "clefbase";
53
+ *
54
+ * try {
55
+ * const { data } = await fns.call("myFunction", payload);
56
+ * } catch (err) {
57
+ * if (err instanceof FunctionsError) {
58
+ * console.error("HTTP status:", err.httpStatus); // e.g. 500
59
+ * console.error("Message:", err.message);
60
+ * }
61
+ * }
62
+ */
63
+ class FunctionsError extends Error {
64
+ constructor(message,
65
+ /** HTTP status code returned by the server, if available */
66
+ httpStatus) {
67
+ super(message);
68
+ this.httpStatus = httpStatus;
69
+ this.name = "FunctionsError";
70
+ if (Error.captureStackTrace) {
71
+ Error.captureStackTrace(this, FunctionsError);
72
+ }
73
+ }
74
+ }
75
+ exports.FunctionsError = FunctionsError;
76
+ // ─── httpsCallable (top-level factory) ───────────────────────────────────────
77
+ /**
78
+ * Create a strongly-typed callable reference to an HTTP-triggered function.
79
+ * Store it once and call it as many times as needed.
80
+ *
81
+ * @example
82
+ * const add = httpsCallable<{ a: number; b: number }, { sum: number }>(fns, "addNumbers");
83
+ * const { data, durationMs } = await add({ a: 3, b: 4 });
84
+ * console.log(data.sum); // 7
85
+ * console.log(durationMs); // e.g. 42
86
+ */
87
+ function httpsCallable(fns, name) {
88
+ return (data) => fns.call(name, data);
89
+ }
90
+ // ─── callFunction ─────────────────────────────────────────────────────────────
91
+ /**
92
+ * Call an HTTP-triggered function in one shot — no need to create a callable ref.
93
+ * Equivalent to `httpsCallable(fns, name)(data)`.
94
+ *
95
+ * @example
96
+ * const { data } = await callFunction(fns, "resizeImage", { url: "https://..." });
97
+ */
98
+ async function callFunction(fns, name, data) {
99
+ return fns.call(name, data);
100
+ }
101
+ // ─── deployFunction ───────────────────────────────────────────────────────────
102
+ /**
103
+ * Deploy (or redeploy) a function from source code.
104
+ * Equivalent to `fns.deploy(options)`.
105
+ *
106
+ * @example
107
+ * await deployFunction(fns, {
108
+ * name: "greetUser",
109
+ * runtime: "node",
110
+ * trigger: { type: "http" },
111
+ * source: `export async function handler(ctx) { return { hi: ctx.data.name }; }`,
112
+ * });
113
+ */
114
+ async function deployFunction(fns, options) {
115
+ return fns.deploy(options);
116
+ }
117
+ // ─── deleteFunction ───────────────────────────────────────────────────────────
118
+ /**
119
+ * Delete a deployed function by name.
120
+ * Equivalent to `fns.delete(name)`.
121
+ */
122
+ async function deleteFunction(fns, name) {
123
+ return fns.delete(name);
124
+ }
125
+ // ─── listFunctions ────────────────────────────────────────────────────────────
126
+ /**
127
+ * List all functions deployed to this project.
128
+ * Equivalent to `fns.list()`.
129
+ */
130
+ async function listFunctions(fns) {
131
+ return fns.list();
132
+ }
133
+ // ─── getFunctionExecutions ────────────────────────────────────────────────────
134
+ /**
135
+ * Fetch execution history for a function.
136
+ * Equivalent to `fns.executions(name, limit)`.
137
+ */
138
+ async function getFunctionExecutions(fns, name, limit = 20) {
139
+ return fns.executions(name, limit);
140
+ }
141
+ // ─── setAuthToken ─────────────────────────────────────────────────────────────
142
+ /**
143
+ * Attach a user auth token so that HTTP function calls include the caller's
144
+ * identity in `ctx.auth` inside the function.
145
+ *
146
+ * Obtain the token from `auth.signIn()` or `auth.signUp()`.
147
+ * Pass `null` to remove a previously set token (e.g. after sign-out).
148
+ *
149
+ * @example
150
+ * import { getAuth, getFunctions, setAuthToken, callFunction } from "clefbase";
151
+ *
152
+ * const auth = getAuth(app);
153
+ * const fns = getFunctions(app);
154
+ *
155
+ * const { token } = await auth.signIn("alice@example.com", "password123");
156
+ * setAuthToken(app, token);
157
+ *
158
+ * // ctx.auth.uid / ctx.auth.email are now available inside the function
159
+ * const { data } = await callFunction(fns, "getUserProfile");
160
+ *
161
+ * // On sign-out:
162
+ * await auth.signOut();
163
+ * setAuthToken(app, null);
164
+ */
165
+ function setAuthToken(app, token) {
166
+ app.authToken = token ?? undefined;
167
+ }
168
+ // ─── deployFromFile ───────────────────────────────────────────────────────────
169
+ /**
170
+ * Deploy a function from a source file on disk. **Node.js / CLI environments only.**
171
+ *
172
+ * Reads the file at `filePath` and calls `fns.deploy()` with the source.
173
+ * Runtime is NOT auto-detected from the file extension — pass it explicitly so
174
+ * you can deploy `.ts` files as Node.js without a separate transpile step.
175
+ *
176
+ * @example
177
+ * // Deploy a TypeScript file as a Node.js function
178
+ * await deployFromFile(fns, {
179
+ * name: "processOrder",
180
+ * runtime: "node",
181
+ * trigger: { type: "http" },
182
+ * filePath: "./src/functions/processOrder.ts",
183
+ * env: { STRIPE_KEY: process.env.STRIPE_KEY! },
184
+ * });
185
+ *
186
+ * // Deploy a Python file
187
+ * await deployFromFile(fns, {
188
+ * name: "analyzeSentiment",
189
+ * runtime: "python",
190
+ * trigger: { type: "http" },
191
+ * filePath: "./fns/analyze_sentiment.py",
192
+ * timeoutMs: 60_000,
193
+ * });
194
+ */
195
+ async function deployFromFile(fns, options) {
196
+ let readFileSync;
197
+ try {
198
+ ({ readFileSync } = await Promise.resolve().then(() => __importStar(require("fs"))));
199
+ }
200
+ catch {
201
+ throw new FunctionsError("deployFromFile() requires Node.js — it cannot be called in a browser environment.");
202
+ }
203
+ const { filePath, ...rest } = options;
204
+ const source = readFileSync(filePath, "utf8");
205
+ return fns.deploy({ ...rest, source });
206
+ }
207
+ // ─── ClefbaseFunctions ────────────────────────────────────────────────────────
208
+ /**
209
+ * Clefbase Functions service — obtained via `getFunctions(app)`.
210
+ *
211
+ * You can use instance methods directly OR the equivalent top-level
212
+ * convenience functions (`httpsCallable`, `callFunction`, `deployFunction`,
213
+ * `deployFromFile`, `setAuthToken`, etc.) — both styles are supported.
214
+ *
215
+ * @example
216
+ * import { initClefbase, getFunctions, httpsCallable, setAuthToken } from "clefbase";
217
+ *
218
+ * const app = initClefbase({ serverUrl, projectId, apiKey, adminSecret: "" });
219
+ * const fns = getFunctions(app);
220
+ *
221
+ * // ── Deploy ──────────────────────────────────────────────────────────────
222
+ * await fns.deploy({
223
+ * name: "greetUser",
224
+ * runtime: "node",
225
+ * trigger: { type: "http" },
226
+ * source: `export async function handler(ctx) { return { hi: ctx.data.name }; }`,
227
+ * });
228
+ *
229
+ * // ── Typed callable ──────────────────────────────────────────────────────
230
+ * const greet = httpsCallable<{ name: string }, { hi: string }>(fns, "greetUser");
231
+ * const { data } = await greet({ name: "Alice" });
232
+ *
233
+ * // ── Auth-aware call ─────────────────────────────────────────────────────
234
+ * const { token } = await getAuth(app).signIn("alice@example.com", "pw");
235
+ * setAuthToken(app, token);
236
+ * await fns.call("secureFunction"); // ctx.auth.uid is now set
237
+ */
238
+ class ClefbaseFunctions {
239
+ /** @internal */
240
+ constructor(_http) {
241
+ this._http = _http;
242
+ }
243
+ // ─── initProject ──────────────────────────────────────────────────────────
244
+ /**
245
+ * Initialise Functions for this project if not already done.
246
+ * `deploy()` calls this automatically, so you rarely need it directly.
247
+ */
248
+ async initProject(opts) {
249
+ return this._http.post("/", opts ?? {});
250
+ }
251
+ // ─── deploy ───────────────────────────────────────────────────────────────
252
+ /**
253
+ * Deploy (or redeploy) a function from source code.
254
+ *
255
+ * Redeploying with the same `name` updates the function in-place.
256
+ * Scheduled functions are re-armed with the new cron expression automatically.
257
+ */
258
+ async deploy(options) {
259
+ return this._http.post("/deploy", options);
260
+ }
261
+ // ─── list ─────────────────────────────────────────────────────────────────
262
+ /**
263
+ * List all functions deployed to this project.
264
+ * Source code is not included in the response.
265
+ */
266
+ async list() {
267
+ return this._http.get("/");
268
+ }
269
+ // ─── delete ───────────────────────────────────────────────────────────────
270
+ /**
271
+ * Delete a deployed function by name.
272
+ * Scheduled functions are de-registered from the cron timer immediately.
273
+ */
274
+ async delete(name) {
275
+ return this._http.delete(`/${encodeURIComponent(name)}`);
276
+ }
277
+ // ─── call ─────────────────────────────────────────────────────────────────
278
+ /**
279
+ * Call an HTTP-triggered function and return its result.
280
+ *
281
+ * Throws a `FunctionsError` on function error, timeout, or not-found.
282
+ * For a reusable typed reference, use `httpsCallable()` instead.
283
+ */
284
+ async call(name, data) {
285
+ try {
286
+ return await this._http.post(`/call/${encodeURIComponent(name)}`, { data: data ?? null });
287
+ }
288
+ catch (err) {
289
+ if (err instanceof types_1.ClefbaseError) {
290
+ throw new FunctionsError(err.message, err.status);
291
+ }
292
+ throw err;
293
+ }
294
+ }
295
+ // ─── executions ───────────────────────────────────────────────────────────
296
+ /**
297
+ * Fetch execution history for a specific function.
298
+ *
299
+ * @param name Function name
300
+ * @param limit Max results to return (default: 20, max: 100)
301
+ */
302
+ async executions(name, limit = 20) {
303
+ return this._http.get(`/${encodeURIComponent(name)}/executions?limit=${Math.min(limit, 100)}`);
304
+ }
305
+ }
306
+ exports.ClefbaseFunctions = ClefbaseFunctions;
307
+ //# sourceMappingURL=functions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"functions.js","sourceRoot":"","sources":["../src/functions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,sCAKC;AAWD,oCAMC;AAgBD,wCAKC;AAQD,wCAKC;AAQD,sCAEC;AAQD,sDAMC;AA2BD,oCAEC;AA8BD,wCAeC;AA/ND,mCAAwC;AAyBxC,iFAAiF;AAEjF;;;;;;;;;;;;;;;GAeG;AACH,MAAa,cAAe,SAAQ,KAAK;IACvC,YACE,OAAe;IACf,4DAA4D;IAC5C,UAAmB;QAEn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IAAI;QACR,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAgB,GAAG,CAAC,CAAC;IAC5C,CAAC;IAED,6EAA6E;IAE7E;;;OAGG;IACH,KAAK,CAAC,MAAM,CAAC,IAAY;QACvB,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,CACtB,IAAI,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAC/B,CAAC;IACJ,CAAC;IAED,6EAA6E;IAE7E;;;;;OAKG;IACH,KAAK,CAAC,IAAI,CACR,IAAY,EACZ,IAAa;QAEb,IAAI,CAAC;YACH,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAC1B,SAAS,kBAAkB,CAAC,IAAI,CAAC,EAAE,EACnC,EAAE,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,CACvB,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,IAAI,GAAG,YAAY,qBAAa,EAAE,CAAC;gBACjC,MAAM,IAAI,cAAc,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;YACpD,CAAC;YACD,MAAM,GAAG,CAAC;QACZ,CAAC;IACH,CAAC;IAED,6EAA6E;IAE7E;;;;;OAKG;IACH,KAAK,CAAC,UAAU,CAAC,IAAY,EAAE,KAAK,GAAG,EAAE;QACvC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CACnB,IAAI,kBAAkB,CAAC,IAAI,CAAC,qBAAqB,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,CACxE,CAAC;IACJ,CAAC;CACF;AAxFD,8CAwFC"}
package/dist/index.d.ts CHANGED
@@ -2,43 +2,60 @@
2
2
  * clefbase — Firebase-style SDK for Clefbase / Cleforyx
3
3
  *
4
4
  * @example
5
- * import { initClefbase, getDatabase, getAuth, getStorage, getHosting, FieldValue } from "clefbase";
5
+ * import {
6
+ * initClefbase, getDatabase, getAuth, getStorage, getHosting,
7
+ * getFunctions, httpsCallable, callFunction, deployFunction, deployFromFile,
8
+ * setAuthToken, FunctionsError, FieldValue,
9
+ * } from "clefbase";
6
10
  *
7
- * const app = initClefbase({
8
- * serverUrl: "https://api.cleforyx.com",
9
- * projectId: "my_project_abc",
10
- * apiKey: "cfx_...",
11
- * adminSecret: "...", // only needed for hosting
12
- * });
11
+ * const app = initClefbase({ serverUrl, projectId, apiKey, adminSecret: "" });
12
+ * const fns = getFunctions(app);
13
+ * const auth = getAuth(app);
13
14
  *
14
- * const db = getDatabase(app);
15
+ * // ── Auth-aware function call ───────────────────────────────────────────────
16
+ * const { token } = await auth.signIn("alice@example.com", "password123");
17
+ * setAuthToken(app, token); // ctx.auth.uid / email now available in function
15
18
  *
16
- * // FieldValue sentinels
17
- * await db.collection("posts").doc("p1").update({
18
- * views: FieldValue.increment(1),
19
- * score: FieldValue.decrement(0.5),
20
- * publishedAt: FieldValue.serverTimestamp(),
21
- * draft: FieldValue.deleteField(),
22
- * tags: FieldValue.arrayUnion("featured"),
23
- * oldTags: FieldValue.arrayRemove("wip"),
24
- * });
19
+ * // ── Typed callable ────────────────────────────────────────────────────────
20
+ * const greet = httpsCallable<{ name: string }, { message: string }>(fns, "greetUser");
21
+ * const { data } = await greet({ name: "Alice" });
22
+ *
23
+ * // ── One-shot call ─────────────────────────────────────────────────────────
24
+ * const { data } = await callFunction(fns, "greetUser", { name: "Bob" });
25
25
  *
26
- * // Batch writes
27
- * const batch = db.batch();
28
- * batch.update(db.collection("counters").doc("hits"), { n: FieldValue.increment(1) });
29
- * batch.delete(db.collection("sessions").doc("expired"));
30
- * await batch.commit();
26
+ * // ── Deploy from source ────────────────────────────────────────────────────
27
+ * await deployFunction(fns, {
28
+ * name: "greetUser",
29
+ * runtime: "node",
30
+ * trigger: { type: "http" },
31
+ * source: `export async function handler(ctx) { return { message: "Hi " + ctx.data.name }; }`,
32
+ * });
31
33
  *
32
- * // Transactions
33
- * await db.runTransaction(async (tx) => {
34
- * const wallet = await tx.get(db.collection("wallets").doc(uid));
35
- * tx.update(db.collection("wallets").doc(uid), { balance: (wallet?.balance as number ?? 0) + 10 });
34
+ * // ── Deploy from file (Node.js) ────────────────────────────────────────────
35
+ * await deployFromFile(fns, {
36
+ * name: "processOrder",
37
+ * runtime: "node",
38
+ * trigger: { type: "http" },
39
+ * filePath: "./src/functions/processOrder.ts",
36
40
  * });
37
41
  *
38
- * // Collection-group queries
39
- * const allComments = await db.collectionGroup("comments").where({ approved: true }).getDocs();
42
+ * // ── Error handling ────────────────────────────────────────────────────────
43
+ * try {
44
+ * await callFunction(fns, "mayFail");
45
+ * } catch (err) {
46
+ * if (err instanceof FunctionsError) {
47
+ * console.error(err.httpStatus, err.message);
48
+ * }
49
+ * }
50
+ *
51
+ * // ── Database ──────────────────────────────────────────────────────────────
52
+ * const db = getDatabase(app);
53
+ * await db.collection("posts").doc("p1").update({
54
+ * views: FieldValue.increment(1),
55
+ * publishedAt: FieldValue.serverTimestamp(),
56
+ * });
40
57
  */
41
- export { ClefbaseApp, initClefbase, getApp, getDatabase, getAuth, getStorage, getHosting, } from "./app";
58
+ export { ClefbaseApp, initClefbase, getApp, getDatabase, getAuth, getStorage, getHosting, getFunctions, } from "./app";
42
59
  export { Database, CollectionReference, CollectionGroup, DocumentReference, Query, WriteBatch, Transaction, runTransaction, } from "./db";
43
60
  export { Auth } from "./auth";
44
61
  export type { GoogleButtonOptions } from "./auth";
@@ -48,6 +65,8 @@ export type { StorageImageStatus } from "./react/StorageImage";
48
65
  export { EmailVerificationCard } from "./react/EmailVerificationCard";
49
66
  export { ClefbaseHosting, SiteReference } from "./hosting";
50
67
  export type { HostingSite, HostingDeploy, HostingFile, DeployResult, DeployOptions, HostingStatus, DeployStatus, } from "./hosting";
68
+ export { ClefbaseFunctions, FunctionsError, httpsCallable, callFunction, deployFunction, deleteFunction, listFunctions, getFunctionExecutions, setAuthToken, deployFromFile, } from "./functions";
69
+ export type { FunctionRuntime, FunctionTrigger, FunctionTriggerType, FunctionDef, FunctionExecution, FunctionsConfig, FunctionStats, DeployFunctionOptions, HttpsCallableResult, } from "./functions";
51
70
  export { FieldValue, FieldValueSentinel } from "./field_value";
52
71
  export type { FieldValueType } from "./field_value";
53
72
  export type { ClefbaseConfig, ClefbaseDocument, QueryOptions, QueryResult, FilterOperator, WhereClause, WhereValue, AuthUser, AuthSession, AuthResult, } from "./types";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAGH,OAAO,EACL,WAAW,EACX,YAAY,EACZ,MAAM,EACN,WAAW,EACX,OAAO,EACP,UAAU,EACV,UAAU,GACX,MAAM,OAAO,CAAC;AAGf,OAAO,EACL,QAAQ,EACR,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EACjB,KAAK,EACL,UAAU,EACV,WAAW,EACX,cAAc,GACf,MAAM,MAAM,CAAC;AAGd,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,YAAY,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAGlD,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC/E,YAAY,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAQ7C,YAAY,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAEtE,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC3D,YAAY,EACV,WAAW,EACX,aAAa,EACb,WAAW,EACX,YAAY,EACZ,aAAa,EACb,aAAa,EACb,YAAY,GACb,MAAM,WAAW,CAAC;AAGnB,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAC/D,YAAY,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;A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