@brickkit/core 0.15.0 → 0.16.0-beta.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.
@@ -1,6 +1,6 @@
1
1
  import { Static, TIntersect, TNumber, TObject, TSchema, TString, TUnion } from "@sinclair/typebox";
2
+ import { SQLiteColumnBuilderBase, blob, foreignKey, index, integer, primaryKey, real, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
2
3
  import { Table } from "drizzle-orm";
3
- import { SQLiteColumnBuilderBase, blob, foreignKey, index as index$1, integer as integer$1, primaryKey, real as real$1, sqliteTable as sqliteTable$1, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
4
4
  import { BunSQLiteDatabase, BunSQLiteDatabase as BunSQLiteDatabase$1 } from "drizzle-orm/bun-sqlite";
5
5
  import { Sql } from "postgres";
6
6
  import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
@@ -8,55 +8,170 @@ import { Database } from "bun:sqlite";
8
8
  /** The HTTP methods an action, endpoint or plugin route can use. */
9
9
  declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE"];
10
10
  type HttpMethod = (typeof HTTP_METHODS)[number];
11
- declare const portType: unique symbol;
12
- /** A typed dependency slot, declared with `port<T>()` and filled by `brick({ deps })`. */
13
- interface Port<T> {
14
- readonly [portType]?: T;
15
- }
16
- /** The dependency slots of a service: `{ carrier: port<Carrier>() }`. */
17
- type Ports = Record<string, Port<unknown>>;
18
- /** The values a set of ports is filled with: `{ carrier: Carrier }`. */
19
- type DepsOf<P> = { [K in keyof P]: P[K] extends Port<infer T> ? T : never; };
20
11
  /**
21
- * Declare a dependency a service needs, without creating it. The app provides
22
- * the value with `brick({ deps })`, and the service's code reads it as
23
- * `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).
12
+ * Type-safe secrets & environment variables.
24
13
  *
25
- * @returns A slot typed as `T`. It holds nothing at runtime.
26
- * @example
27
- * import { defineService, port } from "@brickkit/core";
14
+ * Declare each secret once at module scope instead of scattering untyped
15
+ * `process.env.FOO` reads:
28
16
  *
29
- * export const orders = defineService("orders", {
30
- * database,
31
- * deps: { carrier: port<Carrier>() },
32
- * });
17
+ * const port = defineSecret("PORT").default("3333").transform(Number).require();
18
+ * const baseUrl = defineSecret("BASE_URL").url().require();
19
+ * const key = defineSecret("STRIPE_KEY").validate((v) =>
20
+ * v.startsWith("sk_") || "must start with sk_"
21
+ * ).require();
22
+ *
23
+ * Values resolve from the environment (Bun populates `process.env` from
24
+ * `.env` locally; in prod the same env source applies — a future
25
+ * `SecretSource` such as AWS can slot in without touching call sites).
33
26
  *
34
- * // app.ts
35
- * export default brick({ services: [orders], deps: { carrier: createCarrier() } });
27
+ * Resolution order per secret: test/session override → source (`process.env`
28
+ * by default) → declared `default`. `resolveSecrets()` validates every
29
+ * registered secret at boot and throws listing all missing required ones.
36
30
  */
37
- declare function port<T>(): Port<T>;
31
+ interface SecretSource {
32
+ get(name: string): string | undefined;
33
+ }
34
+ /** Default source: `process.env` (Bun loads `.env` into it automatically). */
35
+ declare const envSource: SecretSource;
36
+ interface SecretOptions {
37
+ /** Fallback when the source has no value. Secrets without a default are required. */
38
+ default?: string;
39
+ }
40
+ /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
41
+ type SecretValidator<T> = (value: T) => void | boolean | string;
42
+ declare class SecretRef<T = string> {
43
+ readonly name: string;
44
+ readonly options: SecretOptions;
45
+ private transformFn?;
46
+ private validators;
47
+ constructor(name: string, options?: SecretOptions);
48
+ /** True when a default was declared (i.e. the secret is optional). */
49
+ get hasDefault(): boolean;
50
+ /** Fallback used when the source has no value. Makes the secret optional. */
51
+ default(value: string): this;
52
+ /**
53
+ * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
54
+ * Runs before validators; a throwing transform fails resolution.
55
+ */
56
+ transform<U>(fn: (raw: string) => U): SecretRef<U>;
57
+ /** Run a custom check on the (transformed) value at every resolution. */
58
+ validate(fn: SecretValidator<T>): this;
59
+ /** Shorthand validator: value must parse as a URL. String refs only. */
60
+ url(this: SecretRef<string>): SecretRef<string>;
61
+ private resolveRaw;
62
+ private coerce;
63
+ /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
64
+ value(source?: SecretSource): T | undefined;
65
+ /** Resolved value, or throws naming the missing/invalid secret. */
66
+ require(source?: SecretSource): T;
67
+ /** True when a value would resolve (override, source, or default). */
68
+ isSet(source?: SecretSource): boolean;
69
+ }
38
70
  /**
39
- * The deps of the app that is running the current listener or workflow step.
40
- * Actions, tools and socket handlers read `ctx.deps` instead.
41
- *
42
- * A workflow step is a plain function the Workflow SDK calls by name, so it
43
- * cannot close over the app that started it. Brick runs every listener and every
44
- * step inside its app, and this returns that app's `brick({ deps })`.
45
- *
46
- * @param ports - Optional: the ports to type the result by (the same object a
47
- * service passes as its `deps` option). Otherwise pass the type: `useDeps<{ carrier: Carrier }>()`.
48
- * @returns The app's deps.
49
- * @throws When called outside a listener or workflow step of a Brick app.
50
- * @example
51
- * export const ordersDeps = { carrier: port<Carrier>() };
71
+ * Declare a secret. Calling it again for the name returns the same ref. From
72
+ * the same line (a module evaluated again) it starts the declaration over, so
73
+ * its builder calls replace the earlier ones instead of adding to them.
74
+ */
75
+ declare function defineSecret(name: string, options?: SecretOptions): SecretRef<string>;
76
+ /**
77
+ * Validate every registered secret at boot. Throws a single error listing
78
+ * all missing required secrets. Returns the resolved values.
79
+ */
80
+ declare function resolveSecrets(opts?: {
81
+ source?: SecretSource;
82
+ }): Record<string, unknown>;
83
+ /** Metadata for introspection (values never exposed — future dashboard use). */
84
+ declare function listSecrets(opts?: {
85
+ source?: SecretSource;
86
+ }): Array<{
87
+ name: string;
88
+ hasDefault: boolean;
89
+ isSet: boolean;
90
+ }>;
91
+ /** Test/session override for one secret (`undefined` clears the override). */
92
+ declare function overrideSecret(name: string, value: string | undefined): void;
93
+ /** Clear registry and overrides. Test-only. */
94
+ declare function resetSecrets(): void;
95
+ /** What `put` returns: the id to keep, and what was stored. */
96
+ interface StoredFile {
97
+ id: string;
98
+ size: number;
99
+ contentType: string;
100
+ }
101
+ /** File methods inside one tenant. Ids are the ones `put` returned; nothing takes a key, a path or a URL. */
102
+ interface ScopedFiles {
103
+ /** Stores the file under a new id Brick generates. `contentType` defaults to the file's own type. */
104
+ put(file: Blob, options?: {
105
+ contentType?: string;
106
+ }): Promise<StoredFile>;
107
+ /** A short-lived signed link that downloads the file as an attachment. `expiresInMs` defaults to 5 minutes. */
108
+ url(id: string, options?: {
109
+ expiresInMs?: number;
110
+ download?: string;
111
+ }): Promise<string>;
112
+ /** The file, or `undefined` when this tenant has none with that id. */
113
+ get(id: string): Promise<Blob | undefined>;
114
+ /** Removes the file; does nothing when this tenant has none with that id. */
115
+ delete(id: string): Promise<void>;
116
+ }
117
+ /**
118
+ * The handle of a file storage. In a call, `ctx.deps.<name>` is scoped to the
119
+ * caller's tenant; outside one, name the tenant with `in(tenant)`.
120
+ */
121
+ interface FileStorage extends ScopedFiles {
122
+ readonly kind: "file";
123
+ /** The files of one tenant, for server code outside a request: a listener, a schedule, a webhook. */
124
+ in(tenant: string): ScopedFiles;
125
+ }
126
+ /** A file storage as a call sees it in `ctx.deps`: the caller's tenant only, with no `in`. */
127
+ interface CallFiles extends ScopedFiles {
128
+ readonly kind: "file";
129
+ }
130
+ /** Deps as a call sees them: each file storage scoped to the caller's tenant. */
131
+ type CallDeps<T> = { [K in keyof T]: CallDep<T[K]>; };
132
+ type CallDep<V> = V extends FileStorage ? CallFiles : V;
133
+ type RawDeps<T> = { [K in keyof T]: RawDep<T[K]>; };
134
+ type RawDep<V> = V extends CallFiles ? FileStorage : V;
135
+ /** A driver for file storage, such as `s3()`. It sees full keys; the handle builds them. */
136
+ interface FileDriver {
137
+ readonly kind: "file";
138
+ /** Put in front of every key. */
139
+ readonly prefix: string;
140
+ /** The directory files are written under, in local mode. */
141
+ readonly local?: string;
142
+ /** Throws when the driver cannot work as configured; `brick()` calls it at startup. */
143
+ check?(): void;
144
+ write(key: string, file: Blob, contentType: string): Promise<void>;
145
+ read(key: string): Promise<Blob | undefined>;
146
+ remove(key: string): Promise<void>;
147
+ /** A signed GET for the key, served with `contentDisposition`. */
148
+ sign(key: string, expiresInMs: number, contentDisposition: string): Promise<string>;
149
+ }
150
+ type Setting = string | SecretRef<string>;
151
+ /** Options of the `s3()` storage driver. Settings left out come from Bun's `S3_*` and `AWS_*` environment variables. */
152
+ interface S3StorageOptions {
153
+ bucket?: string;
154
+ /** Put in front of every key, such as `"files/"`. */
155
+ prefix?: string;
156
+ /** A directory: store files there instead of S3, for local development and tests. */
157
+ local?: string;
158
+ accessKeyId?: Setting;
159
+ secretAccessKey?: Setting;
160
+ sessionToken?: Setting;
161
+ region?: Setting;
162
+ /** An S3-compatible endpoint, such as R2 or MinIO. */
163
+ endpoint?: Setting;
164
+ }
165
+ /**
166
+ * File storage in S3 or an S3-compatible store (R2, MinIO), through Bun's
167
+ * built-in client. Nothing connects or reads credentials until the first call.
168
+ * With `local`, files are written under that directory instead.
52
169
  *
53
- * async function bookCarrier(orderId: string) {
54
- * "use step";
55
- * return useDeps(ordersDeps).carrier.book(orderId);
56
- * }
170
+ * @param options - `bucket`, `prefix`, `local`, and the credentials and
171
+ * `endpoint` Bun's client takes, each a string or a `SecretRef`; left out,
172
+ * Bun's `S3_*` and `AWS_*` environment variables apply.
57
173
  */
58
- declare function useDeps<const P extends Ports>(ports: P): DepsOf<P>;
59
- declare function useDeps<T = Record<string, unknown>>(): T;
174
+ declare function s3(options?: S3StorageOptions): FileDriver;
60
175
  /** A service's declared events: payload schema by event name. */
61
176
  type EventCatalog = Record<string, TSchema>;
62
177
  /**
@@ -431,6 +546,8 @@ interface HookBase<C> {
431
546
  ctx: C;
432
547
  /** The write's open transaction: write other tables through it. */
433
548
  tx: any;
549
+ /** The resource that is written. */
550
+ resource: Resource<any, any, any>;
434
551
  }
435
552
  /** The arguments each host CRUD hook receives, by hook name. */
436
553
  interface PluginHookArgs<C = ActionContext> {
@@ -615,258 +732,718 @@ type PluginTableBuilders = typeof sqliteBuilders & {
615
732
  /** The host database's engine. */
616
733
  readonly engine: "sqlite" | "postgres";
617
734
  };
735
+ type Secrets = Record<string, SecretRef<any>>;
736
+ type OptionsOf<O> = O extends TSchema ? Static<O> : {};
618
737
  /**
619
- * Type-safe secrets & environment variables.
620
- *
621
- * Declare each secret once at module scope instead of scattering untyped
622
- * `process.env.FOO` reads:
623
- *
624
- * const port = defineSecret("PORT").default("3333").transform(Number).require();
625
- * const baseUrl = defineSecret("BASE_URL").url().require();
626
- * const key = defineSecret("STRIPE_KEY").validate((v) =>
627
- * v.startsWith("sk_") || "must start with sk_"
628
- * ).require();
629
- *
630
- * Values resolve from the environment (Bun populates `process.env` from
631
- * `.env` locally; in prod the same env source applies — a future
632
- * `SecretSource` such as AWS can slot in without touching call sites).
633
- *
634
- * Resolution order per secret: test/session override → source (`process.env`
635
- * by default) → declared `default`. `resolveSecrets()` validates every
636
- * registered secret at boot and throws listing all missing required ones.
738
+ * The context of a plugin's actions, endpoints and hooks: the host's request
739
+ * context, loosely typed, with `deps` set to the plugin's own declared deps.
637
740
  */
638
- interface SecretSource {
639
- get(name: string): string | undefined;
741
+ type PluginContext<P extends Record<string, unknown> = {}> = BaseContext<any> & PluginServiceContext<P>;
742
+ /** A plugin's view of its host's service context: loose, except `deps`, which is the plugin's. */
743
+ type PluginServiceContext<P extends Record<string, unknown> = {}> = {
744
+ [key: string]: any;
745
+ /** The values passed for the plugin's `deps` when it was installed; a file storage scoped to the caller's tenant. */
746
+ deps: CallDeps<P>;
747
+ };
748
+ /** What every setup callback receives. */
749
+ interface PluginSetupContext<O, S, T, E extends EventCatalog, P extends Record<string, unknown> = {}> {
750
+ /** The validated options, defaults filled in. */
751
+ options: O;
752
+ /** The declared secrets, to read when they are needed. */
753
+ secrets: S;
754
+ /** The tables this plugin owns, by the keys `tables` returned. */
755
+ tables: T;
756
+ /** The plugin's events, as `emitEvent` and `defineListener` take them. */
757
+ events: EventRefs<E>;
758
+ /** The values passed for `deps` when the plugin was installed. */
759
+ deps: P;
760
+ /** The host service. Actions registered on it read the plugin's deps as `ctx.deps`. */
761
+ service: Service<any, PluginServiceContext<P>>;
762
+ routes: PluginRouteRegistrar<PluginContext<P>>;
763
+ /** The host's CRUD writes: on a service, those of all its resources. */
764
+ hooks: PluginHooks<PluginContext<P>>;
640
765
  }
641
- /** Default source: `process.env` (Bun loads `.env` into it automatically). */
642
- declare const envSource: SecretSource;
643
- interface SecretOptions {
644
- /** Fallback when the source has no value. Secrets without a default are required. */
645
- default?: string;
766
+ /** The lifecycle context of `on("start")` and `on("stop")`. */
767
+ interface PluginLifecycleContext<O, S, P extends Record<string, unknown> = {}> {
768
+ options: O;
769
+ secrets: S;
770
+ deps: P;
646
771
  }
647
- /** A validator: return `true`/`void` when ok, `false`/reason/`throw` when not. */
648
- type SecretValidator<T> = (value: T) => void | boolean | string;
649
- declare class SecretRef<T = string> {
650
- readonly name: string;
651
- readonly options: SecretOptions;
652
- private transformFn?;
653
- private validators;
654
- constructor(name: string, options?: SecretOptions);
655
- /** True when a default was declared (i.e. the secret is optional). */
656
- get hasDefault(): boolean;
657
- /** Fallback used when the source has no value. Makes the secret optional. */
658
- default(value: string): this;
772
+ /** What `app` receives: the app-wide part of a plugin. */
773
+ interface PluginAppContext<O, S, P extends Record<string, unknown> = {}> {
774
+ options: O;
775
+ secrets: S;
776
+ /** The values passed for `deps` when the plugin was installed. */
777
+ deps: P;
659
778
  /**
660
- * Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
661
- * Runs before validators; a throwing transform fails resolution.
779
+ * Run when the app starts (`app.start()`, which `listen`, `brick dev` and
780
+ * `brick start` call) in install order, and when it stops in reverse order.
662
781
  */
663
- transform<U>(fn: (raw: string) => U): SecretRef<U>;
664
- /** Run a custom check on the (transformed) value at every resolution. */
665
- validate(fn: SecretValidator<T>): this;
666
- /** Shorthand validator: value must parse as a URL. String refs only. */
667
- url(this: SecretRef<string>): SecretRef<string>;
668
- private resolveRaw;
669
- private coerce;
670
- /** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
671
- value(source?: SecretSource): T | undefined;
672
- /** Resolved value, or throws naming the missing/invalid secret. */
673
- require(source?: SecretSource): T;
674
- /** True when a value would resolve (override, source, or default). */
675
- isSet(source?: SecretSource): boolean;
782
+ on(event: "start" | "stop", handler: (context: PluginLifecycleContext<O, S, P>) => void | Promise<void>): void;
783
+ /**
784
+ * Run before every request is routed. Return a `Response` (or any value) to
785
+ * answer it here; return nothing to let it through.
786
+ */
787
+ middleware(handler: (context: {
788
+ request: Request;
789
+ set: {
790
+ status?: number | string;
791
+ headers: Record<string, string>;
792
+ };
793
+ }) => unknown): void;
794
+ /**
795
+ * Event listeners to add to the app's `events`. `useDeps()` in their `run`,
796
+ * and in the steps of their `workflow`, returns the plugin's deps.
797
+ */
798
+ listeners(...listeners: EventListener[]): void;
676
799
  }
677
- /**
678
- * Declare a secret. Calling it again for the name returns the same ref. From
679
- * the same line (a module evaluated again) it starts the declaration over, so
680
- * its builder calls replace the earlier ones instead of adding to them.
681
- */
682
- declare function defineSecret(name: string, options?: SecretOptions): SecretRef<string>;
683
- /**
684
- * Validate every registered secret at boot. Throws a single error listing
685
- * all missing required secrets. Returns the resolved values.
686
- */
687
- declare function resolveSecrets(opts?: {
688
- source?: SecretSource;
689
- }): Record<string, unknown>;
690
- /** Metadata for introspection (values never exposed — future dashboard use). */
691
- declare function listSecrets(opts?: {
692
- source?: SecretSource;
693
- }): Array<{
800
+ interface PluginManifest<O extends TSchema | undefined = undefined, S extends Secrets = {}, T extends Record<string, Table> = {}, E extends EventCatalog = {}, RA extends object = {}, SA = unknown, P extends Record<string, unknown> = {}> {
801
+ /** The npm package name, scoped: `@acme/brick-comments`. */
694
802
  name: string;
695
- hasDefault: boolean;
696
- isSet: boolean;
803
+ description?: string;
804
+ /** The Brick versions it supports, as a semver range: `^0.12.0`. */
805
+ brick?: string;
806
+ /** Plugins that must be installed on the same host first, by name. */
807
+ requires?: readonly string[];
808
+ /** A TypeBox schema for the options; defaults fill what the user leaves out. */
809
+ options?: O;
810
+ /** Secrets it reads, from `defineSecret`. */
811
+ secrets?: S;
812
+ /**
813
+ * What it needs from the app, by name, each with a placeholder of its type:
814
+ * `{ mailer: {} as Mailer }`. Only the names and types are used. The user passes
815
+ * the values when installing: `notify(options, { deps: { mailer } })`. Setup
816
+ * parts read them as `deps`, the plugin's actions as `ctx.deps`.
817
+ */
818
+ deps?: P;
819
+ /**
820
+ * Tables it owns. They are created in the host service's database for its
821
+ * engine, named `<host>_<table>` (or with the install's `prefix`), and join
822
+ * schema sync and migrations through `database.tables`.
823
+ */
824
+ tables?: (builders: PluginTableBuilders) => T;
825
+ /** Events it emits; they join the host catalog as `<plugin>.<event>`. */
826
+ events?: E;
827
+ /** Installed with `resource.use()`; returns what the resource gains. */
828
+ resource?: (context: PluginSetupContext<OptionsOf<O>, S, T, E, P> & {
829
+ resource: Resource<any, PluginContext<P>, any>;
830
+ }) => RA & (RA extends PromiseLike<unknown> ? never : unknown);
831
+ /** Installed with `service.use()`; returns what `use` hands back. */
832
+ service?: (context: PluginSetupContext<OptionsOf<O>, S, T, E, P>) => SA & (SA extends PromiseLike<unknown> ? never : unknown);
833
+ /**
834
+ * The app-wide part: lifecycle, middleware and listeners. Runs once per
835
+ * plugin instance when `brick()` creates the app, whether the plugin was
836
+ * installed with `brick({ plugins })`, `service.use()` or `resource.use()`.
837
+ */
838
+ app?: (context: PluginAppContext<OptionsOf<O>, S, P>) => void;
839
+ /**
840
+ * A dashboard extension module (`defineDashboard`), relative to the file
841
+ * that calls `definePlugin`. `brick dev` merges it with the app's own.
842
+ */
843
+ dashboard?: string;
844
+ }
845
+ /** Where the plugin is installed, besides its options. */
846
+ interface PluginInstallOptions {
847
+ /** Table name prefix instead of `<host>_`, such as `"blog_"`; `""` for none. */
848
+ prefix?: string;
849
+ }
850
+ /** What the plugin's capabilities are, read from its manifest. */
851
+ interface PluginInfo {
852
+ readonly name: string;
853
+ readonly description?: string;
854
+ readonly brick?: string;
855
+ readonly requires: readonly string[];
856
+ readonly options?: TSchema;
857
+ readonly secrets: readonly string[];
858
+ /** The names of the deps it declares, passed when installing. */
859
+ readonly deps: readonly string[];
860
+ readonly capabilities: readonly ("tables" | "events" | "resource" | "service" | "app" | "dashboard")[];
861
+ }
862
+ /** A plugin ready to install: `resource.use(p)`, `service.use(p)` or `brick({ plugins: [p] })`. */
863
+ type PluginInstance<RA extends object = {}, SA = unknown> = ResourcePlugin<any, any, RA> & ServicePlugin<any, SA> & {
864
+ readonly info: PluginInfo;
865
+ };
866
+ /** `definePlugin`'s result: call it with options to get an instance. */
867
+ type PluginFactory<O extends TSchema | undefined, RA extends object, SA, P extends Record<string, unknown> = {}> = ((...args: {} extends P ? [options?: Partial<OptionsOf<O>>, install?: PluginInstallOptions] : [options: Partial<OptionsOf<O>> | undefined, install: PluginInstallOptions & {
868
+ deps: P;
869
+ }]) => PluginInstance<RA, SA>) & {
870
+ readonly info: PluginInfo;
871
+ };
872
+ /**
873
+ * Define a plugin: a manifest Brick checks, plus the capabilities the plugin
874
+ * brings. Install its instances with `resource.use()`, `service.use()` or
875
+ * `brick({ plugins })`; scope comes from where it is installed.
876
+ *
877
+ * @param manifest - `name`, `brick` (semver range), `requires`, `options`
878
+ * (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`
879
+ * parts, and a `dashboard` extension.
880
+ * @returns A factory: `comments({ maxLength: 500 })` validates the options and
881
+ * the Brick version and returns an instance to install.
882
+ * @throws From the factory, when the running Brick is outside `brick` or an
883
+ * option is invalid; when installed, when a required plugin is missing or the
884
+ * host does not suit the plugin.
885
+ * @example
886
+ * export const audit = definePlugin({
887
+ * name: "@acme/brick-audit",
888
+ * brick: "^0.12.0",
889
+ * requires: ["@brickkit/crud"],
890
+ * options: t.Object({ table: t.String({ default: "audit" }) }),
891
+ * tables: ({ table, text, timestamp }) => ({
892
+ * log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
893
+ * }),
894
+ * resource: ({ tables, hooks }) => {
895
+ * hooks.afterCreate(({ row, tx }) =>
896
+ * tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
897
+ * return {};
898
+ * },
899
+ * });
900
+ *
901
+ * page.use(audit());
902
+ */
903
+ declare function definePlugin<O extends TSchema | undefined = undefined, S extends Secrets = {}, T extends Record<string, Table> = {}, const E extends EventCatalog = {}, RA extends object = {}, SA = unknown, P extends Record<string, unknown> = {}>(manifest: PluginManifest<O, S, T, E, RA, SA, P>): PluginFactory<O, RA, SA, P>;
904
+ declare function sqliteAudit(name: string): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
905
+ name: string;
906
+ schema: undefined;
907
+ columns: {
908
+ seq: import("drizzle-orm/sqlite-core").SQLiteColumn<{
909
+ name: "seq";
910
+ tableName: string;
911
+ dataType: "number";
912
+ columnType: "SQLiteInteger";
913
+ data: number;
914
+ driverParam: number;
915
+ notNull: true;
916
+ hasDefault: true;
917
+ isPrimaryKey: true;
918
+ isAutoincrement: false;
919
+ hasRuntimeDefault: false;
920
+ enumValues: undefined;
921
+ baseColumn: never;
922
+ identity: undefined;
923
+ generated: undefined;
924
+ }, {}, {}>;
925
+ id: import("drizzle-orm/sqlite-core").SQLiteColumn<{
926
+ name: "id";
927
+ tableName: string;
928
+ dataType: "string";
929
+ columnType: "SQLiteText";
930
+ data: string;
931
+ driverParam: string;
932
+ notNull: true;
933
+ hasDefault: false;
934
+ isPrimaryKey: false;
935
+ isAutoincrement: false;
936
+ hasRuntimeDefault: false;
937
+ enumValues: [string, ...string[]];
938
+ baseColumn: never;
939
+ identity: undefined;
940
+ generated: undefined;
941
+ }, {}, {
942
+ length: number | undefined;
943
+ }>;
944
+ at: import("drizzle-orm/sqlite-core").SQLiteColumn<{
945
+ name: "at";
946
+ tableName: string;
947
+ dataType: "date";
948
+ columnType: "SQLiteTimestamp";
949
+ data: Date;
950
+ driverParam: number;
951
+ notNull: true;
952
+ hasDefault: false;
953
+ isPrimaryKey: false;
954
+ isAutoincrement: false;
955
+ hasRuntimeDefault: false;
956
+ enumValues: undefined;
957
+ baseColumn: never;
958
+ identity: undefined;
959
+ generated: undefined;
960
+ }, {}, {}>;
961
+ service: import("drizzle-orm/sqlite-core").SQLiteColumn<{
962
+ name: "service";
963
+ tableName: string;
964
+ dataType: "string";
965
+ columnType: "SQLiteText";
966
+ data: string;
967
+ driverParam: string;
968
+ notNull: true;
969
+ hasDefault: false;
970
+ isPrimaryKey: false;
971
+ isAutoincrement: false;
972
+ hasRuntimeDefault: false;
973
+ enumValues: [string, ...string[]];
974
+ baseColumn: never;
975
+ identity: undefined;
976
+ generated: undefined;
977
+ }, {}, {
978
+ length: number | undefined;
979
+ }>;
980
+ action: import("drizzle-orm/sqlite-core").SQLiteColumn<{
981
+ name: "action";
982
+ tableName: string;
983
+ dataType: "string";
984
+ columnType: "SQLiteText";
985
+ data: string;
986
+ driverParam: string;
987
+ notNull: true;
988
+ hasDefault: false;
989
+ isPrimaryKey: false;
990
+ isAutoincrement: false;
991
+ hasRuntimeDefault: false;
992
+ enumValues: [string, ...string[]];
993
+ baseColumn: never;
994
+ identity: undefined;
995
+ generated: undefined;
996
+ }, {}, {
997
+ length: number | undefined;
998
+ }>;
999
+ resource: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1000
+ name: "resource";
1001
+ tableName: string;
1002
+ dataType: "string";
1003
+ columnType: "SQLiteText";
1004
+ data: string;
1005
+ driverParam: string;
1006
+ notNull: false;
1007
+ hasDefault: false;
1008
+ isPrimaryKey: false;
1009
+ isAutoincrement: false;
1010
+ hasRuntimeDefault: false;
1011
+ enumValues: [string, ...string[]];
1012
+ baseColumn: never;
1013
+ identity: undefined;
1014
+ generated: undefined;
1015
+ }, {}, {
1016
+ length: number | undefined;
1017
+ }>;
1018
+ recordId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1019
+ name: "record_id";
1020
+ tableName: string;
1021
+ dataType: "string";
1022
+ columnType: "SQLiteText";
1023
+ data: string;
1024
+ driverParam: string;
1025
+ notNull: false;
1026
+ hasDefault: false;
1027
+ isPrimaryKey: false;
1028
+ isAutoincrement: false;
1029
+ hasRuntimeDefault: false;
1030
+ enumValues: [string, ...string[]];
1031
+ baseColumn: never;
1032
+ identity: undefined;
1033
+ generated: undefined;
1034
+ }, {}, {
1035
+ length: number | undefined;
1036
+ }>;
1037
+ actorId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1038
+ name: "actor_id";
1039
+ tableName: string;
1040
+ dataType: "string";
1041
+ columnType: "SQLiteText";
1042
+ data: string;
1043
+ driverParam: string;
1044
+ notNull: false;
1045
+ hasDefault: false;
1046
+ isPrimaryKey: false;
1047
+ isAutoincrement: false;
1048
+ hasRuntimeDefault: false;
1049
+ enumValues: [string, ...string[]];
1050
+ baseColumn: never;
1051
+ identity: undefined;
1052
+ generated: undefined;
1053
+ }, {}, {
1054
+ length: number | undefined;
1055
+ }>;
1056
+ actorLabel: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1057
+ name: "actor_label";
1058
+ tableName: string;
1059
+ dataType: "string";
1060
+ columnType: "SQLiteText";
1061
+ data: string;
1062
+ driverParam: string;
1063
+ notNull: false;
1064
+ hasDefault: false;
1065
+ isPrimaryKey: false;
1066
+ isAutoincrement: false;
1067
+ hasRuntimeDefault: false;
1068
+ enumValues: [string, ...string[]];
1069
+ baseColumn: never;
1070
+ identity: undefined;
1071
+ generated: undefined;
1072
+ }, {}, {
1073
+ length: number | undefined;
1074
+ }>;
1075
+ tenant: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1076
+ name: "tenant";
1077
+ tableName: string;
1078
+ dataType: "string";
1079
+ columnType: "SQLiteText";
1080
+ data: string;
1081
+ driverParam: string;
1082
+ notNull: false;
1083
+ hasDefault: false;
1084
+ isPrimaryKey: false;
1085
+ isAutoincrement: false;
1086
+ hasRuntimeDefault: false;
1087
+ enumValues: [string, ...string[]];
1088
+ baseColumn: never;
1089
+ identity: undefined;
1090
+ generated: undefined;
1091
+ }, {}, {
1092
+ length: number | undefined;
1093
+ }>;
1094
+ traceId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1095
+ name: "trace_id";
1096
+ tableName: string;
1097
+ dataType: "string";
1098
+ columnType: "SQLiteText";
1099
+ data: string;
1100
+ driverParam: string;
1101
+ notNull: false;
1102
+ hasDefault: false;
1103
+ isPrimaryKey: false;
1104
+ isAutoincrement: false;
1105
+ hasRuntimeDefault: false;
1106
+ enumValues: [string, ...string[]];
1107
+ baseColumn: never;
1108
+ identity: undefined;
1109
+ generated: undefined;
1110
+ }, {}, {
1111
+ length: number | undefined;
1112
+ }>;
1113
+ requestId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1114
+ name: "request_id";
1115
+ tableName: string;
1116
+ dataType: "string";
1117
+ columnType: "SQLiteText";
1118
+ data: string;
1119
+ driverParam: string;
1120
+ notNull: false;
1121
+ hasDefault: false;
1122
+ isPrimaryKey: false;
1123
+ isAutoincrement: false;
1124
+ hasRuntimeDefault: false;
1125
+ enumValues: [string, ...string[]];
1126
+ baseColumn: never;
1127
+ identity: undefined;
1128
+ generated: undefined;
1129
+ }, {}, {
1130
+ length: number | undefined;
1131
+ }>;
1132
+ meta: import("drizzle-orm/sqlite-core").SQLiteColumn<{
1133
+ name: "meta";
1134
+ tableName: string;
1135
+ dataType: "json";
1136
+ columnType: "SQLiteTextJson";
1137
+ data: unknown;
1138
+ driverParam: string;
1139
+ notNull: false;
1140
+ hasDefault: false;
1141
+ isPrimaryKey: false;
1142
+ isAutoincrement: false;
1143
+ hasRuntimeDefault: false;
1144
+ enumValues: undefined;
1145
+ baseColumn: never;
1146
+ identity: undefined;
1147
+ generated: undefined;
1148
+ }, {}, {}>;
1149
+ };
1150
+ dialect: 'sqlite';
1151
+ }>;
1152
+ declare function postgresAudit(name: string): import("drizzle-orm/pg-core").PgTableWithColumns<{
1153
+ name: string;
1154
+ schema: undefined;
1155
+ columns: {
1156
+ seq: import("drizzle-orm/pg-core").PgColumn<{
1157
+ name: "seq";
1158
+ tableName: string;
1159
+ dataType: "number";
1160
+ columnType: "PgBigSerial53";
1161
+ data: number;
1162
+ driverParam: number;
1163
+ notNull: true;
1164
+ hasDefault: true;
1165
+ isPrimaryKey: true;
1166
+ isAutoincrement: false;
1167
+ hasRuntimeDefault: false;
1168
+ enumValues: undefined;
1169
+ baseColumn: never;
1170
+ identity: undefined;
1171
+ generated: undefined;
1172
+ }, {}, {}>;
1173
+ id: import("drizzle-orm/pg-core").PgColumn<{
1174
+ name: "id";
1175
+ tableName: string;
1176
+ dataType: "string";
1177
+ columnType: "PgText";
1178
+ data: string;
1179
+ driverParam: string;
1180
+ notNull: true;
1181
+ hasDefault: false;
1182
+ isPrimaryKey: false;
1183
+ isAutoincrement: false;
1184
+ hasRuntimeDefault: false;
1185
+ enumValues: [string, ...string[]];
1186
+ baseColumn: never;
1187
+ identity: undefined;
1188
+ generated: undefined;
1189
+ }, {}, {}>;
1190
+ at: import("drizzle-orm/pg-core").PgColumn<{
1191
+ name: "at";
1192
+ tableName: string;
1193
+ dataType: "date";
1194
+ columnType: "PgTimestamp";
1195
+ data: Date;
1196
+ driverParam: string;
1197
+ notNull: true;
1198
+ hasDefault: false;
1199
+ isPrimaryKey: false;
1200
+ isAutoincrement: false;
1201
+ hasRuntimeDefault: false;
1202
+ enumValues: undefined;
1203
+ baseColumn: never;
1204
+ identity: undefined;
1205
+ generated: undefined;
1206
+ }, {}, {}>;
1207
+ service: import("drizzle-orm/pg-core").PgColumn<{
1208
+ name: "service";
1209
+ tableName: string;
1210
+ dataType: "string";
1211
+ columnType: "PgText";
1212
+ data: string;
1213
+ driverParam: string;
1214
+ notNull: true;
1215
+ hasDefault: false;
1216
+ isPrimaryKey: false;
1217
+ isAutoincrement: false;
1218
+ hasRuntimeDefault: false;
1219
+ enumValues: [string, ...string[]];
1220
+ baseColumn: never;
1221
+ identity: undefined;
1222
+ generated: undefined;
1223
+ }, {}, {}>;
1224
+ action: import("drizzle-orm/pg-core").PgColumn<{
1225
+ name: "action";
1226
+ tableName: string;
1227
+ dataType: "string";
1228
+ columnType: "PgText";
1229
+ data: string;
1230
+ driverParam: string;
1231
+ notNull: true;
1232
+ hasDefault: false;
1233
+ isPrimaryKey: false;
1234
+ isAutoincrement: false;
1235
+ hasRuntimeDefault: false;
1236
+ enumValues: [string, ...string[]];
1237
+ baseColumn: never;
1238
+ identity: undefined;
1239
+ generated: undefined;
1240
+ }, {}, {}>;
1241
+ resource: import("drizzle-orm/pg-core").PgColumn<{
1242
+ name: "resource";
1243
+ tableName: string;
1244
+ dataType: "string";
1245
+ columnType: "PgText";
1246
+ data: string;
1247
+ driverParam: string;
1248
+ notNull: false;
1249
+ hasDefault: false;
1250
+ isPrimaryKey: false;
1251
+ isAutoincrement: false;
1252
+ hasRuntimeDefault: false;
1253
+ enumValues: [string, ...string[]];
1254
+ baseColumn: never;
1255
+ identity: undefined;
1256
+ generated: undefined;
1257
+ }, {}, {}>;
1258
+ recordId: import("drizzle-orm/pg-core").PgColumn<{
1259
+ name: "record_id";
1260
+ tableName: string;
1261
+ dataType: "string";
1262
+ columnType: "PgText";
1263
+ data: string;
1264
+ driverParam: string;
1265
+ notNull: false;
1266
+ hasDefault: false;
1267
+ isPrimaryKey: false;
1268
+ isAutoincrement: false;
1269
+ hasRuntimeDefault: false;
1270
+ enumValues: [string, ...string[]];
1271
+ baseColumn: never;
1272
+ identity: undefined;
1273
+ generated: undefined;
1274
+ }, {}, {}>;
1275
+ actorId: import("drizzle-orm/pg-core").PgColumn<{
1276
+ name: "actor_id";
1277
+ tableName: string;
1278
+ dataType: "string";
1279
+ columnType: "PgText";
1280
+ data: string;
1281
+ driverParam: string;
1282
+ notNull: false;
1283
+ hasDefault: false;
1284
+ isPrimaryKey: false;
1285
+ isAutoincrement: false;
1286
+ hasRuntimeDefault: false;
1287
+ enumValues: [string, ...string[]];
1288
+ baseColumn: never;
1289
+ identity: undefined;
1290
+ generated: undefined;
1291
+ }, {}, {}>;
1292
+ actorLabel: import("drizzle-orm/pg-core").PgColumn<{
1293
+ name: "actor_label";
1294
+ tableName: string;
1295
+ dataType: "string";
1296
+ columnType: "PgText";
1297
+ data: string;
1298
+ driverParam: string;
1299
+ notNull: false;
1300
+ hasDefault: false;
1301
+ isPrimaryKey: false;
1302
+ isAutoincrement: false;
1303
+ hasRuntimeDefault: false;
1304
+ enumValues: [string, ...string[]];
1305
+ baseColumn: never;
1306
+ identity: undefined;
1307
+ generated: undefined;
1308
+ }, {}, {}>;
1309
+ tenant: import("drizzle-orm/pg-core").PgColumn<{
1310
+ name: "tenant";
1311
+ tableName: string;
1312
+ dataType: "string";
1313
+ columnType: "PgText";
1314
+ data: string;
1315
+ driverParam: string;
1316
+ notNull: false;
1317
+ hasDefault: false;
1318
+ isPrimaryKey: false;
1319
+ isAutoincrement: false;
1320
+ hasRuntimeDefault: false;
1321
+ enumValues: [string, ...string[]];
1322
+ baseColumn: never;
1323
+ identity: undefined;
1324
+ generated: undefined;
1325
+ }, {}, {}>;
1326
+ traceId: import("drizzle-orm/pg-core").PgColumn<{
1327
+ name: "trace_id";
1328
+ tableName: string;
1329
+ dataType: "string";
1330
+ columnType: "PgText";
1331
+ data: string;
1332
+ driverParam: string;
1333
+ notNull: false;
1334
+ hasDefault: false;
1335
+ isPrimaryKey: false;
1336
+ isAutoincrement: false;
1337
+ hasRuntimeDefault: false;
1338
+ enumValues: [string, ...string[]];
1339
+ baseColumn: never;
1340
+ identity: undefined;
1341
+ generated: undefined;
1342
+ }, {}, {}>;
1343
+ requestId: import("drizzle-orm/pg-core").PgColumn<{
1344
+ name: "request_id";
1345
+ tableName: string;
1346
+ dataType: "string";
1347
+ columnType: "PgText";
1348
+ data: string;
1349
+ driverParam: string;
1350
+ notNull: false;
1351
+ hasDefault: false;
1352
+ isPrimaryKey: false;
1353
+ isAutoincrement: false;
1354
+ hasRuntimeDefault: false;
1355
+ enumValues: [string, ...string[]];
1356
+ baseColumn: never;
1357
+ identity: undefined;
1358
+ generated: undefined;
1359
+ }, {}, {}>;
1360
+ meta: import("drizzle-orm/pg-core").PgColumn<{
1361
+ name: "meta";
1362
+ tableName: string;
1363
+ dataType: "json";
1364
+ columnType: "PgJsonb";
1365
+ data: unknown;
1366
+ driverParam: unknown;
1367
+ notNull: false;
1368
+ hasDefault: false;
1369
+ isPrimaryKey: false;
1370
+ isAutoincrement: false;
1371
+ hasRuntimeDefault: false;
1372
+ enumValues: undefined;
1373
+ baseColumn: never;
1374
+ identity: undefined;
1375
+ generated: undefined;
1376
+ }, {}, {}>;
1377
+ };
1378
+ dialect: 'pg';
697
1379
  }>;
698
- /** Test/session override for one secret (`undefined` clears the override). */
699
- declare function overrideSecret(name: string, value: string | undefined): void;
700
- /** Clear registry and overrides. Test-only. */
701
- declare function resetSecrets(): void;
702
- type Secrets = Record<string, SecretRef<any>>;
703
- type OptionsOf<O> = O extends TSchema ? Static<O> : {};
1380
+ /** The audit table of a SQLite database. */
1381
+ type SQLiteAuditTable = ReturnType<typeof sqliteAudit>;
1382
+ /** The audit table of a Postgres database. */
1383
+ type PostgresAuditTable = ReturnType<typeof postgresAudit>;
1384
+ /** An audit table, made by `auditTable`. */
1385
+ type AuditTable = SQLiteAuditTable | PostgresAuditTable;
704
1386
  /**
705
- * The context of a plugin's actions, endpoints and hooks: the host's request
706
- * context, loosely typed, with `deps` set to the plugin's own declared deps.
1387
+ * The audit table: one row per change, saying who made it, what ran and on
1388
+ * which record. A service whose database holds it records every create, update
1389
+ * and delete, every command, and every other action that is not a `GET`.
1390
+ * Brick only ever inserts into it; the docs give the trigger that makes the
1391
+ * database refuse anything else.
1392
+ *
1393
+ * Brick does not create tables for you. Put this in the schema of the database
1394
+ * and your migration tool (such as drizzle-kit) creates it. The service must
1395
+ * declare an `identity` hook: that is where the actor comes from.
1396
+ *
1397
+ * @param engine - The database engine, `"sqlite"` or `"postgres"`.
1398
+ * @param options - `name` to call the table something other than `brick_audit`.
1399
+ * @returns A Drizzle table, which you can also read with a resource of your own.
1400
+ * @example
1401
+ * import { auditTable, defineDatabase } from "@brickkit/core";
1402
+ *
1403
+ * export const auditLog = auditTable("postgres");
1404
+ * export const database = defineDatabase({
1405
+ * engine: "postgres",
1406
+ * tables: { orders, auditLog },
1407
+ * });
707
1408
  */
708
- type PluginContext<P extends Ports = {}> = BaseContext<any> & PluginServiceContext<P>;
709
- /** A plugin's view of its host's service context: loose, except `deps`, which is the plugin's. */
710
- type PluginServiceContext<P extends Ports = {}> = {
711
- [key: string]: any;
712
- /** The values passed for the plugin's `deps` when it was installed. */
713
- deps: DepsOf<P>;
714
- };
715
- /** What every setup callback receives. */
716
- interface PluginSetupContext<O, S, T, E extends EventCatalog, P extends Ports = {}> {
717
- /** The validated options, defaults filled in. */
718
- options: O;
719
- /** The declared secrets, to read when they are needed. */
720
- secrets: S;
721
- /** The tables this plugin owns, by the keys `tables` returned. */
722
- tables: T;
723
- /** The plugin's events, as `emitEvent` and `defineListener` take them. */
724
- events: EventRefs<E>;
725
- /** The values passed for `deps` when the plugin was installed. */
726
- deps: DepsOf<P>;
727
- /** The host service. Actions registered on it read the plugin's deps as `ctx.deps`. */
728
- service: Service<any, PluginServiceContext<P>>;
729
- routes: PluginRouteRegistrar<PluginContext<P>>;
730
- /** The host's CRUD writes: on a service, those of all its resources. */
731
- hooks: PluginHooks<PluginContext<P>>;
732
- }
733
- /** The lifecycle context of `on("start")` and `on("stop")`. */
734
- interface PluginLifecycleContext<O, S, P extends Ports = {}> {
735
- options: O;
736
- secrets: S;
737
- deps: DepsOf<P>;
738
- }
739
- /** What `app` receives: the app-wide part of a plugin. */
740
- interface PluginAppContext<O, S, P extends Ports = {}> {
741
- options: O;
742
- secrets: S;
743
- /** The values passed for `deps` when the plugin was installed. */
744
- deps: DepsOf<P>;
745
- /**
746
- * Run when the app starts (`app.start()`, which `listen`, `brick dev` and
747
- * `brick start` call) in install order, and when it stops in reverse order.
748
- */
749
- on(event: "start" | "stop", handler: (context: PluginLifecycleContext<O, S, P>) => void | Promise<void>): void;
750
- /**
751
- * Run before every request is routed. Return a `Response` (or any value) to
752
- * answer it here; return nothing to let it through.
753
- */
754
- middleware(handler: (context: {
755
- request: Request;
756
- set: {
757
- status?: number | string;
758
- headers: Record<string, string>;
759
- };
760
- }) => unknown): void;
761
- /**
762
- * Event listeners to add to the app's `events`. `useDeps()` in their `run`,
763
- * and in the steps of their `workflow`, returns the plugin's deps.
764
- */
765
- listeners(...listeners: EventListener[]): void;
766
- }
767
- interface PluginManifest<O extends TSchema | undefined = undefined, S extends Secrets = {}, T extends Record<string, Table> = {}, E extends EventCatalog = {}, RA extends object = {}, SA = unknown, P extends Ports = {}> {
768
- /** The npm package name, scoped: `@acme/brick-comments`. */
769
- name: string;
770
- description?: string;
771
- /** The Brick versions it supports, as a semver range: `^0.12.0`. */
772
- brick?: string;
773
- /** Plugins that must be installed on the same host first, by name. */
774
- requires?: readonly string[];
775
- /** A TypeBox schema for the options; defaults fill what the user leaves out. */
776
- options?: O;
777
- /** Secrets it reads, from `defineSecret`. */
778
- secrets?: S;
779
- /**
780
- * What it needs from the app, declared with `port<T>()`. The user passes the
781
- * values when installing: `notify(options, { deps: { mailer } })`. Setup
782
- * parts read them as `deps`, the plugin's actions as `ctx.deps`.
783
- */
784
- deps?: P;
785
- /**
786
- * Tables it owns. They are created in the host service's database for its
787
- * engine, named `<host>_<table>` (or with the install's `prefix`), and join
788
- * schema sync and migrations through `database.tables`.
789
- */
790
- tables?: (builders: PluginTableBuilders) => T;
791
- /** Events it emits; they join the host catalog as `<plugin>.<event>`. */
792
- events?: E;
793
- /** Installed with `resource.use()`; returns what the resource gains. */
794
- resource?: (context: PluginSetupContext<OptionsOf<O>, S, T, E, P> & {
795
- resource: Resource<any, PluginContext<P>, any>;
796
- }) => RA & (RA extends PromiseLike<unknown> ? never : unknown);
797
- /** Installed with `service.use()`; returns what `use` hands back. */
798
- service?: (context: PluginSetupContext<OptionsOf<O>, S, T, E, P>) => SA & (SA extends PromiseLike<unknown> ? never : unknown);
799
- /**
800
- * The app-wide part: lifecycle, middleware and listeners. Runs once per
801
- * plugin instance when `brick()` creates the app, whether the plugin was
802
- * installed with `brick({ plugins })`, `service.use()` or `resource.use()`.
803
- */
804
- app?: (context: PluginAppContext<OptionsOf<O>, S, P>) => void;
805
- /**
806
- * A dashboard extension module (`defineDashboard`), relative to the file
807
- * that calls `definePlugin`. `brick dev` merges it with the app's own.
808
- */
809
- dashboard?: string;
810
- }
811
- /** Where the plugin is installed, besides its options. */
812
- interface PluginInstallOptions {
813
- /** Table name prefix instead of `<host>_`, such as `"blog_"`; `""` for none. */
814
- prefix?: string;
815
- }
816
- /** What the plugin's capabilities are, read from its manifest. */
817
- interface PluginInfo {
818
- readonly name: string;
819
- readonly description?: string;
820
- readonly brick?: string;
821
- readonly requires: readonly string[];
822
- readonly options?: TSchema;
823
- readonly secrets: readonly string[];
824
- /** The names of the deps it declares, passed when installing. */
825
- readonly deps: readonly string[];
826
- readonly capabilities: readonly ("tables" | "events" | "resource" | "service" | "app" | "dashboard")[];
827
- }
828
- /** A plugin ready to install: `resource.use(p)`, `service.use(p)` or `brick({ plugins: [p] })`. */
829
- type PluginInstance<RA extends object = {}, SA = unknown> = ResourcePlugin<any, any, RA> & ServicePlugin<any, SA> & {
830
- readonly info: PluginInfo;
831
- };
832
- /** `definePlugin`'s result: call it with options to get an instance. */
833
- type PluginFactory<O extends TSchema | undefined, RA extends object, SA, P extends Ports = {}> = ((...args: {} extends P ? [options?: Partial<OptionsOf<O>>, install?: PluginInstallOptions] : [options: Partial<OptionsOf<O>> | undefined, install: PluginInstallOptions & {
834
- deps: DepsOf<P>;
835
- }]) => PluginInstance<RA, SA>) & {
836
- readonly info: PluginInfo;
837
- };
1409
+ declare function auditTable(engine: "sqlite", options?: {
1410
+ name?: string;
1411
+ }): SQLiteAuditTable;
1412
+ declare function auditTable(engine: "postgres", options?: {
1413
+ name?: string;
1414
+ }): PostgresAuditTable;
1415
+ /** Whether a value is an audit table made by `auditTable`. */
1416
+ declare function isAuditTable(value: unknown): value is AuditTable;
838
1417
  /**
839
- * Define a plugin: a manifest Brick checks, plus the capabilities the plugin
840
- * brings. Install its instances with `resource.use()`, `service.use()` or
841
- * `brick({ plugins })`; scope comes from where it is installed.
1418
+ * Record a change of your own from an action: for what Brick cannot see, or to
1419
+ * add `meta`. By default the row is inserted at once. Pass the `tx` of a
1420
+ * transaction you have open to commit it with your writes instead; once `tx`
1421
+ * commits it is the record of this call, and Brick does not add the automatic row.
842
1422
  *
843
- * @param manifest - `name`, `brick` (semver range), `requires`, `options`
844
- * (TypeBox), `secrets`, `tables`, `events`, the `resource`, `service` and `app`
845
- * parts, and a `dashboard` extension.
846
- * @returns A factory: `comments({ maxLength: 500 })` validates the options and
847
- * the Brick version and returns an instance to install.
848
- * @throws From the factory, when the running Brick is outside `brick` or an
849
- * option is invalid; when installed, when a required plugin is missing or the
850
- * host does not suit the plugin.
1423
+ * Brick copies no input or output into the log: `meta` holds what you pass.
1424
+ *
1425
+ * @param ctx - The action context: it names the service and the actor.
1426
+ * @param entry - `action` defaults to the running action's name, and is needed
1427
+ * in an action that is not itself recorded (a `GET`, `audit: false`).
1428
+ * `resource` and `recordId` say which record; `meta` is JSON of your choosing.
1429
+ * @param options - `tx`: an open transaction on the service's database.
1430
+ * @throws When `ctx` is not from an action of a service whose database holds an
1431
+ * audit table (a listener, a schedule or a workflow step has no such context),
1432
+ * or when `action` is missing.
851
1433
  * @example
852
- * export const audit = definePlugin({
853
- * name: "@acme/brick-audit",
854
- * brick: "^0.12.0",
855
- * requires: ["@brickkit/crud"],
856
- * options: t.Object({ table: t.String({ default: "audit" }) }),
857
- * tables: ({ table, text, timestamp }) => ({
858
- * log: table("log", { id: text("id").primaryKey(), at: timestamp("at").notNull() }),
859
- * }),
860
- * resource: ({ tables, hooks }) => {
861
- * hooks.afterCreate(({ row, tx }) =>
862
- * tx.insert(tables.log).values({ id: String(row.id), at: new Date() }));
863
- * return {};
864
- * },
1434
+ * await runInTransaction(ctx.db, async (tx) => {
1435
+ * await tx.update(orders).set({ status: "refunded" }).where(eq(orders.id, input.orderId));
1436
+ * await recordAudit(ctx, { resource: "order", recordId: input.orderId, meta: { reason: input.reason } }, { tx });
865
1437
  * });
866
- *
867
- * page.use(audit());
868
1438
  */
869
- declare function definePlugin<O extends TSchema | undefined = undefined, S extends Secrets = {}, T extends Record<string, Table> = {}, const E extends EventCatalog = {}, RA extends object = {}, SA = unknown, P extends Ports = {}>(manifest: PluginManifest<O, S, T, E, RA, SA, P>): PluginFactory<O, RA, SA, P>;
1439
+ declare function recordAudit(ctx: ActionContext, entry: {
1440
+ action?: string;
1441
+ resource?: string;
1442
+ recordId?: string | number;
1443
+ meta?: unknown;
1444
+ }, options?: {
1445
+ tx?: unknown;
1446
+ }): Promise<void>;
870
1447
  declare const OUTBOX_STATUSES: readonly ["pending", "claimed", "delivered", "dead"];
871
1448
  /** What the outbox rows are in, by state. */
872
1449
  type OutboxStatus = (typeof OUTBOX_STATUSES)[number];
@@ -1901,16 +2478,15 @@ declare function scheduleTable(engine: "postgres", options?: {
1901
2478
  * service `defineService` makes is one.
1902
2479
  */
1903
2480
  interface ServicePort<TDb = any, TServiceContext extends Record<string, any> = Record<string, any>> extends Service<TDb, TServiceContext> {
1904
- /** The values of this service's `deps`. Set by `brick({ deps })`. */
1905
- readonly deps?: Readonly<Record<string, unknown>>;
2481
+ readonly deps: Readonly<Record<string, unknown>>;
1906
2482
  /** Whether the service declares an event catalog. */
1907
2483
  readonly hasCatalog: boolean;
1908
- setDeps(deps: Readonly<Record<string, unknown>>): void;
1909
2484
  /** `resolveContext`, for an action or socket a plugin install created: it sees `pluginDeps`. */
1910
2485
  resolveContext(callCtx?: Partial<BaseContext<TDb> & TServiceContext>, pluginDeps?: Readonly<Record<string, unknown>>): Promise<BaseContext<TDb> & TServiceContext>;
1911
2486
  setRecorder(recorder: ServiceEvents | undefined): void;
1912
2487
  getOutbox(): OutboxTable | undefined;
1913
2488
  getScheduleTable(): ScheduleTable | undefined;
2489
+ getAuditTable(): AuditTable | undefined;
1914
2490
  /** @throws When the event is not in the catalog or its payload does not match. */
1915
2491
  checkEvent(name: string, payload: unknown): void;
1916
2492
  /** Adds events to the catalog (a plugin's). */
@@ -1923,6 +2499,75 @@ interface ServicePort<TDb = any, TServiceContext extends Record<string, any> = R
1923
2499
  /** Marks the definitions changed, so cached architecture and OpenAPI are rebuilt. */
1924
2500
  touch(): void;
1925
2501
  }
2502
+ /** What a verifier sees of a delivery. */
2503
+ interface WebhookRequest {
2504
+ /** The body exactly as it arrived. */
2505
+ rawBody: Uint8Array;
2506
+ headers: Headers;
2507
+ url: string;
2508
+ method: string;
2509
+ }
2510
+ /**
2511
+ * Decides whether the provider sent a delivery. `false`, or a throw, refuses it
2512
+ * (401); `true` accepts; `{ eventId }` accepts and names the event.
2513
+ * Set `suppliesEventId` on a verifier that always returns one, so a webhook
2514
+ * needs no `eventId` option.
2515
+ */
2516
+ type WebhookVerifier = ((request: WebhookRequest) => boolean | {
2517
+ eventId: string | number;
2518
+ } | Promise<boolean | {
2519
+ eventId: string | number;
2520
+ }>) & {
2521
+ suppliesEventId?: true;
2522
+ /** Set on a verifier that signs the body (a GET has none, so it cannot serve one). */
2523
+ signsBody?: true;
2524
+ };
2525
+ /** What `service.webhook` takes. */
2526
+ interface WebhookConfig<TInput extends TSchema, TErrors extends Record<string, ActionErrorDefinition>, TContext> {
2527
+ /** Its route is `<method> /api/<service>/<name>` (POST by default), as for an action. */
2528
+ name: string;
2529
+ description?: string;
2530
+ /** Relative to the service, as for an action. */
2531
+ path?: string;
2532
+ /** Default `"POST"`. With `"GET"` the input is the query string. */
2533
+ method?: "POST" | "GET";
2534
+ /** Runs first, on the raw body. Nothing else runs until it accepts. */
2535
+ verify: WebhookVerifier;
2536
+ /** The payload: JSON, or a form (`application/x-www-form-urlencoded`). Properties it does not declare are dropped. */
2537
+ input: TInput;
2538
+ /**
2539
+ * The delivery's id, so one sent twice runs once: a non-empty string or a
2540
+ * safe integer (`7` and `"7"` are one id); anything else, `undefined`
2541
+ * included, is no id. Not needed when the verifier supplies one.
2542
+ */
2543
+ eventId?: (args: {
2544
+ input: Static<TInput>;
2545
+ headers: Headers;
2546
+ url: string;
2547
+ method: string;
2548
+ }) => string | number | undefined | Promise<string | number | undefined>;
2549
+ /** `false` runs every delivery, with no check for repeats. Else `ttlMs` is how long a handled id is remembered (default 7 days). */
2550
+ replay?: false | {
2551
+ ttlMs?: number;
2552
+ };
2553
+ /** Largest body accepted, in bytes (default 1 MiB). */
2554
+ maxBodyBytes?: number;
2555
+ rateLimit?: RateLimits<Static<TInput>, TContext>;
2556
+ /** The delivery's audit row when the service's database holds an audit table: written when the handler returns, not for a refused or repeated delivery or one whose handler throws. `false` leaves it out. */
2557
+ audit?: AuditConfig<Static<TInput>>;
2558
+ errors?: TErrors;
2559
+ tags?: string[];
2560
+ /** What the provider is answered: the return value, which may be a `Response`; `{ ok: true }` for nothing. */
2561
+ execute: (params: {
2562
+ input: Static<TInput>;
2563
+ ctx: TContext;
2564
+ error: ErrorBuilder<TErrors>;
2565
+ /** `undefined` when `replay` is `false` and the delivery has no id. */
2566
+ eventId: string | undefined;
2567
+ }) => unknown;
2568
+ }
2569
+ /** Whether an action was declared with `service.webhook`. */
2570
+ declare function isWebhook(action: object): boolean;
1926
2571
  /** Set on actions declared with `resource.action(...)`. */
1927
2572
  interface ResourceActionInfo {
1928
2573
  resource: string;
@@ -2054,7 +2699,7 @@ interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<
2054
2699
  /** Optional Drizzle schema object for typed relational queries */
2055
2700
  schema?: TSchema;
2056
2701
  }
2057
- type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase<TSchema> & {
2702
+ type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>> = BunSQLiteDatabase$1<TSchema> & {
2058
2703
  $client: Database;
2059
2704
  };
2060
2705
  /**
@@ -2065,7 +2710,7 @@ type BrickSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string
2065
2710
  * other runtimes (e.g. Node) stays safe until this function is actually
2066
2711
  * called.
2067
2712
  */
2068
- declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase<TSchema>;
2713
+ declare function createSQLiteDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(config?: SQLiteDatabaseConfig<TSchema>): BunSQLiteDatabase$1<TSchema>;
2069
2714
  interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> {
2070
2715
  /** Existing postgres-js client. Connection options are ignored; the caller owns its lifecycle. */
2071
2716
  client?: Sql;
@@ -2167,10 +2812,32 @@ declare function isDatabaseHandle(value: unknown): value is DatabaseHandle<unkno
2167
2812
  *
2168
2813
  * export const database = defineDatabase({ tables: { pages } });
2169
2814
  */
2170
- declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase$1<TSchema>, TSchema>;
2815
+ declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options?: SQLiteDefinition<TSchema>): DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema>;
2171
2816
  declare function defineDatabase<TSchema extends Record<string, unknown> = Record<string, unknown>>(options: PostgresDefinition<TSchema>): DatabaseHandle<PostgresJsDatabase<TSchema> & {
2172
2817
  $client: Sql;
2173
2818
  }, TSchema>;
2819
+ /** The schema, unchanged in type and validation, marked sensitive. */
2820
+ declare function Sensitive<T extends TSchema>(schema: T): T;
2821
+ /** Whether any part of a schema is marked sensitive. */
2822
+ declare function hasSensitive(schema: unknown): boolean;
2823
+ type Reveal<TInput = unknown, TContext = any> = boolean | ((args: {
2824
+ field: string;
2825
+ input: TInput;
2826
+ ctx: TContext;
2827
+ }) => boolean | Promise<boolean>);
2828
+ interface Sensitivity {
2829
+ input(input: unknown): void;
2830
+ output(output: unknown, input: unknown, ctx: unknown): Promise<unknown>;
2831
+ }
2832
+ /**
2833
+ * Keep a secret out of what Brick logs and traces for the rest of the running
2834
+ * call: the logger, the span recorder and error responses replace it with
2835
+ * `[REDACTED]`. Call it as soon as `execute` loads a secret, before it can be
2836
+ * logged. It takes each string and number in the value, as a `t.Sensitive`
2837
+ * field's value is taken: booleans, and numbers under 4 digits, are left out.
2838
+ * Outside a call with `t.Sensitive` fields it does nothing.
2839
+ */
2840
+ declare function redact(value: unknown): void;
2174
2841
  /** The codes every action, listener and socket handler can raise, with their status and default message. */
2175
2842
  declare const STANDARD_ERRORS: {
2176
2843
  readonly BAD_REQUEST: {
@@ -2193,6 +2860,10 @@ declare const STANDARD_ERRORS: {
2193
2860
  readonly status: 409;
2194
2861
  readonly message: "Conflict";
2195
2862
  };
2863
+ readonly RATE_LIMITED: {
2864
+ readonly status: 429;
2865
+ readonly message: "Too Many Requests";
2866
+ };
2196
2867
  readonly INTERNAL_SERVER_ERROR: {
2197
2868
  readonly status: 500;
2198
2869
  readonly message: "Internal Server Error";
@@ -2241,6 +2912,54 @@ declare function signDashboardIdentity(identity: DashboardIdentity, now?: number
2241
2912
  * dashboard let in by token. Actions read it as `ctx.dashboard?.user`.
2242
2913
  */
2243
2914
  declare function dashboardUser(request: Request): DashboardUser | undefined;
2915
+ /**
2916
+ * Who a call comes from, as the service's `identity` hook says. Brick treats
2917
+ * the strings as opaque: it compares and stores them, never interprets them.
2918
+ */
2919
+ interface Identity {
2920
+ /** Who: the rate-limit key and the audit actor. */
2921
+ id: string;
2922
+ /** A display name for the audit log. */
2923
+ label?: string;
2924
+ /** Which tenant: scopes file storage and is recorded in the audit log. */
2925
+ tenant?: string;
2926
+ }
2927
+ /**
2928
+ * A limit on how often an action runs: at most `max` calls per `windowMs`, per key.
2929
+ * A fixed window, counted in the service's key-value storage.
2930
+ */
2931
+ interface RateLimit<TInput = any, TCtx = ActionContext> {
2932
+ /**
2933
+ * Whose calls count together: `"actor"` (the service's `identity` id; an
2934
+ * anonymous caller counts by IP), `"ip"` (the client address; skipped when
2935
+ * there is none, as in-process), or a function of the validated input and
2936
+ * the context. A function that returns `null` or `undefined` skips this
2937
+ * limit for the call.
2938
+ */
2939
+ per: "actor" | "ip" | ((args: {
2940
+ input: TInput;
2941
+ ctx: TCtx;
2942
+ }) => string | null | undefined);
2943
+ /** Calls allowed per window. */
2944
+ max: number;
2945
+ /** The window's length in milliseconds. */
2946
+ windowMs: number;
2947
+ }
2948
+ /** Where an app finds the client address, given the request and the socket peer: a non-empty string, or `undefined` for none. */
2949
+ type ClientIp = (args: {
2950
+ request: Request;
2951
+ peer: string | undefined;
2952
+ }) => string | undefined;
2953
+ /**
2954
+ * The client address of a call as rate limits count it, or `undefined` when it
2955
+ * has none: in-process without a request, or `app.handle` without `clientIp`.
2956
+ * An IPv4-mapped or NAT64 IPv6 address counts as its IPv4 address, any other
2957
+ * IPv6 address by its /64, and every spelling of one address the same. For a
2958
+ * custom `per` that combines it with another key.
2959
+ *
2960
+ * @throws When `clientIp` returns anything but a non-empty string or `undefined`.
2961
+ */
2962
+ declare function clientAddress(ctx: object): string | undefined;
2244
2963
  /** How many outbox rows are in each state. */
2245
2964
  type OutboxCounts = Record<OutboxStatus, number>;
2246
2965
  /**
@@ -2386,8 +3105,8 @@ declare class EventsHub {
2386
3105
  private stopping;
2387
3106
  /**
2388
3107
  * @param options - The `events` option.
2389
- * @param deps - The app's `brick({ deps })`, which `useDeps()` returns in its
2390
- * listeners and workflow steps.
3108
+ * @param deps - The deps of the app's services, which `useDeps()` returns in
3109
+ * its listeners, schedules and workflow steps.
2391
3110
  */
2392
3111
  constructor(options: EventsOptions, deps?: Record<string, unknown>);
2393
3112
  /**
@@ -2740,7 +3459,6 @@ type ErrorDetails<TDef> = TDef extends {
2740
3459
  interface ValidationErrorItem {
2741
3460
  path: string;
2742
3461
  message: string;
2743
- value?: unknown;
2744
3462
  type?: number;
2745
3463
  }
2746
3464
  declare class ValidationError extends Error {
@@ -2783,6 +3501,7 @@ interface StandardErrorMap {
2783
3501
  FORBIDDEN: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2784
3502
  NOT_FOUND: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2785
3503
  CONFLICT: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
3504
+ RATE_LIMITED: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2786
3505
  INTERNAL_SERVER_ERROR: (overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never;
2787
3506
  [key: string]: ((overrideMessage?: string, details?: unknown, options?: ErrorOptions) => never) | undefined;
2788
3507
  }
@@ -2807,13 +3526,43 @@ interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined,
2807
3526
  emits?: string[];
2808
3527
  tags?: string[];
2809
3528
  }
3529
+ /** One rate limit or several; see `RateLimit`. */
3530
+ type RateLimits<TInput = any, TCtx = ActionContext> = RateLimit<TInput, TCtx> | readonly RateLimit<TInput, TCtx>[];
3531
+ /**
3532
+ * How an action is recorded in the audit log: `false` leaves it out. `resource`
3533
+ * names the record's kind and `record` returns its id, from the validated input
3534
+ * and the result. Needs an audit table in the service's database; ignored without.
3535
+ */
3536
+ type AuditConfig<TInput = any, TResult = any> = false | {
3537
+ resource?: string;
3538
+ record?: (args: {
3539
+ input: TInput;
3540
+ result: TResult;
3541
+ }) => string | number | undefined;
3542
+ };
2810
3543
  interface ActionConfigWithAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
3544
+ /**
3545
+ * Whether this call may receive the output's `t.Sensitive` fields; by default
3546
+ * they are removed. `field` is the JSON pointer (`/items/0/token`). With
3547
+ * anything but `true`, a sensitive output field must be `t.Optional`.
3548
+ */
3549
+ reveal?: Reveal<TInputSchema extends TSchema ? Static<TInputSchema> : any, TContext>;
2811
3550
  /**
2812
3551
  * `true` refuses (401) any HTTP call that did not come through the
2813
3552
  * dashboard's `/app/*` proxy, so only the dashboard's pages can reach it.
2814
3553
  * `ctx.dashboard` is then set.
2815
3554
  */
2816
3555
  dashboard?: boolean;
3556
+ /**
3557
+ * Refuse calls over a limit (429, `RATE_LIMITED`), counted per caller in the
3558
+ * service's key-value storage. Runs after input validation, before `authorize`.
3559
+ */
3560
+ rateLimit?: RateLimits<TInputSchema extends TSchema ? Static<TInputSchema> : any, TContext>;
3561
+ /**
3562
+ * Recorded in the audit log when the service has an audit table and the
3563
+ * action's HTTP method is not `GET`. `false` leaves it out, for a `POST` that only reads.
3564
+ */
3565
+ audit?: AuditConfig<TInputSchema extends TSchema ? Static<TInputSchema> : any, TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2817
3566
  authorize: (params: {
2818
3567
  user?: TContext extends {
2819
3568
  user: infer U;
@@ -2828,12 +3577,28 @@ interface ActionConfigWithAuthorize<TInputSchema extends TSchema | undefined = u
2828
3577
  }) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
2829
3578
  }
2830
3579
  interface ActionConfigWithoutAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors> {
3580
+ /**
3581
+ * Whether this call may receive the output's `t.Sensitive` fields; by default
3582
+ * they are removed. `field` is the JSON pointer (`/items/0/token`). With
3583
+ * anything but `true`, a sensitive output field must be `t.Optional`.
3584
+ */
3585
+ reveal?: Reveal<TInputSchema extends TSchema ? Static<TInputSchema> : any, TContext>;
2831
3586
  /**
2832
3587
  * `true` refuses (401) any HTTP call that did not come through the
2833
3588
  * dashboard's `/app/*` proxy, so only the dashboard's pages can reach it.
2834
3589
  * `ctx.dashboard` is then set.
2835
3590
  */
2836
3591
  dashboard?: boolean;
3592
+ /**
3593
+ * Refuse calls over a limit (429, `RATE_LIMITED`), counted per caller in the
3594
+ * service's key-value storage. Runs after input validation, before `authorize`.
3595
+ */
3596
+ rateLimit?: RateLimits<TInputSchema extends TSchema ? Static<TInputSchema> : any, TContext>;
3597
+ /**
3598
+ * Recorded in the audit log when the service has an audit table and the
3599
+ * action's HTTP method is not `GET`. `false` leaves it out, for a `POST` that only reads.
3600
+ */
3601
+ audit?: AuditConfig<TInputSchema extends TSchema ? Static<TInputSchema> : any, TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2837
3602
  authorize?: undefined;
2838
3603
  execute: (params: {
2839
3604
  input: TInputSchema extends TSchema ? Static<TInputSchema> : any;
@@ -2842,18 +3607,20 @@ interface ActionConfigWithoutAuthorize<TInputSchema extends TSchema | undefined
2842
3607
  }) => Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema extends TSchema ? Static<TOutputSchema> : any);
2843
3608
  }
2844
3609
  type ActionConfig<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> = ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext> | ActionConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>;
3610
+ /** What a direct call may pass as `ctx`: any part of the action's context, with `deps` replaceable per name. */
3611
+ type CallContext<TContext> = { [K in keyof TContext]?: K extends "deps" ? Partial<TContext[K]> : TContext[K]; };
2845
3612
  interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> {
2846
3613
  (params: {
2847
3614
  input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2848
- ctx?: Partial<TContext>;
3615
+ ctx?: CallContext<TContext>;
2849
3616
  }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2850
3617
  name: string;
2851
3618
  serviceName?: string;
2852
3619
  config: ActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>;
2853
- run(input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: Partial<TContext>): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
3620
+ run(input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: CallContext<TContext>): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2854
3621
  execute(params: {
2855
3622
  input?: TInputSchema extends TSchema ? Static<TInputSchema> : any;
2856
- ctx?: Partial<TContext>;
3623
+ ctx?: CallContext<TContext>;
2857
3624
  }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>;
2858
3625
  validateInput(input: unknown): {
2859
3626
  success: true;
@@ -3008,6 +3775,8 @@ interface CommandConfig<TIn extends TSchema | undefined = undefined, TOut extend
3008
3775
  * schema's properties. Without it the reply is `{ id }`.
3009
3776
  */
3010
3777
  output?: TOut;
3778
+ /** As an action's `reveal`: which `t.Sensitive` output fields this call may receive. */
3779
+ reveal?: Reveal<ResourceActionInput<TIn, true>, TCtx>;
3011
3780
  errors?: TErr;
3012
3781
  /** Which child tables to load with the row, by their name on the resource. */
3013
3782
  load?: {
@@ -3015,6 +3784,18 @@ interface CommandConfig<TIn extends TSchema | undefined = undefined, TOut extend
3015
3784
  };
3016
3785
  /** For a resource without `crud`: which rows the command may load. */
3017
3786
  access?: ResourceActionAccess<TCtx>;
3787
+ /**
3788
+ * Refuse calls over a limit (429, `RATE_LIMITED`), counted per caller in the
3789
+ * service's key-value storage. Runs after input validation, before `authorize`.
3790
+ */
3791
+ rateLimit?: RateLimits<ResourceActionInput<TIn, true>, TCtx>;
3792
+ /**
3793
+ * Recorded in the audit log, with the resource and the record's `id`, in the
3794
+ * command's transaction, when the service has an audit table. `false` leaves it out.
3795
+ */
3796
+ audit?: AuditConfig<ResourceActionInput<TIn, true>, TOut extends TSchema ? Static<TOut> : {
3797
+ id: string | number;
3798
+ }>;
3018
3799
  authorize?: (params: {
3019
3800
  user?: TCtx extends {
3020
3801
  user: infer U;
@@ -3064,8 +3845,21 @@ interface ResourceActionConfig<TIn extends TSchema | undefined = undefined, TOut
3064
3845
  * answers 404 before `execute` runs.
3065
3846
  */
3066
3847
  record?: TRecord;
3848
+ /** As an action's `reveal`: which `t.Sensitive` output fields this call may receive. */
3849
+ reveal?: Reveal<ResourceActionInput<TIn, TRecord>, TCtx>;
3067
3850
  /** For a record action on a resource without `crud`: which rows it may load. */
3068
3851
  access?: ResourceActionAccess<TCtx>;
3852
+ /**
3853
+ * Refuse calls over a limit (429, `RATE_LIMITED`), counted per caller in the
3854
+ * service's key-value storage. Runs after input validation, before `authorize`.
3855
+ */
3856
+ rateLimit?: RateLimits<ResourceActionInput<TIn, TRecord>, TCtx>;
3857
+ /**
3858
+ * Recorded in the audit log, with the resource and, for a record action, the
3859
+ * `id`, when the service has an audit table and the action's HTTP method is not
3860
+ * `GET`. `false` leaves it out.
3861
+ */
3862
+ audit?: AuditConfig<ResourceActionInput<TIn, TRecord>, TOut extends TSchema ? Static<TOut> : any>;
3069
3863
  authorize?: (params: {
3070
3864
  user?: TCtx extends {
3071
3865
  user: infer U;
@@ -3081,16 +3875,34 @@ interface ResourceActionConfig<TIn extends TSchema | undefined = undefined, TOut
3081
3875
  row: TRecord extends true ? TRow : undefined;
3082
3876
  }) => Promise<TOut extends TSchema ? Static<TOut> : any> | (TOut extends TSchema ? Static<TOut> : any);
3083
3877
  }
3084
- interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any> {
3878
+ interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any, TDeps extends object = Record<string, unknown>> {
3085
3879
  database?: DatabaseHandle<TDb>;
3086
3880
  /**
3087
- * What the service needs from the app, as typed slots: `{ carrier: port<Carrier>() }`.
3088
- * `brick({ deps })` provides the values, and actions read them as `ctx.deps`.
3881
+ * The values the service's code uses, such as clients: `{ carrier: createCarrier() }`,
3882
+ * as a plain object (a class instance or a Map as the whole object is refused when the module is imported).
3883
+ * Actions read them as `ctx.deps`, typed from this object. They are created
3884
+ * when the module is imported, so a dep should connect on first use.
3089
3885
  */
3090
- deps?: Ports;
3886
+ deps?: TDeps;
3091
3887
  context?: (baseCtx: BaseContext<TDb> & {
3092
3888
  user?: unknown;
3093
- }) => Promise<TServiceContext> | TServiceContext;
3889
+ deps: Readonly<TDeps>;
3890
+ }) => Promise<TServiceContext & {
3891
+ deps?: never;
3892
+ }> | (TServiceContext & {
3893
+ deps?: never;
3894
+ });
3895
+ /**
3896
+ * Who the caller is and which tenant they act in, for the features that need
3897
+ * it. Runs at most once per call, and only when a feature asks. Return `null`
3898
+ * or `undefined` for an anonymous caller.
3899
+ *
3900
+ * @example
3901
+ * identity: (ctx) => ctx.user && { id: ctx.user.id, tenant: ctx.user.orgId },
3902
+ */
3903
+ identity?: (ctx: BaseContext<TDb> & TServiceContext & {
3904
+ deps: Readonly<TDeps>;
3905
+ }) => Identity | null | undefined | Promise<Identity | null | undefined>;
3094
3906
  /**
3095
3907
  * The service's event catalog: payload schema by event name. Each becomes
3096
3908
  * `service.events.<name>`, recorded as `<service>.<name>`.
@@ -3114,6 +3926,15 @@ interface ActionSchema {
3114
3926
  hasAuthorize: boolean;
3115
3927
  hasScope?: boolean;
3116
3928
  accessPolicy?: ActionAccessPolicy;
3929
+ /** The action's rate limits, without their keys. */
3930
+ rateLimit?: {
3931
+ max: number;
3932
+ windowMs: number;
3933
+ }[];
3934
+ /** `true` when a call is recorded in the audit log; absent when it is not. */
3935
+ audited?: boolean;
3936
+ /** Set on a webhook (`service.webhook`): a verified provider callback, not an action callers invoke. */
3937
+ webhook?: true;
3117
3938
  errors?: Record<string, ActionErrorDefinition>;
3118
3939
  emits?: string[];
3119
3940
  tags?: string[];
@@ -3154,7 +3975,7 @@ interface ArchitectureSchema {
3154
3975
  /** Every `definePlugin` installation, with its dashboard extension. */
3155
3976
  plugins?: InstalledPlugin[];
3156
3977
  }
3157
- interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>, TEvents extends EventCatalog = EventCatalog> {
3978
+ interface Service<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>, TEvents extends EventCatalog = EventCatalog> {
3158
3979
  readonly name: string;
3159
3980
  /** The declared events, as handles for `defineListener` and `emitEvent`. */
3160
3981
  readonly events: EventRefs<TEvents>;
@@ -3170,6 +3991,11 @@ interface Service<TDb = BunSQLiteDatabase$1<Record<string, unknown>>, TServiceCo
3170
3991
  action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
3171
3992
  action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
3172
3993
  action<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
3994
+ /**
3995
+ * Declare a provider webhook: an action in which `verify` accepts the
3996
+ * delivery before anything else runs. See `WebhookConfig`.
3997
+ */
3998
+ webhook<TIn extends TSchema, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: WebhookConfig<TIn, TErr, BaseContext<TDb> & TServiceContext>): Action<TIn, undefined, TErr, BaseContext<TDb> & TServiceContext>;
3173
3999
  tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): this;
3174
4000
  tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
3175
4001
  tool<TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>(config: ToolConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>;
@@ -3195,5 +4021,4 @@ interface ProxyOptions {
3195
4021
  from?: string;
3196
4022
  context?: Partial<ActionContext>;
3197
4023
  }
3198
- export { BrickSocketError as $, CrudEventPayload as $n, text$1 as $t, Resource as A, PluginFactory as An, useDeps as Ar, WireError as At, ServiceSchema as B, SecretRef as Bn, PostgresDatabaseConfig as Bt, ErrorDetails as C, OutboxStatus as Cn, crudEventName as Cr, DashboardIdentity as Ct, NarrowAuthorizedContext as D, outboxTable as Dn, Port as Dr, signDashboardIdentity as Dt, Logger as E, SQLiteOutboxTable as En, DepsOf as Er, dashboardUser as Et, ResourceConfig as F, PluginManifest as Fn, PostgresDefinition as Ft, ToolConfigWithoutAuthorize as G, overrideSecret as Gn, blob as Gt, Tool as H, defineSecret as Hn, BrickSQLiteDatabase as Ht, ResourceIdentity as I, PluginServiceContext as In, SQLiteDefinition as It, ValidationErrorItem as J, PluginTableBuilders as Jn, index$1 as Jt, ToolOptions as K, resetSecrets as Kn, createSQLiteDatabase as Kt, ResourceTypeOptions as L, PluginSetupContext as Ln, defineDatabase as Lt, ResourceActionConfig as M, PluginInstallOptions as Mn, DatabaseDefinition as Mt, ResourceActionInput as N, PluginInstance as Nn, DatabaseHandle as Nt, PreparationContribution as O, PluginAppContext as On, Ports as Or, STANDARD_ERRORS as Ot, ResourceChild as P, PluginLifecycleContext as Pn, EnvInput as Pt, BrickSocketConnectOptions as Q, getHostHooks as Qn, sqliteTable$1 as Qt, Service as R, definePlugin as Rn, isDatabaseHandle as Rt, ErrorBuilder as S, scheduleTable as Sn, EventRefs as Sr, DASHBOARD_KEY_ENV as St, InferTableRow as T, PostgresOutboxTable as Tn, isCrudEvent as Tr, dashboardKey as Tt, ToolAnnotations as U, envSource as Un, BunSQLiteDatabase$1 as Ut, StandardErrorMap as V, SecretSource as Vn, createPostgresDatabase as Vt, ToolConfigWithAuthorize as W, listSecrets as Wn, SQLiteDatabaseConfig as Wt, BrickSocketClient as X, PluginHookArgs as Xn, primaryKey as Xt, BrickClientSocket as Y, HostHooks as Yn, integer$1 as Yt, BrickSocketConfig as Z, PluginHooks as Zn, real$1 as Zt, CommandDecision as _, ServicePort as _n, ScheduleWorkflowRun as _r, stopAllEvents as _t, ActionConfigWithoutAuthorize as a, PluginRouteMethod as an, EventWorkflow as ar, BrickSocketStatus as at, DefaultServiceContext as b, ScheduleRunRecord as bn, EventCatalog as br, OutboxCounts as bt, ActionExecutionError as c, PluginRoutes as cn, ListenerFailure as cr, SocketEmitArgs as ct, BaseActionConfig as d, ResourcePluginContext as dn, WorkflowEvent as dr, SocketPayloads as dt, uniqueIndex as en, DispatchOptions as er, BrickSocketHandle as et, BaseContext as f, ResourcePluginTypes as fn, WorkflowsOptions as fr, SocketReplay as ft, CommandConfig as g, ResourceActionInfo as gn, ScheduleWorkflow as gr, ScheduleControl as gt, CommandChildren as h, ActionAccessInfo as hn, ScheduleRun as hr, EventsHub as ht, ActionConfigWithAuthorize as i, PluginEndpointContext as in, EventRecorder as ir, BrickSocketSender as it, ResourceActionAccess as j, PluginInfo as jn, HttpMethod as jr, isControlEvent as jt, ProxyOptions as k, PluginContext as kn, port as kr, StandardErrorCode as kt, ActionSchema as l, ResourcePlugin as ln, RetryDecision as lr, SocketEmitOptions as lt, Command as m, ServicePluginContext as mn, ScheduleConfig as mr, EventsDefinition as mt, ActionAccessPolicy as n, InstalledPlugin as nn, EventEnvelope as nr, BrickSocketReconnectOptions as nt, ActionContext as o, PluginRouteRegistrar as on, EventsOptions as or, SocketBroker as ot, ChildChanges as p, ServicePlugin as pn, Schedule as pr, SocketSchemas as pt, ValidationError as q, resolveSecrets as qn, foreignKey as qt, ActionConfig as r, PLUGIN_KIND as rn, EventListener as rr, BrickSocketSchema as rt, ActionErrorDefinition as s, PluginRouteScope as sn, EventsWorld as sr, SocketBrokerMessage as st, Action as t, ContextOf as tn, EventDelivery as tr, BrickSocketHandlerError as tt, ArchitectureSchema as u, ResourcePluginAPI as un, ServiceEvents as ur, SocketEventArgs as ut, CommandErrors as v, PostgresScheduleTable as vn, defineSchedule as vr, ScheduleState as vt, InferTableInsert as w, OutboxTable as wn, crudEventSource as wr, DashboardUser as wt, DuplicateNameError as x, ScheduleTable as xn, EventRef as xr, DASHBOARD_IDENTITY_HEADER as xt, CommandRow as y, SQLiteScheduleTable as yn, CrudEventOperation as yr, Dispatcher as yt, ServiceOptions as z, SecretOptions as zn, PostgresDatabase as zt };
3199
- //# sourceMappingURL=types.d.ts.map
4024
+ export { BrickSocketClient as $, PluginInfo as $n, listSecrets as $r, createPostgresDatabase as $t, PreparationContribution as A, WebhookRequest as An, ScheduleWorkflowRun as Ar, DashboardIdentity as At, ResourceTypeOptions as B, OutboxTable as Bn, CallFiles as Br, Sensitive as Bt, DuplicateNameError as C, ResourcePluginContext as Cn, ServiceEvents as Cr, OutboxCounts as Ct, InferTableRow as D, ActionAccessInfo as Dn, ScheduleConfig as Dr, Identity as Dt, InferTableInsert as E, ServicePluginContext as En, Schedule as Er, clientAddress as Et, ResourceActionConfig as F, SQLiteScheduleTable as Fn, EventRefs as Fr, STANDARD_ERRORS as Ft, Tool as G, PostgresAuditTable as Gn, ScopedFiles as Gr, DatabaseHandle as Gt, ServiceOptions as H, SQLiteOutboxTable as Hn, FileStorage as Hr, hasSensitive as Ht, ResourceActionInput as I, ScheduleRunRecord as In, crudEventName as Ir, StandardErrorCode as It, ToolConfigWithoutAuthorize as J, isAuditTable as Jn, SecretOptions as Jr, SQLiteDefinition as Jt, ToolAnnotations as K, SQLiteAuditTable as Kn, StoredFile as Kr, EnvInput as Kt, ResourceChild as L, ScheduleTable as Ln, crudEventSource as Lr, WireError as Lt, RateLimits as M, isWebhook as Mn, CrudEventOperation as Mr, dashboardKey as Mt, Resource as N, ServicePort as Nn, EventCatalog as Nr, dashboardUser as Nt, Logger as O, ResourceActionInfo as On, ScheduleRun as Or, DASHBOARD_IDENTITY_HEADER as Ot, ResourceActionAccess as P, PostgresScheduleTable as Pn, EventRef as Pr, signDashboardIdentity as Pt, BrickClientSocket as Q, PluginFactory as Qn, envSource as Qr, PostgresDatabaseConfig as Qt, ResourceConfig as R, scheduleTable as Rn, isCrudEvent as Rr, isControlEvent as Rt, DefaultServiceContext as S, ResourcePluginAPI as Sn, RetryDecision as Sr, Dispatcher as St, ErrorDetails as T, ServicePlugin as Tn, WorkflowsOptions as Tr, RateLimit as Tt, ServiceSchema as U, outboxTable as Un, RawDeps as Ur, redact as Ut, Service as V, PostgresOutboxTable as Vn, FileDriver as Vr, Sensitivity as Vt, StandardErrorMap as W, AuditTable as Wn, S3StorageOptions as Wr, DatabaseDefinition as Wt, ValidationError as X, PluginAppContext as Xn, SecretSource as Xr, isDatabaseHandle as Xt, ToolOptions as Y, recordAudit as Yn, SecretRef as Yr, defineDatabase as Yt, ValidationErrorItem as Z, PluginContext as Zn, defineSecret as Zr, PostgresDatabase as Zt, CommandChildren as _, PluginRouteMethod as _n, EventRecorder as _r, EventsDefinition as _t, ActionConfigWithoutAuthorize as a, foreignKey as an, PluginSetupContext as ar, BrickSocketReconnectOptions as at, CommandErrors as b, PluginRoutes as bn, EventsWorld as br, stopAllEvents as bt, ActionExecutionError as c, primaryKey as cn, HostHooks as cr, BrickSocketStatus as ct, AuditConfig as d, text as dn, getHostHooks as dr, SocketEmitArgs as dt, overrideSecret as ei, BrickSQLiteDatabase as en, PluginInstallOptions as er, BrickSocketConfig as et, BaseActionConfig as f, uniqueIndex as fn, CrudEventPayload as fr, SocketEmitOptions as ft, Command as g, PluginEndpointContext as gn, EventListener as gr, SocketSchemas as gt, ChildChanges as h, PLUGIN_KIND as hn, EventEnvelope as hr, SocketReplay as ht, ActionConfigWithAuthorize as i, createSQLiteDatabase as in, PluginServiceContext as ir, BrickSocketHandlerError as it, ProxyOptions as j, WebhookVerifier as jn, defineSchedule as jr, DashboardUser as jt, NarrowAuthorizedContext as k, WebhookConfig as kn, ScheduleWorkflow as kr, DASHBOARD_KEY_ENV as kt, ActionSchema as l, real as ln, PluginHookArgs as lr, SocketBroker as lt, CallContext as m, InstalledPlugin as mn, EventDelivery as mr, SocketPayloads as mt, ActionAccessPolicy as n, resolveSecrets as ni, SQLiteDatabaseConfig as nn, PluginLifecycleContext as nr, BrickSocketError as nt, ActionContext as o, index as on, definePlugin as or, BrickSocketSchema as ot, BaseContext as p, ContextOf as pn, DispatchOptions as pr, SocketEventArgs as pt, ToolConfigWithAuthorize as q, auditTable as qn, s3 as qr, PostgresDefinition as qt, ActionConfig as r, HttpMethod as ri, blob as rn, PluginManifest as rr, BrickSocketHandle as rt, ActionErrorDefinition as s, integer as sn, PluginTableBuilders as sr, BrickSocketSender as st, Action as t, resetSecrets as ti, BunSQLiteDatabase as tn, PluginInstance as tr, BrickSocketConnectOptions as tt, ArchitectureSchema as u, sqliteTable as un, PluginHooks as ur, SocketBrokerMessage as ut, CommandConfig as v, PluginRouteRegistrar as vn, EventWorkflow as vr, EventsHub as vt, ErrorBuilder as w, ResourcePluginTypes as wn, WorkflowEvent as wr, ClientIp as wt, CommandRow as x, ResourcePlugin as xn, ListenerFailure as xr, ScheduleState as xt, CommandDecision as y, PluginRouteScope as yn, EventsOptions as yr, ScheduleControl as yt, ResourceIdentity as z, OutboxStatus as zn, CallDeps as zr, Reveal as zt };