@mccaskie-labs/workbench-nudges 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +5 -0
- package/README.md +65 -2
- package/dist/cli.d.ts +12 -0
- package/dist/cli.js +146 -0
- package/dist/config.d.ts +9 -0
- package/dist/config.js +140 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +10 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +15 -0
- package/dist/migration.d.ts +4 -0
- package/dist/migration.js +378 -0
- package/dist/nudges.d.ts +172 -0
- package/dist/nudges.js +371 -0
- package/dist/starters.d.ts +80 -0
- package/dist/starters.js +61 -0
- package/dist/styles.d.ts +34 -0
- package/dist/styles.js +70 -0
- package/dist/time.d.ts +18 -0
- package/dist/time.js +100 -0
- package/dist/types.d.ts +136 -0
- package/dist/types.js +3 -0
- package/dist/ui.d.ts +39 -0
- package/dist/ui.js +83 -0
- package/dist/words.d.ts +4 -0
- package/dist/words.js +121 -0
- package/package.json +48 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# @mccaskie-labs/workbench-nudges
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- First version (`docs/capabilities/09-follow-up-nudges.md`): `createNudges` over the app's own database with `nudgesMigration` (service role only). `start()` sets a rule going for a subject (refused with `not_allowed`, writing nothing, when the account's plan lacks `nudges`); `touch()` stops it on the rule's `stops_on` events, starts it over on `restarts_on`, and moves it on when the owner sent the follow-up (`we_replied`); `snooze()`, `dismiss()`, `due()` with each draft, and a daily `cleanup()` (ended nudges after 90 days, drafts after 30 at most). `tick()`, from the app's cron every 15 minutes, claims due rows with a lease under `skip locked` so overlapping runs draft each once, loads the latest facts through the app's `refresh`, ends a nudge whose date has passed, drafts with the reply drafter (alternatives when the date was taken), and sends one digest email a day per account with a count and no names. Quiet hours move a step to their end; days are local days. `workbench/nudges.json` is checked by `checkNudgeConfig` and `npx workbench-nudges generate` (at most three steps a rule), with `init` and `migration` commands, the `quote-follow-up` starter guide, `outreachRefresh` for workbench-social's contacts, and the Waiting for you list (`renderNudgeList`, `nudgeAction`; plain HTML; `wb-nudge-*`, `NUDGE_STYLES`; words in English, Tagalog and Taglish).
|
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mccaskie-labs/workbench-nudges
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Follow-up nudges for apps built on Workbench, a private platform: when a conversation goes quiet ("no reply in 3 days"), the follow-up shows in the app's Waiting for you list already drafted, and the owner gets one email a day saying how many are ready. Spec: `docs/capabilities/09-follow-up-nudges.md`. Published publicly so Workbench projects can install it with no token; it is not supported for other uses.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @mccaskie-labs/workbench-nudges
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Nudges remind the **business**. They never message its customer: the owner copies the draft and sends it.
|
|
10
|
+
|
|
11
|
+
## Set up
|
|
12
|
+
|
|
13
|
+
1. `npx workbench-nudges init` writes `workbench/nudges.json` (quotes with no reply, and businesses that haven't answered a first message) and the `quote-follow-up` reply guide. Edit them; the client questions in `capabilities/nudges.json` say how.
|
|
14
|
+
2. `npx workbench-ai replies generate`, then `npx workbench-nudges generate` checks the rules (no rule has more than three steps; every guide must exist) and writes `src/nudges.generated.ts` (`NUDGE_RULES`). Checks can run `npx workbench-nudges generate --check`.
|
|
15
|
+
3. `npx workbench-nudges migration` writes `nudgesMigration` and its down file. It creates functions, so Control asks for approval even on staging.
|
|
16
|
+
4. Add `"*/15 * * * *"` to `triggers.crons` in `wrangler.jsonc`, and `nudges` to a plan's features in `workbench/plans.json`.
|
|
17
|
+
|
|
18
|
+
## Use
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createNudges } from '@mccaskie-labs/workbench-nudges'
|
|
22
|
+
import { NUDGE_RULES } from './nudges.generated'
|
|
23
|
+
|
|
24
|
+
const nudges = createNudges({
|
|
25
|
+
db: serviceClient, ai, mailer, plans, rules: NUDGE_RULES,
|
|
26
|
+
// The latest facts when a step comes due: a date booked meanwhile gets alternatives.
|
|
27
|
+
refresh: async (n) => ({ facts: await quoteFacts(n.subject.id) }),
|
|
28
|
+
owners: async (account) => [{ email: await ownerEmail(account) }],
|
|
29
|
+
listUrl: (account) => `https://${host}/app/waiting`,
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
await nudges.start({ rule: 'quote-no-reply', account: venue.id, subject: { type: 'enquiry', id }, facts: { date: '2026-12-12' } })
|
|
33
|
+
await nudges.touch({ type: 'enquiry', id }, 'they_replied') // or booked, closed; we_replied when the owner sent the follow-up
|
|
34
|
+
|
|
35
|
+
// scheduled(), every 15 minutes:
|
|
36
|
+
ctx.waitUntil(nudges.tick())
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
- `tick()` claims the due rows with a lease (`for update skip locked`), so two cron runs at once draft each nudge once. It drafts with the reply drafter **when the step comes due**, never when it is set, and only if the account's plan has `nudges` (`plans.feature`; a `plans.meter` counts each draft).
|
|
40
|
+
- `skip_if.date_passed` ends a nudge whose `date` fact has passed; `skip_if.date_unavailable` offers the `alternatives` fact in the draft (or ends it with `"stop"`). The facts follow the reply drafter's names: `date`, `available` (`yes` or `no`), `alternatives`.
|
|
41
|
+
- Quiet hours move a step that would fall in them to their end. `"3d"` is three days on the local clock.
|
|
42
|
+
- After the last step, a nudge left alone ends `ends_after` (7 days) later. A rule never has more than three steps.
|
|
43
|
+
- The digest: one email a day per account with something due, from `digest_at` (the end of the quiet hours, or 08:00), with a count and a link, never a customer's name. `email_owner: "each"` emails as each comes due; `"none"` uses only the list.
|
|
44
|
+
- `cleanup()` once a day: ended nudges after 90 days, drafts after 30 at most (and as soon as their nudge moves on or ends).
|
|
45
|
+
- Outreach contacts (workbench-social): start `supplier-no-reply` with subject `{ type: 'outreach_contact', id }` when an opener is logged, and use `outreachRefresh(outreach)` as the refresh for that subject type: a contact that replied ends its nudge.
|
|
46
|
+
|
|
47
|
+
## The Waiting for you list
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { nudgeAction, renderNudgeList } from '@mccaskie-labs/workbench-nudges'
|
|
51
|
+
import { renderReplyBox } from '@mccaskie-labs/workbench-ai/reply-ui'
|
|
52
|
+
|
|
53
|
+
html = renderNudgeList(await nudges.due(account), { endpoint: '/app/waiting', replyBox: renderReplyBox, label: (n) => titleOf(n.subject) })
|
|
54
|
+
// The buttons post here, behind the owner's sign-in:
|
|
55
|
+
const r = await nudgeAction(nudges, fields, account) // sent, snooze (a day, out of quiet hours) or dismiss
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Every element carries a `wb-nudge-*` class with a default style (`NUDGE_STYLES`, written by `npx workbench-ui styles`); the draft uses the reply drafter's `wb-reply-*` box. Words are in `NUDGE_WORDS` (English, Tagalog, Taglish) under `ui.wbnudge.*`.
|
|
59
|
+
|
|
60
|
+
## Data
|
|
61
|
+
|
|
62
|
+
| Table | Holds | Kept |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `nudges` | rule, account, subject (an id in the app's own tables), step, due time, status, why it stopped, start()'s facts (ids and dates) | 90 days after it ends |
|
|
65
|
+
| `nudge_drafts` | the latest draft of a due nudge (may hold the customer's first name) | until the nudge moves on or ends; 30 days at most |
|
|
66
|
+
| `nudge_digests` | which accounts got the day's digest, and the count | 60 days |
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import type { NudgeConfig } from "./types.ts";
|
|
3
|
+
export declare const NUDGES_FILE = "workbench/nudges.json";
|
|
4
|
+
export declare const NUDGES_MODULE = "src/nudges.generated.ts";
|
|
5
|
+
/** The starting files `init` writes, by path. */
|
|
6
|
+
export declare function starterFiles(): Record<string, string>;
|
|
7
|
+
/** The generated module for a checked config. */
|
|
8
|
+
export declare function moduleText(c: NudgeConfig): string;
|
|
9
|
+
/** Reads and checks the project's nudges.json and that its guides exist. Throws naming every problem. */
|
|
10
|
+
export declare function readNudges(dir: string): NudgeConfig;
|
|
11
|
+
/** Runs one command; returns the exit code. */
|
|
12
|
+
export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void): number;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `npx workbench-nudges init [dir]`, run in a project's folder: writes
|
|
3
|
+
// workbench/nudges.json (the spec's two rules) and the quote-follow-up reply
|
|
4
|
+
// guide (workbench/replies/quote-follow-up.json). A file already there is
|
|
5
|
+
// left as it is.
|
|
6
|
+
//
|
|
7
|
+
// `npx workbench-nudges generate [--check] [dir]` reads workbench/nudges.json,
|
|
8
|
+
// checks it (more than three steps a rule is refused, so nobody is chased a
|
|
9
|
+
// fourth time; every guide must be in workbench/replies/), and writes
|
|
10
|
+
// src/nudges.generated.ts: NUDGE_RULES for createNudges. --check writes
|
|
11
|
+
// nothing and fails when the file is out of date or wrong.
|
|
12
|
+
//
|
|
13
|
+
// `npx workbench-nudges migration [dir]` writes nudgesMigration into
|
|
14
|
+
// supabase/migrations/<timestamp>_workbench_nudges.sql, and its down file into
|
|
15
|
+
// supabase/rollback/, unless a nudges migration is already there.
|
|
16
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { dirname, join, resolve } from "node:path";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
import { guidesOf, nudgeProblems } from "./config.js";
|
|
20
|
+
import { nudgesMigration } from "./migration.js";
|
|
21
|
+
import { QUOTE_FOLLOW_UP_GUIDE, STARTER_NUDGES } from "./starters.js";
|
|
22
|
+
const USAGE = "usage: workbench-nudges init [dir]\n workbench-nudges generate [--check] [dir]\n workbench-nudges migration [dir]";
|
|
23
|
+
export const NUDGES_FILE = "workbench/nudges.json";
|
|
24
|
+
export const NUDGES_MODULE = "src/nudges.generated.ts";
|
|
25
|
+
const json = (v) => `${JSON.stringify(v, null, 2)}\n`;
|
|
26
|
+
const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
|
|
27
|
+
/** The starting files `init` writes, by path. */
|
|
28
|
+
export function starterFiles() {
|
|
29
|
+
return {
|
|
30
|
+
[NUDGES_FILE]: json(STARTER_NUDGES),
|
|
31
|
+
"workbench/replies/quote-follow-up.json": json(QUOTE_FOLLOW_UP_GUIDE),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** The generated module for a checked config. */
|
|
35
|
+
export function moduleText(c) {
|
|
36
|
+
return [
|
|
37
|
+
`// Generated by \`npx workbench-nudges generate\` from ${NUDGES_FILE}. Don't edit: change the`,
|
|
38
|
+
"// JSON and generate again (Checks runs `npx workbench-nudges generate --check`).",
|
|
39
|
+
"",
|
|
40
|
+
'import type { NudgeConfig } from "@mccaskie-labs/workbench-nudges";',
|
|
41
|
+
"",
|
|
42
|
+
`export const NUDGE_RULES = ${JSON.stringify(c, null, 2)} as const satisfies NudgeConfig;`,
|
|
43
|
+
"",
|
|
44
|
+
"export type NudgeRuleName = keyof typeof NUDGE_RULES.rules;",
|
|
45
|
+
"",
|
|
46
|
+
].join("\n");
|
|
47
|
+
}
|
|
48
|
+
/** Reads and checks the project's nudges.json and that its guides exist. Throws naming every problem. */
|
|
49
|
+
export function readNudges(dir) {
|
|
50
|
+
const path = join(dir, NUDGES_FILE);
|
|
51
|
+
if (!existsSync(path))
|
|
52
|
+
throw new Error(`${NUDGES_FILE} is missing: run npx workbench-nudges init, then answer the nudges questions (capabilities/nudges.json, offer)`);
|
|
53
|
+
let parsed;
|
|
54
|
+
try {
|
|
55
|
+
parsed = JSON.parse(read(path));
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
throw new Error(`${NUDGES_FILE}: not valid JSON (${e.message})`);
|
|
59
|
+
}
|
|
60
|
+
const problems = nudgeProblems(parsed, NUDGES_FILE);
|
|
61
|
+
if (problems.length)
|
|
62
|
+
throw new Error(problems.join("\n"));
|
|
63
|
+
const config = parsed;
|
|
64
|
+
const missing = guidesOf(config).filter((g) => !existsSync(join(dir, "workbench/replies", `${g}.json`)));
|
|
65
|
+
if (missing.length) {
|
|
66
|
+
throw new Error(missing
|
|
67
|
+
.map((g) => `${NUDGES_FILE}: the reply guide ${g} isn't in workbench/replies/${g === "outreach-follow-up" ? " (npx workbench-social outreach init writes it)" : g === "quote-follow-up" ? " (npx workbench-nudges init writes it)" : ""}`)
|
|
68
|
+
.join("\n"));
|
|
69
|
+
}
|
|
70
|
+
return config;
|
|
71
|
+
}
|
|
72
|
+
function migrationStamp(at) {
|
|
73
|
+
return at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
74
|
+
}
|
|
75
|
+
/** Runs one command; returns the exit code. */
|
|
76
|
+
export function run(argv, log = console.log, err = console.error) {
|
|
77
|
+
const [command, ...args] = argv;
|
|
78
|
+
const check = args.includes("--check");
|
|
79
|
+
const rest = args.filter((a) => a !== "--check");
|
|
80
|
+
const bad = rest.find((a) => a.startsWith("--"));
|
|
81
|
+
if (!["init", "generate", "migration"].includes(command ?? "") || bad || (check && command !== "generate") || rest.length > 1) {
|
|
82
|
+
err(bad ? `${bad} isn't an option\n${USAGE}` : USAGE);
|
|
83
|
+
return 2;
|
|
84
|
+
}
|
|
85
|
+
const dir = resolve(rest[0] ?? ".");
|
|
86
|
+
try {
|
|
87
|
+
if (command === "init") {
|
|
88
|
+
for (const [path, text] of Object.entries(starterFiles())) {
|
|
89
|
+
const at = join(dir, path);
|
|
90
|
+
if (existsSync(at)) {
|
|
91
|
+
log(`${path} is already there; left as it is`);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
mkdirSync(dirname(at), { recursive: true });
|
|
95
|
+
writeFileSync(at, text);
|
|
96
|
+
log(`wrote ${path}`);
|
|
97
|
+
}
|
|
98
|
+
log("Now set time_zone in workbench/nudges.json to the country pack's, keep the rules the client wants, and run `npx workbench-ai replies generate` and `npx workbench-nudges generate`. The supplier-no-reply rule needs `npx workbench-social outreach init` (its outreach-follow-up guide).");
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
if (command === "migration") {
|
|
102
|
+
const folder = join(dir, "supabase/migrations");
|
|
103
|
+
if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_nudges.sql"))) {
|
|
104
|
+
log("supabase/migrations already has the nudges migration; nothing written");
|
|
105
|
+
return 0;
|
|
106
|
+
}
|
|
107
|
+
const name = `${migrationStamp(new Date())}_workbench_nudges.sql`;
|
|
108
|
+
mkdirSync(folder, { recursive: true });
|
|
109
|
+
mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
|
|
110
|
+
writeFileSync(join(folder, name), `-- workbench-nudges: follow-up nudges (docs/capabilities/09-follow-up-nudges.md)\n${nudgesMigration.up}`);
|
|
111
|
+
writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${nudgesMigration.down}`);
|
|
112
|
+
log(`wrote supabase/migrations/${name} and its down file`);
|
|
113
|
+
return 0;
|
|
114
|
+
}
|
|
115
|
+
const config = readNudges(dir);
|
|
116
|
+
const text = moduleText(config);
|
|
117
|
+
const out = join(dir, NUDGES_MODULE);
|
|
118
|
+
if (check) {
|
|
119
|
+
if (!existsSync(out) || read(out) !== text) {
|
|
120
|
+
err(`${NUDGES_MODULE} is out of date: run npx workbench-nudges generate`);
|
|
121
|
+
return 1;
|
|
122
|
+
}
|
|
123
|
+
log(`${NUDGES_MODULE} is up to date`);
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
127
|
+
writeFileSync(out, text);
|
|
128
|
+
const rules = Object.keys(config.rules);
|
|
129
|
+
log(`wrote ${NUDGES_MODULE}: ${rules.length} rule${rules.length === 1 ? "" : "s"} (${rules.join(", ")})`);
|
|
130
|
+
return 0;
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
err(e.message);
|
|
134
|
+
return 1;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const isMain = (() => {
|
|
138
|
+
try {
|
|
139
|
+
return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
})();
|
|
145
|
+
if (isMain)
|
|
146
|
+
process.exitCode = run(process.argv.slice(2));
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { NudgeConfig } from "./types.ts";
|
|
2
|
+
/** The most steps any rule may have, whatever max_steps says. */
|
|
3
|
+
export declare const MAX_STEPS = 3;
|
|
4
|
+
/** Every problem with a nudges.json, or none. */
|
|
5
|
+
export declare function nudgeProblems(value: unknown, where?: string): string[];
|
|
6
|
+
/** Checks workbench/nudges.json and returns it typed, or throws bad_config naming every problem. */
|
|
7
|
+
export declare function checkNudgeConfig(value: unknown): NudgeConfig;
|
|
8
|
+
/** The reply guides the rules draft with, each once. */
|
|
9
|
+
export declare function guidesOf(config: NudgeConfig): string[];
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// workbench/nudges.json (docs/capabilities/09-follow-up-nudges.md, "Config
|
|
2
|
+
// format"): checked here, by createNudges and by `npx workbench-nudges
|
|
3
|
+
// generate`, which refuses more than three steps a rule so nobody is chased a
|
|
4
|
+
// fourth time.
|
|
5
|
+
import { NudgesError } from "./errors.js";
|
|
6
|
+
import { clockMinutes, durationMinutes, validZone } from "./time.js";
|
|
7
|
+
/** The most steps any rule may have, whatever max_steps says. */
|
|
8
|
+
export const MAX_STEPS = 3;
|
|
9
|
+
const LANGS = ["en", "tl", "taglish"];
|
|
10
|
+
const NAME = /^[a-z][a-z0-9-]{0,39}$/;
|
|
11
|
+
const EVENT = /^[a-z][a-z0-9_]{0,39}$/;
|
|
12
|
+
const TOP = ["$schema", "format", "time_zone", "quiet_hours", "digest_at", "language", "max_steps", "retention_days", "draft_days", "plans", "rules"];
|
|
13
|
+
const RULE = ["starts_on", "stops_on", "restarts_on", "steps", "skip_if", "email_owner", "ends_after", "language"];
|
|
14
|
+
const NINETY_DAYS = 90 * 1440;
|
|
15
|
+
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
16
|
+
/** Every problem with a nudges.json, or none. */
|
|
17
|
+
export function nudgeProblems(value, where = "nudges.json") {
|
|
18
|
+
const p = [];
|
|
19
|
+
if (!isObj(value))
|
|
20
|
+
return [`${where}: not a JSON object`];
|
|
21
|
+
for (const k of Object.keys(value))
|
|
22
|
+
if (!TOP.includes(k))
|
|
23
|
+
p.push(`${k} isn't a nudges setting`);
|
|
24
|
+
if (value.format !== 1)
|
|
25
|
+
p.push("format must be 1");
|
|
26
|
+
if (!validZone(value.time_zone))
|
|
27
|
+
p.push("time_zone must be an IANA time zone, such as Asia/Manila");
|
|
28
|
+
if (value.quiet_hours !== undefined) {
|
|
29
|
+
const q = value.quiet_hours;
|
|
30
|
+
if (!isObj(q) || clockMinutes(q.from) === null || clockMinutes(q.to) === null || Object.keys(q).some((k) => k !== "from" && k !== "to")) {
|
|
31
|
+
p.push('quiet_hours must be { "from": "21:00", "to": "08:00" } (24-hour clock)');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (value.digest_at !== undefined && clockMinutes(value.digest_at) === null)
|
|
35
|
+
p.push('digest_at must be a time such as "08:00"');
|
|
36
|
+
if (value.language !== undefined && !LANGS.includes(value.language))
|
|
37
|
+
p.push(`language must be one of ${LANGS.join(", ")}`);
|
|
38
|
+
const whole = (k, min, max) => {
|
|
39
|
+
const v = value[k];
|
|
40
|
+
if (v !== undefined && (!Number.isInteger(v) || v < min || v > max))
|
|
41
|
+
p.push(`${k} must be a whole number from ${min} to ${max}`);
|
|
42
|
+
};
|
|
43
|
+
whole("max_steps", 1, MAX_STEPS);
|
|
44
|
+
whole("retention_days", 1, 365);
|
|
45
|
+
whole("draft_days", 1, 30);
|
|
46
|
+
const maxSteps = Number.isInteger(value.max_steps) ? Math.min(value.max_steps, MAX_STEPS) : MAX_STEPS;
|
|
47
|
+
if (value.plans !== undefined) {
|
|
48
|
+
const pl = value.plans;
|
|
49
|
+
const ok = (v) => v === undefined || (typeof v === "string" && /^[a-z][a-z0-9_]{0,39}$/.test(v));
|
|
50
|
+
if (!isObj(pl) || !ok(pl.feature) || !ok(pl.meter) || Object.keys(pl).some((k) => k !== "feature" && k !== "meter"))
|
|
51
|
+
p.push("plans must be { feature?, meter? }, each a plans.json name");
|
|
52
|
+
}
|
|
53
|
+
if (!isObj(value.rules) || Object.keys(value.rules).length === 0) {
|
|
54
|
+
p.push("rules must name at least one rule");
|
|
55
|
+
return p.map((x) => `${where}: ${x}`);
|
|
56
|
+
}
|
|
57
|
+
for (const [name, r] of Object.entries(value.rules)) {
|
|
58
|
+
const at = `rules.${name}`;
|
|
59
|
+
if (!NAME.test(name))
|
|
60
|
+
p.push(`${at}: a rule's name is lower case letters, digits and dashes`);
|
|
61
|
+
if (!isObj(r)) {
|
|
62
|
+
p.push(`${at}: not an object`);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
for (const k of Object.keys(r))
|
|
66
|
+
if (!RULE.includes(k))
|
|
67
|
+
p.push(`${at}.${k} isn't a rule setting`);
|
|
68
|
+
if (typeof r.starts_on !== "string" || !EVENT.test(r.starts_on))
|
|
69
|
+
p.push(`${at}.starts_on must be an event name such as quote_sent`);
|
|
70
|
+
const events = (k, required) => {
|
|
71
|
+
const v = r[k];
|
|
72
|
+
if (v === undefined && !required)
|
|
73
|
+
return [];
|
|
74
|
+
if (!Array.isArray(v) || (required && v.length === 0) || !v.every((e) => typeof e === "string" && EVENT.test(e))) {
|
|
75
|
+
p.push(`${at}.${k} must be a list of event names such as they_replied`);
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
return v;
|
|
79
|
+
};
|
|
80
|
+
const stops = events("stops_on", true);
|
|
81
|
+
const restarts = events("restarts_on", false);
|
|
82
|
+
for (const e of restarts)
|
|
83
|
+
if (stops.includes(e))
|
|
84
|
+
p.push(`${at}: ${e} can't both stop and restart the rule`);
|
|
85
|
+
if (!Array.isArray(r.steps) || r.steps.length === 0) {
|
|
86
|
+
p.push(`${at}.steps must be a list of one to ${maxSteps} steps`);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
if (r.steps.length > maxSteps)
|
|
90
|
+
p.push(`${at} has ${r.steps.length} steps; at most ${maxSteps} (max_steps), so nobody is chased a fourth time`);
|
|
91
|
+
r.steps.forEach((s, i) => {
|
|
92
|
+
const sat = `${at}.steps[${i}]`;
|
|
93
|
+
if (!isObj(s)) {
|
|
94
|
+
p.push(`${sat}: not an object`);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
for (const k of Object.keys(s))
|
|
98
|
+
if (!["after", "guide", "say"].includes(k))
|
|
99
|
+
p.push(`${sat}.${k} isn't a step setting`);
|
|
100
|
+
const mins = durationMinutes(s.after);
|
|
101
|
+
if (mins === null || mins > NINETY_DAYS)
|
|
102
|
+
p.push(`${sat}.after must be a duration up to 90 days, such as 3d, 12h or 30m`);
|
|
103
|
+
if (typeof s.guide !== "string" || !NAME.test(s.guide))
|
|
104
|
+
p.push(`${sat}.guide must be a reply guide's name (workbench/replies/<name>.json)`);
|
|
105
|
+
if (s.say !== undefined && (typeof s.say !== "string" || !s.say.trim() || s.say.length > 300))
|
|
106
|
+
p.push(`${sat}.say must be text up to 300 characters`);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
if (r.skip_if !== undefined) {
|
|
110
|
+
const s = r.skip_if;
|
|
111
|
+
if (!isObj(s) ||
|
|
112
|
+
(s.date_passed !== undefined && typeof s.date_passed !== "boolean") ||
|
|
113
|
+
(s.date_unavailable !== undefined && s.date_unavailable !== "offer_alternatives" && s.date_unavailable !== "stop") ||
|
|
114
|
+
Object.keys(s).some((k) => k !== "date_passed" && k !== "date_unavailable")) {
|
|
115
|
+
p.push(`${at}.skip_if must be { "date_passed": true|false, "date_unavailable": "offer_alternatives"|"stop" }`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (r.email_owner !== undefined && !["daily_digest", "each", "none"].includes(r.email_owner))
|
|
119
|
+
p.push(`${at}.email_owner must be daily_digest, each or none`);
|
|
120
|
+
if (r.ends_after !== undefined) {
|
|
121
|
+
const mins = durationMinutes(r.ends_after);
|
|
122
|
+
if (mins === null || mins > NINETY_DAYS)
|
|
123
|
+
p.push(`${at}.ends_after must be a duration up to 90 days, such as 7d`);
|
|
124
|
+
}
|
|
125
|
+
if (r.language !== undefined && !LANGS.includes(r.language))
|
|
126
|
+
p.push(`${at}.language must be one of ${LANGS.join(", ")}`);
|
|
127
|
+
}
|
|
128
|
+
return p.map((x) => `${where}: ${x}`);
|
|
129
|
+
}
|
|
130
|
+
/** Checks workbench/nudges.json and returns it typed, or throws bad_config naming every problem. */
|
|
131
|
+
export function checkNudgeConfig(value) {
|
|
132
|
+
const problems = nudgeProblems(value);
|
|
133
|
+
if (problems.length)
|
|
134
|
+
throw new NudgesError("bad_config", problems.join("; "));
|
|
135
|
+
return value;
|
|
136
|
+
}
|
|
137
|
+
/** The reply guides the rules draft with, each once. */
|
|
138
|
+
export function guidesOf(config) {
|
|
139
|
+
return [...new Set(Object.values(config.rules).flatMap((r) => r.steps.map((s) => s.guide)))].sort();
|
|
140
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type NudgesErrorCode =
|
|
2
|
+
/** workbench/nudges.json is out of shape (or a rule has more steps than max_steps). */
|
|
3
|
+
"bad_config"
|
|
4
|
+
/** A call's arguments are out of shape. */
|
|
5
|
+
| "bad_input"
|
|
6
|
+
/** No such rule in workbench/nudges.json. */
|
|
7
|
+
| "unknown_rule"
|
|
8
|
+
/** No such nudge, or it has ended. */
|
|
9
|
+
| "unknown_nudge"
|
|
10
|
+
/** The account's plan doesn't include nudges (or they are switched off for it). Nothing was written. */
|
|
11
|
+
| "not_allowed"
|
|
12
|
+
/** The database refused or failed. */
|
|
13
|
+
| "store_failed";
|
|
14
|
+
export declare class NudgesError extends Error {
|
|
15
|
+
readonly code: NudgesErrorCode;
|
|
16
|
+
constructor(code: NudgesErrorCode, message: string);
|
|
17
|
+
}
|
package/dist/errors.js
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { createNudges, outreachRefresh, type NudgeContext, type NudgeLink, type NudgeOwner, type NudgeRefresh, type Nudges, type NudgesAi, type NudgesClient, type NudgesMailer, type NudgesOptions, type NudgesPlans, type OutreachLike, type StartRequest, type TouchKind } from "./nudges.ts";
|
|
2
|
+
export { checkNudgeConfig, MAX_STEPS, nudgeProblems } from "./config.ts";
|
|
3
|
+
export { nudgesMigration } from "./migration.ts";
|
|
4
|
+
export { QUOTE_FOLLOW_UP_GUIDE, STARTER_NUDGES } from "./starters.ts";
|
|
5
|
+
export { nudgeAction, renderNudge, renderNudgeList, type ActionResult, type ListOptions, type Words } from "./ui.ts";
|
|
6
|
+
export { NUDGE_WORDS, NUDGE_WORD_KEYS, type NudgeWordKey } from "./words.ts";
|
|
7
|
+
export { NUDGE_STYLES } from "./styles.ts";
|
|
8
|
+
export { NudgesError, type NudgesErrorCode } from "./errors.ts";
|
|
9
|
+
export { NUDGE_STATUSES } from "./types.ts";
|
|
10
|
+
export type { DueNudge, DueReason, Duration, EmailOwner, Lang, Nudge, NudgeConfig, NudgeConfig as NudgeRules, NudgeDraft, NudgeRule, NudgeStatus, NudgeStep, Subject, TickResult } from "./types.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// @mccaskie-labs/workbench-nudges: follow-up nudges
|
|
2
|
+
// (docs/capabilities/09-follow-up-nudges.md). Remind the business to follow
|
|
3
|
+
// up when a conversation goes quiet, with the follow-up drafted by the reply
|
|
4
|
+
// drafter (capability 4) when it comes due. A store in the app's own database
|
|
5
|
+
// (nudgesMigration), a rules file (workbench/nudges.json), and tick() from the
|
|
6
|
+
// app's cron every 15 minutes. Nudges never message the business's customer.
|
|
7
|
+
export { createNudges, outreachRefresh } from "./nudges.js";
|
|
8
|
+
export { checkNudgeConfig, MAX_STEPS, nudgeProblems } from "./config.js";
|
|
9
|
+
export { nudgesMigration } from "./migration.js";
|
|
10
|
+
export { QUOTE_FOLLOW_UP_GUIDE, STARTER_NUDGES } from "./starters.js";
|
|
11
|
+
export { nudgeAction, renderNudge, renderNudgeList } from "./ui.js";
|
|
12
|
+
export { NUDGE_WORDS, NUDGE_WORD_KEYS } from "./words.js";
|
|
13
|
+
export { NUDGE_STYLES } from "./styles.js";
|
|
14
|
+
export { NudgesError } from "./errors.js";
|
|
15
|
+
export { NUDGE_STATUSES } from "./types.js";
|