@hintergrund/worker 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/api/cms/handlers/assets.handler.d.ts +24 -1
  2. package/dist/api/cms/handlers/assets.handler.d.ts.map +1 -1
  3. package/dist/api/cms/handlers/assets.handler.js +111 -210
  4. package/dist/api/cms/handlers/config.handler.d.ts +4 -0
  5. package/dist/api/cms/handlers/config.handler.d.ts.map +1 -1
  6. package/dist/api/cms/handlers/config.handler.js +20 -71
  7. package/dist/api/cms/handlers/content.handler.d.ts +12 -1
  8. package/dist/api/cms/handlers/content.handler.d.ts.map +1 -1
  9. package/dist/api/cms/handlers/content.handler.js +57 -233
  10. package/dist/api/cms/handlers/dashboard.handler.js +1 -1
  11. package/dist/api/emails/handlers/branding.handler.d.ts +17 -0
  12. package/dist/api/emails/handlers/branding.handler.d.ts.map +1 -0
  13. package/dist/api/emails/handlers/branding.handler.js +120 -0
  14. package/dist/api/emails/handlers/campaigns.handler.d.ts +32 -0
  15. package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -0
  16. package/dist/api/emails/handlers/campaigns.handler.js +139 -0
  17. package/dist/api/emails/handlers/contacts.handler.d.ts +37 -0
  18. package/dist/api/emails/handlers/contacts.handler.d.ts.map +1 -0
  19. package/dist/api/emails/handlers/contacts.handler.js +161 -0
  20. package/dist/api/emails/handlers/invoice.handler.d.ts +30 -0
  21. package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -0
  22. package/dist/api/emails/handlers/invoice.handler.js +463 -0
  23. package/dist/api/emails/handlers/public.handler.d.ts +36 -0
  24. package/dist/api/emails/handlers/public.handler.d.ts.map +1 -0
  25. package/dist/api/emails/handlers/public.handler.js +350 -0
  26. package/dist/api/emails/handlers/send.handler.d.ts +23 -0
  27. package/dist/api/emails/handlers/send.handler.d.ts.map +1 -0
  28. package/dist/api/emails/handlers/send.handler.js +117 -0
  29. package/dist/api/emails/handlers/settings.handler.d.ts +36 -0
  30. package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -0
  31. package/dist/api/emails/handlers/settings.handler.js +312 -0
  32. package/dist/api/emails/handlers/templates.handler.d.ts +32 -0
  33. package/dist/api/emails/handlers/templates.handler.d.ts.map +1 -0
  34. package/dist/api/emails/handlers/templates.handler.js +132 -0
  35. package/dist/api/emails/routes/admin.routes.d.ts +9 -0
  36. package/dist/api/emails/routes/admin.routes.d.ts.map +1 -0
  37. package/dist/api/emails/routes/admin.routes.js +77 -0
  38. package/dist/api/emails/routes/index.d.ts +9 -0
  39. package/dist/api/emails/routes/index.d.ts.map +1 -0
  40. package/dist/api/emails/routes/index.js +14 -0
  41. package/dist/api/emails/routes/public.routes.d.ts +9 -0
  42. package/dist/api/emails/routes/public.routes.d.ts.map +1 -0
  43. package/dist/api/emails/routes/public.routes.js +15 -0
  44. package/dist/api/newsletter/handlers/emails.handler.d.ts +13 -3
  45. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +1 -1
  46. package/dist/api/newsletter/handlers/emails.handler.js +140 -12
  47. package/dist/api/newsletter/handlers/invoice.handler.d.ts +22 -0
  48. package/dist/api/newsletter/handlers/invoice.handler.d.ts.map +1 -0
  49. package/dist/api/newsletter/handlers/invoice.handler.js +455 -0
  50. package/dist/api/newsletter/handlers/public.handler.d.ts +4 -4
  51. package/dist/api/newsletter/handlers/public.handler.d.ts.map +1 -1
  52. package/dist/api/newsletter/handlers/public.handler.js +78 -20
  53. package/dist/api/newsletter/handlers/send.handler.d.ts +2 -2
  54. package/dist/api/newsletter/handlers/send.handler.js +3 -3
  55. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +4 -4
  56. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +1 -1
  57. package/dist/api/newsletter/handlers/subscribers.handler.js +8 -4
  58. package/dist/api/newsletter/routes/admin.routes.d.ts.map +1 -1
  59. package/dist/api/newsletter/routes/admin.routes.js +8 -1
  60. package/dist/api/shop/handlers/assets.handler.d.ts +3 -0
  61. package/dist/api/shop/handlers/assets.handler.d.ts.map +1 -0
  62. package/dist/api/shop/handlers/assets.handler.js +62 -0
  63. package/dist/api/shop/handlers/checkout.handler.d.ts +10 -0
  64. package/dist/api/shop/handlers/checkout.handler.d.ts.map +1 -0
  65. package/dist/api/shop/handlers/checkout.handler.js +50 -0
  66. package/dist/api/shop/handlers/products.handler.d.ts +0 -7
  67. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
  68. package/dist/api/shop/handlers/products.handler.js +0 -23
  69. package/dist/api/shop/handlers/public.handler.d.ts +17 -0
  70. package/dist/api/shop/handlers/public.handler.d.ts.map +1 -0
  71. package/dist/api/shop/handlers/public.handler.js +108 -0
  72. package/dist/api/shop/handlers/webhook.handler.d.ts +10 -0
  73. package/dist/api/shop/handlers/webhook.handler.d.ts.map +1 -0
  74. package/dist/api/shop/handlers/webhook.handler.js +233 -0
  75. package/dist/api/shop/routes.d.ts.map +1 -1
  76. package/dist/api/shop/routes.js +9 -12
  77. package/dist/hintergrund-assets.d.ts +2 -2
  78. package/dist/hintergrund-assets.d.ts.map +1 -1
  79. package/dist/hintergrund-assets.js +2 -2
  80. package/dist/index.d.ts +9 -17
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +4 -7
  83. package/dist/lib/config.d.ts +13 -7
  84. package/dist/lib/config.d.ts.map +1 -1
  85. package/dist/lib/config.js +39 -44
  86. package/dist/lib/github.d.ts +124 -0
  87. package/dist/lib/github.d.ts.map +1 -0
  88. package/dist/lib/github.js +286 -0
  89. package/dist/lib/plunk.d.ts +207 -0
  90. package/dist/lib/plunk.d.ts.map +1 -0
  91. package/dist/lib/plunk.js +262 -0
  92. package/dist/middleware/auth.d.ts.map +1 -1
  93. package/dist/middleware/auth.js +2 -5
  94. package/package.json +32 -31
@@ -1,64 +1,28 @@
1
- import { Octokit } from '@octokit/rest';
2
- import { getCmsConfig } from '../../../lib/config';
1
+ import { getCmsConfig, getGitHubConfig } from '../../../lib/config';
2
+ import { createGitHubClient } from '../../../lib/github';
3
3
  /**
4
- * Decode base64 content to UTF-8 string.
5
- * atob() decodes to Latin-1, which corrupts multi-byte UTF-8 characters.
4
+ * GET /api/admin/contents
5
+ * Fetch all content collections from GitHub
6
6
  */
7
- function decodeBase64UTF8(base64) {
8
- const binaryString = atob(base64);
9
- const bytes = new Uint8Array(binaryString.length);
10
- for (let i = 0; i < binaryString.length; i++) {
11
- bytes[i] = binaryString.charCodeAt(i);
12
- }
13
- return new TextDecoder('utf-8').decode(bytes);
14
- }
15
- /**
16
- * Encode UTF-8 string to base64.
17
- * btoa() only works with Latin-1, which corrupts multi-byte UTF-8 characters like ß.
18
- */
19
- function encodeUTF8Base64(str) {
20
- const bytes = new TextEncoder().encode(str);
21
- let binaryString = '';
22
- for (let i = 0; i < bytes.length; i++) {
23
- binaryString += String.fromCharCode(bytes[i]);
24
- }
25
- return btoa(binaryString);
26
- }
27
7
  export async function getContents(c) {
28
8
  try {
29
9
  const config = getCmsConfig(c.env);
30
- const octokit = new Octokit({
31
- auth: config.gitToken
32
- });
10
+ const gitConfig = getGitHubConfig(c.env);
11
+ const github = createGitHubClient(gitConfig);
33
12
  // Get current commit SHA from branch
34
- const ref = await octokit.rest.git.getRef({
35
- owner: config.gitOwner,
36
- repo: config.gitRepo,
37
- ref: `heads/${config.gitBranch}`
38
- });
39
- const commitSha = ref.data.object.sha;
40
- const configFile = await octokit.rest.repos.getContent({
41
- owner: config.gitOwner,
42
- repo: config.gitRepo,
43
- path: `${config.contentDir}/config.json`
44
- });
45
- // Type guard to check if data is a file (not array or directory)
46
- if (Array.isArray(configFile.data) || !('content' in configFile.data)) {
47
- throw new Error('Config file not found or is not a file');
13
+ const commitSha = await github.getCommitSha();
14
+ // Read content config
15
+ const configResult = await github.readJsonFile(`${config.contentDir}/config.json`);
16
+ if (!configResult) {
17
+ throw new Error('Config file not found');
48
18
  }
49
- const contentConfig = JSON.parse(decodeBase64UTF8(configFile.data.content || ''));
50
- const collections = await Promise.all(Object.keys(contentConfig).map(async (content) => {
51
- const contentFile = await octokit.rest.repos.getContent({
52
- owner: config.gitOwner,
53
- repo: config.gitRepo,
54
- path: `${config.contentDir}/${content}.json`
55
- });
56
- // Type guard to check if data is a file (not array or directory)
57
- if (Array.isArray(contentFile.data) || !('content' in contentFile.data)) {
58
- throw new Error(`Content file ${content}.json not found or is not a file`);
59
- }
19
+ const contentConfig = configResult.data;
20
+ // Fetch all content files in parallel
21
+ const collectionKeys = Object.keys(contentConfig);
22
+ const collections = await Promise.all(collectionKeys.map(async (content) => {
23
+ const result = await github.readJsonFile(`${config.contentDir}/${content}.json`);
60
24
  return {
61
- [content]: JSON.parse(decodeBase64UTF8(contentFile.data.content || ''))
25
+ [content]: result?.data || {}
62
26
  };
63
27
  }));
64
28
  const collectionsObject = collections.reduce((acc, cur) => ({ ...acc, ...cur }), {});
@@ -67,125 +31,44 @@ export async function getContents(c) {
67
31
  collections: collectionsObject,
68
32
  commitSha
69
33
  };
70
- return new Response(JSON.stringify(response), {
71
- status: 200
72
- });
34
+ return c.json(response);
73
35
  }
74
36
  catch (error) {
75
37
  console.error('Error fetching contents:', error);
76
- return new Response(JSON.stringify({
38
+ return c.json({
77
39
  error: error.message || 'Failed to fetch contents',
78
40
  details: error.toString()
79
- }), {
80
- status: 500,
81
- headers: { 'Content-Type': 'application/json' }
82
- });
41
+ }, 500);
83
42
  }
84
43
  }
85
44
  /**
86
45
  * Sync contents from GitHub - optimized for conditional fetching
87
- * Only fetches content data from GitHub if commitSha has changed
88
46
  */
89
47
  export async function syncContents(c) {
90
- try {
91
- const config = getCmsConfig(c.env);
92
- const octokit = new Octokit({
93
- auth: config.gitToken
94
- });
95
- // Get current commit SHA from branch
96
- const ref = await octokit.rest.git.getRef({
97
- owner: config.gitOwner,
98
- repo: config.gitRepo,
99
- ref: `heads/${config.gitBranch}`
100
- });
101
- const commitSha = ref.data.object.sha;
102
- // Always fetch config (it's small and may change without commitSha changing)
103
- const configFile = await octokit.rest.repos.getContent({
104
- owner: config.gitOwner,
105
- repo: config.gitRepo,
106
- path: `${config.contentDir}/config.json`
107
- });
108
- // Type guard to check if data is a file (not array or directory)
109
- if (Array.isArray(configFile.data) || !('content' in configFile.data)) {
110
- throw new Error('Config file not found or is not a file');
111
- }
112
- const contentConfig = JSON.parse(decodeBase64UTF8(configFile.data.content || ''));
113
- // Fetch all content files from GitHub
114
- const collections = await Promise.all(Object.keys(contentConfig).map(async (content) => {
115
- const contentFile = await octokit.rest.repos.getContent({
116
- owner: config.gitOwner,
117
- repo: config.gitRepo,
118
- path: `${config.contentDir}/${content}.json`
119
- });
120
- // Type guard to check if data is a file (not array or directory)
121
- if (Array.isArray(contentFile.data) || !('content' in contentFile.data)) {
122
- throw new Error(`Content file ${content}.json not found or is not a file`);
123
- }
124
- return {
125
- [content]: JSON.parse(decodeBase64UTF8(contentFile.data.content || ''))
126
- };
127
- }));
128
- const collectionsObject = collections.reduce((acc, cur) => ({ ...acc, ...cur }), {});
129
- const response = {
130
- config: contentConfig,
131
- collections: collectionsObject,
132
- commitSha
133
- };
134
- return new Response(JSON.stringify(response), {
135
- status: 200,
136
- headers: {
137
- 'Content-Type': 'application/json'
138
- }
139
- });
140
- }
141
- catch (error) {
142
- console.error('Error syncing contents:', error);
143
- return new Response(JSON.stringify({
144
- error: error.message || 'Failed to sync contents',
145
- details: error.toString()
146
- }), {
147
- status: 500,
148
- headers: { 'Content-Type': 'application/json' }
149
- });
150
- }
48
+ // For now, this is same as getContents, but could be optimized later with If-None-Match
49
+ return getContents(c);
151
50
  }
51
+ /**
52
+ * PUT /api/admin/contents
53
+ * Update content collections in GitHub atomically
54
+ */
152
55
  export async function updateContents(c) {
153
56
  try {
154
57
  const request = await c.req.json();
155
58
  const config = getCmsConfig(c.env);
156
- const octokit = new Octokit({
157
- auth: config.gitToken
158
- });
159
- // Get reference from branch
160
- const ref = await octokit.rest.git.getRef({
161
- owner: config.gitOwner,
162
- repo: config.gitRepo,
163
- ref: `heads/${config.gitBranch}`
164
- });
165
- const currentCommitSha = ref.data.object.sha;
166
- // Check for conflicts - if commit SHA doesn't match, someone else has committed
59
+ const gitConfig = getGitHubConfig(c.env);
60
+ const github = createGitHubClient(gitConfig);
61
+ // Get current commit SHA
62
+ const currentCommitSha = await github.getCommitSha();
63
+ // Check for conflicts
167
64
  if (request.commitSha !== currentCommitSha) {
168
- // Fetch current collections to show in conflict UI
169
- const configFile = await octokit.rest.repos.getContent({
170
- owner: config.gitOwner,
171
- repo: config.gitRepo,
172
- path: `${config.contentDir}/config.json`
173
- });
174
- if (Array.isArray(configFile.data) || !('content' in configFile.data)) {
175
- throw new Error('Config file not found or is not a file');
176
- }
177
- const contentConfig = JSON.parse(decodeBase64UTF8(configFile.data.content || ''));
65
+ // Fetch current state for conflict resolution
66
+ const configResult = await github.readJsonFile(`${config.contentDir}/config.json`);
67
+ const contentConfig = configResult?.data || {};
178
68
  const collections = await Promise.all(Object.keys(contentConfig).map(async (content) => {
179
- const contentFile = await octokit.rest.repos.getContent({
180
- owner: config.gitOwner,
181
- repo: config.gitRepo,
182
- path: `${config.contentDir}/${content}.json`
183
- });
184
- if (Array.isArray(contentFile.data) || !('content' in contentFile.data)) {
185
- throw new Error(`Content file ${content}.json not found or is not a file`);
186
- }
69
+ const result = await github.readJsonFile(`${config.contentDir}/${content}.json`);
187
70
  return {
188
- [content]: JSON.parse(decodeBase64UTF8(contentFile.data.content || ''))
71
+ [content]: result?.data || {}
189
72
  };
190
73
  }));
191
74
  const serverCollections = collections.reduce((acc, cur) => ({ ...acc, ...cur }), {});
@@ -195,99 +78,40 @@ export async function updateContents(c) {
195
78
  serverCollections,
196
79
  message: 'Content has been modified by another user. Please resolve conflicts.'
197
80
  };
198
- return new Response(JSON.stringify(conflictResponse), { status: 409 });
81
+ return c.json(conflictResponse, 409);
199
82
  }
200
- // Get latest commit
201
- const commit = await octokit.rest.git.getCommit({
202
- owner: config.gitOwner,
203
- repo: config.gitRepo,
204
- commit_sha: currentCommitSha
205
- });
206
- // Create blob for each change and save file tree
207
- const blobs = await Promise.all(Object.keys(request.collections).map(async (content) => {
208
- const blob = await octokit.rest.git.createBlob({
209
- owner: config.gitOwner,
210
- repo: config.gitRepo,
211
- content: JSON.stringify(request.collections[content], null, 4),
212
- encoding: 'utf-8'
213
- });
214
- return {
215
- path: `${config.contentDir}/${content}.json`,
216
- mode: '100644',
217
- type: 'blob',
218
- sha: blob.data.sha
219
- };
83
+ // Prepare files for atomic update
84
+ const files = Object.keys(request.collections).map((content) => ({
85
+ path: `${config.contentDir}/${content}.json`,
86
+ content: JSON.stringify(request.collections[content], null, 4)
220
87
  }));
221
- // Create tree
222
- const newTree = await octokit.rest.git.createTree({
223
- owner: config.gitOwner,
224
- repo: config.gitRepo,
225
- tree: blobs,
226
- base_tree: commit.data.tree.sha
227
- });
228
- // Create commit
229
- const newCommit = await octokit.rest.git.createCommit({
230
- owner: config.gitOwner,
231
- repo: config.gitRepo,
232
- message: 'Update content',
233
- tree: newTree.data.sha,
234
- parents: [commit.data.sha]
235
- });
236
- // Update reference
237
- await octokit.rest.git.updateRef({
238
- owner: config.gitOwner,
239
- repo: config.gitRepo,
240
- ref: `heads/${config.gitBranch}`,
241
- sha: newCommit.data.sha
242
- });
88
+ // Write to GitHub atomically
89
+ await github.writeFilesAtomic(files, 'Update content', currentCommitSha);
243
90
  const response = { success: true };
244
- return new Response(JSON.stringify(response), { status: 200 });
91
+ return c.json(response);
245
92
  }
246
93
  catch (error) {
247
- console.log(error);
248
- return new Response(JSON.stringify(error), {
249
- status: 500
250
- });
94
+ console.error('Update contents error:', error);
95
+ return c.json({ error: error.message || 'Failed to update contents' }, 500);
251
96
  }
252
97
  }
98
+ /**
99
+ * DELETE /api/admin/contents
100
+ * Actually this seems to be an update operation in disguise (updating a file with filtered records)
101
+ */
253
102
  export async function deleteContent(c) {
254
103
  try {
255
104
  const deleteData = await c.req.json();
256
105
  const contentId = Object.keys(deleteData)[0];
257
106
  const config = getCmsConfig(c.env);
258
- const octokit = new Octokit({
259
- auth: config.gitToken
260
- });
261
- const fileInfo = await octokit.rest.repos.getContent({
262
- owner: config.gitOwner,
263
- repo: config.gitRepo,
264
- path: `${config.contentDir}/${contentId}.json`,
265
- ref: config.gitBranch
266
- });
267
- // Type guard to check if data is a file (not array or directory)
268
- if (Array.isArray(fileInfo.data) || !('sha' in fileInfo.data)) {
269
- throw new Error(`File ${contentId}.json not found or is not a file`);
270
- }
271
- const response = await octokit.rest.repos.createOrUpdateFileContents({
272
- owner: config.gitOwner,
273
- repo: config.gitRepo,
274
- path: `${config.contentDir}/${contentId}.json`,
275
- message: `Delete record(s) from ${contentId} [CI SKIP]`,
276
- content: encodeUTF8Base64(JSON.stringify(deleteData[contentId], null, 4)),
277
- branch: config.gitBranch,
278
- sha: fileInfo.data.sha
279
- });
280
- if (response.status !== 200) {
281
- return new Response(`Error deleting record(s) from ${contentId}`, {
282
- status: 500
283
- });
284
- }
285
- return new Response(`Deleted record from ${contentId}`, { status: 200 });
107
+ const gitConfig = getGitHubConfig(c.env);
108
+ const github = createGitHubClient(gitConfig);
109
+ // This handler in the old code was just writing the updated file
110
+ await github.writeJsonFile(`${config.contentDir}/${contentId}.json`, deleteData[contentId], `Delete record(s) from ${contentId} [CI SKIP]`);
111
+ return c.json({ message: `Deleted record from ${contentId}` });
286
112
  }
287
113
  catch (error) {
288
- console.log(error);
289
- return new Response(error.message, {
290
- status: 500
291
- });
114
+ console.error('Delete content error:', error);
115
+ return c.json({ error: error.message || 'Failed to delete content' }, 500);
292
116
  }
293
117
  }
@@ -9,7 +9,7 @@ export async function getDashboard(c) {
9
9
  }
10
10
  catch (error) {
11
11
  // Fallback to default config if parsing fails
12
- const configParams = 'config=\'{"cms":true,"newsletter":false,"shop":false}\'';
12
+ const configParams = 'config=\'{"cms":true,"emails":false,"shop":false}\'';
13
13
  return c.html(getTemplate('admin', c.env.UI_BASE_URL, configParams));
14
14
  }
15
15
  }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Branding Handler
3
+ *
4
+ * Manages global email branding stored in GitHub.
5
+ */
6
+ import { Context } from 'hono';
7
+ /**
8
+ * GET /api/email/admin/branding
9
+ * Get the global branding configuration from GitHub
10
+ */
11
+ export declare function getBranding(c: Context): Promise<Response>;
12
+ /**
13
+ * PUT /api/email/admin/branding
14
+ * Save/update the global branding configuration to GitHub
15
+ */
16
+ export declare function saveBranding(c: Context): Promise<Response>;
17
+ //# sourceMappingURL=branding.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"branding.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/branding.handler.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAsC/B;;;GAGG;AACH,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAmB/D;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA8EhE"}
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Branding Handler
3
+ *
4
+ * Manages global email branding stored in GitHub.
5
+ */
6
+ import { getGitHubConfig } from '../../../lib/config';
7
+ import { createGitHubClient } from '../../../lib/github';
8
+ // Default branding configuration
9
+ function getDefaultBranding() {
10
+ return {
11
+ primaryColor: '#3498db',
12
+ companyName: 'Company Name',
13
+ footerText: 'You are receiving this email because you subscribed to our newsletter.',
14
+ backgroundColor: '#f6f6f6',
15
+ contentBackgroundColor: '#ffffff',
16
+ maxWidth: '580px',
17
+ borderRadius: '3px',
18
+ logoAlign: 'center',
19
+ logoSize: '120px',
20
+ };
21
+ }
22
+ // Default branding record
23
+ function getDefaultBrandingRecord() {
24
+ return {
25
+ id: 'global',
26
+ config: getDefaultBranding(),
27
+ logo: undefined,
28
+ createdAt: Date.now(),
29
+ updatedAt: Date.now(),
30
+ };
31
+ }
32
+ /**
33
+ * Get the settings file path
34
+ */
35
+ function getSettingsPath() {
36
+ return `emails/settings.json`;
37
+ }
38
+ /**
39
+ * GET /api/email/admin/branding
40
+ * Get the global branding configuration from GitHub
41
+ */
42
+ export async function getBranding(c) {
43
+ try {
44
+ const gitConfig = getGitHubConfig(c.env);
45
+ const github = createGitHubClient(gitConfig);
46
+ const settingsPath = getSettingsPath();
47
+ // Try to read settings from GitHub
48
+ const result = await github.readJsonFile(settingsPath);
49
+ if (!result || !result.data.branding) {
50
+ // Return default branding if file doesn't exist
51
+ return c.json({ branding: getDefaultBrandingRecord() });
52
+ }
53
+ return c.json({ branding: result.data.branding });
54
+ }
55
+ catch (error) {
56
+ console.error('Get branding error:', error);
57
+ return c.json({ branding: getDefaultBrandingRecord() });
58
+ }
59
+ }
60
+ /**
61
+ * PUT /api/email/admin/branding
62
+ * Save/update the global branding configuration to GitHub
63
+ */
64
+ export async function saveBranding(c) {
65
+ try {
66
+ const body = await c.req.json();
67
+ if (!body.config) {
68
+ return c.json({ success: false, message: 'Config is required' }, 400);
69
+ }
70
+ // Validate required fields
71
+ if (!body.config.primaryColor || !body.config.companyName) {
72
+ return c.json({ success: false, message: 'primaryColor and companyName are required' }, 400);
73
+ }
74
+ const gitConfig = getGitHubConfig(c.env);
75
+ const github = createGitHubClient(gitConfig);
76
+ const settingsPath = getSettingsPath();
77
+ const now = Date.now();
78
+ // Read existing settings
79
+ const existing = await github.readJsonFile(settingsPath);
80
+ // Check for conflicts if commitSha provided
81
+ if (body.commitSha) {
82
+ const currentSha = await github.getCommitSha();
83
+ if (body.commitSha !== currentSha) {
84
+ // Fetch current branding for conflict resolution
85
+ const currentSettings = await github.readJsonFile(settingsPath);
86
+ return c.json({
87
+ conflict: true,
88
+ currentCommitSha: currentSha,
89
+ serverBranding: currentSettings?.data.branding || getDefaultBrandingRecord(),
90
+ message: 'Settings have been modified. Please resolve conflicts.',
91
+ }, 409);
92
+ }
93
+ }
94
+ // Build updated branding record
95
+ const branding = {
96
+ id: 'global',
97
+ config: body.config,
98
+ logo: body.logo ?? existing?.data.branding?.logo ?? undefined,
99
+ createdAt: existing?.data.branding?.createdAt || now,
100
+ updatedAt: now,
101
+ };
102
+ // Merge with existing settings (preserve invoice config)
103
+ const settings = {
104
+ branding,
105
+ invoice: existing?.data.invoice,
106
+ };
107
+ // Write to GitHub
108
+ await github.writeJsonFile(settingsPath, settings, 'Update email branding [skip ci]');
109
+ // Get new commit SHA
110
+ const newCommitSha = await github.getCommitSha();
111
+ return c.json({ success: true, branding, commitSha: newCommitSha });
112
+ }
113
+ catch (error) {
114
+ console.error('Save branding error:', error);
115
+ return c.json({
116
+ success: false,
117
+ message: error instanceof Error ? error.message : 'Failed to save branding',
118
+ }, 500);
119
+ }
120
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Campaigns Handler
3
+ *
4
+ * Manages email campaigns via Plunk API.
5
+ */
6
+ import { Context } from 'hono';
7
+ /**
8
+ * GET /api/email/admin/campaigns
9
+ * Get all campaigns from Plunk
10
+ */
11
+ export declare function getCampaigns(c: Context): Promise<Response>;
12
+ /**
13
+ * GET /api/email/admin/campaigns/:id
14
+ * Get a single campaign from Plunk
15
+ */
16
+ export declare function getCampaign(c: Context): Promise<Response>;
17
+ /**
18
+ * POST /api/email/admin/campaigns
19
+ * Create a new campaign in Plunk
20
+ */
21
+ export declare function createCampaign(c: Context): Promise<Response>;
22
+ /**
23
+ * POST /api/email/admin/campaigns/:id/send
24
+ * Send a campaign to all subscribed contacts
25
+ */
26
+ export declare function sendCampaign(c: Context): Promise<Response>;
27
+ /**
28
+ * POST /api/email/admin/campaigns/:id/test
29
+ * Send a test email for a campaign
30
+ */
31
+ export declare function testCampaign(c: Context): Promise<Response>;
32
+ //# sourceMappingURL=campaigns.handler.d.ts.map
@@ -0,0 +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;AAG/B;;;GAGG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgBhE;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsB/D;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA0ClE;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA0BhE;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqChE"}
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Campaigns Handler
3
+ *
4
+ * Manages email campaigns via Plunk API.
5
+ */
6
+ import { createPlunkClient } from '../../../lib/plunk';
7
+ /**
8
+ * GET /api/email/admin/campaigns
9
+ * Get all campaigns from Plunk
10
+ */
11
+ export async function getCampaigns(c) {
12
+ try {
13
+ const plunk = createPlunkClient(c.env);
14
+ const { campaigns } = await plunk.getCampaigns();
15
+ return c.json({ campaigns });
16
+ }
17
+ catch (error) {
18
+ console.error('Get campaigns error:', error);
19
+ return c.json({
20
+ success: false,
21
+ message: error instanceof Error ? error.message : 'Failed to fetch campaigns',
22
+ }, 500);
23
+ }
24
+ }
25
+ /**
26
+ * GET /api/email/admin/campaigns/:id
27
+ * Get a single campaign from Plunk
28
+ */
29
+ export async function getCampaign(c) {
30
+ try {
31
+ const id = c.req.param('id');
32
+ if (!id) {
33
+ return c.json({ success: false, message: 'Campaign ID is required' }, 400);
34
+ }
35
+ const plunk = createPlunkClient(c.env);
36
+ const campaign = await plunk.getCampaign(id);
37
+ return c.json({ campaign });
38
+ }
39
+ catch (error) {
40
+ console.error('Get campaign error:', error);
41
+ return c.json({
42
+ success: false,
43
+ message: error instanceof Error ? error.message : 'Failed to fetch campaign',
44
+ }, 500);
45
+ }
46
+ }
47
+ /**
48
+ * POST /api/email/admin/campaigns
49
+ * Create a new campaign in Plunk
50
+ */
51
+ export async function createCampaign(c) {
52
+ try {
53
+ const body = await c.req.json();
54
+ if (!body.name || !body.subject || !body.body) {
55
+ return c.json({ success: false, message: 'Name, subject, and body are required' }, 400);
56
+ }
57
+ const plunk = createPlunkClient(c.env);
58
+ const result = await plunk.createCampaign({
59
+ name: body.name,
60
+ subject: body.subject,
61
+ body: body.body,
62
+ from: body.from,
63
+ style: body.style,
64
+ });
65
+ return c.json({
66
+ success: true,
67
+ campaign: {
68
+ id: result.id,
69
+ },
70
+ });
71
+ }
72
+ catch (error) {
73
+ console.error('Create campaign error:', error);
74
+ return c.json({
75
+ success: false,
76
+ message: error instanceof Error ? error.message : 'Failed to create campaign',
77
+ }, 500);
78
+ }
79
+ }
80
+ /**
81
+ * POST /api/email/admin/campaigns/:id/send
82
+ * Send a campaign to all subscribed contacts
83
+ */
84
+ export async function sendCampaign(c) {
85
+ try {
86
+ const id = c.req.param('id');
87
+ if (!id) {
88
+ return c.json({ success: false, message: 'Campaign ID is required' }, 400);
89
+ }
90
+ const plunk = createPlunkClient(c.env);
91
+ const result = await plunk.sendCampaign(id);
92
+ return c.json({
93
+ success: true,
94
+ timestamp: result.timestamp,
95
+ emails: result.emails?.length || 0,
96
+ });
97
+ }
98
+ catch (error) {
99
+ console.error('Send campaign error:', error);
100
+ return c.json({
101
+ success: false,
102
+ message: error instanceof Error ? error.message : 'Failed to send campaign',
103
+ }, 500);
104
+ }
105
+ }
106
+ /**
107
+ * POST /api/email/admin/campaigns/:id/test
108
+ * Send a test email for a campaign
109
+ */
110
+ export async function testCampaign(c) {
111
+ try {
112
+ const id = c.req.param('id');
113
+ if (!id) {
114
+ return c.json({ success: false, message: 'Campaign ID is required' }, 400);
115
+ }
116
+ const body = await c.req.json();
117
+ if (!body.email) {
118
+ return c.json({ success: false, message: 'Test email is required' }, 400);
119
+ }
120
+ // Validate email format
121
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
122
+ if (!emailRegex.test(body.email)) {
123
+ return c.json({ success: false, message: 'Invalid email format' }, 400);
124
+ }
125
+ const plunk = createPlunkClient(c.env);
126
+ await plunk.testCampaign(id, body.email);
127
+ return c.json({
128
+ success: true,
129
+ message: `Test email sent to ${body.email}`,
130
+ });
131
+ }
132
+ catch (error) {
133
+ console.error('Test campaign error:', error);
134
+ return c.json({
135
+ success: false,
136
+ message: error instanceof Error ? error.message : 'Failed to send test email',
137
+ }, 500);
138
+ }
139
+ }