sandcms 0.6.3 → 0.8.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 (175) hide show
  1. package/README.md +15 -11
  2. package/dist/admin/Account.svelte +2 -0
  3. package/dist/admin/Admin.svelte +21 -6
  4. package/dist/admin/AssetAttachment.svelte +9 -6
  5. package/dist/admin/AssetAttachment.svelte.d.ts +3 -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 +5 -10
  9. package/dist/admin/Fields.svelte +2 -8
  10. package/dist/admin/Fields.svelte.d.ts +0 -1
  11. package/dist/admin/Gallery.svelte +221 -80
  12. package/dist/admin/Gallery.svelte.d.ts +0 -1
  13. package/dist/admin/Inbox.svelte +3 -2
  14. package/dist/admin/LinkField.svelte +0 -3
  15. package/dist/admin/LinkField.svelte.d.ts +0 -1
  16. package/dist/admin/MediaLibrary.svelte +10 -7
  17. package/dist/admin/MediaPicker.svelte +43 -35
  18. package/dist/admin/MediaPicker.svelte.d.ts +0 -1
  19. package/dist/admin/Navigation.svelte +13 -2
  20. package/dist/admin/Pages.svelte +195 -0
  21. package/dist/admin/Pages.svelte.d.ts +7 -0
  22. package/dist/admin/Shell.svelte +27 -5
  23. package/dist/admin/SortableList.svelte +82 -61
  24. package/dist/admin/SortableList.svelte.d.ts +3 -1
  25. package/dist/admin/ThemePicker.svelte +72 -0
  26. package/dist/admin/ThemePicker.svelte.d.ts +18 -0
  27. package/dist/admin/UploadButton.svelte +2 -1
  28. package/dist/admin/UploadProgress.svelte +24 -0
  29. package/dist/admin/UploadProgress.svelte.d.ts +7 -0
  30. package/dist/admin/Users.svelte +8 -3
  31. package/dist/admin/client.d.ts +3 -670
  32. package/dist/admin/client.js +2 -1
  33. package/dist/admin/components/ui/alert/alert.svelte.d.ts +3 -13
  34. package/dist/admin/components/ui/attachment/attachment-media.svelte.d.ts +3 -13
  35. package/dist/admin/components/ui/attachment/attachment.svelte.d.ts +6 -26
  36. package/dist/admin/components/ui/badge/badge.svelte.d.ts +7 -25
  37. package/dist/admin/components/ui/button/button.svelte.d.ts +15 -53
  38. package/dist/admin/components/ui/toggle/toggle.svelte.d.ts +6 -26
  39. package/dist/admin/generated/admin.css +823 -115
  40. package/dist/admin/navigation.d.ts +9 -0
  41. package/dist/admin/navigation.js +20 -1
  42. package/dist/admin/theme-context.d.ts +7 -0
  43. package/dist/admin/theme-context.js +3 -0
  44. package/dist/admin/theme.d.ts +7 -0
  45. package/dist/admin/theme.js +14 -0
  46. package/dist/admin/types.d.ts +3 -1
  47. package/dist/admin/uploads.d.ts +8 -1
  48. package/dist/admin/uploads.js +94 -16
  49. package/dist/blueprints/files.js +1 -0
  50. package/dist/blueprints/labels.d.ts +6 -0
  51. package/dist/blueprints/labels.js +14 -0
  52. package/dist/blueprints/load.js +16 -2
  53. package/dist/blueprints/types.d.ts +4 -1
  54. package/dist/cli/admin.d.ts +39 -0
  55. package/dist/cli/admin.js +95 -0
  56. package/dist/cli/backup.js +4 -4
  57. package/dist/cli/doctor.d.ts +10 -1
  58. package/dist/cli/doctor.js +98 -33
  59. package/dist/cli/email-test.d.ts +3 -0
  60. package/dist/cli/email-test.js +20 -0
  61. package/dist/cli/files.d.ts +2 -6
  62. package/dist/cli/files.js +12 -2
  63. package/dist/cli/index.js +401 -95
  64. package/dist/cli/rebaseline.d.ts +10 -0
  65. package/dist/cli/rebaseline.js +117 -0
  66. package/dist/cli/scaffold.js +8 -8
  67. package/dist/cli/setup.js +16 -26
  68. package/dist/cli/upgrade.js +34 -7
  69. package/dist/env.d.ts +26 -2
  70. package/dist/env.js +48 -6
  71. package/dist/notification-fields.js +2 -1
  72. package/dist/server/admin-load.d.ts +85 -5
  73. package/dist/server/admin-load.js +26 -1
  74. package/dist/server/api-access.d.ts +4 -0
  75. package/dist/server/api-access.js +15 -2
  76. package/dist/server/api-keys.d.ts +96 -0
  77. package/dist/server/api-keys.js +115 -0
  78. package/dist/server/api-pagination.d.ts +3 -0
  79. package/dist/server/api.js +21 -63
  80. package/dist/server/auth.d.ts +10 -9
  81. package/dist/server/cms.d.ts +63 -21
  82. package/dist/server/cms.js +64 -7
  83. package/dist/server/db/auto-migrate.d.ts +0 -4
  84. package/dist/server/db/auto-migrate.js +12 -3
  85. package/dist/server/db/legacy.d.ts +13 -0
  86. package/dist/server/db/legacy.js +60 -0
  87. package/dist/server/db/migration-data.js +2 -34
  88. package/dist/server/db/migrations/{0000_foundation.sql → 0000_baseline.sql} +120 -4
  89. package/dist/server/db/migrations/meta/0000_snapshot.json +578 -3
  90. package/dist/server/db/migrations/meta/_journal.json +2 -58
  91. package/dist/server/db/schema.d.ts +119 -2
  92. package/dist/server/db/schema.js +23 -9
  93. package/dist/server/db/store.d.ts +25 -2
  94. package/dist/server/db/store.js +90 -26
  95. package/dist/server/forms.js +2 -1
  96. package/dist/server/hooks.js +155 -81
  97. package/dist/server/media/contracts.d.ts +115 -0
  98. package/dist/server/media/contracts.js +12 -0
  99. package/dist/server/media/deletions.d.ts +2 -1
  100. package/dist/server/media/deletions.js +3 -3
  101. package/dist/server/media/delivery.js +7 -11
  102. package/dist/server/media/processor-child.d.ts +2 -0
  103. package/dist/server/media/processor-child.js +236 -0
  104. package/dist/server/media/processor.d.ts +51 -0
  105. package/dist/server/media/processor.js +135 -0
  106. package/dist/server/media/render-math.d.ts +24 -0
  107. package/dist/server/media/render-math.js +50 -0
  108. package/dist/server/media/runner.d.ts +30 -1
  109. package/dist/server/media/runner.js +418 -165
  110. package/dist/server/media/service.d.ts +53 -11
  111. package/dist/server/media/service.js +307 -98
  112. package/dist/server/media/storage.d.ts +5 -0
  113. package/dist/server/media/storage.js +279 -0
  114. package/dist/server/media/upload-ticket.d.ts +12 -0
  115. package/dist/server/media/upload-ticket.js +35 -0
  116. package/dist/server/media/verify.d.ts +64 -0
  117. package/dist/server/media/verify.js +201 -0
  118. package/dist/server/platform/http.d.ts +27 -0
  119. package/dist/server/platform/http.js +77 -0
  120. package/dist/server/platform/index.d.ts +52 -0
  121. package/dist/server/platform/index.js +98 -0
  122. package/dist/server/platform/snapshots.d.ts +18 -0
  123. package/dist/server/platform/snapshots.js +110 -0
  124. package/dist/server/platform/volume.d.ts +20 -0
  125. package/dist/server/platform/volume.js +60 -0
  126. package/docs/acceptance.md +7 -5
  127. package/docs/api.md +56 -4
  128. package/docs/cloudflare.md +26 -152
  129. package/docs/content.md +20 -5
  130. package/docs/deployment.md +222 -57
  131. package/docs/email.md +6 -0
  132. package/docs/forms.md +2 -2
  133. package/docs/media.md +94 -21
  134. package/docs/package.md +21 -18
  135. package/docs/plans/0.7-self-hosted.md +264 -0
  136. package/docs/releases.md +37 -1
  137. package/docs/upgrades.md +72 -9
  138. package/package.json +37 -44
  139. package/templates/Dockerfile +32 -0
  140. package/templates/integration.ts +26 -5
  141. package/templates/openship.json +9 -0
  142. package/templates/railpack.json +1 -1
  143. package/templates/sandcms/blueprints/files/image.yaml +1 -1
  144. package/templates/sandcms/config.yaml +1 -1
  145. package/dist/cli/cloudflare.d.ts +0 -8
  146. package/dist/cli/cloudflare.js +0 -135
  147. package/dist/server/db/migrations/0001_independent_password_resets.sql +0 -3
  148. package/dist/server/db/migrations/0002_email_failure_reason.sql +0 -1
  149. package/dist/server/db/migrations/0003_direct_r2_uploads.sql +0 -10
  150. package/dist/server/db/migrations/0004_agent_api_keys.sql +0 -38
  151. package/dist/server/db/migrations/0005_api_retention_and_pagination.sql +0 -3
  152. package/dist/server/db/migrations/0006_durable_media_deletion.sql +0 -7
  153. package/dist/server/db/migrations/0007_content_and_job_indexes.sql +0 -2
  154. package/dist/server/db/migrations/0008_search_text_cache.sql +0 -45
  155. package/dist/server/db/migrations/meta/0001_snapshot.json +0 -1197
  156. package/dist/server/db/migrations/meta/0002_snapshot.json +0 -1204
  157. package/dist/server/db/migrations/meta/0003_snapshot.json +0 -1281
  158. package/dist/server/db/migrations/meta/0004_snapshot.json +0 -1546
  159. package/dist/server/db/migrations/meta/0005_snapshot.json +0 -1572
  160. package/dist/server/db/migrations/meta/0006_snapshot.json +0 -1627
  161. package/dist/server/db/migrations/meta/0007_snapshot.json +0 -1643
  162. package/dist/server/db/migrations/meta/0008_snapshot.json +0 -1711
  163. package/dist/worker/index.d.ts +0 -10
  164. package/dist/worker/index.js +0 -460
  165. package/dist/worker/local.d.ts +0 -5
  166. package/dist/worker/local.js +0 -57
  167. package/dist/worker/source.d.ts +0 -2
  168. package/dist/worker/source.js +0 -31
  169. package/dist/worker/uploads.d.ts +0 -22
  170. package/dist/worker/uploads.js +0 -48
  171. package/templates/sandcms/worker/index.ts +0 -1
  172. package/templates/sandcms/worker/local.ts +0 -1
  173. package/templates/sandcms/worker/wrangler.jsonc +0 -6
  174. /package/dist/{worker → server/media}/svg.d.ts +0 -0
  175. /package/dist/{worker → server/media}/svg.js +0 -0
@@ -0,0 +1,236 @@
1
+ // Media processor child process (spawned by processor.ts over Bun IPC). One request per process.
2
+ import { appendFileSync, writeFileSync } from 'node:fs';
3
+ import { availableParallelism, getPriority, setPriority } from 'node:os';
4
+ import { rm } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import sharp, {} from 'sharp';
7
+ import { masterSize, renderPlan } from './render-math.js';
8
+ /** libvips threads per decode/encode; more lets an idle server finish a batch sooner. */
9
+ export function mediaThreads(value = process.env.SANDCMS_MEDIA_THREADS) {
10
+ const threads = Number(value);
11
+ return Number.isSafeInteger(threads) && threads > 0
12
+ ? Math.min(threads, availableParallelism())
13
+ : 1;
14
+ }
15
+ sharp.cache(false);
16
+ sharp.concurrency(mediaThreads());
17
+ // Allowlist loaders so an SVG/PDF/etc. declared as a raster type is never rasterized.
18
+ sharp.block({ operation: ['VipsForeignLoad'] });
19
+ sharp.unblock({
20
+ operation: [
21
+ 'VipsForeignLoadJpeg',
22
+ 'VipsForeignLoadPng',
23
+ 'VipsForeignLoadWebp',
24
+ 'VipsForeignLoadHeif',
25
+ 'VipsForeignLoadNsgif',
26
+ 'VipsForeignLoadTiff'
27
+ ]
28
+ });
29
+ try {
30
+ // Under memory pressure the kernel should kill this child, not the web server.
31
+ writeFileSync('/proc/self/oom_score_adj', '1000');
32
+ }
33
+ catch {
34
+ // Not Linux, or not permitted.
35
+ }
36
+ try {
37
+ // Background work: the site's own requests always win the CPU over image processing.
38
+ setPriority(10);
39
+ }
40
+ catch {
41
+ // Not permitted on this platform.
42
+ }
43
+ if (process.env.SANDCMS_PROCESSOR_TRACE)
44
+ appendFileSync(process.env.SANDCMS_PROCESSOR_TRACE, `start threads=${sharp.concurrency()} nice=${getPriority()}\n`);
45
+ const formats = {
46
+ 'image/jpeg': (m) => m.format === 'jpeg',
47
+ 'image/png': (m) => m.format === 'png',
48
+ 'image/webp': (m) => m.format === 'webp',
49
+ 'image/avif': (m) => m.format === 'heif' && m.compression === 'av1',
50
+ 'image/gif': (m) => m.format === 'gif',
51
+ 'image/tiff': (m) => m.format === 'tiff'
52
+ };
53
+ class Rejection extends Error {
54
+ status;
55
+ constructor(status, message) {
56
+ super(message);
57
+ this.status = status;
58
+ }
59
+ }
60
+ const open = (path, maxPixels) => sharp(path, { failOn: 'error', limitInputPixels: maxPixels });
61
+ function classify(error) {
62
+ if (error instanceof Rejection)
63
+ return error;
64
+ const message = error instanceof Error ? error.message : String(error);
65
+ if (/unsupported image format/i.test(message))
66
+ return new Rejection(415, 'Unsupported image format');
67
+ if (/pixel limit/i.test(message))
68
+ return new Rejection(413, 'Image has too many pixels');
69
+ return new Rejection(422, `Image could not be decoded: ${message.split('\n')[0]}`);
70
+ }
71
+ async function probe(path, mime, maxPixels) {
72
+ let meta;
73
+ try {
74
+ meta = await open(path, maxPixels).metadata();
75
+ }
76
+ catch (error) {
77
+ throw classify(error);
78
+ }
79
+ if (!formats[mime]?.(meta))
80
+ throw new Rejection(415, `File is not a valid ${mime} image`);
81
+ const { width = 0, height = 0 } = meta.autoOrient ?? meta;
82
+ if (width < 1 || height < 1)
83
+ throw new Rejection(422, 'Image has no dimensions');
84
+ if (width * height > maxPixels)
85
+ throw new Rejection(413, 'Image has too many pixels');
86
+ return { width, height, exif: meta.exif };
87
+ }
88
+ /** Validate the whole stream cheaply (shrink-on-load where supported) so truncated files are rejected up front. */
89
+ async function verifyDecode(path, maxPixels) {
90
+ try {
91
+ await open(path, maxPixels)
92
+ .resize(64, 64, { fit: 'inside', withoutEnlargement: true })
93
+ .raw()
94
+ .toBuffer();
95
+ }
96
+ catch (error) {
97
+ throw classify(error);
98
+ }
99
+ }
100
+ // Minimal TIFF/EXIF IFD0 reader: only Artist (0x013b) and Copyright (0x8298) survive into variants.
101
+ function credits(exif) {
102
+ if (!exif || exif.length < 14)
103
+ return undefined;
104
+ const base = exif.subarray(0, 6).toString('latin1') === 'Exif\0\0' ? 6 : 0;
105
+ const le = exif.toString('latin1', base, base + 2) === 'II';
106
+ const u16 = (o) => (le ? exif.readUInt16LE(o) : exif.readUInt16BE(o));
107
+ const u32 = (o) => (le ? exif.readUInt32LE(o) : exif.readUInt32BE(o));
108
+ const out = {};
109
+ try {
110
+ const ifd = base + u32(base + 4);
111
+ const count = u16(ifd);
112
+ for (let i = 0; i < count; i++) {
113
+ const entry = ifd + 2 + i * 12;
114
+ const tag = u16(entry);
115
+ const name = tag === 0x013b ? 'Artist' : tag === 0x8298 ? 'Copyright' : undefined;
116
+ if (!name || u16(entry + 2) !== 2)
117
+ continue;
118
+ const length = u32(entry + 4);
119
+ const start = length <= 4 ? entry + 8 : base + u32(entry + 8);
120
+ const value = exif
121
+ .toString('latin1', start, start + length)
122
+ .replace(/\0[\s\S]*$/, '')
123
+ .trim();
124
+ if (value)
125
+ out[name] = value;
126
+ }
127
+ }
128
+ catch {
129
+ return undefined;
130
+ }
131
+ return Object.keys(out).length ? out : undefined;
132
+ }
133
+ const send = (message) => process.send(message);
134
+ let resume;
135
+ const proceed = () => new Promise((resolve) => (resume = resolve));
136
+ async function report(id, value) {
137
+ send({ type: 'report', id, report: value });
138
+ await proceed();
139
+ }
140
+ async function encode(master, source, spec, exif, path) {
141
+ if (!['webp', 'avif', 'jpeg'].includes(spec.format))
142
+ throw new Error(`Raster input cannot become ${spec.format}`);
143
+ const plan = renderPlan(source.width, source.height, spec);
144
+ let image = sharp(master.path);
145
+ if (plan.resize.width !== master.width || plan.resize.height !== master.height)
146
+ image = image.resize(plan.resize.width, plan.resize.height, { fit: 'fill' });
147
+ if (plan.crop)
148
+ image = image.extract(plan.crop);
149
+ if (exif)
150
+ image = image.withExif({ IFD0: exif });
151
+ if (spec.format === 'jpeg')
152
+ image = image.flatten({ background: '#ffffff' }).jpeg({ quality: spec.quality, mozjpeg: true });
153
+ else if (spec.format === 'webp')
154
+ image = image.webp({ quality: spec.quality });
155
+ else
156
+ image = image.avif({ quality: spec.quality });
157
+ return image.toFile(path);
158
+ }
159
+ async function render(id, input) {
160
+ const { specs } = input;
161
+ let master;
162
+ let source;
163
+ let exif;
164
+ let failure;
165
+ // Uncompressed 8-bit sRGB TIFF: lossless, cheap to reread, and readable through the allowed loaders.
166
+ const masterPath = join(input.workDir, `master-${process.pid}.tif`);
167
+ try {
168
+ const probed = await probe(input.sourcePath, input.mime, input.maxPixels);
169
+ source = { width: probed.width, height: probed.height };
170
+ exif = credits(probed.exif);
171
+ const size = masterSize(source.width, source.height, specs);
172
+ if (process.env.SANDCMS_PROCESSOR_TRACE)
173
+ appendFileSync(process.env.SANDCMS_PROCESSOR_TRACE, `decode ${input.sourcePath}\n`);
174
+ let image = open(input.sourcePath, input.maxPixels).autoOrient();
175
+ if (size.width !== source.width || size.height !== source.height)
176
+ image = image.resize(size.width, size.height, { fit: 'fill' });
177
+ const info = await image.toColourspace('srgb').tiff({ compression: 'none' }).toFile(masterPath);
178
+ master = { path: masterPath, width: info.width, height: info.height };
179
+ }
180
+ catch (error) {
181
+ failure = classify(error).message;
182
+ }
183
+ for (let index = 0; index < specs.length; index++) {
184
+ const spec = specs[index];
185
+ const name = `${spec.preset}-${spec.size}.${spec.format}`;
186
+ if (!master || !source) {
187
+ await report(id, { index, error: failure ?? 'Image could not be decoded' });
188
+ continue;
189
+ }
190
+ const tmpPath = join(input.workDir, `${name}.tmp`);
191
+ try {
192
+ const info = await encode(master, source, spec, exif, tmpPath);
193
+ await report(id, {
194
+ index,
195
+ tmpPath,
196
+ variant: {
197
+ key: `${input.id}/${input.version}/${name}`,
198
+ preset: spec.preset,
199
+ size: spec.size,
200
+ width: info.width,
201
+ height: info.height,
202
+ format: spec.format
203
+ }
204
+ });
205
+ }
206
+ catch (error) {
207
+ await rm(tmpPath, { force: true });
208
+ await report(id, {
209
+ index,
210
+ error: error instanceof Error ? error.message.split('\n')[0] : String(error)
211
+ });
212
+ }
213
+ }
214
+ await rm(masterPath, { force: true });
215
+ }
216
+ async function handle(message) {
217
+ if (message.type === 'continue')
218
+ return resume?.();
219
+ try {
220
+ if (message.type === 'inspect') {
221
+ const { width, height } = await probe(message.path, message.mime, message.maxPixels);
222
+ await verifyDecode(message.path, message.maxPixels);
223
+ send({ type: 'result', id: message.id, value: { width, height } });
224
+ }
225
+ else {
226
+ await render(message.id, message.input);
227
+ send({ type: 'result', id: message.id, value: null });
228
+ }
229
+ }
230
+ catch (error) {
231
+ const rejection = classify(error);
232
+ send({ type: 'error', id: message.id, status: rejection.status, message: rejection.message });
233
+ }
234
+ }
235
+ process.on('message', (message) => void handle(message));
236
+ send({ type: 'ready' });
@@ -0,0 +1,51 @@
1
+ import { type InspectResult, type MediaProcessor, type RenderReport, type VariantSpec } from './contracts.js';
2
+ export interface RenderInput {
3
+ id: string;
4
+ version: string;
5
+ sourcePath: string;
6
+ mime: string;
7
+ maxPixels: number;
8
+ workDir: string;
9
+ specs: VariantSpec[];
10
+ }
11
+ export type ParentMessage = {
12
+ type: 'inspect';
13
+ id: number;
14
+ path: string;
15
+ mime: string;
16
+ maxPixels: number;
17
+ } | {
18
+ type: 'render';
19
+ id: number;
20
+ input: RenderInput;
21
+ } | {
22
+ type: 'continue';
23
+ id: number;
24
+ };
25
+ export type ChildMessage = {
26
+ type: 'ready';
27
+ } | {
28
+ type: 'report';
29
+ id: number;
30
+ report: RenderReport;
31
+ } | {
32
+ type: 'result';
33
+ id: number;
34
+ value: InspectResult | null;
35
+ } | {
36
+ type: 'error';
37
+ id: number;
38
+ status: number;
39
+ message: string;
40
+ };
41
+ /**
42
+ * Child entry lookup: explicit option, env, a sibling with this module's extension (source tree or unbundled
43
+ * dist), the `sandcms/media-processor` package export (when this module is bundled into an app), then any sibling.
44
+ */
45
+ export declare function resolveProcessorEntry(entry?: string): string;
46
+ /** The child sees only what sharp and Bun need; secrets (SANDCMS_SECRET, SMTP, API tokens) stay in the parent. */
47
+ export declare function childEnv(source?: Record<string, string | undefined>): Record<string, string>;
48
+ export declare function createProcessor(options?: {
49
+ entry?: string;
50
+ timeoutMs?: number;
51
+ }): MediaProcessor;
@@ -0,0 +1,135 @@
1
+ // Parent side of the media processor: one sharp child process per inspect/render call (see processor-child.ts).
2
+ // The child loads sharp at runtime, so consumers must keep `sharp` external in their Vite SSR build
3
+ // (`ssr.external: ['sharp']`); the child entry itself is resolved from disk, never bundled.
4
+ import { existsSync } from 'node:fs';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { MediaRequestError } from './contracts.js';
7
+ const RENDER_TIMEOUT = 10 * 60_000;
8
+ const INSPECT_TIMEOUT = 2 * 60_000;
9
+ const fileOf = (url) => {
10
+ try {
11
+ const path = fileURLToPath(url);
12
+ return existsSync(path) ? path : undefined;
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ };
18
+ /**
19
+ * Child entry lookup: explicit option, env, a sibling with this module's extension (source tree or unbundled
20
+ * dist), the `sandcms/media-processor` package export (when this module is bundled into an app), then any sibling.
21
+ */
22
+ export function resolveProcessorEntry(entry) {
23
+ if (entry)
24
+ return entry;
25
+ if (process.env.SANDCMS_PROCESSOR_ENTRY)
26
+ return process.env.SANDCMS_PROCESSOR_ENTRY;
27
+ const ext = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
28
+ const own = fileOf(new URL(`./processor-child${ext}`, import.meta.url));
29
+ if (own)
30
+ return own;
31
+ let exported;
32
+ try {
33
+ exported = fileOf(import.meta.resolve('sandcms/media-processor'));
34
+ }
35
+ catch {
36
+ // Not installed as a package (or export missing).
37
+ }
38
+ const found = exported ??
39
+ fileOf(new URL('./processor-child.js', import.meta.url)) ??
40
+ fileOf(new URL('./processor-child.ts', import.meta.url));
41
+ if (!found)
42
+ throw new Error('Media processor entry not found; set SANDCMS_PROCESSOR_ENTRY to processor-child.js');
43
+ return found;
44
+ }
45
+ /** The child sees only what sharp and Bun need; secrets (SANDCMS_SECRET, SMTP, API tokens) stay in the parent. */
46
+ export function childEnv(source = process.env) {
47
+ const env = {};
48
+ for (const [name, value] of Object.entries(source))
49
+ if (value !== undefined &&
50
+ (['PATH', 'HOME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL', 'TZ', 'NODE_ENV'].includes(name) ||
51
+ [
52
+ 'SANDCMS_PROCESSOR_TRACE',
53
+ 'SANDCMS_MEDIA_THREADS',
54
+ 'LD_LIBRARY_PATH',
55
+ 'DYLD_LIBRARY_PATH'
56
+ ].includes(name) ||
57
+ /^(MALLOC_|VIPS_|SHARP_|UV_THREADPOOL_SIZE$)/.test(name)))
58
+ env[name] = value;
59
+ return env;
60
+ }
61
+ export function createProcessor(options = {}) {
62
+ const children = new Set();
63
+ let entry;
64
+ function run(request, timeoutMs, onReport) {
65
+ entry ??= resolveProcessorEntry(options.entry);
66
+ return new Promise((resolve, reject) => {
67
+ let settled = false;
68
+ let timer;
69
+ const arm = () => {
70
+ clearTimeout(timer);
71
+ timer = setTimeout(() => finish(new Error(`Media processor timed out after ${timeoutMs} ms`)), timeoutMs);
72
+ };
73
+ const finish = (error, value) => {
74
+ if (settled)
75
+ return;
76
+ settled = true;
77
+ clearTimeout(timer);
78
+ children.delete(child);
79
+ child.kill('SIGKILL');
80
+ if (error)
81
+ reject(error);
82
+ else
83
+ resolve(value);
84
+ };
85
+ const child = Bun.spawn([process.execPath, entry], {
86
+ ipc(raw) {
87
+ const message = raw;
88
+ if (settled)
89
+ return;
90
+ if (message.type === 'ready')
91
+ return void child.send(request);
92
+ if (message.type === 'result')
93
+ return finish(null, message.value);
94
+ if (message.type === 'error')
95
+ return finish(request.type === 'inspect'
96
+ ? new MediaRequestError(message.status, message.message)
97
+ : new Error(message.message));
98
+ if (message.type === 'report') {
99
+ clearTimeout(timer);
100
+ Promise.resolve()
101
+ .then(() => onReport?.(message.report))
102
+ .then(() => {
103
+ if (settled)
104
+ return;
105
+ arm();
106
+ child.send({ type: 'continue', id: message.id });
107
+ }, (error) => finish(error instanceof Error ? error : new Error(String(error))));
108
+ }
109
+ },
110
+ serialization: 'json',
111
+ env: childEnv(),
112
+ stdin: 'ignore',
113
+ stdout: 'inherit',
114
+ stderr: 'inherit'
115
+ });
116
+ children.add(child);
117
+ arm();
118
+ void child.exited.then((code) => finish(new Error(`Media processor exited unexpectedly (${child.signalCode ?? `code ${code}`})`)));
119
+ });
120
+ }
121
+ let next = 0;
122
+ return {
123
+ inspect(path, mime, maxPixels) {
124
+ return run({ type: 'inspect', id: ++next, path, mime, maxPixels }, options.timeoutMs ?? INSPECT_TIMEOUT);
125
+ },
126
+ render(input, onReport) {
127
+ return run({ type: 'render', id: ++next, input }, options.timeoutMs ?? RENDER_TIMEOUT, onReport).then(() => undefined);
128
+ },
129
+ close() {
130
+ for (const child of children)
131
+ child.kill('SIGKILL');
132
+ children.clear();
133
+ }
134
+ };
135
+ }
@@ -0,0 +1,24 @@
1
+ import type { VariantSpec } from './contracts.js';
2
+ export type SizeSpec = Pick<VariantSpec, 'size' | 'aspectRatio'>;
3
+ export type PlanSpec = Pick<VariantSpec, 'size' | 'aspectRatio' | 'focus'>;
4
+ export interface Box {
5
+ width: number;
6
+ height: number;
7
+ }
8
+ export interface RenderPlan extends Box {
9
+ /** Scale the source to exactly this size (fit: fill) before cropping. Equals the output size without a crop. */
10
+ resize: Box;
11
+ /** Region of the resized image to keep, present only for aspect-ratio presets. */
12
+ crop?: {
13
+ left: number;
14
+ top: number;
15
+ width: number;
16
+ height: number;
17
+ };
18
+ }
19
+ /** Output dimensions, identical to the Worker: scale-down to `size` on the long edge, or a cover crop for aspect presets. */
20
+ export declare function variantSize(width: number, height: number, spec: SizeSpec): Box;
21
+ /** Resize + optional crop that produces `variantSize`, keeping the focus point (default centre) as central as possible. */
22
+ export declare function renderPlan(width: number, height: number, spec: PlanSpec): RenderPlan;
23
+ /** Smallest intermediate every spec can be derived from without upscaling. */
24
+ export declare function masterSize(width: number, height: number, specs: PlanSpec[]): Box;
@@ -0,0 +1,50 @@
1
+ /** Output dimensions, identical to the Worker: scale-down to `size` on the long edge, or a cover crop for aspect presets. */
2
+ export function variantSize(width, height, spec) {
3
+ if (spec.aspectRatio) {
4
+ const targetWidth = Math.max(1, Math.round(spec.size * Math.min(1, spec.aspectRatio)));
5
+ const targetHeight = Math.max(1, Math.round(spec.size / Math.max(1, spec.aspectRatio)));
6
+ const cropScale = Math.min(1, width / targetWidth, height / targetHeight);
7
+ return {
8
+ width: Math.max(1, Math.round(targetWidth * cropScale)),
9
+ height: Math.max(1, Math.round(targetHeight * cropScale))
10
+ };
11
+ }
12
+ const scale = Math.min(1, spec.size / Math.max(width, height));
13
+ return {
14
+ width: Math.max(1, Math.round(width * scale)),
15
+ height: Math.max(1, Math.round(height * scale))
16
+ };
17
+ }
18
+ const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
19
+ /** Resize + optional crop that produces `variantSize`, keeping the focus point (default centre) as central as possible. */
20
+ export function renderPlan(width, height, spec) {
21
+ const out = variantSize(width, height, spec);
22
+ if (!spec.aspectRatio)
23
+ return { ...out, resize: out };
24
+ const scale = Math.min(1, Math.max(out.width / width, out.height / height));
25
+ const resize = {
26
+ width: clamp(Math.round(width * scale), out.width, width),
27
+ height: clamp(Math.round(height * scale), out.height, height)
28
+ };
29
+ const focus = spec.focus ?? { x: 0.5, y: 0.5 };
30
+ return {
31
+ ...out,
32
+ resize,
33
+ crop: {
34
+ left: clamp(Math.round(focus.x * resize.width - out.width / 2), 0, resize.width - out.width),
35
+ top: clamp(Math.round(focus.y * resize.height - out.height / 2), 0, resize.height - out.height),
36
+ width: out.width,
37
+ height: out.height
38
+ }
39
+ };
40
+ }
41
+ /** Smallest intermediate every spec can be derived from without upscaling. */
42
+ export function masterSize(width, height, specs) {
43
+ let w = 1, h = 1;
44
+ for (const spec of specs) {
45
+ const { resize } = renderPlan(width, height, spec);
46
+ w = Math.max(w, resize.width);
47
+ h = Math.max(h, resize.height);
48
+ }
49
+ return { width: Math.min(width, w), height: Math.min(height, h) };
50
+ }
@@ -1,2 +1,31 @@
1
1
  import type { Store } from '../db/store.js';
2
- export declare function createRunner(store: Store, worker: (path: string, init?: RequestInit) => Promise<Response>, enqueue: (id: string, mime: string) => void, deletePending: () => Promise<boolean>): () => Promise<boolean>;
2
+ import { type MediaProcessor, type MediaStorage, type VariantSpec } from './contracts.js';
3
+ /**
4
+ * Upload sessions that can still write or validate files: they reserve disk space.
5
+ * Expired, idle-past-expiry and permanently failed sessions are dead rows kept only for their error.
6
+ */
7
+ export declare const liveUploadSession: (now?: number) => import("drizzle-orm").SQL<unknown> | undefined;
8
+ /** Legacy BLOB uploads the runner will still try to validate. */
9
+ export declare const liveLegacyUpload: () => import("drizzle-orm").SQL<unknown>;
10
+ /** Take or renew a named exclusive lease. Returns false while another owner holds it. */
11
+ export declare function takeLease(store: Store, name: string, owner: string, ttl: number): boolean;
12
+ export declare function releaseLease(store: Store, name: string, owner: string): void;
13
+ /** Serializes processor use within one process: one decode at a time, uploads and renders alike. */
14
+ export declare function processorQueue(load: () => Promise<MediaProcessor>): {
15
+ readonly busy: boolean;
16
+ run<T>(work: (processor: MediaProcessor) => Promise<T>): Promise<T>;
17
+ };
18
+ export declare const variantKey: (id: string, version: string, spec: VariantSpec) => string;
19
+ export declare function createRunner(store: Store, deps: {
20
+ storage: MediaStorage;
21
+ processor: ReturnType<typeof processorQueue>;
22
+ maxPixels: number;
23
+ owner: string;
24
+ enqueue: (id: string, mime: string) => void;
25
+ deletePending: () => Promise<boolean>;
26
+ /** Lease renewal interval while waiting on the processor (tests shorten it). */
27
+ heartbeat?: number;
28
+ }): {
29
+ maintain: () => Promise<boolean>;
30
+ render: () => Promise<boolean>;
31
+ };