// @bun
var{defineProperty:w,getOwnPropertyNames:T,getOwnPropertyDescriptor:E}=Object,C=Object.prototype.hasOwnProperty;function y(j){return this[j]}var m=(j)=>{var q=(M??=new WeakMap).get(j),B;if(q)return q;if(q=w({},"__esModule",{value:!0}),j&&typeof j==="object"||typeof j==="function"){for(var F of T(j))if(!C.call(q,F))w(q,F,{get:y.bind(j,F),enumerable:!(B=E(j,F))||B.enumerable})}return M.set(j,q),q},M;var x=(j)=>j;function U(j,q){this[j]=x.bind(null,q)}var u=(j,q)=>{for(var B in q)w(j,B,{get:q[B],enumerable:!0,configurable:!0,set:U.bind(q,B)})};var V=(j,q)=>()=>(j&&(q=j(j=0)),q);var p=import.meta.require;async function b(j,q){let{endpoint:B,method:F="POST",headers:O={},expirationSeconds:Q=3600,oneTimeUse:X=!1,params:J={}}=q,$=JSON.stringify({url:j,expirationSeconds:Q,oneTimeUse:X,...J}),Y=await fetch(B,{method:F,headers:{"Content-Type":"application/json",...O},body:F!=="GET"?$:void 0});if(!Y.ok)throw Error(`Failed to sign URL: ${Y.status} ${Y.statusText}`);let G=await Y.json();return{url:G.url||G.signedUrl,signature:G.signature,expires:G.expires||Date.now()+Q*1000,oneTimeUse:G.oneTimeUse||X}}async function f(j,q){let{endpoint:B,method:F="POST",headers:O={},expirationSeconds:Q=3600,oneTimeUse:X=!1,params:J={}}=q,$=JSON.stringify({urls:j,expirationSeconds:Q,oneTimeUse:X,...J}),Y=await fetch(B,{method:F,headers:{"Content-Type":"application/json",...O},body:F!=="GET"?$:void 0});if(!Y.ok)throw Error(`Failed to batch sign URLs: ${Y.status} ${Y.statusText}`);let G=await Y.json(),K=new Map,H=new Map;if(Array.isArray(G.results))for(let Z of G.results)if(Z.error)H.set(Z.url,Z.error);else K.set(Z.url||Z.originalUrl,{url:Z.signedUrl||Z.url,signature:Z.signature,expires:Z.expires||Date.now()+Q*1000,oneTimeUse:Z.oneTimeUse||X});else if(typeof G.signatures==="object"){for(let[Z,R]of Object.entries(G.signatures)){let P=R;K.set(Z,{url:P.signedUrl||P.url||Z,signature:P.signature,expires:P.expires||Date.now()+Q*1000,oneTimeUse:X})}if(G.errors)for(let[Z,R]of Object.entries(G.errors))H.set(Z,R)}return{signatures:K,errors:H}}async function i(j,q,B=10){let F=new Map,O=new Map,Q=[];for(let J=0;J<j.length;J+=B)Q.push(j.slice(J,J+B));let X=await Promise.all(Q.map((J)=>f(J,q)));for(let J of X){for(let[$,Y]of J.signatures)F.set($,Y);for(let[$,Y]of J.errors)O.set($,Y)}return{signatures:F,errors:O}}function S(j){return j.expires>Date.now()}function A(j){return Math.max(0,j.expires-Date.now())}function d(j,q=300000){return A(j)<q}async function D(j){if(j.check)return await j.check();return!0}function z(j){let q={};if(j.role)q.role=j.role;if(j.permission)q.permission=j.permission;if(j.userId)q.userId=j.userId;return q}async function c(j,q){let B=`${j}:${q.endpoint}`,F=W.get(B);if(F&&S(F)&&!d(F))return F;let O=await b(j,q);return W.set(B,O),O}function n(){W.clear()}function s(){let j=0,q=Date.now();for(let[B,F]of W)if(F.expires<=q)W.delete(B),j++;return j}function I(){return`
(function() {
  'use strict';

  if (typeof window === 'undefined') return;

  window.STX = window.STX || {};
  var cache = new Map();

  window.STX.signUrl = async function(src, config) {
    var cacheKey = src + ':' + config.endpoint;
    var cached = cache.get(cacheKey);

    if (cached && cached.expires > Date.now()) {
      return cached;
    }

    var response = await fetch(config.endpoint, {
      method: config.method || 'POST',
      headers: Object.assign({ 'Content-Type': 'application/json' }, config.headers || {}),
      body: JSON.stringify({ url: src, expirationSeconds: config.expirationSeconds || 3600 })
    });

    if (!response.ok) throw new Error('Failed to sign URL');

    var data = await response.json();
    var signed = {
      url: data.url || data.signedUrl,
      signature: data.signature,
      expires: data.expires || Date.now() + (config.expirationSeconds || 3600) * 1000
    };

    cache.set(cacheKey, signed);
    return signed;
  };

  window.STX.batchSignUrls = async function(sources, config) {
    var response = await fetch(config.endpoint, {
      method: config.method || 'POST',
      headers: Object.assign({ 'Content-Type': 'application/json' }, config.headers || {}),
      body: JSON.stringify({ urls: sources, expirationSeconds: config.expirationSeconds || 3600 })
    });

    if (!response.ok) throw new Error('Failed to batch sign URLs');

    return response.json();
  };

  window.STX.loadProtectedMedia = async function(element, config) {
    var src = element.dataset.protectedSrc;
    if (!src) return;

    try {
      var signed = await window.STX.signUrl(src, config);
      if (element.tagName === 'IMG') {
        element.src = signed.url;
      }
else if (element.tagName === 'VIDEO') {
        element.src = signed.url;
        element.load();
      }
else if (element.tagName === 'SOURCE') {
        element.src = signed.url;
        element.parentElement.load();
      }
    }
catch (error) {
      console.error('Failed to load protected media:', error);
      if (element.dataset.fallback) {
        element.src = element.dataset.fallback;
      }
    }
  };
})();
`.trim()}var W;var N=V(()=>{W=new Map});async function jj(j){let{src:q,alt:B="",signatureEndpoint:F="/api/sign",signatureConfig:O={},auth:Q,fallback:X,oneTimeUse:J=!0}=j,$=j.class,Y=j.style;if(Q){if(!await D(Q)){if(X)return{html:`<img src="${_(X)}" alt="${_(B)}"${$?` class="${_($)}"`:""}${Y?` style="${_(Y)}"`:""} />`};return{html:"<!-- Protected content: access denied -->"}}}let G={endpoint:F,oneTimeUse:J,...O,params:Q?z(Q):O.params},K=`stx-protected-${Math.random().toString(36).slice(2,8)}`,H=[`id="${K}"`,`data-protected-src="${_(q)}"`,`data-signature-endpoint="${_(F)}"`,`alt="${_(B)}"`];if(X)H.push(`data-fallback="${_(X)}"`),H.push(`src="${_(X)}"`);else H.push('src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"');if($)H.push(`class="${_($)}"`);if(Y)H.push(`style="${_(Y)}"`);let Z=`
(function() {
  var el = document.getElementById('${K}');
  if (!el) return;

  STX.loadProtectedMedia(el, {
    endpoint: '${_(F)}',
    oneTimeUse: ${J},
    expirationSeconds: ${O.expirationSeconds||3600}
  });
})();
`.trim();return{html:`<img ${H.join(" ")} />`,script:Z}}async function qj(j){let{src:q,signatureEndpoint:B="/api/sign",signatureConfig:F={},auth:O,fallback:Q,oneTimeUse:X=!0,poster:J,controls:$=!0,autoplay:Y=!1,muted:G=!1,loop:K=!1}=j,H=j.class,Z=j.style,R=j.alt;if(O){if(!await D(O))return{html:"<!-- Protected video: access denied -->"}}let P=`stx-protected-video-${Math.random().toString(36).slice(2,8)}`,L=[`id="${P}"`,`data-protected-src="${_(q)}"`,`data-signature-endpoint="${_(B)}"`];if(J)L.push(`poster="${_(J)}"`);if($)L.push("controls");if(Y)L.push("autoplay");if(G)L.push("muted");if(K)L.push("loop");if(H)L.push(`class="${_(H)}"`);if(Z)L.push(`style="${_(Z)}"`);if(Q)L.push(`data-fallback="${_(Q)}"`);let k=`
(function() {
  var el = document.getElementById('${P}');
  if (!el) return;

  STX.loadProtectedMedia(el, {
    endpoint: '${_(B)}',
    oneTimeUse: ${X},
    expirationSeconds: ${F.expirationSeconds||3600}
  });
})();
`.trim();return{html:`<video ${L.join(" ")}></video>`,script:k}}async function Bj(j,q){let B=/data-protected-src="([^"]+)"/g,F=[],O;while((O=B.exec(j))!==null)F.push(O[1]);if(F.length===0)return{html:j,script:""};let Q=I()+`

`;return Q+=`
(function() {
  var sources = ${JSON.stringify(F)};
  var endpoint = '${_(q)}';

  // Batch sign all URLs
  STX.batchSignUrls(sources, { endpoint: endpoint })
    .then(function(data) {
      sources.forEach(function(src) {
        var els = document.querySelectorAll('[data-protected-src="' + src + '"]');
        var signedUrl = data.signatures && data.signatures[src];

        els.forEach(function(el) {
          if (signedUrl) {
            if (el.tagName === 'IMG') el.src = signedUrl.url;
            else if (el.tagName === 'VIDEO') { el.src = signedUrl.url; el.load(); }
          }
else if (el.dataset.fallback) {
            el.src = el.dataset.fallback;
          }
        });
      });
    })
    .catch(function(error) {
      console.error('Failed to sign protected media:', error);
      document.querySelectorAll('[data-protected-src]').forEach(function(el) {
        if (el.dataset.fallback) el.src = el.dataset.fallback;
      });
    });
})();
`.trim(),{html:j,script:Q}}function Fj(j,q,B){if(q.src)return{src:String(q.src),alt:String(q.alt||""),signatureEndpoint:String(q.signatureEndpoint||"/api/sign"),auth:q.auth,fallback:q.fallback?String(q.fallback):void 0,oneTimeUse:q.oneTimeUse!==!1};let F=j.trim();if(F.startsWith("@protected(")||F.startsWith("("))F=F.replace(/^@protected\(/,"").replace(/^\(/,"").replace(/\)$/,"");let O=h(F);return{src:v(O[0],B)||"",alt:v(O[1],B)||"",...typeof O[2]==="object"?O[2]:{}}}function h(j){let q=[],B="",F=!1,O="",Q=0;for(let X=0;X<j.length;X++){let J=j[X],$=X>0?j[X-1]:"";if((J==='"'||J==="'")&&$!=="\\"){if(!F)F=!0,O=J;else if(J===O)F=!1;else B+=J;continue}if(!F){if(J==="{")Q++;if(J==="}")Q--;if(J===","&&Q===0){q.push(B.trim()),B="";continue}}B+=J}if(B.trim())q.push(B.trim());return q}function v(j,q){if(typeof j!=="string")return j;let B=j.trim();if(B.startsWith('"')&&B.endsWith('"')||B.startsWith("'")&&B.endsWith("'"))return B.slice(1,-1);if(q[B]!==void 0)return q[B];if(B.startsWith("{"))try{return JSON.parse(B)}catch{}return B}function _(j){return j.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#039;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var l=V(()=>{N()});l();export{qj as renderProtectedVideo,jj as renderProtectedImg,Bj as processProtectedMedia,Fj as parseProtectedArgs};
