@corti/dictation-web 0.5.0 → 0.5.2-rc

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/bundle.js CHANGED
@@ -1049,7 +1049,7 @@ function usageEvent(detail) {
1049
1049
  });
1050
1050
  }
1051
1051
  function errorEvent(error) {
1052
- const message = error instanceof Error && error.message ? error.message : String(error);
1052
+ const message = error instanceof Error && error.message ? error.message : JSON.stringify(error);
1053
1053
  return new CustomEvent("error", {
1054
1054
  bubbles: false,
1055
1055
  composed: true,
@@ -1211,7 +1211,7 @@ function getLanguageName(languageCode) {
1211
1211
  }
1212
1212
  }
1213
1213
  function getLanguagesByRegion(region) {
1214
- const languages = DEFAULT_LANGUAGES_BY_REGION[region || "default"] || DEFAULT_LANGUAGES_BY_REGION.default;
1214
+ const languages = DEFAULT_LANGUAGES_BY_REGION[region || "default"] || DEFAULT_LANGUAGES_BY_REGION["default"];
1215
1215
  const defaultLanguage = languages?.[0];
1216
1216
  return { defaultLanguage, languages };
1217
1217
  }
@@ -1347,14 +1347,14 @@ function decodeToken(token) {
1347
1347
  const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
1348
1348
  let jsonPayload;
1349
1349
  try {
1350
- jsonPayload = decodeURIComponent(atob(base64).split("").map((c6) => `%${`00${c6.charCodeAt(0).toString(16)}`.slice(-2)}`).join(""));
1351
- } catch (_error) {
1350
+ jsonPayload = decodeURIComponent(atob(base64).split("").map((c6) => "%" + ("00" + c6.charCodeAt(0).toString(16)).slice(-2)).join(""));
1351
+ } catch (error) {
1352
1352
  throw new Error("Failed to decode token payload");
1353
1353
  }
1354
1354
  let tokenDetails;
1355
1355
  try {
1356
1356
  tokenDetails = JSON.parse(jsonPayload);
1357
- } catch (_error) {
1357
+ } catch (error) {
1358
1358
  throw new Error("Invalid JSON payload in token");
1359
1359
  }
1360
1360
  const issuerUrl = tokenDetails.iss;
@@ -1765,6 +1765,19 @@ var UnauthorizedError = class _UnauthorizedError extends CortiError {
1765
1765
  }
1766
1766
  };
1767
1767
 
1768
+ // node_modules/@corti/sdk/dist/esm/api/errors/BadGatewayError.mjs
1769
+ var BadGatewayError = class _BadGatewayError extends CortiError {
1770
+ constructor(body, rawResponse) {
1771
+ super({
1772
+ message: "BadGatewayError",
1773
+ statusCode: 502,
1774
+ body,
1775
+ rawResponse
1776
+ });
1777
+ Object.setPrototypeOf(this, _BadGatewayError.prototype);
1778
+ }
1779
+ };
1780
+
1768
1781
  // node_modules/@corti/sdk/dist/esm/core/auth/OAuthTokenProvider.mjs
1769
1782
  var __awaiter = function(thisArg, _arguments, P2, generator) {
1770
1783
  function adopt(value) {
@@ -2383,6 +2396,15 @@ function requestWithRetries(requestFn_1) {
2383
2396
  });
2384
2397
  }
2385
2398
 
2399
+ // node_modules/@corti/sdk/dist/esm/custom/utils/withCredentialsConfig.mjs
2400
+ var defaultWithCredentials = void 0;
2401
+ function getDefaultWithCredentials() {
2402
+ return defaultWithCredentials;
2403
+ }
2404
+ function setDefaultWithCredentials(value) {
2405
+ defaultWithCredentials = value;
2406
+ }
2407
+
2386
2408
  // node_modules/@corti/sdk/dist/esm/core/fetcher/Fetcher.mjs
2387
2409
  var __awaiter9 = function(thisArg, _arguments, P2, generator) {
2388
2410
  function adopt(value) {
@@ -2444,7 +2466,8 @@ function fetcherImpl(args) {
2444
2466
  const fetchFn = yield getFetchFn();
2445
2467
  try {
2446
2468
  const response = yield requestWithRetries(() => __awaiter9(this, void 0, void 0, function* () {
2447
- return makeRequest(fetchFn, url, args.method, yield getHeaders(args), requestBody, args.timeoutMs, args.abortSignal, args.withCredentials, args.duplex);
2469
+ var _a;
2470
+ return makeRequest(fetchFn, url, args.method, yield getHeaders(args), requestBody, args.timeoutMs, args.abortSignal, (_a = args.withCredentials) !== null && _a !== void 0 ? _a : getDefaultWithCredentials(), args.duplex);
2448
2471
  }), args.maxRetries);
2449
2472
  if (response.status >= 200 && response.status < 400) {
2450
2473
  return {
@@ -5168,12 +5191,16 @@ var AuthGetTokenRequest = schemas_exports.object({
5168
5191
  var agents_exports = {};
5169
5192
  __export(agents_exports, {
5170
5193
  AgentsCreateAgent: () => AgentsCreateAgent,
5194
+ AgentsCreateAgentAgentType: () => AgentsCreateAgentAgentType,
5171
5195
  AgentsCreateAgentExpertsItem: () => AgentsCreateAgentExpertsItem,
5172
5196
  AgentsMessageSendParams: () => AgentsMessageSendParams,
5173
5197
  AgentsMessageSendResponse: () => AgentsMessageSendResponse,
5174
5198
  list: () => list_exports
5175
5199
  });
5176
5200
 
5201
+ // node_modules/@corti/sdk/dist/esm/serialization/resources/agents/types/AgentsCreateAgentAgentType.mjs
5202
+ var AgentsCreateAgentAgentType = schemas_exports.enum_(["expert", "orchestrator", "interviewing-expert"]);
5203
+
5177
5204
  // node_modules/@corti/sdk/dist/esm/serialization/types/AgentsCreateMcpServerTransportType.mjs
5178
5205
  var AgentsCreateMcpServerTransportType = schemas_exports.enum_(["stdio", "streamable_http", "sse"]);
5179
5206
 
@@ -5186,6 +5213,7 @@ var AgentsCreateMcpServer = schemas_exports.object({
5186
5213
  description: schemas_exports.string().optional(),
5187
5214
  transportType: AgentsCreateMcpServerTransportType,
5188
5215
  authorizationType: AgentsCreateMcpServerAuthorizationType,
5216
+ authorizationScope: schemas_exports.string().optional(),
5189
5217
  url: schemas_exports.string(),
5190
5218
  redirectUrl: schemas_exports.string().optional(),
5191
5219
  token: schemas_exports.string().optional()
@@ -5200,15 +5228,16 @@ var AgentsCreateExpert = schemas_exports.object({
5200
5228
  mcpServers: schemas_exports.list(AgentsCreateMcpServer).optional()
5201
5229
  });
5202
5230
 
5203
- // node_modules/@corti/sdk/dist/esm/serialization/types/AgentsExpertReference.mjs
5204
- var AgentsExpertReference = schemas_exports.object({
5231
+ // node_modules/@corti/sdk/dist/esm/serialization/types/AgentsCreateExpertReference.mjs
5232
+ var AgentsCreateExpertReference = schemas_exports.object({
5205
5233
  type: schemas_exports.stringLiteral("reference"),
5206
5234
  id: schemas_exports.string().optional(),
5207
- name: schemas_exports.string().optional()
5235
+ name: schemas_exports.string().optional(),
5236
+ systemPrompt: schemas_exports.string().optional()
5208
5237
  });
5209
5238
 
5210
5239
  // node_modules/@corti/sdk/dist/esm/serialization/resources/agents/types/AgentsCreateAgentExpertsItem.mjs
5211
- var AgentsCreateAgentExpertsItem = schemas_exports.undiscriminatedUnion([AgentsCreateExpert, AgentsExpertReference]);
5240
+ var AgentsCreateAgentExpertsItem = schemas_exports.undiscriminatedUnion([AgentsCreateExpert, AgentsCreateExpertReference]);
5212
5241
 
5213
5242
  // node_modules/@corti/sdk/dist/esm/serialization/types/AgentsMessageRole.mjs
5214
5243
  var AgentsMessageRole = schemas_exports.enum_(["user", "agent"]);
@@ -5332,6 +5361,7 @@ var AgentsMcpServer = schemas_exports.object({
5332
5361
  name: schemas_exports.string(),
5333
5362
  transportType: AgentsMcpServerTransportType,
5334
5363
  authorizationType: AgentsMcpServerAuthorizationType,
5364
+ authorizationScope: schemas_exports.string().optional(),
5335
5365
  url: schemas_exports.string(),
5336
5366
  redirectUrl: schemas_exports.string().optionalNullable()
5337
5367
  });
@@ -5346,6 +5376,14 @@ var AgentsExpert = schemas_exports.object({
5346
5376
  mcpServers: schemas_exports.list(AgentsMcpServer).optional()
5347
5377
  });
5348
5378
 
5379
+ // node_modules/@corti/sdk/dist/esm/serialization/types/AgentsExpertReference.mjs
5380
+ var AgentsExpertReference = schemas_exports.object({
5381
+ type: schemas_exports.stringLiteral("reference"),
5382
+ id: schemas_exports.string(),
5383
+ name: schemas_exports.string(),
5384
+ systemPrompt: schemas_exports.string().optional()
5385
+ });
5386
+
5349
5387
  // node_modules/@corti/sdk/dist/esm/serialization/types/AgentsAgentExpertsItem.mjs
5350
5388
  var AgentsAgentExpertsItem = schemas_exports.undiscriminatedUnion([AgentsExpert, AgentsExpertReference]);
5351
5389
 
@@ -5374,6 +5412,7 @@ var Response = schemas_exports.list(AgentsAgentResponse);
5374
5412
  // node_modules/@corti/sdk/dist/esm/serialization/resources/agents/client/requests/AgentsCreateAgent.mjs
5375
5413
  var AgentsCreateAgent = schemas_exports.object({
5376
5414
  name: schemas_exports.string(),
5415
+ agentType: AgentsCreateAgentAgentType.optional(),
5377
5416
  systemPrompt: schemas_exports.string().optional(),
5378
5417
  description: schemas_exports.string(),
5379
5418
  experts: schemas_exports.list(AgentsCreateAgentExpertsItem).optional()
@@ -5489,6 +5528,25 @@ var DocumentsUpdateRequest = schemas_exports.object({
5489
5528
  sections: schemas_exports.list(DocumentsSectionInput).optional()
5490
5529
  });
5491
5530
 
5531
+ // node_modules/@corti/sdk/dist/esm/serialization/types/CommonCodingSystemEnum.mjs
5532
+ var CommonCodingSystemEnum = schemas_exports.enum_(["icd10cm", "icd10pcs", "cpt"]);
5533
+
5534
+ // node_modules/@corti/sdk/dist/esm/serialization/types/CommonDocumentIdContext.mjs
5535
+ var CommonDocumentIdContext = schemas_exports.object({
5536
+ type: schemas_exports.stringLiteral("documentId"),
5537
+ documentId: schemas_exports.string()
5538
+ });
5539
+
5540
+ // node_modules/@corti/sdk/dist/esm/serialization/types/CommonAiContext.mjs
5541
+ var CommonAiContext = schemas_exports.undiscriminatedUnion([CommonTextContext, CommonDocumentIdContext]);
5542
+
5543
+ // node_modules/@corti/sdk/dist/esm/serialization/resources/codes/client/requests/CodesGeneralPredictRequest.mjs
5544
+ var CodesGeneralPredictRequest = schemas_exports.object({
5545
+ system: schemas_exports.list(CommonCodingSystemEnum),
5546
+ context: schemas_exports.list(CommonAiContext),
5547
+ maxCandidates: schemas_exports.number().optional()
5548
+ });
5549
+
5492
5550
  // node_modules/@corti/sdk/dist/esm/serialization/types/FactsContext.mjs
5493
5551
  var FactsContext = schemas_exports.object({
5494
5552
  text: schemas_exports.string(),
@@ -5579,12 +5637,11 @@ var InteractionsEncounterResponse = schemas_exports.object({
5579
5637
 
5580
5638
  // node_modules/@corti/sdk/dist/esm/serialization/types/ErrorResponse.mjs
5581
5639
  var ErrorResponse = schemas_exports.object({
5582
- requestid: schemas_exports.string().optional(),
5640
+ requestid: schemas_exports.string(),
5641
+ status: schemas_exports.number(),
5583
5642
  type: schemas_exports.string(),
5584
- status: schemas_exports.number().optional(),
5585
- title: schemas_exports.string().optional(),
5586
- details: schemas_exports.string().optional(),
5587
- instance: schemas_exports.string().optional()
5643
+ detail: schemas_exports.string(),
5644
+ validationErrors: schemas_exports.list(schemas_exports.record(schemas_exports.string(), schemas_exports.string())).optional()
5588
5645
  });
5589
5646
 
5590
5647
  // node_modules/@corti/sdk/dist/esm/serialization/types/FactsFactGroupsItemTranslationsItem.mjs
@@ -5797,6 +5854,27 @@ var FactsBatchUpdateResponse = schemas_exports.object({
5797
5854
  facts: schemas_exports.list(FactsBatchUpdateItem)
5798
5855
  });
5799
5856
 
5857
+ // node_modules/@corti/sdk/dist/esm/serialization/types/CodesGeneralReadResponseEvidencesItem.mjs
5858
+ var CodesGeneralReadResponseEvidencesItem = schemas_exports.object({
5859
+ contextIndex: schemas_exports.number().optional(),
5860
+ text: schemas_exports.string().optional()
5861
+ });
5862
+
5863
+ // node_modules/@corti/sdk/dist/esm/serialization/types/CodesGeneralReadResponse.mjs
5864
+ var CodesGeneralReadResponse = schemas_exports.object({
5865
+ system: CommonCodingSystemEnum,
5866
+ code: schemas_exports.string(),
5867
+ display: schemas_exports.string(),
5868
+ evidences: schemas_exports.list(CodesGeneralReadResponseEvidencesItem).optional()
5869
+ });
5870
+
5871
+ // node_modules/@corti/sdk/dist/esm/serialization/types/CodesGeneralResponse.mjs
5872
+ var CodesGeneralResponse = schemas_exports.object({
5873
+ codes: schemas_exports.list(CodesGeneralReadResponse),
5874
+ candidates: schemas_exports.list(CodesGeneralReadResponse),
5875
+ usageInfo: CommonUsageInfo.optional()
5876
+ });
5877
+
5800
5878
  // node_modules/@corti/sdk/dist/esm/serialization/types/FactsExtractResponseFactsItem.mjs
5801
5879
  var FactsExtractResponseFactsItem = schemas_exports.object({
5802
5880
  group: schemas_exports.string(),
@@ -5859,12 +5937,17 @@ var CommonTranscriptResponse = schemas_exports.object({
5859
5937
  end: schemas_exports.number()
5860
5938
  });
5861
5939
 
5940
+ // node_modules/@corti/sdk/dist/esm/serialization/types/TranscriptsStatusEnum.mjs
5941
+ var TranscriptsStatusEnum = schemas_exports.enum_(["completed", "processing", "failed"]);
5942
+
5862
5943
  // node_modules/@corti/sdk/dist/esm/serialization/types/TranscriptsResponse.mjs
5863
5944
  var TranscriptsResponse = schemas_exports.object({
5864
5945
  id: Uuid,
5865
5946
  metadata: TranscriptsMetadata,
5866
5947
  transcripts: schemas_exports.list(CommonTranscriptResponse).optionalNullable(),
5867
- usageInfo: CommonUsageInfo
5948
+ usageInfo: CommonUsageInfo,
5949
+ recordingId: Uuid,
5950
+ status: TranscriptsStatusEnum
5868
5951
  });
5869
5952
 
5870
5953
  // node_modules/@corti/sdk/dist/esm/serialization/types/TranscriptsData.mjs
@@ -5885,6 +5968,11 @@ var TranscriptsListResponse = schemas_exports.object({
5885
5968
  transcripts: schemas_exports.list(TranscriptsListItem).optionalNullable()
5886
5969
  });
5887
5970
 
5971
+ // node_modules/@corti/sdk/dist/esm/serialization/types/TranscriptsStatusResponse.mjs
5972
+ var TranscriptsStatusResponse = schemas_exports.object({
5973
+ status: TranscriptsStatusEnum
5974
+ });
5975
+
5888
5976
  // node_modules/@corti/sdk/dist/esm/serialization/types/CommonSortingDirectionEnum.mjs
5889
5977
  var CommonSortingDirectionEnum = schemas_exports.enum_(["asc", "desc"]);
5890
5978
 
@@ -5909,13 +5997,12 @@ var StreamConfigTranscription = schemas_exports.object({
5909
5997
  });
5910
5998
 
5911
5999
  // node_modules/@corti/sdk/dist/esm/serialization/types/StreamConfigModeType.mjs
5912
- var StreamConfigModeType = schemas_exports.enum_(["facts", "transcription", "documentation"]);
6000
+ var StreamConfigModeType = schemas_exports.enum_(["facts", "transcription"]);
5913
6001
 
5914
6002
  // node_modules/@corti/sdk/dist/esm/serialization/types/StreamConfigMode.mjs
5915
6003
  var StreamConfigMode = schemas_exports.object({
5916
6004
  type: StreamConfigModeType,
5917
- outputLocale: StreamSupportedLanguage.optional(),
5918
- templateId: schemas_exports.string().optional()
6005
+ outputLocale: StreamSupportedLanguage.optional()
5919
6006
  });
5920
6007
 
5921
6008
  // node_modules/@corti/sdk/dist/esm/serialization/types/StreamConfig.mjs
@@ -7674,7 +7761,7 @@ var Transcripts = class {
7674
7761
  });
7675
7762
  }
7676
7763
  /**
7677
- * Create a transcript from an audio file attached, via `/recordings` endpoint, to the interaction.<br/><Note>Each interaction may have more than one audio file and transcript associated with it. While audio files up to 60min in total duration, or 150MB in total size, may be attached to an interaction, synchronous processing is only supported for audio files less than ~2min in duration.<br/><br/>If an audio file takes longer to transcribe than the 25sec synchronous processing timeout, then it will continue to process asynchronously. In this scenario, an empty transcript will be returned with a location header that can be used to retrieve the final transcript.<br/><br/>The client can poll the Get Transcript endpoint (`GET /interactions/{id}/transcripts/{transcriptId}/status`) for transcript status changes:<br/>- `200 OK` with status `processing`, `completed`, or `failed`<br/>- `404 Not Found` if the `interactionId` or `transcriptId` are invalid<br/><br/>The completed transcript can be retrieved via the Get Transcript endpoint (`GET /interactions/{id}/transcripts/{transcriptId}/`).</Note>
7764
+ * Create a transcript from an audio file attached, via `/recordings` endpoint, to the interaction.<br/><Note>Each interaction may have more than one audio file and transcript associated with it. While audio files up to 60min in total duration, or 150MB in total size, may be attached to an interaction, synchronous processing is only supported for audio files less than ~2min in duration.<br/><br/>If an audio file takes longer to transcribe than the 25sec synchronous processing timeout, then it will continue to process asynchronously. In this scenario, an incomplete or empty transcript with `status=processing` will be returned with a location header that can be used to retrieve the final transcript.<br/><br/>The client can poll the Get Transcript endpoint (`GET /interactions/{id}/transcripts/{transcriptId}/status`) for transcript status changes:<br/>- `200 OK` with status `processing`, `completed`, or `failed`<br/>- `404 Not Found` if the `interactionId` or `transcriptId` are invalid<br/><br/>The completed transcript can be retrieved via the Get Transcript endpoint (`GET /interactions/{id}/transcripts/{transcriptId}/`).</Note>
7678
7765
  *
7679
7766
  * @param {Corti.Uuid} id - The unique identifier of the interaction. Must be a valid UUID.
7680
7767
  * @param {Corti.TranscriptsCreateRequest} request
@@ -7973,6 +8060,76 @@ var Transcripts = class {
7973
8060
  }
7974
8061
  });
7975
8062
  }
8063
+ /**
8064
+ * Poll for transcript creation status.<br/><Note>Status of `completed` indicates the transcript is finalized.<br/>If the transcript is retrieved while status is `processing`, then it will be incomplete.<br/>Status of `failed` indicate the transcript was not created successfully; please retry.</Note>
8065
+ *
8066
+ * @param {Corti.Uuid} id - The unique identifier of the interaction. Must be a valid UUID.
8067
+ * @param {Corti.Uuid} transcriptId - The unique identifier of the transcript. Must be a valid UUID.
8068
+ * @param {Transcripts.RequestOptions} requestOptions - Request-specific configuration.
8069
+ *
8070
+ * @throws {@link Corti.NotFoundError}
8071
+ *
8072
+ * @example
8073
+ * await client.transcripts.getStatus("f47ac10b-58cc-4372-a567-0e02b2c3d479", "f47ac10b-58cc-4372-a567-0e02b2c3d479")
8074
+ */
8075
+ getStatus(id, transcriptId, requestOptions) {
8076
+ return HttpResponsePromise.fromPromise(this.__getStatus(id, transcriptId, requestOptions));
8077
+ }
8078
+ __getStatus(id, transcriptId, requestOptions) {
8079
+ return __awaiter19(this, void 0, void 0, function* () {
8080
+ var _a, _b;
8081
+ const _response = yield fetcher({
8082
+ url: url_exports.join((_a = yield Supplier.get(this._options.baseUrl)) !== null && _a !== void 0 ? _a : (yield Supplier.get(this._options.environment)).base, `interactions/${encodeURIComponent(Uuid.jsonOrThrow(id, { omitUndefined: true }))}/transcripts/${encodeURIComponent(Uuid.jsonOrThrow(transcriptId, { omitUndefined: true }))}/status`),
8083
+ method: "GET",
8084
+ headers: mergeHeaders((_b = this._options) === null || _b === void 0 ? void 0 : _b.headers, mergeOnlyDefinedHeaders({
8085
+ Authorization: yield this._getAuthorizationHeader(),
8086
+ "Tenant-Name": requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.tenantName
8087
+ }), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.headers),
8088
+ timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4,
8089
+ maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
8090
+ abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
8091
+ });
8092
+ if (_response.ok) {
8093
+ return {
8094
+ data: TranscriptsStatusResponse.parseOrThrow(_response.body, {
8095
+ unrecognizedObjectKeys: "passthrough",
8096
+ allowUnrecognizedUnionMembers: true,
8097
+ allowUnrecognizedEnumValues: true,
8098
+ skipValidation: true,
8099
+ breadcrumbsPrefix: ["response"]
8100
+ }),
8101
+ rawResponse: _response.rawResponse
8102
+ };
8103
+ }
8104
+ if (_response.error.reason === "status-code") {
8105
+ switch (_response.error.statusCode) {
8106
+ case 404:
8107
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
8108
+ default:
8109
+ throw new CortiError({
8110
+ statusCode: _response.error.statusCode,
8111
+ body: _response.error.body,
8112
+ rawResponse: _response.rawResponse
8113
+ });
8114
+ }
8115
+ }
8116
+ switch (_response.error.reason) {
8117
+ case "non-json":
8118
+ throw new CortiError({
8119
+ statusCode: _response.error.statusCode,
8120
+ body: _response.error.rawBody,
8121
+ rawResponse: _response.rawResponse
8122
+ });
8123
+ case "timeout":
8124
+ throw new CortiTimeoutError("Timeout exceeded when calling GET /interactions/{id}/transcripts/{transcriptId}/status.");
8125
+ case "unknown":
8126
+ throw new CortiError({
8127
+ message: _response.error.errorMessage,
8128
+ rawResponse: _response.rawResponse
8129
+ });
8130
+ }
8131
+ });
8132
+ }
7976
8133
  _getAuthorizationHeader() {
7977
8134
  return __awaiter19(this, void 0, void 0, function* () {
7978
8135
  const bearer = yield Supplier.get(this._options.token);
@@ -8648,7 +8805,7 @@ var Documents = class {
8648
8805
  });
8649
8806
  }
8650
8807
  /**
8651
- * Generate Document.
8808
+ * This endpoint offers different ways to generate a document. Find guides to document generation [here](/textgen/documents-standard).
8652
8809
  *
8653
8810
  * @param {Corti.Uuid} id - The unique identifier of the interaction. Must be a valid UUID.
8654
8811
  * @param {Corti.DocumentsCreateRequest} request
@@ -10153,7 +10310,7 @@ var Agents = class {
10153
10310
  });
10154
10311
  }
10155
10312
  /**
10156
- * This endpoint retrieves the experts registry, which contains information about all available experts that can be referenced when creating agents through the AgentsExpertReference schema.
10313
+ * This endpoint retrieves the experts registry, which contains information about all available experts that can be referenced when creating agents through the AgentsCreateExpertReference schema.
10157
10314
  *
10158
10315
  * @param {Corti.AgentsGetRegistryExpertsRequest} request
10159
10316
  * @param {Agents.RequestOptions} requestOptions - Request-specific configuration.
@@ -10247,7 +10404,7 @@ var Agents = class {
10247
10404
  }
10248
10405
  };
10249
10406
 
10250
- // node_modules/@corti/sdk/dist/esm/api/resources/stream/client/Socket.mjs
10407
+ // node_modules/@corti/sdk/dist/esm/api/resources/codes/client/Client.mjs
10251
10408
  var __awaiter24 = function(thisArg, _arguments, P2, generator) {
10252
10409
  function adopt(value) {
10253
10410
  return value instanceof P2 ? value : new P2(function(resolve) {
@@ -10275,6 +10432,167 @@ var __awaiter24 = function(thisArg, _arguments, P2, generator) {
10275
10432
  step((generator = generator.apply(thisArg, _arguments || [])).next());
10276
10433
  });
10277
10434
  };
10435
+ var Codes = class {
10436
+ constructor(_options) {
10437
+ this._options = _options;
10438
+ }
10439
+ /**
10440
+ * Predict medical codes from provided context.<br/><Note>This is a stateless endpoint, designed to predict ICD-10-CM, ICD-10-PCS, and CPT codes based on input text string or documentId.<br/><br/>More than one code system may be defined in a single request, and the maximum number of codes to return per system can also be defined.<br/><br/>Code prediction requests have two possible values for context:<br/>- `text`: One set of code prediction results will be returned based on all input text defined.<br/>- `documentId`: Code prediction will be based on that defined document only.<br/><br/>The response includes two sets of results:<br/>- `Codes`: Highest confidence bundle of codes, as selected by the code prediction model<br/>- `Candidates`: Full list of candidate codes as predicted by the model, rank sorted by model confidence with maximum possible value of 50.<br/><br/>All predicted code results are based on input context defined in the request only (not other external data or assets associated with an interaction).</Note>
10441
+ *
10442
+ * @param {Corti.CodesGeneralPredictRequest} request
10443
+ * @param {Codes.RequestOptions} requestOptions - Request-specific configuration.
10444
+ *
10445
+ * @throws {@link Corti.BadRequestError}
10446
+ * @throws {@link Corti.ForbiddenError}
10447
+ * @throws {@link Corti.InternalServerError}
10448
+ * @throws {@link Corti.BadGatewayError}
10449
+ * @throws {@link Corti.GatewayTimeoutError}
10450
+ *
10451
+ * @example
10452
+ * await client.codes.predict({
10453
+ * system: ["icd10cm", "cpt"],
10454
+ * context: [{
10455
+ * type: "text",
10456
+ * text: "Short arm splint applied in ED for pain control."
10457
+ * }],
10458
+ * maxCandidates: 5
10459
+ * })
10460
+ */
10461
+ predict(request, requestOptions) {
10462
+ return HttpResponsePromise.fromPromise(this.__predict(request, requestOptions));
10463
+ }
10464
+ __predict(request, requestOptions) {
10465
+ return __awaiter24(this, void 0, void 0, function* () {
10466
+ var _a, _b;
10467
+ const _response = yield fetcher({
10468
+ url: url_exports.join((_a = yield Supplier.get(this._options.baseUrl)) !== null && _a !== void 0 ? _a : (yield Supplier.get(this._options.environment)).base, "tools/coding/"),
10469
+ method: "POST",
10470
+ headers: mergeHeaders((_b = this._options) === null || _b === void 0 ? void 0 : _b.headers, mergeOnlyDefinedHeaders({
10471
+ Authorization: yield this._getAuthorizationHeader(),
10472
+ "Tenant-Name": requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.tenantName
10473
+ }), requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.headers),
10474
+ contentType: "application/json",
10475
+ requestType: "json",
10476
+ body: CodesGeneralPredictRequest.jsonOrThrow(request, {
10477
+ unrecognizedObjectKeys: "strip",
10478
+ omitUndefined: true
10479
+ }),
10480
+ timeoutMs: (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeoutInSeconds) != null ? requestOptions.timeoutInSeconds * 1e3 : 6e4,
10481
+ maxRetries: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.maxRetries,
10482
+ abortSignal: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.abortSignal
10483
+ });
10484
+ if (_response.ok) {
10485
+ return {
10486
+ data: CodesGeneralResponse.parseOrThrow(_response.body, {
10487
+ unrecognizedObjectKeys: "passthrough",
10488
+ allowUnrecognizedUnionMembers: true,
10489
+ allowUnrecognizedEnumValues: true,
10490
+ skipValidation: true,
10491
+ breadcrumbsPrefix: ["response"]
10492
+ }),
10493
+ rawResponse: _response.rawResponse
10494
+ };
10495
+ }
10496
+ if (_response.error.reason === "status-code") {
10497
+ switch (_response.error.statusCode) {
10498
+ case 400:
10499
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
10500
+ case 403:
10501
+ throw new ForbiddenError(ErrorResponse.parseOrThrow(_response.error.body, {
10502
+ unrecognizedObjectKeys: "passthrough",
10503
+ allowUnrecognizedUnionMembers: true,
10504
+ allowUnrecognizedEnumValues: true,
10505
+ skipValidation: true,
10506
+ breadcrumbsPrefix: ["response"]
10507
+ }), _response.rawResponse);
10508
+ case 500:
10509
+ throw new InternalServerError(ErrorResponse.parseOrThrow(_response.error.body, {
10510
+ unrecognizedObjectKeys: "passthrough",
10511
+ allowUnrecognizedUnionMembers: true,
10512
+ allowUnrecognizedEnumValues: true,
10513
+ skipValidation: true,
10514
+ breadcrumbsPrefix: ["response"]
10515
+ }), _response.rawResponse);
10516
+ case 502:
10517
+ throw new BadGatewayError(ErrorResponse.parseOrThrow(_response.error.body, {
10518
+ unrecognizedObjectKeys: "passthrough",
10519
+ allowUnrecognizedUnionMembers: true,
10520
+ allowUnrecognizedEnumValues: true,
10521
+ skipValidation: true,
10522
+ breadcrumbsPrefix: ["response"]
10523
+ }), _response.rawResponse);
10524
+ case 504:
10525
+ throw new GatewayTimeoutError(ErrorResponse.parseOrThrow(_response.error.body, {
10526
+ unrecognizedObjectKeys: "passthrough",
10527
+ allowUnrecognizedUnionMembers: true,
10528
+ allowUnrecognizedEnumValues: true,
10529
+ skipValidation: true,
10530
+ breadcrumbsPrefix: ["response"]
10531
+ }), _response.rawResponse);
10532
+ default:
10533
+ throw new CortiError({
10534
+ statusCode: _response.error.statusCode,
10535
+ body: _response.error.body,
10536
+ rawResponse: _response.rawResponse
10537
+ });
10538
+ }
10539
+ }
10540
+ switch (_response.error.reason) {
10541
+ case "non-json":
10542
+ throw new CortiError({
10543
+ statusCode: _response.error.statusCode,
10544
+ body: _response.error.rawBody,
10545
+ rawResponse: _response.rawResponse
10546
+ });
10547
+ case "timeout":
10548
+ throw new CortiTimeoutError("Timeout exceeded when calling POST /tools/coding/.");
10549
+ case "unknown":
10550
+ throw new CortiError({
10551
+ message: _response.error.errorMessage,
10552
+ rawResponse: _response.rawResponse
10553
+ });
10554
+ }
10555
+ });
10556
+ }
10557
+ _getAuthorizationHeader() {
10558
+ return __awaiter24(this, void 0, void 0, function* () {
10559
+ const bearer = yield Supplier.get(this._options.token);
10560
+ if (bearer != null) {
10561
+ return `Bearer ${bearer}`;
10562
+ }
10563
+ return void 0;
10564
+ });
10565
+ }
10566
+ };
10567
+
10568
+ // node_modules/@corti/sdk/dist/esm/api/resources/stream/client/Socket.mjs
10569
+ var __awaiter25 = function(thisArg, _arguments, P2, generator) {
10570
+ function adopt(value) {
10571
+ return value instanceof P2 ? value : new P2(function(resolve) {
10572
+ resolve(value);
10573
+ });
10574
+ }
10575
+ return new (P2 || (P2 = Promise))(function(resolve, reject) {
10576
+ function fulfilled(value) {
10577
+ try {
10578
+ step(generator.next(value));
10579
+ } catch (e10) {
10580
+ reject(e10);
10581
+ }
10582
+ }
10583
+ function rejected(value) {
10584
+ try {
10585
+ step(generator["throw"](value));
10586
+ } catch (e10) {
10587
+ reject(e10);
10588
+ }
10589
+ }
10590
+ function step(result) {
10591
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
10592
+ }
10593
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10594
+ });
10595
+ };
10278
10596
  var StreamSocket = class {
10279
10597
  constructor(args) {
10280
10598
  this.eventHandlers = {};
@@ -10394,7 +10712,7 @@ var StreamSocket = class {
10394
10712
  }
10395
10713
  /** Returns a promise that resolves when the websocket is open. */
10396
10714
  waitForOpen() {
10397
- return __awaiter24(this, void 0, void 0, function* () {
10715
+ return __awaiter25(this, void 0, void 0, function* () {
10398
10716
  if (this.socket.readyState === ReconnectingWebSocket.OPEN) {
10399
10717
  return this.socket;
10400
10718
  }
@@ -10424,7 +10742,7 @@ var StreamSocket = class {
10424
10742
  };
10425
10743
 
10426
10744
  // node_modules/@corti/sdk/dist/esm/api/resources/stream/client/Client.mjs
10427
- var __awaiter25 = function(thisArg, _arguments, P2, generator) {
10745
+ var __awaiter26 = function(thisArg, _arguments, P2, generator) {
10428
10746
  function adopt(value) {
10429
10747
  return value instanceof P2 ? value : new P2(function(resolve) {
10430
10748
  resolve(value);
@@ -10456,7 +10774,7 @@ var Stream = class {
10456
10774
  this._options = _options;
10457
10775
  }
10458
10776
  connect(args) {
10459
- return __awaiter25(this, void 0, void 0, function* () {
10777
+ return __awaiter26(this, void 0, void 0, function* () {
10460
10778
  var _a;
10461
10779
  const { id, tenantName, token, headers, debug, reconnectAttempts } = args;
10462
10780
  const _queryParams = {};
@@ -10474,7 +10792,7 @@ var Stream = class {
10474
10792
  });
10475
10793
  }
10476
10794
  _getAuthorizationHeader() {
10477
- return __awaiter25(this, void 0, void 0, function* () {
10795
+ return __awaiter26(this, void 0, void 0, function* () {
10478
10796
  const bearer = yield Supplier.get(this._options.token);
10479
10797
  if (bearer != null) {
10480
10798
  return `Bearer ${bearer}`;
@@ -10520,8 +10838,72 @@ var StreamSocket2 = class extends StreamSocket {
10520
10838
  }
10521
10839
  };
10522
10840
 
10841
+ // node_modules/@corti/sdk/dist/esm/custom/utils/encodeHeadersAsWsProtocols.mjs
10842
+ var __awaiter27 = function(thisArg, _arguments, P2, generator) {
10843
+ function adopt(value) {
10844
+ return value instanceof P2 ? value : new P2(function(resolve) {
10845
+ resolve(value);
10846
+ });
10847
+ }
10848
+ return new (P2 || (P2 = Promise))(function(resolve, reject) {
10849
+ function fulfilled(value) {
10850
+ try {
10851
+ step(generator.next(value));
10852
+ } catch (e10) {
10853
+ reject(e10);
10854
+ }
10855
+ }
10856
+ function rejected(value) {
10857
+ try {
10858
+ step(generator["throw"](value));
10859
+ } catch (e10) {
10860
+ reject(e10);
10861
+ }
10862
+ }
10863
+ function step(result) {
10864
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
10865
+ }
10866
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10867
+ });
10868
+ };
10869
+ var SDK_HEADER_NAMES = /* @__PURE__ */ new Set([
10870
+ "Tenant-Name",
10871
+ "X-Fern-Language",
10872
+ "X-Fern-SDK-Name",
10873
+ "X-Fern-SDK-Version",
10874
+ "User-Agent",
10875
+ "X-Fern-Runtime",
10876
+ "X-Fern-Runtime-Version"
10877
+ ]);
10878
+ function buildProtocolsFromHeaders(headers_1) {
10879
+ return __awaiter27(this, arguments, void 0, function* (headers, filterSdkHeaders = false) {
10880
+ if (!headers || Object.keys(headers).length === 0) {
10881
+ return [];
10882
+ }
10883
+ const protocols = [];
10884
+ for (const [name, valueOrSupplier] of Object.entries(headers)) {
10885
+ if (filterSdkHeaders && SDK_HEADER_NAMES.has(name)) {
10886
+ continue;
10887
+ }
10888
+ const value = yield Supplier.get(valueOrSupplier);
10889
+ if (value != null && value !== "") {
10890
+ protocols.push(name, encodeURIComponent(value));
10891
+ }
10892
+ }
10893
+ return protocols;
10894
+ });
10895
+ }
10896
+ function getWsProtocols(options, proxyProtocols) {
10897
+ return __awaiter27(this, void 0, void 0, function* () {
10898
+ const headerProtocols = options.encodeHeadersAsWsProtocols && options.headers ? yield buildProtocolsFromHeaders(options.headers, true) : [];
10899
+ const resolvedProxy = proxyProtocols == null ? [] : Array.isArray(proxyProtocols) ? proxyProtocols : yield buildProtocolsFromHeaders(proxyProtocols, false);
10900
+ const combined = [...headerProtocols, ...resolvedProxy];
10901
+ return combined.length > 0 ? combined : [];
10902
+ });
10903
+ }
10904
+
10523
10905
  // node_modules/@corti/sdk/dist/esm/custom/CustomStream.mjs
10524
- var __awaiter26 = function(thisArg, _arguments, P2, generator) {
10906
+ var __awaiter28 = function(thisArg, _arguments, P2, generator) {
10525
10907
  function adopt(value) {
10526
10908
  return value instanceof P2 ? value : new P2(function(resolve) {
10527
10909
  resolve(value);
@@ -10560,23 +10942,32 @@ var __rest3 = function(s8, e10) {
10560
10942
  return t7;
10561
10943
  };
10562
10944
  var Stream2 = class extends Stream {
10945
+ /** Patch: constructor accepts extended options so _options is correctly typed. */
10946
+ constructor(_options) {
10947
+ super(_options);
10948
+ this._options = _options;
10949
+ }
10563
10950
  /**
10564
- * Patch: use custom connect method to support passing _options parameters
10565
- * Added optional `proxy` parameter for direct WebSocket connection (proxy scenarios)
10951
+ * Patch: use custom connect method to support passing _options parameters.
10952
+ * Patch: optional proxy parameter for direct WebSocket connection (proxy scenarios).
10953
+ * Patch: use proxy path when proxy is passed or encodeHeadersAsWsProtocols is set.
10954
+ * Patch: protocols from getWsProtocols; queryParameters from proxy or empty.
10566
10955
  */
10567
10956
  connect(_a) {
10568
10957
  const _super = Object.create(null, {
10569
10958
  connect: { get: () => super.connect }
10570
10959
  });
10571
- return __awaiter26(this, void 0, void 0, function* () {
10572
- var _b, _c;
10960
+ return __awaiter28(this, void 0, void 0, function* () {
10961
+ var _b, _c, _d, _e, _f;
10573
10962
  var { configuration, proxy } = _a, args = __rest3(_a, ["configuration", "proxy"]);
10574
- const socket = proxy ? new ReconnectingWebSocket({
10575
- url: proxy.url,
10576
- protocols: proxy.protocols || [],
10577
- queryParameters: proxy.queryParameters || {},
10578
- headers: args.headers || {},
10579
- options: { debug: (_b = args.debug) !== null && _b !== void 0 ? _b : false, maxRetries: (_c = args.reconnectAttempts) !== null && _c !== void 0 ? _c : 30 }
10963
+ const useProxyPath = proxy || this._options.encodeHeadersAsWsProtocols;
10964
+ const protocols = yield getWsProtocols(this._options, proxy === null || proxy === void 0 ? void 0 : proxy.protocols);
10965
+ const socket = useProxyPath ? new ReconnectingWebSocket({
10966
+ url: (proxy === null || proxy === void 0 ? void 0 : proxy.url) || url_exports.join((_b = yield Supplier.get(this._options["baseUrl"])) !== null && _b !== void 0 ? _b : (yield Supplier.get(this._options["environment"])).wss, `/interactions/${encodeURIComponent(args.id)}/streams`),
10967
+ protocols,
10968
+ queryParameters: (_c = proxy === null || proxy === void 0 ? void 0 : proxy.queryParameters) !== null && _c !== void 0 ? _c : {},
10969
+ headers: (_d = args.headers) !== null && _d !== void 0 ? _d : {},
10970
+ options: { debug: (_e = args.debug) !== null && _e !== void 0 ? _e : false, maxRetries: (_f = args.reconnectAttempts) !== null && _f !== void 0 ? _f : 30 }
10580
10971
  }) : (yield _super.connect.call(this, Object.assign(Object.assign({}, args), { token: (yield this._getAuthorizationHeader()) || "", tenantName: yield Supplier.get(this._options.tenantName) }))).socket;
10581
10972
  const ws = new StreamSocket2({ socket });
10582
10973
  if (!configuration) {
@@ -10627,7 +11018,7 @@ var Stream2 = class extends Stream {
10627
11018
  };
10628
11019
 
10629
11020
  // node_modules/@corti/sdk/dist/esm/api/resources/transcribe/client/Socket.mjs
10630
- var __awaiter27 = function(thisArg, _arguments, P2, generator) {
11021
+ var __awaiter29 = function(thisArg, _arguments, P2, generator) {
10631
11022
  function adopt(value) {
10632
11023
  return value instanceof P2 ? value : new P2(function(resolve) {
10633
11024
  resolve(value);
@@ -10773,7 +11164,7 @@ var TranscribeSocket = class {
10773
11164
  }
10774
11165
  /** Returns a promise that resolves when the websocket is open. */
10775
11166
  waitForOpen() {
10776
- return __awaiter27(this, void 0, void 0, function* () {
11167
+ return __awaiter29(this, void 0, void 0, function* () {
10777
11168
  if (this.socket.readyState === ReconnectingWebSocket.OPEN) {
10778
11169
  return this.socket;
10779
11170
  }
@@ -10803,7 +11194,7 @@ var TranscribeSocket = class {
10803
11194
  };
10804
11195
 
10805
11196
  // node_modules/@corti/sdk/dist/esm/api/resources/transcribe/client/Client.mjs
10806
- var __awaiter28 = function(thisArg, _arguments, P2, generator) {
11197
+ var __awaiter30 = function(thisArg, _arguments, P2, generator) {
10807
11198
  function adopt(value) {
10808
11199
  return value instanceof P2 ? value : new P2(function(resolve) {
10809
11200
  resolve(value);
@@ -10835,7 +11226,7 @@ var Transcribe = class {
10835
11226
  this._options = _options;
10836
11227
  }
10837
11228
  connect(args) {
10838
- return __awaiter28(this, void 0, void 0, function* () {
11229
+ return __awaiter30(this, void 0, void 0, function* () {
10839
11230
  var _a;
10840
11231
  const { tenantName, token, headers, debug, reconnectAttempts } = args;
10841
11232
  const _queryParams = {};
@@ -10853,7 +11244,7 @@ var Transcribe = class {
10853
11244
  });
10854
11245
  }
10855
11246
  _getAuthorizationHeader() {
10856
- return __awaiter28(this, void 0, void 0, function* () {
11247
+ return __awaiter30(this, void 0, void 0, function* () {
10857
11248
  const bearer = yield Supplier.get(this._options.token);
10858
11249
  if (bearer != null) {
10859
11250
  return `Bearer ${bearer}`;
@@ -10900,7 +11291,7 @@ var TranscribeSocket2 = class extends TranscribeSocket {
10900
11291
  };
10901
11292
 
10902
11293
  // node_modules/@corti/sdk/dist/esm/custom/CustomTranscribe.mjs
10903
- var __awaiter29 = function(thisArg, _arguments, P2, generator) {
11294
+ var __awaiter31 = function(thisArg, _arguments, P2, generator) {
10904
11295
  function adopt(value) {
10905
11296
  return value instanceof P2 ? value : new P2(function(resolve) {
10906
11297
  resolve(value);
@@ -10939,23 +11330,32 @@ var __rest4 = function(s8, e10) {
10939
11330
  return t7;
10940
11331
  };
10941
11332
  var Transcribe2 = class extends Transcribe {
11333
+ /** Patch: constructor accepts extended options so _options is correctly typed. */
11334
+ constructor(_options) {
11335
+ super(_options);
11336
+ this._options = _options;
11337
+ }
10942
11338
  /**
10943
- * Patch: use custom connect method to support passing _options parameters
10944
- * Added optional `proxy` parameter for direct WebSocket connection (proxy scenarios)
11339
+ * Patch: use custom connect method to support passing _options parameters.
11340
+ * Patch: optional proxy parameter for direct WebSocket connection (proxy scenarios).
11341
+ * Patch: use proxy path when proxy is passed or encodeHeadersAsWsProtocols is set.
11342
+ * Patch: protocols from getWsProtocols; queryParameters from proxy or empty.
10945
11343
  */
10946
11344
  connect() {
10947
11345
  const _super = Object.create(null, {
10948
11346
  connect: { get: () => super.connect }
10949
11347
  });
10950
- return __awaiter29(this, arguments, void 0, function* (_a = {}) {
10951
- var _b, _c;
11348
+ return __awaiter31(this, arguments, void 0, function* (_a = {}) {
11349
+ var _b, _c, _d, _e, _f;
10952
11350
  var { configuration, proxy } = _a, args = __rest4(_a, ["configuration", "proxy"]);
10953
- const socket = proxy ? new ReconnectingWebSocket({
10954
- url: proxy.url,
10955
- protocols: proxy.protocols || [],
10956
- queryParameters: proxy.queryParameters || {},
10957
- headers: args.headers || {},
10958
- options: { debug: (_b = args.debug) !== null && _b !== void 0 ? _b : false, maxRetries: (_c = args.reconnectAttempts) !== null && _c !== void 0 ? _c : 30 }
11351
+ const useProxyPath = proxy || this._options.encodeHeadersAsWsProtocols;
11352
+ const protocols = yield getWsProtocols(this._options, proxy === null || proxy === void 0 ? void 0 : proxy.protocols);
11353
+ const socket = useProxyPath ? new ReconnectingWebSocket({
11354
+ url: (proxy === null || proxy === void 0 ? void 0 : proxy.url) || url_exports.join((_b = yield Supplier.get(this._options["baseUrl"])) !== null && _b !== void 0 ? _b : (yield Supplier.get(this._options["environment"])).wss, "/transcribe"),
11355
+ protocols,
11356
+ queryParameters: (_c = proxy === null || proxy === void 0 ? void 0 : proxy.queryParameters) !== null && _c !== void 0 ? _c : {},
11357
+ headers: (_d = args.headers) !== null && _d !== void 0 ? _d : {},
11358
+ options: { debug: (_e = args.debug) !== null && _e !== void 0 ? _e : false, maxRetries: (_f = args.reconnectAttempts) !== null && _f !== void 0 ? _f : 30 }
10959
11359
  }) : (yield _super.connect.call(this, Object.assign(Object.assign({}, args), { token: (yield this._getAuthorizationHeader()) || "", tenantName: yield Supplier.get(this._options.tenantName) }))).socket;
10960
11360
  const ws = new TranscribeSocket2({ socket });
10961
11361
  if (!configuration) {
@@ -11006,10 +11406,10 @@ var Transcribe2 = class extends Transcribe {
11006
11406
  };
11007
11407
 
11008
11408
  // node_modules/@corti/sdk/dist/esm/version.mjs
11009
- var SDK_VERSION = "0.9.0";
11409
+ var SDK_VERSION = "0.10.1";
11010
11410
 
11011
11411
  // node_modules/@corti/sdk/dist/esm/custom/utils/resolveClientOptions.mjs
11012
- var __awaiter30 = function(thisArg, _arguments, P2, generator) {
11412
+ var __awaiter32 = function(thisArg, _arguments, P2, generator) {
11013
11413
  function adopt(value) {
11014
11414
  return value instanceof P2 ? value : new P2(function(resolve) {
11015
11415
  resolve(value);
@@ -11074,7 +11474,7 @@ function resolveClientOptions(options) {
11074
11474
  };
11075
11475
  }
11076
11476
  const auth = options.auth;
11077
- const tokenResponsePromise = (() => __awaiter30(this, void 0, void 0, function* () {
11477
+ const tokenResponsePromise = (() => __awaiter32(this, void 0, void 0, function* () {
11078
11478
  const tokenResponse = yield Supplier.get(auth.refreshAccessToken);
11079
11479
  const decoded = decodeToken2(tokenResponse.accessToken);
11080
11480
  if (!decoded && !options.baseUrl && typeof options.environment !== "object") {
@@ -11099,7 +11499,7 @@ function resolveClientOptions(options) {
11099
11499
  }
11100
11500
 
11101
11501
  // node_modules/@corti/sdk/dist/esm/custom/CortiClient.mjs
11102
- var __awaiter31 = function(thisArg, _arguments, P2, generator) {
11502
+ var __awaiter33 = function(thisArg, _arguments, P2, generator) {
11103
11503
  function adopt(value) {
11104
11504
  return value instanceof P2 ? value : new P2(function(resolve) {
11105
11505
  resolve(value);
@@ -11140,7 +11540,10 @@ var CortiClient = class {
11140
11540
  "User-Agent": `@corti/sdk/${SDK_VERSION}`,
11141
11541
  "X-Fern-Runtime": RUNTIME.type,
11142
11542
  "X-Fern-Runtime-Version": RUNTIME.version
11143
- }, _options === null || _options === void 0 ? void 0 : _options.headers), clientId: _options.auth && "clientId" in _options.auth ? _options.auth.clientId : void 0, clientSecret: _options.auth && "clientSecret" in _options.auth ? _options.auth.clientSecret : void 0, token: _options.auth && "accessToken" in _options.auth ? _options.auth.accessToken : void 0, tenantName, environment: getEnvironment(environment) });
11543
+ }, _options === null || _options === void 0 ? void 0 : _options.headers), clientId: _options.auth && "clientId" in _options.auth ? _options.auth.clientId : void 0, clientSecret: _options.auth && "clientSecret" in _options.auth ? _options.auth.clientSecret : void 0, token: _options.auth && "accessToken" in _options.auth ? _options.auth.accessToken : void 0, tenantName, environment: getEnvironment(environment), withCredentials: _options.withCredentials });
11544
+ if (_options.withCredentials !== void 0) {
11545
+ setDefaultWithCredentials(_options.withCredentials);
11546
+ }
11144
11547
  if (_options.auth) {
11145
11548
  this._oauthTokenProvider = "clientId" in _options.auth ? new OAuthTokenProvider({
11146
11549
  clientId: _options.auth.clientId,
@@ -11154,55 +11557,61 @@ var CortiClient = class {
11154
11557
  }
11155
11558
  get interactions() {
11156
11559
  var _a;
11157
- return (_a = this._interactions) !== null && _a !== void 0 ? _a : this._interactions = new Interactions(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11560
+ return (_a = this._interactions) !== null && _a !== void 0 ? _a : this._interactions = new Interactions(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11158
11561
  return yield this._oauthTokenProvider.getToken();
11159
11562
  }) : void 0 }));
11160
11563
  }
11161
11564
  get recordings() {
11162
11565
  var _a;
11163
- return (_a = this._recordings) !== null && _a !== void 0 ? _a : this._recordings = new Recordings(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11566
+ return (_a = this._recordings) !== null && _a !== void 0 ? _a : this._recordings = new Recordings(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11164
11567
  return yield this._oauthTokenProvider.getToken();
11165
11568
  }) : void 0 }));
11166
11569
  }
11167
11570
  get transcripts() {
11168
11571
  var _a;
11169
- return (_a = this._transcripts) !== null && _a !== void 0 ? _a : this._transcripts = new Transcripts(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11572
+ return (_a = this._transcripts) !== null && _a !== void 0 ? _a : this._transcripts = new Transcripts(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11170
11573
  return yield this._oauthTokenProvider.getToken();
11171
11574
  }) : void 0 }));
11172
11575
  }
11173
11576
  get facts() {
11174
11577
  var _a;
11175
- return (_a = this._facts) !== null && _a !== void 0 ? _a : this._facts = new Facts(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11578
+ return (_a = this._facts) !== null && _a !== void 0 ? _a : this._facts = new Facts(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11176
11579
  return yield this._oauthTokenProvider.getToken();
11177
11580
  }) : void 0 }));
11178
11581
  }
11179
11582
  get documents() {
11180
11583
  var _a;
11181
- return (_a = this._documents) !== null && _a !== void 0 ? _a : this._documents = new Documents(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11584
+ return (_a = this._documents) !== null && _a !== void 0 ? _a : this._documents = new Documents(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11182
11585
  return yield this._oauthTokenProvider.getToken();
11183
11586
  }) : void 0 }));
11184
11587
  }
11185
11588
  get templates() {
11186
11589
  var _a;
11187
- return (_a = this._templates) !== null && _a !== void 0 ? _a : this._templates = new Templates(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11590
+ return (_a = this._templates) !== null && _a !== void 0 ? _a : this._templates = new Templates(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11188
11591
  return yield this._oauthTokenProvider.getToken();
11189
11592
  }) : void 0 }));
11190
11593
  }
11191
11594
  get agents() {
11192
11595
  var _a;
11193
- return (_a = this._agents) !== null && _a !== void 0 ? _a : this._agents = new Agents(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11596
+ return (_a = this._agents) !== null && _a !== void 0 ? _a : this._agents = new Agents(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11194
11597
  return yield this._oauthTokenProvider.getToken();
11195
11598
  }) : void 0 }));
11196
11599
  }
11197
11600
  get stream() {
11198
11601
  var _a;
11199
- return (_a = this._stream) !== null && _a !== void 0 ? _a : this._stream = new Stream2(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11602
+ return (_a = this._stream) !== null && _a !== void 0 ? _a : this._stream = new Stream2(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11200
11603
  return yield this._oauthTokenProvider.getToken();
11201
11604
  }) : void 0 }));
11202
11605
  }
11203
11606
  get transcribe() {
11204
11607
  var _a;
11205
- return (_a = this._transcribe) !== null && _a !== void 0 ? _a : this._transcribe = new Transcribe2(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter31(this, void 0, void 0, function* () {
11608
+ return (_a = this._transcribe) !== null && _a !== void 0 ? _a : this._transcribe = new Transcribe2(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11609
+ return yield this._oauthTokenProvider.getToken();
11610
+ }) : void 0 }));
11611
+ }
11612
+ get codes() {
11613
+ var _a;
11614
+ return (_a = this._codes) !== null && _a !== void 0 ? _a : this._codes = new Codes(Object.assign(Object.assign({}, this._options), { token: this._oauthTokenProvider ? () => __awaiter33(this, void 0, void 0, function* () {
11206
11615
  return yield this._oauthTokenProvider.getToken();
11207
11616
  }) : void 0 }));
11208
11617
  }
@@ -11282,14 +11691,17 @@ var _DictationController_callbacks;
11282
11691
  var _DictationController_lastDictationConfig;
11283
11692
  var _DictationController_lastSocketUrl;
11284
11693
  var _DictationController_lastSocketProxy;
11285
- var _DictationController_messageBuffer;
11286
- var _DictationController_connectionPromise;
11694
+ var _DictationController_outboundQueue;
11695
+ var _DictationController_socketReady;
11696
+ var _DictationController_connectingPromise;
11697
+ var _DictationController_connectionGeneration;
11698
+ var _DictationController_isConnecting;
11287
11699
  var _DictationController_configHasChanged;
11288
- var _DictationController_establishConnection;
11289
- var _DictationController_flushMessageBuffer;
11700
+ var _DictationController_doConnect;
11290
11701
  var _DictationController_connectProxy;
11291
11702
  var _DictationController_connectAuth;
11292
11703
  var _DictationController_setupWebSocketHandlers;
11704
+ var _DictationController_drain;
11293
11705
  var DictationController = class {
11294
11706
  constructor(host) {
11295
11707
  _DictationController_instances.add(this);
@@ -11300,23 +11712,21 @@ var DictationController = class {
11300
11712
  _DictationController_lastDictationConfig.set(this, null);
11301
11713
  _DictationController_lastSocketUrl.set(this, void 0);
11302
11714
  _DictationController_lastSocketProxy.set(this, void 0);
11303
- _DictationController_messageBuffer.set(this, []);
11304
- _DictationController_connectionPromise.set(this, null);
11715
+ _DictationController_outboundQueue.set(this, []);
11716
+ _DictationController_socketReady.set(this, false);
11717
+ _DictationController_connectingPromise.set(this, null);
11718
+ _DictationController_connectionGeneration.set(this, 0);
11719
+ _DictationController_isConnecting.set(this, false);
11305
11720
  this.mediaRecorderHandler = (data) => {
11306
- if (__classPrivateFieldGet4(this, _DictationController_connectionPromise, "f")) {
11307
- console.log("[DictationController] Buffering audio chunk (connection pending):", data.size);
11308
- __classPrivateFieldGet4(this, _DictationController_messageBuffer, "f").push({ data, type: "audio" });
11721
+ if (__classPrivateFieldGet4(this, _DictationController_socketReady, "f") && this.isConnectionOpen()) {
11722
+ __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.send(data);
11723
+ __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", {
11724
+ size: data.size,
11725
+ type: "audio"
11726
+ });
11309
11727
  return;
11310
11728
  }
11311
- console.log("[DictationController] Sending audio chunk directly:", {
11312
- size: data.size,
11313
- socketState: __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.readyState
11314
- });
11315
- __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.sendAudio(data);
11316
- __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", {
11317
- size: data.size,
11318
- type: "audio"
11319
- });
11729
+ __classPrivateFieldGet4(this, _DictationController_outboundQueue, "f").push(data);
11320
11730
  };
11321
11731
  this.host = host;
11322
11732
  host.addController(this);
@@ -11325,50 +11735,39 @@ var DictationController = class {
11325
11735
  this.cleanup();
11326
11736
  }
11327
11737
  async connect(dictationConfig = DEFAULT_DICTATION_CONFIG, callbacks = {}) {
11328
- const newConnection = __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_configHasChanged).call(this) || !this.isConnectionOpen();
11329
- if (newConnection) {
11330
- this.cleanup();
11331
- if (__classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.readyState === WebSocket.OPEN) {
11332
- throw new Error("Already connected. Disconnect before reconnecting.");
11333
- }
11334
- __classPrivateFieldSet3(this, _DictationController_connectionPromise, __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_establishConnection).call(this, dictationConfig), "f");
11335
- await __classPrivateFieldGet4(this, _DictationController_connectionPromise, "f");
11336
- __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", {
11337
- configuration: dictationConfig,
11338
- type: "config"
11339
- });
11340
- __classPrivateFieldSet3(this, _DictationController_lastDictationConfig, this.host._dictationConfig || null, "f");
11341
- __classPrivateFieldSet3(this, _DictationController_lastSocketUrl, this.host._socketUrl, "f");
11342
- __classPrivateFieldSet3(this, _DictationController_lastSocketProxy, this.host._socketProxy, "f");
11738
+ if (__classPrivateFieldGet4(this, _DictationController_connectingPromise, "f") && !__classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_configHasChanged).call(this)) {
11739
+ return __classPrivateFieldGet4(this, _DictationController_connectingPromise, "f");
11343
11740
  }
11344
- __classPrivateFieldSet3(this, _DictationController_callbacks, callbacks, "f");
11345
- __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_setupWebSocketHandlers).call(this, callbacks);
11346
- return newConnection;
11741
+ __classPrivateFieldSet3(this, _DictationController_isConnecting, true, "f");
11742
+ __classPrivateFieldSet3(this, _DictationController_connectingPromise, __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_doConnect).call(this, dictationConfig, callbacks).finally(() => {
11743
+ __classPrivateFieldSet3(this, _DictationController_isConnecting, false, "f");
11744
+ __classPrivateFieldSet3(this, _DictationController_connectingPromise, null, "f");
11745
+ }), "f");
11746
+ return __classPrivateFieldGet4(this, _DictationController_connectingPromise, "f");
11347
11747
  }
11348
11748
  async pause() {
11349
- console.log("[DictationController] pause() called", {
11350
- connectionPending: !!__classPrivateFieldGet4(this, _DictationController_connectionPromise, "f"),
11351
- socketState: __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.readyState
11352
- });
11353
- if (__classPrivateFieldGet4(this, _DictationController_connectionPromise, "f")) {
11354
- console.log("[DictationController] Buffering flush (connection pending)");
11355
- __classPrivateFieldGet4(this, _DictationController_messageBuffer, "f").push({ data: { type: "flush" }, type: "flush" });
11749
+ if (__classPrivateFieldGet4(this, _DictationController_socketReady, "f") && this.isConnectionOpen()) {
11750
+ __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.send(JSON.stringify({ type: "flush" }));
11751
+ __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", { type: "flush" });
11356
11752
  return;
11357
11753
  }
11358
- console.log("[DictationController] Sending flush", {
11359
- socketState: __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.readyState
11360
- });
11361
- __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.sendFlush({ type: "flush" });
11362
- __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", { type: "flush" });
11754
+ __classPrivateFieldGet4(this, _DictationController_outboundQueue, "f").push({ type: "flush" });
11363
11755
  }
11364
11756
  isConnectionOpen() {
11365
11757
  return __classPrivateFieldGet4(this, _DictationController_webSocket, "f") !== null && (__classPrivateFieldGet4(this, _DictationController_webSocket, "f").readyState === WebSocket.OPEN || __classPrivateFieldGet4(this, _DictationController_webSocket, "f").readyState === WebSocket.CONNECTING);
11366
11758
  }
11759
+ isConnecting() {
11760
+ return __classPrivateFieldGet4(this, _DictationController_isConnecting, "f");
11761
+ }
11762
+ async waitForConnection() {
11763
+ await __classPrivateFieldGet4(this, _DictationController_connectingPromise, "f");
11764
+ }
11367
11765
  async closeConnection(onClose) {
11368
11766
  await new Promise((resolve, reject) => {
11369
11767
  const oldSocket = __classPrivateFieldGet4(this, _DictationController_webSocket, "f");
11370
11768
  __classPrivateFieldSet3(this, _DictationController_webSocket, null, "f");
11371
- if (!oldSocket || oldSocket.readyState !== WebSocket.OPEN) {
11769
+ if (!oldSocket || oldSocket.readyState !== WebSocket.OPEN && oldSocket.readyState !== WebSocket.CONNECTING) {
11770
+ __classPrivateFieldSet3(this, _DictationController_socketReady, false, "f");
11372
11771
  resolve();
11373
11772
  return;
11374
11773
  }
@@ -11382,11 +11781,18 @@ var DictationController = class {
11382
11781
  }
11383
11782
  resolve();
11384
11783
  });
11784
+ const wasReady = __classPrivateFieldGet4(this, _DictationController_socketReady, "f");
11785
+ __classPrivateFieldSet3(this, _DictationController_socketReady, false, "f");
11385
11786
  oldSocket.on("message", (message) => {
11386
11787
  __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("received", message);
11387
11788
  if (__classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onMessage) {
11388
11789
  __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onMessage(message);
11389
11790
  }
11791
+ if (!wasReady && message.type === "CONFIG_ACCEPTED") {
11792
+ oldSocket.sendEnd({ type: "end" });
11793
+ __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", { type: "end" });
11794
+ return;
11795
+ }
11390
11796
  if (message.type === "ended") {
11391
11797
  if (__classPrivateFieldGet4(this, _DictationController_closeTimeout, "f")) {
11392
11798
  clearTimeout(__classPrivateFieldGet4(this, _DictationController_closeTimeout, "f"));
@@ -11396,8 +11802,10 @@ var DictationController = class {
11396
11802
  return;
11397
11803
  }
11398
11804
  });
11399
- oldSocket.sendEnd({ type: "end" });
11400
- __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", { type: "end" });
11805
+ if (wasReady) {
11806
+ oldSocket.sendEnd({ type: "end" });
11807
+ __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", { type: "end" });
11808
+ }
11401
11809
  __classPrivateFieldSet3(this, _DictationController_closeTimeout, window.setTimeout(() => {
11402
11810
  reject(new Error("Connection close timeout"));
11403
11811
  if (oldSocket?.readyState === WebSocket.OPEN) {
@@ -11407,72 +11815,55 @@ var DictationController = class {
11407
11815
  });
11408
11816
  }
11409
11817
  cleanup() {
11818
+ var _a;
11819
+ __classPrivateFieldSet3(this, _DictationController_connectionGeneration, (_a = __classPrivateFieldGet4(this, _DictationController_connectionGeneration, "f"), _a++, _a), "f");
11820
+ __classPrivateFieldSet3(this, _DictationController_socketReady, false, "f");
11410
11821
  if (__classPrivateFieldGet4(this, _DictationController_closeTimeout, "f")) {
11411
11822
  clearTimeout(__classPrivateFieldGet4(this, _DictationController_closeTimeout, "f"));
11412
11823
  __classPrivateFieldSet3(this, _DictationController_closeTimeout, void 0, "f");
11413
11824
  }
11414
- if (__classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.readyState === WebSocket.OPEN) {
11415
- __classPrivateFieldGet4(this, _DictationController_webSocket, "f").close();
11825
+ if (this.isConnectionOpen()) {
11826
+ __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.close();
11416
11827
  }
11417
11828
  __classPrivateFieldSet3(this, _DictationController_webSocket, null, "f");
11418
11829
  __classPrivateFieldSet3(this, _DictationController_cortiClient, null, "f");
11419
11830
  __classPrivateFieldSet3(this, _DictationController_lastDictationConfig, null, "f");
11420
11831
  __classPrivateFieldSet3(this, _DictationController_lastSocketUrl, void 0, "f");
11421
11832
  __classPrivateFieldSet3(this, _DictationController_lastSocketProxy, void 0, "f");
11422
- __classPrivateFieldSet3(this, _DictationController_messageBuffer, [], "f");
11423
- __classPrivateFieldSet3(this, _DictationController_connectionPromise, null, "f");
11833
+ if (__classPrivateFieldGet4(this, _DictationController_outboundQueue, "f").length > 0) {
11834
+ this.host.dispatchEvent(errorEvent(`${__classPrivateFieldGet4(this, _DictationController_outboundQueue, "f").length} unsent audio message(s) were discarded because the configuration changed before the connection was closed`));
11835
+ }
11836
+ __classPrivateFieldSet3(this, _DictationController_outboundQueue, [], "f");
11424
11837
  }
11425
11838
  };
11426
- _DictationController_cortiClient = /* @__PURE__ */ new WeakMap(), _DictationController_webSocket = /* @__PURE__ */ new WeakMap(), _DictationController_closeTimeout = /* @__PURE__ */ new WeakMap(), _DictationController_callbacks = /* @__PURE__ */ new WeakMap(), _DictationController_lastDictationConfig = /* @__PURE__ */ new WeakMap(), _DictationController_lastSocketUrl = /* @__PURE__ */ new WeakMap(), _DictationController_lastSocketProxy = /* @__PURE__ */ new WeakMap(), _DictationController_messageBuffer = /* @__PURE__ */ new WeakMap(), _DictationController_connectionPromise = /* @__PURE__ */ new WeakMap(), _DictationController_instances = /* @__PURE__ */ new WeakSet(), _DictationController_configHasChanged = function _DictationController_configHasChanged2() {
11839
+ _DictationController_cortiClient = /* @__PURE__ */ new WeakMap(), _DictationController_webSocket = /* @__PURE__ */ new WeakMap(), _DictationController_closeTimeout = /* @__PURE__ */ new WeakMap(), _DictationController_callbacks = /* @__PURE__ */ new WeakMap(), _DictationController_lastDictationConfig = /* @__PURE__ */ new WeakMap(), _DictationController_lastSocketUrl = /* @__PURE__ */ new WeakMap(), _DictationController_lastSocketProxy = /* @__PURE__ */ new WeakMap(), _DictationController_outboundQueue = /* @__PURE__ */ new WeakMap(), _DictationController_socketReady = /* @__PURE__ */ new WeakMap(), _DictationController_connectingPromise = /* @__PURE__ */ new WeakMap(), _DictationController_connectionGeneration = /* @__PURE__ */ new WeakMap(), _DictationController_isConnecting = /* @__PURE__ */ new WeakMap(), _DictationController_instances = /* @__PURE__ */ new WeakSet(), _DictationController_configHasChanged = function _DictationController_configHasChanged2() {
11427
11840
  return JSON.stringify(this.host._dictationConfig) !== JSON.stringify(__classPrivateFieldGet4(this, _DictationController_lastDictationConfig, "f")) || this.host._socketUrl !== __classPrivateFieldGet4(this, _DictationController_lastSocketUrl, "f") || JSON.stringify(this.host._socketProxy) !== JSON.stringify(__classPrivateFieldGet4(this, _DictationController_lastSocketProxy, "f"));
11428
- }, _DictationController_establishConnection = async function _DictationController_establishConnection2(dictationConfig) {
11429
- try {
11430
- console.log("[DictationController] Delay complete, connecting to WebSocket...");
11431
- __classPrivateFieldSet3(this, _DictationController_webSocket, this.host._socketUrl || this.host._socketProxy ? await __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_connectProxy).call(this, dictationConfig) : await __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_connectAuth).call(this, dictationConfig), "f");
11432
- console.log("[DictationController] Starting connection establishment (10s delay)...");
11433
- await new Promise((resolve) => setTimeout(resolve, 1e4));
11434
- console.log("[DictationController] WebSocket connected, flushing message buffer...", {
11435
- bufferedMessages: __classPrivateFieldGet4(this, _DictationController_messageBuffer, "f").length,
11436
- socketState: __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.readyState
11437
- });
11438
- __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_flushMessageBuffer).call(this);
11439
- } catch (error) {
11440
- console.error("[DictationController] Connection establishment failed:", error);
11441
- __classPrivateFieldSet3(this, _DictationController_messageBuffer, [], "f");
11442
- throw error;
11443
- } finally {
11444
- console.log("[DictationController] Connection promise cleared");
11445
- __classPrivateFieldSet3(this, _DictationController_connectionPromise, null, "f");
11446
- }
11447
- }, _DictationController_flushMessageBuffer = function _DictationController_flushMessageBuffer2() {
11448
- console.log("[DictationController] Flushing buffer:", {
11449
- messages: __classPrivateFieldGet4(this, _DictationController_messageBuffer, "f").length,
11450
- socketState: __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.readyState
11451
- });
11452
- for (const message of __classPrivateFieldGet4(this, _DictationController_messageBuffer, "f")) {
11453
- switch (message.type) {
11454
- case "audio":
11455
- console.log("[DictationController] Sending buffered audio chunk:", message.data.size);
11456
- __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.sendAudio(message.data);
11457
- __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", {
11458
- size: message.data.size,
11459
- type: "audio"
11460
- });
11461
- break;
11462
- case "flush":
11463
- console.log("[DictationController] Sending buffered flush");
11464
- __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.sendFlush(message.data);
11465
- __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", message.data);
11466
- break;
11467
- case "end":
11468
- console.log("[DictationController] Sending buffered end");
11469
- __classPrivateFieldGet4(this, _DictationController_webSocket, "f")?.sendEnd(message.data);
11470
- __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", message.data);
11471
- break;
11472
- }
11473
- }
11474
- console.log("[DictationController] Buffer cleared");
11475
- __classPrivateFieldSet3(this, _DictationController_messageBuffer, [], "f");
11841
+ }, _DictationController_doConnect = async function _DictationController_doConnect2(dictationConfig, callbacks) {
11842
+ const newConnection = __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_configHasChanged).call(this) || !this.isConnectionOpen();
11843
+ if (newConnection) {
11844
+ this.cleanup();
11845
+ __classPrivateFieldSet3(this, _DictationController_lastDictationConfig, this.host._dictationConfig || null, "f");
11846
+ __classPrivateFieldSet3(this, _DictationController_lastSocketUrl, this.host._socketUrl, "f");
11847
+ __classPrivateFieldSet3(this, _DictationController_lastSocketProxy, this.host._socketProxy, "f");
11848
+ const generation = __classPrivateFieldGet4(this, _DictationController_connectionGeneration, "f");
11849
+ const socket = this.host._socketUrl || this.host._socketProxy ? await __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_connectProxy).call(this, dictationConfig) : await __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_connectAuth).call(this, dictationConfig);
11850
+ if (__classPrivateFieldGet4(this, _DictationController_connectionGeneration, "f") !== generation) {
11851
+ socket.close();
11852
+ return "superseded";
11853
+ }
11854
+ __classPrivateFieldSet3(this, _DictationController_webSocket, socket, "f");
11855
+ __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", {
11856
+ configuration: dictationConfig,
11857
+ type: "config"
11858
+ });
11859
+ }
11860
+ __classPrivateFieldSet3(this, _DictationController_callbacks, callbacks, "f");
11861
+ __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_setupWebSocketHandlers).call(this, callbacks);
11862
+ if (!newConnection && this.isConnectionOpen()) {
11863
+ __classPrivateFieldSet3(this, _DictationController_socketReady, true, "f");
11864
+ __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_drain).call(this);
11865
+ }
11866
+ return newConnection;
11476
11867
  }, _DictationController_connectProxy = async function _DictationController_connectProxy2(dictationConfig) {
11477
11868
  const proxyOptions = this.host._socketProxy || {
11478
11869
  url: this.host._socketUrl || ""
@@ -11507,21 +11898,49 @@ _DictationController_cortiClient = /* @__PURE__ */ new WeakMap(), _DictationCont
11507
11898
  throw new Error("WebSocket not initialized");
11508
11899
  }
11509
11900
  __classPrivateFieldGet4(this, _DictationController_webSocket, "f").on("message", (message) => {
11901
+ if (message.type === "CONFIG_ACCEPTED") {
11902
+ __classPrivateFieldSet3(this, _DictationController_socketReady, true, "f");
11903
+ __classPrivateFieldGet4(this, _DictationController_instances, "m", _DictationController_drain).call(this);
11904
+ }
11510
11905
  callbacks.onNetworkActivity?.("received", message);
11511
11906
  if (callbacks.onMessage) {
11512
11907
  callbacks.onMessage(message);
11513
11908
  }
11514
11909
  });
11515
11910
  __classPrivateFieldGet4(this, _DictationController_webSocket, "f").on("error", (event) => {
11911
+ __classPrivateFieldSet3(this, _DictationController_socketReady, false, "f");
11516
11912
  if (callbacks.onError) {
11517
11913
  callbacks.onError(event);
11518
11914
  }
11519
11915
  });
11520
11916
  __classPrivateFieldGet4(this, _DictationController_webSocket, "f").on("close", (event) => {
11917
+ __classPrivateFieldSet3(this, _DictationController_socketReady, false, "f");
11521
11918
  if (callbacks.onClose) {
11522
11919
  callbacks.onClose(event);
11523
11920
  }
11524
11921
  });
11922
+ }, _DictationController_drain = function _DictationController_drain2() {
11923
+ if (!__classPrivateFieldGet4(this, _DictationController_socketReady, "f") || !this.isConnectionOpen() || __classPrivateFieldGet4(this, _DictationController_outboundQueue, "f").length === 0) {
11924
+ return;
11925
+ }
11926
+ while (__classPrivateFieldGet4(this, _DictationController_outboundQueue, "f").length > 0 && this.isConnectionOpen()) {
11927
+ const item = __classPrivateFieldGet4(this, _DictationController_outboundQueue, "f").shift();
11928
+ if (item === void 0) {
11929
+ break;
11930
+ }
11931
+ if (item instanceof Blob) {
11932
+ __classPrivateFieldGet4(this, _DictationController_webSocket, "f").send(item);
11933
+ __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", {
11934
+ size: item.size,
11935
+ type: "audio"
11936
+ });
11937
+ continue;
11938
+ }
11939
+ __classPrivateFieldGet4(this, _DictationController_webSocket, "f").send(JSON.stringify(item));
11940
+ __classPrivateFieldGet4(this, _DictationController_callbacks, "f")?.onNetworkActivity?.("sent", {
11941
+ type: item.type
11942
+ });
11943
+ }
11525
11944
  };
11526
11945
 
11527
11946
  // dist/utils/keybinding.js
@@ -11755,10 +12174,10 @@ var MediaController = class {
11755
12174
  hostDisconnected() {
11756
12175
  this.cleanup();
11757
12176
  }
11758
- async initialize(dataHandler, onTrackEnded) {
12177
+ async initialize(onTrackEnded, dataHandler) {
11759
12178
  await this.cleanup();
11760
- __classPrivateFieldSet5(this, _MediaController_dataHandler, dataHandler, "f");
11761
12179
  __classPrivateFieldSet5(this, _MediaController_onTrackEnded, onTrackEnded, "f");
12180
+ __classPrivateFieldSet5(this, _MediaController_dataHandler, dataHandler, "f");
11762
12181
  __classPrivateFieldSet5(this, _MediaController_mediaStream, await getMediaStream(this.host._selectedDevice?.deviceId, this.host._debug_displayAudio), "f");
11763
12182
  __classPrivateFieldGet6(this, _MediaController_mediaStream, "f").getTracks().forEach((track) => {
11764
12183
  track.addEventListener("ended", () => {
@@ -12212,16 +12631,6 @@ var DictationRecordingButton = class DictationRecordingButton2 extends i4 {
12212
12631
  _DictationRecordingButton_connection.set(this, "CLOSED");
12213
12632
  _DictationRecordingButton_handleWebSocketMessage.set(this, (message) => {
12214
12633
  switch (message.type) {
12215
- case "CONFIG_ACCEPTED":
12216
- console.log("[RecordingButton] CONFIG_ACCEPTED received", {
12217
- recordingState: this._recordingState,
12218
- willSetProcessing: this._recordingState === "initializing"
12219
- });
12220
- if (this._recordingState === "initializing") {
12221
- __classPrivateFieldSet6(this, _DictationRecordingButton_processing, true, "f");
12222
- __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "recording");
12223
- }
12224
- break;
12225
12634
  case "CONFIG_DENIED":
12226
12635
  this.dispatchEvent(errorEvent(`Config denied: ${message.reason ?? "Unknown reason"}`));
12227
12636
  __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_handleStop).call(this);
@@ -12252,13 +12661,13 @@ var DictationRecordingButton = class DictationRecordingButton2 extends i4 {
12252
12661
  }
12253
12662
  });
12254
12663
  _DictationRecordingButton_handleWebSocketError.set(this, (error) => {
12255
- this.dispatchEvent(errorEvent(`Socket error: ${error.message}`));
12664
+ this.dispatchEvent(errorEvent("Socket error: " + error.message));
12256
12665
  __classPrivateFieldSet6(this, _DictationRecordingButton_processing, false, "f");
12257
12666
  __classPrivateFieldSet6(this, _DictationRecordingButton_connection, "CLOSED", "f");
12258
12667
  __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_handleStop).call(this);
12259
12668
  });
12260
12669
  _DictationRecordingButton_handleWebSocketClose.set(this, (event) => {
12261
- if (__classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").isConnectionOpen()) {
12670
+ if (__classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").isConnectionOpen() || __classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").isConnecting()) {
12262
12671
  return;
12263
12672
  }
12264
12673
  __classPrivateFieldSet6(this, _DictationRecordingButton_processing, false, "f");
@@ -12306,7 +12715,7 @@ var DictationRecordingButton = class DictationRecordingButton2 extends i4 {
12306
12715
  }
12307
12716
  try {
12308
12717
  __classPrivateFieldSet6(this, _DictationRecordingButton_connection, "CONNECTING", "f");
12309
- __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "stopped");
12718
+ __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, this._recordingState);
12310
12719
  await __classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").connect(this._dictationConfig, {
12311
12720
  onClose: __classPrivateFieldGet7(this, _DictationRecordingButton_handleWebSocketClose, "f"),
12312
12721
  onError: __classPrivateFieldGet7(this, _DictationRecordingButton_handleWebSocketError, "f"),
@@ -12316,7 +12725,7 @@ var DictationRecordingButton = class DictationRecordingButton2 extends i4 {
12316
12725
  }
12317
12726
  });
12318
12727
  __classPrivateFieldSet6(this, _DictationRecordingButton_connection, "OPEN", "f");
12319
- __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "stopped");
12728
+ __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, this._recordingState);
12320
12729
  } catch (error) {
12321
12730
  __classPrivateFieldSet6(this, _DictationRecordingButton_connection, "CLOSED", "f");
12322
12731
  this.dispatchEvent(errorEvent(error));
@@ -12326,6 +12735,9 @@ var DictationRecordingButton = class DictationRecordingButton2 extends i4 {
12326
12735
  if (this._recordingState !== "stopped" || __classPrivateFieldGet7(this, _DictationRecordingButton_processing, "f")) {
12327
12736
  return;
12328
12737
  }
12738
+ if (__classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").isConnecting()) {
12739
+ await __classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").waitForConnection();
12740
+ }
12329
12741
  if (!__classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").isConnectionOpen()) {
12330
12742
  __classPrivateFieldSet6(this, _DictationRecordingButton_connection, "CLOSED", "f");
12331
12743
  __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "stopped");
@@ -12382,26 +12794,23 @@ _DictationRecordingButton_dispatchRecordingStateChanged = function _DictationRec
12382
12794
  }));
12383
12795
  };
12384
12796
  _DictationRecordingButton_handleStart = async function _DictationRecordingButton_handleStart2() {
12385
- console.log("[RecordingButton] handleStart() called");
12386
12797
  __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "initializing");
12387
12798
  try {
12388
- console.log("[RecordingButton] Initializing media controller...");
12389
- await __classPrivateFieldGet7(this, _DictationRecordingButton_mediaController, "f").initialize(__classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").mediaRecorderHandler, () => {
12799
+ await __classPrivateFieldGet7(this, _DictationRecordingButton_mediaController, "f").initialize(() => {
12390
12800
  if (this._recordingState === "recording") {
12391
12801
  this.dispatchEvent(errorEvent("Recording device access was lost."));
12392
12802
  __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_handleStop).call(this);
12393
12803
  }
12394
- });
12395
- console.log("[RecordingButton] Starting MediaRecorder...");
12804
+ }, __classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").mediaRecorderHandler);
12396
12805
  __classPrivateFieldGet7(this, _DictationRecordingButton_mediaController, "f").mediaRecorder?.start(AUDIO_CHUNK_INTERVAL_MS);
12397
12806
  __classPrivateFieldGet7(this, _DictationRecordingButton_mediaController, "f").startAudioLevelMonitoring((level) => {
12398
12807
  this.dispatchEvent(audioLevelChangedEvent(level));
12399
12808
  });
12809
+ __classPrivateFieldSet6(this, _DictationRecordingButton_processing, true, "f");
12400
12810
  if (__classPrivateFieldGet7(this, _DictationRecordingButton_connection, "f") !== "OPEN") {
12401
12811
  __classPrivateFieldSet6(this, _DictationRecordingButton_connection, "CONNECTING", "f");
12402
12812
  }
12403
12813
  __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "recording");
12404
- console.log("[RecordingButton] Connecting to WebSocket...");
12405
12814
  const isNewConnection = await __classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").connect(this._dictationConfig, {
12406
12815
  onClose: __classPrivateFieldGet7(this, _DictationRecordingButton_handleWebSocketClose, "f"),
12407
12816
  onError: __classPrivateFieldGet7(this, _DictationRecordingButton_handleWebSocketError, "f"),
@@ -12410,34 +12819,25 @@ _DictationRecordingButton_handleStart = async function _DictationRecordingButton
12410
12819
  this.dispatchEvent(networkActivityEvent(direction, data));
12411
12820
  }
12412
12821
  });
12413
- console.log("[RecordingButton] Connection established", { isNewConnection });
12414
- if (!isNewConnection) {
12415
- __classPrivateFieldSet6(this, _DictationRecordingButton_processing, true, "f");
12822
+ if (isNewConnection === "superseded") {
12823
+ return;
12416
12824
  }
12417
12825
  __classPrivateFieldSet6(this, _DictationRecordingButton_connection, "OPEN", "f");
12418
- __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "recording");
12826
+ __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, this._recordingState);
12419
12827
  } catch (error) {
12420
- console.error("[RecordingButton] Error in handleStart:", error);
12421
12828
  this.dispatchEvent(errorEvent(error));
12422
12829
  await __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_handleStop).call(this);
12423
12830
  }
12424
12831
  };
12425
12832
  _DictationRecordingButton_handleStop = async function _DictationRecordingButton_handleStop2() {
12426
- console.log("[RecordingButton] handleStop() called");
12427
12833
  __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "stopping");
12428
12834
  try {
12429
- console.log("[RecordingButton] Stopping audio level monitoring...");
12430
12835
  __classPrivateFieldGet7(this, _DictationRecordingButton_mediaController, "f").stopAudioLevelMonitoring();
12431
- console.log("[RecordingButton] Stopping media recorder...");
12432
12836
  await __classPrivateFieldGet7(this, _DictationRecordingButton_mediaController, "f").stopRecording();
12433
12837
  __classPrivateFieldGet7(this, _DictationRecordingButton_instances, "m", _DictationRecordingButton_dispatchRecordingStateChanged).call(this, "stopped");
12434
- console.log("[RecordingButton] Calling dictationController.pause()...");
12435
12838
  await __classPrivateFieldGet7(this, _DictationRecordingButton_dictationController, "f").pause();
12436
- console.log("[RecordingButton] Cleaning up media controller...");
12437
12839
  await __classPrivateFieldGet7(this, _DictationRecordingButton_mediaController, "f").cleanup();
12438
- console.log("[RecordingButton] Stop complete");
12439
12840
  } catch (error) {
12440
- console.error("[RecordingButton] Error in handleStop:", error);
12441
12841
  this.dispatchEvent(errorEvent(error));
12442
12842
  }
12443
12843
  };