/* Copyright 2026 Renchao Wu. Apache-2.0. Declared bounded HTTP range planning profile. */ export const VERSION='0.1.0';export const IDENTITY='work:http-range-desk:v1';export const CONTRACT_SHA='0f5ea519f90c54011ab2def053f0c3bc722a55c1fe505b246a8c437801bb2b8b'; const MAX=9223372036854775807n;const MONTHS=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];const DAYS=['Sun','Mon','Tue','Wed','Thu','Fri','Sat']; function object(v){if(!v||typeof v!=='object'||Array.isArray(v)||![Object.prototype,null].includes(Object.getPrototypeOf(v)))throw TypeError('Expected ordinary object');} function exact(v,keys){object(v);if(Object.keys(v).length!==keys.length||keys.some(k=>!Object.hasOwn(v,k)))throw TypeError('Missing or extra fields');} function header(v,max,name){if(v!==null&&(typeof v!=='string'||v.length>max||/[\r\n\0]/.test(v)))throw TypeError(`${name}: bounded header string or null required`);} function trim(v){return v.replace(/^[ \t]+|[ \t]+$/g,'');} function tag(s){if(typeof s!=='string')return null;let weak=s.startsWith('W/'),body=weak?s.slice(2):s;if(body.length<2||body[0]!=='"'||body.at(-1)!=='"')return null;let value=body.slice(1,-1);for(let c of value){let k=c.codePointAt(0);if(!(k===33||k>=35&&k<=126||k>=128&&k<=255))return null;}return {weak,opaque:value};} function date(s){if(typeof s!=='string')return null;let m=/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/.exec(s);if(!m)return null;let day=+m[2],month=MONTHS.indexOf(m[3]),year=+m[4],h=+m[5],min=+m[6],sec=+m[7];if(year<1601||day<1||h>23||min>59||sec>59)return null;let t=new Date(Date.UTC(year,month,day,h,min,sec));if(t.getUTCFullYear()!==year||t.getUTCMonth()!==month||t.getUTCDate()!==day||DAYS[t.getUTCDay()]!==m[1])return null;return t.getTime()/1000;} function freeze(x){if(x&&typeof x==='object'){for(let v of Object.values(x))freeze(v);Object.freeze(x);}return x;} async function sha(bytes){let data=new Uint8Array(await crypto.subtle.digest('SHA-256',bytes));return [...data].map(x=>x.toString(16).padStart(2,'0')).join('');} export function parseRequest(text){if(typeof text!=='string'||text.length>65536)throw TypeError('JSON text cap 65,536 UTF-16 units');return validate(JSON.parse(text));} function validate(q){exact(q,['method','base_status','resource','range','if_range']);if(!['GET','HEAD'].includes(q.method)||![200,304,412].includes(q.base_status)||typeof q.base_status!=='number')throw TypeError('Expected GET/HEAD and base_status 200/304/412');let r=q.resource;exact(r,['length','etag','last_modified','date_is_strong']);if(typeof r.length!=='string'||!/^(0|[1-9][0-9]{0,18})$/.test(r.length)||BigInt(r.length)>MAX)throw TypeError('Resource length must be canonical decimal string within signed 64-bit nonnegative range');header(r.etag,1024,'ETag');if(r.etag!==null&&!tag(r.etag))throw TypeError('Resource ETag is outside the quoted entity-tag profile');header(r.last_modified,29,'Last-Modified');if(r.last_modified!==null&&date(r.last_modified)===null)throw TypeError('Resource date must be canonical real IMF-fixdate within profile');if(typeof r.date_is_strong!=='boolean'||r.date_is_strong&&r.last_modified===null)throw TypeError('Explicit date strength assertion requires a known date');header(q.range,8192,'Range');header(q.if_range,1024,'If-Range');return q;} function notEvaluated(){return {status:'not-evaluated',unit:null,complete:false,raw_token_count:null,empty_member_count:null,nonempty_member_count:null,semantic_satisfiable_members:null,members:[]};} export function parseRange(raw,length){if(typeof raw!=='string'||raw.length>8192||/[\r\n\0]/.test(raw))throw TypeError('Bounded non-null Range header required');if(typeof length!=='string'||!/^(0|[1-9][0-9]{0,18})$/.test(length)||BigInt(length)>MAX)throw TypeError('Canonical resource length required');let n=BigInt(length),text=trim(raw),equals=text.indexOf('='),a={status:'malformed',unit:null,complete:true,raw_token_count:0,empty_member_count:0,nonempty_member_count:0,semantic_satisfiable_members:null,members:[]};if(equals<1||text.indexOf('=',equals+1)!==-1)return a;let unit=text.slice(0,equals);if(!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(unit))return a;a.unit=unit;if(unit.toLowerCase()!=='bytes'){a.status='unsupported-unit';a.complete=false;a.raw_token_count=null;a.empty_member_count=null;a.nonempty_member_count=null;return a;}let tokens=text.slice(equals+1).split(',');a.raw_token_count=tokens.length;let malformed=false,outside=false,sat=0; for(let [ordinal,rawMember] of tokens.entries()){let value=trim(rawMember),row={ordinal,raw:rawMember,trimmed:value,kind:null,status:null,first:null,last:null,suffix:null,satisfiable:null,interval:null};a.members.push(row);if(value===''){a.empty_member_count++;row.status='ignored-empty';if(a.empty_member_count>64){row.status='outside-profile-empty-cap';outside=true;break;}continue;}a.nonempty_member_count++;if(a.nonempty_member_count>64){row.status='outside-profile-range-cap';outside=true;break;}let m=/^(?:([0-9]+)-([0-9]*)|-([0-9]+))$/.exec(value);if(!m){row.status='malformed';malformed=true;continue;}let components=[m[1],m[2],m[3]].filter(x=>x!==undefined&&x!=='');if(components.some(x=>x.length>256)){row.status='outside-profile-digit-cap';outside=true;break;}let first,last,start,end;row.status='valid';if(m[3]!==undefined){let count=BigInt(m[3]);row.kind='suffix';row.suffix=String(count);row.satisfiable=count>0n;if(row.satisfiable){start=n>count?n-count:0n;end=n;}}else{first=BigInt(m[1]);last=m[2]===''?null:BigInt(m[2]);row.kind=last===null?'open':'closed';row.first=String(first);row.last=last===null?null:String(last);if(last!==null&&last=n?n:last+1n;}}if(row.satisfiable){sat++;row.interval={first:String(start),last:end>start?String(end-1n):null,exclusive_end:String(end),length:String(end-start)};}} a.status=outside?'outside-profile':malformed||a.nonempty_member_count===0?'malformed':'valid';a.complete=!outside;a.semantic_satisfiable_members=a.status==='valid'?sat:null;return a;} export function compareIfRange(raw,resource){if(raw===null)return {kind:'not-present',status:'allow',matches:true,provided:null,comparison:null,date_strength_is_caller_asserted:true};let v=trim(raw),t=tag(v);if(t){let current=tag(resource.etag);let matches=!!current&&!t.weak&&!current.weak&&t.opaque===current.opaque;return {kind:'entity-tag',status:matches?'match':'nonmatch',matches,provided:raw,comparison:'strong-exact',request_is_weak:t.weak,current_is_weak:current?.weak??null,date_strength_is_caller_asserted:true};}let d=date(v);if(d!==null){let match=resource.date_is_strong&&resource.last_modified!==null&&d===date(resource.last_modified);return {kind:'http-date',status:match?'match':'nonmatch',matches:match,provided:raw,comparison:'exact-seconds-not-earlier-or-equal',date_strength_is_caller_asserted:true,date_asserted_strong:resource.date_is_strong,current_last_modified:resource.last_modified};}let older=/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),/.test(v)||/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) /.test(v)||/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:60 GMT$/.test(v);return {kind:older?'outside-profile':'invalid-validator',status:older?'outside-profile':'nonmatch',matches:older?null:false,provided:raw,comparison:null,date_strength_is_caller_asserted:true};} function unionOf(intervals){let sorted=intervals.map(r=>[BigInt(r.first),BigInt(r.exclusive_end)]).filter(([a,b])=>aa[0]b[0]?1:0),union=[];for(let[a,b]of sorted){if(union.length&&a<=union.at(-1)[1]){if(b>union.at(-1)[1])union.at(-1)[1]=b;}else union.push([a,b]);}return union.map(([a,b])=>({first:String(a),last:String(b-1n),exclusive_end:String(b),length:String(b-a)}));} export async function makeReport(input,payload=null){let rawSnapshot=JSON.stringify(input);if(typeof rawSnapshot!=='string'||rawSnapshot.length>65536)throw TypeError('Bounded JSON request required');let q=validate(JSON.parse(rawSnapshot)),n=BigInt(q.resource.length),bytes=null;if(payload!==null){if(!(payload instanceof Uint8Array)||payload.byteLength>1048576)throw TypeError('Payload must be Uint8Array up to 1 MiB');bytes=new Uint8Array(payload);if(BigInt(bytes.byteLength)!==n)throw RangeError('Observed local payload length disagrees with asserted resource length');}let analysis=notEvaluated(),condition={kind:'not-evaluated',status:'not-evaluated',matches:null,provided:q.if_range,comparison:null,date_strength_is_caller_asserted:true},status=null,reason='',trace=[],selected=[]; function full(why){status=200;reason=why;if(q.method==='GET'&&n>0n)selected=[{member_ordinal:null,first:'0',last:String(n-1n),exclusive_end:String(n),length:String(n)}];} if(q.base_status!==200){status=q.base_status;reason='base-status';trace.push('Caller-supplied other-precondition outcome takes precedence; Range and If-Range not evaluated.');}else if(q.method!=='GET'){status=200;reason='method';trace.push('Range semantics not defined for HEAD; no selected representation body.');}else if(q.range===null){full('no-range');trace.push('No Range header; If-Range ignored.');}else{analysis=parseRange(q.range,q.resource.length);trace.push(`Range analysis: ${analysis.status}.`);if(analysis.status==='outside-profile'){reason='outside-profile';}else if(analysis.status==='unsupported-unit'){full('unsupported-unit');}else if(analysis.status==='malformed'){full('malformed-range-policy');}else{condition=compareIfRange(q.if_range,q.resource);trace.push(`If-Range: ${condition.status}.`);if(condition.status==='outside-profile'){reason='outside-profile';}else if(!condition.matches){full('if-range-failed');}else if(n===0n){full('empty-representation-policy');trace.push('RFC permits ignoring ranges on an empty representation; a nonzero suffix remains semantically satisfiable in analysis.');}else if(analysis.semantic_satisfiable_members===0){status=416;reason='all-unsatisfiable';}else{status=206;reason='partial-ranges';selected=analysis.members.filter(r=>r.status==='valid'&&r.satisfiable).map(r=>({member_ordinal:r.ordinal,...r.interval}));}}} let union=unionOf(selected),sum=selected.reduce((a,r)=>a+BigInt(r.length),0n),unique=union.reduce((a,r)=>a+BigInt(r.length),0n);let parts=selected.map((r,i)=>({part_ordinal:i,...r,content_range:status===206?`bytes ${r.first}-${r.last}/${n}`:null}));let actual=null;if(bytes!==null){let slices=[];for(let part of parts){let b=bytes.slice(Number(BigInt(part.first)),Number(BigInt(part.exclusive_end)));slices.push({part_ordinal:part.part_ordinal,observed_byte_length:String(b.length),sha256:await sha(b),preview_first32_hex:[...b.slice(0,32)].map(x=>x.toString(16).padStart(2,'0')).join(''),preview_truncated:b.length>32});}actual={whole_observed_byte_length:String(bytes.length),whole_sha256:await sha(bytes),slices,local_only_no_upload:true};} let report={schema:'http-range-desk-report-v1',version:VERSION,author:'Renchao Wu',work_identity:IDENTITY,provenance:{contract_sha256:CONTRACT_SHA,request_snapshot_sha256:await sha(new TextEncoder().encode(rawSnapshot)),snapshot_digest_not_raw_JSON_bytes:true},request:q,scope:{declared_bounded_profile_not_universal_server:true,resource_metadata_is_caller_asserted:true,other_preconditions_are_caller_supplied:true,date_strength_is_caller_asserted:true,representation_is_encoded_octets_not_characters:true,no_network_request_made:true,no_training:true,payload_observed:bytes!==null,multipart_wire_body_not_constructed:true},decision_trace:trace,range_analysis:analysis,if_range:condition,plan:{status,reason,range_response_policy:'optional-range-support-ignore-malformed-and-empty-keep-all-satisfiable-parts',kind:status===206?(parts.length===1?'single-range':'multipart-plan'):status===200&&q.method==='GET'?'full-representation':status===null?'outside-profile':'no-selected-representation-data',content_range:status===416?`bytes */${n}`:status===206&&parts.length===1?parts[0].content_range:null,planned_content_length:status===206&&parts.length===1?parts[0].length:status===200&&q.method==='GET'?String(n):null,wire_body_length_unknown:true,selected_payload_bytes:String(sum),unique_payload_bytes:String(unique),overlap_payload_bytes:String(sum-unique),selected_intervals:parts,diagnostic_union_intervals:union,request_order_and_duplicate_parts_preserved:true},actual_payload:actual};return freeze(report);} export function reportCsv(r){let cols=['part_ordinal','member_ordinal','first_inclusive','last_inclusive','exclusive_end','length','content_range','observed_byte_length','sha256','preview_first32_hex'],rows=r.plan.selected_intervals.map(p=>{let s=r.actual_payload?.slices.find(s=>s.part_ordinal===p.part_ordinal);return[p.part_ordinal,p.member_ordinal,p.first,p.last,p.exclusive_end,p.length,p.content_range,s?.observed_byte_length,s?.sha256,s?.preview_first32_hex];});return [cols,...rows].map(row=>row.map(x=>'"'+String(x??'').replaceAll('"','""')+'"').join(',')).join('\r\n')+'\r\n';}