import { STAFF_PHOTO_LIMITS as limits, STAFF_PHOTO_POLICY, StaffPhotoError, inspectStaffPhoto, inspectStaffWebp, sniffStaffPhoto, stripStaffWebpMetadata, normaliseStaffPhotoOrientation, isUnsupportedStaffImage } from '../../../packages/contracts/src/staff-photo.js'; import { decodeStaffHeic } from './staff-heic.js'; import { encodeStaffWebp } from './staff-webp.js'; import { checkedAnnotation, drawManagerMarks } from './manager-photo.js'; // One decoder at a time per window; Web Locks additionally serialise same-origin // windows. A bounded waiting queue never starts four large phone decodes at once. let tail = Promise.resolve(), waiting = 0; const abortError = () => Object.assign(new Error('Photo preparation stopped. The original remains on this phone. Tap Try again.'), { name: 'AbortError', code: 'STAFF_PHOTO_INTERRUPTED' }); const cancelled = signal => { if (signal?.aborted) throw signal.reason || abortError(); }; const copyName = name => `${String(name || 'Site photo').replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9_-]+/g, '-').slice(0, 100) || 'Site-photo'}.webp`; function stopped(promise, signal, dispose = () => {}) { return new Promise((resolve, reject) => { let done = false; const stop = () => { if (done) return; done = true; reject(signal.reason || abortError()); }; signal.addEventListener('abort', stop, { once: true }); Promise.resolve(promise).then(value => { signal.removeEventListener('abort', stop); if (done || signal.aborted) { dispose(value); if (!done) reject(signal.reason || abortError()); return; } done = true; resolve(value); }, error => { signal.removeEventListener('abort', stop); if (!done) { done = true; reject(error); } }); if (signal.aborted) stop(); }); } async function nativeDecode(blob, signal, info) { if (typeof globalThis.createImageBitmap === 'function') { // EXIF orientation is neutral in this private decoder input. Ask the native // decoder to downsample raw dimensions before handing pixels to JS. const { width, height } = info; const scale = Math.min(1, limits.side / Math.max(width, height)); const resize = scale < 1 && info.type !== 'image/heic' ? { resizeWidth: Math.max(1, Math.round(width * scale)), resizeHeight: Math.max(1, Math.round(height * scale)), resizeQuality: 'high' } : {}; // ImageBitmap decoding cannot be cancelled. The public caller can stop // waiting immediately, but this work retains its queue/Web Lock lease // until native work settles so a retry cannot overlap a large decode. try { const bitmap = await createImageBitmap(blob, { imageOrientation: 'from-image', colorSpaceConversion: 'default', ...resize }); if (signal.aborted) { bitmap.close?.(); cancelled(signal); } return bitmap; } catch (error) { cancelled(signal); } } // Safari can decode a HEIC in an even when ImageBitmap rejects that // format. This is the device's local decoder; it never uploads to a service. // offers no decode-size control. Refuse large fallbacks instead of // allocating a 48 MP raster alongside the phone's other work. if (info.width * info.height > 20_000_000) throw new StaffPhotoError('This browser cannot safely downsample this large photo locally. Export a JPEG or PNG copy under 20 megapixels and try again. Nothing was uploaded.', 'STAFF_PHOTO_MEMORY'); if (typeof globalThis.Image !== 'function') throw new Error('No local image decoder'); return new Promise((resolve, reject) => { const img = new Image(), url = URL.createObjectURL(blob); const cleanup = () => { URL.revokeObjectURL(url); signal.removeEventListener('abort', stop); img.onload = img.onerror = null; }; const stop = () => { cleanup(); img.src = ''; reject(signal.reason || abortError()); }; img.onload = () => { cleanup(); resolve(img); }; img.onerror = () => { cleanup(); img.src = ''; reject(new Error('No local decoder for this image')); }; signal.addEventListener('abort', stop, { once: true }); img.src = url; if (signal.aborted) stop(); }); } async function convert(file, { signal, onProgress, annotation }) { cancelled(signal); if (!file?.size || file.size > limits.inputBytes) throw new StaffPhotoError('Choose a photo under 30 MiB. Export a smaller JPEG or PNG copy. The original has not been sent.', 'STAFF_PHOTO_BYTES'); onProgress({ status: 'preparing', progress: 5, message: 'Checking photo on this phone…' }); const source = new Uint8Array(await file.arrayBuffer()); cancelled(signal); const info = inspectStaffPhoto(source); if (info.type === 'image/heic' && info.width * info.height > 20_000_000) throw new StaffPhotoError('For safe local HEIC decoding, export a JPEG or PNG copy under 20 megapixels and retry. Nothing was uploaded; the source stays on this phone.', 'STAFF_PHOTO_MEMORY'); const typed = info.type === 'image/heic' ? null : new Blob([normaliseStaffPhotoOrientation(source, info.type)], { type: info.type }); let image, canvas; try { onProgress({ status: 'preparing', progress: 20, message: 'Preparing private WebP copy on this phone…' }); try { if (info.type === 'image/heic') { // Browser HEIC success alone does not prove SDR colour, single-frame or // EXIF/container normalization. The finite checked local decoder is // authoritative on every browser; native decoding sees only its fresh // lossless colour-managed PNG, never an unchecked original HEIC. const decoded = await decodeStaffHeic(source,{signal,onProgress}); cancelled(signal); image = await nativeDecode(decoded.blob,signal,{type:'image/png',width:decoded.width,height:decoded.height}); } else image = await nativeDecode(typed, signal, info); } catch (error) { cancelled(signal); if (error instanceof StaffPhotoError) throw error; throw new StaffPhotoError('This photo could not be decoded on this phone. Export a fresh JPEG or PNG copy and try again. Nothing was uploaded.', 'STAFF_PHOTO_DECODE'); } cancelled(signal); const rawWidth = image.width || image.naturalWidth, rawHeight = image.height || image.naturalHeight; const swapped = info.orientation >= 5, width = swapped ? rawHeight : rawWidth, height = swapped ? rawWidth : rawHeight; if (!width || !height || width > Math.floor(limits.pixels / height)) throw new StaffPhotoError('The decoded photo exceeds the safe phone pixel limit. Export a smaller copy.', 'STAFF_PHOTO_PIXELS'); const scale = Math.min(1, limits.side / Math.max(width, height)); const dimensions = { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) }; let output; // Full decode above proves the compressed payload is usable. A clean, // bounded WebP is already normalised: preserve its exact compressed bytes. const unchanged = !annotation?.marks?.length && info.type === 'image/webp' && info.clean && Math.max(info.width, info.height) <= limits.side && file.size <= limits.outputBytes; if (unchanged) output = typed; else { if (typeof document === 'undefined') throw new StaffPhotoError('Local WebP conversion is unavailable. Update Staff in a supported phone browser.', 'STAFF_PHOTO_ENCODER'); canvas = document.createElement('canvas'); canvas.width = dimensions.width; canvas.height = dimensions.height; const context = canvas.getContext('2d', { colorSpace: 'srgb', alpha: true }); if (!context) throw new StaffPhotoError('The phone could not allocate photo memory. Close other apps, export a smaller JPEG and retry.', 'STAFF_PHOTO_MEMORY'); context.imageSmoothingEnabled = true; context.imageSmoothingQuality = 'high'; // Explicit EXIF transforms also handle browsers that ignore WebP EXIF. // HEIC transforms stay with its checked local decoder. sRGB rendering // interprets ICC before all source metadata is discarded. const w = dimensions.width, h = dimensions.height; const matrices = { 2: [-1,0,0,1,w,0], 3: [-1,0,0,-1,w,h], 4: [1,0,0,-1,0,h], 5: [0,1,1,0,0,0], 6: [0,1,-1,0,w,0], 7: [0,-1,-1,0,w,h], 8: [0,-1,1,0,0,h] }; if (matrices[info.orientation]) context.setTransform(...matrices[info.orientation]); context.drawImage(image, 0, 0, swapped ? h : w, swapped ? w : h); drawManagerMarks(context, w, h, annotation); image?.close?.(); if (image && !image.close) image.src = ''; image = null; output = await encodeStaffWebp(canvas, context, { signal, onProgress }); cancelled(signal); } cancelled(signal); if (output.size > limits.outputBytes) throw new StaffPhotoError('The safe WebP copy is still over 10 MiB. Choose a smaller photo. The original has not been sent.', 'STAFF_PHOTO_OUTPUT_SIZE'); let bytes = new Uint8Array(await output.arrayBuffer()); cancelled(signal); if (sniffStaffPhoto(bytes) !== 'image/webp') throw new StaffPhotoError('This browser cannot encode WebP locally. Update Staff/browser or use another supported phone. Nothing was uploaded.', 'STAFF_PHOTO_ENCODER'); if (!unchanged) { bytes = stripStaffWebpMetadata(bytes); output = new Blob([bytes], { type: 'image/webp' }); } const actual = inspectStaffWebp(bytes, { clean: true }); if (actual.width !== dimensions.width || actual.height !== dimensions.height) throw new StaffPhotoError('The phone encoder did not return the expected WebP. Update your browser or export a smaller JPEG and retry.', 'STAFF_PHOTO_ENCODER'); const sha256 = [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))].map(x => x.toString(16).padStart(2, '0')).join(''); const result = { blob: output.slice(0, output.size, 'image/webp'), name: copyName(file.name), type: 'image/webp', preparation: { policy: STAFF_PHOTO_POLICY, source_type: info.type, source_bytes: file.size, size_bytes: output.size, width: actual.width, height: actual.height, sha256, colour_space: 'sRGB', metadata_removed: true, reencoded: !unchanged } }; onProgress({ status: 'prepared', progress: 100, message: `WebP ready: ${Math.round(output.size / 1024)} KB from ${Math.round(file.size / 1024)} KB. Original retained on phone.` }); return result; } finally { image?.close?.(); if (image && !image.close) image.src = ''; if (canvas) { canvas.width = canvas.height = 1; } } } export async function prepareStaffPhoto(file, { signal, onProgress = () => {}, annotation: inputAnnotation } = {}) { const annotation = checkedAnnotation(inputAnnotation); if (waiting >= 4) throw new StaffPhotoError('Four photos are already waiting to prepare. Finish them, then retry this photo.', 'STAFF_PHOTO_BUSY'); waiting++; const deadline = new AbortController(); const cancel = () => deadline.abort(abortError()); signal?.addEventListener('abort', cancel, { once: true }); if (signal?.aborted) cancel(); const timer = setTimeout(() => deadline.abort(new StaffPhotoError('Photo preparation took too long. Export a smaller JPEG or PNG and tap Try again. Nothing was uploaded.', 'STAFF_PHOTO_TIMEOUT')), limits.timeoutMs); const work = tail.catch(() => {}).then(async () => { cancelled(deadline.signal); const run = () => convert(file, { signal: deadline.signal, onProgress, annotation }); if (globalThis.navigator?.locks?.request) return navigator.locks.request('tomar-staff-photo', { signal: deadline.signal }, run); return run(); }); // Admission counts live work, including cancelled native decodes and queued // File references. Returning to a cancelled caller must not free capacity. tail = work.then(() => {}, () => {}).finally(() => { waiting--; clearTimeout(timer); signal?.removeEventListener('abort', cancel); }); return stopped(work, deadline.signal); } // Mixed evidence accepts video/audio/PDF through existing paths, but every // actual photo is found by its bytes, including a misleading .pdf or empty MIME. export async function prepareStaffMedia(file, options = {}) { const head = new Uint8Array(await file.slice(0, 4096).arrayBuffer()); if (isUnsupportedStaffImage(head)) throw new StaffPhotoError('This image format is not supported for local photo conversion. Export a JPEG or PNG copy and retry. Nothing was uploaded.', 'STAFF_PHOTO_UNSUPPORTED'); const actual = sniffStaffPhoto(head); if (actual || options.photo || /^image\//i.test(file.type || '') || /\.(?:jpe?g|png|webp|gif|heic|heif|avif|bmp|tiff?|svg|dng)$/i.test(file.name || '')) return prepareStaffPhoto(file, options); return { blob: file, name: file.name, type: file.type || 'application/octet-stream', preparation: null }; }