@egdesk/next-api-plugin 1.5.4 → 1.5.6

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.
@@ -73,7 +73,7 @@ import type { NextRequest } from 'next/server';
73
73
  /**
74
74
  * EGDesk Database Proxy Middleware
75
75
  *
76
- * Intercepts __user_data_proxy, __browser_recording_proxy, and __internal_knowledge_proxy requests
76
+ * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, and __company_research_proxy requests
77
77
  * and forwards them to the EGDesk MCP HTTP server.
78
78
  * This allows CORS-free database access in both local and tunneled environments.
79
79
  *
@@ -181,6 +181,38 @@ export async function middleware(request: NextRequest) {
181
181
  }
182
182
  }
183
183
 
184
+ if (pathname.includes('__company_research_proxy')) {
185
+ try {
186
+ const body = await request.text();
187
+
188
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
189
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
190
+
191
+ const headers: HeadersInit = {
192
+ 'Content-Type': 'application/json',
193
+ };
194
+
195
+ if (apiKey) {
196
+ headers['X-Api-Key'] = apiKey;
197
+ }
198
+
199
+ const response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
200
+ method: 'POST',
201
+ headers,
202
+ body,
203
+ });
204
+
205
+ const result = await response.json();
206
+
207
+ return NextResponse.json(result, { status: response.status });
208
+ } catch (error: any) {
209
+ return NextResponse.json(
210
+ { error: 'Proxy error', message: error.message },
211
+ { status: 500 }
212
+ );
213
+ }
214
+ }
215
+
184
216
  // Continue to next middleware or route
185
217
  return NextResponse.next();
186
218
  }
@@ -75,11 +75,24 @@ import type { NextRequest } from 'next/server';
75
75
  /**
76
76
  * EGDesk Database Proxy (Next.js 16+)
77
77
  *
78
- * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __ai_center_proxy, and __korean_law_proxy requests
78
+ * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __seo_proxy, __ssl_proxy, __local_agent_proxy, and __pageindex_proxy requests
79
79
  * and forwards them to the EGDesk MCP HTTP server. This avoids CORS in local and tunneled environments.
80
80
  *
81
81
  * Generated by @egdesk/next-api-plugin
82
82
  */
83
+
84
+ /** Build EGDesk routing headers from env vars (injected into every upstream call). */
85
+ function buildEgdeskHeaders(): Record<string, string> {
86
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
87
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
88
+ const projectId = process.env.NEXT_PUBLIC_EGDESK_PROJECT_ID;
89
+ const egdeskEnv = process.env.NEXT_PUBLIC_EGDESK_ENV;
90
+ if (apiKey) headers['X-Api-Key'] = apiKey;
91
+ if (projectId) headers['X-EGDesk-Project-Id'] = projectId;
92
+ if (egdeskEnv) headers['X-EGDesk-Env'] = egdeskEnv;
93
+ return headers;
94
+ }
95
+
83
96
  export async function proxy(request: NextRequest) {
84
97
  const { pathname } = request.nextUrl;
85
98
 
@@ -87,23 +100,12 @@ export async function proxy(request: NextRequest) {
87
100
  if (pathname.includes('__user_data_proxy')) {
88
101
  try {
89
102
  const body = await request.text();
90
-
91
- // Read API key and URL from environment
92
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
93
103
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
94
104
 
95
- const headers: HeadersInit = {
96
- 'Content-Type': 'application/json',
97
- };
98
-
99
- if (apiKey) {
100
- headers['X-Api-Key'] = apiKey;
101
- }
102
-
103
105
  // Forward to EGDesk MCP server
104
106
  const response = await fetch(\`\${apiUrl}/user-data/tools/call\`, {
105
107
  method: 'POST',
106
- headers,
108
+ headers: buildEgdeskHeaders(),
107
109
  body,
108
110
  });
109
111
 
@@ -121,21 +123,11 @@ export async function proxy(request: NextRequest) {
121
123
  if (pathname.includes('__browser_recording_proxy')) {
122
124
  try {
123
125
  const body = await request.text();
124
-
125
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
126
126
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
127
127
 
128
- const headers: HeadersInit = {
129
- 'Content-Type': 'application/json',
130
- };
131
-
132
- if (apiKey) {
133
- headers['X-Api-Key'] = apiKey;
134
- }
135
-
136
128
  const response = await fetch(\`\${apiUrl}/browser-recording/tools/call\`, {
137
129
  method: 'POST',
138
- headers,
130
+ headers: buildEgdeskHeaders(),
139
131
  body,
140
132
  });
141
133
 
@@ -153,21 +145,11 @@ export async function proxy(request: NextRequest) {
153
145
  if (pathname.includes('__internal_knowledge_proxy')) {
154
146
  try {
155
147
  const body = await request.text();
156
-
157
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
158
148
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
159
149
 
160
- const headers: HeadersInit = {
161
- 'Content-Type': 'application/json',
162
- };
163
-
164
- if (apiKey) {
165
- headers['X-Api-Key'] = apiKey;
166
- }
167
-
168
150
  const response = await fetch(\`\${apiUrl}/internal-knowledge/tools/call\`, {
169
151
  method: 'POST',
170
- headers,
152
+ headers: buildEgdeskHeaders(),
171
153
  body,
172
154
  });
173
155
 
@@ -185,21 +167,55 @@ export async function proxy(request: NextRequest) {
185
167
  if (pathname.includes('__ai_center_proxy')) {
186
168
  try {
187
169
  const body = await request.text();
170
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
171
+
172
+ const response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
173
+ method: 'POST',
174
+ headers: buildEgdeskHeaders(),
175
+ body,
176
+ });
177
+
178
+ const result = await response.json();
179
+
180
+ return NextResponse.json(result, { status: response.status });
181
+ } catch (error: any) {
182
+ return NextResponse.json(
183
+ { error: 'Proxy error', message: error.message },
184
+ { status: 500 }
185
+ );
186
+ }
187
+ }
188
188
 
189
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
189
+ if (pathname.includes('__korean_law_proxy')) {
190
+ try {
191
+ const body = await request.text();
190
192
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
191
193
 
192
- const headers: HeadersInit = {
193
- 'Content-Type': 'application/json',
194
- };
194
+ const response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
195
+ method: 'POST',
196
+ headers: buildEgdeskHeaders(),
197
+ body,
198
+ });
195
199
 
196
- if (apiKey) {
197
- headers['X-Api-Key'] = apiKey;
198
- }
200
+ const result = await response.json();
199
201
 
200
- const response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
202
+ return NextResponse.json(result, { status: response.status });
203
+ } catch (error: any) {
204
+ return NextResponse.json(
205
+ { error: 'Proxy error', message: error.message },
206
+ { status: 500 }
207
+ );
208
+ }
209
+ }
210
+
211
+ if (pathname.includes('__seo_proxy')) {
212
+ try {
213
+ const body = await request.text();
214
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
215
+
216
+ const response = await fetch(\`\${apiUrl}/seo/tools/call\`, {
201
217
  method: 'POST',
202
- headers,
218
+ headers: buildEgdeskHeaders(),
203
219
  body,
204
220
  });
205
221
 
@@ -214,24 +230,80 @@ export async function proxy(request: NextRequest) {
214
230
  }
215
231
  }
216
232
 
217
- if (pathname.includes('__korean_law_proxy')) {
233
+ if (pathname.includes('__ssl_proxy')) {
218
234
  try {
219
235
  const body = await request.text();
236
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
220
237
 
221
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
238
+ const response = await fetch(\`\${apiUrl}/ssl/tools/call\`, {
239
+ method: 'POST',
240
+ headers: buildEgdeskHeaders(),
241
+ body,
242
+ });
243
+
244
+ const result = await response.json();
245
+
246
+ return NextResponse.json(result, { status: response.status });
247
+ } catch (error: any) {
248
+ return NextResponse.json(
249
+ { error: 'Proxy error', message: error.message },
250
+ { status: 500 }
251
+ );
252
+ }
253
+ }
254
+
255
+ if (pathname.includes('__company_research_proxy')) {
256
+ try {
257
+ const body = await request.text();
222
258
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
223
259
 
224
- const headers: HeadersInit = {
225
- 'Content-Type': 'application/json',
226
- };
260
+ const response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
261
+ method: 'POST',
262
+ headers: buildEgdeskHeaders(),
263
+ body,
264
+ });
227
265
 
228
- if (apiKey) {
229
- headers['X-Api-Key'] = apiKey;
230
- }
266
+ const result = await response.json();
231
267
 
232
- const response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
268
+ return NextResponse.json(result, { status: response.status });
269
+ } catch (error: any) {
270
+ return NextResponse.json(
271
+ { error: 'Proxy error', message: error.message },
272
+ { status: 500 }
273
+ );
274
+ }
275
+ }
276
+
277
+ if (pathname.includes('__local_agent_proxy')) {
278
+ try {
279
+ const body = await request.text();
280
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
281
+
282
+ const response = await fetch(\`\${apiUrl}/local-agent/tools/call\`, {
283
+ method: 'POST',
284
+ headers: buildEgdeskHeaders(),
285
+ body,
286
+ });
287
+
288
+ const result = await response.json();
289
+
290
+ return NextResponse.json(result, { status: response.status });
291
+ } catch (error: any) {
292
+ return NextResponse.json(
293
+ { error: 'Proxy error', message: error.message },
294
+ { status: 500 }
295
+ );
296
+ }
297
+ }
298
+
299
+ if (pathname.includes('__pageindex_proxy')) {
300
+ try {
301
+ const body = await request.text();
302
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
303
+
304
+ const response = await fetch(\`\${apiUrl}/pageindex/tools/call\`, {
233
305
  method: 'POST',
234
- headers,
306
+ headers: buildEgdeskHeaders(),
235
307
  body,
236
308
  });
237
309
 
@@ -254,7 +326,7 @@ export const config = {
254
326
  matcher: [
255
327
  /*
256
328
  * Match all paths except static assets
257
- * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __ai_center_proxy / __korean_law_proxy
329
+ * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __company_research_proxy / __ai_center_proxy / __korean_law_proxy / __seo_proxy / __ssl_proxy / __local_agent_proxy / __pageindex_proxy
258
330
  */
259
331
  '/:path*',
260
332
  ],
package/dist/index.d.ts CHANGED
@@ -6,6 +6,16 @@
6
6
  */
7
7
  export interface SetupOptions {
8
8
  egdeskUrl?: string;
9
+ /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
10
+ prodEgdeskUrl?: string;
11
+ /**
12
+ * URL used only for table discovery (discoverTables). Defaults to egdeskUrl.
13
+ * Set this to the EGDesk internal server URL (e.g. http://localhost:8080) when egdeskUrl
14
+ * is a per-project proxy port that doesn't serve the EGDesk MCP HTTP API.
15
+ */
16
+ discoveryUrl?: string;
17
+ /** Stable EGDesk project UUID — written as NEXT_PUBLIC_EGDESK_PROJECT_ID in env files */
18
+ egdeskProjectId?: string;
9
19
  apiKey?: string;
10
20
  useProxy?: boolean;
11
21
  }
@@ -23,5 +33,6 @@ export type { UserDataTable, UserDataConfig } from './setup-userdata';
23
33
  export { discoverTables } from './setup-userdata';
24
34
  export { generateMiddleware } from './generate-middleware';
25
35
  export { generateProxy } from './generate-proxy';
26
- export { generateHelpers } from './generate-helpers';
36
+ export { generateHelpers, generateSchemaFile, ensureSchemaFile, formatEgdeskSchemaFileContent } from './generate-helpers';
37
+ export type { SchemaTableDefinition, EnsureSchemaFileResult } from './generate-helpers';
27
38
  export { generateApiWrapper } from './generate-api-wrapper';
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * Provides middleware-based database access for Next.js applications.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.generateApiWrapper = exports.generateHelpers = exports.generateProxy = exports.generateMiddleware = exports.discoverTables = void 0;
9
+ exports.generateApiWrapper = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateProxy = exports.generateMiddleware = exports.discoverTables = void 0;
10
10
  exports.setupNextApiPlugin = setupNextApiPlugin;
11
11
  const setup_userdata_1 = require("./setup-userdata");
12
12
  const generate_middleware_1 = require("./generate-middleware");
@@ -23,25 +23,30 @@ const generate_api_wrapper_1 = require("./generate-api-wrapper");
23
23
  * - .env.local (environment variables)
24
24
  */
25
25
  async function setupNextApiPlugin(projectPath, options = {}) {
26
- const { egdeskUrl = 'http://localhost:8080', apiKey, useProxy = true } = options;
26
+ const { egdeskUrl = 'http://localhost:8080', prodEgdeskUrl, discoveryUrl, egdeskProjectId, apiKey, useProxy = true } = options;
27
27
  console.log('🔍 Discovering EGDesk user-data tables...');
28
28
  try {
29
- const tables = await (0, setup_userdata_1.discoverTables)(egdeskUrl, apiKey);
30
- if (tables.length === 0) {
29
+ const [devTables, prodTables] = await Promise.all([
30
+ (0, setup_userdata_1.discoverTables)(discoveryUrl ?? egdeskUrl, apiKey, egdeskProjectId, 'development'),
31
+ (0, setup_userdata_1.discoverTables)(discoveryUrl ?? egdeskUrl, apiKey, egdeskProjectId, 'production'),
32
+ ]);
33
+ if (devTables.length === 0) {
31
34
  console.warn('⚠️ No tables found. Import data in EGDesk first.');
32
35
  console.log('');
33
36
  console.log('Generating files anyway with empty table list...');
34
37
  }
35
38
  else {
36
- console.log(`✅ Found ${tables.length} table(s):`);
37
- tables.forEach((table, index) => {
39
+ console.log(`✅ Found ${devTables.length} dev table(s), ${prodTables.length} prod table(s):`);
40
+ devTables.forEach((table, index) => {
38
41
  console.log(` ${index + 1}. ${table.displayName} (${table.rowCount} rows)`);
39
42
  });
40
43
  }
41
44
  const config = {
42
45
  apiKey: apiKey || null,
43
46
  baseUrl: egdeskUrl,
44
- tables,
47
+ prodBaseUrl: prodEgdeskUrl,
48
+ egdeskProjectId,
49
+ tables: devTables,
45
50
  generatedAt: new Date().toISOString()
46
51
  };
47
52
  // Generate all configuration files
@@ -57,20 +62,27 @@ async function setupNextApiPlugin(projectPath, options = {}) {
57
62
  (0, generate_middleware_1.generateMiddleware)(projectPath);
58
63
  }
59
64
  (0, setup_userdata_1.generateConfigFile)(projectPath, config);
65
+ (0, generate_helpers_1.ensureSchemaFile)(projectPath, devTables.map((table) => ({
66
+ tableName: table.tableName,
67
+ displayName: table.displayName,
68
+ columns: table.columns,
69
+ })));
60
70
  (0, generate_helpers_1.generateHelpers)(projectPath);
61
71
  (0, generate_api_wrapper_1.generateApiWrapper)(projectPath);
62
- (0, setup_userdata_1.updateEnvLocal)(projectPath, config);
72
+ (0, setup_userdata_1.updateEnvFiles)(projectPath, config, prodTables);
63
73
  const proxyFile = useProxy ? 'proxy.ts' : 'middleware.ts';
64
74
  console.log('');
65
75
  console.log('✅ Setup complete! Files generated:');
66
76
  console.log(` - ${proxyFile} (database proxy)`);
67
77
  console.log(' - egdesk.config.ts (type-safe config)');
78
+ console.log(' - egdesk.schema.ts (committed seed schema — add to git if newly created)');
68
79
  console.log(' - egdesk-helpers.ts (helper functions)');
69
80
  console.log(' - src/lib/api.ts (basePath-aware fetch wrapper)');
70
- console.log(' - .env.local (environment variables)');
81
+ console.log(' - .env.development.local (dev environment variables)');
82
+ console.log(' - .env.production.local (prod environment variables)');
71
83
  console.log('');
72
84
  console.log('📝 Next steps:');
73
- console.log(' 1. Add .env.local to your .gitignore');
85
+ console.log(' 1. Add .env.*.local to your .gitignore');
74
86
  console.log(' 2. Restart your Next.js dev server');
75
87
  console.log(' 3. Import and use helpers in your components:');
76
88
  console.log(' import { queryTable } from "./egdesk-helpers"');
@@ -97,5 +109,8 @@ var generate_proxy_2 = require("./generate-proxy");
97
109
  Object.defineProperty(exports, "generateProxy", { enumerable: true, get: function () { return generate_proxy_2.generateProxy; } });
98
110
  var generate_helpers_2 = require("./generate-helpers");
99
111
  Object.defineProperty(exports, "generateHelpers", { enumerable: true, get: function () { return generate_helpers_2.generateHelpers; } });
112
+ Object.defineProperty(exports, "generateSchemaFile", { enumerable: true, get: function () { return generate_helpers_2.generateSchemaFile; } });
113
+ Object.defineProperty(exports, "ensureSchemaFile", { enumerable: true, get: function () { return generate_helpers_2.ensureSchemaFile; } });
114
+ Object.defineProperty(exports, "formatEgdeskSchemaFileContent", { enumerable: true, get: function () { return generate_helpers_2.formatEgdeskSchemaFileContent; } });
100
115
  var generate_api_wrapper_2 = require("./generate-api-wrapper");
101
116
  Object.defineProperty(exports, "generateApiWrapper", { enumerable: true, get: function () { return generate_api_wrapper_2.generateApiWrapper; } });
@@ -16,22 +16,38 @@ export interface UserDataTable {
16
16
  }
17
17
  export interface UserDataConfig {
18
18
  apiKey: string | null;
19
+ /** Dev server URL — used for .env.development.local and egdesk.config.ts */
19
20
  baseUrl: string;
21
+ /** Prod server URL — used for .env.production.local (falls back to baseUrl when absent) */
22
+ prodBaseUrl?: string;
23
+ /** Stable EGDesk project UUID — written as NEXT_PUBLIC_EGDESK_PROJECT_ID in env files */
24
+ egdeskProjectId?: string;
20
25
  tables: UserDataTable[];
21
26
  generatedAt: string;
22
27
  }
23
28
  /**
24
29
  * Fetch available tables from EGDesk
25
30
  */
26
- export declare function discoverTables(egdeskUrl?: string, apiKey?: string): Promise<UserDataTable[]>;
31
+ export declare function discoverTables(egdeskUrl?: string, apiKey?: string, egdeskProjectId?: string, env?: 'development' | 'production'): Promise<UserDataTable[]>;
27
32
  /**
28
33
  * Read existing .env.local file or return empty object
29
34
  */
30
35
  export declare function readEnvLocal(projectPath: string): Record<string, string>;
31
36
  /**
32
37
  * Update .env.local file with Next.js environment variables
38
+ * @deprecated Use updateEnvFiles() instead for per-environment URL support
33
39
  */
34
40
  export declare function updateEnvLocal(projectPath: string, config: UserDataConfig): void;
41
+ /**
42
+ * Write .env.development.local (dev URL) and .env.production.local (prod URL).
43
+ *
44
+ * Next.js loads .env.development.local for `next dev` and .env.production.local
45
+ * for `next build` / `next start`, so the correct EGDesk server address is picked
46
+ * up automatically without any runtime switching.
47
+ */
48
+ export declare function updateEnvFiles(projectPath: string, config: UserDataConfig,
49
+ /** Tables discovered for the production environment. Falls back to config.tables when omitted. */
50
+ prodTables?: UserDataTable[]): void;
35
51
  /**
36
52
  * Generate TypeScript config file with table definitions
37
53
  */
@@ -42,6 +42,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
42
42
  exports.discoverTables = discoverTables;
43
43
  exports.readEnvLocal = readEnvLocal;
44
44
  exports.updateEnvLocal = updateEnvLocal;
45
+ exports.updateEnvFiles = updateEnvFiles;
45
46
  exports.generateConfigFile = generateConfigFile;
46
47
  const fs = __importStar(require("fs"));
47
48
  const path = __importStar(require("path"));
@@ -49,7 +50,7 @@ const os = __importStar(require("os"));
49
50
  /**
50
51
  * Fetch available tables from EGDesk
51
52
  */
52
- async function discoverTables(egdeskUrl = 'http://localhost:8080', apiKey) {
53
+ async function discoverTables(egdeskUrl = 'http://localhost:8080', apiKey, egdeskProjectId, env = 'development') {
53
54
  try {
54
55
  const headers = {
55
56
  'Content-Type': 'application/json'
@@ -57,6 +58,10 @@ async function discoverTables(egdeskUrl = 'http://localhost:8080', apiKey) {
57
58
  if (apiKey) {
58
59
  headers['X-Api-Key'] = apiKey;
59
60
  }
61
+ if (egdeskProjectId) {
62
+ headers['X-EGDesk-Project-Id'] = egdeskProjectId;
63
+ headers['X-EGDesk-Env'] = env;
64
+ }
60
65
  // List all tables
61
66
  const listResponse = await fetch(`${egdeskUrl}/user-data/tools/call`, {
62
67
  method: 'POST',
@@ -126,15 +131,19 @@ async function discoverTables(egdeskUrl = 'http://localhost:8080', apiKey) {
126
131
  return tablesWithColumns;
127
132
  }
128
133
  catch (error) {
134
+ // Connection refused / server not yet up — treat as no tables rather than a hard failure
135
+ if (error?.cause?.code === 'ECONNREFUSED' || error?.code === 'ECONNREFUSED') {
136
+ console.warn(`⚠️ EGDesk server not reachable at ${egdeskUrl} — proceeding with empty table list`);
137
+ return [];
138
+ }
129
139
  console.error('Failed to discover tables:', error);
130
140
  throw error;
131
141
  }
132
142
  }
133
143
  /**
134
- * Read existing .env.local file or return empty object
144
+ * Parse an env file into a key→value map
135
145
  */
136
- function readEnvLocal(projectPath) {
137
- const envPath = path.join(projectPath, '.env.local');
146
+ function parseEnvFile(envPath) {
138
147
  if (!fs.existsSync(envPath)) {
139
148
  return {};
140
149
  }
@@ -151,8 +160,15 @@ function readEnvLocal(projectPath) {
151
160
  }
152
161
  return envVars;
153
162
  }
163
+ /**
164
+ * Read existing .env.local file or return empty object
165
+ */
166
+ function readEnvLocal(projectPath) {
167
+ return parseEnvFile(path.join(projectPath, '.env.local'));
168
+ }
154
169
  /**
155
170
  * Update .env.local file with Next.js environment variables
171
+ * @deprecated Use updateEnvFiles() instead for per-environment URL support
156
172
  */
157
173
  function updateEnvLocal(projectPath, config) {
158
174
  const envPath = path.join(projectPath, '.env.local');
@@ -177,6 +193,76 @@ function updateEnvLocal(projectPath, config) {
177
193
  fs.writeFileSync(envPath, envContent.replace(/\r?\n/g, os.EOL), 'utf-8');
178
194
  console.log(`✅ Updated ${envPath}`);
179
195
  }
196
+ /**
197
+ * Write .env.development.local (dev URL) and .env.production.local (prod URL).
198
+ *
199
+ * Next.js loads .env.development.local for `next dev` and .env.production.local
200
+ * for `next build` / `next start`, so the correct EGDesk server address is picked
201
+ * up automatically without any runtime switching.
202
+ */
203
+ function updateEnvFiles(projectPath, config,
204
+ /** Tables discovered for the production environment. Falls back to config.tables when omitted. */
205
+ prodTables) {
206
+ function buildTableComments(tables) {
207
+ return [
208
+ '',
209
+ '# Available Tables',
210
+ `# Total tables: ${tables.length}`,
211
+ ...tables.map((table, index) => `# ${index + 1}. ${table.displayName} (${table.tableName}) - ${table.rowCount != null ? table.rowCount : '?'} rows, ${table.columnCount} columns`),
212
+ ''
213
+ ];
214
+ }
215
+ // EGDesk-managed keys — always overwritten with fresh values
216
+ const egdeskKeys = new Set([
217
+ 'NEXT_PUBLIC_EGDESK_API_URL',
218
+ 'NEXT_PUBLIC_EGDESK_API_KEY',
219
+ 'NEXT_PUBLIC_EGDESK_PROJECT_ID',
220
+ 'NEXT_PUBLIC_EGDESK_ENV',
221
+ ]);
222
+ function writeEnvFile(envPath, apiUrl, label, egdeskEnv, tables) {
223
+ // Preserve existing non-EGDesk vars
224
+ const existing = parseEnvFile(envPath);
225
+ const preserved = Object.fromEntries(Object.entries(existing).filter(([k]) => !egdeskKeys.has(k)));
226
+ const aiWarning = egdeskEnv === 'production' ? [
227
+ '# ============================================================',
228
+ '# ⚠️ AI ASSISTANT — DO NOT READ, EDIT, OR USE THIS FILE ⚠️',
229
+ '# This is the PRODUCTION environment configuration.',
230
+ '# AI must only work with the development environment.',
231
+ '# Never query, reference, or modify production data.',
232
+ '# Changes to production are made by the developer, not AI.',
233
+ '# ============================================================',
234
+ '',
235
+ ] : [];
236
+ const vercelNote = egdeskEnv === 'production' && apiUrl.includes('tunneling-service')
237
+ ? [
238
+ '# Vercel: copy these vars to your Vercel project Environment Variables.',
239
+ '# API URL is the MCP tunnel root (/t/{tunnelId}) — NOT the /p/{project} Next.js URL.',
240
+ '',
241
+ ]
242
+ : [];
243
+ const lines = [
244
+ ...aiWarning,
245
+ ...vercelNote,
246
+ `# EGDesk User Data Configuration (${label})`,
247
+ `# Generated at: ${config.generatedAt}`,
248
+ '',
249
+ `NEXT_PUBLIC_EGDESK_API_URL=${apiUrl}`,
250
+ ...(config.egdeskProjectId ? [`NEXT_PUBLIC_EGDESK_PROJECT_ID=${config.egdeskProjectId}`] : []),
251
+ `NEXT_PUBLIC_EGDESK_ENV=${egdeskEnv}`,
252
+ ...(config.apiKey ? [`NEXT_PUBLIC_EGDESK_API_KEY=${config.apiKey}`] : []),
253
+ ...Object.entries(preserved).map(([k, v]) => `${k}=${v}`),
254
+ ...buildTableComments(tables)
255
+ ];
256
+ fs.writeFileSync(envPath, lines.join('\n').replace(/\r?\n/g, os.EOL), 'utf-8');
257
+ console.log(`✅ Updated ${envPath}`);
258
+ }
259
+ // .env.development.local — loaded by `next dev`
260
+ const devPath = path.join(projectPath, '.env.development.local');
261
+ writeEnvFile(devPath, config.baseUrl, 'development', 'development', config.tables);
262
+ // .env.production.local — loaded by `next build` / `next start`
263
+ const prodPath = path.join(projectPath, '.env.production.local');
264
+ writeEnvFile(prodPath, config.prodBaseUrl ?? config.baseUrl, 'production', 'production', prodTables ?? config.tables);
265
+ }
180
266
  /**
181
267
  * Generate TypeScript config file with table definitions
182
268
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egdesk/next-api-plugin",
3
- "version": "1.5.4",
3
+ "version": "1.5.6",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",