@webiny/api-core 6.6.0-alpha.0 → 6.6.0-alpha.1
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/ApiCoreFeature.js +6 -0
- package/ApiCoreFeature.js.map +1 -1
- package/exports/api/security/api-key.d.ts +1 -0
- package/exports/api/security/api-key.js +1 -0
- package/features/ai/Ai.d.ts +3 -1
- package/features/ai/Ai.js +39 -4
- package/features/ai/Ai.js.map +1 -1
- package/features/ai/AnthropicSdkFactory.js +12 -0
- package/features/ai/AnthropicSdkFactory.js.map +1 -1
- package/features/ai/OpenAiSdkFactory.js +16 -0
- package/features/ai/OpenAiSdkFactory.js.map +1 -1
- package/features/ai/TextExtractor/DefaultTextExtractor.d.ts +9 -0
- package/features/ai/TextExtractor/DefaultTextExtractor.js +28 -0
- package/features/ai/TextExtractor/DefaultTextExtractor.js.map +1 -0
- package/features/ai/TextExtractor/abstractions.d.ts +12 -0
- package/features/ai/TextExtractor/abstractions.js +5 -0
- package/features/ai/TextExtractor/abstractions.js.map +1 -0
- package/features/ai/TextExtractor/index.d.ts +3 -0
- package/features/ai/TextExtractor/index.js +2 -0
- package/features/ai/TextExtractor/parsers/docxParser.d.ts +1 -0
- package/features/ai/TextExtractor/parsers/docxParser.js +111 -0
- package/features/ai/TextExtractor/parsers/docxParser.js.map +1 -0
- package/features/ai/abstractions.d.ts +19 -0
- package/features/ai/abstractions.js.map +1 -1
- package/features/ai/events.d.ts +59 -0
- package/features/ai/events.js +41 -0
- package/features/ai/events.js.map +1 -0
- package/features/ai/feature.js +2 -0
- package/features/ai/feature.js.map +1 -1
- package/features/ai/index.d.ts +5 -1
- package/features/ai/index.js +2 -0
- package/features/dateFormatter/DefaultDateFormatter.d.ts +15 -0
- package/features/dateFormatter/DefaultDateFormatter.js +20 -0
- package/features/dateFormatter/DefaultDateFormatter.js.map +1 -0
- package/features/dateFormatter/abstractions.d.ts +13 -0
- package/features/dateFormatter/abstractions.js +5 -0
- package/features/dateFormatter/abstractions.js.map +1 -0
- package/features/dateFormatter/feature.d.ts +4 -0
- package/features/dateFormatter/feature.js +11 -0
- package/features/dateFormatter/feature.js.map +1 -0
- package/features/dateFormatter/index.d.ts +3 -0
- package/features/dateFormatter/index.js +2 -0
- package/features/featureFlags/decorators/FeatureFlagsWithLicenseDecorator.d.ts +13 -0
- package/features/featureFlags/decorators/FeatureFlagsWithLicenseDecorator.js +49 -0
- package/features/featureFlags/decorators/FeatureFlagsWithLicenseDecorator.js.map +1 -0
- package/features/security/IdentityContext/IdentityContext.d.ts +3 -3
- package/features/security/IdentityContext/IdentityContext.js +6 -6
- package/features/security/IdentityContext/IdentityContext.js.map +1 -1
- package/features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.js +11 -6
- package/features/security/apiKeys/CreateApiKey/CreateApiKeyUseCase.js.map +1 -1
- package/features/security/apiKeys/GetApiKey/GetApiKeyUseCase.d.ts +1 -1
- package/features/security/apiKeys/GetApiKey/GetApiKeyUseCase.js.map +1 -1
- package/features/security/apiKeys/GetApiKeyBySlug/GetApiKeyBySlugUseCase.d.ts +1 -3
- package/features/security/apiKeys/GetApiKeyBySlug/GetApiKeyBySlugUseCase.js.map +1 -1
- package/features/security/apiKeys/GetApiKeyBySlug/abstractions.d.ts +1 -1
- package/features/security/apiKeys/GetApiKeyBySlug/abstractions.js.map +1 -1
- package/features/security/apiKeys/GetApiKeyByToken/GetApiKeyByTokenUseCase.d.ts +1 -3
- package/features/security/apiKeys/GetApiKeyByToken/GetApiKeyByTokenUseCase.js.map +1 -1
- package/features/security/apiKeys/GetApiKeyByToken/abstractions.d.ts +1 -1
- package/features/security/apiKeys/GetApiKeyByToken/abstractions.js.map +1 -1
- package/features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.js +9 -3
- package/features/security/apiKeys/UpdateApiKey/UpdateApiKeyUseCase.js.map +1 -1
- package/features/security/apiKeys/feature.js +7 -2
- package/features/security/apiKeys/feature.js.map +1 -1
- package/features/security/apiKeys/shared/ApiKeyProvider.d.ts +3 -5
- package/features/security/apiKeys/shared/ApiKeyProvider.js +6 -21
- package/features/security/apiKeys/shared/ApiKeyProvider.js.map +1 -1
- package/features/security/apiKeys/shared/ApiKeysRepository.d.ts +1 -0
- package/features/security/apiKeys/shared/ApiKeysRepository.js +19 -4
- package/features/security/apiKeys/shared/ApiKeysRepository.js.map +1 -1
- package/features/security/apiKeys/shared/generateToken.d.ts +1 -1
- package/features/security/apiKeys/shared/generateToken.js.map +1 -1
- package/features/security/apiKeys/shared/schemas.d.ts +2 -2
- package/features/security/apiKeys/shared/schemas.js +2 -2
- package/features/security/apiKeys/shared/schemas.js.map +1 -1
- package/features/security/apiKeys/shared/types.d.ts +1 -1
- package/features/security/authorization/GroupsTeamsAuthorizer/GetPermissionsFromIdentity.d.ts +3 -3
- package/features/security/authorization/GroupsTeamsAuthorizer/GetPermissionsFromIdentity.js +5 -5
- package/features/security/authorization/GroupsTeamsAuthorizer/GetPermissionsFromIdentity.js.map +1 -1
- package/features/security/roles/CreateRole/CreateRoleUseCase.js +11 -6
- package/features/security/roles/CreateRole/CreateRoleUseCase.js.map +1 -1
- package/features/security/roles/CreateRole/schema.d.ts +1 -1
- package/features/security/roles/CreateRole/schema.js +1 -1
- package/features/security/roles/CreateRole/schema.js.map +1 -1
- package/features/security/roles/UpdateRole/UpdateRoleUseCase.js +9 -3
- package/features/security/roles/UpdateRole/UpdateRoleUseCase.js.map +1 -1
- package/features/security/roles/UpdateRole/schema.d.ts +1 -1
- package/features/security/roles/UpdateRole/schema.js +1 -1
- package/features/security/roles/UpdateRole/schema.js.map +1 -1
- package/features/security/shared/description.d.ts +4 -0
- package/features/security/shared/description.js +7 -0
- package/features/security/shared/description.js.map +1 -0
- package/features/security/shared/index.d.ts +1 -0
- package/features/security/shared/index.js +1 -0
- package/features/security/teams/CreateTeam/CreateTeamUseCase.d.ts +3 -1
- package/features/security/teams/CreateTeam/CreateTeamUseCase.js +20 -8
- package/features/security/teams/CreateTeam/CreateTeamUseCase.js.map +1 -1
- package/features/security/teams/CreateTeam/schema.d.ts +1 -1
- package/features/security/teams/CreateTeam/schema.js +1 -1
- package/features/security/teams/CreateTeam/schema.js.map +1 -1
- package/features/security/teams/UpdateTeam/UpdateTeamUseCase.d.ts +3 -1
- package/features/security/teams/UpdateTeam/UpdateTeamUseCase.js +20 -5
- package/features/security/teams/UpdateTeam/UpdateTeamUseCase.js.map +1 -1
- package/features/security/teams/UpdateTeam/schema.d.ts +1 -1
- package/features/security/teams/UpdateTeam/schema.js +1 -1
- package/features/security/teams/UpdateTeam/schema.js.map +1 -1
- package/features/security/teams/shared/resolveRoleIdentifiers.d.ts +17 -0
- package/features/security/teams/shared/resolveRoleIdentifiers.js +32 -0
- package/features/security/teams/shared/resolveRoleIdentifiers.js.map +1 -0
- package/features/slugify/DefaultSlugify.d.ts +8 -0
- package/features/slugify/DefaultSlugify.js +20 -0
- package/features/slugify/DefaultSlugify.js.map +1 -0
- package/features/slugify/abstractions.d.ts +12 -0
- package/features/slugify/abstractions.js +5 -0
- package/features/slugify/abstractions.js.map +1 -0
- package/features/slugify/feature.d.ts +4 -0
- package/features/slugify/feature.js +11 -0
- package/features/slugify/feature.js.map +1 -0
- package/features/slugify/index.d.ts +3 -0
- package/features/slugify/index.js +2 -0
- package/features/stringFormatter/DefaultStringFormatter.d.ts +17 -0
- package/features/stringFormatter/DefaultStringFormatter.js +19 -0
- package/features/stringFormatter/DefaultStringFormatter.js.map +1 -0
- package/features/stringFormatter/abstractions.d.ts +11 -0
- package/features/stringFormatter/abstractions.js +5 -0
- package/features/stringFormatter/abstractions.js.map +1 -0
- package/features/stringFormatter/feature.d.ts +4 -0
- package/features/stringFormatter/feature.js +13 -0
- package/features/stringFormatter/feature.js.map +1 -0
- package/features/stringFormatter/index.d.ts +3 -0
- package/features/stringFormatter/index.js +2 -0
- package/features/task/TaskDefinition/abstractions.d.ts +76 -4
- package/features/task/TaskDefinition/abstractions.js +2 -1
- package/features/task/TaskDefinition/abstractions.js.map +1 -1
- package/features/wcp/WcpContext/WcpContext.d.ts +6 -0
- package/features/wcp/WcpContext/WcpContext.js +18 -0
- package/features/wcp/WcpContext/WcpContext.js.map +1 -1
- package/features/wcp/WcpContext/decorators/WcpContextWithFeatureFlagsDecorator.d.ts +18 -0
- package/features/wcp/WcpContext/decorators/WcpContextWithFeatureFlagsDecorator.js +57 -25
- package/features/wcp/WcpContext/decorators/WcpContextWithFeatureFlagsDecorator.js.map +1 -1
- package/features/wcp/WcpFeature.js +2 -0
- package/features/wcp/WcpFeature.js.map +1 -1
- package/features/wcp/WcpLicenseLoader.d.ts +25 -0
- package/features/wcp/WcpLicenseLoader.js +58 -0
- package/features/wcp/WcpLicenseLoader.js.map +1 -0
- package/features/wcp/WcpLicenseProvider.d.ts +6 -14
- package/features/wcp/WcpLicenseProvider.js +3 -7
- package/features/wcp/WcpLicenseProvider.js.map +1 -1
- package/features/wcp/resolveWcpProjectEnvironment.d.ts +9 -0
- package/features/wcp/resolveWcpProjectEnvironment.js +23 -0
- package/features/wcp/resolveWcpProjectEnvironment.js.map +1 -0
- package/graphql/featureFlags/FeatureFlagsSchemaFactory.d.ts +9 -0
- package/graphql/featureFlags/FeatureFlagsSchemaFactory.js +49 -0
- package/graphql/featureFlags/FeatureFlagsSchemaFactory.js.map +1 -0
- package/graphql/wcp/WcpSchemaFactory.js +2 -0
- package/graphql/wcp/WcpSchemaFactory.js.map +1 -1
- package/package.json +18 -18
- package/testing/environment.d.ts +14 -0
- package/testing/environment.js +18 -0
- package/testing/environment.js.map +1 -0
- package/types/security.d.ts +1 -1
- package/features/wcp/loadWcpLicense.d.ts +0 -2
- package/features/wcp/loadWcpLicense.js +0 -51
- package/features/wcp/loadWcpLicense.js.map +0 -1
package/ApiCoreFeature.js
CHANGED
|
@@ -13,6 +13,8 @@ import { EncryptionFeature } from "./features/encryption/feature.js";
|
|
|
13
13
|
import { HasherFeature } from "./features/hashing/feature.js";
|
|
14
14
|
import { FeatureFlagsFeature } from "./features/featureFlags/feature.js";
|
|
15
15
|
import { MaskerFeature } from "./features/masker/feature.js";
|
|
16
|
+
import { StringFormatterFeature } from "./features/stringFormatter/feature.js";
|
|
17
|
+
import { DateFormatterFeature } from "./features/dateFormatter/feature.js";
|
|
16
18
|
import { AiFeature } from "./features/ai/feature.js";
|
|
17
19
|
import { WcpFeature } from "./features/wcp/WcpFeature.js";
|
|
18
20
|
import { NullWebhookDispatcher } from "./features/webhooks/WebhookDispatcher/NullWebhookDispatcher.js";
|
|
@@ -23,12 +25,15 @@ import { SecuritySchemaFactory } from "./graphql/security/SecuritySchemaFactory.
|
|
|
23
25
|
import { UsersSchemaFactory } from "./graphql/users/UsersSchemaFactory.js";
|
|
24
26
|
import { SystemSchemaFactory } from "./graphql/system/SystemSchemaFactory.js";
|
|
25
27
|
import { WcpSchemaFactory } from "./graphql/wcp/WcpSchemaFactory.js";
|
|
28
|
+
import { FeatureFlagsSchemaFactory } from "./graphql/featureFlags/FeatureFlagsSchemaFactory.js";
|
|
26
29
|
const ApiCoreFeature = createFeature({
|
|
27
30
|
name: "ApiCore",
|
|
28
31
|
register (container, config = {}) {
|
|
29
32
|
const storageOperations = container.resolve(ApiCoreStorageOperationsFactory).create();
|
|
30
33
|
WcpFeature.register(container, config.wcpLicense);
|
|
31
34
|
MaskerFeature.register(container);
|
|
35
|
+
StringFormatterFeature.register(container);
|
|
36
|
+
DateFormatterFeature.register(container);
|
|
32
37
|
AiFeature.register(container);
|
|
33
38
|
LoggerFeature.register(container);
|
|
34
39
|
EventPublisherFeature.register(container);
|
|
@@ -50,6 +55,7 @@ const ApiCoreFeature = createFeature({
|
|
|
50
55
|
container.register(UsersSchemaFactory);
|
|
51
56
|
container.register(SystemSchemaFactory);
|
|
52
57
|
container.register(WcpSchemaFactory);
|
|
58
|
+
container.register(FeatureFlagsSchemaFactory);
|
|
53
59
|
}
|
|
54
60
|
});
|
|
55
61
|
export { ApiCoreFeature };
|
package/ApiCoreFeature.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ApiCoreFeature.js","sources":["../src/ApiCoreFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { Container } from \"@webiny/di\";\nimport { EventPublisherFeature } from \"~/features/eventPublisher/feature.js\";\nimport { LoggerFeature } from \"~/features/logger/feature.js\";\nimport { SecurityFeature } from \"~/features/security/SecurityFeature.js\";\nimport { SystemFeature } from \"~/features/system/SystemFeature.js\";\nimport { TenancyFeature } from \"./features/tenancy/TenancyFeature.js\";\nimport { AdminUsersFeature } from \"~/features/users/AdminUsersFeature.js\";\nimport type { ApiCoreConfig } from \"~/types/core.js\";\nimport { ApiCoreStorageOperationsFactory } from \"~/features/storageOperations/abstractions.js\";\nimport { IdpAuthenticatorFeature } from \"~/idp/feature.js\";\nimport { KeyValueStoreFeature } from \"~/features/keyValueStore/feature.js\";\nimport { BuildParamsFeature } from \"~/features/buildParams/feature.js\";\nimport { EncryptionFeature } from \"~/features/encryption/feature.js\";\nimport { HasherFeature } from \"~/features/hashing/feature.js\";\nimport { FeatureFlagsFeature } from \"~/features/featureFlags/feature.js\";\nimport { MaskerFeature } from \"~/features/masker/feature.js\";\nimport { AiFeature } from \"~/features/ai/feature.js\";\nimport { WcpFeature } from \"~/features/wcp/WcpFeature.js\";\nimport { NullWebhookDispatcher } from \"./features/webhooks/WebhookDispatcher/NullWebhookDispatcher.js\";\nimport { WebhookProviderFeature } from \"~/features/webhooks/index.js\";\nimport { RequestContextFeature } from \"~/features/requestContext/index.js\";\nimport { ApiCoreSchemaFactory } from \"~/graphql/ApiCoreSchemaFactory.js\";\nimport { SecuritySchemaFactory } from \"~/graphql/security/SecuritySchemaFactory.js\";\nimport { UsersSchemaFactory } from \"~/graphql/users/UsersSchemaFactory.js\";\nimport { SystemSchemaFactory } from \"~/graphql/system/SystemSchemaFactory.js\";\nimport { WcpSchemaFactory } from \"~/graphql/wcp/WcpSchemaFactory.js\";\n\nexport const ApiCoreFeature = createFeature({\n name: \"ApiCore\",\n register(container: Container, config: ApiCoreConfig = {}) {\n // Storage operations are built synchronously, here, from the adapter-provided factory —\n // the same way for every event (no out-of-feature construction, no async initializer).\n const storageOperations = container.resolve(ApiCoreStorageOperationsFactory).create();\n\n // Register features\n WcpFeature.register(container, config.wcpLicense);\n MaskerFeature.register(container);\n AiFeature.register(container);\n LoggerFeature.register(container);\n EventPublisherFeature.register(container);\n BuildParamsFeature.register(container);\n EncryptionFeature.register(container);\n HasherFeature.register(container);\n FeatureFlagsFeature.register(container);\n TenancyFeature.register(container, storageOperations.tenancyStorageOperations);\n SecurityFeature.register(container, storageOperations.securityStorageOperations);\n AdminUsersFeature.register(container, storageOperations.usersStorageOperations);\n KeyValueStoreFeature.register(container, storageOperations.keyValueStorageOperations);\n SystemFeature.register(container);\n IdpAuthenticatorFeature.register(container);\n RequestContextFeature.register(container);\n container.register(NullWebhookDispatcher).inSingletonScope();\n WebhookProviderFeature.register(container);\n\n // Core API GraphQL schema: a base factory (root types + scalars) plus one\n // CoreGraphQLSchemaFactory per domain.\n container.register(ApiCoreSchemaFactory);\n container.register(SecuritySchemaFactory);\n container.register(UsersSchemaFactory);\n container.register(SystemSchemaFactory);\n container.register(WcpSchemaFactory);\n }\n});\n"],"names":["ApiCoreFeature","createFeature","container","config","storageOperations","ApiCoreStorageOperationsFactory","WcpFeature","MaskerFeature","AiFeature","LoggerFeature","EventPublisherFeature","BuildParamsFeature","EncryptionFeature","HasherFeature","FeatureFlagsFeature","TenancyFeature","SecurityFeature","AdminUsersFeature","KeyValueStoreFeature","SystemFeature","IdpAuthenticatorFeature","RequestContextFeature","NullWebhookDispatcher","WebhookProviderFeature","ApiCoreSchemaFactory","SecuritySchemaFactory","UsersSchemaFactory","SystemSchemaFactory","WcpSchemaFactory"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ApiCoreFeature.js","sources":["../src/ApiCoreFeature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { Container } from \"@webiny/di\";\nimport { EventPublisherFeature } from \"~/features/eventPublisher/feature.js\";\nimport { LoggerFeature } from \"~/features/logger/feature.js\";\nimport { SecurityFeature } from \"~/features/security/SecurityFeature.js\";\nimport { SystemFeature } from \"~/features/system/SystemFeature.js\";\nimport { TenancyFeature } from \"./features/tenancy/TenancyFeature.js\";\nimport { AdminUsersFeature } from \"~/features/users/AdminUsersFeature.js\";\nimport type { ApiCoreConfig } from \"~/types/core.js\";\nimport { ApiCoreStorageOperationsFactory } from \"~/features/storageOperations/abstractions.js\";\nimport { IdpAuthenticatorFeature } from \"~/idp/feature.js\";\nimport { KeyValueStoreFeature } from \"~/features/keyValueStore/feature.js\";\nimport { BuildParamsFeature } from \"~/features/buildParams/feature.js\";\nimport { EncryptionFeature } from \"~/features/encryption/feature.js\";\nimport { HasherFeature } from \"~/features/hashing/feature.js\";\nimport { FeatureFlagsFeature } from \"~/features/featureFlags/feature.js\";\nimport { MaskerFeature } from \"~/features/masker/feature.js\";\nimport { StringFormatterFeature } from \"~/features/stringFormatter/feature.js\";\nimport { DateFormatterFeature } from \"~/features/dateFormatter/feature.js\";\nimport { AiFeature } from \"~/features/ai/feature.js\";\nimport { WcpFeature } from \"~/features/wcp/WcpFeature.js\";\nimport { NullWebhookDispatcher } from \"./features/webhooks/WebhookDispatcher/NullWebhookDispatcher.js\";\nimport { WebhookProviderFeature } from \"~/features/webhooks/index.js\";\nimport { RequestContextFeature } from \"~/features/requestContext/index.js\";\nimport { ApiCoreSchemaFactory } from \"~/graphql/ApiCoreSchemaFactory.js\";\nimport { SecuritySchemaFactory } from \"~/graphql/security/SecuritySchemaFactory.js\";\nimport { UsersSchemaFactory } from \"~/graphql/users/UsersSchemaFactory.js\";\nimport { SystemSchemaFactory } from \"~/graphql/system/SystemSchemaFactory.js\";\nimport { WcpSchemaFactory } from \"~/graphql/wcp/WcpSchemaFactory.js\";\nimport { FeatureFlagsSchemaFactory } from \"~/graphql/featureFlags/FeatureFlagsSchemaFactory.js\";\n\nexport const ApiCoreFeature = createFeature({\n name: \"ApiCore\",\n register(container: Container, config: ApiCoreConfig = {}) {\n // Storage operations are built synchronously, here, from the adapter-provided factory —\n // the same way for every event (no out-of-feature construction, no async initializer).\n const storageOperations = container.resolve(ApiCoreStorageOperationsFactory).create();\n\n // Register features\n WcpFeature.register(container, config.wcpLicense);\n MaskerFeature.register(container);\n StringFormatterFeature.register(container);\n DateFormatterFeature.register(container);\n AiFeature.register(container);\n LoggerFeature.register(container);\n EventPublisherFeature.register(container);\n BuildParamsFeature.register(container);\n EncryptionFeature.register(container);\n HasherFeature.register(container);\n FeatureFlagsFeature.register(container);\n TenancyFeature.register(container, storageOperations.tenancyStorageOperations);\n SecurityFeature.register(container, storageOperations.securityStorageOperations);\n AdminUsersFeature.register(container, storageOperations.usersStorageOperations);\n KeyValueStoreFeature.register(container, storageOperations.keyValueStorageOperations);\n SystemFeature.register(container);\n IdpAuthenticatorFeature.register(container);\n RequestContextFeature.register(container);\n container.register(NullWebhookDispatcher).inSingletonScope();\n WebhookProviderFeature.register(container);\n\n // Core API GraphQL schema: a base factory (root types + scalars) plus one\n // CoreGraphQLSchemaFactory per domain.\n container.register(ApiCoreSchemaFactory);\n container.register(SecuritySchemaFactory);\n container.register(UsersSchemaFactory);\n container.register(SystemSchemaFactory);\n container.register(WcpSchemaFactory);\n container.register(FeatureFlagsSchemaFactory);\n }\n});\n"],"names":["ApiCoreFeature","createFeature","container","config","storageOperations","ApiCoreStorageOperationsFactory","WcpFeature","MaskerFeature","StringFormatterFeature","DateFormatterFeature","AiFeature","LoggerFeature","EventPublisherFeature","BuildParamsFeature","EncryptionFeature","HasherFeature","FeatureFlagsFeature","TenancyFeature","SecurityFeature","AdminUsersFeature","KeyValueStoreFeature","SystemFeature","IdpAuthenticatorFeature","RequestContextFeature","NullWebhookDispatcher","WebhookProviderFeature","ApiCoreSchemaFactory","SecuritySchemaFactory","UsersSchemaFactory","SystemSchemaFactory","WcpSchemaFactory","FeatureFlagsSchema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BeforeDeleteEventHandler, DeleteApiKeyUseCase } from "../../../features/security/apiKeys/DeleteApiKey/index.js";
|
|
3
3
|
export { GetApiKeyUseCase } from "../../../features/security/apiKeys/GetApiKey/index.js";
|
|
4
4
|
export { GetApiKeyByTokenUseCase } from "../../../features/security/apiKeys/GetApiKeyByToken/index.js";
|
|
5
|
+
export { GetApiKeyBySlugUseCase } from "../../../features/security/apiKeys/GetApiKeyBySlug/index.js";
|
|
5
6
|
export { ListApiKeysUseCase } from "../../../features/security/apiKeys/ListApiKeys/index.js";
|
|
6
7
|
export { ApiKeyAfterUpdateEventHandler, ApiKeyBeforeUpdateEventHandler, UpdateApiKeyUseCase } from "../../../features/security/apiKeys/UpdateApiKey/index.js";
|
|
7
8
|
export { ApiKeyFactory } from "../../../features/security/apiKeys/shared/abstractions.js";
|
|
@@ -2,6 +2,7 @@ export { ApiKeyAfterCreateEventHandler, ApiKeyBeforeCreateEventHandler, CreateAp
|
|
|
2
2
|
export { ApiKeyAfterDeleteEventHandler, ApiKeyBeforeDeleteEventHandler, DeleteApiKeyUseCase } from "../../../features/security/apiKeys/DeleteApiKey/index.js";
|
|
3
3
|
export { GetApiKeyUseCase } from "../../../features/security/apiKeys/GetApiKey/index.js";
|
|
4
4
|
export { GetApiKeyByTokenUseCase } from "../../../features/security/apiKeys/GetApiKeyByToken/index.js";
|
|
5
|
+
export { GetApiKeyBySlugUseCase } from "../../../features/security/apiKeys/GetApiKeyBySlug/index.js";
|
|
5
6
|
export { ListApiKeysUseCase } from "../../../features/security/apiKeys/ListApiKeys/index.js";
|
|
6
7
|
export { ApiKeyAfterUpdateEventHandler, ApiKeyBeforeUpdateEventHandler, UpdateApiKeyUseCase } from "../../../features/security/apiKeys/UpdateApiKey/index.js";
|
|
7
8
|
export { ApiKeyFactory } from "../../../features/security/apiKeys/shared/abstractions.js";
|
package/features/ai/Ai.d.ts
CHANGED
|
@@ -6,12 +6,14 @@ import { AiConnectionFactory } from "./abstractions.js";
|
|
|
6
6
|
import type { AiGenerateTextParams, AiModel } from "./abstractions.js";
|
|
7
7
|
import type { AiStreamTextParams } from "./abstractions.js";
|
|
8
8
|
import type { IAiConnectionInline } from "./abstractions.js";
|
|
9
|
+
import { EventPublisher } from "../../features/eventPublisher/index.js";
|
|
9
10
|
declare class AiImpl implements AiAbstraction.Interface {
|
|
10
11
|
private readonly sdkFactories;
|
|
11
12
|
private readonly connectionFactories;
|
|
13
|
+
private readonly eventPublisher;
|
|
12
14
|
private sdkCache;
|
|
13
15
|
private resolvedConnections;
|
|
14
|
-
constructor(sdkFactories: AiSdkFactory.Interface[], connectionFactories: AiConnectionFactory.Interface[]);
|
|
16
|
+
constructor(sdkFactories: AiSdkFactory.Interface[], connectionFactories: AiConnectionFactory.Interface[], eventPublisher: EventPublisher.Interface);
|
|
15
17
|
generateText(params: AiGenerateTextParams): ReturnType<typeof generateText>;
|
|
16
18
|
streamText(params: AiStreamTextParams): Promise<ReturnType<typeof streamText>>;
|
|
17
19
|
listModels(): Promise<AiModel[]>;
|
package/features/ai/Ai.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { createImplementation } from "@webiny/feature/api";
|
|
2
2
|
import { generateText, streamText } from "ai";
|
|
3
3
|
import { Ai, AiConnectionFactory, AiSdkFactory } from "./abstractions.js";
|
|
4
|
+
import { mdbid } from "@webiny/utils/mdbid.js";
|
|
5
|
+
import { EventPublisher } from "../eventPublisher/index.js";
|
|
6
|
+
import { AiAfterGenerateTextEvent, AiBeforeGenerateTextEvent, AiBeforeStreamTextEvent, AiGenerateTextErrorEvent } from "./events.js";
|
|
4
7
|
function toAiModel(factory, modelId, modelName) {
|
|
5
8
|
return {
|
|
6
9
|
providerId: factory.id,
|
|
@@ -10,22 +13,53 @@ function toAiModel(factory, modelId, modelName) {
|
|
|
10
13
|
};
|
|
11
14
|
}
|
|
12
15
|
class AiImpl {
|
|
13
|
-
constructor(sdkFactories, connectionFactories){
|
|
16
|
+
constructor(sdkFactories, connectionFactories, eventPublisher){
|
|
14
17
|
this.sdkFactories = sdkFactories;
|
|
15
18
|
this.connectionFactories = connectionFactories;
|
|
19
|
+
this.eventPublisher = eventPublisher;
|
|
16
20
|
this.sdkCache = new Map();
|
|
17
21
|
this.resolvedConnections = null;
|
|
18
22
|
}
|
|
19
|
-
generateText(params) {
|
|
23
|
+
async generateText(params) {
|
|
20
24
|
const { model, connection, ...rest } = params;
|
|
21
|
-
|
|
25
|
+
const resolvedModel = await this.resolveLanguageModel(model, connection);
|
|
26
|
+
const requestId = mdbid();
|
|
27
|
+
await this.eventPublisher.publish(new AiBeforeGenerateTextEvent({
|
|
28
|
+
requestId,
|
|
29
|
+
params
|
|
30
|
+
}));
|
|
31
|
+
const start = performance.now();
|
|
32
|
+
try {
|
|
33
|
+
const result = await generateText({
|
|
22
34
|
model: resolvedModel,
|
|
23
35
|
...rest
|
|
36
|
+
});
|
|
37
|
+
const duration = performance.now() - start;
|
|
38
|
+
await this.eventPublisher.publish(new AiAfterGenerateTextEvent({
|
|
39
|
+
requestId,
|
|
40
|
+
params,
|
|
41
|
+
result,
|
|
42
|
+
duration
|
|
43
|
+
}));
|
|
44
|
+
return result;
|
|
45
|
+
} catch (err) {
|
|
46
|
+
const duration = performance.now() - start;
|
|
47
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
48
|
+
await this.eventPublisher.publish(new AiGenerateTextErrorEvent({
|
|
49
|
+
requestId,
|
|
50
|
+
params,
|
|
51
|
+
error,
|
|
52
|
+
duration
|
|
24
53
|
}));
|
|
54
|
+
throw err;
|
|
55
|
+
}
|
|
25
56
|
}
|
|
26
57
|
async streamText(params) {
|
|
27
58
|
const { model, connection, ...rest } = params;
|
|
28
59
|
const resolvedModel = await this.resolveLanguageModel(model, connection);
|
|
60
|
+
await this.eventPublisher.publish(new AiBeforeStreamTextEvent({
|
|
61
|
+
params
|
|
62
|
+
}));
|
|
29
63
|
return streamText({
|
|
30
64
|
model: resolvedModel,
|
|
31
65
|
...rest
|
|
@@ -108,7 +142,8 @@ const Ai_Ai = createImplementation({
|
|
|
108
142
|
{
|
|
109
143
|
multiple: true
|
|
110
144
|
}
|
|
111
|
-
]
|
|
145
|
+
],
|
|
146
|
+
EventPublisher
|
|
112
147
|
]
|
|
113
148
|
});
|
|
114
149
|
export { Ai_Ai as Ai };
|
package/features/ai/Ai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/ai/Ai.js","sources":["../../../src/features/ai/Ai.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { generateText } from \"ai\";\nimport { streamText } from \"ai\";\nimport { Ai as AiAbstraction } from \"./abstractions.js\";\nimport { AiSdkFactory } from \"./abstractions.js\";\nimport { AiConnectionFactory } from \"./abstractions.js\";\nimport type { AiGenerateTextParams, AiModel, IAiSdkFactory } from \"./abstractions.js\";\nimport type { AiStreamTextParams } from \"./abstractions.js\";\nimport type { IAiSdk } from \"./abstractions.js\";\nimport type { IAiConnection } from \"./abstractions.js\";\nimport type { IAiConnectionInline } from \"./abstractions.js\";\nimport type { LanguageModel } from \"ai\";\n\nfunction toAiModel(factory: IAiSdkFactory, modelId: string, modelName: string): AiModel {\n return {\n providerId: factory.id,\n providerName: factory.name,\n modelId,\n modelName\n };\n}\n\nclass AiImpl implements AiAbstraction.Interface {\n private sdkCache = new Map<string, IAiSdk>();\n private resolvedConnections: IAiConnection[] | null = null;\n\n constructor(\n private readonly sdkFactories: AiSdkFactory.Interface[],\n private readonly connectionFactories: AiConnectionFactory.Interface[]\n ) {}\n\n generateText(params: AiGenerateTextParams): ReturnType<typeof generateText> {\n const { model, connection, ...rest } = params;\n return this.resolveLanguageModel(model, connection).then(resolvedModel => {\n // Cast required: spreading the discriminated Prompt union loses its narrowing.\n return generateText({ model: resolvedModel, ...rest } as Parameters<\n typeof generateText\n >[0]);\n });\n }\n\n async streamText(params: AiStreamTextParams): Promise<ReturnType<typeof streamText>> {\n const { model, connection, ...rest } = params;\n const resolvedModel = await this.resolveLanguageModel(model, connection);\n // Cast required: spreading the discriminated Prompt union loses its narrowing.\n return streamText({ model: resolvedModel, ...rest } as Parameters<typeof streamText>[0]);\n }\n\n listModels(): Promise<AiModel[]> {\n return Promise.resolve(\n this.sdkFactories.flatMap(factory =>\n factory.models.map(m => toAiModel(factory, m.id, m.name))\n )\n );\n }\n\n async listModelsByConnections(): Promise<AiModel[]> {\n const connections = await this.getConnections();\n return connections.flatMap(conn => {\n const factory = this.sdkFactories.find(f => f.id === conn.sdkName);\n if (!factory) {\n return [];\n }\n return factory.models.map(m => toAiModel(factory, m.id, m.name));\n });\n }\n\n async listModelsByConnection(connection: string | IAiConnectionInline): Promise<AiModel[]> {\n const conn = await this.resolveConnection(undefined, connection);\n const factory = this.sdkFactories.find(f => f.id === conn.sdkName);\n if (!factory) {\n return [];\n }\n return factory.models.map(m => toAiModel(factory, m.id, m.name));\n }\n\n private async resolveLanguageModel(\n modelId: string,\n connection?: string | IAiConnectionInline\n ): Promise<LanguageModel> {\n const slashIndex = modelId.indexOf(\"/\");\n if (slashIndex === -1) {\n throw new Error(\n `Invalid model ID \"${modelId}\". Expected format: \"<providerId>/<modelId>\" (e.g. \"openai/gpt-4o\").`\n );\n }\n\n const providerId = modelId.slice(0, slashIndex);\n const modelName = modelId.slice(slashIndex + 1);\n\n const conn = await this.resolveConnection(providerId, connection);\n const sdk = await this.getSdk(conn);\n return sdk.languageModel(modelName);\n }\n\n private async getConnections(): Promise<IAiConnection[]> {\n if (!this.resolvedConnections) {\n this.resolvedConnections = await Promise.all(\n this.connectionFactories.map(f => f.execute())\n );\n }\n return this.resolvedConnections;\n }\n\n private async resolveConnection(\n providerId: string | undefined,\n connection?: string | IAiConnectionInline\n ): Promise<IAiConnectionInline> {\n if (typeof connection === \"object\") {\n return connection;\n }\n\n const connections = await this.getConnections();\n\n if (typeof connection === \"string\") {\n const found = connections.find(c => c.id === connection);\n if (!found) {\n const known = connections.map(c => `\"${c.id}\"`).join(\", \");\n throw new Error(\n `Unknown AI connection \"${connection}\". Registered connections: ${known}.`\n );\n }\n return found;\n }\n\n const found = connections.find(c => c.sdkName === providerId);\n if (!found) {\n const known = connections.map(c => `\"${c.id}\" (${c.sdkName})`).join(\", \");\n throw new Error(\n `No AI connection found for provider \"${providerId}\". Registered connections: ${known}.`\n );\n }\n return found;\n }\n\n private async getSdk(connection: IAiConnectionInline): Promise<IAiSdk> {\n const cacheKey =\n \"id\" in connection\n ? (connection as IAiConnection).id\n : `${connection.sdkName}:${connection.apiKey ?? \"__env__\"}`;\n\n const cached = this.sdkCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const factory = this.sdkFactories.find(f => f.id === connection.sdkName);\n if (!factory) {\n const known = this.sdkFactories.map(f => `\"${f.id}\"`).join(\", \");\n throw new Error(\n `No AI SDK factory found for \"${connection.sdkName}\". Registered factories: ${known}.`\n );\n }\n\n const sdk = await factory.execute(connection.apiKey);\n this.sdkCache.set(cacheKey, sdk);\n return sdk;\n }\n}\n\nexport const Ai = createImplementation({\n abstraction: AiAbstraction,\n implementation: AiImpl,\n dependencies: [\n [AiSdkFactory, { multiple: true }],\n [AiConnectionFactory, { multiple: true }]\n ]\n});\n"],"names":["toAiModel","factory","modelId","modelName","AiImpl","sdkFactories","connectionFactories","Map","params","model","connection","rest","resolvedModel","generateText","streamText","Promise","m","connections","conn","f","undefined","slashIndex","Error","providerId","sdk","found","c","known","cacheKey","cached","Ai","createImplementation","AiAbstraction","AiSdkFactory","AiConnectionFactory"],"mappings":";;;AAaA,SAASA,UAAUC,OAAsB,EAAEC,OAAe,EAAEC,SAAiB;IACzE,OAAO;QACH,YAAYF,QAAQ,EAAE;QACtB,cAAcA,QAAQ,IAAI;QAC1BC;QACAC;IACJ;AACJ;AAEA,MAAMC;IAIF,YACqBC,YAAsC,EACtCC,mBAAoD,CACvE;aAFmBD,YAAY,GAAZA;aACAC,mBAAmB,GAAnBA;aALb,QAAQ,GAAG,IAAIC;aACf,mBAAmB,GAA2B;IAKnD;IAEH,a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BAAE,UAAU;YAAK;SAAE;QAClC;YAACC;YAAqB;gBAAE,UAAU;YAAK;SAAE;KAC5C;AACL"}
|
|
1
|
+
{"version":3,"file":"features/ai/Ai.js","sources":["../../../src/features/ai/Ai.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { generateText } from \"ai\";\nimport { streamText } from \"ai\";\nimport { Ai as AiAbstraction } from \"./abstractions.js\";\nimport { AiSdkFactory } from \"./abstractions.js\";\nimport { AiConnectionFactory } from \"./abstractions.js\";\nimport type { AiGenerateTextParams, AiModel, IAiSdkFactory } from \"./abstractions.js\";\nimport type { AiStreamTextParams } from \"./abstractions.js\";\nimport type { IAiSdk } from \"./abstractions.js\";\nimport type { IAiConnection } from \"./abstractions.js\";\nimport type { IAiConnectionInline } from \"./abstractions.js\";\nimport type { LanguageModel } from \"ai\";\nimport { mdbid } from \"@webiny/utils/mdbid.js\";\nimport { EventPublisher } from \"~/features/eventPublisher/index.js\";\nimport {\n AiBeforeGenerateTextEvent,\n AiAfterGenerateTextEvent,\n AiGenerateTextErrorEvent,\n AiBeforeStreamTextEvent\n} from \"./events.js\";\n\nfunction toAiModel(factory: IAiSdkFactory, modelId: string, modelName: string): AiModel {\n return {\n providerId: factory.id,\n providerName: factory.name,\n modelId,\n modelName\n };\n}\n\nclass AiImpl implements AiAbstraction.Interface {\n private sdkCache = new Map<string, IAiSdk>();\n private resolvedConnections: IAiConnection[] | null = null;\n\n constructor(\n private readonly sdkFactories: AiSdkFactory.Interface[],\n private readonly connectionFactories: AiConnectionFactory.Interface[],\n private readonly eventPublisher: EventPublisher.Interface\n ) {}\n\n async generateText(params: AiGenerateTextParams): ReturnType<typeof generateText> {\n const { model, connection, ...rest } = params;\n const resolvedModel = await this.resolveLanguageModel(model, connection);\n const requestId = mdbid();\n\n await this.eventPublisher.publish(new AiBeforeGenerateTextEvent({ requestId, params }));\n\n const start = performance.now();\n\n try {\n const result = await generateText({ model: resolvedModel, ...rest } as Parameters<\n typeof generateText\n >[0]);\n\n const duration = performance.now() - start;\n\n await this.eventPublisher.publish(\n new AiAfterGenerateTextEvent({ requestId, params, result, duration })\n );\n\n return result;\n } catch (err) {\n const duration = performance.now() - start;\n const error = err instanceof Error ? err : new Error(String(err));\n\n await this.eventPublisher.publish(\n new AiGenerateTextErrorEvent({ requestId, params, error, duration })\n );\n\n throw err;\n }\n }\n\n async streamText(params: AiStreamTextParams): Promise<ReturnType<typeof streamText>> {\n const { model, connection, ...rest } = params;\n const resolvedModel = await this.resolveLanguageModel(model, connection);\n\n await this.eventPublisher.publish(new AiBeforeStreamTextEvent({ params }));\n\n // Cast required: spreading the discriminated Prompt union loses its narrowing.\n return streamText({ model: resolvedModel, ...rest } as Parameters<typeof streamText>[0]);\n }\n\n listModels(): Promise<AiModel[]> {\n return Promise.resolve(\n this.sdkFactories.flatMap(factory =>\n factory.models.map(m => toAiModel(factory, m.id, m.name))\n )\n );\n }\n\n async listModelsByConnections(): Promise<AiModel[]> {\n const connections = await this.getConnections();\n return connections.flatMap(conn => {\n const factory = this.sdkFactories.find(f => f.id === conn.sdkName);\n if (!factory) {\n return [];\n }\n return factory.models.map(m => toAiModel(factory, m.id, m.name));\n });\n }\n\n async listModelsByConnection(connection: string | IAiConnectionInline): Promise<AiModel[]> {\n const conn = await this.resolveConnection(undefined, connection);\n const factory = this.sdkFactories.find(f => f.id === conn.sdkName);\n if (!factory) {\n return [];\n }\n return factory.models.map(m => toAiModel(factory, m.id, m.name));\n }\n\n private async resolveLanguageModel(\n modelId: string,\n connection?: string | IAiConnectionInline\n ): Promise<LanguageModel> {\n const slashIndex = modelId.indexOf(\"/\");\n if (slashIndex === -1) {\n throw new Error(\n `Invalid model ID \"${modelId}\". Expected format: \"<providerId>/<modelId>\" (e.g. \"openai/gpt-4o\").`\n );\n }\n\n const providerId = modelId.slice(0, slashIndex);\n const modelName = modelId.slice(slashIndex + 1);\n\n const conn = await this.resolveConnection(providerId, connection);\n const sdk = await this.getSdk(conn);\n return sdk.languageModel(modelName);\n }\n\n private async getConnections(): Promise<IAiConnection[]> {\n if (!this.resolvedConnections) {\n this.resolvedConnections = await Promise.all(\n this.connectionFactories.map(f => f.execute())\n );\n }\n return this.resolvedConnections;\n }\n\n private async resolveConnection(\n providerId: string | undefined,\n connection?: string | IAiConnectionInline\n ): Promise<IAiConnectionInline> {\n if (typeof connection === \"object\") {\n return connection;\n }\n\n const connections = await this.getConnections();\n\n if (typeof connection === \"string\") {\n const found = connections.find(c => c.id === connection);\n if (!found) {\n const known = connections.map(c => `\"${c.id}\"`).join(\", \");\n throw new Error(\n `Unknown AI connection \"${connection}\". Registered connections: ${known}.`\n );\n }\n return found;\n }\n\n const found = connections.find(c => c.sdkName === providerId);\n if (!found) {\n const known = connections.map(c => `\"${c.id}\" (${c.sdkName})`).join(\", \");\n throw new Error(\n `No AI connection found for provider \"${providerId}\". Registered connections: ${known}.`\n );\n }\n return found;\n }\n\n private async getSdk(connection: IAiConnectionInline): Promise<IAiSdk> {\n const cacheKey =\n \"id\" in connection\n ? (connection as IAiConnection).id\n : `${connection.sdkName}:${connection.apiKey ?? \"__env__\"}`;\n\n const cached = this.sdkCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const factory = this.sdkFactories.find(f => f.id === connection.sdkName);\n if (!factory) {\n const known = this.sdkFactories.map(f => `\"${f.id}\"`).join(\", \");\n throw new Error(\n `No AI SDK factory found for \"${connection.sdkName}\". Registered factories: ${known}.`\n );\n }\n\n const sdk = await factory.execute(connection.apiKey);\n this.sdkCache.set(cacheKey, sdk);\n return sdk;\n }\n}\n\nexport const Ai = createImplementation({\n abstraction: AiAbstraction,\n implementation: AiImpl,\n dependencies: [\n [AiSdkFactory, { multiple: true }],\n [AiConnectionFactory, { multiple: true }],\n EventPublisher\n ]\n});\n"],"names":["toAiModel","factory","modelId","modelName","AiImpl","sdkFactories","connectionFactories","eventPublisher","Map","params","model","connection","rest","resolvedModel","requestId","mdbid","AiBeforeGenerateTextEvent","start","performance","result","generateText","duration","AiAfterGenerateTextEvent","err","error","Error","String","AiGenerateTextErrorEvent","AiBeforeStreamTextEvent","streamText","Promise","m","connections","conn","f","undefined","slashIndex","providerId","sdk","found","c","known","cacheKey","cached","Ai","createImplementation","AiAbstraction","AiSdkFactory","AiConnectionFactory","EventPublisher"],"mappings":";;;;;;AAqBA,SAASA,UAAUC,OAAsB,EAAEC,OAAe,EAAEC,SAAiB;IACzE,OAAO;QACH,YAAYF,QAAQ,EAAE;QACtB,cAAcA,QAAQ,IAAI;QAC1BC;QACAC;IACJ;AACJ;AAEA,MAAMC;IAIF,YACqBC,YAAsC,EACtCC,mBAAoD,EACpDC,cAAwC,CAC3D;aAHmBF,YAAY,GAAZA;aACAC,mBAAmB,GAAnBA;aACAC,cAAc,GAAdA;aANb,QAAQ,GAAG,IAAIC;aACf,mBAAmB,GAA2B;IAMnD;IAEH,MAAM,aAAaC,MAA4B,EAAmC;QAC9E,MAAM,EAAEC,KAAK,EAAEC,UAAU,EAAE,GAAGC,MAAM,GAAGH;QACvC,MAAMI,gBAAgB,MAAM,IAAI,CAAC,oBAAoB,CAACH,OAAOC;QAC7D,MAAMG,YAAYC;QAElB,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,IAAIC,0BAA0B;YAAEF;YAAWL;QAAO;QAEpF,MAAMQ,QAAQC,YAAY,GAAG;QAE7B,IAAI;YACA,MAAMC,SAAS,MAAMC,aAAa;gBAAE,OAAOP;gBAAe,GAAGD,IAAI;YAAC;YAIlE,MAAMS,WAAWH,YAAY,GAAG,KAAKD;YAErC,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAC7B,IAAIK,yBAAyB;gBAAER;gBAAWL;gBAAQU;gBAAQE;YAAS;YAGvE,OAAOF;QACX,EAAE,OAAOI,KAAK;YACV,MAAMF,WAAWH,YAAY,GAAG,KAAKD;YACrC,MAAMO,QAAQD,eAAeE,QAAQF,MAAM,IAAIE,MAAMC,OAAOH;YAE5D,MAAM,IAAI,CAAC,cAAc,CA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,UAAU;YAAK;SAAE;QAClC;YAACC;YAAqB;gBAAE,UAAU;YAAK;SAAE;QACzCC;KACH;AACL"}
|
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
import { createImplementation } from "@webiny/feature/api";
|
|
2
2
|
import { AiSdkFactory } from "./abstractions.js";
|
|
3
3
|
const ANTHROPIC_MODELS = [
|
|
4
|
+
{
|
|
5
|
+
id: "claude-opus-5",
|
|
6
|
+
name: "Claude Opus 5"
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
id: "claude-sonnet-5",
|
|
10
|
+
name: "Claude Sonnet 5"
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
id: "claude-fable-5",
|
|
14
|
+
name: "Claude Fable 5"
|
|
15
|
+
},
|
|
4
16
|
{
|
|
5
17
|
id: "claude-opus-4-7",
|
|
6
18
|
name: "Claude Opus 4.7"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/ai/AnthropicSdkFactory.js","sources":["../../../src/features/ai/AnthropicSdkFactory.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { AiSdkFactory as AiSdkFactoryAbstraction } from \"./abstractions.js\";\nimport type { IAiSdk, IAiSdkModel } from \"./abstractions.js\";\n\nconst ANTHROPIC_MODELS: IAiSdkModel[] = [\n { id: \"claude-opus-4-7\", name: \"Claude Opus 4.7\" },\n { id: \"claude-opus-4-6\", name: \"Claude Opus 4.6\" },\n { id: \"claude-opus-4-5\", name: \"Claude Opus 4.5\" },\n { id: \"claude-sonnet-4-6\", name: \"Claude Sonnet 4.6\" },\n { id: \"claude-sonnet-4-5\", name: \"Claude Sonnet 4.5\" },\n { id: \"claude-haiku-4-5\", name: \"Claude Haiku 4.5\" }\n];\n\nclass AnthropicSdkFactoryImpl implements AiSdkFactoryAbstraction.Interface {\n readonly id = \"anthropic\";\n readonly name = \"Anthropic\";\n readonly models = ANTHROPIC_MODELS;\n\n async execute(apiKey?: string): Promise<IAiSdk> {\n const { createAnthropic } = await import(\"@ai-sdk/anthropic\");\n const provider = createAnthropic({\n apiKey: apiKey ?? process.env.WEBINY_API_ANTHROPIC_API_KEY\n });\n return {\n languageModel: modelId => provider.chat(modelId)\n };\n }\n}\n\nexport const AnthropicSdkFactory = createImplementation({\n abstraction: AiSdkFactoryAbstraction,\n implementation: AnthropicSdkFactoryImpl,\n dependencies: []\n});\n"],"names":["ANTHROPIC_MODELS","AnthropicSdkFactoryImpl","apiKey","createAnthropic","provider","process","modelId","AnthropicSdkFactory","createImplementation","AiSdkFactoryAbstraction"],"mappings":";;AAIA,MAAMA,mBAAkC;IACpC;QAAE,IAAI;QAAmB,MAAM;IAAkB;IACjD;QAAE,IAAI;QAAmB,MAAM;IAAkB;IACjD;QAAE,IAAI;QAAmB,MAAM;IAAkB;IACjD;QAAE,IAAI;QAAqB,MAAM;IAAoB;IACrD;QAAE,IAAI;QAAqB,MAAM;IAAoB;IACrD;QAAE,IAAI;QAAoB,MAAM;IAAmB;CACtD;AAED,MAAMC;IAKF,MAAM,QAAQC,MAAe,EAAmB;QAC5C,MAAM,EAAEC,eAAe,EAAE,GAAG,MAAM,MAAM,CAAC;QACzC,MAAMC,WAAWD,gBAAgB;YAC7B,QAAQD,UAAUG,QAAQ,GAAG,CAAC,4BAA4B;QAC9D;QACA,OAAO;YACH,eAAeC,CAAAA,UAAWF,SAAS,IAAI,CAACE;QAC5C;IACJ;;aAZS,EAAE,GAAG;aACL,IAAI,GAAG;aACP,MAAM,GAAGN;;AAWtB;AAEO,MAAMO,sBAAsBC,qBAAqB;IACpD,aAAaC;IACb,gBAAgBR;IAChB,cAAc,EAAE;AACpB"}
|
|
1
|
+
{"version":3,"file":"features/ai/AnthropicSdkFactory.js","sources":["../../../src/features/ai/AnthropicSdkFactory.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { AiSdkFactory as AiSdkFactoryAbstraction } from \"./abstractions.js\";\nimport type { IAiSdk, IAiSdkModel } from \"./abstractions.js\";\n\nconst ANTHROPIC_MODELS: IAiSdkModel[] = [\n { id: \"claude-opus-5\", name: \"Claude Opus 5\" },\n { id: \"claude-sonnet-5\", name: \"Claude Sonnet 5\" },\n { id: \"claude-fable-5\", name: \"Claude Fable 5\" },\n { id: \"claude-opus-4-7\", name: \"Claude Opus 4.7\" },\n { id: \"claude-opus-4-6\", name: \"Claude Opus 4.6\" },\n { id: \"claude-opus-4-5\", name: \"Claude Opus 4.5\" },\n { id: \"claude-sonnet-4-6\", name: \"Claude Sonnet 4.6\" },\n { id: \"claude-sonnet-4-5\", name: \"Claude Sonnet 4.5\" },\n { id: \"claude-haiku-4-5\", name: \"Claude Haiku 4.5\" }\n];\n\nclass AnthropicSdkFactoryImpl implements AiSdkFactoryAbstraction.Interface {\n readonly id = \"anthropic\";\n readonly name = \"Anthropic\";\n readonly models = ANTHROPIC_MODELS;\n\n async execute(apiKey?: string): Promise<IAiSdk> {\n const { createAnthropic } = await import(\"@ai-sdk/anthropic\");\n const provider = createAnthropic({\n apiKey: apiKey ?? process.env.WEBINY_API_ANTHROPIC_API_KEY\n });\n return {\n languageModel: modelId => provider.chat(modelId)\n };\n }\n}\n\nexport const AnthropicSdkFactory = createImplementation({\n abstraction: AiSdkFactoryAbstraction,\n implementation: AnthropicSdkFactoryImpl,\n dependencies: []\n});\n"],"names":["ANTHROPIC_MODELS","AnthropicSdkFactoryImpl","apiKey","createAnthropic","provider","process","modelId","AnthropicSdkFactory","createImplementation","AiSdkFactoryAbstraction"],"mappings":";;AAIA,MAAMA,mBAAkC;IACpC;QAAE,IAAI;QAAiB,MAAM;IAAgB;IAC7C;QAAE,IAAI;QAAmB,MAAM;IAAkB;IACjD;QAAE,IAAI;QAAkB,MAAM;IAAiB;IAC/C;QAAE,IAAI;QAAmB,MAAM;IAAkB;IACjD;QAAE,IAAI;QAAmB,MAAM;IAAkB;IACjD;QAAE,IAAI;QAAmB,MAAM;IAAkB;IACjD;QAAE,IAAI;QAAqB,MAAM;IAAoB;IACrD;QAAE,IAAI;QAAqB,MAAM;IAAoB;IACrD;QAAE,IAAI;QAAoB,MAAM;IAAmB;CACtD;AAED,MAAMC;IAKF,MAAM,QAAQC,MAAe,EAAmB;QAC5C,MAAM,EAAEC,eAAe,EAAE,GAAG,MAAM,MAAM,CAAC;QACzC,MAAMC,WAAWD,gBAAgB;YAC7B,QAAQD,UAAUG,QAAQ,GAAG,CAAC,4BAA4B;QAC9D;QACA,OAAO;YACH,eAAeC,CAAAA,UAAWF,SAAS,IAAI,CAACE;QAC5C;IACJ;;aAZS,EAAE,GAAG;aACL,IAAI,GAAG;aACP,MAAM,GAAGN;;AAWtB;AAEO,MAAMO,sBAAsBC,qBAAqB;IACpD,aAAaC;IACb,gBAAgBR;IAChB,cAAc,EAAE;AACpB"}
|
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
import { createImplementation } from "@webiny/feature/api";
|
|
2
2
|
import { AiSdkFactory } from "./abstractions.js";
|
|
3
3
|
const OPENAI_MODELS = [
|
|
4
|
+
{
|
|
5
|
+
id: "gpt-5.6-sol",
|
|
6
|
+
name: "GPT-5.6 Sol"
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
id: "gpt-5.6-terra",
|
|
10
|
+
name: "GPT-5.6 Terra"
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
id: "gpt-5.6-luna",
|
|
14
|
+
name: "GPT-5.6 Luna"
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
id: "gpt-5.5",
|
|
18
|
+
name: "GPT-5.5"
|
|
19
|
+
},
|
|
4
20
|
{
|
|
5
21
|
id: "gpt-5.4",
|
|
6
22
|
name: "GPT-5.4"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/ai/OpenAiSdkFactory.js","sources":["../../../src/features/ai/OpenAiSdkFactory.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { AiSdkFactory as AiSdkFactoryAbstraction } from \"./abstractions.js\";\nimport type { IAiSdk, IAiSdkModel } from \"./abstractions.js\";\n\nconst OPENAI_MODELS: IAiSdkModel[] = [\n { id: \"gpt-5.4\", name: \"GPT-5.4\" },\n { id: \"gpt-5.4-mini\", name: \"GPT-5.4 Mini\" },\n { id: \"gpt-5.4-nano\", name: \"GPT-5.4 Nano\" },\n { id: \"gpt-5.4-pro\", name: \"GPT-5.4 Pro\" },\n { id: \"gpt-5.3-chat-latest\", name: \"GPT-5.3 Chat\" },\n { id: \"gpt-4.1\", name: \"GPT-4.1\" },\n { id: \"gpt-4.1-mini\", name: \"GPT-4.1 Mini\" },\n { id: \"gpt-4.1-nano\", name: \"GPT-4.1 Nano\" },\n { id: \"gpt-4o\", name: \"GPT-4o\" },\n { id: \"gpt-4o-mini\", name: \"GPT-4o Mini\" },\n { id: \"o4-mini\", name: \"o4 Mini\" },\n { id: \"o3\", name: \"o3\" }\n];\n\nclass OpenAiSdkFactoryImpl implements AiSdkFactoryAbstraction.Interface {\n readonly id = \"openai\";\n readonly name = \"OpenAI\";\n readonly models = OPENAI_MODELS;\n\n async execute(apiKey?: string): Promise<IAiSdk> {\n const { createOpenAI } = await import(\"@ai-sdk/openai\");\n const provider = createOpenAI({\n apiKey: apiKey ?? process.env.WEBINY_API_OPENAI_API_KEY\n });\n return {\n languageModel: modelId => provider.chat(modelId)\n };\n }\n}\n\nexport const OpenAiSdkFactory = createImplementation({\n abstraction: AiSdkFactoryAbstraction,\n implementation: OpenAiSdkFactoryImpl,\n dependencies: []\n});\n"],"names":["OPENAI_MODELS","OpenAiSdkFactoryImpl","apiKey","createOpenAI","provider","process","modelId","OpenAiSdkFactory","createImplementation","AiSdkFactoryAbstraction"],"mappings":";;AAIA,MAAMA,gBAA+B;IACjC;QAAE,IAAI;QAAW,MAAM;IAAU;IACjC;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAe,MAAM;IAAc;IACzC;QAAE,IAAI;QAAuB,MAAM;IAAe;IAClD;QAAE,IAAI;QAAW,MAAM;IAAU;IACjC;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAU,MAAM;IAAS;IAC/B;QAAE,IAAI;QAAe,MAAM;IAAc;IACzC;QAAE,IAAI;QAAW,MAAM;IAAU;IACjC;QAAE,IAAI;QAAM,MAAM;IAAK;CAC1B;AAED,MAAMC;IAKF,MAAM,QAAQC,MAAe,EAAmB;QAC5C,MAAM,EAAEC,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC;QACtC,MAAMC,WAAWD,aAAa;YAC1B,QAAQD,UAAUG,QAAQ,GAAG,CAAC,yBAAyB;QAC3D;QACA,OAAO;YACH,eAAeC,CAAAA,UAAWF,SAAS,IAAI,CAACE;QAC5C;IACJ;;aAZS,EAAE,GAAG;aACL,IAAI,GAAG;aACP,MAAM,GAAGN;;AAWtB;AAEO,MAAMO,mBAAmBC,qBAAqB;IACjD,aAAaC;IACb,gBAAgBR;IAChB,cAAc,EAAE;AACpB"}
|
|
1
|
+
{"version":3,"file":"features/ai/OpenAiSdkFactory.js","sources":["../../../src/features/ai/OpenAiSdkFactory.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { AiSdkFactory as AiSdkFactoryAbstraction } from \"./abstractions.js\";\nimport type { IAiSdk, IAiSdkModel } from \"./abstractions.js\";\n\nconst OPENAI_MODELS: IAiSdkModel[] = [\n { id: \"gpt-5.6-sol\", name: \"GPT-5.6 Sol\" },\n { id: \"gpt-5.6-terra\", name: \"GPT-5.6 Terra\" },\n { id: \"gpt-5.6-luna\", name: \"GPT-5.6 Luna\" },\n { id: \"gpt-5.5\", name: \"GPT-5.5\" },\n { id: \"gpt-5.4\", name: \"GPT-5.4\" },\n { id: \"gpt-5.4-mini\", name: \"GPT-5.4 Mini\" },\n { id: \"gpt-5.4-nano\", name: \"GPT-5.4 Nano\" },\n { id: \"gpt-5.4-pro\", name: \"GPT-5.4 Pro\" },\n { id: \"gpt-5.3-chat-latest\", name: \"GPT-5.3 Chat\" },\n { id: \"gpt-4.1\", name: \"GPT-4.1\" },\n { id: \"gpt-4.1-mini\", name: \"GPT-4.1 Mini\" },\n { id: \"gpt-4.1-nano\", name: \"GPT-4.1 Nano\" },\n { id: \"gpt-4o\", name: \"GPT-4o\" },\n { id: \"gpt-4o-mini\", name: \"GPT-4o Mini\" },\n { id: \"o4-mini\", name: \"o4 Mini\" },\n { id: \"o3\", name: \"o3\" }\n];\n\nclass OpenAiSdkFactoryImpl implements AiSdkFactoryAbstraction.Interface {\n readonly id = \"openai\";\n readonly name = \"OpenAI\";\n readonly models = OPENAI_MODELS;\n\n async execute(apiKey?: string): Promise<IAiSdk> {\n const { createOpenAI } = await import(\"@ai-sdk/openai\");\n const provider = createOpenAI({\n apiKey: apiKey ?? process.env.WEBINY_API_OPENAI_API_KEY\n });\n return {\n languageModel: modelId => provider.chat(modelId)\n };\n }\n}\n\nexport const OpenAiSdkFactory = createImplementation({\n abstraction: AiSdkFactoryAbstraction,\n implementation: OpenAiSdkFactoryImpl,\n dependencies: []\n});\n"],"names":["OPENAI_MODELS","OpenAiSdkFactoryImpl","apiKey","createOpenAI","provider","process","modelId","OpenAiSdkFactory","createImplementation","AiSdkFactoryAbstraction"],"mappings":";;AAIA,MAAMA,gBAA+B;IACjC;QAAE,IAAI;QAAe,MAAM;IAAc;IACzC;QAAE,IAAI;QAAiB,MAAM;IAAgB;IAC7C;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAW,MAAM;IAAU;IACjC;QAAE,IAAI;QAAW,MAAM;IAAU;IACjC;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAe,MAAM;IAAc;IACzC;QAAE,IAAI;QAAuB,MAAM;IAAe;IAClD;QAAE,IAAI;QAAW,MAAM;IAAU;IACjC;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAgB,MAAM;IAAe;IAC3C;QAAE,IAAI;QAAU,MAAM;IAAS;IAC/B;QAAE,IAAI;QAAe,MAAM;IAAc;IACzC;QAAE,IAAI;QAAW,MAAM;IAAU;IACjC;QAAE,IAAI;QAAM,MAAM;IAAK;CAC1B;AAED,MAAMC;IAKF,MAAM,QAAQC,MAAe,EAAmB;QAC5C,MAAM,EAAEC,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC;QACtC,MAAMC,WAAWD,aAAa;YAC1B,QAAQD,UAAUG,QAAQ,GAAG,CAAC,yBAAyB;QAC3D;QACA,OAAO;YACH,eAAeC,CAAAA,UAAWF,SAAS,IAAI,CAACE;QAC5C;IACJ;;aAZS,EAAE,GAAG;aACL,IAAI,GAAG;aACP,MAAM,GAAGN;;AAWtB;AAEO,MAAMO,mBAAmBC,qBAAqB;IACjD,aAAaC;IACb,gBAAgBR;IAChB,cAAc,EAAE;AACpB"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { TextExtractor, type TextExtractorResult } from "./abstractions.js";
|
|
2
|
+
declare class TextExtractorImpl implements TextExtractor.Interface {
|
|
3
|
+
canExtract(mimeType: string): boolean;
|
|
4
|
+
extract(buffer: Buffer, mimeType: string): Promise<TextExtractorResult>;
|
|
5
|
+
}
|
|
6
|
+
export declare const DefaultTextExtractor: typeof TextExtractorImpl & {
|
|
7
|
+
__abstraction: import("@webiny/di").Abstraction<import("./abstractions.js").ITextExtractor>;
|
|
8
|
+
};
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { TextExtractor } from "./abstractions.js";
|
|
2
|
+
import { extractDocxText } from "./parsers/docxParser.js";
|
|
3
|
+
const TEXT_MIME_PREFIX = "text/";
|
|
4
|
+
const SUPPORTED_MIME_TYPES = new Set([
|
|
5
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
6
|
+
"application/json"
|
|
7
|
+
]);
|
|
8
|
+
class TextExtractorImpl {
|
|
9
|
+
canExtract(mimeType) {
|
|
10
|
+
return mimeType.startsWith(TEXT_MIME_PREFIX) || SUPPORTED_MIME_TYPES.has(mimeType);
|
|
11
|
+
}
|
|
12
|
+
async extract(buffer, mimeType) {
|
|
13
|
+
if (mimeType.startsWith(TEXT_MIME_PREFIX) || "application/json" === mimeType) return {
|
|
14
|
+
text: buffer.toString("utf-8")
|
|
15
|
+
};
|
|
16
|
+
if ("application/vnd.openxmlformats-officedocument.wordprocessingml.document" === mimeType) return {
|
|
17
|
+
text: await extractDocxText(buffer)
|
|
18
|
+
};
|
|
19
|
+
throw new Error(`Unsupported MIME type: ${mimeType}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const DefaultTextExtractor = TextExtractor.createImplementation({
|
|
23
|
+
implementation: TextExtractorImpl,
|
|
24
|
+
dependencies: []
|
|
25
|
+
});
|
|
26
|
+
export { DefaultTextExtractor };
|
|
27
|
+
|
|
28
|
+
//# sourceMappingURL=DefaultTextExtractor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/ai/TextExtractor/DefaultTextExtractor.js","sources":["../../../../src/features/ai/TextExtractor/DefaultTextExtractor.ts"],"sourcesContent":["import { TextExtractor, type TextExtractorResult } from \"./abstractions.js\";\nimport { extractDocxText } from \"./parsers/docxParser.js\";\n\nconst TEXT_MIME_PREFIX = \"text/\";\n\nconst SUPPORTED_MIME_TYPES = new Set([\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \"application/json\"\n]);\n\nclass TextExtractorImpl implements TextExtractor.Interface {\n canExtract(mimeType: string): boolean {\n return mimeType.startsWith(TEXT_MIME_PREFIX) || SUPPORTED_MIME_TYPES.has(mimeType);\n }\n\n async extract(buffer: Buffer, mimeType: string): Promise<TextExtractorResult> {\n if (mimeType.startsWith(TEXT_MIME_PREFIX) || mimeType === \"application/json\") {\n return { text: buffer.toString(\"utf-8\") };\n }\n\n if (\n mimeType === \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\"\n ) {\n return { text: await extractDocxText(buffer) };\n }\n\n throw new Error(`Unsupported MIME type: ${mimeType}`);\n }\n}\n\nexport const DefaultTextExtractor = TextExtractor.createImplementation({\n implementation: TextExtractorImpl,\n dependencies: []\n});\n"],"names":["TEXT_MIME_PREFIX","SUPPORTED_MIME_TYPES","Set","TextExtractorImpl","mimeType","buffer","extractDocxText","Error","DefaultTextExtractor","TextExtractor"],"mappings":";;AAGA,MAAMA,mBAAmB;AAEzB,MAAMC,uBAAuB,IAAIC,IAAI;IACjC;IACA;CACH;AAED,MAAMC;IACF,WAAWC,QAAgB,EAAW;QAClC,OAAOA,SAAS,UAAU,CAACJ,qBAAqBC,qBAAqB,GAAG,CAACG;IAC7E;IAEA,MAAM,QAAQC,MAAc,EAAED,QAAgB,EAAgC;QAC1E,IAAIA,SAAS,UAAU,CAACJ,qBAAqBI,AAAa,uBAAbA,UACzC,OAAO;YAAE,MAAMC,OAAO,QAAQ,CAAC;QAAS;QAG5C,IACID,AAAa,8EAAbA,UAEA,OAAO;YAAE,MAAM,MAAME,gBAAgBD;QAAQ;QAGjD,MAAM,IAAIE,MAAM,CAAC,uBAAuB,EAAEH,UAAU;IACxD;AACJ;AAEO,MAAMI,uBAAuBC,cAAc,oBAAoB,CAAC;IACnE,gBAAgBN;IAChB,cAAc,EAAE;AACpB"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface TextExtractorResult {
|
|
2
|
+
text: string;
|
|
3
|
+
}
|
|
4
|
+
export interface ITextExtractor {
|
|
5
|
+
canExtract(mimeType: string): boolean;
|
|
6
|
+
extract(buffer: Buffer, mimeType: string): Promise<TextExtractorResult>;
|
|
7
|
+
}
|
|
8
|
+
export declare const TextExtractor: import("@webiny/di").Abstraction<ITextExtractor>;
|
|
9
|
+
export declare namespace TextExtractor {
|
|
10
|
+
type Interface = ITextExtractor;
|
|
11
|
+
type Result = TextExtractorResult;
|
|
12
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/ai/TextExtractor/abstractions.js","sources":["../../../../src/features/ai/TextExtractor/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\n\nexport interface TextExtractorResult {\n text: string;\n}\n\nexport interface ITextExtractor {\n canExtract(mimeType: string): boolean;\n extract(buffer: Buffer, mimeType: string): Promise<TextExtractorResult>;\n}\n\nexport const TextExtractor = createAbstraction<ITextExtractor>(\"TextExtractor\");\n\nexport namespace TextExtractor {\n export type Interface = ITextExtractor;\n export type Result = TextExtractorResult;\n}\n"],"names":["TextExtractor","createAbstraction"],"mappings":";AAWO,MAAMA,gBAAgBC,kBAAkC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function extractDocxText(buffer: Buffer): Promise<string>;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { inflateRawSync } from "node:zlib";
|
|
2
|
+
async function extractDocxText(buffer) {
|
|
3
|
+
const xml = extractFileFromZip(buffer, "word/document.xml");
|
|
4
|
+
if (!xml) throw new Error("Invalid DOCX: word/document.xml not found.");
|
|
5
|
+
const stylesXml = extractFileFromZip(buffer, "word/styles.xml");
|
|
6
|
+
const styleMap = stylesXml ? buildStyleMap(stylesXml) : new Map();
|
|
7
|
+
return convertToMarkdown(xml, styleMap);
|
|
8
|
+
}
|
|
9
|
+
function buildStyleMap(stylesXml) {
|
|
10
|
+
const map = new Map();
|
|
11
|
+
const styleRegex = /<w:style\s[^>]*w:styleId="([^"]*)"[^>]*>[\s\S]*?<\/w:style>/g;
|
|
12
|
+
let match;
|
|
13
|
+
while(null !== (match = styleRegex.exec(stylesXml))){
|
|
14
|
+
const styleId = match[1];
|
|
15
|
+
const block = match[0];
|
|
16
|
+
const nameMatch = block.match(/<w:name\s+w:val="([^"]*)"/);
|
|
17
|
+
if (nameMatch) map.set(styleId, nameMatch[1]);
|
|
18
|
+
}
|
|
19
|
+
return map;
|
|
20
|
+
}
|
|
21
|
+
function getHeadingLevel(paragraphXml, styleMap) {
|
|
22
|
+
const styleMatch = paragraphXml.match(/<w:pStyle\s+w:val="([^"]*)"/);
|
|
23
|
+
if (!styleMatch) return 0;
|
|
24
|
+
const styleId = styleMatch[1];
|
|
25
|
+
const directMatch = styleId.match(/^[Hh]eading(\d)$/);
|
|
26
|
+
if (directMatch) return parseInt(directMatch[1], 10);
|
|
27
|
+
const styleName = styleMap.get(styleId) ?? "";
|
|
28
|
+
const nameMatch = styleName.match(/^[Hh]eading\s*(\d)$/);
|
|
29
|
+
if (nameMatch) return parseInt(nameMatch[1], 10);
|
|
30
|
+
if (/title/i.test(styleName) || /title/i.test(styleId)) return 1;
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
function isListItem(paragraphXml) {
|
|
34
|
+
return /<w:numId\s/.test(paragraphXml);
|
|
35
|
+
}
|
|
36
|
+
function extractRunMarkdown(runXml) {
|
|
37
|
+
const textRegex = /<w:t(?:\s[^>]*)?>([^<]*)<\/w:t>/g;
|
|
38
|
+
const texts = [];
|
|
39
|
+
let match;
|
|
40
|
+
while(null !== (match = textRegex.exec(runXml)))texts.push(match[1]);
|
|
41
|
+
if (0 === texts.length) return "";
|
|
42
|
+
const text = texts.join("");
|
|
43
|
+
const isBold = /<w:b[\s/>]/.test(runXml) && !/<w:b\s+w:val="(false|0)"/.test(runXml);
|
|
44
|
+
const isItalic = /<w:i[\s/>]/.test(runXml) && !/<w:i\s+w:val="(false|0)"/.test(runXml);
|
|
45
|
+
if (isBold && isItalic) return `***${text}***`;
|
|
46
|
+
if (isBold) return `**${text}**`;
|
|
47
|
+
if (isItalic) return `*${text}*`;
|
|
48
|
+
return text;
|
|
49
|
+
}
|
|
50
|
+
function convertToMarkdown(xml, styleMap) {
|
|
51
|
+
const paragraphs = [];
|
|
52
|
+
const paragraphRegex = /<w:p[\s>][\s\S]*?<\/w:p>/g;
|
|
53
|
+
let paragraphMatch;
|
|
54
|
+
while(null !== (paragraphMatch = paragraphRegex.exec(xml))){
|
|
55
|
+
const paragraphXml = paragraphMatch[0];
|
|
56
|
+
const runRegex = /<w:r[\s>][\s\S]*?<\/w:r>/g;
|
|
57
|
+
const runs = [];
|
|
58
|
+
let runMatch;
|
|
59
|
+
while(null !== (runMatch = runRegex.exec(paragraphXml))){
|
|
60
|
+
const md = extractRunMarkdown(runMatch[0]);
|
|
61
|
+
if (md) runs.push(md);
|
|
62
|
+
}
|
|
63
|
+
if (0 === runs.length) continue;
|
|
64
|
+
let line = runs.join("");
|
|
65
|
+
const headingLevel = getHeadingLevel(paragraphXml, styleMap);
|
|
66
|
+
if (headingLevel > 0 && headingLevel <= 6) line = `${"#".repeat(headingLevel)} ${line}`;
|
|
67
|
+
else if (isListItem(paragraphXml)) line = `- ${line}`;
|
|
68
|
+
paragraphs.push(line);
|
|
69
|
+
}
|
|
70
|
+
return paragraphs.join("\n\n");
|
|
71
|
+
}
|
|
72
|
+
function extractFileFromZip(buffer, targetPath) {
|
|
73
|
+
const eocdOffset = findEocd(buffer);
|
|
74
|
+
if (-1 === eocdOffset) throw new Error("Invalid ZIP: End of Central Directory not found.");
|
|
75
|
+
const cdOffset = buffer.readUInt32LE(eocdOffset + 16);
|
|
76
|
+
const cdSize = buffer.readUInt32LE(eocdOffset + 12);
|
|
77
|
+
const cdEnd = cdOffset + cdSize;
|
|
78
|
+
let offset = cdOffset;
|
|
79
|
+
while(offset < cdEnd){
|
|
80
|
+
const sig = buffer.readUInt32LE(offset);
|
|
81
|
+
if (0x02014b50 !== sig) break;
|
|
82
|
+
const compressionMethod = buffer.readUInt16LE(offset + 10);
|
|
83
|
+
const compressedSize = buffer.readUInt32LE(offset + 20);
|
|
84
|
+
const fileNameLen = buffer.readUInt16LE(offset + 28);
|
|
85
|
+
const extraLen = buffer.readUInt16LE(offset + 30);
|
|
86
|
+
const commentLen = buffer.readUInt16LE(offset + 32);
|
|
87
|
+
const localHeaderOffset = buffer.readUInt32LE(offset + 42);
|
|
88
|
+
const fileName = buffer.toString("utf-8", offset + 46, offset + 46 + fileNameLen);
|
|
89
|
+
if (fileName === targetPath) return readLocalFile(buffer, localHeaderOffset, compressionMethod, compressedSize);
|
|
90
|
+
offset += 46 + fileNameLen + extraLen + commentLen;
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
function readLocalFile(buffer, offset, compressionMethod, compressedSize) {
|
|
95
|
+
const sig = buffer.readUInt32LE(offset);
|
|
96
|
+
if (0x04034b50 !== sig) throw new Error("Invalid ZIP: bad local file header.");
|
|
97
|
+
const localFileNameLen = buffer.readUInt16LE(offset + 26);
|
|
98
|
+
const localExtraLen = buffer.readUInt16LE(offset + 28);
|
|
99
|
+
const dataOffset = offset + 30 + localFileNameLen + localExtraLen;
|
|
100
|
+
const raw = buffer.subarray(dataOffset, dataOffset + compressedSize);
|
|
101
|
+
if (0 === compressionMethod) return raw.toString("utf-8");
|
|
102
|
+
if (8 === compressionMethod) return inflateRawSync(raw).toString("utf-8");
|
|
103
|
+
throw new Error(`Unsupported ZIP compression method: ${compressionMethod}`);
|
|
104
|
+
}
|
|
105
|
+
function findEocd(buffer) {
|
|
106
|
+
for(let i = buffer.length - 22; i >= Math.max(0, buffer.length - 65557); i--)if (0x06054b50 === buffer.readUInt32LE(i)) return i;
|
|
107
|
+
return -1;
|
|
108
|
+
}
|
|
109
|
+
export { extractDocxText };
|
|
110
|
+
|
|
111
|
+
//# sourceMappingURL=docxParser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/ai/TextExtractor/parsers/docxParser.js","sources":["../../../../../src/features/ai/TextExtractor/parsers/docxParser.ts"],"sourcesContent":["import { inflateRawSync } from \"node:zlib\";\n\nexport async function extractDocxText(buffer: Buffer): Promise<string> {\n const xml = extractFileFromZip(buffer, \"word/document.xml\");\n if (!xml) {\n throw new Error(\"Invalid DOCX: word/document.xml not found.\");\n }\n\n const stylesXml = extractFileFromZip(buffer, \"word/styles.xml\");\n const styleMap = stylesXml ? buildStyleMap(stylesXml) : new Map<string, string>();\n\n return convertToMarkdown(xml, styleMap);\n}\n\nfunction buildStyleMap(stylesXml: string): Map<string, string> {\n const map = new Map<string, string>();\n const styleRegex = /<w:style\\s[^>]*w:styleId=\"([^\"]*)\"[^>]*>[\\s\\S]*?<\\/w:style>/g;\n let match: RegExpExecArray | null;\n\n while ((match = styleRegex.exec(stylesXml)) !== null) {\n const styleId = match[1];\n const block = match[0];\n const nameMatch = block.match(/<w:name\\s+w:val=\"([^\"]*)\"/);\n if (nameMatch) {\n map.set(styleId, nameMatch[1]);\n }\n }\n\n return map;\n}\n\nfunction getHeadingLevel(paragraphXml: string, styleMap: Map<string, string>): number {\n const styleMatch = paragraphXml.match(/<w:pStyle\\s+w:val=\"([^\"]*)\"/);\n if (!styleMatch) {\n return 0;\n }\n\n const styleId = styleMatch[1];\n\n const directMatch = styleId.match(/^[Hh]eading(\\d)$/);\n if (directMatch) {\n return parseInt(directMatch[1], 10);\n }\n\n const styleName = styleMap.get(styleId) ?? \"\";\n const nameMatch = styleName.match(/^[Hh]eading\\s*(\\d)$/);\n if (nameMatch) {\n return parseInt(nameMatch[1], 10);\n }\n\n if (/title/i.test(styleName) || /title/i.test(styleId)) {\n return 1;\n }\n\n return 0;\n}\n\nfunction isListItem(paragraphXml: string): boolean {\n return /<w:numId\\s/.test(paragraphXml);\n}\n\nfunction extractRunMarkdown(runXml: string): string {\n const textRegex = /<w:t(?:\\s[^>]*)?>([^<]*)<\\/w:t>/g;\n const texts: string[] = [];\n let match: RegExpExecArray | null;\n while ((match = textRegex.exec(runXml)) !== null) {\n texts.push(match[1]);\n }\n if (texts.length === 0) {\n return \"\";\n }\n\n const text = texts.join(\"\");\n const isBold = /<w:b[\\s/>]/.test(runXml) && !/<w:b\\s+w:val=\"(false|0)\"/.test(runXml);\n const isItalic = /<w:i[\\s/>]/.test(runXml) && !/<w:i\\s+w:val=\"(false|0)\"/.test(runXml);\n\n if (isBold && isItalic) {\n return `***${text}***`;\n }\n if (isBold) {\n return `**${text}**`;\n }\n if (isItalic) {\n return `*${text}*`;\n }\n return text;\n}\n\nfunction convertToMarkdown(xml: string, styleMap: Map<string, string>): string {\n const paragraphs: string[] = [];\n const paragraphRegex = /<w:p[\\s>][\\s\\S]*?<\\/w:p>/g;\n let paragraphMatch: RegExpExecArray | null;\n\n while ((paragraphMatch = paragraphRegex.exec(xml)) !== null) {\n const paragraphXml = paragraphMatch[0];\n\n const runRegex = /<w:r[\\s>][\\s\\S]*?<\\/w:r>/g;\n const runs: string[] = [];\n let runMatch: RegExpExecArray | null;\n while ((runMatch = runRegex.exec(paragraphXml)) !== null) {\n const md = extractRunMarkdown(runMatch[0]);\n if (md) {\n runs.push(md);\n }\n }\n\n if (runs.length === 0) {\n continue;\n }\n\n let line = runs.join(\"\");\n const headingLevel = getHeadingLevel(paragraphXml, styleMap);\n\n if (headingLevel > 0 && headingLevel <= 6) {\n line = `${\"#\".repeat(headingLevel)} ${line}`;\n } else if (isListItem(paragraphXml)) {\n line = `- ${line}`;\n }\n\n paragraphs.push(line);\n }\n\n return paragraphs.join(\"\\n\\n\");\n}\n\n// --- ZIP utilities (unchanged) ---\n\nfunction extractFileFromZip(buffer: Buffer, targetPath: string): string | null {\n const eocdOffset = findEocd(buffer);\n if (eocdOffset === -1) {\n throw new Error(\"Invalid ZIP: End of Central Directory not found.\");\n }\n\n const cdOffset = buffer.readUInt32LE(eocdOffset + 16);\n const cdSize = buffer.readUInt32LE(eocdOffset + 12);\n const cdEnd = cdOffset + cdSize;\n let offset = cdOffset;\n\n while (offset < cdEnd) {\n const sig = buffer.readUInt32LE(offset);\n if (sig !== 0x02014b50) {\n break;\n }\n\n const compressionMethod = buffer.readUInt16LE(offset + 10);\n const compressedSize = buffer.readUInt32LE(offset + 20);\n const fileNameLen = buffer.readUInt16LE(offset + 28);\n const extraLen = buffer.readUInt16LE(offset + 30);\n const commentLen = buffer.readUInt16LE(offset + 32);\n const localHeaderOffset = buffer.readUInt32LE(offset + 42);\n const fileName = buffer.toString(\"utf-8\", offset + 46, offset + 46 + fileNameLen);\n\n if (fileName === targetPath) {\n return readLocalFile(buffer, localHeaderOffset, compressionMethod, compressedSize);\n }\n\n offset += 46 + fileNameLen + extraLen + commentLen;\n }\n\n return null;\n}\n\nfunction readLocalFile(\n buffer: Buffer,\n offset: number,\n compressionMethod: number,\n compressedSize: number\n): string {\n const sig = buffer.readUInt32LE(offset);\n if (sig !== 0x04034b50) {\n throw new Error(\"Invalid ZIP: bad local file header.\");\n }\n\n const localFileNameLen = buffer.readUInt16LE(offset + 26);\n const localExtraLen = buffer.readUInt16LE(offset + 28);\n const dataOffset = offset + 30 + localFileNameLen + localExtraLen;\n\n const raw = buffer.subarray(dataOffset, dataOffset + compressedSize);\n\n if (compressionMethod === 0) {\n return raw.toString(\"utf-8\");\n }\n\n if (compressionMethod === 8) {\n return inflateRawSync(raw).toString(\"utf-8\");\n }\n\n throw new Error(`Unsupported ZIP compression method: ${compressionMethod}`);\n}\n\nfunction findEocd(buffer: Buffer): number {\n for (let i = buffer.length - 22; i >= Math.max(0, buffer.length - 65557); i--) {\n if (buffer.readUInt32LE(i) === 0x06054b50) {\n return i;\n }\n }\n return -1;\n}\n"],"names":["extractDocxText","buffer","xml","extractFileFromZip","Error","stylesXml","styleMap","buildStyleMap","Map","convertToMarkdown","map","styleRegex","match","styleId","block","nameMatch","getHeadingLevel","paragraphXml","styleMatch","directMatch","parseInt","styleName","isListItem","extractRunMarkdown","runXml","textRegex","texts","text","isBold","isItalic","paragraphs","paragraphRegex","paragraphMatch","runRegex","runs","runMatch","md","line","headingLevel","targetPath","eocdOffset","findEocd","cdOffset","cdSize","cdEnd","offset","sig","compressionMethod","compressedSize","fileNameLen","extraLen","commentLen","localHeaderOffset","fileName","readLocalFile","localFileNameLen","localExtraLen","dataOffset","raw","inflateRawSync","i","Math"],"mappings":";AAEO,eAAeA,gBAAgBC,MAAc;IAChD,MAAMC,MAAMC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AAmBC;IAEpD,MAAME,MAAMzD,OAAO,QAAQ,CAACwD,YAAYA,aAAaT;IAErD,IAAID,AAAsB,MAAtBA,mBACA,OAAOW,IAAI,QAAQ,CAAC;IAGxB,IAAIX,AAAsB,MAAtBA,mBACA,OAAOY,eAAeD,KAAK,QAAQ,CAAC;IAGxC,MAAM,IAAItD,MAAM,CAAC,oCAAoC,EAAE2C,mBAAmB;AAC9E;AAEA,SAASN,SAASxC,MAAc;IAC5B,IAAK,IAAI2D,IAAI3D,OAAO,MAAM,GAAG,IAAI2D,KAAKC,KAAK,GAAG,CAAC,GAAG5D,OAAO,MAAM,GAAG,QAAQ2D,IACtE,IAAI3D,AAA2B,eAA3BA,OAAO,YAAY,CAAC2D,IACpB,OAAOA;IAGf,OAAO;AACX"}
|
|
@@ -70,16 +70,35 @@ export declare namespace Ai {
|
|
|
70
70
|
type GenerateTextParams = AiGenerateTextParams;
|
|
71
71
|
type StreamTextParams = AiStreamTextParams;
|
|
72
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Behavioural hints about a tool. Purely advisory — they never replace a permission check.
|
|
75
|
+
* Names mirror the MCP tool annotations so they can be forwarded verbatim to MCP clients,
|
|
76
|
+
* which use them to decide what to auto-approve and what to confirm with the user.
|
|
77
|
+
*/
|
|
78
|
+
export interface IAiSdkToolAnnotations {
|
|
79
|
+
/** Tool does not modify state. */
|
|
80
|
+
readOnlyHint?: boolean;
|
|
81
|
+
/** Tool may perform destructive updates (only meaningful when not read-only). */
|
|
82
|
+
destructiveHint?: boolean;
|
|
83
|
+
/** Repeated calls with the same arguments have no additional effect. */
|
|
84
|
+
idempotentHint?: boolean;
|
|
85
|
+
/** Tool interacts with entities outside its own closed world. */
|
|
86
|
+
openWorldHint?: boolean;
|
|
87
|
+
}
|
|
73
88
|
export interface IAiSdkTool<TInput = any> {
|
|
74
89
|
readonly name: string;
|
|
75
90
|
readonly description: string;
|
|
76
91
|
readonly inputSchema: FlexibleSchema<TInput>;
|
|
92
|
+
/** Human-friendly display name. Falls back to `name` when omitted. */
|
|
93
|
+
readonly title?: string;
|
|
94
|
+
readonly annotations?: IAiSdkToolAnnotations;
|
|
77
95
|
execute(input: TInput): Promise<unknown>;
|
|
78
96
|
}
|
|
79
97
|
/** A single tool that can be provided to AI generateText/streamText calls. */
|
|
80
98
|
export declare const AiSdkTool: import("@webiny/di").Abstraction<IAiSdkTool<any>>;
|
|
81
99
|
export declare namespace AiSdkTool {
|
|
82
100
|
type Interface = IAiSdkTool;
|
|
101
|
+
type Annotations = IAiSdkToolAnnotations;
|
|
83
102
|
}
|
|
84
103
|
export interface IAiSdkTools {
|
|
85
104
|
getToolSet(): ToolSet;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/ai/abstractions.js","sources":["../../../src/features/ai/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { generateText } from \"ai\";\nimport type { streamText } from \"ai\";\nimport type { LanguageModel } from \"ai\";\nimport type { FlexibleSchema, ToolSet } from \"ai\";\n\n// AiSdk\n\nexport interface IAiSdkModel {\n id: string; // raw model id, e.g. \"claude-sonnet-4-5\"\n name: string; // human-friendly name, e.g. \"Claude Sonnet 4.5\"\n}\n\nexport interface IAiSdk {\n languageModel(modelId: string): LanguageModel;\n}\n\n/** A single AI SDK instance (e.g. OpenAI, Anthropic) that resolves model instances. */\nexport const AiSdk = createAbstraction<IAiSdk>(\"AiSdk\");\n\nexport namespace AiSdk {\n export type Interface = IAiSdk;\n}\n\n// AiSdkFactory\n\nexport interface IAiSdkFactory {\n readonly id: string; // machine id, e.g. \"anthropic\"\n readonly name: string; // human-friendly name, e.g. \"Anthropic\"\n readonly models: readonly IAiSdkModel[]; // static model list, no API call needed\n execute(apiKey?: string): Promise<IAiSdk>;\n}\n\n/** Factory that asynchronously initialises an AI SDK. Register one per provider namespace. */\nexport const AiSdkFactory = createAbstraction<IAiSdkFactory>(\"AiSdkFactory\");\n\nexport namespace AiSdkFactory {\n export type Interface = IAiSdkFactory;\n}\n\n// AiConnection\n\nexport interface IAiConnectionInline {\n readonly sdkName: string;\n readonly apiKey?: string;\n}\n\nexport interface IAiConnection extends IAiConnectionInline {\n readonly id: string;\n}\n\n// AiConnectionFactory\n\nexport interface IAiConnectionFactory {\n execute(): Promise<IAiConnection>;\n}\n\n/** Factory that asynchronously produces an AiConnection. */\nexport const AiConnectionFactory = createAbstraction<IAiConnectionFactory>(\"AiConnectionFactory\");\n\nexport namespace AiConnectionFactory {\n export type Interface = IAiConnectionFactory;\n}\n\n// Ai\n\ntype SDKGenerateTextParams = Parameters<typeof generateText>[0];\ntype SDKStreamTextParams = Parameters<typeof streamText>[0];\n\nexport type AiGenerateTextParams = Omit<SDKGenerateTextParams, \"model\"> & {\n model: string;\n connection?: string | IAiConnectionInline;\n};\nexport type AiStreamTextParams = Omit<SDKStreamTextParams, \"model\"> & {\n model: string;\n connection?: string | IAiConnectionInline;\n};\n\nexport interface AiModel {\n providerId: string; // e.g. \"anthropic\"\n providerName: string; // e.g. \"Anthropic\"\n modelId: string; // e.g. \"claude-sonnet-4-5\"\n modelName: string; // e.g. \"Claude Sonnet 4.5\"\n}\n\nexport interface IAi {\n generateText(params: AiGenerateTextParams): ReturnType<typeof generateText>;\n streamText(params: AiStreamTextParams): Promise<ReturnType<typeof streamText>>;\n listModels(): Promise<AiModel[]>;\n listModelsByConnections(): Promise<AiModel[]>;\n listModelsByConnection(connection: string | IAiConnectionInline): Promise<AiModel[]>;\n}\n\n/** Interact with AI language models using registered providers. */\nexport const Ai = createAbstraction<IAi>(\"Ai\");\n\nexport namespace Ai {\n export type Interface = IAi;\n export type GenerateTextParams = AiGenerateTextParams;\n export type StreamTextParams = AiStreamTextParams;\n}\n\n// AiSdkTool\n\nexport interface IAiSdkTool<TInput = any> {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: FlexibleSchema<TInput>;\n execute(input: TInput): Promise<unknown>;\n}\n\n/** A single tool that can be provided to AI generateText/streamText calls. */\nexport const AiSdkTool = createAbstraction<IAiSdkTool>(\"AiSdkTool\");\n\nexport namespace AiSdkTool {\n export type Interface = IAiSdkTool;\n}\n\n// AiSdkTools\n\nexport interface IAiSdkTools {\n getToolSet(): ToolSet;\n}\n\n/** Collection of AI SDK tools. Returns a ready-to-use ToolSet for generateText/streamText. */\nexport const AiSdkTools = createAbstraction<IAiSdkTools>(\"AiSdkTools\");\n\nexport namespace AiSdkTools {\n export type Interface = IAiSdkTools;\n}\n"],"names":["AiSdk","createAbstraction","AiSdkFactory","AiConnectionFactory","Ai","AiSdkTool","AiSdkTools"],"mappings":";AAkBO,MAAMA,QAAQC,kBAA0B;AAgBxC,MAAMC,eAAeD,kBAAiC;AAwBtD,MAAME,sBAAsBF,kBAAwC;AAoCpE,MAAMG,KAAKH,kBAAuB;
|
|
1
|
+
{"version":3,"file":"features/ai/abstractions.js","sources":["../../../src/features/ai/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { generateText } from \"ai\";\nimport type { streamText } from \"ai\";\nimport type { LanguageModel } from \"ai\";\nimport type { FlexibleSchema, ToolSet } from \"ai\";\n\n// AiSdk\n\nexport interface IAiSdkModel {\n id: string; // raw model id, e.g. \"claude-sonnet-4-5\"\n name: string; // human-friendly name, e.g. \"Claude Sonnet 4.5\"\n}\n\nexport interface IAiSdk {\n languageModel(modelId: string): LanguageModel;\n}\n\n/** A single AI SDK instance (e.g. OpenAI, Anthropic) that resolves model instances. */\nexport const AiSdk = createAbstraction<IAiSdk>(\"AiSdk\");\n\nexport namespace AiSdk {\n export type Interface = IAiSdk;\n}\n\n// AiSdkFactory\n\nexport interface IAiSdkFactory {\n readonly id: string; // machine id, e.g. \"anthropic\"\n readonly name: string; // human-friendly name, e.g. \"Anthropic\"\n readonly models: readonly IAiSdkModel[]; // static model list, no API call needed\n execute(apiKey?: string): Promise<IAiSdk>;\n}\n\n/** Factory that asynchronously initialises an AI SDK. Register one per provider namespace. */\nexport const AiSdkFactory = createAbstraction<IAiSdkFactory>(\"AiSdkFactory\");\n\nexport namespace AiSdkFactory {\n export type Interface = IAiSdkFactory;\n}\n\n// AiConnection\n\nexport interface IAiConnectionInline {\n readonly sdkName: string;\n readonly apiKey?: string;\n}\n\nexport interface IAiConnection extends IAiConnectionInline {\n readonly id: string;\n}\n\n// AiConnectionFactory\n\nexport interface IAiConnectionFactory {\n execute(): Promise<IAiConnection>;\n}\n\n/** Factory that asynchronously produces an AiConnection. */\nexport const AiConnectionFactory = createAbstraction<IAiConnectionFactory>(\"AiConnectionFactory\");\n\nexport namespace AiConnectionFactory {\n export type Interface = IAiConnectionFactory;\n}\n\n// Ai\n\ntype SDKGenerateTextParams = Parameters<typeof generateText>[0];\ntype SDKStreamTextParams = Parameters<typeof streamText>[0];\n\nexport type AiGenerateTextParams = Omit<SDKGenerateTextParams, \"model\"> & {\n model: string;\n connection?: string | IAiConnectionInline;\n};\nexport type AiStreamTextParams = Omit<SDKStreamTextParams, \"model\"> & {\n model: string;\n connection?: string | IAiConnectionInline;\n};\n\nexport interface AiModel {\n providerId: string; // e.g. \"anthropic\"\n providerName: string; // e.g. \"Anthropic\"\n modelId: string; // e.g. \"claude-sonnet-4-5\"\n modelName: string; // e.g. \"Claude Sonnet 4.5\"\n}\n\nexport interface IAi {\n generateText(params: AiGenerateTextParams): ReturnType<typeof generateText>;\n streamText(params: AiStreamTextParams): Promise<ReturnType<typeof streamText>>;\n listModels(): Promise<AiModel[]>;\n listModelsByConnections(): Promise<AiModel[]>;\n listModelsByConnection(connection: string | IAiConnectionInline): Promise<AiModel[]>;\n}\n\n/** Interact with AI language models using registered providers. */\nexport const Ai = createAbstraction<IAi>(\"Ai\");\n\nexport namespace Ai {\n export type Interface = IAi;\n export type GenerateTextParams = AiGenerateTextParams;\n export type StreamTextParams = AiStreamTextParams;\n}\n\n// AiSdkTool\n\n/**\n * Behavioural hints about a tool. Purely advisory — they never replace a permission check.\n * Names mirror the MCP tool annotations so they can be forwarded verbatim to MCP clients,\n * which use them to decide what to auto-approve and what to confirm with the user.\n */\nexport interface IAiSdkToolAnnotations {\n /** Tool does not modify state. */\n readOnlyHint?: boolean;\n /** Tool may perform destructive updates (only meaningful when not read-only). */\n destructiveHint?: boolean;\n /** Repeated calls with the same arguments have no additional effect. */\n idempotentHint?: boolean;\n /** Tool interacts with entities outside its own closed world. */\n openWorldHint?: boolean;\n}\n\nexport interface IAiSdkTool<TInput = any> {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: FlexibleSchema<TInput>;\n /** Human-friendly display name. Falls back to `name` when omitted. */\n readonly title?: string;\n readonly annotations?: IAiSdkToolAnnotations;\n execute(input: TInput): Promise<unknown>;\n}\n\n/** A single tool that can be provided to AI generateText/streamText calls. */\nexport const AiSdkTool = createAbstraction<IAiSdkTool>(\"AiSdkTool\");\n\nexport namespace AiSdkTool {\n export type Interface = IAiSdkTool;\n export type Annotations = IAiSdkToolAnnotations;\n}\n\n// AiSdkTools\n\nexport interface IAiSdkTools {\n getToolSet(): ToolSet;\n}\n\n/** Collection of AI SDK tools. Returns a ready-to-use ToolSet for generateText/streamText. */\nexport const AiSdkTools = createAbstraction<IAiSdkTools>(\"AiSdkTools\");\n\nexport namespace AiSdkTools {\n export type Interface = IAiSdkTools;\n}\n"],"names":["AiSdk","createAbstraction","AiSdkFactory","AiConnectionFactory","Ai","AiSdkTool","AiSdkTools"],"mappings":";AAkBO,MAAMA,QAAQC,kBAA0B;AAgBxC,MAAMC,eAAeD,kBAAiC;AAwBtD,MAAME,sBAAsBF,kBAAwC;AAoCpE,MAAMG,KAAKH,kBAAuB;AAqClC,MAAMI,YAAYJ,kBAA8B;AAchD,MAAMK,aAAaL,kBAA+B"}
|