alchemy 0.76.0 → 0.77.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/bin/alchemy.js +111 -30
  2. package/bin/services/execute-alchemy.ts +10 -1
  3. package/lib/aws/ec2/index.d.ts +1 -0
  4. package/lib/aws/ec2/index.d.ts.map +1 -1
  5. package/lib/aws/ec2/index.js +1 -0
  6. package/lib/aws/ec2/index.js.map +1 -1
  7. package/lib/aws/index.d.ts +1 -7
  8. package/lib/aws/index.d.ts.map +1 -1
  9. package/lib/aws/index.js +1 -8
  10. package/lib/aws/index.js.map +1 -1
  11. package/lib/cloudflare/auth.d.ts.map +1 -1
  12. package/lib/cloudflare/auth.js +1 -0
  13. package/lib/cloudflare/auth.js.map +1 -1
  14. package/lib/cloudflare/bucket-custom-domain.d.ts +90 -0
  15. package/lib/cloudflare/bucket-custom-domain.d.ts.map +1 -0
  16. package/lib/cloudflare/bucket-custom-domain.js +81 -0
  17. package/lib/cloudflare/bucket-custom-domain.js.map +1 -0
  18. package/lib/cloudflare/bucket.d.ts +28 -4
  19. package/lib/cloudflare/bucket.d.ts.map +1 -1
  20. package/lib/cloudflare/bucket.js +41 -14
  21. package/lib/cloudflare/bucket.js.map +1 -1
  22. package/lib/cloudflare/cloudflare-env-proxy.d.ts.map +1 -1
  23. package/lib/cloudflare/cloudflare-env-proxy.js +0 -3
  24. package/lib/cloudflare/cloudflare-env-proxy.js.map +1 -1
  25. package/lib/cloudflare/compatibility-date.gen.d.ts +1 -1
  26. package/lib/cloudflare/compatibility-date.gen.js +1 -1
  27. package/lib/cloudflare/index.d.ts +1 -0
  28. package/lib/cloudflare/index.d.ts.map +1 -1
  29. package/lib/cloudflare/index.js +1 -0
  30. package/lib/cloudflare/index.js.map +1 -1
  31. package/lib/cloudflare/miniflare/build-worker-options.d.ts.map +1 -1
  32. package/lib/cloudflare/miniflare/build-worker-options.js +3 -1
  33. package/lib/cloudflare/miniflare/build-worker-options.js.map +1 -1
  34. package/lib/cloudflare/miniflare/remote-binding-proxy.d.ts.map +1 -1
  35. package/lib/cloudflare/miniflare/remote-binding-proxy.js +73 -9
  36. package/lib/cloudflare/miniflare/remote-binding-proxy.js.map +1 -1
  37. package/lib/cloudflare/react-router/plugin.d.ts +2 -1
  38. package/lib/cloudflare/react-router/plugin.d.ts.map +1 -1
  39. package/lib/cloudflare/react-router/plugin.js +6 -14
  40. package/lib/cloudflare/react-router/plugin.js.map +1 -1
  41. package/lib/cloudflare/vite/plugin.d.ts.map +1 -1
  42. package/lib/cloudflare/vite/plugin.js +0 -3
  43. package/lib/cloudflare/vite/plugin.js.map +1 -1
  44. package/lib/cloudflare/worker-bundle.d.ts.map +1 -1
  45. package/lib/cloudflare/worker-bundle.js +17 -0
  46. package/lib/cloudflare/worker-bundle.js.map +1 -1
  47. package/lib/cloudflare/worker-metadata.d.ts.map +1 -1
  48. package/lib/cloudflare/worker-metadata.js +6 -4
  49. package/lib/cloudflare/worker-metadata.js.map +1 -1
  50. package/lib/cloudflare/worker-subdomain.d.ts.map +1 -1
  51. package/lib/cloudflare/worker-subdomain.js +0 -1
  52. package/lib/cloudflare/worker-subdomain.js.map +1 -1
  53. package/lib/cloudflare/worker.d.ts.map +1 -1
  54. package/lib/cloudflare/worker.js +28 -38
  55. package/lib/cloudflare/worker.js.map +1 -1
  56. package/lib/cloudflare/wrangler.json.d.ts +2 -281
  57. package/lib/cloudflare/wrangler.json.d.ts.map +1 -1
  58. package/lib/cloudflare/wrangler.json.js +23 -11
  59. package/lib/cloudflare/wrangler.json.js.map +1 -1
  60. package/lib/encrypt.d.ts +28 -3
  61. package/lib/encrypt.d.ts.map +1 -1
  62. package/lib/encrypt.js +77 -3
  63. package/lib/encrypt.js.map +1 -1
  64. package/lib/planetscale/role.d.ts +9 -0
  65. package/lib/planetscale/role.d.ts.map +1 -1
  66. package/lib/planetscale/role.js +18 -3
  67. package/lib/planetscale/role.js.map +1 -1
  68. package/lib/prisma-postgres/api.d.ts.map +1 -1
  69. package/lib/prisma-postgres/api.js +1 -0
  70. package/lib/prisma-postgres/api.js.map +1 -1
  71. package/lib/scope.d.ts +5 -0
  72. package/lib/scope.d.ts.map +1 -1
  73. package/lib/scope.js +23 -0
  74. package/lib/scope.js.map +1 -1
  75. package/lib/serde.js +1 -1
  76. package/lib/serde.js.map +1 -1
  77. package/lib/util/telemetry.js +4 -0
  78. package/lib/util/telemetry.js.map +1 -1
  79. package/package.json +12 -10
  80. package/src/aws/ec2/index.ts +1 -0
  81. package/src/aws/index.ts +1 -9
  82. package/src/cloudflare/auth.ts +1 -0
  83. package/src/cloudflare/bucket-custom-domain.ts +281 -0
  84. package/src/cloudflare/bucket.ts +85 -18
  85. package/src/cloudflare/cloudflare-env-proxy.ts +0 -3
  86. package/src/cloudflare/compatibility-date.gen.ts +1 -1
  87. package/src/cloudflare/index.ts +1 -0
  88. package/src/cloudflare/miniflare/build-worker-options.ts +3 -1
  89. package/src/cloudflare/miniflare/remote-binding-proxy.ts +80 -9
  90. package/src/cloudflare/react-router/plugin.ts +9 -21
  91. package/src/cloudflare/vite/plugin.ts +0 -3
  92. package/src/cloudflare/worker-bundle.ts +28 -1
  93. package/src/cloudflare/worker-metadata.ts +8 -4
  94. package/src/cloudflare/worker-subdomain.ts +0 -1
  95. package/src/cloudflare/worker.ts +32 -45
  96. package/src/cloudflare/wrangler.json.ts +62 -397
  97. package/src/encrypt.ts +115 -3
  98. package/src/planetscale/role.ts +30 -3
  99. package/src/prisma-postgres/api.ts +1 -0
  100. package/src/scope.ts +27 -0
  101. package/src/serde.ts +1 -1
  102. package/src/util/telemetry.ts +5 -0
  103. package/workers/cloudflare-state-store.js +4802 -8
  104. package/workers/dofs-state-store.js +632 -2
  105. package/workers/remote-binding-proxy.js +1929 -3
  106. package/workers/tunnel-proxy.js +58 -6
  107. package/workers/tunnel-proxy.ts +1 -1
@@ -1,3 +1,1929 @@
1
- Symbol.dispose||(Symbol.dispose=Symbol.for("dispose"));Symbol.asyncDispose||(Symbol.asyncDispose=Symbol.for("asyncDispose"));var W=navigator.userAgent==="Cloudflare-Workers"?"cloudflare:workers":null,b;W&&(b=await import(W));var D=b?b.RpcTarget:class{};function j(t){switch(typeof t){case"boolean":case"number":case"string":return"primitive";case"undefined":return"undefined";case"object":case"function":break;case"bigint":return"bigint";default:return"unsupported"}if(t===null)return"primitive";let e=Object.getPrototypeOf(t);switch(e){case Object.prototype:return"object";case Function.prototype:return"function";case Array.prototype:return"array";case Date.prototype:return"date";case Uint8Array.prototype:return"bytes";case w.prototype:return"stub";case c.prototype:return"rpc-promise";default:if(b){if(e==b.RpcStub.prototype||t instanceof b.ServiceStub)return"rpc-target";if(e==b.RpcPromise.prototype||e==b.RpcProperty.prototype)return"rpc-thenable"}return t instanceof D?"rpc-target":t instanceof Error?"error":"unsupported"}}function z(){throw new Error("RPC map() implementation was not loaded.")}var M={applyMap:z,sendMap:z},x=class{},y=class extends x{constructor(t){super(),this.error=t}call(t,e){return this}map(t,e,r){return this}get(t){return this}dup(){return this}pull(){return Promise.reject(this.error)}ignoreUnhandledRejections(){}dispose(){}onBroken(t){try{t(this.error)}catch(e){Promise.resolve(e)}}},_=new y(new Error("Attempted to use RPC stub after it has been disposed.")),O=(t,e,r)=>t.call(e,r);function ee(t,e){let r=O;O=t;try{return e()}finally{O=r}}var f=Symbol("realStub"),te={apply(t,e,r){let s=t.raw;return new c(O(s.hook,s.pathIfPromise||[],m.fromAppParams(r)),[])},get(t,e,r){let s=t.raw;return e===f?s:e in c.prototype?s[e]:typeof e=="string"?new c(s.hook,s.pathIfPromise?[...s.pathIfPromise,e]:[e]):e===Symbol.dispose&&(!s.pathIfPromise||s.pathIfPromise.length==0)?()=>{s.hook.dispose(),s.hook=_}:void 0},has(t,e){let r=t.raw;return e===f?!0:e in c.prototype?e in r:typeof e=="string"?!0:e===Symbol.dispose&&(!r.pathIfPromise||r.pathIfPromise.length==0)},construct(t,e){throw new Error("An RPC stub cannot be used as a constructor.")},defineProperty(t,e,r){throw new Error("Can't define properties on RPC stubs.")},deleteProperty(t,e){throw new Error("Can't delete properties on RPC stubs.")},getOwnPropertyDescriptor(t,e){},getPrototypeOf(t){return Object.getPrototypeOf(t.raw)},isExtensible(t){return!1},ownKeys(t){return[]},preventExtensions(t){return!0},set(t,e,r,s){throw new Error("Can't assign properties on RPC stubs.")},setPrototypeOf(t,e){throw new Error("Can't override prototype of RPC stubs.")}},w=class L extends D{constructor(e,r){if(super(),!(e instanceof x)){let i=e;if(i instanceof D||i instanceof Function?e=I.create(i,void 0):e=new g(m.fromAppReturn(i)),r)throw new TypeError("RpcStub constructor expected one argument, received two.")}this.hook=e,this.pathIfPromise=r;let s=()=>{};return s.raw=this,new Proxy(s,te)}hook;pathIfPromise;dup(){let e=this[f];return e.pathIfPromise?new L(e.hook.get(e.pathIfPromise)):new L(e.hook.dup())}onRpcBroken(e){this[f].hook.onBroken(e)}map(e){let{hook:r,pathIfPromise:s}=this[f];return M.sendMap(r,s||[],e)}},c=class extends w{constructor(t,e){super(t,e)}then(t,e){return N(this).then(...arguments)}catch(t){return N(this).catch(...arguments)}finally(t){return N(this).finally(...arguments)}};function re(t){let{hook:e,pathIfPromise:r}=t[f];return r&&r.length>0?e.get(r):e}function se(t){let{hook:e,pathIfPromise:r}=t[f];return r?e.get(r):e.dup()}function $(t){let{hook:e,pathIfPromise:r}=t[f];if(!(r&&r.length>0))return e}function H(t){return t[f].hook}function A(t){return t[f]}async function N(t){let{hook:e,pathIfPromise:r}=t[f];return r.length>0&&(e=e.get(r)),(await e.pull()).deliverResolve()}var m=class d{constructor(e,r,s,i){this.value=e,this.source=r,this.stubs=s,this.promises=i}static fromAppParams(e){return new d(e,"params")}static fromAppReturn(e){return new d(e,"return")}static fromArray(e){let r=[],s=[],i=[];for(let o of e){o.ensureDeepCopied();for(let n of o.stubs)r.push(n);for(let n of o.promises)n.parent===o&&(n={parent:i,property:i.length,promise:n.promise}),s.push(n);i.push(o.value)}return new d(i,"owned",r,s)}static forEvaluate(e,r){return new d(null,"owned",e,r)}static deepCopyFrom(e,r,s){let i=new d(null,"owned",[],[]);return i.value=i.deepCopy(e,r,"value",i,!0,s),i}rpcTargets;getHookForRpcTarget(e,r,s=!0){if(this.source==="params")return I.create(e,r);if(this.source==="return"){let i=this.rpcTargets?.get(e);return i?s?i.dup():(this.rpcTargets?.delete(e),i):(i=I.create(e,r),s?(this.rpcTargets||(this.rpcTargets=new Map),this.rpcTargets.set(e,i),i.dup()):i)}else throw new Error("owned payload shouldn't contain raw RpcTargets")}deepCopy(e,r,s,i,o,n){switch(j(e)){case"unsupported":return e;case"primitive":case"bigint":case"date":case"bytes":case"error":case"undefined":return e;case"array":{let a=e,p=a.length,h=new Array(p);for(let u=0;u<p;u++)h[u]=this.deepCopy(a[u],a,u,h,o,n);return h}case"object":{let a={},p=e;for(let h in p)a[h]=this.deepCopy(p[h],p,h,a,o,n);return a}case"stub":case"rpc-promise":{let a=e,p;if(o?p=se(a):p=re(a),a instanceof c){let h=new c(p,[]);return this.promises.push({parent:i,property:s,promise:h}),h}else{let h=new w(p);return this.stubs.push(h),h}}case"function":case"rpc-target":{let a=e,p;return n?p=new w(n.getHookForRpcTarget(a,r,o)):p=new w(I.create(a,r)),this.stubs.push(p),p}case"rpc-thenable":{let a=e,p;return n?p=new c(n.getHookForRpcTarget(a,r,o),[]):p=new c(I.create(a,r),[]),this.promises.push({parent:i,property:s,promise:p}),p}default:throw new Error("unreachable")}}ensureDeepCopied(){if(this.source!=="owned"){let e=this.source==="params";this.stubs=[],this.promises=[];try{this.value=this.deepCopy(this.value,void 0,"value",this,e,this)}catch(r){throw this.stubs=void 0,this.promises=void 0,r}if(this.source="owned",this.rpcTargets&&this.rpcTargets.size>0)throw new Error("Not all rpcTargets were accounted for in deep-copy?");this.rpcTargets=void 0}}deliverTo(e,r,s){if(this.ensureDeepCopied(),this.value instanceof c)d.deliverRpcPromiseTo(this.value,e,r,s);else{e[r]=this.value;for(let i of this.promises)d.deliverRpcPromiseTo(i.promise,i.parent,i.property,s)}}static deliverRpcPromiseTo(e,r,s,i){let o=$(e);if(!o)throw new Error("property promises should have been resolved earlier");let n=o.pull();n instanceof d?n.deliverTo(r,s,i):i.push(n.then(l=>{let a=[];if(l.deliverTo(r,s,a),a.length>0)return Promise.all(a)}))}async deliverCall(e,r){try{let s=[];this.deliverTo(this,"value",s),s.length>0&&await Promise.all(s);let i=Function.prototype.apply.call(e,r,this.value);return i instanceof c?d.fromAppReturn(i):d.fromAppReturn(await i)}finally{this.dispose()}}async deliverResolve(){try{let e=[];this.deliverTo(this,"value",e),e.length>0&&await Promise.all(e);let r=this.value;return r instanceof Object&&(Symbol.dispose in r||Object.defineProperty(r,Symbol.dispose,{value:()=>this.dispose(),writable:!0,enumerable:!1,configurable:!0})),r}catch(e){throw this.dispose(),e}}dispose(){if(this.source==="owned")this.stubs.forEach(e=>e[Symbol.dispose]()),this.promises.forEach(e=>e.promise[Symbol.dispose]());else if(this.source==="return"&&(this.disposeImpl(this.value,void 0),this.rpcTargets&&this.rpcTargets.size>0))throw new Error("Not all rpcTargets were accounted for in disposeImpl()?");this.source="owned",this.stubs=[],this.promises=[]}disposeImpl(e,r){switch(j(e)){case"unsupported":case"primitive":case"bigint":case"bytes":case"date":case"error":case"undefined":return;case"array":{let i=e,o=i.length;for(let n=0;n<o;n++)this.disposeImpl(i[n],i);return}case"object":{let i=e;for(let o in i)this.disposeImpl(i[o],i);return}case"stub":case"rpc-promise":{let o=$(e);o&&o.dispose();return}case"function":case"rpc-target":{let i=e,o=this.rpcTargets?.get(i);o?(o.dispose(),this.rpcTargets.delete(i)):Q(i);return}case"rpc-thenable":return;default:return}}ignoreUnhandledRejections(){this.stubs?(this.stubs.forEach(e=>{H(e).ignoreUnhandledRejections()}),this.promises.forEach(e=>H(e.promise).ignoreUnhandledRejections())):this.ignoreUnhandledRejectionsImpl(this.value)}ignoreUnhandledRejectionsImpl(e){switch(j(e)){case"unsupported":case"primitive":case"bigint":case"bytes":case"date":case"error":case"undefined":case"function":case"rpc-target":return;case"array":{let s=e,i=s.length;for(let o=0;o<i;o++)this.ignoreUnhandledRejectionsImpl(s[o]);return}case"object":{let s=e;for(let i in s)this.ignoreUnhandledRejectionsImpl(s[i]);return}case"stub":case"rpc-promise":H(e).ignoreUnhandledRejections();return;case"rpc-thenable":e.then(s=>{},s=>{});return;default:return}}};function U(t,e,r,s){for(let i=0;i<r.length;i++){e=t;let o=r[i];if(o in Object.prototype){t=void 0;continue}switch(j(t)){case"object":case"function":Object.hasOwn(t,o)?t=t[o]:t=void 0;break;case"array":Number.isInteger(o)&&o>=0?t=t[o]:t=void 0;break;case"rpc-target":case"rpc-thenable":{Object.hasOwn(t,o)?t=void 0:t=t[o],s=null;break}case"stub":case"rpc-promise":{let{hook:l,pathIfPromise:a}=A(t);return{hook:l,remainingPath:a?a.concat(r.slice(i)):r.slice(i)}}case"primitive":case"bigint":case"bytes":case"date":case"error":t=void 0;break;case"undefined":t=t[o];break;case"unsupported":{if(i===0)throw new TypeError("RPC stub points at a non-serializable type.");{let l=r.slice(0,i).join("."),a=r.slice(0,i).join(".");throw new TypeError(`'${l}' is not a serializable type, so property ${a} cannot be accessed.`)}}default:throw new TypeError("unreachable")}}if(t instanceof c){let{hook:i,pathIfPromise:o}=A(t);return{hook:i,remainingPath:o||[]}}return{value:t,parent:e,owner:s}}var V=class extends x{call(t,e){try{let{value:r,owner:s}=this.getValue(),i=U(r,void 0,t,s);if(i.hook)return i.hook.call(i.remainingPath,e);if(typeof i.value!="function")throw new TypeError(`'${t.join(".")}' is not a function.`);let o=e.deliverCall(i.value,i.parent);return new ie(o.then(n=>new g(n)))}catch(r){return new y(r)}}map(t,e,r){try{let s;try{let{value:i,owner:o}=this.getValue();s=U(i,void 0,t,o)}catch(i){for(let o of e)o.dispose();throw i}return s.hook?s.hook.map(s.remainingPath,e,r):M.applyMap(s.value,s.parent,s.owner,e,r)}catch(s){return new y(s)}}get(t){try{let{value:e,owner:r}=this.getValue();if(t.length===0&&r===null)throw new Error("Can't dup an RpcTarget stub as a promise.");let s=U(e,void 0,t,r);return s.hook?s.hook.get(s.remainingPath):new g(m.deepCopyFrom(s.value,s.parent,s.owner))}catch(e){return new y(e)}}},g=class G extends V{constructor(e){super(),this.payload=e}payload;getPayload(){if(this.payload)return this.payload;throw new Error("Attempted to use an RPC StubHook after it was disposed.")}getValue(){let e=this.getPayload();return{value:e.value,owner:e}}dup(){let e=this.getPayload();return new G(m.deepCopyFrom(e.value,void 0,e))}pull(){return this.getPayload()}ignoreUnhandledRejections(){this.payload&&this.payload.ignoreUnhandledRejections()}dispose(){this.payload&&(this.payload.dispose(),this.payload=void 0)}onBroken(e){this.payload&&this.payload.value instanceof w&&this.payload.value.onRpcBroken(e)}};function Q(t){if(Symbol.dispose in t)try{t[Symbol.dispose]()}catch(e){Promise.reject(e)}}var I=class F extends V{static create(e,r){return typeof e!="function"&&(r=void 0),new F(e,r)}constructor(e,r,s){super(),this.target=e,this.parent=r,s?s.refcount&&(this.refcount=s.refcount,++this.refcount.count):Symbol.dispose in e&&(this.refcount={count:1})}target;parent;refcount;getTarget(){if(this.target)return this.target;throw new Error("Attempted to use an RPC StubHook after it was disposed.")}getValue(){return{value:this.getTarget(),owner:null}}dup(){return new F(this.getTarget(),this.parent,this)}pull(){let e=this.getTarget();return"then"in e?Promise.resolve(e).then(r=>m.fromAppReturn(r)):Promise.reject(new Error("Tried to resolve a non-promise stub."))}ignoreUnhandledRejections(){}dispose(){this.target&&(this.refcount&&--this.refcount.count==0&&Q(this.target),this.target=void 0)}onBroken(e){}},ie=class B extends x{promise;resolution;constructor(e){super(),this.promise=e.then(r=>(this.resolution=r,r))}call(e,r){return r.ensureDeepCopied(),new B(this.promise.then(s=>s.call(e,r)))}map(e,r,s){return new B(this.promise.then(i=>i.map(e,r,s),i=>{for(let o of r)o.dispose();throw i}))}get(e){return new B(this.promise.then(r=>r.get(e)))}dup(){return this.resolution?this.resolution.dup():new B(this.promise.then(e=>e.dup()))}pull(){return this.resolution?this.resolution.pull():this.promise.then(e=>e.pull())}ignoreUnhandledRejections(){this.resolution?this.resolution.ignoreUnhandledRejections():this.promise.then(e=>{e.ignoreUnhandledRejections()},e=>{})}dispose(){this.resolution?this.resolution.dispose():this.promise.then(e=>{e.dispose()},e=>{})}onBroken(e){this.resolution?this.resolution.onBroken(e):this.promise.then(r=>{r.onBroken(e)},e)}},oe=class{exportStub(t){throw new Error("Cannot serialize RPC stubs without an RPC session.")}exportPromise(t){throw new Error("Cannot serialize RPC stubs without an RPC session.")}getImport(t){}unexport(t){}onSendError(t){}},ne=new oe,ae={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,AggregateError},R=class K{constructor(e,r){this.exporter=e,this.source=r}static devaluate(e,r,s=ne,i){let o=new K(s,i);try{return o.devaluateImpl(e,r,0)}catch(n){if(o.exports)try{s.unexport(o.exports)}catch{}throw n}}exports;devaluateImpl(e,r,s){if(s>=64)throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");switch(j(e)){case"unsupported":{let o;try{o=`Cannot serialize value: ${e}`}catch{o="Cannot serialize value: (couldn't stringify value)"}throw new TypeError(o)}case"primitive":return e;case"object":{let o=e,n={};for(let l in o)n[l]=this.devaluateImpl(o[l],o,s+1);return n}case"array":{let o=e,n=o.length,l=new Array(n);for(let a=0;a<n;a++)l[a]=this.devaluateImpl(o[a],o,s+1);return[l]}case"bigint":return["bigint",e.toString()];case"date":return["date",e.getTime()];case"bytes":{let o=e;return o.toBase64?["bytes",o.toBase64({omitPadding:!0})]:["bytes",btoa(String.fromCharCode.apply(null,o).replace(/=*$/,""))]}case"error":{let o=e,n=this.exporter.onSendError(o);n&&(o=n);let l=["error",o.name,o.message];return n&&n.stack&&l.push(n.stack),l}case"undefined":return["undefined"];case"stub":case"rpc-promise":{if(!this.source)throw new Error("Can't serialize RPC stubs in this context.");let{hook:o,pathIfPromise:n}=A(e),l=this.exporter.getImport(o);return l!==void 0?n?n.length>0?["pipeline",l,n]:["pipeline",l]:["import",l]:(n?o=o.get(n):o=o.dup(),this.devaluateHook(n?"promise":"export",o))}case"function":case"rpc-target":{if(!this.source)throw new Error("Can't serialize RPC stubs in this context.");let o=this.source.getHookForRpcTarget(e,r);return this.devaluateHook("export",o)}case"rpc-thenable":{if(!this.source)throw new Error("Can't serialize RPC stubs in this context.");let o=this.source.getHookForRpcTarget(e,r);return this.devaluateHook("promise",o)}default:throw new Error("unreachable")}}devaluateHook(e,r){this.exports||(this.exports=[]);let s=e==="promise"?this.exporter.exportPromise(r):this.exporter.exportStub(r);return this.exports.push(s),[e,s]}};var le=class{importStub(t){throw new Error("Cannot deserialize RPC stubs without an RPC session.")}importPromise(t){throw new Error("Cannot deserialize RPC stubs without an RPC session.")}getExport(t){}},ke=new le,v=class X{constructor(e){this.importer=e}stubs=[];promises=[];evaluate(e){let r=m.forEvaluate(this.stubs,this.promises);try{return r.value=this.evaluateImpl(e,r,"value"),r}catch(s){throw r.dispose(),s}}evaluateCopy(e){return this.evaluate(structuredClone(e))}evaluateImpl(e,r,s){if(e instanceof Array){if(e.length==1&&e[0]instanceof Array){let i=e[0];for(let o=0;o<i.length;o++)i[o]=this.evaluateImpl(i[o],i,o);return i}else switch(e[0]){case"bigint":if(typeof e[1]=="string")return BigInt(e[1]);break;case"date":if(typeof e[1]=="number")return new Date(e[1]);break;case"bytes":{let i=Uint8Array;if(typeof e[1]=="string"){if(i.fromBase64)return i.fromBase64(e[1]);{let o=atob(e[1]),n=o.length,l=new Uint8Array(n);for(let a=0;a<n;a++)l[a]=o.charCodeAt(a);return l}}break}case"error":if(e.length>=3&&typeof e[1]=="string"&&typeof e[2]=="string"){let i=ae[e[1]]||Error,o=new i(e[2]);return typeof e[3]=="string"&&(o.stack=e[3]),o}break;case"undefined":if(e.length===1)return;break;case"import":case"pipeline":{if(e.length<2||e.length>4||typeof e[1]!="number")break;let i=this.importer.getExport(e[1]);if(!i)throw new Error(`no such entry on exports table: ${e[1]}`);let o=e[0]=="pipeline",n=h=>{if(o){let u=new c(h,[]);return this.promises.push({promise:u,parent:r,property:s}),u}else{let u=new c(h,[]);return this.stubs.push(u),u}};if(e.length==2)return n(o?i.get([]):i.dup());let l=e[2];if(!(l instanceof Array)||!l.every(h=>typeof h=="string"||typeof h=="number"))break;if(e.length==3)return n(i.get(l));let a=e[3];if(!(a instanceof Array))break;return a=new X(this.importer).evaluate([a]),n(i.call(l,a))}case"remap":{if(e.length!==5||typeof e[1]!="number"||!(e[2]instanceof Array)||!(e[3]instanceof Array)||!(e[4]instanceof Array))break;let i=this.importer.getExport(e[1]);if(!i)throw new Error(`no such entry on exports table: ${e[1]}`);let o=e[2];if(!o.every(h=>typeof h=="string"||typeof h=="number"))break;let n=e[3].map(h=>{if(!(h instanceof Array)||h.length!==2||h[0]!=="import"&&h[0]!=="export"||typeof h[1]!="number")throw new TypeError(`unknown map capture: ${JSON.stringify(h)}`);if(h[0]==="export")return this.importer.importStub(h[1]);{let u=this.importer.getExport(h[1]);if(!u)throw new Error(`no such entry on exports table: ${h[1]}`);return u.dup()}}),l=e[4],a=i.map(o,n,l),p=new c(a,[]);return this.promises.push({promise:p,parent:r,property:s}),p}case"export":case"promise":if(typeof e[1]=="number")if(e[0]=="promise"){let i=this.importer.importPromise(e[1]),o=new c(i,[]);return this.promises.push({parent:r,property:s,promise:o}),o}else{let i=this.importer.importStub(e[1]),o=new w(i);return this.stubs.push(o),o}break}throw new TypeError(`unknown special value: ${JSON.stringify(e)}`)}else if(e instanceof Object){let i=e;for(let o in i)o in Object.prototype||o==="toJSON"?(this.evaluateImpl(i[o],i,o),delete i[o]):i[o]=this.evaluateImpl(i[o],i,o);return i}else return e}};var S=class{constructor(t,e,r){this.session=t,this.importId=e,r&&(this.activePull=Promise.withResolvers())}localRefcount=0;remoteRefcount=1;activePull;resolution;onBrokenRegistrations;resolve(t){if(this.localRefcount==0){t.dispose();return}if(this.resolution=t,this.sendRelease(),this.onBrokenRegistrations){for(let e of this.onBrokenRegistrations){let r=this.session.onBrokenCallbacks[e],s=this.session.onBrokenCallbacks.length;t.onBroken(r),this.session.onBrokenCallbacks[s]===r?delete this.session.onBrokenCallbacks[s]:delete this.session.onBrokenCallbacks[e]}this.onBrokenRegistrations=void 0}this.activePull&&(this.activePull.resolve(),this.activePull=void 0)}async awaitResolution(){return this.activePull||(this.session.sendPull(this.importId),this.activePull=Promise.withResolvers()),await this.activePull.promise,this.resolution.pull()}dispose(){this.resolution?this.resolution.dispose():(this.abort(new Error("RPC was canceled because the RpcPromise was disposed.")),this.sendRelease())}abort(t){this.resolution||(this.resolution=new y(t),this.activePull&&(this.activePull.reject(t),this.activePull=void 0),this.onBrokenRegistrations=void 0)}onBroken(t){if(this.resolution)this.resolution.onBroken(t);else{let e=this.session.onBrokenCallbacks.length;this.session.onBrokenCallbacks.push(t),this.onBrokenRegistrations||(this.onBrokenRegistrations=[]),this.onBrokenRegistrations.push(e)}}sendRelease(){this.remoteRefcount>0&&(this.session.sendRelease(this.importId,this.remoteRefcount),this.remoteRefcount=0)}},E=class Y extends x{constructor(e,r){super(),this.isPromise=e,++r.localRefcount,this.entry=r}entry;collectPath(e){return this}getEntry(){if(this.entry)return this.entry;throw new Error("This RpcImportHook was already disposed.")}call(e,r){let s=this.getEntry();return s.resolution?s.resolution.call(e,r):s.session.sendCall(s.importId,e,r)}map(e,r,s){let i;try{i=this.getEntry()}catch(o){for(let n of r)n.dispose();throw o}return i.resolution?i.resolution.map(e,r,s):i.session.sendMap(i.importId,e,r,s)}get(e){let r=this.getEntry();return r.resolution?r.resolution.get(e):r.session.sendCall(r.importId,e)}dup(){return new Y(!1,this.getEntry())}pull(){let e=this.getEntry();if(!this.isPromise)throw new Error("Can't pull this hook because it's not a promise hook.");return e.resolution?e.resolution.pull():e.awaitResolution()}ignoreUnhandledRejections(){}dispose(){let e=this.entry;this.entry=void 0,e&&--e.localRefcount===0&&e.dispose()}onBroken(e){this.entry&&this.entry.onBroken(e)}},he=class extends E{session;constructor(t){super(!1,t),this.session=t.session}dispose(){if(this.session){let t=this.session;this.session=void 0,t.shutdown()}}},pe=class{constructor(t,e,r){this.transport=t,this.options=r,this.exports.push({hook:e,refcount:1}),this.imports.push(new S(this,0,!1));let s,i=new Promise((o,n)=>{s=n});this.cancelReadLoop=s,this.readLoop(i).catch(o=>this.abort(o))}exports=[];reverseExports=new Map;imports=[];abortReason;cancelReadLoop;nextExportId=-1;onBatchDone;pullCount=0;onBrokenCallbacks=[];getMainImport(){return new he(this.imports[0])}shutdown(){this.abort(new Error("RPC session was shut down by disposing the main stub"),!1)}exportStub(t){if(this.abortReason)throw this.abortReason;let e=this.reverseExports.get(t);if(e!==void 0)return++this.exports[e].refcount,e;{let r=this.nextExportId--;return this.exports[r]={hook:t,refcount:1},this.reverseExports.set(t,r),r}}exportPromise(t){if(this.abortReason)throw this.abortReason;let e=this.nextExportId--;return this.exports[e]={hook:t,refcount:1},this.reverseExports.set(t,e),this.ensureResolvingExport(e),e}unexport(t){for(let e of t)this.releaseExport(e,1)}releaseExport(t,e){let r=this.exports[t];if(!r)throw new Error(`no such export ID: ${t}`);if(r.refcount<e)throw new Error(`refcount would go negative: ${r.refcount} < ${e}`);r.refcount-=e,r.refcount===0&&(delete this.exports[t],this.reverseExports.delete(r.hook),r.hook.dispose())}onSendError(t){if(this.options.onSendError)return this.options.onSendError(t)}ensureResolvingExport(t){let e=this.exports[t];if(!e)throw new Error(`no such export ID: ${t}`);if(!e.pull){let r=async()=>{let s=e.hook;for(;;){let i=await s.pull();if(i.value instanceof w){let{hook:o,pathIfPromise:n}=A(i.value);if(n&&n.length==0&&this.getImport(s)===void 0){s=o;continue}}return i}};++this.pullCount,e.pull=r().then(s=>{let i=R.devaluate(s.value,void 0,this,s);this.send(["resolve",t,i])},s=>{this.send(["reject",t,R.devaluate(s,void 0,this)])}).catch(s=>{try{this.send(["reject",t,R.devaluate(s,void 0,this)])}catch(i){this.abort(i)}}).finally(()=>{--this.pullCount===0&&this.onBatchDone&&this.onBatchDone.resolve()})}}getImport(t){if(t instanceof E&&t.entry&&t.entry.session===this)return t.entry.importId}importStub(t){if(this.abortReason)throw this.abortReason;let e=this.imports[t];return e||(e=new S(this,t,!1),this.imports[t]=e),new E(!1,e)}importPromise(t){if(this.abortReason)throw this.abortReason;if(this.imports[t])return new y(new Error("Bug in RPC system: The peer sent a promise reusing an existing export ID."));let e=new S(this,t,!0);return this.imports[t]=e,new E(!0,e)}getExport(t){return this.exports[t]?.hook}send(t){if(this.abortReason!==void 0)return;let e;try{e=JSON.stringify(t)}catch(r){try{this.abort(r)}catch{}throw r}this.transport.send(e).catch(r=>this.abort(r,!1))}sendCall(t,e,r){if(this.abortReason)throw this.abortReason;let s=["pipeline",t,e];if(r){let o=R.devaluate(r.value,void 0,this,r);s.push(o[0])}this.send(["push",s]);let i=new S(this,this.imports.length,!1);return this.imports.push(i),new E(!0,i)}sendMap(t,e,r,s){if(this.abortReason){for(let l of r)l.dispose();throw this.abortReason}let i=r.map(l=>{let a=this.getImport(l);return a!==void 0?["import",a]:["export",this.exportStub(l)]}),o=["remap",t,e,i,s];this.send(["push",o]);let n=new S(this,this.imports.length,!1);return this.imports.push(n),new E(!0,n)}sendPull(t){if(this.abortReason)throw this.abortReason;this.send(["pull",t])}sendRelease(t,e){this.abortReason||(this.send(["release",t,e]),delete this.imports[t])}abort(t,e=!0){if(this.abortReason===void 0){if(this.cancelReadLoop(t),e)try{this.transport.send(JSON.stringify(["abort",R.devaluate(t,void 0,this)])).catch(r=>{})}catch{}if(t===void 0&&(t="undefined"),this.abortReason=t,this.onBatchDone&&this.onBatchDone.reject(t),this.transport.abort)try{this.transport.abort(t)}catch(r){Promise.resolve(r)}for(let r in this.onBrokenCallbacks)try{this.onBrokenCallbacks[r](t)}catch(s){Promise.resolve(s)}for(let r in this.imports)this.imports[r].abort(t);for(let r in this.exports)this.exports[r].hook.dispose()}}async readLoop(t){for(;!this.abortReason;){let e=JSON.parse(await Promise.race([this.transport.receive(),t]));if(this.abortReason)break;if(e instanceof Array)switch(e[0]){case"push":if(e.length>1){let r=new v(this).evaluate(e[1]),s=new g(r);s.ignoreUnhandledRejections(),this.exports.push({hook:s,refcount:1});continue}break;case"pull":{let r=e[1];if(typeof r=="number"){this.ensureResolvingExport(r);continue}break}case"resolve":case"reject":{let r=e[1];if(typeof r=="number"&&e.length>2){let s=this.imports[r];if(s)if(e[0]=="resolve")s.resolve(new g(new v(this).evaluate(e[2])));else{let i=new v(this).evaluate(e[2]);i.dispose(),s.resolve(new y(i.value))}else e[0]=="resolve"&&new v(this).evaluate(e[2]).dispose();continue}break}case"release":{let r=e[1],s=e[2];if(typeof r=="number"&&typeof s=="number"){this.releaseExport(r,s);continue}break}case"abort":{let r=new v(this).evaluate(e[1]);r.dispose(),this.abort(r,!1);break}}throw new Error(`bad RPC message: ${JSON.stringify(e)}`)}}async drain(){if(this.abortReason)throw this.abortReason;if(this.pullCount>0){let{promise:t,resolve:e,reject:r}=Promise.withResolvers();this.onBatchDone={resolve:e,reject:r},await t}}getStats(){let t={imports:0,exports:0};for(let e in this.imports)++t.imports;for(let e in this.exports)++t.exports;return t}},Z=class{#e;#t;constructor(t,e,r={}){let s;e?s=new g(m.fromAppReturn(e)):s=new y(new Error("This connection has no main object.")),this.#e=new pe(t,s,r),this.#t=new w(this.#e.getMainImport())}getRemoteMain(){return this.#t}getStats(){return this.#e.getStats()}drain(){return this.#e.drain()}};function ce(t,e,r){typeof t=="string"&&(t=new WebSocket(t));let s=new de(t);return new Z(s,e,r).getRemoteMain()}function ue(t,e,r){if(t.headers.get("Upgrade")?.toLowerCase()!=="websocket")return new Response("This endpoint only accepts WebSocket requests.",{status:400});let s=new WebSocketPair,i=s[0];return i.accept(),ce(i,e,r),new Response(null,{status:101,webSocket:s[1]})}var de=class{constructor(t){this.#e=t,t.readyState===WebSocket.CONNECTING&&(this.#t=[],t.addEventListener("open",e=>{try{for(let r of this.#t)t.send(r)}catch(r){this.#o(r)}this.#t=void 0})),t.addEventListener("message",e=>{this.#s||(typeof e.data=="string"?this.#r?(this.#r(e.data),this.#r=void 0,this.#i=void 0):this.#n.push(e.data):this.#o(new TypeError("Received non-string message from WebSocket.")))}),t.addEventListener("close",e=>{this.#o(new Error(`Peer closed WebSocket: ${e.code} ${e.reason}`))}),t.addEventListener("error",e=>{this.#o(new Error("WebSocket connection failed."))})}#e;#t;#r;#i;#n=[];#s;async send(t){this.#t===void 0?this.#e.send(t):this.#t.push(t)}async receive(){if(this.#n.length>0)return this.#n.shift();if(this.#s)throw this.#s;return new Promise((t,e)=>{this.#r=t,this.#i=e})}abort(t){let e;t instanceof Error?e=t.message:e=`${t}`,this.#e.close(3e3,e),this.#s||(this.#s=t)}#o(t){this.#s||(this.#s=t,this.#i&&(this.#i(t),this.#r=void 0,this.#i=void 0))}};var fe=class{constructor(t){this.#t=t}#e=[];#t;#r=Promise.withResolvers();async send(t){this.#e.push(t)}async receive(){let t=this.#t.shift();return t!==void 0?t:(this.#r.resolve(),new Promise(e=>{}))}abort(t){this.#r.reject(t)}whenAllReceived(){return this.#r.promise}getResponseBody(){return this.#e.join(`
2
- `)}};async function me(t,e,r){if(t.method!=="POST")return new Response("This endpoint only accepts POST requests.",{status:405});let s=await t.text(),i=s===""?[]:s.split(`
3
- `),o=new fe(i),n=new Z(o,e,r);return await o.whenAllReceived(),await n.drain(),new Response(o.getResponseBody())}var k,we=class{context;captureMap=new Map;instructions=[];constructor(t,e){k?this.context={parent:k,captures:[],subject:k.capture(t),path:e}:this.context={parent:void 0,captures:[],subject:t,path:e},k=this}unregister(){k=this.context.parent}makeInput(){return new T(this,0)}makeOutput(t){let e;try{e=R.devaluate(t.value,void 0,this,t)}finally{t.dispose()}return this.instructions.push(e),this.context.parent?(this.context.parent.instructions.push(["remap",this.context.subject,this.context.path,this.context.captures.map(r=>["import",r]),this.instructions]),new T(this.context.parent,this.context.parent.instructions.length)):this.context.subject.map(this.context.path,this.context.captures,this.instructions)}pushCall(t,e,r){let s=R.devaluate(r.value,void 0,this,r);s=s[0];let i=this.capture(t.dup());return this.instructions.push(["pipeline",i,e,s]),new T(this,this.instructions.length)}pushGet(t,e){let r=this.capture(t.dup());return this.instructions.push(["pipeline",r,e]),new T(this,this.instructions.length)}capture(t){if(t instanceof T&&t.mapper===this)return t.idx;let e=this.captureMap.get(t);if(e===void 0){if(this.context.parent){let r=this.context.parent.capture(t);this.context.captures.push(r)}else this.context.captures.push(t);e=-this.context.captures.length,this.captureMap.set(t,e)}return e}exportStub(t){throw new Error("Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.")}exportPromise(t){return this.exportStub(t)}getImport(t){return this.capture(t)}unexport(t){}onSendError(t){}};M.sendMap=(t,e,r)=>{let s=new we(t,e),i;try{i=m.fromAppReturn(ee(s.pushCall.bind(s),()=>r(new c(s.makeInput(),[]))))}finally{s.unregister()}if(i instanceof Promise)throw i.catch(o=>{}),new Error("RPC map() callbacks cannot be async.");return new c(s.makeOutput(i),[])};function C(){throw new Error("Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.")}var T=class extends x{constructor(t,e){super(),this.mapper=t,this.idx=e}dup(){return this}dispose(){}get(t){if(t.length==0)return this;if(k)return k.pushGet(this,t);C()}call(t,e){C()}map(t,e,r){C()}pull(){C()}ignoreUnhandledRejections(){}onBroken(t){C()}},ge=class{constructor(t,e){this.captures=t,this.variables=[e]}variables;dispose(){for(let t of this.variables)t.dispose()}apply(t){try{if(t.length<1)throw new Error("Invalid empty mapper function.");for(let e of t.slice(0,-1)){let r=new v(this).evaluateCopy(e);if(r.value instanceof w){let s=$(r.value);if(s){this.variables.push(s);continue}}this.variables.push(new g(r))}return new v(this).evaluateCopy(t[t.length-1])}finally{for(let e of this.variables)e.dispose()}}importStub(t){throw new Error("A mapper function cannot refer to exports.")}importPromise(t){return this.importStub(t)}getExport(t){return t<0?this.captures[-t-1]:this.variables[t]}};function J(t,e,r,s,i){let o=new g(m.deepCopyFrom(t,e,r)),n=new ge(s,o);try{return n.apply(i)}finally{n.dispose()}}M.applyMap=(t,e,r,s,i)=>{try{let o;if(t instanceof c)throw new Error("applyMap() can't be called on RpcPromise");if(t instanceof Array){let n=[];try{for(let l of t)n.push(J(l,t,r,s,i))}catch(l){for(let a of n)a.dispose();throw l}o=m.fromArray(n)}else t==null?o=m.fromAppReturn(t):o=J(t,e,r,s,i);return new g(o)}finally{for(let o of s)o.dispose()}};async function q(t,e){if(t.method==="POST"){let r=await me(t,e);return r.headers.set("Access-Control-Allow-Origin","*"),r}else return t.headers.get("Upgrade")?.toLowerCase()==="websocket"?ue(t,e):new Response("This endpoint only accepts POST or WebSocket requests.",{status:400})}import{EmailMessage as be}from"cloudflare:email";var P=class extends Error{constructor(e){super(`Binding ${e?`"${e}"`:""} not found`)}};function ye(t,e){let r=new URL(t.url),s=r.searchParams.get("MF-Binding");if(!s)throw new P;let i=e[s];if(!i)throw new P(s);if(i.constructor.name==="SendEmail")return{async send(o){let n=new be(o.from,o.to,o["EmailMessage::raw"]);return i.send(n)}};if(r.searchParams.has("MF-Dispatch-Namespace-Options")){let{name:o,args:n,options:l}=JSON.parse(r.searchParams.get("MF-Dispatch-Namespace-Options"));return i.get(o,n,l)}return i}function Re(t,e){let r=t.headers.get("MF-Binding");if(!r)throw new P;let s=e[r];if(!s)throw new P(r);let i=t.headers.get("MF-Dispatch-Namespace-Options");if(i){let{name:o,args:n,options:l}=JSON.parse(i);return s.get(o,n,l)}return s}function ve(t){let e=new URL(t.url);return t.headers.has("Upgrade")&&e.searchParams.has("MF-Binding")}var We={async fetch(t,e){try{if(ve(t))return q(t,ye(t,e));{let r=Re(t,e),s=new Headers;for(let[i,o]of t.headers)i.startsWith("mf-header-")?s.set(i.slice(10),o):i==="upgrade"&&s.set(i,o);return r.fetch(t.headers.get("MF-URL")??"http://example.com",new Request(t,{redirect:"manual",headers:s}))}}catch(r){return r instanceof P?new Response(r.message,{status:400}):new Response(r.message,{status:500})}}};export{We as default};
1
+ import { EmailMessage } from "cloudflare:email";
2
+
3
+ //#region ../node_modules/.bun/capnweb@0.1.0/node_modules/capnweb/dist/index.js
4
+ if (!Symbol.dispose) Symbol.dispose = Symbol.for("dispose");
5
+ if (!Symbol.asyncDispose) Symbol.asyncDispose = Symbol.for("asyncDispose");
6
+ var workersModuleName = navigator.userAgent === "Cloudflare-Workers" ? "cloudflare:workers" : null;
7
+ var workersModule;
8
+ if (workersModuleName) workersModule = await import(
9
+ /* @vite-ignore */
10
+ workersModuleName
11
+ );
12
+ var RpcTarget = workersModule ? workersModule.RpcTarget : class {};
13
+ function typeForRpc(value) {
14
+ switch (typeof value) {
15
+ case "boolean":
16
+ case "number":
17
+ case "string": return "primitive";
18
+ case "undefined": return "undefined";
19
+ case "object":
20
+ case "function": break;
21
+ case "bigint": return "bigint";
22
+ default: return "unsupported";
23
+ }
24
+ if (value === null) return "primitive";
25
+ let prototype = Object.getPrototypeOf(value);
26
+ switch (prototype) {
27
+ case Object.prototype: return "object";
28
+ case Function.prototype: return "function";
29
+ case Array.prototype: return "array";
30
+ case Date.prototype: return "date";
31
+ case Uint8Array.prototype: return "bytes";
32
+ case RpcStub.prototype: return "stub";
33
+ case RpcPromise.prototype: return "rpc-promise";
34
+ default:
35
+ if (workersModule) {
36
+ if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) return "rpc-target";
37
+ else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) return "rpc-thenable";
38
+ }
39
+ if (value instanceof RpcTarget) return "rpc-target";
40
+ if (value instanceof Error) return "error";
41
+ return "unsupported";
42
+ }
43
+ }
44
+ function mapNotLoaded() {
45
+ throw new Error("RPC map() implementation was not loaded.");
46
+ }
47
+ var mapImpl = {
48
+ applyMap: mapNotLoaded,
49
+ sendMap: mapNotLoaded
50
+ };
51
+ var StubHook = class {};
52
+ var ErrorStubHook = class extends StubHook {
53
+ constructor(error) {
54
+ super();
55
+ this.error = error;
56
+ }
57
+ call(path, args) {
58
+ return this;
59
+ }
60
+ map(path, captures, instructions) {
61
+ return this;
62
+ }
63
+ get(path) {
64
+ return this;
65
+ }
66
+ dup() {
67
+ return this;
68
+ }
69
+ pull() {
70
+ return Promise.reject(this.error);
71
+ }
72
+ ignoreUnhandledRejections() {}
73
+ dispose() {}
74
+ onBroken(callback) {
75
+ try {
76
+ callback(this.error);
77
+ } catch (err) {
78
+ Promise.resolve(err);
79
+ }
80
+ }
81
+ };
82
+ var DISPOSED_HOOK = new ErrorStubHook(/* @__PURE__ */ new Error("Attempted to use RPC stub after it has been disposed."));
83
+ var doCall = (hook, path, params) => {
84
+ return hook.call(path, params);
85
+ };
86
+ function withCallInterceptor(interceptor, callback) {
87
+ let oldValue = doCall;
88
+ doCall = interceptor;
89
+ try {
90
+ return callback();
91
+ } finally {
92
+ doCall = oldValue;
93
+ }
94
+ }
95
+ var RAW_STUB = Symbol("realStub");
96
+ var PROXY_HANDLERS = {
97
+ apply(target, thisArg, argumentsList) {
98
+ let stub = target.raw;
99
+ return new RpcPromise(doCall(stub.hook, stub.pathIfPromise || [], RpcPayload.fromAppParams(argumentsList)), []);
100
+ },
101
+ get(target, prop, receiver) {
102
+ let stub = target.raw;
103
+ if (prop === RAW_STUB) return stub;
104
+ else if (prop in RpcPromise.prototype) return stub[prop];
105
+ else if (typeof prop === "string") return new RpcPromise(stub.hook, stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]);
106
+ else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return () => {
107
+ stub.hook.dispose();
108
+ stub.hook = DISPOSED_HOOK;
109
+ };
110
+ else return;
111
+ },
112
+ has(target, prop) {
113
+ let stub = target.raw;
114
+ if (prop === RAW_STUB) return true;
115
+ else if (prop in RpcPromise.prototype) return prop in stub;
116
+ else if (typeof prop === "string") return true;
117
+ else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return true;
118
+ else return false;
119
+ },
120
+ construct(target, args) {
121
+ throw new Error("An RPC stub cannot be used as a constructor.");
122
+ },
123
+ defineProperty(target, property, attributes) {
124
+ throw new Error("Can't define properties on RPC stubs.");
125
+ },
126
+ deleteProperty(target, p) {
127
+ throw new Error("Can't delete properties on RPC stubs.");
128
+ },
129
+ getOwnPropertyDescriptor(target, p) {},
130
+ getPrototypeOf(target) {
131
+ return Object.getPrototypeOf(target.raw);
132
+ },
133
+ isExtensible(target) {
134
+ return false;
135
+ },
136
+ ownKeys(target) {
137
+ return [];
138
+ },
139
+ preventExtensions(target) {
140
+ return true;
141
+ },
142
+ set(target, p, newValue, receiver) {
143
+ throw new Error("Can't assign properties on RPC stubs.");
144
+ },
145
+ setPrototypeOf(target, v) {
146
+ throw new Error("Can't override prototype of RPC stubs.");
147
+ }
148
+ };
149
+ var RpcStub = class _RpcStub extends RpcTarget {
150
+ constructor(hook, pathIfPromise) {
151
+ super();
152
+ if (!(hook instanceof StubHook)) {
153
+ let value = hook;
154
+ if (value instanceof RpcTarget || value instanceof Function) hook = TargetStubHook.create(value, void 0);
155
+ else hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));
156
+ if (pathIfPromise) throw new TypeError("RpcStub constructor expected one argument, received two.");
157
+ }
158
+ this.hook = hook;
159
+ this.pathIfPromise = pathIfPromise;
160
+ let func = () => {};
161
+ func.raw = this;
162
+ return new Proxy(func, PROXY_HANDLERS);
163
+ }
164
+ hook;
165
+ pathIfPromise;
166
+ dup() {
167
+ let target = this[RAW_STUB];
168
+ if (target.pathIfPromise) return new _RpcStub(target.hook.get(target.pathIfPromise));
169
+ else return new _RpcStub(target.hook.dup());
170
+ }
171
+ onRpcBroken(callback) {
172
+ this[RAW_STUB].hook.onBroken(callback);
173
+ }
174
+ map(func) {
175
+ let { hook, pathIfPromise } = this[RAW_STUB];
176
+ return mapImpl.sendMap(hook, pathIfPromise || [], func);
177
+ }
178
+ };
179
+ var RpcPromise = class extends RpcStub {
180
+ constructor(hook, pathIfPromise) {
181
+ super(hook, pathIfPromise);
182
+ }
183
+ then(onfulfilled, onrejected) {
184
+ return pullPromise(this).then(...arguments);
185
+ }
186
+ catch(onrejected) {
187
+ return pullPromise(this).catch(...arguments);
188
+ }
189
+ finally(onfinally) {
190
+ return pullPromise(this).finally(...arguments);
191
+ }
192
+ };
193
+ function unwrapStubTakingOwnership(stub) {
194
+ let { hook, pathIfPromise } = stub[RAW_STUB];
195
+ if (pathIfPromise && pathIfPromise.length > 0) return hook.get(pathIfPromise);
196
+ else return hook;
197
+ }
198
+ function unwrapStubAndDup(stub) {
199
+ let { hook, pathIfPromise } = stub[RAW_STUB];
200
+ if (pathIfPromise) return hook.get(pathIfPromise);
201
+ else return hook.dup();
202
+ }
203
+ function unwrapStubNoProperties(stub) {
204
+ let { hook, pathIfPromise } = stub[RAW_STUB];
205
+ if (pathIfPromise && pathIfPromise.length > 0) return;
206
+ return hook;
207
+ }
208
+ function unwrapStubOrParent(stub) {
209
+ return stub[RAW_STUB].hook;
210
+ }
211
+ function unwrapStubAndPath(stub) {
212
+ return stub[RAW_STUB];
213
+ }
214
+ async function pullPromise(promise) {
215
+ let { hook, pathIfPromise } = promise[RAW_STUB];
216
+ if (pathIfPromise.length > 0) hook = hook.get(pathIfPromise);
217
+ return (await hook.pull()).deliverResolve();
218
+ }
219
+ var RpcPayload = class _RpcPayload {
220
+ constructor(value, source, stubs, promises) {
221
+ this.value = value;
222
+ this.source = source;
223
+ this.stubs = stubs;
224
+ this.promises = promises;
225
+ }
226
+ static fromAppParams(value) {
227
+ return new _RpcPayload(value, "params");
228
+ }
229
+ static fromAppReturn(value) {
230
+ return new _RpcPayload(value, "return");
231
+ }
232
+ static fromArray(array) {
233
+ let stubs = [];
234
+ let promises = [];
235
+ let resultArray = [];
236
+ for (let payload of array) {
237
+ payload.ensureDeepCopied();
238
+ for (let stub of payload.stubs) stubs.push(stub);
239
+ for (let promise of payload.promises) {
240
+ if (promise.parent === payload) promise = {
241
+ parent: resultArray,
242
+ property: resultArray.length,
243
+ promise: promise.promise
244
+ };
245
+ promises.push(promise);
246
+ }
247
+ resultArray.push(payload.value);
248
+ }
249
+ return new _RpcPayload(resultArray, "owned", stubs, promises);
250
+ }
251
+ static forEvaluate(stubs, promises) {
252
+ return new _RpcPayload(null, "owned", stubs, promises);
253
+ }
254
+ static deepCopyFrom(value, oldParent, owner) {
255
+ let result = new _RpcPayload(null, "owned", [], []);
256
+ result.value = result.deepCopy(value, oldParent, "value", result, true, owner);
257
+ return result;
258
+ }
259
+ rpcTargets;
260
+ getHookForRpcTarget(target, parent, dupStubs = true) {
261
+ if (this.source === "params") return TargetStubHook.create(target, parent);
262
+ else if (this.source === "return") {
263
+ let hook = this.rpcTargets?.get(target);
264
+ if (hook) if (dupStubs) return hook.dup();
265
+ else {
266
+ this.rpcTargets?.delete(target);
267
+ return hook;
268
+ }
269
+ else {
270
+ hook = TargetStubHook.create(target, parent);
271
+ if (dupStubs) {
272
+ if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
273
+ this.rpcTargets.set(target, hook);
274
+ return hook.dup();
275
+ } else return hook;
276
+ }
277
+ } else throw new Error("owned payload shouldn't contain raw RpcTargets");
278
+ }
279
+ deepCopy(value, oldParent, property, parent, dupStubs, owner) {
280
+ switch (typeForRpc(value)) {
281
+ case "unsupported": return value;
282
+ case "primitive":
283
+ case "bigint":
284
+ case "date":
285
+ case "bytes":
286
+ case "error":
287
+ case "undefined": return value;
288
+ case "array": {
289
+ let array = value;
290
+ let len = array.length;
291
+ let result = new Array(len);
292
+ for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);
293
+ return result;
294
+ }
295
+ case "object": {
296
+ let result = {};
297
+ let object = value;
298
+ for (let i in object) result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);
299
+ return result;
300
+ }
301
+ case "stub":
302
+ case "rpc-promise": {
303
+ let stub = value;
304
+ let hook;
305
+ if (dupStubs) hook = unwrapStubAndDup(stub);
306
+ else hook = unwrapStubTakingOwnership(stub);
307
+ if (stub instanceof RpcPromise) {
308
+ let promise = new RpcPromise(hook, []);
309
+ this.promises.push({
310
+ parent,
311
+ property,
312
+ promise
313
+ });
314
+ return promise;
315
+ } else {
316
+ let newStub = new RpcStub(hook);
317
+ this.stubs.push(newStub);
318
+ return newStub;
319
+ }
320
+ }
321
+ case "function":
322
+ case "rpc-target": {
323
+ let target = value;
324
+ let stub;
325
+ if (owner) stub = new RpcStub(owner.getHookForRpcTarget(target, oldParent, dupStubs));
326
+ else stub = new RpcStub(TargetStubHook.create(target, oldParent));
327
+ this.stubs.push(stub);
328
+ return stub;
329
+ }
330
+ case "rpc-thenable": {
331
+ let target = value;
332
+ let promise;
333
+ if (owner) promise = new RpcPromise(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);
334
+ else promise = new RpcPromise(TargetStubHook.create(target, oldParent), []);
335
+ this.promises.push({
336
+ parent,
337
+ property,
338
+ promise
339
+ });
340
+ return promise;
341
+ }
342
+ default: throw new Error("unreachable");
343
+ }
344
+ }
345
+ ensureDeepCopied() {
346
+ if (this.source !== "owned") {
347
+ let dupStubs = this.source === "params";
348
+ this.stubs = [];
349
+ this.promises = [];
350
+ try {
351
+ this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
352
+ } catch (err) {
353
+ this.stubs = void 0;
354
+ this.promises = void 0;
355
+ throw err;
356
+ }
357
+ this.source = "owned";
358
+ if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error("Not all rpcTargets were accounted for in deep-copy?");
359
+ this.rpcTargets = void 0;
360
+ }
361
+ }
362
+ deliverTo(parent, property, promises) {
363
+ this.ensureDeepCopied();
364
+ if (this.value instanceof RpcPromise) _RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);
365
+ else {
366
+ parent[property] = this.value;
367
+ for (let record of this.promises) _RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);
368
+ }
369
+ }
370
+ static deliverRpcPromiseTo(promise, parent, property, promises) {
371
+ let hook = unwrapStubNoProperties(promise);
372
+ if (!hook) throw new Error("property promises should have been resolved earlier");
373
+ let inner = hook.pull();
374
+ if (inner instanceof _RpcPayload) inner.deliverTo(parent, property, promises);
375
+ else promises.push(inner.then((payload) => {
376
+ let subPromises = [];
377
+ payload.deliverTo(parent, property, subPromises);
378
+ if (subPromises.length > 0) return Promise.all(subPromises);
379
+ }));
380
+ }
381
+ async deliverCall(func, thisArg) {
382
+ try {
383
+ let promises = [];
384
+ this.deliverTo(this, "value", promises);
385
+ if (promises.length > 0) await Promise.all(promises);
386
+ let result = Function.prototype.apply.call(func, thisArg, this.value);
387
+ if (result instanceof RpcPromise) return _RpcPayload.fromAppReturn(result);
388
+ else return _RpcPayload.fromAppReturn(await result);
389
+ } finally {
390
+ this.dispose();
391
+ }
392
+ }
393
+ async deliverResolve() {
394
+ try {
395
+ let promises = [];
396
+ this.deliverTo(this, "value", promises);
397
+ if (promises.length > 0) await Promise.all(promises);
398
+ let result = this.value;
399
+ if (result instanceof Object) {
400
+ if (!(Symbol.dispose in result)) Object.defineProperty(result, Symbol.dispose, {
401
+ value: () => this.dispose(),
402
+ writable: true,
403
+ enumerable: false,
404
+ configurable: true
405
+ });
406
+ }
407
+ return result;
408
+ } catch (err) {
409
+ this.dispose();
410
+ throw err;
411
+ }
412
+ }
413
+ dispose() {
414
+ if (this.source === "owned") {
415
+ this.stubs.forEach((stub) => stub[Symbol.dispose]());
416
+ this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
417
+ } else if (this.source === "return") {
418
+ this.disposeImpl(this.value, void 0);
419
+ if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error("Not all rpcTargets were accounted for in disposeImpl()?");
420
+ }
421
+ this.source = "owned";
422
+ this.stubs = [];
423
+ this.promises = [];
424
+ }
425
+ disposeImpl(value, parent) {
426
+ switch (typeForRpc(value)) {
427
+ case "unsupported":
428
+ case "primitive":
429
+ case "bigint":
430
+ case "bytes":
431
+ case "date":
432
+ case "error":
433
+ case "undefined": return;
434
+ case "array": {
435
+ let array = value;
436
+ let len = array.length;
437
+ for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);
438
+ return;
439
+ }
440
+ case "object": {
441
+ let object = value;
442
+ for (let i in object) this.disposeImpl(object[i], object);
443
+ return;
444
+ }
445
+ case "stub":
446
+ case "rpc-promise": {
447
+ let hook = unwrapStubNoProperties(value);
448
+ if (hook) hook.dispose();
449
+ return;
450
+ }
451
+ case "function":
452
+ case "rpc-target": {
453
+ let target = value;
454
+ let hook = this.rpcTargets?.get(target);
455
+ if (hook) {
456
+ hook.dispose();
457
+ this.rpcTargets.delete(target);
458
+ } else disposeRpcTarget(target);
459
+ return;
460
+ }
461
+ case "rpc-thenable": return;
462
+ default: return;
463
+ }
464
+ }
465
+ ignoreUnhandledRejections() {
466
+ if (this.stubs) {
467
+ this.stubs.forEach((stub) => {
468
+ unwrapStubOrParent(stub).ignoreUnhandledRejections();
469
+ });
470
+ this.promises.forEach((promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections());
471
+ } else this.ignoreUnhandledRejectionsImpl(this.value);
472
+ }
473
+ ignoreUnhandledRejectionsImpl(value) {
474
+ switch (typeForRpc(value)) {
475
+ case "unsupported":
476
+ case "primitive":
477
+ case "bigint":
478
+ case "bytes":
479
+ case "date":
480
+ case "error":
481
+ case "undefined":
482
+ case "function":
483
+ case "rpc-target": return;
484
+ case "array": {
485
+ let array = value;
486
+ let len = array.length;
487
+ for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);
488
+ return;
489
+ }
490
+ case "object": {
491
+ let object = value;
492
+ for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);
493
+ return;
494
+ }
495
+ case "stub":
496
+ case "rpc-promise":
497
+ unwrapStubOrParent(value).ignoreUnhandledRejections();
498
+ return;
499
+ case "rpc-thenable":
500
+ value.then((_) => {}, (_) => {});
501
+ return;
502
+ default: return;
503
+ }
504
+ }
505
+ };
506
+ function followPath(value, parent, path, owner) {
507
+ for (let i = 0; i < path.length; i++) {
508
+ parent = value;
509
+ let part = path[i];
510
+ if (part in Object.prototype) {
511
+ value = void 0;
512
+ continue;
513
+ }
514
+ switch (typeForRpc(value)) {
515
+ case "object":
516
+ case "function":
517
+ if (Object.hasOwn(value, part)) value = value[part];
518
+ else value = void 0;
519
+ break;
520
+ case "array":
521
+ if (Number.isInteger(part) && part >= 0) value = value[part];
522
+ else value = void 0;
523
+ break;
524
+ case "rpc-target":
525
+ case "rpc-thenable":
526
+ if (Object.hasOwn(value, part)) value = void 0;
527
+ else value = value[part];
528
+ owner = null;
529
+ break;
530
+ case "stub":
531
+ case "rpc-promise": {
532
+ let { hook, pathIfPromise } = unwrapStubAndPath(value);
533
+ return {
534
+ hook,
535
+ remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i)
536
+ };
537
+ }
538
+ case "primitive":
539
+ case "bigint":
540
+ case "bytes":
541
+ case "date":
542
+ case "error":
543
+ value = void 0;
544
+ break;
545
+ case "undefined":
546
+ value = value[part];
547
+ break;
548
+ case "unsupported": if (i === 0) throw new TypeError(`RPC stub points at a non-serializable type.`);
549
+ else {
550
+ let prefix = path.slice(0, i).join(".");
551
+ let remainder = path.slice(0, i).join(".");
552
+ throw new TypeError(`'${prefix}' is not a serializable type, so property ${remainder} cannot be accessed.`);
553
+ }
554
+ default: throw new TypeError("unreachable");
555
+ }
556
+ }
557
+ if (value instanceof RpcPromise) {
558
+ let { hook, pathIfPromise } = unwrapStubAndPath(value);
559
+ return {
560
+ hook,
561
+ remainingPath: pathIfPromise || []
562
+ };
563
+ }
564
+ return {
565
+ value,
566
+ parent,
567
+ owner
568
+ };
569
+ }
570
+ var ValueStubHook = class extends StubHook {
571
+ call(path, args) {
572
+ try {
573
+ let { value, owner } = this.getValue();
574
+ let followResult = followPath(value, void 0, path, owner);
575
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
576
+ if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
577
+ return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
578
+ return new PayloadStubHook(payload);
579
+ }));
580
+ } catch (err) {
581
+ return new ErrorStubHook(err);
582
+ }
583
+ }
584
+ map(path, captures, instructions) {
585
+ try {
586
+ let followResult;
587
+ try {
588
+ let { value, owner } = this.getValue();
589
+ followResult = followPath(value, void 0, path, owner);
590
+ } catch (err) {
591
+ for (let cap of captures) cap.dispose();
592
+ throw err;
593
+ }
594
+ if (followResult.hook) return followResult.hook.map(followResult.remainingPath, captures, instructions);
595
+ return mapImpl.applyMap(followResult.value, followResult.parent, followResult.owner, captures, instructions);
596
+ } catch (err) {
597
+ return new ErrorStubHook(err);
598
+ }
599
+ }
600
+ get(path) {
601
+ try {
602
+ let { value, owner } = this.getValue();
603
+ if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
604
+ let followResult = followPath(value, void 0, path, owner);
605
+ if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
606
+ return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
607
+ } catch (err) {
608
+ return new ErrorStubHook(err);
609
+ }
610
+ }
611
+ };
612
+ var PayloadStubHook = class _PayloadStubHook extends ValueStubHook {
613
+ constructor(payload) {
614
+ super();
615
+ this.payload = payload;
616
+ }
617
+ payload;
618
+ getPayload() {
619
+ if (this.payload) return this.payload;
620
+ else throw new Error("Attempted to use an RPC StubHook after it was disposed.");
621
+ }
622
+ getValue() {
623
+ let payload = this.getPayload();
624
+ return {
625
+ value: payload.value,
626
+ owner: payload
627
+ };
628
+ }
629
+ dup() {
630
+ let thisPayload = this.getPayload();
631
+ return new _PayloadStubHook(RpcPayload.deepCopyFrom(thisPayload.value, void 0, thisPayload));
632
+ }
633
+ pull() {
634
+ return this.getPayload();
635
+ }
636
+ ignoreUnhandledRejections() {
637
+ if (this.payload) this.payload.ignoreUnhandledRejections();
638
+ }
639
+ dispose() {
640
+ if (this.payload) {
641
+ this.payload.dispose();
642
+ this.payload = void 0;
643
+ }
644
+ }
645
+ onBroken(callback) {
646
+ if (this.payload) {
647
+ if (this.payload.value instanceof RpcStub) this.payload.value.onRpcBroken(callback);
648
+ }
649
+ }
650
+ };
651
+ function disposeRpcTarget(target) {
652
+ if (Symbol.dispose in target) try {
653
+ target[Symbol.dispose]();
654
+ } catch (err) {
655
+ Promise.reject(err);
656
+ }
657
+ }
658
+ var TargetStubHook = class _TargetStubHook extends ValueStubHook {
659
+ static create(value, parent) {
660
+ if (typeof value !== "function") parent = void 0;
661
+ return new _TargetStubHook(value, parent);
662
+ }
663
+ constructor(target, parent, dupFrom) {
664
+ super();
665
+ this.target = target;
666
+ this.parent = parent;
667
+ if (dupFrom) {
668
+ if (dupFrom.refcount) {
669
+ this.refcount = dupFrom.refcount;
670
+ ++this.refcount.count;
671
+ }
672
+ } else if (Symbol.dispose in target) this.refcount = { count: 1 };
673
+ }
674
+ target;
675
+ parent;
676
+ refcount;
677
+ getTarget() {
678
+ if (this.target) return this.target;
679
+ else throw new Error("Attempted to use an RPC StubHook after it was disposed.");
680
+ }
681
+ getValue() {
682
+ return {
683
+ value: this.getTarget(),
684
+ owner: null
685
+ };
686
+ }
687
+ dup() {
688
+ return new _TargetStubHook(this.getTarget(), this.parent, this);
689
+ }
690
+ pull() {
691
+ let target = this.getTarget();
692
+ if ("then" in target) return Promise.resolve(target).then((resolution) => {
693
+ return RpcPayload.fromAppReturn(resolution);
694
+ });
695
+ else return Promise.reject(/* @__PURE__ */ new Error("Tried to resolve a non-promise stub."));
696
+ }
697
+ ignoreUnhandledRejections() {}
698
+ dispose() {
699
+ if (this.target) {
700
+ if (this.refcount) {
701
+ if (--this.refcount.count == 0) disposeRpcTarget(this.target);
702
+ }
703
+ this.target = void 0;
704
+ }
705
+ }
706
+ onBroken(callback) {}
707
+ };
708
+ var PromiseStubHook = class _PromiseStubHook extends StubHook {
709
+ promise;
710
+ resolution;
711
+ constructor(promise) {
712
+ super();
713
+ this.promise = promise.then((res) => {
714
+ this.resolution = res;
715
+ return res;
716
+ });
717
+ }
718
+ call(path, args) {
719
+ args.ensureDeepCopied();
720
+ return new _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
721
+ }
722
+ map(path, captures, instructions) {
723
+ return new _PromiseStubHook(this.promise.then((hook) => hook.map(path, captures, instructions), (err) => {
724
+ for (let cap of captures) cap.dispose();
725
+ throw err;
726
+ }));
727
+ }
728
+ get(path) {
729
+ return new _PromiseStubHook(this.promise.then((hook) => hook.get(path)));
730
+ }
731
+ dup() {
732
+ if (this.resolution) return this.resolution.dup();
733
+ else return new _PromiseStubHook(this.promise.then((hook) => hook.dup()));
734
+ }
735
+ pull() {
736
+ if (this.resolution) return this.resolution.pull();
737
+ else return this.promise.then((hook) => hook.pull());
738
+ }
739
+ ignoreUnhandledRejections() {
740
+ if (this.resolution) this.resolution.ignoreUnhandledRejections();
741
+ else this.promise.then((res) => {
742
+ res.ignoreUnhandledRejections();
743
+ }, (err) => {});
744
+ }
745
+ dispose() {
746
+ if (this.resolution) this.resolution.dispose();
747
+ else this.promise.then((hook) => {
748
+ hook.dispose();
749
+ }, (err) => {});
750
+ }
751
+ onBroken(callback) {
752
+ if (this.resolution) this.resolution.onBroken(callback);
753
+ else this.promise.then((hook) => {
754
+ hook.onBroken(callback);
755
+ }, callback);
756
+ }
757
+ };
758
+ var NullExporter = class {
759
+ exportStub(stub) {
760
+ throw new Error("Cannot serialize RPC stubs without an RPC session.");
761
+ }
762
+ exportPromise(stub) {
763
+ throw new Error("Cannot serialize RPC stubs without an RPC session.");
764
+ }
765
+ getImport(hook) {}
766
+ unexport(ids) {}
767
+ onSendError(error) {}
768
+ };
769
+ var NULL_EXPORTER = new NullExporter();
770
+ var ERROR_TYPES = {
771
+ Error,
772
+ EvalError,
773
+ RangeError,
774
+ ReferenceError,
775
+ SyntaxError,
776
+ TypeError,
777
+ URIError,
778
+ AggregateError
779
+ };
780
+ var Devaluator = class _Devaluator {
781
+ constructor(exporter, source) {
782
+ this.exporter = exporter;
783
+ this.source = source;
784
+ }
785
+ static devaluate(value, parent, exporter = NULL_EXPORTER, source) {
786
+ let devaluator = new _Devaluator(exporter, source);
787
+ try {
788
+ return devaluator.devaluateImpl(value, parent, 0);
789
+ } catch (err) {
790
+ if (devaluator.exports) try {
791
+ exporter.unexport(devaluator.exports);
792
+ } catch (err2) {}
793
+ throw err;
794
+ }
795
+ }
796
+ exports;
797
+ devaluateImpl(value, parent, depth) {
798
+ if (depth >= 64) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
799
+ switch (typeForRpc(value)) {
800
+ case "unsupported": {
801
+ let msg;
802
+ try {
803
+ msg = `Cannot serialize value: ${value}`;
804
+ } catch (err) {
805
+ msg = "Cannot serialize value: (couldn't stringify value)";
806
+ }
807
+ throw new TypeError(msg);
808
+ }
809
+ case "primitive": return value;
810
+ case "object": {
811
+ let object = value;
812
+ let result = {};
813
+ for (let key in object) result[key] = this.devaluateImpl(object[key], object, depth + 1);
814
+ return result;
815
+ }
816
+ case "array": {
817
+ let array = value;
818
+ let len = array.length;
819
+ let result = new Array(len);
820
+ for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);
821
+ return [result];
822
+ }
823
+ case "bigint": return ["bigint", value.toString()];
824
+ case "date": return ["date", value.getTime()];
825
+ case "bytes": {
826
+ let bytes = value;
827
+ if (bytes.toBase64) return ["bytes", bytes.toBase64({ omitPadding: true })];
828
+ else return ["bytes", btoa(String.fromCharCode.apply(null, bytes).replace(/=*$/, ""))];
829
+ }
830
+ case "error": {
831
+ let e = value;
832
+ let rewritten = this.exporter.onSendError(e);
833
+ if (rewritten) e = rewritten;
834
+ let result = [
835
+ "error",
836
+ e.name,
837
+ e.message
838
+ ];
839
+ if (rewritten && rewritten.stack) result.push(rewritten.stack);
840
+ return result;
841
+ }
842
+ case "undefined": return ["undefined"];
843
+ case "stub":
844
+ case "rpc-promise": {
845
+ if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
846
+ let { hook, pathIfPromise } = unwrapStubAndPath(value);
847
+ let importId = this.exporter.getImport(hook);
848
+ if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [
849
+ "pipeline",
850
+ importId,
851
+ pathIfPromise
852
+ ];
853
+ else return ["pipeline", importId];
854
+ else return ["import", importId];
855
+ if (pathIfPromise) hook = hook.get(pathIfPromise);
856
+ else hook = hook.dup();
857
+ return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);
858
+ }
859
+ case "function":
860
+ case "rpc-target": {
861
+ if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
862
+ let hook = this.source.getHookForRpcTarget(value, parent);
863
+ return this.devaluateHook("export", hook);
864
+ }
865
+ case "rpc-thenable": {
866
+ if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
867
+ let hook = this.source.getHookForRpcTarget(value, parent);
868
+ return this.devaluateHook("promise", hook);
869
+ }
870
+ default: throw new Error("unreachable");
871
+ }
872
+ }
873
+ devaluateHook(type, hook) {
874
+ if (!this.exports) this.exports = [];
875
+ let exportId = type === "promise" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);
876
+ this.exports.push(exportId);
877
+ return [type, exportId];
878
+ }
879
+ };
880
+ var NullImporter = class {
881
+ importStub(idx) {
882
+ throw new Error("Cannot deserialize RPC stubs without an RPC session.");
883
+ }
884
+ importPromise(idx) {
885
+ throw new Error("Cannot deserialize RPC stubs without an RPC session.");
886
+ }
887
+ getExport(idx) {}
888
+ };
889
+ var NULL_IMPORTER = new NullImporter();
890
+ var Evaluator = class _Evaluator {
891
+ constructor(importer) {
892
+ this.importer = importer;
893
+ }
894
+ stubs = [];
895
+ promises = [];
896
+ evaluate(value) {
897
+ let payload = RpcPayload.forEvaluate(this.stubs, this.promises);
898
+ try {
899
+ payload.value = this.evaluateImpl(value, payload, "value");
900
+ return payload;
901
+ } catch (err) {
902
+ payload.dispose();
903
+ throw err;
904
+ }
905
+ }
906
+ evaluateCopy(value) {
907
+ return this.evaluate(structuredClone(value));
908
+ }
909
+ evaluateImpl(value, parent, property) {
910
+ if (value instanceof Array) {
911
+ if (value.length == 1 && value[0] instanceof Array) {
912
+ let result = value[0];
913
+ for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i);
914
+ return result;
915
+ } else switch (value[0]) {
916
+ case "bigint":
917
+ if (typeof value[1] == "string") return BigInt(value[1]);
918
+ break;
919
+ case "date":
920
+ if (typeof value[1] == "number") return new Date(value[1]);
921
+ break;
922
+ case "bytes": {
923
+ let b64 = Uint8Array;
924
+ if (typeof value[1] == "string") if (b64.fromBase64) return b64.fromBase64(value[1]);
925
+ else {
926
+ let bs = atob(value[1]);
927
+ let len = bs.length;
928
+ let bytes = new Uint8Array(len);
929
+ for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
930
+ return bytes;
931
+ }
932
+ break;
933
+ }
934
+ case "error":
935
+ if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
936
+ let result = new (ERROR_TYPES[value[1]] || Error)(value[2]);
937
+ if (typeof value[3] === "string") result.stack = value[3];
938
+ return result;
939
+ }
940
+ break;
941
+ case "undefined":
942
+ if (value.length === 1) return;
943
+ break;
944
+ case "import":
945
+ case "pipeline": {
946
+ if (value.length < 2 || value.length > 4) break;
947
+ if (typeof value[1] != "number") break;
948
+ let hook = this.importer.getExport(value[1]);
949
+ if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);
950
+ let isPromise = value[0] == "pipeline";
951
+ let addStub = (hook2) => {
952
+ if (isPromise) {
953
+ let promise = new RpcPromise(hook2, []);
954
+ this.promises.push({
955
+ promise,
956
+ parent,
957
+ property
958
+ });
959
+ return promise;
960
+ } else {
961
+ let stub = new RpcPromise(hook2, []);
962
+ this.stubs.push(stub);
963
+ return stub;
964
+ }
965
+ };
966
+ if (value.length == 2) if (isPromise) return addStub(hook.get([]));
967
+ else return addStub(hook.dup());
968
+ let path = value[2];
969
+ if (!(path instanceof Array)) break;
970
+ if (!path.every((part) => {
971
+ return typeof part == "string" || typeof part == "number";
972
+ })) break;
973
+ if (value.length == 3) return addStub(hook.get(path));
974
+ let args = value[3];
975
+ if (!(args instanceof Array)) break;
976
+ args = new _Evaluator(this.importer).evaluate([args]);
977
+ return addStub(hook.call(path, args));
978
+ }
979
+ case "remap": {
980
+ if (value.length !== 5 || typeof value[1] !== "number" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array)) break;
981
+ let hook = this.importer.getExport(value[1]);
982
+ if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);
983
+ let path = value[2];
984
+ if (!path.every((part) => {
985
+ return typeof part == "string" || typeof part == "number";
986
+ })) break;
987
+ let captures = value[3].map((cap) => {
988
+ if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== "import" && cap[0] !== "export" || typeof cap[1] !== "number") throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);
989
+ if (cap[0] === "export") return this.importer.importStub(cap[1]);
990
+ else {
991
+ let exp = this.importer.getExport(cap[1]);
992
+ if (!exp) throw new Error(`no such entry on exports table: ${cap[1]}`);
993
+ return exp.dup();
994
+ }
995
+ });
996
+ let instructions = value[4];
997
+ let promise = new RpcPromise(hook.map(path, captures, instructions), []);
998
+ this.promises.push({
999
+ promise,
1000
+ parent,
1001
+ property
1002
+ });
1003
+ return promise;
1004
+ }
1005
+ case "export":
1006
+ case "promise":
1007
+ if (typeof value[1] == "number") if (value[0] == "promise") {
1008
+ let promise = new RpcPromise(this.importer.importPromise(value[1]), []);
1009
+ this.promises.push({
1010
+ parent,
1011
+ property,
1012
+ promise
1013
+ });
1014
+ return promise;
1015
+ } else {
1016
+ let stub = new RpcStub(this.importer.importStub(value[1]));
1017
+ this.stubs.push(stub);
1018
+ return stub;
1019
+ }
1020
+ break;
1021
+ }
1022
+ throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1023
+ } else if (value instanceof Object) {
1024
+ let result = value;
1025
+ for (let key in result) if (key in Object.prototype || key === "toJSON") {
1026
+ this.evaluateImpl(result[key], result, key);
1027
+ delete result[key];
1028
+ } else result[key] = this.evaluateImpl(result[key], result, key);
1029
+ return result;
1030
+ } else return value;
1031
+ }
1032
+ };
1033
+ var ImportTableEntry = class {
1034
+ constructor(session, importId, pulling) {
1035
+ this.session = session;
1036
+ this.importId = importId;
1037
+ if (pulling) this.activePull = Promise.withResolvers();
1038
+ }
1039
+ localRefcount = 0;
1040
+ remoteRefcount = 1;
1041
+ activePull;
1042
+ resolution;
1043
+ onBrokenRegistrations;
1044
+ resolve(resolution) {
1045
+ if (this.localRefcount == 0) {
1046
+ resolution.dispose();
1047
+ return;
1048
+ }
1049
+ this.resolution = resolution;
1050
+ this.sendRelease();
1051
+ if (this.onBrokenRegistrations) {
1052
+ for (let i of this.onBrokenRegistrations) {
1053
+ let callback = this.session.onBrokenCallbacks[i];
1054
+ let endIndex = this.session.onBrokenCallbacks.length;
1055
+ resolution.onBroken(callback);
1056
+ if (this.session.onBrokenCallbacks[endIndex] === callback) delete this.session.onBrokenCallbacks[endIndex];
1057
+ else delete this.session.onBrokenCallbacks[i];
1058
+ }
1059
+ this.onBrokenRegistrations = void 0;
1060
+ }
1061
+ if (this.activePull) {
1062
+ this.activePull.resolve();
1063
+ this.activePull = void 0;
1064
+ }
1065
+ }
1066
+ async awaitResolution() {
1067
+ if (!this.activePull) {
1068
+ this.session.sendPull(this.importId);
1069
+ this.activePull = Promise.withResolvers();
1070
+ }
1071
+ await this.activePull.promise;
1072
+ return this.resolution.pull();
1073
+ }
1074
+ dispose() {
1075
+ if (this.resolution) this.resolution.dispose();
1076
+ else {
1077
+ this.abort(/* @__PURE__ */ new Error("RPC was canceled because the RpcPromise was disposed."));
1078
+ this.sendRelease();
1079
+ }
1080
+ }
1081
+ abort(error) {
1082
+ if (!this.resolution) {
1083
+ this.resolution = new ErrorStubHook(error);
1084
+ if (this.activePull) {
1085
+ this.activePull.reject(error);
1086
+ this.activePull = void 0;
1087
+ }
1088
+ this.onBrokenRegistrations = void 0;
1089
+ }
1090
+ }
1091
+ onBroken(callback) {
1092
+ if (this.resolution) this.resolution.onBroken(callback);
1093
+ else {
1094
+ let index = this.session.onBrokenCallbacks.length;
1095
+ this.session.onBrokenCallbacks.push(callback);
1096
+ if (!this.onBrokenRegistrations) this.onBrokenRegistrations = [];
1097
+ this.onBrokenRegistrations.push(index);
1098
+ }
1099
+ }
1100
+ sendRelease() {
1101
+ if (this.remoteRefcount > 0) {
1102
+ this.session.sendRelease(this.importId, this.remoteRefcount);
1103
+ this.remoteRefcount = 0;
1104
+ }
1105
+ }
1106
+ };
1107
+ var RpcImportHook = class _RpcImportHook extends StubHook {
1108
+ constructor(isPromise, entry) {
1109
+ super();
1110
+ this.isPromise = isPromise;
1111
+ ++entry.localRefcount;
1112
+ this.entry = entry;
1113
+ }
1114
+ entry;
1115
+ collectPath(path) {
1116
+ return this;
1117
+ }
1118
+ getEntry() {
1119
+ if (this.entry) return this.entry;
1120
+ else throw new Error("This RpcImportHook was already disposed.");
1121
+ }
1122
+ call(path, args) {
1123
+ let entry = this.getEntry();
1124
+ if (entry.resolution) return entry.resolution.call(path, args);
1125
+ else return entry.session.sendCall(entry.importId, path, args);
1126
+ }
1127
+ map(path, captures, instructions) {
1128
+ let entry;
1129
+ try {
1130
+ entry = this.getEntry();
1131
+ } catch (err) {
1132
+ for (let cap of captures) cap.dispose();
1133
+ throw err;
1134
+ }
1135
+ if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1136
+ else return entry.session.sendMap(entry.importId, path, captures, instructions);
1137
+ }
1138
+ get(path) {
1139
+ let entry = this.getEntry();
1140
+ if (entry.resolution) return entry.resolution.get(path);
1141
+ else return entry.session.sendCall(entry.importId, path);
1142
+ }
1143
+ dup() {
1144
+ return new _RpcImportHook(false, this.getEntry());
1145
+ }
1146
+ pull() {
1147
+ let entry = this.getEntry();
1148
+ if (!this.isPromise) throw new Error("Can't pull this hook because it's not a promise hook.");
1149
+ if (entry.resolution) return entry.resolution.pull();
1150
+ return entry.awaitResolution();
1151
+ }
1152
+ ignoreUnhandledRejections() {}
1153
+ dispose() {
1154
+ let entry = this.entry;
1155
+ this.entry = void 0;
1156
+ if (entry) {
1157
+ if (--entry.localRefcount === 0) entry.dispose();
1158
+ }
1159
+ }
1160
+ onBroken(callback) {
1161
+ if (this.entry) this.entry.onBroken(callback);
1162
+ }
1163
+ };
1164
+ var RpcMainHook = class extends RpcImportHook {
1165
+ session;
1166
+ constructor(entry) {
1167
+ super(false, entry);
1168
+ this.session = entry.session;
1169
+ }
1170
+ dispose() {
1171
+ if (this.session) {
1172
+ let session = this.session;
1173
+ this.session = void 0;
1174
+ session.shutdown();
1175
+ }
1176
+ }
1177
+ };
1178
+ var RpcSessionImpl = class {
1179
+ constructor(transport, mainHook, options) {
1180
+ this.transport = transport;
1181
+ this.options = options;
1182
+ this.exports.push({
1183
+ hook: mainHook,
1184
+ refcount: 1
1185
+ });
1186
+ this.imports.push(new ImportTableEntry(this, 0, false));
1187
+ let rejectFunc;
1188
+ let abortPromise = new Promise((resolve, reject) => {
1189
+ rejectFunc = reject;
1190
+ });
1191
+ this.cancelReadLoop = rejectFunc;
1192
+ this.readLoop(abortPromise).catch((err) => this.abort(err));
1193
+ }
1194
+ exports = [];
1195
+ reverseExports = /* @__PURE__ */ new Map();
1196
+ imports = [];
1197
+ abortReason;
1198
+ cancelReadLoop;
1199
+ nextExportId = -1;
1200
+ onBatchDone;
1201
+ pullCount = 0;
1202
+ onBrokenCallbacks = [];
1203
+ getMainImport() {
1204
+ return new RpcMainHook(this.imports[0]);
1205
+ }
1206
+ shutdown() {
1207
+ this.abort(/* @__PURE__ */ new Error("RPC session was shut down by disposing the main stub"), false);
1208
+ }
1209
+ exportStub(hook) {
1210
+ if (this.abortReason) throw this.abortReason;
1211
+ let existingExportId = this.reverseExports.get(hook);
1212
+ if (existingExportId !== void 0) {
1213
+ ++this.exports[existingExportId].refcount;
1214
+ return existingExportId;
1215
+ } else {
1216
+ let exportId = this.nextExportId--;
1217
+ this.exports[exportId] = {
1218
+ hook,
1219
+ refcount: 1
1220
+ };
1221
+ this.reverseExports.set(hook, exportId);
1222
+ return exportId;
1223
+ }
1224
+ }
1225
+ exportPromise(hook) {
1226
+ if (this.abortReason) throw this.abortReason;
1227
+ let exportId = this.nextExportId--;
1228
+ this.exports[exportId] = {
1229
+ hook,
1230
+ refcount: 1
1231
+ };
1232
+ this.reverseExports.set(hook, exportId);
1233
+ this.ensureResolvingExport(exportId);
1234
+ return exportId;
1235
+ }
1236
+ unexport(ids) {
1237
+ for (let id of ids) this.releaseExport(id, 1);
1238
+ }
1239
+ releaseExport(exportId, refcount) {
1240
+ let entry = this.exports[exportId];
1241
+ if (!entry) throw new Error(`no such export ID: ${exportId}`);
1242
+ if (entry.refcount < refcount) throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);
1243
+ entry.refcount -= refcount;
1244
+ if (entry.refcount === 0) {
1245
+ delete this.exports[exportId];
1246
+ this.reverseExports.delete(entry.hook);
1247
+ entry.hook.dispose();
1248
+ }
1249
+ }
1250
+ onSendError(error) {
1251
+ if (this.options.onSendError) return this.options.onSendError(error);
1252
+ }
1253
+ ensureResolvingExport(exportId) {
1254
+ let exp = this.exports[exportId];
1255
+ if (!exp) throw new Error(`no such export ID: ${exportId}`);
1256
+ if (!exp.pull) {
1257
+ let resolve = async () => {
1258
+ let hook = exp.hook;
1259
+ for (;;) {
1260
+ let payload = await hook.pull();
1261
+ if (payload.value instanceof RpcStub) {
1262
+ let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);
1263
+ if (pathIfPromise && pathIfPromise.length == 0) {
1264
+ if (this.getImport(hook) === void 0) {
1265
+ hook = inner;
1266
+ continue;
1267
+ }
1268
+ }
1269
+ }
1270
+ return payload;
1271
+ }
1272
+ };
1273
+ ++this.pullCount;
1274
+ exp.pull = resolve().then((payload) => {
1275
+ let value = Devaluator.devaluate(payload.value, void 0, this, payload);
1276
+ this.send([
1277
+ "resolve",
1278
+ exportId,
1279
+ value
1280
+ ]);
1281
+ }, (error) => {
1282
+ this.send([
1283
+ "reject",
1284
+ exportId,
1285
+ Devaluator.devaluate(error, void 0, this)
1286
+ ]);
1287
+ }).catch((error) => {
1288
+ try {
1289
+ this.send([
1290
+ "reject",
1291
+ exportId,
1292
+ Devaluator.devaluate(error, void 0, this)
1293
+ ]);
1294
+ } catch (error2) {
1295
+ this.abort(error2);
1296
+ }
1297
+ }).finally(() => {
1298
+ if (--this.pullCount === 0) {
1299
+ if (this.onBatchDone) this.onBatchDone.resolve();
1300
+ }
1301
+ });
1302
+ }
1303
+ }
1304
+ getImport(hook) {
1305
+ if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;
1306
+ else return;
1307
+ }
1308
+ importStub(idx) {
1309
+ if (this.abortReason) throw this.abortReason;
1310
+ let entry = this.imports[idx];
1311
+ if (!entry) {
1312
+ entry = new ImportTableEntry(this, idx, false);
1313
+ this.imports[idx] = entry;
1314
+ }
1315
+ return new RpcImportHook(false, entry);
1316
+ }
1317
+ importPromise(idx) {
1318
+ if (this.abortReason) throw this.abortReason;
1319
+ if (this.imports[idx]) return new ErrorStubHook(/* @__PURE__ */ new Error("Bug in RPC system: The peer sent a promise reusing an existing export ID."));
1320
+ let entry = new ImportTableEntry(this, idx, true);
1321
+ this.imports[idx] = entry;
1322
+ return new RpcImportHook(true, entry);
1323
+ }
1324
+ getExport(idx) {
1325
+ return this.exports[idx]?.hook;
1326
+ }
1327
+ send(msg) {
1328
+ if (this.abortReason !== void 0) return;
1329
+ let msgText;
1330
+ try {
1331
+ msgText = JSON.stringify(msg);
1332
+ } catch (err) {
1333
+ try {
1334
+ this.abort(err);
1335
+ } catch (err2) {}
1336
+ throw err;
1337
+ }
1338
+ this.transport.send(msgText).catch((err) => this.abort(err, false));
1339
+ }
1340
+ sendCall(id, path, args) {
1341
+ if (this.abortReason) throw this.abortReason;
1342
+ let value = [
1343
+ "pipeline",
1344
+ id,
1345
+ path
1346
+ ];
1347
+ if (args) {
1348
+ let devalue = Devaluator.devaluate(args.value, void 0, this, args);
1349
+ value.push(devalue[0]);
1350
+ }
1351
+ this.send(["push", value]);
1352
+ let entry = new ImportTableEntry(this, this.imports.length, false);
1353
+ this.imports.push(entry);
1354
+ return new RpcImportHook(true, entry);
1355
+ }
1356
+ sendMap(id, path, captures, instructions) {
1357
+ if (this.abortReason) {
1358
+ for (let cap of captures) cap.dispose();
1359
+ throw this.abortReason;
1360
+ }
1361
+ let value = [
1362
+ "remap",
1363
+ id,
1364
+ path,
1365
+ captures.map((hook) => {
1366
+ let importId = this.getImport(hook);
1367
+ if (importId !== void 0) return ["import", importId];
1368
+ else return ["export", this.exportStub(hook)];
1369
+ }),
1370
+ instructions
1371
+ ];
1372
+ this.send(["push", value]);
1373
+ let entry = new ImportTableEntry(this, this.imports.length, false);
1374
+ this.imports.push(entry);
1375
+ return new RpcImportHook(true, entry);
1376
+ }
1377
+ sendPull(id) {
1378
+ if (this.abortReason) throw this.abortReason;
1379
+ this.send(["pull", id]);
1380
+ }
1381
+ sendRelease(id, remoteRefcount) {
1382
+ if (this.abortReason) return;
1383
+ this.send([
1384
+ "release",
1385
+ id,
1386
+ remoteRefcount
1387
+ ]);
1388
+ delete this.imports[id];
1389
+ }
1390
+ abort(error, trySendAbortMessage = true) {
1391
+ if (this.abortReason !== void 0) return;
1392
+ this.cancelReadLoop(error);
1393
+ if (trySendAbortMessage) try {
1394
+ this.transport.send(JSON.stringify(["abort", Devaluator.devaluate(error, void 0, this)])).catch((err) => {});
1395
+ } catch (err) {}
1396
+ if (error === void 0) error = "undefined";
1397
+ this.abortReason = error;
1398
+ if (this.onBatchDone) this.onBatchDone.reject(error);
1399
+ if (this.transport.abort) try {
1400
+ this.transport.abort(error);
1401
+ } catch (err) {
1402
+ Promise.resolve(err);
1403
+ }
1404
+ for (let i in this.onBrokenCallbacks) try {
1405
+ this.onBrokenCallbacks[i](error);
1406
+ } catch (err) {
1407
+ Promise.resolve(err);
1408
+ }
1409
+ for (let i in this.imports) this.imports[i].abort(error);
1410
+ for (let i in this.exports) this.exports[i].hook.dispose();
1411
+ }
1412
+ async readLoop(abortPromise) {
1413
+ while (!this.abortReason) {
1414
+ let msg = JSON.parse(await Promise.race([this.transport.receive(), abortPromise]));
1415
+ if (this.abortReason) break;
1416
+ if (msg instanceof Array) switch (msg[0]) {
1417
+ case "push":
1418
+ if (msg.length > 1) {
1419
+ let hook = new PayloadStubHook(new Evaluator(this).evaluate(msg[1]));
1420
+ hook.ignoreUnhandledRejections();
1421
+ this.exports.push({
1422
+ hook,
1423
+ refcount: 1
1424
+ });
1425
+ continue;
1426
+ }
1427
+ break;
1428
+ case "pull": {
1429
+ let exportId = msg[1];
1430
+ if (typeof exportId == "number") {
1431
+ this.ensureResolvingExport(exportId);
1432
+ continue;
1433
+ }
1434
+ break;
1435
+ }
1436
+ case "resolve":
1437
+ case "reject": {
1438
+ let importId = msg[1];
1439
+ if (typeof importId == "number" && msg.length > 2) {
1440
+ let imp = this.imports[importId];
1441
+ if (imp) if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this).evaluate(msg[2])));
1442
+ else {
1443
+ let payload = new Evaluator(this).evaluate(msg[2]);
1444
+ payload.dispose();
1445
+ imp.resolve(new ErrorStubHook(payload.value));
1446
+ }
1447
+ else if (msg[0] == "resolve") new Evaluator(this).evaluate(msg[2]).dispose();
1448
+ continue;
1449
+ }
1450
+ break;
1451
+ }
1452
+ case "release": {
1453
+ let exportId = msg[1];
1454
+ let refcount = msg[2];
1455
+ if (typeof exportId == "number" && typeof refcount == "number") {
1456
+ this.releaseExport(exportId, refcount);
1457
+ continue;
1458
+ }
1459
+ break;
1460
+ }
1461
+ case "abort": {
1462
+ let payload = new Evaluator(this).evaluate(msg[1]);
1463
+ payload.dispose();
1464
+ this.abort(payload, false);
1465
+ break;
1466
+ }
1467
+ }
1468
+ throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);
1469
+ }
1470
+ }
1471
+ async drain() {
1472
+ if (this.abortReason) throw this.abortReason;
1473
+ if (this.pullCount > 0) {
1474
+ let { promise, resolve, reject } = Promise.withResolvers();
1475
+ this.onBatchDone = {
1476
+ resolve,
1477
+ reject
1478
+ };
1479
+ await promise;
1480
+ }
1481
+ }
1482
+ getStats() {
1483
+ let result = {
1484
+ imports: 0,
1485
+ exports: 0
1486
+ };
1487
+ for (let i in this.imports) ++result.imports;
1488
+ for (let i in this.exports) ++result.exports;
1489
+ return result;
1490
+ }
1491
+ };
1492
+ var RpcSession = class {
1493
+ #session;
1494
+ #mainStub;
1495
+ constructor(transport, localMain, options = {}) {
1496
+ let mainHook;
1497
+ if (localMain) mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));
1498
+ else mainHook = new ErrorStubHook(/* @__PURE__ */ new Error("This connection has no main object."));
1499
+ this.#session = new RpcSessionImpl(transport, mainHook, options);
1500
+ this.#mainStub = new RpcStub(this.#session.getMainImport());
1501
+ }
1502
+ getRemoteMain() {
1503
+ return this.#mainStub;
1504
+ }
1505
+ getStats() {
1506
+ return this.#session.getStats();
1507
+ }
1508
+ drain() {
1509
+ return this.#session.drain();
1510
+ }
1511
+ };
1512
+ function newWebSocketRpcSession(webSocket, localMain, options) {
1513
+ if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
1514
+ return new RpcSession(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
1515
+ }
1516
+ function newWorkersWebSocketRpcResponse(request, localMain, options) {
1517
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return new Response("This endpoint only accepts WebSocket requests.", { status: 400 });
1518
+ let pair = new WebSocketPair();
1519
+ let server = pair[0];
1520
+ server.accept();
1521
+ newWebSocketRpcSession(server, localMain, options);
1522
+ return new Response(null, {
1523
+ status: 101,
1524
+ webSocket: pair[1]
1525
+ });
1526
+ }
1527
+ var WebSocketTransport = class {
1528
+ constructor(webSocket) {
1529
+ this.#webSocket = webSocket;
1530
+ if (webSocket.readyState === WebSocket.CONNECTING) {
1531
+ this.#sendQueue = [];
1532
+ webSocket.addEventListener("open", (event) => {
1533
+ try {
1534
+ for (let message of this.#sendQueue) webSocket.send(message);
1535
+ } catch (err) {
1536
+ this.#receivedError(err);
1537
+ }
1538
+ this.#sendQueue = void 0;
1539
+ });
1540
+ }
1541
+ webSocket.addEventListener("message", (event) => {
1542
+ if (this.#error);
1543
+ else if (typeof event.data === "string") if (this.#receiveResolver) {
1544
+ this.#receiveResolver(event.data);
1545
+ this.#receiveResolver = void 0;
1546
+ this.#receiveRejecter = void 0;
1547
+ } else this.#receiveQueue.push(event.data);
1548
+ else this.#receivedError(/* @__PURE__ */ new TypeError("Received non-string message from WebSocket."));
1549
+ });
1550
+ webSocket.addEventListener("close", (event) => {
1551
+ this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));
1552
+ });
1553
+ webSocket.addEventListener("error", (event) => {
1554
+ this.#receivedError(/* @__PURE__ */ new Error(`WebSocket connection failed.`));
1555
+ });
1556
+ }
1557
+ #webSocket;
1558
+ #sendQueue;
1559
+ #receiveResolver;
1560
+ #receiveRejecter;
1561
+ #receiveQueue = [];
1562
+ #error;
1563
+ async send(message) {
1564
+ if (this.#sendQueue === void 0) this.#webSocket.send(message);
1565
+ else this.#sendQueue.push(message);
1566
+ }
1567
+ async receive() {
1568
+ if (this.#receiveQueue.length > 0) return this.#receiveQueue.shift();
1569
+ else if (this.#error) throw this.#error;
1570
+ else return new Promise((resolve, reject) => {
1571
+ this.#receiveResolver = resolve;
1572
+ this.#receiveRejecter = reject;
1573
+ });
1574
+ }
1575
+ abort(reason) {
1576
+ let message;
1577
+ if (reason instanceof Error) message = reason.message;
1578
+ else message = `${reason}`;
1579
+ this.#webSocket.close(3e3, message);
1580
+ if (!this.#error) this.#error = reason;
1581
+ }
1582
+ #receivedError(reason) {
1583
+ if (!this.#error) {
1584
+ this.#error = reason;
1585
+ if (this.#receiveRejecter) {
1586
+ this.#receiveRejecter(reason);
1587
+ this.#receiveResolver = void 0;
1588
+ this.#receiveRejecter = void 0;
1589
+ }
1590
+ }
1591
+ }
1592
+ };
1593
+ var BatchServerTransport = class {
1594
+ constructor(batch) {
1595
+ this.#batchToReceive = batch;
1596
+ }
1597
+ #batchToSend = [];
1598
+ #batchToReceive;
1599
+ #allReceived = Promise.withResolvers();
1600
+ async send(message) {
1601
+ this.#batchToSend.push(message);
1602
+ }
1603
+ async receive() {
1604
+ let msg = this.#batchToReceive.shift();
1605
+ if (msg !== void 0) return msg;
1606
+ else {
1607
+ this.#allReceived.resolve();
1608
+ return new Promise((r) => {});
1609
+ }
1610
+ }
1611
+ abort(reason) {
1612
+ this.#allReceived.reject(reason);
1613
+ }
1614
+ whenAllReceived() {
1615
+ return this.#allReceived.promise;
1616
+ }
1617
+ getResponseBody() {
1618
+ return this.#batchToSend.join("\n");
1619
+ }
1620
+ };
1621
+ async function newHttpBatchRpcResponse(request, localMain, options) {
1622
+ if (request.method !== "POST") return new Response("This endpoint only accepts POST requests.", { status: 405 });
1623
+ let body = await request.text();
1624
+ let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
1625
+ let rpc = new RpcSession(transport, localMain, options);
1626
+ await transport.whenAllReceived();
1627
+ await rpc.drain();
1628
+ return new Response(transport.getResponseBody());
1629
+ }
1630
+ var currentMapBuilder;
1631
+ var MapBuilder = class {
1632
+ context;
1633
+ captureMap = /* @__PURE__ */ new Map();
1634
+ instructions = [];
1635
+ constructor(subject, path) {
1636
+ if (currentMapBuilder) this.context = {
1637
+ parent: currentMapBuilder,
1638
+ captures: [],
1639
+ subject: currentMapBuilder.capture(subject),
1640
+ path
1641
+ };
1642
+ else this.context = {
1643
+ parent: void 0,
1644
+ captures: [],
1645
+ subject,
1646
+ path
1647
+ };
1648
+ currentMapBuilder = this;
1649
+ }
1650
+ unregister() {
1651
+ currentMapBuilder = this.context.parent;
1652
+ }
1653
+ makeInput() {
1654
+ return new MapVariableHook(this, 0);
1655
+ }
1656
+ makeOutput(result) {
1657
+ let devalued;
1658
+ try {
1659
+ devalued = Devaluator.devaluate(result.value, void 0, this, result);
1660
+ } finally {
1661
+ result.dispose();
1662
+ }
1663
+ this.instructions.push(devalued);
1664
+ if (this.context.parent) {
1665
+ this.context.parent.instructions.push([
1666
+ "remap",
1667
+ this.context.subject,
1668
+ this.context.path,
1669
+ this.context.captures.map((cap) => ["import", cap]),
1670
+ this.instructions
1671
+ ]);
1672
+ return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);
1673
+ } else return this.context.subject.map(this.context.path, this.context.captures, this.instructions);
1674
+ }
1675
+ pushCall(hook, path, params) {
1676
+ let devalued = Devaluator.devaluate(params.value, void 0, this, params);
1677
+ devalued = devalued[0];
1678
+ let subject = this.capture(hook.dup());
1679
+ this.instructions.push([
1680
+ "pipeline",
1681
+ subject,
1682
+ path,
1683
+ devalued
1684
+ ]);
1685
+ return new MapVariableHook(this, this.instructions.length);
1686
+ }
1687
+ pushGet(hook, path) {
1688
+ let subject = this.capture(hook.dup());
1689
+ this.instructions.push([
1690
+ "pipeline",
1691
+ subject,
1692
+ path
1693
+ ]);
1694
+ return new MapVariableHook(this, this.instructions.length);
1695
+ }
1696
+ capture(hook) {
1697
+ if (hook instanceof MapVariableHook && hook.mapper === this) return hook.idx;
1698
+ let result = this.captureMap.get(hook);
1699
+ if (result === void 0) {
1700
+ if (this.context.parent) {
1701
+ let parentIdx = this.context.parent.capture(hook);
1702
+ this.context.captures.push(parentIdx);
1703
+ } else this.context.captures.push(hook);
1704
+ result = -this.context.captures.length;
1705
+ this.captureMap.set(hook, result);
1706
+ }
1707
+ return result;
1708
+ }
1709
+ exportStub(hook) {
1710
+ throw new Error("Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.");
1711
+ }
1712
+ exportPromise(hook) {
1713
+ return this.exportStub(hook);
1714
+ }
1715
+ getImport(hook) {
1716
+ return this.capture(hook);
1717
+ }
1718
+ unexport(ids) {}
1719
+ onSendError(error) {}
1720
+ };
1721
+ mapImpl.sendMap = (hook, path, func) => {
1722
+ let builder = new MapBuilder(hook, path);
1723
+ let result;
1724
+ try {
1725
+ result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {
1726
+ return func(new RpcPromise(builder.makeInput(), []));
1727
+ }));
1728
+ } finally {
1729
+ builder.unregister();
1730
+ }
1731
+ if (result instanceof Promise) {
1732
+ result.catch((err) => {});
1733
+ throw new Error("RPC map() callbacks cannot be async.");
1734
+ }
1735
+ return new RpcPromise(builder.makeOutput(result), []);
1736
+ };
1737
+ function throwMapperBuilderUseError() {
1738
+ throw new Error("Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.");
1739
+ }
1740
+ var MapVariableHook = class extends StubHook {
1741
+ constructor(mapper, idx) {
1742
+ super();
1743
+ this.mapper = mapper;
1744
+ this.idx = idx;
1745
+ }
1746
+ dup() {
1747
+ return this;
1748
+ }
1749
+ dispose() {}
1750
+ get(path) {
1751
+ if (path.length == 0) return this;
1752
+ else if (currentMapBuilder) return currentMapBuilder.pushGet(this, path);
1753
+ else throwMapperBuilderUseError();
1754
+ }
1755
+ call(path, args) {
1756
+ throwMapperBuilderUseError();
1757
+ }
1758
+ map(path, captures, instructions) {
1759
+ throwMapperBuilderUseError();
1760
+ }
1761
+ pull() {
1762
+ throwMapperBuilderUseError();
1763
+ }
1764
+ ignoreUnhandledRejections() {}
1765
+ onBroken(callback) {
1766
+ throwMapperBuilderUseError();
1767
+ }
1768
+ };
1769
+ var MapApplicator = class {
1770
+ constructor(captures, input) {
1771
+ this.captures = captures;
1772
+ this.variables = [input];
1773
+ }
1774
+ variables;
1775
+ dispose() {
1776
+ for (let variable of this.variables) variable.dispose();
1777
+ }
1778
+ apply(instructions) {
1779
+ try {
1780
+ if (instructions.length < 1) throw new Error("Invalid empty mapper function.");
1781
+ for (let instruction of instructions.slice(0, -1)) {
1782
+ let payload = new Evaluator(this).evaluateCopy(instruction);
1783
+ if (payload.value instanceof RpcStub) {
1784
+ let hook = unwrapStubNoProperties(payload.value);
1785
+ if (hook) {
1786
+ this.variables.push(hook);
1787
+ continue;
1788
+ }
1789
+ }
1790
+ this.variables.push(new PayloadStubHook(payload));
1791
+ }
1792
+ return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);
1793
+ } finally {
1794
+ for (let variable of this.variables) variable.dispose();
1795
+ }
1796
+ }
1797
+ importStub(idx) {
1798
+ throw new Error("A mapper function cannot refer to exports.");
1799
+ }
1800
+ importPromise(idx) {
1801
+ return this.importStub(idx);
1802
+ }
1803
+ getExport(idx) {
1804
+ if (idx < 0) return this.captures[-idx - 1];
1805
+ else return this.variables[idx];
1806
+ }
1807
+ };
1808
+ function applyMapToElement(input, parent, owner, captures, instructions) {
1809
+ let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
1810
+ try {
1811
+ return mapper.apply(instructions);
1812
+ } finally {
1813
+ mapper.dispose();
1814
+ }
1815
+ }
1816
+ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
1817
+ try {
1818
+ let result;
1819
+ if (input instanceof RpcPromise) throw new Error("applyMap() can't be called on RpcPromise");
1820
+ else if (input instanceof Array) {
1821
+ let payloads = [];
1822
+ try {
1823
+ for (let elem of input) payloads.push(applyMapToElement(elem, input, owner, captures, instructions));
1824
+ } catch (err) {
1825
+ for (let payload of payloads) payload.dispose();
1826
+ throw err;
1827
+ }
1828
+ result = RpcPayload.fromArray(payloads);
1829
+ } else if (input === null || input === void 0) result = RpcPayload.fromAppReturn(input);
1830
+ else result = applyMapToElement(input, parent, owner, captures, instructions);
1831
+ return new PayloadStubHook(result);
1832
+ } finally {
1833
+ for (let cap of captures) cap.dispose();
1834
+ }
1835
+ };
1836
+ async function newWorkersRpcResponse(request, localMain) {
1837
+ if (request.method === "POST") {
1838
+ let response = await newHttpBatchRpcResponse(request, localMain);
1839
+ response.headers.set("Access-Control-Allow-Origin", "*");
1840
+ return response;
1841
+ } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain);
1842
+ else return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });
1843
+ }
1844
+
1845
+ //#endregion
1846
+ //#region workers/remote-binding-proxy.ts
1847
+ var BindingNotFoundError = class extends Error {
1848
+ constructor(name) {
1849
+ super(`Binding ${name ? `"${name}"` : ""} not found`);
1850
+ }
1851
+ };
1852
+ /**
1853
+ * For most bindings, we expose them as
1854
+ * - RPC stubs directly to capnweb, or
1855
+ * - HTTP based fetchers
1856
+ * However, there are some special cases:
1857
+ * - SendEmail bindings need to take EmailMessage as their first parameter,
1858
+ * which is not serialisable. As such, we reconstruct it before sending it
1859
+ * on to the binding. See packages/miniflare/src/workers/email/email.worker.ts
1860
+ * - Dispatch Namespace bindings have a synchronous .get() method. Since we
1861
+ * can't emulate that over an async boundary, we mock it locally and _actually_
1862
+ * perform the .get() remotely at the first appropriate async point. See
1863
+ * packages/miniflare/src/workers/dispatch-namespace/dispatch-namespace.worker.ts
1864
+ *
1865
+ * getExposedJSRPCBinding() and getExposedFetcher() perform the logic for figuring out
1866
+ * which binding is being accessed, dependending on the request. Note: Both have logic
1867
+ * for dispatch namespaces, because dispatch namespaces can use both fetch or RPC depending
1868
+ * on context.
1869
+ */
1870
+ function getExposedJSRPCBinding(request, env) {
1871
+ const url = new URL(request.url);
1872
+ const bindingName = url.searchParams.get("MF-Binding");
1873
+ if (!bindingName) throw new BindingNotFoundError();
1874
+ const targetBinding = env[bindingName];
1875
+ if (!targetBinding) throw new BindingNotFoundError(bindingName);
1876
+ if (targetBinding.constructor.name === "SendEmail") return { async send(e) {
1877
+ const message = new EmailMessage(e.from, e.to, e["EmailMessage::raw"]);
1878
+ return targetBinding.send(message);
1879
+ } };
1880
+ if (url.searchParams.has("MF-Dispatch-Namespace-Options")) {
1881
+ const { name, args, options } = JSON.parse(url.searchParams.get("MF-Dispatch-Namespace-Options"));
1882
+ return targetBinding.get(name, args, options);
1883
+ }
1884
+ return targetBinding;
1885
+ }
1886
+ function getExposedFetcher(request, env) {
1887
+ const bindingName = request.headers.get("MF-Binding");
1888
+ if (!bindingName) throw new BindingNotFoundError();
1889
+ const targetBinding = env[bindingName];
1890
+ if (!targetBinding) throw new BindingNotFoundError(bindingName);
1891
+ const dispatchNamespaceOptions = request.headers.get("MF-Dispatch-Namespace-Options");
1892
+ if (dispatchNamespaceOptions) {
1893
+ const { name, args, options } = JSON.parse(dispatchNamespaceOptions);
1894
+ return targetBinding.get(name, args, options);
1895
+ }
1896
+ return targetBinding;
1897
+ }
1898
+ /**
1899
+ * This Worker can proxy two types of remote binding:
1900
+ * 1. "raw" bindings, where this Worker has been configured to pass through the raw
1901
+ * fetch from a local workerd instance to the relevant binding
1902
+ * 2. JSRPC bindings, where this Worker uses capnweb to proxy RPC
1903
+ * communication in userland. This is always over a WebSocket connection
1904
+ */
1905
+ function isJSRPCBinding(request) {
1906
+ const url = new URL(request.url);
1907
+ return request.headers.has("Upgrade") && url.searchParams.has("MF-Binding");
1908
+ }
1909
+ var remote_binding_proxy_default = { async fetch(request, env) {
1910
+ try {
1911
+ if (isJSRPCBinding(request)) return newWorkersRpcResponse(request, getExposedJSRPCBinding(request, env));
1912
+ else {
1913
+ const fetcher = getExposedFetcher(request, env);
1914
+ const originalHeaders = new Headers();
1915
+ for (const [name, value] of request.headers) if (name.startsWith("mf-header-")) originalHeaders.set(name.slice(10), value);
1916
+ else if (name === "upgrade") originalHeaders.set(name, value);
1917
+ return fetcher.fetch(request.headers.get("MF-URL") ?? "http://example.com", new Request(request, {
1918
+ redirect: "manual",
1919
+ headers: originalHeaders
1920
+ }));
1921
+ }
1922
+ } catch (e) {
1923
+ if (e instanceof BindingNotFoundError) return new Response(e.message, { status: 400 });
1924
+ return new Response(e.message, { status: 500 });
1925
+ }
1926
+ } };
1927
+
1928
+ //#endregion
1929
+ export { remote_binding_proxy_default as default };