@blockspark/chat-widget 1.0.17 → 1.0.18

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 (41) hide show
  1. package/README.md +28 -28
  2. package/dist/{ChatWidget-DKfLes8T.js → ChatWidget-Bs0XV_7i.js} +31 -36
  3. package/dist/ChatWidget-Bs0XV_7i.js.map +1 -0
  4. package/dist/ChatWidget-PcqRrOmi.cjs +2 -0
  5. package/dist/ChatWidget-PcqRrOmi.cjs.map +1 -0
  6. package/dist/adapters/vue/useChatMode.d.ts +1 -1
  7. package/dist/adapters/vue/useChatMode.d.ts.map +1 -1
  8. package/dist/components/ChatWidget.d.ts +1 -5
  9. package/dist/components/ChatWidget.d.ts.map +1 -1
  10. package/dist/core/stateManager.d.ts.map +1 -1
  11. package/dist/core/types.d.ts +0 -2
  12. package/dist/core/types.d.ts.map +1 -1
  13. package/dist/entry/vite.d.ts +1 -1
  14. package/dist/hooks/useChatMode.d.ts +1 -1
  15. package/dist/hooks/useChatMode.d.ts.map +1 -1
  16. package/dist/index.cjs.js +1 -1
  17. package/dist/index.cjs.js.map +1 -1
  18. package/dist/index.d.ts +5 -5
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.esm.js +39 -22
  21. package/dist/index.esm.js.map +1 -1
  22. package/dist/nuxt.cjs.js +1 -1
  23. package/dist/nuxt.esm.js +2 -2
  24. package/dist/sanitize-C8MB41vY.cjs +4 -0
  25. package/dist/sanitize-C8MB41vY.cjs.map +1 -0
  26. package/dist/{sanitize-O18C3eqP.js → sanitize-Cm1kskSD.js} +154 -1260
  27. package/dist/sanitize-Cm1kskSD.js.map +1 -0
  28. package/dist/services/dialogflowBackendService.d.ts +36 -0
  29. package/dist/services/dialogflowBackendService.d.ts.map +1 -0
  30. package/dist/styles.css +1 -1
  31. package/dist/types.d.ts +1 -1
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/vue.cjs.js +1 -1
  34. package/dist/vue.esm.js +2 -2
  35. package/package.json +2 -2
  36. package/dist/ChatWidget-DKfLes8T.js.map +0 -1
  37. package/dist/ChatWidget-lvHzA07s.cjs +0 -2
  38. package/dist/ChatWidget-lvHzA07s.cjs.map +0 -1
  39. package/dist/sanitize-D904jROs.cjs +0 -4
  40. package/dist/sanitize-D904jROs.cjs.map +0 -1
  41. package/dist/sanitize-O18C3eqP.js.map +0 -1
@@ -1,1266 +1,160 @@
1
- const crypto$1 = crypto;
2
- const isCryptoKey = (key) => key instanceof CryptoKey;
3
- const encoder = new TextEncoder();
4
- const decoder = new TextDecoder();
5
- function concat(...buffers) {
6
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
7
- const buf = new Uint8Array(size);
8
- let i = 0;
9
- for (const buffer of buffers) {
10
- buf.set(buffer, i);
11
- i += buffer.length;
12
- }
13
- return buf;
14
- }
15
- const encodeBase64 = (input) => {
16
- let unencoded = input;
17
- if (typeof unencoded === "string") {
18
- unencoded = encoder.encode(unencoded);
19
- }
20
- const CHUNK_SIZE = 32768;
21
- const arr = [];
22
- for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {
23
- arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));
24
- }
25
- return btoa(arr.join(""));
26
- };
27
- const encode = (input) => {
28
- return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
29
- };
30
- const decodeBase64 = (encoded) => {
31
- const binary = atob(encoded);
32
- const bytes = new Uint8Array(binary.length);
33
- for (let i = 0; i < binary.length; i++) {
34
- bytes[i] = binary.charCodeAt(i);
35
- }
36
- return bytes;
37
- };
38
- const decode = (input) => {
39
- let encoded = input;
40
- if (encoded instanceof Uint8Array) {
41
- encoded = decoder.decode(encoded);
42
- }
43
- encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "");
1
+ const DEFAULT_BASE_URL$1 = typeof process !== "undefined" && process.env?.REACT_APP_BACKEND_BASE_URL || "http://localhost:8012";
2
+ async function createDialogflowSession(config, existingSessionId) {
44
3
  try {
45
- return decodeBase64(encoded);
46
- } catch {
47
- throw new TypeError("The input to be decoded is not correctly encoded.");
48
- }
49
- };
50
- class JOSEError extends Error {
51
- constructor(message2, options) {
52
- super(message2, options);
53
- this.code = "ERR_JOSE_GENERIC";
54
- this.name = this.constructor.name;
55
- Error.captureStackTrace?.(this, this.constructor);
56
- }
57
- }
58
- JOSEError.code = "ERR_JOSE_GENERIC";
59
- class JWTClaimValidationFailed extends JOSEError {
60
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
61
- super(message2, { cause: { claim, reason, payload } });
62
- this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
63
- this.claim = claim;
64
- this.reason = reason;
65
- this.payload = payload;
66
- }
67
- }
68
- JWTClaimValidationFailed.code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
69
- class JWTExpired extends JOSEError {
70
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
71
- super(message2, { cause: { claim, reason, payload } });
72
- this.code = "ERR_JWT_EXPIRED";
73
- this.claim = claim;
74
- this.reason = reason;
75
- this.payload = payload;
76
- }
77
- }
78
- JWTExpired.code = "ERR_JWT_EXPIRED";
79
- class JOSEAlgNotAllowed extends JOSEError {
80
- constructor() {
81
- super(...arguments);
82
- this.code = "ERR_JOSE_ALG_NOT_ALLOWED";
83
- }
84
- }
85
- JOSEAlgNotAllowed.code = "ERR_JOSE_ALG_NOT_ALLOWED";
86
- class JOSENotSupported extends JOSEError {
87
- constructor() {
88
- super(...arguments);
89
- this.code = "ERR_JOSE_NOT_SUPPORTED";
90
- }
91
- }
92
- JOSENotSupported.code = "ERR_JOSE_NOT_SUPPORTED";
93
- class JWEDecryptionFailed extends JOSEError {
94
- constructor(message2 = "decryption operation failed", options) {
95
- super(message2, options);
96
- this.code = "ERR_JWE_DECRYPTION_FAILED";
97
- }
98
- }
99
- JWEDecryptionFailed.code = "ERR_JWE_DECRYPTION_FAILED";
100
- class JWEInvalid extends JOSEError {
101
- constructor() {
102
- super(...arguments);
103
- this.code = "ERR_JWE_INVALID";
104
- }
105
- }
106
- JWEInvalid.code = "ERR_JWE_INVALID";
107
- class JWSInvalid extends JOSEError {
108
- constructor() {
109
- super(...arguments);
110
- this.code = "ERR_JWS_INVALID";
111
- }
112
- }
113
- JWSInvalid.code = "ERR_JWS_INVALID";
114
- class JWTInvalid extends JOSEError {
115
- constructor() {
116
- super(...arguments);
117
- this.code = "ERR_JWT_INVALID";
118
- }
119
- }
120
- JWTInvalid.code = "ERR_JWT_INVALID";
121
- class JWKInvalid extends JOSEError {
122
- constructor() {
123
- super(...arguments);
124
- this.code = "ERR_JWK_INVALID";
125
- }
126
- }
127
- JWKInvalid.code = "ERR_JWK_INVALID";
128
- class JWKSInvalid extends JOSEError {
129
- constructor() {
130
- super(...arguments);
131
- this.code = "ERR_JWKS_INVALID";
132
- }
133
- }
134
- JWKSInvalid.code = "ERR_JWKS_INVALID";
135
- class JWKSNoMatchingKey extends JOSEError {
136
- constructor(message2 = "no applicable key found in the JSON Web Key Set", options) {
137
- super(message2, options);
138
- this.code = "ERR_JWKS_NO_MATCHING_KEY";
139
- }
140
- }
141
- JWKSNoMatchingKey.code = "ERR_JWKS_NO_MATCHING_KEY";
142
- class JWKSMultipleMatchingKeys extends JOSEError {
143
- constructor(message2 = "multiple matching keys found in the JSON Web Key Set", options) {
144
- super(message2, options);
145
- this.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
146
- }
147
- }
148
- JWKSMultipleMatchingKeys.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS";
149
- class JWKSTimeout extends JOSEError {
150
- constructor(message2 = "request timed out", options) {
151
- super(message2, options);
152
- this.code = "ERR_JWKS_TIMEOUT";
153
- }
154
- }
155
- JWKSTimeout.code = "ERR_JWKS_TIMEOUT";
156
- class JWSSignatureVerificationFailed extends JOSEError {
157
- constructor(message2 = "signature verification failed", options) {
158
- super(message2, options);
159
- this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
160
- }
161
- }
162
- JWSSignatureVerificationFailed.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
163
- function unusable(name, prop = "algorithm.name") {
164
- return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
165
- }
166
- function isAlgorithm(algorithm, name) {
167
- return algorithm.name === name;
168
- }
169
- function getHashLength(hash) {
170
- return parseInt(hash.name.slice(4), 10);
171
- }
172
- function getNamedCurve$1(alg) {
173
- switch (alg) {
174
- case "ES256":
175
- return "P-256";
176
- case "ES384":
177
- return "P-384";
178
- case "ES512":
179
- return "P-521";
180
- default:
181
- throw new Error("unreachable");
182
- }
183
- }
184
- function checkUsage(key, usages) {
185
- if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {
186
- let msg = "CryptoKey does not support this operation, its usages must include ";
187
- if (usages.length > 2) {
188
- const last = usages.pop();
189
- msg += `one of ${usages.join(", ")}, or ${last}.`;
190
- } else if (usages.length === 2) {
191
- msg += `one of ${usages[0]} or ${usages[1]}.`;
192
- } else {
193
- msg += `${usages[0]}.`;
194
- }
195
- throw new TypeError(msg);
196
- }
197
- }
198
- function checkSigCryptoKey(key, alg, ...usages) {
199
- switch (alg) {
200
- case "HS256":
201
- case "HS384":
202
- case "HS512": {
203
- if (!isAlgorithm(key.algorithm, "HMAC"))
204
- throw unusable("HMAC");
205
- const expected = parseInt(alg.slice(2), 10);
206
- const actual = getHashLength(key.algorithm.hash);
207
- if (actual !== expected)
208
- throw unusable(`SHA-${expected}`, "algorithm.hash");
209
- break;
210
- }
211
- case "RS256":
212
- case "RS384":
213
- case "RS512": {
214
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
215
- throw unusable("RSASSA-PKCS1-v1_5");
216
- const expected = parseInt(alg.slice(2), 10);
217
- const actual = getHashLength(key.algorithm.hash);
218
- if (actual !== expected)
219
- throw unusable(`SHA-${expected}`, "algorithm.hash");
220
- break;
221
- }
222
- case "PS256":
223
- case "PS384":
224
- case "PS512": {
225
- if (!isAlgorithm(key.algorithm, "RSA-PSS"))
226
- throw unusable("RSA-PSS");
227
- const expected = parseInt(alg.slice(2), 10);
228
- const actual = getHashLength(key.algorithm.hash);
229
- if (actual !== expected)
230
- throw unusable(`SHA-${expected}`, "algorithm.hash");
231
- break;
232
- }
233
- case "EdDSA": {
234
- if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") {
235
- throw unusable("Ed25519 or Ed448");
236
- }
237
- break;
238
- }
239
- case "Ed25519": {
240
- if (!isAlgorithm(key.algorithm, "Ed25519"))
241
- throw unusable("Ed25519");
242
- break;
243
- }
244
- case "ES256":
245
- case "ES384":
246
- case "ES512": {
247
- if (!isAlgorithm(key.algorithm, "ECDSA"))
248
- throw unusable("ECDSA");
249
- const expected = getNamedCurve$1(alg);
250
- const actual = key.algorithm.namedCurve;
251
- if (actual !== expected)
252
- throw unusable(expected, "algorithm.namedCurve");
253
- break;
254
- }
255
- default:
256
- throw new TypeError("CryptoKey does not support this operation");
257
- }
258
- checkUsage(key, usages);
259
- }
260
- function message(msg, actual, ...types2) {
261
- types2 = types2.filter(Boolean);
262
- if (types2.length > 2) {
263
- const last = types2.pop();
264
- msg += `one of type ${types2.join(", ")}, or ${last}.`;
265
- } else if (types2.length === 2) {
266
- msg += `one of type ${types2[0]} or ${types2[1]}.`;
267
- } else {
268
- msg += `of type ${types2[0]}.`;
269
- }
270
- if (actual == null) {
271
- msg += ` Received ${actual}`;
272
- } else if (typeof actual === "function" && actual.name) {
273
- msg += ` Received function ${actual.name}`;
274
- } else if (typeof actual === "object" && actual != null) {
275
- if (actual.constructor?.name) {
276
- msg += ` Received an instance of ${actual.constructor.name}`;
277
- }
278
- }
279
- return msg;
280
- }
281
- const invalidKeyInput = (actual, ...types2) => {
282
- return message("Key must be ", actual, ...types2);
283
- };
284
- function withAlg(alg, actual, ...types2) {
285
- return message(`Key for the ${alg} algorithm must be `, actual, ...types2);
286
- }
287
- const isKeyLike = (key) => {
288
- if (isCryptoKey(key)) {
289
- return true;
290
- }
291
- return key?.[Symbol.toStringTag] === "KeyObject";
292
- };
293
- const types = ["CryptoKey"];
294
- const isDisjoint = (...headers) => {
295
- const sources = headers.filter(Boolean);
296
- if (sources.length === 0 || sources.length === 1) {
297
- return true;
298
- }
299
- let acc;
300
- for (const header of sources) {
301
- const parameters = Object.keys(header);
302
- if (!acc || acc.size === 0) {
303
- acc = new Set(parameters);
304
- continue;
305
- }
306
- for (const parameter of parameters) {
307
- if (acc.has(parameter)) {
308
- return false;
309
- }
310
- acc.add(parameter);
311
- }
312
- }
313
- return true;
314
- };
315
- function isObjectLike(value) {
316
- return typeof value === "object" && value !== null;
317
- }
318
- function isObject(input) {
319
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
320
- return false;
321
- }
322
- if (Object.getPrototypeOf(input) === null) {
323
- return true;
324
- }
325
- let proto = input;
326
- while (Object.getPrototypeOf(proto) !== null) {
327
- proto = Object.getPrototypeOf(proto);
328
- }
329
- return Object.getPrototypeOf(input) === proto;
330
- }
331
- const checkKeyLength = (alg, key) => {
332
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
333
- const { modulusLength } = key.algorithm;
334
- if (typeof modulusLength !== "number" || modulusLength < 2048) {
335
- throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
336
- }
337
- }
338
- };
339
- function isJWK(key) {
340
- return isObject(key) && typeof key.kty === "string";
341
- }
342
- function isPrivateJWK(key) {
343
- return key.kty !== "oct" && typeof key.d === "string";
344
- }
345
- function isPublicJWK(key) {
346
- return key.kty !== "oct" && typeof key.d === "undefined";
347
- }
348
- function isSecretJWK(key) {
349
- return isJWK(key) && key.kty === "oct" && typeof key.k === "string";
350
- }
351
- function subtleMapping(jwk) {
352
- let algorithm;
353
- let keyUsages;
354
- switch (jwk.kty) {
355
- case "RSA": {
356
- switch (jwk.alg) {
357
- case "PS256":
358
- case "PS384":
359
- case "PS512":
360
- algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
361
- keyUsages = jwk.d ? ["sign"] : ["verify"];
362
- break;
363
- case "RS256":
364
- case "RS384":
365
- case "RS512":
366
- algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
367
- keyUsages = jwk.d ? ["sign"] : ["verify"];
368
- break;
369
- case "RSA-OAEP":
370
- case "RSA-OAEP-256":
371
- case "RSA-OAEP-384":
372
- case "RSA-OAEP-512":
373
- algorithm = {
374
- name: "RSA-OAEP",
375
- hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
376
- };
377
- keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
378
- break;
379
- default:
380
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
381
- }
382
- break;
383
- }
384
- case "EC": {
385
- switch (jwk.alg) {
386
- case "ES256":
387
- algorithm = { name: "ECDSA", namedCurve: "P-256" };
388
- keyUsages = jwk.d ? ["sign"] : ["verify"];
389
- break;
390
- case "ES384":
391
- algorithm = { name: "ECDSA", namedCurve: "P-384" };
392
- keyUsages = jwk.d ? ["sign"] : ["verify"];
393
- break;
394
- case "ES512":
395
- algorithm = { name: "ECDSA", namedCurve: "P-521" };
396
- keyUsages = jwk.d ? ["sign"] : ["verify"];
397
- break;
398
- case "ECDH-ES":
399
- case "ECDH-ES+A128KW":
400
- case "ECDH-ES+A192KW":
401
- case "ECDH-ES+A256KW":
402
- algorithm = { name: "ECDH", namedCurve: jwk.crv };
403
- keyUsages = jwk.d ? ["deriveBits"] : [];
404
- break;
405
- default:
406
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
407
- }
408
- break;
409
- }
410
- case "OKP": {
411
- switch (jwk.alg) {
412
- case "Ed25519":
413
- algorithm = { name: "Ed25519" };
414
- keyUsages = jwk.d ? ["sign"] : ["verify"];
415
- break;
416
- case "EdDSA":
417
- algorithm = { name: jwk.crv };
418
- keyUsages = jwk.d ? ["sign"] : ["verify"];
419
- break;
420
- case "ECDH-ES":
421
- case "ECDH-ES+A128KW":
422
- case "ECDH-ES+A192KW":
423
- case "ECDH-ES+A256KW":
424
- algorithm = { name: jwk.crv };
425
- keyUsages = jwk.d ? ["deriveBits"] : [];
426
- break;
427
- default:
428
- throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
429
- }
430
- break;
431
- }
432
- default:
433
- throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
434
- }
435
- return { algorithm, keyUsages };
436
- }
437
- const parse = async (jwk) => {
438
- if (!jwk.alg) {
439
- throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
440
- }
441
- const { algorithm, keyUsages } = subtleMapping(jwk);
442
- const rest = [
443
- algorithm,
444
- jwk.ext ?? false,
445
- jwk.key_ops ?? keyUsages
446
- ];
447
- const keyData = { ...jwk };
448
- delete keyData.alg;
449
- delete keyData.use;
450
- return crypto$1.subtle.importKey("jwk", keyData, ...rest);
451
- };
452
- const exportKeyValue = (k) => decode(k);
453
- let privCache;
454
- let pubCache;
455
- const isKeyObject = (key) => {
456
- return key?.[Symbol.toStringTag] === "KeyObject";
457
- };
458
- const importAndCache = async (cache, key, jwk, alg, freeze2 = false) => {
459
- let cached = cache.get(key);
460
- if (cached?.[alg]) {
461
- return cached[alg];
462
- }
463
- const cryptoKey = await parse({ ...jwk, alg });
464
- if (freeze2)
465
- Object.freeze(key);
466
- if (!cached) {
467
- cache.set(key, { [alg]: cryptoKey });
468
- } else {
469
- cached[alg] = cryptoKey;
470
- }
471
- return cryptoKey;
472
- };
473
- const normalizePublicKey = (key, alg) => {
474
- if (isKeyObject(key)) {
475
- let jwk = key.export({ format: "jwk" });
476
- delete jwk.d;
477
- delete jwk.dp;
478
- delete jwk.dq;
479
- delete jwk.p;
480
- delete jwk.q;
481
- delete jwk.qi;
482
- if (jwk.k) {
483
- return exportKeyValue(jwk.k);
484
- }
485
- pubCache || (pubCache = /* @__PURE__ */ new WeakMap());
486
- return importAndCache(pubCache, key, jwk, alg);
487
- }
488
- if (isJWK(key)) {
489
- if (key.k)
490
- return decode(key.k);
491
- pubCache || (pubCache = /* @__PURE__ */ new WeakMap());
492
- const cryptoKey = importAndCache(pubCache, key, key, alg, true);
493
- return cryptoKey;
494
- }
495
- return key;
496
- };
497
- const normalizePrivateKey = (key, alg) => {
498
- if (isKeyObject(key)) {
499
- let jwk = key.export({ format: "jwk" });
500
- if (jwk.k) {
501
- return exportKeyValue(jwk.k);
502
- }
503
- privCache || (privCache = /* @__PURE__ */ new WeakMap());
504
- return importAndCache(privCache, key, jwk, alg);
505
- }
506
- if (isJWK(key)) {
507
- if (key.k)
508
- return decode(key.k);
509
- privCache || (privCache = /* @__PURE__ */ new WeakMap());
510
- const cryptoKey = importAndCache(privCache, key, key, alg, true);
511
- return cryptoKey;
512
- }
513
- return key;
514
- };
515
- const normalize = { normalizePublicKey, normalizePrivateKey };
516
- const findOid = (keyData, oid, from = 0) => {
517
- if (from === 0) {
518
- oid.unshift(oid.length);
519
- oid.unshift(6);
520
- }
521
- const i = keyData.indexOf(oid[0], from);
522
- if (i === -1)
523
- return false;
524
- const sub = keyData.subarray(i, i + oid.length);
525
- if (sub.length !== oid.length)
526
- return false;
527
- return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);
528
- };
529
- const getNamedCurve = (keyData) => {
530
- switch (true) {
531
- case findOid(keyData, [42, 134, 72, 206, 61, 3, 1, 7]):
532
- return "P-256";
533
- case findOid(keyData, [43, 129, 4, 0, 34]):
534
- return "P-384";
535
- case findOid(keyData, [43, 129, 4, 0, 35]):
536
- return "P-521";
537
- case findOid(keyData, [43, 101, 110]):
538
- return "X25519";
539
- case findOid(keyData, [43, 101, 111]):
540
- return "X448";
541
- case findOid(keyData, [43, 101, 112]):
542
- return "Ed25519";
543
- case findOid(keyData, [43, 101, 113]):
544
- return "Ed448";
545
- default:
546
- throw new JOSENotSupported("Invalid or unsupported EC Key Curve or OKP Key Sub Type");
547
- }
548
- };
549
- const genericImport = async (replace, keyFormat, pem, alg, options) => {
550
- let algorithm;
551
- let keyUsages;
552
- const keyData = new Uint8Array(atob(pem.replace(replace, "")).split("").map((c) => c.charCodeAt(0)));
553
- switch (alg) {
554
- case "PS256":
555
- case "PS384":
556
- case "PS512":
557
- algorithm = { name: "RSA-PSS", hash: `SHA-${alg.slice(-3)}` };
558
- keyUsages = ["sign"];
559
- break;
560
- case "RS256":
561
- case "RS384":
562
- case "RS512":
563
- algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${alg.slice(-3)}` };
564
- keyUsages = ["sign"];
565
- break;
566
- case "RSA-OAEP":
567
- case "RSA-OAEP-256":
568
- case "RSA-OAEP-384":
569
- case "RSA-OAEP-512":
570
- algorithm = {
571
- name: "RSA-OAEP",
572
- hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`
573
- };
574
- keyUsages = ["decrypt", "unwrapKey"];
575
- break;
576
- case "ES256":
577
- algorithm = { name: "ECDSA", namedCurve: "P-256" };
578
- keyUsages = ["sign"];
579
- break;
580
- case "ES384":
581
- algorithm = { name: "ECDSA", namedCurve: "P-384" };
582
- keyUsages = ["sign"];
583
- break;
584
- case "ES512":
585
- algorithm = { name: "ECDSA", namedCurve: "P-521" };
586
- keyUsages = ["sign"];
587
- break;
588
- case "ECDH-ES":
589
- case "ECDH-ES+A128KW":
590
- case "ECDH-ES+A192KW":
591
- case "ECDH-ES+A256KW": {
592
- const namedCurve = getNamedCurve(keyData);
593
- algorithm = namedCurve.startsWith("P-") ? { name: "ECDH", namedCurve } : { name: namedCurve };
594
- keyUsages = ["deriveBits"];
595
- break;
596
- }
597
- case "Ed25519":
598
- algorithm = { name: "Ed25519" };
599
- keyUsages = ["sign"];
600
- break;
601
- case "EdDSA":
602
- algorithm = { name: getNamedCurve(keyData) };
603
- keyUsages = ["sign"];
604
- break;
605
- default:
606
- throw new JOSENotSupported('Invalid or unsupported "alg" (Algorithm) value');
607
- }
608
- return crypto$1.subtle.importKey(keyFormat, keyData, algorithm, false, keyUsages);
609
- };
610
- const fromPKCS8 = (pem, alg, options) => {
611
- return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g, "pkcs8", pem, alg);
612
- };
613
- async function importPKCS8(pkcs8, alg, options) {
614
- if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
615
- throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
616
- }
617
- return fromPKCS8(pkcs8, alg);
618
- }
619
- const tag = (key) => key?.[Symbol.toStringTag];
620
- const jwkMatchesOp = (alg, key, usage) => {
621
- if (key.use !== void 0 && key.use !== "sig") {
622
- throw new TypeError("Invalid key for this operation, when present its use must be sig");
623
- }
624
- if (key.key_ops !== void 0 && key.key_ops.includes?.(usage) !== true) {
625
- throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);
626
- }
627
- if (key.alg !== void 0 && key.alg !== alg) {
628
- throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);
629
- }
630
- return true;
631
- };
632
- const symmetricTypeCheck = (alg, key, usage, allowJwk) => {
633
- if (key instanceof Uint8Array)
634
- return;
635
- if (allowJwk && isJWK(key)) {
636
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
637
- return;
638
- throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
639
- }
640
- if (!isKeyLike(key)) {
641
- throw new TypeError(withAlg(alg, key, ...types, "Uint8Array", allowJwk ? "JSON Web Key" : null));
642
- }
643
- if (key.type !== "secret") {
644
- throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
645
- }
646
- };
647
- const asymmetricTypeCheck = (alg, key, usage, allowJwk) => {
648
- if (allowJwk && isJWK(key)) {
649
- switch (usage) {
650
- case "sign":
651
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
652
- return;
653
- throw new TypeError(`JSON Web Key for this operation be a private JWK`);
654
- case "verify":
655
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
656
- return;
657
- throw new TypeError(`JSON Web Key for this operation be a public JWK`);
658
- }
659
- }
660
- if (!isKeyLike(key)) {
661
- throw new TypeError(withAlg(alg, key, ...types, allowJwk ? "JSON Web Key" : null));
662
- }
663
- if (key.type === "secret") {
664
- throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
665
- }
666
- if (usage === "sign" && key.type === "public") {
667
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
668
- }
669
- if (usage === "decrypt" && key.type === "public") {
670
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
671
- }
672
- if (key.algorithm && usage === "verify" && key.type === "private") {
673
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
674
- }
675
- if (key.algorithm && usage === "encrypt" && key.type === "private") {
676
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
677
- }
678
- };
679
- function checkKeyType(allowJwk, alg, key, usage) {
680
- const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg);
681
- if (symmetric) {
682
- symmetricTypeCheck(alg, key, usage, allowJwk);
683
- } else {
684
- asymmetricTypeCheck(alg, key, usage, allowJwk);
685
- }
686
- }
687
- checkKeyType.bind(void 0, false);
688
- const checkKeyTypeWithJwk = checkKeyType.bind(void 0, true);
689
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
690
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
691
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
692
- }
693
- if (!protectedHeader || protectedHeader.crit === void 0) {
694
- return /* @__PURE__ */ new Set();
695
- }
696
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
697
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
698
- }
699
- let recognized;
700
- if (recognizedOption !== void 0) {
701
- recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
702
- } else {
703
- recognized = recognizedDefault;
704
- }
705
- for (const parameter of protectedHeader.crit) {
706
- if (!recognized.has(parameter)) {
707
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
708
- }
709
- if (joseHeader[parameter] === void 0) {
710
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
711
- }
712
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
713
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
714
- }
715
- }
716
- return new Set(protectedHeader.crit);
717
- }
718
- function subtleDsa(alg, algorithm) {
719
- const hash = `SHA-${alg.slice(-3)}`;
720
- switch (alg) {
721
- case "HS256":
722
- case "HS384":
723
- case "HS512":
724
- return { hash, name: "HMAC" };
725
- case "PS256":
726
- case "PS384":
727
- case "PS512":
728
- return { hash, name: "RSA-PSS", saltLength: alg.slice(-3) >> 3 };
729
- case "RS256":
730
- case "RS384":
731
- case "RS512":
732
- return { hash, name: "RSASSA-PKCS1-v1_5" };
733
- case "ES256":
734
- case "ES384":
735
- case "ES512":
736
- return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
737
- case "Ed25519":
738
- return { name: "Ed25519" };
739
- case "EdDSA":
740
- return { name: algorithm.name };
741
- default:
742
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
743
- }
744
- }
745
- async function getCryptoKey(alg, key, usage) {
746
- {
747
- key = await normalize.normalizePrivateKey(key, alg);
748
- }
749
- if (isCryptoKey(key)) {
750
- checkSigCryptoKey(key, alg, usage);
751
- return key;
752
- }
753
- if (key instanceof Uint8Array) {
754
- if (!alg.startsWith("HS")) {
755
- throw new TypeError(invalidKeyInput(key, ...types));
756
- }
757
- return crypto$1.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
758
- }
759
- throw new TypeError(invalidKeyInput(key, ...types, "Uint8Array", "JSON Web Key"));
760
- }
761
- const epoch = (date) => Math.floor(date.getTime() / 1e3);
762
- const minute = 60;
763
- const hour = minute * 60;
764
- const day = hour * 24;
765
- const week = day * 7;
766
- const year = day * 365.25;
767
- const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
768
- const secs = (str) => {
769
- const matched = REGEX.exec(str);
770
- if (!matched || matched[4] && matched[1]) {
771
- throw new TypeError("Invalid time period format");
772
- }
773
- const value = parseFloat(matched[2]);
774
- const unit = matched[3].toLowerCase();
775
- let numericDate;
776
- switch (unit) {
777
- case "sec":
778
- case "secs":
779
- case "second":
780
- case "seconds":
781
- case "s":
782
- numericDate = Math.round(value);
783
- break;
784
- case "minute":
785
- case "minutes":
786
- case "min":
787
- case "mins":
788
- case "m":
789
- numericDate = Math.round(value * minute);
790
- break;
791
- case "hour":
792
- case "hours":
793
- case "hr":
794
- case "hrs":
795
- case "h":
796
- numericDate = Math.round(value * hour);
797
- break;
798
- case "day":
799
- case "days":
800
- case "d":
801
- numericDate = Math.round(value * day);
802
- break;
803
- case "week":
804
- case "weeks":
805
- case "w":
806
- numericDate = Math.round(value * week);
807
- break;
808
- default:
809
- numericDate = Math.round(value * year);
810
- break;
811
- }
812
- if (matched[1] === "-" || matched[4] === "ago") {
813
- return -numericDate;
814
- }
815
- return numericDate;
816
- };
817
- const sign = async (alg, key, data) => {
818
- const cryptoKey = await getCryptoKey(alg, key, "sign");
819
- checkKeyLength(alg, cryptoKey);
820
- const signature = await crypto$1.subtle.sign(subtleDsa(alg, cryptoKey.algorithm), cryptoKey, data);
821
- return new Uint8Array(signature);
822
- };
823
- class FlattenedSign {
824
- constructor(payload) {
825
- if (!(payload instanceof Uint8Array)) {
826
- throw new TypeError("payload must be an instance of Uint8Array");
827
- }
828
- this._payload = payload;
829
- }
830
- setProtectedHeader(protectedHeader) {
831
- if (this._protectedHeader) {
832
- throw new TypeError("setProtectedHeader can only be called once");
833
- }
834
- this._protectedHeader = protectedHeader;
835
- return this;
836
- }
837
- setUnprotectedHeader(unprotectedHeader) {
838
- if (this._unprotectedHeader) {
839
- throw new TypeError("setUnprotectedHeader can only be called once");
840
- }
841
- this._unprotectedHeader = unprotectedHeader;
842
- return this;
843
- }
844
- async sign(key, options) {
845
- if (!this._protectedHeader && !this._unprotectedHeader) {
846
- throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
847
- }
848
- if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) {
849
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
850
- }
851
- const joseHeader = {
852
- ...this._protectedHeader,
853
- ...this._unprotectedHeader
4
+ const backendBaseUrl = config.backendBaseUrl || DEFAULT_BASE_URL$1;
5
+ const requestBody = {
6
+ dfProjectId: config.dfProjectId,
7
+ dfLocation: config.dfLocation || "us-central1",
8
+ dfAgentId: config.dfAgentId,
9
+ languageCode: config.languageCode || "en"
854
10
  };
855
- const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this._protectedHeader, joseHeader);
856
- let b64 = true;
857
- if (extensions.has("b64")) {
858
- b64 = this._protectedHeader.b64;
859
- if (typeof b64 !== "boolean") {
860
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
861
- }
862
- }
863
- const { alg } = joseHeader;
864
- if (typeof alg !== "string" || !alg) {
865
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
866
- }
867
- checkKeyTypeWithJwk(alg, key, "sign");
868
- let payload = this._payload;
869
- if (b64) {
870
- payload = encoder.encode(encode(payload));
871
- }
872
- let protectedHeader;
873
- if (this._protectedHeader) {
874
- protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader)));
875
- } else {
876
- protectedHeader = encoder.encode("");
877
- }
878
- const data = concat(protectedHeader, encoder.encode("."), payload);
879
- const signature = await sign(alg, key, data);
880
- const jws = {
881
- signature: encode(signature),
882
- payload: ""
883
- };
884
- if (b64) {
885
- jws.payload = decoder.decode(payload);
886
- }
887
- if (this._unprotectedHeader) {
888
- jws.header = this._unprotectedHeader;
889
- }
890
- if (this._protectedHeader) {
891
- jws.protected = decoder.decode(protectedHeader);
892
- }
893
- return jws;
894
- }
895
- }
896
- class CompactSign {
897
- constructor(payload) {
898
- this._flattened = new FlattenedSign(payload);
899
- }
900
- setProtectedHeader(protectedHeader) {
901
- this._flattened.setProtectedHeader(protectedHeader);
902
- return this;
903
- }
904
- async sign(key, options) {
905
- const jws = await this._flattened.sign(key, options);
906
- if (jws.payload === void 0) {
907
- throw new TypeError("use the flattened module for creating JWS with b64: false");
908
- }
909
- return `${jws.protected}.${jws.payload}.${jws.signature}`;
910
- }
911
- }
912
- function validateInput(label, input) {
913
- if (!Number.isFinite(input)) {
914
- throw new TypeError(`Invalid ${label} input`);
915
- }
916
- return input;
917
- }
918
- class ProduceJWT {
919
- constructor(payload = {}) {
920
- if (!isObject(payload)) {
921
- throw new TypeError("JWT Claims Set MUST be an object");
922
- }
923
- this._payload = payload;
924
- }
925
- setIssuer(issuer) {
926
- this._payload = { ...this._payload, iss: issuer };
927
- return this;
928
- }
929
- setSubject(subject) {
930
- this._payload = { ...this._payload, sub: subject };
931
- return this;
932
- }
933
- setAudience(audience) {
934
- this._payload = { ...this._payload, aud: audience };
935
- return this;
936
- }
937
- setJti(jwtId) {
938
- this._payload = { ...this._payload, jti: jwtId };
939
- return this;
940
- }
941
- setNotBefore(input) {
942
- if (typeof input === "number") {
943
- this._payload = { ...this._payload, nbf: validateInput("setNotBefore", input) };
944
- } else if (input instanceof Date) {
945
- this._payload = { ...this._payload, nbf: validateInput("setNotBefore", epoch(input)) };
946
- } else {
947
- this._payload = { ...this._payload, nbf: epoch(/* @__PURE__ */ new Date()) + secs(input) };
948
- }
949
- return this;
950
- }
951
- setExpirationTime(input) {
952
- if (typeof input === "number") {
953
- this._payload = { ...this._payload, exp: validateInput("setExpirationTime", input) };
954
- } else if (input instanceof Date) {
955
- this._payload = { ...this._payload, exp: validateInput("setExpirationTime", epoch(input)) };
956
- } else {
957
- this._payload = { ...this._payload, exp: epoch(/* @__PURE__ */ new Date()) + secs(input) };
958
- }
959
- return this;
960
- }
961
- setIssuedAt(input) {
962
- if (typeof input === "undefined") {
963
- this._payload = { ...this._payload, iat: epoch(/* @__PURE__ */ new Date()) };
964
- } else if (input instanceof Date) {
965
- this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch(input)) };
966
- } else if (typeof input === "string") {
967
- this._payload = {
968
- ...this._payload,
969
- iat: validateInput("setIssuedAt", epoch(/* @__PURE__ */ new Date()) + secs(input))
970
- };
971
- } else {
972
- this._payload = { ...this._payload, iat: validateInput("setIssuedAt", input) };
973
- }
974
- return this;
975
- }
976
- }
977
- class SignJWT extends ProduceJWT {
978
- setProtectedHeader(protectedHeader) {
979
- this._protectedHeader = protectedHeader;
980
- return this;
981
- }
982
- async sign(key, options) {
983
- const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));
984
- sig.setProtectedHeader(this._protectedHeader);
985
- if (Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) {
986
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
987
- }
988
- return sig.sign(key, options);
989
- }
990
- }
991
- async function getAccessTokenFromServiceAccount(serviceAccountKey) {
992
- const now = Math.floor(Date.now() / 1e3);
993
- let privateKeyPem = serviceAccountKey.private_key;
994
- if (privateKeyPem) {
995
- privateKeyPem = privateKeyPem.trim();
996
- if (!privateKeyPem.includes("-----BEGIN")) {
997
- const keyContent = privateKeyPem.replace(/\s/g, "");
998
- const formattedKey = keyContent.match(/.{1,64}/g)?.join("\n") || keyContent;
999
- privateKeyPem = `-----BEGIN PRIVATE KEY-----
1000
- ${formattedKey}
1001
- -----END PRIVATE KEY-----`;
1002
- } else {
1003
- privateKeyPem = privateKeyPem.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
1004
- if (privateKeyPem.includes("BEGIN RSA PRIVATE KEY")) {
1005
- throw new Error(
1006
- "Private key is in PKCS#1 format (RSA PRIVATE KEY). Please download a new service account key from Google Cloud Console. The key should be in PKCS#8 format (PRIVATE KEY)."
1007
- );
1008
- }
1009
- const keyMatch = privateKeyPem.match(/-----BEGIN PRIVATE KEY-----\n?([\s\S]*?)\n?-----END PRIVATE KEY-----/);
1010
- if (keyMatch) {
1011
- const keyContent = keyMatch[1].replace(/\s/g, "");
1012
- if (!keyContent.includes("\n") || keyContent.length > 64) {
1013
- const formattedKey = keyContent.match(/.{1,64}/g)?.join("\n") || keyContent;
1014
- privateKeyPem = `-----BEGIN PRIVATE KEY-----
1015
- ${formattedKey}
1016
- -----END PRIVATE KEY-----`;
1017
- }
1018
- }
1019
- }
1020
- } else {
1021
- throw new Error("Private key is missing from service account key");
1022
- }
1023
- try {
1024
- const privateKey = await importPKCS8(privateKeyPem, "RS256");
1025
- const jwt = await new SignJWT({
1026
- scope: "https://www.googleapis.com/auth/cloud-platform"
1027
- }).setProtectedHeader({ alg: "RS256" }).setIssuedAt(now).setExpirationTime(now + 3600).setIssuer(serviceAccountKey.client_email).setSubject(serviceAccountKey.client_email).setAudience("https://oauth2.googleapis.com/token").sign(privateKey);
1028
- const response = await fetch("https://oauth2.googleapis.com/token", {
1029
- method: "POST",
1030
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
1031
- body: new URLSearchParams({
1032
- grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
1033
- assertion: jwt
1034
- })
1035
- });
1036
- if (!response.ok) {
1037
- const error = await response.json();
1038
- throw new Error(error.error_description || "Failed to get access token");
1039
- }
1040
- const data = await response.json();
1041
- return data.access_token;
1042
- } catch (error) {
1043
- if (error.message && error.message.includes("pkcs8")) {
1044
- throw new Error(
1045
- "Invalid private key format. The service account key must be in PKCS#8 format. Please ensure your service account key JSON file has a properly formatted private_key field. If you downloaded the key from Google Cloud Console, it should already be in the correct format."
1046
- );
1047
- }
1048
- throw error;
1049
- }
1050
- }
1051
- async function getAccessToken(config) {
1052
- if (config.accessToken) {
1053
- return config.accessToken;
1054
- }
1055
- if (!config.serviceAccountKey) {
1056
- throw new Error("Either serviceAccountKey or accessToken must be provided");
1057
- }
1058
- return await getAccessTokenFromServiceAccount(config.serviceAccountKey);
1059
- }
1060
- function createSessionPath(projectId, location, agentId, sessionId) {
1061
- return `projects/${projectId}/locations/${location}/agents/${agentId}/sessions/${sessionId}`;
1062
- }
1063
- function extractRichContent(responseMessages) {
1064
- let richContent = null;
1065
- for (const msg of responseMessages) {
1066
- if (msg.payload) {
1067
- if (msg.payload.richContent) {
1068
- richContent = msg.payload.richContent;
1069
- break;
1070
- }
1071
- if (msg.payload.fields && msg.payload.fields.richContent) {
1072
- const richContentValue = msg.payload.fields.richContent;
1073
- if (richContentValue.listValue && richContentValue.listValue.values) {
1074
- richContent = richContentValue.listValue.values.map((v) => {
1075
- if (v.listValue && v.listValue.values) {
1076
- return v.listValue.values.map((item) => {
1077
- if (item.structValue && item.structValue.fields) {
1078
- const fields = item.structValue.fields;
1079
- if (fields.type && fields.options) {
1080
- return {
1081
- type: fields.type.stringValue || fields.type,
1082
- options: fields.options.listValue ? fields.options.listValue.values.map((opt) => ({
1083
- text: opt.structValue?.fields?.text?.stringValue || "",
1084
- payload: opt.structValue?.fields?.payload?.stringValue || ""
1085
- })) : []
1086
- };
1087
- }
1088
- }
1089
- return item;
1090
- });
1091
- }
1092
- return v;
1093
- });
1094
- } else if (typeof richContentValue === "object" && !richContentValue.listValue) {
1095
- richContent = richContentValue;
1096
- }
1097
- break;
1098
- }
11
+ if (existingSessionId) {
12
+ requestBody.sessionId = existingSessionId;
1099
13
  }
1100
- }
1101
- return richContent;
1102
- }
1103
- async function createDialogflowSession(config) {
1104
- try {
1105
- const accessToken = await getAccessToken(config);
1106
- const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1107
- const location = config.dfLocation.split(" ")[0].trim();
1108
- const sessionPath = createSessionPath(
1109
- config.dfProjectId,
1110
- location,
1111
- config.dfAgentId,
1112
- sessionId
1113
- );
1114
- const apiEndpoint = `https://${location}-dialogflow.googleapis.com/v3/${sessionPath}:detectIntent`;
1115
- const request = {
1116
- queryInput: {
1117
- text: {
1118
- text: "hello"
1119
- },
1120
- languageCode: config.languageCode || "en"
1121
- }
1122
- };
1123
- const response = await fetch(apiEndpoint, {
14
+ const response = await fetch(`${backendBaseUrl}/api/dialogflow/session/create`, {
1124
15
  method: "POST",
1125
16
  headers: {
1126
- "Authorization": `Bearer ${accessToken}`,
1127
17
  "Content-Type": "application/json"
18
+ // Don't send X-Session-ID header for Dialogflow-only operations
1128
19
  },
1129
- body: JSON.stringify(request)
20
+ body: JSON.stringify(requestBody)
1130
21
  });
1131
22
  if (!response.ok) {
1132
- const error = await response.json().catch(() => ({}));
1133
- throw new Error(error.error?.message || `HTTP error! status: ${response.status}`);
23
+ const contentType2 = response.headers.get("content-type");
24
+ let error = {};
25
+ if (contentType2 && contentType2.includes("application/json")) {
26
+ try {
27
+ error = await response.json();
28
+ } catch {
29
+ error = {};
30
+ }
31
+ } else {
32
+ const text2 = await response.text();
33
+ throw new Error(
34
+ `API endpoint returned HTML instead of JSON. Status: ${response.status}. Response preview: ${text2.substring(0, 200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${backendBaseUrl}/api/dialogflow/session/create`
35
+ );
36
+ }
37
+ if (response.status === 400) {
38
+ throw new Error(error.message || "Bad request. Please check your Dialogflow configuration.");
39
+ } else if (response.status === 401) {
40
+ throw new Error(error.message || "Authentication failed. Please check your backend configuration.");
41
+ } else if (response.status === 403) {
42
+ throw new Error(error.message || "Access forbidden. Please check your permissions.");
43
+ } else if (response.status === 404) {
44
+ throw new Error(error.message || "Dialogflow agent not found. Please check your project ID, location, and agent ID.");
45
+ } else if (response.status === 500) {
46
+ throw new Error(error.message || "Internal server error. Please try again later.");
47
+ }
48
+ throw new Error(error.message || `HTTP error! status: ${response.status}`);
49
+ }
50
+ const contentType = response.headers.get("content-type");
51
+ if (!contentType || !contentType.includes("application/json")) {
52
+ const clonedResponse = response.clone();
53
+ const text2 = await clonedResponse.text();
54
+ throw new Error(
55
+ `API endpoint returned non-JSON response. Status: ${response.status}. Content-Type: ${contentType || "unknown"}. Response body: ${text2.substring(0, 200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${backendBaseUrl}/api/dialogflow/session/create`
56
+ );
1134
57
  }
1135
58
  const data = await response.json();
1136
- let welcomeMessage = "Hello! I'm BlockSpark AI Assistant. How can I help you today?";
1137
- let richContent = null;
1138
- if (data.queryResult?.responseMessages) {
1139
- const textMessages = data.queryResult.responseMessages.filter((msg) => msg.text).map((msg) => msg.text.text.join(" "));
1140
- if (textMessages.length > 0) {
1141
- welcomeMessage = textMessages.join(" ");
1142
- }
1143
- richContent = extractRichContent(data.queryResult.responseMessages);
1144
- } else if (data.queryResult?.fulfillmentText) {
1145
- welcomeMessage = data.queryResult.fulfillmentText;
59
+ if (data.status !== "success") {
60
+ throw new Error(data.message || "Failed to create session. Backend returned unsuccessful status.");
1146
61
  }
62
+ const responseData = data.data || data;
1147
63
  return {
1148
- session_id: sessionId,
1149
- message: welcomeMessage,
1150
- ...richContent && { richContent }
64
+ session_id: responseData.session_id || data.session_id,
65
+ message: responseData.message || "Hello! How can I help you today?",
66
+ ...responseData.richContent && { richContent: responseData.richContent }
1151
67
  };
1152
68
  } catch (error) {
1153
69
  console.error("Error creating Dialogflow session:", error);
1154
- const errorMessage = error.message || "Failed to create session";
1155
- if (errorMessage.includes("401") || errorMessage.includes("Unauthorized")) {
1156
- throw new Error("Authentication failed. Please check your service account key or access token.");
1157
- } else if (errorMessage.includes("403") || errorMessage.includes("Forbidden")) {
1158
- throw new Error("Access forbidden. Please check your Dialogflow API permissions.");
1159
- } else if (errorMessage.includes("404") || errorMessage.includes("Not Found")) {
1160
- throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");
1161
- }
1162
- throw new Error(errorMessage);
70
+ if (error.message?.includes("Failed to fetch") || error.message?.includes("CORS")) {
71
+ throw new Error("Network error. Unable to connect to backend. Please check your network connection and CORS settings.");
72
+ }
73
+ if (error.message && !error.message.includes("HTTP error")) {
74
+ throw error;
75
+ }
76
+ throw new Error(error.message || "Failed to create Dialogflow session");
1163
77
  }
1164
78
  }
1165
- async function sendDialogflowMessage(message2, sessionId, config) {
79
+ async function sendDialogflowMessage(message, sessionId, config) {
1166
80
  try {
1167
- const accessToken = await getAccessToken(config);
1168
- const location = config.dfLocation.split(" ")[0].trim();
1169
- const sessionPath = createSessionPath(
1170
- config.dfProjectId,
1171
- location,
1172
- config.dfAgentId,
1173
- sessionId
1174
- );
1175
- const apiEndpoint = `https://${location}-dialogflow.googleapis.com/v3/${sessionPath}:detectIntent`;
1176
- const request = {
1177
- queryInput: {
1178
- text: {
1179
- text: message2.trim()
81
+ const backendBaseUrl = config.backendBaseUrl || DEFAULT_BASE_URL$1;
82
+ const requestBody = {
83
+ message: message.trim(),
84
+ dfProjectId: config.dfProjectId,
85
+ dfLocation: config.dfLocation || "us-central1",
86
+ dfAgentId: config.dfAgentId,
87
+ languageCode: config.languageCode || "en"
88
+ };
89
+ const response = await fetch(
90
+ `${backendBaseUrl}/api/dialogflow/session/${encodeURIComponent(sessionId)}/message`,
91
+ {
92
+ method: "POST",
93
+ headers: {
94
+ "Content-Type": "application/json"
95
+ // Don't send X-Session-ID header for Dialogflow-only operations
1180
96
  },
1181
- languageCode: config.languageCode || "en"
97
+ body: JSON.stringify(requestBody)
1182
98
  }
1183
- };
1184
- const response = await fetch(apiEndpoint, {
1185
- method: "POST",
1186
- headers: {
1187
- "Authorization": `Bearer ${accessToken}`,
1188
- "Content-Type": "application/json"
1189
- },
1190
- body: JSON.stringify(request)
1191
- });
99
+ );
1192
100
  if (!response.ok) {
1193
- const errorText = await response.text();
1194
- let errorData = {};
1195
- try {
1196
- errorData = JSON.parse(errorText);
1197
- } catch {
1198
- errorData = { message: errorText || `HTTP ${response.status}` };
1199
- }
1200
- const errorMessage = errorData.error?.message || errorData.message || `HTTP error! status: ${response.status}`;
1201
- console.error("Dialogflow API Error (sendMessage):", {
1202
- status: response.status,
1203
- statusText: response.statusText,
1204
- error: errorData,
1205
- endpoint: apiEndpoint
1206
- });
1207
- throw new Error(errorMessage);
1208
- }
1209
- const data = await response.json();
1210
- let responseText = "I'm sorry, I didn't understand that. Could you please rephrase?";
1211
- let richContent = null;
1212
- let handoff = false;
1213
- if (data.queryResult?.parameters?.fields?.handoff?.boolValue === true) {
1214
- handoff = true;
1215
- } else if (data.queryResult?.responseMessages) {
1216
- for (const msg of data.queryResult.responseMessages) {
1217
- if (msg.payload) {
1218
- if (typeof msg.payload === "object") {
1219
- if (msg.payload.handoff === true) {
1220
- handoff = true;
1221
- break;
1222
- }
1223
- if (msg.payload.fields?.handoff?.boolValue === true) {
1224
- handoff = true;
1225
- break;
1226
- }
1227
- }
101
+ const contentType2 = response.headers.get("content-type");
102
+ let error = {};
103
+ if (contentType2 && contentType2.includes("application/json")) {
104
+ try {
105
+ error = await response.json();
106
+ } catch {
107
+ error = {};
1228
108
  }
109
+ } else {
110
+ const text2 = await response.text();
111
+ throw new Error(
112
+ `API endpoint returned HTML instead of JSON. Status: ${response.status}. Response preview: ${text2.substring(0, 200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${backendBaseUrl}/api/dialogflow/session/${encodeURIComponent(sessionId)}/message`
113
+ );
1229
114
  }
115
+ if (response.status === 400) {
116
+ throw new Error(error.message || "Bad request. Please check your message and configuration.");
117
+ } else if (response.status === 401) {
118
+ throw new Error(error.message || "Authentication failed. Please check your backend configuration.");
119
+ } else if (response.status === 403) {
120
+ throw new Error(error.message || "Access forbidden. Please check your permissions.");
121
+ } else if (response.status === 404) {
122
+ throw new Error(error.message || "Dialogflow session not found. Please check your session ID.");
123
+ } else if (response.status === 500) {
124
+ throw new Error(error.message || "Internal server error. Please try again later.");
125
+ }
126
+ throw new Error(error.message || `HTTP error! status: ${response.status}`);
127
+ }
128
+ const contentType = response.headers.get("content-type");
129
+ if (!contentType || !contentType.includes("application/json")) {
130
+ const clonedResponse = response.clone();
131
+ const text2 = await clonedResponse.text();
132
+ throw new Error(
133
+ `API endpoint returned non-JSON response. Status: ${response.status}. Content-Type: ${contentType || "unknown"}. Response body: ${text2.substring(0, 200)}. This usually means the endpoint doesn't exist or the server is misconfigured. URL: ${backendBaseUrl}/api/dialogflow/session/${encodeURIComponent(sessionId)}/message`
134
+ );
1230
135
  }
1231
- if (data.handoff === true) {
1232
- handoff = true;
1233
- }
1234
- if (data.queryResult?.responseMessages) {
1235
- const textMessages = data.queryResult.responseMessages.filter((msg) => msg.text).map((msg) => msg.text.text.join(" "));
1236
- if (textMessages.length > 0) {
1237
- responseText = textMessages.join(" ");
1238
- }
1239
- richContent = extractRichContent(data.queryResult.responseMessages);
1240
- } else if (data.queryResult?.fulfillmentText) {
1241
- responseText = data.queryResult.fulfillmentText;
136
+ const data = await response.json();
137
+ if (data.status !== "success") {
138
+ throw new Error(data.message || "Failed to send message. Backend returned unsuccessful status.");
1242
139
  }
140
+ const responseData = data.data || data;
1243
141
  return {
1244
- response: responseText,
1245
- session_id: sessionId,
1246
- source: "dialogflow",
1247
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1248
- ...richContent && { richContent },
1249
- ...handoff && { handoff: true }
142
+ response: responseData.response || responseData.message || "I'm sorry, I didn't understand that. Could you please rephrase?",
143
+ session_id: responseData.session_id || data.session_id || sessionId,
144
+ source: responseData.source || "dialogflow",
145
+ timestamp: responseData.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
146
+ ...responseData.richContent && { richContent: responseData.richContent },
147
+ ...responseData.handoff !== void 0 && { handoff: responseData.handoff }
1250
148
  };
1251
149
  } catch (error) {
1252
150
  console.error("Error sending message to Dialogflow:", error);
1253
- const errorMessage = error.message || "Failed to send message";
1254
- if (errorMessage.includes("401") || errorMessage.includes("Unauthorized")) {
1255
- throw new Error("Authentication failed. Please check your service account key or access token.");
1256
- } else if (errorMessage.includes("403") || errorMessage.includes("Forbidden")) {
1257
- throw new Error("Access forbidden. Please check your Dialogflow API permissions.");
1258
- } else if (errorMessage.includes("404") || errorMessage.includes("Not Found")) {
1259
- throw new Error("Dialogflow agent not found. Please check your project ID, location, and agent ID.");
1260
- } else if (errorMessage.includes("CORS")) {
1261
- throw new Error("CORS error. Dialogflow API may not allow browser requests. Consider using a backend proxy.");
1262
- }
1263
- throw new Error(errorMessage);
151
+ if (error.message?.includes("Failed to fetch") || error.message?.includes("CORS")) {
152
+ throw new Error("Network error. Unable to connect to backend. Please check your network connection and CORS settings.");
153
+ }
154
+ if (error.message && !error.message.includes("HTTP error")) {
155
+ throw error;
156
+ }
157
+ throw new Error(error.message || "Failed to send message to Dialogflow");
1264
158
  }
1265
159
  }
1266
160
  const SESSION_KEY = "chat_session_id";
@@ -1308,8 +202,8 @@ function getSessionManager() {
1308
202
  return sessionManagerInstance;
1309
203
  }
1310
204
  class ChatResolvedError extends Error {
1311
- constructor(message2 = "chat_resolved") {
1312
- super(message2);
205
+ constructor(message = "chat_resolved") {
206
+ super(message);
1313
207
  this.reason = "chat_resolved";
1314
208
  this.name = "ChatResolvedError";
1315
209
  }
@@ -1505,7 +399,7 @@ class ChatService {
1505
399
  /**
1506
400
  * Send message to agent via REST API
1507
401
  */
1508
- async sendMessageToAgent(chatId, sessionId, message2) {
402
+ async sendMessageToAgent(chatId, sessionId, message) {
1509
403
  try {
1510
404
  const headers = {
1511
405
  "Content-Type": "application/json",
@@ -1520,7 +414,7 @@ class ChatService {
1520
414
  method: "POST",
1521
415
  headers,
1522
416
  body: JSON.stringify({
1523
- content: message2
417
+ content: message
1524
418
  })
1525
419
  }
1526
420
  );
@@ -1575,7 +469,7 @@ class ChatService {
1575
469
  return {
1576
470
  id: data.id,
1577
471
  sender_type: "customer",
1578
- content: message2,
472
+ content: message,
1579
473
  timestamp: data.timestamp || (/* @__PURE__ */ new Date()).toISOString()
1580
474
  };
1581
475
  } catch (error) {
@@ -1717,35 +611,35 @@ class ChatService {
1717
611
  };
1718
612
  this.ws.onmessage = (event) => {
1719
613
  try {
1720
- const message2 = JSON.parse(event.data);
614
+ const message = JSON.parse(event.data);
1721
615
  if (this.debug) {
1722
616
  console.log("WebSocket raw message received:", event.data);
1723
- console.log("WebSocket parsed message:", message2);
617
+ console.log("WebSocket parsed message:", message);
1724
618
  }
1725
- if (message2.session_id) {
1726
- this.sessionManager.updateSessionFromResponse({ session_id: message2.session_id });
619
+ if (message.session_id) {
620
+ this.sessionManager.updateSessionFromResponse({ session_id: message.session_id });
1727
621
  }
1728
- if (message2.type === "agent_accepted" || message2.type === "chat_resolved" || message2.type === "chat_ended") {
622
+ if (message.type === "agent_accepted" || message.type === "chat_resolved" || message.type === "chat_ended") {
1729
623
  console.log("🔔 Received notification message:", {
1730
- type: message2.type,
1731
- chat_id: message2.chat_id,
1732
- timestamp: message2.timestamp,
1733
- to_agent: message2.to_agent,
1734
- to_agent_id: message2.to_agent_id
624
+ type: message.type,
625
+ chat_id: message.chat_id,
626
+ timestamp: message.timestamp,
627
+ to_agent: message.to_agent,
628
+ to_agent_id: message.to_agent_id
1735
629
  });
1736
630
  }
1737
- if (message2.type === "pong") {
631
+ if (message.type === "pong") {
1738
632
  return;
1739
633
  }
1740
- if (this.debug && message2.type === "message") {
634
+ if (this.debug && message.type === "message") {
1741
635
  console.log("Processing message type:", {
1742
- type: message2.type,
1743
- sender_type: message2.sender_type,
1744
- content: message2.content?.substring(0, 50) + "...",
1745
- id: message2.id
636
+ type: message.type,
637
+ sender_type: message.sender_type,
638
+ content: message.content?.substring(0, 50) + "...",
639
+ id: message.id
1746
640
  });
1747
641
  }
1748
- this.messageHandlers.forEach((handler) => handler(message2));
642
+ this.messageHandlers.forEach((handler) => handler(message));
1749
643
  } catch (error) {
1750
644
  console.error("Error parsing WebSocket message:", error);
1751
645
  if (this.debug) {
@@ -1795,7 +689,7 @@ class ChatService {
1795
689
  /**
1796
690
  * Send message via WebSocket
1797
691
  */
1798
- sendMessageViaWebSocket(message2) {
692
+ sendMessageViaWebSocket(message) {
1799
693
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1800
694
  return false;
1801
695
  }
@@ -1803,7 +697,7 @@ class ChatService {
1803
697
  this.ws.send(
1804
698
  JSON.stringify({
1805
699
  type: "message",
1806
- content: message2
700
+ content: message
1807
701
  })
1808
702
  );
1809
703
  return true;
@@ -2875,11 +1769,11 @@ function createDOMPurify() {
2875
1769
  CONFIG = null;
2876
1770
  SET_CONFIG = false;
2877
1771
  };
2878
- DOMPurify.isValidAttribute = function(tag2, attr, value) {
1772
+ DOMPurify.isValidAttribute = function(tag, attr, value) {
2879
1773
  if (!CONFIG) {
2880
1774
  _parseConfig({});
2881
1775
  }
2882
- const lcTag = transformCaseFunc(tag2);
1776
+ const lcTag = transformCaseFunc(tag);
2883
1777
  const lcName = transformCaseFunc(attr);
2884
1778
  return _isValidAttribute(lcTag, lcName, value);
2885
1779
  };
@@ -2945,4 +1839,4 @@ export {
2945
1839
  linkifyText as l,
2946
1840
  sendDialogflowMessage as s
2947
1841
  };
2948
- //# sourceMappingURL=sanitize-O18C3eqP.js.map
1842
+ //# sourceMappingURL=sanitize-Cm1kskSD.js.map