@egdesk/next-api-plugin 1.5.11 → 1.5.13

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.
@@ -146,6 +146,13 @@ function generateHelpers(projectPath, options = {}) {
146
146
  * Schema files:
147
147
  * - egdesk.schema.ts — committed seed schema (edit this; commit to git)
148
148
  * - egdesk.config.ts — auto-generated runtime snapshot (gitignored; do not edit)
149
+ *
150
+ * AI / external agents:
151
+ * - If egdesk-user-data MCP is connected (Claude Desktop / Antigravity / Cursor), prefer MCP tools
152
+ * for exploring My DB: user_data_list_projects → user_data_select_project → user_data_list_tables / query.
153
+ * - Check that EGDesk is running and MCP tools are actually available before relying on them.
154
+ * - For app code in this repo, keep using these helpers (queryTable, etc.) — MCP is optional for agents.
155
+ * - If MCP tools are missing/empty, fall back to helpers + EGDESK-README.md; ask the user to install MCP from EGDesk.
149
156
  */
150
157
 
151
158
  import { EGDESK_CONFIG } from './egdesk.config';
@@ -392,6 +399,16 @@ export async function getTableSchema(tableName: string) {
392
399
  return callUserDataTool('user_data_get_schema', { tableName });
393
400
  }
394
401
 
402
+ /**
403
+ * Get schemas for multiple tables in ONE call (preferred over repeated getTableSchema).
404
+ * Omit tableNames to fetch schemas for all tables.
405
+ */
406
+ export async function getTableSchemas(tableNames?: string[]) {
407
+ return callUserDataTool('user_data_get_schemas_batch', {
408
+ ...(tableNames?.length ? { tableNames } : {}),
409
+ });
410
+ }
411
+
395
412
  /**
396
413
  * Create a new table
397
414
  */
@@ -559,6 +576,190 @@ export async function getFileStats(tableName?: string) {
559
576
  });
560
577
  }
561
578
 
579
+ // ==========================================
580
+ // USER DATA CRON JOBS
581
+ // ==========================================
582
+
583
+ export type UserDataCronActionType = 'sync_config' | 'browser_recording' | 'backup' | 'script';
584
+ export type UserDataCronFrequencyType = 'daily' | 'weekly' | 'monthly' | 'custom' | 'cron';
585
+
586
+ export type UserDataCronActionPayload = {
587
+ syncConfigId?: string;
588
+ syncConfigName?: string;
589
+ testPath?: string;
590
+ testName?: string;
591
+ scriptPath?: string;
592
+ functionName?: string;
593
+ args?: unknown;
594
+ timeoutMs?: number;
595
+ cwd?: string;
596
+ };
597
+
598
+ export type CreateUserDataCronJobOptions = {
599
+ name: string;
600
+ actionType: UserDataCronActionType;
601
+ actionPayload?: UserDataCronActionPayload;
602
+ /** Flat alias for actionPayload.syncConfigId */
603
+ syncConfigId?: string;
604
+ syncConfigName?: string;
605
+ /** Flat alias for actionPayload.testPath */
606
+ testPath?: string;
607
+ testName?: string;
608
+ /** Flat alias for actionPayload.scriptPath (.js/.mjs/.cjs) */
609
+ scriptPath?: string;
610
+ functionName?: string;
611
+ args?: unknown;
612
+ timeoutMs?: number;
613
+ cwd?: string;
614
+ scheduledTime?: string;
615
+ /** Defaults to daily when omitted */
616
+ frequencyType?: UserDataCronFrequencyType;
617
+ dayOfWeek?: number;
618
+ dayOfMonth?: number;
619
+ customIntervalDays?: number;
620
+ cronExpression?: string;
621
+ enabled?: boolean;
622
+ };
623
+
624
+ export type UpdateUserDataCronJobOptions = Partial<CreateUserDataCronJobOptions> & {
625
+ jobId: string;
626
+ };
627
+
628
+ /** List UserData cron jobs for the active project+env */
629
+ export async function listUserDataCronJobs() {
630
+ return callUserDataTool('user_data_cron_list', {});
631
+ }
632
+
633
+ /** Get a UserData cron job by id */
634
+ export async function getUserDataCronJob(jobId: string) {
635
+ return callUserDataTool('user_data_cron_get', { jobId });
636
+ }
637
+
638
+ /** Create a UserData cron job (sync_config / browser_recording / backup) */
639
+ export async function createUserDataCronJob(options: CreateUserDataCronJobOptions) {
640
+ return callUserDataTool('user_data_cron_create', options);
641
+ }
642
+
643
+ /** Update a UserData cron job */
644
+ export async function updateUserDataCronJob(options: UpdateUserDataCronJobOptions) {
645
+ return callUserDataTool('user_data_cron_update', options);
646
+ }
647
+
648
+ /** Delete a UserData cron job */
649
+ export async function deleteUserDataCronJob(jobId: string) {
650
+ return callUserDataTool('user_data_cron_delete', { jobId });
651
+ }
652
+
653
+ /** Enable or pause a UserData cron job */
654
+ export async function toggleUserDataCronJob(jobId: string, enabled: boolean) {
655
+ return callUserDataTool('user_data_cron_toggle', { jobId, enabled });
656
+ }
657
+
658
+ /** Run a UserData cron job immediately */
659
+ export async function runUserDataCronJobNow(jobId: string) {
660
+ return callUserDataTool('user_data_cron_run_now', { jobId });
661
+ }
662
+
663
+ /** List execution history for a UserData cron job */
664
+ export async function listUserDataCronExecutions(jobId: string, limit?: number) {
665
+ return callUserDataTool('user_data_cron_executions', {
666
+ jobId,
667
+ ...(limit != null ? { limit } : {}),
668
+ });
669
+ }
670
+
671
+ /** Get UserData cron scheduler status */
672
+ export async function getUserDataCronStatus() {
673
+ return callUserDataTool('user_data_cron_status', {});
674
+ }
675
+
676
+ // ==========================================
677
+ // USER DATA QUEUE JOBS
678
+ // ==========================================
679
+
680
+ export type UserDataQueueActionType =
681
+ | 'sync_config'
682
+ | 'browser_recording'
683
+ | 'backup'
684
+ | 'script';
685
+
686
+ export type UserDataQueueActionPayload = UserDataCronActionPayload;
687
+
688
+ export type EnqueueUserDataQueueJobOptions = {
689
+ name?: string;
690
+ actionType: UserDataQueueActionType;
691
+ actionPayload?: UserDataQueueActionPayload;
692
+ syncConfigId?: string;
693
+ syncConfigName?: string;
694
+ testPath?: string;
695
+ testName?: string;
696
+ scriptPath?: string;
697
+ functionName?: string;
698
+ args?: unknown;
699
+ timeoutMs?: number;
700
+ cwd?: string;
701
+ priority?: number;
702
+ maxAttempts?: number;
703
+ runAfter?: string | null;
704
+ idempotencyKey?: string | null;
705
+ };
706
+
707
+ /** List UserData queue jobs for the active project+env */
708
+ export async function listUserDataQueueJobs(options?: {
709
+ status?: string;
710
+ limit?: number;
711
+ }) {
712
+ return callUserDataTool('user_data_queue_list', options || {});
713
+ }
714
+
715
+ /** Get a UserData queue job by id */
716
+ export async function getUserDataQueueJob(jobId: string) {
717
+ return callUserDataTool('user_data_queue_get', { jobId });
718
+ }
719
+
720
+ /** Enqueue a UserData job (sync_config / browser_recording / backup / script) */
721
+ export async function enqueueUserDataQueueJob(options: EnqueueUserDataQueueJobOptions) {
722
+ return callUserDataTool('user_data_queue_enqueue', options);
723
+ }
724
+
725
+ /** Cancel a pending UserData queue job */
726
+ export async function cancelUserDataQueueJob(jobId: string) {
727
+ return callUserDataTool('user_data_queue_cancel', { jobId });
728
+ }
729
+
730
+ /** Retry a failed/dead/cancelled UserData queue job */
731
+ export async function retryUserDataQueueJob(jobId: string) {
732
+ return callUserDataTool('user_data_queue_retry', { jobId });
733
+ }
734
+
735
+ /** Delete a UserData queue job */
736
+ export async function deleteUserDataQueueJob(jobId: string) {
737
+ return callUserDataTool('user_data_queue_delete', { jobId });
738
+ }
739
+
740
+ /** Run a UserData queue job immediately */
741
+ export async function runUserDataQueueJobNow(jobId: string) {
742
+ return callUserDataTool('user_data_queue_run_now', { jobId });
743
+ }
744
+
745
+ /** List attempt history for a UserData queue job */
746
+ export async function listUserDataQueueRuns(jobId: string, limit?: number) {
747
+ return callUserDataTool('user_data_queue_runs', {
748
+ jobId,
749
+ ...(limit != null ? { limit } : {}),
750
+ });
751
+ }
752
+
753
+ /** Get UserData queue counts by status */
754
+ export async function getUserDataQueueStats() {
755
+ return callUserDataTool('user_data_queue_stats', {});
756
+ }
757
+
758
+ /** Get UserData queue worker status */
759
+ export async function getUserDataQueueStatus() {
760
+ return callUserDataTool('user_data_queue_status', {});
761
+ }
762
+
562
763
  // ==========================================
563
764
  // USER DATA REAL-TIME SUBSCRIPTIONS
564
765
  // ==========================================
@@ -605,7 +806,16 @@ export function onUserDataChanged(
605
806
 
606
807
  const apiUrl = EGDESK_CONFIG.apiUrl || '';
607
808
  const apiKey = EGDESK_CONFIG.apiKey || '';
608
- const sseUrl = apiKey ? \`\${apiUrl}/user-data/sse?key=\${encodeURIComponent(apiKey)}\` : \`\${apiUrl}/user-data/sse\`;
809
+ const projectId =
810
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_PROJECT_ID) || '';
811
+ const egdeskEnv =
812
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_ENV) || '';
813
+ const sseParams = new URLSearchParams();
814
+ if (apiKey) sseParams.set('key', apiKey);
815
+ if (projectId) sseParams.set('egdeskId', projectId);
816
+ if (egdeskEnv) sseParams.set('environment', egdeskEnv);
817
+ const sseQuery = sseParams.toString();
818
+ const sseUrl = \`\${apiUrl}/user-data/sse\${sseQuery ? \`?\${sseQuery}\` : ''}\`;
609
819
  const es = new EventSource(sseUrl);
610
820
 
611
821
  es.addEventListener('message', (e: MessageEvent) => {
@@ -2359,6 +2569,242 @@ export async function deletePageIndexDocument(docId: string) {
2359
2569
  return callPageIndexTool('pageindex_delete_document', { doc_id: docId });
2360
2570
  }
2361
2571
 
2572
+ // ==========================================
2573
+ // Drive (MCP) — change watch / poll / events
2574
+ // ==========================================
2575
+
2576
+ /**
2577
+ * Call EGDesk Drive MCP tool (Google Drive change notifications + poll).
2578
+ *
2579
+ * Auth on EGDesk: GOOGLE_SERVICE_ACCOUNT_JSON or Google Workspace sign-in.
2580
+ * Share target folders with the service account when using SA credentials.
2581
+ *
2582
+ * - Server: \`POST {apiUrl}/drive/tools/call\`
2583
+ * - Client: \`POST /__drive_proxy\` (see proxy.ts / middleware)
2584
+ * - Webhook (Google push, not this helper): \`POST {apiUrl}/drive/webhook\`
2585
+ */
2586
+ export async function callDriveTool(
2587
+ toolName: string,
2588
+ args: Record<string, any> = {}
2589
+ ): Promise<any> {
2590
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2591
+
2592
+ const isServer = typeof window === 'undefined';
2593
+
2594
+ let response: Response;
2595
+ if (isServer) {
2596
+ const apiUrl =
2597
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2598
+ EGDESK_CONFIG.apiUrl;
2599
+ response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
2600
+ method: 'POST',
2601
+ headers: buildServerEgdeskHeaders(),
2602
+ body
2603
+ });
2604
+ } else {
2605
+ response = await apiFetch('/__drive_proxy', {
2606
+ method: 'POST',
2607
+ headers: { 'Content-Type': 'application/json' },
2608
+ body
2609
+ });
2610
+ }
2611
+
2612
+ return parseEgdeskMcpToolResponse(response);
2613
+ }
2614
+
2615
+ /** Check Drive auth (service account / Google OAuth) */
2616
+ export async function getDriveAuthStatus() {
2617
+ return callDriveTool('drive_auth_status', {});
2618
+ }
2619
+
2620
+ /**
2621
+ * Start Google OAuth for Drive. Returns { status:'pending', authUrl } immediately.
2622
+ * Open authUrl in the browser, then poll getDriveAuthStatus() until connected.
2623
+ */
2624
+ export async function startDriveAuthLogin(options: {
2625
+ openWindow?: boolean;
2626
+ forceConsent?: boolean;
2627
+ } = {}) {
2628
+ return callDriveTool('drive_auth_login', options);
2629
+ }
2630
+
2631
+ /** Initialize Drive sync (page token + target folders; optional snapshot) */
2632
+ export async function initDriveSync(options: {
2633
+ folderIds: string[];
2634
+ snapshot?: boolean;
2635
+ downloadPath?: string;
2636
+ reset?: boolean;
2637
+ }) {
2638
+ return callDriveTool('drive_init', options);
2639
+ }
2640
+
2641
+ /** Start drive.changes.watch; webhook = {webhookBaseUrl}/drive/webhook */
2642
+ export async function watchDriveChanges(options: {
2643
+ webhookBaseUrl: string;
2644
+ ttlSeconds?: number;
2645
+ }) {
2646
+ return callDriveTool('drive_watch', options);
2647
+ }
2648
+
2649
+ /** Stop the active Drive watch channel */
2650
+ export async function stopDriveWatch() {
2651
+ return callDriveTool('drive_stop', {});
2652
+ }
2653
+
2654
+ /** One-shot poll via changes.list (no tunnel needed) */
2655
+ export async function pollDriveChanges(options: { download?: boolean } = {}) {
2656
+ return callDriveTool('drive_poll', options);
2657
+ }
2658
+
2659
+ /** Keep watching saved folders on an interval (persists + auto-resumes) */
2660
+ export async function startDrivePollLoop(options: {
2661
+ intervalSeconds?: number;
2662
+ download?: boolean;
2663
+ } = {}) {
2664
+ return callDriveTool('drive_start_poll_loop', options);
2665
+ }
2666
+
2667
+ /** Stop continuous poll loop (folders/page token stay saved) */
2668
+ export async function stopDrivePollLoop() {
2669
+ return callDriveTool('drive_stop_poll_loop', {});
2670
+ }
2671
+
2672
+ /** Sync state, channel expiry, and event counts */
2673
+ export async function getDriveStatus() {
2674
+ return callDriveTool('drive_status', {});
2675
+ }
2676
+
2677
+ /** List currently watched folders with names and Drive URLs */
2678
+ export async function listDriveWatchedFolders() {
2679
+ return callDriveTool('drive_list_watched_folders', {});
2680
+ }
2681
+
2682
+ /** List recent drive_file_events */
2683
+ export async function listDriveEvents(options: {
2684
+ limit?: number;
2685
+ downloadedOnly?: boolean;
2686
+ since?: string;
2687
+ } = {}) {
2688
+ return callDriveTool('drive_list_events', options);
2689
+ }
2690
+
2691
+ /** Replace monitored folder IDs without resetting the page token */
2692
+ export async function setDriveTargetFolders(folderIds: string[]) {
2693
+ return callDriveTool('drive_set_target_folders', { folderIds });
2694
+ }
2695
+
2696
+ // ==========================================
2697
+ // Knowledge Wiki (MCP) — Obsidian + wikiHow
2698
+ // ==========================================
2699
+
2700
+ /**
2701
+ * Call EGDesk Knowledge Wiki MCP tool (Obsidian vault index + wikiHow guides).
2702
+ *
2703
+ * - Server: \`POST {apiUrl}/knowledge-wiki/tools/call\`
2704
+ * - Client: \`POST /__knowledge_wiki_proxy\` (see proxy.ts / middleware)
2705
+ */
2706
+ export async function callKnowledgeWikiTool(
2707
+ toolName: string,
2708
+ args: Record<string, any> = {}
2709
+ ): Promise<any> {
2710
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2711
+
2712
+ const isServer = typeof window === 'undefined';
2713
+
2714
+ let response: Response;
2715
+ if (isServer) {
2716
+ const apiUrl =
2717
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2718
+ EGDESK_CONFIG.apiUrl;
2719
+ response = await fetch(\`\${apiUrl}/knowledge-wiki/tools/call\`, {
2720
+ method: 'POST',
2721
+ headers: buildServerEgdeskHeaders(),
2722
+ body
2723
+ });
2724
+ } else {
2725
+ response = await apiFetch('/__knowledge_wiki_proxy', {
2726
+ method: 'POST',
2727
+ headers: { 'Content-Type': 'application/json' },
2728
+ body
2729
+ });
2730
+ }
2731
+
2732
+ return parseEgdeskMcpToolResponse(response);
2733
+ }
2734
+
2735
+ export async function getKnowledgeWikiStatus() {
2736
+ return callKnowledgeWikiTool('knowledge_wiki_status', {});
2737
+ }
2738
+
2739
+ export async function searchKnowledgeWiki(
2740
+ query: string,
2741
+ options: { limit?: number; sources?: Array<'obsidian' | 'wikihow'> } = {}
2742
+ ) {
2743
+ return callKnowledgeWikiTool('knowledge_wiki_search', { query, ...options });
2744
+ }
2745
+
2746
+ export async function setObsidianVault(vaultPath: string) {
2747
+ return callKnowledgeWikiTool('obsidian_set_vault', { vaultPath });
2748
+ }
2749
+
2750
+ export async function indexObsidianVault(options: { vaultPath?: string } = {}) {
2751
+ return callKnowledgeWikiTool('obsidian_index', options);
2752
+ }
2753
+
2754
+ export async function listObsidianNotes(options: {
2755
+ limit?: number;
2756
+ offset?: number;
2757
+ tag?: string;
2758
+ } = {}) {
2759
+ return callKnowledgeWikiTool('obsidian_list_notes', options);
2760
+ }
2761
+
2762
+ export async function getObsidianNote(options: {
2763
+ path?: string;
2764
+ title?: string;
2765
+ id?: string;
2766
+ }) {
2767
+ return callKnowledgeWikiTool('obsidian_get_note', options);
2768
+ }
2769
+
2770
+ export async function searchObsidianNotes(query: string, limit?: number) {
2771
+ return callKnowledgeWikiTool('obsidian_search', { query, limit });
2772
+ }
2773
+
2774
+ export async function getObsidianBacklinks(title: string, limit?: number) {
2775
+ return callKnowledgeWikiTool('obsidian_backlinks', { title, limit });
2776
+ }
2777
+
2778
+ export async function listObsidianTags() {
2779
+ return callKnowledgeWikiTool('obsidian_list_tags', {});
2780
+ }
2781
+
2782
+ export async function searchWikiHow(
2783
+ query: string,
2784
+ options: { lang?: string; limit?: number } = {}
2785
+ ) {
2786
+ return callKnowledgeWikiTool('wikihow_search', { query, ...options });
2787
+ }
2788
+
2789
+ export async function getWikiHowGuide(
2790
+ titleOrUrl: string,
2791
+ options: { lang?: string; cache?: boolean } = {}
2792
+ ) {
2793
+ return callKnowledgeWikiTool('wikihow_get_guide', { titleOrUrl, ...options });
2794
+ }
2795
+
2796
+ export async function listCachedWikiHow(options: {
2797
+ limit?: number;
2798
+ offset?: number;
2799
+ lang?: string;
2800
+ } = {}) {
2801
+ return callKnowledgeWikiTool('wikihow_list_cached', options);
2802
+ }
2803
+
2804
+ export async function searchCachedWikiHow(query: string, limit?: number) {
2805
+ return callKnowledgeWikiTool('wikihow_search_cached', { query, limit });
2806
+ }
2807
+
2362
2808
  // ==========================================
2363
2809
  // EGDesk Config (MCP) — Gemini / Google API keys
2364
2810
  // ==========================================
@@ -264,4 +264,32 @@ export const config = {
264
264
  `;
265
265
  fs.writeFileSync(middlewarePath, middlewareContent.replace(/\r?\n/g, os.EOL), 'utf-8');
266
266
  console.log(`✅ Generated ${middlewarePath}`);
267
+ // Next.js 16+ errors if both middleware.ts and proxy.ts exist.
268
+ removeConflictingInterceptorFiles(projectPath, middlewarePath);
269
+ }
270
+ function removeFileIfExists(filePath) {
271
+ if (!fs.existsSync(filePath))
272
+ return;
273
+ try {
274
+ fs.unlinkSync(filePath);
275
+ console.log(`🗑️ Removed conflicting ${path.basename(filePath)}: ${filePath}`);
276
+ }
277
+ catch (err) {
278
+ console.warn(`⚠️ Could not remove ${filePath}:`, err);
279
+ }
280
+ }
281
+ function removeConflictingInterceptorFiles(projectPath, keepPath) {
282
+ const candidates = [
283
+ path.join(projectPath, 'proxy.ts'),
284
+ path.join(projectPath, 'src', 'proxy.ts'),
285
+ path.join(projectPath, 'proxy.js'),
286
+ path.join(projectPath, 'src', 'proxy.js'),
287
+ path.join(projectPath, 'middleware.ts'),
288
+ path.join(projectPath, 'src', 'middleware.ts'),
289
+ ];
290
+ for (const filePath of candidates) {
291
+ if (path.resolve(filePath) === path.resolve(keepPath))
292
+ continue;
293
+ removeFileIfExists(filePath);
294
+ }
267
295
  }
@@ -75,7 +75,7 @@ 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, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __seo_proxy, __ssl_proxy, __local_agent_proxy, __pageindex_proxy, __egdesk_config_proxy, __ai_caller_proxy, and __kakao_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, __pageindex_proxy, __drive_proxy, __knowledge_wiki_proxy, __egdesk_config_proxy, __ai_caller_proxy, and __kakao_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
@@ -318,6 +318,50 @@ export async function proxy(request: NextRequest) {
318
318
  }
319
319
  }
320
320
 
321
+ if (pathname.includes('__drive_proxy')) {
322
+ try {
323
+ const body = await request.text();
324
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
325
+
326
+ const response = await fetch(\`\${apiUrl}/drive/tools/call\`, {
327
+ method: 'POST',
328
+ headers: buildEgdeskHeaders(),
329
+ body,
330
+ });
331
+
332
+ const result = await response.json();
333
+
334
+ return NextResponse.json(result, { status: response.status });
335
+ } catch (error: any) {
336
+ return NextResponse.json(
337
+ { error: 'Proxy error', message: error.message },
338
+ { status: 500 }
339
+ );
340
+ }
341
+ }
342
+
343
+ if (pathname.includes('__knowledge_wiki_proxy')) {
344
+ try {
345
+ const body = await request.text();
346
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
347
+
348
+ const response = await fetch(\`\${apiUrl}/knowledge-wiki/tools/call\`, {
349
+ method: 'POST',
350
+ headers: buildEgdeskHeaders(),
351
+ body,
352
+ });
353
+
354
+ const result = await response.json();
355
+
356
+ return NextResponse.json(result, { status: response.status });
357
+ } catch (error: any) {
358
+ return NextResponse.json(
359
+ { error: 'Proxy error', message: error.message },
360
+ { status: 500 }
361
+ );
362
+ }
363
+ }
364
+
321
365
  if (pathname.includes('__kakao_proxy')) {
322
366
  try {
323
367
  const body = await request.text();
@@ -392,7 +436,7 @@ export const config = {
392
436
  matcher: [
393
437
  /*
394
438
  * Match all paths except static assets
395
- * 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 / __egdesk_config_proxy / __ai_caller_proxy / __kakao_proxy
439
+ * 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 / __drive_proxy / __knowledge_wiki_proxy / __egdesk_config_proxy / __ai_caller_proxy / __kakao_proxy
396
440
  */
397
441
  '/:path*',
398
442
  ],
@@ -400,4 +444,42 @@ export const config = {
400
444
  `;
401
445
  fs.writeFileSync(proxyPath, proxyContent.replace(/\r?\n/g, os.EOL), 'utf-8');
402
446
  console.log(`✅ Generated ${proxyPath}`);
447
+ // Next.js 16+ errors if both middleware.ts and proxy.ts exist.
448
+ removeConflictingInterceptorFiles(projectPath, 'proxy', proxyPath);
449
+ }
450
+ function removeFileIfExists(filePath, label) {
451
+ if (!fs.existsSync(filePath))
452
+ return;
453
+ try {
454
+ fs.unlinkSync(filePath);
455
+ console.log(`🗑️ Removed conflicting ${label}: ${filePath}`);
456
+ }
457
+ catch (err) {
458
+ console.warn(`⚠️ Could not remove ${filePath}:`, err);
459
+ }
460
+ }
461
+ /** Drop the other interceptor convention (and duplicates in root vs src/). */
462
+ function removeConflictingInterceptorFiles(projectPath, keep, keepPath) {
463
+ const candidates = keep === 'proxy'
464
+ ? [
465
+ path.join(projectPath, 'middleware.ts'),
466
+ path.join(projectPath, 'src', 'middleware.ts'),
467
+ path.join(projectPath, 'middleware.js'),
468
+ path.join(projectPath, 'src', 'middleware.js'),
469
+ path.join(projectPath, 'proxy.ts'),
470
+ path.join(projectPath, 'src', 'proxy.ts'),
471
+ ]
472
+ : [
473
+ path.join(projectPath, 'proxy.ts'),
474
+ path.join(projectPath, 'src', 'proxy.ts'),
475
+ path.join(projectPath, 'proxy.js'),
476
+ path.join(projectPath, 'src', 'proxy.js'),
477
+ path.join(projectPath, 'middleware.ts'),
478
+ path.join(projectPath, 'src', 'middleware.ts'),
479
+ ];
480
+ for (const filePath of candidates) {
481
+ if (path.resolve(filePath) === path.resolve(keepPath))
482
+ continue;
483
+ removeFileIfExists(filePath, path.basename(filePath));
484
+ }
403
485
  }
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * The minimum EGDesk app version this plugin version is compatible with.
9
9
  * The app checks this at setup time and warns on mismatch.
10
10
  */
11
- export declare const COMPATIBLE_APP_VERSION = "1.4.16";
11
+ export declare const COMPATIBLE_APP_VERSION = "1.4.24";
12
12
  export interface SetupOptions {
13
13
  egdeskUrl?: string;
14
14
  /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
@@ -37,7 +37,7 @@ export declare function detectNextUseProxy(projectPath: string): boolean;
37
37
  */
38
38
  export declare function setupNextApiPlugin(projectPath: string, options?: SetupOptions): Promise<void>;
39
39
  export type { UserDataTable, UserDataConfig } from './setup-userdata';
40
- export { discoverTables } from './setup-userdata';
40
+ export { discoverTables, generateConfigFile, loadTablesFromSchemaFile, updateEnvFiles } from './setup-userdata';
41
41
  export { generateMiddleware } from './generate-middleware';
42
42
  export { generateProxy } from './generate-proxy';
43
43
  export { generateHelpers, generateSchemaFile, ensureSchemaFile, formatEgdeskSchemaFileContent } from './generate-helpers';
package/dist/index.js CHANGED
@@ -39,14 +39,14 @@ var __importStar = (this && this.__importStar) || (function () {
39
39
  };
40
40
  })();
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.generateApiWrapper = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateProxy = exports.generateMiddleware = exports.discoverTables = exports.COMPATIBLE_APP_VERSION = void 0;
42
+ exports.generateApiWrapper = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateProxy = exports.generateMiddleware = exports.updateEnvFiles = exports.loadTablesFromSchemaFile = exports.generateConfigFile = exports.discoverTables = exports.COMPATIBLE_APP_VERSION = void 0;
43
43
  exports.detectNextUseProxy = detectNextUseProxy;
44
44
  exports.setupNextApiPlugin = setupNextApiPlugin;
45
45
  /**
46
46
  * The minimum EGDesk app version this plugin version is compatible with.
47
47
  * The app checks this at setup time and warns on mismatch.
48
48
  */
49
- exports.COMPATIBLE_APP_VERSION = '1.4.16';
49
+ exports.COMPATIBLE_APP_VERSION = '1.4.24';
50
50
  const fs = __importStar(require("fs"));
51
51
  const path = __importStar(require("path"));
52
52
  const setup_userdata_1 = require("./setup-userdata");
@@ -118,21 +118,41 @@ async function setupNextApiPlugin(projectPath, options = {}) {
118
118
  const { egdeskUrl = 'http://localhost:8080', prodEgdeskUrl, discoveryUrl, egdeskProjectId, apiKey, useProxy } = options;
119
119
  const resolvedUseProxy = useProxy ?? detectNextUseProxy(projectPath);
120
120
  console.log('🔍 Discovering EGDesk user-data tables...');
121
+ let devTables = [];
122
+ let prodTables = [];
123
+ let apiKeyNames = [];
124
+ let usedSchemaFallback = false;
121
125
  try {
122
- const [devTables, prodTables, apiKeyNames] = await Promise.all([
126
+ [devTables, prodTables, apiKeyNames] = await Promise.all([
123
127
  (0, setup_userdata_1.discoverTables)(discoveryUrl ?? egdeskUrl, apiKey, egdeskProjectId, 'development'),
124
128
  (0, setup_userdata_1.discoverTables)(discoveryUrl ?? egdeskUrl, apiKey, egdeskProjectId, 'production'),
125
129
  discoverApiKeyNames(discoveryUrl ?? egdeskUrl, apiKey, egdeskProjectId),
126
130
  ]);
131
+ }
132
+ catch (error) {
133
+ console.error('❌ Live table discovery failed:', error);
134
+ console.warn('⚠️ Falling back to egdesk.schema.ts so egdesk.config.ts / helpers are still generated');
135
+ devTables = (0, setup_userdata_1.loadTablesFromSchemaFile)(projectPath);
136
+ prodTables = [];
137
+ usedSchemaFallback = true;
138
+ try {
139
+ apiKeyNames = await discoverApiKeyNames(discoveryUrl ?? egdeskUrl, apiKey, egdeskProjectId);
140
+ }
141
+ catch {
142
+ apiKeyNames = [];
143
+ }
144
+ }
145
+ try {
127
146
  if (devTables.length === 0) {
128
147
  console.warn('⚠️ No tables found. Import data in EGDesk first.');
129
148
  console.log('');
130
149
  console.log('Generating files anyway with empty table list...');
131
150
  }
132
151
  else {
133
- console.log(`✅ Found ${devTables.length} dev table(s), ${prodTables.length} prod table(s):`);
152
+ const source = usedSchemaFallback ? 'schema fallback' : 'live discovery';
153
+ console.log(`✅ Found ${devTables.length} dev table(s), ${prodTables.length} prod table(s) (${source}):`);
134
154
  devTables.forEach((table, index) => {
135
- console.log(` ${index + 1}. ${table.displayName} (${table.rowCount} rows)`);
155
+ console.log(` ${index + 1}. ${table.displayName} (${table.rowCount ?? 0} rows)`);
136
156
  });
137
157
  }
138
158
  if (apiKeyNames.length > 0) {
@@ -200,6 +220,9 @@ async function setupNextApiPlugin(projectPath, options = {}) {
200
220
  }
201
221
  var setup_userdata_2 = require("./setup-userdata");
202
222
  Object.defineProperty(exports, "discoverTables", { enumerable: true, get: function () { return setup_userdata_2.discoverTables; } });
223
+ Object.defineProperty(exports, "generateConfigFile", { enumerable: true, get: function () { return setup_userdata_2.generateConfigFile; } });
224
+ Object.defineProperty(exports, "loadTablesFromSchemaFile", { enumerable: true, get: function () { return setup_userdata_2.loadTablesFromSchemaFile; } });
225
+ Object.defineProperty(exports, "updateEnvFiles", { enumerable: true, get: function () { return setup_userdata_2.updateEnvFiles; } });
203
226
  var generate_middleware_2 = require("./generate-middleware");
204
227
  Object.defineProperty(exports, "generateMiddleware", { enumerable: true, get: function () { return generate_middleware_2.generateMiddleware; } });
205
228
  var generate_proxy_2 = require("./generate-proxy");
@@ -48,6 +48,11 @@ export declare function updateEnvLocal(projectPath: string, config: UserDataConf
48
48
  export declare function updateEnvFiles(projectPath: string, config: UserDataConfig,
49
49
  /** Tables discovered for the production environment. Falls back to config.tables when omitted. */
50
50
  prodTables?: UserDataTable[]): void;
51
+ /**
52
+ * Parse TABLES from egdesk.schema.ts (or a leftover egdesk.config.ts) when
53
+ * live discovery fails. Returns [] if the file is missing or unparseable.
54
+ */
55
+ export declare function loadTablesFromSchemaFile(projectPath: string): UserDataTable[];
51
56
  /**
52
57
  * Generate TypeScript config file with table definitions
53
58
  */
@@ -43,6 +43,7 @@ exports.discoverTables = discoverTables;
43
43
  exports.readEnvLocal = readEnvLocal;
44
44
  exports.updateEnvLocal = updateEnvLocal;
45
45
  exports.updateEnvFiles = updateEnvFiles;
46
+ exports.loadTablesFromSchemaFile = loadTablesFromSchemaFile;
46
47
  exports.generateConfigFile = generateConfigFile;
47
48
  const fs = __importStar(require("fs"));
48
49
  const path = __importStar(require("path"));
@@ -262,6 +263,78 @@ prodTables) {
262
263
  const prodPath = path.join(projectPath, '.env.production.local');
263
264
  writeEnvFile(prodPath, config.prodBaseUrl ?? config.baseUrl, 'production', 'production', prodTables ?? config.tables);
264
265
  }
266
+ /**
267
+ * Parse TABLES from egdesk.schema.ts (or a leftover egdesk.config.ts) when
268
+ * live discovery fails. Returns [] if the file is missing or unparseable.
269
+ */
270
+ function loadTablesFromSchemaFile(projectPath) {
271
+ const candidates = [
272
+ path.join(projectPath, 'egdesk.schema.ts'),
273
+ path.join(projectPath, 'egdesk.config.ts'),
274
+ ];
275
+ for (const filePath of candidates) {
276
+ if (!fs.existsSync(filePath))
277
+ continue;
278
+ try {
279
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
280
+ const tablesMatch = fileContent.match(/export\s+const\s+TABLES\s*=\s*\{([\s\S]*?)\}\s*as\s+const/);
281
+ if (!tablesMatch)
282
+ continue;
283
+ const body = tablesMatch[1];
284
+ const tables = [];
285
+ const entryRegex = /\w+\s*:\s*\{/g;
286
+ let match;
287
+ while ((match = entryRegex.exec(body)) !== null) {
288
+ const start = match.index + match[0].length - 1;
289
+ let depth = 0;
290
+ let end = -1;
291
+ for (let i = start; i < body.length; i++) {
292
+ if (body[i] === '{')
293
+ depth++;
294
+ else if (body[i] === '}') {
295
+ depth--;
296
+ if (depth === 0) {
297
+ end = i;
298
+ break;
299
+ }
300
+ }
301
+ }
302
+ if (end === -1)
303
+ continue;
304
+ const block = body.slice(start + 1, end);
305
+ const nameMatch = block.match(/\bname\s*:\s*['"`]([^'"`]+)['"`]/);
306
+ const displayNameMatch = block.match(/\bdisplayName\s*:\s*['"`]([^'"`]+)['"`]/);
307
+ const columnsMatch = block.match(/\bcolumns\s*:\s*\[([\s\S]*?)\]/);
308
+ if (!nameMatch || !displayNameMatch || !columnsMatch)
309
+ continue;
310
+ const columns = [];
311
+ const colRegex = /['"`]([^'"`]+)['"`]/g;
312
+ let colMatch;
313
+ while ((colMatch = colRegex.exec(columnsMatch[1])) !== null) {
314
+ columns.push(colMatch[1]);
315
+ }
316
+ if (columns.length === 0)
317
+ continue;
318
+ tables.push({
319
+ id: nameMatch[1],
320
+ tableName: nameMatch[1],
321
+ displayName: displayNameMatch[1],
322
+ columnCount: columns.length,
323
+ columns,
324
+ rowCount: 0,
325
+ });
326
+ }
327
+ if (tables.length > 0) {
328
+ console.log(`📋 Loaded ${tables.length} table(s) from ${path.basename(filePath)} (discovery fallback)`);
329
+ return tables;
330
+ }
331
+ }
332
+ catch (err) {
333
+ console.warn(`⚠️ Failed to parse ${filePath} for discovery fallback:`, err);
334
+ }
335
+ }
336
+ return [];
337
+ }
265
338
  /**
266
339
  * Generate TypeScript config file with table definitions
267
340
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egdesk/next-api-plugin",
3
- "version": "1.5.11",
3
+ "version": "1.5.13",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",