@syntropika/tembra-sdk 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.js +36 -2
- package/dist/embedded.js +1 -1
- package/dist/host.js +36 -2
- package/dist/node.js +36 -2
- package/dist/runtime/calls.d.ts +5 -0
- package/package.json +3 -3
- package/src/embedded.ts +9 -1
- package/src/runtime/calls.ts +41 -2
package/dist/browser.js
CHANGED
|
@@ -1548,9 +1548,43 @@ function isContext(value) {
|
|
|
1548
1548
|
// src/runtime/calls.ts
|
|
1549
1549
|
class Calls {
|
|
1550
1550
|
session;
|
|
1551
|
+
#interrupted = new Set;
|
|
1551
1552
|
constructor(session) {
|
|
1552
1553
|
this.session = session;
|
|
1553
1554
|
}
|
|
1555
|
+
interrupt() {
|
|
1556
|
+
const error = new TembraError({
|
|
1557
|
+
code: Code.Closed,
|
|
1558
|
+
reason: "javascript",
|
|
1559
|
+
message: "JavaScript execution was interrupted"
|
|
1560
|
+
});
|
|
1561
|
+
for (const reject of this.#interrupted)
|
|
1562
|
+
reject(error);
|
|
1563
|
+
this.#interrupted.clear();
|
|
1564
|
+
}
|
|
1565
|
+
async execute(operation) {
|
|
1566
|
+
let reject;
|
|
1567
|
+
let failure;
|
|
1568
|
+
const interrupted = new Promise((_, fail) => {
|
|
1569
|
+
reject = (error) => {
|
|
1570
|
+
failure = error;
|
|
1571
|
+
fail(error);
|
|
1572
|
+
};
|
|
1573
|
+
});
|
|
1574
|
+
this.#interrupted.add(reject);
|
|
1575
|
+
try {
|
|
1576
|
+
return await Promise.race([
|
|
1577
|
+
Promise.resolve().then(() => {
|
|
1578
|
+
if (failure)
|
|
1579
|
+
throw failure;
|
|
1580
|
+
return operation();
|
|
1581
|
+
}),
|
|
1582
|
+
interrupted
|
|
1583
|
+
]);
|
|
1584
|
+
} finally {
|
|
1585
|
+
this.#interrupted.delete(reject);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1554
1588
|
signal(root) {
|
|
1555
1589
|
const session = this.session;
|
|
1556
1590
|
let controller = session.controllers.get(root);
|
|
@@ -1621,7 +1655,7 @@ class Calls {
|
|
|
1621
1655
|
const handle = environment?.orb.definition.services?.[reference.address.service]?.methods[method];
|
|
1622
1656
|
if (!environment || !handle)
|
|
1623
1657
|
throw new TembraError(Errors.Gone.Implementation);
|
|
1624
|
-
return await handle(environment.value, entered, ...arguments_);
|
|
1658
|
+
return await this.execute(() => handle(environment.value, entered, ...arguments_));
|
|
1625
1659
|
} catch (error) {
|
|
1626
1660
|
outcome = Outcome.Error;
|
|
1627
1661
|
throw error;
|
|
@@ -1651,7 +1685,7 @@ class Calls {
|
|
|
1651
1685
|
...environment.object ? { object: environment.object.id } : {}
|
|
1652
1686
|
});
|
|
1653
1687
|
try {
|
|
1654
|
-
return await handle(new Context(session, ctx.root, invocation, ctx.frame));
|
|
1688
|
+
return await this.execute(() => handle(new Context(session, ctx.root, invocation, ctx.frame)));
|
|
1655
1689
|
} finally {
|
|
1656
1690
|
session.kernel.command(KernelOp.FinishCall, { call: invocation.id });
|
|
1657
1691
|
session.lifecycle.flush();
|
package/dist/embedded.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var l=Object.freeze({Invalid:"invalid",Unavailable:"unavailable",Released:"released",Gone:"gone",Expired:"expired",Cancelled:"cancelled",Forbidden:"forbidden",Conflict:"conflict",Unsupported:"unsupported",Closed:"closed",Exhausted:"exhausted"}),u=Object.freeze({ActivationBusy:"activation_busy",Address:"address",AlreadyCommitted:"already_committed",AmbiguousScope:"ambiguous_scope",ApiVersion:"api_version",Arguments:"arguments",AsyncFactory:"async_factory",AsyncState:"async_state",Bigint:"bigint",ByteResult:"byte_result",Call:"call",Callback:"callback",CleanupBusy:"cleanup_busy",Clock:"clock",Codec:"codec",Connection:"connection",Context:"context",Contribution:"contribution",CoordinationLimits:"coordination_limits",Deadline:"deadline",Dependency:"dependency",DependencyCycle:"dependency_cycle",DependencyService:"dependency_service",Disposing:"disposing",Driver:"driver",Duplicate:"duplicate",DuplicateContribution:"duplicate_contribution",DuplicateListener:"duplicate_listener",DuplicateResource:"duplicate_resource",DuplicateService:"duplicate_service",EffectResults:"effect_results",EffectsRunning:"effects_running",EngineEffect:"engine_effect",EventSource:"event_source",ExclusiveDependent:"exclusive_dependent",Executor:"executor",Orb:"orb",OrbGone:"orb_gone",OrbInstalled:"orb_installed",OrbScope:"orb_scope",Factory:"factory",FactoryExpired:"factory_expired",FrameSize:"frame_size",GateBusy:"gate_busy",GateOrb:"gate_orb",GateObject:"gate_object",Hook:"hook",HookDependency:"hook_dependency",Hooks:"hooks",HooksDisabled:"hooks_disabled",Host:"host",HostAddress:"host_address",HostResource:"host_resource",HostResourceReload:"host_resource_reload",Identities:"identities",Implementation:"implementation",Invocation:"invocation",Javascript:"javascript",JsonAccessor:"json_accessor",JsonCycle:"json_cycle",JsonNumber:"json_number",JsonSymbol:"json_symbol",JsonTag:"json_tag",JsonType:"json_type",JsonValue:"json_value",Lifetime:"lifetime",Linger:"linger",ListenerCallback:"listener_callback",LiveConsumer:"live_consumer",LiveReference:"live_reference",LocalValue:"local_value",Memory:"memory",Metadata:"metadata",MetadataSize:"metadata_size",Method:"method",MigrationGate:"migration_gate",MigrationRequired:"migration_required",MigrationValue:"migration_value",MissingHook:"missing_hook",MissingMethod:"missing_method",NativeEffect:"native_effect",NativeMethod:"native_method",NativeObject:"native_object",NativeService:"native_service",Next:"next",NextUsed:"next_used",NotReady:"not_ready",Object:"object",ObjectState:"object_state",ObservationSource:"observation_source",ObservationAdmitted:"observation_admitted",Opaque:"opaque",Operation:"operation",OperationOwner:"operation_owner",Owner:"owner",Payload:"payload",PendingRequests:"pending_requests",PrepareDeadline:"prepare_deadline",Priority:"priority",Program:"program",ProgramPhase:"program_phase",ProgramRunning:"program_running",Reference:"reference",ReloadAborted:"reload_aborted",ReloadDeadline:"reload_deadline",ReloadPreparing:"reload_preparing",ReloadRunning:"reload_running",ReloadTicket:"reload_ticket",RemoteOpaque:"remote_opaque",RemoteReferences:"remote_references",Request:"request",RequestIds:"request_ids",Requires:"requires",Resource:"resource",ResourceDependencies:"resource_dependencies",ResourceDependency:"resource_dependency",ResourceHost:"resource_host",ResourceInFactory:"resource_in_factory",ResourceState:"resource_state",ResourceVersion:"resource_version",Result:"result",RetainedVersions:"retained_versions",RevisionExhausted:"revision_exhausted",Root:"root",Route:"route",RpcFrame:"rpc_frame",RpcOperation:"rpc_operation",RpcRequest:"rpc_request",RustType:"rust_type",Scope:"scope",ScopeClosed:"scope_closed",ScopeOrb:"scope_orb",ScopeOwner:"scope_owner",ScopeResource:"scope_resource",Serialization:"serialization",Service:"service",ServiceGone:"service_gone",State:"state",StateCycle:"state_cycle",StateInitialized:"state_initialized",StateOwner:"state_owner",StateRevision:"state_revision",StateValidation:"state_validation",StateValue:"state_value",StateVersion:"state_version",Subscription:"subscription",SubscriptionBusy:"subscription_busy",SubscriptionIdle:"subscription_idle",SubscriptionQueue:"subscription_queue",SubscriptionSize:"subscription_size",SubscriptionsDisabled:"subscriptions_disabled",Superseded:"superseded",Task:"task",Telemetry:"telemetry",UndeclaredDependency:"undeclared_dependency",UndeclaredService:"undeclared_service",UnknownService:"unknown_service",UpgradeConflict:"upgrade_conflict",Utf8:"utf8",Value:"value",ValueGone:"value_gone",ValuesExhausted:"values_exhausted",Views:"views"}),G=Object.freeze({Referenced:"referenced",Host:"host"}),_=Object.freeze({Loading:"loading",Live:"live",Released:"released",Gone:"gone"}),D=Object.freeze({Prepared:"prepared",Committed:"committed",Aborted:"aborted"}),ie=Object.freeze({Observe:"observe",Transform:"transform",Decide:"decide"});var d=Object.freeze({ContextDerive:"context-derive",ContextValue:"context-value",ContextStats:"context-stats",Allocate:"allocate",ScopeRegister:"scope-register",ScopeExists:"scope-exists",ScopesForOwner:"scopes-for-owner",ScopesForOrb:"scopes-for-orb",ScopeAddResource:"scope-add-resource",ScopeActivate:"scope-activate",ScopesCleanup:"scopes-cleanup",ScopesReloadRegistered:"scopes-reload-registered",ScopesReload:"scopes-reload",ProgramRun:"program-run",ProgramNext:"program-next",ProgramCompleteStep:"program-complete-step",ProgramCommit:"program-commit",ProgramAbort:"program-abort",ProgramForget:"program-forget",Features:"features",Prepare:"prepare",Gate:"gate",GateOrbs:"gate-orbs",Commit:"commit",Abort:"abort",Orbs:"orbs",Orb:"orb",OrbNamed:"orb-named",NextDeadline:"next-deadline",Address:"address",Acquire:"acquire",Ready:"ready",Dependency:"dependency",Undepend:"undepend",Fail:"fail",Status:"status",Release:"release",Forget:"forget",Root:"root",CleanupRoot:"cleanup-root",RootPrincipal:"root-principal",CheckContext:"check-context",CheckRoot:"check-root",EndRoot:"end-root",CancelRoot:"cancel-root",BeginCall:"begin-call",BeginOperation:"begin-operation",BeginHookObservation:"begin-hook-observation",FinishCall:"finish-call",Invocation:"invocation",StateInit:"state-init",Snapshot:"snapshot",StateAdopt:"state-adopt",Task:"task",TaskRoot:"task-root",StopTask:"stop-task",FinishTask:"finish-task",Resource:"resource",ResourceOpened:"resource-opened",ResourceValue:"resource-value",CloseResource:"close-resource",ResourceClosed:"resource-closed",Disposed:"disposed",Tick:"tick",NextWake:"next-wake",NextIdle:"next-idle",Close:"close",FinishClose:"finish-close",Diagnostics:"diagnostics",Drain:"drain",Restrict:"restrict",Contribute:"contribute",ContributionOrdinal:"contribution-ordinal",HookPlan:"hook-plan",Listen:"listen",Subscribe:"subscribe",Enqueue:"enqueue",NextDelivery:"next-delivery",FinishDelivery:"finish-delivery",Unsubscribe:"unsubscribe"}),C=Object.freeze({Execute:"execute",CancelEffects:"cancel-effects",ProgramPrepared:"program-prepared",ProgramComplete:"program-complete",Dispose:"dispose",CloseResource:"close-resource",DropValue:"drop-value",CancelRoot:"cancel-root",CancelTask:"cancel-task",RetireOrb:"retire-orb",State:"state",SubscriptionFailed:"subscription-failed",DetachSubscription:"detach-subscription",Deliver:"deliver"}),j=Object.freeze({Stop:"stop",Open:"open",Close:"close",Restore:"restore",Prepare:"prepare",Validate:"validate",Initialize:"initialize",Migrate:"migrate",Adopt:"adopt",Start:"start",Drop:"drop"}),Ge=Object.freeze({Execute:"execute",Wait:"wait",Prepared:"prepared",Complete:"complete",Failed:"failed"}),Be=Object.freeze({Activate:"activate",Dispose:"dispose",CancelEffect:"cancel-effect",Effect:"effect",Invoke:"invoke",Contribute:"contribute"}),We=Object.freeze({Describe:"describe",Get:"get",Release:"release",Call:"call",Cancel:"cancel"}),$e=Object.freeze({State:"state"}),I=Object.freeze({Host:"host",Orb:"orb",Object:"object"}),S=Object.freeze({Declaring:"declaring",Prepared:"prepared",Live:"live",Closed:"closed"}),Qe=Object.freeze({Preparing:"preparing",Commit:"commit",Abort:"abort"}),ae=Object.freeze({Ok:"ok",Error:"error"}),K=Object.freeze({Bigint:"bigint",Bytes:"bytes",Object:"object"}),je=Object.freeze({Json:"tembra-json/1",MessagePack:"tembra-msgpack/1"});function f(e,t,n){return Object.freeze({code:e,reason:t,message:n})}var c=Object.freeze({Cancelled:Object.freeze({EngineEffect:f(l.Cancelled,u.EngineEffect,"The engine effect was cancelled"),Request:f(l.Cancelled,u.Request,"The request was cancelled"),Resource:f(l.Cancelled,u.Resource,"Resource opening was cancelled"),Root:f(l.Cancelled,u.Root,"The operation was cancelled"),Task:f(l.Cancelled,u.Task,"The task was cancelled")}),Closed:Object.freeze({Host:f(l.Closed,u.Host,"The host is closing")}),Conflict:Object.freeze({AlreadyCommitted:f(l.Conflict,u.AlreadyCommitted,"The replacement is already committed"),Codec:f(l.Conflict,u.Codec,"The Rust and JS host codecs must agree"),PrepareDeadline:f(l.Conflict,u.PrepareDeadline,"The preparation deadline expired"),ReloadRunning:f(l.Conflict,u.ReloadRunning,"A replacement is already running"),ReloadTicket:f(l.Conflict,u.ReloadTicket,"The replacement is no longer prepared")}),Exhausted:Object.freeze({FrameSize:f(l.Exhausted,u.FrameSize,"The frame exceeds the configured size limit"),PendingRequests:f(l.Exhausted,u.PendingRequests,"The pending request limit was reached"),RemoteReferences:f(l.Exhausted,u.RemoteReferences,"The remote reference limit was reached"),RequestIds:f(l.Exhausted,u.RequestIds,"Request identities are exhausted"),SubscriptionQueue:f(l.Exhausted,u.SubscriptionQueue,"The subscription queue is full")}),Expired:Object.freeze({Next:f(l.Expired,u.Next,"Continuation scope has ended")}),Forbidden:Object.freeze({Context:f(l.Forbidden,u.Context,"An issued context from this host is required"),HostResource:f(l.Forbidden,u.HostResource,"The host resource was not declared"),Method:f(l.Forbidden,u.Method,"The method is not allowed by this reference"),ObservationSource:f(l.Forbidden,u.ObservationSource,"Hook observation requires the original physical invocation"),Opaque:f(l.Forbidden,u.Opaque,"The resource is not available as an opaque local value"),Service:f(l.Forbidden,u.Service,"Access to this service is forbidden"),StateOwner:f(l.Forbidden,u.StateOwner,"Only the owning orb may change this state"),UndeclaredDependency:f(l.Forbidden,u.UndeclaredDependency,"The dependency was not declared"),UndeclaredService:f(l.Forbidden,u.UndeclaredService,"The service was not declared as a dependency")}),Gone:Object.freeze({Connection:f(l.Gone,u.Connection,"The connection is closed"),Contribution:f(l.Gone,u.Contribution,"The contribution is no longer available"),Implementation:f(l.Gone,u.Implementation,"The implementation is no longer available"),ListenerCallback:f(l.Gone,u.ListenerCallback,"The listener callback is no longer available"),Reference:f(l.Gone,u.Reference,"The reference is no longer available"),Resource:f(l.Gone,u.Resource,"The resource is no longer available"),Scope:f(l.Gone,u.Scope,"The declaration scope is no longer available"),State:f(l.Gone,u.State,"State owner is gone")}),Invalid:Object.freeze({Address:f(l.Invalid,u.Address,"Invalid address"),AsyncFactory:f(l.Invalid,u.AsyncFactory,"Factories must be synchronous"),AsyncState:f(l.Invalid,u.AsyncState,"State updates and migrations must be synchronous"),CoordinationLimits:f(l.Invalid,u.CoordinationLimits,"Invalid coordination limits"),DependencyCycle:f(l.Invalid,u.DependencyCycle,"Orb factories cannot acquire their own services"),DependencyService:f(l.Invalid,u.DependencyService,"Invalid dependency service"),DuplicateListener:f(l.Invalid,u.DuplicateListener,"Invalid duplicate listener"),DuplicateResource:f(l.Invalid,u.DuplicateResource,"Invalid duplicate resource"),EventSource:f(l.Invalid,u.EventSource,"Invalid event source"),Orb:f(l.Invalid,u.Orb,"An orb needs a name and positive API version"),OrbGone:f(l.Invalid,u.OrbGone,"Invalid orb gone"),OrbInstalled:f(l.Invalid,u.OrbInstalled,"Use reload to replace an installed orb"),Factory:f(l.Invalid,u.Factory,"Invalid factory"),FactoryExpired:f(l.Invalid,u.FactoryExpired,"Declarations must be synchronous"),Hook:f(l.Invalid,u.Hook,"Hooks need a run function"),HookDependency:f(l.Invalid,u.HookDependency,"Invalid hook dependency"),HooksDisabled:f(l.Invalid,u.HooksDisabled,"Invalid hooks disabled"),JsonAccessor:f(l.Invalid,u.JsonAccessor,"Invalid json accessor"),JsonCycle:f(l.Invalid,u.JsonCycle,"Invalid json cycle"),JsonNumber:f(l.Invalid,u.JsonNumber,"Use BigInt for integers outside the safe Number range"),JsonSymbol:f(l.Invalid,u.JsonSymbol,"Invalid json symbol"),JsonTag:f(l.Invalid,u.JsonTag,"Unknown or malformed portable type tag"),JsonType:f(l.Invalid,u.JsonType,"Supply a codec for custom object types"),JsonValue:f(l.Invalid,u.JsonValue,"This JSON codec requires explicit portable values"),Method:f(l.Invalid,u.Method,"Methods must be functions"),NextUsed:f(l.Invalid,u.NextUsed,"Invalid next used"),Priority:f(l.Invalid,u.Priority,"Invalid priority"),Reference:f(l.Invalid,u.Reference,"An issued local reference is required"),Resource:f(l.Invalid,u.Resource,"Invalid resource"),ResourceHost:f(l.Invalid,u.ResourceHost,"Resource dependencies must belong to the same host"),ResourceInFactory:f(l.Invalid,u.ResourceInFactory,"Resources open after declaration"),RpcFrame:f(l.Invalid,u.RpcFrame,"Invalid rpc frame"),RpcOperation:f(l.Invalid,u.RpcOperation,"Invalid rpc operation"),RpcRequest:f(l.Invalid,u.RpcRequest,"Invalid rpc request"),Service:f(l.Invalid,u.Service,"Invalid service"),ServiceGone:f(l.Invalid,u.ServiceGone,"Invalid service gone"),State:f(l.Invalid,u.State,"Service does not expose state"),StateCycle:f(l.Invalid,u.StateCycle,"State cannot contain cycles"),StateValidation:f(l.Invalid,u.StateValidation,"The orb rejected the state candidate"),StateValue:f(l.Invalid,u.StateValue,"State cannot contain accessors"),StateVersion:f(l.Invalid,u.StateVersion,"Invalid state version"),SubscriptionsDisabled:f(l.Invalid,u.SubscriptionsDisabled,"Invalid subscriptions disabled"),SubscriptionSize:f(l.Invalid,u.SubscriptionSize,"A local byte budget requires an explicit sizeOf function"),Task:f(l.Invalid,u.Task,"Invalid task"),Utf8:f(l.Invalid,u.Utf8,"Invalid utf8"),ValueGone:f(l.Invalid,u.ValueGone,"Invalid value gone"),ValuesExhausted:f(l.Invalid,u.ValuesExhausted,"Invalid values exhausted")}),Released:Object.freeze({Reference:f(l.Released,u.Reference,"The reference has been released")}),Unavailable:Object.freeze({Callback:f(l.Unavailable,u.Callback,"A callback failed"),OrbScope:f(l.Unavailable,u.OrbScope,"The orb scope is unavailable"),NotReady:f(l.Unavailable,u.NotReady,"The object is not ready"),Route:f(l.Unavailable,u.Route,"The route is unavailable")}),Unsupported:Object.freeze({EngineEffect:f(l.Unsupported,u.EngineEffect,"The engine effect is not supported by this adapter"),RemoteOpaque:f(l.Unsupported,u.RemoteOpaque,"Opaque resources are local to their language environment"),Telemetry:f(l.Unsupported,u.Telemetry,"Telemetry is disabled in this kernel"),Views:f(l.Unsupported,u.Views,"Reference views are disabled in this kernel")})});var He=new Set(Object.values(l));function Me(e){return typeof e==="object"&&e!==null&&"code"in e&&He.has(e.code)&&"reason"in e&&typeof e.reason==="string"&&"message"in e&&typeof e.message==="string"}class b extends Error{code;reason;constructor(e,t=e.message,n){super(t,n);this.name="TembraError",this.code=e.code,this.reason=e.reason}}function z(e){let t=c.Unavailable.Callback.message;try{if(e instanceof b)return e;if(Me(e))return new b(e,e.message,{cause:e});t=String(e instanceof Error?e.message:e)}catch{}return new b(c.Unavailable.Callback,t,{cause:e})}function h(e,t=e.message){throw new b(e,t)}var B="$tembra";function ce(e,t){if(typeof e==="bigint")return{[B]:[K.Bigint,e.toString()]};if(e instanceof Uint8Array)return{[B]:[K.Bytes,[...e]]};if(e===null||typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber,"Use BigInt for integers outside the safe Number range");return e}if(typeof e!=="object")h(c.Invalid.JsonValue,"This JSON codec requires explicit portable values");if(t.has(e))h(c.Invalid.JsonCycle);let n=Object.getPrototypeOf(e);if(!Array.isArray(e)&&n!==Object.prototype&&n!==null)h(c.Invalid.JsonType,"Supply a codec for custom object types");t.add(e);try{if(Array.isArray(e))return Array.from(e,(r)=>ce(r,t));let o=Reflect.ownKeys(e).map((r)=>{if(typeof r!=="string")h(c.Invalid.JsonSymbol);let s=Object.getOwnPropertyDescriptor(e,r);if(!Object.hasOwn(s,"value"))h(c.Invalid.JsonAccessor);return[r,ce(s.value,t)]});return Object.hasOwn(e,B)?{[B]:[K.Object,o]}:Object.fromEntries(o)}finally{t.delete(e)}}function ne(e){if(e===null||typeof e!=="object"){if(typeof e==="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber);return e}if(Array.isArray(e))return e.map(ne);if(Object.hasOwn(e,B)){let t=e[B];if(Object.keys(e).length!==1||!Array.isArray(t)||t.length!==2)h(c.Invalid.JsonTag);let[n,o]=t;if(n===K.Bigint&&typeof o==="string"&&/^-?(0|[1-9]\d*)$/.test(o))return BigInt(o);if(n===K.Bytes&&Array.isArray(o)&&o.every((r)=>Number.isInteger(r)&&r>=0&&r<=255))return Uint8Array.from(o);if(n===K.Object&&Array.isArray(o)){if(!o.every((r)=>Array.isArray(r)&&r.length===2&&typeof r[0]==="string"))h(c.Invalid.JsonTag);return Object.fromEntries(o.map(([r,s])=>[r,ne(s)]))}h(c.Invalid.JsonTag,"Unknown or malformed portable type tag")}return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ne(n)]))}function Ke(e){let t=[];for(let n of e){let o=n.codePointAt(0);if(o>=55296&&o<=57343)o=65533;if(o<128)t.push(o);else if(o<2048)t.push(192|o>>6,128|o&63);else if(o<65536)t.push(224|o>>12,128|o>>6&63,128|o&63);else t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}return Uint8Array.from(t)}function Ue(e){let t=[];for(let n=0;n<e.length;){let o=e[n++];if(o<128){t.push(String.fromCharCode(o));continue}let r=o>=194&&o<=223?1:o>=224&&o<=239?2:o>=240&&o<=244?3:-1;if(r<0||n+r>e.length)h(c.Invalid.Utf8);let s=o&127>>r+1;for(let a=0;a<r;a++){let i=e[n++];if((i&192)!==128)h(c.Invalid.Utf8);s=s<<6|i&63}if(s<[0,128,2048,65536][r]||s>1114111||s>=55296&&s<=57343)h(c.Invalid.Utf8);t.push(String.fromCodePoint(s))}return t.join("")}var W=Object.freeze({id:je.Json,serialize:(e)=>Ke(JSON.stringify(ce(e,new WeakSet))),deserialize:(e)=>ne(JSON.parse(Ue(e)))});var P=Object.freeze({Text:"text",Integer:"integer",Boolean:"boolean",Opaque:"opaque"});class U{name;version;kind;constructor(e,t,n){this.name=e;this.version=t;this.kind=n;Object.freeze(this)}static text(e,t=1){return new U(e,t,P.Text)}static integer(e,t=1){return new U(e,t,P.Integer)}static boolean(e,t=1){return new U(e,t,P.Boolean)}static opaque(e,t=1){return new U(e,t,P.Opaque)}source(e,t){if(this.kind!==P.Opaque)return;let n=typeof e==="object"&&e!==null?t.session.contextTokens.get(e):void 0;if(!n||n.root!==t.root)throw TypeError("An owner-issued opaque reference from this host and root is required");return n.source}}function de(e,t,n){let o=e.session.kernel.command(d.ContextValue,{root:e.root,context:n,call:e.invocation?.id,key:t});if(!o)return;if(o.kind!==P.Opaque)return o.value;let r=Object.freeze({opaque:!0});return e.session.contextTokens.set(r,{root:e.root,source:o.source}),r}function Ee(e,t,n){let o=de(e,t,n);if(!o)throw TypeError("The owner did not issue a reference");return o}var Ie=Symbol.for("@syntropika/tembra-sdk/service-identities"),Q=Object.getOwnPropertyDescriptor(globalThis,Ie)?.value;if(Q!==void 0&&!(Q instanceof WeakMap))throw TypeError("The SDK service identity slot must contain a WeakMap");var X=Q instanceof WeakMap?Q:new WeakMap;if(Q===void 0)Object.defineProperty(globalThis,Ie,{value:X});function De(e,t,n){let o=new Map;for(let[r,s,a]of n){let i={orb:e,name:r,apiVersion:t};for(let p of[s,a]){let m=o.get(p)??X.get(p);if(m&&(m.orb!==e||m.name!==r||m.apiVersion!==t))h(c.Invalid.Service,"A service definition must have one orb, name and API version");o.set(p,i)}}for(let[r,s]of o)X.set(r,s)}function Y(e,t={}){if(typeof e==="string")return{name:e,options:t};let n=X.get(e);if(!n)h(c.Invalid.Service,"Declare this service in an orb before acquiring it");if(t.apiVersion!==void 0&&t.apiVersion!==n.apiVersion)h(c.Invalid.Service,"The acquisition API version must match the service declaration");return{name:n.name,options:{...t,apiVersion:n.apiVersion}}}function le(e){if(!e.name||!Number.isInteger(e.apiVersion)||e.apiVersion<=0)h(c.Invalid.Orb,"An orb needs a name and positive API version");let t=Object.fromEntries(Object.entries(e.services??{}).map(([a,i])=>{if(!a||!i.methods||typeof i.methods!=="object")h(c.Invalid.Service);if(i.create&&typeof i.create!=="function")h(c.Invalid.Factory);for(let m of Object.values(i.methods))if(typeof m!=="function")h(c.Invalid.Method,"Methods must be functions");let p={...i,methods:Object.freeze({...i.methods})};return[a,Object.freeze(p)]})),n=Object.fromEntries(Object.entries(e.requires??{}).map(([a,i])=>[a,Object.freeze({...i,...i.methods?{methods:Object.freeze([...i.methods])}:{},...i.hooks?{hooks:Object.freeze([...i.hooks])}:{},...i.services?{services:Object.freeze(Object.fromEntries(Object.entries(i.services).map(([p,m])=>[p,Object.freeze([...m])])))}:{}})])),o=Object.fromEntries(Object.entries(e.hooks??{}).map(([a,i])=>{if(typeof i.run!=="function")h(c.Invalid.Hook,"Hooks need a run function");return[a,Object.freeze({...i,capabilities:Object.freeze([...i.capabilities??[]])})]})),r=Object.fromEntries(Object.entries(e.contributes??{}).map(([a,i])=>[a,Object.freeze(Object.fromEntries(Object.entries(i).map(([p,m])=>[p,typeof m==="function"?m:Object.freeze({...m})])))])),s=Object.freeze({...e,services:Object.freeze(t),requires:Object.freeze(n),hooks:Object.freeze(o),contributes:Object.freeze(r)});return De(e.name,e.apiVersion,Object.entries(e.services??{}).map(([a,i])=>[a,i,t[a]])),s}class pe{allocate;#e=1;#t=new Map;constructor(e){this.allocate=e}put(e){if(this.#e>4294967295)h(c.Invalid.ValuesExhausted);let t=this.allocate?this.allocate():this.#e++;return this.#t.set(t,e),t}get(e){if(!this.#t.has(e))h(c.Invalid.ValueGone);return this.#t.get(e)}drop(e){this.#t.delete(e)}has(e){return this.#t.has(e)}set(e,t){this.#t.set(e,t)}clear(){this.#t.clear()}get size(){return this.#t.size}}var Pe=new WeakSet;function Z(e){let t=new WeakSet;function n(o){if(o===null||typeof o!=="object"){if(["function","symbol"].includes(typeof o))h(c.Invalid.StateValue,"State must contain plain data");return}if(Pe.has(o))return;if(t.has(o))h(c.Invalid.StateCycle,"State cannot contain cycles");let r=Object.getPrototypeOf(o);if(!Array.isArray(o)&&r!==Object.prototype&&r!==null)h(c.Invalid.StateValue,"State requires plain objects and arrays");t.add(o);for(let s of Reflect.ownKeys(o)){if(typeof s!=="string")h(c.Invalid.StateValue,"State cannot contain symbol properties");let a=Object.getOwnPropertyDescriptor(o,s);if(!Object.hasOwn(a,"value"))h(c.Invalid.StateValue,"State cannot contain accessors");n(a.value)}t.delete(o),Object.freeze(o),Pe.add(o)}return n(e),e}class oe{compute;report;check;#e;#t=new Set;#n=new Set;#o=!0;#r;#s;#i;constructor(e,t,n,o){this.compute=e;this.report=n;this.check=o;this.#e=Z(e(t))}get value(){return this.check(),this.#e}track(e,t){this.#r=e,this.#i=t;let n=new WeakRef(this);this.#s=()=>n.deref()?.detach(),e?.add(this.#s)}detach(){if(!this.#o)return;if(this.#o=!1,this.#s)this.#r?.delete(this.#s);this.#i?.(),this.#t.clear();for(let e of this.#n)e.deref()?.detach();this.#n.clear()}prepare(e){if(!this.#o)return;try{this.check()}catch{this.detach();return}let t;try{t=Z(this.compute(e))}catch(o){this.detach(),this.report(o);return}if(!this.#o)return;let n=[];if(!Object.is(t,this.#e))for(let o of this.#n){let s=o.deref()?.prepare(t);if(s)n.push(s);else this.#n.delete(o)}return{adopt:()=>{if(!this.#o||Object.is(t,this.#e))return()=>{};this.#e=t;let o=n.map((s)=>s.adopt()),r=[...this.#t];return()=>{if(!this.#o)return;for(let s of o)s();for(let s of r)try{s(t)}catch(a){this.report(a)}}}}}select(e){this.check();let t=new oe(e,this.#e,this.report,this.check);this.check();let n=new WeakRef(t);return this.#n.add(n),t.track(this.#r,()=>this.#n.delete(n)),t}subscribe(e){this.check(),this.#t.add(e);try{e(this.#e)}catch(t){this.report(t)}return()=>{this.#t.delete(e)}}}class L{backend;object;closed=!1;#e;#t=new Set;#n=new Set;constructor(e,t,n){this.backend=e;this.object=t;this.#e=arguments.length>=3?n:e.value(e.snapshot(t).value)}check(){if(this.closed)throw new b(c.Gone.State,"State owner is gone")}get value(){return this.check(),this.#e}view(e,t=()=>this.check()){let n=this;return{get value(){return t(),n.value},update(o,r){t(),n.backend.check(o,n.object);let s=n.backend.snapshot(n.object),a=n.backend.value(s.value),i=r(a);if(F(i,e),n.backend.check(o,n.object),Object.is(i,a))return a;let p=n.prepare(i);n.backend.adopt(n.object,o,s.revision,i);let m=n.adopt(p,i);return n.backend.publish(m),i},select:(o)=>(t(),n.select(o,t)),subscribe:(o)=>(t(),n.subscribe(o))}}select(e,t=()=>this.check(),n){t();let o=new oe(e,this.value,(s)=>this.backend.report(s),t);t();let r=new WeakRef(o);return this.#n.add(r),o.track(n,()=>this.#n.delete(r)),o}subscribe(e){this.check(),this.#t.add(e);try{e(this.value)}catch(t){this.backend.report(t)}return()=>{this.#t.delete(e)}}prepare(e){let t=[];for(let n of this.#n){let r=n.deref()?.prepare(e);if(r)t.push(r);else this.#n.delete(n)}return t}adopt(e,t){this.#e=t;let n=e.map((r)=>r.adopt()),o=[...this.#t];return()=>{for(let r of n)r();for(let r of o)try{r(t)}catch(s){this.backend.report(s)}}}close(){this.closed=!0,this.#e=void 0,this.#t.clear();for(let e of this.#n)e.deref()?.detach();this.#n.clear()}}function F(e,t){if(e&&typeof e.then==="function")h(c.Invalid.AsyncState,"State updates and migrations must be synchronous");let n=Z(e),o=t.validate?.(n);if(o!==void 0&&o!==!0)h(c.Invalid.StateValidation,"Orb rejected the candidate state");return n}class H{session;environment;constructor(e,t){this.session=e;this.environment=t}check(){if(this.environment.phase!==S.Declaring)h(c.Invalid.FactoryExpired,"Declarations must be synchronous")}get principal(){return this.session.principalFor(this.environment.object?.id??0)}get orb(){return this.environment.orb.scope?.value}get key(){return this.environment.object?.address.key??["main"]}state(e,t={}){this.check();let n=this.environment,o=n.object;if(!o||n.state)h(c.Invalid.State,"An object declares exactly one state");let r=t.version??1;if(!Number.isInteger(r)||r<=0)h(c.Invalid.StateVersion);let s=o.binding;if(!s&&o.live)s=new L(this.session,o.id,F(e,t));if(!s){let i=F(e,t),p=this.session.values.put(i);try{this.session.kernel.command(d.StateInit,{object:o.id,value:p,version:r})}catch(m){throw this.session.values.drop(p),m}o.binding=s=new L(this.session,o.id)}let a=s.view(t);return n.state={initial:e,options:t,binding:s},a}get(e,t,n={}){this.check();let o=Y(e,n),r=this.session.scopes.requirement(this.environment,o.name),s=r.service;if(typeof e!=="string"&&s!==o.name)h(c.Invalid.Service,"A typed dependency must resolve its declared service name");if(!this.environment.object&&this.environment.orb.definition.services?.[s])h(c.Invalid.DependencyCycle);let a=Y(e,{...n,...r.apiVersion?{apiVersion:r.apiVersion}:{},...r.methods?{methods:r.methods}:{},principal:n.principal??this.principal}),i=JSON.stringify([s,t,n.principal??this.principal]),p=this.environment.dependencies.get(i);if(p)return p;let m=this.session.handles.hold(s,t,a.options);if(this.environment.object)try{this.session.kernel.command(d.Dependency,{object:this.environment.object.id,reference:this.session.handles.reference(m).id})}catch(y){throw m.release(),y}return this.environment.dependencies.set(i,m),m}resource(e,t){if(this.check(),!t)return this.session.scopes.hostResource(e);if(this.environment.resources.has(e))h(c.Invalid.DuplicateResource,e);let n=this.session.resources.declare(this.environment,e,t);return this.environment.resources.set(e,n),n.handle}task(e){if(this.check(),typeof e!=="function")h(c.Invalid.Task);this.environment.tasks.push({start:e})}on(e,t,n,o={}){if(this.check(),!this.session.kernel.features.subscriptions)h(c.Invalid.SubscriptionsDisabled);if(o.maxBytes!==void 0&&!o.sizeOf)h(c.Invalid.SubscriptionSize,"A local byte budget requires an explicit sizeOf function");if(!e||this.environment.listeners.some((r)=>r.name===e))h(c.Invalid.DuplicateListener,e);this.environment.listeners.push({name:e,source:t,handle:n,options:o})}hook(e){if(this.check(),!this.session.kernel.features.hooks)h(c.Invalid.HooksDisabled);if(!this.environment.orb.definition.hooks?.[e])h(c.Invalid.Hook,e);let t=this.session.kernel.command(d.Allocate);return{run:(n,o)=>this.session.orbs.runHook(this.environment,e,n,o),observe:(n,o)=>this.session.orbs.observe(this.environment,e,t,n,o)}}}function Ae(e,t,n){return{get value(){return t(),e.value},select(o){return t(),e.select(o,t,n)},subscribe(o){t();let r=e.subscribe((i)=>{try{t()}catch{return}o(i)}),s=!0,a=()=>{if(!s)return;s=!1,n.delete(a),r()};n.add(a);try{t()}catch{a()}return a}}}class ue{port;features;constructor(e){this.port=e;this.features=this.command(d.Features)}command(e,t={}){let n=JSON.parse(this.port.request(JSON.stringify({...t,op:e})));if(n.error)throw new b(n.error);return n.ok}}class fe{capacity;sampleEvery;#e=[];#t=0;constructor(e=256,t=1){this.capacity=e;this.sampleEvery=t;if(!Number.isInteger(e)||e<=0||!Number.isInteger(t)||t<=0)throw RangeError("Invalid telemetry limits")}sample(){return this.#t++%this.sampleEvery===0}record(e){if(this.#e.length===this.capacity)this.#e.shift();this.#e.push(e)}drain(){return this.#e.splice(0)}}class me{session;tasks=new Map;listeners=new Map;#e=new WeakMap;constructor(e){this.session=e}prepare(e,t){for(let n of e.listeners){let o=typeof n.source==="function"?n.source():n.source;if(!o||typeof o.subscribe!=="function")h(c.Invalid.EventSource);let r=this.session.kernel.command(d.Listen,{scope:e.id,previous:t?.id,name:n.name,source:this.identity(o),sizing:n.options.sizeOf?this.identity(n.options.sizeOf):0,operation:this.session.kernel.command(d.Allocate),maxPending:n.options.maxPending??64,...n.options.maxBytes?{maxBytes:n.options.maxBytes}:{},coalesce:"select"in o}),s=this.listeners.get(r);if(s){n.running=s;continue}let a={id:r,definition:n,environment:e,stopped:!1,detach(){}};n.running=a,this.listeners.set(r,a);try{if(a.detach=o.subscribe((i)=>{if(a.stopped)return;let p=this.session.values.put(i);try{let m=n.options.sizeOf?.(i)??0;if(!Number.isSafeInteger(m)||m<0||m>4294967295)throw new b(c.Invalid.SubscriptionSize);this.session.kernel.command(d.Enqueue,{subscription:r,payload:p,bytes:m})}catch(m){this.session.values.drop(p),this.session.report(m),this.failed(r)}this.session.lifecycle.flush()}),a.stopped)a.detach()}catch(i){throw this.stopListener(a),i}}}start(e){e.phase=S.Live;for(let t of e.listeners){let n=t.running;n.environment=e,n.definition=t}for(let t of e.tasks)this.startTask(e,t)}startTask(e,t){if(t.running||e.phase!==S.Live||this.session.closing)return;let n=this.session.kernel.command(d.Task,{owner:e.owner}),o=new AbortController,r=this.session.kernel.command(d.Allocate),s={id:n,controller:o,done:Promise.resolve()};t.running=s,this.tasks.set(n,s),s.done=this.session.track(Promise.resolve().then(async()=>{try{await t.start({signal:o.signal,root:(a)=>{let i=this.session.kernel.command(d.TaskRoot,{task:n,principal:this.session.principalFor(e.object?.id??0)});return this.session.calls.root(()=>this.session.calls.owned(e,r,a,i),!1,i)}})}catch(a){if(!o.signal.aborted)this.session.report(a)}finally{this.session.kernel.command(d.Tick,{now:this.session.now()}),this.session.kernel.command(d.FinishTask,{task:n}),this.tasks.delete(n),delete t.running,this.session.lifecycle.flush()}}))}identity(e){let t=this.#e.get(e);if(t===void 0)t=this.session.kernel.command(d.Allocate),this.#e.set(e,t);return t}deliver(e,t,n){let o=this.listeners.get(e),r=Promise.resolve().then(async()=>{try{if(!o)throw new b(c.Gone.ListenerCallback);await this.session.calls.owned(o.environment,n,(s)=>o.definition.handle(s,this.session.values.get(t)))}catch(s){this.session.report(s)}finally{this.session.kernel.command(d.FinishDelivery,{subscription:e}),this.session.lifecycle.flush()}});if(o)o.done=r;this.session.track(r)}detach(e){let t=this.listeners.get(e);if(t)this.stopListener(t)}cancel(e){this.tasks.get(e)?.controller.abort(new b(c.Cancelled.Task))}failed(e){let t=this.listeners.get(e);if(!t)return;this.session.report(new b(c.Exhausted.SubscriptionQueue)),this.stopListener(t)}stopListener(e){if(e.stopped)return;e.stopped=!0;try{e.detach()}catch(t){this.session.report(t)}this.session.kernel.command(d.Unsubscribe,{subscription:e.id}),this.listeners.delete(e.id),this.session.lifecycle.flush()}async stop(e){for(let t of e.tasks)if(t.running)this.session.kernel.command(d.StopTask,{task:t.running.id});this.session.lifecycle.flush(),await Promise.all(e.tasks.map((t)=>t.running?.done)),await Promise.all(e.listeners.map((t)=>t.running?.done))}}var re=new WeakMap;class A{session;root;invocation;frame;constructor(e,t,n,o=0){this.session=e;this.root=t;this.invocation=n;this.frame=o;re.set(this,this)}with(e,t){let n=e.source(t,this),o=this.session.kernel.command(d.ContextDerive,{root:this.root,context:this.frame,call:this.invocation?.id,key:e,...e.kind===P.Opaque?{source:n}:{value:t}});return new A(this.session,this.root,this.invocation,o)}value(e){return de(this,e,this.frame)}exportValues(e){let t={};for(let n of e){if(n.kind===P.Opaque)throw TypeError("Local opaque references cannot be exported");let o=this.value(n);if(o!==void 0)t[`${n.name}@${n.version}`]=o}return t}get principal(){return this.session.kernel.command(d.RootPrincipal,{root:this.root})}get signal(){return this.session.calls.signal(this.root)}check(){this.session.kernel.command(d.CheckContext,{root:this.root,call:this.invocation?.id})}cancel(){this.session.kernel.command(d.CancelRoot,{root:this.root}),this.session.lifecycle.flush()}get(e,t,n={}){return this.check(),this.session.handles.get(e,t,n,this)}resource(e){return this.check(),this.session.scopes.hostResource(e)}}function he(e,t){if(typeof e!=="object"||e===null||re.get(e)?.session!==t)throw new b(c.Forbidden.Context,"An issued context from this host is required");return re.get(e)}function V(e,t){let n=he(e,t);return n.check(),n}function _e(e){return typeof e==="object"&&e!==null&&re.has(e)}class be{session;constructor(e){this.session=e}signal(e){let t=this.session,n=t.controllers.get(e);if(!n){n=new AbortController;try{t.kernel.command(d.CheckRoot,{root:e})}catch(o){if(!(o instanceof b)||o.code!==l.Cancelled)throw o;n.abort(o)}t.controllers.set(e,n)}return n.signal}releaseRoot(e){for(let t of this.session.rootReferences.get(e)??[])this.session.handles.release(t);this.session.rootReferences.delete(e),this.session.controllers.delete(e)}async root(e,t=!1,n,o=this.session.principal){let r=this.session,s=n??r.kernel.command(t?d.CleanupRoot:d.Root,{principal:o}),a=new A(r,s);try{return await e(a)}finally{if(this.releaseRoot(s),r.options.native?.rootEnded?.(s),!r.lifecycle.closedDiagnostics)r.kernel.command(d.EndRoot,{root:s});r.controllers.delete(s),r.lifecycle.flush()}}async invoke(e,t,n,o){let r=this.session;if(V(o,r),e.released)throw new b(c.Released.Reference);await e.ready;let s=r.options.native?.admit?.(e.id,t,o),a;if(s)a=s.call;else o.check(),a=r.kernel.command(d.BeginCall,{reference:e.id,root:o.root,context:o.frame||void 0,method:t});let i=new A(r,o.root,a,o.frame),p=r.track((async()=>{let m=r.telemetry?.sample(),y=m?r.now():0,v=ae.Ok;try{let g=r.options.native;if(g&&(s?.native??g.hasOrb(a.orb)))return await g.invoke(a,n,i);let R=r.objects.get(a.object)?.versions.get(a.orb),x=R?.orb.definition.services?.[e.address.service]?.methods[t];if(!R||!x)throw new b(c.Gone.Implementation);return await x(R.value,i,...n)}catch(g){throw v=ae.Error,g}finally{if(m)r.telemetry.record({service:e.address.service,method:t,root:a.root,codeVersion:a.codeVersion,duration:r.now()-y,outcome:v});r.lifecycle.finishCall(a.id)}})());return this.observe(p,o.signal)}async owned(e,t,n,o){let r=this.session,s=async(a)=>{let i=r.kernel.command(d.BeginOperation,{orb:e.orb.info.id,root:a.root,context:a.frame||void 0,operation:t,...e.object?{object:e.object.id}:{}});try{return await n(new A(r,a.root,i,a.frame))}finally{r.kernel.command(d.FinishCall,{call:i.id}),r.lifecycle.flush()}};return o===void 0?this.root(s,!1,void 0,r.principalFor(e.object?.id??0)):s(typeof o==="number"?new A(r,o):o)}async observe(e,t){if(t.aborted)throw t.reason;let n,o=new Promise((r,s)=>{n=()=>s(t.reason??new b(c.Cancelled.Root)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,o])}finally{t.removeEventListener("abort",n)}}}class ve{session;records=new Map;operations=new Map;#e=new Map;#t=new Map;constructor(e){this.session=e}declarations(e){let t=e.map((s)=>le(s)),n=this.session.kernel.command(d.Orbs),o=(s)=>t.find((a)=>a.name===s),r=t.map((s)=>{if(!this.session.kernel.features.views&&Object.values(s.services??{}).some((i)=>i.access))throw new b(c.Unsupported.Views);let a=Object.entries(s.requires??{}).map(([i,p])=>{let m=p.orb??i,y=o(m),v=n.find((R)=>R.name===m),g=y?Object.keys(y.services??{}):v?.services.map((R)=>R.name)??[],k=g.includes(i)?i:g.length===1?g[0]:void 0;if(p.methods&&!k)h(c.Invalid.DependencyService,`Use explicit services for ${m}`);return{orb:m,apiVersion:p.apiVersion,services:p.services??(p.methods?{[k]:p.methods}:{}),hooks:p.hooks??[]}});for(let[i,p]of Object.entries(s.contributes??{})){let m=s.requires?.[i];if(!m)h(c.Invalid.HookDependency,i);for(let[y,v]of Object.entries(p)){if(!m.hooks?.includes(y))h(c.Invalid.HookDependency,y);let g=typeof v==="function"?0:v.priority??0;if(!Number.isInteger(g)||g<-2147483648||g>2147483647)h(c.Invalid.Priority)}}return{name:s.name,apiVersion:s.apiVersion,requires:a,hooks:Object.keys(s.hooks??{}),services:Object.entries(s.services??{}).map(([i,p])=>({name:i,methods:Object.keys(p.methods),lifetime:p.lifetime??G.Referenced,linger:p.linger??0}))}});return{definitions:t,metadata:r}}async install(e){let t=this.session.kernel.command(d.Orbs);if(e.some((s)=>t.some((a)=>a.name===s.name)))h(c.Invalid.OrbInstalled,"Use reload to replace an installed orb");let n=this.declarations(e),o=this.session.kernel.command(d.Prepare,{orbs:n.metadata});this.session.kernel.command(d.Commit,{ticket:o.id});let r=o.orbs.map((s)=>({info:s,definition:n.definitions.find((a)=>a.name===s.name)}));for(let s of r)this.records.set(s.info.id,s);for(let s of r)this.registerContributions(s);await Promise.all(r.map((s)=>this.ready(s)));for(let s of r)for(let a of s.info.services.filter((i)=>i.lifetime===G.Host))(await this.session.handles.get(a.name,"main",{principal:"host"})).release();this.session.lifecycle.flush()}scope(e){if(e.scope)return e.scope;let t=this.session.scopes.environment({kind:I.Orb,id:e.info.owner},e);e.scope=t;try{let n=e.definition.create?.(new H(this.session,t))??{};if(n&&typeof n.then==="function")h(c.Invalid.AsyncFactory);t.value=n}finally{t.phase=S.Prepared,this.session.programs.register(t)}return t}ready(e){if(e.scope?.phase===S.Live)return Promise.resolve();let t=this.#e.get(e.info.id);if(!t){t=(async()=>{try{if(await this.session.scopes.readyHostScope(),e.scope?.phase===S.Closed)delete e.scope;let o=this.scope(e);await this.session.programs.activate(o.id)}catch(o){if(e.scope)await this.session.programs.cleanup([e.scope]),delete e.scope;throw o}})(),this.#e.set(e.info.id,t);let n=()=>{if(this.#e.get(e.info.id)===t)this.#e.delete(e.info.id)};t.then(n,n)}return t}registerContributions(e){for(let[t,n]of Object.entries(e.definition.contributes??{})){let r=e.definition.requires[t].orb??t;for(let[s,a]of Object.entries(n)){let i=this.session.kernel.command(d.Allocate),p=JSON.stringify([e.info.name,r,s]);if(!this.#t.has(p))this.#t.set(p,this.session.kernel.command(d.ContributionOrdinal));this.operations.set(i,{orb:e,handler:typeof a==="function"?a:a.handle}),this.session.kernel.command(d.Contribute,{orb:e.info.id,target:r,hook:s,operation:i,priority:typeof a==="function"?0:a.priority??0,ordinal:this.#t.get(p)})}}}async runHook(e,t,n,o){n=V(n,this.session);let r=e.orb.definition.hooks?.[t];if(!r)h(c.Invalid.Hook,t);let a=this.session.kernel.command(d.HookPlan,{root:n.root,target:e.orb.info.name,hook:t}).map((i)=>async(p,m,y)=>this.runContribution(i,p,m,y));return r.run(n,o,a)}async observe(e,t,n,o,r){o=he(o,this.session);let s=e.orb.definition.hooks?.[t];if(!s)h(c.Invalid.Hook,t);if(!o.invocation)throw new b(c.Forbidden.ObservationSource);let a=this.session.kernel.command(d.BeginHookObservation,{source:o.invocation.id,orb:e.orb.info.id,operation:n,...e.object?{object:e.object.id}:{},hook:t});await this.session.track(this.session.calls.root(async()=>{try{let i=new A(this.session,a.invocation.root,a.invocation),p=a.plan.map((m)=>async(y,v,g)=>this.runContribution(m,y,v,g));await s.run(i,r,p)}finally{this.session.lifecycle.finishCall(a.invocation.id)}},!1,a.invocation.root))}async runContribution(e,t,n,o){t=V(t,this.session);let r=this.operations.get(e);if(!r){let a=this.session.options.native;if(a?.hasContribution?.(e)&&a.contribute)return a.contribute(e,t,n);throw new b(c.Gone.Contribution)}let s=r.orb.scope;if(!s)throw new b(c.Unavailable.OrbScope);return this.session.calls.owned(s,e,(a)=>r.handler(a,n,o),t)}retire(e){let t=this.session.kernel.command(d.ScopesForOrb,{orb:e}),n=this.session.programs.cleanupScopes(t);this.session.track(n.then(()=>{for(let[o,r]of this.operations)if(r.orb.info.id===e)this.operations.delete(o);this.records.delete(e),this.#e.delete(e)}),!0)}}class ye{session;constructor(e){this.session=e}get closedDiagnostics(){return this.#r}#e;#t=!1;#n;#o;#r;flush(e){if(this.#t)return;this.#t=!0;try{for(;;){let t=e??this.session.kernel.command(d.Drain);if(e=void 0,!t.length)break;for(let n of t)try{this.action(n)}catch(o){this.session.report(o)}}}finally{this.#t=!1,this.scheduleLinger()}}finishCall(e){let t=this.session;if(!this.#t&&t.options.native?.finish){let n=t.options.native.finish(e,t.now());if(!n.actions.length){this.scheduleLinger(n.deadline);return}this.flush(n.actions);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.FinishCall,{call:e}),this.flush()}action(e){let t=this.session;if(t.options.native?.notify?.(e)&&!(e.type===C.ProgramComplete&&t.programs.pending(e.id)))return;switch(e.type){case C.Execute:case C.CancelEffects:case C.ProgramPrepared:case C.ProgramComplete:t.programs.dispatch(e);break;case C.DropValue:t.values.drop(e.id),t.options.native?.dropValue?.(e.id);break;case C.CancelRoot:t.controllers.get(e.id)?.abort(new b(c.Cancelled.Root));break;case C.CancelTask:t.activities.cancel(e.id);break;case C.Deliver:t.activities.deliver(e.id,e.payload,e.operation);break;case C.DetachSubscription:t.activities.detach(e.id);break;case C.SubscriptionFailed:t.activities.failed(e.id);break;case C.Dispose:t.track(this.dispose(e.id),!0);break;case C.CloseResource:break;case C.RetireOrb:t.handles.retire(e.id),t.orbs.retire(e.id);break;case C.State:{let o=t.objects.get(e.id);if(!o?.binding)break;let r=t.snapshot(e.id);if(!t.values.has(r.value)){let s=t.value(r.value);t.publish(o.binding.adopt(o.binding.prepare(s),s))}break}}}async dispose(e){let t=this.session,n=t.objects.get(e);if(!n){await t.options.native?.dispose(e),t.kernel.command(d.Disposed,{object:e}),this.flush();return}return n.disposing??=(async()=>{let o=[];await n.activation.catch(()=>{});let r=t.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e}});try{await t.programs.cleanupScopes(r)}catch(s){o.push(s)}try{if(t.options.native?.hasOrb(n.orb))await t.options.native.dispose(e)}catch(s){o.push(s)}if(n.binding?.close(),t.kernel.command(d.Disposed,{object:e}),t.objects.delete(e),this.flush(),o.length)throw AggregateError(o,"Object cleanup failed")})(),n.disposing}scheduleLinger(e){let t=this.session;if(t.closing)return;let n=(e===void 0?t.kernel.command(d.NextDeadline):e)??void 0;if(n===this.#o)return;if(this.#n!==void 0)clearTimeout(this.#n);if(this.#n=void 0,this.#o=n,n===void 0)return;this.#n=setTimeout(()=>{if(this.#o!==n)return;this.#n=void 0,this.#o=void 0,t.kernel.command(d.Tick,{now:t.now()}),this.flush()},Math.max(0,n-t.now())),this.#n.unref?.()}diagnostics(){let e=this.session;if(this.#r)return this.#r;return{...e.kernel.command(d.Diagnostics),values:e.values.size,pendingJobs:e.jobs.size}}close(){let e=this.session;return this.#e??=(async()=>{e.closing=!0,clearTimeout(this.#n),this.#n=void 0,this.#o=void 0,e.kernel.command(d.Close),await e.replacements.cancel(),this.flush();for(;;){await e.options.native?.settled?.(),this.flush();let t=[...e.jobs];if(!t.length)break;await Promise.allSettled(t),this.flush()}if(e.kernel.command(d.FinishClose),e.values.clear(),e.handles.clear(),e.orbs.records.clear(),e.scopes.clear(),this.#r=this.diagnostics(),e.kernel.port.free?.(),e.cleanupErrors.length)throw AggregateError(e.cleanupErrors,"Host cleanup failed")})(),this.#e}}function ee(){let e,t,n=new Promise((o,r)=>{e=o,t=r});return n.catch(()=>{}),{promise:n,resolve:e,reject:t}}function Ve(e,t){return e.slice(0,t).replace(/[\uD800-\uDFFF]/gu,"�")}class ge{session;scopes=new Map;#e=new Map;constructor(e){this.session=e}register(e){let t=e.owner.kind===I.Host?void 0:e.object?e.orb.scope:this.session.hostScope;this.session.kernel.command(d.ScopeRegister,{scope:e.id,owner:e.owner,orb:e.orb.info.id,parents:t?[t.id]:[],dependencies:[...e.dependencies.values()].map((n)=>this.session.handles.reference(n).id),resources:[...e.resources.values()].map((n)=>n.id),stateVersion:e.state?.options.version??(e.state?1:void 0),migrate:Boolean(e.state?.options.migrate)})}activate(e){return this.run(this.session.kernel.command(d.ScopeActivate,{scope:e}))}cleanup(e){let t=e.map((n)=>n.id).filter((n)=>this.session.kernel.command(d.ScopeExists,{scope:n}));return this.cleanupScopes(t)}cleanupScopes(e){return e.length?this.run(this.session.kernel.command(d.ScopesCleanup,{scopes:e})):Promise.resolve()}pending(e){return this.#e.has(e)}run(e){let t=this.#e.get(e);if(t)return t.promise;let n=ee();this.#e.set(e,n);try{this.session.kernel.command(d.ProgramRun,{program:e}),this.session.lifecycle.flush()}catch(o){this.#e.delete(e),n.reject(o)}return n.promise}dispatch(e){if(e.type===C.Execute)this.session.track(Promise.allSettled(e.effects.map((t)=>this.execute(t))).then((t)=>{let n=Math.max(0,Math.min(2048,Math.floor((1048448-t.length*96)/(12*t.length)))),o=t.map((r)=>{if(r.status==="fulfilled")return{value:r.value??null};try{let{code:s,reason:a,message:i}=z(r.reason);if(!Object.values(l).includes(s)||typeof a!=="string"||typeof i!=="string")return{error:c.Unavailable.Callback};return{error:{code:s,reason:Ve(a,n),message:Ve(i,n)}}}catch{return{error:c.Unavailable.Callback}}});this.session.kernel.command(d.ProgramCompleteStep,{program:e.id,results:o}),this.session.lifecycle.flush()}));else if(e.type===C.CancelEffects)for(let t of e.effects){if(t.type!==j.Open&&t.type!==j.Restore)continue;let n=this.session.resources.find(t.resource);if(n)n.controller.abort(new b(c.Cancelled.EngineEffect));else if(this.session.options.native?.cancelEffect){let o=this.session.options.native.cancelEffect.bind(this.session.options.native);this.session.track(Promise.resolve().then(()=>o(t))).catch((r)=>this.session.report(r))}}else{let t=this.#e.get(e.id);if(this.#e.delete(e.id),e.error){let n=new b(e.error);if(t)t.reject(n);else this.session.cleanupErrors.push(n),this.session.report(n)}else t?.resolve()}}resource(e){let t=this.session.resources.find(e);if(t)return t;throw new b(c.Gone.Resource)}async execute(e){let t=e.scope===void 0?void 0:this.scopes.get(e.scope);if(e.scope!==void 0&&!t&&this.session.options.native)return this.session.options.native.effect(e);if((e.type===j.Close||e.type===j.Open)&&!this.session.resources.find(e.resource)&&this.session.options.native)return this.session.options.native.effect(e);switch(e.type){case j.Open:await this.resource(e.resource).start();break;case j.Close:await this.session.resources.close(this.resource(e.resource));break;case j.Restore:await this.session.resources.reopen(this.resource(e.previous),e.resource);break;case j.Stop:if(t)await this.session.activities.stop(t);break;case j.Prepare:{if(!t)throw new b(c.Gone.Scope);this.session.activities.prepare(t,e.previous?this.scopes.get(e.previous):void 0);break}case j.Validate:F(this.session.value(e.value),t.state.options);break;case j.Initialize:return this.candidate(t,t.state.initial);case j.Migrate:{let n=t.state;return this.candidate(t,n.options.migrate(this.session.value(e.value),e.version))}case j.Adopt:{let n=new Map;for(let o of e.replacements){if(!o.next)continue;let r=this.scopes.get(o.next);for(let[s,a]of r.resourceDeclarations??[])s.options=a;if(delete r.resourceDeclarations,n.set(r.orb.info.id,r.orb),r.object){if(r.state)r.object.binding=r.state.binding;r.object.orb=r.orb.info.id,r.object.versions.set(r.orb.info.id,r)}}for(let o of n.values())this.session.orbs.records.set(o.info.id,o),this.session.orbs.registerContributions(o);for(let o of e.replacements){let r=o.next?this.scopes.get(o.next):void 0;if(r?.object)this.session.handles.refreshReferences(r.object,r.orb)}for(let o of e.replacements)if(o.next)this.scopes.get(o.next)?.state?.publish?.();break}case j.Start:if(t){if(this.session.activities.start(t),t.object)t.object.live=!0}break;case j.Drop:{if(!t)break;for(let n of t.dependencies.values())this.session.handles.revoke(this.session.handles.reference(n).id);t.dependencies.clear();for(let n of t.resources.values())this.session.resources.closedRecords.delete(n.id);if(t.phase=S.Closed,t.object)t.object.versions.delete(t.orb.info.id);this.scopes.delete(t.id);break}default:throw new b(c.Unsupported.EngineEffect,e.type)}}candidate(e,t){let n=e.state,o=F(t,n.options),r=this.session.values.put(o);return n.publish=()=>this.session.publish(n.binding.adopt(n.binding.prepare(o),o)),r}}var qe=new WeakMap,ke=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry((e)=>e.session.deref()?.handles.release(e.id));class we{session;constructor(e){this.session=e}#e=new Map;#t=new Map;activateAcquired(e,t,n=[]){let o=this.session,r=o.objects.get(e.object);if(!r){let y=ee();r={id:e.object,address:t,orb:e.orb,versions:new Map,activation:y.promise},o.objects.set(r.id,r);let v=r;o.track(o.scopes.activate(v,e).then(y.resolve,(g)=>{v.error=g;try{o.kernel.command(d.Fail,{object:v.id})}catch{}y.reject(g),o.lifecycle.flush()}))}if(!this.claimExists(e.reference))return r.activation;let a=this.orbMetadata(r.orb).services.find((y)=>y.name===t.service)?.methods??[],i={id:e.reference,object:e.object,address:t,methods:new Set(a),requiredMethods:new Set(n),stateCleanups:new Set,ready:r.activation,released:!1,nativeOwned:!0},p=o.orbs.records.get(r.orb)?.definition.services?.[t.service]?.access;try{this.referenceMethods(i,a,p)}catch(y){if(o.kernel.features.views&&this.claimExists(i.id))o.kernel.command(d.Restrict,{reference:i.id,methods:[]});throw y}o.references.set(i.id,i);let m=this.#t.get(i.object);if(!m)this.#t.set(i.object,m=new Set);return m.add(i),r.activation}hold(e,t,n={},o){let r;if(typeof e==="string")r=e;else{let w=Y(e,n);r=w.name,n=w.options}let s=this.session;if(o)V(o,s);s.kernel.command(d.Tick,{now:s.now()});let a={service:r,key:typeof t==="string"?[t]:[...t],principal:n.principal??o?.principal??s.principal},i=s.kernel.command(d.Acquire,{...a,apiVersion:n.apiVersion??0,methods:n.methods??[]}),p=s.objects.get(i.object);if(!p){let w=ee();p={id:i.object,address:a,orb:i.orb,versions:new Map,activation:w.promise},s.objects.set(p.id,p);let T=p;queueMicrotask(()=>{s.track(s.scopes.activate(T,i).then(w.resolve,(M)=>{T.error=M;try{s.kernel.command(d.Fail,{object:T.id})}catch{}w.reject(M),s.lifecycle.flush()}))})}let m=this.orbMetadata(i.orb),y=new Set(m.services.find((w)=>w.name===r)?.methods??[]),v={id:i.reference,object:i.object,address:a,methods:y,requiredMethods:new Set(n.methods??[]),stateCleanups:new Set,ready:p.activation,released:!1,...o?{context:o}:{}},g=s.options.native?.access?.(i.orb,r,a.principal),k=g?()=>({methods:g}):s.orbs.records.get(i.orb)?.definition.services?.[r]?.access;try{this.referenceMethods(v,y,k)}catch(w){throw s.kernel.command(d.Release,{reference:v.id}),s.kernel.command(d.Forget,{reference:v.id}),s.lifecycle.flush(),w}s.references.set(v.id,v);let R=this.#t.get(v.object);if(!R)R=new Set,this.#t.set(v.object,R);if(R.add(v),o){let w=s.rootReferences.get(o.root);if(!w)w=new Set,s.rootReferences.set(o.root,w);w.add(v.id)}let x=()=>{if(v.released)throw new b(c.Released.Reference);if(s.closing)throw new b(c.Gone.Reference);let w=s.objects.get(v.object);if(!w||w.disposing||w.error)throw new b(c.Gone.Reference);if(!w.live)throw new b(c.Unavailable.NotReady)},E={get ready(){return v.ready},get status(){return v.released?_.Released:q.closing?_.Gone:q.kernel.command(d.Status,{reference:v.id})},get state(){x();let w=q.objects.get(v.object)?.binding;if(!w)h(c.Invalid.State,"Service does not expose state");return Ae(w,x,v.stateCleanups)},release:()=>this.release(v.id),opaque:(w)=>{x();let T=s.objects.get(v.object),M=T.versions.get(T.orb)?.resources.get(w);if(!M?.options.opaque)throw new b(c.Forbidden.Opaque,w);return M.handle.value}},q=s,J=new Proxy(E,{get:(w,T,M)=>{if(T==="then")return;if(Object.hasOwn(w,T))return Reflect.get(w,T,M);if(typeof T!=="string")return;if(!v.methods.has(T))return;return(...te)=>{let se=v.context;if(_e(te.at(-1)))se=te.pop();return se?s.calls.invoke(v,T,te,V(se,s)):s.calls.root((Fe)=>s.calls.invoke(v,T,te,Fe),!1,void 0,v.address.principal)}}});return qe.set(J,{session:s,record:v}),ke?.register(J,{session:new WeakRef(s),id:v.id},v),J}async get(e,t,n={},o){let r=this.hold(e,t,n,o);try{return await r.ready,r}catch(s){throw r.release(),s}}reference(e){let t=typeof e==="object"&&e!==null?qe.get(e):void 0;if(!t||t.session!==this.session)h(c.Invalid.Reference,"An issued local reference is required");return t.record}orbMetadata(e){let t=this.session.orbs.records.get(e)?.info;if(t)return t;let n=this.#e.get(e);if(!n)n=this.session.kernel.command(d.Orb,{id:e}),this.#e.set(e,n);return n}referenceMethods(e,t,n,o=!1){let r=this.session;if(n&&!r.kernel.features.views)throw new b(c.Unsupported.Views);let s=n?new Set(n(e.address.principal).methods):void 0,a=new Set([...t].filter((i)=>(!e.requiredMethods.size||e.requiredMethods.has(i))&&(!s||s.has(i))));if(n||o&&r.kernel.features.views)r.kernel.command(d.Restrict,{reference:e.id,methods:[...a]});e.methods=a}refreshReferences(e,t){let n=this.session,o=t.definition.services?.[e.address.service];if(!o)return;let r=Object.keys(o.methods);for(let s of this.#t.get(e.id)??[]){if(s.released)continue;if(s.nativeOwned&&!this.claimExists(s.id)){this.revoke(s.id);continue}try{this.referenceMethods(s,r,o.access,!0)}catch(a){if(s.methods.clear(),!s.released&&n.kernel.features.views)n.kernel.command(d.Restrict,{reference:s.id,methods:[]});n.report(a)}}}claimExists(e){try{let t=this.session.kernel.command(d.Status,{reference:e});return t!==_.Released&&t!==_.Gone}catch(t){if(t instanceof b&&(t.code===l.Gone||t.code===l.Released))return!1;throw t}}forget(e){for(let n of e.stateCleanups)n();e.stateCleanups.clear(),this.session.references.delete(e.id);let t=this.#t.get(e.object);if(t?.delete(e),!t?.size)this.#t.delete(e.object)}release(e){let t=this.session,n=t.references.get(e);if(!n||n.released)return;if(n.released=!0,ke?.unregister(n),t.lifecycle.closedDiagnostics){this.forget(n);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.Release,{reference:e}),t.kernel.command(d.Forget,{reference:e}),this.forget(n),t.lifecycle.flush()}revoke(e){let t=this.session.references.get(e);if(!t)return;t.released=!0,ke?.unregister(t),this.forget(t)}retire(e){this.#e.delete(e)}clear(){for(let e of this.session.references.values())this.forget(e);this.session.references.clear(),this.#t.clear(),this.#e.clear()}}class Re{session;#e;#t;#n;constructor(e){this.session=e}async replace(e,t={},n=[]){return(await this.prepare(e,t,n)).commit()}prepare(e,t={},n=[]){if(this.session.closing)return Promise.reject(new b(c.Closed.Host));if(this.#e)return Promise.reject(new b(c.Conflict.ReloadRunning));let o=this.capture(e,t,n);return this.#e=o,o.catch(()=>{if(this.#e===o)this.#e=void 0}),o}async cancel(){if(this.#n?.status===D.Prepared)return this.#n.abort();if(this.#t!==void 0){this.session.kernel.command(d.ProgramAbort,{program:this.#t});let e=this.session.programs.run(this.#t);this.session.lifecycle.flush(),await e.catch(()=>{})}await this.#e?.catch(()=>{return})}async capture(e,t,n){let o=this.session,r=o.orbs.declarations(e),s=o.kernel.command(d.Prepare,{orbs:r.metadata,remove:n}),a=new Map(r.definitions.map((k)=>[k.name,k])),i=s.orbs.map((k)=>({info:k,definition:a.get(k.name),ticket:s.id})),p=new Map(i.map((k)=>[k.info.id,k])),m;try{for(let k of i)o.orbs.scope(k);for(let k of s.objects){let R=o.objects.get(k);if(!R)continue;let x=s.providers[R.address.service],E=x===void 0?void 0:p.get(x);if(E)o.scopes.createEnvironment(R,E)}for(let k of i)k.ticket=void 0;if(m=o.kernel.command(d.ScopesReloadRegistered,{ticket:s.id,deadline:t.deadline??5000,now:o.now()}),this.#t=m,await o.programs.run(m),o.closing)await o.programs.run(m)}catch(k){if(this.#t=void 0,m===void 0){o.kernel.command(d.Abort,{ticket:s.id});let R=s.orbs.flatMap((x)=>o.kernel.command(d.ScopesForOrb,{orb:x.id}));await o.programs.cleanupScopes(R)}throw k}this.#t=void 0;let y=m,v={codeVersion:s.codeVersion,orbs:i.map((k)=>k.info.name)},g=D.Prepared;return this.#n={report:v,get status(){return g},commit:async()=>{if(g!==D.Prepared)throw new b(c.Conflict.ReloadTicket);this.#n=void 0;try{o.kernel.command(d.ProgramCommit,{program:y})}catch(k){throw o.kernel.command(d.ProgramAbort,{program:y}),await o.programs.run(y).catch(()=>{}),g=D.Aborted,this.#e=void 0,k}return g=D.Committed,this.#e=void 0,await o.programs.run(y),v},abort:async()=>{if(g===D.Aborted)return;if(g!==D.Prepared)throw new b(c.Conflict.AlreadyCommitted);g=D.Aborted,this.#n=void 0,this.#e=void 0,o.kernel.command(d.ProgramAbort,{program:y});try{await o.programs.run(y)}catch(k){if(!(k instanceof b)||k.reason!==u.ReloadAborted)throw k}}}}}var ze=new WeakMap;class Oe{session;records=new Map;closedRecords=new Map;constructor(e){this.session=e}find(e){return this.records.get(e)??this.closedRecords.get(e)}dependencyIds(e){let t=[];for(let n of e.deps??[]){let o=typeof n==="object"&&n!==null?ze.get(n):void 0;if(o){if(o.session!==this.session)h(c.Invalid.ResourceHost,"Resource dependencies must belong to the same host");t.push(o.id)}else this.session.handles.reference(n)}return t}register(e,t,n){return this.session.kernel.command(d.Resource,{owner:e.owner,name:t,version:n.version??1,exclusive:n.exclusive??!1,dependencies:this.dependencyIds(n)}).id}redeclare(e,t){for(let n of t.resources.values())this.records.delete(n.id),this.closedRecords.delete(n.id),n.reset(this.register(e,n.name,n.options)),n.dependencies=this.dependencyIds(n.options),this.records.set(n.id,n),e.resources.set(n.name,n)}declare(e,t,n){if(!t||typeof n.open!=="function")h(c.Invalid.Resource);let o=this.register(e,t,n),r=this.records.get(o);if(r)return(e.resourceDeclarations??=new Map).set(r,n),r;let s=new AbortController,a=Object.freeze({get value(){if(e.phase===S.Declaring)h(c.Invalid.ResourceInFactory,"Resources open after declaration");let p=i.session.kernel.command(d.ResourceValue,{resource:i.id});return i.session.value(p)},version:n.version??1}),i={id:o,name:t,options:n,handle:a,dependencies:this.dependencyIds(n),controller:s,session:this.session,reset:(p)=>{i.id=p,i.controller=new AbortController,delete i.value,delete i.closed,delete i.started},start:()=>(i.started??=(async()=>{let p=i.options,m=await p.open(i.controller.signal),y=this.session.values.put(m);try{this.session.kernel.command(d.ResourceOpened,{resource:i.id,value:y})}catch(v){if(this.session.values.drop(y),p.close)await this.session.calls.root((g)=>p.close(m,g),!0);throw v}i.value=y})(),i.started.catch(()=>{}),i.started)};return ze.set(a,i),this.records.set(o,i),i}async close(e){return e.closed??=(async()=>{e.controller.abort(new b(c.Cancelled.Resource)),await e.started?.catch(()=>{});try{if(e.value!==void 0&&e.options.close){let t=this.session.value(e.value);await this.session.calls.root((n)=>e.options.close(t,n),!0)}}finally{this.session.kernel.command(d.ResourceClosed,{resource:e.id}),this.records.delete(e.id),this.closedRecords.set(e.id,e),this.session.lifecycle.flush()}})(),e.closed}async reopen(e,t){this.closedRecords.delete(e.id),e.reset(t),this.records.set(t,e),await e.start()}}class Se{session;constructor(e){this.session=e}#e=new Map;#t=new Set;#n;environment(e,t,n){let o={id:this.session.kernel.command(d.Allocate),owner:e,orb:t,...n?{object:n}:{},phase:S.Declaring,value:{},dependencies:new Map,resources:new Map,tasks:[],listeners:[]};return this.session.programs.scopes.set(o.id,o),o}async activate(e,t){let n=this.session;if(n.options.native?.hasOrb(t.orb)){await n.options.native.activate(e.id,t.orb,e.address.service,e.address.key,e.address.principal);let o=n.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e.id}});await Promise.all(o.map((r)=>n.programs.activate(r)));try{n.snapshot(e.id),e.binding=new L(n,e.id)}catch{}}else{let o=n.orbs.records.get(t.orb);if(!o)h(c.Invalid.OrbGone);await n.orbs.ready(o);let r=this.createEnvironment(e,o);e.versions.set(o.info.id,r),await this.session.programs.activate(r.id)}if(n.kernel.command(d.Status,{reference:t.reference})===_.Loading)n.kernel.command(d.Ready,{object:e.id});e.live=!0,n.lifecycle.flush()}createEnvironment(e,t){let n=t.definition.services?.[e.address.service];if(!n)h(c.Invalid.ServiceGone);let o=this.environment({kind:I.Object,id:e.id},t,e);try{let r=n.create?.(new H(this.session,o))??{};if(r&&typeof r.then==="function")h(c.Invalid.AsyncFactory,"Factories must be synchronous");return o.value=r,o}finally{o.phase=S.Prepared,this.session.programs.register(o)}}readyHostScope(){let e=this.session;if(e.closing)return Promise.reject(new b(c.Closed.Host));if(this.#n)return this.#n;let t=(async()=>{if(e.hostScope.phase===S.Closed)e.hostScope=await this.redeclareHostScope(e.hostScope);await this.session.programs.activate(e.hostScope.id);while(this.#t.size){let o=this.#t.values().next().value;if(o.phase===S.Closed||[...o.resources.values()].some((r)=>e.resources.dependencyIds(r.options).some((s,a)=>s!==r.dependencies[a]))){let r=o;o=await this.redeclareHostScope(r),this.#t.delete(r),this.#t.add(o)}await this.session.programs.activate(o.id),this.#t.delete(o)}})();this.#n=t;let n=()=>{if(this.#n===t)this.#n=void 0};return t.then(n,n),t}async redeclareHostScope(e){let t=this.session;await t.programs.cleanup([e]);let n=this.environment({kind:I.Host},e.orb);return t.resources.redeclare(n,e),n.phase=S.Prepared,t.programs.register(n),n}requirement(e,t){if(e.orb.definition.services?.[t])return{service:t,apiVersion:e.orb.info.apiVersion};for(let[o,r]of Object.entries(e.orb.definition.requires??{})){let s;try{s=this.session.kernel.command(d.OrbNamed,{name:r.orb??o,ticket:e.orb.ticket})}catch(p){if(p instanceof b&&p.code===l.Gone&&p.reason===u.Orb)continue;throw p}let a=o===t?s.services.find((p)=>p.name===o)??(s.services.length===1?s.services[0]:void 0):s.services.find((p)=>p.name===t);if(!a)continue;let i=r.services?.[a.name]??r.methods;if(!i)throw new b(c.Forbidden.UndeclaredService,t);return{service:a.name,apiVersion:r.apiVersion,methods:i}}throw new b(c.Forbidden.UndeclaredDependency,t)}hostResource(e){let t=this.#e.get(e);if(!t)throw new b(c.Forbidden.HostResource,e);return t.handle}resource(e,t){let n=this.session;if(n.closing)throw new b(c.Closed.Host);if(this.#e.has(e))h(c.Invalid.DuplicateResource);let o=this.environment({kind:I.Host},n.hostScope.orb);try{let r=new H(n,o).resource(e,t);return this.#e.set(e,o.resources.get(e)),o.phase=S.Prepared,n.programs.register(o),this.#t.add(o),n.track(this.readyHostScope()).catch((s)=>n.report(s)),r}catch(r){throw n.programs.scopes.delete(o.id),r}}registerHost(e){for(let[t,n]of e.resources)this.#e.set(t,n)}clear(){this.#e.clear(),this.#t.clear()}}class xe{options;contextTokens=new WeakMap;calls=new be(this);handles=new we(this);scopes=new Se(this);lifecycle=new ye(this);kernel;values;resources=new Oe(this);activities=new me(this);orbs=new ve(this);replacements=new Re(this);programs=new ge(this);objects=new Map;references=new Map;rootReferences=new Map;controllers=new Map;jobs=new Set;cleanupErrors=[];hostScope;codec;name;principal;errors=[];now;telemetry;closing=!1;#e=!1;#t=[];constructor(e){this.options=e;if(this.kernel=new ue(e.kernel),e.telemetry&&!this.kernel.features.telemetry)throw new b(c.Unsupported.Telemetry);this.telemetry=e.telemetry?new fe(e.telemetry.capacity,e.telemetry.sampleEvery):void 0,this.values=new pe(()=>this.kernel.command(d.Allocate)),this.codec=e.serialization??W,this.name=e.name??"host",this.principal=e.principal??"host";let t=e.now??(()=>performance.now()),n=e.clockOrigin??t();this.now=()=>Math.floor(t()-n);let o={info:{id:0,owner:0,name:"$host",apiVersion:1,codeVersion:1,services:[],hooks:[],requires:[]},definition:{name:"$host",apiVersion:1}};this.hostScope=this.scopes.environment({kind:I.Host},o);for(let[r,s]of Object.entries(e.resources??{}))new H(this,this.hostScope).resource(r,s);this.scopes.registerHost(this.hostScope),this.hostScope.phase=S.Prepared,this.programs.register(this.hostScope)}principalFor(e){return this.objects.get(e)?.address.principal??this.principal}snapshot(e){return this.kernel.command(d.Snapshot,{object:e})}value(e){if(this.values.has(e))return this.values.get(e);if(!this.options.native)h(c.Invalid.ValueGone);let t=this.options.native.value(e);return this.values.set(e,t),t}check(e,t){let n=V(e,this);if(!n.invocation||n.invocation.object!==t)throw new b(c.Forbidden.StateOwner);return n.invocation}adopt(e,t,n,o){let r=this.check(t,e),s=this.values.put(o);try{return this.kernel.command(d.StateAdopt,{call:r.id,object:e,revision:n,value:s})}catch(a){throw this.values.drop(s),a}finally{this.lifecycle.flush()}}publish(e){if(this.#t.push(e),this.#e)return;this.#e=!0;try{while(this.#t.length)this.#t.shift()()}finally{this.#e=!1}}report(e){let t=z(e);if(this.errors.length===64)this.errors.shift();this.errors.push(t);try{this.options.onError?.(t)}catch{}}track(e,t=!1){return this.jobs.add(e),e.then(()=>{this.jobs.delete(e)},(n)=>{if(this.jobs.delete(e),t)this.cleanupErrors.push(n),this.report(n)}),e}}class Ce{session;constructor(e){this.session=new xe(e)}get name(){return this.session.name}get features(){return this.session.kernel.features}install(e){return this.session.orbs.install(Array.isArray(e)?e:[e])}async load(e){if(!this.session.options.load)throw Error("This host has no module loader");await this.install(await this.session.options.load(e))}reload(e,t){return this.session.replacements.replace(e,t)}prepare(e,t){return this.session.replacements.prepare(e,t)}remove(e,t){return this.session.replacements.replace([],t,e)}hold(e,t,n){return this.session.handles.hold(e,t,n)}get(e,t,n){return this.session.handles.get(e,t,n)}root(e,t={}){return this.session.calls.root(e,!1,void 0,t.principal)}resource(e,t){return this.session.scopes.resource(e,t)}diagnostics(){return this.session.lifecycle.diagnostics()}errors(){return this.session.errors.splice(0)}traces(){return this.session.telemetry?.drain()??[]}installedOrbs(){return this.session.kernel.command(d.Orbs).map((e)=>{let t=this.session.orbs.records.get(e.id)?.definition,n=Object.freeze({...e,hookCapabilities:Object.fromEntries(e.hooks.map((o)=>[o,t?.hooks?.[o]?.capabilities??[]]))});return Object.freeze({...e,describe:()=>n})})}close(){return this.session.lifecycle.close()}}var O=Deno.core.ops,N=globalThis;N.queueMicrotask??=(e)=>Promise.resolve().then(e);N.performance??={now:()=>O.op_tembra_now()};N.AbortController??=class{signal={aborted:!1,reason:void 0,listeners:new Set,addEventListener(e,t){this.listeners.add(t)},removeEventListener(e,t){this.listeners.delete(t)},throwIfAborted(){if(this.aborted)throw this.reason}};abort(e=Error("Aborted")){if(this.signal.aborted)return;this.signal.aborted=!0,this.signal.reason=e;for(let t of[...this.signal.listeners])t();this.signal.listeners.clear()}};var Le=0,Te=new Set;N.setTimeout??=(e,t=0,...n)=>{let o=++Le;return Te.add(o),O.op_tembra_sleep(o,Math.max(0,Math.min(2147483647,t))).then(()=>{if(Te.delete(o))e(...n)}),o};N.clearTimeout??=(e)=>{if(Te.delete(e))O.op_tembra_clear_timer(e)};function Ne(e={}){let t=e.serialization??W;if(t.id!==O.op_tembra_codec())throw new b(c.Conflict.Codec,"The Rust and JS host codecs must agree");function n(i){let p=t.deserialize(i);if(p.error)throw new b(p.error);return p.ok}let o=O.op_tembra_driver_enabled?.()??!1,r=new Map;N.__tembraDeliver=(i)=>{for(let[p,m,y]of i){let v=r.get(p);if(!v)throw Error("unknown native completion");r.delete(p);try{if(!y)throw Error(m);v.resolve(n(m))}catch(g){v.reject(g)}}};function s(i,p){let m=O.op_tembra_submit(i,p);return new Promise((y,v)=>r.set(m,{resolve:y,reject:v}))}let a=new Ce({...e,clockOrigin:0,kernel:{request:(i)=>O.op_tembra_kernel(i)},native:{...o?{admit:(i,p,m)=>{let y=JSON.parse(O.op_tembra_admit(JSON.stringify({reference:i,method:p,root:m.root,context:m.frame,parent:m.invocation?.id})));if(y.error)throw new b(y.error);return y.ok},finish:(i,p)=>{let m=JSON.parse(O.op_tembra_finish(i,String(p)));if(m.error)throw new b(m.error);return m.ok}}:{},rootEnded:(i)=>O.op_tembra_end_context(i),access:(i,p,m)=>JSON.parse(O.op_tembra_access(i,p,m))??void 0,settled:()=>O.op_tembra_settled(),notify:(i)=>O.op_tembra_notify(JSON.stringify(i)),hasContribution:(i)=>O.op_tembra_has_contribution?.(i)??!1,contribute:async(i,p,m)=>n(await O.op_tembra_native("contribute",t.serialize({operation:i,root:p.root,frame:p.frame,...m===void 0?{}:{input:m}}))).value,hasOrb:(i)=>O.op_tembra_has_orb(i),activate:async(i,p,m)=>{n(await O.op_tembra_native("activate",t.serialize({object:i,orb:p,service:m})))},invoke:async(i,p)=>o?s("invoke",t.serialize({invocation:i,arguments:p})):n(await O.op_tembra_native("invoke",t.serialize({invocation:i,arguments:p}))),dispose:async(i)=>{n(await O.op_tembra_native("dispose",t.serialize({object:i})))},effect:async(i)=>n(await O.op_tembra_native("effect",t.serialize(i))),cancelEffect:async(i)=>{n(await O.op_tembra_native("cancel-effect",t.serialize(i)))},value:(i)=>n(O.op_tembra_value(i)),dropValue:(i)=>O.op_tembra_drop_value(i)}});if(O.op_tembra_callback_next)(async()=>{for(;;){let i=O.op_tembra_callback_next();Deno.core.unrefOpPromise(i);let p=await i;if(!p.length)return;let m=new DataView(p.buffer,p.byteOffset,9),y=m.getUint8(0),v=m.getUint32(1,!0)+m.getUint32(5,!0)*4294967296;if(y!==0){if(y===2)a.session.calls.releaseRoot(v);if(y===3)a.session.handles.revoke(v);a.session.lifecycle.flush();continue}let g;try{g=t.deserialize(p.subarray(9))}catch(k){let{code:R,reason:x,message:E}=z(k);O.op_tembra_callback_error(v,JSON.stringify({code:R,reason:x,message:E}),!0);continue}a.session.track((async()=>{let k;try{let R;if(g.kind==="activate")await a.session.handles.activateAcquired(g.acquired,g.address,g.methods),R=null;else{let x=g.call,E=a.session.kernel.command(d.Invocation,{call:x}),q=new A(a.session,E.root,E,g.frame);if(g.kind==="invoke"){let J=a.session.objects.get(E.object),w=J?.versions.get(E.orb),T=w?.orb.definition.services?.[J.address.service]?.methods[E.method];if(!T||!w)throw new b(c.Gone.Implementation);R=await T(w.value,q,...g.input)}else R=await a.session.orbs.runContribution(g.operation,q,g.input)}k=R===void 0?{}:{value:R}}catch(R){let x=z(R);k={error:{code:x.code,reason:x.reason,message:x.message}}}try{O.op_tembra_callback_complete(v,t.serialize(k))}catch(R){let{code:x,reason:E,message:q}=z(R);O.op_tembra_callback_error(v,JSON.stringify({code:x,reason:E,message:q}),!1)}})(),!0)}})();return a}N.Tembra=Object.freeze({ContextKey:U,ContextKind:P,opaqueFrom:Ee,createHost:Ne,jsonCodec:W,Code:l,Reason:u,Lifetime:G,Status:_,ReloadStatus:D,HookCapability:ie,Errors:c});})();
|
|
1
|
+
(()=>{var l=Object.freeze({Invalid:"invalid",Unavailable:"unavailable",Released:"released",Gone:"gone",Expired:"expired",Cancelled:"cancelled",Forbidden:"forbidden",Conflict:"conflict",Unsupported:"unsupported",Closed:"closed",Exhausted:"exhausted"}),u=Object.freeze({ActivationBusy:"activation_busy",Address:"address",AlreadyCommitted:"already_committed",AmbiguousScope:"ambiguous_scope",ApiVersion:"api_version",Arguments:"arguments",AsyncFactory:"async_factory",AsyncState:"async_state",Bigint:"bigint",ByteResult:"byte_result",Call:"call",Callback:"callback",CleanupBusy:"cleanup_busy",Clock:"clock",Codec:"codec",Connection:"connection",Context:"context",Contribution:"contribution",CoordinationLimits:"coordination_limits",Deadline:"deadline",Dependency:"dependency",DependencyCycle:"dependency_cycle",DependencyService:"dependency_service",Disposing:"disposing",Driver:"driver",Duplicate:"duplicate",DuplicateContribution:"duplicate_contribution",DuplicateListener:"duplicate_listener",DuplicateResource:"duplicate_resource",DuplicateService:"duplicate_service",EffectResults:"effect_results",EffectsRunning:"effects_running",EngineEffect:"engine_effect",EventSource:"event_source",ExclusiveDependent:"exclusive_dependent",Executor:"executor",Orb:"orb",OrbGone:"orb_gone",OrbInstalled:"orb_installed",OrbScope:"orb_scope",Factory:"factory",FactoryExpired:"factory_expired",FrameSize:"frame_size",GateBusy:"gate_busy",GateOrb:"gate_orb",GateObject:"gate_object",Hook:"hook",HookDependency:"hook_dependency",Hooks:"hooks",HooksDisabled:"hooks_disabled",Host:"host",HostAddress:"host_address",HostResource:"host_resource",HostResourceReload:"host_resource_reload",Identities:"identities",Implementation:"implementation",Invocation:"invocation",Javascript:"javascript",JsonAccessor:"json_accessor",JsonCycle:"json_cycle",JsonNumber:"json_number",JsonSymbol:"json_symbol",JsonTag:"json_tag",JsonType:"json_type",JsonValue:"json_value",Lifetime:"lifetime",Linger:"linger",ListenerCallback:"listener_callback",LiveConsumer:"live_consumer",LiveReference:"live_reference",LocalValue:"local_value",Memory:"memory",Metadata:"metadata",MetadataSize:"metadata_size",Method:"method",MigrationGate:"migration_gate",MigrationRequired:"migration_required",MigrationValue:"migration_value",MissingHook:"missing_hook",MissingMethod:"missing_method",NativeEffect:"native_effect",NativeMethod:"native_method",NativeObject:"native_object",NativeService:"native_service",Next:"next",NextUsed:"next_used",NotReady:"not_ready",Object:"object",ObjectState:"object_state",ObservationSource:"observation_source",ObservationAdmitted:"observation_admitted",Opaque:"opaque",Operation:"operation",OperationOwner:"operation_owner",Owner:"owner",Payload:"payload",PendingRequests:"pending_requests",PrepareDeadline:"prepare_deadline",Priority:"priority",Program:"program",ProgramPhase:"program_phase",ProgramRunning:"program_running",Reference:"reference",ReloadAborted:"reload_aborted",ReloadDeadline:"reload_deadline",ReloadPreparing:"reload_preparing",ReloadRunning:"reload_running",ReloadTicket:"reload_ticket",RemoteOpaque:"remote_opaque",RemoteReferences:"remote_references",Request:"request",RequestIds:"request_ids",Requires:"requires",Resource:"resource",ResourceDependencies:"resource_dependencies",ResourceDependency:"resource_dependency",ResourceHost:"resource_host",ResourceInFactory:"resource_in_factory",ResourceState:"resource_state",ResourceVersion:"resource_version",Result:"result",RetainedVersions:"retained_versions",RevisionExhausted:"revision_exhausted",Root:"root",Route:"route",RpcFrame:"rpc_frame",RpcOperation:"rpc_operation",RpcRequest:"rpc_request",RustType:"rust_type",Scope:"scope",ScopeClosed:"scope_closed",ScopeOrb:"scope_orb",ScopeOwner:"scope_owner",ScopeResource:"scope_resource",Serialization:"serialization",Service:"service",ServiceGone:"service_gone",State:"state",StateCycle:"state_cycle",StateInitialized:"state_initialized",StateOwner:"state_owner",StateRevision:"state_revision",StateValidation:"state_validation",StateValue:"state_value",StateVersion:"state_version",Subscription:"subscription",SubscriptionBusy:"subscription_busy",SubscriptionIdle:"subscription_idle",SubscriptionQueue:"subscription_queue",SubscriptionSize:"subscription_size",SubscriptionsDisabled:"subscriptions_disabled",Superseded:"superseded",Task:"task",Telemetry:"telemetry",UndeclaredDependency:"undeclared_dependency",UndeclaredService:"undeclared_service",UnknownService:"unknown_service",UpgradeConflict:"upgrade_conflict",Utf8:"utf8",Value:"value",ValueGone:"value_gone",ValuesExhausted:"values_exhausted",Views:"views"}),G=Object.freeze({Referenced:"referenced",Host:"host"}),A=Object.freeze({Loading:"loading",Live:"live",Released:"released",Gone:"gone"}),P=Object.freeze({Prepared:"prepared",Committed:"committed",Aborted:"aborted"}),ie=Object.freeze({Observe:"observe",Transform:"transform",Decide:"decide"});var d=Object.freeze({ContextDerive:"context-derive",ContextValue:"context-value",ContextStats:"context-stats",Allocate:"allocate",ScopeRegister:"scope-register",ScopeExists:"scope-exists",ScopesForOwner:"scopes-for-owner",ScopesForOrb:"scopes-for-orb",ScopeAddResource:"scope-add-resource",ScopeActivate:"scope-activate",ScopesCleanup:"scopes-cleanup",ScopesReloadRegistered:"scopes-reload-registered",ScopesReload:"scopes-reload",ProgramRun:"program-run",ProgramNext:"program-next",ProgramCompleteStep:"program-complete-step",ProgramCommit:"program-commit",ProgramAbort:"program-abort",ProgramForget:"program-forget",Features:"features",Prepare:"prepare",Gate:"gate",GateOrbs:"gate-orbs",Commit:"commit",Abort:"abort",Orbs:"orbs",Orb:"orb",OrbNamed:"orb-named",NextDeadline:"next-deadline",Address:"address",Acquire:"acquire",Ready:"ready",Dependency:"dependency",Undepend:"undepend",Fail:"fail",Status:"status",Release:"release",Forget:"forget",Root:"root",CleanupRoot:"cleanup-root",RootPrincipal:"root-principal",CheckContext:"check-context",CheckRoot:"check-root",EndRoot:"end-root",CancelRoot:"cancel-root",BeginCall:"begin-call",BeginOperation:"begin-operation",BeginHookObservation:"begin-hook-observation",FinishCall:"finish-call",Invocation:"invocation",StateInit:"state-init",Snapshot:"snapshot",StateAdopt:"state-adopt",Task:"task",TaskRoot:"task-root",StopTask:"stop-task",FinishTask:"finish-task",Resource:"resource",ResourceOpened:"resource-opened",ResourceValue:"resource-value",CloseResource:"close-resource",ResourceClosed:"resource-closed",Disposed:"disposed",Tick:"tick",NextWake:"next-wake",NextIdle:"next-idle",Close:"close",FinishClose:"finish-close",Diagnostics:"diagnostics",Drain:"drain",Restrict:"restrict",Contribute:"contribute",ContributionOrdinal:"contribution-ordinal",HookPlan:"hook-plan",Listen:"listen",Subscribe:"subscribe",Enqueue:"enqueue",NextDelivery:"next-delivery",FinishDelivery:"finish-delivery",Unsubscribe:"unsubscribe"}),C=Object.freeze({Execute:"execute",CancelEffects:"cancel-effects",ProgramPrepared:"program-prepared",ProgramComplete:"program-complete",Dispose:"dispose",CloseResource:"close-resource",DropValue:"drop-value",CancelRoot:"cancel-root",CancelTask:"cancel-task",RetireOrb:"retire-orb",State:"state",SubscriptionFailed:"subscription-failed",DetachSubscription:"detach-subscription",Deliver:"deliver"}),j=Object.freeze({Stop:"stop",Open:"open",Close:"close",Restore:"restore",Prepare:"prepare",Validate:"validate",Initialize:"initialize",Migrate:"migrate",Adopt:"adopt",Start:"start",Drop:"drop"}),Ge=Object.freeze({Execute:"execute",Wait:"wait",Prepared:"prepared",Complete:"complete",Failed:"failed"}),Be=Object.freeze({Activate:"activate",Dispose:"dispose",CancelEffect:"cancel-effect",Effect:"effect",Invoke:"invoke",Contribute:"contribute"}),We=Object.freeze({Describe:"describe",Get:"get",Release:"release",Call:"call",Cancel:"cancel"}),$e=Object.freeze({State:"state"}),I=Object.freeze({Host:"host",Orb:"orb",Object:"object"}),S=Object.freeze({Declaring:"declaring",Prepared:"prepared",Live:"live",Closed:"closed"}),Qe=Object.freeze({Preparing:"preparing",Commit:"commit",Abort:"abort"}),ae=Object.freeze({Ok:"ok",Error:"error"}),K=Object.freeze({Bigint:"bigint",Bytes:"bytes",Object:"object"}),je=Object.freeze({Json:"tembra-json/1",MessagePack:"tembra-msgpack/1"});function f(e,t,n){return Object.freeze({code:e,reason:t,message:n})}var c=Object.freeze({Cancelled:Object.freeze({EngineEffect:f(l.Cancelled,u.EngineEffect,"The engine effect was cancelled"),Request:f(l.Cancelled,u.Request,"The request was cancelled"),Resource:f(l.Cancelled,u.Resource,"Resource opening was cancelled"),Root:f(l.Cancelled,u.Root,"The operation was cancelled"),Task:f(l.Cancelled,u.Task,"The task was cancelled")}),Closed:Object.freeze({Host:f(l.Closed,u.Host,"The host is closing")}),Conflict:Object.freeze({AlreadyCommitted:f(l.Conflict,u.AlreadyCommitted,"The replacement is already committed"),Codec:f(l.Conflict,u.Codec,"The Rust and JS host codecs must agree"),PrepareDeadline:f(l.Conflict,u.PrepareDeadline,"The preparation deadline expired"),ReloadRunning:f(l.Conflict,u.ReloadRunning,"A replacement is already running"),ReloadTicket:f(l.Conflict,u.ReloadTicket,"The replacement is no longer prepared")}),Exhausted:Object.freeze({FrameSize:f(l.Exhausted,u.FrameSize,"The frame exceeds the configured size limit"),PendingRequests:f(l.Exhausted,u.PendingRequests,"The pending request limit was reached"),RemoteReferences:f(l.Exhausted,u.RemoteReferences,"The remote reference limit was reached"),RequestIds:f(l.Exhausted,u.RequestIds,"Request identities are exhausted"),SubscriptionQueue:f(l.Exhausted,u.SubscriptionQueue,"The subscription queue is full")}),Expired:Object.freeze({Next:f(l.Expired,u.Next,"Continuation scope has ended")}),Forbidden:Object.freeze({Context:f(l.Forbidden,u.Context,"An issued context from this host is required"),HostResource:f(l.Forbidden,u.HostResource,"The host resource was not declared"),Method:f(l.Forbidden,u.Method,"The method is not allowed by this reference"),ObservationSource:f(l.Forbidden,u.ObservationSource,"Hook observation requires the original physical invocation"),Opaque:f(l.Forbidden,u.Opaque,"The resource is not available as an opaque local value"),Service:f(l.Forbidden,u.Service,"Access to this service is forbidden"),StateOwner:f(l.Forbidden,u.StateOwner,"Only the owning orb may change this state"),UndeclaredDependency:f(l.Forbidden,u.UndeclaredDependency,"The dependency was not declared"),UndeclaredService:f(l.Forbidden,u.UndeclaredService,"The service was not declared as a dependency")}),Gone:Object.freeze({Connection:f(l.Gone,u.Connection,"The connection is closed"),Contribution:f(l.Gone,u.Contribution,"The contribution is no longer available"),Implementation:f(l.Gone,u.Implementation,"The implementation is no longer available"),ListenerCallback:f(l.Gone,u.ListenerCallback,"The listener callback is no longer available"),Reference:f(l.Gone,u.Reference,"The reference is no longer available"),Resource:f(l.Gone,u.Resource,"The resource is no longer available"),Scope:f(l.Gone,u.Scope,"The declaration scope is no longer available"),State:f(l.Gone,u.State,"State owner is gone")}),Invalid:Object.freeze({Address:f(l.Invalid,u.Address,"Invalid address"),AsyncFactory:f(l.Invalid,u.AsyncFactory,"Factories must be synchronous"),AsyncState:f(l.Invalid,u.AsyncState,"State updates and migrations must be synchronous"),CoordinationLimits:f(l.Invalid,u.CoordinationLimits,"Invalid coordination limits"),DependencyCycle:f(l.Invalid,u.DependencyCycle,"Orb factories cannot acquire their own services"),DependencyService:f(l.Invalid,u.DependencyService,"Invalid dependency service"),DuplicateListener:f(l.Invalid,u.DuplicateListener,"Invalid duplicate listener"),DuplicateResource:f(l.Invalid,u.DuplicateResource,"Invalid duplicate resource"),EventSource:f(l.Invalid,u.EventSource,"Invalid event source"),Orb:f(l.Invalid,u.Orb,"An orb needs a name and positive API version"),OrbGone:f(l.Invalid,u.OrbGone,"Invalid orb gone"),OrbInstalled:f(l.Invalid,u.OrbInstalled,"Use reload to replace an installed orb"),Factory:f(l.Invalid,u.Factory,"Invalid factory"),FactoryExpired:f(l.Invalid,u.FactoryExpired,"Declarations must be synchronous"),Hook:f(l.Invalid,u.Hook,"Hooks need a run function"),HookDependency:f(l.Invalid,u.HookDependency,"Invalid hook dependency"),HooksDisabled:f(l.Invalid,u.HooksDisabled,"Invalid hooks disabled"),JsonAccessor:f(l.Invalid,u.JsonAccessor,"Invalid json accessor"),JsonCycle:f(l.Invalid,u.JsonCycle,"Invalid json cycle"),JsonNumber:f(l.Invalid,u.JsonNumber,"Use BigInt for integers outside the safe Number range"),JsonSymbol:f(l.Invalid,u.JsonSymbol,"Invalid json symbol"),JsonTag:f(l.Invalid,u.JsonTag,"Unknown or malformed portable type tag"),JsonType:f(l.Invalid,u.JsonType,"Supply a codec for custom object types"),JsonValue:f(l.Invalid,u.JsonValue,"This JSON codec requires explicit portable values"),Method:f(l.Invalid,u.Method,"Methods must be functions"),NextUsed:f(l.Invalid,u.NextUsed,"Invalid next used"),Priority:f(l.Invalid,u.Priority,"Invalid priority"),Reference:f(l.Invalid,u.Reference,"An issued local reference is required"),Resource:f(l.Invalid,u.Resource,"Invalid resource"),ResourceHost:f(l.Invalid,u.ResourceHost,"Resource dependencies must belong to the same host"),ResourceInFactory:f(l.Invalid,u.ResourceInFactory,"Resources open after declaration"),RpcFrame:f(l.Invalid,u.RpcFrame,"Invalid rpc frame"),RpcOperation:f(l.Invalid,u.RpcOperation,"Invalid rpc operation"),RpcRequest:f(l.Invalid,u.RpcRequest,"Invalid rpc request"),Service:f(l.Invalid,u.Service,"Invalid service"),ServiceGone:f(l.Invalid,u.ServiceGone,"Invalid service gone"),State:f(l.Invalid,u.State,"Service does not expose state"),StateCycle:f(l.Invalid,u.StateCycle,"State cannot contain cycles"),StateValidation:f(l.Invalid,u.StateValidation,"The orb rejected the state candidate"),StateValue:f(l.Invalid,u.StateValue,"State cannot contain accessors"),StateVersion:f(l.Invalid,u.StateVersion,"Invalid state version"),SubscriptionsDisabled:f(l.Invalid,u.SubscriptionsDisabled,"Invalid subscriptions disabled"),SubscriptionSize:f(l.Invalid,u.SubscriptionSize,"A local byte budget requires an explicit sizeOf function"),Task:f(l.Invalid,u.Task,"Invalid task"),Utf8:f(l.Invalid,u.Utf8,"Invalid utf8"),ValueGone:f(l.Invalid,u.ValueGone,"Invalid value gone"),ValuesExhausted:f(l.Invalid,u.ValuesExhausted,"Invalid values exhausted")}),Released:Object.freeze({Reference:f(l.Released,u.Reference,"The reference has been released")}),Unavailable:Object.freeze({Callback:f(l.Unavailable,u.Callback,"A callback failed"),OrbScope:f(l.Unavailable,u.OrbScope,"The orb scope is unavailable"),NotReady:f(l.Unavailable,u.NotReady,"The object is not ready"),Route:f(l.Unavailable,u.Route,"The route is unavailable")}),Unsupported:Object.freeze({EngineEffect:f(l.Unsupported,u.EngineEffect,"The engine effect is not supported by this adapter"),RemoteOpaque:f(l.Unsupported,u.RemoteOpaque,"Opaque resources are local to their language environment"),Telemetry:f(l.Unsupported,u.Telemetry,"Telemetry is disabled in this kernel"),Views:f(l.Unsupported,u.Views,"Reference views are disabled in this kernel")})});var He=new Set(Object.values(l));function Me(e){return typeof e==="object"&&e!==null&&"code"in e&&He.has(e.code)&&"reason"in e&&typeof e.reason==="string"&&"message"in e&&typeof e.message==="string"}class b extends Error{code;reason;constructor(e,t=e.message,n){super(t,n);this.name="TembraError",this.code=e.code,this.reason=e.reason}}function z(e){let t=c.Unavailable.Callback.message;try{if(e instanceof b)return e;if(Me(e))return new b(e,e.message,{cause:e});t=String(e instanceof Error?e.message:e)}catch{}return new b(c.Unavailable.Callback,t,{cause:e})}function h(e,t=e.message){throw new b(e,t)}var B="$tembra";function ce(e,t){if(typeof e==="bigint")return{[B]:[K.Bigint,e.toString()]};if(e instanceof Uint8Array)return{[B]:[K.Bytes,[...e]]};if(e===null||typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber,"Use BigInt for integers outside the safe Number range");return e}if(typeof e!=="object")h(c.Invalid.JsonValue,"This JSON codec requires explicit portable values");if(t.has(e))h(c.Invalid.JsonCycle);let n=Object.getPrototypeOf(e);if(!Array.isArray(e)&&n!==Object.prototype&&n!==null)h(c.Invalid.JsonType,"Supply a codec for custom object types");t.add(e);try{if(Array.isArray(e))return Array.from(e,(r)=>ce(r,t));let o=Reflect.ownKeys(e).map((r)=>{if(typeof r!=="string")h(c.Invalid.JsonSymbol);let s=Object.getOwnPropertyDescriptor(e,r);if(!Object.hasOwn(s,"value"))h(c.Invalid.JsonAccessor);return[r,ce(s.value,t)]});return Object.hasOwn(e,B)?{[B]:[K.Object,o]}:Object.fromEntries(o)}finally{t.delete(e)}}function ne(e){if(e===null||typeof e!=="object"){if(typeof e==="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber);return e}if(Array.isArray(e))return e.map(ne);if(Object.hasOwn(e,B)){let t=e[B];if(Object.keys(e).length!==1||!Array.isArray(t)||t.length!==2)h(c.Invalid.JsonTag);let[n,o]=t;if(n===K.Bigint&&typeof o==="string"&&/^-?(0|[1-9]\d*)$/.test(o))return BigInt(o);if(n===K.Bytes&&Array.isArray(o)&&o.every((r)=>Number.isInteger(r)&&r>=0&&r<=255))return Uint8Array.from(o);if(n===K.Object&&Array.isArray(o)){if(!o.every((r)=>Array.isArray(r)&&r.length===2&&typeof r[0]==="string"))h(c.Invalid.JsonTag);return Object.fromEntries(o.map(([r,s])=>[r,ne(s)]))}h(c.Invalid.JsonTag,"Unknown or malformed portable type tag")}return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ne(n)]))}function Ke(e){let t=[];for(let n of e){let o=n.codePointAt(0);if(o>=55296&&o<=57343)o=65533;if(o<128)t.push(o);else if(o<2048)t.push(192|o>>6,128|o&63);else if(o<65536)t.push(224|o>>12,128|o>>6&63,128|o&63);else t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}return Uint8Array.from(t)}function Ue(e){let t=[];for(let n=0;n<e.length;){let o=e[n++];if(o<128){t.push(String.fromCharCode(o));continue}let r=o>=194&&o<=223?1:o>=224&&o<=239?2:o>=240&&o<=244?3:-1;if(r<0||n+r>e.length)h(c.Invalid.Utf8);let s=o&127>>r+1;for(let a=0;a<r;a++){let i=e[n++];if((i&192)!==128)h(c.Invalid.Utf8);s=s<<6|i&63}if(s<[0,128,2048,65536][r]||s>1114111||s>=55296&&s<=57343)h(c.Invalid.Utf8);t.push(String.fromCodePoint(s))}return t.join("")}var W=Object.freeze({id:je.Json,serialize:(e)=>Ke(JSON.stringify(ce(e,new WeakSet))),deserialize:(e)=>ne(JSON.parse(Ue(e)))});var D=Object.freeze({Text:"text",Integer:"integer",Boolean:"boolean",Opaque:"opaque"});class U{name;version;kind;constructor(e,t,n){this.name=e;this.version=t;this.kind=n;Object.freeze(this)}static text(e,t=1){return new U(e,t,D.Text)}static integer(e,t=1){return new U(e,t,D.Integer)}static boolean(e,t=1){return new U(e,t,D.Boolean)}static opaque(e,t=1){return new U(e,t,D.Opaque)}source(e,t){if(this.kind!==D.Opaque)return;let n=typeof e==="object"&&e!==null?t.session.contextTokens.get(e):void 0;if(!n||n.root!==t.root)throw TypeError("An owner-issued opaque reference from this host and root is required");return n.source}}function de(e,t,n){let o=e.session.kernel.command(d.ContextValue,{root:e.root,context:n,call:e.invocation?.id,key:t});if(!o)return;if(o.kind!==D.Opaque)return o.value;let r=Object.freeze({opaque:!0});return e.session.contextTokens.set(r,{root:e.root,source:o.source}),r}function Ee(e,t,n){let o=de(e,t,n);if(!o)throw TypeError("The owner did not issue a reference");return o}var Ie=Symbol.for("@syntropika/tembra-sdk/service-identities"),Q=Object.getOwnPropertyDescriptor(globalThis,Ie)?.value;if(Q!==void 0&&!(Q instanceof WeakMap))throw TypeError("The SDK service identity slot must contain a WeakMap");var X=Q instanceof WeakMap?Q:new WeakMap;if(Q===void 0)Object.defineProperty(globalThis,Ie,{value:X});function Pe(e,t,n){let o=new Map;for(let[r,s,a]of n){let i={orb:e,name:r,apiVersion:t};for(let p of[s,a]){let m=o.get(p)??X.get(p);if(m&&(m.orb!==e||m.name!==r||m.apiVersion!==t))h(c.Invalid.Service,"A service definition must have one orb, name and API version");o.set(p,i)}}for(let[r,s]of o)X.set(r,s)}function Y(e,t={}){if(typeof e==="string")return{name:e,options:t};let n=X.get(e);if(!n)h(c.Invalid.Service,"Declare this service in an orb before acquiring it");if(t.apiVersion!==void 0&&t.apiVersion!==n.apiVersion)h(c.Invalid.Service,"The acquisition API version must match the service declaration");return{name:n.name,options:{...t,apiVersion:n.apiVersion}}}function le(e){if(!e.name||!Number.isInteger(e.apiVersion)||e.apiVersion<=0)h(c.Invalid.Orb,"An orb needs a name and positive API version");let t=Object.fromEntries(Object.entries(e.services??{}).map(([a,i])=>{if(!a||!i.methods||typeof i.methods!=="object")h(c.Invalid.Service);if(i.create&&typeof i.create!=="function")h(c.Invalid.Factory);for(let m of Object.values(i.methods))if(typeof m!=="function")h(c.Invalid.Method,"Methods must be functions");let p={...i,methods:Object.freeze({...i.methods})};return[a,Object.freeze(p)]})),n=Object.fromEntries(Object.entries(e.requires??{}).map(([a,i])=>[a,Object.freeze({...i,...i.methods?{methods:Object.freeze([...i.methods])}:{},...i.hooks?{hooks:Object.freeze([...i.hooks])}:{},...i.services?{services:Object.freeze(Object.fromEntries(Object.entries(i.services).map(([p,m])=>[p,Object.freeze([...m])])))}:{}})])),o=Object.fromEntries(Object.entries(e.hooks??{}).map(([a,i])=>{if(typeof i.run!=="function")h(c.Invalid.Hook,"Hooks need a run function");return[a,Object.freeze({...i,capabilities:Object.freeze([...i.capabilities??[]])})]})),r=Object.fromEntries(Object.entries(e.contributes??{}).map(([a,i])=>[a,Object.freeze(Object.fromEntries(Object.entries(i).map(([p,m])=>[p,typeof m==="function"?m:Object.freeze({...m})])))])),s=Object.freeze({...e,services:Object.freeze(t),requires:Object.freeze(n),hooks:Object.freeze(o),contributes:Object.freeze(r)});return Pe(e.name,e.apiVersion,Object.entries(e.services??{}).map(([a,i])=>[a,i,t[a]])),s}class pe{allocate;#e=1;#t=new Map;constructor(e){this.allocate=e}put(e){if(this.#e>4294967295)h(c.Invalid.ValuesExhausted);let t=this.allocate?this.allocate():this.#e++;return this.#t.set(t,e),t}get(e){if(!this.#t.has(e))h(c.Invalid.ValueGone);return this.#t.get(e)}drop(e){this.#t.delete(e)}has(e){return this.#t.has(e)}set(e,t){this.#t.set(e,t)}clear(){this.#t.clear()}get size(){return this.#t.size}}var De=new WeakSet;function Z(e){let t=new WeakSet;function n(o){if(o===null||typeof o!=="object"){if(["function","symbol"].includes(typeof o))h(c.Invalid.StateValue,"State must contain plain data");return}if(De.has(o))return;if(t.has(o))h(c.Invalid.StateCycle,"State cannot contain cycles");let r=Object.getPrototypeOf(o);if(!Array.isArray(o)&&r!==Object.prototype&&r!==null)h(c.Invalid.StateValue,"State requires plain objects and arrays");t.add(o);for(let s of Reflect.ownKeys(o)){if(typeof s!=="string")h(c.Invalid.StateValue,"State cannot contain symbol properties");let a=Object.getOwnPropertyDescriptor(o,s);if(!Object.hasOwn(a,"value"))h(c.Invalid.StateValue,"State cannot contain accessors");n(a.value)}t.delete(o),Object.freeze(o),De.add(o)}return n(e),e}class oe{compute;report;check;#e;#t=new Set;#n=new Set;#o=!0;#r;#s;#i;constructor(e,t,n,o){this.compute=e;this.report=n;this.check=o;this.#e=Z(e(t))}get value(){return this.check(),this.#e}track(e,t){this.#r=e,this.#i=t;let n=new WeakRef(this);this.#s=()=>n.deref()?.detach(),e?.add(this.#s)}detach(){if(!this.#o)return;if(this.#o=!1,this.#s)this.#r?.delete(this.#s);this.#i?.(),this.#t.clear();for(let e of this.#n)e.deref()?.detach();this.#n.clear()}prepare(e){if(!this.#o)return;try{this.check()}catch{this.detach();return}let t;try{t=Z(this.compute(e))}catch(o){this.detach(),this.report(o);return}if(!this.#o)return;let n=[];if(!Object.is(t,this.#e))for(let o of this.#n){let s=o.deref()?.prepare(t);if(s)n.push(s);else this.#n.delete(o)}return{adopt:()=>{if(!this.#o||Object.is(t,this.#e))return()=>{};this.#e=t;let o=n.map((s)=>s.adopt()),r=[...this.#t];return()=>{if(!this.#o)return;for(let s of o)s();for(let s of r)try{s(t)}catch(a){this.report(a)}}}}}select(e){this.check();let t=new oe(e,this.#e,this.report,this.check);this.check();let n=new WeakRef(t);return this.#n.add(n),t.track(this.#r,()=>this.#n.delete(n)),t}subscribe(e){this.check(),this.#t.add(e);try{e(this.#e)}catch(t){this.report(t)}return()=>{this.#t.delete(e)}}}class L{backend;object;closed=!1;#e;#t=new Set;#n=new Set;constructor(e,t,n){this.backend=e;this.object=t;this.#e=arguments.length>=3?n:e.value(e.snapshot(t).value)}check(){if(this.closed)throw new b(c.Gone.State,"State owner is gone")}get value(){return this.check(),this.#e}view(e,t=()=>this.check()){let n=this;return{get value(){return t(),n.value},update(o,r){t(),n.backend.check(o,n.object);let s=n.backend.snapshot(n.object),a=n.backend.value(s.value),i=r(a);if(F(i,e),n.backend.check(o,n.object),Object.is(i,a))return a;let p=n.prepare(i);n.backend.adopt(n.object,o,s.revision,i);let m=n.adopt(p,i);return n.backend.publish(m),i},select:(o)=>(t(),n.select(o,t)),subscribe:(o)=>(t(),n.subscribe(o))}}select(e,t=()=>this.check(),n){t();let o=new oe(e,this.value,(s)=>this.backend.report(s),t);t();let r=new WeakRef(o);return this.#n.add(r),o.track(n,()=>this.#n.delete(r)),o}subscribe(e){this.check(),this.#t.add(e);try{e(this.value)}catch(t){this.backend.report(t)}return()=>{this.#t.delete(e)}}prepare(e){let t=[];for(let n of this.#n){let r=n.deref()?.prepare(e);if(r)t.push(r);else this.#n.delete(n)}return t}adopt(e,t){this.#e=t;let n=e.map((r)=>r.adopt()),o=[...this.#t];return()=>{for(let r of n)r();for(let r of o)try{r(t)}catch(s){this.backend.report(s)}}}close(){this.closed=!0,this.#e=void 0,this.#t.clear();for(let e of this.#n)e.deref()?.detach();this.#n.clear()}}function F(e,t){if(e&&typeof e.then==="function")h(c.Invalid.AsyncState,"State updates and migrations must be synchronous");let n=Z(e),o=t.validate?.(n);if(o!==void 0&&o!==!0)h(c.Invalid.StateValidation,"Orb rejected the candidate state");return n}class H{session;environment;constructor(e,t){this.session=e;this.environment=t}check(){if(this.environment.phase!==S.Declaring)h(c.Invalid.FactoryExpired,"Declarations must be synchronous")}get principal(){return this.session.principalFor(this.environment.object?.id??0)}get orb(){return this.environment.orb.scope?.value}get key(){return this.environment.object?.address.key??["main"]}state(e,t={}){this.check();let n=this.environment,o=n.object;if(!o||n.state)h(c.Invalid.State,"An object declares exactly one state");let r=t.version??1;if(!Number.isInteger(r)||r<=0)h(c.Invalid.StateVersion);let s=o.binding;if(!s&&o.live)s=new L(this.session,o.id,F(e,t));if(!s){let i=F(e,t),p=this.session.values.put(i);try{this.session.kernel.command(d.StateInit,{object:o.id,value:p,version:r})}catch(m){throw this.session.values.drop(p),m}o.binding=s=new L(this.session,o.id)}let a=s.view(t);return n.state={initial:e,options:t,binding:s},a}get(e,t,n={}){this.check();let o=Y(e,n),r=this.session.scopes.requirement(this.environment,o.name),s=r.service;if(typeof e!=="string"&&s!==o.name)h(c.Invalid.Service,"A typed dependency must resolve its declared service name");if(!this.environment.object&&this.environment.orb.definition.services?.[s])h(c.Invalid.DependencyCycle);let a=Y(e,{...n,...r.apiVersion?{apiVersion:r.apiVersion}:{},...r.methods?{methods:r.methods}:{},principal:n.principal??this.principal}),i=JSON.stringify([s,t,n.principal??this.principal]),p=this.environment.dependencies.get(i);if(p)return p;let m=this.session.handles.hold(s,t,a.options);if(this.environment.object)try{this.session.kernel.command(d.Dependency,{object:this.environment.object.id,reference:this.session.handles.reference(m).id})}catch(y){throw m.release(),y}return this.environment.dependencies.set(i,m),m}resource(e,t){if(this.check(),!t)return this.session.scopes.hostResource(e);if(this.environment.resources.has(e))h(c.Invalid.DuplicateResource,e);let n=this.session.resources.declare(this.environment,e,t);return this.environment.resources.set(e,n),n.handle}task(e){if(this.check(),typeof e!=="function")h(c.Invalid.Task);this.environment.tasks.push({start:e})}on(e,t,n,o={}){if(this.check(),!this.session.kernel.features.subscriptions)h(c.Invalid.SubscriptionsDisabled);if(o.maxBytes!==void 0&&!o.sizeOf)h(c.Invalid.SubscriptionSize,"A local byte budget requires an explicit sizeOf function");if(!e||this.environment.listeners.some((r)=>r.name===e))h(c.Invalid.DuplicateListener,e);this.environment.listeners.push({name:e,source:t,handle:n,options:o})}hook(e){if(this.check(),!this.session.kernel.features.hooks)h(c.Invalid.HooksDisabled);if(!this.environment.orb.definition.hooks?.[e])h(c.Invalid.Hook,e);let t=this.session.kernel.command(d.Allocate);return{run:(n,o)=>this.session.orbs.runHook(this.environment,e,n,o),observe:(n,o)=>this.session.orbs.observe(this.environment,e,t,n,o)}}}function _e(e,t,n){return{get value(){return t(),e.value},select(o){return t(),e.select(o,t,n)},subscribe(o){t();let r=e.subscribe((i)=>{try{t()}catch{return}o(i)}),s=!0,a=()=>{if(!s)return;s=!1,n.delete(a),r()};n.add(a);try{t()}catch{a()}return a}}}class ue{port;features;constructor(e){this.port=e;this.features=this.command(d.Features)}command(e,t={}){let n=JSON.parse(this.port.request(JSON.stringify({...t,op:e})));if(n.error)throw new b(n.error);return n.ok}}class fe{capacity;sampleEvery;#e=[];#t=0;constructor(e=256,t=1){this.capacity=e;this.sampleEvery=t;if(!Number.isInteger(e)||e<=0||!Number.isInteger(t)||t<=0)throw RangeError("Invalid telemetry limits")}sample(){return this.#t++%this.sampleEvery===0}record(e){if(this.#e.length===this.capacity)this.#e.shift();this.#e.push(e)}drain(){return this.#e.splice(0)}}class me{session;tasks=new Map;listeners=new Map;#e=new WeakMap;constructor(e){this.session=e}prepare(e,t){for(let n of e.listeners){let o=typeof n.source==="function"?n.source():n.source;if(!o||typeof o.subscribe!=="function")h(c.Invalid.EventSource);let r=this.session.kernel.command(d.Listen,{scope:e.id,previous:t?.id,name:n.name,source:this.identity(o),sizing:n.options.sizeOf?this.identity(n.options.sizeOf):0,operation:this.session.kernel.command(d.Allocate),maxPending:n.options.maxPending??64,...n.options.maxBytes?{maxBytes:n.options.maxBytes}:{},coalesce:"select"in o}),s=this.listeners.get(r);if(s){n.running=s;continue}let a={id:r,definition:n,environment:e,stopped:!1,detach(){}};n.running=a,this.listeners.set(r,a);try{if(a.detach=o.subscribe((i)=>{if(a.stopped)return;let p=this.session.values.put(i);try{let m=n.options.sizeOf?.(i)??0;if(!Number.isSafeInteger(m)||m<0||m>4294967295)throw new b(c.Invalid.SubscriptionSize);this.session.kernel.command(d.Enqueue,{subscription:r,payload:p,bytes:m})}catch(m){this.session.values.drop(p),this.session.report(m),this.failed(r)}this.session.lifecycle.flush()}),a.stopped)a.detach()}catch(i){throw this.stopListener(a),i}}}start(e){e.phase=S.Live;for(let t of e.listeners){let n=t.running;n.environment=e,n.definition=t}for(let t of e.tasks)this.startTask(e,t)}startTask(e,t){if(t.running||e.phase!==S.Live||this.session.closing)return;let n=this.session.kernel.command(d.Task,{owner:e.owner}),o=new AbortController,r=this.session.kernel.command(d.Allocate),s={id:n,controller:o,done:Promise.resolve()};t.running=s,this.tasks.set(n,s),s.done=this.session.track(Promise.resolve().then(async()=>{try{await t.start({signal:o.signal,root:(a)=>{let i=this.session.kernel.command(d.TaskRoot,{task:n,principal:this.session.principalFor(e.object?.id??0)});return this.session.calls.root(()=>this.session.calls.owned(e,r,a,i),!1,i)}})}catch(a){if(!o.signal.aborted)this.session.report(a)}finally{this.session.kernel.command(d.Tick,{now:this.session.now()}),this.session.kernel.command(d.FinishTask,{task:n}),this.tasks.delete(n),delete t.running,this.session.lifecycle.flush()}}))}identity(e){let t=this.#e.get(e);if(t===void 0)t=this.session.kernel.command(d.Allocate),this.#e.set(e,t);return t}deliver(e,t,n){let o=this.listeners.get(e),r=Promise.resolve().then(async()=>{try{if(!o)throw new b(c.Gone.ListenerCallback);await this.session.calls.owned(o.environment,n,(s)=>o.definition.handle(s,this.session.values.get(t)))}catch(s){this.session.report(s)}finally{this.session.kernel.command(d.FinishDelivery,{subscription:e}),this.session.lifecycle.flush()}});if(o)o.done=r;this.session.track(r)}detach(e){let t=this.listeners.get(e);if(t)this.stopListener(t)}cancel(e){this.tasks.get(e)?.controller.abort(new b(c.Cancelled.Task))}failed(e){let t=this.listeners.get(e);if(!t)return;this.session.report(new b(c.Exhausted.SubscriptionQueue)),this.stopListener(t)}stopListener(e){if(e.stopped)return;e.stopped=!0;try{e.detach()}catch(t){this.session.report(t)}this.session.kernel.command(d.Unsubscribe,{subscription:e.id}),this.listeners.delete(e.id),this.session.lifecycle.flush()}async stop(e){for(let t of e.tasks)if(t.running)this.session.kernel.command(d.StopTask,{task:t.running.id});this.session.lifecycle.flush(),await Promise.all(e.tasks.map((t)=>t.running?.done)),await Promise.all(e.listeners.map((t)=>t.running?.done))}}var re=new WeakMap;class _{session;root;invocation;frame;constructor(e,t,n,o=0){this.session=e;this.root=t;this.invocation=n;this.frame=o;re.set(this,this)}with(e,t){let n=e.source(t,this),o=this.session.kernel.command(d.ContextDerive,{root:this.root,context:this.frame,call:this.invocation?.id,key:e,...e.kind===D.Opaque?{source:n}:{value:t}});return new _(this.session,this.root,this.invocation,o)}value(e){return de(this,e,this.frame)}exportValues(e){let t={};for(let n of e){if(n.kind===D.Opaque)throw TypeError("Local opaque references cannot be exported");let o=this.value(n);if(o!==void 0)t[`${n.name}@${n.version}`]=o}return t}get principal(){return this.session.kernel.command(d.RootPrincipal,{root:this.root})}get signal(){return this.session.calls.signal(this.root)}check(){this.session.kernel.command(d.CheckContext,{root:this.root,call:this.invocation?.id})}cancel(){this.session.kernel.command(d.CancelRoot,{root:this.root}),this.session.lifecycle.flush()}get(e,t,n={}){return this.check(),this.session.handles.get(e,t,n,this)}resource(e){return this.check(),this.session.scopes.hostResource(e)}}function he(e,t){if(typeof e!=="object"||e===null||re.get(e)?.session!==t)throw new b(c.Forbidden.Context,"An issued context from this host is required");return re.get(e)}function V(e,t){let n=he(e,t);return n.check(),n}function Ae(e){return typeof e==="object"&&e!==null&&re.has(e)}class be{session;#e=new Set;constructor(e){this.session=e}interrupt(){let e=new b({code:l.Closed,reason:"javascript",message:"JavaScript execution was interrupted"});for(let t of this.#e)t(e);this.#e.clear()}async execute(e){let t,n,o=new Promise((r,s)=>{t=(a)=>{n=a,s(a)}});this.#e.add(t);try{return await Promise.race([Promise.resolve().then(()=>{if(n)throw n;return e()}),o])}finally{this.#e.delete(t)}}signal(e){let t=this.session,n=t.controllers.get(e);if(!n){n=new AbortController;try{t.kernel.command(d.CheckRoot,{root:e})}catch(o){if(!(o instanceof b)||o.code!==l.Cancelled)throw o;n.abort(o)}t.controllers.set(e,n)}return n.signal}releaseRoot(e){for(let t of this.session.rootReferences.get(e)??[])this.session.handles.release(t);this.session.rootReferences.delete(e),this.session.controllers.delete(e)}async root(e,t=!1,n,o=this.session.principal){let r=this.session,s=n??r.kernel.command(t?d.CleanupRoot:d.Root,{principal:o}),a=new _(r,s);try{return await e(a)}finally{if(this.releaseRoot(s),r.options.native?.rootEnded?.(s),!r.lifecycle.closedDiagnostics)r.kernel.command(d.EndRoot,{root:s});r.controllers.delete(s),r.lifecycle.flush()}}async invoke(e,t,n,o){let r=this.session;if(V(o,r),e.released)throw new b(c.Released.Reference);await e.ready;let s=r.options.native?.admit?.(e.id,t,o),a;if(s)a=s.call;else o.check(),a=r.kernel.command(d.BeginCall,{reference:e.id,root:o.root,context:o.frame||void 0,method:t});let i=new _(r,o.root,a,o.frame),p=r.track((async()=>{let m=r.telemetry?.sample(),y=m?r.now():0,v=ae.Ok;try{let g=r.options.native;if(g&&(s?.native??g.hasOrb(a.orb)))return await g.invoke(a,n,i);let R=r.objects.get(a.object)?.versions.get(a.orb),x=R?.orb.definition.services?.[e.address.service]?.methods[t];if(!R||!x)throw new b(c.Gone.Implementation);return await this.execute(()=>x(R.value,i,...n))}catch(g){throw v=ae.Error,g}finally{if(m)r.telemetry.record({service:e.address.service,method:t,root:a.root,codeVersion:a.codeVersion,duration:r.now()-y,outcome:v});r.lifecycle.finishCall(a.id)}})());return this.observe(p,o.signal)}async owned(e,t,n,o){let r=this.session,s=async(a)=>{let i=r.kernel.command(d.BeginOperation,{orb:e.orb.info.id,root:a.root,context:a.frame||void 0,operation:t,...e.object?{object:e.object.id}:{}});try{return await this.execute(()=>n(new _(r,a.root,i,a.frame)))}finally{r.kernel.command(d.FinishCall,{call:i.id}),r.lifecycle.flush()}};return o===void 0?this.root(s,!1,void 0,r.principalFor(e.object?.id??0)):s(typeof o==="number"?new _(r,o):o)}async observe(e,t){if(t.aborted)throw t.reason;let n,o=new Promise((r,s)=>{n=()=>s(t.reason??new b(c.Cancelled.Root)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,o])}finally{t.removeEventListener("abort",n)}}}class ve{session;records=new Map;operations=new Map;#e=new Map;#t=new Map;constructor(e){this.session=e}declarations(e){let t=e.map((s)=>le(s)),n=this.session.kernel.command(d.Orbs),o=(s)=>t.find((a)=>a.name===s),r=t.map((s)=>{if(!this.session.kernel.features.views&&Object.values(s.services??{}).some((i)=>i.access))throw new b(c.Unsupported.Views);let a=Object.entries(s.requires??{}).map(([i,p])=>{let m=p.orb??i,y=o(m),v=n.find((R)=>R.name===m),g=y?Object.keys(y.services??{}):v?.services.map((R)=>R.name)??[],k=g.includes(i)?i:g.length===1?g[0]:void 0;if(p.methods&&!k)h(c.Invalid.DependencyService,`Use explicit services for ${m}`);return{orb:m,apiVersion:p.apiVersion,services:p.services??(p.methods?{[k]:p.methods}:{}),hooks:p.hooks??[]}});for(let[i,p]of Object.entries(s.contributes??{})){let m=s.requires?.[i];if(!m)h(c.Invalid.HookDependency,i);for(let[y,v]of Object.entries(p)){if(!m.hooks?.includes(y))h(c.Invalid.HookDependency,y);let g=typeof v==="function"?0:v.priority??0;if(!Number.isInteger(g)||g<-2147483648||g>2147483647)h(c.Invalid.Priority)}}return{name:s.name,apiVersion:s.apiVersion,requires:a,hooks:Object.keys(s.hooks??{}),services:Object.entries(s.services??{}).map(([i,p])=>({name:i,methods:Object.keys(p.methods),lifetime:p.lifetime??G.Referenced,linger:p.linger??0}))}});return{definitions:t,metadata:r}}async install(e){let t=this.session.kernel.command(d.Orbs);if(e.some((s)=>t.some((a)=>a.name===s.name)))h(c.Invalid.OrbInstalled,"Use reload to replace an installed orb");let n=this.declarations(e),o=this.session.kernel.command(d.Prepare,{orbs:n.metadata});this.session.kernel.command(d.Commit,{ticket:o.id});let r=o.orbs.map((s)=>({info:s,definition:n.definitions.find((a)=>a.name===s.name)}));for(let s of r)this.records.set(s.info.id,s);for(let s of r)this.registerContributions(s);await Promise.all(r.map((s)=>this.ready(s)));for(let s of r)for(let a of s.info.services.filter((i)=>i.lifetime===G.Host))(await this.session.handles.get(a.name,"main",{principal:"host"})).release();this.session.lifecycle.flush()}scope(e){if(e.scope)return e.scope;let t=this.session.scopes.environment({kind:I.Orb,id:e.info.owner},e);e.scope=t;try{let n=e.definition.create?.(new H(this.session,t))??{};if(n&&typeof n.then==="function")h(c.Invalid.AsyncFactory);t.value=n}finally{t.phase=S.Prepared,this.session.programs.register(t)}return t}ready(e){if(e.scope?.phase===S.Live)return Promise.resolve();let t=this.#e.get(e.info.id);if(!t){t=(async()=>{try{if(await this.session.scopes.readyHostScope(),e.scope?.phase===S.Closed)delete e.scope;let o=this.scope(e);await this.session.programs.activate(o.id)}catch(o){if(e.scope)await this.session.programs.cleanup([e.scope]),delete e.scope;throw o}})(),this.#e.set(e.info.id,t);let n=()=>{if(this.#e.get(e.info.id)===t)this.#e.delete(e.info.id)};t.then(n,n)}return t}registerContributions(e){for(let[t,n]of Object.entries(e.definition.contributes??{})){let r=e.definition.requires[t].orb??t;for(let[s,a]of Object.entries(n)){let i=this.session.kernel.command(d.Allocate),p=JSON.stringify([e.info.name,r,s]);if(!this.#t.has(p))this.#t.set(p,this.session.kernel.command(d.ContributionOrdinal));this.operations.set(i,{orb:e,handler:typeof a==="function"?a:a.handle}),this.session.kernel.command(d.Contribute,{orb:e.info.id,target:r,hook:s,operation:i,priority:typeof a==="function"?0:a.priority??0,ordinal:this.#t.get(p)})}}}async runHook(e,t,n,o){n=V(n,this.session);let r=e.orb.definition.hooks?.[t];if(!r)h(c.Invalid.Hook,t);let a=this.session.kernel.command(d.HookPlan,{root:n.root,target:e.orb.info.name,hook:t}).map((i)=>async(p,m,y)=>this.runContribution(i,p,m,y));return r.run(n,o,a)}async observe(e,t,n,o,r){o=he(o,this.session);let s=e.orb.definition.hooks?.[t];if(!s)h(c.Invalid.Hook,t);if(!o.invocation)throw new b(c.Forbidden.ObservationSource);let a=this.session.kernel.command(d.BeginHookObservation,{source:o.invocation.id,orb:e.orb.info.id,operation:n,...e.object?{object:e.object.id}:{},hook:t});await this.session.track(this.session.calls.root(async()=>{try{let i=new _(this.session,a.invocation.root,a.invocation),p=a.plan.map((m)=>async(y,v,g)=>this.runContribution(m,y,v,g));await s.run(i,r,p)}finally{this.session.lifecycle.finishCall(a.invocation.id)}},!1,a.invocation.root))}async runContribution(e,t,n,o){t=V(t,this.session);let r=this.operations.get(e);if(!r){let a=this.session.options.native;if(a?.hasContribution?.(e)&&a.contribute)return a.contribute(e,t,n);throw new b(c.Gone.Contribution)}let s=r.orb.scope;if(!s)throw new b(c.Unavailable.OrbScope);return this.session.calls.owned(s,e,(a)=>r.handler(a,n,o),t)}retire(e){let t=this.session.kernel.command(d.ScopesForOrb,{orb:e}),n=this.session.programs.cleanupScopes(t);this.session.track(n.then(()=>{for(let[o,r]of this.operations)if(r.orb.info.id===e)this.operations.delete(o);this.records.delete(e),this.#e.delete(e)}),!0)}}class ye{session;constructor(e){this.session=e}get closedDiagnostics(){return this.#r}#e;#t=!1;#n;#o;#r;flush(e){if(this.#t)return;this.#t=!0;try{for(;;){let t=e??this.session.kernel.command(d.Drain);if(e=void 0,!t.length)break;for(let n of t)try{this.action(n)}catch(o){this.session.report(o)}}}finally{this.#t=!1,this.scheduleLinger()}}finishCall(e){let t=this.session;if(!this.#t&&t.options.native?.finish){let n=t.options.native.finish(e,t.now());if(!n.actions.length){this.scheduleLinger(n.deadline);return}this.flush(n.actions);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.FinishCall,{call:e}),this.flush()}action(e){let t=this.session;if(t.options.native?.notify?.(e)&&!(e.type===C.ProgramComplete&&t.programs.pending(e.id)))return;switch(e.type){case C.Execute:case C.CancelEffects:case C.ProgramPrepared:case C.ProgramComplete:t.programs.dispatch(e);break;case C.DropValue:t.values.drop(e.id),t.options.native?.dropValue?.(e.id);break;case C.CancelRoot:t.controllers.get(e.id)?.abort(new b(c.Cancelled.Root));break;case C.CancelTask:t.activities.cancel(e.id);break;case C.Deliver:t.activities.deliver(e.id,e.payload,e.operation);break;case C.DetachSubscription:t.activities.detach(e.id);break;case C.SubscriptionFailed:t.activities.failed(e.id);break;case C.Dispose:t.track(this.dispose(e.id),!0);break;case C.CloseResource:break;case C.RetireOrb:t.handles.retire(e.id),t.orbs.retire(e.id);break;case C.State:{let o=t.objects.get(e.id);if(!o?.binding)break;let r=t.snapshot(e.id);if(!t.values.has(r.value)){let s=t.value(r.value);t.publish(o.binding.adopt(o.binding.prepare(s),s))}break}}}async dispose(e){let t=this.session,n=t.objects.get(e);if(!n){await t.options.native?.dispose(e),t.kernel.command(d.Disposed,{object:e}),this.flush();return}return n.disposing??=(async()=>{let o=[];await n.activation.catch(()=>{});let r=t.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e}});try{await t.programs.cleanupScopes(r)}catch(s){o.push(s)}try{if(t.options.native?.hasOrb(n.orb))await t.options.native.dispose(e)}catch(s){o.push(s)}if(n.binding?.close(),t.kernel.command(d.Disposed,{object:e}),t.objects.delete(e),this.flush(),o.length)throw AggregateError(o,"Object cleanup failed")})(),n.disposing}scheduleLinger(e){let t=this.session;if(t.closing)return;let n=(e===void 0?t.kernel.command(d.NextDeadline):e)??void 0;if(n===this.#o)return;if(this.#n!==void 0)clearTimeout(this.#n);if(this.#n=void 0,this.#o=n,n===void 0)return;this.#n=setTimeout(()=>{if(this.#o!==n)return;this.#n=void 0,this.#o=void 0,t.kernel.command(d.Tick,{now:t.now()}),this.flush()},Math.max(0,n-t.now())),this.#n.unref?.()}diagnostics(){let e=this.session;if(this.#r)return this.#r;return{...e.kernel.command(d.Diagnostics),values:e.values.size,pendingJobs:e.jobs.size}}close(){let e=this.session;return this.#e??=(async()=>{e.closing=!0,clearTimeout(this.#n),this.#n=void 0,this.#o=void 0,e.kernel.command(d.Close),await e.replacements.cancel(),this.flush();for(;;){await e.options.native?.settled?.(),this.flush();let t=[...e.jobs];if(!t.length)break;await Promise.allSettled(t),this.flush()}if(e.kernel.command(d.FinishClose),e.values.clear(),e.handles.clear(),e.orbs.records.clear(),e.scopes.clear(),this.#r=this.diagnostics(),e.kernel.port.free?.(),e.cleanupErrors.length)throw AggregateError(e.cleanupErrors,"Host cleanup failed")})(),this.#e}}function ee(){let e,t,n=new Promise((o,r)=>{e=o,t=r});return n.catch(()=>{}),{promise:n,resolve:e,reject:t}}function Ve(e,t){return e.slice(0,t).replace(/[\uD800-\uDFFF]/gu,"�")}class ge{session;scopes=new Map;#e=new Map;constructor(e){this.session=e}register(e){let t=e.owner.kind===I.Host?void 0:e.object?e.orb.scope:this.session.hostScope;this.session.kernel.command(d.ScopeRegister,{scope:e.id,owner:e.owner,orb:e.orb.info.id,parents:t?[t.id]:[],dependencies:[...e.dependencies.values()].map((n)=>this.session.handles.reference(n).id),resources:[...e.resources.values()].map((n)=>n.id),stateVersion:e.state?.options.version??(e.state?1:void 0),migrate:Boolean(e.state?.options.migrate)})}activate(e){return this.run(this.session.kernel.command(d.ScopeActivate,{scope:e}))}cleanup(e){let t=e.map((n)=>n.id).filter((n)=>this.session.kernel.command(d.ScopeExists,{scope:n}));return this.cleanupScopes(t)}cleanupScopes(e){return e.length?this.run(this.session.kernel.command(d.ScopesCleanup,{scopes:e})):Promise.resolve()}pending(e){return this.#e.has(e)}run(e){let t=this.#e.get(e);if(t)return t.promise;let n=ee();this.#e.set(e,n);try{this.session.kernel.command(d.ProgramRun,{program:e}),this.session.lifecycle.flush()}catch(o){this.#e.delete(e),n.reject(o)}return n.promise}dispatch(e){if(e.type===C.Execute)this.session.track(Promise.allSettled(e.effects.map((t)=>this.execute(t))).then((t)=>{let n=Math.max(0,Math.min(2048,Math.floor((1048448-t.length*96)/(12*t.length)))),o=t.map((r)=>{if(r.status==="fulfilled")return{value:r.value??null};try{let{code:s,reason:a,message:i}=z(r.reason);if(!Object.values(l).includes(s)||typeof a!=="string"||typeof i!=="string")return{error:c.Unavailable.Callback};return{error:{code:s,reason:Ve(a,n),message:Ve(i,n)}}}catch{return{error:c.Unavailable.Callback}}});this.session.kernel.command(d.ProgramCompleteStep,{program:e.id,results:o}),this.session.lifecycle.flush()}));else if(e.type===C.CancelEffects)for(let t of e.effects){if(t.type!==j.Open&&t.type!==j.Restore)continue;let n=this.session.resources.find(t.resource);if(n)n.controller.abort(new b(c.Cancelled.EngineEffect));else if(this.session.options.native?.cancelEffect){let o=this.session.options.native.cancelEffect.bind(this.session.options.native);this.session.track(Promise.resolve().then(()=>o(t))).catch((r)=>this.session.report(r))}}else{let t=this.#e.get(e.id);if(this.#e.delete(e.id),e.error){let n=new b(e.error);if(t)t.reject(n);else this.session.cleanupErrors.push(n),this.session.report(n)}else t?.resolve()}}resource(e){let t=this.session.resources.find(e);if(t)return t;throw new b(c.Gone.Resource)}async execute(e){let t=e.scope===void 0?void 0:this.scopes.get(e.scope);if(e.scope!==void 0&&!t&&this.session.options.native)return this.session.options.native.effect(e);if((e.type===j.Close||e.type===j.Open)&&!this.session.resources.find(e.resource)&&this.session.options.native)return this.session.options.native.effect(e);switch(e.type){case j.Open:await this.resource(e.resource).start();break;case j.Close:await this.session.resources.close(this.resource(e.resource));break;case j.Restore:await this.session.resources.reopen(this.resource(e.previous),e.resource);break;case j.Stop:if(t)await this.session.activities.stop(t);break;case j.Prepare:{if(!t)throw new b(c.Gone.Scope);this.session.activities.prepare(t,e.previous?this.scopes.get(e.previous):void 0);break}case j.Validate:F(this.session.value(e.value),t.state.options);break;case j.Initialize:return this.candidate(t,t.state.initial);case j.Migrate:{let n=t.state;return this.candidate(t,n.options.migrate(this.session.value(e.value),e.version))}case j.Adopt:{let n=new Map;for(let o of e.replacements){if(!o.next)continue;let r=this.scopes.get(o.next);for(let[s,a]of r.resourceDeclarations??[])s.options=a;if(delete r.resourceDeclarations,n.set(r.orb.info.id,r.orb),r.object){if(r.state)r.object.binding=r.state.binding;r.object.orb=r.orb.info.id,r.object.versions.set(r.orb.info.id,r)}}for(let o of n.values())this.session.orbs.records.set(o.info.id,o),this.session.orbs.registerContributions(o);for(let o of e.replacements){let r=o.next?this.scopes.get(o.next):void 0;if(r?.object)this.session.handles.refreshReferences(r.object,r.orb)}for(let o of e.replacements)if(o.next)this.scopes.get(o.next)?.state?.publish?.();break}case j.Start:if(t){if(this.session.activities.start(t),t.object)t.object.live=!0}break;case j.Drop:{if(!t)break;for(let n of t.dependencies.values())this.session.handles.revoke(this.session.handles.reference(n).id);t.dependencies.clear();for(let n of t.resources.values())this.session.resources.closedRecords.delete(n.id);if(t.phase=S.Closed,t.object)t.object.versions.delete(t.orb.info.id);this.scopes.delete(t.id);break}default:throw new b(c.Unsupported.EngineEffect,e.type)}}candidate(e,t){let n=e.state,o=F(t,n.options),r=this.session.values.put(o);return n.publish=()=>this.session.publish(n.binding.adopt(n.binding.prepare(o),o)),r}}var qe=new WeakMap,ke=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry((e)=>e.session.deref()?.handles.release(e.id));class we{session;constructor(e){this.session=e}#e=new Map;#t=new Map;activateAcquired(e,t,n=[]){let o=this.session,r=o.objects.get(e.object);if(!r){let y=ee();r={id:e.object,address:t,orb:e.orb,versions:new Map,activation:y.promise},o.objects.set(r.id,r);let v=r;o.track(o.scopes.activate(v,e).then(y.resolve,(g)=>{v.error=g;try{o.kernel.command(d.Fail,{object:v.id})}catch{}y.reject(g),o.lifecycle.flush()}))}if(!this.claimExists(e.reference))return r.activation;let a=this.orbMetadata(r.orb).services.find((y)=>y.name===t.service)?.methods??[],i={id:e.reference,object:e.object,address:t,methods:new Set(a),requiredMethods:new Set(n),stateCleanups:new Set,ready:r.activation,released:!1,nativeOwned:!0},p=o.orbs.records.get(r.orb)?.definition.services?.[t.service]?.access;try{this.referenceMethods(i,a,p)}catch(y){if(o.kernel.features.views&&this.claimExists(i.id))o.kernel.command(d.Restrict,{reference:i.id,methods:[]});throw y}o.references.set(i.id,i);let m=this.#t.get(i.object);if(!m)this.#t.set(i.object,m=new Set);return m.add(i),r.activation}hold(e,t,n={},o){let r;if(typeof e==="string")r=e;else{let w=Y(e,n);r=w.name,n=w.options}let s=this.session;if(o)V(o,s);s.kernel.command(d.Tick,{now:s.now()});let a={service:r,key:typeof t==="string"?[t]:[...t],principal:n.principal??o?.principal??s.principal},i=s.kernel.command(d.Acquire,{...a,apiVersion:n.apiVersion??0,methods:n.methods??[]}),p=s.objects.get(i.object);if(!p){let w=ee();p={id:i.object,address:a,orb:i.orb,versions:new Map,activation:w.promise},s.objects.set(p.id,p);let T=p;queueMicrotask(()=>{s.track(s.scopes.activate(T,i).then(w.resolve,(M)=>{T.error=M;try{s.kernel.command(d.Fail,{object:T.id})}catch{}w.reject(M),s.lifecycle.flush()}))})}let m=this.orbMetadata(i.orb),y=new Set(m.services.find((w)=>w.name===r)?.methods??[]),v={id:i.reference,object:i.object,address:a,methods:y,requiredMethods:new Set(n.methods??[]),stateCleanups:new Set,ready:p.activation,released:!1,...o?{context:o}:{}},g=s.options.native?.access?.(i.orb,r,a.principal),k=g?()=>({methods:g}):s.orbs.records.get(i.orb)?.definition.services?.[r]?.access;try{this.referenceMethods(v,y,k)}catch(w){throw s.kernel.command(d.Release,{reference:v.id}),s.kernel.command(d.Forget,{reference:v.id}),s.lifecycle.flush(),w}s.references.set(v.id,v);let R=this.#t.get(v.object);if(!R)R=new Set,this.#t.set(v.object,R);if(R.add(v),o){let w=s.rootReferences.get(o.root);if(!w)w=new Set,s.rootReferences.set(o.root,w);w.add(v.id)}let x=()=>{if(v.released)throw new b(c.Released.Reference);if(s.closing)throw new b(c.Gone.Reference);let w=s.objects.get(v.object);if(!w||w.disposing||w.error)throw new b(c.Gone.Reference);if(!w.live)throw new b(c.Unavailable.NotReady)},E={get ready(){return v.ready},get status(){return v.released?A.Released:q.closing?A.Gone:q.kernel.command(d.Status,{reference:v.id})},get state(){x();let w=q.objects.get(v.object)?.binding;if(!w)h(c.Invalid.State,"Service does not expose state");return _e(w,x,v.stateCleanups)},release:()=>this.release(v.id),opaque:(w)=>{x();let T=s.objects.get(v.object),M=T.versions.get(T.orb)?.resources.get(w);if(!M?.options.opaque)throw new b(c.Forbidden.Opaque,w);return M.handle.value}},q=s,J=new Proxy(E,{get:(w,T,M)=>{if(T==="then")return;if(Object.hasOwn(w,T))return Reflect.get(w,T,M);if(typeof T!=="string")return;if(!v.methods.has(T))return;return(...te)=>{let se=v.context;if(Ae(te.at(-1)))se=te.pop();return se?s.calls.invoke(v,T,te,V(se,s)):s.calls.root((Fe)=>s.calls.invoke(v,T,te,Fe),!1,void 0,v.address.principal)}}});return qe.set(J,{session:s,record:v}),ke?.register(J,{session:new WeakRef(s),id:v.id},v),J}async get(e,t,n={},o){let r=this.hold(e,t,n,o);try{return await r.ready,r}catch(s){throw r.release(),s}}reference(e){let t=typeof e==="object"&&e!==null?qe.get(e):void 0;if(!t||t.session!==this.session)h(c.Invalid.Reference,"An issued local reference is required");return t.record}orbMetadata(e){let t=this.session.orbs.records.get(e)?.info;if(t)return t;let n=this.#e.get(e);if(!n)n=this.session.kernel.command(d.Orb,{id:e}),this.#e.set(e,n);return n}referenceMethods(e,t,n,o=!1){let r=this.session;if(n&&!r.kernel.features.views)throw new b(c.Unsupported.Views);let s=n?new Set(n(e.address.principal).methods):void 0,a=new Set([...t].filter((i)=>(!e.requiredMethods.size||e.requiredMethods.has(i))&&(!s||s.has(i))));if(n||o&&r.kernel.features.views)r.kernel.command(d.Restrict,{reference:e.id,methods:[...a]});e.methods=a}refreshReferences(e,t){let n=this.session,o=t.definition.services?.[e.address.service];if(!o)return;let r=Object.keys(o.methods);for(let s of this.#t.get(e.id)??[]){if(s.released)continue;if(s.nativeOwned&&!this.claimExists(s.id)){this.revoke(s.id);continue}try{this.referenceMethods(s,r,o.access,!0)}catch(a){if(s.methods.clear(),!s.released&&n.kernel.features.views)n.kernel.command(d.Restrict,{reference:s.id,methods:[]});n.report(a)}}}claimExists(e){try{let t=this.session.kernel.command(d.Status,{reference:e});return t!==A.Released&&t!==A.Gone}catch(t){if(t instanceof b&&(t.code===l.Gone||t.code===l.Released))return!1;throw t}}forget(e){for(let n of e.stateCleanups)n();e.stateCleanups.clear(),this.session.references.delete(e.id);let t=this.#t.get(e.object);if(t?.delete(e),!t?.size)this.#t.delete(e.object)}release(e){let t=this.session,n=t.references.get(e);if(!n||n.released)return;if(n.released=!0,ke?.unregister(n),t.lifecycle.closedDiagnostics){this.forget(n);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.Release,{reference:e}),t.kernel.command(d.Forget,{reference:e}),this.forget(n),t.lifecycle.flush()}revoke(e){let t=this.session.references.get(e);if(!t)return;t.released=!0,ke?.unregister(t),this.forget(t)}retire(e){this.#e.delete(e)}clear(){for(let e of this.session.references.values())this.forget(e);this.session.references.clear(),this.#t.clear(),this.#e.clear()}}class Re{session;#e;#t;#n;constructor(e){this.session=e}async replace(e,t={},n=[]){return(await this.prepare(e,t,n)).commit()}prepare(e,t={},n=[]){if(this.session.closing)return Promise.reject(new b(c.Closed.Host));if(this.#e)return Promise.reject(new b(c.Conflict.ReloadRunning));let o=this.capture(e,t,n);return this.#e=o,o.catch(()=>{if(this.#e===o)this.#e=void 0}),o}async cancel(){if(this.#n?.status===P.Prepared)return this.#n.abort();if(this.#t!==void 0){this.session.kernel.command(d.ProgramAbort,{program:this.#t});let e=this.session.programs.run(this.#t);this.session.lifecycle.flush(),await e.catch(()=>{})}await this.#e?.catch(()=>{return})}async capture(e,t,n){let o=this.session,r=o.orbs.declarations(e),s=o.kernel.command(d.Prepare,{orbs:r.metadata,remove:n}),a=new Map(r.definitions.map((k)=>[k.name,k])),i=s.orbs.map((k)=>({info:k,definition:a.get(k.name),ticket:s.id})),p=new Map(i.map((k)=>[k.info.id,k])),m;try{for(let k of i)o.orbs.scope(k);for(let k of s.objects){let R=o.objects.get(k);if(!R)continue;let x=s.providers[R.address.service],E=x===void 0?void 0:p.get(x);if(E)o.scopes.createEnvironment(R,E)}for(let k of i)k.ticket=void 0;if(m=o.kernel.command(d.ScopesReloadRegistered,{ticket:s.id,deadline:t.deadline??5000,now:o.now()}),this.#t=m,await o.programs.run(m),o.closing)await o.programs.run(m)}catch(k){if(this.#t=void 0,m===void 0){o.kernel.command(d.Abort,{ticket:s.id});let R=s.orbs.flatMap((x)=>o.kernel.command(d.ScopesForOrb,{orb:x.id}));await o.programs.cleanupScopes(R)}throw k}this.#t=void 0;let y=m,v={codeVersion:s.codeVersion,orbs:i.map((k)=>k.info.name)},g=P.Prepared;return this.#n={report:v,get status(){return g},commit:async()=>{if(g!==P.Prepared)throw new b(c.Conflict.ReloadTicket);this.#n=void 0;try{o.kernel.command(d.ProgramCommit,{program:y})}catch(k){throw o.kernel.command(d.ProgramAbort,{program:y}),await o.programs.run(y).catch(()=>{}),g=P.Aborted,this.#e=void 0,k}return g=P.Committed,this.#e=void 0,await o.programs.run(y),v},abort:async()=>{if(g===P.Aborted)return;if(g!==P.Prepared)throw new b(c.Conflict.AlreadyCommitted);g=P.Aborted,this.#n=void 0,this.#e=void 0,o.kernel.command(d.ProgramAbort,{program:y});try{await o.programs.run(y)}catch(k){if(!(k instanceof b)||k.reason!==u.ReloadAborted)throw k}}}}}var ze=new WeakMap;class Oe{session;records=new Map;closedRecords=new Map;constructor(e){this.session=e}find(e){return this.records.get(e)??this.closedRecords.get(e)}dependencyIds(e){let t=[];for(let n of e.deps??[]){let o=typeof n==="object"&&n!==null?ze.get(n):void 0;if(o){if(o.session!==this.session)h(c.Invalid.ResourceHost,"Resource dependencies must belong to the same host");t.push(o.id)}else this.session.handles.reference(n)}return t}register(e,t,n){return this.session.kernel.command(d.Resource,{owner:e.owner,name:t,version:n.version??1,exclusive:n.exclusive??!1,dependencies:this.dependencyIds(n)}).id}redeclare(e,t){for(let n of t.resources.values())this.records.delete(n.id),this.closedRecords.delete(n.id),n.reset(this.register(e,n.name,n.options)),n.dependencies=this.dependencyIds(n.options),this.records.set(n.id,n),e.resources.set(n.name,n)}declare(e,t,n){if(!t||typeof n.open!=="function")h(c.Invalid.Resource);let o=this.register(e,t,n),r=this.records.get(o);if(r)return(e.resourceDeclarations??=new Map).set(r,n),r;let s=new AbortController,a=Object.freeze({get value(){if(e.phase===S.Declaring)h(c.Invalid.ResourceInFactory,"Resources open after declaration");let p=i.session.kernel.command(d.ResourceValue,{resource:i.id});return i.session.value(p)},version:n.version??1}),i={id:o,name:t,options:n,handle:a,dependencies:this.dependencyIds(n),controller:s,session:this.session,reset:(p)=>{i.id=p,i.controller=new AbortController,delete i.value,delete i.closed,delete i.started},start:()=>(i.started??=(async()=>{let p=i.options,m=await p.open(i.controller.signal),y=this.session.values.put(m);try{this.session.kernel.command(d.ResourceOpened,{resource:i.id,value:y})}catch(v){if(this.session.values.drop(y),p.close)await this.session.calls.root((g)=>p.close(m,g),!0);throw v}i.value=y})(),i.started.catch(()=>{}),i.started)};return ze.set(a,i),this.records.set(o,i),i}async close(e){return e.closed??=(async()=>{e.controller.abort(new b(c.Cancelled.Resource)),await e.started?.catch(()=>{});try{if(e.value!==void 0&&e.options.close){let t=this.session.value(e.value);await this.session.calls.root((n)=>e.options.close(t,n),!0)}}finally{this.session.kernel.command(d.ResourceClosed,{resource:e.id}),this.records.delete(e.id),this.closedRecords.set(e.id,e),this.session.lifecycle.flush()}})(),e.closed}async reopen(e,t){this.closedRecords.delete(e.id),e.reset(t),this.records.set(t,e),await e.start()}}class Se{session;constructor(e){this.session=e}#e=new Map;#t=new Set;#n;environment(e,t,n){let o={id:this.session.kernel.command(d.Allocate),owner:e,orb:t,...n?{object:n}:{},phase:S.Declaring,value:{},dependencies:new Map,resources:new Map,tasks:[],listeners:[]};return this.session.programs.scopes.set(o.id,o),o}async activate(e,t){let n=this.session;if(n.options.native?.hasOrb(t.orb)){await n.options.native.activate(e.id,t.orb,e.address.service,e.address.key,e.address.principal);let o=n.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e.id}});await Promise.all(o.map((r)=>n.programs.activate(r)));try{n.snapshot(e.id),e.binding=new L(n,e.id)}catch{}}else{let o=n.orbs.records.get(t.orb);if(!o)h(c.Invalid.OrbGone);await n.orbs.ready(o);let r=this.createEnvironment(e,o);e.versions.set(o.info.id,r),await this.session.programs.activate(r.id)}if(n.kernel.command(d.Status,{reference:t.reference})===A.Loading)n.kernel.command(d.Ready,{object:e.id});e.live=!0,n.lifecycle.flush()}createEnvironment(e,t){let n=t.definition.services?.[e.address.service];if(!n)h(c.Invalid.ServiceGone);let o=this.environment({kind:I.Object,id:e.id},t,e);try{let r=n.create?.(new H(this.session,o))??{};if(r&&typeof r.then==="function")h(c.Invalid.AsyncFactory,"Factories must be synchronous");return o.value=r,o}finally{o.phase=S.Prepared,this.session.programs.register(o)}}readyHostScope(){let e=this.session;if(e.closing)return Promise.reject(new b(c.Closed.Host));if(this.#n)return this.#n;let t=(async()=>{if(e.hostScope.phase===S.Closed)e.hostScope=await this.redeclareHostScope(e.hostScope);await this.session.programs.activate(e.hostScope.id);while(this.#t.size){let o=this.#t.values().next().value;if(o.phase===S.Closed||[...o.resources.values()].some((r)=>e.resources.dependencyIds(r.options).some((s,a)=>s!==r.dependencies[a]))){let r=o;o=await this.redeclareHostScope(r),this.#t.delete(r),this.#t.add(o)}await this.session.programs.activate(o.id),this.#t.delete(o)}})();this.#n=t;let n=()=>{if(this.#n===t)this.#n=void 0};return t.then(n,n),t}async redeclareHostScope(e){let t=this.session;await t.programs.cleanup([e]);let n=this.environment({kind:I.Host},e.orb);return t.resources.redeclare(n,e),n.phase=S.Prepared,t.programs.register(n),n}requirement(e,t){if(e.orb.definition.services?.[t])return{service:t,apiVersion:e.orb.info.apiVersion};for(let[o,r]of Object.entries(e.orb.definition.requires??{})){let s;try{s=this.session.kernel.command(d.OrbNamed,{name:r.orb??o,ticket:e.orb.ticket})}catch(p){if(p instanceof b&&p.code===l.Gone&&p.reason===u.Orb)continue;throw p}let a=o===t?s.services.find((p)=>p.name===o)??(s.services.length===1?s.services[0]:void 0):s.services.find((p)=>p.name===t);if(!a)continue;let i=r.services?.[a.name]??r.methods;if(!i)throw new b(c.Forbidden.UndeclaredService,t);return{service:a.name,apiVersion:r.apiVersion,methods:i}}throw new b(c.Forbidden.UndeclaredDependency,t)}hostResource(e){let t=this.#e.get(e);if(!t)throw new b(c.Forbidden.HostResource,e);return t.handle}resource(e,t){let n=this.session;if(n.closing)throw new b(c.Closed.Host);if(this.#e.has(e))h(c.Invalid.DuplicateResource);let o=this.environment({kind:I.Host},n.hostScope.orb);try{let r=new H(n,o).resource(e,t);return this.#e.set(e,o.resources.get(e)),o.phase=S.Prepared,n.programs.register(o),this.#t.add(o),n.track(this.readyHostScope()).catch((s)=>n.report(s)),r}catch(r){throw n.programs.scopes.delete(o.id),r}}registerHost(e){for(let[t,n]of e.resources)this.#e.set(t,n)}clear(){this.#e.clear(),this.#t.clear()}}class xe{options;contextTokens=new WeakMap;calls=new be(this);handles=new we(this);scopes=new Se(this);lifecycle=new ye(this);kernel;values;resources=new Oe(this);activities=new me(this);orbs=new ve(this);replacements=new Re(this);programs=new ge(this);objects=new Map;references=new Map;rootReferences=new Map;controllers=new Map;jobs=new Set;cleanupErrors=[];hostScope;codec;name;principal;errors=[];now;telemetry;closing=!1;#e=!1;#t=[];constructor(e){this.options=e;if(this.kernel=new ue(e.kernel),e.telemetry&&!this.kernel.features.telemetry)throw new b(c.Unsupported.Telemetry);this.telemetry=e.telemetry?new fe(e.telemetry.capacity,e.telemetry.sampleEvery):void 0,this.values=new pe(()=>this.kernel.command(d.Allocate)),this.codec=e.serialization??W,this.name=e.name??"host",this.principal=e.principal??"host";let t=e.now??(()=>performance.now()),n=e.clockOrigin??t();this.now=()=>Math.floor(t()-n);let o={info:{id:0,owner:0,name:"$host",apiVersion:1,codeVersion:1,services:[],hooks:[],requires:[]},definition:{name:"$host",apiVersion:1}};this.hostScope=this.scopes.environment({kind:I.Host},o);for(let[r,s]of Object.entries(e.resources??{}))new H(this,this.hostScope).resource(r,s);this.scopes.registerHost(this.hostScope),this.hostScope.phase=S.Prepared,this.programs.register(this.hostScope)}principalFor(e){return this.objects.get(e)?.address.principal??this.principal}snapshot(e){return this.kernel.command(d.Snapshot,{object:e})}value(e){if(this.values.has(e))return this.values.get(e);if(!this.options.native)h(c.Invalid.ValueGone);let t=this.options.native.value(e);return this.values.set(e,t),t}check(e,t){let n=V(e,this);if(!n.invocation||n.invocation.object!==t)throw new b(c.Forbidden.StateOwner);return n.invocation}adopt(e,t,n,o){let r=this.check(t,e),s=this.values.put(o);try{return this.kernel.command(d.StateAdopt,{call:r.id,object:e,revision:n,value:s})}catch(a){throw this.values.drop(s),a}finally{this.lifecycle.flush()}}publish(e){if(this.#t.push(e),this.#e)return;this.#e=!0;try{while(this.#t.length)this.#t.shift()()}finally{this.#e=!1}}report(e){let t=z(e);if(this.errors.length===64)this.errors.shift();this.errors.push(t);try{this.options.onError?.(t)}catch{}}track(e,t=!1){return this.jobs.add(e),e.then(()=>{this.jobs.delete(e)},(n)=>{if(this.jobs.delete(e),t)this.cleanupErrors.push(n),this.report(n)}),e}}class Ce{session;constructor(e){this.session=new xe(e)}get name(){return this.session.name}get features(){return this.session.kernel.features}install(e){return this.session.orbs.install(Array.isArray(e)?e:[e])}async load(e){if(!this.session.options.load)throw Error("This host has no module loader");await this.install(await this.session.options.load(e))}reload(e,t){return this.session.replacements.replace(e,t)}prepare(e,t){return this.session.replacements.prepare(e,t)}remove(e,t){return this.session.replacements.replace([],t,e)}hold(e,t,n){return this.session.handles.hold(e,t,n)}get(e,t,n){return this.session.handles.get(e,t,n)}root(e,t={}){return this.session.calls.root(e,!1,void 0,t.principal)}resource(e,t){return this.session.scopes.resource(e,t)}diagnostics(){return this.session.lifecycle.diagnostics()}errors(){return this.session.errors.splice(0)}traces(){return this.session.telemetry?.drain()??[]}installedOrbs(){return this.session.kernel.command(d.Orbs).map((e)=>{let t=this.session.orbs.records.get(e.id)?.definition,n=Object.freeze({...e,hookCapabilities:Object.fromEntries(e.hooks.map((o)=>[o,t?.hooks?.[o]?.capabilities??[]]))});return Object.freeze({...e,describe:()=>n})})}close(){return this.session.lifecycle.close()}}var O=Deno.core.ops,N=globalThis;N.queueMicrotask??=(e)=>Promise.resolve().then(e);N.performance??={now:()=>O.op_tembra_now()};N.AbortController??=class{signal={aborted:!1,reason:void 0,listeners:new Set,addEventListener(e,t){this.listeners.add(t)},removeEventListener(e,t){this.listeners.delete(t)},throwIfAborted(){if(this.aborted)throw this.reason}};abort(e=Error("Aborted")){if(this.signal.aborted)return;this.signal.aborted=!0,this.signal.reason=e;for(let t of[...this.signal.listeners])t();this.signal.listeners.clear()}};var Le=0,Te=new Set;N.setTimeout??=(e,t=0,...n)=>{let o=++Le;return Te.add(o),O.op_tembra_sleep(o,Math.max(0,Math.min(2147483647,t))).then(()=>{if(Te.delete(o))e(...n)}),o};N.clearTimeout??=(e)=>{if(Te.delete(e))O.op_tembra_clear_timer(e)};function Ne(e={}){let t=e.serialization??W;if(t.id!==O.op_tembra_codec())throw new b(c.Conflict.Codec,"The Rust and JS host codecs must agree");function n(i){let p=t.deserialize(i);if(p.error)throw new b(p.error);return p.ok}let o=O.op_tembra_driver_enabled?.()??!1,r=new Map;N.__tembraDeliver=(i)=>{for(let[p,m,y]of i){let v=r.get(p);if(!v)throw Error("unknown native completion");r.delete(p);try{if(!y)throw Error(m);v.resolve(n(m))}catch(g){v.reject(g)}}};function s(i,p){let m=O.op_tembra_submit(i,p);return new Promise((y,v)=>r.set(m,{resolve:y,reject:v}))}let a=new Ce({...e,clockOrigin:0,kernel:{request:(i)=>O.op_tembra_kernel(i)},native:{...o?{admit:(i,p,m)=>{let y=JSON.parse(O.op_tembra_admit(JSON.stringify({reference:i,method:p,root:m.root,context:m.frame,parent:m.invocation?.id})));if(y.error)throw new b(y.error);return y.ok},finish:(i,p)=>{let m=JSON.parse(O.op_tembra_finish(i,String(p)));if(m.error)throw new b(m.error);return m.ok}}:{},rootEnded:(i)=>O.op_tembra_end_context(i),access:(i,p,m)=>JSON.parse(O.op_tembra_access(i,p,m))??void 0,settled:()=>O.op_tembra_settled(),notify:(i)=>O.op_tembra_notify(JSON.stringify(i)),hasContribution:(i)=>O.op_tembra_has_contribution?.(i)??!1,contribute:async(i,p,m)=>n(await O.op_tembra_native("contribute",t.serialize({operation:i,root:p.root,frame:p.frame,...m===void 0?{}:{input:m}}))).value,hasOrb:(i)=>O.op_tembra_has_orb(i),activate:async(i,p,m)=>{n(await O.op_tembra_native("activate",t.serialize({object:i,orb:p,service:m})))},invoke:async(i,p)=>o?s("invoke",t.serialize({invocation:i,arguments:p})):n(await O.op_tembra_native("invoke",t.serialize({invocation:i,arguments:p}))),dispose:async(i)=>{n(await O.op_tembra_native("dispose",t.serialize({object:i})))},effect:async(i)=>n(await O.op_tembra_native("effect",t.serialize(i))),cancelEffect:async(i)=>{n(await O.op_tembra_native("cancel-effect",t.serialize(i)))},value:(i)=>n(O.op_tembra_value(i)),dropValue:(i)=>O.op_tembra_drop_value(i)}});if(O.op_tembra_callback_next)(async()=>{for(;;){let i=O.op_tembra_callback_next();Deno.core.unrefOpPromise(i);let p=await i;if(!p.length)return;let m=new DataView(p.buffer,p.byteOffset,9),y=m.getUint8(0),v=m.getUint32(1,!0)+m.getUint32(5,!0)*4294967296;if(y!==0){if(y===2)a.session.calls.releaseRoot(v);if(y===3)a.session.handles.revoke(v);a.session.lifecycle.flush();continue}let g;try{g=t.deserialize(p.subarray(9))}catch(k){let{code:R,reason:x,message:E}=z(k);O.op_tembra_callback_error(v,JSON.stringify({code:R,reason:x,message:E}),!0);continue}a.session.track((async()=>{let k;try{let R;if(g.kind==="activate")await a.session.handles.activateAcquired(g.acquired,g.address,g.methods),R=null;else{let x=g.call,E=a.session.kernel.command(d.Invocation,{call:x}),q=new _(a.session,E.root,E,g.frame);if(g.kind==="invoke"){let J=a.session.objects.get(E.object),w=J?.versions.get(E.orb),T=w?.orb.definition.services?.[J.address.service]?.methods[E.method];if(!T||!w)throw new b(c.Gone.Implementation);R=await a.session.calls.execute(()=>T(w.value,q,...g.input))}else R=await a.session.orbs.runContribution(g.operation,q,g.input)}k=R===void 0?{}:{value:R}}catch(R){let x=z(R);k={error:{code:x.code,reason:x.reason,message:x.message}}}try{O.op_tembra_callback_complete(v,t.serialize(k))}catch(R){let{code:x,reason:E,message:q}=z(R);O.op_tembra_callback_error(v,JSON.stringify({code:x,reason:E,message:q}),!1)}})(),!0)}})();return a}N.Tembra=Object.freeze({closeInterrupted:(e)=>(e.session.kernel.command(d.Close),e.session.calls.interrupt(),e.close()),ContextKey:U,ContextKind:D,opaqueFrom:Ee,createHost:Ne,jsonCodec:W,Code:l,Reason:u,Lifetime:G,Status:A,ReloadStatus:P,HookCapability:ie,Errors:c});})();
|
package/dist/host.js
CHANGED
|
@@ -1510,9 +1510,43 @@ function isContext(value) {
|
|
|
1510
1510
|
// src/runtime/calls.ts
|
|
1511
1511
|
class Calls {
|
|
1512
1512
|
session;
|
|
1513
|
+
#interrupted = new Set;
|
|
1513
1514
|
constructor(session) {
|
|
1514
1515
|
this.session = session;
|
|
1515
1516
|
}
|
|
1517
|
+
interrupt() {
|
|
1518
|
+
const error = new TembraError({
|
|
1519
|
+
code: Code.Closed,
|
|
1520
|
+
reason: "javascript",
|
|
1521
|
+
message: "JavaScript execution was interrupted"
|
|
1522
|
+
});
|
|
1523
|
+
for (const reject of this.#interrupted)
|
|
1524
|
+
reject(error);
|
|
1525
|
+
this.#interrupted.clear();
|
|
1526
|
+
}
|
|
1527
|
+
async execute(operation) {
|
|
1528
|
+
let reject;
|
|
1529
|
+
let failure;
|
|
1530
|
+
const interrupted = new Promise((_, fail) => {
|
|
1531
|
+
reject = (error) => {
|
|
1532
|
+
failure = error;
|
|
1533
|
+
fail(error);
|
|
1534
|
+
};
|
|
1535
|
+
});
|
|
1536
|
+
this.#interrupted.add(reject);
|
|
1537
|
+
try {
|
|
1538
|
+
return await Promise.race([
|
|
1539
|
+
Promise.resolve().then(() => {
|
|
1540
|
+
if (failure)
|
|
1541
|
+
throw failure;
|
|
1542
|
+
return operation();
|
|
1543
|
+
}),
|
|
1544
|
+
interrupted
|
|
1545
|
+
]);
|
|
1546
|
+
} finally {
|
|
1547
|
+
this.#interrupted.delete(reject);
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1516
1550
|
signal(root) {
|
|
1517
1551
|
const session = this.session;
|
|
1518
1552
|
let controller = session.controllers.get(root);
|
|
@@ -1583,7 +1617,7 @@ class Calls {
|
|
|
1583
1617
|
const handle = environment?.orb.definition.services?.[reference.address.service]?.methods[method];
|
|
1584
1618
|
if (!environment || !handle)
|
|
1585
1619
|
throw new TembraError(Errors.Gone.Implementation);
|
|
1586
|
-
return await handle(environment.value, entered, ...arguments_);
|
|
1620
|
+
return await this.execute(() => handle(environment.value, entered, ...arguments_));
|
|
1587
1621
|
} catch (error) {
|
|
1588
1622
|
outcome = Outcome.Error;
|
|
1589
1623
|
throw error;
|
|
@@ -1613,7 +1647,7 @@ class Calls {
|
|
|
1613
1647
|
...environment.object ? { object: environment.object.id } : {}
|
|
1614
1648
|
});
|
|
1615
1649
|
try {
|
|
1616
|
-
return await handle(new Context(session, ctx.root, invocation, ctx.frame));
|
|
1650
|
+
return await this.execute(() => handle(new Context(session, ctx.root, invocation, ctx.frame)));
|
|
1617
1651
|
} finally {
|
|
1618
1652
|
session.kernel.command(KernelOp.FinishCall, { call: invocation.id });
|
|
1619
1653
|
session.lifecycle.flush();
|
package/dist/node.js
CHANGED
|
@@ -1553,9 +1553,43 @@ function isContext(value) {
|
|
|
1553
1553
|
// src/runtime/calls.ts
|
|
1554
1554
|
class Calls {
|
|
1555
1555
|
session;
|
|
1556
|
+
#interrupted = new Set;
|
|
1556
1557
|
constructor(session) {
|
|
1557
1558
|
this.session = session;
|
|
1558
1559
|
}
|
|
1560
|
+
interrupt() {
|
|
1561
|
+
const error = new TembraError({
|
|
1562
|
+
code: Code.Closed,
|
|
1563
|
+
reason: "javascript",
|
|
1564
|
+
message: "JavaScript execution was interrupted"
|
|
1565
|
+
});
|
|
1566
|
+
for (const reject of this.#interrupted)
|
|
1567
|
+
reject(error);
|
|
1568
|
+
this.#interrupted.clear();
|
|
1569
|
+
}
|
|
1570
|
+
async execute(operation) {
|
|
1571
|
+
let reject;
|
|
1572
|
+
let failure;
|
|
1573
|
+
const interrupted = new Promise((_, fail) => {
|
|
1574
|
+
reject = (error) => {
|
|
1575
|
+
failure = error;
|
|
1576
|
+
fail(error);
|
|
1577
|
+
};
|
|
1578
|
+
});
|
|
1579
|
+
this.#interrupted.add(reject);
|
|
1580
|
+
try {
|
|
1581
|
+
return await Promise.race([
|
|
1582
|
+
Promise.resolve().then(() => {
|
|
1583
|
+
if (failure)
|
|
1584
|
+
throw failure;
|
|
1585
|
+
return operation();
|
|
1586
|
+
}),
|
|
1587
|
+
interrupted
|
|
1588
|
+
]);
|
|
1589
|
+
} finally {
|
|
1590
|
+
this.#interrupted.delete(reject);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1559
1593
|
signal(root) {
|
|
1560
1594
|
const session = this.session;
|
|
1561
1595
|
let controller = session.controllers.get(root);
|
|
@@ -1626,7 +1660,7 @@ class Calls {
|
|
|
1626
1660
|
const handle = environment?.orb.definition.services?.[reference.address.service]?.methods[method];
|
|
1627
1661
|
if (!environment || !handle)
|
|
1628
1662
|
throw new TembraError(Errors.Gone.Implementation);
|
|
1629
|
-
return await handle(environment.value, entered, ...arguments_);
|
|
1663
|
+
return await this.execute(() => handle(environment.value, entered, ...arguments_));
|
|
1630
1664
|
} catch (error) {
|
|
1631
1665
|
outcome = Outcome.Error;
|
|
1632
1666
|
throw error;
|
|
@@ -1656,7 +1690,7 @@ class Calls {
|
|
|
1656
1690
|
...environment.object ? { object: environment.object.id } : {}
|
|
1657
1691
|
});
|
|
1658
1692
|
try {
|
|
1659
|
-
return await handle(new Context(session, ctx.root, invocation, ctx.frame));
|
|
1693
|
+
return await this.execute(() => handle(new Context(session, ctx.root, invocation, ctx.frame)));
|
|
1660
1694
|
} finally {
|
|
1661
1695
|
session.kernel.command(KernelOp.FinishCall, { call: invocation.id });
|
|
1662
1696
|
session.lifecycle.flush();
|
package/dist/runtime/calls.d.ts
CHANGED
|
@@ -4,9 +4,14 @@ import type { Environment, ReferenceRecord } from "./records.ts";
|
|
|
4
4
|
import type { Session } from "./session.ts";
|
|
5
5
|
/** Execute JS calls. Rust controls admission and physical lifetime. */
|
|
6
6
|
export declare class Calls {
|
|
7
|
+
#private;
|
|
7
8
|
readonly session: Session;
|
|
8
9
|
/** Connect JS callback execution to the session kernel. */
|
|
9
10
|
constructor(session: Session);
|
|
11
|
+
/** Settle JavaScript frames after the embedding has unwound a terminated V8 turn. */
|
|
12
|
+
interrupt(): void;
|
|
13
|
+
/** Keep the callback frame separate from its physical completion bookkeeping. */
|
|
14
|
+
execute<T>(operation: () => Completion<T>): Promise<T>;
|
|
10
15
|
/** Lazily mirror root cancellation into an AbortSignal. */
|
|
11
16
|
signal(root: number): AbortSignal;
|
|
12
17
|
/** Revoke claims and cancellation mirrors when either language ends a root. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syntropika/tembra-sdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -89,8 +89,8 @@
|
|
|
89
89
|
"access": "public"
|
|
90
90
|
},
|
|
91
91
|
"dependencies": {
|
|
92
|
-
"@syntropika/tembra-engine-node": "0.2.
|
|
93
|
-
"@syntropika/tembra-engine-wasm": "0.2.
|
|
92
|
+
"@syntropika/tembra-engine-node": "0.2.2",
|
|
93
|
+
"@syntropika/tembra-engine-wasm": "0.2.2",
|
|
94
94
|
"enhanced-resolve": "5.26.0",
|
|
95
95
|
"typescript": "5.9.3"
|
|
96
96
|
},
|
package/src/embedded.ts
CHANGED
|
@@ -242,7 +242,9 @@ function createHost(options: Omit<HostOptions, "kernel" | "native"> = {}): Host
|
|
|
242
242
|
invocation.method
|
|
243
243
|
];
|
|
244
244
|
if (!handle || !environment) throw new TembraError(Errors.Gone.Implementation);
|
|
245
|
-
result = await
|
|
245
|
+
result = await host.session.calls.execute(() =>
|
|
246
|
+
handle(environment.value, ctx, ...request.input),
|
|
247
|
+
);
|
|
246
248
|
} else {
|
|
247
249
|
result = await host.session.orbs.runContribution(
|
|
248
250
|
request.operation,
|
|
@@ -278,6 +280,12 @@ function createHost(options: Omit<HostOptions, "kernel" | "native"> = {}): Host
|
|
|
278
280
|
}
|
|
279
281
|
|
|
280
282
|
globals.Tembra = Object.freeze({
|
|
283
|
+
/** Drain terminal cleanup after the embedding has interrupted and unwound JavaScript. */
|
|
284
|
+
closeInterrupted: (host: Host) => {
|
|
285
|
+
host.session.kernel.command(KernelOp.Close);
|
|
286
|
+
host.session.calls.interrupt();
|
|
287
|
+
return host.close();
|
|
288
|
+
},
|
|
281
289
|
ContextKey,
|
|
282
290
|
ContextKind,
|
|
283
291
|
opaqueFrom,
|
package/src/runtime/calls.ts
CHANGED
|
@@ -10,9 +10,46 @@ import type { Session } from "./session.ts";
|
|
|
10
10
|
|
|
11
11
|
/** Execute JS calls. Rust controls admission and physical lifetime. */
|
|
12
12
|
export class Calls {
|
|
13
|
+
readonly #interrupted = new Set<(error: unknown) => void>();
|
|
14
|
+
|
|
13
15
|
/** Connect JS callback execution to the session kernel. */
|
|
14
16
|
constructor(readonly session: Session) {}
|
|
15
17
|
|
|
18
|
+
/** Settle JavaScript frames after the embedding has unwound a terminated V8 turn. */
|
|
19
|
+
interrupt(): void {
|
|
20
|
+
const error = new TembraError({
|
|
21
|
+
code: Code.Closed,
|
|
22
|
+
reason: "javascript",
|
|
23
|
+
message: "JavaScript execution was interrupted",
|
|
24
|
+
});
|
|
25
|
+
for (const reject of this.#interrupted) reject(error);
|
|
26
|
+
this.#interrupted.clear();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Keep the callback frame separate from its physical completion bookkeeping. */
|
|
30
|
+
async execute<T>(operation: () => Completion<T>): Promise<T> {
|
|
31
|
+
let reject!: (error: unknown) => void;
|
|
32
|
+
let failure: unknown;
|
|
33
|
+
const interrupted = new Promise<never>((_, fail) => {
|
|
34
|
+
reject = (error) => {
|
|
35
|
+
failure = error;
|
|
36
|
+
fail(error);
|
|
37
|
+
};
|
|
38
|
+
});
|
|
39
|
+
this.#interrupted.add(reject);
|
|
40
|
+
try {
|
|
41
|
+
return await Promise.race([
|
|
42
|
+
Promise.resolve().then(() => {
|
|
43
|
+
if (failure) throw failure;
|
|
44
|
+
return operation();
|
|
45
|
+
}),
|
|
46
|
+
interrupted,
|
|
47
|
+
]);
|
|
48
|
+
} finally {
|
|
49
|
+
this.#interrupted.delete(reject);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
16
53
|
/** Lazily mirror root cancellation into an AbortSignal. */
|
|
17
54
|
signal(root: number): AbortSignal {
|
|
18
55
|
const session = this.session;
|
|
@@ -99,7 +136,7 @@ export class Calls {
|
|
|
99
136
|
const handle =
|
|
100
137
|
environment?.orb.definition.services?.[reference.address.service]?.methods[method];
|
|
101
138
|
if (!environment || !handle) throw new TembraError(Errors.Gone.Implementation);
|
|
102
|
-
return await handle(environment.value, entered, ...arguments_);
|
|
139
|
+
return await this.execute(() => handle(environment.value, entered, ...arguments_));
|
|
103
140
|
} catch (error) {
|
|
104
141
|
outcome = Outcome.Error;
|
|
105
142
|
throw error;
|
|
@@ -137,7 +174,9 @@ export class Calls {
|
|
|
137
174
|
...(environment.object ? { object: environment.object.id } : {}),
|
|
138
175
|
});
|
|
139
176
|
try {
|
|
140
|
-
return await
|
|
177
|
+
return await this.execute(() =>
|
|
178
|
+
handle(new Context(session, ctx.root, invocation, ctx.frame)),
|
|
179
|
+
);
|
|
141
180
|
} finally {
|
|
142
181
|
session.kernel.command(KernelOp.FinishCall, { call: invocation.id });
|
|
143
182
|
session.lifecycle.flush();
|