@lpdjs/firestore-repo-service 3.0.13 → 3.0.15
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 +117 -0
- package/dist/actor-context-DQZgWqj3.d.ts +117 -0
- package/dist/{create-servers-LyRLAOh3.d.cts → create-servers-B5Z5v2SP.d.cts} +11 -5
- package/dist/{create-servers-Db1xUY2N.d.ts → create-servers-p1-jJNTG.d.ts} +11 -5
- package/dist/history/index.cjs +1 -1
- package/dist/history/index.cjs.map +1 -1
- package/dist/history/index.d.cts +67 -7
- package/dist/history/index.d.ts +67 -7
- package/dist/history/index.js +1 -1
- package/dist/history/index.js.map +1 -1
- package/dist/index.cjs +81 -81
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +20 -14
- package/dist/index.d.ts +20 -14
- package/dist/index.js +81 -81
- package/dist/index.js.map +1 -1
- package/dist/llms-full.txt +1 -1
- package/dist/llms.txt +1 -1
- package/dist/{openapi-QVpqnnes.d.cts → openapi-B9utXiEH.d.cts} +1 -1
- package/dist/{openapi-CNIA7QRw.d.ts → openapi-Bsqq2zgh.d.ts} +1 -1
- package/dist/{queue-BEB-ujA3.d.ts → queue-NFod6hTT.d.ts} +1 -1
- package/dist/{queue-CpHe6M5j.d.cts → queue-zw2B7GPx.d.cts} +1 -1
- package/dist/{read-15-TcgCz.d.ts → read-BPov7lws.d.ts} +30 -7
- package/dist/{read-B15YaPyR.d.cts → read-Dfah1PPl.d.cts} +30 -7
- package/dist/{rules-Cafrkb9v.d.ts → rules-18wH7Uak.d.ts} +1 -1
- package/dist/{rules-Bu2NB7Eb.d.cts → rules-oSXoV4Js.d.cts} +1 -1
- package/dist/servers/admin/index.cjs +5 -5
- package/dist/servers/admin/index.cjs.map +1 -1
- package/dist/servers/admin/index.d.cts +5 -4
- package/dist/servers/admin/index.d.ts +5 -4
- package/dist/servers/admin/index.js +5 -5
- package/dist/servers/admin/index.js.map +1 -1
- package/dist/servers/crud/index.cjs +2 -2
- package/dist/servers/crud/index.cjs.map +1 -1
- package/dist/servers/crud/index.d.cts +10 -9
- package/dist/servers/crud/index.d.ts +10 -9
- package/dist/servers/crud/index.js +2 -2
- package/dist/servers/crud/index.js.map +1 -1
- package/dist/servers/hono/index.cjs +14 -14
- package/dist/servers/hono/index.cjs.map +1 -1
- package/dist/servers/hono/index.d.cts +11 -3
- package/dist/servers/hono/index.d.ts +11 -3
- package/dist/servers/hono/index.js +14 -14
- package/dist/servers/hono/index.js.map +1 -1
- package/dist/servers/index.cjs +94 -94
- package/dist/servers/index.cjs.map +1 -1
- package/dist/servers/index.d.cts +13 -12
- package/dist/servers/index.d.ts +13 -12
- package/dist/servers/index.js +94 -94
- package/dist/servers/index.js.map +1 -1
- package/dist/sync/bigquery.d.cts +2 -2
- package/dist/sync/bigquery.d.ts +2 -2
- package/dist/sync/index.cjs +55 -55
- package/dist/sync/index.cjs.map +1 -1
- package/dist/sync/index.d.cts +6 -6
- package/dist/sync/index.d.ts +6 -6
- package/dist/sync/index.js +55 -55
- package/dist/sync/index.js.map +1 -1
- package/dist/sync/meilisearch.cjs +2 -2
- package/dist/sync/meilisearch.cjs.map +1 -1
- package/dist/sync/meilisearch.d.cts +2 -2
- package/dist/sync/meilisearch.d.ts +2 -2
- package/dist/sync/meilisearch.js +2 -2
- package/dist/sync/meilisearch.js.map +1 -1
- package/dist/{types-o-9qoExc.d.cts → types-BDTx8VPg.d.cts} +8 -0
- package/dist/{types-CNseHqF7.d.cts → types-BGh5_2fl.d.cts} +4 -4
- package/dist/{types-DGQURFSq.d.ts → types-B_FrzmO4.d.ts} +1 -1
- package/dist/{types-DmXW_fVz.d.ts → types-Cc6lelk1.d.ts} +4 -4
- package/dist/{types--RamYGF1.d.cts → types-D6zvWzRt.d.cts} +96 -2
- package/dist/{types--RamYGF1.d.ts → types-D6zvWzRt.d.ts} +96 -2
- package/dist/{types-VVuLlmfc.d.cts → types-D78FPJeF.d.cts} +1 -1
- package/dist/{types-B51LYvQZ.d.cts → types-Dc3lX99O.d.cts} +20 -19
- package/dist/{types-Ci0dGbuW.d.ts → types-DgFJLwAu.d.ts} +20 -19
- package/dist/{types-D3W_RaDA.d.ts → types-w1rEqs0Z.d.ts} +8 -0
- package/package.json +1 -1
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Request-scoped & programmatic actor context backed by `AsyncLocalStorage`.
|
|
5
|
+
*
|
|
6
|
+
* Uses a `globalThis[Symbol.for(...)]` singleton so separate tsup bundles
|
|
7
|
+
* (`dist/index`, `dist/servers/hono`, `dist/servers/crud`, `dist/history`,
|
|
8
|
+
* `dist/servers/index`) always share the exact same `AsyncLocalStorage`
|
|
9
|
+
* instance.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Actor & audit metadata captured for history writes. */
|
|
13
|
+
interface HistoryActor {
|
|
14
|
+
userId?: string | null;
|
|
15
|
+
userEmail?: string | null;
|
|
16
|
+
reason?: string | null;
|
|
17
|
+
comment?: string | null;
|
|
18
|
+
extras?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
/** Function resolving the current actor lazily from a Hono `Context`. */
|
|
21
|
+
type ActorResolver = (c: Context) => HistoryActor | null | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Declarative configuration for {@link createActorResolver} so projects can
|
|
24
|
+
* customize context keys, nested user property paths, and request headers
|
|
25
|
+
* without writing a full resolver from scratch.
|
|
26
|
+
*/
|
|
27
|
+
interface ActorResolverFieldConfig {
|
|
28
|
+
/**
|
|
29
|
+
* Hono context keys inspected in order via `c.get(key)`.
|
|
30
|
+
* Default: `["user", "docsUser"]`.
|
|
31
|
+
*/
|
|
32
|
+
contextKeys?: string[];
|
|
33
|
+
/**
|
|
34
|
+
* Property paths on the user object checked in order for `userId`.
|
|
35
|
+
* Supports dot-notation (e.g. `"baseUser.id"`).
|
|
36
|
+
* Default: `["uid", "id", "sub"]`.
|
|
37
|
+
*/
|
|
38
|
+
userIdFields?: string[];
|
|
39
|
+
/**
|
|
40
|
+
* Property paths on the user object checked in order for `userEmail`.
|
|
41
|
+
* Supports dot-notation (e.g. `"baseUser.email"`).
|
|
42
|
+
* Default: `["email"]`.
|
|
43
|
+
*/
|
|
44
|
+
userEmailFields?: string[];
|
|
45
|
+
/**
|
|
46
|
+
* HTTP header name for change reason, or `false` to disable header lookup.
|
|
47
|
+
* Default: `"x-history-reason"`.
|
|
48
|
+
*/
|
|
49
|
+
reasonHeader?: string | false;
|
|
50
|
+
/**
|
|
51
|
+
* HTTP header name for change comment, or `false` to disable header lookup.
|
|
52
|
+
* Default: `"x-history-comment"`.
|
|
53
|
+
*/
|
|
54
|
+
commentHeader?: string | false;
|
|
55
|
+
/**
|
|
56
|
+
* Optional extractor to populate `actor.extras` from `(c, user)`.
|
|
57
|
+
*/
|
|
58
|
+
extras?: (c: Context, user: Record<string, unknown> | null) => Record<string, unknown> | undefined;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Accepted by `HonoServerOptions.actorResolver`, `ApiRegistryOptions.actorResolver`,
|
|
62
|
+
* `CrudServerOptions.actorResolver`, and `CreateServersDeps.actorResolver`:
|
|
63
|
+
* either a custom resolver function or a declarative field-mapping config.
|
|
64
|
+
*/
|
|
65
|
+
type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;
|
|
66
|
+
/**
|
|
67
|
+
* Build an {@link ActorResolver} from a declarative field/header configuration.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* const actorResolver = createActorResolver({
|
|
72
|
+
* contextKeys: ["authUser", "user"],
|
|
73
|
+
* userIdFields: ["docId", "uid"],
|
|
74
|
+
* userEmailFields: ["baseUser.email", "email"],
|
|
75
|
+
* reasonHeader: "x-audit-reason",
|
|
76
|
+
* });
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
declare function createActorResolver(config?: ActorResolverFieldConfig): ActorResolver;
|
|
80
|
+
/**
|
|
81
|
+
* Default actor resolver compatible with Firebase JWT / `firebaseBearerAuth` /
|
|
82
|
+
* custom auth middlewares setting `c.get("user")` or `c.get("docsUser")`.
|
|
83
|
+
*/
|
|
84
|
+
declare const defaultActorResolver: ActorResolver;
|
|
85
|
+
/**
|
|
86
|
+
* Hono middleware mounted automatically at the top of `HonoServer`.
|
|
87
|
+
* Stores `{ c, resolver }` in `AsyncLocalStorage` so downstream repository
|
|
88
|
+
* writes resolve the authenticated user lazily after auth middlewares run.
|
|
89
|
+
*/
|
|
90
|
+
declare function createActorContextMiddleware(resolver?: ActorResolverOption): MiddlewareHandler;
|
|
91
|
+
/**
|
|
92
|
+
* Resolve the active {@link HistoryActor} for the current async execution
|
|
93
|
+
* context, or `null` when outside any scope or when no actor is available.
|
|
94
|
+
*/
|
|
95
|
+
declare function getCurrentActor(): HistoryActor | null;
|
|
96
|
+
/**
|
|
97
|
+
* Execute `fn` within an isolated actor scope — ideal for crons, Pub/Sub
|
|
98
|
+
* workers, scripts, and unit tests.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* await withActor({ userId: "cron:invoicing", reason: "monthly-run" }, async () => {
|
|
103
|
+
* await repos.invoices.create(payload);
|
|
104
|
+
* });
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
declare function withActor<T>(actor: HistoryActor, fn: () => T): T;
|
|
108
|
+
/**
|
|
109
|
+
* Enrich or override actor metadata (`reason`, `comment`, `extras`, …) for the
|
|
110
|
+
* current active request / `withActor` scope without touching repository calls.
|
|
111
|
+
*
|
|
112
|
+
* Safe no-op returning `false` when called outside any active ALS scope.
|
|
113
|
+
*/
|
|
114
|
+
declare function setRequestActorMeta(meta: Partial<HistoryActor>): boolean;
|
|
115
|
+
|
|
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 };
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Request-scoped & programmatic actor context backed by `AsyncLocalStorage`.
|
|
5
|
+
*
|
|
6
|
+
* Uses a `globalThis[Symbol.for(...)]` singleton so separate tsup bundles
|
|
7
|
+
* (`dist/index`, `dist/servers/hono`, `dist/servers/crud`, `dist/history`,
|
|
8
|
+
* `dist/servers/index`) always share the exact same `AsyncLocalStorage`
|
|
9
|
+
* instance.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Actor & audit metadata captured for history writes. */
|
|
13
|
+
interface HistoryActor {
|
|
14
|
+
userId?: string | null;
|
|
15
|
+
userEmail?: string | null;
|
|
16
|
+
reason?: string | null;
|
|
17
|
+
comment?: string | null;
|
|
18
|
+
extras?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
/** Function resolving the current actor lazily from a Hono `Context`. */
|
|
21
|
+
type ActorResolver = (c: Context) => HistoryActor | null | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Declarative configuration for {@link createActorResolver} so projects can
|
|
24
|
+
* customize context keys, nested user property paths, and request headers
|
|
25
|
+
* without writing a full resolver from scratch.
|
|
26
|
+
*/
|
|
27
|
+
interface ActorResolverFieldConfig {
|
|
28
|
+
/**
|
|
29
|
+
* Hono context keys inspected in order via `c.get(key)`.
|
|
30
|
+
* Default: `["user", "docsUser"]`.
|
|
31
|
+
*/
|
|
32
|
+
contextKeys?: string[];
|
|
33
|
+
/**
|
|
34
|
+
* Property paths on the user object checked in order for `userId`.
|
|
35
|
+
* Supports dot-notation (e.g. `"baseUser.id"`).
|
|
36
|
+
* Default: `["uid", "id", "sub"]`.
|
|
37
|
+
*/
|
|
38
|
+
userIdFields?: string[];
|
|
39
|
+
/**
|
|
40
|
+
* Property paths on the user object checked in order for `userEmail`.
|
|
41
|
+
* Supports dot-notation (e.g. `"baseUser.email"`).
|
|
42
|
+
* Default: `["email"]`.
|
|
43
|
+
*/
|
|
44
|
+
userEmailFields?: string[];
|
|
45
|
+
/**
|
|
46
|
+
* HTTP header name for change reason, or `false` to disable header lookup.
|
|
47
|
+
* Default: `"x-history-reason"`.
|
|
48
|
+
*/
|
|
49
|
+
reasonHeader?: string | false;
|
|
50
|
+
/**
|
|
51
|
+
* HTTP header name for change comment, or `false` to disable header lookup.
|
|
52
|
+
* Default: `"x-history-comment"`.
|
|
53
|
+
*/
|
|
54
|
+
commentHeader?: string | false;
|
|
55
|
+
/**
|
|
56
|
+
* Optional extractor to populate `actor.extras` from `(c, user)`.
|
|
57
|
+
*/
|
|
58
|
+
extras?: (c: Context, user: Record<string, unknown> | null) => Record<string, unknown> | undefined;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Accepted by `HonoServerOptions.actorResolver`, `ApiRegistryOptions.actorResolver`,
|
|
62
|
+
* `CrudServerOptions.actorResolver`, and `CreateServersDeps.actorResolver`:
|
|
63
|
+
* either a custom resolver function or a declarative field-mapping config.
|
|
64
|
+
*/
|
|
65
|
+
type ActorResolverOption = ActorResolver | ActorResolverFieldConfig;
|
|
66
|
+
/**
|
|
67
|
+
* Build an {@link ActorResolver} from a declarative field/header configuration.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* const actorResolver = createActorResolver({
|
|
72
|
+
* contextKeys: ["authUser", "user"],
|
|
73
|
+
* userIdFields: ["docId", "uid"],
|
|
74
|
+
* userEmailFields: ["baseUser.email", "email"],
|
|
75
|
+
* reasonHeader: "x-audit-reason",
|
|
76
|
+
* });
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
declare function createActorResolver(config?: ActorResolverFieldConfig): ActorResolver;
|
|
80
|
+
/**
|
|
81
|
+
* Default actor resolver compatible with Firebase JWT / `firebaseBearerAuth` /
|
|
82
|
+
* custom auth middlewares setting `c.get("user")` or `c.get("docsUser")`.
|
|
83
|
+
*/
|
|
84
|
+
declare const defaultActorResolver: ActorResolver;
|
|
85
|
+
/**
|
|
86
|
+
* Hono middleware mounted automatically at the top of `HonoServer`.
|
|
87
|
+
* Stores `{ c, resolver }` in `AsyncLocalStorage` so downstream repository
|
|
88
|
+
* writes resolve the authenticated user lazily after auth middlewares run.
|
|
89
|
+
*/
|
|
90
|
+
declare function createActorContextMiddleware(resolver?: ActorResolverOption): MiddlewareHandler;
|
|
91
|
+
/**
|
|
92
|
+
* Resolve the active {@link HistoryActor} for the current async execution
|
|
93
|
+
* context, or `null` when outside any scope or when no actor is available.
|
|
94
|
+
*/
|
|
95
|
+
declare function getCurrentActor(): HistoryActor | null;
|
|
96
|
+
/**
|
|
97
|
+
* Execute `fn` within an isolated actor scope — ideal for crons, Pub/Sub
|
|
98
|
+
* workers, scripts, and unit tests.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```ts
|
|
102
|
+
* await withActor({ userId: "cron:invoicing", reason: "monthly-run" }, async () => {
|
|
103
|
+
* await repos.invoices.create(payload);
|
|
104
|
+
* });
|
|
105
|
+
* ```
|
|
106
|
+
*/
|
|
107
|
+
declare function withActor<T>(actor: HistoryActor, fn: () => T): T;
|
|
108
|
+
/**
|
|
109
|
+
* Enrich or override actor metadata (`reason`, `comment`, `extras`, …) for the
|
|
110
|
+
* current active request / `withActor` scope without touching repository calls.
|
|
111
|
+
*
|
|
112
|
+
* Safe no-op returning `false` when called outside any active ALS scope.
|
|
113
|
+
*/
|
|
114
|
+
declare function setRequestActorMeta(meta: Partial<HistoryActor>): boolean;
|
|
115
|
+
|
|
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 };
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { S as SyncQueue } from './queue-
|
|
2
|
-
import { F as FirestoreSyncConfig, S as SyncEvent } from './types-
|
|
3
|
-
import { O as OpenAPIDocument } from './openapi-
|
|
1
|
+
import { S as SyncQueue } from './queue-zw2B7GPx.cjs';
|
|
2
|
+
import { F as FirestoreSyncConfig, S as SyncEvent } from './types-D78FPJeF.cjs';
|
|
3
|
+
import { O as OpenAPIDocument } from './openapi-B9utXiEH.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 {
|
|
8
|
-
import {
|
|
7
|
+
import { A as ActorResolverOption } from './actor-context-DQZgWqj3.cjs';
|
|
8
|
+
import { H as HistoryTriggersConfig } from './types-D6zvWzRt.cjs';
|
|
9
|
+
import { C as ConfiguredRepository, b as CrudRepoConfig, a as CrudServerOptions } from './types-BGh5_2fl.cjs';
|
|
9
10
|
import { MeilisearchAdapterOptions, MeilisearchAdapter } from './sync/meilisearch.cjs';
|
|
10
11
|
import { AdminRepoConfig, AdminServerOptions } from './servers/admin/index.cjs';
|
|
11
12
|
|
|
@@ -59,6 +60,11 @@ interface CreateServersDeps {
|
|
|
59
60
|
* Per-pipeline or per-repo options override these defaults.
|
|
60
61
|
*/
|
|
61
62
|
triggerOptions?: TriggerOptions;
|
|
63
|
+
/**
|
|
64
|
+
* Default `actorResolver` applied to Hono-backed servers (e.g. `servers.crud()`).
|
|
65
|
+
* Per-server options override this default.
|
|
66
|
+
*/
|
|
67
|
+
actorResolver?: ActorResolverOption;
|
|
62
68
|
}
|
|
63
69
|
/**
|
|
64
70
|
* Pre-binds a repository mapping to all server builders.
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { S as SyncQueue } from './queue-
|
|
2
|
-
import { F as FirestoreSyncConfig, S as SyncEvent } from './types-
|
|
3
|
-
import { O as OpenAPIDocument } from './openapi-
|
|
1
|
+
import { S as SyncQueue } from './queue-NFod6hTT.js';
|
|
2
|
+
import { F as FirestoreSyncConfig, S as SyncEvent } from './types-B_FrzmO4.js';
|
|
3
|
+
import { O as OpenAPIDocument } from './openapi-Bsqq2zgh.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 {
|
|
8
|
-
import {
|
|
7
|
+
import { A as ActorResolverOption } from './actor-context-DQZgWqj3.js';
|
|
8
|
+
import { H as HistoryTriggersConfig } from './types-D6zvWzRt.js';
|
|
9
|
+
import { C as ConfiguredRepository, b as CrudRepoConfig, a as CrudServerOptions } from './types-Cc6lelk1.js';
|
|
9
10
|
import { MeilisearchAdapterOptions, MeilisearchAdapter } from './sync/meilisearch.js';
|
|
10
11
|
import { AdminRepoConfig, AdminServerOptions } from './servers/admin/index.js';
|
|
11
12
|
|
|
@@ -59,6 +60,11 @@ interface CreateServersDeps {
|
|
|
59
60
|
* Per-pipeline or per-repo options override these defaults.
|
|
60
61
|
*/
|
|
61
62
|
triggerOptions?: TriggerOptions;
|
|
63
|
+
/**
|
|
64
|
+
* Default `actorResolver` applied to Hono-backed servers (e.g. `servers.crud()`).
|
|
65
|
+
* Per-server options override this default.
|
|
66
|
+
*/
|
|
67
|
+
actorResolver?: ActorResolverOption;
|
|
62
68
|
}
|
|
63
69
|
/**
|
|
64
70
|
* Pre-binds a repository mapping to all server builders.
|
package/dist/history/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var crypto=require('crypto'),firestore=require('firebase-admin/firestore');function $(t){return t.match(/^\{([^}]+)\}$/)?.[1]?.trim()||null}function L(t,e="docId",r=false){if(typeof t!="string"||!t.trim())return {rawPath:t??"",collectionId:"",collectionPath:"",parentKeys:[],documentPathTemplate:null,hasTemplate:false};let n=t.split("/").map(o=>o.trim()).filter(Boolean);if(n.length===0)return {rawPath:t,collectionId:t,collectionPath:t,parentKeys:[],documentPathTemplate:null,hasTemplate:false};if(n.length===1){let o=n[0];return {rawPath:t,collectionId:o,collectionPath:o,parentKeys:[],documentPathTemplate:r?null:`${o}/{${e}}`,hasTemplate:t.includes("{")&&t.includes("}")}}let i=n.length%2===0,c=i?n.slice(0,-1):n,l=c[c.length-1],a=c.join("/"),g=c.slice(0,-1).map($).filter(o=>o!==null),s=i?n.join("/"):`${a}/{${e}}`;return {rawPath:t,collectionId:l,collectionPath:a,parentKeys:g,documentPathTemplate:s,hasTemplate:true}}function b(t){if(t===null)return "null";if(t===void 0)return "undefined";if(t instanceof firestore.Timestamp)return "timestamp";if(t instanceof Date)return "date";if(Array.isArray(t))return "array";let e=typeof t;return e==="string"||e==="number"||e==="boolean"?e:"object"}function V(t,e,r=new WeakMap){if(t===e)return true;if(t===null||e===null||t===void 0||e===void 0)return t===e;if(t instanceof firestore.Timestamp&&e instanceof firestore.Timestamp)return t.isEqual(e);if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)||Array.isArray(e)){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return false;if(r.get(t)===e)return true;r.set(t,e);for(let n=0;n<t.length;n++)if(!V(t[n],e[n],r))return false;return true}if(typeof t=="object"&&typeof e=="object"){if(t instanceof Date||e instanceof Date||t instanceof firestore.Timestamp||e instanceof firestore.Timestamp)return false;if(r.get(t)===e)return true;r.set(t,e);let n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return false;for(let c of n)if(!Object.prototype.hasOwnProperty.call(e,c)||!V(t[c],e[c],r))return false;return true}return false}function x(t,e,r={}){let n=new Set([...r.exclude??[],...r.metaFields??[],...r.systemKeys??[]]),i=r.include?new Set(r.include):null,c=t??{},l=e??{},a=new Set([...Object.keys(c),...Object.keys(l)]),d={};for(let g of a){if(n.has(g)||i&&!i.has(g))continue;let s=c[g],o=l[g];V(s,o)||(d[g]={oldValue:s===void 0?null:s,newValue:o===void 0?null:o,type:{old:b(s),new:b(o)}});}return d}var W=7e5;function M(t){let e=t.ttlOverride??t.config.ttl,n={schemaVersion:2,historyDocId:crypto.randomUUID(),historyToObjectId:t.entityId,historySetAt:firestore.Timestamp.now(),operation:t.operation,meta:t.meta,changes:t.changes};e&&(n.expiresAt=firestore.Timestamp.fromMillis(Date.now()+e.days*24*60*60*1e3));let i=c=>{try{return Buffer.byteLength(JSON.stringify(c,(l,a)=>a instanceof firestore.Timestamp?a.toMillis():a),"utf8")}catch{return 0}};if(i(n.changes)>W){let c={};for(let[l,a]of Object.entries(n.changes)){let d=i(a.oldValue),g=i(a.newValue);c[l]={oldValue:d>5e4?"[truncated]":a.oldValue,newValue:g>5e4?"[truncated]":a.newValue,type:a.type};}n.changes=c,n._truncated=true;}return n}async function R(t,e,r,n){let i=e;return r.onBeforeWrite&&(i=await r.onBeforeWrite(e,n)),i?(await t.doc(i.historyDocId).set(i),{written:true,entry:i}):{written:false,reason:"dropped-by-onBeforeWrite"}}function P(t,e){let r=t??{},n={},i=e.meta;if(!i)return n;let c=s=>{if(!s)return;let o=r[s];return o===void 0||o===null?null:String(o)},l=c(i.userId);l!==void 0&&(n.userId=l);let a=c(i.userEmail);a!==void 0&&(n.userEmail=a);let d=c(i.reason);d!==void 0&&(n.reason=d);let g=c(i.comment);if(g!==void 0&&(n.comment=g),i.extras&&i.extras.length>0){let s={},o=false;for(let y of i.extras)y in r&&(s[y]=r[y],o=true);o&&(n.extras=s);}return n}function E(t){let e=t.meta;if(!e)return [];let r=[];return e.userId&&r.push(e.userId),e.userEmail&&r.push(e.userEmail),e.reason&&r.push(e.reason),e.comment&&r.push(e.comment),e.extras&&r.push(...e.extras),r}var z="history";function q(t){let e=t&&typeof t.history=="object"&&t.history!==null?t.history:void 0,r=[t?.documentKey,t?.pathKey,t?.createdKey,t?.updatedKey].filter(c=>typeof c=="string"),n=typeof t?.path=="string"?t.path:null,i=n?L(n,t?.documentKey??"docId"):null;return {historyConfig:e,systemKeys:r,isGroup:!!t?.isGroup,collectionPath:i?i.collectionPath:null,documentPathTemplate:i&&(!t?.isGroup||i.collectionPath.includes("/"))?i.documentPathTemplate:null}}function J(t){let e=t._historyConfig??(typeof t.history=="object"&&t.history!==null&&"enabled"in t.history?t.history:void 0),r=t._collectionPath??t.ref?.path??null,n=typeof t._documentPathTemplate=="string"?t._documentPathTemplate:null;return {historyConfig:e,systemKeys:t._systemKeys??[],isGroup:!!t._isGroup,collectionPath:r,documentPathTemplate:n&&(!t._isGroup||r&&r.includes("/"))?n:null}}function X(t,e){return e?`${e}/{docId}`:(console.warn(`[HistoryTriggers] Cannot determine collection path for "${t}". Skipping.`),null)}function Y(t,e){let{onDocumentWritten:r}=e.deps,n={},i=t?.rawMapping,c=i?Object.entries(i).map(([l,a])=>[l,q(a)]):Object.entries(t).map(([l,a])=>[l,J(a)]);for(let[l,a]of c){let d=a.historyConfig;if(!d?.enabled)continue;let g=d.subcollection??z,s=d.ttl??e.defaults?.ttl,o=e.repos?.[l],y;if(a.isGroup){let f=o?.triggerPath??a.documentPathTemplate;if(!f){console.warn(`[HistoryTriggers] Skipping collection-group repo "${l}". Provide a triggerPath in the history triggers repos override or use a full path template.`);continue}y=f;}else y=o?.triggerPath??a.documentPathTemplate??X(l,a.collectionPath);if(!y)continue;let u=a.systemKeys,p=u[0]??"docId",D=E(d),h={...e.triggerOptions,...d?.triggerOptions,...o?.triggerOptions},T=Object.keys(h).length>0,m=async f=>{try{let H=f.data?.before?.data(),O=f.data?.after?.data(),w;if(!H&&O)w="create";else if(H&&!O)w="delete";else if(H&&O)w="update";else return;let C=String(O?.[p]??H?.[p]??f.params?.docId??f.data?.after?.id??f.data?.before?.id??"");if(!C)return;let j=x(H??{},O??{},{include:d.include,exclude:d.exclude,metaFields:D,systemKeys:u});if(w==="update"&&Object.keys(j).length===0)return;let v=P(O??H??null,d),U=M({entityId:C,operation:w,changes:j,meta:v,config:d,ttlOverride:s}),S=f.data?.after?.ref??f.data?.before?.ref;if(!S)return;let G=S.collection(g);await R(G,U,d,{repoName:l,docId:C,before:H??null,after:O??null});}catch(H){console.error(`[HistoryTriggers] Failed to record history for "${l}":`,H);}};n[`${l}_onHistory`]=r(T?{document:y,...h}:y,m);}return n}var _=5;function Q(t){return t.schemaVersion===2}function K(t){if(typeof t!="string")return "object";switch(t){case "string":case "number":case "boolean":case "object":case "array":case "timestamp":case "date":case "null":case "undefined":return t;default:return "object"}}function Z(t){return {historyDocId:t.historyDocId,historyToObjectId:t.historyToObjectId,historySetAt:t.historySetAt,schemaVersion:2,operation:t.operation,meta:t.meta??{},changes:t.changes??{}}}function tt(t){let e={};t.historyUserId!==void 0&&(e.userId=t.historyUserId??null),t.historyUserEmail!==void 0&&(e.userEmail=t.historyUserEmail??null);let r=t.extraHistoryDetails??null;r&&(r.reason!==void 0&&(e.reason=r.reason??null),r.comment!==void 0&&(e.comment=r.comment??null));let n={},i=false;if(t.historyDetails&&typeof t.historyDetails=="object")for(let[c,l]of Object.entries(t.historyDetails))n[c]=l,i=true;if(t.extraContentKeys&&typeof t.extraContentKeys=="object")for(let[c,l]of Object.entries(t.extraContentKeys))n[`content.${c}`]=l,i=true;return i&&(e.extras=n),e}function et(t){let e=t.changes?.oldValue??null,r=t.changes?.newValue??null,n=t.types?.oldValue,i=t.types?.newValue;return {oldValue:e,newValue:r,type:{old:n?K(n):b(e),new:i?K(i):b(r)}}}function nt(t){let e=et(t),r=tt(t);return {historyDocId:t.historyDocId,historyToObjectId:t.historyToObjectId,historySetAt:t.historySetAt,schemaVersion:1,operation:"update",meta:r,changes:{[t.field]:e}}}function ot(t,e,r){return Math.abs(t.toMillis()-e.toMillis())<=r}function rt(t,e){return (t.userId??null)===(e.userId??null)}function F(t,e={}){let r=e.groupToleranceMs??_,n=[];for(let i of t){if(Q(i)){n.push(Z(i));continue}let l=nt(i),a=n[n.length-1];a&&a.schemaVersion===1&&ot(a.historySetAt,l.historySetAt,r)&&rt(a.meta,l.meta)?Object.assign(a.changes,l.changes):n.push(l);}return n}var it="history",st=50;function B(t,e,r){return t(...r).collection(e)}function at(t){return String(t[t.length-1]??"")}function lt(t,e,r,n){if(!n?.enabled)return null;let i=n.subcollection??it;async function c(...s){let o={},y=s,u=s[s.length-1];u!==null&&typeof u=="object"&&!(u instanceof firestore.Timestamp)&&("limit"in u||"cursor"in u||"direction"in u)&&(o=u,y=s.slice(0,-1));let p=B(t,i,y),D=o.direction??"desc",h=p.orderBy("historySetAt",D);return o.cursor&&(h=h.startAfter(o.cursor)),o.limit&&o.limit>0&&(h=h.limit(o.limit)),(await h.get()).docs.map(m=>({id:m.id,data:m.data()}))}async function l(...s){let o={},y=s,u=s[s.length-1];u!==null&&typeof u=="object"&&!(u instanceof firestore.Timestamp)&&("limit"in u||"cursor"in u||"direction"in u||"fields"in u||"operations"in u)&&(o=u,y=s.slice(0,-1));let p=o.limit??st,D=Math.max(p,Math.min(p*8,500)),h=await c(...y,{limit:D,cursor:o.cursor,direction:o.direction??"desc"}),T=F(h.map(m=>m.data));if(o.fields&&o.fields.length>0){let m=new Set(o.fields);T=T.filter(f=>Object.keys(f.changes).some(H=>m.has(H)));}if(o.operations&&o.operations.length>0){let m=new Set(o.operations);T=T.filter(f=>m.has(f.operation));}return T.slice(0,p)}async function a(...s){let o=s[s.length-1],y={},u,p;return o!==null&&typeof o=="object"&&!(o instanceof firestore.Timestamp)?(y=o,u=s[s.length-2],p=s.slice(0,-2)):(u=o,p=s.slice(0,-1)),l(...p,{...y,fields:[u]})}async function d(...s){let o=s[s.length-1],y={},u,p;return o!==null&&typeof o=="object"&&!(o instanceof firestore.Timestamp)?(y=o,u=s[s.length-2],p=s.slice(0,-2)):(u=o,p=s.slice(0,-1)),l(...p,{...y,operations:[u]})}async function g(...s){let o=s[s.length-1],y=s.slice(0,-1),u=at(y),p=x(o.before??{},o.after??{},{include:n.include,exclude:n.exclude,metaFields:E(n),systemKeys:e});if(o.operation==="update"&&Object.keys(p).length===0)return null;let h={...P(o.after??o.before??null,n),...o.meta??{}},T=M({entityId:u,operation:o.operation,changes:p,meta:h,config:n}),m=B(t,i,y),f=await R(m,T,n,{repoName:r,docId:u,before:o.before??null,after:o.after??null});return !f.written||!f.entry?null:{historyDocId:f.entry.historyDocId,historyToObjectId:f.entry.historyToObjectId,historySetAt:f.entry.historySetAt,schemaVersion:2,operation:f.entry.operation,meta:f.entry.meta,changes:f.entry.changes}}return {list:l,raw:c,byField:a,byOperation:d,recordManual:g}}exports.DEFAULT_GROUP_TOLERANCE_MS=_;exports.buildHistoryEntry=M;exports.computeDiff=x;exports.createHistoryMethods=lt;exports.createHistoryTriggers=Y;exports.extractMeta=P;exports.metaFieldsOf=E;exports.normalizeHistoryDocs=F;exports.valueType=b;exports.valuesEqual=V;exports.writeHistoryEntry=R;//# 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 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
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|