nowity 1.0.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 (192) hide show
  1. package/README.md +751 -0
  2. package/dist/api/contract.d.ts +186 -0
  3. package/dist/api/contract.d.ts.map +1 -0
  4. package/dist/api/contract.js +251 -0
  5. package/dist/api/errors.d.ts +50 -0
  6. package/dist/api/errors.d.ts.map +1 -0
  7. package/dist/api/errors.js +50 -0
  8. package/dist/api/index.d.ts +13 -0
  9. package/dist/api/index.d.ts.map +1 -0
  10. package/dist/api/index.js +32 -0
  11. package/dist/client/confirmed-store.d.ts +33 -0
  12. package/dist/client/confirmed-store.d.ts.map +1 -0
  13. package/dist/client/confirmed-store.js +123 -0
  14. package/dist/client/connection.d.ts +102 -0
  15. package/dist/client/connection.d.ts.map +1 -0
  16. package/dist/client/connection.js +285 -0
  17. package/dist/client/list.d.ts +102 -0
  18. package/dist/client/list.d.ts.map +1 -0
  19. package/dist/client/list.js +257 -0
  20. package/dist/client/live-query.d.ts +153 -0
  21. package/dist/client/live-query.d.ts.map +1 -0
  22. package/dist/client/live-query.js +244 -0
  23. package/dist/client/nowity-client.d.ts +188 -0
  24. package/dist/client/nowity-client.d.ts.map +1 -0
  25. package/dist/client/nowity-client.js +580 -0
  26. package/dist/client/null-transport.d.ts +16 -0
  27. package/dist/client/null-transport.d.ts.map +1 -0
  28. package/dist/client/null-transport.js +17 -0
  29. package/dist/client/overlay.d.ts +44 -0
  30. package/dist/client/overlay.d.ts.map +1 -0
  31. package/dist/client/overlay.js +90 -0
  32. package/dist/client/query-source.d.ts +78 -0
  33. package/dist/client/query-source.d.ts.map +1 -0
  34. package/dist/client/query-source.js +57 -0
  35. package/dist/client/ssr-source.d.ts +70 -0
  36. package/dist/client/ssr-source.d.ts.map +1 -0
  37. package/dist/client/ssr-source.js +134 -0
  38. package/dist/client/transport.d.ts +19 -0
  39. package/dist/client/transport.d.ts.map +1 -0
  40. package/dist/client/transport.js +2 -0
  41. package/dist/client/ws-transport.d.ts +30 -0
  42. package/dist/client/ws-transport.d.ts.map +1 -0
  43. package/dist/client/ws-transport.js +89 -0
  44. package/dist/client.d.ts +47 -0
  45. package/dist/client.d.ts.map +1 -0
  46. package/dist/client.js +80 -0
  47. package/dist/core/diff.d.ts +14 -0
  48. package/dist/core/diff.d.ts.map +1 -0
  49. package/dist/core/diff.js +56 -0
  50. package/dist/core/normalize.d.ts +16 -0
  51. package/dist/core/normalize.d.ts.map +1 -0
  52. package/dist/core/normalize.js +67 -0
  53. package/dist/core/protocol.d.ts +215 -0
  54. package/dist/core/protocol.d.ts.map +1 -0
  55. package/dist/core/protocol.js +14 -0
  56. package/dist/core/ssr-bridge.d.ts +69 -0
  57. package/dist/core/ssr-bridge.d.ts.map +1 -0
  58. package/dist/core/ssr-bridge.js +40 -0
  59. package/dist/core/types.d.ts +96 -0
  60. package/dist/core/types.d.ts.map +1 -0
  61. package/dist/core/types.js +17 -0
  62. package/dist/index.d.ts +47 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +98 -0
  65. package/dist/ironbean/client.d.ts +7 -0
  66. package/dist/ironbean/client.d.ts.map +1 -0
  67. package/dist/ironbean/client.js +38 -0
  68. package/dist/ironbean/server.d.ts +42 -0
  69. package/dist/ironbean/server.d.ts.map +1 -0
  70. package/dist/ironbean/server.js +62 -0
  71. package/dist/ironbean/tokens.d.ts +26 -0
  72. package/dist/ironbean/tokens.d.ts.map +1 -0
  73. package/dist/ironbean/tokens.js +23 -0
  74. package/dist/next/config.d.ts +7 -0
  75. package/dist/next/config.d.ts.map +1 -0
  76. package/dist/next/config.js +77 -0
  77. package/dist/next/live.d.ts +69 -0
  78. package/dist/next/live.d.ts.map +1 -0
  79. package/dist/next/live.js +70 -0
  80. package/dist/next/serve.d.ts +44 -0
  81. package/dist/next/serve.d.ts.map +1 -0
  82. package/dist/next/serve.js +107 -0
  83. package/dist/next/server.d.ts +62 -0
  84. package/dist/next/server.d.ts.map +1 -0
  85. package/dist/next/server.js +127 -0
  86. package/dist/react/connection-context.d.ts +4 -0
  87. package/dist/react/connection-context.d.ts.map +1 -0
  88. package/dist/react/connection-context.js +28 -0
  89. package/dist/react/grid-list.d.ts +34 -0
  90. package/dist/react/grid-list.d.ts.map +1 -0
  91. package/dist/react/grid-list.js +62 -0
  92. package/dist/react/hydrate.d.ts +22 -0
  93. package/dist/react/hydrate.d.ts.map +1 -0
  94. package/dist/react/hydrate.js +18 -0
  95. package/dist/react/index.d.ts +35 -0
  96. package/dist/react/index.d.ts.map +1 -0
  97. package/dist/react/index.js +51 -0
  98. package/dist/react/list.d.ts +31 -0
  99. package/dist/react/list.d.ts.map +1 -0
  100. package/dist/react/list.js +35 -0
  101. package/dist/react/prerendered.d.ts +33 -0
  102. package/dist/react/prerendered.d.ts.map +1 -0
  103. package/dist/react/prerendered.js +165 -0
  104. package/dist/react/provider.d.ts +64 -0
  105. package/dist/react/provider.d.ts.map +1 -0
  106. package/dist/react/provider.js +130 -0
  107. package/dist/react/refusals.d.ts +31 -0
  108. package/dist/react/refusals.d.ts.map +1 -0
  109. package/dist/react/refusals.js +51 -0
  110. package/dist/react/restricted.d.ts +76 -0
  111. package/dist/react/restricted.d.ts.map +1 -0
  112. package/dist/react/restricted.js +126 -0
  113. package/dist/react/use-list.d.ts +42 -0
  114. package/dist/react/use-list.d.ts.map +1 -0
  115. package/dist/react/use-list.js +56 -0
  116. package/dist/react/use-query.d.ts +66 -0
  117. package/dist/react/use-query.d.ts.map +1 -0
  118. package/dist/react/use-query.js +126 -0
  119. package/dist/react/virtual.d.ts +60 -0
  120. package/dist/react/virtual.d.ts.map +1 -0
  121. package/dist/react/virtual.js +131 -0
  122. package/dist/server/api/auth.d.ts +37 -0
  123. package/dist/server/api/auth.d.ts.map +1 -0
  124. package/dist/server/api/auth.js +54 -0
  125. package/dist/server/api/bridge.d.ts +28 -0
  126. package/dist/server/api/bridge.d.ts.map +1 -0
  127. package/dist/server/api/bridge.js +330 -0
  128. package/dist/server/api/collector.d.ts +25 -0
  129. package/dist/server/api/collector.d.ts.map +1 -0
  130. package/dist/server/api/collector.js +184 -0
  131. package/dist/server/api/configure.d.ts +31 -0
  132. package/dist/server/api/configure.d.ts.map +1 -0
  133. package/dist/server/api/configure.js +67 -0
  134. package/dist/server/api/execution.d.ts +77 -0
  135. package/dist/server/api/execution.d.ts.map +1 -0
  136. package/dist/server/api/execution.js +97 -0
  137. package/dist/server/api/list.d.ts +141 -0
  138. package/dist/server/api/list.d.ts.map +1 -0
  139. package/dist/server/api/list.js +281 -0
  140. package/dist/server/api/prerender.d.ts +32 -0
  141. package/dist/server/api/prerender.d.ts.map +1 -0
  142. package/dist/server/api/prerender.js +69 -0
  143. package/dist/server/api/read-keys.d.ts +128 -0
  144. package/dist/server/api/read-keys.d.ts.map +1 -0
  145. package/dist/server/api/read-keys.js +464 -0
  146. package/dist/server/api/read-set.d.ts +103 -0
  147. package/dist/server/api/read-set.d.ts.map +1 -0
  148. package/dist/server/api/read-set.js +210 -0
  149. package/dist/server/api/runtime.d.ts +36 -0
  150. package/dist/server/api/runtime.d.ts.map +1 -0
  151. package/dist/server/api/runtime.js +49 -0
  152. package/dist/server/api/tracked-client.d.ts +6 -0
  153. package/dist/server/api/tracked-client.d.ts.map +1 -0
  154. package/dist/server/api/tracked-client.js +56 -0
  155. package/dist/server/change-source/change-source.d.ts +41 -0
  156. package/dist/server/change-source/change-source.d.ts.map +1 -0
  157. package/dist/server/change-source/change-source.js +2 -0
  158. package/dist/server/change-source/outbox-change-source.d.ts +106 -0
  159. package/dist/server/change-source/outbox-change-source.d.ts.map +1 -0
  160. package/dist/server/change-source/outbox-change-source.js +237 -0
  161. package/dist/server/change-source/wal-change-source.d.ts +85 -0
  162. package/dist/server/change-source/wal-change-source.d.ts.map +1 -0
  163. package/dist/server/change-source/wal-change-source.js +193 -0
  164. package/dist/server/db.d.ts +51 -0
  165. package/dist/server/db.d.ts.map +1 -0
  166. package/dist/server/db.js +53 -0
  167. package/dist/server/evaluate.d.ts +39 -0
  168. package/dist/server/evaluate.d.ts.map +1 -0
  169. package/dist/server/evaluate.js +61 -0
  170. package/dist/server/invalidation-index.d.ts +64 -0
  171. package/dist/server/invalidation-index.d.ts.map +1 -0
  172. package/dist/server/invalidation-index.js +0 -0
  173. package/dist/server/mutator.d.ts +59 -0
  174. package/dist/server/mutator.d.ts.map +1 -0
  175. package/dist/server/mutator.js +77 -0
  176. package/dist/server/query.d.ts +113 -0
  177. package/dist/server/query.d.ts.map +1 -0
  178. package/dist/server/query.js +35 -0
  179. package/dist/server/setup.d.ts +30 -0
  180. package/dist/server/setup.d.ts.map +1 -0
  181. package/dist/server/setup.js +107 -0
  182. package/dist/server/sql/setup.sql +215 -0
  183. package/dist/server/ssr.d.ts +29 -0
  184. package/dist/server/ssr.d.ts.map +1 -0
  185. package/dist/server/ssr.js +43 -0
  186. package/dist/server/sync-engine.d.ts +256 -0
  187. package/dist/server/sync-engine.d.ts.map +1 -0
  188. package/dist/server/sync-engine.js +805 -0
  189. package/dist/server/ws-server.d.ts +56 -0
  190. package/dist/server/ws-server.d.ts.map +1 -0
  191. package/dist/server/ws-server.js +241 -0
  192. package/package.json +81 -0
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ /**
3
+ * What a query read, derived rather than declared.
4
+ *
5
+ * The old `QueryDef.tables` was a hand-maintained list of invalidation
6
+ * dependencies, and a wrong one is invisible: the query simply stops updating.
7
+ * Here the dependency set is what the query *asked for*, recorded while it runs —
8
+ * the same relationship a MobX computed has with the observables it touched.
9
+ *
10
+ * The read set is taken from the Prisma arguments, not from the rows that came
11
+ * back, and that distinction is the whole reason this works for permissions. A
12
+ * user who is not a member reads `ProjectMember` and finds nothing; recording
13
+ * the *intent* still puts `ProjectMember` in the dependency set, so adding them
14
+ * to the project later invalidates the subscription. Recording results would
15
+ * not — there were none.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.ReadSetTracker = void 0;
19
+ exports.datamodelOf = datamodelOf;
20
+ /**
21
+ * The schema, as the Prisma client itself carries it.
22
+ *
23
+ * `Prisma.dmmf.datamodel` says the same thing, but requires the application to
24
+ * import and pass it. The client already knows, so asking it is one less thing
25
+ * to configure and one less thing to get wrong.
26
+ */
27
+ function datamodelOf(prisma) {
28
+ const runtime = prisma?._runtimeDataModel?.models;
29
+ if (!runtime) {
30
+ throw new Error("Could not read the schema from the Prisma client. Pass `datamodel: Prisma.dmmf.datamodel`.");
31
+ }
32
+ return {
33
+ models: Object.entries(runtime).map(([name, model]) => ({
34
+ name,
35
+ dbName: model.dbName ?? null,
36
+ fields: model.fields,
37
+ })),
38
+ };
39
+ }
40
+ /** Prisma operations that write. A `@query` that calls one is a bug, not a warning. */
41
+ const WRITE_OPERATIONS = new Set([
42
+ "create",
43
+ "createMany",
44
+ "createManyAndReturn",
45
+ "update",
46
+ "updateMany",
47
+ "updateManyAndReturn",
48
+ "upsert",
49
+ "delete",
50
+ "deleteMany",
51
+ "executeRaw",
52
+ "executeRawUnsafe",
53
+ "$executeRaw",
54
+ "$executeRawUnsafe",
55
+ ]);
56
+ /** Operations that bypass the model layer, so nothing can be derived from them. */
57
+ const RAW_OPERATIONS = new Set([
58
+ "queryRaw",
59
+ "queryRawUnsafe",
60
+ "$queryRaw",
61
+ "$queryRawUnsafe",
62
+ "$executeRaw",
63
+ "$executeRawUnsafe",
64
+ ]);
65
+ /** Prisma's scalar types, as the three kinds a browser can order by. */
66
+ const SCALAR_KINDS = {
67
+ Int: "number",
68
+ BigInt: "number",
69
+ Float: "number",
70
+ Decimal: "number",
71
+ DateTime: "date",
72
+ Boolean: "boolean",
73
+ };
74
+ class ReadSetTracker {
75
+ constructor(datamodel) {
76
+ /** model → (relation field → relation) */
77
+ this.relations = new Map();
78
+ /** model → (field → the kind a browser can compare it as) */
79
+ this.fieldKinds = new Map();
80
+ /** model → (scalar field → what it is and where it lives) */
81
+ this.scalars = new Map();
82
+ /** model → table name */
83
+ this.tables = new Map();
84
+ /** model → identity field */
85
+ this.idFields = new Map();
86
+ for (const model of datamodel.models) {
87
+ this.tables.set(model.name, model.dbName || model.name);
88
+ const scalars = new Map();
89
+ this.scalars.set(model.name, scalars);
90
+ for (const field of model.fields) {
91
+ // A list column holds many values, so `where: { tags: … }` is a
92
+ // list filter and never the plain equality a read key needs.
93
+ if (field.kind === "object" || field.isList)
94
+ continue;
95
+ scalars.set(field.name, {
96
+ type: field.type,
97
+ kind: field.kind,
98
+ column: field.dbName || field.name,
99
+ });
100
+ }
101
+ const relations = new Map();
102
+ const kinds = new Map();
103
+ this.fieldKinds.set(model.name, kinds);
104
+ for (const field of model.fields) {
105
+ if (field.isId)
106
+ this.idFields.set(model.name, field.name);
107
+ if (field.kind !== "object") {
108
+ // Everything that is not a number, a date or a boolean is
109
+ // text as far as ordering goes — including enums, whose
110
+ // order is the database's too.
111
+ kinds.set(field.name, SCALAR_KINDS[field.type] ?? "text");
112
+ }
113
+ if (field.kind !== "object")
114
+ continue;
115
+ const localKey = field.relationFromFields?.[0];
116
+ relations.set(field.name, {
117
+ field: field.name,
118
+ target: field.type,
119
+ isList: field.isList === true,
120
+ ...(localKey ? { localKey } : {}),
121
+ });
122
+ }
123
+ this.relations.set(model.name, relations);
124
+ }
125
+ }
126
+ /** How a browser may compare a field, or undefined if there is no such field. */
127
+ fieldKind(model, field) {
128
+ return this.fieldKinds.get(model)?.get(field);
129
+ }
130
+ /**
131
+ * Prisma's type name for a scalar field, or undefined when the field is not
132
+ * a scalar of this model — a relation, a list, or something the schema does
133
+ * not have at all.
134
+ */
135
+ fieldType(model, field) {
136
+ return this.scalars.get(model)?.get(field)?.type;
137
+ }
138
+ /** True when the field is an enum, whose values travel as their string label. */
139
+ isEnum(model, field) {
140
+ return this.scalars.get(model)?.get(field)?.kind === "enum";
141
+ }
142
+ /** The column a field is stored in — the name a change event will use. */
143
+ columnFor(model, field) {
144
+ return this.scalars.get(model)?.get(field)?.column ?? field;
145
+ }
146
+ relation(model, field) {
147
+ return this.relations.get(model)?.get(field);
148
+ }
149
+ idField(model) {
150
+ return this.idFields.get(model) ?? "id";
151
+ }
152
+ models() {
153
+ return [...this.tables.keys()];
154
+ }
155
+ relationsOf(model) {
156
+ return [...(this.relations.get(model)?.values() ?? [])];
157
+ }
158
+ tableFor(model) {
159
+ return this.tables.get(model) ?? model;
160
+ }
161
+ isWrite(operation) {
162
+ return WRITE_OPERATIONS.has(operation);
163
+ }
164
+ isRaw(operation) {
165
+ return RAW_OPERATIONS.has(operation);
166
+ }
167
+ /**
168
+ * Record everything one Prisma call touches.
169
+ *
170
+ * Relation names in `where`, `select`, `include`, `orderBy` and friends are
171
+ * followed to their models, so a permission check expressed as a nested
172
+ * filter — `where: { project: { members: { some: { userId } } } }` — lands
173
+ * `Project` and `ProjectMember` in the set without anyone declaring them.
174
+ */
175
+ record(model, args, into) {
176
+ if (!model)
177
+ return;
178
+ into.add(this.tableFor(model));
179
+ this.walk(model, args, into, 0);
180
+ }
181
+ walk(model, value, into, depth) {
182
+ // Prisma rejects deeper nesting long before this; the guard is only here
183
+ // so a cyclic argument object cannot spin forever.
184
+ if (depth > 24 || value === null || typeof value !== "object")
185
+ return;
186
+ if (Array.isArray(value)) {
187
+ for (const item of value)
188
+ this.walk(model, item, into, depth + 1);
189
+ return;
190
+ }
191
+ const relations = this.relations.get(model);
192
+ for (const [key, child] of Object.entries(value)) {
193
+ const related = relations?.get(key)?.target;
194
+ if (related) {
195
+ into.add(this.tableFor(related));
196
+ this.walk(related, child, into, depth + 1);
197
+ continue;
198
+ }
199
+ // Not a relation: `where`, `select`, `AND`, a scalar filter, whatever.
200
+ // Descending with the same model over-approximates at worst, and an
201
+ // over-approximated read set only costs a recomputation.
202
+ this.walk(model, child, into, depth + 1);
203
+ }
204
+ }
205
+ /** Entity name for the rows an operation returns, when it has one. */
206
+ entityFor(model) {
207
+ return model && this.tables.has(model) ? model : undefined;
208
+ }
209
+ }
210
+ exports.ReadSetTracker = ReadSetTracker;
@@ -0,0 +1,36 @@
1
+ import { PrismaSnapshotRunner } from "../db";
2
+ import { type BuiltApi } from "./bridge";
3
+ import { ReadSetTracker, type DataModel } from "./read-set";
4
+ export interface NowityRuntimeConfig {
5
+ /** The application's Prisma client. */
6
+ prisma: any;
7
+ /** Read from the client itself unless given. */
8
+ datamodel?: DataModel;
9
+ /**
10
+ * The class the application injects as its database handle, typically
11
+ * `class Db extends PrismaClient {}`. It is bound to a per-execution view of
12
+ * the client, so a singleton service holding it still talks to the right
13
+ * transaction.
14
+ */
15
+ db?: Function;
16
+ /**
17
+ * The implementations this process serves.
18
+ *
19
+ * Listing them changes nothing a decorator has not already done — a class is
20
+ * registered the moment its module is evaluated. What the list buys is that
21
+ * the import is a real one, visible in the file, and checked: a service that
22
+ * is not here is a service nobody can see was ever wired in, and a class
23
+ * listed without `@api` fails at startup rather than at the first call.
24
+ */
25
+ services?: Function[];
26
+ onWarning?: (message: string) => void;
27
+ }
28
+ export interface NowityRuntime {
29
+ api: BuiltApi;
30
+ snapshots: PrismaSnapshotRunner;
31
+ /** The tracking client — every endpoint read and write goes through it. */
32
+ prisma: any;
33
+ tracker: ReadSetTracker;
34
+ }
35
+ export declare function createNowityRuntime(config: NowityRuntimeConfig): NowityRuntime;
36
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/server/api/runtime.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEnD,OAAO,EAAE,cAAc,EAAe,KAAK,SAAS,EAAE,MAAM,YAAY,CAAC;AAGzE,MAAM,WAAW,mBAAmB;IAChC,uCAAuC;IACvC,MAAM,EAAE,GAAG,CAAC;IACZ,gDAAgD;IAChD,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB;;;;;OAKG;IACH,EAAE,CAAC,EAAE,QAAQ,CAAC;IACd;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAAC;IACtB,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC;AAED,MAAM,WAAW,aAAa;IAC1B,GAAG,EAAE,QAAQ,CAAC;IACd,SAAS,EAAE,oBAAoB,CAAC;IAChC,2EAA2E;IAC3E,MAAM,EAAE,GAAG,CAAC;IACZ,OAAO,EAAE,cAAc,CAAC;CAC3B;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,mBAAmB,GAAG,aAAa,CA+B9E"}
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNowityRuntime = createNowityRuntime;
4
+ /**
5
+ * The read half of the server: contracts, registries, snapshots.
6
+ *
7
+ * Deliberately free of the WebSocket server and the change stream. A Next.js
8
+ * process needs exactly this much to render a page — the endpoints and a way to
9
+ * read them — and nothing here reaches `http` or `ws`, which matters because
10
+ * Next compiles `instrumentation.ts` for the edge runtime too, where neither
11
+ * exists.
12
+ *
13
+ * The sync server is a process of its own ({@link createNowityServer}), which is
14
+ * also the honest shape of the constraint: the App Router has no supported way
15
+ * to take over a connection for a WebSocket upgrade.
16
+ */
17
+ const ironbean_1 = require("ironbean");
18
+ const contract_1 = require("../../api/contract");
19
+ const db_1 = require("../db");
20
+ const bridge_1 = require("./bridge");
21
+ const execution_1 = require("./execution");
22
+ const read_set_1 = require("./read-set");
23
+ const tracked_client_1 = require("./tracked-client");
24
+ function createNowityRuntime(config) {
25
+ const tracker = new read_set_1.ReadSetTracker(config.datamodel ?? (0, read_set_1.datamodelOf)(config.prisma));
26
+ const prisma = (0, tracked_client_1.trackReads)(config.prisma, tracker);
27
+ if (config.db)
28
+ (0, ironbean_1.take)(config.db).setFactory(() => (0, execution_1.ambientPrisma)());
29
+ const contracts = (0, contract_1.resolveContracts)();
30
+ for (const service of config.services ?? []) {
31
+ if (!(0, contract_1.contractOf)(service)) {
32
+ throw new Error(`"${service.name}" is listed as a service but carries no @api(...). ` +
33
+ `Mark it with the contract token it implements.`);
34
+ }
35
+ }
36
+ for (const contract of contracts) {
37
+ if (contract.impl && contract.impl !== contract.contract) {
38
+ (0, ironbean_1.take)(contract.contract).bindTo(contract.impl);
39
+ }
40
+ }
41
+ const context = (0, ironbean_1.getBaseApplicationContext)();
42
+ const api = (0, bridge_1.buildApi)({
43
+ contracts,
44
+ tracker,
45
+ resolve: (contract) => context.getBean(contract),
46
+ onWarning: config.onWarning,
47
+ });
48
+ return { api, snapshots: new db_1.PrismaSnapshotRunner(prisma), prisma, tracker };
49
+ }
@@ -0,0 +1,6 @@
1
+ import type { ReadSetTracker } from "./read-set";
2
+ export interface ExtendablePrisma {
3
+ $extends(extension: unknown): any;
4
+ }
5
+ export declare function trackReads<T extends ExtendablePrisma>(prisma: T, tracker: ReadSetTracker): T;
6
+ //# sourceMappingURL=tracked-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracked-client.d.ts","sourceRoot":"","sources":["../../../src/server/api/tracked-client.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,CAAC,SAAS,EAAE,OAAO,GAAG,GAAG,CAAC;CACrC;AAED,wBAAgB,UAAU,CAAC,CAAC,SAAS,gBAAgB,EAAE,MAAM,EAAE,CAAC,EAAE,OAAO,EAAE,cAAc,GAAG,CAAC,CAoD5F"}
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.trackReads = trackReads;
4
+ /**
5
+ * The Prisma client that watches itself.
6
+ *
7
+ * One extension sits in front of every operation and does three things: it
8
+ * records what was read into the ambient execution, it refuses writes inside a
9
+ * `@query`, and it notes when something happened that it could not interpret.
10
+ *
11
+ * The refusal is worth more than it looks. A `@query` is re-executed on every
12
+ * change to a table it read, so a write hidden inside one would fire again on
13
+ * every invalidation — an accidental infinite loop that is very hard to see from
14
+ * the outside. Better to make it impossible.
15
+ */
16
+ const execution_1 = require("./execution");
17
+ const list_1 = require("./list");
18
+ function trackReads(prisma, tracker) {
19
+ return prisma.$extends({
20
+ name: "nowity-read-set",
21
+ query: {
22
+ async $allOperations({ model, operation, args, query, }) {
23
+ const execution = (0, execution_1.peekExecution)();
24
+ if (!execution)
25
+ return query(args);
26
+ if (execution.kind === "query" && tracker.isWrite(operation)) {
27
+ throw new Error(`A @query method may not write. "${operation}" on ` +
28
+ `"${model ?? "raw"}" was called inside a live query, which is ` +
29
+ `re-executed on every change to the tables it reads.`);
30
+ }
31
+ if (tracker.isRaw(operation) || !model) {
32
+ // Nothing to derive from raw SQL. Say so rather than guess:
33
+ // the subscription falls back to being revalidated always.
34
+ execution.untracked = true;
35
+ }
36
+ else {
37
+ tracker.record(model, args, execution.reads);
38
+ // Recorded from the arguments as the method wrote them. The
39
+ // window pushed in below narrows the rows further, and a
40
+ // narrower read is still covered by the wider key set.
41
+ execution.keys?.record(model, args);
42
+ execution.lastModel = model;
43
+ }
44
+ // The one place a `@list` endpoint is paged: its collection is a
45
+ // `findMany` it wrote without a window, and this is where the
46
+ // window the browser is looking at goes in. Recorded either way,
47
+ // because which call *was* the collection is only knowable once
48
+ // the method has finished.
49
+ if (execution.list && model && operation === "findMany") {
50
+ return query((0, list_1.interceptFindMany)(execution.list, model, args).args);
51
+ }
52
+ return query(args);
53
+ },
54
+ },
55
+ });
56
+ }
@@ -0,0 +1,41 @@
1
+ import type { TransactionBatch } from "../../core/types";
2
+ import type { SnapshotContext } from "../db";
3
+ export type BatchHandler = (batch: TransactionBatch) => Promise<void>;
4
+ /**
5
+ * The single internal interface for change events (§5.1 of the design doc).
6
+ *
7
+ * The engine never learns whether events come from an outbox table or from
8
+ * logical replication. That is the whole point: the outbox is the cheap default,
9
+ * WAL can be swapped in later without touching the sync engine.
10
+ *
11
+ * Contract every implementation must honour:
12
+ * 1. `handler` is called once per database transaction, with commit boundaries
13
+ * preserved and in commit order.
14
+ * 2. `handler` is awaited; no further batch is delivered until it resolves.
15
+ * 3. Delivery is at-least-once. Duplicates are allowed — the engine recomputes
16
+ * queries from the database, so replaying a batch produces an empty diff.
17
+ * 4. `startPosition` must be the *first* statement executed in `snap`, and must
18
+ * return a position from which replay covers everything that a snapshot
19
+ * taken in `snap` may not see.
20
+ */
21
+ export interface ChangeSource {
22
+ readonly name: string;
23
+ /**
24
+ * Whether events carry the client and mutation that caused them.
25
+ *
26
+ * When they do, the only clients whose mutation watermark can have moved in
27
+ * a batch are the ones named in it, so the engine need not ask the database
28
+ * about every open connection on every change. The outbox trigger records
29
+ * it; logical replication cannot, because `set_config` is not in the WAL.
30
+ *
31
+ * Absent means "no", which costs a wider bookkeeping read and never a wrong
32
+ * one.
33
+ */
34
+ readonly attributesWrites?: boolean;
35
+ startPosition(snap: SnapshotContext): Promise<string>;
36
+ start(from: string, handler: BatchHandler): Promise<void>;
37
+ stop(): Promise<void>;
38
+ /** Drain everything currently available. Used by tests to avoid sleeps. */
39
+ drain(): Promise<void>;
40
+ }
41
+ //# sourceMappingURL=change-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"change-source.d.ts","sourceRoot":"","sources":["../../../src/server/change-source/change-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAE7C,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,gBAAgB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,WAAW,YAAY;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB;;;;;;;;;;OAUG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAEpC,aAAa,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEtD,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1D,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtB,2EAA2E;IAC3E,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B"}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,106 @@
1
+ import type { Pool } from "pg";
2
+ import type { SnapshotContext } from "../db";
3
+ import type { BatchHandler, ChangeSource } from "./change-source";
4
+ export interface OutboxChangeSourceOptions {
5
+ pool: Pool;
6
+ /** LISTEN channel used as a doorbell. */
7
+ channel?: string;
8
+ /** Safety-net poll interval; NOTIFY normally wakes the reader first. */
9
+ pollIntervalMs?: number;
10
+ /** Max rows fetched per round-trip (transactions are never split). */
11
+ batchSize?: number;
12
+ /**
13
+ * Identity of this reader in `nowity_consumer`, for retention.
14
+ *
15
+ * Defaults to a fresh id per instance, which is the right default for a
16
+ * process that resumes from the transaction horizon anyway: the row exists
17
+ * to hold rows back while the reader is alive, not to resume it afterwards.
18
+ * Give it a stable name only if you want a restarting node to keep its
19
+ * predecessor's watermark rather than leaving it to age out.
20
+ */
21
+ consumerId?: string;
22
+ /**
23
+ * How often to delete outbox rows every live reader has passed. Off unless
24
+ * set — nothing here deletes data without being asked to.
25
+ */
26
+ pruneIntervalMs?: number;
27
+ /** How long a silent consumer holds retention back. Default one hour. */
28
+ pruneStaleAfter?: string;
29
+ onError?: (err: Error) => void;
30
+ }
31
+ /**
32
+ * Change source built on an outbox table filled by triggers, woken by
33
+ * LISTEN/NOTIFY.
34
+ *
35
+ * The interesting part is the read cursor. `seq` alone is not usable: sequence
36
+ * values are assigned before commit, so ordering by `seq` can walk past a row
37
+ * whose transaction commits later, and that row would then be filtered out by
38
+ * `seq > cursor` forever. Instead the reader only consumes rows whose `xid` is
39
+ * strictly below `pg_snapshot_xmin(pg_current_snapshot())` — the oldest
40
+ * transaction id still in flight. That set has two properties we need:
41
+ *
42
+ * - every transaction in it is committed (nothing below xmin can still be
43
+ * running), and no new row can ever appear with such an `xid`;
44
+ * - it grows as a *prefix* of the `xid` order, so a single `xid` cursor is a
45
+ * complete, gap-free bookmark.
46
+ *
47
+ * Cost of that guarantee: one long-running *write* transaction anywhere in the
48
+ * database stalls the stream until it finishes (read-only transactions do not,
49
+ * they never get an xid). For an application with short transactions this is
50
+ * fine; if it ever stops being fine, that is the moment to switch to the WAL
51
+ * source, which gets true commit ordering from the server.
52
+ */
53
+ export declare class OutboxChangeSource implements ChangeSource {
54
+ readonly name = "outbox";
55
+ /** The trigger stamps every row with the mutation that produced it. */
56
+ readonly attributesWrites = true;
57
+ private readonly pool;
58
+ private readonly channel;
59
+ private readonly pollIntervalMs;
60
+ private readonly batchSize;
61
+ private readonly onError;
62
+ readonly consumerId: string;
63
+ private readonly pruneIntervalMs;
64
+ private readonly pruneStaleAfter;
65
+ private cursor;
66
+ /** Last cursor written to `nowity_consumer`; avoids a write per idle lap. */
67
+ private publishedCursor;
68
+ private handler;
69
+ private listener;
70
+ private timer;
71
+ private pruneTimer;
72
+ private running;
73
+ private draining;
74
+ /** Monotonic "please take another lap" counter, see {@link drain}. */
75
+ private requestSeq;
76
+ private servedSeq;
77
+ constructor(opts: OutboxChangeSourceOptions);
78
+ startPosition(snap: SnapshotContext): Promise<string>;
79
+ start(from: string, handler: BatchHandler): Promise<void>;
80
+ stop(): Promise<void>;
81
+ /**
82
+ * Read and dispatch everything currently eligible.
83
+ *
84
+ * Resolves only after a read that *started* after this call, so a test can
85
+ * write to the database, `await drain()`, and know the change has been
86
+ * handed to the engine. The `requestSeq`/`servedSeq` pair is what makes that
87
+ * true even when a read is already in flight: the running loop takes another
88
+ * lap instead of the caller silently piggybacking on a read that began too
89
+ * early.
90
+ */
91
+ drain(): Promise<void>;
92
+ private wake;
93
+ private drainLoop;
94
+ /** Tell retention where this reader is, when it has moved. */
95
+ private publishCursor;
96
+ /**
97
+ * Delete what every live reader has passed. Returns how many rows went.
98
+ *
99
+ * Safe to run from every node at once: the bound is the slowest live
100
+ * consumer's cursor, so two nodes pruning concurrently delete the same rows
101
+ * rather than each other's.
102
+ */
103
+ prune(): Promise<number>;
104
+ private fetch;
105
+ }
106
+ //# sourceMappingURL=outbox-change-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outbox-change-source.d.ts","sourceRoot":"","sources":["../../../src/server/change-source/outbox-change-source.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAc,MAAM,IAAI,CAAC;AAG3C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAElE,MAAM,WAAW,yBAAyB;IACtC,IAAI,EAAE,IAAI,CAAC;IACX,yCAAyC;IACzC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;;;;OAQG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,yEAAyE;IACzE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;CAClC;AAgBD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,kBAAmB,YAAW,YAAY;IACnD,QAAQ,CAAC,IAAI,YAAY;IACzB,uEAAuE;IACvE,QAAQ,CAAC,gBAAgB,QAAQ;IAEjC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAO;IAC5B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAuB;IAC/C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IACzC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IAEzC,OAAO,CAAC,MAAM,CAAM;IACpB,6EAA6E;IAC7E,OAAO,CAAC,eAAe,CAAuB;IAC9C,OAAO,CAAC,OAAO,CAA6B;IAC5C,OAAO,CAAC,QAAQ,CAA2B;IAC3C,OAAO,CAAC,KAAK,CAA+B;IAC5C,OAAO,CAAC,UAAU,CAA+B;IACjD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAA8B;IAC9C,sEAAsE;IACtE,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,SAAS,CAAK;gBAEV,IAAI,EAAE,yBAAyB;IAWrC,aAAa,CAAC,IAAI,EAAE,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC;IAWrD,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IA6BzD,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAsB3B;;;;;;;;;OASG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAc5B,OAAO,CAAC,IAAI;YAKE,SAAS;IA0BvB,8DAA8D;YAChD,aAAa;IAS3B;;;;;;OAMG;IACG,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC;YAOhB,KAAK;CA6BtB"}