opacacms 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bun.lock +34 -0
- package/dist/admin/api-client.d.ts +8 -0
- package/dist/admin/auth-client.d.ts +940 -0
- package/dist/admin/custom-field.d.ts +71 -0
- package/dist/admin/index.d.ts +11 -0
- package/dist/admin/react.d.ts +3 -0
- package/dist/admin/router.d.ts +7 -0
- package/dist/admin/stores/admin-queries.d.ts +32 -0
- package/dist/admin/stores/auth.d.ts +33 -0
- package/dist/admin/stores/column-visibility.d.ts +21 -0
- package/dist/admin/stores/config.d.ts +7 -0
- package/dist/admin/stores/media.d.ts +44 -0
- package/dist/admin/stores/query.d.ts +4 -0
- package/dist/admin/stores/ui.d.ts +11 -0
- package/dist/admin/ui/admin-client.d.ts +7 -0
- package/dist/admin/ui/admin-layout.d.ts +14 -0
- package/dist/admin/ui/components/ColumnVisibilityToggle.d.ts +10 -0
- package/dist/admin/ui/components/DataDetailSheet.d.ts +13 -0
- package/dist/admin/ui/components/DataDetailView.d.ts +9 -0
- package/dist/admin/ui/components/Table.d.ts +10 -0
- package/dist/admin/ui/components/fields/ArrayField.d.ts +13 -0
- package/dist/admin/ui/components/fields/BlocksField.d.ts +17 -0
- package/dist/admin/ui/components/fields/BooleanField.d.ts +13 -0
- package/dist/admin/ui/components/fields/CollapsibleField.d.ts +16 -0
- package/dist/admin/ui/components/fields/DateField.d.ts +13 -0
- package/dist/admin/ui/components/fields/FileField.d.ts +23 -0
- package/dist/admin/ui/components/fields/GroupField.d.ts +13 -0
- package/dist/admin/ui/components/fields/JoinField.d.ts +15 -0
- package/dist/admin/ui/components/fields/NumberField.d.ts +14 -0
- package/dist/admin/ui/components/fields/RadioField.d.ts +17 -0
- package/dist/admin/ui/components/fields/RelationshipField.d.ts +16 -0
- package/dist/admin/ui/components/fields/RowField.d.ts +12 -0
- package/dist/admin/ui/components/fields/SelectField.d.ts +18 -0
- package/dist/admin/ui/components/fields/TabsField.d.ts +15 -0
- package/dist/admin/ui/components/fields/TextAreaField.d.ts +14 -0
- package/dist/admin/ui/components/fields/TextField.d.ts +14 -0
- package/dist/admin/ui/components/fields/VirtualField.d.ts +8 -0
- package/dist/admin/ui/components/fields/index.d.ts +28 -0
- package/dist/admin/ui/components/fields/richtext-editor/index.d.ts +10 -0
- package/dist/admin/ui/components/fields/richtext-editor/nodes/ImageComponent.d.ts +7 -0
- package/dist/admin/ui/components/fields/richtext-editor/nodes/ImageNode.d.ts +27 -0
- package/dist/admin/ui/components/fields/richtext-editor/plugins/ComponentPickerPlugin.d.ts +1 -0
- package/dist/admin/ui/components/fields/richtext-editor/plugins/EditableSyncPlugin.d.ts +5 -0
- package/dist/admin/ui/components/fields/richtext-editor/plugins/NotionToolbarPlugin.d.ts +1 -0
- package/dist/admin/ui/components/fields/richtext-editor/plugins/SimpleToolbarPlugin.d.ts +1 -0
- package/dist/admin/ui/components/fields/richtext-editor/plugins/ValueSyncPlugin.d.ts +5 -0
- package/dist/admin/ui/components/fields/utils.d.ts +1 -0
- package/dist/admin/ui/components/link.d.ts +8 -0
- package/dist/admin/ui/components/media/AssetManagerModal.d.ts +17 -0
- package/dist/admin/ui/components/toast.d.ts +10 -0
- package/dist/admin/ui/components/ui/accordion.d.ts +11 -0
- package/dist/admin/ui/components/ui/alert-dialog.d.ts +12 -0
- package/dist/admin/ui/components/ui/blocks.d.ts +5 -0
- package/dist/admin/ui/components/ui/breadcrumbs.d.ts +7 -0
- package/dist/admin/ui/components/ui/button.d.ts +7 -0
- package/dist/admin/ui/components/ui/collapsible.d.ts +16 -0
- package/dist/admin/ui/components/ui/dialog.d.ts +27 -0
- package/dist/admin/ui/components/ui/group.d.ts +6 -0
- package/dist/admin/ui/components/ui/index.d.ts +17 -0
- package/dist/admin/ui/components/ui/input.d.ts +5 -0
- package/dist/admin/ui/components/ui/join.d.ts +7 -0
- package/dist/admin/ui/components/ui/label.d.ts +3 -0
- package/dist/admin/ui/components/ui/radio-group.d.ts +13 -0
- package/dist/admin/ui/components/ui/relationship-detail-sheet.d.ts +9 -0
- package/dist/admin/ui/components/ui/relationship.d.ts +8 -0
- package/dist/admin/ui/components/ui/scroll-area.d.ts +7 -0
- package/dist/admin/ui/components/ui/select.d.ts +37 -0
- package/dist/admin/ui/components/ui/separator.d.ts +8 -0
- package/dist/admin/ui/components/ui/sheet.d.ts +28 -0
- package/dist/admin/ui/components/ui/tabs.d.ts +17 -0
- package/dist/admin/ui/components/ui/utils.d.ts +1 -0
- package/dist/admin/ui/hooks/use-debounce.d.ts +1 -0
- package/dist/admin/ui/views/collection-list-view.d.ts +5 -0
- package/dist/admin/ui/views/dashboard-view.d.ts +10 -0
- package/dist/admin/ui/views/document-edit-view.d.ts +7 -0
- package/dist/admin/ui/views/global-edit-view.d.ts +19 -0
- package/dist/admin/ui/views/init-view.d.ts +4 -0
- package/dist/admin/ui/views/login-view.d.ts +4 -0
- package/dist/admin/ui/views/media-registry-view.d.ts +7 -0
- package/dist/admin/ui/views/settings-view.d.ts +7 -0
- package/dist/admin/webcomponent.d.ts +1 -0
- package/dist/api.d.ts +6 -0
- package/dist/auth/index.d.ts +2107 -0
- package/dist/auth/migrations.d.ts +5 -0
- package/dist/auth/premissions.d.ts +6 -0
- package/dist/chunk-16vgcf3k.js +88 -0
- package/dist/chunk-2zm8cy1w.js +9482 -0
- package/dist/chunk-5gvbp2qa.js +167 -0
- package/dist/chunk-62ev8gnc.js +41 -0
- package/dist/chunk-6dhs73zq.js +126 -0
- package/dist/chunk-6ew02s0c.js +472 -0
- package/dist/chunk-7a9kn0np.js +116 -0
- package/dist/chunk-8gkhn1d4.js +309 -0
- package/dist/chunk-8sqjbsgt.js +42 -0
- package/dist/chunk-9kxpbcb1.js +85 -0
- package/dist/chunk-cvdd4eqh.js +110 -0
- package/dist/chunk-d3ffeqp9.js +87 -0
- package/dist/chunk-dy5t83hr.js +261 -0
- package/dist/chunk-f3nvxn63.js +17 -0
- package/dist/chunk-hmhcense.js +1352 -0
- package/dist/chunk-j4d50hrx.js +20 -0
- package/dist/chunk-jwjk85ze.js +15 -0
- package/dist/chunk-kwp83w8b.js +250 -0
- package/dist/chunk-s8mqwnm1.js +14 -0
- package/dist/chunk-srsac177.js +85 -0
- package/dist/chunk-v521d72w.js +10 -0
- package/dist/chunk-xa7rjsn2.js +20 -0
- package/dist/chunk-xg35h5a3.js +15 -0
- package/dist/chunk-ybbbqj63.js +130 -0
- package/dist/chunk-zvwb67nd.js +332 -0
- package/dist/cli/commands/generate-types.d.ts +1 -0
- package/dist/cli/commands/init.d.ts +1 -0
- package/dist/cli/commands/migrate-commands.d.ts +5 -0
- package/dist/cli/commands/seed-command.d.ts +2 -0
- package/dist/cli/d1-mock.d.ts +30 -0
- package/dist/cli/index.d.ts +5 -0
- package/dist/cli/index.test.d.ts +1 -0
- package/dist/cli/r2-mock.d.ts +46 -0
- package/dist/cli/seeding.d.ts +17 -0
- package/dist/client.d.ts +51 -0
- package/dist/config-utils.d.ts +6 -0
- package/dist/config.d.ts +10 -0
- package/dist/db/adapter.d.ts +34 -0
- package/dist/db/better-sqlite.d.ts +40 -0
- package/dist/db/bun-sqlite.d.ts +40 -0
- package/dist/db/d1.d.ts +42 -0
- package/dist/db/kysely/data-mapper.d.ts +6 -0
- package/dist/db/kysely/field-mapper.d.ts +22 -0
- package/dist/db/kysely/migration-generator.d.ts +9 -0
- package/dist/db/kysely/query-builder.d.ts +9 -0
- package/dist/db/kysely/schema-builder.d.ts +15 -0
- package/dist/db/kysely/sql-utils.d.ts +1 -0
- package/dist/db/postgres.d.ts +51 -0
- package/dist/db/sqlite.d.ts +41 -0
- package/dist/db/system-schema.d.ts +2 -0
- package/dist/index.d.ts +6 -0
- package/dist/runtimes/bun.d.ts +17 -0
- package/dist/runtimes/cloudflare-workers.d.ts +10 -0
- package/dist/runtimes/next.d.ts +16 -0
- package/dist/runtimes/node.d.ts +18 -0
- package/dist/schema/collection.d.ts +100 -0
- package/dist/schema/fields/base.d.ts +83 -0
- package/dist/schema/fields/index.d.ts +135 -0
- package/dist/schema/global.d.ts +82 -0
- package/dist/schema/index.d.ts +4 -0
- package/dist/schema/infer.d.ts +55 -0
- package/dist/server/admin-router.d.ts +9 -0
- package/dist/server/admin.d.ts +18 -0
- package/dist/server/assets.d.ts +47 -0
- package/dist/server/collection-router.d.ts +14 -0
- package/dist/server/handlers.d.ts +76 -0
- package/dist/server/middlewares/admin.d.ts +6 -0
- package/dist/server/middlewares/auth.d.ts +16 -0
- package/dist/server/middlewares/context.d.ts +9 -0
- package/dist/server/middlewares/cors.d.ts +3 -0
- package/dist/server/middlewares/database-init.d.ts +11 -0
- package/dist/server/middlewares/rate-limit.d.ts +3 -0
- package/dist/server/router.d.ts +7 -0
- package/dist/server/setup-middlewares.d.ts +17 -0
- package/dist/server/system-router.d.ts +9 -0
- package/dist/server.d.ts +6 -0
- package/dist/src/admin/index.css +47 -0
- package/dist/src/admin/index.js +176 -0
- package/dist/src/admin/webcomponent.js +19 -0
- package/dist/src/api.js +27 -0
- package/dist/src/cli/index.js +157 -0
- package/dist/src/client.js +9 -0
- package/dist/src/db/bun-sqlite.js +523 -0
- package/dist/src/db/d1.js +568 -0
- package/dist/src/db/postgres.js +520 -0
- package/dist/src/db/sqlite.js +534 -0
- package/dist/src/index.js +20 -0
- package/dist/src/runtimes/bun.js +36 -0
- package/dist/src/runtimes/cloudflare-workers.js +29 -0
- package/dist/src/runtimes/next.js +26 -0
- package/dist/src/runtimes/node.js +38 -0
- package/dist/src/server.js +27 -0
- package/dist/src/storage/index.js +355 -0
- package/dist/storage/adapters/cloudflare-r2.d.ts +6 -0
- package/dist/storage/adapters/local.d.ts +6 -0
- package/dist/storage/adapters/s3.d.ts +13 -0
- package/dist/storage/errors.d.ts +12 -0
- package/dist/storage/index.d.ts +5 -0
- package/dist/storage/types.d.ts +31 -0
- package/dist/types.d.ts +484 -0
- package/dist/utils/lexical.d.ts +5 -0
- package/dist/utils/logger.d.ts +35 -0
- package/dist/validation.d.ts +300 -0
- package/dist/validator.d.ts +9 -0
- package/global.d.ts +11 -0
- package/package.json +151 -0
- package/src/admin/api-client.ts +63 -0
- package/src/admin/auth-client.ts +40 -0
- package/src/admin/custom-field.ts +179 -0
- package/src/admin/index.ts +15 -0
- package/src/admin/react.tsx +72 -0
- package/src/admin/router.ts +9 -0
- package/src/admin/stores/admin-queries.ts +121 -0
- package/src/admin/stores/auth.ts +61 -0
- package/src/admin/stores/column-visibility.ts +67 -0
- package/src/admin/stores/config.ts +15 -0
- package/src/admin/stores/media.ts +95 -0
- package/src/admin/stores/query.ts +13 -0
- package/src/admin/stores/ui.ts +29 -0
- package/src/admin/ui/admin-client.tsx +283 -0
- package/src/admin/ui/admin-layout.tsx +276 -0
- package/src/admin/ui/components/ColumnVisibilityToggle.tsx +141 -0
- package/src/admin/ui/components/DataDetailSheet.tsx +141 -0
- package/src/admin/ui/components/DataDetailView.tsx +175 -0
- package/src/admin/ui/components/Table.tsx +67 -0
- package/src/admin/ui/components/fields/ArrayField.tsx +166 -0
- package/src/admin/ui/components/fields/BlocksField.tsx +202 -0
- package/src/admin/ui/components/fields/BooleanField.tsx +50 -0
- package/src/admin/ui/components/fields/CollapsibleField.tsx +75 -0
- package/src/admin/ui/components/fields/DateField.tsx +45 -0
- package/src/admin/ui/components/fields/FileField.tsx +322 -0
- package/src/admin/ui/components/fields/GroupField.tsx +50 -0
- package/src/admin/ui/components/fields/JoinField.tsx +23 -0
- package/src/admin/ui/components/fields/NumberField.tsx +46 -0
- package/src/admin/ui/components/fields/RadioField.tsx +62 -0
- package/src/admin/ui/components/fields/RelationshipField.tsx +278 -0
- package/src/admin/ui/components/fields/RowField.tsx +40 -0
- package/src/admin/ui/components/fields/SelectField.tsx +59 -0
- package/src/admin/ui/components/fields/TabsField.tsx +101 -0
- package/src/admin/ui/components/fields/TextAreaField.tsx +54 -0
- package/src/admin/ui/components/fields/TextField.tsx +49 -0
- package/src/admin/ui/components/fields/VirtualField.tsx +53 -0
- package/src/admin/ui/components/fields/index.tsx +371 -0
- package/src/admin/ui/components/fields/richtext-editor/index.tsx +211 -0
- package/src/admin/ui/components/fields/richtext-editor/nodes/ImageComponent.tsx +142 -0
- package/src/admin/ui/components/fields/richtext-editor/nodes/ImageNode.tsx +95 -0
- package/src/admin/ui/components/fields/richtext-editor/plugins/ComponentPickerPlugin.tsx +226 -0
- package/src/admin/ui/components/fields/richtext-editor/plugins/EditableSyncPlugin.tsx +16 -0
- package/src/admin/ui/components/fields/richtext-editor/plugins/NotionToolbarPlugin.tsx +184 -0
- package/src/admin/ui/components/fields/richtext-editor/plugins/SimpleToolbarPlugin.tsx +240 -0
- package/src/admin/ui/components/fields/richtext-editor/plugins/ValueSyncPlugin.tsx +40 -0
- package/src/admin/ui/components/fields/utils.ts +1 -0
- package/src/admin/ui/components/link.tsx +41 -0
- package/src/admin/ui/components/media/AssetManagerModal.tsx +334 -0
- package/src/admin/ui/components/toast.tsx +72 -0
- package/src/admin/ui/components/ui/accordion.tsx +51 -0
- package/src/admin/ui/components/ui/alert-dialog.tsx +98 -0
- package/src/admin/ui/components/ui/blocks.tsx +32 -0
- package/src/admin/ui/components/ui/breadcrumbs.tsx +59 -0
- package/src/admin/ui/components/ui/button.tsx +26 -0
- package/src/admin/ui/components/ui/collapsible.tsx +124 -0
- package/src/admin/ui/components/ui/dialog.tsx +79 -0
- package/src/admin/ui/components/ui/group.tsx +20 -0
- package/src/admin/ui/components/ui/index.ts +17 -0
- package/src/admin/ui/components/ui/input.tsx +12 -0
- package/src/admin/ui/components/ui/join.tsx +53 -0
- package/src/admin/ui/components/ui/label.tsx +11 -0
- package/src/admin/ui/components/ui/radio-group.tsx +75 -0
- package/src/admin/ui/components/ui/relationship-detail-sheet.tsx +122 -0
- package/src/admin/ui/components/ui/relationship.tsx +58 -0
- package/src/admin/ui/components/ui/scroll-area.tsx +19 -0
- package/src/admin/ui/components/ui/select.tsx +187 -0
- package/src/admin/ui/components/ui/separator.tsx +21 -0
- package/src/admin/ui/components/ui/sheet.tsx +106 -0
- package/src/admin/ui/components/ui/tabs.tsx +116 -0
- package/src/admin/ui/components/ui/utils.ts +3 -0
- package/src/admin/ui/hooks/use-debounce.ts +15 -0
- package/src/admin/ui/styles/_locale-switcher.scss +33 -0
- package/src/admin/ui/styles/accordion.scss +60 -0
- package/src/admin/ui/styles/animations.scss +41 -0
- package/src/admin/ui/styles/asset-manager.scss +547 -0
- package/src/admin/ui/styles/badge.scss +13 -0
- package/src/admin/ui/styles/base.scss +22 -0
- package/src/admin/ui/styles/button.scss +161 -0
- package/src/admin/ui/styles/card.scss +13 -0
- package/src/admin/ui/styles/collapsible.scss +75 -0
- package/src/admin/ui/styles/data-detail.scss +92 -0
- package/src/admin/ui/styles/dialog.scss +102 -0
- package/src/admin/ui/styles/empty-state.scss +22 -0
- package/src/admin/ui/styles/group.scss +19 -0
- package/src/admin/ui/styles/index.scss +33 -0
- package/src/admin/ui/styles/input.scss +80 -0
- package/src/admin/ui/styles/label.scss +12 -0
- package/src/admin/ui/styles/layout.scss +56 -0
- package/src/admin/ui/styles/lexical.scss +469 -0
- package/src/admin/ui/styles/loading.scss +102 -0
- package/src/admin/ui/styles/media-registry.scss +597 -0
- package/src/admin/ui/styles/pagination.scss +20 -0
- package/src/admin/ui/styles/radio-group.scss +66 -0
- package/src/admin/ui/styles/row.scss +17 -0
- package/src/admin/ui/styles/scrollbar.scss +36 -0
- package/src/admin/ui/styles/select.scss +121 -0
- package/src/admin/ui/styles/separator.scss +14 -0
- package/src/admin/ui/styles/sheet.scss +152 -0
- package/src/admin/ui/styles/sidebar.scss +148 -0
- package/src/admin/ui/styles/switch.scss +59 -0
- package/src/admin/ui/styles/table.scss +207 -0
- package/src/admin/ui/styles/tabs.scss +62 -0
- package/src/admin/ui/styles/toast.scss +45 -0
- package/src/admin/ui/styles/variables.scss +24 -0
- package/src/admin/ui/views/collection-list-view.tsx +720 -0
- package/src/admin/ui/views/dashboard-view.tsx +263 -0
- package/src/admin/ui/views/document-edit-view.tsx +384 -0
- package/src/admin/ui/views/global-edit-view.tsx +226 -0
- package/src/admin/ui/views/init-view.tsx +182 -0
- package/src/admin/ui/views/login-view.tsx +123 -0
- package/src/admin/ui/views/media-registry-view.tsx +1104 -0
- package/src/admin/ui/views/settings-view.tsx +729 -0
- package/src/admin/webcomponent.tsx +15 -0
- package/src/api.ts +9 -0
- package/src/auth/index.ts +194 -0
- package/src/auth/migrations.ts +87 -0
- package/src/auth/premissions.ts +46 -0
- package/src/cli/commands/generate-types.ts +116 -0
- package/src/cli/commands/init.ts +95 -0
- package/src/cli/commands/migrate-commands.ts +160 -0
- package/src/cli/commands/seed-command.ts +11 -0
- package/src/cli/d1-mock.ts +101 -0
- package/src/cli/index.test.ts +84 -0
- package/src/cli/index.ts +183 -0
- package/src/cli/r2-mock.ts +217 -0
- package/src/cli/seeding.ts +405 -0
- package/src/client.ts +181 -0
- package/src/config-utils.ts +102 -0
- package/src/config.ts +49 -0
- package/src/db/adapter.ts +53 -0
- package/src/db/better-sqlite.ts +630 -0
- package/src/db/bun-sqlite.ts +646 -0
- package/src/db/d1.ts +711 -0
- package/src/db/kysely/data-mapper.ts +142 -0
- package/src/db/kysely/field-mapper.ts +148 -0
- package/src/db/kysely/migration-generator.ts +223 -0
- package/src/db/kysely/query-builder.ts +92 -0
- package/src/db/kysely/schema-builder.ts +439 -0
- package/src/db/kysely/sql-utils.ts +13 -0
- package/src/db/postgres.ts +621 -0
- package/src/db/sqlite.ts +658 -0
- package/src/db/system-schema.ts +121 -0
- package/src/index.ts +13 -0
- package/src/runtimes/README.md +59 -0
- package/src/runtimes/bun.ts +49 -0
- package/src/runtimes/cloudflare-workers.ts +38 -0
- package/src/runtimes/next.ts +26 -0
- package/src/runtimes/node.ts +52 -0
- package/src/schema/collection.ts +184 -0
- package/src/schema/fields/base.ts +164 -0
- package/src/schema/fields/index.ts +427 -0
- package/src/schema/global.ts +145 -0
- package/src/schema/index.ts +4 -0
- package/src/schema/infer.ts +72 -0
- package/src/server/admin-router.ts +20 -0
- package/src/server/admin.ts +142 -0
- package/src/server/assets.ts +306 -0
- package/src/server/collection-router.ts +55 -0
- package/src/server/handlers.ts +722 -0
- package/src/server/middlewares/admin.ts +27 -0
- package/src/server/middlewares/auth.ts +89 -0
- package/src/server/middlewares/context.ts +17 -0
- package/src/server/middlewares/cors.ts +24 -0
- package/src/server/middlewares/database-init.ts +74 -0
- package/src/server/middlewares/rate-limit.ts +71 -0
- package/src/server/router.ts +47 -0
- package/src/server/setup-middlewares.ts +58 -0
- package/src/server/system-router.ts +35 -0
- package/src/server.ts +9 -0
- package/src/storage/adapters/cloudflare-r2.ts +136 -0
- package/src/storage/adapters/local.ts +146 -0
- package/src/storage/adapters/s3.ts +186 -0
- package/src/storage/errors.ts +46 -0
- package/src/storage/index.ts +5 -0
- package/src/storage/types.ts +39 -0
- package/src/types.ts +577 -0
- package/src/utils/lexical.ts +37 -0
- package/src/utils/logger.ts +73 -0
- package/src/validation.ts +429 -0
- package/src/validator.ts +179 -0
- package/test/admin-custom-field.test.ts +162 -0
- package/test/admin-react-field.test.tsx +134 -0
- package/test/api-features.test.ts +78 -0
- package/test/api.test.ts +178 -0
- package/test/auth.test.ts +62 -0
- package/test/cli-integration.test.ts +146 -0
- package/test/cli.test.ts +25 -0
- package/test/db/postgres.test.ts +95 -0
- package/test/db/sqlite-filter.test.ts +53 -0
- package/test/db/sqlite.test.ts +82 -0
- package/test/engine-features.test.ts +79 -0
- package/test/globals.test.ts +74 -0
- package/test/integration-tmp/db-app/opacacms.config.ts +15 -0
- package/test/integration-tmp/my-sqlite-app/opacacms.config.ts +25 -0
- package/test/integration-tmp/my-test-app/index.ts +8 -0
- package/test/integration-tmp/my-test-app/opacacms.config.ts +16 -0
- package/test/integration-tmp/my-test-app/package.json +12 -0
- package/test/populate.test.ts +79 -0
- package/test/runtimes.test.ts +43 -0
- package/test/schema-builder.test.ts +107 -0
- package/test/schema-features.test.ts +63 -0
- package/test/seeding.test.ts +68 -0
- package/test/storage/local.test.ts +72 -0
- package/test/storage/s3.test.ts +60 -0
- package/test/structural-data.test.ts +100 -0
- package/test/test-setup.ts +11 -0
- package/test/validation.test.ts +162 -0
- package/tsconfig.json +42 -0
package/src/db/d1.ts
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
4
|
+
import { CompiledQuery, FileMigrationProvider, Kysely, Migrator, sql } from "kysely";
|
|
5
|
+
import { D1Dialect } from "kysely-d1";
|
|
6
|
+
import type { Collection, FindOptions, Global, PaginatedResult } from "../types";
|
|
7
|
+
import { logger } from "../utils/logger";
|
|
8
|
+
import { BaseDatabaseAdapter } from "./adapter";
|
|
9
|
+
import { flattenPayload, unflattenRow } from "./kysely/data-mapper";
|
|
10
|
+
import { flattenFields, getRelationalFields, toSnakeCase } from "./kysely/field-mapper";
|
|
11
|
+
import { buildKyselyWhere } from "./kysely/query-builder";
|
|
12
|
+
import { pushSchema } from "./kysely/schema-builder";
|
|
13
|
+
|
|
14
|
+
export class D1Adapter extends BaseDatabaseAdapter {
|
|
15
|
+
override name = "d1";
|
|
16
|
+
private _rawDb: D1Database;
|
|
17
|
+
private _db: Kysely<any>;
|
|
18
|
+
private _collections: Collection[] = [];
|
|
19
|
+
private _globals: Global[] = [];
|
|
20
|
+
override push: boolean;
|
|
21
|
+
override migrationDir: string;
|
|
22
|
+
override pushDestructive: boolean;
|
|
23
|
+
|
|
24
|
+
override get raw() {
|
|
25
|
+
return this._rawDb;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
override get db() {
|
|
29
|
+
return this._db;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
constructor(
|
|
33
|
+
db: D1Database,
|
|
34
|
+
options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
|
|
35
|
+
) {
|
|
36
|
+
super();
|
|
37
|
+
this._rawDb = db;
|
|
38
|
+
this._db = new Kysely<any>({
|
|
39
|
+
dialect: new D1Dialect({ database: db }),
|
|
40
|
+
});
|
|
41
|
+
const isDev = typeof process !== "undefined" && process.env.NODE_ENV !== "production";
|
|
42
|
+
this.push = options?.push ?? isDev;
|
|
43
|
+
this.pushDestructive = options?.pushDestructive ?? false;
|
|
44
|
+
this.migrationDir = options?.migrationDir ?? "./migrations";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
override async connect(): Promise<void> {
|
|
48
|
+
// D1 connects automatically per request
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
override async disconnect(): Promise<void> {
|
|
52
|
+
await this._db.destroy();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
override async unsafe(query: string, params?: unknown[]): Promise<unknown> {
|
|
56
|
+
const compiled = CompiledQuery.raw(query, (params || []) as any);
|
|
57
|
+
const result = await this._db.executeQuery(compiled);
|
|
58
|
+
return result.rows;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private async coerceData(collection: string, data: any): Promise<any> {
|
|
62
|
+
const colDef = this._collections.find((c) => c.slug === collection);
|
|
63
|
+
if (!colDef) return data;
|
|
64
|
+
|
|
65
|
+
const result = { ...data };
|
|
66
|
+
const allFields = flattenFields(colDef.fields);
|
|
67
|
+
|
|
68
|
+
for (const field of allFields) {
|
|
69
|
+
const colName = toSnakeCase(field.name!);
|
|
70
|
+
if (!(colName in result)) continue;
|
|
71
|
+
|
|
72
|
+
const value = result[colName];
|
|
73
|
+
if (value === undefined || value === null) continue;
|
|
74
|
+
|
|
75
|
+
switch (field.type) {
|
|
76
|
+
case "boolean":
|
|
77
|
+
result[colName] = value ? 1 : 0;
|
|
78
|
+
break;
|
|
79
|
+
case "number":
|
|
80
|
+
result[colName] = Number(value);
|
|
81
|
+
break;
|
|
82
|
+
case "date":
|
|
83
|
+
if (value instanceof Date) {
|
|
84
|
+
result[colName] = value.toISOString();
|
|
85
|
+
} else if (typeof value === "string") {
|
|
86
|
+
result[colName] = new Date(value).toISOString();
|
|
87
|
+
}
|
|
88
|
+
break;
|
|
89
|
+
case "richtext":
|
|
90
|
+
case "json":
|
|
91
|
+
case "file":
|
|
92
|
+
if (typeof value === "object") {
|
|
93
|
+
result[colName] = JSON.stringify(value);
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
override async count(collection: string, query?: Record<string, unknown>): Promise<number> {
|
|
103
|
+
let qb = this._db.selectFrom(collection).select((eb) => eb.fn.count("id").as("count"));
|
|
104
|
+
if (query && Object.keys(query).length > 0) {
|
|
105
|
+
qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
|
|
106
|
+
}
|
|
107
|
+
const result = await qb.executeTakeFirst();
|
|
108
|
+
return Number(result?.count || 0);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
override async create<T extends object>(collection: string, data: Partial<T>): Promise<T> {
|
|
112
|
+
const colDef = this._collections.find((c) => c.slug === collection);
|
|
113
|
+
const jsonFields =
|
|
114
|
+
colDef?.fields
|
|
115
|
+
.filter((f) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
|
|
116
|
+
.map((f) => f.name!) || [];
|
|
117
|
+
|
|
118
|
+
const flatData = flattenPayload(data, "", jsonFields);
|
|
119
|
+
|
|
120
|
+
const relationalFields = getRelationalFields(colDef?.fields || []);
|
|
121
|
+
const hasManyData: Record<string, unknown[]> = {};
|
|
122
|
+
const blocksData: Record<string, unknown[]> = {};
|
|
123
|
+
|
|
124
|
+
for (const field of relationalFields) {
|
|
125
|
+
const key = field.name!;
|
|
126
|
+
if (Array.isArray(flatData[key])) {
|
|
127
|
+
if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
|
|
128
|
+
hasManyData[key] = flatData[key];
|
|
129
|
+
} else if (field.type === "blocks") {
|
|
130
|
+
blocksData[key] = flatData[key];
|
|
131
|
+
}
|
|
132
|
+
delete flatData[key];
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (!flatData.id) flatData.id = crypto.randomUUID();
|
|
137
|
+
|
|
138
|
+
// Whitelist only fields that exist in the database
|
|
139
|
+
const dbFields = flattenFields(colDef?.fields || []);
|
|
140
|
+
const validCols = new Set(dbFields.map((f) => toSnakeCase(f.name!)));
|
|
141
|
+
validCols.add("id");
|
|
142
|
+
|
|
143
|
+
// Add timestamps if enabled
|
|
144
|
+
const ts = colDef?.timestamps !== false;
|
|
145
|
+
if (ts) {
|
|
146
|
+
const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
|
|
147
|
+
const createdAtField = toSnakeCase(config.createdAt || "createdAt");
|
|
148
|
+
const updatedAtField = toSnakeCase(config.updatedAt || "updatedAt");
|
|
149
|
+
const now = new Date().toISOString();
|
|
150
|
+
if (!flatData[createdAtField]) flatData[createdAtField] = now;
|
|
151
|
+
if (!flatData[updatedAtField]) flatData[updatedAtField] = now;
|
|
152
|
+
validCols.add(createdAtField);
|
|
153
|
+
validCols.add(updatedAtField);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const filteredData: Record<string, any> = {};
|
|
157
|
+
for (const col of Object.keys(flatData)) {
|
|
158
|
+
if (validCols.has(col)) {
|
|
159
|
+
filteredData[col] = flatData[col];
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const coercedData = await this.coerceData(collection, filteredData);
|
|
164
|
+
try {
|
|
165
|
+
await this._db.insertInto(collection).values(coercedData).execute();
|
|
166
|
+
} catch (e: any) {
|
|
167
|
+
logger.error(`[D1] Create failed in ${collection}: ${e.message}`);
|
|
168
|
+
throw e;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// hasMany relations
|
|
172
|
+
for (const [key, values] of Object.entries(hasManyData)) {
|
|
173
|
+
const joinTableName = `${collection}_${toSnakeCase(key)}_relations`.toLowerCase();
|
|
174
|
+
if (values.length > 0) {
|
|
175
|
+
const joinData = values.map((val: any, idx: number) => {
|
|
176
|
+
const tId = typeof val === "object" ? val.id : val;
|
|
177
|
+
return { id: crypto.randomUUID(), source_id: flatData.id, target_id: tId, order: idx };
|
|
178
|
+
});
|
|
179
|
+
await this._db.insertInto(joinTableName).values(joinData).execute();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Blocks
|
|
184
|
+
for (const [key, blocks] of Object.entries(blocksData)) {
|
|
185
|
+
for (let i = 0; i < (blocks as any[]).length; i++) {
|
|
186
|
+
const block = blocks[i] as any;
|
|
187
|
+
if (!block.blockType) continue;
|
|
188
|
+
const blockTableName =
|
|
189
|
+
`${collection}_${toSnakeCase(key)}_${toSnakeCase(block.blockType)}`.toLowerCase();
|
|
190
|
+
const bId = block.id || crypto.randomUUID();
|
|
191
|
+
|
|
192
|
+
// Block fields also need same logic
|
|
193
|
+
const blockDef = relationalFields.find((f) => f.name === key && f.type === "blocks");
|
|
194
|
+
const blockConfig = (blockDef as any)?.blocks?.find((b: any) => b.slug === block.blockType);
|
|
195
|
+
const blockJsonFields =
|
|
196
|
+
blockConfig?.fields
|
|
197
|
+
.filter((f: any) => ["richtext", "json", "file"].includes(f.type))
|
|
198
|
+
.map((f: any) => toSnakeCase(f.name!)) || [];
|
|
199
|
+
|
|
200
|
+
const blockFlatData = flattenPayload({ ...block, id: bId }, "", blockJsonFields);
|
|
201
|
+
|
|
202
|
+
for (const f of blockJsonFields) {
|
|
203
|
+
if (blockFlatData[f] && typeof blockFlatData[f] === "object") {
|
|
204
|
+
blockFlatData[f] = JSON.stringify(blockFlatData[f]);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
delete blockFlatData.blockType;
|
|
209
|
+
const coercedBlockData = await this.coerceData(blockTableName, {
|
|
210
|
+
...blockFlatData,
|
|
211
|
+
_parent_id: flatData.id,
|
|
212
|
+
_order: i,
|
|
213
|
+
block_type: block.blockType,
|
|
214
|
+
});
|
|
215
|
+
await this._db.insertInto(blockTableName).values(coercedBlockData).execute();
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return this.findOne<T>(collection, { id: flatData.id }, this._db) as Promise<T>;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
override async findOne<T extends object>(
|
|
223
|
+
collection: string,
|
|
224
|
+
query: Record<string, unknown>,
|
|
225
|
+
tx?: any,
|
|
226
|
+
): Promise<T | null> {
|
|
227
|
+
const executor = tx || this._db;
|
|
228
|
+
let qb = executor.selectFrom(collection).selectAll();
|
|
229
|
+
if (query && Object.keys(query).length > 0) {
|
|
230
|
+
qb = qb.where((eb: any) => buildKyselyWhere(eb, query) || eb.val(true));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const row = await qb.executeTakeFirst();
|
|
234
|
+
if (!row) return null;
|
|
235
|
+
|
|
236
|
+
const unflattened = unflattenRow(row);
|
|
237
|
+
const colDef = this._collections.find((c) => c.slug === collection);
|
|
238
|
+
|
|
239
|
+
if (colDef) {
|
|
240
|
+
const relationalFields = getRelationalFields(colDef.fields);
|
|
241
|
+
|
|
242
|
+
for (const field of relationalFields) {
|
|
243
|
+
if (!field.name) continue;
|
|
244
|
+
const snakeName = toSnakeCase(field.name);
|
|
245
|
+
if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
|
|
246
|
+
const joinTableName = `${collection}_${snakeName}_relations`.toLowerCase();
|
|
247
|
+
try {
|
|
248
|
+
const relations = await executor
|
|
249
|
+
.selectFrom(joinTableName)
|
|
250
|
+
.selectAll()
|
|
251
|
+
.where("source_id", "=", row.id)
|
|
252
|
+
.orderBy("order", "asc")
|
|
253
|
+
.execute();
|
|
254
|
+
const parts = field.name!.split("__");
|
|
255
|
+
let current = unflattened;
|
|
256
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
257
|
+
if (!current[parts[i]!]) current[parts[i]!] = {};
|
|
258
|
+
current = current[parts[i]!];
|
|
259
|
+
}
|
|
260
|
+
current[parts[parts.length - 1]!] = relations.map((r: any) => r.target_id);
|
|
261
|
+
} catch (e) {}
|
|
262
|
+
} else if (field.type === "blocks" && "blocks" in field && field.blocks) {
|
|
263
|
+
const blockData: any[] = [];
|
|
264
|
+
for (const b of field.blocks) {
|
|
265
|
+
const blockTableName =
|
|
266
|
+
`${collection}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
|
|
267
|
+
try {
|
|
268
|
+
const blocks = await executor
|
|
269
|
+
.selectFrom(blockTableName)
|
|
270
|
+
.selectAll()
|
|
271
|
+
.where("_parent_id", "=", row.id)
|
|
272
|
+
.execute();
|
|
273
|
+
|
|
274
|
+
for (const blk of blocks) {
|
|
275
|
+
const uf = unflattenRow(blk);
|
|
276
|
+
uf.blockType = blk.block_type;
|
|
277
|
+
blockData.push(uf);
|
|
278
|
+
}
|
|
279
|
+
} catch (e) {}
|
|
280
|
+
}
|
|
281
|
+
blockData.sort((a, b) => a._order - b._order);
|
|
282
|
+
blockData.forEach((b) => {
|
|
283
|
+
delete b._order;
|
|
284
|
+
delete b._parent_id;
|
|
285
|
+
});
|
|
286
|
+
const parts = field.name!.split("__");
|
|
287
|
+
let current = unflattened;
|
|
288
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
289
|
+
if (!current[parts[i]!]) current[parts[i]!] = {};
|
|
290
|
+
current = current[parts[i]!];
|
|
291
|
+
}
|
|
292
|
+
current[parts[parts.length - 1]!] = blockData;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return unflattened as T;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
override async find<T extends object>(
|
|
301
|
+
collection: string,
|
|
302
|
+
query?: Record<string, unknown>,
|
|
303
|
+
options?: FindOptions,
|
|
304
|
+
): Promise<PaginatedResult<T>> {
|
|
305
|
+
const page = options?.page || 1;
|
|
306
|
+
const limit = options?.limit || 10;
|
|
307
|
+
const offset = (page - 1) * limit;
|
|
308
|
+
|
|
309
|
+
const total = await this.count(collection, query);
|
|
310
|
+
|
|
311
|
+
let qb = this._db.selectFrom(collection).selectAll().limit(limit).offset(offset);
|
|
312
|
+
if (query && Object.keys(query).length > 0) {
|
|
313
|
+
qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
|
|
314
|
+
}
|
|
315
|
+
if (options?.sort) {
|
|
316
|
+
const [col, dir] = (options.sort ?? "").split(":");
|
|
317
|
+
if (col) {
|
|
318
|
+
qb = qb.orderBy(col as any, dir === "desc" ? "desc" : "asc");
|
|
319
|
+
}
|
|
320
|
+
} else {
|
|
321
|
+
qb = qb.orderBy("created_at" as any, "desc");
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const rows = await qb.execute();
|
|
325
|
+
|
|
326
|
+
const docs = await Promise.all(rows.map((row) => this.findOne<T>(collection, { id: row.id })));
|
|
327
|
+
|
|
328
|
+
const totalPages = Math.ceil(total / limit);
|
|
329
|
+
return {
|
|
330
|
+
docs: docs.filter(Boolean) as T[],
|
|
331
|
+
totalDocs: total,
|
|
332
|
+
limit,
|
|
333
|
+
totalPages,
|
|
334
|
+
page,
|
|
335
|
+
pagingCounter: offset + 1,
|
|
336
|
+
hasNextPage: page * limit < total,
|
|
337
|
+
hasPrevPage: page > 1,
|
|
338
|
+
prevPage: page > 1 ? page - 1 : null,
|
|
339
|
+
nextPage: page < totalPages ? page + 1 : null,
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
override async update<T extends object>(
|
|
344
|
+
collection: string,
|
|
345
|
+
query: Record<string, unknown> | string | number,
|
|
346
|
+
data: Partial<T>,
|
|
347
|
+
): Promise<T> {
|
|
348
|
+
let normalizedQuery = query;
|
|
349
|
+
if (typeof query !== "object" || query === null) {
|
|
350
|
+
normalizedQuery = { id: query };
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const current = await this.findOne<any>(
|
|
354
|
+
collection,
|
|
355
|
+
normalizedQuery as Record<string, unknown>,
|
|
356
|
+
this._db,
|
|
357
|
+
);
|
|
358
|
+
if (!current) throw new Error("Document not found");
|
|
359
|
+
|
|
360
|
+
const colDef = this._collections.find((c) => c.slug === collection);
|
|
361
|
+
const jsonFields =
|
|
362
|
+
colDef?.fields
|
|
363
|
+
.filter((f) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
|
|
364
|
+
.map((f) => f.name!) || [];
|
|
365
|
+
|
|
366
|
+
const flatData = flattenPayload(data, "", jsonFields);
|
|
367
|
+
|
|
368
|
+
const relationalFields = getRelationalFields(colDef?.fields || []);
|
|
369
|
+
const hasManyData: Record<string, unknown[]> = {};
|
|
370
|
+
const blocksData: Record<string, unknown[]> = {};
|
|
371
|
+
|
|
372
|
+
for (const field of relationalFields) {
|
|
373
|
+
const key = field.name!;
|
|
374
|
+
if (Array.isArray(flatData[key])) {
|
|
375
|
+
if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
|
|
376
|
+
hasManyData[key] = flatData[key];
|
|
377
|
+
} else if (field.type === "blocks") {
|
|
378
|
+
blocksData[key] = flatData[key];
|
|
379
|
+
}
|
|
380
|
+
delete flatData[key];
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const ts = colDef?.timestamps !== false;
|
|
385
|
+
if (ts) {
|
|
386
|
+
const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
|
|
387
|
+
const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
|
|
388
|
+
flatData[updatedField] = new Date().toISOString();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
if (Object.keys(flatData).length > 0) {
|
|
392
|
+
// Whitelist only fields that exist in the database
|
|
393
|
+
const dbFields = flattenFields(colDef?.fields || []);
|
|
394
|
+
const validCols = new Set(dbFields.map((f) => toSnakeCase(f.name!)));
|
|
395
|
+
validCols.add("id");
|
|
396
|
+
|
|
397
|
+
if (ts) {
|
|
398
|
+
const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
|
|
399
|
+
validCols.add(toSnakeCase(config.createdAt || "createdAt"));
|
|
400
|
+
validCols.add(toSnakeCase(config.updatedAt || "updatedAt"));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const filteredData: Record<string, any> = {};
|
|
404
|
+
for (const col of Object.keys(flatData)) {
|
|
405
|
+
if (validCols.has(col)) {
|
|
406
|
+
filteredData[col] = flatData[col];
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const coercedData = await this.coerceData(collection, filteredData);
|
|
411
|
+
try {
|
|
412
|
+
await this._db
|
|
413
|
+
.updateTable(collection)
|
|
414
|
+
.set(coercedData)
|
|
415
|
+
.where("id", "=", current.id)
|
|
416
|
+
.execute();
|
|
417
|
+
} catch (e: any) {
|
|
418
|
+
logger.error(`[D1] Update failed in ${collection}: ${e.message}`);
|
|
419
|
+
throw e;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
for (const [key, values] of Object.entries(hasManyData)) {
|
|
424
|
+
const joinTableName = `${collection}_${toSnakeCase(key)}_relations`.toLowerCase();
|
|
425
|
+
await this._db.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
|
|
426
|
+
if (values.length > 0) {
|
|
427
|
+
const joinData = values.map((val: any, idx: number) => {
|
|
428
|
+
const tId = typeof val === "object" ? val.id : val;
|
|
429
|
+
return { id: crypto.randomUUID(), source_id: current.id, target_id: tId, order: idx };
|
|
430
|
+
});
|
|
431
|
+
await this._db.insertInto(joinTableName).values(joinData).execute();
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
for (const [key, blocks] of Object.entries(blocksData)) {
|
|
436
|
+
const blockDef = relationalFields.find((f) => f.name === key && f.type === "blocks");
|
|
437
|
+
if (blockDef && "blocks" in blockDef && blockDef.blocks) {
|
|
438
|
+
for (const b of blockDef.blocks) {
|
|
439
|
+
const blockTableName =
|
|
440
|
+
`${collection}_${toSnakeCase(key)}_${toSnakeCase(b.slug)}`.toLowerCase();
|
|
441
|
+
try {
|
|
442
|
+
await this._db
|
|
443
|
+
.deleteFrom(blockTableName)
|
|
444
|
+
.where("_parent_id", "=", current.id)
|
|
445
|
+
.execute();
|
|
446
|
+
} catch (e) {}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
for (let i = 0; i < (blocks as any[]).length; i++) {
|
|
451
|
+
const block = blocks[i] as any;
|
|
452
|
+
if (!block.blockType) continue;
|
|
453
|
+
const blockTableName =
|
|
454
|
+
`${collection}_${toSnakeCase(key)}_${toSnakeCase(block.blockType)}`.toLowerCase();
|
|
455
|
+
const bId = block.id || crypto.randomUUID();
|
|
456
|
+
|
|
457
|
+
const blockConfig = (blockDef as any)?.blocks?.find((b: any) => b.slug === block.blockType);
|
|
458
|
+
const blockJsonFields =
|
|
459
|
+
blockConfig?.fields
|
|
460
|
+
.filter((f: any) => ["richtext", "json", "file"].includes(f.type))
|
|
461
|
+
.map((f: any) => toSnakeCase(f.name!)) || [];
|
|
462
|
+
|
|
463
|
+
const blockFlatData = flattenPayload({ ...block, id: bId }, "", blockJsonFields);
|
|
464
|
+
|
|
465
|
+
for (const f of blockJsonFields) {
|
|
466
|
+
if (blockFlatData[f] && typeof blockFlatData[f] === "object") {
|
|
467
|
+
blockFlatData[f] = JSON.stringify(blockFlatData[f]);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
delete blockFlatData.blockType;
|
|
472
|
+
const coercedBlockData = await this.coerceData(blockTableName, {
|
|
473
|
+
...blockFlatData,
|
|
474
|
+
_parent_id: current.id,
|
|
475
|
+
_order: i,
|
|
476
|
+
block_type: block.blockType,
|
|
477
|
+
});
|
|
478
|
+
await this._db.insertInto(blockTableName).values(coercedBlockData).execute();
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
return this.findOne<T>(collection, { id: current.id }, this._db) as Promise<T>;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
override async updateMany<T extends object>(
|
|
486
|
+
collection: string,
|
|
487
|
+
query: Record<string, unknown>,
|
|
488
|
+
data: Partial<T>,
|
|
489
|
+
): Promise<number> {
|
|
490
|
+
let qb = this._db.updateTable(collection);
|
|
491
|
+
if (query && Object.keys(query).length > 0) {
|
|
492
|
+
qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const colDef = this._collections.find((c) => c.slug === collection);
|
|
496
|
+
const jsonFields =
|
|
497
|
+
colDef?.fields
|
|
498
|
+
.filter((f) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
|
|
499
|
+
.map((f) => f.name!) || [];
|
|
500
|
+
|
|
501
|
+
const flatData = flattenPayload(data, "", jsonFields);
|
|
502
|
+
|
|
503
|
+
for (const key in flatData) {
|
|
504
|
+
if (Array.isArray(flatData[key])) {
|
|
505
|
+
delete flatData[key];
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const ts = colDef?.timestamps !== false;
|
|
510
|
+
if (ts) {
|
|
511
|
+
const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
|
|
512
|
+
const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
|
|
513
|
+
flatData[updatedField] = new Date().toISOString();
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
if (Object.keys(flatData).length > 0) {
|
|
517
|
+
// Whitelist only fields that exist in the database
|
|
518
|
+
const dbFields = flattenFields(colDef?.fields || []);
|
|
519
|
+
const validCols = new Set(dbFields.map((f) => toSnakeCase(f.name!)));
|
|
520
|
+
validCols.add("id");
|
|
521
|
+
|
|
522
|
+
if (ts) {
|
|
523
|
+
const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
|
|
524
|
+
validCols.add(toSnakeCase(config.createdAt || "createdAt"));
|
|
525
|
+
validCols.add(toSnakeCase(config.updatedAt || "updatedAt"));
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const filteredData: Record<string, any> = {};
|
|
529
|
+
for (const col of Object.keys(flatData)) {
|
|
530
|
+
if (validCols.has(col)) {
|
|
531
|
+
filteredData[col] = flatData[col];
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const coercedData = await this.coerceData(collection, filteredData);
|
|
536
|
+
logger.debug(`[D1] Bulk updating in ${collection}...`);
|
|
537
|
+
try {
|
|
538
|
+
const result = await qb.set(coercedData).executeTakeFirst();
|
|
539
|
+
return Number(result.numUpdatedRows || 0);
|
|
540
|
+
} catch (e: any) {
|
|
541
|
+
logger.error(`[D1] Bulk update failed in ${collection}: ${e.message}`);
|
|
542
|
+
throw e;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return 0;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
override async delete(
|
|
549
|
+
collection: string,
|
|
550
|
+
query: Record<string, unknown> | string | number,
|
|
551
|
+
): Promise<boolean> {
|
|
552
|
+
let normalizedQuery = query;
|
|
553
|
+
if (typeof query !== "object" || query === null) {
|
|
554
|
+
normalizedQuery = { id: query };
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const current = await this.findOne<any>(collection, normalizedQuery as Record<string, unknown>);
|
|
558
|
+
if (!current) return false;
|
|
559
|
+
|
|
560
|
+
const colDef = this._collections.find((c) => c.slug === collection);
|
|
561
|
+
if (colDef) {
|
|
562
|
+
const relationalFields = getRelationalFields(colDef.fields);
|
|
563
|
+
for (const field of relationalFields) {
|
|
564
|
+
if (!field.name) continue;
|
|
565
|
+
const snakeName = toSnakeCase(field.name);
|
|
566
|
+
if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
|
|
567
|
+
const joinTableName = `${collection}_${snakeName}_relations`.toLowerCase();
|
|
568
|
+
try {
|
|
569
|
+
await this._db.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
|
|
570
|
+
} catch (e) {}
|
|
571
|
+
} else if (field.type === "blocks" && "blocks" in field && field.blocks) {
|
|
572
|
+
for (const b of field.blocks) {
|
|
573
|
+
const blockTableName =
|
|
574
|
+
`${collection}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
|
|
575
|
+
try {
|
|
576
|
+
await this._db
|
|
577
|
+
.deleteFrom(blockTableName)
|
|
578
|
+
.where("_parent_id", "=", current.id)
|
|
579
|
+
.execute();
|
|
580
|
+
} catch (e) {}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
await this._db.deleteFrom(collection).where("id", "=", current.id).execute();
|
|
586
|
+
|
|
587
|
+
return true;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
override async deleteMany(collection: string, query: Record<string, unknown>): Promise<number> {
|
|
591
|
+
let selectQb = this._db.selectFrom(collection).select("id");
|
|
592
|
+
if (query && Object.keys(query).length > 0) {
|
|
593
|
+
selectQb = selectQb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
|
|
594
|
+
}
|
|
595
|
+
const docs = await selectQb.execute();
|
|
596
|
+
if (docs.length === 0) return 0;
|
|
597
|
+
|
|
598
|
+
const ids = docs.map((d) => d.id as string);
|
|
599
|
+
const colDef = this._collections.find((c) => c.slug === collection);
|
|
600
|
+
|
|
601
|
+
if (colDef) {
|
|
602
|
+
const relationalFields = getRelationalFields(colDef.fields);
|
|
603
|
+
for (const field of relationalFields) {
|
|
604
|
+
if (!field.name) continue;
|
|
605
|
+
const snakeName = toSnakeCase(field.name);
|
|
606
|
+
if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
|
|
607
|
+
const joinTableName = `${collection}_${snakeName}_relations`.toLowerCase();
|
|
608
|
+
try {
|
|
609
|
+
await this._db.deleteFrom(joinTableName).where("source_id", "in", ids).execute();
|
|
610
|
+
} catch (e) {}
|
|
611
|
+
} else if (field.type === "blocks" && "blocks" in field && field.blocks) {
|
|
612
|
+
for (const b of field.blocks) {
|
|
613
|
+
const blockTableName =
|
|
614
|
+
`${collection}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
|
|
615
|
+
try {
|
|
616
|
+
await this._db.deleteFrom(blockTableName).where("_parent_id", "in", ids).execute();
|
|
617
|
+
} catch (e) {}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
const result = await this._db.deleteFrom(collection).where("id", "in", ids).executeTakeFirst();
|
|
624
|
+
return Number(result.numDeletedRows || 0);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
override async findGlobal<T extends object>(slug: string): Promise<T | null> {
|
|
628
|
+
const row = await this._db
|
|
629
|
+
.selectFrom(slug as any)
|
|
630
|
+
.selectAll()
|
|
631
|
+
.limit(1)
|
|
632
|
+
.executeTakeFirst();
|
|
633
|
+
return row ? (unflattenRow(row) as T) : null;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
override async updateGlobal<T extends object>(slug: string, data: Partial<T>): Promise<T> {
|
|
637
|
+
const existing = await this.findGlobal<any>(slug);
|
|
638
|
+
const flatData = flattenPayload(data);
|
|
639
|
+
|
|
640
|
+
const globalDef = this._globals.find((g) => g.slug === slug);
|
|
641
|
+
const ts = globalDef?.timestamps !== false;
|
|
642
|
+
if (ts) {
|
|
643
|
+
const config = typeof globalDef?.timestamps === "object" ? globalDef.timestamps : {};
|
|
644
|
+
const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
|
|
645
|
+
flatData[updatedField] = new Date().toISOString();
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
if (!existing) {
|
|
649
|
+
if (!flatData.id) flatData.id = "global";
|
|
650
|
+
if (ts) {
|
|
651
|
+
const config = typeof globalDef?.timestamps === "object" ? globalDef.timestamps : {};
|
|
652
|
+
const createdField = toSnakeCase(config.createdAt || "createdAt");
|
|
653
|
+
if (!flatData[createdField])
|
|
654
|
+
flatData[createdField] = flatData[toSnakeCase(config.updatedAt || "updatedAt")];
|
|
655
|
+
}
|
|
656
|
+
await this._db
|
|
657
|
+
.insertInto(slug as any)
|
|
658
|
+
.values(flatData)
|
|
659
|
+
.execute();
|
|
660
|
+
} else {
|
|
661
|
+
await this._db
|
|
662
|
+
.updateTable(slug as any)
|
|
663
|
+
.set(flatData)
|
|
664
|
+
.where("id", "=", (existing as any).id)
|
|
665
|
+
.execute();
|
|
666
|
+
}
|
|
667
|
+
return this.findGlobal<T>(slug) as Promise<T>;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
override async runMigrations(): Promise<void> {
|
|
671
|
+
const migrator = new Migrator({
|
|
672
|
+
db: this._db,
|
|
673
|
+
provider: new FileMigrationProvider({
|
|
674
|
+
fs,
|
|
675
|
+
path,
|
|
676
|
+
migrationFolder: path.resolve(process.cwd(), this.migrationDir),
|
|
677
|
+
}),
|
|
678
|
+
});
|
|
679
|
+
|
|
680
|
+
const { error, results } = await migrator.migrateToLatest();
|
|
681
|
+
|
|
682
|
+
results?.forEach((it) => {
|
|
683
|
+
if (it.status === "Success") {
|
|
684
|
+
logger.success(`🚀 Migration "${it.migrationName}" was executed successfully`);
|
|
685
|
+
} else if (it.status === "Error") {
|
|
686
|
+
logger.error(`❌ Migration "${it.migrationName}" failed`);
|
|
687
|
+
}
|
|
688
|
+
});
|
|
689
|
+
|
|
690
|
+
if (error) {
|
|
691
|
+
throw error;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
override async migrate(collections: Collection[], globals: Global[] = []): Promise<void> {
|
|
696
|
+
this._collections = collections;
|
|
697
|
+
this._globals = globals;
|
|
698
|
+
if (this.push) {
|
|
699
|
+
await pushSchema(this._db, "d1", collections, globals, {
|
|
700
|
+
pushDestructive: this.pushDestructive,
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
export function createD1Adapter(
|
|
707
|
+
db: D1Database,
|
|
708
|
+
options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
|
|
709
|
+
): D1Adapter {
|
|
710
|
+
return new D1Adapter(db, options);
|
|
711
|
+
}
|