@gradio/client 0.16.0 → 0.18.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 (84) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +49 -43
  3. package/dist/client.d.ts +63 -70
  4. package/dist/client.d.ts.map +1 -1
  5. package/dist/constants.d.ts +23 -0
  6. package/dist/constants.d.ts.map +1 -0
  7. package/dist/helpers/api_info.d.ts +25 -0
  8. package/dist/helpers/api_info.d.ts.map +1 -0
  9. package/dist/helpers/data.d.ts +8 -0
  10. package/dist/helpers/data.d.ts.map +1 -0
  11. package/dist/{utils.d.ts → helpers/init_helpers.d.ts} +6 -18
  12. package/dist/helpers/init_helpers.d.ts.map +1 -0
  13. package/dist/helpers/spaces.d.ts +7 -0
  14. package/dist/helpers/spaces.d.ts.map +1 -0
  15. package/dist/index.d.ts +8 -4
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1628 -1398
  18. package/dist/test/handlers.d.ts +3 -0
  19. package/dist/test/handlers.d.ts.map +1 -0
  20. package/dist/test/mock_eventsource.d.ts +2 -0
  21. package/dist/test/mock_eventsource.d.ts.map +1 -0
  22. package/dist/test/server.d.ts +2 -0
  23. package/dist/test/server.d.ts.map +1 -0
  24. package/dist/test/test_data.d.ts +76 -0
  25. package/dist/test/test_data.d.ts.map +1 -0
  26. package/dist/types.d.ts +153 -49
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/upload.d.ts +2 -2
  29. package/dist/upload.d.ts.map +1 -1
  30. package/dist/utils/duplicate.d.ts +4 -0
  31. package/dist/utils/duplicate.d.ts.map +1 -0
  32. package/dist/utils/handle_blob.d.ts +4 -0
  33. package/dist/utils/handle_blob.d.ts.map +1 -0
  34. package/dist/utils/post_data.d.ts +4 -0
  35. package/dist/utils/post_data.d.ts.map +1 -0
  36. package/dist/utils/predict.d.ts +4 -0
  37. package/dist/utils/predict.d.ts.map +1 -0
  38. package/dist/utils/stream.d.ts +8 -0
  39. package/dist/utils/stream.d.ts.map +1 -0
  40. package/dist/utils/submit.d.ts +4 -0
  41. package/dist/utils/submit.d.ts.map +1 -0
  42. package/dist/utils/upload_files.d.ts +4 -0
  43. package/dist/utils/upload_files.d.ts.map +1 -0
  44. package/dist/utils/view_api.d.ts +3 -0
  45. package/dist/utils/view_api.d.ts.map +1 -0
  46. package/dist/{wrapper-6f348d45.js → wrapper-CviSselG.js} +259 -17
  47. package/package.json +10 -3
  48. package/src/client.ts +314 -1691
  49. package/src/constants.ts +27 -0
  50. package/src/globals.d.ts +2 -21
  51. package/src/helpers/api_info.ts +300 -0
  52. package/src/helpers/data.ts +133 -0
  53. package/src/helpers/init_helpers.ts +130 -0
  54. package/src/helpers/spaces.ts +197 -0
  55. package/src/index.ts +16 -10
  56. package/src/test/api_info.test.ts +456 -0
  57. package/src/test/data.test.ts +281 -0
  58. package/src/test/handlers.ts +438 -0
  59. package/src/test/init.test.ts +139 -0
  60. package/src/test/init_helpers.test.ts +94 -0
  61. package/src/test/mock_eventsource.ts +11 -0
  62. package/src/test/post_data.test.ts +45 -0
  63. package/src/test/server.ts +6 -0
  64. package/src/test/spaces.test.ts +145 -0
  65. package/src/test/stream.test.ts +67 -0
  66. package/src/test/test_data.ts +557 -0
  67. package/src/test/upload_files.test.ts +42 -0
  68. package/src/test/view_api.test.ts +53 -0
  69. package/src/types.ts +201 -59
  70. package/src/upload.ts +19 -15
  71. package/src/utils/duplicate.ts +104 -0
  72. package/src/utils/handle_blob.ts +47 -0
  73. package/src/utils/post_data.ts +37 -0
  74. package/src/utils/predict.ts +56 -0
  75. package/src/utils/stream.ts +175 -0
  76. package/src/utils/submit.ts +697 -0
  77. package/src/utils/upload_files.ts +51 -0
  78. package/src/utils/view_api.ts +67 -0
  79. package/src/vite-env.d.ts +1 -0
  80. package/tsconfig.json +15 -2
  81. package/vite.config.js +11 -17
  82. package/dist/utils.d.ts.map +0 -1
  83. package/src/client.node-test.ts +0 -172
  84. package/src/utils.ts +0 -314
package/dist/index.js CHANGED
@@ -1,15 +1,77 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
1
7
  var fn = new Intl.Collator(0, { numeric: 1 }).compare;
2
- function semiver(a, b, bool) {
8
+ function semiver$1(a, b, bool) {
3
9
  a = a.split(".");
4
10
  b = b.split(".");
5
11
  return fn(a[0], b[0]) || fn(a[1], b[1]) || (b[2] = b.slice(2).join("."), bool = /[.-]/.test(a[2] = a.slice(2).join(".")), bool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1);
6
12
  }
13
+ const UPLOAD_URL = "upload";
14
+ const CONFIG_URL = "config";
15
+ const API_INFO_URL = "info";
16
+ const RUNTIME_URL = "runtime";
17
+ const SLEEPTIME_URL = "sleeptime";
18
+ const SPACE_FETCHER_URL = "https://gradio-space-api-fetcher-v2.hf.space/api";
19
+ const QUEUE_FULL_MSG = "This application is currently busy. Please try again. ";
20
+ const BROKEN_CONNECTION_MSG = "Connection errored out. ";
21
+ const CONFIG_ERROR_MSG = "Could not resolve app config. ";
22
+ const SPACE_STATUS_ERROR_MSG = "Could not get space status. ";
23
+ const API_INFO_ERROR_MSG = "Could not get API info. ";
24
+ const SPACE_METADATA_ERROR_MSG = "Space metadata could not be loaded. ";
7
25
  function resolve_root(base_url, root_path, prioritize_base) {
8
26
  if (root_path.startsWith("http://") || root_path.startsWith("https://")) {
9
27
  return prioritize_base ? base_url : root_path;
10
28
  }
11
29
  return base_url + root_path;
12
30
  }
31
+ async function get_jwt(space, token) {
32
+ try {
33
+ const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
34
+ headers: {
35
+ Authorization: `Bearer ${token}`
36
+ }
37
+ });
38
+ const jwt = (await r.json()).token;
39
+ return jwt || false;
40
+ } catch (e) {
41
+ return false;
42
+ }
43
+ }
44
+ function map_names_to_ids(fns) {
45
+ let apis = {};
46
+ fns.forEach(({ api_name }, i) => {
47
+ if (api_name)
48
+ apis[api_name] = i;
49
+ });
50
+ return apis;
51
+ }
52
+ async function resolve_config(endpoint) {
53
+ const headers = this.options.hf_token ? { Authorization: `Bearer ${this.options.hf_token}` } : {};
54
+ headers["Content-Type"] = "application/json";
55
+ if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) {
56
+ const path = window.gradio_config.root;
57
+ const config = window.gradio_config;
58
+ let config_root = resolve_root(endpoint, config.root, false);
59
+ config.root = config_root;
60
+ return { ...config, path };
61
+ } else if (endpoint) {
62
+ const response = await this.fetch(`${endpoint}/${CONFIG_URL}`, {
63
+ headers
64
+ });
65
+ if ((response == null ? void 0 : response.status) === 200) {
66
+ let config = await response.json();
67
+ config.path = config.path ?? "";
68
+ config.root = endpoint;
69
+ return config;
70
+ }
71
+ throw new Error(CONFIG_ERROR_MSG);
72
+ }
73
+ throw new Error(CONFIG_ERROR_MSG);
74
+ }
13
75
  function determine_protocol(endpoint) {
14
76
  if (endpoint.startsWith("http")) {
15
77
  const { protocol, host } = new URL(endpoint);
@@ -41,10 +103,10 @@ function determine_protocol(endpoint) {
41
103
  }
42
104
  const RE_SPACE_NAME = /^[^\/]*\/[^\/]*$/;
43
105
  const RE_SPACE_DOMAIN = /.*hf\.space\/{0,1}$/;
44
- async function process_endpoint(app_reference, token) {
106
+ async function process_endpoint(app_reference, hf_token) {
45
107
  const headers = {};
46
- if (token) {
47
- headers.Authorization = `Bearer ${token}`;
108
+ if (hf_token) {
109
+ headers.Authorization = `Bearer ${hf_token}`;
48
110
  }
49
111
  const _app_reference = app_reference.trim();
50
112
  if (RE_SPACE_NAME.test(_app_reference)) {
@@ -53,15 +115,15 @@ async function process_endpoint(app_reference, token) {
53
115
  `https://huggingface.co/api/spaces/${_app_reference}/host`,
54
116
  { headers }
55
117
  );
56
- if (res.status !== 200)
57
- throw new Error("Space metadata could not be loaded.");
58
118
  const _host = (await res.json()).host;
59
119
  return {
60
120
  space_id: app_reference,
61
121
  ...determine_protocol(_host)
62
122
  };
63
123
  } catch (e) {
64
- throw new Error("Space metadata could not be loaded." + e.message);
124
+ throw new Error(
125
+ "Space metadata could not be loaded. " + e.message
126
+ );
65
127
  }
66
128
  }
67
129
  if (RE_SPACE_DOMAIN.test(_app_reference)) {
@@ -78,160 +140,276 @@ async function process_endpoint(app_reference, token) {
78
140
  ...determine_protocol(_app_reference)
79
141
  };
80
142
  }
81
- function map_names_to_ids(fns) {
82
- let apis = {};
83
- fns.forEach(({ api_name }, i) => {
84
- if (api_name)
85
- apis[api_name] = i;
143
+ function transform_api_info(api_info, config, api_map) {
144
+ const transformed_info = {
145
+ named_endpoints: {},
146
+ unnamed_endpoints: {}
147
+ };
148
+ Object.keys(api_info).forEach((category) => {
149
+ if (category === "named_endpoints" || category === "unnamed_endpoints") {
150
+ transformed_info[category] = {};
151
+ Object.entries(api_info[category]).forEach(
152
+ ([endpoint, { parameters, returns }]) => {
153
+ const dependencyIndex = config.dependencies.findIndex((dep) => dep.api_name === endpoint) || api_map[endpoint.replace("/", "")] || -1;
154
+ const dependencyTypes = dependencyIndex !== -1 ? config.dependencies[dependencyIndex].types : { continuous: false, generator: false };
155
+ const transform_type = (data, component, serializer, signature_type) => ({
156
+ ...data,
157
+ description: get_description(data.type, serializer),
158
+ type: get_type(data.type, component, serializer, signature_type) || ""
159
+ });
160
+ transformed_info[category][endpoint] = {
161
+ parameters: parameters.map(
162
+ (p) => transform_type(p, p.component, p.serializer, "parameter")
163
+ ),
164
+ returns: returns.map(
165
+ (r) => transform_type(r, r.component, r.serializer, "return")
166
+ ),
167
+ type: dependencyTypes
168
+ };
169
+ }
170
+ );
171
+ }
86
172
  });
87
- return apis;
173
+ return transformed_info;
88
174
  }
89
- const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
90
- async function discussions_enabled(space_id) {
91
- try {
92
- const r = await fetch(
93
- `https://huggingface.co/api/spaces/${space_id}/discussions`,
94
- {
95
- method: "HEAD"
96
- }
97
- );
98
- const error = r.headers.get("x-error-message");
99
- if (error && RE_DISABLED_DISCUSSION.test(error))
100
- return false;
101
- return true;
102
- } catch (e) {
103
- return false;
175
+ function get_type(type, component, serializer, signature_type) {
176
+ switch (type.type) {
177
+ case "string":
178
+ return "string";
179
+ case "boolean":
180
+ return "boolean";
181
+ case "number":
182
+ return "number";
183
+ }
184
+ if (serializer === "JSONSerializable" || serializer === "StringSerializable") {
185
+ return "any";
186
+ } else if (serializer === "ListStringSerializable") {
187
+ return "string[]";
188
+ } else if (component === "Image") {
189
+ return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
190
+ } else if (serializer === "FileSerializable") {
191
+ if ((type == null ? void 0 : type.type) === "array") {
192
+ return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
193
+ }
194
+ return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
195
+ } else if (serializer === "GallerySerializable") {
196
+ return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
104
197
  }
105
198
  }
106
- async function get_space_hardware(space_id, token) {
107
- const headers = {};
108
- if (token) {
109
- headers.Authorization = `Bearer ${token}`;
199
+ function get_description(type, serializer) {
200
+ if (serializer === "GallerySerializable") {
201
+ return "array of [file, label] tuples";
202
+ } else if (serializer === "ListStringSerializable") {
203
+ return "array of strings";
204
+ } else if (serializer === "FileSerializable") {
205
+ return "array of files or single file";
110
206
  }
111
- try {
112
- const res = await fetch(
113
- `https://huggingface.co/api/spaces/${space_id}/runtime`,
114
- { headers }
115
- );
116
- if (res.status !== 200)
117
- throw new Error("Space hardware could not be obtained.");
118
- const { hardware } = await res.json();
119
- return hardware;
120
- } catch (e) {
121
- throw new Error(e.message);
207
+ return type.description;
208
+ }
209
+ function handle_message(data, last_status) {
210
+ const queue = true;
211
+ switch (data.msg) {
212
+ case "send_data":
213
+ return { type: "data" };
214
+ case "send_hash":
215
+ return { type: "hash" };
216
+ case "queue_full":
217
+ return {
218
+ type: "update",
219
+ status: {
220
+ queue,
221
+ message: QUEUE_FULL_MSG,
222
+ stage: "error",
223
+ code: data.code,
224
+ success: data.success
225
+ }
226
+ };
227
+ case "heartbeat":
228
+ return {
229
+ type: "heartbeat"
230
+ };
231
+ case "unexpected_error":
232
+ return {
233
+ type: "unexpected_error",
234
+ status: {
235
+ queue,
236
+ message: data.message,
237
+ stage: "error",
238
+ success: false
239
+ }
240
+ };
241
+ case "estimation":
242
+ return {
243
+ type: "update",
244
+ status: {
245
+ queue,
246
+ stage: last_status || "pending",
247
+ code: data.code,
248
+ size: data.queue_size,
249
+ position: data.rank,
250
+ eta: data.rank_eta,
251
+ success: data.success
252
+ }
253
+ };
254
+ case "progress":
255
+ return {
256
+ type: "update",
257
+ status: {
258
+ queue,
259
+ stage: "pending",
260
+ code: data.code,
261
+ progress_data: data.progress_data,
262
+ success: data.success
263
+ }
264
+ };
265
+ case "log":
266
+ return { type: "log", data };
267
+ case "process_generating":
268
+ return {
269
+ type: "generating",
270
+ status: {
271
+ queue,
272
+ message: !data.success ? data.output.error : null,
273
+ stage: data.success ? "generating" : "error",
274
+ code: data.code,
275
+ progress_data: data.progress_data,
276
+ eta: data.average_duration
277
+ },
278
+ data: data.success ? data.output : null
279
+ };
280
+ case "process_completed":
281
+ if ("error" in data.output) {
282
+ return {
283
+ type: "update",
284
+ status: {
285
+ queue,
286
+ message: data.output.error,
287
+ stage: "error",
288
+ code: data.code,
289
+ success: data.success
290
+ }
291
+ };
292
+ }
293
+ return {
294
+ type: "complete",
295
+ status: {
296
+ queue,
297
+ message: !data.success ? data.output.error : void 0,
298
+ stage: data.success ? "complete" : "error",
299
+ code: data.code,
300
+ progress_data: data.progress_data
301
+ },
302
+ data: data.success ? data.output : null
303
+ };
304
+ case "process_starts":
305
+ return {
306
+ type: "update",
307
+ status: {
308
+ queue,
309
+ stage: "pending",
310
+ code: data.code,
311
+ size: data.rank,
312
+ position: 0,
313
+ success: data.success,
314
+ eta: data.eta
315
+ }
316
+ };
122
317
  }
318
+ return { type: "none", status: { stage: "error", queue } };
123
319
  }
124
- async function set_space_hardware(space_id, new_hardware, token) {
125
- const headers = {};
126
- if (token) {
127
- headers.Authorization = `Bearer ${token}`;
320
+ async function view_api() {
321
+ if (this.api_info)
322
+ return this.api_info;
323
+ const { hf_token } = this.options;
324
+ const { config } = this;
325
+ const headers = { "Content-Type": "application/json" };
326
+ if (hf_token) {
327
+ headers.Authorization = `Bearer ${hf_token}`;
328
+ }
329
+ if (!config) {
330
+ return;
128
331
  }
129
332
  try {
130
- const res = await fetch(
131
- `https://huggingface.co/api/spaces/${space_id}/hardware`,
132
- { headers, body: JSON.stringify(new_hardware) }
133
- );
134
- if (res.status !== 200)
135
- throw new Error(
136
- "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
137
- );
138
- const { hardware } = await res.json();
139
- return hardware;
333
+ let response;
334
+ if (semiver$1((config == null ? void 0 : config.version) || "2.0.0", "3.30") < 0) {
335
+ response = await this.fetch(SPACE_FETCHER_URL, {
336
+ method: "POST",
337
+ body: JSON.stringify({
338
+ serialize: false,
339
+ config: JSON.stringify(config)
340
+ }),
341
+ headers
342
+ });
343
+ } else {
344
+ response = await this.fetch(`${config == null ? void 0 : config.root}/${API_INFO_URL}`, {
345
+ headers
346
+ });
347
+ }
348
+ if (!response.ok) {
349
+ throw new Error(BROKEN_CONNECTION_MSG);
350
+ }
351
+ let api_info = await response.json();
352
+ if ("api" in api_info) {
353
+ api_info = api_info.api;
354
+ }
355
+ if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) {
356
+ api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
357
+ }
358
+ return transform_api_info(api_info, config, this.api_map);
140
359
  } catch (e) {
141
- throw new Error(e.message);
360
+ "Could not get API info. " + e.message;
142
361
  }
143
362
  }
144
- async function set_space_timeout(space_id, timeout, token) {
363
+ async function upload_files(root_url, files, upload_id) {
364
+ var _a;
145
365
  const headers = {};
146
- if (token) {
147
- headers.Authorization = `Bearer ${token}`;
366
+ if ((_a = this == null ? void 0 : this.options) == null ? void 0 : _a.hf_token) {
367
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
148
368
  }
149
- try {
150
- const res = await fetch(
151
- `https://huggingface.co/api/spaces/${space_id}/hardware`,
152
- { headers, body: JSON.stringify({ seconds: timeout }) }
153
- );
154
- if (res.status !== 200)
155
- throw new Error(
156
- "Space hardware could not be set. Please ensure the space hardware provided is valid and that a Hugging Face token is passed in."
157
- );
158
- const { hardware } = await res.json();
159
- return hardware;
160
- } catch (e) {
161
- throw new Error(e.message);
369
+ const chunkSize = 1e3;
370
+ const uploadResponses = [];
371
+ let response;
372
+ for (let i = 0; i < files.length; i += chunkSize) {
373
+ const chunk = files.slice(i, i + chunkSize);
374
+ const formData = new FormData();
375
+ chunk.forEach((file) => {
376
+ formData.append("files", file);
377
+ });
378
+ try {
379
+ const upload_url = upload_id ? `${root_url}/upload?upload_id=${upload_id}` : `${root_url}/${UPLOAD_URL}`;
380
+ response = await this.fetch(upload_url, {
381
+ method: "POST",
382
+ body: formData,
383
+ headers
384
+ });
385
+ } catch (e) {
386
+ throw new Error(BROKEN_CONNECTION_MSG + e.message);
387
+ }
388
+ if (!response.ok) {
389
+ const error_text = await response.text();
390
+ return { error: `HTTP ${response.status}: ${error_text}` };
391
+ }
392
+ const output = await response.json();
393
+ if (output) {
394
+ uploadResponses.push(...output);
395
+ }
162
396
  }
397
+ return { files: uploadResponses };
163
398
  }
164
- const hardware_types = [
165
- "cpu-basic",
166
- "cpu-upgrade",
167
- "t4-small",
168
- "t4-medium",
169
- "a10g-small",
170
- "a10g-large",
171
- "a100-large"
172
- ];
173
- function apply_edit(target, path, action, value) {
174
- if (path.length === 0) {
175
- if (action === "replace") {
176
- return value;
177
- } else if (action === "append") {
178
- return target + value;
179
- }
180
- throw new Error(`Unsupported action: ${action}`);
181
- }
182
- let current = target;
183
- for (let i = 0; i < path.length - 1; i++) {
184
- current = current[path[i]];
185
- }
186
- const last_path = path[path.length - 1];
187
- switch (action) {
188
- case "replace":
189
- current[last_path] = value;
190
- break;
191
- case "append":
192
- current[last_path] += value;
193
- break;
194
- case "add":
195
- if (Array.isArray(current)) {
196
- current.splice(Number(last_path), 0, value);
197
- } else {
198
- current[last_path] = value;
199
- }
200
- break;
201
- case "delete":
202
- if (Array.isArray(current)) {
203
- current.splice(Number(last_path), 1);
204
- } else {
205
- delete current[last_path];
206
- }
207
- break;
208
- default:
209
- throw new Error(`Unknown action: ${action}`);
210
- }
211
- return target;
212
- }
213
- function apply_diff(obj, diff) {
214
- diff.forEach(([action, path, value]) => {
215
- obj = apply_edit(obj, path, action, value);
216
- });
217
- return obj;
218
- }
219
- function post_message(message, origin) {
220
- return new Promise((res, _rej) => {
221
- const channel = new MessageChannel();
222
- channel.port1.onmessage = ({ data }) => {
223
- channel.port1.close();
224
- res(data);
225
- };
226
- window.parent.postMessage(message, origin, [channel.port2]);
227
- });
228
- }
229
- async function upload(file_data, root, upload_id, upload_fn = upload_files) {
399
+ async function upload(file_data, root_url, upload_id, max_file_size) {
230
400
  let files = (Array.isArray(file_data) ? file_data : [file_data]).map(
231
401
  (file_data2) => file_data2.blob
232
402
  );
403
+ const oversized_files = files.filter(
404
+ (f) => f.size > (max_file_size ?? Infinity)
405
+ );
406
+ if (oversized_files.length) {
407
+ throw new Error(
408
+ `File size exceeds the maximum allowed size of ${max_file_size} bytes: ${oversized_files.map((f) => f.name).join(", ")}`
409
+ );
410
+ }
233
411
  return await Promise.all(
234
- await upload_fn(root, files, void 0, upload_id).then(
412
+ await this.upload_files(root_url, files, upload_id).then(
235
413
  async (response) => {
236
414
  if (response.error) {
237
415
  throw new Error(response.error);
@@ -241,7 +419,7 @@ async function upload(file_data, root, upload_id, upload_fn = upload_files) {
241
419
  const file = new FileData({
242
420
  ...file_data[i],
243
421
  path: f,
244
- url: root + "/file=" + f
422
+ url: root_url + "/file=" + f
245
423
  });
246
424
  return file;
247
425
  });
@@ -254,7 +432,7 @@ async function upload(file_data, root, upload_id, upload_fn = upload_files) {
254
432
  }
255
433
  async function prepare_files(files, is_stream) {
256
434
  return files.map(
257
- (f, i) => new FileData({
435
+ (f) => new FileData({
258
436
  path: f.name,
259
437
  orig_name: f.name,
260
438
  blob: f,
@@ -275,7 +453,15 @@ class FileData {
275
453
  mime_type,
276
454
  alt_text
277
455
  }) {
278
- this.meta = { _type: "gradio.FileData" };
456
+ __publicField(this, "path");
457
+ __publicField(this, "url");
458
+ __publicField(this, "orig_name");
459
+ __publicField(this, "size");
460
+ __publicField(this, "blob");
461
+ __publicField(this, "is_stream");
462
+ __publicField(this, "mime_type");
463
+ __publicField(this, "alt_text");
464
+ __publicField(this, "meta", { _type: "gradio.FileData" });
279
465
  this.path = path;
280
466
  this.url = url;
281
467
  this.orig_name = orig_name;
@@ -286,1349 +472,1393 @@ class FileData {
286
472
  this.alt_text = alt_text;
287
473
  }
288
474
  }
289
- const QUEUE_FULL_MSG = "This application is too busy. Keep trying!";
290
- const BROKEN_CONNECTION_MSG = "Connection errored out.";
291
- let NodeBlob;
292
- async function duplicate(app_reference, options) {
293
- const { hf_token, private: _private, hardware, timeout } = options;
294
- if (hardware && !hardware_types.includes(hardware)) {
295
- throw new Error(
296
- `Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.`
297
- );
475
+ function update_object(object, newValue, stack) {
476
+ while (stack.length > 1) {
477
+ const key2 = stack.shift();
478
+ if (typeof key2 === "string" || typeof key2 === "number") {
479
+ object = object[key2];
480
+ } else {
481
+ throw new Error("Invalid key type");
482
+ }
298
483
  }
299
- const headers = {
300
- Authorization: `Bearer ${hf_token}`
301
- };
302
- const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, {
303
- headers
304
- })).json()).name;
305
- const space_name = app_reference.split("/")[1];
306
- const body = {
307
- repository: `${user}/${space_name}`
308
- };
309
- if (_private) {
310
- body.private = true;
484
+ const key = stack.shift();
485
+ if (typeof key === "string" || typeof key === "number") {
486
+ object[key] = newValue;
487
+ } else {
488
+ throw new Error("Invalid key type");
311
489
  }
312
- try {
313
- const response = await fetch(
314
- `https://huggingface.co/api/spaces/${app_reference}/duplicate`,
490
+ }
491
+ async function walk_and_store_blobs(data, type = void 0, path = [], root = false, endpoint_info = void 0) {
492
+ if (Array.isArray(data)) {
493
+ let blob_refs = [];
494
+ await Promise.all(
495
+ data.map(async (item) => {
496
+ var _a;
497
+ let new_path = path.slice();
498
+ new_path.push(item);
499
+ const array_refs = await walk_and_store_blobs(
500
+ data[item],
501
+ root ? ((_a = endpoint_info == null ? void 0 : endpoint_info.parameters[item]) == null ? void 0 : _a.component) || void 0 : type,
502
+ new_path,
503
+ false,
504
+ endpoint_info
505
+ );
506
+ blob_refs = blob_refs.concat(array_refs);
507
+ })
508
+ );
509
+ return blob_refs;
510
+ } else if (globalThis.Buffer && data instanceof globalThis.Buffer || data instanceof Blob) {
511
+ const is_image = type === "Image";
512
+ return [
315
513
  {
316
- method: "POST",
317
- headers: { "Content-Type": "application/json", ...headers },
318
- body: JSON.stringify(body)
514
+ path,
515
+ blob: is_image ? false : new NodeBlob([data]),
516
+ type
319
517
  }
320
- );
321
- if (response.status === 409) {
322
- return client(`${user}/${space_name}`, options);
518
+ ];
519
+ } else if (typeof data === "object" && data !== null) {
520
+ let blob_refs = [];
521
+ for (const key of Object.keys(data)) {
522
+ const new_path = [...path, key];
523
+ const value = data[key];
524
+ blob_refs = blob_refs.concat(
525
+ await walk_and_store_blobs(
526
+ value,
527
+ void 0,
528
+ new_path,
529
+ false,
530
+ endpoint_info
531
+ )
532
+ );
323
533
  }
324
- const duplicated_space = await response.json();
325
- let original_hardware;
326
- if (!hardware) {
327
- original_hardware = await get_space_hardware(app_reference, hf_token);
534
+ if (!blob_refs.length && !(data instanceof Blob || data instanceof ArrayBuffer || data instanceof Uint8Array)) {
535
+ return [
536
+ {
537
+ path,
538
+ blob: new NodeBlob([JSON.stringify(data)]),
539
+ type: typeof data
540
+ }
541
+ ];
328
542
  }
329
- const requested_hardware = hardware || original_hardware || "cpu-basic";
330
- await set_space_hardware(
331
- `${user}/${space_name}`,
332
- requested_hardware,
333
- hf_token
334
- );
335
- await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
336
- return client(duplicated_space.url, options);
337
- } catch (e) {
338
- throw new Error(e);
543
+ return blob_refs;
339
544
  }
545
+ return [];
340
546
  }
341
- function api_factory(fetch_implementation, EventSource_factory) {
342
- return { post_data: post_data2, upload_files: upload_files2, client: client2, handle_blob: handle_blob2 };
343
- async function post_data2(url, body, token, additional_headers) {
344
- const headers = { "Content-Type": "application/json" };
345
- if (token) {
346
- headers.Authorization = `Bearer ${token}`;
347
- }
348
- try {
349
- var response = await fetch_implementation(url, {
350
- method: "POST",
351
- body: JSON.stringify(body),
352
- headers: { ...headers, ...additional_headers }
353
- });
354
- } catch (e) {
355
- return [{ error: BROKEN_CONNECTION_MSG }, 500];
356
- }
357
- let output;
358
- let status;
359
- try {
360
- output = await response.json();
361
- status = response.status;
362
- } catch (e) {
363
- output = { error: `Could not parse server response: ${e}` };
364
- status = 500;
365
- }
366
- return [output, status];
547
+ function skip_queue(id, config) {
548
+ var _a, _b;
549
+ if (((_b = (_a = config == null ? void 0 : config.dependencies) == null ? void 0 : _a[id]) == null ? void 0 : _b.queue) !== null) {
550
+ return !config.dependencies[id].queue;
367
551
  }
368
- async function upload_files2(root, files, token, upload_id) {
369
- const headers = {};
370
- if (token) {
371
- headers.Authorization = `Bearer ${token}`;
372
- }
373
- const chunkSize = 1e3;
374
- const uploadResponses = [];
375
- for (let i = 0; i < files.length; i += chunkSize) {
376
- const chunk = files.slice(i, i + chunkSize);
377
- const formData = new FormData();
378
- chunk.forEach((file) => {
379
- formData.append("files", file);
380
- });
381
- try {
382
- const upload_url = upload_id ? `${root}/upload?upload_id=${upload_id}` : `${root}/upload`;
383
- var response = await fetch_implementation(upload_url, {
384
- method: "POST",
385
- body: formData,
386
- headers
387
- });
388
- } catch (e) {
389
- return { error: BROKEN_CONNECTION_MSG };
390
- }
391
- const output = await response.json();
392
- uploadResponses.push(...output);
393
- }
394
- return { files: uploadResponses };
395
- }
396
- async function client2(app_reference, options = {}) {
397
- return new Promise(async (res) => {
398
- const { status_callback, hf_token } = options;
399
- const return_obj = {
400
- predict,
401
- submit,
402
- view_api,
403
- component_server
552
+ return !config.enable_queue;
553
+ }
554
+ function post_message(message, origin) {
555
+ return new Promise((res, _rej) => {
556
+ const channel = new MessageChannel();
557
+ channel.port1.onmessage = ({ data }) => {
558
+ channel.port1.close();
559
+ res(data);
560
+ };
561
+ window.parent.postMessage(message, origin, [channel.port2]);
562
+ });
563
+ }
564
+ async function handle_blob(endpoint, data, api_info) {
565
+ const self = this;
566
+ const blobRefs = await walk_and_store_blobs(
567
+ data,
568
+ void 0,
569
+ [],
570
+ true,
571
+ api_info
572
+ );
573
+ const results = await Promise.all(
574
+ blobRefs.map(async ({ path, blob, type }) => {
575
+ if (!blob)
576
+ return { path, type };
577
+ const response = await self.upload_files(endpoint, [blob]);
578
+ const file_url = response.files && response.files[0];
579
+ return {
580
+ path,
581
+ file_url,
582
+ type,
583
+ name: blob instanceof File ? blob == null ? void 0 : blob.name : void 0
404
584
  };
405
- if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.Websocket) {
406
- const ws = await import("./wrapper-6f348d45.js");
407
- NodeBlob = (await import("node:buffer")).Blob;
408
- global.WebSocket = ws.WebSocket;
409
- }
410
- const { ws_protocol, http_protocol, host, space_id } = await process_endpoint(app_reference, hf_token);
411
- const session_hash = Math.random().toString(36).substring(2);
412
- const last_status = {};
413
- let stream_open = false;
414
- let pending_stream_messages = {};
415
- let pending_diff_streams = {};
416
- let event_stream = null;
417
- const event_callbacks = {};
418
- const unclosed_events = /* @__PURE__ */ new Set();
419
- let config;
420
- let api_map = {};
421
- let jwt = false;
422
- if (hf_token && space_id) {
423
- jwt = await get_jwt(space_id, hf_token);
424
- }
425
- async function config_success(_config) {
426
- config = _config;
427
- if (window.location.protocol === "https:") {
428
- config.root = config.root.replace("http://", "https://");
429
- }
430
- api_map = map_names_to_ids((_config == null ? void 0 : _config.dependencies) || []);
431
- if (config.auth_required) {
432
- return {
433
- config,
434
- ...return_obj
435
- };
436
- }
437
- try {
438
- api = await view_api(config);
439
- } catch (e) {
440
- console.error(`Could not get api details: ${e.message}`);
441
- }
442
- return {
443
- config,
444
- ...return_obj
445
- };
446
- }
447
- let api;
448
- async function handle_space_sucess(status) {
449
- if (status_callback)
450
- status_callback(status);
451
- if (status.status === "running")
452
- try {
453
- config = await resolve_config(
454
- fetch_implementation,
455
- `${http_protocol}//${host}`,
456
- hf_token
457
- );
458
- const _config = await config_success(config);
459
- res(_config);
460
- } catch (e) {
461
- console.error(e);
462
- if (status_callback) {
463
- status_callback({
464
- status: "error",
465
- message: "Could not load this space.",
466
- load_status: "error",
467
- detail: "NOT_FOUND"
468
- });
469
- }
470
- }
471
- }
472
- try {
473
- config = await resolve_config(
474
- fetch_implementation,
475
- `${http_protocol}//${host}`,
476
- hf_token
477
- );
478
- const _config = await config_success(config);
479
- const heartbeat_url = new URL(
480
- `${config.root}/heartbeat/${session_hash}`
481
- );
482
- EventSource_factory(heartbeat_url);
483
- res(_config);
484
- } catch (e) {
485
- console.error(e);
486
- if (space_id) {
487
- check_space_status(
488
- space_id,
489
- RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
490
- handle_space_sucess
491
- );
492
- } else {
493
- if (status_callback)
494
- status_callback({
495
- status: "error",
496
- message: "Could not load this space.",
497
- load_status: "error",
498
- detail: "NOT_FOUND"
499
- });
500
- }
585
+ })
586
+ );
587
+ results.forEach(({ path, file_url, type, name }) => {
588
+ if (type === "Gallery") {
589
+ update_object(data, file_url, path);
590
+ } else if (file_url) {
591
+ const file = new FileData({ path: file_url, orig_name: name });
592
+ update_object(data, file, path);
593
+ }
594
+ });
595
+ return data;
596
+ }
597
+ async function post_data(url, body, additional_headers) {
598
+ const headers = { "Content-Type": "application/json" };
599
+ if (this.options.hf_token) {
600
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
601
+ }
602
+ try {
603
+ var response = await this.fetch(url, {
604
+ method: "POST",
605
+ body: JSON.stringify(body),
606
+ headers: { ...headers, ...additional_headers }
607
+ });
608
+ } catch (e) {
609
+ return [{ error: BROKEN_CONNECTION_MSG }, 500];
610
+ }
611
+ let output;
612
+ let status;
613
+ try {
614
+ output = await response.json();
615
+ status = response.status;
616
+ } catch (e) {
617
+ output = { error: `Could not parse server response: ${e}` };
618
+ status = 500;
619
+ }
620
+ return [output, status];
621
+ }
622
+ async function predict(endpoint, data) {
623
+ let data_returned = false;
624
+ let status_complete = false;
625
+ let dependency;
626
+ if (!this.config) {
627
+ throw new Error("Could not resolve app config");
628
+ }
629
+ if (typeof endpoint === "number") {
630
+ dependency = this.config.dependencies[endpoint];
631
+ } else {
632
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
633
+ dependency = this.config.dependencies[this.api_map[trimmed_endpoint]];
634
+ }
635
+ if (dependency == null ? void 0 : dependency.types.continuous) {
636
+ throw new Error(
637
+ "Cannot call predict on this function as it may run forever. Use submit instead"
638
+ );
639
+ }
640
+ return new Promise(async (resolve, reject) => {
641
+ const app = this.submit(endpoint, data || []);
642
+ let result;
643
+ app.on("data", (d) => {
644
+ if (status_complete) {
645
+ app.destroy();
646
+ resolve(d);
501
647
  }
502
- function predict(endpoint, data, event_data) {
503
- let data_returned = false;
504
- let status_complete = false;
505
- let dependency;
506
- if (typeof endpoint === "number") {
507
- dependency = config.dependencies[endpoint];
508
- } else {
509
- const trimmed_endpoint = endpoint.replace(/^\//, "");
510
- dependency = config.dependencies[api_map[trimmed_endpoint]];
511
- }
512
- if (dependency.types.continuous) {
513
- throw new Error(
514
- "Cannot call predict on this function as it may run forever. Use submit instead"
515
- );
648
+ data_returned = true;
649
+ result = d;
650
+ }).on("status", (status) => {
651
+ if (status.stage === "error")
652
+ reject(status);
653
+ if (status.stage === "complete") {
654
+ status_complete = true;
655
+ if (data_returned) {
656
+ app.destroy();
657
+ resolve(result);
516
658
  }
517
- return new Promise((res2, rej) => {
518
- const app = submit(endpoint, data, event_data);
519
- let result;
520
- app.on("data", (d) => {
521
- if (status_complete) {
522
- app.destroy();
523
- res2(d);
524
- }
525
- data_returned = true;
526
- result = d;
527
- }).on("status", (status) => {
528
- if (status.stage === "error")
529
- rej(status);
530
- if (status.stage === "complete") {
531
- status_complete = true;
532
- if (data_returned) {
533
- app.destroy();
534
- res2(result);
535
- }
536
- }
537
- });
538
- });
539
659
  }
540
- function submit(endpoint, data, event_data, trigger_id = null) {
541
- let fn_index;
542
- let api_info;
543
- let dependency;
544
- if (typeof endpoint === "number") {
545
- fn_index = endpoint;
546
- api_info = api.unnamed_endpoints[fn_index];
547
- dependency = config.dependencies[endpoint];
548
- } else {
549
- const trimmed_endpoint = endpoint.replace(/^\//, "");
550
- fn_index = api_map[trimmed_endpoint];
551
- api_info = api.named_endpoints[endpoint.trim()];
552
- dependency = config.dependencies[api_map[trimmed_endpoint]];
553
- }
554
- if (typeof fn_index !== "number") {
555
- throw new Error(
556
- "There is no endpoint matching that name of fn_index matching that number."
557
- );
558
- }
559
- let websocket;
560
- let eventSource;
561
- let protocol = config.protocol ?? "ws";
562
- const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
563
- let payload;
564
- let event_id = null;
565
- let complete = false;
566
- const listener_map = {};
567
- let url_params = "";
568
- if (typeof window !== "undefined") {
569
- url_params = new URLSearchParams(window.location.search).toString();
570
- }
571
- handle_blob2(`${config.root}`, data, api_info, hf_token).then(
572
- (_payload) => {
573
- payload = {
574
- data: _payload || [],
575
- event_data,
576
- fn_index,
577
- trigger_id
578
- };
579
- if (skip_queue(fn_index, config)) {
580
- fire_event({
581
- type: "status",
582
- endpoint: _endpoint,
583
- stage: "pending",
584
- queue: false,
585
- fn_index,
586
- time: /* @__PURE__ */ new Date()
587
- });
588
- post_data2(
589
- `${config.root}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}${url_params ? "?" + url_params : ""}`,
590
- {
591
- ...payload,
592
- session_hash
593
- },
594
- hf_token
595
- ).then(([output, status_code]) => {
596
- const data2 = output.data;
597
- if (status_code == 200) {
598
- fire_event({
599
- type: "data",
600
- endpoint: _endpoint,
601
- fn_index,
602
- data: data2,
603
- time: /* @__PURE__ */ new Date()
604
- });
605
- fire_event({
606
- type: "status",
607
- endpoint: _endpoint,
608
- fn_index,
609
- stage: "complete",
610
- eta: output.average_duration,
611
- queue: false,
612
- time: /* @__PURE__ */ new Date()
613
- });
614
- } else {
615
- fire_event({
616
- type: "status",
617
- stage: "error",
618
- endpoint: _endpoint,
619
- fn_index,
620
- message: output.error,
621
- queue: false,
622
- time: /* @__PURE__ */ new Date()
623
- });
624
- }
625
- }).catch((e) => {
626
- fire_event({
627
- type: "status",
628
- stage: "error",
629
- message: e.message,
630
- endpoint: _endpoint,
631
- fn_index,
632
- queue: false,
633
- time: /* @__PURE__ */ new Date()
634
- });
635
- });
636
- } else if (protocol == "ws") {
637
- fire_event({
638
- type: "status",
639
- stage: "pending",
640
- queue: true,
641
- endpoint: _endpoint,
660
+ });
661
+ });
662
+ }
663
+ async function check_space_status(id, type, status_callback) {
664
+ let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`;
665
+ let response;
666
+ let _status;
667
+ try {
668
+ response = await fetch(endpoint);
669
+ _status = response.status;
670
+ if (_status !== 200) {
671
+ throw new Error();
672
+ }
673
+ response = await response.json();
674
+ } catch (e) {
675
+ status_callback({
676
+ status: "error",
677
+ load_status: "error",
678
+ message: SPACE_STATUS_ERROR_MSG,
679
+ detail: "NOT_FOUND"
680
+ });
681
+ return;
682
+ }
683
+ if (!response || _status !== 200)
684
+ return;
685
+ const {
686
+ runtime: { stage },
687
+ id: space_name
688
+ } = response;
689
+ switch (stage) {
690
+ case "STOPPED":
691
+ case "SLEEPING":
692
+ status_callback({
693
+ status: "sleeping",
694
+ load_status: "pending",
695
+ message: "Space is asleep. Waking it up...",
696
+ detail: stage
697
+ });
698
+ setTimeout(() => {
699
+ check_space_status(id, type, status_callback);
700
+ }, 1e3);
701
+ break;
702
+ case "PAUSED":
703
+ status_callback({
704
+ status: "paused",
705
+ load_status: "error",
706
+ message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
707
+ detail: stage,
708
+ discussions_enabled: await discussions_enabled(space_name)
709
+ });
710
+ break;
711
+ case "RUNNING":
712
+ case "RUNNING_BUILDING":
713
+ status_callback({
714
+ status: "running",
715
+ load_status: "complete",
716
+ message: "",
717
+ detail: stage
718
+ });
719
+ break;
720
+ case "BUILDING":
721
+ status_callback({
722
+ status: "building",
723
+ load_status: "pending",
724
+ message: "Space is building...",
725
+ detail: stage
726
+ });
727
+ setTimeout(() => {
728
+ check_space_status(id, type, status_callback);
729
+ }, 1e3);
730
+ break;
731
+ default:
732
+ status_callback({
733
+ status: "space_error",
734
+ load_status: "error",
735
+ message: "This space is experiencing an issue.",
736
+ detail: stage,
737
+ discussions_enabled: await discussions_enabled(space_name)
738
+ });
739
+ break;
740
+ }
741
+ }
742
+ const RE_DISABLED_DISCUSSION = /^(?=[^]*\b[dD]iscussions{0,1}\b)(?=[^]*\b[dD]isabled\b)[^]*$/;
743
+ async function discussions_enabled(space_id) {
744
+ try {
745
+ const r = await fetch(
746
+ `https://huggingface.co/api/spaces/${space_id}/discussions`,
747
+ {
748
+ method: "HEAD"
749
+ }
750
+ );
751
+ const error = r.headers.get("x-error-message");
752
+ if (error && RE_DISABLED_DISCUSSION.test(error))
753
+ return false;
754
+ return true;
755
+ } catch (e) {
756
+ return false;
757
+ }
758
+ }
759
+ async function get_space_hardware(space_id, hf_token) {
760
+ const headers = {};
761
+ if (hf_token) {
762
+ headers.Authorization = `Bearer ${hf_token}`;
763
+ }
764
+ try {
765
+ const res = await fetch(
766
+ `https://huggingface.co/api/spaces/${space_id}/${RUNTIME_URL}`,
767
+ { headers }
768
+ );
769
+ if (res.status !== 200)
770
+ throw new Error("Space hardware could not be obtained.");
771
+ const { hardware } = await res.json();
772
+ return hardware.current;
773
+ } catch (e) {
774
+ throw new Error(e.message);
775
+ }
776
+ }
777
+ async function set_space_timeout(space_id, timeout, hf_token) {
778
+ const headers = {};
779
+ if (hf_token) {
780
+ headers.Authorization = `Bearer ${hf_token}`;
781
+ }
782
+ const body = {
783
+ seconds: timeout
784
+ };
785
+ try {
786
+ const res = await fetch(
787
+ `https://huggingface.co/api/spaces/${space_id}/${SLEEPTIME_URL}`,
788
+ {
789
+ method: "POST",
790
+ headers: { "Content-Type": "application/json", ...headers },
791
+ body: JSON.stringify(body)
792
+ }
793
+ );
794
+ if (res.status !== 200) {
795
+ throw new Error(
796
+ "Could not set sleep timeout on duplicated Space. Please visit *ADD HF LINK TO SETTINGS* to set a timeout manually to reduce billing charges."
797
+ );
798
+ }
799
+ const response = await res.json();
800
+ return response;
801
+ } catch (e) {
802
+ throw new Error(e.message);
803
+ }
804
+ }
805
+ const hardware_types = [
806
+ "cpu-basic",
807
+ "cpu-upgrade",
808
+ "cpu-xl",
809
+ "t4-small",
810
+ "t4-medium",
811
+ "a10g-small",
812
+ "a10g-large",
813
+ "a10g-largex2",
814
+ "a10g-largex4",
815
+ "a100-large",
816
+ "zero-a10g",
817
+ "h100",
818
+ "h100x8"
819
+ ];
820
+ async function duplicate(app_reference, options) {
821
+ const { hf_token, private: _private, hardware, timeout } = options;
822
+ if (hardware && !hardware_types.includes(hardware)) {
823
+ throw new Error(
824
+ `Invalid hardware type provided. Valid types are: ${hardware_types.map((v) => `"${v}"`).join(",")}.`
825
+ );
826
+ }
827
+ const headers = {
828
+ Authorization: `Bearer ${hf_token}`,
829
+ "Content-Type": "application/json"
830
+ };
831
+ const user = (await (await fetch(`https://huggingface.co/api/whoami-v2`, {
832
+ headers
833
+ })).json()).name;
834
+ const space_name = app_reference.split("/")[1];
835
+ const body = {
836
+ repository: `${user}/${space_name}`
837
+ };
838
+ if (_private) {
839
+ body.private = true;
840
+ }
841
+ let original_hardware;
842
+ try {
843
+ if (!hardware) {
844
+ original_hardware = await get_space_hardware(app_reference, hf_token);
845
+ }
846
+ } catch (e) {
847
+ throw Error(SPACE_METADATA_ERROR_MSG + e.message);
848
+ }
849
+ const requested_hardware = hardware || original_hardware || "cpu-basic";
850
+ body.hardware = requested_hardware;
851
+ try {
852
+ const response = await fetch(
853
+ `https://huggingface.co/api/spaces/${app_reference}/duplicate`,
854
+ {
855
+ method: "POST",
856
+ headers,
857
+ body: JSON.stringify(body)
858
+ }
859
+ );
860
+ if (response.status === 409) {
861
+ try {
862
+ const client2 = await Client.connect(`${user}/${space_name}`, options);
863
+ return client2;
864
+ } catch (error) {
865
+ console.error("Failed to connect Client instance:", error);
866
+ throw error;
867
+ }
868
+ } else if (response.status !== 200) {
869
+ throw new Error(response.statusText);
870
+ }
871
+ const duplicated_space = await response.json();
872
+ await set_space_timeout(`${user}/${space_name}`, timeout || 300, hf_token);
873
+ return await Client.connect(
874
+ get_space_reference(duplicated_space.url),
875
+ options
876
+ );
877
+ } catch (e) {
878
+ throw new Error(e);
879
+ }
880
+ }
881
+ function get_space_reference(url) {
882
+ const regex = /https:\/\/huggingface.co\/spaces\/([^/]+\/[^/]+)/;
883
+ const match = url.match(regex);
884
+ if (match) {
885
+ return match[1];
886
+ }
887
+ }
888
+ function open_stream() {
889
+ let {
890
+ event_callbacks,
891
+ unclosed_events,
892
+ pending_stream_messages,
893
+ stream_status,
894
+ config,
895
+ jwt
896
+ } = this;
897
+ if (!config) {
898
+ throw new Error("Could not resolve app config");
899
+ }
900
+ stream_status.open = true;
901
+ let stream = null;
902
+ let params = new URLSearchParams({
903
+ session_hash: this.session_hash
904
+ }).toString();
905
+ let url = new URL(`${config.root}/queue/data?${params}`);
906
+ if (jwt) {
907
+ url.searchParams.set("__sign", jwt);
908
+ }
909
+ stream = this.stream_factory(url);
910
+ if (!stream) {
911
+ console.warn("Cannot connect to SSE endpoint: " + url.toString());
912
+ return;
913
+ }
914
+ stream.onmessage = async function(event) {
915
+ let _data = JSON.parse(event.data);
916
+ if (_data.msg === "close_stream") {
917
+ close_stream(stream_status, stream);
918
+ return;
919
+ }
920
+ const event_id = _data.event_id;
921
+ if (!event_id) {
922
+ await Promise.all(
923
+ Object.keys(event_callbacks).map(
924
+ (event_id2) => event_callbacks[event_id2](_data)
925
+ )
926
+ );
927
+ } else if (event_callbacks[event_id] && config) {
928
+ if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1"].includes(config.protocol)) {
929
+ unclosed_events.delete(event_id);
930
+ if (unclosed_events.size === 0) {
931
+ close_stream(stream_status, stream);
932
+ }
933
+ }
934
+ let fn2 = event_callbacks[event_id];
935
+ if (typeof window !== "undefined") {
936
+ window.setTimeout(fn2, 0, _data);
937
+ } else {
938
+ setImmediate(fn2, _data);
939
+ }
940
+ } else {
941
+ if (!pending_stream_messages[event_id]) {
942
+ pending_stream_messages[event_id] = [];
943
+ }
944
+ pending_stream_messages[event_id].push(_data);
945
+ }
946
+ };
947
+ stream.onerror = async function() {
948
+ await Promise.all(
949
+ Object.keys(event_callbacks).map(
950
+ (event_id) => event_callbacks[event_id]({
951
+ msg: "unexpected_error",
952
+ message: BROKEN_CONNECTION_MSG
953
+ })
954
+ )
955
+ );
956
+ close_stream(stream_status, stream);
957
+ };
958
+ }
959
+ function close_stream(stream_status, stream) {
960
+ if (stream_status && stream) {
961
+ stream_status.open = false;
962
+ stream == null ? void 0 : stream.close();
963
+ }
964
+ }
965
+ function apply_diff_stream(pending_diff_streams, event_id, data) {
966
+ let is_first_generation = !pending_diff_streams[event_id];
967
+ if (is_first_generation) {
968
+ pending_diff_streams[event_id] = [];
969
+ data.data.forEach((value, i) => {
970
+ pending_diff_streams[event_id][i] = value;
971
+ });
972
+ } else {
973
+ data.data.forEach((value, i) => {
974
+ let new_data = apply_diff(pending_diff_streams[event_id][i], value);
975
+ pending_diff_streams[event_id][i] = new_data;
976
+ data.data[i] = new_data;
977
+ });
978
+ }
979
+ }
980
+ function apply_diff(obj, diff) {
981
+ diff.forEach(([action, path, value]) => {
982
+ obj = apply_edit(obj, path, action, value);
983
+ });
984
+ return obj;
985
+ }
986
+ function apply_edit(target, path, action, value) {
987
+ if (path.length === 0) {
988
+ if (action === "replace") {
989
+ return value;
990
+ } else if (action === "append") {
991
+ return target + value;
992
+ }
993
+ throw new Error(`Unsupported action: ${action}`);
994
+ }
995
+ let current = target;
996
+ for (let i = 0; i < path.length - 1; i++) {
997
+ current = current[path[i]];
998
+ }
999
+ const last_path = path[path.length - 1];
1000
+ switch (action) {
1001
+ case "replace":
1002
+ current[last_path] = value;
1003
+ break;
1004
+ case "append":
1005
+ current[last_path] += value;
1006
+ break;
1007
+ case "add":
1008
+ if (Array.isArray(current)) {
1009
+ current.splice(Number(last_path), 0, value);
1010
+ } else {
1011
+ current[last_path] = value;
1012
+ }
1013
+ break;
1014
+ case "delete":
1015
+ if (Array.isArray(current)) {
1016
+ current.splice(Number(last_path), 1);
1017
+ } else {
1018
+ delete current[last_path];
1019
+ }
1020
+ break;
1021
+ default:
1022
+ throw new Error(`Unknown action: ${action}`);
1023
+ }
1024
+ return target;
1025
+ }
1026
+ function submit(endpoint, data, event_data, trigger_id) {
1027
+ try {
1028
+ let fire_event = function(event) {
1029
+ const narrowed_listener_map = listener_map;
1030
+ const listeners = narrowed_listener_map[event.type] || [];
1031
+ listeners == null ? void 0 : listeners.forEach((l) => l(event));
1032
+ }, on = function(eventType, listener) {
1033
+ const narrowed_listener_map = listener_map;
1034
+ const listeners = narrowed_listener_map[eventType] || [];
1035
+ narrowed_listener_map[eventType] = listeners;
1036
+ listeners == null ? void 0 : listeners.push(listener);
1037
+ return { on, off, cancel, destroy };
1038
+ }, off = function(eventType, listener) {
1039
+ const narrowed_listener_map = listener_map;
1040
+ let listeners = narrowed_listener_map[eventType] || [];
1041
+ listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
1042
+ narrowed_listener_map[eventType] = listeners;
1043
+ return { on, off, cancel, destroy };
1044
+ }, destroy = function() {
1045
+ var _a;
1046
+ for (const event_type in listener_map) {
1047
+ listener_map && ((_a = listener_map[event_type]) == null ? void 0 : _a.forEach((fn2) => {
1048
+ off(event_type, fn2);
1049
+ }));
1050
+ }
1051
+ };
1052
+ const { hf_token } = this.options;
1053
+ const {
1054
+ fetch: fetch2,
1055
+ app_reference,
1056
+ config,
1057
+ session_hash,
1058
+ api_info,
1059
+ api_map,
1060
+ stream_status,
1061
+ pending_stream_messages,
1062
+ pending_diff_streams,
1063
+ event_callbacks,
1064
+ unclosed_events,
1065
+ post_data: post_data2
1066
+ } = this;
1067
+ if (!api_info)
1068
+ throw new Error("No API found");
1069
+ if (!config)
1070
+ throw new Error("Could not resolve app config");
1071
+ let { fn_index, endpoint_info, dependency } = get_endpoint_info(
1072
+ api_info,
1073
+ endpoint,
1074
+ api_map,
1075
+ config
1076
+ );
1077
+ let websocket;
1078
+ let stream;
1079
+ let protocol = config.protocol ?? "ws";
1080
+ const _endpoint = typeof endpoint === "number" ? "/predict" : endpoint;
1081
+ let payload;
1082
+ let event_id = null;
1083
+ let complete = false;
1084
+ const listener_map = {};
1085
+ let last_status = {};
1086
+ let url_params = typeof window !== "undefined" ? new URLSearchParams(window.location.search).toString() : "";
1087
+ async function cancel() {
1088
+ const _status = {
1089
+ stage: "complete",
1090
+ queue: false,
1091
+ time: /* @__PURE__ */ new Date()
1092
+ };
1093
+ complete = _status;
1094
+ fire_event({
1095
+ ..._status,
1096
+ type: "status",
1097
+ endpoint: _endpoint,
1098
+ fn_index
1099
+ });
1100
+ let cancel_request = {};
1101
+ if (protocol === "ws") {
1102
+ if (websocket && websocket.readyState === 0) {
1103
+ websocket.addEventListener("open", () => {
1104
+ websocket.close();
1105
+ });
1106
+ } else {
1107
+ websocket.close();
1108
+ }
1109
+ cancel_request = { fn_index, session_hash };
1110
+ } else {
1111
+ stream == null ? void 0 : stream.close();
1112
+ cancel_request = { event_id };
1113
+ }
1114
+ try {
1115
+ if (!config) {
1116
+ throw new Error("Could not resolve app config");
1117
+ }
1118
+ await fetch2(`${config.root}/reset`, {
1119
+ headers: { "Content-Type": "application/json" },
1120
+ method: "POST",
1121
+ body: JSON.stringify(cancel_request)
1122
+ });
1123
+ } catch (e) {
1124
+ console.warn(
1125
+ "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
1126
+ );
1127
+ }
1128
+ }
1129
+ this.handle_blob(config.root, data, endpoint_info).then(
1130
+ async (_payload) => {
1131
+ var _a;
1132
+ payload = {
1133
+ data: _payload || [],
1134
+ event_data,
1135
+ fn_index,
1136
+ trigger_id
1137
+ };
1138
+ if (skip_queue(fn_index, config)) {
1139
+ fire_event({
1140
+ type: "status",
1141
+ endpoint: _endpoint,
1142
+ stage: "pending",
1143
+ queue: false,
1144
+ fn_index,
1145
+ time: /* @__PURE__ */ new Date()
1146
+ });
1147
+ post_data2(
1148
+ `${config.root}/run${_endpoint.startsWith("/") ? _endpoint : `/${_endpoint}`}${url_params ? "?" + url_params : ""}`,
1149
+ {
1150
+ ...payload,
1151
+ session_hash
1152
+ }
1153
+ ).then(([output, status_code]) => {
1154
+ const data2 = output.data;
1155
+ if (status_code == 200) {
1156
+ fire_event({
1157
+ type: "data",
1158
+ endpoint: _endpoint,
1159
+ fn_index,
1160
+ data: data2,
1161
+ time: /* @__PURE__ */ new Date(),
1162
+ event_data,
1163
+ trigger_id
1164
+ });
1165
+ fire_event({
1166
+ type: "status",
1167
+ endpoint: _endpoint,
1168
+ fn_index,
1169
+ stage: "complete",
1170
+ eta: output.average_duration,
1171
+ queue: false,
1172
+ time: /* @__PURE__ */ new Date()
1173
+ });
1174
+ } else {
1175
+ fire_event({
1176
+ type: "status",
1177
+ stage: "error",
1178
+ endpoint: _endpoint,
1179
+ fn_index,
1180
+ message: output.error,
1181
+ queue: false,
1182
+ time: /* @__PURE__ */ new Date()
1183
+ });
1184
+ }
1185
+ }).catch((e) => {
1186
+ fire_event({
1187
+ type: "status",
1188
+ stage: "error",
1189
+ message: e.message,
1190
+ endpoint: _endpoint,
1191
+ fn_index,
1192
+ queue: false,
1193
+ time: /* @__PURE__ */ new Date()
1194
+ });
1195
+ });
1196
+ } else if (protocol == "ws") {
1197
+ const { ws_protocol, host } = await process_endpoint(
1198
+ app_reference,
1199
+ hf_token
1200
+ );
1201
+ fire_event({
1202
+ type: "status",
1203
+ stage: "pending",
1204
+ queue: true,
1205
+ endpoint: _endpoint,
1206
+ fn_index,
1207
+ time: /* @__PURE__ */ new Date()
1208
+ });
1209
+ let url = new URL(
1210
+ `${ws_protocol}://${resolve_root(
1211
+ host,
1212
+ config.path,
1213
+ true
1214
+ )}/queue/join${url_params ? "?" + url_params : ""}`
1215
+ );
1216
+ if (this.jwt) {
1217
+ url.searchParams.set("__sign", this.jwt);
1218
+ }
1219
+ websocket = new WebSocket(url);
1220
+ websocket.onclose = (evt) => {
1221
+ if (!evt.wasClean) {
1222
+ fire_event({
1223
+ type: "status",
1224
+ stage: "error",
1225
+ broken: true,
1226
+ message: BROKEN_CONNECTION_MSG,
1227
+ queue: true,
1228
+ endpoint: _endpoint,
642
1229
  fn_index,
643
1230
  time: /* @__PURE__ */ new Date()
644
1231
  });
645
- let url = new URL(`${ws_protocol}://${resolve_root(
646
- host,
647
- config.path,
648
- true
649
- )}
650
- /queue/join${url_params ? "?" + url_params : ""}`);
651
- if (jwt) {
652
- url.searchParams.set("__sign", jwt);
1232
+ }
1233
+ };
1234
+ websocket.onmessage = function(event) {
1235
+ const _data = JSON.parse(event.data);
1236
+ const { type, status, data: data2 } = handle_message(
1237
+ _data,
1238
+ last_status[fn_index]
1239
+ );
1240
+ if (type === "update" && status && !complete) {
1241
+ fire_event({
1242
+ type: "status",
1243
+ endpoint: _endpoint,
1244
+ fn_index,
1245
+ time: /* @__PURE__ */ new Date(),
1246
+ ...status
1247
+ });
1248
+ if (status.stage === "error") {
1249
+ websocket.close();
653
1250
  }
654
- websocket = new WebSocket(url);
655
- websocket.onclose = (evt) => {
656
- if (!evt.wasClean) {
657
- fire_event({
658
- type: "status",
659
- stage: "error",
660
- broken: true,
661
- message: BROKEN_CONNECTION_MSG,
662
- queue: true,
663
- endpoint: _endpoint,
664
- fn_index,
665
- time: /* @__PURE__ */ new Date()
666
- });
667
- }
668
- };
669
- websocket.onmessage = function(event) {
670
- const _data = JSON.parse(event.data);
671
- const { type, status, data: data2 } = handle_message(
672
- _data,
673
- last_status[fn_index]
674
- );
675
- if (type === "update" && status && !complete) {
676
- fire_event({
677
- type: "status",
678
- endpoint: _endpoint,
679
- fn_index,
680
- time: /* @__PURE__ */ new Date(),
681
- ...status
682
- });
683
- if (status.stage === "error") {
684
- websocket.close();
685
- }
686
- } else if (type === "hash") {
687
- websocket.send(JSON.stringify({ fn_index, session_hash }));
688
- return;
689
- } else if (type === "data") {
690
- websocket.send(JSON.stringify({ ...payload, session_hash }));
691
- } else if (type === "complete") {
692
- complete = status;
693
- } else if (type === "log") {
694
- fire_event({
695
- type: "log",
696
- log: data2.log,
697
- level: data2.level,
698
- endpoint: _endpoint,
699
- fn_index
700
- });
701
- } else if (type === "generating") {
702
- fire_event({
703
- type: "status",
704
- time: /* @__PURE__ */ new Date(),
705
- ...status,
706
- stage: status == null ? void 0 : status.stage,
707
- queue: true,
708
- endpoint: _endpoint,
709
- fn_index
710
- });
711
- }
712
- if (data2) {
713
- fire_event({
714
- type: "data",
715
- time: /* @__PURE__ */ new Date(),
716
- data: data2.data,
717
- endpoint: _endpoint,
718
- fn_index
719
- });
720
- if (complete) {
721
- fire_event({
722
- type: "status",
723
- time: /* @__PURE__ */ new Date(),
724
- ...complete,
725
- stage: status == null ? void 0 : status.stage,
726
- queue: true,
727
- endpoint: _endpoint,
728
- fn_index
729
- });
730
- websocket.close();
731
- }
732
- }
733
- };
734
- if (semiver(config.version || "2.0.0", "3.6") < 0) {
735
- addEventListener(
736
- "open",
737
- () => websocket.send(JSON.stringify({ hash: session_hash }))
738
- );
1251
+ } else if (type === "hash") {
1252
+ websocket.send(JSON.stringify({ fn_index, session_hash }));
1253
+ return;
1254
+ } else if (type === "data") {
1255
+ websocket.send(JSON.stringify({ ...payload, session_hash }));
1256
+ } else if (type === "complete") {
1257
+ complete = status;
1258
+ } else if (type === "log") {
1259
+ fire_event({
1260
+ type: "log",
1261
+ log: data2.log,
1262
+ level: data2.level,
1263
+ endpoint: _endpoint,
1264
+ fn_index
1265
+ });
1266
+ } else if (type === "generating") {
1267
+ fire_event({
1268
+ type: "status",
1269
+ time: /* @__PURE__ */ new Date(),
1270
+ ...status,
1271
+ stage: status == null ? void 0 : status.stage,
1272
+ queue: true,
1273
+ endpoint: _endpoint,
1274
+ fn_index
1275
+ });
1276
+ }
1277
+ if (data2) {
1278
+ fire_event({
1279
+ type: "data",
1280
+ time: /* @__PURE__ */ new Date(),
1281
+ data: data2.data,
1282
+ endpoint: _endpoint,
1283
+ fn_index,
1284
+ event_data,
1285
+ trigger_id
1286
+ });
1287
+ if (complete) {
1288
+ fire_event({
1289
+ type: "status",
1290
+ time: /* @__PURE__ */ new Date(),
1291
+ ...complete,
1292
+ stage: status == null ? void 0 : status.stage,
1293
+ queue: true,
1294
+ endpoint: _endpoint,
1295
+ fn_index
1296
+ });
1297
+ websocket.close();
1298
+ }
1299
+ }
1300
+ };
1301
+ if (semiver(config.version || "2.0.0", "3.6") < 0) {
1302
+ addEventListener(
1303
+ "open",
1304
+ () => websocket.send(JSON.stringify({ hash: session_hash }))
1305
+ );
1306
+ }
1307
+ } else if (protocol == "sse") {
1308
+ fire_event({
1309
+ type: "status",
1310
+ stage: "pending",
1311
+ queue: true,
1312
+ endpoint: _endpoint,
1313
+ fn_index,
1314
+ time: /* @__PURE__ */ new Date()
1315
+ });
1316
+ var params = new URLSearchParams({
1317
+ fn_index: fn_index.toString(),
1318
+ session_hash
1319
+ }).toString();
1320
+ let url = new URL(
1321
+ `${config.root}/queue/join?${url_params ? url_params + "&" : ""}${params}`
1322
+ );
1323
+ if (this.jwt) {
1324
+ url.searchParams.set("__sign", this.jwt);
1325
+ }
1326
+ stream = this.stream_factory(url);
1327
+ if (!stream) {
1328
+ return Promise.reject(
1329
+ new Error("Cannot connect to SSE endpoint: " + url.toString())
1330
+ );
1331
+ }
1332
+ stream.onmessage = async function(event) {
1333
+ const _data = JSON.parse(event.data);
1334
+ const { type, status, data: data2 } = handle_message(
1335
+ _data,
1336
+ last_status[fn_index]
1337
+ );
1338
+ if (type === "update" && status && !complete) {
1339
+ fire_event({
1340
+ type: "status",
1341
+ endpoint: _endpoint,
1342
+ fn_index,
1343
+ time: /* @__PURE__ */ new Date(),
1344
+ ...status
1345
+ });
1346
+ if (status.stage === "error") {
1347
+ stream == null ? void 0 : stream.close();
1348
+ }
1349
+ } else if (type === "data") {
1350
+ event_id = _data.event_id;
1351
+ let [_, status2] = await post_data2(`${config.root}/queue/data`, {
1352
+ ...payload,
1353
+ session_hash,
1354
+ event_id
1355
+ });
1356
+ if (status2 !== 200) {
1357
+ fire_event({
1358
+ type: "status",
1359
+ stage: "error",
1360
+ message: BROKEN_CONNECTION_MSG,
1361
+ queue: true,
1362
+ endpoint: _endpoint,
1363
+ fn_index,
1364
+ time: /* @__PURE__ */ new Date()
1365
+ });
1366
+ stream == null ? void 0 : stream.close();
1367
+ }
1368
+ } else if (type === "complete") {
1369
+ complete = status;
1370
+ } else if (type === "log") {
1371
+ fire_event({
1372
+ type: "log",
1373
+ log: data2.log,
1374
+ level: data2.level,
1375
+ endpoint: _endpoint,
1376
+ fn_index
1377
+ });
1378
+ } else if (type === "generating") {
1379
+ fire_event({
1380
+ type: "status",
1381
+ time: /* @__PURE__ */ new Date(),
1382
+ ...status,
1383
+ stage: status == null ? void 0 : status.stage,
1384
+ queue: true,
1385
+ endpoint: _endpoint,
1386
+ fn_index
1387
+ });
1388
+ }
1389
+ if (data2) {
1390
+ fire_event({
1391
+ type: "data",
1392
+ time: /* @__PURE__ */ new Date(),
1393
+ data: data2.data,
1394
+ endpoint: _endpoint,
1395
+ fn_index,
1396
+ event_data,
1397
+ trigger_id
1398
+ });
1399
+ if (complete) {
1400
+ fire_event({
1401
+ type: "status",
1402
+ time: /* @__PURE__ */ new Date(),
1403
+ ...complete,
1404
+ stage: status == null ? void 0 : status.stage,
1405
+ queue: true,
1406
+ endpoint: _endpoint,
1407
+ fn_index
1408
+ });
1409
+ stream == null ? void 0 : stream.close();
739
1410
  }
740
- } else if (protocol == "sse") {
1411
+ }
1412
+ };
1413
+ } else if (protocol == "sse_v1" || protocol == "sse_v2" || protocol == "sse_v2.1" || protocol == "sse_v3") {
1414
+ fire_event({
1415
+ type: "status",
1416
+ stage: "pending",
1417
+ queue: true,
1418
+ endpoint: _endpoint,
1419
+ fn_index,
1420
+ time: /* @__PURE__ */ new Date()
1421
+ });
1422
+ let hostname = "";
1423
+ if (typeof window !== "undefined") {
1424
+ hostname = (_a = window == null ? void 0 : window.location) == null ? void 0 : _a.hostname;
1425
+ }
1426
+ let hfhubdev = "dev.spaces.huggingface.tech";
1427
+ const origin = hostname.includes(".dev.") ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}` : `https://huggingface.co`;
1428
+ const zerogpu_auth_promise = dependency.zerogpu && window.parent != window && config.space_id ? post_message("zerogpu-headers", origin) : Promise.resolve(null);
1429
+ const post_data_promise = zerogpu_auth_promise.then((headers) => {
1430
+ return post_data2(
1431
+ `${config.root}/queue/join?${url_params}`,
1432
+ {
1433
+ ...payload,
1434
+ session_hash
1435
+ },
1436
+ headers
1437
+ );
1438
+ });
1439
+ post_data_promise.then(([response, status]) => {
1440
+ if (status === 503) {
741
1441
  fire_event({
742
1442
  type: "status",
743
- stage: "pending",
1443
+ stage: "error",
1444
+ message: QUEUE_FULL_MSG,
744
1445
  queue: true,
745
1446
  endpoint: _endpoint,
746
1447
  fn_index,
747
1448
  time: /* @__PURE__ */ new Date()
748
1449
  });
749
- var params = new URLSearchParams({
750
- fn_index: fn_index.toString(),
751
- session_hash
752
- }).toString();
753
- let url = new URL(
754
- `${config.root}/queue/join?${url_params ? url_params + "&" : ""}${params}`
755
- );
756
- eventSource = EventSource_factory(url);
757
- eventSource.onmessage = async function(event) {
758
- const _data = JSON.parse(event.data);
759
- const { type, status, data: data2 } = handle_message(
760
- _data,
761
- last_status[fn_index]
762
- );
763
- if (type === "update" && status && !complete) {
764
- fire_event({
765
- type: "status",
766
- endpoint: _endpoint,
767
- fn_index,
768
- time: /* @__PURE__ */ new Date(),
769
- ...status
770
- });
771
- if (status.stage === "error") {
772
- eventSource.close();
773
- }
774
- } else if (type === "data") {
775
- event_id = _data.event_id;
776
- let [_, status2] = await post_data2(
777
- `${config.root}/queue/data`,
778
- {
779
- ...payload,
780
- session_hash,
781
- event_id
782
- },
783
- hf_token
1450
+ } else if (status !== 200) {
1451
+ fire_event({
1452
+ type: "status",
1453
+ stage: "error",
1454
+ message: BROKEN_CONNECTION_MSG,
1455
+ queue: true,
1456
+ endpoint: _endpoint,
1457
+ fn_index,
1458
+ time: /* @__PURE__ */ new Date()
1459
+ });
1460
+ } else {
1461
+ event_id = response.event_id;
1462
+ let callback = async function(_data) {
1463
+ try {
1464
+ const { type, status: status2, data: data2 } = handle_message(
1465
+ _data,
1466
+ last_status[fn_index]
784
1467
  );
785
- if (status2 !== 200) {
1468
+ if (type == "heartbeat") {
1469
+ return;
1470
+ }
1471
+ if (type === "update" && status2 && !complete) {
1472
+ fire_event({
1473
+ type: "status",
1474
+ endpoint: _endpoint,
1475
+ fn_index,
1476
+ time: /* @__PURE__ */ new Date(),
1477
+ ...status2
1478
+ });
1479
+ } else if (type === "complete") {
1480
+ complete = status2;
1481
+ } else if (type == "unexpected_error") {
1482
+ console.error("Unexpected error", status2 == null ? void 0 : status2.message);
786
1483
  fire_event({
787
1484
  type: "status",
788
1485
  stage: "error",
789
- message: BROKEN_CONNECTION_MSG,
1486
+ message: (status2 == null ? void 0 : status2.message) || "An Unexpected Error Occurred!",
790
1487
  queue: true,
791
1488
  endpoint: _endpoint,
792
1489
  fn_index,
793
1490
  time: /* @__PURE__ */ new Date()
794
1491
  });
795
- eventSource.close();
796
- }
797
- } else if (type === "complete") {
798
- complete = status;
799
- } else if (type === "log") {
800
- fire_event({
801
- type: "log",
802
- log: data2.log,
803
- level: data2.level,
804
- endpoint: _endpoint,
805
- fn_index
806
- });
807
- } else if (type === "generating") {
808
- fire_event({
809
- type: "status",
810
- time: /* @__PURE__ */ new Date(),
811
- ...status,
812
- stage: status == null ? void 0 : status.stage,
813
- queue: true,
814
- endpoint: _endpoint,
815
- fn_index
816
- });
817
- }
818
- if (data2) {
819
- fire_event({
820
- type: "data",
821
- time: /* @__PURE__ */ new Date(),
822
- data: data2.data,
823
- endpoint: _endpoint,
824
- fn_index
825
- });
826
- if (complete) {
1492
+ } else if (type === "log") {
1493
+ fire_event({
1494
+ type: "log",
1495
+ log: data2.log,
1496
+ level: data2.level,
1497
+ endpoint: _endpoint,
1498
+ fn_index
1499
+ });
1500
+ return;
1501
+ } else if (type === "generating") {
827
1502
  fire_event({
828
1503
  type: "status",
829
1504
  time: /* @__PURE__ */ new Date(),
830
- ...complete,
831
- stage: status == null ? void 0 : status.stage,
1505
+ ...status2,
1506
+ stage: status2 == null ? void 0 : status2.stage,
832
1507
  queue: true,
833
1508
  endpoint: _endpoint,
834
1509
  fn_index
835
1510
  });
836
- eventSource.close();
1511
+ if (data2 && ["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) {
1512
+ apply_diff_stream(pending_diff_streams, event_id, data2);
1513
+ }
837
1514
  }
838
- }
839
- };
840
- } else if (protocol == "sse_v1" || protocol == "sse_v2" || protocol == "sse_v2.1" || protocol == "sse_v3") {
841
- fire_event({
842
- type: "status",
843
- stage: "pending",
844
- queue: true,
845
- endpoint: _endpoint,
846
- fn_index,
847
- time: /* @__PURE__ */ new Date()
848
- });
849
- let hostname = window.location.hostname;
850
- let hfhubdev = "dev.spaces.huggingface.tech";
851
- const origin = hostname.includes(".dev.") ? `https://moon-${hostname.split(".")[1]}.${hfhubdev}` : `https://huggingface.co`;
852
- const zerogpu_auth_promise = dependency.zerogpu && window.parent != window && config.space_id ? post_message("zerogpu-headers", origin) : Promise.resolve(null);
853
- const post_data_promise = zerogpu_auth_promise.then((headers) => {
854
- return post_data2(
855
- `${config.root}/queue/join?${url_params}`,
856
- {
857
- ...payload,
858
- session_hash
859
- },
860
- hf_token,
861
- headers
862
- );
863
- });
864
- post_data_promise.then(([response, status]) => {
865
- if (status === 503) {
866
- fire_event({
867
- type: "status",
868
- stage: "error",
869
- message: QUEUE_FULL_MSG,
870
- queue: true,
871
- endpoint: _endpoint,
872
- fn_index,
873
- time: /* @__PURE__ */ new Date()
874
- });
875
- } else if (status !== 200) {
1515
+ if (data2) {
1516
+ fire_event({
1517
+ type: "data",
1518
+ time: /* @__PURE__ */ new Date(),
1519
+ data: data2.data,
1520
+ endpoint: _endpoint,
1521
+ fn_index
1522
+ });
1523
+ if (complete) {
1524
+ fire_event({
1525
+ type: "status",
1526
+ time: /* @__PURE__ */ new Date(),
1527
+ ...complete,
1528
+ stage: status2 == null ? void 0 : status2.stage,
1529
+ queue: true,
1530
+ endpoint: _endpoint,
1531
+ fn_index
1532
+ });
1533
+ }
1534
+ }
1535
+ if ((status2 == null ? void 0 : status2.stage) === "complete" || (status2 == null ? void 0 : status2.stage) === "error") {
1536
+ if (event_callbacks[event_id]) {
1537
+ delete event_callbacks[event_id];
1538
+ }
1539
+ if (event_id in pending_diff_streams) {
1540
+ delete pending_diff_streams[event_id];
1541
+ }
1542
+ }
1543
+ } catch (e) {
1544
+ console.error("Unexpected client exception", e);
876
1545
  fire_event({
877
1546
  type: "status",
878
1547
  stage: "error",
879
- message: BROKEN_CONNECTION_MSG,
1548
+ message: "An Unexpected Error Occurred!",
880
1549
  queue: true,
881
1550
  endpoint: _endpoint,
882
1551
  fn_index,
883
1552
  time: /* @__PURE__ */ new Date()
884
1553
  });
885
- } else {
886
- event_id = response.event_id;
887
- let callback = async function(_data) {
888
- try {
889
- const { type, status: status2, data: data2 } = handle_message(
890
- _data,
891
- last_status[fn_index]
892
- );
893
- if (type == "heartbeat") {
894
- return;
895
- }
896
- if (type === "update" && status2 && !complete) {
897
- fire_event({
898
- type: "status",
899
- endpoint: _endpoint,
900
- fn_index,
901
- time: /* @__PURE__ */ new Date(),
902
- ...status2
903
- });
904
- } else if (type === "complete") {
905
- complete = status2;
906
- } else if (type == "unexpected_error") {
907
- console.error("Unexpected error", status2 == null ? void 0 : status2.message);
908
- fire_event({
909
- type: "status",
910
- stage: "error",
911
- message: (status2 == null ? void 0 : status2.message) || "An Unexpected Error Occurred!",
912
- queue: true,
913
- endpoint: _endpoint,
914
- fn_index,
915
- time: /* @__PURE__ */ new Date()
916
- });
917
- } else if (type === "log") {
918
- fire_event({
919
- type: "log",
920
- log: data2.log,
921
- level: data2.level,
922
- endpoint: _endpoint,
923
- fn_index
924
- });
925
- return;
926
- } else if (type === "generating") {
927
- fire_event({
928
- type: "status",
929
- time: /* @__PURE__ */ new Date(),
930
- ...status2,
931
- stage: status2 == null ? void 0 : status2.stage,
932
- queue: true,
933
- endpoint: _endpoint,
934
- fn_index
935
- });
936
- if (data2 && ["sse_v2", "sse_v2.1", "sse_v3"].includes(protocol)) {
937
- apply_diff_stream(event_id, data2);
938
- }
939
- }
940
- if (data2) {
941
- fire_event({
942
- type: "data",
943
- time: /* @__PURE__ */ new Date(),
944
- data: data2.data,
945
- endpoint: _endpoint,
946
- fn_index
947
- });
948
- if (complete) {
949
- fire_event({
950
- type: "status",
951
- time: /* @__PURE__ */ new Date(),
952
- ...complete,
953
- stage: status2 == null ? void 0 : status2.stage,
954
- queue: true,
955
- endpoint: _endpoint,
956
- fn_index
957
- });
958
- }
959
- }
960
- if ((status2 == null ? void 0 : status2.stage) === "complete" || (status2 == null ? void 0 : status2.stage) === "error") {
961
- if (event_callbacks[event_id]) {
962
- delete event_callbacks[event_id];
963
- }
964
- if (event_id in pending_diff_streams) {
965
- delete pending_diff_streams[event_id];
966
- }
967
- }
968
- } catch (e) {
969
- console.error("Unexpected client exception", e);
970
- fire_event({
971
- type: "status",
972
- stage: "error",
973
- message: "An Unexpected Error Occurred!",
974
- queue: true,
975
- endpoint: _endpoint,
976
- fn_index,
977
- time: /* @__PURE__ */ new Date()
978
- });
979
- if (["sse_v2", "sse_v2.1"].includes(protocol)) {
980
- close_stream();
981
- }
982
- }
983
- };
984
- if (event_id in pending_stream_messages) {
985
- pending_stream_messages[event_id].forEach(
986
- (msg) => callback(msg)
987
- );
988
- delete pending_stream_messages[event_id];
989
- }
990
- event_callbacks[event_id] = callback;
991
- unclosed_events.add(event_id);
992
- if (!stream_open) {
993
- open_stream();
1554
+ if (["sse_v2", "sse_v2.1"].includes(protocol)) {
1555
+ close_stream(stream_status, stream);
1556
+ stream_status.open = false;
994
1557
  }
995
1558
  }
996
- });
997
- }
998
- }
999
- );
1000
- function apply_diff_stream(event_id2, data2) {
1001
- let is_first_generation = !pending_diff_streams[event_id2];
1002
- if (is_first_generation) {
1003
- pending_diff_streams[event_id2] = [];
1004
- data2.data.forEach((value, i) => {
1005
- pending_diff_streams[event_id2][i] = value;
1006
- });
1007
- } else {
1008
- data2.data.forEach((value, i) => {
1009
- let new_data = apply_diff(
1010
- pending_diff_streams[event_id2][i],
1011
- value
1012
- );
1013
- pending_diff_streams[event_id2][i] = new_data;
1014
- data2.data[i] = new_data;
1015
- });
1016
- }
1017
- }
1018
- function fire_event(event) {
1019
- const narrowed_listener_map = listener_map;
1020
- const listeners = narrowed_listener_map[event.type] || [];
1021
- listeners == null ? void 0 : listeners.forEach((l) => l(event));
1022
- }
1023
- function on(eventType, listener) {
1024
- const narrowed_listener_map = listener_map;
1025
- const listeners = narrowed_listener_map[eventType] || [];
1026
- narrowed_listener_map[eventType] = listeners;
1027
- listeners == null ? void 0 : listeners.push(listener);
1028
- return { on, off, cancel, destroy };
1029
- }
1030
- function off(eventType, listener) {
1031
- const narrowed_listener_map = listener_map;
1032
- let listeners = narrowed_listener_map[eventType] || [];
1033
- listeners = listeners == null ? void 0 : listeners.filter((l) => l !== listener);
1034
- narrowed_listener_map[eventType] = listeners;
1035
- return { on, off, cancel, destroy };
1036
- }
1037
- async function cancel() {
1038
- const _status = {
1039
- stage: "complete",
1040
- queue: false,
1041
- time: /* @__PURE__ */ new Date()
1042
- };
1043
- complete = _status;
1044
- fire_event({
1045
- ..._status,
1046
- type: "status",
1047
- endpoint: _endpoint,
1048
- fn_index
1049
- });
1050
- let cancel_request = {};
1051
- if (protocol === "ws") {
1052
- if (websocket && websocket.readyState === 0) {
1053
- websocket.addEventListener("open", () => {
1054
- websocket.close();
1055
- });
1056
- } else {
1057
- websocket.close();
1058
- }
1059
- cancel_request = { fn_index, session_hash };
1060
- } else {
1061
- eventSource.close();
1062
- cancel_request = { event_id };
1063
- }
1064
- try {
1065
- await fetch_implementation(`${config.root}/reset`, {
1066
- headers: { "Content-Type": "application/json" },
1067
- method: "POST",
1068
- body: JSON.stringify(cancel_request)
1069
- });
1070
- } catch (e) {
1071
- console.warn(
1072
- "The `/reset` endpoint could not be called. Subsequent endpoint results may be unreliable."
1073
- );
1074
- }
1075
- }
1076
- function destroy() {
1077
- for (const event_type in listener_map) {
1078
- listener_map[event_type].forEach((fn2) => {
1079
- off(event_type, fn2);
1080
- });
1081
- }
1082
- }
1083
- return {
1084
- on,
1085
- off,
1086
- cancel,
1087
- destroy
1088
- };
1089
- }
1090
- function open_stream() {
1091
- stream_open = true;
1092
- let params = new URLSearchParams({
1093
- session_hash
1094
- }).toString();
1095
- let url = new URL(`${config.root}/queue/data?${params}`);
1096
- event_stream = EventSource_factory(url);
1097
- event_stream.onmessage = async function(event) {
1098
- let _data = JSON.parse(event.data);
1099
- if (_data.msg === "close_stream") {
1100
- close_stream();
1101
- return;
1102
- }
1103
- const event_id = _data.event_id;
1104
- if (!event_id) {
1105
- await Promise.all(
1106
- Object.keys(event_callbacks).map(
1107
- (event_id2) => event_callbacks[event_id2](_data)
1108
- )
1109
- );
1110
- } else if (event_callbacks[event_id]) {
1111
- if (_data.msg === "process_completed" && ["sse", "sse_v1", "sse_v2", "sse_v2.1"].includes(config.protocol)) {
1112
- unclosed_events.delete(event_id);
1113
- if (unclosed_events.size === 0) {
1114
- close_stream();
1559
+ };
1560
+ if (event_id in pending_stream_messages) {
1561
+ pending_stream_messages[event_id].forEach(
1562
+ (msg) => callback(msg)
1563
+ );
1564
+ delete pending_stream_messages[event_id];
1565
+ }
1566
+ event_callbacks[event_id] = callback;
1567
+ unclosed_events.add(event_id);
1568
+ if (!stream_status.open) {
1569
+ this.open_stream();
1115
1570
  }
1116
1571
  }
1117
- let fn2 = event_callbacks[event_id];
1118
- window.setTimeout(fn2, 0, _data);
1119
- } else {
1120
- if (!pending_stream_messages[event_id]) {
1121
- pending_stream_messages[event_id] = [];
1122
- }
1123
- pending_stream_messages[event_id].push(_data);
1124
- }
1125
- };
1126
- event_stream.onerror = async function(event) {
1127
- await Promise.all(
1128
- Object.keys(event_callbacks).map(
1129
- (event_id) => event_callbacks[event_id]({
1130
- msg: "unexpected_error",
1131
- message: BROKEN_CONNECTION_MSG
1132
- })
1133
- )
1134
- );
1135
- close_stream();
1136
- };
1137
- }
1138
- function close_stream() {
1139
- stream_open = false;
1140
- event_stream == null ? void 0 : event_stream.close();
1141
- }
1142
- async function component_server(component_id, fn_name, data) {
1143
- var _a;
1144
- const headers = {};
1145
- let root_url;
1146
- let component = config.components.find(
1147
- (comp) => comp.id === component_id
1148
- );
1149
- if ((_a = component == null ? void 0 : component.props) == null ? void 0 : _a.root_url) {
1150
- root_url = component.props.root_url;
1151
- } else {
1152
- root_url = config.root;
1153
- }
1154
- let body;
1155
- if (data.binary) {
1156
- body = new FormData();
1157
- for (const key in data.data) {
1158
- if (key === "binary")
1159
- continue;
1160
- body.append(key, data.data[key]);
1161
- }
1162
- body.set("component_id", component_id);
1163
- body.set("fn_name", fn_name);
1164
- body.set("session_hash", session_hash);
1165
- } else {
1166
- body = JSON.stringify({
1167
- data,
1168
- component_id,
1169
- fn_name,
1170
- session_hash
1171
- });
1172
- headers["Content-Type"] = "application/json";
1173
- }
1174
- if (hf_token) {
1175
- headers.Authorization = `Bearer ${hf_token}`;
1176
- }
1177
- try {
1178
- const response = await fetch_implementation(
1179
- `${root_url}/component_server/`,
1180
- {
1181
- method: "POST",
1182
- body,
1183
- headers
1184
- }
1185
- );
1186
- if (!response.ok) {
1187
- throw new Error(
1188
- "Could not connect to component server: " + response.statusText
1189
- );
1190
- }
1191
- const output = await response.json();
1192
- return output;
1193
- } catch (e) {
1194
- console.warn(e);
1195
- }
1196
- }
1197
- async function view_api(config2) {
1198
- if (api)
1199
- return api;
1200
- const headers = { "Content-Type": "application/json" };
1201
- if (hf_token) {
1202
- headers.Authorization = `Bearer ${hf_token}`;
1203
- }
1204
- let response;
1205
- if (semiver(config2.version || "2.0.0", "3.30") < 0) {
1206
- response = await fetch_implementation(
1207
- "https://gradio-space-api-fetcher-v2.hf.space/api",
1208
- {
1209
- method: "POST",
1210
- body: JSON.stringify({
1211
- serialize: false,
1212
- config: JSON.stringify(config2)
1213
- }),
1214
- headers
1215
- }
1216
- );
1217
- } else {
1218
- response = await fetch_implementation(`${config2.root}/info`, {
1219
- headers
1220
1572
  });
1221
1573
  }
1222
- if (!response.ok) {
1223
- throw new Error(BROKEN_CONNECTION_MSG);
1224
- }
1225
- let api_info = await response.json();
1226
- if ("api" in api_info) {
1227
- api_info = api_info.api;
1228
- }
1229
- if (api_info.named_endpoints["/predict"] && !api_info.unnamed_endpoints["0"]) {
1230
- api_info.unnamed_endpoints[0] = api_info.named_endpoints["/predict"];
1231
- }
1232
- const x = transform_api_info(api_info, config2, api_map);
1233
- return x;
1234
1574
  }
1235
- });
1236
- }
1237
- async function handle_blob2(endpoint, data, api_info, token) {
1238
- const blob_refs = await walk_and_store_blobs(
1239
- data,
1240
- void 0,
1241
- [],
1242
- true,
1243
- api_info
1244
1575
  );
1245
- return Promise.all(
1246
- blob_refs.map(async ({ path, blob, type }) => {
1247
- if (blob) {
1248
- const file_url = (await upload_files2(endpoint, [blob], token)).files[0];
1249
- return { path, file_url, type, name: blob == null ? void 0 : blob.name };
1250
- }
1251
- return { path, type };
1252
- })
1253
- ).then((r) => {
1254
- r.forEach(({ path, file_url, type, name }) => {
1255
- if (type === "Gallery") {
1256
- update_object(data, file_url, path);
1257
- } else if (file_url) {
1258
- const file = new FileData({ path: file_url, orig_name: name });
1259
- update_object(data, file, path);
1260
- }
1261
- });
1262
- return data;
1263
- });
1576
+ return { on, off, cancel, destroy };
1577
+ } catch (error) {
1578
+ console.error("Submit function encountered an error:", error);
1579
+ throw error;
1264
1580
  }
1265
1581
  }
1266
- const { post_data, upload_files, client, handle_blob } = api_factory(
1267
- fetch,
1268
- (...args) => new EventSource(...args)
1269
- );
1270
- function get_type(type, component, serializer, signature_type) {
1271
- switch (type.type) {
1272
- case "string":
1273
- return "string";
1274
- case "boolean":
1275
- return "boolean";
1276
- case "number":
1277
- return "number";
1582
+ function get_endpoint_info(api_info, endpoint, api_map, config) {
1583
+ let fn_index;
1584
+ let endpoint_info;
1585
+ let dependency;
1586
+ if (typeof endpoint === "number") {
1587
+ fn_index = endpoint;
1588
+ endpoint_info = api_info.unnamed_endpoints[fn_index];
1589
+ dependency = config.dependencies[endpoint];
1590
+ } else {
1591
+ const trimmed_endpoint = endpoint.replace(/^\//, "");
1592
+ fn_index = api_map[trimmed_endpoint];
1593
+ endpoint_info = api_info.named_endpoints[endpoint.trim()];
1594
+ dependency = config.dependencies[api_map[trimmed_endpoint]];
1278
1595
  }
1279
- if (serializer === "JSONSerializable" || serializer === "StringSerializable") {
1280
- return "any";
1281
- } else if (serializer === "ListStringSerializable") {
1282
- return "string[]";
1283
- } else if (component === "Image") {
1284
- return signature_type === "parameter" ? "Blob | File | Buffer" : "string";
1285
- } else if (serializer === "FileSerializable") {
1286
- if ((type == null ? void 0 : type.type) === "array") {
1287
- return signature_type === "parameter" ? "(Blob | File | Buffer)[]" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}[]`;
1288
- }
1289
- return signature_type === "parameter" ? "Blob | File | Buffer" : `{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}`;
1290
- } else if (serializer === "GallerySerializable") {
1291
- return signature_type === "parameter" ? "[(Blob | File | Buffer), (string | null)][]" : `[{ name: string; data: string; size?: number; is_file?: boolean; orig_name?: string}, (string | null))][]`;
1596
+ if (typeof fn_index !== "number") {
1597
+ throw new Error(
1598
+ "There is no endpoint matching that name of fn_index matching that number."
1599
+ );
1292
1600
  }
1601
+ return { fn_index, endpoint_info, dependency };
1293
1602
  }
1294
- function get_description(type, serializer) {
1295
- if (serializer === "GallerySerializable") {
1296
- return "array of [file, label] tuples";
1297
- } else if (serializer === "ListStringSerializable") {
1298
- return "array of strings";
1299
- } else if (serializer === "FileSerializable") {
1300
- return "array of files or single file";
1603
+ class NodeBlob extends Blob {
1604
+ constructor(blobParts, options) {
1605
+ super(blobParts, options);
1301
1606
  }
1302
- return type.description;
1303
1607
  }
1304
- function transform_api_info(api_info, config, api_map) {
1305
- const new_data = {
1306
- named_endpoints: {},
1307
- unnamed_endpoints: {}
1308
- };
1309
- for (const key in api_info) {
1310
- const cat = api_info[key];
1311
- for (const endpoint in cat) {
1312
- const dep_index = config.dependencies[endpoint] ? endpoint : api_map[endpoint.replace("/", "")];
1313
- const info = cat[endpoint];
1314
- new_data[key][endpoint] = {};
1315
- new_data[key][endpoint].parameters = {};
1316
- new_data[key][endpoint].returns = {};
1317
- new_data[key][endpoint].type = config.dependencies[dep_index].types;
1318
- new_data[key][endpoint].parameters = info.parameters.map(
1319
- ({ label, component, type, serializer }) => ({
1320
- label,
1321
- component,
1322
- type: get_type(type, component, serializer, "parameter"),
1323
- description: get_description(type, serializer)
1324
- })
1325
- );
1326
- new_data[key][endpoint].returns = info.returns.map(
1327
- ({ label, component, type, serializer }) => ({
1328
- label,
1329
- component,
1330
- type: get_type(type, component, serializer, "return"),
1331
- description: get_description(type, serializer)
1332
- })
1608
+ class Client {
1609
+ constructor(app_reference, options = {}) {
1610
+ __publicField(this, "app_reference");
1611
+ __publicField(this, "options");
1612
+ __publicField(this, "config");
1613
+ __publicField(this, "api_info");
1614
+ __publicField(this, "api_map", {});
1615
+ __publicField(this, "session_hash", Math.random().toString(36).substring(2));
1616
+ __publicField(this, "jwt", false);
1617
+ __publicField(this, "last_status", {});
1618
+ // streaming
1619
+ __publicField(this, "stream_status", { open: false });
1620
+ __publicField(this, "pending_stream_messages", {});
1621
+ __publicField(this, "pending_diff_streams", {});
1622
+ __publicField(this, "event_callbacks", {});
1623
+ __publicField(this, "unclosed_events", /* @__PURE__ */ new Set());
1624
+ __publicField(this, "heartbeat_event", null);
1625
+ __publicField(this, "view_api");
1626
+ __publicField(this, "upload_files");
1627
+ __publicField(this, "upload");
1628
+ __publicField(this, "handle_blob");
1629
+ __publicField(this, "post_data");
1630
+ __publicField(this, "submit");
1631
+ __publicField(this, "predict");
1632
+ __publicField(this, "open_stream");
1633
+ __publicField(this, "resolve_config");
1634
+ this.app_reference = app_reference;
1635
+ this.options = options;
1636
+ this.view_api = view_api.bind(this);
1637
+ this.upload_files = upload_files.bind(this);
1638
+ this.handle_blob = handle_blob.bind(this);
1639
+ this.post_data = post_data.bind(this);
1640
+ this.submit = submit.bind(this);
1641
+ this.predict = predict.bind(this);
1642
+ this.open_stream = open_stream.bind(this);
1643
+ this.resolve_config = resolve_config.bind(this);
1644
+ this.upload = upload.bind(this);
1645
+ }
1646
+ fetch(input, init) {
1647
+ return fetch(input, init);
1648
+ }
1649
+ stream_factory(url) {
1650
+ if (typeof window === "undefined" || typeof EventSource === "undefined") {
1651
+ import("eventsource").then((EventSourceModule) => {
1652
+ return new EventSourceModule.default(url.toString());
1653
+ }).catch(
1654
+ (error) => console.error("Failed to load EventSource module:", error)
1333
1655
  );
1656
+ } else {
1657
+ return new EventSource(url.toString());
1334
1658
  }
1659
+ return null;
1335
1660
  }
1336
- return new_data;
1337
- }
1338
- async function get_jwt(space, token) {
1339
- try {
1340
- const r = await fetch(`https://huggingface.co/api/spaces/${space}/jwt`, {
1341
- headers: {
1342
- Authorization: `Bearer ${token}`
1343
- }
1344
- });
1345
- const jwt = (await r.json()).token;
1346
- return jwt || false;
1347
- } catch (e) {
1348
- console.error(e);
1349
- return false;
1661
+ async init() {
1662
+ var _a;
1663
+ if ((typeof window === "undefined" || !("WebSocket" in window)) && !global.WebSocket) {
1664
+ const ws = await import("./wrapper-CviSselG.js");
1665
+ NodeBlob = (await import("node:buffer")).Blob;
1666
+ global.WebSocket = ws.WebSocket;
1667
+ }
1668
+ try {
1669
+ await this._resolve_config().then(async ({ config }) => {
1670
+ if (config) {
1671
+ this.config = config;
1672
+ if (this.config && this.config.connect_heartbeat) {
1673
+ const heartbeat_url = new URL(
1674
+ `${this.config.root}/heartbeat/${this.session_hash}`
1675
+ );
1676
+ this.heartbeat_event = this.stream_factory(heartbeat_url);
1677
+ if (this.config.space_id && this.options.hf_token) {
1678
+ this.jwt = await get_jwt(
1679
+ this.config.space_id,
1680
+ this.options.hf_token
1681
+ );
1682
+ }
1683
+ }
1684
+ }
1685
+ });
1686
+ } catch (e) {
1687
+ throw Error(CONFIG_ERROR_MSG + e.message);
1688
+ }
1689
+ this.api_info = await this.view_api();
1690
+ this.api_map = map_names_to_ids(((_a = this.config) == null ? void 0 : _a.dependencies) || []);
1350
1691
  }
1351
- }
1352
- function update_object(object, newValue, stack) {
1353
- while (stack.length > 1) {
1354
- object = object[stack.shift()];
1692
+ static async connect(app_reference, options = {}) {
1693
+ const client2 = new this(app_reference, options);
1694
+ await client2.init();
1695
+ return client2;
1696
+ }
1697
+ close() {
1698
+ var _a;
1699
+ (_a = this.heartbeat_event) == null ? void 0 : _a.close();
1700
+ }
1701
+ static async duplicate(app_reference, options = {}) {
1702
+ return duplicate(app_reference, options);
1355
1703
  }
1356
- object[stack.shift()] = newValue;
1357
- }
1358
- async function walk_and_store_blobs(param, type = void 0, path = [], root = false, api_info = void 0) {
1359
- if (Array.isArray(param)) {
1360
- let blob_refs = [];
1361
- await Promise.all(
1362
- param.map(async (v, i) => {
1363
- var _a;
1364
- let new_path = path.slice();
1365
- new_path.push(i);
1366
- const array_refs = await walk_and_store_blobs(
1367
- param[i],
1368
- root ? ((_a = api_info == null ? void 0 : api_info.parameters[i]) == null ? void 0 : _a.component) || void 0 : type,
1369
- new_path,
1370
- false,
1371
- api_info
1372
- );
1373
- blob_refs = blob_refs.concat(array_refs);
1374
- })
1704
+ async _resolve_config() {
1705
+ const { http_protocol, host, space_id } = await process_endpoint(
1706
+ this.app_reference,
1707
+ this.options.hf_token
1375
1708
  );
1376
- return blob_refs;
1377
- } else if (globalThis.Buffer && param instanceof globalThis.Buffer) {
1378
- const is_image = type === "Image";
1379
- return [
1380
- {
1381
- path,
1382
- blob: is_image ? false : new NodeBlob([param]),
1383
- type
1709
+ const { status_callback } = this.options;
1710
+ let config;
1711
+ try {
1712
+ config = await this.resolve_config(`${http_protocol}//${host}`);
1713
+ if (!config) {
1714
+ throw new Error(CONFIG_ERROR_MSG);
1384
1715
  }
1385
- ];
1386
- } else if (typeof param === "object") {
1387
- let blob_refs = [];
1388
- for (let key in param) {
1389
- if (param.hasOwnProperty(key)) {
1390
- let new_path = path.slice();
1391
- new_path.push(key);
1392
- blob_refs = blob_refs.concat(
1393
- await walk_and_store_blobs(
1394
- param[key],
1395
- void 0,
1396
- new_path,
1397
- false,
1398
- api_info
1399
- )
1716
+ return this.config_success(config);
1717
+ } catch (e) {
1718
+ console.error(e);
1719
+ if (space_id) {
1720
+ check_space_status(
1721
+ space_id,
1722
+ RE_SPACE_NAME.test(space_id) ? "space_name" : "subdomain",
1723
+ this.handle_space_success
1400
1724
  );
1725
+ } else {
1726
+ if (status_callback)
1727
+ status_callback({
1728
+ status: "error",
1729
+ message: "Could not load this space.",
1730
+ load_status: "error",
1731
+ detail: "NOT_FOUND"
1732
+ });
1401
1733
  }
1402
1734
  }
1403
- return blob_refs;
1404
- }
1405
- return [];
1406
- }
1407
- function skip_queue(id, config) {
1408
- var _a, _b, _c, _d;
1409
- return !(((_b = (_a = config == null ? void 0 : config.dependencies) == null ? void 0 : _a[id]) == null ? void 0 : _b.queue) === null ? config.enable_queue : (_d = (_c = config == null ? void 0 : config.dependencies) == null ? void 0 : _c[id]) == null ? void 0 : _d.queue) || false;
1410
- }
1411
- async function resolve_config(fetch_implementation, endpoint, token) {
1412
- const headers = {};
1413
- if (token) {
1414
- headers.Authorization = `Bearer ${token}`;
1415
1735
  }
1416
- if (typeof window !== "undefined" && window.gradio_config && location.origin !== "http://localhost:9876" && !window.gradio_config.dev_mode) {
1417
- const path = window.gradio_config.root;
1418
- const config = window.gradio_config;
1419
- config.root = resolve_root(endpoint, config.root, false);
1420
- return { ...config, path };
1421
- } else if (endpoint) {
1422
- let response = await fetch_implementation(`${endpoint}/config`, {
1423
- headers
1424
- });
1425
- if (response.status === 200) {
1426
- const config = await response.json();
1427
- config.path = config.path ?? "";
1428
- config.root = endpoint;
1429
- return config;
1736
+ async config_success(_config) {
1737
+ this.config = _config;
1738
+ if (typeof window !== "undefined") {
1739
+ if (window.location.protocol === "https:") {
1740
+ this.config.root = this.config.root.replace("http://", "https://");
1741
+ }
1742
+ }
1743
+ if (this.config.auth_required) {
1744
+ return this.prepare_return_obj();
1430
1745
  }
1431
- throw new Error("Could not get config.");
1746
+ try {
1747
+ this.api_info = await this.view_api();
1748
+ } catch (e) {
1749
+ console.error(API_INFO_ERROR_MSG + e.message);
1750
+ }
1751
+ return this.prepare_return_obj();
1432
1752
  }
1433
- throw new Error("No config or app endpoint found");
1434
- }
1435
- async function check_space_status(id, type, status_callback) {
1436
- let endpoint = type === "subdomain" ? `https://huggingface.co/api/spaces/by-subdomain/${id}` : `https://huggingface.co/api/spaces/${id}`;
1437
- let response;
1438
- let _status;
1439
- try {
1440
- response = await fetch(endpoint);
1441
- _status = response.status;
1442
- if (_status !== 200) {
1443
- throw new Error();
1753
+ async handle_space_success(status) {
1754
+ const { status_callback } = this.options;
1755
+ if (status_callback)
1756
+ status_callback(status);
1757
+ if (status.status === "running") {
1758
+ try {
1759
+ this.config = await this._resolve_config();
1760
+ if (!this.config) {
1761
+ throw new Error(CONFIG_ERROR_MSG);
1762
+ }
1763
+ const _config = await this.config_success(this.config);
1764
+ return _config;
1765
+ } catch (e) {
1766
+ console.error(e);
1767
+ if (status_callback) {
1768
+ status_callback({
1769
+ status: "error",
1770
+ message: "Could not load this space.",
1771
+ load_status: "error",
1772
+ detail: "NOT_FOUND"
1773
+ });
1774
+ }
1775
+ }
1444
1776
  }
1445
- response = await response.json();
1446
- } catch (e) {
1447
- status_callback({
1448
- status: "error",
1449
- load_status: "error",
1450
- message: "Could not get space status",
1451
- detail: "NOT_FOUND"
1452
- });
1453
- return;
1454
1777
  }
1455
- if (!response || _status !== 200)
1456
- return;
1457
- const {
1458
- runtime: { stage },
1459
- id: space_name
1460
- } = response;
1461
- switch (stage) {
1462
- case "STOPPED":
1463
- case "SLEEPING":
1464
- status_callback({
1465
- status: "sleeping",
1466
- load_status: "pending",
1467
- message: "Space is asleep. Waking it up...",
1468
- detail: stage
1469
- });
1470
- setTimeout(() => {
1471
- check_space_status(id, type, status_callback);
1472
- }, 1e3);
1473
- break;
1474
- case "PAUSED":
1475
- status_callback({
1476
- status: "paused",
1477
- load_status: "error",
1478
- message: "This space has been paused by the author. If you would like to try this demo, consider duplicating the space.",
1479
- detail: stage,
1480
- discussions_enabled: await discussions_enabled(space_name)
1481
- });
1482
- break;
1483
- case "RUNNING":
1484
- case "RUNNING_BUILDING":
1485
- status_callback({
1486
- status: "running",
1487
- load_status: "complete",
1488
- message: "",
1489
- detail: stage
1490
- });
1491
- break;
1492
- case "BUILDING":
1493
- status_callback({
1494
- status: "building",
1495
- load_status: "pending",
1496
- message: "Space is building...",
1497
- detail: stage
1778
+ async component_server(component_id, fn_name, data) {
1779
+ var _a;
1780
+ if (!this.config) {
1781
+ throw new Error(CONFIG_ERROR_MSG);
1782
+ }
1783
+ const headers = {};
1784
+ const { hf_token } = this.options;
1785
+ const { session_hash } = this;
1786
+ if (hf_token) {
1787
+ headers.Authorization = `Bearer ${this.options.hf_token}`;
1788
+ }
1789
+ let root_url;
1790
+ let component = this.config.components.find(
1791
+ (comp) => comp.id === component_id
1792
+ );
1793
+ if ((_a = component == null ? void 0 : component.props) == null ? void 0 : _a.root_url) {
1794
+ root_url = component.props.root_url;
1795
+ } else {
1796
+ root_url = this.config.root;
1797
+ }
1798
+ let body;
1799
+ if ("binary" in data) {
1800
+ body = new FormData();
1801
+ for (const key in data.data) {
1802
+ if (key === "binary")
1803
+ continue;
1804
+ body.append(key, data.data[key]);
1805
+ }
1806
+ body.set("component_id", component_id.toString());
1807
+ body.set("fn_name", fn_name);
1808
+ body.set("session_hash", session_hash);
1809
+ } else {
1810
+ body = JSON.stringify({
1811
+ data,
1812
+ component_id,
1813
+ fn_name,
1814
+ session_hash
1498
1815
  });
1499
- setTimeout(() => {
1500
- check_space_status(id, type, status_callback);
1501
- }, 1e3);
1502
- break;
1503
- default:
1504
- status_callback({
1505
- status: "space_error",
1506
- load_status: "error",
1507
- message: "This space is experiencing an issue.",
1508
- detail: stage,
1509
- discussions_enabled: await discussions_enabled(space_name)
1816
+ headers["Content-Type"] = "application/json";
1817
+ }
1818
+ if (hf_token) {
1819
+ headers.Authorization = `Bearer ${hf_token}`;
1820
+ }
1821
+ try {
1822
+ const response = await this.fetch(`${root_url}/component_server/`, {
1823
+ method: "POST",
1824
+ body,
1825
+ headers
1510
1826
  });
1511
- break;
1512
- }
1513
- }
1514
- function handle_message(data, last_status) {
1515
- const queue = true;
1516
- switch (data.msg) {
1517
- case "send_data":
1518
- return { type: "data" };
1519
- case "send_hash":
1520
- return { type: "hash" };
1521
- case "queue_full":
1522
- return {
1523
- type: "update",
1524
- status: {
1525
- queue,
1526
- message: QUEUE_FULL_MSG,
1527
- stage: "error",
1528
- code: data.code,
1529
- success: data.success
1530
- }
1531
- };
1532
- case "heartbeat":
1533
- return {
1534
- type: "heartbeat"
1535
- };
1536
- case "unexpected_error":
1537
- return {
1538
- type: "unexpected_error",
1539
- status: {
1540
- queue,
1541
- message: data.message,
1542
- stage: "error",
1543
- success: false
1544
- }
1545
- };
1546
- case "estimation":
1547
- return {
1548
- type: "update",
1549
- status: {
1550
- queue,
1551
- stage: last_status || "pending",
1552
- code: data.code,
1553
- size: data.queue_size,
1554
- position: data.rank,
1555
- eta: data.rank_eta,
1556
- success: data.success
1557
- }
1558
- };
1559
- case "progress":
1560
- return {
1561
- type: "update",
1562
- status: {
1563
- queue,
1564
- stage: "pending",
1565
- code: data.code,
1566
- progress_data: data.progress_data,
1567
- success: data.success
1568
- }
1569
- };
1570
- case "log":
1571
- return { type: "log", data };
1572
- case "process_generating":
1573
- return {
1574
- type: "generating",
1575
- status: {
1576
- queue,
1577
- message: !data.success ? data.output.error : null,
1578
- stage: data.success ? "generating" : "error",
1579
- code: data.code,
1580
- progress_data: data.progress_data,
1581
- eta: data.average_duration
1582
- },
1583
- data: data.success ? data.output : null
1584
- };
1585
- case "process_completed":
1586
- if ("error" in data.output) {
1587
- return {
1588
- type: "update",
1589
- status: {
1590
- queue,
1591
- message: data.output.error,
1592
- stage: "error",
1593
- code: data.code,
1594
- success: data.success
1595
- }
1596
- };
1827
+ if (!response.ok) {
1828
+ throw new Error(
1829
+ "Could not connect to component server: " + response.statusText
1830
+ );
1597
1831
  }
1598
- return {
1599
- type: "complete",
1600
- status: {
1601
- queue,
1602
- message: !data.success ? data.output.error : void 0,
1603
- stage: data.success ? "complete" : "error",
1604
- code: data.code,
1605
- progress_data: data.progress_data
1606
- },
1607
- data: data.success ? data.output : null
1608
- };
1609
- case "process_starts":
1610
- return {
1611
- type: "update",
1612
- status: {
1613
- queue,
1614
- stage: "pending",
1615
- code: data.code,
1616
- size: data.rank,
1617
- position: 0,
1618
- success: data.success,
1619
- eta: data.eta
1620
- }
1621
- };
1832
+ const output = await response.json();
1833
+ return output;
1834
+ } catch (e) {
1835
+ console.warn(e);
1836
+ }
1622
1837
  }
1623
- return { type: "none", status: { stage: "error", queue } };
1838
+ prepare_return_obj() {
1839
+ return {
1840
+ config: this.config,
1841
+ predict: this.predict,
1842
+ submit: this.submit,
1843
+ view_api: this.view_api,
1844
+ component_server: this.component_server
1845
+ };
1846
+ }
1847
+ }
1848
+ async function client(app_reference, options = {}) {
1849
+ return await Client.connect(app_reference, options);
1850
+ }
1851
+ async function duplicate_space(app_reference, options) {
1852
+ return await Client.duplicate(app_reference, options);
1624
1853
  }
1625
1854
  export {
1855
+ Client,
1626
1856
  FileData,
1627
- api_factory,
1628
1857
  client,
1629
- duplicate,
1630
- post_data,
1858
+ duplicate_space as duplicate,
1859
+ predict,
1631
1860
  prepare_files,
1861
+ submit,
1632
1862
  upload,
1633
1863
  upload_files
1634
1864
  };