@popmelt.com/core 0.33.0 → 0.33.1
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.
- package/claude-plugin/.claude-plugin/plugin.json +1 -1
- package/codex-plugin/.codex-plugin/plugin.json +1 -1
- package/dist/ExploreAttachment-VKCCEIM7.mjs +1 -0
- package/dist/ParticipantRuntime-YS5SIZUQ.mjs +1 -0
- package/dist/PopmeltTasteConnectedPane-FKIJM3C7.mjs +1 -215
- package/dist/PreviewRuntime-LFPK56NW.mjs +1 -2
- package/dist/QueuedReplies-ZYUDSTS2.mjs +1 -46
- package/dist/SuppliedContext-RWN6UR3K.mjs +1 -2
- package/dist/ThreadErrorCard-7J62GD5W.mjs +1 -2
- package/dist/ThreadPanel-KVNM67WO.mjs +1 -0
- package/dist/adapter-react-three-fiber.mjs +1 -2
- package/dist/bridge-entry.mjs +1 -1
- package/dist/bridge-recovery-3IQN3U6D.mjs +1 -2
- package/dist/bridgeSSEStream-NEYI73TC.mjs +1 -4
- package/dist/bridgeWebSocketStream-H3DCP4T3.mjs +1 -2
- package/dist/browser-runtime-AP35S5MK.mjs +1 -0
- package/dist/browser.mjs +1 -2
- package/dist/canvas-chat-note-NHYL3T6J.mjs +1 -2
- package/dist/checkFixture-MWBOYIM2.mjs +1 -0
- package/dist/chunk-27ADDVGC.mjs +1 -3
- package/dist/chunk-2IASPT6L.mjs +1 -2
- package/dist/chunk-2P2NUZW7.mjs +1 -2
- package/dist/chunk-2VCHBI7Y.mjs +1 -11
- package/dist/chunk-2ZJ4FBTG.mjs +1 -2
- package/dist/chunk-4LHTPRFY.mjs +1 -2
- package/dist/chunk-5K7SACPW.mjs +1 -2
- package/dist/chunk-6V2VCKPG.mjs +1 -53
- package/dist/chunk-6VXFTT5U.mjs +1 -2
- package/dist/chunk-75PQGTKX.mjs +1 -2
- package/dist/chunk-BVTLSUQT.mjs +1 -2
- package/dist/chunk-CPOYMGYY.mjs +1 -2
- package/dist/chunk-DNOKP3JS.mjs +1 -2
- package/dist/chunk-EAV2VV2V.mjs +1 -2
- package/dist/chunk-EX63NVDN.mjs +1 -2
- package/dist/chunk-F5XSNRGT.mjs +1 -2
- package/dist/chunk-GASEZICN.mjs +1 -2
- package/dist/chunk-H7XMDLGU.mjs +30 -0
- package/dist/{chunk-C5WXW6VL.mjs → chunk-HVD5ZG6W.mjs} +1 -1
- package/dist/chunk-J3UIBBU2.mjs +1 -2
- package/dist/chunk-J4WDYITA.mjs +1 -2
- package/dist/chunk-JMMP5JSP.mjs +1 -2
- package/dist/chunk-LVEMYZOA.mjs +1 -2
- package/dist/chunk-N2QUNHV6.mjs +1 -0
- package/dist/chunk-N2ZEZCHO.mjs +1 -2
- package/dist/{chunk-HNCV37XO.mjs → chunk-N6JTX4PD.mjs} +1 -1
- package/dist/chunk-O4HZP3RP.mjs +1 -2
- package/dist/chunk-ODIGT4YJ.mjs +1 -17
- package/dist/chunk-PQT5FYN5.mjs +1 -2
- package/dist/chunk-PSSHCTJ2.mjs +1 -8
- package/dist/chunk-RESPUCV7.mjs +1 -0
- package/dist/chunk-SHAIHRV2.mjs +1 -0
- package/dist/chunk-V2I7PSJW.mjs +1 -2
- package/dist/{chunk-H2UYAUX3.mjs → chunk-VPPVURBR.mjs} +1 -1
- package/dist/chunk-W5NIRROD.mjs +1 -7
- package/dist/chunk-WHJEKDNP.mjs +1 -2
- package/dist/chunk-XKD2ABCO.mjs +1 -7
- package/dist/chunk-XTOCFTVW.mjs +1 -2
- package/dist/chunk-YLKEDOII.mjs +31 -0
- package/dist/chunk-ZHJZPC7U.mjs +1 -2
- package/dist/cli.mjs +1 -1
- package/dist/codex-note-context-4JYQ437H.mjs +2 -0
- package/dist/{codex-project-7VYHYTWO.mjs → codex-project-FA4EK6VR.mjs} +1 -1
- package/dist/focus-inspection-VBS5656D.mjs +1 -2
- package/dist/index.mjs +1 -2
- package/dist/media.mjs +1 -2
- package/dist/{peer-client-MTWZG2FB.mjs → peer-client-KJCPXT76.mjs} +1 -1
- package/dist/plugin-astro.mjs +1 -1
- package/dist/plugin-nuxt.mjs +1 -1
- package/dist/plugin-vite.mjs +1 -1
- package/dist/server.mjs +1 -1
- package/dist/taste-proposal-session-XU4N7RUV.mjs +1 -2
- package/dist/workspace-snapshot-RTTXNNUX.mjs +1 -2
- package/package.json +1 -1
- package/dist/ExploreAttachment-CLFSAWKM.mjs +0 -260
- package/dist/ParticipantRuntime-HW3MOZI5.mjs +0 -139
- package/dist/ThreadPanel-RJIHV3P6.mjs +0 -197
- package/dist/browser-runtime-JJHSKIKD.mjs +0 -2
- package/dist/checkFixture-TJDFGPQI.mjs +0 -2
- package/dist/chunk-7IJGE5AK.mjs +0 -31
- package/dist/chunk-I63OQTCF.mjs +0 -347
- package/dist/chunk-J5SC3R5L.mjs +0 -2
- package/dist/chunk-PHKDIU3X.mjs +0 -30
- package/dist/chunk-XMKYGH62.mjs +0 -142
- package/dist/codex-note-context-YHKPQ4WP.mjs +0 -2
- /package/dist/{chunk-DMWB3IRD.mjs → chunk-QOJCTLQW.mjs} +0 -0
package/dist/chunk-N2ZEZCHO.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
var v=(e,t=0,i=1)=>Math.min(i,Math.max(t,e));function te(e){let{width:t,height:i}=e.rect,s=Math.max(1,e.naturalWidth),r=Math.max(1,e.naturalHeight),a=Math.min(t/s,i/r),o=Math.max(t/s,i/r);switch(e.objectFit){case"contain":return{width:s*a,height:r*a};case"cover":return{width:s*o,height:r*o};case"none":return{width:s,height:r};case"scale-down":{let n=Math.min(1,a);return{width:s*n,height:r*n}}default:return{width:t,height:i}}}function C(e,t){let i=e.trim().toLowerCase();if(i.endsWith("%")){let s=Number.parseFloat(i);return Number.isFinite(s)?t*(s/100):0}if(i.endsWith("px")){let s=Number.parseFloat(i);return Number.isFinite(s)?s:0}return i==="center"?t/2:i==="right"||i==="bottom"?t:0}function ie(e,t,i){let s=e.objectPosition.trim().split(/\s+/),r=s[0]||"50%",a=s[1]||"50%";return{x:C(r,e.rect.width-t),y:C(a,e.rect.height-i)}}function F(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0||e.naturalWidth<=0||e.naturalHeight<=0)return null;let i=e.ownerDocument.defaultView?.getComputedStyle(e)??getComputedStyle(e),s={rect:t,naturalWidth:e.naturalWidth,naturalHeight:e.naturalHeight,objectFit:i.objectFit||"fill",objectPosition:i.objectPosition||"50% 50%"},r=te(s);return{layout:s,rendered:r,position:ie(s,r.width,r.height)}}function L(e,t){let i=F(e);if(!i)return null;let{layout:s,rendered:r,position:a}=i;if(t.x<s.rect.left||t.x>s.rect.left+s.rect.width||t.y<s.rect.top||t.y>s.rect.top+s.rect.height)return null;let o=(t.x-s.rect.left-a.x)/r.width,n=(t.y-s.rect.top-a.y)/r.height;return o>=0&&o<=1&&n>=0&&n<=1?{x:o,y:n}:null}function O(e,t){let i=F(e);if(!i)return null;let{layout:s,rendered:r,position:a}=i,o=(t.left-s.rect.left-a.x)/r.width,n=(t.top-s.rect.top-a.y)/r.height,h=(t.left+t.width-s.rect.left-a.x)/r.width,d=(t.top+t.height-s.rect.top-a.y)/r.height,c=v(Math.min(o,h)),l=v(Math.min(n,d)),u=v(Math.max(o,h)),m=v(Math.max(n,d));return u<=c||m<=l?null:{left:c,top:l,width:u-c,height:m-l}}function z(e,t){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))return null;let i=F(e);if(!i)return null;let{layout:s,rendered:r,position:a}=i,{rect:o}=s,n=o.left+a.x+v(t.left)*r.width,h=o.top+a.y+v(t.top)*r.height,d=o.left+a.x+v(t.left+Math.max(0,t.width))*r.width,c=o.top+a.y+v(t.top+Math.max(0,t.height))*r.height,l=Math.max(o.left,n),u=Math.max(o.top,h),m=Math.min(o.left+o.width,d),g=Math.min(o.top+o.height,c);return m<=l||g<=u?null:{left:l,top:u,width:m-l,height:g-u}}var se="popmelt:see:v1";function P(e){if(!e||typeof e!="object")return!1;let t=e;return["left","top","width","height"].every(i=>typeof t[i]=="number"&&Number.isFinite(t[i]))}function re(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.label=="string"&&typeof t.score=="number"&&(t.origin==="detected"||t.origin==="manual")&&P(t.box)&&(t.detectedBox===void 0||P(t.detectedBox))}function ae(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.detectedLabel=="string"&&P(t.detectedBox)}function N(e){if(!e||typeof e!="object")return!1;let t=e;return t.schemaVersion===1&&typeof t.source=="string"&&typeof t.imageHash=="string"&&typeof t.inferenceKey=="string"&&typeof t.dedupeKey=="string"&&typeof t.updatedAt=="number"&&Array.isArray(t.subjects)&&t.subjects.every(re)&&(t.suppressions===void 0||Array.isArray(t.suppressions)&&t.suppressions.every(ae))}function oe(e={}){let t=e.namespace??se,i=()=>e.storage??window.localStorage,s=n=>`${t}:${n}`,r=n=>`${s(n)}:history`,a=n=>{try{let h=i().getItem(s(n));if(!h)return null;let d=JSON.parse(h);return N(d)?d:null}catch{return null}},o=n=>{try{let h=i().getItem(r(n));if(!h)return[];let d=JSON.parse(h);return Array.isArray(d)?d.filter(N).slice(0,10):[]}catch{return[]}};return{load:a,save(n,h){let d=a(n);if(d&&d.imageHash!==h.imageHash){let c=o(n).filter(l=>l.imageHash!==d.imageHash||l.updatedAt!==d.updatedAt);i().setItem(r(n),JSON.stringify([d,...c].slice(0,10)))}i().setItem(s(n),JSON.stringify(h))},remove(n){i().removeItem(s(n)),i().removeItem(r(n))},loadHistory:o}}function ne(){let e=new Map,t=new Map;return{load:i=>e.get(i)??null,save:(i,s)=>{let r=e.get(i);if(r&&r.imageHash!==s.imageHash){let a=t.get(i)??[];t.set(i,[r,...a.filter(o=>o.imageHash!==r.imageHash||o.updatedAt!==r.updatedAt)].slice(0,10))}e.set(i,s)},remove:i=>{e.delete(i),t.delete(i)},loadHistory:i=>t.get(i)??[]}}function de(e){return{label:e.label,score:e.score,box:{...e.box}}}var H="img";function A(e){let t=2166136261;for(let i=0;i<e.length;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function R(e){return new URL(p(e),e.ownerDocument.baseURI).href}async function he(e){let t=R(e);try{let i=await fetch(t,{cache:"force-cache",credentials:"same-origin"});if(!i.ok)throw new Error(`Unable to hash image (${i.status})`);let s=await i.arrayBuffer();if(!globalThis.crypto?.subtle)throw new Error("SubtleCrypto unavailable");let r=await globalThis.crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(r),a=>a.toString(16).padStart(2,"0")).join("")}catch{return`source:${A(t)}:${e.naturalWidth}x${e.naturalHeight}`}}function p(e){return e.currentSrc||e.src||e.getAttribute("src")||""}function le(e){return e.complete&&e.naturalWidth>0&&e.naturalHeight>0?Promise.resolve():new Promise((t,i)=>{let s=()=>{a(),t()},r=()=>{a(),i(new Error(`Unable to load image: ${p(e)}`))},a=()=>{e.removeEventListener("load",s),e.removeEventListener("error",r)};e.addEventListener("load",s,{once:!0}),e.addEventListener("error",r,{once:!0})})}function ce(e,t){return{id:t.id,image:e,detection:de(t),detectedLabel:t.detectedLabel,detectedBox:t.detectedBox?{...t.detectedBox}:void 0,boundsOverridden:t.boundsOverridden,manual:t.origin==="manual"}}function ue(e){return{id:e.id,label:e.detection.label,detectedLabel:e.detectedLabel,score:e.detection.score,box:{...e.detection.box},detectedBox:e.detectedBox?{...e.detectedBox}:void 0,origin:e.manual?"manual":"detected",boundsOverridden:e.boundsOverridden}}function me(e){return e.origin==="manual"||e.boundsOverridden===!0||!!(e.detectedLabel&&e.label!==e.detectedLabel)}function ge(e,t){return t.x>=e.left&&t.x<=e.left+e.width&&t.y>=e.top&&t.y<=e.top+e.height}var q=class{constructor(e={}){this.options=e,this.surfaceKind="image",this.records=new Map,this.imageKeys=new Map,this.analyzedSources=new WeakMap,this.pending=new WeakMap,this.analysisMetadata=new WeakMap,this.suppressions=new WeakMap,this.writeChains=new WeakMap,this.pendingWrites=new Set,this.refreshQueued=!1,this.destroyed=!1,this.manualSequence=0,this.id=e.id??"see:image",this.readyPromise=this.refresh();let t=e.root??document;this.observer=e.observe!==!1&&typeof MutationObserver<"u"?new MutationObserver(()=>this.queueRefresh()):null,this.observer?.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcset","sizes"]})}whenReady(){return this.readyPromise}listSubjects(){let e=[];for(let t of this.records.keys()){let i=this.resolve(t);i&&e.push(i)}return e}async refresh(){if(this.destroyed)return;let e=this.options.root??document,t=this.options.selector??H,i=new Set;e instanceof HTMLImageElement&&e.matches(t)&&i.add(e);for(let s of e.querySelectorAll(t))s instanceof HTMLImageElement&&i.add(s);for(let s of this.imageKeys.keys())(!i.has(s)||!s.isConnected)&&this.removeImage(s);if(this.options.recognition)for(let s of i)await this.analyze(s);else await Promise.all(Array.from(i,s=>this.analyze(s)))}hitTest(e){let t=null;for(let i of this.records.keys()){let s=this.resolve(i),r=this.records.get(i);if(!s||!r||!ge(s.bounds,e))continue;let a=s.bounds.width*s.bounds.height;(!t||a<t.area||a===t.area&&r.detection.score>t.score)&&(t={subject:s,area:a,score:r.detection.score})}return t?.subject??null}resolve(e){let t=this.records.get(e);if(!t||!t.image.isConnected)return null;let i=z(t.image,t.detection.box);if(!i)return null;let s=t.image.getBoundingClientRect(),r=Math.round(t.detection.score*1e3)/1e3;return{key:e,label:t.detection.label,sourceElement:t.image,imageObject:this.imageObjectContext(t),bounds:i,surfaceBounds:{left:s.left,top:s.top,width:s.width,height:s.height},context:`${t.detection.label} ${t.manual?"labelled":"detected"} in ${t.image.alt||"image"}`,data:{kind:"image-object",label:t.detection.label,origin:t.manual?"manual":"detected",...t.detectedLabel?{detectedLabel:t.detectedLabel}:{},score:String(r),imageSrc:p(t.image)}}}restoreSubject(e,t){if(this.records.has(e))return this.resolve(e);let i=t.imageObject;if(!i)return null;let s=t.sourceElement?.dataAttributes,r=s?.["data-popmelt-media-id"]??s?.["data-popmelt-see-id"],a=this.matchingImages().find(g=>{let f=p(g),y=this.imageIdentity(g,f);return!(!e.startsWith(`${y}:`)||r&&y!==r)});if(!a)return null;let o=this.imageIdentity(a,p(a)),n=e.slice(o.length+1),h={left:i.normalizedBox.x,top:i.normalizedBox.y,width:i.normalizedBox.width,height:i.normalizedBox.height};if(!n||!Object.values(h).every(g=>Number.isFinite(g)&&g>=0&&g<=1))return null;let d=t.dataAttributes,c=t.subjectLabel??d?.label??t.textContent;if(!c)return null;let l=Number(d?.score),u=d?.origin==="manual";this.records.set(e,{id:n,image:a,detection:{label:c,score:Number.isFinite(l)?l:1,box:h},detectedLabel:d?.detectedLabel,detectedBox:u?void 0:{...h},boundsOverridden:!0,manual:u});let m=this.imageKeys.get(a)??new Set;if(m.add(e),this.imageKeys.set(a,m),!this.analysisMetadata.has(a)){let g=R(a);this.analysisMetadata.set(a,{storeKey:`${this.id}:${o}`,source:g,imageHash:`recovered:${A(g)}`,inferenceKey:"",dedupeKey:""}),this.suppressions.set(a,[])}return this.persistImage(a),this.resolve(e)}imageObjectContext(e){let{image:t,detection:{box:i}}=e;return{src:p(t),alt:t.alt,width:t.naturalWidth,height:t.naturalHeight,normalizedBox:{x:i.left,y:i.top,width:i.width,height:i.height},box:{x:i.left*t.naturalWidth,y:i.top*t.naturalHeight,width:i.width*t.naturalWidth,height:i.height*t.naturalHeight}}}async captureSubject(e){let t=this.records.get(e);if(!t?.image.isConnected||!t.image.complete)return null;let{box:i}=this.imageObjectContext(t);if(i.width<=0||i.height<=0)return null;let s=Math.min(1,1024/Math.max(i.width,i.height)),r=document.createElement("canvas");r.width=Math.max(1,Math.round(i.width*s)),r.height=Math.max(1,Math.round(i.height*s));let a=r.getContext("2d");return a?(a.drawImage(t.image,i.x,i.y,i.width,i.height,0,0,r.width,r.height),new Promise((o,n)=>{try{r.toBlob(o,"image/webp",.95)}catch(h){n(h)}})):null}beginCreate(e){let t=this.matchingImages();for(let i=t.length-1;i>=0;i-=1){let s=t[i];if(!s)continue;let r=L(s,e);if(!r)continue;let a=p(s),o=this.imageIdentity(s,a),n=`manual:${this.newObjectId()}`,h=`${o}:${n}`,d={label:"object",score:1,box:{left:r.x,top:r.y,width:0,height:0}},c=!1,l=!1,u=()=>{if(l)return;l=!0,this.records.set(h,{id:n,image:s,detection:d,manual:!0});let m=this.imageKeys.get(s)??new Set;m.add(h),this.imageKeys.set(s,m)};return{key:h,update:m=>{if(c)return null;u();let g=this.clampedImagePoint(s,m);return g?(d.box={left:Math.min(r.x,g.x),top:Math.min(r.y,g.y),width:Math.abs(g.x-r.x),height:Math.abs(g.y-r.y)},this.resolve(h)):this.resolve(h)},commit:()=>c?null:(u(),this.persistImage(s),this.resolve(h)),cancel:()=>{c||(c=!0,l&&this.removeSubject(h))}}}return null}renameSubject(e,t){let i=this.records.get(e),s=t.trim();return!i||!s?null:(!i.manual&&!i.detectedLabel&&(i.detectedLabel=i.detection.label),i.detection.label=s,this.persistImage(i.image),this.resolve(e))}updateSubjectBounds(e,t){let i=this.records.get(e);if(!i)return null;let s=O(i.image,t);return s?(i.detection.box=s,i.boundsOverridden=!0,this.persistImage(i.image),this.resolve(e)):null}removeSubject(e){let t=this.records.get(e);if(!t)return;if(!t.manual){let s=this.suppressions.get(t.image)??[];s.push({detectedLabel:t.detectedLabel??t.detection.label,detectedBox:{...t.detectedBox??t.detection.box}}),this.suppressions.set(t.image,s)}this.records.delete(e);let i=this.imageKeys.get(t.image);i?.delete(e),i?.size===0&&this.imageKeys.delete(t.image),this.persistImage(t.image)}async destroy(){this.destroyed||(this.destroyed=!0,this.observer?.disconnect(),this.records.clear(),this.imageKeys.clear(),await Promise.allSettled(this.pendingWrites),await this.options.recognition?.dispose?.())}queueRefresh(){this.refreshQueued||this.destroyed||(this.refreshQueued=!0,queueMicrotask(()=>{this.refreshQueued=!1,this.readyPromise=this.refresh()}))}async analyze(e){let t=p(e);if(!t||this.analyzedSources.get(e)===t)return;let i=this.pending.get(e);if(i)return i.source===t?i.promise:(await i.promise,this.analyze(e));this.analyzedSources.has(e)&&this.removeImage(e);let s={source:t,promise:Promise.resolve()},r=(async()=>{try{if(await le(e),this.destroyed)return;let a=R(e),o=this.imageIdentity(e,t),n=`${this.id}:${o}`,h=this.options.recognition,d=this.options.store?await this.options.store.load(n):null;if(this.destroyed||p(e)!==t)return;let c=h?.cacheKey??d?.inferenceKey??"",l=h?.configurationKey??d?.dedupeKey??"",u=d?.source===a,m=!!(e.dataset.popmeltMediaId||e.dataset.popmeltSeeId),g=u||m;if(d&&g){let K=new Map(d.subjects.map(x=>[x.id,x]));for(let x of this.imageSubjects(e))K.set(x.id,x);this.replaceImageRecords(e,o,[...K.values()]),this.suppressions.set(e,[...d.suppressions??[]]),this.analysisMetadata.set(e,{storeKey:n,source:a,imageHash:d.imageHash,inferenceKey:d.inferenceKey,dedupeKey:d.dedupeKey})}if(this.options.hydrateOnly){this.analyzedSources.set(e,t);return}let f=this.options.store?await(this.options.imageHasher??he)(e):"ephemeral";if(this.destroyed||p(e)!==t)return;if(d&&g&&d.imageHash===f&&(!h||d.inferenceKey===c&&d.dedupeKey===l)){this.analysisMetadata.set(e,{storeKey:n,source:a,imageHash:f,inferenceKey:c,dedupeKey:l}),this.analyzedSources.set(e,t),await this.saveImage(e);return}let y=g&&d?.imageHash===f;if(d&&!y){let K=new Set(d.subjects.map(I=>I.id)),x=d.subjects.filter(me);this.replaceImageRecords(e,o,[...x,...this.imageSubjects(e).filter(I=>!K.has(I.id))]),this.suppressions.set(e,[])}if(this.analysisMetadata.set(e,{storeKey:n,source:a,imageHash:f,inferenceKey:y?d.inferenceKey:"",dedupeKey:y?d.dedupeKey:""}),!h){this.analyzedSources.set(e,t),await this.saveImage(e);return}let Z=await h.detect(e);if(this.destroyed||p(e)!==t)return;let E=this.suppressions.get(e)??[],ee=h.reconcile(Z,this.imageSubjects(e),E);this.replaceImageRecords(e,o,ee),this.suppressions.set(e,[...E]),this.analysisMetadata.set(e,{storeKey:n,source:a,imageHash:f,inferenceKey:c,dedupeKey:l}),this.analyzedSources.set(e,t),await this.saveImage(e)}catch(a){this.options.onError?.(a,e)}finally{this.pending.get(e)===s&&this.pending.delete(e)}})();return s.promise=r,this.pending.set(e,s),r}replaceImageRecords(e,t,i){this.removeImage(e);let s=new Set;for(let r of i){let a=`${t}:${r.id}`;s.add(a),this.records.set(a,ce(e,r))}this.imageKeys.set(e,s)}imageIdentity(e,t){if(e.dataset.popmeltMediaId)return e.dataset.popmeltMediaId;if(e.dataset.popmeltSeeId)return e.dataset.popmeltSeeId;let i=new URL(t,e.ownerDocument.baseURI).href,s=this.options.root??e.ownerDocument,r=this.options.selector??H,a=Array.from(s.querySelectorAll(r)).filter(n=>p(n)===t),o=Math.max(0,a.indexOf(e));return`${A(i)}:${o}`}matchingImages(){let e=this.options.root??document,t=this.options.selector??H,i=[];e instanceof HTMLImageElement&&e.matches(t)&&i.push(e);for(let s of e.querySelectorAll(t))s instanceof HTMLImageElement&&i.push(s);return i}clampedImagePoint(e,t){let i=z(e,{left:0,top:0,width:1,height:1});return i?L(e,{x:Math.max(i.left,Math.min(i.left+i.width,t.x)),y:Math.max(i.top,Math.min(i.top+i.height,t.y))}):null}newObjectId(){return globalThis.crypto?.randomUUID?.()||A(`${Date.now()}:${this.manualSequence++}:${Math.random().toString(36)}`)}persistImage(e){let t=this.persistencePayload(e);if(!t)return Promise.resolve();let i=(this.writeChains.get(e)??Promise.resolve()).catch(()=>{}).then(()=>t.store.save(t.key,t.analysis)).catch(s=>{this.options.onError?.(s,e)});return this.writeChains.set(e,i),this.pendingWrites.add(i),i.finally(()=>this.pendingWrites.delete(i)),i}async saveImage(e){await this.persistImage(e)}imageSubjects(e){return Array.from(this.imageKeys.get(e)??[]).map(t=>this.records.get(t)).filter(t=>!!t).map(ue)}persistencePayload(e){let t=this.options.store,i=this.analysisMetadata.get(e);if(!t||!i)return null;let s=this.imageSubjects(e),r={schemaVersion:1,source:i.source,imageHash:i.imageHash,inferenceKey:i.inferenceKey,dedupeKey:i.dedupeKey,subjects:s,suppressions:this.suppressions.get(e)??[],updatedAt:Date.now()};return{store:t,key:i.storeKey,analysis:r}}removeImage(e){for(let t of this.imageKeys.get(e)??[])this.records.delete(t);this.imageKeys.delete(e),this.analyzedSources.delete(e),this.analysisMetadata.delete(e),this.suppressions.delete(e)}};function fe(e={}){return new q(e)}var w=(e,t=0,i=1)=>Math.min(i,Math.max(t,e));function B(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0||e.videoWidth<=0||e.videoHeight<=0)return null;let i=e.ownerDocument.defaultView?.getComputedStyle(e)??getComputedStyle(e),s=i.objectFit||"fill",r=Math.min(t.width/e.videoWidth,t.height/e.videoHeight),a=Math.max(t.width/e.videoWidth,t.height/e.videoHeight),o=s==="contain"?r:s==="cover"?a:s==="none"?1:s==="scale-down"?Math.min(1,r):null,n=o?{width:e.videoWidth*o,height:e.videoHeight*o}:{width:t.width,height:t.height},h=(i.objectPosition||"50% 50%").split(/\s+/),d=(c,l)=>c.endsWith("%")?l*(Number.parseFloat(c)/100):c.endsWith("px")?Number.parseFloat(c):c==="center"?l/2:c==="right"||c==="bottom"?l:0;return{rect:t,rendered:n,position:{x:d(h[0]||"50%",t.width-n.width),y:d(h[1]||"50%",t.height-n.height)}}}function j(e,t){let i=B(e);if(!i)return null;let{rect:s,rendered:r,position:a}=i;if(t.x<s.left||t.x>s.right||t.y<s.top||t.y>s.bottom)return null;let o=(t.x-s.left-a.x)/r.width,n=(t.y-s.top-a.y)/r.height;return o>=0&&o<=1&&n>=0&&n<=1?{x:o,y:n}:null}function D(e,t){let i=B(e);if(!i)return null;let{rect:s,rendered:r,position:a}=i,o=s.left+a.x+w(t.left)*r.width,n=s.top+a.y+w(t.top)*r.height,h=s.left+a.x+w(t.left+Math.max(0,t.width))*r.width,d=s.top+a.y+w(t.top+Math.max(0,t.height))*r.height,c=Math.max(s.left,o),l=Math.max(s.top,n),u=Math.min(s.right,h),m=Math.min(s.bottom,d);return u<=c||m<=l?null:{left:c,top:l,width:u-c,height:m-l}}function U(e,t){let i=B(e);if(!i)return null;let{rect:s,rendered:r,position:a}=i,o=(t.left-s.left-a.x)/r.width,n=(t.top-s.top-a.y)/r.height,h=(t.left+t.width-s.left-a.x)/r.width,d=(t.top+t.height-s.top-a.y)/r.height,c=w(Math.min(o,h)),l=w(Math.min(n,d)),u=w(Math.max(o,h)),m=w(Math.max(n,d));return u<=c||m<=l?null:{left:c,top:l,width:u-c,height:m-l}}var ye="video",pe=1/60,Q=30,be=.9,ve=250,M=.001;function $(e){let t=2166136261;for(let i=0;i<e.length;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function b(e){return e.currentSrc||e.src||e.querySelector("source")?.src||e.getAttribute("src")||""}function we(e){return e.readyState>=1&&e.videoWidth>0&&e.videoHeight>0?Promise.resolve():new Promise((t,i)=>{let s=()=>{a(),t()},r=()=>{a(),i(new Error(`Unable to load video: ${b(e)}`))},a=()=>{e.removeEventListener("loadedmetadata",s),e.removeEventListener("error",r)};e.addEventListener("loadedmetadata",s,{once:!0}),e.addEventListener("error",r,{once:!0})})}function xe(e,t,i){let s=(r,a)=>r+(a-r)*i;return{left:s(e.left,t.left),top:s(e.top,t.top),width:s(e.width,t.width),height:s(e.height,t.height)}}function T(e,t){return e.find(i=>t>=i.start-.001&&(i.end===void 0||t<=i.end+.001))??null}function V(e){return!T(e.segments,e.video.currentTime)}function k(e){return e?.motion.createSmoother()??{smooth(t){return{...t,box:{...t.box}}}}}function J(e){return{visible:!V(e),misses:e.misses,hits:e.hits,lostAt:e.lostAt}}function ke(e,t){e.misses=t.misses,e.hits=t.hits,e.lostAt=t.lostAt}function Me(e,t){if(t?.length)return t.map(s=>({...s})).sort((s,r)=>s.start-r.start);let i=e.reduce((s,r)=>Math.min(s,r.time),Number.POSITIVE_INFINITY);return Number.isFinite(i)?[{start:i}]:[]}function S(e,t,i){if(e.length===0||i&&!T(i,t))return null;let s=[...e].sort((d,c)=>d.time-c.time),r=s.findIndex(d=>d.time>=t);if(r<=0)return{...s[0],box:{...s[0].box}};if(r<0){let d=s[s.length-1];return{...d,box:{...d.box}}}let a=s[r-1],o=s[r],n=Math.max(Number.EPSILON,o.time-a.time),h=Math.max(0,Math.min(1,(t-a.time)/n));return{time:t,box:xe(a.box,o.box,h),score:a.score+(o.score-a.score)*h,source:a.source==="manual"||o.source==="manual"?"manual":"tracked"}}function W(e){return!e.video.paused&&e.liveFrame?{...e.liveFrame,box:{...e.liveFrame.box}}:S(e.presentationKeyframes,e.video.currentTime,e.segments)}function Te(e,t){return t.x>=e.left&&t.x<=e.left+e.width&&t.y>=e.top&&t.y<=e.top+e.height}function G(e,t){if(!Te(e.bounds,t))return!1;let i=e.outline;if(!i||i.length<3)return!0;let s=(t.x-e.bounds.left)/e.bounds.width,r=(t.y-e.bounds.top)/e.bounds.height,a=!1;for(let o=0,n=i.length-1;o<i.length;n=o++){let h=i[o],d=i[n];h.y>r!=d.y>r&&s<(d.x-h.x)*(r-h.y)/(d.y-h.y)+h.x&&(a=!a)}return a}function Se(e){let t=e.outline;if(!t||t.length<3)return e.bounds.width*e.bounds.height;let i=0;for(let s=0;s<t.length;s+=1){let r=t[s],a=t[(s+1)%t.length];i+=r.x*a.y-a.x*r.y}return Math.abs(i)/2*e.bounds.width*e.bounds.height}function Y(e,t){return(t.outline?.length?t.outline.map(i=>({x:t.bounds.left+i.x*t.bounds.width,y:t.bounds.top+i.y*t.bounds.height})):[{x:t.bounds.left,y:t.bounds.top},{x:t.bounds.left+t.bounds.width,y:t.bounds.top},{x:t.bounds.left+t.bounds.width,y:t.bounds.top+t.bounds.height},{x:t.bounds.left,y:t.bounds.top+t.bounds.height}]).every(i=>G(e,i))}function Ke(e,t){let i=Math.max(e.left,t.left),s=Math.max(e.top,t.top),r=Math.min(e.left+e.width,t.left+t.width),a=Math.min(e.top+e.height,t.top+t.height),o=Math.max(0,r-i)*Math.max(0,a-s),n=e.width*e.height+t.width*t.height-o;return n>0?o/n:0}var _=class{constructor(e={}){this.options=e,this.surfaceKind="video",this.records=new Map,this.videoKeys=new Map,this.metadata=new WeakMap,this.analyzedSources=new WeakMap,this.listeners=new Map,this.frameHandles=new Map,this.persistTimers=new Map,this.writeChains=new WeakMap,this.pendingWrites=new Set,this.refreshQueued=!1,this.destroyed=!1,this.manualSequence=0,this.detectedSequence=0,this.activeTrackingKey=null,this.segmentationGeneration=0,this.transientKeys=new Set,this.segmentationRequestSignatures=new WeakMap,this.changeListeners=new Set,this.id=e.id??"see:video",this.readyPromise=this.refresh();let t=e.root??document;this.observer=e.observe!==!1&&typeof MutationObserver<"u"?new MutationObserver(()=>this.queueRefresh()):null,this.observer?.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src"]})}whenReady(){return this.readyPromise}subscribe(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}listSubjects(){return Array.from(this.records.keys(),e=>this.transientKeys.has(e)?null:this.resolve(e)).filter(e=>!!e)}async refresh(){if(this.destroyed)return;let e=new Set(this.matchingVideos());for(let t of this.videoKeys.keys())(!e.has(t)||!t.isConnected)&&this.removeVideo(t);await Promise.all(Array.from(e,t=>this.analyze(t)))}hitTest(e){return this.hitTestAll(e)[0]??null}hitTestAll(e){let t=[];for(let i of this.records.keys()){let s=this.resolve(i);!s||!G(s,e)||t.push({subject:s,area:Se(s)})}return this.options.segmentation&&this.scheduleSegmentation(e),t.sort((i,s)=>Y(i.subject,s.subject)?1:Y(s.subject,i.subject)?-1:i.area-s.area).map(({subject:i})=>i)}promoteSubject(e){let t=this.records.get(e);return t?this.transientKeys.delete(e)?(this.activateTrackingRecord(t),this.persistVideo(t.video),this.startSession(t,!0).then(()=>this.scheduleBackwardAnalysis(t)),this.resolve(e)):this.resolve(e):null}resolve(e){let t=this.records.get(e);if(!t?.video.isConnected)return null;let i=W(t);if(!i)return null;let s=D(t.video,i.box);if(!s)return null;let r=t.video.getBoundingClientRect();return{key:e,label:t.label,sourceElement:t.video,videoObject:this.videoObjectContext(t,i),trackingAnchors:t.anchors.map(a=>({...a})),outline:i.outline?.map(a=>({...a})),bounds:s,surfaceBounds:{left:r.left,top:r.top,width:r.width,height:r.height},context:`${t.label} tracked in video at ${t.video.currentTime.toFixed(2)}s`,data:{kind:"video-object",label:t.label,origin:t.origin,score:String(Math.round(i.score*1e3)/1e3),videoSrc:b(t.video),currentTime:String(t.video.currentTime)}}}async captureSubject(e){let t=this.records.get(e);if(!t||t.video.readyState<2)return null;let i=W(t);if(!i)return null;let{video:s}=t,r={x:i.box.left*s.videoWidth,y:i.box.top*s.videoHeight,width:i.box.width*s.videoWidth,height:i.box.height*s.videoHeight},a=Math.min(1,1024/Math.max(r.width,r.height)),o=document.createElement("canvas");o.width=Math.max(1,Math.round(r.width*a)),o.height=Math.max(1,Math.round(r.height*a));let n=o.getContext("2d");return n?(n.drawImage(s,r.x,r.y,r.width,r.height,0,0,o.width,o.height),new Promise((h,d)=>{try{o.toBlob(h,"image/webp",.95)}catch(c){d(c)}})):null}beginCreate(e){let t=this.matchingVideos();for(let i=t.length-1;i>=0;i-=1){let s=t[i];if(!s)continue;let r=j(s,e);if(!r)continue;let a=this.videoIdentity(s),o=`manual:${this.newObjectId()}`,n=`${a}:${o}`,h=Date.now(),d={time:s.currentTime,box:{left:r.x,top:r.y,width:0,height:0},score:1,source:"manual"},c=k(this.options.tracking),l={key:n,id:o,video:s,label:"object",origin:"manual",keyframes:[d],segments:[{start:s.currentTime}],anchors:[],presentationKeyframes:[c.smooth(d)],smoother:c,createdAt:h,updatedAt:h,misses:0,hits:0,analyzedThrough:d.time},u=!1,m=!1,g=()=>{if(m)return;m=!0,this.records.set(n,l);let f=this.videoKeys.get(s)??new Set;f.add(n),this.videoKeys.set(s,f)};return{key:n,update:f=>{if(u)return null;g();let y=j(s,f);return y&&(d.box={left:Math.min(r.x,y.x),top:Math.min(r.y,y.y),width:Math.abs(y.x-r.x),height:Math.abs(y.y-r.y)},l.smoother=k(this.options.tracking),l.presentationKeyframes=[l.smoother.smooth(d)]),this.resolve(n)},commit:()=>u?null:(g(),l.backwardSeedTime=d.time,this.activateTrackingRecord(l),this.persistVideo(s),this.startSession(l,!0).then(()=>this.scheduleBackwardAnalysis(l)),this.resolve(n)),cancel:()=>{u||(u=!0,m&&this.removeSubject(n))}}}return null}renameSubject(e,t){let i=this.records.get(e),s=t.trim();return!i||!s?null:(i.label=s,i.updatedAt=Date.now(),this.activateTrackingRecord(i),this.persistVideo(i.video),this.resolve(e))}updateSubjectBounds(e,t){let i=this.records.get(e);if(!i)return null;let s=U(i.video,t);if(!s)return null;this.openSegment(i,i.video.currentTime),this.insertKeyframe(i,{time:i.video.currentTime,box:s,score:1,source:"manual"}),i.liveFrame=void 0,i.trackingFailed=!1,i.misses=0,i.hits=0,i.lostAt=void 0,i.analyzedThrough=i.video.currentTime;let r=T(i.segments,i.video.currentTime);return r&&Math.abs(r.start-i.video.currentTime)<=.05&&(i.backwardSeedTime=i.video.currentTime,this.cancelBackwardAnalysis(i)),this.activateTrackingRecord(i),this.persistVideo(i.video),this.startSession(i,!0).then(()=>this.reseed(i)).then(()=>this.scheduleBackwardAnalysis(i)),this.resolve(e)}updateSubjectTrackingAnchors(e,t){let i=this.records.get(e);return i?(i.anchors=t.slice(0,3).map(s=>({x:Math.max(0,Math.min(1,s.x)),y:Math.max(0,Math.min(1,s.y))})),i.updatedAt=Date.now(),i.trackingFailed=!1,i.analyzedThrough=i.video.currentTime,i.backwardSeedTime!==void 0&&this.cancelBackwardAnalysis(i),this.activateTrackingRecord(i),this.persistVideo(i.video),this.startSession(i,!0).then(()=>this.reseed(i)).then(()=>this.scheduleBackwardAnalysis(i)),this.resolve(e)):null}removeSubject(e){let t=this.records.get(e);if(!t)return;this.cancelBackwardAnalysis(t),t.session?.dispose?.(),this.activeTrackingKey===e&&(this.activeTrackingKey=null),this.transientKeys.delete(e),this.records.delete(e);let i=this.videoKeys.get(t.video);i?.delete(e),i?.size===0&&this.videoKeys.delete(t.video),this.persistVideo(t.video)}async destroy(){if(this.destroyed)return;this.destroyed=!0,this.observer?.disconnect();for(let t of this.listeners.keys())this.removeVideoListeners(t);await Promise.all(Array.from(this.persistTimers.keys(),t=>this.flushScheduledPersistence(t)));let e=Array.from(this.records.values(),t=>t.backwardAnalysis?.promise).filter(t=>!!t);await Promise.allSettled(Array.from(this.records.values(),t=>(this.cancelBackwardAnalysis(t),t.session?.dispose?.()))),await Promise.allSettled(e),this.records.clear(),this.videoKeys.clear(),this.changeListeners.clear(),await Promise.allSettled(this.pendingWrites)}scheduleSegmentation(e){let t=this.options.segmentation;if(!t||this.destroyed)return;let i=this.matchingVideos();for(let s=i.length-1;s>=0;s-=1){let r=i[s];if(!r||r.readyState<2)continue;let a=j(r,e);if(!a)continue;let o=[Math.round(r.currentTime*30),Math.round(a.x*256),Math.round(a.y*256)].join(":");if(this.segmentationRequestSignatures.get(r)===o)return;this.segmentationRequestSignatures.set(r,o);let n=++this.segmentationGeneration,h=r.currentTime;t.segment(r,h,a).then(d=>{if(!d||this.destroyed||n!==this.segmentationGeneration||!r.isConnected)return;let c=Array.from(this.videoKeys.get(r)??[]).map(l=>this.records.get(l)).filter(l=>!!l).find(l=>{let u=W(l);return u&&Ke(u.box,d.box)>=.65});this.clearTransientSubjects(r,c?.key),c||this.addDetectedSubject(r,h,d);for(let l of this.changeListeners)l()}).catch(d=>this.options.onError?.(d,r));return}}addDetectedSubject(e,t,i){let s=this.videoIdentity(e),r=`detected:${$([t.toFixed(3),i.box.left.toFixed(4),i.box.top.toFixed(4),i.box.width.toFixed(4),i.box.height.toFixed(4),this.detectedSequence++].join(":"))}`,a=`${s}:${r}`,o=e.currentTime,n={time:o,box:{...i.box},score:i.score,source:"tracked",outline:i.outline?.map(u=>({...u}))},h=k(this.options.tracking),d=Date.now(),c={key:a,id:r,video:e,label:i.label?.trim()||"object",origin:"detected",keyframes:[n],segments:[{start:o}],anchors:[],presentationKeyframes:[h.smooth(n)],smoother:h,createdAt:d,updatedAt:d,misses:0,hits:0,analyzedThrough:o,backwardSeedTime:o};this.records.set(a,c),this.transientKeys.add(a);let l=this.videoKeys.get(e)??new Set;l.add(a),this.videoKeys.set(e,l)}clearTransientSubjects(e,t){let i=this.videoKeys.get(e);if(i)for(let s of[...i])s===t||!this.transientKeys.delete(s)||(this.records.delete(s),i.delete(s))}async analyze(e){let t=b(e);if(!(!t||this.analyzedSources.get(e)===t))try{if(await we(e),this.destroyed||b(e)!==t)return;let i=this.videoIdentity(e),s=new URL(t,e.ownerDocument.baseURI).href,r=`${this.id}:${i}`,a=this.options.store?await this.options.store.load(r):null;if(this.destroyed||b(e)!==t)return;this.metadata.set(e,{storeKey:r,source:s,identity:i});let o=!!e.dataset.popmeltMediaId;a&&(a.source===s||o)?this.replaceVideoRecords(e,i,a.tracks):this.videoKeys.has(e)||this.videoKeys.set(e,new Set),this.analyzedSources.set(e,t),this.addVideoListeners(e)}catch(i){this.options.onError?.(i,e)}}addVideoListeners(e){if(this.listeners.has(e))return;let t=()=>{this.clearLiveFrames(e),this.activateMostRecentRecord(e);let a=this.activeRecordFor(e);if(this.options.tracking&&a&&!a.session&&(a.analyzedThrough===void 0||a.analyzedThrough<e.duration-M)){let o=this.startSession(a,!0);e.pause(),o.then(()=>{!this.destroyed&&a.session&&e.play()});return}a&&this.scheduleBackwardAnalysis(a),this.scheduleFrame(e)},i=()=>{this.clearLiveFrames(e);let a=this.activeRecordFor(e);a&&this.scheduleBackwardAnalysis(a),this.flushScheduledPersistence(e)},s=()=>{let a=this.activeRecordFor(e);a?.lastTrackedMediaTime!==void 0&&(a.analyzedThrough=e.duration,a.lastTrackedMediaTime=void 0,a.session?.dispose?.(),a.session=void 0,this.schedulePersistence(e)),i()},r=()=>{let a=this.activeRecordFor(e);if(!a)return;let o=a.lastTrackedMediaTime;if(e.loop&&o!==void 0&&o>=e.duration-.25&&e.currentTime+.25<o&&(a.analyzedThrough??0)>=o-.25){S(a.presentationKeyframes,e.currentTime,a.segments)&&(a.liveFrame=void 0),a.analyzedThrough=Math.max(0,e.currentTime-M*2),a.lastTrackedMediaTime=void 0;let n=a.session;a.session=void 0,Promise.resolve(a.tracking).finally(async()=>{await n?.dispose?.(),!(this.destroyed||this.activeTrackingKey!==a.key)&&(await this.startSession(a),this.scheduleBackwardAnalysis(a))}),this.schedulePersistence(e);return}this.clearLiveFrames(e),a.session&&this.reseed(a)};e.addEventListener("play",t),e.addEventListener("pause",i),e.addEventListener("ended",s),e.addEventListener("seeked",r),this.listeners.set(e,()=>{e.removeEventListener("play",t),e.removeEventListener("pause",i),e.removeEventListener("ended",s),e.removeEventListener("seeked",r)}),e.paused||(this.activateMostRecentRecord(e),this.scheduleFrame(e))}removeVideoListeners(e){this.listeners.get(e)?.(),this.listeners.delete(e);let t=e,i=this.frameHandles.get(e);i!==void 0&&(t.cancelVideoFrameCallback?.(i),cancelAnimationFrame(i)),this.frameHandles.delete(e)}scheduleFrame(e){if(this.destroyed||e.paused||this.frameHandles.has(e))return;let t=e,i=(s,r)=>{this.frameHandles.delete(e),this.trackVideo(e,r.mediaTime),this.scheduleFrame(e)};t.requestVideoFrameCallback?this.frameHandles.set(e,t.requestVideoFrameCallback(i)):this.frameHandles.set(e,requestAnimationFrame(()=>i(performance.now(),{mediaTime:e.currentTime})))}async trackVideo(e,t){let i=this.activeRecordFor(e);if(!i||i.tracking||i.trackingFailed||i.analyzedThrough!==void 0&&t<=i.analyzedThrough+M)return;let s=this.options.tracking?.motion;if(!s)return;let r=s.attempt({state:J(i),time:t,maximumFramesPerSecond:Math.max(1,this.options.maxTrackingFramesPerSecond??Q)});i.lastTrackedMediaTime!==void 0&&Math.abs(t-i.lastTrackedMediaTime)<be/r.framesPerSecond||(i.session||await this.startSession(i),!(!i.session||this.activeTrackingKey!==i.key)&&(i.lastTrackedMediaTime=t,i.tracking=i.session.track(e,t,r.tracking).then(a=>{if(this.destroyed||this.activeTrackingKey!==i.key)return;i.analyzedThrough=Math.max(i.analyzedThrough??t,t);let o=s.observe({state:J(i),time:t,observation:a});ke(i,o.state),a&&o.action==="reopen"&&this.openSegment(i,t),a&&(o.action==="accept"||o.action==="reopen")?this.acceptObservation(i,{...a,source:"tracked"}):o.action==="close"&&(i.liveFrame=void 0,this.closeSegment(i,i.keyframes[i.keyframes.length-1]?.time??t)),this.schedulePersistence(e)}).catch(a=>this.failTracking(i,a)).finally(()=>{i.tracking=void 0}),await i.tracking))}async startSession(e,t=!1){if(e.initializing){await e.initializing;return}if(!this.options.tracking||e.session||e.trackingFailed||this.activeTrackingKey!==e.key||e.video.paused&&!t)return;let i=S(e.keyframes,e.video.currentTime,e.segments)??e.liveFrame;!i||e.video.readyState<2||(e.initializing=this.options.tracking.createSession({video:e.video,time:e.video.currentTime,box:i.box,anchors:e.anchors}).then(s=>{this.destroyed||this.activeTrackingKey!==e.key?s.dispose?.():e.session=s}).catch(s=>this.failTracking(e,s)).finally(()=>{e.initializing=void 0}),await e.initializing)}async reseed(e){let t=S(e.keyframes,e.video.currentTime,e.segments);if(!t){e.session?.dispose?.(),e.session=void 0,e.lostAt=e.video.currentTime,e.liveFrame=void 0,e.misses=0,e.hits=0;return}e.lostAt=void 0,e.misses=0,e.hits=0;try{e.session?.reseed&&await e.session.reseed({video:e.video,time:e.video.currentTime,box:t.box,anchors:e.anchors})}catch(i){this.failTracking(e,i)}}failTracking(e,t){e.trackingFailed=!0,e.liveFrame=void 0,e.session?.dispose?.(),e.session=void 0,this.options.onError?.(t,e.video)}activeRecordFor(e){if(!this.activeTrackingKey)return null;let t=this.records.get(this.activeTrackingKey);return t?.video===e?t:null}activateMostRecentRecord(e){if(this.activeRecordFor(e))return;let t=Array.from(this.videoKeys.get(e)??[]).map(i=>this.records.get(i)).filter(i=>!!i).sort((i,s)=>s.updatedAt-i.updatedAt)[0];t&&this.activateTrackingRecord(t)}activateTrackingRecord(e){if(this.activeTrackingKey===e.key)return;let t=this.activeTrackingKey?this.records.get(this.activeTrackingKey):void 0;this.activeTrackingKey=e.key,t&&(this.cancelBackwardAnalysis(t),t.session?.dispose?.(),t.session=void 0,t.lastTrackedMediaTime=void 0,t.liveFrame=void 0),e.liveFrame=void 0,e.trackingFailed=!1,e.lastTrackedMediaTime=void 0,e.misses=0,e.hits=0,e.lostAt=V(e)?e.video.currentTime:void 0}scheduleBackwardAnalysis(e){if(this.destroyed||!this.options.tracking||e.backwardSeedTime===void 0||e.backwardSeedTime<=M||e.backwardAnalysis||e.initializing||this.activeTrackingKey!==e.key)return;let t={cancelled:!1,promise:Promise.resolve()};e.backwardAnalysis=t,t.promise=this.runBackwardAnalysis(e,t).catch(i=>{t.cancelled||this.options.onError?.(i,e.video)}).finally(()=>{e.backwardAnalysis===t&&(e.backwardAnalysis=void 0,!t.cancelled&&e.backwardSeedTime!==void 0&&(e.backwardSeedTime=void 0),t.cancelled&&!this.destroyed&&this.activeTrackingKey===e.key&&queueMicrotask(()=>this.scheduleBackwardAnalysis(e)))})}cancelBackwardAnalysis(e){let t=e.backwardAnalysis;t&&(t.cancelled=!0)}async runBackwardAnalysis(e,t){let i=e.backwardSeedTime;if(i===void 0)return;let s=await this.options.tracking.motion.analyzeBackward({source:e.video,seedTime:i,keyframes:e.keyframes,anchors:e.anchors,maximumFramesPerSecond:this.options.maxTrackingFramesPerSecond??Q,cancelled:()=>t.cancelled||this.destroyed,forwardWork:()=>e.initializing??e.tracking});if(t.cancelled||this.destroyed)return;let r=T(e.segments,i);r&&(e.keyframes=s.keyframes,r.start=Math.min(r.start,s.earliestTime),e.updatedAt=Date.now(),this.rebuildPresentationTrack(e),this.schedulePersistence(e.video))}acceptObservation(e,t){let i=[...e.keyframes].reverse().find(r=>r.outline?.length)?.outline,s=this.insertKeyframe(e,{...t,outline:t.outline??i});return e.video.paused||(e.liveFrame={...s,box:{...s.box}}),!0}openSegment(e,t){if(T(e.segments,t))return!1;let i=e.segments[e.segments.length-1];return i&&i.end===void 0&&t>=i.start?!1:(e.segments.push({start:t}),e.segments.sort((s,r)=>s.start-r.start),e.smoother=k(this.options.tracking),!0)}closeSegment(e,t){let i=[...e.segments].reverse().find(s=>s.end===void 0);return i?(i.end=Math.max(i.start,t),e.updatedAt=Date.now(),!0):!1}insertKeyframe(e,t){let i={...t,box:{...t.box}},s=e.keyframes.findIndex(a=>Math.abs(a.time-t.time)<.001),r=!1;if(s>=0)e.keyframes[s]=i;else{let a=e.keyframes[e.keyframes.length-1];if(t.source==="tracked"&&a&&Math.abs(t.time-a.time)<pe)e.keyframes[e.keyframes.length-1]=i;else if(!a||t.time>a.time){e.keyframes.push(i);let o=e.smoother.smooth(i);e.presentationKeyframes.push(o),r=!0}else e.keyframes.push(i)}return r||this.rebuildPresentationTrack(e),e.updatedAt=Date.now(),S(e.presentationKeyframes,t.time)??{...i,box:{...i.box}}}rebuildPresentationTrack(e){e.keyframes.sort((s,r)=>s.time-r.time);let t=k(this.options.tracking),i=null;e.presentationKeyframes=e.keyframes.map(s=>{let r=T(e.segments,s.time);return r&&r!==i&&(t=k(this.options.tracking),i=r),t.smooth(s)}),e.smoother=t}clearLiveFrames(e){for(let t of this.videoKeys.get(e)??[]){let i=this.records.get(t);i&&(i.liveFrame=void 0)}}videoObjectContext(e,t){let{video:i}=e,s=e.keyframes.map(r=>r.time);return{src:b(i),width:i.videoWidth,height:i.videoHeight,duration:i.duration,currentTime:i.currentTime,normalizedBox:{x:t.box.left,y:t.box.top,width:t.box.width,height:t.box.height},box:{x:t.box.left*i.videoWidth,y:t.box.top*i.videoHeight,width:t.box.width*i.videoWidth,height:t.box.height*i.videoHeight},trackStart:Math.min(...s),trackEnd:Math.max(...s)}}replaceVideoRecords(e,t,i){this.removeVideoRecords(e);let s=new Set;for(let r of i){let a=`${t}:${r.id}`,o=r.keyframes.map(l=>({...l,box:{...l.box}})),n=Me(o,r.segments),h=o[0],d=k(this.options.tracking);s.add(a);let c={key:a,id:r.id,video:e,label:r.label,origin:r.origin,keyframes:o,segments:n,anchors:(r.anchors??[]).map(l=>({...l})),presentationKeyframes:[],smoother:d,createdAt:r.createdAt,updatedAt:r.updatedAt,misses:0,hits:0,analyzedThrough:r.analyzedThrough,backwardSeedTime:h?.source==="manual"&&h.time>M&&(n[0]?.start??-1)>=h.time-M?h.time:void 0};V(c)&&(c.lostAt=e.currentTime),this.rebuildPresentationTrack(c),r.presentationKeyframes?.length&&(c.presentationKeyframes=r.presentationKeyframes.map(l=>({...l,box:{...l.box}}))),this.records.set(a,c)}this.videoKeys.set(e,s)}persistVideo(e){let t=this.persistTimers.get(e);t!==void 0&&clearTimeout(t),this.persistTimers.delete(e);let i=this.options.store,s=this.metadata.get(e);if(!i||!s)return Promise.resolve();let r=Array.from(this.videoKeys.get(e)??[]).map(n=>this.records.get(n)).filter(n=>!!n).map(n=>({id:n.id,label:n.label,origin:n.origin,keyframes:n.keyframes.map(h=>({...h,box:{...h.box}})),presentationKeyframes:n.presentationKeyframes.map(h=>({...h,box:{...h.box}})),anchors:n.anchors.map(h=>({...h})),segments:n.segments.map(h=>({...h})),analyzedThrough:n.analyzedThrough,createdAt:n.createdAt,updatedAt:n.updatedAt})),a={schemaVersion:3,source:s.source,duration:Number.isFinite(e.duration)?e.duration:0,tracks:r,updatedAt:Date.now()},o=(this.writeChains.get(e)??Promise.resolve()).catch(()=>{}).then(()=>i.save(s.storeKey,a)).catch(n=>this.options.onError?.(n,e));return this.writeChains.set(e,o),this.pendingWrites.add(o),o.finally(()=>this.pendingWrites.delete(o)),o}schedulePersistence(e){!this.options.store||this.persistTimers.has(e)||this.persistTimers.set(e,setTimeout(()=>{this.persistTimers.delete(e),this.persistVideo(e)},ve))}flushScheduledPersistence(e){return this.persistTimers.has(e)?this.persistVideo(e):Promise.resolve()}matchingVideos(){let e=this.options.root??document,t=this.options.selector??ye,i=[];e instanceof HTMLVideoElement&&e.matches(t)&&i.push(e);for(let s of e.querySelectorAll(t))s instanceof HTMLVideoElement&&i.push(s);return i}videoIdentity(e){if(e.dataset.popmeltMediaId)return e.dataset.popmeltMediaId;let t=new URL(b(e),e.ownerDocument.baseURI).href,i=this.matchingVideos().filter(s=>b(s)===b(e));return`${$(t)}:${Math.max(0,i.indexOf(e))}`}newObjectId(){return globalThis.crypto?.randomUUID?.()??$(`${Date.now()}:${this.manualSequence++}:${Math.random()}`)}removeVideoRecords(e){for(let t of this.videoKeys.get(e)??[]){let i=this.records.get(t);i&&this.cancelBackwardAnalysis(i),i?.session?.dispose?.(),this.activeTrackingKey===t&&(this.activeTrackingKey=null),this.transientKeys.delete(t),this.records.delete(t)}this.videoKeys.delete(e)}removeVideo(e){this.removeVideoListeners(e),this.flushScheduledPersistence(e),this.removeVideoRecords(e),this.metadata.delete(e),this.analyzedSources.delete(e)}queueRefresh(){this.refreshQueued||this.destroyed||(this.refreshQueued=!0,queueMicrotask(()=>{this.refreshQueued=!1,this.readyPromise=this.refresh()}))}};function Ae(e={}){return new _(e)}var je="popmelt:media:video:v1";function X(e){if(!e||typeof e!="object")return!1;let t=e;return["left","top","width","height"].every(i=>typeof t[i]=="number"&&Number.isFinite(t[i]))}function Ie(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.start=="number"&&Number.isFinite(t.start)&&(t.end===void 0||typeof t.end=="number"&&Number.isFinite(t.end)&&t.end>=t.start)}function Fe(e){if(!e||typeof e!="object")return!1;let t=e;return(t.schemaVersion===1||t.schemaVersion===2||t.schemaVersion===3)&&typeof t.source=="string"&&typeof t.duration=="number"&&typeof t.updatedAt=="number"&&Array.isArray(t.tracks)&&t.tracks.every(i=>{if(!i||typeof i!="object")return!1;let s=i;return typeof s.id=="string"&&typeof s.label=="string"&&(s.origin==="manual"||s.origin==="detected")&&typeof s.createdAt=="number"&&typeof s.updatedAt=="number"&&(s.analyzedThrough===void 0||typeof s.analyzedThrough=="number"&&Number.isFinite(s.analyzedThrough))&&(s.segments===void 0||Array.isArray(s.segments)&&s.segments.every(Ie))&&Array.isArray(s.keyframes)&&s.keyframes.every(r=>{if(!r||typeof r!="object")return!1;let a=r;return typeof a.time=="number"&&typeof a.score=="number"&&(a.source==="manual"||a.source==="tracked")&&X(a.box)})&&(s.presentationKeyframes===void 0||Array.isArray(s.presentationKeyframes)&&s.presentationKeyframes.every(r=>{if(!r||typeof r!="object")return!1;let a=r;return typeof a.time=="number"&&typeof a.score=="number"&&(a.source==="manual"||a.source==="tracked")&&X(a.box)}))})}function Le(e={}){let t=e.namespace??je,i=()=>e.storage??window.localStorage,s=r=>`${t}:${r}`;return{load(r){try{let a=i().getItem(s(r));if(!a)return null;let o=JSON.parse(a);return Fe(o)?o:null}catch{return null}},save(r,a){i().setItem(s(r),JSON.stringify(a))},remove(r){i().removeItem(s(r))}}}function ze(){let e=new Map;return{load:t=>e.get(t)??null,save:(t,i)=>{e.set(t,i)},remove:t=>{e.delete(t)}}}export{L as a,O as b,z as c,oe as d,ne as e,q as f,fe as g,j as h,D as i,U as j,_ as k,Ae as l,Le as m,ze as n};
|
|
1
|
+
"use client";var e=(e,t=0,i=1)=>Math.min(i,Math.max(t,e));function t(e,t){let i=e.trim().toLowerCase();if(i.endsWith("%")){let e=Number.parseFloat(i);return Number.isFinite(e)?t*(e/100):0}if(i.endsWith("px")){let e=Number.parseFloat(i);return Number.isFinite(e)?e:0}return"center"===i?t/2:"right"===i||"bottom"===i?t:0}function i(e,i,s){let r=e.objectPosition.trim().split(/\s+/),a=r[0]||"50%",n=r[1]||"50%";return{x:t(a,e.rect.width-i),y:t(n,e.rect.height-s)}}function s(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0||e.naturalWidth<=0||e.naturalHeight<=0)return null;let s=e.ownerDocument.defaultView?.getComputedStyle(e)??getComputedStyle(e),r={rect:t,naturalWidth:e.naturalWidth,naturalHeight:e.naturalHeight,objectFit:s.objectFit||"fill",objectPosition:s.objectPosition||"50% 50%"},a=function(e){let{width:t,height:i}=e.rect,s=Math.max(1,e.naturalWidth),r=Math.max(1,e.naturalHeight),a=Math.min(t/s,i/r),n=Math.max(t/s,i/r);switch(e.objectFit){case"contain":return{width:s*a,height:r*a};case"cover":return{width:s*n,height:r*n};case"none":return{width:s,height:r};case"scale-down":{let e=Math.min(1,a);return{width:s*e,height:r*e}}default:return{width:t,height:i}}}(r);return{layout:r,rendered:a,position:i(r,a.width,a.height)}}function r(e,t){let i=s(e);if(!i)return null;let{layout:r,rendered:a,position:n}=i;if(t.x<r.rect.left||t.x>r.rect.left+r.rect.width||t.y<r.rect.top||t.y>r.rect.top+r.rect.height)return null;let o=(t.x-r.rect.left-n.x)/a.width,d=(t.y-r.rect.top-n.y)/a.height;return o>=0&&o<=1&&d>=0&&d<=1?{x:o,y:d}:null}function a(t,i){let r=s(t);if(!r)return null;let{layout:a,rendered:n,position:o}=r,d=(i.left-a.rect.left-o.x)/n.width,h=(i.top-a.rect.top-o.y)/n.height,l=(i.left+i.width-a.rect.left-o.x)/n.width,c=(i.top+i.height-a.rect.top-o.y)/n.height,u=e(Math.min(d,l)),m=e(Math.min(h,c)),g=e(Math.max(d,l)),y=e(Math.max(h,c));return g<=u||y<=m?null:{left:u,top:m,width:g-u,height:y-m}}function n(t,i){if(![i.left,i.top,i.width,i.height].every(Number.isFinite))return null;let r=s(t);if(!r)return null;let{layout:a,rendered:n,position:o}=r,{rect:d}=a,h=d.left+o.x+e(i.left)*n.width,l=d.top+o.y+e(i.top)*n.height,c=d.left+o.x+e(i.left+Math.max(0,i.width))*n.width,u=d.top+o.y+e(i.top+Math.max(0,i.height))*n.height,m=Math.max(d.left,h),g=Math.max(d.top,l),y=Math.min(d.left+d.width,c),f=Math.min(d.top+d.height,u);return y<=m||f<=g?null:{left:m,top:g,width:y-m,height:f-g}}function o(e){if(!e||"object"!=typeof e)return!1;let t=e;return["left","top","width","height"].every(e=>"number"==typeof t[e]&&Number.isFinite(t[e]))}function d(e){if(!e||"object"!=typeof e)return!1;let t=e;return"string"==typeof t.id&&"string"==typeof t.label&&"number"==typeof t.score&&("detected"===t.origin||"manual"===t.origin)&&o(t.box)&&(void 0===t.detectedBox||o(t.detectedBox))}function h(e){if(!e||"object"!=typeof e)return!1;let t=e;return"string"==typeof t.detectedLabel&&o(t.detectedBox)}function l(e){if(!e||"object"!=typeof e)return!1;let t=e;return 1===t.schemaVersion&&"string"==typeof t.source&&"string"==typeof t.imageHash&&"string"==typeof t.inferenceKey&&"string"==typeof t.dedupeKey&&"number"==typeof t.updatedAt&&Array.isArray(t.subjects)&&t.subjects.every(d)&&(void 0===t.suppressions||Array.isArray(t.suppressions)&&t.suppressions.every(h))}function c(e={}){let t=e.namespace??"popmelt:see:v1",i=()=>e.storage??window.localStorage,s=e=>`${t}:${e}`,r=e=>`${s(e)}:history`,a=e=>{try{let t=i().getItem(s(e));if(!t)return null;let r=JSON.parse(t);return l(r)?r:null}catch{return null}},n=e=>{try{let t=i().getItem(r(e));if(!t)return[];let s=JSON.parse(t);return Array.isArray(s)?s.filter(l).slice(0,10):[]}catch{return[]}};return{load:a,save(e,t){let o=a(e);if(o&&o.imageHash!==t.imageHash){let t=n(e).filter(e=>e.imageHash!==o.imageHash||e.updatedAt!==o.updatedAt);i().setItem(r(e),JSON.stringify([o,...t].slice(0,10)))}i().setItem(s(e),JSON.stringify(t))},remove(e){i().removeItem(s(e)),i().removeItem(r(e))},loadHistory:n}}function u(){let e=new Map,t=new Map;return{load:t=>e.get(t)??null,save:(i,s)=>{let r=e.get(i);if(r&&r.imageHash!==s.imageHash){let e=t.get(i)??[];t.set(i,[r,...e.filter(e=>e.imageHash!==r.imageHash||e.updatedAt!==r.updatedAt)].slice(0,10))}e.set(i,s)},remove:i=>{e.delete(i),t.delete(i)},loadHistory:e=>t.get(e)??[]}}function m(e){return{label:e.label,score:e.score,box:{...e.box}}}var g="img";function y(e){let t=2166136261;for(let i=0;i<e.length;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function f(e){return new URL(v(e),e.ownerDocument.baseURI).href}async function p(e){let t=f(e);try{let e=await fetch(t,{cache:"force-cache",credentials:"same-origin"});if(!e.ok)throw new Error(`Unable to hash image (${e.status})`);let i=await e.arrayBuffer();if(!globalThis.crypto?.subtle)throw new Error("SubtleCrypto unavailable");let s=await globalThis.crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(s),e=>e.toString(16).padStart(2,"0")).join("")}catch{return`source:${y(t)}:${e.naturalWidth}x${e.naturalHeight}`}}function v(e){return e.currentSrc||e.src||e.getAttribute("src")||""}function b(e,t){return{id:t.id,image:e,detection:m(t),detectedLabel:t.detectedLabel,detectedBox:t.detectedBox?{...t.detectedBox}:void 0,boundsOverridden:t.boundsOverridden,manual:"manual"===t.origin}}function w(e){return{id:e.id,label:e.detection.label,detectedLabel:e.detectedLabel,score:e.detection.score,box:{...e.detection.box},detectedBox:e.detectedBox?{...e.detectedBox}:void 0,origin:e.manual?"manual":"detected",boundsOverridden:e.boundsOverridden}}function x(e){return"manual"===e.origin||!0===e.boundsOverridden||!(!e.detectedLabel||e.label===e.detectedLabel)}function k(e,t){return t.x>=e.left&&t.x<=e.left+e.width&&t.y>=e.top&&t.y<=e.top+e.height}var M=class{constructor(e={}){this.options=e,this.surfaceKind="image",this.records=new Map,this.imageKeys=new Map,this.analyzedSources=new WeakMap,this.pending=new WeakMap,this.analysisMetadata=new WeakMap,this.suppressions=new WeakMap,this.writeChains=new WeakMap,this.pendingWrites=new Set,this.refreshQueued=!1,this.destroyed=!1,this.manualSequence=0,this.id=e.id??"see:image",this.readyPromise=this.refresh();let t=e.root??document;this.observer=!1!==e.observe&&typeof MutationObserver<"u"?new MutationObserver(()=>this.queueRefresh()):null,this.observer?.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src","srcset","sizes"]})}whenReady(){return this.readyPromise}listSubjects(){let e=[];for(let t of this.records.keys()){let i=this.resolve(t);i&&e.push(i)}return e}async refresh(){if(this.destroyed)return;let e=this.options.root??document,t=this.options.selector??g,i=new Set;e instanceof HTMLImageElement&&e.matches(t)&&i.add(e);for(let s of e.querySelectorAll(t))s instanceof HTMLImageElement&&i.add(s);for(let e of this.imageKeys.keys())(!i.has(e)||!e.isConnected)&&this.removeImage(e);if(this.options.recognition)for(let e of i)await this.analyze(e);else await Promise.all(Array.from(i,e=>this.analyze(e)))}hitTest(e){let t=null;for(let i of this.records.keys()){let s=this.resolve(i),r=this.records.get(i);if(!s||!r||!k(s.bounds,e))continue;let a=s.bounds.width*s.bounds.height;(!t||a<t.area||a===t.area&&r.detection.score>t.score)&&(t={subject:s,area:a,score:r.detection.score})}return t?.subject??null}resolve(e){let t=this.records.get(e);if(!t||!t.image.isConnected)return null;let i=n(t.image,t.detection.box);if(!i)return null;let s=t.image.getBoundingClientRect(),r=Math.round(1e3*t.detection.score)/1e3;return{key:e,label:t.detection.label,sourceElement:t.image,imageObject:this.imageObjectContext(t),bounds:i,surfaceBounds:{left:s.left,top:s.top,width:s.width,height:s.height},context:`${t.detection.label} ${t.manual?"labelled":"detected"} in ${t.image.alt||"image"}`,data:{kind:"image-object",label:t.detection.label,origin:t.manual?"manual":"detected",...t.detectedLabel?{detectedLabel:t.detectedLabel}:{},score:String(r),imageSrc:v(t.image)}}}restoreSubject(e,t){if(this.records.has(e))return this.resolve(e);let i=t.imageObject;if(!i)return null;let s=t.sourceElement?.dataAttributes,r=s?.["data-popmelt-media-id"]??s?.["data-popmelt-see-id"],a=this.matchingImages().find(t=>{let i=v(t),s=this.imageIdentity(t,i);return!(!e.startsWith(`${s}:`)||r&&s!==r)});if(!a)return null;let n=this.imageIdentity(a,v(a)),o=e.slice(n.length+1),d={left:i.normalizedBox.x,top:i.normalizedBox.y,width:i.normalizedBox.width,height:i.normalizedBox.height};if(!o||!Object.values(d).every(e=>Number.isFinite(e)&&e>=0&&e<=1))return null;let h=t.dataAttributes,l=t.subjectLabel??h?.label??t.textContent;if(!l)return null;let c=Number(h?.score),u="manual"===h?.origin;this.records.set(e,{id:o,image:a,detection:{label:l,score:Number.isFinite(c)?c:1,box:d},detectedLabel:h?.detectedLabel,detectedBox:u?void 0:{...d},boundsOverridden:!0,manual:u});let m=this.imageKeys.get(a)??new Set;if(m.add(e),this.imageKeys.set(a,m),!this.analysisMetadata.has(a)){let e=f(a);this.analysisMetadata.set(a,{storeKey:`${this.id}:${n}`,source:e,imageHash:`recovered:${y(e)}`,inferenceKey:"",dedupeKey:""}),this.suppressions.set(a,[])}return this.persistImage(a),this.resolve(e)}imageObjectContext(e){let{image:t,detection:{box:i}}=e;return{src:v(t),alt:t.alt,width:t.naturalWidth,height:t.naturalHeight,normalizedBox:{x:i.left,y:i.top,width:i.width,height:i.height},box:{x:i.left*t.naturalWidth,y:i.top*t.naturalHeight,width:i.width*t.naturalWidth,height:i.height*t.naturalHeight}}}async captureSubject(e){let t=this.records.get(e);if(!t?.image.isConnected||!t.image.complete)return null;let{box:i}=this.imageObjectContext(t);if(i.width<=0||i.height<=0)return null;let s=Math.min(1,1024/Math.max(i.width,i.height)),r=document.createElement("canvas");r.width=Math.max(1,Math.round(i.width*s)),r.height=Math.max(1,Math.round(i.height*s));let a=r.getContext("2d");return a?(a.drawImage(t.image,i.x,i.y,i.width,i.height,0,0,r.width,r.height),new Promise((e,t)=>{try{r.toBlob(e,"image/webp",.95)}catch(e){t(e)}})):null}beginCreate(e){let t=this.matchingImages();for(let i=t.length-1;i>=0;i-=1){let s=t[i];if(!s)continue;let a=r(s,e);if(!a)continue;let n=v(s),o=this.imageIdentity(s,n),d=`manual:${this.newObjectId()}`,h=`${o}:${d}`,l={label:"object",score:1,box:{left:a.x,top:a.y,width:0,height:0}},c=!1,u=!1,m=()=>{if(u)return;u=!0,this.records.set(h,{id:d,image:s,detection:l,manual:!0});let e=this.imageKeys.get(s)??new Set;e.add(h),this.imageKeys.set(s,e)};return{key:h,update:e=>{if(c)return null;m();let t=this.clampedImagePoint(s,e);return t?(l.box={left:Math.min(a.x,t.x),top:Math.min(a.y,t.y),width:Math.abs(t.x-a.x),height:Math.abs(t.y-a.y)},this.resolve(h)):this.resolve(h)},commit:()=>c?null:(m(),this.persistImage(s),this.resolve(h)),cancel:()=>{c||(c=!0,u&&this.removeSubject(h))}}}return null}renameSubject(e,t){let i=this.records.get(e),s=t.trim();return i&&s?(!i.manual&&!i.detectedLabel&&(i.detectedLabel=i.detection.label),i.detection.label=s,this.persistImage(i.image),this.resolve(e)):null}updateSubjectBounds(e,t){let i=this.records.get(e);if(!i)return null;let s=a(i.image,t);return s?(i.detection.box=s,i.boundsOverridden=!0,this.persistImage(i.image),this.resolve(e)):null}removeSubject(e){let t=this.records.get(e);if(!t)return;if(!t.manual){let e=this.suppressions.get(t.image)??[];e.push({detectedLabel:t.detectedLabel??t.detection.label,detectedBox:{...t.detectedBox??t.detection.box}}),this.suppressions.set(t.image,e)}this.records.delete(e);let i=this.imageKeys.get(t.image);i?.delete(e),0===i?.size&&this.imageKeys.delete(t.image),this.persistImage(t.image)}async destroy(){this.destroyed||(this.destroyed=!0,this.observer?.disconnect(),this.records.clear(),this.imageKeys.clear(),await Promise.allSettled(this.pendingWrites),await(this.options.recognition?.dispose?.()))}queueRefresh(){this.refreshQueued||this.destroyed||(this.refreshQueued=!0,queueMicrotask(()=>{this.refreshQueued=!1,this.readyPromise=this.refresh()}))}async analyze(e){let t=v(e);if(!t||this.analyzedSources.get(e)===t)return;let i=this.pending.get(e);if(i)return i.source===t?i.promise:(await i.promise,this.analyze(e));this.analyzedSources.has(e)&&this.removeImage(e);let s={source:t,promise:Promise.resolve()},r=(async()=>{try{if(await(i=e,i.complete&&i.naturalWidth>0&&i.naturalHeight>0?Promise.resolve():new Promise((e,t)=>{let s=()=>{a(),e()},r=()=>{a(),t(new Error(`Unable to load image: ${v(i)}`))},a=()=>{i.removeEventListener("load",s),i.removeEventListener("error",r)};i.addEventListener("load",s,{once:!0}),i.addEventListener("error",r,{once:!0})})),this.destroyed)return;let s=f(e),r=this.imageIdentity(e,t),a=`${this.id}:${r}`,n=this.options.recognition,o=this.options.store?await this.options.store.load(a):null;if(this.destroyed||v(e)!==t)return;let d=n?.cacheKey??o?.inferenceKey??"",h=n?.configurationKey??o?.dedupeKey??"",l=o?.source===s,c=!(!e.dataset.popmeltMediaId&&!e.dataset.popmeltSeeId),u=l||c;if(o&&u){let t=new Map(o.subjects.map(e=>[e.id,e]));for(let i of this.imageSubjects(e))t.set(i.id,i);this.replaceImageRecords(e,r,[...t.values()]),this.suppressions.set(e,[...o.suppressions??[]]),this.analysisMetadata.set(e,{storeKey:a,source:s,imageHash:o.imageHash,inferenceKey:o.inferenceKey,dedupeKey:o.dedupeKey})}if(this.options.hydrateOnly)return void this.analyzedSources.set(e,t);let m=this.options.store?await(this.options.imageHasher??p)(e):"ephemeral";if(this.destroyed||v(e)!==t)return;if(o&&u&&o.imageHash===m&&(!n||o.inferenceKey===d&&o.dedupeKey===h))return this.analysisMetadata.set(e,{storeKey:a,source:s,imageHash:m,inferenceKey:d,dedupeKey:h}),this.analyzedSources.set(e,t),void await this.saveImage(e);let g=u&&o?.imageHash===m;if(o&&!g){let t=new Set(o.subjects.map(e=>e.id)),i=o.subjects.filter(x);this.replaceImageRecords(e,r,[...i,...this.imageSubjects(e).filter(e=>!t.has(e.id))]),this.suppressions.set(e,[])}if(this.analysisMetadata.set(e,{storeKey:a,source:s,imageHash:m,inferenceKey:g?o.inferenceKey:"",dedupeKey:g?o.dedupeKey:""}),!n)return this.analyzedSources.set(e,t),void await this.saveImage(e);let y=await n.detect(e);if(this.destroyed||v(e)!==t)return;let b=this.suppressions.get(e)??[],w=n.reconcile(y,this.imageSubjects(e),b);this.replaceImageRecords(e,r,w),this.suppressions.set(e,[...b]),this.analysisMetadata.set(e,{storeKey:a,source:s,imageHash:m,inferenceKey:d,dedupeKey:h}),this.analyzedSources.set(e,t),await this.saveImage(e)}catch(t){this.options.onError?.(t,e)}finally{this.pending.get(e)===s&&this.pending.delete(e)}var i})();return s.promise=r,this.pending.set(e,s),r}replaceImageRecords(e,t,i){this.removeImage(e);let s=new Set;for(let r of i){let i=`${t}:${r.id}`;s.add(i),this.records.set(i,b(e,r))}this.imageKeys.set(e,s)}imageIdentity(e,t){if(e.dataset.popmeltMediaId)return e.dataset.popmeltMediaId;if(e.dataset.popmeltSeeId)return e.dataset.popmeltSeeId;let i=new URL(t,e.ownerDocument.baseURI).href,s=this.options.root??e.ownerDocument,r=this.options.selector??g,a=Array.from(s.querySelectorAll(r)).filter(e=>v(e)===t),n=Math.max(0,a.indexOf(e));return`${y(i)}:${n}`}matchingImages(){let e=this.options.root??document,t=this.options.selector??g,i=[];e instanceof HTMLImageElement&&e.matches(t)&&i.push(e);for(let s of e.querySelectorAll(t))s instanceof HTMLImageElement&&i.push(s);return i}clampedImagePoint(e,t){let i=n(e,{left:0,top:0,width:1,height:1});return i?r(e,{x:Math.max(i.left,Math.min(i.left+i.width,t.x)),y:Math.max(i.top,Math.min(i.top+i.height,t.y))}):null}newObjectId(){let e=globalThis.crypto?.randomUUID?.();return e||y(`${Date.now()}:${this.manualSequence++}:${Math.random().toString(36)}`)}persistImage(e){let t=this.persistencePayload(e);if(!t)return Promise.resolve();let i=(this.writeChains.get(e)??Promise.resolve()).catch(()=>{}).then(()=>t.store.save(t.key,t.analysis)).catch(t=>{this.options.onError?.(t,e)});return this.writeChains.set(e,i),this.pendingWrites.add(i),i.finally(()=>this.pendingWrites.delete(i)),i}async saveImage(e){await this.persistImage(e)}imageSubjects(e){return Array.from(this.imageKeys.get(e)??[]).map(e=>this.records.get(e)).filter(e=>!!e).map(w)}persistencePayload(e){let t=this.options.store,i=this.analysisMetadata.get(e);if(!t||!i)return null;let s=this.imageSubjects(e),r={schemaVersion:1,source:i.source,imageHash:i.imageHash,inferenceKey:i.inferenceKey,dedupeKey:i.dedupeKey,subjects:s,suppressions:this.suppressions.get(e)??[],updatedAt:Date.now()};return{store:t,key:i.storeKey,analysis:r}}removeImage(e){for(let t of this.imageKeys.get(e)??[])this.records.delete(t);this.imageKeys.delete(e),this.analyzedSources.delete(e),this.analysisMetadata.delete(e),this.suppressions.delete(e)}};function T(e={}){return new M(e)}var S=(e,t=0,i=1)=>Math.min(i,Math.max(t,e));function K(e){let t=e.getBoundingClientRect();if(t.width<=0||t.height<=0||e.videoWidth<=0||e.videoHeight<=0)return null;let i=e.ownerDocument.defaultView?.getComputedStyle(e)??getComputedStyle(e),s=i.objectFit||"fill",r=Math.min(t.width/e.videoWidth,t.height/e.videoHeight),a=Math.max(t.width/e.videoWidth,t.height/e.videoHeight),n="contain"===s?r:"cover"===s?a:"none"===s?1:"scale-down"===s?Math.min(1,r):null,o=n?{width:e.videoWidth*n,height:e.videoHeight*n}:{width:t.width,height:t.height},d=(i.objectPosition||"50% 50%").split(/\s+/),h=(e,t)=>e.endsWith("%")?t*(Number.parseFloat(e)/100):e.endsWith("px")?Number.parseFloat(e):"center"===e?t/2:"right"===e||"bottom"===e?t:0;return{rect:t,rendered:o,position:{x:h(d[0]||"50%",t.width-o.width),y:h(d[1]||"50%",t.height-o.height)}}}function A(e,t){let i=K(e);if(!i)return null;let{rect:s,rendered:r,position:a}=i;if(t.x<s.left||t.x>s.right||t.y<s.top||t.y>s.bottom)return null;let n=(t.x-s.left-a.x)/r.width,o=(t.y-s.top-a.y)/r.height;return n>=0&&n<=1&&o>=0&&o<=1?{x:n,y:o}:null}function j(e,t){let i=K(e);if(!i)return null;let{rect:s,rendered:r,position:a}=i,n=s.left+a.x+S(t.left)*r.width,o=s.top+a.y+S(t.top)*r.height,d=s.left+a.x+S(t.left+Math.max(0,t.width))*r.width,h=s.top+a.y+S(t.top+Math.max(0,t.height))*r.height,l=Math.max(s.left,n),c=Math.max(s.top,o),u=Math.min(s.right,d),m=Math.min(s.bottom,h);return u<=l||m<=c?null:{left:l,top:c,width:u-l,height:m-c}}function I(e,t){let i=K(e);if(!i)return null;let{rect:s,rendered:r,position:a}=i,n=(t.left-s.left-a.x)/r.width,o=(t.top-s.top-a.y)/r.height,d=(t.left+t.width-s.left-a.x)/r.width,h=(t.top+t.height-s.top-a.y)/r.height,l=S(Math.min(n,d)),c=S(Math.min(o,h)),u=S(Math.max(n,d)),m=S(Math.max(o,h));return u<=l||m<=c?null:{left:l,top:c,width:u-l,height:m-c}}var F=1/60,L=.001;function z(e){let t=2166136261;for(let i=0;i<e.length;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function H(e){return e.currentSrc||e.src||e.querySelector("source")?.src||e.getAttribute("src")||""}function P(e,t,i){let s=(e,t)=>e+(t-e)*i;return{left:s(e.left,t.left),top:s(e.top,t.top),width:s(e.width,t.width),height:s(e.height,t.height)}}function R(e,t){return e.find(e=>t>=e.start-.001&&(void 0===e.end||t<=e.end+.001))??null}function B(e){return!R(e.segments,e.video.currentTime)}function $(e){return e?.motion.createSmoother()??{smooth:e=>({...e,box:{...e.box}})}}function V(e){return{visible:!B(e),misses:e.misses,hits:e.hits,lostAt:e.lostAt}}function W(e,t){if(t?.length)return t.map(e=>({...e})).sort((e,t)=>e.start-t.start);let i=e.reduce((e,t)=>Math.min(e,t.time),Number.POSITIVE_INFINITY);return Number.isFinite(i)?[{start:i}]:[]}function E(e,t,i){if(0===e.length||i&&!R(i,t))return null;let s=[...e].sort((e,t)=>e.time-t.time),r=s.findIndex(e=>e.time>=t);if(r<=0)return{...s[0],box:{...s[0].box}};if(r<0){let e=s[s.length-1];return{...e,box:{...e.box}}}let a=s[r-1],n=s[r],o=Math.max(Number.EPSILON,n.time-a.time),d=Math.max(0,Math.min(1,(t-a.time)/o));return{time:t,box:P(a.box,n.box,d),score:a.score+(n.score-a.score)*d,source:"manual"===a.source||"manual"===n.source?"manual":"tracked"}}function C(e){return!e.video.paused&&e.liveFrame?{...e.liveFrame,box:{...e.liveFrame.box}}:E(e.presentationKeyframes,e.video.currentTime,e.segments)}function O(e,t){if(!function(e,t){return t.x>=e.left&&t.x<=e.left+e.width&&t.y>=e.top&&t.y<=e.top+e.height}(e.bounds,t))return!1;let i=e.outline;if(!i||i.length<3)return!0;let s=(t.x-e.bounds.left)/e.bounds.width,r=(t.y-e.bounds.top)/e.bounds.height,a=!1;for(let e=0,t=i.length-1;e<i.length;t=e++){let n=i[e],o=i[t];n.y>r!=o.y>r&&s<(o.x-n.x)*(r-n.y)/(o.y-n.y)+n.x&&(a=!a)}return a}function N(e){let t=e.outline;if(!t||t.length<3)return e.bounds.width*e.bounds.height;let i=0;for(let e=0;e<t.length;e+=1){let s=t[e],r=t[(e+1)%t.length];i+=s.x*r.y-r.x*s.y}return Math.abs(i)/2*e.bounds.width*e.bounds.height}function q(e,t){return(t.outline?.length?t.outline.map(e=>({x:t.bounds.left+e.x*t.bounds.width,y:t.bounds.top+e.y*t.bounds.height})):[{x:t.bounds.left,y:t.bounds.top},{x:t.bounds.left+t.bounds.width,y:t.bounds.top},{x:t.bounds.left+t.bounds.width,y:t.bounds.top+t.bounds.height},{x:t.bounds.left,y:t.bounds.top+t.bounds.height}]).every(t=>O(e,t))}function D(e,t){let i=Math.max(e.left,t.left),s=Math.max(e.top,t.top),r=Math.min(e.left+e.width,t.left+t.width),a=Math.min(e.top+e.height,t.top+t.height),n=Math.max(0,r-i)*Math.max(0,a-s),o=e.width*e.height+t.width*t.height-n;return o>0?n/o:0}var U=class{constructor(e={}){this.options=e,this.surfaceKind="video",this.records=new Map,this.videoKeys=new Map,this.metadata=new WeakMap,this.analyzedSources=new WeakMap,this.listeners=new Map,this.frameHandles=new Map,this.persistTimers=new Map,this.writeChains=new WeakMap,this.pendingWrites=new Set,this.refreshQueued=!1,this.destroyed=!1,this.manualSequence=0,this.detectedSequence=0,this.activeTrackingKey=null,this.segmentationGeneration=0,this.transientKeys=new Set,this.segmentationRequestSignatures=new WeakMap,this.changeListeners=new Set,this.id=e.id??"see:video",this.readyPromise=this.refresh();let t=e.root??document;this.observer=!1!==e.observe&&typeof MutationObserver<"u"?new MutationObserver(()=>this.queueRefresh()):null,this.observer?.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["src"]})}whenReady(){return this.readyPromise}subscribe(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}listSubjects(){return Array.from(this.records.keys(),e=>this.transientKeys.has(e)?null:this.resolve(e)).filter(e=>!!e)}async refresh(){if(this.destroyed)return;let e=new Set(this.matchingVideos());for(let t of this.videoKeys.keys())(!e.has(t)||!t.isConnected)&&this.removeVideo(t);await Promise.all(Array.from(e,e=>this.analyze(e)))}hitTest(e){return this.hitTestAll(e)[0]??null}hitTestAll(e){let t=[];for(let i of this.records.keys()){let s=this.resolve(i);!s||!O(s,e)||t.push({subject:s,area:N(s)})}return this.options.segmentation&&this.scheduleSegmentation(e),t.sort((e,t)=>q(e.subject,t.subject)?1:q(t.subject,e.subject)?-1:e.area-t.area).map(({subject:e})=>e)}promoteSubject(e){let t=this.records.get(e);return t?this.transientKeys.delete(e)?(this.activateTrackingRecord(t),this.persistVideo(t.video),this.startSession(t,!0).then(()=>this.scheduleBackwardAnalysis(t)),this.resolve(e)):this.resolve(e):null}resolve(e){let t=this.records.get(e);if(!t?.video.isConnected)return null;let i=C(t);if(!i)return null;let s=j(t.video,i.box);if(!s)return null;let r=t.video.getBoundingClientRect();return{key:e,label:t.label,sourceElement:t.video,videoObject:this.videoObjectContext(t,i),trackingAnchors:t.anchors.map(e=>({...e})),outline:i.outline?.map(e=>({...e})),bounds:s,surfaceBounds:{left:r.left,top:r.top,width:r.width,height:r.height},context:`${t.label} tracked in video at ${t.video.currentTime.toFixed(2)}s`,data:{kind:"video-object",label:t.label,origin:t.origin,score:String(Math.round(1e3*i.score)/1e3),videoSrc:H(t.video),currentTime:String(t.video.currentTime)}}}async captureSubject(e){let t=this.records.get(e);if(!t||t.video.readyState<2)return null;let i=C(t);if(!i)return null;let{video:s}=t,r={x:i.box.left*s.videoWidth,y:i.box.top*s.videoHeight,width:i.box.width*s.videoWidth,height:i.box.height*s.videoHeight},a=Math.min(1,1024/Math.max(r.width,r.height)),n=document.createElement("canvas");n.width=Math.max(1,Math.round(r.width*a)),n.height=Math.max(1,Math.round(r.height*a));let o=n.getContext("2d");return o?(o.drawImage(s,r.x,r.y,r.width,r.height,0,0,n.width,n.height),new Promise((e,t)=>{try{n.toBlob(e,"image/webp",.95)}catch(e){t(e)}})):null}beginCreate(e){let t=this.matchingVideos();for(let i=t.length-1;i>=0;i-=1){let s=t[i];if(!s)continue;let r=A(s,e);if(!r)continue;let a=this.videoIdentity(s),n=`manual:${this.newObjectId()}`,o=`${a}:${n}`,d=Date.now(),h={time:s.currentTime,box:{left:r.x,top:r.y,width:0,height:0},score:1,source:"manual"},l=$(this.options.tracking),c={key:o,id:n,video:s,label:"object",origin:"manual",keyframes:[h],segments:[{start:s.currentTime}],anchors:[],presentationKeyframes:[l.smooth(h)],smoother:l,createdAt:d,updatedAt:d,misses:0,hits:0,analyzedThrough:h.time},u=!1,m=!1,g=()=>{if(m)return;m=!0,this.records.set(o,c);let e=this.videoKeys.get(s)??new Set;e.add(o),this.videoKeys.set(s,e)};return{key:o,update:e=>{if(u)return null;g();let t=A(s,e);return t&&(h.box={left:Math.min(r.x,t.x),top:Math.min(r.y,t.y),width:Math.abs(t.x-r.x),height:Math.abs(t.y-r.y)},c.smoother=$(this.options.tracking),c.presentationKeyframes=[c.smoother.smooth(h)]),this.resolve(o)},commit:()=>u?null:(g(),c.backwardSeedTime=h.time,this.activateTrackingRecord(c),this.persistVideo(s),this.startSession(c,!0).then(()=>this.scheduleBackwardAnalysis(c)),this.resolve(o)),cancel:()=>{u||(u=!0,m&&this.removeSubject(o))}}}return null}renameSubject(e,t){let i=this.records.get(e),s=t.trim();return i&&s?(i.label=s,i.updatedAt=Date.now(),this.activateTrackingRecord(i),this.persistVideo(i.video),this.resolve(e)):null}updateSubjectBounds(e,t){let i=this.records.get(e);if(!i)return null;let s=I(i.video,t);if(!s)return null;this.openSegment(i,i.video.currentTime),this.insertKeyframe(i,{time:i.video.currentTime,box:s,score:1,source:"manual"}),i.liveFrame=void 0,i.trackingFailed=!1,i.misses=0,i.hits=0,i.lostAt=void 0,i.analyzedThrough=i.video.currentTime;let r=R(i.segments,i.video.currentTime);return r&&Math.abs(r.start-i.video.currentTime)<=.05&&(i.backwardSeedTime=i.video.currentTime,this.cancelBackwardAnalysis(i)),this.activateTrackingRecord(i),this.persistVideo(i.video),this.startSession(i,!0).then(()=>this.reseed(i)).then(()=>this.scheduleBackwardAnalysis(i)),this.resolve(e)}updateSubjectTrackingAnchors(e,t){let i=this.records.get(e);return i?(i.anchors=t.slice(0,3).map(e=>({x:Math.max(0,Math.min(1,e.x)),y:Math.max(0,Math.min(1,e.y))})),i.updatedAt=Date.now(),i.trackingFailed=!1,i.analyzedThrough=i.video.currentTime,void 0!==i.backwardSeedTime&&this.cancelBackwardAnalysis(i),this.activateTrackingRecord(i),this.persistVideo(i.video),this.startSession(i,!0).then(()=>this.reseed(i)).then(()=>this.scheduleBackwardAnalysis(i)),this.resolve(e)):null}removeSubject(e){let t=this.records.get(e);if(!t)return;this.cancelBackwardAnalysis(t),t.session?.dispose?.(),this.activeTrackingKey===e&&(this.activeTrackingKey=null),this.transientKeys.delete(e),this.records.delete(e);let i=this.videoKeys.get(t.video);i?.delete(e),0===i?.size&&this.videoKeys.delete(t.video),this.persistVideo(t.video)}async destroy(){if(this.destroyed)return;this.destroyed=!0,this.observer?.disconnect();for(let e of this.listeners.keys())this.removeVideoListeners(e);await Promise.all(Array.from(this.persistTimers.keys(),e=>this.flushScheduledPersistence(e)));let e=Array.from(this.records.values(),e=>e.backwardAnalysis?.promise).filter(e=>!!e);await Promise.allSettled(Array.from(this.records.values(),e=>(this.cancelBackwardAnalysis(e),e.session?.dispose?.()))),await Promise.allSettled(e),this.records.clear(),this.videoKeys.clear(),this.changeListeners.clear(),await Promise.allSettled(this.pendingWrites)}scheduleSegmentation(e){let t=this.options.segmentation;if(!t||this.destroyed)return;let i=this.matchingVideos();for(let s=i.length-1;s>=0;s-=1){let r=i[s];if(!r||r.readyState<2)continue;let a=A(r,e);if(!a)continue;let n=[Math.round(30*r.currentTime),Math.round(256*a.x),Math.round(256*a.y)].join(":");if(this.segmentationRequestSignatures.get(r)===n)return;this.segmentationRequestSignatures.set(r,n);let o=++this.segmentationGeneration,d=r.currentTime;return void t.segment(r,d,a).then(e=>{if(!e||this.destroyed||o!==this.segmentationGeneration||!r.isConnected)return;let t=Array.from(this.videoKeys.get(r)??[]).map(e=>this.records.get(e)).filter(e=>!!e).find(t=>{let i=C(t);return i&&D(i.box,e.box)>=.65});this.clearTransientSubjects(r,t?.key),t||this.addDetectedSubject(r,d,e);for(let e of this.changeListeners)e()}).catch(e=>this.options.onError?.(e,r))}}addDetectedSubject(e,t,i){let s=this.videoIdentity(e),r=`detected:${z([t.toFixed(3),i.box.left.toFixed(4),i.box.top.toFixed(4),i.box.width.toFixed(4),i.box.height.toFixed(4),this.detectedSequence++].join(":"))}`,a=`${s}:${r}`,n=e.currentTime,o={time:n,box:{...i.box},score:i.score,source:"tracked",outline:i.outline?.map(e=>({...e}))},d=$(this.options.tracking),h=Date.now(),l={key:a,id:r,video:e,label:i.label?.trim()||"object",origin:"detected",keyframes:[o],segments:[{start:n}],anchors:[],presentationKeyframes:[d.smooth(o)],smoother:d,createdAt:h,updatedAt:h,misses:0,hits:0,analyzedThrough:n,backwardSeedTime:n};this.records.set(a,l),this.transientKeys.add(a);let c=this.videoKeys.get(e)??new Set;c.add(a),this.videoKeys.set(e,c)}clearTransientSubjects(e,t){let i=this.videoKeys.get(e);if(i)for(let e of[...i])e===t||!this.transientKeys.delete(e)||(this.records.delete(e),i.delete(e))}async analyze(e){let t=H(e);if(t&&this.analyzedSources.get(e)!==t)try{if(await(i=e,i.readyState>=1&&i.videoWidth>0&&i.videoHeight>0?Promise.resolve():new Promise((e,t)=>{let s=()=>{a(),e()},r=()=>{a(),t(new Error(`Unable to load video: ${H(i)}`))},a=()=>{i.removeEventListener("loadedmetadata",s),i.removeEventListener("error",r)};i.addEventListener("loadedmetadata",s,{once:!0}),i.addEventListener("error",r,{once:!0})})),this.destroyed||H(e)!==t)return;let s=this.videoIdentity(e),r=new URL(t,e.ownerDocument.baseURI).href,a=`${this.id}:${s}`,n=this.options.store?await this.options.store.load(a):null;if(this.destroyed||H(e)!==t)return;this.metadata.set(e,{storeKey:a,source:r,identity:s});let o=!!e.dataset.popmeltMediaId;n&&(n.source===r||o)?this.replaceVideoRecords(e,s,n.tracks):this.videoKeys.has(e)||this.videoKeys.set(e,new Set),this.analyzedSources.set(e,t),this.addVideoListeners(e)}catch(t){this.options.onError?.(t,e)}var i}addVideoListeners(e){if(this.listeners.has(e))return;let t=()=>{this.clearLiveFrames(e),this.activateMostRecentRecord(e);let t=this.activeRecordFor(e);if(this.options.tracking&&t&&!t.session&&(void 0===t.analyzedThrough||t.analyzedThrough<e.duration-L)){let i=this.startSession(t,!0);return e.pause(),void i.then(()=>{!this.destroyed&&t.session&&e.play()})}t&&this.scheduleBackwardAnalysis(t),this.scheduleFrame(e)},i=()=>{this.clearLiveFrames(e);let t=this.activeRecordFor(e);t&&this.scheduleBackwardAnalysis(t),this.flushScheduledPersistence(e)},s=()=>{let t=this.activeRecordFor(e);void 0!==t?.lastTrackedMediaTime&&(t.analyzedThrough=e.duration,t.lastTrackedMediaTime=void 0,t.session?.dispose?.(),t.session=void 0,this.schedulePersistence(e)),i()},r=()=>{let t=this.activeRecordFor(e);if(!t)return;let i=t.lastTrackedMediaTime;if(e.loop&&void 0!==i&&i>=e.duration-.25&&e.currentTime+.25<i&&(t.analyzedThrough??0)>=i-.25){E(t.presentationKeyframes,e.currentTime,t.segments)&&(t.liveFrame=void 0),t.analyzedThrough=Math.max(0,e.currentTime-2*L),t.lastTrackedMediaTime=void 0;let i=t.session;return t.session=void 0,Promise.resolve(t.tracking).finally(async()=>{await(i?.dispose?.()),!this.destroyed&&this.activeTrackingKey===t.key&&(await this.startSession(t),this.scheduleBackwardAnalysis(t))}),void this.schedulePersistence(e)}this.clearLiveFrames(e),t.session&&this.reseed(t)};e.addEventListener("play",t),e.addEventListener("pause",i),e.addEventListener("ended",s),e.addEventListener("seeked",r),this.listeners.set(e,()=>{e.removeEventListener("play",t),e.removeEventListener("pause",i),e.removeEventListener("ended",s),e.removeEventListener("seeked",r)}),e.paused||(this.activateMostRecentRecord(e),this.scheduleFrame(e))}removeVideoListeners(e){this.listeners.get(e)?.(),this.listeners.delete(e);let t=e,i=this.frameHandles.get(e);void 0!==i&&(t.cancelVideoFrameCallback?.(i),cancelAnimationFrame(i)),this.frameHandles.delete(e)}scheduleFrame(e){if(this.destroyed||e.paused||this.frameHandles.has(e))return;let t=e,i=(t,i)=>{this.frameHandles.delete(e),this.trackVideo(e,i.mediaTime),this.scheduleFrame(e)};t.requestVideoFrameCallback?this.frameHandles.set(e,t.requestVideoFrameCallback(i)):this.frameHandles.set(e,requestAnimationFrame(()=>i(performance.now(),{mediaTime:e.currentTime})))}async trackVideo(e,t){let i=this.activeRecordFor(e);if(!i||i.tracking||i.trackingFailed||void 0!==i.analyzedThrough&&t<=i.analyzedThrough+L)return;let s=this.options.tracking?.motion;if(!s)return;let r=s.attempt({state:V(i),time:t,maximumFramesPerSecond:Math.max(1,this.options.maxTrackingFramesPerSecond??30)});void 0!==i.lastTrackedMediaTime&&Math.abs(t-i.lastTrackedMediaTime)<.9/r.framesPerSecond||(i.session||await this.startSession(i),i.session&&this.activeTrackingKey===i.key&&(i.lastTrackedMediaTime=t,i.tracking=i.session.track(e,t,r.tracking).then(r=>{if(this.destroyed||this.activeTrackingKey!==i.key)return;i.analyzedThrough=Math.max(i.analyzedThrough??t,t);let a=s.observe({state:V(i),time:t,observation:r});(function(e,t){e.misses=t.misses,e.hits=t.hits,e.lostAt=t.lostAt})(i,a.state),r&&"reopen"===a.action&&this.openSegment(i,t),!r||"accept"!==a.action&&"reopen"!==a.action?"close"===a.action&&(i.liveFrame=void 0,this.closeSegment(i,i.keyframes[i.keyframes.length-1]?.time??t)):this.acceptObservation(i,{...r,source:"tracked"}),this.schedulePersistence(e)}).catch(e=>this.failTracking(i,e)).finally(()=>{i.tracking=void 0}),await i.tracking))}async startSession(e,t=!1){if(e.initializing)return void await e.initializing;if(!this.options.tracking||e.session||e.trackingFailed||this.activeTrackingKey!==e.key||e.video.paused&&!t)return;let i=E(e.keyframes,e.video.currentTime,e.segments)??e.liveFrame;!i||e.video.readyState<2||(e.initializing=this.options.tracking.createSession({video:e.video,time:e.video.currentTime,box:i.box,anchors:e.anchors}).then(t=>{this.destroyed||this.activeTrackingKey!==e.key?t.dispose?.():e.session=t}).catch(t=>this.failTracking(e,t)).finally(()=>{e.initializing=void 0}),await e.initializing)}async reseed(e){let t=E(e.keyframes,e.video.currentTime,e.segments);if(!t)return e.session?.dispose?.(),e.session=void 0,e.lostAt=e.video.currentTime,e.liveFrame=void 0,e.misses=0,void(e.hits=0);e.lostAt=void 0,e.misses=0,e.hits=0;try{e.session?.reseed&&await e.session.reseed({video:e.video,time:e.video.currentTime,box:t.box,anchors:e.anchors})}catch(t){this.failTracking(e,t)}}failTracking(e,t){e.trackingFailed=!0,e.liveFrame=void 0,e.session?.dispose?.(),e.session=void 0,this.options.onError?.(t,e.video)}activeRecordFor(e){if(!this.activeTrackingKey)return null;let t=this.records.get(this.activeTrackingKey);return t?.video===e?t:null}activateMostRecentRecord(e){if(this.activeRecordFor(e))return;let t=Array.from(this.videoKeys.get(e)??[]).map(e=>this.records.get(e)).filter(e=>!!e).sort((e,t)=>t.updatedAt-e.updatedAt)[0];t&&this.activateTrackingRecord(t)}activateTrackingRecord(e){if(this.activeTrackingKey===e.key)return;let t=this.activeTrackingKey?this.records.get(this.activeTrackingKey):void 0;this.activeTrackingKey=e.key,t&&(this.cancelBackwardAnalysis(t),t.session?.dispose?.(),t.session=void 0,t.lastTrackedMediaTime=void 0,t.liveFrame=void 0),e.liveFrame=void 0,e.trackingFailed=!1,e.lastTrackedMediaTime=void 0,e.misses=0,e.hits=0,e.lostAt=B(e)?e.video.currentTime:void 0}scheduleBackwardAnalysis(e){if(this.destroyed||!this.options.tracking||void 0===e.backwardSeedTime||e.backwardSeedTime<=L||e.backwardAnalysis||e.initializing||this.activeTrackingKey!==e.key)return;let t={cancelled:!1,promise:Promise.resolve()};e.backwardAnalysis=t,t.promise=this.runBackwardAnalysis(e,t).catch(i=>{t.cancelled||this.options.onError?.(i,e.video)}).finally(()=>{e.backwardAnalysis===t&&(e.backwardAnalysis=void 0,!t.cancelled&&void 0!==e.backwardSeedTime&&(e.backwardSeedTime=void 0),t.cancelled&&!this.destroyed&&this.activeTrackingKey===e.key&&queueMicrotask(()=>this.scheduleBackwardAnalysis(e)))})}cancelBackwardAnalysis(e){let t=e.backwardAnalysis;t&&(t.cancelled=!0)}async runBackwardAnalysis(e,t){let i=e.backwardSeedTime;if(void 0===i)return;let s=await this.options.tracking.motion.analyzeBackward({source:e.video,seedTime:i,keyframes:e.keyframes,anchors:e.anchors,maximumFramesPerSecond:this.options.maxTrackingFramesPerSecond??30,cancelled:()=>t.cancelled||this.destroyed,forwardWork:()=>e.initializing??e.tracking});if(t.cancelled||this.destroyed)return;let r=R(e.segments,i);r&&(e.keyframes=s.keyframes,r.start=Math.min(r.start,s.earliestTime),e.updatedAt=Date.now(),this.rebuildPresentationTrack(e),this.schedulePersistence(e.video))}acceptObservation(e,t){let i=[...e.keyframes].reverse().find(e=>e.outline?.length)?.outline,s=this.insertKeyframe(e,{...t,outline:t.outline??i});return e.video.paused||(e.liveFrame={...s,box:{...s.box}}),!0}openSegment(e,t){if(R(e.segments,t))return!1;let i=e.segments[e.segments.length-1];return!(i&&void 0===i.end&&t>=i.start)&&(e.segments.push({start:t}),e.segments.sort((e,t)=>e.start-t.start),e.smoother=$(this.options.tracking),!0)}closeSegment(e,t){let i=[...e.segments].reverse().find(e=>void 0===e.end);return!!i&&(i.end=Math.max(i.start,t),e.updatedAt=Date.now(),!0)}insertKeyframe(e,t){let i={...t,box:{...t.box}},s=e.keyframes.findIndex(e=>Math.abs(e.time-t.time)<.001),r=!1;if(s>=0)e.keyframes[s]=i;else{let s=e.keyframes[e.keyframes.length-1];if("tracked"===t.source&&s&&Math.abs(t.time-s.time)<F)e.keyframes[e.keyframes.length-1]=i;else if(!s||t.time>s.time){e.keyframes.push(i);let t=e.smoother.smooth(i);e.presentationKeyframes.push(t),r=!0}else e.keyframes.push(i)}return r||this.rebuildPresentationTrack(e),e.updatedAt=Date.now(),E(e.presentationKeyframes,t.time)??{...i,box:{...i.box}}}rebuildPresentationTrack(e){e.keyframes.sort((e,t)=>e.time-t.time);let t=$(this.options.tracking),i=null;e.presentationKeyframes=e.keyframes.map(s=>{let r=R(e.segments,s.time);return r&&r!==i&&(t=$(this.options.tracking),i=r),t.smooth(s)}),e.smoother=t}clearLiveFrames(e){for(let t of this.videoKeys.get(e)??[]){let e=this.records.get(t);e&&(e.liveFrame=void 0)}}videoObjectContext(e,t){let{video:i}=e,s=e.keyframes.map(e=>e.time);return{src:H(i),width:i.videoWidth,height:i.videoHeight,duration:i.duration,currentTime:i.currentTime,normalizedBox:{x:t.box.left,y:t.box.top,width:t.box.width,height:t.box.height},box:{x:t.box.left*i.videoWidth,y:t.box.top*i.videoHeight,width:t.box.width*i.videoWidth,height:t.box.height*i.videoHeight},trackStart:Math.min(...s),trackEnd:Math.max(...s)}}replaceVideoRecords(e,t,i){this.removeVideoRecords(e);let s=new Set;for(let r of i){let i=`${t}:${r.id}`,a=r.keyframes.map(e=>({...e,box:{...e.box}})),n=W(a,r.segments),o=a[0],d=$(this.options.tracking);s.add(i);let h={key:i,id:r.id,video:e,label:r.label,origin:r.origin,keyframes:a,segments:n,anchors:(r.anchors??[]).map(e=>({...e})),presentationKeyframes:[],smoother:d,createdAt:r.createdAt,updatedAt:r.updatedAt,misses:0,hits:0,analyzedThrough:r.analyzedThrough,backwardSeedTime:"manual"===o?.source&&o.time>L&&(n[0]?.start??-1)>=o.time-L?o.time:void 0};B(h)&&(h.lostAt=e.currentTime),this.rebuildPresentationTrack(h),r.presentationKeyframes?.length&&(h.presentationKeyframes=r.presentationKeyframes.map(e=>({...e,box:{...e.box}}))),this.records.set(i,h)}this.videoKeys.set(e,s)}persistVideo(e){let t=this.persistTimers.get(e);void 0!==t&&clearTimeout(t),this.persistTimers.delete(e);let i=this.options.store,s=this.metadata.get(e);if(!i||!s)return Promise.resolve();let r=Array.from(this.videoKeys.get(e)??[]).map(e=>this.records.get(e)).filter(e=>!!e).map(e=>({id:e.id,label:e.label,origin:e.origin,keyframes:e.keyframes.map(e=>({...e,box:{...e.box}})),presentationKeyframes:e.presentationKeyframes.map(e=>({...e,box:{...e.box}})),anchors:e.anchors.map(e=>({...e})),segments:e.segments.map(e=>({...e})),analyzedThrough:e.analyzedThrough,createdAt:e.createdAt,updatedAt:e.updatedAt})),a={schemaVersion:3,source:s.source,duration:Number.isFinite(e.duration)?e.duration:0,tracks:r,updatedAt:Date.now()},n=(this.writeChains.get(e)??Promise.resolve()).catch(()=>{}).then(()=>i.save(s.storeKey,a)).catch(t=>this.options.onError?.(t,e));return this.writeChains.set(e,n),this.pendingWrites.add(n),n.finally(()=>this.pendingWrites.delete(n)),n}schedulePersistence(e){!this.options.store||this.persistTimers.has(e)||this.persistTimers.set(e,setTimeout(()=>{this.persistTimers.delete(e),this.persistVideo(e)},250))}flushScheduledPersistence(e){return this.persistTimers.has(e)?this.persistVideo(e):Promise.resolve()}matchingVideos(){let e=this.options.root??document,t=this.options.selector??"video",i=[];e instanceof HTMLVideoElement&&e.matches(t)&&i.push(e);for(let s of e.querySelectorAll(t))s instanceof HTMLVideoElement&&i.push(s);return i}videoIdentity(e){if(e.dataset.popmeltMediaId)return e.dataset.popmeltMediaId;let t=new URL(H(e),e.ownerDocument.baseURI).href,i=this.matchingVideos().filter(t=>H(t)===H(e));return`${z(t)}:${Math.max(0,i.indexOf(e))}`}newObjectId(){return globalThis.crypto?.randomUUID?.()??z(`${Date.now()}:${this.manualSequence++}:${Math.random()}`)}removeVideoRecords(e){for(let t of this.videoKeys.get(e)??[]){let e=this.records.get(t);e&&this.cancelBackwardAnalysis(e),e?.session?.dispose?.(),this.activeTrackingKey===t&&(this.activeTrackingKey=null),this.transientKeys.delete(t),this.records.delete(t)}this.videoKeys.delete(e)}removeVideo(e){this.removeVideoListeners(e),this.flushScheduledPersistence(e),this.removeVideoRecords(e),this.metadata.delete(e),this.analyzedSources.delete(e)}queueRefresh(){this.refreshQueued||this.destroyed||(this.refreshQueued=!0,queueMicrotask(()=>{this.refreshQueued=!1,this.readyPromise=this.refresh()}))}};function Q(e={}){return new U(e)}function J(e){if(!e||"object"!=typeof e)return!1;let t=e;return["left","top","width","height"].every(e=>"number"==typeof t[e]&&Number.isFinite(t[e]))}function G(e){if(!e||"object"!=typeof e)return!1;let t=e;return"number"==typeof t.start&&Number.isFinite(t.start)&&(void 0===t.end||"number"==typeof t.end&&Number.isFinite(t.end)&&t.end>=t.start)}function Y(e={}){let t=e.namespace??"popmelt:media:video:v1",i=()=>e.storage??window.localStorage,s=e=>`${t}:${e}`;return{load(e){try{let t=i().getItem(s(e));if(!t)return null;let r=JSON.parse(t);return function(e){if(!e||"object"!=typeof e)return!1;let t=e;return(1===t.schemaVersion||2===t.schemaVersion||3===t.schemaVersion)&&"string"==typeof t.source&&"number"==typeof t.duration&&"number"==typeof t.updatedAt&&Array.isArray(t.tracks)&&t.tracks.every(e=>{if(!e||"object"!=typeof e)return!1;let t=e;return"string"==typeof t.id&&"string"==typeof t.label&&("manual"===t.origin||"detected"===t.origin)&&"number"==typeof t.createdAt&&"number"==typeof t.updatedAt&&(void 0===t.analyzedThrough||"number"==typeof t.analyzedThrough&&Number.isFinite(t.analyzedThrough))&&(void 0===t.segments||Array.isArray(t.segments)&&t.segments.every(G))&&Array.isArray(t.keyframes)&&t.keyframes.every(e=>{if(!e||"object"!=typeof e)return!1;let t=e;return"number"==typeof t.time&&"number"==typeof t.score&&("manual"===t.source||"tracked"===t.source)&&J(t.box)})&&(void 0===t.presentationKeyframes||Array.isArray(t.presentationKeyframes)&&t.presentationKeyframes.every(e=>{if(!e||"object"!=typeof e)return!1;let t=e;return"number"==typeof t.time&&"number"==typeof t.score&&("manual"===t.source||"tracked"===t.source)&&J(t.box)}))})}(r)?r:null}catch{return null}},save(e,t){i().setItem(s(e),JSON.stringify(t))},remove(e){i().removeItem(s(e))}}}function _(){let e=new Map;return{load:t=>e.get(t)??null,save:(t,i)=>{e.set(t,i)},remove:t=>{e.delete(t)}}}export{r as a,a as b,n as c,c as d,u as e,M as f,T as g,A as h,j as i,I as j,U as k,Q as l,Y as m,_ as n};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as t}from"./chunk-
|
|
2
|
+
import{c as t}from"./chunk-VPPVURBR.mjs";import{E as e,k as r}from"./chunk-YLKEDOII.mjs";import{e as a}from"./chunk-IKCHOC3U.mjs";async function o(o,s){let i=await a(o);if(!i||!s)return[];let n=await r(o,s);return n.length?(await Promise.all([i,...i.mountedStores].map(async r=>{try{let a=await t(r,o);if(!a)return[];let{endpoint:s,request:i}=a,c=[];for(let t of n){let a=await e(s,"/participants/read-canvas-receipt",{...i,method:"POST",body:JSON.stringify({receiptId:t})});a.response.ok&&c.push({storeId:r.storeId,receipt:a.body})}return c}catch{return[]}}))).flat():[]}export{o as a};
|
package/dist/chunk-O4HZP3RP.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
"use client";
|
|
2
|
-
import{a as Y}from"./chunk-XTOCFTVW.mjs";function M(){return{schemaVersion:1,name:"",constraints:[{id:"basis",name:"basis",kind:"layout",value:"16",parentId:null,derivative:1,scale:.75},{id:"padding",name:"padding",kind:"layout",value:"",parentId:"basis",derivative:2,scale:1},{id:"gap",name:"gap",kind:"layout",value:"16",parentId:null,derivative:1,scale:.75},{id:"radii",name:"radii",kind:"layout",value:"",parentId:null,derivative:1,scale:.75},...j(),{id:"primary",name:"primary",kind:"color",value:"oklch(65% 0.16 265)",parentId:null,derivative:0,scale:.125},{id:"secondary",name:"secondary",kind:"color",value:"",parentId:"primary",derivative:30,scale:.125},{id:"tertiary",name:"tertiary",kind:"color",value:"",parentId:"primary",derivative:60,scale:.125}],tokens:[{id:"semantic-color",name:"semantic_color",value:"@primary: 1"},{id:"ad-hoc-spacer",name:"ad-hoc-spacer",value:"@basis: 2"},{id:"ad-hoc-color",name:"ad-hoc-color",value:"#123ccc"},{id:"shadow-lg",name:"shadow-lg",value:"0 10px 15px rgba(0, 0, 0, 0.5)"}]}}function j(){return["body","heading"].flatMap(e=>[{id:`${e}-family`,name:`${e}-family`,kind:"font",group:"typography",typographyRole:e,value:e==="body"?"system-ui, sans-serif":"",parentId:e==="heading"?"body-family":null,derivative:1,scale:1},...["size","height","weight"].map(t=>({id:`${e}-${t}`,name:`${e}-${t}`,kind:"layout",group:"typography",typographyRole:e,value:t==="weight"&&e==="body"?"400":"",parentId:t==="size"?e==="body"?"basis":"body-size":t==="height"?`${e}-size`:e==="body"?null:"body-weight",derivative:t==="height"?1.5:t==="size"?2:1,scale:t==="weight"?100:.125,...t==="weight"?{scaleMode:"increment"}:{}}))])}function ee(e){let t={text:"body-size",height:"body-height",weight:"body-weight"},a=e.constraints.filter(s=>t[s.id]);if(!a.length)return e;let o=[...e.constraints];for(let s of j()){if(o.some(m=>m.id===s.id))continue;let l=a.find(m=>t[m.id]===s.id);o.push(l?{...l,id:s.id,name:s.name,group:s.group,typographyRole:s.typographyRole}:s)}let r=o.filter(s=>!t[s.id]).map(s=>({...s})),n=s=>{let l=new Set([s.id]);for(;s.parentId&&t[s.parentId];){let m=o.find(v=>v.id===s.parentId);if(!m||l.has(s.parentId)){s.parentId=null,s.value="";break}if(l.add(s.parentId),s.derivative*=m.derivative,s.parentId=m.parentId,!m.parentId){try{s.value=I(b(o,s.id))}catch{s.value=m.value}s.derivative=1}}};r.filter(s=>s.typographyRole==="body").forEach(n);for(let s of r){if(!s.parentId||!t[s.parentId])continue;let l=t[s.parentId];try{let m=b(o,s.parentId),v=b(r,l);if(m.kind!=="layout"||v.kind!=="layout"||m.unit!==v.unit||!v.value||W(r,s.id,l))throw Error("Keep the original root");s.derivative*=m.value/v.value,s.parentId=l}catch{n(s)}}let i=new Map(a.map(s=>[s.name.toLowerCase(),t[s.id]]));return a.some(s=>s.id==="text")&&(i.set("text","body-size"),i.set("size","body-size")),{...e,constraints:r,tokens:e.tokens.map(s=>({...s,value:s.value.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|url\([^)]*\)|@([\w-]+)(?::\s*[+-]?(?:\d+\.?\d*|\.\d+))?/gi,(l,m)=>{if(!m)return l;let v=i.get(m.toLowerCase());if(!v)return l;let c=l.replace(`@${m}`,`@${v}`),f=x(o,l),h=x(r,c);return f&&(!h||I(f)!==I(h))?I(f):c})}))}}var E="[+-]?(?:\\d+\\.?\\d*|\\.\\d+)",te=new RegExp(`^(${E})(px|rem|em|%|vw|vh|vmin|vmax|ch)?$`,"i"),re=new RegExp(`^oklch\\(\\s*(${E})(%)?\\s+(${E})\\s+(${E})(?:deg)?\\s*\\)$`,"i"),O=e=>(e%360+360)%360,ne=e=>Math.max(0,Math.min(1,e)),S=e=>Number(e.toFixed(4));function D(e,t){if(e==="font"){let i=t.trim();if(!i||!/[a-z\u0080-\uffff]/i.test(i)||i.length>160||/[;{}()@]|[<>]/.test(i)||[...i].some(s=>s.charCodeAt(0)<32))throw Error("Use a font family or comma-separated font stack");return{kind:e,value:i}}if(e==="layout"){let i=t.trim().match(te);if(!i||!Number.isFinite(Number(i[1]))||Number(i[1])<0)throw Error("Use a positive length, like 24px or 1.5rem");return{kind:e,value:Number(i[1]),unit:i[2]?.toLowerCase()??""}}let a=t.trim().match(re);if(!a)throw Error("Use OKLCH, like oklch(65% 0.16 265)");let o=Number(a[1])/(a[2]?100:1),r=Number(a[3]),n=Number(a[4]);if(![o,r,n].every(Number.isFinite)||o<0||o>1||r<0)throw Error("Lightness must be 0\u2013100% and chroma cannot be negative");return{kind:e,l:o,c:r,h:O(n)}}function W(e,t,a){let o=e.find(i=>i.id===t),r=e.find(i=>i.id===a);if(!o||!r)return"Choose an existing constraint";if(o.kind!==r.kind)return"Connect constraints of the same type";if(o.scaleMode==="increment"!=(r.scaleMode==="increment"))return"Connect weights to weights, and lengths to lengths";let n=new Set([t]);for(;r;){if(n.has(r.id))return"That connection would create a cycle";if(n.add(r.id),!r.parentId)break;if(r=e.find(i=>i.id===r.parentId),!r)return"The parent reference is missing"}return null}function b(e,t,a=0){let o=new Set,r=s=>{if(o.has(s))throw Error("Circular reference");o.add(s);let l=e.find(c=>c.id===s);if(!l)throw Error("The parent reference is missing");if(!Number.isFinite(l.derivative))throw Error("Use a finite derivative");if(!l.parentId)return D(l.kind,l.value);let m=e.find(c=>c.id===l.parentId);if(m&&l.scaleMode==="increment"!=(m.scaleMode==="increment"))throw Error("Connect weights to weights, and lengths to lengths");let v=r(l.parentId);if(v.kind!==l.kind)throw Error("Connect constraints of the same type");if(v.kind==="font")return v;if(v.kind==="layout"){if(l.derivative<0)throw Error("The derivative cannot be negative");return{...v,value:v.value*l.derivative}}return{...v,h:O(v.h+l.derivative)}},n=r(t),i=e.find(s=>s.id===t);if(n.kind==="font"){if(a!==0)throw Error("Font families do not have numeric steps");return n}if(!Number.isFinite(a)||!Number.isFinite(i.scale))throw Error("Use a finite step");if(n.kind==="layout"){if(i.scaleMode==="increment"?i.scale<=0:i.scale<0)throw Error("Use a nonnegative growth rate or a positive weight increment");let s=i.scaleMode==="increment"?Math.max(0,n.value+i.scale*a):n.value*(1+i.scale)**a;if(!Number.isFinite(s))throw Error("The scaled value is too large");return{...n,value:a===0?s:Math.round(s)}}return{...n,l:ne(n.l+i.scale*a)}}function I(e){return e.kind==="font"?e.value:e.kind==="layout"?`${S(e.value)}${e.unit}`:`oklch(${S(e.l*100)}% ${S(e.c)} ${S(e.h)}${e.alpha===void 0?"":` / ${S(e.alpha)}`})`}function A(e){let t=e.trim().match(new RegExp(`^@([^:@/(),]+?)(?::\\s*(${E}))?(?:\\s*/\\s*(${E}%?))?$`));return t&&t[1].trim()&&(t[2]!==void 0||!/\s/.test(t[1].trim()))&&(t[2]===void 0||Number.isFinite(Number(t[2])))&&(t[3]===void 0||F(t[3])!==null)?{name:t[1].trim(),step:t[2]===void 0?null:Number(t[2]),...t[3]===void 0?{}:{opacity:t[3]}}:null}function F(e){if(!new RegExp(`^${E}%?$`).test(e))return null;let t=parseFloat(e)/(e.endsWith("%")?100:1);return Number.isFinite(t)&&t>=0&&t<=1?t:null}function x(e,t){let a=A(t);if(!a)return null;let o=e.find(r=>r.name.toLowerCase()===a.name.toLowerCase());if(!o)return null;try{let r=b(e,o.id,a.step??0);return a.opacity===void 0?r:r.kind==="color"?{...r,alpha:F(a.opacity)}:null}catch{return null}}function ie(e,t,a){let o=e.find(r=>r.id===t);if(o?.kind!=="layout")return o?.derivative??0;try{let r=b(e,t),n=b(e,a);if(r.kind==="layout"&&n.kind==="layout"&&r.unit===n.unit&&n.value!==0){let i=r.value/n.value;if(Number.isFinite(i))return i}}catch{}return 1}function ae(e,t){let a=I(b(e,t));return e.map(o=>o.id===t?{...o,parentId:null,value:a}:o)}function R(e,t){let a=new Set;for(let o=0;o<32;o+=1){if(a.has(e))return;if(a.add(e),e&&typeof e=="object"){let i=e;e=i.$value??i.ref;continue}if(typeof e!="string")return;let r=e.trim(),n=r.replace(/^\{(.+)\}$/,"$1").replace(/^var\(--([^,)]+)\)$/,"$1").replace(/^var\(principles\.([^,)]+)\)$/,"$1").replace(/^principles\./,"");if(Object.hasOwn(t,n)){e=t[n];continue}if(/\b(currentcolor|inherit|initial|unset|revert|var|env|light-dark)\b/i.test(r))return;if(typeof CSS<"u"&&CSS.supports)return CSS.supports("color",r)?r:void 0;if(typeof document<"u"){let i=document.createElement("span").style;return i.color=r,i.color?r:void 0}return}}var q=/^@([\w-]+)(?::\s*[+-]?(?:\d+\.?\d*|\.\d+)(?![\w.]))?(?![\w-]|\s*:)/,oe=/^(?:px|rem|em|ex|ch|cap|ic|lh|rlh|vw|vh|vi|vb|vmin|vmax|[sld]v[whib]|cm|mm|q|in|pt|pc|%)$/i,_=e=>String(Number(e.toPrecision(12)));function Z(e,t){if(e.length>4096||!/^calc\(/i.test(e))return null;let a=5,o=0,r=()=>{throw Error("Invalid calc expression")},n=()=>{for(;/\s/.test(e[a]??"")&&a<e.length;)a++},i=(c,f="")=>!Number.isFinite(c)||f&&!oe.test(f)?r():{kind:f?"length":"number",terms:new Map([[f.toLowerCase(),c]])},s=(c,f)=>({...c,terms:new Map([...c.terms].map(([h,d])=>{let p=d*f;return Number.isFinite(p)||r(),[h,p]}))}),l=()=>{n(),++o>32&&r();try{let c=e[a];if(c==="+"||c==="-")return a++,s(l(),c==="-"?-1:1);if(e[a]==="("||/^calc\(/i.test(e.slice(a))){a+=e[a]==="("?1:5;let d=v();return n(),e[a++]!==")"&&r(),d}let f=e.slice(a).match(q)?.[0];if(f){a+=f.length;let d=x(t,f);if(d?.kind!=="layout")return r();let p=t.find(u=>u.name.toLowerCase()===f.slice(1).split(":")[0].trim().toLowerCase());return i(d.value,d.unit||(p?.scaleMode==="increment"?"":"px"))}let h=e.slice(a).match(/^(\d+\.?\d*|\.\d+)(e[+-]?\d+)?([a-z]+|%)?/i);return h?(a+=h[0].length,i(Number(h[1]+(h[2]??"")),h[3])):r()}finally{o--}},m=()=>{let c=l();for(;;){n();let f=e[a];if(f!=="*"&&f!=="/")return c;a++;let h=l();if(f==="/"){let d=h.terms.get("");if(h.kind!=="number"||!d)return r();c=s(c,1/d)}else if(h.kind==="number")c=s(c,h.terms.get(""));else if(c.kind==="number")c=s(h,c.terms.get(""));else return r()}},v=()=>{let c=m();for(;;){n();let f=e[a];if(f!=="+"&&f!=="-")return c;a++;let h=m();if(c.kind!==h.kind)return r();for(let[d,p]of h.terms){let u=(c.terms.get(d)??0)+p*(f==="-"?-1:1);Number.isFinite(u)||r(),c.terms.set(d,u)}}};try{let c=v();if(n(),e[a++]!==")"||e.slice(a).trim())return null;let f=[...c.terms].filter(([,p])=>p!==0);f.length||f.push([c.terms.keys().next().value??"",0]);let[h,d]=f[0];return{css:f.length===1?`${_(d)}${h}`:`calc(${f.map(([p,u],g)=>`${g?u<0?" - ":" + ":u<0?"-":""}${_(Math.abs(u))}${p}`).join("")})`,kind:c.kind,...f.length===1?{value:d,unit:h}:{}}}catch{return null}}function se(e){let t=[],a=/url\((?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^)'"])*\)|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\*[\s\S]*?\*\/|\bcalc\(/gi;for(let o;o=a.exec(e);){if(!/^calc\(/i.test(o[0]))continue;let r=1,n=a.lastIndex;for(;n<e.length&&r;)e[n]==="("?r++:e[n]===")"&&r--,n++;t.push({start:o.index,end:n,text:e.slice(o.index,n)}),a.lastIndex=n}return t}function z(e,t){let a=e;for(let o of se(e).reverse()){let r=Z(o.text,t);if(!r)return null;a=a.slice(0,o.start)+r.css+a.slice(o.end)}return a}function B(e,t){let a=[],o=(n,i,s)=>{let l=R(n,{});l&&a.push({start:i,end:s,color:l})},r=(n,i=0,s=!1)=>{let l=0;for(;l<n.length;){let m=n[l];if(m==='"'||m==="'"){let u=m;for(l++;l<n.length;l++)if(n[l]==="\\")l++;else if(n[l]===u){l++;break}continue}if(n.startsWith("/*",l)){let u=n.indexOf("*/",l+2);l=u<0?n.length:u+2;continue}if(m==="@"){let u=n.slice(l).match(/^@([^:@(),/]+):\s*([+-]?(?:\d+\.?\d*|\.\d+))(?![\w.])(?:\s*\/\s*[+-]?(?:\d+\.?\d*|\.\d+)%?(?![\w.%]))?(?!\s*\/)/),g=n.slice(l).match(/^@([\w-]+)(?![\w-]|\s*:)(?:\s*\/\s*([+-]?(?:\d+\.?\d*|\.\d+)%?)(?![\w.%]))?(?!\s*\/)/),w=s?n.slice(l).match(q):u??g;if(w){let $=x(t,w[0]),y=A(w[0]);y&&a.push({start:i+l,end:i+l+w[0].length,color:$?.kind==="color"?I($):null,reference:y,...s?{math:!0}:{}}),l+=w[0].length}else l+=n.slice(l).match(/^@[^\s,()]*(?:\s*:\s*[^\s,()]*)?/)?.[0].length??1;continue}let v=n.slice(l).match(/^(?:#[\w-]+|[\w-]+)/)?.[0];if(!v){l++;continue}let c=l;if(l+=v.length,n[l]!=="("){s||o(v,i+c,i+l);continue}let f=++l,h=1,d="";for(;l<n.length&&h;){let u=n[l++];if(u==="\\"){l++;continue}if(d){u===d&&(d="");continue}u==='"'||u==="'"?d=u:u==="("?h++:u===")"&&h--}if(h)continue;let p=R(n.slice(c,l),{});p?a.push({start:i+c,end:i+l,color:p}):/^(?:(?:repeating-)?(?:linear|radial|conic)-gradient|drop-shadow|calc)$/i.test(v)&&r(n.slice(f,l-1),i+f,s||v.toLowerCase()==="calc")}};return r(e),a}function L(e,t){return B(e,t).flatMap(a=>a.color?[{...a,color:a.color}]:[])}function U(e,t){return B(e,t).flatMap(({reference:a,start:o,end:r,math:n})=>a?[{...a,start:o,end:r,...n?{math:!0}:{}}]:[])}function le(e,t){return L(e,t).map(({color:a})=>a)}function de(e,t){let a=U(e,t);return z(e,t)!==null&&a.length===(e.match(/@/g)?.length??0)&&a.every(({start:o,end:r})=>x(t,e.slice(o,r))!==null)}function T(e,t,a=!1){let o=z(e,t);if(o===null)return null;let r=o;for(let n of U(o,t).reverse()){let i=x(t,o.slice(n.start,n.end));if(!i)return null;r=r.slice(0,n.start)+I(i)+(a&&i.kind==="layout"&&!i.unit?"px":"")+r.slice(n.end)}return r}function ue(e,t,a,o){if(o!==void 0){let i=U(e,a)[o];return!i||i.opacity!==void 0&&t.kind!=="color"||i.math&&t.kind!=="layout"?null:e.slice(0,i.start)+`@${t.name}${i.step===null?"":`: ${i.step}`}${i.opacity===void 0?"":` / ${i.opacity}`}`+e.slice(i.end)}let r=A(e);if(r||!e.trim())return r?.opacity!==void 0&&t.kind!=="color"?null:`@${t.name}${r?.step===null?"":`: ${r?.step??0}`}${r?.opacity===void 0?"":` / ${r.opacity}`}`;let n=L(e,a);if(t.kind==="color"&&n.length===1){let{start:i,end:s}=n[0],l=A(e.slice(i,s));return`${e.slice(0,i)}@${t.name}${l?.step===null?"":`: ${l?.step??0}`}${l?.opacity===void 0?"":` / ${l.opacity}`}${e.slice(s)}`}return/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?$/i.test(e.trim())?`@${t.name}: 0`:null}var H=["page","body","heading","muted","card","button","input"],K=["color","backgroundColor","border","borderColor","borderWidth","borderRadius","boxShadow","padding","paddingInline","paddingBlock","gap","fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","opacity"];function ce(e){var t;let a={};for(let o of e.usage??[]){if(!H.includes(o.target)||!K.includes(o.property))continue;let r=null;try{if(o.source.kind==="token"){let i=e.tokens.find(s=>s.id===o.source.id);i&&(r=T(i.value,e.constraints,!["fontWeight","opacity"].includes(o.property)))}else if(o.source.kind==="dimension"){let i=b(e.constraints,o.source.id,o.source.step??0);r=I(i),i.kind==="layout"&&!i.unit&&!["fontWeight","opacity"].includes(o.property)&&(r+="px")}}catch{continue}if(r&&/^-?\d+(?:\.\d+)?$/.test(r)&&["fontSize","letterSpacing","padding","paddingInline","paddingBlock","gap","borderRadius","borderWidth"].includes(o.property)&&(r+="px"),!r||/[;{}]|\b(?:url|expression|var)\s*\(/i.test(r)||r.includes("\\")||[...r].some(i=>i.charCodeAt(0)<32)||typeof CSS<"u"&&CSS.supports&&!CSS.supports(o.property.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`),r))continue;let n=a[t=o.target]??(a[t]={});n[o.property]=["fontWeight","opacity"].includes(o.property)&&Number.isFinite(Number(r))?Number(r):r}return a}var fe=class extends Error{};function P(){let e=M();return{...e,tokens:[],constraints:e.constraints.map(t=>({...t,value:"",parentId:null}))}}var V=(e,t=512)=>typeof e=="string"&&e.length<=t&&![...e].some(a=>a.charCodeAt(0)<32)&&!/[;{}]|\b(?:url|expression)\s*\(/i.test(e);function G(e,t){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(o=>!["name","constraints","tokens","usage","featuredComponentId"].includes(o)))throw Error("Invalid proposal patch.");let a=structuredClone(e);if(t.featuredComponentId!==void 0){if(t.featuredComponentId!==null&&!a.fragments?.some(o=>o.id===t.featuredComponentId))throw Error("The featured component must belong to this Taste.");a.featuredComponentId=t.featuredComponentId}if(t.name!==void 0){if(typeof t.name!="string"||t.name.length>80)throw Error("Invalid name.");a.name=t.name}if(t.constraints!==void 0){if(!Array.isArray(t.constraints)||t.constraints.length>32)throw Error("Invalid dimensions.");let o=new Set;for(let r of t.constraints){if(!r||typeof r!="object"||Object.keys(r).some(i=>!["id","value","parentId","derivative","scale"].includes(i)))throw Error("Invalid dimension patch.");let n=a.constraints.find(i=>i.id===r.id);if(!n||o.has(r.id))throw Error("Unknown or duplicate dimension ID.");if(o.add(r.id),Object.assign(n,r),!V(n.value)||!Number.isFinite(n.derivative)||!Number.isFinite(n.scale)||n.scale<0||n.scaleMode==="increment"&&n.scale<=0||n.kind==="color"&&n.scale>1||n.kind==="font"&&(n.scale!==1||n.derivative!==1)||n.kind==="layout"&&n.derivative<0||n.parentId!==null&&!a.constraints.some(i=>i.id===n.parentId&&i.kind===n.kind))throw Error(`Invalid ${n.id} dimension.`)}for(let r of a.constraints)(r.value||r.parentId)&&b(a.constraints,r.id)}if(t.tokens!==void 0){if(!Array.isArray(t.tokens)||t.tokens.length>128)throw Error("Invalid tokens.");let o=new Set,r=new Set;for(let n of t.tokens){if(!n||typeof n.id!="string"||!/^[a-zA-Z0-9_-]{1,80}$/.test(n.id)||typeof n.name!="string"||!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(n.name)||!V(n.value)||o.has(n.id)||r.has(n.name))throw Error("Invalid or duplicate token.");o.add(n.id),r.add(n.name)}a.tokens=structuredClone(t.tokens)}t.usage!==void 0&&(a.usage=structuredClone(t.usage));for(let o of a.tokens)if(!de(o.value,a.constraints))throw Error(`Invalid reference or calc expression in ${o.name}.`);if(!Array.isArray(a.usage??[])||(a.usage?.length??0)>128)throw Error("Invalid usage mappings.");for(let o of a.usage??[])if(!o||Object.keys(o).some(r=>!["target","property","source"].includes(r))||!H.includes(o.target)||!K.includes(o.property)||!o.source||Object.keys(o.source).some(r=>!["kind","id","step"].includes(r))||!["token","dimension"].includes(o.source.kind)||!(o.source.kind==="token"?a.tokens:a.constraints).some(r=>r.id===o.source.id)||o.source.step!==void 0&&(!Number.isInteger(o.source.step)||Math.abs(o.source.step)>100))throw Error("Usage must reference an existing token or dimension.");return a}function J(e,t=!0,a=!0){let o=M(),r={past:[],future:[]},n={current:{past:[],future:[]}},i={available:t,revision:crypto.randomUUID(),runId:"",openRequest:"",open:!1,mode:"empty",state:e?"complete":"idle",message:"",draft:e??null},s=new Set,l=null,m=new Set,v=d=>{l={id:crypto.randomUUID(),target:d,expiresAt:Date.now()+2e3},m.forEach(p=>p())},c=()=>{l=null,m.forEach(d=>d())},f=d=>{i={...i,...d,revision:crypto.randomUUID()},s.forEach(p=>p())},h={setCreationAllowed(d){a=d},history:n,getLookSnapshot:()=>l,subscribeLook:d=>(m.add(d),()=>{m.delete(d)}),setAvailable(d){i.available!==d&&f({available:d})},getSnapshot:()=>i,subscribe:d=>(s.add(d),()=>{s.delete(d)}),create(d="template",p=!1){if(!a)throw Error("An active subscription is required to create a Taste.");c(),d==="template"&&!p&&(o=M()),d==="template"?(p||(r.past=[],r.future=[]),n.current=r):n.current={past:[],future:[]},f({open:!0,openRequest:crypto.randomUUID(),runId:crypto.randomUUID(),mode:d,state:d==="extract"?"running":"complete",message:"",draft:d==="template"?o:P()})},edit(d){i.state!=="running"&&(i.mode==="template"&&(o=d),f({draft:d}))},addFragment(d,p){if(i.runId!==d||!i.open||i.state==="running"||!i.draft)throw Error("This proposal has changed. Capture the component again.");let u=i.draft;if((u.fragments?.length??0)>=16)throw Error("A proposal can contain up to 16 components.");if(u.fragments?.some(y=>y.id===p.fragment.id))throw Error("This component was already captured.");if(p.tokens.some(y=>u.tokens.some(k=>k.id===y.id||k.name===y.name)))throw Error("A component token conflicts with a shared token. Retry capture.");let g=G({...u,usage:[]},{tokens:p.tokens}),w=y=>{for(let k of Object.values(y.styles))if(!(k.kind==="token"?[...u.tokens,...g.tokens]:g.constraints).some(N=>N.id===k.id))throw Error("A referenced Taste value was removed. Retry capture.");y.children.forEach(k=>{typeof k!="string"&&w(k)})};w(p.fragment.root);let $={...u,fragments:[...u.fragments??[],{...p.fragment,tokens:p.tokens}]};return n.current.past.push(u),n.current.past.length>100&&n.current.past.shift(),n.current.future=[],h.edit($),$},stream(d,p){i.runId===d&&i.state==="running"&&f(p)},close(){c(),f({open:!1,...i.state==="running"?{state:"error",message:"Extraction stopped. Retry or continue editing the partial draft."}:{}})},command(d){let p=(u,g={})=>({status:u,...i,...g,saved:!1,applied:!1});if(d.target!==void 0&&d.action!=="inspect")return p("invalid",{error:"target is only supported for inspection."});if(d.action==="inspect"){let u=d.target;if(u!==void 0){let{draft:g,...w}=i,$=(C,X={})=>({status:C,...w,saved:!1,applied:!1,...X});if(!u||!["dimension","token"].includes(u.kind)||typeof u.id!="string"||!u.id||u.id.length>200)return $("invalid");let y=(u.kind==="dimension"?g?.constraints:g?.tokens)?.find(C=>C.id===u.id);if(!y||!g)return $("not_found",{target:u});let k=null,N;try{k=u.kind==="dimension"?I(b(g.constraints,u.id)):T(y.value,g.constraints)}catch(C){N=C instanceof Error?C.message:"Not resolved yet"}return v({kind:u.kind,id:u.id}),$("ok",{target:u,row:y,resolved:k,...N?{resolutionError:N}:{}})}return i.draft&&v(null),p("ok")}if(!i.available)return p("unavailable",{error:"The host Taste panel is not available in this browser."});if(!["create","modify"].includes(d.action))return p("invalid",{error:"Unknown proposal action."});if(!d.expectedRevision||d.expectedRevision!==i.revision)return p("conflict");if(i.state==="running")return p("busy");try{if(d.action==="create"){let u=d.mode??"template";if(!["template","empty","extract"].includes(u)||d.patch)throw Error("Create accepts a mode; modify the returned draft separately.");h.create(u)}else{if(!i.draft)return p("not_found");let u=G(i.draft,d.patch);n.current.past=[...n.current.past.slice(-99),i.draft],n.current.future=[],i.mode==="template"&&(o=u),f({draft:u,open:!0,openRequest:crypto.randomUUID()})}return p("ok")}catch(u){return p("invalid",{error:u instanceof Error?u.message:"Invalid patch."})}}};return h}var Q=J(null,!1,!1);Y.connect(Q);export{M as a,ee as b,D as c,W as d,b as e,I as f,A as g,F as h,x as i,ie as j,ae as k,R as l,Z as m,z as n,L as o,U as p,le as q,T as r,ue as s,ce as t,fe as u,P as v,J as w,Q as x};
|
|
1
|
+
"use client";import{a as e}from"./chunk-XTOCFTVW.mjs";function t(){return{schemaVersion:1,name:"",constraints:[{id:"basis",name:"basis",kind:"layout",value:"16",parentId:null,derivative:1,scale:.75},{id:"padding",name:"padding",kind:"layout",value:"",parentId:"basis",derivative:2,scale:1},{id:"gap",name:"gap",kind:"layout",value:"16",parentId:null,derivative:1,scale:.75},{id:"radii",name:"radii",kind:"layout",value:"",parentId:null,derivative:1,scale:.75},...r(),{id:"primary",name:"primary",kind:"color",value:"oklch(65% 0.16 265)",parentId:null,derivative:0,scale:.125},{id:"secondary",name:"secondary",kind:"color",value:"",parentId:"primary",derivative:30,scale:.125},{id:"tertiary",name:"tertiary",kind:"color",value:"",parentId:"primary",derivative:60,scale:.125}],tokens:[{id:"semantic-color",name:"semantic_color",value:"@primary: 1"},{id:"ad-hoc-spacer",name:"ad-hoc-spacer",value:"@basis: 2"},{id:"ad-hoc-color",name:"ad-hoc-color",value:"#123ccc"},{id:"shadow-lg",name:"shadow-lg",value:"0 10px 15px rgba(0, 0, 0, 0.5)"}]}}function r(){return["body","heading"].flatMap(e=>[{id:`${e}-family`,name:`${e}-family`,kind:"font",group:"typography",typographyRole:e,value:"body"===e?"system-ui, sans-serif":"",parentId:"heading"===e?"body-family":null,derivative:1,scale:1},...["size","height","weight"].map(t=>({id:`${e}-${t}`,name:`${e}-${t}`,kind:"layout",group:"typography",typographyRole:e,value:"weight"===t&&"body"===e?"400":"",parentId:"size"===t?"body"===e?"basis":"body-size":"height"===t?`${e}-size`:"body"===e?null:"body-weight",derivative:"height"===t?1.5:"size"===t?2:1,scale:"weight"===t?100:.125,..."weight"===t?{scaleMode:"increment"}:{}}))])}function n(e){let t={text:"body-size",height:"body-height",weight:"body-weight"},n=e.constraints.filter(e=>t[e.id]);if(!n.length)return e;let i=[...e.constraints];for(let e of r()){if(i.some(t=>t.id===e.id))continue;let r=n.find(r=>t[r.id]===e.id);i.push(r?{...r,id:e.id,name:e.name,group:e.group,typographyRole:e.typographyRole}:e)}let a=i.filter(e=>!t[e.id]).map(e=>({...e})),o=e=>{let r=new Set([e.id]);for(;e.parentId&&t[e.parentId];){let t=i.find(t=>t.id===e.parentId);if(!t||r.has(e.parentId)){e.parentId=null,e.value="";break}if(r.add(e.parentId),e.derivative*=t.derivative,e.parentId=t.parentId,!t.parentId){try{e.value=f(p(i,e.id))}catch{e.value=t.value}e.derivative=1}}};a.filter(e=>"body"===e.typographyRole).forEach(o);for(let e of a){if(!e.parentId||!t[e.parentId])continue;let r=t[e.parentId];try{let t=p(i,e.parentId),n=p(a,r);if("layout"!==t.kind||"layout"!==n.kind||t.unit!==n.unit||!n.value||c(a,e.id,r))throw Error("Keep the original root");e.derivative*=t.value/n.value,e.parentId=r}catch{o(e)}}let s=new Map(n.map(e=>[e.name.toLowerCase(),t[e.id]]));return n.some(e=>"text"===e.id)&&(s.set("text","body-size"),s.set("size","body-size")),{...e,constraints:a,tokens:e.tokens.map(e=>({...e,value:e.value.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|url\([^)]*\)|@([\w-]+)(?::\s*[+-]?(?:\d+\.?\d*|\.\d+))?/gi,(e,t)=>{if(!t)return e;let r=s.get(t.toLowerCase());if(!r)return e;let n=e.replace(`@${t}`,`@${r}`),o=v(i,e),l=v(a,n);return!o||l&&f(o)===f(l)?n:f(o)})}))}}var i="[+-]?(?:\\d+\\.?\\d*|\\.\\d+)",a=new RegExp(`^(${i})(px|rem|em|%|vw|vh|vmin|vmax|ch)?$`,"i"),o=new RegExp(`^oklch\\(\\s*(${i})(%)?\\s+(${i})\\s+(${i})(?:deg)?\\s*\\)$`,"i"),s=e=>(e%360+360)%360,l=e=>Math.max(0,Math.min(1,e)),d=e=>Number(e.toFixed(4));function u(e,t){if("font"===e){let r=t.trim();if(!r||!/[a-z\u0080-\uffff]/i.test(r)||r.length>160||/[;{}()@]|[<>]/.test(r)||[...r].some(e=>e.charCodeAt(0)<32))throw Error("Use a font family or comma-separated font stack");return{kind:e,value:r}}if("layout"===e){let r=t.trim().match(a);if(!r||!Number.isFinite(Number(r[1]))||Number(r[1])<0)throw Error("Use a positive length, like 24px or 1.5rem");return{kind:e,value:Number(r[1]),unit:r[2]?.toLowerCase()??""}}let r=t.trim().match(o);if(!r)throw Error("Use OKLCH, like oklch(65% 0.16 265)");let n=Number(r[1])/(r[2]?100:1),i=Number(r[3]),l=Number(r[4]);if(![n,i,l].every(Number.isFinite)||n<0||n>1||i<0)throw Error("Lightness must be 0–100% and chroma cannot be negative");return{kind:e,l:n,c:i,h:s(l)}}function c(e,t,r){let n=e.find(e=>e.id===t),i=e.find(e=>e.id===r);if(!n||!i)return"Choose an existing constraint";if(n.kind!==i.kind)return"Connect constraints of the same type";if("increment"===n.scaleMode!=("increment"===i.scaleMode))return"Connect weights to weights, and lengths to lengths";let a=new Set([t]);for(;i;){if(a.has(i.id))return"That connection would create a cycle";if(a.add(i.id),!i.parentId)break;if(i=e.find(e=>e.id===i.parentId),!i)return"The parent reference is missing"}return null}function p(e,t,r=0){let n=new Set,i=t=>{if(n.has(t))throw Error("Circular reference");n.add(t);let r=e.find(e=>e.id===t);if(!r)throw Error("The parent reference is missing");if(!Number.isFinite(r.derivative))throw Error("Use a finite derivative");if(!r.parentId)return u(r.kind,r.value);let a=e.find(e=>e.id===r.parentId);if(a&&"increment"===r.scaleMode!=("increment"===a.scaleMode))throw Error("Connect weights to weights, and lengths to lengths");let o=i(r.parentId);if(o.kind!==r.kind)throw Error("Connect constraints of the same type");if("font"===o.kind)return o;if("layout"===o.kind){if(r.derivative<0)throw Error("The derivative cannot be negative");return{...o,value:o.value*r.derivative}}return{...o,h:s(o.h+r.derivative)}},a=i(t),o=e.find(e=>e.id===t);if("font"===a.kind){if(0!==r)throw Error("Font families do not have numeric steps");return a}if(!Number.isFinite(r)||!Number.isFinite(o.scale))throw Error("Use a finite step");if("layout"===a.kind){if("increment"===o.scaleMode?o.scale<=0:o.scale<0)throw Error("Use a nonnegative growth rate or a positive weight increment");let e="increment"===o.scaleMode?Math.max(0,a.value+o.scale*r):a.value*(1+o.scale)**r;if(!Number.isFinite(e))throw Error("The scaled value is too large");return{...a,value:0===r?e:Math.round(e)}}return{...a,l:l(a.l+o.scale*r)}}function f(e){return"font"===e.kind?e.value:"layout"===e.kind?`${d(e.value)}${e.unit}`:`oklch(${d(100*e.l)}% ${d(e.c)} ${d(e.h)}${void 0===e.alpha?"":` / ${d(e.alpha)}`})`}function m(e){let t=e.trim().match(new RegExp(`^@([^:@/(),]+?)(?::\\s*(${i}))?(?:\\s*/\\s*(${i}%?))?$`));return!t||!t[1].trim()||void 0===t[2]&&/\s/.test(t[1].trim())||void 0!==t[2]&&!Number.isFinite(Number(t[2]))||void 0!==t[3]&&null===h(t[3])?null:{name:t[1].trim(),step:void 0===t[2]?null:Number(t[2]),...void 0===t[3]?{}:{opacity:t[3]}}}function h(e){if(!new RegExp(`^${i}%?$`).test(e))return null;let t=parseFloat(e)/(e.endsWith("%")?100:1);return Number.isFinite(t)&&t>=0&&t<=1?t:null}function v(e,t){let r=m(t);if(!r)return null;let n=e.find(e=>e.name.toLowerCase()===r.name.toLowerCase());if(!n)return null;try{let t=p(e,n.id,r.step??0);return void 0===r.opacity?t:"color"===t.kind?{...t,alpha:h(r.opacity)}:null}catch{return null}}function g(e,t,r){let n=e.find(e=>e.id===t);if("layout"!==n?.kind)return n?.derivative??0;try{let n=p(e,t),i=p(e,r);if("layout"===n.kind&&"layout"===i.kind&&n.unit===i.unit&&0!==i.value){let e=n.value/i.value;if(Number.isFinite(e))return e}}catch{}return 1}function y(e,t){let r=f(p(e,t));return e.map(e=>e.id===t?{...e,parentId:null,value:r}:e)}function k(e,t){let r=new Set;for(let n=0;n<32;n+=1){if(r.has(e))return;if(r.add(e),e&&"object"==typeof e){let t=e;e=t.$value??t.ref;continue}if("string"!=typeof e)return;let n=e.trim(),i=n.replace(/^\{(.+)\}$/,"$1").replace(/^var\(--([^,)]+)\)$/,"$1").replace(/^var\(principles\.([^,)]+)\)$/,"$1").replace(/^principles\./,"");if(!Object.hasOwn(t,i)){if(/\b(currentcolor|inherit|initial|unset|revert|var|env|light-dark)\b/i.test(n))return;if(typeof CSS<"u"&&CSS.supports)return CSS.supports("color",n)?n:void 0;if(typeof document<"u"){let e=document.createElement("span").style;return e.color=n,e.color?n:void 0}return}e=t[i]}}var b=/^@([\w-]+)(?::\s*[+-]?(?:\d+\.?\d*|\.\d+)(?![\w.]))?(?![\w-]|\s*:)/,w=/^(?:px|rem|em|ex|ch|cap|ic|lh|rlh|vw|vh|vi|vb|vmin|vmax|[sld]v[whib]|cm|mm|q|in|pt|pc|%)$/i,I=e=>String(Number(e.toPrecision(12)));function $(e,t){if(e.length>4096||!/^calc\(/i.test(e))return null;let r=5,n=0,i=()=>{throw Error("Invalid calc expression")},a=()=>{for(;/\s/.test(e[r]??"")&&r<e.length;)r++},o=(e,t="")=>!Number.isFinite(e)||t&&!w.test(t)?i():{kind:t?"length":"number",terms:new Map([[t.toLowerCase(),e]])},s=(e,t)=>({...e,terms:new Map([...e.terms].map(([e,r])=>{let n=r*t;return Number.isFinite(n)||i(),[e,n]}))}),l=()=>{a(),++n>32&&i();try{let n=e[r];if("+"===n||"-"===n)return r++,s(l(),"-"===n?-1:1);if("("===e[r]||/^calc\(/i.test(e.slice(r))){r+="("===e[r]?1:5;let t=u();return a(),")"!==e[r++]&&i(),t}let d=e.slice(r).match(b)?.[0];if(d){r+=d.length;let e=v(t,d);if("layout"!==e?.kind)return i();let n=t.find(e=>e.name.toLowerCase()===d.slice(1).split(":")[0].trim().toLowerCase());return o(e.value,e.unit||("increment"===n?.scaleMode?"":"px"))}let c=e.slice(r).match(/^(\d+\.?\d*|\.\d+)(e[+-]?\d+)?([a-z]+|%)?/i);return c?(r+=c[0].length,o(Number(c[1]+(c[2]??"")),c[3])):i()}finally{n--}},d=()=>{let t=l();for(;;){a();let n=e[r];if("*"!==n&&"/"!==n)return t;r++;let o=l();if("/"===n){let e=o.terms.get("");if("number"!==o.kind||!e)return i();t=s(t,1/e)}else if("number"===o.kind)t=s(t,o.terms.get(""));else{if("number"!==t.kind)return i();t=s(o,t.terms.get(""))}}},u=()=>{let t=d();for(;;){a();let n=e[r];if("+"!==n&&"-"!==n)return t;r++;let o=d();if(t.kind!==o.kind)return i();for(let[e,r]of o.terms){let a=(t.terms.get(e)??0)+r*("-"===n?-1:1);Number.isFinite(a)||i(),t.terms.set(e,a)}}};try{let t=u();if(a(),")"!==e[r++]||e.slice(r).trim())return null;let n=[...t.terms].filter(([,e])=>0!==e);n.length||n.push([t.terms.keys().next().value??"",0]);let[i,o]=n[0];return{css:1===n.length?`${I(o)}${i}`:`calc(${n.map(([e,t],r)=>`${r?t<0?" - ":" + ":t<0?"-":""}${I(Math.abs(t))}${e}`).join("")})`,kind:t.kind,...1===n.length?{value:o,unit:i}:{}}}catch{return null}}function E(e,t){let r=e;for(let n of function(e){let t=[],r=/url\((?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^)'"])*\)|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\*[\s\S]*?\*\/|\bcalc\(/gi;for(let n;n=r.exec(e);){if(!/^calc\(/i.test(n[0]))continue;let i=1,a=r.lastIndex;for(;a<e.length&&i;)"("===e[a]?i++:")"===e[a]&&i--,a++;t.push({start:n.index,end:a,text:e.slice(n.index,a)}),r.lastIndex=a}return t}(e).reverse()){let e=$(n.text,t);if(!e)return null;r=r.slice(0,n.start)+e.css+r.slice(n.end)}return r}function x(e,t){let r=[],n=(e,t,n)=>{let i=k(e,{});i&&r.push({start:t,end:n,color:i})},i=(e,a=0,o=!1)=>{let s=0;for(;s<e.length;){let l=e[s];if('"'===l||"'"===l){let t=l;for(s++;s<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t){s++;break}continue}if(e.startsWith("/*",s)){let t=e.indexOf("*/",s+2);s=t<0?e.length:t+2;continue}if("@"===l){let n=e.slice(s).match(/^@([^:@(),/]+):\s*([+-]?(?:\d+\.?\d*|\.\d+))(?![\w.])(?:\s*\/\s*[+-]?(?:\d+\.?\d*|\.\d+)%?(?![\w.%]))?(?!\s*\/)/),i=e.slice(s).match(/^@([\w-]+)(?![\w-]|\s*:)(?:\s*\/\s*([+-]?(?:\d+\.?\d*|\.\d+)%?)(?![\w.%]))?(?!\s*\/)/),l=o?e.slice(s).match(b):n??i;if(l){let e=v(t,l[0]),n=m(l[0]);n&&r.push({start:a+s,end:a+s+l[0].length,color:"color"===e?.kind?f(e):null,reference:n,...o?{math:!0}:{}}),s+=l[0].length}else s+=e.slice(s).match(/^@[^\s,()]*(?:\s*:\s*[^\s,()]*)?/)?.[0].length??1;continue}let d=e.slice(s).match(/^(?:#[\w-]+|[\w-]+)/)?.[0];if(!d){s++;continue}let u=s;if(s+=d.length,"("!==e[s]){o||n(d,a+u,a+s);continue}let c=++s,p=1,h="";for(;s<e.length&&p;){let t=e[s++];"\\"!==t?h?t===h&&(h=""):'"'===t||"'"===t?h=t:"("===t?p++:")"===t&&p--:s++}if(p)continue;let g=k(e.slice(u,s),{});g?r.push({start:a+u,end:a+s,color:g}):/^(?:(?:repeating-)?(?:linear|radial|conic)-gradient|drop-shadow|calc)$/i.test(d)&&i(e.slice(c,s-1),a+c,o||"calc"===d.toLowerCase())}};return i(e),r}function C(e,t){return x(e,t).flatMap(e=>e.color?[{...e,color:e.color}]:[])}function N(e,t){return x(e,t).flatMap(({reference:e,start:t,end:r,math:n})=>e?[{...e,start:t,end:r,...n?{math:!0}:{}}]:[])}function S(e,t){return C(e,t).map(({color:e})=>e)}function A(e,t){let r=N(e,t);return null!==E(e,t)&&r.length===(e.match(/@/g)?.length??0)&&r.every(({start:r,end:n})=>null!==v(t,e.slice(r,n)))}function F(e,t,r=!1){let n=E(e,t);if(null===n)return null;let i=n;for(let e of N(n,t).reverse()){let a=v(t,n.slice(e.start,e.end));if(!a)return null;i=i.slice(0,e.start)+f(a)+(r&&"layout"===a.kind&&!a.unit?"px":"")+i.slice(e.end)}return i}function M(e,t,r,n){if(void 0!==n){let i=N(e,r)[n];return!i||void 0!==i.opacity&&"color"!==t.kind||i.math&&"layout"!==t.kind?null:e.slice(0,i.start)+`@${t.name}${null===i.step?"":`: ${i.step}`}${void 0===i.opacity?"":` / ${i.opacity}`}`+e.slice(i.end)}let i=m(e);if(i||!e.trim())return void 0!==i?.opacity&&"color"!==t.kind?null:`@${t.name}${null===i?.step?"":`: ${i?.step??0}`}${void 0===i?.opacity?"":` / ${i.opacity}`}`;let a=C(e,r);if("color"===t.kind&&1===a.length){let{start:r,end:n}=a[0],i=m(e.slice(r,n));return`${e.slice(0,r)}@${t.name}${null===i?.step?"":`: ${i?.step??0}`}${void 0===i?.opacity?"":` / ${i.opacity}`}${e.slice(n)}`}return/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?$/i.test(e.trim())?`@${t.name}: 0`:null}var U=["page","body","heading","muted","card","button","input"],R=["color","backgroundColor","border","borderColor","borderWidth","borderRadius","boxShadow","padding","paddingInline","paddingBlock","gap","fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","opacity"];function z(e){var t;let r={};for(let n of e.usage??[]){if(!U.includes(n.target)||!R.includes(n.property))continue;let i=null;try{if("token"===n.source.kind){let t=e.tokens.find(e=>e.id===n.source.id);t&&(i=F(t.value,e.constraints,!["fontWeight","opacity"].includes(n.property)))}else if("dimension"===n.source.kind){let t=p(e.constraints,n.source.id,n.source.step??0);i=f(t),"layout"===t.kind&&!t.unit&&!["fontWeight","opacity"].includes(n.property)&&(i+="px")}}catch{continue}(i&&/^-?\d+(?:\.\d+)?$/.test(i)&&["fontSize","letterSpacing","padding","paddingInline","paddingBlock","gap","borderRadius","borderWidth"].includes(n.property)&&(i+="px"),!i||/[;{}]|\b(?:url|expression|var)\s*\(/i.test(i)||i.includes("\\")||[...i].some(e=>e.charCodeAt(0)<32)||typeof CSS<"u"&&CSS.supports&&!CSS.supports(n.property.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),i))||((r[t=n.target]??(r[t]={}))[n.property]=["fontWeight","opacity"].includes(n.property)&&Number.isFinite(Number(i))?Number(i):i)}return r}var T=class extends Error{};function L(){let e=t();return{...e,tokens:[],constraints:e.constraints.map(e=>({...e,value:"",parentId:null}))}}var j=(e,t=512)=>"string"==typeof e&&e.length<=t&&![...e].some(e=>e.charCodeAt(0)<32)&&!/[;{}]|\b(?:url|expression)\s*\(/i.test(e);function O(e,t){if(!t||"object"!=typeof t||Array.isArray(t)||Object.keys(t).some(e=>!["name","constraints","tokens","usage","featuredComponentId"].includes(e)))throw Error("Invalid proposal patch.");let r=structuredClone(e);if(void 0!==t.featuredComponentId){if(null!==t.featuredComponentId&&!r.fragments?.some(e=>e.id===t.featuredComponentId))throw Error("The featured component must belong to this Taste.");r.featuredComponentId=t.featuredComponentId}if(void 0!==t.name){if("string"!=typeof t.name||t.name.length>80)throw Error("Invalid name.");r.name=t.name}if(void 0!==t.constraints){if(!Array.isArray(t.constraints)||t.constraints.length>32)throw Error("Invalid dimensions.");let e=new Set;for(let n of t.constraints){if(!n||"object"!=typeof n||Object.keys(n).some(e=>!["id","value","parentId","derivative","scale"].includes(e)))throw Error("Invalid dimension patch.");let t=r.constraints.find(e=>e.id===n.id);if(!t||e.has(n.id))throw Error("Unknown or duplicate dimension ID.");if(e.add(n.id),Object.assign(t,n),!j(t.value)||!Number.isFinite(t.derivative)||!Number.isFinite(t.scale)||t.scale<0||"increment"===t.scaleMode&&t.scale<=0||"color"===t.kind&&t.scale>1||"font"===t.kind&&(1!==t.scale||1!==t.derivative)||"layout"===t.kind&&t.derivative<0||null!==t.parentId&&!r.constraints.some(e=>e.id===t.parentId&&e.kind===t.kind))throw Error(`Invalid ${t.id} dimension.`)}for(let e of r.constraints)(e.value||e.parentId)&&p(r.constraints,e.id)}if(void 0!==t.tokens){if(!Array.isArray(t.tokens)||t.tokens.length>128)throw Error("Invalid tokens.");let e=new Set,n=new Set;for(let r of t.tokens){if(!r||"string"!=typeof r.id||!/^[a-zA-Z0-9_-]{1,80}$/.test(r.id)||"string"!=typeof r.name||!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(r.name)||!j(r.value)||e.has(r.id)||n.has(r.name))throw Error("Invalid or duplicate token.");e.add(r.id),n.add(r.name)}r.tokens=structuredClone(t.tokens)}void 0!==t.usage&&(r.usage=structuredClone(t.usage));for(let e of r.tokens)if(!A(e.value,r.constraints))throw Error(`Invalid reference or calc expression in ${e.name}.`);if(!Array.isArray(r.usage??[])||(r.usage?.length??0)>128)throw Error("Invalid usage mappings.");for(let e of r.usage??[])if(!e||Object.keys(e).some(e=>!["target","property","source"].includes(e))||!U.includes(e.target)||!R.includes(e.property)||!e.source||Object.keys(e.source).some(e=>!["kind","id","step"].includes(e))||!["token","dimension"].includes(e.source.kind)||!("token"===e.source.kind?r.tokens:r.constraints).some(t=>t.id===e.source.id)||void 0!==e.source.step&&(!Number.isInteger(e.source.step)||Math.abs(e.source.step)>100))throw Error("Usage must reference an existing token or dimension.");return r}function W(e,r=!0,n=!0){let i=t(),a={past:[],future:[]},o={current:{past:[],future:[]}},s={available:r,revision:crypto.randomUUID(),runId:"",openRequest:"",open:!1,mode:"empty",state:e?"complete":"idle",message:"",draft:e??null},l=new Set,d=null,u=new Set,c=e=>{d={id:crypto.randomUUID(),target:e,expiresAt:Date.now()+2e3},u.forEach(e=>e())},m=()=>{d=null,u.forEach(e=>e())},h=e=>{s={...s,...e,revision:crypto.randomUUID()},l.forEach(e=>e())},v={setCreationAllowed(e){n=e},history:o,getLookSnapshot:()=>d,subscribeLook:e=>(u.add(e),()=>{u.delete(e)}),setAvailable(e){s.available!==e&&h({available:e})},getSnapshot:()=>s,subscribe:e=>(l.add(e),()=>{l.delete(e)}),create(e="template",r=!1){if(!n)throw Error("An active subscription is required to create a Taste.");m(),"template"===e&&!r&&(i=t()),"template"===e?(r||(a.past=[],a.future=[]),o.current=a):o.current={past:[],future:[]},h({open:!0,openRequest:crypto.randomUUID(),runId:crypto.randomUUID(),mode:e,state:"extract"===e?"running":"complete",message:"",draft:"template"===e?i:L()})},edit(e){"running"!==s.state&&("template"===s.mode&&(i=e),h({draft:e}))},addFragment(e,t){if(s.runId!==e||!s.open||"running"===s.state||!s.draft)throw Error("This proposal has changed. Capture the component again.");let r=s.draft;if((r.fragments?.length??0)>=16)throw Error("A proposal can contain up to 16 components.");if(r.fragments?.some(e=>e.id===t.fragment.id))throw Error("This component was already captured.");if(t.tokens.some(e=>r.tokens.some(t=>t.id===e.id||t.name===e.name)))throw Error("A component token conflicts with a shared token. Retry capture.");let n=O({...r,usage:[]},{tokens:t.tokens}),i=e=>{for(let t of Object.values(e.styles))if(!("token"===t.kind?[...r.tokens,...n.tokens]:n.constraints).some(e=>e.id===t.id))throw Error("A referenced Taste value was removed. Retry capture.");e.children.forEach(e=>{"string"!=typeof e&&i(e)})};i(t.fragment.root);let a={...r,fragments:[...r.fragments??[],{...t.fragment,tokens:t.tokens}]};return o.current.past.push(r),o.current.past.length>100&&o.current.past.shift(),o.current.future=[],v.edit(a),a},stream(e,t){s.runId===e&&"running"===s.state&&h(t)},close(){m(),h({open:!1,..."running"===s.state?{state:"error",message:"Extraction stopped. Retry or continue editing the partial draft."}:{}})},command(e){let t=(e,t={})=>({status:e,...s,...t,saved:!1,applied:!1});if(void 0!==e.target&&"inspect"!==e.action)return t("invalid",{error:"target is only supported for inspection."});if("inspect"===e.action){let r=e.target;if(void 0!==r){let{draft:e,...t}=s,n=(e,r={})=>({status:e,...t,saved:!1,applied:!1,...r});if(!r||!["dimension","token"].includes(r.kind)||"string"!=typeof r.id||!r.id||r.id.length>200)return n("invalid");let i=("dimension"===r.kind?e?.constraints:e?.tokens)?.find(e=>e.id===r.id);if(!i||!e)return n("not_found",{target:r});let a,o=null;try{o="dimension"===r.kind?f(p(e.constraints,r.id)):F(i.value,e.constraints)}catch(e){a=e instanceof Error?e.message:"Not resolved yet"}return c({kind:r.kind,id:r.id}),n("ok",{target:r,row:i,resolved:o,...a?{resolutionError:a}:{}})}return s.draft&&c(null),t("ok")}if(!s.available)return t("unavailable",{error:"The host Taste panel is not available in this browser."});if(!["create","modify"].includes(e.action))return t("invalid",{error:"Unknown proposal action."});if(!e.expectedRevision||e.expectedRevision!==s.revision)return t("conflict");if("running"===s.state)return t("busy");try{if("create"===e.action){let t=e.mode??"template";if(!["template","empty","extract"].includes(t)||e.patch)throw Error("Create accepts a mode; modify the returned draft separately.");v.create(t)}else{if(!s.draft)return t("not_found");let r=O(s.draft,e.patch);o.current.past=[...o.current.past.slice(-99),s.draft],o.current.future=[],"template"===s.mode&&(i=r),h({draft:r,open:!0,openRequest:crypto.randomUUID()})}return t("ok")}catch(e){return t("invalid",{error:e instanceof Error?e.message:"Invalid patch."})}}};return v}var D=W(null,!1,!1);e.connect(D);export{t as a,n as b,u as c,c as d,p as e,f,m as g,h,v as i,g as j,y as k,k as l,$ as m,E as n,C as o,N as p,S as q,F as r,M as s,z as t,T as u,L as v,W as w,D as x};
|