create-pet-adopt 0.0.0 → 0.3.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/LICENSE +21 -0
- package/README.md +120 -0
- package/index.js +920 -0
- package/package.json +43 -1
- package/template/.env.example +136 -0
- package/template/.pet-adopt/template.json +581 -0
- package/template/LICENSE +21 -0
- package/template/README.md +109 -0
- package/template/_gitignore +28 -0
- package/template/_pnpm-lock.yaml +9251 -0
- package/template/assets/sample-pet.png +0 -0
- package/template/components.json +25 -0
- package/template/docker-compose.yml +110 -0
- package/template/drizzle/pg/0000_initial.sql +176 -0
- package/template/drizzle/pg/0001_greedy_the_renegades.sql +1 -0
- package/template/drizzle/pg/0002_fuzzy_the_renegades.sql +1 -0
- package/template/drizzle/pg/0003_thin_multiple_man.sql +1 -0
- package/template/drizzle/pg/0004_boring_norman_osborn.sql +15 -0
- package/template/drizzle/pg/0005_bitter_proemial_gods.sql +3 -0
- package/template/drizzle/pg/0006_friendly_black_knight.sql +2 -0
- package/template/drizzle/pg/0007_wise_ozymandias.sql +11 -0
- package/template/drizzle/pg/0008_messy_human_fly.sql +2 -0
- package/template/drizzle/pg/0009_amused_lady_bullseye.sql +1 -0
- package/template/drizzle/pg/0010_cute_mauler.sql +7 -0
- package/template/drizzle/pg/0011_clear_purple_man.sql +3 -0
- package/template/drizzle/pg/0012_tiresome_gunslinger.sql +2 -0
- package/template/drizzle/pg/0013_awesome_wong.sql +18 -0
- package/template/drizzle/pg/0014_fantastic_sumo.sql +12 -0
- package/template/drizzle/pg/0015_pink_carnage.sql +12 -0
- package/template/drizzle/pg/0016_sloppy_king_bedlam.sql +2 -0
- package/template/drizzle/pg/0017_steep_warhawk.sql +15 -0
- package/template/drizzle/pg/0018_mixed_otto_octavius.sql +4 -0
- package/template/drizzle/pg/0019_talented_rocket_raccoon.sql +1 -0
- package/template/drizzle/pg/0020_worthless_zodiak.sql +19 -0
- package/template/drizzle/pg/0021_adorable_squadron_supreme.sql +1 -0
- package/template/drizzle/pg/0022_soft_pixie.sql +5 -0
- package/template/drizzle/pg/0023_fluffy_quasar.sql +1 -0
- package/template/drizzle/pg/0024_uneven_ken_ellis.sql +2 -0
- package/template/drizzle/pg/0025_rich_white_queen.sql +3 -0
- package/template/drizzle/pg/0026_spooky_komodo.sql +16 -0
- package/template/drizzle/pg/0027_big_thunderbolts.sql +2 -0
- package/template/drizzle/pg/meta/0000_snapshot.json +1265 -0
- package/template/drizzle/pg/meta/0001_snapshot.json +1272 -0
- package/template/drizzle/pg/meta/0002_snapshot.json +1278 -0
- package/template/drizzle/pg/meta/0003_snapshot.json +1284 -0
- package/template/drizzle/pg/meta/0004_snapshot.json +1401 -0
- package/template/drizzle/pg/meta/0005_snapshot.json +1401 -0
- package/template/drizzle/pg/meta/0006_snapshot.json +1414 -0
- package/template/drizzle/pg/meta/0007_snapshot.json +1485 -0
- package/template/drizzle/pg/meta/0008_snapshot.json +1504 -0
- package/template/drizzle/pg/meta/0009_snapshot.json +1510 -0
- package/template/drizzle/pg/meta/0010_snapshot.json +1556 -0
- package/template/drizzle/pg/meta/0011_snapshot.json +1574 -0
- package/template/drizzle/pg/meta/0012_snapshot.json +1586 -0
- package/template/drizzle/pg/meta/0013_snapshot.json +1730 -0
- package/template/drizzle/pg/meta/0014_snapshot.json +1805 -0
- package/template/drizzle/pg/meta/0015_snapshot.json +1883 -0
- package/template/drizzle/pg/meta/0016_snapshot.json +1897 -0
- package/template/drizzle/pg/meta/0017_snapshot.json +2013 -0
- package/template/drizzle/pg/meta/0018_snapshot.json +1988 -0
- package/template/drizzle/pg/meta/0019_snapshot.json +1994 -0
- package/template/drizzle/pg/meta/0020_snapshot.json +2108 -0
- package/template/drizzle/pg/meta/0021_snapshot.json +2114 -0
- package/template/drizzle/pg/meta/0022_snapshot.json +2126 -0
- package/template/drizzle/pg/meta/0023_snapshot.json +2132 -0
- package/template/drizzle/pg/meta/0024_snapshot.json +2151 -0
- package/template/drizzle/pg/meta/0025_snapshot.json +2169 -0
- package/template/drizzle/pg/meta/0026_snapshot.json +2294 -0
- package/template/drizzle/pg/meta/0027_snapshot.json +2330 -0
- package/template/drizzle/pg/meta/_journal.json +202 -0
- package/template/drizzle/sqlite/0000_initial.sql +176 -0
- package/template/drizzle/sqlite/0001_easy_sebastian_shaw.sql +1 -0
- package/template/drizzle/sqlite/0002_past_king_cobra.sql +1 -0
- package/template/drizzle/sqlite/0003_organic_masked_marvel.sql +1 -0
- package/template/drizzle/sqlite/0004_panoramic_inhumans.sql +15 -0
- package/template/drizzle/sqlite/0005_small_sunset_bain.sql +19 -0
- package/template/drizzle/sqlite/0006_narrow_medusa.sql +2 -0
- package/template/drizzle/sqlite/0007_gray_grandmaster.sql +10 -0
- package/template/drizzle/sqlite/0008_chief_toxin.sql +1 -0
- package/template/drizzle/sqlite/0009_vengeful_tag.sql +1 -0
- package/template/drizzle/sqlite/0010_kind_klaw.sql +7 -0
- package/template/drizzle/sqlite/0011_overrated_meltdown.sql +3 -0
- package/template/drizzle/sqlite/0012_robust_next_avengers.sql +2 -0
- package/template/drizzle/sqlite/0013_melodic_kitty_pryde.sql +18 -0
- package/template/drizzle/sqlite/0014_stormy_cyclops.sql +12 -0
- package/template/drizzle/sqlite/0015_parallel_mongu.sql +11 -0
- package/template/drizzle/sqlite/0016_grey_quicksilver.sql +2 -0
- package/template/drizzle/sqlite/0017_daily_psylocke.sql +15 -0
- package/template/drizzle/sqlite/0018_whole_redwing.sql +4 -0
- package/template/drizzle/sqlite/0019_spotty_mandroid.sql +1 -0
- package/template/drizzle/sqlite/0020_wild_wendell_rand.sql +19 -0
- package/template/drizzle/sqlite/0021_calm_lockheed.sql +1 -0
- package/template/drizzle/sqlite/0022_lonely_emma_frost.sql +5 -0
- package/template/drizzle/sqlite/0023_elite_tony_stark.sql +1 -0
- package/template/drizzle/sqlite/0024_little_lily_hollister.sql +1 -0
- package/template/drizzle/sqlite/0025_tough_shotgun.sql +3 -0
- package/template/drizzle/sqlite/0026_faithful_mephistopheles.sql +16 -0
- package/template/drizzle/sqlite/0027_rapid_arclight.sql +2 -0
- package/template/drizzle/sqlite/meta/0000_snapshot.json +1237 -0
- package/template/drizzle/sqlite/meta/0001_snapshot.json +1245 -0
- package/template/drizzle/sqlite/meta/0002_snapshot.json +1252 -0
- package/template/drizzle/sqlite/meta/0003_snapshot.json +1259 -0
- package/template/drizzle/sqlite/meta/0004_snapshot.json +1369 -0
- package/template/drizzle/sqlite/meta/0005_snapshot.json +1369 -0
- package/template/drizzle/sqlite/meta/0006_snapshot.json +1384 -0
- package/template/drizzle/sqlite/meta/0007_snapshot.json +1459 -0
- package/template/drizzle/sqlite/meta/0008_snapshot.json +1479 -0
- package/template/drizzle/sqlite/meta/0009_snapshot.json +1486 -0
- package/template/drizzle/sqlite/meta/0010_snapshot.json +1533 -0
- package/template/drizzle/sqlite/meta/0011_snapshot.json +1554 -0
- package/template/drizzle/sqlite/meta/0012_snapshot.json +1568 -0
- package/template/drizzle/sqlite/meta/0013_snapshot.json +1687 -0
- package/template/drizzle/sqlite/meta/0014_snapshot.json +1769 -0
- package/template/drizzle/sqlite/meta/0015_snapshot.json +1852 -0
- package/template/drizzle/sqlite/meta/0016_snapshot.json +1867 -0
- package/template/drizzle/sqlite/meta/0017_snapshot.json +1973 -0
- package/template/drizzle/sqlite/meta/0018_snapshot.json +1944 -0
- package/template/drizzle/sqlite/meta/0019_snapshot.json +1951 -0
- package/template/drizzle/sqlite/meta/0020_snapshot.json +2077 -0
- package/template/drizzle/sqlite/meta/0021_snapshot.json +2084 -0
- package/template/drizzle/sqlite/meta/0022_snapshot.json +2098 -0
- package/template/drizzle/sqlite/meta/0023_snapshot.json +2105 -0
- package/template/drizzle/sqlite/meta/0024_snapshot.json +2125 -0
- package/template/drizzle/sqlite/meta/0025_snapshot.json +2146 -0
- package/template/drizzle/sqlite/meta/0026_snapshot.json +2265 -0
- package/template/drizzle/sqlite/meta/0027_snapshot.json +2280 -0
- package/template/drizzle/sqlite/meta/_journal.json +202 -0
- package/template/drizzle.pg.config.ts +8 -0
- package/template/drizzle.sqlite.config.ts +8 -0
- package/template/eslint.config.mjs +22 -0
- package/template/next.config.ts +153 -0
- package/template/package.json +102 -0
- package/template/pet-adopt.blocks.ts +9 -0
- package/template/pet-adopt.config.ts +17 -0
- package/template/pnpm-workspace.yaml +19 -0
- package/template/postcss.config.mjs +5 -0
- package/template/scripts/check-routes.ts +405 -0
- package/template/scripts/check-schemas.ts +58 -0
- package/template/scripts/migrate-all.ts +25 -0
- package/template/scripts/migrate-on-build.ts +71 -0
- package/template/scripts/migrate.ts +20 -0
- package/template/scripts/plugin-generate.ts +92 -0
- package/template/scripts/reset-password.ts +45 -0
- package/template/scripts/reset-two-factor.ts +53 -0
- package/template/scripts/seed.ts +79 -0
- package/template/scripts/setup-env.ts +91 -0
- package/template/scripts/storage-check.ts +53 -0
- package/template/src/app/(admin)/admin/account/AccountForms.tsx +194 -0
- package/template/src/app/(admin)/admin/account/page.tsx +59 -0
- package/template/src/app/(admin)/admin/activity/page.tsx +76 -0
- package/template/src/app/(admin)/admin/authentication/archived/page.tsx +24 -0
- package/template/src/app/(admin)/admin/authentication/layout.tsx +20 -0
- package/template/src/app/(admin)/admin/authentication/page.tsx +36 -0
- package/template/src/app/(admin)/admin/authentication/providers/page.tsx +33 -0
- package/template/src/app/(admin)/admin/email/layout.tsx +21 -0
- package/template/src/app/(admin)/admin/email/page.tsx +43 -0
- package/template/src/app/(admin)/admin/email/templates/page.tsx +38 -0
- package/template/src/app/(admin)/admin/error.tsx +36 -0
- package/template/src/app/(admin)/admin/layout.tsx +26 -0
- package/template/src/app/(admin)/admin/loading.tsx +9 -0
- package/template/src/app/(admin)/admin/media/[id]/page.tsx +97 -0
- package/template/src/app/(admin)/admin/media/page.tsx +34 -0
- package/template/src/app/(admin)/admin/media/search-params.ts +16 -0
- package/template/src/app/(admin)/admin/page.tsx +79 -0
- package/template/src/app/(admin)/admin/pages/PageForm.tsx +604 -0
- package/template/src/app/(admin)/admin/pages/[id]/page.tsx +51 -0
- package/template/src/app/(admin)/admin/pages/new/page.tsx +19 -0
- package/template/src/app/(admin)/admin/pages/page.tsx +49 -0
- package/template/src/app/(admin)/admin/pets/PetForm.tsx +437 -0
- package/template/src/app/(admin)/admin/pets/[id]/page.tsx +41 -0
- package/template/src/app/(admin)/admin/pets/new/page.tsx +26 -0
- package/template/src/app/(admin)/admin/pets/page.tsx +70 -0
- package/template/src/app/(admin)/admin/pets/search-params.ts +16 -0
- package/template/src/app/(admin)/admin/plugins/[plugin]/[[...path]]/page.tsx +73 -0
- package/template/src/app/(admin)/admin/plugins/page.tsx +66 -0
- package/template/src/app/(admin)/admin/settings/SettingsForm.tsx +644 -0
- package/template/src/app/(admin)/admin/settings/email/page.tsx +9 -0
- package/template/src/app/(admin)/admin/settings/page.tsx +40 -0
- package/template/src/app/(admin)/admin/settings/templates/page.tsx +9 -0
- package/template/src/app/(admin)/admin/theme/[id]/page.tsx +28 -0
- package/template/src/app/(admin)/admin/theme/page.tsx +30 -0
- package/template/src/app/(admin)/admin/users/page.tsx +33 -0
- package/template/src/app/(admin)/layout.tsx +75 -0
- package/template/src/app/(admin)/providers.tsx +42 -0
- package/template/src/app/(auth)/admin/confirm-email/page.tsx +40 -0
- package/template/src/app/(auth)/admin/invite/page.tsx +38 -0
- package/template/src/app/(auth)/admin/login/DemoSignIn.tsx +69 -0
- package/template/src/app/(auth)/admin/login/page.tsx +83 -0
- package/template/src/app/(auth)/admin/reset-password/page.tsx +73 -0
- package/template/src/app/(auth)/error.tsx +9 -0
- package/template/src/app/(auth)/layout.tsx +71 -0
- package/template/src/app/(editor)/EditorToast.tsx +43 -0
- package/template/src/app/(editor)/edit/[id]/PageEditor.tsx +586 -0
- package/template/src/app/(editor)/edit/[id]/actions.ts +139 -0
- package/template/src/app/(editor)/edit/[id]/page.tsx +76 -0
- package/template/src/app/(editor)/edit/[id]/preview/page.tsx +81 -0
- package/template/src/app/(editor)/edit/email/[id]/EmailEditor.tsx +236 -0
- package/template/src/app/(editor)/edit/email/[id]/page.tsx +64 -0
- package/template/src/app/(editor)/edit/theme-preview/page.tsx +94 -0
- package/template/src/app/(editor)/editor.css +223 -0
- package/template/src/app/(editor)/error.tsx +32 -0
- package/template/src/app/(editor)/layout.tsx +67 -0
- package/template/src/app/(frontend)/[slug]/page.tsx +53 -0
- package/template/src/app/(frontend)/fonts.ts +8 -0
- package/template/src/app/(frontend)/layout.tsx +107 -0
- package/template/src/app/(frontend)/not-found.tsx +16 -0
- package/template/src/app/(frontend)/page.tsx +42 -0
- package/template/src/app/(frontend)/pets/[slug]/page.tsx +92 -0
- package/template/src/app/(frontend)/pets/page.tsx +42 -0
- package/template/src/app/(frontend)/styles.css +537 -0
- package/template/src/app/(setup)/error.tsx +9 -0
- package/template/src/app/(setup)/layout.tsx +41 -0
- package/template/src/app/(setup)/setup/page.tsx +105 -0
- package/template/src/app/(setup)/setup/storage-check.ts +43 -0
- package/template/src/app/api/auth/[...all]/route.ts +144 -0
- package/template/src/app/health/route.ts +9 -0
- package/template/src/app/media/[...path]/route.ts +45 -0
- package/template/src/app/media/email/[name]/route.ts +60 -0
- package/template/src/app/robots.ts +19 -0
- package/template/src/app/sitemap.ts +24 -0
- package/template/src/components/admin/AdminNav.tsx +153 -0
- package/template/src/components/admin/AdminShell.tsx +107 -0
- package/template/src/components/admin/DemoNotice.tsx +31 -0
- package/template/src/components/admin/EmailConfirmBanner.tsx +44 -0
- package/template/src/components/admin/EmptyState.tsx +10 -0
- package/template/src/components/admin/ErrorSummary.tsx +72 -0
- package/template/src/components/admin/MediaDetails.tsx +218 -0
- package/template/src/components/admin/MediaGrid.tsx +307 -0
- package/template/src/components/admin/MediaLibrary.tsx +103 -0
- package/template/src/components/admin/MediaPager.tsx +66 -0
- package/template/src/components/admin/PageHeader.tsx +22 -0
- package/template/src/components/admin/PhoneInput.tsx +128 -0
- package/template/src/components/admin/PluginWidgetBoundary.tsx +38 -0
- package/template/src/components/admin/PluginWidgets.tsx +51 -0
- package/template/src/components/admin/RemountOnNavigate.tsx +37 -0
- package/template/src/components/admin/StatusBadge.tsx +16 -0
- package/template/src/components/admin/UploadPhotosDialog.tsx +387 -0
- package/template/src/components/admin/UserAvatar.tsx +18 -0
- package/template/src/components/admin/UserMenu.tsx +118 -0
- package/template/src/components/admin/ViewSiteLink.tsx +24 -0
- package/template/src/components/admin/account/ConnectedProviders.tsx +91 -0
- package/template/src/components/admin/account/DeleteAccountCard.tsx +136 -0
- package/template/src/components/admin/account/EmailCard.tsx +137 -0
- package/template/src/components/admin/account/ProfilePicture.tsx +159 -0
- package/template/src/components/admin/activity/ActivityFilters.tsx +146 -0
- package/template/src/components/admin/activity/ActivityLog.tsx +159 -0
- package/template/src/components/admin/activity/RecentActivity.tsx +52 -0
- package/template/src/components/admin/demo-mode.tsx +17 -0
- package/template/src/components/admin/nav-items.ts +47 -0
- package/template/src/components/admin/pages/PageDetails.tsx +198 -0
- package/template/src/components/admin/pages/PageVersions.tsx +296 -0
- package/template/src/components/admin/pages/PagesTable.tsx +467 -0
- package/template/src/components/admin/pets/FilterBar.tsx +154 -0
- package/template/src/components/admin/pets/PetCard.tsx +170 -0
- package/template/src/components/admin/pets/PetList.tsx +112 -0
- package/template/src/components/admin/pets/PetListSkeleton.tsx +84 -0
- package/template/src/components/admin/pets/PetPagination.tsx +91 -0
- package/template/src/components/admin/pets/form/AgeFields.tsx +132 -0
- package/template/src/components/admin/pets/form/LocationFields.tsx +231 -0
- package/template/src/components/admin/pets/form/MediaPickerDialog.tsx +359 -0
- package/template/src/components/admin/pets/form/PhotosField.tsx +176 -0
- package/template/src/components/admin/pets/form/RichTextField.tsx +438 -0
- package/template/src/components/admin/pets/form/SeoImageField.tsx +87 -0
- package/template/src/components/admin/pets/form/SeoPreview.tsx +142 -0
- package/template/src/components/admin/pets/form/fields.tsx +434 -0
- package/template/src/components/admin/pets/form/rich-text-extensions.ts +45 -0
- package/template/src/components/admin/pets/timeline/PetTimeline.tsx +297 -0
- package/template/src/components/admin/pets/timeline/TimelineEntryForm.tsx +289 -0
- package/template/src/components/admin/pets/timeline/TimelinePhotosField.tsx +173 -0
- package/template/src/components/admin/plugins/PluginNotReady.tsx +28 -0
- package/template/src/components/admin/plugins/PluginOverview.tsx +121 -0
- package/template/src/components/admin/plugins/SendTestEmail.tsx +70 -0
- package/template/src/components/admin/settings/AuthProviders.tsx +373 -0
- package/template/src/components/admin/settings/AuthenticationNav.tsx +42 -0
- package/template/src/components/admin/settings/EmailNav.tsx +40 -0
- package/template/src/components/admin/settings/EmailSettingsForm.tsx +325 -0
- package/template/src/components/admin/settings/EmailTemplates.tsx +551 -0
- package/template/src/components/admin/settings/RegionFields.tsx +203 -0
- package/template/src/components/admin/site-time.tsx +26 -0
- package/template/src/components/admin/theme/ThemeEditor.tsx +467 -0
- package/template/src/components/admin/theme/ThemeLibrary.tsx +339 -0
- package/template/src/components/admin/theme/ThemeSwatches.tsx +30 -0
- package/template/src/components/admin/theme/theme-utils.ts +32 -0
- package/template/src/components/admin/two-factor/BackupCodeList.tsx +54 -0
- package/template/src/components/admin/two-factor/TwoFactorCard.tsx +237 -0
- package/template/src/components/admin/two-factor/TwoFactorRequired.tsx +52 -0
- package/template/src/components/admin/two-factor/TwoFactorSetup.tsx +180 -0
- package/template/src/components/admin/use-unsaved-changes.tsx +101 -0
- package/template/src/components/admin/users/ArchivedAccounts.tsx +159 -0
- package/template/src/components/admin/users/InviteDialogs.tsx +131 -0
- package/template/src/components/admin/users/TwoFactorRoles.tsx +80 -0
- package/template/src/components/admin/users/UserDialogs.tsx +681 -0
- package/template/src/components/admin/users/UsersTable.tsx +374 -0
- package/template/src/components/admin/view-only.tsx +43 -0
- package/template/src/components/auth/AcceptInviteForm.tsx +123 -0
- package/template/src/components/auth/AuthNav.tsx +80 -0
- package/template/src/components/auth/ConfirmEmailForm.tsx +73 -0
- package/template/src/components/auth/LoginForm.tsx +250 -0
- package/template/src/components/auth/PageError.tsx +37 -0
- package/template/src/components/auth/ProviderSignIn.tsx +53 -0
- package/template/src/components/auth/ResetPasswordForm.tsx +267 -0
- package/template/src/components/demo/DemoBanner.tsx +38 -0
- package/template/src/components/demo/SiteDemoBanner.tsx +22 -0
- package/template/src/components/demo/wording.ts +21 -0
- package/template/src/components/setup/SetupAccountForm.tsx +93 -0
- package/template/src/components/setup/SetupDone.tsx +95 -0
- package/template/src/components/setup/SetupNav.tsx +49 -0
- package/template/src/components/setup/SetupSampleContent.tsx +67 -0
- package/template/src/components/setup/SetupSiteForm.tsx +104 -0
- package/template/src/components/setup/SetupThemePicker.tsx +73 -0
- package/template/src/components/setup/SkipSetup.tsx +35 -0
- package/template/src/components/site/BuilderContent.tsx +46 -0
- package/template/src/components/site/CopyButton.tsx +28 -0
- package/template/src/components/site/ImageCarousel.tsx +52 -0
- package/template/src/components/site/PetCard.tsx +32 -0
- package/template/src/components/site/PetCatalog.tsx +106 -0
- package/template/src/components/site/PetGallery.tsx +75 -0
- package/template/src/components/site/PetTimeline.tsx +82 -0
- package/template/src/components/site/RemountOnNavigate.tsx +13 -0
- package/template/src/components/site/RichText.tsx +56 -0
- package/template/src/components/site/SmartLink.tsx +37 -0
- package/template/src/components/site/SocialIcons.tsx +26 -0
- package/template/src/components/site/ThemePreviewBridge.tsx +29 -0
- package/template/src/components/site/ThemeStyle.tsx +22 -0
- package/template/src/components/site/ThemeToggle.tsx +36 -0
- package/template/src/components/site/WhatsAppButton.tsx +27 -0
- package/template/src/components/site/timeline-format.ts +20 -0
- package/template/src/db/client.ts +702 -0
- package/template/src/db/compare-tables.ts +41 -0
- package/template/src/db/migrate.ts +28 -0
- package/template/src/db/plugin-migrations.ts +167 -0
- package/template/src/db/schema/pg.ts +484 -0
- package/template/src/db/schema/sqlite.ts +492 -0
- package/template/src/instrumentation.ts +110 -0
- package/template/src/lib/activity.ts +29 -0
- package/template/src/lib/admin/call-action.ts +19 -0
- package/template/src/lib/admin/initials.ts +9 -0
- package/template/src/lib/admin/media-cache.ts +16 -0
- package/template/src/lib/admin/media-page.ts +3 -0
- package/template/src/lib/admin/pet-form.ts +242 -0
- package/template/src/lib/admin/pets-cache.ts +22 -0
- package/template/src/lib/admin/unwrap-client.ts +11 -0
- package/template/src/lib/admin/unwrap.ts +38 -0
- package/template/src/lib/admin/use-media-list.ts +41 -0
- package/template/src/lib/admin/use-pet-list.ts +58 -0
- package/template/src/lib/age.ts +117 -0
- package/template/src/lib/auth-provider-errors.ts +38 -0
- package/template/src/lib/cache.ts +69 -0
- package/template/src/lib/color-mode.ts +48 -0
- package/template/src/lib/demo.ts +78 -0
- package/template/src/lib/email-address.ts +9 -0
- package/template/src/lib/email-template.ts +691 -0
- package/template/src/lib/links.ts +78 -0
- package/template/src/lib/mail-error.ts +38 -0
- package/template/src/lib/media-name.ts +31 -0
- package/template/src/lib/options.ts +134 -0
- package/template/src/lib/pagination.ts +28 -0
- package/template/src/lib/pet-placeholders.ts +34 -0
- package/template/src/lib/pet-seo.ts +40 -0
- package/template/src/lib/pet-timeline.ts +62 -0
- package/template/src/lib/phone.ts +129 -0
- package/template/src/lib/places.ts +84 -0
- package/template/src/lib/queries.ts +549 -0
- package/template/src/lib/revalidate.ts +32 -0
- package/template/src/lib/rich-text.ts +215 -0
- package/template/src/lib/seo.ts +121 -0
- package/template/src/lib/slugify.ts +11 -0
- package/template/src/lib/theme.ts +546 -0
- package/template/src/lib/utils.ts +2 -0
- package/template/src/lib/whatsapp.ts +29 -0
- package/template/src/lib/zod-schema/auth.ts +56 -0
- package/template/src/lib/zod-schema/page.ts +57 -0
- package/template/src/lib/zod-schema/pet-timeline.ts +118 -0
- package/template/src/lib/zod-schema/pet.ts +172 -0
- package/template/src/lib/zod-schema/settings.ts +162 -0
- package/template/src/plugins/host.ts +117 -0
- package/template/src/plugins/icon.ts +89 -0
- package/template/src/plugins/registry.ts +369 -0
- package/template/src/plugins/storage-rules.ts +87 -0
- package/template/src/plugins/storage.ts +184 -0
- package/template/src/puck/actions.ts +46 -0
- package/template/src/puck/config.tsx +1693 -0
- package/template/src/puck/data.ts +196 -0
- package/template/src/puck/demo-mode.tsx +20 -0
- package/template/src/puck/email-config.tsx +267 -0
- package/template/src/puck/icons.tsx +76 -0
- package/template/src/puck/media-picker.tsx +273 -0
- package/template/src/puck/padding.tsx +71 -0
- package/template/src/puck/pet-page-config.tsx +511 -0
- package/template/src/puck/pet-picker.tsx +40 -0
- package/template/src/puck/plugin-block-data.ts +91 -0
- package/template/src/puck/plugin-blocks.tsx +235 -0
- package/template/src/puck/plugin-choice-field.tsx +87 -0
- package/template/src/puck/sanitize.ts +107 -0
- package/template/src/puck/server.ts +36 -0
- package/template/src/puck/types.ts +41 -0
- package/template/src/server/actions/activity.ts +48 -0
- package/template/src/server/actions/auth-providers.ts +171 -0
- package/template/src/server/actions/auth.ts +217 -0
- package/template/src/server/actions/demo.ts +30 -0
- package/template/src/server/actions/email-change.ts +80 -0
- package/template/src/server/actions/email-templates.ts +144 -0
- package/template/src/server/actions/email.ts +70 -0
- package/template/src/server/actions/media.ts +127 -0
- package/template/src/server/actions/pages.ts +159 -0
- package/template/src/server/actions/password-reset.ts +80 -0
- package/template/src/server/actions/pet-timeline.ts +75 -0
- package/template/src/server/actions/pets.ts +74 -0
- package/template/src/server/actions/places.ts +36 -0
- package/template/src/server/actions/settings.ts +29 -0
- package/template/src/server/actions/setup.ts +72 -0
- package/template/src/server/actions/themes.ts +80 -0
- package/template/src/server/actions/two-factor.ts +306 -0
- package/template/src/server/actions/users.ts +200 -0
- package/template/src/server/activity.ts +409 -0
- package/template/src/server/auth-errors.ts +17 -0
- package/template/src/server/auth-providers.ts +359 -0
- package/template/src/server/auth.ts +266 -0
- package/template/src/server/avatars.ts +263 -0
- package/template/src/server/demo-site.ts +169 -0
- package/template/src/server/email-change.ts +278 -0
- package/template/src/server/email-templates.ts +350 -0
- package/template/src/server/email.ts +442 -0
- package/template/src/server/invites.ts +143 -0
- package/template/src/server/media-url.ts +20 -0
- package/template/src/server/media.ts +236 -0
- package/template/src/server/pages.ts +812 -0
- package/template/src/server/password-reset.ts +158 -0
- package/template/src/server/pending-links.ts +46 -0
- package/template/src/server/pet-timeline.ts +181 -0
- package/template/src/server/pets.ts +555 -0
- package/template/src/server/places.ts +113 -0
- package/template/src/server/privacy.ts +21 -0
- package/template/src/server/provider-endpoints.ts +94 -0
- package/template/src/server/provider-guard.ts +157 -0
- package/template/src/server/result.ts +280 -0
- package/template/src/server/sample-content.ts +368 -0
- package/template/src/server/search-text.ts +43 -0
- package/template/src/server/secret-box.ts +38 -0
- package/template/src/server/session.ts +154 -0
- package/template/src/server/settings.ts +361 -0
- package/template/src/server/setup.ts +110 -0
- package/template/src/server/sitemap.ts +88 -0
- package/template/src/server/storage.ts +267 -0
- package/template/src/server/strip-metadata.ts +357 -0
- package/template/src/server/themes.ts +195 -0
- package/template/src/server/throttle.ts +258 -0
- package/template/src/server/two-factor-codes.ts +32 -0
- package/template/src/server/two-factor.ts +158 -0
- package/template/src/server/types.ts +198 -0
- package/template/src/server/uploads.ts +137 -0
- package/template/src/server/users.ts +500 -0
- package/template/tsconfig.json +44 -0
- package/template/ui/components.json +25 -0
- package/template/ui/package.json +12 -0
- package/template/ui/src/components/alert-dialog.tsx +187 -0
- package/template/ui/src/components/avatar.tsx +108 -0
- package/template/ui/src/components/badge.tsx +51 -0
- package/template/ui/src/components/button.tsx +57 -0
- package/template/ui/src/components/card.tsx +102 -0
- package/template/ui/src/components/carousel.tsx +245 -0
- package/template/ui/src/components/checkbox.tsx +27 -0
- package/template/ui/src/components/combobox.tsx +297 -0
- package/template/ui/src/components/dialog.tsx +159 -0
- package/template/ui/src/components/dropdown-menu.tsx +265 -0
- package/template/ui/src/components/field.tsx +238 -0
- package/template/ui/src/components/input-group.tsx +158 -0
- package/template/ui/src/components/input.tsx +19 -0
- package/template/ui/src/components/label.tsx +19 -0
- package/template/ui/src/components/pagination.tsx +127 -0
- package/template/ui/src/components/popover.tsx +89 -0
- package/template/ui/src/components/radio-group.tsx +37 -0
- package/template/ui/src/components/select.tsx +200 -0
- package/template/ui/src/components/separator.tsx +24 -0
- package/template/ui/src/components/sheet.tsx +138 -0
- package/template/ui/src/components/sidebar.tsx +723 -0
- package/template/ui/src/components/skeleton.tsx +13 -0
- package/template/ui/src/components/switch.tsx +31 -0
- package/template/ui/src/components/table.tsx +115 -0
- package/template/ui/src/components/tabs.tsx +81 -0
- package/template/ui/src/components/textarea.tsx +17 -0
- package/template/ui/src/components/toggle.tsx +44 -0
- package/template/ui/src/components/tooltip.tsx +65 -0
- package/template/ui/src/hooks/use-mobile.ts +21 -0
- package/template/ui/src/lib/utils.ts +2 -0
- package/template/ui/src/styles/globals.css +145 -0
|
@@ -0,0 +1,702 @@
|
|
|
1
|
+
// The one place that knows which database is in use.
|
|
2
|
+
//
|
|
3
|
+
// DATABASE_URL picks the dialect:
|
|
4
|
+
// postgres://... -> PostgreSQL
|
|
5
|
+
// file:./pet-adopt.db -> SQLite in a local file (zero setup). The default is
|
|
6
|
+
// DEFAULT_SQLITE_URL, in the git-ignored data/ folder.
|
|
7
|
+
// libsql://... -> SQLite hosted by a libSQL server such as Turso (optional; token in
|
|
8
|
+
// DATABASE_AUTH_TOKEN). https:// and http:// (a local `turso dev`) work too.
|
|
9
|
+
// Both SQLite kinds go through @libsql/client, so they share one schema, one set of migrations and
|
|
10
|
+
// the same queries.
|
|
11
|
+
//
|
|
12
|
+
// Drizzle's SQLite and Postgres tables are different TypeScript types, so the repositories are
|
|
13
|
+
// written once against the SQLite-typed objects and this file hands them the right ones at runtime.
|
|
14
|
+
// Both query builders share the same API (select / insert / update / delete / where / returning),
|
|
15
|
+
// and `scripts/check-schemas.ts` plus the dual-database test run guard against the two drifting.
|
|
16
|
+
//
|
|
17
|
+
// Demo mode (PET_ADOPT_DEMO=1, src/lib/demo.ts) ignores DATABASE_URL: each server instance keeps a
|
|
18
|
+
// throwaway SQLite file in the system's temporary folder, filled with the sample content
|
|
19
|
+
// (src/server/demo-site.ts) and made again every DEMO_RESET_MINUTES. See "Demo mode" below.
|
|
20
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
21
|
+
import { randomBytes } from 'node:crypto'
|
|
22
|
+
import { existsSync, mkdirSync, rmSync } from 'node:fs'
|
|
23
|
+
import os from 'node:os'
|
|
24
|
+
import path from 'node:path'
|
|
25
|
+
|
|
26
|
+
import { sql } from 'drizzle-orm'
|
|
27
|
+
import type { Client, InStatement, Transaction } from '@libsql/client'
|
|
28
|
+
import type { LibSQLDatabase } from 'drizzle-orm/libsql'
|
|
29
|
+
|
|
30
|
+
import { demoProblem, demoResetMinutes, isDemo } from '@/lib/demo'
|
|
31
|
+
import { logError } from '@/server/result'
|
|
32
|
+
|
|
33
|
+
import * as pgSchema from './schema/pg'
|
|
34
|
+
import * as sqliteSchema from './schema/sqlite'
|
|
35
|
+
|
|
36
|
+
export type Dialect = 'sqlite' | 'pg'
|
|
37
|
+
export type Schema = typeof sqliteSchema
|
|
38
|
+
/** The type every repository is written against (see the note above). */
|
|
39
|
+
export type Db = LibSQLDatabase<Schema>
|
|
40
|
+
|
|
41
|
+
export type TransactionOptions = {
|
|
42
|
+
/**
|
|
43
|
+
* Serialises transactions that use the same name, across processes (PostgreSQL advisory lock).
|
|
44
|
+
* Use it when a rule spans several rows, like "never remove the last admin": without it two
|
|
45
|
+
* transactions can each see the other's row, both pass the check, and both commit. SQLite
|
|
46
|
+
* transactions already run one at a time (see openSqlite), so it ignores this.
|
|
47
|
+
*/
|
|
48
|
+
lock?: string
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type Database = {
|
|
52
|
+
dialect: Dialect
|
|
53
|
+
/**
|
|
54
|
+
* True for a local SQLite file: its migrations (the site's and plugins') run when it is opened.
|
|
55
|
+
* PostgreSQL and hosted libSQL are shared by every server instance, so they need `pnpm migrate`.
|
|
56
|
+
*/
|
|
57
|
+
migratesOnOpen: boolean
|
|
58
|
+
db: Db
|
|
59
|
+
/** The tables for this dialect. */
|
|
60
|
+
t: Schema
|
|
61
|
+
/**
|
|
62
|
+
* Runs `fn` atomically. Everything inside should use the `tx` it is given. A transaction started
|
|
63
|
+
* inside another one joins it.
|
|
64
|
+
*
|
|
65
|
+
* SQLite note: transactions run one at a time per process, and on a local file every other
|
|
66
|
+
* statement waits while one is open. Keep transaction bodies short and free of slow awaits (file
|
|
67
|
+
* or network work belongs outside).
|
|
68
|
+
*/
|
|
69
|
+
withTransaction<T>(fn: (tx: Db) => Promise<T>, options?: TransactionOptions): Promise<T>
|
|
70
|
+
close(): Promise<void>
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Read at runtime from the project folder, so keep Turbopack from tracing the whole project for it.
|
|
74
|
+
const MIGRATIONS_ROOT = path.resolve(/* turbopackIgnore: true */ process.cwd(), 'drizzle')
|
|
75
|
+
export const migrationsFolder = (dialect: Dialect) => path.join(MIGRATIONS_ROOT, dialect)
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Local data lives in a git-ignored data/ folder. The path is relative to the site's folder, which
|
|
79
|
+
* is the working directory for `next` and the scripts.
|
|
80
|
+
*/
|
|
81
|
+
export const DEFAULT_SQLITE_URL = 'file:./data/pet-adopt.db'
|
|
82
|
+
|
|
83
|
+
export function resolveDatabaseUrl(): { dialect: Dialect; url: string } {
|
|
84
|
+
// The demo never reads DATABASE_URL: it refuses to run while one is set, and otherwise uses this
|
|
85
|
+
// instance's throwaway copy (a fresh file per process and per reset).
|
|
86
|
+
if (isDemo()) return { dialect: 'sqlite', url: `file:${demoFile()}` }
|
|
87
|
+
const url = process.env.DATABASE_URL || DEFAULT_SQLITE_URL
|
|
88
|
+
if (/^postgres(ql)?:\/\//.test(url)) return { dialect: 'pg', url }
|
|
89
|
+
if (/^(file:|sqlite:)/.test(url) || isRemoteSqlite(url) || !url.includes('://')) return { dialect: 'sqlite', url }
|
|
90
|
+
throw new Error(`Unsupported DATABASE_URL "${url.split('@').pop()}". Use postgres://..., file:./path.db or libsql://...`)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A libSQL server (Turso, or `turso dev` locally) rather than a file. */
|
|
94
|
+
export const isRemoteSqlite = (url: string) => /^(libsql|https?|wss?):\/\//.test(url)
|
|
95
|
+
|
|
96
|
+
const isBuildPhase = () => process.env.NEXT_PHASE === 'phase-production-build'
|
|
97
|
+
|
|
98
|
+
/** How long a statement waits for another process's write lock, or for this process's open transaction (ms). */
|
|
99
|
+
const BUSY_TIMEOUT_MS = 5000
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A shared/exclusive gate for one local SQLite file. Plain statements share it; a transaction takes
|
|
103
|
+
* it alone. Why: libSQL's local driver is synchronous. If a statement from another request needed
|
|
104
|
+
* the write lock while a transaction held it, it would busy-wait inside native code, blocking the
|
|
105
|
+
* event loop, so the transaction could never reach its COMMIT. Waiting here is asynchronous instead.
|
|
106
|
+
* A waiting transaction goes before new statements, so a steady stream of reads cannot starve it.
|
|
107
|
+
*/
|
|
108
|
+
class Gate {
|
|
109
|
+
private shared = 0
|
|
110
|
+
private exclusive = false
|
|
111
|
+
private exclusiveWaiting = 0
|
|
112
|
+
private waiters: Array<() => void> = []
|
|
113
|
+
|
|
114
|
+
constructor(private readonly timeoutMs: number) {}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Waits for a wake-up, but never past `deadline`. Without a limit, code inside a transaction that
|
|
118
|
+
* awaits a promise another request started (a shared cache, say) would wait for that request,
|
|
119
|
+
* which waits for the transaction: forever. Giving up turns that into an error, as SQLite's own
|
|
120
|
+
* busy timeout does.
|
|
121
|
+
*/
|
|
122
|
+
private wait(deadline: number) {
|
|
123
|
+
return new Promise<void>((resolve, reject) => {
|
|
124
|
+
// performance.now(), never Date.now(): this gate runs for every query, also while Next
|
|
125
|
+
// prerenders a page, and a clock read there is a build error under Cache Components.
|
|
126
|
+
const ms = deadline - performance.now()
|
|
127
|
+
if (ms <= 0) return reject(busyError(this.timeoutMs))
|
|
128
|
+
const wake = () => {
|
|
129
|
+
clearTimeout(timer)
|
|
130
|
+
resolve()
|
|
131
|
+
}
|
|
132
|
+
const timer = setTimeout(() => {
|
|
133
|
+
this.waiters = this.waiters.filter((w) => w !== wake)
|
|
134
|
+
reject(busyError(this.timeoutMs))
|
|
135
|
+
}, ms)
|
|
136
|
+
this.waiters.push(wake)
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private wake() {
|
|
141
|
+
const waiters = this.waiters
|
|
142
|
+
this.waiters = []
|
|
143
|
+
for (const resolve of waiters) resolve()
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async share<T>(fn: () => Promise<T>): Promise<T> {
|
|
147
|
+
// performance.now(), not Date.now(): see wait() (a clock read during a prerender fails the build).
|
|
148
|
+
const deadline = performance.now() + this.timeoutMs
|
|
149
|
+
while (this.exclusive || this.exclusiveWaiting > 0) await this.wait(deadline)
|
|
150
|
+
this.shared++
|
|
151
|
+
try {
|
|
152
|
+
return await fn()
|
|
153
|
+
} finally {
|
|
154
|
+
if (--this.shared === 0) this.wake()
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async alone<T>(fn: () => Promise<T>): Promise<T> {
|
|
159
|
+
// performance.now(), not Date.now(): see wait() (a clock read during a prerender fails the build).
|
|
160
|
+
const deadline = performance.now() + this.timeoutMs
|
|
161
|
+
this.exclusiveWaiting++
|
|
162
|
+
try {
|
|
163
|
+
while (this.exclusive || this.shared > 0) await this.wait(deadline)
|
|
164
|
+
} catch (error) {
|
|
165
|
+
// Gave up: statements held back for this transaction may go now.
|
|
166
|
+
this.exclusiveWaiting--
|
|
167
|
+
this.wake()
|
|
168
|
+
throw error
|
|
169
|
+
}
|
|
170
|
+
this.exclusiveWaiting--
|
|
171
|
+
this.exclusive = true
|
|
172
|
+
try {
|
|
173
|
+
return await fn()
|
|
174
|
+
} finally {
|
|
175
|
+
this.exclusive = false
|
|
176
|
+
this.wake()
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Same code SQLite gives a statement that waited too long for a lock. */
|
|
182
|
+
const busyError = (ms: number) =>
|
|
183
|
+
Object.assign(new Error(`The database is busy: waited ${ms / 1000} s for another transaction to finish.`), { code: 'SQLITE_BUSY' })
|
|
184
|
+
|
|
185
|
+
/** SQLITE_BUSY (or one of its extended codes) on the error or a cause: libSQL sets `code`, and `extendedCode` beside it. */
|
|
186
|
+
function isBusy(error: unknown): boolean {
|
|
187
|
+
let current: unknown = error
|
|
188
|
+
for (let depth = 0; depth < 4 && current && typeof current === 'object'; depth++) {
|
|
189
|
+
const { code, extendedCode, cause } = current as { code?: unknown; extendedCode?: unknown; cause?: unknown }
|
|
190
|
+
if ([code, extendedCode].some((value) => typeof value === 'string' && value.startsWith('SQLITE_BUSY'))) return true
|
|
191
|
+
current = cause
|
|
192
|
+
}
|
|
193
|
+
return false
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Between tries at switching a new file to WAL (ms): the other process needs a few milliseconds. */
|
|
197
|
+
const WAL_RETRY_MS = 25
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Puts a local file in WAL mode, unless it is already. Two processes that create the file at the
|
|
201
|
+
* same moment (the server and `pnpm migrate` on a fresh checkout) both ask for the switch, which
|
|
202
|
+
* needs the file to itself, and SQLite refuses the loser at once with SQLITE_BUSY: it does not wait
|
|
203
|
+
* out the busy timeout here as it does for a statement (the connection has it: `timeout` above).
|
|
204
|
+
* So wait and look again, for as long as a statement would have waited; by then the other process
|
|
205
|
+
* has made the switch and there is nothing left to do. Any other error is thrown as it is; still
|
|
206
|
+
* busy at the end, the first busy error.
|
|
207
|
+
*/
|
|
208
|
+
async function switchToWal(client: Client): Promise<void> {
|
|
209
|
+
const deadline = Date.now() + BUSY_TIMEOUT_MS
|
|
210
|
+
let first: unknown
|
|
211
|
+
for (;;) {
|
|
212
|
+
try {
|
|
213
|
+
const { rows } = await client.execute('PRAGMA journal_mode')
|
|
214
|
+
if (String(Object.values(rows[0] ?? {})[0]).toLowerCase() === 'wal') return
|
|
215
|
+
await client.execute('PRAGMA journal_mode = WAL')
|
|
216
|
+
return
|
|
217
|
+
} catch (error) {
|
|
218
|
+
if (!isBusy(error)) throw error
|
|
219
|
+
first ??= error
|
|
220
|
+
if (Date.now() >= deadline) throw first
|
|
221
|
+
await new Promise((resolve) => setTimeout(resolve, WAL_RETRY_MS))
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function openSqlite(url: string): Promise<Database> {
|
|
227
|
+
const [{ createClient }, { drizzle }] = await Promise.all([import('@libsql/client'), import('drizzle-orm/libsql')])
|
|
228
|
+
const remote = isRemoteSqlite(url)
|
|
229
|
+
|
|
230
|
+
let clientUrl = url
|
|
231
|
+
if (!remote) {
|
|
232
|
+
const file = path.resolve(/* turbopackIgnore: true */ process.cwd(), url.replace(/^(sqlite:\/\/|sqlite:|file:)/, ''))
|
|
233
|
+
if (isBuildPhase()) {
|
|
234
|
+
// `next build` must not create an empty database file (or its folder) as a side effect, and
|
|
235
|
+
// libSQL creates a missing file on open. Same code the old driver reported, for the fallback.
|
|
236
|
+
if (!existsSync(file)) throw Object.assign(new Error(`SQLite database ${file} does not exist`), { code: 'SQLITE_CANTOPEN' })
|
|
237
|
+
} else {
|
|
238
|
+
mkdirSync(path.dirname(file), { recursive: true })
|
|
239
|
+
}
|
|
240
|
+
clientUrl = `file:${file}`
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const raw = createClient({
|
|
244
|
+
url: clientUrl,
|
|
245
|
+
authToken: remote ? process.env.DATABASE_AUTH_TOKEN || undefined : undefined,
|
|
246
|
+
timeout: remote ? undefined : BUSY_TIMEOUT_MS,
|
|
247
|
+
})
|
|
248
|
+
try {
|
|
249
|
+
// WAL lets readers carry on while one connection writes. It is stored in the file, so once is
|
|
250
|
+
// enough; a hosted database manages its own journal. Skipped by the build, which only reads.
|
|
251
|
+
if (!remote && !isBuildPhase()) await switchToWal(raw)
|
|
252
|
+
// The schema relies on foreign keys (cascade, restrict). libSQL enables them on every connection
|
|
253
|
+
// by default; refuse to run on a server where they are off rather than lose data quietly.
|
|
254
|
+
const { rows } = await raw.execute('PRAGMA foreign_keys')
|
|
255
|
+
if (Number(Object.values(rows[0] ?? {})[0]) !== 1) {
|
|
256
|
+
throw new Error('This SQLite database does not enforce foreign keys (PRAGMA foreign_keys is off), which the site relies on.')
|
|
257
|
+
}
|
|
258
|
+
} catch (error) {
|
|
259
|
+
raw.close()
|
|
260
|
+
throw error
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// The open transaction of the current async context (see withTransaction).
|
|
264
|
+
const current = new AsyncLocalStorage<Transaction>()
|
|
265
|
+
const openTransaction = () => {
|
|
266
|
+
const tx = current.getStore()
|
|
267
|
+
return tx && !tx.closed ? tx : undefined
|
|
268
|
+
}
|
|
269
|
+
const gate = new Gate(BUSY_TIMEOUT_MS)
|
|
270
|
+
// Statements made while a transaction is open in this async context join it, as nested
|
|
271
|
+
// withTransaction calls do. Anything else waits its turn on a local file (see Gate); a hosted
|
|
272
|
+
// database queues writers itself, so there they run straight away.
|
|
273
|
+
const outside = <T>(fn: () => Promise<T>) => (remote ? fn() : gate.share(fn))
|
|
274
|
+
const client = new Proxy(raw, {
|
|
275
|
+
get(target, prop, receiver) {
|
|
276
|
+
if (prop === 'execute') {
|
|
277
|
+
return (stmt: InStatement | string, args?: never) => {
|
|
278
|
+
const statement = (typeof stmt === 'string' ? { sql: stmt, args: args ?? [] } : stmt) as InStatement
|
|
279
|
+
const tx = openTransaction()
|
|
280
|
+
return tx ? tx.execute(statement) : outside(() => target.execute(statement))
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (prop === 'batch') {
|
|
284
|
+
return (stmts: InStatement[], mode?: 'write' | 'read' | 'deferred') => {
|
|
285
|
+
const tx = openTransaction()
|
|
286
|
+
return tx ? tx.batch(stmts) : outside(() => target.batch(stmts, mode))
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (prop === 'migrate') {
|
|
290
|
+
return (stmts: InStatement[]) => {
|
|
291
|
+
// Migrations need their own transaction (with foreign keys off), so they cannot join one,
|
|
292
|
+
// and waiting for the open one would wait for ourselves.
|
|
293
|
+
if (openTransaction()) return Promise.reject(new Error('Migrations cannot run inside a transaction.'))
|
|
294
|
+
return outside(() => target.migrate(stmts))
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if (prop === 'transaction') {
|
|
298
|
+
return () => {
|
|
299
|
+
throw new Error('Use withTransaction() from src/db/client.ts, not db.transaction(), on SQLite.')
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const value = Reflect.get(target, prop, receiver)
|
|
303
|
+
return typeof value === 'function' ? value.bind(target) : value
|
|
304
|
+
},
|
|
305
|
+
}) as Client
|
|
306
|
+
const db = drizzle(client, { schema: sqliteSchema })
|
|
307
|
+
|
|
308
|
+
// Transactions take turns in this process, on a local file and on a hosted database alike.
|
|
309
|
+
const queue = new Gate(BUSY_TIMEOUT_MS)
|
|
310
|
+
const withTransaction = <T>(fn: (tx: Db) => Promise<T>): Promise<T> => {
|
|
311
|
+
// Already inside a transaction (this call is part of its work): join it. Queueing behind
|
|
312
|
+
// ourselves would wait for a transaction that is waiting for us.
|
|
313
|
+
if (openTransaction()) return fn(db)
|
|
314
|
+
const run = async () => {
|
|
315
|
+
const tx = await raw.transaction('write')
|
|
316
|
+
try {
|
|
317
|
+
// `db` routes every statement made in this async context into `tx`, so code that is handed
|
|
318
|
+
// `tx` and code that reaches for the database itself both take part.
|
|
319
|
+
const result = await current.run(tx, () => fn(db))
|
|
320
|
+
await tx.commit()
|
|
321
|
+
return result
|
|
322
|
+
} catch (error) {
|
|
323
|
+
try {
|
|
324
|
+
await tx.rollback()
|
|
325
|
+
} catch {
|
|
326
|
+
// The transaction already ended (for example a failed COMMIT). Report the original error.
|
|
327
|
+
}
|
|
328
|
+
throw error
|
|
329
|
+
} finally {
|
|
330
|
+
tx.close()
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return queue.alone(() => (remote ? run() : gate.alone(run)))
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
dialect: 'sqlite',
|
|
338
|
+
migratesOnOpen: !remote,
|
|
339
|
+
db,
|
|
340
|
+
t: sqliteSchema,
|
|
341
|
+
withTransaction,
|
|
342
|
+
close: async () => {
|
|
343
|
+
raw.close()
|
|
344
|
+
},
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async function openPostgres(url: string): Promise<Database> {
|
|
349
|
+
const [{ Pool }, { drizzle }] = await Promise.all([import('pg'), import('drizzle-orm/node-postgres')])
|
|
350
|
+
// A query that runs longer than this is cancelled by the server, so one stuck statement cannot
|
|
351
|
+
// hold a pooled connection forever. 0 turns it off (the migrate script does, for slow DDL).
|
|
352
|
+
const statementTimeout = Number(process.env.DB_STATEMENT_TIMEOUT_MS ?? 15_000) || 0
|
|
353
|
+
const pool = new Pool({
|
|
354
|
+
connectionString: url,
|
|
355
|
+
max: Number(process.env.DB_POOL_MAX) || 10,
|
|
356
|
+
idleTimeoutMillis: 30_000,
|
|
357
|
+
connectionTimeoutMillis: 10_000,
|
|
358
|
+
statement_timeout: statementTimeout || undefined,
|
|
359
|
+
query_timeout: statementTimeout ? statementTimeout + 5_000 : undefined,
|
|
360
|
+
idle_in_transaction_session_timeout: 30_000,
|
|
361
|
+
application_name: 'pet-adopt',
|
|
362
|
+
})
|
|
363
|
+
// An idle connection can be dropped at any time (database restart, failover, a proxy's idle
|
|
364
|
+
// timeout). The pool reports that as an 'error' event; with no listener Node treats it as an
|
|
365
|
+
// uncaught exception and the whole server exits. The pool discards the dead connection itself.
|
|
366
|
+
pool.on('error', (error) => logError(error, 'postgres pool'))
|
|
367
|
+
const db = drizzle(pool, { schema: pgSchema })
|
|
368
|
+
// The open transaction of the current async context: a nested withTransaction call joins it, so
|
|
369
|
+
// its work commits or rolls back with the outer one. (Otherwise it would run on another pooled
|
|
370
|
+
// connection: committed on its own, and stuck behind any row or lock the outer one holds.)
|
|
371
|
+
const current = new AsyncLocalStorage<typeof db>()
|
|
372
|
+
return {
|
|
373
|
+
dialect: 'pg',
|
|
374
|
+
migratesOnOpen: false,
|
|
375
|
+
db: db as unknown as Db,
|
|
376
|
+
t: pgSchema as unknown as Schema,
|
|
377
|
+
withTransaction: async (fn, options) => {
|
|
378
|
+
const lock = (tx: typeof db) => tx.execute(sql`select pg_advisory_xact_lock(hashtext(${options!.lock!}))`)
|
|
379
|
+
const outer = current.getStore()
|
|
380
|
+
if (outer) {
|
|
381
|
+
// A session may take an advisory lock it already holds, so a nested lock never waits on itself.
|
|
382
|
+
if (options?.lock) await lock(outer)
|
|
383
|
+
return fn(outer as unknown as Db)
|
|
384
|
+
}
|
|
385
|
+
return db.transaction(async (tx) => {
|
|
386
|
+
if (options?.lock) await lock(tx as unknown as typeof db)
|
|
387
|
+
return current.run(tx as unknown as typeof db, () => fn(tx as unknown as Db))
|
|
388
|
+
})
|
|
389
|
+
},
|
|
390
|
+
close: () => pool.end(),
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
type Holder = { promise?: Promise<Database>; reboundTo?: Schema; demo?: DemoState }
|
|
395
|
+
// Kept on globalThis so hot reloads in development reuse the connection.
|
|
396
|
+
const holder = ((globalThis as { __petAdoptDb?: Holder }).__petAdoptDb ??= {})
|
|
397
|
+
|
|
398
|
+
const tablesFor = (dialect: Dialect): Schema => (dialect === 'pg' ? (pgSchema as unknown as Schema) : sqliteSchema)
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Opens the database once per process. A local SQLite file also applies pending migrations (the
|
|
402
|
+
* site's, then plugins') on first use.
|
|
403
|
+
*
|
|
404
|
+
* In development the connection outlives hot reloads, but a reload can bring a changed schema
|
|
405
|
+
* module (a new column). The cached tables would then be stale and Drizzle fails on the new column
|
|
406
|
+
* ("Cannot convert undefined or null to object"). So the tables are re-bound to the current module
|
|
407
|
+
* when it changes, and a local SQLite file applies any new migrations then too. In production the module never
|
|
408
|
+
* changes, so this is one identity check.
|
|
409
|
+
*
|
|
410
|
+
* In demo mode it hands out this instance's throwaway copy, filled first and made again once it is
|
|
411
|
+
* older than DEMO_RESET_MINUTES (see "Demo mode" below).
|
|
412
|
+
*/
|
|
413
|
+
export async function getDatabase(): Promise<Database> {
|
|
414
|
+
return isDemo() ? demoDatabase() : currentDatabase()
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
async function currentDatabase(): Promise<Database> {
|
|
418
|
+
const database = await openOnce()
|
|
419
|
+
const t = tablesFor(database.dialect)
|
|
420
|
+
if (database.t === t) return database
|
|
421
|
+
// Synchronous after the await, so concurrent callers start one re-bind, not several.
|
|
422
|
+
if (holder.reboundTo !== t) {
|
|
423
|
+
holder.reboundTo = t
|
|
424
|
+
const rebound: Database = { ...database, t }
|
|
425
|
+
holder.promise = (async () => {
|
|
426
|
+
if (rebound.migratesOnOpen && !isBuildPhase()) {
|
|
427
|
+
const { runMigrations } = await import('./migrate')
|
|
428
|
+
await runMigrations(rebound)
|
|
429
|
+
await migratePluginsQuietly(rebound)
|
|
430
|
+
}
|
|
431
|
+
return rebound
|
|
432
|
+
})()
|
|
433
|
+
}
|
|
434
|
+
return holder.promise!
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* A local SQLite file: plugins' own migrations run right after the site's, as the site's do. A plugin that fails
|
|
439
|
+
* is logged and shown as not ready in the admin; it never stops the site from opening its database.
|
|
440
|
+
* (Must not call getDatabase: the database is still being opened.)
|
|
441
|
+
*/
|
|
442
|
+
async function migratePluginsQuietly(database: Database) {
|
|
443
|
+
try {
|
|
444
|
+
const { migratePlugins } = await import('@/plugins/storage')
|
|
445
|
+
await migratePlugins(database)
|
|
446
|
+
} catch (error) {
|
|
447
|
+
logError(error, 'Could not set up plugin tables')
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function openOnce(): Promise<Database> {
|
|
452
|
+
holder.promise ??= (async () => {
|
|
453
|
+
const { dialect, url } = resolveDatabaseUrl()
|
|
454
|
+
const database = dialect === 'pg' ? await openPostgres(url) : await openSqlite(url)
|
|
455
|
+
if (database.migratesOnOpen && !isBuildPhase()) {
|
|
456
|
+
try {
|
|
457
|
+
const { runMigrations } = await import('./migrate')
|
|
458
|
+
await runMigrations(database)
|
|
459
|
+
} catch (error) {
|
|
460
|
+
// Don't leave the file open: the next call opens it again, and they would pile up.
|
|
461
|
+
await database.close().catch(() => undefined)
|
|
462
|
+
throw error
|
|
463
|
+
}
|
|
464
|
+
await migratePluginsQuietly(database)
|
|
465
|
+
}
|
|
466
|
+
return database
|
|
467
|
+
})().catch((error) => {
|
|
468
|
+
holder.promise = undefined // let the next call try again
|
|
469
|
+
throw error
|
|
470
|
+
})
|
|
471
|
+
return holder.promise
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
export async function closeDatabase() {
|
|
475
|
+
const current = holder.promise
|
|
476
|
+
holder.promise = undefined
|
|
477
|
+
if (isDemo()) return closeDemoCopy(current)
|
|
478
|
+
if (current) await (await current).close()
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// ---- Demo mode -------------------------------------------------------------------------------------
|
|
482
|
+
//
|
|
483
|
+
// PET_ADOPT_DEMO=1 (src/lib/demo.ts): this instance's own throwaway copy of the site. Nothing here
|
|
484
|
+
// runs with the switch off.
|
|
485
|
+
//
|
|
486
|
+
// - The copy is a SQLite file in os.tmpdir() with a fresh name per process and per reset, opened
|
|
487
|
+
// like any local file (WAL, the site's and plugins' migrations on open). `next build` creates
|
|
488
|
+
// nothing: the file is missing, so the public reads fall back to their build-time defaults.
|
|
489
|
+
// - The first getDatabase() fills it (src/server/demo-site.ts), and so does the first one after it
|
|
490
|
+
// is DEMO_RESET_MINUTES old: one copy is made at a time and every caller waits for it.
|
|
491
|
+
// - The fill runs where getDatabase() hands it the copy being filled (the `fill` scope below), so
|
|
492
|
+
// the data layer it calls does not wait for the fill itself.
|
|
493
|
+
// - A caller inside an open transaction keeps the copy that transaction runs on.
|
|
494
|
+
// - The fill runs outside any request (`outside`, captured when this module is first loaded, which
|
|
495
|
+
// is in register(), before the server answers anything): a reset is set off by whatever request
|
|
496
|
+
// reaches the database first, which can be a cached read or a background prerender, where Next
|
|
497
|
+
// refuses clock reads and page refreshes. Outside, the fill is like `pnpm seed`.
|
|
498
|
+
// - The replaced copy is closed and deleted RETIRE_AFTER_MS later, so a request that fetched it just
|
|
499
|
+
// before the swap finishes on it instead of failing on a closed client.
|
|
500
|
+
|
|
501
|
+
type DemoState = {
|
|
502
|
+
/** The current copy's file (made on first use). */
|
|
503
|
+
file?: string
|
|
504
|
+
/** Settles once the current copy is open and filled. Replaced by each new copy. */
|
|
505
|
+
ready?: Promise<void>
|
|
506
|
+
/** performance.now() when the current copy was filled; unset while one is being made. */
|
|
507
|
+
filledAt?: number
|
|
508
|
+
/** The copy being filled, for the data layer the fill calls. */
|
|
509
|
+
fill: AsyncLocalStorage<Database>
|
|
510
|
+
/** The copy an open transaction runs on. */
|
|
511
|
+
tx: AsyncLocalStorage<{ database: Database; open: boolean }>
|
|
512
|
+
/** Runs a function outside any request (see above). */
|
|
513
|
+
outside: <R>(fn: () => R) => R
|
|
514
|
+
/** Each copy with its transactions tracked (see withDemoScope). */
|
|
515
|
+
wrapped: WeakMap<Database, Database>
|
|
516
|
+
/** Replaced copies' files, deleted after RETIRE_AFTER_MS or when the process exits. */
|
|
517
|
+
retiring: Set<string>
|
|
518
|
+
/** check:demo shortens RETIRE_AFTER_MS (expireDemoCopyForChecks). */
|
|
519
|
+
retireAfterMs?: number
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** How long a replaced copy stays open for requests that fetched it just before the swap. */
|
|
523
|
+
const RETIRE_AFTER_MS = 30_000
|
|
524
|
+
/** A reset that failed is tried again this much later (the current copy is kept meanwhile). */
|
|
525
|
+
const RETRY_RESET_MS = 60_000
|
|
526
|
+
/** The only files the demo ever deletes: its own copies in the temporary folder. */
|
|
527
|
+
const DEMO_FILE = /^pet-adopt-demo-\d+-[0-9a-f]{12}\.db$/
|
|
528
|
+
|
|
529
|
+
function demoState(): DemoState {
|
|
530
|
+
if (!holder.demo) {
|
|
531
|
+
const state: DemoState = {
|
|
532
|
+
fill: new AsyncLocalStorage(),
|
|
533
|
+
tx: new AsyncLocalStorage(),
|
|
534
|
+
outside: AsyncLocalStorage.snapshot(),
|
|
535
|
+
wrapped: new WeakMap(),
|
|
536
|
+
retiring: new Set(),
|
|
537
|
+
}
|
|
538
|
+
holder.demo = state
|
|
539
|
+
// Leave nothing behind in the temporary folder when the process ends normally.
|
|
540
|
+
process.once('exit', () => {
|
|
541
|
+
for (const file of [state.file, ...state.retiring]) removeDemoFiles(file)
|
|
542
|
+
})
|
|
543
|
+
}
|
|
544
|
+
return holder.demo
|
|
545
|
+
}
|
|
546
|
+
// Taken when this module is first loaded (in register(), outside any request), not on first use.
|
|
547
|
+
if (isDemo()) demoState()
|
|
548
|
+
|
|
549
|
+
function demoFile(): string {
|
|
550
|
+
const problem = demoProblem()
|
|
551
|
+
if (problem) throw new Error(problem)
|
|
552
|
+
const demo = demoState()
|
|
553
|
+
return (demo.file ??= path.join(os.tmpdir(), `pet-adopt-demo-${process.pid}-${randomBytes(6).toString('hex')}.db`))
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** Deletes a copy's file and SQLite's files beside it. Never anything but a demo copy. */
|
|
557
|
+
function removeDemoFiles(file: string | undefined) {
|
|
558
|
+
if (!file || path.dirname(file) !== os.tmpdir() || !DEMO_FILE.test(path.basename(file))) return
|
|
559
|
+
for (const suffix of ['', '-wal', '-shm', '-journal']) {
|
|
560
|
+
try {
|
|
561
|
+
rmSync(file + suffix, { force: true })
|
|
562
|
+
} catch (error) {
|
|
563
|
+
logError(error, `Could not delete the demo copy ${path.basename(file)}${suffix}`)
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const copyAge = (demo: DemoState) => (demo.filledAt === undefined ? 0 : performance.now() - demo.filledAt)
|
|
569
|
+
|
|
570
|
+
async function demoDatabase(): Promise<Database> {
|
|
571
|
+
const demo = demoState()
|
|
572
|
+
const filling = demo.fill.getStore()
|
|
573
|
+
if (filling) return filling
|
|
574
|
+
const tx = demo.tx.getStore()
|
|
575
|
+
if (tx?.open) return tx.database
|
|
576
|
+
// `next build`: open the (missing) file and fail, as any missing local database does.
|
|
577
|
+
if (isBuildPhase()) return currentDatabase()
|
|
578
|
+
for (;;) {
|
|
579
|
+
// A new copy is made at first, and once the current one is too old. While one is being made
|
|
580
|
+
// (filledAt unset), every caller waits for it.
|
|
581
|
+
if (!demo.ready || (demo.filledAt !== undefined && copyAge(demo) >= demoResetMinutes() * 60_000)) {
|
|
582
|
+
const previous = demo.ready ? holder.promise : undefined
|
|
583
|
+
demo.filledAt = undefined
|
|
584
|
+
const making = demo.outside(() => makeDemoCopy(demo, previous))
|
|
585
|
+
demo.ready = making
|
|
586
|
+
// No copy to fall back on: forget the failure, so the next caller tries again.
|
|
587
|
+
making.catch(() => {
|
|
588
|
+
if (demo.ready === making) demo.ready = undefined
|
|
589
|
+
})
|
|
590
|
+
}
|
|
591
|
+
const ready = demo.ready
|
|
592
|
+
await ready
|
|
593
|
+
// Another copy was started while this caller waited (only after a failure): wait for that one.
|
|
594
|
+
if (demo.ready === ready) return withDemoScope(await currentDatabase())
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Opens a new copy in a new file and fills it. On success the previous copy (if any) is retired; on
|
|
600
|
+
* failure the new file is deleted, and the previous copy is kept for RETRY_RESET_MS more, or, with
|
|
601
|
+
* none to keep, the next caller tries again.
|
|
602
|
+
*/
|
|
603
|
+
async function makeDemoCopy(demo: DemoState, previous: Promise<Database> | undefined): Promise<void> {
|
|
604
|
+
const previousFile = demo.file
|
|
605
|
+
let site: typeof import('@/server/demo-site') | undefined
|
|
606
|
+
try {
|
|
607
|
+
const problem = demoProblem()
|
|
608
|
+
if (problem) throw new Error(problem)
|
|
609
|
+
site = await import('@/server/demo-site')
|
|
610
|
+
holder.promise = undefined
|
|
611
|
+
holder.reboundTo = undefined
|
|
612
|
+
demo.file = undefined
|
|
613
|
+
site.beginDemoCopy()
|
|
614
|
+
const database = await currentDatabase()
|
|
615
|
+
await demo.fill.run(database, () => site!.fillDemoSite())
|
|
616
|
+
site.finishDemoCopy()
|
|
617
|
+
demo.filledAt = performance.now()
|
|
618
|
+
} catch (error) {
|
|
619
|
+
const failed = holder.promise
|
|
620
|
+
const failedFile = demo.file
|
|
621
|
+
holder.promise = undefined
|
|
622
|
+
if (failed && failed !== previous) await failed.then((database) => database.close()).catch(() => undefined)
|
|
623
|
+
if (failedFile !== previousFile) removeDemoFiles(failedFile)
|
|
624
|
+
site?.abandonDemoCopy()
|
|
625
|
+
if (previous) {
|
|
626
|
+
logError(error, 'Could not make a fresh copy of the demo; the current one is kept and the reset is tried again in a minute')
|
|
627
|
+
holder.promise = previous
|
|
628
|
+
demo.file = previousFile
|
|
629
|
+
demo.filledAt = performance.now() - demoResetMinutes() * 60_000 + RETRY_RESET_MS
|
|
630
|
+
return
|
|
631
|
+
}
|
|
632
|
+
demo.file = undefined
|
|
633
|
+
throw error
|
|
634
|
+
}
|
|
635
|
+
if (previous && previousFile) retireDemoCopy(demo, previous, previousFile)
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function retireDemoCopy(demo: DemoState, previous: Promise<Database>, file: string) {
|
|
639
|
+
demo.retiring.add(file)
|
|
640
|
+
const timer = setTimeout(() => {
|
|
641
|
+
void previous
|
|
642
|
+
.then((database) => database.close())
|
|
643
|
+
.catch(() => undefined)
|
|
644
|
+
.finally(() => {
|
|
645
|
+
removeDemoFiles(file)
|
|
646
|
+
demo.retiring.delete(file)
|
|
647
|
+
})
|
|
648
|
+
}, demo.retireAfterMs ?? RETIRE_AFTER_MS)
|
|
649
|
+
timer.unref?.()
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* The copy with its transactions tracked: getDatabase() inside one returns this copy, even after a
|
|
654
|
+
* new one replaced it, so a reset never pulls the database out from under an open transaction.
|
|
655
|
+
*/
|
|
656
|
+
function withDemoScope(database: Database): Database {
|
|
657
|
+
const demo = demoState()
|
|
658
|
+
let scoped = demo.wrapped.get(database)
|
|
659
|
+
if (!scoped) {
|
|
660
|
+
const tracked: Database = {
|
|
661
|
+
...database,
|
|
662
|
+
withTransaction: (fn, options) => {
|
|
663
|
+
const scope = { database: tracked, open: true }
|
|
664
|
+
return demo.tx.run(scope, () => database.withTransaction(fn, options)).finally(() => {
|
|
665
|
+
scope.open = false
|
|
666
|
+
})
|
|
667
|
+
},
|
|
668
|
+
}
|
|
669
|
+
demo.wrapped.set(database, tracked)
|
|
670
|
+
scoped = tracked
|
|
671
|
+
}
|
|
672
|
+
return scoped
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** closeDatabase() in demo mode: closes and deletes this copy and empties the pictures (scripts, checks). */
|
|
676
|
+
async function closeDemoCopy(current: Promise<Database> | undefined) {
|
|
677
|
+
const demo = demoState()
|
|
678
|
+
const file = demo.file
|
|
679
|
+
demo.file = undefined
|
|
680
|
+
demo.ready = undefined
|
|
681
|
+
demo.filledAt = undefined
|
|
682
|
+
holder.reboundTo = undefined
|
|
683
|
+
if (current) await current.then((database) => database.close()).catch(() => undefined)
|
|
684
|
+
removeDemoFiles(file)
|
|
685
|
+
const { dropDemoCopy } = await import('@/server/demo-site')
|
|
686
|
+
dropDemoCopy()
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* For check:demo: makes the next getDatabase() replace the copy, as if it were DEMO_RESET_MINUTES
|
|
691
|
+
* old. `retireAfterMs` shortens how long the replaced copy stays open before it is deleted.
|
|
692
|
+
*/
|
|
693
|
+
export function expireDemoCopyForChecks(opts: { retireAfterMs?: number } = {}): void {
|
|
694
|
+
const demo = demoState()
|
|
695
|
+
if (opts.retireAfterMs !== undefined) demo.retireAfterMs = opts.retireAfterMs
|
|
696
|
+
if (demo.filledAt !== undefined) demo.filledAt = performance.now() - demoResetMinutes() * 60_000
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** The current demo copy's file, for logs and checks (null outside demo mode or before it exists). */
|
|
700
|
+
export function demoCopyFile(): string | null {
|
|
701
|
+
return isDemo() ? (holder.demo?.file ?? null) : null
|
|
702
|
+
}
|