@terreno/api 57.2.0 → 57.3.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 (277) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/api.d.ts +4 -0
  4. package/dist/api.js +12 -24
  5. package/dist/auth.d.ts +23 -10
  6. package/dist/auth.js +97 -32
  7. package/dist/authRecovery.d.ts +5 -0
  8. package/dist/authRecovery.js +350 -0
  9. package/dist/authTokens.d.ts +8 -0
  10. package/dist/authTokens.js +162 -0
  11. package/dist/betterAuth.d.ts +33 -0
  12. package/dist/betterAuthApp.d.ts +4 -0
  13. package/dist/betterAuthApp.js +26 -8
  14. package/dist/betterAuthSetup.d.ts +44 -2
  15. package/dist/betterAuthSetup.js +288 -18
  16. package/dist/collectionRegistry.d.ts +38 -0
  17. package/dist/collectionRegistry.js +72 -0
  18. package/dist/configurationApp.d.ts +11 -2
  19. package/dist/configurationApp.js +2 -4
  20. package/dist/docLoader.js +35 -6
  21. package/dist/expressServer.d.ts +26 -3
  22. package/dist/expressServer.js +79 -11
  23. package/dist/index.d.ts +16 -0
  24. package/dist/index.js +38 -2
  25. package/dist/mcp/auth.d.ts +1 -0
  26. package/dist/mcp/auth.js +47 -25
  27. package/dist/mcp/handlers.d.ts +1 -1
  28. package/dist/mcp/handlers.js +67 -233
  29. package/dist/mcp/query.d.ts +2 -2
  30. package/dist/mcp/registry.d.ts +1 -5
  31. package/dist/mcp/registry.js +31 -20
  32. package/dist/mcp/schemaGenerator.d.ts +2 -7
  33. package/dist/mcp/schemaGenerator.js +41 -116
  34. package/dist/mcp/server.d.ts +1 -0
  35. package/dist/mcp/server.js +1 -0
  36. package/dist/mcp/serviceTokens.d.ts +16 -0
  37. package/dist/mcp/serviceTokens.js +345 -0
  38. package/dist/mcp/types.d.ts +2 -2
  39. package/dist/models/mcpServiceToken.d.ts +3 -0
  40. package/dist/models/mcpServiceToken.js +208 -0
  41. package/dist/openApiBuilder.d.ts +5 -4
  42. package/dist/openApiBuilder.js +61 -8
  43. package/dist/openApiCompat.js +1 -1
  44. package/dist/openApiValidator.js +0 -2
  45. package/dist/plugins.d.ts +14 -1
  46. package/dist/plugins.js +17 -6
  47. package/dist/populate.d.ts +2 -2
  48. package/dist/populate.js +47 -42
  49. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  50. package/dist/rateLimit/applyTrustProxy.js +17 -0
  51. package/dist/rateLimit/createStore.d.ts +2 -0
  52. package/dist/rateLimit/createStore.js +28 -0
  53. package/dist/rateLimit/memoryStore.d.ts +2 -0
  54. package/dist/rateLimit/memoryStore.js +108 -0
  55. package/dist/rateLimit/middleware.d.ts +11 -0
  56. package/dist/rateLimit/middleware.js +110 -0
  57. package/dist/rateLimit/mongoStore.d.ts +3 -0
  58. package/dist/rateLimit/mongoStore.js +122 -0
  59. package/dist/rateLimit/policies.d.ts +14 -0
  60. package/dist/rateLimit/policies.js +151 -0
  61. package/dist/rateLimit/redisStore.d.ts +3 -0
  62. package/dist/rateLimit/redisStore.js +155 -0
  63. package/dist/rateLimit/types.d.ts +54 -0
  64. package/dist/rateLimit/types.js +9 -0
  65. package/dist/rbac/access.js +5 -1
  66. package/dist/rbac/assertAllowed.d.ts +9 -0
  67. package/dist/rbac/assertAllowed.js +182 -0
  68. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  69. package/dist/rbac/modelRouterAccess.js +8 -4
  70. package/dist/rbac/permissionUtils.js +3 -2
  71. package/dist/rbac/resolve.js +5 -4
  72. package/dist/rbac/routes.js +15 -6
  73. package/dist/realtime/deprecation.d.ts +12 -0
  74. package/dist/realtime/deprecation.js +32 -0
  75. package/dist/realtime/realtimeApp.d.ts +1 -1
  76. package/dist/realtime/realtimeApp.js +10 -11
  77. package/dist/realtime/registry.d.ts +0 -31
  78. package/dist/realtime/registry.js +44 -31
  79. package/dist/realtime/socketAuth.d.ts +5 -5
  80. package/dist/realtime/socketAuth.js +11 -1
  81. package/dist/realtime/socketUser.d.ts +5 -1
  82. package/dist/realtime/types.d.ts +14 -4
  83. package/dist/schemaMetadata.d.ts +56 -0
  84. package/dist/schemaMetadata.js +513 -0
  85. package/dist/seedRunner.d.ts +88 -0
  86. package/dist/seedRunner.js +627 -0
  87. package/dist/sync/executors.d.ts +12 -2
  88. package/dist/sync/executors.js +8 -10
  89. package/dist/sync/loadHarness.js +28 -19
  90. package/dist/sync/models.js +26 -24
  91. package/dist/sync/mutationHandler.d.ts +9 -0
  92. package/dist/sync/mutationHandler.js +11 -6
  93. package/dist/sync/registrationSideEffects.d.ts +35 -0
  94. package/dist/sync/registrationSideEffects.js +151 -0
  95. package/dist/sync/registry.d.ts +2 -52
  96. package/dist/sync/registry.js +38 -187
  97. package/dist/sync/routes.js +3 -2
  98. package/dist/sync/scripts/compactTombstones.js +0 -2
  99. package/dist/sync/syncApp.d.ts +3 -3
  100. package/dist/sync/syncApp.js +4 -4
  101. package/dist/sync/syncBatch.js +3 -2
  102. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  103. package/dist/sync/syncSeqPlugin.js +20 -16
  104. package/dist/terrenoApp.d.ts +19 -5
  105. package/dist/terrenoApp.js +66 -18
  106. package/dist/tests/models.d.ts +2 -0
  107. package/dist/tests/models.js +6 -0
  108. package/dist/types/authToken.d.ts +33 -0
  109. package/dist/types/authToken.js +2 -0
  110. package/dist/types/mcpServiceToken.d.ts +41 -0
  111. package/dist/types/mcpServiceToken.js +2 -0
  112. package/dist/webhooks/headerValue.d.ts +2 -0
  113. package/dist/webhooks/headerValue.js +14 -0
  114. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  115. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  116. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  117. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  118. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  119. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  120. package/dist/webhooks/rawBody.d.ts +14 -0
  121. package/dist/webhooks/rawBody.js +22 -0
  122. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  123. package/dist/webhooks/timingSafeEqual.js +17 -0
  124. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  125. package/dist/webhooks/verifiers/hmac.js +49 -0
  126. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  127. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  128. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  129. package/dist/webhooks/verifiers/stripe.js +99 -0
  130. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  131. package/dist/webhooks/verifiers/twilio.js +112 -0
  132. package/dist/webhooks/webhooksApp.d.ts +33 -0
  133. package/dist/webhooks/webhooksApp.js +195 -0
  134. package/package.json +4 -5
  135. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  136. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  137. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  138. package/src/actions.ts +20 -13
  139. package/src/adminModelRouter.test.ts +133 -0
  140. package/src/api.arrayOperations.test.ts +43 -31
  141. package/src/api.hooks.test.ts +38 -29
  142. package/src/api.query.test.ts +31 -31
  143. package/src/api.test.ts +95 -96
  144. package/src/api.ts +16 -27
  145. package/src/auth.test.ts +107 -51
  146. package/src/auth.ts +98 -29
  147. package/src/authRecovery.test.ts +281 -0
  148. package/src/authRecovery.ts +279 -0
  149. package/src/authTokens.test.ts +94 -0
  150. package/src/authTokens.ts +118 -0
  151. package/src/authVerification.test.ts +293 -0
  152. package/src/betterAuth.ts +24 -0
  153. package/src/betterAuthApp.test.ts +1 -0
  154. package/src/betterAuthApp.ts +27 -9
  155. package/src/betterAuthSetup.test.ts +568 -38
  156. package/src/betterAuthSetup.ts +260 -5
  157. package/src/collectionRegistry.test.ts +165 -0
  158. package/src/collectionRegistry.ts +115 -0
  159. package/src/configurationApp.ts +13 -7
  160. package/src/docLoader.test.ts +45 -1
  161. package/src/docLoader.ts +37 -6
  162. package/src/express.d.ts +1 -0
  163. package/src/expressServer.test.ts +130 -66
  164. package/src/expressServer.ts +75 -19
  165. package/src/githubAuth.test.ts +60 -55
  166. package/src/index.ts +58 -0
  167. package/src/mcp/auth.test.ts +47 -0
  168. package/src/mcp/auth.ts +32 -11
  169. package/src/mcp/handlers.ts +45 -172
  170. package/src/mcp/integration.test.ts +59 -9
  171. package/src/mcp/query.ts +2 -4
  172. package/src/mcp/registry.ts +29 -20
  173. package/src/mcp/schemaGenerator.test.ts +8 -0
  174. package/src/mcp/schemaGenerator.ts +49 -131
  175. package/src/mcp/server.ts +2 -0
  176. package/src/mcp/serviceTokens.test.ts +330 -0
  177. package/src/mcp/serviceTokens.ts +307 -0
  178. package/src/mcp/toolGenerator.test.ts +1 -1
  179. package/src/mcp/types.ts +2 -6
  180. package/src/models/mcpServiceToken.test.ts +129 -0
  181. package/src/models/mcpServiceToken.ts +158 -0
  182. package/src/openApi.test.ts +80 -64
  183. package/src/openApiBuilder.test.ts +95 -7
  184. package/src/openApiBuilder.ts +46 -9
  185. package/src/openApiCompat.ts +1 -1
  186. package/src/openApiValidator.test.ts +49 -54
  187. package/src/openApiValidator.ts +1 -3
  188. package/src/plugins.test.ts +14 -0
  189. package/src/plugins.ts +34 -9
  190. package/src/populate.test.ts +34 -0
  191. package/src/populate.ts +40 -29
  192. package/src/rateLimit/applyTrustProxy.ts +17 -0
  193. package/src/rateLimit/createStore.ts +25 -0
  194. package/src/rateLimit/memoryStore.ts +40 -0
  195. package/src/rateLimit/middleware.ts +79 -0
  196. package/src/rateLimit/mongoStore.test.ts +80 -0
  197. package/src/rateLimit/mongoStore.ts +76 -0
  198. package/src/rateLimit/policies.ts +130 -0
  199. package/src/rateLimit/rateLimit.test.ts +328 -0
  200. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  201. package/src/rateLimit/redisStore.test.ts +114 -0
  202. package/src/rateLimit/redisStore.ts +85 -0
  203. package/src/rateLimit/types.ts +64 -0
  204. package/src/rbac/access.ts +5 -1
  205. package/src/rbac/assertAllowed.test.ts +325 -0
  206. package/src/rbac/assertAllowed.ts +157 -0
  207. package/src/rbac/backfillAdmins.test.ts +124 -0
  208. package/src/rbac/fieldViews.test.ts +89 -0
  209. package/src/rbac/modelRouterAccess.test.ts +126 -0
  210. package/src/rbac/modelRouterAccess.ts +5 -2
  211. package/src/rbac/permissionUtils.ts +3 -2
  212. package/src/rbac/realtimeAccess.test.ts +109 -1
  213. package/src/rbac/resolve.ts +5 -4
  214. package/src/rbac/roleManager.test.ts +169 -0
  215. package/src/rbac/routes.test.ts +233 -0
  216. package/src/rbac/routes.ts +16 -6
  217. package/src/realtime/deprecation.test.ts +60 -0
  218. package/src/realtime/deprecation.ts +32 -0
  219. package/src/realtime/realtime.test.ts +8 -4
  220. package/src/realtime/realtimeApp.ts +10 -11
  221. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  222. package/src/realtime/registry.ts +48 -42
  223. package/src/realtime/sessionRevalidation.test.ts +57 -44
  224. package/src/realtime/socketAuth.test.ts +75 -23
  225. package/src/realtime/socketAuth.ts +17 -6
  226. package/src/realtime/socketUser.ts +5 -3
  227. package/src/realtime/types.ts +14 -4
  228. package/src/schemaMetadata.test.ts +405 -0
  229. package/src/schemaMetadata.ts +593 -0
  230. package/src/scrubAdminFields.test.ts +105 -0
  231. package/src/seedRunner.test.ts +591 -0
  232. package/src/seedRunner.ts +464 -0
  233. package/src/sync/docMatchesMutationData.test.ts +16 -0
  234. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  235. package/src/sync/executors.test.ts +40 -0
  236. package/src/sync/executors.ts +24 -12
  237. package/src/sync/integration.test.ts +15 -7
  238. package/src/sync/loadHarness.ts +28 -19
  239. package/src/sync/models.ts +32 -18
  240. package/src/sync/mutationHandler.test.ts +16 -16
  241. package/src/sync/mutationHandler.ts +9 -7
  242. package/src/sync/registrationSideEffects.test.ts +126 -0
  243. package/src/sync/registrationSideEffects.ts +131 -0
  244. package/src/sync/registry.ts +45 -171
  245. package/src/sync/routes.ts +3 -2
  246. package/src/sync/scripts/compactTombstones.ts +0 -2
  247. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  248. package/src/sync/sync.test.ts +25 -23
  249. package/src/sync/syncApp.ts +4 -4
  250. package/src/sync/syncBatch.ts +3 -2
  251. package/src/sync/syncFrontier.test.ts +17 -15
  252. package/src/sync/syncPhaseC.test.ts +54 -43
  253. package/src/sync/syncRoutes.test.ts +51 -36
  254. package/src/sync/syncSeqPlugin.ts +66 -44
  255. package/src/sync/syncSocket.test.ts +112 -81
  256. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  257. package/src/terrenoApp.ts +87 -15
  258. package/src/tests/models.ts +14 -1
  259. package/src/types/authToken.ts +43 -0
  260. package/src/types/mcpServiceToken.ts +54 -0
  261. package/src/webhooks/headerValue.test.ts +22 -0
  262. package/src/webhooks/headerValue.ts +12 -0
  263. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  264. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  265. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  266. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  267. package/src/webhooks/rawBody.test.ts +74 -0
  268. package/src/webhooks/rawBody.ts +23 -0
  269. package/src/webhooks/timingSafeEqual.ts +16 -0
  270. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  271. package/src/webhooks/verifiers/hmac.ts +54 -0
  272. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  273. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  274. package/src/webhooks/verifiers/stripe.ts +67 -0
  275. package/src/webhooks/verifiers/twilio.ts +69 -0
  276. package/src/webhooks/webhooksApp.test.ts +221 -0
  277. package/src/webhooks/webhooksApp.ts +144 -0
@@ -0,0 +1,591 @@
1
+ import {afterEach, describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import mongoose, {Schema} from "mongoose";
4
+
5
+ import {APIError} from "./errors";
6
+ import {isDeletedPlugin} from "./plugins";
7
+ import {runSeedCli, runSeeds, type SeedStep, seedBetterAuthUser} from "./seedRunner";
8
+
9
+ interface SeedWidgetDocument {
10
+ key: string;
11
+ label: string;
12
+ }
13
+
14
+ const seedWidgetSchema = new Schema<SeedWidgetDocument>({
15
+ key: {description: "Stable seed key", required: true, type: String, unique: true},
16
+ label: {description: "Seeded display label", required: true, type: String},
17
+ });
18
+ const SeedWidget =
19
+ (mongoose.models.SeedRunnerWidget as mongoose.Model<SeedWidgetDocument> | undefined) ??
20
+ mongoose.model<SeedWidgetDocument>("SeedRunnerWidget", seedWidgetSchema);
21
+
22
+ const widgetStep = (label: string): SeedStep => ({
23
+ name: "widgets",
24
+ reset: async (context) => {
25
+ await context.deleteMany(SeedWidget);
26
+ },
27
+ run: async (context) => {
28
+ await context.upsert(SeedWidget, {key: "primary"}, {label});
29
+ },
30
+ });
31
+
32
+ interface SeedSoftWidgetDocument {
33
+ content?: Map<string, string>;
34
+ deleted?: boolean;
35
+ key: string;
36
+ label: string;
37
+ rules?: Array<{_id?: mongoose.Types.ObjectId; name: string}>;
38
+ }
39
+
40
+ const seedSoftWidgetSchema = new Schema<SeedSoftWidgetDocument>({
41
+ content: {
42
+ description: "Localized seed content",
43
+ of: {description: "Localized string", type: String},
44
+ type: Map,
45
+ },
46
+ key: {description: "Stable seed key", required: true, type: String},
47
+ label: {description: "Seeded display label", required: true, type: String},
48
+ rules: {
49
+ description: "Nested seed payload",
50
+ type: [
51
+ {
52
+ name: {description: "Nested rule name", required: true, type: String},
53
+ },
54
+ ],
55
+ },
56
+ });
57
+ seedSoftWidgetSchema.plugin(isDeletedPlugin);
58
+ const SeedSoftWidget =
59
+ (mongoose.models.SeedRunnerSoftWidget as mongoose.Model<SeedSoftWidgetDocument> | undefined) ??
60
+ mongoose.model<SeedSoftWidgetDocument>("SeedRunnerSoftWidget", seedSoftWidgetSchema);
61
+
62
+ interface SeedDatedWidgetDocument {
63
+ key: string;
64
+ label: string;
65
+ note?: string | null;
66
+ publishedAt?: Date;
67
+ }
68
+
69
+ const seedDatedWidgetSchema = new Schema<SeedDatedWidgetDocument>({
70
+ key: {description: "Stable seed key", required: true, type: String},
71
+ label: {description: "Seeded display label", required: true, type: String},
72
+ note: {description: "Optional note", type: String},
73
+ publishedAt: {description: "Publish timestamp", type: Date},
74
+ });
75
+ const SeedDatedWidget =
76
+ (mongoose.models.SeedRunnerDatedWidget as mongoose.Model<SeedDatedWidgetDocument> | undefined) ??
77
+ mongoose.model<SeedDatedWidgetDocument>("SeedRunnerDatedWidget", seedDatedWidgetSchema);
78
+
79
+ afterEach(async () => {
80
+ await SeedWidget.deleteMany({});
81
+ await SeedSoftWidget.deleteMany({});
82
+ await SeedDatedWidget.deleteMany({});
83
+ process.env.NODE_ENV = "test";
84
+ });
85
+
86
+ describe("runSeeds", () => {
87
+ it("creates, updates, and then leaves keyed seed data unchanged", async () => {
88
+ const created = await runSeeds({name: "test", steps: [widgetStep("First")]});
89
+ const updated = await runSeeds({name: "test", steps: [widgetStep("Second")]});
90
+ const unchanged = await runSeeds({name: "test", steps: [widgetStep("Second")]});
91
+
92
+ assert.equal(created.summary.created, 1);
93
+ assert.equal(updated.summary.updated, 1);
94
+ assert.equal(unchanged.summary.unchanged, 1);
95
+ assert.equal((await SeedWidget.findOne({key: "primary"}))?.label, "Second");
96
+ });
97
+
98
+ it("previews sync and reset operations without writing", async () => {
99
+ await SeedWidget.create({key: "primary", label: "Old"});
100
+
101
+ const result = await runSeeds({
102
+ dryRun: true,
103
+ mode: "reset",
104
+ name: "test",
105
+ steps: [widgetStep("New")],
106
+ });
107
+
108
+ assert.equal(result.summary.deleted, 1);
109
+ assert.equal(result.summary.updated, 1);
110
+ assert.equal((await SeedWidget.findOne({key: "primary"}))?.label, "Old");
111
+ });
112
+
113
+ it("runs selected steps with dependencies in declared order", async () => {
114
+ const calls: string[] = [];
115
+ const steps: SeedStep[] = [
116
+ {name: "users", run: async () => void calls.push("users")},
117
+ {
118
+ dependsOn: ["users"],
119
+ name: "todos",
120
+ run: async () => void calls.push("todos"),
121
+ },
122
+ {name: "flags", run: async () => void calls.push("flags")},
123
+ ];
124
+
125
+ const result = await runSeeds({name: "test", only: ["todos"], steps});
126
+
127
+ assert.deepEqual(calls, ["users", "todos"]);
128
+ assert.deepEqual(result.steps, ["users", "todos"]);
129
+ });
130
+
131
+ it("runs reset handlers in reverse dependency order before reseeding", async () => {
132
+ const calls: string[] = [];
133
+ const steps: SeedStep[] = [
134
+ {
135
+ name: "parents",
136
+ reset: async () => void calls.push("reset parents"),
137
+ run: async () => void calls.push("seed parents"),
138
+ },
139
+ {
140
+ dependsOn: ["parents"],
141
+ name: "children",
142
+ reset: async () => void calls.push("reset children"),
143
+ run: async () => void calls.push("seed children"),
144
+ },
145
+ ];
146
+
147
+ await runSeeds({mode: "reset", name: "test", steps});
148
+
149
+ assert.deepEqual(calls, ["reset children", "reset parents", "seed parents", "seed children"]);
150
+ });
151
+
152
+ it("revives a soft-deleted document instead of creating a duplicate", async () => {
153
+ const created = await SeedSoftWidget.create({key: "primary", label: "Old"});
154
+ created.deleted = true;
155
+ await created.save();
156
+
157
+ const result = await runSeeds({
158
+ name: "test",
159
+ steps: [
160
+ {
161
+ name: "widgets",
162
+ run: async (context) => {
163
+ await context.upsert(SeedSoftWidget, {key: "primary"}, {label: "Restored"});
164
+ },
165
+ },
166
+ ],
167
+ });
168
+
169
+ assert.equal(result.summary.created, 0);
170
+ assert.equal(result.summary.updated, 1);
171
+ assert.equal(await SeedSoftWidget.countDocuments({key: "primary"}), 1);
172
+ const revived = await SeedSoftWidget.findOne({key: "primary"});
173
+ assert.equal(revived?.label, "Restored");
174
+ assert.isNotTrue(revived?.deleted);
175
+ });
176
+
177
+ it("treats nested subdocuments as unchanged when only generated ids differ", async () => {
178
+ await runSeeds({
179
+ name: "test",
180
+ steps: [
181
+ {
182
+ name: "widgets",
183
+ run: async (context) => {
184
+ await context.upsert(
185
+ SeedSoftWidget,
186
+ {key: "flag"},
187
+ {label: "Flag", rules: [{name: "admin-users"}]}
188
+ );
189
+ },
190
+ },
191
+ ],
192
+ });
193
+ const unchanged = await runSeeds({
194
+ name: "test",
195
+ steps: [
196
+ {
197
+ name: "widgets",
198
+ run: async (context) => {
199
+ await context.upsert(
200
+ SeedSoftWidget,
201
+ {key: "flag"},
202
+ {label: "Flag", rules: [{name: "admin-users"}]}
203
+ );
204
+ },
205
+ },
206
+ ],
207
+ });
208
+
209
+ assert.equal(unchanged.summary.unchanged, 1);
210
+ assert.equal(unchanged.summary.updated, 0);
211
+ });
212
+
213
+ it("collapses duplicate live documents for the same seed key", async () => {
214
+ await SeedSoftWidget.create({key: "primary", label: "First"});
215
+ await SeedSoftWidget.create({key: "primary", label: "Second"});
216
+
217
+ const result = await runSeeds({
218
+ name: "test",
219
+ steps: [
220
+ {
221
+ name: "widgets",
222
+ run: async (context) => {
223
+ await context.upsert(SeedSoftWidget, {key: "primary"}, {label: "Canonical"});
224
+ },
225
+ },
226
+ ],
227
+ });
228
+
229
+ assert.equal(result.summary.deleted, 1);
230
+ assert.equal(result.summary.updated, 1);
231
+ assert.equal((await SeedSoftWidget.find({key: "primary"})).length, 1);
232
+ const kept = await SeedSoftWidget.findOne({key: "primary"});
233
+ assert.equal(kept?.label, "Canonical");
234
+ assert.equal((await SeedSoftWidget.find({deleted: true, key: "primary"})).length, 1);
235
+ });
236
+
237
+ it("treats Map seed values as unchanged after Mongoose stores them", async () => {
238
+ const content = new Map([["en", "Hello"]]);
239
+ const step: SeedStep = {
240
+ name: "widgets",
241
+ run: async (context) => {
242
+ await context.upsert(SeedSoftWidget, {key: "form"}, {content, label: "Form"});
243
+ },
244
+ };
245
+ await runSeeds({name: "test", steps: [step]});
246
+ const unchanged = await runSeeds({name: "test", steps: [step]});
247
+
248
+ assert.equal(unchanged.summary.unchanged, 1);
249
+ assert.equal(unchanged.summary.updated, 0);
250
+ });
251
+
252
+ it("treats null and Date seed values as unchanged after Mongoose stores them", async () => {
253
+ const step: SeedStep = {
254
+ name: "widgets",
255
+ run: async (context) => {
256
+ await context.upsert(
257
+ SeedDatedWidget,
258
+ {key: "dated"},
259
+ {label: "Dated", note: null, publishedAt: new Date("2024-01-02T03:04:05.000Z")}
260
+ );
261
+ },
262
+ };
263
+ const created = await runSeeds({name: "test", steps: [step]});
264
+ const unchanged = await runSeeds({name: "test", steps: [step]});
265
+
266
+ assert.equal(created.summary.created, 1);
267
+ assert.equal(unchanged.summary.unchanged, 1);
268
+ assert.equal(unchanged.summary.updated, 0);
269
+ });
270
+
271
+ it("hard-deletes duplicate documents when the model has no soft delete", async () => {
272
+ await SeedDatedWidget.create({key: "dup", label: "First"});
273
+ await SeedDatedWidget.create({key: "dup", label: "Second"});
274
+
275
+ const result = await runSeeds({
276
+ name: "test",
277
+ steps: [
278
+ {
279
+ name: "widgets",
280
+ run: async (context) => {
281
+ await context.upsert(SeedDatedWidget, {key: "dup"}, {label: "Canonical"});
282
+ },
283
+ },
284
+ ],
285
+ });
286
+
287
+ assert.equal(result.summary.deleted, 1);
288
+ assert.equal(result.summary.updated, 1);
289
+ const remaining = await SeedDatedWidget.find({key: "dup"});
290
+ assert.equal(remaining.length, 1);
291
+ assert.equal(remaining[0]?.label, "Canonical");
292
+ });
293
+
294
+ it("reports deleteMany as unchanged when nothing matches", async () => {
295
+ const result = await runSeeds({
296
+ name: "test",
297
+ steps: [
298
+ {
299
+ name: "widgets",
300
+ run: async (context) => {
301
+ await context.deleteMany(SeedWidget, {key: "missing"});
302
+ },
303
+ },
304
+ ],
305
+ });
306
+
307
+ assert.equal(result.summary.unchanged, 0);
308
+ assert.equal(result.summary.deleted, 0);
309
+ assert.deepEqual(result.changes, [
310
+ {
311
+ change: "unchanged",
312
+ count: 0,
313
+ key: JSON.stringify({key: "missing"}),
314
+ model: "SeedRunnerWidget",
315
+ },
316
+ ]);
317
+ });
318
+
319
+ it("rejects duplicate step names", async () => {
320
+ let thrown: unknown;
321
+ try {
322
+ await runSeeds({
323
+ name: "test",
324
+ steps: [
325
+ {name: "same", run: async () => {}},
326
+ {name: "same", run: async () => {}},
327
+ ],
328
+ });
329
+ } catch (error: unknown) {
330
+ thrown = error;
331
+ }
332
+
333
+ assert.instanceOf(thrown, APIError);
334
+ assert.equal((thrown as APIError).title, "Seed step names must be unique");
335
+ });
336
+
337
+ it("rejects unknown --only steps with the available step names", async () => {
338
+ let thrown: unknown;
339
+ try {
340
+ await runSeeds({
341
+ name: "test",
342
+ only: ["nope"],
343
+ steps: [
344
+ {name: "one", run: async () => {}},
345
+ {name: "two", run: async () => {}},
346
+ ],
347
+ });
348
+ } catch (error: unknown) {
349
+ thrown = error;
350
+ }
351
+
352
+ assert.instanceOf(thrown, APIError);
353
+ assert.equal((thrown as APIError).status, 400);
354
+ assert.equal((thrown as APIError).title, "Unknown seed step");
355
+ assert.include((thrown as APIError).detail ?? "", "one, two");
356
+ });
357
+
358
+ it("rejects dependency cycles when selecting steps", async () => {
359
+ let thrown: unknown;
360
+ try {
361
+ await runSeeds({
362
+ name: "test",
363
+ only: ["a"],
364
+ steps: [
365
+ {dependsOn: ["b"], name: "a", run: async () => {}},
366
+ {dependsOn: ["a"], name: "b", run: async () => {}},
367
+ ],
368
+ });
369
+ } catch (error: unknown) {
370
+ thrown = error;
371
+ }
372
+
373
+ assert.instanceOf(thrown, APIError);
374
+ assert.equal((thrown as APIError).title, "Seed step dependency cycle");
375
+ assert.equal((thrown as APIError).detail, "a -> b -> a");
376
+ });
377
+
378
+ it("includes a shared dependency only once", async () => {
379
+ const calls: string[] = [];
380
+ const result = await runSeeds({
381
+ name: "test",
382
+ only: ["left", "right"],
383
+ steps: [
384
+ {name: "base", run: async () => void calls.push("base")},
385
+ {dependsOn: ["base"], name: "left", run: async () => void calls.push("left")},
386
+ {dependsOn: ["base"], name: "right", run: async () => void calls.push("right")},
387
+ {name: "skipped", run: async () => void calls.push("skipped")},
388
+ ],
389
+ });
390
+
391
+ assert.deepEqual(result.steps, ["base", "left", "right"]);
392
+ assert.deepEqual(calls, ["base", "left", "right"]);
393
+ });
394
+
395
+ it("blocks production resets unless forced and explicitly allowed", async () => {
396
+ process.env.NODE_ENV = "production";
397
+
398
+ let resetError: unknown;
399
+ try {
400
+ await runSeeds({force: true, mode: "reset", name: "test", steps: []});
401
+ } catch (error: unknown) {
402
+ resetError = error;
403
+ }
404
+ assert.match(String(resetError), /Production seed reset is disabled/);
405
+ const result = await runSeeds({
406
+ allowProductionReset: true,
407
+ force: true,
408
+ mode: "reset",
409
+ name: "test",
410
+ steps: [],
411
+ });
412
+ assert.isTrue(result.success);
413
+ });
414
+ });
415
+
416
+ describe("runSeedCli", () => {
417
+ it("parses reset, dry-run, force, and repeated only options", async () => {
418
+ const calls: string[] = [];
419
+ const steps: SeedStep[] = [
420
+ {
421
+ name: "one",
422
+ reset: async () => void calls.push("reset one"),
423
+ run: async () => void calls.push("one"),
424
+ },
425
+ {name: "two", run: async () => void calls.push("two")},
426
+ ];
427
+
428
+ const cli = await runSeedCli({
429
+ argv: ["--reset", "--dry-run", "--force", "--only", "one"],
430
+ name: "bun run seed",
431
+ steps,
432
+ });
433
+
434
+ assert.equal(cli.exitCode, 0);
435
+ assert.equal(cli.result?.mode, "reset");
436
+ assert.isTrue(cli.result?.dryRun);
437
+ assert.deepEqual(calls, ["reset one", "one"]);
438
+ });
439
+
440
+ it("returns help without connecting and rejects unknown options", async () => {
441
+ let didConnect = false;
442
+ const help = await runSeedCli({
443
+ argv: ["--help"],
444
+ connect: async () => {
445
+ didConnect = true;
446
+ },
447
+ name: "bun run seed",
448
+ steps: [widgetStep("Example")],
449
+ });
450
+ const invalid = await runSeedCli({
451
+ argv: ["--wat"],
452
+ name: "bun run seed",
453
+ steps: [],
454
+ });
455
+
456
+ assert.equal(help.exitCode, 0);
457
+ assert.include(help.help ?? "", "--reset");
458
+ assert.isFalse(didConnect);
459
+ assert.equal(invalid.exitCode, 2);
460
+ assert.include(invalid.help ?? "", "Unknown option(s): --wat");
461
+ });
462
+
463
+ it("parses --only=<step> and returns exit code 1 when seeding fails", async () => {
464
+ const calls: string[] = [];
465
+ const ok = await runSeedCli({
466
+ argv: ["--only=two"],
467
+ name: "bun run seed",
468
+ steps: [
469
+ {name: "one", run: async () => void calls.push("one")},
470
+ {name: "two", run: async () => void calls.push("two")},
471
+ ],
472
+ });
473
+ assert.equal(ok.exitCode, 0);
474
+ assert.deepEqual(calls, ["two"]);
475
+
476
+ const errors: string[] = [];
477
+ const failed = await runSeedCli({
478
+ argv: [],
479
+ log: {
480
+ catch: () => {},
481
+ debug: () => {},
482
+ error: (message: string) => void errors.push(message),
483
+ info: () => {},
484
+ warn: () => {},
485
+ },
486
+ name: "bun run seed",
487
+ steps: [
488
+ {
489
+ name: "boom",
490
+ run: async () => {
491
+ throw new Error("seed exploded");
492
+ },
493
+ },
494
+ ],
495
+ });
496
+ assert.equal(failed.exitCode, 1);
497
+ assert.isUndefined(failed.result);
498
+ assert.deepEqual(errors, ["Seed failed: seed exploded"]);
499
+ });
500
+ });
501
+
502
+ interface SeedAuthUserDocument {
503
+ betterAuthId?: string;
504
+ email: string;
505
+ name?: string;
506
+ }
507
+
508
+ const seedAuthUserSchema = new Schema<SeedAuthUserDocument>({
509
+ betterAuthId: {description: "Better Auth id", type: String},
510
+ email: {description: "Email", required: true, type: String},
511
+ name: {description: "Name", type: String},
512
+ });
513
+ const SeedAuthUser =
514
+ (mongoose.models.SeedRunnerAuthUser as mongoose.Model<SeedAuthUserDocument> | undefined) ??
515
+ mongoose.model<SeedAuthUserDocument>("SeedRunnerAuthUser", seedAuthUserSchema);
516
+
517
+ describe("seedBetterAuthUser", () => {
518
+ const seedUser = {email: "seed@example.com", name: "Seed User", password: "testpassword123"};
519
+
520
+ afterEach(async () => {
521
+ await SeedAuthUser.deleteMany({});
522
+ });
523
+
524
+ it("creates an application user from a successful sign-up", async () => {
525
+ const authId = new mongoose.Types.ObjectId().toString();
526
+ const auth = {
527
+ api: {
528
+ signUpEmail: async () => ({
529
+ user: {email: seedUser.email, id: authId, name: seedUser.name},
530
+ }),
531
+ },
532
+ };
533
+
534
+ const user = await seedBetterAuthUser({
535
+ auth: auth as never,
536
+ user: seedUser,
537
+ userModel: SeedAuthUser as never,
538
+ });
539
+
540
+ assert.equal(user.email, seedUser.email);
541
+ assert.equal((user as {betterAuthId?: string}).betterAuthId, authId);
542
+ });
543
+
544
+ it("falls back to sign-in when sign-up fails", async () => {
545
+ const authId = new mongoose.Types.ObjectId().toString();
546
+ const auth = {
547
+ api: {
548
+ signInEmail: async () => ({
549
+ user: {email: seedUser.email, id: authId, name: seedUser.name},
550
+ }),
551
+ signUpEmail: async () => {
552
+ throw new Error("already exists");
553
+ },
554
+ },
555
+ };
556
+
557
+ const user = await seedBetterAuthUser({
558
+ auth: auth as never,
559
+ user: seedUser,
560
+ userModel: SeedAuthUser as never,
561
+ });
562
+
563
+ assert.equal(user.email, seedUser.email);
564
+ assert.equal((user as {betterAuthId?: string}).betterAuthId, authId);
565
+ });
566
+
567
+ it("throws APIError when Better Auth returns no user", async () => {
568
+ const auth = {
569
+ api: {
570
+ signInEmail: async () => ({user: undefined}),
571
+ signUpEmail: async () => {
572
+ throw new Error("already exists");
573
+ },
574
+ },
575
+ };
576
+
577
+ let thrown: unknown;
578
+ try {
579
+ await seedBetterAuthUser({
580
+ auth: auth as never,
581
+ user: seedUser,
582
+ userModel: SeedAuthUser as never,
583
+ });
584
+ } catch (error: unknown) {
585
+ thrown = error;
586
+ }
587
+
588
+ assert.instanceOf(thrown, APIError);
589
+ assert.equal((thrown as APIError).title, "Better Auth seed returned no user");
590
+ });
591
+ });