@gradio/client 0.20.0 → 1.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +201 -0
  2. package/README.md +21 -36
  3. package/dist/client.d.ts +6 -7
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/constants.d.ts +3 -0
  6. package/dist/constants.d.ts.map +1 -1
  7. package/dist/helpers/data.d.ts +15 -1
  8. package/dist/helpers/data.d.ts.map +1 -1
  9. package/dist/helpers/init_helpers.d.ts.map +1 -1
  10. package/dist/helpers/spaces.d.ts.map +1 -1
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +496 -114
  14. package/dist/test/handlers.d.ts +1 -0
  15. package/dist/test/handlers.d.ts.map +1 -1
  16. package/dist/test/test_data.d.ts.map +1 -1
  17. package/dist/types.d.ts +93 -24
  18. package/dist/types.d.ts.map +1 -1
  19. package/dist/utils/handle_blob.d.ts +2 -1
  20. package/dist/utils/handle_blob.d.ts.map +1 -1
  21. package/dist/utils/predict.d.ts +2 -2
  22. package/dist/utils/predict.d.ts.map +1 -1
  23. package/dist/utils/stream.d.ts +2 -1
  24. package/dist/utils/stream.d.ts.map +1 -1
  25. package/dist/utils/submit.d.ts +2 -2
  26. package/dist/utils/submit.d.ts.map +1 -1
  27. package/index.html +39 -0
  28. package/package.json +5 -2
  29. package/src/client.ts +40 -35
  30. package/src/constants.ts +4 -0
  31. package/src/helpers/api_info.ts +1 -1
  32. package/src/helpers/data.ts +124 -10
  33. package/src/helpers/init_helpers.ts +5 -0
  34. package/src/helpers/spaces.ts +2 -1
  35. package/src/index.ts +6 -1
  36. package/src/test/api_info.test.ts +0 -1
  37. package/src/test/data.test.ts +201 -26
  38. package/src/test/handlers.ts +9 -1
  39. package/src/test/stream.test.ts +12 -10
  40. package/src/test/test_data.ts +8 -5
  41. package/src/test/upload_files.test.ts +1 -1
  42. package/src/types.ts +110 -26
  43. package/src/utils/handle_blob.ts +91 -1
  44. package/src/utils/predict.ts +15 -16
  45. package/src/utils/stream.ts +66 -13
  46. package/src/utils/submit.ts +156 -63
  47. package/src/utils/upload_files.ts +1 -1
  48. package/vite.config.js +37 -24
package/dist/index.js CHANGED
@@ -4,6 +4,25 @@ var __publicField = (obj, key, value) => {
4
4
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
5
  return value;
6
6
  };
7
+ var __accessCheck = (obj, member, msg) => {
8
+ if (!member.has(obj))
9
+ throw TypeError("Cannot " + msg);
10
+ };
11
+ var __privateGet = (obj, member, getter) => {
12
+ __accessCheck(obj, member, "read from private field");
13
+ return getter ? getter.call(obj) : member.get(obj);
14
+ };
15
+ var __privateAdd = (obj, member, value) => {
16
+ if (member.has(obj))
17
+ throw TypeError("Cannot add the same private member more than once");
18
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
19
+ };
20
+ var __privateSet = (obj, member, value, setter) => {
21
+ __accessCheck(obj, member, "write to private field");
22
+ setter ? setter.call(obj, value) : member.set(obj, value);
23
+ return value;
24
+ };
25
+ var _currentLine;
7
26
  var fn = new Intl.Collator(0, { numeric: 1 }).compare;
8
27
  function semiver(a, b, bool) {
9
28
  a = a.split(".");
@@ -28,6 +47,9 @@ const INVALID_URL_MSG = "Invalid URL. A full URL path is required.";
28
47
  const UNAUTHORIZED_MSG = "Not authorized to access this space. ";
29
48
  const INVALID_CREDENTIALS_MSG = "Invalid credentials. Could not login. ";
30
49
  const MISSING_CREDENTIALS_MSG = "Login credentials are required to access this space.";
50
+ const NODEJS_FS_ERROR_MSG = "File system access is only available in Node.js environments";
51
+ const ROOT_URL_ERROR_MSG = "Root URL not found in client config";
52
+ const FILE_PROCESSING_ERROR_MSG = "Error uploading file";
31
53
  function resolve_root(base_url, root_path, prioritize_base) {
32
54
  if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
33
55
  return prioritize_base ? base_url : root_path;
@@ -57,6 +79,7 @@ function map_names_to_ids(fns) {
57
79
  return apis;
58
80
  }
59
81
  async function resolve_config(endpoint) {
82
+ var _a;
60
83
  const headers = this.options.hf_token ? { Authorization: `Bearer ${this.options.hf_token}` } : {};
61
84
  headers["Content-Type"] = "application/json";
62
85
  if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) {
@@ -80,6 +103,11 @@ async function resolve_config(endpoint) {
80
103
  let config = await response.json();
81
104
  config.path = config.path ?? "";
82
105
  config.root = endpoint;
106
+ (_a = config.dependencies) == null ? void 0 : _a.forEach((dep, i) => {
107
+ if (dep.id === void 0) {
108
+ dep.id = i;
109
+ }
110
+ });
83
111
  return config;
84
112
  } else if ((response == null ? void 0 : response.status) === 401) {
85
113
  throw new Error(UNAUTHORIZED_MSG);
@@ -233,7 +261,7 @@ function transform_api_info(api_info, config, api_map) {
233
261
  const dependencyIndex = ((_a = config.dependencies.find(
234
262
  (dep) => dep.api_name === endpoint || dep.api_name === endpoint.replace("/", "")
235
263
  )) == null ? void 0 : _a.id) || api_map[endpoint.replace("/", "")] || -1;
236
- const dependencyTypes = dependencyIndex !== -1 ? (_b = config.dependencies.find((dep) => dep.id == dependencyIndex)) == null ? void 0 : _b.types : { continuous: false, generator: false };
264
+ const dependencyTypes = dependencyIndex !== -1 ? (_b = config.dependencies.find((dep) => dep.id == dependencyIndex)) == null ? void 0 : _b.types : { continuous: false, generator: false, cancel: false };
237
265
  if (dependencyIndex !== -1 && ((_d = (_c = config.dependencies.find((dep) => dep.id == dependencyIndex)) == null ? void 0 : _c.inputs) == null ? void 0 : _d.length) !== parameters.length) {
238
266
  const components = config.dependencies.find((dep) => dep.id == dependencyIndex).inputs.map(
239
267
  (input) => {
@@ -526,7 +554,7 @@ async function upload_files(root_url, files, upload_id) {
526
554
  formData.append("files", file);
527
555
  });
528
556
  try {
529
- const upload_url = upload_id ? `${root_url}/upload?upload_id=${upload_id}` : `${root_url}/${UPLOAD_URL}`;
557
+ const upload_url = upload_id ? `${root_url}/${UPLOAD_URL}?upload_id=${upload_id}` : `${root_url}/${UPLOAD_URL}`;
530
558
  response = await this.fetch(upload_url, {
531
559
  method: "POST",
532
560
  body: formData,
@@ -623,6 +651,18 @@ class FileData {
623
651
  this.alt_text = alt_text;
624
652
  }
625
653
  }
654
+ class Command {
655
+ constructor(command, meta) {
656
+ __publicField(this, "type");
657
+ __publicField(this, "command");
658
+ __publicField(this, "meta");
659
+ __publicField(this, "fileData");
660
+ this.type = "command";
661
+ this.command = command;
662
+ this.meta = meta;
663
+ }
664
+ }
665
+ const is_node = typeof process !== "undefined" && process.versions && process.versions.node;
626
666
  function update_object(object, newValue, stack) {
627
667
  while (stack.length > 1) {
628
668
  const key2 = stack.shift();
@@ -659,11 +699,10 @@ async function walk_and_store_blobs(data, type = void 0, path = [], root = false
659
699
  );
660
700
  return blob_refs;
661
701
  } else if (globalThis.Buffer && data instanceof globalThis.Buffer || data instanceof Blob) {
662
- const is_image = type === "Image";
663
702
  return [
664
703
  {
665
704
  path,
666
- blob: is_image ? false : new NodeBlob([data]),
705
+ blob: new Blob([data]),
667
706
  type
668
707
  }
669
708
  ];
@@ -704,8 +743,80 @@ function post_message(message, origin) {
704
743
  window.parent.postMessage(message, origin, [channel.port2]);
705
744
  });
706
745
  }
746
+ function handle_file(file_or_url) {
747
+ if (typeof file_or_url === "string") {
748
+ if (file_or_url.startsWith("http://") || file_or_url.startsWith("https://")) {
749
+ return {
750
+ path: file_or_url,
751
+ url: file_or_url,
752
+ orig_name: file_or_url.split("/").pop() ?? "unknown",
753
+ meta: { _type: "gradio.FileData" }
754
+ };
755
+ }
756
+ if (is_node) {
757
+ return new Command("upload_file", {
758
+ path: file_or_url,
759
+ name: file_or_url,
760
+ orig_path: file_or_url
761
+ });
762
+ }
763
+ } else if (typeof File !== "undefined" && file_or_url instanceof File) {
764
+ return {
765
+ path: file_or_url instanceof File ? file_or_url.name : "blob",
766
+ orig_name: file_or_url instanceof File ? file_or_url.name : "unknown",
767
+ // @ts-ignore
768
+ blob: file_or_url instanceof File ? file_or_url : new Blob([file_or_url]),
769
+ size: file_or_url instanceof Blob ? file_or_url.size : Buffer.byteLength(file_or_url),
770
+ mime_type: file_or_url instanceof File ? file_or_url.type : "application/octet-stream",
771
+ // Default MIME type for buffers
772
+ meta: { _type: "gradio.FileData" }
773
+ };
774
+ } else if (file_or_url instanceof Buffer) {
775
+ return new Blob([file_or_url]);
776
+ } else if (file_or_url instanceof Blob) {
777
+ return file_or_url;
778
+ }
779
+ throw new Error(
780
+ "Invalid input: must be a URL, File, Blob, or Buffer object."
781
+ );
782
+ }
783
+ function handle_payload(resolved_payload, dependency, components, type, with_null_state = false) {
784
+ if (type === "input" && !with_null_state) {
785
+ throw new Error("Invalid code path. Cannot skip state inputs for input.");
786
+ }
787
+ if (type === "output" && with_null_state) {
788
+ return resolved_payload;
789
+ }
790
+ let updated_payload = [];
791
+ let payload_index = 0;
792
+ for (let i = 0; i < dependency.inputs.length; i++) {
793
+ const input_id = dependency.inputs[i];
794
+ const component = components.find((c) => c.id === input_id);
795
+ if ((component == null ? void 0 : component.type) === "state") {
796
+ if (with_null_state) {
797
+ if (resolved_payload.length === dependency.inputs.length) {
798
+ const value = resolved_payload[payload_index];
799
+ updated_payload.push(value);
800
+ payload_index++;
801
+ } else {
802
+ updated_payload.push(null);
803
+ }
804
+ } else {
805
+ payload_index++;
806
+ continue;
807
+ }
808
+ continue;
809
+ } else {
810
+ const value = resolved_payload[payload_index];
811
+ updated_payload.push(value);
812
+ payload_index++;
813
+ }
814
+ }
815
+ return updated_payload;
816
+ }
707
817
  async function handle_blob(endpoint, data, api_info) {
708
818
  const self = this;
819
+ await process_local_file_commands(self, data);
709
820
  const blobRefs = await walk_and_store_blobs(
710
821
  data,
711
822
  void 0,
@@ -737,6 +848,55 @@ async function handle_blob(endpoint, data, api_info) {
737
848
  });
738
849
  return data;
739
850
  }
851
+ async function process_local_file_commands(client2, data) {
852
+ var _a, _b;
853
+ const root = ((_a = client2.config) == null ? void 0 : _a.root) || ((_b = client2.config) == null ? void 0 : _b.root_url);
854
+ if (!root) {
855
+ throw new Error(ROOT_URL_ERROR_MSG);
856
+ }
857
+ await recursively_process_commands(client2, data);
858
+ }
859
+ async function recursively_process_commands(client2, data, path = []) {
860
+ for (const key in data) {
861
+ if (data[key] instanceof Command) {
862
+ await process_single_command(client2, data, key);
863
+ } else if (typeof data[key] === "object" && data[key] !== null) {
864
+ await recursively_process_commands(client2, data[key], [...path, key]);
865
+ }
866
+ }
867
+ }
868
+ async function process_single_command(client2, data, key) {
869
+ var _a, _b;
870
+ let cmd_item = data[key];
871
+ const root = ((_a = client2.config) == null ? void 0 : _a.root) || ((_b = client2.config) == null ? void 0 : _b.root_url);
872
+ if (!root) {
873
+ throw new Error(ROOT_URL_ERROR_MSG);
874
+ }
875
+ try {
876
+ let fileBuffer;
877
+ let fullPath;
878
+ if (typeof process !== "undefined" && process.versions && process.versions.node) {
879
+ const fs = await import("fs/promises");
880
+ const path = await import("path");
881
+ fullPath = path.resolve(process.cwd(), cmd_item.meta.path);
882
+ fileBuffer = await fs.readFile(fullPath);
883
+ } else {
884
+ throw new Error(NODEJS_FS_ERROR_MSG);
885
+ }
886
+ const file = new Blob([fileBuffer], { type: "application/octet-stream" });
887
+ const response = await client2.upload_files(root, [file]);
888
+ const file_url = response.files && response.files[0];
889
+ if (file_url) {
890
+ const fileData = new FileData({
891
+ path: file_url,
892
+ orig_name: cmd_item.meta.name || ""
893
+ });
894
+ data[key] = fileData;
895
+ }
896
+ } catch (error) {
897
+ console.error(FILE_PROCESSING_ERROR_MSG, error);
898
+ }
899
+ }
740
900
  async function post_data(url, body, additional_headers) {
741
901
  const headers = { "Content-Type": "application/json" };
742
902
  if (this.options.hf_token) {
@@ -784,26 +944,27 @@ async function predict(endpoint, data) {
784
944
  );
785
945
  }
786
946
  return new Promise(async (resolve, reject) => {
787
- const app = this.submit(endpoint, data);
947
+ const app = this.submit(endpoint, data, null, null, true);
788
948
  let result;
789
- app.on("data", (d) => {
790
- if (status_complete) {
791
- app.destroy();
792
- resolve(d);
793
- }
794
- data_returned = true;
795
- result = d;
796
- }).on("status", (status) => {
797
- if (status.stage === "error")
798
- reject(status);
799
- if (status.stage === "complete") {
800
- status_complete = true;
801
- if (data_returned) {
802
- app.destroy();
949
+ for await (const message of app) {
950
+ if (message.type === "data") {
951
+ if (status_complete) {
803
952
  resolve(result);
804
953
  }
954
+ data_returned = true;
955
+ result = message;
805
956
  }
806
- });
957
+ if (message.type === "status") {
958
+ if (message.stage === "error")
959
+ reject(message);
960
+ if (message.stage === "complete") {
961
+ status_complete = true;
962
+ if (data_returned) {
963
+ resolve(result);
964
+ }
965
+ }
966
+ }
967
+ }
807
968
  });
808
969
  }
809
970
  async function check_space_status(id, type, status_callback) {
@@ -895,7 +1056,7 @@ async function discussions_enabled(space_id) {
895
1056
  }
896
1057
  );
897
1058
  const error = r.headers.get("x-error-message");
898
- if (error && RE_DISABLED_DISCUSSION.test(error))
1059
+ if (!r.ok || error && RE_DISABLED_DISCUSSION.test(error))
899
1060
  return false;
900
1061
  return true;
901
1062
  } catch (e) {
@@ -1047,6 +1208,106 @@ function get_space_reference(url) {
1047
1208
  return match[1];
1048
1209
  }
1049
1210
  }
1211
+ class TextLineStream extends TransformStream {
1212
+ /** Constructs a new instance. */
1213
+ constructor(options = { allowCR: false }) {
1214
+ super({
1215
+ transform: (chars, controller) => {
1216
+ chars = __privateGet(this, _currentLine) + chars;
1217
+ while (true) {
1218
+ const lfIndex = chars.indexOf("\n");
1219
+ const crIndex = options.allowCR ? chars.indexOf("\r") : -1;
1220
+ if (crIndex !== -1 && crIndex !== chars.length - 1 && (lfIndex === -1 || lfIndex - 1 > crIndex)) {
1221
+ controller.enqueue(chars.slice(0, crIndex));
1222
+ chars = chars.slice(crIndex + 1);
1223
+ continue;
1224
+ }
1225
+ if (lfIndex === -1)
1226
+ break;
1227
+ const endIndex = chars[lfIndex - 1] === "\r" ? lfIndex - 1 : lfIndex;
1228
+ controller.enqueue(chars.slice(0, endIndex));
1229
+ chars = chars.slice(lfIndex + 1);
1230
+ }
1231
+ __privateSet(this, _currentLine, chars);
1232
+ },
1233
+ flush: (controller) => {
1234
+ if (__privateGet(this, _currentLine) === "")
1235
+ return;
1236
+ const currentLine = options.allowCR && __privateGet(this, _currentLine).endsWith("\r") ? __privateGet(this, _currentLine).slice(0, -1) : __privateGet(this, _currentLine);
1237
+ controller.enqueue(currentLine);
1238
+ }
1239
+ });
1240
+ __privateAdd(this, _currentLine, "");
1241
+ }
1242
+ }
1243
+ _currentLine = new WeakMap();
1244
+ function stream$1(input) {
1245
+ let decoder = new TextDecoderStream();
1246
+ let split2 = new TextLineStream({ allowCR: true });
1247
+ return input.pipeThrough(decoder).pipeThrough(split2);
1248
+ }
1249
+ function split(input) {
1250
+ let rgx = /[:]\s*/;
1251
+ let match = rgx.exec(input);
1252
+ let idx = match && match.index;
1253
+ if (idx) {
1254
+ return [
1255
+ input.substring(0, idx),
1256
+ input.substring(idx + match[0].length)
1257
+ ];
1258
+ }
1259
+ }
1260
+ function fallback(headers, key, value) {
1261
+ let tmp = headers.get(key);
1262
+ if (!tmp)
1263
+ headers.set(key, value);
1264
+ }
1265
+ async function* events(res, signal) {
1266
+ if (!res.body)
1267
+ return;
1268
+ let iter = stream$1(res.body);
1269
+ let line, reader = iter.getReader();
1270
+ let event;
1271
+ for (; ; ) {
1272
+ if (signal && signal.aborted) {
1273
+ return reader.cancel();
1274
+ }
1275
+ line = await reader.read();
1276
+ if (line.done)
1277
+ return;
1278
+ if (!line.value) {
1279
+ if (event)
1280
+ yield event;
1281
+ event = void 0;
1282
+ continue;
1283
+ }
1284
+ let [field, value] = split(line.value) || [];
1285
+ if (!field)
1286
+ continue;
1287
+ if (field === "data") {
1288
+ event || (event = {});
1289
+ event[field] = event[field] ? event[field] + "\n" + value : value;
1290
+ } else if (field === "event") {
1291
+ event || (event = {});
1292
+ event[field] = value;
1293
+ } else if (field === "id") {
1294
+ event || (event = {});
1295
+ event[field] = +value || value;
1296
+ } else if (field === "retry") {
1297
+ event || (event = {});
1298
+ event[field] = +value || void 0;
1299
+ }
1300
+ }
1301
+ }
1302
+ async function stream(input, init) {
1303
+ let req = new Request(input, init);
1304
+ fallback(req.headers, "Accept", "text/event-stream");
1305
+ fallback(req.headers, "Content-Type", "application/json");
1306
+ let r = await fetch(req);
1307
+ if (!r.ok)
1308
+ throw r;
1309
+ return events(r, req.signal);
1310
+ }
1050
1311
  async function open_stream() {
1051
1312
  let {
1052
1313
  event_callbacks,
@@ -1056,11 +1317,12 @@ async function open_stream() {
1056
1317
  config,
1057
1318
  jwt
1058
1319
  } = this;
1320
+ const that = this;
1059
1321
  if (!config) {
1060
1322
  throw new Error("Could not resolve app config");
1061
1323
  }
1062
1324
  stream_status.open = true;
1063
- let stream = null;
1325
+ let stream2 = null;
1064
1326
  let params = new URLSearchParams({
1065
1327
  session_hash: this.session_hash
1066
1328
  }).toString();
@@ -1068,15 +1330,15 @@ async function open_stream() {
1068
1330
  if (jwt) {
1069
1331
  url.searchParams.set("__sign", jwt);
1070
1332
  }
1071
- stream = await this.stream(url);
1072
- if (!stream) {
1333
+ stream2 = this.stream(url);
1334
+ if (!stream2) {
1073
1335
  console.warn("Cannot connect to SSE endpoint: " + url.toString());
1074
1336
  return;
1075
1337
  }
1076
- stream.onmessage = async function(event) {
1338
+ stream2.onmessage = async function(event) {
1077
1339
  let _data = JSON.parse(event.data);
1078
1340
  if (_data.msg === "close_stream") {
1079
- close_stream(stream_status, stream);
1341
+ close_stream(stream_status, that.abort_controller);
1080
1342
  return;
1081
1343
  }
1082
1344
  const event_id = _data.event_id;
@@ -1087,17 +1349,16 @@ async function open_stream() {
1087
1349
  )
1088
1350
  );
1089
1351
  } else if (event_callbacks[event_id] && config) {
1090
- if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1"].includes(config.protocol)) {
1352
+ if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1", "sse_v3"].includes(
1353
+ config.protocol
1354
+ )) {
1091
1355
  unclosed_events.delete(event_id);
1092
- if (unclosed_events.size === 0) {
1093
- close_stream(stream_status, stream);
1094
- }
1095
1356
  }
1096
1357
  let fn2 = event_callbacks[event_id];
1097
- if (typeof window !== "undefined") {
1098
- window.setTimeout(fn2, 0, _data);
1358
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1359
+ setTimeout(fn2, 0, _data);
1099
1360
  } else {
1100
- setImmediate(fn2, _data);
1361
+ fn2(_data);
1101
1362
  }
1102
1363
  } else {
1103
1364
  if (!pending_stream_messages[event_id]) {
@@ -1106,7 +1367,7 @@ async function open_stream() {
1106
1367
  pending_stream_messages[event_id].push(_data);
1107
1368
  }
1108
1369
  };
1109
- stream.onerror = async function() {
1370
+ stream2.onerror = async function() {
1110
1371
  await Promise.all(
1111
1372
  Object.keys(event_callbacks).map(
1112
1373
  (event_id) => event_callbacks[event_id]({
@@ -1115,13 +1376,12 @@ async function open_stream() {
1115
1376
  })
1116
1377
  )
1117
1378
  );
1118
- close_stream(stream_status, stream);
1119
1379
  };
1120
1380
  }
1121
- function close_stream(stream_status, stream) {
1122
- if (stream_status && stream) {
1381
+ function close_stream(stream_status, abort_controller) {
1382
+ if (stream_status) {
1123
1383
  stream_status.open = false;
1124
- stream == null ? void 0 : stream.close();
1384
+ abort_controller == null ? void 0 : abort_controller.abort();
1125
1385
  }
1126
1386
  }
1127
1387
  function apply_diff_stream(pending_diff_streams, event_id, data) {
@@ -1185,31 +1445,81 @@ function apply_edit(target, path, action, value) {
1185
1445
  }
1186
1446
  return target;
1187
1447
  }
1188
- function submit(endpoint, data, event_data, trigger_id) {
1448
+ function readable_stream(input, init = {}) {
1449
+ const instance = {
1450
+ close: () => {
1451
+ throw new Error("Method not implemented.");
1452
+ },
1453
+ onerror: null,
1454
+ onmessage: null,
1455
+ onopen: null,
1456
+ readyState: 0,
1457
+ url: input.toString(),
1458
+ withCredentials: false,
1459
+ CONNECTING: 0,
1460
+ OPEN: 1,
1461
+ CLOSED: 2,
1462
+ addEventListener: () => {
1463
+ throw new Error("Method not implemented.");
1464
+ },
1465
+ dispatchEvent: () => {
1466
+ throw new Error("Method not implemented.");
1467
+ },
1468
+ removeEventListener: () => {
1469
+ throw new Error("Method not implemented.");
1470
+ }
1471
+ };
1472
+ stream(input, init).then(async (res) => {
1473
+ instance.readyState = instance.OPEN;
1474
+ try {
1475
+ for await (const chunk of res) {
1476
+ instance.onmessage && instance.onmessage(chunk);
1477
+ }
1478
+ instance.readyState = instance.CLOSED;
1479
+ } catch (e) {
1480
+ instance.onerror && instance.onerror(e);
1481
+ instance.readyState = instance.CLOSED;
1482
+ }
1483
+ }).catch((e) => {
1484
+ console.error(e);
1485
+ instance.onerror && instance.onerror(e);
1486
+ instance.readyState = instance.CLOSED;
1487
+ });
1488
+ return instance;
1489
+ }
1490
+ function submit(endpoint, data, event_data, trigger_id, all_events) {
1491
+ var _a;
1189
1492
  try {
1190
1493
  let fire_event = function(event) {
1191
- const narrowed_listener_map = listener_map;
1192
- const listeners = narrowed_listener_map[event.type] || [];
1193
- listeners == null ? void 0 : listeners.forEach((l) => l(event));
1194
- }, on = function(eventType, listener) {
1195
- const narrowed_listener_map = listener_map;
1196
- const listeners = narrowed_listener_map[eventType] || [];
1197
- narrowed_listener_map[eventType] = listeners;
1198
- listeners == null ? void 0 : listeners.push(listener);
1199
- return { on, off, cancel, destroy };
1200
- }, off = function(eventType, listener) {
1201
- const narrowed_listener_map = listener_map;
1202
- let listeners = narrowed_listener_map[eventType] || [];
1203
- listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
1204
- narrowed_listener_map[eventType] = listeners;
1205
- return { on, off, cancel, destroy };
1206
- }, destroy = function() {
1207
- var _a;
1208
- for (const event_type in listener_map) {
1209
- listener_map && ((_a = listener_map[event_type]) == null ? void 0 : _a.forEach((fn2) => {
1210
- off(event_type, fn2);
1211
- }));
1494
+ if (all_events || events_to_publish[event.type]) {
1495
+ push_event(event);
1496
+ }
1497
+ }, close = function() {
1498
+ done = true;
1499
+ while (resolvers.length > 0)
1500
+ resolvers.shift()({
1501
+ value: void 0,
1502
+ done: true
1503
+ });
1504
+ }, push = function(data2) {
1505
+ if (done)
1506
+ return;
1507
+ if (resolvers.length > 0) {
1508
+ resolvers.shift()(data2);
1509
+ } else {
1510
+ values.push(data2);
1212
1511
  }
1512
+ }, push_error = function(error) {
1513
+ push(thenable_reject(error));
1514
+ close();
1515
+ }, push_event = function(event) {
1516
+ push({ value: event, done: false });
1517
+ }, next = function() {
1518
+ if (values.length > 0)
1519
+ return Promise.resolve(values.shift());
1520
+ if (done)
1521
+ return Promise.resolve({ value: void 0, done: true });
1522
+ return new Promise((resolve) => resolvers.push(resolve));
1213
1523
  };
1214
1524
  const { hf_token } = this.options;
1215
1525
  const {
@@ -1224,8 +1534,10 @@ function submit(endpoint, data, event_data, trigger_id) {
1224
1534
  pending_diff_streams,
1225
1535
  event_callbacks,
1226
1536
  unclosed_events,
1227
- post_data: post_data2
1537
+ post_data: post_data2,
1538
+ options
1228
1539
  } = this;
1540
+ const that = this;
1229
1541
  if (!api_info)
1230
1542
  throw new Error("No API found");
1231
1543
  if (!config)
@@ -1238,15 +1550,21 @@ function submit(endpoint, data, event_data, trigger_id) {
1238
1550
  );
1239
1551
  let resolved_data = map_data_to_params(data, api_info);
1240
1552
  let websocket;
1241
- let stream;
1553
+ let stream2;
1242
1554
  let protocol = config.protocol ?? "ws";
1243
1555
  const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
1244
1556
  let payload;
1245
1557
  let event_id = null;
1246
1558
  let complete = false;
1247
- const listener_map = {};
1248
1559
  let last_status = {};
1249
- let url_params = typeof window !== "undefined" ? new URLSearchParams(window.location.search).toString() : "";
1560
+ let url_params = typeof window !== "undefined" && typeof document !== "undefined" ? new URLSearchParams(window.location.search).toString() : "";
1561
+ const events_to_publish = ((_a = options == null ? void 0 : options.events) == null ? void 0 : _a.reduce(
1562
+ (acc, event) => {
1563
+ acc[event] = true;
1564
+ return acc;
1565
+ },
1566
+ {}
1567
+ )) || {};
1250
1568
  async function cancel() {
1251
1569
  const _status = {
1252
1570
  stage: "complete",
@@ -1260,6 +1578,7 @@ function submit(endpoint, data, event_data, trigger_id) {
1260
1578
  endpoint: _endpoint,
1261
1579
  fn_index
1262
1580
  });
1581
+ let reset_request = {};
1263
1582
  let cancel_request = {};
1264
1583
  if (protocol === "ws") {
1265
1584
  if (websocket && websocket.readyState === 0) {
@@ -1269,19 +1588,28 @@ function submit(endpoint, data, event_data, trigger_id) {
1269
1588
  } else {
1270
1589
  websocket.close();
1271
1590
  }
1272
- cancel_request = { fn_index, session_hash };
1591
+ reset_request = { fn_index, session_hash };
1273
1592
  } else {
1274
- stream == null ? void 0 : stream.close();
1275
- cancel_request = { event_id };
1593
+ close_stream(stream_status, that.abort_controller);
1594
+ close();
1595
+ reset_request = { event_id };
1596
+ cancel_request = { event_id, session_hash, fn_index };
1276
1597
  }
1277
1598
  try {
1278
1599
  if (!config) {
1279
1600
  throw new Error("Could not resolve app config");
1280
1601
  }
1602
+ if ("event_id" in cancel_request) {
1603
+ await fetch2(`${config.root}/cancel`, {
1604
+ headers: { "Content-Type": "application/json" },
1605
+ method: "POST",
1606
+ body: JSON.stringify(cancel_request)
1607
+ });
1608
+ }
1281
1609
  await fetch2(`${config.root}/reset`, {
1282
1610
  headers: { "Content-Type": "application/json" },
1283
1611
  method: "POST",
1284
- body: JSON.stringify(cancel_request)
1612
+ body: JSON.stringify(reset_request)
1285
1613
  });
1286
1614
  } catch (e) {
1287
1615
  console.warn(
@@ -1319,9 +1647,16 @@ function submit(endpoint, data, event_data, trigger_id) {
1319
1647
  }
1320
1648
  this.handle_blob(config.root, resolved_data, endpoint_info).then(
1321
1649
  async (_payload) => {
1322
- var _a;
1650
+ var _a2;
1651
+ let input_data = handle_payload(
1652
+ _payload,
1653
+ dependency,
1654
+ config.components,
1655
+ "input",
1656
+ true
1657
+ );
1323
1658
  payload = {
1324
- data: _payload || [],
1659
+ data: input_data || [],
1325
1660
  event_data,
1326
1661
  fn_index,
1327
1662
  trigger_id
@@ -1348,7 +1683,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1348
1683
  type: "data",
1349
1684
  endpoint: _endpoint,
1350
1685
  fn_index,
1351
- data: data2,
1686
+ data: handle_payload(
1687
+ data2,
1688
+ dependency,
1689
+ config.components,
1690
+ "output",
1691
+ options.with_null_state
1692
+ ),
1352
1693
  time: /* @__PURE__ */ new Date(),
1353
1694
  event_data,
1354
1695
  trigger_id
@@ -1472,7 +1813,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1472
1813
  fire_event({
1473
1814
  type: "data",
1474
1815
  time: /* @__PURE__ */ new Date(),
1475
- data: data2.data,
1816
+ data: handle_payload(
1817
+ data2.data,
1818
+ dependency,
1819
+ config.components,
1820
+ "output",
1821
+ options.with_null_state
1822
+ ),
1476
1823
  endpoint: _endpoint,
1477
1824
  fn_index,
1478
1825
  event_data,
@@ -1517,13 +1864,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1517
1864
  if (this.jwt) {
1518
1865
  url.searchParams.set("__sign", this.jwt);
1519
1866
  }
1520
- stream = await this.stream(url);
1521
- if (!stream) {
1867
+ stream2 = this.stream(url);
1868
+ if (!stream2) {
1522
1869
  return Promise.reject(
1523
1870
  new Error("Cannot connect to SSE endpoint: " + url.toString())
1524
1871
  );
1525
1872
  }
1526
- stream.onmessage = async function(event) {
1873
+ stream2.onmessage = async function(event) {
1527
1874
  const _data = JSON.parse(event.data);
1528
1875
  const { type, status, data: data2 } = handle_message(
1529
1876
  _data,
@@ -1538,7 +1885,8 @@ function submit(endpoint, data, event_data, trigger_id) {
1538
1885
  ...status
1539
1886
  });
1540
1887
  if (status.stage === "error") {
1541
- stream == null ? void 0 : stream.close();
1888
+ stream2 == null ? void 0 : stream2.close();
1889
+ close();
1542
1890
  }
1543
1891
  } else if (type === "data") {
1544
1892
  event_id = _data.event_id;
@@ -1557,7 +1905,8 @@ function submit(endpoint, data, event_data, trigger_id) {
1557
1905
  fn_index,
1558
1906
  time: /* @__PURE__ */ new Date()
1559
1907
  });
1560
- stream == null ? void 0 : stream.close();
1908
+ stream2 == null ? void 0 : stream2.close();
1909
+ close();
1561
1910
  }
1562
1911
  } else if (type === "complete") {
1563
1912
  complete = status;
@@ -1584,7 +1933,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1584
1933
  fire_event({
1585
1934
  type: "data",
1586
1935
  time: /* @__PURE__ */ new Date(),
1587
- data: data2.data,
1936
+ data: handle_payload(
1937
+ data2.data,
1938
+ dependency,
1939
+ config.components,
1940
+ "output",
1941
+ options.with_null_state
1942
+ ),
1588
1943
  endpoint: _endpoint,
1589
1944
  fn_index,
1590
1945
  event_data,
@@ -1600,7 +1955,8 @@ function submit(endpoint, data, event_data, trigger_id) {
1600
1955
  endpoint: _endpoint,
1601
1956
  fn_index
1602
1957
  });
1603
- stream == null ? void 0 : stream.close();
1958
+ stream2 == null ? void 0 : stream2.close();
1959
+ close();
1604
1960
  }
1605
1961
  }
1606
1962
  };
@@ -1614,12 +1970,12 @@ function submit(endpoint, data, event_data, trigger_id) {
1614
1970
  time: /* @__PURE__ */ new Date()
1615
1971
  });
1616
1972
  let hostname = "";
1617
- if (typeof window !== "undefined") {
1618
- hostname = (_a = window == null ? void 0 : window.location) == null ? void 0 : _a.hostname;
1973
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1974
+ hostname = (_a2 = window == null ? void 0 : window.location) == null ? void 0 : _a2.hostname;
1619
1975
  }
1620
1976
  let hfhubdev = "dev.spaces.huggingface.tech";
1621
1977
  const origin = hostname.includes(".dev.") ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}` : `https://huggingface.co`;
1622
- const is_iframe = typeof window !== "undefined" && window.parent != window;
1978
+ const is_iframe = typeof window !== "undefined" && typeof document !== "undefined" && window.parent != window;
1623
1979
  const is_zerogpu_space = dependency.zerogpu && config.space_id;
1624
1980
  const zerogpu_auth_promise = is_iframe && is_zerogpu_space ? post_message("zerogpu-headers", origin) : Promise.resolve(null);
1625
1981
  const post_data_promise = zerogpu_auth_promise.then((headers) => {
@@ -1712,7 +2068,13 @@ function submit(endpoint, data, event_data, trigger_id) {
1712
2068
  fire_event({
1713
2069
  type: "data",
1714
2070
  time: /* @__PURE__ */ new Date(),
1715
- data: data2.data,
2071
+ data: handle_payload(
2072
+ data2.data,
2073
+ dependency,
2074
+ config.components,
2075
+ "output",
2076
+ options.with_null_state
2077
+ ),
1716
2078
  endpoint: _endpoint,
1717
2079
  fn_index
1718
2080
  });
@@ -1750,9 +2112,10 @@ function submit(endpoint, data, event_data, trigger_id) {
1750
2112
  fn_index,
1751
2113
  time: /* @__PURE__ */ new Date()
1752
2114
  });
1753
- if (["sse_v2", "sse_v2.1"].includes(protocol)) {
1754
- close_stream(stream_status, stream);
2115
+ if (["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) {
2116
+ close_stream(stream_status, that.abort_controller);
1755
2117
  stream_status.open = false;
2118
+ close();
1756
2119
  }
1757
2120
  }
1758
2121
  };
@@ -1772,12 +2135,33 @@ function submit(endpoint, data, event_data, trigger_id) {
1772
2135
  }
1773
2136
  }
1774
2137
  );
1775
- return { on, off, cancel, destroy };
2138
+ let done = false;
2139
+ const values = [];
2140
+ const resolvers = [];
2141
+ const iterator = {
2142
+ [Symbol.asyncIterator]: () => iterator,
2143
+ next,
2144
+ throw: async (value) => {
2145
+ push_error(value);
2146
+ return next();
2147
+ },
2148
+ return: async () => {
2149
+ close();
2150
+ return next();
2151
+ },
2152
+ cancel
2153
+ };
2154
+ return iterator;
1776
2155
  } catch (error) {
1777
2156
  console.error("Submit function encountered an error:", error);
1778
2157
  throw error;
1779
2158
  }
1780
2159
  }
2160
+ function thenable_reject(error) {
2161
+ return {
2162
+ then: (resolve, reject) => reject(error)
2163
+ };
2164
+ }
1781
2165
  function get_endpoint_info(api_info, endpoint, api_map, config) {
1782
2166
  let fn_index;
1783
2167
  let endpoint_info;
@@ -1801,13 +2185,8 @@ function get_endpoint_info(api_info, endpoint, api_map, config) {
1801
2185
  }
1802
2186
  return { fn_index, endpoint_info, dependency };
1803
2187
  }
1804
- class NodeBlob extends Blob {
1805
- constructor(blobParts, options) {
1806
- super(blobParts, options);
1807
- }
1808
- }
1809
2188
  class Client {
1810
- constructor(app_reference, options = {}) {
2189
+ constructor(app_reference, options = { events: ["data"] }) {
1811
2190
  __publicField(this, "app_reference");
1812
2191
  __publicField(this, "options");
1813
2192
  __publicField(this, "config");
@@ -1824,6 +2203,8 @@ class Client {
1824
2203
  __publicField(this, "event_callbacks", {});
1825
2204
  __publicField(this, "unclosed_events", /* @__PURE__ */ new Set());
1826
2205
  __publicField(this, "heartbeat_event", null);
2206
+ __publicField(this, "abort_controller", null);
2207
+ __publicField(this, "stream_instance", null);
1827
2208
  __publicField(this, "view_api");
1828
2209
  __publicField(this, "upload_files");
1829
2210
  __publicField(this, "upload");
@@ -1835,6 +2216,9 @@ class Client {
1835
2216
  __publicField(this, "resolve_config");
1836
2217
  __publicField(this, "resolve_cookies");
1837
2218
  this.app_reference = app_reference;
2219
+ if (!options.events) {
2220
+ options.events = ["data"];
2221
+ }
1838
2222
  this.options = options;
1839
2223
  this.view_api = view_api.bind(this);
1840
2224
  this.upload_files = upload_files.bind(this);
@@ -1854,24 +2238,17 @@ class Client {
1854
2238
  }
1855
2239
  return fetch(input, { ...init, headers });
1856
2240
  }
1857
- async stream(url) {
1858
- if (typeof window === "undefined" || typeof EventSource === "undefined") {
1859
- try {
1860
- const EventSourceModule = await import("eventsource");
1861
- return new EventSourceModule.default(url.toString());
1862
- } catch (error) {
1863
- console.error("Failed to load EventSource module:", error);
1864
- throw error;
1865
- }
1866
- } else {
1867
- return new EventSource(url.toString());
1868
- }
2241
+ stream(url) {
2242
+ this.abort_controller = new AbortController();
2243
+ this.stream_instance = readable_stream(url.toString(), {
2244
+ signal: this.abort_controller.signal
2245
+ });
2246
+ return this.stream_instance;
1869
2247
  }
1870
2248
  async init() {
1871
2249
  var _a;
1872
2250
  if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.WebSocket) {
1873
2251
  const ws = await import("./wrapper-CviSselG.js");
1874
- NodeBlob = (await import("node:buffer")).Blob;
1875
2252
  global.WebSocket = ws.WebSocket;
1876
2253
  }
1877
2254
  try {
@@ -1888,7 +2265,6 @@ class Client {
1888
2265
  this.api_map = map_names_to_ids(((_a = this.config) == null ? void 0 : _a.dependencies) || []);
1889
2266
  }
1890
2267
  async _resolve_hearbeat(_config) {
1891
- var _a;
1892
2268
  if (_config) {
1893
2269
  this.config = _config;
1894
2270
  if (this.config && this.config.connect_heartbeat) {
@@ -1911,13 +2287,14 @@ class Client {
1911
2287
  if (this.jwt) {
1912
2288
  heartbeat_url.searchParams.set("__sign", this.jwt);
1913
2289
  }
1914
- if (!this.heartbeat_event)
1915
- this.heartbeat_event = await this.stream(heartbeat_url);
1916
- } else {
1917
- (_a = this.heartbeat_event) == null ? void 0 : _a.close();
2290
+ if (!this.heartbeat_event) {
2291
+ this.heartbeat_event = this.stream(heartbeat_url);
2292
+ }
1918
2293
  }
1919
2294
  }
1920
- static async connect(app_reference, options = {}) {
2295
+ static async connect(app_reference, options = {
2296
+ events: ["data"]
2297
+ }) {
1921
2298
  const client2 = new this(app_reference, options);
1922
2299
  await client2.init();
1923
2300
  return client2;
@@ -1926,7 +2303,9 @@ class Client {
1926
2303
  var _a;
1927
2304
  (_a = this.heartbeat_event) == null ? void 0 : _a.close();
1928
2305
  }
1929
- static async duplicate(app_reference, options = {}) {
2306
+ static async duplicate(app_reference, options = {
2307
+ events: ["data"]
2308
+ }) {
1930
2309
  return duplicate(app_reference, options);
1931
2310
  }
1932
2311
  async _resolve_config() {
@@ -1963,7 +2342,7 @@ class Client {
1963
2342
  }
1964
2343
  async config_success(_config) {
1965
2344
  this.config = _config;
1966
- if (typeof window !== "undefined") {
2345
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
1967
2346
  if (window.location.protocol === "https:") {
1968
2347
  this.config.root = this.config.root.replace("http://", "https://");
1969
2348
  }
@@ -2080,7 +2459,9 @@ class Client {
2080
2459
  };
2081
2460
  }
2082
2461
  }
2083
- async function client(app_reference, options = {}) {
2462
+ async function client(app_reference, options = {
2463
+ events: ["data"]
2464
+ }) {
2084
2465
  return await Client.connect(app_reference, options);
2085
2466
  }
2086
2467
  async function duplicate_space(app_reference, options) {
@@ -2091,6 +2472,7 @@ export {
2091
2472
  FileData,
2092
2473
  client,
2093
2474
  duplicate_space as duplicate,
2475
+ handle_file,
2094
2476
  predict,
2095
2477
  prepare_files,
2096
2478
  submit,