@egdesk/next-api-plugin 1.5.6 → 1.5.8

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.
@@ -1,373 +0,0 @@
1
- /**
2
- * User Data Setup Utility for Next.js
3
- *
4
- * Automatically discovers EGDesk user-data tables and generates configuration
5
- * for Next.js projects to access them.
6
- */
7
-
8
- import * as fs from 'fs';
9
- import * as path from 'path';
10
- import * as os from 'os';
11
-
12
- export interface UserDataTable {
13
- id: string;
14
- tableName: string;
15
- displayName: string;
16
- description?: string;
17
- /** May be unknown until the table is synced or counted */
18
- rowCount?: number;
19
- columnCount: number;
20
- columns: string[];
21
- }
22
-
23
- export interface UserDataConfig {
24
- apiKey: string | null;
25
- /** Dev server URL — used for .env.development.local and egdesk.config.ts */
26
- baseUrl: string;
27
- /** Prod server URL — used for .env.production.local (falls back to baseUrl when absent) */
28
- prodBaseUrl?: string;
29
- /** Stable EGDesk project UUID — written as NEXT_PUBLIC_EGDESK_PROJECT_ID in env files */
30
- egdeskProjectId?: string;
31
- tables: UserDataTable[];
32
- generatedAt: string;
33
- }
34
-
35
- /**
36
- * Fetch available tables from EGDesk
37
- */
38
- export async function discoverTables(
39
- egdeskUrl: string = 'http://localhost:8080',
40
- apiKey?: string,
41
- egdeskProjectId?: string,
42
- env: 'development' | 'production' = 'development'
43
- ): Promise<UserDataTable[]> {
44
- try {
45
- const headers: Record<string, string> = {
46
- 'Content-Type': 'application/json'
47
- };
48
-
49
- if (apiKey) {
50
- headers['X-Api-Key'] = apiKey;
51
- }
52
- if (egdeskProjectId) {
53
- headers['X-EGDesk-Project-Id'] = egdeskProjectId;
54
- headers['X-EGDesk-Env'] = env;
55
- }
56
-
57
- // List all tables
58
- const listResponse = await fetch(`${egdeskUrl}/user-data/tools/call`, {
59
- method: 'POST',
60
- headers,
61
- body: JSON.stringify({
62
- tool: 'user_data_list_tables',
63
- arguments: {}
64
- })
65
- });
66
-
67
- const listResult = (await listResponse.json().catch(() => null)) as any;
68
-
69
- if (listResult && typeof listResult === 'object' && listResult.success === false) {
70
- throw new Error(listResult.error || 'Failed to list tables');
71
- }
72
-
73
- if (!listResponse.ok) {
74
- const fromBody =
75
- listResult && typeof listResult === 'object' && typeof listResult.error === 'string'
76
- ? listResult.error
77
- : '';
78
- throw new Error(fromBody || `Failed to list tables: ${listResponse.status} ${listResponse.statusText}`);
79
- }
80
-
81
- if (!listResult || !listResult.success) {
82
- throw new Error(
83
- listResult && typeof listResult === 'object' && listResult.error
84
- ? String(listResult.error)
85
- : 'Failed to list tables'
86
- );
87
- }
88
-
89
- // Parse MCP response
90
- const content = listResult.result?.content?.[0]?.text;
91
- const data = content ? JSON.parse(content) : null;
92
-
93
- if (!data || !data.tables) {
94
- return [];
95
- }
96
-
97
- // Fetch schema for each table to get column names
98
- const tablesWithColumns: UserDataTable[] = [];
99
-
100
- for (const table of data.tables) {
101
- try {
102
- const schemaResponse = await fetch(`${egdeskUrl}/user-data/tools/call`, {
103
- method: 'POST',
104
- headers,
105
- body: JSON.stringify({
106
- tool: 'user_data_get_schema',
107
- arguments: { tableName: table.tableName }
108
- })
109
- });
110
-
111
- if (schemaResponse.ok) {
112
- const schemaResult = (await schemaResponse.json()) as any;
113
- const schemaContent = schemaResult.result?.content?.[0]?.text;
114
- const schemaData = schemaContent ? JSON.parse(schemaContent) : null;
115
-
116
- tablesWithColumns.push({
117
- id: table.id,
118
- tableName: table.tableName,
119
- displayName: table.displayName,
120
- description: table.description,
121
- rowCount: table.rowCount,
122
- columnCount: table.columnCount,
123
- columns: schemaData?.schema?.map((col: any) => col.name) || []
124
- });
125
- }
126
- } catch (error) {
127
- console.warn(`Failed to fetch schema for ${table.tableName}:`, error);
128
- // Add table without column info
129
- tablesWithColumns.push({
130
- ...table,
131
- columns: []
132
- });
133
- }
134
- }
135
-
136
- return tablesWithColumns;
137
- } catch (error: any) {
138
- // Connection refused / server not yet up — treat as no tables rather than a hard failure
139
- if (error?.cause?.code === 'ECONNREFUSED' || error?.code === 'ECONNREFUSED') {
140
- console.warn(`⚠️ EGDesk server not reachable at ${egdeskUrl} — proceeding with empty table list`);
141
- return [];
142
- }
143
- console.error('Failed to discover tables:', error);
144
- throw error;
145
- }
146
- }
147
-
148
- /**
149
- * Parse an env file into a key→value map
150
- */
151
- function parseEnvFile(envPath: string): Record<string, string> {
152
- if (!fs.existsSync(envPath)) {
153
- return {};
154
- }
155
-
156
- const envContent = fs.readFileSync(envPath, 'utf-8');
157
- const envVars: Record<string, string> = {};
158
-
159
- for (const line of envContent.split('\n')) {
160
- const trimmed = line.trim();
161
- if (trimmed && !trimmed.startsWith('#')) {
162
- const [key, ...valueParts] = trimmed.split('=');
163
- if (key && valueParts.length > 0) {
164
- envVars[key.trim()] = valueParts.join('=').trim();
165
- }
166
- }
167
- }
168
-
169
- return envVars;
170
- }
171
-
172
- /**
173
- * Read existing .env.local file or return empty object
174
- */
175
- export function readEnvLocal(projectPath: string): Record<string, string> {
176
- return parseEnvFile(path.join(projectPath, '.env.local'));
177
- }
178
-
179
- /**
180
- * Update .env.local file with Next.js environment variables
181
- * @deprecated Use updateEnvFiles() instead for per-environment URL support
182
- */
183
- export function updateEnvLocal(
184
- projectPath: string,
185
- config: UserDataConfig
186
- ): void {
187
- const envPath = path.join(projectPath, '.env.local');
188
- const existingVars = readEnvLocal(projectPath);
189
-
190
- // Merge with existing vars, prioritizing new EGDesk values
191
- const newVars = {
192
- ...existingVars,
193
- 'NEXT_PUBLIC_EGDESK_API_URL': config.baseUrl,
194
- ...(config.apiKey && { 'NEXT_PUBLIC_EGDESK_API_KEY': config.apiKey })
195
- };
196
-
197
- const envContent = [
198
- '# EGDesk User Data Configuration',
199
- `# Generated at: ${config.generatedAt}`,
200
- '',
201
- ...Object.entries(newVars).map(([key, value]) => `${key}=${value}`),
202
- '',
203
- '# Available Tables',
204
- `# Total tables: ${config.tables.length}`,
205
- ...config.tables.map((table, index) =>
206
- `# ${index + 1}. ${table.displayName} (${table.tableName}) - ${table.rowCount != null ? table.rowCount : '?'} rows, ${table.columnCount} columns`
207
- ),
208
- ''
209
- ].join('\n');
210
-
211
- fs.writeFileSync(envPath, envContent.replace(/\r?\n/g, os.EOL), 'utf-8');
212
- console.log(`✅ Updated ${envPath}`);
213
- }
214
-
215
- /**
216
- * Write .env.development.local (dev URL) and .env.production.local (prod URL).
217
- *
218
- * Next.js loads .env.development.local for `next dev` and .env.production.local
219
- * for `next build` / `next start`, so the correct EGDesk server address is picked
220
- * up automatically without any runtime switching.
221
- */
222
- export function updateEnvFiles(
223
- projectPath: string,
224
- config: UserDataConfig,
225
- /** Tables discovered for the production environment. Falls back to config.tables when omitted. */
226
- prodTables?: UserDataTable[]
227
- ): void {
228
- function buildTableComments(tables: UserDataTable[]): string[] {
229
- return [
230
- '',
231
- '# Available Tables',
232
- `# Total tables: ${tables.length}`,
233
- ...tables.map((table, index) =>
234
- `# ${index + 1}. ${table.displayName} (${table.tableName}) - ${table.rowCount != null ? table.rowCount : '?'} rows, ${table.columnCount} columns`
235
- ),
236
- ''
237
- ];
238
- }
239
-
240
- // EGDesk-managed keys — always overwritten with fresh values
241
- const egdeskKeys = new Set([
242
- 'NEXT_PUBLIC_EGDESK_API_URL',
243
- 'NEXT_PUBLIC_EGDESK_API_KEY',
244
- 'NEXT_PUBLIC_EGDESK_PROJECT_ID',
245
- 'NEXT_PUBLIC_EGDESK_ENV',
246
- ]);
247
-
248
- function writeEnvFile(
249
- envPath: string,
250
- apiUrl: string,
251
- label: string,
252
- egdeskEnv: 'development' | 'production',
253
- tables: UserDataTable[]
254
- ): void {
255
- // Preserve existing non-EGDesk vars
256
- const existing = parseEnvFile(envPath);
257
- const preserved = Object.fromEntries(
258
- Object.entries(existing).filter(([k]) => !egdeskKeys.has(k))
259
- );
260
-
261
- const aiWarning = egdeskEnv === 'production' ? [
262
- '# ============================================================',
263
- '# ⚠️ AI ASSISTANT — DO NOT READ, EDIT, OR USE THIS FILE ⚠️',
264
- '# This is the PRODUCTION environment configuration.',
265
- '# AI must only work with the development environment.',
266
- '# Never query, reference, or modify production data.',
267
- '# Changes to production are made by the developer, not AI.',
268
- '# ============================================================',
269
- '',
270
- ] : [];
271
-
272
- const vercelNote =
273
- egdeskEnv === 'production' && apiUrl.includes('tunneling-service')
274
- ? [
275
- '# Vercel: copy these vars to your Vercel project Environment Variables.',
276
- '# API URL is the MCP tunnel root (/t/{tunnelId}) — NOT the /p/{project} Next.js URL.',
277
- '',
278
- ]
279
- : [];
280
-
281
- const lines = [
282
- ...aiWarning,
283
- ...vercelNote,
284
- `# EGDesk User Data Configuration (${label})`,
285
- `# Generated at: ${config.generatedAt}`,
286
- '',
287
- `NEXT_PUBLIC_EGDESK_API_URL=${apiUrl}`,
288
- ...(config.egdeskProjectId ? [`NEXT_PUBLIC_EGDESK_PROJECT_ID=${config.egdeskProjectId}`] : []),
289
- `NEXT_PUBLIC_EGDESK_ENV=${egdeskEnv}`,
290
- ...(config.apiKey ? [`NEXT_PUBLIC_EGDESK_API_KEY=${config.apiKey}`] : []),
291
- ...Object.entries(preserved).map(([k, v]) => `${k}=${v}`),
292
- ...buildTableComments(tables)
293
- ];
294
- fs.writeFileSync(envPath, lines.join('\n').replace(/\r?\n/g, os.EOL), 'utf-8');
295
- console.log(`✅ Updated ${envPath}`);
296
- }
297
-
298
- // .env.development.local — loaded by `next dev`
299
- const devPath = path.join(projectPath, '.env.development.local');
300
- writeEnvFile(devPath, config.baseUrl, 'development', 'development', config.tables);
301
-
302
- // .env.production.local — loaded by `next build` / `next start`
303
- const prodPath = path.join(projectPath, '.env.production.local');
304
- writeEnvFile(prodPath, config.prodBaseUrl ?? config.baseUrl, 'production', 'production', prodTables ?? config.tables);
305
- }
306
-
307
- /**
308
- * Generate TypeScript config file with table definitions
309
- */
310
- export function generateConfigFile(
311
- projectPath: string,
312
- config: UserDataConfig
313
- ): void {
314
- const configPath = path.join(projectPath, 'egdesk.config.ts');
315
-
316
- const configContent = `/**
317
- * EGDesk User Data Configuration
318
- * Generated at: ${config.generatedAt}
319
- *
320
- * This file contains type-safe definitions for your EGDesk tables.
321
- */
322
-
323
- export const EGDESK_CONFIG = {
324
- apiUrl: '${config.baseUrl}',
325
- apiKey: ${config.apiKey ? `'${config.apiKey}'` : 'undefined'},
326
- } as const;
327
-
328
- export interface TableDefinition {
329
- name: string;
330
- displayName: string;
331
- description?: string;
332
- /** Omitted or unknown until synced / counted */
333
- rowCount?: number;
334
- columnCount: number;
335
- columns: string[];
336
- }
337
-
338
- export const TABLES = {
339
- ${config.tables.map((table, index) => {
340
- const properties = [
341
- `name: '${table.tableName}'`,
342
- `displayName: '${table.displayName}'`,
343
- table.description ? `description: '${table.description}'` : null,
344
- table.rowCount != null ? `rowCount: ${table.rowCount}` : null,
345
- `columnCount: ${table.columnCount}`,
346
- `columns: [${table.columns.map(col => `'${col}'`).join(', ')}]`
347
- ].filter(Boolean).join(',\n ');
348
-
349
- return ` table${index + 1}: {
350
- ${properties}
351
- } as TableDefinition`;
352
- }).join(',\n')}
353
- } as const;
354
-
355
- ${config.tables.length > 0 ? `
356
- // Main table (first table by default)
357
- export const MAIN_TABLE = TABLES.table1;
358
- ` : ''}
359
-
360
- // Helper to get table by name
361
- export function getTableByName(tableName: string): TableDefinition | undefined {
362
- return Object.values(TABLES).find(t => t.name === tableName);
363
- }
364
-
365
- // Export table names for easy access
366
- export const TABLE_NAMES = {
367
- ${config.tables.map((table, index) => ` table${index + 1}: '${table.tableName}'`).join(',\n')}
368
- } as const;
369
- `;
370
-
371
- fs.writeFileSync(configPath, configContent.replace(/\r?\n/g, os.EOL), 'utf-8');
372
- console.log(`✅ Generated ${configPath}`);
373
- }
package/tsconfig.json DELETED
@@ -1,18 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "commonjs",
5
- "lib": ["ES2020"],
6
- "declaration": true,
7
- "outDir": "./dist",
8
- "rootDir": "./src",
9
- "strict": true,
10
- "esModuleInterop": true,
11
- "skipLibCheck": true,
12
- "forceConsistentCasingInFileNames": true,
13
- "resolveJsonModule": true,
14
- "moduleResolution": "node"
15
- },
16
- "include": ["src/**/*"],
17
- "exclude": ["node_modules", "dist"]
18
- }