@arcote.tech/arc 0.3.6 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/adapters/auth-adapter.d.ts +35 -20
  2. package/dist/adapters/command-wire.d.ts +4 -2
  3. package/dist/adapters/event-wire.d.ts +28 -3
  4. package/dist/adapters/index.d.ts +1 -0
  5. package/dist/adapters/query-wire.d.ts +6 -4
  6. package/dist/adapters/wire.d.ts +7 -11
  7. package/dist/context-element/aggregate/aggregate-base.d.ts +31 -0
  8. package/dist/context-element/aggregate/aggregate-builder.d.ts +139 -0
  9. package/dist/context-element/aggregate/aggregate-data.d.ts +114 -0
  10. package/dist/context-element/aggregate/aggregate-element.d.ts +69 -0
  11. package/dist/context-element/aggregate/index.d.ts +31 -0
  12. package/dist/context-element/aggregate/simple-aggregate.d.ts +94 -0
  13. package/dist/context-element/command/command-context.d.ts +3 -32
  14. package/dist/context-element/context-element.d.ts +7 -1
  15. package/dist/context-element/element-context.d.ts +39 -0
  16. package/dist/context-element/index.d.ts +2 -0
  17. package/dist/context-element/route/route.d.ts +8 -26
  18. package/dist/context-element/static-view/static-view.d.ts +2 -2
  19. package/dist/context-element/view/index.d.ts +1 -1
  20. package/dist/data-storage/store-state.abstract.d.ts +1 -0
  21. package/dist/elements/branded.d.ts +1 -0
  22. package/dist/elements/object.d.ts +2 -2
  23. package/dist/elements/optional.d.ts +1 -1
  24. package/dist/fragment/arc-fragment.d.ts +18 -0
  25. package/dist/fragment/index.d.ts +2 -0
  26. package/dist/index.d.ts +16 -0
  27. package/dist/index.js +1006 -458
  28. package/dist/model/context-accessor.d.ts +51 -0
  29. package/dist/model/index.d.ts +4 -0
  30. package/dist/model/live-query/live-query.d.ts +4 -26
  31. package/dist/model/model-adapters.d.ts +5 -0
  32. package/dist/model/model-like.d.ts +9 -0
  33. package/dist/model/model.d.ts +10 -1
  34. package/dist/model/mutation-executor/mutation-executor.d.ts +2 -2
  35. package/dist/model/scoped-model.d.ts +66 -0
  36. package/dist/model/scoped-wire-proxy.d.ts +23 -0
  37. package/dist/streaming/index.d.ts +0 -2
  38. package/dist/streaming/streaming-live-query.d.ts +10 -12
  39. package/dist/streaming/streaming-query-cache.d.ts +25 -4
  40. package/package.json +1 -1
@@ -1,9 +1,10 @@
1
1
  /**
2
- * AuthAdapter - Manages authentication token for the model
2
+ * AuthAdapter - Manages authentication tokens per scope
3
3
  *
4
- * Stores the current JWT token and provides decoded params.
4
+ * Stores JWT tokens keyed by scope name and provides decoded params.
5
+ * Auto-persists tokens to localStorage (when available) under `arc:token:{scope}`.
5
6
  * On client: decodes token without signature verification
6
- * On server: token is verified before being set
7
+ * On server: token is verified before being set (no localStorage)
7
8
  */
8
9
  export interface DecodedToken {
9
10
  tokenName: string;
@@ -12,36 +13,50 @@ export interface DecodedToken {
12
13
  exp?: number;
13
14
  }
14
15
  export declare class AuthAdapter {
15
- private token;
16
- private decoded;
16
+ private scopes;
17
17
  /**
18
- * Set the JWT token
19
- * Decodes the payload (without signature verification on client)
18
+ * Set the JWT token for a scope.
19
+ * Auto-persists to localStorage when available.
20
20
  */
21
- setToken(token: string | null): void;
21
+ setToken(token: string | null, scope?: string): void;
22
22
  /**
23
- * Get the raw JWT token string
23
+ * Load all persisted scope tokens from localStorage.
24
+ * Call once on app init before any queries.
24
25
  */
25
- getToken(): string | null;
26
+ loadPersisted(): void;
26
27
  /**
27
- * Get decoded token data
28
+ * Get the raw JWT token string for a scope
28
29
  */
29
- getDecoded(): DecodedToken | null;
30
+ getToken(scope?: string): string | null;
30
31
  /**
31
- * Get token params (e.g., { userId, projectId })
32
+ * Get decoded token data for a scope
32
33
  */
33
- getParams(): Record<string, any> | null;
34
+ getDecoded(scope?: string): DecodedToken | null;
34
35
  /**
35
- * Get token name (e.g., "user")
36
+ * Get token params for a scope (e.g., { userId, projectId })
36
37
  */
37
- getTokenName(): string | null;
38
+ getParams(scope?: string): Record<string, any> | null;
38
39
  /**
39
- * Check if token is set and valid
40
+ * Get token name for a scope (e.g., "user")
40
41
  */
41
- isAuthenticated(): boolean;
42
+ getTokenName(scope?: string): string | null;
42
43
  /**
43
- * Check if token is expired
44
+ * Check if authenticated.
45
+ * If scope is given, checks that scope. If omitted, checks any scope.
44
46
  */
45
- isExpired(): boolean;
47
+ isAuthenticated(scope?: string): boolean;
48
+ /**
49
+ * Check if token is expired for a scope
50
+ */
51
+ isExpired(scope?: string): boolean;
52
+ /**
53
+ * Get all scope names that have tokens
54
+ */
55
+ getAllScopes(): string[];
56
+ /**
57
+ * Clear all scope tokens and their localStorage entries.
58
+ * Call on logout.
59
+ */
60
+ clear(): void;
46
61
  }
47
62
  //# sourceMappingURL=auth-adapter.d.ts.map
@@ -5,8 +5,9 @@
5
5
  * - Execute commands remotely on the server
6
6
  * - Handle command request/response serialization
7
7
  * - Automatic FormData handling for file uploads
8
+ * - Per-request auth via scope + token
8
9
  */
9
- import { Wire } from "./wire";
10
+ import { Wire, type WireAuth } from "./wire";
10
11
  export declare class CommandWire extends Wire {
11
12
  constructor(baseUrl: string);
12
13
  /**
@@ -14,9 +15,10 @@ export declare class CommandWire extends Wire {
14
15
  *
15
16
  * @param name - Command name
16
17
  * @param params - Command parameters
18
+ * @param auth - Scope and token for this request
17
19
  * @returns Command result from server
18
20
  */
19
- executeCommand(name: string, params: any): Promise<any>;
21
+ executeCommand(name: string, params: any, auth?: WireAuth): Promise<any>;
20
22
  /**
21
23
  * Check if object contains any File instances (recursively)
22
24
  */
@@ -5,6 +5,7 @@
5
5
  * - Sends locally created events to the host
6
6
  * - Receives events from the host (from other clients)
7
7
  * - Handles reconnection and sync state
8
+ * - Manages per-scope token caching
8
9
  */
9
10
  export interface SyncableEvent {
10
11
  localId: string;
@@ -20,24 +21,33 @@ export interface ReceivedEvent {
20
21
  createdAt: string;
21
22
  clientId: string;
22
23
  }
24
+ import type { ContextDescriptor } from "../model/context-accessor";
23
25
  type EventWireState = "disconnected" | "connecting" | "connected";
24
26
  export declare class EventWire {
25
27
  private readonly baseUrl;
26
28
  private instanceId;
27
29
  private ws;
28
30
  private state;
29
- private token;
31
+ private scopeTokens;
30
32
  private lastHostEventId;
31
33
  private pendingEvents;
32
34
  private onEventCallback?;
33
35
  private onSyncedCallback?;
34
36
  private reconnectTimeout?;
35
37
  private syncRequested;
38
+ private viewSubscriptions;
39
+ private viewSubCounter;
40
+ private pendingViewSubs;
36
41
  constructor(baseUrl: string);
37
42
  /**
38
- * Set authentication token
43
+ * Set a scope token. If connected, sends scope:auth message to server.
44
+ * If token is null, removes the scope.
39
45
  */
40
- setAuthToken(token: string | null): void;
46
+ setScopeToken(scope: string, token: string | null): void;
47
+ /**
48
+ * Check if any scope has a token set
49
+ */
50
+ hasScopeTokens(): boolean;
41
51
  /**
42
52
  * Set the last synced host event ID
43
53
  * Used to restore sync state after page refresh
@@ -67,13 +77,28 @@ export declare class EventWire {
67
77
  * Set callback for when events are confirmed synced
68
78
  */
69
79
  onSynced(callback: (localIds: string[]) => void): void;
80
+ /**
81
+ * Subscribe to a server-side query via WebSocket.
82
+ * Server executes the descriptor and pushes results on change.
83
+ */
84
+ subscribeQuery(descriptor: ContextDescriptor, callback: (data: any[]) => void, scope?: string): string;
85
+ /**
86
+ * Unsubscribe from a server-side query.
87
+ */
88
+ unsubscribeQuery(subscriptionId: string): void;
70
89
  /**
71
90
  * Get current connection state
72
91
  */
73
92
  getState(): EventWireState;
93
+ /**
94
+ * Send all cached scope tokens to the server
95
+ * Called on connect and reconnect
96
+ */
97
+ private sendAllScopeTokens;
74
98
  private handleMessage;
75
99
  private requestSync;
76
100
  private flushPendingEvents;
101
+ private flushPendingViewSubs;
77
102
  private scheduleReconnect;
78
103
  }
79
104
  export {};
@@ -16,6 +16,7 @@ export type { ReceivedEvent, SyncableEvent } from "./event-wire";
16
16
  export { QueryWire } from "./query-wire";
17
17
  export type { StreamConnection } from "./query-wire";
18
18
  export { Wire } from "./wire";
19
+ export type { WireAuth } from "./wire";
19
20
  export { EVENT_TABLES, LocalEventPublisher } from "./event-publisher";
20
21
  export type { EventPublisher, EventWithSyncStatus, StoredEvent, StoredEventSyncStatus, StoredEventTag, } from "./event-publisher";
21
22
  //# sourceMappingURL=index.d.ts.map
@@ -4,8 +4,9 @@
4
4
  * Provides:
5
5
  * - One-shot queries via HTTP POST
6
6
  * - Live queries via Server-Sent Events (SSE)
7
+ * - Per-request auth via scope + token
7
8
  */
8
- import { Wire } from "./wire";
9
+ import { Wire, type WireAuth } from "./wire";
9
10
  export interface StreamConnection {
10
11
  eventSource: EventSource;
11
12
  unsubscribe: () => void;
@@ -17,18 +18,19 @@ export declare class QueryWire extends Wire {
17
18
  *
18
19
  * @param viewName - Name of the view to query
19
20
  * @param options - Query options (where, orderBy, limit)
21
+ * @param auth - Scope and token for this request
20
22
  * @returns Query results
21
23
  */
22
- query(viewName: string, options?: any): Promise<any[]>;
24
+ query(viewName: string, options?: any, auth?: WireAuth): Promise<any[]>;
23
25
  /**
24
26
  * Create a live query stream using SSE
25
27
  *
26
28
  * @param viewName - Name of the view to stream
27
29
  * @param options - Query options (where, orderBy, limit)
28
30
  * @param callback - Called when data changes
29
- * @param token - Auth token for the stream (optional, uses wire token if not provided)
31
+ * @param auth - Scope and token for this request (SSE uses URL params since headers aren't supported)
30
32
  * @returns StreamConnection with unsubscribe method
31
33
  */
32
- stream(viewName: string, options: any, callback: (data: any[]) => void, token?: string | null): StreamConnection;
34
+ stream(viewName: string, options: any, callback: (data: any[]) => void, auth?: WireAuth): StreamConnection;
33
35
  }
34
36
  //# sourceMappingURL=query-wire.d.ts.map
@@ -1,28 +1,24 @@
1
1
  /**
2
2
  * Wire - Base abstraction for client-server communication
3
3
  *
4
- * Handles JWT token management and provides fetch abstraction
4
+ * Handles per-request auth (scope + token) and provides fetch abstraction
5
5
  * for making authenticated requests to the server.
6
6
  */
7
+ export interface WireAuth {
8
+ scope: string;
9
+ token: string | null;
10
+ }
7
11
  export declare class Wire {
8
- private token;
9
12
  protected readonly baseUrl: string;
10
13
  constructor(baseUrl: string);
11
- /**
12
- * Set authentication token for requests
13
- */
14
- setAuthToken(token: string | null): void;
15
- /**
16
- * Get the current auth token
17
- */
18
- getAuthToken(): string | null;
19
14
  /**
20
15
  * Get the base URL
21
16
  */
22
17
  getBaseUrl(): string;
23
18
  /**
24
19
  * Make authenticated fetch request to server
20
+ * Auth is passed per-request via the auth parameter
25
21
  */
26
- fetch(endpoint: string, options?: RequestInit): Promise<Response>;
22
+ fetch(endpoint: string, options?: RequestInit, auth?: WireAuth): Promise<Response>;
27
23
  }
28
24
  //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Aggregate Base Class
3
+ *
4
+ * Base class that aggregate instances extend.
5
+ * Provides this.value (current state), this._id, and this.ctx (mutation context).
6
+ */
7
+ import type { ArcIdAny } from "../../elements/id";
8
+ import type { ArcObjectAny } from "../../elements/object";
9
+ import type { ModelAdapters } from "../../model/model-adapters";
10
+ import type { $type } from "../../utils/types/get-type";
11
+ import type { ArcViewItem } from "../view/view-context";
12
+ import type { AggregateInstanceCtx } from "./aggregate-builder";
13
+ import type { AggregateEventEntry } from "./aggregate-data";
14
+ /**
15
+ * Base class for aggregate instances.
16
+ *
17
+ * Created by queryContext when wrapping view rows.
18
+ * Provides:
19
+ * - this.value — current state from the view
20
+ * - this._id — entity identifier
21
+ * - this.ctx — mutation context with emit per registered event
22
+ */
23
+ export declare class AggregateBase<Id extends ArcIdAny = ArcIdAny, Schema extends ArcObjectAny = ArcObjectAny, Events extends AggregateEventEntry[] = AggregateEventEntry[]> {
24
+ #private;
25
+ readonly value: $type<Schema>;
26
+ readonly _id: $type<Id>;
27
+ constructor(row: ArcViewItem<Id, Schema>, adapters: ModelAdapters);
28
+ toJSON(): any;
29
+ get ctx(): AggregateInstanceCtx<Events>;
30
+ }
31
+ //# sourceMappingURL=aggregate-base.d.ts.map
@@ -0,0 +1,139 @@
1
+ import type { ArcIdAny } from "../../elements/id";
2
+ import { ArcObject, type ArcObjectAny, type ArcRawShape } from "../../elements/object";
3
+ import type { ArcTokenAny } from "../../token/token";
4
+ import type { $type } from "../../utils/types/get-type";
5
+ import type { Simplify } from "../../utils";
6
+ import { ArcEvent, type ArcEventAny } from "../event/event";
7
+ import type { ArcEventInstance } from "../event/instance";
8
+ import type { ArcViewHandlerContext } from "../view/view-context";
9
+ import type { ViewProtection, ViewProtectionFn } from "../view/view-data";
10
+ import { AggregateBase } from "./aggregate-base";
11
+ import type { AggregateCronMethodEntry, AggregateEventEntry, AggregateMutateMethodEntry, AggregateQueryMethodEntry } from "./aggregate-data";
12
+ type InlineArcEvent<EN extends string, PS extends ArcRawShape> = ArcEvent<{
13
+ name: EN;
14
+ payload: ArcObject<PS>;
15
+ protections: [];
16
+ }>;
17
+ type AggregateRow<Id extends ArcIdAny, Schema extends ArcObjectAny> = Simplify<$type<Schema> & {
18
+ _id: $type<Id>;
19
+ }>;
20
+ type AggregatePrivateQuery<Id extends ArcIdAny, Schema extends ArcObjectAny> = {
21
+ find: (options?: any) => Promise<AggregateRow<Id, Schema>[]>;
22
+ findOne: (where?: any) => Promise<AggregateRow<Id, Schema> | undefined>;
23
+ };
24
+ type MutateMethodContext<Id extends ArcIdAny, Schema extends ArcObjectAny, Events extends AggregateEventEntry[]> = {
25
+ [E in Events[number] as E["event"]["name"]]: {
26
+ emit: (payload: E["event"]["payload"] extends {
27
+ deserialize: (...a: any) => any;
28
+ } ? $type<E["event"]["payload"]> : undefined) => Promise<void>;
29
+ };
30
+ } & {
31
+ $auth: {
32
+ params: any;
33
+ tokenName: string;
34
+ };
35
+ $query: AggregatePrivateQuery<Id, Schema>;
36
+ };
37
+ type ClientQueryContext<Id extends ArcIdAny, Schema extends ArcObjectAny> = {
38
+ $query: {
39
+ find: {
40
+ <M extends new (row: AggregateRow<Id, Schema>, adapters: any) => any>(options: any, mapper: M): Promise<InstanceType<M>[]>;
41
+ (options?: any): Promise<AggregateRow<Id, Schema>[]>;
42
+ };
43
+ findOne: {
44
+ <M extends new (row: AggregateRow<Id, Schema>, adapters: any) => any>(where: any, mapper: M): Promise<InstanceType<M> | undefined>;
45
+ (where?: any): Promise<AggregateRow<Id, Schema> | undefined>;
46
+ };
47
+ };
48
+ $auth: {
49
+ params: any;
50
+ tokenName: string;
51
+ };
52
+ };
53
+ export type AggregateInstanceCtx<Events extends AggregateEventEntry[]> = {
54
+ [E in Events[number] as E["event"]["name"]]: {
55
+ emit: (payload: E["event"]["payload"] extends {
56
+ deserialize: (...a: any) => any;
57
+ } ? $type<E["event"]["payload"]> : undefined) => Promise<void>;
58
+ };
59
+ };
60
+ type PublicEvents<Events extends AggregateEventEntry[]> = Extract<Events[number], {
61
+ isPublic: true;
62
+ }>;
63
+ type PublicEventNames<Events extends AggregateEventEntry[]> = PublicEvents<Events>["event"]["name"];
64
+ type GetPublicEvent<Events extends AggregateEventEntry[], Name extends string> = Extract<PublicEvents<Events>, {
65
+ event: {
66
+ name: Name;
67
+ };
68
+ }>["event"];
69
+ export declare class AggregateBuilder<Name extends string, Id extends ArcIdAny, Schema extends ArcObjectAny, Events extends AggregateEventEntry[], MutateMethods extends AggregateMutateMethodEntry[], QueryMethods extends AggregateQueryMethodEntry[] = []> {
70
+ private readonly _name;
71
+ private readonly _id;
72
+ private readonly _schema;
73
+ private readonly _events;
74
+ private readonly _protections;
75
+ private readonly _mutateMethods;
76
+ private readonly _queryMethods;
77
+ constructor(name: Name, id: Id, schema: Schema, events?: Events, protections?: ViewProtection[], mutateMethods?: MutateMethods, queryMethods?: QueryMethods);
78
+ protectBy<T extends ArcTokenAny>(token: T, protectionFn: ViewProtectionFn<any>): AggregateBuilder<Name, Id, Schema, Events, MutateMethods, QueryMethods>;
79
+ event<const EventName extends string, PayloadShape extends ArcRawShape>(eventName: EventName, payload: PayloadShape, handler: (ctx: ArcViewHandlerContext<Id, Schema>, event: ArcEventInstance<InlineArcEvent<EventName, PayloadShape>>) => Promise<void>): AggregateBuilder<Name, Id, Schema, [
80
+ ...Events,
81
+ AggregateEventEntry<InlineArcEvent<EventName, PayloadShape>, Id, Schema, false>
82
+ ], MutateMethods, QueryMethods>;
83
+ publicEvent<const EventName extends string, PayloadShape extends ArcRawShape>(eventName: EventName, payload: PayloadShape, handler: (ctx: ArcViewHandlerContext<Id, Schema>, event: ArcEventInstance<InlineArcEvent<EventName, PayloadShape>>) => Promise<void>): AggregateBuilder<Name, Id, Schema, [
84
+ ...Events,
85
+ AggregateEventEntry<InlineArcEvent<EventName, PayloadShape>, Id, Schema, true>
86
+ ], MutateMethods, QueryMethods>;
87
+ handleEvent<E extends ArcEventAny>(arcEvent: E, handler: (ctx: ArcViewHandlerContext<Id, Schema>, event: ArcEventInstance<E>) => Promise<void>): AggregateBuilder<Name, Id, Schema, [
88
+ ...Events,
89
+ AggregateEventEntry<E, ArcIdAny, ArcObjectAny, false>
90
+ ], MutateMethods, QueryMethods>;
91
+ mutateMethod<const MethodName extends string, ParamsShape extends ArcRawShape, HR = void, R = never>(methodName: MethodName, config: {
92
+ params: ParamsShape;
93
+ result?: R;
94
+ }, handler: ((ctx: MutateMethodContext<Id, Schema, Events>, params: $type<ArcObject<ParamsShape>>) => Promise<HR>) | false): AggregateBuilder<Name, Id, Schema, Events, [
95
+ ...MutateMethods,
96
+ {
97
+ name: MethodName;
98
+ params: ArcObject<ParamsShape>;
99
+ handler: typeof handler;
100
+ handlerReturn: HR;
101
+ result: R;
102
+ }
103
+ ], QueryMethods>;
104
+ /**
105
+ * Attach a cron schedule to the last declared mutateMethod.
106
+ * The CronScheduler will call this method on the given schedule
107
+ * for every existing aggregate instance.
108
+ *
109
+ * @param expression - A cron expression (e.g. "0 *\/6 * * *" for every 6 hours)
110
+ */
111
+ cron(expression: string): AggregateBuilder<Name, Id, Schema, Events, MutateMethods, QueryMethods>;
112
+ clientQuery<const MethodName extends string, H extends (ctx: ClientQueryContext<Id, Schema>, ...args: any[]) => Promise<any>>(methodName: MethodName, handler: H): AggregateBuilder<Name, Id, Schema, Events, MutateMethods, [
113
+ ...QueryMethods,
114
+ {
115
+ name: MethodName;
116
+ handler: H;
117
+ }
118
+ ]>;
119
+ build(): AggregateConstructor<Name, Id, Schema, Events, MutateMethods, QueryMethods>;
120
+ }
121
+ export type AggregateConstructor<Name extends string = string, Id extends ArcIdAny = ArcIdAny, Schema extends ArcObjectAny = ArcObjectAny, Events extends AggregateEventEntry[] = AggregateEventEntry[], MutateMethods extends AggregateMutateMethodEntry[] = AggregateMutateMethodEntry[], QueryMethods extends AggregateQueryMethodEntry[] = AggregateQueryMethodEntry[]> = (new (row: import("../view/view-context").ArcViewItem<Id, Schema>, adapters: import("../../model/model-adapters").ModelAdapters) => AggregateBase<Id, Schema, Events>) & {
122
+ readonly __aggregateName: Name;
123
+ readonly __aggregateId: Id;
124
+ readonly __aggregateSchema: Schema;
125
+ readonly __aggregateEvents: Events;
126
+ readonly __aggregateProtections: ViewProtection[];
127
+ readonly __aggregateMutateMethods: MutateMethods;
128
+ readonly __aggregateQueryMethods: QueryMethods;
129
+ readonly __aggregateCronMethods: AggregateCronMethodEntry[];
130
+ getEvent<EventName extends PublicEventNames<Events>>(name: EventName): GetPublicEvent<Events, EventName>;
131
+ };
132
+ export type AggregateConstructorAny = AggregateConstructor<any, any, any, any, any, any>;
133
+ /** Extract the full row type ({ _id, ...fields }) from an aggregate constructor. */
134
+ export type AggregateData<Ctor extends AggregateConstructorAny> = {
135
+ _id: $type<Ctor["__aggregateId"]>;
136
+ } & $type<Ctor["__aggregateSchema"]>;
137
+ export declare function aggregate<const Name extends string, Id extends ArcIdAny, SchemaShape extends ArcRawShape>(name: Name, id: Id, schema: SchemaShape): AggregateBuilder<Name, Id, ArcObject<SchemaShape>, [], [], []>;
138
+ export {};
139
+ //# sourceMappingURL=aggregate-builder.d.ts.map
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Aggregate Data Types
3
+ *
4
+ * Type definitions for aggregate configuration stored as static fields
5
+ * on the aggregate constructor class.
6
+ */
7
+ import type { ArcIdAny } from "../../elements/id";
8
+ import type { ArcObjectAny } from "../../elements/object";
9
+ import type { ArcEventAny } from "../event/event";
10
+ import type { Simplify } from "../../utils";
11
+ import type { ArcEventInstance } from "../event/instance";
12
+ import type { ArcViewHandlerContext } from "../view/view-context";
13
+ import type { ViewProtection } from "../view/view-data";
14
+ /**
15
+ * Handler for an aggregate event — same signature as ArcView handler.
16
+ * Receives ctx with set/modify/remove and the event instance.
17
+ */
18
+ export type AggregateEventHandler<Id extends ArcIdAny, Schema extends ArcObjectAny, Event extends ArcEventAny> = (ctx: ArcViewHandlerContext<Id, Schema>, event: ArcEventInstance<Event>) => Promise<void>;
19
+ /**
20
+ * Entry in the aggregate's event registry.
21
+ * Pairs an ArcEvent instance with its view handler.
22
+ *
23
+ * - isInline: true if event was created via .event() or .publicEvent() (inline definition)
24
+ * - isPublic: true if event was created via .publicEvent() (accessible via getEvent())
25
+ */
26
+ export interface AggregateEventEntry<Event extends ArcEventAny = ArcEventAny, Id extends ArcIdAny = ArcIdAny, Schema extends ArcObjectAny = ArcObjectAny, IsPublic extends boolean = boolean> {
27
+ readonly event: Event;
28
+ readonly handler: (ctx: any, event: any) => Promise<void>;
29
+ readonly isInline: boolean;
30
+ readonly isPublic: IsPublic;
31
+ }
32
+ /**
33
+ * Context passed to mutateMethod handlers.
34
+ * Provides emit per registered event + $auth from adapters.
35
+ */
36
+ export type AggregateMutateContext<Events extends AggregateEventEntry[]> = {
37
+ [E in Events[number] as E["event"]["name"]]: {
38
+ emit: (payload: any) => Promise<void>;
39
+ };
40
+ } & {
41
+ $auth: {
42
+ params: any;
43
+ tokenName: string;
44
+ };
45
+ };
46
+ /**
47
+ * Entry in the aggregate's mutateMethod registry.
48
+ * Defines a named mutation exposed via mutateContext/useCommands.
49
+ */
50
+ export interface AggregateMutateMethodEntry {
51
+ readonly name: string;
52
+ readonly params: ArcObjectAny;
53
+ readonly handler: ((ctx: any, params: any) => Promise<any>) | false;
54
+ readonly result?: any;
55
+ readonly cronExpression?: string;
56
+ }
57
+ /**
58
+ * Cron method entry extracted at build time.
59
+ * Used by CronScheduler to discover and register cron jobs.
60
+ */
61
+ export interface AggregateCronMethodEntry {
62
+ readonly aggregateName: string;
63
+ readonly methodName: string;
64
+ readonly cronExpression: string;
65
+ }
66
+ /**
67
+ * Entry in the aggregate's clientQuery registry.
68
+ * Defines a named query exposed via queryContext/useQuery.
69
+ */
70
+ export interface AggregateQueryMethodEntry {
71
+ readonly name: string;
72
+ readonly handler: (...args: any[]) => Promise<any>;
73
+ }
74
+ /**
75
+ * Maps MutateMethods tuple → { methodName: (params) => Promise<ReturnType> }
76
+ * Used as return type of mutateContext() on ArcAggregateElement.
77
+ */
78
+ /** Resolve mutateMethod return type: explicit result > handler return > Promise<any> */
79
+ type MutateReturn<M> = M extends {
80
+ result: infer R;
81
+ } ? [R] extends [never] ? M extends {
82
+ handlerReturn: infer HR;
83
+ } ? Promise<HR> : Promise<any> : Promise<R> : M extends {
84
+ handlerReturn: infer HR;
85
+ } ? Promise<HR> : Promise<any>;
86
+ export type AggregateMutateMethodContext<MutateMethods extends AggregateMutateMethodEntry[]> = {
87
+ [M in MutateMethods[number] as M["name"]]: M["params"] extends {
88
+ deserialize: (...a: any) => infer P;
89
+ } ? (params: P) => MutateReturn<M> : () => MutateReturn<M>;
90
+ };
91
+ /**
92
+ * Maps QueryMethods tuple → { methodName: consumer API }
93
+ * Extracts params and return type directly from handler.
94
+ * Uses rest args pattern so handlers without params produce no-arg consumer methods.
95
+ */
96
+ export type AggregateQueryContext<QueryMethods extends AggregateQueryMethodEntry[]> = {
97
+ [M in QueryMethods[number] as M["name"]]: M["handler"] extends (ctx: any, ...args: infer Args) => Promise<infer R> ? (...args: Args) => Promise<Simplify<R>> : never;
98
+ };
99
+ /**
100
+ * Static configuration stored on the aggregate constructor.
101
+ * Read by aggregateContextElement() to build the ArcContextElement.
102
+ */
103
+ export interface AggregateStaticConfig {
104
+ readonly __aggregateName: string;
105
+ readonly __aggregateId: ArcIdAny;
106
+ readonly __aggregateSchema: ArcObjectAny;
107
+ readonly __aggregateEvents: AggregateEventEntry[];
108
+ readonly __aggregateProtections: ViewProtection[];
109
+ readonly __aggregateMutateMethods: AggregateMutateMethodEntry[];
110
+ readonly __aggregateQueryMethods: AggregateQueryMethodEntry[];
111
+ readonly __aggregateCronMethods: AggregateCronMethodEntry[];
112
+ }
113
+ export {};
114
+ //# sourceMappingURL=aggregate-data.d.ts.map
@@ -0,0 +1,69 @@
1
+ /**
2
+ * ArcAggregateElement
3
+ *
4
+ * Implements ArcContextElement for an aggregate.
5
+ * Created by aggregateContextElement(Constructor).
6
+ *
7
+ * Looks like an ArcView to the rest of the system:
8
+ * - queryContext() → find/findOne returning class instances
9
+ * - mutateContext() → emit per registered event
10
+ * - getHandlers() / getElements() → for eventPublisher.registerViews()
11
+ * - databaseStoreSchema() → view table schema
12
+ */
13
+ import type { DatabaseStoreSchema } from "../../data-storage/database-store";
14
+ import type { ModelAdapters } from "../../model/model-adapters";
15
+ import { ArcContextElement } from "../context-element";
16
+ import type { ArcEventAny } from "../event/event";
17
+ import type { AggregateConstructorAny } from "./aggregate-builder";
18
+ import type { AggregateMutateMethodContext, AggregateQueryContext } from "./aggregate-data";
19
+ /**
20
+ * ArcAggregateElement — single context element for an aggregate.
21
+ *
22
+ * From the framework's perspective this behaves like a view:
23
+ * - eventPublisher.registerViews() accepts it (duck typing via getHandlers/getElements/schema)
24
+ * - queryContext provides find/findOne
25
+ * - mutateContext provides emit per event
26
+ */
27
+ export declare class ArcAggregateElement<Ctor extends AggregateConstructorAny> extends ArcContextElement<Ctor["__aggregateName"]> {
28
+ private readonly ctor;
29
+ /** Expose schema for eventPublisher view registration (duck typing) */
30
+ readonly schema: Ctor["__aggregateSchema"];
31
+ constructor(ctor: Ctor);
32
+ /**
33
+ * Returns event handlers keyed by event name.
34
+ * Same shape as ArcView.getHandlers().
35
+ */
36
+ getHandlers(): Record<string, (ctx: any, event: any) => Promise<void>>;
37
+ /**
38
+ * Returns event elements this aggregate listens to.
39
+ * Same shape as ArcView.getElements().
40
+ */
41
+ getElements(): ArcEventAny[];
42
+ /**
43
+ * queryContext — exposes declared queryMethod entries as callable functions.
44
+ *
45
+ * Each queryMethod handler receives { $query: { find, findOne }, $auth }
46
+ * where $query reads from the appropriate adapter (dataStorage, streamingCache, or queryWire).
47
+ * Returns aggregate class instances.
48
+ */
49
+ queryContext(adapters: ModelAdapters): AggregateQueryContext<Ctor["__aggregateQueryMethods"]>;
50
+ /**
51
+ * Build private query methods (find/findOne) that work across all adapter modes.
52
+ * Used internally by queryMethod handlers via ctx.$query.
53
+ */
54
+ private buildPrivateQuery;
55
+ private getAuth;
56
+ /**
57
+ * mutateContext — exposes declared mutateMethod entries as callable functions.
58
+ *
59
+ * Each mutateMethod becomes a named function: `(params) => Promise<any>`.
60
+ * The handler receives a context with emit per event + $auth + $query.
61
+ */
62
+ mutateContext(adapters: ModelAdapters): AggregateMutateMethodContext<Ctor["__aggregateMutateMethods"]>;
63
+ /**
64
+ * databaseStoreSchema — same as ArcView.
65
+ * Creates a table named after the aggregate with _id + schema fields.
66
+ */
67
+ databaseStoreSchema(): DatabaseStoreSchema;
68
+ }
69
+ //# sourceMappingURL=aggregate-element.d.ts.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Aggregate module
3
+ *
4
+ * Exports:
5
+ * - aggregate() — builder entry point
6
+ * - aggregateContextElement() — creates ArcContextElement from aggregate class
7
+ * - AggregateBase — base class for instances
8
+ * - Types
9
+ */
10
+ export { aggregate, AggregateBuilder } from "./aggregate-builder";
11
+ export type { AggregateConstructor, AggregateConstructorAny, AggregateData, AggregateInstanceCtx, } from "./aggregate-builder";
12
+ export { AggregateBase } from "./aggregate-base";
13
+ export { ArcAggregateElement } from "./aggregate-element";
14
+ export type { AggregateCronMethodEntry, AggregateEventEntry, AggregateEventHandler, AggregateMutateMethodContext, AggregateMutateMethodEntry, AggregateQueryContext, AggregateQueryMethodEntry, AggregateStaticConfig, } from "./aggregate-data";
15
+ export type { ArcEventPayload } from "../event/instance";
16
+ import type { AggregateConstructorAny } from "./aggregate-builder";
17
+ import { ArcAggregateElement } from "./aggregate-element";
18
+ /**
19
+ * Create an ArcContextElement from an aggregate class.
20
+ *
21
+ * @param ctor - Aggregate class (extends the result of aggregate().build())
22
+ * @returns ArcAggregateElement ready for context([])
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * const taskElement = aggregateContextElement(Task);
27
+ * const appContext = context([taskElement]);
28
+ * ```
29
+ */
30
+ export declare function aggregateContextElement<Ctor extends AggregateConstructorAny>(ctor: Ctor): ArcAggregateElement<Ctor>;
31
+ //# sourceMappingURL=index.d.ts.map