@kognitivedev/cloud-web-search 0.2.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js ADDED
@@ -0,0 +1,516 @@
1
+ "use strict";
2
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
3
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4
+ var m = o[Symbol.asyncIterator], i;
5
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
6
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
7
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
8
+ };
9
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
10
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
11
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
12
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
13
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
14
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
15
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
16
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
17
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
18
+ function fulfill(value) { resume("next", value); }
19
+ function reject(value) { resume("throw", value); }
20
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.KognitiveCloudWebSearchClient = void 0;
24
+ exports.readCloudWebSearchEventStream = readCloudWebSearchEventStream;
25
+ const client_core_1 = require("@kognitivedev/client-core");
26
+ const errors_1 = require("./errors");
27
+ const rich_events_1 = require("./rich-events");
28
+ const sse_1 = require("./sse");
29
+ const validation_1 = require("./validation");
30
+ const TERMINAL_STATUSES = new Set(["completed", "error", "cancelled"]);
31
+ const NON_PROGRESS_EVENT_TYPES = new Set([
32
+ "job.completed",
33
+ "job.failed",
34
+ "job.error",
35
+ "job.cancelled",
36
+ "websearch.research.answer.delta",
37
+ "websearch.research.reasoning",
38
+ "websearch.research.status",
39
+ "websearch.research.todo.generated",
40
+ "websearch.research.answer.completed",
41
+ ]);
42
+ function isTransportLike(value) {
43
+ return Boolean(value
44
+ && typeof value === "object"
45
+ && "baseUrl" in value
46
+ && "json" in value
47
+ && "raw" in value
48
+ && "poll" in value);
49
+ }
50
+ function stableStringify(value) {
51
+ if (Array.isArray(value)) {
52
+ return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
53
+ }
54
+ if (value instanceof Date) {
55
+ return JSON.stringify(value.toISOString());
56
+ }
57
+ if ((0, validation_1.isPlainObject)(value)) {
58
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
59
+ }
60
+ return JSON.stringify(value);
61
+ }
62
+ function toProgressFingerprint(progress) {
63
+ return stableStringify({
64
+ stage: progress.stage,
65
+ message: progress.message,
66
+ timestamp: progress.timestamp,
67
+ });
68
+ }
69
+ function rememberProgress(seenProgress, progress, eventId) {
70
+ const progressKey = `progress:${toProgressFingerprint(progress)}`;
71
+ const eventKey = eventId ? `event:${eventId}` : null;
72
+ const duplicate = seenProgress.has(progressKey) || (eventKey ? seenProgress.has(eventKey) : false);
73
+ seenProgress.add(progressKey);
74
+ if (eventKey) {
75
+ seenProgress.add(eventKey);
76
+ }
77
+ return !duplicate;
78
+ }
79
+ function normalizeTimestamp(value) {
80
+ return typeof value === "string" ? value : value.toISOString();
81
+ }
82
+ function deriveStatusFromRecord(record, fallback) {
83
+ if ((0, validation_1.isJobStatus)(record.status)) {
84
+ return record.status;
85
+ }
86
+ switch (record.eventType) {
87
+ case "job.created":
88
+ return "queued";
89
+ case "job.started":
90
+ return "in_progress";
91
+ case "job.completed":
92
+ return "completed";
93
+ case "job.failed":
94
+ case "job.error":
95
+ return "error";
96
+ case "job.cancelled":
97
+ return "cancelled";
98
+ default:
99
+ return fallback !== null && fallback !== void 0 ? fallback : "in_progress";
100
+ }
101
+ }
102
+ function toProgressEntry(record) {
103
+ if (typeof record.stage !== "string" || typeof record.message !== "string") {
104
+ return null;
105
+ }
106
+ const payload = (0, validation_1.isPlainObject)(record.payload) ? (0, validation_1.cloneUnknown)(record.payload) : undefined;
107
+ return Object.assign({ stage: record.stage, message: record.message, timestamp: normalizeTimestamp(record.createdAt) }, (payload ? { metadata: payload } : {}));
108
+ }
109
+ function shouldEmitProgress(record) {
110
+ if (typeof record.stage !== "string" || typeof record.message !== "string") {
111
+ return false;
112
+ }
113
+ if (NON_PROGRESS_EVENT_TYPES.has(record.eventType)) {
114
+ return false;
115
+ }
116
+ if (record.eventType.startsWith("websearch.workflow.")) {
117
+ return false;
118
+ }
119
+ return true;
120
+ }
121
+ function assertJobId(jobId, path = "jobId") {
122
+ const value = jobId.trim();
123
+ if (!value) {
124
+ throw new errors_1.CloudWebSearchValidationError(path, "non-empty string", jobId);
125
+ }
126
+ return value;
127
+ }
128
+ function rememberObservedJobId(observedJobId, nextJobId, path) {
129
+ if (observedJobId && observedJobId !== nextJobId) {
130
+ throw new errors_1.CloudWebSearchValidationError(path, `jobId "${observedJobId}"`, nextJobId);
131
+ }
132
+ return nextJobId;
133
+ }
134
+ function extractResultFromPayload(payload, options, path = "event.payload") {
135
+ if (payload === undefined || payload === null) {
136
+ return null;
137
+ }
138
+ if ((0, validation_1.isPlainObject)(payload) && "result" in payload) {
139
+ return payload.result === null
140
+ ? null
141
+ : (0, validation_1.decodeCloudWebSearchResult)(payload.result, options, `${path}.result`);
142
+ }
143
+ return (0, validation_1.decodeCloudWebSearchResult)(payload, options, path);
144
+ }
145
+ function extractErrorMessage(payload, fallback) {
146
+ if ((0, validation_1.isPlainObject)(payload) && typeof payload.errorMessage === "string" && payload.errorMessage.trim()) {
147
+ return payload.errorMessage;
148
+ }
149
+ if ((0, validation_1.isPlainObject)(payload) && typeof payload.reason === "string" && payload.reason.trim()) {
150
+ return payload.reason;
151
+ }
152
+ return fallback;
153
+ }
154
+ function applyLifecycleUpdate(job, record, options) {
155
+ var _a;
156
+ if (!job) {
157
+ return;
158
+ }
159
+ job.updatedAt = normalizeTimestamp(record.createdAt);
160
+ switch (record.eventType) {
161
+ case "job.created":
162
+ job.status = "queued";
163
+ break;
164
+ case "job.started":
165
+ job.status = "in_progress";
166
+ break;
167
+ case "job.completed":
168
+ job.status = "completed";
169
+ job.results = extractResultFromPayload(record.payload, options, `stream.${record.eventType}.payload`);
170
+ job.errorMessage = null;
171
+ break;
172
+ case "job.failed":
173
+ case "job.error":
174
+ job.status = "error";
175
+ job.errorMessage = extractErrorMessage(record.payload, (_a = record.message) !== null && _a !== void 0 ? _a : "Web search job failed");
176
+ break;
177
+ case "job.cancelled":
178
+ job.status = "cancelled";
179
+ job.errorMessage = "Job cancelled";
180
+ break;
181
+ default:
182
+ break;
183
+ }
184
+ }
185
+ function createSearchJobInput(input, parameters) {
186
+ if (typeof input === "string") {
187
+ return Object.assign({ mode: "search", query: input }, (parameters ? { parameters } : {}));
188
+ }
189
+ return Object.assign({ mode: "search", query: input.query }, (input.parameters ? { parameters: input.parameters } : {}));
190
+ }
191
+ function createResearchJobInput(input, options) {
192
+ if (typeof input === "string") {
193
+ return Object.assign(Object.assign(Object.assign({ mode: "research", instructions: input }, ((options === null || options === void 0 ? void 0 : options.responseInstructions) ? { responseInstructions: options.responseInstructions } : {})), ((options === null || options === void 0 ? void 0 : options.responseSchema) ? { responseSchema: options.responseSchema } : {})), ((options === null || options === void 0 ? void 0 : options.parameters) ? { parameters: options.parameters } : {}));
194
+ }
195
+ return Object.assign(Object.assign(Object.assign({ mode: "research", instructions: input.instructions }, (input.responseInstructions ? { responseInstructions: input.responseInstructions } : {})), (input.responseSchema ? { responseSchema: input.responseSchema } : {})), (input.parameters ? { parameters: input.parameters } : {}));
196
+ }
197
+ function readCloudWebSearchEventStream(stream, options) {
198
+ return __asyncGenerator(this, arguments, function* readCloudWebSearchEventStream_1() {
199
+ var _a, e_1, _b, _c;
200
+ var _d, _e, _f;
201
+ let currentJob = null;
202
+ let observedJobId = null;
203
+ const seenProgress = new Set();
204
+ try {
205
+ for (var _g = true, _h = __asyncValues((0, sse_1.readSSEStream)(stream)), _j; _j = yield __await(_h.next()), _a = _j.done, !_a; _g = true) {
206
+ _c = _j.value;
207
+ _g = false;
208
+ const frame = _c;
209
+ let lifecycleDecodeError = null;
210
+ if (frame.event === "job.snapshot") {
211
+ const payload = (0, validation_1.decodeJobSnapshotPayload)(frame.data, options, "stream.job.snapshot");
212
+ observedJobId = rememberObservedJobId(observedJobId, payload.job.id, "stream.job.snapshot.job.id");
213
+ currentJob = (0, validation_1.cloneUnknown)(payload.job);
214
+ yield yield __await({
215
+ type: "snapshot",
216
+ job: (0, validation_1.cloneUnknown)(currentJob),
217
+ });
218
+ for (const progress of currentJob.progress) {
219
+ if (!rememberProgress(seenProgress, progress)) {
220
+ continue;
221
+ }
222
+ yield yield __await({
223
+ type: "progress",
224
+ jobId: currentJob.id,
225
+ job: (0, validation_1.cloneUnknown)(currentJob),
226
+ status: currentJob.status,
227
+ progress: (0, validation_1.cloneUnknown)(progress),
228
+ replay: true,
229
+ });
230
+ }
231
+ continue;
232
+ }
233
+ if (frame.event === "job.keepalive") {
234
+ const payload = (0, validation_1.decodeKeepalivePayload)(frame.data, "stream.job.keepalive");
235
+ observedJobId = rememberObservedJobId(observedJobId, payload.jobId, "stream.job.keepalive.jobId");
236
+ yield yield __await({
237
+ type: "keepalive",
238
+ jobId: payload.jobId,
239
+ timestamp: payload.timestamp,
240
+ });
241
+ continue;
242
+ }
243
+ if (frame.event === "job.progress") {
244
+ try {
245
+ const payload = (0, validation_1.decodeDirectProgressPayload)(frame.data, "stream.job.progress");
246
+ observedJobId = rememberObservedJobId(observedJobId, payload.jobId, "stream.job.progress.jobId");
247
+ if (!rememberProgress(seenProgress, payload.progress, frame.id)) {
248
+ continue;
249
+ }
250
+ if (currentJob && currentJob.id === payload.jobId) {
251
+ currentJob.status = payload.status;
252
+ currentJob.progress.push((0, validation_1.cloneUnknown)(payload.progress));
253
+ currentJob.updatedAt = payload.progress.timestamp;
254
+ }
255
+ yield yield __await(Object.assign({ type: "progress", jobId: payload.jobId, job: (0, validation_1.cloneUnknown)(currentJob), status: payload.status, progress: (0, validation_1.cloneUnknown)(payload.progress) }, (frame.id ? { eventId: frame.id } : {})));
256
+ continue;
257
+ }
258
+ catch (error) {
259
+ if (!(error instanceof errors_1.CloudWebSearchValidationError)) {
260
+ throw error;
261
+ }
262
+ lifecycleDecodeError = error;
263
+ }
264
+ }
265
+ if (frame.event === "job.completed") {
266
+ try {
267
+ const payload = (0, validation_1.decodeDirectCompletedPayload)(frame.data, options, "stream.job.completed");
268
+ observedJobId = rememberObservedJobId(observedJobId, payload.job.id, "stream.job.completed.job.id");
269
+ currentJob = (0, validation_1.cloneUnknown)(payload.job);
270
+ currentJob.status = "completed";
271
+ currentJob.results = (0, validation_1.cloneUnknown)(payload.result);
272
+ yield yield __await(Object.assign({ type: "completed", jobId: payload.job.id, job: (0, validation_1.cloneUnknown)(currentJob), result: (0, validation_1.cloneUnknown)(payload.result) }, (frame.id ? { eventId: frame.id } : {})));
273
+ continue;
274
+ }
275
+ catch (error) {
276
+ if (!(error instanceof errors_1.CloudWebSearchValidationError)) {
277
+ throw error;
278
+ }
279
+ lifecycleDecodeError = error;
280
+ }
281
+ }
282
+ if (frame.event === "job.error" || frame.event === "job.failed") {
283
+ try {
284
+ const payload = (0, validation_1.decodeDirectErrorPayload)(frame.data, options, `stream.${frame.event}`);
285
+ observedJobId = rememberObservedJobId(observedJobId, payload.job.id, `stream.${frame.event}.job.id`);
286
+ currentJob = (0, validation_1.cloneUnknown)(payload.job);
287
+ currentJob.status = "error";
288
+ currentJob.errorMessage = payload.errorMessage;
289
+ yield yield __await(Object.assign({ type: "error", jobId: payload.job.id, job: (0, validation_1.cloneUnknown)(currentJob), errorMessage: payload.errorMessage }, (frame.id ? { eventId: frame.id } : {})));
290
+ continue;
291
+ }
292
+ catch (error) {
293
+ if (!(error instanceof errors_1.CloudWebSearchValidationError)) {
294
+ throw error;
295
+ }
296
+ lifecycleDecodeError = error;
297
+ }
298
+ }
299
+ if (frame.event === "job.cancelled") {
300
+ try {
301
+ const payload = (0, validation_1.decodeDirectCancelledPayload)(frame.data, options, "stream.job.cancelled");
302
+ observedJobId = rememberObservedJobId(observedJobId, payload.job.id, "stream.job.cancelled.job.id");
303
+ currentJob = (0, validation_1.cloneUnknown)(payload.job);
304
+ currentJob.status = "cancelled";
305
+ currentJob.errorMessage = (_d = currentJob.errorMessage) !== null && _d !== void 0 ? _d : "Job cancelled";
306
+ yield yield __await(Object.assign({ type: "cancelled", jobId: payload.job.id, job: (0, validation_1.cloneUnknown)(currentJob) }, (frame.id ? { eventId: frame.id } : {})));
307
+ continue;
308
+ }
309
+ catch (error) {
310
+ if (!(error instanceof errors_1.CloudWebSearchValidationError)) {
311
+ throw error;
312
+ }
313
+ lifecycleDecodeError = error;
314
+ }
315
+ }
316
+ let record = null;
317
+ try {
318
+ record = (0, validation_1.decodeCloudWebSearchJobEventRecord)(frame.data, `stream.${frame.event}`);
319
+ }
320
+ catch (error) {
321
+ if (lifecycleDecodeError) {
322
+ throw lifecycleDecodeError;
323
+ }
324
+ if (error instanceof errors_1.CloudWebSearchValidationError) {
325
+ yield yield __await({
326
+ type: "unknown",
327
+ job: (0, validation_1.cloneUnknown)(currentJob),
328
+ frame: (0, validation_1.cloneUnknown)(frame),
329
+ });
330
+ continue;
331
+ }
332
+ throw error;
333
+ }
334
+ observedJobId = rememberObservedJobId(observedJobId, record.jobId, `stream.${frame.event}.jobId`);
335
+ applyLifecycleUpdate(currentJob, record, options);
336
+ if (shouldEmitProgress(record)) {
337
+ const progress = toProgressEntry(record);
338
+ if (progress && rememberProgress(seenProgress, progress, record.id)) {
339
+ if (currentJob && currentJob.id === record.jobId) {
340
+ currentJob.status = deriveStatusFromRecord(record, currentJob.status);
341
+ currentJob.progress.push((0, validation_1.cloneUnknown)(progress));
342
+ currentJob.updatedAt = progress.timestamp;
343
+ }
344
+ yield yield __await({
345
+ type: "progress",
346
+ jobId: record.jobId,
347
+ job: (0, validation_1.cloneUnknown)(currentJob),
348
+ status: deriveStatusFromRecord(record, currentJob === null || currentJob === void 0 ? void 0 : currentJob.status),
349
+ progress: (0, validation_1.cloneUnknown)(progress),
350
+ eventId: record.id,
351
+ rawEventType: record.eventType,
352
+ raw: (0, validation_1.cloneUnknown)(record),
353
+ });
354
+ }
355
+ continue;
356
+ }
357
+ if (record.eventType === "job.completed") {
358
+ yield yield __await({
359
+ type: "completed",
360
+ jobId: record.jobId,
361
+ job: (0, validation_1.cloneUnknown)(currentJob),
362
+ result: (0, validation_1.cloneUnknown)((_e = currentJob === null || currentJob === void 0 ? void 0 : currentJob.results) !== null && _e !== void 0 ? _e : extractResultFromPayload(record.payload, options, `stream.${record.eventType}.payload`)),
363
+ eventId: record.id,
364
+ raw: (0, validation_1.cloneUnknown)(record),
365
+ });
366
+ continue;
367
+ }
368
+ if (record.eventType === "job.failed" || record.eventType === "job.error") {
369
+ yield yield __await({
370
+ type: "error",
371
+ jobId: record.jobId,
372
+ job: (0, validation_1.cloneUnknown)(currentJob),
373
+ errorMessage: (_f = currentJob === null || currentJob === void 0 ? void 0 : currentJob.errorMessage) !== null && _f !== void 0 ? _f : extractErrorMessage(record.payload, "Web search job failed"),
374
+ eventId: record.id,
375
+ raw: (0, validation_1.cloneUnknown)(record),
376
+ });
377
+ continue;
378
+ }
379
+ if (record.eventType === "job.cancelled") {
380
+ yield yield __await({
381
+ type: "cancelled",
382
+ jobId: record.jobId,
383
+ job: (0, validation_1.cloneUnknown)(currentJob),
384
+ eventId: record.id,
385
+ raw: (0, validation_1.cloneUnknown)(record),
386
+ });
387
+ continue;
388
+ }
389
+ yield yield __await({
390
+ type: "event",
391
+ jobId: record.jobId,
392
+ job: (0, validation_1.cloneUnknown)(currentJob),
393
+ event: (0, validation_1.cloneUnknown)(record),
394
+ });
395
+ }
396
+ }
397
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
398
+ finally {
399
+ try {
400
+ if (!_g && !_a && (_b = _h.return)) yield __await(_b.call(_h));
401
+ }
402
+ finally { if (e_1) throw e_1.error; }
403
+ }
404
+ });
405
+ }
406
+ class KognitiveCloudWebSearchClient {
407
+ constructor(config) {
408
+ this.jobs = {
409
+ list: (options) => this.listJobs(options),
410
+ create: (input) => this.createJob(input),
411
+ createSearch: (input, parameters) => this.createSearchJob(input, parameters),
412
+ createResearch: (input, options) => this.createResearchJob(input, options),
413
+ get: (jobId, options) => this.getJob(jobId, options),
414
+ result: (jobId, options) => this.getJobResult(jobId, options),
415
+ cancel: (jobId, options) => this.cancelJob(jobId, options),
416
+ stream: (jobId, init) => this.streamJob(jobId, init),
417
+ subscribe: (jobId, options) => this.subscribeToJob(jobId, options),
418
+ subscribeRich: (jobId, options) => this.subscribeToRichJob(jobId, options),
419
+ streamUrl: (jobId) => this.getJobEventsStreamUrl(jobId),
420
+ waitForCompletion: (jobId, options) => this.waitForCompletion(jobId, options),
421
+ };
422
+ this.transport = isTransportLike(config) ? config : new client_core_1.HttpTransport(config);
423
+ }
424
+ getJobEventsStreamUrl(jobId) {
425
+ return `${this.transport.baseUrl}/api/cloud/web-search/jobs/${encodeURIComponent(assertJobId(jobId))}/events/stream`;
426
+ }
427
+ async listJobs(options) {
428
+ const response = await this.transport.json("/api/cloud/web-search/jobs");
429
+ return (0, validation_1.decodeCloudWebSearchJobListEnvelope)(response, options).jobs;
430
+ }
431
+ async createJob(input) {
432
+ const body = (0, validation_1.validateCreateCloudWebSearchJobInput)(input);
433
+ const response = await this.transport.json("/api/cloud/web-search/jobs", {
434
+ method: "POST",
435
+ body: JSON.stringify(body),
436
+ });
437
+ return (0, validation_1.decodeCloudWebSearchJobRecord)(response, undefined, "jobs.create");
438
+ }
439
+ async createSearchJob(input, parameters) {
440
+ return this.createJob(createSearchJobInput(input, parameters));
441
+ }
442
+ async createResearchJob(input, options) {
443
+ return this.createJob(createResearchJobInput(input, options));
444
+ }
445
+ async getJob(jobId, options) {
446
+ const response = await this.transport.json(`/api/cloud/web-search/jobs/${encodeURIComponent(assertJobId(jobId))}`);
447
+ return (0, validation_1.decodeCloudWebSearchJobRecord)(response, options, "jobs.get");
448
+ }
449
+ async getJobResult(jobId, options) {
450
+ const response = await this.transport.json(`/api/cloud/web-search/jobs/${encodeURIComponent(assertJobId(jobId))}/result`);
451
+ return (0, validation_1.decodeCloudWebSearchJobResultEnvelope)(response, options, "jobs.result");
452
+ }
453
+ async cancelJob(jobId, options) {
454
+ const response = await this.transport.json(`/api/cloud/web-search/jobs/${encodeURIComponent(assertJobId(jobId))}/cancel`, {
455
+ method: "POST",
456
+ });
457
+ return (0, validation_1.decodeCloudWebSearchJobRecord)(response, options, "jobs.cancel");
458
+ }
459
+ async streamJob(jobId, init) {
460
+ return this.transport.raw(`/api/cloud/web-search/jobs/${encodeURIComponent(assertJobId(jobId))}/events/stream`, init);
461
+ }
462
+ async subscribeToJob(jobId, options) {
463
+ const response = await this.streamJob(jobId, options === null || options === void 0 ? void 0 : options.init);
464
+ if (!response.body) {
465
+ throw new errors_1.CloudWebSearchStreamProtocolError("Cloud web-search stream response did not include a body");
466
+ }
467
+ return readCloudWebSearchEventStream(response.body, options);
468
+ }
469
+ async subscribeToRichJob(jobId, options) {
470
+ const events = await this.subscribeToJob(jobId, options);
471
+ function richStream() {
472
+ return __asyncGenerator(this, arguments, function* richStream_1() {
473
+ var _a, e_2, _b, _c;
474
+ try {
475
+ for (var _d = true, events_1 = __asyncValues(events), events_1_1; events_1_1 = yield __await(events_1.next()), _a = events_1_1.done, !_a; _d = true) {
476
+ _c = events_1_1.value;
477
+ _d = false;
478
+ const event = _c;
479
+ for (const richEvent of (0, rich_events_1.toCloudWebSearchRichEvents)(event)) {
480
+ yield yield __await(richEvent);
481
+ }
482
+ }
483
+ }
484
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
485
+ finally {
486
+ try {
487
+ if (!_d && !_a && (_b = events_1.return)) yield __await(_b.call(events_1));
488
+ }
489
+ finally { if (e_2) throw e_2.error; }
490
+ }
491
+ });
492
+ }
493
+ return richStream();
494
+ }
495
+ async waitForCompletion(jobId, options) {
496
+ var _a, _b;
497
+ const normalizedJobId = assertJobId(jobId);
498
+ const job = await this.transport.poll(() => this.getJob(normalizedJobId, options), {
499
+ intervalMs: options === null || options === void 0 ? void 0 : options.intervalMs,
500
+ timeoutMs: options === null || options === void 0 ? void 0 : options.timeoutMs,
501
+ isDone: (value) => TERMINAL_STATUSES.has(value.status),
502
+ });
503
+ if (job.status === "completed") {
504
+ const envelope = await this.getJobResult(normalizedJobId, options);
505
+ return {
506
+ job,
507
+ result: envelope.result,
508
+ };
509
+ }
510
+ if (job.status === "cancelled") {
511
+ throw new Error((_a = job.errorMessage) !== null && _a !== void 0 ? _a : `Web search job ${normalizedJobId} was cancelled`);
512
+ }
513
+ throw new Error((_b = job.errorMessage) !== null && _b !== void 0 ? _b : `Web search job ${normalizedJobId} finished with status ${job.status}`);
514
+ }
515
+ }
516
+ exports.KognitiveCloudWebSearchClient = KognitiveCloudWebSearchClient;
@@ -0,0 +1,9 @@
1
+ export declare class CloudWebSearchValidationError extends Error {
2
+ readonly path: string;
3
+ readonly expected: string;
4
+ readonly actual: unknown;
5
+ constructor(path: string, expected: string, actual: unknown);
6
+ }
7
+ export declare class CloudWebSearchStreamProtocolError extends Error {
8
+ constructor(message: string);
9
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CloudWebSearchStreamProtocolError = exports.CloudWebSearchValidationError = void 0;
4
+ class CloudWebSearchValidationError extends Error {
5
+ constructor(path, expected, actual) {
6
+ super(`Invalid cloud web-search payload at ${path}: expected ${expected}`);
7
+ this.name = "CloudWebSearchValidationError";
8
+ this.path = path;
9
+ this.expected = expected;
10
+ this.actual = actual;
11
+ }
12
+ }
13
+ exports.CloudWebSearchValidationError = CloudWebSearchValidationError;
14
+ class CloudWebSearchStreamProtocolError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = "CloudWebSearchStreamProtocolError";
18
+ }
19
+ }
20
+ exports.CloudWebSearchStreamProtocolError = CloudWebSearchStreamProtocolError;
@@ -0,0 +1,6 @@
1
+ export { KognitiveCloudWebSearchClient, readCloudWebSearchEventStream } from "./client";
2
+ export { CloudWebSearchStreamProtocolError, CloudWebSearchValidationError } from "./errors";
3
+ export { toCloudWebSearchRichEvents } from "./rich-events";
4
+ export { readSSEStream } from "./sse";
5
+ export type { ParsedSSEEvent } from "./sse";
6
+ export type { CloudWebSearchClientConfig, CloudWebSearchDecodeOptions, CloudWebSearchExecutionParameters, CloudWebSearchJobEventRecord, CloudWebSearchJobRecord, CloudWebSearchJobResultEnvelope, CloudWebSearchJobStatus, CloudWebSearchJobWaitResult, CloudWebSearchMode, CloudWebSearchOutputParser, CloudWebSearchProductAnswer, CloudWebSearchProgressEntry, CloudWebSearchRichEvent, CloudWebSearchRichSource, CloudWebSearchResearchJobInput, CloudWebSearchResult, CloudWebSearchSearchJobInput, CloudWebSearchSource, CloudWebSearchStreamEvent, CloudWebSearchSubscribeOptions, CloudWebSearchTimeRange, CreateCloudWebSearchJobInput, LogLevel, ResearchPlan, ResearchPlanTodo, WaitForCompletionOptions, } from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readSSEStream = exports.toCloudWebSearchRichEvents = exports.CloudWebSearchValidationError = exports.CloudWebSearchStreamProtocolError = exports.readCloudWebSearchEventStream = exports.KognitiveCloudWebSearchClient = void 0;
4
+ var client_1 = require("./client");
5
+ Object.defineProperty(exports, "KognitiveCloudWebSearchClient", { enumerable: true, get: function () { return client_1.KognitiveCloudWebSearchClient; } });
6
+ Object.defineProperty(exports, "readCloudWebSearchEventStream", { enumerable: true, get: function () { return client_1.readCloudWebSearchEventStream; } });
7
+ var errors_1 = require("./errors");
8
+ Object.defineProperty(exports, "CloudWebSearchStreamProtocolError", { enumerable: true, get: function () { return errors_1.CloudWebSearchStreamProtocolError; } });
9
+ Object.defineProperty(exports, "CloudWebSearchValidationError", { enumerable: true, get: function () { return errors_1.CloudWebSearchValidationError; } });
10
+ var rich_events_1 = require("./rich-events");
11
+ Object.defineProperty(exports, "toCloudWebSearchRichEvents", { enumerable: true, get: function () { return rich_events_1.toCloudWebSearchRichEvents; } });
12
+ var sse_1 = require("./sse");
13
+ Object.defineProperty(exports, "readSSEStream", { enumerable: true, get: function () { return sse_1.readSSEStream; } });
@@ -0,0 +1,2 @@
1
+ import type { CloudWebSearchRichEvent, CloudWebSearchStreamEvent } from "./types";
2
+ export declare function toCloudWebSearchRichEvents<TOutput = unknown>(event: CloudWebSearchStreamEvent<TOutput>): CloudWebSearchRichEvent<TOutput>[];