sandcms 0.6.2 → 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 (260) hide show
  1. package/README.md +14 -10
  2. package/dist/admin/Account.svelte +286 -83
  3. package/dist/admin/Admin.svelte +14 -1
  4. package/dist/admin/ApiKeys.svelte +146 -79
  5. package/dist/admin/AssetAttachment.svelte +10 -12
  6. package/dist/admin/AssetAttachment.svelte.d.ts +0 -1
  7. package/dist/admin/BlueprintFields.svelte +20 -5
  8. package/dist/admin/BlueprintFields.svelte.d.ts +2 -1
  9. package/dist/admin/Collection.svelte +111 -54
  10. package/dist/admin/Dashboard.svelte +3 -37
  11. package/dist/admin/DateField.svelte +75 -0
  12. package/dist/admin/DateField.svelte.d.ts +11 -0
  13. package/dist/admin/Editor.svelte +70 -65
  14. package/dist/admin/Fields.svelte +24 -23
  15. package/dist/admin/Fields.svelte.d.ts +0 -1
  16. package/dist/admin/FocusPicker.svelte +1 -2
  17. package/dist/admin/Gallery.svelte +2 -7
  18. package/dist/admin/Gallery.svelte.d.ts +0 -1
  19. package/dist/admin/GlobalSearch.svelte +54 -26
  20. package/dist/admin/HoverHint.svelte +37 -0
  21. package/dist/admin/HoverHint.svelte.d.ts +8 -0
  22. package/dist/admin/Inbox.svelte +6 -11
  23. package/dist/admin/LinkField.svelte +128 -66
  24. package/dist/admin/LinkField.svelte.d.ts +0 -1
  25. package/dist/admin/Login.svelte +0 -1
  26. package/dist/admin/MediaLibrary.svelte +70 -56
  27. package/dist/admin/MediaPicker.svelte +62 -55
  28. package/dist/admin/MediaPicker.svelte.d.ts +0 -1
  29. package/dist/admin/NotificationSettings.svelte +35 -27
  30. package/dist/admin/RichText.svelte +2 -2
  31. package/dist/admin/RowMenu.svelte +28 -0
  32. package/dist/admin/RowMenu.svelte.d.ts +10 -0
  33. package/dist/admin/SearchList.svelte +51 -14
  34. package/dist/admin/Shell.svelte +64 -29
  35. package/dist/admin/ThemePicker.svelte +72 -0
  36. package/dist/admin/ThemePicker.svelte.d.ts +18 -0
  37. package/dist/admin/UploadButton.svelte +2 -1
  38. package/dist/admin/UploadProgress.svelte +24 -0
  39. package/dist/admin/UploadProgress.svelte.d.ts +7 -0
  40. package/dist/admin/Users.svelte +106 -50
  41. package/dist/admin/client.d.ts +5 -670
  42. package/dist/admin/client.js +20 -1
  43. package/dist/admin/components/ui/alert/alert.svelte.d.ts +3 -13
  44. package/dist/admin/components/ui/attachment/attachment-media.svelte.d.ts +3 -13
  45. package/dist/admin/components/ui/attachment/attachment.svelte.d.ts +6 -26
  46. package/dist/admin/components/ui/badge/badge.svelte.d.ts +7 -25
  47. package/dist/admin/components/ui/button/button.svelte.d.ts +15 -53
  48. package/dist/admin/components/ui/calendar/calendar-caption.svelte +76 -0
  49. package/dist/admin/components/ui/calendar/calendar-caption.svelte.d.ts +19 -0
  50. package/dist/admin/components/ui/calendar/calendar-cell.svelte +19 -0
  51. package/dist/admin/components/ui/calendar/calendar-cell.svelte.d.ts +4 -0
  52. package/dist/admin/components/ui/calendar/calendar-day.svelte +33 -0
  53. package/dist/admin/components/ui/calendar/calendar-day.svelte.d.ts +4 -0
  54. package/dist/admin/components/ui/calendar/calendar-grid-body.svelte +12 -0
  55. package/dist/admin/components/ui/calendar/calendar-grid-body.svelte.d.ts +4 -0
  56. package/dist/admin/components/ui/calendar/calendar-grid-head.svelte +12 -0
  57. package/dist/admin/components/ui/calendar/calendar-grid-head.svelte.d.ts +4 -0
  58. package/dist/admin/components/ui/calendar/calendar-grid-row.svelte +12 -0
  59. package/dist/admin/components/ui/calendar/calendar-grid-row.svelte.d.ts +4 -0
  60. package/dist/admin/components/ui/calendar/calendar-grid.svelte +16 -0
  61. package/dist/admin/components/ui/calendar/calendar-grid.svelte.d.ts +4 -0
  62. package/dist/admin/components/ui/calendar/calendar-head-cell.svelte +19 -0
  63. package/dist/admin/components/ui/calendar/calendar-head-cell.svelte.d.ts +4 -0
  64. package/dist/admin/components/ui/calendar/calendar-header.svelte +19 -0
  65. package/dist/admin/components/ui/calendar/calendar-header.svelte.d.ts +4 -0
  66. package/dist/admin/components/ui/calendar/calendar-heading.svelte +16 -0
  67. package/dist/admin/components/ui/calendar/calendar-heading.svelte.d.ts +4 -0
  68. package/dist/admin/components/ui/calendar/calendar-month-select.svelte +48 -0
  69. package/dist/admin/components/ui/calendar/calendar-month-select.svelte.d.ts +4 -0
  70. package/dist/admin/components/ui/calendar/calendar-month.svelte +15 -0
  71. package/dist/admin/components/ui/calendar/calendar-month.svelte.d.ts +5 -0
  72. package/dist/admin/components/ui/calendar/calendar-months.svelte +19 -0
  73. package/dist/admin/components/ui/calendar/calendar-months.svelte.d.ts +5 -0
  74. package/dist/admin/components/ui/calendar/calendar-nav.svelte +19 -0
  75. package/dist/admin/components/ui/calendar/calendar-nav.svelte.d.ts +5 -0
  76. package/dist/admin/components/ui/calendar/calendar-next-button.svelte +37 -0
  77. package/dist/admin/components/ui/calendar/calendar-next-button.svelte.d.ts +8 -0
  78. package/dist/admin/components/ui/calendar/calendar-prev-button.svelte +37 -0
  79. package/dist/admin/components/ui/calendar/calendar-prev-button.svelte.d.ts +8 -0
  80. package/dist/admin/components/ui/calendar/calendar-year-select.svelte +47 -0
  81. package/dist/admin/components/ui/calendar/calendar-year-select.svelte.d.ts +4 -0
  82. package/dist/admin/components/ui/calendar/calendar.svelte +115 -0
  83. package/dist/admin/components/ui/calendar/calendar.svelte.d.ts +21 -0
  84. package/dist/admin/components/ui/calendar/index.d.ts +19 -0
  85. package/dist/admin/components/ui/calendar/index.js +21 -0
  86. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-checkbox-group.svelte +16 -0
  87. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-checkbox-group.svelte.d.ts +4 -0
  88. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-checkbox-item.svelte +46 -0
  89. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-checkbox-item.svelte.d.ts +9 -0
  90. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-content.svelte +31 -0
  91. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-content.svelte.d.ts +10 -0
  92. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-group-heading.svelte +22 -0
  93. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-group-heading.svelte.d.ts +8 -0
  94. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-group.svelte +7 -0
  95. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-group.svelte.d.ts +4 -0
  96. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-item.svelte +27 -0
  97. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-item.svelte.d.ts +8 -0
  98. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-label.svelte +24 -0
  99. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-label.svelte.d.ts +8 -0
  100. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-portal.svelte +7 -0
  101. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-portal.svelte.d.ts +3 -0
  102. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-radio-group.svelte +16 -0
  103. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-radio-group.svelte.d.ts +4 -0
  104. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-radio-item.svelte +36 -0
  105. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-radio-item.svelte.d.ts +4 -0
  106. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-separator.svelte +17 -0
  107. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-separator.svelte.d.ts +4 -0
  108. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-shortcut.svelte +23 -0
  109. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-shortcut.svelte.d.ts +5 -0
  110. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte +31 -0
  111. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte.d.ts +10 -0
  112. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelte +29 -0
  113. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelte.d.ts +7 -0
  114. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-sub.svelte +7 -0
  115. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-sub.svelte.d.ts +3 -0
  116. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-trigger.svelte +7 -0
  117. package/dist/admin/components/ui/dropdown-menu/dropdown-menu-trigger.svelte.d.ts +4 -0
  118. package/dist/admin/components/ui/dropdown-menu/dropdown-menu.svelte +7 -0
  119. package/dist/admin/components/ui/dropdown-menu/dropdown-menu.svelte.d.ts +3 -0
  120. package/dist/admin/components/ui/dropdown-menu/index.d.ts +18 -0
  121. package/dist/admin/components/ui/dropdown-menu/index.js +18 -0
  122. package/dist/admin/components/ui/input-otp/index.d.ts +5 -0
  123. package/dist/admin/components/ui/input-otp/index.js +5 -0
  124. package/dist/admin/components/ui/input-otp/input-otp-group.svelte +23 -0
  125. package/dist/admin/components/ui/input-otp/input-otp-group.svelte.d.ts +5 -0
  126. package/dist/admin/components/ui/input-otp/input-otp-separator.svelte +27 -0
  127. package/dist/admin/components/ui/input-otp/input-otp-separator.svelte.d.ts +5 -0
  128. package/dist/admin/components/ui/input-otp/input-otp-slot.svelte +29 -0
  129. package/dist/admin/components/ui/input-otp/input-otp-slot.svelte.d.ts +4 -0
  130. package/dist/admin/components/ui/input-otp/input-otp.svelte +24 -0
  131. package/dist/admin/components/ui/input-otp/input-otp.svelte.d.ts +4 -0
  132. package/dist/admin/components/ui/popover/index.d.ts +9 -0
  133. package/dist/admin/components/ui/popover/index.js +11 -0
  134. package/dist/admin/components/ui/popover/popover-close.svelte +7 -0
  135. package/dist/admin/components/ui/popover/popover-close.svelte.d.ts +4 -0
  136. package/dist/admin/components/ui/popover/popover-content.svelte +31 -0
  137. package/dist/admin/components/ui/popover/popover-content.svelte.d.ts +10 -0
  138. package/dist/admin/components/ui/popover/popover-description.svelte +20 -0
  139. package/dist/admin/components/ui/popover/popover-description.svelte.d.ts +5 -0
  140. package/dist/admin/components/ui/popover/popover-header.svelte +20 -0
  141. package/dist/admin/components/ui/popover/popover-header.svelte.d.ts +5 -0
  142. package/dist/admin/components/ui/popover/popover-portal.svelte +7 -0
  143. package/dist/admin/components/ui/popover/popover-portal.svelte.d.ts +3 -0
  144. package/dist/admin/components/ui/popover/popover-title.svelte +20 -0
  145. package/dist/admin/components/ui/popover/popover-title.svelte.d.ts +5 -0
  146. package/dist/admin/components/ui/popover/popover-trigger.svelte +17 -0
  147. package/dist/admin/components/ui/popover/popover-trigger.svelte.d.ts +4 -0
  148. package/dist/admin/components/ui/popover/popover.svelte +7 -0
  149. package/dist/admin/components/ui/popover/popover.svelte.d.ts +3 -0
  150. package/dist/admin/components/ui/switch/switch.svelte +2 -2
  151. package/dist/admin/components/ui/toggle/toggle.svelte.d.ts +6 -26
  152. package/dist/admin/components/ui/tooltip/index.d.ts +6 -0
  153. package/dist/admin/components/ui/tooltip/index.js +8 -0
  154. package/dist/admin/components/ui/tooltip/tooltip-content.svelte +48 -0
  155. package/dist/admin/components/ui/tooltip/tooltip-content.svelte.d.ts +11 -0
  156. package/dist/admin/components/ui/tooltip/tooltip-portal.svelte +7 -0
  157. package/dist/admin/components/ui/tooltip/tooltip-portal.svelte.d.ts +4 -0
  158. package/dist/admin/components/ui/tooltip/tooltip-provider.svelte +7 -0
  159. package/dist/admin/components/ui/tooltip/tooltip-provider.svelte.d.ts +4 -0
  160. package/dist/admin/components/ui/tooltip/tooltip-trigger.svelte +7 -0
  161. package/dist/admin/components/ui/tooltip/tooltip-trigger.svelte.d.ts +25 -0
  162. package/dist/admin/components/ui/tooltip/tooltip.svelte +7 -0
  163. package/dist/admin/components/ui/tooltip/tooltip.svelte.d.ts +25 -0
  164. package/dist/admin/generated/admin.css +1298 -234
  165. package/dist/admin/slug.d.ts +1 -0
  166. package/dist/admin/slug.js +6 -0
  167. package/dist/admin/theme-context.d.ts +7 -0
  168. package/dist/admin/theme-context.js +3 -0
  169. package/dist/admin/theme.d.ts +7 -0
  170. package/dist/admin/theme.js +14 -0
  171. package/dist/admin/types.d.ts +2 -1
  172. package/dist/admin/uploads.d.ts +8 -1
  173. package/dist/admin/uploads.js +94 -16
  174. package/dist/blueprints/files.js +1 -0
  175. package/dist/blueprints/load.js +7 -2
  176. package/dist/blueprints/types.d.ts +4 -1
  177. package/dist/cli/doctor.d.ts +3 -1
  178. package/dist/cli/doctor.js +85 -30
  179. package/dist/cli/files.d.ts +2 -6
  180. package/dist/cli/files.js +11 -2
  181. package/dist/cli/index.js +99 -31
  182. package/dist/cli/scaffold.js +8 -8
  183. package/dist/cli/setup.js +16 -26
  184. package/dist/cli/upgrade.js +21 -2
  185. package/dist/env.d.ts +32 -0
  186. package/dist/env.js +53 -3
  187. package/dist/server/admin-load.d.ts +13 -5
  188. package/dist/server/admin-load.js +8 -3
  189. package/dist/server/api-access.d.ts +4 -0
  190. package/dist/server/api-access.js +15 -2
  191. package/dist/server/api-pagination.d.ts +3 -0
  192. package/dist/server/api.js +11 -3
  193. package/dist/server/auth.d.ts +11 -9
  194. package/dist/server/auth.js +23 -0
  195. package/dist/server/cms.d.ts +65 -18
  196. package/dist/server/cms.js +62 -6
  197. package/dist/server/db/migration-data.js +4 -0
  198. package/dist/server/db/migrations/0009_local_media.sql +9 -0
  199. package/dist/server/db/migrations/meta/0009_snapshot.json +1763 -0
  200. package/dist/server/db/migrations/meta/_journal.json +7 -0
  201. package/dist/server/db/schema.d.ts +119 -2
  202. package/dist/server/db/schema.js +15 -3
  203. package/dist/server/hooks.js +155 -81
  204. package/dist/server/media/contracts.d.ts +115 -0
  205. package/dist/server/media/contracts.js +12 -0
  206. package/dist/server/media/deletions.d.ts +2 -1
  207. package/dist/server/media/deletions.js +3 -3
  208. package/dist/server/media/delivery.js +7 -11
  209. package/dist/server/media/import-r2.d.ts +56 -0
  210. package/dist/server/media/import-r2.js +342 -0
  211. package/dist/server/media/processor-child.d.ts +2 -0
  212. package/dist/server/media/processor-child.js +236 -0
  213. package/dist/server/media/processor.d.ts +51 -0
  214. package/dist/server/media/processor.js +135 -0
  215. package/dist/server/media/render-math.d.ts +24 -0
  216. package/dist/server/media/render-math.js +50 -0
  217. package/dist/server/media/runner.d.ts +30 -1
  218. package/dist/server/media/runner.js +418 -165
  219. package/dist/server/media/service.d.ts +56 -10
  220. package/dist/server/media/service.js +309 -98
  221. package/dist/server/media/storage.d.ts +5 -0
  222. package/dist/server/media/storage.js +279 -0
  223. package/dist/server/media/svg.d.ts +5 -0
  224. package/dist/server/media/svg.js +142 -0
  225. package/dist/server/media/upload-ticket.d.ts +12 -0
  226. package/dist/server/media/upload-ticket.js +35 -0
  227. package/dist/server/media/verify.d.ts +36 -0
  228. package/dist/server/media/verify.js +109 -0
  229. package/dist/server/platform/http.d.ts +27 -0
  230. package/dist/server/platform/http.js +77 -0
  231. package/dist/server/platform/index.d.ts +52 -0
  232. package/dist/server/platform/index.js +98 -0
  233. package/dist/server/platform/snapshots.d.ts +18 -0
  234. package/dist/server/platform/snapshots.js +110 -0
  235. package/dist/server/platform/volume.d.ts +20 -0
  236. package/dist/server/platform/volume.js +60 -0
  237. package/dist/worker/svg.d.ts +1 -5
  238. package/dist/worker/svg.js +2 -142
  239. package/docs/acceptance.md +6 -4
  240. package/docs/api.md +42 -4
  241. package/docs/cloudflare.md +48 -142
  242. package/docs/content.md +2 -2
  243. package/docs/deployment.md +159 -57
  244. package/docs/forms.md +1 -1
  245. package/docs/media.md +85 -21
  246. package/docs/package.md +21 -18
  247. package/docs/plans/0.7-self-hosted.md +264 -0
  248. package/docs/releases.md +27 -1
  249. package/docs/upgrades.md +44 -6
  250. package/package.json +38 -37
  251. package/templates/Dockerfile +28 -0
  252. package/templates/integration.ts +18 -2
  253. package/templates/railpack.json +1 -1
  254. package/templates/sandcms/blueprints/files/image.yaml +1 -1
  255. package/templates/sandcms/config.yaml +0 -1
  256. package/dist/cli/cloudflare.d.ts +0 -8
  257. package/dist/cli/cloudflare.js +0 -135
  258. package/templates/sandcms/worker/index.ts +0 -1
  259. package/templates/sandcms/worker/local.ts +0 -1
  260. package/templates/sandcms/worker/wrangler.jsonc +0 -6
@@ -0,0 +1,5 @@
1
+ import { type MediaStorage } from './contracts.js';
2
+ /** Same shape as the public delivery route: `{id}/{version}/{preset}-{size}.{format}`. */
3
+ export declare const variantKeyPattern: RegExp;
4
+ /** Local-disk media storage. See contracts.ts for the layout and durability rules. */
5
+ export declare function createLocalStorage(root: string): MediaStorage;
@@ -0,0 +1,279 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { copyFile, link, mkdir, open, readdir, rename, rm, rmdir, stat, statfs, unlink } from 'node:fs/promises';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { MediaRequestError } from './contracts.js';
6
+ const idPattern = /^[a-f0-9-]{36}$/;
7
+ /** Same shape as the public delivery route: `{id}/{version}/{preset}-{size}.{format}`. */
8
+ export const variantKeyPattern = /^([a-f0-9-]{36})\/([a-f0-9]{16})\/([a-z][a-z0-9_-]*)-(\d+)\.(webp|avif|jpeg|svg)$/;
9
+ const usageTtl = 30_000;
10
+ function assertId(id) {
11
+ if (!idPattern.test(id))
12
+ throw new Error('Invalid media ID');
13
+ }
14
+ function assertKey(key) {
15
+ if (!variantKeyPattern.test(key))
16
+ throw new Error('Invalid variant key');
17
+ }
18
+ const temporary = (path) => `${path}.${crypto.randomUUID()}.partial`;
19
+ async function syncFile(path) {
20
+ const handle = await open(path, 'r+');
21
+ try {
22
+ await handle.sync();
23
+ }
24
+ finally {
25
+ await handle.close();
26
+ }
27
+ }
28
+ async function syncDir(path) {
29
+ const handle = await open(path, 'r');
30
+ try {
31
+ await handle.sync();
32
+ }
33
+ finally {
34
+ await handle.close();
35
+ }
36
+ }
37
+ /** mkdir -p that fsyncs the parent of every directory it creates, so new entries survive a crash. */
38
+ async function ensureDir(path) {
39
+ const created = await mkdir(path, { recursive: true });
40
+ if (!created)
41
+ return;
42
+ for (let dir = path; dir.length >= created.length; dir = dirname(dir))
43
+ await syncDir(dirname(dir));
44
+ }
45
+ /** Durably move `from` to `to`: fsync the file, rename (copy across filesystems), fsync the target directory. */
46
+ async function commit(from, to) {
47
+ await ensureDir(dirname(to));
48
+ await syncFile(from);
49
+ try {
50
+ await rename(from, to);
51
+ }
52
+ catch (error) {
53
+ if (error.code !== 'EXDEV')
54
+ throw error;
55
+ const partial = temporary(to);
56
+ try {
57
+ await copyFile(from, partial);
58
+ await syncFile(partial);
59
+ await rename(partial, to);
60
+ }
61
+ catch (cause) {
62
+ await rm(partial, { force: true });
63
+ throw cause;
64
+ }
65
+ await rm(from, { force: true });
66
+ }
67
+ await syncDir(dirname(to));
68
+ }
69
+ async function size(path) {
70
+ let total = 0;
71
+ const entries = await readdir(path, { withFileTypes: true, recursive: true }).catch((error) => {
72
+ if (error.code === 'ENOENT')
73
+ return [];
74
+ throw error;
75
+ });
76
+ for (const entry of entries)
77
+ if (entry.isFile())
78
+ total += (await stat(join(entry.parentPath, entry.name)).catch(() => ({ size: 0 }))).size;
79
+ return total;
80
+ }
81
+ /** Local-disk media storage. See contracts.ts for the layout and durability rules. */
82
+ export function createLocalStorage(root) {
83
+ root = resolve(root);
84
+ const originals = join(root, 'originals'), variants = join(root, 'variants'), tmp = join(root, 'tmp');
85
+ const uploadDir = (id, attempt) => {
86
+ assertId(id);
87
+ assertId(attempt);
88
+ return join(tmp, id, attempt);
89
+ };
90
+ const stagedPath = (id, attempt) => join(uploadDir(id, attempt), 'staged');
91
+ const chunkIndexes = async (dir) => (await readdir(dir).catch(() => []))
92
+ .filter((name) => /^(0|[1-9]\d*)$/.test(name))
93
+ .map(Number)
94
+ .sort((a, b) => a - b);
95
+ let usedBytes;
96
+ return {
97
+ root,
98
+ async writeChunk(id, attempt, index, body, maxBytes, exact = false) {
99
+ if (!Number.isSafeInteger(index) || index < 0)
100
+ throw new Error('Invalid chunk index');
101
+ const dir = uploadDir(id, attempt);
102
+ await ensureDir(dir);
103
+ const target = join(dir, String(index)), partial = temporary(target);
104
+ const handle = await open(partial, 'wx');
105
+ let written = 0;
106
+ try {
107
+ const reader = body.getReader();
108
+ try {
109
+ for (;;) {
110
+ const { done, value } = await reader.read();
111
+ if (done)
112
+ break;
113
+ written += value.byteLength;
114
+ if (written > maxBytes)
115
+ throw new MediaRequestError(413, 'Chunk exceeds the chunk size');
116
+ for (let offset = 0; offset < value.byteLength;)
117
+ offset += (await handle.write(value, offset)).bytesWritten;
118
+ }
119
+ }
120
+ catch (error) {
121
+ await reader.cancel().catch(() => { });
122
+ throw error;
123
+ }
124
+ if (exact && written !== maxBytes)
125
+ throw new MediaRequestError(400, `Chunk ${index} must contain ${maxBytes} bytes`);
126
+ await handle.sync();
127
+ }
128
+ catch (error) {
129
+ await handle.close();
130
+ await rm(partial, { force: true });
131
+ throw error;
132
+ }
133
+ await handle.close();
134
+ await rename(partial, target);
135
+ await syncDir(dir);
136
+ return written;
137
+ },
138
+ async listChunks(id, attempt) {
139
+ return chunkIndexes(uploadDir(id, attempt));
140
+ },
141
+ async assemble(id, attempt, totalBytes) {
142
+ const dir = uploadDir(id, attempt), staged = stagedPath(id, attempt);
143
+ const indexes = await chunkIndexes(dir);
144
+ // A completed assembly is authoritative; chunks re-sent after it carry the same bytes.
145
+ if (existsSync(staged)) {
146
+ if ((await stat(staged)).size !== totalBytes)
147
+ throw new MediaRequestError(400, 'Upload size does not match');
148
+ for (const index of indexes)
149
+ await rm(join(dir, String(index)), { force: true });
150
+ return staged;
151
+ }
152
+ if (!indexes.length || indexes.some((value, i) => value !== i))
153
+ throw new MediaRequestError(400, 'Upload is incomplete. Send the missing chunks again.');
154
+ let total = 0;
155
+ for (const index of indexes)
156
+ total += (await stat(join(dir, String(index)))).size;
157
+ if (total !== totalBytes)
158
+ throw new MediaRequestError(400, 'Upload size does not match');
159
+ const partial = temporary(staged);
160
+ const handle = await open(partial, 'wx');
161
+ try {
162
+ for (const index of indexes) {
163
+ const source = await open(join(dir, String(index)), 'r');
164
+ try {
165
+ const buffer = new Uint8Array(1024 * 1024);
166
+ for (;;) {
167
+ const { bytesRead } = await source.read(buffer, 0, buffer.length, null);
168
+ if (!bytesRead)
169
+ break;
170
+ for (let offset = 0; offset < bytesRead;)
171
+ offset += (await handle.write(buffer, offset, bytesRead - offset)).bytesWritten;
172
+ }
173
+ }
174
+ finally {
175
+ await source.close();
176
+ }
177
+ }
178
+ await handle.sync();
179
+ }
180
+ catch (error) {
181
+ await handle.close();
182
+ await rm(partial, { force: true });
183
+ throw error;
184
+ }
185
+ await handle.close();
186
+ await rename(partial, staged);
187
+ await syncDir(dir);
188
+ for (const index of indexes)
189
+ await rm(join(dir, String(index)), { force: true });
190
+ return staged;
191
+ },
192
+ async promoteOriginal(id, staged) {
193
+ assertId(id);
194
+ await ensureDir(originals);
195
+ await syncFile(staged);
196
+ // link() never replaces an existing original, unlike rename().
197
+ await link(staged, join(originals, id));
198
+ await syncDir(originals);
199
+ await unlink(staged);
200
+ await syncDir(dirname(staged));
201
+ usedBytes = undefined;
202
+ },
203
+ originalPath(id) {
204
+ if (!idPattern.test(id))
205
+ return null;
206
+ const path = join(originals, id);
207
+ return existsSync(path) ? path : null;
208
+ },
209
+ async workDir(id) {
210
+ assertId(id);
211
+ const dir = join(tmp, id, 'work');
212
+ await ensureDir(dir);
213
+ return dir;
214
+ },
215
+ // Removals ignore IDs that no write could have accepted.
216
+ async removeWork(id) {
217
+ if (!idPattern.test(id))
218
+ return;
219
+ await rm(join(tmp, id, 'work'), { recursive: true, force: true });
220
+ await rmdir(join(tmp, id)).catch(() => { });
221
+ },
222
+ async writeVariant(key, tmpPath) {
223
+ assertKey(key);
224
+ const hash = createHash('sha256');
225
+ let bytes = 0;
226
+ for await (const chunk of Bun.file(tmpPath).stream()) {
227
+ hash.update(chunk);
228
+ bytes += chunk.byteLength;
229
+ }
230
+ await commit(tmpPath, join(variants, key));
231
+ usedBytes = undefined;
232
+ return { etag: hash.digest('hex').slice(0, 16), bytes };
233
+ },
234
+ variantPath(key) {
235
+ if (!variantKeyPattern.test(key))
236
+ return null;
237
+ const path = join(variants, key);
238
+ return existsSync(path) ? path : null;
239
+ },
240
+ async removeAsset(id) {
241
+ if (!idPattern.test(id))
242
+ return;
243
+ await rm(join(originals, id), { force: true });
244
+ await rm(join(variants, id), { recursive: true, force: true });
245
+ await rm(join(tmp, id), { recursive: true, force: true });
246
+ usedBytes = undefined;
247
+ },
248
+ async removeUpload(id, attempt) {
249
+ if (!idPattern.test(id) || !idPattern.test(attempt))
250
+ return;
251
+ await rm(uploadDir(id, attempt), { recursive: true, force: true });
252
+ await rmdir(join(tmp, id)).catch(() => { });
253
+ },
254
+ async sweepTmp(olderThan) {
255
+ let removed = 0;
256
+ for (const id of await readdir(tmp).catch(() => [])) {
257
+ const dir = join(tmp, id);
258
+ for (const entry of await readdir(dir).catch(() => [])) {
259
+ const path = join(dir, entry);
260
+ const info = await stat(path).catch(() => null);
261
+ if (!info || info.mtimeMs >= olderThan.getTime())
262
+ continue;
263
+ await rm(path, { recursive: true, force: true });
264
+ removed++;
265
+ }
266
+ if (!(await readdir(dir).catch(() => [])).length)
267
+ await rm(dir, { recursive: true, force: true });
268
+ }
269
+ return removed;
270
+ },
271
+ async usage() {
272
+ await ensureDir(root);
273
+ const fs = await statfs(root);
274
+ if (!usedBytes || Date.now() - usedBytes.at > usageTtl)
275
+ usedBytes = { bytes: (await size(originals)) + (await size(variants)), at: Date.now() };
276
+ return { bytes: usedBytes.bytes, free: fs.bavail * fs.bsize };
277
+ }
278
+ };
279
+ }
@@ -0,0 +1,5 @@
1
+ export declare function sanitizeSvg(input: string): string;
2
+ export declare function svgDimensions(svg: string): {
3
+ width: number;
4
+ height: number;
5
+ };
@@ -0,0 +1,142 @@
1
+ import { SaxesParser } from 'saxes';
2
+ const elements = new Set([
3
+ 'svg',
4
+ 'g',
5
+ 'defs',
6
+ 'path',
7
+ 'rect',
8
+ 'circle',
9
+ 'ellipse',
10
+ 'line',
11
+ 'polyline',
12
+ 'polygon',
13
+ 'text',
14
+ 'tspan',
15
+ 'title',
16
+ 'desc',
17
+ 'linearGradient',
18
+ 'radialGradient',
19
+ 'stop',
20
+ 'clipPath',
21
+ 'mask',
22
+ 'use',
23
+ 'symbol'
24
+ ]);
25
+ const attributes = new Set([
26
+ 'id',
27
+ 'viewBox',
28
+ 'width',
29
+ 'height',
30
+ 'x',
31
+ 'y',
32
+ 'x1',
33
+ 'x2',
34
+ 'y1',
35
+ 'y2',
36
+ 'cx',
37
+ 'cy',
38
+ 'r',
39
+ 'rx',
40
+ 'ry',
41
+ 'd',
42
+ 'points',
43
+ 'fill',
44
+ 'fill-rule',
45
+ 'fill-opacity',
46
+ 'stroke',
47
+ 'stroke-width',
48
+ 'stroke-linecap',
49
+ 'stroke-linejoin',
50
+ 'stroke-dasharray',
51
+ 'stroke-dashoffset',
52
+ 'stroke-opacity',
53
+ 'opacity',
54
+ 'transform',
55
+ 'gradientTransform',
56
+ 'gradientUnits',
57
+ 'offset',
58
+ 'stop-color',
59
+ 'stop-opacity',
60
+ 'clip-path',
61
+ 'clip-rule',
62
+ 'mask',
63
+ 'preserveAspectRatio',
64
+ 'font-family',
65
+ 'font-size',
66
+ 'font-weight',
67
+ 'text-anchor',
68
+ 'dx',
69
+ 'dy',
70
+ 'href'
71
+ ]);
72
+ const escape = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[c]);
73
+ export function sanitizeSvg(input) {
74
+ if (new TextEncoder().encode(input).length > 1_000_000)
75
+ throw new Error('SVG limit is 1 MB');
76
+ let result = '', depth = 0, skip = 0, count = 0, root = false;
77
+ const parser = new SaxesParser({ xmlns: true });
78
+ parser.on('doctype', () => {
79
+ throw new Error('SVG document types and entities are not allowed');
80
+ });
81
+ parser.on('error', (e) => {
82
+ throw e;
83
+ });
84
+ parser.on('opentag', (tag) => {
85
+ depth++;
86
+ if (depth > 64 || ++count > 10000)
87
+ throw new Error('SVG is too complex');
88
+ if (depth === 1) {
89
+ if (tag.local !== 'svg' || tag.uri !== 'http://www.w3.org/2000/svg')
90
+ throw new Error('Expected an SVG root and namespace');
91
+ root = true;
92
+ }
93
+ if (skip || !elements.has(tag.local) || tag.uri !== 'http://www.w3.org/2000/svg') {
94
+ skip++;
95
+ return;
96
+ }
97
+ result += '<' + tag.local;
98
+ if (depth === 1)
99
+ result += ' xmlns="http://www.w3.org/2000/svg"';
100
+ for (const attr of Object.values(tag.attributes)) {
101
+ if (!attributes.has(attr.name) || attr.prefix || /[<>\u0000-\u001f]/.test(attr.value))
102
+ continue;
103
+ if (attr.name === 'href' && !/^#[a-zA-Z_][\w:.-]*$/.test(attr.value))
104
+ continue;
105
+ if (/url\s*\(/i.test(attr.value) && !/^url\(#[a-zA-Z_][\w:.-]*\)$/.test(attr.value))
106
+ continue;
107
+ if (/(?:javascript|data|https?):|\/\//i.test(attr.value))
108
+ continue;
109
+ result += ` ${attr.name}="${escape(attr.value)}"`;
110
+ }
111
+ result += '>';
112
+ });
113
+ parser.on('text', (text) => {
114
+ if (!skip)
115
+ result += escape(text);
116
+ });
117
+ parser.on('cdata', (text) => {
118
+ if (!skip)
119
+ result += escape(text);
120
+ });
121
+ parser.on('closetag', (tag) => {
122
+ if (skip)
123
+ skip--;
124
+ else
125
+ result += `</${tag.local}>`;
126
+ depth--;
127
+ });
128
+ parser.write(input).close();
129
+ if (!root)
130
+ throw new Error('Empty SVG');
131
+ return result;
132
+ }
133
+ export function svgDimensions(svg) {
134
+ const root = /<svg\b[^>]*>/.exec(svg)?.[0] ?? '';
135
+ const viewBox = /viewBox="([^"]+)"/.exec(root)?.[1].trim().split(/[ ,]+/).map(Number);
136
+ const width = viewBox?.[2] ?? parseFloat(/\bwidth="([^"]+)"/.exec(root)?.[1] ?? '300');
137
+ const height = viewBox?.[3] ?? parseFloat(/\bheight="([^"]+)"/.exec(root)?.[1] ?? '150');
138
+ return {
139
+ width: Number.isFinite(width) && width > 0 ? Math.round(width) : 300,
140
+ height: Number.isFinite(height) && height > 0 ? Math.round(height) : 150
141
+ };
142
+ }
@@ -0,0 +1,12 @@
1
+ /** Claims bound into an upload ticket. `sub` is the user ID of the session user or API key owner. */
2
+ export interface UploadTicket {
3
+ id: string;
4
+ attempt: string;
5
+ mime: string;
6
+ bytes: number;
7
+ sub: string;
8
+ exp: number;
9
+ }
10
+ export declare function signUploadTicket(secret: string, ticket: UploadTicket): string;
11
+ /** Returns the claims when the signature is valid and unexpired; otherwise null. */
12
+ export declare function verifyUploadTicket(secret: string, token: string | null, now?: number): UploadTicket | null;
@@ -0,0 +1,35 @@
1
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
2
+ const key = (secret) => createHash('sha256').update(`sandcms-upload-ticket:${secret}`).digest();
3
+ const encode = (value) => Buffer.from(value).toString('base64url');
4
+ export function signUploadTicket(secret, ticket) {
5
+ const payload = encode(JSON.stringify(ticket));
6
+ const signature = createHmac('sha256', key(secret)).update(payload).digest('base64url');
7
+ return `${payload}.${signature}`;
8
+ }
9
+ /** Returns the claims when the signature is valid and unexpired; otherwise null. */
10
+ export function verifyUploadTicket(secret, token, now = Date.now()) {
11
+ if (!token)
12
+ return null;
13
+ const [payload, signature, extra] = token.split('.');
14
+ if (!payload || !signature || extra !== undefined)
15
+ return null;
16
+ const expected = createHmac('sha256', key(secret)).update(payload).digest();
17
+ const given = Buffer.from(signature, 'base64url');
18
+ if (given.length !== expected.length || !timingSafeEqual(given, expected))
19
+ return null;
20
+ try {
21
+ const ticket = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
22
+ if (typeof ticket.id !== 'string' ||
23
+ typeof ticket.attempt !== 'string' ||
24
+ typeof ticket.mime !== 'string' ||
25
+ typeof ticket.sub !== 'string' ||
26
+ !Number.isSafeInteger(ticket.bytes) ||
27
+ !Number.isSafeInteger(ticket.exp) ||
28
+ ticket.exp < now)
29
+ return null;
30
+ return ticket;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
@@ -0,0 +1,36 @@
1
+ import type { Store } from '../db/store.js';
2
+ import type { MediaStorage } from './contracts.js';
3
+ export interface VerifyReport {
4
+ checked: number;
5
+ missingOriginals: string[];
6
+ missingVariants: {
7
+ id: string;
8
+ key: string;
9
+ }[];
10
+ /** Assets whose missing variants were queued for rendering again. */
11
+ requeued: string[];
12
+ /** Assets marked failed because their original is gone. */
13
+ failed: string[];
14
+ /** Missing variants without a job to re-run; `media rebuild --force` or a re-upload fixes them. */
15
+ unrepairable: {
16
+ id: string;
17
+ key: string;
18
+ }[];
19
+ }
20
+ /** Report media rows whose original or active variants are missing on disk; optionally repair them. */
21
+ export declare function verifyMedia(cms: {
22
+ store: Store;
23
+ media: {
24
+ storage: MediaStorage;
25
+ };
26
+ }, { repair }?: {
27
+ repair?: boolean | undefined;
28
+ }): VerifyReport;
29
+ /**
30
+ * Queue a re-render of every ready raster asset's active version with the local processor, keeping the
31
+ * version (and so every public URL). Existing files keep serving until each variant is replaced.
32
+ * Returns the number of assets queued.
33
+ */
34
+ export declare function forceRebuild(cms: {
35
+ store: Store;
36
+ }): number;
@@ -0,0 +1,109 @@
1
+ // Operator checks for local media: `sandcms media verify [--repair]` and `sandcms media rebuild --force`.
2
+ import { and, eq, notExists } from 'drizzle-orm';
3
+ import { jobs, media, mediaDeletions, uploads, uploadSessions } from '../db/schema.js';
4
+ import { variantKey } from './runner.js';
5
+ const missingOriginal = 'Original file is missing. Upload this image again.';
6
+ function current(store) {
7
+ const { db } = store;
8
+ return db
9
+ .select()
10
+ .from(media)
11
+ .where(and(notExists(db.select().from(mediaDeletions).where(eq(mediaDeletions.mediaId, media.id))),
12
+ // In-flight uploads have no original yet.
13
+ notExists(db.select().from(uploadSessions).where(eq(uploadSessions.mediaId, media.id))), notExists(db.select().from(uploads).where(eq(uploads.mediaId, media.id)))))
14
+ .all()
15
+ .filter((a) => a.status !== 'deleting');
16
+ }
17
+ /** Report media rows whose original or active variants are missing on disk; optionally repair them. */
18
+ export function verifyMedia(cms, { repair = false } = {}) {
19
+ const { db } = cms.store, storage = cms.media.storage;
20
+ const report = {
21
+ checked: 0,
22
+ missingOriginals: [],
23
+ missingVariants: [],
24
+ requeued: [],
25
+ failed: [],
26
+ unrepairable: []
27
+ };
28
+ for (const asset of current(cms.store)) {
29
+ const assetJobs = db.select().from(jobs).where(eq(jobs.mediaId, asset.id)).all();
30
+ // Never accepted (e.g. an expired upload): there is nothing to verify.
31
+ if (!asset.activeVersion && !assetJobs.length)
32
+ continue;
33
+ report.checked++;
34
+ const missing = asset.activeVersion
35
+ ? asset.variants.filter((v) => !storage.variantPath(v.key)).map((v) => v.key)
36
+ : [];
37
+ for (const key of missing)
38
+ report.missingVariants.push({ id: asset.id, key });
39
+ if (!storage.originalPath(asset.id)) {
40
+ report.missingOriginals.push(asset.id);
41
+ if (repair && !(asset.status === 'failed' && asset.error === missingOriginal)) {
42
+ db.update(media)
43
+ .set({ status: 'failed', error: missingOriginal })
44
+ .where(eq(media.id, asset.id))
45
+ .run();
46
+ report.failed.push(asset.id);
47
+ }
48
+ continue;
49
+ }
50
+ if (!repair || !missing.length)
51
+ continue;
52
+ db.transaction(() => {
53
+ let requeued = false;
54
+ for (const key of missing) {
55
+ const job = assetJobs.find((j) => j.version === asset.activeVersion && variantKey(asset.id, j.version, j.spec) === key);
56
+ if (!job) {
57
+ report.unrepairable.push({ id: asset.id, key });
58
+ continue;
59
+ }
60
+ db.update(jobs)
61
+ .set({ status: 'pending', attempts: 0, nextAttempt: 0, leaseUntil: 0, error: null })
62
+ .where(eq(jobs.id, job.id))
63
+ .run();
64
+ requeued = true;
65
+ }
66
+ if (!requeued)
67
+ return;
68
+ report.requeued.push(asset.id);
69
+ // When a newer set is already in progress, its completion activates that set instead.
70
+ if (asset.targetVersion === asset.activeVersion)
71
+ db.update(media)
72
+ .set({ status: 'processing', error: null })
73
+ .where(eq(media.id, asset.id))
74
+ .run();
75
+ });
76
+ }
77
+ return report;
78
+ }
79
+ /**
80
+ * Queue a re-render of every ready raster asset's active version with the local processor, keeping the
81
+ * version (and so every public URL). Existing files keep serving until each variant is replaced.
82
+ * Returns the number of assets queued.
83
+ */
84
+ export function forceRebuild(cms) {
85
+ const { db } = cms.store;
86
+ let queued = 0;
87
+ db.transaction(() => {
88
+ for (const asset of current(cms.store)) {
89
+ if (asset.status !== 'ready' ||
90
+ !asset.activeVersion ||
91
+ asset.activeVersion !== asset.targetVersion ||
92
+ asset.mime === 'image/svg+xml')
93
+ continue;
94
+ const set = and(eq(jobs.mediaId, asset.id), eq(jobs.version, asset.activeVersion));
95
+ if (!db.select({ id: jobs.id }).from(jobs).where(set).get())
96
+ continue;
97
+ db.update(jobs)
98
+ .set({ status: 'pending', attempts: 0, nextAttempt: 0, leaseUntil: 0, error: null })
99
+ .where(set)
100
+ .run();
101
+ db.update(media)
102
+ .set({ status: 'processing', error: null })
103
+ .where(eq(media.id, asset.id))
104
+ .run();
105
+ queued++;
106
+ }
107
+ });
108
+ return queued;
109
+ }
@@ -0,0 +1,27 @@
1
+ import type { RequestEvent } from '@sveltejs/kit';
2
+ import type { Store } from '../db/store.js';
3
+ export declare const HEALTH_PATH = "/_sandcms/health";
4
+ export interface PlatformCms {
5
+ store: Pick<Store, 'sqlite'>;
6
+ options: {
7
+ origin: string;
8
+ indexing?: boolean;
9
+ canonicalRedirect?: boolean;
10
+ };
11
+ seo?: {
12
+ robots(): string;
13
+ } | null;
14
+ }
15
+ /** Lowercase, drop the protocol's default port and a trailing dot: `Example.COM.:443` → `example.com`. */
16
+ export declare function normalizeHost(host: string, protocol?: string): string;
17
+ /** The robots.txt body when the site is not indexed, otherwise the SEO module's (or null when SEO is off). */
18
+ export declare function robotsTxt(cms: PlatformCms): string | null;
19
+ /** Adds `X-Robots-Tag: noindex, nofollow` to every response when `indexing` is false. */
20
+ export declare function applyIndexingHeaders(cms: PlatformCms, response: Response): Response;
21
+ /**
22
+ * Handles platform routes before anything else: `GET|HEAD /_sandcms/health` (liveness: the database opens),
23
+ * the canonical-host redirect, and the disallow-all robots.txt of an unindexed site. Returns null otherwise.
24
+ */
25
+ export declare function platformHandle(cms: PlatformCms, event: Pick<RequestEvent, 'request'>, { dev }?: {
26
+ dev?: boolean | undefined;
27
+ }): Response | null;