sandcms 0.6.3 → 0.7.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.
Files changed (124) hide show
  1. package/README.md +14 -10
  2. package/dist/admin/Account.svelte +2 -0
  3. package/dist/admin/Admin.svelte +14 -1
  4. package/dist/admin/AssetAttachment.svelte +1 -3
  5. package/dist/admin/AssetAttachment.svelte.d.ts +0 -1
  6. package/dist/admin/BlueprintFields.svelte +0 -3
  7. package/dist/admin/BlueprintFields.svelte.d.ts +0 -1
  8. package/dist/admin/Editor.svelte +0 -1
  9. package/dist/admin/Fields.svelte +0 -7
  10. package/dist/admin/Fields.svelte.d.ts +0 -1
  11. package/dist/admin/Gallery.svelte +2 -6
  12. package/dist/admin/Gallery.svelte.d.ts +0 -1
  13. package/dist/admin/LinkField.svelte +0 -3
  14. package/dist/admin/LinkField.svelte.d.ts +0 -1
  15. package/dist/admin/MediaLibrary.svelte +10 -7
  16. package/dist/admin/MediaPicker.svelte +7 -15
  17. package/dist/admin/MediaPicker.svelte.d.ts +0 -1
  18. package/dist/admin/ThemePicker.svelte +72 -0
  19. package/dist/admin/ThemePicker.svelte.d.ts +18 -0
  20. package/dist/admin/UploadButton.svelte +2 -1
  21. package/dist/admin/UploadProgress.svelte +24 -0
  22. package/dist/admin/UploadProgress.svelte.d.ts +7 -0
  23. package/dist/admin/client.d.ts +3 -670
  24. package/dist/admin/client.js +2 -1
  25. package/dist/admin/components/ui/alert/alert.svelte.d.ts +3 -13
  26. package/dist/admin/components/ui/attachment/attachment-media.svelte.d.ts +3 -13
  27. package/dist/admin/components/ui/attachment/attachment.svelte.d.ts +6 -26
  28. package/dist/admin/components/ui/badge/badge.svelte.d.ts +7 -25
  29. package/dist/admin/components/ui/button/button.svelte.d.ts +15 -53
  30. package/dist/admin/components/ui/toggle/toggle.svelte.d.ts +6 -26
  31. package/dist/admin/generated/admin.css +529 -101
  32. package/dist/admin/theme-context.d.ts +7 -0
  33. package/dist/admin/theme-context.js +3 -0
  34. package/dist/admin/theme.d.ts +7 -0
  35. package/dist/admin/theme.js +14 -0
  36. package/dist/admin/types.d.ts +2 -1
  37. package/dist/admin/uploads.d.ts +8 -1
  38. package/dist/admin/uploads.js +94 -16
  39. package/dist/blueprints/files.js +1 -0
  40. package/dist/blueprints/load.js +7 -2
  41. package/dist/blueprints/types.d.ts +4 -1
  42. package/dist/cli/doctor.d.ts +3 -1
  43. package/dist/cli/doctor.js +85 -30
  44. package/dist/cli/files.d.ts +2 -6
  45. package/dist/cli/files.js +11 -2
  46. package/dist/cli/index.js +99 -31
  47. package/dist/cli/scaffold.js +8 -8
  48. package/dist/cli/setup.js +16 -26
  49. package/dist/cli/upgrade.js +21 -2
  50. package/dist/env.d.ts +32 -0
  51. package/dist/env.js +53 -3
  52. package/dist/server/admin-load.d.ts +13 -5
  53. package/dist/server/admin-load.js +6 -1
  54. package/dist/server/api-access.d.ts +4 -0
  55. package/dist/server/api-access.js +15 -2
  56. package/dist/server/api-pagination.d.ts +3 -0
  57. package/dist/server/api.js +5 -2
  58. package/dist/server/auth.d.ts +10 -9
  59. package/dist/server/cms.d.ts +65 -18
  60. package/dist/server/cms.js +62 -6
  61. package/dist/server/db/migration-data.js +4 -0
  62. package/dist/server/db/migrations/0009_local_media.sql +9 -0
  63. package/dist/server/db/migrations/meta/0009_snapshot.json +1763 -0
  64. package/dist/server/db/migrations/meta/_journal.json +7 -0
  65. package/dist/server/db/schema.d.ts +119 -2
  66. package/dist/server/db/schema.js +15 -3
  67. package/dist/server/hooks.js +155 -81
  68. package/dist/server/media/contracts.d.ts +115 -0
  69. package/dist/server/media/contracts.js +12 -0
  70. package/dist/server/media/deletions.d.ts +2 -1
  71. package/dist/server/media/deletions.js +3 -3
  72. package/dist/server/media/delivery.js +7 -11
  73. package/dist/server/media/import-r2.d.ts +56 -0
  74. package/dist/server/media/import-r2.js +342 -0
  75. package/dist/server/media/processor-child.d.ts +2 -0
  76. package/dist/server/media/processor-child.js +236 -0
  77. package/dist/server/media/processor.d.ts +51 -0
  78. package/dist/server/media/processor.js +135 -0
  79. package/dist/server/media/render-math.d.ts +24 -0
  80. package/dist/server/media/render-math.js +50 -0
  81. package/dist/server/media/runner.d.ts +30 -1
  82. package/dist/server/media/runner.js +418 -165
  83. package/dist/server/media/service.d.ts +56 -10
  84. package/dist/server/media/service.js +309 -98
  85. package/dist/server/media/storage.d.ts +5 -0
  86. package/dist/server/media/storage.js +279 -0
  87. package/dist/server/media/svg.d.ts +5 -0
  88. package/dist/server/media/svg.js +142 -0
  89. package/dist/server/media/upload-ticket.d.ts +12 -0
  90. package/dist/server/media/upload-ticket.js +35 -0
  91. package/dist/server/media/verify.d.ts +36 -0
  92. package/dist/server/media/verify.js +109 -0
  93. package/dist/server/platform/http.d.ts +27 -0
  94. package/dist/server/platform/http.js +77 -0
  95. package/dist/server/platform/index.d.ts +52 -0
  96. package/dist/server/platform/index.js +98 -0
  97. package/dist/server/platform/snapshots.d.ts +18 -0
  98. package/dist/server/platform/snapshots.js +110 -0
  99. package/dist/server/platform/volume.d.ts +20 -0
  100. package/dist/server/platform/volume.js +60 -0
  101. package/dist/worker/svg.d.ts +1 -5
  102. package/dist/worker/svg.js +2 -142
  103. package/docs/acceptance.md +6 -4
  104. package/docs/api.md +41 -3
  105. package/docs/cloudflare.md +48 -142
  106. package/docs/content.md +2 -2
  107. package/docs/deployment.md +159 -57
  108. package/docs/forms.md +1 -1
  109. package/docs/media.md +85 -21
  110. package/docs/package.md +21 -18
  111. package/docs/plans/0.7-self-hosted.md +264 -0
  112. package/docs/releases.md +17 -1
  113. package/docs/upgrades.md +35 -6
  114. package/package.json +36 -37
  115. package/templates/Dockerfile +28 -0
  116. package/templates/integration.ts +18 -2
  117. package/templates/railpack.json +1 -1
  118. package/templates/sandcms/blueprints/files/image.yaml +1 -1
  119. package/templates/sandcms/config.yaml +0 -1
  120. package/dist/cli/cloudflare.d.ts +0 -8
  121. package/dist/cli/cloudflare.js +0 -135
  122. package/templates/sandcms/worker/index.ts +0 -1
  123. package/templates/sandcms/worker/local.ts +0 -1
  124. package/templates/sandcms/worker/wrangler.jsonc +0 -6
@@ -22,7 +22,7 @@ export function scaffold(root, name, packageSource) {
22
22
  private: true,
23
23
  type: 'module',
24
24
  imports: { '#lib': './src/lib/index.ts', '#lib/*': './src/lib/*' },
25
- packageManager: 'bun@1.4.0',
25
+ packageManager: 'bun@1.4.4',
26
26
  scripts: {
27
27
  dev: 'bun --bun vite dev --host 0.0.0.0 --port 5410 --strictPort',
28
28
  build: 'bun x --no-install sandcms validate && bun --bun vite build',
@@ -31,17 +31,17 @@ export function scaffold(root, name, packageSource) {
31
31
  },
32
32
  dependencies: { [PACKAGE_NAME]: packageSource ?? PACKAGE_VERSION },
33
33
  devDependencies: {
34
- '@sveltejs/kit': '3.0.0',
34
+ '@sveltejs/kit': '3.2.0',
35
35
  '@sveltejs/vite-plugin-svelte': '7.3.1',
36
- svelte: '5.57.1',
37
- vite: '8.3.1',
36
+ svelte: '5.57.3',
37
+ vite: '8.3.8',
38
38
  typescript: '6.0.3',
39
- '@sveltejs/adapter-bun': '1.0.0',
40
- 'svelte-check': '4.7.6',
41
- '@types/bun': '1.4.2'
39
+ '@sveltejs/adapter-bun': '1.0.1',
40
+ 'svelte-check': '4.7.8',
41
+ '@types/bun': '1.4.4'
42
42
  }
43
43
  }, null, 2) + '\n');
44
- write(join(root, 'vite.config.ts'), "import adapter from '@sveltejs/adapter-bun';\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte';\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n// Keep Better Auth on native async storage when the Bun adapter bundles the server.\nexport default defineConfig({plugins:[sveltekit({adapter:adapter(),paths:{origin:process.env.SANDCMS_ORIGIN},preprocess:vitePreprocess()})],ssr:{external:['bun:sqlite'],noExternal:['@better-auth/core']}});\n");
44
+ write(join(root, 'vite.config.ts'), "import adapter from '@sveltejs/adapter-bun';\nimport { vitePreprocess } from '@sveltejs/vite-plugin-svelte';\nimport { sveltekit } from '@sveltejs/kit/vite';\nimport { defineConfig } from 'vite';\n// The origin comes from each request's Host header, so a domain change needs no rebuild.\n// Keep native modules external and Better Auth on native async storage in the server build.\nexport default defineConfig({plugins:[sveltekit({adapter:adapter(),preprocess:vitePreprocess()})],ssr:{external:['bun:sqlite','sharp'],noExternal:['@better-auth/core']}});\n");
45
45
  write(join(root, 'tsconfig.json'), JSON.stringify({
46
46
  extends: '$app/tsconfig',
47
47
  include: ['src', 'test', '*'],
package/dist/cli/setup.js CHANGED
@@ -3,8 +3,7 @@ import { join, resolve } from 'node:path';
3
3
  import * as p from '@clack/prompts';
4
4
  import { parse as parseEnv } from 'dotenv';
5
5
  import { planFiles, applyPlan, migrationReport, routeConflicts, write, PACKAGE_NAME, PACKAGE_VERSION } from './files.js';
6
- import { answer, confirm, text, run } from './prompts.js';
7
- import { configureWorker } from './cloudflare.js';
6
+ import { answer, text, run } from './prompts.js';
8
7
  import { scaffold, assertFreshDirectory } from './scaffold.js';
9
8
  import { openStore, pendingMigrations } from '../server/db/store.js';
10
9
  import { createUser } from '../server/auth.js';
@@ -27,11 +26,12 @@ export async function setup(options) {
27
26
  const notes = [
28
27
  'SvelteKit 3 is required. Migrate developer-owned Vite configuration, package imports, and tsconfig before applying generated integrations; see docs/upgrades.md#sveltekit-3.',
29
28
  'Public website routes remain developer-owned.',
30
- 'Run sandcms user bootstrap against the production database after deployment.',
29
+ 'Deploy the generated Dockerfile as one container with one persistent volume at /data. Set SANDCMS_BOOTSTRAP_EMAIL for the first start to create the admin, or run sandcms user bootstrap against the production database. See docs/deployment.md.',
31
30
  'Existing adapters are preserved. Configure @sveltejs/adapter-bun as shown in docs/deployment.md.',
32
- 'Setup adds commented proxy settings to .env.local. For Dokploy + Cloudflare, secure origin ingress, then set SANDCMS_TRUSTED_PROXY_HEADER=cf-connecting-ip and ADDRESS_HEADER=cf-connecting-ip in Dokploy runtime variables; see docs/deployment.md#client-ip-behind-dokploy-and-cloudflare.',
33
- 'Existing Vite configuration is preserved. Include @better-auth/core in ssr.noExternal to retain native async request storage in Bun production builds. See docs/deployment.md#server-build-configuration.',
34
- 'If .dockerignore is customized, merge the template exclusions before building: environment files, credentials, data/, and local Worker state must stay outside the image.'
31
+ 'Existing Vite configuration is preserved. Do not set paths.origin: the site derives its origin from the request and redirects other hostnames to SANDCMS_ORIGIN. Keep bun:sqlite and sharp in ssr.external and @better-auth/core in ssr.noExternal. See docs/deployment.md#server-build-configuration.',
32
+ 'An existing server hook must run cmsHandle first in sequence(): it enforces request size limits and handles health checks, redirects and media before other hooks.',
33
+ 'Set BODY_SIZE_LIMIT=10M wherever the site runs; setup adds it to .env.local and the Dockerfile sets it in the image. Setup adds commented proxy settings to .env.local; set SANDCMS_TRUSTED_PROXY_HEADER and ADDRESS_HEADER to the client IP header your reverse proxy sets.',
34
+ 'If .dockerignore is customized, merge the template exclusions before building: environment files, credentials and data/ must stay outside the image.'
35
35
  ];
36
36
  const report = migrationReport(plan, notes);
37
37
  console.log(report);
@@ -44,25 +44,14 @@ export async function setup(options) {
44
44
  const ignore = join(root, '.gitignore');
45
45
  const existingIgnore = existsSync(ignore) ? readFileSync(ignore, 'utf8') : '';
46
46
  appendFileSync(ignore, '\n' +
47
- [
48
- 'node_modules/',
49
- '.svelte-kit/',
50
- 'build/',
51
- '.env',
52
- '.env.*',
53
- '!.env.example',
54
- 'data/',
55
- '.wrangler/',
56
- '.dev.vars',
57
- '.dev.vars.*'
58
- ]
47
+ ['node_modules/', '.svelte-kit/', 'build/', '.env', '.env.*', '!.env.example', 'data/']
59
48
  .filter((s) => !existingIgnore.split('\n').includes(s))
60
49
  .join('\n') +
61
50
  '\n');
62
51
  const env = join(root, '.env.local'), previous = existsSync(env) ? readFileSync(env, 'utf8') : '';
63
52
  const previousSettings = parseEnv(previous);
64
53
  const settings = {
65
- BODY_SIZE_LIMIT: '1M',
54
+ BODY_SIZE_LIMIT: '10M',
66
55
  SANDCMS_DATABASE: options.database ?? './data/sandcms.sqlite',
67
56
  SANDCMS_ORIGIN: 'http://localhost:5410',
68
57
  SANDCMS_SECRET: crypto.randomUUID() + crypto.randomUUID()
@@ -70,11 +59,14 @@ export async function setup(options) {
70
59
  const additions = Object.entries(settings)
71
60
  .filter(([key]) => !previousSettings[key])
72
61
  .map(([key, v]) => `${key}=${v}`);
62
+ const mentioned = (key) => new RegExp(`^\\s*#?\\s*${key}\\s*=`, 'm').test(previous);
73
63
  const proxyExamples = ['SANDCMS_TRUSTED_PROXY_HEADER', 'ADDRESS_HEADER']
74
- .filter((key) => !new RegExp(`^\\s*#?\\s*${key}\\s*=`, 'm').test(previous))
75
- .map((key) => `# ${key}=cf-connecting-ip`);
64
+ .filter((key) => !mentioned(key))
65
+ .map((key) => `# ${key}=x-real-ip`);
76
66
  if (proxyExamples.length)
77
- additions.push('# Dokploy + Cloudflare: enable both settings in Dokploy runtime variables only after', '# restricting website ingress to Cloudflare and keeping the container port private.', '# See docs/deployment.md#client-ip-behind-dokploy-and-cloudflare.', ...proxyExamples);
67
+ additions.push('# Behind a reverse proxy, set both to the client IP header the proxy sets and overwrites,', '# in the host runtime variables. See docs/deployment.md.', ...proxyExamples);
68
+ if (!mentioned('SANDCMS_INDEXING'))
69
+ additions.push('# Preview sites: keep search engines out until launch.', '# SANDCMS_INDEXING=false');
78
70
  appendFileSync(env, '\n' + additions.join('\n') + '\n', { mode: 0o600 });
79
71
  chmodSync(env, 0o600);
80
72
  if (!options.skipInstall) {
@@ -93,7 +85,7 @@ export async function setup(options) {
93
85
  }))
94
86
  }));
95
87
  if (addons.length)
96
- await run(['bun', 'x', 'sv@0.17.1', 'add', ...addons], root);
88
+ await run(['bun', 'x', 'sv@1.4.0', 'add', ...addons], root);
97
89
  }
98
90
  const dbPath = options.database ?? previousSettings.SANDCMS_DATABASE ?? settings.SANDCMS_DATABASE;
99
91
  const target = resolve(root, dbPath);
@@ -117,7 +109,5 @@ export async function setup(options) {
117
109
  finally {
118
110
  store.close();
119
111
  }
120
- if (!options.yes && (await confirm('Configure and deploy Cloudflare media now?')))
121
- await configureWorker(root, name);
122
- console.log('Setup complete. Review sandcms/setup-report.md. Run bun run dev. In production: sandcms migrate, then sandcms user bootstrap against the mounted database.');
112
+ console.log('Setup complete. Review sandcms/setup-report.md. Run bun run dev. In production, set SANDCMS_AUTO_MIGRATE=true and, for the first start, SANDCMS_BOOTSTRAP_EMAIL; see docs/deployment.md.');
123
113
  }
@@ -1,7 +1,7 @@
1
1
  import { join } from 'node:path';
2
2
  import { readFileSync, existsSync } from 'node:fs';
3
3
  import { createTwoFilesPatch } from 'diff';
4
- import { planFiles, applyPlan, migrationReport, write, readManifest, routeConflicts } from './files.js';
4
+ import { PACKAGE_NAME, planFiles, applyPlan, migrationReport, write, readManifest, routeConflicts } from './files.js';
5
5
  import { confirm } from './prompts.js';
6
6
  import { loadDefinition } from '../blueprints/load.js';
7
7
  import { inspectMigrations } from '../server/db/store.js';
@@ -15,8 +15,27 @@ export async function upgrade(root, check = false, database) {
15
15
  'The website now validates SandCMS environment variables on start through src/env.ts. Ensure SANDCMS_ORIGIN and a 32-character SANDCMS_SECRET are set in every environment. See docs/upgrades.md#validated-environment-variables.',
16
16
  'Include @better-auth/core in ssr.noExternal in your Vite configuration, then rebuild and restart the website to fix concurrent image preview failures. Developer-owned configuration is preserved. See docs/deployment.md#server-build-configuration.',
17
17
  'From 0.5.0, database changes use incremental migrations. Back up with the installed package before updating, then run sandcms migrate. Changed pre-0.5.0 baselines still require a fresh database. See docs/upgrades.md.',
18
- 'Worker compatibility range: protocol 6 (Worker also accepts protocols 3, 4 and 5 for existing website processes). Deploy with sandcms worker update before upgrading website processes; expect temporary media downtime. Configure Worker R2 signing credentials, bucket CORS and staging lifecycle rules for direct uploads; run the incremental database migration; metadata inspection and encoding use remote transformations; verify both in staging. Purge old /media/* caches and keep R2 public access disabled. See docs/media.md.'
18
+ '0.7.0 stores media on the site volume instead of Cloudflare. Before deploying: check that no uploads are pending, take a backup, and make sure the volume has free space of at least 3 × the current media. See docs/upgrades.md.',
19
+ 'Confirm cmsHandle runs first in sequence() in src/hooks.server.ts: it enforces request size limits and handles health checks, host redirects, uploads and media before other hooks.',
20
+ 'Add sharp to ssr.external next to bun:sqlite in your Vite configuration. Remove paths.origin: the site now derives its origin from the request and redirects other hostnames to SANDCMS_ORIGIN.',
21
+ 'Set BODY_SIZE_LIMIT=10M. Overlapping (zero-downtime) and stop-then-start deploys both work. The generated Dockerfile includes a HEALTHCHECK on /_sandcms/health; railpack.json remains supported.',
22
+ 'Deploy with SANDCMS_WORKER_URL and SANDCMS_WORKER_TOKEN still set, run sandcms media import-r2 once, check the site, then remove the Worker variables. The Worker and its R2 bucket can be deleted after a restore from backup has been verified to contain the originals.'
19
23
  ];
24
+ const vite = ['vite.config.ts', 'vite.config.js']
25
+ .map((file) => join(root, file))
26
+ .filter(existsSync)
27
+ .map((file) => readFileSync(file, 'utf8'))
28
+ .join('\n');
29
+ if (/paths\s*:\s*\{[^}]*\borigin\b/.test(vite))
30
+ notes.push('Your Vite configuration sets paths.origin. Remove it so a domain change needs no rebuild.');
31
+ if (vite && !/['"]sharp['"]/.test(vite))
32
+ notes.push('Your Vite configuration does not list sharp in ssr.external yet.');
33
+ if (!plan.some((p) => p.path === 'Dockerfile'))
34
+ notes.push(`A Dockerfile with a HEALTHCHECK on /_sandcms/health is available at node_modules/${PACKAGE_NAME}/templates/Dockerfile. It was not added because this site builds with Railpack, and hosts that detect a Dockerfile switch builders. To switch, copy it to the project root; later upgrades then keep it current.`);
35
+ if (plan.some((p) => /^src\/lib\/server\/sandcms\/index\.[jt]s$/.test(p.path) && p.status === 'conflict'))
36
+ notes.push('Your src/lib/server/sandcms/index.ts is customized. Pass server: true to createCMS and call media.start() before storing the instance (close and rethrow on failure), so the data-volume lock is taken before the database opens. Pass SANDCMS_CANONICAL_REDIRECT as canonicalRedirect. See the proposed diff below.');
37
+ if (existsSync(join(root, 'sandcms/worker')))
38
+ notes.push('sandcms/worker/ is no longer used by SandCMS. Keep it until sandcms media import-r2 has been verified, then remove it together with the Cloudflare Worker.');
20
39
  if (database)
21
40
  notes.push('Pending DB migrations: ' +
22
41
  (inspectMigrations(database)
package/dist/env.d.ts CHANGED
@@ -28,6 +28,38 @@ export declare function sandcmsEnvVars({ building }?: SandcmsEnvOptions): {
28
28
  description: string;
29
29
  schema: (value: string | undefined) => string;
30
30
  };
31
+ SANDCMS_MEDIA_DIR: {
32
+ description: string;
33
+ schema: (value: string | undefined) => string | undefined;
34
+ };
35
+ SANDCMS_MEDIA_THREADS: {
36
+ description: string;
37
+ schema: (value: string | undefined) => number | undefined;
38
+ };
39
+ SANDCMS_REQUEST_LIMIT: {
40
+ description: string;
41
+ schema: (value: string | undefined) => number | undefined;
42
+ };
43
+ SANDCMS_INDEXING: {
44
+ description: string;
45
+ schema: (value: string | undefined) => boolean;
46
+ };
47
+ SANDCMS_CANONICAL_REDIRECT: {
48
+ description: string;
49
+ schema: (value: string | undefined) => boolean;
50
+ };
51
+ SANDCMS_SITE_RENAME: {
52
+ description: string;
53
+ schema: (value: string | undefined) => boolean;
54
+ };
55
+ SANDCMS_BOOTSTRAP_EMAIL: {
56
+ description: string;
57
+ schema: (value: string | undefined) => string | undefined;
58
+ };
59
+ SANDCMS_ALLOW_UNMOUNTED_DATA: {
60
+ description: string;
61
+ schema: (value: string | undefined) => boolean;
62
+ };
31
63
  SANDCMS_WORKER_TOKEN: {
32
64
  description: string;
33
65
  schema: (value: string | undefined) => string | undefined;
package/dist/env.js CHANGED
@@ -56,16 +56,66 @@ export function sandcmsEnvVars({ building = false } = {}) {
56
56
  return value;
57
57
  })
58
58
  },
59
+ SANDCMS_MEDIA_DIR: {
60
+ description: 'Media directory on the site volume. Defaults to <database directory>/media.',
61
+ schema: optional
62
+ },
63
+ SANDCMS_MEDIA_THREADS: {
64
+ description: 'CPU threads for image processing (default 1). More finishes batches sooner on an idle server; Docker still shares CPU fairly between sites under load.',
65
+ schema: (value) => {
66
+ if (!optional(value))
67
+ return undefined;
68
+ if (!/^[1-9]\d*$/.test(value))
69
+ throw new Error('Must be a positive whole number');
70
+ return Number(value);
71
+ }
72
+ },
73
+ SANDCMS_REQUEST_LIMIT: {
74
+ description: 'Largest request body in bytes outside chunked uploads (default 1 MB).',
75
+ schema: (value) => {
76
+ if (!optional(value))
77
+ return undefined;
78
+ if (!/^\d+$/.test(value.trim()) || !Number(value))
79
+ throw new Error('Must be a positive integer');
80
+ return Number(value);
81
+ }
82
+ },
83
+ SANDCMS_INDEXING: {
84
+ description: 'Set false on preview sites: sends X-Robots-Tag noindex and a disallow-all robots.txt.',
85
+ schema: (value) => boolean(value) !== 'false'
86
+ },
87
+ SANDCMS_CANONICAL_REDIRECT: {
88
+ description: 'Redirect other hostnames to SANDCMS_ORIGIN (default true). Behind a proxy that rewrites Host, set HOST_HEADER=x-forwarded-host instead of disabling this.',
89
+ schema: (value) => boolean(value) !== 'false'
90
+ },
91
+ SANDCMS_SITE_RENAME: {
92
+ description: 'Start once with true after renaming the project in config.yaml, so the data volume site-id follows the new name.',
93
+ schema: (value) => boolean(value) === 'true'
94
+ },
95
+ SANDCMS_BOOTSTRAP_EMAIL: {
96
+ description: 'On start with no users, create this admin and log a one-time password.',
97
+ schema: (value) => {
98
+ if (!optional(value))
99
+ return undefined;
100
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim()))
101
+ throw new Error('Must be an email address');
102
+ return value.trim();
103
+ }
104
+ },
105
+ SANDCMS_ALLOW_UNMOUNTED_DATA: {
106
+ description: 'Allow a production database outside a mounted volume (the directory must persist).',
107
+ schema: (value) => boolean(value) === 'true'
108
+ },
59
109
  SANDCMS_WORKER_TOKEN: {
60
- description: 'Media Worker token.',
110
+ description: 'Deprecated: legacy Cloudflare media Worker token, used only by sandcms media import-r2.',
61
111
  schema: optional
62
112
  },
63
113
  SANDCMS_WORKER_URL: {
64
- description: 'Overrides config media.workerUrl for this environment.',
114
+ description: 'Deprecated: legacy Cloudflare media Worker URL, used only by sandcms media import-r2.',
65
115
  schema: (value) => (optional(value) ? url(value) : undefined)
66
116
  },
67
117
  SANDCMS_TRUSTED_PROXY_HEADER: {
68
- description: 'Client IP header set by a trusted reverse proxy; see docs/deployment.md.',
118
+ description: 'Client IP header set by a trusted reverse proxy (e.g. x-real-ip); see docs/deployment.md.',
69
119
  schema: (value) => {
70
120
  const header = value?.trim();
71
121
  if (!header)
@@ -39,6 +39,7 @@ export declare function dashboardData(cms: CMS, mediaCount: number): {
39
39
  };
40
40
  };
41
41
  export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
42
+ theme: "system" | "light" | "dark";
42
43
  screen: string;
43
44
  user: {
44
45
  id: string;
@@ -70,21 +71,23 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
70
71
  export?: string[];
71
72
  }[];
72
73
  emailEnabled: boolean;
73
- workerUrl: string;
74
74
  mediaVersion: string;
75
75
  fileBlueprints: import("../index.ts").FileBlueprint[];
76
76
  defaultFileBlueprint: string;
77
77
  } | {
78
+ theme: "system" | "light" | "dark";
78
79
  screen: string;
79
80
  user: null;
80
81
  emailEnabled: boolean;
81
82
  next?: undefined;
82
83
  } | {
84
+ theme: "system" | "light" | "dark";
83
85
  screen: string;
84
86
  user: null;
85
87
  emailEnabled: boolean;
86
88
  next: string;
87
89
  } | {
90
+ theme: "system" | "light" | "dark";
88
91
  blueprint: import("../index.ts").Blueprint;
89
92
  entry: {
90
93
  id: string;
@@ -130,6 +133,9 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
130
133
  error: string | null;
131
134
  createdAt: number;
132
135
  searchText: string | null;
136
+ width: number | null;
137
+ height: number | null;
138
+ uploadAttempt: string | null;
133
139
  }[];
134
140
  relations: Relations;
135
141
  screen: string;
@@ -163,12 +169,12 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
163
169
  export?: string[];
164
170
  }[];
165
171
  emailEnabled: boolean;
166
- workerUrl: string;
167
172
  mediaVersion: string;
168
173
  fileBlueprints: import("../index.ts").FileBlueprint[];
169
174
  defaultFileBlueprint: string;
170
175
  next?: undefined;
171
176
  } | {
177
+ theme: "system" | "light" | "dark";
172
178
  assets: {
173
179
  expectedVersion: string;
174
180
  blueprint: string;
@@ -184,6 +190,9 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
184
190
  error: string | null;
185
191
  createdAt: number;
186
192
  searchText: string | null;
193
+ width: number | null;
194
+ height: number | null;
195
+ uploadAttempt: string | null;
187
196
  }[];
188
197
  relations: Relations;
189
198
  photographerCollection: string | undefined;
@@ -220,12 +229,12 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
220
229
  export?: string[];
221
230
  }[];
222
231
  emailEnabled: boolean;
223
- workerUrl: string;
224
232
  mediaVersion: string;
225
233
  fileBlueprints: import("../index.ts").FileBlueprint[];
226
234
  defaultFileBlueprint: string;
227
235
  next?: undefined;
228
236
  } | {
237
+ theme: "system" | "light" | "dark";
229
238
  blueprint: import("../index.ts").Blueprint;
230
239
  submissions: {
231
240
  id: string;
@@ -278,12 +287,12 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
278
287
  export?: string[];
279
288
  }[];
280
289
  emailEnabled: boolean;
281
- workerUrl: string;
282
290
  mediaVersion: string;
283
291
  fileBlueprints: import("../index.ts").FileBlueprint[];
284
292
  defaultFileBlueprint: string;
285
293
  next?: undefined;
286
294
  } | {
295
+ theme: "system" | "light" | "dark";
287
296
  invitations: {
288
297
  id: string;
289
298
  email: string;
@@ -330,7 +339,6 @@ export declare function adminLoad(cms: CMS, event: RequestEvent): Promise<{
330
339
  export?: string[];
331
340
  }[];
332
341
  emailEnabled: boolean;
333
- workerUrl: string;
334
342
  mediaVersion: string;
335
343
  fileBlueprints: import("../index.ts").FileBlueprint[];
336
344
  defaultFileBlueprint: string;
@@ -4,6 +4,7 @@ import { and, asc, count, desc, eq, inArray, sql } from 'drizzle-orm';
4
4
  import { requireUser } from './auth.js';
5
5
  import { documents, references, submissions, user } from './db/schema.js';
6
6
  import { blueprintIcon } from './blueprint-icons.js';
7
+ import { parseTheme, themeCookie } from '../admin/theme.js';
7
8
  const entryBlueprintIds = (cms) => cms.definition.blueprints.filter((b) => b.kind !== 'form').map((b) => b.id);
8
9
  const formBlueprintIds = (cms) => cms.definition.blueprints.filter((b) => b.kind === 'form').map((b) => b.id);
9
10
  // Matches String(draft.title ?? 'Untitled') without parsing every draft in JS.
@@ -98,6 +99,11 @@ export function dashboardData(cms, mediaCount) {
98
99
  };
99
100
  }
100
101
  export async function adminLoad(cms, event) {
102
+ // Rendered on the admin root during SSR so the chosen theme paints without a flash.
103
+ const theme = parseTheme(event.cookies.get(themeCookie));
104
+ return { ...(await screenLoad(cms, event)), theme };
105
+ }
106
+ async function screenLoad(cms, event) {
101
107
  const session = await cms.auth.api.getSession({ headers: event.request.headers }), path = event.params.path ?? '';
102
108
  // Preserve notification links through sign-in, accepting only local form paths.
103
109
  const requestedNext = event.url.searchParams.get('next') ?? '';
@@ -129,7 +135,6 @@ export async function adminLoad(cms, event) {
129
135
  navigationIcon: blueprintIcon(blueprint)
130
136
  })),
131
137
  emailEnabled: cms.email.enabled,
132
- workerUrl: cms.media.workerUrl,
133
138
  mediaVersion: cms.media.version,
134
139
  fileBlueprints: fileBlueprints(cms.definition),
135
140
  defaultFileBlueprint: getFileBlueprint(cms.definition).id
@@ -1,4 +1,6 @@
1
1
  import type { CMS } from './cms.js';
2
+ /** Chunk endpoint of a chunked upload (`media/upload/{id}`), relative to `/api/cms/`. */
3
+ export declare const uploadChunkRoute: (path: string) => boolean;
2
4
  export declare function apiKeyRoute(path: string, method: string): boolean;
3
5
  export declare function apiPrincipal(cms: CMS, request: Request, path: string): Promise<{
4
6
  user: {
@@ -29,3 +31,5 @@ export declare function apiPrincipal(cms: CMS, request: Request, path: string):
29
31
  };
30
32
  keyId: null;
31
33
  }>;
34
+ /** User ID of the caller: the API key owner, or the signed-in admin/editor (with the origin check for writes). */
35
+ export declare function principalUserId(cms: CMS, request: Request, path: string): Promise<string>;
@@ -14,8 +14,13 @@ const writes = new Set([
14
14
  'media/retry',
15
15
  'media/delete'
16
16
  ]);
17
+ const chunkRoute = /^media\/upload\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
+ /** Chunk endpoint of a chunked upload (`media/upload/{id}`), relative to `/api/cms/`. */
19
+ export const uploadChunkRoute = (path) => chunkRoute.test(path);
17
20
  export function apiKeyRoute(path, method) {
18
- return (method === 'GET' && reads.has(path)) || (method === 'POST' && writes.has(path));
21
+ return ((method === 'GET' && reads.has(path)) ||
22
+ (method === 'POST' && writes.has(path)) ||
23
+ ((method === 'PUT' || method === 'GET') && uploadChunkRoute(path)));
19
24
  }
20
25
  export async function apiPrincipal(cms, request, path) {
21
26
  // An explicitly supplied credential never falls back to a browser cookie.
@@ -30,7 +35,8 @@ export async function apiPrincipal(cms, request, path) {
30
35
  }
31
36
  if (!apiKeyRoute(path, request.method))
32
37
  error(403, 'API keys can only access content and media');
33
- const action = request.method === 'GET' ? 'read' : 'write';
38
+ // Chunk status (GET) belongs to an upload, so it needs the same write permission as PUT.
39
+ const action = request.method === 'GET' && !uploadChunkRoute(path) ? 'read' : 'write';
34
40
  if (!result.key.permissions?.cms?.includes(action))
35
41
  error(403, 'API key permission denied');
36
42
  const owner = cms.store.db.select().from(user).where(eq(user.id, result.key.referenceId)).get();
@@ -50,3 +56,10 @@ export async function apiPrincipal(cms, request, path) {
50
56
  error(403, 'Change your temporary password first');
51
57
  return { user: session.user, keyId: null };
52
58
  }
59
+ /** User ID of the caller: the API key owner, or the signed-in admin/editor (with the origin check for writes). */
60
+ export async function principalUserId(cms, request, path) {
61
+ const { user } = await apiPrincipal(cms, request, path);
62
+ if (!['admin', 'editor'].includes(user.role ?? ''))
63
+ error(403, 'You cannot access the CMS');
64
+ return user.id;
65
+ }
@@ -31,6 +31,9 @@ export declare function mediaPage(cms: CMS, params: URLSearchParams): {
31
31
  error: string | null;
32
32
  createdAt: number;
33
33
  searchText: string | null;
34
+ width: number | null;
35
+ height: number | null;
36
+ uploadAttempt: string | null;
34
37
  }[];
35
38
  nextCursor: string | null;
36
39
  };
@@ -9,6 +9,7 @@ import { eq, lt, desc } from 'drizzle-orm';
9
9
  import { contentPage, mediaPage } from './api-pagination.js';
10
10
  import { globalSearch } from './search.js';
11
11
  import { ValidationError } from '../blueprints/validate.js';
12
+ import { MediaRequestError } from './media/contracts.js';
12
13
  const replayRetention = 48 * 60 * 60 * 1000;
13
14
  const lastPruned = new WeakMap();
14
15
  function orderedJson(value) {
@@ -269,9 +270,9 @@ export async function apiHandler(cms, event) {
269
270
  name: body.name,
270
271
  type: body.type,
271
272
  size: body.size
272
- }, blueprint || undefined));
273
+ }, blueprint || undefined, { userId: session.user.id }));
273
274
  case 'media/upload/complete':
274
- return json(cms.media.completeUpload(id));
275
+ return json(await cms.media.completeUpload(id));
275
276
  case 'media/update':
276
277
  cms.media.updateMetadata(id, body.metadata);
277
278
  break;
@@ -331,6 +332,8 @@ export async function apiHandler(cms, event) {
331
332
  return json({ ok: true });
332
333
  }
333
334
  catch (e) {
335
+ if (e instanceof MediaRequestError)
336
+ return json({ error: e.message }, { status: e.status });
334
337
  if (e && typeof e === 'object' && 'status' in e)
335
338
  throw e;
336
339
  return json({
@@ -56,21 +56,22 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
56
56
  plugins: [{
57
57
  id: "two-factor";
58
58
  version: string;
59
+ shouldRequireTwoFactor: (ctx: import("better-auth").GenericEndpointContext) => Promise<boolean>;
59
60
  endpoints: {
60
61
  enableTwoFactor: import("better-auth").StrictEndpoint<"/two-factor/enable", {
61
62
  method: "POST";
62
63
  body: import("better-auth").ZodObject<{
63
64
  password: import("better-auth").ZodOptional<import("better-auth").ZodString>;
64
65
  method: import("better-auth").ZodDefault<import("better-auth").ZodEnum<{
65
- otp: "otp";
66
66
  totp: "totp";
67
+ otp: "otp";
67
68
  }>>;
68
69
  issuer: import("better-auth").ZodOptional<import("better-auth").ZodString>;
69
70
  }, import("zod/v4/core").$strip> | import("better-auth").ZodObject<{
70
71
  password: import("better-auth").ZodString;
71
72
  method: import("better-auth").ZodDefault<import("better-auth").ZodEnum<{
72
- otp: "otp";
73
73
  totp: "totp";
74
+ otp: "otp";
74
75
  }>>;
75
76
  issuer: import("better-auth").ZodOptional<import("better-auth").ZodString>;
76
77
  }, import("zod/v4/core").$strip>;
@@ -298,7 +299,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
298
299
  };
299
300
  }, {
300
301
  token: string | undefined;
301
- user: (Record<string, any> & {
302
+ user: ({
302
303
  id: string;
303
304
  createdAt: Date;
304
305
  updatedAt: Date;
@@ -306,7 +307,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
306
307
  emailVerified: boolean;
307
308
  name: string;
308
309
  image?: string | null | undefined;
309
- }) | import("better-auth/plugins").UserWithTwoFactor;
310
+ } & Record<string, any>) | import("better-auth/plugins").UserWithTwoFactor;
310
311
  }>;
311
312
  generateBackupCodes: import("better-auth").StrictEndpoint<"/two-factor/generate-backup-codes", {
312
313
  method: "POST";
@@ -493,7 +494,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
493
494
  user: import("better-auth/plugins").UserWithTwoFactor;
494
495
  } | {
495
496
  token: string;
496
- user: Record<string, any> & {
497
+ user: {
497
498
  id: string;
498
499
  createdAt: Date;
499
500
  updatedAt: Date;
@@ -501,7 +502,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
501
502
  emailVerified: boolean;
502
503
  name: string;
503
504
  image?: string | null | undefined;
504
- };
505
+ } & Record<string, any>;
505
506
  }>;
506
507
  generateTOTP: import("better-auth").StrictEndpoint<string, {
507
508
  method: "POST";
@@ -624,7 +625,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
624
625
  user: import("better-auth/plugins").UserWithTwoFactor;
625
626
  } | {
626
627
  token: string;
627
- user: Record<string, any> & {
628
+ user: {
628
629
  id: string;
629
630
  createdAt: Date;
630
631
  updatedAt: Date;
@@ -632,7 +633,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
632
633
  emailVerified: boolean;
633
634
  name: string;
634
635
  image?: string | null | undefined;
635
- };
636
+ } & Record<string, any>;
636
637
  }>;
637
638
  };
638
639
  options: NoInfer<{
@@ -859,7 +860,7 @@ export declare function createAuth(store: Store, options: AuthOptions): import("
859
860
  } | null) => void;
860
861
  socialProviders: import("better-auth").OAuthProvider[];
861
862
  authCookies: import("better-auth").BetterAuthCookies;
862
- logger: ReturnType<(options?: import("better-auth").Logger | undefined) => import("better-auth").InternalLogger>;
863
+ logger: ReturnType<typeof import("better-auth").createLogger>;
863
864
  rateLimit: {
864
865
  enabled: boolean;
865
866
  window: number;