Skip to content

Commit fc4793c

Browse files
authored
feat(site): send email sign-ups to OpenSend (#62385)
1 parent a7515ce commit fc4793c

43 files changed

Lines changed: 365 additions & 329 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎services/site/README.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,20 @@ dev.opencode.ai, `opencode-site-production` on opencode.ai), its bindings and it
4848
pushes to `dev` and `production` (`.github/workflows/deploy-site.yml`). Production takes no routes until
4949
`productionOwnsRoot` is switched on.
5050

51+
### Email sign-up
52+
53+
The home page's sign-up adds addresses to the OpenSend newsletter list (`src/lib/opensend.ts`) with
54+
the `OPENSEND_API_KEY` secret, a live OpenSend API key with manage permission. `cloudflare.config.ts`
55+
declares it, so a deploy fails until it's set on the Worker:
56+
57+
```bash
58+
read -s OPENSEND_API_KEY
59+
bunx cf workers secrets update OPENSEND_API_KEY --worker opencode-site-dev --text "$OPENSEND_API_KEY"
60+
```
61+
62+
In `bun run dev`, export `OPENSEND_API_KEY` to send real sign-ups; without it the form answers as if
63+
it worked and says nothing was sent.
64+
5165
The V2 docs at `/v2` are part of this app (`src/docs/`, see `src/docs/AGENTS.md`). `script/build.ts` prerenders
5266
them into the Worker's assets after `vite build`.
5367

‎services/site/cloudflare.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ export default defineConfig(({ mode }) => {
3232
env: {
3333
ASSETS: bindings.assets(),
3434
STAGE: bindings.text(dev ? "dev" : "production"),
35+
// The email sign-up's OpenSend key (lib/opensend.ts). A deploy fails until it's set on the Worker.
36+
OPENSEND_API_KEY: bindings.secret(),
3537
},
3638
triggers:
3739
dev || productionOwnsRoot

‎services/site/script/check-worker-start.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,12 @@ const modules = Object.fromEntries(
4040
}),
4141
),
4242
)
43-
// The site binds its assets and text values only; another kind of binding needs emulating here first.
43+
// The site binds its assets, text values and secrets only; another kind of binding needs emulating
44+
// here first. A secret gets a placeholder: its calls go nowhere (see below).
4445
const env = Object.fromEntries(
4546
Object.entries(config.env ?? {}).map(([name, binding]) => {
4647
if (binding.type === "text") return [name, { type: "text" as const, value: binding.value }]
48+
if (binding.type === "secret") return [name, { type: "text" as const, value: "check-worker-start" }]
4749
if (binding.type === "assets") return [name, { type: "assets" as const }]
4850
throw new Error(`check-worker-start: the ${binding.type} binding ${name} is not emulated`)
4951
}),

‎services/site/src/component/email-signup.tsx‎

Lines changed: 0 additions & 57 deletions
This file was deleted.

‎services/site/src/component/site/signup.css‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,6 @@
198198
cursor: text;
199199

200200
&[data-state="subscribed"],
201-
&[data-state="confirm"],
202201
&[data-state="already"] {
203202
cursor: auto;
204203
}
@@ -237,7 +236,7 @@
237236
vertical-align: bottom;
238237

239238
/* No underline: the grey placeholder and the caret say it's editable. Keyboard focus adds a ring. */
240-
[data-slot="sentence"]:not([data-state="subscribed"], [data-state="confirm"], [data-state="already"]) &[data-ring] {
239+
[data-slot="sentence"]:not([data-state="subscribed"], [data-state="already"]) &[data-ring] {
241240
outline: 2px solid var(--link);
242241
outline-offset: 0.12em;
243242
}
@@ -277,7 +276,6 @@
277276

278277
/* Once sent, the address is plain text in the sentence. */
279278
[data-state="subscribed"],
280-
[data-state="confirm"],
281279
[data-state="already"] {
282280
input {
283281
cursor: text;
@@ -301,10 +299,6 @@
301299
color: var(--text);
302300
}
303301

304-
[data-slot="note"] {
305-
animation: signup-in 320ms var(--ease-out);
306-
}
307-
308302
/* The button holds its place while hidden, so the page doesn't move when it shows. */
309303
[data-component="site-button"] {
310304
border: 0;
@@ -359,8 +353,7 @@
359353
}
360354

361355
@media (prefers-reduced-motion: reduce) {
362-
[data-slot="error"],
363-
[data-slot="note"] {
356+
[data-slot="error"] {
364357
animation: none;
365358
}
366359

‎services/site/src/component/site/signup.tsx‎

Lines changed: 19 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,21 @@ import "./signup.css"
44
import { action, useAction } from "@solidjs/router"
55
import { Resource } from "#resource"
66
import { createEffect, createSignal, createUniqueId, Match, on, onCleanup, Show, Switch, untrack } from "solid-js"
7-
import { z } from "zod"
7+
import { getRequestEvent } from "solid-js/web"
8+
import { subscribe, type SignupStatus } from "~/lib/opensend"
89
import { designCopy } from "./design-copy"
910
import { siteSettings } from "./settings"
1011

1112
/**
12-
* The home page's email sign-up. It adds the address to the same EmailOctopus list as the live
13-
* site's form (component/email-signup.tsx), from a server action, so the API key never reaches the
14-
* browser. Settings › Sign-up style picks one of three forms; all are real forms with an email
15-
* field, and without JavaScript they still post to the action.
13+
* The home page's email sign-up. It adds the address to the OpenSend newsletter list
14+
* (lib/opensend.ts) from a server action, so the API key never reaches the browser. Settings ›
15+
* Sign-up style picks one of three forms; all are real forms with an email field, and without
16+
* JavaScript they still post to the action.
1617
*/
1718

18-
const listId = "8b9bb82c-9d5f-11f0-975f-0df6fd1e4945"
19-
20-
// The fields of EmailOctopus's contact that tell a new address from one already on the list.
21-
const contact = z.object({
22-
status: z.enum(["pending", "subscribed", "unsubscribed"]),
23-
created_at: z.string(),
24-
})
25-
2619
type Result = {
27-
status: "subscribed" | "confirm" | "already" | "invalid" | "error"
28-
// Set only in development without the EmailOctopus key: nothing was sent.
20+
status: SignupStatus
21+
// Set only in development without the OpenSend key: nothing was sent.
2922
dev?: boolean
3023
}
3124

@@ -35,28 +28,16 @@ const signup = action(async (form: FormData): Promise<Result> => {
3528
if (!validEmail(email)) return { status: "invalid" }
3629
const key = apiKey()
3730
if (!key) return import.meta.env.DEV ? { status: "subscribed", dev: true } : { status: "error" }
38-
const response = await fetch(`https://api.emailoctopus.com/lists/${listId}/contacts`, {
39-
method: "PUT",
40-
headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
41-
body: JSON.stringify({ email_address: email }),
42-
}).catch(() => undefined)
43-
if (!response?.ok) {
44-
console.error("EmailOctopus sign-up failed:", response?.status, await response?.text().catch(() => ""))
45-
return { status: "error" }
46-
}
47-
const saved = contact.safeParse(await response.json().catch(() => undefined))
48-
if (!saved.success) return { status: "subscribed" }
49-
// The call creates or updates, so a contact made more than a minute ago was already there.
50-
const existing = Date.now() - Date.parse(saved.data.created_at) > 60_000
51-
if (saved.data.status === "pending") return { status: "confirm" }
52-
if (saved.data.status === "unsubscribed") return { status: "error" }
53-
return { status: existing ? "already" : "subscribed" }
31+
// Server actions only see a same-origin referer (lib/server-action.ts): the page with the form.
32+
const request = getRequestEvent()!.request
33+
const page = new URL(request.headers.get("referer") ?? request.url)
34+
return { status: await subscribe({ key, email, page: page.origin + page.pathname, at: new Date() }) }
5435
}, "site-signup")
5536

5637
// Outside development the Resource is always linked; in plain `vite dev` it throws.
5738
function apiKey() {
5839
try {
59-
return Resource.EMAILOCTOPUS_API_KEY.value
40+
return Resource.OPENSEND_API_KEY.value
6041
} catch {
6142
return undefined
6243
}
@@ -71,7 +52,6 @@ const messages = {
7152
invalid: "home.signup.invalid",
7253
error: "home.signup.error",
7354
subscribed: "home.signup.subscribed",
74-
confirm: "home.signup.confirm",
7555
already: "home.signup.already",
7656
} as const satisfies Record<string, Key>
7757

@@ -85,7 +65,7 @@ const sentenceErrors = {
8565
type State =
8666
| { status: "idle" | "pending" }
8767
| { status: "empty" | "invalid" | "error"; email: string }
88-
| { status: "subscribed" | "confirm" | "already"; email: string; dev?: boolean }
68+
| { status: "subscribed" | "already"; email: string; dev?: boolean }
8969

9070
const reduced = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches
9171

@@ -98,7 +78,7 @@ function createSignup() {
9878
const id = createUniqueId()
9979
let input: HTMLInputElement | undefined
10080

101-
const done = () => ["subscribed", "confirm", "already"].includes(state().status)
81+
const done = () => ["subscribed", "already"].includes(state().status)
10282
const problem = () => {
10383
const current = state()
10484
return current.status === "empty" || current.status === "invalid" || current.status === "error"
@@ -248,9 +228,7 @@ function InputForm(props: { signup: Signup }) {
248228
<span data-slot="sr-only">
249229
{i18n.t(s.state().status === "already" ? messages.already : messages.subscribed)}{" "}
250230
</span>
251-
{s.state().status === "confirm"
252-
? i18n.t("home.signup.checkInbox", { email: s.email() })
253-
: i18n.t("home.signup.tellFirst", { email: s.email() })}
231+
{i18n.t("home.signup.tellFirst", { email: s.email() })}
254232
</Show>
255233
</p>
256234
<DevNote signup={s} />
@@ -269,7 +247,7 @@ function SentenceForm(props: { signup: Signup }) {
269247
const verb = () => {
270248
const status = s.state().status
271249
if (status === "already") return i18n.t("home.signup.alreadyAt")
272-
if (status === "subscribed" || status === "confirm") return i18n.t("home.signup.onListAt")
250+
if (status === "subscribed") return i18n.t("home.signup.onListAt")
273251
return ""
274252
}
275253
const ready = () => !s.done() && validEmail(s.value().trim())
@@ -391,9 +369,6 @@ function SentenceForm(props: { signup: Signup }) {
391369
</button>
392370
}
393371
>
394-
<Show when={s.state().status === "confirm"}>
395-
<span data-slot="note">{i18n.t("home.signup.confirmNote")}</span>
396-
</Show>
397372
<button type="button" data-slot="again" onClick={s.reset}>
398373
{i18n.t("home.signup.again")}
399374
</button>
@@ -485,12 +460,7 @@ function TerminalForm(props: { signup: Signup }) {
485460
<span data-slot="dim" aria-hidden="true">
486461
└
487462
</span>
488-
<span>
489-
{i18n.t(s.state().status === "already" ? messages.already : messages.subscribed)}
490-
<Show when={s.state().status === "confirm"}>
491-
<span data-slot="dim"> {i18n.t("home.signup.confirmNote")}</span>
492-
</Show>
493-
</span>
463+
<span>{i18n.t(s.state().status === "already" ? messages.already : messages.subscribed)}</span>
494464
</div>
495465
</Match>
496466
</Switch>
@@ -527,7 +497,7 @@ function TerminalForm(props: { signup: Signup }) {
527497
function DevNote(props: { signup: Signup }) {
528498
return (
529499
<Show when={props.signup.dev()}>
530-
<p data-slot="dev">Development: not sent. EMAILOCTOPUS_API_KEY isn't linked; run with `sst shell`.</p>
500+
<p data-slot="dev">Development: not sent. OPENSEND_API_KEY isn't set.</p>
531501
</Show>
532502
)
533503
}

‎services/site/src/i18n/ar.ts‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,6 @@ export const dict = {
2828
"legal.privacy": "الخصوصية",
2929
"legal.terms": "الشروط",
3030
"legal.englishOnly": "هذا المستند متاح باللغة الإنجليزية فقط.",
31-
"email.title": "كن الأول في المعرفة عند إطلاق منتجات جديدة",
32-
"email.subtitle": "انضم إلى قائمة الانتظار للحصول على وصول مبكر.",
33-
"email.placeholder": "عنوان البريد الإلكتروني",
34-
"email.subscribe": "اشتراك",
35-
"email.success": "تبقّت خطوة واحدة: تحقق من بريدك وأكّد عنوانك",
3631
"notFound.title": "غير موجود | OpenCode",
3732
"notFound.heading": "404 - الصفحة غير موجودة",
3833
"notFound.home": "الرئيسية",
@@ -548,16 +543,13 @@ export const dict = {
548543
"home.signup.again": "استخدم عنوانًا آخر",
549544
"home.signup.againLower": "استخدم عنوانًا آخر",
550545
"home.signup.toSubscribe": "للاشتراك",
551-
"home.signup.confirmNote": "تحقق من بريدك لتأكيد عنوانك.",
552-
"home.signup.checkInbox": "تحقق من {{email}} لتأكيد عنوانك.",
553546
"home.signup.tellFirst": "سنخبرك أولًا على {{email}}.",
554547
"home.signup.onListAt": "أنت في القائمة بالعنوان",
555548
"home.signup.alreadyAt": "أنت في القائمة بالفعل بالعنوان",
556549
"home.signup.empty": "أدخل عنوان بريدك الإلكتروني.",
557550
"home.signup.invalid": "أدخل عنوان بريد كاملًا، مثل you@example.com.",
558551
"home.signup.error": "لم يكتمل الطلب. حاول مرة أخرى بعد قليل.",
559552
"home.signup.subscribed": "أنت في القائمة.",
560-
"home.signup.confirm": "أنت في القائمة. تحقق من بريدك لتأكيد عنوانك.",
561553
"home.signup.already": "أنت في القائمة بالفعل.",
562554
"home.signup.sentenceEmpty": "اكتب عنوانك أولًا.",
563555
"home.signup.sentenceInvalid": "يبدو العنوان ناقصًا.",
@@ -608,7 +600,6 @@ export const dict = {
608600
"legal.status.degraded": "أداء متراجع",
609601
"legal.status.outage": "انقطاع في الخدمة",
610602
"legal.status.unknown": "حالة النظام",
611-
"email.error": "تعذّر الاشتراك. يُرجى المحاولة مرة أخرى.",
612603
"zen.faq.q9": "هل يمكنني استرداد أموالي؟",
613604
"zen.faq.a9": "قد تكون مؤهلًا لاسترداد أموالك إذا تم الخصم خلال آخر 14 يومًا ولم تستخدم الرصيد الناتج عن عملية الشراء هذه. {{contact}} لطلب استرداد الأموال.",
614605
"go.promo.hy4": "يتوفر Hy4 الآن في Go.",

‎services/site/src/i18n/br.ts‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,6 @@ export const dict = {
2828
"legal.privacy": "Privacidade",
2929
"legal.terms": "Termos",
3030
"legal.englishOnly": "Este documento está disponível apenas em inglês.",
31-
"email.title": "Seja o primeiro a saber quando lançarmos novos produtos",
32-
"email.subtitle": "Entre na lista de espera para acesso antecipado.",
33-
"email.placeholder": "Endereço de e-mail",
34-
"email.subscribe": "Inscrever-se",
35-
"email.success": "Quase lá, verifique sua caixa de entrada e confirme seu e-mail",
3631
"notFound.title": "Não encontrado | OpenCode",
3732
"notFound.heading": "404 - Página não encontrada",
3833
"notFound.home": "Início",
@@ -561,9 +556,6 @@ export const dict = {
561556
"home.signup.alreadyAt": "Você já está na lista com",
562557
"home.signup.body": "Seja o primeiro a saber quando lançarmos novos produtos.",
563558
"home.signup.button": "Avise-me",
564-
"home.signup.checkInbox": "Confira {{email}} para confirmar seu endereço.",
565-
"home.signup.confirm": "Você está na lista. Confira sua caixa de entrada para confirmar o endereço.",
566-
"home.signup.confirmNote": "Confira sua caixa de entrada para confirmar o endereço.",
567559
"home.signup.empty": "Digite seu e-mail.",
568560
"home.signup.error": "Não deu certo. Tente de novo em instantes.",
569561
"home.signup.invalid": "Digite um e-mail completo, como voce@exemplo.com.",
@@ -605,7 +597,6 @@ export const dict = {
605597
"legal.status.degraded": "Desempenho degradado",
606598
"legal.status.outage": "Interrupção do serviço",
607599
"legal.status.unknown": "Status do sistema",
608-
"email.error": "Não foi possível concluir a inscrição. Tente novamente.",
609600
"zen.faq.q9": "Posso receber um reembolso?",
610601
"zen.faq.a9": "Você pode ter direito a um reembolso se a cobrança foi feita nos últimos 14 dias e você não usou os créditos dessa compra. {{contact}} para solicitar um reembolso.",
611602
"go.promo.hy4": "Hy4 já está disponível no Go.",

0 commit comments

Comments
 (0)