@yielded/auth-persistence 0.1.0-beta.10

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 (182) hide show
  1. package/README.md +27 -0
  2. package/dist/Adapter.d.mts +30 -0
  3. package/dist/Adapter.mjs +25 -0
  4. package/dist/index.d.mts +7 -0
  5. package/dist/index.mjs +7 -0
  6. package/dist/internal/PasswordPreparedPostconditions.d.mts +22 -0
  7. package/dist/internal/PasswordPreparedPostconditions.mjs +12 -0
  8. package/dist/internal/PasswordPreparedPostconditions.mjs.map +1 -0
  9. package/dist/internal/configuration.d.mts +174 -0
  10. package/dist/internal/configuration.mjs +7 -0
  11. package/dist/internal/configuration.mjs.map +1 -0
  12. package/dist/internal/email-kernel.d.mts +275 -0
  13. package/dist/internal/email-kernel.mjs +487 -0
  14. package/dist/internal/email-kernel.mjs.map +1 -0
  15. package/dist/internal/mapping-error.d.mts +10 -0
  16. package/dist/internal/mapping-error.mjs +30 -0
  17. package/dist/internal/mapping-error.mjs.map +1 -0
  18. package/dist/internal/models/common.d.mts +12 -0
  19. package/dist/internal/models/email-model.d.mts +353 -0
  20. package/dist/internal/models/email-model.mjs +21 -0
  21. package/dist/internal/models/email-model.mjs.map +1 -0
  22. package/dist/internal/models/passkey-model.d.mts +266 -0
  23. package/dist/internal/models/passkey-model.mjs +34 -0
  24. package/dist/internal/models/passkey-model.mjs.map +1 -0
  25. package/dist/internal/models/passkey-registration-ceremony-model.d.mts +49 -0
  26. package/dist/internal/models/passkey-registration-ceremony-model.mjs +18 -0
  27. package/dist/internal/models/passkey-registration-ceremony-model.mjs.map +1 -0
  28. package/dist/internal/models/passkey-write-model.d.mts +189 -0
  29. package/dist/internal/models/passkey-write-model.mjs +13 -0
  30. package/dist/internal/models/passkey-write-model.mjs.map +1 -0
  31. package/dist/internal/models/password-model.d.mts +328 -0
  32. package/dist/internal/models/password-model.mjs +23 -0
  33. package/dist/internal/models/password-model.mjs.map +1 -0
  34. package/dist/internal/models/proof-model.d.mts +285 -0
  35. package/dist/internal/models/proof-model.mjs +17 -0
  36. package/dist/internal/models/proof-model.mjs.map +1 -0
  37. package/dist/internal/models/session-model.d.mts +199 -0
  38. package/dist/internal/models/session-model.mjs +20 -0
  39. package/dist/internal/models/session-model.mjs.map +1 -0
  40. package/dist/internal/models/step-up-model.d.mts +66 -0
  41. package/dist/internal/models/step-up-model.mjs +9 -0
  42. package/dist/internal/models/step-up-model.mjs.map +1 -0
  43. package/dist/internal/oauth-app.d.mts +11 -0
  44. package/dist/internal/oauth-app.mjs +57 -0
  45. package/dist/internal/oauth-app.mjs.map +1 -0
  46. package/dist/internal/oauth-server.d.mts +10 -0
  47. package/dist/internal/oauth-server.mjs +66 -0
  48. package/dist/internal/oauth-server.mjs.map +1 -0
  49. package/dist/internal/passkey/admission.d.mts +6 -0
  50. package/dist/internal/passkey/admission.mjs +216 -0
  51. package/dist/internal/passkey/admission.mjs.map +1 -0
  52. package/dist/internal/passkey/credentials.d.mts +14 -0
  53. package/dist/internal/passkey/credentials.mjs +249 -0
  54. package/dist/internal/passkey/credentials.mjs.map +1 -0
  55. package/dist/internal/passkey/enrollment.mjs +138 -0
  56. package/dist/internal/passkey/enrollment.mjs.map +1 -0
  57. package/dist/internal/passkey/flow.d.mts +21 -0
  58. package/dist/internal/passkey/flow.mjs +452 -0
  59. package/dist/internal/passkey/flow.mjs.map +1 -0
  60. package/dist/internal/passkey/management.mjs +231 -0
  61. package/dist/internal/passkey/management.mjs.map +1 -0
  62. package/dist/internal/passkey/registration-ceremony.d.mts +9 -0
  63. package/dist/internal/passkey/registration-ceremony.mjs +129 -0
  64. package/dist/internal/passkey/registration-ceremony.mjs.map +1 -0
  65. package/dist/internal/passkey/registration-custody.d.mts +2 -0
  66. package/dist/internal/passkey/registration-custody.mjs +52 -0
  67. package/dist/internal/passkey/registration-custody.mjs.map +1 -0
  68. package/dist/internal/passkey/registration-write.mjs +211 -0
  69. package/dist/internal/passkey/registration-write.mjs.map +1 -0
  70. package/dist/internal/passkey/state.d.mts +10 -0
  71. package/dist/internal/passkey/state.mjs +234 -0
  72. package/dist/internal/passkey/state.mjs.map +1 -0
  73. package/dist/internal/passkey/target.d.mts +19 -0
  74. package/dist/internal/passkey/target.mjs +190 -0
  75. package/dist/internal/passkey/target.mjs.map +1 -0
  76. package/dist/internal/passkey/write-state.d.mts +17 -0
  77. package/dist/internal/passkey/write-state.mjs +345 -0
  78. package/dist/internal/passkey/write-state.mjs.map +1 -0
  79. package/dist/internal/passkey/write-target.mjs +192 -0
  80. package/dist/internal/passkey/write-target.mjs.map +1 -0
  81. package/dist/internal/passkey-kernel.d.mts +5592 -0
  82. package/dist/internal/passkey-kernel.mjs +49 -0
  83. package/dist/internal/passkey-kernel.mjs.map +1 -0
  84. package/dist/internal/passkeys.d.mts +7 -0
  85. package/dist/internal/passkeys.mjs +368 -0
  86. package/dist/internal/passkeys.mjs.map +1 -0
  87. package/dist/internal/password-kernel.d.mts +290 -0
  88. package/dist/internal/password-kernel.mjs +704 -0
  89. package/dist/internal/password-kernel.mjs.map +1 -0
  90. package/dist/internal/persistence.d.mts +25 -0
  91. package/dist/internal/persistence.mjs +291 -0
  92. package/dist/internal/persistence.mjs.map +1 -0
  93. package/dist/internal/phone-kernel.d.mts +162 -0
  94. package/dist/internal/phone-kernel.mjs +434 -0
  95. package/dist/internal/phone-kernel.mjs.map +1 -0
  96. package/dist/internal/proof-kernel.d.mts +93 -0
  97. package/dist/internal/proof-kernel.mjs +619 -0
  98. package/dist/internal/proof-kernel.mjs.map +1 -0
  99. package/dist/internal/query-operations.d.mts +61 -0
  100. package/dist/internal/registration-contract.d.mts +16 -0
  101. package/dist/internal/registration.mjs +66 -0
  102. package/dist/internal/registration.mjs.map +1 -0
  103. package/dist/internal/session-kernel.d.mts +48 -0
  104. package/dist/internal/session-kernel.mjs +737 -0
  105. package/dist/internal/session-kernel.mjs.map +1 -0
  106. package/dist/internal/sql-persistence.d.mts +10 -0
  107. package/dist/internal/sql-persistence.mjs +37 -0
  108. package/dist/internal/sql-persistence.mjs.map +1 -0
  109. package/dist/internal/sql-query.mjs +207 -0
  110. package/dist/internal/sql-query.mjs.map +1 -0
  111. package/dist/internal/sql-table.d.mts +36 -0
  112. package/dist/internal/sql-table.mjs +81 -0
  113. package/dist/internal/sql-table.mjs.map +1 -0
  114. package/dist/internal/standalone.d.mts +9 -0
  115. package/dist/internal/standalone.mjs +13 -0
  116. package/dist/internal/standalone.mjs.map +1 -0
  117. package/dist/internal/step-up-state.d.mts +49 -0
  118. package/dist/internal/step-up-state.mjs +32 -0
  119. package/dist/internal/step-up-state.mjs.map +1 -0
  120. package/dist/internal/storage-mapping.mjs +686 -0
  121. package/dist/internal/storage-mapping.mjs.map +1 -0
  122. package/dist/internal/storage-tables.d.mts +913 -0
  123. package/dist/internal/storage-tables.mjs +387 -0
  124. package/dist/internal/storage-tables.mjs.map +1 -0
  125. package/dist/internal/storage-validation.mjs +58 -0
  126. package/dist/internal/storage-validation.mjs.map +1 -0
  127. package/dist/internal/transaction-execution-kernel.d.mts +38 -0
  128. package/dist/internal/transaction-execution-kernel.mjs +116 -0
  129. package/dist/internal/transaction-execution-kernel.mjs.map +1 -0
  130. package/dist/internal/transaction-kernel.d.mts +77 -0
  131. package/dist/internal/transaction-kernel.mjs +260 -0
  132. package/dist/internal/transaction-kernel.mjs.map +1 -0
  133. package/package.json +1 -0
  134. package/src/Adapter.ts +291 -0
  135. package/src/index.ts +6 -0
  136. package/src/internal/PasswordPreparedPostconditions.ts +30 -0
  137. package/src/internal/configuration.ts +282 -0
  138. package/src/internal/email-kernel.ts +1535 -0
  139. package/src/internal/mapping-error.ts +36 -0
  140. package/src/internal/models/common.ts +11 -0
  141. package/src/internal/models/email-model.ts +559 -0
  142. package/src/internal/models/passkey-model.ts +390 -0
  143. package/src/internal/models/passkey-registration-ceremony-model.ts +72 -0
  144. package/src/internal/models/passkey-write-model.ts +297 -0
  145. package/src/internal/models/password-model.ts +513 -0
  146. package/src/internal/models/proof-model.ts +424 -0
  147. package/src/internal/models/session-model.ts +375 -0
  148. package/src/internal/models/step-up-model.ts +135 -0
  149. package/src/internal/oauth-app.ts +82 -0
  150. package/src/internal/oauth-server.ts +89 -0
  151. package/src/internal/passkey/admission.ts +361 -0
  152. package/src/internal/passkey/credentials.ts +511 -0
  153. package/src/internal/passkey/enrollment.ts +326 -0
  154. package/src/internal/passkey/flow.ts +1062 -0
  155. package/src/internal/passkey/management.ts +421 -0
  156. package/src/internal/passkey/registration-ceremony.ts +283 -0
  157. package/src/internal/passkey/registration-custody.ts +91 -0
  158. package/src/internal/passkey/registration-write.ts +426 -0
  159. package/src/internal/passkey/state.ts +353 -0
  160. package/src/internal/passkey/target.ts +586 -0
  161. package/src/internal/passkey/write-state.ts +681 -0
  162. package/src/internal/passkey/write-target.ts +452 -0
  163. package/src/internal/passkey-kernel.ts +104 -0
  164. package/src/internal/passkeys.ts +606 -0
  165. package/src/internal/password-kernel.ts +2124 -0
  166. package/src/internal/persistence.ts +588 -0
  167. package/src/internal/phone-kernel.ts +846 -0
  168. package/src/internal/proof-kernel.ts +1954 -0
  169. package/src/internal/query-operations.ts +81 -0
  170. package/src/internal/registration-contract.ts +22 -0
  171. package/src/internal/registration.ts +161 -0
  172. package/src/internal/session-kernel.ts +2217 -0
  173. package/src/internal/sql-persistence.ts +45 -0
  174. package/src/internal/sql-query.ts +298 -0
  175. package/src/internal/sql-table.ts +104 -0
  176. package/src/internal/standalone.ts +30 -0
  177. package/src/internal/step-up-state.ts +139 -0
  178. package/src/internal/storage-mapping.ts +708 -0
  179. package/src/internal/storage-tables.ts +408 -0
  180. package/src/internal/storage-validation.ts +117 -0
  181. package/src/internal/transaction-execution-kernel.ts +313 -0
  182. package/src/internal/transaction-kernel.ts +593 -0
@@ -0,0 +1,387 @@
1
+ import { Schema } from "effect";
2
+ //#region src/internal/storage-tables.ts
3
+ const StorageColumn = Schema.Struct({
4
+ name: Schema.NonEmptyString,
5
+ type: Schema.Literals([
6
+ "text",
7
+ "integer",
8
+ "boolean"
9
+ ]),
10
+ nullable: Schema.optionalKey(Schema.Boolean)
11
+ });
12
+ const StorageTable = Schema.Struct({
13
+ name: Schema.NonEmptyString,
14
+ schema: Schema.optionalKey(Schema.NonEmptyString),
15
+ columns: Schema.Record(Schema.String, StorageColumn),
16
+ unique: Schema.Array(Schema.Array(Schema.String))
17
+ });
18
+ const text = { type: "text" };
19
+ const integer = { type: "integer" };
20
+ const boolean = { type: "boolean" };
21
+ const optionalText = {
22
+ ...text,
23
+ nullable: true
24
+ };
25
+ const optionalInteger = {
26
+ ...integer,
27
+ nullable: true
28
+ };
29
+ const spec = (columns, unique) => ({
30
+ columns,
31
+ unique
32
+ });
33
+ /** Logical roles are independent of table names and migration ownership. */
34
+ const storageTables = {
35
+ subjects: spec({
36
+ id: text,
37
+ active: boolean,
38
+ securityRevision: text
39
+ }, [["id"]]),
40
+ identifiers: spec({
41
+ namespace: text,
42
+ value: text,
43
+ subjectId: text,
44
+ revision: text,
45
+ verifiedAt: optionalInteger,
46
+ active: boolean
47
+ }, [["namespace", "value"]]),
48
+ credentials: spec({
49
+ credentialId: text,
50
+ subjectId: text,
51
+ revision: text,
52
+ active: boolean
53
+ }, [["credentialId"]]),
54
+ passwords: spec({
55
+ moduleId: text,
56
+ subjectId: text,
57
+ credentialId: text,
58
+ credentialRevision: text,
59
+ verifierVersion: text,
60
+ verifier: text,
61
+ normalization: text
62
+ }, [["moduleId", "subjectId"], ["moduleId", "credentialId"]]),
63
+ passwordAttempts: spec({
64
+ moduleId: text,
65
+ action: text,
66
+ attemptId: text,
67
+ identifierNamespace: text,
68
+ identifierValue: text,
69
+ subjectId: optionalText,
70
+ credentialId: optionalText,
71
+ securityRevision: optionalText,
72
+ credentialRevision: optionalText,
73
+ verifierVersion: optionalText,
74
+ identifierBindingRevision: optionalText,
75
+ admittedAt: integer,
76
+ deadline: integer,
77
+ retentionUntil: integer,
78
+ state: text
79
+ }, [["moduleId", "attemptId"]]),
80
+ passwordScopes: spec({
81
+ moduleId: text,
82
+ action: text,
83
+ scopeKind: text,
84
+ scopeKey: text
85
+ }, [[
86
+ "moduleId",
87
+ "action",
88
+ "scopeKind",
89
+ "scopeKey"
90
+ ]]),
91
+ passwordCharges: spec({
92
+ moduleId: text,
93
+ action: text,
94
+ scopeKind: text,
95
+ scopeKey: text,
96
+ attemptId: text,
97
+ occurredAt: integer,
98
+ retentionUntil: integer
99
+ }, [[
100
+ "moduleId",
101
+ "action",
102
+ "scopeKind",
103
+ "scopeKey",
104
+ "attemptId"
105
+ ]]),
106
+ passwordCommands: spec({
107
+ moduleId: text,
108
+ commandId: text,
109
+ action: text,
110
+ bindingDigest: text,
111
+ decision: text,
112
+ retentionUntil: integer
113
+ }, [["moduleId", "commandId"]]),
114
+ passwordRegistrations: spec({
115
+ moduleId: text,
116
+ requestId: text
117
+ }, [["moduleId", "requestId"]]),
118
+ emailCredentials: spec({
119
+ moduleId: text,
120
+ subjectId: text,
121
+ credentialId: text,
122
+ identifierNamespace: text,
123
+ identifierValue: text,
124
+ credentialRevision: text,
125
+ active: boolean
126
+ }, [["moduleId", "credentialId"], [
127
+ "moduleId",
128
+ "identifierNamespace",
129
+ "identifierValue"
130
+ ]]),
131
+ emailCommands: spec({
132
+ moduleId: text,
133
+ commandId: text,
134
+ action: text,
135
+ bindingDigest: text,
136
+ retentionUntil: integer
137
+ }, [["moduleId", "commandId"]]),
138
+ phoneState: spec({
139
+ scope: text,
140
+ state: text,
141
+ version: text
142
+ }, [["scope"]]),
143
+ passkeyCredentials: spec({
144
+ credentialId: text,
145
+ subjectId: text,
146
+ rpId: text,
147
+ protocolCredentialId: text,
148
+ credentialKey: text,
149
+ handleKey: text,
150
+ userHandle: text,
151
+ publicKey: text,
152
+ algorithm: integer,
153
+ profile: text,
154
+ credentialRevision: text,
155
+ active: boolean,
156
+ primarySignIn: boolean,
157
+ enrollmentUserVerified: boolean,
158
+ backupEligible: boolean,
159
+ backupState: boolean,
160
+ counter: integer,
161
+ maximumCounter: integer,
162
+ name: text,
163
+ createdAt: integer,
164
+ lastUsedAt: optionalInteger
165
+ }, [["credentialId"], ["credentialKey"]]),
166
+ passkeyOwnership: spec({
167
+ credentialKey: text,
168
+ rpId: text,
169
+ protocolCredentialId: text,
170
+ subjectId: optionalText,
171
+ credentialId: optionalText,
172
+ state: text,
173
+ version: text,
174
+ reservationId: optionalText
175
+ }, [["credentialKey"]]),
176
+ passkeyHandles: spec({
177
+ handleKey: text,
178
+ rpId: text,
179
+ userHandle: text,
180
+ subjectId: optionalText,
181
+ state: text,
182
+ version: text,
183
+ reservationId: optionalText
184
+ }, [["handleKey"], ["rpId", "subjectId"]]),
185
+ passkeyModules: spec({
186
+ moduleId: text,
187
+ active: boolean,
188
+ policyRevision: text,
189
+ policy: text
190
+ }, [["moduleId"]]),
191
+ passkeyFlows: spec({
192
+ moduleId: text,
193
+ flowId: text,
194
+ commandId: text,
195
+ purpose: text,
196
+ state: text,
197
+ version: text,
198
+ generation: integer,
199
+ snapshot: text,
200
+ policySnapshot: text,
201
+ requestBindingVerifier: text,
202
+ requestBindingExpiresAt: integer,
203
+ issuedAt: integer,
204
+ expiresAt: integer,
205
+ retentionUntil: integer,
206
+ claimId: optionalText,
207
+ claimedAt: optionalInteger,
208
+ claimExpiresAt: optionalInteger,
209
+ credentialSnapshot: optionalText,
210
+ subjectScope: optionalText,
211
+ targetScope: optionalText
212
+ }, [["moduleId", "flowId"], ["moduleId", "commandId"]]),
213
+ passkeyAdmissions: spec({
214
+ authorityScope: text,
215
+ moduleId: text,
216
+ version: text,
217
+ ownerMarker: text,
218
+ admittedAt: optionalInteger
219
+ }, [["authorityScope", "moduleId"]]),
220
+ passkeyCharges: spec({
221
+ moduleId: text,
222
+ flowId: text,
223
+ purpose: text,
224
+ kind: text,
225
+ scope: text,
226
+ originalWindowMillis: integer,
227
+ admittedAt: optionalInteger,
228
+ retainUntil: optionalInteger,
229
+ version: text,
230
+ ownerMarker: text
231
+ }, [[
232
+ "moduleId",
233
+ "flowId",
234
+ "kind"
235
+ ]]),
236
+ passkeyCommands: spec({
237
+ moduleId: text,
238
+ commandId: text,
239
+ subjectId: text,
240
+ credentialId: text,
241
+ intent: text,
242
+ decision: text,
243
+ retentionUntil: integer,
244
+ version: text
245
+ }, [["moduleId", "commandId"]]),
246
+ proofRequests: spec({
247
+ moduleId: text,
248
+ requestId: text,
249
+ fingerprint: text,
250
+ proofId: text,
251
+ purpose: text,
252
+ keyId: text,
253
+ createdAt: integer,
254
+ retentionUntil: integer,
255
+ receipt: text
256
+ }, [["moduleId", "requestId"]]),
257
+ proofSeries: spec({
258
+ moduleId: text,
259
+ purpose: text,
260
+ scopeKey: text,
261
+ activeProofId: optionalText,
262
+ lastIssueAt: optionalInteger,
263
+ version: text
264
+ }, [[
265
+ "moduleId",
266
+ "purpose",
267
+ "scopeKey"
268
+ ]]),
269
+ proofGenerations: spec({
270
+ moduleId: text,
271
+ purpose: text,
272
+ proofId: text,
273
+ requestId: text,
274
+ seriesKey: text,
275
+ deliveryId: text,
276
+ binding: text,
277
+ verifierKeyId: text,
278
+ verifierDigest: text,
279
+ issuedAt: integer,
280
+ expiresAt: integer,
281
+ version: text,
282
+ state: text,
283
+ sendCount: integer,
284
+ deliveryState: text,
285
+ claimVersion: optionalText,
286
+ claimDeadline: optionalInteger,
287
+ retryAt: optionalInteger,
288
+ deliveryRetryMillis: integer,
289
+ retentionUntil: integer,
290
+ fingerprint: text
291
+ }, [["moduleId", "proofId"], ["moduleId", "deliveryId"]]),
292
+ proofContinuations: spec({
293
+ moduleId: text,
294
+ purpose: text,
295
+ continuationId: text,
296
+ digest: text,
297
+ proofId: text,
298
+ seriesKey: text,
299
+ binding: text,
300
+ expiresAt: integer,
301
+ consumed: boolean,
302
+ version: text,
303
+ retentionUntil: integer
304
+ }, [["moduleId", "continuationId"], ["moduleId", "digest"]]),
305
+ proofScopes: spec({
306
+ moduleId: text,
307
+ purpose: text,
308
+ action: text,
309
+ scopeKind: text,
310
+ scopeKey: text
311
+ }, [[
312
+ "moduleId",
313
+ "purpose",
314
+ "action",
315
+ "scopeKind",
316
+ "scopeKey"
317
+ ]]),
318
+ proofAbuse: spec({
319
+ moduleId: text,
320
+ purpose: text,
321
+ action: text,
322
+ scopeKind: text,
323
+ scopeKey: text,
324
+ commandId: text,
325
+ occurredAt: integer,
326
+ retentionUntil: integer
327
+ }, [[
328
+ "moduleId",
329
+ "action",
330
+ "scopeKind",
331
+ "scopeKey",
332
+ "commandId"
333
+ ]]),
334
+ proofFailures: spec({
335
+ moduleId: text,
336
+ purpose: text,
337
+ seriesKey: text,
338
+ commandId: text,
339
+ occurredAt: integer,
340
+ retentionUntil: integer
341
+ }, [[
342
+ "moduleId",
343
+ "seriesKey",
344
+ "commandId"
345
+ ]]),
346
+ proofCommands: spec({
347
+ moduleId: text,
348
+ commandId: text,
349
+ kind: text,
350
+ decision: text,
351
+ retentionUntil: integer
352
+ }, [["moduleId", "commandId"]]),
353
+ sessions: spec({
354
+ sessionId: text,
355
+ subjectId: text,
356
+ digest: text,
357
+ version: text,
358
+ securityRevision: text,
359
+ issuedAt: integer,
360
+ expiresAt: integer,
361
+ absoluteExpiresAt: integer,
362
+ record: text
363
+ }, [["sessionId"], ["digest"]]),
364
+ sessionFlows: spec({
365
+ flowId: text,
366
+ subjectId: text,
367
+ state: text,
368
+ pendingDigest: optionalText,
369
+ dedupUntil: integer
370
+ }, [["flowId"]])
371
+ };
372
+ const tableDefinition = (role, name, subjectType = "text") => {
373
+ const table = storageTables[role];
374
+ return {
375
+ name,
376
+ columns: Object.fromEntries(Object.entries(table.columns).map(([key, column]) => [key, {
377
+ ...column,
378
+ name: key.replace(/[A-Z]/g, (letter) => "_" + letter.toLowerCase()),
379
+ ...key === "subjectId" ? { type: subjectType } : {}
380
+ }])),
381
+ unique: table.unique
382
+ };
383
+ };
384
+ //#endregion
385
+ export { StorageColumn, StorageTable, storageTables, tableDefinition };
386
+
387
+ //# sourceMappingURL=storage-tables.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-tables.mjs","names":[],"sources":["../../src/internal/storage-tables.ts"],"sourcesContent":["import { Schema } from \"effect\";\n\nexport const StorageColumn = Schema.Struct({\n name: Schema.NonEmptyString,\n type: Schema.Literals([\"text\", \"integer\", \"boolean\"]),\n nullable: Schema.optionalKey(Schema.Boolean),\n});\n\nexport const StorageTable = Schema.Struct({\n name: Schema.NonEmptyString,\n schema: Schema.optionalKey(Schema.NonEmptyString),\n columns: Schema.Record(Schema.String, StorageColumn),\n unique: Schema.Array(Schema.Array(Schema.String)),\n});\n\nexport type StorageTable = typeof StorageTable.Type;\n\nconst text = { type: \"text\" as const };\nconst integer = { type: \"integer\" as const };\nconst boolean = { type: \"boolean\" as const };\nconst optionalText = { ...text, nullable: true };\nconst optionalInteger = { ...integer, nullable: true };\n\nconst spec = <C extends Readonly<Record<string, Omit<typeof StorageColumn.Type, \"name\">>>>(\n columns: C,\n unique: ReadonlyArray<ReadonlyArray<Extract<keyof C, string>>>,\n) => ({ columns, unique });\n\n/** Logical roles are independent of table names and migration ownership. */\nexport const storageTables = {\n subjects: spec({ id: text, active: boolean, securityRevision: text }, [[\"id\"]]),\n identifiers: spec(\n {\n namespace: text,\n value: text,\n subjectId: text,\n revision: text,\n verifiedAt: optionalInteger,\n active: boolean,\n },\n [[\"namespace\", \"value\"]],\n ),\n credentials: spec({ credentialId: text, subjectId: text, revision: text, active: boolean }, [\n [\"credentialId\"],\n ]),\n passwords: spec(\n {\n moduleId: text,\n subjectId: text,\n credentialId: text,\n credentialRevision: text,\n verifierVersion: text,\n verifier: text,\n normalization: text,\n },\n [\n [\"moduleId\", \"subjectId\"],\n [\"moduleId\", \"credentialId\"],\n ],\n ),\n passwordAttempts: spec(\n {\n moduleId: text,\n action: text,\n attemptId: text,\n identifierNamespace: text,\n identifierValue: text,\n subjectId: optionalText,\n credentialId: optionalText,\n securityRevision: optionalText,\n credentialRevision: optionalText,\n verifierVersion: optionalText,\n identifierBindingRevision: optionalText,\n admittedAt: integer,\n deadline: integer,\n retentionUntil: integer,\n state: text,\n },\n [[\"moduleId\", \"attemptId\"]],\n ),\n passwordScopes: spec({ moduleId: text, action: text, scopeKind: text, scopeKey: text }, [\n [\"moduleId\", \"action\", \"scopeKind\", \"scopeKey\"],\n ]),\n passwordCharges: spec(\n {\n moduleId: text,\n action: text,\n scopeKind: text,\n scopeKey: text,\n attemptId: text,\n occurredAt: integer,\n retentionUntil: integer,\n },\n [[\"moduleId\", \"action\", \"scopeKind\", \"scopeKey\", \"attemptId\"]],\n ),\n passwordCommands: spec(\n {\n moduleId: text,\n commandId: text,\n action: text,\n bindingDigest: text,\n decision: text,\n retentionUntil: integer,\n },\n [[\"moduleId\", \"commandId\"]],\n ),\n passwordRegistrations: spec({ moduleId: text, requestId: text }, [[\"moduleId\", \"requestId\"]]),\n emailCredentials: spec(\n {\n moduleId: text,\n subjectId: text,\n credentialId: text,\n identifierNamespace: text,\n identifierValue: text,\n credentialRevision: text,\n active: boolean,\n },\n [\n [\"moduleId\", \"credentialId\"],\n [\"moduleId\", \"identifierNamespace\", \"identifierValue\"],\n ],\n ),\n emailCommands: spec(\n { moduleId: text, commandId: text, action: text, bindingDigest: text, retentionUntil: integer },\n [[\"moduleId\", \"commandId\"]],\n ),\n phoneState: spec({ scope: text, state: text, version: text }, [[\"scope\"]]),\n passkeyCredentials: spec(\n {\n credentialId: text,\n subjectId: text,\n rpId: text,\n protocolCredentialId: text,\n credentialKey: text,\n handleKey: text,\n userHandle: text,\n publicKey: text,\n algorithm: integer,\n profile: text,\n credentialRevision: text,\n active: boolean,\n primarySignIn: boolean,\n enrollmentUserVerified: boolean,\n backupEligible: boolean,\n backupState: boolean,\n counter: integer,\n maximumCounter: integer,\n name: text,\n createdAt: integer,\n lastUsedAt: optionalInteger,\n },\n [[\"credentialId\"], [\"credentialKey\"]],\n ),\n passkeyOwnership: spec(\n {\n credentialKey: text,\n rpId: text,\n protocolCredentialId: text,\n subjectId: optionalText,\n credentialId: optionalText,\n state: text,\n version: text,\n reservationId: optionalText,\n },\n [[\"credentialKey\"]],\n ),\n passkeyHandles: spec(\n {\n handleKey: text,\n rpId: text,\n userHandle: text,\n subjectId: optionalText,\n state: text,\n version: text,\n reservationId: optionalText,\n },\n [[\"handleKey\"], [\"rpId\", \"subjectId\"]],\n ),\n passkeyModules: spec(\n {\n moduleId: text,\n active: boolean,\n policyRevision: text,\n policy: text,\n },\n [[\"moduleId\"]],\n ),\n passkeyFlows: spec(\n {\n moduleId: text,\n flowId: text,\n commandId: text,\n purpose: text,\n state: text,\n version: text,\n generation: integer,\n snapshot: text,\n policySnapshot: text,\n requestBindingVerifier: text,\n requestBindingExpiresAt: integer,\n issuedAt: integer,\n expiresAt: integer,\n retentionUntil: integer,\n claimId: optionalText,\n claimedAt: optionalInteger,\n claimExpiresAt: optionalInteger,\n credentialSnapshot: optionalText,\n subjectScope: optionalText,\n targetScope: optionalText,\n },\n [\n [\"moduleId\", \"flowId\"],\n [\"moduleId\", \"commandId\"],\n ],\n ),\n passkeyAdmissions: spec(\n {\n authorityScope: text,\n moduleId: text,\n version: text,\n ownerMarker: text,\n admittedAt: optionalInteger,\n },\n [[\"authorityScope\", \"moduleId\"]],\n ),\n passkeyCharges: spec(\n {\n moduleId: text,\n flowId: text,\n purpose: text,\n kind: text,\n scope: text,\n originalWindowMillis: integer,\n admittedAt: optionalInteger,\n retainUntil: optionalInteger,\n version: text,\n ownerMarker: text,\n },\n [[\"moduleId\", \"flowId\", \"kind\"]],\n ),\n passkeyCommands: spec(\n {\n moduleId: text,\n commandId: text,\n subjectId: text,\n credentialId: text,\n intent: text,\n decision: text,\n retentionUntil: integer,\n version: text,\n },\n [[\"moduleId\", \"commandId\"]],\n ),\n proofRequests: spec(\n {\n moduleId: text,\n requestId: text,\n fingerprint: text,\n proofId: text,\n purpose: text,\n keyId: text,\n createdAt: integer,\n retentionUntil: integer,\n receipt: text,\n },\n [[\"moduleId\", \"requestId\"]],\n ),\n proofSeries: spec(\n {\n moduleId: text,\n purpose: text,\n scopeKey: text,\n activeProofId: optionalText,\n lastIssueAt: optionalInteger,\n version: text,\n },\n [[\"moduleId\", \"purpose\", \"scopeKey\"]],\n ),\n proofGenerations: spec(\n {\n moduleId: text,\n purpose: text,\n proofId: text,\n requestId: text,\n seriesKey: text,\n deliveryId: text,\n binding: text,\n verifierKeyId: text,\n verifierDigest: text,\n issuedAt: integer,\n expiresAt: integer,\n version: text,\n state: text,\n sendCount: integer,\n deliveryState: text,\n claimVersion: optionalText,\n claimDeadline: optionalInteger,\n retryAt: optionalInteger,\n deliveryRetryMillis: integer,\n retentionUntil: integer,\n fingerprint: text,\n },\n [\n [\"moduleId\", \"proofId\"],\n [\"moduleId\", \"deliveryId\"],\n ],\n ),\n proofContinuations: spec(\n {\n moduleId: text,\n purpose: text,\n continuationId: text,\n digest: text,\n proofId: text,\n seriesKey: text,\n binding: text,\n expiresAt: integer,\n consumed: boolean,\n version: text,\n retentionUntil: integer,\n },\n [\n [\"moduleId\", \"continuationId\"],\n [\"moduleId\", \"digest\"],\n ],\n ),\n proofScopes: spec(\n { moduleId: text, purpose: text, action: text, scopeKind: text, scopeKey: text },\n [[\"moduleId\", \"purpose\", \"action\", \"scopeKind\", \"scopeKey\"]],\n ),\n proofAbuse: spec(\n {\n moduleId: text,\n purpose: text,\n action: text,\n scopeKind: text,\n scopeKey: text,\n commandId: text,\n occurredAt: integer,\n retentionUntil: integer,\n },\n [[\"moduleId\", \"action\", \"scopeKind\", \"scopeKey\", \"commandId\"]],\n ),\n proofFailures: spec(\n {\n moduleId: text,\n purpose: text,\n seriesKey: text,\n commandId: text,\n occurredAt: integer,\n retentionUntil: integer,\n },\n [[\"moduleId\", \"seriesKey\", \"commandId\"]],\n ),\n proofCommands: spec(\n { moduleId: text, commandId: text, kind: text, decision: text, retentionUntil: integer },\n [[\"moduleId\", \"commandId\"]],\n ),\n sessions: spec(\n {\n sessionId: text,\n subjectId: text,\n digest: text,\n version: text,\n securityRevision: text,\n issuedAt: integer,\n expiresAt: integer,\n absoluteExpiresAt: integer,\n record: text,\n },\n [[\"sessionId\"], [\"digest\"]],\n ),\n sessionFlows: spec(\n {\n flowId: text,\n subjectId: text,\n state: text,\n pendingDigest: optionalText,\n dedupUntil: integer,\n },\n [[\"flowId\"]],\n ),\n} as const;\n\nexport type StorageRole = keyof typeof storageTables;\n\nexport const tableDefinition = (\n role: StorageRole,\n name: string,\n subjectType: \"text\" | \"integer\" = \"text\",\n): StorageTable => {\n const table = storageTables[role];\n\n return {\n name,\n columns: Object.fromEntries(\n Object.entries(table.columns).map(([key, column]) => [\n key,\n {\n ...column,\n name: key.replace(/[A-Z]/g, (letter) => \"_\" + letter.toLowerCase()),\n ...(key === \"subjectId\" ? { type: subjectType } : {}),\n },\n ]),\n ),\n unique: table.unique,\n };\n};\n"],"mappings":";;AAEA,MAAa,gBAAgB,OAAO,OAAO;CACzC,MAAM,OAAO;CACb,MAAM,OAAO,SAAS;EAAC;EAAQ;EAAW;CAAS,CAAC;CACpD,UAAU,OAAO,YAAY,OAAO,OAAO;AAC7C,CAAC;AAED,MAAa,eAAe,OAAO,OAAO;CACxC,MAAM,OAAO;CACb,QAAQ,OAAO,YAAY,OAAO,cAAc;CAChD,SAAS,OAAO,OAAO,OAAO,QAAQ,aAAa;CACnD,QAAQ,OAAO,MAAM,OAAO,MAAM,OAAO,MAAM,CAAC;AAClD,CAAC;AAID,MAAM,OAAO,EAAE,MAAM,OAAgB;AACrC,MAAM,UAAU,EAAE,MAAM,UAAmB;AAC3C,MAAM,UAAU,EAAE,MAAM,UAAmB;AAC3C,MAAM,eAAe;CAAE,GAAG;CAAM,UAAU;AAAK;AAC/C,MAAM,kBAAkB;CAAE,GAAG;CAAS,UAAU;AAAK;AAErD,MAAM,QACJ,SACA,YACI;CAAE;CAAS;AAAO;;AAGxB,MAAa,gBAAgB;CAC3B,UAAU,KAAK;EAAE,IAAI;EAAM,QAAQ;EAAS,kBAAkB;CAAK,GAAG,CAAC,CAAC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B,MAAM,QAAQ,cAAc;CAE5B,OAAO;EACL;EACA,SAAS,OAAO,YACd,OAAO,QAAQ,MAAM,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,YAAY,CACnD,KACA;GACE,GAAG;GACH,MAAM,IAAI,QAAQ,WAAW,WAAW,MAAM,OAAO,YAAY,CAAC;GAClE,GAAI,QAAQ,cAAc,EAAE,MAAM,YAAY,IAAI,CAAC;EACrD,CACF,CAAC,CACH;EACA,QAAQ,MAAM;CAChB;AACF"}
@@ -0,0 +1,58 @@
1
+ import { PersistenceConfigurationError } from "./configuration.mjs";
2
+ import { Effect, Schema } from "effect";
3
+ //#region src/internal/storage-validation.ts
4
+ const Column = Schema.Struct({
5
+ name: Schema.String,
6
+ pk: Schema.Int
7
+ });
8
+ const Index = Schema.Struct({
9
+ name: Schema.String,
10
+ unique: Schema.Int,
11
+ partial: Schema.Int
12
+ });
13
+ const IndexColumn = Schema.Struct({ name: Schema.NullOr(Schema.String) });
14
+ const PgColumns = Schema.Array(Schema.Struct({ name: Schema.String }));
15
+ const PgKeys = Schema.Array(Schema.Struct({ columns: Schema.Array(Schema.String) }));
16
+ const quote = (value) => "\"" + value.replaceAll("\"", "\"\"") + "\"";
17
+ const qualifiedTableName = (table) => (table.schema === void 0 ? "" : quote(table.schema) + ".") + quote(table.name);
18
+ /** Validate physical uniqueness before the first authentication operation. A
19
+ * partial or expression index cannot establish these unconditional guarantees. */
20
+ const validateStorage = (client, dialect, table, required) => Effect.gen(function* () {
21
+ const physicalKeys = yield* dialect === "sqlite" ? Effect.gen(function* () {
22
+ if (table.schema !== void 0 && table.schema !== "main") return yield* PersistenceConfigurationError.make({ reason: "SQLite storage must belong to the main database" });
23
+ const columns = yield* client`select name, pk from pragma_table_info(${table.name})`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Column))));
24
+ for (const column of Object.values(table.columns)) if (!columns.some((actual) => actual.name === column.name)) return yield* PersistenceConfigurationError.make({ reason: `Missing SQL column ${table.name}.${column.name}` });
25
+ const keys = [];
26
+ const primary = columns.filter((column) => column.pk > 0).sort((a, b) => a.pk - b.pk);
27
+ if (primary.length > 0) keys.push(primary.map((column) => column.name));
28
+ const indexes = yield* client`select name, "unique", partial from pragma_index_list(${table.name})`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Index))));
29
+ for (const index of indexes) {
30
+ if (index.unique !== 1 || index.partial !== 0) continue;
31
+ const columns = yield* client`select name from pragma_index_info(${index.name})`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(IndexColumn))));
32
+ if (columns.every((column) => column.name !== null)) keys.push(columns.flatMap((column) => column.name === null ? [] : [column.name]));
33
+ }
34
+ return keys;
35
+ }) : Effect.gen(function* () {
36
+ const relation = qualifiedTableName(table);
37
+ const columns = yield* client`select attname as name from pg_attribute where attrelid = to_regclass(${relation}) and attnum > 0 and not attisdropped`.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PgColumns)));
38
+ for (const column of Object.values(table.columns)) if (!columns.some((actual) => actual.name === column.name)) return yield* PersistenceConfigurationError.make({ reason: `Missing SQL column ${relation}.${column.name}` });
39
+ return (yield* client`
40
+ select array_agg(a.attname order by k.ordinality) as columns
41
+ from pg_index i
42
+ cross join lateral unnest(i.indkey) with ordinality as k(attnum, ordinality)
43
+ join pg_attribute a on a.attrelid = i.indrelid and a.attnum = k.attnum
44
+ where i.indrelid = to_regclass(${relation}) and i.indisunique and i.indisvalid
45
+ and i.indimmediate and i.indpred is null and i.indexprs is null
46
+ and k.ordinality <= i.indnkeyatts
47
+ group by i.indexrelid
48
+ `.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PgKeys)))).map((index) => index.columns);
49
+ });
50
+ for (const keys of required) {
51
+ const columns = keys.map((key) => table.columns[key]?.name);
52
+ if (columns.some((column) => column === void 0) || !physicalKeys.some((actual) => actual.length === columns.length && actual.every((column) => columns.includes(column)))) return yield* PersistenceConfigurationError.make({ reason: `Missing unique key on ${table.name} (${keys.join(", ")})` });
53
+ }
54
+ }).pipe(Effect.mapError((error) => Schema.is(PersistenceConfigurationError)(error) ? error : PersistenceConfigurationError.make({ reason: `Cannot validate SQL storage for ${table.name}` })));
55
+ //#endregion
56
+ export { qualifiedTableName, validateStorage };
57
+
58
+ //# sourceMappingURL=storage-validation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-validation.mjs","names":[],"sources":["../../src/internal/storage-validation.ts"],"sourcesContent":["import { Effect, Schema } from \"effect\";\nimport type { SqlClient } from \"effect/unstable/sql/SqlClient\";\n\nimport { PersistenceConfigurationError } from \"./configuration\";\nimport type { StorageTable } from \"./storage-tables\";\n\nconst Column = Schema.Struct({ name: Schema.String, pk: Schema.Int });\nconst Index = Schema.Struct({ name: Schema.String, unique: Schema.Int, partial: Schema.Int });\nconst IndexColumn = Schema.Struct({ name: Schema.NullOr(Schema.String) });\nconst PgColumns = Schema.Array(Schema.Struct({ name: Schema.String }));\nconst PgKeys = Schema.Array(Schema.Struct({ columns: Schema.Array(Schema.String) }));\nconst quote = (value: string) => '\"' + value.replaceAll('\"', '\"\"') + '\"';\n\nexport const qualifiedTableName = (table: Pick<StorageTable, \"name\" | \"schema\">) =>\n (table.schema === undefined ? \"\" : quote(table.schema) + \".\") + quote(table.name);\n\n/** Validate physical uniqueness before the first authentication operation. A\n * partial or expression index cannot establish these unconditional guarantees. */\nexport const validateStorage = (\n client: SqlClient,\n dialect: \"pg\" | \"sqlite\",\n table: StorageTable,\n required: ReadonlyArray<ReadonlyArray<string>>,\n) =>\n Effect.gen(function* () {\n const physicalKeys: ReadonlyArray<ReadonlyArray<string>> = yield* dialect === \"sqlite\"\n ? Effect.gen(function* () {\n if (table.schema !== undefined && table.schema !== \"main\")\n return yield* PersistenceConfigurationError.make({\n reason: \"SQLite storage must belong to the main database\",\n });\n\n const columns = yield* client`select name, pk from pragma_table_info(${table.name})`.pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Column))),\n );\n\n for (const column of Object.values(table.columns)) {\n if (!columns.some((actual) => actual.name === column.name))\n return yield* PersistenceConfigurationError.make({\n reason: `Missing SQL column ${table.name}.${column.name}`,\n });\n }\n const keys: string[][] = [];\n const primary = columns.filter((column) => column.pk > 0).sort((a, b) => a.pk - b.pk);\n\n if (primary.length > 0) keys.push(primary.map((column) => column.name));\n\n const indexes =\n yield* client`select name, \"unique\", partial from pragma_index_list(${table.name})`.pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Index))),\n );\n\n for (const index of indexes) {\n if (index.unique !== 1 || index.partial !== 0) continue;\n\n const columns = yield* client`select name from pragma_index_info(${index.name})`.pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(IndexColumn))),\n );\n\n if (columns.every((column) => column.name !== null))\n keys.push(columns.flatMap((column) => (column.name === null ? [] : [column.name])));\n }\n\n return keys;\n })\n : Effect.gen(function* () {\n const relation = qualifiedTableName(table);\n\n const columns =\n yield* client`select attname as name from pg_attribute where attrelid = to_regclass(${relation}) and attnum > 0 and not attisdropped`.pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(PgColumns)),\n );\n\n for (const column of Object.values(table.columns)) {\n if (!columns.some((actual) => actual.name === column.name))\n return yield* PersistenceConfigurationError.make({\n reason: `Missing SQL column ${relation}.${column.name}`,\n });\n }\n\n const indexes = yield* client`\n select array_agg(a.attname order by k.ordinality) as columns\n from pg_index i\n cross join lateral unnest(i.indkey) with ordinality as k(attnum, ordinality)\n join pg_attribute a on a.attrelid = i.indrelid and a.attnum = k.attnum\n where i.indrelid = to_regclass(${relation}) and i.indisunique and i.indisvalid\n and i.indimmediate and i.indpred is null and i.indexprs is null\n and k.ordinality <= i.indnkeyatts\n group by i.indexrelid\n `.pipe(Effect.flatMap(Schema.decodeUnknownEffect(PgKeys)));\n\n return indexes.map((index) => index.columns);\n });\n\n for (const keys of required) {\n const columns = keys.map((key) => table.columns[key]?.name);\n\n if (\n columns.some((column) => column === undefined) ||\n !physicalKeys.some(\n (actual) =>\n actual.length === columns.length && actual.every((column) => columns.includes(column)),\n )\n )\n return yield* PersistenceConfigurationError.make({\n reason: `Missing unique key on ${table.name} (${keys.join(\", \")})`,\n });\n }\n }).pipe(\n Effect.mapError((error) =>\n Schema.is(PersistenceConfigurationError)(error)\n ? error\n : PersistenceConfigurationError.make({\n reason: `Cannot validate SQL storage for ${table.name}`,\n }),\n ),\n );\n"],"mappings":";;;AAMA,MAAM,SAAS,OAAO,OAAO;CAAE,MAAM,OAAO;CAAQ,IAAI,OAAO;AAAI,CAAC;AACpE,MAAM,QAAQ,OAAO,OAAO;CAAE,MAAM,OAAO;CAAQ,QAAQ,OAAO;CAAK,SAAS,OAAO;AAAI,CAAC;AAC5F,MAAM,cAAc,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,OAAO,MAAM,EAAE,CAAC;AACxE,MAAM,YAAY,OAAO,MAAM,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC;AACrE,MAAM,SAAS,OAAO,MAAM,OAAO,OAAO,EAAE,SAAS,OAAO,MAAM,OAAO,MAAM,EAAE,CAAC,CAAC;AACnF,MAAM,SAAS,UAAkB,OAAM,MAAM,WAAW,MAAK,MAAI,IAAI;AAErE,MAAa,sBAAsB,WAChC,MAAM,WAAW,KAAA,IAAY,KAAK,MAAM,MAAM,MAAM,IAAI,OAAO,MAAM,MAAM,IAAI;;;AAIlF,MAAa,mBACX,QACA,SACA,OACA,aAEA,OAAO,IAAI,aAAa;CACtB,MAAM,eAAqD,OAAO,YAAY,WAC1E,OAAO,IAAI,aAAa;EACtB,IAAI,MAAM,WAAW,KAAA,KAAa,MAAM,WAAW,QACjD,OAAO,OAAO,8BAA8B,KAAK,EAC/C,QAAQ,kDACV,CAAC;EAEH,MAAM,UAAU,OAAO,MAAM,0CAA0C,MAAM,KAAK,GAAG,KACnF,OAAO,QAAQ,OAAO,oBAAoB,OAAO,MAAM,MAAM,CAAC,CAAC,CACjE;EAEA,KAAK,MAAM,UAA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AAsB,SAAS,GAAG,OAAO,OACnD,CAAC;EAcL,QAAO,OAXgB,MAAM;;;;;2CAKI,SAAS;;;;UAI1C,KAAK,OAAO,QAAQ,OAAO,oBAAoB,MAAM,CAAC,CAAC,EAAA,CAExC,KAAK,UAAU,MAAM,OAAO;CAC7C,CAAC;CAEL,KAAK,MAAM,QAAQ,UAAU;EAC3B,MAAM,UAAU,KAAK,KAAK,QAAQ,MAAM,QAAQ,IAAI,EAAE,IAAI;EAE1D,IACE,QAAQ,MAAM,WAAW,WAAW,KAAA,CAAS,KAC7C,CAAC,aAAa,MACX,WACC,OAAO,WAAW,QAAQ,UAAU,OAAO,OAAO,WAAW,QAAQ,SAAS,MAAM,CAAC,CACzF,GAEA,OAAO,OAAO,8BAA8B,KAAK,EAC/C,QAAQ,yBAAyB,MAAM,KAAK,IAAI,KAAK,KAAK,IAAI,EAAE,GAClE,CAAC;CACL;AACF,CAAC,CAAC,CAAC,KACD,OAAO,UAAU,UACf,OAAO,GAAG,6BAA6B,CAAC,CAAC,KAAK,IAC1C,QACA,8BAA8B,KAAK,EACjC,QAAQ,mCAAmC,MAAM,OACnD,CAAC,CACP,CACF"}
@@ -0,0 +1,38 @@
1
+ import { TransactionNativeDatabase, TransactionOwner, makeTransactionKernel } from "./transaction-kernel.mjs";
2
+ import { Context, Effect } from "effect";
3
+ import { CurrentCommitJournal, HookConfigurationError, LifecycleHooks } from "@yielded/auth/Hooks";
4
+ import { Statement } from "effect/unstable/sql/Statement";
5
+ import * as SqlClient from "effect/unstable/sql/SqlClient";
6
+ import * as SqlError$1 from "effect/unstable/sql/SqlError";
7
+ //#region src/internal/transaction-execution-kernel.d.ts
8
+ export interface TransactionTargetConfiguration<Failure> {
9
+ readonly mode: "interactive" | "synchronous" | "batch";
10
+ readonly dialect: "pg" | "mysql" | "sqlite";
11
+ readonly locking: boolean;
12
+ readonly standaloneGuard: (database: any) => Effect.Effect<void, Failure>;
13
+ readonly transaction?: <A, E, R>(database: any, body: (transaction: any) => Effect.Effect<A, E, R>) => Effect.Effect<A, E | SqlError$1.SqlError | Failure, R>;
14
+ }
15
+ export type TransactionCoordinatorError<E, Failure> = E | Failure | HookConfigurationError | SqlError$1.SqlError;
16
+ export interface TransactionBound<Failure> {
17
+ readonly owner: TransactionOwner<Failure>;
18
+ used: boolean;
19
+ poisoned: boolean;
20
+ active: boolean;
21
+ inFlight: number;
22
+ }
23
+ export interface TransactionExecution<Failure, OwnerId, Requirements = LifecycleHooks> {
24
+ readonly bound: boolean;
25
+ readonly active: () => boolean;
26
+ readonly admit: Effect.Effect<void, Failure>;
27
+ readonly poison: () => void;
28
+ readonly run: <A, E, R>(body: Effect.Effect<A, E, R>, mutation?: boolean) => Effect.Effect<A, Failure, Exclude<R, OwnerId | CurrentCommitJournal> | Requirements>;
29
+ }
30
+ export declare const makeTransactionExecutionKernel: (transactions: Pick<ReturnType<typeof makeTransactionKernel>, "makeTransactionOwner" | "reportTransactionFailure">) => {
31
+ sqlClientTransactionStandaloneGuard: <Failure>(unavailable: () => Failure, database: {
32
+ readonly $client: Pick<SqlClient.SqlClient, "transactionService">;
33
+ }) => Effect.Effect<void, Failure, never>;
34
+ makeTransactionExecution: <Failure, OwnerId>(ownerTag: Context.Key<OwnerId, TransactionOwner<Failure>>, database: TransactionNativeDatabase, configuration: TransactionTargetConfiguration<Failure>, unavailable: () => Failure, nonce: () => string, bound?: TransactionBound<Failure>) => TransactionExecution<Failure, OwnerId>;
35
+ coordinateTransactionOwner: <Failure, OwnerId, Resources, AllocationError, Services, Transaction, A, E, R>(database: TransactionNativeDatabase, ownerTag: Context.Key<OwnerId, TransactionOwner<Failure>>, configuration: TransactionTargetConfiguration<Failure>, allocate: Effect.Effect<Resources, AllocationError>, unavailable: () => Failure, nonce: () => string, services: (execution: TransactionExecution<Failure, OwnerId>, resources: Resources) => Services, owner: (transaction: Transaction, services: Services, append: (statement: Statement<any>) => void) => Effect.Effect<A, E, R>) => Effect.Effect<A, TransactionCoordinatorError<E, Failure>, Exclude<R, CurrentCommitJournal> | LifecycleHooks>;
36
+ };
37
+ //#endregion
38
+ //# sourceMappingURL=transaction-execution-kernel.d.mts.map
@@ -0,0 +1,116 @@
1
+ import { requireStandalone } from "./standalone.mjs";
2
+ import { Context, Effect } from "effect";
3
+ import { CurrentCommitJournal, coordinateCommit, hasCommitScope } from "@yielded/auth/Hooks";
4
+ //#region src/internal/transaction-execution-kernel.ts
5
+ const makeTransactionExecutionKernel = (transactions) => {
6
+ const { makeTransactionOwner, reportTransactionFailure } = transactions;
7
+ const sqlClientTransactionStandaloneGuard = (unavailable, database) => requireStandalone(unavailable, database.$client);
8
+ const makeTransactionExecution = (ownerTag, database, configuration, unavailable, nonce, bound) => {
9
+ const invariant = (value) => {
10
+ if (!value) throw unavailable();
11
+ };
12
+ return {
13
+ bound: bound !== void 0,
14
+ active: () => bound === void 0 || bound.active,
15
+ admit: bound !== void 0 ? Effect.suspend(() => bound.active ? Effect.void : Effect.fail(unavailable())) : Effect.gen(function* () {
16
+ if (yield* hasCommitScope) return yield* Effect.fail(unavailable());
17
+ yield* configuration.standaloneGuard(database);
18
+ }),
19
+ poison: () => {
20
+ if (bound !== void 0) bound.poisoned = true;
21
+ },
22
+ run: (body, mutation = true) => {
23
+ return Effect.suspend(() => {
24
+ let entered = false;
25
+ return (bound !== void 0 ? Effect.gen(function* () {
26
+ if (!bound.active) return yield* Effect.fail(unavailable());
27
+ entered = true;
28
+ bound.inFlight++;
29
+ if (!mutation) return yield* Effect.provideContext(body, Context.make(ownerTag, bound.owner).pipe(Context.add(CurrentCommitJournal, bound.owner.journal)));
30
+ invariant(!bound.used && !bound.poisoned);
31
+ bound.used = true;
32
+ return (yield* coordinateCommit((journal) => Effect.gen(function* () {
33
+ bound.owner.guards.push(journal.prepare(void 0));
34
+ return yield* Effect.provideContext(body, Context.make(ownerTag, {
35
+ ...bound.owner,
36
+ journal
37
+ }).pipe(Context.add(CurrentCommitJournal, journal)));
38
+ }), { mode: configuration.mode })).value;
39
+ }).pipe(Effect.onExit((exit) => Effect.sync(() => {
40
+ if (entered) bound.inFlight--;
41
+ if (exit._tag === "Failure") bound.poisoned = true;
42
+ }))) : Effect.gen(function* () {
43
+ if (yield* hasCommitScope) return yield* Effect.fail(unavailable());
44
+ yield* configuration.standaloneGuard(database);
45
+ const marker = nonce();
46
+ return (yield* coordinateCommit((journal) => {
47
+ const run = (tx) => Effect.gen(function* () {
48
+ const owner = makeTransactionOwner(tx, journal, marker, unavailable, {
49
+ client: database.$client,
50
+ batch: configuration.mode === "batch",
51
+ locking: configuration.locking,
52
+ mysql: configuration.dialect === "mysql",
53
+ dialect: configuration.dialect
54
+ });
55
+ const value = yield* Effect.provideContext(body, Context.make(ownerTag, owner).pipe(Context.add(CurrentCommitJournal, journal)));
56
+ yield* owner.finish();
57
+ if (configuration.mode === "batch") yield* tx.$client.batch(owner.statements);
58
+ return value;
59
+ });
60
+ return configuration.mode === "batch" ? run(database) : configuration.transaction !== void 0 ? configuration.transaction(database, run) : database.transaction(run);
61
+ }, { mode: configuration.mode })).value;
62
+ })).pipe((operation) => reportTransactionFailure(operation, unavailable), Effect.mapError(unavailable), Effect.catchDefect(() => Effect.fail(unavailable())));
63
+ });
64
+ }
65
+ };
66
+ };
67
+ const coordinateTransactionOwner = (database, ownerTag, configuration, allocate, unavailable, nonce, services, owner) => {
68
+ return Effect.gen(function* () {
69
+ if (yield* hasCommitScope) return yield* Effect.fail(unavailable());
70
+ yield* configuration.standaloneGuard(database);
71
+ const resources = yield* allocate.pipe((operation) => reportTransactionFailure(operation, unavailable), Effect.mapError(unavailable), Effect.catchDefect(() => Effect.fail(unavailable())));
72
+ const marker = nonce();
73
+ return (yield* coordinateCommit((journal) => {
74
+ const run = (tx) => Effect.gen(function* () {
75
+ const state = makeTransactionOwner(tx, journal, marker, unavailable, {
76
+ client: database.$client,
77
+ batch: configuration.mode === "batch",
78
+ dialect: configuration.dialect,
79
+ mysql: configuration.dialect === "mysql",
80
+ locking: configuration.locking
81
+ });
82
+ const bound = {
83
+ owner: state,
84
+ used: false,
85
+ poisoned: false,
86
+ active: true,
87
+ inFlight: 0
88
+ };
89
+ return yield* Effect.gen(function* () {
90
+ const value = yield* owner(tx, services(makeTransactionExecution(ownerTag, tx, configuration, unavailable, nonce, bound), resources), (statement) => {
91
+ if (!bound.active) throw unavailable();
92
+ state.statements.push(statement);
93
+ });
94
+ bound.active = false;
95
+ if (bound.poisoned || bound.inFlight !== 0) return yield* Effect.fail(unavailable());
96
+ yield* state.finish();
97
+ if (configuration.mode === "batch") yield* tx.$client.batch(state.statements);
98
+ return value;
99
+ }).pipe(Effect.ensuring(Effect.sync(() => {
100
+ bound.active = false;
101
+ })));
102
+ });
103
+ return configuration.mode === "batch" ? run(database) : configuration.transaction !== void 0 ? configuration.transaction(database, run) : database.transaction(run);
104
+ }, { mode: configuration.mode })).value;
105
+ });
106
+ };
107
+ return {
108
+ sqlClientTransactionStandaloneGuard,
109
+ makeTransactionExecution,
110
+ coordinateTransactionOwner
111
+ };
112
+ };
113
+ //#endregion
114
+ export { makeTransactionExecutionKernel };
115
+
116
+ //# sourceMappingURL=transaction-execution-kernel.mjs.map