@reventlessdev/reventless-seed 1.0.0-alpha.1 → 1.0.0-alpha.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 (106) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/lib/bs/.compiler.log +2 -2
  3. package/lib/bs/.sourcedirs.json +1 -0
  4. package/lib/bs/ReventlessSeed.cmi +0 -0
  5. package/lib/bs/ReventlessSeed.cmt +0 -0
  6. package/lib/bs/ReventlessSeed.mlmap +3 -0
  7. package/lib/bs/compiler-info.json +2 -2
  8. package/lib/bs/src/Seed-ReventlessSeed.cmi +0 -0
  9. package/lib/bs/src/Seed-ReventlessSeed.cmt +0 -0
  10. package/lib/bs/src/Seed.ast +0 -0
  11. package/lib/bs/src/Seed.res +19 -0
  12. package/lib/bs/src/Seed.res.mjs +6 -0
  13. package/lib/bs/src/Seed_Client-ReventlessSeed.cmi +0 -0
  14. package/lib/bs/src/Seed_Client-ReventlessSeed.cmj +0 -0
  15. package/lib/bs/src/Seed_Client-ReventlessSeed.cmt +0 -0
  16. package/lib/bs/src/Seed_Client.ast +0 -0
  17. package/lib/bs/src/Seed_Client.res +62 -11
  18. package/lib/bs/src/Seed_Client.res.mjs +51 -5
  19. package/lib/bs/src/Seed_Connect-ReventlessSeed.cmi +0 -0
  20. package/lib/bs/src/Seed_Connect-ReventlessSeed.cmj +0 -0
  21. package/lib/bs/src/Seed_Connect-ReventlessSeed.cmt +0 -0
  22. package/lib/bs/src/Seed_Connect.ast +0 -0
  23. package/lib/bs/src/Seed_Connect.res +86 -0
  24. package/lib/bs/src/Seed_Connect.res.mjs +62 -0
  25. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmi +0 -0
  26. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmj +0 -0
  27. package/lib/bs/src/Seed_Prompt-ReventlessSeed.cmt +0 -0
  28. package/lib/bs/src/Seed_Prompt.ast +0 -0
  29. package/lib/bs/src/Seed_Prompt.res +178 -0
  30. package/lib/bs/src/Seed_Prompt.res.mjs +172 -0
  31. package/lib/bs/src/Seed_Random-ReventlessSeed.cmt +0 -0
  32. package/lib/bs/src/Seed_Runner-ReventlessSeed.cmi +0 -0
  33. package/lib/bs/src/Seed_Runner-ReventlessSeed.cmj +0 -0
  34. package/lib/bs/src/Seed_Runner-ReventlessSeed.cmt +0 -0
  35. package/lib/bs/src/Seed_Runner.ast +0 -0
  36. package/lib/bs/src/Seed_Runner.res +122 -6
  37. package/lib/bs/src/Seed_Runner.res.mjs +87 -1
  38. package/lib/bs/src/Seed_Types-ReventlessSeed.cmt +0 -0
  39. package/lib/bs/src/Seed_Upload-ReventlessSeed.cmi +0 -0
  40. package/lib/bs/src/Seed_Upload-ReventlessSeed.cmj +0 -0
  41. package/lib/bs/src/Seed_Upload-ReventlessSeed.cmt +0 -0
  42. package/lib/bs/src/Seed_Upload.ast +0 -0
  43. package/lib/bs/src/Seed_Upload.res +40 -42
  44. package/lib/bs/src/Seed_Upload.res.mjs +65 -69
  45. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmi +0 -0
  46. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmj +0 -0
  47. package/lib/bs/tests/Seed_RandomTest-ReventlessSeed.cmt +0 -0
  48. package/lib/bs/tests/Seed_RandomTest.ast +0 -0
  49. package/lib/bs/tests/Seed_RandomTest.res +160 -0
  50. package/lib/bs/tests/Seed_RandomTest.res.mjs +208 -0
  51. package/lib/ocaml/.compiler.log +2 -2
  52. package/lib/ocaml/ReventlessSeed.cmi +0 -0
  53. package/lib/ocaml/ReventlessSeed.cmt +0 -0
  54. package/lib/ocaml/ReventlessSeed.mlmap +3 -0
  55. package/lib/ocaml/Seed-ReventlessSeed.cmi +0 -0
  56. package/lib/ocaml/Seed-ReventlessSeed.cmt +0 -0
  57. package/lib/ocaml/Seed.ast +0 -0
  58. package/lib/ocaml/Seed.res +19 -0
  59. package/lib/ocaml/Seed_Client-ReventlessSeed.cmi +0 -0
  60. package/lib/ocaml/Seed_Client-ReventlessSeed.cmj +0 -0
  61. package/lib/ocaml/Seed_Client-ReventlessSeed.cmt +0 -0
  62. package/lib/ocaml/Seed_Client.ast +0 -0
  63. package/lib/ocaml/Seed_Client.res +62 -11
  64. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmi +0 -0
  65. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmj +0 -0
  66. package/lib/ocaml/Seed_Connect-ReventlessSeed.cmt +0 -0
  67. package/lib/ocaml/Seed_Connect.ast +0 -0
  68. package/lib/ocaml/Seed_Connect.res +86 -0
  69. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmi +0 -0
  70. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmj +0 -0
  71. package/lib/ocaml/Seed_Prompt-ReventlessSeed.cmt +0 -0
  72. package/lib/ocaml/Seed_Prompt.ast +0 -0
  73. package/lib/ocaml/Seed_Prompt.res +178 -0
  74. package/lib/ocaml/Seed_Random-ReventlessSeed.cmt +0 -0
  75. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmi +0 -0
  76. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmj +0 -0
  77. package/lib/ocaml/Seed_RandomTest-ReventlessSeed.cmt +0 -0
  78. package/lib/ocaml/Seed_RandomTest.ast +0 -0
  79. package/lib/ocaml/Seed_RandomTest.res +160 -0
  80. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmi +0 -0
  81. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmj +0 -0
  82. package/lib/ocaml/Seed_Runner-ReventlessSeed.cmt +0 -0
  83. package/lib/ocaml/Seed_Runner.ast +0 -0
  84. package/lib/ocaml/Seed_Runner.res +122 -6
  85. package/lib/ocaml/Seed_Types-ReventlessSeed.cmt +0 -0
  86. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmi +0 -0
  87. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmj +0 -0
  88. package/lib/ocaml/Seed_Upload-ReventlessSeed.cmt +0 -0
  89. package/lib/ocaml/Seed_Upload.ast +0 -0
  90. package/lib/ocaml/Seed_Upload.res +40 -42
  91. package/package.json +6 -2
  92. package/rescript.json +9 -1
  93. package/src/Seed.res +19 -0
  94. package/src/Seed.res.mjs +6 -0
  95. package/src/Seed_Client.res +62 -11
  96. package/src/Seed_Client.res.mjs +51 -5
  97. package/src/Seed_Connect.res +86 -0
  98. package/src/Seed_Connect.res.mjs +62 -0
  99. package/src/Seed_Prompt.res +178 -0
  100. package/src/Seed_Prompt.res.mjs +172 -0
  101. package/src/Seed_Runner.res +122 -6
  102. package/src/Seed_Runner.res.mjs +87 -1
  103. package/src/Seed_Upload.res +40 -42
  104. package/src/Seed_Upload.res.mjs +65 -69
  105. package/tests/Seed_RandomTest.res +160 -0
  106. package/tests/Seed_RandomTest.res.mjs +208 -0
@@ -0,0 +1,178 @@
1
+ // One shared readline interface for every interactive prompt in a seed run.
2
+ //
3
+ // The reason this module exists: creating and closing a fresh `readline`
4
+ // interface per prompt leaves NodeProcess.stdin paused after the first `close`, so the
5
+ // second prompt (password after username) never fires and the run hangs. A
6
+ // single interface, created lazily and closed exactly once, avoids that — and a
7
+ // `muted` gate on its output lets password entry reuse the same interface
8
+ // instead of opening a second one just to suppress the echo.
9
+ //
10
+ // Node bindings are declared here as typed externals; this package is
11
+ // stdlib-only, so no `%raw`.
12
+
13
+ open Seed_Types
14
+
15
+ // ── Node bindings ─────────────────────────────────────────────────────────────
16
+
17
+ type rl
18
+ type rlOptions = {input: NodeProcess.stream, output: NodeProcess.stream, terminal?: bool}
19
+ @module("node:readline") external createInterface: rlOptions => rl = "createInterface"
20
+ @send external question: (rl, string, string => unit) => unit = "question"
21
+ @send external closeRl: rl => unit = "close"
22
+ @set external setWriteToOutput: (rl, string => unit) => unit = "_writeToOutput"
23
+
24
+ // ── Shared interface ──────────────────────────────────────────────────────────
25
+
26
+ // Created on first use, closed once via `close`. `muted` gates the echo so the
27
+ // same interface serves both visible and hidden prompts.
28
+ let rlRef: ref<option<rl>> = ref(None)
29
+ let muted = ref(false)
30
+
31
+ let iface = (): rl =>
32
+ switch rlRef.contents {
33
+ | Some(rl) => rl
34
+ | None =>
35
+ let rl = createInterface({input: NodeProcess.stdin, output: NodeProcess.stdout, terminal: true})
36
+ rl->setWriteToOutput(s =>
37
+ if !muted.contents {
38
+ NodeProcess.stdout->NodeProcess.write(s)
39
+ }
40
+ )
41
+ rlRef := Some(rl)
42
+ rl
43
+ }
44
+
45
+ let close = (): unit =>
46
+ switch rlRef.contents {
47
+ | Some(rl) =>
48
+ rl->closeRl
49
+ rlRef := None
50
+ // Closing the interface is not enough: a terminal-mode readline leaves
51
+ // NodeProcess.stdin resumed and reffed, which keeps the event loop alive so the CLI
52
+ // never exits after seeding. Release it explicitly.
53
+ NodeProcess.stdin->NodeProcess.pause
54
+ NodeProcess.stdin->NodeProcess.unref
55
+ | None => ()
56
+ }
57
+
58
+ // ── Env + TTY ─────────────────────────────────────────────────────────────────
59
+
60
+ let envValue = (key: string): option<string> =>
61
+ switch NodeProcess.env->Dict.get(key) {
62
+ | Some(v) if v->String.trim != "" => Some(v->String.trim)
63
+ | _ => None
64
+ }
65
+
66
+ let requireTty = (): unit =>
67
+ if !(NodeProcess.stdin->NodeProcess.isTTY->Option.getOr(false)) {
68
+ throw(
69
+ Failed(
70
+ "no TTY for an interactive prompt — set the documented SEED_* / REVENTLESS_DEMO_* " ++
71
+ "env vars to run non-interactively.",
72
+ ),
73
+ )
74
+ }
75
+
76
+ // ── Prompts ───────────────────────────────────────────────────────────────────
77
+
78
+ let ask = (query: string): promise<string> =>
79
+ Promise.make((resolve, _) => {
80
+ let rl = iface()
81
+ rl->question(query, answer => resolve(answer->String.trim))
82
+ })
83
+
84
+ // Same interface, echo suppressed for the keystrokes. `question` writes the
85
+ // prompt synchronously first (while unmuted), then muting is switched on so only
86
+ // the typed characters are hidden — the canonical readline recipe, which keeps
87
+ // the line editor's cursor state consistent (a manual write + empty `question`
88
+ // left some terminals unable to read the next line).
89
+ let askHidden = (query: string): promise<string> =>
90
+ Promise.make((resolve, _) => {
91
+ let rl = iface()
92
+ rl->question(query, answer => {
93
+ muted := false
94
+ NodeProcess.stdout->NodeProcess.write("\n")
95
+ resolve(answer)
96
+ })
97
+ muted := true
98
+ })
99
+
100
+ /**
101
+ * Chooses one of `options` (a label paired with the value it selects).
102
+ *
103
+ * Auto-returns when there is a single option, so a lone data set or stack needs
104
+ * no keypress. `env` (e.g. `SEED_SET`) preselects by matching label or 1-based
105
+ * index, so CI runs without a TTY. Otherwise it prints a numbered menu.
106
+ */
107
+ let select = async (
108
+ ~title: string,
109
+ ~options: array<(string, 'a)>,
110
+ ~env=?,
111
+ ): 'a =>
112
+ switch options {
113
+ | [(_, only)] => only
114
+ | _ =>
115
+ let fromEnv =
116
+ env
117
+ ->Option.flatMap(envValue)
118
+ ->Option.flatMap(v =>
119
+ switch options->Array.findIndex(((label, _)) => label == v) {
120
+ | -1 =>
121
+ switch Int.fromString(v) {
122
+ | Some(n) if n >= 1 && n <= options->Array.length => options->Array.get(n - 1)
123
+ | _ => None
124
+ }
125
+ | i => options->Array.get(i)
126
+ }
127
+ )
128
+ switch fromEnv {
129
+ | Some((_, value)) => value
130
+ | None =>
131
+ requireTty()
132
+ Console.log("")
133
+ Console.log(title)
134
+ Console.log("")
135
+ options->Array.forEachWithIndex(((label, _), i) =>
136
+ Console.log(` ${(i + 1)->Int.toString}) ${label}`)
137
+ )
138
+ let rec pick = async (): 'a => {
139
+ let answer = await ask(`\nSelect [1-${(options->Array.length)->Int.toString}]: `)
140
+ switch Int.fromString(answer) {
141
+ | Some(n) if n >= 1 && n <= options->Array.length =>
142
+ let (_, value) = options->Array.getUnsafe(n - 1)
143
+ value
144
+ | _ =>
145
+ Console.log(" Not a valid choice.")
146
+ await pick()
147
+ }
148
+ }
149
+ await pick()
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Prompts for a username (visible) and password (echo muted).
155
+ *
156
+ * `REVENTLESS_DEMO_USER` / `REVENTLESS_DEMO_PASSWORD` skip the prompts. With
157
+ * `localDefaults`, empty input falls back to `admin`/`admin` — the dev login.
158
+ */
159
+ let credentials = async (~localDefaults: bool=false): (string, string) => {
160
+ let username = switch envValue("REVENTLESS_DEMO_USER") {
161
+ | Some(u) => u
162
+ | None =>
163
+ requireTty()
164
+ let entered = await ask(localDefaults ? "Username [admin]: " : "Username: ")
165
+ entered == "" && localDefaults ? "admin" : entered
166
+ }
167
+ let password = switch envValue("REVENTLESS_DEMO_PASSWORD") {
168
+ | Some(p) => p
169
+ | None =>
170
+ requireTty()
171
+ let entered = await askHidden(localDefaults ? "Password [admin]: " : "Password: ")
172
+ entered == "" && localDefaults ? "admin" : entered
173
+ }
174
+ if username == "" || password == "" {
175
+ throw(Failed("username and password are required."))
176
+ }
177
+ (username, password)
178
+ }
@@ -0,0 +1,172 @@
1
+ // Generated by ReScript, PLEASE EDIT WITH CARE
2
+
3
+ import * as Stdlib_Int from "@rescript/runtime/lib/es6/Stdlib_Int.js";
4
+ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
5
+ import * as Nodereadline from "node:readline";
6
+ import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.js";
7
+ import * as Seed_Types$ReventlessSeed from "./Seed_Types.res.mjs";
8
+
9
+ let rlRef = {
10
+ contents: undefined
11
+ };
12
+
13
+ let muted = {
14
+ contents: false
15
+ };
16
+
17
+ function iface() {
18
+ let rl = rlRef.contents;
19
+ if (rl !== undefined) {
20
+ return Primitive_option.valFromOption(rl);
21
+ }
22
+ let rl$1 = Nodereadline.createInterface({
23
+ input: process.stdin,
24
+ output: process.stdout,
25
+ terminal: true
26
+ });
27
+ rl$1._writeToOutput = s => {
28
+ if (!muted.contents) {
29
+ process.stdout.write(s);
30
+ return;
31
+ }
32
+ };
33
+ rlRef.contents = Primitive_option.some(rl$1);
34
+ return rl$1;
35
+ }
36
+
37
+ function close() {
38
+ let rl = rlRef.contents;
39
+ if (rl !== undefined) {
40
+ Primitive_option.valFromOption(rl).close();
41
+ rlRef.contents = undefined;
42
+ process.stdin.pause();
43
+ process.stdin.unref();
44
+ return;
45
+ }
46
+ }
47
+
48
+ function envValue(key) {
49
+ let v = process.env[key];
50
+ if (v !== undefined && v.trim() !== "") {
51
+ return v.trim();
52
+ }
53
+ }
54
+
55
+ function requireTty() {
56
+ if (Stdlib_Option.getOr(process.stdin.isTTY, false)) {
57
+ return;
58
+ }
59
+ throw {
60
+ RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
61
+ _1: "no TTY for an interactive prompt — set the documented SEED_* / REVENTLESS_DEMO_* env vars to run non-interactively.",
62
+ Error: new Error()
63
+ };
64
+ }
65
+
66
+ function ask(query) {
67
+ return new Promise((resolve, param) => {
68
+ let rl = iface();
69
+ rl.question(query, answer => resolve(answer.trim()));
70
+ });
71
+ }
72
+
73
+ function askHidden(query) {
74
+ return new Promise((resolve, param) => {
75
+ let rl = iface();
76
+ rl.question(query, answer => {
77
+ muted.contents = false;
78
+ process.stdout.write("\n");
79
+ resolve(answer);
80
+ });
81
+ muted.contents = true;
82
+ });
83
+ }
84
+
85
+ async function select(title, options, env) {
86
+ if (options.length === 1) {
87
+ return options[0][1];
88
+ }
89
+ let fromEnv = Stdlib_Option.flatMap(Stdlib_Option.flatMap(env, envValue), v => {
90
+ let i = options.findIndex(param => param[0] === v);
91
+ if (i !== -1) {
92
+ return options[i];
93
+ }
94
+ let n = Stdlib_Int.fromString(v, undefined);
95
+ if (n !== undefined && n >= 1 && n <= options.length) {
96
+ return options[n - 1 | 0];
97
+ }
98
+ });
99
+ if (fromEnv !== undefined) {
100
+ return fromEnv[1];
101
+ }
102
+ requireTty();
103
+ console.log("");
104
+ console.log(title);
105
+ console.log("");
106
+ options.forEach((param, i) => {
107
+ console.log(` ` + (i + 1 | 0).toString() + `) ` + param[0]);
108
+ });
109
+ let pick = async () => {
110
+ let answer = await ask(`\nSelect [1-` + options.length.toString() + `]: `);
111
+ let n = Stdlib_Int.fromString(answer, undefined);
112
+ if (n !== undefined) {
113
+ if (n >= 1 && n <= options.length) {
114
+ return options[n - 1 | 0][1];
115
+ } else {
116
+ console.log(" Not a valid choice.");
117
+ return await pick();
118
+ }
119
+ } else {
120
+ console.log(" Not a valid choice.");
121
+ return await pick();
122
+ }
123
+ };
124
+ return await pick();
125
+ }
126
+
127
+ async function credentials(localDefaultsOpt) {
128
+ let localDefaults = localDefaultsOpt !== undefined ? localDefaultsOpt : false;
129
+ let u = envValue("REVENTLESS_DEMO_USER");
130
+ let username;
131
+ if (u !== undefined) {
132
+ username = u;
133
+ } else {
134
+ requireTty();
135
+ let entered = await ask(localDefaults ? "Username [admin]: " : "Username: ");
136
+ username = entered === "" && localDefaults ? "admin" : entered;
137
+ }
138
+ let p = envValue("REVENTLESS_DEMO_PASSWORD");
139
+ let password;
140
+ if (p !== undefined) {
141
+ password = p;
142
+ } else {
143
+ requireTty();
144
+ let entered$1 = await askHidden(localDefaults ? "Password [admin]: " : "Password: ");
145
+ password = entered$1 === "" && localDefaults ? "admin" : entered$1;
146
+ }
147
+ if (username === "" || password === "") {
148
+ throw {
149
+ RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
150
+ _1: "username and password are required.",
151
+ Error: new Error()
152
+ };
153
+ }
154
+ return [
155
+ username,
156
+ password
157
+ ];
158
+ }
159
+
160
+ export {
161
+ rlRef,
162
+ muted,
163
+ iface,
164
+ close,
165
+ envValue,
166
+ requireTty,
167
+ ask,
168
+ askHidden,
169
+ select,
170
+ credentials,
171
+ }
172
+ /* node:readline Not a pure module */
Binary file
@@ -2,11 +2,9 @@
2
2
 
3
3
  open Seed_Types
4
4
 
5
- @scope("process") @val external exit: int => unit = "exit"
6
- @scope("process") @val external env: dict<string> = "env"
7
5
 
8
6
  let envOr = (key: string, fallback: string): string =>
9
- env->Dict.get(key)->Option.getOr(fallback)
7
+ NodeProcess.env->Dict.get(key)->Option.getOr(fallback)
10
8
 
11
9
  /** One line of progress per phase, so a slow run never looks hung. */
12
10
  let report = (line: string): unit => Console.log(` ${line}`)
@@ -90,19 +88,52 @@ let warn = (warnings: array<string>): unit =>
90
88
  warnings->Array.forEach(w => Console.log(` - ${w}`))
91
89
  }
92
90
 
91
+ /**
92
+ * Pre-flight: refuse to seed onto a store that already holds data.
93
+ *
94
+ * The harness is a one-shot against a fresh store — a re-run would hit the
95
+ * domain's own duplicate rejections (`CategoryAlreadyExists`, …) and abort
96
+ * mid-phase. Catching it here, before any command is sent, turns that into an
97
+ * honest "nothing was written" startup abort instead of a misleading
98
+ * half-seeded one. It is the inverse of `verifyViews`: seeding refuses to start
99
+ * unless the store reads empty. Stops at the first non-empty probe view, so a
100
+ * populated store aborts after a single query.
101
+ */
102
+ let assertStoreEmpty = async (client: Seed_Client.t, ~probeViews: array<string>): unit =>
103
+ for i in 0 to probeViews->Array.length - 1 {
104
+ switch probeViews->Array.get(i) {
105
+ | Some(name) =>
106
+ let count = await Seed_Client.countNodes(client, ~field=name)
107
+ if count > 0 {
108
+ throw(
109
+ Failed(
110
+ `the target store is not empty — "${name}" already holds ${count->Int.toString} row(s). Seeding is a one-shot against a fresh store; reset the store before re-running.`,
111
+ ),
112
+ )
113
+ }
114
+ | None => ()
115
+ }
116
+ }
117
+
93
118
  /**
94
119
  * Wraps a seed run. On failure it prints the cause and exits non-zero, saying
95
120
  * plainly that the store is now half-seeded — recovery is a reset, not a re-run.
96
121
  */
97
122
  let run = async (main: unit => promise<unit>): unit =>
98
- try await main() catch {
123
+ try {
124
+ await main()
125
+ // Exit cleanly: HTTP keep-alive sockets (and, on the interactive path, the
126
+ // readline/stdin handle) can otherwise keep the event loop alive so the CLI
127
+ // appears to hang after a successful run.
128
+ NodeProcess.exit(0)
129
+ } catch {
99
130
  | Failed(message) =>
100
131
  Console.error("")
101
132
  Console.error("Seeding aborted — the store is now half-seeded; re-run against a")
102
133
  Console.error("fresh store once the cause below is fixed.")
103
134
  Console.error("")
104
135
  Console.error(message)
105
- exit(1)
136
+ NodeProcess.exit(1)
106
137
  | exn =>
107
138
  Console.error("")
108
139
  Console.error("Seeding aborted with an unexpected error:")
@@ -110,5 +141,90 @@ let run = async (main: unit => promise<unit>): unit =>
110
141
  Console.error(
111
142
  exn->JsExn.fromException->Option.flatMap(JsExn.message)->Option.getOr("unknown"),
112
143
  )
113
- exit(1)
144
+ NodeProcess.exit(1)
114
145
  }
146
+
147
+ /**
148
+ * A named, seedable data set. `seed` owns everything domain-specific — the
149
+ * phases, `verifyViews`, the summary board — so the generic runner never sees
150
+ * domain detail. `label` is what the selection menu shows.
151
+ */
152
+ type dataSet = {
153
+ name: string,
154
+ label: string,
155
+ seed: Seed_Connect.connection => promise<unit>,
156
+ // View names probed by the fresh-store guard before any command is sent; a
157
+ // non-empty one aborts the run at startup. Omit to skip the guard.
158
+ probeViews?: array<string>,
159
+ }
160
+
161
+ /**
162
+ * A failure before any command is sent — bad data-set selection, an
163
+ * unreachable/undeployed target, a login failure. Nothing was written, so this
164
+ * says so plainly rather than warning about a half-seeded store (which would
165
+ * send the user resetting a store the run never touched).
166
+ */
167
+ let abortStartup = (message: string): unit => {
168
+ Seed_Prompt.close()
169
+ Console.error("")
170
+ Console.error("Seeding did not start — nothing was written. Fix the cause below and re-run.")
171
+ Console.error("")
172
+ Console.error(message)
173
+ NodeProcess.exit(1)
174
+ }
175
+
176
+ /**
177
+ * Top-level seed entry: choose a data set (auto when there is one, `SEED_SET`
178
+ * or a menu otherwise), connect, then hand the connection to the chosen set.
179
+ * Prompts are closed before seeding so the shared readline never lingers.
180
+ *
181
+ * Selection and connect run before any command is sent, so a failure there is
182
+ * reported as "did not start"; only failures inside the data set's own `seed`
183
+ * carry the half-seeded warning (via `run`).
184
+ */
185
+ let seed = (~sets: array<dataSet>, ~connect: unit => promise<Seed_Connect.connection>): unit => {
186
+ let go = async () => {
187
+ let started = try {
188
+ let chosen = switch sets {
189
+ | [only] => only
190
+ | _ =>
191
+ switch Seed_Prompt.envValue("SEED_SET") {
192
+ | Some(wanted) =>
193
+ switch sets->Array.find(s => s.name == wanted) {
194
+ | Some(s) => s
195
+ | None =>
196
+ throw(
197
+ Failed(
198
+ `SEED_SET="${wanted}" matches no data set (have: ${sets
199
+ ->Array.map(s => s.name)
200
+ ->Array.join(", ")})`,
201
+ ),
202
+ )
203
+ }
204
+ | None =>
205
+ await Seed_Prompt.select(~title="Data set:", ~options=sets->Array.map(s => (s.label, s)))
206
+ }
207
+ }
208
+ let connection = await connect()
209
+ Seed_Prompt.close()
210
+ // Runs inside this pre-seed `try`, so refusing a non-empty store (or a
211
+ // failed probe query) is reported as "did not start", not "half-seeded".
212
+ await assertStoreEmpty(connection.client, ~probeViews=chosen.probeViews->Option.getOr([]))
213
+ Some((chosen, connection))
214
+ } catch {
215
+ | Failed(message) =>
216
+ abortStartup(message)
217
+ None
218
+ | exn =>
219
+ abortStartup(exn->JsExn.fromException->Option.flatMap(JsExn.message)->Option.getOr("unknown"))
220
+ None
221
+ }
222
+ switch started {
223
+ | None => () // unreachable: abortStartup has already exited
224
+ | Some((chosen, connection)) =>
225
+ heading(`Seeding "${chosen.label}" into ${connection.label}`)
226
+ await run(() => chosen.seed(connection))
227
+ }
228
+ }
229
+ go()->ignore
230
+ }
@@ -6,6 +6,7 @@ import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.js";
6
6
  import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.js";
7
7
  import * as Seed_Types$ReventlessSeed from "./Seed_Types.res.mjs";
8
8
  import * as Seed_Client$ReventlessSeed from "./Seed_Client.res.mjs";
9
+ import * as Seed_Prompt$ReventlessSeed from "./Seed_Prompt.res.mjs";
9
10
 
10
11
  function envOr(key, fallback) {
11
12
  return Stdlib_Option.getOr(process.env[key], fallback);
@@ -82,9 +83,27 @@ function warn(warnings) {
82
83
  }
83
84
  }
84
85
 
86
+ async function assertStoreEmpty(client, probeViews) {
87
+ for (let i = 0, i_finish = probeViews.length; i < i_finish; ++i) {
88
+ let name = probeViews[i];
89
+ if (name !== undefined) {
90
+ let count = await Seed_Client$ReventlessSeed.countNodes(client, name);
91
+ if (count > 0) {
92
+ throw {
93
+ RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
94
+ _1: `the target store is not empty — "` + name + `" already holds ` + count.toString() + ` row(s). Seeding is a one-shot against a fresh store; reset the store before re-running.`,
95
+ Error: new Error()
96
+ };
97
+ }
98
+ }
99
+ }
100
+ }
101
+
85
102
  async function run(main) {
86
103
  try {
87
- return await main();
104
+ await main();
105
+ process.exit(0);
106
+ return;
88
107
  } catch (raw_message) {
89
108
  let message = Primitive_exceptions.internalToException(raw_message);
90
109
  if (message.RE_EXN_ID === Seed_Types$ReventlessSeed.Failed) {
@@ -105,6 +124,70 @@ async function run(main) {
105
124
  }
106
125
  }
107
126
 
127
+ function abortStartup(message) {
128
+ Seed_Prompt$ReventlessSeed.close();
129
+ console.error("");
130
+ console.error("Seeding did not start — nothing was written. Fix the cause below and re-run.");
131
+ console.error("");
132
+ console.error(message);
133
+ process.exit(1);
134
+ }
135
+
136
+ function seed(sets, connect) {
137
+ let go = async () => {
138
+ let started;
139
+ try {
140
+ let chosen;
141
+ if (sets.length !== 1) {
142
+ let wanted = Seed_Prompt$ReventlessSeed.envValue("SEED_SET");
143
+ if (wanted !== undefined) {
144
+ let s = sets.find(s => s.name === wanted);
145
+ if (s !== undefined) {
146
+ chosen = s;
147
+ } else {
148
+ throw {
149
+ RE_EXN_ID: Seed_Types$ReventlessSeed.Failed,
150
+ _1: `SEED_SET="` + wanted + `" matches no data set (have: ` + sets.map(s => s.name).join(", ") + `)`,
151
+ Error: new Error()
152
+ };
153
+ }
154
+ } else {
155
+ chosen = await Seed_Prompt$ReventlessSeed.select("Data set:", sets.map(s => [
156
+ s.label,
157
+ s
158
+ ]), undefined);
159
+ }
160
+ } else {
161
+ chosen = sets[0];
162
+ }
163
+ let connection = await connect();
164
+ Seed_Prompt$ReventlessSeed.close();
165
+ await assertStoreEmpty(connection.client, Stdlib_Option.getOr(chosen.probeViews, []));
166
+ started = [
167
+ chosen,
168
+ connection
169
+ ];
170
+ } catch (raw_message) {
171
+ let message = Primitive_exceptions.internalToException(raw_message);
172
+ if (message.RE_EXN_ID === Seed_Types$ReventlessSeed.Failed) {
173
+ abortStartup(message._1);
174
+ started = undefined;
175
+ } else {
176
+ abortStartup(Stdlib_Option.getOr(Stdlib_Option.flatMap(Stdlib_JsExn.fromException(message), Stdlib_JsExn.message), "unknown"));
177
+ started = undefined;
178
+ }
179
+ }
180
+ if (started === undefined) {
181
+ return;
182
+ }
183
+ let connection$1 = started[1];
184
+ let chosen$1 = started[0];
185
+ heading(`Seeding "` + chosen$1.label + `" into ` + connection$1.label);
186
+ return await run(() => chosen$1.seed(connection$1));
187
+ };
188
+ go();
189
+ }
190
+
108
191
  export {
109
192
  envOr,
110
193
  report,
@@ -113,6 +196,9 @@ export {
113
196
  verifyViews,
114
197
  unfillableWarnings,
115
198
  warn,
199
+ assertStoreEmpty,
116
200
  run,
201
+ abortStartup,
202
+ seed,
117
203
  }
118
204
  /* Stdlib_JsExn Not a pure module */
Binary file