@nodestackapp/server 2.0.0 → 2.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.
- package/README.md +4 -3
- package/dist/NodeStack.d.ts +9 -0
- package/dist/NodeStack.d.ts.map +1 -1
- package/dist/NodeStack.js +24 -3
- package/dist/NodeStack.js.map +1 -1
- package/dist/admin/AdminUIBundler.d.ts.map +1 -1
- package/dist/admin/AdminUIBundler.js +9 -5
- package/dist/admin/AdminUIBundler.js.map +1 -1
- package/dist/admin/ui/css/codemirror.css +98 -0
- package/dist/admin/ui/css/main.css +2309 -2189
- package/dist/admin/ui/index.html +8331 -5295
- package/dist/admin/ui/js/api.js +44 -14
- package/dist/admin/ui/js/app.js +480 -254
- package/dist/admin/ui/js/apps.js +29 -14
- package/dist/admin/ui/js/codemirror.js +15 -0
- package/dist/admin/ui/js/collections.js +38 -9
- package/dist/admin/ui/js/command-palette.js +12 -1
- package/dist/admin/ui/js/functions-tester.js +432 -0
- package/dist/admin/ui/js/functions-workbench.js +1038 -0
- package/dist/admin/ui/js/functions.js +765 -0
- package/dist/admin/ui/js/modals.js +6 -2
- package/dist/admin/ui/js/plugin-tester.js +562 -559
- package/dist/admin/ui/js/plugins.js +198 -77
- package/dist/admin/ui/js/records.js +89 -54
- package/dist/admin/ui/js/schema.js +23 -9
- package/dist/admin/ui/js/views.js +82 -34
- package/dist/admin/ui/js/webhooks.js +1111 -1104
- package/dist/apps/AppScope.d.ts +4 -0
- package/dist/apps/AppScope.d.ts.map +1 -1
- package/dist/apps/AppScope.js +33 -1
- package/dist/apps/AppScope.js.map +1 -1
- package/dist/auth/ApiKeyService.d.ts +91 -0
- package/dist/auth/ApiKeyService.d.ts.map +1 -0
- package/dist/auth/ApiKeyService.js +414 -0
- package/dist/auth/ApiKeyService.js.map +1 -0
- package/dist/auth/AuthService.d.ts +33 -1
- package/dist/auth/AuthService.d.ts.map +1 -1
- package/dist/auth/AuthService.js +219 -1
- package/dist/auth/AuthService.js.map +1 -1
- package/dist/auth/oauth/AppleProvider.d.ts +23 -0
- package/dist/auth/oauth/AppleProvider.d.ts.map +1 -0
- package/dist/auth/oauth/AppleProvider.js +161 -0
- package/dist/auth/oauth/AppleProvider.js.map +1 -0
- package/dist/auth/oauth/BaseOAuthProvider.d.ts +18 -0
- package/dist/auth/oauth/BaseOAuthProvider.d.ts.map +1 -0
- package/dist/auth/oauth/BaseOAuthProvider.js +79 -0
- package/dist/auth/oauth/BaseOAuthProvider.js.map +1 -0
- package/dist/auth/oauth/DiscordProvider.d.ts +11 -0
- package/dist/auth/oauth/DiscordProvider.d.ts.map +1 -0
- package/dist/auth/oauth/DiscordProvider.js +47 -0
- package/dist/auth/oauth/DiscordProvider.js.map +1 -0
- package/dist/auth/oauth/GitHubProvider.d.ts +13 -0
- package/dist/auth/oauth/GitHubProvider.d.ts.map +1 -0
- package/dist/auth/oauth/GitHubProvider.js +90 -0
- package/dist/auth/oauth/GitHubProvider.js.map +1 -0
- package/dist/auth/oauth/GoogleProvider.d.ts +11 -0
- package/dist/auth/oauth/GoogleProvider.d.ts.map +1 -0
- package/dist/auth/oauth/GoogleProvider.js +43 -0
- package/dist/auth/oauth/GoogleProvider.js.map +1 -0
- package/dist/auth/oauth/MicrosoftProvider.d.ts +11 -0
- package/dist/auth/oauth/MicrosoftProvider.d.ts.map +1 -0
- package/dist/auth/oauth/MicrosoftProvider.js +83 -0
- package/dist/auth/oauth/MicrosoftProvider.js.map +1 -0
- package/dist/auth/oauth/OAuthProviderRegistry.d.ts +32 -0
- package/dist/auth/oauth/OAuthProviderRegistry.d.ts.map +1 -0
- package/dist/auth/oauth/OAuthProviderRegistry.js +232 -0
- package/dist/auth/oauth/OAuthProviderRegistry.js.map +1 -0
- package/dist/auth/oauth/types.d.ts +63 -0
- package/dist/auth/oauth/types.d.ts.map +1 -0
- package/dist/auth/oauth/types.js +3 -0
- package/dist/auth/oauth/types.js.map +1 -0
- package/dist/cli/cli.js +10 -10
- package/dist/cli/cli.js.map +1 -1
- package/dist/core/container/Tokens.d.ts +2 -0
- package/dist/core/container/Tokens.d.ts.map +1 -1
- package/dist/core/container/Tokens.js +2 -0
- package/dist/core/container/Tokens.js.map +1 -1
- package/dist/core/plugins/PluginManager.d.ts.map +1 -1
- package/dist/core/plugins/PluginManager.js +73 -19
- package/dist/core/plugins/PluginManager.js.map +1 -1
- package/dist/database/migrations/SystemMigrations.d.ts.map +1 -1
- package/dist/database/migrations/SystemMigrations.js +40 -0
- package/dist/database/migrations/SystemMigrations.js.map +1 -1
- package/dist/functions/FunctionService.d.ts +80 -0
- package/dist/functions/FunctionService.d.ts.map +1 -0
- package/dist/functions/FunctionService.js +610 -0
- package/dist/functions/FunctionService.js.map +1 -0
- package/dist/functions/runtime/IFunctionRuntime.d.ts +23 -0
- package/dist/functions/runtime/IFunctionRuntime.d.ts.map +1 -0
- package/dist/functions/runtime/IFunctionRuntime.js +3 -0
- package/dist/functions/runtime/IFunctionRuntime.js.map +1 -0
- package/dist/functions/runtime/QuickJsWasmRuntime.d.ts +21 -0
- package/dist/functions/runtime/QuickJsWasmRuntime.d.ts.map +1 -0
- package/dist/functions/runtime/QuickJsWasmRuntime.js +418 -0
- package/dist/functions/runtime/QuickJsWasmRuntime.js.map +1 -0
- package/dist/functions/runtime/SandboxedRunner.d.ts +31 -0
- package/dist/functions/runtime/SandboxedRunner.d.ts.map +1 -0
- package/dist/functions/runtime/SandboxedRunner.js +61 -0
- package/dist/functions/runtime/SandboxedRunner.js.map +1 -0
- package/dist/functions/security/SsrfGuard.d.ts +41 -0
- package/dist/functions/security/SsrfGuard.d.ts.map +1 -0
- package/dist/functions/security/SsrfGuard.js +470 -0
- package/dist/functions/security/SsrfGuard.js.map +1 -0
- package/dist/functions/types.d.ts +109 -0
- package/dist/functions/types.d.ts.map +1 -0
- package/dist/functions/types.js +3 -0
- package/dist/functions/types.js.map +1 -0
- package/dist/http/HttpServer.d.ts +7 -1
- package/dist/http/HttpServer.d.ts.map +1 -1
- package/dist/http/HttpServer.js +66 -1
- package/dist/http/HttpServer.js.map +1 -1
- package/dist/http/controllers/ApiKeyController.d.ts +31 -0
- package/dist/http/controllers/ApiKeyController.d.ts.map +1 -0
- package/dist/http/controllers/ApiKeyController.js +52 -0
- package/dist/http/controllers/ApiKeyController.js.map +1 -0
- package/dist/http/controllers/AuthController.d.ts +29 -1
- package/dist/http/controllers/AuthController.d.ts.map +1 -1
- package/dist/http/controllers/AuthController.js +42 -1
- package/dist/http/controllers/AuthController.js.map +1 -1
- package/dist/http/controllers/FunctionController.d.ts +64 -0
- package/dist/http/controllers/FunctionController.d.ts.map +1 -0
- package/dist/http/controllers/FunctionController.js +202 -0
- package/dist/http/controllers/FunctionController.js.map +1 -0
- package/dist/http/controllers/RecordController.d.ts.map +1 -1
- package/dist/http/controllers/RecordController.js +4 -0
- package/dist/http/controllers/RecordController.js.map +1 -1
- package/dist/http/middleware/AuthMiddleware.d.ts +6 -1
- package/dist/http/middleware/AuthMiddleware.d.ts.map +1 -1
- package/dist/http/middleware/AuthMiddleware.js +79 -8
- package/dist/http/middleware/AuthMiddleware.js.map +1 -1
- package/dist/index.d.ts +11 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +22 -3
- package/dist/index.js.map +1 -1
- package/dist/plugins/chat-notifications.d.ts +51 -0
- package/dist/plugins/chat-notifications.d.ts.map +1 -0
- package/dist/plugins/chat-notifications.js +545 -0
- package/dist/plugins/chat-notifications.js.map +1 -0
- package/dist/plugins/index.d.ts +1 -1
- package/dist/plugins/index.d.ts.map +1 -1
- package/dist/plugins/index.js +1 -1
- package/dist/plugins/index.js.map +1 -1
- package/dist/plugins/webhooks.d.ts +5 -34
- package/dist/plugins/webhooks.d.ts.map +1 -1
- package/dist/plugins/webhooks.js +11 -412
- package/dist/plugins/webhooks.js.map +1 -1
- package/dist/records/MockDataService.d.ts.map +1 -1
- package/dist/records/MockDataService.js +3 -0
- package/dist/records/MockDataService.js.map +1 -1
- package/dist/records/RecordService.d.ts.map +1 -1
- package/dist/records/RecordService.js +39 -30
- package/dist/records/RecordService.js.map +1 -1
- package/dist/records/RecordValidator.d.ts +6 -0
- package/dist/records/RecordValidator.d.ts.map +1 -0
- package/dist/records/RecordValidator.js +100 -0
- package/dist/records/RecordValidator.js.map +1 -0
- package/package.json +89 -88
|
@@ -0,0 +1,1038 @@
|
|
|
1
|
+
// Serverless Functions Dedicated Workbench & Code Editor Module
|
|
2
|
+
// Companion module for NodeStack Admin UI Functions
|
|
3
|
+
|
|
4
|
+
// ==========================================
|
|
5
|
+
// 1. Context API (ctx) Documentation & Snippets
|
|
6
|
+
// ==========================================
|
|
7
|
+
|
|
8
|
+
const CTX_DOCS = [
|
|
9
|
+
// HTTP Request (ctx.request)
|
|
10
|
+
{
|
|
11
|
+
name: 'ctx.request.body',
|
|
12
|
+
type: 'any',
|
|
13
|
+
cat: 'request',
|
|
14
|
+
desc: 'Parsed JSON payload sent in HTTP POST/PATCH invocation',
|
|
15
|
+
snippet: 'const body = ctx.request?.body || {};\n'
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
name: 'ctx.request.query',
|
|
19
|
+
type: 'Record<string, any>',
|
|
20
|
+
cat: 'request',
|
|
21
|
+
desc: 'URL query string parameters (e.g. ?limit=10&status=active)',
|
|
22
|
+
snippet: 'const { limit, status } = ctx.request?.query || {};\n'
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
name: 'ctx.request.auth',
|
|
26
|
+
type: '{ id, role, email } | null',
|
|
27
|
+
cat: 'request',
|
|
28
|
+
desc: 'Authenticated caller identity, or null if public invocation',
|
|
29
|
+
snippet: 'if (!ctx.request?.auth) return { status: 401, body: { error: "Unauthorized" } };\n'
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
name: 'ctx.request.headers',
|
|
33
|
+
type: 'Record<string, string>',
|
|
34
|
+
cat: 'request',
|
|
35
|
+
desc: 'HTTP request headers map (lowercase header keys)',
|
|
36
|
+
snippet: 'const authHeader = ctx.request?.headers["authorization"];\n'
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
name: 'ctx.request.method',
|
|
40
|
+
type: "'GET' | 'POST' | 'PATCH' | 'DELETE'",
|
|
41
|
+
cat: 'request',
|
|
42
|
+
desc: 'HTTP method used to invoke this function',
|
|
43
|
+
snippet: 'const method = ctx.request?.method;\n'
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
// DB Lifecycle Event (ctx.event)
|
|
47
|
+
{
|
|
48
|
+
name: 'ctx.event.record',
|
|
49
|
+
type: 'Record<string, any>',
|
|
50
|
+
cat: 'event',
|
|
51
|
+
desc: 'Target database record being mutated during collection lifecycle hook',
|
|
52
|
+
snippet: 'const record = ctx.event?.record;\n'
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
name: 'ctx.event.collection',
|
|
56
|
+
type: 'string',
|
|
57
|
+
cat: 'event',
|
|
58
|
+
desc: 'Target collection name triggering this lifecycle event',
|
|
59
|
+
snippet: 'const collection = ctx.event?.collection;\n'
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: 'ctx.event.action',
|
|
63
|
+
type: "'create' | 'update' | 'delete'",
|
|
64
|
+
cat: 'event',
|
|
65
|
+
desc: 'Collection mutation action triggering this hook',
|
|
66
|
+
snippet: 'const action = ctx.event?.action;\n'
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: 'ctx.event.isBefore',
|
|
70
|
+
type: 'boolean',
|
|
71
|
+
cat: 'event',
|
|
72
|
+
desc: 'true for before-write hooks (can validate or cancel write), false for after-write',
|
|
73
|
+
snippet: 'if (ctx.event?.isBefore && !isValid) return { status: 400, body: { cancel: true, reason: "Validation failed" } };\n'
|
|
74
|
+
},
|
|
75
|
+
|
|
76
|
+
// Database CRUD (ctx.records)
|
|
77
|
+
{
|
|
78
|
+
name: 'ctx.records.get(col, id)',
|
|
79
|
+
type: 'Promise<Record>',
|
|
80
|
+
cat: 'records',
|
|
81
|
+
desc: 'Fetch a single record by collection name and record ID',
|
|
82
|
+
snippet: 'const item = await ctx.records.get("products", id);\n'
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: 'ctx.records.list(col, opts)',
|
|
86
|
+
type: 'Promise<{ items, totalItems }>',
|
|
87
|
+
cat: 'records',
|
|
88
|
+
desc: 'Query records with filter, sort, page, and perPage options',
|
|
89
|
+
snippet: 'const { items, totalItems } = await ctx.records.list("orders", { filter: "status = \'paid\'", perPage: 20 });\n'
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
name: 'ctx.records.create(col, data)',
|
|
93
|
+
type: 'Promise<Record>',
|
|
94
|
+
cat: 'records',
|
|
95
|
+
desc: 'Create and insert a new record into target collection',
|
|
96
|
+
snippet: 'const newRec = await ctx.records.create("audit_events", { event: "checkout", timestamp: new Date().toISOString() });\n'
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
name: 'ctx.records.update(col, id, data)',
|
|
100
|
+
type: 'Promise<Record>',
|
|
101
|
+
cat: 'records',
|
|
102
|
+
desc: 'Update fields on an existing database record',
|
|
103
|
+
snippet: 'await ctx.records.update("products", productId, { inStock: false });\n'
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
name: 'ctx.records.delete(col, id)',
|
|
107
|
+
type: 'Promise<boolean>',
|
|
108
|
+
cat: 'records',
|
|
109
|
+
desc: 'Delete a record from database by collection name and ID',
|
|
110
|
+
snippet: 'await ctx.records.delete("temp_tokens", tokenId);\n'
|
|
111
|
+
},
|
|
112
|
+
|
|
113
|
+
// Outbound Network, Secrets & Logging
|
|
114
|
+
{
|
|
115
|
+
name: 'ctx.fetch(url, options)',
|
|
116
|
+
type: 'Promise<{ ok, status, json(), text() }>',
|
|
117
|
+
cat: 'utils',
|
|
118
|
+
desc: 'SSRF-guarded outbound HTTP request to third-party APIs',
|
|
119
|
+
snippet: 'const res = await ctx.fetch("https://api.example.com/data", { method: "POST" });\nconst data = await res.json();\n'
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
name: 'ctx.env',
|
|
123
|
+
type: 'Record<string, string>',
|
|
124
|
+
cat: 'utils',
|
|
125
|
+
desc: 'Environment variables and secrets defined in the JSON configuration below',
|
|
126
|
+
snippet: 'const secretKey = ctx.env.MY_API_KEY;\n'
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
name: 'ctx.log(...args)',
|
|
130
|
+
type: '(...args: any[]) => void',
|
|
131
|
+
cat: 'utils',
|
|
132
|
+
desc: 'Structured execution logging captured in the function Execution Logs tab',
|
|
133
|
+
snippet: 'ctx.log("Processing execution step", { step: 1, time: Date.now() });\n'
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
name: 'ctx.app',
|
|
137
|
+
type: '{ id, slug, name }',
|
|
138
|
+
cat: 'utils',
|
|
139
|
+
desc: 'Current tenant application identification and slug',
|
|
140
|
+
snippet: 'const { id, slug } = ctx.app;\n'
|
|
141
|
+
}
|
|
142
|
+
];
|
|
143
|
+
|
|
144
|
+
function renderCtxItemsHtml(activeCategory = 'all') {
|
|
145
|
+
return CTX_DOCS.map(item => {
|
|
146
|
+
const isVisible = activeCategory === 'all' || item.cat === activeCategory;
|
|
147
|
+
const jsSnippetArg = JSON.stringify(item.snippet).replace(/"/g, '"');
|
|
148
|
+
return `
|
|
149
|
+
<div class="ctx-item" data-cat="${item.cat}" style="display: ${isVisible ? 'flex' : 'none'}; flex-direction: column; gap: 4px; padding: 7px 10px; border-radius: 6px; background: var(--bg-card); border: 1px solid var(--border-subtle); font-size: 11.5px;">
|
|
150
|
+
<div style="display: flex; align-items: center; justify-content: space-between; gap: 6px;">
|
|
151
|
+
<div style="display: flex; align-items: center; gap: 6px; overflow: hidden;">
|
|
152
|
+
<code style="color: var(--accent-primary); font-weight: 600; font-size: 12px; white-space: nowrap;">${escapeHtml(item.name)}</code>
|
|
153
|
+
<span style="font-size: 10px; color: var(--text-muted); padding: 1px 5px; background: var(--bg-input); border-radius: 3px; border: 1px solid var(--border-subtle); white-space: nowrap;">${escapeHtml(item.type)}</span>
|
|
154
|
+
</div>
|
|
155
|
+
<button type="button" class="btn btn-secondary btn-sm" onclick="insertFunctionSnippet(${jsSnippetArg})" style="font-size: 10px; padding: 2px 7px; flex-shrink: 0;" title="Click to insert snippet into code editor">
|
|
156
|
+
+ Insert
|
|
157
|
+
</button>
|
|
158
|
+
</div>
|
|
159
|
+
<div style="color: var(--text-muted); font-size: 11px; line-height: 1.35;">
|
|
160
|
+
${escapeHtml(item.desc)}
|
|
161
|
+
</div>
|
|
162
|
+
</div>
|
|
163
|
+
`;
|
|
164
|
+
}).join('');
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function insertFunctionSnippet(snippet) {
|
|
168
|
+
if (functionsState.cmEditor) {
|
|
169
|
+
functionsState.cmEditor.replaceSelection(snippet);
|
|
170
|
+
functionsState.cmEditor.save();
|
|
171
|
+
functionsState.cmEditor.focus();
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const textarea = document.getElementById('fn-editor-code');
|
|
175
|
+
if (!textarea) return;
|
|
176
|
+
|
|
177
|
+
const start = textarea.selectionStart;
|
|
178
|
+
const end = textarea.selectionEnd;
|
|
179
|
+
const val = textarea.value;
|
|
180
|
+
|
|
181
|
+
if (start !== undefined && end !== undefined && start >= 0) {
|
|
182
|
+
textarea.value = val.substring(0, start) + snippet + val.substring(end);
|
|
183
|
+
textarea.selectionStart = textarea.selectionEnd = start + snippet.length;
|
|
184
|
+
} else {
|
|
185
|
+
textarea.value += '\n' + snippet;
|
|
186
|
+
}
|
|
187
|
+
textarea.focus();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function filterCtxCategory(category) {
|
|
191
|
+
const buttons = document.querySelectorAll('.ctx-cat-btn');
|
|
192
|
+
buttons.forEach(btn => {
|
|
193
|
+
const isTarget = btn.getAttribute('data-cat') === category;
|
|
194
|
+
if (isTarget) {
|
|
195
|
+
btn.classList.add('active');
|
|
196
|
+
btn.style.background = 'var(--accent-primary)';
|
|
197
|
+
btn.style.color = '#fff';
|
|
198
|
+
} else {
|
|
199
|
+
btn.classList.remove('active');
|
|
200
|
+
btn.style.background = 'var(--bg-card)';
|
|
201
|
+
btn.style.color = 'var(--text-muted)';
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
const items = document.querySelectorAll('.ctx-item');
|
|
206
|
+
items.forEach(item => {
|
|
207
|
+
const cat = item.getAttribute('data-cat');
|
|
208
|
+
item.style.display = (category === 'all' || cat === category) ? 'flex' : 'none';
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function filterCtxSearch(query) {
|
|
213
|
+
const q = (query || '').toLowerCase().trim();
|
|
214
|
+
const items = document.querySelectorAll('.ctx-item');
|
|
215
|
+
items.forEach(item => {
|
|
216
|
+
const text = item.textContent.toLowerCase();
|
|
217
|
+
item.style.display = (!q || text.includes(q)) ? 'flex' : 'none';
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function applyStarterRecipe(key) {
|
|
222
|
+
if (!key || !STARTER_RECIPES[key]) return;
|
|
223
|
+
if (functionsState.cmEditor) {
|
|
224
|
+
functionsState.cmEditor.setValue(STARTER_RECIPES[key]);
|
|
225
|
+
functionsState.cmEditor.save();
|
|
226
|
+
functionsState.cmEditor.focus();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const area = document.getElementById('fn-editor-code');
|
|
230
|
+
if (area) {
|
|
231
|
+
area.value = STARTER_RECIPES[key];
|
|
232
|
+
area.focus();
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function toggleWorkbenchCtxRef(forceState) {
|
|
237
|
+
if (typeof forceState === 'boolean') {
|
|
238
|
+
functionsState.isCtxRefExpanded = forceState;
|
|
239
|
+
} else {
|
|
240
|
+
functionsState.isCtxRefExpanded = !functionsState.isCtxRefExpanded;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const header = document.getElementById('workbench-ctx-header');
|
|
244
|
+
const content = document.getElementById('workbench-ctx-content');
|
|
245
|
+
const btn = document.getElementById('btn-toggle-workbench-ctx');
|
|
246
|
+
const toolbarBtn = document.getElementById('btn-toolbar-toggle-ctx');
|
|
247
|
+
|
|
248
|
+
if (header) {
|
|
249
|
+
header.style.borderBottom = functionsState.isCtxRefExpanded ? '1px solid var(--border-subtle)' : 'none';
|
|
250
|
+
}
|
|
251
|
+
if (content) {
|
|
252
|
+
content.style.display = functionsState.isCtxRefExpanded ? 'flex' : 'none';
|
|
253
|
+
}
|
|
254
|
+
if (btn) {
|
|
255
|
+
btn.textContent = functionsState.isCtxRefExpanded ? 'Hide Reference ▴' : 'Show Reference ▾';
|
|
256
|
+
}
|
|
257
|
+
if (toolbarBtn) {
|
|
258
|
+
toolbarBtn.style.background = functionsState.isCtxRefExpanded ? 'var(--accent-primary)' : 'var(--bg-card-hover)';
|
|
259
|
+
toolbarBtn.style.color = functionsState.isCtxRefExpanded ? '#fff' : 'var(--text-main)';
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ==========================================
|
|
264
|
+
// 2. CodeMirror Integration & Themes
|
|
265
|
+
// ==========================================
|
|
266
|
+
|
|
267
|
+
function getCodeMirrorTheme() {
|
|
268
|
+
if (typeof ThemeManager !== 'undefined' && typeof ThemeManager.getEffectiveTheme === 'function') {
|
|
269
|
+
return ThemeManager.getEffectiveTheme() === 'light' ? 'eclipse' : 'dracula';
|
|
270
|
+
}
|
|
271
|
+
if (typeof document !== 'undefined' && document.documentElement) {
|
|
272
|
+
return document.documentElement.classList.contains('light') ? 'eclipse' : 'dracula';
|
|
273
|
+
}
|
|
274
|
+
return 'dracula';
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function initFunctionCodeMirror() {
|
|
278
|
+
if (typeof CodeMirror === 'undefined') return;
|
|
279
|
+
const codeArea = document.getElementById('fn-editor-code');
|
|
280
|
+
if (!codeArea) return;
|
|
281
|
+
|
|
282
|
+
if (functionsState.cmEditor) {
|
|
283
|
+
try {
|
|
284
|
+
functionsState.cmEditor.toTextArea();
|
|
285
|
+
} catch (_) {}
|
|
286
|
+
functionsState.cmEditor = null;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
try {
|
|
290
|
+
functionsState.cmEditor = CodeMirror.fromTextArea(codeArea, {
|
|
291
|
+
mode: { name: 'javascript', typescript: true },
|
|
292
|
+
theme: getCodeMirrorTheme(),
|
|
293
|
+
lineNumbers: true,
|
|
294
|
+
matchBrackets: true,
|
|
295
|
+
autoCloseBrackets: true,
|
|
296
|
+
tabSize: 2,
|
|
297
|
+
indentWithTabs: false,
|
|
298
|
+
lineWrapping: true,
|
|
299
|
+
extraKeys: {
|
|
300
|
+
'Tab': function(cm) {
|
|
301
|
+
cm.replaceSelection(' ');
|
|
302
|
+
},
|
|
303
|
+
'Ctrl-S': function() {
|
|
304
|
+
saveFunctionEditor();
|
|
305
|
+
},
|
|
306
|
+
'Cmd-S': function() {
|
|
307
|
+
saveFunctionEditor();
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
functionsState.cmEditor.on('change', () => {
|
|
313
|
+
functionsState.cmEditor.save();
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
setTimeout(() => {
|
|
317
|
+
functionsState.cmEditor?.refresh();
|
|
318
|
+
}, 50);
|
|
319
|
+
} catch (err) {
|
|
320
|
+
console.warn('CodeMirror initialization skipped or failed:', err);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (typeof window !== 'undefined') {
|
|
325
|
+
window.addEventListener('nodestack-theme-changed', (e) => {
|
|
326
|
+
if (functionsState.cmEditor) {
|
|
327
|
+
const isLight = (e.detail && e.detail.effective === 'light') || getCodeMirrorTheme() === 'eclipse';
|
|
328
|
+
functionsState.cmEditor.setOption('theme', isLight ? 'eclipse' : 'dracula');
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ==========================================
|
|
334
|
+
// 3. Workbench Routing & Navigation
|
|
335
|
+
// ==========================================
|
|
336
|
+
|
|
337
|
+
function openCreateFunctionPage() {
|
|
338
|
+
openFunctionEditor('new', true, 'code');
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function openFunctionEditor(idOrName = 'new', pushState = true, initialTab = 'code') {
|
|
342
|
+
let fn;
|
|
343
|
+
|
|
344
|
+
if (idOrName === 'new' || !idOrName) {
|
|
345
|
+
fn = {
|
|
346
|
+
isNew: true,
|
|
347
|
+
id: '',
|
|
348
|
+
name: '',
|
|
349
|
+
description: '',
|
|
350
|
+
code: STARTER_RECIPES.starter,
|
|
351
|
+
enabled: true,
|
|
352
|
+
authPolicy: 'public',
|
|
353
|
+
methods: ['GET', 'POST'],
|
|
354
|
+
eventTrigger: '',
|
|
355
|
+
timeoutMs: 1000,
|
|
356
|
+
memoryLimitMb: 32,
|
|
357
|
+
allowedDomains: [],
|
|
358
|
+
elevated: false,
|
|
359
|
+
env: {},
|
|
360
|
+
};
|
|
361
|
+
} else {
|
|
362
|
+
fn = (functionsState.functions || []).find(f => f.id === idOrName || f.name === idOrName);
|
|
363
|
+
|
|
364
|
+
if (!fn) {
|
|
365
|
+
try {
|
|
366
|
+
const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
|
|
367
|
+
const endpoint = slug && slug !== 'default'
|
|
368
|
+
? `/api/apps/${slug}/functions/${encodeURIComponent(idOrName)}`
|
|
369
|
+
: `/api/functions/${encodeURIComponent(idOrName)}`;
|
|
370
|
+
fn = await api(endpoint);
|
|
371
|
+
} catch (_) {}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
if (!fn) {
|
|
375
|
+
toast(`Function '${idOrName}' not found`, 'error');
|
|
376
|
+
if (typeof selectNav === 'function') selectNav('functions', false);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
functionsState.currentView = 'editor';
|
|
382
|
+
functionsState.activeFunctionForEdit = fn;
|
|
383
|
+
functionsState.editorTab = initialTab || 'code';
|
|
384
|
+
|
|
385
|
+
if (pushState && typeof updateUrl === 'function') {
|
|
386
|
+
updateUrl(fn.isNew ? '/_/functions/new' : '/_/functions/' + encodeURIComponent(fn.name || fn.id));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if (typeof updateBreadcrumbs === 'function') {
|
|
390
|
+
updateBreadcrumbs();
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
renderFunctionEditorView(fn);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function closeFunctionEditor(pushState = true) {
|
|
397
|
+
if (functionsState.cmEditor) {
|
|
398
|
+
try {
|
|
399
|
+
functionsState.cmEditor.toTextArea();
|
|
400
|
+
} catch (_) {}
|
|
401
|
+
functionsState.cmEditor = null;
|
|
402
|
+
}
|
|
403
|
+
functionsState.currentView = 'list';
|
|
404
|
+
functionsState.activeFunctionForEdit = null;
|
|
405
|
+
|
|
406
|
+
if (pushState && typeof updateUrl === 'function') {
|
|
407
|
+
updateUrl('/_/functions');
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (typeof updateBreadcrumbs === 'function') {
|
|
411
|
+
updateBreadcrumbs();
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if (typeof renderFunctionsView === 'function') {
|
|
415
|
+
renderFunctionsView();
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function switchFunctionEditorTab(tab) {
|
|
420
|
+
functionsState.editorTab = tab;
|
|
421
|
+
['code', 'test', 'config', 'logs'].forEach(t => {
|
|
422
|
+
const btn = document.getElementById('editor-tab-btn-' + t);
|
|
423
|
+
const pane = document.getElementById('fn-editor-pane-' + t);
|
|
424
|
+
if (btn) btn.classList.toggle('active', t === tab);
|
|
425
|
+
if (pane) {
|
|
426
|
+
if (t === 'code') {
|
|
427
|
+
pane.style.display = (t === tab) ? 'flex' : 'none';
|
|
428
|
+
if (t === tab && functionsState.cmEditor) {
|
|
429
|
+
setTimeout(() => { functionsState.cmEditor?.refresh(); }, 20);
|
|
430
|
+
}
|
|
431
|
+
} else if (t === 'test' || t === 'config') {
|
|
432
|
+
pane.style.display = (t === tab) ? 'grid' : 'none';
|
|
433
|
+
} else if (t === 'logs') {
|
|
434
|
+
pane.style.display = (t === tab) ? 'flex' : 'none';
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
if (tab === 'logs' && typeof loadFunctionEditorLogs === 'function') {
|
|
440
|
+
loadFunctionEditorLogs();
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function syncEditorFunctionName(val) {
|
|
445
|
+
const clean = (val || '').toLowerCase().replace(/[^a-z0-9_-]/g, '');
|
|
446
|
+
const headerInput = document.getElementById('fn-editor-name-header');
|
|
447
|
+
const configInput = document.getElementById('fn-editor-name');
|
|
448
|
+
if (headerInput && headerInput.value !== clean) headerInput.value = clean;
|
|
449
|
+
if (configInput && configInput.value !== clean) configInput.value = clean;
|
|
450
|
+
if (functionsState.activeFunctionForEdit) {
|
|
451
|
+
functionsState.activeFunctionForEdit.name = clean;
|
|
452
|
+
}
|
|
453
|
+
const preview = document.getElementById('fn-editor-endpoint-preview');
|
|
454
|
+
if (preview) {
|
|
455
|
+
const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
|
|
456
|
+
const prefix = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
|
|
457
|
+
preview.textContent = `ANY ${prefix}/${clean || '{name}'}/invoke`;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function copyFunctionEndpoint(path) {
|
|
462
|
+
const fullUrl = window.location.origin + path;
|
|
463
|
+
if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
|
|
464
|
+
navigator.clipboard.writeText(fullUrl).then(() => {
|
|
465
|
+
toast('Copied function endpoint URL to clipboard', 'info');
|
|
466
|
+
}).catch(() => {
|
|
467
|
+
prompt('Copy function endpoint URL:', fullUrl);
|
|
468
|
+
});
|
|
469
|
+
} else {
|
|
470
|
+
prompt('Copy function endpoint URL:', fullUrl);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function updateEditorHeaderBadges(fn) {
|
|
475
|
+
const container = document.getElementById('editor-header-badges');
|
|
476
|
+
if (!container) return;
|
|
477
|
+
container.innerHTML = `
|
|
478
|
+
<span class="badge" style="background: ${fn.enabled !== false ? 'rgba(16, 185, 129, 0.15)' : 'var(--bg-card-hover)'}; color: ${fn.enabled !== false ? '#10b981' : 'var(--text-muted)'};">
|
|
479
|
+
${fn.enabled !== false ? '● Active' : '○ Disabled'}
|
|
480
|
+
</span>
|
|
481
|
+
<span class="badge" style="background: rgba(59, 130, 246, 0.15); color: #3b82f6;">
|
|
482
|
+
${escapeHtml((fn.authPolicy || 'public').toUpperCase())}
|
|
483
|
+
</span>
|
|
484
|
+
${fn.elevated ? '<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444;" title="Runs with elevated permissions bypassing rules">Elevated</span>' : ''}
|
|
485
|
+
`;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// ==========================================
|
|
489
|
+
// 4. Workbench Sub-Renderers & Main Assembler
|
|
490
|
+
// ==========================================
|
|
491
|
+
|
|
492
|
+
function renderWorkbenchHeader(fn, isNew, invokePath) {
|
|
493
|
+
return `
|
|
494
|
+
<div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 1rem; border-bottom: 1px solid var(--border-subtle); padding-bottom: 1rem;">
|
|
495
|
+
<div style="display: flex; align-items: center; gap: 14px;">
|
|
496
|
+
<button class="btn btn-secondary btn-sm" onclick="closeFunctionEditor()" title="Back to functions list" style="display: flex; align-items: center; gap: 6px;">
|
|
497
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
|
|
498
|
+
<span>Functions</span>
|
|
499
|
+
</button>
|
|
500
|
+
<div>
|
|
501
|
+
${isNew ? `
|
|
502
|
+
<div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
|
|
503
|
+
<input type="text" id="fn-editor-name-header" class="input" placeholder="function-name" value="${escapeHtml(fn.name || '')}" oninput="syncEditorFunctionName(this.value)" style="font-family: monospace; font-size: 1.15rem; font-weight: 700; width: 250px; padding: 4px 10px;" title="Function Name (Slug)">
|
|
504
|
+
<span class="badge" style="background: rgba(99, 102, 241, 0.15); color: #6366f1; font-weight: 600;">✨ New Function</span>
|
|
505
|
+
</div>
|
|
506
|
+
<div style="display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--text-muted); margin-top: 4px; flex-wrap: wrap;">
|
|
507
|
+
<span>Endpoint: <code id="fn-editor-endpoint-preview" style="font-size: 11px; background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px; color: var(--text-main); font-family: monospace;">ANY ${escapeHtml(invokePath)}</code></span>
|
|
508
|
+
<span>Default limits: 1000ms / 32MB</span>
|
|
509
|
+
</div>
|
|
510
|
+
` : `
|
|
511
|
+
<div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
|
|
512
|
+
<h2 style="font-size: 1.35rem; font-weight: 700; color: var(--text-main); margin: 0; font-family: monospace; display: flex; align-items: center; gap: 8px;">
|
|
513
|
+
${escapeHtml(fn.name)}
|
|
514
|
+
</h2>
|
|
515
|
+
<div id="editor-header-badges" style="display: inline-flex; align-items: center; gap: 6px;">
|
|
516
|
+
<span class="badge" style="background: ${fn.enabled !== false ? 'rgba(16, 185, 129, 0.15)' : 'var(--bg-card-hover)'}; color: ${fn.enabled !== false ? '#10b981' : 'var(--text-muted)'};">
|
|
517
|
+
${fn.enabled !== false ? '● Active' : '○ Disabled'}
|
|
518
|
+
</span>
|
|
519
|
+
<span class="badge" style="background: rgba(59, 130, 246, 0.15); color: #3b82f6;">
|
|
520
|
+
${escapeHtml((fn.authPolicy || 'public').toUpperCase())}
|
|
521
|
+
</span>
|
|
522
|
+
${fn.elevated ? '<span class="badge" style="background: rgba(239, 68, 68, 0.15); color: #ef4444;" title="Runs with elevated permissions bypassing rules">Elevated</span>' : ''}
|
|
523
|
+
</div>
|
|
524
|
+
</div>
|
|
525
|
+
<div style="display: flex; align-items: center; gap: 10px; font-size: 12px; color: var(--text-muted); margin-top: 4px; flex-wrap: wrap;">
|
|
526
|
+
<span>Endpoint: <code style="font-size: 11px; background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px; color: var(--text-main); font-family: monospace;">ANY ${escapeHtml(invokePath)}</code></span>
|
|
527
|
+
<button type="button" class="btn btn-secondary btn-sm" onclick="copyFunctionEndpoint('${invokePath}')" style="font-size: 10px; padding: 1px 6px;" title="Copy full invoke endpoint">
|
|
528
|
+
📋 Copy URL
|
|
529
|
+
</button>
|
|
530
|
+
${fn.eventTrigger ? `<span style="color: var(--accent-primary);">⚡ Hook: <code>${escapeHtml(fn.eventTrigger)}</code></span>` : ''}
|
|
531
|
+
<span>Limits: ${fn.timeoutMs || 1000}ms / ${fn.memoryLimitMb || 32}MB</span>
|
|
532
|
+
</div>
|
|
533
|
+
`}
|
|
534
|
+
</div>
|
|
535
|
+
</div>
|
|
536
|
+
|
|
537
|
+
<div style="display: flex; align-items: center; gap: 8px;">
|
|
538
|
+
${!isNew ? `
|
|
539
|
+
<button class="btn btn-secondary btn-sm" onclick="switchFunctionEditorTab('test')" style="display: flex; align-items: center; gap: 6px;">
|
|
540
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
|
541
|
+
<span>Run Test</span>
|
|
542
|
+
</button>
|
|
543
|
+
<button class="btn btn-secondary btn-sm" onclick="deleteFunctionPrompt('${fn.id}', '${escapeHtml(fn.name)}')" style="color: var(--accent-danger);" title="Delete Function">
|
|
544
|
+
Delete
|
|
545
|
+
</button>
|
|
546
|
+
` : `
|
|
547
|
+
<button class="btn btn-secondary btn-sm" onclick="closeFunctionEditor()" title="Cancel and return to list">
|
|
548
|
+
Cancel
|
|
549
|
+
</button>
|
|
550
|
+
`}
|
|
551
|
+
<button class="btn btn-primary btn-sm" id="btn-editor-save" onclick="saveFunctionEditor()" style="display: flex; align-items: center; gap: 6px; font-weight: 600;">
|
|
552
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
|
|
553
|
+
<span>${isNew ? 'Create Function' : 'Save Changes'}</span>
|
|
554
|
+
</button>
|
|
555
|
+
</div>
|
|
556
|
+
</div>
|
|
557
|
+
`;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function renderWorkbenchTabs(activeTab) {
|
|
561
|
+
return `
|
|
562
|
+
<div style="display: flex; align-items: center; gap: 8px; border-bottom: 1px solid var(--border-subtle); padding-bottom: 8px;">
|
|
563
|
+
<button class="webhook-tab-btn ${activeTab === 'code' ? 'active' : ''}" id="editor-tab-btn-code" onclick="switchFunctionEditorTab('code')">
|
|
564
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
|
|
565
|
+
Code & Context Reference
|
|
566
|
+
</button>
|
|
567
|
+
<button class="webhook-tab-btn ${activeTab === 'test' ? 'active' : ''}" id="editor-tab-btn-test" onclick="switchFunctionEditorTab('test')">
|
|
568
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
|
|
569
|
+
Live Test Runner
|
|
570
|
+
</button>
|
|
571
|
+
<button class="webhook-tab-btn ${activeTab === 'config' ? 'active' : ''}" id="editor-tab-btn-config" onclick="switchFunctionEditorTab('config')">
|
|
572
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
|
|
573
|
+
Configuration & Triggers
|
|
574
|
+
</button>
|
|
575
|
+
<button class="webhook-tab-btn ${activeTab === 'logs' ? 'active' : ''}" id="editor-tab-btn-logs" onclick="switchFunctionEditorTab('logs')">
|
|
576
|
+
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
|
|
577
|
+
Function Logs & History
|
|
578
|
+
</button>
|
|
579
|
+
</div>
|
|
580
|
+
`;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function renderWorkbenchCodePane(fn) {
|
|
584
|
+
return `
|
|
585
|
+
<div id="fn-editor-pane-code" class="fn-editor-pane" style="display: ${functionsState.editorTab === 'code' ? 'flex' : 'none'}; flex-direction: column; gap: 1rem; width: 100%;">
|
|
586
|
+
<div class="card" style="padding: 1rem; display: flex; flex-direction: column; gap: 0.75rem;">
|
|
587
|
+
<div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
|
|
588
|
+
<div style="display: flex; align-items: center; gap: 8px;">
|
|
589
|
+
<span style="font-weight: 600; font-size: 13px; color: var(--text-heading);">Function Handler Source</span>
|
|
590
|
+
<span style="font-size: 11px; color: var(--text-muted); font-family: monospace;">export default async function(ctx) { ... }</span>
|
|
591
|
+
</div>
|
|
592
|
+
<div style="display: flex; align-items: center; gap: 8px;">
|
|
593
|
+
<button type="button" class="btn btn-secondary btn-sm" id="btn-toolbar-toggle-ctx" onclick="toggleWorkbenchCtxRef()" style="font-size: 11px; display: flex; align-items: center; gap: 6px; padding: 3px 9px; background: ${functionsState.isCtxRefExpanded ? 'var(--accent-primary)' : 'var(--bg-card-hover)'}; color: ${functionsState.isCtxRefExpanded ? '#fff' : 'var(--text-main)'};" title="Toggle Context Reference Panel">
|
|
594
|
+
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
|
|
595
|
+
<span>Context API (ctx)</span>
|
|
596
|
+
</button>
|
|
597
|
+
<span style="font-size: 11px; color: var(--text-muted);">Templates:</span>
|
|
598
|
+
<select class="input" style="font-size: 11px; padding: 2px 8px;" onchange="applyStarterRecipe(this.value)">
|
|
599
|
+
<option value="">Apply Recipe...</option>
|
|
600
|
+
<option value="starter">Basic Hello World</option>
|
|
601
|
+
<option value="discount">Cart Discount Calculation</option>
|
|
602
|
+
<option value="hook">Validation & Mutation Hook</option>
|
|
603
|
+
<option value="fetch">External API Fetch</option>
|
|
604
|
+
</select>
|
|
605
|
+
<span style="font-size: 10px; color: var(--text-muted); background: var(--bg-card-hover); padding: 2px 6px; border-radius: 4px;">Ctrl+S to save</span>
|
|
606
|
+
</div>
|
|
607
|
+
</div>
|
|
608
|
+
|
|
609
|
+
<textarea id="fn-editor-code" style="width: 100%; min-height: 520px; height: calc(100vh - 290px); font-family: 'JetBrains Mono', Consolas, Monaco, monospace; font-size: 13px; line-height: 1.5; padding: 14px; border-radius: 8px; border: 1px solid var(--border-subtle); background: #0f172a; color: #f8fafc; resize: vertical;" spellcheck="false">${escapeHtml(fn.code)}</textarea>
|
|
610
|
+
|
|
611
|
+
<!-- Vertical Collapsible Context API Reference (Collapsed by default) -->
|
|
612
|
+
<div class="ctx-reference-panel" style="border: 1px solid var(--border-subtle); border-radius: 8px; background: var(--bg-input); overflow: hidden; margin-top: 4px;">
|
|
613
|
+
<div id="workbench-ctx-header" onclick="toggleWorkbenchCtxRef()" style="display: flex; align-items: center; justify-content: space-between; padding: 9px 14px; background: var(--bg-card); cursor: pointer; user-select: none; border-bottom: ${functionsState.isCtxRefExpanded ? '1px solid var(--border-subtle)' : 'none'}; font-size: 12px;">
|
|
614
|
+
<div style="display: flex; align-items: center; gap: 8px; font-weight: 600; color: var(--text-heading);">
|
|
615
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: var(--accent-primary);"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
|
|
616
|
+
<span>Context Reference (<code>ctx</code>)</span>
|
|
617
|
+
<span style="font-size: 11px; color: var(--text-muted); font-weight: normal;">— 1-click snippet insert for request, events, CRUD & network</span>
|
|
618
|
+
</div>
|
|
619
|
+
<div style="display: flex; align-items: center; gap: 8px;">
|
|
620
|
+
<span class="badge" style="background: var(--bg-card-hover); color: var(--text-muted); font-size: 10px;">18 items</span>
|
|
621
|
+
<button type="button" class="btn btn-secondary btn-sm" id="btn-toggle-workbench-ctx" onclick="event.stopPropagation(); toggleWorkbenchCtxRef();" style="font-size: 11px; padding: 2px 9px;">
|
|
622
|
+
${functionsState.isCtxRefExpanded ? 'Hide Reference ▴' : 'Show Reference ▾'}
|
|
623
|
+
</button>
|
|
624
|
+
</div>
|
|
625
|
+
</div>
|
|
626
|
+
|
|
627
|
+
<div id="workbench-ctx-content" style="display: ${functionsState.isCtxRefExpanded ? 'flex' : 'none'}; flex-direction: column; gap: 10px; padding: 12px 14px; background: var(--bg-card);">
|
|
628
|
+
<div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px;">
|
|
629
|
+
<div style="display: flex; align-items: center; gap: 5px; flex-wrap: wrap;">
|
|
630
|
+
<button type="button" class="ctx-cat-btn active" data-cat="all" onclick="filterCtxCategory('all')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--accent-primary); color: #fff; cursor: pointer; font-weight: 500;">All (18)</button>
|
|
631
|
+
<button type="button" class="ctx-cat-btn" data-cat="request" onclick="filterCtxCategory('request')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">HTTP (ctx.request)</button>
|
|
632
|
+
<button type="button" class="ctx-cat-btn" data-cat="event" onclick="filterCtxCategory('event')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">DB Events (ctx.event)</button>
|
|
633
|
+
<button type="button" class="ctx-cat-btn" data-cat="records" onclick="filterCtxCategory('records')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">Database CRUD (ctx.records)</button>
|
|
634
|
+
<button type="button" class="ctx-cat-btn" data-cat="utils" onclick="filterCtxCategory('utils')" style="font-size: 11px; padding: 3px 9px; border-radius: 4px; border: 1px solid var(--border-subtle); background: var(--bg-card); color: var(--text-muted); cursor: pointer; font-weight: 500;">Fetch, Env & Logs</button>
|
|
635
|
+
</div>
|
|
636
|
+
<div style="flex: 1; max-width: 260px; min-width: 180px;">
|
|
637
|
+
<input type="text" id="ctx-search-input" class="input" placeholder="Search ctx variables..." oninput="filterCtxSearch(this.value)" style="width: 100%; font-size: 11px; padding: 4px 8px;">
|
|
638
|
+
</div>
|
|
639
|
+
</div>
|
|
640
|
+
|
|
641
|
+
<div id="ctx-items-container" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 8px; max-height: 240px; overflow-y: auto; padding-right: 4px;">
|
|
642
|
+
${renderCtxItemsHtml()}
|
|
643
|
+
</div>
|
|
644
|
+
</div>
|
|
645
|
+
</div>
|
|
646
|
+
</div>
|
|
647
|
+
</div>
|
|
648
|
+
`;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
function renderWorkbenchConfigPane(fn, isNew, allowedDomainsString, envString) {
|
|
652
|
+
return `
|
|
653
|
+
<div id="fn-editor-pane-config" class="fn-editor-pane" style="display: ${functionsState.editorTab === 'config' ? 'grid' : 'none'}; grid-template-columns: 1fr 1fr; gap: 1rem; align-items: start;">
|
|
654
|
+
<!-- Column 1: General & Triggers -->
|
|
655
|
+
<div style="display: flex; flex-direction: column; gap: 1rem;">
|
|
656
|
+
<div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
|
|
657
|
+
<div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
|
|
658
|
+
General Settings
|
|
659
|
+
</div>
|
|
660
|
+
<div>
|
|
661
|
+
<label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Function Identifier (Name)</label>
|
|
662
|
+
<input type="text" id="fn-editor-name" class="input" value="${escapeHtml(fn.name || '')}" ${isNew ? 'placeholder="e.g. calculate-discount" oninput="syncEditorFunctionName(this.value)"' : 'readonly'} style="width: 100%; font-family: monospace; ${!isNew ? 'background: var(--bg-input); opacity: 0.85;' : ''}">
|
|
663
|
+
<span style="font-size: 11px; color: var(--text-muted); margin-top: 2px; display: block;">Immutable endpoint slug for API invocation routes. Alphanumeric characters, underscores, and dashes only.</span>
|
|
664
|
+
</div>
|
|
665
|
+
<div>
|
|
666
|
+
<label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Description</label>
|
|
667
|
+
<input type="text" id="fn-editor-desc" class="input" value="${escapeHtml(fn.description || '')}" placeholder="What does this function do?" style="width: 100%;">
|
|
668
|
+
</div>
|
|
669
|
+
<div style="display: flex; align-items: center; gap: 10px; padding: 10px; background: var(--bg-card-hover); border-radius: 6px;">
|
|
670
|
+
<input type="checkbox" id="fn-editor-enabled" ${fn.enabled !== false ? 'checked' : ''} style="cursor: pointer;">
|
|
671
|
+
<div>
|
|
672
|
+
<label for="fn-editor-enabled" style="font-size: 12px; font-weight: 600; cursor: pointer; color: var(--text-main);">Function Enabled</label>
|
|
673
|
+
<div style="font-size: 11px; color: var(--text-muted);">When disabled, API calls return 503 Service Unavailable and lifecycle hooks skip execution.</div>
|
|
674
|
+
</div>
|
|
675
|
+
</div>
|
|
676
|
+
</div>
|
|
677
|
+
|
|
678
|
+
<div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
|
|
679
|
+
<div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
|
|
680
|
+
Triggers & Invocation
|
|
681
|
+
</div>
|
|
682
|
+
<div>
|
|
683
|
+
<label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Database Lifecycle Hook Trigger</label>
|
|
684
|
+
<input type="text" id="fn-editor-hook" class="input" value="${escapeHtml(fn.eventTrigger || '')}" placeholder="e.g. orders:beforeCreate or articles:afterUpdate" style="width: 100%; font-size: 12px; font-family: monospace;">
|
|
685
|
+
<span style="font-size: 11px; color: var(--text-muted); margin-top: 3px; display: block;">
|
|
686
|
+
Format: <code><collection>:<phase><Action></code>. Available phases: <code>beforeCreate</code>, <code>afterCreate</code>, <code>beforeUpdate</code>, <code>afterUpdate</code>, <code>beforeDelete</code>, <code>afterDelete</code>.
|
|
687
|
+
</span>
|
|
688
|
+
</div>
|
|
689
|
+
</div>
|
|
690
|
+
</div>
|
|
691
|
+
|
|
692
|
+
<!-- Column 2: Runtime Limits, Auth & Secrets -->
|
|
693
|
+
<div style="display: flex; flex-direction: column; gap: 1rem;">
|
|
694
|
+
<div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 1rem;">
|
|
695
|
+
<div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px;">
|
|
696
|
+
Security & Guardrails
|
|
697
|
+
</div>
|
|
698
|
+
<div>
|
|
699
|
+
<label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Authorization Policy</label>
|
|
700
|
+
<select id="fn-editor-auth" class="input" style="width: 100%;">
|
|
701
|
+
<option value="public" ${fn.authPolicy === 'public' ? 'selected' : ''}>Public (No Token Required)</option>
|
|
702
|
+
<option value="auth" ${fn.authPolicy === 'auth' ? 'selected' : ''}>User Token (Requires Bearer JWT)</option>
|
|
703
|
+
<option value="admin" ${fn.authPolicy === 'admin' ? 'selected' : ''}>Admin Only (Requires Admin Token)</option>
|
|
704
|
+
<option value="apiKey" ${fn.authPolicy === 'apiKey' ? 'selected' : ''}>API Key (Requires nsk_live_...)</option>
|
|
705
|
+
</select>
|
|
706
|
+
</div>
|
|
707
|
+
|
|
708
|
+
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
|
|
709
|
+
<div>
|
|
710
|
+
<label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px;">Timeout (ms)</label>
|
|
711
|
+
<input type="number" id="fn-editor-timeout" class="input" value="${fn.timeoutMs || 1000}" min="100" max="15000" style="width: 100%; font-size: 12px;">
|
|
712
|
+
</div>
|
|
713
|
+
<div>
|
|
714
|
+
<label style="display: block; font-size: 11px; font-weight: 600; margin-bottom: 4px;">Memory Cap (MB)</label>
|
|
715
|
+
<input type="number" id="fn-editor-memory" class="input" value="${fn.memoryLimitMb || 32}" min="4" max="128" style="width: 100%; font-size: 12px;">
|
|
716
|
+
</div>
|
|
717
|
+
</div>
|
|
718
|
+
|
|
719
|
+
<div>
|
|
720
|
+
<label style="display: block; font-size: 12px; font-weight: 600; margin-bottom: 4px;">Outbound Egress Whitelist (SSRF Protection)</label>
|
|
721
|
+
<input type="text" id="fn-editor-domains" class="input" value="${escapeHtml(allowedDomainsString)}" placeholder="e.g. api.stripe.com, *.resend.com (Leave blank for all public domains)" style="width: 100%; font-size: 12px;">
|
|
722
|
+
</div>
|
|
723
|
+
|
|
724
|
+
<div style="display: flex; align-items: center; gap: 8px; padding: 10px; background: rgba(239, 68, 68, 0.08); border-radius: 6px; border: 1px solid rgba(239, 68, 68, 0.2);">
|
|
725
|
+
<input type="checkbox" id="fn-editor-elevated" ${fn.elevated ? 'checked' : ''} style="cursor: pointer;">
|
|
726
|
+
<div>
|
|
727
|
+
<label for="fn-editor-elevated" style="font-size: 12px; font-weight: 600; cursor: pointer; color: var(--accent-danger);">
|
|
728
|
+
Elevated Service Role
|
|
729
|
+
</label>
|
|
730
|
+
<div style="font-size: 11px; color: var(--text-muted);">Bypasses collection RuleEngine access rules. Allows reading and mutating records as superuser.</div>
|
|
731
|
+
</div>
|
|
732
|
+
</div>
|
|
733
|
+
</div>
|
|
734
|
+
|
|
735
|
+
<div class="card" style="padding: 1.25rem; display: flex; flex-direction: column; gap: 0.75rem;">
|
|
736
|
+
<div style="font-weight: 600; font-size: 13px; color: var(--text-heading); border-bottom: 1px solid var(--border-subtle); padding-bottom: 6px; display: flex; align-items: center; justify-content: space-between;">
|
|
737
|
+
<span>Environment Secrets (<code>ctx.env</code>)</span>
|
|
738
|
+
<span style="font-size: 11px; color: var(--text-muted); font-weight: normal;">JSON Object</span>
|
|
739
|
+
</div>
|
|
740
|
+
<textarea id="fn-editor-env" style="width: 100%; height: 95px; font-family: monospace; font-size: 12px; padding: 8px; border-radius: 6px; border: 1px solid var(--border-subtle); background: var(--bg-card-hover); color: var(--text-main);" placeholder='{ "STRIPE_SECRET": "sk_test_..." }'>${escapeHtml(envString)}</textarea>
|
|
741
|
+
<span style="font-size: 11px; color: var(--text-muted);">Encrypted in database and injected at runtime into <code>ctx.env</code>. Isolated from system <code>process.env</code>.</span>
|
|
742
|
+
</div>
|
|
743
|
+
</div>
|
|
744
|
+
</div>
|
|
745
|
+
`;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function renderFunctionEditorView(fn) {
|
|
749
|
+
const container = document.getElementById('page-view-functions') || document.getElementById('main-body');
|
|
750
|
+
if (!container) return;
|
|
751
|
+
|
|
752
|
+
const isNew = !!fn.isNew;
|
|
753
|
+
const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
|
|
754
|
+
const invokePrefix = slug && slug !== 'default'
|
|
755
|
+
? `/api/apps/${slug}/functions`
|
|
756
|
+
: `/api/functions`;
|
|
757
|
+
const invokePath = `${invokePrefix}/${fn.name || '{name}'}/invoke`;
|
|
758
|
+
|
|
759
|
+
const envString = fn.env && Object.keys(fn.env).length > 0
|
|
760
|
+
? JSON.stringify(fn.env, null, 2)
|
|
761
|
+
: '{}';
|
|
762
|
+
|
|
763
|
+
const allowedDomainsString = (fn.allowedDomains || []).join(', ');
|
|
764
|
+
|
|
765
|
+
const testPaneHtml = typeof renderWorkbenchTestPane === 'function'
|
|
766
|
+
? renderWorkbenchTestPane(fn, isNew)
|
|
767
|
+
: '';
|
|
768
|
+
|
|
769
|
+
const logsPaneHtml = typeof renderWorkbenchLogsPane === 'function'
|
|
770
|
+
? renderWorkbenchLogsPane(fn, isNew)
|
|
771
|
+
: '';
|
|
772
|
+
|
|
773
|
+
container.innerHTML = `
|
|
774
|
+
<div class="function-editor-page" style="max-width: 1440px; margin: 0 auto; padding: 1.25rem 1.5rem; display: flex; flex-direction: column; gap: 1rem;">
|
|
775
|
+
${renderWorkbenchHeader(fn, isNew, invokePath)}
|
|
776
|
+
${renderWorkbenchTabs(functionsState.editorTab)}
|
|
777
|
+
${renderWorkbenchCodePane(fn)}
|
|
778
|
+
${testPaneHtml}
|
|
779
|
+
${renderWorkbenchConfigPane(fn, isNew, allowedDomainsString, envString)}
|
|
780
|
+
${logsPaneHtml}
|
|
781
|
+
</div>
|
|
782
|
+
`;
|
|
783
|
+
|
|
784
|
+
// Attach keyboard shortcut for saving and tab indentation
|
|
785
|
+
const codeArea = document.getElementById('fn-editor-code');
|
|
786
|
+
if (codeArea) {
|
|
787
|
+
codeArea.addEventListener('keydown', (e) => {
|
|
788
|
+
if (e.key === 'Tab') {
|
|
789
|
+
e.preventDefault();
|
|
790
|
+
const start = codeArea.selectionStart;
|
|
791
|
+
const end = codeArea.selectionEnd;
|
|
792
|
+
codeArea.value = codeArea.value.substring(0, start) + ' ' + codeArea.value.substring(end);
|
|
793
|
+
codeArea.selectionStart = codeArea.selectionEnd = start + 2;
|
|
794
|
+
}
|
|
795
|
+
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
|
796
|
+
e.preventDefault();
|
|
797
|
+
saveFunctionEditor();
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// Global Ctrl+S handler while on workbench view
|
|
803
|
+
window.onkeydown = (e) => {
|
|
804
|
+
if ((e.ctrlKey || e.metaKey) && e.key === 's' && functionsState.currentView === 'editor') {
|
|
805
|
+
e.preventDefault();
|
|
806
|
+
saveFunctionEditor();
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
// Initialize CodeMirror editor
|
|
811
|
+
initFunctionCodeMirror();
|
|
812
|
+
|
|
813
|
+
// If logs tab is active on existing function, load logs
|
|
814
|
+
if (functionsState.editorTab === 'logs' && !isNew && typeof loadFunctionEditorLogs === 'function') {
|
|
815
|
+
loadFunctionEditorLogs();
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// ==========================================
|
|
820
|
+
// 5. Persistence Handlers
|
|
821
|
+
// ==========================================
|
|
822
|
+
|
|
823
|
+
async function saveFunctionEditor() {
|
|
824
|
+
const btn = document.getElementById('btn-editor-save');
|
|
825
|
+
const fn = functionsState.activeFunctionForEdit;
|
|
826
|
+
if (!fn) return;
|
|
827
|
+
|
|
828
|
+
const isNew = !!fn.isNew;
|
|
829
|
+
|
|
830
|
+
if (btn) {
|
|
831
|
+
btn.disabled = true;
|
|
832
|
+
btn.textContent = isNew ? 'Creating...' : 'Saving...';
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
try {
|
|
836
|
+
if (functionsState.cmEditor) {
|
|
837
|
+
functionsState.cmEditor.save();
|
|
838
|
+
}
|
|
839
|
+
const codeEl = document.getElementById('fn-editor-code');
|
|
840
|
+
const descEl = document.getElementById('fn-editor-desc');
|
|
841
|
+
const authEl = document.getElementById('fn-editor-auth');
|
|
842
|
+
const hookEl = document.getElementById('fn-editor-hook');
|
|
843
|
+
const timeoutEl = document.getElementById('fn-editor-timeout');
|
|
844
|
+
const memoryEl = document.getElementById('fn-editor-memory');
|
|
845
|
+
const domainsEl = document.getElementById('fn-editor-domains');
|
|
846
|
+
const elevatedEl = document.getElementById('fn-editor-elevated');
|
|
847
|
+
const enabledEl = document.getElementById('fn-editor-enabled');
|
|
848
|
+
const envEl = document.getElementById('fn-editor-env');
|
|
849
|
+
|
|
850
|
+
const nameHeaderEl = document.getElementById('fn-editor-name-header');
|
|
851
|
+
const nameConfigEl = document.getElementById('fn-editor-name');
|
|
852
|
+
let name = (nameHeaderEl ? nameHeaderEl.value.trim() : (nameConfigEl ? nameConfigEl.value.trim() : (fn.name || ''))).toLowerCase();
|
|
853
|
+
|
|
854
|
+
if (isNew) {
|
|
855
|
+
if (!name) {
|
|
856
|
+
throw new Error('Please enter a function identifier (name)');
|
|
857
|
+
}
|
|
858
|
+
if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
|
|
859
|
+
throw new Error('Function name must contain only alphanumeric characters, underscores, and dashes');
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
const code = codeEl ? codeEl.value : fn.code;
|
|
864
|
+
const description = descEl ? descEl.value.trim() : (fn.description || '');
|
|
865
|
+
const authPolicy = authEl ? authEl.value : (fn.authPolicy || 'public');
|
|
866
|
+
const eventTrigger = hookEl ? hookEl.value.trim() : (fn.eventTrigger || '');
|
|
867
|
+
const timeoutMs = timeoutEl ? (parseInt(timeoutEl.value, 10) || 1000) : fn.timeoutMs;
|
|
868
|
+
const memoryLimitMb = memoryEl ? (parseInt(memoryEl.value, 10) || 32) : fn.memoryLimitMb;
|
|
869
|
+
const domainsRaw = domainsEl ? domainsEl.value.trim() : '';
|
|
870
|
+
const allowedDomains = domainsRaw ? domainsRaw.split(',').map(s => s.trim()).filter(Boolean) : (fn.allowedDomains || []);
|
|
871
|
+
const elevated = elevatedEl ? elevatedEl.checked : !!fn.elevated;
|
|
872
|
+
const enabled = enabledEl ? enabledEl.checked : (fn.enabled !== false);
|
|
873
|
+
|
|
874
|
+
let env = fn.env || {};
|
|
875
|
+
if (envEl && envEl.value.trim()) {
|
|
876
|
+
try {
|
|
877
|
+
env = JSON.parse(envEl.value.trim());
|
|
878
|
+
} catch {
|
|
879
|
+
throw new Error('Environment secrets must be valid JSON');
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
const payload = {
|
|
884
|
+
description,
|
|
885
|
+
authPolicy,
|
|
886
|
+
eventTrigger: eventTrigger || null,
|
|
887
|
+
timeoutMs,
|
|
888
|
+
memoryLimitMb,
|
|
889
|
+
allowedDomains,
|
|
890
|
+
elevated,
|
|
891
|
+
enabled,
|
|
892
|
+
code,
|
|
893
|
+
env,
|
|
894
|
+
};
|
|
895
|
+
|
|
896
|
+
const slug = typeof getActiveAppSlug === 'function' ? getActiveAppSlug() : 'default';
|
|
897
|
+
const baseUrl = slug && slug !== 'default' ? `/api/apps/${slug}/functions` : '/api/functions';
|
|
898
|
+
|
|
899
|
+
if (isNew) {
|
|
900
|
+
const createPayload = {
|
|
901
|
+
name,
|
|
902
|
+
methods: fn.methods || ['GET', 'POST'],
|
|
903
|
+
...payload,
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
const created = await api(baseUrl, {
|
|
907
|
+
method: 'POST',
|
|
908
|
+
headers: { 'Content-Type': 'application/json' },
|
|
909
|
+
body: JSON.stringify(createPayload),
|
|
910
|
+
});
|
|
911
|
+
|
|
912
|
+
functionsState.activeFunctionForEdit = created;
|
|
913
|
+
if (!Array.isArray(functionsState.functions)) {
|
|
914
|
+
functionsState.functions = [];
|
|
915
|
+
}
|
|
916
|
+
const existingIdx = functionsState.functions.findIndex(f => f.id === created.id);
|
|
917
|
+
if (existingIdx !== -1) {
|
|
918
|
+
functionsState.functions[existingIdx] = created;
|
|
919
|
+
} else {
|
|
920
|
+
functionsState.functions.unshift(created);
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
toast(`Function '${created.name}' created successfully`, 'success');
|
|
924
|
+
if (typeof updateUrl === 'function') {
|
|
925
|
+
updateUrl('/_/functions/' + encodeURIComponent(created.name));
|
|
926
|
+
}
|
|
927
|
+
if (typeof updateBreadcrumbs === 'function') {
|
|
928
|
+
updateBreadcrumbs();
|
|
929
|
+
}
|
|
930
|
+
renderFunctionEditorView(created);
|
|
931
|
+
if (typeof loadFunctionStats === 'function') {
|
|
932
|
+
await loadFunctionStats();
|
|
933
|
+
}
|
|
934
|
+
} else {
|
|
935
|
+
const updated = await api(`${baseUrl}/${fn.id}`, {
|
|
936
|
+
method: 'PATCH',
|
|
937
|
+
headers: { 'Content-Type': 'application/json' },
|
|
938
|
+
body: JSON.stringify(payload),
|
|
939
|
+
});
|
|
940
|
+
|
|
941
|
+
functionsState.activeFunctionForEdit = updated;
|
|
942
|
+
const idx = (functionsState.functions || []).findIndex(f => f.id === fn.id);
|
|
943
|
+
if (idx !== -1) {
|
|
944
|
+
functionsState.functions[idx] = updated;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
updateEditorHeaderBadges(updated);
|
|
948
|
+
toast(`Function '${updated.name}' saved successfully`, 'success');
|
|
949
|
+
if (typeof loadFunctionStats === 'function') {
|
|
950
|
+
await loadFunctionStats();
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
} catch (err) {
|
|
954
|
+
toast(err.message || 'Failed to save function', 'error');
|
|
955
|
+
} finally {
|
|
956
|
+
if (btn) {
|
|
957
|
+
btn.disabled = false;
|
|
958
|
+
const active = functionsState.activeFunctionForEdit;
|
|
959
|
+
const stillNew = active && active.isNew;
|
|
960
|
+
btn.innerHTML = stillNew
|
|
961
|
+
? `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg><span>Create Function</span>`
|
|
962
|
+
: `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg><span>Save Changes</span>`;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// ==========================================
|
|
968
|
+
// 6. Backward Compatibility Shims
|
|
969
|
+
// ==========================================
|
|
970
|
+
|
|
971
|
+
function openCreateFunctionModal() {
|
|
972
|
+
openCreateFunctionPage();
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
function openEditFunctionModal(id) {
|
|
976
|
+
openFunctionEditor(id);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
function openTestFunctionModal(id) {
|
|
980
|
+
openFunctionEditor(id, true, 'test');
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
function renderFunctionModal(fnData) {
|
|
984
|
+
openFunctionEditor(fnData?.isNew ? 'new' : (fnData?.id || fnData?.name || 'new'));
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function closeFunctionModal() {
|
|
988
|
+
const modalRoot = document.getElementById('modal-root');
|
|
989
|
+
if (modalRoot) modalRoot.innerHTML = '';
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
async function saveFunctionModal() {
|
|
993
|
+
return saveFunctionEditor();
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
async function executeFunctionLiveTest() {
|
|
997
|
+
if (typeof executeFunctionEditorTest === 'function') {
|
|
998
|
+
return executeFunctionEditorTest();
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
function toggleCtxReference() {
|
|
1003
|
+
toggleWorkbenchCtxRef();
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
// Global Exports
|
|
1007
|
+
if (typeof window !== 'undefined') {
|
|
1008
|
+
window.CTX_DOCS = CTX_DOCS;
|
|
1009
|
+
window.renderCtxItemsHtml = renderCtxItemsHtml;
|
|
1010
|
+
window.insertFunctionSnippet = insertFunctionSnippet;
|
|
1011
|
+
window.filterCtxCategory = filterCtxCategory;
|
|
1012
|
+
window.filterCtxSearch = filterCtxSearch;
|
|
1013
|
+
window.applyStarterRecipe = applyStarterRecipe;
|
|
1014
|
+
window.toggleWorkbenchCtxRef = toggleWorkbenchCtxRef;
|
|
1015
|
+
window.toggleCtxReference = toggleCtxReference;
|
|
1016
|
+
window.getCodeMirrorTheme = getCodeMirrorTheme;
|
|
1017
|
+
window.initFunctionCodeMirror = initFunctionCodeMirror;
|
|
1018
|
+
window.openCreateFunctionPage = openCreateFunctionPage;
|
|
1019
|
+
window.openFunctionEditor = openFunctionEditor;
|
|
1020
|
+
window.closeFunctionEditor = closeFunctionEditor;
|
|
1021
|
+
window.switchFunctionEditorTab = switchFunctionEditorTab;
|
|
1022
|
+
window.syncEditorFunctionName = syncEditorFunctionName;
|
|
1023
|
+
window.copyFunctionEndpoint = copyFunctionEndpoint;
|
|
1024
|
+
window.updateEditorHeaderBadges = updateEditorHeaderBadges;
|
|
1025
|
+
window.renderWorkbenchHeader = renderWorkbenchHeader;
|
|
1026
|
+
window.renderWorkbenchTabs = renderWorkbenchTabs;
|
|
1027
|
+
window.renderWorkbenchCodePane = renderWorkbenchCodePane;
|
|
1028
|
+
window.renderWorkbenchConfigPane = renderWorkbenchConfigPane;
|
|
1029
|
+
window.renderFunctionEditorView = renderFunctionEditorView;
|
|
1030
|
+
window.saveFunctionEditor = saveFunctionEditor;
|
|
1031
|
+
window.openCreateFunctionModal = openCreateFunctionModal;
|
|
1032
|
+
window.openEditFunctionModal = openEditFunctionModal;
|
|
1033
|
+
window.openTestFunctionModal = openTestFunctionModal;
|
|
1034
|
+
window.renderFunctionModal = renderFunctionModal;
|
|
1035
|
+
window.closeFunctionModal = closeFunctionModal;
|
|
1036
|
+
window.saveFunctionModal = saveFunctionModal;
|
|
1037
|
+
window.executeFunctionLiveTest = executeFunctionLiveTest;
|
|
1038
|
+
}
|