webloom-framework 0.4.2 → 0.4.3
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/README.md +11 -1
- package/dist/advanced.d.ts +8 -8
- package/dist/advanced.js +4 -4
- package/dist/advanced.js.map +1 -1
- package/dist/{chunk-RRNUE457.js → chunk-UZAO6ORB.js} +110 -26
- package/dist/chunk-UZAO6ORB.js.map +1 -0
- package/dist/{chunk-XVD7ALPV.js → chunk-YIIDRFHK.js} +106 -15
- package/dist/chunk-YIIDRFHK.js.map +1 -0
- package/dist/{chunk-CKML74MG.js → chunk-ZP5QYTXX.js} +4 -4
- package/dist/chunk-ZP5QYTXX.js.map +1 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.js +4 -4
- package/dist/{messageBus-BDtkjs6y.d.ts → messageBus-DigYfj74.d.ts} +1 -1
- package/dist/messagePortServiceTransport-B9-24RK6.d.ts +355 -0
- package/dist/react.d.ts +1 -1
- package/dist/react.js +1 -1
- package/dist/{runtimeTypes-CleHMFaq.d.ts → runtimeTypes-50LVQs0h.d.ts} +7 -220
- package/dist/{sharedWorkerHost-BNMUW-8v.d.ts → sharedWorkerHost-DikS18hA.d.ts} +55 -2
- package/dist/testing.d.ts +6 -6
- package/dist/testing.js +4 -4
- package/dist/{windowRuntime-BGl_jfbK.d.ts → windowRuntime-e1Tn6SnN.d.ts} +2 -2
- package/docs/api.md +28 -1
- package/docs/proposals/webloom-v4/requirements.md +1 -1
- package/package.json +1 -1
- package/dist/chunk-CKML74MG.js.map +0 -1
- package/dist/chunk-RRNUE457.js.map +0 -1
- package/dist/chunk-XVD7ALPV.js.map +0 -1
- package/dist/messagePortServiceTransport-DyNmdgoa.d.ts +0 -150
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# WebLoom
|
|
2
2
|
|
|
3
|
-
WebLoom 是一个只面向浏览器的插件 Runtime 框架。0.4.
|
|
3
|
+
WebLoom 是一个只面向浏览器的插件 Runtime 框架。0.4.3 管理真实的
|
|
4
4
|
`window-main` 和 `shared-worker` JavaScript realm、插件运行单元、实例、依赖图、
|
|
5
5
|
ResourceScope、权限租约、typed capability、服务桥和资源缓存;路由、存储、日志、
|
|
6
6
|
国际化等产品能力由插件或下游应用注入。
|
|
@@ -95,6 +95,16 @@ const coordinator = definePlugin({
|
|
|
95
95
|
startSharedWorkerApp({ id: "coordinator", plugins: [coordinator], expose: [Health] });
|
|
96
96
|
```
|
|
97
97
|
|
|
98
|
+
`startSharedWorkerApp()` 会在插件注册前申请浏览器 Web Lock:锁名默认是
|
|
99
|
+
`webloom.runtime:<runtimeId>`,不包含版本号、构建标识或 Worker URL。多个页面使用同一个
|
|
100
|
+
SharedWorker 时只由同一个物理 Worker 申请一次;第二个物理 Worker 使用立即检查语义,
|
|
101
|
+
冲突时返回 `runtime_lock_conflict`,不会等待或启动插件。
|
|
102
|
+
|
|
103
|
+
这项冲突语义只适用于双方都支持 Web Locks 的版本。registry `0.4.2` 不申请 Web Lock,
|
|
104
|
+
所以新包 `0.4.3` 不能自动发现一个已经存活的 `0.4.2` Worker。首次从 0.4.2 启用运行锁
|
|
105
|
+
必须先关闭所有旧页面并确认旧 Worker 退出,再启用新包;这是部署冷切换,不是运行时接管。
|
|
106
|
+
后续双方都支持 Web Locks 时,才显示“请刷新或关闭所有相关页面后重新打开”的冲突提示。
|
|
107
|
+
|
|
98
108
|
Window 侧只连接 Worker,不创建第二套 Worker 插件生命周期:
|
|
99
109
|
|
|
100
110
|
```ts
|
package/dist/advanced.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { R as RuntimeKind, C as CapabilityDescriptor, P as PluginManifest, a as PluginGraph, b as RuntimeUnitDependency, c as PluginReverseDep, d as RuntimeUnitDescriptor, L as LifecycleScopeIdentity, e as PluginPermission, f as LifecycleScope, g as PermissionLease, S as ScopedTaskScheduler, h as CreateUpgradeGateOptions, U as UpgradeGate, i as
|
|
2
|
-
export {
|
|
3
|
-
import { M as MessagePortLike,
|
|
4
|
-
export { C as CreateCapabilityBridgeOptions,
|
|
5
|
-
import { R as ReceivePortLedger, a as RuntimeLimitsInput, b as RuntimeBudget, c as RuntimePluginDefinition } from './sharedWorkerHost-
|
|
6
|
-
export {
|
|
7
|
-
export { c as createWindowAppFromHost, h as hostForWindowApp } from './windowRuntime-
|
|
1
|
+
import { R as RuntimeKind, C as CapabilityDescriptor, P as PluginManifest, a as PluginGraph, b as RuntimeUnitDependency, c as PluginReverseDep, d as RuntimeUnitDescriptor, L as LifecycleScopeIdentity, e as PluginPermission, f as LifecycleScope, g as PermissionLease, S as ScopedTaskScheduler, h as CreateUpgradeGateOptions, U as UpgradeGate, i as ServiceReference, j as RuntimeEndpointBinding, k as CapabilityPeer, l as RuntimeDrainResult, m as ResourceStoreApi$1, W as WindowApp, n as RuntimeHandle } from './runtimeTypes-50LVQs0h.js';
|
|
2
|
+
export { o as CapabilityRegistration, p as CapabilityRegistry, q as ContextExtensionInput, r as ContributionAdapter, s as ContributionAdapterInput, t as ContributionHandle, u as CreatePluginHostOptions, H as HostCapabilityRegistration, v as HostInspection, w as PermissionPolicyInput, x as PermissionPolicyResult, y as PluginConfigStore, z as PluginHost, A as RuntimeUnitAttributesInput, B as RuntimeUnitAvailabilityInput, D as RuntimeUnitParentScopeInput, E as RuntimeUnitSnapshot, F as StartupCapabilityError, G as StartupPluginError, I as createCapabilityRegistry, J as createInMemoryPluginConfigStore, K as createPluginHost, M as invokeCapabilityHandler } from './runtimeTypes-50LVQs0h.js';
|
|
3
|
+
import { R as RuntimeCallMessage, M as MessagePortLike, a as RuntimeTransport, b as RuntimeEndpointSession } from './messagePortServiceTransport-B9-24RK6.js';
|
|
4
|
+
export { C as CreateCapabilityBridgeOptions, c as CreatePluginIntentControllerOptions, d as RUNTIME_CALL_TYPE, e as RUNTIME_CANCEL_TYPE, f as RUNTIME_CLOSE_ACK_TYPE, g as RUNTIME_CLOSE_TYPE, h as RUNTIME_CREDIT_TYPE, i as RUNTIME_ERROR_MESSAGE_TYPE, j as RUNTIME_ERROR_TYPE, k as RUNTIME_NEXT_TYPE, l as RUNTIME_PROTOCOL_VERSION, m as RUNTIME_RESULT_TYPE, n as RUNTIME_SNAPSHOT_TYPE, o as RuntimeCancelMessage, p as RuntimeCloseAckMessage, q as RuntimeCloseMessage, r as RuntimeCreditMessage, s as RuntimeErrorMessage, t as RuntimeErrorResponseMessage, u as RuntimeMessageCodec, v as RuntimeNextMessage, w as RuntimeReceiveMetadata, x as RuntimeResultMessage, y as RuntimeSessionBinding, z as RuntimeSnapshotMessage, A as RuntimeSnapshotUnit, B as RuntimeStreamDoneMessage, D as RuntimeStreamReadyMessage, E as RuntimeUnaryResultMessage, F as RuntimeUnitImplementation, G as RuntimeWireMessage, H as createCapabilityBridge, I as createMessagePortRuntimeTransport, J as createPluginIntentController, K as createResourceRegistry, L as createRuntimeMessageCodec, N as createRuntimeUnitImplementationRegistry, O as isRuntimeSnapshot, P as registerOwnedResource, Q as validateTransferables } from './messagePortServiceTransport-B9-24RK6.js';
|
|
5
|
+
import { R as ReceivePortLedger, a as RuntimeLimitsInput, b as RuntimeBudget, c as RuntimePluginDefinition } from './sharedWorkerHost-DikS18hA.js';
|
|
6
|
+
export { C as CreateResourceScopeOptions, P as PeerController, d as PeerExposureOptions, e as ResourceScopeOptions, f as RuntimeLockError, g as RuntimeLockFailureCode, h as RuntimeLockHandle, i as RuntimeLockManagerLike, j as RuntimeLockMessages, k as RuntimeLockOptions, S as SharedWorkerApp, l as StartSharedWorkerAppForTestingOptions, m as StartSharedWorkerAppOptions, W as WEBLOOM_RUNTIME_LOCK_PREFIX, n as bridgeForRuntimeHandle, o as createLifecycleScope, p as createResourceScope } from './sharedWorkerHost-DikS18hA.js';
|
|
7
|
+
export { c as createWindowAppFromHost, h as hostForWindowApp } from './windowRuntime-e1Tn6SnN.js';
|
|
8
8
|
|
|
9
9
|
interface PluginGraphOptions {
|
|
10
10
|
/** 当前 Host 的 Runtime;未指定时只用于静态检查。 */
|
|
@@ -177,4 +177,4 @@ declare function registerPlugins(app: WindowApp, definitions: readonly RuntimePl
|
|
|
177
177
|
/** 把一个连接绑定到现有 WindowApp;替换时先撤销旧 bridge。 */
|
|
178
178
|
declare function attachRemote(app: WindowApp, runtime: RuntimeHandle): Promise<() => void>;
|
|
179
179
|
|
|
180
|
-
export { type CreatePermissionLeaseOptions, type CreateScopedRegistryFacadeOptions, type CreateScopedTaskSchedulerOptions, MessagePortLike, type MessagePortServiceCallInput, type MessagePortServiceProviderOptions, type PluginGraphOptions, type PreparedRequest, type ResourceStoreApi, RuntimeCallMessage,
|
|
180
|
+
export { type CreatePermissionLeaseOptions, type CreateScopedRegistryFacadeOptions, type CreateScopedTaskSchedulerOptions, MessagePortLike, type MessagePortServiceCallInput, type MessagePortServiceProviderOptions, type PluginGraphOptions, type PreparedRequest, type ResourceStoreApi, RuntimeCallMessage, RuntimeTransport, type ScopedRegistryRegistration, type VerifyPermissionLeaseOptions, attachRemote, buildPluginGraph, createMessagePortServiceProvider, createPermissionLease, createScopedRegistryFacade, createScopedTaskScheduler, createUpgradeGate, dependenciesOfManifest, providesOfManifest, registerPlugins, reverseDependentsOf, selectRuntimeUnit, validatePluginGraph, verifyPermissionLease };
|
package/dist/advanced.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export { createPluginIntentController } from './chunk-4DSINPZD.js';
|
|
2
|
-
import { bridgeForRuntimeHandle } from './chunk-
|
|
3
|
-
export {
|
|
4
|
-
import { hostForWindowApp, materializePluginDefinitions, UpgradeGateRejectedError } from './chunk-
|
|
5
|
-
export { RUNTIME_CALL_TYPE, RUNTIME_CANCEL_TYPE, RUNTIME_CLOSE_ACK_TYPE, RUNTIME_CLOSE_TYPE, RUNTIME_CREDIT_TYPE, RUNTIME_ERROR_MESSAGE_TYPE, RUNTIME_ERROR_TYPE, RUNTIME_NEXT_TYPE, RUNTIME_PROTOCOL_VERSION, RUNTIME_RESULT_TYPE, RUNTIME_SNAPSHOT_TYPE, StartupCapabilityError, StartupPluginError, buildPluginGraph, createCapabilityRegistry, createInMemoryPluginConfigStore, createLifecycleScope, createPermissionLease, createPluginHost, createResourceRegistry, createResourceScope, createRuntimeMessageCodec, createRuntimeUnitImplementationRegistry, createScopedTaskScheduler, createWindowAppFromHost, dependenciesOfManifest, hostForWindowApp, invokeCapabilityHandler, isRuntimeSnapshot, providesOfManifest, registerOwnedResource, reverseDependentsOf, selectRuntimeUnit, validatePluginGraph } from './chunk-
|
|
2
|
+
import { bridgeForRuntimeHandle } from './chunk-YIIDRFHK.js';
|
|
3
|
+
export { RuntimeLockError, WEBLOOM_RUNTIME_LOCK_PREFIX, bridgeForRuntimeHandle, createCapabilityBridge, createMessagePortRuntimeTransport, createMessagePortServiceProvider, validateTransferables } from './chunk-YIIDRFHK.js';
|
|
4
|
+
import { hostForWindowApp, materializePluginDefinitions, UpgradeGateRejectedError } from './chunk-ZP5QYTXX.js';
|
|
5
|
+
export { RUNTIME_CALL_TYPE, RUNTIME_CANCEL_TYPE, RUNTIME_CLOSE_ACK_TYPE, RUNTIME_CLOSE_TYPE, RUNTIME_CREDIT_TYPE, RUNTIME_ERROR_MESSAGE_TYPE, RUNTIME_ERROR_TYPE, RUNTIME_NEXT_TYPE, RUNTIME_PROTOCOL_VERSION, RUNTIME_RESULT_TYPE, RUNTIME_SNAPSHOT_TYPE, StartupCapabilityError, StartupPluginError, buildPluginGraph, createCapabilityRegistry, createInMemoryPluginConfigStore, createLifecycleScope, createPermissionLease, createPluginHost, createResourceRegistry, createResourceScope, createRuntimeMessageCodec, createRuntimeUnitImplementationRegistry, createScopedTaskScheduler, createWindowAppFromHost, dependenciesOfManifest, hostForWindowApp, invokeCapabilityHandler, isRuntimeSnapshot, providesOfManifest, registerOwnedResource, reverseDependentsOf, selectRuntimeUnit, validatePluginGraph } from './chunk-ZP5QYTXX.js';
|
|
6
6
|
|
|
7
7
|
// src/lifecycle/permissionVerifier.ts
|
|
8
8
|
function verifyPermissionLease(options) {
|
package/dist/advanced.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lifecycle/permissionVerifier.ts","../src/lifecycle/scopedRegistry.ts","../src/lifecycle/upgradeGate.ts","../src/advanced.ts"],"names":["input"],"mappings":";;;;;;;AAmBO,SAAS,sBAAsB,OAAA,EAA6C;AACjF,EAAA,OAAA,CAAQ,KAAA,CAAM,MAAA,CAAO,OAAA,CAAQ,UAAU,CAAA;AACvC,EAAA,IAAI,QAAQ,OAAA,EAAS,OAAA,CAAQ,KAAA,CAAM,aAAA,CAAc,QAAQ,OAAO,CAAA;AAClE;;;ACWA,SAAS,aAAa,KAAA,EAAoC;AACxD,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,UAAU,OAAO,MAAA;AAChD,EAAA,MAAM,KAAM,KAAA,CAA2B,EAAA;AACvC,EAAA,OAAO,OAAO,EAAA,KAAO,QAAA,IAAY,EAAA,CAAG,MAAA,GAAS,IAAI,EAAA,GAAK,MAAA;AACxD;AAEA,SAAS,wBAAA,GAAyD;AAChE,EAAA,OAAO,CAAC,EAAE,MAAA,EAAQ,UAAA,EAAY,YAAY,CAAA,EAAG,gBAAA,EAAkB,cAAc,CAAA;AAC/E;AAGO,SAAS,0BAAA,CACd,MAAA,EACA,KAAA,EACA,OAAA,EACG;AACH,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,aAAA,IAAiB,wBAAA,EAAyB;AAChE,EAAA,MAAM,QAAA,GAAW,IAAI,GAAA,CAAI,KAAA,CAAM,GAAA,CAAI,CAAC,IAAA,KAAS,CAAC,IAAA,CAAK,MAAA,EAAQ,IAAI,CAAC,CAAC,CAAA;AACjE,EAAA,MAAM,oBAAoB,IAAI,GAAA;AAAA,IAC5B,KAAA,CAAM,GAAA,CAAI,CAAC,IAAA,KAAS,IAAA,CAAK,gBAAgB,CAAA,CAAE,MAAA,CAAO,CAAC,MAAA,KAA6B,OAAA,CAAQ,MA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,KAAgB,WAAA,EAAgE;AACpH,EAAA,MAAM,IAAA,GAAO,iBAAiB,GAAG,CAAA;AACjC,EAAA,MAAM,YAAA,GAAe,4BAAA,CAA6B,WAAA,EAAa,GAAA,CAAI,WAAW,CAAA;AAC9E,EAAA,KAAA,MAAW,cAAc,YAAA,EAAc,IAAA,CAAK,uBAAuB,EAAE,QAAA,EAAU,WAAW,QAAA,CAAS,EAAA,EAAI,MAAA,EAAQ,UAAA,CAAW,QAAQ,KAAA,EAAO,UAAA,CAAW,OAAO,YAAA,EAAc,UAAA,CAAW,cAAc,CAAA;AAClM,EAAA,MAAM,IAAA,CAAK,YAAY,YAAA,CAAa,GAAA,CAAI,CAAC,UAAA,KAAe,UAAA,CAAW,QAAQ,CAAC,CAAA;AAC9E;AAGA,eAAsB,YAAA,CAAa,KAAgB,OAAA,EAA6C;AAC9F,EAAA,MAAM,IAAA,GAAO,iBAAiB,GAAG,CAAA;AACjC,EAAA,MAAM,MAAA,GAA2B,uBAAuB,OAAO,CAAA;AAC/D,EAAA,IAAA,CAAK,aAAa,MAAM,CAAA;AACxB,EAAA,MAAM,KAAK,SAAA,EAAU;AACrB,EAAA,OAAO,MAAM,IAAA,CAAK,YAAA,CAAa,yBAAyB,CAAA;AAC1D","file":"advanced.js","sourcesContent":["// 权限租约的最终边界验证器。\n//\n// Context 中的 permissions 只用于限制误用;RPC handler、最终存储写入或\n// 签名提交处必须调用这里,不能信任请求体自带的 pluginId / owner / 世代。\n\nimport type {\n PermissionLease,\n PluginPermission,\n} from \"../contracts/lifecycle.js\";\n\nexport interface VerifyPermissionLeaseOptions {\n /** 已由受信装配层创建的租约。 */\n lease: PermissionLease;\n /** 本次实际操作所需的最小权限。 */\n permission: PluginPermission;\n /** 从端口 / 当前会话权威取得的绑定值。 */\n binding?: Parameters<PermissionLease[\"assertBinding\"]>[0];\n}\n/** 在最终 RPC / I/O 边界执行一次 fail-closed 校验。 */\nexport function verifyPermissionLease(options: VerifyPermissionLeaseOptions): void {\n options.lease.assert(options.permission);\n if (options.binding) options.lease.assertBinding(options.binding);\n}\n","// 把已有 Registry 绑定到插件实例作用域。\n//\n// 该 facade 不改变 Registry 的业务类型,只在注册方法周围登记所有权:\n// 资源创建成功后立刻绑定 instance scope,停止时按 after-teardown 阶段\n// 注销。setup 前后 snapshot 仍保留作旧插件兼容兜底,但新注册不依赖它。\n\nimport type { LifecycleScope } from \"../contracts/lifecycle.js\";\n\nexport interface ScopedRegistryRegistration {\n /** 注册方法名,例如 register / registerFeature。 */\n method: string;\n /** 从参数哪个位置读取带 id 的定义。 */\n idArgument?: number;\n /** 没有返回取消函数时使用的注销方法。 */\n unregisterMethod?: string;\n /** 注销方法的参数位置;默认使用 idArgument。 */\n unregisterArgument?: number;\n /** 含 ownerPluginId 参数的注册方法;由 Host 绑定当前插件身份。 */\n bindPluginIdArgument?: number;\n /** 定义对象中的 ownerPluginId 字段;存在时必须与当前插件一致。 */\n ownerPluginIdProperty?: string;\n}\n\nexport interface CreateScopedRegistryFacadeOptions {\n /** 日志和作用域资源中显示的注册表名。 */\n name: string;\n /** 注册方法规则;缺省只包装 register(item)。 */\n registrations?: readonly ScopedRegistryRegistration[];\n}\n\ntype AnyFunction = (...args: any[]) => any;\ntype RegistryTarget = Record<PropertyKey, any>;\n\nfunction definitionId(value: unknown): string | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const id = (value as { id?: unknown }).id;\n return typeof id === \"string\" && id.length > 0 ? id : undefined;\n}\n\nfunction defaultRegistrationRules(): ScopedRegistryRegistration[] {\n return [{ method: \"register\", idArgument: 0, unregisterMethod: \"unregister\" }];\n}\n\n/** 创建一个只对当前插件实例开放的 Registry 视图。 */\nexport function createScopedRegistryFacade<T extends object>(\n target: T,\n scope: LifecycleScope,\n options: CreateScopedRegistryFacadeOptions\n): T {\n const rules = options.registrations ?? defaultRegistrationRules();\n const byMethod = new Map(rules.map((rule) => [rule.method, rule]));\n const unregisterMethods = new Set(\n rules.map((rule) => rule.unregisterMethod).filter((method): method is string => Boolean(method))\n );\n interface OwnedRegistration {\n id?: string;\n unregisterMethod?: string;\n active: boolean;\n /** revoke 时同步失效的入口;异步 dispose 只作为兜底。 */\n revokeNow: (reason: string) => void;\n /** revoke 已触发但尚未完成的底层注销;dispose 需要等待它。 */\n revokedCleanup?: Promise<void>;\n removeScopeCleanup: () => void;\n }\n const ownedRegistrations = new Set<OwnedRegistration>();\n const objectTarget = target as RegistryTarget;\n\n const remember = (\n rule: ScopedRegistryRegistration,\n id: string | undefined,\n result: unknown,\n args: unknown[]\n ): unknown => {\n const unregisterMethod = rule.unregisterMethod;\n if (typeof result !== \"function\" && (!unregisterMethod || id === undefined)) return result;\n const key = rule.method + \":\" + (id ?? \"returned\");\n let active = true;\n let removeScopeRevoke: () => void = () => undefined;\n let removeScopeCleanup: () => void = () => undefined;\n const entry = {} as OwnedRegistration;\n const clearOwnership = (removeDispose = true): boolean => {\n if (!active) return false;\n active = false;\n ownedRegistrations.delete(entry);\n removeScopeRevoke();\n if (removeDispose) removeScopeCleanup();\n return true;\n };\n const invokeUnregister = (...offArgs: unknown[]): unknown => {\n if (typeof result === \"function\") {\n return (result as AnyFunction).apply(target, offArgs);\n }\n const unregister = objectTarget[unregisterMethod!];\n if (typeof unregister !== \"function\") return undefined;\n const unregisterArgument = rule.unregisterArgument ?? rule.idArgument ?? 0;\n const unregisterArgs = [...args];\n unregisterArgs[unregisterArgument] = id;\n return unregister.apply(target, unregisterArgs);\n };\n const cleanup = async (_reason: string): Promise<void> => {\n if (!active) {\n if (entry.revokedCleanup) await entry.revokedCleanup;\n return;\n }\n if (!clearOwnership()) return;\n await invokeUnregister();\n };\n const revokeNow = (_reason: string): void => {\n if (!clearOwnership(false)) return;\n try {\n const pending = invokeUnregister();\n if (pending && typeof (pending as PromiseLike<unknown>).then === \"function\") {\n const revokedCleanup = Promise.resolve(pending).then(() => undefined);\n entry.revokedCleanup = revokedCleanup;\n revokedCleanup.catch(() => undefined);\n }\n } catch (error) {\n // revoke 必须继续同步撤权;把同步失败留给 dispose 的结果,不能\n // 重新暴露旧注册项,也不能让失败 Promise 变成未处理异常。\n entry.revokedCleanup = Promise.reject(error);\n entry.revokedCleanup.catch(() => undefined);\n }\n };\n entry.id = id;\n entry.unregisterMethod = unregisterMethod;\n entry.revokeNow = revokeNow;\n Object.defineProperty(entry, \"active\", {\n enumerable: true,\n configurable: false,\n get: () => active,\n set: (value: boolean) => { active = value; },\n });\n entry.removeScopeCleanup = removeScopeCleanup;\n ownedRegistrations.add(entry);\n removeScopeCleanup = scope.onDispose(\n cleanup,\n options.name + \":\" + key,\n \"after-teardown\"\n );\n entry.removeScopeCleanup = removeScopeCleanup;\n removeScopeRevoke = scope.onRevoke(revokeNow);\n\n if (typeof result === \"function\") {\n return (...offArgs: unknown[]) => {\n if (!clearOwnership()) return undefined;\n return (result as AnyFunction).apply(target, offArgs);\n };\n }\n return result;\n };\n\n return new Proxy(target, {\n get(current, property, receiver) {\n const value = Reflect.get(current, property, receiver);\n if (typeof value !== \"function\") return value;\n const rule = typeof property === \"string\" ? byMethod.get(property) : undefined;\n if (rule) {\n return (...args: unknown[]) => {\n scope.assertActive();\n const callArgs = [...args];\n if (rule.bindPluginIdArgument !== undefined && scope.identity.pluginId) {\n const claimedPluginId = callArgs[rule.bindPluginIdArgument];\n if (claimedPluginId !== undefined && claimedPluginId !== scope.identity.pluginId) {\n throw new Error(\n \"Registry owner \\\"\" + String(claimedPluginId) +\n \"\\\" does not match plugin instance \\\"\" + scope.identity.pluginId + \"\\\"\"\n );\n }\n callArgs[rule.bindPluginIdArgument] = scope.identity.pluginId;\n }\n if (rule.ownerPluginIdProperty && scope.identity.pluginId) {\n const definition = callArgs[rule.idArgument ?? 0];\n if (definition && typeof definition === \"object\") {\n const claimedPluginId = (definition as Record<string, unknown>)[rule.ownerPluginIdProperty];\n if (claimedPluginId !== undefined && claimedPluginId !== scope.identity.pluginId) {\n throw new Error(\n \"Registry owner \\\"\" + String(claimedPluginId) +\n \"\\\" does not match plugin instance \\\"\" + scope.identity.pluginId + \"\\\"\"\n );\n }\n }\n }\n const result = (value as AnyFunction).apply(target, callArgs);\n const id = rule.idArgument === undefined ? undefined : definitionId(callArgs[rule.idArgument]);\n return remember(rule, id, result, callArgs);\n };\n }\n // 插件主动注销只能操作自己在本作用域登记过的 id;例如\n // protected-outpoint 的 unregisterByOwner 属于领域批量操作,不在这里\n // 冒充单条资源注销,仍由领域接口自己做 owner 校验。\n if (typeof property === \"string\" && unregisterMethods.has(property)) {\n return (...args: unknown[]) => {\n scope.assertActive();\n const id = definitionId(args[0]) ?? (typeof args[0] === \"string\" ? args[0] : undefined);\n const owned = [...ownedRegistrations].find((entry) =>\n entry.active && entry.id === id && entry.unregisterMethod === property\n );\n if (!owned) {\n throw new Error(\n \"Registry resource \\\"\" + (id ?? \"unknown\") + \"\\\" is not owned by this plugin instance\"\n );\n }\n const result = (value as AnyFunction).apply(target, args);\n owned.active = false;\n ownedRegistrations.delete(owned);\n owned.removeScopeCleanup();\n return result;\n };\n }\n return (value as AnyFunction).bind(target);\n },\n }) as T;\n}\n","// Worker / 页面升级接管门禁。\n//\n// 这是一个本地写入栅栏,不是 leader 选举器,也不是跨 Worker 调度器:\n// - handshake 只校验协议、构建、接管世代和精确契约版本;\n// - active 期间才发放新的 I/O 租约;\n// - beginDrain 同步关闭新入口,已有 I/O 可以继续排空;\n// - drain 超时返回未排空,调用方不能据此开放下一代写入。\n//\n// 真正的存储 / 签名服务仍必须在最终边界重复校验 authorityInstanceId 和\n// handoverGeneration。这个模块只能提供可复用的接管语义,不能替代服务端校验。\n\nimport type {\n CreateUpgradeGateOptions,\n UpgradeDrainResult,\n UpgradeGate,\n UpgradeGateState,\n UpgradeHandshake,\n UpgradeHandshakeResult,\n UpgradeIoLease,\n UpgradeSession,\n} from \"../contracts/lifecycle.js\";\nimport { UpgradeGateRejectedError } from \"../contracts/lifecycle.js\";\n\ninterface LeaseRecord {\n session: SessionRecord;\n operation: \"read\" | \"write\";\n controller: AbortController;\n revoked: boolean;\n reason: string;\n removeExternalAbort?: () => void;\n}\n\ninterface SessionRecord {\n sessionId: string;\n connectionId: string;\n contractVersion: string;\n controller: AbortController;\n revoked: boolean;\n reason: string;\n leases: Set<LeaseRecord>;\n session?: UpgradeSession;\n}\n\nfunction validGeneration(value: number): boolean {\n return Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction uniqueStrings(values: readonly string[]): string[] {\n return [...new Set(values.filter((value) => typeof value === \"string\" && value.length > 0))];\n}\n\nfunction makeSessionId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `upgrade-session:${crypto.randomUUID()}`;\n }\n } catch {\n // 会话标识用于防止误绑定;真正的授权仍由握手和最终边界校验。\n }\n return `upgrade-session:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;\n}\n\nfunction buildIsCompatible(options: CreateUpgradeGateOptions, buildId: string): boolean {\n try {\n if (options.isBuildCompatible) return options.isBuildCompatible(buildId);\n } catch {\n return false;\n }\n return buildId === options.buildId || options.compatibleBuildIds?.has(buildId) === true;\n}\n\n/** 创建一个绑定当前构建和接管世代的升级门禁。 */\nexport function createUpgradeGate(options: CreateUpgradeGateOptions): UpgradeGate {\n if (!options.protocolVersion || !options.buildId || !options.authorityInstanceId) {\n throw new Error(\"升级门禁的 protocolVersion、buildId 和 authorityInstanceId 必须有效\");\n }\n if (!validGeneration(options.handoverGeneration)) {\n throw new Error(\"升级门禁的 handoverGeneration 必须是非负安全整数\");\n }\n const contractVersions = uniqueStrings(options.supportedContractVersions);\n if (contractVersions.length === 0) {\n throw new Error(\"升级门禁至少需要一个 supportedContractVersions\");\n }\n\n let currentState: UpgradeGateState = \"active\";\n let closeReason = \"upgrade gate closed\";\n const leases = new Set<LeaseRecord>();\n const sessions = new Set<SessionRecord>();\n const sessionByObject = new WeakMap<UpgradeSession, SessionRecord>();\n const emptyWaiters = new Set<() => void>();\n\n const notifyEmpty = () => {\n if (leases.size !== 0) return;\n for (const resolve of [...emptyWaiters]) {\n emptyWaiters.delete(resolve);\n resolve();\n }\n };\n\n const removeLease = (record: LeaseRecord) => {\n if (!leases.delete(record)) return;\n record.session.leases.delete(record);\n record.removeExternalAbort?.();\n record.removeExternalAbort = undefined;\n notifyEmpty();\n };\n\n const revokeSession = (record: SessionRecord, reason: string) => {\n if (record.revoked) return;\n record.revoked = true;\n record.reason = reason;\n try {\n record.controller.abort(new UpgradeGateRejectedError(reason));\n } catch {\n record.controller.abort();\n }\n for (const lease of [...record.leases]) revokeLease(lease, reason);\n sessions.delete(record);\n };\n\n const revokeLease = (record: LeaseRecord, reason: string) => {\n if (record.revoked) return;\n record.revoked = true;\n record.reason = reason;\n try {\n record.controller.abort(new UpgradeGateRejectedError(reason));\n } catch {\n record.controller.abort();\n }\n removeLease(record);\n };\n\n const assertAccepting = () => {\n if (currentState === \"active\") return;\n throw new UpgradeGateRejectedError(currentState === \"draining\" ? \"draining\" : \"closed\", closeReason);\n };\n\n const handshake = (input: UpgradeHandshake): UpgradeHandshakeResult => {\n if (currentState !== \"active\") {\n return { accepted: false, reason: currentState === \"draining\" ? \"draining\" : \"closed\" };\n }\n if (\n typeof input.connectionId !== \"string\"\n || input.connectionId.length === 0\n || input.protocolVersion !== options.protocolVersion\n || typeof input.protocolVersion !== \"string\"\n || typeof input.buildId !== \"string\"\n || typeof input.authorityInstanceId !== \"string\"\n || input.authorityInstanceId.length === 0\n ) {\n return { accepted: false, reason: \"protocol-mismatch\" };\n }\n if (!buildIsCompatible(options, input.buildId)) {\n return { accepted: false, reason: \"build-incompatible\" };\n }\n if (!validGeneration(input.handoverGeneration)) {\n return { accepted: false, reason: \"stale-generation\" };\n }\n if (input.handoverGeneration < options.handoverGeneration) {\n return { accepted: false, reason: \"stale-generation\" };\n }\n if (input.handoverGeneration > options.handoverGeneration) {\n return { accepted: false, reason: \"future-generation\" };\n }\n const contractVersion = contractVersions.find((version) => input.supportedContractVersions.includes(version));\n if (!contractVersion) return { accepted: false, reason: \"contract-mismatch\" };\n const sessionRecord: SessionRecord = {\n sessionId: makeSessionId(),\n connectionId: input.connectionId,\n contractVersion,\n controller: new AbortController(),\n revoked: false,\n reason: \"upgrade session closed\",\n leases: new Set(),\n };\n const session: UpgradeSession = {\n connectionId: sessionRecord.connectionId,\n sessionId: sessionRecord.sessionId,\n authorityInstanceId: options.authorityInstanceId,\n handoverGeneration: options.handoverGeneration,\n contractVersion,\n get revoked() {\n return sessionRecord.revoked || !sessions.has(sessionRecord);\n },\n signal: sessionRecord.controller.signal,\n assertActive() {\n if (sessionRecord.revoked || !sessions.has(sessionRecord)) {\n throw new UpgradeGateRejectedError(sessionRecord.reason, \"升级握手会话已失效\");\n }\n if (currentState === \"closed\") {\n throw new UpgradeGateRejectedError(\"closed\", closeReason);\n }\n },\n admit(input) {\n return admitForSession(sessionRecord, input);\n },\n close(reason = \"upgrade session closed\") {\n revokeSession(sessionRecord, reason);\n },\n };\n sessionRecord.session = session;\n sessions.add(sessionRecord);\n sessionByObject.set(session, sessionRecord);\n return {\n accepted: true,\n mode: options.mode ?? \"cold-switch\",\n handoverGeneration: options.handoverGeneration,\n contractVersion,\n connectionId: sessionRecord.connectionId,\n sessionId: sessionRecord.sessionId,\n session,\n };\n };\n\n const admitForSession = (\n sessionRecord: SessionRecord,\n input: { operation: \"read\" | \"write\"; signal?: AbortSignal }\n ): UpgradeIoLease => {\n if (sessionRecord.revoked || !sessions.has(sessionRecord)) {\n throw new UpgradeGateRejectedError(sessionRecord.reason, \"升级握手会话已失效\");\n }\n assertAccepting();\n if (input.signal?.aborted) {\n throw new UpgradeGateRejectedError(\"caller-aborted\", \"I/O 在取得接管租约前已取消\");\n }\n\n const record: LeaseRecord = {\n session: sessionRecord,\n operation: input.operation,\n controller: new AbortController(),\n revoked: false,\n reason: \"upgrade I/O lease released\",\n };\n leases.add(record);\n sessionRecord.leases.add(record);\n if (input.signal) {\n const onAbort = () => revokeLease(record, \"caller-aborted\");\n input.signal.addEventListener(\"abort\", onAbort, { once: true });\n record.removeExternalAbort = () => input.signal?.removeEventListener(\"abort\", onAbort);\n }\n\n const lease: UpgradeIoLease = {\n connectionId: sessionRecord.connectionId,\n sessionId: sessionRecord.sessionId,\n authorityInstanceId: options.authorityInstanceId,\n handoverGeneration: options.handoverGeneration,\n contractVersion: sessionRecord.contractVersion,\n operation: record.operation,\n get revoked() {\n return record.revoked || !leases.has(record);\n },\n signal: record.controller.signal,\n assertActive() {\n if (record.revoked || !leases.has(record)) {\n throw new UpgradeGateRejectedError(record.reason, \"升级 I/O 租约已失效\");\n }\n // beginDrain 不撤销已发租约;它只阻止新 I/O,给已提交操作一个排空窗口。\n if (currentState === \"closed\") {\n throw new UpgradeGateRejectedError(\"closed\", closeReason);\n }\n },\n release() {\n if (record.revoked) return;\n record.revoked = true;\n record.reason = \"upgrade I/O lease released\";\n removeLease(record);\n },\n };\n return lease;\n };\n\n const admit = (input: Parameters<UpgradeGate[\"admit\"]>[0]): UpgradeIoLease => {\n const sessionRecord = sessionByObject.get(input.session);\n if (!sessionRecord) {\n throw new UpgradeGateRejectedError(\"invalid-session\", \"I/O 必须使用当前门禁握手返回的会话\");\n }\n return admitForSession(sessionRecord, input);\n };\n\n const beginDrain = (reason = \"upgrade handover draining\") => {\n if (currentState !== \"active\") return;\n closeReason = reason;\n currentState = \"draining\";\n };\n\n const drain = async (timeoutMs?: number): Promise<UpgradeDrainResult> => {\n beginDrain();\n if (leases.size === 0) return { state: currentState, drained: true, pending: 0 };\n if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 0)) {\n throw new Error(\"升级排空 timeoutMs 必须是非负有限数\");\n }\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timerResolve: (() => void) | undefined;\n const empty = new Promise<void>((resolve) => {\n emptyWaiters.add(resolve);\n timerResolve = resolve;\n });\n const timeoutPromise = timeoutMs === undefined\n ? undefined\n : new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs);\n });\n if (timeoutPromise) await Promise.race([empty, timeoutPromise]);\n else await empty;\n if (timeout !== undefined) clearTimeout(timeout);\n if (timerResolve) emptyWaiters.delete(timerResolve);\n const pending = leases.size;\n return { state: currentState, drained: pending === 0, pending };\n };\n\n const close = (reason = \"upgrade gate closed\") => {\n if (currentState === \"closed\") return;\n closeReason = reason;\n currentState = \"closed\";\n for (const session of [...sessions]) revokeSession(session, reason);\n for (const lease of [...leases]) revokeLease(lease, reason);\n notifyEmpty();\n };\n\n return {\n get state() { return currentState; },\n mode: options.mode ?? \"cold-switch\",\n authorityInstanceId: options.authorityInstanceId,\n handoverGeneration: options.handoverGeneration,\n handshake,\n assertAccepting,\n admit,\n beginDrain,\n drain,\n close,\n activeIo: () => leases.size,\n };\n}\n","// WebLoom v4 advanced 装配入口。\n// 这些 API 是同一套 Host/transport 实现的显式扩展,不提供旧 API 兼容层。\n\nexport * from \"./host/createPluginHost.js\";\nexport * from \"./host/pluginGraph.js\";\nexport * from \"./host/capabilityRegistry.js\";\nexport * from \"./host/runtimeUnitImplementationRegistry.js\";\nexport * from \"./lifecycle/resourceScope.js\";\nexport * from \"./lifecycle/permissionLease.js\";\nexport * from \"./lifecycle/permissionVerifier.js\";\nexport * from \"./lifecycle/pluginIntentController.js\";\nexport * from \"./lifecycle/taskScheduler.js\";\nexport * from \"./lifecycle/scopedRegistry.js\";\nexport * from \"./lifecycle/upgradeGate.js\";\nexport { createResourceRegistry, registerOwnedResource } from \"./resources/resourceRegistry.js\";\n/** Resource Store 的 advanced 类型出口;显式 alias 可被 dts bundler 保留。 */\nexport type ResourceStoreApi = import(\"./resources/resourceStore.js\").ResourceStoreApi;\nexport * from \"./transport/serviceBridge.js\";\nexport * from \"./transport/messagePortServiceTransport.js\";\nexport * from \"./transport/messagePortServiceProvider.js\";\nexport { createWindowAppFromHost, hostForWindowApp } from \"./runtime/windowRuntime.js\";\nexport { bridgeForRuntimeHandle } from \"./runtime/connectSharedWorker.js\";\nexport type { ActivePeerSnapshot, PeerController, PeerExposureOptions, PeerLifecycleEvent, StartSharedWorkerAppOptions, StartSharedWorkerAppForTestingOptions, SharedWorkerApp } from \"./runtime/sharedWorkerHost.js\";\nexport * from \"./runtime/runtimeProtocol.js\";\nexport * from \"./runtime/runtimeSession.js\";\n\nimport type { RuntimeHandle, WindowApp } from \"./runtime/runtimeTypes.js\";\nimport type { RuntimePluginDefinition } from \"./runtime/pluginDefinitions.js\";\nimport { materializePluginDefinitions } from \"./runtime/pluginDefinitions.js\";\nimport { hostForWindowApp } from \"./runtime/windowRuntime.js\";\nimport { bridgeForRuntimeHandle } from \"./runtime/connectSharedWorker.js\";\nimport type { CapabilityBridge } from \"./contracts/capability.js\";\n\n/** 分阶段向已经拥有的 App 注册新的 typed plugin definitions。 */\nexport async function registerPlugins(app: WindowApp, definitions: readonly RuntimePluginDefinition[]): Promise<void> {\n const host = hostForWindowApp(app);\n const materialized = materializePluginDefinitions(definitions, app.runtimeKind);\n for (const definition of materialized) host.registerImplementation({ pluginId: definition.manifest.id, unitId: definition.unitId, setup: definition.setup, capabilities: definition.capabilities });\n await host.registerAll(materialized.map((definition) => definition.manifest));\n}\n\n/** 把一个连接绑定到现有 WindowApp;替换时先撤销旧 bridge。 */\nexport async function attachRemote(app: WindowApp, runtime: RuntimeHandle): Promise<() => void> {\n const host = hostForWindowApp(app);\n const bridge: CapabilityBridge = bridgeForRuntimeHandle(runtime);\n host.attachRemote(bridge);\n await host.reconcile();\n return () => host.detachRemote(\"Remote Runtime detached\");\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/lifecycle/permissionVerifier.ts","../src/lifecycle/scopedRegistry.ts","../src/lifecycle/upgradeGate.ts","../src/advanced.ts"],"names":["input"],"mappings":";;;;;;;AAmBO,SAAS,sBAAsB,OAAA,EAA6C;AACjF,EAAA,OAAA,CAAQ,KAAA,CAAM,MAAA,CAAO,OAAA,CAAQ,UAAU,CAAA;AACvC,EAAA,IAAI,QAAQ,OAAA,EAAS,OAAA,CAAQ,KAAA,CAAM,aAAA,CAAc,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MAAM,IAAA,CAAK,YAAY,YAAA,CAAa,GAAA,CAAI,CAAC,UAAA,KAAe,UAAA,CAAW,QAAQ,CAAC,CAAA;AAC9E;AAGA,eAAsB,YAAA,CAAa,KAAgB,OAAA,EAA6C;AAC9F,EAAA,MAAM,IAAA,GAAO,iBAAiB,GAAG,CAAA;AACjC,EAAA,MAAM,MAAA,GAA2B,uBAAuB,OAAO,CAAA;AAC/D,EAAA,IAAA,CAAK,aAAa,MAAM,CAAA;AACxB,EAAA,MAAM,KAAK,SAAA,EAAU;AACrB,EAAA,OAAO,MAAM,IAAA,CAAK,YAAA,CAAa,yBAAyB,CAAA;AAC1D","file":"advanced.js","sourcesContent":["// 权限租约的最终边界验证器。\n//\n// Context 中的 permissions 只用于限制误用;RPC handler、最终存储写入或\n// 签名提交处必须调用这里,不能信任请求体自带的 pluginId / owner / 世代。\n\nimport type {\n PermissionLease,\n PluginPermission,\n} from \"../contracts/lifecycle.js\";\n\nexport interface VerifyPermissionLeaseOptions {\n /** 已由受信装配层创建的租约。 */\n lease: PermissionLease;\n /** 本次实际操作所需的最小权限。 */\n permission: PluginPermission;\n /** 从端口 / 当前会话权威取得的绑定值。 */\n binding?: Parameters<PermissionLease[\"assertBinding\"]>[0];\n}\n/** 在最终 RPC / I/O 边界执行一次 fail-closed 校验。 */\nexport function verifyPermissionLease(options: VerifyPermissionLeaseOptions): void {\n options.lease.assert(options.permission);\n if (options.binding) options.lease.assertBinding(options.binding);\n}\n","// 把已有 Registry 绑定到插件实例作用域。\n//\n// 该 facade 不改变 Registry 的业务类型,只在注册方法周围登记所有权:\n// 资源创建成功后立刻绑定 instance scope,停止时按 after-teardown 阶段\n// 注销。setup 前后 snapshot 仍保留作旧插件兼容兜底,但新注册不依赖它。\n\nimport type { LifecycleScope } from \"../contracts/lifecycle.js\";\n\nexport interface ScopedRegistryRegistration {\n /** 注册方法名,例如 register / registerFeature。 */\n method: string;\n /** 从参数哪个位置读取带 id 的定义。 */\n idArgument?: number;\n /** 没有返回取消函数时使用的注销方法。 */\n unregisterMethod?: string;\n /** 注销方法的参数位置;默认使用 idArgument。 */\n unregisterArgument?: number;\n /** 含 ownerPluginId 参数的注册方法;由 Host 绑定当前插件身份。 */\n bindPluginIdArgument?: number;\n /** 定义对象中的 ownerPluginId 字段;存在时必须与当前插件一致。 */\n ownerPluginIdProperty?: string;\n}\n\nexport interface CreateScopedRegistryFacadeOptions {\n /** 日志和作用域资源中显示的注册表名。 */\n name: string;\n /** 注册方法规则;缺省只包装 register(item)。 */\n registrations?: readonly ScopedRegistryRegistration[];\n}\n\ntype AnyFunction = (...args: any[]) => any;\ntype RegistryTarget = Record<PropertyKey, any>;\n\nfunction definitionId(value: unknown): string | undefined {\n if (!value || typeof value !== \"object\") return undefined;\n const id = (value as { id?: unknown }).id;\n return typeof id === \"string\" && id.length > 0 ? id : undefined;\n}\n\nfunction defaultRegistrationRules(): ScopedRegistryRegistration[] {\n return [{ method: \"register\", idArgument: 0, unregisterMethod: \"unregister\" }];\n}\n\n/** 创建一个只对当前插件实例开放的 Registry 视图。 */\nexport function createScopedRegistryFacade<T extends object>(\n target: T,\n scope: LifecycleScope,\n options: CreateScopedRegistryFacadeOptions\n): T {\n const rules = options.registrations ?? defaultRegistrationRules();\n const byMethod = new Map(rules.map((rule) => [rule.method, rule]));\n const unregisterMethods = new Set(\n rules.map((rule) => rule.unregisterMethod).filter((method): method is string => Boolean(method))\n );\n interface OwnedRegistration {\n id?: string;\n unregisterMethod?: string;\n active: boolean;\n /** revoke 时同步失效的入口;异步 dispose 只作为兜底。 */\n revokeNow: (reason: string) => void;\n /** revoke 已触发但尚未完成的底层注销;dispose 需要等待它。 */\n revokedCleanup?: Promise<void>;\n removeScopeCleanup: () => void;\n }\n const ownedRegistrations = new Set<OwnedRegistration>();\n const objectTarget = target as RegistryTarget;\n\n const remember = (\n rule: ScopedRegistryRegistration,\n id: string | undefined,\n result: unknown,\n args: unknown[]\n ): unknown => {\n const unregisterMethod = rule.unregisterMethod;\n if (typeof result !== \"function\" && (!unregisterMethod || id === undefined)) return result;\n const key = rule.method + \":\" + (id ?? \"returned\");\n let active = true;\n let removeScopeRevoke: () => void = () => undefined;\n let removeScopeCleanup: () => void = () => undefined;\n const entry = {} as OwnedRegistration;\n const clearOwnership = (removeDispose = true): boolean => {\n if (!active) return false;\n active = false;\n ownedRegistrations.delete(entry);\n removeScopeRevoke();\n if (removeDispose) removeScopeCleanup();\n return true;\n };\n const invokeUnregister = (...offArgs: unknown[]): unknown => {\n if (typeof result === \"function\") {\n return (result as AnyFunction).apply(target, offArgs);\n }\n const unregister = objectTarget[unregisterMethod!];\n if (typeof unregister !== \"function\") return undefined;\n const unregisterArgument = rule.unregisterArgument ?? rule.idArgument ?? 0;\n const unregisterArgs = [...args];\n unregisterArgs[unregisterArgument] = id;\n return unregister.apply(target, unregisterArgs);\n };\n const cleanup = async (_reason: string): Promise<void> => {\n if (!active) {\n if (entry.revokedCleanup) await entry.revokedCleanup;\n return;\n }\n if (!clearOwnership()) return;\n await invokeUnregister();\n };\n const revokeNow = (_reason: string): void => {\n if (!clearOwnership(false)) return;\n try {\n const pending = invokeUnregister();\n if (pending && typeof (pending as PromiseLike<unknown>).then === \"function\") {\n const revokedCleanup = Promise.resolve(pending).then(() => undefined);\n entry.revokedCleanup = revokedCleanup;\n revokedCleanup.catch(() => undefined);\n }\n } catch (error) {\n // revoke 必须继续同步撤权;把同步失败留给 dispose 的结果,不能\n // 重新暴露旧注册项,也不能让失败 Promise 变成未处理异常。\n entry.revokedCleanup = Promise.reject(error);\n entry.revokedCleanup.catch(() => undefined);\n }\n };\n entry.id = id;\n entry.unregisterMethod = unregisterMethod;\n entry.revokeNow = revokeNow;\n Object.defineProperty(entry, \"active\", {\n enumerable: true,\n configurable: false,\n get: () => active,\n set: (value: boolean) => { active = value; },\n });\n entry.removeScopeCleanup = removeScopeCleanup;\n ownedRegistrations.add(entry);\n removeScopeCleanup = scope.onDispose(\n cleanup,\n options.name + \":\" + key,\n \"after-teardown\"\n );\n entry.removeScopeCleanup = removeScopeCleanup;\n removeScopeRevoke = scope.onRevoke(revokeNow);\n\n if (typeof result === \"function\") {\n return (...offArgs: unknown[]) => {\n if (!clearOwnership()) return undefined;\n return (result as AnyFunction).apply(target, offArgs);\n };\n }\n return result;\n };\n\n return new Proxy(target, {\n get(current, property, receiver) {\n const value = Reflect.get(current, property, receiver);\n if (typeof value !== \"function\") return value;\n const rule = typeof property === \"string\" ? byMethod.get(property) : undefined;\n if (rule) {\n return (...args: unknown[]) => {\n scope.assertActive();\n const callArgs = [...args];\n if (rule.bindPluginIdArgument !== undefined && scope.identity.pluginId) {\n const claimedPluginId = callArgs[rule.bindPluginIdArgument];\n if (claimedPluginId !== undefined && claimedPluginId !== scope.identity.pluginId) {\n throw new Error(\n \"Registry owner \\\"\" + String(claimedPluginId) +\n \"\\\" does not match plugin instance \\\"\" + scope.identity.pluginId + \"\\\"\"\n );\n }\n callArgs[rule.bindPluginIdArgument] = scope.identity.pluginId;\n }\n if (rule.ownerPluginIdProperty && scope.identity.pluginId) {\n const definition = callArgs[rule.idArgument ?? 0];\n if (definition && typeof definition === \"object\") {\n const claimedPluginId = (definition as Record<string, unknown>)[rule.ownerPluginIdProperty];\n if (claimedPluginId !== undefined && claimedPluginId !== scope.identity.pluginId) {\n throw new Error(\n \"Registry owner \\\"\" + String(claimedPluginId) +\n \"\\\" does not match plugin instance \\\"\" + scope.identity.pluginId + \"\\\"\"\n );\n }\n }\n }\n const result = (value as AnyFunction).apply(target, callArgs);\n const id = rule.idArgument === undefined ? undefined : definitionId(callArgs[rule.idArgument]);\n return remember(rule, id, result, callArgs);\n };\n }\n // 插件主动注销只能操作自己在本作用域登记过的 id;例如\n // protected-outpoint 的 unregisterByOwner 属于领域批量操作,不在这里\n // 冒充单条资源注销,仍由领域接口自己做 owner 校验。\n if (typeof property === \"string\" && unregisterMethods.has(property)) {\n return (...args: unknown[]) => {\n scope.assertActive();\n const id = definitionId(args[0]) ?? (typeof args[0] === \"string\" ? args[0] : undefined);\n const owned = [...ownedRegistrations].find((entry) =>\n entry.active && entry.id === id && entry.unregisterMethod === property\n );\n if (!owned) {\n throw new Error(\n \"Registry resource \\\"\" + (id ?? \"unknown\") + \"\\\" is not owned by this plugin instance\"\n );\n }\n const result = (value as AnyFunction).apply(target, args);\n owned.active = false;\n ownedRegistrations.delete(owned);\n owned.removeScopeCleanup();\n return result;\n };\n }\n return (value as AnyFunction).bind(target);\n },\n }) as T;\n}\n","// Worker / 页面升级接管门禁。\n//\n// 这是一个本地写入栅栏,不是 leader 选举器,也不是跨 Worker 调度器:\n// - handshake 只校验协议、构建、接管世代和精确契约版本;\n// - active 期间才发放新的 I/O 租约;\n// - beginDrain 同步关闭新入口,已有 I/O 可以继续排空;\n// - drain 超时返回未排空,调用方不能据此开放下一代写入。\n//\n// 真正的存储 / 签名服务仍必须在最终边界重复校验 authorityInstanceId 和\n// handoverGeneration。这个模块只能提供可复用的接管语义,不能替代服务端校验。\n\nimport type {\n CreateUpgradeGateOptions,\n UpgradeDrainResult,\n UpgradeGate,\n UpgradeGateState,\n UpgradeHandshake,\n UpgradeHandshakeResult,\n UpgradeIoLease,\n UpgradeSession,\n} from \"../contracts/lifecycle.js\";\nimport { UpgradeGateRejectedError } from \"../contracts/lifecycle.js\";\n\ninterface LeaseRecord {\n session: SessionRecord;\n operation: \"read\" | \"write\";\n controller: AbortController;\n revoked: boolean;\n reason: string;\n removeExternalAbort?: () => void;\n}\n\ninterface SessionRecord {\n sessionId: string;\n connectionId: string;\n contractVersion: string;\n controller: AbortController;\n revoked: boolean;\n reason: string;\n leases: Set<LeaseRecord>;\n session?: UpgradeSession;\n}\n\nfunction validGeneration(value: number): boolean {\n return Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction uniqueStrings(values: readonly string[]): string[] {\n return [...new Set(values.filter((value) => typeof value === \"string\" && value.length > 0))];\n}\n\nfunction makeSessionId(): string {\n try {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `upgrade-session:${crypto.randomUUID()}`;\n }\n } catch {\n // 会话标识用于防止误绑定;真正的授权仍由握手和最终边界校验。\n }\n return `upgrade-session:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;\n}\n\nfunction buildIsCompatible(options: CreateUpgradeGateOptions, buildId: string): boolean {\n try {\n if (options.isBuildCompatible) return options.isBuildCompatible(buildId);\n } catch {\n return false;\n }\n return buildId === options.buildId || options.compatibleBuildIds?.has(buildId) === true;\n}\n\n/** 创建一个绑定当前构建和接管世代的升级门禁。 */\nexport function createUpgradeGate(options: CreateUpgradeGateOptions): UpgradeGate {\n if (!options.protocolVersion || !options.buildId || !options.authorityInstanceId) {\n throw new Error(\"升级门禁的 protocolVersion、buildId 和 authorityInstanceId 必须有效\");\n }\n if (!validGeneration(options.handoverGeneration)) {\n throw new Error(\"升级门禁的 handoverGeneration 必须是非负安全整数\");\n }\n const contractVersions = uniqueStrings(options.supportedContractVersions);\n if (contractVersions.length === 0) {\n throw new Error(\"升级门禁至少需要一个 supportedContractVersions\");\n }\n\n let currentState: UpgradeGateState = \"active\";\n let closeReason = \"upgrade gate closed\";\n const leases = new Set<LeaseRecord>();\n const sessions = new Set<SessionRecord>();\n const sessionByObject = new WeakMap<UpgradeSession, SessionRecord>();\n const emptyWaiters = new Set<() => void>();\n\n const notifyEmpty = () => {\n if (leases.size !== 0) return;\n for (const resolve of [...emptyWaiters]) {\n emptyWaiters.delete(resolve);\n resolve();\n }\n };\n\n const removeLease = (record: LeaseRecord) => {\n if (!leases.delete(record)) return;\n record.session.leases.delete(record);\n record.removeExternalAbort?.();\n record.removeExternalAbort = undefined;\n notifyEmpty();\n };\n\n const revokeSession = (record: SessionRecord, reason: string) => {\n if (record.revoked) return;\n record.revoked = true;\n record.reason = reason;\n try {\n record.controller.abort(new UpgradeGateRejectedError(reason));\n } catch {\n record.controller.abort();\n }\n for (const lease of [...record.leases]) revokeLease(lease, reason);\n sessions.delete(record);\n };\n\n const revokeLease = (record: LeaseRecord, reason: string) => {\n if (record.revoked) return;\n record.revoked = true;\n record.reason = reason;\n try {\n record.controller.abort(new UpgradeGateRejectedError(reason));\n } catch {\n record.controller.abort();\n }\n removeLease(record);\n };\n\n const assertAccepting = () => {\n if (currentState === \"active\") return;\n throw new UpgradeGateRejectedError(currentState === \"draining\" ? \"draining\" : \"closed\", closeReason);\n };\n\n const handshake = (input: UpgradeHandshake): UpgradeHandshakeResult => {\n if (currentState !== \"active\") {\n return { accepted: false, reason: currentState === \"draining\" ? \"draining\" : \"closed\" };\n }\n if (\n typeof input.connectionId !== \"string\"\n || input.connectionId.length === 0\n || input.protocolVersion !== options.protocolVersion\n || typeof input.protocolVersion !== \"string\"\n || typeof input.buildId !== \"string\"\n || typeof input.authorityInstanceId !== \"string\"\n || input.authorityInstanceId.length === 0\n ) {\n return { accepted: false, reason: \"protocol-mismatch\" };\n }\n if (!buildIsCompatible(options, input.buildId)) {\n return { accepted: false, reason: \"build-incompatible\" };\n }\n if (!validGeneration(input.handoverGeneration)) {\n return { accepted: false, reason: \"stale-generation\" };\n }\n if (input.handoverGeneration < options.handoverGeneration) {\n return { accepted: false, reason: \"stale-generation\" };\n }\n if (input.handoverGeneration > options.handoverGeneration) {\n return { accepted: false, reason: \"future-generation\" };\n }\n const contractVersion = contractVersions.find((version) => input.supportedContractVersions.includes(version));\n if (!contractVersion) return { accepted: false, reason: \"contract-mismatch\" };\n const sessionRecord: SessionRecord = {\n sessionId: makeSessionId(),\n connectionId: input.connectionId,\n contractVersion,\n controller: new AbortController(),\n revoked: false,\n reason: \"upgrade session closed\",\n leases: new Set(),\n };\n const session: UpgradeSession = {\n connectionId: sessionRecord.connectionId,\n sessionId: sessionRecord.sessionId,\n authorityInstanceId: options.authorityInstanceId,\n handoverGeneration: options.handoverGeneration,\n contractVersion,\n get revoked() {\n return sessionRecord.revoked || !sessions.has(sessionRecord);\n },\n signal: sessionRecord.controller.signal,\n assertActive() {\n if (sessionRecord.revoked || !sessions.has(sessionRecord)) {\n throw new UpgradeGateRejectedError(sessionRecord.reason, \"升级握手会话已失效\");\n }\n if (currentState === \"closed\") {\n throw new UpgradeGateRejectedError(\"closed\", closeReason);\n }\n },\n admit(input) {\n return admitForSession(sessionRecord, input);\n },\n close(reason = \"upgrade session closed\") {\n revokeSession(sessionRecord, reason);\n },\n };\n sessionRecord.session = session;\n sessions.add(sessionRecord);\n sessionByObject.set(session, sessionRecord);\n return {\n accepted: true,\n mode: options.mode ?? \"cold-switch\",\n handoverGeneration: options.handoverGeneration,\n contractVersion,\n connectionId: sessionRecord.connectionId,\n sessionId: sessionRecord.sessionId,\n session,\n };\n };\n\n const admitForSession = (\n sessionRecord: SessionRecord,\n input: { operation: \"read\" | \"write\"; signal?: AbortSignal }\n ): UpgradeIoLease => {\n if (sessionRecord.revoked || !sessions.has(sessionRecord)) {\n throw new UpgradeGateRejectedError(sessionRecord.reason, \"升级握手会话已失效\");\n }\n assertAccepting();\n if (input.signal?.aborted) {\n throw new UpgradeGateRejectedError(\"caller-aborted\", \"I/O 在取得接管租约前已取消\");\n }\n\n const record: LeaseRecord = {\n session: sessionRecord,\n operation: input.operation,\n controller: new AbortController(),\n revoked: false,\n reason: \"upgrade I/O lease released\",\n };\n leases.add(record);\n sessionRecord.leases.add(record);\n if (input.signal) {\n const onAbort = () => revokeLease(record, \"caller-aborted\");\n input.signal.addEventListener(\"abort\", onAbort, { once: true });\n record.removeExternalAbort = () => input.signal?.removeEventListener(\"abort\", onAbort);\n }\n\n const lease: UpgradeIoLease = {\n connectionId: sessionRecord.connectionId,\n sessionId: sessionRecord.sessionId,\n authorityInstanceId: options.authorityInstanceId,\n handoverGeneration: options.handoverGeneration,\n contractVersion: sessionRecord.contractVersion,\n operation: record.operation,\n get revoked() {\n return record.revoked || !leases.has(record);\n },\n signal: record.controller.signal,\n assertActive() {\n if (record.revoked || !leases.has(record)) {\n throw new UpgradeGateRejectedError(record.reason, \"升级 I/O 租约已失效\");\n }\n // beginDrain 不撤销已发租约;它只阻止新 I/O,给已提交操作一个排空窗口。\n if (currentState === \"closed\") {\n throw new UpgradeGateRejectedError(\"closed\", closeReason);\n }\n },\n release() {\n if (record.revoked) return;\n record.revoked = true;\n record.reason = \"upgrade I/O lease released\";\n removeLease(record);\n },\n };\n return lease;\n };\n\n const admit = (input: Parameters<UpgradeGate[\"admit\"]>[0]): UpgradeIoLease => {\n const sessionRecord = sessionByObject.get(input.session);\n if (!sessionRecord) {\n throw new UpgradeGateRejectedError(\"invalid-session\", \"I/O 必须使用当前门禁握手返回的会话\");\n }\n return admitForSession(sessionRecord, input);\n };\n\n const beginDrain = (reason = \"upgrade handover draining\") => {\n if (currentState !== \"active\") return;\n closeReason = reason;\n currentState = \"draining\";\n };\n\n const drain = async (timeoutMs?: number): Promise<UpgradeDrainResult> => {\n beginDrain();\n if (leases.size === 0) return { state: currentState, drained: true, pending: 0 };\n if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs < 0)) {\n throw new Error(\"升级排空 timeoutMs 必须是非负有限数\");\n }\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timerResolve: (() => void) | undefined;\n const empty = new Promise<void>((resolve) => {\n emptyWaiters.add(resolve);\n timerResolve = resolve;\n });\n const timeoutPromise = timeoutMs === undefined\n ? undefined\n : new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs);\n });\n if (timeoutPromise) await Promise.race([empty, timeoutPromise]);\n else await empty;\n if (timeout !== undefined) clearTimeout(timeout);\n if (timerResolve) emptyWaiters.delete(timerResolve);\n const pending = leases.size;\n return { state: currentState, drained: pending === 0, pending };\n };\n\n const close = (reason = \"upgrade gate closed\") => {\n if (currentState === \"closed\") return;\n closeReason = reason;\n currentState = \"closed\";\n for (const session of [...sessions]) revokeSession(session, reason);\n for (const lease of [...leases]) revokeLease(lease, reason);\n notifyEmpty();\n };\n\n return {\n get state() { return currentState; },\n mode: options.mode ?? \"cold-switch\",\n authorityInstanceId: options.authorityInstanceId,\n handoverGeneration: options.handoverGeneration,\n handshake,\n assertAccepting,\n admit,\n beginDrain,\n drain,\n close,\n activeIo: () => leases.size,\n };\n}\n","// WebLoom v4 advanced 装配入口。\n// 这些 API 是同一套 Host/transport 实现的显式扩展,不提供旧 API 兼容层。\n\nexport * from \"./host/createPluginHost.js\";\nexport * from \"./host/pluginGraph.js\";\nexport * from \"./host/capabilityRegistry.js\";\nexport * from \"./host/runtimeUnitImplementationRegistry.js\";\nexport * from \"./lifecycle/resourceScope.js\";\nexport * from \"./lifecycle/permissionLease.js\";\nexport * from \"./lifecycle/permissionVerifier.js\";\nexport * from \"./lifecycle/pluginIntentController.js\";\nexport * from \"./lifecycle/taskScheduler.js\";\nexport * from \"./lifecycle/scopedRegistry.js\";\nexport * from \"./lifecycle/upgradeGate.js\";\nexport { createResourceRegistry, registerOwnedResource } from \"./resources/resourceRegistry.js\";\n/** Resource Store 的 advanced 类型出口;显式 alias 可被 dts bundler 保留。 */\nexport type ResourceStoreApi = import(\"./resources/resourceStore.js\").ResourceStoreApi;\nexport * from \"./transport/serviceBridge.js\";\nexport * from \"./transport/messagePortServiceTransport.js\";\nexport * from \"./transport/messagePortServiceProvider.js\";\nexport { createWindowAppFromHost, hostForWindowApp } from \"./runtime/windowRuntime.js\";\nexport { bridgeForRuntimeHandle } from \"./runtime/connectSharedWorker.js\";\nexport type { PeerController, PeerExposureOptions, StartSharedWorkerAppOptions, StartSharedWorkerAppForTestingOptions, SharedWorkerApp } from \"./runtime/sharedWorkerHost.js\";\nexport * from \"./runtime/runtimeProtocol.js\";\nexport { RuntimeLockError, WEBLOOM_RUNTIME_LOCK_PREFIX } from \"./runtime/runtimeLock.js\";\nexport type { RuntimeLockFailureCode, RuntimeLockManagerLike, RuntimeLockMessages, RuntimeLockOptions, RuntimeLockHandle } from \"./runtime/runtimeLock.js\";\n\nimport type { RuntimeHandle, WindowApp } from \"./runtime/runtimeTypes.js\";\nimport type { RuntimePluginDefinition } from \"./runtime/pluginDefinitions.js\";\nimport { materializePluginDefinitions } from \"./runtime/pluginDefinitions.js\";\nimport { hostForWindowApp } from \"./runtime/windowRuntime.js\";\nimport { bridgeForRuntimeHandle } from \"./runtime/connectSharedWorker.js\";\nimport type { CapabilityBridge } from \"./contracts/capability.js\";\n\n/** 分阶段向已经拥有的 App 注册新的 typed plugin definitions。 */\nexport async function registerPlugins(app: WindowApp, definitions: readonly RuntimePluginDefinition[]): Promise<void> {\n const host = hostForWindowApp(app);\n const materialized = materializePluginDefinitions(definitions, app.runtimeKind);\n for (const definition of materialized) host.registerImplementation({ pluginId: definition.manifest.id, unitId: definition.unitId, setup: definition.setup, capabilities: definition.capabilities });\n await host.registerAll(materialized.map((definition) => definition.manifest));\n}\n\n/** 把一个连接绑定到现有 WindowApp;替换时先撤销旧 bridge。 */\nexport async function attachRemote(app: WindowApp, runtime: RuntimeHandle): Promise<() => void> {\n const host = hostForWindowApp(app);\n const bridge: CapabilityBridge = bridgeForRuntimeHandle(runtime);\n host.attachRemote(bridge);\n await host.reconcile();\n return () => host.detachRemote(\"Remote Runtime detached\");\n}\n"]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { createRuntimeEndpointBinding, createMessagePortRuntimeTransport, createRuntimeEndpointSession, createCapabilityBridge, createPeerScopeView, createCapabilityPeerView, createMessagePortServiceProvider } from './chunk-
|
|
2
|
-
import { RuntimeInitializationError, normalizeRuntimeLimits, createRuntimeBudget, createRuntimeMessageCodec, capabilityKey, materializePluginDefinitions, createRuntimeUnitImplementationRegistry, createPluginHost, RUNTIME_SNAPSHOT_TYPE,
|
|
1
|
+
import { createInMemoryRuntimeLockManager, createRuntimeLock, RuntimeLockError, createRuntimeEndpointBinding, createMessagePortRuntimeTransport, createRuntimeEndpointSession, createCapabilityBridge, createPeerScopeView, createCapabilityPeerView, createMessagePortServiceProvider } from './chunk-YIIDRFHK.js';
|
|
2
|
+
import { RuntimeInitializationError, normalizeRuntimeLimits, createRuntimeBudget, createRuntimeMessageCodec, capabilityKey, materializePluginDefinitions, createRuntimeUnitImplementationRegistry, createPluginHost, RUNTIME_SNAPSHOT_TYPE, RUNTIME_PROTOCOL_VERSION, RUNTIME_ERROR_TYPE, cloneFrozenAttributes, WebLoomError, validateDto } from './chunk-ZP5QYTXX.js';
|
|
3
3
|
|
|
4
4
|
// src/runtime/sharedWorkerHost.ts
|
|
5
|
+
var testRuntimeLockManager = createInMemoryRuntimeLockManager();
|
|
5
6
|
function makeId(prefix) {
|
|
6
7
|
try {
|
|
7
8
|
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return `${prefix}:${crypto.randomUUID()}`;
|
|
@@ -12,7 +13,7 @@ function makeId(prefix) {
|
|
|
12
13
|
function message(error) {
|
|
13
14
|
return error instanceof Error ? error.message : String(error);
|
|
14
15
|
}
|
|
15
|
-
function startSharedWorkerAppInternal(options, injectedScope) {
|
|
16
|
+
function startSharedWorkerAppInternal(options, injectedScope, allowInjectedLockManager = false) {
|
|
16
17
|
if (!options || typeof options.id !== "string" || options.id.trim() === "") throw new TypeError("SharedWorker runtime id must be a non-empty string");
|
|
17
18
|
const scope = injectedScope ?? (globalThis.onconnect !== void 0 ? globalThis : void 0);
|
|
18
19
|
if (!scope) throw new RuntimeInitializationError({ phase: "validate", error: "startSharedWorkerApp must run in a SharedWorkerGlobalScope" });
|
|
@@ -32,6 +33,11 @@ function startSharedWorkerAppInternal(options, injectedScope) {
|
|
|
32
33
|
let accepting = true;
|
|
33
34
|
let host;
|
|
34
35
|
let disposePromise;
|
|
36
|
+
const runtimeLockOptions = options.runtimeLock === void 0 || allowInjectedLockManager ? options.runtimeLock : { messages: options.runtimeLock.messages };
|
|
37
|
+
const runtimeLock = createRuntimeLock(options.id, runtimeLockOptions);
|
|
38
|
+
let runtimeLockSettled = false;
|
|
39
|
+
let runtimeFailure;
|
|
40
|
+
const pendingPorts = [];
|
|
35
41
|
const emitPeerLifecycle = (event) => {
|
|
36
42
|
const frozen = Object.freeze({
|
|
37
43
|
...event,
|
|
@@ -49,7 +55,17 @@ function startSharedWorkerAppInternal(options, injectedScope) {
|
|
|
49
55
|
const currentHost = host;
|
|
50
56
|
const units = currentHost ? currentHost.installed().flatMap((pluginId) => currentHost.state(pluginId).units.map((unit) => ({ pluginId: unit.pluginId, unitId: unit.unitId, runtime: unit.runtime, ...unit.instanceId !== void 0 ? { instanceId: unit.instanceId } : {}, state: unit.kind }))) : [];
|
|
51
57
|
const services = runtimeState === "ready" && host ? host.serviceReferences().map((service) => ({ kind: service.kind, capabilityId: service.capabilityId, contractVersion: service.contractVersion, serviceInstanceId: service.serviceInstanceId, attributes: cloneFrozenAttributes(service.attributes), ...service.grantId !== void 0 ? { grantId: service.grantId } : {}, ...service.authorizationRevision !== void 0 ? { authorizationRevision: service.authorizationRevision } : {} })) : [];
|
|
52
|
-
return Object.freeze({
|
|
58
|
+
return Object.freeze({
|
|
59
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
60
|
+
runtimeId: options.id,
|
|
61
|
+
runtimeKind: "shared-worker",
|
|
62
|
+
runtimeInstanceId,
|
|
63
|
+
revision,
|
|
64
|
+
state: runtimeState,
|
|
65
|
+
units: Object.freeze(units),
|
|
66
|
+
services: Object.freeze(services),
|
|
67
|
+
...runtimeFailure ? { error: runtimeFailure.message, errorCode: runtimeFailure.code } : {}
|
|
68
|
+
});
|
|
53
69
|
};
|
|
54
70
|
const emit = (snapshot = localSnapshot()) => {
|
|
55
71
|
for (const listener of [...listeners]) {
|
|
@@ -90,6 +106,15 @@ function startSharedWorkerAppInternal(options, injectedScope) {
|
|
|
90
106
|
options.snapshotObserver?.(base);
|
|
91
107
|
for (const endpoint of endpoints) {
|
|
92
108
|
try {
|
|
109
|
+
if (runtimeFailure) {
|
|
110
|
+
endpoint.transport.send({
|
|
111
|
+
type: RUNTIME_ERROR_TYPE,
|
|
112
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
113
|
+
code: runtimeFailure.code,
|
|
114
|
+
message: runtimeFailure.message,
|
|
115
|
+
phase: runtimeFailure.phase
|
|
116
|
+
});
|
|
117
|
+
}
|
|
93
118
|
publish(endpoint, endpoint.exposures, base);
|
|
94
119
|
} catch {
|
|
95
120
|
closeEndpoint(endpoint, "Runtime snapshot publication failed");
|
|
@@ -388,12 +413,73 @@ function startSharedWorkerAppInternal(options, injectedScope) {
|
|
|
388
413
|
}
|
|
389
414
|
}
|
|
390
415
|
};
|
|
416
|
+
const sendRuntimeFailure = (port) => {
|
|
417
|
+
if (!runtimeFailure) {
|
|
418
|
+
sendTerminalSnapshot(port);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
try {
|
|
422
|
+
port.start();
|
|
423
|
+
port.postMessage({
|
|
424
|
+
type: RUNTIME_ERROR_TYPE,
|
|
425
|
+
protocolVersion: RUNTIME_PROTOCOL_VERSION,
|
|
426
|
+
code: runtimeFailure.code,
|
|
427
|
+
message: runtimeFailure.message,
|
|
428
|
+
phase: runtimeFailure.phase
|
|
429
|
+
});
|
|
430
|
+
setTimeout(() => {
|
|
431
|
+
try {
|
|
432
|
+
port.close();
|
|
433
|
+
} catch {
|
|
434
|
+
}
|
|
435
|
+
}, 0);
|
|
436
|
+
} catch {
|
|
437
|
+
try {
|
|
438
|
+
port.close();
|
|
439
|
+
} catch {
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
const drainPendingPorts = () => {
|
|
444
|
+
const ports = pendingPorts.splice(0);
|
|
445
|
+
for (const port of ports) {
|
|
446
|
+
if (!accepting || disposed || endpoints.size >= limits.maxPeers) {
|
|
447
|
+
sendTerminalSnapshot(port);
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
if (runtimeFailure) {
|
|
451
|
+
sendRuntimeFailure(port);
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
try {
|
|
455
|
+
createEndpoint(port);
|
|
456
|
+
} catch {
|
|
457
|
+
try {
|
|
458
|
+
port.close();
|
|
459
|
+
} catch {
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
const failPendingPorts = () => {
|
|
465
|
+
const ports = pendingPorts.splice(0);
|
|
466
|
+
for (const port of ports) sendRuntimeFailure(port);
|
|
467
|
+
};
|
|
391
468
|
scope.onconnect = (event) => {
|
|
392
469
|
for (const port of event.ports ?? []) {
|
|
393
470
|
if (!accepting || disposed || endpoints.size >= limits.maxPeers) {
|
|
394
471
|
sendTerminalSnapshot(port);
|
|
395
472
|
continue;
|
|
396
473
|
}
|
|
474
|
+
if (!runtimeLockSettled) {
|
|
475
|
+
if (pendingPorts.length >= limits.maxPeers) sendTerminalSnapshot(port);
|
|
476
|
+
else pendingPorts.push(port);
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
if (runtimeFailure) {
|
|
480
|
+
sendRuntimeFailure(port);
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
397
483
|
try {
|
|
398
484
|
createEndpoint(port);
|
|
399
485
|
} catch {
|
|
@@ -404,11 +490,13 @@ function startSharedWorkerAppInternal(options, injectedScope) {
|
|
|
404
490
|
}
|
|
405
491
|
}
|
|
406
492
|
};
|
|
407
|
-
|
|
493
|
+
const ready = runtimeLock.acquired.then(async () => {
|
|
494
|
+
if (disposed) throw new Error("SharedWorker Runtime was disposed before the browser lock was acquired");
|
|
495
|
+
runtimeLockSettled = true;
|
|
408
496
|
const materialized = materializePluginDefinitions(options.plugins, "shared-worker");
|
|
409
497
|
manifests = materialized.map((item) => item.manifest);
|
|
410
498
|
const implementations = createRuntimeUnitImplementationRegistry(materialized.map((item) => ({ pluginId: item.manifest.id, unitId: item.unitId, setup: item.setup, capabilities: item.capabilities })));
|
|
411
|
-
const { id: _id, plugins: _plugins, expose: _expose, configurePeer: _configurePeer, ...hostOptions } = options;
|
|
499
|
+
const { id: _id, plugins: _plugins, expose: _expose, configurePeer: _configurePeer, runtimeLock: _runtimeLock, ...hostOptions } = options;
|
|
412
500
|
host = createPluginHost({ ...hostOptions, runtime: "shared-worker", runtimeId: options.id, runtimeInstanceId, runtimeUnitImplementationRegistry: implementations });
|
|
413
501
|
host.subscribe(() => {
|
|
414
502
|
if (runtimeState === "ready" && !disposed) {
|
|
@@ -416,33 +504,25 @@ function startSharedWorkerAppInternal(options, injectedScope) {
|
|
|
416
504
|
publishAll();
|
|
417
505
|
} else emit();
|
|
418
506
|
});
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
const failure = new RuntimeInitializationError({ phase: "validate", error: message(error) });
|
|
422
|
-
const failedReady = Promise.reject(failure);
|
|
423
|
-
void failedReady.catch(() => void 0);
|
|
424
|
-
const failedInspection = () => ({ runtimeId: options.id, runtimeKind: "shared-worker", runtimeInstanceId, version: 0, pluginCount: 0, peerCount: endpoints.size, pendingCallCount: 0, activeStreamCount: 0, plugins: [] });
|
|
425
|
-
return { runtimeKind: "shared-worker", runtimeId: options.id, runtimeInstanceId, ready: () => failedReady, reconcile: async () => failedReady, state: localSnapshot, subscribe(listener) {
|
|
426
|
-
listeners.add(listener);
|
|
427
|
-
listener(localSnapshot());
|
|
428
|
-
return () => listeners.delete(listener);
|
|
429
|
-
}, inspect: failedInspection, activePeers: () => Object.freeze([]), subscribePeerLifecycle(listener) {
|
|
430
|
-
peerLifecycleListeners.add(listener);
|
|
431
|
-
return () => peerLifecycleListeners.delete(listener);
|
|
432
|
-
}, notifyPeerHandoff: () => false, dispose: async () => ({ scopeId: `runtime:${runtimeInstanceId}`, state: "stopped", attempted: 0, released: 0, pending: [], errors: [], cleanupIncomplete: false }) };
|
|
433
|
-
}
|
|
434
|
-
const ready = host.registerAll(manifests).then(() => {
|
|
507
|
+
drainPendingPorts();
|
|
508
|
+
await host.registerAll(manifests);
|
|
435
509
|
for (const endpoint of endpoints) endpoint.installTopLevelExposures();
|
|
436
510
|
if (!disposed) {
|
|
437
511
|
runtimeState = "ready";
|
|
438
512
|
revision += 1;
|
|
439
513
|
publishAll();
|
|
440
514
|
}
|
|
441
|
-
}
|
|
515
|
+
}).catch((error) => {
|
|
442
516
|
if (!disposed) {
|
|
443
517
|
runtimeState = "failed";
|
|
518
|
+
const code = error instanceof RuntimeLockError ? error.code : error && typeof error === "object" && typeof error.code === "string" ? error.code : "runtime_initialization_failed";
|
|
519
|
+
runtimeFailure = { code, message: message(error), phase: error instanceof RuntimeLockError ? "wait" : "execute" };
|
|
520
|
+
runtimeLockSettled = true;
|
|
521
|
+
failPendingPorts();
|
|
444
522
|
publishAll();
|
|
445
523
|
}
|
|
524
|
+
void runtimeLock.release();
|
|
525
|
+
if (error instanceof RuntimeLockError) throw error;
|
|
446
526
|
throw new RuntimeInitializationError({ phase: "startup", error: message(error) });
|
|
447
527
|
});
|
|
448
528
|
void ready.catch(() => void 0);
|
|
@@ -475,6 +555,8 @@ function startSharedWorkerAppInternal(options, injectedScope) {
|
|
|
475
555
|
if (disposePromise) return disposePromise;
|
|
476
556
|
accepting = false;
|
|
477
557
|
disposed = true;
|
|
558
|
+
runtimeLockSettled = true;
|
|
559
|
+
for (const port of pendingPorts.splice(0)) sendTerminalSnapshot(port);
|
|
478
560
|
runtimeState = "stopping";
|
|
479
561
|
const endpointsToClose = [...endpoints];
|
|
480
562
|
publishAll();
|
|
@@ -493,6 +575,7 @@ function startSharedWorkerAppInternal(options, injectedScope) {
|
|
|
493
575
|
emit(terminal);
|
|
494
576
|
const endpointClosures = endpointsToClose.map((endpoint) => closeEndpoint(endpoint, reason));
|
|
495
577
|
await Promise.all(endpointClosures);
|
|
578
|
+
await runtimeLock.release();
|
|
496
579
|
return result;
|
|
497
580
|
})();
|
|
498
581
|
return disposePromise;
|
|
@@ -505,9 +588,10 @@ function startSharedWorkerApp(options) {
|
|
|
505
588
|
}
|
|
506
589
|
function startSharedWorkerAppForTesting(options) {
|
|
507
590
|
const { globalScope, ...runtimeOptions } = options;
|
|
508
|
-
|
|
591
|
+
const withTestLock = runtimeOptions.runtimeLock === void 0 ? { ...runtimeOptions, runtimeLock: { manager: testRuntimeLockManager } } : runtimeOptions;
|
|
592
|
+
return startSharedWorkerAppInternal(withTestLock, globalScope, true);
|
|
509
593
|
}
|
|
510
594
|
|
|
511
595
|
export { startSharedWorkerApp, startSharedWorkerAppForTesting };
|
|
512
|
-
//# sourceMappingURL=chunk-
|
|
513
|
-
//# sourceMappingURL=chunk-
|
|
596
|
+
//# sourceMappingURL=chunk-UZAO6ORB.js.map
|
|
597
|
+
//# sourceMappingURL=chunk-UZAO6ORB.js.map
|