@panphora/clayjs 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,14 +2,16 @@
2
2
  // hyper-html-api/dist/hyper-html-api.engine.min.js via hyper-html-api
3
3
  // `npm run copy-to-clayjs`. Edit the hyper-html-api source and re-run.
4
4
  (function () {
5
- var hyperHtmlApiData=(()=>{var Y=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var de=(e,t)=>{for(var n in t)Y(e,n,{get:t[n],enumerable:!0})},$e=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of De(t))!_e.call(e,r)&&r!==n&&Y(e,r,{get:()=>t[r],enumerable:!(o=ke(t,r))||o.enumerable});return e};var We=e=>$e(Y({},"__esModule",{value:!0}),e);var st={};de(st,{applyData:()=>ue,default:()=>it,engine:()=>z,extractData:()=>fe});var F=["textContent","innerText","innerHTML","outerHTML","value","checked","selected","disabled","readOnly","type","tagName","nodeName","nodeType","nodeValue","childElementCount","id","className","classList","baseURI","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","dataset","currentSrc","duration","paused","title","documentURI","contentType"],X=new Set(F),he=new Set(["textContent","innerText","innerHTML","value","checked","selected","disabled","readOnly","type","id","className","title"]),G=new Set(["tagName","nodeName","nodeType","nodeValue","childElementCount","classList","baseURI","documentURI","contentType","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","currentSrc","duration","paused","dataset"]);var V={};de(V,{EmptyListInsert:()=>$,MAX_RULE_DEPTH:()=>I,MaxRuleDepthExceeded:()=>N,NoRulesTag:()=>Z,RuleTargetReadOnly:()=>W,RulesParseError:()=>L,ShapeMismatch:()=>_,UnknownRulesVersion:()=>D,WriteRefused:()=>K,WriteRejected:()=>Q});var L=class extends Error{constructor(t,n){super(t),this.name="RulesParseError",this.cause=n}},D=class extends Error{constructor(t){super(`unknown rules version: ${t}. Library supports "1".`),this.name="UnknownRulesVersion",this.version=t}},I=20,N=class extends Error{constructor(t){super(`rule depth exceeded ${I} at path: ${t.join(".")}`),this.name="MaxRuleDepthExceeded",this.path=t}},_=class extends Error{constructor(t){super(`shape mismatch: ${t.length} field(s) failed validation`),this.name="ShapeMismatch",this.mismatches=t}},$=class extends Error{constructor(t){super(`cannot add items to empty list at "${t.join(".")}" \u2014 no sibling to clone as template. Seed the list with a hidden item first.`),this.name="EmptyListInsert",this.path=t}},W=class extends Error{constructor(t){super(`cannot write to read-only DOM property "${t}"`),this.name="RuleTargetReadOnly",this.target=t}},K=class extends Error{constructor(t){super(`write refused: ${t.length} write(s) broke the content-only policy`),this.name="WriteRefused",this.refusals=t}},Z=class extends Error{constructor(t){super(`no <script data-rules-name~="${t}"> rules tag in this document`),this.name="NoRulesTag",this.token=t}},Q=class extends Error{constructor(t,n){super(`write rejected: ${t.length} unknown key(s), ${n.length} rule(s) with no matching element`),this.name="WriteRejected",this.unknownKeys=t,this.unmatched=n}};function R(e){let t=0,n=null,o=-1;for(let r=0;r<e.length;r++){let i=e[r];i==="\\"?r++:n?i===n&&(n=null):i==='"'||i==="'"?n=i:i==="["||i==="("?t++:i==="]"||i===")"?t>0&&t--:i==="@"&&t===0&&(o=r)}return o}function ee(e){let t=R(e);return t===-1?{selector:e,prop:null}:{selector:e.slice(0,t),prop:e.slice(t+1)||null}}function C(e,t,n,o={}){if(Object.prototype.hasOwnProperty.call(o,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");return te(e,t,n,{depth:0,path:[]},o)}function te(e,t,n,o,r){if(o.depth>I)throw new N(o.path);if(typeof n=="string")return ve(e,t,n,o,r);if(Array.isArray(n)){let[i,c]=n,s=e.find(t,i,r);return me(r,o,s),s.map((l,u)=>te(e,l,c,{depth:o.depth+1,path:[...o.path,u]},r))}if(typeof n=="object"&&n!==null){let i={};for(let[c,s]of Object.entries(n))i[c]=te(e,t,s,{depth:o.depth+1,path:[...o.path,c]},r);return i}return null}function ve(e,t,n,o,r){if(n.endsWith("[]")){let s=n.slice(0,-2),l=e.find(t,s,r);return me(r,o,l),l.map(u=>e.text(u))}if(n.startsWith("@"))return pe(e,t,n.slice(1));let i=R(n);if(i!==-1){let s=n.slice(0,i),l=n.slice(i+1),u=s?e.find(t,s,r):[t];return u.length===0?null:pe(e,u[0],l)}if(n===".")return e.text(t);let c=e.find(t,n,r);return c.length===0?null:e.text(c[0])}function me(e,t,n){if(typeof e.onRowsRead=="function")try{e.onRowsRead(t.path.slice(),n)}catch(o){console.warn(`[hyper-html-api] onRowsRead threw at "${t.path.join(".")||"(root)"}"`,o)}}function pe(e,t,n){if(X.has(n)){let r=e.prop(t,n);return r==null?null:String(r)}let o=e.attr(t,n);return o||null}function we(e,t,n,o){let r=e.length,i=t.length,c=new Array(r).fill(-1);if(o){let f=new Set;for(let h=0;h<r;h++){let y=o[h];!(y>=0&&y<i)||f.has(y)||(c[h]=y,f.add(y))}}if(r===0||i===0)return c;let s=e.map(f=>ye(f,n)),l=t.map(f=>ye(f,n)),u=new Array(i).fill(!1);for(let f of c)f>=0&&(u[f]=!0);let a=new Map;l.forEach((f,h)=>{u[h]||a.set(f,a.has(f)?-1:h)});let g=new Map;s.forEach((f,h)=>{c[h]>=0||g.set(f,(g.get(f)||0)+1)}),s.forEach((f,h)=>{if(c[h]>=0||g.get(f)!==1)return;let y=a.get(f);y===void 0||y===-1||u[y]||(c[h]=y,u[y]=!0)});let d=[];for(let f=0;f<r;f++)c[f]<0&&d.push(f);let O=[];for(let f=0;f<i;f++)u[f]||O.push(f);if(d.length===0||O.length===0)return c;let m=r*i+1,p=(f,h)=>He(e[f],t[h],n)*m+Math.abs(f-h);for(let[f,h]of Be(d,O,p))c[f]=h;return c}var Ee=e=>typeof e=="object"&&e!==null;function ye(e,t){if(!Ee(t))return e==null?" null":String(e);let n=Object.keys(t);return JSON.stringify(n.map(o=>{let r=JSON.stringify(e?.[o]);return r===void 0?" undef":r}))}function He(e,t,n){if(!Ee(n))return e===t?0:1;let o=Object.keys(n);if(o.length===0)return 0;let r=0;for(let i of o){let c=JSON.stringify(e?.[i]),s=JSON.stringify(t?.[i]);c!==s&&r++}return r}function Be(e,t,n){return e.length<=t.length?ge(e,t,n,!1):ge(t,e,(o,r)=>n(r,o),!0)}function ge(e,t,n,o){let r=e.length,i=t.length,c=[];for(let g=0;g<=r;g++)c.push(new Float64Array(i+1).fill(1/0));let s=[];for(let g=0;g<=r;g++)s.push(new Uint8Array(i+1));for(let g=0;g<=i;g++)c[r][g]=0;for(let g=r-1;g>=0;g--)for(let d=i-1;d>=0;d--){let O=n(e[g],t[d])+c[g+1][d+1],m=c[g][d+1];O<=m?(c[g][d]=O,s[g][d]=1):c[g][d]=m}let l=[],u=0,a=0;for(;u<r&&a<i;)s[u][a]&&(l.push(o?[t[a],e[u]]:[e[u],t[a]]),u++),a++;return l}function re(e,t,n,o,r,i,c,s={}){let l=e.find(t,n,s);if(r.length===0){l.forEach(w=>e.remove(w)),ne(s,"onRowsApplied",i.path,[]);return}let u=r.length>l.length,a=l[0]||null;if(u&&!a&&(a=Fe(e,t,n,s),!a))throw new $(i.path);let g=l.map(w=>ze(e,w,o,s)),d=null;if(u&&a){d=e.clone(a),s.templateAttr&&e.removeAttr(d,s.templateAttr);let w=e.stripIds(d);w>0&&console.warn(`[hyper-html-api] stripped ${w} id attribute(s) from cloned template at "${i.path.join(".")||"(root)"}"`)}let O=we(r,g,o,qe(e,l,r,i,s)),m=l[0]||a,p=e.parent(m),f=l.length>0?Te(e,p,m):0,h=Ke(e,l),y=new Set,x=[],A=r.map((w,T)=>{let E=O[T];if(E>=0)return y.add(E),x.push(!1),l[E];x.push(!0);let S=e.clone(d);return e.stripIds(S),S});l.forEach((w,T)=>{y.has(T)||e.remove(w)}),h?A.forEach((w,T)=>{let E=f+T;e.children(p).findIndex(Pe=>e.sameNode(Pe,w))!==E&&e.insertAt(p,w,E)}):Ve(e,A,x,p,f),Ue(e,A,o,r,i,c,s),ne(s,"onRowsApplied",i.path,A)}function ne(e,t,n,o){if(typeof e[t]=="function")try{return e[t](n.slice(),o)}catch(r){console.warn(`[hyper-html-api] ${t} threw at "${n.join(".")||"(root)"}"`,r);return}}function qe(e,t,n,o,r){let i=ne(r,"identifyRows",o.path,n);if(!Array.isArray(i))return null;let c=new Array(n.length).fill(-1),s=new Set;for(let l=0;l<n.length;l++)if(i[l]){for(let u=0;u<t.length;u++)if(!(s.has(u)||!e.sameNode(t[u],i[l]))){c[l]=u,s.add(u);break}}return c}function Ue(e,t,n,o,r,i,c){t.forEach((s,l)=>{if(n===null){let u=o[l],a=u==null?"":String(u);e.text(s)!==a&&e.text(s,a)}else{let u=i(e,s,n,o[l],{depth:r.depth+1,path:[...r.path,l]},c);u&&u!==s&&(t[l]=u)}})}function ze(e,t,n,o){return n===null?e.text(t):C(e,t,n,o.onRowsRead?{...o,onRowsRead:void 0}:o)}function Te(e,t,n){let o=e.children(t);for(let r=0;r<o.length;r++)if(e.sameNode(o[r],n))return r;return-1}function Fe(e,t,n,o){if(!o.templateAttr)return null;let r=t;for(;r;){let i=e.find(r,n,{includeRulesTag:!1,templateAttr:null});for(let c of i)if(e.attr(c,o.templateAttr)!=null)return c;r=e.parent(r)}return null}function Ke(e,t){if(t.length<=1)return!0;let n=e.parent(t[0]);if(!n)return!1;let o=e.children(n),r=[];for(let i of t){let c=o.findIndex(s=>e.sameNode(s,i));if(c===-1)return!1;r.push(c)}return r.sort((i,c)=>i-c),r[r.length-1]-r[0]===r.length-1}function Ve(e,t,n,o,r){let i=null,c=r;for(let s=0;s<t.length;s++){if(!n[s]){i=t[s];continue}let l=i?e.parent(i):o;if(!l)continue;let u=i?Te(e,l,i)+1:c++;e.insertAt(l,t[s],u),i=t[s]}}var Ae=new Set(["checked","selected","disabled","readOnly","paused"]);function j(e,t,n,o,r={}){if(Object.prototype.hasOwnProperty.call(r,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");let i=[];if(oe(n,o,[],i),i.length)throw new _(i);J(e,t,n,o,{depth:0,path:[]},r)}function J(e,t,n,o,r,i={}){if(r.depth>I)throw new N(r.path);if(o===void 0)return t;if(typeof n=="string")return Je(e,t,n,o,r,i);if(Array.isArray(n)){let[c,s]=n;return re(e,t,c,s,o,r,J,i),t}if(typeof n=="object"&&n!==null){for(let[c,s]of Object.entries(n)){let l=J(e,t,s,o==null?o:o[c],{depth:r.depth+1,path:[...r.path,c]},i);l&&l!==t&&(t=l)}return t}return t}function Je(e,t,n,o,r,i){if(n.endsWith("[]")){let l=n.slice(0,-2);return re(e,t,l,null,o,r,J,i),t}if(n.startsWith("@"))return Oe(e,t,n.slice(1),o);let c=R(n);if(c!==-1){let l=n.slice(0,c),u=n.slice(c+1),a=l?e.find(t,l,i):[t];return a.length===0||Oe(e,a[0],u,o),t}if(n===".")return xe(e,t,o),t;let s=e.find(t,n,i);return s.length===0||xe(e,s[0],o),t}function xe(e,t,n){let o=n==null?"":String(n);e.text(t)!==o&&e.text(t,o)}function Oe(e,t,n,o){if(G.has(n)){let i=e.prop(t,n);if(i===o||i!=null&&o!=null&&String(i)===String(o))return t;throw new W(n)}if(n==="outerHTML"){let i=o==null?"":String(o);return e.replaceWith(t,i)}if(he.has(n)){let i=Ye(n,o);return e.prop(t,n)!==i&&e.prop(t,n,i),t}let r=o==null?"":String(o);return e.attr(t,n)!==r&&e.attr(t,n,r),t}function Ye(e,t){return t==null?Ae.has(e)?!1:"":Ae.has(e)?t==="false"?!1:!!t:t}function oe(e,t,n,o){if(t!==void 0){if(typeof e=="string"){if(e.endsWith("[]")){Array.isArray(t)?t.forEach((r,i)=>{typeof r=="object"&&r!==null&&o.push({path:H([...n,i]),expected:"scalar",got:v(r)})}):o.push({path:H(n),expected:"array",got:v(t)});return}t!==null&&typeof t=="object"&&o.push({path:H(n),expected:"scalar",got:v(t)});return}if(Array.isArray(e)){if(!Array.isArray(t)){o.push({path:H(n),expected:"array",got:v(t)});return}let r=e[1];t.forEach((i,c)=>oe(r,i,[...n,c],o));return}if(typeof e=="object"&&e!==null){if(t===null||Array.isArray(t)||typeof t!="object"){o.push({path:H(n),expected:"object",got:v(t)});return}for(let[r,i]of Object.entries(e))oe(i,t[r],[...n,r],o)}}}function v(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function H(e){return e.join(".")}function ie(e){try{return JSON.parse(e)}catch(t){throw new L(`Invalid strict JSON: ${t.message}`,t)}}function B(e){try{return JSON.parse(e)}catch{}let t={BRACE_OPEN:"{",BRACE_CLOSE:"}",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",COLON:":",COMMA:",",STRING:"STRING",SELECTOR:"SELECTOR",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",BOOLEAN:"BOOLEAN"};function n(r){let i=[],c=0;for(;c<r.length;){let s=r[c];if(/\s/.test(s)){c++;continue}if("{}".includes(s)){i.push({type:s,value:s}),c++;continue}if(s==="["){let g=!1,d=c+1;for(;d<r.length&&/\s/.test(r[d]);)d++;if(d<r.length&&/[a-zA-Z_]/.test(r[d])&&(g=!0),!g){i.push({type:s,value:s}),c++;continue}}if(s==="]"){i.push({type:s,value:s}),c++;continue}if(s===":"){i.push({type:t.COLON,value:s}),c++;continue}if(s===","){i.push({type:t.COMMA,value:s}),c++;continue}if(s==='"'||s==="'"){let g=s,d=c+1;for(;d<r.length&&r[d]!==g;)r[d]==="\\"&&d++,d++;i.push({type:t.STRING,value:r.substring(c+1,d),quoted:!0,sourceQuote:g}),c=d+1;continue}let l=c,u;for(;l<r.length&&!/[{},]/.test(r[l]);)if(r[l]===":"){let g=[":first",":last",":nth-child",":nth-of-type",":first-child",":last-child",":first-of-type",":last-of-type",":only-child",":only-of-type",":hover",":focus",":active",":visited",":disabled",":enabled",":checked",":empty",":root",":target",":not",":before",":after",":nth-last-child",":nth-last-of-type"],d=!1;for(let O of g){let m=O.substring(1);if(r.substring(l+1,l+1+m.length)===m){d=!0,l+=m.length;break}}if(!d)break}else if(r[l]==="["){for(l++;l<r.length&&r[l]!=="]";){if(r[l]==='"'||r[l]==="'"){let g=r[l];for(l++;l<r.length&&r[l]!==g;)r[l]==="\\"&&l++,l++}l++}l<r.length&&r[l]==="]"&&l++}else l++;u=r.substring(c,l);let a=t.IDENTIFIER;/^-?\d+(\.\d+)?$/.test(u)?a=t.NUMBER:u==="true"||u==="false"||u==="null"?a=t.BOOLEAN:/^[.#@\[]|[.#@\[]| /.test(u)&&(a=t.SELECTOR),i.push({type:a,value:u,quoted:!1}),c=l}return i}function o(r){let i="";for(let c=0;c<r.length;c++){let s=r[c];if("{}".includes(s.type)||"[]".includes(s.type)){i+=s.value;continue}if(s.type===t.COLON){i+=s.value;continue}if(s.type===t.COMMA){let l=r[c+1];if(l&&(l.type==="}"||l.type==="]"))continue;i+=s.value;continue}if(s.type===t.STRING&&s.quoted){let l=s.value;s.sourceQuote==="'"&&(l=l.replace(/\\'/g,"'"),l=l.replace(/(\\*)"/g,(u,a)=>a.length%2===0?a+'\\"':u)),i+=`"${l}"`;continue}if(s.type===t.NUMBER||s.type===t.BOOLEAN){i+=s.value;continue}if(s.type===t.SELECTOR||s.type===t.IDENTIFIER){i+=`"${s.value}"`;continue}i+=`"${s.value}"`}return i}try{let r=n(e),i=o(r);return JSON.parse(i)}catch(r){throw new L("Invalid extraction rules syntax: "+r.message,r)}}var Xe="1",be=/^[a-zA-Z0-9_-]+$/;function P(e,t,n){let o;if(n===void 0)o="script[data-rules-name]";else{if(typeof n!="string"||!be.test(n))throw new Error(`hyper-html-api: invalid rules token ${JSON.stringify(n)} (must match ${be})`);o=`script[data-rules-name~="${n}"]`}let r=e.find(t,o,{includeRulesTag:!0});if(r.length===0)return null;n!==void 0&&r.length>1&&console.warn(`hyper-html-api: ${r.length} rules tags match data-rules-name~="${n}"; using the first.`);let i=r[0],c=e.attr(i,"data-rules-version");if(c!==Xe)throw new D(c);return{rules:B(e.text(i)),tagNode:i}}var Se=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),Ge=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),Re=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui"]);function se(e,t){if(!e||e.nodeType!==1)return!1;let n=e.getAttribute?.("clay");return!!(n&&n.split(/\s+/).includes(t)||e.hasAttribute?.(t))}function Ze(e,t){if(se(e,t))return!0;for(let[n,o]of Object.entries(Ge))if(o.includes(t)&&se(e,n))return!0;return!1}function q(e){let t=Se[e];if(!t)throw new Error(`Unknown region capability: ${e}`);return[...t.tokens,...t.bundles].flatMap(n=>[`[clay~="${n}"]`,`[${n}]`]).join(", ")}function Qe(e,t){let n=e&&e.nodeType===1?e:e?.parentElement;for(;n&&n.nodeType===1;){let o=Se[t];if(!o)throw new Error(`Unknown region capability: ${t}`);if(o.tokens.some(r=>Ze(n,r))||o.bundles.some(r=>se(n,r)))return n;n=n.parentElement}return null}function Ce(e,t){return!!Qe(e,t)}var et=Object.freeze({refusedRuleForms:["innerHTML","outerHTML"],refusedTargets:["script","style","template","noscript","iframe","object","embed","xmp","plaintext","noembed","noframes","meta","link","base","animate","set","animatemotion","animatetransform"],refusedAttributes:["style","srcdoc","is","http-equiv","sandbox","allow","nonce","integrity","charset","htmlclaytoken","htmlclayid","data-rules-name","data-rules-version","clay","contenteditable",...Re],refusedAttributePrefixes:["on"],urlAttributes:["href","src","srcset","action","formaction","poster","cite","data","ping","background","longdesc","usemap","xlink:href","manifest","codebase","icon"],refusedSchemes:["javascript","vbscript","data"]});function le(e,t,n){if(n&&typeof n=="object")return{rules:n,tagNode:null};if(typeof n=="string"){let o=t&&t.ownerDocument?t.ownerDocument:t;return P(e,o,n)}return null}var nt=/:(?:focus(?:-within|-visible)?|hover|active|visited|defined)\b/i;function Ne(e,t){if(!/^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(e.tagName||""))return;let n=(e.getAttribute?.("type")||"").toLowerCase();if("value"in e&&"value"in t&&e.tagName!=="OPTION"&&n!=="checkbox"&&n!=="radio"&&(t.value=e.value),"checked"in e&&"checked"in t&&(t.checked=e.checked),"selected"in e&&"selected"in t&&(t.selected=e.selected),e.tagName==="SELECT")for(let o=0;o<e.options.length;o++)t.options[o].selected=e.options[o].selected;"indeterminate"in e&&"indeterminate"in t&&(t.indeterminate=e.indeterminate)}function Me(e,t,n,o){if(o)return!!e.closest?.(t);let r=e;for(;r?.nodeType===1;){if(r.matches(t))return!0;if(r===n)break;r=r.parentElement}return!1}function Le(e,t,n,o,r,i,c,s){if(e.nodeType===1&&((c?Ce(e,n):Me(e,o,i,!1))||r&&Me(e,r,i,c)))return null;let l=t.importNode(e,!1);s.cloneToLive.set(l,e),s.liveToClone.set(e,l);let u=e.nodeType===1&&e.tagName==="TEMPLATE"?e.content:e,a=l.nodeType===1&&l.tagName==="TEMPLATE"?l.content:l;u!==e&&(s.cloneToLive.set(a,u),s.liveToClone.set(u,a));for(let g of u.childNodes||[]){let d=Le(g,t,n,o,r,i,c,s);d&&(a.appendChild(d),g.nodeType===1&&Ne(g,d))}return e.nodeType===1&&Ne(e,l),l}function U(e,{capability:t="data",exclude:n=null,inherit:o=!0}={}){if(!e)throw new TypeError("createContentView requires a DOM context");let r=e.nodeType===9?e:e.ownerDocument;if(!r?.implementation?.createHTMLDocument)throw new TypeError("createContentView requires an HTML DOM implementation");let i=r.implementation.createHTMLDocument(""),c=new WeakMap,s=new WeakMap,l=e.nodeType===9?e.documentElement:e;n&&i.documentElement.matches(n);let u=q(t),a=Le(l,i,t,u,n,l,o,{cloneToLive:c,liveToClone:s});e.nodeType===9&&a&&(i.replaceChild(a,i.documentElement),s.set(e,i),c.set(i,e));let g=d=>{if(nt.test(d))throw new Error(`Filtered content queries do not support stateful selector: ${d}`)};return{root:a,document:i,capability:t,selector:q(t),cloneToLive:c,liveToClone:s,original(d){return c.get(d)||null},cloneOf(d){return s.get(d)||null},query(d,O=a){return g(d),Array.from(O.querySelectorAll(d),m=>c.get(m)||m)},text(d=a){return(d===a?a:s.get(d))?.textContent||""},html(d=a){return(d===a?a:s.get(d))?.innerHTML??""},clone(d=a){let O=d===a?a:s.get(d);return O?i.importNode(O,!0):null}}}function Ie(e){return e&&e.nodeType===1&&e.tagName==="SCRIPT"&&e.hasAttribute&&e.hasAttribute("data-rules-name")}function rt(e){return e?(e.nodeType===9||e.nodeType===11,e):null}var b={semanticExclude:!0,find(e,t,n={}){let o=rt(e);if(!o||!o.querySelectorAll)return[];let r=Array.from(o.querySelectorAll(t));n.includeRulesTag||(r=r.filter(s=>!Ie(s)));let i=[];n.skip&&i.push(n.skip);let c=n.templateAttr===null?null:n.templateAttr||"cms-template";if(c&&i.push("["+c+"]"),i.length){let s=i.join(", ");r=r.filter(l=>!l.closest||!l.closest(s))}return r},parent(e){return e?e.parentElement:null},children(e){return e?Array.from(e.children):[]},text(e,t){if(t===void 0)return(e.textContent||"").trim();e.textContent=t},attr(e,t,n){if(n===void 0)return e.hasAttribute&&e.hasAttribute(t)?e.getAttribute(t):null;e.setAttribute(t,n)},removeAttr(e,t){e&&e.removeAttribute&&e.removeAttribute(t)},prop(e,t,n){if(n===void 0){let o=e?e[t]:void 0;return o!==void 0?o:null}e[t]=n},clone(e){return e.cloneNode(!0)},insertAt(e,t,n){let o=e.children[n]||null;e.insertBefore(t,o)},remove(e){e&&e.parentNode&&e.parentNode.removeChild(e)},replaceWith(e,t){if(!e||!e.parentNode)throw new Error("dom.replaceWith: node has no parent");let o=e.ownerDocument.createElement("template");o.innerHTML=t;let r=o.content.firstElementChild;if(!r)throw new Error("dom.replaceWith: html did not parse to an element");return e.parentNode.replaceChild(r,e),r},stripIds(e){let t=0;return e.id&&(e.removeAttribute("id"),t++),(e.querySelectorAll?e.querySelectorAll("[id]"):[]).forEach(o=>{o.removeAttribute("id"),t++}),t},sameNode(e,t){return e===t}};function M(e,t={}){if(t.exclude===null)return b;let n=[q("data"),t.exclude].filter(Boolean).join(", "),o=e.nodeType===9?e:e.ownerDocument||e,r=e.nodeType===9?e.documentElement:e;if(!t._write&&!r?.matches?.(n)&&!r?.querySelector?.(n)&&!o?.querySelector?.(n))return b;let i=e.nodeType===9||!e.isConnected?e:e.ownerDocument,c=e.nodeType===9?e:e.ownerDocument,s=null,l=()=>s||(s=U(i,{capability:"data",exclude:t.exclude||null})),u=m=>{let p=l();return m===e?p.cloneOf(e):p.cloneOf(m)||m},a=m=>s?.original(m)||m,g=(m,p)=>{l().liveToClone.set(m,p),l().cloneToLive.set(p,m);let f=m.childNodes||[],h=p.childNodes||[];for(let y=0;y<Math.min(f.length,h.length);y++)g(f[y],h[y])},d=(m,p,f,h)=>{let y=Array.from(m.childNodes).filter(E=>s.cloneOf(E)),A=y[0];for(;A&&y.includes(A);)A=A.nextSibling;for(let E of y)E.remove();if(f==="innerHTML"){let E=c.createElement("template");E.innerHTML=h;for(let S of Array.from(E.content.childNodes))m.insertBefore(S,A||null)}else m.insertBefore(c.createTextNode(h),A||null);let w=U(m,{capability:"data",exclude:t.exclude||null});p.replaceChildren(...Array.from(w.root?.childNodes||[]));let T=E=>{let S=w.original(E);S&&(s.liveToClone.set(S,E),s.cloneToLive.set(E,S));for(let ae of Array.from(E.childNodes||[]))T(ae)};for(let E of Array.from(p.childNodes))T(E)},O={...b,find(m,p,f={}){let h=u(m);if(!h?.querySelectorAll)return[];let y=l().query(p,h);f.includeRulesTag||(y=y.filter(w=>!Ie(w)));let x=[];f.skip&&x.push(f.skip);let A=f.templateAttr===null?null:f.templateAttr||"cms-template";if(A&&x.push(`[${A}]`),x.length){let w=x.join(", ");y=y.filter(T=>!T.closest?.(w))}return y},parent(m){let p=u(m)?.parentElement;return p?a(p):null},children(m){return Array.from(u(m)?.children||[],a)},text(m,p){if(p===void 0){let y=a(m);return!y?.matches?.(n)&&!y?.querySelector?.(n)?b.text(y):(u(m)?.textContent||"").trim()}let f=a(m);if(!f?.matches?.(n)&&!f?.querySelector?.(n)&&!s){b.text(f,p);return}let h=l().cloneOf(f);h?d(f,h,"textContent",p):b.text(f,p)},attr(m,p,f){let h=a(m);if(f===void 0)return b.attr(h,p);b.attr(h,p,f);let y=s?.cloneOf(h);y&&(b.attr(y,p,f),U(h,{capability:"data",exclude:t.exclude||null}).root===null&&(y.remove(),s.liveToClone.delete(h),s.cloneToLive.delete(y)))},removeAttr(m,p){let f=a(m);b.removeAttr(f,p);let h=s?.cloneOf(f);h&&b.removeAttr(h,p)},prop(m,p,f){let h=a(m);if(f===void 0)return p==="innerHTML"||p==="outerHTML"||p==="textContent"||p==="innerText"?b.prop(u(h),p):b.prop(h,p);let y=p==="innerHTML"||p==="textContent"||p==="innerText",x=y?l().cloneOf(h):s?.cloneOf(h);x&&y?d(h,x,p,f):(b.prop(h,p,f),x&&b.prop(x,p,f))},clone(m){let p=u(m);return p===m?b.clone(m):c.importNode(p,!0)},insertAt(m,p,f){let h=a(m),x=O.children(h)[f]||(()=>{for(let T=h.children.length-1;T>=0;T--){let E=h.children[T];if(l().cloneOf(E))return E.nextElementSibling}return h.firstElementChild})(),A=a(p);h.insertBefore(A,x||null);let w=l().cloneOf(h);if(w){let T=l().cloneOf(A);T||(T=c.importNode(A,!0),g(A,T));let E=Array.from(w.children);w.insertBefore(T,E[f]||null)}},remove(m){let p=a(m),f=l().cloneOf(p);b.remove(p),f&&b.remove(f)},replaceWith(m,p){let f=a(m),h=l().cloneOf(f),y=b.replaceWith(f,p);if(h){let x=U(y,{capability:"data",exclude:t.exclude||null});if(!x.root)h.remove();else{h.replaceWith(x.root);let A=w=>{let T=x.original(w);T&&(s.liveToClone.set(T,w),s.cloneToLive.set(w,T));for(let E of Array.from(w.childNodes||[]))A(E)};A(x.root)}}return y}};return O}var k=b;var z={extract:(e,t,n={})=>C(M(e,n),e,t,n),apply:(e,t,n,o={})=>j(M(e,{...o,_write:!0}),e,t,n,o),findRulesIn:(e,t)=>P(k,e,t),findRules:(e,t)=>le(k,e,t),bind:(e,t,n={})=>{let o=le(k,e,t);if(!o){let r=typeof t=="string"?`data-rules-name~="${t}"`:"the provided rules object";throw new Error(`hyper-html-api: could not resolve rules for ${r}`)}return{...o,get:()=>C(M(e,n),e,o.rules,n),set:r=>j(M(e,{...n,_write:!0}),e,o.rules,r,n)}},parseStrict:ie,parseRelaxed:B,ruleAttrIndex:R,splitRule:ee,errors:V,DOM_PROPERTIES:F},ce=e=>!!e&&typeof e.nodeType=="number";function je(e){let t=e&&e.ownerDocument?e.ownerDocument:e,n=k.find(t,"script[data-rules-name]",{includeRulesTag:!0});if(n.length===0)throw new Error('hyper-html-api: no rules tag found. Add <script type="application/json" data-rules-name="\u2026" data-rules-version="1"> or pass rules.');if(n.length>1)throw new Error('hyper-html-api: multiple rules tags found; pass a name, e.g. extractData("api").');return P(k,t).rules}function fe(e,t){let n=ce(e)?e:document,o=ce(e)?t:e;return o===void 0?C(M(n),n,je(n)):z.bind(n,o).get()}function ue(e,t,n){if(!ce(e))throw new Error("hyper-html-api: applyData(root, data, source?) needs a DOM root as the first argument.");return n===void 0?j(M(e),e,je(e),t):z.bind(e,n).set(t),e}var ot={engine:z,extractData:fe,applyData:ue},it=ot;return We(st);})();
5
+ var hyperHtmlApiData=(()=>{var Q=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var Ve=Object.prototype.hasOwnProperty;var Ee=(e,t)=>{for(var n in t)Q(e,n,{get:t[n],enumerable:!0})},Je=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Fe(t))!Ve.call(e,r)&&r!==n&&Q(e,r,{get:()=>t[r],enumerable:!(o=Ke(t,r))||o.enumerable});return e};var Ye=e=>Je(Q({},"__esModule",{value:!0}),e);var Mt={};Ee(Mt,{applyData:()=>ge,default:()=>Nt,engine:()=>Y,extractData:()=>ye});var G=["textContent","innerText","innerHTML","outerHTML","value","checked","selected","disabled","readOnly","type","tagName","nodeName","nodeType","nodeValue","childElementCount","id","className","classList","baseURI","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","dataset","currentSrc","duration","paused","title","documentURI","contentType"],ee=new Set(G),Te=new Set(["textContent","innerText","innerHTML","value","checked","selected","disabled","readOnly","type","id","className","title"]),_=new Set(["tagName","nodeName","nodeType","nodeValue","childElementCount","classList","baseURI","documentURI","contentType","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","currentSrc","duration","paused","dataset"]);var R={};Ee(R,{EmptyListInsert:()=>v,MAX_RULE_DEPTH:()=>j,MaxRuleDepthExceeded:()=>I,NoRulesTag:()=>te,RuleTargetReadOnly:()=>H,RulesParseError:()=>P,ShapeMismatch:()=>W,UnknownRulesVersion:()=>$,WriteRefused:()=>q,WriteRejected:()=>ne});var P=class extends Error{constructor(t,n){super(t),this.name="RulesParseError",this.cause=n}},$=class extends Error{constructor(t){super(`unknown rules version: ${t}. Library supports "1".`),this.name="UnknownRulesVersion",this.version=t}},j=20,I=class extends Error{constructor(t){super(`rule depth exceeded ${j} at path: ${t.join(".")}`),this.name="MaxRuleDepthExceeded",this.path=t}},W=class extends Error{constructor(t){super(`shape mismatch: ${t.length} field(s) failed validation`),this.name="ShapeMismatch",this.mismatches=t}},v=class extends Error{constructor(t){super(`cannot add items to empty list at "${t.join(".")}" \u2014 no sibling to clone as template. Seed the list with a hidden item first.`),this.name="EmptyListInsert",this.path=t}},H=class extends Error{constructor(t){super(`cannot write to read-only DOM property "${t}"`),this.name="RuleTargetReadOnly",this.target=t}},q=class extends Error{constructor(t){super(`write refused: ${t.length} write(s) broke the content-only policy`),this.name="WriteRefused",this.refusals=t}},te=class extends Error{constructor(t){super(`no <script data-rules-name~="${t}"> rules tag in this document`),this.name="NoRulesTag",this.token=t}},ne=class extends Error{constructor(t,n){super(`write rejected: ${t.length} unknown key(s), ${n.length} rule(s) with no matching element`),this.name="WriteRejected",this.unknownKeys=t,this.unmatched=n}};function S(e){let t=0,n=null,o=-1;for(let r=0;r<e.length;r++){let s=e[r];s==="\\"?r++:n?s===n&&(n=null):s==='"'||s==="'"?n=s:s==="["||s==="("?t++:s==="]"||s===")"?t>0&&t--:s==="@"&&t===0&&(o=r)}return o}function re(e){let t=S(e);return t===-1?{selector:e,prop:null}:{selector:e.slice(0,t),prop:e.slice(t+1)||null}}function M(e,t,n,o={}){if(Object.prototype.hasOwnProperty.call(o,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");return oe(e,t,n,{depth:0,path:[]},o)}function oe(e,t,n,o,r){if(o.depth>j)throw new I(o.path);if(typeof n=="string")return Ge(e,t,n,o,r);if(Array.isArray(n)){let[s,l]=n,c=e.find(t,s,r);return Oe(r,o,c),c.map((i,f)=>oe(e,i,l,{depth:o.depth+1,path:[...o.path,f]},r))}if(typeof n=="object"&&n!==null){let s={};for(let[l,c]of Object.entries(n))s[l]=oe(e,t,c,{depth:o.depth+1,path:[...o.path,l]},r);return s}return null}function Ge(e,t,n,o,r){if(n.endsWith("[]")){let c=n.slice(0,-2),i=e.find(t,c,r);return Oe(r,o,i),i.map(f=>e.text(f))}if(n.startsWith("@"))return Ae(e,t,n.slice(1));let s=S(n);if(s!==-1){let c=n.slice(0,s),i=n.slice(s+1),f=c?e.find(t,c,r):[t];return f.length===0?null:Ae(e,f[0],i)}if(n===".")return e.text(t);let l=e.find(t,n,r);return l.length===0?null:e.text(l[0])}function Oe(e,t,n){if(typeof e.onRowsRead=="function")try{e.onRowsRead(t.path.slice(),n)}catch(o){console.warn(`[hyper-html-api] onRowsRead threw at "${t.path.join(".")||"(root)"}"`,o)}}function Ae(e,t,n){if(ee.has(n)){let r=e.prop(t,n);return r==null?null:String(r)}let o=e.attr(t,n);return o||null}function Se(e,t,n,o){let r=e.length,s=t.length,l=new Array(r).fill(-1);if(o){let a=new Set;for(let m=0;m<r;m++){let g=o[m];!(g>=0&&g<s)||a.has(g)||(l[m]=g,a.add(g))}}if(r===0||s===0)return l;let c=e.map(a=>xe(a,n)),i=t.map(a=>xe(a,n)),f=new Array(s).fill(!1);for(let a of l)a>=0&&(f[a]=!0);let u=new Map;i.forEach((a,m)=>{f[m]||u.set(a,u.has(a)?-1:m)});let p=new Map;c.forEach((a,m)=>{l[m]>=0||p.set(a,(p.get(a)||0)+1)}),c.forEach((a,m)=>{if(l[m]>=0||p.get(a)!==1)return;let g=u.get(a);g===void 0||g===-1||f[g]||(l[m]=g,f[g]=!0)});let d=[];for(let a=0;a<r;a++)l[a]<0&&d.push(a);let w=[];for(let a=0;a<s;a++)f[a]||w.push(a);if(d.length===0||w.length===0)return l;let h=r*s+1,y=(a,m)=>Xe(e[a],t[m],n)*h+Math.abs(a-m);for(let[a,m]of Ze(d,w,y))l[a]=m;return l}var Re=e=>typeof e=="object"&&e!==null;function xe(e,t){if(!Re(t))return e==null?" null":String(e);let n=Object.keys(t);return JSON.stringify(n.map(o=>{let r=JSON.stringify(e?.[o]);return r===void 0?" undef":r}))}function Xe(e,t,n){if(!Re(n))return e===t?0:1;let o=Object.keys(n);if(o.length===0)return 0;let r=0;for(let s of o){let l=JSON.stringify(e?.[s]),c=JSON.stringify(t?.[s]);l!==c&&r++}return r}function Ze(e,t,n){return e.length<=t.length?be(e,t,n,!1):be(t,e,(o,r)=>n(r,o),!0)}function be(e,t,n,o){let r=e.length,s=t.length,l=[];for(let p=0;p<=r;p++)l.push(new Float64Array(s+1).fill(1/0));let c=[];for(let p=0;p<=r;p++)c.push(new Uint8Array(s+1));for(let p=0;p<=s;p++)l[r][p]=0;for(let p=r-1;p>=0;p--)for(let d=s-1;d>=0;d--){let w=n(e[p],t[d])+l[p+1][d+1],h=l[p][d+1];w<=h?(l[p][d]=w,c[p][d]=1):l[p][d]=h}let i=[],f=0,u=0;for(;f<r&&u<s;)c[f][u]&&(i.push(o?[t[u],e[f]]:[e[f],t[u]]),f++),u++;return i}function se(e,t,n,o,r,s,l,c={}){let i=e.find(t,n,c);if(r.length===0){i.forEach(E=>e.remove(E)),ie(c,"onRowsApplied",s.path,[]);return}let f=r.length>i.length,u=i[0]||null;if(f&&!u&&(u=nt(e,t,n,c),!u))throw new v(s.path);let p=i.map(E=>tt(e,E,o,c)),d=null;if(f&&u){d=e.clone(u),c.templateAttr&&e.removeAttr(d,c.templateAttr);let E=e.stripIds(d);E>0&&console.warn(`[hyper-html-api] stripped ${E} id attribute(s) from cloned template at "${s.path.join(".")||"(root)"}"`)}let w=Se(r,p,o,Qe(e,i,r,s,c)),h=i[0]||u,y=e.parent(h),a=i.length>0?Ne(e,y,h):0,m=rt(e,i),g=new Set,x=[],O=r.map((E,A)=>{let T=w[A];if(T>=0)return g.add(T),x.push(!1),i[T];x.push(!0);let N=e.clone(d);return e.stripIds(N),N});i.forEach((E,A)=>{g.has(A)||e.remove(E)}),m?O.forEach((E,A)=>{let T=a+A;e.children(y).findIndex(ze=>e.sameNode(ze,E))!==T&&e.insertAt(y,E,T)}):ot(e,O,x,y,a),et(e,O,o,r,s,l,c),ie(c,"onRowsApplied",s.path,O)}function ie(e,t,n,o){if(typeof e[t]=="function")try{return e[t](n.slice(),o)}catch(r){console.warn(`[hyper-html-api] ${t} threw at "${n.join(".")||"(root)"}"`,r);return}}function Qe(e,t,n,o,r){let s=ie(r,"identifyRows",o.path,n);if(!Array.isArray(s))return null;let l=new Array(n.length).fill(-1),c=new Set;for(let i=0;i<n.length;i++)if(s[i]){for(let f=0;f<t.length;f++)if(!(c.has(f)||!e.sameNode(t[f],s[i]))){l[i]=f,c.add(f);break}}return l}function et(e,t,n,o,r,s,l){t.forEach((c,i)=>{if(n===null){let f=o[i],u=f==null?"":String(f);e.text(c)!==u&&e.text(c,u)}else{let f=s(e,c,n,o[i],{depth:r.depth+1,path:[...r.path,i]},l);f&&f!==c&&(t[i]=f)}})}function tt(e,t,n,o){return n===null?e.text(t):M(e,t,n,o.onRowsRead?{...o,onRowsRead:void 0}:o)}function Ne(e,t,n){let o=e.children(t);for(let r=0;r<o.length;r++)if(e.sameNode(o[r],n))return r;return-1}function nt(e,t,n,o){if(!o.templateAttr)return null;let r=t;for(;r;){let s=e.find(r,n,{includeRulesTag:!1,templateAttr:null});for(let l of s)if(e.attr(l,o.templateAttr)!=null)return l;r=e.parent(r)}return null}function rt(e,t){if(t.length<=1)return!0;let n=e.parent(t[0]);if(!n)return!1;let o=e.children(n),r=[];for(let s of t){let l=o.findIndex(c=>e.sameNode(c,s));if(l===-1)return!1;r.push(l)}return r.sort((s,l)=>s-l),r[r.length-1]-r[0]===r.length-1}function ot(e,t,n,o,r){let s=null,l=r;for(let c=0;c<t.length;c++){if(!n[c]){s=t[c];continue}let i=s?e.parent(s):o;if(!i)continue;let f=s?Ne(e,i,s)+1:l++;e.insertAt(i,t[c],f),s=t[c]}}var Me=new Set(["checked","selected","disabled","readOnly","paused"]);function L(e,t,n,o,r={}){if(Object.prototype.hasOwnProperty.call(r,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");let s=[];if(ce(n,o,[],s),s.length)throw new W(s);X(e,t,n,o,{depth:0,path:[]},r)}function X(e,t,n,o,r,s={}){if(r.depth>j)throw new I(r.path);if(o===void 0)return t;if(typeof n=="string")return it(e,t,n,o,r,s);if(Array.isArray(n)){let[l,c]=n;return se(e,t,l,c,o,r,X,s),t}if(typeof n=="object"&&n!==null){for(let[l,c]of Object.entries(n)){let i=X(e,t,c,o==null?o:o[l],{depth:r.depth+1,path:[...r.path,l]},s);i&&i!==t&&(t=i)}return t}return t}function it(e,t,n,o,r,s){if(n.endsWith("[]")){let i=n.slice(0,-2);return se(e,t,i,null,o,r,X,s),t}if(n.startsWith("@"))return Ie(e,t,n.slice(1),o);let l=S(n);if(l!==-1){let i=n.slice(0,l),f=n.slice(l+1),u=i?e.find(t,i,s):[t];return u.length===0||Ie(e,u[0],f,o),t}if(n===".")return Ce(e,t,o),t;let c=e.find(t,n,s);return c.length===0||Ce(e,c[0],o),t}function Ce(e,t,n){let o=n==null?"":String(n);e.text(t)!==o&&e.text(t,o)}function Ie(e,t,n,o){if(_.has(n)){let s=e.prop(t,n);if(s===o||s!=null&&o!=null&&String(s)===String(o))return t;throw new H(n)}if(n==="outerHTML"){let s=o==null?"":String(o);return e.replaceWith(t,s)}if(Te.has(n)){let s=st(n,o);return e.prop(t,n)!==s&&e.prop(t,n,s),t}let r=o==null?"":String(o);return e.attr(t,n)!==r&&e.attr(t,n,r),t}function st(e,t){return t==null?Me.has(e)?!1:"":Me.has(e)?t==="false"?!1:!!t:t}function ce(e,t,n,o){if(t!==void 0){if(typeof e=="string"){if(e.endsWith("[]")){Array.isArray(t)?t.forEach((r,s)=>{typeof r=="object"&&r!==null&&o.push({path:U([...n,s]),expected:"scalar",got:B(r)})}):o.push({path:U(n),expected:"array",got:B(t)});return}t!==null&&typeof t=="object"&&o.push({path:U(n),expected:"scalar",got:B(t)});return}if(Array.isArray(e)){if(!Array.isArray(t)){o.push({path:U(n),expected:"array",got:B(t)});return}let r=e[1];t.forEach((s,l)=>ce(r,s,[...n,l],o));return}if(typeof e=="object"&&e!==null){if(t===null||Array.isArray(t)||typeof t!="object"){o.push({path:U(n),expected:"object",got:B(t)});return}for(let[r,s]of Object.entries(e))ce(s,t[r],[...n,r],o)}}}function B(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function U(e){return e.join(".")}function le(e){try{return JSON.parse(e)}catch(t){throw new P(`Invalid strict JSON: ${t.message}`,t)}}function z(e){try{return JSON.parse(e)}catch{}let t={BRACE_OPEN:"{",BRACE_CLOSE:"}",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",COLON:":",COMMA:",",STRING:"STRING",SELECTOR:"SELECTOR",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",BOOLEAN:"BOOLEAN"};function n(r){let s=[],l=0;for(;l<r.length;){let c=r[l];if(/\s/.test(c)){l++;continue}if("{}".includes(c)){s.push({type:c,value:c}),l++;continue}if(c==="["){let p=!1,d=l+1;for(;d<r.length&&/\s/.test(r[d]);)d++;if(d<r.length&&/[a-zA-Z_]/.test(r[d])&&(p=!0),!p){s.push({type:c,value:c}),l++;continue}}if(c==="]"){s.push({type:c,value:c}),l++;continue}if(c===":"){s.push({type:t.COLON,value:c}),l++;continue}if(c===","){s.push({type:t.COMMA,value:c}),l++;continue}if(c==='"'||c==="'"){let p=c,d=l+1;for(;d<r.length&&r[d]!==p;)r[d]==="\\"&&d++,d++;s.push({type:t.STRING,value:r.substring(l+1,d),quoted:!0,sourceQuote:p}),l=d+1;continue}let i=l,f;for(;i<r.length&&!/[{},]/.test(r[i]);)if(r[i]===":"){let p=[":first",":last",":nth-child",":nth-of-type",":first-child",":last-child",":first-of-type",":last-of-type",":only-child",":only-of-type",":hover",":focus",":active",":visited",":disabled",":enabled",":checked",":empty",":root",":target",":not",":before",":after",":nth-last-child",":nth-last-of-type"],d=!1;for(let w of p){let h=w.substring(1);if(r.substring(i+1,i+1+h.length)===h){d=!0,i+=h.length;break}}if(!d)break}else if(r[i]==="["){for(i++;i<r.length&&r[i]!=="]";){if(r[i]==='"'||r[i]==="'"){let p=r[i];for(i++;i<r.length&&r[i]!==p;)r[i]==="\\"&&i++,i++}i++}i<r.length&&r[i]==="]"&&i++}else i++;f=r.substring(l,i);let u=t.IDENTIFIER;/^-?\d+(\.\d+)?$/.test(f)?u=t.NUMBER:f==="true"||f==="false"||f==="null"?u=t.BOOLEAN:/^[.#@\[]|[.#@\[]| /.test(f)&&(u=t.SELECTOR),s.push({type:u,value:f,quoted:!1}),l=i}return s}function o(r){let s="";for(let l=0;l<r.length;l++){let c=r[l];if("{}".includes(c.type)||"[]".includes(c.type)){s+=c.value;continue}if(c.type===t.COLON){s+=c.value;continue}if(c.type===t.COMMA){let i=r[l+1];if(i&&(i.type==="}"||i.type==="]"))continue;s+=c.value;continue}if(c.type===t.STRING&&c.quoted){let i=c.value;c.sourceQuote==="'"&&(i=i.replace(/\\'/g,"'"),i=i.replace(/(\\*)"/g,(f,u)=>u.length%2===0?u+'\\"':f)),s+=`"${i}"`;continue}if(c.type===t.NUMBER||c.type===t.BOOLEAN){s+=c.value;continue}if(c.type===t.SELECTOR||c.type===t.IDENTIFIER){s+=`"${c.value}"`;continue}s+=`"${c.value}"`}return s}try{let r=n(e),s=o(r);return JSON.parse(s)}catch(r){throw new P("Invalid extraction rules syntax: "+r.message,r)}}var ct="1",Le=/^[a-zA-Z0-9_-]+$/;function k(e,t,n){let o;if(n===void 0)o="script[data-rules-name]";else{if(typeof n!="string"||!Le.test(n))throw new Error(`hyper-html-api: invalid rules token ${JSON.stringify(n)} (must match ${Le})`);o=`script[data-rules-name~="${n}"]`}let r=e.find(t,o,{includeRulesTag:!0});if(r.length===0)return null;n!==void 0&&r.length>1&&console.warn(`hyper-html-api: ${r.length} rules tags match data-rules-name~="${n}"; using the first.`);let s=r[0],l=e.attr(s,"data-rules-version");if(l!==ct)throw new $(l);return{rules:z(e.text(s)),tagNode:s}}var Pe=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),lt=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),je=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui"]);function fe(e,t){if(!e||e.nodeType!==1)return!1;let n=e.getAttribute?.("clay");return!!(n&&n.split(/\s+/).includes(t)||e.hasAttribute?.(t))}function ft(e,t){if(fe(e,t))return!0;for(let[n,o]of Object.entries(lt))if(o.includes(t)&&fe(e,n))return!0;return!1}function K(e){let t=Pe[e];if(!t)throw new Error(`Unknown region capability: ${e}`);return[...t.tokens,...t.bundles].flatMap(n=>[`[clay~="${n}"]`,`[${n}]`]).join(", ")}function ut(e,t){let n=e&&e.nodeType===1?e:e?.parentElement;for(;n&&n.nodeType===1;){let o=Pe[t];if(!o)throw new Error(`Unknown region capability: ${t}`);if(o.tokens.some(r=>ft(n,r))||o.bundles.some(r=>fe(n,r)))return n;n=n.parentElement}return null}function ke(e,t){return!!ut(e,t)}var ue=Object.freeze({refusedRuleForms:["innerHTML","outerHTML"],refusedTargets:["script","style","template","noscript","iframe","object","embed","xmp","plaintext","noembed","noframes","meta","link","base","animate","set","animatemotion","animatetransform"],refusedAttributes:["style","srcdoc","is","http-equiv","sandbox","allow","nonce","integrity","charset","htmlclaytoken","htmlclayid","data-rules-name","data-rules-version","clay","contenteditable",...je],refusedAttributePrefixes:["on"],urlAttributes:["href","src","srcset","action","formaction","poster","cite","data","ping","background","longdesc","usemap","xlink:href","manifest","codebase","icon"],refusedSchemes:["javascript","vbscript","data"]}),at=new Set(["textContent","innerText"]);function De(e){let n=String(e).replace(/^[\u0000- ]+|[\u0000- ]+$/g,"").replace(/[\t\n\r]/g,"").match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);return n?n[1].toLowerCase():null}var dt=/^[^\t\n\f\r "'>/=\u0000-\u001f\u007f]+$/;function _e(e,t,n=ue){if(!dt.test(String(e)))return`attribute name ${JSON.stringify(String(e))} is not valid`;let o=String(e).toLowerCase();if(n.refusedAttributePrefixes.some(r=>o.startsWith(r)))return`attribute "${o}" can run script`;if(n.refusedAttributes.includes(o))return`attribute "${o}" is not content`;if(n.urlAttributes.includes(o)&&t!=null){let r=o==="srcset"?String(t).split(",").map(s=>s.trim().split(/\s+/)[0]).filter(Boolean):[String(t)];for(let s of r){let l=De(s);if(l&&n.refusedSchemes.includes(l))return`"${l}:" URLs are not allowed in "${o}"`}}return null}function ae(e,t){let n=e.prop(t,"tagName");return n?String(n).toLowerCase():""}function ht(e,t){let n=ae(e,t)||"node",o=e.attr(t,"id");return o?`<${n}#${o}>`:`<${n}>`}function pt(e,t,n){let o=t;for(;o;){let r=ae(e,o);if(r&&n.refusedTargets.includes(r))return r;o=e.parent(o)}return null}function $e(e,t){return e.find(t,"script[data-rules-name]",{includeRulesTag:!0,templateAttr:null}).length>0}function mt(e,t){return ae(e,t)==="script"&&e.attr(t,"data-rules-name")!=null?!0:$e(e,t)}function Z(e,t=ue){let n=[],o=(i,f)=>(n.push({target:ht(e,i),reason:f}),!1),r=i=>{let f=pt(e,i,t);return f?o(i,`inside <${f}>, which is not content`):!0},s=i=>r(i)?$e(e,i)?o(i,"a text write here would delete the data rules tag"):!0:!1,l=(i,f,u)=>{if(!r(i))return!1;let p=_e(f,u,t);return p?o(i,p):!0};return{...e,text(i,f){if(f===void 0)return e.text(i);s(i)&&e.text(i,f)},attr(i,f,u){if(u===void 0)return e.attr(i,f);l(i,f,u)&&e.attr(i,f,u)},prop(i,f,u){if(u===void 0)return e.prop(i,f);if(t.refusedRuleForms.includes(f))return o(i,`"@${f}" writes HTML, only text is allowed`);if(at.has(f)){s(i)&&e.prop(i,f,u);return}l(i,f==="className"?"class":f,u)&&e.prop(i,f,u)},remove(i){if(mt(e,i)){o(i,"removing this would delete the data rules tag");return}e.remove(i)},replaceWith(i,f){return f===e.prop(i,"outerHTML")||o(i,'"@outerHTML" writes HTML, only text is allowed'),i},refusals:n,assertClean(){if(n.length)throw new q(n.slice())}}}function F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function We(e){return e.reduce((t,n)=>typeof n=="number"?`${t}[${n}]`:t?`${t}.${n}`:n,"")}function de(e,t,n,o,r={}){let s=[],l=[];function c(f,u,p){if(Array.isArray(f)){let[,d]=f;if(!Array.isArray(u)||!F(d))return;u.forEach((w,h)=>c(d,w,[...p,h]));return}if(!(!F(f)||!F(u)))for(let d of Object.keys(u))Object.prototype.hasOwnProperty.call(f,d)?c(f[d],u[d],[...p,d]):s.push(We([...p,d]))}function i(f,u,p,d){if(p!==void 0){if(typeof u=="string"){if(u.endsWith("[]")||u==="."||u.startsWith("@"))return;let w=S(u),h=w===-1?u:u.slice(0,w);if(!h)return;e.find(f,h,r).length===0&&l.push({path:We(d),selector:h});return}if(!Array.isArray(u)&&F(u)&&F(p))for(let[w,h]of Object.entries(u))i(f,h,p[w],[...d,w])}}return c(n,o,[]),i(t,n,o,[]),{unknownKeys:s,unmatched:l}}function he(e,t,n){if(n&&typeof n=="object")return{rules:n,tagNode:null};if(typeof n=="string"){let o=t&&t.ownerDocument?t.ownerDocument:t;return k(e,o,n)}return null}var gt=/:(?:focus(?:-within|-visible)?|hover|active|visited|defined)\b/i;function ve(e,t){if(!/^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(e.tagName||""))return;let n=(e.getAttribute?.("type")||"").toLowerCase();if("value"in e&&"value"in t&&e.tagName!=="OPTION"&&n!=="checkbox"&&n!=="radio"&&n!=="file"&&(t.value=e.value),e.tagName==="INPUT"&&(n==="checkbox"||n==="radio")&&(t.checked=e.checked),e.tagName==="OPTION"&&(t.selected=e.selected),e.tagName==="SELECT")for(let o=0;o<e.options.length;o++)t.options[o].selected=e.options[o].selected;"indeterminate"in e&&"indeterminate"in t&&(t.indeterminate=e.indeterminate)}function He(e,t,n,o){if(o)return!!e.closest?.(t);let r=e;for(;r?.nodeType===1;){if(r.matches(t))return!0;if(r===n)break;r=r.parentElement}return!1}function qe(e,t,n,o,r,s,l,c){if(e.nodeType===1&&((l?ke(e,n):He(e,o,s,!1))||r&&(l&&e!==s?e.matches(r):He(e,r,s,l))))return null;let i=t.importNode(e,!1);c.cloneToLive.set(i,e),c.liveToClone.set(e,i);let f=e.nodeType===1&&e.tagName==="TEMPLATE"?e.content:e,u=i.nodeType===1&&i.tagName==="TEMPLATE"?i.content:i;f!==e&&(c.cloneToLive.set(u,f),c.liveToClone.set(f,u));for(let p of f.childNodes||[]){let d=qe(p,t,n,o,r,s,l,c);d&&(u.appendChild(d),p.nodeType===1&&ve(p,d))}return e.nodeType===1&&ve(e,i),i}function V(e,{capability:t="data",exclude:n=null,inherit:o=!0}={}){if(!e)throw new TypeError("createContentView requires a DOM context");let r=e.nodeType===9?e:e.ownerDocument;if(!r?.implementation?.createHTMLDocument)throw new TypeError("createContentView requires an HTML DOM implementation");let s=r.implementation.createHTMLDocument(""),l=new WeakMap,c=new WeakMap,i=e.nodeType===9?e.documentElement:e;n&&s.documentElement.matches(n);let f=K(t),u=qe(i,s,t,f,n,i,o,{cloneToLive:l,liveToClone:c});e.nodeType===9&&u&&(s.replaceChild(u,s.documentElement),c.set(e,s),l.set(s,e));let p=d=>{if(gt.test(d))throw new Error(`Filtered content queries do not support stateful selector: ${d}`)};return{root:u,document:s,capability:t,selector:K(t),cloneToLive:l,liveToClone:c,original(d){return l.get(d)||null},cloneOf(d){return c.get(d)||null},query(d,w=u){return p(d),Array.from(w.querySelectorAll(d),h=>l.get(h)||h)},text(d=u){return(d===u?u:c.get(d))?.textContent||""},html(d=u){return(d===u?u:c.get(d))?.innerHTML??""},clone(d=u){let w=d===u?u:c.get(d);return w?s.importNode(w,!0):null}}}function Be(e){return e&&e.nodeType===1&&e.tagName==="SCRIPT"&&e.hasAttribute&&e.hasAttribute("data-rules-name")}function wt(e){return e?(e.nodeType===9||e.nodeType===11,e):null}var b={semanticExclude:!0,find(e,t,n={}){let o=wt(e);if(!o||!o.querySelectorAll)return[];let r=Array.from(o.querySelectorAll(t));n.includeRulesTag||(r=r.filter(c=>!Be(c)));let s=[];n.skip&&s.push(n.skip);let l=n.templateAttr===null?null:n.templateAttr||"cms-template";if(l&&s.push("["+l+"]"),s.length){let c=s.join(", ");r=r.filter(i=>!i.closest||!i.closest(c))}return r},parent(e){return e?e.parentElement:null},children(e){return e?Array.from(e.children):[]},text(e,t){if(t===void 0)return(e.textContent||"").trim();e.textContent=t},attr(e,t,n){if(n===void 0)return e.hasAttribute&&e.hasAttribute(t)?e.getAttribute(t):null;e.setAttribute(t,n)},removeAttr(e,t){e&&e.removeAttribute&&e.removeAttribute(t)},prop(e,t,n){if(n===void 0){let o=e?e[t]:void 0;return o!==void 0?o:null}e[t]=n},clone(e){return e.cloneNode(!0)},insertAt(e,t,n){let o=e.children[n]||null;e.insertBefore(t,o)},remove(e){e&&e.parentNode&&e.parentNode.removeChild(e)},replaceWith(e,t){if(!e||!e.parentNode)throw new Error("dom.replaceWith: node has no parent");let o=e.ownerDocument.createElement("template");o.innerHTML=t;let r=o.content.firstElementChild;if(!r)throw new Error("dom.replaceWith: html did not parse to an element");return e.parentNode.replaceChild(r,e),r},stripIds(e){let t=0;return e.id&&(e.removeAttribute("id"),t++),(e.querySelectorAll?e.querySelectorAll("[id]"):[]).forEach(o=>{o.removeAttribute("id"),t++}),t},sameNode(e,t){return e===t}};function C(e,t={}){if(t.exclude===null)return b;let n=[K("data"),t.exclude].filter(Boolean).join(", "),o=e.nodeType===9?e:e.ownerDocument||e,r=e.nodeType===9?e.documentElement:e;if(!t._write&&!r?.matches?.(n)&&!r?.querySelector?.(n)&&!o?.querySelector?.(n))return b;let s=e.nodeType===9||!e.isConnected?e:e.ownerDocument,l=e.nodeType===9?e:e.ownerDocument,c=null,i=()=>c||(c=V(s,{capability:"data",exclude:t.exclude||null})),f=h=>{let y=i();return h===e?y.cloneOf(e):y.cloneOf(h)||h},u=h=>c?.original(h)||h,p=(h,y)=>{i().liveToClone.set(h,y),i().cloneToLive.set(y,h);let a=h.childNodes||[],m=y.childNodes||[];for(let g=0;g<Math.min(a.length,m.length);g++)p(a[g],m[g])},d=(h,y,a,m)=>{let g=Array.from(h.childNodes).filter(T=>c.cloneOf(T)),O=g[0];for(;O&&g.includes(O);)O=O.nextSibling;for(let T of g)T.remove();if(a==="innerHTML"){let T=l.createElement("template");T.innerHTML=m;for(let N of Array.from(T.content.childNodes))h.insertBefore(N,O||null)}else h.insertBefore(l.createTextNode(m),O||null);let E=V(h,{capability:"data",exclude:t.exclude||null});y.replaceChildren(...Array.from(E.root?.childNodes||[]));let A=T=>{let N=E.original(T);N&&(c.liveToClone.set(N,T),c.cloneToLive.set(T,N));for(let we of Array.from(T.childNodes||[]))A(we)};for(let T of Array.from(y.childNodes))A(T)},w={...b,find(h,y,a={}){let m=f(h);if(!m?.querySelectorAll)return[];let g=i().query(y,m);a.includeRulesTag||(g=g.filter(E=>!Be(E)));let x=[];a.skip&&x.push(a.skip);let O=a.templateAttr===null?null:a.templateAttr||"cms-template";if(O&&x.push(`[${O}]`),x.length){let E=x.join(", ");g=g.filter(A=>!A.closest?.(E))}return g},parent(h){let y=f(h)?.parentElement;return y?u(y):null},children(h){return Array.from(f(h)?.children||[],u)},text(h,y){if(y===void 0){let g=u(h);return!g?.matches?.(n)&&!g?.querySelector?.(n)?b.text(g):(f(h)?.textContent||"").trim()}let a=u(h);if(!a?.matches?.(n)&&!a?.querySelector?.(n)&&!c){b.text(a,y);return}let m=i().cloneOf(a);m?d(a,m,"textContent",y):b.text(a,y)},attr(h,y,a){let m=u(h);if(a===void 0)return b.attr(m,y);b.attr(m,y,a);let g=c?.cloneOf(m);g&&(b.attr(g,y,a),V(m,{capability:"data",exclude:t.exclude||null}).root===null&&(g.remove(),c.liveToClone.delete(m),c.cloneToLive.delete(g)))},removeAttr(h,y){let a=u(h);b.removeAttr(a,y);let m=c?.cloneOf(a);m&&b.removeAttr(m,y)},prop(h,y,a){let m=u(h);if(a===void 0)return y==="innerHTML"||y==="outerHTML"||y==="textContent"||y==="innerText"?b.prop(f(m),y):b.prop(m,y);let g=y==="innerHTML"||y==="textContent"||y==="innerText",x=g?i().cloneOf(m):c?.cloneOf(m);x&&g?d(m,x,y,a):(b.prop(m,y,a),x&&b.prop(x,y,a))},clone(h){let y=f(h);return y===h?b.clone(h):l.importNode(y,!0)},insertAt(h,y,a){let m=u(h),x=w.children(m)[a]||(()=>{for(let A=m.children.length-1;A>=0;A--){let T=m.children[A];if(i().cloneOf(T))return T.nextElementSibling}return m.firstElementChild})(),O=u(y);m.insertBefore(O,x||null);let E=i().cloneOf(m);if(E){let A=i().cloneOf(O);A||(A=l.importNode(O,!0),p(O,A));let T=Array.from(E.children);E.insertBefore(A,T[a]||null)}},remove(h){let y=u(h),a=i().cloneOf(y);b.remove(y),a&&b.remove(a)},replaceWith(h,y){let a=u(h),m=i().cloneOf(a),g=b.replaceWith(a,y);if(m){let x=V(g,{capability:"data",exclude:t.exclude||null});if(!x.root)m.remove();else{m.replaceWith(x.root);let O=E=>{let A=x.original(E);A&&(c.liveToClone.set(A,E),c.cloneToLive.set(E,A));for(let T of Array.from(E.childNodes||[]))O(T)};O(x.root)}}return g}};return w}var J=b;var Y={extract:(e,t,n={})=>M(C(e,n),e,t,n),apply:(e,t,n,o={})=>L(C(e,{...o,_write:!0}),e,t,n,o),findRulesIn:(e,t)=>k(J,e,t),findRules:(e,t)=>he(J,e,t),bind:(e,t,n={})=>{let o=he(J,e,t);if(!o){let r=typeof t=="string"?`data-rules-name~="${t}"`:"the provided rules object";throw new Error(`hyper-html-api: could not resolve rules for ${r}`)}return{...o,get:()=>M(C(e,n),e,o.rules,n),set:r=>L(C(e,{...n,_write:!0}),e,o.rules,r,n)}},parseStrict:le,parseRelaxed:z,ruleAttrIndex:S,splitRule:re,errors:R,DOM_PROPERTIES:G},pe=e=>!!e&&typeof e.nodeType=="number";function Ue(e){let t=e&&e.ownerDocument?e.ownerDocument:e,n=k(J,t,"api");if(!n)throw new R.NoRulesTag("api");return n.rules}function Et(e){if(e.nodeType===9)return e;let t=e.ownerDocument?.documentElement;if(t?.contains(e))return t;let n=e;for(;n.parentNode;)n=n.parentNode;return n}function Tt(e){if(e.nodeType!==11||!e.host)return e.cloneNode(!0);let t=e.ownerDocument.createDocumentFragment();for(let n of e.childNodes)t.appendChild(n.cloneNode(!0));return t}function At(e,t){let n=[];for(;t!==e;){let o=t.parentNode;n.push(Array.prototype.indexOf.call(o.childNodes,t)),t=o}return n.reverse()}function Ot(e,t){return t.reduce((n,o)=>n.childNodes[o],e)}function D(e,t){let n=e.querySelectorAll?Array.from(e.querySelectorAll(t)):[];return e.matches?.(t)&&n.unshift(e),n}function xt(e,t){let n=D(e,"option"),o=D(t,"option");n.forEach((i,f)=>o[f].selected=i.selected);let r=D(e,"input"),s=D(t,"input");r.forEach((i,f)=>{let u=i.type.toLowerCase();u!=="file"&&(s[f].value=i.value),(u==="checkbox"||u==="radio")&&(s[f].checked=i.checked)});let l=D(e,"textarea"),c=D(t,"textarea");l.forEach((i,f)=>c[f].value=i.value)}function me(e,t){if(t!==void 0){if(typeof e=="string"){if(e.endsWith("[]"))return;let n=e.startsWith("@")?0:S(e);if(n===-1)return;let o=e.slice(n+1);if(_.has(o))throw new R.RuleTargetReadOnly(o);return}if(Array.isArray(e)){if(!Array.isArray(t))return;t.forEach(n=>me(e[1],n));return}if(e&&typeof e=="object"&&t&&typeof t=="object"&&!Array.isArray(t))for(let[n,o]of Object.entries(e))me(o,t[n])}}function bt(e,t,n){let o={templateAttr:"cms-template"},r=Et(e),s=At(r,e),l=Tt(r);xt(r,l);let c=Ot(l,s),i=C(l,{...o,_write:!0}),f=de(i,c,t,n,o);if(f.unknownKeys.length||f.unmatched.length)throw new R.WriteRejected(f.unknownKeys,f.unmatched);let u=Z(i);L(u,c,t,n,o),u.assertClean(),me(t,n);let p=Z(C(r,{...o,_write:!0}));L(p,e,t,n,o),p.assertClean()}function St(e){if(!(e instanceof Error))return e;let t=e.name||"Error";try{e.code=t}catch{Object.defineProperty(e,"code",{value:t,configurable:!0,enumerable:!0})}return e instanceof R.WriteRefused?e.details=e.refusals:e instanceof R.WriteRejected?e.details={unknownKeys:e.unknownKeys,unmatched:e.unmatched}:e instanceof R.ShapeMismatch?e.details=e.mismatches:Array.isArray(e.path)?e.details={path:e.path}:typeof e.target=="string"?e.details={target:e.target}:e.token!==void 0?e.details={token:e.token}:e.version!==void 0?e.details={version:e.version}:e.details={},e}function ye(e,t){let n=pe(e)?e:document,o=pe(e)?t:e;return o===void 0?M(C(n),n,Ue(n)):Y.bind(n,o).get()}function ge(e,t,n){try{if(!pe(e))throw new Error("hyper-html-api: applyData(root, data, source?) needs a DOM root as the first argument.");let o=n===void 0?Ue(e):Y.bind(e,n).rules;bt(e,o,t)}catch(o){throw St(o)}return e}var Rt={engine:Y,extractData:ye,applyData:ge},Nt=Rt;return Ye(Mt);})();
6
6
  window.clay = window.clay || {};
7
7
  window.clay.extractData = hyperHtmlApiData.extractData;
8
- // clayjs-level sugar: applyData(data) writes into the whole document, matching
9
- // extractData's root sniff. Explicit-root applyData(el, data, source?) passes through.
10
- window.clay.applyData = function (root, data, source) {
11
- if (root && typeof root.nodeType === "number") return hyperHtmlApiData.applyData(root, data, source);
12
- return hyperHtmlApiData.applyData(document, root, data);
8
+ window.clay.applyData = function (values, optionsOrSource, source) {
9
+ if (values && typeof values.nodeType === "number") return hyperHtmlApiData.applyData(values, optionsOrSource, source);
10
+ var isObject = optionsOrSource !== null && typeof optionsOrSource === "object";
11
+ var proto = isObject ? Object.getPrototypeOf(optionsOrSource) : null;
12
+ var isOptions = isObject && (proto === Object.prototype || proto === null) && Object.prototype.hasOwnProperty.call(optionsOrSource, "rules");
13
+ var rules = isOptions ? optionsOrSource.rules : optionsOrSource;
14
+ return hyperHtmlApiData.applyData(document, values, rules == null ? undefined : rules);
13
15
  };
14
16
  window.clay.loaded = window.clay.loaded || {};
15
17
  window.clay.loaded.data = Promise.resolve();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panphora/clayjs",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "type": "module",
5
5
  "description": "clayjs: malleable HTML files. Save lifecycle for self-saving HTML.",
6
6
  "license": "MIT-0",
@@ -7,7 +7,7 @@ import { isSaveConflicted } from "./save.js";
7
7
  import { gateCaptureToken } from "../lib/dirty-gate.js";
8
8
  import { reloadAfterDiscard } from "./unsaved-warning.js";
9
9
  import { bevelButton, bevelIconButton, bevelSurface, bevelWell, bevelText, protectIcon, RUNTIME_ONLY } from "../ui/bevel-controls.js";
10
- import { TOKENS, FONT_SANS, FONT_MONO } from "../ui/bevel.js";
10
+ import { TOKENS, FONT_SANS, FONT_MONO, GLYPHS } from "../ui/bevel.js";
11
11
 
12
12
  // One notice for everything this tab holds that the page no longer shows: edits
13
13
  // another save replaced (the ledger, clay.conflicts) and a save the host refused.
@@ -34,8 +34,6 @@ const SOURCES = {
34
34
 
35
35
  const MINIMIZE_SVG = '<svg viewBox="0 0 12 12" width="12" height="12" aria-hidden="true"><path d="M2.5 9.5h7" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="square"/></svg>';
36
36
 
37
- const EYE_SVG = '<svg viewBox="0 0 256 256" width="16" height="16" fill="currentColor" aria-hidden="true">' + '<path d="M247.31,124.76c-.35-.79-8.82-19.58-27.65-38.41C194.57,61.26,162.88,48,128,48S61.43,61.26,36.34,86.35C17.51,105.18,9,124,8.69,124.76a8,8,0,0,0,0,6.5c.35.79,8.82,19.57,27.65,38.4C61.43,194.74,93.12,208,128,208s66.57-13.26,91.66-38.34c18.83-18.83,27.3-37.61,27.65-38.4A8,8,0,0,0,247.31,124.76ZM128,192c-30.78,0-57.67-11.19-79.93-33.25A133.47,133.47,0,0,1,25,128,133.33,133.33,0,0,1,48.07,97.25C70.33,75.19,97.22,64,128,64s57.67,11.19,79.93,33.25A133.46,133.46,0,0,1,231.05,128C223.84,141.46,192.43,192,128,192Zm0-112a48,48,0,1,0,48,48A48.05,48.05,0,0,0,128,80Zm0,80a32,32,0,1,1,32-32A32,32,0,0,1,128,160Z"/>' + '</svg>';
38
-
39
37
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
40
38
 
41
39
  const BLOCKED_ROW = "This spot changed again. Review the latest edit or download your copy.";
@@ -391,7 +389,7 @@ function eyeButton(row) {
391
389
  const base = ["all:initial", "color-scheme:inherit", "box-sizing:border-box", "cursor:pointer", "display:inline-grid", "place-items:center", "width:22px", "height:20px", `color:${TOKENS.ink}`];
392
390
  const b = el("button", base);
393
391
  b.type = "button";
394
- b.innerHTML = EYE_SVG;
392
+ b.innerHTML = GLYPHS.conflictEye;
395
393
  protectIcon(b.firstElementChild, 16);
396
394
  b.setAttribute("aria-label", `Show ${row.name} on page`);
397
395
  b.title = "Show on page";
@@ -0,0 +1,321 @@
1
+ import { hostSupports } from "./host-meta.js";
2
+ import { saveToken } from "./host-attrs.js";
3
+
4
+ const DATA_READ = "data-read";
5
+ const DATA_WRITE = "data-write";
6
+ const WRITE_HOLD_REASON = "Waiting for the page data write to finish";
7
+ const SYNC_WAIT_MS = 12000;
8
+ const HTTP_WAIT_MS = 30000;
9
+
10
+ function refusal(code, message, details) {
11
+ const error = new Error(message);
12
+ error.code = code;
13
+ error.details = details;
14
+ return error;
15
+ }
16
+
17
+ async function responseBody(response) {
18
+ if (typeof response.json === "function") return response.json();
19
+ const text = await response.text();
20
+ return text ? JSON.parse(text) : null;
21
+ }
22
+
23
+ async function responseError(response) {
24
+ let body = {};
25
+ try {
26
+ body = (await responseBody(response)) || {};
27
+ } catch {}
28
+
29
+ const message = body.message || body.error || response.statusText || `Request failed (${response.status})`;
30
+ const error = new Error(message);
31
+ error.status = response.status;
32
+ error.error = body.error;
33
+ error.details = body.details;
34
+ return error;
35
+ }
36
+
37
+ function responseEtag(response) {
38
+ const value = response.headers?.get?.("ETag");
39
+ return typeof value === "string" && value ? value : null;
40
+ }
41
+
42
+ function dataUrl(rules, location) {
43
+ const base = `${location.origin}${location.pathname}`;
44
+ if (rules !== undefined) return `${base}?data=${encodeURIComponent(JSON.stringify(rules))}`;
45
+ return `${location.origin}/_/api${location.pathname}`;
46
+ }
47
+
48
+ function connected(sync) {
49
+ return !!sync && !sync.isDestroyed && sync.sse?.readyState === 1;
50
+ }
51
+
52
+ function syncWaiter(eventTarget, timeoutMs) {
53
+ const seen = [];
54
+ let expected = null;
55
+ let resolvePending = null;
56
+ let timer = null;
57
+
58
+ const matchesExact = (detail) =>
59
+ detail?.source === "disk" && (expected === null || detail.etag === expected);
60
+
61
+ const matchesPending = (detail) =>
62
+ detail?.source === "disk" && (detail.etag == null || expected === null || detail.etag === expected);
63
+
64
+ const cleanup = () => {
65
+ clearTimeout(timer);
66
+ eventTarget.removeEventListener("clay:sync-applied", onApplied);
67
+ };
68
+
69
+ const onApplied = (event) => {
70
+ seen.push(event.detail);
71
+ if (!resolvePending || !matchesPending(event.detail)) return;
72
+ const resolve = resolvePending;
73
+ resolvePending = null;
74
+ cleanup();
75
+ resolve(true);
76
+ };
77
+
78
+ eventTarget.addEventListener("clay:sync-applied", onApplied);
79
+
80
+ return {
81
+ waitFor(etag) {
82
+ expected = etag;
83
+ if (seen.some(matchesExact)) {
84
+ cleanup();
85
+ return Promise.resolve(true);
86
+ }
87
+ return new Promise((resolve) => {
88
+ resolvePending = resolve;
89
+ timer = setTimeout(() => {
90
+ resolvePending = null;
91
+ cleanup();
92
+ resolve(false);
93
+ }, timeoutMs);
94
+ });
95
+ },
96
+ cancel: cleanup,
97
+ };
98
+ }
99
+
100
+ function httpDeadline(timeoutMs) {
101
+ const controller = new AbortController();
102
+ let rejectDeadline;
103
+ const expired = new Promise((_, reject) => {
104
+ rejectDeadline = reject;
105
+ });
106
+ const timer = setTimeout(() => {
107
+ const error = new Error("The page data write timed out.");
108
+ error.name = "TimeoutError";
109
+ controller.abort(error);
110
+ rejectDeadline(error);
111
+ }, timeoutMs);
112
+
113
+ return {
114
+ signal: controller.signal,
115
+ waitFor(promise) {
116
+ return Promise.race([promise, expired]);
117
+ },
118
+ cancel() {
119
+ clearTimeout(timer);
120
+ },
121
+ };
122
+ }
123
+
124
+ async function defaultWriteModules() {
125
+ const [save, saveCore, etag, warning, editMode] = await Promise.all([
126
+ import("./save.js"),
127
+ import("./save-core.js"),
128
+ import("./etag.js"),
129
+ import("./unsaved-warning.js"),
130
+ import("./is-edit-mode.js"),
131
+ ]);
132
+ return { ...save, ...saveCore, ...etag, ...warning, ...editMode };
133
+ }
134
+
135
+ export function createPageDataApi({
136
+ supports = hostSupports,
137
+ token = saveToken,
138
+ fetchImpl = (...args) => fetch(...args),
139
+ getLocation = () => window.location,
140
+ eventTarget = document,
141
+ loadWriteModules = defaultWriteModules,
142
+ syncTimeoutMs = SYNC_WAIT_MS,
143
+ httpTimeoutMs = HTTP_WAIT_MS,
144
+ } = {}) {
145
+ let liveSync = null;
146
+ let writeRunning = false;
147
+ let writeOutcomeUnknown = false;
148
+
149
+ function setLiveSync(sync) {
150
+ liveSync = sync;
151
+ }
152
+
153
+ async function readData(rules) {
154
+ if (!(await supports(DATA_READ))) {
155
+ throw refusal("DataReadUnsupported", "This host does not support reading page data.");
156
+ }
157
+
158
+ let response;
159
+ try {
160
+ response = await fetchImpl(dataUrl(rules, getLocation()), {
161
+ method: "GET",
162
+ credentials: "same-origin",
163
+ cache: "no-store",
164
+ redirect: "error",
165
+ });
166
+ } catch (cause) {
167
+ throw Object.assign(refusal("DataReadFailed", cause?.message || "Could not read page data."), { cause });
168
+ }
169
+
170
+ if (!response.ok) throw await responseError(response);
171
+ return { data: await responseBody(response), etag: responseEtag(response) };
172
+ }
173
+
174
+ function assertWriteState(modules, { checkHold = true } = {}) {
175
+ if (writeOutcomeUnknown) {
176
+ throw refusal("DataWriteOutcomeUnknown", "A previous page data write has an unknown outcome. Reload before writing again.");
177
+ }
178
+ if (writeRunning) {
179
+ throw refusal("DataWriteInProgress", "Another page data write is already running.");
180
+ }
181
+ if (modules.isSaveInProgress()) {
182
+ throw refusal("SaveInProgress", "The page is already being saved.");
183
+ }
184
+ if (modules.saveFateIsUnknown()) {
185
+ throw refusal("SaveOutcomeUnknown", "The page's last save has an unknown outcome.");
186
+ }
187
+ if (checkHold && (modules.savesHeld() || modules.isSaveConflicted())) {
188
+ throw refusal("SavesHeld", "The page cannot write data while another save hold is active.");
189
+ }
190
+ if (modules.hasUnsavedChanges()) {
191
+ throw refusal("UnsavedChanges", "Save or discard the page's unsaved changes before writing data.");
192
+ }
193
+ if (!connected(liveSync)) {
194
+ throw refusal("SyncRequired", "Page data writes require the sync plugin to be connected.");
195
+ }
196
+ }
197
+
198
+ async function waitForBaseline(modules) {
199
+ if (modules.baselineSettled()) return;
200
+ await new Promise((resolve) => eventTarget.addEventListener("clay:baseline-settled", resolve, { once: true }));
201
+ }
202
+
203
+ async function writeData(values, { rules, ifMatch } = {}) {
204
+ if (!(await supports(DATA_WRITE))) {
205
+ throw refusal("DataWriteUnsupported", "This host does not support writing page data.");
206
+ }
207
+
208
+ const modules = await loadWriteModules();
209
+ if (!modules.isEditMode) {
210
+ throw refusal("DataWriteUnavailable", "Page data writes require an editable page.");
211
+ }
212
+
213
+ await waitForBaseline(modules);
214
+ assertWriteState(modules);
215
+
216
+ let match = ifMatch;
217
+ if (match == null) match = modules.lastSeenEtag() || await modules.seedEtag();
218
+ if (typeof match !== "string" || match === "") {
219
+ throw refusal("DataWriteVersionRequired", "Page data writes require a trustworthy document ETag.");
220
+ }
221
+
222
+ assertWriteState(modules);
223
+ writeRunning = true;
224
+ modules.holdAllSaves(WRITE_HOLD_REASON);
225
+
226
+ let waiter = null;
227
+ try {
228
+ if (modules.isSaveInProgress()) {
229
+ throw refusal("SaveInProgress", "The page is already being saved.");
230
+ }
231
+ if (modules.saveFateIsUnknown()) {
232
+ throw refusal("SaveOutcomeUnknown", "The page's last save has an unknown outcome.");
233
+ }
234
+ if (modules.isSaveConflicted()) {
235
+ throw refusal("SavesHeld", "The page cannot write data while another save hold is active.");
236
+ }
237
+ if (modules.hasUnsavedChanges()) {
238
+ throw refusal("UnsavedChanges", "Save or discard the page's unsaved changes before writing data.");
239
+ }
240
+ if (!connected(liveSync)) {
241
+ throw refusal("SyncRequired", "Page data writes require the sync plugin to be connected.");
242
+ }
243
+
244
+ const headers = {
245
+ "Content-Type": "application/json",
246
+ "If-Match": match,
247
+ };
248
+ const currentToken = token();
249
+ if (currentToken) headers["Save-Token"] = currentToken;
250
+
251
+ const body = JSON.stringify(values);
252
+ waiter = syncWaiter(eventTarget, syncTimeoutMs);
253
+ const deadline = httpDeadline(httpTimeoutMs);
254
+
255
+ let response;
256
+ try {
257
+ response = await deadline.waitFor(fetchImpl(dataUrl(rules, getLocation()), {
258
+ method: "POST",
259
+ credentials: "same-origin",
260
+ redirect: "error",
261
+ headers,
262
+ body,
263
+ signal: deadline.signal,
264
+ }));
265
+ } catch (cause) {
266
+ deadline.cancel();
267
+ writeOutcomeUnknown = true;
268
+ throw Object.assign(
269
+ refusal("DataWriteOutcomeUnknown", "The page data write has an unknown outcome. Do not retry automatically."),
270
+ { cause, unknownOutcome: true }
271
+ );
272
+ }
273
+
274
+ let data;
275
+ try {
276
+ if (!response.ok) throw await deadline.waitFor(responseError(response));
277
+ data = await deadline.waitFor(responseBody(response));
278
+ } catch (cause) {
279
+ if (cause?.status) throw cause;
280
+ writeOutcomeUnknown = true;
281
+ throw Object.assign(
282
+ refusal("DataWriteOutcomeUnknown", "The page data was written, but its response could not be read."),
283
+ { cause, unknownOutcome: true }
284
+ );
285
+ } finally {
286
+ deadline.cancel();
287
+ }
288
+
289
+ const etag = responseEtag(response);
290
+ if (etag && etag === modules.lastSeenEtag()) {
291
+ waiter.cancel();
292
+ waiter = null;
293
+ return { data, etag };
294
+ }
295
+
296
+ const applied = await waiter.waitFor(etag);
297
+ waiter = null;
298
+ if (!applied) {
299
+ return {
300
+ data,
301
+ etag,
302
+ pageUpdatePending: true,
303
+ message: "Written, page update pending.",
304
+ };
305
+ }
306
+ return { data, etag };
307
+ } finally {
308
+ waiter?.cancel();
309
+ writeRunning = false;
310
+ modules.releaseAllSaves({ reason: WRITE_HOLD_REASON });
311
+ }
312
+ }
313
+
314
+ return { readData, writeData, setLiveSync };
315
+ }
316
+
317
+ const pageData = createPageDataApi();
318
+
319
+ export const readData = pageData.readData;
320
+ export const writeData = pageData.writeData;
321
+ export const setPageDataLiveSync = pageData.setLiveSync;
package/src/core/save.js CHANGED
@@ -214,23 +214,26 @@ export function resumeAutosave() {
214
214
  }
215
215
 
216
216
  // ============================================
217
- // THE PREVIEW HOLD
217
+ // THE ALL-SAVE HOLD
218
218
  // ============================================
219
219
  //
220
- // While an AI edit's rewrite is on screen and not yet kept, the DOM holds words the
221
- // person has not accepted. Every save would write them, the explicit ones included,
222
- // so for that window no save goes out at all. A save asked for meanwhile is
223
- // remembered and runs on release; Keep releases without the replay because it saves
224
- // right after.
220
+ // While an operation owns the page's persisted state, no save goes out at all. A
221
+ // save asked for meanwhile is remembered and runs on release.
225
222
  let previewHold = 0;
226
223
  let previewMissed = false;
224
+ const PREVIEW_HOLD_REASON = 'Waiting for the AI edit to be kept or reverted';
225
+ const holdReasons = new Map();
227
226
 
228
- export function holdAllSaves() {
227
+ export function holdAllSaves(reason = PREVIEW_HOLD_REASON) {
229
228
  previewHold++;
229
+ holdReasons.set(reason, (holdReasons.get(reason) || 0) + 1);
230
230
  }
231
231
 
232
- export function releaseAllSaves({ replay = true } = {}) {
233
- if (previewHold === 0) return;
232
+ export function releaseAllSaves({ replay = true, reason = PREVIEW_HOLD_REASON } = {}) {
233
+ const count = holdReasons.get(reason) || 0;
234
+ if (count === 0) return;
235
+ if (count === 1) holdReasons.delete(reason);
236
+ else holdReasons.set(reason, count - 1);
234
237
  previewHold--;
235
238
  if (previewHold > 0) return;
236
239
  const missed = previewMissed;
@@ -242,11 +245,16 @@ export function savesHeld() {
242
245
  return previewHold > 0;
243
246
  }
244
247
 
248
+ export function saveHoldReason() {
249
+ if (previewHold === 0) return null;
250
+ return holdReasons.keys().next().value || PREVIEW_HOLD_REASON;
251
+ }
252
+
245
253
  function heldForPreview(callback, resolve) {
246
254
  if (previewHold === 0) return false;
247
255
  previewMissed = true;
248
256
  clearExplicitSave();
249
- const skipped = skipped_('Waiting for the AI edit to be kept or reverted');
257
+ const skipped = skipped_(saveHoldReason());
250
258
  callback(skipped);
251
259
  resolve(skipped);
252
260
  return true;
@@ -854,7 +862,7 @@ export function savePageThrottled(callback = () => {}) {
854
862
 
855
863
  if (previewHold > 0) {
856
864
  previewMissed = true;
857
- const skipped = skipped_('Waiting for the AI edit to be kept or reverted');
865
+ const skipped = skipped_(saveHoldReason());
858
866
  callback(skipped);
859
867
  return Promise.resolve(skipped);
860
868
  }
@@ -5,9 +5,9 @@ const UNSUPPORTED_SELECTOR = /:(?:focus(?:-within|-visible)?|hover|active|visite
5
5
  function copyControlState(source, copy) {
6
6
  if (!/^(INPUT|TEXTAREA|SELECT|OPTION)$/.test(source.tagName || '')) return
7
7
  const type = (source.getAttribute?.('type') || '').toLowerCase()
8
- if ('value' in source && 'value' in copy && source.tagName !== 'OPTION' && type !== 'checkbox' && type !== 'radio') copy.value = source.value
9
- if ('checked' in source && 'checked' in copy) copy.checked = source.checked
10
- if ('selected' in source && 'selected' in copy) copy.selected = source.selected
8
+ if ('value' in source && 'value' in copy && source.tagName !== 'OPTION' && type !== 'checkbox' && type !== 'radio' && type !== 'file') copy.value = source.value
9
+ if (source.tagName === 'INPUT' && (type === 'checkbox' || type === 'radio')) copy.checked = source.checked
10
+ if (source.tagName === 'OPTION') copy.selected = source.selected
11
11
  if (source.tagName === 'SELECT') {
12
12
  for (let i = 0; i < source.options.length; i++) copy.options[i].selected = source.options[i].selected
13
13
  }
@@ -8,6 +8,7 @@ export const CORE_WAVES = {
8
8
  // is exactly the case where edit mode is off, so the editOnly wave would never
9
9
  // reach it. It draws nothing on any other page.
10
10
  "core/stale-host-notice.js",
11
+ "core/page-data.js",
11
12
  ],
12
13
  editOnly: [
13
14
  "vendor/hyper-morph.vendor.js",
@@ -66,6 +67,7 @@ export const MODULES = {
66
67
  "lib/mutation.js": () => import("./lib/mutation.js"),
67
68
  "core/edit-mode.js": () => import("./core/edit-mode.js"),
68
69
  "core/stale-host-notice.js": () => import("./core/stale-host-notice.js"),
70
+ "core/page-data.js": () => import("./core/page-data.js"),
69
71
  "core/snapshot.js": () => import("./core/snapshot.js"),
70
72
  "core/save-core.js": () => import("./core/save-core.js"),
71
73
  "core/save.js": () => import("./core/save.js"),