| 1 | // fixtures/uploads.mjs — getting one picture from a file picker into a |
| 2 | // deck (spec §2.7). |
| 3 | // |
| 4 | // Five steps, in this order, and each one can be the last: |
| 5 | // |
| 6 | // choose the file is a type and a size the deck accepts |
| 7 | // sign POST /d/{sqid}/uploads — where do these bytes go |
| 8 | // put PUT straight to the bucket (or, in development, to the |
| 9 | // app, which has no presigning to offer) |
| 10 | // register POST /d/{sqid}/assets — the server reads what landed, |
| 11 | // sniffs it, sanitises an SVG, and answers with the record |
| 12 | // op the CLIENT applies register_asset with that record, so |
| 13 | // the change reaches the document the same way every other |
| 14 | // change does: one op, one update, one undo step |
| 15 | // |
| 16 | // The last step is the whole reason register does not write the |
| 17 | // document itself. A server writing into the Y.Doc behind the editor |
| 18 | // would be a second writer with no seq, no actor, and nothing for undo |
| 19 | // to take back. |
| 20 | // |
| 21 | // Every step is a seam the caller supplies (sign, put, register, |
| 22 | // applyOp, and measure/hash for the two browser APIs), so the state |
| 23 | // machine is testable with fakes. It imports only clip-poster.mjs, the |
| 24 | // drawing of a clip's first frame. |
| 25 | |
| 26 | import { capturePoster } from './clip-poster.mjs' |
| 27 | |
| 28 | /** §2.7's ceiling: 20 MiB per image. */ |
| 29 | export const MAX_BYTES = 20 * 1024 * 1024 |
| 30 | |
| 31 | /** §2.7's four types, the same list the server's allowlist holds. */ |
| 32 | export const TYPES = ['image/png', 'image/jpeg', 'image/webp', 'image/svg+xml'] |
| 33 | |
| 34 | /** A clip's ceiling and its two kinds (scenes and clips spec §2), as assets.go holds them. */ |
| 35 | export const MAX_CLIP_BYTES = 50 * 1024 * 1024 |
| 36 | export const CLIP_TYPES = ['video/mp4', 'video/webm'] |
| 37 | |
| 38 | /** |
| 39 | * A refusal with a code the caller can turn into one of its own |
| 40 | * strings. `code` is one of the client's own ('type', 'toolarge', |
| 41 | * 'altfirst') or whatever the server sent in its `error` field |
| 42 | * ('no_store', 'unsafe_svg', …); `message` is the server's own words |
| 43 | * when it sent any, and empty when the refusal was made here — the |
| 44 | * caller has the catalog and this module has no English. |
| 45 | */ |
| 46 | export class UploadError extends Error { |
| 47 | constructor (code, message = '') { |
| 48 | super(code) |
| 49 | this.name = 'UploadError' |
| 50 | this.code = code |
| 51 | this.serverMessage = message |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /** The states an upload passes through, in order. */ |
| 56 | export const STATES = ['idle', 'sign', 'put', 'register', 'op', 'done', 'error'] |
| 57 | |
| 58 | /** |
| 59 | * Reads a file's intrinsic size by decoding it, so width and height on |
| 60 | * the <img> are the picture's own and the layout does not jump. |
| 61 | * |
| 62 | * createImageBitmap where there is one; an <img> and an object URL |
| 63 | * otherwise, which is also the path an SVG with no intrinsic size takes |
| 64 | * (it reports the default 300×150, and a wrong-but-present size is |
| 65 | * still better for layout than none). |
| 66 | * |
| 67 | * Never throws: a size that could not be read is {width: 0, height: 0}, |
| 68 | * which the server bounds to 0 and the renderer then omits. |
| 69 | */ |
| 70 | export async function measureImage (file) { |
| 71 | const none = { width: 0, height: 0 } |
| 72 | try { |
| 73 | if (typeof createImageBitmap === 'function' && typeof file.arrayBuffer === 'function') { |
| 74 | const bmp = await createImageBitmap(file) |
| 75 | const out = { width: bmp.width, height: bmp.height } |
| 76 | if (typeof bmp.close === 'function') bmp.close() |
| 77 | return out |
| 78 | } |
| 79 | } catch { /* fall through to the <img> */ } |
| 80 | if (typeof Image !== 'function' || typeof URL === 'undefined' || !URL.createObjectURL) return none |
| 81 | const url = URL.createObjectURL(file) |
| 82 | try { |
| 83 | return await new Promise(resolve => { |
| 84 | const img = new Image() |
| 85 | img.onload = () => resolve({ width: img.naturalWidth || 0, height: img.naturalHeight || 0 }) |
| 86 | img.onerror = () => resolve(none) |
| 87 | img.src = url |
| 88 | }) |
| 89 | } finally { |
| 90 | URL.revokeObjectURL(url) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /** |
| 95 | * The file's SHA-256 as lowercase hex, declared to the sign endpoint. |
| 96 | * |
| 97 | * It is NOT the address the bytes land at: since codex 1 and 2 the app |
| 98 | * mints a staging key of its own and presigns a PUT for that, so |
| 99 | * nothing a browser says decides where anything is written. The server |
| 100 | * re-reads what landed, re-hashes it, and puts THAT under the hash it |
| 101 | * computed; the final ref comes back from register, and this number is |
| 102 | * only a client's claim about the file it picked — worth recording |
| 103 | * next to the upload, never worth believing. |
| 104 | * |
| 105 | * crypto.subtle needs a secure context — https, or localhost, which |
| 106 | * development is. |
| 107 | */ |
| 108 | export async function sha256Hex (file) { |
| 109 | const subtle = globalThis.crypto && globalThis.crypto.subtle |
| 110 | if (!subtle) throw new UploadError('nohash') |
| 111 | const digest = await subtle.digest('SHA-256', await file.arrayBuffer()) |
| 112 | return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('') |
| 113 | } |
| 114 | |
| 115 | /** The file is one of the four types, and not too big. Throws otherwise. */ |
| 116 | export function checkFile (file) { |
| 117 | if (!file) throw new UploadError('nofile') |
| 118 | if (!TYPES.includes(String(file.type || '').toLowerCase())) throw new UploadError('type') |
| 119 | if (!(file.size > 0) || file.size > MAX_BYTES) throw new UploadError('toolarge') |
| 120 | } |
| 121 | |
| 122 | /** The file is an MP4 or WebM of at most 50 MiB. Throws otherwise. */ |
| 123 | export function checkClip (file) { |
| 124 | if (!file) throw new UploadError('nofile') |
| 125 | if (!CLIP_TYPES.includes(String(file.type || '').toLowerCase())) throw new UploadError('type') |
| 126 | if (!(file.size > 0) || file.size > MAX_CLIP_BYTES) throw new UploadError('toolarge') |
| 127 | } |
| 128 | |
| 129 | /** |
| 130 | * A clip's refusal in the catalog's words, with its file's name: |
| 131 | * labels.clip for anything that is not a video this browser can show, |
| 132 | * labels.clipBig for one over 50 MB, labels.failed for the rest. The |
| 133 | * server's own message is a developer's (assets.go's videoFail). |
| 134 | */ |
| 135 | export function clipMessage (err, labels, name) { |
| 136 | const code = err && err.code |
| 137 | const words = code === 'type' || code === 'not_a_video' ? labels.clip |
| 138 | : code === 'toolarge' || code === 'too_large' ? labels.clipBig : null |
| 139 | return words ? String(words).replace('{name}', name || '') : labels.failed |
| 140 | } |
| 141 | |
| 142 | /** |
| 143 | * The uploader. Every step is a seam: |
| 144 | * |
| 145 | * sign({name, size, type, hash}) → {ref, url, headers} |
| 146 | * put(url, file, headers) → resolves when the bytes are up |
| 147 | * register({ref, name, width, height, alt, decorative}) → the record |
| 148 | * applyOp(record) → the caller writes register_asset |
| 149 | * measure(file) → {width, height} (optional) |
| 150 | * hash(file) → hex sha256 (optional) |
| 151 | * staged(ref) → where staged bytes are read back |
| 152 | * capture(url, name) → a clip's poster (optional) |
| 153 | * onState(state, detail) → progress, for the status line |
| 154 | * |
| 155 | * upload(file, {alt, decorative, applyOp}) resolves with the record the |
| 156 | * server validated and the caller registered, or rejects with an |
| 157 | * UploadError. A per-call applyOp wins over the constructor's: which |
| 158 | * block an upload belongs to is decided when the file is CHOSEN, and a |
| 159 | * 20 MiB upload is long enough for somebody to have selected another |
| 160 | * one by the time it lands. |
| 161 | * |
| 162 | * uploadClip(file, {applyOp}) is a clip's: the video staged, its first |
| 163 | * frame drawn from it and registered as a decorative picture, the video |
| 164 | * registered naming the poster's ref, then applyOp(video, poster). |
| 165 | */ |
| 166 | export function createUploader ({ sign, put, register, applyOp, measure = measureImage, hash = sha256Hex, staged = ref => ref, capture = capturePoster, onState = () => {} }) { |
| 167 | // One at a time. A second pick while one is in flight would race two |
| 168 | // register_asset ops onto the same block's `asset` prop, and the |
| 169 | // winner would be whichever request happened to come back second. |
| 170 | let busy = false |
| 171 | |
| 172 | async function upload (file, { alt = '', decorative = false, applyOp: applyNow } = {}) { |
| 173 | if (busy) throw new UploadError('busy') |
| 174 | checkFile(file) |
| 175 | // §2.4's rule, asked before anything moves rather than after 20 MiB |
| 176 | // has been uploaded: an image needs a description unless it is |
| 177 | // marked decorative. |
| 178 | if (!String(alt).trim() && !decorative) throw new UploadError('altfirst') |
| 179 | |
| 180 | // The size is read once the bytes are up, so a slow decode does |
| 181 | // not sit between choosing a file and anything visibly happening. |
| 182 | return run(async () => { |
| 183 | const record = await send(file, async () => ({ ...(await measure(file)), alt: String(alt).trim(), decorative: !!decorative })) |
| 184 | onState('op') |
| 185 | await (applyNow || applyOp)(record) |
| 186 | return record |
| 187 | }) |
| 188 | } |
| 189 | |
| 190 | // One file signed and put (stage), then registered: fields() gives |
| 191 | // what register is told beside the ref and the name. |
| 192 | async function stage (file) { |
| 193 | onState('sign') |
| 194 | const signed = await sign({ name: file.name || '', size: file.size, type: file.type, hash: await hash(file) }) |
| 195 | if (!signed || !signed.url || !signed.ref) throw new UploadError('failed') |
| 196 | onState('put') |
| 197 | await put(signed.url, file, signed.headers || {}) |
| 198 | return signed.ref |
| 199 | } |
| 200 | async function enter (ref, file, fields) { |
| 201 | onState('register') |
| 202 | const record = await register({ ref, name: file.name || '', ...(await fields()) }) |
| 203 | if (!record || !record.id || !record.ref) throw new UploadError('failed') |
| 204 | return record |
| 205 | } |
| 206 | const send = async (file, fields) => enter(await stage(file), file, fields) |
| 207 | |
| 208 | // One at a time, every failure an UploadError, done or error said. |
| 209 | async function run (work) { |
| 210 | busy = true |
| 211 | try { |
| 212 | const record = await work() |
| 213 | onState('done', record) |
| 214 | return record |
| 215 | } catch (err) { |
| 216 | const e = err instanceof UploadError ? err : new UploadError('failed', err && err.message ? err.message : '') |
| 217 | onState('error', e) |
| 218 | throw e |
| 219 | } finally { |
| 220 | busy = false |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | async function uploadClip (file, { applyOp: applyNow } = {}) { |
| 225 | if (busy) throw new UploadError('busy') |
| 226 | checkClip(file) |
| 227 | return run(async () => { |
| 228 | const ref = await stage(file) |
| 229 | // A video this browser cannot draw a frame of, it cannot show. |
| 230 | const shot = await capture(staged(ref), file.name).catch(err => { throw err instanceof UploadError ? err : new UploadError('type') }) |
| 231 | const { width, height, duration } = shot |
| 232 | const poster = await send(shot.file, async () => ({ width, height, alt: '', decorative: true })) |
| 233 | const video = await enter(ref, file, async () => ({ width, height, alt: '', decorative: false, poster: poster.ref, duration })) |
| 234 | onState('op') |
| 235 | await (applyNow || applyOp)(video, poster) |
| 236 | return video |
| 237 | }) |
| 238 | } |
| 239 | |
| 240 | return { upload, uploadClip, get busy () { return busy } } |
| 241 | } |
| 242 | |
| 243 | /** |
| 244 | * Turns one of this app's JSON refusals into an UploadError. `res` is a |
| 245 | * fetch Response; the body is {error, message} (assets.go's assetFail). |
| 246 | * A body that is not that shape still produces an error the caller can |
| 247 | * word — the status alone is enough to know it did not work. |
| 248 | */ |
| 249 | export async function refusal (res) { |
| 250 | let body = null |
| 251 | try { body = await res.json() } catch { /* not JSON, which is answer enough */ } |
| 252 | const code = body && typeof body.error === 'string' ? body.error : `http_${res.status}` |
| 253 | return new UploadError(code, body && typeof body.message === 'string' ? body.message : '') |
| 254 | } |
| 255 | |