kordexa 0.4.2 → 0.4.3
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.
- package/bin/kordexa.js +8 -2
- package/package.json +1 -1
- package/src/cli.js +171 -39
- package/src/email.js +68 -0
- package/src/prompts.js +433 -49
- package/src/research.js +12 -5
- package/src/setup-answers.js +282 -0
- package/src/workflow.js +3 -0
- package/tests/node/guided-setup.test.js +366 -0
- package/tests/node/resend.test.js +177 -0
package/bin/kordexa.js
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { main } from "../src/cli.js";
|
|
3
3
|
|
|
4
|
+
const FOLDER_ERRORS = {
|
|
5
|
+
EACCES: "Kordexa doesn't have permission to write in this folder. Try a folder you own.",
|
|
6
|
+
EPERM: "Kordexa doesn't have permission to write in this folder. Try a folder you own.",
|
|
7
|
+
EROFS: "This folder is read-only. Try a folder you can write to.",
|
|
8
|
+
ENOSPC: "Your disk is full. Free up some space and try again."
|
|
9
|
+
};
|
|
10
|
+
|
|
4
11
|
main(process.argv.slice(2)).catch((error) => {
|
|
5
|
-
console.error(error?.message || error);
|
|
12
|
+
console.error(FOLDER_ERRORS[error?.code] || error?.message || error);
|
|
6
13
|
process.exitCode = 1;
|
|
7
14
|
});
|
|
8
|
-
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -1,17 +1,42 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import { writeAgentAdapters } from "./adapters.js";
|
|
4
5
|
import { appendGitignore, loadConfig, loadEnvFile, readJson, resolveDataDir, saveConfig, writeJson, writeLocalEnv, validateConfig, CONFIG_FILE } from "./config.js";
|
|
5
6
|
import { createCoursePack, saveCoursePack } from "./courses.js";
|
|
6
|
-
import { sendMail, smtpConfigFromEnv } from "./email.js";
|
|
7
|
+
import { dailyEmailKey, resendConfigFromEnv, sendMail, sendWithResend, smtpConfigFromEnv } from "./email.js";
|
|
7
8
|
import { createHarness, saveHarness } from "./harness.js";
|
|
8
9
|
import { generate30DayPlan, renderDailyEmail } from "./planner.js";
|
|
9
10
|
import { buildProgressionCard, copyDefaultTerminalCard, saveProgressionCard } from "./progression-card.js";
|
|
10
11
|
import { appendProgress, createWeeklySummary, planStatus, reviewProgress } from "./progress.js";
|
|
11
|
-
import { collectOnboarding } from "./prompts.js";
|
|
12
|
+
import { SetupCancelled, askEmailDelivery, collectOnboarding, createTerminalIO } from "./prompts.js";
|
|
12
13
|
import { appendResearchIndex, createResearchDigest, enrichDigestLinks, saveResearchDigest } from "./research.js";
|
|
14
|
+
import { parsePlanDays } from "./setup-answers.js";
|
|
13
15
|
import { workflowStatus, writeGithubWorkflow } from "./workflow.js";
|
|
14
16
|
|
|
17
|
+
const COMMANDS = ["plan", "status", "harness", "courses", "research", "links", "send-today", "log-progress", "weekly-summary", "recommend-next", "progress-card", "terminal-card", "setup-email", "setup-secrets", "doctor", "help"];
|
|
18
|
+
const SETUP_VALUE_FLAGS = {
|
|
19
|
+
"--name": "name",
|
|
20
|
+
"--email": "email",
|
|
21
|
+
"--role": "targetRole",
|
|
22
|
+
"--target-role": "targetRole",
|
|
23
|
+
"--current-learning": "currentLearning",
|
|
24
|
+
"--skill": "focusSkill",
|
|
25
|
+
"--focus-skill": "focusSkill",
|
|
26
|
+
"--stage": "currentStage",
|
|
27
|
+
"--current-stage": "currentStage",
|
|
28
|
+
"--weekly-hours": "weeklyHours",
|
|
29
|
+
"--days": "planDays",
|
|
30
|
+
"--time": "dailyEmailTime",
|
|
31
|
+
"--timezone": "timezone",
|
|
32
|
+
"--smtp-host": "smtpHost",
|
|
33
|
+
"--smtp-port": "smtpPort",
|
|
34
|
+
"--smtp-user": "smtpUser",
|
|
35
|
+
"--smtp-pass": "smtpPass",
|
|
36
|
+
"--smtp-from": "smtpFrom"
|
|
37
|
+
};
|
|
38
|
+
const SETUP_SWITCHES = ["--yes", "--non-interactive", "--offline", "--restart", "--allow-home", "--json"];
|
|
39
|
+
|
|
15
40
|
export async function main(argv = []) {
|
|
16
41
|
const command = normalizeCommand(argv[0]);
|
|
17
42
|
if (command === "send-today") return sendToday(argv.slice(1));
|
|
@@ -26,9 +51,11 @@ export async function main(argv = []) {
|
|
|
26
51
|
if (command === "recommend-next") return recommendNext();
|
|
27
52
|
if (command === "progress-card") return progressCard();
|
|
28
53
|
if (command === "terminal-card") return terminalCard();
|
|
54
|
+
if (command === "setup-email") return setupEmail();
|
|
29
55
|
if (command === "setup-secrets") return setupSecrets();
|
|
30
56
|
if (command === "doctor") return doctor();
|
|
31
57
|
if (command === "help") return printHelp();
|
|
58
|
+
if (command !== "init" && !command.startsWith("-")) throw new Error(unknownCommandMessage(command));
|
|
32
59
|
return init(argv);
|
|
33
60
|
}
|
|
34
61
|
|
|
@@ -38,11 +65,72 @@ function normalizeCommand(value) {
|
|
|
38
65
|
return value;
|
|
39
66
|
}
|
|
40
67
|
|
|
68
|
+
function unknownCommandMessage(command) {
|
|
69
|
+
const closest = COMMANDS.map((name) => [name, editDistance(command, name)]).sort((a, b) => a[1] - b[1])[0];
|
|
70
|
+
const suggestion = closest[1] <= 3 ? ` Did you mean "${closest[0]}"?` : "";
|
|
71
|
+
return `Unknown command "${command}".${suggestion} Run npx kordexa --help to see every command.`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function editDistance(first, second) {
|
|
75
|
+
let previous = Array.from({ length: second.length + 1 }, (_, index) => index);
|
|
76
|
+
for (let row = 1; row <= first.length; row += 1) {
|
|
77
|
+
const current = [row];
|
|
78
|
+
for (let column = 1; column <= second.length; column += 1) {
|
|
79
|
+
const cost = first[row - 1] === second[column - 1] ? 0 : 1;
|
|
80
|
+
current[column] = Math.min(previous[column] + 1, current[column - 1] + 1, previous[column - 1] + cost);
|
|
81
|
+
}
|
|
82
|
+
previous = current;
|
|
83
|
+
}
|
|
84
|
+
return previous[second.length];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function isHomeOrRootFolder() {
|
|
88
|
+
const here = fs.realpathSync(process.cwd());
|
|
89
|
+
return here === path.parse(here).root || here === fs.realpathSync(os.homedir());
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Setup writes several files, so a learner's home folder needs a clear yes.
|
|
93
|
+
async function confirmProjectFolder({ io, allowHome }) {
|
|
94
|
+
if (allowHome || !isHomeOrRootFolder()) return;
|
|
95
|
+
const advice = "Create a project folder first: mkdir my-learning && cd my-learning";
|
|
96
|
+
if (!io) throw new Error(`Kordexa won't add files to your home folder. ${advice}`);
|
|
97
|
+
io.say("");
|
|
98
|
+
io.say("You're in your home folder, and Kordexa will add its files here.");
|
|
99
|
+
io.say(` ${advice}`);
|
|
100
|
+
const answer = (await io.ask("Continue here anyway? [y/N] ")).trim().toLowerCase();
|
|
101
|
+
if (answer !== "y" && answer !== "yes") throw new SetupCancelled("Setup stopped. Nothing was saved.");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function assertKnownSetupOptions(argv) {
|
|
105
|
+
const start = argv[0] && !argv[0].startsWith("-") ? 1 : 0;
|
|
106
|
+
for (let index = start; index < argv.length; index += 1) {
|
|
107
|
+
const option = argv[index];
|
|
108
|
+
if (SETUP_SWITCHES.includes(option)) continue;
|
|
109
|
+
if (!SETUP_VALUE_FLAGS[option]) throw new Error(`Unknown option "${option}". Run npx kordexa --help to see the options.`);
|
|
110
|
+
const value = argv[index + 1];
|
|
111
|
+
if (value === undefined || value.startsWith("--")) throw new Error(`Please add a value after ${option}.`);
|
|
112
|
+
index += 1;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
41
116
|
async function init(argv) {
|
|
117
|
+
assertKnownSetupOptions(argv);
|
|
42
118
|
const nonInteractive = argv.includes("--yes") || argv.includes("--non-interactive");
|
|
43
119
|
const overrides = parseKeyValues(argv);
|
|
44
120
|
const existing = existingSetup();
|
|
45
|
-
const
|
|
121
|
+
const io = nonInteractive ? null : createTerminalIO();
|
|
122
|
+
let answers;
|
|
123
|
+
try {
|
|
124
|
+
await confirmProjectFolder({ io, allowHome: argv.includes("--allow-home") });
|
|
125
|
+
answers = await collectOnboarding({ defaults: existing.defaults, nonInteractive, overrides, io });
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (!(error instanceof SetupCancelled)) throw error;
|
|
128
|
+
console.log(`\n${error.message}`);
|
|
129
|
+
process.exitCode = 130;
|
|
130
|
+
return;
|
|
131
|
+
} finally {
|
|
132
|
+
io?.close();
|
|
133
|
+
}
|
|
46
134
|
const config = {
|
|
47
135
|
version: 1,
|
|
48
136
|
command: "/kordexa",
|
|
@@ -80,6 +168,10 @@ async function init(argv) {
|
|
|
80
168
|
appendResearchIndex(config, digestPath, digest);
|
|
81
169
|
const workflowPath = writeGithubWorkflow(config);
|
|
82
170
|
const { warnings } = workflowStatus();
|
|
171
|
+
if (!nonInteractive && !argv.includes("--json")) {
|
|
172
|
+
printSetupComplete(config, plan, answers.emailConnected, warnings);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
83
175
|
outputJson({
|
|
84
176
|
status: "initialized",
|
|
85
177
|
command: "/kordexa",
|
|
@@ -97,6 +189,39 @@ async function init(argv) {
|
|
|
97
189
|
});
|
|
98
190
|
}
|
|
99
191
|
|
|
192
|
+
function printSetupComplete(config, plan, emailConnected, warnings) {
|
|
193
|
+
const { learner, schedule } = config;
|
|
194
|
+
console.log("");
|
|
195
|
+
console.log(`You're all set, ${learner.name}.`);
|
|
196
|
+
console.log(` Plan: ${plan.days.length} days toward ${learner.targetRole}`);
|
|
197
|
+
console.log(` First skill: ${learner.focusSkill}`);
|
|
198
|
+
console.log(` Daily email: ${schedule.dailyEmailTime} ${schedule.timezone}${emailConnected ? "" : " (not connected yet)"}`);
|
|
199
|
+
console.log(` Saved in: ${process.cwd()}`);
|
|
200
|
+
console.log("");
|
|
201
|
+
console.log("Next steps:");
|
|
202
|
+
console.log(" npx kordexa send-today --dry-run Preview today's plan");
|
|
203
|
+
if (!emailConnected) console.log(" npx kordexa setup-email Connect your email");
|
|
204
|
+
console.log(" npx kordexa status See your progress");
|
|
205
|
+
for (const warning of warnings) console.log(`\nWarning: ${warning}`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function setupEmail() {
|
|
209
|
+
const config = loadConfig();
|
|
210
|
+
const env = loadEnvFile(path.join(process.cwd(), ".env.local"));
|
|
211
|
+
const io = createTerminalIO();
|
|
212
|
+
try {
|
|
213
|
+
const email = await askEmailDelivery(io, { email: config.learner.email, smtpUser: env.SMTP_USER, smtpPass: env.SMTP_PASS });
|
|
214
|
+
writeLocalEnv({ SMTP_HOST: email.smtpHost, SMTP_PORT: email.smtpPort, SMTP_USER: email.smtpUser, SMTP_PASS: email.smtpPass, SMTP_FROM: email.smtpFrom });
|
|
215
|
+
if (email.smtpUser) console.log("\nEmail settings saved. Preview your plan with: npx kordexa send-today --dry-run");
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (!(error instanceof SetupCancelled)) throw error;
|
|
218
|
+
console.log("\nEmail setup stopped. Nothing was changed.");
|
|
219
|
+
process.exitCode = 130;
|
|
220
|
+
} finally {
|
|
221
|
+
io.close();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
100
225
|
// Re-running setup must not reset a learner's profile, email login or schedule.
|
|
101
226
|
function existingSetup() {
|
|
102
227
|
let config = null;
|
|
@@ -138,8 +263,12 @@ function regeneratePlan(argv) {
|
|
|
138
263
|
if (focusSkill) config.learner.focusSkill = focusSkill;
|
|
139
264
|
const currentLearning = valueAfter(argv, "--current-learning");
|
|
140
265
|
if (currentLearning) config.learner.currentLearning = currentLearning;
|
|
141
|
-
const
|
|
142
|
-
if (
|
|
266
|
+
const daysArg = valueAfter(argv, "--days");
|
|
267
|
+
if (daysArg !== undefined) {
|
|
268
|
+
const days = parsePlanDays(daysArg);
|
|
269
|
+
if (!days.ok) throw new Error(days.error);
|
|
270
|
+
config.learner.planDays = days.value;
|
|
271
|
+
}
|
|
143
272
|
const plan = generate30DayPlan(config.learner);
|
|
144
273
|
writeDataJson(config, "30-day-plan.json", plan);
|
|
145
274
|
saveConfig(config);
|
|
@@ -180,7 +309,10 @@ async function sendToday(argv) {
|
|
|
180
309
|
const env = { ...process.env, ...loadEnvFile(path.join(process.cwd(), ".env.local")) };
|
|
181
310
|
const smtp = smtpConfigFromEnv(env);
|
|
182
311
|
const message = renderDailyEmail(config, plan, day, { progressReview, researchDigest: digest, progressionCard, coursePack });
|
|
183
|
-
const
|
|
312
|
+
const resend = resendConfigFromEnv(env);
|
|
313
|
+
const result = resend && !dryRun
|
|
314
|
+
? await sendWithResend({ resend, message, idempotencyKey: dailyEmailKey(message.to, config.schedule?.startDate, day) })
|
|
315
|
+
: await sendMail({ smtp, message, dryRun });
|
|
184
316
|
writeDataJson(config, "latest-email.json", { generatedAt: new Date().toISOString(), researchDigest: digestPath, ...result });
|
|
185
317
|
outputJson(result);
|
|
186
318
|
}
|
|
@@ -201,7 +333,7 @@ function showStatus() {
|
|
|
201
333
|
|
|
202
334
|
async function research(argv) {
|
|
203
335
|
const { config, plan } = loadRuntime();
|
|
204
|
-
const day =
|
|
336
|
+
const day = parsePositiveDay(valueAfter(argv, "--day") ?? "1", plan);
|
|
205
337
|
const topic = valueAfter(argv, "--topic") || plan.days.find((entry) => entry.day === day)?.title || config.learner.targetRole;
|
|
206
338
|
const digest = createResearchDigest({ config, topic, day, roleKey: plan.roleKey });
|
|
207
339
|
await enrichDigestLinks(digest, { offline: argv.includes("--offline") });
|
|
@@ -212,7 +344,7 @@ async function research(argv) {
|
|
|
212
344
|
|
|
213
345
|
async function links(argv) {
|
|
214
346
|
const { config, plan } = loadRuntime();
|
|
215
|
-
const day =
|
|
347
|
+
const day = parsePositiveDay(valueAfter(argv, "--day") ?? "1", plan);
|
|
216
348
|
const topic = valueAfter(argv, "--topic") || plan.days.find((entry) => entry.day === day)?.title || config.learner.targetRole;
|
|
217
349
|
const digest = createResearchDigest({ config, topic, day, roleKey: plan.roleKey });
|
|
218
350
|
await enrichDigestLinks(digest, { offline: argv.includes("--offline"), limit: 3 });
|
|
@@ -248,10 +380,19 @@ function courses() {
|
|
|
248
380
|
|
|
249
381
|
function logProgress(argv) {
|
|
250
382
|
const { config, plan } = loadRuntime();
|
|
383
|
+
const completed = valueAfter(argv, "--completed")?.trim();
|
|
384
|
+
const evidence = valueAfter(argv, "--evidence")?.trim();
|
|
385
|
+
if (!completed || !evidence) {
|
|
386
|
+
throw new Error('Please say what you finished and link your proof: npx kordexa log-progress --completed "Built the demo" --evidence "github.com/me/demo"');
|
|
387
|
+
}
|
|
388
|
+
const dayArg = valueAfter(argv, "--day");
|
|
389
|
+
if (dayArg !== undefined) parsePositiveDay(dayArg, plan);
|
|
390
|
+
assertWholeNumber(valueAfter(argv, "--minutes"), "--minutes", 0, 1440);
|
|
391
|
+
assertWholeNumber(valueAfter(argv, "--confidence"), "--confidence", 1, 5);
|
|
251
392
|
const entry = appendProgress(config, {
|
|
252
|
-
day:
|
|
253
|
-
completed
|
|
254
|
-
evidence
|
|
393
|
+
day: dayArg,
|
|
394
|
+
completed,
|
|
395
|
+
evidence,
|
|
255
396
|
minutes: valueAfter(argv, "--minutes"),
|
|
256
397
|
confidence: valueAfter(argv, "--confidence"),
|
|
257
398
|
blocker: valueAfter(argv, "--blocker")
|
|
@@ -264,7 +405,8 @@ function logProgress(argv) {
|
|
|
264
405
|
|
|
265
406
|
function weeklySummary(argv) {
|
|
266
407
|
const { config, plan } = loadRuntime();
|
|
267
|
-
const
|
|
408
|
+
const totalWeeks = Math.ceil(plan.days.length / 7);
|
|
409
|
+
const week = assertWholeNumber(valueAfter(argv, "--week") ?? "1", "--week", 1, totalWeeks);
|
|
268
410
|
const summary = createWeeklySummary(config, plan, week);
|
|
269
411
|
writeDataJson(config, `weekly-summary-${week}.json`, summary);
|
|
270
412
|
outputJson(summary);
|
|
@@ -313,7 +455,7 @@ function terminalCard() {
|
|
|
313
455
|
function setupSecrets() {
|
|
314
456
|
const config = loadConfig();
|
|
315
457
|
const env = loadEnvFile(path.join(process.cwd(), ".env.local"));
|
|
316
|
-
const commands = [
|
|
458
|
+
const commands = env.RESEND_API_KEY ? ["gh secret set RESEND_API_KEY"] : [
|
|
317
459
|
secretCommand("SMTP_HOST", env.SMTP_HOST || "<smtp-host>"),
|
|
318
460
|
secretCommand("SMTP_PORT", env.SMTP_PORT || "465"),
|
|
319
461
|
secretCommand("SMTP_USER", env.SMTP_USER || "<smtp-user>"),
|
|
@@ -341,7 +483,7 @@ function doctor() {
|
|
|
341
483
|
|
|
342
484
|
const scheduled = workflowStatus();
|
|
343
485
|
const localSettings = { ...process.env, ...loadEnvFile(path.join(process.cwd(), ".env.local")) };
|
|
344
|
-
const missingEmailSettings = ["SMTP_HOST", "SMTP_USER", "SMTP_PASS"].filter((key) => !localSettings[key]);
|
|
486
|
+
const missingEmailSettings = localSettings.RESEND_API_KEY ? [] : ["SMTP_HOST", "SMTP_USER", "SMTP_PASS"].filter((key) => !localSettings[key]);
|
|
345
487
|
|
|
346
488
|
const checks = {
|
|
347
489
|
agentsMd: fs.existsSync(path.join(process.cwd(), "AGENTS.md")),
|
|
@@ -359,7 +501,7 @@ function doctor() {
|
|
|
359
501
|
const nextSteps = [];
|
|
360
502
|
if (!setupComplete || (!workflow && !scheduled.outdated)) nextSteps.push("Run npx kordexa to finish setup.");
|
|
361
503
|
if (needsUpgrade) nextSteps.push("Run npx kordexa --yes to update the scheduled workflow. Your profile, email settings, progress and start date are kept.");
|
|
362
|
-
if (!localEmail) nextSteps.push(`Add ${missingEmailSettings.join(", ")} to .env.local
|
|
504
|
+
if (!localEmail) nextSteps.push(`Add ${missingEmailSettings.join(", ")} to .env.local, or run npx kordexa setup-email to connect your email. For scheduled email, run npx kordexa setup-secrets.`);
|
|
363
505
|
let status = "ready";
|
|
364
506
|
if (!setupComplete || (!workflow && !scheduled.outdated)) status = "needs-setup";
|
|
365
507
|
else if (needsUpgrade) status = "needs-upgrade";
|
|
@@ -395,6 +537,7 @@ Commands:
|
|
|
395
537
|
npx kordexa recommend-next
|
|
396
538
|
npx kordexa progress-card
|
|
397
539
|
npx kordexa terminal-card
|
|
540
|
+
npx kordexa setup-email
|
|
398
541
|
npx kordexa setup-secrets
|
|
399
542
|
npx kordexa doctor
|
|
400
543
|
|
|
@@ -403,44 +546,33 @@ Note: /eduorchestrate stays available inside agents as a legacy alias for /korde
|
|
|
403
546
|
}
|
|
404
547
|
|
|
405
548
|
function parseKeyValues(argv) {
|
|
406
|
-
const map = {
|
|
407
|
-
"--name": "name",
|
|
408
|
-
"--email": "email",
|
|
409
|
-
"--role": "targetRole",
|
|
410
|
-
"--target-role": "targetRole",
|
|
411
|
-
"--current-learning": "currentLearning",
|
|
412
|
-
"--skill": "focusSkill",
|
|
413
|
-
"--focus-skill": "focusSkill",
|
|
414
|
-
"--stage": "currentStage",
|
|
415
|
-
"--current-stage": "currentStage",
|
|
416
|
-
"--weekly-hours": "weeklyHours",
|
|
417
|
-
"--days": "planDays",
|
|
418
|
-
"--time": "dailyEmailTime",
|
|
419
|
-
"--timezone": "timezone",
|
|
420
|
-
"--smtp-host": "smtpHost",
|
|
421
|
-
"--smtp-port": "smtpPort",
|
|
422
|
-
"--smtp-user": "smtpUser",
|
|
423
|
-
"--smtp-pass": "smtpPass",
|
|
424
|
-
"--smtp-from": "smtpFrom"
|
|
425
|
-
};
|
|
426
549
|
const overrides = {};
|
|
427
550
|
for (let index = 0; index < argv.length; index += 1) {
|
|
428
|
-
const key =
|
|
551
|
+
const key = SETUP_VALUE_FLAGS[argv[index]];
|
|
429
552
|
if (key && argv[index + 1]) overrides[key] = argv[index + 1];
|
|
430
553
|
}
|
|
431
554
|
return overrides;
|
|
432
555
|
}
|
|
433
556
|
|
|
557
|
+
function assertWholeNumber(value, flag, min, max) {
|
|
558
|
+
if (value === undefined) return undefined;
|
|
559
|
+
const number = Number(value);
|
|
560
|
+
if (!/^\d+$/.test(String(value)) || number < min || number > max) {
|
|
561
|
+
throw new Error(`${flag} must be a whole number from ${min} to ${max}.`);
|
|
562
|
+
}
|
|
563
|
+
return number;
|
|
564
|
+
}
|
|
565
|
+
|
|
434
566
|
function valueAfter(argv, flag) {
|
|
435
567
|
const index = argv.indexOf(flag);
|
|
436
568
|
return index >= 0 ? argv[index + 1] : undefined;
|
|
437
569
|
}
|
|
438
570
|
|
|
439
571
|
function parsePositiveDay(value, plan) {
|
|
440
|
-
|
|
572
|
+
const lastDay = plan?.days?.length || 1;
|
|
441
573
|
const day = Number.parseInt(value, 10);
|
|
442
|
-
if (
|
|
443
|
-
if (plan?.days?.length && day >
|
|
574
|
+
if (!/^\d+$/.test(String(value || "")) || day < 1) throw new Error(`--day must be a whole number from 1 to ${lastDay}.`);
|
|
575
|
+
if (plan?.days?.length && day > lastDay) throw new Error(`Day ${day} is outside this ${lastDay}-day plan.`);
|
|
444
576
|
return day;
|
|
445
577
|
}
|
|
446
578
|
|
package/src/email.js
CHANGED
|
@@ -12,6 +12,74 @@ export function smtpConfigFromEnv(env = process.env) {
|
|
|
12
12
|
};
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
const RESEND_ENDPOINT = "https://api.resend.com/emails";
|
|
16
|
+
const RESEND_TEST_SENDER = "Kordexa <onboarding@resend.dev>";
|
|
17
|
+
const RESEND_TIMEOUT_MS = 15000;
|
|
18
|
+
const RESEND_MAX_ATTEMPTS = 3;
|
|
19
|
+
|
|
20
|
+
export function resendConfigFromEnv(env = process.env) {
|
|
21
|
+
if (!env.RESEND_API_KEY) return null;
|
|
22
|
+
return { apiKey: env.RESEND_API_KEY, from: env.RESEND_FROM || RESEND_TEST_SENDER };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The key stays the same for one learner's plan day, so a retry can't send twice.
|
|
26
|
+
export function dailyEmailKey(to, startDate, day) {
|
|
27
|
+
const learner = crypto.createHash("sha256").update(String(to).toLowerCase()).digest("hex").slice(0, 24);
|
|
28
|
+
return `kordexa-${learner}-${startDate || "unscheduled"}-day-${day}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function sendWithResend({ resend, message, idempotencyKey, wait = delay }) {
|
|
32
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
33
|
+
let response;
|
|
34
|
+
try {
|
|
35
|
+
response = await fetch(RESEND_ENDPOINT, {
|
|
36
|
+
method: "POST",
|
|
37
|
+
signal: AbortSignal.timeout(RESEND_TIMEOUT_MS),
|
|
38
|
+
headers: {
|
|
39
|
+
authorization: `Bearer ${resend.apiKey}`,
|
|
40
|
+
"content-type": "application/json",
|
|
41
|
+
"user-agent": "kordexa-cli",
|
|
42
|
+
...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {})
|
|
43
|
+
},
|
|
44
|
+
body: JSON.stringify({ from: resend.from, to: [message.to], subject: message.subject, html: message.html, text: message.text })
|
|
45
|
+
});
|
|
46
|
+
} catch {
|
|
47
|
+
if (attempt < RESEND_MAX_ATTEMPTS) {
|
|
48
|
+
await wait(attempt * 1000);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
throw new Error("Couldn't reach Resend. Check your internet connection and try again.");
|
|
52
|
+
}
|
|
53
|
+
if (response.ok) {
|
|
54
|
+
const { id } = await response.json();
|
|
55
|
+
return { sent: true, to: message.to, subject: message.subject, transport: "resend", id };
|
|
56
|
+
}
|
|
57
|
+
if ((response.status === 429 || response.status >= 500) && attempt < RESEND_MAX_ATTEMPTS) {
|
|
58
|
+
const retryAfter = Number(response.headers?.get?.("retry-after"));
|
|
59
|
+
await wait(Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : attempt * 1000);
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
throw new Error(await resendErrorMessage(response, message.to));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function resendErrorMessage(response, to) {
|
|
67
|
+
const details = await response.json().catch(() => ({}));
|
|
68
|
+
const reason = String(details.message || "");
|
|
69
|
+
if (response.status === 401 || /api key/i.test(reason)) {
|
|
70
|
+
return "Resend didn't accept the API key. Create a new key at resend.com/api-keys and update RESEND_API_KEY in .env.local.";
|
|
71
|
+
}
|
|
72
|
+
if (response.status === 403 && /testing emails|verify a domain/i.test(reason)) {
|
|
73
|
+
return `Resend's free test sender can only email the address on your Resend account, so it can't send to ${to}. Use that address, or verify a domain in Resend.`;
|
|
74
|
+
}
|
|
75
|
+
if (response.status === 429) return "Resend's sending limit was reached. Please try again later.";
|
|
76
|
+
return `Resend couldn't send this email (error ${response.status}). ${reason}`.trim();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function delay(ms) {
|
|
80
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
81
|
+
}
|
|
82
|
+
|
|
15
83
|
export async function sendMail({ smtp, message, dryRun = false }) {
|
|
16
84
|
if (dryRun) {
|
|
17
85
|
return { dryRun: true, message };
|