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.
- package/README.md +7 -4
- package/cli/generateProject.ts +11 -18
- package/cli/main.ts +1 -1
- package/cli/templates/passport.ts +1 -1
- package/core/access/catalog/moduleFields.ts +25 -2
- package/core/access/testing/index.ts +26 -4
- package/core/agent/ToolRunner.ts +2 -1
- package/core/agent/defineTool.ts +109 -0
- package/core/agent/index.ts +8 -3
- package/core/agent/moduleContributions-v1.ts +3 -10
- package/core/app/index.ts +1 -1
- package/core/app/messages.ts +3 -3
- package/core/app/runApp.ts +90 -26
- package/core/cache/ICache.ts +1 -1
- package/core/cache/README.md +4 -2
- package/core/cache/SPEC.md +16 -9
- package/core/cache/http/missingCacheModuleCheck.ts +5 -4
- package/core/cache/internal/buildCacheProviders.ts +4 -5
- package/core/cache/providers/cachedProviders.ts +1 -1
- package/core/di/index.ts +0 -4
- package/core/di/lowLevel.ts +12 -0
- package/core/di/module/index.ts +0 -3
- package/core/di/module/shortcuts.ts +31 -86
- package/core/generatedRuntime.ts +11 -0
- package/core/grpc/Grpc.module.ts +2 -1
- package/core/grpc/grpcClients.ts +2 -1
- package/core/http/Authorization/metadata.ts +1 -1
- package/core/http/Errors/HttpError.ts +1 -1
- package/core/http/Http.config.ts +22 -0
- package/core/http/HttpContext/HttpContext.ts +1 -1
- package/core/http/HttpServer.ts +10 -7
- package/core/http/OpenApi/openApiDocument.ts +1 -1
- package/core/http/httpModule.ts +10 -8
- package/core/http/index.ts +1 -0
- package/core/http/options.ts +5 -1
- package/core/http-client/httpClients.ts +2 -1
- package/core/infra/Infra.ts +3 -3
- package/core/infra/connectors/codex/CodexAppServerClient.ts +1 -1
- package/core/infra/connectors/codex/contracts.ts +3 -3
- package/core/infra/connectors/llm.ts +2 -1
- package/core/infra/connectors/redis.ts +2 -1
- package/core/kernel/KernelBuilder.ts +2 -1
- package/core/kernel/config/ConfigRegistry.ts +2 -1
- package/core/kernel/config/addConfigOptions.ts +2 -1
- package/core/kernel/config/defineConfig.ts +1 -1
- package/core/kernel/events/EventBus.ts +1 -0
- package/core/kernel/events/eventSubscribers.ts +1 -1
- package/core/kernel/events/onEvent.ts +2 -1
- package/core/orm/buildOrmProviders.ts +2 -1
- package/core/orm/encryptedWith.ts +1 -1
- package/core/orm/ormModule.ts +2 -1
- package/core/orm/registerRepositories.ts +2 -1
- package/core/scripts/di-generate.ts +52 -8
- package/core/testing/index.ts +51 -11
- package/core/tools/index.ts +1 -1
- package/core/tools/orm/ormEntityTools.ts +54 -28
- package/core/websocket/DESIGN.md +5 -3
- package/core/websocket/middleware.ts +1 -1
- package/core/websocket/websocketModule.ts +3 -3
- package/core/workflow/definitions_module/WorkflowDefinitions.module.ts +1 -2
- package/core/workflow/definitions_module/code/defineProcess.ts +213 -11
- package/core/workflow/definitions_module/code/inspectProcesses.ts +12 -2
- package/core/workflow/index.ts +14 -1
- package/core/workflow/runtime_module/services/IWorkflowRuntime.service.ts +10 -6
- package/core/workflow/runtime_module/services/WorkflowRuntime.service.ts +5 -2
- package/core/workflow/testing/index.ts +46 -4
- package/index.ts +4 -3
- package/library/terminal/messages.ts +6 -6
- package/library/validation/README.md +1 -1
- package/library/validation/SPEC.md +1 -1
- package/library/workflow/index.ts +1 -0
- package/library/workflow/nodeConfigs.ts +130 -0
- package/package.json +2 -1
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { registerFrameworkClassDeps } from "../../di/module/autoDeps";
|
|
1
|
+
import { defineTool, ToolError, type AgentToolExecutionContext, type DefinedTool } from "../../agent";
|
|
2
|
+
import type { Class } from "../../di";
|
|
4
3
|
import { ModelBuilder, type DbContext, type DbSet, type EntityModel, type FieldSelector, type Operand, type Predicate, type PropertyModel } from "../../orm";
|
|
5
4
|
|
|
6
5
|
/** What a process may do with an entity. */
|
|
7
6
|
export type OrmEntityOperation = "find" | "create" | "update" | "delete";
|
|
8
7
|
|
|
9
|
-
export interface OrmEntityToolsOptions {
|
|
8
|
+
export interface OrmEntityToolsOptions<Op extends OrmEntityOperation = OrmEntityOperation> {
|
|
10
9
|
/** The context of the entity, from `@Module({ ormBazis })`. */
|
|
11
10
|
readonly context: Class<DbContext>;
|
|
12
|
-
readonly ops: readonly
|
|
11
|
+
readonly ops: readonly Op[];
|
|
13
12
|
/** The only fields a Tool reads, filters by, sorts by and writes. The key is always read and filtered by, never written. */
|
|
14
13
|
readonly fields: readonly string[];
|
|
15
14
|
/**
|
|
@@ -28,6 +27,33 @@ export interface OrmEntityToolsOptions {
|
|
|
28
27
|
readonly maxChanges?: number;
|
|
29
28
|
}
|
|
30
29
|
|
|
30
|
+
/** A filter of records: field → a value to equal, or `{ eq, ne, gt, gte, lt, lte, in, nin, contains, startsWith, isNull }`. */
|
|
31
|
+
export type OrmEntityWhere = Readonly<Record<string, unknown>>;
|
|
32
|
+
|
|
33
|
+
/** What each Tool takes, as a step of a process maps it. */
|
|
34
|
+
export interface OrmEntityToolInputs {
|
|
35
|
+
readonly find: {
|
|
36
|
+
readonly where?: OrmEntityWhere;
|
|
37
|
+
readonly sort?: readonly { readonly field: string; readonly dir?: "asc" | "desc" }[];
|
|
38
|
+
readonly limit?: number;
|
|
39
|
+
readonly offset?: number;
|
|
40
|
+
};
|
|
41
|
+
readonly create: { readonly values: Readonly<Record<string, unknown>> };
|
|
42
|
+
readonly update: { readonly where: OrmEntityWhere; readonly values: Readonly<Record<string, unknown>> };
|
|
43
|
+
readonly delete: { readonly where: OrmEntityWhere };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** What each Tool gives back; a trial run adds `dryRun: true` to what would have changed. */
|
|
47
|
+
export interface OrmEntityToolOutputs {
|
|
48
|
+
readonly find: { readonly items: readonly Readonly<Record<string, unknown>>[]; readonly total: number };
|
|
49
|
+
readonly create: { readonly item: Readonly<Record<string, unknown>>; readonly dryRun?: boolean };
|
|
50
|
+
readonly update: { readonly updated: number; readonly dryRun?: boolean };
|
|
51
|
+
readonly delete: { readonly deleted: number; readonly dryRun?: boolean };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The Tools of the listed operations, by operation: `orderTools.find`. */
|
|
55
|
+
export type OrmEntityToolSet<Op extends OrmEntityOperation = OrmEntityOperation> = { readonly [P in Op]: DefinedTool<OrmEntityToolInputs[P], OrmEntityToolOutputs[P]> };
|
|
56
|
+
|
|
31
57
|
/** What the reference kinds `orm.entity` and `orm.field` read about a made Tool. */
|
|
32
58
|
export interface OrmEntityToolInfo {
|
|
33
59
|
readonly entity: string;
|
|
@@ -66,15 +92,20 @@ type Run = (set: DbSet<object>, input: Json, context: AgentToolExecutionContext,
|
|
|
66
92
|
/**
|
|
67
93
|
* Tools `orm.<entity>.find|create|update|delete` over an entity of the application
|
|
68
94
|
* (WORKFLOW-002 §7.4). Nothing is open by itself: the application names the
|
|
69
|
-
* operations and the fields. The result
|
|
70
|
-
*
|
|
71
|
-
*
|
|
95
|
+
* operations and the fields. The result is a set of Tools named by operation: it
|
|
96
|
+
* goes to `@Module({ tools })`, and a process names a Tool of it by reference.
|
|
97
|
+
* The module imports `StandardToolsModule` for the reference kinds `orm.entity`
|
|
98
|
+
* and `orm.field`. All of them run with `context.dryRun`: nothing is written then.
|
|
72
99
|
*
|
|
73
100
|
* ```ts
|
|
74
|
-
*
|
|
101
|
+
* export const orderTools = ormEntityTools(Order, { context: OrdersDbContext, ops: ["find", "update"], fields: ["status", "amount"], partitionField: "shopId" });
|
|
102
|
+
*
|
|
103
|
+
* @Module({ imports: [StandardToolsModule], tools: [orderTools] })
|
|
104
|
+
*
|
|
105
|
+
* serviceTask({ tool: orderTools.find, input: { where: { status: "new" } } })
|
|
75
106
|
* ```
|
|
76
107
|
*/
|
|
77
|
-
export function ormEntityTools(entity: EntityClass<object>, options: OrmEntityToolsOptions):
|
|
108
|
+
export function ormEntityTools<const Op extends OrmEntityOperation>(entity: EntityClass<object>, options: OrmEntityToolsOptions<Op>): OrmEntityToolSet<Op> {
|
|
78
109
|
const model = ModelBuilder.build(entity);
|
|
79
110
|
const name = options.name ?? entity.name.replace(/(?<=[a-z0-9])[A-Z]/g, (letter) => `-${letter}`).toLowerCase();
|
|
80
111
|
const fail = (problem: string) => new TypeError(`ormEntityTools(${entity.name}): ${problem}`);
|
|
@@ -101,10 +132,12 @@ export function ormEntityTools(entity: EntityClass<object>, options: OrmEntityTo
|
|
|
101
132
|
maxChanges,
|
|
102
133
|
};
|
|
103
134
|
const callers = options.callers ?? ["workflow"];
|
|
104
|
-
|
|
135
|
+
const tools: Partial<Record<OrmEntityOperation, DefinedTool>> = {};
|
|
136
|
+
for (const op of new Set<OrmEntityOperation>(options.ops)) {
|
|
105
137
|
if (!Object.hasOwn(OPERATIONS, op)) throw fail(`unknown operation ${JSON.stringify(op)}`);
|
|
106
|
-
|
|
107
|
-
}
|
|
138
|
+
tools[op] = madeTool(spec, op, callers);
|
|
139
|
+
}
|
|
140
|
+
return Object.freeze(tools) as OrmEntityToolSet<Op>;
|
|
108
141
|
}
|
|
109
142
|
|
|
110
143
|
function limit(value: number | undefined, fallback: number, max: number, fail: (problem: string) => Error, name: string): number {
|
|
@@ -113,10 +146,9 @@ function limit(value: number | undefined, fallback: number, max: number, fail: (
|
|
|
113
146
|
return value;
|
|
114
147
|
}
|
|
115
148
|
|
|
116
|
-
function
|
|
149
|
+
function madeTool(spec: Spec, op: OrmEntityOperation, callers: readonly string[]): DefinedTool {
|
|
117
150
|
const { describe, run, sideEffect, input, output } = OPERATIONS[op];
|
|
118
|
-
|
|
119
|
-
@Tool({
|
|
151
|
+
const tool = defineTool({
|
|
120
152
|
name: `orm.${spec.name}.${op}`,
|
|
121
153
|
description: describe(spec.entity.name),
|
|
122
154
|
sideEffect,
|
|
@@ -124,19 +156,13 @@ function toolClass(spec: Spec, op: OrmEntityOperation, callers: readonly string[
|
|
|
124
156
|
dryRun: "supported",
|
|
125
157
|
inputSchema: input(spec),
|
|
126
158
|
outputSchema: output(spec),
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
constructor(private readonly services: ServiceProvider) {}
|
|
130
|
-
|
|
131
|
-
async execute(raw: unknown, context: AgentToolExecutionContext): Promise<unknown> {
|
|
132
|
-
const db = this.services.resolve(spec.context) as DbContext;
|
|
159
|
+
execute: async (raw, context, services) => {
|
|
160
|
+
const db = services.resolve(spec.context) as DbContext;
|
|
133
161
|
return await run(spec)(db.setOf(spec.entity), inputOf(raw), context, db);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
INFO.set(OrmEntityTool, { entity: spec.entity.name, fields: spec.readable });
|
|
139
|
-
return OrmEntityTool;
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
INFO.set(tool, { entity: spec.entity.name, fields: spec.readable });
|
|
165
|
+
return tool;
|
|
140
166
|
}
|
|
141
167
|
|
|
142
168
|
interface Operation {
|
package/core/websocket/DESIGN.md
CHANGED
|
@@ -30,7 +30,8 @@ import { Module, singleton } from "@/core/di";
|
|
|
30
30
|
@Module({ gateways: [ChatGateway], providers: [singleton(ChatHistory)] })
|
|
31
31
|
export class ChatModule {}
|
|
32
32
|
|
|
33
|
-
|
|
33
|
+
@App({ modules: [AppModule], http: {}, websocket: { requireAuth: true, authenticator } })
|
|
34
|
+
export class Application {}
|
|
34
35
|
```
|
|
35
36
|
|
|
36
37
|
Without `runApp`, `websocketModule({ imports: [ChatModule], ... })` next to
|
|
@@ -101,7 +102,7 @@ default, `replayDelivery: "transport"`.
|
|
|
101
102
|
### Client-confirmed replay
|
|
102
103
|
|
|
103
104
|
Opt in with `?replay=client-ack` on each connection, or require it for all clients
|
|
104
|
-
with
|
|
105
|
+
with `@App({ websocket: { replayDelivery: "client-ack" } })`. The adapter
|
|
105
106
|
must support CAS. A saved client-ack session cannot reconnect in transport mode;
|
|
106
107
|
such an upgrade returns 409. Invalid/duplicate replay query values return 400.
|
|
107
108
|
|
|
@@ -150,7 +151,8 @@ Pass an existing native Bun RedisClient from the host infrastructure:
|
|
|
150
151
|
const adapter = new RedisWebSocketAdapter(hostRedisClient, {
|
|
151
152
|
keyPrefix: "my-app:ws", // same on participating nodes; distinct per application
|
|
152
153
|
});
|
|
153
|
-
|
|
154
|
+
@App({ modules: [AppModule], http: {}, websocket: { adapter, replayDelivery: "client-ack" } })
|
|
155
|
+
export class Application {}
|
|
154
156
|
```
|
|
155
157
|
|
|
156
158
|
The adapter owns only a duplicate connection for pub/sub. Closing the adapter
|
|
@@ -26,7 +26,7 @@ export interface WsAuthenticationContext {
|
|
|
26
26
|
readonly request?: Request;
|
|
27
27
|
/**
|
|
28
28
|
* The application's services, for a token check that needs them
|
|
29
|
-
* (`services.resolve(AuthTokens)`). Set by
|
|
29
|
+
* (`services.resolve(AuthTokens)`). Set by `@App({ websocket })`.
|
|
30
30
|
*/
|
|
31
31
|
readonly services?: ServiceResolver;
|
|
32
32
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import {
|
|
2
|
-
DI,
|
|
3
2
|
collectModuleGateways,
|
|
4
3
|
markGlobal,
|
|
5
4
|
Module,
|
|
@@ -8,6 +7,7 @@ import {
|
|
|
8
7
|
type ProviderDefinition,
|
|
9
8
|
type ServiceResolver,
|
|
10
9
|
} from "../di";
|
|
10
|
+
import { DI } from "../di/lowLevel";
|
|
11
11
|
import { WEBSOCKET_UPGRADE } from "../http";
|
|
12
12
|
import { LOGGER } from "../kernel";
|
|
13
13
|
import { WebSocketService } from "./WebSocketService";
|
|
@@ -54,13 +54,13 @@ export interface WebSocketModuleConfig {
|
|
|
54
54
|
readonly exposeHandlerErrors?: boolean;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
/** Server-wide WebSocket settings of
|
|
57
|
+
/** Server-wide WebSocket settings of `@App({ websocket })`; gateways come from the modules. */
|
|
58
58
|
export type WebSocketOptions = Omit<WebSocketModuleConfig, "imports">;
|
|
59
59
|
|
|
60
60
|
/**
|
|
61
61
|
* Serves the gateways declared by the modules of `imports` on the shared HTTP
|
|
62
62
|
* listener. `runApp` installs it next to the HTTP module whenever a module
|
|
63
|
-
* declares `gateways`;
|
|
63
|
+
* declares `gateways`; `@App({ websocket })` passes the settings.
|
|
64
64
|
*
|
|
65
65
|
* ```ts
|
|
66
66
|
* @Module({ gateways: [ChatGateway], providers: [singleton(ChatHistory)] })
|
|
@@ -12,7 +12,6 @@ import { definitionsPermissions } from "./access/Definitions.permissions";
|
|
|
12
12
|
import { FolderReferences } from "./access/Folder.references";
|
|
13
13
|
import { ProcessReferences } from "./access/Process.references";
|
|
14
14
|
import { ProcessFolderLookup } from "./access/ProcessFolder.lookup";
|
|
15
|
-
import { ProcessPartitionLookup } from "./access/ProcessPartition.lookup";
|
|
16
15
|
import { CatalogImport } from "./code/CatalogImport";
|
|
17
16
|
import { CodeProcessCatalog } from "./code/CodeProcessCatalog";
|
|
18
17
|
import { CodeProcessPublisher } from "./code/CodeProcessPublisher";
|
|
@@ -48,8 +47,8 @@ import { WorkflowDefinitions } from "./services/WorkflowDefinitions.service";
|
|
|
48
47
|
scoped(WorkflowReferences),
|
|
49
48
|
scoped(CatalogImport),
|
|
50
49
|
scoped(IWorkflowDefinitions, WorkflowDefinitions),
|
|
50
|
+
// Shared with the Runtime and Tasks parts: owned and exported here.
|
|
51
51
|
scoped(ProcessFolderLookup),
|
|
52
|
-
scoped(ProcessPartitionLookup),
|
|
53
52
|
singleton(HOSTED_SERVICE, CodeProcessPublisher),
|
|
54
53
|
],
|
|
55
54
|
controllers: [ProcessesController],
|
|
@@ -1,9 +1,134 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { toolNameOf, type DefinedTool } from "../../../agent";
|
|
2
|
+
import type {
|
|
3
|
+
Expr,
|
|
4
|
+
LocalizedText,
|
|
5
|
+
NodeConfigs,
|
|
6
|
+
NodeKind,
|
|
7
|
+
ProcessDiagram,
|
|
8
|
+
ProcessDocument,
|
|
9
|
+
ProcessFlow,
|
|
10
|
+
ProcessNode,
|
|
11
|
+
ProcessNodeOf,
|
|
12
|
+
ProcessSettings,
|
|
13
|
+
TypedProcessFlow,
|
|
14
|
+
TypedProcessNode,
|
|
15
|
+
VariableSpec,
|
|
16
|
+
} from "../../../../library/workflow";
|
|
2
17
|
|
|
3
18
|
const CODE_PROCESS = Symbol.for("bazis/core/workflow/code-process");
|
|
19
|
+
declare const PROCESS_TYPES: unique symbol;
|
|
20
|
+
|
|
21
|
+
/** A class with `@Tool`: a process names it instead of writing its name. */
|
|
22
|
+
export type ToolClass = abstract new (...args: never[]) => { execute(...args: never[]): unknown };
|
|
23
|
+
/** A Tool of a step: by reference (a class with `@Tool`, a Tool made by `defineTool`), or by name. */
|
|
24
|
+
export type ToolRef = string | ToolClass | DefinedTool;
|
|
25
|
+
/** A process another one calls or hands its failures to: by reference, or by key. */
|
|
26
|
+
export type ProcessRef = string | CodeProcess;
|
|
27
|
+
|
|
28
|
+
/** The node configs a process in code may write: a Tool and a process by reference. */
|
|
29
|
+
export interface CodeNodeConfigs extends Omit<NodeConfigs, "serviceTask" | "callProcess"> {
|
|
30
|
+
readonly serviceTask: Omit<NodeConfigs["serviceTask"], "tool"> & { readonly tool: ToolRef };
|
|
31
|
+
readonly callProcess: Omit<NodeConfigs["callProcess"], "process"> & { readonly process: ProcessRef };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A node as code writes it: the `config` of its kind, the ids of the document's own nodes. */
|
|
35
|
+
export type CodeProcessNode<Id extends string = string> = TypedProcessNode<Id, CodeNodeConfigs>;
|
|
36
|
+
|
|
37
|
+
/** The settings of a process in code: the error handler by reference. */
|
|
38
|
+
export interface CodeProcessSettings extends Omit<ProcessSettings, "errorHandler"> {
|
|
39
|
+
/** The process to start when an instance fails or times out. */
|
|
40
|
+
readonly errorHandler?: ProcessRef;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
type FieldValue<F> =
|
|
44
|
+
F extends { readonly type: "enum"; readonly values: readonly (infer Value)[] } ? Value
|
|
45
|
+
: F extends { readonly type: "string" | "text" | "date" | "datetime" | "ref" | "enum" } ? string
|
|
46
|
+
: F extends { readonly type: "number" | "integer" } ? number
|
|
47
|
+
: F extends { readonly type: "boolean" } ? boolean
|
|
48
|
+
: F extends { readonly type: "list" } ? readonly unknown[]
|
|
49
|
+
: F extends { readonly type: "object" } ? Readonly<Record<string, unknown>>
|
|
50
|
+
: unknown;
|
|
51
|
+
|
|
52
|
+
type Flat<T> = { readonly [K in keyof T]: T[K] };
|
|
53
|
+
|
|
54
|
+
/** What a start of the process takes: its `in` variables; the `required` ones must be there. */
|
|
55
|
+
export type ProcessInput<V extends readonly VariableSpec[]> = string extends V[number]["name"]
|
|
56
|
+
? Readonly<Record<string, unknown>>
|
|
57
|
+
: Flat<
|
|
58
|
+
& { [F in V[number] as F extends { readonly direction: "in"; readonly required: true } ? F["name"] : never]: FieldValue<F> }
|
|
59
|
+
& { [F in V[number] as F extends { readonly direction: "in" } ? (F extends { readonly required: true } ? never : F["name"]) : never]?: FieldValue<F> }
|
|
60
|
+
>;
|
|
61
|
+
|
|
62
|
+
/** What a finished process gives back: its `out` variables. */
|
|
63
|
+
export type ProcessOutput<V extends readonly VariableSpec[]> = string extends V[number]["name"]
|
|
64
|
+
? Readonly<Record<string, unknown>>
|
|
65
|
+
: Flat<{ [F in V[number] as F extends { readonly direction: "out" } ? F["name"] : never]: FieldValue<F> | null }>;
|
|
66
|
+
|
|
67
|
+
/** What a Tool takes: the parameter of its `execute`. `unknown` when it does not say. */
|
|
68
|
+
type ToolInputOf<T> =
|
|
69
|
+
T extends DefinedTool<infer Input, unknown> ? Input
|
|
70
|
+
: T extends abstract new (...args: never[]) => { execute(input: infer Input, ...rest: never[]): unknown } ? Input
|
|
71
|
+
: unknown;
|
|
72
|
+
|
|
73
|
+
/** `config.input` of a step against what its Tool or process takes: every required parameter, no unknown one. */
|
|
74
|
+
type InputOf<Target, Given> = unknown extends Target ? unknown
|
|
75
|
+
: Target extends object
|
|
76
|
+
? string extends keyof Target ? unknown
|
|
77
|
+
: { readonly config: ({} extends Target ? { readonly input?: MappingOf<Target, Given> } : { readonly input: MappingOf<Target, Given> }) }
|
|
78
|
+
: unknown;
|
|
79
|
+
|
|
80
|
+
type MappingOf<Target, Given> = { readonly [P in keyof Target]: Expr } & { readonly [P in Exclude<keyof Given, keyof Target>]?: never };
|
|
81
|
+
|
|
82
|
+
type CheckedInput<Node> =
|
|
83
|
+
Node extends { readonly kind: "serviceTask"; readonly config: { readonly tool: infer Tool; readonly input?: infer Given } } ? InputOf<ToolInputOf<Tool>, Given>
|
|
84
|
+
: Node extends { readonly kind: "callProcess"; readonly config: { readonly process: infer Called; readonly input?: infer Given } }
|
|
85
|
+
? (Called extends CodeProcess<infer Input, unknown> ? InputOf<Input, Given> : unknown)
|
|
86
|
+
: unknown;
|
|
87
|
+
|
|
88
|
+
/** The nodes of a document, as `defineProcess` reads their type. */
|
|
89
|
+
export type CodeProcessNodes = Readonly<Record<string, ProcessNode | CodeProcessNode>>;
|
|
90
|
+
|
|
91
|
+
type KeysOf<T> = T extends unknown ? keyof T : never;
|
|
92
|
+
type ValueOf<T, K extends PropertyKey> = T extends unknown ? (K extends keyof T ? T[K] : never) : never;
|
|
93
|
+
/** Whether a value of this type is not a closed object: a primitive, a list of anything, a map by any key. */
|
|
94
|
+
type IsOpen<T> = T extends unknown ? (T extends readonly unknown[] ? false : T extends object ? (string extends keyof T ? true : false) : true) : never;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* `Given` with every key the allowed type does not know turned into `never`:
|
|
98
|
+
* a misspelled optional field is an error, not a field nobody reads.
|
|
99
|
+
*/
|
|
100
|
+
type Exact<Given, Allowed> =
|
|
101
|
+
true extends IsOpen<NonNullable<Allowed>> ? unknown
|
|
102
|
+
: Given extends readonly (infer Item)[] ? (NonNullable<Allowed> extends readonly (infer AllowedItem)[] ? readonly Exact<Item, AllowedItem>[] : unknown)
|
|
103
|
+
: Given extends object ? { readonly [P in keyof Given]: P extends KeysOf<NonNullable<Allowed>> ? Exact<Given[P], ValueOf<NonNullable<Allowed>, P>> : never }
|
|
104
|
+
: unknown;
|
|
105
|
+
|
|
106
|
+
type ExactNode<Node, Id extends string> = Node extends { readonly kind: infer Kind extends NodeKind } ? Exact<Node, ProcessNodeOf<Kind, Id, CodeNodeConfigs>> : unknown;
|
|
107
|
+
|
|
108
|
+
/** What the nodes written as a literal must also be: of their kind, with known fields, with the input their Tool takes. */
|
|
109
|
+
type CheckedNodes<N> = string extends keyof N ? unknown : { readonly [Id in keyof N]: CodeProcessNode<keyof N & string> & CheckedInput<N[Id]> & ExactNode<N[Id], keyof N & string> };
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The document of a process in code. Written as a literal, it is checked while
|
|
113
|
+
* you type: the `config` of each node kind, the nodes that flows, `attachedTo`
|
|
114
|
+
* and `parent` name, the input of a Tool or a called process given by
|
|
115
|
+
* reference. A document that already exists as data (exported from a designer,
|
|
116
|
+
* built by a function, upgraded from version 1) is taken as it is.
|
|
117
|
+
*/
|
|
118
|
+
export interface CodeProcessDocument<V extends readonly VariableSpec[], N extends CodeProcessNodes> {
|
|
119
|
+
readonly schemaVersion: ProcessDocument["schemaVersion"];
|
|
120
|
+
/** `in` — the input of a start, `local` — inside the process, `out` — what it gives back. */
|
|
121
|
+
readonly variables?: V;
|
|
122
|
+
readonly settings?: CodeProcessSettings;
|
|
123
|
+
readonly nodes: N & CheckedNodes<N>;
|
|
124
|
+
readonly flows: Readonly<Record<string, string extends keyof N ? ProcessFlow : TypedProcessFlow<keyof N & string>>>;
|
|
125
|
+
readonly diagram?: ProcessDiagram;
|
|
126
|
+
/** The application's data by namespace; the engine does not read it. */
|
|
127
|
+
readonly extensions?: Readonly<Record<string, unknown>>;
|
|
128
|
+
}
|
|
4
129
|
|
|
5
130
|
/** What `defineProcess` takes: the catalog fields of the process and its document. */
|
|
6
|
-
export interface ProcessDefinition {
|
|
131
|
+
export interface ProcessDefinition<V extends readonly VariableSpec[] = readonly VariableSpec[], N extends CodeProcessNodes = CodeProcessNodes> {
|
|
7
132
|
/** The key it is started by: `^[a-z][a-z0-9_.-]{0,63}$`. */
|
|
8
133
|
readonly key: string;
|
|
9
134
|
readonly title: LocalizedText;
|
|
@@ -14,12 +139,27 @@ export interface ProcessDefinition {
|
|
|
14
139
|
readonly owner?: string | null;
|
|
15
140
|
/** Days to keep completed and cancelled instances; omitted keeps them. */
|
|
16
141
|
readonly retentionDays?: number | null;
|
|
17
|
-
readonly document:
|
|
142
|
+
readonly document: CodeProcessDocument<V, N>;
|
|
18
143
|
}
|
|
19
144
|
|
|
20
|
-
/**
|
|
21
|
-
|
|
145
|
+
/**
|
|
146
|
+
* A process described in code: listed in `@Module({ processes })` and published
|
|
147
|
+
* at start (WORKFLOW-001 §14). `Input` and `Output` come from its variables:
|
|
148
|
+
* `runtime.start(process, { input })` and a `callProcess` step are checked by them.
|
|
149
|
+
* Plain `CodeProcess` is any process.
|
|
150
|
+
*/
|
|
151
|
+
export interface CodeProcess<Input = never, Output = unknown> {
|
|
152
|
+
readonly key: string;
|
|
153
|
+
readonly title: LocalizedText;
|
|
154
|
+
readonly description?: LocalizedText | null;
|
|
155
|
+
readonly folder?: string | null;
|
|
156
|
+
readonly owner?: string | null;
|
|
157
|
+
readonly retentionDays?: number | null;
|
|
158
|
+
/** The document as it is stored: Tools by name, processes by key. */
|
|
159
|
+
readonly document: ProcessDocument;
|
|
22
160
|
readonly [CODE_PROCESS]: true;
|
|
161
|
+
/** Only for the types. */
|
|
162
|
+
readonly [PROCESS_TYPES]?: { readonly input: (input: Input) => void; readonly output: Output };
|
|
23
163
|
}
|
|
24
164
|
|
|
25
165
|
/**
|
|
@@ -27,20 +167,82 @@ export interface CodeProcess extends ProcessDefinition {
|
|
|
27
167
|
* description: checks happen when the container is built and at start.
|
|
28
168
|
*
|
|
29
169
|
* ```ts
|
|
30
|
-
* //
|
|
31
|
-
* export const
|
|
170
|
+
* // order/process/OrderApproval.process.ts
|
|
171
|
+
* export const orderApproval = defineProcess({
|
|
32
172
|
* key: "order-approval",
|
|
33
173
|
* title: "Order approval",
|
|
34
|
-
* document: {
|
|
174
|
+
* document: {
|
|
175
|
+
* schemaVersion: "bazis.workflow/v2",
|
|
176
|
+
* variables: [{ name: "orderId", type: "string", direction: "in", required: true }],
|
|
177
|
+
* nodes: {
|
|
178
|
+
* Start: { kind: "manualStart", title: "Start" },
|
|
179
|
+
* Approve: { kind: "serviceTask", title: "Approve", config: { tool: SetOrderStatusTool, input: { orderId: "$input.orderId", status: "approved" } } },
|
|
180
|
+
* End: { kind: "end", title: "End" },
|
|
181
|
+
* },
|
|
182
|
+
* flows: { a: { source: "Start", target: "Approve" }, b: { source: "Approve", target: "End" } },
|
|
183
|
+
* },
|
|
35
184
|
* });
|
|
185
|
+
*
|
|
186
|
+
* await runtime.start(orderApproval, { actor, input: { orderId: "o-1" } });
|
|
36
187
|
* ```
|
|
37
188
|
*
|
|
38
|
-
* A
|
|
189
|
+
* A Tool is named by its class (or by a Tool made by `defineTool`:
|
|
190
|
+
* `orderTools.find`), a called process and the error handler by their
|
|
191
|
+
* `defineProcess` result; a name or a key in a string is still taken, for what
|
|
192
|
+
* the module does not see. A document of version 1 goes through `upgradeDocument`.
|
|
39
193
|
*/
|
|
40
|
-
export function defineProcess
|
|
41
|
-
|
|
194
|
+
export function defineProcess<const V extends readonly VariableSpec[] = readonly VariableSpec[], const N extends CodeProcessNodes = Readonly<Record<string, ProcessNode>>>(
|
|
195
|
+
definition: ProcessDefinition<V, N>,
|
|
196
|
+
): CodeProcess<ProcessInput<V>, ProcessOutput<V>> {
|
|
197
|
+
const { document, ...catalog } = definition;
|
|
198
|
+
return Object.freeze({ ...catalog, document: storedDocument(String(definition.key), document as unknown as LooseDocument), [CODE_PROCESS]: true as const });
|
|
42
199
|
}
|
|
43
200
|
|
|
44
201
|
export function isCodeProcess(value: unknown): value is CodeProcess {
|
|
45
202
|
return typeof value === "object" && value !== null && (value as Record<symbol, unknown>)[CODE_PROCESS] === true;
|
|
46
203
|
}
|
|
204
|
+
|
|
205
|
+
interface LooseDocument {
|
|
206
|
+
readonly settings?: { readonly errorHandler?: unknown };
|
|
207
|
+
readonly nodes?: unknown;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The document with its references written as the engine stores them: a Tool by name, a process by key. */
|
|
211
|
+
function storedDocument(key: string, document: LooseDocument): ProcessDocument {
|
|
212
|
+
// A wrong shape is the business of the checks at start: they name every problem at once.
|
|
213
|
+
if (typeof document !== "object" || document === null) return document as unknown as ProcessDocument;
|
|
214
|
+
const out: Record<string, unknown> = { ...document };
|
|
215
|
+
if (typeof document.settings === "object" && document.settings !== null && document.settings.errorHandler !== undefined) {
|
|
216
|
+
out.settings = { ...document.settings, errorHandler: processKeyOf(key, "settings.errorHandler", document.settings.errorHandler) };
|
|
217
|
+
}
|
|
218
|
+
if (typeof document.nodes === "object" && document.nodes !== null && !Array.isArray(document.nodes)) {
|
|
219
|
+
const nodes: Record<string, unknown> = {};
|
|
220
|
+
for (const [id, node] of Object.entries(document.nodes as Record<string, unknown>)) nodes[id] = storedNode(key, id, node);
|
|
221
|
+
out.nodes = nodes;
|
|
222
|
+
}
|
|
223
|
+
return out as unknown as ProcessDocument;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function storedNode(key: string, id: string, node: unknown): unknown {
|
|
227
|
+
if (typeof node !== "object" || node === null) return node;
|
|
228
|
+
const { kind, config } = node as { readonly kind?: unknown; readonly config?: unknown };
|
|
229
|
+
if (typeof config !== "object" || config === null) return node;
|
|
230
|
+
const fields = config as Record<string, unknown>;
|
|
231
|
+
if (kind === "serviceTask" && typeof fields.tool === "function") {
|
|
232
|
+
const name = toolNameOf(fields.tool);
|
|
233
|
+
if (name === undefined) {
|
|
234
|
+
throw new TypeError(`defineProcess("${key}"): node "${id}" names ${fields.tool.name || "a class"} as its Tool, but it is neither a class with @Tool nor a Tool made by defineTool.`);
|
|
235
|
+
}
|
|
236
|
+
return { ...node, config: { ...fields, tool: name } };
|
|
237
|
+
}
|
|
238
|
+
if (kind === "callProcess" && typeof fields.process !== "string" && fields.process !== undefined) {
|
|
239
|
+
return { ...node, config: { ...fields, process: processKeyOf(key, `node "${id}"`, fields.process) } };
|
|
240
|
+
}
|
|
241
|
+
return node;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function processKeyOf(key: string, where: string, value: unknown): unknown {
|
|
245
|
+
if (typeof value === "string") return value;
|
|
246
|
+
if (isCodeProcess(value)) return value.key;
|
|
247
|
+
throw new TypeError(`defineProcess("${key}"): ${where} must name a process by its key or by its defineProcess(...) result.`);
|
|
248
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { expandModuleMetadata, type BazisModuleRef } from "../../../di";
|
|
2
2
|
import { describeTool, toolMetadataOf } from "../../../agent";
|
|
3
|
+
import { moduleToolsOf } from "../../../agent/defineTool";
|
|
3
4
|
import { documentReferences, schemaReferenceKinds, validateProcess } from "../../../../library/workflow";
|
|
4
5
|
import { WORKFLOW_CALLER } from "../../internal/WorkflowTools";
|
|
5
6
|
import { WorkflowDefinitionsModule } from "../WorkflowDefinitions.module";
|
|
@@ -38,8 +39,8 @@ export function inspectProcesses(root: BazisModuleRef): ProcessInspection {
|
|
|
38
39
|
const fields = moduleRef as { readonly processes?: unknown; readonly tools?: unknown; readonly references?: unknown };
|
|
39
40
|
if (typeof fields.references === "object" && fields.references !== null) for (const kind of Object.keys(fields.references)) kinds.add(kind);
|
|
40
41
|
if (Array.isArray(fields.tools)) {
|
|
41
|
-
for (const target of fields.tools) {
|
|
42
|
-
const metadata =
|
|
42
|
+
for (const target of toolsOrNone(fields.tools)) {
|
|
43
|
+
const metadata = toolMetadataOf(target as new () => object);
|
|
43
44
|
if (metadata?.callers.includes(WORKFLOW_CALLER)) {
|
|
44
45
|
tools.add(metadata.name);
|
|
45
46
|
const input = describeTool({ target: target as new () => object, metadata }).input;
|
|
@@ -83,3 +84,12 @@ export function inspectProcesses(root: BazisModuleRef): ProcessInspection {
|
|
|
83
84
|
tools: [...tools].sort(),
|
|
84
85
|
};
|
|
85
86
|
}
|
|
87
|
+
|
|
88
|
+
/** The Tools of a module; a wrong list is reported by the start, not by the check. */
|
|
89
|
+
function toolsOrNone(tools: unknown): readonly unknown[] {
|
|
90
|
+
try {
|
|
91
|
+
return moduleToolsOf(tools);
|
|
92
|
+
} catch {
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
}
|
package/core/workflow/index.ts
CHANGED
|
@@ -11,7 +11,20 @@ import type { tasksPermissions } from "./tasks_module/access/Tasks.permissions";
|
|
|
11
11
|
import "./generated/deps";
|
|
12
12
|
|
|
13
13
|
export { WorkflowModule } from "./Workflow.module";
|
|
14
|
-
export {
|
|
14
|
+
export {
|
|
15
|
+
defineProcess,
|
|
16
|
+
type CodeNodeConfigs,
|
|
17
|
+
type CodeProcess,
|
|
18
|
+
type CodeProcessDocument,
|
|
19
|
+
type CodeProcessNode,
|
|
20
|
+
type CodeProcessSettings,
|
|
21
|
+
type ProcessDefinition,
|
|
22
|
+
type ProcessInput,
|
|
23
|
+
type ProcessOutput,
|
|
24
|
+
type ProcessRef,
|
|
25
|
+
type ToolClass,
|
|
26
|
+
type ToolRef,
|
|
27
|
+
} from "./definitions_module/code/defineProcess";
|
|
15
28
|
export { WorkflowSetupError } from "./definitions_module/code/codeProcesses";
|
|
16
29
|
export { WorkflowClock, SystemWorkflowClock } from "./contracts/WorkflowClock";
|
|
17
30
|
export { WorkflowDefinitionsModule } from "./definitions_module/WorkflowDefinitions.module";
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import type { AccessFilter } from "../../../access";
|
|
2
2
|
import type { FormIssue } from "../../../../library/workflow";
|
|
3
3
|
import type { OrmTransaction } from "../../../orm";
|
|
4
|
+
import type { CodeProcess } from "../../definitions_module/code/defineProcess";
|
|
4
5
|
import type { WorkflowActor, WorkflowAuditOptions, WorkflowPage, WorkflowPaging } from "../../contracts/types";
|
|
5
6
|
import type { HistoryType } from "../model/WfHistory.model";
|
|
6
7
|
import type { InstanceStatus, StartedVia } from "../model/WfInstance.model";
|
|
7
8
|
import type { TokenStatus } from "../model/WfToken.model";
|
|
8
9
|
|
|
9
|
-
export interface StartInstance extends WorkflowAuditOptions {
|
|
10
|
-
|
|
10
|
+
export interface StartInstance<Input = unknown> extends WorkflowAuditOptions {
|
|
11
|
+
/** The `in` variables of the process. */
|
|
12
|
+
readonly input?: Input;
|
|
11
13
|
/** The application's scope: a space, an organization. */
|
|
12
14
|
readonly partition?: string | null;
|
|
13
15
|
/** The application's own key of what the instance is about: `order:42`. */
|
|
@@ -24,14 +26,14 @@ export interface StartInstance extends WorkflowAuditOptions {
|
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
/** One element of a mass start. */
|
|
27
|
-
export interface StartManyItem {
|
|
28
|
-
readonly input?:
|
|
29
|
+
export interface StartManyItem<Input = unknown> {
|
|
30
|
+
readonly input?: Input;
|
|
29
31
|
/** What the instance is about: required, it is what `sameKey` compares. */
|
|
30
32
|
readonly businessKey: string;
|
|
31
33
|
}
|
|
32
34
|
|
|
33
|
-
export interface StartMany extends WorkflowAuditOptions {
|
|
34
|
-
readonly items: readonly StartManyItem[];
|
|
35
|
+
export interface StartMany<Input = unknown> extends WorkflowAuditOptions {
|
|
36
|
+
readonly items: readonly StartManyItem<Input>[];
|
|
35
37
|
readonly partition?: string | null;
|
|
36
38
|
readonly actor: WorkflowActor;
|
|
37
39
|
readonly language?: string;
|
|
@@ -163,8 +165,10 @@ export interface InstanceListQuery extends WorkflowPaging {
|
|
|
163
165
|
*/
|
|
164
166
|
export abstract class IWorkflowRuntime {
|
|
165
167
|
/** Starts the latest version of a process from its manual start. It may wait as `pending` (`maxConcurrent`, `sameKey: "queue"`). */
|
|
168
|
+
abstract start<Input>(process: CodeProcess<Input, unknown>, options: StartInstance<Input>): Promise<InstanceDetails>;
|
|
166
169
|
abstract start(processKey: string, options: StartInstance): Promise<InstanceDetails>;
|
|
167
170
|
/** Starts an instance per element, each in its own transaction, and says what became of each. */
|
|
171
|
+
abstract startMany<Input>(process: CodeProcess<Input, unknown>, options: StartMany<Input>): Promise<readonly StartManyResult[]>;
|
|
168
172
|
abstract startMany(processKey: string, options: StartMany): Promise<readonly StartManyResult[]>;
|
|
169
173
|
abstract cancel(instanceId: string, options: CancelInstance): Promise<InstanceDetails>;
|
|
170
174
|
/** Retries the failed steps of a `failed` instance. An instance called by another one is retried through its caller. */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CodeProcess } from "../../definitions_module/code/defineProcess";
|
|
1
2
|
import { grantsToWhere } from "../../../access";
|
|
2
3
|
import { paginate, type OrmTransaction } from "../../../orm";
|
|
3
4
|
import { inputSpecOf, type FormSpec } from "../../../../library/workflow";
|
|
@@ -46,7 +47,8 @@ export class WorkflowRuntime extends IWorkflowRuntime {
|
|
|
46
47
|
super();
|
|
47
48
|
}
|
|
48
49
|
|
|
49
|
-
async start(
|
|
50
|
+
async start(process: string | CodeProcess<unknown, unknown>, options: StartInstance): Promise<InstanceDetails> {
|
|
51
|
+
const processKey = typeof process === "string" ? process : process.key;
|
|
50
52
|
actorOf(options.actor);
|
|
51
53
|
const partition = optionalText(options.partition, "partition");
|
|
52
54
|
const businessKey = optionalText(options.businessKey, "businessKey");
|
|
@@ -60,7 +62,8 @@ export class WorkflowRuntime extends IWorkflowRuntime {
|
|
|
60
62
|
return await this.instance(id);
|
|
61
63
|
}
|
|
62
64
|
|
|
63
|
-
async startMany(
|
|
65
|
+
async startMany(process: string | CodeProcess<unknown, unknown>, options: StartMany): Promise<readonly StartManyResult[]> {
|
|
66
|
+
const processKey = typeof process === "string" ? process : process.key;
|
|
64
67
|
actorOf(options.actor);
|
|
65
68
|
const partition = optionalText(options.partition, "partition");
|
|
66
69
|
if (!Array.isArray(options.items) || options.items.length === 0 || options.items.length > MAX_START_MANY) throw new WorkflowError("invalid_input", `items must be a list of 1–${MAX_START_MANY}`);
|