{"schemaVersion":1,"id":"stillmade.captioned-business-clip","version":"1.0.2","name":"Captioned Business Clip","description":"Turn a selected talking-head recording and reviewed subtitles into a captioned clip with original speech and approved branding.","license":"MIT","startingChat":"native","summary":{"text":"Turn a selected talking-head recording and reviewed subtitles into a captioned clip with original speech and approved branding.","origin":"human","generation":"authored","status":"ready"},"defaults":{"aspectRatio":"9:16","brief":"Upload one original video and supply reviewed SRT subtitles with source timestamps. Choose complete source phrases, enter only approved titles and names, then review the original speech, captions, framing and finished export. Founder assistance may prepare the transcript; automatic transcription and automatic best-moment selection are not included in this Block. Never invent a testimonial or change the speaker’s meaning."},"onboarding":[],"packages":[{"manifest":{"schemaVersion":1,"sdkVersion":"0.1.0","id":"stillmade.short-form-finish","version":"1.0.1","name":"Short-form Finish","description":"Turn selected source footage and reviewed subtitles into an editable captioned short with original speech and approved copy.","kind":"task","runtime":"javascript","entry":"src/run.js","license":"MIT","inputs":{"assets":{"type":"video[]","primary":true,"default":[],"required":true,"semantic":"legacy.asset-list.assets","sources":["upstream","user"],"description":"One saved video with measured dimensions and duration."},"music":{"type":"audio[]","default":[],"semantic":"legacy.asset-list.assets","sources":["user"],"description":"Optional licensed audio file covering the full output. Low background level under speech.","required":false},"audioMode":{"type":"text","default":"original","description":"Original sound, or silent footage for a product demonstration only.","semantic":"stillmade.short_form.audiomode","sources":["user","default"],"required":false},"speechVolume":{"type":"number","default":100,"min":25,"max":200,"description":"Original sound volume percent. Review the result for clipping or distortion.","semantic":"stillmade.short_form.speechvolume","sources":["user","default"],"required":false},"purpose":{"type":"text","default":"talking-head","description":"Talking-head, testimonial, or product demonstration.","semantic":"stillmade.short_form.purpose","sources":["user","default"],"required":false},"cuts":{"type":"text","default":"","description":"Optional source selections, one seconds range per line (for example 0-18.5). Blank uses the first 60 seconds. Finish at complete phrase boundaries.","semantic":"stillmade.short_form.cuts","sources":["user","default"],"required":false},"subtitles":{"type":"text","default":"","description":"Reviewed SRT subtitles using ORIGINAL source timestamps. Paste text from a caption file. Transcription is not performed by this Block.","semantic":"stillmade.short_form.subtitles","sources":["user","default"],"required":false},"title":{"type":"text","default":"","description":"Exact approved opening hook, up to 64 characters.","semantic":"stillmade.short_form.title","sources":["user","default"],"required":false},"byline":{"type":"text","default":"","description":"Exact speaker or product label, up to 64 characters.","semantic":"stillmade.short_form.byline","sources":["user","default"],"required":false},"cta":{"type":"text","default":"","description":"Optional approved closing call to action, up to 64 characters.","semantic":"stillmade.short_form.cta","sources":["user","default"],"required":false},"disclosure":{"type":"text","default":"","description":"Optional source credit or demo disclosure, up to 100 characters.","semantic":"stillmade.short_form.disclosure","sources":["user","default"],"required":false},"captionStyle":{"type":"text","default":"Clean","description":"Clean or Emphasis caption treatment.","semantic":"stillmade.short_form.captionstyle","sources":["user","default"],"required":false},"aspect":{"type":"text","default":"9:16","description":"Output frame shape.","semantic":"stillmade.short_form.aspect","sources":["user","default"],"required":false},"fit":{"type":"text","default":"contain","description":"Preserve the whole frame or crop to fill. Review faces after cropping.","semantic":"stillmade.short_form.fit","sources":["user","default"],"required":false},"cropX":{"type":"number","default":0,"min":-100,"max":100,"description":"Manual horizontal framing adjustment in editor preview units.","semantic":"stillmade.short_form.cropx","sources":["user","default"],"required":false},"rightsConfirmed":{"type":"boolean","default":false,"required":true,"sources":["user"],"description":"I have permission to use the source footage and approved statements.","semantic":"stillmade.short_form.rightsconfirmed"}},"outputs":{"timeline":{"type":"timeline","primary":true,"semantic":"legacy.timeline.updatededitor","description":"Editable source cuts, original speech, phrase captions and approved titles."},"review":{"type":"json","semantic":"stillmade.short_form.review","description":"Source selections, caption count and human review requirements.","schema":{"schemaVersion":"integer","state":"string","humanApproved":"boolean","purpose":"string","durationSec":"number","source":{"assetId":"string","versionId":"string"},"cuts":[{"from":"number","to":"number"}],"subtitleCount":"integer","providerCalls":"integer","warnings":"string[]"}}},"permissions":{"project":["asset.read"],"network":[],"filesystem":[],"secrets":[]},"ui":[{"port":"audioMode","control":"select","options":["original","silent"]},{"port":"speechVolume","control":"slider","min":25,"max":200,"step":5},{"port":"purpose","control":"select","options":["talking-head","testimonial","product-demo"]},{"port":"captionStyle","control":"select","options":["Clean","Emphasis"]},{"port":"aspect","control":"select","options":["9:16","1:1","16:9"]},{"port":"fit","control":"select","options":["contain","cover"]},{"port":"cropX","control":"slider","min":-100,"max":100,"step":1}],"platforms":{"phone":{"supported":true},"browser":{"supported":true},"desktop":{"supported":true}},"provenance":{"notice":"Original source (authorship declared by the packager)\nLicense: MIT\nChanges: Original implementation declared by the packager; no reused repository or dependency code.\nFiles: LICENSE, src/run.js\n\nMIT License\n\nCopyright (c) <year> <copyright holders>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and \nassociated documentation files (the \"Software\"), to deal in the Software without restriction, including \nwithout limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \ncopies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the \nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial \nportions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT \nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO \nEVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER \nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE \nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n","portableSources":[{"kind":"original","license":"MIT","paths":["LICENSE","src/run.js"],"evidence":["upstream/0/LICENSE","upstream/0/src/run.js"],"changes":"Original implementation declared by the packager; no reused repository or dependency code."}]},"semantics":[{"name":"stillmade.short_form.audiomode","description":"Original sound, or silent footage for a product demonstration only.","parents":[]},{"name":"stillmade.short_form.speechvolume","description":"Original sound volume percent. Review the result for clipping or distortion.","parents":[]},{"name":"stillmade.short_form.purpose","description":"Talking-head, testimonial, or product demonstration.","parents":[]},{"name":"stillmade.short_form.cuts","description":"Optional source selections, one seconds range per line (for example 0-18.5). Blank uses the first 60 seconds. Finish at complete phrase boundaries.","parents":[]},{"name":"stillmade.short_form.subtitles","description":"Reviewed SRT subtitles using ORIGINAL source timestamps. Paste text from a caption file. Transcription is not performed by this Block.","parents":[]},{"name":"stillmade.short_form.title","description":"Exact approved opening hook, up to 64 characters.","parents":[]},{"name":"stillmade.short_form.byline","description":"Exact speaker or product label, up to 64 characters.","parents":[]},{"name":"stillmade.short_form.cta","description":"Optional approved closing call to action, up to 64 characters.","parents":[]},{"name":"stillmade.short_form.disclosure","description":"Optional source credit or demo disclosure, up to 100 characters.","parents":[]},{"name":"stillmade.short_form.captionstyle","description":"Clean or Emphasis caption treatment.","parents":[]},{"name":"stillmade.short_form.aspect","description":"Output frame shape.","parents":[]},{"name":"stillmade.short_form.fit","description":"Preserve the whole frame or crop to fill. Review faces after cropping.","parents":[]},{"name":"stillmade.short_form.cropx","description":"Manual horizontal framing adjustment in editor preview units.","parents":[]},{"name":"stillmade.short_form.rightsconfirmed","description":"I have permission to use the source footage and approved statements.","parents":[]},{"name":"stillmade.short_form.review","description":"Source selections, caption count and human review requirements.","parents":[]}]},"code":"// Owned, deterministic editing implementation. No I/O, model or host imports.\nconst copy = value => JSON.parse(JSON.stringify(value));\nconst check = (ok, message) => { if (!ok) throw Error(message); };\nconst round = n => Math.round(n * 1000000) / 1000000;\nconst text = (value, name, max = 80) => {\n check(typeof value === 'string' && value.length <= max && !/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f]/.test(value), name + ' must be short plain text.');\n return value.trim();\n};\nconst assets = input.assets;\ncheck(Array.isArray(assets) && assets.length === 1, 'Choose one original video.');\nconst source = assets[0];\ncheck(source.kind === 'video' && typeof source.assetId === 'string' && source.assetId && typeof source.versionId === 'string' && source.versionId, 'The video needs its exact saved asset and version.');\ncheck(typeof source.url === 'string' && /^(https:\\/\\/|http:\\/\\/(localhost|127\\.0\\.0\\.1)(:\\d+)?\\/|\\/api\\/media\\/|sm-media:|blob:)/.test(source.url) && !/^https?:\\/\\/[^/?#]*@/.test(source.url), 'Use a saved media reference.');\ncheck(Number.isFinite(source.duration) && source.duration > 0 && Number.isFinite(source.width) && source.width > 0 && Number.isFinite(source.height) && source.height > 0, 'Upload the original video again to measure its duration and dimensions.');\ncheck(input.rightsConfirmed === true, 'Confirm permission to use this video and the exact supplied statements.');\nconst purpose = input.purpose || 'talking-head';\ncheck(['talking-head', 'testimonial', 'product-demo'].includes(purpose), 'Choose a supported production job.');\nconst title = text(input.title || '', 'Opening title', 64);\nconst byline = text(input.byline || '', 'Speaker or product label', 64);\nconst cta = text(input.cta || '', 'Closing call to action', 64);\nconst disclosure = text(input.disclosure || '', 'Disclosure', 100);\nconst aspect = input.aspect || '9:16';\ncheck(['9:16','1:1','16:9'].includes(aspect), 'Choose a supported frame shape.');\nconst style = input.captionStyle || 'Clean';\ncheck(['Clean','Emphasis'].includes(style), 'Choose Clean or Emphasis captions.');\nconst fit = input.fit || 'contain';\ncheck(['contain','cover'].includes(fit), 'Choose full frame or crop to fill.');\nconst cropX = input.cropX === undefined ? 0 : input.cropX;\ncheck(Number.isFinite(cropX) && Math.abs(cropX) <= 100, 'Horizontal framing must be from -100 to 100.');\n// Each selected source interval stays in supplied order. We never invent a\n// quote, remove a qualifying word, or silently select a supposedly viral moment.\nconst rawCuts = (input.cuts || '').trim();\ncheck(rawCuts.length <= 1200, 'Use up to 12 source selections.');\nconst cuts = rawCuts ? rawCuts.split(/\\n/).filter(line => line.trim()).map(line => {\n const match = line.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*[-,]\\s*(\\d+(?:\\.\\d+)?)$/);\n check(match, 'Use one source range per line, in seconds: 0-18.5');\n return {from:Number(match[1]),to:Number(match[2])};\n}) : [{from:0,to:Math.min(source.duration,60)}];\ncheck(cuts.length > 0 && cuts.length <= 12, 'Choose 1–12 source selections.');\nfor (const cut of cuts) check(cut.to > cut.from && cut.from >= 0 && cut.to <= source.duration + .02, 'A selected range falls outside the source video.');\nconst duration = round(cuts.reduce((n,c) => n+c.to-c.from,0));\ncheck(duration >= 5 && duration <= 90, 'The finished clip must be 5–90 seconds.');\nconst srt = input.subtitles || '';\ncheck(typeof srt === 'string' && srt.length <= 60000, 'Supply an SRT transcript, up to 60,000 characters.');\nconst time = stamp => { const m = stamp.match(/^(\\d{1,2}):(\\d{2}):(\\d{2})[,.](\\d{3})$/); check(m && +m[2]<60 && +m[3]<60, 'Invalid subtitle timestamp.'); return +m[1]*3600 + +m[2]*60 + +m[3] + +m[4]/1000; };\nlet cues = [];\nif (srt.trim()) cues = srt.replace(/^\\uFEFF/,'').replace(/\\r/g,'').trim().split(/\\n\\s*\\n/).map(chunk => {\n const lines = chunk.split('\\n'); if (/^\\d+$/.test(lines[0].trim())) lines.shift();\n const timing = lines.shift().trim().match(/^(\\S+)\\s+-->\\s+(\\S+)$/);\n check(timing && lines.length, 'Each subtitle needs a start, end and spoken text.');\n const start = time(timing[1]), end = time(timing[2]);\n check(end > start && end <= source.duration+.05, 'Subtitle timing falls outside the source.');\n const value = text(lines.join(' ').replace(/\\s+/g,' '), 'Subtitle', 180);\n check(value && !/<[^>]*>/.test(value), 'Use plain subtitle text without markup.');\n return {start,end,text:value};\n});\ncheck(cues.length <= 500, 'Select a transcript with at most 500 captions.');\nfor(let i=1;i<cues.length;i++) check(cues[i].start >= cues[i-1].end-.02, 'Subtitle cues must be ordered and must not overlap.');\ncheck(purpose === 'product-demo' || cues.length > 0, 'Paste reviewed SRT subtitles for this clip. Automatic transcription is a separate approved service.');\nconst audioMode=input.audioMode||'original';\ncheck(['original','silent'].includes(audioMode), 'Choose original sound or silent footage.');\ncheck(audioMode==='original'||purpose==='product-demo','Keep the original speaker’s voice for captioned speech and customer stories.');\nconst speechVolume=input.speechVolume===undefined?100:input.speechVolume;\ncheck(Number.isFinite(speechVolume)&&speechVolume>=25&&speechVolume<=200,'Source volume must be 25–200 percent. Listen for distortion.');\nconst music=input.music||[];\ncheck(Array.isArray(music)&&music.length<=1,'Choose at most one music file.');\nif(music.length){const m=music[0];check(m.kind==='audio'&&typeof m.assetId==='string'&&m.assetId&&typeof m.versionId==='string'&&m.versionId&&typeof m.url==='string'&&/^(https:\\/\\/|http:\\/\\/(localhost|127\\.0\\.0\\.1)(:\\d+)?\\/|\\/api\\/media\\/|sm-media:|blob:)/.test(m.url)&&!/^https?:\\/\\/[^/?#]*@/.test(m.url)&&Number.isFinite(m.duration)&&m.duration>=duration,'Choose a saved, rights-cleared music file long enough for the full clip.');}\nconst clips=[], audioItems=[], captions=[], overlays=[];\nlet cursor=0;\ncuts.forEach((cut,index)=>{\n const length=round(cut.to-cut.from), id='selection-'+(index+1);\n clips.push({id,kind:'video',trackId:'video',asset:copy(source),assetId:source.assetId,versionId:source.versionId,url:source.url,title:source.name||'Original video',start:round(cursor),duration:length,trimStart:cut.from,speed:1,volume:0,transform:{fit,scale:1,x:cropX,y:0,rotation:0,opacity:1},motion:{type:'none'},transition:{type:'Cut',duration:0}});\n // Dedicated source audio: editing and rendering use the same trimmed interval,\n // and muted visual clips prevent a second embedded copy at normal export.\n if(audioMode==='original')audioItems.push({id:id+'-sound',trackId:'speech',asset:copy(source),assetId:source.assetId,versionId:source.versionId,url:source.url,title:'Original speech',start:round(cursor),duration:length,sourceOffset:cut.from,trimStart:cut.from,volume:speechVolume,rate:1,fadeIn:0,fadeOut:0});\n for (const cue of cues) {\n  const from=Math.max(cut.from,cue.start),to=Math.min(cut.to,cue.end);\n  if(to<=from)continue;\n  // A cut inside a subtitle changes what the words mean. Require reviewed\n  // boundaries rather than show an entire quote over a partial source phrase.\n  check(cue.start >= cut.from-.05 && cue.end <= cut.to+.05, 'A cut splits a subtitle. Move the cut to a phrase boundary or revise the transcript.');\n  captions.push({id:'caption-'+captions.length,trackId:'captions',type:'text',text:cue.text,start:round(cursor+from-cut.from),end:round(cursor+to-cut.from),font:'Hanken Grotesk',size:aspect==='9:16'?15:21,color:style==='Emphasis'?'#F7F0DB':'#FFFFFF',background:'#0A0A0A',backgroundOpacity:75,backgroundPadding:5,backgroundRadius:3,width:.82,x:50,y:76,position:'center',animation:style==='Emphasis'?'pop':'none',animIn:.12,animOut:0});\n }\n cursor += length;\n});\nif(music.length){const m=music[0];audioItems.push({id:'music-bed',trackId:'music',asset:copy(m),assetId:m.assetId,versionId:m.versionId,url:m.url,title:m.name||'Music',start:0,duration,sourceOffset:0,trimStart:0,volume:audioMode==='original'?12:65,rate:1,fadeIn:.3,fadeOut:.8});}\nconst addText=(id,value,start,end,y,size)=>{if(value)overlays.push({id,trackId:'copy',type:'text',text:value,start,end,font:'Hanken Grotesk',size,color:'#F7F0DB',background:'#0A0A0A',backgroundOpacity:80,backgroundPadding:5,width:.82,x:50,y,position:'center',animation:'fade',animIn:.2,animOut:.15});};\naddText('opening',title,0,Math.min(3,duration),16,aspect==='9:16'?16:22);\naddText('byline',byline,0,Math.min(5,duration),90,7);\naddText('cta',cta,Math.max(0,duration-3),duration,17,14);\naddText('disclosure',disclosure,0,duration,95,5.5);\nconst timeline={schemaVersion:1,activeTimelineId:'short-form',name:title||'Captioned clip',aspect,aspectRatio:aspect,previewH:369,backgroundColor:'#0A0A0A',tracks:[{id:'video',type:'video',label:'Source selections'},{id:'speech',type:'audio',label:'Original speech'},{id:'music',type:'audio',label:'Music'},{id:'captions',type:'caption',label:'Reviewed subtitles'},{id:'copy',type:'text',label:'Approved copy'}],trackOrder:['video','speech','music','captions','copy'],clips,audioItems,captions,textOverlays:overlays,stickers:[],effects:[],audio:copy(audioItems),overlays:copy([...captions,...overlays]),targetDuration:duration,exportSettings:{aspect,fps:30,resolution:'1080p',quality:'high'}};\nreturn {timeline,review:{schemaVersion:1,state:'needs-human-review',humanApproved:false,purpose,durationSec:duration,source:{assetId:source.assetId,versionId:source.versionId},cuts:copy(cuts),subtitleCount:captions.length,providerCalls:0,warnings:['Watch and listen to the entire export. Confirm every caption against the actual speech and preserve the speaker’s meaning.',...(fit==='cover'?['Crop-to-fill can hide faces or demonstrations. Review framing at every cut.']:[]),'SRT provides phrase timing. No word-level alignment or automatic transcription is claimed.']}};\n","tests":[{"name":"Preserve original speech and reviewed source captions","input":{"assets":[{"kind":"video","assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","width":1080,"height":1920,"duration":12}],"purpose":"talking-head","cuts":"0-12","subtitles":"1\n00:00:00,000 --> 00:00:04,000\nThis is the original sentence.\n\n2\n00:00:04,000 --> 00:00:12,000\nKeep the complete thought in the clip.","title":"An approved hook","rightsConfirmed":true},"expected":{"timeline":{"schemaVersion":1,"activeTimelineId":"short-form","name":"An approved hook","aspect":"9:16","aspectRatio":"9:16","previewH":369,"backgroundColor":"#0A0A0A","tracks":[{"id":"video","type":"video","label":"Source selections"},{"id":"speech","type":"audio","label":"Original speech"},{"id":"music","type":"audio","label":"Music"},{"id":"captions","type":"caption","label":"Reviewed subtitles"},{"id":"copy","type":"text","label":"Approved copy"}],"trackOrder":["video","speech","music","captions","copy"],"clips":[{"id":"selection-1","kind":"video","trackId":"video","asset":{"kind":"video","assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","width":1080,"height":1920,"duration":12},"assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","title":"Original video","start":0,"duration":12,"trimStart":0,"speed":1,"volume":0,"transform":{"fit":"contain","scale":1,"x":0,"y":0,"rotation":0,"opacity":1},"motion":{"type":"none"},"transition":{"type":"Cut","duration":0}}],"audioItems":[{"id":"selection-1-sound","trackId":"speech","asset":{"kind":"video","assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","width":1080,"height":1920,"duration":12},"assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","title":"Original speech","start":0,"duration":12,"sourceOffset":0,"trimStart":0,"volume":100,"rate":1,"fadeIn":0,"fadeOut":0}],"captions":[{"id":"caption-0","trackId":"captions","type":"text","text":"This is the original sentence.","start":0,"end":4,"font":"Hanken Grotesk","size":15,"color":"#FFFFFF","background":"#0A0A0A","backgroundOpacity":75,"backgroundPadding":5,"backgroundRadius":3,"width":0.82,"x":50,"y":76,"position":"center","animation":"none","animIn":0.12,"animOut":0},{"id":"caption-1","trackId":"captions","type":"text","text":"Keep the complete thought in the clip.","start":4,"end":12,"font":"Hanken Grotesk","size":15,"color":"#FFFFFF","background":"#0A0A0A","backgroundOpacity":75,"backgroundPadding":5,"backgroundRadius":3,"width":0.82,"x":50,"y":76,"position":"center","animation":"none","animIn":0.12,"animOut":0}],"textOverlays":[{"id":"opening","trackId":"copy","type":"text","text":"An approved hook","start":0,"end":3,"font":"Hanken Grotesk","size":16,"color":"#F7F0DB","background":"#0A0A0A","backgroundOpacity":80,"backgroundPadding":5,"width":0.82,"x":50,"y":16,"position":"center","animation":"fade","animIn":0.2,"animOut":0.15}],"stickers":[],"effects":[],"audio":[{"id":"selection-1-sound","trackId":"speech","asset":{"kind":"video","assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","width":1080,"height":1920,"duration":12},"assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","title":"Original speech","start":0,"duration":12,"sourceOffset":0,"trimStart":0,"volume":100,"rate":1,"fadeIn":0,"fadeOut":0}],"overlays":[{"id":"caption-0","trackId":"captions","type":"text","text":"This is the original sentence.","start":0,"end":4,"font":"Hanken Grotesk","size":15,"color":"#FFFFFF","background":"#0A0A0A","backgroundOpacity":75,"backgroundPadding":5,"backgroundRadius":3,"width":0.82,"x":50,"y":76,"position":"center","animation":"none","animIn":0.12,"animOut":0},{"id":"caption-1","trackId":"captions","type":"text","text":"Keep the complete thought in the clip.","start":4,"end":12,"font":"Hanken Grotesk","size":15,"color":"#FFFFFF","background":"#0A0A0A","backgroundOpacity":75,"backgroundPadding":5,"backgroundRadius":3,"width":0.82,"x":50,"y":76,"position":"center","animation":"none","animIn":0.12,"animOut":0},{"id":"opening","trackId":"copy","type":"text","text":"An approved hook","start":0,"end":3,"font":"Hanken Grotesk","size":16,"color":"#F7F0DB","background":"#0A0A0A","backgroundOpacity":80,"backgroundPadding":5,"width":0.82,"x":50,"y":16,"position":"center","animation":"fade","animIn":0.2,"animOut":0.15}],"targetDuration":12,"exportSettings":{"aspect":"9:16","fps":30,"resolution":"1080p","quality":"high"}},"review":{"schemaVersion":1,"state":"needs-human-review","humanApproved":false,"purpose":"talking-head","durationSec":12,"source":{"assetId":"approved-video","versionId":"v1"},"cuts":[{"from":0,"to":12}],"subtitleCount":2,"providerCalls":0,"warnings":["Watch and listen to the entire export. Confirm every caption against the actual speech and preserve the speaker’s meaning.","SRT provides phrase timing. No word-level alignment or automatic transcription is claimed."]}}},{"name":"Rebase selected phrases without changing their words","input":{"assets":[{"kind":"video","assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","width":1080,"height":1920,"duration":12}],"purpose":"talking-head","cuts":"4-12","subtitles":"1\n00:00:00,000 --> 00:00:04,000\nThis is the original sentence.\n\n2\n00:00:04,000 --> 00:00:12,000\nKeep the complete thought in the clip.","title":"An approved hook","rightsConfirmed":true},"expected":{"timeline":{"schemaVersion":1,"activeTimelineId":"short-form","name":"An approved hook","aspect":"9:16","aspectRatio":"9:16","previewH":369,"backgroundColor":"#0A0A0A","tracks":[{"id":"video","type":"video","label":"Source selections"},{"id":"speech","type":"audio","label":"Original speech"},{"id":"music","type":"audio","label":"Music"},{"id":"captions","type":"caption","label":"Reviewed subtitles"},{"id":"copy","type":"text","label":"Approved copy"}],"trackOrder":["video","speech","music","captions","copy"],"clips":[{"id":"selection-1","kind":"video","trackId":"video","asset":{"kind":"video","assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","width":1080,"height":1920,"duration":12},"assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","title":"Original video","start":0,"duration":8,"trimStart":4,"speed":1,"volume":0,"transform":{"fit":"contain","scale":1,"x":0,"y":0,"rotation":0,"opacity":1},"motion":{"type":"none"},"transition":{"type":"Cut","duration":0}}],"audioItems":[{"id":"selection-1-sound","trackId":"speech","asset":{"kind":"video","assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","width":1080,"height":1920,"duration":12},"assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","title":"Original speech","start":0,"duration":8,"sourceOffset":4,"trimStart":4,"volume":100,"rate":1,"fadeIn":0,"fadeOut":0}],"captions":[{"id":"caption-0","trackId":"captions","type":"text","text":"Keep the complete thought in the clip.","start":0,"end":8,"font":"Hanken Grotesk","size":15,"color":"#FFFFFF","background":"#0A0A0A","backgroundOpacity":75,"backgroundPadding":5,"backgroundRadius":3,"width":0.82,"x":50,"y":76,"position":"center","animation":"none","animIn":0.12,"animOut":0}],"textOverlays":[{"id":"opening","trackId":"copy","type":"text","text":"An approved hook","start":0,"end":3,"font":"Hanken Grotesk","size":16,"color":"#F7F0DB","background":"#0A0A0A","backgroundOpacity":80,"backgroundPadding":5,"width":0.82,"x":50,"y":16,"position":"center","animation":"fade","animIn":0.2,"animOut":0.15}],"stickers":[],"effects":[],"audio":[{"id":"selection-1-sound","trackId":"speech","asset":{"kind":"video","assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","width":1080,"height":1920,"duration":12},"assetId":"approved-video","versionId":"v1","url":"https://media.example/approved.mp4","title":"Original speech","start":0,"duration":8,"sourceOffset":4,"trimStart":4,"volume":100,"rate":1,"fadeIn":0,"fadeOut":0}],"overlays":[{"id":"caption-0","trackId":"captions","type":"text","text":"Keep the complete thought in the clip.","start":0,"end":8,"font":"Hanken Grotesk","size":15,"color":"#FFFFFF","background":"#0A0A0A","backgroundOpacity":75,"backgroundPadding":5,"backgroundRadius":3,"width":0.82,"x":50,"y":76,"position":"center","animation":"none","animIn":0.12,"animOut":0},{"id":"opening","trackId":"copy","type":"text","text":"An approved hook","start":0,"end":3,"font":"Hanken Grotesk","size":16,"color":"#F7F0DB","background":"#0A0A0A","backgroundOpacity":80,"backgroundPadding":5,"width":0.82,"x":50,"y":16,"position":"center","animation":"fade","animIn":0.2,"animOut":0.15}],"targetDuration":8,"exportSettings":{"aspect":"9:16","fps":30,"resolution":"1080p","quality":"high"}},"review":{"schemaVersion":1,"state":"needs-human-review","humanApproved":false,"purpose":"talking-head","durationSec":8,"source":{"assetId":"approved-video","versionId":"v1"},"cuts":[{"from":4,"to":12}],"subtitleCount":1,"providerCalls":0,"warnings":["Watch and listen to the entire export. Confirm every caption against the actual speech and preserve the speaker’s meaning.","SRT provides phrase timing. No word-level alignment or automatic transcription is claimed."]}}}],"portable":{"format":"stillmade-block/1","dependencies":[],"sources":[{"kind":"original","license":"MIT","paths":["LICENSE","src/run.js"],"evidence":["upstream/0/LICENSE","upstream/0/src/run.js"],"changes":"Original implementation declared by the packager; no reused repository or dependency code."}],"files":{"upstream/0/LICENSE":"MIT License\n\nCopyright (c) <year> <copyright holders>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and \nassociated documentation files (the \"Software\"), to deal in the Software without restriction, including \nwithout limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \ncopies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the \nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial \nportions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT \nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO \nEVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER \nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE \nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n","upstream/0/src/run.js":"// Owned, deterministic editing implementation. No I/O, model or host imports.\nconst copy = value => JSON.parse(JSON.stringify(value));\nconst check = (ok, message) => { if (!ok) throw Error(message); };\nconst round = n => Math.round(n * 1000000) / 1000000;\nconst text = (value, name, max = 80) => {\n check(typeof value === 'string' && value.length <= max && !/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f]/.test(value), name + ' must be short plain text.');\n return value.trim();\n};\nconst assets = input.assets;\ncheck(Array.isArray(assets) && assets.length === 1, 'Choose one original video.');\nconst source = assets[0];\ncheck(source.kind === 'video' && typeof source.assetId === 'string' && source.assetId && typeof source.versionId === 'string' && source.versionId, 'The video needs its exact saved asset and version.');\ncheck(typeof source.url === 'string' && /^(https:\\/\\/|http:\\/\\/(localhost|127\\.0\\.0\\.1)(:\\d+)?\\/|\\/api\\/media\\/|sm-media:|blob:)/.test(source.url) && !/^https?:\\/\\/[^/?#]*@/.test(source.url), 'Use a saved media reference.');\ncheck(Number.isFinite(source.duration) && source.duration > 0 && Number.isFinite(source.width) && source.width > 0 && Number.isFinite(source.height) && source.height > 0, 'Upload the original video again to measure its duration and dimensions.');\ncheck(input.rightsConfirmed === true, 'Confirm permission to use this video and the exact supplied statements.');\nconst purpose = input.purpose || 'talking-head';\ncheck(['talking-head', 'testimonial', 'product-demo'].includes(purpose), 'Choose a supported production job.');\nconst title = text(input.title || '', 'Opening title', 64);\nconst byline = text(input.byline || '', 'Speaker or product label', 64);\nconst cta = text(input.cta || '', 'Closing call to action', 64);\nconst disclosure = text(input.disclosure || '', 'Disclosure', 100);\nconst aspect = input.aspect || '9:16';\ncheck(['9:16','1:1','16:9'].includes(aspect), 'Choose a supported frame shape.');\nconst style = input.captionStyle || 'Clean';\ncheck(['Clean','Emphasis'].includes(style), 'Choose Clean or Emphasis captions.');\nconst fit = input.fit || 'contain';\ncheck(['contain','cover'].includes(fit), 'Choose full frame or crop to fill.');\nconst cropX = input.cropX === undefined ? 0 : input.cropX;\ncheck(Number.isFinite(cropX) && Math.abs(cropX) <= 100, 'Horizontal framing must be from -100 to 100.');\n// Each selected source interval stays in supplied order. We never invent a\n// quote, remove a qualifying word, or silently select a supposedly viral moment.\nconst rawCuts = (input.cuts || '').trim();\ncheck(rawCuts.length <= 1200, 'Use up to 12 source selections.');\nconst cuts = rawCuts ? rawCuts.split(/\\n/).filter(line => line.trim()).map(line => {\n const match = line.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*[-,]\\s*(\\d+(?:\\.\\d+)?)$/);\n check(match, 'Use one source range per line, in seconds: 0-18.5');\n return {from:Number(match[1]),to:Number(match[2])};\n}) : [{from:0,to:Math.min(source.duration,60)}];\ncheck(cuts.length > 0 && cuts.length <= 12, 'Choose 1–12 source selections.');\nfor (const cut of cuts) check(cut.to > cut.from && cut.from >= 0 && cut.to <= source.duration + .02, 'A selected range falls outside the source video.');\nconst duration = round(cuts.reduce((n,c) => n+c.to-c.from,0));\ncheck(duration >= 5 && duration <= 90, 'The finished clip must be 5–90 seconds.');\nconst srt = input.subtitles || '';\ncheck(typeof srt === 'string' && srt.length <= 60000, 'Supply an SRT transcript, up to 60,000 characters.');\nconst time = stamp => { const m = stamp.match(/^(\\d{1,2}):(\\d{2}):(\\d{2})[,.](\\d{3})$/); check(m && +m[2]<60 && +m[3]<60, 'Invalid subtitle timestamp.'); return +m[1]*3600 + +m[2]*60 + +m[3] + +m[4]/1000; };\nlet cues = [];\nif (srt.trim()) cues = srt.replace(/^\\uFEFF/,'').replace(/\\r/g,'').trim().split(/\\n\\s*\\n/).map(chunk => {\n const lines = chunk.split('\\n'); if (/^\\d+$/.test(lines[0].trim())) lines.shift();\n const timing = lines.shift().trim().match(/^(\\S+)\\s+-->\\s+(\\S+)$/);\n check(timing && lines.length, 'Each subtitle needs a start, end and spoken text.');\n const start = time(timing[1]), end = time(timing[2]);\n check(end > start && end <= source.duration+.05, 'Subtitle timing falls outside the source.');\n const value = text(lines.join(' ').replace(/\\s+/g,' '), 'Subtitle', 180);\n check(value && !/<[^>]*>/.test(value), 'Use plain subtitle text without markup.');\n return {start,end,text:value};\n});\ncheck(cues.length <= 500, 'Select a transcript with at most 500 captions.');\nfor(let i=1;i<cues.length;i++) check(cues[i].start >= cues[i-1].end-.02, 'Subtitle cues must be ordered and must not overlap.');\ncheck(purpose === 'product-demo' || cues.length > 0, 'Paste reviewed SRT subtitles for this clip. Automatic transcription is a separate approved service.');\nconst audioMode=input.audioMode||'original';\ncheck(['original','silent'].includes(audioMode), 'Choose original sound or silent footage.');\ncheck(audioMode==='original'||purpose==='product-demo','Keep the original speaker’s voice for captioned speech and customer stories.');\nconst speechVolume=input.speechVolume===undefined?100:input.speechVolume;\ncheck(Number.isFinite(speechVolume)&&speechVolume>=25&&speechVolume<=200,'Source volume must be 25–200 percent. Listen for distortion.');\nconst music=input.music||[];\ncheck(Array.isArray(music)&&music.length<=1,'Choose at most one music file.');\nif(music.length){const m=music[0];check(m.kind==='audio'&&typeof m.assetId==='string'&&m.assetId&&typeof m.versionId==='string'&&m.versionId&&typeof m.url==='string'&&/^(https:\\/\\/|http:\\/\\/(localhost|127\\.0\\.0\\.1)(:\\d+)?\\/|\\/api\\/media\\/|sm-media:|blob:)/.test(m.url)&&!/^https?:\\/\\/[^/?#]*@/.test(m.url)&&Number.isFinite(m.duration)&&m.duration>=duration,'Choose a saved, rights-cleared music file long enough for the full clip.');}\nconst clips=[], audioItems=[], captions=[], overlays=[];\nlet cursor=0;\ncuts.forEach((cut,index)=>{\n const length=round(cut.to-cut.from), id='selection-'+(index+1);\n clips.push({id,kind:'video',trackId:'video',asset:copy(source),assetId:source.assetId,versionId:source.versionId,url:source.url,title:source.name||'Original video',start:round(cursor),duration:length,trimStart:cut.from,speed:1,volume:0,transform:{fit,scale:1,x:cropX,y:0,rotation:0,opacity:1},motion:{type:'none'},transition:{type:'Cut',duration:0}});\n // Dedicated source audio: editing and rendering use the same trimmed interval,\n // and muted visual clips prevent a second embedded copy at normal export.\n if(audioMode==='original')audioItems.push({id:id+'-sound',trackId:'speech',asset:copy(source),assetId:source.assetId,versionId:source.versionId,url:source.url,title:'Original speech',start:round(cursor),duration:length,sourceOffset:cut.from,trimStart:cut.from,volume:speechVolume,rate:1,fadeIn:0,fadeOut:0});\n for (const cue of cues) {\n  const from=Math.max(cut.from,cue.start),to=Math.min(cut.to,cue.end);\n  if(to<=from)continue;\n  // A cut inside a subtitle changes what the words mean. Require reviewed\n  // boundaries rather than show an entire quote over a partial source phrase.\n  check(cue.start >= cut.from-.05 && cue.end <= cut.to+.05, 'A cut splits a subtitle. Move the cut to a phrase boundary or revise the transcript.');\n  captions.push({id:'caption-'+captions.length,trackId:'captions',type:'text',text:cue.text,start:round(cursor+from-cut.from),end:round(cursor+to-cut.from),font:'Hanken Grotesk',size:aspect==='9:16'?15:21,color:style==='Emphasis'?'#F7F0DB':'#FFFFFF',background:'#0A0A0A',backgroundOpacity:75,backgroundPadding:5,backgroundRadius:3,width:.82,x:50,y:76,position:'center',animation:style==='Emphasis'?'pop':'none',animIn:.12,animOut:0});\n }\n cursor += length;\n});\nif(music.length){const m=music[0];audioItems.push({id:'music-bed',trackId:'music',asset:copy(m),assetId:m.assetId,versionId:m.versionId,url:m.url,title:m.name||'Music',start:0,duration,sourceOffset:0,trimStart:0,volume:audioMode==='original'?12:65,rate:1,fadeIn:.3,fadeOut:.8});}\nconst addText=(id,value,start,end,y,size)=>{if(value)overlays.push({id,trackId:'copy',type:'text',text:value,start,end,font:'Hanken Grotesk',size,color:'#F7F0DB',background:'#0A0A0A',backgroundOpacity:80,backgroundPadding:5,width:.82,x:50,y,position:'center',animation:'fade',animIn:.2,animOut:.15});};\naddText('opening',title,0,Math.min(3,duration),16,aspect==='9:16'?16:22);\naddText('byline',byline,0,Math.min(5,duration),90,7);\naddText('cta',cta,Math.max(0,duration-3),duration,17,14);\naddText('disclosure',disclosure,0,duration,95,5.5);\nconst timeline={schemaVersion:1,activeTimelineId:'short-form',name:title||'Captioned clip',aspect,aspectRatio:aspect,previewH:369,backgroundColor:'#0A0A0A',tracks:[{id:'video',type:'video',label:'Source selections'},{id:'speech',type:'audio',label:'Original speech'},{id:'music',type:'audio',label:'Music'},{id:'captions',type:'caption',label:'Reviewed subtitles'},{id:'copy',type:'text',label:'Approved copy'}],trackOrder:['video','speech','music','captions','copy'],clips,audioItems,captions,textOverlays:overlays,stickers:[],effects:[],audio:copy(audioItems),overlays:copy([...captions,...overlays]),targetDuration:duration,exportSettings:{aspect,fps:30,resolution:'1080p',quality:'high'}};\nreturn {timeline,review:{schemaVersion:1,state:'needs-human-review',humanApproved:false,purpose,durationSec:duration,source:{assetId:source.assetId,versionId:source.versionId},cuts:copy(cuts),subtitleCount:captions.length,providerCalls:0,warnings:['Watch and listen to the entire export. Confirm every caption against the actual speech and preserve the speaker’s meaning.',...(fit==='cover'?['Crop-to-fill can hide faces or demonstrations. Review framing at every cut.']:[]),'SRT provides phrase timing. No word-level alignment or automatic transcription is claimed.']}};\n"},"lineage":{"parents":[],"changes":"Packaged original Block source for StillMade."}}},{"manifest":{"schemaVersion":1,"sdkVersion":"0.1.0","id":"sm.editor","version":"2.2.9","name":"Editor","description":"Build and render a complete editable timeline, including coded vector scenes whose transforms may be omitted or retained in the scene document.","kind":"workspace","runtime":"javascript","entry":"src/run.js","license":"MIT","provenance":{"notice":"Original source (authorship declared by the packager)\nLicense: MIT\nChanges: Original implementation declared by the packager; no reused repository or dependency code.\nFiles: LICENSE, src/run.js, src/view.json\n\nMIT License\n\nCopyright (c) <year> <copyright holders>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and \nassociated documentation files (the \"Software\"), to deal in the Software without restriction, including \nwithout limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \ncopies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the \nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial \nportions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT \nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO \nEVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER \nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE \nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n","portableSources":[{"kind":"original","license":"MIT","paths":["LICENSE","src/run.js","src/view.json"],"evidence":["upstream/0/LICENSE","upstream/0/src/run.js","upstream/0/src/view.json"],"changes":"Original implementation declared by the packager; no reused repository or dependency code."}]},"inputs":{"editor":{"type":"timeline","context":"editor","primary":true,"required":false,"default":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[],"audioItems":[],"captions":[],"textOverlays":[],"effects":[]},"description":"The complete current Editor document. All internal editing tools and retained media/version data remain together.","semantic":"editor_timeline","sources":["project"]},"assets":{"type":"asset[]","context":"assets","required":false,"default":[],"description":"Current project media used to assemble an initial editable timeline when the Editor is empty.","semantic":"legacy.asset-list.assets","sources":["project"]},"updatedEditor":{"type":"timeline","required":false,"default":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[],"audioItems":[],"captions":[],"textOverlays":[],"effects":[]},"description":"The complete edited timeline prepared in this workspace.","semantic":"legacy.timeline.updatededitor","sources":["upstream","user","default"]},"commit":{"type":"boolean","default":false,"description":"Prepare the edited Editor document for StillMade review and Apply.","semantic":"legacy.boolean.commit","required":false,"sources":["user","default"]},"action":{"type":"text","required":false,"default":"none","description":"The Block-owned interface selects a declared host action.","semantic":"legacy.text.action","sources":["user","default"]},"renderFps":{"type":"integer","min":12,"max":60,"default":30,"description":"Frames per second sent to the declared final-render service.","semantic":"legacy.integer.renderfps","required":false,"sources":["user","default"]},"renderResolution":{"type":"integer","min":480,"max":2160,"default":1080,"description":"Output height sent to the declared final-render service.","semantic":"legacy.integer.renderresolution","required":false,"sources":["user","default"]},"renderQuality":{"type":"text","default":"high","description":"Output quality sent to the declared final-render service.","semantic":"legacy.text.renderquality","required":false,"sources":["user","default"]}},"outputs":{"editor":{"type":"timeline","primary":true,"role":"editor_timeline","description":"The complete edited timeline for immediate use and downstream Blocks.","semantic":"editor_timeline"},"edit":{"type":"workspace-edit","description":"An exact before/after Editor change reviewed before it updates the project.","semantic":"legacy.workspace-edit.edit"},"mediaAction":{"type":"approval","required":false,"role":"portable_media_action","description":"A bounded final-render request executed only after the user chooses Render and play.","semantic":"portable_media_action"}},"permissions":{"project":["context.editor.read","context.assets.read","workspace.editor.propose"],"network":[],"filesystem":[],"secrets":[],"actions":["final.render"]},"ui":[],"platforms":{"phone":{"supported":true},"browser":{"supported":true},"desktop":{"supported":true}}},"code":"const copy = value => JSON.parse(JSON.stringify(value));\nconst source = copy(input.editor || {schemaVersion:1,activeTimelineId:'timeline-1',tracks:[],clips:[],audioItems:[],captions:[],textOverlays:[],effects:[]});\nconst assets=Array.isArray(input.assets)?input.assets.filter(asset=>asset&&['image','video','audio'].includes(asset.kind)&&asset.assetId&&asset.versionId&&asset.url).slice(0,500):[];\nconst assembled=copy(source);if(!assembled.clips?.length&&!assembled.audioItems?.length&&assets.length){assembled.tracks=[{id:'video',kind:'video',label:'Video'},{id:'audio',kind:'audio',label:'Audio'}];let cursor=0;assembled.clips=assets.filter(asset=>asset.kind!=='audio').map((asset,index)=>{const duration=Math.max(.001,Number(asset.duration)||Number(asset.durationSec)||4),clip={id:'clip-'+String(index+1)+'-'+String(asset.assetId),trackId:'video',start:cursor,duration,trimStart:0,speed:1,volume:1,asset:copy(asset),url:asset.url};cursor+=duration;return clip});assembled.audioItems=assets.filter(asset=>asset.kind==='audio').map((asset,index)=>({id:'audio-'+String(index+1)+'-'+String(asset.assetId),trackId:'audio',start:0,duration:Math.max(.001,Number(asset.duration)||Number(asset.durationSec)||cursor||1),trimStart:0,volume:1,asset:copy(asset),url:asset.url}));assembled.targetDuration=Math.max(cursor,...assembled.audioItems.map(item=>item.duration));}\nconst candidate = input.commit || input.action === 'render' ? copy(input.updatedEditor) : assembled;\nif (!candidate || Array.isArray(candidate) || candidate.schemaVersion !== 1 || typeof candidate.activeTimelineId !== 'string' || !candidate.activeTimelineId) throw new Error('Keep the complete version 1 Editor document and active timeline identity.');\nconst names=['tracks','clips','audioItems','captions','textOverlays','stickers','effects','markers','fxEvents','liveOverlays','mediaItems','timelineVersions'];\nif (!names.every(name => candidate[name] === undefined || Array.isArray(candidate[name]) && candidate[name].length <= 10000 && candidate[name].every(item => item && typeof item === 'object' && !Array.isArray(item) && typeof item.id === 'string' && item.id.length > 0 && item.id.length <= 200) && new Set(candidate[name].map(item => item.id)).size === candidate[name].length)) throw new Error('Editor collections need valid distinct retained item IDs.');\nconst itemEnd=item=>Math.max(0,Number(item.start)||0)+Math.max(.001,Number(item.duration)||Number(item.durationMs)/1000||.001);\nconst outputs={editor:candidate,edit:{schemaVersion:1,title:`Update Editor timeline ${candidate.activeTimelineId}`,field:'editor',before:source,after:candidate}};\nif(input.action==='render'){const clips=Array.isArray(candidate.clips)?candidate.clips:[],audio=Array.isArray(candidate.audioItems)?candidate.audioItems:[],overlays=[...(candidate.captions||[]),...(candidate.textOverlays||[]),...(candidate.effects||[])],targetDuration=Math.max(.001,Number(candidate.targetDuration)||0,...clips.map(itemEnd),...audio.map(itemEnd),...overlays.map(itemEnd));outputs.mediaAction={schemaVersion:1,kind:'stillmade.media-action',operation:'final.render',request:{schemaVersion:1,kind:'video',timeline:{...candidate,clips,audio,overlays,targetDuration},settings:{fps:input.renderFps,resolution:input.renderResolution,quality:input.renderQuality},source:{id:'sm.editor',version:'2.2.9'}},resultPort:null};}\nreturn outputs;\n","view":{"html":"<main class=\"editor-workspace\">\n  <header><div><small>Production workspace</small><h1>Editor</h1><p id=\"summary\">Loading the complete timeline…</p></div><div class=\"actions\"><button id=\"build\" type=\"button\" class=\"secondary\">Build from project media</button><button id=\"undo\" type=\"button\" class=\"secondary\">Undo</button><button id=\"redo\" type=\"button\" class=\"secondary\">Redo</button><button id=\"snapshot\" type=\"button\" class=\"secondary\">Save version</button><button id=\"reset\" type=\"button\" class=\"secondary\">Reset changes</button><button id=\"addText\" type=\"button\" class=\"secondary\">Add text</button><button id=\"addCaption\" type=\"button\" class=\"secondary\">Add caption</button><button id=\"save\" type=\"button\" data-stillmade-action=\"run\">Review changes</button></div></header>\n  <output id=\"status\" role=\"status\" aria-live=\"polite\"></output>\n  <p id=\"sharedResult\" class=\"hint\" aria-live=\"polite\"></p>\n  <section id=\"recovery\" hidden><h2>Keep your work safe</h2><p id=\"recoveryMessage\"></p><div class=\"row\"><button id=\"retryShared\" type=\"button\" class=\"secondary\">Retry checked changes</button><button id=\"discardShared\" type=\"button\" class=\"secondary\">Discard my unshared changes</button><button id=\"resetSharedSource\" type=\"button\" class=\"secondary\" hidden>Review updated project timeline</button></div><p>The project source changed. Starting from it replaces the shared timeline draft for everyone. Unfinished JSON is retained for separate review.</p><button id=\"confirmSourceReset\" type=\"button\" hidden>Replace everyone's shared draft with the updated project timeline</button></section>\n  <section><h2>Timeline</h2><div class=\"grid\"><label>Active timeline<input id=\"timelineId\" type=\"text\" disabled></label><label>Aspect ratio<input id=\"aspect\" type=\"text\"></label><label>Playhead (seconds)<input id=\"playhead\" type=\"range\" min=\"0\" max=\"1\" step=\"0.05\" value=\"0\"></label></div><p id=\"timecode\" class=\"hint\"></p><div id=\"composition\" class=\"cards\"></div></section>\n  <section><h2>Project media</h2><p class=\"hint\">Preview an exact saved version, then add it to this timeline without leaving the Block.</p><img id=\"imagePreview\" alt=\"Selected project media preview\" hidden><video id=\"videoPreview\" controls hidden></video><audio id=\"audioPreview\" controls hidden></audio><div id=\"assets\" class=\"cards media-grid\"></div></section>\n  <section><h2>Video</h2><div id=\"clips\" class=\"cards\"></div></section>\n  <section><h2>Audio and scoring</h2><div id=\"audio\" class=\"cards\"></div></section>\n  <section><h2>Saved timeline versions</h2><div id=\"versions\" class=\"cards\"></div></section>\n  <section><h2>Text and motion graphics</h2><div id=\"text\" class=\"cards\"></div><p id=\"graphics\" class=\"hint\"></p></section>\n  <section><h2>Captions</h2><div id=\"captions\" class=\"cards\"></div></section>\n  <section><div class=\"card-head\"><h2>Effects</h2><button id=\"addEffect\" type=\"button\" class=\"secondary\">Add effect</button></div><div id=\"effects\" class=\"cards\"></div></section>\n  <details id=\"rawDetails\"><summary>Complete Editor data</summary><p>All timeline lanes, motion graphics, grade settings, transitions, scoring, versions, and export settings are retained. Use this editor for fields not shown on the lane cards.</p><p id=\"rawNotice\" class=\"hint\"></p><textarea id=\"raw\" class=\"raw\" spellcheck=\"false\" aria-label=\"Complete Editor data\"></textarea><div class=\"row\"><button id=\"applyRaw\" type=\"button\" class=\"secondary\">Apply JSON to workspace</button><button id=\"discardRaw\" type=\"button\" class=\"secondary\">Discard shared JSON draft</button></div></details>\n<section><h2>Final export</h2><p>Render this exact timeline through StillMade’s approved device renderer.</p><div class=\"grid\"><label>Frame rate<select id=\"renderFps\"><option value=\"24\">24 fps</option><option value=\"30\" selected>30 fps</option><option value=\"60\">60 fps</option></select></label><label>Resolution<select id=\"renderResolution\"><option value=\"720\">720p</option><option value=\"1080\" selected>1080p</option><option value=\"2160\">2160p</option></select></label><label>Quality<select id=\"renderQuality\"><option value=\"standard\">Standard</option><option value=\"high\" selected>High</option></select></label></div><button id=\"renderFinal\" type=\"button\">Render final video</button></section></main>\n","css":".editor-workspace{max-width:1160px;margin:0 auto;padding:8px;color:var(--fg)}header,.actions,.card-head,.row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}header{justify-content:space-between;margin-bottom:14px}header h1{margin:2px 0}header p,header small,details p,output,.hint{color:var(--fg-muted)}section,details{margin:12px 0;padding:16px;border:1px solid var(--border-tok);border-radius:var(--r-3);background:var(--bg-elev-1)}section h2{margin:0 0 10px}.cards{display:grid;gap:10px}.card{padding:12px;border:1px solid var(--border-tok);border-radius:var(--r-2);background:var(--bg)}.card-head{justify-content:space-between}.card h3{margin:0;font-size:16px}.grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}label{display:grid;gap:5px;margin:7px 0;font-size:13px;font-weight:600}input,textarea{width:100%;background:var(--bg)}textarea{min-height:70px;resize:vertical}.wide{grid-column:1/-1}.secondary{background:transparent;color:var(--fg)}.danger{background:transparent;color:var(--signal)}.raw{min-height:440px;font-family:var(--font-mono);font-size:12px}output{display:block;min-height:24px;margin:8px 2px}\n@media(max-width:900px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:560px){.editor-workspace{padding:0}.grid{grid-template-columns:1fr}.actions{width:100%}.actions button{flex:1}section,details{padding:12px}}\n.media-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.media-card p{margin:4px 0;color:var(--fg-muted)}video,audio{display:block;width:100%;margin:10px 0}video[hidden],audio[hidden]{display:none}select{width:100%;background:var(--bg)}\n.card,.grid>*{min-width:0}.card h3,.card strong,.card p{overflow-wrap:anywhere}img{max-width:100%;height:auto}@media(max-width:560px){.media-grid{grid-template-columns:1fr}}\n","javascript":"const status=document.getElementById('status'),summary=document.getElementById('summary'),raw=document.getElementById('raw'),save=document.getElementById('save'),aspect=document.getElementById('aspect'),timelineId=document.getElementById('timelineId'),graphics=document.getElementById('graphics'),build=document.getElementById('build'),imagePreview=document.getElementById('imagePreview'),videoPreview=document.getElementById('videoPreview'),audioPreview=document.getElementById('audioPreview'),playhead=document.getElementById('playhead'),timecode=document.getElementById('timecode');\nconst empty={schemaVersion:1,activeTimelineId:'timeline-1',tracks:[],clips:[],audioItems:[],captions:[],textOverlays:[],effects:[]};\nlet source=empty,draft=empty,assets=[],previewUrl='',previewSerial=0,busy=false,revision=0;\nlet shared=null,scratchShared=null,optionsShared=null,scratch={text:null,base:null},options={renderFps:30,renderResolution:1080,renderQuality:'high'};\nlet access={canEdit:false,error:null},scratchAccess={canEdit:false,error:null},optionsAccess={canEdit:false,error:null},sourceResetArmed=false,rawBaseline=null,rawStale=false;\nlet undoStack=[],redoStack=[],historyBefore=null,historyAfter=null;\nconst tokens=new Map(),identities=new Map(),pages=new Map();\nconst clone=value=>JSON.parse(JSON.stringify(value));\nconst text=value=>value===undefined||value===null?'':String(value);\nconst uniqueId=prefix=>prefix+'-'+Date.now().toString(36)+'-'+Math.random().toString(36).slice(2,14);\nconst blocked=()=>busy||!shared||!scratchShared||!optionsShared||!access.canEdit||!scratchAccess.canEdit||!optionsAccess.canEdit||!!access.error||!!scratchAccess.error||!!optionsAccess.error;\nconst allowed=()=>access.canEdit&&scratchAccess.canEdit&&optionsAccess.canEdit&&!access.error&&!scratchAccess.error&&!optionsAccess.error;\nconst token=(kind,item)=>{const key=JSON.stringify(kind==='asset'?[kind,item.kind,item.assetId,item.versionId]:[kind,item.id]);if(!tokens.has(key)){const value='i'+String(tokens.size+1);tokens.set(key,value);}const handle=tokens.get(key);identities.set(handle,{kind,item});return handle;};\nconst normalize=value=>({...value,tracks:Array.isArray(value.tracks)?value.tracks:[],clips:Array.isArray(value.clips)?value.clips:[],audioItems:Array.isArray(value.audioItems)?value.audioItems:[],captions:Array.isArray(value.captions)?value.captions:[],textOverlays:Array.isArray(value.textOverlays)?value.textOverlays:[],effects:Array.isArray(value.effects)?value.effects:[]});\nconst assemble=()=>{const next=clone(source),media=assets.filter(asset=>asset&&['image','video','audio'].includes(asset.kind)&&asset.assetId&&asset.versionId&&asset.url).slice(0,500);if(next.clips?.length||next.audioItems?.length||!media.length)return normalize(next);next.tracks=[{id:'video',kind:'video',label:'Video'},{id:'audio',kind:'audio',label:'Audio'}];let cursor=0;next.clips=media.filter(asset=>asset.kind!=='audio').map((asset,index)=>{const duration=Math.max(.001,Number(asset.duration)||Number(asset.durationSec)||4),clip={id:'clip-'+String(index+1)+'-'+text(asset.assetId),trackId:'video',start:cursor,duration,trimStart:0,speed:1,volume:1,asset:clone(asset),url:asset.url};cursor+=duration;return clip;});next.audioItems=media.filter(asset=>asset.kind==='audio').map((asset,index)=>({id:'audio-'+String(index+1)+'-'+text(asset.assetId),trackId:'audio',start:0,duration:Math.max(.001,Number(asset.duration)||Number(asset.durationSec)||cursor||1),trimStart:0,volume:1,asset:clone(asset),url:asset.url}));next.targetDuration=Math.max(cursor,...next.audioItems.map(item=>item.duration));return normalize(next);};\nconst field=(label,action,value,type='text',wide=false)=>({tag:'label',className:wide?'wide':'',children:[{tag:'span',text:label},{tag:'input',id:'control-'+action.replace(':','-'),type,action,value:Number.isFinite(value)?value:text(value),disabled:blocked(),label}]});\nconst remove=action=>({tag:'button',action,text:'Remove',className:'danger',disabled:blocked()});\nconst assetCard=(item,index)=>({tag:'article',id:'card-'+token('asset',item),className:'card media-card',children:[{tag:'strong',text:text(item.name)||text(item.assetId)},{tag:'p',text:text(item.kind)+' · version '+text(item.versionId)},{tag:'div',className:'row',children:[{tag:'button',action:'preview-asset:'+token('asset',item),text:'Preview',className:'secondary',disabled:false},{tag:'button',action:'add-asset:'+token('asset',item),text:item.kind==='audio'?'Add audio':'Add clip',className:'secondary',disabled:blocked()}]}]});\nconst clipCard=(item,index)=>({tag:'article',id:'card-'+token('clip',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.label)||text(item.name)||text(item.id)},{tag:'div',className:'row',children:[{tag:'button',action:'preview-clip:'+token('clip',item),text:'Preview',className:'secondary',disabled:!(item.asset||item.assetId)},{tag:'button',action:'move-clip-up:'+token('clip',item),text:'Up',className:'secondary',disabled:blocked()||index===0},{tag:'button',action:'move-clip-down:'+token('clip',item),text:'Down',className:'secondary',disabled:blocked()||index===draft.clips.length-1},{tag:'button',action:'split-clip:'+token('clip',item),text:'Split',className:'secondary',disabled:blocked()||Number(item.duration)<=0.002},{tag:'button',action:'duplicate-clip:'+token('clip',item),text:'Duplicate',className:'secondary',disabled:blocked()},remove('remove-clip:'+token('clip',item))]}]},{tag:'div',className:'grid',children:[field('Track','clip-track:'+token('clip',item),item.trackId),field('Start (seconds)','clip-start:'+token('clip',item),item.start,'number'),field('Length (seconds)','clip-duration:'+token('clip',item),item.duration,'number'),field('Trim start','clip-trim:'+token('clip',item),item.trimStart,'number'),field('Speed','clip-speed:'+token('clip',item),item.speed,'number'),field('Volume','clip-volume:'+token('clip',item),item.volume,'number'),field('Transition','clip-transition:'+token('clip',item),item.transition&&item.transition.type),field('Transition length','clip-transition-duration:'+token('clip',item),item.transition&&item.transition.duration,'number'),field('Motion','clip-motion:'+token('clip',item),item.motion&&item.motion.type),field('Motion easing','clip-easing:'+token('clip',item),item.motion&&item.motion.easing),field('Opacity','clip-opacity:'+token('clip',item),item.transform&&item.transform.opacity!==undefined?item.transform.opacity:item.opacity,'number'),{tag:'label',children:[{tag:'span',text:'Reverse playback'},{tag:'input',type:'checkbox',id:'control-'+('clip-reverse:'+token('clip',item)).replace(':','-'),action:'clip-reverse:'+token('clip',item),checked:!!item.reverse,disabled:blocked(),label:'Reverse playback'}]}]}]});\nconst audioCard=(item,index)=>({tag:'article',id:'card-'+token('audio',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.label)||text(item.name)||text(item.id)},{tag:'div',className:'row',children:[{tag:'button',action:'preview-audio:'+token('audio',item),text:'Preview',className:'secondary',disabled:!(item.asset||item.assetId)},remove('remove-audio:'+token('audio',item))]}]},{tag:'div',className:'grid',children:[field('Track','audio-track:'+token('audio',item),item.trackId),field('Start (seconds)','audio-start:'+token('audio',item),item.start,'number'),field('Length (seconds)','audio-duration:'+token('audio',item),item.duration,'number'),field('Trim start','audio-trim:'+token('audio',item),item.trimStart===undefined?item.sourceOffset:item.trimStart,'number'),field('Volume','audio-volume:'+token('audio',item),item.volume,'number'),field('Fade in','audio-fade-in:'+token('audio',item),item.fadeIn,'number'),field('Fade out','audio-fade-out:'+token('audio',item),item.fadeOut,'number'),field('Ducking','audio-ducking:'+token('audio',item),item.ducking,'number'),field('Playback speed','audio-rate:'+token('audio',item),item.rate,'number'),{tag:'label',children:[{tag:'span',text:'Loop source'},{tag:'input',type:'checkbox',id:'control-'+('audio-loop:'+token('audio',item)).replace(':','-'),action:'audio-loop:'+token('audio',item),checked:!!item.loop,disabled:blocked(),label:'Loop source'}]},{tag:'label',children:[{tag:'span',text:'Muted'},{tag:'input',type:'checkbox',id:'control-'+('audio-muted:'+token('audio',item)).replace(':','-'),action:'audio-muted:'+token('audio',item),checked:!!item.muted,disabled:blocked(),label:'Muted'}]}]}]});\nconst textCard=(item,index)=>({tag:'article',id:'card-'+token('text',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.id)},remove('remove-text:'+token('text',item))]},{tag:'div',className:'grid',children:[field('Text','text-value:'+token('text',item),item.text,'text',true),field('Track','text-track:'+token('text',item),item.trackId),field('Start (seconds)','text-start:'+token('text',item),item.start,'number'),field('Length (seconds)','text-duration:'+token('text',item),item.duration,'number'),field('Animation','text-animation:'+token('text',item),item.animation)]}]});\nconst captionCard=(item,index)=>({tag:'article',id:'card-'+token('caption',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.id)},remove('remove-caption:'+token('caption',item))]},{tag:'div',className:'grid',children:[field('Caption','caption-value:'+token('caption',item),item.text,'text',true),field('Track','caption-track:'+token('caption',item),item.trackId),field('Start (seconds)','caption-start:'+token('caption',item),item.start,'number'),field('End (seconds)','caption-end:'+token('caption',item),item.end,'number'),field('Animation','caption-animation:'+token('caption',item),item.animation)]}]});\nconst effectCard=(item,index)=>({tag:'article',id:'card-'+token('effect',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.type)||text(item.id)},remove('remove-effect:'+token('effect',item))]},{tag:'div',className:'grid',children:[field('Type','effect-type:'+token('effect',item),item.type),field('Track','effect-track:'+token('effect',item),item.trackId),field('Start (seconds)','effect-start:'+token('effect',item),item.start,'number'),field('Length (seconds)','effect-duration:'+token('effect',item),item.duration,'number'),field('Intensity','effect-intensity:'+token('effect',item),item.intensity,'number')]}]});\nconst largeTimeline=()=>draft.clips.length+draft.audioItems.length+draft.textOverlays.length+draft.captions.length+draft.effects.length>2000;\nconst itemFinish=item=>(Number(item.start)||0)+Math.max(.001,Number(item.duration)||Number(item.end)-(Number(item.start)||0)||.001);\nconst composition=()=>{const at=Number(playhead.value)||0;if(largeTimeline()){StillMade.render('composition',[{tag:'strong',text:'Lightweight preview · large timeline'},{tag:'p',text:'Partial preview: the live composition summary is paused to keep editing responsive. Every timeline item is retained for editing and the complete final render.'},{tag:'p',text:'The personal playhead uses the saved timeline duration, or a 24-hour preview window when none is supplied.'}]);timecode.textContent='Playhead '+at.toFixed(2)+' seconds';return;}const activeClips=draft.clips.filter(item=>at>=(Number(item.start)||0)&&at<itemFinish(item)),activeAudio=draft.audioItems.filter(item=>at>=(Number(item.start)||0)&&at<itemFinish(item)),activeOverlays=[...draft.textOverlays,...draft.captions,...draft.effects].filter(item=>at>=(Number(item.start)||0)&&at<itemFinish(item));StillMade.render('composition',[{tag:'strong',text:'At '+at.toFixed(2)+'s'},{tag:'p',text:(activeClips.length?activeClips.slice(0,12).map(item=>text(item.label)||text(item.id)).join(', '):'No video')+' · '+String(activeAudio.length)+' audio · '+String(activeOverlays.length)+' overlays'}]);timecode.textContent='Playhead '+at.toFixed(2)+' seconds';};\nconst rawIsOpen=()=>document.getElementById('rawDetails').getAttribute('open')!==null;\nconst renderRawPreview=()=>{if(!rawIsOpen())return;if(scratch.text!==null){if(raw.value!==scratch.text)raw.value=scratch.text;return;}rawBaseline=draft;const value=JSON.stringify(draft,null,2);if(raw.value!==value)raw.value=value;};\nconst schedulePreview=()=>{if(rawIsOpen())StillMade.scheduleSharedEdit('editorRawPreview',renderRawPreview);};\nconst drawRecovery=()=>{const states=[access,scratchAccess,optionsAccess],failure=states.find(value=>value.error),sourceMismatch=states.some(value=>value.sourceConflict),waiting=states.some(value=>value.pending),editable=states.every(value=>value.canEdit);document.getElementById('recovery').hidden=!failure;document.getElementById('recoveryMessage').textContent=failure?failure.error:'';document.getElementById('retryShared').disabled=!editable||waiting||sourceMismatch||busy;document.getElementById('discardShared').disabled=!editable||waiting||sourceMismatch||busy;document.getElementById('resetSharedSource').hidden=!sourceMismatch;document.getElementById('resetSharedSource').disabled=!editable||waiting||busy;document.getElementById('confirmSourceReset').hidden=!sourceMismatch||!sourceResetArmed;document.getElementById('confirmSourceReset').disabled=!editable||waiting||busy;document.getElementById('rawNotice').textContent=scratch.text===null?'JSON typing is shared live. Apply checks the original displayed values before updating the timeline.':rawStale?'The timeline changed. Shared JSON text is retained; Apply will check for conflicting edits.':'This unfinished JSON draft is shared live. Apply it when ready, or discard the shared scratch.';save.disabled=blocked()||scratch.text!==null;document.getElementById('renderFinal').disabled=blocked()||scratch.text!==null;document.getElementById('applyRaw').disabled=blocked()||scratch.text===null;document.getElementById('discardRaw').disabled=blocked()||scratch.text===null;document.getElementById('undo').disabled=blocked()||(!undoStack.length&&!historyBefore);document.getElementById('redo').disabled=blocked()||!redoStack.length;};\nconst versionCard=(item,index)=>({tag:'article',id:'card-'+token('version',item),className:'card',children:[{tag:'strong',text:text(item.label)||text(item.id)},{tag:'p',text:text(item.createdAt)},{tag:'button',action:'restore-version:'+token('version',item),text:'Restore this version',className:'secondary',disabled:blocked()}]});\nconst renderPage=(target,rows,card,size,emptyMessage)=>{const last=Math.max(0,Math.ceil(rows.length/size)-1),page=Math.min(last,pages.get(target)||0);pages.set(target,page);const content=rows.length?rows.slice(page*size,(page+1)*size).map((item,index)=>card(item,page*size+index)):[{tag:'p',text:emptyMessage}];if(rows.length>size)content.push({tag:'div',className:'row',children:[{tag:'button',action:'page-prev:'+target,text:'Previous',className:'secondary',disabled:page===0},{tag:'span',text:'Page '+String(page+1)+' of '+String(last+1)+' · '+String(rows.length)+' items'},{tag:'button',action:'page-next:'+target,text:'Next',className:'secondary',disabled:page===last}]});StillMade.render(target,content);};\nconst drawOptions=()=>{document.getElementById('renderFps').value=String(options.renderFps);document.getElementById('renderResolution').value=String(options.renderResolution);document.getElementById('renderQuality').value=options.renderQuality;};\nconst draw=()=>{renderPage('assets',assets,assetCard,12,'No saved project media is available.');renderPage('clips',draft.clips,clipCard,4,'No video clips.');renderPage('audio',draft.audioItems,audioCard,4,'No audio items.');renderPage('text',draft.textOverlays,textCard,8,'No text overlays.');renderPage('captions',draft.captions,captionCard,8,'No captions.');renderPage('effects',draft.effects,effectCard,8,'No effects.');renderPage('versions',Array.isArray(draft.timelineVersions)?draft.timelineVersions:[],versionCard,5,'No saved versions yet.');timelineId.value=text(draft.activeTimelineId);const duration=largeTimeline()?Math.max(1,Number(draft.targetDuration)||86400,Number(playhead.value)||0):Math.max(1,Number(draft.targetDuration)||0,...draft.clips.map(itemFinish),...draft.audioItems.map(itemFinish));playhead.max=String(duration);StillMade.scheduleSharedEdit('editorComposition',composition);aspect.value=text(draft.aspect);const mg=(Array.isArray(draft.fullscreenFrames)?draft.fullscreenFrames.length:0)+(Array.isArray(draft.figureSweeps)?draft.figureSweeps.length:0)+(Array.isArray(draft.graphs)?draft.graphs.length:0);graphics.textContent=String(mg)+' motion graphic item'+(mg===1?'':'s')+' retained in this Editor Block. Use Complete Editor data for advanced motion-graphics fields.';summary.textContent=String(draft.clips.length)+' video · '+String(draft.audioItems.length)+' audio · '+String(draft.captions.length)+' captions · '+String(draft.textOverlays.length)+' text';['reset','addText','addCaption','addEffect','snapshot','renderFps','renderResolution','renderQuality'].forEach(id=>{document.getElementById(id).disabled=blocked();});build.disabled=blocked()||!assets.length;aspect.disabled=blocked();raw.disabled=blocked();drawOptions();drawRecovery();schedulePreview();};\nconst captureHistory=()=>{if(!historyBefore)return;const before=historyBefore,after=historyAfter;historyBefore=null;historyAfter=null;try{const forward=StillMade.diffDocument(before,after);if(forward.length){undoStack=[...undoStack,{forward,inverse:StillMade.diffDocument(after,before)}].slice(-50);redoStack=[];}}catch(error){undoStack=[];redoStack=[];status.textContent='This change is too large for local undo. The shared timeline is retained.';}drawRecovery();};\nconst commitEdit=(next,record=true)=>{if(record){if(!historyBefore)historyBefore=draft;historyAfter=next;StillMade.scheduleSharedEdit('editorHistory',captureHistory);}draft=next;revision+=1;sourceResetArmed=false;if(scratch.text!==null)rawStale=true;shared.changed();schedulePreview();StillMade.scheduleSharedEdit('editorComposition',composition);drawRecovery();status.textContent='Sharing timeline changes. Review changes applies the document to your project.';};\nconst replaceRows=(kind,rows)=>{if(kind==='clip')commitEdit({...draft,clips:rows});if(kind==='audio')commitEdit({...draft,audioItems:rows});if(kind==='text')commitEdit({...draft,textOverlays:rows});if(kind==='caption')commitEdit({...draft,captions:rows});if(kind==='effect')commitEdit({...draft,effects:rows});};\nconst rowsFor=kind=>kind==='clip'?draft.clips:kind==='audio'?draft.audioItems:kind==='text'?draft.textOverlays:kind==='caption'?draft.captions:kind==='effect'?draft.effects:kind==='version'?(draft.timelineVersions||[]):[];\nconst previewItem=(item,kind,trim=0)=>{const serial=++previewSerial;if(previewUrl){StillMade.releaseMedia(previewUrl);previewUrl='';}imagePreview.hidden=true;videoPreview.hidden=true;audioPreview.hidden=true;const value=item.asset||item,mediaKind=value.kind||kind,request=mediaKind==='image'?StillMade.previewImage(value):StillMade.previewMedia({...value,kind:mediaKind});request.then(result=>{if(serial!==previewSerial){if(mediaKind!=='image')StillMade.releaseMedia(result.url);return;}if(mediaKind==='image'){imagePreview.src=result.url;imagePreview.hidden=false;}else if(mediaKind==='audio'){previewUrl=result.url;audioPreview.src=result.url;audioPreview.hidden=false;}else{previewUrl=result.url;videoPreview.src=result.url;videoPreview.currentTime=Math.max(0,Number(trim)||0);videoPreview.hidden=false;}status.textContent='Previewing '+text(item.label||item.name||item.id||item.assetId)+'.';}).catch(error=>{if(serial===previewSerial)status.textContent=error.message;});};\naspect.addEventListener('input',()=>{if(blocked())return;commitEdit({...draft,aspect:aspect.value});});\nplayhead.addEventListener('input',()=>{timecode.textContent='Playhead '+(Number(playhead.value)||0).toFixed(2)+' seconds';StillMade.scheduleSharedEdit('editorComposition',composition);});\ndocument.getElementById('rawDetails').addEventListener('toggle',renderRawPreview);\nraw.addEventListener('input',()=>{if(blocked())return;scratch={text:raw.value,base:scratch.text===null?(rawBaseline||draft):scratch.base};scratchShared.changed();drawRecovery();});\ndocument.getElementById('discardRaw').addEventListener('click',()=>{if(blocked())return;scratch={text:null,base:null};rawStale=false;scratchShared.changed();renderRawPreview();drawRecovery();});\nStillMade.onAction(event=>{const parts=event.action.split(':'),kind=parts[0],handle=parts[1];if(kind==='page-prev'||kind==='page-next'){if(!['assets','clips','audio','text','captions','effects','versions'].includes(handle))return;pages.set(handle,Math.max(0,(pages.get(handle)||0)+(kind==='page-prev'?-1:1)));draw();return;}const identity=identities.get(handle);if(!identity)return;const rows=rowsFor(identity.kind),item=(identity.kind==='asset'?assets:rows).includes(identity.item)?identity.item:null,index=rows.indexOf(item);if(!item)return;\n if(kind==='preview-clip'&&identity.kind==='clip'){previewItem(item,'video',item.trimStart);return;}if(kind==='preview-audio'&&identity.kind==='audio'){previewItem(item,'audio');return;}if(kind==='preview-asset'&&identity.kind==='asset'){previewItem(item,item.kind);return;}if(blocked())return;\n if(kind==='restore-version'&&identity.kind==='version'){commitEdit({...draft,clips:clone(item.clips||[]),audioItems:clone(item.audioItems||[]),captions:clone(item.captions||[]),textOverlays:clone(item.textOverlays||[]),effects:clone(item.effects||[])});draw();return;}\n if(kind==='add-asset'&&identity.kind==='asset'){const media=clone(item),duration=Math.max(.001,Number(media.duration)||Number(media.durationSec)||4);if(media.kind==='audio')commitEdit({...draft,audioItems:[...draft.audioItems,{id:uniqueId('audio'),trackId:'audio',start:0,duration,trimStart:0,volume:1,asset:media,url:media.url}]});else{const start=draft.clips.reduce((end,value)=>Math.max(end,itemFinish(value)),0);commitEdit({...draft,clips:[...draft.clips,{id:uniqueId('clip'),trackId:'video',start,duration,trimStart:0,speed:1,volume:1,asset:media,url:media.url}]});}draw();return;}\n if((kind==='move-clip-up'||kind==='move-clip-down')&&identity.kind==='clip'){const targetIndex=index+(kind==='move-clip-up'?-1:1),target=rows.at(targetIndex);if(targetIndex<0||!target)return;const reordered=rows.slice();reordered.splice(targetIndex,1,item);reordered.splice(index,1,target);replaceRows('clip',reordered);draw();return;}\n if(kind==='duplicate-clip'&&identity.kind==='clip'){const next={...clone(item),id:uniqueId('clip-copy'),start:itemFinish(item)};replaceRows('clip',[...rows.slice(0,index+1),next,...rows.slice(index+1)]);draw();return;}\n if(kind==='split-clip'&&identity.kind==='clip'){const half=Math.max(.001,Number(item.duration)||.001)/2;if(half<.001)return;const second={...clone(item),id:uniqueId('clip-split'),start:(Number(item.start)||0)+half,duration:half,trimStart:(Number(item.trimStart)||0)+half};replaceRows('clip',[...rows.slice(0,index),{...item,duration:half},second,...rows.slice(index+1)]);draw();return;}\n if(kind==='remove-'+identity.kind&&['clip','audio','text','caption','effect'].includes(identity.kind)){const remaining=rows.slice();remaining.splice(index,1);replaceRows(identity.kind,remaining);draw();return;}\n const next={...item};let recognized=true;\n if(identity.kind==='clip'){if(kind==='clip-track')next.trackId=event.value;else if(kind==='clip-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='clip-duration')next.duration=Math.max(.001,Number(event.value)||.001);else if(kind==='clip-trim')next.trimStart=Math.max(0,Number(event.value)||0);else if(kind==='clip-speed')next.speed=Math.max(.01,Number(event.value)||1);else if(kind==='clip-volume')next.volume=Math.max(0,Number(event.value)||0);else if(kind==='clip-transition'||kind==='clip-transition-duration'){const prior=item.transition&&!Array.isArray(item.transition)?item.transition:{type:'Cut',duration:0};next.transition=kind==='clip-transition'?{...prior,type:event.value}:{...prior,duration:Math.max(0,Number(event.value)||0)};}else if(kind==='clip-opacity')next.transform={...(item.transform&&!Array.isArray(item.transform)?item.transform:{}),opacity:Math.max(0,Math.min(1,Number(event.value)||0))};else if(kind==='clip-reverse')next.reverse=event.checked;else if(kind==='clip-motion'||kind==='clip-easing'){const prior=item.motion&&!Array.isArray(item.motion)?item.motion:{type:'none',easing:'ease-in-out'};next.motion=kind==='clip-motion'?{...prior,type:event.value}:{...prior,easing:event.value};}else recognized=false;}\n else if(identity.kind==='audio'){if(kind==='audio-track')next.trackId=event.value;else if(kind==='audio-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='audio-duration')next.duration=Math.max(.001,Number(event.value)||.001);else if(kind==='audio-trim'){next.trimStart=Math.max(0,Number(event.value)||0);next.sourceOffset=next.trimStart;}else if(kind==='audio-volume')next.volume=Math.max(0,Number(event.value)||0);else if(kind==='audio-fade-in')next.fadeIn=Math.max(0,Number(event.value)||0);else if(kind==='audio-fade-out')next.fadeOut=Math.max(0,Number(event.value)||0);else if(kind==='audio-ducking')next.ducking=Math.max(0,Math.min(1,Number(event.value)||0));else if(kind==='audio-rate')next.rate=Math.max(.05,Math.min(4,Number(event.value)||1));else if(kind==='audio-loop')next.loop=event.checked;else if(kind==='audio-muted')next.muted=event.checked;else recognized=false;}\n else if(identity.kind==='text'){if(kind==='text-value')next.text=event.value;else if(kind==='text-track')next.trackId=event.value;else if(kind==='text-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='text-duration')next.duration=Math.max(.001,Number(event.value)||.001);else if(kind==='text-animation')next.animation=event.value;else recognized=false;}\n else if(identity.kind==='caption'){if(kind==='caption-value')next.text=event.value;else if(kind==='caption-track')next.trackId=event.value;else if(kind==='caption-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='caption-end')next.end=Math.max((Number(item.start)||0)+.001,Number(event.value)||(Number(item.start)||0)+.001);else if(kind==='caption-animation')next.animation=event.value;else recognized=false;}\n else if(identity.kind==='effect'){if(kind==='effect-type')next.type=event.value;else if(kind==='effect-track')next.trackId=event.value;else if(kind==='effect-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='effect-duration')next.duration=Math.max(.001,Number(event.value)||.001);else if(kind==='effect-intensity')next.intensity=Number(event.value)||0;else recognized=false;}\n else recognized=false;if(recognized){const updated=rows.slice();updated.splice(index,1,next);replaceRows(identity.kind,updated);identities.set(handle,{kind:identity.kind,item:next});}\n});\nbuild.addEventListener('click',()=>{if(blocked())return;const assembled=assemble();const next=source.clips?.length||source.audioItems?.length?assembled:{...assembled,clips:assembled.clips.map(item=>({...item,id:uniqueId('clip')})),audioItems:assembled.audioItems.map(item=>({...item,id:uniqueId('audio')}))};commitEdit(next);draw();});\ndocument.getElementById('addText').addEventListener('click',()=>{if(blocked())return;commitEdit({...draft,textOverlays:[...draft.textOverlays,{id:uniqueId('text'),trackId:'text',text:'New text',start:0,duration:2,animation:'none'}]});draw();});\ndocument.getElementById('addCaption').addEventListener('click',()=>{if(blocked())return;commitEdit({...draft,captions:[...draft.captions,{id:uniqueId('caption'),trackId:'captions',text:'New caption',start:0,end:2,font:'Hanken Grotesk',animation:'none'}]});draw();});\ndocument.getElementById('addEffect').addEventListener('click',()=>{if(blocked())return;commitEdit({...draft,effects:[...draft.effects,{id:uniqueId('effect'),trackId:'video',type:'fade',start:0,duration:1,intensity:1}]});draw();});\nconst undoEdit=redo=>{if(blocked())return;captureHistory();const entry=redo?redoStack.at(-1):undoStack.at(-1);if(!entry)return;try{const next=StillMade.applyDocument(draft,redo?entry.forward:entry.inverse);if(redo){redoStack=redoStack.slice(0,-1);undoStack=[...undoStack,entry];}else{undoStack=undoStack.slice(0,-1);redoStack=[...redoStack,entry];}commitEdit(next,false);draw();status.textContent=redo?'Your checked change was restored.':'Your checked change was undone. Teammate edits are retained.';}catch(error){status.textContent='Cannot '+(redo?'redo':'undo')+' because the same content changed. The shared timeline is retained.';}};\ndocument.getElementById('undo').addEventListener('click',()=>undoEdit(false));\ndocument.getElementById('redo').addEventListener('click',()=>undoEdit(true));\ndocument.getElementById('snapshot').addEventListener('click',()=>{if(blocked())return;const version={id:uniqueId('timeline-version'),label:'Timeline version '+String((draft.timelineVersions||[]).length+1),createdAt:new Date().toISOString(),clips:clone(draft.clips),audioItems:clone(draft.audioItems),captions:clone(draft.captions),textOverlays:clone(draft.textOverlays),effects:clone(draft.effects)};commitEdit({...draft,timelineVersions:[...(draft.timelineVersions||[]),version].slice(-50)});draw();});\ndocument.getElementById('reset').addEventListener('click',()=>{if(blocked())return;commitEdit(normalize(clone(source)));draw();status.textContent='Reset to the current project timeline is being shared.';});\nconst validateEditor=value=>{if(!value||Array.isArray(value)||value.schemaVersion!==1||typeof value.activeTimelineId!=='string'||!value.activeTimelineId)throw Error('Editor JSON must be a version 1 document with an active timeline ID.');[value.tracks,value.clips,value.audioItems,value.captions,value.textOverlays,value.stickers,value.effects,value.markers,value.fxEvents,value.liveOverlays,value.mediaItems,value.timelineVersions].forEach(rows=>{if(rows===undefined)return;if(!Array.isArray(rows)||rows.length>10000||rows.some(item=>!item||Array.isArray(item)||typeof item.id!=='string'||!item.id||item.id.length>200)||new Set(rows.map(item=>item.id)).size!==rows.length)throw Error('Each Editor collection needs at most 10,000 items with distinct, nonempty IDs of at most 200 characters.');});return normalize(value);};\ndocument.getElementById('applyRaw').addEventListener('click',async()=>{if(blocked()||scratch.text===null)return;const requested=JSON.stringify(scratch);busy=true;draw();try{await scratchShared.flush();if(JSON.stringify(scratch)!==requested)throw Error('The shared JSON draft changed. Review the latest text before applying it.');if(!allowed())throw Error('Editing access changed. JSON text is retained.');const pending=scratch,value=validateEditor(JSON.parse(pending.text)),edits=StillMade.diffDocument(pending.base||draft,value);commitEdit(StillMade.applyDocument(draft,edits));await shared.flush();if(!allowed())throw Error('Editing access changed. JSON text is retained.');if(JSON.stringify(scratch)===requested){scratch={text:null,base:null};rawStale=false;scratchShared.changed();await scratchShared.flush();}status.textContent='Complete Editor data applied to the shared timeline.';}catch(error){status.textContent=error.message;}finally{busy=false;draw();}});\nconst editOptions=next=>{if(blocked())return;options=next;optionsShared.changed();revision+=1;};\ndocument.getElementById('renderFps').addEventListener('change',()=>editOptions({...options,renderFps:Number(document.getElementById('renderFps').value)}));\ndocument.getElementById('renderResolution').addEventListener('change',()=>editOptions({...options,renderResolution:Number(document.getElementById('renderResolution').value)}));\ndocument.getElementById('renderQuality').addEventListener('change',()=>editOptions({...options,renderQuality:document.getElementById('renderQuality').value}));\nconst runAction=async(render)=>{if(blocked()||scratch.text!==null)return;busy=true;draw();status.textContent=render?'Preparing the exact final render…':'Checking the complete Editor timeline…';try{await shared.flush();await scratchShared.flush();await optionsShared.flush();if(!allowed()||scratch.text!==null)throw Error('Editing access or the shared draft changed. The action was not run.');const started=revision;await StillMade.run({editor:clone(source),updatedEditor:clone(draft),commit:!render,...render?{action:'render',...options}:{}});status.textContent=started!==revision?'A result is ready below; newer shared edits were retained.':render?'Final render is ready below. Choose Render final file to start the device renderer.':'Editor changes are ready below. Review the before and after, then choose Apply.';}catch(error){status.textContent=error.message||'The Editor action could not be prepared.';}finally{busy=false;draw();}};\nsave.addEventListener('click',()=>runAction(false));\ndocument.getElementById('renderFinal').addEventListener('click',()=>runAction(true));\nconst recover=async(action)=>{if(busy||!shared||![access,scratchAccess,optionsAccess].every(value=>value.canEdit&&!value.pending))return;busy=true;draw();try{await action();sourceResetArmed=false;undoStack=[];redoStack=[];historyBefore=null;historyAfter=null;status.textContent='Shared Editor draft recovered.';}catch(error){status.textContent=error.message;}finally{busy=false;draw();}};\ndocument.getElementById('retryShared').addEventListener('click',()=>recover(async()=>{await shared.retry();await scratchShared.retry();await optionsShared.retry();}));\ndocument.getElementById('discardShared').addEventListener('click',()=>recover(async()=>{await shared.discard();await scratchShared.discard();await optionsShared.discard();}));\ndocument.getElementById('resetSharedSource').addEventListener('click',()=>{sourceResetArmed=true;drawRecovery();});\ndocument.getElementById('confirmSourceReset').addEventListener('click',()=>{if(!sourceResetArmed||!access.sourceConflict)return;sourceResetArmed=false;recover(()=>shared.resetSharedSource({discardSharedEdits:true}));});\nStillMade.onShared(value=>{sourceResetArmed=false;drawRecovery();const outputs=value.outputs||{};document.getElementById('sharedResult').textContent=outputs.mediaAction?'A final-render plan is available in the shared result below.':outputs.editor?'The latest reviewed Editor result is available below.':'';});\nStillMade.onInput(values=>{sourceResetArmed=false;source=clone(values.editor||empty);assets=Array.isArray(values.assets)?clone(values.assets):[];previewSerial+=1;if(previewUrl){StillMade.releaseMedia(previewUrl);previewUrl='';}imagePreview.hidden=true;videoPreview.hidden=true;audioPreview.hidden=true;const next=normalize(values.updatedEditor&&(values.updatedEditor.clips?.length||values.updatedEditor.audioItems?.length||values.updatedEditor.timelineVersions?.length)?clone(values.updatedEditor):source.clips?.length||source.audioItems?.length?clone(source):assemble());if(!shared){draft=next;shared=StillMade.connectDocument({key:'editorDocument',source:next,read:()=>draft,replace:value=>{sourceResetArmed=false;captureHistory();draft=value;revision+=1;if(scratch.text!==null)rawStale=true;draw();}});scratchShared=StillMade.connectDocument({key:'editorScratch',source:{text:null,base:null},read:()=>scratch,replace:value=>{scratch=value;rawStale=scratch.text!==null;if(scratch.text!==null&&rawIsOpen()&&raw.value!==scratch.text)raw.value=scratch.text;else schedulePreview();drawRecovery();}});optionsShared=StillMade.connectDocument({key:'editorOptions',source:{renderFps:30,renderResolution:1080,renderQuality:'high'},read:()=>options,replace:value=>{options=value;revision+=1;drawOptions();}});shared.onStatus(value=>{const redraw=access.canEdit!==value.canEdit||access.error!==value.error;access=value;if(redraw)draw();else drawRecovery();});scratchShared.onStatus(value=>{const redraw=scratchAccess.canEdit!==value.canEdit||scratchAccess.error!==value.error;scratchAccess=value;if(redraw)draw();else drawRecovery();});optionsShared.onStatus(value=>{const redraw=optionsAccess.canEdit!==value.canEdit||optionsAccess.error!==value.error;optionsAccess=value;if(redraw)draw();else drawRecovery();});playhead.value='0';}else shared.replaceSource(next);revision+=1;draw();status.textContent=access.error||'Timeline changes, JSON drafts and export settings are shared live. Playback and previews are personal.';});\n"},"tests":[{"name":"Retain the complete Editor and all internal tools","input":{"editor":{"schemaVersion":1,"activeTimelineId":"timeline-1","aspect":"16:9","tracks":[{"id":"video","type":"video"},{"id":"audio","type":"audio"}],"clips":[{"id":"clip-1","trackId":"video","start":0,"duration":4,"url":"https://media.example/clip.mp4","motion":{"type":"push-in"},"color":{"brightness":5},"transition":{"type":"Fade","duration":0.5}}],"audioItems":[{"id":"music-1","trackId":"audio","start":0,"duration":4,"url":"https://media.example/music.mp3","volume":70}],"captions":[{"id":"caption-1","trackId":"captions","text":"Hello","start":0,"end":1}],"textOverlays":[{"id":"title-1","text":"Opening","start":0,"duration":2}],"effects":[{"id":"effect-1","type":"grain","start":0,"duration":4}],"fullscreenFrames":[{"id":"mg-frame-1","title":"Motion graphic"}],"figureSweeps":[{"id":"mg-figure-1","value":42}],"audioScore":{"wholeMusic":{"versions":[{"url":"https://media.example/score.mp3"}],"idx":0}},"timelineVersions":[{"id":"timeline-1","name":"Main","clips":[]}],"exportSettings":{"resolution":"1080p"},"custom":{"keep":true}},"updatedEditor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[],"audioItems":[],"captions":[],"textOverlays":[],"effects":[]},"commit":false},"expected":{"editor":{"schemaVersion":1,"activeTimelineId":"timeline-1","aspect":"16:9","tracks":[{"id":"video","type":"video"},{"id":"audio","type":"audio"}],"clips":[{"id":"clip-1","trackId":"video","start":0,"duration":4,"url":"https://media.example/clip.mp4","motion":{"type":"push-in"},"color":{"brightness":5},"transition":{"type":"Fade","duration":0.5}}],"audioItems":[{"id":"music-1","trackId":"audio","start":0,"duration":4,"url":"https://media.example/music.mp3","volume":70}],"captions":[{"id":"caption-1","trackId":"captions","text":"Hello","start":0,"end":1}],"textOverlays":[{"id":"title-1","text":"Opening","start":0,"duration":2}],"effects":[{"id":"effect-1","type":"grain","start":0,"duration":4}],"fullscreenFrames":[{"id":"mg-frame-1","title":"Motion graphic"}],"figureSweeps":[{"id":"mg-figure-1","value":42}],"audioScore":{"wholeMusic":{"versions":[{"url":"https://media.example/score.mp3"}],"idx":0}},"timelineVersions":[{"id":"timeline-1","name":"Main","clips":[]}],"exportSettings":{"resolution":"1080p"},"custom":{"keep":true}},"edit":{"schemaVersion":1,"title":"Update Editor timeline timeline-1","field":"editor","before":{"schemaVersion":1,"activeTimelineId":"timeline-1","aspect":"16:9","tracks":[{"id":"video","type":"video"},{"id":"audio","type":"audio"}],"clips":[{"id":"clip-1","trackId":"video","start":0,"duration":4,"url":"https://media.example/clip.mp4","motion":{"type":"push-in"},"color":{"brightness":5},"transition":{"type":"Fade","duration":0.5}}],"audioItems":[{"id":"music-1","trackId":"audio","start":0,"duration":4,"url":"https://media.example/music.mp3","volume":70}],"captions":[{"id":"caption-1","trackId":"captions","text":"Hello","start":0,"end":1}],"textOverlays":[{"id":"title-1","text":"Opening","start":0,"duration":2}],"effects":[{"id":"effect-1","type":"grain","start":0,"duration":4}],"fullscreenFrames":[{"id":"mg-frame-1","title":"Motion graphic"}],"figureSweeps":[{"id":"mg-figure-1","value":42}],"audioScore":{"wholeMusic":{"versions":[{"url":"https://media.example/score.mp3"}],"idx":0}},"timelineVersions":[{"id":"timeline-1","name":"Main","clips":[]}],"exportSettings":{"resolution":"1080p"},"custom":{"keep":true}},"after":{"schemaVersion":1,"activeTimelineId":"timeline-1","aspect":"16:9","tracks":[{"id":"video","type":"video"},{"id":"audio","type":"audio"}],"clips":[{"id":"clip-1","trackId":"video","start":0,"duration":4,"url":"https://media.example/clip.mp4","motion":{"type":"push-in"},"color":{"brightness":5},"transition":{"type":"Fade","duration":0.5}}],"audioItems":[{"id":"music-1","trackId":"audio","start":0,"duration":4,"url":"https://media.example/music.mp3","volume":70}],"captions":[{"id":"caption-1","trackId":"captions","text":"Hello","start":0,"end":1}],"textOverlays":[{"id":"title-1","text":"Opening","start":0,"duration":2}],"effects":[{"id":"effect-1","type":"grain","start":0,"duration":4}],"fullscreenFrames":[{"id":"mg-frame-1","title":"Motion graphic"}],"figureSweeps":[{"id":"mg-figure-1","value":42}],"audioScore":{"wholeMusic":{"versions":[{"url":"https://media.example/score.mp3"}],"idx":0}},"timelineVersions":[{"id":"timeline-1","name":"Main","clips":[]}],"exportSettings":{"resolution":"1080p"},"custom":{"keep":true}}}}},{"name":"Prepare one exact complete Editor update","input":{"editor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[{"id":"video","type":"video"}],"clips":[{"id":"clip-1","trackId":"video","start":0,"duration":4,"url":"https://media.example/clip.mp4","volume":100}],"audioItems":[],"captions":[],"textOverlays":[{"id":"title-1","text":"Old","start":0,"duration":2}],"effects":[]},"updatedEditor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[{"id":"video","type":"video"}],"clips":[{"id":"clip-1","trackId":"video","start":1,"duration":3,"url":"https://media.example/clip.mp4","volume":80}],"audioItems":[],"captions":[],"textOverlays":[{"id":"title-1","text":"New","start":1,"duration":2}],"effects":[]},"commit":true},"expected":{"editor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[{"id":"video","type":"video"}],"clips":[{"id":"clip-1","trackId":"video","start":1,"duration":3,"url":"https://media.example/clip.mp4","volume":80}],"audioItems":[],"captions":[],"textOverlays":[{"id":"title-1","text":"New","start":1,"duration":2}],"effects":[]},"edit":{"schemaVersion":1,"title":"Update Editor timeline timeline-1","field":"editor","before":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[{"id":"video","type":"video"}],"clips":[{"id":"clip-1","trackId":"video","start":0,"duration":4,"url":"https://media.example/clip.mp4","volume":100}],"audioItems":[],"captions":[],"textOverlays":[{"id":"title-1","text":"Old","start":0,"duration":2}],"effects":[]},"after":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[{"id":"video","type":"video"}],"clips":[{"id":"clip-1","trackId":"video","start":1,"duration":3,"url":"https://media.example/clip.mp4","volume":80}],"audioItems":[],"captions":[],"textOverlays":[{"id":"title-1","text":"New","start":1,"duration":2}],"effects":[]}}}},{"name":"Build initial timeline from exact project media versions","input":{"editor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[],"audioItems":[],"captions":[],"textOverlays":[],"effects":[]},"assets":[{"kind":"video","assetId":"video-1","versionId":"v1","url":"https://media.example/video.mp4","duration":5},{"kind":"image","assetId":"image-1","versionId":"v2","url":"https://media.example/image.png"},{"kind":"audio","assetId":"music-1","versionId":"v1","url":"https://media.example/music.mp3","duration":9}],"updatedEditor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[],"audioItems":[],"captions":[],"textOverlays":[],"effects":[]},"commit":false,"action":"none"},"expected":{"editor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[{"id":"video","kind":"video","label":"Video"},{"id":"audio","kind":"audio","label":"Audio"}],"clips":[{"id":"clip-1-video-1","trackId":"video","start":0,"duration":5,"trimStart":0,"speed":1,"volume":1,"asset":{"kind":"video","assetId":"video-1","versionId":"v1","url":"https://media.example/video.mp4","duration":5},"url":"https://media.example/video.mp4"},{"id":"clip-2-image-1","trackId":"video","start":5,"duration":4,"trimStart":0,"speed":1,"volume":1,"asset":{"kind":"image","assetId":"image-1","versionId":"v2","url":"https://media.example/image.png"},"url":"https://media.example/image.png"}],"audioItems":[{"id":"audio-1-music-1","trackId":"audio","start":0,"duration":9,"trimStart":0,"volume":1,"asset":{"kind":"audio","assetId":"music-1","versionId":"v1","url":"https://media.example/music.mp3","duration":9},"url":"https://media.example/music.mp3"}],"captions":[],"textOverlays":[],"effects":[],"targetDuration":9},"edit":{"schemaVersion":1,"title":"Update Editor timeline timeline-1","field":"editor","before":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[],"audioItems":[],"captions":[],"textOverlays":[],"effects":[]},"after":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[{"id":"video","kind":"video","label":"Video"},{"id":"audio","kind":"audio","label":"Audio"}],"clips":[{"id":"clip-1-video-1","trackId":"video","start":0,"duration":5,"trimStart":0,"speed":1,"volume":1,"asset":{"kind":"video","assetId":"video-1","versionId":"v1","url":"https://media.example/video.mp4","duration":5},"url":"https://media.example/video.mp4"},{"id":"clip-2-image-1","trackId":"video","start":5,"duration":4,"trimStart":0,"speed":1,"volume":1,"asset":{"kind":"image","assetId":"image-1","versionId":"v2","url":"https://media.example/image.png"},"url":"https://media.example/image.png"}],"audioItems":[{"id":"audio-1-music-1","trackId":"audio","start":0,"duration":9,"trimStart":0,"volume":1,"asset":{"kind":"audio","assetId":"music-1","versionId":"v1","url":"https://media.example/music.mp3","duration":9},"url":"https://media.example/music.mp3"}],"captions":[],"textOverlays":[],"effects":[],"targetDuration":9}}}},{"name":"Retain valid legacy native IDs and nullable transforms","input":{"editor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[],"audioItems":[],"captions":[],"textOverlays":[],"effects":[]},"updatedEditor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[{"id":"界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界\u0001","start":0,"duration":4,"transform":null}],"audioItems":[],"captions":[],"textOverlays":[],"effects":[],"custom":{"keep":true}},"commit":true},"expected":{"editor":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[{"id":"界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界\u0001","start":0,"duration":4,"transform":null}],"audioItems":[],"captions":[],"textOverlays":[],"effects":[],"custom":{"keep":true}},"edit":{"schemaVersion":1,"title":"Update Editor timeline timeline-1","field":"editor","before":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[],"audioItems":[],"captions":[],"textOverlays":[],"effects":[]},"after":{"schemaVersion":1,"activeTimelineId":"timeline-1","tracks":[],"clips":[{"id":"界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界\u0001","start":0,"duration":4,"transform":null}],"audioItems":[],"captions":[],"textOverlays":[],"effects":[],"custom":{"keep":true}}}}}],"portable":{"format":"stillmade-block/1","dependencies":[],"sources":[{"kind":"original","license":"MIT","paths":["LICENSE","src/run.js","src/view.json"],"evidence":["upstream/0/LICENSE","upstream/0/src/run.js","upstream/0/src/view.json"],"changes":"Original implementation declared by the packager; no reused repository or dependency code."}],"files":{"upstream/0/LICENSE":"MIT License\n\nCopyright (c) <year> <copyright holders>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and \nassociated documentation files (the \"Software\"), to deal in the Software without restriction, including \nwithout limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \ncopies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the \nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial \nportions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT \nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO \nEVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER \nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE \nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n","upstream/0/src/run.js":"const copy = value => JSON.parse(JSON.stringify(value));\nconst source = copy(input.editor || {schemaVersion:1,activeTimelineId:'timeline-1',tracks:[],clips:[],audioItems:[],captions:[],textOverlays:[],effects:[]});\nconst assets=Array.isArray(input.assets)?input.assets.filter(asset=>asset&&['image','video','audio'].includes(asset.kind)&&asset.assetId&&asset.versionId&&asset.url).slice(0,500):[];\nconst assembled=copy(source);if(!assembled.clips?.length&&!assembled.audioItems?.length&&assets.length){assembled.tracks=[{id:'video',kind:'video',label:'Video'},{id:'audio',kind:'audio',label:'Audio'}];let cursor=0;assembled.clips=assets.filter(asset=>asset.kind!=='audio').map((asset,index)=>{const duration=Math.max(.001,Number(asset.duration)||Number(asset.durationSec)||4),clip={id:'clip-'+String(index+1)+'-'+String(asset.assetId),trackId:'video',start:cursor,duration,trimStart:0,speed:1,volume:1,asset:copy(asset),url:asset.url};cursor+=duration;return clip});assembled.audioItems=assets.filter(asset=>asset.kind==='audio').map((asset,index)=>({id:'audio-'+String(index+1)+'-'+String(asset.assetId),trackId:'audio',start:0,duration:Math.max(.001,Number(asset.duration)||Number(asset.durationSec)||cursor||1),trimStart:0,volume:1,asset:copy(asset),url:asset.url}));assembled.targetDuration=Math.max(cursor,...assembled.audioItems.map(item=>item.duration));}\nconst candidate = input.commit || input.action === 'render' ? copy(input.updatedEditor) : assembled;\nif (!candidate || Array.isArray(candidate) || candidate.schemaVersion !== 1 || typeof candidate.activeTimelineId !== 'string' || !candidate.activeTimelineId) throw new Error('Keep the complete version 1 Editor document and active timeline identity.');\nconst names=['tracks','clips','audioItems','captions','textOverlays','stickers','effects','markers','fxEvents','liveOverlays','mediaItems','timelineVersions'];\nif (!names.every(name => candidate[name] === undefined || Array.isArray(candidate[name]) && candidate[name].length <= 10000 && candidate[name].every(item => item && typeof item === 'object' && !Array.isArray(item) && typeof item.id === 'string' && item.id.length > 0 && item.id.length <= 200) && new Set(candidate[name].map(item => item.id)).size === candidate[name].length)) throw new Error('Editor collections need valid distinct retained item IDs.');\nconst itemEnd=item=>Math.max(0,Number(item.start)||0)+Math.max(.001,Number(item.duration)||Number(item.durationMs)/1000||.001);\nconst outputs={editor:candidate,edit:{schemaVersion:1,title:`Update Editor timeline ${candidate.activeTimelineId}`,field:'editor',before:source,after:candidate}};\nif(input.action==='render'){const clips=Array.isArray(candidate.clips)?candidate.clips:[],audio=Array.isArray(candidate.audioItems)?candidate.audioItems:[],overlays=[...(candidate.captions||[]),...(candidate.textOverlays||[]),...(candidate.effects||[])],targetDuration=Math.max(.001,Number(candidate.targetDuration)||0,...clips.map(itemEnd),...audio.map(itemEnd),...overlays.map(itemEnd));outputs.mediaAction={schemaVersion:1,kind:'stillmade.media-action',operation:'final.render',request:{schemaVersion:1,kind:'video',timeline:{...candidate,clips,audio,overlays,targetDuration},settings:{fps:input.renderFps,resolution:input.renderResolution,quality:input.renderQuality},source:{id:'sm.editor',version:'2.2.9'}},resultPort:null};}\nreturn outputs;\n","upstream/0/src/view.json":"{\n  \"html\": \"<main class=\\\"editor-workspace\\\">\\n  <header><div><small>Production workspace</small><h1>Editor</h1><p id=\\\"summary\\\">Loading the complete timeline…</p></div><div class=\\\"actions\\\"><button id=\\\"build\\\" type=\\\"button\\\" class=\\\"secondary\\\">Build from project media</button><button id=\\\"undo\\\" type=\\\"button\\\" class=\\\"secondary\\\">Undo</button><button id=\\\"redo\\\" type=\\\"button\\\" class=\\\"secondary\\\">Redo</button><button id=\\\"snapshot\\\" type=\\\"button\\\" class=\\\"secondary\\\">Save version</button><button id=\\\"reset\\\" type=\\\"button\\\" class=\\\"secondary\\\">Reset changes</button><button id=\\\"addText\\\" type=\\\"button\\\" class=\\\"secondary\\\">Add text</button><button id=\\\"addCaption\\\" type=\\\"button\\\" class=\\\"secondary\\\">Add caption</button><button id=\\\"save\\\" type=\\\"button\\\" data-stillmade-action=\\\"run\\\">Review changes</button></div></header>\\n  <output id=\\\"status\\\" role=\\\"status\\\" aria-live=\\\"polite\\\"></output>\\n  <p id=\\\"sharedResult\\\" class=\\\"hint\\\" aria-live=\\\"polite\\\"></p>\\n  <section id=\\\"recovery\\\" hidden><h2>Keep your work safe</h2><p id=\\\"recoveryMessage\\\"></p><div class=\\\"row\\\"><button id=\\\"retryShared\\\" type=\\\"button\\\" class=\\\"secondary\\\">Retry checked changes</button><button id=\\\"discardShared\\\" type=\\\"button\\\" class=\\\"secondary\\\">Discard my unshared changes</button><button id=\\\"resetSharedSource\\\" type=\\\"button\\\" class=\\\"secondary\\\" hidden>Review updated project timeline</button></div><p>The project source changed. Starting from it replaces the shared timeline draft for everyone. Unfinished JSON is retained for separate review.</p><button id=\\\"confirmSourceReset\\\" type=\\\"button\\\" hidden>Replace everyone's shared draft with the updated project timeline</button></section>\\n  <section><h2>Timeline</h2><div class=\\\"grid\\\"><label>Active timeline<input id=\\\"timelineId\\\" type=\\\"text\\\" disabled></label><label>Aspect ratio<input id=\\\"aspect\\\" type=\\\"text\\\"></label><label>Playhead (seconds)<input id=\\\"playhead\\\" type=\\\"range\\\" min=\\\"0\\\" max=\\\"1\\\" step=\\\"0.05\\\" value=\\\"0\\\"></label></div><p id=\\\"timecode\\\" class=\\\"hint\\\"></p><div id=\\\"composition\\\" class=\\\"cards\\\"></div></section>\\n  <section><h2>Project media</h2><p class=\\\"hint\\\">Preview an exact saved version, then add it to this timeline without leaving the Block.</p><img id=\\\"imagePreview\\\" alt=\\\"Selected project media preview\\\" hidden><video id=\\\"videoPreview\\\" controls hidden></video><audio id=\\\"audioPreview\\\" controls hidden></audio><div id=\\\"assets\\\" class=\\\"cards media-grid\\\"></div></section>\\n  <section><h2>Video</h2><div id=\\\"clips\\\" class=\\\"cards\\\"></div></section>\\n  <section><h2>Audio and scoring</h2><div id=\\\"audio\\\" class=\\\"cards\\\"></div></section>\\n  <section><h2>Saved timeline versions</h2><div id=\\\"versions\\\" class=\\\"cards\\\"></div></section>\\n  <section><h2>Text and motion graphics</h2><div id=\\\"text\\\" class=\\\"cards\\\"></div><p id=\\\"graphics\\\" class=\\\"hint\\\"></p></section>\\n  <section><h2>Captions</h2><div id=\\\"captions\\\" class=\\\"cards\\\"></div></section>\\n  <section><div class=\\\"card-head\\\"><h2>Effects</h2><button id=\\\"addEffect\\\" type=\\\"button\\\" class=\\\"secondary\\\">Add effect</button></div><div id=\\\"effects\\\" class=\\\"cards\\\"></div></section>\\n  <details id=\\\"rawDetails\\\"><summary>Complete Editor data</summary><p>All timeline lanes, motion graphics, grade settings, transitions, scoring, versions, and export settings are retained. Use this editor for fields not shown on the lane cards.</p><p id=\\\"rawNotice\\\" class=\\\"hint\\\"></p><textarea id=\\\"raw\\\" class=\\\"raw\\\" spellcheck=\\\"false\\\" aria-label=\\\"Complete Editor data\\\"></textarea><div class=\\\"row\\\"><button id=\\\"applyRaw\\\" type=\\\"button\\\" class=\\\"secondary\\\">Apply JSON to workspace</button><button id=\\\"discardRaw\\\" type=\\\"button\\\" class=\\\"secondary\\\">Discard shared JSON draft</button></div></details>\\n<section><h2>Final export</h2><p>Render this exact timeline through StillMade’s approved device renderer.</p><div class=\\\"grid\\\"><label>Frame rate<select id=\\\"renderFps\\\"><option value=\\\"24\\\">24 fps</option><option value=\\\"30\\\" selected>30 fps</option><option value=\\\"60\\\">60 fps</option></select></label><label>Resolution<select id=\\\"renderResolution\\\"><option value=\\\"720\\\">720p</option><option value=\\\"1080\\\" selected>1080p</option><option value=\\\"2160\\\">2160p</option></select></label><label>Quality<select id=\\\"renderQuality\\\"><option value=\\\"standard\\\">Standard</option><option value=\\\"high\\\" selected>High</option></select></label></div><button id=\\\"renderFinal\\\" type=\\\"button\\\">Render final video</button></section></main>\\n\",\n  \"css\": \".editor-workspace{max-width:1160px;margin:0 auto;padding:8px;color:var(--fg)}header,.actions,.card-head,.row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}header{justify-content:space-between;margin-bottom:14px}header h1{margin:2px 0}header p,header small,details p,output,.hint{color:var(--fg-muted)}section,details{margin:12px 0;padding:16px;border:1px solid var(--border-tok);border-radius:var(--r-3);background:var(--bg-elev-1)}section h2{margin:0 0 10px}.cards{display:grid;gap:10px}.card{padding:12px;border:1px solid var(--border-tok);border-radius:var(--r-2);background:var(--bg)}.card-head{justify-content:space-between}.card h3{margin:0;font-size:16px}.grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}label{display:grid;gap:5px;margin:7px 0;font-size:13px;font-weight:600}input,textarea{width:100%;background:var(--bg)}textarea{min-height:70px;resize:vertical}.wide{grid-column:1/-1}.secondary{background:transparent;color:var(--fg)}.danger{background:transparent;color:var(--signal)}.raw{min-height:440px;font-family:var(--font-mono);font-size:12px}output{display:block;min-height:24px;margin:8px 2px}\\n@media(max-width:900px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:560px){.editor-workspace{padding:0}.grid{grid-template-columns:1fr}.actions{width:100%}.actions button{flex:1}section,details{padding:12px}}\\n.media-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.media-card p{margin:4px 0;color:var(--fg-muted)}video,audio{display:block;width:100%;margin:10px 0}video[hidden],audio[hidden]{display:none}select{width:100%;background:var(--bg)}\\n.card,.grid>*{min-width:0}.card h3,.card strong,.card p{overflow-wrap:anywhere}img{max-width:100%;height:auto}@media(max-width:560px){.media-grid{grid-template-columns:1fr}}\\n\",\n  \"javascript\": \"const status=document.getElementById('status'),summary=document.getElementById('summary'),raw=document.getElementById('raw'),save=document.getElementById('save'),aspect=document.getElementById('aspect'),timelineId=document.getElementById('timelineId'),graphics=document.getElementById('graphics'),build=document.getElementById('build'),imagePreview=document.getElementById('imagePreview'),videoPreview=document.getElementById('videoPreview'),audioPreview=document.getElementById('audioPreview'),playhead=document.getElementById('playhead'),timecode=document.getElementById('timecode');\\nconst empty={schemaVersion:1,activeTimelineId:'timeline-1',tracks:[],clips:[],audioItems:[],captions:[],textOverlays:[],effects:[]};\\nlet source=empty,draft=empty,assets=[],previewUrl='',previewSerial=0,busy=false,revision=0;\\nlet shared=null,scratchShared=null,optionsShared=null,scratch={text:null,base:null},options={renderFps:30,renderResolution:1080,renderQuality:'high'};\\nlet access={canEdit:false,error:null},scratchAccess={canEdit:false,error:null},optionsAccess={canEdit:false,error:null},sourceResetArmed=false,rawBaseline=null,rawStale=false;\\nlet undoStack=[],redoStack=[],historyBefore=null,historyAfter=null;\\nconst tokens=new Map(),identities=new Map(),pages=new Map();\\nconst clone=value=>JSON.parse(JSON.stringify(value));\\nconst text=value=>value===undefined||value===null?'':String(value);\\nconst uniqueId=prefix=>prefix+'-'+Date.now().toString(36)+'-'+Math.random().toString(36).slice(2,14);\\nconst blocked=()=>busy||!shared||!scratchShared||!optionsShared||!access.canEdit||!scratchAccess.canEdit||!optionsAccess.canEdit||!!access.error||!!scratchAccess.error||!!optionsAccess.error;\\nconst allowed=()=>access.canEdit&&scratchAccess.canEdit&&optionsAccess.canEdit&&!access.error&&!scratchAccess.error&&!optionsAccess.error;\\nconst token=(kind,item)=>{const key=JSON.stringify(kind==='asset'?[kind,item.kind,item.assetId,item.versionId]:[kind,item.id]);if(!tokens.has(key)){const value='i'+String(tokens.size+1);tokens.set(key,value);}const handle=tokens.get(key);identities.set(handle,{kind,item});return handle;};\\nconst normalize=value=>({...value,tracks:Array.isArray(value.tracks)?value.tracks:[],clips:Array.isArray(value.clips)?value.clips:[],audioItems:Array.isArray(value.audioItems)?value.audioItems:[],captions:Array.isArray(value.captions)?value.captions:[],textOverlays:Array.isArray(value.textOverlays)?value.textOverlays:[],effects:Array.isArray(value.effects)?value.effects:[]});\\nconst assemble=()=>{const next=clone(source),media=assets.filter(asset=>asset&&['image','video','audio'].includes(asset.kind)&&asset.assetId&&asset.versionId&&asset.url).slice(0,500);if(next.clips?.length||next.audioItems?.length||!media.length)return normalize(next);next.tracks=[{id:'video',kind:'video',label:'Video'},{id:'audio',kind:'audio',label:'Audio'}];let cursor=0;next.clips=media.filter(asset=>asset.kind!=='audio').map((asset,index)=>{const duration=Math.max(.001,Number(asset.duration)||Number(asset.durationSec)||4),clip={id:'clip-'+String(index+1)+'-'+text(asset.assetId),trackId:'video',start:cursor,duration,trimStart:0,speed:1,volume:1,asset:clone(asset),url:asset.url};cursor+=duration;return clip;});next.audioItems=media.filter(asset=>asset.kind==='audio').map((asset,index)=>({id:'audio-'+String(index+1)+'-'+text(asset.assetId),trackId:'audio',start:0,duration:Math.max(.001,Number(asset.duration)||Number(asset.durationSec)||cursor||1),trimStart:0,volume:1,asset:clone(asset),url:asset.url}));next.targetDuration=Math.max(cursor,...next.audioItems.map(item=>item.duration));return normalize(next);};\\nconst field=(label,action,value,type='text',wide=false)=>({tag:'label',className:wide?'wide':'',children:[{tag:'span',text:label},{tag:'input',id:'control-'+action.replace(':','-'),type,action,value:Number.isFinite(value)?value:text(value),disabled:blocked(),label}]});\\nconst remove=action=>({tag:'button',action,text:'Remove',className:'danger',disabled:blocked()});\\nconst assetCard=(item,index)=>({tag:'article',id:'card-'+token('asset',item),className:'card media-card',children:[{tag:'strong',text:text(item.name)||text(item.assetId)},{tag:'p',text:text(item.kind)+' · version '+text(item.versionId)},{tag:'div',className:'row',children:[{tag:'button',action:'preview-asset:'+token('asset',item),text:'Preview',className:'secondary',disabled:false},{tag:'button',action:'add-asset:'+token('asset',item),text:item.kind==='audio'?'Add audio':'Add clip',className:'secondary',disabled:blocked()}]}]});\\nconst clipCard=(item,index)=>({tag:'article',id:'card-'+token('clip',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.label)||text(item.name)||text(item.id)},{tag:'div',className:'row',children:[{tag:'button',action:'preview-clip:'+token('clip',item),text:'Preview',className:'secondary',disabled:!(item.asset||item.assetId)},{tag:'button',action:'move-clip-up:'+token('clip',item),text:'Up',className:'secondary',disabled:blocked()||index===0},{tag:'button',action:'move-clip-down:'+token('clip',item),text:'Down',className:'secondary',disabled:blocked()||index===draft.clips.length-1},{tag:'button',action:'split-clip:'+token('clip',item),text:'Split',className:'secondary',disabled:blocked()||Number(item.duration)<=0.002},{tag:'button',action:'duplicate-clip:'+token('clip',item),text:'Duplicate',className:'secondary',disabled:blocked()},remove('remove-clip:'+token('clip',item))]}]},{tag:'div',className:'grid',children:[field('Track','clip-track:'+token('clip',item),item.trackId),field('Start (seconds)','clip-start:'+token('clip',item),item.start,'number'),field('Length (seconds)','clip-duration:'+token('clip',item),item.duration,'number'),field('Trim start','clip-trim:'+token('clip',item),item.trimStart,'number'),field('Speed','clip-speed:'+token('clip',item),item.speed,'number'),field('Volume','clip-volume:'+token('clip',item),item.volume,'number'),field('Transition','clip-transition:'+token('clip',item),item.transition&&item.transition.type),field('Transition length','clip-transition-duration:'+token('clip',item),item.transition&&item.transition.duration,'number'),field('Motion','clip-motion:'+token('clip',item),item.motion&&item.motion.type),field('Motion easing','clip-easing:'+token('clip',item),item.motion&&item.motion.easing),field('Opacity','clip-opacity:'+token('clip',item),item.transform&&item.transform.opacity!==undefined?item.transform.opacity:item.opacity,'number'),{tag:'label',children:[{tag:'span',text:'Reverse playback'},{tag:'input',type:'checkbox',id:'control-'+('clip-reverse:'+token('clip',item)).replace(':','-'),action:'clip-reverse:'+token('clip',item),checked:!!item.reverse,disabled:blocked(),label:'Reverse playback'}]}]}]});\\nconst audioCard=(item,index)=>({tag:'article',id:'card-'+token('audio',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.label)||text(item.name)||text(item.id)},{tag:'div',className:'row',children:[{tag:'button',action:'preview-audio:'+token('audio',item),text:'Preview',className:'secondary',disabled:!(item.asset||item.assetId)},remove('remove-audio:'+token('audio',item))]}]},{tag:'div',className:'grid',children:[field('Track','audio-track:'+token('audio',item),item.trackId),field('Start (seconds)','audio-start:'+token('audio',item),item.start,'number'),field('Length (seconds)','audio-duration:'+token('audio',item),item.duration,'number'),field('Trim start','audio-trim:'+token('audio',item),item.trimStart===undefined?item.sourceOffset:item.trimStart,'number'),field('Volume','audio-volume:'+token('audio',item),item.volume,'number'),field('Fade in','audio-fade-in:'+token('audio',item),item.fadeIn,'number'),field('Fade out','audio-fade-out:'+token('audio',item),item.fadeOut,'number'),field('Ducking','audio-ducking:'+token('audio',item),item.ducking,'number'),field('Playback speed','audio-rate:'+token('audio',item),item.rate,'number'),{tag:'label',children:[{tag:'span',text:'Loop source'},{tag:'input',type:'checkbox',id:'control-'+('audio-loop:'+token('audio',item)).replace(':','-'),action:'audio-loop:'+token('audio',item),checked:!!item.loop,disabled:blocked(),label:'Loop source'}]},{tag:'label',children:[{tag:'span',text:'Muted'},{tag:'input',type:'checkbox',id:'control-'+('audio-muted:'+token('audio',item)).replace(':','-'),action:'audio-muted:'+token('audio',item),checked:!!item.muted,disabled:blocked(),label:'Muted'}]}]}]});\\nconst textCard=(item,index)=>({tag:'article',id:'card-'+token('text',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.id)},remove('remove-text:'+token('text',item))]},{tag:'div',className:'grid',children:[field('Text','text-value:'+token('text',item),item.text,'text',true),field('Track','text-track:'+token('text',item),item.trackId),field('Start (seconds)','text-start:'+token('text',item),item.start,'number'),field('Length (seconds)','text-duration:'+token('text',item),item.duration,'number'),field('Animation','text-animation:'+token('text',item),item.animation)]}]});\\nconst captionCard=(item,index)=>({tag:'article',id:'card-'+token('caption',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.id)},remove('remove-caption:'+token('caption',item))]},{tag:'div',className:'grid',children:[field('Caption','caption-value:'+token('caption',item),item.text,'text',true),field('Track','caption-track:'+token('caption',item),item.trackId),field('Start (seconds)','caption-start:'+token('caption',item),item.start,'number'),field('End (seconds)','caption-end:'+token('caption',item),item.end,'number'),field('Animation','caption-animation:'+token('caption',item),item.animation)]}]});\\nconst effectCard=(item,index)=>({tag:'article',id:'card-'+token('effect',item),className:'card',children:[{tag:'div',className:'card-head',children:[{tag:'h3',text:text(item.type)||text(item.id)},remove('remove-effect:'+token('effect',item))]},{tag:'div',className:'grid',children:[field('Type','effect-type:'+token('effect',item),item.type),field('Track','effect-track:'+token('effect',item),item.trackId),field('Start (seconds)','effect-start:'+token('effect',item),item.start,'number'),field('Length (seconds)','effect-duration:'+token('effect',item),item.duration,'number'),field('Intensity','effect-intensity:'+token('effect',item),item.intensity,'number')]}]});\\nconst largeTimeline=()=>draft.clips.length+draft.audioItems.length+draft.textOverlays.length+draft.captions.length+draft.effects.length>2000;\\nconst itemFinish=item=>(Number(item.start)||0)+Math.max(.001,Number(item.duration)||Number(item.end)-(Number(item.start)||0)||.001);\\nconst composition=()=>{const at=Number(playhead.value)||0;if(largeTimeline()){StillMade.render('composition',[{tag:'strong',text:'Lightweight preview · large timeline'},{tag:'p',text:'Partial preview: the live composition summary is paused to keep editing responsive. Every timeline item is retained for editing and the complete final render.'},{tag:'p',text:'The personal playhead uses the saved timeline duration, or a 24-hour preview window when none is supplied.'}]);timecode.textContent='Playhead '+at.toFixed(2)+' seconds';return;}const activeClips=draft.clips.filter(item=>at>=(Number(item.start)||0)&&at<itemFinish(item)),activeAudio=draft.audioItems.filter(item=>at>=(Number(item.start)||0)&&at<itemFinish(item)),activeOverlays=[...draft.textOverlays,...draft.captions,...draft.effects].filter(item=>at>=(Number(item.start)||0)&&at<itemFinish(item));StillMade.render('composition',[{tag:'strong',text:'At '+at.toFixed(2)+'s'},{tag:'p',text:(activeClips.length?activeClips.slice(0,12).map(item=>text(item.label)||text(item.id)).join(', '):'No video')+' · '+String(activeAudio.length)+' audio · '+String(activeOverlays.length)+' overlays'}]);timecode.textContent='Playhead '+at.toFixed(2)+' seconds';};\\nconst rawIsOpen=()=>document.getElementById('rawDetails').getAttribute('open')!==null;\\nconst renderRawPreview=()=>{if(!rawIsOpen())return;if(scratch.text!==null){if(raw.value!==scratch.text)raw.value=scratch.text;return;}rawBaseline=draft;const value=JSON.stringify(draft,null,2);if(raw.value!==value)raw.value=value;};\\nconst schedulePreview=()=>{if(rawIsOpen())StillMade.scheduleSharedEdit('editorRawPreview',renderRawPreview);};\\nconst drawRecovery=()=>{const states=[access,scratchAccess,optionsAccess],failure=states.find(value=>value.error),sourceMismatch=states.some(value=>value.sourceConflict),waiting=states.some(value=>value.pending),editable=states.every(value=>value.canEdit);document.getElementById('recovery').hidden=!failure;document.getElementById('recoveryMessage').textContent=failure?failure.error:'';document.getElementById('retryShared').disabled=!editable||waiting||sourceMismatch||busy;document.getElementById('discardShared').disabled=!editable||waiting||sourceMismatch||busy;document.getElementById('resetSharedSource').hidden=!sourceMismatch;document.getElementById('resetSharedSource').disabled=!editable||waiting||busy;document.getElementById('confirmSourceReset').hidden=!sourceMismatch||!sourceResetArmed;document.getElementById('confirmSourceReset').disabled=!editable||waiting||busy;document.getElementById('rawNotice').textContent=scratch.text===null?'JSON typing is shared live. Apply checks the original displayed values before updating the timeline.':rawStale?'The timeline changed. Shared JSON text is retained; Apply will check for conflicting edits.':'This unfinished JSON draft is shared live. Apply it when ready, or discard the shared scratch.';save.disabled=blocked()||scratch.text!==null;document.getElementById('renderFinal').disabled=blocked()||scratch.text!==null;document.getElementById('applyRaw').disabled=blocked()||scratch.text===null;document.getElementById('discardRaw').disabled=blocked()||scratch.text===null;document.getElementById('undo').disabled=blocked()||(!undoStack.length&&!historyBefore);document.getElementById('redo').disabled=blocked()||!redoStack.length;};\\nconst versionCard=(item,index)=>({tag:'article',id:'card-'+token('version',item),className:'card',children:[{tag:'strong',text:text(item.label)||text(item.id)},{tag:'p',text:text(item.createdAt)},{tag:'button',action:'restore-version:'+token('version',item),text:'Restore this version',className:'secondary',disabled:blocked()}]});\\nconst renderPage=(target,rows,card,size,emptyMessage)=>{const last=Math.max(0,Math.ceil(rows.length/size)-1),page=Math.min(last,pages.get(target)||0);pages.set(target,page);const content=rows.length?rows.slice(page*size,(page+1)*size).map((item,index)=>card(item,page*size+index)):[{tag:'p',text:emptyMessage}];if(rows.length>size)content.push({tag:'div',className:'row',children:[{tag:'button',action:'page-prev:'+target,text:'Previous',className:'secondary',disabled:page===0},{tag:'span',text:'Page '+String(page+1)+' of '+String(last+1)+' · '+String(rows.length)+' items'},{tag:'button',action:'page-next:'+target,text:'Next',className:'secondary',disabled:page===last}]});StillMade.render(target,content);};\\nconst drawOptions=()=>{document.getElementById('renderFps').value=String(options.renderFps);document.getElementById('renderResolution').value=String(options.renderResolution);document.getElementById('renderQuality').value=options.renderQuality;};\\nconst draw=()=>{renderPage('assets',assets,assetCard,12,'No saved project media is available.');renderPage('clips',draft.clips,clipCard,4,'No video clips.');renderPage('audio',draft.audioItems,audioCard,4,'No audio items.');renderPage('text',draft.textOverlays,textCard,8,'No text overlays.');renderPage('captions',draft.captions,captionCard,8,'No captions.');renderPage('effects',draft.effects,effectCard,8,'No effects.');renderPage('versions',Array.isArray(draft.timelineVersions)?draft.timelineVersions:[],versionCard,5,'No saved versions yet.');timelineId.value=text(draft.activeTimelineId);const duration=largeTimeline()?Math.max(1,Number(draft.targetDuration)||86400,Number(playhead.value)||0):Math.max(1,Number(draft.targetDuration)||0,...draft.clips.map(itemFinish),...draft.audioItems.map(itemFinish));playhead.max=String(duration);StillMade.scheduleSharedEdit('editorComposition',composition);aspect.value=text(draft.aspect);const mg=(Array.isArray(draft.fullscreenFrames)?draft.fullscreenFrames.length:0)+(Array.isArray(draft.figureSweeps)?draft.figureSweeps.length:0)+(Array.isArray(draft.graphs)?draft.graphs.length:0);graphics.textContent=String(mg)+' motion graphic item'+(mg===1?'':'s')+' retained in this Editor Block. Use Complete Editor data for advanced motion-graphics fields.';summary.textContent=String(draft.clips.length)+' video · '+String(draft.audioItems.length)+' audio · '+String(draft.captions.length)+' captions · '+String(draft.textOverlays.length)+' text';['reset','addText','addCaption','addEffect','snapshot','renderFps','renderResolution','renderQuality'].forEach(id=>{document.getElementById(id).disabled=blocked();});build.disabled=blocked()||!assets.length;aspect.disabled=blocked();raw.disabled=blocked();drawOptions();drawRecovery();schedulePreview();};\\nconst captureHistory=()=>{if(!historyBefore)return;const before=historyBefore,after=historyAfter;historyBefore=null;historyAfter=null;try{const forward=StillMade.diffDocument(before,after);if(forward.length){undoStack=[...undoStack,{forward,inverse:StillMade.diffDocument(after,before)}].slice(-50);redoStack=[];}}catch(error){undoStack=[];redoStack=[];status.textContent='This change is too large for local undo. The shared timeline is retained.';}drawRecovery();};\\nconst commitEdit=(next,record=true)=>{if(record){if(!historyBefore)historyBefore=draft;historyAfter=next;StillMade.scheduleSharedEdit('editorHistory',captureHistory);}draft=next;revision+=1;sourceResetArmed=false;if(scratch.text!==null)rawStale=true;shared.changed();schedulePreview();StillMade.scheduleSharedEdit('editorComposition',composition);drawRecovery();status.textContent='Sharing timeline changes. Review changes applies the document to your project.';};\\nconst replaceRows=(kind,rows)=>{if(kind==='clip')commitEdit({...draft,clips:rows});if(kind==='audio')commitEdit({...draft,audioItems:rows});if(kind==='text')commitEdit({...draft,textOverlays:rows});if(kind==='caption')commitEdit({...draft,captions:rows});if(kind==='effect')commitEdit({...draft,effects:rows});};\\nconst rowsFor=kind=>kind==='clip'?draft.clips:kind==='audio'?draft.audioItems:kind==='text'?draft.textOverlays:kind==='caption'?draft.captions:kind==='effect'?draft.effects:kind==='version'?(draft.timelineVersions||[]):[];\\nconst previewItem=(item,kind,trim=0)=>{const serial=++previewSerial;if(previewUrl){StillMade.releaseMedia(previewUrl);previewUrl='';}imagePreview.hidden=true;videoPreview.hidden=true;audioPreview.hidden=true;const value=item.asset||item,mediaKind=value.kind||kind,request=mediaKind==='image'?StillMade.previewImage(value):StillMade.previewMedia({...value,kind:mediaKind});request.then(result=>{if(serial!==previewSerial){if(mediaKind!=='image')StillMade.releaseMedia(result.url);return;}if(mediaKind==='image'){imagePreview.src=result.url;imagePreview.hidden=false;}else if(mediaKind==='audio'){previewUrl=result.url;audioPreview.src=result.url;audioPreview.hidden=false;}else{previewUrl=result.url;videoPreview.src=result.url;videoPreview.currentTime=Math.max(0,Number(trim)||0);videoPreview.hidden=false;}status.textContent='Previewing '+text(item.label||item.name||item.id||item.assetId)+'.';}).catch(error=>{if(serial===previewSerial)status.textContent=error.message;});};\\naspect.addEventListener('input',()=>{if(blocked())return;commitEdit({...draft,aspect:aspect.value});});\\nplayhead.addEventListener('input',()=>{timecode.textContent='Playhead '+(Number(playhead.value)||0).toFixed(2)+' seconds';StillMade.scheduleSharedEdit('editorComposition',composition);});\\ndocument.getElementById('rawDetails').addEventListener('toggle',renderRawPreview);\\nraw.addEventListener('input',()=>{if(blocked())return;scratch={text:raw.value,base:scratch.text===null?(rawBaseline||draft):scratch.base};scratchShared.changed();drawRecovery();});\\ndocument.getElementById('discardRaw').addEventListener('click',()=>{if(blocked())return;scratch={text:null,base:null};rawStale=false;scratchShared.changed();renderRawPreview();drawRecovery();});\\nStillMade.onAction(event=>{const parts=event.action.split(':'),kind=parts[0],handle=parts[1];if(kind==='page-prev'||kind==='page-next'){if(!['assets','clips','audio','text','captions','effects','versions'].includes(handle))return;pages.set(handle,Math.max(0,(pages.get(handle)||0)+(kind==='page-prev'?-1:1)));draw();return;}const identity=identities.get(handle);if(!identity)return;const rows=rowsFor(identity.kind),item=(identity.kind==='asset'?assets:rows).includes(identity.item)?identity.item:null,index=rows.indexOf(item);if(!item)return;\\n if(kind==='preview-clip'&&identity.kind==='clip'){previewItem(item,'video',item.trimStart);return;}if(kind==='preview-audio'&&identity.kind==='audio'){previewItem(item,'audio');return;}if(kind==='preview-asset'&&identity.kind==='asset'){previewItem(item,item.kind);return;}if(blocked())return;\\n if(kind==='restore-version'&&identity.kind==='version'){commitEdit({...draft,clips:clone(item.clips||[]),audioItems:clone(item.audioItems||[]),captions:clone(item.captions||[]),textOverlays:clone(item.textOverlays||[]),effects:clone(item.effects||[])});draw();return;}\\n if(kind==='add-asset'&&identity.kind==='asset'){const media=clone(item),duration=Math.max(.001,Number(media.duration)||Number(media.durationSec)||4);if(media.kind==='audio')commitEdit({...draft,audioItems:[...draft.audioItems,{id:uniqueId('audio'),trackId:'audio',start:0,duration,trimStart:0,volume:1,asset:media,url:media.url}]});else{const start=draft.clips.reduce((end,value)=>Math.max(end,itemFinish(value)),0);commitEdit({...draft,clips:[...draft.clips,{id:uniqueId('clip'),trackId:'video',start,duration,trimStart:0,speed:1,volume:1,asset:media,url:media.url}]});}draw();return;}\\n if((kind==='move-clip-up'||kind==='move-clip-down')&&identity.kind==='clip'){const targetIndex=index+(kind==='move-clip-up'?-1:1),target=rows.at(targetIndex);if(targetIndex<0||!target)return;const reordered=rows.slice();reordered.splice(targetIndex,1,item);reordered.splice(index,1,target);replaceRows('clip',reordered);draw();return;}\\n if(kind==='duplicate-clip'&&identity.kind==='clip'){const next={...clone(item),id:uniqueId('clip-copy'),start:itemFinish(item)};replaceRows('clip',[...rows.slice(0,index+1),next,...rows.slice(index+1)]);draw();return;}\\n if(kind==='split-clip'&&identity.kind==='clip'){const half=Math.max(.001,Number(item.duration)||.001)/2;if(half<.001)return;const second={...clone(item),id:uniqueId('clip-split'),start:(Number(item.start)||0)+half,duration:half,trimStart:(Number(item.trimStart)||0)+half};replaceRows('clip',[...rows.slice(0,index),{...item,duration:half},second,...rows.slice(index+1)]);draw();return;}\\n if(kind==='remove-'+identity.kind&&['clip','audio','text','caption','effect'].includes(identity.kind)){const remaining=rows.slice();remaining.splice(index,1);replaceRows(identity.kind,remaining);draw();return;}\\n const next={...item};let recognized=true;\\n if(identity.kind==='clip'){if(kind==='clip-track')next.trackId=event.value;else if(kind==='clip-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='clip-duration')next.duration=Math.max(.001,Number(event.value)||.001);else if(kind==='clip-trim')next.trimStart=Math.max(0,Number(event.value)||0);else if(kind==='clip-speed')next.speed=Math.max(.01,Number(event.value)||1);else if(kind==='clip-volume')next.volume=Math.max(0,Number(event.value)||0);else if(kind==='clip-transition'||kind==='clip-transition-duration'){const prior=item.transition&&!Array.isArray(item.transition)?item.transition:{type:'Cut',duration:0};next.transition=kind==='clip-transition'?{...prior,type:event.value}:{...prior,duration:Math.max(0,Number(event.value)||0)};}else if(kind==='clip-opacity')next.transform={...(item.transform&&!Array.isArray(item.transform)?item.transform:{}),opacity:Math.max(0,Math.min(1,Number(event.value)||0))};else if(kind==='clip-reverse')next.reverse=event.checked;else if(kind==='clip-motion'||kind==='clip-easing'){const prior=item.motion&&!Array.isArray(item.motion)?item.motion:{type:'none',easing:'ease-in-out'};next.motion=kind==='clip-motion'?{...prior,type:event.value}:{...prior,easing:event.value};}else recognized=false;}\\n else if(identity.kind==='audio'){if(kind==='audio-track')next.trackId=event.value;else if(kind==='audio-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='audio-duration')next.duration=Math.max(.001,Number(event.value)||.001);else if(kind==='audio-trim'){next.trimStart=Math.max(0,Number(event.value)||0);next.sourceOffset=next.trimStart;}else if(kind==='audio-volume')next.volume=Math.max(0,Number(event.value)||0);else if(kind==='audio-fade-in')next.fadeIn=Math.max(0,Number(event.value)||0);else if(kind==='audio-fade-out')next.fadeOut=Math.max(0,Number(event.value)||0);else if(kind==='audio-ducking')next.ducking=Math.max(0,Math.min(1,Number(event.value)||0));else if(kind==='audio-rate')next.rate=Math.max(.05,Math.min(4,Number(event.value)||1));else if(kind==='audio-loop')next.loop=event.checked;else if(kind==='audio-muted')next.muted=event.checked;else recognized=false;}\\n else if(identity.kind==='text'){if(kind==='text-value')next.text=event.value;else if(kind==='text-track')next.trackId=event.value;else if(kind==='text-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='text-duration')next.duration=Math.max(.001,Number(event.value)||.001);else if(kind==='text-animation')next.animation=event.value;else recognized=false;}\\n else if(identity.kind==='caption'){if(kind==='caption-value')next.text=event.value;else if(kind==='caption-track')next.trackId=event.value;else if(kind==='caption-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='caption-end')next.end=Math.max((Number(item.start)||0)+.001,Number(event.value)||(Number(item.start)||0)+.001);else if(kind==='caption-animation')next.animation=event.value;else recognized=false;}\\n else if(identity.kind==='effect'){if(kind==='effect-type')next.type=event.value;else if(kind==='effect-track')next.trackId=event.value;else if(kind==='effect-start')next.start=Math.max(0,Number(event.value)||0);else if(kind==='effect-duration')next.duration=Math.max(.001,Number(event.value)||.001);else if(kind==='effect-intensity')next.intensity=Number(event.value)||0;else recognized=false;}\\n else recognized=false;if(recognized){const updated=rows.slice();updated.splice(index,1,next);replaceRows(identity.kind,updated);identities.set(handle,{kind:identity.kind,item:next});}\\n});\\nbuild.addEventListener('click',()=>{if(blocked())return;const assembled=assemble();const next=source.clips?.length||source.audioItems?.length?assembled:{...assembled,clips:assembled.clips.map(item=>({...item,id:uniqueId('clip')})),audioItems:assembled.audioItems.map(item=>({...item,id:uniqueId('audio')}))};commitEdit(next);draw();});\\ndocument.getElementById('addText').addEventListener('click',()=>{if(blocked())return;commitEdit({...draft,textOverlays:[...draft.textOverlays,{id:uniqueId('text'),trackId:'text',text:'New text',start:0,duration:2,animation:'none'}]});draw();});\\ndocument.getElementById('addCaption').addEventListener('click',()=>{if(blocked())return;commitEdit({...draft,captions:[...draft.captions,{id:uniqueId('caption'),trackId:'captions',text:'New caption',start:0,end:2,font:'Hanken Grotesk',animation:'none'}]});draw();});\\ndocument.getElementById('addEffect').addEventListener('click',()=>{if(blocked())return;commitEdit({...draft,effects:[...draft.effects,{id:uniqueId('effect'),trackId:'video',type:'fade',start:0,duration:1,intensity:1}]});draw();});\\nconst undoEdit=redo=>{if(blocked())return;captureHistory();const entry=redo?redoStack.at(-1):undoStack.at(-1);if(!entry)return;try{const next=StillMade.applyDocument(draft,redo?entry.forward:entry.inverse);if(redo){redoStack=redoStack.slice(0,-1);undoStack=[...undoStack,entry];}else{undoStack=undoStack.slice(0,-1);redoStack=[...redoStack,entry];}commitEdit(next,false);draw();status.textContent=redo?'Your checked change was restored.':'Your checked change was undone. Teammate edits are retained.';}catch(error){status.textContent='Cannot '+(redo?'redo':'undo')+' because the same content changed. The shared timeline is retained.';}};\\ndocument.getElementById('undo').addEventListener('click',()=>undoEdit(false));\\ndocument.getElementById('redo').addEventListener('click',()=>undoEdit(true));\\ndocument.getElementById('snapshot').addEventListener('click',()=>{if(blocked())return;const version={id:uniqueId('timeline-version'),label:'Timeline version '+String((draft.timelineVersions||[]).length+1),createdAt:new Date().toISOString(),clips:clone(draft.clips),audioItems:clone(draft.audioItems),captions:clone(draft.captions),textOverlays:clone(draft.textOverlays),effects:clone(draft.effects)};commitEdit({...draft,timelineVersions:[...(draft.timelineVersions||[]),version].slice(-50)});draw();});\\ndocument.getElementById('reset').addEventListener('click',()=>{if(blocked())return;commitEdit(normalize(clone(source)));draw();status.textContent='Reset to the current project timeline is being shared.';});\\nconst validateEditor=value=>{if(!value||Array.isArray(value)||value.schemaVersion!==1||typeof value.activeTimelineId!=='string'||!value.activeTimelineId)throw Error('Editor JSON must be a version 1 document with an active timeline ID.');[value.tracks,value.clips,value.audioItems,value.captions,value.textOverlays,value.stickers,value.effects,value.markers,value.fxEvents,value.liveOverlays,value.mediaItems,value.timelineVersions].forEach(rows=>{if(rows===undefined)return;if(!Array.isArray(rows)||rows.length>10000||rows.some(item=>!item||Array.isArray(item)||typeof item.id!=='string'||!item.id||item.id.length>200)||new Set(rows.map(item=>item.id)).size!==rows.length)throw Error('Each Editor collection needs at most 10,000 items with distinct, nonempty IDs of at most 200 characters.');});return normalize(value);};\\ndocument.getElementById('applyRaw').addEventListener('click',async()=>{if(blocked()||scratch.text===null)return;const requested=JSON.stringify(scratch);busy=true;draw();try{await scratchShared.flush();if(JSON.stringify(scratch)!==requested)throw Error('The shared JSON draft changed. Review the latest text before applying it.');if(!allowed())throw Error('Editing access changed. JSON text is retained.');const pending=scratch,value=validateEditor(JSON.parse(pending.text)),edits=StillMade.diffDocument(pending.base||draft,value);commitEdit(StillMade.applyDocument(draft,edits));await shared.flush();if(!allowed())throw Error('Editing access changed. JSON text is retained.');if(JSON.stringify(scratch)===requested){scratch={text:null,base:null};rawStale=false;scratchShared.changed();await scratchShared.flush();}status.textContent='Complete Editor data applied to the shared timeline.';}catch(error){status.textContent=error.message;}finally{busy=false;draw();}});\\nconst editOptions=next=>{if(blocked())return;options=next;optionsShared.changed();revision+=1;};\\ndocument.getElementById('renderFps').addEventListener('change',()=>editOptions({...options,renderFps:Number(document.getElementById('renderFps').value)}));\\ndocument.getElementById('renderResolution').addEventListener('change',()=>editOptions({...options,renderResolution:Number(document.getElementById('renderResolution').value)}));\\ndocument.getElementById('renderQuality').addEventListener('change',()=>editOptions({...options,renderQuality:document.getElementById('renderQuality').value}));\\nconst runAction=async(render)=>{if(blocked()||scratch.text!==null)return;busy=true;draw();status.textContent=render?'Preparing the exact final render…':'Checking the complete Editor timeline…';try{await shared.flush();await scratchShared.flush();await optionsShared.flush();if(!allowed()||scratch.text!==null)throw Error('Editing access or the shared draft changed. The action was not run.');const started=revision;await StillMade.run({editor:clone(source),updatedEditor:clone(draft),commit:!render,...render?{action:'render',...options}:{}});status.textContent=started!==revision?'A result is ready below; newer shared edits were retained.':render?'Final render is ready below. Choose Render final file to start the device renderer.':'Editor changes are ready below. Review the before and after, then choose Apply.';}catch(error){status.textContent=error.message||'The Editor action could not be prepared.';}finally{busy=false;draw();}};\\nsave.addEventListener('click',()=>runAction(false));\\ndocument.getElementById('renderFinal').addEventListener('click',()=>runAction(true));\\nconst recover=async(action)=>{if(busy||!shared||![access,scratchAccess,optionsAccess].every(value=>value.canEdit&&!value.pending))return;busy=true;draw();try{await action();sourceResetArmed=false;undoStack=[];redoStack=[];historyBefore=null;historyAfter=null;status.textContent='Shared Editor draft recovered.';}catch(error){status.textContent=error.message;}finally{busy=false;draw();}};\\ndocument.getElementById('retryShared').addEventListener('click',()=>recover(async()=>{await shared.retry();await scratchShared.retry();await optionsShared.retry();}));\\ndocument.getElementById('discardShared').addEventListener('click',()=>recover(async()=>{await shared.discard();await scratchShared.discard();await optionsShared.discard();}));\\ndocument.getElementById('resetSharedSource').addEventListener('click',()=>{sourceResetArmed=true;drawRecovery();});\\ndocument.getElementById('confirmSourceReset').addEventListener('click',()=>{if(!sourceResetArmed||!access.sourceConflict)return;sourceResetArmed=false;recover(()=>shared.resetSharedSource({discardSharedEdits:true}));});\\nStillMade.onShared(value=>{sourceResetArmed=false;drawRecovery();const outputs=value.outputs||{};document.getElementById('sharedResult').textContent=outputs.mediaAction?'A final-render plan is available in the shared result below.':outputs.editor?'The latest reviewed Editor result is available below.':'';});\\nStillMade.onInput(values=>{sourceResetArmed=false;source=clone(values.editor||empty);assets=Array.isArray(values.assets)?clone(values.assets):[];previewSerial+=1;if(previewUrl){StillMade.releaseMedia(previewUrl);previewUrl='';}imagePreview.hidden=true;videoPreview.hidden=true;audioPreview.hidden=true;const next=normalize(values.updatedEditor&&(values.updatedEditor.clips?.length||values.updatedEditor.audioItems?.length||values.updatedEditor.timelineVersions?.length)?clone(values.updatedEditor):source.clips?.length||source.audioItems?.length?clone(source):assemble());if(!shared){draft=next;shared=StillMade.connectDocument({key:'editorDocument',source:next,read:()=>draft,replace:value=>{sourceResetArmed=false;captureHistory();draft=value;revision+=1;if(scratch.text!==null)rawStale=true;draw();}});scratchShared=StillMade.connectDocument({key:'editorScratch',source:{text:null,base:null},read:()=>scratch,replace:value=>{scratch=value;rawStale=scratch.text!==null;if(scratch.text!==null&&rawIsOpen()&&raw.value!==scratch.text)raw.value=scratch.text;else schedulePreview();drawRecovery();}});optionsShared=StillMade.connectDocument({key:'editorOptions',source:{renderFps:30,renderResolution:1080,renderQuality:'high'},read:()=>options,replace:value=>{options=value;revision+=1;drawOptions();}});shared.onStatus(value=>{const redraw=access.canEdit!==value.canEdit||access.error!==value.error;access=value;if(redraw)draw();else drawRecovery();});scratchShared.onStatus(value=>{const redraw=scratchAccess.canEdit!==value.canEdit||scratchAccess.error!==value.error;scratchAccess=value;if(redraw)draw();else drawRecovery();});optionsShared.onStatus(value=>{const redraw=optionsAccess.canEdit!==value.canEdit||optionsAccess.error!==value.error;optionsAccess=value;if(redraw)draw();else drawRecovery();});playhead.value='0';}else shared.replaceSource(next);revision+=1;draw();status.textContent=access.error||'Timeline changes, JSON drafts and export settings are shared live. Playback and previews are personal.';});\\n\"\n}"},"lineage":{"parents":[],"changes":"Packaged original Block source for StillMade."}}}],"stages":[{"id":"make","blockId":"stillmade.short-form-finish","version":"1.0.1","label":"Captioned Business Clip","config":{"purpose":"talking-head","aspect":"9:16","captionStyle":"Clean","fit":"contain"}},{"id":"finish","blockId":"sm.editor","version":"2.2.9","label":"Editor","config":{"commit":true,"renderFps":30,"renderResolution":1080,"renderQuality":"high"}}],"connections":[{"from":{"stage":"make","port":"timeline"},"to":{"stage":"finish","port":"updatedEditor"}}],"outcome":{"type":"export","dedupe":"material_project_state","minimumDurationSec":5}}