d1s 0.2.11 → 0.2.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.
- package/dist/.next/.next/BUILD_ID +1 -1
- package/dist/.next/.next/app-build-manifest.json +28 -28
- package/dist/.next/.next/app-path-routes-manifest.json +1 -1
- package/dist/.next/.next/build-manifest.json +3 -3
- package/dist/.next/.next/cache/.rscinfo +1 -1
- package/dist/.next/.next/cache/.tsbuildinfo +1 -1
- package/dist/.next/.next/cache/webpack/client-production/0.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/1.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/10.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/11.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/12.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/2.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/3.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/4.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/5.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/6.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/7.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/8.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/9.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/index.pack +0 -0
- package/dist/.next/.next/cache/webpack/client-production/index.pack.old +0 -0
- package/dist/.next/.next/cache/webpack/edge-server-production/index.pack +0 -0
- package/dist/.next/.next/cache/webpack/server-production/0.pack +0 -0
- package/dist/.next/.next/cache/webpack/server-production/1.pack +0 -0
- package/dist/.next/.next/cache/webpack/server-production/2.pack +0 -0
- package/dist/.next/.next/cache/webpack/server-production/3.pack +0 -0
- package/dist/.next/.next/cache/webpack/server-production/index.pack +0 -0
- package/dist/.next/.next/cache/webpack/server-production/index.pack.old +0 -0
- package/dist/.next/.next/next-minimal-server.js.nft.json +1 -1
- package/dist/.next/.next/next-server.js.nft.json +1 -1
- package/dist/.next/.next/prerender-manifest.json +1 -1
- package/dist/.next/.next/required-server-files.json +1 -1
- package/dist/.next/.next/server/app/_not-found/page.js +1 -1
- package/dist/.next/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/dist/.next/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/_not-found.html +1 -1
- package/dist/.next/.next/server/app/_not-found.rsc +4 -4
- package/dist/.next/.next/server/app/api/cloudflare/route.js +1 -1
- package/dist/.next/.next/server/app/api/cloudflare/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/databases/route.js +1 -1
- package/dist/.next/.next/server/app/api/databases/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/migrations/sync/route.js +5 -5
- package/dist/.next/.next/server/app/api/migrations/sync/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/migrations/sync-files/route.js +3 -3
- package/dist/.next/.next/server/app/api/migrations/sync-files/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/pull-data/confirm/route.js +1 -1
- package/dist/.next/.next/server/app/api/pull-data/confirm/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/pull-remote/confirm/route.js +2 -2
- package/dist/.next/.next/server/app/api/pull-remote/confirm/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/pull-remote/preview/route.js +4 -4
- package/dist/.next/.next/server/app/api/pull-remote/preview/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/push-remote/confirm/route.js +5 -5
- package/dist/.next/.next/server/app/api/push-remote/confirm/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/push-remote/preview/route.js +4 -4
- package/dist/.next/.next/server/app/api/push-remote/preview/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/query/route.js +3 -3
- package/dist/.next/.next/server/app/api/query/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/tables/[name]/route.js +5 -5
- package/dist/.next/.next/server/app/api/tables/[name]/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/tables/route.js +2 -2
- package/dist/.next/.next/server/app/api/tables/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/api/update/route.js +1 -1
- package/dist/.next/.next/server/app/api/update/route_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app/index.html +2 -2
- package/dist/.next/.next/server/app/index.rsc +5 -5
- package/dist/.next/.next/server/app/page.js +7 -7
- package/dist/.next/.next/server/app/page.js.nft.json +1 -1
- package/dist/.next/.next/server/app/page_client-reference-manifest.js +1 -1
- package/dist/.next/.next/server/app-paths-manifest.json +1 -1
- package/dist/.next/.next/server/chunks/226.js +12 -12
- package/dist/.next/.next/server/chunks/391.js +1 -1
- package/dist/.next/.next/server/chunks/572.js +1 -0
- package/dist/.next/.next/server/chunks/992.js +3 -3
- package/dist/.next/.next/server/middleware-build-manifest.js +1 -1
- package/dist/.next/.next/server/next-font-manifest.js +1 -1
- package/dist/.next/.next/server/next-font-manifest.json +1 -1
- package/dist/.next/.next/server/pages/404.html +1 -1
- package/dist/.next/.next/server/pages/500.html +1 -1
- package/dist/.next/.next/server/server-reference-manifest.json +1 -1
- package/dist/.next/.next/static/chunks/{576-c4daf274bb6469a1.js → 576-18a2209e1ed26aad.js} +1 -1
- package/dist/.next/.next/static/chunks/{92-c4466e0f1ca8a3a8.js → 92-5f7522943fcb72a8.js} +1 -1
- package/dist/.next/.next/static/chunks/app/{layout-be6ee67cf0c92654.js → layout-40ec07d04681ba81.js} +1 -1
- package/dist/.next/.next/static/chunks/app/page-f05cd0fc436bf9bc.js +1 -0
- package/dist/.next/.next/static/chunks/app/page-f2bc307c0d8acdaa.js +1 -0
- package/dist/.next/.next/static/chunks/{main-app-fa35024de9bd9284.js → main-app-4506e88db72db4b7.js} +1 -1
- package/dist/.next/.next/static/css/{9f6c25c5400f83d3.css → 7c16f57d325d0d7d.css} +1 -1
- package/dist/.next/.next/static/ejYPqJ2kVicVp5EFWOZIC/_buildManifest.js +1 -0
- package/dist/.next/.next/static/ejYPqJ2kVicVp5EFWOZIC/_ssgManifest.js +1 -0
- package/dist/.next/.next/static/gABGrAoO8IPArDo_Ns_7g/_buildManifest.js +1 -0
- package/dist/.next/.next/static/gABGrAoO8IPArDo_Ns_7g/_ssgManifest.js +1 -0
- package/dist/.next/.next/static/gh-QfIUVo4FTTduYCVKT6/_buildManifest.js +1 -0
- package/dist/.next/.next/static/gh-QfIUVo4FTTduYCVKT6/_ssgManifest.js +1 -0
- package/dist/.next/.next/static/media/8d697b304b401681-s.woff2 +0 -0
- package/dist/.next/.next/static/media/9610d9e46709d722-s.woff2 +0 -0
- package/dist/.next/.next/static/thaCy2qVeNqYYhdayr13C/_buildManifest.js +1 -0
- package/dist/.next/.next/static/thaCy2qVeNqYYhdayr13C/_ssgManifest.js +1 -0
- package/dist/.next/.next/static/ybCx6L6gHqtODbKmlhU-d/_buildManifest.js +1 -0
- package/dist/.next/.next/static/ybCx6L6gHqtODbKmlhU-d/_ssgManifest.js +1 -0
- package/dist/.next/.next/trace +3 -3
- package/dist/.next/.next/types/app/api/cloudflare/route.ts +1 -1
- package/dist/.next/.next/types/app/api/databases/route.ts +1 -1
- package/dist/.next/.next/types/app/api/migrations/sync/route.ts +1 -1
- package/dist/.next/.next/types/app/api/migrations/sync-files/route.ts +1 -1
- package/dist/.next/.next/types/app/api/pull-data/confirm/route.ts +1 -1
- package/dist/.next/.next/types/app/api/pull-remote/confirm/route.ts +1 -1
- package/dist/.next/.next/types/app/api/pull-remote/preview/route.ts +1 -1
- package/dist/.next/.next/types/app/api/push-remote/confirm/route.ts +1 -1
- package/dist/.next/.next/types/app/api/push-remote/preview/route.ts +1 -1
- package/dist/.next/.next/types/app/api/query/route.ts +1 -1
- package/dist/.next/.next/types/app/api/tables/[name]/route.ts +1 -1
- package/dist/.next/.next/types/app/api/tables/route.ts +1 -1
- package/dist/.next/.next/types/app/api/update/route.ts +1 -1
- package/dist/.next/.next/types/app/page.ts +1 -1
- package/dist/.next/BUILD_ID +1 -1
- package/dist/.next/app-build-manifest.json +28 -28
- package/dist/.next/app-path-routes-manifest.json +1 -1
- package/dist/.next/build-manifest.json +3 -3
- package/dist/.next/cache/.rscinfo +1 -1
- package/dist/.next/cache/.tsbuildinfo +1 -1
- package/dist/.next/cache/webpack/client-production/0.pack +0 -0
- package/dist/.next/cache/webpack/client-production/1.pack +0 -0
- package/dist/.next/cache/webpack/client-production/2.pack +0 -0
- package/dist/.next/cache/webpack/client-production/index.pack +0 -0
- package/dist/.next/cache/webpack/client-production/index.pack.old +0 -0
- package/dist/.next/cache/webpack/edge-server-production/index.pack +0 -0
- package/dist/.next/cache/webpack/server-production/0.pack +0 -0
- package/dist/.next/cache/webpack/server-production/index.pack +0 -0
- package/dist/.next/next-minimal-server.js.nft.json +1 -1
- package/dist/.next/next-server.js.nft.json +1 -1
- package/dist/.next/prerender-manifest.json +1 -1
- package/dist/.next/required-server-files.json +1 -1
- package/dist/.next/server/app/_not-found/page.js +1 -1
- package/dist/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/dist/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/_not-found.html +1 -1
- package/dist/.next/server/app/_not-found.rsc +4 -4
- package/dist/.next/server/app/api/cloudflare/route.js +1 -1
- package/dist/.next/server/app/api/cloudflare/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/databases/route.js +1 -1
- package/dist/.next/server/app/api/databases/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/migrations/sync/route.js +5 -5
- package/dist/.next/server/app/api/migrations/sync/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/migrations/sync-files/route.js +3 -3
- package/dist/.next/server/app/api/migrations/sync-files/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/pull-data/confirm/route.js +1 -1
- package/dist/.next/server/app/api/pull-data/confirm/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/pull-remote/confirm/route.js +2 -2
- package/dist/.next/server/app/api/pull-remote/confirm/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/pull-remote/preview/route.js +4 -4
- package/dist/.next/server/app/api/pull-remote/preview/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/push-remote/confirm/route.js +5 -5
- package/dist/.next/server/app/api/push-remote/confirm/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/push-remote/preview/route.js +4 -4
- package/dist/.next/server/app/api/push-remote/preview/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/query/route.js +3 -3
- package/dist/.next/server/app/api/query/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/tables/[name]/route.js +5 -5
- package/dist/.next/server/app/api/tables/[name]/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/tables/route.js +2 -2
- package/dist/.next/server/app/api/tables/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/api/update/route.js +1 -1
- package/dist/.next/server/app/api/update/route_client-reference-manifest.js +1 -1
- package/dist/.next/server/app/index.html +2 -2
- package/dist/.next/server/app/index.rsc +5 -5
- package/dist/.next/server/app/page.js +7 -7
- package/dist/.next/server/app/page.js.nft.json +1 -1
- package/dist/.next/server/app/page_client-reference-manifest.js +1 -1
- package/dist/.next/server/app-paths-manifest.json +1 -1
- package/dist/.next/server/chunks/226.js +12 -12
- package/dist/.next/server/chunks/391.js +1 -1
- package/dist/.next/server/chunks/572.js +1 -0
- package/dist/.next/server/chunks/992.js +3 -3
- package/dist/.next/server/middleware-build-manifest.js +1 -1
- package/dist/.next/server/next-font-manifest.js +1 -1
- package/dist/.next/server/next-font-manifest.json +1 -1
- package/dist/.next/server/pages/404.html +1 -1
- package/dist/.next/server/pages/500.html +1 -1
- package/dist/.next/server/server-reference-manifest.json +1 -1
- package/dist/.next/static/IX-QLbm7scYnyqWeeimal/_buildManifest.js +1 -0
- package/dist/.next/static/IX-QLbm7scYnyqWeeimal/_ssgManifest.js +1 -0
- package/dist/.next/static/chunks/{576-c4daf274bb6469a1.js → 576-18a2209e1ed26aad.js} +1 -1
- package/dist/.next/static/chunks/{92-c4466e0f1ca8a3a8.js → 92-5f7522943fcb72a8.js} +1 -1
- package/dist/.next/static/chunks/app/{layout-be6ee67cf0c92654.js → layout-40ec07d04681ba81.js} +1 -1
- package/dist/.next/static/chunks/app/page-f05cd0fc436bf9bc.js +1 -0
- package/dist/.next/static/chunks/{main-app-fa35024de9bd9284.js → main-app-4506e88db72db4b7.js} +1 -1
- package/dist/.next/static/css/{9f6c25c5400f83d3.css → 7c16f57d325d0d7d.css} +1 -1
- package/dist/.next/static/media/8d697b304b401681-s.woff2 +0 -0
- package/dist/.next/static/media/9610d9e46709d722-s.woff2 +0 -0
- package/dist/.next/trace +3 -14
- package/dist/.next/types/app/api/cloudflare/route.ts +1 -1
- package/dist/.next/types/app/api/databases/route.ts +1 -1
- package/dist/.next/types/app/api/migrations/sync/route.ts +1 -1
- package/dist/.next/types/app/api/migrations/sync-files/route.ts +1 -1
- package/dist/.next/types/app/api/pull-data/confirm/route.ts +1 -1
- package/dist/.next/types/app/api/pull-remote/confirm/route.ts +1 -1
- package/dist/.next/types/app/api/pull-remote/preview/route.ts +1 -1
- package/dist/.next/types/app/api/push-remote/confirm/route.ts +1 -1
- package/dist/.next/types/app/api/push-remote/preview/route.ts +1 -1
- package/dist/.next/types/app/api/query/route.ts +1 -1
- package/dist/.next/types/app/api/tables/[name]/route.ts +1 -1
- package/dist/.next/types/app/api/tables/route.ts +1 -1
- package/dist/.next/types/app/api/update/route.ts +1 -1
- package/dist/.next/types/app/page.ts +1 -1
- package/dist/app/api/tables/[name]/route.js +22 -10
- package/dist/app/globals.css +39 -0
- package/dist/d1-studio.js +2 -2
- package/dist/lib/data-type-handlers.js +426 -0
- package/dist/lib/sql-operations.js +32 -8
- package/dist/lib/sql-sanitizer.js +233 -0
- package/package.json +3 -9
- package/dist/.next/.next/server/chunks/90.js +0 -1
- package/dist/.next/.next/static/chunks/app/page-36ed30b2266617f3.js +0 -1
- package/dist/.next/server/chunks/90.js +0 -1
- package/dist/.next/static/chunks/app/page-36ed30b2266617f3.js +0 -1
- package/dist/app/app/api/cloudflare/route.js +0 -150
- package/dist/app/app/api/databases/route.js +0 -71
- package/dist/app/app/api/migrations/sync/route.js +0 -174
- package/dist/app/app/api/migrations/sync-files/route.js +0 -172
- package/dist/app/app/api/pull-data/confirm/route.js +0 -230
- package/dist/app/app/api/pull-remote/confirm/route.js +0 -278
- package/dist/app/app/api/pull-remote/preview/route.js +0 -144
- package/dist/app/app/api/push-remote/confirm/route.js +0 -196
- package/dist/app/app/api/push-remote/preview/route.js +0 -179
- package/dist/app/app/api/query/route.js +0 -168
- package/dist/app/app/api/tables/[name]/route.js +0 -174
- package/dist/app/app/api/tables/route.js +0 -178
- package/dist/app/app/api/update/route.js +0 -45
- package/dist/app/app/globals.css +0 -93
- package/dist/app/app/layout.jsx +0 -35
- package/dist/app/app/page.jsx +0 -34
- package/next.config.mjs +0 -18
- package/postcss.config.mjs +0 -8
- package/scripts/studio.js +0 -199
- package/scripts/test.js +0 -366
- package/src/app/api/cloudflare/route.js +0 -150
- package/src/app/api/databases/route.js +0 -71
- package/src/app/api/migrations/sync/route.js +0 -174
- package/src/app/api/migrations/sync-files/route.js +0 -172
- package/src/app/api/pull-data/confirm/route.js +0 -230
- package/src/app/api/pull-remote/confirm/route.js +0 -278
- package/src/app/api/pull-remote/preview/route.js +0 -144
- package/src/app/api/push-remote/confirm/route.js +0 -196
- package/src/app/api/push-remote/preview/route.js +0 -179
- package/src/app/api/query/route.js +0 -168
- package/src/app/api/tables/[name]/route.js +0 -174
- package/src/app/api/tables/route.js +0 -178
- package/src/app/api/update/route.js +0 -45
- package/src/app/globals.css +0 -93
- package/src/app/layout.jsx +0 -35
- package/src/app/page.jsx +0 -34
- package/src/components/cloudflare-credentials-modal.jsx +0 -94
- package/src/components/column-selector.jsx +0 -133
- package/src/components/column-sorting.jsx +0 -65
- package/src/components/delete-records-dialog.jsx +0 -64
- package/src/components/download-button.jsx +0 -205
- package/src/components/edit-error-alert.jsx +0 -30
- package/src/components/editable-cell.jsx +0 -163
- package/src/components/editable-row.jsx +0 -169
- package/src/components/environment-handler.jsx +0 -332
- package/src/components/environment-select.jsx +0 -62
- package/src/components/pull-preview-toast.jsx +0 -215
- package/src/components/push-error-alert.jsx +0 -72
- package/src/components/push-preview-toast.jsx +0 -183
- package/src/components/query-results.jsx +0 -112
- package/src/components/refresh-button.jsx +0 -61
- package/src/components/resize-columns.jsx +0 -101
- package/src/components/sidebar.jsx +0 -254
- package/src/components/sql-editor.jsx +0 -411
- package/src/components/sql-error-display.jsx +0 -167
- package/src/components/sync-migrations-button.jsx +0 -87
- package/src/components/table-error-dialog.jsx +0 -65
- package/src/components/table-toolbar.jsx +0 -285
- package/src/components/table-view.jsx +0 -843
- package/src/components/ui/alert.jsx +0 -47
- package/src/components/ui/button.jsx +0 -48
- package/src/components/ui/card.jsx +0 -50
- package/src/components/ui/checkbox.jsx +0 -24
- package/src/components/ui/collapsible.jsx +0 -11
- package/src/components/ui/dialog.jsx +0 -96
- package/src/components/ui/dropdown-menu.jsx +0 -158
- package/src/components/ui/input.jsx +0 -19
- package/src/components/ui/scroll-area.jsx +0 -40
- package/src/components/ui/select.jsx +0 -121
- package/src/components/ui/separator.jsx +0 -25
- package/src/components/ui/sheet.jsx +0 -109
- package/src/components/ui/sidebar.jsx +0 -620
- package/src/components/ui/skeleton.jsx +0 -14
- package/src/components/ui/table.jsx +0 -86
- package/src/components/ui/tabs.jsx +0 -43
- package/src/components/ui/toast.jsx +0 -86
- package/src/components/ui/toaster.jsx +0 -35
- package/src/components/ui/tooltip.jsx +0 -28
- package/src/components/update-banner.jsx +0 -93
- package/src/context/database-context.js +0 -510
- package/src/hooks/use-mobile.jsx +0 -19
- package/src/hooks/use-sql-error.ts +0 -23
- package/src/hooks/use-toast.js +0 -155
- package/src/lib/database-queue.js +0 -37
- package/src/lib/error.js +0 -20
- package/src/lib/find-wrangler-config.js +0 -74
- package/src/lib/license.js +0 -99
- package/src/lib/logger.js +0 -58
- package/src/lib/migrations.js +0 -415
- package/src/lib/parse-sql-error.js +0 -200
- package/src/lib/request-deduplication.js +0 -24
- package/src/lib/schema-operations.js +0 -106
- package/src/lib/sql-error-types.js +0 -14
- package/src/lib/sql-operations.js +0 -647
- package/src/lib/utils.js +0 -6
- package/src/lib/version-utils.js +0 -34
- /package/dist/.next/.next/static/{OUHnbB-64afrrZQL0Srn5 → FEsQ9jwPUQv5A3fwg6Opl}/_buildManifest.js +0 -0
- /package/dist/.next/.next/static/{OUHnbB-64afrrZQL0Srn5 → FEsQ9jwPUQv5A3fwg6Opl}/_ssgManifest.js +0 -0
- /package/dist/.next/.next/static/{ZBTCAyp1kO5FdEHMU-Dw2 → Y9mYu4WBghepP5oT_3OdR}/_buildManifest.js +0 -0
- /package/dist/.next/.next/static/{ZBTCAyp1kO5FdEHMU-Dw2 → Y9mYu4WBghepP5oT_3OdR}/_ssgManifest.js +0 -0
- /package/dist/.next/.next/static/{bHYW7fgIBDF8-Q33_WPoE → ae3gNmoSGm-R5LJC4UagI}/_buildManifest.js +0 -0
- /package/dist/.next/.next/static/{bHYW7fgIBDF8-Q33_WPoE → ae3gNmoSGm-R5LJC4UagI}/_ssgManifest.js +0 -0
- /package/dist/.next/{static/ZBTCAyp1kO5FdEHMU-Dw2 → .next/static/bKfUJeuvAQlBmR3TjrfkH}/_buildManifest.js +0 -0
- /package/dist/.next/{static/ZBTCAyp1kO5FdEHMU-Dw2 → .next/static/bKfUJeuvAQlBmR3TjrfkH}/_ssgManifest.js +0 -0
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { promisify } from 'util';
|
|
4
4
|
import { exec } from 'child_process';
|
|
5
|
+
import { sanitizeTableName, sanitizeColumnName, createParameterizedQuery } from './sql-sanitizer.js';
|
|
5
6
|
import logger from '@/lib/logger';
|
|
6
7
|
|
|
7
8
|
const execAsync = promisify(exec);
|
|
@@ -226,8 +227,16 @@ export function removeSQLComments(sql) {
|
|
|
226
227
|
* @returns {Promise<boolean>} True if the table exists; otherwise, false.
|
|
227
228
|
*/
|
|
228
229
|
export async function tableExists(projectDir, databaseName, env, tableName, remote = false) {
|
|
229
|
-
//
|
|
230
|
-
|
|
230
|
+
// Validate and sanitize table name to prevent SQL injection
|
|
231
|
+
try {
|
|
232
|
+
sanitizeTableName(tableName); // This will throw if invalid
|
|
233
|
+
} catch (error) {
|
|
234
|
+
logger.error('Invalid table name:', tableName, error.message);
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Query the sqlite_master table for the given table name using proper escaping
|
|
239
|
+
const query = `SELECT name FROM sqlite_master WHERE type='table' AND name = '${tableName.replace(/'/g, "''")}' COLLATE NOCASE;`;
|
|
231
240
|
|
|
232
241
|
const result = await executeSQL(projectDir, databaseName, query, env, remote);
|
|
233
242
|
try {
|
|
@@ -282,10 +291,18 @@ export async function executeSQL(projectDir, databaseName, sql, env = {}, remote
|
|
|
282
291
|
}
|
|
283
292
|
}
|
|
284
293
|
|
|
294
|
+
// Validate database name to prevent command injection
|
|
295
|
+
if (!databaseName || typeof databaseName !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(databaseName)) {
|
|
296
|
+
throw new Error('Invalid database name for security reasons');
|
|
297
|
+
}
|
|
298
|
+
|
|
285
299
|
const isWindows = process.platform === 'win32';
|
|
286
300
|
const npxCommand = isWindows ? 'npx.cmd' : 'npx';
|
|
287
301
|
const executionFlag = remote ? '--remote' : '--local';
|
|
288
|
-
|
|
302
|
+
|
|
303
|
+
// Additional SQL escape for shell command execution
|
|
304
|
+
const shellEscapedSQL = cleanSQL.replace(/"/g, '\\"').replace(/\$/g, '\\$');
|
|
305
|
+
const command = `${npxCommand} wrangler d1 execute ${databaseName} ${executionFlag} --command="${shellEscapedSQL}"`;
|
|
289
306
|
|
|
290
307
|
// Only log in development
|
|
291
308
|
if (logger.shouldLog('debug')) {
|
|
@@ -357,8 +374,12 @@ export async function fetchRemoteTableData(
|
|
|
357
374
|
limit,
|
|
358
375
|
orderingColumn = "id"
|
|
359
376
|
) {
|
|
360
|
-
//
|
|
361
|
-
const
|
|
377
|
+
// Validate and sanitize inputs to prevent SQL injection
|
|
378
|
+
const sanitizedTableName = sanitizeTableName(tableName);
|
|
379
|
+
const sanitizedColumn = sanitizeColumnName(orderingColumn);
|
|
380
|
+
const safeLimit = Math.max(1, Math.min(parseInt(limit) || 50, 1000)); // Cap limit to prevent large queries
|
|
381
|
+
|
|
382
|
+
const query = `SELECT * FROM ${sanitizedTableName} ORDER BY ${sanitizedColumn} DESC LIMIT ${safeLimit};`;
|
|
362
383
|
try {
|
|
363
384
|
// Execute the SQL command on the remote database.
|
|
364
385
|
const result = await executeSQL(projectDir, databaseName, query, env, true);
|
|
@@ -393,9 +414,12 @@ export async function fetchRemoteTableData(
|
|
|
393
414
|
export function generateBulkInsertSQL(tableName, rows) {
|
|
394
415
|
if (!rows || rows.length === 0) return '';
|
|
395
416
|
|
|
396
|
-
//
|
|
417
|
+
// Validate and sanitize table name
|
|
418
|
+
const sanitizedTableName = sanitizeTableName(tableName);
|
|
419
|
+
|
|
420
|
+
// Get the list of columns from the first row object and sanitize them
|
|
397
421
|
const columns = Object.keys(rows[0]);
|
|
398
|
-
const columnList = columns.map(col =>
|
|
422
|
+
const columnList = columns.map(col => sanitizeColumnName(col)).join(', ');
|
|
399
423
|
|
|
400
424
|
// Build the values list for each row.
|
|
401
425
|
const valuesList = rows.map(row => {
|
|
@@ -408,7 +432,7 @@ export function generateBulkInsertSQL(tableName, rows) {
|
|
|
408
432
|
return `(${values})`;
|
|
409
433
|
}).join(', ');
|
|
410
434
|
|
|
411
|
-
return `INSERT INTO
|
|
435
|
+
return `INSERT INTO ${sanitizedTableName} (${columnList}) VALUES ${valuesList};`;
|
|
412
436
|
}
|
|
413
437
|
|
|
414
438
|
// ---------------------------------------------------------------------
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL Sanitization and Security Utilities
|
|
3
|
+
* Prevents SQL injection attacks by properly escaping and validating identifiers
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Validates and sanitizes table names to prevent SQL injection
|
|
8
|
+
* @param {string} tableName - The table name to sanitize
|
|
9
|
+
* @returns {string} - Sanitized table name wrapped in quotes
|
|
10
|
+
* @throws {Error} - If table name is invalid
|
|
11
|
+
*/
|
|
12
|
+
export function sanitizeTableName(tableName) {
|
|
13
|
+
if (!tableName || typeof tableName !== 'string') {
|
|
14
|
+
throw new Error('Table name must be a non-empty string');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// SQLite identifier rules: must start with letter or underscore, contain only letters, digits, underscores
|
|
18
|
+
const validIdentifierRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
19
|
+
|
|
20
|
+
if (!validIdentifierRegex.test(tableName)) {
|
|
21
|
+
throw new Error(`Invalid table name: ${tableName}. Must start with letter or underscore and contain only letters, digits, and underscores.`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// SQLite reserved words that should not be used as table names
|
|
25
|
+
const reservedWords = [
|
|
26
|
+
'SELECT', 'FROM', 'WHERE', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP',
|
|
27
|
+
'ALTER', 'TABLE', 'INDEX', 'VIEW', 'TRIGGER', 'PRAGMA', 'VACUUM', 'REINDEX',
|
|
28
|
+
'EXPLAIN', 'QUERY', 'PLAN', 'TRANSACTION', 'BEGIN', 'COMMIT', 'ROLLBACK'
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
if (reservedWords.includes(tableName.toUpperCase())) {
|
|
32
|
+
throw new Error(`Table name cannot be a reserved word: ${tableName}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Return properly quoted identifier
|
|
36
|
+
return `"${tableName}"`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Validates and sanitizes column names to prevent SQL injection
|
|
41
|
+
* @param {string} columnName - The column name to sanitize
|
|
42
|
+
* @returns {string} - Sanitized column name wrapped in quotes
|
|
43
|
+
* @throws {Error} - If column name is invalid
|
|
44
|
+
*/
|
|
45
|
+
export function sanitizeColumnName(columnName) {
|
|
46
|
+
if (!columnName || typeof columnName !== 'string') {
|
|
47
|
+
throw new Error('Column name must be a non-empty string');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const validIdentifierRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
|
|
51
|
+
|
|
52
|
+
if (!validIdentifierRegex.test(columnName)) {
|
|
53
|
+
throw new Error(`Invalid column name: ${columnName}. Must start with letter or underscore and contain only letters, digits, and underscores.`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return `"${columnName}"`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Creates a parameterized query with proper escaping
|
|
61
|
+
* @param {string} query - The SQL query template with ? placeholders
|
|
62
|
+
* @param {Array} params - Array of parameter values
|
|
63
|
+
* @returns {Object} - Object with query and params
|
|
64
|
+
*/
|
|
65
|
+
export function createParameterizedQuery(query, params = []) {
|
|
66
|
+
if (!query || typeof query !== 'string') {
|
|
67
|
+
throw new Error('Query must be a non-empty string');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (!Array.isArray(params)) {
|
|
71
|
+
throw new Error('Parameters must be an array');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Count placeholders in query
|
|
75
|
+
const placeholderCount = (query.match(/\?/g) || []).length;
|
|
76
|
+
|
|
77
|
+
if (placeholderCount !== params.length) {
|
|
78
|
+
throw new Error(`Parameter count mismatch: expected ${placeholderCount}, got ${params.length}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
query: query.trim(),
|
|
83
|
+
params: params
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Builds a safe WHERE clause with proper parameterization
|
|
89
|
+
* @param {Object} conditions - Object with column:value pairs
|
|
90
|
+
* @returns {Object} - Object with whereClause and params
|
|
91
|
+
*/
|
|
92
|
+
export function buildWhereClause(conditions) {
|
|
93
|
+
if (!conditions || typeof conditions !== 'object') {
|
|
94
|
+
throw new Error('Conditions must be an object');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const entries = Object.entries(conditions);
|
|
98
|
+
if (entries.length === 0) {
|
|
99
|
+
return { whereClause: '', params: [] };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const clauses = [];
|
|
103
|
+
const params = [];
|
|
104
|
+
|
|
105
|
+
for (const [column, value] of entries) {
|
|
106
|
+
const sanitizedColumn = sanitizeColumnName(column);
|
|
107
|
+
clauses.push(`${sanitizedColumn} = ?`);
|
|
108
|
+
params.push(value);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
whereClause: clauses.join(' AND '),
|
|
113
|
+
params: params
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Builds a safe UPDATE query with proper parameterization
|
|
119
|
+
* @param {string} tableName - The table name
|
|
120
|
+
* @param {Object} updates - Object with column:value pairs to update
|
|
121
|
+
* @param {Object} conditions - Object with column:value pairs for WHERE clause
|
|
122
|
+
* @returns {Object} - Object with query and params
|
|
123
|
+
*/
|
|
124
|
+
export function buildUpdateQuery(tableName, updates, conditions) {
|
|
125
|
+
const sanitizedTableName = sanitizeTableName(tableName);
|
|
126
|
+
|
|
127
|
+
if (!updates || typeof updates !== 'object' || Object.keys(updates).length === 0) {
|
|
128
|
+
throw new Error('Updates must be a non-empty object');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const updateEntries = Object.entries(updates);
|
|
132
|
+
const setClause = updateEntries.map(([column]) =>
|
|
133
|
+
`${sanitizeColumnName(column)} = ?`
|
|
134
|
+
).join(', ');
|
|
135
|
+
|
|
136
|
+
const { whereClause, params: whereParams } = buildWhereClause(conditions);
|
|
137
|
+
|
|
138
|
+
if (!whereClause) {
|
|
139
|
+
throw new Error('WHERE clause is required for UPDATE queries');
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const updateParams = updateEntries.map(([, value]) => value);
|
|
143
|
+
|
|
144
|
+
return createParameterizedQuery(
|
|
145
|
+
`UPDATE ${sanitizedTableName} SET ${setClause} WHERE ${whereClause}`,
|
|
146
|
+
[...updateParams, ...whereParams]
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Builds a safe DELETE query with proper parameterization
|
|
152
|
+
* @param {string} tableName - The table name
|
|
153
|
+
* @param {Object} conditions - Object with column:value pairs for WHERE clause
|
|
154
|
+
* @returns {Object} - Object with query and params
|
|
155
|
+
*/
|
|
156
|
+
export function buildDeleteQuery(tableName, conditions) {
|
|
157
|
+
const sanitizedTableName = sanitizeTableName(tableName);
|
|
158
|
+
|
|
159
|
+
const { whereClause, params } = buildWhereClause(conditions);
|
|
160
|
+
|
|
161
|
+
if (!whereClause) {
|
|
162
|
+
throw new Error('WHERE clause is required for DELETE queries');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return createParameterizedQuery(
|
|
166
|
+
`DELETE FROM ${sanitizedTableName} WHERE ${whereClause}`,
|
|
167
|
+
params
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Builds a safe INSERT query with proper parameterization
|
|
173
|
+
* @param {string} tableName - The table name
|
|
174
|
+
* @param {Object} data - Object with column:value pairs to insert
|
|
175
|
+
* @returns {Object} - Object with query and params
|
|
176
|
+
*/
|
|
177
|
+
export function buildInsertQuery(tableName, data) {
|
|
178
|
+
const sanitizedTableName = sanitizeTableName(tableName);
|
|
179
|
+
|
|
180
|
+
if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {
|
|
181
|
+
throw new Error('Data must be a non-empty object');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const entries = Object.entries(data);
|
|
185
|
+
const columns = entries.map(([column]) => sanitizeColumnName(column)).join(', ');
|
|
186
|
+
const placeholders = entries.map(() => '?').join(', ');
|
|
187
|
+
const values = entries.map(([, value]) => value);
|
|
188
|
+
|
|
189
|
+
return createParameterizedQuery(
|
|
190
|
+
`INSERT INTO ${sanitizedTableName} (${columns}) VALUES (${placeholders})`,
|
|
191
|
+
values
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Validates that a value is safe for use in SQL queries
|
|
197
|
+
* @param {any} value - The value to validate
|
|
198
|
+
* @returns {boolean} - True if value is safe
|
|
199
|
+
*/
|
|
200
|
+
export function isSafeValue(value) {
|
|
201
|
+
// Allow null, undefined, numbers, booleans, and strings
|
|
202
|
+
const safeTypes = ['string', 'number', 'boolean', 'undefined'];
|
|
203
|
+
return value === null || safeTypes.includes(typeof value);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Sanitizes a value for safe SQL usage
|
|
208
|
+
* @param {any} value - The value to sanitize
|
|
209
|
+
* @returns {any} - Sanitized value
|
|
210
|
+
*/
|
|
211
|
+
export function sanitizeValue(value) {
|
|
212
|
+
if (!isSafeValue(value)) {
|
|
213
|
+
throw new Error(`Unsafe value type: ${typeof value}`);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return value;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Escapes special characters in LIKE patterns
|
|
221
|
+
* @param {string} pattern - The LIKE pattern to escape
|
|
222
|
+
* @returns {string} - Escaped pattern
|
|
223
|
+
*/
|
|
224
|
+
export function escapeLikePattern(pattern) {
|
|
225
|
+
if (typeof pattern !== 'string') {
|
|
226
|
+
throw new Error('LIKE pattern must be a string');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return pattern
|
|
230
|
+
.replace(/\\/g, '\\\\') // Escape backslashes
|
|
231
|
+
.replace(/%/g, '\\%') // Escape percent signs
|
|
232
|
+
.replace(/_/g, '\\_'); // Escape underscores
|
|
233
|
+
}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "d1s",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.13",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Manage your Cloudflare D1 database locally, lightning fast.",
|
|
6
6
|
"main": "./dist/d1-studio.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"d1studio": "dist/d1-studio.js"
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"scripts": {
|
|
11
11
|
"dev": "next dev",
|
|
12
12
|
"build": "next build",
|
|
13
|
-
"build:cli": "mkdir -p dist/lib && cp -r src/lib/* dist/lib/ && cp -r src/app dist/app && cp scripts/studio.js dist/d1-studio.js && cp -r .next dist/.next && chmod +x dist/d1-studio.js",
|
|
13
|
+
"build:cli": "npm run build && mkdir -p dist/lib && mkdir -p dist/app && cp -r src/lib/* dist/lib/ && cp -r src/app/* dist/app/ && cp scripts/studio.js dist/d1-studio.js && cp -r .next dist/.next && chmod +x dist/d1-studio.js",
|
|
14
14
|
"start": "next start",
|
|
15
15
|
"prepare": "npm run build:cli",
|
|
16
16
|
"link": "npm link",
|
|
@@ -22,12 +22,6 @@
|
|
|
22
22
|
},
|
|
23
23
|
"files": [
|
|
24
24
|
"dist",
|
|
25
|
-
"public",
|
|
26
|
-
"src",
|
|
27
|
-
"scripts",
|
|
28
|
-
"next.config.mjs",
|
|
29
|
-
"tailwind.config.jms",
|
|
30
|
-
"postcss.config.mjs",
|
|
31
25
|
"README.md"
|
|
32
26
|
],
|
|
33
27
|
"keywords": [
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
exports.id=90,exports.ids=[90],exports.modules={1241:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,3219,23)),Promise.resolve().then(r.t.bind(r,4863,23)),Promise.resolve().then(r.t.bind(r,5155,23)),Promise.resolve().then(r.t.bind(r,802,23)),Promise.resolve().then(r.t.bind(r,9350,23)),Promise.resolve().then(r.t.bind(r,8530,23)),Promise.resolve().then(r.t.bind(r,8921,23))},4041:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,6959,23)),Promise.resolve().then(r.t.bind(r,3875,23)),Promise.resolve().then(r.t.bind(r,8903,23)),Promise.resolve().then(r.t.bind(r,7174,23)),Promise.resolve().then(r.t.bind(r,4178,23)),Promise.resolve().then(r.t.bind(r,7190,23)),Promise.resolve().then(r.t.bind(r,1365,23))},4400:(e,t,r)=>{Promise.resolve().then(r.bind(r,3164)),Promise.resolve().then(r.bind(r,1831))},7952:(e,t,r)=>{Promise.resolve().then(r.bind(r,2652)),Promise.resolve().then(r.bind(r,2899))},2652:(e,t,r)=>{"use strict";r.d(t,{Toaster:()=>v});var a=r(5512),s=r(6888),o=r(8009),i=r(8952),n=r(1643),c=r(1255),l=r(3603);let d=i.Kq,u=o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.LM,{ref:r,className:(0,l.cn)("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),...t}));u.displayName=i.LM.displayName;let h=(0,n.F)("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),p=o.forwardRef(({className:e,variant:t,...r},s)=>(0,a.jsx)(i.bL,{ref:s,className:(0,l.cn)(h({variant:t}),e),...r}));p.displayName=i.bL.displayName,o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.rc,{ref:r,className:(0,l.cn)("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),...t})).displayName=i.rc.displayName;let m=o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.bm,{ref:r,className:(0,l.cn)("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",...t,children:(0,a.jsx)(c.A,{className:"h-4 w-4"})}));m.displayName=i.bm.displayName;let f=o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.hE,{ref:r,className:(0,l.cn)("text-sm font-semibold [&+div]:text-xs",e),...t}));f.displayName=i.hE.displayName;let b=o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.VY,{ref:r,className:(0,l.cn)("text-sm opacity-90",e),...t}));function v(){let{toasts:e}=(0,s.dj)();return(0,a.jsxs)(d,{children:[e.map(function({id:e,title:t,description:r,action:s,...o}){return(0,a.jsxs)(p,{...o,children:[(0,a.jsxs)("div",{className:"grid gap-1",children:[t&&(0,a.jsx)(f,{children:t}),r&&(0,a.jsx)(b,{children:r})]}),s,(0,a.jsx)(m,{})]},e)}),(0,a.jsx)(u,{})]})}b.displayName=i.VY.displayName},8180:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>u,metadata:()=>d});var a=r(2740),s=r(7944),o=r.n(s),i=r(5510),n=r.n(i);r(1135);var c=r(1831),l=r(3164);let d={title:"d1-studio",description:"Native D1 database studio."};function u({children:e}){return(0,a.jsx)("html",{lang:"en",children:(0,a.jsx)("body",{className:`${o().variable} ${n().variable} antialiased`,children:(0,a.jsxs)(c.DatabaseProvider,{children:[e,(0,a.jsx)(l.Toaster,{})," "]})})})}},3164:(e,t,r)=>{"use strict";r.d(t,{Toaster:()=>a});let a=(0,r(4379).registerClientReference)(function(){throw Error("Attempted to call Toaster() from the server but Toaster is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/kona/Desktop/d1studio/src/components/ui/toaster.jsx","Toaster")},1135:()=>{},2899:(e,t,r)=>{"use strict";r.d(t,{DatabaseProvider:()=>u,t:()=>h});var a=r(5512),s=r(8009),o=r(6888);let i=new Map;function n(e,t,r=2e3){let a=i.get(e);if(a&&Date.now()-a.timestamp<r)return a.promise;let s=t();return i.set(e,{promise:s,timestamp:Date.now()}),s.finally(()=>{setTimeout(()=>{i.delete(e)},r)}),s}let c=(0,s.createContext)(void 0);class l{constructor(){this.cache=new Map}get(e){return this.cache.get(e)||null}set(e,t,r,a){this.cache.set(e,{data:t,schema:r,meta:a,timestamp:Date.now()})}update(e,t,r,a){let s=this.cache.get(e);s&&this.cache.set(e,{data:t||s.data,schema:r||s.schema,meta:a||s.meta,timestamp:Date.now()})}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}}class d{constructor(){this.queue=[],this.processing=!1}async add(e){return new Promise((t,r)=>{this.queue.push({operation:e,resolve:t,reject:r}),this.process()})}async process(){if(this.processing||0===this.queue.length)return;this.processing=!0;let{operation:e,resolve:t,reject:r}=this.queue.shift();try{let r=await e();t(r)}catch(e){r(e)}finally{this.processing=!1,this.process()}}}function u({children:e}){let{toast:t}=(0,o.dj)(),[r,i]=(0,s.useState)([]),[u,h]=(0,s.useState)(!0),[p,m]=(0,s.useState)(null),[f,b]=(0,s.useState)(null);(0,s.useRef)(new d);let[v,y]=(0,s.useState)(null),g=(0,s.useRef)(new l).current,w=(0,s.useCallback)((e,t=1,r=50)=>{let a=`table-${e}-${t}-${r}`;return g.get(a)},[]),x=(0,s.useCallback)(e=>{g.cache.forEach((t,r)=>{r.startsWith(`table-${e}-`)&&g.invalidate(r)})},[]),T=(0,s.useCallback)((e,t,r,a,s=1,o=50)=>{let i=`table-${e}-${s}-${o}`;g.update(i,t,r,a)},[]),S=(0,s.useCallback)(async e=>n(`query-${e}`,async()=>{try{let t=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e})});if(!t.ok){let e="Failed to execute query";try{let r=await t.json();e=r?.error?.message||e}catch(e){}throw Error(e)}let r=await t.json();if(!r.success)throw Error(r.error||"Query execution failed");return r}catch(e){throw e||Error("An unknown error occurred")}},1e3),[]),j=(0,s.useCallback)(async e=>{try{let t=await fetch(`/api/tables/${e}`),r=await t.json();if(!t.ok||!r.success)throw Error(r.error||"Failed to fetch table schema");return r.schema||[]}catch(e){throw console.error("Schema fetch error:",e),t({variant:"destructive",title:"Schema Fetch Failed",description:e.message}),e}},[t]),E=(0,s.useCallback)(async(e,r={})=>{let{forceFetch:a=!1,page:s=1,limit:o=50}=r,i=`table-${e}-${s}-${o}`;if(!a){let e=g.get(i);if(e)return e}return n(`table-${e}-${s}-${o}`,async()=>{try{let t=await fetch(`/api/tables/${e}?page=${s}&limit=${o}`,{headers:{"Cache-Control":"no-cache",Pragma:"no-cache"}});if(!t.ok)throw Error("Failed to fetch table data");let r=await t.json();if(!r.success)throw Error(r.error||"Failed to fetch table data");return g.set(i,r.data,r.schema,r.meta),r}catch(e){throw console.error("Error fetching table data:",e),t({variant:"destructive",title:"Data Fetch Failed",description:e.message}),e}},1e3)},[t]),C=(0,s.useCallback)(async e=>{try{return g.invalidate(e),await E(e,{forceFetch:!0})}catch(e){throw console.error("Error updating table data:",e),t({variant:"destructive",title:"Update Failed",description:e.message}),e}},[E,t]),P=(0,s.useCallback)(async(e,t={})=>(y(e),await E(e,t)),[E]),k=(0,s.useCallback)(async()=>n("refresh-tables",async()=>{h(!0),m(null);try{let e=await fetch("/api/tables");if(!e.ok)throw Error("Failed to fetch tables");let t=await e.json();if(t.error)throw Error(t.error);return i(t.tables||[]),t.tables||[]}catch(e){throw m(e.message),t({variant:"destructive",title:"Refresh Failed",description:e.message}),e}finally{h(!1)}},2e3),[t]),D=(0,s.useCallback)(async e=>{try{await S(e),g.clear(),await k(),t({title:"Success",description:"Table created successfully"})}catch(e){throw t({variant:"destructive",title:"Create Table Failed",description:e.message}),Error(`Failed to create table: ${e.message}`)}},[S,k,t]),N=(0,s.useCallback)(async e=>{try{await S(`DROP TABLE ${e};`),g.invalidate(e),await k(),t({title:"Success",description:"Table dropped successfully"})}catch(e){throw t({variant:"destructive",title:"Drop Table Failed",description:e.message}),Error(`Failed to drop table: ${e.message}`)}},[S,k,t]),$=(0,s.useCallback)(async e=>{try{let r=await fetch("/api/migrations/sync",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let e=await r.json();throw Error(e.error?.message||"Failed to sync migrations")}let a=await r.json();return t({title:"Success",description:"Migrations synced successfully"}),a}catch(e){throw console.error("Error syncing migrations:",e),t({variant:"destructive",title:"Sync Failed",description:e.message}),e}},[t]),F=(0,s.useCallback)(async()=>{try{let e=localStorage.getItem("cf_credentials");if(!e)throw Error("No Cloudflare credentials found. Please connect to Cloudflare first.");let t=JSON.parse(e);if(!t.accountId||!t.apiToken)throw Error("Invalid credentials stored. Please reconnect to Cloudflare.");let r=await fetch("/api/pull-remote/confirm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:t.accountId,apiToken:t.apiToken})}),a=await r.json();if(!r.ok||!a.success)throw Error(a.error?.message||"Failed to pull from remote");return g.clear(),await k(),a}catch(e){throw console.error("Error pulling from remote:",e),t({variant:"destructive",title:"Pull Failed",description:e.message}),e}},[k,t]),O=(0,s.useCallback)(async e=>{try{let t=await fetch("/api/push-remote",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json();if(!t.ok)throw Error(r.error?.message||"Failed to push to remote");return r}catch(e){throw console.error("Error pushing to remote:",e),e}},[t]),A=(0,s.useMemo)(()=>({tables:r,currentDatabase:f,isLoading:u,error:p,activeTable:v,refreshTables:k,executeQuery:S,fetchTableSchema:j,fetchTableData:E,updateTableData:C,createTable:D,dropTable:N,syncMigrations:$,pullFromRemote:F,pushToRemote:O,getCachedTable:w,updateTableCache:T,invalidateTable:x,switchTable:P}),[r,f,u,p,v,k,S,j,E,C,D,N,$,F,O,w,T,x,P]);return(0,a.jsx)(c.Provider,{value:A,children:e})}function h(){let e=(0,s.useContext)(c);if(!e)throw Error("useDatabase must be used within a DatabaseProvider");return e}},6888:(e,t,r)=>{"use strict";r.d(t,{dj:()=>h});var a=r(8009);let s=0,o=new Map,i=e=>{if(o.has(e))return;let t=setTimeout(()=>{o.delete(e),d({type:"REMOVE_TOAST",toastId:e})},1e6);o.set(e,t)},n=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{let{toastId:r}=t;return r?i(r):e.toasts.forEach(e=>{i(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===r||void 0===r?{...e,open:!1}:e)}}case"REMOVE_TOAST":if(void 0===t.toastId)return{...e,toasts:[]};return{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},c=[],l={toasts:[]};function d(e){l=n(l,e),c.forEach(e=>{e(l)})}function u({...e}){let t=(s=(s+1)%Number.MAX_SAFE_INTEGER).toString(),r=()=>d({type:"DISMISS_TOAST",toastId:t});return d({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||r()}}}),{id:t,dismiss:r,update:e=>d({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function h(){let[e,t]=a.useState(l);return a.useEffect(()=>(c.push(t),()=>{let e=c.indexOf(t);e>-1&&c.splice(e,1)}),[e]),{...e,toast:u,dismiss:e=>d({type:"DISMISS_TOAST",toastId:e})}}},3603:(e,t,r)=>{"use strict";r.d(t,{cn:()=>o});var a=r(2281),s=r(4805);function o(...e){return(0,s.QP)((0,a.$)(e))}},1831:(e,t,r)=>{"use strict";r.d(t,{DatabaseProvider:()=>s});var a=r(4379);let s=(0,a.registerClientReference)(function(){throw Error("Attempted to call DatabaseProvider() from the server but DatabaseProvider is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/kona/Desktop/d1studio/src/context/database-context.js","DatabaseProvider");(0,a.registerClientReference)(function(){throw Error("Attempted to call useDatabase() from the server but useDatabase is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/kona/Desktop/d1studio/src/context/database-context.js","useDatabase")}};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[974],{3320:(e,t,a)=>{Promise.resolve().then(a.bind(a,2624))},2624:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>tt});var s=a(5155),l=a(2115),n=a(2398),r=a(1680),i=a(7443),o=a(2591),c=a(2783),d=a(4031);let u=l.forwardRef((e,t)=>{let{className:a,type:l,...n}=e;return(0,s.jsx)("input",{type:l,className:(0,d.cn)("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",a),ref:t,...n})});u.displayName="Input";var m=a(1027);let h=(0,m.F)("relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",{variants:{variant:{default:"bg-background text-foreground",destructive:"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive"}},defaultVariants:{variant:"default"}}),x=l.forwardRef((e,t)=>{let{className:a,variant:l,...n}=e;return(0,s.jsx)("div",{ref:t,role:"alert",className:(0,d.cn)(h({variant:l}),a),...n})});x.displayName="Alert",l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("h5",{ref:t,className:(0,d.cn)("mb-1 font-medium leading-none tracking-tight",a),...l})}).displayName="AlertTitle";let f=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("div",{ref:t,className:(0,d.cn)("text-sm [&_p]:leading-relaxed",a),...l})});f.displayName="AlertDescription";var p=a(33),g=a(6217),v=a(689);let N=g.bL;g.l9;let j=g.ZL;g.bm;let b=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(g.hJ,{ref:t,className:(0,d.cn)("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",a),...l})});b.displayName=g.hJ.displayName;let w=l.forwardRef((e,t)=>{let{className:a,children:l,...n}=e;return(0,s.jsxs)(j,{children:[(0,s.jsx)(b,{}),(0,s.jsxs)(g.UC,{ref:t,className:(0,d.cn)("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",a),...n,children:[l,(0,s.jsxs)(g.bm,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[(0,s.jsx)(v.A,{className:"h-4 w-4"}),(0,s.jsx)("span",{className:"sr-only",children:"Close"})]})]})]})});w.displayName=g.UC.displayName;let y=e=>{let{className:t,...a}=e;return(0,s.jsx)("div",{className:(0,d.cn)("flex flex-col space-y-1.5 text-center sm:text-left",t),...a})};y.displayName="DialogHeader";let C=e=>{let{className:t,...a}=e;return(0,s.jsx)("div",{className:(0,d.cn)("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...a})};C.displayName="DialogFooter";let S=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(g.hE,{ref:t,className:(0,d.cn)("text-lg font-semibold leading-none tracking-tight",a),...l})});S.displayName=g.hE.displayName;let E=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(g.VY,{ref:t,className:(0,d.cn)("text-sm text-muted-foreground",a),...l})});E.displayName=g.VY.displayName;var R=a(2317);let T=(0,m.F)("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),A=l.forwardRef((e,t)=>{let{className:a,variant:l,size:n,asChild:r=!1,...i}=e,o=r?R.DX:"button";return(0,s.jsx)(o,{className:(0,d.cn)(T({variant:l,size:n,className:a})),ref:t,...i})});function k(e){let{open:t,onClose:a,onSubmit:n}=e,[r,i]=(0,l.useState)(""),[o,d]=(0,l.useState)(""),[m,h]=(0,l.useState)(""),[p,g]=(0,l.useState)(!1),v=async e=>{e.preventDefault(),h(""),g(!0);try{await n({accountId:r,apiToken:o}),localStorage.setItem("cf_credentials",JSON.stringify({accountId:r,apiToken:o})),a()}catch(e){h(e.message)}finally{g(!1)}};return(0,s.jsx)(N,{open:t,onOpenChange:a,children:(0,s.jsxs)(w,{className:"sm:max-w-md",children:[(0,s.jsxs)(y,{children:[(0,s.jsx)(S,{children:"Connect to Cloudflare"}),(0,s.jsx)(E,{children:"Enter your Cloudflare credentials to push your database to production."})]}),(0,s.jsxs)("form",{onSubmit:v,className:"space-y-4 mt-4",children:[m&&(0,s.jsx)(x,{variant:"destructive",children:(0,s.jsx)(f,{children:m})}),(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsx)("label",{className:"text-sm font-medium",children:"Account ID"}),(0,s.jsx)(u,{placeholder:"Your Cloudflare Account ID",value:r,onChange:e=>i(e.target.value),required:!0})]}),(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsx)("label",{className:"text-sm font-medium",children:"API Token"}),(0,s.jsx)(u,{type:"password",placeholder:"Your D1 Database API Token",value:o,onChange:e=>d(e.target.value),required:!0})]}),(0,s.jsxs)("div",{className:"flex justify-end gap-3",children:[(0,s.jsx)(A,{type:"button",variant:"outline",onClick:a,children:"Cancel"}),(0,s.jsxs)(A,{type:"submit",disabled:p,children:[p&&(0,s.jsx)(c.A,{className:"mr-2 h-4 w-4 animate-spin"}),"Connect"]})]})]})]})})}A.displayName="Button";var _=a(6528),O=a(1868);let L=l.forwardRef((e,t)=>{let{className:a,children:l,...n}=e;return(0,s.jsxs)(O.bL,{ref:t,className:(0,d.cn)("relative overflow-hidden",a),...n,children:[(0,s.jsx)(O.LM,{className:"h-full w-full rounded-[inherit]",children:l}),(0,s.jsx)(I,{}),(0,s.jsx)(O.OK,{})]})});L.displayName=O.bL.displayName;let I=l.forwardRef((e,t)=>{let{className:a,orientation:l="vertical",...n}=e;return(0,s.jsx)(O.VM,{ref:t,orientation:l,className:(0,d.cn)("flex touch-none select-none transition-colors","vertical"===l&&"h-full w-2.5 border-l border-l-transparent p-[1px]","horizontal"===l&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",a),...n,children:(0,s.jsx)(O.lr,{className:"relative flex-1 rounded-full bg-border"})})});I.displayName=O.VM.displayName;let P=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("div",{className:"relative w-full overflow-auto",children:(0,s.jsx)("table",{ref:t,className:(0,d.cn)("w-full caption-bottom text-sm",a),...l})})});P.displayName="Table";let U=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("thead",{ref:t,className:(0,d.cn)("[&_tr]:border-b",a),...l})});U.displayName="TableHeader";let F=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("tbody",{ref:t,className:(0,d.cn)("[&_tr:last-child]:border-0",a),...l})});F.displayName="TableBody",l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("tfoot",{ref:t,className:(0,d.cn)("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",a),...l})}).displayName="TableFooter";let D=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("tr",{ref:t,className:(0,d.cn)("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",a),...l})});D.displayName="TableRow";let M=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("th",{ref:t,className:(0,d.cn)("h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",a),...l})});M.displayName="TableHead";let z=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("td",{ref:t,className:(0,d.cn)("p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",a),...l})});z.displayName="TableCell",l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)("caption",{ref:t,className:(0,d.cn)("mt-4 text-sm text-muted-foreground",a),...l})}).displayName="TableCaption";let Q=function(e){let{preview:t=[],onConfirm:a,onCancel:n,isConfirming:r,error:i,isLoading:o,success:u}=e,[m,h]=(0,l.useState)(!0);if(o)return(0,s.jsx)("div",{className:"fixed bottom-4 right-4 z-50 font-sans w-[600px]",children:(0,s.jsx)("div",{className:"rounded-lg border p-4 shadow-lg bg-background",children:(0,s.jsxs)("div",{className:"flex items-start gap-3",children:[(0,s.jsx)(c.A,{className:"h-5 w-5 text-neutral-600 shrink-0 mt-0.5 animate-spin"}),(0,s.jsx)("div",{className:"flex-1 space-y-3",children:(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsx)("p",{className:"font-medium text-neutral-800",children:"Preparing Push Migration"}),(0,s.jsx)("p",{className:"text-sm text-neutral-600",children:"Checking local migrations..."})]})})]})})});if(!(null==t?void 0:t.length))return(0,s.jsx)("div",{className:"fixed bottom-4 right-4 z-50 w-[600px]",children:(0,s.jsx)("div",{className:"rounded-lg border p-4",children:(0,s.jsx)("p",{className:"text-sm font-medium",children:"No migrations to preview"})})});let x=t.filter(e=>"will be applied"===e.action).length,f=t.filter(e=>"skipped"===e.action).length;t.filter(e=>"applied"===e.action).length;let p=e=>{switch(e){case"will be applied":return"\uD83D\uDD52️";case"applied":case"skipped":return"✅";case"failed":return"❌";default:return""}};return(0,s.jsx)("div",{className:"fixed bottom-4 right-4 z-50 font-sans w-[600px]",children:(0,s.jsx)("div",{className:(0,d.cn)("rounded-lg border p-4 shadow-lg",i?"bg-destructive/15":"bg-background"),children:(0,s.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,s.jsxs)("div",{className:"space-y-2",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsx)("h5",{className:"font-medium text-neutral-900",children:"Push Migration Preview"}),(0,s.jsx)("button",{onClick:n,className:"text-neutral-500 hover:text-neutral-900 p-1 rounded-md hover:bg-neutral-100",children:(0,s.jsx)(v.A,{className:"h-4 w-4"})})]}),(0,s.jsxs)("p",{className:"text-sm text-neutral-700",children:[x," migration(s) \uD83D\uDD52️ pending, ",f," to ✅ skip"]}),i?(0,s.jsx)("p",{className:"text-sm text-destructive font-medium mt-1",children:i.message}):u&&(0,s.jsx)("p",{className:"text-sm text-green-700 font-medium mt-1",children:u})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)("button",{onClick:()=>h(!m),className:"text-sm font-medium hover:underline",children:m?"Hide Details":"Show Details"}),m&&(0,s.jsx)(L,{className:"h-[480px] mt-2 rounded border border-neutral-200",children:(0,s.jsxs)(P,{children:[(0,s.jsx)(U,{children:(0,s.jsxs)(D,{children:[(0,s.jsx)(M,{children:"Migration"}),(0,s.jsx)(M,{className:"text-center w-24",children:"Status"})]})}),(0,s.jsx)(F,{children:t.map((e,t)=>(0,s.jsxs)(D,{children:[(0,s.jsx)(z,{className:"font-mono text-xs",children:e.name}),(0,s.jsx)(z,{className:"text-center align-middle",children:p(e.action)})]},t))})]})})]}),(0,s.jsxs)("div",{className:"flex gap-2 pt-1",children:[(0,s.jsx)(A,{onClick:a,disabled:r||0===x,className:"flex-1",children:r?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(c.A,{className:"mr-2 h-4 w-4 animate-spin"}),"Confirming..."]}):"Confirm Push"}),(0,s.jsx)(A,{variant:"outline",onClick:n,disabled:r,className:"flex-1",children:"Cancel"})]})]})})})},V=function(e){let{preview:t=[],onConfirm:a,onCancel:n,onDataPull:r,isConfirming:i,isDataPulling:o,error:u,isLoading:m,success:h}=e;console.log("PullPreviewToast rendered with:",{previewLength:t.length,isConfirming:i,error:u,isLoading:m}),(0,l.useEffect)(()=>(console.log("PullPreviewToast mounted/updated"),()=>console.log("PullPreviewToast unmounted")),[]);let[x,f]=(0,l.useState)(!1);if(m)return console.log("Rendering loading state"),(0,s.jsx)("div",{className:"fixed bottom-4 right-4 z-50 font-sans w-[600px]",children:(0,s.jsx)("div",{className:"rounded-lg border p-4 shadow-lg bg-background",children:(0,s.jsxs)("div",{className:"flex items-start gap-3",children:[(0,s.jsx)(c.A,{className:"h-5 w-5 text-neutral-600 shrink-0 mt-0.5 animate-spin"}),(0,s.jsx)("div",{className:"flex-1 space-y-3",children:(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsx)("p",{className:"font-medium text-neutral-800",children:"Preparing Pull Migration"}),(0,s.jsx)("p",{className:"text-sm text-neutral-600",children:"Checking remote migrations..."})]})})]})})});if(!(null==t?void 0:t.length))return console.log("No preview data available"),(0,s.jsx)("div",{className:"fixed bottom-4 right-4 z-50 w-[600px]",children:(0,s.jsx)("div",{className:"rounded-lg border bg-destructive/15 p-4",children:(0,s.jsx)("div",{className:"flex items-center gap-2",children:(0,s.jsx)("p",{className:"text-sm font-medium text-destructive",children:"No preview data available"})})})});let p=t.filter(e=>(e.migration||e.name||"").endsWith(".sql")),g=p.length;console.log("Migration stats:",{totalMigrations:g});let N=h&&!o&&!u;return(0,s.jsx)("div",{className:"fixed bottom-4 right-4 z-50 font-sans w-[600px]",children:(0,s.jsx)("div",{className:(0,d.cn)("rounded-lg border p-4 shadow-lg",u?"bg-destructive/15":"bg-background"),children:(0,s.jsx)("div",{className:"flex items-start gap-x-1",children:(0,s.jsxs)("div",{className:"flex-1 space-y-3",children:[(0,s.jsxs)("div",{className:"space-y-1",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between",children:[(0,s.jsx)("h5",{className:(0,d.cn)("font-medium",u?"text-destructive":"text-neutral-900"),children:u?"Pull Migration Error":"Pull Migration Preview"}),(0,s.jsx)("button",{onClick:n,className:"text-neutral-500 hover:text-neutral-900 p-1 rounded-md hover:bg-neutral-100",children:(0,s.jsx)(v.A,{className:"h-4 w-4"})})]}),(0,s.jsx)("p",{className:(0,d.cn)("text-sm",u?"text-destructive/80":"text-neutral-700"),children:"".concat(g," migration(s) will be applied")}),u&&(0,s.jsx)("p",{className:"text-sm text-destructive font-medium mt-1",children:u.message}),h&&(0,s.jsx)("p",{className:"text-sm text-green-700 font-medium mt-1",children:h})]}),(0,s.jsxs)("div",{children:[(0,s.jsx)("button",{onClick:()=>f(!x),className:"text-sm font-medium hover:underline",children:x?"Hide Details":"Show Details"}),x&&(0,s.jsx)(L,{className:"h-[480px] mt-2 rounded border border-neutral-200",children:(0,s.jsxs)("div",{className:"w-full",children:[(0,s.jsx)("div",{className:"bg-neutral-50 border-b px-4 py-2",children:(0,s.jsx)("div",{className:"text-sm font-medium text-neutral-600",children:"Migration"})}),(0,s.jsx)("div",{children:p.map((e,t)=>(0,s.jsx)("div",{className:"px-4 py-2 border-b last:border-0",children:(0,s.jsx)("div",{className:"font-mono text-xs",children:e.migration||e.name})},t))})]})})]}),(0,s.jsx)("div",{className:"flex flex-col gap-2 pt-1",children:(0,s.jsxs)("div",{className:"flex gap-2",children:[(0,s.jsx)(A,{onClick:a,disabled:i,className:"flex-1 ".concat(i?"cursor-not-allowed opacity-50":""),children:i?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin"}),"Confirming..."]}):"Confirm Pull"}),(0,s.jsxs)("div",{className:"flex-1 flex flex-col gap-2",children:[(0,s.jsx)(A,{onClick:r,disabled:!N,variant:"outline",className:"w-full ".concat(N?"":"cursor-not-allowed opacity-50"),children:o?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin"}),"Syncing remote data..."]}):"Sync remote data"}),(0,s.jsx)("p",{className:"text-xs text-neutral-500 text-center",children:"75 records per table"})]})]})})]})})})})};var K=a(3409),J=a(2645),q=a(2488),Y=a(7193);let X=K.bL;K.YJ;let H=K.WT,W=l.forwardRef((e,t)=>{let{className:a,children:l,...n}=e;return(0,s.jsxs)(K.l9,{ref:t,className:(0,d.cn)("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",a),...n,children:[l,(0,s.jsx)(K.In,{asChild:!0,children:(0,s.jsx)(J.A,{className:"h-4 w-4 opacity-50"})})]})});W.displayName=K.l9.displayName;let B=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(K.PP,{ref:t,className:(0,d.cn)("flex cursor-default items-center justify-center py-1",a),...l,children:(0,s.jsx)(q.A,{className:"h-4 w-4"})})});B.displayName=K.PP.displayName;let G=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(K.wn,{ref:t,className:(0,d.cn)("flex cursor-default items-center justify-center py-1",a),...l,children:(0,s.jsx)(J.A,{className:"h-4 w-4"})})});G.displayName=K.wn.displayName;let Z=l.forwardRef((e,t)=>{let{className:a,children:l,position:n="popper",...r}=e;return(0,s.jsx)(K.ZL,{children:(0,s.jsxs)(K.UC,{ref:t,className:(0,d.cn)("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","popper"===n&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",a),position:n,...r,children:[(0,s.jsx)(B,{}),(0,s.jsx)(K.LM,{className:(0,d.cn)("p-1","popper"===n&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:l}),(0,s.jsx)(G,{})]})})});Z.displayName=K.UC.displayName,l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(K.JU,{ref:t,className:(0,d.cn)("px-2 py-1.5 text-sm font-semibold",a),...l})}).displayName=K.JU.displayName;let $=l.forwardRef((e,t)=>{let{className:a,children:l,...n}=e;return(0,s.jsxs)(K.q7,{ref:t,className:(0,d.cn)("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...n,children:[(0,s.jsx)("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,s.jsx)(K.VF,{children:(0,s.jsx)(Y.A,{className:"h-4 w-4"})})}),(0,s.jsx)(K.p4,{children:l})]})});$.displayName=K.q7.displayName,l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(K.wv,{ref:t,className:(0,d.cn)("-mx-1 my-1 h-px bg-muted",a),...l})}).displayName=K.wv.displayName;var ee=a(2303),et=a(319),ea=a(5942);function es(e){let{value:t,onValueChange:a,isLoading:l,disabled:n,showPreview:r}=e;return(0,s.jsxs)(X,{value:t,onValueChange:a,disabled:n||l||r,children:[(0,s.jsx)(W,{className:"w-full bg-white border-neutral-200 font-medium",children:(0,s.jsx)("div",{className:"flex items-center gap-1 text-sm",children:l||r?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin text-muted-foreground"}),(0,s.jsx)("span",{className:"text-muted-foreground font-medium",children:"pull"===t?"Pulling...":"syncing"===t?"Syncing...":"production"===t?"Pushing...":"Loading..."})]}):(0,s.jsx)(H,{placeholder:"Environment",className:"w-full"})})}),(0,s.jsxs)(Z,{children:[(0,s.jsx)($,{value:"local",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(ee.A,{className:"h-4 w-4"}),(0,s.jsx)("span",{children:"Local"})]})}),(0,s.jsx)($,{value:"pull",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(et.A,{className:"h-4 w-4"}),(0,s.jsx)("span",{children:"Pull remote"})]})}),(0,s.jsx)($,{value:"production",children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(ea.A,{className:"h-4 w-4"}),(0,s.jsx)("span",{children:"Push remote"})]})})]})]})}function el(e){var t;let{className:a,currentView:d,onNavigate:m,onTableSelect:h}=e,{tables:g,refreshTables:v,isLoading:N,error:j}=(0,p.t)(),[b,w]=(0,l.useState)([]),[y,C]=(0,l.useState)(""),[S,E]=(0,l.useState)("local"),[R,T]=(0,l.useState)(!1),[A,O]=(0,l.useState)(null),[L,I]=(0,l.useState)(!1),{isConnecting:P,isPushing:U,showPreview:F,connectToCloudflare:D,pushToRemote:M,pullFromRemote:z,pullToRemotePreview:K,validateStoredCredentials:J,PreviewUI:q}=function(){var e,t;let[a,n]=(0,l.useState)(!1),[r,i]=(0,l.useState)(!1),[o,c]=(0,l.useState)(!1),[d,u]=(0,l.useState)(!1),[m,h]=(0,l.useState)(null),[x,f]=(0,l.useState)(null),[g,v]=(0,l.useState)(null),[N,j]=(0,l.useState)(null),[b,w]=(0,l.useState)("local"),{toast:y}=(0,_.dj)(),{refreshTables:C}=(0,p.t)(),S=()=>{u(!1),h(null),f(null),v(null),j(null)},E=async()=>{let e=localStorage.getItem("cf_credentials");if(!e)return null;try{let t=JSON.parse(e),a=await fetch("/api/cloudflare",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok)throw Error("Invalid stored credentials");let s=await a.json();return{...t,databaseId:s.database.id}}catch(e){return console.error("Failed to validate stored credentials:",e),localStorage.removeItem("cf_credentials"),null}},R=async()=>{try{v("push"),u(!0),i(!0),f(null),j(null),h({preview:[]});let t=await E();if(!t)throw Error("No valid credentials found");let a=await fetch("/api/push-remote/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await a.json();if(!s.success){var e;throw Error((null===(e=s.error)||void 0===e?void 0:e.message)||"Failed to generate preview")}h(s.details.details)}catch(e){console.error("Push to remote preview failed:",e),f(e),y({title:"Preview Failed",description:e.message||"Failed to generate preview",variant:"destructive"})}finally{i(!1)}},T=async()=>{try{i(!0),f(null),j(null);let t=await E();if(!t)throw Error("No valid credentials found");let a=await fetch("/api/push-remote/confirm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await a.json();if(!s.success){var e;throw Error((null===(e=s.error)||void 0===e?void 0:e.message)||"Failed to confirm push")}h(e=>({...e,preview:e.preview.map(e=>({...e,action:"will be applied"===e.action?"applied":e.action}))})),j("Applied ".concat(s.details.applied," migration(s), skipped ").concat(s.details.skipped,".")),w("local")}catch(e){console.error("Push to remote confirm failed:",e),f(e),w("local")}finally{i(!1)}},A=async()=>{try{v("pull"),u(!0),i(!0),f(null),j(null),h({preview:[]});let t=await E();if(!t)throw Error("No valid credentials found");let a=await fetch("/api/pull-remote/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await a.json();if(!s.success){var e;throw Error((null===(e=s.error)||void 0===e?void 0:e.message)||"Failed to generate pull preview")}h(s.details)}catch(e){console.error("Pull to remote preview failed:",e),f(e),y({title:"Preview Failed",description:e.message||"Failed to generate pull preview",variant:"destructive"})}finally{i(!1)}},k=async()=>{try{i(!0),w("pull"),f(null),j(null);let t=await E();if(!t)throw Error("No valid credentials found");let a=await fetch("/api/pull-remote/confirm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await a.json();if(!s.success){var e;throw Error((null===(e=s.error)||void 0===e?void 0:e.message)||"Failed to confirm pull")}j("Pull migrations applied successfully."),h(e=>({...e,preview:e.preview.map(e=>({...e,action:"will be applied"===e.action?"applied":e.action}))})),await C()}catch(e){console.error("Pull to remote confirm failed:",e),f(e)}finally{i(!1),w("local")}},O=async()=>{try{c(!0),w("syncing"),f(null),j(null);let t=await E();if(!t)throw Error("No valid credentials found");let a=await fetch("/api/pull-data/confirm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),s=await a.json();if(!s.success){var e;throw Error((null===(e=s.error)||void 0===e?void 0:e.message)||"Failed to confirm data pull")}j("Remote data synced successfully."),await C()}catch(e){console.error("Data pull confirm failed:",e),f(e)}finally{c(!1),w("local")}};async function L(e){try{n(!0);let t=await fetch("/api/cloudflare",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),a=await t.json();if(!t.ok)throw Error(a.error||"Failed to connect to Cloudflare");localStorage.setItem("cf_credentials",JSON.stringify({...e,databaseId:a.database.id})),y({title:"Connected to Cloudflare",description:"Connected to database: ".concat(a.database.name),variant:"default"})}catch(e){throw y({title:"Connection Failed",description:e.message||"Failed to connect to Cloudflare",variant:"destructive"}),e}finally{n(!1)}}let I=d&&("pull"===g?(0,s.jsx)(V,{preview:(null==m?void 0:m.preview)||[],onConfirm:k,onDataPull:O,onCancel:S,isConfirming:r,isDataPulling:o,error:x,success:N,isLoading:r&&!(null==m?void 0:null===(e=m.preview)||void 0===e?void 0:e.length)}):(0,s.jsx)(Q,{preview:(null==m?void 0:m.preview)||[],onConfirm:T,onCancel:S,isConfirming:r,error:x,success:N,isLoading:r&&!(null==m?void 0:null===(t=m.preview)||void 0===t?void 0:t.length)}));return{isConnecting:a,isPushing:r,isDataPulling:o,showPreview:d,previewError:x,environment:b,setEnvironment:w,pushToRemote:R,pullToRemotePreview:A,confirmPull:k,confirmDataPull:O,connectToCloudflare:L,validateStoredCredentials:E,PreviewUI:I}}(),Y=(0,l.useMemo)(()=>{let e=[...(null==g?void 0:g.filter(e=>e.toLowerCase().includes(y.toLowerCase())))||[]].sort((e,t)=>e.localeCompare(t)),t=e.indexOf("d1_migrations");return -1!==t&&(e.splice(t,1),e.unshift("d1_migrations")),e},[g,y]),X=async e=>{try{I(!0),O(e),h(e)}catch(e){console.error("Error selecting table:",e)}finally{I(!1)}},H=async e=>{if(console.log("Environment change triggered:",e),E(e),"production"===e)try{if(!await J()){T(!0);return}await M()}catch(e){console.error("Environment change failed:",e),E("local")}else if("pull"===e)try{if(!await J()){T(!0);return}await K()}catch(e){console.error("Pull from remote failed:",e),E("local")}else E(e)};return(0,l.useEffect)(()=>{(async()=>{try{let e=await fetch("/api/databases"),t=await e.json();if(!e.ok)throw Error(t.error||"Failed to fetch databases");w(t.databases||[])}catch(e){console.error("Error fetching databases:",e)}})(),v()},[v]),(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("aside",{className:"".concat(a," top-[var(--banner-height,0px)] left-0 h-[calc(100vh-var(--banner-height,0px))] bg-neutral-50 p-4"),children:[(0,s.jsxs)("div",{className:"flex flex-col h-full font-sans",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,s.jsx)(n.A,{className:"h-5 w-5"}),(0,s.jsx)("span",{className:"font-mono font-bold text-sm",children:"d1-studio"})]}),j&&(0,s.jsxs)(x,{variant:"destructive",className:"mb-4",children:[(0,s.jsx)(r.A,{className:"h-4 w-4"}),(0,s.jsx)(f,{className:"text-sm ml-2",children:j})]}),(0,s.jsxs)("div",{className:"mb-2",children:[(0,s.jsx)("div",{className:"text-xs text-muted-foreground mb-1",children:"Database name"}),(0,s.jsx)("div",{className:"font-semibold text-sm",children:(null===(t=b[0])||void 0===t?void 0:t.database_name)||"No database found"})]}),(0,s.jsx)("div",{className:"mb-6",children:(0,s.jsx)(es,{className:"w-full",value:S,onValueChange:H,isLoading:U,disabled:P,showPreview:F})}),(0,s.jsx)("div",{className:"mb-3",children:(0,s.jsxs)("button",{className:"w-full flex items-center gap-x-1 border rounded-md text-sm font-medium transition-colors px-2 py-2\n ".concat("sql-editor"===d?"bg-neutral-900 text-white":"bg-white hover:bg-neutral-100"),onClick:()=>m("sql-editor"),disabled:L,children:[(0,s.jsx)(i.A,{className:"h-[16px] w-[16px]"}),"SQL editor"]})}),(0,s.jsxs)("div",{className:"relative mb-3 bg-white",children:[(0,s.jsx)(o.A,{className:"absolute left-2 top-2.5 h-4 w-4 text-neutral-500"}),(0,s.jsx)(u,{placeholder:"Search tables",value:y,onChange:e=>C(e.target.value),className:"pl-7"})]}),(0,s.jsxs)("div",{className:"flex-1 min-h-0 flex flex-col",children:[(0,s.jsxs)("div",{className:"flex items-center justify-between mb-1 flex-none",children:[(0,s.jsxs)("h3",{className:"text-sm font-medium text-muted-foreground",children:["Tables ",(null==g?void 0:g.length)?"(".concat(g.length,")"):""]}),N&&(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin text-muted-foreground"})]}),(0,s.jsx)("div",{className:"overflow-y-auto flex-1",children:(0,s.jsxs)("div",{className:"pr-2 pb-4",children:[" ",!N&&0===Y.length&&(0,s.jsx)("div",{className:"text-sm font-medium text-muted-foreground px-2 py-2",children:y?"No matching tables found":j?"Error loading tables":"No tables available"}),Y.map(e=>(0,s.jsx)("button",{className:"w-full text-left text-sm font-medium rounded-md transition-colors px-2 py-2\n ".concat("table-view"===d&&A===e?"bg-[#F0F0F0] text-neutral-900 font-semibold":"text-neutral-700 hover:bg-[#F2F2F2]","\n ").concat(L&&"opacity-50 cursor-not-allowed"),onClick:()=>X(e),disabled:L,children:e},e))]})})]})]}),(0,s.jsx)(k,{open:R,onClose:()=>{T(!1),E("local")},onSubmit:D})]}),q]})}var en=a(707),er=a(1170),ei=a(939),eo=a(5377);function ec(e){let{results:t}=e;return t&&Array.isArray(t)?(0,s.jsxs)("div",{className:"text-xs font-medium text-neutral-900 flex items-center gap-2 mb-2",children:[t.length," ",1===t.length?"row":"rows"," returned"]}):null}function ed(e){var t;let{error:a}=e;console.debug("SQLErrorDisplay - Received error prop:",a);let l=a&&"string"==typeof a.message?a:{message:"An unknown error occurred",details:{}};return(0,s.jsxs)("div",{children:[(0,s.jsx)("div",{className:"text-neutral-700 text-sm",children:l.message}),(null===(t=l.details)||void 0===t?void 0:t.stderr)&&(0,s.jsx)("pre",{className:"mt-2 p-2 text-xs text-red-500 whitespace-pre-wrap",children:l.details.stderr})]})}function eu(e){let{query:t,results:a}=e;if(!(null==a?void 0:a.length))return(0,s.jsx)("div",{className:"text-sm text-neutral-500",children:"No results to display."});let l=null==t?void 0:t.trim().toLowerCase().startsWith("pragma table_info"),n=l?["Column Name","Type","Not Null","Default Value","Primary Key"]:Object.keys(a[0]),r=l?a.map(e=>({"Column Name":e.name,Type:e.type,"Not Null":1===e.notnull?"YES":"NO","Default Value":e.dflt_value||"(null)","Primary Key":1===e.pk?"YES":"NO"})):a;return(0,s.jsxs)("div",{className:"flex flex-col h-full",children:[(0,s.jsx)(ec,{results:r}),(0,s.jsx)("div",{className:"flex-1 overflow-auto border rounded-lg",children:(0,s.jsx)("div",{className:"min-w-full",children:(0,s.jsxs)(P,{children:[(0,s.jsx)(U,{children:(0,s.jsx)(D,{className:"bg-muted/50",children:n.map(e=>(0,s.jsx)(M,{className:"font-mono text-xs font-medium text-muted-foreground",children:e},e))})}),(0,s.jsx)(F,{children:r.map((e,t)=>(0,s.jsx)(D,{className:"hover:bg-muted/50",children:n.map(a=>{let l=e[a],n=null===l?"(null)":String(l);return(0,s.jsx)(z,{className:"font-monospace text-xs whitespace-nowrap",children:n},"".concat(t,"-").concat(a))})},t))})]})})})]})}var em=a(4471),eh=a(5325),ex=a(1703);let ef=em.bL,ep=em.l9;em.YJ,em.ZL,em.Pb,em.z6,l.forwardRef((e,t)=>{let{className:a,inset:l,children:n,...r}=e;return(0,s.jsxs)(em.ZP,{ref:t,className:(0,d.cn)("flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",l&&"pl-8",a),...r,children:[n,(0,s.jsx)(eh.A,{className:"ml-auto"})]})}).displayName=em.ZP.displayName,l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(em.G5,{ref:t,className:(0,d.cn)("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...l})}).displayName=em.G5.displayName;let eg=l.forwardRef((e,t)=>{let{className:a,sideOffset:l=4,...n}=e;return(0,s.jsx)(em.ZL,{children:(0,s.jsx)(em.UC,{ref:t,sideOffset:l,className:(0,d.cn)("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n})})});eg.displayName=em.UC.displayName;let ev=l.forwardRef((e,t)=>{let{className:a,inset:l,...n}=e;return(0,s.jsx)(em.q7,{ref:t,className:(0,d.cn)("relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",l&&"pl-8",a),...n})});ev.displayName=em.q7.displayName,l.forwardRef((e,t)=>{let{className:a,children:l,checked:n,...r}=e;return(0,s.jsxs)(em.H_,{ref:t,className:(0,d.cn)("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),checked:n,...r,children:[(0,s.jsx)("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,s.jsx)(em.VF,{children:(0,s.jsx)(Y.A,{className:"h-4 w-4"})})}),l]})}).displayName=em.H_.displayName,l.forwardRef((e,t)=>{let{className:a,children:l,...n}=e;return(0,s.jsxs)(em.hN,{ref:t,className:(0,d.cn)("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",a),...n,children:[(0,s.jsx)("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:(0,s.jsx)(em.VF,{children:(0,s.jsx)(ex.A,{className:"h-2 w-2 fill-current"})})}),l]})}).displayName=em.hN.displayName,l.forwardRef((e,t)=>{let{className:a,inset:l,...n}=e;return(0,s.jsx)(em.JU,{ref:t,className:(0,d.cn)("px-2 py-1.5 text-sm font-semibold",l&&"pl-8",a),...n})}).displayName=em.JU.displayName,l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(em.wv,{ref:t,className:(0,d.cn)("-mx-1 my-1 h-px bg-muted",a),...l})}).displayName=em.wv.displayName;let eN={SYNTAX_ERROR:"SYNTAX_ERROR",EXECUTION_ERROR:"EXECUTION_ERROR",TABLE_NOT_FOUND:"TABLE_NOT_FOUND",TABLE_EXISTS:"TABLE_EXISTS",FOREIGN_KEY_ERROR:"FOREIGN_KEY_ERROR",UNIQUE_CONSTRAINT_ERROR:"UNIQUE_CONSTRAINT_ERROR",NOT_NULL_CONSTRAINT_ERROR:"NOT_NULL_CONSTRAINT_ERROR",CHECK_CONSTRAINT_ERROR:"CHECK_CONSTRAINT_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"};function ej(e){if(console.debug("parseSQLError - Received error:",e),!e)return console.debug("parseSQLError - error is null or undefined."),{type:eN.UNKNOWN_ERROR,message:"An unknown error occurred",details:{}};let t="",a=null,s=null,l=e.cmd||e.details&&e.details.command;if(l){let e=l.match(RegExp('--command="(.+?)"',"s"));e&&console.debug("parseSQLError - Extracted original query:",s=e[1].replace(/\\n/g,"\n"))}let n=e.stderr||e.details&&e.details.stderr;if(n){let r=n.replace(/\x1B\[[0-9;]*[a-zA-Z]/g,"");if(console.debug("parseSQLError - Cleaned stderr:",r),r.includes("env: node: No such file or directory"))return console.debug("parseSQLError - Detected 'env: node: No such file or directory' error."),{type:eN.EXECUTION_ERROR,message:e.message||"Execution error: env: node: No such file or directory",details:{originalQuery:s,stderr:r}};let i=r.match(/near "([^"]+)": syntax error at offset (\d+)/);if(i){let[e,l,n]=i;return a=parseInt(n,10),t='Syntax error near "'.concat(l,'" at position ').concat(a),console.debug("parseSQLError - Syntax error detected:",{near:l,offset:a}),{type:eN.SYNTAX_ERROR,message:t,details:{originalQuery:s,errorLocation:{offset:a,near:l},stderr:r}}}if(r.includes("UNIQUE constraint failed")){let[e,t,a]=r.match(/UNIQUE constraint failed: (\w+)\.(\w+)/)||[];return console.debug("parseSQLError - UNIQUE constraint error detected:",{table:t,column:a}),{type:eN.UNIQUE_CONSTRAINT_ERROR,message:"Unique constraint violation updating ".concat(t,".").concat(a),details:{originalQuery:s,stderr:r}}}if(r.includes("NOT NULL constraint failed")){let[e,t,a]=r.match(/NOT NULL constraint failed: (\w+)\.(\w+)/)||[];return console.debug("parseSQLError - NOT NULL constraint error detected:",{table:t,column:a}),{type:eN.NOT_NULL_CONSTRAINT_ERROR,message:"NOT NULL constraint violation updating ".concat(t,".").concat(a),details:{originalQuery:s,stderr:r}}}if(r.includes("CHECK constraint failed")){let[e,t]=r.match(/CHECK constraint failed: (\w+)/)||[];return console.debug("parseSQLError - CHECK constraint error detected:",{constraintName:t}),{type:eN.CHECK_CONSTRAINT_ERROR,message:"Check constraint violation updating ".concat(t),details:{originalQuery:s,stderr:r}}}if(r.includes("FOREIGN KEY constraint failed")){console.debug("parseSQLError - FOREIGN KEY constraint error detected.");let e=/--command="([^"]+)"/.exec(l||""),t=e?e[1]:null,a={};if(t){let e=/UPDATE\s+(\w+)\s+SET\s+(\w+)\s*=/.exec(t);e&&(a={table:e[1],column:e[2]})}let s=a.table?"Foreign key constraint violation updating ".concat(a.table,".").concat(a.column):"Foreign key constraint violation";return{type:eN.FOREIGN_KEY_ERROR,message:s,details:{...a,originalQuery:t,stderr:r}}}if(r.includes("no such table")){let[e,t]=r.match(/no such table: (\w+)/)||[];return console.debug("parseSQLError - Table not found error detected:",{table:t}),{type:eN.TABLE_NOT_FOUND,message:"Table not found: ".concat(t),details:{originalQuery:s,stderr:r}}}if(r.includes("already exists")){let[e,t]=r.match(/table (\w+) already exists/)||[];return console.debug("parseSQLError - Table exists error detected:",{table:t}),{type:eN.TABLE_EXISTS,message:"Table already exists: ".concat(t),details:{originalQuery:s,stderr:r}}}return console.debug("parseSQLError - No specific error match found. Using fallback for execution error."),{type:eN.EXECUTION_ERROR,message:e.message||"Failed to execute SQL command",details:{originalQuery:s,stderr:r}}}return console.debug("parseSQLError - No stderr available; using default error handling."),{type:eN.UNKNOWN_ERROR,message:e.message||"An unknown error occurred",details:{}}}let eb={"Show Tables":"SELECT name\n FROM sqlite_master \n WHERE type='table' \n AND name NOT LIKE 'sqlite_%';","Table Schema":"-- Table Schema\n-- Replace table_name with your table name\nPRAGMA table_info(table_name);","Table Indexes":"-- Table Indexes\n-- Replace table_name with your table name\nSELECT \n m.name as table_name,\n i.name as index_name,\n i.sql as index_definition\nFROM sqlite_master m\nJOIN sqlite_master i ON m.name = i.tbl_name\nWHERE m.type = 'table'\nAND i.type = 'index'\nAND m.name = 'table_name';","Foreign Keys":"-- Foreign Key Information\n-- Replace table_name with your table name\nPRAGMA foreign_key_list(table_name);","Table Data":"-- Table Data\n-- Replace table_name with your table name\nSELECT * FROM table_name LIMIT 100;","Row Count":"-- Row Count\n-- Replace table_name with your table name\nSELECT COUNT(*) as total_rows FROM table_name;","Column Stats":"-- Column Statistics\n-- Replace table_name and column_name with your values\nSELECT \n COUNT(*) as total_rows,\n COUNT(column_name) as non_null_count,\n COUNT(DISTINCT column_name) as unique_values,\n MIN(column_name) as min_value,\n MAX(column_name) as max_value\nFROM table_name;","Create Table":"CREATE TABLE IF NOT EXISTS new_table (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL,\n email TEXT UNIQUE,\n status TEXT CHECK(status IN ('active', 'inactive')) DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP\n);\n\n-- Create indexes\nCREATE INDEX idx_new_table_name ON new_table(name);\nCREATE UNIQUE INDEX idx_new_table_email ON new_table(email);","Create View":"-- Create a view\nCREATE VIEW view_name AS\nSELECT column1, column2\nFROM table_name\nWHERE condition;"},ew={"Schema Information":["Show Tables","Table Schema","Table Indexes","Foreign Keys"],"Data Queries":["Table Data","Row Count","Column Stats"],"Schema Modification":["Create Table","Create View"]};function ey(e){let{onSelectQuery:t}=e;return(0,s.jsxs)(ef,{children:[(0,s.jsx)(ep,{asChild:!0,children:(0,s.jsxs)(A,{variant:"outline",size:"sm",children:["Query Templates",(0,s.jsx)(J.A,{className:"ml-2 h-4 w-4"})]})}),(0,s.jsx)(eg,{align:"start",className:"w-72",children:Object.entries(ew).map(e=>{let[a,n]=e;return(0,s.jsxs)(l.Fragment,{children:[(0,s.jsx)("div",{className:"px-2 py-1.5 text-sm font-semibold text-neutral-900 font-sans",children:a}),n.map(e=>(0,s.jsx)(ev,{onClick:()=>t(e),className:"font-sans text-neutral-800",children:e},e))]},a)})})]})}function eC(){let{executeQuery:e,refreshTables:t}=(0,p.t)(),[a,n]=(0,l.useState)(null),[r,i]=(0,l.useState)(!1),[o,d]=(0,l.useState)(300),[u,m]=(0,l.useState)(!1),h=(0,l.useRef)(null),x=(0,l.useRef)(null);(0,l.useEffect)(()=>{x.current&&(x.current.style.height="".concat(o,"px"))},[o]);let f=(0,l.useCallback)(e=>{e.preventDefault();let t=e.pageY,a=e=>{d(Math.min(Math.max(o+(e.pageY-t),100),.8*window.innerHeight))},s=()=>{document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",s)};document.addEventListener("mousemove",a),document.addEventListener("mouseup",s)},[o]),g=async()=>{if(!h.current)return;let a=h.current.getValue().trim().replace(/;+$/,"");if(!a){n({success:!1,error:{message:"Query cannot be empty."}});return}try{var s,l,r,o;i(!0),n(null);let c=await e(a);/^(CREATE|DROP|ALTER)\s+TABLE/i.test(a)&&await t();let d=[];if(c.results){if(Array.isArray(c.results)){if(c.results.length>0&&(null===(s=c.results[0])||void 0===s?void 0:s.columns)&&(null===(l=c.results[0])||void 0===l?void 0:l.values)){let e=c.results[0];d=e.values.map(t=>e.columns.reduce((e,a,s)=>(e[a]=t[s],e),{}))}else d=1===c.results.length&&c.results[0].results&&Array.isArray(c.results[0].results)?c.results[0].results:c.results}else if(c.results.columns&&c.results.values){let e=c.results;d=e.values.map(t=>e.columns.reduce((e,a,s)=>(e[a]=t[s],e),{}))}}else if(c.result&&c.result.results){if(Array.isArray(c.result.results)){if(c.result.results.length>0&&(null===(r=c.result.results[0])||void 0===r?void 0:r.columns)&&(null===(o=c.result.results[0])||void 0===o?void 0:o.values)){let e=c.result.results[0];d=e.values.map(t=>e.columns.reduce((e,a,s)=>(e[a]=t[s],e),{}))}else d=1===c.result.results.length&&c.result.results[0].results&&Array.isArray(c.result.results[0].results)?c.result.results[0].results:c.result.results}else if(c.result.results.columns&&c.result.results.values){let e=c.result.results;d=e.values.map(t=>e.columns.reduce((e,a,s)=>(e[a]=t[s],e),{}))}}n({success:!0,results:d})}catch(e){n({success:!1,error:ej(e)||{message:"An unknown error occurred",details:{}}})}finally{i(!1)}};return(0,s.jsxs)("div",{className:"h-full flex flex-col bg-white text-neutral-900 font-sans",children:[(0,s.jsx)("div",{className:"px-4 py-2 bg-neutral-100 border-b flex items-center gap-4",children:(0,s.jsx)(ey,{onSelectQuery:e=>{if(h.current){let t=Object.keys(eb).find(t=>t.toLowerCase()===e.toLowerCase());if(t){let e=eb[t];h.current.setValue(e),h.current.focus()}else console.warn("Query template not found for: ".concat(e))}}})}),(0,s.jsx)("div",{ref:x,className:"relative pt-2 overflow-hidden",style:{height:"".concat(o,"px"),minHeight:"100px"},children:(0,s.jsx)(en.Ay,{height:"100%",language:"sql",options:{minimap:{enabled:!1},fontSize:14,wordWrap:"on",automaticLayout:!0,lineNumbers:"on",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},onMount:e=>{h.current=e,e.addCommand(monaco.KeyMod.CtrlCmd|monaco.KeyCode.Enter,()=>{g()})}})}),(0,s.jsx)("div",{className:"relative h-0.5 cursor-row-resize bg-neutral-200 group ".concat(u?"bg-neutral-300":"hover:bg-neutral-300"),onMouseDown:e=>{m(!0),f(e)},onMouseUp:()=>m(!1),children:(0,s.jsx)("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-neutral-900 rounded-sm px-0.5 \n ".concat(u?"visible":"invisible group-hover:visible"),children:(0,s.jsx)(er.A,{className:"h-3 w-3 text-white"})})}),(0,s.jsx)("div",{className:"px-4 py-3 bg-neutral-100 border-b font-sans",children:(0,s.jsxs)("div",{className:"flex justify-between items-center",children:[(0,s.jsx)("h3",{className:"text-sm font-medium",children:"Results"}),(0,s.jsxs)(A,{size:"sm",onClick:g,disabled:r,className:"flex items-center gap-1 text-sm font-medium",children:["Run",r?(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin"}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(ei.A,{className:"h-4 w-4"}),(0,s.jsx)(eo.A,{className:"h-4 w-4"})]})]})]})}),(0,s.jsx)("div",{className:"flex-1 overflow-auto p-4 bg-white",children:(()=>{var e;if(r)return(0,s.jsxs)("div",{className:"flex items-center text-sm text-neutral-700",children:[(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin mr-2 font-sans"}),"Running your query..."]});if(!a)return(0,s.jsx)("div",{className:"text-sm text-neutral-500 font-sans",children:"Run the query to see the results."});if(!a.success)return console.debug("SQLEditor - Rendering error:",a.error),(0,s.jsx)(ed,{error:a.error});let t=a.results;return t&&0!==t.length?(0,s.jsx)(eu,{query:(null===(e=h.current)||void 0===e?void 0:e.getValue())||"",results:t}):(0,s.jsx)("div",{className:"text-sm text-neutral-900 font-sans",children:"Success. No results to display."})})()})]})}var eS=a(6352);let eE=l.forwardRef((e,t)=>{let{className:a,...l}=e;return(0,s.jsx)(eS.bL,{ref:t,className:(0,d.cn)("peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",a),...l,children:(0,s.jsx)(eS.C1,{className:(0,d.cn)("flex items-center justify-center text-current"),children:(0,s.jsx)(Y.A,{className:"h-4 w-4"})})})});eE.displayName=eS.bL.displayName;var eR=a(138),eT=a(1598),eA=a(2884),ek=a(9710);let e_=ek.Kq,eO=ek.bL,eL=ek.l9,eI=l.forwardRef((e,t)=>{let{className:a,sideOffset:l=4,...n}=e;return(0,s.jsx)(ek.ZL,{children:(0,s.jsx)(ek.UC,{ref:t,sideOffset:l,className:(0,d.cn)("z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a),...n})})});eI.displayName=ek.UC.displayName;var eP=a(6235);let eU=(0,l.memo)(e=>{let{onRefresh:t,disabled:a}=e,[n,r]=(0,l.useState)(!1),i=async()=>{if(!n&&!a){r(!0);try{await t()}catch(e){console.error("Refresh failed:",e)}finally{setTimeout(()=>{r(!1)},500)}}};return(0,s.jsx)(e_,{children:(0,s.jsxs)(eO,{children:[(0,s.jsx)(eL,{asChild:!0,children:(0,s.jsx)(A,{variant:"outline",size:"icon",onClick:i,disabled:n||a,className:"h-8",children:n?(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin"}):(0,s.jsx)(eP.A,{className:"h-4 w-4"})})}),(0,s.jsx)(eI,{children:(0,s.jsx)("p",{children:"Refresh table data"})})]})})});eU.displayName="RefreshButton";var eF=a(7973);let eD=(0,l.memo)(e=>{let{tableName:t,onSync:a}=e,[n,r]=(0,l.useState)(!1),{toast:i}=(0,_.dj)();if("d1_migrations"!==t)return null;let o=async()=>{try{r(!0);let e=await fetch("/api/migrations/sync-files",{method:"POST"}),t=await e.json();if(!e.ok)throw Error(t.error||"Failed to sync migrations");let{added:s=[],removed:l=[]}=t.details||{};i({title:"Migrations Synced",description:"Added: ".concat(s.length,", Removed: ").concat(l.length)}),a&&await a()}catch(e){console.error("Error syncing migrations:",e),i({variant:"destructive",title:"Sync Failed",description:e.message})}finally{r(!1)}};return(0,s.jsx)(e_,{children:(0,s.jsxs)(eO,{children:[(0,s.jsx)(eL,{asChild:!0,children:(0,s.jsx)(A,{variant:"outline",size:"icon",onClick:o,disabled:n,className:"h-8",children:n?(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin"}):(0,s.jsx)(eF.A,{className:"h-4 w-4"})})}),(0,s.jsx)(eI,{children:(0,s.jsx)("p",{children:"Sync migration files with d1_migrations table"})})]})})});eD.displayName="SyncMigrationsButton";var eM=a(358),ez=a(8742),eQ=a(6697);let eV=(0,l.memo)(e=>{let{tableName:t,onDownloadStart:a,onDownloadComplete:n,disabled:r}=e,[i,o]=(0,l.useState)(!1),{toast:d}=(0,_.dj)(),u=(e,t)=>{try{let a=new Blob([e],{type:"application/octet-stream"}),s=window.URL.createObjectURL(a),l=document.createElement("a");l.href=s,l.download=t,document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(s)}catch(e){throw console.error("Error during file download:",e),e}},m=async e=>{if(!r)try{o(!0),null==a||a();let s=await fetch("/api/tables/".concat(t)),l=await s.json();if(!s.ok)throw Error(l.error||"Failed to fetch data");let{data:r,schema:i}=l;if(!(null==r?void 0:r.length)){d({title:"No Data",description:"The table is empty.",variant:"destructive"});return}let c=new Date().toISOString().split("T")[0],m="".concat(t,"_").concat(c,".").concat(e);switch(e){case"json":{let e=JSON.stringify(r,null,2);u(e,m);break}case"csv":{let e=Object.keys(r[0]),t=[e.join(","),...r.map(t=>e.map(e=>{let a=t[e];if(null==a)return"";if("string"==typeof a){let e=a.replace(/"/g,'""');return'"'.concat(e,'"')}return a}).join(","))].join("\n");u(t,m);break}case"sql":{let e="CREATE TABLE IF NOT EXISTS ".concat(t," (\n")+i.map(e=>{let t=[];return e.pk&&t.push("PRIMARY KEY"),e.notnull||t.push("NOT NULL")," ".concat(e.name," ").concat(e.type).concat(t.length?" ".concat(t.join(" ")):"")}).join(",\n")+"\n);\n\n",a=r.map(e=>{let a=Object.keys(e),s=a.map(t=>{let a=e[t];return null===a?"NULL":"string"==typeof a?"'".concat(a.replace(/'/g,"''"),"'"):a});return"INSERT INTO ".concat(t," (").concat(a.join(", "),")\nVALUES (").concat(s.join(", "),");")}).join("\n");u(e+a,m)}}d({title:"Download Complete",description:"".concat(r.length," rows exported as ").concat(e.toUpperCase(),".")}),null==n||n()}catch(e){console.error("Download error:",e),d({variant:"destructive",title:"Download Failed",description:e.message})}finally{o(!1)}};return(0,s.jsxs)(ef,{children:[(0,s.jsx)(e_,{children:(0,s.jsxs)(eO,{children:[(0,s.jsx)(eL,{asChild:!0,children:(0,s.jsx)(ep,{asChild:!0,children:(0,s.jsx)(A,{variant:"outline",size:"icon",className:"h-8",disabled:i||r,children:i?(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin"}):(0,s.jsx)(et.A,{className:"h-4 w-4"})})})}),(0,s.jsx)(eI,{children:(0,s.jsx)("p",{children:"Download table data"})})]})}),(0,s.jsxs)(eg,{align:"end",children:[(0,s.jsxs)(ev,{onClick:()=>m("json"),disabled:r,children:[(0,s.jsx)(eM.A,{className:"mr-2 h-4 w-4"}),(0,s.jsx)("span",{children:"Download JSON"})]}),(0,s.jsxs)(ev,{onClick:()=>m("csv"),disabled:r,children:[(0,s.jsx)(ez.A,{className:"mr-2 h-4 w-4"}),(0,s.jsx)("span",{children:"Download CSV"})]}),(0,s.jsxs)(ev,{onClick:()=>m("sql"),disabled:r,children:[(0,s.jsx)(eQ.A,{className:"mr-2 h-4 w-4"}),(0,s.jsx)("span",{children:"Download SQL"})]})]})]})});eV.displayName="DownloadButton";var eK=a(9045);let eJ=function(e){let{schema:t=[],visibleColumns:a=[],onColumnToggle:n}=e,[r,i]=(0,l.useState)("");(0,l.useEffect)(()=>{if(!t||0===t.length)return;let e=t.map(e=>e.name);0===a.length&&e.forEach(e=>n(e))},[t,a.length,n]);let o=t.filter(e=>e.name.toLowerCase().includes(r.toLowerCase())),c=o.map(e=>e.name),d=c.length>0&&c.every(e=>a.includes(e)),m=e=>{n(e)};return(0,s.jsxs)(ef,{children:[(0,s.jsx)(ep,{asChild:!0,children:(0,s.jsxs)(A,{size:"sm",variant:"outline",className:"font-semibold",children:[(0,s.jsx)(eK.A,{className:"h-4 w-4"}),"Columns (",a.length,")"]})}),(0,s.jsxs)(eg,{align:"end",className:"w-64 font-sans",children:[(0,s.jsx)("div",{className:"p-2",children:(0,s.jsx)(u,{placeholder:"Search columns...",value:r,onChange:e=>i(e.target.value),className:"h-8"})}),(0,s.jsxs)("div",{className:"flex items-center space-x-2 px-2 py-1.5 hover:bg-accent rounded-md",children:[(0,s.jsx)(eE,{id:"select-all-columns",checked:d,onCheckedChange:e=>{e?o.forEach(e=>{a.includes(e.name)||n(e.name)}):o.forEach(e=>{a.includes(e.name)&&n(e.name)})},className:"shrink-0"}),(0,s.jsxs)("label",{htmlFor:"select-all-columns",className:"flex-1 cursor-pointer text-sm font-medium",children:["Select All ",r&&"(Filtered)"]})]}),(0,s.jsx)("div",{className:"max-h-[300px] overflow-y-auto",children:o.map(e=>(0,s.jsxs)("div",{className:"flex items-start space-x-2 px-2 py-1.5 hover:bg-accent rounded-md",children:[(0,s.jsx)(eE,{id:"column-".concat(e.name),checked:a.includes(e.name),onCheckedChange:()=>m(e.name),className:"mt-1"}),(0,s.jsxs)("label",{htmlFor:"column-".concat(e.name),className:"flex-1 cursor-pointer",children:[(0,s.jsx)("div",{className:"text-sm font-medium",children:e.name}),(0,s.jsx)("div",{className:"text-xs text-muted-foreground",children:e.type.toLowerCase()})]})]},e.name))})]})]})},eq=(0,l.memo)(e=>{let{onAdd:t,onDelete:a,selectedCount:l,disabled:n,newRecordsCount:r,schema:i,visibleColumns:o,onColumnToggle:c}=e;return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)(e_,{children:(0,s.jsxs)(eO,{children:[(0,s.jsx)(eL,{asChild:!0,children:(0,s.jsx)("span",{children:(0,s.jsxs)(A,{size:"sm",variant:"outline",className:"font-semibold opacity-50 cursor-not-allowed",disabled:!0,children:[(0,s.jsx)(eR.A,{className:"h-4 w-4"}),"Filters"]})})}),(0,s.jsx)(eI,{children:(0,s.jsx)("p",{children:"Filters are not available yet. Coming soon!"})})]})}),(0,s.jsx)(eJ,{schema:i,visibleColumns:o,onColumnToggle:c}),(0,s.jsx)("div",{className:"h-4 border-r mx-2"}),(0,s.jsx)(A,{size:"sm",variant:"default",className:"font-semibold",onClick:t,children:"Add record"}),l>0&&(0,s.jsxs)(A,{size:"sm",className:"font-semibold",onClick:a,variant:"destructive",disabled:n||r>0,children:["Delete ",l," ",1===l?"record":"records"]})]})}),eY=(0,l.memo)(e=>{let{totalRows:t}=e;return(0,s.jsxs)("span",{className:"text-sm text-neutral-600",children:[t," ",1===t?"row":"rows"]})}),eX=(0,l.memo)(e=>{let{currentPage:t,totalPages:a,onPageChange:l,disabled:n,newRecordsCount:r}=e;return(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)(A,{variant:"ghost",size:"icon",onClick:()=>{console.log("Pagination: navigating to previous page",t-1),l(t-1)},disabled:1===t||n||r>0,className:"h-8",children:(0,s.jsx)(eT.A,{className:"h-4 w-4"})}),(0,s.jsxs)("span",{className:"text-sm",children:["Page ",t," of ",a]}),(0,s.jsx)(A,{variant:"ghost",size:"icon",onClick:()=>{console.log("Pagination: navigating to next page",t+1),l(t+1)},disabled:t===a||n||r>0,className:"h-8",children:(0,s.jsx)(eA.A,{className:"h-4 w-4"})})]})}),eH=(0,l.memo)(e=>{let{value:t,onValueChange:a,disabled:l,newRecordsCount:n}=e;return(0,s.jsxs)(X,{value:t.toString(),onValueChange:a,disabled:l||n>0,children:[(0,s.jsx)(W,{className:"w-20 h-8",children:(0,s.jsx)(H,{})}),(0,s.jsxs)(Z,{children:[(0,s.jsx)($,{value:"50",children:"50"}),(0,s.jsx)($,{value:"100",children:"100"}),(0,s.jsx)($,{value:"250",children:"250"})]})]})}),eW=(0,l.memo)(e=>{let{onSave:t,onDiscard:a,totalChanges:l,isSaving:n}=e;return(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(A,{size:"sm",variant:"ghost",className:"font-semibold",onClick:a,disabled:n,children:"Discard changes"}),(0,s.jsx)(A,{size:"sm",className:"font-semibold bg-green-600 hover:bg-green-700",variant:"default",onClick:t,disabled:n,children:n?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(c.A,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save ".concat(l," ").concat(1===l?"change":"changes")})]})}),eB=e=>{let{selectedCount:t=0,onAdd:a,onDelete:l,onRefresh:n,totalRows:r=0,currentPage:i=1,totalPages:o=1,onPageChange:c,rowsPerPage:d=50,onRowsPerPageChange:u,tableName:m,onDownloadStart:h,onDownloadComplete:x,disabled:f=!1,editCount:p=0,newRecordsCount:g=0,onSaveChanges:v,onDiscardChanges:N,isSaving:j=!1,schema:b,visibleColumns:w,onColumnToggle:y}=e,C=p+g;return(0,s.jsx)("div",{className:"flex items-center justify-between p-3 border-b bg-background font-sans",children:(0,s.jsxs)("div",{className:"flex items-center justify-between w-full",children:[(0,s.jsx)(eq,{onAdd:a,onDelete:l,selectedCount:t,disabled:f||j,newRecordsCount:g,schema:b,visibleColumns:w,onColumnToggle:y}),(0,s.jsx)("div",{className:"flex items-center gap-4",children:C>0?(0,s.jsx)(eW,{onSave:v,onDiscard:N,totalChanges:C,isSaving:j}):(0,s.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,s.jsx)(eY,{totalRows:r}),(0,s.jsx)(eX,{currentPage:i,totalPages:o,onPageChange:c,disabled:f,newRecordsCount:g}),(0,s.jsx)(eH,{value:d,onValueChange:e=>{u(parseInt(e,10)),c(1)},disabled:f,newRecordsCount:g}),(0,s.jsx)(eU,{onRefresh:n,disabled:f}),(0,s.jsx)(eD,{tableName:m,onSync:n,disabled:f}),(0,s.jsx)(eV,{tableName:m,onDownloadStart:h,onDownloadComplete:x,disabled:f})]})})]})})};eB.displayName="TableToolbar";let eG=(0,l.memo)(eB);function eZ(e){let{value:t,row:a,column:n,schema:r,onChange:i,onStartEdit:o,isEditing:c}=e,d="string"==typeof t?t.replace(/^'|'$/g,""):t,[m,h]=(0,l.useState)(d),[x,f]=(0,l.useState)("auto"),p=(0,l.useRef)(null),g=(0,l.useRef)(null),v=r.find(e=>e.name===n),N=(0,l.useMemo)(()=>(null==v?void 0:v.check)||null,[v]),j=(0,l.useMemo)(()=>{var e;let t=(null==v?void 0:null===(e=v.type)||void 0===e?void 0:e.toLowerCase())||"";return"boolean"===t||"bool"===t||"integer"===t&&n.toLowerCase().startsWith("is_")},[v,n]);(0,l.useEffect)(()=>{h(d)},[d]),(0,l.useEffect)(()=>{if(p.current&&!c){let e=p.current.offsetWidth;f("".concat(e,"px"))}},[c]),(0,l.useEffect)(()=>{c&&g.current&&(g.current.focus(),g.current.select())},[c]),null==v||v.pk;let b=(0,l.useCallback)(e=>{let t=j?"true"===e?1:"false"===e?0:e:e;h(e),null==i||i(t)},[i,j]),w=(0,l.useCallback)(()=>{!c&&o&&o(d)},[c,o,d]),y="border-x border-neutral-200 px-3 py-2.5 text-xs font-mono whitespace-nowrap",C=(0,l.useMemo)(()=>null==d?"null":j?1===d||"1"===d||"true"===d?"true":"false":d.toString(),[d,j]);return c?j?(0,s.jsx)(z,{className:"".concat(y," p-0"),style:{width:x},children:(0,s.jsx)("div",{className:"w-full h-full",children:(0,s.jsxs)(X,{value:C,onValueChange:b,defaultOpen:c,children:[(0,s.jsx)(W,{className:"w-full h-9 min-w-0 rounded-none border-0 bg-orange-50 text-orange-900",children:(0,s.jsx)(H,{placeholder:"Select value"})}),(0,s.jsxs)(Z,{className:"min-w-[8rem]",children:[(0,s.jsx)($,{value:"true",children:"true"}),(0,s.jsx)($,{value:"false",children:"false"})]})]})})}):(null==N?void 0:N.length)>0?(0,s.jsx)(z,{className:"".concat(y," p-0"),style:{width:x},children:(0,s.jsx)("div",{className:"w-full h-full",children:(0,s.jsxs)(X,{value:null!=m?m:N[0],onValueChange:b,defaultOpen:c,children:[(0,s.jsx)(W,{className:"w-full h-9 min-w-0 rounded-none border-0 bg-orange-50 text-orange-900",children:(0,s.jsx)(H,{placeholder:"Select ".concat(n)})}),(0,s.jsx)(Z,{className:"min-w-[8rem]",children:N.map(e=>(0,s.jsx)($,{value:e,children:e},e))})]})})}):(0,s.jsx)(z,{className:"".concat(y," p-0"),style:{width:x},children:(0,s.jsx)(u,{ref:g,value:null!=m?m:"",onChange:e=>b(e.target.value),className:"w-full min-w-0 rounded-none border-0 bg-orange-50 text-orange-900"})}):(0,s.jsx)(z,{ref:p,className:"".concat(y," cursor-pointer hover:bg-muted/50"),onClick:w,children:C})}var e$=a(5524);function e0(e){return"string"==typeof e?e.replace(/^'|'$/g,""):e}function e1(e){let{schema:t,onRemove:a,onChange:n,showCheckbox:r=!1,initialData:i={}}=e,[o,c]=(0,l.useState)(()=>t.reduce((e,t)=>{var a;let s=null!==(a=i[t.name])&&void 0!==a?a:null;return null===(s=e0(s))&&(t.dflt_value?s=e0(t.dflt_value):"INTEGER"===t.type.toUpperCase()?s="":"TEXT"===t.type.toUpperCase()&&(s="")),e[t.name]=s,e},{})),d=(e,t)=>{let a={...o,[e]:t};c(a),null==n||n(a)},m=e=>{var t;let a=(null===(t=e.type)||void 0===t?void 0:t.toLowerCase())||"";return"boolean"===a||"bool"===a||"integer"===a&&e.name.toLowerCase().startsWith("is_")};return(0,s.jsxs)(D,{className:"bg-orange-50/50",children:[(0,s.jsx)(z,{className:"w-10 p-0",children:(0,s.jsx)("div",{className:"pl-1 flex items-center",children:r?(0,s.jsx)(eE,{disabled:!0}):(0,s.jsx)(A,{variant:"ghost",size:"icon",className:"h-8 w-8 text-orange-700 hover:text-orange-800",onClick:a,children:(0,s.jsx)(e$.A,{className:"h-4 w-4"})})})}),t.map(e=>{var t,a;let l=1===e.pk,n=e.check||null;if(m(e)){let t="false";if(null!==e.dflt_value&&void 0!==e.dflt_value){let a=e.dflt_value.toString().toLowerCase();t="1"===a||"true"===a||"'true'"===a||'"true"'===a?"true":"false"}let a=null!==o[e.name]&&void 0!==o[e.name]?1===o[e.name]||!0===o[e.name]||"true"===o[e.name]?"true":"false":t;return(0,s.jsx)(z,{className:"border-x border-neutral-200 p-0",children:(0,s.jsx)("div",{className:"w-full",children:(0,s.jsxs)(X,{value:a,onValueChange:t=>d(e.name,"true"===t?1:0),children:[(0,s.jsx)(W,{className:"w-full h-9 min-w-0 rounded-none border-0 bg-orange-50 text-orange-900",title:"Default: ".concat(t),children:(0,s.jsx)(H,{placeholder:"Select ".concat(e.name)})}),(0,s.jsxs)(Z,{className:"min-w-[8rem]",children:[(0,s.jsx)($,{value:"true",children:"true"}),(0,s.jsx)($,{value:"false",children:"false"})]})]})})},e.name)}return(null==n?void 0:n.length)>0?(0,s.jsx)(z,{className:"border-x border-neutral-200 p-0",children:(0,s.jsx)("div",{className:"w-full",children:(0,s.jsxs)(X,{value:null!==(t=o[e.name])&&void 0!==t?t:n[0],onValueChange:t=>d(e.name,t),children:[(0,s.jsx)(W,{className:"w-full h-9 min-w-0 rounded-none border-0 bg-orange-50 text-orange-900",children:(0,s.jsx)(H,{placeholder:"Select ".concat(e.name)})}),(0,s.jsx)(Z,{className:"min-w-[8rem]",children:n.map(e=>(0,s.jsx)($,{value:e,children:e},e))})]})})},e.name):(0,s.jsx)(z,{className:"border-x border-neutral-200 p-0",children:(0,s.jsx)(u,{value:null!==(a=o[e.name])&&void 0!==a?a:"",onChange:t=>d(e.name,t.target.value),className:"w-full min-w-0 rounded-none border-0 px-2 bg-orange-50 text-orange-900",placeholder:l?"Auto-generated":"Enter ".concat(e.name)})},e.name)})]})}let e4=function(e){let{isOpen:t,onClose:a,onConfirm:l,selectedCount:n,tableName:i,isDeleting:o,error:c}=e;return(0,s.jsx)(N,{open:t,onOpenChange:a,children:(0,s.jsxs)(w,{className:"sm:max-w-md font-sans",children:[(0,s.jsxs)(y,{children:[(0,s.jsxs)(S,{className:"mb-2",children:["Delete ",n," ",1===n?"Record":"Records","?"]}),(0,s.jsxs)(E,{className:"text-neutral-600 font-medium",children:["You're about to delete ",n," ",1===n?"record":"records"," from ",(0,s.jsx)("span",{className:"font-sans font-bold text-neutral-900",children:i}),"."]})]}),c&&(0,s.jsxs)(x,{variant:"destructive",children:[(0,s.jsx)(r.A,{className:"h-4 w-4"}),(0,s.jsx)(f,{children:c})]}),(0,s.jsxs)(C,{className:"flex gap-1 mt-2 sm:justify-end font-sans",children:[(0,s.jsx)(A,{variant:"outline",onClick:a,disabled:o,children:"Cancel"}),(0,s.jsx)(A,{variant:"destructive",onClick:l,disabled:o,children:o?"Deleting...":"Delete"})]})]})})};function e2(e){var t;let{isOpen:a,onClose:l,error:n}=e;if(!n||!a)return null;let{message:i,icon:o}=n?{message:n.message,icon:r.A}:{message:"An unknown error occurred.",icon:r.A};return(0,s.jsx)(N,{open:a,onOpenChange:l,children:(0,s.jsxs)(w,{className:"sm:max-w-md font-sans",children:[(0,s.jsx)(y,{children:(0,s.jsxs)("div",{className:"flex items-center gap-2",children:[(0,s.jsx)(o,{className:"h-4 w-4 text-red-500"}),(0,s.jsx)(S,{children:"Error"})]})}),(0,s.jsxs)("div",{className:"space-y-4",children:[(0,s.jsx)("p",{className:"bg-neutral-100 p-2 rounded-md text-neutral-900",children:i}),(null===(t=n.details)||void 0===t?void 0:t.suggestions)&&(0,s.jsxs)("div",{className:"text-sm space-y-1",children:[(0,s.jsx)("p",{className:"font-medium",children:"Suggestions:"}),(0,s.jsx)("ul",{className:"list-disc pl-4 space-y-1",children:n.details.suggestions.map((e,t)=>(0,s.jsx)("li",{children:e},t))})]})]}),(0,s.jsx)("div",{className:"flex justify-end gap-2 mt-4",children:(0,s.jsx)(A,{variant:"default",onClick:l,children:"Got it"})})]})})}let e5=e=>{let{children:t,width:a,onResize:n,className:r=""}=e,[i,o]=(0,l.useState)(!1),c=(0,l.useRef)(null),d=(0,l.useCallback)(e=>{var t;e.preventDefault(),o(!0);let a=e.clientX,s=(null===(t=c.current)||void 0===t?void 0:t.offsetWidth)||0,l=e=>{c.current&&n(Math.max(s+(e.clientX-a),100))},r=()=>{o(!1),document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",r)};document.addEventListener("mousemove",l),document.addEventListener("mouseup",r)},[n]);return(0,s.jsxs)("th",{ref:c,className:"relative ".concat(r," ").concat(i?"select-none":""),style:{width:"".concat(a,"px")},children:[t,(0,s.jsx)("div",{className:"absolute top-0 right-0 h-full w-1 cursor-col-resize group hover:bg-neutral-300",onMouseDown:d})]})},e3=e=>{let{columns:t,children:a,onColumnsResize:n,className:r=""}=e,[i,o]=(0,l.useState)(t.reduce((e,t)=>({...e,[t.key]:t.width||150}),{})),c=(0,l.useCallback)((e,t)=>{o(a=>{let s={...a,[e]:t};return null==n||n(s),s})},[n]);return(0,s.jsx)("div",{className:"w-full ".concat(r),children:l.Children.map(a,e=>l.isValidElement(e)?l.cloneElement(e,{onResize:c}):e)})};var e9=a(3998),e8=a(3303),e7=a(8729);function e6(e){let{column:t,sortConfig:a,onSort:l,children:n}=e,r=a[t];return(0,s.jsx)("div",{className:"flex items-center w-full",children:(0,s.jsxs)(A,{variant:"ghost",size:"sm",className:"h-8 hover:bg-neutral-100 w-full justify-between",onClick:()=>{l(t,r?"asc"===r?"desc":null:"asc")},children:[(0,s.jsx)("span",{className:"flex items-center gap-1 font-mono",children:n}),(0,s.jsxs)("span",{className:"shrink-0",children:["asc"===r&&(0,s.jsx)(e9.A,{className:"h-4 w-4"}),"desc"===r&&(0,s.jsx)(e8.A,{className:"h-4 w-4"}),!r&&(0,s.jsx)(e7.A,{className:"h-4 w-4"})]})]})})}function te(e){let{tableName:t}=e,{executeQuery:a,getCachedTable:n,updateTableCache:i,invalidateTable:o,switchTable:d,activeTable:u,updateTableData:m}=(0,p.t)(),{toast:h}=(0,_.dj)(),[g,v]=(0,l.useState)(()=>[]),[N,j]=(0,l.useState)([]),[b,w]=(0,l.useState)(0),[y,C]=(0,l.useState)(!0),[S,E]=(0,l.useState)(!1),[R,T]=(0,l.useState)(null),[A,k]=(0,l.useState)(new Map),[O,Q]=(0,l.useState)(new Set),[V,K]=(0,l.useState)([]),[J,q]=(0,l.useState)(1),[Y,X]=(0,l.useState)(50),[H,W]=(0,l.useState)(1),[B,G]=(0,l.useState)(new Set),Z=(0,l.useRef)(null),[$,ee]=(0,l.useState)(!1),[et,ea]=(0,l.useState)(!1),[es,el]=(0,l.useState)(null),[en,er]=(0,l.useState)(!1),[ei,eo]=(0,l.useState)(null),[ec,ed]=(0,l.useState)({}),[eu,em]=(0,l.useState)({}),[eh,ex]=(0,l.useState)([]);(0,l.useEffect)(()=>{if(t){let e=localStorage.getItem("table-widths-".concat(t));e&&em(JSON.parse(e));let a=localStorage.getItem("table-columns-".concat(t));if(a)try{ex(JSON.parse(a))}catch(e){ex([])}}},[t]);let ef=(0,l.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!t)return;let a=n(t,J,Y);if(a&&!e){v(a.data),j(a.schema),w(a.meta.total),W(a.meta.totalPages);return}C(!0),T(null),G(new Set);try{let a=await d(t,{page:J,limit:Y,forceFetch:e});return a.meta.page=J,v(Array.isArray(a.data)?a.data:[]),j(a.schema||[]),w(a.meta.total),W(a.meta.totalPages),!0}catch(e){throw console.error("Error loading table data:",e),T(e.message||String(e)),h({variant:"destructive",title:"Error",description:"Failed to load table: ".concat(e.message)}),e}finally{C(!1)}},[t,J,Y,n,d,h,eh.length]),ep=(0,l.useCallback)(e=>{ex(a=>{let s=a.includes(e)?a.filter(t=>t!==e):[...a,e];return localStorage.setItem("table-columns-".concat(t),JSON.stringify(s)),s})},[t]),eg=(0,l.useCallback)((e,a)=>{em(s=>{let l={...s,[e]:a};return localStorage.setItem("table-widths-".concat(t),JSON.stringify(l)),l})},[t]),ev=(0,l.useCallback)(async()=>{try{G(new Set),o(t),await ef(!0),h({title:"Success",description:"Table data refreshed"})}catch(e){console.error("Refresh failed:",e),h({variant:"destructive",title:"Refresh Failed",description:e.message})}},[ef,o,t,h]),eN=(0,l.useCallback)((e,a)=>{ed(t=>({...t,[e]:a}));let s=a&&g.length?[...g].sort((t,s)=>{let l=t[e],n=s[e];if(null==l&&null==n)return 0;if(null==l)return 1;if(null==n)return -1;if("number"==typeof l&&"number"==typeof n)return"asc"===a?l-n:n-l;let r=String(l).toLowerCase(),i=String(n).toLowerCase();return"asc"===a?r.localeCompare(i):i.localeCompare(r)}):g;v(s);let l=n(t);l&&i(t,s,l.schema,{...l.meta,currentPage:J,limit:Y},J,Y)},[g,t,n,i]),eb=(0,l.useCallback)((e,t,a)=>{let s="".concat(e,"-").concat(t);k(e=>new Map(e).set(s,{value:a,originalValue:a})),Q(t=>new Set(t).add(e))},[]),ew=(0,l.useCallback)((e,t,a)=>{var s,l;let n="".concat(e,"-").concat(t),r=g[e],i=null!==(l=null===(s=A.get(n))||void 0===s?void 0:s.originalValue)&&void 0!==l?l:r[t];if(a===i){let t=new Map(A);if(t.delete(n),k(t),!Array.from(t.keys()).some(t=>t.startsWith("".concat(e,"-")))){let t=new Set(O);t.delete(e),Q(t)}}else k(e=>new Map(e).set(n,{value:a,originalValue:i})),Q(t=>new Set(t).add(e))},[g,A,O]),ey=(0,l.useCallback)(()=>{K(e=>[...e,{}])},[]),eC=(0,l.useCallback)(e=>{K(t=>t.filter((t,a)=>a!==e))},[]),eS=(0,l.useCallback)((e,t)=>{K(a=>{let s=[...a];return s[e]=t,s})},[]),eR=async function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];E(!0);try{if(V.length>0){let e=0,s=N.filter(e=>"datetime"===e.type.toLowerCase()).map(e=>e.name);for(let l of V){let n=Object.keys(l).filter(e=>null!==l[e]&&""!==l[e]&&"null"!==l[e]);if(s.forEach(e=>{n.includes(e)||n.push(e)}),0===n.length)continue;let r=n.map(e=>{if(s.includes(e))return"CURRENT_TIMESTAMP";let t=l[e];return null===t||""===t||"null"===t?"NULL":"'".concat(t.toString().replace(/'/g,"''"),"'")}),i="INSERT INTO ".concat(t," (").concat(n.join(", "),") VALUES (").concat(r.join(", "),");");await a(i),e++}if(e>0){let a=await m(t);v(a.data),w(a.meta.total),W(Math.ceil(a.meta.total/Y)),h({title:"Success",description:"Added ".concat(e," ").concat(1===e?"record":"records")})}K([])}if(A.size>0&&(e||!ei)){var s;let e=null===(s=N.find(e=>1===e.pk))||void 0===s?void 0:s.name;if(!e)throw Error("No primary key found in table schema");let l=new Map;A.forEach((t,a)=>{let[s,n]=a.split("-"),r=g[s];l.has(r[e])||l.set(r[e],new Map),l.get(r[e]).set(n,t.value)});let n=0;for(let[s,r]of l){let l=Array.from(r.entries()).map(e=>{let[t,a]=e;return null===a||""===a||"null"===a?"".concat(t," = NULL"):"CURRENT_TIMESTAMP"===a?"".concat(t," = CURRENT_TIMESTAMP"):"".concat(t," = '").concat(a.toString().replace(/'/g,"''"),"'")}).join(", "),i="\n UPDATE ".concat(t,"\n SET ").concat(l,"\n WHERE ").concat(e," = ").concat(s,";\n ");await a(i),n++}if(n>0){let e=await m(t);v(e.data),w(e.meta.total),W(Math.ceil(e.meta.total/Y)),h({title:"Success",description:"Updated ".concat(n," ").concat(1===n?"record":"records")})}}k(new Map),Q(new Set),eo(null)}catch(e){eo({...ej(e),stderr:e.stderr,stdout:e.stdout}),er(!0)}finally{E(!1)}},eT=(0,l.useCallback)(async()=>{if(ea(!0),el(null),t){ea(!0),el(null);try{var e;let s=null===(e=N.find(e=>1===e.pk))||void 0===e?void 0:e.name;if(!s)throw Error("No primary key found in table schema");let l=Array.from(B).map(e=>g[e][s]);if(0===l.length)return;let r="DELETE FROM ".concat(t," WHERE ").concat(s," IN (").concat(l.join(","),");");await a(r);let o=new Set(l),c=g.filter(e=>!o.has(e[s]));v(c),w(e=>e-l.length),W(Math.ceil((b-l.length)/Y));let d=n(t);d&&i(t,c,d.schema,{...d.meta,total:d.meta.total-l.length}),J>1&&g.length===l.length&&(q(e=>e-1),await ef()),ee(!1),G(new Set),h({title:"Success",description:"Successfully deleted ".concat(l.length," ").concat(1===l.length?"record":"records")})}catch(e){console.error("Delete operation failed:",e),el(e.message||String(e))}finally{ea(!1)}}},[t,B,g,N,a,m,ef,J,Y,b,h,n,i]);(0,l.useEffect)(()=>{if(!t)return;k(new Map),Q(new Set),K([]),T(null),G(new Set),q(1);let e=n(t,1,Y);e?(v(e.data),j(e.schema),w(e.meta.total),W(e.meta.totalPages),ex(a=>{if(a.length)return a;let s=e.schema.map(e=>e.name);return localStorage.setItem("table-columns-".concat(t),JSON.stringify(s)),s})):ef(!1)},[t,Y]),(0,l.useEffect)(()=>{if(u===t){let e=n(t);e&&(v(e.data),j(e.schema),w(e.meta.total),W(e.meta.totalPages))}},[u,t,n]),(0,l.useEffect)(()=>{if(t&&!y){var e;let a=n(t,J,Y);a&&J===(null===(e=a.meta)||void 0===e?void 0:e.currentPage)||ef(!1)}},[t,J,Y,y,ef,n]),(0,l.useEffect)(()=>{Z.current&&(Z.current.indeterminate=B.size>0&&B.size<g.length)},[B.size,g.length]);let eA=(0,l.useCallback)(e=>{G(e?new Set(g.map((e,t)=>t)):new Set)},[g]),ek=(0,l.useCallback)((e,t)=>{G(a=>{let s=new Set(a);return t?s.add(e):s.delete(e),s})},[]);(0,l.useCallback)(e=>{em(e),localStorage.setItem("table-widths-".concat(t),JSON.stringify(e))},[t]);let e_=N.filter(e=>eh.includes(e.name)),eO=A.size>0||V.length>0;return R?(0,s.jsx)("div",{className:"p-4",children:(0,s.jsxs)(x,{variant:"destructive",children:[(0,s.jsx)(r.A,{className:"h-4 w-4"}),(0,s.jsxs)(f,{children:["Failed to load table: ",R]})]})}):(0,s.jsxs)("div",{className:"h-full flex flex-col",children:[(0,s.jsx)(eG,{selectedCount:B.size,totalRows:b,currentPage:J,totalPages:H,rowsPerPage:Y,onPageChange:q,onRowsPerPageChange:X,onAdd:ey,onDelete:()=>ee(!0),onRefresh:ev,tableName:t,disabled:eO,editCount:A.size,newRecordsCount:V.length,isSaving:S,onSaveChanges:eR,onDiscardChanges:()=>{k(new Map),Q(new Set),K([]),eo(null),h({description:"Changes discarded"})},schema:N,visibleColumns:eh,onColumnToggle:ep}),(0,s.jsx)(e3,{columns:N,onColumnsResize:eg,children:(0,s.jsx)("div",{className:"flex-1 overflow-hidden bg-background font-mono",children:(0,s.jsx)(L,{className:"w-full h-screen",children:(0,s.jsxs)("div",{className:"relative w-max min-w-fit pb-4",children:[(0,s.jsxs)(P,{children:[!y&&(0,s.jsx)(U,{className:"bg-neutral-100 sticky top-0 z-30",children:(0,s.jsxs)(D,{children:[(0,s.jsx)(M,{className:"w-10 p-0 border-r border-neutral-200",children:(0,s.jsx)("div",{className:"py-0.5 px-3 flex items-center",children:(0,s.jsx)(eE,{ref:Z,checked:B.size===g.length&&g.length>0,onCheckedChange:eA,disabled:eO})})}),e_.map(e=>{var t;return(0,s.jsx)(e5,{width:eu[e.name]||150,onResize:t=>eg(e.name,t),className:"py-0.5 whitespace-nowrap border-r border-neutral-200",children:(0,s.jsxs)(e6,{column:e.name,sortConfig:ec,onSort:eN,children:[(0,s.jsx)("span",{className:"text-xs font-bold text-foreground",children:e.name}),(0,s.jsx)("span",{className:"text-xs text-muted-foreground",children:null===(t=e.type)||void 0===t?void 0:t.toLowerCase()})]})},e.name)})]})}),(0,s.jsxs)(F,{children:[y&&(0,s.jsx)(D,{className:"hover:bg-transparent",children:(0,s.jsx)(z,{colSpan:e_.length+1,className:"h-[calc(100vh-200px)]",children:(0,s.jsx)("div",{className:"h-full w-full flex items-center justify-center",children:(0,s.jsx)(c.A,{className:"h-6 w-6 animate-spin text-primary"})})})}),!y&&(0,s.jsxs)(s.Fragment,{children:[V.map((e,t)=>(0,s.jsx)(e1,{schema:e_,onRemove:()=>eC(t),onChange:e=>eS(t,e)},"new-".concat(t))),0===g.length&&0===V.length?(0,s.jsx)(D,{className:"hover:bg-transparent",children:(0,s.jsx)(z,{colSpan:e_.length+1,className:"h-[calc(100vh-200px)] text-center text-muted-foreground",children:"Table is empty"})}):g.map((e,t)=>(0,s.jsxs)(D,{className:"".concat(B.has(t)?"bg-muted/50":""),children:[(0,s.jsx)(z,{className:"p-0",children:(0,s.jsx)("div",{className:"px-3 py-2.5 flex items-center",children:(0,s.jsx)(eE,{checked:B.has(t),onCheckedChange:e=>ek(t,e),disabled:eO})})}),e_.map(a=>{let l="".concat(t,"-").concat(a.name),n=A.get(l);return(0,s.jsx)(eZ,{value:n?n.value:e[a.name],row:e,column:a.name,schema:N,onChange:e=>ew(t,a.name,e),onStartEdit:e=>eb(t,a.name,e),isEditing:A.has(l),style:{width:"".concat(eu[a.name]||150,"px")}},a.name)})]},t))]})]})]}),(0,s.jsx)(I,{orientation:"horizontal"})]})})})}),(0,s.jsx)(e4,{isOpen:$,onClose:()=>{ee(!1),el(null)},onConfirm:eT,selectedCount:B.size,tableName:t,isDeleting:et,error:es}),(0,s.jsx)(e2,{isOpen:en,onClose:()=>er(!1),error:ei,onOpenInSQL:()=>{er(!1)},onUpdateAnyway:async()=>{er(!1),await eR(!0)},showSQLOption:(null==ei?void 0:ei.type)==="NULLABLE_PK"})]})}function tt(){let[e,t]=(0,l.useState)("sql-editor"),[a,n]=(0,l.useState)(null);return(0,s.jsxs)("div",{className:"flex h-screen bg-background",children:[(0,s.jsx)(el,{className:"w-64 border-r flex-shrink-0",currentView:e,onNavigate:t,onTableSelect:e=>{n(e),t("table-view")}}),(0,s.jsxs)("main",{className:"flex-1 overflow-hidden",children:["sql-editor"===e&&(0,s.jsx)(eC,{}),"table-view"===e&&a&&(0,s.jsx)(te,{tableName:a})]})]})}}},e=>{var t=t=>e(e.s=t);e.O(0,[692,576,735,441,517,358],()=>t(3320)),_N_E=e.O()}]);
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
exports.id=90,exports.ids=[90],exports.modules={1241:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,3219,23)),Promise.resolve().then(r.t.bind(r,4863,23)),Promise.resolve().then(r.t.bind(r,5155,23)),Promise.resolve().then(r.t.bind(r,802,23)),Promise.resolve().then(r.t.bind(r,9350,23)),Promise.resolve().then(r.t.bind(r,8530,23)),Promise.resolve().then(r.t.bind(r,8921,23))},4041:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,6959,23)),Promise.resolve().then(r.t.bind(r,3875,23)),Promise.resolve().then(r.t.bind(r,8903,23)),Promise.resolve().then(r.t.bind(r,7174,23)),Promise.resolve().then(r.t.bind(r,4178,23)),Promise.resolve().then(r.t.bind(r,7190,23)),Promise.resolve().then(r.t.bind(r,1365,23))},4400:(e,t,r)=>{Promise.resolve().then(r.bind(r,3164)),Promise.resolve().then(r.bind(r,1831))},7952:(e,t,r)=>{Promise.resolve().then(r.bind(r,2652)),Promise.resolve().then(r.bind(r,2899))},2652:(e,t,r)=>{"use strict";r.d(t,{Toaster:()=>v});var a=r(5512),s=r(6888),o=r(8009),i=r(8952),n=r(1643),c=r(1255),l=r(3603);let d=i.Kq,u=o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.LM,{ref:r,className:(0,l.cn)("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),...t}));u.displayName=i.LM.displayName;let h=(0,n.F)("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),p=o.forwardRef(({className:e,variant:t,...r},s)=>(0,a.jsx)(i.bL,{ref:s,className:(0,l.cn)(h({variant:t}),e),...r}));p.displayName=i.bL.displayName,o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.rc,{ref:r,className:(0,l.cn)("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),...t})).displayName=i.rc.displayName;let m=o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.bm,{ref:r,className:(0,l.cn)("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",...t,children:(0,a.jsx)(c.A,{className:"h-4 w-4"})}));m.displayName=i.bm.displayName;let f=o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.hE,{ref:r,className:(0,l.cn)("text-sm font-semibold [&+div]:text-xs",e),...t}));f.displayName=i.hE.displayName;let b=o.forwardRef(({className:e,...t},r)=>(0,a.jsx)(i.VY,{ref:r,className:(0,l.cn)("text-sm opacity-90",e),...t}));function v(){let{toasts:e}=(0,s.dj)();return(0,a.jsxs)(d,{children:[e.map(function({id:e,title:t,description:r,action:s,...o}){return(0,a.jsxs)(p,{...o,children:[(0,a.jsxs)("div",{className:"grid gap-1",children:[t&&(0,a.jsx)(f,{children:t}),r&&(0,a.jsx)(b,{children:r})]}),s,(0,a.jsx)(m,{})]},e)}),(0,a.jsx)(u,{})]})}b.displayName=i.VY.displayName},8180:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>u,metadata:()=>d});var a=r(2740),s=r(7944),o=r.n(s),i=r(5510),n=r.n(i);r(1135);var c=r(1831),l=r(3164);let d={title:"d1-studio",description:"Native D1 database studio."};function u({children:e}){return(0,a.jsx)("html",{lang:"en",children:(0,a.jsx)("body",{className:`${o().variable} ${n().variable} antialiased`,children:(0,a.jsxs)(c.DatabaseProvider,{children:[e,(0,a.jsx)(l.Toaster,{})," "]})})})}},3164:(e,t,r)=>{"use strict";r.d(t,{Toaster:()=>a});let a=(0,r(4379).registerClientReference)(function(){throw Error("Attempted to call Toaster() from the server but Toaster is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/kona/Desktop/d1studio/src/components/ui/toaster.jsx","Toaster")},1135:()=>{},2899:(e,t,r)=>{"use strict";r.d(t,{DatabaseProvider:()=>u,t:()=>h});var a=r(5512),s=r(8009),o=r(6888);let i=new Map;function n(e,t,r=2e3){let a=i.get(e);if(a&&Date.now()-a.timestamp<r)return a.promise;let s=t();return i.set(e,{promise:s,timestamp:Date.now()}),s.finally(()=>{setTimeout(()=>{i.delete(e)},r)}),s}let c=(0,s.createContext)(void 0);class l{constructor(){this.cache=new Map}get(e){return this.cache.get(e)||null}set(e,t,r,a){this.cache.set(e,{data:t,schema:r,meta:a,timestamp:Date.now()})}update(e,t,r,a){let s=this.cache.get(e);s&&this.cache.set(e,{data:t||s.data,schema:r||s.schema,meta:a||s.meta,timestamp:Date.now()})}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}}class d{constructor(){this.queue=[],this.processing=!1}async add(e){return new Promise((t,r)=>{this.queue.push({operation:e,resolve:t,reject:r}),this.process()})}async process(){if(this.processing||0===this.queue.length)return;this.processing=!0;let{operation:e,resolve:t,reject:r}=this.queue.shift();try{let r=await e();t(r)}catch(e){r(e)}finally{this.processing=!1,this.process()}}}function u({children:e}){let{toast:t}=(0,o.dj)(),[r,i]=(0,s.useState)([]),[u,h]=(0,s.useState)(!0),[p,m]=(0,s.useState)(null),[f,b]=(0,s.useState)(null);(0,s.useRef)(new d);let[v,y]=(0,s.useState)(null),g=(0,s.useRef)(new l).current,w=(0,s.useCallback)((e,t=1,r=50)=>{let a=`table-${e}-${t}-${r}`;return g.get(a)},[]),x=(0,s.useCallback)(e=>{g.cache.forEach((t,r)=>{r.startsWith(`table-${e}-`)&&g.invalidate(r)})},[]),T=(0,s.useCallback)((e,t,r,a,s=1,o=50)=>{let i=`table-${e}-${s}-${o}`;g.update(i,t,r,a)},[]),S=(0,s.useCallback)(async e=>n(`query-${e}`,async()=>{try{let t=await fetch("/api/query",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e})});if(!t.ok){let e="Failed to execute query";try{let r=await t.json();e=r?.error?.message||e}catch(e){}throw Error(e)}let r=await t.json();if(!r.success)throw Error(r.error||"Query execution failed");return r}catch(e){throw e||Error("An unknown error occurred")}},1e3),[]),j=(0,s.useCallback)(async e=>{try{let t=await fetch(`/api/tables/${e}`),r=await t.json();if(!t.ok||!r.success)throw Error(r.error||"Failed to fetch table schema");return r.schema||[]}catch(e){throw console.error("Schema fetch error:",e),t({variant:"destructive",title:"Schema Fetch Failed",description:e.message}),e}},[t]),E=(0,s.useCallback)(async(e,r={})=>{let{forceFetch:a=!1,page:s=1,limit:o=50}=r,i=`table-${e}-${s}-${o}`;if(!a){let e=g.get(i);if(e)return e}return n(`table-${e}-${s}-${o}`,async()=>{try{let t=await fetch(`/api/tables/${e}?page=${s}&limit=${o}`,{headers:{"Cache-Control":"no-cache",Pragma:"no-cache"}});if(!t.ok)throw Error("Failed to fetch table data");let r=await t.json();if(!r.success)throw Error(r.error||"Failed to fetch table data");return g.set(i,r.data,r.schema,r.meta),r}catch(e){throw console.error("Error fetching table data:",e),t({variant:"destructive",title:"Data Fetch Failed",description:e.message}),e}},1e3)},[t]),C=(0,s.useCallback)(async e=>{try{return g.invalidate(e),await E(e,{forceFetch:!0})}catch(e){throw console.error("Error updating table data:",e),t({variant:"destructive",title:"Update Failed",description:e.message}),e}},[E,t]),P=(0,s.useCallback)(async(e,t={})=>(y(e),await E(e,t)),[E]),k=(0,s.useCallback)(async()=>n("refresh-tables",async()=>{h(!0),m(null);try{let e=await fetch("/api/tables");if(!e.ok)throw Error("Failed to fetch tables");let t=await e.json();if(t.error)throw Error(t.error);return i(t.tables||[]),t.tables||[]}catch(e){throw m(e.message),t({variant:"destructive",title:"Refresh Failed",description:e.message}),e}finally{h(!1)}},2e3),[t]),D=(0,s.useCallback)(async e=>{try{await S(e),g.clear(),await k(),t({title:"Success",description:"Table created successfully"})}catch(e){throw t({variant:"destructive",title:"Create Table Failed",description:e.message}),Error(`Failed to create table: ${e.message}`)}},[S,k,t]),N=(0,s.useCallback)(async e=>{try{await S(`DROP TABLE ${e};`),g.invalidate(e),await k(),t({title:"Success",description:"Table dropped successfully"})}catch(e){throw t({variant:"destructive",title:"Drop Table Failed",description:e.message}),Error(`Failed to drop table: ${e.message}`)}},[S,k,t]),$=(0,s.useCallback)(async e=>{try{let r=await fetch("/api/migrations/sync",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let e=await r.json();throw Error(e.error?.message||"Failed to sync migrations")}let a=await r.json();return t({title:"Success",description:"Migrations synced successfully"}),a}catch(e){throw console.error("Error syncing migrations:",e),t({variant:"destructive",title:"Sync Failed",description:e.message}),e}},[t]),F=(0,s.useCallback)(async()=>{try{let e=localStorage.getItem("cf_credentials");if(!e)throw Error("No Cloudflare credentials found. Please connect to Cloudflare first.");let t=JSON.parse(e);if(!t.accountId||!t.apiToken)throw Error("Invalid credentials stored. Please reconnect to Cloudflare.");let r=await fetch("/api/pull-remote/confirm",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:t.accountId,apiToken:t.apiToken})}),a=await r.json();if(!r.ok||!a.success)throw Error(a.error?.message||"Failed to pull from remote");return g.clear(),await k(),a}catch(e){throw console.error("Error pulling from remote:",e),t({variant:"destructive",title:"Pull Failed",description:e.message}),e}},[k,t]),O=(0,s.useCallback)(async e=>{try{let t=await fetch("/api/push-remote",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json();if(!t.ok)throw Error(r.error?.message||"Failed to push to remote");return r}catch(e){throw console.error("Error pushing to remote:",e),e}},[t]),A=(0,s.useMemo)(()=>({tables:r,currentDatabase:f,isLoading:u,error:p,activeTable:v,refreshTables:k,executeQuery:S,fetchTableSchema:j,fetchTableData:E,updateTableData:C,createTable:D,dropTable:N,syncMigrations:$,pullFromRemote:F,pushToRemote:O,getCachedTable:w,updateTableCache:T,invalidateTable:x,switchTable:P}),[r,f,u,p,v,k,S,j,E,C,D,N,$,F,O,w,T,x,P]);return(0,a.jsx)(c.Provider,{value:A,children:e})}function h(){let e=(0,s.useContext)(c);if(!e)throw Error("useDatabase must be used within a DatabaseProvider");return e}},6888:(e,t,r)=>{"use strict";r.d(t,{dj:()=>h});var a=r(8009);let s=0,o=new Map,i=e=>{if(o.has(e))return;let t=setTimeout(()=>{o.delete(e),d({type:"REMOVE_TOAST",toastId:e})},1e6);o.set(e,t)},n=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,1)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(e=>e.id===t.toast.id?{...e,...t.toast}:e)};case"DISMISS_TOAST":{let{toastId:r}=t;return r?i(r):e.toasts.forEach(e=>{i(e.id)}),{...e,toasts:e.toasts.map(e=>e.id===r||void 0===r?{...e,open:!1}:e)}}case"REMOVE_TOAST":if(void 0===t.toastId)return{...e,toasts:[]};return{...e,toasts:e.toasts.filter(e=>e.id!==t.toastId)}}},c=[],l={toasts:[]};function d(e){l=n(l,e),c.forEach(e=>{e(l)})}function u({...e}){let t=(s=(s+1)%Number.MAX_SAFE_INTEGER).toString(),r=()=>d({type:"DISMISS_TOAST",toastId:t});return d({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:e=>{e||r()}}}),{id:t,dismiss:r,update:e=>d({type:"UPDATE_TOAST",toast:{...e,id:t}})}}function h(){let[e,t]=a.useState(l);return a.useEffect(()=>(c.push(t),()=>{let e=c.indexOf(t);e>-1&&c.splice(e,1)}),[e]),{...e,toast:u,dismiss:e=>d({type:"DISMISS_TOAST",toastId:e})}}},3603:(e,t,r)=>{"use strict";r.d(t,{cn:()=>o});var a=r(2281),s=r(4805);function o(...e){return(0,s.QP)((0,a.$)(e))}},1831:(e,t,r)=>{"use strict";r.d(t,{DatabaseProvider:()=>s});var a=r(4379);let s=(0,a.registerClientReference)(function(){throw Error("Attempted to call DatabaseProvider() from the server but DatabaseProvider is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/kona/Desktop/d1studio/src/context/database-context.js","DatabaseProvider");(0,a.registerClientReference)(function(){throw Error("Attempted to call useDatabase() from the server but useDatabase is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/kona/Desktop/d1studio/src/context/database-context.js","useDatabase")}};
|