// @requirements REQ-PRODUCT-SETUP-SESSION import {captureEditorFields,restoreEditorFields} from './setup-session-fields.js'; import type {EditorFields,InventoryEditorDraft} from './setup-session-fields.js'; // @requirements REQ-PRODUCT-STORAGE-AUTHORING REQ-PRODUCT-A11Y REQ-PRODUCT-MOBILE import {toPublicConfig} from './config.js'; import {createStorageDraftPlan,assertStorageDraftBaseline,storageDraftReviewStep,serializeStorageDraftReview,readStorageDraftReview} from './setup-storage.js'; import {technologyCollectionScope} from './technology-collection-policy.js'; import type {StorageDraftItem,StorageDraftPlan,StorageInventoryChange,StorageServiceScope,StorageDraftReviewStep} from './setup-storage.js'; import type {StorageItem} from './types.js'; /** Public inventory proposals stay separate from the host draft until explicit save. */ export function mountStorageEditor(container:HTMLElement,options:{getConfig():unknown;onChange(plan:StorageDraftPlan):void}){ const doc=container.ownerDocument,view=doc.defaultView;if(!view||!options||typeof options.getConfig!=='function'||typeof options.onChange!=='function')throw Error('Supply a document window and draft read/change callbacks.'); const node=(tag:K,text?:string)=>{const el=doc.createElement(tag);if(text!==undefined)el.textContent=text;return el;},root=node('details');root.className='nb-setup-purpose-editor nb-setup-storage-editor';container.append(root);const summary=node('summary'),summaryTitle=node('h2'),body=node('div');summary.append(summaryTitle);body.className='nb-setup-purpose-body';root.append(summary,body);body.append(node('p','Declare actual storage names, owners and duration. These facts appear in notices. Saving changes neither browser storage nor permission.')); const filter=node('input');filter.type='search';filter.setAttribute('aria-label','Find declared storage');filter.placeholder='Find a storage name, ID or service';body.append(filter);const list=node('div');list.className='nb-setup-purpose-list';body.append(list);const paging=node('div');paging.className='nb-setup-purpose-actions';const previous=node('button','Previous storage items'),next=node('button','Next storage items'),count=node('p');for(const b of [previous,next]){b.type='button';b.className='nb-choice-button';}paging.append(previous,count,next);body.append(paging);let page=0,destroyed=false,reviewUrl:string|undefined,generation=0;const reviewSteps:StorageDraftReviewStep[]=[];type Proposal={baseline:unknown;id?:string;remove:boolean;fields:EditorFields;owner?:string;scopes:[string,{scope:string;technology:string}][]};let draftRead:(()=>Proposal)|undefined; const add=node('button','Declare storage');add.type='button';add.className='nb-choice-button';body.append(add);const status=node('p');status.setAttribute('role','status');const download=node('a','Download storage-change review');download.hidden=true;body.append(status,download);const panel=node('section');panel.className='nb-setup-purpose-proposal';panel.hidden=true;body.append(panel); for(const type of ['input','change'])root.addEventListener(type,event=>event.stopPropagation());root.addEventListener('keydown',event=>{event.stopPropagation();if(event.key==='Enter'&&!event.isComposing&&(event.target as HTMLElement)?.tagName==='INPUT')event.preventDefault();}); function close(){generation++;panel.hidden=true;panel.replaceChildren();} function clearReview(){if(reviewUrl)view!.URL.revokeObjectURL(reviewUrl);reviewUrl=undefined;download.hidden=true;download.removeAttribute('href');download.removeAttribute('download');} function render(){if(destroyed)return;list.replaceChildren();try{const c=toPublicConfig(options.getConfig(),{mode:'preview'}),protectedIds=new Set(c.storageExceptions?.entries.flatMap(e=>e.serviceIds)??[]),query=filter.value.toLocaleLowerCase(),items=c.storage.filter(i=>[i.id,i.name,i.serviceId,c.services.find(s=>s.id===i.serviceId)?.name??''].some(v=>v.toLocaleLowerCase().includes(query)));summaryTitle.textContent='Browser storage · '+c.storage.length+' declared';page=Math.min(page,Math.max(0,Math.ceil(items.length/12)-1));const visible=items.slice(page*12,page*12+12);count.textContent=items.length?'Showing '+(page*12+1)+'–'+(page*12+visible.length)+' of '+items.length:'No matching declarations';previous.disabled=page===0;next.disabled=(page+1)*12>=items.length;paging.hidden=items.length<=12;if(!items.length)list.append(node('p',c.storage.length?'No declarations match this search.':'No storage declared. A catalog hint is not a declaration of actual use.'));for(const item of visible){const card=node('section');card.className='nb-setup-purpose-card';card.append(node('h3',item.name),node('p',item.type+' · '+item.classification+' · '+item.serviceId),node('p',item.duration));const locked=item.classification==='exception'||protectedIds.has(item.serviceId),actions=node('div');actions.className='nb-setup-purpose-actions';if(locked)card.append(node('p','Owned by an assessed-exception profile. Review that complete profile separately.'));for(const [label,remove] of [['Edit',false],['Remove',true]] as const){const b=node('button',label);b.type='button';b.disabled=locked;b.className='nb-choice-button';b.setAttribute('aria-label',label+' storage '+item.name);b.addEventListener('click',()=>{try{edit(item,remove);}catch{status.textContent='Finish importing a valid config before editing storage.';}});actions.append(b);}card.append(actions);list.append(card);}add.disabled=!c.services.some(s=>!protectedIds.has(s.id));}catch{summaryTitle.textContent='Browser storage';list.append(node('p','Finish importing a valid config before editing storage.'));}} function edit(prior?:StorageItem,remove=false,resume?:Proposal){if(destroyed)return;const snapshot=toPublicConfig(resume?.baseline??options.getConfig(),{mode:'preview'});if(prior){const fresh=snapshot.storage.find(item=>item.id===prior!.id),protectedIds=new Set(snapshot.storageExceptions?.entries.flatMap(e=>e.serviceIds)??[]);if(!fresh||fresh.classification==='exception'||protectedIds.has(fresh.serviceId))throw Error('Reopen the current storage inventory before editing this item.');prior=structuredClone(fresh);}close();const operation=generation;panel.hidden=false;root.open=true;const heading=node('h3',remove?'Remove storage declaration':prior?'Edit storage declaration':'Declare browser storage');heading.tabIndex=-1;panel.append(heading,node('p','All facts below are public. Do not enter stored values, personal identifiers or tokens. A necessity reason is an assertion for review, not a qualification decision.'));const error=node('p');error.setAttribute('role','alert');panel.append(error); const prefix='nb-storage-'+crypto.randomUUID();let seq=0;const fields:(HTMLInputElement|HTMLTextAreaElement|HTMLSelectElement)[]=[]; function field(parent:HTMLElement,label:string,value:string,choices?:[string,string][],multiline=false,required=true,max=2000){const wrap=node('div');wrap.className='nb-setup-purpose-field';const caption=node('label',label),id=prefix+'-'+seq++,control=choices?node('select'):multiline?node('textarea'):node('input');control.id=id;caption.htmlFor=id;if(choices)for(const [value,text] of choices){const o=node('option',text);o.value=value;control.append(o);}else (control as HTMLInputElement|HTMLTextAreaElement).maxLength=max;if(control instanceof view!.HTMLTextAreaElement)control.rows=3;control.value=value;control.required=required;fields.push(control);wrap.append(caption,control);parent.append(wrap);return control;} const grid=node('div');grid.className='nb-setup-purpose-fields';panel.append(grid);let readItem:()=>StorageDraftItem; const protectedIds=new Set(snapshot.storageExceptions?.entries.flatMap(e=>e.serviceIds)??[]);let owner:HTMLSelectElement|undefined; if(remove){panel.append(node('p','Remove '+prior!.name+' ('+prior!.id+') from the draft? Previous names/owners stay in the change review. Existing markers and cleanup targets still need host migration.'));readItem=()=>{throw Error('No replacement for removal.');};} else{const id=field(grid,'Stable storage ID',prior?.id??'',undefined,false,true,120) as HTMLInputElement;id.readOnly=!!prior;id.pattern='[a-z][a-z0-9-]*';const name=field(grid,'Actual storage name',prior?.name??'',undefined,false,true,300);const type=field(grid,'Storage type',prior?.type??'',[['','Choose the actual type'],['cookie','Cookie'],['localStorage','Local storage'],['sessionStorage','Session storage'],['indexedDB','IndexedDB'],['other','Other']]);owner=field(grid,'Owning service',prior?.serviceId??'',[['','Choose the actual owner'],...snapshot.services.filter(s=>!protectedIds.has(s.id)).map(s=>[s.id,s.name+' · '+s.id] as [string,string])]) as HTMLSelectElement;const duration=field(grid,'Actual duration',prior?.duration??'');const classification=field(grid,'Storage classification',prior?.classification??'',[['','Choose after assessment'],['optional','Optional'],['necessary','Necessary — public reason required']]);const reason=field(grid,'Public necessity reason',prior?.necessityReason??'',undefined,true,false);const reasonState=()=>{reason.required=classification.value==='necessary';};classification.addEventListener('change',reasonState);reasonState();panel.append(node('p','The built-in cleanup adapter handles exact optional cookie/local/session items only. Cookie paths/domains, inaccessible or partitioned cookies, IndexedDB and other storage need separate host work.')); readItem=()=>({id:id.value.trim(),name:name.value,type:type.value as StorageItem['type'],serviceId:owner!.value,duration:duration.value.trim(),classification:classification.value as 'optional'|'necessary',...(reason.value.trim()?{necessityReason:reason.value.trim()}:{})} as StorageDraftItem); } const scopeArea=node('section');panel.append(scopeArea);const values=new Map(resume?.scopes??[]);let scopeReaders:(()=>StorageServiceScope)[]=[]; function scopeFields(){scopeArea.replaceChildren(node('h4','Affected consent-service versions'));scopeReaders=[];const ids=new Set([...(prior?[prior.serviceId]:[]),...(owner?.value?[owner.value]:[])]),enrolled=snapshot.consent?.services.filter(s=>ids.has(s.id))??[];if(!enrolled.length)scopeArea.append(node('p','No consent-managed owner is affected. No consent scope will be added.'));for(const entry of enrolled){const group=node('div');group.className='nb-setup-purpose-card';scopeArea.append(group);const service=snapshot.services.find(s=>s.id===entry.id)!;group.append(node('h4',service.name),node('p','Current: '+entry.scope),node('p','A new material version affects every purpose of this owner: '+service.purposeIds.join(', ')+'. Use a never-reused version; only the current value can be checked here.'));const cached=values.get(entry.id)??{scope:'',technology:''};values.set(entry.id,cached);const version=field(group,service.name+' — new material version',cached.scope,undefined,false,true,200);version.addEventListener('input',()=>{cached.scope=version.value;});let declaration:HTMLTextAreaElement|undefined;if(entry.scope.startsWith('technology-v1:')){declaration=field(group,service.name+' — revised technology declaration JSON',cached.technology,undefined,true,true,30000) as HTMLTextAreaElement;declaration.addEventListener('input',()=>{cached.technology=declaration!.value;});const derive=node('button','Use revised declaration scope');derive.type='button';derive.className='nb-choice-button';derive.addEventListener('click',async()=>{derive.disabled=true;try{const binding=JSON.parse(declaration!.value);if(binding.serviceId!==entry.id)throw Error();const derived=await technologyCollectionScope(binding);if(destroyed||operation!==generation||!declaration!.isConnected)return;version.value=derived;cached.scope=derived;panel.dispatchEvent(new view!.Event('input',{bubbles:true}));error.textContent='';}catch{if(!destroyed&&operation===generation)error.textContent='Supply the complete revised declaration for this service before deriving its scope.';}finally{if(!destroyed&&operation===generation)derive.disabled=false;}});group.append(derive);}scopeReaders.push(()=>({id:entry.id,scope:version.value.trim(),...(declaration?{technology:JSON.parse(declaration.value)}:{})}));}} if(owner&&resume?.owner!==undefined)owner.value=resume.owner;scopeFields();owner?.addEventListener('change',scopeFields); const ack=node('input');ack.type='checkbox';ack.dataset.sessionReview='';const ackLabel=node('label');ackLabel.className='nb-setup-storage-ack';ackLabel.append(ack,doc.createTextNode('Apply these declaration and material-version changes to the local draft'));panel.append(ackLabel); const actions=node('div');actions.className='nb-setup-purpose-actions';const save=node('button',remove?'Remove declaration':'Save storage declaration'),cancel=node('button','Cancel storage changes');for(const b of [save,cancel]){b.type='button';b.className='nb-choice-button';}save.classList.add('nb-primary');actions.append(save,cancel);panel.append(actions);cancel.addEventListener('click',()=>{close();add.focus();}); save.addEventListener('click',async()=>{if(save.disabled||destroyed||operation!==generation)return;error.textContent='';for(const f of fields.filter(f=>f.isConnected)){f.removeAttribute('aria-invalid');if(!f.checkValidity()){f.setAttribute('aria-invalid','true');error.textContent='Complete the highlighted public field. No type, owner or classification is inferred.';f.focus();return;}}if(!ack.checked){error.textContent='Review the public facts, affected versions and migration work, then confirm the local draft change.';ack.focus();return;}save.disabled=true;for(const f of fields)f.disabled=true;ack.disabled=true;let pendingUrl:string|undefined;try{const mutation:StorageInventoryChange=remove?{action:'remove',storageId:prior!.id}:prior?{action:'update',storageId:prior.id,item:readItem()}:{action:'add',item:readItem()},current=(()=>{try{return options.getConfig();}catch{throw Error('Could not read the current host draft. Check it before saving.');}})(),plan=await createStorageDraftPlan(current,{baseline:snapshot,changes:[mutation],serviceScopes:scopeReaders.map(read=>read())});if(destroyed||operation!==generation)return; let latest:unknown;try{latest=options.getConfig();}catch{throw Error('Could not read the current host draft. Check it before saving.');}assertStorageDraftBaseline(latest,snapshot); const step=storageDraftReviewStep(plan),review=serializeStorageDraftReview([...reviewSteps,step]); try{pendingUrl=view!.URL.createObjectURL(new view!.Blob([review],{type:'application/json'}));}catch{throw Error('The change-review download is unavailable. Keep the current draft and retry in a browser that supports local file downloads.');} try{options.onChange(plan);}catch{error.textContent='Could not confirm the host draft update. Check the current draft before trying again.';return;} reviewSteps.push(step);clearReview();reviewUrl=pendingUrl;pendingUrl=undefined; if(destroyed){clearReview();return;}close();render();status.textContent='Storage declaration saved in the local draft. No browser data was changed. Download the cumulative change review before leaving this setup session.';download.href=reviewUrl!;download.download='storage-change-review.private.json';download.hidden=false;add.focus(); }catch(e){if(!destroyed&&operation===generation)error.textContent=e instanceof Error?e.message:'Could not apply the storage proposal.';}finally{if(pendingUrl)view!.URL.revokeObjectURL(pendingUrl);if(!destroyed&&operation===generation){save.disabled=false;for(const f of fields)f.disabled=false;ack.disabled=false;}}});draftRead=()=>({baseline:snapshot,...(prior?{id:prior.id}:{}),remove,fields:captureEditorFields(panel),...(owner?{owner:owner.value}:{}),scopes:[...values]});if(resume){restoreEditorFields(panel,resume.fields);const classification=panel.querySelectorAll('select')[2];classification?.dispatchEvent(new view!.Event('change'));}heading.focus(); } filter.addEventListener('input',()=>{page=0;render();});previous.addEventListener('click',()=>{page--;render();});next.addEventListener('click',()=>{page++;render();});add.addEventListener('click',()=>{try{edit();}catch{status.textContent='Declare a real service and import a valid config before adding storage.';}});render();return {getSessionDraft(){return {open:root.open,filter:filter.value,review:structuredClone(reviewSteps),...(!panel.hidden&&draftRead?{proposal:draftRead()}:{})};},restoreSessionDraft(draft:{open:boolean;filter:string;review:StorageDraftReviewStep[];proposal?:Proposal}){const steps=readStorageDraftReview(draft.review);if(steps.length){const text=serializeStorageDraftReview(steps),url=view!.URL.createObjectURL(new view!.Blob([text],{type:'application/json'}));clearReview();reviewSteps.splice(0,reviewSteps.length,...steps);reviewUrl=url;download.href=url;download.download='storage-change-review.private.json';download.hidden=false;}filter.value=draft.filter;render();if(draft.proposal){const p=draft.proposal,c=toPublicConfig(p.baseline,{mode:'preview'}),prior=p.id?c.storage.find(v=>v.id===p.id):undefined;if(p.id&&!prior||p.remove&&!prior)throw Error('The saved storage item is missing.');edit(prior,p.remove,p);}root.open=draft.open;},show(){if(destroyed)throw Error('Editor has ended.');root.open=true;summary.focus();},open(){edit();},refresh({discardDraft=false}={}){if(discardDraft)close();render();},destroy(){if(destroyed)return;destroyed=true;clearReview();root.remove();}}; }