ezlogs-nextjs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +779 -0
  3. package/bin/install-triggers.cjs +75 -0
  4. package/dist/actors/index.cjs +111 -0
  5. package/dist/actors/index.d.cts +52 -0
  6. package/dist/actors/index.d.ts +52 -0
  7. package/dist/actors/index.js +107 -0
  8. package/dist/configuration-D9x9Gvds.d.cts +190 -0
  9. package/dist/configuration-D9x9Gvds.d.ts +190 -0
  10. package/dist/db/drizzle.cjs +898 -0
  11. package/dist/db/drizzle.d.cts +68 -0
  12. package/dist/db/drizzle.d.ts +68 -0
  13. package/dist/db/drizzle.js +893 -0
  14. package/dist/db/prisma.cjs +826 -0
  15. package/dist/db/prisma.d.cts +3 -0
  16. package/dist/db/prisma.d.ts +3 -0
  17. package/dist/db/prisma.js +824 -0
  18. package/dist/db/supabase.cjs +1027 -0
  19. package/dist/db/supabase.d.cts +32 -0
  20. package/dist/db/supabase.d.ts +32 -0
  21. package/dist/db/supabase.js +1024 -0
  22. package/dist/index.cjs +3329 -0
  23. package/dist/index.d.cts +305 -0
  24. package/dist/index.d.ts +305 -0
  25. package/dist/index.js +3317 -0
  26. package/dist/jobs/bullmq.cjs +624 -0
  27. package/dist/jobs/bullmq.d.cts +33 -0
  28. package/dist/jobs/bullmq.d.ts +33 -0
  29. package/dist/jobs/bullmq.js +621 -0
  30. package/dist/jobs/inngest.cjs +645 -0
  31. package/dist/jobs/inngest.d.cts +21 -0
  32. package/dist/jobs/inngest.d.ts +21 -0
  33. package/dist/jobs/inngest.js +642 -0
  34. package/dist/jobs/supabase-queues.cjs +661 -0
  35. package/dist/jobs/supabase-queues.d.cts +37 -0
  36. package/dist/jobs/supabase-queues.d.ts +37 -0
  37. package/dist/jobs/supabase-queues.js +657 -0
  38. package/dist/jobs/trigger.cjs +622 -0
  39. package/dist/jobs/trigger.d.cts +46 -0
  40. package/dist/jobs/trigger.d.ts +46 -0
  41. package/dist/jobs/trigger.js +619 -0
  42. package/dist/jobs/upstash-workflow.cjs +673 -0
  43. package/dist/jobs/upstash-workflow.d.cts +57 -0
  44. package/dist/jobs/upstash-workflow.d.ts +57 -0
  45. package/dist/jobs/upstash-workflow.js +669 -0
  46. package/dist/nextjs-plugin/index.cjs +232 -0
  47. package/dist/nextjs-plugin/index.d.cts +68 -0
  48. package/dist/nextjs-plugin/index.d.ts +68 -0
  49. package/dist/nextjs-plugin/index.js +229 -0
  50. package/dist/nextjs-plugin/loader.cjs +16248 -0
  51. package/dist/nextjs-plugin/loader.d.cts +61 -0
  52. package/dist/nextjs-plugin/loader.d.ts +61 -0
  53. package/dist/nextjs-plugin/loader.js +16242 -0
  54. package/dist/triggers/index.cjs +1354 -0
  55. package/dist/triggers/index.d.cts +243 -0
  56. package/dist/triggers/index.d.ts +243 -0
  57. package/dist/triggers/index.js +1337 -0
  58. package/package.json +150 -0
  59. package/sql/postgres/00_install.sql +205 -0
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Internal logger for the agent.
3
+ *
4
+ * Mirrors EzLogsAgent::Logger: prefixed messages, `:warn` default level,
5
+ * never throws. The host app must never see an exception from logging.
6
+ */
7
+ type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
8
+
9
+ /**
10
+ * Configuration mirrors EzLogsAgent::Configuration.
11
+ *
12
+ * Defaults match Ruby exactly. User-supplied excluded* arrays are MERGED with
13
+ * the DEFAULT_* constants via the `all*` getters — same semantics as
14
+ * Ruby's `all_excluded_paths`, `all_excluded_tables`, etc.
15
+ *
16
+ * Public surface is intentionally narrow. Anything not in InitOptions is
17
+ * not configurable.
18
+ */
19
+
20
+ interface ActorContext {
21
+ /** Stable identifier for the user (e.g. `user.id`). REQUIRED. */
22
+ id: string;
23
+ /** Human-readable label (e.g. `user.email`). Optional. */
24
+ label?: string;
25
+ }
26
+ /**
27
+ * Minimal request-shape contract for `actorFromRequest`. We don't import
28
+ * Next.js types here to keep the package framework-light; users pass
29
+ * whatever request object they're given by the runtime.
30
+ *
31
+ * The hook may return a value or a Promise — Phase 4 actor extractors
32
+ * (Clerk, NextAuth, Auth.js) are async because they call into the
33
+ * framework's auth helpers, which lazy-import the SDK.
34
+ */
35
+ type ActorFromRequest = (request: unknown) => ActorContext | null | undefined | Promise<ActorContext | null | undefined>;
36
+ /**
37
+ * Resolver for a display name. Either:
38
+ * - a column name on the row (e.g. "name"), or
39
+ * - a function that returns a string from the row (e.g.
40
+ * `(row) => \`${row.first_name} ${row.last_name}\``).
41
+ *
42
+ * Functions let users compose names from multiple columns when no
43
+ * single field is sufficient. Resolver functions are invoked inside a
44
+ * try/catch — a thrown resolver collapses to "no display name" so a
45
+ * buggy resolver can never crash the host application.
46
+ */
47
+ type DisplayNameResolver = string | ((row: Record<string, unknown>) => string | null | undefined);
48
+ /**
49
+ * Maps a model class name → resolver used to derive the human-readable
50
+ * display value, mirroring Ruby's `display_name_for`.
51
+ */
52
+ type DisplayNameMap = Record<string, DisplayNameResolver>;
53
+ /**
54
+ * Classifier for Server Action failure return values.
55
+ *
56
+ * Many Next.js codebases (next-safe-action templates, the
57
+ * Vercel App Router examples, tRPC) catch errors inside the action and
58
+ * return `{ success: false, error: "..." }` instead of throwing. The
59
+ * HTTP response is 200, so the agent can't tell the action failed
60
+ * without inspecting the return value.
61
+ *
62
+ * If this classifier returns true the event is recorded as a failure
63
+ * with the supplied `errorMessage`. A thrown classifier or one that
64
+ * returns undefined is treated as "no opinion" — the default heuristic
65
+ * (`{ success: false, error: <truthy string> }`) still applies.
66
+ *
67
+ * @param result the value the Server Action returned
68
+ * @returns true / failure descriptor when the result represents a
69
+ * failure, false / undefined otherwise
70
+ */
71
+ type ServerActionErrorClassifier = (result: unknown) => boolean | {
72
+ errorMessage: string;
73
+ } | null | undefined;
74
+ interface InitOptions {
75
+ /** Defaults to `https://app.ezlogs.io` (the hosted EZLogs service). Override for self-hosting. */
76
+ serverUrl?: string;
77
+ projectToken: string;
78
+ captureHttp?: boolean;
79
+ captureDb?: boolean;
80
+ captureJobs?: boolean;
81
+ bufferSize?: number;
82
+ /** Send interval in milliseconds. Ruby uses seconds (3); Node uses ms (3000). */
83
+ sendInterval?: number;
84
+ retryAttempts?: number;
85
+ excludedPaths?: string[];
86
+ excludedTables?: string[];
87
+ excludedJobClasses?: string[];
88
+ excludedGraphqlOperations?: string[];
89
+ excludedGraphqlVariableKeys?: string[];
90
+ actorFromRequest?: ActorFromRequest;
91
+ displayNameFor?: DisplayNameMap;
92
+ /**
93
+ * Detect when a Server Action's return value represents a failure.
94
+ * See {@link ServerActionErrorClassifier}. The default heuristic
95
+ * (`{ success: false, error: <string> }`) runs in addition to any
96
+ * classifier you supply.
97
+ */
98
+ isServerActionError?: ServerActionErrorClassifier;
99
+ /** Patch globalThis.fetch to inject X-Correlation-ID. Default true. */
100
+ patchGlobalFetch?: boolean;
101
+ /**
102
+ * When true (default), the HTTP capturer extracts the current actor
103
+ * from the most-recently-constructed Supabase client by calling
104
+ * `.auth.getUser()` once per request. Use the actorFromRequest hook
105
+ * to override or disable. Set to false to skip the extra auth call
106
+ * when you don't use Supabase or want a custom actor source only.
107
+ */
108
+ actorFromSupabase?: boolean;
109
+ /**
110
+ * Trigger-based DB capture path. When set, the HTTP capturers flush
111
+ * `ezlogs_audit_log` rows tagged with the current correlation_id at
112
+ * the end of each request and emit them as `database_callback`
113
+ * events. Run `npx ezlogs-nextjs install-triggers` once per
114
+ * database to set up the audit table + trigger function, then
115
+ * either:
116
+ * - set this option to a function that runs a single SQL
117
+ * statement (e.g. `(sql, params) => pg.query(sql, params)`),
118
+ * - or wrap your mutations in `withDatabaseContext(client, cb)`
119
+ * so the trigger sees the actor + correlation GUCs.
120
+ *
121
+ * `params` is positional Postgres-style (`$1`, `$2`). The result
122
+ * shape can be `{ rows: [...] }` (pg) or a bare array (drizzle's
123
+ * `db.execute`). The agent never inspects the return value.
124
+ */
125
+ databaseReader?: DatabaseReader;
126
+ /**
127
+ * If supplied, the agent monkey-patches `pgModule.Client.prototype.query`
128
+ * at init so every `client.query(...)` (and therefore `pool.query(...)`,
129
+ * which routes through the same Client method) auto-injects
130
+ * `SET LOCAL ezlogs.actor_id` / `ezlogs.correlation_id` for the
131
+ * current request. Without this you'd have to wrap each customer
132
+ * mutation with `getDatabaseContext()` + manual SET statements.
133
+ *
134
+ * Pass the customer's own `pg` import — NOT the agent's — so the
135
+ * patch lands on the same Client class their app code uses (in a
136
+ * monorepo there can be multiple copies of pg).
137
+ *
138
+ * import * as pg from "pg";
139
+ * ezlogs.init({ patchDatabaseClient: pg, databaseReader: ... });
140
+ *
141
+ * Idempotent. The shape is `unknown` so we don't import `pg` types
142
+ * in the configuration module — the actual structural check lives
143
+ * in `patchPgClient`.
144
+ */
145
+ patchDatabaseClient?: unknown;
146
+ /**
147
+ * Time-window fallback for stacks where SET LOCAL can't propagate
148
+ * (supabase-js, PostgREST, anything that auto-commits per request
149
+ * and doesn't expose explicit transactions). When true, the agent
150
+ * runs `SELECT MAX(id) FROM ezlogs_audit_log` at the start of every
151
+ * request and remembers the value. At end of request the reader
152
+ * drains rows whose `correlation_id` matches OR (`correlation_id`
153
+ * is NULL and `id` is greater than the snapshot) — i.e. rows the
154
+ * trigger fired during this request even though the customer's
155
+ * client couldn't tag them.
156
+ *
157
+ * Default false. Enable for supabase-js apps. Adds one cheap
158
+ * `SELECT MAX(id)` per request. See AGENT_PARITY_NOTES.md for the
159
+ * concurrency caveat (concurrent same-actor mutations may blur).
160
+ */
161
+ databaseSnapshotMode?: boolean;
162
+ /**
163
+ * One-line install for the trigger-based capture. Pass your Postgres
164
+ * connection string; the agent does the rest:
165
+ * 1. Lazy-imports `pg` and constructs a Pool (4 connections, max).
166
+ * `pg` must be in your project's dependencies — the agent will
167
+ * log a debug message and skip the trigger path if it's missing.
168
+ * 2. Wires that Pool as `databaseReader` for the audit-log drain.
169
+ * 3. Patches `pg.Client.prototype.query` so every customer query
170
+ * auto-injects SET LOCAL. Drizzle (node-postgres) and Prisma
171
+ * (`@prisma/adapter-pg`) both run on `pg` and inherit zero-touch
172
+ * capture without any extra wiring on the customer's side.
173
+ * 4. Enables `databaseSnapshotMode` — the time-window fallback
174
+ * that catches supabase-js / PostgREST writes whose audit row
175
+ * didn't get our SET LOCAL.
176
+ *
177
+ * Customers who want to override individual pieces can still pass
178
+ * `databaseReader` / `patchDatabaseClient` / `databaseSnapshotMode`
179
+ * directly; explicit values win over the auto-wired pieces.
180
+ */
181
+ databaseUrl?: string;
182
+ logLevel?: LogLevel;
183
+ }
184
+ /**
185
+ * SQL executor for the trigger-based capture path. See `databaseReader`
186
+ * on {@link InitOptions}.
187
+ */
188
+ type DatabaseReader = (sql: string, params: ReadonlyArray<unknown>) => Promise<unknown>;
189
+
190
+ export type { ActorContext as A, DisplayNameMap as D, InitOptions as I, ActorFromRequest as a };