bazis 0.137.0 → 0.138.0

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 (73) hide show
  1. package/README.md +7 -4
  2. package/cli/generateProject.ts +11 -18
  3. package/cli/main.ts +1 -1
  4. package/cli/templates/passport.ts +1 -1
  5. package/core/access/catalog/moduleFields.ts +25 -2
  6. package/core/access/testing/index.ts +26 -4
  7. package/core/agent/ToolRunner.ts +2 -1
  8. package/core/agent/defineTool.ts +109 -0
  9. package/core/agent/index.ts +8 -3
  10. package/core/agent/moduleContributions-v1.ts +3 -10
  11. package/core/app/index.ts +1 -1
  12. package/core/app/messages.ts +3 -3
  13. package/core/app/runApp.ts +90 -26
  14. package/core/cache/ICache.ts +1 -1
  15. package/core/cache/README.md +4 -2
  16. package/core/cache/SPEC.md +16 -9
  17. package/core/cache/http/missingCacheModuleCheck.ts +5 -4
  18. package/core/cache/internal/buildCacheProviders.ts +4 -5
  19. package/core/cache/providers/cachedProviders.ts +1 -1
  20. package/core/di/index.ts +0 -4
  21. package/core/di/lowLevel.ts +12 -0
  22. package/core/di/module/index.ts +0 -3
  23. package/core/di/module/shortcuts.ts +31 -86
  24. package/core/generatedRuntime.ts +11 -0
  25. package/core/grpc/Grpc.module.ts +2 -1
  26. package/core/grpc/grpcClients.ts +2 -1
  27. package/core/http/Authorization/metadata.ts +1 -1
  28. package/core/http/Errors/HttpError.ts +1 -1
  29. package/core/http/Http.config.ts +22 -0
  30. package/core/http/HttpContext/HttpContext.ts +1 -1
  31. package/core/http/HttpServer.ts +10 -7
  32. package/core/http/OpenApi/openApiDocument.ts +1 -1
  33. package/core/http/httpModule.ts +10 -8
  34. package/core/http/index.ts +1 -0
  35. package/core/http/options.ts +5 -1
  36. package/core/http-client/httpClients.ts +2 -1
  37. package/core/infra/Infra.ts +3 -3
  38. package/core/infra/connectors/codex/CodexAppServerClient.ts +1 -1
  39. package/core/infra/connectors/codex/contracts.ts +3 -3
  40. package/core/infra/connectors/llm.ts +2 -1
  41. package/core/infra/connectors/redis.ts +2 -1
  42. package/core/kernel/KernelBuilder.ts +2 -1
  43. package/core/kernel/config/ConfigRegistry.ts +2 -1
  44. package/core/kernel/config/addConfigOptions.ts +2 -1
  45. package/core/kernel/config/defineConfig.ts +1 -1
  46. package/core/kernel/events/EventBus.ts +1 -0
  47. package/core/kernel/events/eventSubscribers.ts +1 -1
  48. package/core/kernel/events/onEvent.ts +2 -1
  49. package/core/orm/buildOrmProviders.ts +2 -1
  50. package/core/orm/encryptedWith.ts +1 -1
  51. package/core/orm/ormModule.ts +2 -1
  52. package/core/orm/registerRepositories.ts +2 -1
  53. package/core/scripts/di-generate.ts +52 -8
  54. package/core/testing/index.ts +51 -11
  55. package/core/tools/index.ts +1 -1
  56. package/core/tools/orm/ormEntityTools.ts +54 -28
  57. package/core/websocket/DESIGN.md +5 -3
  58. package/core/websocket/middleware.ts +1 -1
  59. package/core/websocket/websocketModule.ts +3 -3
  60. package/core/workflow/definitions_module/WorkflowDefinitions.module.ts +1 -2
  61. package/core/workflow/definitions_module/code/defineProcess.ts +213 -11
  62. package/core/workflow/definitions_module/code/inspectProcesses.ts +12 -2
  63. package/core/workflow/index.ts +14 -1
  64. package/core/workflow/runtime_module/services/IWorkflowRuntime.service.ts +10 -6
  65. package/core/workflow/runtime_module/services/WorkflowRuntime.service.ts +5 -2
  66. package/core/workflow/testing/index.ts +46 -4
  67. package/index.ts +4 -3
  68. package/library/terminal/messages.ts +6 -6
  69. package/library/validation/README.md +1 -1
  70. package/library/validation/SPEC.md +1 -1
  71. package/library/workflow/index.ts +1 -0
  72. package/library/workflow/nodeConfigs.ts +130 -0
  73. package/package.json +2 -1
@@ -0,0 +1,22 @@
1
+ import { defineConfig } from "../kernel";
2
+
3
+ /**
4
+ * Where the HTTP server listens. `BAZIS_HTTP__HOST` and `BAZIS_HTTP__PORT` set it
5
+ * from the environment. Outside `production` the server is reachable from this
6
+ * machine only; in `production` it listens on every interface.
7
+ *
8
+ * A `port` or `hostname` written in `@App({ http })` is fixed in code and wins.
9
+ */
10
+ export const httpConfig = defineConfig("http", {
11
+ default: {
12
+ host: "127.0.0.1",
13
+ port: 3000,
14
+ },
15
+ production: {
16
+ host: "0.0.0.0",
17
+ },
18
+ validate: {
19
+ port: (port) => (Number.isInteger(port) && port >= 0 && port <= 65535 ? undefined : "must be a TCP port (0-65535)"),
20
+ host: (host) => (host.trim() === "" ? "must not be empty" : undefined),
21
+ },
22
+ });
@@ -50,7 +50,7 @@ export class HttpContext {
50
50
  /** Validator captured by the owning HTTP server. */
51
51
  readonly modelValidator?: ModelValidator,
52
52
  /**
53
- * Response language of this request: `runApp({ language })`, or the best
53
+ * Response language of this request: `@App({ language })`, or the best
54
54
  * match of `Accept-Language` when several languages are supported.
55
55
  * `undefined` without `language`.
56
56
  */
@@ -23,6 +23,7 @@ import { HTTP_ERROR_HOOK, HTTP_ERROR_MAPPER, ROUTE_MIDDLEWARE_COMPOSER, SERVER_M
23
23
  import type { HealthEndpointOptions, RouteMiddlewareComposer, HttpModuleOptions, HttpServerOptions } from "./options";
24
24
  import { WEBSOCKET_UPGRADE, type WebSocketUpgrade } from "./WebSocketUpgrade";
25
25
  import { HttpSetupError, type HttpError } from "./Errors/HttpError";
26
+ import { httpConfig } from "./Http.config";
26
27
  import { clientAddress, trustedProxies, type TrustedProxies } from "./HttpContext/clientAddress";
27
28
  import { EN_HTTP_MESSAGES, formatMessage, languageHeaders, type HttpMessageKey, type MessageParams, type SelectedLanguage } from "./Errors/messages";
28
29
  import { getModelValidator, type ModelValidator } from "./Binding/modelValidator";
@@ -282,14 +283,14 @@ export class HttpServer implements HostedService {
282
283
  }
283
284
 
284
285
  private async startBunServer(create: (listen: ListenOptions) => ReturnType<typeof Bun.serve>): Promise<ReturnType<typeof Bun.serve>> {
285
- const attempts = this.options.port === 0 ? 10 : 1;
286
+ const listen = this.listenOptions();
287
+ const attempts = listen.port === 0 ? 10 : 1;
286
288
  let lastError: unknown;
287
289
  for (let attempt = 0; attempt < attempts; attempt += 1) {
288
- const listen = await this.resolveListenOptions();
289
290
  try {
290
291
  return create(listen);
291
292
  } catch (error) {
292
- if (this.options.port !== 0 || !isAddressInUse(error)) {
293
+ if (listen.port !== 0 || !isAddressInUse(error)) {
293
294
  throw error;
294
295
  }
295
296
  lastError = error;
@@ -298,12 +299,14 @@ export class HttpServer implements HostedService {
298
299
  throw lastError;
299
300
  }
300
301
 
301
- private async resolveListenOptions(): Promise<ListenOptions> {
302
- const hostname = this.options.hostname ?? (this.options.port === 0 ? "127.0.0.1" : undefined);
302
+ /** The address: what the options fix in code, otherwise the `http` settings. */
303
+ private listenOptions(): ListenOptions {
304
+ const settings = this.resolver.tryResolve(httpConfig.token);
303
305
  // Let the operating system reserve an ephemeral port atomically. Picking a
304
306
  // random port in user space creates a check/use race between concurrent
305
307
  // application or test processes and can still exhaust every retry.
306
- const port = this.options.port ?? 3000;
308
+ const port = this.options.port ?? settings?.get("port") ?? 3000;
309
+ const hostname = this.options.hostname ?? (this.options.port === 0 ? "127.0.0.1" : settings?.get("host"));
307
310
  return {
308
311
  port,
309
312
  ...(hostname !== undefined ? { hostname } : {}),
@@ -417,7 +420,7 @@ export class HttpServer implements HostedService {
417
420
  return request.method === "HEAD" ? stripBody(response) : response;
418
421
  }
419
422
 
420
- /** The response language of a request; `undefined` without `runApp({ language })`. */
423
+ /** The response language of a request; `undefined` without `@App({ language })`. */
421
424
  private selected(request: Request | undefined): SelectedLanguage | undefined {
422
425
  try {
423
426
  return this.options.languages?.select(request?.headers.get("accept-language"));
@@ -23,7 +23,7 @@ export interface HttpOpenApiDocumentBuildInput {
23
23
  readonly versioning?: ApiVersioningOptions;
24
24
  readonly title: string;
25
25
  readonly version: string;
26
- /** Default checks of `runApp({ http: { authorize } })`: such routes are secured too. */
26
+ /** Default checks of `@App({ http: { authorize } })`: such routes are secured too. */
27
27
  readonly authorize?: readonly AuthorizeCheck[];
28
28
  }
29
29
 
@@ -1,24 +1,25 @@
1
- import { DI, HOSTED_SERVICE, Module, SERVICE_PROVIDER, collectModuleControllers, type BazisModule, type ProviderDefinition } from "../di";
1
+ import { HOSTED_SERVICE, Module, SERVICE_PROVIDER, collectModuleControllers, type BazisModule, type ProviderDefinition } from "../di";
2
+ import { DI } from "../di/lowLevel";
2
3
  import { HttpServer } from "./HttpServer";
4
+ import { httpConfig } from "./Http.config";
3
5
  import type { HttpModuleOptions, HttpServerOptions } from "./options";
4
6
 
5
7
  /**
6
8
  * Builds the HTTP module: discovers the `controllers` of the modules in
7
- * `imports` and registers the HttpServer hosted service.
9
+ * `imports` and registers the HttpServer hosted service. The address comes from
10
+ * {@link httpConfig} unless the options fix it.
8
11
  *
9
12
  * ```ts
10
13
  * @Module({
11
14
  * controllers: [UsersController],
12
- * providers: [scoped(IUserStore, UserService, [repositoryFor(User)] as const)],
15
+ * providers: [scoped(IUserStore, UserService)],
13
16
  * })
14
17
  * export class UsersModule {}
15
18
  *
16
- * export const AppModule = createApp({
17
- * imports: [UsersModule],
18
- * http: { port: 3000, prefix: "api" },
19
- * }).module;
19
+ * @App({ modules: [UsersModule], http: { prefix: "api" } })
20
+ * export class Application {}
20
21
  *
21
- * await Bazis.run(AppModule);
22
+ * await runApp(Application);
22
23
  * ```
23
24
  */
24
25
  export function httpModule(options: HttpModuleOptions): BazisModule {
@@ -37,6 +38,7 @@ export function httpModule(options: HttpModuleOptions): BazisModule {
37
38
 
38
39
  @Module({
39
40
  imports: options.imports,
41
+ config: httpConfig,
40
42
  providers,
41
43
  })
42
44
  class HttpModule {}
@@ -6,6 +6,7 @@
6
6
  * dependencies, compatible with `bun build --compile`.
7
7
  */
8
8
  export { httpModule } from "./httpModule";
9
+ export { httpConfig } from "./Http.config";
9
10
  export { HttpServer } from "./HttpServer";
10
11
  export { WEBSOCKET_UPGRADE, type WebSocketUpgrade } from "./WebSocketUpgrade";
11
12
  export type {
@@ -72,8 +72,12 @@ export interface HttpModuleOptions {
72
72
  * either listed here or exported by global modules.
73
73
  */
74
74
  readonly imports?: readonly import("../di").BazisModuleRef[];
75
- /** Listen port (default 3000; 0 — random free port). */
75
+ /**
76
+ * Fixes the listen port in code (0 — a random free port). Leave it out: the
77
+ * port then comes from the `http.port` setting, 3000 unless `BAZIS_HTTP__PORT` says otherwise.
78
+ */
76
79
  readonly port?: number;
80
+ /** Fixes the listen address in code. Leave it out: it comes from the `http.host` setting (`BAZIS_HTTP__HOST`). */
77
81
  readonly hostname?: string;
78
82
  /** Global route prefix, e.g. "api". */
79
83
  readonly prefix?: string;
@@ -1,4 +1,5 @@
1
- import { DI, registerModuleMetadataExpander, type BazisModuleMetadata, type BazisModuleRef, type ServiceResolver } from "../di";
1
+ import { registerModuleMetadataExpander, type BazisModuleMetadata, type BazisModuleRef, type ServiceResolver } from "../di";
2
+ import { DI } from "../di/lowLevel";
2
3
  import { getOutboundCorrelationHeaders, type ConfigDefinition } from "../kernel";
3
4
  import { HttpClientBase, HttpClientError, type RequestConfig } from "../../library/http-client";
4
5
 
@@ -1,5 +1,4 @@
1
1
  import {
2
- DI,
3
2
  HOSTED_SERVICE,
4
3
  Module,
5
4
  createToken,
@@ -12,6 +11,7 @@ import {
12
11
  type BazisModuleRef,
13
12
  type ProviderDefinition,
14
13
  } from "../di";
14
+ import { DI } from "../di/lowLevel";
15
15
  import { ConfigRegistry, HEALTH_CHECK, StartupReport } from "../kernel";
16
16
  import { InfraError, type InfraConnector } from "./InfraConnector";
17
17
  import { InfraLifecycle } from "./InfraLifecycle";
@@ -136,7 +136,7 @@ function buildInfraDefinitions(manifest: InfraManifest): {
136
136
 
137
137
  /**
138
138
  * Dynamic infrastructure module (a plain metadata object): the same as
139
- * `@Infra`, but without a class. Handy for `imports` or `runApp({ infra })`.
139
+ * `@Infra`, but without a class. Handy for `imports` or `@App({ infra })`.
140
140
  */
141
141
  export function infraModule(manifest: InfraManifest): BazisModuleRef {
142
142
  try {
@@ -153,7 +153,7 @@ export function infraModule(manifest: InfraManifest): BazisModuleRef {
153
153
  /**
154
154
  * Infrastructure decorator. Puts the metadata of a regular **global module**
155
155
  * on the class, so the class becomes a valid `BazisModuleRef`: it can be passed
156
- * to `runApp({ infra: AppInfra })` or to `imports`.
156
+ * to `@App({ infra: AppInfra })` or to `imports`.
157
157
  *
158
158
  * The class stays pure metadata (like `@Module`) and is **never instantiated**:
159
159
  * only the clients it lists live and hold state.
@@ -232,7 +232,7 @@ export class CodexAppServerClient implements CodexClient {
232
232
  if (method === "account/updated") this.modelCache = undefined;
233
233
  }, () => { this.clearLogin(); this.modelCache = undefined; });
234
234
  const initialized = await client.request("initialize", {
235
- clientInfo: { name: "bazis", title: "Bazis", version: "0.137.0" }, capabilities: { experimentalApi: true },
235
+ clientInfo: { name: "bazis", title: "Bazis", version: "0.138.0" }, capabilities: { experimentalApi: true },
236
236
  }, 15_000, signal);
237
237
  if (resolve(text(initialized.codexHome, 4096)) !== this.paths.home) throw new CodexError("PROTOCOL_ERROR");
238
238
  client.notify("initialized");
@@ -52,7 +52,7 @@ const EN_CODEX_MESSAGES: Readonly<Record<CodexErrorCode, string>> = Object.freez
52
52
  LOGIN_EXPIRED: "The sign-in window expired. Start signing in again.",
53
53
  });
54
54
 
55
- /** Russian texts for every code; `runApp({ language: "ru" })` turns them on. */
55
+ /** Russian texts for every code; `@App({ language: "ru" })` turns them on. */
56
56
  export const RU_CODEX_MESSAGES: Readonly<Record<CodexErrorCode, string>> = Object.freeze({
57
57
  NOT_CONFIGURED: "Подключение ChatGPT не настроено на сервере.",
58
58
  UNAVAILABLE: "Codex App Server недоступен. Проверьте его установку и настройки.",
@@ -73,7 +73,7 @@ let own: Partial<Record<CodexErrorCode, string>> = {};
73
73
  let messages: Readonly<Record<CodexErrorCode, string>> = EN_CODEX_MESSAGES;
74
74
 
75
75
  /**
76
- * @internal `runApp({ language })` sets the language of the texts. It is
76
+ * @internal `@App({ language })` sets the language of the texts. It is
77
77
  * process-wide, like the texts themselves: the last started application wins.
78
78
  */
79
79
  export function useCodexLanguage(name: keyof typeof CODEX_LANGUAGES): void {
@@ -81,7 +81,7 @@ export function useCodexLanguage(name: keyof typeof CODEX_LANGUAGES): void {
81
81
  messages = Object.freeze({ ...language, ...own });
82
82
  }
83
83
 
84
- /** `message` is user-facing text for `code`, in the language of `runApp({ language })`. */
84
+ /** `message` is user-facing text for `code`, in the language of `@App({ language })`. */
85
85
  export class CodexError extends Error {
86
86
  constructor(readonly code: CodexErrorCode) { super(messages[code]); this.name = "CodexError"; }
87
87
 
@@ -1,6 +1,7 @@
1
1
  import type { AppConfig, ConfigRegistry, Secret } from "../../kernel";
2
2
  import { AGENT_MODEL_PROVIDER, AGENT_RUNTIME_OPTIONS, AgentRuntime, type AgentModelProvider } from "../../agent";
3
- import { DI, DiError, HOSTED_SERVICE, SERVICE_PROVIDER, type ProviderDefinition } from "../../di";
3
+ import { DiError, HOSTED_SERVICE, SERVICE_PROVIDER, type ProviderDefinition } from "../../di";
4
+ import { DI } from "../../di/lowLevel";
4
5
  import { LOGGER } from "../../kernel/logging/Logger";
5
6
  import { reader, requireValue, settingNames } from "../connectorConfig";
6
7
  import { InfraError, type InfraConnector } from "../InfraConnector";
@@ -7,7 +7,8 @@ import {
7
7
  connectionCache,
8
8
  type DistributedCacheStores,
9
9
  } from "../../cache";
10
- import { createToken, DI, type InjectionToken, type ProviderDefinition } from "../../di";
10
+ import { createToken, type InjectionToken, type ProviderDefinition } from "../../di";
11
+ import { DI } from "../../di/lowLevel";
11
12
  import type { AppConfig, Secret } from "../../kernel";
12
13
  import { RedisDistributedCacheBackend, type RedisDistributedCacheTuning } from "../cache/RedisDistributedCacheBackend";
13
14
  import { reader, requireValue, settingNames } from "../connectorConfig";
@@ -1,4 +1,5 @@
1
- import { DI, Global, Module, collectModuleConfigs, createContainer, type BazisModule, type BazisModuleRef, type ProviderDefinition } from "../di";
1
+ import { Global, Module, collectModuleConfigs, createContainer, type BazisModule, type BazisModuleRef, type ProviderDefinition } from "../di";
2
+ import { DI } from "../di/lowLevel";
2
3
  import { isBazisModuleClass } from "../di/module/Module";
3
4
  import { ApplicationLifetime } from "./ApplicationLifetime";
4
5
  import { Configuration, loadConfiguration } from "./config/Configuration";
@@ -1,4 +1,5 @@
1
- import { DI, type ProviderDefinition } from "../../di";
1
+ import { type ProviderDefinition } from "../../di";
2
+ import { DI } from "../../di/lowLevel";
2
3
  import { KernelError } from "../errors";
3
4
  import type { EnvironmentName } from "../types";
4
5
  import type { Configuration } from "./Configuration";
@@ -1,5 +1,6 @@
1
1
  import type { InjectionToken, Options, ProviderDefinition, ServiceCollection, ServiceResolver } from "../../di";
2
- import { DI, OPTIONS_STARTUP_VALIDATOR, OptionsValidationError } from "../../di";
2
+ import { OPTIONS_STARTUP_VALIDATOR, OptionsValidationError } from "../../di";
3
+ import { DI } from "../../di/lowLevel";
3
4
  import { ConfigKeyMissingError } from "../errors";
4
5
  import { Configuration } from "./Configuration";
5
6
 
@@ -15,7 +15,7 @@ registerNamedDependencyHint((name) => {
15
15
  const match = /^Config:(.+)$/.exec(name);
16
16
  if (!match) return undefined;
17
17
  const declaration = match[1] === "default" ? "defineConfig({ … })" : `defineConfig("${match[1]}", …)`;
18
- return `The config ${declaration} is not declared in the application: add it to \`config\` of the module that uses it, or to runApp({ config }).`;
18
+ return `The config ${declaration} is not declared in the application: add it to \`config\` of the module that uses it, or to @App({ config }).`;
19
19
  });
20
20
 
21
21
  type Stand = "development" | "test" | "production";
@@ -1,4 +1,5 @@
1
1
  import { createToken, type ServiceResolver } from "../../di";
2
+ import { DI } from "../../di/lowLevel";
2
3
  import type { EventHandler, EventToken } from "./EventToken";
3
4
  import { awaitAbortable } from "../internal/awaitAbortable";
4
5
 
@@ -1,5 +1,4 @@
1
1
  import {
2
- DI,
3
2
  Module,
4
3
  singleton,
5
4
  type Class,
@@ -7,6 +6,7 @@ import {
7
6
  type ProviderDefinition,
8
7
  type ServiceResolver,
9
8
  } from "../../di";
9
+ import { DI } from "../../di/lowLevel";
10
10
  import { EVENT_HANDLER, type EventSubscription } from "./EventBus";
11
11
  import type { EventHandler, EventToken } from "./EventToken";
12
12
 
@@ -1,4 +1,5 @@
1
- import { DI, type ProviderDefinition, type ServiceCollection } from "../../di";
1
+ import { type ProviderDefinition, type ServiceCollection } from "../../di";
2
+ import { DI } from "../../di/lowLevel";
2
3
  import { EVENT_HANDLER, type EventSubscription } from "./EventBus";
3
4
  import type { EventHandler, EventToken } from "./EventToken";
4
5
 
@@ -1,4 +1,5 @@
1
- import { DI, HOSTED_SERVICE, type InjectionToken, type ModuleOwnedContributionSnapshot, type ProviderDefinition, type ProviderDependencyList, type ServiceResolver } from "../di";
1
+ import { HOSTED_SERVICE, type InjectionToken, type ModuleOwnedContributionSnapshot, type ProviderDefinition, type ProviderDependencyList, type ServiceResolver } from "../di";
2
+ import { DI } from "../di/lowLevel";
2
3
  import { contextEntities } from "./contextEntities";
3
4
  import { getGeneratedClassDeps } from "../di/module/autoDeps";
4
5
  import { resolveDependencyList } from "../di/internal/resolveDependencyList";
@@ -60,7 +60,7 @@ export function bindEncryptedColumns(options: DbContextOptions, registry: Config
60
60
  try {
61
61
  view = registry.get(binding.config) as { get(key: string): unknown };
62
62
  } catch {
63
- throw new OrmError(`${where}: the config "${prefixOf(binding)}" is not declared in the application; add it to \`config\` of the module that owns ${entity.name} or to runApp({ config }).`);
63
+ throw new OrmError(`${where}: the config "${prefixOf(binding)}" is not declared in the application; add it to \`config\` of the module that owns ${entity.name} or to @App({ config }).`);
64
64
  }
65
65
  const value = view.get(binding.field);
66
66
  const secret = value instanceof Secret ? value.reveal() : value;
@@ -1,4 +1,5 @@
1
- import { DI, HOSTED_SERVICE, singletonValue, type BazisModuleRef, type ProviderDefinition } from "../di";
1
+ import { HOSTED_SERVICE, singletonValue, type BazisModuleRef, type ProviderDefinition } from "../di";
2
+ import { DI } from "../di/lowLevel";
2
3
  import {
3
4
  OrmError,
4
5
  type DatabaseProvider,
@@ -1,4 +1,5 @@
1
- import { DI, type DiRegistrar } from "../di";
1
+ import { type DiRegistrar } from "../di";
2
+ import { DI } from "../di/lowLevel";
2
3
  import { Repository, type DbContext, type DbContextOptions } from "../../library/orm";
3
4
  import { repositoryFor } from "./repository";
4
5
 
@@ -994,6 +994,35 @@ function collectDiClassRegistrations(source: ts.SourceFile): void {
994
994
  if (properties.has("provide") && properties.has("useClass")
995
995
  && (!properties.has("deps") || properties.get("deps")!.getText() === "undefined")) record(properties.get("useClass"));
996
996
  };
997
+ /** The `lookup` classes of a `definePermissions({...})` result: of `scope` and of the attributes in `on`. */
998
+ const permissionLookups = (expression: ts.Expression | undefined): ts.Expression[] => {
999
+ const declared = (node: ts.Expression | undefined, depth = 0): ts.ObjectLiteralExpression | undefined => {
1000
+ if (!node || depth > 5) return undefined;
1001
+ if (ts.isCallExpression(node)) return objectFor(node.arguments[0]);
1002
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) return declared(node.expression, depth + 1);
1003
+ let symbol = checker.getSymbolAtLocation(node);
1004
+ if (symbol && (symbol.flags & ts.SymbolFlags.Alias)) symbol = checker.getAliasedSymbol(symbol);
1005
+ const declaration = symbol?.valueDeclaration;
1006
+ return declaration && ts.isVariableDeclaration(declaration) ? declared(declaration.initializer, depth + 1) : undefined;
1007
+ };
1008
+ const permissions = declared(expression);
1009
+ const found: ts.Expression[] = [];
1010
+ if (!permissions) return found;
1011
+ const lookupOf = (holder: ts.Expression | undefined): void => {
1012
+ const object = objectFor(holder);
1013
+ const lookup = object && propertiesOf(object).get("lookup");
1014
+ if (lookup) found.push(lookup);
1015
+ };
1016
+ for (const spec of propertiesOf(permissions).values()) {
1017
+ const permission = objectFor(spec);
1018
+ if (!permission) continue;
1019
+ const fields = propertiesOf(permission);
1020
+ lookupOf(fields.get("scope"));
1021
+ const attributes = objectFor(fields.get("on"));
1022
+ if (attributes) for (const attribute of propertiesOf(attributes).values()) lookupOf(attribute);
1023
+ }
1024
+ return found;
1025
+ };
997
1026
  const visitedModules = new Set<ts.ObjectLiteralExpression>();
998
1027
  const recordModule = (expression: ts.Expression | undefined): void => {
999
1028
  const object = objectFor(expression);
@@ -1007,6 +1036,8 @@ function collectDiClassRegistrations(source: ts.SourceFile): void {
1007
1036
  // `references: { "orders.order": OrderReferences }`: the field registers the classes.
1008
1037
  const references = objectFor(properties.get("references"));
1009
1038
  if (references) for (const entry of propertiesOf(references).values()) record(entry);
1039
+ // `permissions: orderPermissions`: the field registers the `lookup` classes its permissions name.
1040
+ for (const lookup of permissionLookups(properties.get("permissions"))) record(lookup);
1010
1041
  const imports = properties.get("imports");
1011
1042
  if (imports && ts.isArrayLiteralExpression(imports)) for (const entry of imports.elements) recordModule(entry);
1012
1043
  };
@@ -1106,13 +1137,26 @@ function collectProviderFormErrors(source: ts.SourceFile): void {
1106
1137
  }
1107
1138
  fatalErrors.push(`BAZIS_DI_PROVIDER_FORM: ${sourceLocation(element)}: providers of ${module}: "${text(element)}" is not an agreed registration. A computed service is a class with a constructor: scoped(IService, Service). Agreed forms: ${AGREED_PROVIDERS}.`);
1108
1139
  };
1109
- /** Tools made from an entity: they are classes too, and carry their own wiring. */
1110
- const isOrmEntityTools = (element: ts.Expression): boolean => {
1111
- if (!ts.isSpreadElement(element)) return false;
1112
- const call = resolved(element.expression, ts.isCallExpression);
1113
- const target = call && callee(call);
1114
- return target?.name === "ormEntityTools" && target.file?.endsWith("/core/tools/orm/ormEntityTools.ts") === true;
1140
+ /**
1141
+ * Tools made by a function: a Tool of `defineTool`, a set of them, or a call (or a
1142
+ * spread) that gives them. They carry their own wiring, so codegen has nothing to add.
1143
+ */
1144
+ const madeToolType = (type: ts.Type, depth = 0): boolean => {
1145
+ if (depth > 3) return false;
1146
+ const alias = type.aliasSymbol;
1147
+ if (alias && (alias.name === "DefinedTool" || alias.name === "ToolSet")
1148
+ && alias.declarations?.some((entry) => entry.getSourceFile().fileName.replace(/\\/g, "/").endsWith("/core/agent/defineTool.ts"))) return true;
1149
+ if (type.isUnion()) return type.types.every((part) => madeToolType(part, depth + 1));
1150
+ if (checker.isArrayType(type) || checker.isTupleType(type)) {
1151
+ const items = checker.getTypeArguments(type as ts.TypeReference);
1152
+ return items.length > 0 && items.every((item) => madeToolType(item, depth + 1));
1153
+ }
1154
+ if ((type.flags & ts.TypeFlags.Object) === 0 || type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) return false;
1155
+ const members = type.getProperties();
1156
+ return members.length > 0 && members.every((member) => madeToolType(checker.getTypeOfSymbol(member), depth + 1));
1115
1157
  };
1158
+ const isMadeTools = (element: ts.Expression): boolean =>
1159
+ madeToolType(checker.getTypeAtLocation(ts.isSpreadElement(element) ? element.expression : element));
1116
1160
  /**
1117
1161
  * `permissions: orderPermissions`: the exported constant goes to the generated
1118
1162
  * `permissions.ts`, which makes its keys the type of `can` and `defineRoles`.
@@ -1148,9 +1192,9 @@ function collectProviderFormErrors(source: ts.SourceFile): void {
1148
1192
  }
1149
1193
  for (const element of list.elements) {
1150
1194
  if (field === "providers") checkProvider(module, element);
1151
- else if (field === "tools" && isOrmEntityTools(element)) continue;
1195
+ else if (field === "tools" && isMadeTools(element)) continue;
1152
1196
  else if (!ts.isIdentifier(element) && !ts.isPropertyAccessExpression(element)) {
1153
- fatalErrors.push(`BAZIS_DI_PROVIDER_FORM: ${sourceLocation(element)}: ${field} of ${module}: "${text(element)}" — list the class itself; its constructor dependencies come from codegen.`);
1197
+ fatalErrors.push(`BAZIS_DI_PROVIDER_FORM: ${sourceLocation(element)}: ${field} of ${module}: "${text(element)}" — list the class itself; its constructor dependencies come from codegen.${field === "tools" ? " A Tool made by a function comes from defineTool(...)." : ""}`);
1154
1198
  }
1155
1199
  }
1156
1200
  }
@@ -1,9 +1,8 @@
1
- import { HOSTED_SERVICE, type BazisModuleRef, type DiContainer, type ProviderDefinition } from "../di";
1
+ import { HOSTED_SERVICE, type BazisModuleRef, type DiContainer, type ProviderDefinition, type Token } from "../di";
2
2
  import { loadBazisGeneratedRuntime } from "../generatedRuntime";
3
3
  import { HttpServer, type HttpModuleOptions } from "../http";
4
4
  import { KernelBuilder, type Kernel } from "../kernel";
5
- import { composeApp } from "../app/runApp";
6
- import type { RunAppOptions } from "../app";
5
+ import { appOptionsOf, composeApp, type AppSettings } from "../app/runApp";
7
6
 
8
7
  export interface TestContainerOptions {
9
8
  /** Replacements for registered providers: `singleton(ITaskStore, FakeStore)`. */
@@ -23,18 +22,30 @@ export interface TestContainerOptions {
23
22
  * const container = await createTestContainer(TaskModule, { overrides: [singleton(ITaskStore, FakeStore)] });
24
23
  * const tasks = container.createScope().resolve(TaskService);
25
24
  * ```
25
+ *
26
+ * Given an `@App` class, the graph also holds its infrastructure, cache and configs.
26
27
  */
27
28
  export async function createTestContainer(root: BazisModuleRef, options: TestContainerOptions = {}): Promise<DiContainer> {
28
29
  await loadBazisGeneratedRuntime();
29
- const builder = new KernelBuilder(root).useOptions({ startupReport: false, environment: "test", signals: [] });
30
+ const declared = appOptionsOf(root);
31
+ const graph = declared === undefined ? root : composeApp(root, { infra: declared.infra, cache: declared.cache, config: declared.config, language: declared.language, messages: declared.messages });
32
+ const builder = new KernelBuilder(graph).useOptions({ startupReport: false, environment: "test", signals: [] });
30
33
  options.configure?.(builder);
31
34
  if (options.overrides !== undefined) builder.useOverrides(options.overrides);
32
35
  const kernel: Kernel = await builder.build();
33
36
  return kernel.container;
34
37
  }
35
38
 
36
- export interface TestAppOptions extends Omit<RunAppOptions, "http"> {
37
- /** HTTP options; the test app always listens on 127.0.0.1 and a free port. `false`: no HTTP server. */
39
+ /**
40
+ * What a test changes in the application it starts. For an `@App` class every
41
+ * field replaces the declared one; for a module it is the whole description.
42
+ */
43
+ export interface TestAppOptions extends Omit<AppSettings, "http"> {
44
+ /**
45
+ * HTTP options; the test app always listens on 127.0.0.1 and a free port.
46
+ * `false`: no HTTP server. Left out: the `http` of the `@App` class; a module
47
+ * (or an `@App` without `http`, given other HTTP options here) gets a server with the defaults.
48
+ */
38
49
  readonly http?: Omit<HttpModuleOptions, "port" | "hostname"> | false;
39
50
  /** Replacements for registered providers, see `createContainer` `overrides`. */
40
51
  readonly overrides?: readonly ProviderDefinition[];
@@ -45,7 +56,16 @@ export interface TestApp {
45
56
  readonly url: string;
46
57
  /** `fetch` relative to {@link url}: `app.fetch("/tasks/1")`. */
47
58
  fetch(path: string, init?: RequestInit): Promise<Response>;
48
- /** The application container: `app.container.createScope().resolve(TaskService)`. */
59
+ /**
60
+ * Calls a service the way a request does: in a scope of its own, closed when
61
+ * the work is done.
62
+ *
63
+ * ```ts
64
+ * const task = await app.use(ITaskService, (tasks) => tasks.create("Write the report"));
65
+ * ```
66
+ */
67
+ use<T, R>(service: Token<T>, work: (service: T) => R | Promise<R>): Promise<R>;
68
+ /** The application container, when {@link use} is not enough: singletons, several services of one scope. */
49
69
  readonly container: DiContainer;
50
70
  /** Graceful stop, like SIGTERM in a real run. */
51
71
  stop(): Promise<void>;
@@ -57,20 +77,32 @@ export interface TestApp {
57
77
  * Configuration errors and failing startup throw instead of exiting the process.
58
78
  *
59
79
  * ```ts
60
- * const app = await startTestApp(AppModule, { overrides: [singleton(ITaskStore, FakeStore)] });
80
+ * const app = await startTestApp(TodoApp, { overrides: [singleton(ITaskStore, FakeStore)] });
61
81
  * try {
62
82
  * expect((await app.fetch("/tasks/1")).status).toBe(200);
63
83
  * } finally {
64
84
  * await app.stop();
65
85
  * }
66
86
  * ```
87
+ *
88
+ * `root` is the `@App` class: the test starts what production starts, and the
89
+ * options only say what differs. A single module works too, to test a part of
90
+ * the application: `startTestApp(TaskModule, { infra: TestInfra })`.
67
91
  */
68
92
  export async function startTestApp(root: BazisModuleRef, options: TestAppOptions = {}): Promise<TestApp> {
69
93
  await loadBazisGeneratedRuntime();
70
- const { http, overrides, configure, kernel: kernelOptions, ...rest } = options;
71
- const appRoot = composeApp(root, { ...rest, http: http === false ? undefined : { ...http, hostname: "127.0.0.1", port: 0 } });
94
+ const declared = appOptionsOf(root);
95
+ const { modules: _modules, ...base } = declared ?? { modules: [] };
96
+ const merged: TestAppOptions & { readonly http?: HttpModuleOptions | Omit<HttpModuleOptions, "port" | "hostname"> | false } = { ...base, ...options };
97
+ const { http: _http, overrides, configure, kernel: kernelOptions, ...rest } = merged;
98
+ // A worker application (an `@App` without `http`) stays without a server unless the test asks for one.
99
+ const serve = options.http !== false && (declared === undefined || declared.http !== undefined || options.http !== undefined);
100
+ const http = options.http === false ? undefined : { ...declared?.http, ...options.http };
101
+ const appRoot = composeApp(root, { ...rest, http: serve ? { ...http, hostname: "127.0.0.1", port: 0 } : undefined });
72
102
  const builder = new KernelBuilder(appRoot).useOptions({ startupReport: false, ...kernelOptions, environment: kernelOptions?.environment ?? "test", signals: [] });
73
- configure?.(builder);
103
+ if (declared !== undefined) builder.useApplicationRoot(root);
104
+ declared?.configure?.(builder);
105
+ if (configure !== declared?.configure) configure?.(builder);
74
106
  if (overrides !== undefined) builder.useOverrides(overrides);
75
107
  const kernel: Kernel = await builder.build();
76
108
  await kernel.start();
@@ -79,6 +111,14 @@ export async function startTestApp(root: BazisModuleRef, options: TestAppOptions
79
111
  return {
80
112
  url,
81
113
  container: kernel.container,
114
+ use: async (service, work) => {
115
+ const scope = kernel.container.createScope();
116
+ try {
117
+ return await work(scope.resolve(service));
118
+ } finally {
119
+ await scope.dispose();
120
+ }
121
+ },
82
122
  fetch: (path, init) => {
83
123
  if (!url) throw new Error("startTestApp was started with http: false.");
84
124
  return fetch(`${url}${path}`, init);
@@ -8,4 +8,4 @@ export { StandardToolsModule } from "./StandardTools.module";
8
8
  export { toolsConfig, type ToolsSettings } from "./contracts/Tools.config";
9
9
  export { HttpRequestTool } from "./http/HttpRequest.tool";
10
10
  export { ConfigSecretStore, SecretStore, type SecretContext } from "./secrets/SecretStore";
11
- export { ormEntityTools, type OrmEntityOperation, type OrmEntityToolsOptions } from "./orm/ormEntityTools";
11
+ export { ormEntityTools, type OrmEntityOperation, type OrmEntityToolInputs, type OrmEntityToolOutputs, type OrmEntityToolSet, type OrmEntityToolsOptions, type OrmEntityWhere } from "./orm/ormEntityTools";