@lpdjs/firestore-repo-service 3.0.16 → 3.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{actor-context-DQZgWqj3.d.cts → actor-context-zNobm6nG.d.cts} +17 -2
- package/dist/{actor-context-DQZgWqj3.d.ts → actor-context-zNobm6nG.d.ts} +17 -2
- package/dist/{create-servers-BMpE8oAc.d.cts → create-servers-DydjOOOS.d.cts} +3 -3
- package/dist/{create-servers-DSXdPM6o.d.ts → create-servers-bMJVVjPj.d.ts} +3 -3
- package/dist/effects-BYvL8JUK.d.ts +158 -0
- package/dist/effects-DcM19dy4.d.cts +158 -0
- package/dist/history/index.cjs +1 -1
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +1 -1
- package/dist/history/index.d.ts +1 -1
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/index.cjs +95 -95
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +95 -95
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +139 -2
- package/dist/llms.txt +1 -1
- package/dist/servers/admin/index.d.cts +3 -3
- package/dist/servers/admin/index.d.ts +3 -3
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +6 -7
- package/dist/servers/crud/index.d.ts +6 -7
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.cjs +12 -12
- package/dist/servers/hono/index.cjs.map +1 -1
- package/dist/servers/hono/index.d.cts +4 -4
- package/dist/servers/hono/index.d.ts +4 -4
- package/dist/servers/hono/index.js +12 -12
- package/dist/servers/hono/index.js.map +1 -1
- package/dist/servers/index.cjs +101 -101
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +6 -7
- package/dist/servers/index.d.ts +6 -7
- package/dist/servers/index.js +101 -101
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/index.cjs +44 -44
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.js +44 -44
- package/dist/sync/index.js.map +1 -1
- package/dist/{types-CaCBG76r.d.ts → types-5Q7JDDba.d.ts} +332 -3
- package/dist/{types-w1rEqs0Z.d.ts → types-BJ6MAavL.d.ts} +1 -1
- package/dist/{types-mKcJozu4.d.cts → types-BYPdlGSL.d.cts} +332 -3
- package/dist/{types-BDTx8VPg.d.cts → types-XvVG8_9J.d.cts} +1 -1
- package/package.json +1 -1
- package/dist/openapi-CKTuB2Yz.d.ts +0 -70
- package/dist/openapi-Cb3QMU0Q.d.cts +0 -70
- package/dist/rules-DY5f_wPw.d.ts +0 -30
- package/dist/rules-DhNUzbIl.d.cts +0 -30
|
@@ -63,6 +63,15 @@ interface ActorResolverFieldConfig {
|
|
|
63
63
|
* either a custom resolver function or a declarative field-mapping config.
|
|
64
64
|
*/
|
|
65
65
|
type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;
|
|
66
|
+
/** Canonical default HTTP header name for change reason. */
|
|
67
|
+
declare const DEFAULT_HISTORY_REASON_HEADER = "X-History-Reason";
|
|
68
|
+
/** Canonical default HTTP header name for change comment. */
|
|
69
|
+
declare const DEFAULT_HISTORY_COMMENT_HEADER = "X-History-Comment";
|
|
70
|
+
/** Resolved history audit header names exposed by an `actorResolver`. */
|
|
71
|
+
interface ResolvedHistoryHeaderNames {
|
|
72
|
+
reasonHeader: string | false;
|
|
73
|
+
commentHeader: string | false;
|
|
74
|
+
}
|
|
66
75
|
/**
|
|
67
76
|
* Build an {@link ActorResolver} from a declarative field/header configuration.
|
|
68
77
|
*
|
|
@@ -77,6 +86,12 @@ type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;
|
|
|
77
86
|
* ```
|
|
78
87
|
*/
|
|
79
88
|
declare function createActorResolver(config?: ActorResolverFieldConfig): ActorResolver;
|
|
89
|
+
/**
|
|
90
|
+
* Inspect an {@link ActorResolverOption} (declarative config object, resolver
|
|
91
|
+
* created via {@link createActorResolver}, custom function, or `undefined`)
|
|
92
|
+
* and return the effective history audit header names for OpenAPI / CORS.
|
|
93
|
+
*/
|
|
94
|
+
declare function getActorResolverHeaders(option?: ActorResolverOption): ResolvedHistoryHeaderNames;
|
|
80
95
|
/**
|
|
81
96
|
* Default actor resolver compatible with Firebase JWT / `firebaseBearerAuth` /
|
|
82
97
|
* custom auth middlewares setting `c.get("user")` or `c.get("docsUser")`.
|
|
@@ -113,5 +128,5 @@ declare function withActor<T>(actor: HistoryActor, fn: () => T): T;
|
|
|
113
128
|
*/
|
|
114
129
|
declare function setRequestActorMeta(meta: Partial<HistoryActor>): boolean;
|
|
115
130
|
|
|
116
|
-
export { createActorContextMiddleware as c, createActorResolver as d, defaultActorResolver as e, getCurrentActor as g, setRequestActorMeta as s, withActor as w };
|
|
117
|
-
export type { ActorResolverOption as A, HistoryActor as H, ActorResolver as a, ActorResolverFieldConfig as b };
|
|
131
|
+
export { DEFAULT_HISTORY_COMMENT_HEADER as D, createActorContextMiddleware as c, createActorResolver as d, defaultActorResolver as e, DEFAULT_HISTORY_REASON_HEADER as f, getCurrentActor as g, getActorResolverHeaders as h, setRequestActorMeta as s, withActor as w };
|
|
132
|
+
export type { ActorResolverOption as A, HistoryActor as H, ResolvedHistoryHeaderNames as R, ActorResolver as a, ActorResolverFieldConfig as b };
|
|
@@ -63,6 +63,15 @@ interface ActorResolverFieldConfig {
|
|
|
63
63
|
* either a custom resolver function or a declarative field-mapping config.
|
|
64
64
|
*/
|
|
65
65
|
type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;
|
|
66
|
+
/** Canonical default HTTP header name for change reason. */
|
|
67
|
+
declare const DEFAULT_HISTORY_REASON_HEADER = "X-History-Reason";
|
|
68
|
+
/** Canonical default HTTP header name for change comment. */
|
|
69
|
+
declare const DEFAULT_HISTORY_COMMENT_HEADER = "X-History-Comment";
|
|
70
|
+
/** Resolved history audit header names exposed by an `actorResolver`. */
|
|
71
|
+
interface ResolvedHistoryHeaderNames {
|
|
72
|
+
reasonHeader: string | false;
|
|
73
|
+
commentHeader: string | false;
|
|
74
|
+
}
|
|
66
75
|
/**
|
|
67
76
|
* Build an {@link ActorResolver} from a declarative field/header configuration.
|
|
68
77
|
*
|
|
@@ -77,6 +86,12 @@ type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;
|
|
|
77
86
|
* ```
|
|
78
87
|
*/
|
|
79
88
|
declare function createActorResolver(config?: ActorResolverFieldConfig): ActorResolver;
|
|
89
|
+
/**
|
|
90
|
+
* Inspect an {@link ActorResolverOption} (declarative config object, resolver
|
|
91
|
+
* created via {@link createActorResolver}, custom function, or `undefined`)
|
|
92
|
+
* and return the effective history audit header names for OpenAPI / CORS.
|
|
93
|
+
*/
|
|
94
|
+
declare function getActorResolverHeaders(option?: ActorResolverOption): ResolvedHistoryHeaderNames;
|
|
80
95
|
/**
|
|
81
96
|
* Default actor resolver compatible with Firebase JWT / `firebaseBearerAuth` /
|
|
82
97
|
* custom auth middlewares setting `c.get("user")` or `c.get("docsUser")`.
|
|
@@ -113,5 +128,5 @@ declare function withActor<T>(actor: HistoryActor, fn: () => T): T;
|
|
|
113
128
|
*/
|
|
114
129
|
declare function setRequestActorMeta(meta: Partial<HistoryActor>): boolean;
|
|
115
130
|
|
|
116
|
-
export { createActorContextMiddleware as c, createActorResolver as d, defaultActorResolver as e, getCurrentActor as g, setRequestActorMeta as s, withActor as w };
|
|
117
|
-
export type { ActorResolverOption as A, HistoryActor as H, ActorResolver as a, ActorResolverFieldConfig as b };
|
|
131
|
+
export { DEFAULT_HISTORY_COMMENT_HEADER as D, createActorContextMiddleware as c, createActorResolver as d, defaultActorResolver as e, DEFAULT_HISTORY_REASON_HEADER as f, getCurrentActor as g, getActorResolverHeaders as h, setRequestActorMeta as s, withActor as w };
|
|
132
|
+
export type { ActorResolverOption as A, HistoryActor as H, ResolvedHistoryHeaderNames as R, ActorResolver as a, ActorResolverFieldConfig as b };
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { S as SyncQueue } from './queue-zw2B7GPx.cjs';
|
|
2
2
|
import { F as FirestoreSyncConfig, S as SyncEvent } from './types-D78FPJeF.cjs';
|
|
3
|
-
import { O as OpenAPIDocument } from './
|
|
3
|
+
import { O as OpenAPIDocument } from './effects-DcM19dy4.cjs';
|
|
4
4
|
import * as firebase_functions_v2_https from 'firebase-functions/v2/https';
|
|
5
5
|
import { onRequest, HttpsOptions } from 'firebase-functions/v2/https';
|
|
6
6
|
import { DocumentOptions } from 'firebase-functions/v2/firestore';
|
|
7
|
-
import { A as ActorResolverOption } from './actor-context-
|
|
7
|
+
import { A as ActorResolverOption } from './actor-context-zNobm6nG.cjs';
|
|
8
8
|
import { H as HistoryTriggersConfig } from './types-D6zvWzRt.cjs';
|
|
9
|
-
import { C as ConfiguredRepository,
|
|
9
|
+
import { C as ConfiguredRepository, r as CrudRepoConfig, a as CrudServerOptions } from './types-BYPdlGSL.cjs';
|
|
10
10
|
import { MeilisearchAdapterOptions, MeilisearchAdapter } from './sync/meilisearch.cjs';
|
|
11
11
|
import { AdminRepoConfig, AdminServerOptions } from './servers/admin/index.cjs';
|
|
12
12
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { S as SyncQueue } from './queue-NFod6hTT.js';
|
|
2
2
|
import { F as FirestoreSyncConfig, S as SyncEvent } from './types-B_FrzmO4.js';
|
|
3
|
-
import { O as OpenAPIDocument } from './
|
|
3
|
+
import { O as OpenAPIDocument } from './effects-BYvL8JUK.js';
|
|
4
4
|
import * as firebase_functions_v2_https from 'firebase-functions/v2/https';
|
|
5
5
|
import { onRequest, HttpsOptions } from 'firebase-functions/v2/https';
|
|
6
6
|
import { DocumentOptions } from 'firebase-functions/v2/firestore';
|
|
7
|
-
import { A as ActorResolverOption } from './actor-context-
|
|
7
|
+
import { A as ActorResolverOption } from './actor-context-zNobm6nG.js';
|
|
8
8
|
import { H as HistoryTriggersConfig } from './types-D6zvWzRt.js';
|
|
9
|
-
import { C as ConfiguredRepository,
|
|
9
|
+
import { C as ConfiguredRepository, r as CrudRepoConfig, a as CrudServerOptions } from './types-5Q7JDDba.js';
|
|
10
10
|
import { MeilisearchAdapterOptions, MeilisearchAdapter } from './sync/meilisearch.js';
|
|
11
11
|
import { AdminRepoConfig, AdminServerOptions } from './servers/admin/index.js';
|
|
12
12
|
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { t as CrudRepoRegistry, J as OpenAPISpecOptions, D as DeepDiffReturn, V as RulesMap, v as CrudUpdateRuleContext, G as MutationsMap, w as CrudWriteOperation, k as CrudBeforeCreateContext, l as CrudBeforeUpdateContext, y as EffectsMap, m as CrudEffectOperation, c as ApplyEffectsResult, j as CrudAfterUpdateContext, E as EffectExecutionResult } from './types-5Q7JDDba.js';
|
|
2
|
+
import { b as AuthUser } from './firebase-auth-nG3prKoj.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenAPI 3.1 specification generator for the CRUD server.
|
|
6
|
+
*
|
|
7
|
+
* Introspects each `CrudRepoEntry` and uses Zod 4's native `z.toJSONSchema()`
|
|
8
|
+
* to produce a fully typed OpenAPI document ready for Scalar UI or codegen.
|
|
9
|
+
*
|
|
10
|
+
* @module servers/crud/openapi
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Minimal subset of an OpenAPI 3.1 document we produce. */
|
|
14
|
+
interface OpenAPIDocument {
|
|
15
|
+
openapi: "3.1.0";
|
|
16
|
+
info: OpenAPIInfo;
|
|
17
|
+
servers?: {
|
|
18
|
+
url: string;
|
|
19
|
+
description?: string;
|
|
20
|
+
}[];
|
|
21
|
+
paths: Record<string, Record<string, OpenAPIOperation>>;
|
|
22
|
+
components: {
|
|
23
|
+
schemas: Record<string, Record<string, unknown>>;
|
|
24
|
+
securitySchemes?: Record<string, Record<string, unknown>>;
|
|
25
|
+
};
|
|
26
|
+
security?: Record<string, string[]>[];
|
|
27
|
+
tags?: {
|
|
28
|
+
name: string;
|
|
29
|
+
description?: string;
|
|
30
|
+
}[];
|
|
31
|
+
}
|
|
32
|
+
interface OpenAPIInfo {
|
|
33
|
+
title: string;
|
|
34
|
+
version: string;
|
|
35
|
+
description?: string;
|
|
36
|
+
}
|
|
37
|
+
interface OpenAPIOperation {
|
|
38
|
+
operationId: string;
|
|
39
|
+
summary: string;
|
|
40
|
+
tags: string[];
|
|
41
|
+
parameters?: Record<string, unknown>[];
|
|
42
|
+
requestBody?: Record<string, unknown>;
|
|
43
|
+
responses: Record<string, Record<string, unknown>>;
|
|
44
|
+
security?: Record<string, string[]>[];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Generate a full OpenAPI 3.1 specification from a `CrudRepoRegistry`.
|
|
48
|
+
*
|
|
49
|
+
* Uses Zod 4's native `z.toJSONSchema()` to convert each repo's schema
|
|
50
|
+
* into a JSON Schema component, then assembles paths for the standard
|
|
51
|
+
* CRUD endpoints.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* import { generateOpenAPISpec } from "@lpdjs/firestore-repo-service/servers/crud";
|
|
56
|
+
*
|
|
57
|
+
* const spec = generateOpenAPISpec(registry, "/api", {
|
|
58
|
+
* title: "My API",
|
|
59
|
+
* version: "1.0.0",
|
|
60
|
+
* servers: [{ url: "https://my-api.example.com" }],
|
|
61
|
+
* auth: "bearer",
|
|
62
|
+
* });
|
|
63
|
+
*
|
|
64
|
+
* // Write to file
|
|
65
|
+
* fs.writeFileSync("openapi.json", JSON.stringify(spec, null, 2));
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
declare function generateOpenAPISpec(registry: CrudRepoRegistry, basePath: string, options?: OpenAPISpecOptions): OpenAPIDocument;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Computes a typed diff between the existing document (`before`) and the incoming partial changes (`changesInput`).
|
|
72
|
+
* Only fields whose values have actually changed (via structural equality) are included in `changes`.
|
|
73
|
+
*/
|
|
74
|
+
declare function computeDeepDiff<T extends Record<string, unknown>>(before: T, changesInput: Partial<T>): DeepDiffReturn<T>;
|
|
75
|
+
/**
|
|
76
|
+
* Helper to define field-by-field before-rules with strong typing.
|
|
77
|
+
*/
|
|
78
|
+
declare function createRules<T>(rules: RulesMap<T>): RulesMap<T>;
|
|
79
|
+
/**
|
|
80
|
+
* Executes a map of field rules against a computed diff.
|
|
81
|
+
* Evaluates rules only for the keys that changed in `diff.changes`.
|
|
82
|
+
* Returns `{ allowed: true }` if all rules pass, or `{ allowed: false, reason: rule.description }` on the first failure.
|
|
83
|
+
*/
|
|
84
|
+
declare function applyRules<T>(diff: DeepDiffReturn<T>, rulesMap: RulesMap<T>, user?: AuthUser): Promise<{
|
|
85
|
+
allowed: boolean;
|
|
86
|
+
reason?: string;
|
|
87
|
+
}>;
|
|
88
|
+
/**
|
|
89
|
+
* Wraps a rules map into a standard `rules.update` handler for `createCrudServer`.
|
|
90
|
+
*/
|
|
91
|
+
declare function createBeforeRules<T>(rulesMap: RulesMap<T>): (ctx: CrudUpdateRuleContext<T>) => Promise<{
|
|
92
|
+
allowed: boolean;
|
|
93
|
+
reason?: string;
|
|
94
|
+
}>;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* @module servers/crud/mutations
|
|
98
|
+
*
|
|
99
|
+
* Pre-write mutation engine for CRUD payload normalization and server-derived
|
|
100
|
+
* field injection before persisting to Firestore.
|
|
101
|
+
*/
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Helper to define field-by-field (and wildcard `"*"`) pre-write mutations
|
|
105
|
+
* with strong typing.
|
|
106
|
+
*/
|
|
107
|
+
declare function createMutations<T>(mutations: MutationsMap<T>): MutationsMap<T>;
|
|
108
|
+
/**
|
|
109
|
+
* Executes a map of pre-write mutations against `body` / `diff`:
|
|
110
|
+
* 1. Runs per-field mutations for each key present in `diff.changes`.
|
|
111
|
+
* 2. Runs wildcard `"*"` mutations unconditionally after per-field mutations.
|
|
112
|
+
*/
|
|
113
|
+
declare function applyMutations<T>(body: Partial<T>, doc: T | null, diff: DeepDiffReturn<T>, mutationsMap: MutationsMap<T>, user?: AuthUser, operation?: CrudWriteOperation): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Wraps a {@link MutationsMap} into a `hooks.beforeUpdate` handler
|
|
116
|
+
* (analogous to `createBeforeRules`).
|
|
117
|
+
*/
|
|
118
|
+
declare function createBeforeUpdateMutations<T>(mutationsMap: MutationsMap<T>): (ctx: CrudBeforeUpdateContext<T>) => Promise<void>;
|
|
119
|
+
/**
|
|
120
|
+
* Wraps a {@link MutationsMap} into a `hooks.beforeCreate` handler
|
|
121
|
+
* (analogous to `createBeforeRules`).
|
|
122
|
+
*/
|
|
123
|
+
declare function createBeforeCreateMutations<T>(mutationsMap: MutationsMap<T>): (ctx: CrudBeforeCreateContext<T>) => Promise<void>;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* @module servers/crud/effects
|
|
127
|
+
*
|
|
128
|
+
* Reactive post-write effects engine aligned with `rules.ts` / `mutations.ts`.
|
|
129
|
+
* Evaluates field-level and wildcard `"*"` effect rules against a recomputed diff,
|
|
130
|
+
* captures per-rule errors without aborting sibling effects, and aggregates
|
|
131
|
+
* optional follow-up document patches (`changesNeeded`).
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Helper to define field-by-field (and wildcard `"*"`) post-write effects
|
|
136
|
+
* with strong typing.
|
|
137
|
+
*/
|
|
138
|
+
declare function createEffects<T, TContext>(effects: EffectsMap<T, TContext>): EffectsMap<T, TContext>;
|
|
139
|
+
/**
|
|
140
|
+
* Executes a map of reactive effects against a computed `diff`:
|
|
141
|
+
* 1. Runs per-field effects for every key in `diff.changes`.
|
|
142
|
+
* 2. Runs wildcard `"*"` effects after per-field effects.
|
|
143
|
+
*
|
|
144
|
+
* Each effect is isolated in a `try/catch` so one failure never prevents
|
|
145
|
+
* remaining effects from executing. Any `Partial<T>` patches returned by
|
|
146
|
+
* handlers are merged into `changesNeeded`.
|
|
147
|
+
*/
|
|
148
|
+
declare function applyEffects<T, TContext>(diff: DeepDiffReturn<T>, effectsMap: EffectsMap<T, TContext>, context: TContext, user?: AuthUser, operation?: CrudEffectOperation): Promise<ApplyEffectsResult<T>>;
|
|
149
|
+
/**
|
|
150
|
+
* Wraps an {@link EffectsMap} into a `hooks.afterUpdate` handler
|
|
151
|
+
* (analogous to `createBeforeRules`).
|
|
152
|
+
*/
|
|
153
|
+
declare function createAfterUpdateEffects<T, TContext>(effectsMap: EffectsMap<T, TContext>, buildContext: (ctx: CrudAfterUpdateContext<T>) => TContext, options?: {
|
|
154
|
+
onRuleError?: (result: EffectExecutionResult, ctx: CrudAfterUpdateContext<T>) => void | Promise<void>;
|
|
155
|
+
}): (ctx: CrudAfterUpdateContext<T>) => Promise<void | Partial<T>>;
|
|
156
|
+
|
|
157
|
+
export { applyEffects as a, applyMutations as b, applyRules as c, computeDeepDiff as d, createAfterUpdateEffects as e, createBeforeCreateMutations as f, createBeforeRules as g, createBeforeUpdateMutations as h, createEffects as i, createMutations as j, createRules as k, generateOpenAPISpec as l };
|
|
158
|
+
export type { OpenAPIDocument as O };
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { t as CrudRepoRegistry, J as OpenAPISpecOptions, D as DeepDiffReturn, V as RulesMap, v as CrudUpdateRuleContext, G as MutationsMap, w as CrudWriteOperation, k as CrudBeforeCreateContext, l as CrudBeforeUpdateContext, y as EffectsMap, m as CrudEffectOperation, c as ApplyEffectsResult, j as CrudAfterUpdateContext, E as EffectExecutionResult } from './types-BYPdlGSL.cjs';
|
|
2
|
+
import { b as AuthUser } from './firebase-auth-nG3prKoj.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenAPI 3.1 specification generator for the CRUD server.
|
|
6
|
+
*
|
|
7
|
+
* Introspects each `CrudRepoEntry` and uses Zod 4's native `z.toJSONSchema()`
|
|
8
|
+
* to produce a fully typed OpenAPI document ready for Scalar UI or codegen.
|
|
9
|
+
*
|
|
10
|
+
* @module servers/crud/openapi
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Minimal subset of an OpenAPI 3.1 document we produce. */
|
|
14
|
+
interface OpenAPIDocument {
|
|
15
|
+
openapi: "3.1.0";
|
|
16
|
+
info: OpenAPIInfo;
|
|
17
|
+
servers?: {
|
|
18
|
+
url: string;
|
|
19
|
+
description?: string;
|
|
20
|
+
}[];
|
|
21
|
+
paths: Record<string, Record<string, OpenAPIOperation>>;
|
|
22
|
+
components: {
|
|
23
|
+
schemas: Record<string, Record<string, unknown>>;
|
|
24
|
+
securitySchemes?: Record<string, Record<string, unknown>>;
|
|
25
|
+
};
|
|
26
|
+
security?: Record<string, string[]>[];
|
|
27
|
+
tags?: {
|
|
28
|
+
name: string;
|
|
29
|
+
description?: string;
|
|
30
|
+
}[];
|
|
31
|
+
}
|
|
32
|
+
interface OpenAPIInfo {
|
|
33
|
+
title: string;
|
|
34
|
+
version: string;
|
|
35
|
+
description?: string;
|
|
36
|
+
}
|
|
37
|
+
interface OpenAPIOperation {
|
|
38
|
+
operationId: string;
|
|
39
|
+
summary: string;
|
|
40
|
+
tags: string[];
|
|
41
|
+
parameters?: Record<string, unknown>[];
|
|
42
|
+
requestBody?: Record<string, unknown>;
|
|
43
|
+
responses: Record<string, Record<string, unknown>>;
|
|
44
|
+
security?: Record<string, string[]>[];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Generate a full OpenAPI 3.1 specification from a `CrudRepoRegistry`.
|
|
48
|
+
*
|
|
49
|
+
* Uses Zod 4's native `z.toJSONSchema()` to convert each repo's schema
|
|
50
|
+
* into a JSON Schema component, then assembles paths for the standard
|
|
51
|
+
* CRUD endpoints.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```ts
|
|
55
|
+
* import { generateOpenAPISpec } from "@lpdjs/firestore-repo-service/servers/crud";
|
|
56
|
+
*
|
|
57
|
+
* const spec = generateOpenAPISpec(registry, "/api", {
|
|
58
|
+
* title: "My API",
|
|
59
|
+
* version: "1.0.0",
|
|
60
|
+
* servers: [{ url: "https://my-api.example.com" }],
|
|
61
|
+
* auth: "bearer",
|
|
62
|
+
* });
|
|
63
|
+
*
|
|
64
|
+
* // Write to file
|
|
65
|
+
* fs.writeFileSync("openapi.json", JSON.stringify(spec, null, 2));
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
declare function generateOpenAPISpec(registry: CrudRepoRegistry, basePath: string, options?: OpenAPISpecOptions): OpenAPIDocument;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Computes a typed diff between the existing document (`before`) and the incoming partial changes (`changesInput`).
|
|
72
|
+
* Only fields whose values have actually changed (via structural equality) are included in `changes`.
|
|
73
|
+
*/
|
|
74
|
+
declare function computeDeepDiff<T extends Record<string, unknown>>(before: T, changesInput: Partial<T>): DeepDiffReturn<T>;
|
|
75
|
+
/**
|
|
76
|
+
* Helper to define field-by-field before-rules with strong typing.
|
|
77
|
+
*/
|
|
78
|
+
declare function createRules<T>(rules: RulesMap<T>): RulesMap<T>;
|
|
79
|
+
/**
|
|
80
|
+
* Executes a map of field rules against a computed diff.
|
|
81
|
+
* Evaluates rules only for the keys that changed in `diff.changes`.
|
|
82
|
+
* Returns `{ allowed: true }` if all rules pass, or `{ allowed: false, reason: rule.description }` on the first failure.
|
|
83
|
+
*/
|
|
84
|
+
declare function applyRules<T>(diff: DeepDiffReturn<T>, rulesMap: RulesMap<T>, user?: AuthUser): Promise<{
|
|
85
|
+
allowed: boolean;
|
|
86
|
+
reason?: string;
|
|
87
|
+
}>;
|
|
88
|
+
/**
|
|
89
|
+
* Wraps a rules map into a standard `rules.update` handler for `createCrudServer`.
|
|
90
|
+
*/
|
|
91
|
+
declare function createBeforeRules<T>(rulesMap: RulesMap<T>): (ctx: CrudUpdateRuleContext<T>) => Promise<{
|
|
92
|
+
allowed: boolean;
|
|
93
|
+
reason?: string;
|
|
94
|
+
}>;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* @module servers/crud/mutations
|
|
98
|
+
*
|
|
99
|
+
* Pre-write mutation engine for CRUD payload normalization and server-derived
|
|
100
|
+
* field injection before persisting to Firestore.
|
|
101
|
+
*/
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Helper to define field-by-field (and wildcard `"*"`) pre-write mutations
|
|
105
|
+
* with strong typing.
|
|
106
|
+
*/
|
|
107
|
+
declare function createMutations<T>(mutations: MutationsMap<T>): MutationsMap<T>;
|
|
108
|
+
/**
|
|
109
|
+
* Executes a map of pre-write mutations against `body` / `diff`:
|
|
110
|
+
* 1. Runs per-field mutations for each key present in `diff.changes`.
|
|
111
|
+
* 2. Runs wildcard `"*"` mutations unconditionally after per-field mutations.
|
|
112
|
+
*/
|
|
113
|
+
declare function applyMutations<T>(body: Partial<T>, doc: T | null, diff: DeepDiffReturn<T>, mutationsMap: MutationsMap<T>, user?: AuthUser, operation?: CrudWriteOperation): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* Wraps a {@link MutationsMap} into a `hooks.beforeUpdate` handler
|
|
116
|
+
* (analogous to `createBeforeRules`).
|
|
117
|
+
*/
|
|
118
|
+
declare function createBeforeUpdateMutations<T>(mutationsMap: MutationsMap<T>): (ctx: CrudBeforeUpdateContext<T>) => Promise<void>;
|
|
119
|
+
/**
|
|
120
|
+
* Wraps a {@link MutationsMap} into a `hooks.beforeCreate` handler
|
|
121
|
+
* (analogous to `createBeforeRules`).
|
|
122
|
+
*/
|
|
123
|
+
declare function createBeforeCreateMutations<T>(mutationsMap: MutationsMap<T>): (ctx: CrudBeforeCreateContext<T>) => Promise<void>;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* @module servers/crud/effects
|
|
127
|
+
*
|
|
128
|
+
* Reactive post-write effects engine aligned with `rules.ts` / `mutations.ts`.
|
|
129
|
+
* Evaluates field-level and wildcard `"*"` effect rules against a recomputed diff,
|
|
130
|
+
* captures per-rule errors without aborting sibling effects, and aggregates
|
|
131
|
+
* optional follow-up document patches (`changesNeeded`).
|
|
132
|
+
*/
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Helper to define field-by-field (and wildcard `"*"`) post-write effects
|
|
136
|
+
* with strong typing.
|
|
137
|
+
*/
|
|
138
|
+
declare function createEffects<T, TContext>(effects: EffectsMap<T, TContext>): EffectsMap<T, TContext>;
|
|
139
|
+
/**
|
|
140
|
+
* Executes a map of reactive effects against a computed `diff`:
|
|
141
|
+
* 1. Runs per-field effects for every key in `diff.changes`.
|
|
142
|
+
* 2. Runs wildcard `"*"` effects after per-field effects.
|
|
143
|
+
*
|
|
144
|
+
* Each effect is isolated in a `try/catch` so one failure never prevents
|
|
145
|
+
* remaining effects from executing. Any `Partial<T>` patches returned by
|
|
146
|
+
* handlers are merged into `changesNeeded`.
|
|
147
|
+
*/
|
|
148
|
+
declare function applyEffects<T, TContext>(diff: DeepDiffReturn<T>, effectsMap: EffectsMap<T, TContext>, context: TContext, user?: AuthUser, operation?: CrudEffectOperation): Promise<ApplyEffectsResult<T>>;
|
|
149
|
+
/**
|
|
150
|
+
* Wraps an {@link EffectsMap} into a `hooks.afterUpdate` handler
|
|
151
|
+
* (analogous to `createBeforeRules`).
|
|
152
|
+
*/
|
|
153
|
+
declare function createAfterUpdateEffects<T, TContext>(effectsMap: EffectsMap<T, TContext>, buildContext: (ctx: CrudAfterUpdateContext<T>) => TContext, options?: {
|
|
154
|
+
onRuleError?: (result: EffectExecutionResult, ctx: CrudAfterUpdateContext<T>) => void | Promise<void>;
|
|
155
|
+
}): (ctx: CrudAfterUpdateContext<T>) => Promise<void | Partial<T>>;
|
|
156
|
+
|
|
157
|
+
export { applyEffects as a, applyMutations as b, applyRules as c, computeDeepDiff as d, createAfterUpdateEffects as e, createBeforeCreateMutations as f, createBeforeRules as g, createBeforeUpdateMutations as h, createEffects as i, createMutations as j, createRules as k, generateOpenAPISpec as l };
|
|
158
|
+
export type { OpenAPIDocument as O };
|
package/dist/history/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var crypto=require('crypto'),firestore=require('firebase-admin/firestore'),async_hooks=require('async_hooks');function te(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function N(e,t="docId",r=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let n=e.split("/").map(a=>a.trim()).filter(Boolean);if(n.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(n.length===1){let a=n[0];return {rawPath:e,collectionId:a,collectionPath:a,parentKeys:[],documentPathTemplate:r?null:`${a}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let i=n.length%2===0,c=i?n.slice(0,-1):n,u=c[c.length-1],l=c.join("/"),T=c.slice(0,-1).map(te).filter(a=>a!==null),p=i?n.join("/"):`${l}/{${t}}`;return {rawPath:e,collectionId:u,collectionPath:l,parentKeys:T,documentPathTemplate:p,hasTemplate:true}}function R(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof firestore.Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function P(e,t,r=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(r.get(e)===t)return true;r.set(e,t);for(let n=0;n<e.length;n++)if(!P(e[n],t[n],r))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(r.get(e)===t)return true;r.set(e,t);let n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return false;for(let c of n)if(!Object.prototype.hasOwnProperty.call(t,c)||!P(e[c],t[c],r))return false;return true}return false}function M(e,t,r={}){let n=new Set([...r.exclude??[],...r.metaFields??[],...r.systemKeys??[]]),i=r.include?new Set(r.include):null,c=e??{},u=t??{},l=new Set([...Object.keys(c),...Object.keys(u)]),y={};for(let T of l){if(n.has(T)||i&&!i.has(T))continue;let p=c[T],a=u[T];P(p,a)||(y[T]={oldValue:p===void 0?null:p,newValue:a===void 0?null:a,type:{old:R(p),new:R(a)}});}return y}var K=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),L=globalThis,v=L[K]??(L[K]=new async_hooks.AsyncLocalStorage);function re(e,t){if(!t.includes("."))return e[t];let r=e;for(let n of t.split(".")){if(!r||typeof r!="object")return;r=r[n];}return r}function q(e,t){for(let r of t){let n=re(e,r);if(typeof n=="string"&&n.length>0)return n;if(typeof n=="number")return String(n)}return null}function z(e,t){if(t===false)return;let r=e?.req?.header;if(typeof r!="function")return;let n=r.call(e.req,t);return typeof n=="string"&&n.length>0?n:void 0}function _(e={}){let t=e.contextKeys??["user","docsUser"],r=e.userIdFields??["uid","id","sub"],n=e.userEmailFields??["email"],i=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,c=e.commentHeader===void 0?"x-history-comment":e.commentHeader,u=e.extras;return l=>{let y=null,T=l?.get;if(typeof T=="function")for(let o of t){let s=T.call(l,o);if(s&&typeof s=="object"){y=s;break}}let p=z(l,i),a=z(l,c),g=u?u(l,y):void 0;return y?{userId:q(y,r),userEmail:q(y,n),...p!==void 0?{reason:p}:{},...a!==void 0?{comment:a}:{},...g?{extras:g}:{}}:p===void 0&&a===void 0&&!g?null:{...p!==void 0?{reason:p}:{},...a!==void 0?{comment:a}:{},...g?{extras:g}:{}}}}var Y=_();function oe(e){if(e)return typeof e=="function"?e:_(e)}function se(e){let t=oe(e);return async(r,n)=>{await v.run({c:r,resolver:t},async()=>{await n();});}}function D(){let e=v.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??Y)(e.c);}catch{t=null;}if(!t&&!e.override)return null;let r={...t??{}};return e.override&&(e.override.userId!==void 0&&(r.userId=e.override.userId),e.override.userEmail!==void 0&&(r.userEmail=e.override.userEmail),e.override.reason!==void 0&&(r.reason=e.override.reason),e.override.comment!==void 0&&(r.comment=e.override.comment),e.override.extras!==void 0&&(r.extras={...t?.extras??{},...e.override.extras})),r}function ie(e,t){return v.run({override:{...e}},t)}function ae(e){let t=v.getStore();if(!t)return false;let r=t.override??{},n={...r,...e};return (r.extras||e.extras)&&(n.extras={...r.extras??{},...e.extras??{}}),t.override=n,true}var U="_historyMeta";function A(e){if(!e?.enabled||e.shadow===false||e.meta&&e.shadow===void 0)return null;let t=e.shadow,r=typeof t=="string"&&t.trim().length>0?t.trim():typeof t=="object"&&t!==null&&typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():U,n=typeof t=="object"&&t!==null?t.fields:void 0;return {key:r,fields:{userId:n?.userId??"userId",userEmail:n?.userEmail??"userEmail",reason:n?.reason??"reason",comment:n?.comment??"comment",extras:n?.extras??"extras"}}}function le(e){return A(e)?.key??null}function ce(e){let t=A(e);return t?[t.key]:[]}function ue(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let r=e;if(!(t in r))return e;let{[t]:n,...i}=r;return i}function de(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let r=A(t);if(!r)return;let n=D(),i=t.fallbackActor??{},c=n?.userId!==void 0?n.userId:i.userId??null,u=n?.userEmail!==void 0?n.userEmail:i.userEmail??null,l=n?.reason??null,y=n?.comment??null,T=n?.extras&&Object.keys(n.extras).length>0?n.extras:null,p={},{fields:a}=r;a.userId!==false&&(p[a.userId]=c),a.userEmail!==false&&(p[a.userEmail]=u),a.reason!==false&&(p[a.reason]=l),a.comment!==false&&(p[a.comment]=y),a.extras!==false&&(p[a.extras]=T),e[r.key]=p;}var ye=7e5;function C(e){let t=e.ttlOverride??e.config.ttl,n={schemaVersion:2,historyDocId:crypto.randomUUID(),historyToObjectId:e.entityId,historySetAt:firestore.Timestamp.now(),operation:e.operation,meta:e.meta,...e.custom?{custom:e.custom}:{},changes:e.changes};t&&(n.expiresAt=firestore.Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let i=c=>{try{return Buffer.byteLength(JSON.stringify(c,(u,l)=>l instanceof firestore.Timestamp?l.toMillis():l),"utf8")}catch{return 0}};if(i(n.changes)>ye){let c={};for(let[u,l]of Object.entries(n.changes)){let y=i(l.oldValue),T=i(l.newValue);c[u]={oldValue:y>5e4?"[truncated]":l.oldValue,newValue:T>5e4?"[truncated]":l.newValue,type:l.type};}n.changes=c,n._truncated=true;}return n}async function I(e,t,r,n){let i=t;return r.onBeforeWrite&&(i=await r.onBeforeWrite(t,n)),i?(await e.doc(i.historyDocId).set(i),{written:true,entry:i}):{written:false,reason:"dropped-by-onBeforeWrite"}}function F(e,t){let r=e??{},n={},i=A(t);if(i){let a=r[i.key];if(a&&typeof a=="object"&&!Array.isArray(a)){let g=a,o=x=>{if(x===false||!(x in g))return;let f=g[x];return f==null?null:String(f)},s=o(i.fields.userId);s!==void 0&&(n.userId=s);let h=o(i.fields.userEmail);h!==void 0&&(n.userEmail=h);let d=o(i.fields.reason);d!==void 0&&(n.reason=d);let H=o(i.fields.comment);if(H!==void 0&&(n.comment=H),i.fields.extras!==false){let x=g[i.fields.extras];x&&typeof x=="object"&&!Array.isArray(x)&&Object.keys(x).length>0&&(n.extras=x);}}return n}let c=t.meta;if(!c)return n;let u=a=>{if(!a)return;let g=r[a];return g===void 0||g===null?null:String(g)},l=u(c.userId);l!==void 0&&(n.userId=l);let y=u(c.userEmail);y!==void 0&&(n.userEmail=y);let T=u(c.reason);T!==void 0&&(n.reason=T);let p=u(c.comment);if(p!==void 0&&(n.comment=p),c.extras&&c.extras.length>0){let a={},g=false;for(let o of c.extras)o in r&&(a[o]=r[o],g=true);g&&(n.extras=a);}return n}function S(e){let t=[],r=A(e);r&&t.push(r.key);let n=e.meta;return n&&(n.userId&&t.push(n.userId),n.userEmail&&t.push(n.userEmail),n.reason&&t.push(n.reason),n.comment&&t.push(n.comment),n.extras&&t.push(...n.extras)),t}var me="history";function pe(e){let t=e&&typeof e.history=="object"&&e.history!==null?e.history:void 0,r=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(c=>typeof c=="string"),n=typeof e?.path=="string"?e.path:null,i=n?N(n,e?.documentKey??"docId"):null;return {historyConfig:t,systemKeys:r,isGroup:!!e?.isGroup,collectionPath:i?i.collectionPath:null,documentPathTemplate:i&&(!e?.isGroup||i.collectionPath.includes("/"))?i.documentPathTemplate:null}}function ge(e){let t=e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),r=e._collectionPath??e.ref?.path??null,n=typeof e._documentPathTemplate=="string"?e._documentPathTemplate:null;return {historyConfig:t,systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:r,documentPathTemplate:n&&(!e._isGroup||r&&r.includes("/"))?n:null}}function he(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function He(e,t){let{onDocumentWritten:r}=t.deps,n={},i=e?.rawMapping,c=i?Object.entries(i).map(([u,l])=>[u,pe(l)]):Object.entries(e).map(([u,l])=>[u,ge(l)]);for(let[u,l]of c){let y=l.historyConfig;if(!y?.enabled)continue;let T=y.subcollection??me,p=y.ttl??t.defaults?.ttl,a=t.repos?.[u],g;if(l.isGroup){let f=a?.triggerPath??l.documentPathTemplate;if(!f){console.warn(`[HistoryTriggers] Skipping collection-group repo "${u}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}g=f;}else g=a?.triggerPath??l.documentPathTemplate??he(u,l.collectionPath);if(!g)continue;let o=l.systemKeys,s=o[0]??"docId",h=S(y),d={...t.triggerOptions,...y?.triggerOptions,...a?.triggerOptions},H=Object.keys(d).length>0,x=async f=>{try{let w=f.data?.before?.data(),m=f.data?.after?.data(),k;if(!w&&m)k="create";else if(w&&!m)k="delete";else if(w&&m)k="update";else return;let O=String(m?.[s]??w?.[s]??f.params?.docId??f.data?.after?.id??f.data?.before?.id??"");if(!O)return;let V=M(w??{},m??{},{include:y.include,exclude:y.exclude,metaFields:h,systemKeys:o});if(k==="update"&&Object.keys(V).length===0)return;let b=F(m??w??null,y),Z=C({entityId:O,operation:k,changes:V,meta:b,config:y,ttlOverride:p}),$=f.data?.after?.ref??f.data?.before?.ref;if(!$)return;let ee=$.collection(T);await I(ee,Z,y,{repoName:u,docId:O,before:w??null,after:m??null});}catch(w){console.error(`[HistoryTriggers] Failed to record history for "${u}":`,w);}};n[`${u}_onHistory`]=r(H?{document:g,...d}:g,x);}return n}var X=5;function Te(e){return e.schemaVersion===2}function J(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function xe(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},...e.custom?{custom:e.custom}:{},changes:e.changes??{}}}function we(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let r=e.extraHistoryDetails??null;r&&(r.reason!==void 0&&(t.reason=r.reason??null),r.comment!==void 0&&(t.comment=r.comment??null));let n={},i=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[c,u]of Object.entries(e.historyDetails))n[c]=u,i=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[c,u]of Object.entries(e.extraContentKeys))n[`content.${c}`]=u,i=true;return i&&(t.extras=n),t}function be(e){let t=e.changes?.oldValue??null,r=e.changes?.newValue??null,n=e.types?.oldValue,i=e.types?.newValue;return {oldValue:t,newValue:r,type:{old:n?J(n):R(t),new:i?J(i):R(r)}}}function ke(e){let t=be(e),r=we(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:r,changes:{[e.field]:t}}}function Oe(e,t,r){return Math.abs(e.toMillis()-t.toMillis())<=r}function Ae(e,t){return (e.userId??null)===(t.userId??null)}function W(e,t={}){let r=t.groupToleranceMs??X,n=[];for(let i of e){if(Te(i)){n.push(xe(i));continue}let u=ke(i),l=n[n.length-1];l&&l.schemaVersion===1&&Oe(l.historySetAt,u.historySetAt,r)&&Ae(l.meta,u.meta)?Object.assign(l.changes,u.changes):n.push(u);}return n}var Re="history",De=50;function G(e,t,r){return e(...r).collection(t)}function Q(e){return String(e[e.length-1]??"")}function Ce(e,t,r,n){if(!n?.enabled)return null;let i=n.subcollection??Re;async function c(...o){let s={},h=o,d=o[o.length-1];d!==null&&typeof d=="object"&&!(d instanceof firestore.Timestamp)&&("limit"in d||"cursor"in d||"direction"in d)&&(s=d,h=o.slice(0,-1));let H=G(e,i,h),x=s.direction??"desc",f=H.orderBy("historySetAt",x);return s.cursor&&(f=f.startAfter(s.cursor)),s.limit&&s.limit>0&&(f=f.limit(s.limit)),(await f.get()).docs.map(m=>({id:m.id,data:m.data()}))}async function u(...o){let s={},h=o,d=o[o.length-1];d!==null&&typeof d=="object"&&!(d instanceof firestore.Timestamp)&&("limit"in d||"cursor"in d||"direction"in d||"fields"in d||"operations"in d)&&(s=d,h=o.slice(0,-1));let H=s.limit??De,x=Math.max(H,Math.min(H*8,500)),f=await c(...h,{limit:x,cursor:s.cursor,direction:s.direction??"desc"}),w=W(f.map(m=>m.data));if(s.fields&&s.fields.length>0){let m=new Set(s.fields);w=w.filter(k=>Object.keys(k.changes).some(O=>m.has(O)));}if(s.operations&&s.operations.length>0){let m=new Set(s.operations);w=w.filter(k=>m.has(k.operation));}return w.slice(0,H)}async function l(...o){let s=o[o.length-1],h={},d,H;return s!==null&&typeof s=="object"&&!(s instanceof firestore.Timestamp)?(h=s,d=o[o.length-2],H=o.slice(0,-2)):(d=s,H=o.slice(0,-1)),u(...H,{...h,fields:[d]})}async function y(...o){let s=o[o.length-1],h={},d,H;return s!==null&&typeof s=="object"&&!(s instanceof firestore.Timestamp)?(h=s,d=o[o.length-2],H=o.slice(0,-2)):(d=s,H=o.slice(0,-1)),u(...H,{...h,operations:[d]})}function T(o){let s={title:o.title,display:o.display??true};return o.description!==void 0&&(s.description=o.description),o.key!==void 0&&(s.key=o.key),o.data!==void 0&&(s.data=o.data),s}function p(){let o=D(),s=n.fallbackActor??{},h=o?.userId!==void 0?o.userId:s.userId??null,d=o?.userEmail!==void 0?o.userEmail:s.userEmail??null;return {userId:h,userEmail:d,...o?.reason!==void 0?{reason:o.reason}:{},...o?.comment!==void 0?{comment:o.comment}:{},...o?.extras&&Object.keys(o.extras).length>0?{extras:o.extras}:{}}}async function a(...o){let s=o[o.length-1],h=o.slice(0,-1),d=Q(h),H=M(s.before??{},s.after??{},{include:n.include,exclude:n.exclude,metaFields:S(n),systemKeys:t});if(s.operation==="update"&&Object.keys(H).length===0)return null;let x=F(s.after??s.before??null,n),f=D(),m={...f?{...f.userId!==void 0?{userId:f.userId}:{},...f.userEmail!==void 0?{userEmail:f.userEmail}:{},...f.reason!==void 0?{reason:f.reason}:{},...f.comment!==void 0?{comment:f.comment}:{},...f.extras&&Object.keys(f.extras).length>0?{extras:f.extras}:{}}:{},...x,...s.meta??{}},k=s.custom?T(s.custom):void 0,O=C({entityId:d,operation:s.operation,changes:H,meta:m,custom:k,config:n}),V=G(e,i,h),b=await I(V,O,n,{repoName:r,docId:d,before:s.before??null,after:s.after??null});return !b.written||!b.entry?null:{historyDocId:b.entry.historyDocId,historyToObjectId:b.entry.historyToObjectId,historySetAt:b.entry.historySetAt,schemaVersion:2,operation:b.entry.operation,meta:b.entry.meta,...b.entry.custom?{custom:b.entry.custom}:{},changes:b.entry.changes}}async function g(...o){let s=o[o.length-1],h=o.slice(0,-1),d=Q(h),H=T(s),x={...p(),...s.meta??{}},f=C({entityId:d,operation:"custom",changes:{},meta:x,custom:H,config:n}),w=G(e,i,h),m=await I(w,f,n,{repoName:r,docId:d,before:null,after:null});return !m.written||!m.entry?null:{historyDocId:m.entry.historyDocId,historyToObjectId:m.entry.historyToObjectId,historySetAt:m.entry.historySetAt,schemaVersion:2,operation:m.entry.operation,meta:m.entry.meta,...m.entry.custom?{custom:m.entry.custom}:{},changes:m.entry.changes}}return {list:u,raw:c,byField:l,byOperation:y,recordManual:a,recordCustom:g}}exports.DEFAULT_GROUP_TOLERANCE_MS=X;exports.DEFAULT_HISTORY_SHADOW_KEY=U;exports.buildHistoryEntry=C;exports.computeDiff=M;exports.createActorContextMiddleware=se;exports.createActorResolver=_;exports.createHistoryMethods=Ce;exports.createHistoryTriggers=He;exports.defaultActorResolver=Y;exports.extractMeta=F;exports.getCurrentActor=D;exports.getHistoryIdentityKeys=ce;exports.getHistoryShadowKey=le;exports.injectHistoryMeta=de;exports.metaFieldsOf=S;exports.normalizeHistoryDocs=W;exports.resolveShadowConfig=A;exports.setRequestActorMeta=ae;exports.stripHistoryShadowField=ue;exports.valueType=R;exports.valuesEqual=P;exports.withActor=ie;exports.writeHistoryEntry=I;//# sourceMappingURL=index.cjs.map
|
|
1
|
+
'use strict';var crypto=require('crypto'),firestore=require('firebase-admin/firestore'),async_hooks=require('async_hooks');function te(e){return e.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function $(e,t="docId",n=false){if(typeof e!="string"||!e.trim())return {rawPath:e??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let r=e.split("/").map(a=>a.trim()).filter(Boolean);if(r.length===0)return {rawPath:e,collectionId:e,collectionPath:e,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(r.length===1){let a=r[0];return {rawPath:e,collectionId:a,collectionPath:a,parentKeys:[],documentPathTemplate:n?null:`${a}/{${t}}`,hasTemplate:e.includes("{")&&e.includes("}")}}let i=r.length%2===0,l=i?r.slice(0,-1):r,u=l[l.length-1],d=l.join("/"),H=l.slice(0,-1).map(te).filter(a=>a!==null),h=i?r.join("/"):`${d}/{${t}}`;return {rawPath:e,collectionId:u,collectionPath:d,parentKeys:H,documentPathTemplate:h,hasTemplate:true}}function A(e){if(e===null)return "null";if(e===void 0)return "undefined";if(e instanceof firestore.Timestamp)return "timestamp";if(e instanceof Date)return "date";if(Array.isArray(e))return "array";let t=typeof e;return t==="string"||t==="number"||t==="boolean"?t:"object"}function V(e,t,n=new WeakMap){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(e instanceof firestore.Timestamp&&t instanceof firestore.Timestamp)return e.isEqual(t);if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return false;if(n.get(e)===t)return true;n.set(e,t);for(let r=0;r<e.length;r++)if(!V(e[r],t[r],n))return false;return true}if(typeof e=="object"&&typeof t=="object"){if(e instanceof Date||t instanceof Date||e instanceof firestore.Timestamp||t instanceof firestore.Timestamp)return false;if(n.get(e)===t)return true;n.set(e,t);let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return false;for(let l of r)if(!Object.prototype.hasOwnProperty.call(t,l)||!V(e[l],t[l],n))return false;return true}return false}function M(e,t,n={}){let r=new Set([...n.exclude??[],...n.metaFields??[],...n.systemKeys??[]]),i=n.include?new Set(n.include):null,l=e??{},u=t??{},d=new Set([...Object.keys(l),...Object.keys(u)]),g={};for(let H of d){if(r.has(H)||i&&!i.has(H))continue;let h=l[H],a=u[H];V(h,a)||(g[H]={oldValue:h===void 0?null:h,newValue:a===void 0?null:a,type:{old:A(h),new:A(a)}});}return g}var ne="X-History-Reason",oe="X-History-Comment",se=Symbol.for("@lpdjs/firestore-repo-service:actorResolverHeaders"),_=Symbol.for("@lpdjs/firestore-repo-service:actorContext"),K=globalThis,P=K[_]??(K[_]=new async_hooks.AsyncLocalStorage);function ie(e,t){if(!t.includes("."))return e[t];let n=e;for(let r of t.split(".")){if(!n||typeof n!="object")return;n=n[r];}return n}function q(e,t){for(let n of t){let r=ie(e,n);if(typeof r=="string"&&r.length>0)return r;if(typeof r=="number")return String(r)}return null}function Y(e,t){if(t===false)return;let n=e?.req?.header;if(typeof n!="function")return;let r=n.call(e.req,t);return typeof r=="string"&&r.length>0?r:void 0}function L(e={}){let t=e.contextKeys??["user","docsUser"],n=e.userIdFields??["uid","id","sub"],r=e.userEmailFields??["email"],i=e.reasonHeader===void 0?"x-history-reason":e.reasonHeader,l=e.commentHeader===void 0?"x-history-comment":e.commentHeader,u=e.reasonHeader===void 0?ne:e.reasonHeader,d=e.commentHeader===void 0?oe:e.commentHeader,g=e.extras,H=h=>{let a=null,T=h?.get;if(typeof T=="function")for(let c of t){let p=T.call(h,c);if(p&&typeof p=="object"){a=p;break}}let o=Y(h,i),s=Y(h,l),y=g?g(h,a):void 0;return a?{userId:q(a,n),userEmail:q(a,r),...o!==void 0?{reason:o}:{},...s!==void 0?{comment:s}:{},...y?{extras:y}:{}}:o===void 0&&s===void 0&&!y?null:{...o!==void 0?{reason:o}:{},...s!==void 0?{comment:s}:{},...y?{extras:y}:{}}};return Object.defineProperty(H,se,{value:{reasonHeader:u,commentHeader:d},enumerable:false,configurable:false}),H}var z=L();function ae(e){if(e)return typeof e=="function"?e:L(e)}function le(e){let t=ae(e);return async(n,r)=>{await P.run({c:n,resolver:t},async()=>{await r();});}}function D(){let e=P.getStore();if(!e)return null;let t=null;if(e.c)try{t=(e.resolver??z)(e.c);}catch{t=null;}if(!t&&!e.override)return null;let n={...t??{}};return e.override&&(e.override.userId!==void 0&&(n.userId=e.override.userId),e.override.userEmail!==void 0&&(n.userEmail=e.override.userEmail),e.override.reason!==void 0&&(n.reason=e.override.reason),e.override.comment!==void 0&&(n.comment=e.override.comment),e.override.extras!==void 0&&(n.extras={...t?.extras??{},...e.override.extras})),n}function ce(e,t){return P.run({override:{...e}},t)}function ue(e){let t=P.getStore();if(!t)return false;let n=t.override??{},r={...n,...e};return (n.extras||e.extras)&&(r.extras={...n.extras??{},...e.extras??{}}),t.override=r,true}var U="_historyMeta";function k(e){if(!e?.enabled||e.shadow===false||e.meta&&e.shadow===void 0)return null;let t=e.shadow,n=typeof t=="string"&&t.trim().length>0?t.trim():typeof t=="object"&&t!==null&&typeof t.key=="string"&&t.key.trim().length>0?t.key.trim():U,r=typeof t=="object"&&t!==null?t.fields:void 0;return {key:n,fields:{userId:r?.userId??"userId",userEmail:r?.userEmail??"userEmail",reason:r?.reason??"reason",comment:r?.comment??"comment",extras:r?.extras??"extras"}}}function de(e){return k(e)?.key??null}function fe(e){let t=k(e);return t?[t.key]:[]}function ye(e,t){if(!t||!e||typeof e!="object"||Array.isArray(e))return e;let n=e;if(!(t in n))return e;let{[t]:r,...i}=n;return i}function me(e,t){if(!t?.enabled||t.autoInjectMeta===false)return;let n=k(t);if(!n)return;let r=D(),i=t.fallbackActor??{},l=r?.userId!==void 0?r.userId:i.userId??null,u=r?.userEmail!==void 0?r.userEmail:i.userEmail??null,d=r?.reason??null,g=r?.comment??null,H=r?.extras&&Object.keys(r.extras).length>0?r.extras:null,h={},{fields:a}=n;a.userId!==false&&(h[a.userId]=l),a.userEmail!==false&&(h[a.userEmail]=u),a.reason!==false&&(h[a.reason]=d),a.comment!==false&&(h[a.comment]=g),a.extras!==false&&(h[a.extras]=H),e[n.key]=h;}var ge=7e5;function C(e){let t=e.ttlOverride??e.config.ttl,r={schemaVersion:2,historyDocId:crypto.randomUUID(),historyToObjectId:e.entityId,historySetAt:firestore.Timestamp.now(),operation:e.operation,meta:e.meta,...e.custom?{custom:e.custom}:{},changes:e.changes};t&&(r.expiresAt=firestore.Timestamp.fromMillis(Date.now()+t.days*24*60*60*1e3));let i=l=>{try{return Buffer.byteLength(JSON.stringify(l,(u,d)=>d instanceof firestore.Timestamp?d.toMillis():d),"utf8")}catch{return 0}};if(i(r.changes)>ge){let l={};for(let[u,d]of Object.entries(r.changes)){let g=i(d.oldValue),H=i(d.newValue);l[u]={oldValue:g>5e4?"[truncated]":d.oldValue,newValue:H>5e4?"[truncated]":d.newValue,type:d.type};}r.changes=l,r._truncated=true;}return r}async function E(e,t,n,r){let i=t;return n.onBeforeWrite&&(i=await n.onBeforeWrite(t,r)),i?(await e.doc(i.historyDocId).set(i),{written:true,entry:i}):{written:false,reason:"dropped-by-onBeforeWrite"}}function F(e,t){let n=e??{},r={},i=k(t);if(i){let a=n[i.key];if(a&&typeof a=="object"&&!Array.isArray(a)){let T=a,o=x=>{if(x===false||!(x in T))return;let f=T[x];return f==null?null:String(f)},s=o(i.fields.userId);s!==void 0&&(r.userId=s);let y=o(i.fields.userEmail);y!==void 0&&(r.userEmail=y);let c=o(i.fields.reason);c!==void 0&&(r.reason=c);let p=o(i.fields.comment);if(p!==void 0&&(r.comment=p),i.fields.extras!==false){let x=T[i.fields.extras];x&&typeof x=="object"&&!Array.isArray(x)&&Object.keys(x).length>0&&(r.extras=x);}}return r}let l=t.meta;if(!l)return r;let u=a=>{if(!a)return;let T=n[a];return T===void 0||T===null?null:String(T)},d=u(l.userId);d!==void 0&&(r.userId=d);let g=u(l.userEmail);g!==void 0&&(r.userEmail=g);let H=u(l.reason);H!==void 0&&(r.reason=H);let h=u(l.comment);if(h!==void 0&&(r.comment=h),l.extras&&l.extras.length>0){let a={},T=false;for(let o of l.extras)o in n&&(a[o]=n[o],T=true);T&&(r.extras=a);}return r}function S(e){let t=[],n=k(e);n&&t.push(n.key);let r=e.meta;return r&&(r.userId&&t.push(r.userId),r.userEmail&&t.push(r.userEmail),r.reason&&t.push(r.reason),r.comment&&t.push(r.comment),r.extras&&t.push(...r.extras)),t}var he="history";function He(e){let t=e&&typeof e.history=="object"&&e.history!==null?e.history:void 0,n=[e?.documentKey,e?.pathKey,e?.createdKey,e?.updatedKey].filter(l=>typeof l=="string"),r=typeof e?.path=="string"?e.path:null,i=r?$(r,e?.documentKey??"docId"):null;return {historyConfig:t,systemKeys:n,isGroup:!!e?.isGroup,collectionPath:i?i.collectionPath:null,documentPathTemplate:i&&(!e?.isGroup||i.collectionPath.includes("/"))?i.documentPathTemplate:null}}function Te(e){let t=e._historyConfig??(typeof e.history=="object"&&e.history!==null&&"enabled"in e.history?e.history:void 0),n=e._collectionPath??e.ref?.path??null,r=typeof e._documentPathTemplate=="string"?e._documentPathTemplate:null;return {historyConfig:t,systemKeys:e._systemKeys??[],isGroup:!!e._isGroup,collectionPath:n,documentPathTemplate:r&&(!e._isGroup||n&&n.includes("/"))?r:null}}function xe(e,t){return t?`${t}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${e}". Skipping.`),null)}function we(e,t){let{onDocumentWritten:n}=t.deps,r={},i=e?.rawMapping,l=i?Object.entries(i).map(([u,d])=>[u,He(d)]):Object.entries(e).map(([u,d])=>[u,Te(d)]);for(let[u,d]of l){let g=d.historyConfig;if(!g?.enabled)continue;let H=g.subcollection??he,h=g.ttl??t.defaults?.ttl,a=t.repos?.[u],T;if(d.isGroup){let f=a?.triggerPath??d.documentPathTemplate;if(!f){console.warn(`[HistoryTriggers] Skipping collection-group repo "${u}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}T=f;}else T=a?.triggerPath??d.documentPathTemplate??xe(u,d.collectionPath);if(!T)continue;let o=d.systemKeys,s=o[0]??"docId",y=S(g),c={...t.triggerOptions,...g?.triggerOptions,...a?.triggerOptions},p=Object.keys(c).length>0,x=async f=>{try{let w=f.data?.before?.data(),m=f.data?.after?.data(),b;if(!w&&m)b="create";else if(w&&!m)b="delete";else if(w&&m)b="update";else return;let O=String(m?.[s]??w?.[s]??f.params?.docId??f.data?.after?.id??f.data?.before?.id??"");if(!O)return;let v=M(w??{},m??{},{include:g.include,exclude:g.exclude,metaFields:y,systemKeys:o});if(b==="update"&&Object.keys(v).length===0)return;let R=F(m??w??null,g),Z=C({entityId:O,operation:b,changes:v,meta:R,config:g,ttlOverride:h}),G=f.data?.after?.ref??f.data?.before?.ref;if(!G)return;let ee=G.collection(H);await E(ee,Z,g,{repoName:u,docId:O,before:w??null,after:m??null});}catch(w){console.error(`[HistoryTriggers] Failed to record history for "${u}":`,w);}};r[`${u}_onHistory`]=n(p?{document:T,...c}:T,x);}return r}var J=5;function Re(e){return e.schemaVersion===2}function X(e){if(typeof e!="string")return "object";switch(e){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return e;default:return "object"}}function be(e){return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:2,operation:e.operation,meta:e.meta??{},...e.custom?{custom:e.custom}:{},changes:e.changes??{}}}function Oe(e){let t={};e.historyUserId!==void 0&&(t.userId=e.historyUserId??null),e.historyUserEmail!==void 0&&(t.userEmail=e.historyUserEmail??null);let n=e.extraHistoryDetails??null;n&&(n.reason!==void 0&&(t.reason=n.reason??null),n.comment!==void 0&&(t.comment=n.comment??null));let r={},i=false;if(e.historyDetails&&typeof e.historyDetails=="object")for(let[l,u]of Object.entries(e.historyDetails))r[l]=u,i=true;if(e.extraContentKeys&&typeof e.extraContentKeys=="object")for(let[l,u]of Object.entries(e.extraContentKeys))r[`content.${l}`]=u,i=true;return i&&(t.extras=r),t}function ke(e){let t=e.changes?.oldValue??null,n=e.changes?.newValue??null,r=e.types?.oldValue,i=e.types?.newValue;return {oldValue:t,newValue:n,type:{old:r?X(r):A(t),new:i?X(i):A(n)}}}function Ae(e){let t=ke(e),n=Oe(e);return {historyDocId:e.historyDocId,historyToObjectId:e.historyToObjectId,historySetAt:e.historySetAt,schemaVersion:1,operation:"update",meta:n,changes:{[e.field]:t}}}function De(e,t,n){return Math.abs(e.toMillis()-t.toMillis())<=n}function Ce(e,t){return (e.userId??null)===(t.userId??null)}function N(e,t={}){let n=t.groupToleranceMs??J,r=[];for(let i of e){if(Re(i)){r.push(be(i));continue}let u=Ae(i),d=r[r.length-1];d&&d.schemaVersion===1&&De(d.historySetAt,u.historySetAt,n)&&Ce(d.meta,u.meta)?Object.assign(d.changes,u.changes):r.push(u);}return r}var Ee="history",Ie=50;function W(e,t,n){return e(...n).collection(t)}function Q(e){return String(e[e.length-1]??"")}function Me(e,t,n,r){if(!r?.enabled)return null;let i=r.subcollection??Ee;async function l(...o){let s={},y=o,c=o[o.length-1];c!==null&&typeof c=="object"&&!(c instanceof firestore.Timestamp)&&("limit"in c||"cursor"in c||"direction"in c)&&(s=c,y=o.slice(0,-1));let p=W(e,i,y),x=s.direction??"desc",f=p.orderBy("historySetAt",x);return s.cursor&&(f=f.startAfter(s.cursor)),s.limit&&s.limit>0&&(f=f.limit(s.limit)),(await f.get()).docs.map(m=>({id:m.id,data:m.data()}))}async function u(...o){let s={},y=o,c=o[o.length-1];c!==null&&typeof c=="object"&&!(c instanceof firestore.Timestamp)&&("limit"in c||"cursor"in c||"direction"in c||"fields"in c||"operations"in c)&&(s=c,y=o.slice(0,-1));let p=s.limit??Ie,x=Math.max(p,Math.min(p*8,500)),f=await l(...y,{limit:x,cursor:s.cursor,direction:s.direction??"desc"}),w=N(f.map(m=>m.data));if(s.fields&&s.fields.length>0){let m=new Set(s.fields);w=w.filter(b=>Object.keys(b.changes).some(O=>m.has(O)));}if(s.operations&&s.operations.length>0){let m=new Set(s.operations);w=w.filter(b=>m.has(b.operation));}return w.slice(0,p)}async function d(...o){let s=o[o.length-1],y={},c,p;return s!==null&&typeof s=="object"&&!(s instanceof firestore.Timestamp)?(y=s,c=o[o.length-2],p=o.slice(0,-2)):(c=s,p=o.slice(0,-1)),u(...p,{...y,fields:[c]})}async function g(...o){let s=o[o.length-1],y={},c,p;return s!==null&&typeof s=="object"&&!(s instanceof firestore.Timestamp)?(y=s,c=o[o.length-2],p=o.slice(0,-2)):(c=s,p=o.slice(0,-1)),u(...p,{...y,operations:[c]})}function H(o){let s={title:o.title,display:o.display??true};return o.description!==void 0&&(s.description=o.description),o.key!==void 0&&(s.key=o.key),o.data!==void 0&&(s.data=o.data),s}function h(){let o=D(),s=r.fallbackActor??{},y=o?.userId!==void 0?o.userId:s.userId??null,c=o?.userEmail!==void 0?o.userEmail:s.userEmail??null;return {userId:y,userEmail:c,...o?.reason!==void 0?{reason:o.reason}:{},...o?.comment!==void 0?{comment:o.comment}:{},...o?.extras&&Object.keys(o.extras).length>0?{extras:o.extras}:{}}}async function a(...o){let s=o[o.length-1],y=o.slice(0,-1),c=Q(y),p=M(s.before??{},s.after??{},{include:r.include,exclude:r.exclude,metaFields:S(r),systemKeys:t});if(s.operation==="update"&&Object.keys(p).length===0)return null;let x=F(s.after??s.before??null,r),f=D(),m={...f?{...f.userId!==void 0?{userId:f.userId}:{},...f.userEmail!==void 0?{userEmail:f.userEmail}:{},...f.reason!==void 0?{reason:f.reason}:{},...f.comment!==void 0?{comment:f.comment}:{},...f.extras&&Object.keys(f.extras).length>0?{extras:f.extras}:{}}:{},...x,...s.meta??{}},b=s.custom?H(s.custom):void 0,O=C({entityId:c,operation:s.operation,changes:p,meta:m,custom:b,config:r}),v=W(e,i,y),R=await E(v,O,r,{repoName:n,docId:c,before:s.before??null,after:s.after??null});return !R.written||!R.entry?null:{historyDocId:R.entry.historyDocId,historyToObjectId:R.entry.historyToObjectId,historySetAt:R.entry.historySetAt,schemaVersion:2,operation:R.entry.operation,meta:R.entry.meta,...R.entry.custom?{custom:R.entry.custom}:{},changes:R.entry.changes}}async function T(...o){let s=o[o.length-1],y=o.slice(0,-1),c=Q(y),p=H(s),x={...h(),...s.meta??{}},f=C({entityId:c,operation:"custom",changes:{},meta:x,custom:p,config:r}),w=W(e,i,y),m=await E(w,f,r,{repoName:n,docId:c,before:null,after:null});return !m.written||!m.entry?null:{historyDocId:m.entry.historyDocId,historyToObjectId:m.entry.historyToObjectId,historySetAt:m.entry.historySetAt,schemaVersion:2,operation:m.entry.operation,meta:m.entry.meta,...m.entry.custom?{custom:m.entry.custom}:{},changes:m.entry.changes}}return {list:u,raw:l,byField:d,byOperation:g,recordManual:a,recordCustom:T}}exports.DEFAULT_GROUP_TOLERANCE_MS=J;exports.DEFAULT_HISTORY_SHADOW_KEY=U;exports.buildHistoryEntry=C;exports.computeDiff=M;exports.createActorContextMiddleware=le;exports.createActorResolver=L;exports.createHistoryMethods=Me;exports.createHistoryTriggers=we;exports.defaultActorResolver=z;exports.extractMeta=F;exports.getCurrentActor=D;exports.getHistoryIdentityKeys=fe;exports.getHistoryShadowKey=de;exports.injectHistoryMeta=me;exports.metaFieldsOf=S;exports.normalizeHistoryDocs=N;exports.resolveShadowConfig=k;exports.setRequestActorMeta=ue;exports.stripHistoryShadowField=ye;exports.valueType=A;exports.valuesEqual=V;exports.withActor=ce;exports.writeHistoryEntry=E;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|