@hintergrund/worker 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +4 -36
  2. package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -1
  3. package/dist/api/cms/handlers/admin-users.handler.js +8 -5
  4. package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
  5. package/dist/api/cms/handlers/setup.handler.js +56 -19
  6. package/dist/api/cms/handlers/website-repo.handler.d.ts +5 -0
  7. package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
  8. package/dist/api/cms/handlers/website-repo.handler.js +30 -8
  9. package/dist/api/cms/routes/index.d.ts.map +1 -1
  10. package/dist/api/cms/routes/index.js +9 -2
  11. package/dist/api/emails/handlers/campaigns.handler.d.ts +1 -1
  12. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
  13. package/dist/api/emails/handlers/campaigns.handler.js +12 -13
  14. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
  15. package/dist/api/emails/handlers/public.handler.js +7 -10
  16. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
  17. package/dist/api/emails/handlers/send.handler.js +8 -14
  18. package/dist/api/emails/handlers/settings.handler.d.ts +4 -23
  19. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
  20. package/dist/api/emails/handlers/settings.handler.js +9 -19
  21. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
  22. package/dist/api/emails/routes/admin.routes.js +2 -5
  23. package/dist/api/emails/routes/mail.routes.d.ts.map +1 -1
  24. package/dist/api/emails/routes/mail.routes.js +62 -16
  25. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
  26. package/dist/api/shop/handlers/public.handler.js +18 -18
  27. package/dist/api/shop/routes.js +2 -2
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +8 -14
  31. package/dist/lib/design.d.ts +0 -1
  32. package/dist/lib/design.d.ts.map +1 -1
  33. package/dist/lib/design.js +1 -8
  34. package/dist/lib/email-template.d.ts +2 -12
  35. package/dist/lib/email-template.d.ts.map +1 -1
  36. package/dist/lib/email-template.js +3 -35
  37. package/dist/lib/email.d.ts.map +1 -1
  38. package/dist/lib/email.js +12 -1
  39. package/dist/lib/invoice.d.ts +2 -11
  40. package/dist/lib/invoice.d.ts.map +1 -1
  41. package/dist/lib/invoice.js +6 -39
  42. package/dist/lib/mail-schema.d.ts +1 -1
  43. package/dist/lib/mail-schema.d.ts.map +1 -1
  44. package/dist/lib/mail-schema.js +4 -1
  45. package/dist/lib/mail.d.ts.map +1 -1
  46. package/dist/lib/mail.js +11 -0
  47. package/dist/lib/project-db.d.ts +6 -1
  48. package/dist/lib/project-db.d.ts.map +1 -1
  49. package/dist/lib/project-db.js +9 -0
  50. package/dist/lib/website-i18n.d.ts +14 -6
  51. package/dist/lib/website-i18n.d.ts.map +1 -1
  52. package/dist/lib/website-i18n.js +37 -102
  53. package/dist/middleware/auth.d.ts +7 -0
  54. package/dist/middleware/auth.d.ts.map +1 -1
  55. package/dist/middleware/auth.js +14 -1
  56. package/package.json +2 -4
package/README.md CHANGED
@@ -1,45 +1,13 @@
1
1
  # @hintergrund/worker
2
2
 
3
- Backend worker package for the Hintergrund CMS Cloudflare Worker.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- pnpm add @hintergrund/worker
9
- ```
10
-
11
- ## Usage
3
+ Backend Worker package for the Hintergrund CMS.
12
4
 
13
5
  ```typescript
14
6
  import { createApp } from '@hintergrund/worker';
15
7
 
16
- const app = createApp();
17
-
18
- export default app;
8
+ export default createApp();
19
9
  ```
20
10
 
21
- ## Exports
22
-
23
- ### `createApp()`
24
- Creates and configures a new Hono app instance with:
25
- - CORS middleware
26
- - CMS routes under `/api/cms`
27
- - Static asset serving with SPA fallback
11
+ `createApp()` returns a Hono app with CORS, the CMS routes under `/api/cms` and static assets with an SPA fallback. It also exports the `Bindings` type. Released together with `runtime-contracts` and `ui` (see the root `CLAUDE.md`).
28
12
 
29
- ### Types
30
- - `Bindings` - Cloudflare Worker bindings type
31
-
32
- ### Utilities
33
- - JWT utilities from `./jwt`
34
- - Utility functions from `./utils`
35
- - Template utilities from `./template`
36
-
37
- ## Development
38
-
39
- ```bash
40
- # Build the package
41
- pnpm run build
42
-
43
- # Watch mode
44
- pnpm run dev
45
- ```
13
+ `pnpm build` builds the package; `pnpm dev` watches.
@@ -1 +1 @@
1
- {"version":3,"file":"admin-users.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/admin-users.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAS9C,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI3E;AACD,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmB5E;AACD,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAM7E;AACD,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgB3E;AACD,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAS5E"}
1
+ {"version":3,"file":"admin-users.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/admin-users.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAS9C,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI3E;AACD,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmB5E;AACD,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAM7E;AACD,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAkB3E;AACD,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAS5E"}
@@ -1,9 +1,9 @@
1
- import { createId, ensureSchema, nowSeconds } from '../../../lib/project-db';
1
+ import { createId, ensureSchema, nowSeconds, parsePermissions, userPermissions } from '../../../lib/project-db';
2
2
  import { sendRecovery, validEmail } from '../../../lib/user-recovery';
3
3
  function userToResponse(user, currentId) {
4
4
  return { id: user.id, email: user.email, name: user.name, disabledAt: user.disabled_at,
5
5
  createdAt: user.created_at, updatedAt: user.updated_at, hasPassword: !!user.password_hash,
6
- isFirst: user.initial_admin === 1, isCurrent: user.id === currentId };
6
+ permissions: userPermissions(user), isFirst: user.initial_admin === 1, isCurrent: user.id === currentId };
7
7
  }
8
8
  export async function listAdminUsers(c) {
9
9
  const db = await ensureSchema(c.env);
@@ -19,8 +19,8 @@ export async function createAdminUser(c) {
19
19
  const db = await ensureSchema(c.env);
20
20
  const now = nowSeconds();
21
21
  const id = createId('user');
22
- const result = await db.prepare(`INSERT INTO admin_users (id, email, name, password_hash, login_method, created_at, updated_at)
23
- VALUES (?, ?, ?, NULL, 'password', ?, ?) ON CONFLICT(email) DO NOTHING`).bind(id, email, name, now, now).run();
22
+ const result = await db.prepare(`INSERT INTO admin_users (id, email, name, password_hash, login_method, permissions, created_at, updated_at)
23
+ VALUES (?, ?, ?, NULL, 'password', ?, ?, ?) ON CONFLICT(email) DO NOTHING`).bind(id, email, name, parsePermissions(body.permissions).join(','), now, now).run();
24
24
  if (!result.meta.changes)
25
25
  return c.json({ error: 'A user with this email already exists.' }, 409);
26
26
  const user = (await db.prepare('SELECT * FROM admin_users WHERE id = ?').bind(id).first());
@@ -59,10 +59,13 @@ export async function patchAdminUser(c) {
59
59
  return c.json({ error: 'User not found.' }, 404);
60
60
  if (body.disabled && (existing.initial_admin === 1 || userId === c.get('user')?.userId))
61
61
  return c.json({ error: 'You cannot disable yourself or the original owner.' }, 400);
62
+ if (body.permissions !== undefined && (!Array.isArray(body.permissions) || existing.initial_admin === 1 || userId === c.get('user')?.userId))
63
+ return c.json({ error: 'Permissions cannot be changed for yourself or the original owner.' }, 400);
64
+ const permissions = body.permissions === undefined ? existing.permissions : parsePermissions(body.permissions).join(',');
62
65
  const name = typeof body.name === 'string' ? body.name.trim().slice(0, 200) : existing.name;
63
66
  const disabled = body.disabled === undefined ? existing.disabled_at : body.disabled ? nowSeconds() : null;
64
67
  await db.batch([
65
- db.prepare('UPDATE admin_users SET name = ?, disabled_at = ?, updated_at = ? WHERE id = ?').bind(name, disabled, Math.max(nowSeconds(), existing.updated_at + 1), userId),
68
+ db.prepare('UPDATE admin_users SET name = ?, disabled_at = ?, permissions = ?, updated_at = ? WHERE id = ?').bind(name, disabled, permissions, Math.max(nowSeconds(), existing.updated_at + 1), userId),
66
69
  db.prepare('DELETE FROM user_recovery WHERE user_id = ?').bind(userId),
67
70
  ]);
68
71
  return c.json({ success: true });
@@ -1 +1 @@
1
- {"version":3,"file":"setup.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/setup.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAWpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAe9C,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAQtG;AAQD,uFAAuF;AACvF,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAIzE;AAED,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqMzE;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAE7E"}
1
+ {"version":3,"file":"setup.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/setup.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAWpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAe9C,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,OAAO,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAQtG;AAkBD,uFAAuF;AACvF,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiBzE;AAED,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA+MzE;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAE7E"}
@@ -7,9 +7,9 @@ import { DEFAULT_SHOP_SETTINGS } from '../../shop/handlers/products.handler';
7
7
  import Stripe from 'stripe';
8
8
  import { checkIntegrationKey } from '../../../lib/integration-health';
9
9
  import { createId, ensureSchema, issueSessionForUser, nowSeconds } from '../../../lib/project-db';
10
- import { AGENT_PROVIDERS, AGENT_PROVIDER_SECRETS, CONFIG_PATH as WEBSITE_CONFIG_PATH, SHOP_SETTINGS_PATH, EMAIL_SETTINGS_PATH, LEGAL_CONTENT_PATH, normalizeProjectFeatures } from '@hintergrund/runtime-contracts';
10
+ import { AGENT_PROVIDERS, AGENT_PROVIDER_SECRETS, CONFIG_PATH as WEBSITE_CONFIG_PATH, SHOP_SETTINGS_PATH, EMAIL_SETTINGS_PATH, LEGAL_CONTENT_PATH, LIB_BARREL_PATH, PROJECT_FEATURES, PROJECT_FEATURE_LABELS, isDisabledFeaturePath, normalizeProjectConfig, normalizeProjectFeatures, pruneLibBarrel } from '@hintergrund/runtime-contracts';
11
11
  import { validateI18nConfig, DEFAULT_I18N_CONFIG } from '@hintergrund/runtime-contracts';
12
- import { initializeWebsiteLanguages } from '../../../lib/website-i18n';
12
+ import { translateWebsiteFiles } from '../../../lib/website-i18n';
13
13
  async function hasAdminUsers(c) {
14
14
  const db = await ensureSchema(c.env);
15
15
  const row = await db.prepare('SELECT COUNT(*) AS count FROM admin_users').first();
@@ -35,13 +35,35 @@ async function deploy(c, client = createGitHubClient(getGitHubConfig(c.env))) {
35
35
  const { owner, repo, branch } = client.getRepoInfo();
36
36
  await (await client.getOctokit()).rest.actions.createWorkflowDispatch({ owner, repo, workflow_id: 'deploy.yml', ref: branch });
37
37
  }
38
+ /**
39
+ * The site config as provisioned. Its features are the ones whose code the repository
40
+ * contains — every feature for the blueprint, the owner's choice for a demo — so setup
41
+ * offers only those, and its languages are where the demo left them.
42
+ */
43
+ async function provisionedConfig(client) {
44
+ const { data } = await readJsonConfig(client, WEBSITE_CONFIG_PATH, {});
45
+ return { raw: data, ...normalizeProjectConfig(data) };
46
+ }
38
47
  /** One-time, project-owned bootstrap. It is unavailable as soon as an admin exists. */
39
48
  export async function setupContext(c) {
40
49
  if (await hasAdminUsers(c))
41
50
  return c.json({ error: 'Project setup has already been completed.' }, 409);
42
51
  if (!(await hasValidSetupToken(c.env, c.req.query('token'))))
43
52
  return c.json({ error: 'Invalid setup link.' }, 403);
44
- return c.json({ suggestedEmail: c.env.SETUP_ADMIN_EMAIL?.trim() || undefined });
53
+ const client = createGitHubClient(getGitHubConfig(c.env));
54
+ const [config, sender] = await Promise.all([
55
+ provisionedConfig(client).catch(() => null),
56
+ readJsonConfig(client, EMAIL_SETTINGS_PATH, {}).then(({ data }) => data).catch(() => ({})),
57
+ ]);
58
+ return c.json({
59
+ suggestedEmail: c.env.SETUP_ADMIN_EMAIL?.trim() || undefined,
60
+ features: config?.features,
61
+ languages: config?.languages,
62
+ fromEmail: sender.fromEmail || undefined,
63
+ fromName: sender.fromName || undefined,
64
+ // The local harness never deploys, so provider keys are optional there.
65
+ local: c.env.DISABLE_DEPLOYMENTS === 'true',
66
+ });
45
67
  }
46
68
  export async function setupProject(c) {
47
69
  if (await hasAdminUsers(c))
@@ -63,6 +85,7 @@ export async function setupProject(c) {
63
85
  return c.json({ error: error instanceof Error ? error.message : 'Invalid website languages.' }, 400);
64
86
  }
65
87
  const features = normalizeProjectFeatures(body.features);
88
+ const local = c.env.DISABLE_DEPLOYMENTS === 'true';
66
89
  const needsEmail = features.sell || features.newsletters;
67
90
  const MIN_PASSWORD_LENGTH = 12;
68
91
  const password = typeof body.password === 'string' ? body.password : '';
@@ -79,17 +102,15 @@ export async function setupProject(c) {
79
102
  }
80
103
  if (features.sell && (!business.companyName || !business.street || !business.city))
81
104
  return c.json({ error: 'Enter your business name and address for invoices.' }, 400);
82
- const footerText = typeof body.footerText === 'string' ? body.footerText.trim().slice(0, 8000) : 'If you have any questions, please contact us.';
83
- const footerHtml = `<p>${footerText.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('\n', '<br>')}</p>`;
84
105
  if (!email)
85
106
  return c.json({ error: 'An email address is required.' }, 400);
86
107
  if (password.length < MIN_PASSWORD_LENGTH) {
87
108
  return c.json({ error: `Choose a password of at least ${MIN_PASSWORD_LENGTH} characters.` }, 400);
88
109
  }
89
- if (needsEmail && (!plunkApiKey || !fromEmail)) {
110
+ if (needsEmail && ((!plunkApiKey && !local) || !fromEmail)) {
90
111
  return c.json({ error: 'An email provider API key and sender address are required.' }, 400);
91
112
  }
92
- if (!agentProvider || !agentProviderKey)
113
+ if (!agentProvider || (!agentProviderKey && !local))
93
114
  return c.json({ error: 'Choose an AI provider and enter its API key.' }, 400);
94
115
  if (features.sell && !paymentProvider)
95
116
  return c.json({ error: 'Choose a payment provider.' }, 400);
@@ -105,8 +126,8 @@ export async function setupProject(c) {
105
126
  }
106
127
  // Validate credentials before creating an administrator or changing the repository.
107
128
  const health = await Promise.all([
108
- checkIntegrationKey(agentProvider, agentProviderKey),
109
- ...(needsEmail ? [checkIntegrationKey('plunk', plunkApiKey)] : []),
129
+ ...(agentProviderKey ? [checkIntegrationKey(agentProvider, agentProviderKey)] : []),
130
+ ...(needsEmail && plunkApiKey ? [checkIntegrationKey('plunk', plunkApiKey)] : []),
110
131
  ...(stripeSecretKey ? [checkIntegrationKey('stripe', stripeSecretKey)] : []),
111
132
  ]);
112
133
  const failed = health.find(result => !result.valid);
@@ -123,10 +144,25 @@ export async function setupProject(c) {
123
144
  console.error('Project setup GitHub preflight failed:', error);
124
145
  return c.json({ error: 'GitHub repository is unavailable. Check the project GitHub App configuration and try again.' }, 503);
125
146
  }
147
+ // Setup can only narrow what the repository contains: a feature whose code was never
148
+ // committed cannot be switched on here.
149
+ const provisioned = await provisionedConfig(client);
150
+ const unavailable = PROJECT_FEATURES.find((feature) => features[feature] && !provisioned.features[feature]);
151
+ if (unavailable)
152
+ return c.json({ error: `This site was built without “${PROJECT_FEATURE_LABELS[unavailable]}”.` }, 400);
126
153
  // The website itself arrives with the repository: it is committed at provisioning
127
- // from the site the owner built in the demo. Setup only stages the configuration
128
- // that depends on the answers given here.
154
+ // from the site the owner built in the demo. Setup stages the configuration that
155
+ // depends on the answers given here, and removes the code of every feature left off,
156
+ // so the site never ships what it does not do.
129
157
  const staged = { files: [], deletions: [] };
158
+ const { blobs } = await client.readTree();
159
+ staged.deletions = blobs.map((blob) => blob.path).filter((path) => isDisabledFeaturePath(path, features));
160
+ const barrel = await client.readFile(LIB_BARREL_PATH);
161
+ if (barrel) {
162
+ const pruned = pruneLibBarrel(barrel.content, features);
163
+ if (pruned !== barrel.content)
164
+ staged.files.push({ path: LIB_BARREL_PATH, content: pruned, encoding: 'utf8' });
165
+ }
130
166
  const db = await ensureSchema(c.env);
131
167
  const now = nowSeconds();
132
168
  const user = {
@@ -136,6 +172,7 @@ export async function setupProject(c) {
136
172
  password_hash: await hashPw(password, c.env.SECRET ?? ''),
137
173
  initial_admin: 1,
138
174
  disabled_at: null,
175
+ permissions: '',
139
176
  created_at: now,
140
177
  updated_at: now,
141
178
  };
@@ -176,12 +213,12 @@ export async function setupProject(c) {
176
213
  secrets[name] = value;
177
214
  }
178
215
  await Promise.all(Object.entries(secrets).map(([secretName, value]) => client.setActionsSecret(secretName, value)));
179
- const { data: setupState, commitSha: setupCommitSha } = await readJsonConfig(client, WEBSITE_CONFIG_PATH, {});
180
216
  await stageConfig(client, WEBSITE_CONFIG_PATH, {
181
- ...setupState,
217
+ ...provisioned.raw,
182
218
  complete: true,
183
219
  features,
184
- }, 'Record project features [skip ci]', setupCommitSha);
220
+ languages,
221
+ }, 'Record project features [skip ci]');
185
222
  const { data: shopSettings, commitSha: shopCommitSha } = await readJsonConfig(client, SHOP_SETTINGS_PATH, DEFAULT_SHOP_SETTINGS);
186
223
  await stageConfig(client, SHOP_SETTINGS_PATH, {
187
224
  ...DEFAULT_SHOP_SETTINGS,
@@ -202,7 +239,6 @@ export async function setupProject(c) {
202
239
  const { data: emailSettings, commitSha } = await readJsonConfig(client, EMAIL_SETTINGS_PATH, {});
203
240
  await stageConfig(client, EMAIL_SETTINGS_PATH, {
204
241
  ...emailSettings,
205
- footerHtml,
206
242
  fromEmail: typeof body.fromEmail === 'string' ? body.fromEmail.trim() : emailSettings.fromEmail,
207
243
  fromName: typeof body.fromName === 'string' ? body.fromName.trim() : emailSettings.fromName,
208
244
  replyTo: typeof body.replyTo === 'string' ? body.replyTo.trim() : emailSettings.replyTo,
@@ -212,13 +248,14 @@ export async function setupProject(c) {
212
248
  const { data: legal, commitSha: legalCommitSha } = await readJsonConfig(client, LEGAL_CONTENT_PATH, {});
213
249
  await stageConfig(client, LEGAL_CONTENT_PATH, { ...legal, ...business }, 'Record business details [skip ci]', legalCommitSha);
214
250
  }
215
- // Translate the staged configuration and record the chosen languages. The website's
216
- // own content was translated when its demo draft was committed at provisioning.
251
+ // Translate against the whole repository, not just what setup staged: every
252
+ // page needs the languages added here. Unchanged content
253
+ // keeps the translations the demo already made.
217
254
  try {
218
- await initializeWebsiteLanguages(staged.files, languages, {
255
+ staged.files = await translateWebsiteFiles(client, staged.files, {
219
256
  ...c.env, GEMINI_API_KEY: agentProvider === 'google' ? agentProviderKey : undefined,
220
257
  DEEPSEEK_API_KEY: agentProvider === 'deepseek' ? agentProviderKey : undefined,
221
- });
258
+ }, await client.getCommitSha(), staged.deletions);
222
259
  }
223
260
  catch (error) {
224
261
  console.error('Setup translation failed:', error);
@@ -13,4 +13,9 @@ export declare function historyWebsiteRepo(c: Context<HonoEnv>): Promise<Respons
13
13
  */
14
14
  export declare function syncWebsiteRepo(c: Context<HonoEnv>): Promise<Response>;
15
15
  export declare function commitWebsiteRepo(c: Context<HonoEnv>): Promise<Response>;
16
+ /**
17
+ * Translates what the editor asks for and returns it; nothing is written to Git. The editor
18
+ * stages the result in the working copy like any other edit, so the owner reviews it before saving.
19
+ */
20
+ export declare function translateWebsiteMessages(c: Context<HonoEnv>): Promise<Response>;
16
21
  //# sourceMappingURL=website-repo.handler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"website-repo.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/website-repo.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAuC9C,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE1D;AAED,yFAAyF;AACzF,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6B5E;AAED,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAG5E;AAED,8FAA8F;AAC9F,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAK/E;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiB5E;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwD9E"}
1
+ {"version":3,"file":"website-repo.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/website-repo.handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAwC9C,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAE1D;AAED,yFAAyF;AACzF,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6B5E;AAED,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAG5E;AAED,8FAA8F;AAC9F,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAK/E;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiB5E;AAED,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqD9E;AAED;;;GAGG;AACH,wBAAsB,wBAAwB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,QAAQ,CAAC,CAerF"}
@@ -1,7 +1,8 @@
1
1
  import { getGitHubConfig } from '../../../lib/config';
2
2
  import { createGitHubClient } from '../../../lib/github';
3
- import { CONFIG_PATH, STATIC_DIR, isDisabledFeaturePath, isWebsitePath, normalizeProjectConfig } from '@hintergrund/runtime-contracts';
4
- import { translateWebsiteFiles } from '../../../lib/website-i18n';
3
+ import { CONFIG_PATH, EMAIL_CAMPAIGNS_DIR, EMAILS_DIR, SHOP_DIR, STATIC_DIR, isDisabledFeaturePath, isWebsitePath, normalizeProjectConfig } from '@hintergrund/runtime-contracts';
4
+ import { WEBSITE_LANGUAGES } from '@hintergrund/runtime-contracts';
5
+ import { translateAll } from '../../../lib/website-i18n';
5
6
  const STATIC_MIME_TYPES = {
6
7
  '.jpg': 'image/jpeg',
7
8
  '.jpeg': 'image/jpeg',
@@ -115,6 +116,13 @@ export async function commitWebsiteRepo(c) {
115
116
  const deletions = Array.isArray(body.deletions)
116
117
  ? [...new Set(body.deletions.map((path) => normalizePath(String(path ?? ''))))]
117
118
  : [];
119
+ // One commit endpoint serves three workspaces, so each path must belong to an area the user holds.
120
+ const held = c.get('user')?.permissions ?? [];
121
+ // The shared email files hold both the order and the signup emails, so either area may edit them.
122
+ const areasOf = (path) => path.startsWith(SHOP_DIR) ? ['shop'] : path.startsWith(EMAIL_CAMPAIGNS_DIR) ? ['newsletter'] : path.startsWith(EMAILS_DIR) ? ['shop', 'newsletter'] : ['website'];
123
+ const forbidden = [...files.map((file) => file.path), ...deletions].find((path) => !held.includes('settings') && !areasOf(path).some((area) => held.includes(area)));
124
+ if (forbidden)
125
+ return c.json({ error: `You do not have access to edit ${forbidden}` }, 403);
118
126
  const invalidPath = [...files.map((file) => file.path), ...deletions].find((path) => !isAllowedWebsitePath(path));
119
127
  if (invalidPath) {
120
128
  return c.json({ error: `Path is not allowed for website sync: ${invalidPath}` }, 400);
@@ -150,14 +158,28 @@ export async function commitWebsiteRepo(c) {
150
158
  }
151
159
  }
152
160
  const baseCommitSha = body.baseCommitSha ? String(body.baseCommitSha) : await client.getCommitSha();
153
- let output;
161
+ const commitSha = await client.writeFilesAtomic(files, String(body.message || 'Publish website changes'), baseCommitSha, deletions);
162
+ return c.json({ success: true, commitSha });
163
+ }
164
+ /**
165
+ * Translates what the editor asks for and returns it; nothing is written to Git. The editor
166
+ * stages the result in the working copy like any other edit, so the owner reviews it before saving.
167
+ */
168
+ export async function translateWebsiteMessages(c) {
169
+ const body = await c.req.json().catch(() => ({}));
170
+ const items = Array.isArray(body.items) ? body.items.map((item) => ({ id: String(item.id ?? ''), source: String(item.source ?? ''), language: String(item.language ?? ''), target: String(item.target ?? ''), ...(typeof item.text === 'string' && typeof item.previousSource === 'string' ? { text: item.text.slice(0, 16000), previousSource: item.previousSource.slice(0, 16000) } : {}) })) : [];
171
+ if (items.length === 0 || items.length > 200 || items.some((item) => !item.id || !(item.language in WEBSITE_LANGUAGES) || !(item.target in WEBSITE_LANGUAGES))) {
172
+ return c.json({ error: 'Choose supported languages and up to 200 messages.' }, 400);
173
+ }
174
+ if (items.reduce((sum, item) => sum + item.source.length, 0) > 100_000)
175
+ return c.json({ error: 'Too much text in one request.' }, 413);
154
176
  try {
155
- output = await translateWebsiteFiles(client, files, c.env, baseCommitSha, deletions);
177
+ const values = await translateAll(c.env, items);
178
+ const translations = {};
179
+ items.forEach((item, index) => { (translations[item.target] ??= {})[item.id] = values[index]; });
180
+ return c.json({ translations });
156
181
  }
157
182
  catch (error) {
158
- return c.json({ error: error instanceof Error ? error.message : 'Website translation failed. Your changes have not been published.' }, 422);
183
+ return c.json({ error: error instanceof Error ? error.message : 'Translation failed.' }, 422);
159
184
  }
160
- const generatedFiles = output.filter((file) => !writtenPaths.has(file.path));
161
- const commitSha = await client.writeFilesAtomic(output, String(body.message || 'Publish website changes'), baseCommitSha, deletions.filter(path => !output.some((file) => file.path === path)));
162
- return c.json({ success: true, commitSha, generatedFiles });
163
185
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/routes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAe5B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAG9C,QAAA,MAAM,SAAS,sDAAsB,CAAC;AA8BtC,eAAe,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/routes/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAe5B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAG9C,QAAA,MAAM,SAAS,sDAAsB,CAAC;AAqCtC,eAAe,SAAS,CAAC"}
@@ -1,10 +1,10 @@
1
1
  import { Hono } from 'hono';
2
2
  import { getDashboard } from '../handlers/dashboard.handler';
3
- import { authMiddleware } from '../../../middleware/auth';
3
+ import { authMiddleware, requirePermission } from '../../../middleware/auth';
4
4
  import authRoutes from './auth.routes';
5
5
  import { createAdminUser, deleteAdminUser, listAdminUsers, patchAdminUser, sendUserRecovery } from '../handlers/admin-users.handler';
6
6
  import { getAgentConfig, proxyAgentRequest } from '../handlers/agent-provider.handler';
7
- import { commitWebsiteRepo, getWebsiteAsset, headWebsiteRepo, historyWebsiteRepo, syncWebsiteRepo } from '../handlers/website-repo.handler';
7
+ import { commitWebsiteRepo, getWebsiteAsset, headWebsiteRepo, historyWebsiteRepo, syncWebsiteRepo, translateWebsiteMessages } from '../handlers/website-repo.handler';
8
8
  import { deleteGitHubSecret, listGitHubSecrets, upsertGitHubSecret } from '../handlers/github-secrets.handler';
9
9
  import { setupContext, setupProject } from '../handlers/setup.handler';
10
10
  import { testIntegration, testSetupIntegration } from '../handlers/integrations.handler';
@@ -18,6 +18,12 @@ cmsRoutes.post('/setup', setupProject);
18
18
  cmsRoutes.post('/setup/integrations/:provider/test', testSetupIntegration);
19
19
  // Protected routes
20
20
  cmsRoutes.use('/*', authMiddleware);
21
+ // Website commits are shared by the site, shop and emails workspaces; the handler checks each path's own area.
22
+ cmsRoutes.use('/users/*', requirePermission('settings'));
23
+ cmsRoutes.use('/github/*', requirePermission('settings'));
24
+ cmsRoutes.use('/integrations/*', requirePermission('settings'));
25
+ cmsRoutes.use('/website/*', requirePermission('website', 'shop', 'newsletter', 'settings'));
26
+ cmsRoutes.use('/agent/*', requirePermission('website', 'shop', 'newsletter', 'settings'));
21
27
  cmsRoutes.get('/users', listAdminUsers);
22
28
  cmsRoutes.post('/users', createAdminUser);
23
29
  cmsRoutes.post('/users/:id/recovery', sendUserRecovery);
@@ -29,6 +35,7 @@ cmsRoutes.get('/website/repo/head', headWebsiteRepo);
29
35
  cmsRoutes.post('/website/repo/sync', syncWebsiteRepo);
30
36
  cmsRoutes.get('/website/repo/history', historyWebsiteRepo);
31
37
  cmsRoutes.put('/website/repo/commit', commitWebsiteRepo);
38
+ cmsRoutes.post('/website/i18n/translate', translateWebsiteMessages);
32
39
  cmsRoutes.get('/website/repo/assets/:path{.+}', getWebsiteAsset);
33
40
  cmsRoutes.post('/integrations/:provider/test', testIntegration);
34
41
  cmsRoutes.get('/github/secrets', listGitHubSecrets);
@@ -6,7 +6,7 @@
6
6
  import { Context } from 'hono';
7
7
  /** GET /api/email/admin/campaigns — every campaign that was sent, newest first. */
8
8
  export declare function getCampaigns(c: Context): Promise<Response>;
9
- /** POST /api/email/admin/campaigns/:id/send — sends the published draft to every subscriber. */
9
+ /** POST /api/email/admin/campaigns/:id/send — sends the published draft to every subscriber, or to one segment when the body names it. */
10
10
  export declare function sendCampaign(c: Context): Promise<Response>;
11
11
  /** POST /api/email/admin/campaigns/test — sends the copy being edited, published or not. */
12
12
  export declare function testCampaign(c: Context): Promise<Response>;
@@ -1 +1 @@
1
- {"version":3,"file":"campaigns.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/campaigns.handler.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA2B/B,mFAAmF;AACnF,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAUhE;AAED,gGAAgG;AAChG,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoDhE;AAED,4FAA4F;AAC5F,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiBhE"}
1
+ {"version":3,"file":"campaigns.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/campaigns.handler.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA4B/B,mFAAmF;AACnF,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAUhE;AAED,0IAA0I;AAC1I,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAkDhE;AAED,4FAA4F;AAC5F,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiBhE"}
@@ -7,8 +7,9 @@ import { getProjectDb } from '../../../lib/project-db';
7
7
  import { getGitHubConfig } from '../../../lib/config';
8
8
  import { createGitHubClient } from '../../../lib/github';
9
9
  import { assertEmailConfigured, sendEmail } from '../../../lib/email';
10
- import { renderEmailTemplate } from '../../../lib/email-template';
11
- import { readEmailTemplateData } from './settings.handler';
10
+ import { unsubscribeUrl } from '../../../lib/email-template';
11
+ import { renderEmail } from '@hintergrund/runtime-contracts';
12
+ import { readEmailLayout } from './settings.handler';
12
13
  import { EMAIL_CAMPAIGNS_DIR } from '@hintergrund/runtime-contracts';
13
14
  const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
14
15
  function rowToCampaign(row) {
@@ -38,7 +39,7 @@ export async function getCampaigns(c) {
38
39
  return c.json({ success: false, message: 'Failed to fetch campaigns' }, 500);
39
40
  }
40
41
  }
41
- /** POST /api/email/admin/campaigns/:id/send — sends the published draft to every subscriber. */
42
+ /** POST /api/email/admin/campaigns/:id/send — sends the published draft to every subscriber, or to one segment when the body names it. */
42
43
  export async function sendCampaign(c) {
43
44
  try {
44
45
  const id = c.req.param('id') ?? '';
@@ -54,13 +55,15 @@ export async function sendCampaign(c) {
54
55
  if (!isDraft(draft))
55
56
  return c.json({ success: false, message: 'Publish this campaign with a subject and body before sending it.' }, 400);
56
57
  assertEmailConfigured(c.env);
58
+ const segment = (await c.req.json().catch(() => ({}))).segment?.trim();
57
59
  const { results: subscribers } = await db
58
- .prepare("SELECT email, name FROM subscribers WHERE status = 'subscribed'")
60
+ .prepare(`SELECT email, name FROM subscribers WHERE status = 'subscribed'${segment ? " AND EXISTS (SELECT 1 FROM json_each(data_json, '$.segments') WHERE value = ?)" : ''}`)
61
+ .bind(...(segment ? [segment] : []))
59
62
  .all();
60
63
  if (!subscribers || subscribers.length === 0) {
61
- return c.json({ success: false, message: 'No subscribed contacts found' }, 400);
64
+ return c.json({ success: false, message: segment ? 'No subscribed contacts in this segment' : 'No subscribed contacts found' }, 400);
62
65
  }
63
- const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
66
+ const layout = await readEmailLayout(c.env);
64
67
  const origin = new URL(c.req.url).origin;
65
68
  let sentCount = 0;
66
69
  for (const subscriber of subscribers) {
@@ -69,11 +72,7 @@ export async function sendCampaign(c) {
69
72
  to: subscriber.email,
70
73
  toName: subscriber.name ?? undefined,
71
74
  subject: draft.subject,
72
- html: renderEmailTemplate({
73
- bodyHtml: draft.bodyHtml,
74
- template: settings.emailTemplate, logoDataUrl,
75
- unsubscribeUrl: `${origin}/api/email/unsubscribe?email=${encodeURIComponent(subscriber.email)}`,
76
- }),
75
+ html: renderEmail(layout, draft.bodyHtml, unsubscribeUrl(origin, subscriber.email)),
77
76
  });
78
77
  sentCount++;
79
78
  }
@@ -101,11 +100,11 @@ export async function testCampaign(c) {
101
100
  return c.json({ success: false, message: 'A valid test address is required' }, 400);
102
101
  if (!isDraft({ ...body, name: body.name ?? '' }))
103
102
  return c.json({ success: false, message: 'A subject and body are required' }, 400);
104
- const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
103
+ const layout = await readEmailLayout(c.env);
105
104
  await sendEmail(c.env, {
106
105
  to: body.email,
107
106
  subject: `[TEST] ${body.subject}`,
108
- html: renderEmailTemplate({ bodyHtml: body.bodyHtml, template: settings.emailTemplate, logoDataUrl }),
107
+ html: renderEmail(layout, body.bodyHtml),
109
108
  });
110
109
  return c.json({ success: true, message: `Test email sent to ${body.email}` });
111
110
  }
@@ -1 +1 @@
1
- {"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/public.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAQ/B,gCAAgC;AAChC,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiD7D;AAoBD,6BAA6B;AAC7B,wBAAsB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAyC3D;AAED,kCAAkC;AAClC,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoC/D;AAED,yDAAyD;AACzD,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA2DvE"}
1
+ {"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/public.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAS/B,gCAAgC;AAChC,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAiD7D;AAiBD,6BAA6B;AAC7B,wBAAsB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwC3D;AAED,kCAAkC;AAClC,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoC/D;AAED,yDAAyD;AACzD,wBAAsB,mBAAmB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA2DvE"}
@@ -3,8 +3,9 @@
3
3
  */
4
4
  import { getProjectDb, createId } from '../../../lib/project-db';
5
5
  import { sendEmail } from '../../../lib/email';
6
- import { renderEmailTemplate } from '../../../lib/email-template';
7
- import { readEmailTemplateData, readEmailTemplates } from './settings.handler';
6
+ import { unsubscribeUrl } from '../../../lib/email-template';
7
+ import { renderEmail } from '@hintergrund/runtime-contracts';
8
+ import { readEmailLayout, readEmailTemplates } from './settings.handler';
8
9
  const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
9
10
  /** POST /api/email/subscribe */
10
11
  export async function subscribe(c) {
@@ -54,12 +55,9 @@ async function sendConfirmation(c, email, token) {
54
55
  const origin = new URL(c.req.url).origin;
55
56
  const confirmUrl = `${origin}/emails/confirm?token=${token}`;
56
57
  try {
57
- const [{ settings, logoDataUrl }, { confirmation }] = await Promise.all([readEmailTemplateData(c.env), readEmailTemplates(c.env)]);
58
+ const [layout, { confirmation }] = await Promise.all([readEmailLayout(c.env), readEmailTemplates(c.env)]);
58
59
  const bodyHtml = confirmation.bodyHtml.replaceAll('{{confirm_url}}', confirmUrl);
59
- const html = renderEmailTemplate({
60
- bodyHtml,
61
- template: settings.emailTemplate, logoDataUrl,
62
- });
60
+ const html = renderEmail(layout, bodyHtml);
63
61
  await sendEmail(c.env, { to: email, subject: confirmation.subject, html });
64
62
  }
65
63
  catch (err) {
@@ -82,7 +80,7 @@ export async function confirm(c) {
82
80
  if (!subscriber) {
83
81
  return c.json({ success: false, message: 'Invalid or expired confirmation token' }, 400);
84
82
  }
85
- const [{ settings, logoDataUrl }, { welcome }] = await Promise.all([readEmailTemplateData(c.env), readEmailTemplates(c.env)]);
83
+ const [layout, { welcome }] = await Promise.all([readEmailLayout(c.env), readEmailTemplates(c.env)]);
86
84
  const result = await db.prepare(`UPDATE subscribers SET status = 'subscribed', confirmed_at = ?, subscribed_at = ?, confirmation_token = NULL, updated_at = ? WHERE id = ? AND status = 'pending' AND confirmation_token = ?`).bind(now, now, now, subscriber.id, token).run();
87
85
  // Only the request that consumes the token sends a welcome. Confirmation stays
88
86
  // successful if the provider fails; never undo consent or send it twice on refresh.
@@ -91,8 +89,7 @@ export async function confirm(c) {
91
89
  await sendEmail(c.env, {
92
90
  to: subscriber.email,
93
91
  subject: welcome.subject,
94
- html: renderEmailTemplate({ bodyHtml: welcome.bodyHtml, template: settings.emailTemplate, logoDataUrl,
95
- unsubscribeUrl: `${new URL(c.req.url).origin}/api/email/unsubscribe?email=${encodeURIComponent(subscriber.email)}` }),
92
+ html: renderEmail(layout, welcome.bodyHtml, unsubscribeUrl(new URL(c.req.url).origin, subscriber.email)),
96
93
  });
97
94
  }
98
95
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"send.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/send.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAQ/B,8DAA8D;AAC9D,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqCrE;AAED,wEAAwE;AACxE,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6CjE"}
1
+ {"version":3,"file":"send.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/send.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAS/B,8DAA8D;AAC9D,wBAAsB,iBAAiB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAkCrE;AAED,wEAAwE;AACxE,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAyCjE"}
@@ -3,8 +3,9 @@
3
3
  */
4
4
  import { getProjectDb } from '../../../lib/project-db';
5
5
  import { sendEmail } from '../../../lib/email';
6
- import { renderEmailTemplate } from '../../../lib/email-template';
7
- import { readEmailTemplateData } from './settings.handler';
6
+ import { unsubscribeUrl } from '../../../lib/email-template';
7
+ import { renderEmail } from '@hintergrund/runtime-contracts';
8
+ import { readEmailLayout } from './settings.handler';
8
9
  const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
9
10
  /** POST /api/email/admin/send — transactional single email */
10
11
  export async function sendTransactional(c) {
@@ -16,15 +17,12 @@ export async function sendTransactional(c) {
16
17
  if (!EMAIL_REGEX.test(body.to)) {
17
18
  return c.json({ success: false, message: 'Invalid email format' }, 400);
18
19
  }
19
- const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
20
+ const layout = await readEmailLayout(c.env);
20
21
  await sendEmail(c.env, {
21
22
  to: body.to,
22
23
  toName: body.name,
23
24
  subject: body.subject,
24
- html: renderEmailTemplate({
25
- bodyHtml: body.bodyHtml,
26
- template: settings.emailTemplate, logoDataUrl,
27
- }),
25
+ html: renderEmail(layout, body.bodyHtml),
28
26
  from: body.from,
29
27
  replyTo: body.replyTo,
30
28
  });
@@ -43,7 +41,7 @@ export async function sendBulkEmail(c) {
43
41
  return c.json({ success: false, message: 'subject and bodyHtml are required' }, 400);
44
42
  }
45
43
  const db = getProjectDb(c.env);
46
- const { settings, logoDataUrl } = await readEmailTemplateData(c.env);
44
+ const layout = await readEmailLayout(c.env);
47
45
  const { results: subscribers } = await db
48
46
  .prepare("SELECT email, name FROM subscribers WHERE status = 'subscribed'")
49
47
  .all();
@@ -53,17 +51,13 @@ export async function sendBulkEmail(c) {
53
51
  let sentCount = 0;
54
52
  const origin = new URL(c.req.url).origin;
55
53
  for (const subscriber of subscribers) {
56
- const unsubscribeUrl = `${origin}/api/email/unsubscribe?email=${encodeURIComponent(subscriber.email)}`;
54
+ const unsubscribe = unsubscribeUrl(origin, subscriber.email);
57
55
  try {
58
56
  await sendEmail(c.env, {
59
57
  to: subscriber.email,
60
58
  toName: subscriber.name ?? undefined,
61
59
  subject: body.subject,
62
- html: renderEmailTemplate({
63
- bodyHtml: body.bodyHtml,
64
- template: settings.emailTemplate, logoDataUrl,
65
- unsubscribeUrl,
66
- }),
60
+ html: renderEmail(layout, body.bodyHtml, unsubscribe),
67
61
  });
68
62
  sentCount++;
69
63
  }
@@ -1,29 +1,10 @@
1
1
  import type { Bindings } from '../../../index';
2
- import { type GitHubClient } from '../../../lib/github';
3
- import { type BusinessDetails, type EmailTemplates } from '@hintergrund/runtime-contracts';
4
- /** Reads the letterhead chosen in email settings and inlines it, as mail clients need a data URL. */
5
- export declare function resolveLogoDataUrl(github: GitHubClient, logoPath: string | undefined): Promise<string | undefined>;
2
+ import { type BusinessDetails, type EmailSettings, type EmailTemplates } from '@hintergrund/runtime-contracts';
6
3
  export declare function readEmailSettings(env: Bindings): Promise<{
7
- settings: {
8
- emailTemplate: import("@hintergrund/runtime-contracts").EmailTemplateConfig;
9
- footerHtml?: string;
10
- logoPath?: string;
11
- fromEmail?: string;
12
- fromName?: string;
13
- replyTo?: string;
14
- };
15
- }>;
16
- export declare function readEmailTemplateData(env: Bindings): Promise<{
17
- settings: {
18
- emailTemplate: import("@hintergrund/runtime-contracts").EmailTemplateConfig;
19
- footerHtml?: string;
20
- logoPath?: string;
21
- fromEmail?: string;
22
- fromName?: string;
23
- replyTo?: string;
24
- };
25
- logoDataUrl: string | undefined;
4
+ settings: EmailSettings;
26
5
  }>;
6
+ /** The document every email is sent in. Its images and links are site paths; mail clients need absolute URLs. */
7
+ export declare function readEmailLayout(env: Bindings): Promise<string | undefined>;
27
8
  /** The copy of every automated email; a missing message falls back to the default. */
28
9
  export declare function readEmailTemplates(env: Bindings): Promise<EmailTemplates>;
29
10
  /** The business behind the site, as the imprint shows it. */