@getvitops/utils 3.0.0 → 4.0.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 +70 -0
- package/README.md +1 -1
- package/dist/indexing/index.d.mts +4 -7
- package/dist/indexing/index.d.mts.map +1 -1
- package/dist/indexing/index.mjs +13 -37
- package/dist/indexing/index.mjs.map +1 -1
- package/dist/notify/index.d.mts +207 -0
- package/dist/notify/index.d.mts.map +1 -0
- package/dist/notify/index.mjs +320 -0
- package/dist/notify/index.mjs.map +1 -0
- package/dist/onboarding/index.d.mts +231 -0
- package/dist/onboarding/index.d.mts.map +1 -0
- package/dist/onboarding/index.mjs +448 -0
- package/dist/onboarding/index.mjs.map +1 -0
- package/dist/platform-CIdwwI_Z.mjs +88 -0
- package/dist/platform-CIdwwI_Z.mjs.map +1 -0
- package/dist/token--18wN9UR.d.mts +46 -0
- package/dist/token--18wN9UR.d.mts.map +1 -0
- package/dist/token-BV7tPHh2.mjs +96 -0
- package/dist/token-BV7tPHh2.mjs.map +1 -0
- package/dist/tracking/index.d.mts +88 -0
- package/dist/tracking/index.d.mts.map +1 -0
- package/dist/tracking/index.mjs +77 -0
- package/dist/tracking/index.mjs.map +1 -0
- package/dist/types-C3lHaSrU.d.mts +69 -0
- package/dist/types-C3lHaSrU.d.mts.map +1 -0
- package/package.json +13 -1
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { n as identifyPlatform, t as getPrimaryClickId } from "../platform-CIdwwI_Z.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/notify/email.ts
|
|
4
|
+
/**
|
|
5
|
+
* Provider errors worth retrying.
|
|
6
|
+
*
|
|
7
|
+
* Everything else is a configuration fault — an unverified sender, a malformed
|
|
8
|
+
* payload, a suppressed recipient — where a retry is pure latency and the send
|
|
9
|
+
* will fail identically. Retrying those also burns the daily quota.
|
|
10
|
+
*/
|
|
11
|
+
const RETRYABLE = new Set([
|
|
12
|
+
"E_RATE_LIMIT_EXCEEDED",
|
|
13
|
+
"E_DELIVERY_FAILED",
|
|
14
|
+
"E_INTERNAL_SERVER_ERROR"
|
|
15
|
+
]);
|
|
16
|
+
function codeOf(error) {
|
|
17
|
+
const code = error?.code;
|
|
18
|
+
return typeof code === "string" ? code : void 0;
|
|
19
|
+
}
|
|
20
|
+
function messageOf(error) {
|
|
21
|
+
return error instanceof Error ? error.message : String(error);
|
|
22
|
+
}
|
|
23
|
+
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
24
|
+
/**
|
|
25
|
+
* Send one rendered message according to a plan.
|
|
26
|
+
*
|
|
27
|
+
* Never throws: a failed notification must not take down the request that
|
|
28
|
+
* produced it. The visitor has already submitted their form, and failing their
|
|
29
|
+
* response because our mail didn't go out would turn a lost notification into a
|
|
30
|
+
* lost conversion. The failure is returned instead, for the caller to log.
|
|
31
|
+
*/
|
|
32
|
+
async function sendEmail(plan, message, binding, options = {}) {
|
|
33
|
+
if (!plan.enabled || !plan.to || !plan.from) return {
|
|
34
|
+
channel: "email",
|
|
35
|
+
sent: false,
|
|
36
|
+
reason: plan.skip ?? "Channel not enabled."
|
|
37
|
+
};
|
|
38
|
+
const attempts = Math.max(1, options.attempts ?? 3);
|
|
39
|
+
const sleep = options.sleep ?? wait;
|
|
40
|
+
for (let attempt = 1; attempt <= attempts; attempt++) try {
|
|
41
|
+
await binding.send({
|
|
42
|
+
to: plan.to,
|
|
43
|
+
from: plan.fromName ? {
|
|
44
|
+
email: plan.from,
|
|
45
|
+
name: plan.fromName
|
|
46
|
+
} : { email: plan.from },
|
|
47
|
+
subject: message.subject,
|
|
48
|
+
text: message.text,
|
|
49
|
+
html: message.html,
|
|
50
|
+
...plan.replyTo ? { replyTo: plan.replyTo } : {}
|
|
51
|
+
});
|
|
52
|
+
return {
|
|
53
|
+
channel: "email",
|
|
54
|
+
sent: true
|
|
55
|
+
};
|
|
56
|
+
} catch (error) {
|
|
57
|
+
const code = codeOf(error);
|
|
58
|
+
if (attempt === attempts || !code || !RETRYABLE.has(code)) return {
|
|
59
|
+
channel: "email",
|
|
60
|
+
sent: false,
|
|
61
|
+
reason: messageOf(error),
|
|
62
|
+
...code ? { code } : {}
|
|
63
|
+
};
|
|
64
|
+
await sleep(2 ** (attempt - 1) * 250);
|
|
65
|
+
}
|
|
66
|
+
/* c8 ignore next -- the loop always returns; this satisfies the type checker. */
|
|
67
|
+
return {
|
|
68
|
+
channel: "email",
|
|
69
|
+
sent: false,
|
|
70
|
+
reason: "Exhausted attempts."
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Print the message instead of sending it.
|
|
75
|
+
*
|
|
76
|
+
* The dev path, for a machine with no binding. Explicit rather than a silent
|
|
77
|
+
* no-op, because "I never saw the notification" is the symptom of both a broken
|
|
78
|
+
* integration and a working one nobody could observe.
|
|
79
|
+
*/
|
|
80
|
+
function logEmail(plan, message, log = console.log) {
|
|
81
|
+
log([
|
|
82
|
+
"\n========== NOTIFICATION EMAIL (not sent — no binding) ==========",
|
|
83
|
+
`To: ${plan.to ?? "(unresolved)"}`,
|
|
84
|
+
`From: ${plan.from ?? "(unresolved)"}`,
|
|
85
|
+
`Subject: ${message.subject}`,
|
|
86
|
+
"---",
|
|
87
|
+
message.text,
|
|
88
|
+
"================================================================\n"
|
|
89
|
+
].join("\n"));
|
|
90
|
+
return {
|
|
91
|
+
channel: "email",
|
|
92
|
+
sent: false,
|
|
93
|
+
reason: "No binding — logged to the console."
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/notify/plan.ts
|
|
99
|
+
/** Default Workers binding name for Cloudflare Email Sending. */
|
|
100
|
+
const DEFAULT_EMAIL_BINDING = "EMAIL";
|
|
101
|
+
/** Normalise the `email` shorthand: a bare address means a Cloudflare send to it. */
|
|
102
|
+
function normalizeEmailChannel(input) {
|
|
103
|
+
if (input === void 0) return void 0;
|
|
104
|
+
return typeof input === "string" ? {
|
|
105
|
+
provider: "cloudflare",
|
|
106
|
+
to: input
|
|
107
|
+
} : input;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Who the notification reaches.
|
|
111
|
+
*
|
|
112
|
+
* An explicit recipient wins; otherwise it falls to the site's own contact
|
|
113
|
+
* addresses, primary first. This cascade is why a site that has already said
|
|
114
|
+
* where it receives mail doesn't have to say it twice.
|
|
115
|
+
*/
|
|
116
|
+
function resolveRecipient(channel, ctx) {
|
|
117
|
+
if (channel.to) return channel.to;
|
|
118
|
+
return ctx.locationEmails?.find((e) => !!e);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* The From address.
|
|
122
|
+
*
|
|
123
|
+
* `noreply@<canonical>` by default, because the sending domain has to be one the
|
|
124
|
+
* site controls — Cloudflare rejects anything else with `E_SENDER_NOT_VERIFIED`,
|
|
125
|
+
* and guessing from the recipient's domain would send that failure every time.
|
|
126
|
+
*/
|
|
127
|
+
function resolveSender(channel, ctx) {
|
|
128
|
+
if (channel.from) return channel.from;
|
|
129
|
+
if (!ctx.canonical) return void 0;
|
|
130
|
+
let host;
|
|
131
|
+
try {
|
|
132
|
+
host = new URL(ctx.canonical).hostname;
|
|
133
|
+
} catch {
|
|
134
|
+
host = ctx.canonical.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
|
|
135
|
+
}
|
|
136
|
+
return host ? `noreply@${host}` : void 0;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Decide what will be sent, and say why anything won't be.
|
|
140
|
+
*
|
|
141
|
+
* Every "off" carries a reason rather than being an absence, so a caller can
|
|
142
|
+
* report the misconfiguration instead of reporting success over a no-op.
|
|
143
|
+
*/
|
|
144
|
+
function planNotifications(ctx) {
|
|
145
|
+
const email = planEmail(ctx);
|
|
146
|
+
return {
|
|
147
|
+
email,
|
|
148
|
+
empty: !email.enabled
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function planEmail(ctx) {
|
|
152
|
+
const channel = normalizeEmailChannel(ctx.notifications?.email);
|
|
153
|
+
const binding = channel?.binding ?? "EMAIL";
|
|
154
|
+
if (!channel) return {
|
|
155
|
+
provider: "cloudflare",
|
|
156
|
+
binding,
|
|
157
|
+
enabled: false,
|
|
158
|
+
skip: "No `notifications.email` configured."
|
|
159
|
+
};
|
|
160
|
+
const to = resolveRecipient(channel, ctx);
|
|
161
|
+
if (!to) return {
|
|
162
|
+
provider: "cloudflare",
|
|
163
|
+
binding,
|
|
164
|
+
enabled: false,
|
|
165
|
+
skip: "No recipient: set `notifications.email.to`, or give a location an `email` so the notification has somewhere to go."
|
|
166
|
+
};
|
|
167
|
+
const from = resolveSender(channel, ctx);
|
|
168
|
+
if (!from) return {
|
|
169
|
+
provider: "cloudflare",
|
|
170
|
+
binding,
|
|
171
|
+
to,
|
|
172
|
+
enabled: false,
|
|
173
|
+
skip: "No sender: set `notifications.email.from`, or `domains.canonical` so `noreply@<host>` can be derived. Cloudflare only sends from a domain you have onboarded."
|
|
174
|
+
};
|
|
175
|
+
return {
|
|
176
|
+
provider: "cloudflare",
|
|
177
|
+
binding,
|
|
178
|
+
to,
|
|
179
|
+
from,
|
|
180
|
+
fromName: channel.fromName ?? ctx.organizationName,
|
|
181
|
+
replyTo: channel.replyTo,
|
|
182
|
+
enabled: true
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
//#endregion
|
|
187
|
+
//#region src/notify/render.ts
|
|
188
|
+
/**
|
|
189
|
+
* Turning a `ConversionEvent` into something a person reads.
|
|
190
|
+
*
|
|
191
|
+
* Pure, and separate from both the plan and the sender, because rendering is the
|
|
192
|
+
* part that differs per channel: an SMS channel will render the same event in 160
|
|
193
|
+
* characters, a portal log as a row. The event stays the fact; only this file has
|
|
194
|
+
* an opinion about prose.
|
|
195
|
+
*
|
|
196
|
+
* The layout is three sections — who got in touch, which ad sent them, and what
|
|
197
|
+
* the request looked like — because that is the order the reader needs them in.
|
|
198
|
+
* The contact details are the point; attribution is why it matters; the visitor
|
|
199
|
+
* context is for when something looks wrong.
|
|
200
|
+
*/
|
|
201
|
+
/**
|
|
202
|
+
* Fields never worth putting in a notification.
|
|
203
|
+
*
|
|
204
|
+
* A honeypot is not visitor-supplied — it is bait, and reporting it as something
|
|
205
|
+
* they submitted is untrue. The same rule `legal/derive.ts` applies when deriving
|
|
206
|
+
* `piiCollected`, and for the same reason. Callers may strip more.
|
|
207
|
+
*/
|
|
208
|
+
const OMIT_FIELDS = new Set([
|
|
209
|
+
"website",
|
|
210
|
+
"_honeypot",
|
|
211
|
+
"honeypot",
|
|
212
|
+
"cf-turnstile-response"
|
|
213
|
+
]);
|
|
214
|
+
function label(key) {
|
|
215
|
+
return key.charAt(0).toUpperCase() + key.slice(1).replace(/[_-]/g, " ");
|
|
216
|
+
}
|
|
217
|
+
function escapeHtml(value) {
|
|
218
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* The event as sections — the shared structure behind both renderings.
|
|
222
|
+
*
|
|
223
|
+
* Extracted so the text and HTML versions cannot disagree about content. They
|
|
224
|
+
* differ only in markup; a field added here appears in both.
|
|
225
|
+
*/
|
|
226
|
+
function describeEvent(event) {
|
|
227
|
+
const t = event.tracking;
|
|
228
|
+
const platform = t ? identifyPlatform(t) : null;
|
|
229
|
+
const clickId = t ? getPrimaryClickId(t) : null;
|
|
230
|
+
const contact = [];
|
|
231
|
+
let subject;
|
|
232
|
+
if (event.type === "form" && event.formData) {
|
|
233
|
+
subject = `[Contact Form] New submission from ${event.formData["name"] ?? "Unknown"}`;
|
|
234
|
+
for (const [key, value] of Object.entries(event.formData)) if (!OMIT_FIELDS.has(key) && value) contact.push([label(key), value]);
|
|
235
|
+
} else {
|
|
236
|
+
const phone = event.phone ?? "unknown";
|
|
237
|
+
subject = `[Phone Call] Visitor calling ${phone}`;
|
|
238
|
+
contact.push(["Phone", phone]);
|
|
239
|
+
}
|
|
240
|
+
const attribution = [];
|
|
241
|
+
if (t) {
|
|
242
|
+
if (platform) attribution.push(["Platform", platform]);
|
|
243
|
+
if (clickId) attribution.push([`Click ID (${clickId.param})`, clickId.value]);
|
|
244
|
+
for (const key of [
|
|
245
|
+
"utm_campaign",
|
|
246
|
+
"utm_source",
|
|
247
|
+
"utm_medium",
|
|
248
|
+
"utm_content",
|
|
249
|
+
"utm_term"
|
|
250
|
+
]) {
|
|
251
|
+
const value = t[key];
|
|
252
|
+
if (value) attribution.push([label(key.replace("utm_", "")), String(value)]);
|
|
253
|
+
}
|
|
254
|
+
if (t.ab_variant) attribution.push(["A/B variant", t.ab_variant]);
|
|
255
|
+
}
|
|
256
|
+
const context = [];
|
|
257
|
+
if (t?.landingPage) context.push(["Landing page", t.landingPage]);
|
|
258
|
+
if (t?.referrer) context.push(["Referrer", t.referrer]);
|
|
259
|
+
if (t?.ts) context.push(["First visit", new Date(t.ts).toISOString()]);
|
|
260
|
+
context.push(["Received", new Date(event.at).toISOString()]);
|
|
261
|
+
if (event.userAgent) context.push(["User agent", event.userAgent]);
|
|
262
|
+
if (event.ip) context.push(["IP", event.ip]);
|
|
263
|
+
const sections = [
|
|
264
|
+
{
|
|
265
|
+
heading: "Contact details",
|
|
266
|
+
lines: contact
|
|
267
|
+
},
|
|
268
|
+
{
|
|
269
|
+
heading: "Ad attribution",
|
|
270
|
+
lines: attribution.length ? attribution : [["Source", "None — visitor arrived without ad tracking"]]
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
heading: "Visitor context",
|
|
274
|
+
lines: context
|
|
275
|
+
}
|
|
276
|
+
];
|
|
277
|
+
return {
|
|
278
|
+
subject,
|
|
279
|
+
sections: sections.filter((s) => s.lines.length)
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/** Render for e-mail. Both halves, always — see `RenderedMessage`. */
|
|
283
|
+
function renderEmail(event) {
|
|
284
|
+
const { subject, sections } = describeEvent(event);
|
|
285
|
+
return {
|
|
286
|
+
subject,
|
|
287
|
+
text: sections.map((s) => [`--- ${s.heading} ---`, ...s.lines.map(([k, v]) => `${k}: ${v}`)].join("\n")).join("\n\n"),
|
|
288
|
+
html: sections.map((s) => `<h2 style="font:600 14px system-ui;margin:24px 0 8px">${escapeHtml(s.heading)}</h2><table style="font:14px system-ui;border-collapse:collapse">${s.lines.map(([k, v]) => `<tr><td style="padding:2px 12px 2px 0;color:#666;vertical-align:top">${escapeHtml(k)}</td><td style="padding:2px 0">${escapeHtml(v)}</td></tr>`).join("")}</table>`).join("")
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
//#endregion
|
|
293
|
+
//#region src/notify/index.ts
|
|
294
|
+
/**
|
|
295
|
+
* Notify every configured channel about a conversion.
|
|
296
|
+
*
|
|
297
|
+
* Channels are independent: one failing must not stop the others, and none of
|
|
298
|
+
* them may throw into the request that produced the event. Every outcome —
|
|
299
|
+
* delivered, skipped, failed — comes back as data for the caller to log.
|
|
300
|
+
*/
|
|
301
|
+
async function notify(event, ctx, deps = {}) {
|
|
302
|
+
const plan = planNotifications(ctx);
|
|
303
|
+
const results = [];
|
|
304
|
+
if (plan.email.enabled) {
|
|
305
|
+
const message = renderEmail(event);
|
|
306
|
+
results.push(deps.email ? await sendEmail(plan.email, message, deps.email) : logEmail(plan.email, message));
|
|
307
|
+
} else results.push({
|
|
308
|
+
channel: "email",
|
|
309
|
+
sent: false,
|
|
310
|
+
reason: plan.email.skip ?? "Not configured."
|
|
311
|
+
});
|
|
312
|
+
return {
|
|
313
|
+
results,
|
|
314
|
+
delivered: results.some((r) => r.sent)
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
//#endregion
|
|
319
|
+
export { DEFAULT_EMAIL_BINDING, describeEvent, logEmail, normalizeEmailChannel, notify, planNotifications, renderEmail, resolveRecipient, resolveSender, sendEmail };
|
|
320
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/notify/email.ts","../../src/notify/plan.ts","../../src/notify/render.ts","../../src/notify/index.ts"],"sourcesContent":["/**\n * The e-mail channel — Cloudflare Email Sending.\n *\n * I/O only: it executes an `EmailPlan` and decides nothing. Whether to send, to\n * whom, and from where were all settled in `plan.ts`.\n *\n * **The binding is passed in, never imported.** `@getvitops/utils` does not depend\n * on `cloudflare:workers`, so this module runs in Node and in a test with a stub,\n * and the Astro package gains no Cloudflare coupling. The consumer's route hands\n * over `env.EMAIL`.\n *\n * Uses the current Email Sending binding — a structured `send({ to, from,\n * subject, html, text })` — not the legacy `EmailMessage` + hand-built MIME path.\n * The domain in `from` must have been onboarded (`wrangler email sending enable\n * <domain>`); nothing here can check that, which is why `E_SENDER_NOT_VERIFIED`\n * is surfaced verbatim rather than collapsed into \"send failed\".\n */\nimport type { RenderedMessage } from './types.ts';\nimport type { ChannelResult, EmailBinding, EmailPlan } from './types.ts';\n\n/**\n * Provider errors worth retrying.\n *\n * Everything else is a configuration fault — an unverified sender, a malformed\n * payload, a suppressed recipient — where a retry is pure latency and the send\n * will fail identically. Retrying those also burns the daily quota.\n */\nconst RETRYABLE = new Set([\n 'E_RATE_LIMIT_EXCEEDED',\n 'E_DELIVERY_FAILED',\n 'E_INTERNAL_SERVER_ERROR',\n]);\n\nfunction codeOf(error: unknown): string | undefined {\n const code = (error as { code?: unknown } | null)?.code;\n return typeof code === 'string' ? code : undefined;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport interface SendEmailOptions {\n /** Attempts for a retryable failure (default 3). */\n attempts?: number;\n /** Injected for tests; real callers let it default to a real delay. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nconst wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Send one rendered message according to a plan.\n *\n * Never throws: a failed notification must not take down the request that\n * produced it. The visitor has already submitted their form, and failing their\n * response because our mail didn't go out would turn a lost notification into a\n * lost conversion. The failure is returned instead, for the caller to log.\n */\nexport async function sendEmail(\n plan: EmailPlan,\n message: RenderedMessage,\n binding: EmailBinding,\n options: SendEmailOptions = {},\n): Promise<ChannelResult> {\n if (!plan.enabled || !plan.to || !plan.from) {\n return { channel: 'email', sent: false, reason: plan.skip ?? 'Channel not enabled.' };\n }\n\n const attempts = Math.max(1, options.attempts ?? 3);\n const sleep = options.sleep ?? wait;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n await binding.send({\n to: plan.to,\n from: plan.fromName ? { email: plan.from, name: plan.fromName } : { email: plan.from },\n subject: message.subject,\n text: message.text,\n html: message.html,\n ...(plan.replyTo ? { replyTo: plan.replyTo } : {}),\n });\n return { channel: 'email', sent: true };\n } catch (error) {\n const code = codeOf(error);\n if (attempt === attempts || !code || !RETRYABLE.has(code)) {\n return {\n channel: 'email',\n sent: false,\n reason: messageOf(error),\n ...(code ? { code } : {}),\n };\n }\n // Exponential backoff. Cloudflare's rate limit is per-account, so a burst\n // of conversions retrying in lockstep would keep colliding.\n await sleep(2 ** (attempt - 1) * 250);\n }\n }\n\n /* c8 ignore next -- the loop always returns; this satisfies the type checker. */\n return { channel: 'email', sent: false, reason: 'Exhausted attempts.' };\n}\n\n/**\n * Print the message instead of sending it.\n *\n * The dev path, for a machine with no binding. Explicit rather than a silent\n * no-op, because \"I never saw the notification\" is the symptom of both a broken\n * integration and a working one nobody could observe.\n */\nexport function logEmail(\n plan: EmailPlan,\n message: RenderedMessage,\n log: (line: string) => void = console.log,\n): ChannelResult {\n log(\n [\n '\\n========== NOTIFICATION EMAIL (not sent — no binding) ==========',\n `To: ${plan.to ?? '(unresolved)'}`,\n `From: ${plan.from ?? '(unresolved)'}`,\n `Subject: ${message.subject}`,\n '---',\n message.text,\n '================================================================\\n',\n ].join('\\n'),\n );\n return { channel: 'email', sent: false, reason: 'No binding — logged to the console.' };\n}\n","/**\n * Every decision a notification makes, as one pure function.\n *\n * Pure in the load-bearing sense: no `fetch`, no binding, no clock. Whether a\n * channel fires, who it reaches, and *why* it was skipped are all decided here and\n * asserted in `plan.test.ts`; the senders beside this file do what they are told\n * and decide nothing. That is the same split `indexing/plan.ts` makes against\n * `gsc.ts`, and `@getvitops/core`'s consent store makes against its DOM wiring,\n * for the same reason: the consequential logic has to be testable without the\n * environment it runs in.\n *\n * The practical payoff is that a misconfigured site can be told exactly what will\n * and won't happen without sending anything — a silently unsent conversion\n * notification is indistinguishable from no conversion.\n */\nimport type { EmailChannelConfig, EmailPlan, NotificationPlan, NotifyContext } from './types.ts';\n\n/** Default Workers binding name for Cloudflare Email Sending. */\nexport const DEFAULT_EMAIL_BINDING = 'EMAIL';\n\n/** Normalise the `email` shorthand: a bare address means a Cloudflare send to it. */\nexport function normalizeEmailChannel(\n input: string | EmailChannelConfig | undefined,\n): EmailChannelConfig | undefined {\n if (input === undefined) return undefined;\n return typeof input === 'string' ? { provider: 'cloudflare', to: input } : input;\n}\n\n/**\n * Who the notification reaches.\n *\n * An explicit recipient wins; otherwise it falls to the site's own contact\n * addresses, primary first. This cascade is why a site that has already said\n * where it receives mail doesn't have to say it twice.\n */\nexport function resolveRecipient(\n channel: EmailChannelConfig,\n ctx: NotifyContext,\n): string | undefined {\n if (channel.to) return channel.to;\n return ctx.locationEmails?.find((e) => !!e);\n}\n\n/**\n * The From address.\n *\n * `noreply@<canonical>` by default, because the sending domain has to be one the\n * site controls — Cloudflare rejects anything else with `E_SENDER_NOT_VERIFIED`,\n * and guessing from the recipient's domain would send that failure every time.\n */\nexport function resolveSender(channel: EmailChannelConfig, ctx: NotifyContext): string | undefined {\n if (channel.from) return channel.from;\n if (!ctx.canonical) return undefined;\n let host: string;\n try {\n host = new URL(ctx.canonical).hostname;\n } catch {\n // A bare hostname is a legitimate way to write `domains.canonical`.\n host = ctx.canonical.replace(/^https?:\\/\\//, '').replace(/\\/.*$/, '');\n }\n return host ? `noreply@${host}` : undefined;\n}\n\n/**\n * Decide what will be sent, and say why anything won't be.\n *\n * Every \"off\" carries a reason rather than being an absence, so a caller can\n * report the misconfiguration instead of reporting success over a no-op.\n */\nexport function planNotifications(ctx: NotifyContext): NotificationPlan {\n const email = planEmail(ctx);\n return { email, empty: !email.enabled };\n}\n\nfunction planEmail(ctx: NotifyContext): EmailPlan {\n const channel = normalizeEmailChannel(ctx.notifications?.email);\n const binding = channel?.binding ?? DEFAULT_EMAIL_BINDING;\n\n if (!channel) {\n return {\n provider: 'cloudflare',\n binding,\n enabled: false,\n skip: 'No `notifications.email` configured.',\n };\n }\n\n const to = resolveRecipient(channel, ctx);\n if (!to) {\n return {\n provider: 'cloudflare',\n binding,\n enabled: false,\n skip:\n 'No recipient: set `notifications.email.to`, or give a location an `email` ' +\n 'so the notification has somewhere to go.',\n };\n }\n\n const from = resolveSender(channel, ctx);\n if (!from) {\n return {\n provider: 'cloudflare',\n binding,\n to,\n enabled: false,\n skip:\n 'No sender: set `notifications.email.from`, or `domains.canonical` so ' +\n '`noreply@<host>` can be derived. Cloudflare only sends from a domain you have onboarded.',\n };\n }\n\n return {\n provider: 'cloudflare',\n binding,\n to,\n from,\n fromName: channel.fromName ?? ctx.organizationName,\n replyTo: channel.replyTo,\n enabled: true,\n };\n}\n","/**\n * Turning a `ConversionEvent` into something a person reads.\n *\n * Pure, and separate from both the plan and the sender, because rendering is the\n * part that differs per channel: an SMS channel will render the same event in 160\n * characters, a portal log as a row. The event stays the fact; only this file has\n * an opinion about prose.\n *\n * The layout is three sections — who got in touch, which ad sent them, and what\n * the request looked like — because that is the order the reader needs them in.\n * The contact details are the point; attribution is why it matters; the visitor\n * context is for when something looks wrong.\n */\nimport { getPrimaryClickId, identifyPlatform } from '../tracking/platform.ts';\nimport type { ConversionEvent } from '../tracking/types.ts';\nimport type { RenderedMessage } from './types.ts';\n\n/**\n * Fields never worth putting in a notification.\n *\n * A honeypot is not visitor-supplied — it is bait, and reporting it as something\n * they submitted is untrue. The same rule `legal/derive.ts` applies when deriving\n * `piiCollected`, and for the same reason. Callers may strip more.\n */\nconst OMIT_FIELDS = new Set(['website', '_honeypot', 'honeypot', 'cf-turnstile-response']);\n\nfunction label(key: string): string {\n return key.charAt(0).toUpperCase() + key.slice(1).replace(/[_-]/g, ' ');\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\n/** One section: a heading and its lines. Empty sections are dropped by the caller. */\ninterface Section {\n heading: string;\n lines: [string, string][];\n}\n\n/**\n * The event as sections — the shared structure behind both renderings.\n *\n * Extracted so the text and HTML versions cannot disagree about content. They\n * differ only in markup; a field added here appears in both.\n */\nexport function describeEvent(event: ConversionEvent): { subject: string; sections: Section[] } {\n const t = event.tracking;\n const platform = t ? identifyPlatform(t) : null;\n const clickId = t ? getPrimaryClickId(t) : null;\n\n const contact: [string, string][] = [];\n let subject: string;\n\n if (event.type === 'form' && event.formData) {\n const name = event.formData['name'] ?? 'Unknown';\n subject = `[Contact Form] New submission from ${name}`;\n for (const [key, value] of Object.entries(event.formData)) {\n if (!OMIT_FIELDS.has(key) && value) contact.push([label(key), value]);\n }\n } else {\n const phone = event.phone ?? 'unknown';\n subject = `[Phone Call] Visitor calling ${phone}`;\n contact.push(['Phone', phone]);\n }\n\n const attribution: [string, string][] = [];\n if (t) {\n if (platform) attribution.push(['Platform', platform]);\n if (clickId) attribution.push([`Click ID (${clickId.param})`, clickId.value]);\n for (const key of ['utm_campaign', 'utm_source', 'utm_medium', 'utm_content', 'utm_term']) {\n const value = t[key];\n if (value) attribution.push([label(key.replace('utm_', '')), String(value)]);\n }\n if (t.ab_variant) attribution.push(['A/B variant', t.ab_variant]);\n }\n\n const context: [string, string][] = [];\n if (t?.landingPage) context.push(['Landing page', t.landingPage]);\n if (t?.referrer) context.push(['Referrer', t.referrer]);\n if (t?.ts) context.push(['First visit', new Date(t.ts).toISOString()]);\n context.push(['Received', new Date(event.at).toISOString()]);\n if (event.userAgent) context.push(['User agent', event.userAgent]);\n if (event.ip) context.push(['IP', event.ip]);\n\n const sections: Section[] = [\n { heading: 'Contact details', lines: contact },\n // Stated rather than omitted: \"we don't know where this came from\" is a\n // useful answer, and a silently missing section reads as a bug in the tool.\n {\n heading: 'Ad attribution',\n lines: attribution.length\n ? attribution\n : [['Source', 'None — visitor arrived without ad tracking']],\n },\n { heading: 'Visitor context', lines: context },\n ];\n\n return { subject, sections: sections.filter((s) => s.lines.length) };\n}\n\n/** Render for e-mail. Both halves, always — see `RenderedMessage`. */\nexport function renderEmail(event: ConversionEvent): RenderedMessage {\n const { subject, sections } = describeEvent(event);\n\n const text = sections\n .map((s) => [`--- ${s.heading} ---`, ...s.lines.map(([k, v]) => `${k}: ${v}`)].join('\\n'))\n .join('\\n\\n');\n\n const html = sections\n .map(\n (s) =>\n `<h2 style=\"font:600 14px system-ui;margin:24px 0 8px\">${escapeHtml(s.heading)}</h2>` +\n `<table style=\"font:14px system-ui;border-collapse:collapse\">${s.lines\n .map(\n ([k, v]) =>\n `<tr><td style=\"padding:2px 12px 2px 0;color:#666;vertical-align:top\">${escapeHtml(k)}</td>` +\n `<td style=\"padding:2px 0\">${escapeHtml(v)}</td></tr>`,\n )\n .join('')}</table>`,\n )\n .join('');\n\n return { subject, text, html };\n}\n","/**\n * Conversion notifications — plan, render, dispatch.\n *\n * The seam between \"a conversion happened\" and \"someone found out about it\".\n * A `ConversionEvent` from `@getvitops/utils/tracking` goes in; where it goes and\n * how it reads are config, not code at the call site.\n *\n * Three files, three jobs, matching `indexing/`:\n * - `plan.ts` decides everything, purely — which channels, which recipients,\n * and why anything is off.\n * - `render.ts` turns the event into prose, purely.\n * - `email.ts` executes, and decides nothing.\n *\n * ---\n *\n * **TODO — further channels.** Only `email` is implemented. The seam is\n * `NotificationsConfig` + a sender with `sendEmail`'s signature `(plan, message,\n * transport) => ChannelResult`; adding one should mean a new sender file, a new\n * branch in `planNotifications`, and a schema variant — touching neither\n * `ConversionEvent` nor the recipient cascade. Planned:\n * - `sms` — the same event rendered short. `render.ts` already separates\n * `describeEvent` from `renderEmail` for exactly this.\n * - `persist` — append to a store (D1, a portal log) the client reviews.\n * The generic `email`/`text`/`persist` helpers taking content + provider config\n * belong at that point, not before: one implemented channel is not enough to know\n * what the abstraction should be.\n */\nimport type { ConversionEvent } from '../tracking/types.ts';\nimport { logEmail, sendEmail } from './email.ts';\nimport { planNotifications } from './plan.ts';\nimport { renderEmail } from './render.ts';\nimport type { ChannelResult, EmailBinding, NotifyContext } from './types.ts';\n\nexport interface NotifyDeps {\n /**\n * The Workers `send_email` binding (`env.EMAIL`). Omit it and the notification\n * is printed instead — the dev path.\n */\n email?: EmailBinding | undefined;\n}\n\nexport interface NotifyResult {\n results: ChannelResult[];\n /** True when at least one channel delivered. */\n delivered: boolean;\n}\n\n/**\n * Notify every configured channel about a conversion.\n *\n * Channels are independent: one failing must not stop the others, and none of\n * them may throw into the request that produced the event. Every outcome —\n * delivered, skipped, failed — comes back as data for the caller to log.\n */\nexport async function notify(\n event: ConversionEvent,\n ctx: NotifyContext,\n deps: NotifyDeps = {},\n): Promise<NotifyResult> {\n const plan = planNotifications(ctx);\n const results: ChannelResult[] = [];\n\n if (plan.email.enabled) {\n const message = renderEmail(event);\n results.push(\n deps.email ? await sendEmail(plan.email, message, deps.email) : logEmail(plan.email, message),\n );\n } else {\n results.push({ channel: 'email', sent: false, reason: plan.email.skip ?? 'Not configured.' });\n }\n\n return { results, delivered: results.some((r) => r.sent) };\n}\n\nexport {\n DEFAULT_EMAIL_BINDING,\n normalizeEmailChannel,\n planNotifications,\n resolveRecipient,\n resolveSender,\n} from './plan.ts';\nexport { describeEvent, renderEmail } from './render.ts';\nexport { logEmail, sendEmail } from './email.ts';\nexport type {\n ChannelPlan,\n ChannelResult,\n EmailBinding,\n EmailChannelConfig,\n EmailPlan,\n NotificationPlan,\n NotificationsConfig,\n NotifyContext,\n RenderedMessage,\n} from './types.ts';\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,YAAY,IAAI,I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,MAAM,EAAE,SAAS,aAAa,cAAc,KAAK;CAoBjD,OAAO;EAAE;EAAS,MAlBL,SACV,KAAK,MAAM,CAAC,OAAO,EAAE,QAAQ,OAAO,GAAG,EAAE,MAAM,KAAK,CAAC,GAAG,OAAO,GAAG,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CACzF,KAAK,MAgBa;EAAG,MAdX,SACV,KACE,MACC,yDAAyD,WAAW,EAAE,OAAO,EAAE,mEAChB,EAAE,MAC9D,KACE,CAAC,GAAG,OACH,wEAAwE,WAAW,CAAC,EAAE,iCACzD,WAAW,CAAC,EAAE,WAC/C,CAAC,CACA,KAAK,EAAE,EAAE,SAChB,CAAC,CACA,KAAK,EAEmB;CAAE;AAC/B;;;;;;;;;;;AC1EA,eAAsB,OACpB,OACA,KACA,OAAmB,CAAC,GACG;CACvB,MAAM,OAAO,kBAAkB,GAAG;CAClC,MAAM,UAA2B,CAAC;CAElC,IAAI,KAAK,MAAM,SAAS;EACtB,MAAM,UAAU,YAAY,KAAK;EACjC,QAAQ,KACN,KAAK,QAAQ,MAAM,UAAU,KAAK,OAAO,SAAS,KAAK,KAAK,IAAI,SAAS,KAAK,OAAO,OAAO,CAC9F;CACF,OACE,QAAQ,KAAK;EAAE,SAAS;EAAS,MAAM;EAAO,QAAQ,KAAK,MAAM,QAAQ;CAAkB,CAAC;CAG9F,OAAO;EAAE;EAAS,WAAW,QAAQ,MAAM,MAAM,EAAE,IAAI;CAAE;AAC3D"}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { n as GoogleOAuth } from "../token--18wN9UR.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/onboarding/types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The onboarding module's own option surface.
|
|
6
|
+
*
|
|
7
|
+
* Deliberately structural rather than `Config['site']['searchConsole']` imported
|
|
8
|
+
* from `@getvitops/generator`: the generator already depends on this package, so
|
|
9
|
+
* importing back would be a cycle. The vocabulary mirrors that block field for
|
|
10
|
+
* field, so the CLI's adapter is a flat map — the same arrangement, and for the
|
|
11
|
+
* same reason, as `IndexingConfig` beside it.
|
|
12
|
+
*
|
|
13
|
+
* Optional fields are written `?: T | undefined` throughout: `exactOptionalPropertyTypes`
|
|
14
|
+
* is on, and these types describe a *parsed JSON config* where an absent key and an
|
|
15
|
+
* explicit `undefined` are the same thing.
|
|
16
|
+
*/
|
|
17
|
+
/** One domain to onboard, as the config declares it. */
|
|
18
|
+
interface DomainSetup {
|
|
19
|
+
/** The domain, bare (`acme.ca`). Becomes the `sc-domain:` property and the DNS zone name. */
|
|
20
|
+
domain: string;
|
|
21
|
+
/**
|
|
22
|
+
* Emails added as verification owners on the Site Verification web resource.
|
|
23
|
+
* Additive: existing owners are never removed.
|
|
24
|
+
*/
|
|
25
|
+
delegatedOwners?: string[] | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* A Google Group to grant Full-User access in Search Console. Surfaced as a
|
|
28
|
+
* reminder only — Search Console has no user/permission API.
|
|
29
|
+
*/
|
|
30
|
+
fullUserGroup?: string | undefined;
|
|
31
|
+
}
|
|
32
|
+
/** Everything `plan()` needs, once the CLI has read the config and creds. */
|
|
33
|
+
interface OnboardingConfig {
|
|
34
|
+
/** The domains to onboard. Already filtered to `--domain` if that was passed. */
|
|
35
|
+
domains: DomainSetup[];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* One domain's observed live state, gathered by the executors before planning.
|
|
39
|
+
*
|
|
40
|
+
* `plan()` compares this against the desired `DomainSetup` to decide each step —
|
|
41
|
+
* the same shape the indexing planner takes its sitemap snapshot in, for the same
|
|
42
|
+
* reason: the decision is pure, the observation is not.
|
|
43
|
+
*/
|
|
44
|
+
interface DomainState {
|
|
45
|
+
/** The Cloudflare zone id for the domain, if one was found. */
|
|
46
|
+
zoneId?: string | undefined;
|
|
47
|
+
/** An apex TXT record already carrying the verification token exists. */
|
|
48
|
+
txtPresent: boolean;
|
|
49
|
+
/** The Site Verification web resource reports this domain as verified. */
|
|
50
|
+
verified: boolean;
|
|
51
|
+
/** Owners currently on the web resource (empty when not yet verified). */
|
|
52
|
+
currentOwners: string[];
|
|
53
|
+
/** A `sc-domain:` property already exists in Search Console. */
|
|
54
|
+
propertyExists: boolean;
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/onboarding/plan.d.ts
|
|
58
|
+
/** A step's decision: do it, or skip it because it already holds. */
|
|
59
|
+
type StepAction = 'create' | 'update' | 'skip';
|
|
60
|
+
interface StepPlan {
|
|
61
|
+
action: StepAction;
|
|
62
|
+
/** Why it's a skip, or what the mutation will do. */
|
|
63
|
+
detail: string;
|
|
64
|
+
}
|
|
65
|
+
/** The four onboarding steps for one domain, decided against its live state. */
|
|
66
|
+
interface DomainPlan {
|
|
67
|
+
domain: string;
|
|
68
|
+
/** `sc-domain:` property identifier this domain maps to. */
|
|
69
|
+
siteUrl: string;
|
|
70
|
+
/** Ensure the apex TXT verification record. */
|
|
71
|
+
txt: StepPlan;
|
|
72
|
+
/** Verify ownership via the Site Verification API (DNS_TXT). */
|
|
73
|
+
verify: StepPlan;
|
|
74
|
+
/** Add the Search Console domain property. */
|
|
75
|
+
property: StepPlan;
|
|
76
|
+
/** Add delegated owners to the verified web resource. */
|
|
77
|
+
owners: StepPlan;
|
|
78
|
+
/** Owners not yet present that the run should add. */
|
|
79
|
+
ownersToAdd: string[];
|
|
80
|
+
/** Manual follow-ups (e.g. a Full-User group). */
|
|
81
|
+
reminders: string[];
|
|
82
|
+
}
|
|
83
|
+
interface OnboardingPlan {
|
|
84
|
+
domains: DomainPlan[];
|
|
85
|
+
/** Operator-facing warnings that span the whole run. */
|
|
86
|
+
notes: string[];
|
|
87
|
+
}
|
|
88
|
+
/** The `sc-domain:` property identifier for a bare domain. */
|
|
89
|
+
declare const siteUrlFor: (domain: string) => string;
|
|
90
|
+
/**
|
|
91
|
+
* Backoff ladder for the verification retry, in milliseconds.
|
|
92
|
+
*
|
|
93
|
+
* DNS_TXT verification fails until the record has propagated, which is a matter of
|
|
94
|
+
* seconds-to-minutes, not a real error — so the schedule is a *policy*, decided
|
|
95
|
+
* here and asserted in the tests, while the actual sleeping is the CLI's job.
|
|
96
|
+
* Capped at `maxAttempts`; a domain still unverified after the last attempt is
|
|
97
|
+
* reported PENDING, never failed.
|
|
98
|
+
*/
|
|
99
|
+
declare function backoffSchedule(maxAttempts?: number): number[];
|
|
100
|
+
/** Decide the four steps for one domain from its desired config and live state. */
|
|
101
|
+
declare function planDomain(setup: DomainSetup, state: DomainState): DomainPlan;
|
|
102
|
+
/**
|
|
103
|
+
* The owner set to PUT: everyone already there, plus everyone being added.
|
|
104
|
+
*
|
|
105
|
+
* `updateOwners` REPLACES the owner list, so this is the one computation standing
|
|
106
|
+
* between a delegation and locking yourself out — pass a bare `ownersToAdd` and
|
|
107
|
+
* the account that just verified the domain is removed from it. It belongs here
|
|
108
|
+
* rather than at the call site for exactly that reason: it is a decision, it is
|
|
109
|
+
* the dangerous one, and the executor is not allowed to make it.
|
|
110
|
+
*
|
|
111
|
+
* `current` comes FIRST so the API's own casing survives dedupe; matching is
|
|
112
|
+
* case-insensitive, mirroring `planDomain`'s `present` check, because Google
|
|
113
|
+
* echoes back addresses in whatever case the account uses and a case-sensitive
|
|
114
|
+
* `Set` would re-add an owner who is already there.
|
|
115
|
+
*/
|
|
116
|
+
declare function ownerUnion(current: string[], toAdd: string[]): string[];
|
|
117
|
+
/** Plan every domain. */
|
|
118
|
+
declare function plan(config: OnboardingConfig, states: Map<string, DomainState>): OnboardingPlan;
|
|
119
|
+
/** Any step on any domain is a mutation — i.e. the live state has drifted. */
|
|
120
|
+
declare function hasDrift(p: OnboardingPlan): boolean;
|
|
121
|
+
/** Render a plan as the block `--dry` and `--check` print. */
|
|
122
|
+
declare function formatPlan(p: OnboardingPlan): string;
|
|
123
|
+
/** The outcome of one domain's run, for the summary table. */
|
|
124
|
+
interface DomainResult {
|
|
125
|
+
domain: string;
|
|
126
|
+
txt: 'created' | 'present' | 'failed' | '—';
|
|
127
|
+
verified: 'yes' | 'pending' | 'failed' | '—';
|
|
128
|
+
property: 'added' | 'present' | 'failed' | '—';
|
|
129
|
+
reminders: string[];
|
|
130
|
+
}
|
|
131
|
+
/** Render the end-of-run summary: one row per domain, plus any reminders. */
|
|
132
|
+
declare function formatSummary(results: DomainResult[]): string;
|
|
133
|
+
//#endregion
|
|
134
|
+
//#region src/onboarding/cloudflare.d.ts
|
|
135
|
+
/** Find the zone id for a domain (`GET /zones?name=`). */
|
|
136
|
+
declare function findZoneId(token: string, domain: string, fetchImpl?: typeof fetch): Promise<{
|
|
137
|
+
ok: boolean;
|
|
138
|
+
status: number;
|
|
139
|
+
zoneId?: string;
|
|
140
|
+
message?: string;
|
|
141
|
+
}>;
|
|
142
|
+
/** List the apex TXT record contents for a zone. */
|
|
143
|
+
declare function listApexTxt(token: string, zoneId: string, domain: string, fetchImpl?: typeof fetch): Promise<{
|
|
144
|
+
ok: boolean;
|
|
145
|
+
status: number;
|
|
146
|
+
contents: string[];
|
|
147
|
+
message?: string;
|
|
148
|
+
}>;
|
|
149
|
+
/**
|
|
150
|
+
* Create an apex TXT record. **Create only** — never called when one already
|
|
151
|
+
* exists (the planner decides that), and there is no sibling that edits or removes.
|
|
152
|
+
*/
|
|
153
|
+
declare function createApexTxt(token: string, zoneId: string, domain: string, content: string, fetchImpl?: typeof fetch): Promise<{
|
|
154
|
+
ok: boolean;
|
|
155
|
+
status: number;
|
|
156
|
+
message?: string;
|
|
157
|
+
}>;
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region src/onboarding/google.d.ts
|
|
160
|
+
/** Exchange a user OAuth refresh token for a short-lived access token. */
|
|
161
|
+
declare function refreshTokenGrant(oauth: GoogleOAuth, fetchImpl?: typeof fetch): Promise<string>;
|
|
162
|
+
/**
|
|
163
|
+
* Ask the Site Verification API for the DNS_TXT token for a domain.
|
|
164
|
+
*
|
|
165
|
+
* Returns the full `google-site-verification=…` value that goes in the apex TXT
|
|
166
|
+
* record. It is deterministic per (user, domain), so re-fetching it and comparing
|
|
167
|
+
* against DNS is what makes the TXT step idempotent.
|
|
168
|
+
*/
|
|
169
|
+
declare function getVerificationToken(token: string, domain: string, fetchImpl?: typeof fetch): Promise<{
|
|
170
|
+
ok: boolean;
|
|
171
|
+
status: number;
|
|
172
|
+
token?: string;
|
|
173
|
+
message?: string;
|
|
174
|
+
}>;
|
|
175
|
+
/**
|
|
176
|
+
* Look up the verified web resource for a domain, if any.
|
|
177
|
+
*
|
|
178
|
+
* Uses `webResource.list` rather than a `get` by id, because the id format for an
|
|
179
|
+
* INET_DOMAIN resource is awkward to construct by hand and the list only ever
|
|
180
|
+
* contains resources the user already owns — so a hit *is* the verified state, and
|
|
181
|
+
* carries the id and owners the later steps need.
|
|
182
|
+
*/
|
|
183
|
+
declare function getWebResource(token: string, domain: string, fetchImpl?: typeof fetch): Promise<{
|
|
184
|
+
ok: boolean;
|
|
185
|
+
status: number;
|
|
186
|
+
exists: boolean;
|
|
187
|
+
id?: string;
|
|
188
|
+
owners: string[];
|
|
189
|
+
message?: string;
|
|
190
|
+
}>;
|
|
191
|
+
/** Verify ownership (DNS_TXT). Succeeds only once the TXT record has propagated. */
|
|
192
|
+
declare function verifyWebResource(token: string, domain: string, fetchImpl?: typeof fetch): Promise<{
|
|
193
|
+
ok: boolean;
|
|
194
|
+
status: number;
|
|
195
|
+
id?: string;
|
|
196
|
+
owners: string[];
|
|
197
|
+
message?: string;
|
|
198
|
+
}>;
|
|
199
|
+
/**
|
|
200
|
+
* Set the owners of a verified web resource to a given list.
|
|
201
|
+
*
|
|
202
|
+
* The API replaces the owner set, so the caller passes the **union** of the
|
|
203
|
+
* current owners and the ones to add — never a bare list of new owners, which
|
|
204
|
+
* would drop everyone already there.
|
|
205
|
+
*/
|
|
206
|
+
declare function updateOwners(token: string, id: string, domain: string, owners: string[], fetchImpl?: typeof fetch): Promise<{
|
|
207
|
+
ok: boolean;
|
|
208
|
+
status: number;
|
|
209
|
+
message?: string;
|
|
210
|
+
}>;
|
|
211
|
+
/** Whether a Search Console property already exists (`GET sites/{siteUrl}`). */
|
|
212
|
+
declare function getSite(token: string, siteUrl: string, fetchImpl?: typeof fetch): Promise<{
|
|
213
|
+
ok: boolean;
|
|
214
|
+
status: number;
|
|
215
|
+
exists: boolean;
|
|
216
|
+
message?: string;
|
|
217
|
+
}>;
|
|
218
|
+
/**
|
|
219
|
+
* Add a Search Console property (`PUT sites/{siteUrl}`).
|
|
220
|
+
*
|
|
221
|
+
* A `403` here almost always means the domain is not yet verified for this user
|
|
222
|
+
* rather than a transient error — property creation is gated on ownership.
|
|
223
|
+
*/
|
|
224
|
+
declare function addSite(token: string, siteUrl: string, fetchImpl?: typeof fetch): Promise<{
|
|
225
|
+
ok: boolean;
|
|
226
|
+
status: number;
|
|
227
|
+
message?: string;
|
|
228
|
+
}>;
|
|
229
|
+
//#endregion
|
|
230
|
+
export { type DomainPlan, type DomainResult, type DomainSetup, type DomainState, type GoogleOAuth, type OnboardingConfig, type OnboardingPlan, type StepAction, type StepPlan, addSite, backoffSchedule, createApexTxt, findZoneId, formatPlan, formatSummary, getSite, getVerificationToken, getWebResource, hasDrift, listApexTxt, ownerUnion, plan, planDomain, refreshTokenGrant, siteUrlFor, updateOwners, verifyWebResource };
|
|
231
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/onboarding/types.ts","../../src/onboarding/plan.ts","../../src/onboarding/cloudflare.ts","../../src/onboarding/google.ts"],"mappings":";;;;;;AAeA;;;;;;;;AAYe;AAIf;;UAhBiB,WAAA;EAkBf;EAhBA,MAAA;EAiCe;;;;EA5Bf,eAAA;EAgCA;;;;EA3BA,aAAA;AAAA;;UAIe,gBAAA;;EAEf,OAAA,EAAS,WAAW;AAAA;;;;;;ACZd;AAIR;UDyBiB,WAAA;;EAEf,MAAA;ECpBQ;EDsBR,UAAA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