@blinkdotnew/dev-sdk 2.1.9 → 2.2.2

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/dist/index.js CHANGED
@@ -7,6 +7,33 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
7
7
  throw Error('Dynamic require of "' + x + '" is not supported');
8
8
  });
9
9
 
10
+ // ../core/src/platform.ts
11
+ function detectPlatform() {
12
+ if (typeof Deno !== "undefined") {
13
+ return "deno";
14
+ }
15
+ if (typeof process !== "undefined" && process.versions?.node) {
16
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
17
+ return "react-native";
18
+ }
19
+ return "node";
20
+ }
21
+ if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
22
+ return "react-native";
23
+ }
24
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
25
+ return "web";
26
+ }
27
+ return "node";
28
+ }
29
+ var platform = detectPlatform();
30
+ var isWeb = platform === "web";
31
+ var isReactNative = platform === "react-native";
32
+ var isNode = platform === "node";
33
+ var isDeno = platform === "deno";
34
+ var isBrowser = isWeb || isReactNative;
35
+ var isServer = isNode || isDeno;
36
+
10
37
  // ../core/src/storage-adapter.ts
11
38
  var WebStorageAdapter = class {
12
39
  getItem(key) {
@@ -92,6 +119,9 @@ var NoOpStorageAdapter = class {
92
119
  }
93
120
  };
94
121
  function getDefaultStorageAdapter() {
122
+ if (isDeno) {
123
+ return new NoOpStorageAdapter();
124
+ }
95
125
  if (typeof window !== "undefined" && typeof localStorage !== "undefined") {
96
126
  try {
97
127
  localStorage.setItem("__test__", "test");
@@ -103,28 +133,6 @@ function getDefaultStorageAdapter() {
103
133
  return new NoOpStorageAdapter();
104
134
  }
105
135
 
106
- // ../core/src/platform.ts
107
- function detectPlatform() {
108
- if (typeof process !== "undefined" && process.versions?.node) {
109
- if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
110
- return "react-native";
111
- }
112
- return "node";
113
- }
114
- if (typeof navigator !== "undefined" && navigator.product === "ReactNative") {
115
- return "react-native";
116
- }
117
- if (typeof window !== "undefined" && typeof document !== "undefined") {
118
- return "web";
119
- }
120
- return "node";
121
- }
122
- var platform = detectPlatform();
123
- var isWeb = platform === "web";
124
- var isReactNative = platform === "react-native";
125
- var isNode = platform === "node";
126
- var isBrowser = isWeb || isReactNative;
127
-
128
136
  // ../core/src/types.ts
129
137
  var BlinkError = class extends Error {
130
138
  constructor(message, code, status, details) {
@@ -388,17 +396,44 @@ function convertKeysToCamelCase(obj) {
388
396
  return converted;
389
397
  }
390
398
  var HttpClient = class {
391
- authUrl;
392
- coreUrl;
399
+ authUrl = "https://blink.new";
400
+ coreUrl = "https://core.blink.new";
393
401
  projectId;
402
+ publishableKey;
403
+ secretKey;
404
+ // Permanent, non-expiring key (like Stripe's sk_live_...)
394
405
  getToken;
395
406
  getValidToken;
396
407
  constructor(config, getToken, getValidToken) {
397
408
  this.projectId = config.projectId;
409
+ this.publishableKey = config.publishableKey;
410
+ this.secretKey = config.secretKey || config.serviceToken;
398
411
  this.getToken = getToken;
399
412
  this.getValidToken = getValidToken;
400
- this.authUrl = config.auth?.authUrl ?? "https://blink.new";
401
- this.coreUrl = config.auth?.coreUrl ?? "https://core.blink.new";
413
+ }
414
+ shouldAttachPublishableKey(path, method) {
415
+ if (method !== "GET" && method !== "POST") return false;
416
+ if (path.includes("/api/analytics/")) return true;
417
+ if (path.includes("/api/storage/")) return true;
418
+ if (path.includes("/api/db/") && path.includes("/rest/v1/")) return method === "GET";
419
+ return false;
420
+ }
421
+ shouldSkipSecretKey(url) {
422
+ try {
423
+ const parsed = new URL(url);
424
+ return parsed.hostname.endsWith(".functions.blink.new");
425
+ } catch {
426
+ return false;
427
+ }
428
+ }
429
+ getAuthorizationHeader(url, token) {
430
+ if (this.secretKey && !this.shouldSkipSecretKey(url)) {
431
+ return `Bearer ${this.secretKey}`;
432
+ }
433
+ if (token) {
434
+ return `Bearer ${token}`;
435
+ }
436
+ return null;
402
437
  }
403
438
  /**
404
439
  * Make an authenticated request to the Blink API
@@ -406,19 +441,23 @@ var HttpClient = class {
406
441
  async request(path, options = {}) {
407
442
  const url = this.buildUrl(path, options.searchParams);
408
443
  const token = this.getValidToken ? await this.getValidToken() : this.getToken();
444
+ const method = options.method || "GET";
409
445
  const headers = {
410
446
  "Content-Type": "application/json",
411
447
  ...options.headers
412
448
  };
413
- if (token) {
414
- headers.Authorization = `Bearer ${token}`;
449
+ const auth = this.getAuthorizationHeader(url, token);
450
+ if (auth) {
451
+ headers.Authorization = auth;
452
+ } else if (this.publishableKey && !headers["x-blink-publishable-key"] && this.shouldAttachPublishableKey(path, method)) {
453
+ headers["x-blink-publishable-key"] = this.publishableKey;
415
454
  }
416
455
  const requestInit = {
417
- method: options.method || "GET",
456
+ method,
418
457
  headers,
419
458
  signal: options.signal
420
459
  };
421
- if (options.body && options.method !== "GET") {
460
+ if (options.body && method !== "GET") {
422
461
  requestInit.body = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
423
462
  }
424
463
  try {
@@ -572,12 +611,12 @@ var HttpClient = class {
572
611
  throw new BlinkValidationError("Unsupported file type");
573
612
  }
574
613
  formData.append("path", filePath);
575
- if (options.upsert !== void 0) {
576
- formData.append("options", JSON.stringify({ upsert: options.upsert }));
577
- }
578
614
  const headers = {};
579
- if (token) {
580
- headers.Authorization = `Bearer ${token}`;
615
+ const auth = this.getAuthorizationHeader(url, token);
616
+ if (auth) {
617
+ headers.Authorization = auth;
618
+ } else if (this.publishableKey && path.includes("/api/storage/") && !headers["x-blink-publishable-key"]) {
619
+ headers["x-blink-publishable-key"] = this.publishableKey;
581
620
  }
582
621
  try {
583
622
  if (typeof XMLHttpRequest !== "undefined" && options.onProgress) {
@@ -678,7 +717,7 @@ var HttpClient = class {
678
717
  });
679
718
  }
680
719
  /**
681
- * Stream AI text generation with Vercel AI SDK data stream format
720
+ * Stream AI text generation - uses Vercel AI SDK's pipeUIMessageStreamToResponse (Data Stream Protocol)
682
721
  */
683
722
  async streamAiText(prompt, options = {}, onChunk) {
684
723
  const url = this.buildUrl(`/api/ai/${this.projectId}/text`);
@@ -686,9 +725,8 @@ var HttpClient = class {
686
725
  const headers = {
687
726
  "Content-Type": "application/json"
688
727
  };
689
- if (token) {
690
- headers.Authorization = `Bearer ${token}`;
691
- }
728
+ const auth = this.getAuthorizationHeader(url, token);
729
+ if (auth) headers.Authorization = auth;
692
730
  const body = {
693
731
  prompt,
694
732
  stream: true,
@@ -708,7 +746,7 @@ var HttpClient = class {
708
746
  if (!response.body) {
709
747
  throw new BlinkNetworkError("No response body for streaming");
710
748
  }
711
- return this.parseDataStream(response.body, onChunk);
749
+ return this.parseDataStreamProtocol(response.body, onChunk);
712
750
  } catch (error) {
713
751
  if (error instanceof BlinkError) {
714
752
  throw error;
@@ -733,7 +771,7 @@ var HttpClient = class {
733
771
  });
734
772
  }
735
773
  /**
736
- * Stream AI object generation with Vercel AI SDK data stream format
774
+ * Stream AI object generation - uses Vercel AI SDK's pipeTextStreamToResponse
737
775
  */
738
776
  async streamAiObject(prompt, options = {}, onPartial) {
739
777
  const url = this.buildUrl(`/api/ai/${this.projectId}/object`);
@@ -741,9 +779,8 @@ var HttpClient = class {
741
779
  const headers = {
742
780
  "Content-Type": "application/json"
743
781
  };
744
- if (token) {
745
- headers.Authorization = `Bearer ${token}`;
746
- }
782
+ const auth = this.getAuthorizationHeader(url, token);
783
+ if (auth) headers.Authorization = auth;
747
784
  const body = {
748
785
  prompt,
749
786
  stream: true,
@@ -763,7 +800,35 @@ var HttpClient = class {
763
800
  if (!response.body) {
764
801
  throw new BlinkNetworkError("No response body for streaming");
765
802
  }
766
- return this.parseDataStream(response.body, void 0, onPartial);
803
+ const reader = response.body.getReader();
804
+ const decoder = new TextDecoder();
805
+ let buffer = "";
806
+ let latestObject = {};
807
+ try {
808
+ while (true) {
809
+ const { done, value } = await reader.read();
810
+ if (done) break;
811
+ const chunk = decoder.decode(value, { stream: true });
812
+ buffer += chunk;
813
+ try {
814
+ const parsed = JSON.parse(buffer);
815
+ latestObject = parsed;
816
+ if (onPartial) {
817
+ onPartial(parsed);
818
+ }
819
+ } catch {
820
+ }
821
+ }
822
+ if (buffer) {
823
+ try {
824
+ latestObject = JSON.parse(buffer);
825
+ } catch {
826
+ }
827
+ }
828
+ return { object: latestObject };
829
+ } finally {
830
+ reader.releaseLock();
831
+ }
767
832
  } catch (error) {
768
833
  if (error instanceof BlinkError) {
769
834
  throw error;
@@ -820,6 +885,17 @@ var HttpClient = class {
820
885
  signal
821
886
  });
822
887
  }
888
+ async aiVideo(prompt, options = {}) {
889
+ const { signal, ...body } = options;
890
+ return this.request(`/api/ai/${this.projectId}/video`, {
891
+ method: "POST",
892
+ body: {
893
+ prompt,
894
+ ...body
895
+ },
896
+ signal
897
+ });
898
+ }
823
899
  /**
824
900
  * Data-specific requests
825
901
  */
@@ -861,6 +937,38 @@ var HttpClient = class {
861
937
  async dataSearch(projectId, request) {
862
938
  return this.post(`/api/data/${projectId}/search`, request);
863
939
  }
940
+ /**
941
+ * Connector requests
942
+ */
943
+ formatProviderForPath(provider) {
944
+ return provider.replace("_", "-");
945
+ }
946
+ async connectorStatus(provider) {
947
+ return this.request(`/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}/status`, {
948
+ method: "GET"
949
+ });
950
+ }
951
+ async connectorExecute(provider, request) {
952
+ const path = request.method.startsWith("/") ? request.method : `/${request.method}`;
953
+ const url = `/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}${path}`;
954
+ const method = (request.http_method || "GET").toUpperCase();
955
+ if (method === "GET") {
956
+ return this.request(url, {
957
+ method: "GET",
958
+ searchParams: request.params
959
+ });
960
+ }
961
+ return this.request(url, {
962
+ method,
963
+ body: request.params || {}
964
+ });
965
+ }
966
+ async connectorSaveApiKey(provider, request) {
967
+ return this.request(`/api/connectors/${this.formatProviderForPath(provider)}/${this.projectId}/api-key`, {
968
+ method: "POST",
969
+ body: request
970
+ });
971
+ }
864
972
  /**
865
973
  * Realtime-specific requests
866
974
  */
@@ -926,93 +1034,94 @@ var HttpClient = class {
926
1034
  }
927
1035
  }
928
1036
  /**
929
- * Parse Vercel AI SDK data stream format
930
- * Handles text chunks (0:"text"), partial objects (2:[...]), and metadata (d:, e:)
1037
+ * Parse Vercel AI SDK v5 Data Stream Protocol (Server-Sent Events)
1038
+ * Supports all event types from the UI Message Stream protocol
931
1039
  */
932
- async parseDataStream(body, onChunk, onPartial) {
1040
+ async parseDataStreamProtocol(body, onChunk) {
933
1041
  const reader = body.getReader();
934
1042
  const decoder = new TextDecoder();
1043
+ const finalResult = {
1044
+ text: "",
1045
+ toolCalls: [],
1046
+ toolResults: [],
1047
+ sources: [],
1048
+ files: [],
1049
+ reasoning: []
1050
+ };
935
1051
  let buffer = "";
936
- let finalResult = {};
937
1052
  try {
938
1053
  while (true) {
939
1054
  const { done, value } = await reader.read();
940
1055
  if (done) break;
941
1056
  buffer += decoder.decode(value, { stream: true });
942
- const lines = buffer.split(/\r?\n/);
1057
+ const lines = buffer.split("\n");
943
1058
  buffer = lines.pop() || "";
944
1059
  for (const line of lines) {
945
1060
  if (!line.trim()) continue;
1061
+ if (line === "[DONE]") {
1062
+ continue;
1063
+ }
1064
+ if (!line.startsWith("data: ")) continue;
946
1065
  try {
947
- if (line.startsWith("f:")) {
948
- const metadata = JSON.parse(line.slice(2));
949
- finalResult.messageId = metadata.messageId;
950
- } else if (line.startsWith("0:")) {
951
- const textChunk = JSON.parse(line.slice(2));
952
- if (onChunk) {
953
- onChunk(textChunk);
954
- }
955
- finalResult.text = (finalResult.text || "") + textChunk;
956
- } else if (line.startsWith("2:")) {
957
- const data = JSON.parse(line.slice(2));
958
- if (Array.isArray(data) && data.length > 0) {
959
- const item = data[0];
960
- if (typeof item === "string") {
961
- finalResult.status = item;
962
- } else if (typeof item === "object") {
963
- if (onPartial) {
964
- onPartial(item);
965
- }
966
- finalResult.object = item;
1066
+ const jsonStr = line.slice(6);
1067
+ const part = JSON.parse(jsonStr);
1068
+ switch (part.type) {
1069
+ case "text-start":
1070
+ break;
1071
+ case "text-delta":
1072
+ if (part.delta) {
1073
+ finalResult.text += part.delta;
1074
+ if (onChunk) onChunk(part.delta);
967
1075
  }
968
- }
969
- } else if (line.startsWith("d:")) {
970
- const metadata = JSON.parse(line.slice(2));
971
- if (metadata.usage) {
972
- finalResult.usage = metadata.usage;
973
- }
974
- if (metadata.finishReason) {
975
- finalResult.finishReason = metadata.finishReason;
976
- }
977
- } else if (line.startsWith("e:")) {
978
- const errorData = JSON.parse(line.slice(2));
979
- finalResult.error = errorData;
980
- }
981
- } catch (error) {
982
- console.warn("Failed to parse stream line:", line, error);
983
- }
984
- }
985
- }
986
- if (buffer.trim()) {
987
- try {
988
- if (buffer.startsWith("0:")) {
989
- const textChunk = JSON.parse(buffer.slice(2));
990
- if (onChunk) {
991
- onChunk(textChunk);
992
- }
993
- finalResult.text = (finalResult.text || "") + textChunk;
994
- } else if (buffer.startsWith("2:")) {
995
- const data = JSON.parse(buffer.slice(2));
996
- if (Array.isArray(data) && data.length > 0) {
997
- const item = data[0];
998
- if (typeof item === "object") {
999
- if (onPartial) {
1000
- onPartial(item);
1076
+ if (part.textDelta) {
1077
+ finalResult.text += part.textDelta;
1078
+ if (onChunk) onChunk(part.textDelta);
1001
1079
  }
1002
- finalResult.object = item;
1003
- }
1004
- }
1005
- } else if (buffer.startsWith("d:")) {
1006
- const metadata = JSON.parse(buffer.slice(2));
1007
- if (metadata.usage) {
1008
- finalResult.usage = metadata.usage;
1009
- }
1010
- if (metadata.finishReason) {
1011
- finalResult.finishReason = metadata.finishReason;
1080
+ break;
1081
+ case "text-end":
1082
+ break;
1083
+ case "tool-call":
1084
+ finalResult.toolCalls.push({
1085
+ toolCallId: part.toolCallId,
1086
+ toolName: part.toolName,
1087
+ args: part.args
1088
+ });
1089
+ break;
1090
+ case "tool-result":
1091
+ finalResult.toolResults.push({
1092
+ toolCallId: part.toolCallId,
1093
+ toolName: part.toolName,
1094
+ result: part.result
1095
+ });
1096
+ break;
1097
+ case "source-url":
1098
+ finalResult.sources.push({
1099
+ id: part.id,
1100
+ url: part.url,
1101
+ title: part.title
1102
+ });
1103
+ break;
1104
+ case "file":
1105
+ finalResult.files.push(part.file);
1106
+ break;
1107
+ case "reasoning":
1108
+ finalResult.reasoning.push(part.content);
1109
+ break;
1110
+ case "finish":
1111
+ finalResult.finishReason = part.finishReason;
1112
+ finalResult.usage = part.usage;
1113
+ if (part.response) finalResult.response = part.response;
1114
+ break;
1115
+ case "error":
1116
+ finalResult.error = part.error;
1117
+ throw new Error(part.error);
1118
+ case "data":
1119
+ if (!finalResult.customData) finalResult.customData = [];
1120
+ finalResult.customData.push(part.value);
1121
+ break;
1012
1122
  }
1123
+ } catch (e) {
1013
1124
  }
1014
- } catch (error) {
1015
- console.warn("Failed to parse final buffer:", buffer, error);
1016
1125
  }
1017
1126
  }
1018
1127
  return finalResult;
@@ -1157,6 +1266,15 @@ function getSessionStorage() {
1157
1266
  return null;
1158
1267
  }
1159
1268
  }
1269
+ function isSafari() {
1270
+ if (!hasWindow()) return false;
1271
+ const ua = navigator.userAgent.toLowerCase();
1272
+ const hasSafariUA = /safari/i.test(ua) && !/chrome|chromium|android/i.test(ua);
1273
+ const isSafariVendor = typeof navigator !== "undefined" && /apple computer|apple/i.test(navigator.vendor || "");
1274
+ const isIOSSafari = /safari/i.test(ua) && /iphone|ipad|ipod/i.test(ua);
1275
+ const hasSafariProperties = typeof window !== "undefined" && "safari" in window && !("chrome" in window);
1276
+ return hasSafariUA || isSafariVendor || isIOSSafari || hasSafariProperties;
1277
+ }
1160
1278
 
1161
1279
  // src/auth.ts
1162
1280
  var BlinkAuth = class {
@@ -1179,16 +1297,16 @@ var BlinkAuth = class {
1179
1297
  this.authConfig = {
1180
1298
  mode: "managed",
1181
1299
  // Default mode
1182
- authUrl: "https://laverna-nonsubmissive-semirhythmically.ngrok-free.dev",
1183
- coreUrl: "https://core.blink.new",
1300
+ authUrl: "https://dev.blink.new",
1301
+ coreUrl: "https://core.dev.blink.new",
1184
1302
  detectSessionInUrl: true,
1185
1303
  // Default to true for web compatibility
1186
1304
  ...config.auth
1187
1305
  };
1188
- this.authUrl = "https://laverna-nonsubmissive-semirhythmically.ngrok-free.dev";
1189
- this.coreUrl = this.authConfig.coreUrl || "https://core.blink.new";
1306
+ this.authUrl = this.authConfig.authUrl || "https://dev.blink.new";
1307
+ this.coreUrl = this.authConfig.coreUrl || "https://core.dev.blink.new";
1190
1308
  const hostname = getLocationHostname();
1191
- if (hostname && this.authUrl === "https://blink.new" && (hostname === "localhost" || hostname === "127.0.0.1")) {
1309
+ if (hostname && this.authUrl === "https://dev.blink.new" && (hostname === "localhost" || hostname === "127.0.0.1")) {
1192
1310
  console.warn("\u26A0\uFE0F Using default authUrl in development. Set auth.authUrl to your app origin for headless auth endpoints to work.");
1193
1311
  }
1194
1312
  if (config.authRequired !== void 0 && !config.auth?.mode) {
@@ -1240,7 +1358,7 @@ var BlinkAuth = class {
1240
1358
  setupParentWindowListener() {
1241
1359
  if (!isWeb || !this.isIframe || !hasWindow()) return;
1242
1360
  window.addEventListener("message", (event) => {
1243
- if (event.origin !== "https://blink.new" && event.origin !== "http://localhost:3000" && event.origin !== "http://localhost:3001") {
1361
+ if (event.origin !== "https://dev.blink.new" && event.origin !== "https://blink.new" && event.origin !== "http://localhost:3000" && event.origin !== "http://localhost:3001") {
1244
1362
  return;
1245
1363
  }
1246
1364
  if (event.data?.type === "BLINK_AUTH_TOKENS") {
@@ -1903,7 +2021,7 @@ var BlinkAuth = class {
1903
2021
  if (!hasWindow()) {
1904
2022
  throw new BlinkAuthError("NETWORK_ERROR" /* NETWORK_ERROR */, "signInWithProvider requires a browser environment");
1905
2023
  }
1906
- const shouldPreferRedirect = isWeb && this.isIframe || typeof window !== "undefined" && window.crossOriginIsolated === true;
2024
+ const shouldPreferRedirect = isWeb && this.isIframe || typeof window !== "undefined" && window.crossOriginIsolated === true || isWeb && isSafari();
1907
2025
  const state = this.generateState();
1908
2026
  try {
1909
2027
  const sessionStorage = getSessionStorage();
@@ -2939,6 +3057,11 @@ var BlinkAuth = class {
2939
3057
  };
2940
3058
 
2941
3059
  // src/database.ts
3060
+ function assertServerOnly(methodName) {
3061
+ if (typeof window !== "undefined") {
3062
+ throw new Error(`${methodName} is server-only. Use Blink CRUD methods (blink.db.<table>.*) instead.`);
3063
+ }
3064
+ }
2942
3065
  function camelToSnake3(str) {
2943
3066
  return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
2944
3067
  }
@@ -3157,6 +3280,7 @@ var BlinkTable = class {
3157
3280
  * Raw SQL query on this table (for advanced use cases)
3158
3281
  */
3159
3282
  async sql(query, params) {
3283
+ assertServerOnly("blink.db.<table>.sql");
3160
3284
  const response = await this.httpClient.dbSql(query, params);
3161
3285
  return response.data;
3162
3286
  }
@@ -3205,6 +3329,7 @@ var BlinkDatabase = class {
3205
3329
  * Execute raw SQL query
3206
3330
  */
3207
3331
  async sql(query, params) {
3332
+ assertServerOnly("blink.db.sql");
3208
3333
  const response = await this.httpClient.dbSql(query, params);
3209
3334
  return response.data;
3210
3335
  }
@@ -3212,6 +3337,7 @@ var BlinkDatabase = class {
3212
3337
  * Execute batch SQL operations
3213
3338
  */
3214
3339
  async batch(statements, mode = "write") {
3340
+ assertServerOnly("blink.db.batch");
3215
3341
  const response = await this.httpClient.dbBatch(statements, mode);
3216
3342
  return response.data;
3217
3343
  }
@@ -3274,7 +3400,6 @@ var BlinkStorageImpl = class {
3274
3400
  correctedPath,
3275
3401
  // Use corrected path with proper extension
3276
3402
  {
3277
- upsert: options.upsert,
3278
3403
  onProgress: options.onProgress,
3279
3404
  contentType: detectedContentType
3280
3405
  // Pass detected content type
@@ -3294,7 +3419,7 @@ var BlinkStorageImpl = class {
3294
3419
  if (error instanceof Error && "status" in error) {
3295
3420
  const status = error.status;
3296
3421
  if (status === 409) {
3297
- throw new BlinkStorageError("File already exists. Set upsert: true to overwrite.", 409);
3422
+ throw new BlinkStorageError("File already exists.", 409);
3298
3423
  }
3299
3424
  if (status === 400) {
3300
3425
  throw new BlinkStorageError("Invalid request parameters", 400);
@@ -3339,7 +3464,6 @@ var BlinkStorageImpl = class {
3339
3464
  detectedContentType
3340
3465
  };
3341
3466
  } catch (error) {
3342
- console.warn("File type detection failed, using original path:", error);
3343
3467
  return {
3344
3468
  correctedPath: originalPath,
3345
3469
  detectedContentType: "application/octet-stream"
@@ -3729,13 +3853,7 @@ var BlinkAIImpl = class {
3729
3853
  options.prompt || "",
3730
3854
  requestBody
3731
3855
  );
3732
- if (response.data?.result) {
3733
- return response.data.result;
3734
- } else if (response.data?.text) {
3735
- return response.data;
3736
- } else {
3737
- throw new BlinkAIError("Invalid response format: missing text");
3738
- }
3856
+ return response.data;
3739
3857
  } catch (error) {
3740
3858
  if (error instanceof BlinkAIError) {
3741
3859
  throw error;
@@ -3804,9 +3922,14 @@ var BlinkAIImpl = class {
3804
3922
  );
3805
3923
  return {
3806
3924
  text: result.text || "",
3807
- finishReason: "stop",
3925
+ finishReason: result.finishReason || "stop",
3808
3926
  usage: result.usage,
3809
- ...result
3927
+ toolCalls: result.toolCalls,
3928
+ toolResults: result.toolResults,
3929
+ sources: result.sources,
3930
+ files: result.files,
3931
+ reasoningDetails: result.reasoning,
3932
+ response: result.response
3810
3933
  };
3811
3934
  } catch (error) {
3812
3935
  if (error instanceof BlinkAIError) {
@@ -3885,13 +4008,7 @@ var BlinkAIImpl = class {
3885
4008
  signal: options.signal
3886
4009
  }
3887
4010
  );
3888
- if (response.data?.result) {
3889
- return response.data.result;
3890
- } else if (response.data?.object) {
3891
- return response.data;
3892
- } else {
3893
- throw new BlinkAIError("Invalid response format: missing object");
3894
- }
4011
+ return response.data;
3895
4012
  } catch (error) {
3896
4013
  if (error instanceof BlinkAIError) {
3897
4014
  throw error;
@@ -3953,8 +4070,7 @@ var BlinkAIImpl = class {
3953
4070
  return {
3954
4071
  object: result.object || {},
3955
4072
  finishReason: "stop",
3956
- usage: result.usage,
3957
- ...result
4073
+ usage: result.usage
3958
4074
  };
3959
4075
  } catch (error) {
3960
4076
  if (error instanceof BlinkAIError) {
@@ -4215,6 +4331,131 @@ var BlinkAIImpl = class {
4215
4331
  );
4216
4332
  }
4217
4333
  }
4334
+ /**
4335
+ * Generates videos from text prompts or images using AI video generation models.
4336
+ *
4337
+ * @param options - Object containing:
4338
+ * - `prompt`: Text description of the video to generate (required)
4339
+ * - `model`: Video model to use (optional). Available models:
4340
+ * **Text-to-Video Models:**
4341
+ * - `"fal-ai/veo3.1"` - Google Veo 3.1 (best quality)
4342
+ * - `"fal-ai/veo3.1/fast"` (default) - Veo 3.1 fast mode (faster, cheaper)
4343
+ * - `"fal-ai/sora-2/text-to-video/pro"` - OpenAI Sora 2
4344
+ * - `"fal-ai/kling-video/v2.6/pro/text-to-video"` - Kling 2.6
4345
+ * **Image-to-Video Models:**
4346
+ * - `"fal-ai/veo3.1/image-to-video"` - Veo 3.1 I2V
4347
+ * - `"fal-ai/veo3.1/fast/image-to-video"` - Veo 3.1 fast I2V
4348
+ * - `"fal-ai/sora-2/image-to-video/pro"` - Sora 2 I2V
4349
+ * - `"fal-ai/kling-video/v2.6/pro/image-to-video"` - Kling 2.6 I2V
4350
+ * - `image_url`: Source image URL for image-to-video (required for I2V models)
4351
+ * - `duration`: Video duration ("4s", "5s", "6s", "8s", "10s", "12s")
4352
+ * - `aspect_ratio`: Aspect ratio ("16:9", "9:16", "1:1")
4353
+ * - `resolution`: Resolution ("720p", "1080p") - Veo/Sora only
4354
+ * - `negative_prompt`: What to avoid in generation - Veo/Kling only
4355
+ * - `generate_audio`: Generate audio with video (default: true)
4356
+ * - `seed`: For reproducibility - Veo only
4357
+ * - `cfg_scale`: Guidance scale (0-1) - Kling only
4358
+ * - Plus optional signal parameter
4359
+ *
4360
+ * @example
4361
+ * ```ts
4362
+ * // Basic text-to-video generation (uses default fast model)
4363
+ * const { result } = await blink.ai.generateVideo({
4364
+ * prompt: "A serene sunset over the ocean with gentle waves"
4365
+ * });
4366
+ * console.log("Video URL:", result.video.url);
4367
+ *
4368
+ * // High quality with Veo 3.1
4369
+ * const { result } = await blink.ai.generateVideo({
4370
+ * prompt: "A cinematic shot of a futuristic city at night",
4371
+ * model: "fal-ai/veo3.1",
4372
+ * resolution: "1080p",
4373
+ * aspect_ratio: "16:9"
4374
+ * });
4375
+ *
4376
+ * // Image-to-video animation
4377
+ * const { result } = await blink.ai.generateVideo({
4378
+ * prompt: "Animate this image with gentle camera movement",
4379
+ * model: "fal-ai/veo3.1/fast/image-to-video",
4380
+ * image_url: "https://example.com/my-image.jpg",
4381
+ * duration: "5s"
4382
+ * });
4383
+ *
4384
+ * // Using Sora 2 for creative videos
4385
+ * const { result } = await blink.ai.generateVideo({
4386
+ * prompt: "A magical forest with glowing fireflies",
4387
+ * model: "fal-ai/sora-2/text-to-video/pro",
4388
+ * duration: "8s"
4389
+ * });
4390
+ *
4391
+ * // Using Kling for detailed videos
4392
+ * const { result, usage } = await blink.ai.generateVideo({
4393
+ * prompt: "A professional cooking tutorial scene",
4394
+ * model: "fal-ai/kling-video/v2.6/pro/text-to-video",
4395
+ * negative_prompt: "blur, distort, low quality",
4396
+ * cfg_scale: 0.7
4397
+ * });
4398
+ * console.log("Credits charged:", usage?.creditsCharged);
4399
+ * ```
4400
+ *
4401
+ * @returns Promise<VideoGenerationResponse> - Object containing:
4402
+ * - `result.video.url`: URL to the generated video
4403
+ * - `result.video.content_type`: MIME type (video/mp4)
4404
+ * - `result.video.file_name`: Generated filename
4405
+ * - `result.video.file_size`: File size in bytes
4406
+ * - `metadata`: Generation metadata (projectId, timestamp, model)
4407
+ * - `usage`: Credits charged and cost information
4408
+ */
4409
+ async generateVideo(options) {
4410
+ try {
4411
+ if (!options.prompt) {
4412
+ throw new BlinkAIError("Prompt is required");
4413
+ }
4414
+ const i2vModels = [
4415
+ "fal-ai/veo3.1/image-to-video",
4416
+ "fal-ai/veo3.1/fast/image-to-video",
4417
+ "fal-ai/sora-2/image-to-video/pro",
4418
+ "fal-ai/kling-video/v2.6/pro/image-to-video"
4419
+ ];
4420
+ if (options.model && i2vModels.includes(options.model) && !options.image_url) {
4421
+ throw new BlinkAIError("image_url is required for image-to-video models");
4422
+ }
4423
+ if (options.image_url) {
4424
+ const validation = this.validateImageUrl(options.image_url);
4425
+ if (!validation.isValid) {
4426
+ throw new BlinkAIError(`Invalid image_url: ${validation.error}`);
4427
+ }
4428
+ }
4429
+ const response = await this.httpClient.aiVideo(
4430
+ options.prompt,
4431
+ {
4432
+ model: options.model,
4433
+ image_url: options.image_url,
4434
+ duration: options.duration,
4435
+ aspect_ratio: options.aspect_ratio,
4436
+ resolution: options.resolution,
4437
+ negative_prompt: options.negative_prompt,
4438
+ generate_audio: options.generate_audio,
4439
+ seed: options.seed,
4440
+ cfg_scale: options.cfg_scale,
4441
+ signal: options.signal
4442
+ }
4443
+ );
4444
+ if (!response.data?.result?.video?.url) {
4445
+ throw new BlinkAIError("Invalid response format: missing video URL");
4446
+ }
4447
+ return response.data;
4448
+ } catch (error) {
4449
+ if (error instanceof BlinkAIError) {
4450
+ throw error;
4451
+ }
4452
+ throw new BlinkAIError(
4453
+ `Video generation failed: ${error instanceof Error ? error.message : "Unknown error"}`,
4454
+ void 0,
4455
+ { originalError: error }
4456
+ );
4457
+ }
4458
+ }
4218
4459
  /**
4219
4460
  * Converts text to speech using AI voice synthesis models.
4220
4461
  *
@@ -5273,7 +5514,6 @@ var BlinkAnalyticsImpl = class {
5273
5514
  } catch (error) {
5274
5515
  this.queue = [...events, ...this.queue];
5275
5516
  this.persistQueue();
5276
- console.error("Failed to send analytics events:", error);
5277
5517
  }
5278
5518
  if (this.queue.length > 0) {
5279
5519
  this.timer = setTimeout(() => this.flush(), BATCH_TIMEOUT);
@@ -5464,6 +5704,64 @@ var BlinkAnalyticsImpl = class {
5464
5704
  }
5465
5705
  };
5466
5706
 
5707
+ // src/connectors.ts
5708
+ var BlinkConnectorsImpl = class {
5709
+ constructor(httpClient) {
5710
+ this.httpClient = httpClient;
5711
+ }
5712
+ async status(provider, options) {
5713
+ const response = await this.httpClient.connectorStatus(provider);
5714
+ return response.data;
5715
+ }
5716
+ async execute(provider, request) {
5717
+ const response = await this.httpClient.connectorExecute(provider, request);
5718
+ return response.data;
5719
+ }
5720
+ async saveApiKey(provider, request) {
5721
+ const response = await this.httpClient.connectorSaveApiKey(provider, request);
5722
+ return response.data;
5723
+ }
5724
+ };
5725
+
5726
+ // src/functions.ts
5727
+ var BlinkFunctionsImpl = class {
5728
+ httpClient;
5729
+ projectId;
5730
+ constructor(httpClient, projectId, _getToken) {
5731
+ this.httpClient = httpClient;
5732
+ this.projectId = projectId;
5733
+ }
5734
+ /**
5735
+ * Get the project suffix from the full project ID.
5736
+ * Project IDs are formatted as: prj_xxxxx
5737
+ * The suffix is the last 8 characters used in function URLs.
5738
+ */
5739
+ getProjectSuffix() {
5740
+ return this.projectId.slice(-8);
5741
+ }
5742
+ /**
5743
+ * Build the full function URL
5744
+ */
5745
+ buildFunctionUrl(functionSlug, searchParams) {
5746
+ const suffix = this.getProjectSuffix();
5747
+ const baseUrl = `https://${suffix}--${functionSlug}.functions.blink.new`;
5748
+ if (!searchParams || Object.keys(searchParams).length === 0) {
5749
+ return baseUrl;
5750
+ }
5751
+ const url = new URL(baseUrl);
5752
+ Object.entries(searchParams).forEach(([key, value]) => {
5753
+ url.searchParams.set(key, value);
5754
+ });
5755
+ return url.toString();
5756
+ }
5757
+ async invoke(functionSlug, options = {}) {
5758
+ const { method = "POST", body, headers = {}, searchParams } = options;
5759
+ const url = this.buildFunctionUrl(functionSlug, searchParams);
5760
+ const res = await this.httpClient.request(url, { method, body, headers });
5761
+ return { data: res.data, status: res.status, headers: res.headers };
5762
+ }
5763
+ };
5764
+
5467
5765
  // src/client.ts
5468
5766
  var BlinkClientImpl = class {
5469
5767
  auth;
@@ -5474,8 +5772,13 @@ var BlinkClientImpl = class {
5474
5772
  realtime;
5475
5773
  notifications;
5476
5774
  analytics;
5775
+ connectors;
5776
+ functions;
5477
5777
  httpClient;
5478
5778
  constructor(config) {
5779
+ if ((config.secretKey || config.serviceToken) && isBrowser) {
5780
+ throw new Error("secretKey/serviceToken is server-only. Do not provide it in browser/React Native clients.");
5781
+ }
5479
5782
  this.auth = new BlinkAuth(config);
5480
5783
  this.httpClient = new HttpClient(
5481
5784
  config,
@@ -5489,6 +5792,12 @@ var BlinkClientImpl = class {
5489
5792
  this.realtime = new BlinkRealtimeImpl(this.httpClient, config.projectId);
5490
5793
  this.notifications = new BlinkNotificationsImpl(this.httpClient);
5491
5794
  this.analytics = new BlinkAnalyticsImpl(this.httpClient, config.projectId);
5795
+ this.connectors = new BlinkConnectorsImpl(this.httpClient);
5796
+ this.functions = new BlinkFunctionsImpl(
5797
+ this.httpClient,
5798
+ config.projectId,
5799
+ () => this.auth.getValidToken()
5800
+ );
5492
5801
  this.auth.onAuthStateChanged((state) => {
5493
5802
  if (state.isAuthenticated && state.user) {
5494
5803
  this.analytics.setUserId(state.user.id);
@@ -5510,6 +5819,7 @@ function createClient(config) {
5510
5819
  exports.AsyncStorageAdapter = AsyncStorageAdapter;
5511
5820
  exports.BlinkAIImpl = BlinkAIImpl;
5512
5821
  exports.BlinkAnalyticsImpl = BlinkAnalyticsImpl;
5822
+ exports.BlinkConnectorsImpl = BlinkConnectorsImpl;
5513
5823
  exports.BlinkDataImpl = BlinkDataImpl;
5514
5824
  exports.BlinkDatabase = BlinkDatabase;
5515
5825
  exports.BlinkRealtimeChannel = BlinkRealtimeChannel;
@@ -5521,8 +5831,10 @@ exports.WebStorageAdapter = WebStorageAdapter;
5521
5831
  exports.createClient = createClient;
5522
5832
  exports.getDefaultStorageAdapter = getDefaultStorageAdapter;
5523
5833
  exports.isBrowser = isBrowser;
5834
+ exports.isDeno = isDeno;
5524
5835
  exports.isNode = isNode;
5525
5836
  exports.isReactNative = isReactNative;
5837
+ exports.isServer = isServer;
5526
5838
  exports.isWeb = isWeb;
5527
5839
  exports.platform = platform;
5528
5840
  //# sourceMappingURL=index.js.map