@hintergrund/worker 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +45 -0
  2. package/dist/api/builder/handlers/generate.handler.d.ts +12 -0
  3. package/dist/api/builder/handlers/generate.handler.d.ts.map +1 -0
  4. package/dist/api/builder/handlers/generate.handler.js +203 -0
  5. package/dist/api/builder/handlers/template.handler.d.ts +12 -0
  6. package/dist/api/builder/handlers/template.handler.d.ts.map +1 -0
  7. package/dist/api/builder/handlers/template.handler.js +208 -0
  8. package/dist/api/builder/routes.d.ts +7 -0
  9. package/dist/api/builder/routes.d.ts.map +1 -0
  10. package/dist/api/builder/routes.js +15 -0
  11. package/dist/api/cms/handlers/assets.handler.d.ts +8 -0
  12. package/dist/api/cms/handlers/assets.handler.d.ts.map +1 -0
  13. package/dist/api/cms/handlers/assets.handler.js +299 -0
  14. package/dist/api/cms/handlers/auth.handler.d.ts +11 -0
  15. package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -0
  16. package/dist/api/cms/handlers/auth.handler.js +214 -0
  17. package/dist/api/cms/handlers/config.handler.d.ts +3 -0
  18. package/dist/api/cms/handlers/config.handler.d.ts.map +1 -0
  19. package/dist/api/cms/handlers/config.handler.js +88 -0
  20. package/dist/api/cms/handlers/content.handler.d.ts +10 -0
  21. package/dist/api/cms/handlers/content.handler.d.ts.map +1 -0
  22. package/dist/api/cms/handlers/content.handler.js +293 -0
  23. package/dist/api/cms/handlers/dashboard.handler.d.ts +6 -0
  24. package/dist/api/cms/handlers/dashboard.handler.d.ts.map +1 -0
  25. package/dist/api/cms/handlers/dashboard.handler.js +15 -0
  26. package/dist/api/cms/routes/assets.routes.d.ts +4 -0
  27. package/dist/api/cms/routes/assets.routes.d.ts.map +1 -0
  28. package/dist/api/cms/routes/assets.routes.js +13 -0
  29. package/dist/api/cms/routes/auth.routes.d.ts +4 -0
  30. package/dist/api/cms/routes/auth.routes.d.ts.map +1 -0
  31. package/dist/api/cms/routes/auth.routes.js +7 -0
  32. package/dist/api/cms/routes/content.routes.d.ts +4 -0
  33. package/dist/api/cms/routes/content.routes.d.ts.map +1 -0
  34. package/dist/api/cms/routes/content.routes.js +11 -0
  35. package/dist/api/cms/routes/index.d.ts +4 -0
  36. package/dist/api/cms/routes/index.d.ts.map +1 -0
  37. package/dist/api/cms/routes/index.js +16 -0
  38. package/dist/api/newsletter/handlers/email.handler.d.ts +7 -0
  39. package/dist/api/newsletter/handlers/email.handler.d.ts.map +1 -0
  40. package/dist/api/newsletter/handlers/email.handler.js +102 -0
  41. package/dist/api/newsletter/handlers/emails.handler.d.ts +21 -0
  42. package/dist/api/newsletter/handlers/emails.handler.d.ts.map +1 -0
  43. package/dist/api/newsletter/handlers/emails.handler.js +134 -0
  44. package/dist/api/newsletter/handlers/public.handler.d.ts +22 -0
  45. package/dist/api/newsletter/handlers/public.handler.d.ts.map +1 -0
  46. package/dist/api/newsletter/handlers/public.handler.js +242 -0
  47. package/dist/api/newsletter/handlers/send.handler.d.ts +12 -0
  48. package/dist/api/newsletter/handlers/send.handler.d.ts.map +1 -0
  49. package/dist/api/newsletter/handlers/send.handler.js +153 -0
  50. package/dist/api/newsletter/handlers/subscribers.handler.d.ts +22 -0
  51. package/dist/api/newsletter/handlers/subscribers.handler.d.ts.map +1 -0
  52. package/dist/api/newsletter/handlers/subscribers.handler.js +191 -0
  53. package/dist/api/newsletter/routes/admin.routes.d.ts +4 -0
  54. package/dist/api/newsletter/routes/admin.routes.d.ts.map +1 -0
  55. package/dist/api/newsletter/routes/admin.routes.js +21 -0
  56. package/dist/api/newsletter/routes/index.d.ts +4 -0
  57. package/dist/api/newsletter/routes/index.d.ts.map +1 -0
  58. package/dist/api/newsletter/routes/index.js +9 -0
  59. package/dist/api/newsletter/routes/public.routes.d.ts +4 -0
  60. package/dist/api/newsletter/routes/public.routes.d.ts.map +1 -0
  61. package/dist/api/newsletter/routes/public.routes.js +9 -0
  62. package/dist/api/shop/handlers/customers.handler.d.ts +17 -0
  63. package/dist/api/shop/handlers/customers.handler.d.ts.map +1 -0
  64. package/dist/api/shop/handlers/customers.handler.js +89 -0
  65. package/dist/api/shop/handlers/orders.handler.d.ts +17 -0
  66. package/dist/api/shop/handlers/orders.handler.d.ts.map +1 -0
  67. package/dist/api/shop/handlers/orders.handler.js +84 -0
  68. package/dist/api/shop/handlers/prices.handler.d.ts +17 -0
  69. package/dist/api/shop/handlers/prices.handler.d.ts.map +1 -0
  70. package/dist/api/shop/handlers/prices.handler.js +87 -0
  71. package/dist/api/shop/handlers/products.handler.d.ts +45 -0
  72. package/dist/api/shop/handlers/products.handler.d.ts.map +1 -0
  73. package/dist/api/shop/handlers/products.handler.js +243 -0
  74. package/dist/api/shop/handlers/stats.handler.d.ts +10 -0
  75. package/dist/api/shop/handlers/stats.handler.d.ts.map +1 -0
  76. package/dist/api/shop/handlers/stats.handler.js +71 -0
  77. package/dist/api/shop/routes.d.ts +7 -0
  78. package/dist/api/shop/routes.d.ts.map +1 -0
  79. package/dist/api/shop/routes.js +31 -0
  80. package/dist/cms-assets.d.ts +4 -0
  81. package/dist/cms-assets.d.ts.map +1 -0
  82. package/dist/cms-assets.js +5 -0
  83. package/dist/cms-bundle.d.ts +3 -0
  84. package/dist/cms-bundle.d.ts.map +1 -0
  85. package/dist/cms-bundle.js +4 -0
  86. package/dist/config-loader.d.ts +26 -0
  87. package/dist/config-loader.d.ts.map +1 -0
  88. package/dist/config-loader.js +98 -0
  89. package/dist/hintergrund-assets.d.ts +4 -0
  90. package/dist/hintergrund-assets.d.ts.map +1 -0
  91. package/dist/hintergrund-assets.js +9 -0
  92. package/dist/index.d.ts +35 -0
  93. package/dist/index.d.ts.map +1 -0
  94. package/dist/index.js +66 -0
  95. package/dist/jwt.d.ts +26 -0
  96. package/dist/jwt.d.ts.map +1 -0
  97. package/dist/jwt.js +102 -0
  98. package/dist/lib/auth/crypto.d.ts +23 -0
  99. package/dist/lib/auth/crypto.d.ts.map +1 -0
  100. package/dist/lib/auth/crypto.js +110 -0
  101. package/dist/lib/auth/jwt.d.ts +38 -0
  102. package/dist/lib/auth/jwt.d.ts.map +1 -0
  103. package/dist/lib/auth/jwt.js +120 -0
  104. package/dist/lib/config.d.ts +31 -0
  105. package/dist/lib/config.d.ts.map +1 -0
  106. package/dist/lib/config.js +174 -0
  107. package/dist/lib/email.d.ts +16 -0
  108. package/dist/lib/email.d.ts.map +1 -0
  109. package/dist/lib/email.js +83 -0
  110. package/dist/lib/template.d.ts +2 -0
  111. package/dist/lib/template.d.ts.map +1 -0
  112. package/dist/lib/template.js +226 -0
  113. package/dist/middleware/auth.d.ts +9 -0
  114. package/dist/middleware/auth.d.ts.map +1 -0
  115. package/dist/middleware/auth.js +93 -0
  116. package/dist/template.d.ts +2 -0
  117. package/dist/template.d.ts.map +1 -0
  118. package/dist/template.js +61 -0
  119. package/dist/utils.d.ts +23 -0
  120. package/dist/utils.d.ts.map +1 -0
  121. package/dist/utils.js +110 -0
  122. package/package.json +32 -0
package/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # @hintergrund/worker
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
12
+
13
+ ```typescript
14
+ import { createApp } from '@hintergrund/worker';
15
+
16
+ const app = createApp();
17
+
18
+ export default app;
19
+ ```
20
+
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
28
+
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
+ ```
@@ -0,0 +1,12 @@
1
+ import { Context } from 'hono';
2
+ /**
3
+ * POST /api/builder/admin/chat
4
+ * Analyze user request, return implementation plan + questions
5
+ */
6
+ export declare function chat(c: Context): Promise<Response>;
7
+ /**
8
+ * POST /api/builder/admin/implement
9
+ * Generate final code based on conversation
10
+ */
11
+ export declare function implement(c: Context): Promise<Response>;
12
+ //# sourceMappingURL=generate.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generate.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/builder/handlers/generate.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA8K/B;;;GAGG;AACH,wBAAsB,IAAI,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAgDxD;AAED;;;GAGG;AACH,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6C7D"}
@@ -0,0 +1,203 @@
1
+ import { getBuilderConfig } from '../../../lib/config';
2
+ const SYSTEM_PROMPT = `You are an AI assistant helping to build and modify a SvelteKit website. You are working with a template that includes CMS integration, newsletter signup, and shop functionality.
3
+
4
+ ## Template Structure
5
+ - src/routes/ - SvelteKit page components (+page.svelte, +layout.svelte)
6
+ - src/lib/components/ - Reusable Svelte 5 components
7
+ - src/lib/content/globals.json - Site content (name, tagline, about text, social links, newsletter text)
8
+ - src/lib/content/config.json - CMS schema definitions
9
+ - src/lib/api/newsletter.ts - Newsletter API client (subscribe, unsubscribe, confirm)
10
+ - src/lib/api/shop.ts - Shop API client (getProducts, createCheckoutSession)
11
+ - src/lib/assets/ - Static images
12
+ - static/ - Public static files
13
+
14
+ ## Svelte 5 Patterns
15
+ - Use $state() for reactive state: let count = $state(0);
16
+ - Use $derived() for computed values: const doubled = $derived(count * 2);
17
+ - Use $effect() for side effects: $effect(() => { console.log(count); });
18
+ - Use $props() for component props: let { name, value = '' } = $props();
19
+
20
+ ## Content Management
21
+ - Site content is in src/lib/content/globals.json
22
+ - Components import content: import { globals } from '$lib';
23
+ - Access content: globals.siteName, globals.siteTagline, etc.
24
+
25
+ ## API Integration
26
+ - Newsletter: import { subscribeToNewsletter } from '$lib/api/newsletter';
27
+ - Shop: import { getProducts, createCheckoutSession } from '$lib/api/shop';
28
+
29
+ ## CSS Styling
30
+ - Use scoped <style> blocks in Svelte components
31
+ - CSS custom properties are available (--color-gray-900, etc.)
32
+ - Follow existing design patterns in the codebase
33
+
34
+ ## Guidelines
35
+ 1. Follow existing code patterns and naming conventions
36
+ 2. Keep components small and focused
37
+ 3. Use semantic HTML elements
38
+ 4. Ensure responsive design
39
+ 5. Maintain accessibility (aria labels, keyboard navigation)`;
40
+ const CHAT_PROMPT = `Based on the user's request, analyze what changes need to be made to the website.
41
+
42
+ Your response must be valid JSON with this structure:
43
+ {
44
+ "plan": "A detailed implementation plan describing what will be changed and how",
45
+ "questions": ["List of clarifying questions if you need more information to implement properly"],
46
+ "affectedFiles": ["List of file paths that will be modified"]
47
+ }
48
+
49
+ Rules:
50
+ 1. If the request is clear and you have all the information needed, return an empty questions array
51
+ 2. If you need more details to implement properly, ask specific clarifying questions
52
+ 3. If there are no questions, end your plan with: "Do you have any additional changes you'd like to make, or should I implement this now?"
53
+ 4. The plan should be specific about what code changes will be made
54
+ 5. List ALL files that will need to be modified
55
+
56
+ Respond ONLY with valid JSON, no markdown code blocks.`;
57
+ const IMPLEMENT_PROMPT = `Based on the conversation history, implement all the requested changes.
58
+
59
+ Your response must be valid JSON with this structure:
60
+ {
61
+ "files": {
62
+ "path/to/file.svelte": "complete file content",
63
+ "path/to/another/file.ts": "complete file content"
64
+ },
65
+ "summary": "Brief summary of all changes made"
66
+ }
67
+
68
+ Rules:
69
+ 1. Return the COMPLETE file content for each modified file, not partial snippets
70
+ 2. Include ALL files that need to be changed based on the entire conversation
71
+ 3. Follow the existing code style and patterns
72
+ 4. Ensure the code is production-ready and error-free
73
+ 5. The summary should list what was changed in each file
74
+
75
+ Respond ONLY with valid JSON, no markdown code blocks.`;
76
+ /**
77
+ * Call Gemini API
78
+ */
79
+ async function callGemini(apiKey, systemPrompt, userPrompt, conversationHistory = []) {
80
+ // Build conversation context
81
+ const historyContext = conversationHistory
82
+ .map(msg => `${msg.role === 'user' ? 'User' : 'Assistant'}: ${msg.content}`)
83
+ .join('\n\n');
84
+ const fullPrompt = historyContext
85
+ ? `${historyContext}\n\nUser: ${userPrompt}`
86
+ : userPrompt;
87
+ const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=${apiKey}`, {
88
+ method: 'POST',
89
+ headers: {
90
+ 'Content-Type': 'application/json'
91
+ },
92
+ body: JSON.stringify({
93
+ contents: [
94
+ {
95
+ role: 'user',
96
+ parts: [{ text: `${systemPrompt}\n\n${fullPrompt}` }]
97
+ }
98
+ ],
99
+ generationConfig: {
100
+ temperature: 0.7,
101
+ maxOutputTokens: 8192
102
+ }
103
+ })
104
+ });
105
+ if (!response.ok) {
106
+ const error = await response.text();
107
+ throw new Error(`Gemini API error: ${error}`);
108
+ }
109
+ const data = await response.json();
110
+ const text = data.candidates?.[0]?.content?.parts?.[0]?.text;
111
+ if (!text) {
112
+ throw new Error('No response from Gemini');
113
+ }
114
+ return text;
115
+ }
116
+ /**
117
+ * Parse JSON from AI response, handling potential markdown code blocks
118
+ */
119
+ function parseAIResponse(text) {
120
+ // Remove markdown code blocks if present
121
+ let cleaned = text.trim();
122
+ if (cleaned.startsWith('```json')) {
123
+ cleaned = cleaned.slice(7);
124
+ }
125
+ else if (cleaned.startsWith('```')) {
126
+ cleaned = cleaned.slice(3);
127
+ }
128
+ if (cleaned.endsWith('```')) {
129
+ cleaned = cleaned.slice(0, -3);
130
+ }
131
+ cleaned = cleaned.trim();
132
+ return JSON.parse(cleaned);
133
+ }
134
+ /**
135
+ * POST /api/builder/admin/chat
136
+ * Analyze user request, return implementation plan + questions
137
+ */
138
+ export async function chat(c) {
139
+ try {
140
+ const request = await c.req.json();
141
+ const config = getBuilderConfig(c.env);
142
+ // Build file context
143
+ const fileContext = Object.entries(request.currentFiles)
144
+ .map(([path, content]) => `### ${path}\n\`\`\`\n${content}\n\`\`\``)
145
+ .join('\n\n');
146
+ const userPrompt = `${CHAT_PROMPT}
147
+
148
+ ## Current Files
149
+ ${fileContext}
150
+
151
+ ## User Request
152
+ ${request.message}`;
153
+ const aiResponse = await callGemini(config.geminiApiKey, SYSTEM_PROMPT, userPrompt, request.conversationHistory);
154
+ const parsed = parseAIResponse(aiResponse);
155
+ const response = {
156
+ success: true,
157
+ response: {
158
+ plan: parsed.plan,
159
+ questions: parsed.questions || [],
160
+ affectedFiles: parsed.affectedFiles || []
161
+ }
162
+ };
163
+ return c.json(response);
164
+ }
165
+ catch (error) {
166
+ console.error('Chat error:', error);
167
+ return c.json({ success: false, error: error.message || 'Failed to process chat' }, 500);
168
+ }
169
+ }
170
+ /**
171
+ * POST /api/builder/admin/implement
172
+ * Generate final code based on conversation
173
+ */
174
+ export async function implement(c) {
175
+ try {
176
+ const request = await c.req.json();
177
+ const config = getBuilderConfig(c.env);
178
+ // Build file context
179
+ const fileContext = Object.entries(request.currentFiles)
180
+ .map(([path, content]) => `### ${path}\n\`\`\`\n${content}\n\`\`\``)
181
+ .join('\n\n');
182
+ const userPrompt = `${IMPLEMENT_PROMPT}
183
+
184
+ ## Current Files
185
+ ${fileContext}
186
+
187
+ Please implement all the changes discussed in the conversation.`;
188
+ const aiResponse = await callGemini(config.geminiApiKey, SYSTEM_PROMPT, userPrompt, request.conversationHistory);
189
+ const parsed = parseAIResponse(aiResponse);
190
+ const response = {
191
+ success: true,
192
+ result: {
193
+ files: parsed.files || {},
194
+ summary: parsed.summary || 'Changes implemented'
195
+ }
196
+ };
197
+ return c.json(response);
198
+ }
199
+ catch (error) {
200
+ console.error('Implement error:', error);
201
+ return c.json({ success: false, error: error.message || 'Failed to implement changes' }, 500);
202
+ }
203
+ }
@@ -0,0 +1,12 @@
1
+ import { Context } from 'hono';
2
+ /**
3
+ * GET /api/builder/admin/template
4
+ * Fetch all template files from the GitHub repository
5
+ */
6
+ export declare function getTemplate(c: Context): Promise<Response>;
7
+ /**
8
+ * PUT /api/builder/admin/template
9
+ * Save modified files to GitHub (commit)
10
+ */
11
+ export declare function updateTemplate(c: Context): Promise<Response>;
12
+ //# sourceMappingURL=template.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/builder/handlers/template.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA+G/B;;;GAGG;AACH,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwC/D;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA4FlE"}
@@ -0,0 +1,208 @@
1
+ import { Octokit } from '@octokit/rest';
2
+ import { getBuilderConfig } from '../../../lib/config';
3
+ // Files to include from the template repo
4
+ const INCLUDED_PATHS = [
5
+ 'src/',
6
+ 'static/',
7
+ 'svelte.config.js',
8
+ 'vite.config.ts',
9
+ 'tsconfig.json',
10
+ 'package.json'
11
+ ];
12
+ // Files to exclude
13
+ const EXCLUDED_PATHS = [
14
+ 'node_modules/',
15
+ '.svelte-kit/',
16
+ 'build/',
17
+ '.git/'
18
+ ];
19
+ function shouldIncludeFile(path) {
20
+ // Check exclusions first
21
+ for (const excluded of EXCLUDED_PATHS) {
22
+ if (path.startsWith(excluded) || path.includes('/' + excluded)) {
23
+ return false;
24
+ }
25
+ }
26
+ // Check if it matches any included path
27
+ for (const included of INCLUDED_PATHS) {
28
+ if (path.startsWith(included) || path === included.replace('/', '')) {
29
+ return true;
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+ /**
35
+ * Recursively fetch all files from a GitHub directory
36
+ */
37
+ async function fetchDirectoryContents(octokit, owner, repo, path, branch) {
38
+ const files = [];
39
+ try {
40
+ const response = await octokit.rest.repos.getContent({
41
+ owner,
42
+ repo,
43
+ path,
44
+ ref: branch
45
+ });
46
+ if (Array.isArray(response.data)) {
47
+ // It's a directory
48
+ for (const item of response.data) {
49
+ if (!shouldIncludeFile(item.path)) {
50
+ continue;
51
+ }
52
+ if (item.type === 'dir') {
53
+ const subFiles = await fetchDirectoryContents(octokit, owner, repo, item.path, branch);
54
+ files.push(...subFiles);
55
+ }
56
+ else if (item.type === 'file') {
57
+ // Fetch file content
58
+ const fileResponse = await octokit.rest.repos.getContent({
59
+ owner,
60
+ repo,
61
+ path: item.path,
62
+ ref: branch
63
+ });
64
+ if (!Array.isArray(fileResponse.data) && 'content' in fileResponse.data) {
65
+ files.push({
66
+ path: item.path,
67
+ content: atob(fileResponse.data.content),
68
+ sha: fileResponse.data.sha
69
+ });
70
+ }
71
+ }
72
+ }
73
+ }
74
+ else if ('content' in response.data) {
75
+ // It's a single file
76
+ files.push({
77
+ path: response.data.path,
78
+ content: atob(response.data.content),
79
+ sha: response.data.sha
80
+ });
81
+ }
82
+ }
83
+ catch (error) {
84
+ if (error.status !== 404) {
85
+ throw error;
86
+ }
87
+ }
88
+ return files;
89
+ }
90
+ /**
91
+ * GET /api/builder/admin/template
92
+ * Fetch all template files from the GitHub repository
93
+ */
94
+ export async function getTemplate(c) {
95
+ try {
96
+ const config = getBuilderConfig(c.env);
97
+ const [owner, repo] = config.templateRepo.split('/');
98
+ const octokit = new Octokit({
99
+ auth: config.gitToken
100
+ });
101
+ // Get current commit SHA
102
+ const ref = await octokit.rest.git.getRef({
103
+ owner,
104
+ repo,
105
+ ref: `heads/${config.gitBranch}`
106
+ });
107
+ const commitSha = ref.data.object.sha;
108
+ // Fetch all files from included paths
109
+ const allFiles = [];
110
+ for (const includePath of INCLUDED_PATHS) {
111
+ const pathToFetch = includePath.endsWith('/') ? includePath.slice(0, -1) : includePath;
112
+ const files = await fetchDirectoryContents(octokit, owner, repo, pathToFetch, config.gitBranch);
113
+ allFiles.push(...files);
114
+ }
115
+ const response = {
116
+ files: allFiles,
117
+ commitSha,
118
+ templateRepo: config.templateRepo
119
+ };
120
+ return c.json(response);
121
+ }
122
+ catch (error) {
123
+ console.error('Failed to fetch template:', error);
124
+ return c.json({ success: false, error: error.message || 'Failed to fetch template' }, 500);
125
+ }
126
+ }
127
+ /**
128
+ * PUT /api/builder/admin/template
129
+ * Save modified files to GitHub (commit)
130
+ */
131
+ export async function updateTemplate(c) {
132
+ try {
133
+ const request = await c.req.json();
134
+ const config = getBuilderConfig(c.env);
135
+ const [owner, repo] = config.templateRepo.split('/');
136
+ const octokit = new Octokit({
137
+ auth: config.gitToken
138
+ });
139
+ // Get current commit SHA
140
+ const ref = await octokit.rest.git.getRef({
141
+ owner,
142
+ repo,
143
+ ref: `heads/${config.gitBranch}`
144
+ });
145
+ const currentCommitSha = ref.data.object.sha;
146
+ // Check for conflicts
147
+ if (request.commitSha !== currentCommitSha) {
148
+ const conflictResponse = {
149
+ conflict: true,
150
+ currentCommitSha,
151
+ message: 'Template has been modified. Please sync and try again.'
152
+ };
153
+ return c.json(conflictResponse, 409);
154
+ }
155
+ // Get the current commit
156
+ const commit = await octokit.rest.git.getCommit({
157
+ owner,
158
+ repo,
159
+ commit_sha: currentCommitSha
160
+ });
161
+ // Create blobs for each modified file
162
+ const blobs = await Promise.all(Object.entries(request.files).map(async ([path, content]) => {
163
+ const blob = await octokit.rest.git.createBlob({
164
+ owner,
165
+ repo,
166
+ content: content,
167
+ encoding: 'utf-8'
168
+ });
169
+ return {
170
+ path,
171
+ mode: '100644',
172
+ type: 'blob',
173
+ sha: blob.data.sha
174
+ };
175
+ }));
176
+ // Create new tree
177
+ const newTree = await octokit.rest.git.createTree({
178
+ owner,
179
+ repo,
180
+ tree: blobs,
181
+ base_tree: commit.data.tree.sha
182
+ });
183
+ // Create commit
184
+ const newCommit = await octokit.rest.git.createCommit({
185
+ owner,
186
+ repo,
187
+ message: 'Update template via Builder',
188
+ tree: newTree.data.sha,
189
+ parents: [commit.data.sha]
190
+ });
191
+ // Update branch reference
192
+ await octokit.rest.git.updateRef({
193
+ owner,
194
+ repo,
195
+ ref: `heads/${config.gitBranch}`,
196
+ sha: newCommit.data.sha
197
+ });
198
+ const response = {
199
+ success: true,
200
+ newCommitSha: newCommit.data.sha
201
+ };
202
+ return c.json(response);
203
+ }
204
+ catch (error) {
205
+ console.error('Failed to update template:', error);
206
+ return c.json({ success: false, error: error.message || 'Failed to update template' }, 500);
207
+ }
208
+ }
@@ -0,0 +1,7 @@
1
+ import { Hono } from 'hono';
2
+ import type { Bindings } from '../../index';
3
+ declare const builderRoutes: Hono<{
4
+ Bindings: Bindings;
5
+ }, import("hono/types").BlankSchema, "/">;
6
+ export default builderRoutes;
7
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/api/builder/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAO5C,QAAA,MAAM,aAAa;cAAwB,QAAQ;yCAAK,CAAC;AAazD,eAAe,aAAa,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { Hono } from 'hono';
2
+ import { authMiddleware } from '../../middleware/auth';
3
+ // Import handlers
4
+ import { getTemplate, updateTemplate } from './handlers/template.handler';
5
+ import { chat, implement } from './handlers/generate.handler';
6
+ const builderRoutes = new Hono();
7
+ // Apply auth middleware to all builder routes
8
+ builderRoutes.use('/admin/*', authMiddleware);
9
+ // Template routes
10
+ builderRoutes.get('/admin/template', getTemplate);
11
+ builderRoutes.put('/admin/template', updateTemplate);
12
+ // AI routes
13
+ builderRoutes.post('/admin/chat', chat);
14
+ builderRoutes.post('/admin/implement', implement);
15
+ export default builderRoutes;
@@ -0,0 +1,8 @@
1
+ import { Context } from 'hono';
2
+ export declare function listAssets(c: Context): Promise<Response>;
3
+ export declare function uploadAsset(c: Context): Promise<Response>;
4
+ export declare function deleteAsset(c: Context): Promise<Response>;
5
+ export declare function getAssetByPath(c: Context): Promise<Response>;
6
+ export declare function syncAssets(c: Context): Promise<Response>;
7
+ export declare function syncAssetsMock(_c: Context): Promise<Response>;
8
+ //# sourceMappingURL=assets.handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assets.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/cms/handlers/assets.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA+B/B,wBAAsB,UAAU,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA+B9D;AAED,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA+B/D;AAED,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA+C/D;AAED,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsClE;AAED,wBAAsB,UAAU,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAuG9D;AAED,wBAAsB,cAAc,CAAC,EAAE,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqDnE"}