@tstdl/base 0.92.145 → 0.92.147

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/ai/ai-file.service.d.ts +29 -1
  2. package/ai/ai-file.service.js +66 -23
  3. package/ai/ai-session.d.ts +28 -1
  4. package/ai/ai-session.js +27 -0
  5. package/ai/ai.service.d.ts +89 -5
  6. package/ai/ai.service.js +130 -27
  7. package/ai/functions.d.ts +7 -1
  8. package/ai/functions.js +7 -1
  9. package/ai/module.d.ts +8 -0
  10. package/ai/module.js +4 -0
  11. package/ai/types.d.ts +115 -2
  12. package/ai/types.js +16 -0
  13. package/api/client/client.d.ts +1 -1
  14. package/api/client/client.js +1 -1
  15. package/api/default-error-handlers.d.ts +1 -1
  16. package/api/index.d.ts +1 -9
  17. package/api/index.js +1 -9
  18. package/api/response.d.ts +1 -1
  19. package/api/server/api-controller.d.ts +1 -1
  20. package/api/server/error-handler.d.ts +1 -1
  21. package/api/server/gateway.d.ts +1 -5
  22. package/api/server/gateway.js +0 -4
  23. package/api/server/middlewares/catch-error.middleware.d.ts +1 -1
  24. package/api/server/module.d.ts +1 -1
  25. package/api/types.d.ts +1 -1
  26. package/application/application.d.ts +1 -1
  27. package/authentication/authentication.api.d.ts +36 -1
  28. package/authentication/authentication.api.js +28 -0
  29. package/authentication/client/api.client.d.ts +14 -1
  30. package/authentication/client/api.client.js +13 -0
  31. package/authentication/client/authentication.service.d.ts +104 -1
  32. package/authentication/client/authentication.service.js +103 -0
  33. package/authentication/client/http-client.middleware.d.ts +5 -0
  34. package/authentication/client/http-client.middleware.js +6 -2
  35. package/authentication/client/module.d.ts +20 -1
  36. package/authentication/client/module.js +6 -1
  37. package/authentication/client/tokens.d.ts +6 -0
  38. package/authentication/client/tokens.js +6 -0
  39. package/authentication/models/authentication-credentials.model.d.ts +6 -0
  40. package/authentication/models/authentication-credentials.model.js +6 -0
  41. package/authentication/models/authentication-session.model.d.ts +6 -0
  42. package/authentication/models/authentication-session.model.js +6 -0
  43. package/authentication/models/init-secret-reset-data.model.d.ts +10 -1
  44. package/authentication/models/init-secret-reset-data.model.js +10 -1
  45. package/authentication/models/token-payload-base.model.d.ts +24 -4
  46. package/authentication/models/token-payload-base.model.js +24 -4
  47. package/authentication/models/token.model.d.ts +33 -2
  48. package/authentication/server/authentication-ancillary.service.d.ts +27 -4
  49. package/authentication/server/authentication-ancillary.service.js +7 -0
  50. package/authentication/server/authentication-api-request-token.provider.d.ts +3 -0
  51. package/authentication/server/authentication-api-request-token.provider.js +3 -0
  52. package/authentication/server/authentication-secret-requirements.validator.d.ts +37 -0
  53. package/authentication/server/authentication-secret-requirements.validator.js +22 -0
  54. package/authentication/server/authentication.api-controller.d.ts +66 -1
  55. package/authentication/server/authentication.api-controller.js +65 -0
  56. package/authentication/server/authentication.service.d.ts +191 -11
  57. package/authentication/server/authentication.service.js +157 -8
  58. package/authentication/server/helper.d.ts +44 -5
  59. package/authentication/server/helper.js +43 -4
  60. package/authentication/server/module.d.ts +23 -1
  61. package/authentication/server/module.js +23 -1
  62. package/browser/browser-context-controller.d.ts +1 -1
  63. package/browser/browser-controller.d.ts +1 -1
  64. package/browser/browser-controller.js +1 -1
  65. package/browser/element-controller.d.ts +1 -1
  66. package/browser/locator-controller.d.ts +1 -1
  67. package/context/context.d.ts +1 -1
  68. package/data-structures/context-data-map.d.ts +1 -1
  69. package/database/mongo/mongo-base.repository.d.ts +1 -1
  70. package/database/mongo/types.d.ts +1 -1
  71. package/database/query.d.ts +1 -1
  72. package/document-management/models/document-management-table.d.ts +1 -1
  73. package/document-management/models/document-validation-definition.model.d.ts +1 -1
  74. package/document-management/server/schemas.d.ts +1 -1
  75. package/document-management/server/services/document-collection.service.d.ts +1 -1
  76. package/document-management/server/services/document-management-observation.service.d.ts +1 -1
  77. package/document-management/server/services/document-management.service.d.ts +1 -1
  78. package/document-management/server/services/document-property.service.d.ts +3 -3
  79. package/document-management/server/services/document-request.service.d.ts +1 -1
  80. package/document-management/server/services/document-validation.service.d.ts +1 -1
  81. package/document-management/server/services/document-workflow.service.d.ts +1 -1
  82. package/document-management/server/services/document.service.d.ts +1 -1
  83. package/document-management/server/services/singleton.d.ts +1 -1
  84. package/document-management/service-models/document-management.view-model.d.ts +1 -1
  85. package/document-management/service-models/enriched/enriched-document-assignment.view.d.ts +1 -1
  86. package/document-management/service-models/enriched/enriched-document-category.view.d.ts +1 -1
  87. package/document-management/service-models/enriched/enriched-document-collection.view.d.ts +1 -1
  88. package/document-management/service-models/enriched/enriched-document-request.view.d.ts +1 -1
  89. package/document-management/service-models/enriched/enriched-document-type.view.d.ts +1 -1
  90. package/document-management/service-models/enriched/enriched-document.view.d.ts +1 -1
  91. package/document-management/service-models/enriched/enriched-requests-template-data.model.d.ts +1 -1
  92. package/dom/file-select-dialog.d.ts +1 -1
  93. package/enumeration/enumeration.d.ts +1 -1
  94. package/errors/custom.error.d.ts +3 -0
  95. package/errors/custom.error.js +0 -1
  96. package/errors/errors.localization.d.ts +1 -1
  97. package/errors/not-supported.error.d.ts +1 -1
  98. package/{formats.js → formats/formats.js} +3 -3
  99. package/formats/index.d.ts +1 -0
  100. package/formats/index.js +1 -0
  101. package/http/client/http-client-request.d.ts +1 -1
  102. package/http/client/http-client-response.d.ts +1 -1
  103. package/http/client/http-client.d.ts +1 -1
  104. package/http/client/module.d.ts +1 -1
  105. package/http/http-body.d.ts +1 -1
  106. package/http/http-value-map.d.ts +1 -1
  107. package/http/http.error.d.ts +1 -1
  108. package/http/server/http-server-request.d.ts +1 -1
  109. package/http/server/http-server-response.d.ts +1 -1
  110. package/http/types.d.ts +1 -1
  111. package/http/utils.d.ts +1 -1
  112. package/injector/decorators.d.ts +1 -1
  113. package/injector/index.d.ts +1 -1
  114. package/injector/index.js +1 -1
  115. package/injector/injector.d.ts +10 -1
  116. package/injector/injector.js +6 -0
  117. package/injector/interfaces.d.ts +1 -1
  118. package/injector/provider.d.ts +1 -1
  119. package/injector/resolution.d.ts +10 -5
  120. package/injector/resolve-chain.d.ts +2 -2
  121. package/injector/resolve-chain.js +1 -1
  122. package/injector/resolve.error.js +1 -1
  123. package/injector/token.d.ts +8 -1
  124. package/injector/token.js +7 -0
  125. package/injector/types.d.ts +1 -1
  126. package/key-value-store/key-value-store.provider.d.ts +2 -2
  127. package/key-value-store/key-value.store.d.ts +2 -2
  128. package/key-value-store/mongo/mongo-key-value-store.provider.d.ts +1 -1
  129. package/key-value-store/mongo/mongo-key-value.store.d.ts +1 -1
  130. package/key-value-store/postgres/key-value-store.service.d.ts +1 -1
  131. package/mail/mail.service.d.ts +1 -1
  132. package/mail/models/mail-data.model.d.ts +1 -1
  133. package/mail/models/mail-template.model.d.ts +1 -1
  134. package/mail/module.d.ts +1 -1
  135. package/module/index.d.ts +0 -1
  136. package/module/index.js +0 -1
  137. package/module/module-base.d.ts +1 -1
  138. package/module/module-metric-reporter.js +1 -1
  139. package/module/module.d.ts +1 -1
  140. package/module/modules/function.module.js +1 -1
  141. package/object-storage/object.d.ts +1 -1
  142. package/openid-connect/mongo-oidc-state.repository.d.ts +1 -1
  143. package/openid-connect/oidc.service.d.ts +1 -1
  144. package/orm/decorators.d.ts +2 -2
  145. package/orm/entity.d.ts +1 -1
  146. package/orm/index.d.ts +3 -3
  147. package/orm/index.js +3 -3
  148. package/orm/query.d.ts +1 -1
  149. package/orm/repository.types.d.ts +1 -1
  150. package/orm/schemas/json.d.ts +1 -1
  151. package/orm/server/database-schema.d.ts +1 -1
  152. package/orm/server/drizzle/schema-converter.d.ts +1 -1
  153. package/orm/server/repository.d.ts +1 -1
  154. package/orm/server/transaction.d.ts +1 -1
  155. package/orm/server/transactional.d.ts +3 -3
  156. package/orm/server/types.d.ts +1 -1
  157. package/orm/types.d.ts +1 -1
  158. package/package.json +23 -20
  159. package/queue/mongo/job.d.ts +1 -1
  160. package/queue/mongo/queue.js +31 -31
  161. package/queue/postgres/job.model.d.ts +1 -1
  162. package/queue/postgres/queue.d.ts +1 -1
  163. package/queue/postgres/queue.provider.d.ts +1 -1
  164. package/queue/provider.d.ts +1 -1
  165. package/reflection/decorators.d.ts +1 -1
  166. package/reflection/registry.d.ts +1 -1
  167. package/reflection/types.d.ts +1 -1
  168. package/reflection/utils.d.ts +1 -1
  169. package/rpc/model.d.ts +1 -1
  170. package/rxjs-utils/retry-backoff.js +2 -2
  171. package/schema/converters/openapi-converter.d.ts +1 -1
  172. package/schema/decorators/schema.d.ts +1 -1
  173. package/schema/decorators/utils.d.ts +1 -1
  174. package/schema/schema.d.ts +1 -1
  175. package/schema/schema.error.d.ts +1 -1
  176. package/schema/schemas/array.d.ts +1 -1
  177. package/schema/schemas/enumeration.d.ts +1 -1
  178. package/schema/schemas/function.d.ts +1 -1
  179. package/schema/schemas/instance.d.ts +1 -1
  180. package/schema/schemas/nullable.d.ts +1 -1
  181. package/schema/schemas/number.d.ts +1 -1
  182. package/schema/schemas/object.d.ts +1 -1
  183. package/schema/schemas/one-or-many.d.ts +1 -1
  184. package/schema/schemas/optional.d.ts +1 -1
  185. package/schema/schemas/simple.d.ts +1 -1
  186. package/search-index/elastic/model/index-mapping.d.ts +1 -1
  187. package/search-index/elastic/search-index.js +3 -4
  188. package/search-index/memory/memory-search-index.d.ts +1 -1
  189. package/search-index/memory/memory-search-index.js +1 -1
  190. package/serializer/handlers/binary.d.ts +1 -1
  191. package/serializer/serializable.d.ts +1 -1
  192. package/serializer/types.d.ts +1 -1
  193. package/templates/module.d.ts +1 -1
  194. package/templates/renderers/handlebars.template-renderer.d.ts +1 -1
  195. package/templates/renderers/jsx.template-renderer.d.ts +1 -1
  196. package/templates/renderers/mjml.template-renderer.d.ts +1 -1
  197. package/templates/renderers/string.template-renderer.d.ts +1 -1
  198. package/templates/resolvers/file.template-resolver.d.ts +1 -1
  199. package/templates/resolvers/jsx.template-resolver.d.ts +1 -1
  200. package/templates/resolvers/string.template-resolver.d.ts +1 -1
  201. package/templates/template.model.d.ts +1 -1
  202. package/templates/template.renderer.d.ts +1 -1
  203. package/templates/template.service.d.ts +1 -1
  204. package/text/dynamic-text.model.d.ts +1 -1
  205. package/text/localization.service.d.ts +1 -1
  206. package/types/geo-json.d.ts +1 -1
  207. package/types/index.d.ts +2 -0
  208. package/types/tagged.d.ts +1 -1
  209. package/{types.d.ts → types/types.d.ts} +2 -1
  210. package/utils/async-hook/async-hook.d.ts +109 -0
  211. package/utils/async-hook/async-hook.js +77 -3
  212. package/utils/backoff.d.ts +125 -43
  213. package/utils/backoff.js +140 -65
  214. package/utils/base64.d.ts +1 -1
  215. package/utils/base64.js +1 -2
  216. package/utils/binary.d.ts +1 -1
  217. package/utils/comparison.d.ts +5 -5
  218. package/utils/comparison.js +5 -3
  219. package/utils/cryptography.d.ts +1 -1
  220. package/utils/encoding.d.ts +1 -1
  221. package/utils/enum.d.ts +1 -1
  222. package/utils/equals.d.ts +1 -1
  223. package/utils/format-error.d.ts +1 -1
  224. package/utils/function/class.d.ts +1 -1
  225. package/utils/function/memoize.d.ts +1 -1
  226. package/utils/helpers.d.ts +1 -1
  227. package/utils/helpers.js +2 -2
  228. package/utils/jwt.d.ts +3 -3
  229. package/utils/merge.d.ts +1 -1
  230. package/utils/middleware.js +3 -3
  231. package/utils/object/decycle.d.ts +1 -1
  232. package/utils/object/forward-ref.d.ts +1 -1
  233. package/utils/object/lazy-property.d.ts +1 -1
  234. package/utils/object/object.d.ts +1 -1
  235. package/utils/object/property-name.d.ts +1 -1
  236. package/utils/patch-worker.d.ts +1 -1
  237. package/utils/reactive-value-to-signal.d.ts +1 -1
  238. package/utils/reflection.d.ts +1 -1
  239. package/utils/repl.d.ts +1 -1
  240. package/utils/singleton.d.ts +1 -1
  241. package/utils/stream/size-limited-stream.d.ts +1 -1
  242. package/utils/type/extends.d.ts +1 -1
  243. package/utils/type-guards.d.ts +1 -1
  244. package/utils/url-builder.d.ts +1 -1
  245. package/utils/z-base32.d.ts +1 -1
  246. package/module/utils.d.ts +0 -4
  247. package/module/utils.js +0 -21
  248. /package/{formats.d.ts → formats/formats.d.ts} +0 -0
  249. /package/{types.js → types/types.js} +0 -0
  250. /package/{web-types.d.ts → types/web-types.d.ts} +0 -0
  251. /package/{web-types.js → types/web-types.js} +0 -0
@@ -1,7 +1,9 @@
1
- import '../polyfills.js';
2
1
  import type { Resolvable, resolveArgumentType } from '../injector/interfaces.js';
3
2
  import type { AiServiceOptions } from './ai.service.js';
4
3
  import type { FileContentPart, FileInput } from './types.js';
4
+ /**
5
+ * Options for {@link AiFileService}.
6
+ */
5
7
  export type AiFileServiceOptions = Pick<AiServiceOptions, 'apiKey' | 'keyFile' | 'vertex'>;
6
8
  export type AiFileServiceArgument = AiFileServiceOptions;
7
9
  type File = {
@@ -10,12 +12,38 @@ type File = {
10
12
  uri: string;
11
13
  mimeType: string;
12
14
  };
15
+ /**
16
+ * Manages file uploads and state for use with AI models.
17
+ * Handles both Google Generative AI File API and Google Cloud Storage for Vertex AI.
18
+ */
13
19
  export declare class AiFileService implements Resolvable<AiFileServiceArgument> {
14
20
  #private;
15
21
  readonly [resolveArgumentType]: AiFileServiceArgument;
22
+ /**
23
+ * Uploads and processes a single file, making it available for AI model consumption.
24
+ * @param fileInput The file to process.
25
+ * @returns A promise that resolves to a {@link FileContentPart} for use in AI requests.
26
+ */
16
27
  processFile(fileInput: FileInput): Promise<FileContentPart>;
28
+ /**
29
+ * Uploads and processes multiple files in parallel, making them available for AI model consumption.
30
+ * @param fileInputs The files to process.
31
+ * @returns A promise that resolves to an array of {@link FileContentPart} for use in AI requests.
32
+ */
17
33
  processFiles(fileInputs: FileInput[]): Promise<FileContentPart[]>;
34
+ /**
35
+ * Retrieves a file by its internal ID.
36
+ * The file must have been processed by this service instance before.
37
+ * @param id The internal ID of the file.
38
+ * @returns The file, or `undefined` if not found.
39
+ */
18
40
  getFileById(id: string): File | undefined;
41
+ /**
42
+ * Retrieves a file by its URI (e.g., GCS URI).
43
+ * The file must have been processed by this service instance before.
44
+ * @param uri The URI of the file.
45
+ * @returns The file, or `undefined` if not found.
46
+ */
19
47
  getFileByUri(uri: string): File | undefined;
20
48
  private getFile;
21
49
  private getFiles;
@@ -4,21 +4,25 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
- import '../polyfills.js';
8
7
  import { openAsBlob } from 'node:fs';
8
+ import { Readable } from 'node:stream';
9
+ import { ReadableStream as NodeReadableStream } from 'node:stream/web';
9
10
  import { Storage } from '@google-cloud/storage';
10
11
  import { FileState, GoogleGenAI } from '@google/genai';
12
+ import { CancellationSignal } from '../cancellation/token.js';
11
13
  import { AsyncEnumerable } from '../enumerable/async-enumerable.js';
12
14
  import { DetailsError } from '../errors/details.error.js';
13
- import { NotImplementedError } from '../errors/not-implemented.error.js';
14
15
  import { Singleton } from '../injector/decorators.js';
15
16
  import { inject, injectArgument } from '../injector/inject.js';
16
17
  import { Logger } from '../logger/logger.js';
17
18
  import { createArray } from '../utils/array/array.js';
19
+ import { backoffGenerator } from '../utils/backoff.js';
18
20
  import { formatBytes } from '../utils/format.js';
19
- import { timeout } from '../utils/timing.js';
20
21
  import { assertDefinedPass, isBlob, isDefined, isUndefined } from '../utils/type-guards.js';
21
- import { millisecondsPerSecond } from '../utils/units.js';
22
+ /**
23
+ * Manages file uploads and state for use with AI models.
24
+ * Handles both Google Generative AI File API and Google Cloud Storage for Vertex AI.
25
+ */
22
26
  let AiFileService = class AiFileService {
23
27
  #options = injectArgument(this);
24
28
  #genAI = new GoogleGenAI({
@@ -32,13 +36,32 @@ let AiFileService = class AiFileService {
32
36
  #fileMap = new Map();
33
37
  #fileUriMap = new Map();
34
38
  #logger = inject(Logger, 'AiFileService');
39
+ #cancellationSignal = inject(CancellationSignal);
40
+ #backoffOptions = {
41
+ cancellationSignal: this.#cancellationSignal,
42
+ strategy: 'linear',
43
+ initialDelay: 1000,
44
+ increase: 500,
45
+ jitter: 0.2,
46
+ maximumDelay: 10000,
47
+ };
35
48
  #bucket;
49
+ /**
50
+ * Uploads and processes a single file, making it available for AI model consumption.
51
+ * @param fileInput The file to process.
52
+ * @returns A promise that resolves to a {@link FileContentPart} for use in AI requests.
53
+ */
36
54
  async processFile(fileInput) {
37
55
  const file = await this.getFile(fileInput);
38
56
  this.#fileMap.set(file.id, file);
39
57
  this.#fileUriMap.set(file.uri, file);
40
58
  return { file: file.id };
41
59
  }
60
+ /**
61
+ * Uploads and processes multiple files in parallel, making them available for AI model consumption.
62
+ * @param fileInputs The files to process.
63
+ * @returns A promise that resolves to an array of {@link FileContentPart} for use in AI requests.
64
+ */
42
65
  async processFiles(fileInputs) {
43
66
  const files = await this.getFiles(fileInputs);
44
67
  return files.map((file) => {
@@ -47,9 +70,21 @@ let AiFileService = class AiFileService {
47
70
  return { file: file.id };
48
71
  });
49
72
  }
73
+ /**
74
+ * Retrieves a file by its internal ID.
75
+ * The file must have been processed by this service instance before.
76
+ * @param id The internal ID of the file.
77
+ * @returns The file, or `undefined` if not found.
78
+ */
50
79
  getFileById(id) {
51
80
  return this.#fileMap.get(id);
52
81
  }
82
+ /**
83
+ * Retrieves a file by its URI (e.g., GCS URI).
84
+ * The file must have been processed by this service instance before.
85
+ * @param uri The URI of the file.
86
+ * @returns The file, or `undefined` if not found.
87
+ */
53
88
  getFileByUri(uri) {
54
89
  return this.#fileUriMap.get(uri);
55
90
  }
@@ -74,18 +109,16 @@ let AiFileService = class AiFileService {
74
109
  : await openAsBlob(fileInput.path, { type: fileInput.mimeType });
75
110
  this.#logger.verbose(`Uploading file "${id}" (${formatBytes(blob.size)})...`);
76
111
  if (isDefined(this.#storage)) {
77
- throw new NotImplementedError();
78
- /*
79
112
  const bucket = await this.getBucket();
80
- const [file] = await bucket.upload(path, { destination: id, contentType: mimeType });
81
-
113
+ const file = bucket.file(id);
114
+ const blobStream = Readable.fromWeb(blob.stream());
115
+ await file.save(blobStream, { contentType: blob.type, resumable: false });
82
116
  return {
83
- id,
84
- name: id,
85
- uri: file.cloudStorageURI.toString(),
86
- mimeType
117
+ id,
118
+ name: id, // For Vertex, name is the GCS object id
119
+ uri: `gs://${bucket.name}/${file.name}`,
120
+ mimeType: blob.type,
87
121
  };
88
- */
89
122
  }
90
123
  const response = await this.#genAI.files.upload({ file: blob, config: { mimeType: blob.type } });
91
124
  return {
@@ -103,9 +136,11 @@ let AiFileService = class AiFileService {
103
136
  return this.#bucket;
104
137
  }
105
138
  const bucketName = assertDefinedPass(this.#options.vertex.bucket, 'Bucket not specified');
106
- const [exists] = await this.#storage.bucket(bucketName).exists();
139
+ const bucket = this.#storage.bucket(bucketName);
140
+ const [exists] = await bucket.exists();
107
141
  if (!exists) {
108
- const [bucket] = await this.#storage.createBucket(bucketName, {
142
+ this.#logger.info(`Bucket "${bucketName}" not found, creating...`);
143
+ const [createdBucket] = await this.#storage.createBucket(bucketName, {
109
144
  location: this.#options.vertex.location,
110
145
  lifecycle: {
111
146
  rule: [{
@@ -114,24 +149,32 @@ let AiFileService = class AiFileService {
114
149
  }],
115
150
  },
116
151
  });
152
+ this.#bucket = createdBucket;
153
+ }
154
+ else {
117
155
  this.#bucket = bucket;
118
156
  }
119
157
  return this.#bucket;
120
158
  }
121
159
  async waitForFileActive(file) {
122
- if (isUndefined(this.#genAI)) {
160
+ if (isDefined(this.#options.vertex)) {
161
+ // For Vertex, uploads to GCS are instantly "active"
123
162
  return;
124
163
  }
125
- let state = await this.#genAI.files.get({ name: file.name });
126
- while (state.state == FileState.PROCESSING) {
127
- await timeout(millisecondsPerSecond);
128
- state = await this.#genAI.files.get({ name: file.name });
129
- }
130
- if (state.state == FileState.FAILED) {
131
- throw new DetailsError(state.error?.message ?? `Failed to process file ${state.name}`, state.error?.details);
164
+ for await (const backoff of backoffGenerator(this.#backoffOptions)) {
165
+ const state = await this.#genAI.files.get({ name: file.name });
166
+ if (state.state == FileState.ACTIVE) {
167
+ this.#logger.verbose(`File "${file.id}" is active.`);
168
+ return;
169
+ }
170
+ if (state.state == FileState.FAILED) {
171
+ throw new DetailsError(state.error?.message ?? `Failed to process file ${state.name}`, state.error?.details);
172
+ }
173
+ backoff();
132
174
  }
133
175
  }
134
176
  async waitForFilesActive(files) {
177
+ // parallelizing does not help here, as each file upload is independently processed in the background
135
178
  for (const file of files) {
136
179
  await this.waitForFileActive(file);
137
180
  }
@@ -1,11 +1,38 @@
1
- import type { OneOrMany } from '../types.js';
1
+ import type { OneOrMany } from '../types/index.js';
2
2
  import type { AiService, CallFunctionsOptions, SpecializedGenerationResult } from './ai.service.js';
3
3
  import type { Content, GenerationRequest, GenerationResult, SchemaFunctionDeclarations, SchemaFunctionDeclarationsResult } from './types.js';
4
+ /**
5
+ * Represents a conversational session with an AI model.
6
+ *
7
+ * This class maintains the history of contents (messages) in a conversation,
8
+ * allowing for stateful, multi-turn interactions with the AI.
9
+ */
4
10
  export declare class AiSession {
5
11
  #private;
12
+ /**
13
+ * The history of contents in the session.
14
+ */
6
15
  readonly contents: Content[];
16
+ /**
17
+ * Creates an instance of `AiSession`.
18
+ * @param aiService The {@link AiService} instance to use for AI interactions.
19
+ */
7
20
  constructor(aiService: AiService);
21
+ /**
22
+ * Adds new content to the session's history without triggering a generation.
23
+ * @param content The content or contents to add.
24
+ */
8
25
  addContent(content: OneOrMany<Content>): void;
26
+ /**
27
+ * Prompts the model to call one or more functions based on the provided context and session history.
28
+ * The new user content and the resulting model response (function calls) are automatically added to the session history.
29
+ * @param options The options for the function call request.
30
+ */
9
31
  callFunctions<const T extends SchemaFunctionDeclarations>(options: CallFunctionsOptions<T>): Promise<SpecializedGenerationResult<SchemaFunctionDeclarationsResult<T>[]>>;
32
+ /**
33
+ * Generates content from the model based on the provided request and the current session history.
34
+ * The new user content and the resulting model response are automatically added to the session history.
35
+ * @param request The generation request.
36
+ */
10
37
  generate(request: GenerationRequest): Promise<GenerationResult>;
11
38
  }
package/ai/ai-session.js CHANGED
@@ -1,19 +1,46 @@
1
1
  import { toArray } from '../utils/array/array.js';
2
+ /**
3
+ * Represents a conversational session with an AI model.
4
+ *
5
+ * This class maintains the history of contents (messages) in a conversation,
6
+ * allowing for stateful, multi-turn interactions with the AI.
7
+ */
2
8
  export class AiSession {
3
9
  #aiService;
10
+ /**
11
+ * The history of contents in the session.
12
+ */
4
13
  contents = [];
14
+ /**
15
+ * Creates an instance of `AiSession`.
16
+ * @param aiService The {@link AiService} instance to use for AI interactions.
17
+ */
5
18
  constructor(aiService) {
6
19
  this.#aiService = aiService;
7
20
  }
21
+ /**
22
+ * Adds new content to the session's history without triggering a generation.
23
+ * @param content The content or contents to add.
24
+ */
8
25
  addContent(content) {
9
26
  this.contents.push(...toArray(content));
10
27
  }
28
+ /**
29
+ * Prompts the model to call one or more functions based on the provided context and session history.
30
+ * The new user content and the resulting model response (function calls) are automatically added to the session history.
31
+ * @param options The options for the function call request.
32
+ */
11
33
  async callFunctions(options) {
12
34
  this.contents.push(...toArray(options.contents));
13
35
  const result = await this.#aiService.callFunctions({ ...options, contents: this.contents });
14
36
  this.contents.push(result.raw.content);
15
37
  return result;
16
38
  }
39
+ /**
40
+ * Generates content from the model based on the provided request and the current session history.
41
+ * The new user content and the resulting model response are automatically added to the session history.
42
+ * @param request The generation request.
43
+ */
17
44
  async generate(request) {
18
45
  this.contents.push(...toArray(request.contents));
19
46
  const result = await this.#aiService.generate({ ...request, contents: this.contents });
@@ -1,23 +1,43 @@
1
1
  import type { Resolvable, resolveArgumentType } from '../injector/interfaces.js';
2
2
  import { type SchemaTestable } from '../schema/index.js';
3
- import type { Enumeration as EnumerationType, EnumerationValue } from '../types.js';
3
+ import type { Enumeration as EnumerationType, EnumerationValue } from '../types/index.js';
4
4
  import { AiSession } from './ai-session.js';
5
- import { type AiModel, type FileContentPart, type FileInput, type FunctionResultContentPart, type GenerationOptions, type GenerationRequest, type GenerationResult, type SchemaFunctionDeclarations, type SchemaFunctionDeclarationsResult } from './types.js';
5
+ import { type AiModel, type FileContentPart, type FileInput, type GenerationOptions, type GenerationRequest, type GenerationResult, type SchemaFunctionDeclarations, type SchemaFunctionDeclarationsResult } from './types.js';
6
+ /**
7
+ * A generation result that includes a specialized, typed result alongside the raw generation data.
8
+ * @template T The type of the specialized result.
9
+ */
6
10
  export type SpecializedGenerationResult<T> = {
11
+ /** The specialized, typed result. */
7
12
  result: T;
13
+ /** The raw, underlying generation result from the AI model. */
8
14
  raw: GenerationResult;
9
15
  };
16
+ /**
17
+ * An async generator for specialized generation results, which also provides access to the final raw generation data.
18
+ * @template T The type of the specialized result yielded by the generator.
19
+ */
10
20
  export type SpecializedGenerationResultGenerator<T> = AsyncGenerator<T> & {
11
21
  raw: Promise<GenerationResult>;
12
22
  };
23
+ /**
24
+ * Options for configuring the {@link AiService}.
25
+ */
13
26
  export declare class AiServiceOptions {
27
+ /** Google AI API key. */
14
28
  apiKey?: string;
29
+ /** Path to the Google Cloud credentials file. */
15
30
  keyFile?: string;
31
+ /** Vertex AI specific options. If provided, the service will use Vertex AI endpoints. */
16
32
  vertex?: {
17
33
  project: string;
18
34
  location: string;
19
35
  bucket?: string;
20
36
  };
37
+ /**
38
+ * The default model to use for generation requests.
39
+ * @default 'gemini-2.5-flash-lite'
40
+ */
21
41
  defaultModel?: AiModel;
22
42
  }
23
43
  export type AiServiceArgument = AiServiceOptions;
@@ -32,22 +52,79 @@ export type AnalyzeContentResult<T extends EnumerationType> = {
32
52
  documentTypes: ClassificationResult<T>[];
33
53
  tags: string[];
34
54
  };
55
+ /**
56
+ * Options for a function-calling request.
57
+ * @template T The schema declarations for the available functions.
58
+ */
35
59
  export type CallFunctionsOptions<T extends SchemaFunctionDeclarations> = Pick<GenerationRequest, 'contents' | 'model' | 'systemInstruction' | 'functionCallingMode'> & GenerationOptions & {
60
+ /** The function declarations available for the model to call. */
36
61
  functions: T;
37
62
  };
63
+ /**
64
+ * A service for interacting with Google's Generative AI models (Gemini).
65
+ *
66
+ * This service provides methods for content generation, function calling, and file processing,
67
+ * supporting both standard Google AI and Vertex AI endpoints.
68
+ */
38
69
  export declare class AiService implements Resolvable<AiServiceArgument> {
39
70
  #private;
71
+ /**
72
+ * The default AI model to use for requests if not specified otherwise.
73
+ */
40
74
  readonly defaultModel: AiModel;
41
75
  readonly [resolveArgumentType]: AiServiceArgument;
76
+ /**
77
+ * Creates a new {@link AiSession} for managing conversational history.
78
+ */
42
79
  createSession(): AiSession;
80
+ /**
81
+ * Processes a single file for use in AI requests by uploading it and making it available to the model.
82
+ * @param fileInput The file to process.
83
+ * @returns A promise that resolves to a {@link FileContentPart} which can be included in a generation request.
84
+ */
43
85
  processFile(fileInput: FileInput): Promise<FileContentPart>;
86
+ /**
87
+ * Processes multiple files in parallel for use in AI requests.
88
+ * @param fileInputs The files to process.
89
+ * @returns A promise that resolves to an array of {@link FileContentPart}s which can be included in generation requests.
90
+ */
44
91
  processFiles(fileInputs: FileInput[]): Promise<FileContentPart[]>;
92
+ /**
93
+ * Creates a file content part from a previously processed file ID.
94
+ * This does not re-upload the file.
95
+ * @param id The ID of the file, obtained from {@link AiFileService.processFile} or {@link AiFileService.processFiles}.
96
+ * @returns A {@link FileContentPart} for use in a generation request.
97
+ */
45
98
  getFileById(id: string): FileContentPart;
46
- callFunctions<const T extends SchemaFunctionDeclarations>(options: CallFunctionsOptions<T>): Promise<SpecializedGenerationResult<SchemaFunctionDeclarationsResult<T>[]> & {
47
- getFunctionResultContentParts: () => FunctionResultContentPart[];
48
- }>;
99
+ /**
100
+ * A high-level method to prompt the model to call one or more functions.
101
+ * This method sends the request and parses the model's response to identify function calls.
102
+ * If the function declaration includes a handler, it will be executed automatically.
103
+ * @param options The options for the function call request.
104
+ * @returns A promise that resolves to a {@link SpecializedGenerationResult} containing the function call results.
105
+ */
106
+ callFunctions<const T extends SchemaFunctionDeclarations>(options: CallFunctionsOptions<T>): Promise<SpecializedGenerationResult<SchemaFunctionDeclarationsResult<T>[]>>;
107
+ /**
108
+ * A streaming version of `callFunctions`.
109
+ * Yields function call results as they are received from the model.
110
+ * If function declarations include handlers, they are executed as soon as a complete function call is parsed.
111
+ * @param options The options for the function call request.
112
+ * @returns A {@link SpecializedGenerationResultGenerator} that yields function call results.
113
+ */
49
114
  callFunctionsStream<const T extends SchemaFunctionDeclarations>(options: CallFunctionsOptions<T>): SpecializedGenerationResultGenerator<SchemaFunctionDeclarationsResult<T>>;
115
+ /**
116
+ * Generates content from the model based on a request.
117
+ * This method waits for the full response from the model. For streaming, use {@link generateStream}.
118
+ * @param request The generation request.
119
+ * @returns A promise that resolves to the complete {@link GenerationResult}.
120
+ */
50
121
  generate<S>(request: GenerationRequest<S>): Promise<GenerationResult<S>>;
122
+ /**
123
+ * Generates content as a stream.
124
+ * Yields partial generation results as they are received from the model.
125
+ * @param request The generation request.
126
+ * @returns An `AsyncGenerator` that yields {@link GenerationResult} chunks.
127
+ */
51
128
  generateStream<S>(request: GenerationRequest<S>): AsyncGenerator<GenerationResult<S>>;
52
129
  private _callFunctionsStream;
53
130
  private getModelOutputTokenLimit;
@@ -57,4 +134,11 @@ export declare class AiService implements Resolvable<AiServiceArgument> {
57
134
  private convertFunctions;
58
135
  private convertGoogleContent;
59
136
  }
137
+ /**
138
+ * Merges an array of streaming generation results into a single, consolidated result.
139
+ * This is useful for combining the chunks from a streaming response into a final object.
140
+ * @param items The array of {@link GenerationResult} items from a stream.
141
+ * @param schema An optional schema to parse the merged JSON output.
142
+ * @returns A single, merged {@link GenerationResult}.
143
+ */
60
144
  export declare function mergeGenerationStreamItems<S>(items: GenerationResult<S>[], schema?: SchemaTestable<S>): GenerationResult<S>;