@lunora/container 1.0.0-alpha.30 → 1.0.0-alpha.32

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.
@@ -1,4 +1,4 @@
1
- import{DurableObject as F,WorkerEntrypoint as $}from"cloudflare:workers";function D(i=9){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=new Uint8Array(i);crypto.getRandomValues(e);let n="";for(let s=0;s<i;s++)n+=t[e[s]%t.length];return n}function W(i){if(typeof i=="number")return i;if(typeof i=="string"){const t=i.match(/^(\d+)([smh])$/);if(!t)throw new Error(`invalid time expression ${i}`);const e=parseInt(t[1]),n=t[2];switch(n){case"s":return e;case"m":return e*60;case"h":return e*60*60;default:throw new Error(`unknown time unit ${n}`)}}throw new Error(`invalid type for a time expression: ${typeof i}`)}const B="there is no container instance that can be provided to this durable object",_="you are requesting too many containers per second",E="runtime signalled the container to exit:",C="container exited with unexpected exit code:",j="container is not listening",T="__CF_CONTAINER_STATE",k="OUTBOUND_CONFIGURATION",U=3,O=100,G=180*1e3,P=5e3,V="10m",v=300,H=8e3,R=2e4,N=33;function et(i,t){return t}const g=new Map,S=new Map,A=new Map,K={SIGINT:2,SIGTERM:15,SIGKILL:9};function m(i,t){return(i instanceof Error?i.message:String(i)).toLowerCase().includes(t)}const I=i=>m(i,B),X=i=>m(i,_),J=i=>m(i,E),M=i=>m(i,j),Y=i=>m(i,C);function z(i){return i instanceof Error?J(i)?+i.message.toLowerCase().slice(i.message.toLowerCase().indexOf(E)+E.length+1):Y(i)?+i.message.toLowerCase().slice(i.message.toLowerCase().indexOf(C)+C.length+1):null:null}function L(i,t){const e=new AbortController;if(i?.aborted)return e.abort(),e.signal;i?.addEventListener("abort",()=>e.abort());const n=setTimeout(()=>e.abort(),t);return e.signal.addEventListener("abort",()=>clearTimeout(n)),e.signal}function x(i,t){const e=i.split("*");if(e.length===1)return i===t;if(!t.startsWith(e[0])||!t.endsWith(e[e.length-1]))return!1;let n=e[0].length;for(let s=1;s<e.length-1;s++){const o=t.indexOf(e[s],n);if(o===-1)return!1;n=o+e[s].length}return n<=t.length-e[e.length-1].length}function q(i,t){return t.some(e=>x(e,i))}function Q(i){let t=i.length;for(;t>0&&i[t-1]===".";)t--;return i.slice(0,t)}class Z{storage;status;constructor(t){this.storage=t}async setRunning(){await this.setStatusAndupdate("running")}async setHealthy(){await this.setStatusAndupdate("healthy")}async setStopping(){await this.setStatusAndupdate("stopping")}async setStopped(){await this.setStatusAndupdate("stopped")}async setStoppedIfUnchanged(t){this.status===t&&await this.setStopped()}async setStoppedWithCode(t){this.status={status:"stopped_with_code",lastChange:Date.now(),exitCode:t},await this.update()}async getState(){if(!this.status){const t=await this.storage.get(T);t?this.status=t:(this.status={status:"stopped",lastChange:Date.now()},await this.update())}return this.status}async setStatusAndupdate(t){this.status={status:t,lastChange:Date.now()},await this.update()}async update(){if(!this.status)throw new Error("status should be init");await this.storage.put(T,this.status)}}class nt extends ${async fetch(t){const e=new URL(t.url),n=Q(e.hostname),{className:s,containerId:o,outboundByHostOverrides:a,outboundHandlerOverride:c,enableInternet:d,allowedHosts:r,deniedHosts:l,interceptAll:f}=this.ctx.props,p={containerId:o,className:s};if(l&&q(n,l))return new Response("Origin is disallowed",{status:520});if(r&&!q(n,r))return new Response("Origin is disallowed",{status:520});const y=g.get(s);if(a&&y){const w=a[n]??Object.entries(a).find(([b])=>b!==n&&x(b,n))?.[1];if(w&&y[w.method])return y[w.method](t,this.env,{...p,params:w.params})}const u=A.get(s);if(u){const w=u[n]??Object.entries(u).find(([b])=>b!==n&&x(b,n))?.[1];if(w)return w(t,this.env,p)}if(!f)return r||d?fetch(t):new Response("Origin is disallowed",{status:520});if(c&&y?.[c.method])return y[c.method](t,this.env,{...p,params:c.params});const h=S.get(s);return h&&y?.[h]?y[h](t,this.env,p):r||d?fetch(t):new Response("Origin is disallowed",{status:520})}}class st extends F{static get outboundByHost(){return A.get(this.name)}static set outboundByHost(t){A.set(this.name,t)}static get outboundHandlers(){return g.get(this.name)}static set outboundHandlers(t){const e=g.get(this.name)??{};g.set(this.name,{...e,...t})}static get outbound(){const t=S.get(this.name);if(t)return g.get(this.name)?.[t]}static set outbound(t){const e="__outbound__",n=g.get(this.name)??{};g.set(this.name,{...n,[e]:t}),S.set(this.name,e)}static get outboundProxies(){return this.outboundHandlers}static set outboundProxies(t){this.outboundHandlers=t}static get outboundProxy(){return this.outbound}static set outboundProxy(t){this.outbound=t}defaultPort;requiredPorts;sleepAfter=V;envVars={};entrypoint;enableInternet=!0;labels={};interceptHttps=!1;allowedHosts;deniedHosts;pingEndpoint="ping";applyOutboundInterceptionPromise=Promise.resolve();usingInterception=!1;constructor(t,e,n){if(super(t,e),t.container===void 0)throw new Error("Containers have not been enabled for this Durable Object class. Have you correctly setup your Wrangler config? More info: https://developers.cloudflare.com/containers/get-started/#configuration");this.state=new Z(this.ctx.storage);const s=this.restoreOutboundConfiguration();this.ctx.blockConcurrencyWhile(async()=>{await this.scheduleNextAlarm(),this.renewActivityTimeout();const o=this.constructor;(s!==void 0||o.outboundByHost!==void 0||o.outbound!==void 0||o.outboundHandlers!==void 0||this.effectiveAllowedHosts!==void 0||this.effectiveDeniedHosts!==void 0)&&(this.usingInterception=!0),this.container.running&&(this.applyOutboundInterceptionPromise=this.applyOutboundInterception())}),this.container=t.container,n&&(n.defaultPort!==void 0&&(this.defaultPort=n.defaultPort),n.sleepAfter!==void 0&&(this.sleepAfter=n.sleepAfter),n.envVars!==void 0&&(this.envVars=n.envVars),n.entrypoint!==void 0&&(this.entrypoint=n.entrypoint),n.enableInternet!==void 0&&(this.enableInternet=n.enableInternet)),this.sql`
1
+ import{WorkerEntrypoint as B,DurableObject as D}from"cloudflare:workers";function $(i=9){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",e=new Uint8Array(i);crypto.getRandomValues(e);let n="";for(let s=0;s<i;s++)n+=t[e[s]%t.length];return n}function W(i){if(typeof i=="number")return i;if(typeof i=="string"){const t=i.match(/^(\d+)([smh])$/);if(!t)throw new Error(`invalid time expression ${i}`);const e=parseInt(t[1]),n=t[2];switch(n){case"s":return e;case"m":return e*60;case"h":return e*60*60;default:throw new Error(`unknown time unit ${n}`)}}throw new Error(`invalid type for a time expression: ${typeof i}`)}const F="there is no container instance that can be provided to this durable object",U="you are requesting too many containers per second",H="runtime signalled the container to exit:",T="container exited with unexpected exit code:",q="container is not listening",R="__CF_CONTAINER_STATE",x="OUTBOUND_CONFIGURATION",j=3,E=100,G=180*1e3,N=5e3,V="10m",v=300,O=8e3,P=2e4,M=33;function et(i,t){return t}const w=new Map,S=new Map,C=new Map,K={SIGINT:2,SIGTERM:15,SIGKILL:9};function m(i,t){return(i instanceof Error?i.message:String(i)).toLowerCase().includes(t)}const I=i=>m(i,F),X=i=>m(i,U),J=i=>m(i,H),k=i=>m(i,q),Y=i=>m(i,T);function z(i){return i instanceof Error?J(i)?+i.message.toLowerCase().slice(i.message.toLowerCase().indexOf(H)+H.length+1):Y(i)?+i.message.toLowerCase().slice(i.message.toLowerCase().indexOf(T)+T.length+1):null:null}function _(i,t){const e=new AbortController;if(i?.aborted)return e.abort(),e.signal;i?.addEventListener("abort",()=>e.abort());const n=setTimeout(()=>e.abort(),t);return e.signal.addEventListener("abort",()=>clearTimeout(n)),e.signal}function A(i,t){const e=i.split("*");if(e.length===1)return i===t;if(!t.startsWith(e[0])||!t.endsWith(e[e.length-1]))return!1;let n=e[0].length;for(let s=1;s<e.length-1;s++){const o=t.indexOf(e[s],n);if(o===-1)return!1;n=o+e[s].length}return n<=t.length-e[e.length-1].length}function L(i,t){return t.some(e=>A(e,i))}function Z(i){let t=i.length;for(;t>0&&i[t-1]===".";)t--;return i.slice(0,t)}class Q{storage;status;constructor(t){this.storage=t}async setRunning(){await this.setStatusAndupdate("running")}async setHealthy(){await this.setStatusAndupdate("healthy")}async setStopping(){await this.setStatusAndupdate("stopping")}async setStopped(){await this.setStatusAndupdate("stopped")}async setStoppedIfUnchanged(t){this.status===t&&await this.setStopped()}async setStoppedWithCode(t){this.status={status:"stopped_with_code",lastChange:Date.now(),exitCode:t},await this.update()}async getState(){if(!this.status){const t=await this.storage.get(R);t?this.status=t:(this.status={status:"stopped",lastChange:Date.now()},await this.update())}return this.status}async setStatusAndupdate(t){this.status={status:t,lastChange:Date.now()},await this.update()}async update(){if(!this.status)throw new Error("status should be init");await this.storage.put(R,this.status)}}class nt extends B{async fetch(t){const e=new URL(t.url),n=Z(e.hostname),{className:s,containerId:o,outboundByHostOverrides:a,outboundHandlerOverride:c,enableInternet:d,allowedHosts:r,deniedHosts:l,interceptAll:p}=this.ctx.props,f={containerId:o,className:s};if(l&&L(n,l))return new Response("Origin is disallowed",{status:520});if(r&&!L(n,r))return new Response("Origin is disallowed",{status:520});const g=w.get(s);if(a&&g){const y=a[n]??Object.entries(a).find(([b])=>b!==n&&A(b,n))?.[1];if(y&&g[y.method])return g[y.method](t,this.env,{...f,params:y.params})}const h=C.get(s);if(h){const y=h[n]??Object.entries(h).find(([b])=>b!==n&&A(b,n))?.[1];if(y)return y(t,this.env,f)}if(!p)return r||d?fetch(t):new Response("Origin is disallowed",{status:520});if(c&&g?.[c.method])return g[c.method](t,this.env,{...f,params:c.params});const u=S.get(s);return u&&g?.[u]?g[u](t,this.env,f):r||d?fetch(t):new Response("Origin is disallowed",{status:520})}}class st extends D{static get outboundByHost(){return C.get(this.name)}static set outboundByHost(t){C.set(this.name,t)}static get outboundHandlers(){return w.get(this.name)}static set outboundHandlers(t){const e=w.get(this.name)??{};w.set(this.name,{...e,...t})}static get outbound(){const t=S.get(this.name);if(t)return w.get(this.name)?.[t]}static set outbound(t){const e="__outbound__",n=w.get(this.name)??{};w.set(this.name,{...n,[e]:t}),S.set(this.name,e)}static get outboundProxies(){return this.outboundHandlers}static set outboundProxies(t){this.outboundHandlers=t}static get outboundProxy(){return this.outbound}static set outboundProxy(t){this.outbound=t}defaultPort;requiredPorts;sleepAfter=V;envVars={};entrypoint;enableInternet=!0;labels={};interceptHttps=!1;allowedHosts;deniedHosts;pingEndpoint="ping";applyOutboundInterceptionPromise=Promise.resolve();usingInterception=!1;constructor(t,e,n){if(super(t,e),t.container===void 0)throw new Error("Containers have not been enabled for this Durable Object class. Have you correctly setup your Wrangler config? More info: https://developers.cloudflare.com/containers/get-started/#configuration");this.state=new Q(this.ctx.storage);const s=this.restoreOutboundConfiguration();this.ctx.blockConcurrencyWhile(async()=>{await this.scheduleNextAlarm(),this.renewActivityTimeout();const o=this.constructor;(s!==void 0||o.outboundByHost!==void 0||o.outbound!==void 0||o.outboundHandlers!==void 0||this.effectiveAllowedHosts!==void 0||this.effectiveDeniedHosts!==void 0)&&(this.usingInterception=!0),this.container.running&&(this.applyOutboundInterceptionPromise=this.applyOutboundInterception())}),this.container=t.container,n&&(n.defaultPort!==void 0&&(this.defaultPort=n.defaultPort),n.sleepAfter!==void 0&&(this.sleepAfter=n.sleepAfter),n.envVars!==void 0&&(this.envVars=n.envVars),n.entrypoint!==void 0&&(this.entrypoint=n.entrypoint),n.enableInternet!==void 0&&(this.enableInternet=n.enableInternet)),this.sql`
2
2
  CREATE TABLE IF NOT EXISTS container_schedules (
3
3
  id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),
4
4
  callback TEXT NOT NULL,
@@ -8,7 +8,7 @@ import{DurableObject as F,WorkerEntrypoint as $}from"cloudflare:workers";functio
8
8
  delayInSeconds INTEGER,
9
9
  created_at INTEGER DEFAULT (unixepoch())
10
10
  )
11
- `,this.container.running&&(this.monitor=this.container.monitor(),this.setupMonitorCallbacks())}async getState(){return{...await this.state.getState()}}async setOutboundHandler(t,...e){this.validateOutboundHandlerMethodName(t),this.outboundHandlerOverride=e.length===0?{method:t}:{method:t,params:e[0]},await this.refreshOutboundInterception()}async setOutboundByHost(t,e,...n){this.validateOutboundHandlerMethodName(e),this.outboundByHostOverrides[t]=n.length===0?{method:e}:{method:e,params:n[0]},await this.refreshOutboundInterception()}async removeOutboundByHost(t){delete this.outboundByHostOverrides[t],await this.refreshOutboundInterception()}async setOutboundByHosts(t){for(const e of Object.values(t)){const n=typeof e=="string"?e:e.method;this.validateOutboundHandlerMethodName(n)}this.outboundByHostOverrides=Object.fromEntries(Object.entries(t).map(([e,n])=>[e,typeof n=="string"?{method:n}:n])),await this.refreshOutboundInterception()}async setAllowedHosts(t){this.allowedHostsOverride=[...t],this.usingInterception=!0,await this.refreshOutboundInterception()}async setDeniedHosts(t){this.deniedHostsOverride=[...t],this.usingInterception=!0,await this.refreshOutboundInterception()}async allowHost(t){const e=this.effectiveAllowedHosts??[];e.includes(t)||(this.allowedHostsOverride=[...e,t]),this.usingInterception=!0,await this.refreshOutboundInterception()}async denyHost(t){const e=this.effectiveDeniedHosts??[];e.includes(t)||(this.deniedHostsOverride=[...e,t]),this.usingInterception=!0,await this.refreshOutboundInterception()}async removeAllowedHost(t){this.allowedHostsOverride=(this.effectiveAllowedHosts??[]).filter(e=>e!==t),await this.refreshOutboundInterception()}async removeDeniedHost(t){this.deniedHostsOverride=(this.effectiveDeniedHosts??[]).filter(e=>e!==t),await this.refreshOutboundInterception()}async start(t,e){const n=e?.portToCheck??this.defaultPort??(this.requiredPorts?this.requiredPorts[0]:N),s=e?.waitInterval??v;await this.startContainerIfNotRunning({signal:e?.signal,waitInterval:s,retries:e?.retries??Math.ceil(H/s),portToCheck:n},t),this.setupMonitorCallbacks(),await this.ctx.blockConcurrencyWhile(async()=>{await this.onStart()})}async startAndWaitForPorts(t,e,n){let s,o,a;typeof t=="object"&&t!==null&&!Array.isArray(t)?(s=t.ports,o=t.cancellationOptions,a=t.startOptions):(s=t,o=e,a=n);const c=await this.getPortsToCheck(s);await this.syncPendingStoppedEvents(),o??={};const d=o.instanceGetTimeoutMS??H,r=o.waitInterval??v,l=Math.ceil(d/r),f={signal:o.abort,retries:l,waitInterval:r,portToCheck:c[0]},p=await this.startContainerIfNotRunning(f,a);let y=Math.ceil((o.portReadyTimeoutMS??R)/r)-p;for(const u of c)y=await this.waitForPort({signal:o.abort,waitInterval:r,retries:y,portToCheck:u});this.setupMonitorCallbacks(),await this.ctx.blockConcurrencyWhile(async()=>{await this.state.setHealthy(),await this.onStart()})}async waitForPort(t){const e=t.portToCheck,n=this.container.getTcpPort(e),s=new Promise(c=>{t.signal?.addEventListener("abort",()=>{c(!0)})}),o=t.waitInterval??v,a=t.retries??Math.ceil(R/o);for(let c=0;c<a;c++)try{const d=L(t.signal,P);await n.fetch(`http://${this.pingEndpoint}`,{signal:d});break}catch(d){const r=d instanceof Error?d.message:String(d);if(!this.container.running){try{await this.onError(new Error("Container crashed while checking for ports, did you start the container and setup the entrypoint correctly?"))}catch{}throw d}if(c===a-1){try{await this.onError(`Failed to verify port ${e} is available after ${(c+1)*o}ms, last error: ${r}`)}catch{}throw d}if(await Promise.any([new Promise(l=>setTimeout(l,o)),s]),t.signal?.aborted)throw new Error("Container request aborted.",{cause:d})}return a}async stop(t="SIGTERM"){this.container.running&&this.container.signal(typeof t=="string"?K[t]:t),await this.syncPendingStoppedEvents()}async destroy(){await this.container.destroy()}onStart(){}onStop(t){}async onActivityExpired(){console.log("Activity expired, signalling container to stop"),this.container.running&&await this.stop()}onError(t){throw console.error("Container error:",t),t}renewActivityTimeout(){const t=W(this.sleepAfter)*1e3;this.sleepAfterMs=Date.now()+t}decrementInflight(){this.inflightRequests=Math.max(0,this.inflightRequests-1),this.inflightRequests===0&&this.renewActivityTimeout()}async schedule(t,e,n){const s=D(9);if(typeof e!="string")throw new Error("Callback must be a string (method name)");if(typeof this[e]!="function")throw new Error(`this.${e} is not a function`);if(t instanceof Date){const o=Math.floor(t.getTime()/1e3);return this.sql`
11
+ `,this.container.running&&(this.monitor=this.container.monitor(),this.setupMonitorCallbacks())}async getState(){return{...await this.state.getState()}}async setOutboundHandler(t,...e){this.validateOutboundHandlerMethodName(t),this.outboundHandlerOverride=e.length===0?{method:t}:{method:t,params:e[0]},await this.refreshOutboundInterception()}async setOutboundByHost(t,e,...n){this.validateOutboundHandlerMethodName(e),this.outboundByHostOverrides[t]=n.length===0?{method:e}:{method:e,params:n[0]},await this.refreshOutboundInterception()}async removeOutboundByHost(t){delete this.outboundByHostOverrides[t],await this.refreshOutboundInterception()}async setOutboundByHosts(t){for(const e of Object.values(t)){const n=typeof e=="string"?e:e.method;this.validateOutboundHandlerMethodName(n)}this.outboundByHostOverrides=Object.fromEntries(Object.entries(t).map(([e,n])=>[e,typeof n=="string"?{method:n}:n])),await this.refreshOutboundInterception()}async setAllowedHosts(t){this.allowedHostsOverride=[...t],this.usingInterception=!0,await this.refreshOutboundInterception()}async setDeniedHosts(t){this.deniedHostsOverride=[...t],this.usingInterception=!0,await this.refreshOutboundInterception()}async allowHost(t){const e=this.effectiveAllowedHosts??[];e.includes(t)||(this.allowedHostsOverride=[...e,t]),this.usingInterception=!0,await this.refreshOutboundInterception()}async denyHost(t){const e=this.effectiveDeniedHosts??[];e.includes(t)||(this.deniedHostsOverride=[...e,t]),this.usingInterception=!0,await this.refreshOutboundInterception()}async removeAllowedHost(t){this.allowedHostsOverride=(this.effectiveAllowedHosts??[]).filter(e=>e!==t),await this.refreshOutboundInterception()}async removeDeniedHost(t){this.deniedHostsOverride=(this.effectiveDeniedHosts??[]).filter(e=>e!==t),await this.refreshOutboundInterception()}async start(t,e){const n=e?.portToCheck??this.defaultPort??(this.requiredPorts?this.requiredPorts[0]:M),s=e?.waitInterval??v;await this.startContainerIfNotRunning({signal:e?.signal,waitInterval:s,retries:e?.retries??Math.ceil(O/s),portToCheck:n},t),this.setupMonitorCallbacks(),await this.ctx.blockConcurrencyWhile(async()=>{await this.onStart()})}async startAndWaitForPorts(t,e,n){let s,o,a;typeof t=="object"&&t!==null&&!Array.isArray(t)?(s=t.ports,o=t.cancellationOptions,a=t.startOptions):(s=t,o=e,a=n);const c=await this.getPortsToCheck(s);await this.syncPendingStoppedEvents(),o??={};const d=o.instanceGetTimeoutMS??O,r=o.waitInterval??v,l=Math.ceil(d/r),p={signal:o.abort,retries:l,waitInterval:r,portToCheck:c[0]},f=await this.startContainerIfNotRunning(p,a);let h=Math.ceil((o.portReadyTimeoutMS??P)/r)-f;for(const u of c)h=await this.waitForPort({signal:o.abort,waitInterval:r,retries:h,portToCheck:u});this.setupMonitorCallbacks(),await this.ctx.blockConcurrencyWhile(async()=>{await this.state.setHealthy(),await this.onStart()})}async waitForPort(t){const e=t.portToCheck,n=this.container.getTcpPort(e),s=new Promise(c=>{t.signal?.addEventListener("abort",()=>{c(!0)})}),o=t.waitInterval??v,a=t.retries??Math.ceil(P/o);for(let c=0;c<a;c++)try{const d=_(t.signal,N);await n.fetch(`http://${this.pingEndpoint}`,{signal:d});break}catch(d){const r=d instanceof Error?d.message:String(d);if(!this.container.running){try{await this.onError(new Error("Container crashed while checking for ports, did you start the container and setup the entrypoint correctly?"))}catch{}throw d}if(c===a-1){try{await this.onError(`Failed to verify port ${e} is available after ${(c+1)*o}ms, last error: ${r}`)}catch{}throw d}if(await Promise.any([new Promise(l=>setTimeout(l,o)),s]),t.signal?.aborted)throw new Error("Container request aborted.",{cause:d})}return a}async stop(t="SIGTERM"){this.container.running&&this.container.signal(typeof t=="string"?K[t]:t),await this.syncPendingStoppedEvents()}async destroy(){await this.container.destroy()}onStart(){}onStop(t){}async onActivityExpired(){console.log("Activity expired, signalling container to stop"),this.container.running&&await this.stop()}onError(t){throw console.error("Container error:",t),t}renewActivityTimeout(){const t=W(this.sleepAfter)*1e3;this.sleepAfterMs=Date.now()+t}decrementInflight(){this.inflightRequests=Math.max(0,this.inflightRequests-1),this.inflightRequests===0&&this.renewActivityTimeout()}async schedule(t,e,n){const s=$(9);if(typeof e!="string")throw new Error("Callback must be a string (method name)");if(typeof this[e]!="function")throw new Error(`this.${e} is not a function`);if(t instanceof Date){const o=Math.floor(t.getTime()/1e3);return this.sql`
12
12
  INSERT OR REPLACE INTO container_schedules (id, callback, payload, type, time)
13
13
  VALUES (${s}, ${e}, ${JSON.stringify(n)}, 'scheduled', ${o})
14
14
  `,await this.scheduleNextAlarm(),{taskId:s,callback:e,payload:n,time:o,type:"scheduled"}}if(typeof t=="number"){const o=Math.floor(Date.now()/1e3+t);return this.sql`
@@ -16,11 +16,11 @@ import{DurableObject as F,WorkerEntrypoint as $}from"cloudflare:workers";functio
16
16
  VALUES (${s}, ${e}, ${JSON.stringify(n)}, 'delayed', ${t}, ${o})
17
17
  `,await this.scheduleNextAlarm(),{taskId:s,callback:e,payload:n,delayInSeconds:t,time:o,type:"delayed"}}throw new Error("Invalid schedule type. 'when' must be a Date or number of seconds")}async containerFetch(t,e,n){const{request:s,port:o}=this.requestAndPortFromContainerFetchArgs(t,e,n),a=await this.state.getState();if(!this.container.running||a.status!=="healthy")try{await this.startAndWaitForPorts(o,{abort:s.signal})}catch(r){return I(r)?new Response(`There is no Container instance available at this time.
18
18
  This is likely because you have reached your max concurrent instance count (set in wrangler config) or are you currently provisioning the Container.
19
- If you are deploying your Container for the first time, check your dashboard to see provisioning status, this may take a few minutes.`,{status:503}):X(r)?new Response(r instanceof Error?r.message:String(r),{status:429}):new Response(`Failed to start container: ${r instanceof Error?r.message:String(r)}`,{status:500})}const c=this.container.getTcpPort(o),d=s.url.replace("https:","http:");this.inflightRequests++;try{this.renewActivityTimeout();const r=await c.fetch(d,s);if(r.webSocket!==null){const l=r.webSocket,[f,p]=Object.values(new WebSocketPair);let y=!1;const u=()=>{y||(y=!0,this.decrementInflight())};return l.accept(),p.accept(),p.addEventListener("message",async h=>{this.renewActivityTimeout();try{const w=h.data instanceof Blob?await h.data.arrayBuffer():h.data;l.send(w)}catch{p.close(1011,"Failed to forward message to container")}}),l.addEventListener("message",async h=>{this.renewActivityTimeout();try{const w=h.data instanceof Blob?await h.data.arrayBuffer():h.data;p.send(w)}catch{l.close(1011,"Failed to forward message to client")}}),p.addEventListener("close",h=>{u();const w=h.code===1005||h.code===1006?1e3:h.code;l.close(w,h.reason)}),l.addEventListener("close",h=>{u();const w=h.code===1005||h.code===1006?1e3:h.code;p.close(w,h.reason)}),p.addEventListener("error",()=>{u(),l.close(1011,"Client WebSocket error")}),l.addEventListener("error",()=>{u(),p.close(1011,"Container WebSocket error")}),new Response(null,{status:r.status,webSocket:f,headers:r.headers})}if(r.body!==null){const{readable:l,writable:f}=new IdentityTransformStream;return r.body?.pipeTo(f).finally(()=>{this.decrementInflight()}),new Response(l,r)}return this.decrementInflight(),r}catch(r){if(this.decrementInflight(),!(r instanceof Error))throw r;return r.message.includes("Network connection lost.")?new Response("Container suddenly disconnected, try again",{status:500}):(console.error(`Error proxying request to container ${this.ctx.id}:`,r),new Response(`Error proxying request to container: ${r instanceof Error?r.message:String(r)}`,{status:500}))}}async fetch(t){if(this.defaultPort===void 0&&!t.headers.has("cf-container-target-port"))throw new Error("No port configured for this container. Set the `defaultPort` in your Container subclass, or specify a port with `container.fetch(switchPort(request, port))`.");let e=this.defaultPort;if(t.headers.has("cf-container-target-port")){const n=parseInt(t.headers.get("cf-container-target-port")??"");if(isNaN(n))throw new Error("port value from switchPort is not a number");e=n}return await this.containerFetch(t,e)}container;onStopCalled=!1;state;monitor;startInFlight;monitoredPromise;sleepAfterMs=0;inflightRequests=0;outboundByHostOverrides={};outboundHandlerOverride;allowedHostsOverride;deniedHostsOverride;hasInterceptAllRegistration=!1;validateOutboundHandlerMethodName(t){const e=g.get(this.constructor.name);if(!e||!(t in e))throw new Error(`Outbound handler method '${t}' not found in outboundHandlers for ${this.constructor.name}`)}get effectiveAllowedHosts(){return this.allowedHostsOverride??this.allowedHosts}get effectiveDeniedHosts(){return this.deniedHostsOverride??this.deniedHosts}getOutboundConfiguration(){return{outboundByHostOverrides:Object.keys(this.outboundByHostOverrides).length>0?this.outboundByHostOverrides:void 0,outboundHandlerOverride:this.outboundHandlerOverride,allowedHosts:this.effectiveAllowedHosts,deniedHosts:this.effectiveDeniedHosts,hasInterceptAllRegistration:this.hasInterceptAllRegistration||void 0}}persistOutboundConfiguration(t){this.ctx.storage.kv.put(k,{...t,allowedHosts:this.allowedHostsOverride,deniedHosts:this.deniedHostsOverride})}restoreOutboundConfiguration(){const t=this.ctx.storage.kv.get(k);if(t){if(this.outboundHandlerOverride=void 0,t.outboundHandlerOverride!==void 0)try{this.validateOutboundHandlerMethodName(t.outboundHandlerOverride.method),this.outboundHandlerOverride=t.outboundHandlerOverride}catch(e){console.warn("Ignoring invalid persisted outbound handler override:",e)}this.outboundByHostOverrides={};for(const[e,n]of Object.entries(t.outboundByHostOverrides??{}))try{this.validateOutboundHandlerMethodName(n.method),this.outboundByHostOverrides[e]=n}catch(s){console.warn(`Ignoring invalid persisted outbound override for ${e}:`,s)}return this.hasInterceptAllRegistration=t.hasInterceptAllRegistration===!0,t.allowedHosts&&(this.allowedHostsOverride=t.allowedHosts),t.deniedHosts&&(this.deniedHostsOverride=t.deniedHosts),this.getOutboundConfiguration()}}needsCatchAllInterception(){return this.constructor.outbound!==void 0||this.outboundHandlerOverride!==void 0}hasMutableOutboundConfiguration(){return Object.keys(this.outboundByHostOverrides).length>0||this.allowedHostsOverride!==void 0||this.deniedHostsOverride!==void 0}shouldInterceptAllOutbound(){return this.hasInterceptAllRegistration||this.needsCatchAllInterception()||this.effectiveAllowedHosts!==void 0||this.effectiveDeniedHosts!==void 0||this.hasMutableOutboundConfiguration()}getStaticOutboundByHostKeys(){const t=this.constructor;return t.outboundByHost?Object.keys(t.outboundByHost):[]}getHostsToIntercept(){const t=new Set,e=this.constructor;if(e.outboundByHost)for(const n of Object.keys(e.outboundByHost))t.add(n);for(const n of Object.keys(this.outboundByHostOverrides))t.add(n);return[...t]}async refreshOutboundInterception(){this.usingInterception&&(this.applyOutboundInterceptionPromise=this.applyOutboundInterception(),await this.applyOutboundInterceptionPromise)}async applyOutboundInterception(){const t=this.ctx;if(t.exports===void 0)throw new Error("ctx.exports is undefined, please try to update your compatibility date or export ContainerProxy from the containers package in your worker entrypoint");if(t.exports.ContainerProxy===void 0)throw new Error("ctx.exports.ContainerProxy is undefined, export ContainerProxy from the containers package in your worker entrypoint");const e=this.shouldInterceptAllOutbound();e&&(this.hasInterceptAllRegistration=e);const n=this.getOutboundConfiguration();this.persistOutboundConfiguration(n);const s=this.getHostsToIntercept(),o={enableInternet:this.enableInternet,containerId:this.ctx.id.toString(),className:this.constructor.name,outboundByHostOverrides:n.outboundByHostOverrides,outboundHandlerOverride:n.outboundHandlerOverride,allowedHosts:n.allowedHosts,deniedHosts:n.deniedHosts,interceptAll:e},a=t.exports.ContainerProxy({props:o});if(e){for(const c of this.getStaticOutboundByHostKeys())await this.container.interceptOutboundHttp(c,a),this.interceptHttps&&await this.container.interceptOutboundHttps(c,a);this.interceptHttps&&await this.container.interceptOutboundHttps("*",a),await this.container.interceptAllOutboundHttp(a)}else for(const c of s)await this.container.interceptOutboundHttp(c,a),this.interceptHttps&&await this.container.interceptOutboundHttps(c,a)}sql(t,...e){const n=t.reduce((s,o,a)=>s+o+(a<e.length?"?":""),"");return[...this.ctx.storage.sql.exec(n,...e)]}requestAndPortFromContainerFetchArgs(t,e,n){let s,o;if(t instanceof Request)s=t,o=typeof e=="number"?e:void 0;else{const a=typeof t=="string"?t:t.toString(),c=typeof e=="number"?{}:e||{};o=typeof e=="number"?e:typeof n=="number"?n:void 0,s=new Request(a,c)}if(o??=this.defaultPort,o===void 0)throw new Error("No port specified for container fetch. Set defaultPort or specify a port parameter.");return{request:s,port:o}}async getPortsToCheck(t){return t!==void 0?Array.isArray(t)?t:[t]:this.requiredPorts&&this.requiredPorts.length>0?[...this.requiredPorts]:[this.defaultPort??N]}async startContainerIfNotRunning(t,e){if(this.startInFlight)return this.startInFlight;if(this.container.running)return this.monitor||(this.monitor=this.container.monitor()),0;const n=this.doStartContainer(t,e);this.startInFlight=n;try{return await n}finally{this.startInFlight===n&&(this.startInFlight=void 0)}}async doStartContainer(t,e){const n=new Promise(a=>{t.signal?.addEventListener("abort",()=>{a(!0)})}),s=t.waitInterval??v,o=t.retries??Math.ceil(H/s);for(let a=0;a<o;a++){const c=e?.envVars??this.envVars,d=e?.entrypoint??this.entrypoint,r=e?.enableInternet??this.enableInternet,l=e?.labels??this.labels,f={enableInternet:r};c&&Object.keys(c).length>0&&(f.env=c),d&&(f.entrypoint=d),l&&Object.keys(l).length>0&&(f.labels=l),this.renewActivityTimeout();const p=async()=>{const u=await this.monitor?.catch(h=>h);if(typeof u=="number"){const h=new Error(`Container exited before we could determine the container health, exit code: ${u}`);await this.state.setStoppedWithCode(u),this.monitor=void 0;try{await this.onError(h)}catch{}throw h}else if(!I(u)){await this.state.setStopped(),this.monitor=void 0;try{await this.onError(u)}catch{}throw u}};a>0&&!this.container.running&&await p(),await this.scheduleNextAlarm(),this.container.running?await this.scheduleNextAlarm():(await this.refreshOutboundInterception(),this.container.start(f),this.monitor=this.container.monitor(),await this.state.setRunning()),this.renewActivityTimeout();const y=this.container.getTcpPort(t.portToCheck);try{const u=L(t.signal,P);return await y.fetch("http://containerstarthealthcheck",{signal:u}),a}catch(u){if(M(u)&&this.container.running)return a;if(!this.container.running&&M(u)&&await p(),await Promise.any([new Promise(h=>setTimeout(h,t.waitInterval)),n]),t.signal?.aborted)throw new Error("Aborted waiting for container to start as we received a cancellation signal",{cause:u});if(o===a+1)throw u instanceof Error&&u.message.includes("Network connection lost")&&this.ctx.abort(),await p(),await this.state.setStopped(),this.monitor=void 0,new Error(B,{cause:u});continue}}throw new Error(`Container did not start after ${o*s}ms`)}setupMonitorCallbacks(){const t=this.monitor;!t||this.monitoredPromise===t||(this.monitoredPromise=t,t.then(async()=>{await this.ctx.blockConcurrencyWhile(async()=>{this.monitor===t&&await this.state.setStoppedWithCode(0)})}).catch(async e=>{if(this.monitor!==t)return;if(I(e)){await this.ctx.blockConcurrencyWhile(async()=>{this.monitor===t&&await this.state.setStopped()});return}const n=z(e);if(n!==null){await this.ctx.blockConcurrencyWhile(async()=>{this.monitor===t&&await this.state.setStoppedWithCode(n)});return}if(await this.ctx.blockConcurrencyWhile(async()=>{this.monitor===t&&await this.state.setStopped()}),this.monitor===t)try{await this.onError(e)}catch{}}).finally(()=>{this.monitor===t&&(this.monitoredPromise=void 0,this.monitor=void 0)}))}deleteSchedules(t){this.sql`DELETE FROM container_schedules WHERE callback = ${t}`}async alarm(t){if(t!==void 0&&t.isRetry&&t.retryCount>U){((Number(this.sql`SELECT COUNT(*) as count FROM container_schedules`[0]?.count)||0)>0||this.container.running)&&await this.scheduleNextAlarm();return}const e=this.sql`
19
+ If you are deploying your Container for the first time, check your dashboard to see provisioning status, this may take a few minutes.`,{status:503}):X(r)?new Response(r instanceof Error?r.message:String(r),{status:429}):new Response(`Failed to start container: ${r instanceof Error?r.message:String(r)}`,{status:500})}const c=this.container.getTcpPort(o),d=s.url.replace("https:","http:");this.inflightRequests++;try{this.renewActivityTimeout();const r=await c.fetch(d,s);if(r.webSocket!==null){const l=r.webSocket,[p,f]=Object.values(new WebSocketPair);let g=!1;const h=()=>{g||(g=!0,this.decrementInflight())};return l.accept(),f.accept(),f.addEventListener("message",async u=>{this.renewActivityTimeout();try{const y=u.data instanceof Blob?await u.data.arrayBuffer():u.data;l.send(y)}catch{f.close(1011,"Failed to forward message to container")}}),l.addEventListener("message",async u=>{this.renewActivityTimeout();try{const y=u.data instanceof Blob?await u.data.arrayBuffer():u.data;f.send(y)}catch{l.close(1011,"Failed to forward message to client")}}),f.addEventListener("close",u=>{h();const y=u.code===1005||u.code===1006?1e3:u.code;l.close(y,u.reason)}),l.addEventListener("close",u=>{h();const y=u.code===1005||u.code===1006?1e3:u.code;f.close(y,u.reason)}),f.addEventListener("error",()=>{h(),l.close(1011,"Client WebSocket error")}),l.addEventListener("error",()=>{h(),f.close(1011,"Container WebSocket error")}),new Response(null,{status:r.status,webSocket:p,headers:r.headers})}if(r.body!==null){const{readable:l,writable:p}=new IdentityTransformStream;return r.body?.pipeTo(p).finally(()=>{this.decrementInflight()}),new Response(l,r)}return this.decrementInflight(),r}catch(r){if(this.decrementInflight(),!(r instanceof Error))throw r;return r.message.includes("Network connection lost.")?new Response("Container suddenly disconnected, try again",{status:500}):(console.error(`Error proxying request to container ${this.ctx.id}:`,r),new Response(`Error proxying request to container: ${r instanceof Error?r.message:String(r)}`,{status:500}))}}async fetch(t){if(this.defaultPort===void 0&&!t.headers.has("cf-container-target-port"))throw new Error("No port configured for this container. Set the `defaultPort` in your Container subclass, or specify a port with `container.fetch(switchPort(request, port))`.");let e=this.defaultPort;if(t.headers.has("cf-container-target-port")){const n=parseInt(t.headers.get("cf-container-target-port")??"");if(isNaN(n))throw new Error("port value from switchPort is not a number");e=n}return await this.containerFetch(t,e)}container;onStopCalled=!1;state;monitor;startInFlight;monitoredPromise;sleepAfterMs=0;inflightRequests=0;outboundByHostOverrides={};outboundHandlerOverride;allowedHostsOverride;deniedHostsOverride;hasInterceptAllRegistration=!1;validateOutboundHandlerMethodName(t){const e=w.get(this.constructor.name);if(!e||!(t in e))throw new Error(`Outbound handler method '${t}' not found in outboundHandlers for ${this.constructor.name}`)}get effectiveAllowedHosts(){return this.allowedHostsOverride??this.allowedHosts}get effectiveDeniedHosts(){return this.deniedHostsOverride??this.deniedHosts}getOutboundConfiguration(){return{outboundByHostOverrides:Object.keys(this.outboundByHostOverrides).length>0?this.outboundByHostOverrides:void 0,outboundHandlerOverride:this.outboundHandlerOverride,allowedHosts:this.effectiveAllowedHosts,deniedHosts:this.effectiveDeniedHosts,hasInterceptAllRegistration:this.hasInterceptAllRegistration||void 0}}persistOutboundConfiguration(t){this.ctx.storage.kv.put(x,{...t,allowedHosts:this.allowedHostsOverride,deniedHosts:this.deniedHostsOverride})}restoreOutboundConfiguration(){const t=this.ctx.storage.kv.get(x);if(t){if(this.outboundHandlerOverride=void 0,t.outboundHandlerOverride!==void 0)try{this.validateOutboundHandlerMethodName(t.outboundHandlerOverride.method),this.outboundHandlerOverride=t.outboundHandlerOverride}catch(e){console.warn("Ignoring invalid persisted outbound handler override:",e)}this.outboundByHostOverrides={};for(const[e,n]of Object.entries(t.outboundByHostOverrides??{}))try{this.validateOutboundHandlerMethodName(n.method),this.outboundByHostOverrides[e]=n}catch(s){console.warn(`Ignoring invalid persisted outbound override for ${e}:`,s)}return this.hasInterceptAllRegistration=t.hasInterceptAllRegistration===!0,t.allowedHosts&&(this.allowedHostsOverride=t.allowedHosts),t.deniedHosts&&(this.deniedHostsOverride=t.deniedHosts),this.getOutboundConfiguration()}}needsCatchAllInterception(){return this.constructor.outbound!==void 0||this.outboundHandlerOverride!==void 0}hasMutableOutboundConfiguration(){return Object.keys(this.outboundByHostOverrides).length>0||this.allowedHostsOverride!==void 0||this.deniedHostsOverride!==void 0}shouldInterceptAllOutbound(){return this.hasInterceptAllRegistration||this.needsCatchAllInterception()||this.effectiveAllowedHosts!==void 0||this.effectiveDeniedHosts!==void 0||this.hasMutableOutboundConfiguration()}getStaticOutboundByHostKeys(){const t=this.constructor;return t.outboundByHost?Object.keys(t.outboundByHost):[]}getHostsToIntercept(){const t=new Set,e=this.constructor;if(e.outboundByHost)for(const n of Object.keys(e.outboundByHost))t.add(n);for(const n of Object.keys(this.outboundByHostOverrides))t.add(n);return[...t]}async refreshOutboundInterception(){this.usingInterception&&(this.applyOutboundInterceptionPromise=this.applyOutboundInterception(),await this.applyOutboundInterceptionPromise)}async applyOutboundInterception(){const t=this.ctx;if(t.exports===void 0)throw new Error("ctx.exports is undefined, please try to update your compatibility date or export ContainerProxy from the containers package in your worker entrypoint");if(t.exports.ContainerProxy===void 0)throw new Error("ctx.exports.ContainerProxy is undefined, export ContainerProxy from the containers package in your worker entrypoint");const e=this.shouldInterceptAllOutbound();e&&(this.hasInterceptAllRegistration=e);const n=this.getOutboundConfiguration();this.persistOutboundConfiguration(n);const s=this.getHostsToIntercept(),o={enableInternet:this.enableInternet,containerId:this.ctx.id.toString(),className:this.constructor.name,outboundByHostOverrides:n.outboundByHostOverrides,outboundHandlerOverride:n.outboundHandlerOverride,allowedHosts:n.allowedHosts,deniedHosts:n.deniedHosts,interceptAll:e},a=t.exports.ContainerProxy({props:o});if(e){for(const c of this.getStaticOutboundByHostKeys())await this.container.interceptOutboundHttp(c,a),this.interceptHttps&&await this.container.interceptOutboundHttps(c,a);this.interceptHttps&&await this.container.interceptOutboundHttps("*",a),await this.container.interceptAllOutboundHttp(a)}else for(const c of s)await this.container.interceptOutboundHttp(c,a),this.interceptHttps&&await this.container.interceptOutboundHttps(c,a)}sql(t,...e){const n=t.reduce((s,o,a)=>s+o+(a<e.length?"?":""),"");return[...this.ctx.storage.sql.exec(n,...e)]}requestAndPortFromContainerFetchArgs(t,e,n){let s,o;if(t instanceof Request)s=t,o=typeof e=="number"?e:void 0;else{const a=typeof t=="string"?t:t.toString(),c=typeof e=="number"?{}:e||{};o=typeof e=="number"?e:typeof n=="number"?n:void 0,s=new Request(a,c)}if(o??=this.defaultPort,o===void 0)throw new Error("No port specified for container fetch. Set defaultPort or specify a port parameter.");return{request:s,port:o}}async getPortsToCheck(t){return t!==void 0?Array.isArray(t)?t:[t]:this.requiredPorts&&this.requiredPorts.length>0?[...this.requiredPorts]:[this.defaultPort??M]}async startContainerIfNotRunning(t,e){if(this.startInFlight)return this.startInFlight;if(this.container.running)return this.monitor||(this.monitor=this.container.monitor()),0;const n=this.doStartContainer(t,e);this.startInFlight=n;try{return await n}finally{this.startInFlight===n&&(this.startInFlight=void 0)}}async doStartContainer(t,e){const n=new Promise(a=>{t.signal?.addEventListener("abort",()=>{a(!0)})}),s=t.waitInterval??v,o=t.retries??Math.ceil(O/s);for(let a=0;a<o;a++){const c=e?.envVars??this.envVars,d=e?.entrypoint??this.entrypoint,r=e?.enableInternet??this.enableInternet,l=e?.labels??this.labels,p={enableInternet:r};c&&Object.keys(c).length>0&&(p.env=c),d&&(p.entrypoint=d),l&&Object.keys(l).length>0&&(p.labels=l),this.renewActivityTimeout();const f=async()=>{const h=await this.monitor?.catch(u=>u);if(typeof h=="number"){const u=new Error(`Container exited before we could determine the container health, exit code: ${h}`);await this.state.setStoppedWithCode(h),this.monitor=void 0;try{await this.onError(u)}catch{}throw u}else if(!I(h)){await this.state.setStopped(),this.monitor=void 0;try{await this.onError(h)}catch{}throw h}};a>0&&!this.container.running&&await f(),await this.scheduleNextAlarm(),this.container.running?await this.scheduleNextAlarm():(await this.refreshOutboundInterception(),this.container.start(p),this.monitor=this.container.monitor(),await this.state.setRunning()),this.renewActivityTimeout();const g=this.container.getTcpPort(t.portToCheck);try{const h=_(t.signal,N);return await g.fetch("http://containerstarthealthcheck",{signal:h}),a}catch(h){if(k(h)&&this.container.running)return a;if(!this.container.running&&k(h)&&await f(),await Promise.any([new Promise(u=>setTimeout(u,t.waitInterval)),n]),t.signal?.aborted)throw new Error("Aborted waiting for container to start as we received a cancellation signal",{cause:h});if(o===a+1)throw h instanceof Error&&h.message.includes("Network connection lost")&&this.ctx.abort(),await f(),await this.state.setStopped(),this.monitor=void 0,new Error(F,{cause:h});continue}}throw new Error(`Container did not start after ${o*s}ms`)}setupMonitorCallbacks(){const t=this.monitor;!t||this.monitoredPromise===t||(this.monitoredPromise=t,t.then(async()=>{await this.ctx.blockConcurrencyWhile(async()=>{this.monitor===t&&await this.state.setStoppedWithCode(0)})}).catch(async e=>{if(this.monitor!==t)return;if(I(e)){await this.ctx.blockConcurrencyWhile(async()=>{this.monitor===t&&await this.state.setStopped()});return}const n=z(e);if(n!==null){await this.ctx.blockConcurrencyWhile(async()=>{this.monitor===t&&await this.state.setStoppedWithCode(n)});return}if(await this.ctx.blockConcurrencyWhile(async()=>{this.monitor===t&&await this.state.setStopped()}),this.monitor===t)try{await this.onError(e)}catch{}}).finally(()=>{this.monitor===t&&(this.monitoredPromise=void 0,this.monitor=void 0)}))}deleteSchedules(t){this.sql`DELETE FROM container_schedules WHERE callback = ${t}`}async alarm(t){if(t!==void 0&&t.isRetry&&t.retryCount>j){((Number(this.sql`SELECT COUNT(*) as count FROM container_schedules`[0]?.count)||0)>0||this.container.running)&&await this.scheduleNextAlarm();return}const e=this.sql`
20
20
  SELECT * FROM container_schedules;
21
- `;let n=Date.now()+G;const s=Date.now()/1e3;for(const d of e){if(d.time>s)continue;const r=this[d.callback];if(!r||typeof r!="function"){console.error(`Callback ${d.callback} not found or is not a function`);continue}const l=this.getSchedule(d.id);try{const f=d.payload?JSON.parse(d.payload):void 0;await r.call(this,f,await l)}catch(f){console.error(`Error executing scheduled callback "${d.callback}":`,f)}this.sql`DELETE FROM container_schedules WHERE id = ${d.id}`}const o=this.sql`
21
+ `;let n=Date.now()+G;const s=Date.now()/1e3;for(const d of e){if(d.time>s)continue;const r=this[d.callback];if(!r||typeof r!="function"){console.error(`Callback ${d.callback} not found or is not a function`);continue}const l=this.getSchedule(d.id);try{const p=d.payload?JSON.parse(d.payload):void 0;await r.call(this,p,await l)}catch(p){console.error(`Error executing scheduled callback "${d.callback}":`,p)}this.sql`DELETE FROM container_schedules WHERE id = ${d.id}`}const o=this.sql`
22
22
  SELECT * FROM container_schedules;
23
- `,a=Math.min(...o.map(d=>d.time*1e3));if(!this.container.running){await this.syncPendingStoppedEvents(),o.length==0?await this.ctx.storage.deleteAlarm():await this.ctx.storage.setAlarm(a);return}if(this.isActivityExpired()){await this.onActivityExpired(),this.renewActivityTimeout(),await this.ctx.storage.setAlarm(Date.now()+O);return}n=Math.min(a,n,this.sleepAfterMs);const c=Math.max(n,Date.now()+O);await this.ctx.storage.setAlarm(c)}async syncPendingStoppedEvents(){const t=await this.state.getState();if(!this.container.running&&(t.status==="healthy"||t.status==="running")){await this.callOnStop({exitCode:0,reason:"exit"},t);return}if(!this.container.running&&t.status==="stopped_with_code"){await this.callOnStop({exitCode:t.exitCode??0,reason:"exit"},t);return}}async callOnStop(t,e){if(this.onStopCalled)return;this.onStopCalled=!0;const n=this.onStop(t);n instanceof Promise?await n.finally(()=>{this.onStopCalled=!1}):this.onStopCalled=!1,await this.state.setStoppedIfUnchanged(e)}async scheduleNextAlarm(t=1e3){const e=Date.now()+Math.max(t,O),n=await this.ctx.storage.getAlarm();n!==null&&n<=e||(await this.ctx.storage.setAlarm(e),await this.ctx.storage.sync())}async listSchedules(t){const e=this.sql`
23
+ `,a=Math.min(...o.map(d=>d.time*1e3));if(!this.container.running){await this.syncPendingStoppedEvents(),o.length==0?await this.ctx.storage.deleteAlarm():await this.ctx.storage.setAlarm(a);return}if(this.isActivityExpired()){await this.onActivityExpired(),this.renewActivityTimeout(),await this.ctx.storage.setAlarm(Date.now()+E);return}n=Math.min(a,n,this.sleepAfterMs);const c=Math.max(n,Date.now()+E);await this.ctx.storage.setAlarm(c)}async syncPendingStoppedEvents(){const t=await this.state.getState();if(!this.container.running&&(t.status==="healthy"||t.status==="running")){await this.callOnStop({exitCode:0,reason:"exit"},t);return}if(!this.container.running&&t.status==="stopped_with_code"){await this.callOnStop({exitCode:t.exitCode??0,reason:"exit"},t);return}}async callOnStop(t,e){if(this.onStopCalled)return;this.onStopCalled=!0;const n=this.onStop(t);n instanceof Promise?await n.finally(()=>{this.onStopCalled=!1}):this.onStopCalled=!1,await this.state.setStoppedIfUnchanged(e)}async scheduleNextAlarm(t=1e3){const e=Date.now()+Math.max(t,E),n=await this.ctx.storage.getAlarm();n!==null&&n<=e||(await this.ctx.storage.setAlarm(e),await this.ctx.storage.sync())}async listSchedules(t){const e=this.sql`
24
24
  SELECT * FROM container_schedules WHERE callback = ${t} LIMIT 1
25
25
  `;return!e||e.length===0?[]:e.map(this.toSchedule)}toSchedule(t){let e;try{e=JSON.parse(t.payload)}catch(n){console.error(`Error parsing payload for schedule ${t.id}:`,n),e=void 0}return t.type==="delayed"?{taskId:t.id,callback:t.callback,payload:e,type:"delayed",time:t.time,delayInSeconds:t.delayInSeconds}:{taskId:t.id,callback:t.callback,payload:e,type:"scheduled",time:t.time}}async getSchedule(t){const e=this.sql`
26
26
  SELECT * FROM container_schedules WHERE id = ${t} LIMIT 1
@@ -1 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";const d=new Set(["basic","lite","standard-1","standard-2","standard-3","standard-4"]),o=/^[A-Z_]\w*$/i,l=/^\d+[smh]$/,u={h:3600,m:60,s:1},E=e=>{if(typeof e=="number")return Math.floor(e);if(l.exec(e)===null)throw new TypeError(`Invalid duration "${e}" — expected a number of seconds or "<n>[smh]"`);return Number(e.slice(0,-1))*(u[e.slice(-1)]??1)},m=e=>{const t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n===-1?t:t.slice(n+1)},y=e=>{const t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)||"/"},$=e=>{if(typeof e!="string")return"build"in e?{buildDir:e.build.endsWith("/")?e.build.slice(0,-1):e.build,kind:"build"}:{kind:"registry",reference:e.registry};if(m(e).startsWith("Dockerfile"))return{buildContext:y(e),dockerfilePath:e,kind:"dockerfile"};const t=e.endsWith("/")?e.slice(0,-1):e;return{buildContext:t,dockerfilePath:`${t}/Dockerfile`,kind:"dockerfile"}},k=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}Container`,I=e=>`CONTAINER_${e.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"_").toUpperCase()}`,S=e=>`lunora-${e.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"-").toLowerCase()}:build`,g=e=>{if(typeof e=="string"){if(e.length===0)throw new TypeError("defineContainer: `image` must be a non-empty path or a { registry } reference");if(e.includes(":"))throw new TypeError(`defineContainer: \`image\` string "${e}" looks like a registry reference — pass it as { registry: "${e}" } instead. Plain strings are local Dockerfile paths.`);return}if("build"in e){if(typeof e.build!="string"||e.build.length===0)throw new TypeError("defineContainer: `image.build` must be a non-empty source directory for Railpack to build");return}if(typeof e.registry!="string"||e.registry.length===0)throw new TypeError("defineContainer: `image.registry` must be a non-empty fully-qualified image reference")},h=(e,t,n)=>{for(const[r,i]of Object.entries(e.secretsStore??{})){if(!o.test(r))throw new TypeError(`defineContainer: secretsStore env name "${r}" is not a valid environment variable name`);if(typeof i!="string"||i.trim().length===0)throw new TypeError(`defineContainer: \`secretsStore["${r}"]\` must be a non-empty Secrets Store binding name`);if(t.has(r)||n.has(r))throw new TypeError(`defineContainer: "${r}" is declared in both \`secretsStore\` and \`env\`/\`secrets\` — pick one source for the value`)}},w=e=>{for(const r of Object.keys(e.env??{}))if(!o.test(r))throw new TypeError(`defineContainer: env variable name "${r}" is not a valid environment variable name`);for(const r of Object.keys(e.buildArgs??{}))if(!o.test(r))throw new TypeError(`defineContainer: buildArg name "${r}" is not a valid environment variable name`);const t=new Set(Object.keys(e.env??{})),n=new Set(e.secrets);for(const r of e.secrets??[]){if(!o.test(r))throw new TypeError(`defineContainer: secret name "${r}" is not a valid environment variable name`);if(t.has(r))throw new TypeError(`defineContainer: "${r}" is declared in both \`env\` and \`secrets\` — a secret would silently overwrite the static env value; pick one`)}h(e,t,n)},s=(e,t)=>{if(!Number.isInteger(e)||e<1||e>65535)throw new TypeError(`defineContainer: \`${t}\` must be an integer in 1–65535 (got ${String(e)})`)},b=e=>{for(const t of e.readyOn??[]){if(typeof t.path!="string"||t.path.trim().length===0)throw new TypeError("defineContainer: `readyOn[].path` must be a non-empty HTTP path string");if(t.path!==t.path.trim())throw new TypeError("defineContainer: `readyOn[].path` must not have leading or trailing whitespace");if(t.port!==void 0&&s(t.port,"readyOn[].port"),t.status!==void 0&&(!Number.isInteger(t.status)||t.status<100||t.status>599))throw new TypeError(`defineContainer: \`readyOn[].status\` must be an HTTP status code in 100–599 (got ${String(t.status)})`)}},f=(e,t)=>{if(e!==void 0){if(typeof e=="string"){if(!l.test(e))throw new TypeError(`defineContainer: \`${t}\` string "${e}" must be a number of seconds followed by a unit, e.g. "30s", "5m", or "1h"`)}else if(!Number.isInteger(e)||e<1)throw new TypeError(`defineContainer: \`${t}\` must be a positive integer number of seconds or a duration string like "5m" (got ${String(e)})`)}},v=e=>{for(const t of["allowedHosts","deniedHosts"])if(e[t]?.some(n=>typeof n!="string"||n.trim().length===0))throw new TypeError(`defineContainer: \`${t}\` must be an array of non-empty hostname patterns`);if(e.interceptHttps!==void 0&&typeof e.interceptHttps!="boolean")throw new TypeError("defineContainer: `interceptHttps` must be a boolean, or omitted")},C=e=>{if(e.requiredPorts!==void 0){if(e.requiredPorts.length===0)throw new TypeError("defineContainer: `requiredPorts` must be a non-empty array of ports, or omitted");for(const t of e.requiredPorts)s(t,"requiredPorts[]")}if(e.entrypoint!==void 0&&(e.entrypoint.length===0||e.entrypoint.some(t=>typeof t!="string"||t.trim().length===0)))throw new TypeError("defineContainer: `entrypoint` must be a non-empty array of non-empty strings, or omitted");if(v(e),e.pingEndpoint!==void 0&&(typeof e.pingEndpoint!="string"||e.pingEndpoint.trim().length===0))throw new TypeError("defineContainer: `pingEndpoint` must be a non-empty path string");for(const[t,n]of Object.entries(e.labels??{}))if(t.trim().length===0||typeof n!="string")throw new TypeError("defineContainer: `labels` must be a record of non-empty keys to string values");b(e)},P=e=>{g(e.image),e.defaultPort!==void 0&&s(e.defaultPort,"defaultPort");const t=e.rollout?.stepPercentage;if(t!==void 0&&(!Number.isInteger(t)||t<1||t>100))throw new TypeError(`defineContainer: \`rollout.stepPercentage\` must be an integer in 1–100 (got ${String(t)})`);if(e.maxInstances!==void 0&&(!Number.isInteger(e.maxInstances)||e.maxInstances<1))throw new TypeError(`defineContainer: \`maxInstances\` must be a positive integer (got ${String(e.maxInstances)})`);if(typeof e.instanceType=="string"&&!d.has(e.instanceType))throw new TypeError(`defineContainer: unknown \`instanceType\` "${e.instanceType}" — use one of ${[...d].join(", ")}, or a custom { vcpu, memoryMib, diskMb } object`);return f(e.sleepAfter,"sleepAfter"),f(e.hardTimeout,"hardTimeout"),w(e),C(e),{...e,isLunoraContainer:!0}},A=e=>typeof e=="object"&&e!==null&&e.isLunoraContainer===!0,N=(e,t,n)=>{const r={...e.env};for(const i of e.secrets??[]){const a=t[i];if(typeof a!="string"){const p=n===void 0?"container":`container "${n}"`;throw new c("INTERNAL",`${p}: declared secret "${i}" is not set on the Worker environment. Add it to .dev.vars for local dev and run \`wrangler secret put ${i}\` for production.`)}r[i]=a}return r};export{I as containerBindingName,S as containerBuildTag,k as containerClassName,P as defineContainer,A as isContainerDefinition,$ as normalizeContainerImage,E as parseDurationSeconds,N as resolveContainerEnvVars};
1
+ import{LunoraError as f}from"@lunora/errors";const d=new Set(["basic","lite","standard-1","standard-2","standard-3","standard-4"]),s=/^[A-Z_]\w*$/i,c=/^\d+[smh]$/,u={h:3600,m:60,s:1},g=e=>{if(typeof e=="number")return Math.floor(e);if(c.exec(e)===null)throw new TypeError(`Invalid duration "${e}" — expected a number of seconds or "<n>[smh]"`);return Number(e.slice(0,-1))*(u[e.slice(-1)]??1)},y=e=>{const t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n===-1?t:t.slice(n+1)},m=e=>{const t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)||"/"},$=e=>{if(typeof e!="string")return"build"in e?{buildDir:e.build.endsWith("/")?e.build.slice(0,-1):e.build,kind:"build"}:{kind:"registry",reference:e.registry};if(y(e).startsWith("Dockerfile"))return{buildContext:m(e),dockerfilePath:e,kind:"dockerfile"};const t=e.endsWith("/")?e.slice(0,-1):e;return{buildContext:t,dockerfilePath:`${t}/Dockerfile`,kind:"dockerfile"}},k=e=>`${e.charAt(0).toUpperCase()}${e.slice(1)}Container`,N=e=>`CONTAINER_${e.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"_").toUpperCase()}`,S=e=>`lunora-${e.replaceAll(/(?<=[a-z0-9])(?=[A-Z])/g,"-").toLowerCase()}:build`,h=e=>{if(typeof e=="string"){if(e.length===0)throw new TypeError("defineContainer: `image` must be a non-empty path or a { registry } reference");if(e.includes(":"))throw new TypeError(`defineContainer: \`image\` string "${e}" looks like a registry reference — pass it as { registry: "${e}" } instead. Plain strings are local Dockerfile paths.`);return}if("build"in e){if(typeof e.build!="string"||e.build.length===0)throw new TypeError("defineContainer: `image.build` must be a non-empty source directory for Railpack to build");return}if(typeof e.registry!="string"||e.registry.length===0)throw new TypeError("defineContainer: `image.registry` must be a non-empty fully-qualified image reference")},b=(e,t,n)=>{for(const[r,o]of Object.entries(e.secretsStore??{})){if(!s.test(r))throw new TypeError(`defineContainer: secretsStore env name "${r}" is not a valid environment variable name`);if(typeof o!="string"||o.trim().length===0)throw new TypeError(`defineContainer: \`secretsStore["${r}"]\` must be a non-empty Secrets Store binding name`);if(t.has(r)||n.has(r))throw new TypeError(`defineContainer: "${r}" is declared in both \`secretsStore\` and \`env\`/\`secrets\` — pick one source for the value`)}},w=e=>{for(const r of Object.keys(e.env??{}))if(!s.test(r))throw new TypeError(`defineContainer: env variable name "${r}" is not a valid environment variable name`);for(const r of Object.keys(e.buildArgs??{}))if(!s.test(r))throw new TypeError(`defineContainer: buildArg name "${r}" is not a valid environment variable name`);const t=new Set(Object.keys(e.env??{})),n=new Set(e.secrets);for(const r of e.secrets??[]){if(!s.test(r))throw new TypeError(`defineContainer: secret name "${r}" is not a valid environment variable name`);if(t.has(r))throw new TypeError(`defineContainer: "${r}" is declared in both \`env\` and \`secrets\` — a secret would silently overwrite the static env value; pick one`)}b(e,t,n)},i=(e,t)=>{if(!Number.isInteger(e)||e<1||e>65535)throw new TypeError(`defineContainer: \`${t}\` must be an integer in 1–65535 (got ${String(e)})`)},v=e=>{for(const t of e.readyOn??[]){if(typeof t.path!="string"||t.path.trim().length===0)throw new TypeError("defineContainer: `readyOn[].path` must be a non-empty HTTP path string");if(t.path!==t.path.trim())throw new TypeError("defineContainer: `readyOn[].path` must not have leading or trailing whitespace");if(t.port!==void 0&&i(t.port,"readyOn[].port"),t.status!==void 0&&(!Number.isInteger(t.status)||t.status<100||t.status>599))throw new TypeError(`defineContainer: \`readyOn[].status\` must be an HTTP status code in 100–599 (got ${String(t.status)})`)}},l=(e,t)=>{if(e!==void 0){if(typeof e=="string"){if(!c.test(e))throw new TypeError(`defineContainer: \`${t}\` string "${e}" must be a number of seconds followed by a unit, e.g. "30s", "5m", or "1h"`)}else if(!Number.isInteger(e)||e<1)throw new TypeError(`defineContainer: \`${t}\` must be a positive integer number of seconds or a duration string like "5m" (got ${String(e)})`)}},E=e=>{for(const t of["allowedHosts","deniedHosts"])if(e[t]?.some(r=>typeof r!="string"||r.trim().length===0))throw new TypeError(`defineContainer: \`${t}\` must be an array of non-empty hostname patterns`);if(e.interceptHttps!==void 0&&typeof e.interceptHttps!="boolean")throw new TypeError("defineContainer: `interceptHttps` must be a boolean, or omitted")},T=e=>{if(e.requiredPorts!==void 0){if(e.requiredPorts.length===0)throw new TypeError("defineContainer: `requiredPorts` must be a non-empty array of ports, or omitted");for(const t of e.requiredPorts)i(t,"requiredPorts[]")}if(e.entrypoint!==void 0&&(e.entrypoint.length===0||e.entrypoint.some(t=>typeof t!="string"||t.trim().length===0)))throw new TypeError("defineContainer: `entrypoint` must be a non-empty array of non-empty strings, or omitted");if(E(e),e.pingEndpoint!==void 0&&(typeof e.pingEndpoint!="string"||e.pingEndpoint.trim().length===0))throw new TypeError("defineContainer: `pingEndpoint` must be a non-empty path string");for(const[t,n]of Object.entries(e.labels??{}))if(t.trim().length===0||typeof n!="string")throw new TypeError("defineContainer: `labels` must be a record of non-empty keys to string values");v(e)},I=e=>{h(e.image),e.defaultPort!==void 0&&i(e.defaultPort,"defaultPort");const t=e.rollout?.stepPercentage;if(t!==void 0&&(!Number.isInteger(t)||t<1||t>100))throw new TypeError(`defineContainer: \`rollout.stepPercentage\` must be an integer in 1–100 (got ${String(t)})`);if(e.maxInstances!==void 0&&(!Number.isInteger(e.maxInstances)||e.maxInstances<1))throw new TypeError(`defineContainer: \`maxInstances\` must be a positive integer (got ${String(e.maxInstances)})`);if(typeof e.instanceType=="string"&&!d.has(e.instanceType))throw new TypeError(`defineContainer: unknown \`instanceType\` "${e.instanceType}" — use one of ${[...d].join(", ")}, or a custom { vcpu, memoryMib, diskMb } object`);return l(e.sleepAfter,"sleepAfter"),l(e.hardTimeout,"hardTimeout"),w(e),T(e),{...e,isLunoraContainer:!0}},A=e=>typeof e=="object"&&e!==null&&e.isLunoraContainer===!0,P=(e,t,n)=>{const r={...e.env};for(const o of e.secrets??[]){const a=t[o];if(typeof a!="string"){const p=n===void 0?"container":`container "${n}"`;throw new f("INTERNAL",`${p}: declared secret "${o}" is not set on the Worker environment. Add it to .dev.vars for local dev and run \`wrangler secret put ${o}\` for production.`)}r[o]=a}return r};export{N as containerBindingName,S as containerBuildTag,k as containerClassName,I as defineContainer,A as isContainerDefinition,$ as normalizeContainerImage,g as parseDurationSeconds,P as resolveContainerEnvVars};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{containerBindingName as k}from"./containerBindingName-D01FopQt.mjs";import{e as F,r as U}from"./exec-BjOpQOTW.mjs";import{a as I}from"./jurisdiction-DtE9s70w.mjs";const N=3,D=3e4,q=3,W=500,j="cf-container-target-port",v="__lunora",p=t=>t.split("/").find(e=>e!=="")??"",C=(t,e)=>{const o=typeof t=="string"?t:t.url,n=URL.parse(o.startsWith("/")?`http://container${o}`:o);if(n===null)return;const{pathname:r}=n;let s=r;try{s=decodeURIComponent(r)}catch{}if(p(r)===v||p(s)===v)throw new R("BAD_REQUEST",`${e}: \`/${v}/*\` is reserved for Lunora's own container routes and cannot be reached with \`fetch\`. Use \`exec\` to run a command.`)},P=(t,e,o,n)=>{const r=typeof t=="string"&&t.startsWith("/")?new Request(`http://container${t}`,e):new Request(t,e);return o!==void 0&&r.headers.set(j,String(o)),n!==void 0&&r.headers.set("traceparent",n),r},L=async t=>{t<=0||await new Promise(e=>{setTimeout(e,t)})},Y=/no container instance|not listening|try again later|rate.?limit|provision/i,z="no Container instance available",G="Failed to start container:",K=1024,V=async t=>(await U(t.clone().body,K)).text,O=t=>t instanceof Error&&Y.test(t.message),H=async t=>{if(t.status===429)return!0;if(t.status!==500&&t.status!==503)return!1;try{const e=await V(t);return e.includes(z)||e.startsWith(G)}catch{return!1}},w=t=>`ctx.containers.${t.exportName}`,S=(t,e,o={},n,r)=>{const s=Math.max(1,o.attempts??q),a=o.backoffMs??W,A=o.maxBackoffMs??D,g=async(i,f)=>{const T=typeof i=="string"?s:1;let l;for(let d=0;d<T;d+=1){const u=d===T-1;d>0&&await L(Math.min(a*2**(d-1),A));try{const m=await t(P(i,f,n,r));if(u||!await H(m))return m}catch(m){if(l=m,u||!O(m))throw m}}throw l instanceof Error?l:new Error("ctx.containers: cold-start retry exhausted")};return{exec:F(g,e),fetch:async(i,f)=>(C(i,e),g(i,f)),port:i=>S(t,e,o,i,r)}},x=(t,e,o,n,r)=>S(async s=>t.get(t.idFromName(e)).fetch(s),o,n,void 0,r),c=async(t,e,o,n)=>{const r=t[e];if(typeof r!="function")throw new TypeError(`ctx.containers: the "${o}" container DO does not expose ${e}() — is @lunora/container/do up to date?`);return r(n)},J=(t,e)=>({allow:async o=>c(t(),"allowHost",e,o),deny:async o=>c(t(),"denyHost",e,o),removeAllowed:async o=>c(t(),"removeAllowedHost",e,o),removeDenied:async o=>c(t(),"removeDeniedHost",e,o),setAllowed:async o=>c(t(),"setAllowedHosts",e,[...o]),setDenied:async o=>c(t(),"setDeniedHosts",e,[...o])}),b=(t,e,o,n,r)=>{const s=()=>t.get(t.idFromName(o));return{...S(async a=>s().fetch(a),w(e),n,void 0,r),destroy:async()=>c(s(),"destroy",e.binding),egress:J(s,e.binding),getState:async()=>c(s(),"getState",e.binding),renewActivityTimeout:async()=>c(s(),"renewActivityTimeout",e.binding),start:async a=>c(s(),"start",e.binding,a),stop:async a=>c(s(),"stop",e.binding,a)}},B=t=>`pool-${String(Math.floor(Math.random()*t))}`,Q=t=>t.status>=500,M=(t,e,o={},n,r)=>{const s=o.size??e.maxInstances??N,a=Math.max(1,o.attempts??3),A=o.backoffMs??100,g=o.maxBackoffMs??D,i=`${w(e)}.pool()`,f=(l,d)=>async(u,m)=>{const E=typeof u=="string"?a:1;let _;for(let h=0;h<E;h+=1){h>0&&await L(Math.min(A*2**(h-1),g));const $=P(u,m,n,r);try{const y=await t.get(t.idFromName(B(s))).fetch($);if(h===E-1||!await l(y))return y}catch(y){if(_=y,!d(y))throw y}}throw _ instanceof Error?_:new Error(`ctx.containers.${e.exportName}.pool(): all ${String(E)} attempts failed`)},T=f(o.retryOn??Q,()=>!0);return{exec:F(f(H,O),i),fetch:async(l,d)=>(C(l,i),T(l,d)),port:l=>M(t,e,o,l,r)}},X=(t,e,o)=>({any:(n,r)=>x(t,B(n??e.maxInstances??N),w(e),r,o),get:(n,r)=>b(t,e,n,r,o),pool:n=>M(t,e,n,void 0,o)}),Z=t=>{const e=()=>{throw new R("INTERNAL",`ctx.containers.${t.exportName}: no "${t.binding}" Durable Object binding found. Run \`lunora dev\` (or \`lunora deploy\`) to reconcile wrangler.jsonc, and make sure the worker entry re-exports the generated container classes.`)};return{any:e,get:e,pool:e}},st=(t,e,o,n)=>{const r={};for(const s of e){const a=t[s.binding];r[s.exportName]=a&&typeof a.idFromName=="function"&&typeof a.get=="function"?X(I(a,o),s,n):Z(s)}return r},tt=t=>{const e=o=>({allowHost:()=>Promise.resolve(),denyHost:()=>Promise.resolve(),destroy:()=>Promise.resolve(),fetch:n=>Promise.resolve(t(n,{name:o})),getState:()=>Promise.resolve({lastChange:0}),removeAllowedHost:()=>Promise.resolve(),removeDeniedHost:()=>Promise.resolve(),renewActivityTimeout:()=>Promise.resolve(),setAllowedHosts:()=>Promise.resolve(),setDeniedHosts:()=>Promise.resolve(),start:()=>Promise.resolve(),stop:()=>Promise.resolve()});return{get:o=>e(String(o)),idFromName:o=>o}},at=t=>{const e={};for(const[o,n]of Object.entries(t)){const r=tt(n),s={binding:k(o),exportName:o};e[o]={any:()=>x(r,"pool-0",w(s),{attempts:1}),get:a=>b(r,s,a,{attempts:1}),pool:()=>x(r,"pool-0",`${w(s)}.pool()`,{attempts:1})}}return e};export{st as createContainerContext,at as createContainerTestContext};
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";const w=async(o,r,t)=>{if(o===null)return{overflowed:!1,text:""};const e=o.getReader(),n=new TextDecoder,a=()=>{e.cancel().catch(()=>{})};t?.addEventListener("abort",a);let s="",c=0,u=!1;try{for(;t?.aborted!==!0;){const{done:f,value:i}=await e.read();if(f)break;if(c+i.byteLength>r){u=!0,s+=n.decode(i.subarray(0,r-c),{stream:!0});break}c+=i.byteLength,s+=n.decode(i,{stream:!0})}s+=n.decode()}finally{t?.removeEventListener("abort",a),e.cancel().catch(()=>{})}if(t?.aborted===!0)throw t.reason;return{overflowed:u,text:s}},l="/__lunora/exec",E=512,b=1e6,v="<redacted>",h=(o,r)=>{if(r===void 0)return o;let t=o;for(const e of Object.values(r))e.length>0&&(t=t.split(e).join(v));return t},x=o=>{if(o===null||typeof o!="object")return;const{code:r,stderr:t,stdout:e}=o;if(typeof r=="number")return{code:r,stderr:typeof t=="string"?t:"",stdout:typeof e=="string"?e:""}},m=(o,r)=>{if(r===void 0)return{dispose:()=>{},signal:o};const t=new AbortController,e=setTimeout(()=>{t.abort(new d("INTERNAL",`ctx.containers: exec timed out after ${String(r)}ms`))},r);return{dispose:()=>{clearTimeout(e)},signal:o===void 0?t.signal:AbortSignal.any([o,t.signal])}},T=(o,r)=>async(t,e={})=>{if(typeof t!="string"||t.length===0)throw new d("BAD_REQUEST",`${r}: exec requires a non-empty \`command\``);const n=e.maxOutputBytes??b;if(!Number.isSafeInteger(n)||n<=0)throw new d("BAD_REQUEST",`${r}: exec \`maxOutputBytes\` must be a positive whole number of bytes, got ${String(n)}`);const a=m(e.signal,e.timeoutMs);try{const s=await o(l,{body:JSON.stringify({args:e.args??[],command:t,...e.cwd===void 0?{}:{cwd:e.cwd},...e.env===void 0?{}:{env:e.env},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),headers:{"content-type":"application/json"},method:"POST",...a.signal===void 0?{}:{signal:a.signal}});if(!s.ok){const i=await w(s.body,E,a.signal).then(y=>h(y.text,e.env),()=>"<unreadable body>");throw new d("INTERNAL",`${r}: exec failed — the container answered ${String(s.status)} for POST ${l}. Does it serve that route? Body: ${i}`)}const c=await w(s.body,n,a.signal);if(c.overflowed)throw new d("INTERNAL",`${r}: exec response exceeded ${String(n)} bytes and was abandoned — it is buffered whole to be parsed, so an unbounded one would exhaust the isolate. Cap the command's output, or raise \`maxOutputBytes\`.`);let u;try{u=JSON.parse(c.text)}catch{throw new d("INTERNAL",`${r}: exec response was not JSON — expected {"code","stdout","stderr"} from POST ${l}`)}const f=x(u);if(f===void 0)throw new d("INTERNAL",`${r}: exec response is missing a numeric \`code\` — expected {"code","stdout","stderr"} from POST ${l}`);return f}finally{a.dispose()}};export{l as C,T as e,w as r};
@@ -0,0 +1 @@
1
+ const t=(o,r)=>{if(r===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/container: Durable Object namespace does not support jurisdiction("${r}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(r)};export{t as a};
@@ -7,14 +7,12 @@
7
7
  */
8
8
  /**
9
9
  * Named instance types Cloudflare Containers provides.
10
- * @experimental
11
10
  */
12
11
  type NamedContainerInstanceType = "basic" | "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4";
13
12
  /**
14
13
  * A custom instance type. Cloudflare's bounds at the time of writing: up to
15
14
  * 4 vCPU, 12 GiB memory, 20 GB disk, ≥ 3 GiB memory per vCPU and ≤ 2 GB disk
16
15
  * per GiB memory. The config-layer validator enforces the documented ranges.
17
- * @experimental
18
16
  */
19
17
  interface CustomContainerInstanceType {
20
18
  /** Disk in MB. Cloudflare's default is 2000 (2 GB). */
@@ -26,12 +24,10 @@ interface CustomContainerInstanceType {
26
24
  }
27
25
  /**
28
26
  * `ContainerInstanceType` is part of the experimental `@lunora/container` API and may change without a major version bump.
29
- * @experimental
30
27
  */
31
28
  type ContainerInstanceType = CustomContainerInstanceType | NamedContainerInstanceType;
32
29
  /**
33
30
  * Rolling-deploy tuning for a container.
34
- * @experimental
35
31
  */
36
32
  interface ContainerRollout {
37
33
  /** Seconds an active instance runs before it's eligible for update (wrangler `rollout_active_grace_period`). */
@@ -43,7 +39,6 @@ interface ContainerRollout {
43
39
  * A pre-built image pulled from a registry — the Cloudflare Registry, Docker
44
40
  * Hub, or Amazon ECR (the registries `wrangler deploy` supports). The
45
41
  * reference must be fully qualified, e.g. `docker.io/acme/transcoder:1.4`.
46
- * @experimental
47
42
  */
48
43
  interface RegistryImageSource {
49
44
  registry: string;
@@ -53,7 +48,6 @@ interface RegistryImageSource {
53
48
  * source directory and `lunora deploy` builds an OCI image with Railpack
54
49
  * (needs a BuildKit instance) and pushes it to the Cloudflare Registry before
55
50
  * wrangler runs. Opt-in — the Dockerfile path is the zero-extra-deps default.
56
- * @experimental
57
51
  */
58
52
  interface BuildImageSource {
59
53
  build: string;
@@ -63,7 +57,6 @@ interface BuildImageSource {
63
57
  * either a directory containing a `Dockerfile` (normalized to
64
58
  * `<dir>/Dockerfile` with the directory as the build context) or a path to
65
59
  * the Dockerfile itself — while `{ registry }` is a pre-built image reference.
66
- * @experimental
67
60
  */
68
61
  type ContainerImageSource = BuildImageSource | RegistryImageSource | string;
69
62
  /**
@@ -76,7 +69,6 @@ type ContainerImageSource = BuildImageSource | RegistryImageSource | string;
76
69
  * functions), so codegen and the config layer can read it without evaluating
77
70
  * code. (Upstream cloudflare/containers#188 expresses the same idea as handler
78
71
  * functions; the Lunora config is data-only, so it's modelled as descriptors.)
79
- * @experimental
80
72
  */
81
73
  interface ContainerReadinessCheck {
82
74
  /** HTTP path probed on the container, e.g. `"/ready"` (a leading slash is optional). */
@@ -88,7 +80,6 @@ interface ContainerReadinessCheck {
88
80
  }
89
81
  /**
90
82
  * `ContainerConfig` is part of the experimental `@lunora/container` API and may change without a major version bump.
91
- * @experimental
92
83
  */
93
84
  interface ContainerConfig {
94
85
  /**
@@ -246,7 +237,6 @@ interface ContainerConfig {
246
237
  /**
247
238
  * The value `defineContainer` returns: the validated config plus a brand the
248
239
  * codegen discovery and the generated Container DO class key on.
249
- * @experimental
250
240
  */
251
241
  interface ContainerDefinition extends ContainerConfig {
252
242
  /** Brand marking a value as a Lunora container definition. */
@@ -254,7 +244,6 @@ interface ContainerDefinition extends ContainerConfig {
254
244
  }
255
245
  /**
256
246
  * A normalized image source, as written into `wrangler.jsonc`.
257
- * @experimental
258
247
  */
259
248
  type NormalizedContainerImage = {
260
249
  /** Build context directory (wrangler `image_build_context`). */
@@ -275,7 +264,6 @@ type NormalizedContainerImage = {
275
264
  * Cloudflare Durable Object data-residency jurisdiction. Widening union —
276
265
  * Cloudflare adds values over time.
277
266
  * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
278
- * @experimental
279
267
  */
280
268
  type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
281
- export { BuildImageSource as B, ContainerConfig as C, DurableObjectJurisdiction as D, NormalizedContainerImage as N, RegistryImageSource as R, ContainerDefinition as a, ContainerImageSource as b, ContainerInstanceType as c, ContainerReadinessCheck as d, ContainerRollout as e, CustomContainerInstanceType as f, NamedContainerInstanceType as g };
269
+ export { BuildImageSource as B, ContainerDefinition as C, DurableObjectJurisdiction as D, NormalizedContainerImage as N, RegistryImageSource as R, ContainerConfig as a, ContainerImageSource as b, ContainerInstanceType as c, ContainerReadinessCheck as d, ContainerRollout as e, CustomContainerInstanceType as f, NamedContainerInstanceType as g };
@@ -7,14 +7,12 @@
7
7
  */
8
8
  /**
9
9
  * Named instance types Cloudflare Containers provides.
10
- * @experimental
11
10
  */
12
11
  type NamedContainerInstanceType = "basic" | "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4";
13
12
  /**
14
13
  * A custom instance type. Cloudflare's bounds at the time of writing: up to
15
14
  * 4 vCPU, 12 GiB memory, 20 GB disk, ≥ 3 GiB memory per vCPU and ≤ 2 GB disk
16
15
  * per GiB memory. The config-layer validator enforces the documented ranges.
17
- * @experimental
18
16
  */
19
17
  interface CustomContainerInstanceType {
20
18
  /** Disk in MB. Cloudflare's default is 2000 (2 GB). */
@@ -26,12 +24,10 @@ interface CustomContainerInstanceType {
26
24
  }
27
25
  /**
28
26
  * `ContainerInstanceType` is part of the experimental `@lunora/container` API and may change without a major version bump.
29
- * @experimental
30
27
  */
31
28
  type ContainerInstanceType = CustomContainerInstanceType | NamedContainerInstanceType;
32
29
  /**
33
30
  * Rolling-deploy tuning for a container.
34
- * @experimental
35
31
  */
36
32
  interface ContainerRollout {
37
33
  /** Seconds an active instance runs before it's eligible for update (wrangler `rollout_active_grace_period`). */
@@ -43,7 +39,6 @@ interface ContainerRollout {
43
39
  * A pre-built image pulled from a registry — the Cloudflare Registry, Docker
44
40
  * Hub, or Amazon ECR (the registries `wrangler deploy` supports). The
45
41
  * reference must be fully qualified, e.g. `docker.io/acme/transcoder:1.4`.
46
- * @experimental
47
42
  */
48
43
  interface RegistryImageSource {
49
44
  registry: string;
@@ -53,7 +48,6 @@ interface RegistryImageSource {
53
48
  * source directory and `lunora deploy` builds an OCI image with Railpack
54
49
  * (needs a BuildKit instance) and pushes it to the Cloudflare Registry before
55
50
  * wrangler runs. Opt-in — the Dockerfile path is the zero-extra-deps default.
56
- * @experimental
57
51
  */
58
52
  interface BuildImageSource {
59
53
  build: string;
@@ -63,7 +57,6 @@ interface BuildImageSource {
63
57
  * either a directory containing a `Dockerfile` (normalized to
64
58
  * `<dir>/Dockerfile` with the directory as the build context) or a path to
65
59
  * the Dockerfile itself — while `{ registry }` is a pre-built image reference.
66
- * @experimental
67
60
  */
68
61
  type ContainerImageSource = BuildImageSource | RegistryImageSource | string;
69
62
  /**
@@ -76,7 +69,6 @@ type ContainerImageSource = BuildImageSource | RegistryImageSource | string;
76
69
  * functions), so codegen and the config layer can read it without evaluating
77
70
  * code. (Upstream cloudflare/containers#188 expresses the same idea as handler
78
71
  * functions; the Lunora config is data-only, so it's modelled as descriptors.)
79
- * @experimental
80
72
  */
81
73
  interface ContainerReadinessCheck {
82
74
  /** HTTP path probed on the container, e.g. `"/ready"` (a leading slash is optional). */
@@ -88,7 +80,6 @@ interface ContainerReadinessCheck {
88
80
  }
89
81
  /**
90
82
  * `ContainerConfig` is part of the experimental `@lunora/container` API and may change without a major version bump.
91
- * @experimental
92
83
  */
93
84
  interface ContainerConfig {
94
85
  /**
@@ -246,7 +237,6 @@ interface ContainerConfig {
246
237
  /**
247
238
  * The value `defineContainer` returns: the validated config plus a brand the
248
239
  * codegen discovery and the generated Container DO class key on.
249
- * @experimental
250
240
  */
251
241
  interface ContainerDefinition extends ContainerConfig {
252
242
  /** Brand marking a value as a Lunora container definition. */
@@ -254,7 +244,6 @@ interface ContainerDefinition extends ContainerConfig {
254
244
  }
255
245
  /**
256
246
  * A normalized image source, as written into `wrangler.jsonc`.
257
- * @experimental
258
247
  */
259
248
  type NormalizedContainerImage = {
260
249
  /** Build context directory (wrangler `image_build_context`). */
@@ -275,7 +264,6 @@ type NormalizedContainerImage = {
275
264
  * Cloudflare Durable Object data-residency jurisdiction. Widening union —
276
265
  * Cloudflare adds values over time.
277
266
  * @see https://developers.cloudflare.com/durable-objects/reference/data-location/
278
- * @experimental
279
267
  */
280
268
  type DurableObjectJurisdiction = "eu" | "fedramp" | "us";
281
- export { BuildImageSource as B, ContainerConfig as C, DurableObjectJurisdiction as D, NormalizedContainerImage as N, RegistryImageSource as R, ContainerDefinition as a, ContainerImageSource as b, ContainerInstanceType as c, ContainerReadinessCheck as d, ContainerRollout as e, CustomContainerInstanceType as f, NamedContainerInstanceType as g };
269
+ export { BuildImageSource as B, ContainerDefinition as C, DurableObjectJurisdiction as D, NormalizedContainerImage as N, RegistryImageSource as R, ContainerConfig as a, ContainerImageSource as b, ContainerInstanceType as c, ContainerReadinessCheck as d, ContainerRollout as e, CustomContainerInstanceType as f, NamedContainerInstanceType as g };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/container",
3
- "version": "1.0.0-alpha.30",
3
+ "version": "1.0.0-alpha.32",
4
4
  "description": "Cloudflare Containers for Lunora: defineContainer, generated Container DO classes, and the ctx.containers action surface",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -56,7 +56,7 @@
56
56
  "access": "public"
57
57
  },
58
58
  "dependencies": {
59
- "@lunora/errors": "1.0.0-alpha.21"
59
+ "@lunora/errors": "1.0.0-alpha.22"
60
60
  },
61
61
  "engines": {
62
62
  "node": "^22.15.0 || >=24.11.0"
@@ -1 +0,0 @@
1
- import{LunoraError as D}from"@lunora/errors";import{containerBindingName as E}from"./containerBindingName-CP4v-2Cw.mjs";import{e as $}from"./jurisdiction-BKRNOTip.mjs";const v=3,x=3e4,k=3,S=500,T="cf-container-target-port",b=(t,e,o,n)=>{const r=typeof t=="string"&&t.startsWith("/")?new Request(`http://container${t}`,e):new Request(t,e);return o!==void 0&&r.headers.set(T,String(o)),n!==void 0&&r.headers.set("traceparent",n),r},P=async t=>{t<=0||await new Promise(e=>{setTimeout(e,t)})},C=/no container instance|not listening|try again later|rate.?limit|provision/i,F="no Container instance available",R="Failed to start container:",j=1024,B=async t=>{const e=t.clone().body;if(e===null)return"";const o=e.getReader(),n=new TextDecoder;let r="";try{for(;r.length<j;){const{done:s,value:a}=await o.read();if(s)break;r+=n.decode(a,{stream:!0})}}finally{await o.cancel()}return r},I=t=>t instanceof Error&&C.test(t.message),O=async t=>{if(t.status===429)return!0;if(t.status!==500&&t.status!==503)return!1;try{const e=await B(t);return e.includes(F)||e.startsWith(R)}catch{return!1}},h=(t,e={},o,n)=>{const r=Math.max(1,e.attempts??k),s=e.backoffMs??S,a=e.maxBackoffMs??x;return{fetch:async(d,g)=>{const u=typeof d=="string"?r:1;let l;for(let m=0;m<u;m+=1){const f=m===u-1;m>0&&await P(Math.min(s*2**(m-1),a));try{const c=await t(b(d,g,o,n));if(f||!await O(c))return c}catch(c){if(l=c,f||!I(c))throw c}}throw l instanceof Error?l:new Error("ctx.containers: cold-start retry exhausted")},port:d=>h(t,e,d,n)}},w=(t,e,o,n)=>h(async r=>t.get(t.idFromName(e)).fetch(r),o,void 0,n),i=async(t,e,o,n)=>{const r=t[e];if(typeof r!="function")throw new TypeError(`ctx.containers: the "${o}" container DO does not expose ${e}() — is @lunora/container/do up to date?`);return r(n)},q=(t,e)=>({allow:async o=>i(t(),"allowHost",e,o),deny:async o=>i(t(),"denyHost",e,o),removeAllowed:async o=>i(t(),"removeAllowedHost",e,o),removeDenied:async o=>i(t(),"removeDeniedHost",e,o),setAllowed:async o=>i(t(),"setAllowedHosts",e,[...o]),setDenied:async o=>i(t(),"setDeniedHosts",e,[...o])}),H=(t,e,o,n,r)=>{const s=()=>t.get(t.idFromName(o));return{...h(async a=>s().fetch(a),n,void 0,r),destroy:async()=>i(s(),"destroy",e.binding),egress:q(s,e.binding),getState:async()=>i(s(),"getState",e.binding),renewActivityTimeout:async()=>i(s(),"renewActivityTimeout",e.binding),start:async a=>i(s(),"start",e.binding,a),stop:async a=>i(s(),"stop",e.binding,a)}},N=t=>`pool-${String(Math.floor(Math.random()*t))}`,L=t=>t.status>=500,A=(t,e,o={},n,r)=>{const s=o.size??e.maxInstances??v,a=Math.max(1,o.attempts??3),d=o.backoffMs??100,g=o.maxBackoffMs??x,u=o.retryOn??L;return{fetch:async(l,m)=>{const f=typeof l=="string"?a:1;let c;for(let y=0;y<f;y+=1){y>0&&await P(Math.min(d*2**(y-1),g));const M=b(l,m,n,r);try{const p=await t.get(t.idFromName(N(s))).fetch(M);if(y===f-1||!u(p))return p}catch(p){c=p}}throw c instanceof Error?c:new Error(`ctx.containers.${e.exportName}.pool(): all ${String(f)} attempts failed`)},port:l=>A(t,e,o,l,r)}},z=(t,e,o)=>({any:(n,r)=>w(t,N(n??e.maxInstances??v),r,o),get:(n,r)=>H(t,e,n,r,o),pool:n=>A(t,e,n,void 0,o)}),W=t=>{const e=()=>{throw new D("INTERNAL",`ctx.containers.${t.exportName}: no "${t.binding}" Durable Object binding found. Run \`lunora dev\` (or \`lunora deploy\`) to reconcile wrangler.jsonc, and make sure the worker entry re-exports the generated container classes.`)};return{any:e,get:e,pool:e}},G=(t,e,o,n)=>{const r={};for(const s of e){const a=t[s.binding];r[s.exportName]=a&&typeof a.idFromName=="function"&&typeof a.get=="function"?z($(a,o),s,n):W(s)}return r},J=t=>{const e=o=>({allowHost:()=>Promise.resolve(),denyHost:()=>Promise.resolve(),destroy:()=>Promise.resolve(),fetch:n=>Promise.resolve(t(n,{name:o})),getState:()=>Promise.resolve({lastChange:0}),removeAllowedHost:()=>Promise.resolve(),removeDeniedHost:()=>Promise.resolve(),renewActivityTimeout:()=>Promise.resolve(),setAllowedHosts:()=>Promise.resolve(),setDeniedHosts:()=>Promise.resolve(),start:()=>Promise.resolve(),stop:()=>Promise.resolve()});return{get:o=>e(String(o)),idFromName:o=>o}},K=t=>{const e={};for(const[o,n]of Object.entries(t)){const r=J(n),s={binding:E(o)};e[o]={any:()=>w(r,"pool-0",{attempts:1}),get:a=>H(r,s,a,{attempts:1}),pool:()=>w(r,"pool-0",{attempts:1})}}return e};export{G as createContainerContext,K as createContainerTestContext};
@@ -1 +0,0 @@
1
- const r=(o,e)=>{if(e===void 0)return o;if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/container: Durable Object namespace does not support jurisdiction("${e}") — update @cloudflare/workers-types or remove the jurisdiction option`);return o.jurisdiction(e)};export{r as e};