@opetope/runtime 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (314) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +345 -0
  4. package/README.ru.md +344 -0
  5. package/dist/application-compiler-edges.d.ts +3 -0
  6. package/dist/application-compiler-edges.js +2 -0
  7. package/dist/application-compiler-edges.js.map +1 -0
  8. package/dist/application-compiler-graph.d.ts +8 -0
  9. package/dist/application-compiler-graph.js +2 -0
  10. package/dist/application-compiler-graph.js.map +1 -0
  11. package/dist/application-compiler.d.ts +116 -0
  12. package/dist/application-compiler.js +2 -0
  13. package/dist/application-compiler.js.map +1 -0
  14. package/dist/application-conditions.d.ts +18 -0
  15. package/dist/application-conditions.js +2 -0
  16. package/dist/application-conditions.js.map +1 -0
  17. package/dist/application-definition.d.ts +30 -0
  18. package/dist/application-definition.js +2 -0
  19. package/dist/application-definition.js.map +1 -0
  20. package/dist/application-error.d.ts +10 -0
  21. package/dist/application-error.js +2 -0
  22. package/dist/application-error.js.map +1 -0
  23. package/dist/application-execution.d.ts +43 -0
  24. package/dist/application-execution.js +2 -0
  25. package/dist/application-execution.js.map +1 -0
  26. package/dist/application-feature-bindings.d.ts +11 -0
  27. package/dist/application-feature-bindings.js +2 -0
  28. package/dist/application-feature-bindings.js.map +1 -0
  29. package/dist/application-feature-instance.d.ts +5 -0
  30. package/dist/application-feature-instance.js +2 -0
  31. package/dist/application-feature-instance.js.map +1 -0
  32. package/dist/application-group-order.d.ts +29 -0
  33. package/dist/application-group-order.js +2 -0
  34. package/dist/application-group-order.js.map +1 -0
  35. package/dist/application-instance-retirement.d.ts +36 -0
  36. package/dist/application-instance-retirement.js +2 -0
  37. package/dist/application-instance-retirement.js.map +1 -0
  38. package/dist/application-open-options.d.ts +29 -0
  39. package/dist/application-open-options.js +2 -0
  40. package/dist/application-open-options.js.map +1 -0
  41. package/dist/application-port-compiler.d.ts +28 -0
  42. package/dist/application-port-compiler.js +2 -0
  43. package/dist/application-port-compiler.js.map +1 -0
  44. package/dist/attachment-call-declaration.d.ts +43 -0
  45. package/dist/attachment-call-declaration.js +2 -0
  46. package/dist/attachment-call-declaration.js.map +1 -0
  47. package/dist/attachment-declaration.d.ts +68 -0
  48. package/dist/attachment-declaration.js +2 -0
  49. package/dist/attachment-declaration.js.map +1 -0
  50. package/dist/attachment-execution.d.ts +9 -0
  51. package/dist/attachment-execution.js +2 -0
  52. package/dist/attachment-execution.js.map +1 -0
  53. package/dist/attachment-retirement-scheduler.d.ts +14 -0
  54. package/dist/attachment-retirement-scheduler.js +2 -0
  55. package/dist/attachment-retirement-scheduler.js.map +1 -0
  56. package/dist/call-option-snapshot.d.ts +20 -0
  57. package/dist/call-option-snapshot.js +2 -0
  58. package/dist/call-option-snapshot.js.map +1 -0
  59. package/dist/compile-call-target-bindings.d.ts +14 -0
  60. package/dist/compile-call-target-bindings.js +2 -0
  61. package/dist/compile-call-target-bindings.js.map +1 -0
  62. package/dist/compile-module-template.d.ts +38 -0
  63. package/dist/compile-module-template.js +2 -0
  64. package/dist/compile-module-template.js.map +1 -0
  65. package/dist/condition-group-execution.d.ts +44 -0
  66. package/dist/condition-group-execution.js +2 -0
  67. package/dist/condition-group-execution.js.map +1 -0
  68. package/dist/condition-override.d.ts +28 -0
  69. package/dist/condition-override.js +2 -0
  70. package/dist/condition-override.js.map +1 -0
  71. package/dist/condition-source.d.ts +10 -0
  72. package/dist/condition-source.js +2 -0
  73. package/dist/condition-source.js.map +1 -0
  74. package/dist/condition-types.d.ts +14 -0
  75. package/dist/condition.d.ts +28 -0
  76. package/dist/condition.js +2 -0
  77. package/dist/condition.js.map +1 -0
  78. package/dist/control-registry.d.ts +56 -0
  79. package/dist/control-registry.js +2 -0
  80. package/dist/control-registry.js.map +1 -0
  81. package/dist/dynamic-scope-child.d.ts +23 -0
  82. package/dist/dynamic-scope-child.js +2 -0
  83. package/dist/dynamic-scope-child.js.map +1 -0
  84. package/dist/dynamic-scope-controller.d.ts +16 -0
  85. package/dist/dynamic-scope-controller.js +2 -0
  86. package/dist/dynamic-scope-controller.js.map +1 -0
  87. package/dist/feature-attachment-authoring-types.d.ts +51 -0
  88. package/dist/feature-attachment-lowering.d.ts +18 -0
  89. package/dist/feature-attachment-lowering.js +2 -0
  90. package/dist/feature-attachment-lowering.js.map +1 -0
  91. package/dist/feature-attachment.d.ts +45 -0
  92. package/dist/feature-attachment.js +2 -0
  93. package/dist/feature-attachment.js.map +1 -0
  94. package/dist/feature-authoring-types.d.ts +196 -0
  95. package/dist/feature-authoring.d.ts +15 -0
  96. package/dist/feature-authoring.js +2 -0
  97. package/dist/feature-authoring.js.map +1 -0
  98. package/dist/feature-body.d.ts +53 -0
  99. package/dist/feature-body.js +2 -0
  100. package/dist/feature-body.js.map +1 -0
  101. package/dist/feature-call-authority.d.ts +8 -0
  102. package/dist/feature-call-authority.js +2 -0
  103. package/dist/feature-call-authority.js.map +1 -0
  104. package/dist/feature-call-types.d.ts +39 -0
  105. package/dist/feature-call.d.ts +18 -0
  106. package/dist/feature-call.js +2 -0
  107. package/dist/feature-call.js.map +1 -0
  108. package/dist/feature-calls.d.ts +6 -0
  109. package/dist/feature-calls.js +2 -0
  110. package/dist/feature-calls.js.map +1 -0
  111. package/dist/feature-contract.d.ts +70 -0
  112. package/dist/feature-contract.js +2 -0
  113. package/dist/feature-contract.js.map +1 -0
  114. package/dist/feature-contribution-model.d.ts +38 -0
  115. package/dist/feature-contribution-model.js +2 -0
  116. package/dist/feature-contribution-model.js.map +1 -0
  117. package/dist/feature-contribution.d.ts +126 -0
  118. package/dist/feature-contribution.js +2 -0
  119. package/dist/feature-contribution.js.map +1 -0
  120. package/dist/feature-definition-api.d.ts +53 -0
  121. package/dist/feature-definition-support.d.ts +21 -0
  122. package/dist/feature-definition-support.js +2 -0
  123. package/dist/feature-definition-support.js.map +1 -0
  124. package/dist/feature-effect.d.ts +26 -0
  125. package/dist/feature-effect.js +2 -0
  126. package/dist/feature-effect.js.map +1 -0
  127. package/dist/feature-event.d.ts +32 -0
  128. package/dist/feature-event.js +2 -0
  129. package/dist/feature-event.js.map +1 -0
  130. package/dist/feature-generation.d.ts +34 -0
  131. package/dist/feature-generation.js +2 -0
  132. package/dist/feature-generation.js.map +1 -0
  133. package/dist/feature-lazy-generation.d.ts +6 -0
  134. package/dist/feature-lazy-generation.js +2 -0
  135. package/dist/feature-lazy-generation.js.map +1 -0
  136. package/dist/feature-lazy.d.ts +44 -0
  137. package/dist/feature-lazy.js +2 -0
  138. package/dist/feature-lazy.js.map +1 -0
  139. package/dist/feature-materialization-binding.d.ts +31 -0
  140. package/dist/feature-materialization-binding.js +2 -0
  141. package/dist/feature-materialization-binding.js.map +1 -0
  142. package/dist/feature-materialization-types.d.ts +45 -0
  143. package/dist/feature-model-dependencies.d.ts +23 -0
  144. package/dist/feature-model-dependencies.js +2 -0
  145. package/dist/feature-model-dependencies.js.map +1 -0
  146. package/dist/feature-model.d.ts +60 -0
  147. package/dist/feature-model.js +2 -0
  148. package/dist/feature-model.js.map +1 -0
  149. package/dist/feature-optional.d.ts +15 -0
  150. package/dist/feature-optional.js +2 -0
  151. package/dist/feature-optional.js.map +1 -0
  152. package/dist/feature-own-lowering.d.ts +22 -0
  153. package/dist/feature-own-lowering.js +2 -0
  154. package/dist/feature-own-lowering.js.map +1 -0
  155. package/dist/feature-port-binding.d.ts +6 -0
  156. package/dist/feature-port-binding.js +2 -0
  157. package/dist/feature-port-binding.js.map +1 -0
  158. package/dist/feature-port.d.ts +66 -0
  159. package/dist/feature-port.js +2 -0
  160. package/dist/feature-port.js.map +1 -0
  161. package/dist/feature-record.d.ts +6 -0
  162. package/dist/feature-record.js +2 -0
  163. package/dist/feature-record.js.map +1 -0
  164. package/dist/feature-resource.d.ts +29 -0
  165. package/dist/feature-resource.js +2 -0
  166. package/dist/feature-resource.js.map +1 -0
  167. package/dist/feature-scope-types.d.ts +35 -0
  168. package/dist/feature-scope.d.ts +29 -0
  169. package/dist/feature-scope.js +2 -0
  170. package/dist/feature-scope.js.map +1 -0
  171. package/dist/feature-stream.d.ts +37 -0
  172. package/dist/feature-stream.js +2 -0
  173. package/dist/feature-stream.js.map +1 -0
  174. package/dist/feature-timers.d.ts +14 -0
  175. package/dist/feature-timers.js +2 -0
  176. package/dist/feature-timers.js.map +1 -0
  177. package/dist/index.d.ts +19 -0
  178. package/dist/index.js +2 -0
  179. package/dist/index.js.map +1 -0
  180. package/dist/inspection-activity-protocol.d.ts +63 -0
  181. package/dist/inspection-activity.d.ts +54 -0
  182. package/dist/inspection-activity.js +2 -0
  183. package/dist/inspection-activity.js.map +1 -0
  184. package/dist/inspection-diff.d.ts +10 -0
  185. package/dist/inspection-diff.js +2 -0
  186. package/dist/inspection-diff.js.map +1 -0
  187. package/dist/inspection-module-activity.d.ts +4 -0
  188. package/dist/inspection-module-activity.js +2 -0
  189. package/dist/inspection-module-activity.js.map +1 -0
  190. package/dist/inspection-observer.d.ts +38 -0
  191. package/dist/inspection-observer.js +2 -0
  192. package/dist/inspection-observer.js.map +1 -0
  193. package/dist/inspection-plan.d.ts +33 -0
  194. package/dist/inspection-plan.js +2 -0
  195. package/dist/inspection-plan.js.map +1 -0
  196. package/dist/inspection-protocol.d.ts +333 -0
  197. package/dist/inspection-protocol.js +2 -0
  198. package/dist/inspection-protocol.js.map +1 -0
  199. package/dist/inspection-registry.d.ts +41 -0
  200. package/dist/inspection-registry.js +2 -0
  201. package/dist/inspection-registry.js.map +1 -0
  202. package/dist/inspection-session.d.ts +92 -0
  203. package/dist/inspection-session.js +2 -0
  204. package/dist/inspection-session.js.map +1 -0
  205. package/dist/inspection-snapshot.d.ts +4 -0
  206. package/dist/inspection-snapshot.js +2 -0
  207. package/dist/inspection-snapshot.js.map +1 -0
  208. package/dist/inspection-state.d.ts +91 -0
  209. package/dist/inspection-state.js +2 -0
  210. package/dist/inspection-state.js.map +1 -0
  211. package/dist/instance-demand.d.ts +31 -0
  212. package/dist/instance-demand.js +2 -0
  213. package/dist/instance-demand.js.map +1 -0
  214. package/dist/internal.d.ts +41 -0
  215. package/dist/internal.js +2 -0
  216. package/dist/internal.js.map +1 -0
  217. package/dist/keyed-scope-controller.d.ts +11 -0
  218. package/dist/keyed-scope-controller.js +2 -0
  219. package/dist/keyed-scope-controller.js.map +1 -0
  220. package/dist/model-kernel.d.ts +18 -0
  221. package/dist/model-kernel.js +2 -0
  222. package/dist/model-kernel.js.map +1 -0
  223. package/dist/module-call-context.d.ts +7 -0
  224. package/dist/module-call-context.js +2 -0
  225. package/dist/module-call-context.js.map +1 -0
  226. package/dist/module-call-runtime.d.ts +21 -0
  227. package/dist/module-call-runtime.js +2 -0
  228. package/dist/module-call-runtime.js.map +1 -0
  229. package/dist/module-generation.d.ts +57 -0
  230. package/dist/module-generation.js +2 -0
  231. package/dist/module-generation.js.map +1 -0
  232. package/dist/module-instance-types.d.ts +156 -0
  233. package/dist/module-instance.d.ts +19 -0
  234. package/dist/module-instance.js +2 -0
  235. package/dist/module-instance.js.map +1 -0
  236. package/dist/module-runtime-identity.d.ts +4 -0
  237. package/dist/module-runtime-identity.js +2 -0
  238. package/dist/module-runtime-identity.js.map +1 -0
  239. package/dist/module-scope-open.d.ts +4 -0
  240. package/dist/module-scope-open.js +2 -0
  241. package/dist/module-scope-open.js.map +1 -0
  242. package/dist/module-scope-retirement.d.ts +3 -0
  243. package/dist/module-scope-retirement.js +2 -0
  244. package/dist/module-scope-retirement.js.map +1 -0
  245. package/dist/module-template-ir.d.ts +59 -0
  246. package/dist/owner-generation-retirement.d.ts +6 -0
  247. package/dist/owner-generation-retirement.js +2 -0
  248. package/dist/owner-generation-retirement.js.map +1 -0
  249. package/dist/owner-generation-state.d.ts +123 -0
  250. package/dist/owner-generation-state.js +2 -0
  251. package/dist/owner-generation-state.js.map +1 -0
  252. package/dist/owner-generation.d.ts +16 -0
  253. package/dist/owner-generation.js +2 -0
  254. package/dist/owner-generation.js.map +1 -0
  255. package/dist/public-module-definition.d.ts +9 -0
  256. package/dist/public-module-definition.js +2 -0
  257. package/dist/public-module-definition.js.map +1 -0
  258. package/dist/public-module-instance.d.ts +6 -0
  259. package/dist/public-module-instance.js +2 -0
  260. package/dist/public-module-instance.js.map +1 -0
  261. package/dist/public-module-retirement-diagnostics.d.ts +5 -0
  262. package/dist/public-module-retirement-diagnostics.js +2 -0
  263. package/dist/public-module-retirement-diagnostics.js.map +1 -0
  264. package/dist/public-module-retirement.d.ts +3 -0
  265. package/dist/public-module-retirement.js +2 -0
  266. package/dist/public-module-retirement.js.map +1 -0
  267. package/dist/public-module-scope.d.ts +5 -0
  268. package/dist/public-module-scope.js +2 -0
  269. package/dist/public-module-scope.js.map +1 -0
  270. package/dist/public-module-state.d.ts +28 -0
  271. package/dist/public-module-state.js +2 -0
  272. package/dist/public-module-state.js.map +1 -0
  273. package/dist/public-module-types.d.ts +295 -0
  274. package/dist/public-module.d.ts +4 -0
  275. package/dist/resource-cache.d.ts +12 -0
  276. package/dist/resource-cache.js +2 -0
  277. package/dist/resource-cache.js.map +1 -0
  278. package/dist/resource-controller.d.ts +29 -0
  279. package/dist/resource-controller.js +2 -0
  280. package/dist/resource-controller.js.map +1 -0
  281. package/dist/resource-policy.d.ts +16 -0
  282. package/dist/resource-policy.js +2 -0
  283. package/dist/resource-policy.js.map +1 -0
  284. package/dist/resource-snapshot.d.ts +12 -0
  285. package/dist/resource-snapshot.js +2 -0
  286. package/dist/resource-snapshot.js.map +1 -0
  287. package/dist/resource-types.d.ts +3 -0
  288. package/dist/runtime-error-reporting.d.ts +4 -0
  289. package/dist/runtime-error-reporting.js +2 -0
  290. package/dist/runtime-error-reporting.js.map +1 -0
  291. package/dist/stream-backpressure.d.ts +18 -0
  292. package/dist/stream-backpressure.js +2 -0
  293. package/dist/stream-backpressure.js.map +1 -0
  294. package/dist/stream-cleanup.d.ts +17 -0
  295. package/dist/stream-cleanup.js +2 -0
  296. package/dist/stream-cleanup.js.map +1 -0
  297. package/dist/stream-controller-types.d.ts +51 -0
  298. package/dist/stream-controller.d.ts +5 -0
  299. package/dist/stream-controller.js +2 -0
  300. package/dist/stream-controller.js.map +1 -0
  301. package/docs/agent-guide.md +214 -0
  302. package/docs/agent-guide.ru.md +208 -0
  303. package/docs/cookbook.md +734 -0
  304. package/docs/cookbook.ru.md +729 -0
  305. package/docs/decisions.md +1437 -0
  306. package/docs/devtools.md +423 -0
  307. package/docs/devtools.ru.md +419 -0
  308. package/docs/how-it-works.md +521 -0
  309. package/docs/how-it-works.ru.md +495 -0
  310. package/docs/releases.md +78 -0
  311. package/docs/releases.ru.md +78 -0
  312. package/docs/spec.md +874 -0
  313. package/docs/spec.ru.md +884 -0
  314. package/package.json +72 -0
@@ -0,0 +1,57 @@
1
+ import { FeatureError } from '@opetope/core';
2
+ import type { DeclarationId } from '@opetope/core';
3
+ import type { ExactInput, IsAny } from '@opetope/core/internal';
4
+ import type { CleanupFailurePolicy, ErrorReporter, ModuleDefinition, ModuleInstanceRef, ModuleRuntimeRecord, ModuleScopeRef } from './public-module.js';
5
+ type SynchronousResult<Value> = [Value] extends [never] ? unknown : IsAny<Value> extends true ? never : [Extract<Value, PromiseLike<unknown>>] extends [never] ? unknown : never;
6
+ type GenerationScopeValues<Runtime extends Readonly<Record<string, unknown>>> = string extends keyof Runtime ? never : {
7
+ readonly [Key in keyof Runtime as Runtime[Key] extends ModuleScopeRef<infer _Value, infer _Id> ? Key : never]: Runtime[Key] extends ModuleScopeRef<infer Value, infer _Id> ? Value : never;
8
+ };
9
+ type GenerationNotReadyFailure = {
10
+ readonly attachmentId: DeclarationId | undefined;
11
+ readonly cause: unknown;
12
+ readonly phase: 'open';
13
+ readonly reason: 'cancelled' | 'closed' | 'failed' | 'quarantined' | 'retired' | 'superseded' | 'threw';
14
+ readonly scope: string;
15
+ readonly stage: 'scope';
16
+ } | {
17
+ readonly cause: unknown;
18
+ readonly phase: 'open';
19
+ readonly stage: 'prepare';
20
+ };
21
+ /**
22
+ * The handle a host holds for one opened feature. It is the kernel's instance ref, named with the author's word,
23
+ * Because a public member must not spell a kernel concept (D114).
24
+ */
25
+ type FeatureInstanceHandle<Id extends string> = ModuleInstanceRef<Id>;
26
+ interface FeatureInstance<Id extends string, Prepared = void> {
27
+ readonly close: () => Promise<void>;
28
+ readonly instance: FeatureInstanceHandle<Id>;
29
+ readonly ready: Promise<Prepared>;
30
+ }
31
+ interface GenerationBaseOptions<Runtime extends Readonly<Record<string, unknown>>, Values> {
32
+ readonly cleanupFailure?: CleanupFailurePolicy;
33
+ readonly reporter: ErrorReporter;
34
+ readonly scopes: ExactInput<Values, GenerationScopeValues<Runtime>>;
35
+ }
36
+ interface GenerationPreparedOptions<Id extends string, Runtime extends ModuleRuntimeRecord<Id>, Values, Prepared> extends GenerationBaseOptions<Runtime, Values> {
37
+ readonly prepare: (instance: ModuleInstanceRef<Id>) => Prepared;
38
+ }
39
+ type GenerationUnpreparedOptions<Runtime extends Readonly<Record<string, unknown>>, Values> = GenerationBaseOptions<Runtime, Values> & {
40
+ readonly prepare?: never;
41
+ };
42
+ /**
43
+ * The top line names what failed and why. The cause used to sit two levels down, so an author read «preparation
44
+ * Failed» and had to walk `failure.cause` by hand to find the key and the sentence.
45
+ */
46
+ declare function notReadyGeneration(moduleId: DeclarationId, failure: GenerationNotReadyFailure): FeatureError;
47
+ /** Idempotent by construction: `retire()` of an already retiring instance returns the same record (D189). */
48
+ declare function fenceFeatureGeneration(generation: object): void;
49
+ /** D186: a lazy header hands out its own object, so it registers the fence that reaches the instance it opens. */
50
+ declare function registerFeatureGenerationFence(generation: object, fence: () => void): void;
51
+ /** A feature with contributions hands out a wrapper, and the fence follows the object the application holds. */
52
+ declare function carryFeatureGenerationFence(from: object, to: object): void;
53
+ declare function quarantinedGeneration(moduleId: DeclarationId, failures: readonly unknown[], cause: unknown, retryOperation: () => Promise<void>): FeatureError;
54
+ declare function openFeature<const Id extends string, const Runtime extends ModuleRuntimeRecord<Id>, const Values extends GenerationScopeValues<Runtime>, const Options extends GenerationUnpreparedOptions<Runtime, Values>>(definition: ModuleDefinition<Id, Runtime>, options: ExactInput<Options, GenerationUnpreparedOptions<Runtime, Values>>): FeatureInstance<Id>;
55
+ declare function openFeature<const Id extends string, const Runtime extends ModuleRuntimeRecord<Id>, const Values extends GenerationScopeValues<Runtime>, Prepared, const Options extends GenerationPreparedOptions<Id, Runtime, Values, Prepared>>(definition: ModuleDefinition<Id, Runtime>, options: ExactInput<Options, GenerationPreparedOptions<Id, Runtime, Values, Prepared>> & SynchronousResult<Prepared>): FeatureInstance<Id, Prepared>;
56
+ export { carryFeatureGenerationFence, fenceFeatureGeneration, notReadyGeneration, openFeature, quarantinedGeneration, registerFeatureGenerationFence, };
57
+ export type { FeatureInstance };
@@ -0,0 +1,2 @@
1
+ import{FeatureError as E}from"@opetope/core";import{hasOwn as l}from"@opetope/core/internal";import{assertPlainRecord as T}from"./feature-record.js";import{reportRuntimeFailure as j}from"./runtime-error-reporting.js";import{instantiateModule as C}from"./public-module-instance.js";import{getModuleScopeEntries as P}from"./public-module-definition.js";import{projectModuleCleanupFailures as z}from"./public-module-retirement-diagnostics.js";const x=Object.freeze([]),I=new Set(["cleanupFailure","prepare","reporter","scopes"]);function U(e){return e instanceof Error?` ${e.message}`:typeof e=="string"&&e.length>0?` ${e}`:""}function V(e){return e.stage==="prepare"?"preparation failed":e.attachmentId===void 0?`scope ${e.scope} failed to open`:`attachment ${e.attachmentId.slice(e.attachmentId.lastIndexOf("/")+1)} failed to open`}function k(e,n){const t=V(n);return new E("not-ready",e,{failure:n,message:`Feature ${e} instance ${t}.${U(n.cause)}`})}const h=new WeakMap;function A(e){var n;(n=h.get(e))==null||n()}function W(e,n){h.set(e,n)}function B(e,n){const t=h.get(e);t!==void 0&&h.set(n,t)}function D(e){let n,t=e;const i=()=>{t=()=>n??Promise.resolve()};return()=>{const a=t();return n!==void 0||(n=a,a.then(i,i)),a}}function $(e,n,t,i){return new E("quarantined",e,{cause:t,failures:n,retryCleanup:D(i)})}function H(e,n){T(n,"openFeature scopes");const t=P(e),i=new Set(t.map(r=>r.key)),a=Reflect.ownKeys(n);for(const r of a)if(typeof r!="string"||!i.has(r))throw new TypeError(`Unknown openFeature scope ${String(r)}.`);if(a.length!==t.length){const r=t.find(y=>!l(n,y.key));throw new TypeError(`openFeature requires scope ${(r==null?void 0:r.key)??"<unknown>"}.`)}return t.map(r=>({key:r.key,scope:r.scope,value:Reflect.get(n,r.key)}))}function J(e){for(const n of Reflect.ownKeys(e))if(!I.has(n))throw new TypeError(`Unknown openFeature option ${String(n)}.`)}function L(e){if(!l(e,"scopes"))throw new TypeError("openFeature requires own scopes.");if(!l(e,"reporter"))throw new TypeError("openFeature requires own reporter.")}function N(e){const n=l(e,"cleanupFailure")?Reflect.get(e,"cleanupFailure"):"report";if(n!=="report"&&n!=="quarantine")throw new TypeError('openFeature cleanupFailure must be "report" or "quarantine".');return n}function Q(e){const n=l(e,"prepare")?Reflect.get(e,"prepare"):void 0;if(n!==void 0&&typeof n!="function")throw new TypeError("openFeature prepare must be a function.");return n}function X(e){const n=Reflect.get(e,"reporter");if(typeof n!="function")throw new TypeError("openFeature reporter must be a function.");return n}function Y(e,n){return T(n,"openFeature options"),J(n),L(n),{cleanupFailure:N(n),prepare:Q(n),reporter:X(n),scopes:H(e,Reflect.get(n,"scopes"))}}function Z(e){return(typeof e!="object"||e===null)&&typeof e!="function"?!1:typeof Reflect.get(e,"then")=="function"}function _(e,n,t){return k(e,Object.freeze({attachmentId:void 0,cause:t,phase:"open",reason:"threw",scope:n.key,stage:"scope"}))}function v(e,n,t){if(t.kind!=="ready")return k(e,Object.freeze({attachmentId:t.kind==="not-ready"?t.attachmentId:void 0,cause:t.kind==="not-ready"?t.cause:void 0,phase:"open",reason:t.kind==="not-ready"?t.reason:"retired",scope:n.key,stage:"scope"}))}async function ee(e,n,t){try{const i=await n.scope(t.scope).open(t.value);return v(e,t,i)}catch(i){return _(e,t,i)}}function ne(e,n){Promise.resolve(e).catch(t=>j(t,n))}function te(e,n,t,i,a){let r,y=!1,R=!1,w;const G=(o,u)=>{let s;const p=z(n,o.failures);return $(e,p,u,()=>{const g=n.retire();if(s!==void 0)return s;const f=g.retry().then(O=>{if(O.kind==="quarantined")throw G(O,u)});return s=f,w=f,f})},K=()=>{R=!0,n.retire()},d=o=>{const u=n.retire();if(w!==void 0)return w;const s=u.drain().then(p=>{if(p.kind==="quarantined")throw G(p,o)});return w=s,s},F=()=>{if(R)return r??(r=new E("retired",e))},q=()=>{a=x};let c,m;try{if(c=t==null?void 0:t(n),Z(c)){const o=c;throw c=void 0,ne(o,i),new TypeError("openFeature prepare must return synchronously.")}}catch(o){m=k(e,Object.freeze({cause:o,phase:"open",stage:"prepare"}))}finally{t=void 0}let S=m===void 0?(async()=>{for(const s of a){const p=F();if(p!==void 0)throw await d(p),p;const g=await ee(e,n,s);if(g!==void 0){const f=F()??g;throw await d(f),f}}const o=F();if(o!==void 0)throw await d(o),o;const u=c;return c=void 0,y=!0,u})():d(m).then(()=>{throw m});const M=S.then(o=>(q(),o),o=>{throw c=void 0,q(),o});S=void 0;const b={close:()=>(R=!0,d(y?void 0:F())),instance:n,ready:M};return h.set(b,K),b}function re(e,n){const t=Y(e,n),i=C(e,{cleanupFailure:t.cleanupFailure,reporter:t.reporter});return te(e.id,i,t.prepare,t.reporter,t.scopes)}export{B as carryFeatureGenerationFence,A as fenceFeatureGeneration,k as notReadyGeneration,re as openFeature,$ as quarantinedGeneration,W as registerFeatureGenerationFence};
2
+ //# sourceMappingURL=module-generation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module-generation.js","sources":["../src/module-generation.ts"],"sourcesContent":["import { FeatureError } from '@opetope/core';\nimport type { DeclarationId } from '@opetope/core';\nimport type { ExactInput, IsAny } from '@opetope/core/internal';\nimport { hasOwn } from '@opetope/core/internal';\n\nimport { assertPlainRecord } from './feature-record';\nimport { getModuleScopeEntries, instantiateModule, projectModuleCleanupFailures } from './public-module';\nimport type {\n CleanupFailurePolicy,\n ErrorReporter,\n ModuleDefinition,\n ModuleDrainOutcome,\n ModuleInstance,\n ModuleInstanceRef,\n ModuleRuntimeRecord,\n ModuleScopeOpenOutcome,\n ModuleScopeRef,\n} from './public-module';\nimport { reportRuntimeFailure } from './runtime-error-reporting';\n\ntype SynchronousResult<Value> = [Value] extends [never]\n ? unknown\n : IsAny<Value> extends true\n ? never\n : [Extract<Value, PromiseLike<unknown>>] extends [never]\n ? unknown\n : never;\n\ntype GenerationScopeValues<Runtime extends Readonly<Record<string, unknown>>> = string extends keyof Runtime\n ? never\n : {\n readonly [\n Key in keyof Runtime as Runtime[Key] extends ModuleScopeRef<infer _Value, infer _Id> ? Key : never\n ]: Runtime[Key] extends ModuleScopeRef<infer Value, infer _Id> ? Value : never;\n };\n\ntype GenerationNotReadyFailure =\n | {\n readonly attachmentId: DeclarationId | undefined;\n readonly cause: unknown;\n readonly phase: 'open';\n readonly reason: 'cancelled' | 'closed' | 'failed' | 'quarantined' | 'retired' | 'superseded' | 'threw';\n readonly scope: string;\n readonly stage: 'scope';\n }\n | {\n readonly cause: unknown;\n readonly phase: 'open';\n readonly stage: 'prepare';\n };\n\n/**\n * The handle a host holds for one opened feature. It is the kernel's instance ref, named with the author's word,\n * Because a public member must not spell a kernel concept (D114).\n */\ntype FeatureInstanceHandle<Id extends string> = ModuleInstanceRef<Id>;\n\ninterface FeatureInstance<Id extends string, Prepared = void> {\n readonly close: () => Promise<void>;\n readonly instance: FeatureInstanceHandle<Id>;\n readonly ready: Promise<Prepared>;\n}\n\ninterface GenerationBaseOptions<Runtime extends Readonly<Record<string, unknown>>, Values> {\n readonly cleanupFailure?: CleanupFailurePolicy;\n readonly reporter: ErrorReporter;\n readonly scopes: ExactInput<Values, GenerationScopeValues<Runtime>>;\n}\n\ninterface GenerationPreparedOptions<\n Id extends string,\n Runtime extends ModuleRuntimeRecord<Id>,\n Values,\n Prepared,\n> extends GenerationBaseOptions<Runtime, Values> {\n readonly prepare: (instance: ModuleInstanceRef<Id>) => Prepared;\n}\n\ntype GenerationUnpreparedOptions<Runtime extends Readonly<Record<string, unknown>>, Values> = GenerationBaseOptions<\n Runtime,\n Values\n> & {\n readonly prepare?: never;\n};\n\ntype ScopeValueEntry = {\n readonly key: string;\n readonly scope: ModuleScopeRef<unknown>;\n readonly value: unknown;\n};\n\nconst emptyScopeValueEntries: readonly ScopeValueEntry[] = Object.freeze([]);\n\ntype GenerationOptionsSnapshot<Id extends string> = {\n readonly cleanupFailure: CleanupFailurePolicy;\n readonly prepare: ((instance: ModuleInstanceRef<Id>) => unknown) | undefined;\n readonly reporter: ErrorReporter;\n readonly scopes: readonly ScopeValueEntry[];\n};\n\nconst moduleGenerationOptionKeys = new Set<PropertyKey>(['cleanupFailure', 'prepare', 'reporter', 'scopes']);\n\n/** What a cause can tell an author without printing a stack: its own sentence, or nothing at all. */\nfunction causeSentence(cause: unknown): string {\n if (cause instanceof Error) return ` ${cause.message}`;\n\n return typeof cause === 'string' && cause.length > 0 ? ` ${cause}` : '';\n}\n\n/** An attachment names itself, so the top line says `attachment polling`, not the hidden scope it was lowered into. */\nfunction failedSubject(failure: GenerationNotReadyFailure): string {\n if (failure.stage === 'prepare') return 'preparation failed';\n\n if (failure.attachmentId === undefined) return `scope ${failure.scope} failed to open`;\n\n return `attachment ${failure.attachmentId.slice(failure.attachmentId.lastIndexOf('/') + 1)} failed to open`;\n}\n\n/**\n * The top line names what failed and why. The cause used to sit two levels down, so an author read «preparation\n * Failed» and had to walk `failure.cause` by hand to find the key and the sentence.\n */\nfunction notReadyGeneration(moduleId: DeclarationId, failure: GenerationNotReadyFailure): FeatureError {\n const where = failedSubject(failure);\n\n return new FeatureError('not-ready', moduleId, {\n failure,\n message: `Feature ${moduleId} instance ${where}.${causeSentence(failure.cause)}`,\n });\n}\n\n/** The reentrancy guard the quarantine class used to own: one pending retry per error instance. */\n/** The fence of a generation, kept off its public shape: only the application layer above may stop admission. */\nconst generationFences = new WeakMap<object, () => void>();\n\n/** Idempotent by construction: `retire()` of an already retiring instance returns the same record (D189). */\nfunction fenceFeatureGeneration(generation: object): void {\n generationFences.get(generation)?.();\n}\n\n/** D186: a lazy header hands out its own object, so it registers the fence that reaches the instance it opens. */\nfunction registerFeatureGenerationFence(generation: object, fence: () => void): void {\n generationFences.set(generation, fence);\n}\n\n/** A feature with contributions hands out a wrapper, and the fence follows the object the application holds. */\nfunction carryFeatureGenerationFence(from: object, to: object): void {\n const fence = generationFences.get(from);\n\n if (fence !== undefined) generationFences.set(to, fence);\n}\n\nfunction quarantineRetry(retryOperation: () => Promise<void>): () => Promise<void> {\n let pending: Promise<void> | undefined;\n let operation = retryOperation;\n const release = (): void => {\n operation = () => pending ?? Promise.resolve();\n };\n\n return () => {\n // Invoke first so a retry callback cannot bypass the guard by receiving its own pending promise.\n const retry = operation();\n\n if (pending !== undefined) return retry;\n\n pending = retry;\n void retry.then(release, release);\n\n return retry;\n };\n}\n\nfunction quarantinedGeneration(\n moduleId: DeclarationId,\n failures: readonly unknown[],\n cause: unknown,\n retryOperation: () => Promise<void>,\n): FeatureError {\n return new FeatureError('quarantined', moduleId, {\n cause,\n failures,\n retryCleanup: quarantineRetry(retryOperation),\n });\n}\n\nfunction snapshotScopeValues<Id extends string, Runtime extends ModuleRuntimeRecord<Id>>(\n definition: ModuleDefinition<Id, Runtime>,\n value: unknown,\n): readonly ScopeValueEntry[] {\n assertPlainRecord(value, 'openFeature scopes');\n const expected = getModuleScopeEntries(definition);\n const expectedKeys = new Set(expected.map(entry => entry.key));\n const propertyKeys = Reflect.ownKeys(value);\n\n for (const propertyKey of propertyKeys) {\n if (typeof propertyKey !== 'string' || !expectedKeys.has(propertyKey)) {\n throw new TypeError(`Unknown openFeature scope ${String(propertyKey)}.`);\n }\n }\n\n if (propertyKeys.length !== expected.length) {\n const missing = expected.find(entry => !hasOwn(value, entry.key));\n\n throw new TypeError(`openFeature requires scope ${missing?.key ?? '<unknown>'}.`);\n }\n\n return expected.map(entry => ({\n key: entry.key,\n scope: entry.scope as unknown as ModuleScopeRef<unknown>,\n value: Reflect.get(value, entry.key),\n }));\n}\n\nfunction assertKnownModuleGenerationOptionKeys(value: object): void {\n for (const propertyKey of Reflect.ownKeys(value)) {\n if (!moduleGenerationOptionKeys.has(propertyKey)) {\n throw new TypeError(`Unknown openFeature option ${String(propertyKey)}.`);\n }\n }\n}\n\nfunction assertRequiredModuleGenerationOptions(value: object): void {\n if (!hasOwn(value, 'scopes')) throw new TypeError('openFeature requires own scopes.');\n\n if (!hasOwn(value, 'reporter')) throw new TypeError('openFeature requires own reporter.');\n}\n\nfunction snapshotGenerationCleanupFailure(value: object): CleanupFailurePolicy {\n const cleanupFailure: unknown = hasOwn(value, 'cleanupFailure') ? Reflect.get(value, 'cleanupFailure') : 'report';\n\n if (cleanupFailure !== 'report' && cleanupFailure !== 'quarantine') {\n throw new TypeError('openFeature cleanupFailure must be \"report\" or \"quarantine\".');\n }\n\n return cleanupFailure;\n}\n\nfunction snapshotGenerationPrepare<Id extends string>(\n value: object,\n): ((instance: ModuleInstanceRef<Id>) => unknown) | undefined {\n const prepare: unknown = hasOwn(value, 'prepare') ? Reflect.get(value, 'prepare') : undefined;\n\n if (prepare !== undefined && typeof prepare !== 'function') {\n throw new TypeError('openFeature prepare must be a function.');\n }\n\n return prepare as ((instance: ModuleInstanceRef<Id>) => unknown) | undefined;\n}\n\nfunction snapshotGenerationReporter(value: object): ErrorReporter {\n const reporter: unknown = Reflect.get(value, 'reporter');\n\n if (typeof reporter !== 'function') throw new TypeError('openFeature reporter must be a function.');\n\n return reporter as ErrorReporter;\n}\n\nfunction snapshotModuleGenerationOptions<Id extends string, Runtime extends ModuleRuntimeRecord<Id>>(\n definition: ModuleDefinition<Id, Runtime>,\n value: unknown,\n): GenerationOptionsSnapshot<Id> {\n assertPlainRecord(value, 'openFeature options');\n assertKnownModuleGenerationOptionKeys(value);\n assertRequiredModuleGenerationOptions(value);\n\n return {\n cleanupFailure: snapshotGenerationCleanupFailure(value),\n prepare: snapshotGenerationPrepare<Id>(value),\n reporter: snapshotGenerationReporter(value),\n scopes: snapshotScopeValues(definition, Reflect.get(value, 'scopes')),\n };\n}\n\nfunction isThenable(value: unknown): boolean {\n if ((typeof value !== 'object' || value === null) && typeof value !== 'function') return false;\n\n return typeof Reflect.get(value, 'then') === 'function';\n}\n\nfunction failedScopeCall(moduleId: DeclarationId, entry: ScopeValueEntry, cause: unknown): FeatureError {\n return notReadyGeneration(\n moduleId,\n Object.freeze({\n attachmentId: undefined,\n cause,\n phase: 'open' as const,\n reason: 'threw' as const,\n scope: entry.key,\n stage: 'scope' as const,\n }),\n );\n}\n\nfunction failedScopeOutcome(\n moduleId: DeclarationId,\n entry: ScopeValueEntry,\n outcome: ModuleScopeOpenOutcome,\n): FeatureError | undefined {\n if (outcome.kind === 'ready') return undefined;\n\n return notReadyGeneration(\n moduleId,\n Object.freeze({\n attachmentId: outcome.kind === 'not-ready' ? outcome.attachmentId : undefined,\n cause: outcome.kind === 'not-ready' ? outcome.cause : undefined,\n phase: 'open' as const,\n reason: outcome.kind === 'not-ready' ? outcome.reason : ('retired' as const),\n scope: entry.key,\n stage: 'scope' as const,\n }),\n );\n}\n\nasync function openGenerationScope<Id extends string>(\n moduleId: DeclarationId,\n instance: ModuleInstance<Id>,\n entry: ScopeValueEntry,\n): Promise<FeatureError | undefined> {\n try {\n const outcome = await instance.scope(entry.scope as unknown as ModuleScopeRef<unknown, Id>).open(entry.value);\n\n return failedScopeOutcome(moduleId, entry, outcome);\n } catch (cause) {\n return failedScopeCall(moduleId, entry, cause);\n }\n}\n\nfunction superviseInvalidPreparation(result: unknown, reporter: ErrorReporter): void {\n void Promise.resolve(result).catch((error: unknown) => reportRuntimeFailure(error, reporter));\n}\n\nfunction createModuleGenerationController<Id extends string>(\n moduleId: DeclarationId,\n instance: ModuleInstance<Id>,\n prepare: ((instance: ModuleInstanceRef<Id>) => unknown) | undefined,\n reporter: ErrorReporter,\n scopeEntries: readonly ScopeValueEntry[],\n): FeatureInstance<Id, unknown> {\n let inactiveReason: FeatureError | undefined;\n let openingCommitted = false;\n let retirementRequested = false;\n let retirementAttempt: Promise<void> | undefined;\n\n const quarantineError = (\n outcome: Extract<ModuleDrainOutcome, { readonly kind: 'quarantined' }>,\n cause: unknown,\n ): FeatureError => {\n let retry: Promise<void> | undefined;\n const failures = projectModuleCleanupFailures(instance, outcome.failures);\n\n return quarantinedGeneration(moduleId, failures, cause, () => {\n const handle = instance.retire();\n\n if (retry !== undefined) return retry;\n\n const attempt = handle.retry().then(nextOutcome => {\n if (nextOutcome.kind === 'quarantined') throw quarantineError(nextOutcome, cause);\n });\n retry = attempt;\n retirementAttempt = attempt;\n\n return attempt;\n });\n };\n\n /**\n * Admission stops here and nothing physical starts: the instance is fenced, so a call saved by someone else can no\n * longer begin a body, while the ordered drain of the layer above still decides when cleanup runs (D189).\n */\n const fence = (): void => {\n retirementRequested = true;\n instance.retire();\n };\n\n const startRetirement = (cause: unknown): Promise<void> => {\n const handle = instance.retire();\n\n if (retirementAttempt !== undefined) return retirementAttempt;\n\n const attempt = handle.drain().then(outcome => {\n if (outcome.kind === 'quarantined') throw quarantineError(outcome, cause);\n });\n retirementAttempt = attempt;\n\n return attempt;\n };\n\n const cancellationReason = (): FeatureError | undefined => {\n if (!retirementRequested) return undefined;\n\n return (inactiveReason ??= new FeatureError('retired', moduleId));\n };\n\n const releaseScopeEntries = (): void => {\n scopeEntries = emptyScopeValueEntries;\n };\n\n let prepared: unknown;\n let preparationFailure: FeatureError | undefined;\n\n try {\n prepared = prepare?.(instance);\n\n if (isThenable(prepared)) {\n const asynchronousPreparation = prepared;\n prepared = undefined;\n superviseInvalidPreparation(asynchronousPreparation, reporter);\n\n throw new TypeError('openFeature prepare must return synchronously.');\n }\n } catch (cause) {\n preparationFailure = notReadyGeneration(\n moduleId,\n Object.freeze({ cause, phase: 'open' as const, stage: 'prepare' as const }),\n );\n } finally {\n prepare = undefined;\n }\n\n let opening: Promise<unknown> | undefined =\n preparationFailure === undefined\n ? (async (): Promise<unknown> => {\n for (const entry of scopeEntries) {\n const inactive = cancellationReason();\n\n if (inactive !== undefined) {\n await startRetirement(inactive);\n\n throw inactive;\n }\n\n const failure = await openGenerationScope(moduleId, instance, entry);\n\n if (failure !== undefined) {\n const reason = cancellationReason() ?? failure;\n\n await startRetirement(reason);\n\n throw reason;\n }\n }\n\n const inactive = cancellationReason();\n\n if (inactive !== undefined) {\n await startRetirement(inactive);\n\n throw inactive;\n }\n\n const result = prepared;\n prepared = undefined;\n openingCommitted = true;\n\n return result;\n })()\n : startRetirement(preparationFailure).then(() => {\n throw preparationFailure;\n });\n const ready = opening.then(\n value => {\n releaseScopeEntries();\n\n return value;\n },\n (cause: unknown) => {\n prepared = undefined;\n releaseScopeEntries();\n\n throw cause;\n },\n );\n opening = undefined;\n const generation = {\n close: (): Promise<void> => {\n retirementRequested = true;\n\n return startRetirement(openingCommitted ? undefined : cancellationReason());\n },\n instance,\n ready,\n };\n generationFences.set(generation, fence);\n\n return generation;\n}\n\nfunction openFeature<\n const Id extends string,\n const Runtime extends ModuleRuntimeRecord<Id>,\n const Values extends GenerationScopeValues<Runtime>,\n const Options extends GenerationUnpreparedOptions<Runtime, Values>,\n>(\n definition: ModuleDefinition<Id, Runtime>,\n options: ExactInput<Options, GenerationUnpreparedOptions<Runtime, Values>>,\n): FeatureInstance<Id>;\nfunction openFeature<\n const Id extends string,\n const Runtime extends ModuleRuntimeRecord<Id>,\n const Values extends GenerationScopeValues<Runtime>,\n Prepared,\n const Options extends GenerationPreparedOptions<Id, Runtime, Values, Prepared>,\n>(\n definition: ModuleDefinition<Id, Runtime>,\n options: ExactInput<Options, GenerationPreparedOptions<Id, Runtime, Values, Prepared>> & SynchronousResult<Prepared>,\n): FeatureInstance<Id, Prepared>;\nfunction openFeature<const Id extends string, const Runtime extends ModuleRuntimeRecord<Id>>(\n definition: ModuleDefinition<Id, Runtime>,\n options: unknown,\n): FeatureInstance<Id, unknown> {\n const snapshot = snapshotModuleGenerationOptions(definition, options);\n const instance = instantiateModule(definition, {\n cleanupFailure: snapshot.cleanupFailure,\n reporter: snapshot.reporter,\n });\n\n return createModuleGenerationController(\n definition.id,\n instance,\n snapshot.prepare,\n snapshot.reporter,\n snapshot.scopes,\n );\n}\n\nexport {\n carryFeatureGenerationFence,\n fenceFeatureGeneration,\n notReadyGeneration,\n openFeature,\n quarantinedGeneration,\n registerFeatureGenerationFence,\n};\nexport type { FeatureInstance };\n"],"names":["emptyScopeValueEntries","moduleGenerationOptionKeys","causeSentence","cause","failedSubject","failure","notReadyGeneration","moduleId","where","FeatureError","generationFences","fenceFeatureGeneration","generation","_a","registerFeatureGenerationFence","fence","carryFeatureGenerationFence","from","to","quarantineRetry","retryOperation","pending","operation","release","retry","quarantinedGeneration","failures","snapshotScopeValues","definition","value","assertPlainRecord","expected","getModuleScopeEntries","expectedKeys","entry","propertyKeys","propertyKey","missing","hasOwn","assertKnownModuleGenerationOptionKeys","assertRequiredModuleGenerationOptions","snapshotGenerationCleanupFailure","cleanupFailure","snapshotGenerationPrepare","prepare","snapshotGenerationReporter","reporter","snapshotModuleGenerationOptions","isThenable","failedScopeCall","failedScopeOutcome","outcome","openGenerationScope","instance","superviseInvalidPreparation","result","error","reportRuntimeFailure","createModuleGenerationController","scopeEntries","inactiveReason","openingCommitted","retirementRequested","retirementAttempt","quarantineError","projectModuleCleanupFailures","handle","attempt","nextOutcome","startRetirement","cancellationReason","releaseScopeEntries","prepared","preparationFailure","asynchronousPreparation","opening","inactive","reason","ready","openFeature","options","snapshot","instantiateModule"],"mappings":"wbA2FA,MAAMA,EAAqD,OAAO,OAAO,EAAE,EASrEC,EAA6B,IAAI,IAAiB,CAAC,iBAAkB,UAAW,WAAY,QAAQ,CAAC,EAG3G,SAASC,EAAcC,EAAc,CACnC,OAAIA,aAAiB,MAAc,IAAIA,EAAM,OAAO,GAE7C,OAAOA,GAAU,UAAYA,EAAM,OAAS,EAAI,IAAIA,CAAK,GAAK,EACvE,CAGA,SAASC,EAAcC,EAA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EAAYG,CAAK,EAE/BH,CACT,CAqBA,SAASmE,GACPnD,EACAoD,EAAgB,CAEhB,MAAMC,EAAWlC,EAAgCnB,EAAYoD,CAAO,EAC9D3B,EAAW6B,EAAkBtD,EAAY,CAC7C,eAAgBqD,EAAS,eACzB,SAAUA,EAAS,QACpB,CAAA,EAED,OAAOvB,GACL9B,EAAW,GACXyB,EACA4B,EAAS,QACTA,EAAS,SACTA,EAAS,MAAM,CAEnB"}
@@ -0,0 +1,156 @@
1
+ import type { Call, DeclarationId } from '@opetope/core';
2
+ import type { AttachmentDrainOutcome, AttachmentIntentOutcome, AttachmentReadinessRef, AttachmentRetryOutcome } from '@opetope/core/internal';
3
+ import type { LifetimeAttachmentRef, ScopeBlueprint } from './attachment-declaration.js';
4
+ import type { AttachmentCallbackInvoker, AttachmentErrorReporter } from './attachment-execution.js';
5
+ import type { MaterializationBinding } from './feature-materialization-binding.js';
6
+ import type { ModuleCallRegistry } from './module-call-runtime.js';
7
+ import type { AttachmentTemplateSlot, CompiledModuleTemplateIR, ScopeAttachmentSlot, ScopeTemplateSlot } from './module-template-ir.js';
8
+ import type { OwnerBoundAttachment, OwnerGeneration, OwnerGenerationController, OwnerGenerationPlanRetirement, OwnerGenerationRef } from './owner-generation.js';
9
+ declare const localAttachmentModuleInstanceBrand: unique symbol;
10
+ declare const localScopeInstanceBrand: unique symbol;
11
+ declare const localScopeRetirementBrand: unique symbol;
12
+ interface LocalScopeClosedOutcome {
13
+ readonly kind: 'closed';
14
+ }
15
+ interface LocalAttachmentIdentity {
16
+ readonly attachmentId: DeclarationId;
17
+ readonly attachmentSlot: AttachmentTemplateSlot;
18
+ }
19
+ /**
20
+ * One shape for one fact: the physical close of an attachment either quarantined itself or rejected. The scheduler,
21
+ * the local scope and the retire handle all speak this form, so no layer reprojects it (D164).
22
+ */
23
+ type LocalAttachmentCloseFailureOutcome = Extract<AttachmentDrainOutcome | AttachmentRetryOutcome, {
24
+ readonly kind: 'quarantined';
25
+ }> | {
26
+ readonly error: unknown;
27
+ readonly kind: 'rejected';
28
+ };
29
+ interface LocalAttachmentCloseFailure extends LocalAttachmentIdentity {
30
+ readonly outcome: LocalAttachmentCloseFailureOutcome;
31
+ }
32
+ interface LocalScopeQuarantinedOutcome {
33
+ readonly failedAttachments: readonly LocalAttachmentCloseFailure[];
34
+ readonly kind: 'quarantined';
35
+ }
36
+ type LocalScopeDrainOutcome = LocalScopeClosedOutcome | LocalScopeQuarantinedOutcome;
37
+ /** One pair of handles for one fact: the scheduler and the scope retire handle answer the same two questions. */
38
+ interface AttachmentRetirementScheduler {
39
+ readonly drain: () => Promise<LocalScopeDrainOutcome>;
40
+ readonly retry: () => Promise<LocalScopeDrainOutcome>;
41
+ }
42
+ interface LocalScopeRetirement extends AttachmentRetirementScheduler {
43
+ readonly [localScopeRetirementBrand]: true;
44
+ }
45
+ interface LocalScopeReadyOutcome {
46
+ readonly kind: 'ready';
47
+ }
48
+ interface LocalScopeNotReadyOutcome {
49
+ readonly attachmentId: DeclarationId;
50
+ readonly attachmentSlot: AttachmentTemplateSlot;
51
+ readonly drain: LocalScopeDrainOutcome;
52
+ readonly kind: 'not-ready';
53
+ readonly outcome: AttachmentIntentOutcome;
54
+ readonly retirement: LocalScopeRetirement;
55
+ }
56
+ interface LocalScopeRetiredOutcome {
57
+ readonly drain: LocalScopeDrainOutcome;
58
+ readonly kind: 'retired';
59
+ readonly retirement: LocalScopeRetirement;
60
+ }
61
+ type LocalScopeOpenOutcome = LocalScopeNotReadyOutcome | LocalScopeReadyOutcome | LocalScopeRetiredOutcome;
62
+ interface LocalScopeInstance<Value> {
63
+ readonly [localScopeInstanceBrand]: true;
64
+ readonly open: (value: Value) => Promise<LocalScopeOpenOutcome>;
65
+ readonly ref: OwnerGenerationRef;
66
+ readonly retire: () => LocalScopeRetirement;
67
+ }
68
+ interface LocalAttachmentModuleDiagnostics {
69
+ readonly activeScopes: number;
70
+ readonly attachmentControllers: number;
71
+ readonly deferredFailures: readonly LocalDeferredAttachmentFailure[];
72
+ readonly scopeControllers: number;
73
+ }
74
+ interface LocalDeferredAttachmentFailure extends LocalAttachmentIdentity {
75
+ readonly outcome: DeferredAttachmentFailureOutcome;
76
+ }
77
+ interface LocalAttachmentModuleInstance {
78
+ readonly diagnostics: () => LocalAttachmentModuleDiagnostics;
79
+ readonly [localAttachmentModuleInstanceBrand]: true;
80
+ readonly readiness: <Value>(attachment: LifetimeAttachmentRef<Value>) => AttachmentReadinessRef;
81
+ readonly scope: <Value>(scope: ScopeBlueprint<Value>) => LocalScopeInstance<Value>;
82
+ }
83
+ type AttachmentInstance = {
84
+ readonly bound: OwnerBoundAttachment<unknown>;
85
+ readonly id: DeclarationId;
86
+ readonly scopeAttachmentSlot: ScopeAttachmentSlot;
87
+ readonly slot: AttachmentTemplateSlot;
88
+ };
89
+ type ScopeGenerationPhase = 'committing' | 'fencing' | 'opening' | 'ready' | 'retiring';
90
+ type CriticalFailure = {
91
+ readonly attachment: AttachmentInstance;
92
+ readonly outcome: AttachmentIntentOutcome;
93
+ };
94
+ type DeferredAttachmentFailureOutcome = Extract<AttachmentIntentOutcome, {
95
+ readonly kind: 'failed' | 'quarantined';
96
+ }> | {
97
+ readonly error: unknown;
98
+ readonly kind: 'rejected';
99
+ };
100
+ type ScopeGeneration = {
101
+ readonly attachmentStates: Uint8Array;
102
+ callbackInvocationDepth: number;
103
+ criticalPending: number;
104
+ failure: CriticalFailure | undefined;
105
+ readonly generation: OwnerGeneration;
106
+ readonly invokeAttachmentCallback: AttachmentCallbackInvoker;
107
+ openingValue: unknown;
108
+ readonly openPromise: Promise<LocalScopeOpenOutcome>;
109
+ phase: ScopeGenerationPhase;
110
+ rejectOpen: (error: unknown) => void;
111
+ resolveOpen: (outcome: LocalScopeOpenOutcome) => void;
112
+ retirement: RetirementRecord | undefined;
113
+ unstartedAttachments: number;
114
+ value: unknown;
115
+ };
116
+ type ScopeInstanceRecord = {
117
+ active: ScopeGeneration | undefined;
118
+ readonly attachmentInstances: readonly AttachmentInstance[];
119
+ readonly controller: OwnerGenerationController;
120
+ readonly deferredFailures: Map<AttachmentInstance, DeferredAttachmentFailureOutcome>;
121
+ readonly runtime: LocalScopeInstance<unknown>;
122
+ readonly slot: ScopeTemplateSlot;
123
+ };
124
+ /** One record per live instance: everything the runtime knows about it hangs here, not in parallel indexes (D166). */
125
+ type ModuleInstanceRecord = {
126
+ readonly attachments: readonly AttachmentInstance[];
127
+ readonly callRegistry: ModuleCallRegistry;
128
+ readonly callTargets: readonly Call<unknown, unknown>[];
129
+ readonly deferredFailures: Map<AttachmentInstance, DeferredAttachmentFailureOutcome>;
130
+ readonly materializationBindings: readonly (MaterializationBinding | undefined)[];
131
+ readonly plan: CompiledModuleTemplateIR;
132
+ readonly reporterState: AttachmentErrorReporterState;
133
+ readonly retainScopeValues: boolean;
134
+ readonly scopes: readonly ScopeInstanceRecord[];
135
+ };
136
+ type AttachmentErrorReporterState = {
137
+ reporter: AttachmentErrorReporter | undefined;
138
+ };
139
+ type RetirementRecord = {
140
+ drainPromise: Promise<LocalScopeDrainOutcome> | undefined;
141
+ readonly handleState: RetirementHandleState;
142
+ ownerRetirement: OwnerGenerationPlanRetirement | undefined;
143
+ prepared: Promise<void> | undefined;
144
+ rejectPrepared: (error: unknown) => void;
145
+ resolvePrepared: () => void;
146
+ retryPromise: Promise<LocalScopeDrainOutcome> | undefined;
147
+ runtime: LocalScopeRetirement;
148
+ scheduler: AttachmentRetirementScheduler | undefined;
149
+ scope: ScopeInstanceRecord | undefined;
150
+ state: ScopeGeneration | undefined;
151
+ };
152
+ type RetirementHandleState = {
153
+ outcome: LocalScopeDrainOutcome | undefined;
154
+ record: RetirementRecord | undefined;
155
+ };
156
+ export type { AttachmentErrorReporterState, AttachmentInstance, AttachmentRetirementScheduler, DeferredAttachmentFailureOutcome, LocalAttachmentCloseFailure, LocalAttachmentCloseFailureOutcome, LocalAttachmentIdentity, LocalAttachmentModuleDiagnostics, LocalAttachmentModuleInstance, LocalDeferredAttachmentFailure, LocalScopeDrainOutcome, LocalScopeInstance, LocalScopeOpenOutcome, LocalScopeRetirement, ModuleInstanceRecord, RetirementHandleState, RetirementRecord, ScopeGeneration, ScopeGenerationPhase, ScopeInstanceRecord, };
@@ -0,0 +1,19 @@
1
+ import type { Call } from '@opetope/core';
2
+ import type { AttachmentCallRef } from './attachment-call-declaration.js';
3
+ import type { ScopeBlueprint } from './attachment-declaration.js';
4
+ import type { AttachmentErrorReporter } from './attachment-execution.js';
5
+ import type { LocalAttachmentModuleInstance, LocalScopeInstance, LocalScopeRetirement, ModuleInstanceRecord } from './module-instance-types.js';
6
+ import type { CompiledModuleTemplateIR } from './module-template-ir.js';
7
+ declare function requireModuleInstanceRecord(instance: LocalAttachmentModuleInstance): ModuleInstanceRecord;
8
+ declare function hasActiveLocalAttachmentCallback(record: ModuleInstanceRecord): boolean;
9
+ declare function revokeLocalAttachmentModuleCallTargets(record: ModuleInstanceRecord): void;
10
+ /** Every live half of an instance hangs on its record, so the layers above pass the record, not a handle (D166). */
11
+ declare function resolveAttachmentCallTarget<Input, Output>(record: ModuleInstanceRecord, call: AttachmentCallRef<Input, Output>): Call<Input, Output>;
12
+ declare function retireLocalScopeIfActive<Value>(record: ModuleInstanceRecord, scope: ScopeBlueprint<Value>): LocalScopeRetirement | undefined;
13
+ declare function localScopeInstance<Value>(record: ModuleInstanceRecord, scope: ScopeBlueprint<Value>): LocalScopeInstance<Value>;
14
+ /** The internal entry hands out the authentic handle; the layers inside the package pass the record itself. */
15
+ declare function instantiateModuleTemplate(plan: CompiledModuleTemplateIR): LocalAttachmentModuleInstance;
16
+ declare function instantiateRetainedModuleTemplate(plan: CompiledModuleTemplateIR, reporter?: AttachmentErrorReporter): ModuleInstanceRecord;
17
+ declare function releaseLocalAttachmentErrorReporter(record: ModuleInstanceRecord): void;
18
+ export { hasActiveLocalAttachmentCallback, instantiateModuleTemplate, instantiateRetainedModuleTemplate, localScopeInstance, releaseLocalAttachmentErrorReporter, requireModuleInstanceRecord, resolveAttachmentCallTarget, retireLocalScopeIfActive, revokeLocalAttachmentModuleCallTargets, };
19
+ export type { LocalAttachmentCloseFailure, LocalAttachmentIdentity, LocalAttachmentModuleDiagnostics, LocalAttachmentModuleInstance, LocalScopeDrainOutcome, LocalScopeInstance, LocalScopeOpenOutcome, LocalScopeRetirement, ModuleInstanceRecord, } from './module-instance-types.js';
@@ -0,0 +1,2 @@
1
+ import{createAttachmentLifecycleController as $,mintAttachmentCallTarget as F,assertCallContextCurrent as b,inheritCallContextLifetime as T,inheritCallExecutionMetadata as y,releaseCallExecutionMetadata as h,retireCallContext as g,settleGuardedResult as L,combineAbortSignals as v,withCallTargetResultFinalizer as z,throwIfSignalAborted as B,revokeCallTarget as x}from"@opetope/core/internal";import{invokeAttachmentClose as G,invokeAttachmentOpen as N}from"./attachment-execution.js";import{getCompiledTemplateRecord as D,compiledAttachmentRecipe as W,getCompiledAttachmentSlot as q,getCompiledCallTargetBindingSlot as O,compiledAttachmentCallRecipe as H,getCompiledScopeSlot as P}from"./compile-module-template.js";import{createMaterializationBinding as J,withMaterializationBinding as K}from"./feature-materialization-binding.js";import{bindLocalCallResolver as I}from"./module-call-context.js";import{retireModuleAttachmentCalls as E,createModuleCallRegistry as Q,createModuleCallInvoker as U}from"./module-call-runtime.js";import{deferredFailureDiagnostics as V,beginScopeOpen as X}from"./module-scope-open.js";import{beginScopeRetirement as R}from"./module-scope-retirement.js";import{createOwnerGenerationSlot as Y,bindAttachmentLifecycleToOwner as Z,getOwnerGenerationAuthoritySource as _}from"./owner-generation.js";const tt=new WeakMap;function A(t){return typeof t=="object"&&t!==null||typeof t=="function"}function et(t){return t.scopes.some(n=>{var o;return(((o=n.active)==null?void 0:o.callbackInvocationDepth)??0)!==0})}function nt(t){for(const n of t.callTargets)x(n)}function rt(t,n){const o=O(t.plan,n),i=t.callTargets[o];if(i===void 0)throw new TypeError(`Call-target binding slot ${o} is not instantiated.`);return i}function j(t,n){const o=P(t.plan,n),i=t.scopes[o];if(i===void 0)throw new TypeError(`Scope slot ${o} is not instantiated.`);return i}function ot(t,n){const o=j(t,n);return o.active===void 0?void 0:R(o).runtime}function at(t,n,o){return(i,d)=>{const u=o(n),c=v([d.signal,u.generation.signal]),e=Object.freeze({signal:c.signal,source:u.value,throwIfAborted:()=>B(c.signal)});let r;try{y(d,e),r=t.run(i,e)}catch(s){throw h(e),c.dispose(),s}if(!A(r))try{return e.throwIfAborted(),r}finally{h(e),c.dispose()}return z(r,{assertCurrent:e.throwIfAborted,finalize:()=>{h(e),c.dispose()},signal:c.signal})}}function it(t,n,o,i){return(d,u)=>{const c=o(n),e=v([u.signal,c.generation.signal]),r=Object.freeze({signal:e.signal,source:c.value,throwIfAborted(){b(r)}});I(r,i);const s=r.throwIfAborted;let f;try{T(u,r),y(u,r),f=t.run(d,r)}catch(l){throw h(r),g(r),e.dispose(),l}if(!A(f))try{return s(),f}finally{h(r),g(r),e.dispose()}return z(f,{assertCurrent:s,finalize:()=>{h(r),g(r),e.dispose()},signal:e.signal})}}function ct(t,n,o,i,d,u,c){const e=o.policy;if(e===void 0)throw new TypeError(`Call ${t} lost its compiled policy recipe.`);const r=U(t,n,e,c);return(s,f)=>{const l=d(i);return r({execute:p=>{const a=Object.freeze({signal:p.signal,source:l.value,throwIfAborted(){b(a)}});I(a,u);const w=a.throwIfAborted;let m;try{T(f,a),y(a,a),m=o.run(s,a)}catch(C){throw h(a),g(a),C}if(!A(m))try{return w(),m}finally{h(a),g(a)}return L(m,{assertCurrent:w,finalize:()=>{h(a),g(a)},waitForPhysicalSettlement:!0})},generation:l.generation,input:s,parent:f})}}function st(t,n,o,i,d,u,c){return Object.freeze(t.attachments.map(e=>{const r=o[e.slot];if(r===void 0)throw new TypeError(`Attachment ${e.identity.id} lost its compiled recipe.`);const s=J(r);c[e.slot]=s;const f=$({close:async p=>{const a=i(e.ownerScopeSlot);return await E(u,a.generation,e.slot),G(r,p.signal,a.value,a.invokeAttachmentCallback,d.reporter)},id:e.identity.id,open:p=>{const a=i(e.ownerScopeSlot);return K(s,()=>N(r,p,a.invokeAttachmentCallback,d.reporter,()=>E(u,a.generation,e.slot)))}}),l=n[e.ownerScopeSlot];if(l===void 0)throw new TypeError(`Attachment ${e.identity.id} lost its compiled owner scope.`);return Object.freeze({bound:Z(l.ref,f),id:e.identity.id,scopeAttachmentSlot:e.scopeAttachmentSlot,slot:e.slot})}))}function lt(t,n,o,i,d,u){const c={current:void 0},e=s=>{var p;const f=O(t,s),l=(p=c.current)==null?void 0:p[f];if(l===void 0)throw new TypeError(`Call-target binding slot ${f} is not instantiated.`);return l},r=Object.freeze(t.callTargetBindings.map(s=>{const f=o[s.withinAttachmentSlot];if(f===void 0)throw new TypeError(`Call target ${s.id} lost its attachment binding.`);const l=t.attachments[s.withinAttachmentSlot];if(l===void 0)throw new TypeError(`Call target ${s.id} lost its attachment node.`);const p=i[l.ownerScopeSlot];if(p===void 0)throw new TypeError(`Call target ${s.id} lost its owner binding.`);const a=H(n,s.slot),w=a.nestedFeatureCalls===!0,m=a.policy!==void 0?ct(s.id,s.withinAttachmentSlot,a,l.ownerScopeSlot,d,e,u):w?it(a,l.ownerScopeSlot,d,e):at(a,l.ownerScopeSlot,d);return F({id:s.id,owner:_(p),run:m,within:f.bound.readiness})}));return c.current=r,r}function ut(t,n,o){const{attachments:i,deferredFailures:d,plan:u}=t;u.scopes.forEach(c=>{var f;const e=Object.freeze({open:l=>X(t,n[c.slot],l),ref:(f=o[c.slot])==null?void 0:f.ref,retire:()=>R(n[c.slot]).runtime});if(e.ref===void 0)throw new TypeError(`Scope ${c.identity.id} lost its owner controller.`);const s={active:void 0,attachmentInstances:Object.freeze(c.attachmentSlots.map(l=>{const p=i[l];if(p===void 0)throw new TypeError(`Attachment slot ${l} is not instantiated.`);return p})),controller:o[c.slot],deferredFailures:d,runtime:e,slot:c.slot};n[c.slot]=s})}function M(t,n){return j(t,n).runtime}function ft(t){const{attachments:n,plan:o}=t;return Object.freeze({diagnostics(){return Object.freeze({activeScopes:t.scopes.filter(i=>i.active!==void 0).length,attachmentControllers:n.length,deferredFailures:V(t),scopeControllers:t.scopes.length})},readiness(i){const d=q(o,i),u=n[d];if(u===void 0)throw new TypeError(`Attachment slot ${d} is not instantiated.`);return u.bound.readiness},scope(i){return M(t,i)}})}function k(t,n,o){const i=D(t),d=Object.freeze(t.attachments.map(m=>W(i,m.slot))),u=Object.freeze(t.scopes.map(m=>Y({id:m.identity.id}))),c=new Map,e={reporter:o},r=[],s=m=>{var S;const C=(S=r[m])==null?void 0:S.active;if(C===void 0)throw new TypeError(`Scope slot ${m} has no active generation value.`);return C},f=Q(),l=[],p=st(t,u,d,s,e,f,l),a=lt(t,i,p,u,s,f),w={attachments:p,callRegistry:f,callTargets:a,deferredFailures:c,materializationBindings:Object.freeze(l),plan:t,reporterState:e,retainScopeValues:n,scopes:r};return ut(w,r,u),Object.freeze(r),w}function dt(t){const n=k(t,!1),o=ft(n);return tt.set(o,n),o}function pt(t,n){return k(t,!0,n)}function mt(t){t.reporterState.reporter=void 0}export{et as hasActiveLocalAttachmentCallback,dt as instantiateModuleTemplate,pt as instantiateRetainedModuleTemplate,M as localScopeInstance,mt as releaseLocalAttachmentErrorReporter,rt as resolveAttachmentCallTarget,ot as retireLocalScopeIfActive,nt as revokeLocalAttachmentModuleCallTargets};
2
+ //# sourceMappingURL=module-instance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module-instance.js","sources":["../src/module-instance.ts"],"sourcesContent":["import type { Call } from '@opetope/core';\nimport type { AttachmentReadinessRef, CallContext } from '@opetope/core/internal';\nimport {\n assertCallContextCurrent,\n combineAbortSignals,\n createAttachmentLifecycleController,\n inheritCallContextLifetime,\n inheritCallExecutionMetadata,\n mintAttachmentCallTarget,\n releaseCallExecutionMetadata,\n retireCallContext,\n revokeCallTarget,\n settleGuardedResult,\n throwIfSignalAborted,\n withCallTargetResultFinalizer,\n} from '@opetope/core/internal';\n\nimport type { AttachmentCallRef, CompiledAttachmentCallRecipe } from './attachment-call-declaration';\nimport type { LifetimeAttachmentRef, ScopeBlueprint } from './attachment-declaration';\nimport { invokeAttachmentClose, invokeAttachmentOpen } from './attachment-execution';\nimport type { AttachmentErrorReporter } from './attachment-execution';\nimport {\n compiledAttachmentCallRecipe,\n compiledAttachmentRecipe,\n getCompiledAttachmentSlot,\n getCompiledCallTargetBindingSlot,\n getCompiledScopeSlot,\n getCompiledTemplateRecord,\n} from './compile-module-template';\nimport type { CompiledModuleTemplateRecord } from './compile-module-template';\nimport { createMaterializationBinding, withMaterializationBinding } from './feature-materialization-binding';\nimport type { MaterializationBinding } from './feature-materialization-binding';\nimport { bindLocalCallResolver } from './module-call-context';\nimport { createModuleCallInvoker, createModuleCallRegistry, retireModuleAttachmentCalls } from './module-call-runtime';\nimport type { ModuleCallRegistry } from './module-call-runtime';\nimport type {\n AttachmentErrorReporterState,\n AttachmentInstance,\n DeferredAttachmentFailureOutcome,\n LocalAttachmentModuleDiagnostics,\n LocalAttachmentModuleInstance,\n LocalScopeInstance,\n LocalScopeOpenOutcome,\n LocalScopeRetirement,\n ModuleInstanceRecord,\n ScopeGeneration,\n ScopeInstanceRecord,\n} from './module-instance-types';\nimport { beginScopeOpen, deferredFailureDiagnostics } from './module-scope-open';\nimport { beginScopeRetirement } from './module-scope-retirement';\nimport type { CompiledModuleTemplateIR, ScopeTemplateSlot } from './module-template-ir';\nimport {\n bindAttachmentLifecycleToOwner,\n createOwnerGenerationSlot,\n getOwnerGenerationAuthoritySource,\n} from './owner-generation';\nimport type { OwnerGeneration, OwnerGenerationController } from './owner-generation';\nimport type { ModuleCallContext } from './public-module';\n\nconst moduleInstances = new WeakMap<object, ModuleInstanceRecord>();\n\ntype AttachmentCallRun = (input: unknown, context: CallContext) => unknown;\ntype ReadScopeState = (slot: ScopeTemplateSlot) => ScopeGeneration;\ntype ResolveLocalCall = <Input, Output>(call: AttachmentCallRef<Input, Output>) => Call<Input, Output>;\n\nfunction canHaveThen(value: unknown): value is ((...arguments_: never[]) => unknown) | object {\n return (typeof value === 'object' && value !== null) || typeof value === 'function';\n}\n\nfunction requireModuleInstanceRecord(instance: LocalAttachmentModuleInstance): ModuleInstanceRecord {\n const record = moduleInstances.get(instance);\n\n if (record === undefined) throw new TypeError('Inauthentic local instance.');\n\n return record;\n}\n\nfunction hasActiveLocalAttachmentCallback(record: ModuleInstanceRecord): boolean {\n return record.scopes.some(scope => (scope.active?.callbackInvocationDepth ?? 0) !== 0);\n}\n\nfunction revokeLocalAttachmentModuleCallTargets(record: ModuleInstanceRecord): void {\n for (const target of record.callTargets) revokeCallTarget(target);\n}\n\n/** Every live half of an instance hangs on its record, so the layers above pass the record, not a handle (D166). */\nfunction resolveAttachmentCallTarget<Input, Output>(\n record: ModuleInstanceRecord,\n call: AttachmentCallRef<Input, Output>,\n): Call<Input, Output> {\n const slot = getCompiledCallTargetBindingSlot(record.plan, call);\n const target = record.callTargets[slot];\n\n if (target === undefined) throw new TypeError(`Call-target binding slot ${slot} is not instantiated.`);\n\n return target as Call<Input, Output>;\n}\n\nfunction requireLocalScopeRecord<Value>(record: ModuleInstanceRecord, scope: ScopeBlueprint<Value>) {\n const slot = getCompiledScopeSlot(record.plan, scope);\n const scopeRecord = record.scopes[slot];\n\n if (scopeRecord === undefined) throw new TypeError(`Scope slot ${slot} is not instantiated.`);\n\n return scopeRecord;\n}\n\nfunction retireLocalScopeIfActive<Value>(\n record: ModuleInstanceRecord,\n scope: ScopeBlueprint<Value>,\n): LocalScopeRetirement | undefined {\n const scopeRecord = requireLocalScopeRecord(record, scope);\n\n return scopeRecord.active === undefined ? undefined : beginScopeRetirement(scopeRecord).runtime;\n}\n\nfunction createAttachmentCallRun(\n recipe: CompiledAttachmentCallRecipe<unknown, unknown>,\n scopeSlot: ScopeTemplateSlot,\n readScopeState: ReadScopeState,\n): AttachmentCallRun {\n return (input, context) => {\n const state = readScopeState(scopeSlot);\n const combined = combineAbortSignals([context.signal, state.generation.signal]);\n const callContext: ModuleCallContext<unknown> = Object.freeze({\n signal: combined.signal,\n source: state.value,\n throwIfAborted: () => throwIfSignalAborted(combined.signal),\n });\n let result: unknown;\n\n try {\n inheritCallExecutionMetadata(context, callContext);\n result = recipe.run(input, callContext);\n } catch (error) {\n releaseCallExecutionMetadata(callContext);\n combined.dispose();\n throw error;\n }\n\n if (!canHaveThen(result)) {\n try {\n callContext.throwIfAborted();\n\n return result;\n } finally {\n releaseCallExecutionMetadata(callContext);\n combined.dispose();\n }\n }\n\n return withCallTargetResultFinalizer(result, {\n assertCurrent: callContext.throwIfAborted,\n finalize: () => {\n releaseCallExecutionMetadata(callContext);\n combined.dispose();\n },\n signal: combined.signal,\n });\n };\n}\n\nfunction createNestedFeatureCallRun(\n recipe: CompiledAttachmentCallRecipe<unknown, unknown>,\n scopeSlot: ScopeTemplateSlot,\n readScopeState: ReadScopeState,\n resolveLocalCall: ResolveLocalCall,\n): AttachmentCallRun {\n return (input, context) => {\n const state = readScopeState(scopeSlot);\n const combined = combineAbortSignals([context.signal, state.generation.signal]);\n const callContext: ModuleCallContext<unknown> = Object.freeze({\n signal: combined.signal,\n source: state.value,\n throwIfAborted(): void {\n assertCallContextCurrent(callContext);\n },\n });\n bindLocalCallResolver(callContext, resolveLocalCall);\n const assertCurrent = callContext.throwIfAborted;\n let result: unknown;\n\n try {\n inheritCallContextLifetime(context, callContext);\n inheritCallExecutionMetadata(context, callContext);\n result = recipe.run(input, callContext);\n } catch (error) {\n releaseCallExecutionMetadata(callContext);\n retireCallContext(callContext);\n combined.dispose();\n throw error;\n }\n\n if (!canHaveThen(result)) {\n try {\n assertCurrent();\n\n return result;\n } finally {\n releaseCallExecutionMetadata(callContext);\n retireCallContext(callContext);\n combined.dispose();\n }\n }\n\n return withCallTargetResultFinalizer(result, {\n assertCurrent,\n finalize: () => {\n releaseCallExecutionMetadata(callContext);\n retireCallContext(callContext);\n combined.dispose();\n },\n signal: combined.signal,\n });\n };\n}\n\nfunction createFeatureCallRun(\n id: string,\n attachmentSlot: number,\n recipe: CompiledAttachmentCallRecipe<unknown, unknown>,\n scopeSlot: ScopeTemplateSlot,\n readScopeState: ReadScopeState,\n resolveLocalCall: ResolveLocalCall,\n callRegistry: ModuleCallRegistry,\n): AttachmentCallRun {\n const policy = recipe.policy;\n\n if (policy === undefined) throw new TypeError(`Call ${id} lost its compiled policy recipe.`);\n\n const invokeModuleCall = createModuleCallInvoker(id, attachmentSlot, policy, callRegistry);\n\n return (input, context) => {\n const state = readScopeState(scopeSlot);\n\n return invokeModuleCall({\n execute: executionContext => {\n const callContext: ModuleCallContext<unknown> = Object.freeze({\n signal: executionContext.signal,\n source: state.value,\n throwIfAborted(): void {\n assertCallContextCurrent(callContext);\n },\n });\n bindLocalCallResolver(callContext, resolveLocalCall);\n const assertCurrent = callContext.throwIfAborted;\n let result: unknown;\n\n try {\n inheritCallContextLifetime(context, callContext);\n inheritCallExecutionMetadata(callContext, callContext);\n result = recipe.run(input, callContext);\n } catch (error) {\n releaseCallExecutionMetadata(callContext);\n retireCallContext(callContext);\n throw error;\n }\n\n if (!canHaveThen(result)) {\n try {\n assertCurrent();\n\n return result;\n } finally {\n releaseCallExecutionMetadata(callContext);\n retireCallContext(callContext);\n }\n }\n\n return settleGuardedResult(result, {\n assertCurrent,\n finalize: () => {\n releaseCallExecutionMetadata(callContext);\n retireCallContext(callContext);\n },\n // The executor owns prompt cancellation. Its body result must still join physical completion.\n waitForPhysicalSettlement: true,\n });\n },\n generation: state.generation,\n input,\n parent: context,\n });\n };\n}\n\nfunction createAttachmentInstances(\n plan: CompiledModuleTemplateIR,\n controllers: readonly OwnerGenerationController[],\n recipes: readonly ReturnType<typeof compiledAttachmentRecipe>[],\n readScopeState: ReadScopeState,\n reporterState: AttachmentErrorReporterState,\n callRegistry: ModuleCallRegistry,\n materializationBindings: (MaterializationBinding | undefined)[],\n): readonly AttachmentInstance[] {\n return Object.freeze(\n plan.attachments.map(node => {\n const recipe = recipes[node.slot];\n\n if (recipe === undefined) throw new TypeError(`Attachment ${node.identity.id} lost its compiled recipe.`);\n\n const materializationBinding = createMaterializationBinding(recipe);\n materializationBindings[node.slot] = materializationBinding;\n\n const lifecycle = createAttachmentLifecycleController<OwnerGeneration, unknown>({\n close: async context => {\n const state = readScopeState(node.ownerScopeSlot);\n\n await retireModuleAttachmentCalls(callRegistry, state.generation, node.slot);\n\n return invokeAttachmentClose(\n recipe,\n context.signal,\n state.value,\n state.invokeAttachmentCallback,\n reporterState.reporter,\n );\n },\n id: node.identity.id,\n open: context => {\n const state = readScopeState(node.ownerScopeSlot);\n\n return withMaterializationBinding(materializationBinding, () =>\n invokeAttachmentOpen(recipe, context, state.invokeAttachmentCallback, reporterState.reporter, () =>\n retireModuleAttachmentCalls(callRegistry, state.generation, node.slot),\n ),\n );\n },\n });\n const owner = controllers[node.ownerScopeSlot];\n\n if (owner === undefined) throw new TypeError(`Attachment ${node.identity.id} lost its compiled owner scope.`);\n\n return Object.freeze({\n bound: bindAttachmentLifecycleToOwner(owner.ref, lifecycle),\n id: node.identity.id,\n scopeAttachmentSlot: node.scopeAttachmentSlot,\n slot: node.slot,\n });\n }),\n );\n}\n\nfunction createCallTargets(\n plan: CompiledModuleTemplateIR,\n template: CompiledModuleTemplateRecord,\n attachments: readonly AttachmentInstance[],\n controllers: readonly OwnerGenerationController[],\n readScopeState: (slot: ScopeTemplateSlot) => ScopeGeneration,\n callRegistry: ModuleCallRegistry,\n): readonly Call<unknown, unknown>[] {\n const targetState: { current: readonly Call<unknown, unknown>[] | undefined } = { current: undefined };\n const resolveLocalCall: ResolveLocalCall = <Input, Output>(call: AttachmentCallRef<Input, Output>) => {\n const slot = getCompiledCallTargetBindingSlot(plan, call);\n const target = targetState.current?.[slot];\n\n if (target === undefined) throw new TypeError(`Call-target binding slot ${slot} is not instantiated.`);\n\n return target as Call<Input, Output>;\n };\n const targets = Object.freeze(\n plan.callTargetBindings.map(binding => {\n const attachment = attachments[binding.withinAttachmentSlot];\n\n if (attachment === undefined) {\n throw new TypeError(`Call target ${binding.id} lost its attachment binding.`);\n }\n\n const attachmentNode = plan.attachments[binding.withinAttachmentSlot];\n\n if (attachmentNode === undefined) throw new TypeError(`Call target ${binding.id} lost its attachment node.`);\n\n const owner = controllers[attachmentNode.ownerScopeSlot];\n\n if (owner === undefined) throw new TypeError(`Call target ${binding.id} lost its owner binding.`);\n\n const recipe = compiledAttachmentCallRecipe(template, binding.slot);\n const usesNestedFeatureCalls = recipe.nestedFeatureCalls === true;\n const run =\n recipe.policy !== undefined\n ? createFeatureCallRun(\n binding.id,\n binding.withinAttachmentSlot,\n recipe,\n attachmentNode.ownerScopeSlot,\n readScopeState,\n resolveLocalCall,\n callRegistry,\n )\n : usesNestedFeatureCalls\n ? createNestedFeatureCallRun(recipe, attachmentNode.ownerScopeSlot, readScopeState, resolveLocalCall)\n : createAttachmentCallRun(recipe, attachmentNode.ownerScopeSlot, readScopeState);\n\n return mintAttachmentCallTarget({\n id: binding.id,\n owner: getOwnerGenerationAuthoritySource(owner),\n run,\n within: attachment.bound.readiness,\n });\n }),\n );\n targetState.current = targets;\n\n return targets;\n}\n\nfunction createScopeRecords(\n instance: ModuleInstanceRecord,\n scopes: ScopeInstanceRecord[],\n controllers: readonly OwnerGenerationController[],\n): void {\n const { attachments, deferredFailures, plan } = instance;\n\n plan.scopes.forEach(node => {\n const runtime = Object.freeze({\n open: (value: unknown): Promise<LocalScopeOpenOutcome> => beginScopeOpen(instance, scopes[node.slot]!, value),\n ref: controllers[node.slot]?.ref,\n retire: (): LocalScopeRetirement => beginScopeRetirement(scopes[node.slot]!).runtime,\n }) as LocalScopeInstance<unknown>;\n\n if (runtime.ref === undefined) throw new TypeError(`Scope ${node.identity.id} lost its owner controller.`);\n\n const attachmentInstances = Object.freeze(\n node.attachmentSlots.map(slot => {\n const attachment = attachments[slot];\n\n if (attachment === undefined) throw new TypeError(`Attachment slot ${slot} is not instantiated.`);\n\n return attachment;\n }),\n );\n const scopeRecord: ScopeInstanceRecord = {\n active: undefined,\n attachmentInstances,\n controller: controllers[node.slot]!,\n deferredFailures,\n runtime,\n slot: node.slot,\n };\n scopes[node.slot] = scopeRecord;\n });\n}\n\nfunction localScopeInstance<Value>(\n record: ModuleInstanceRecord,\n scope: ScopeBlueprint<Value>,\n): LocalScopeInstance<Value> {\n return requireLocalScopeRecord(record, scope).runtime;\n}\n\nfunction createModuleInstanceRuntime(instanceRecord: ModuleInstanceRecord): LocalAttachmentModuleInstance {\n const { attachments, plan } = instanceRecord;\n\n return Object.freeze({\n diagnostics(): LocalAttachmentModuleDiagnostics {\n return Object.freeze({\n activeScopes: instanceRecord.scopes.filter(scope => scope.active !== undefined).length,\n attachmentControllers: attachments.length,\n deferredFailures: deferredFailureDiagnostics(instanceRecord),\n scopeControllers: instanceRecord.scopes.length,\n });\n },\n readiness<Value>(attachment: LifetimeAttachmentRef<Value>): AttachmentReadinessRef {\n const slot = getCompiledAttachmentSlot(plan, attachment);\n const attachmentInstance = attachments[slot];\n\n if (attachmentInstance === undefined) throw new TypeError(`Attachment slot ${slot} is not instantiated.`);\n\n return attachmentInstance.bound.readiness;\n },\n scope<Value>(scope: ScopeBlueprint<Value>): LocalScopeInstance<Value> {\n return localScopeInstance(instanceRecord, scope);\n },\n }) as LocalAttachmentModuleInstance;\n}\n\nfunction instantiateModuleTemplateWithOptions(\n plan: CompiledModuleTemplateIR,\n retainScopeValues: boolean,\n reporter?: AttachmentErrorReporter,\n): ModuleInstanceRecord {\n const template = getCompiledTemplateRecord(plan);\n const recipes = Object.freeze(plan.attachments.map(node => compiledAttachmentRecipe(template, node.slot)));\n const controllers = Object.freeze(plan.scopes.map(scope => createOwnerGenerationSlot({ id: scope.identity.id })));\n const deferredFailures = new Map<AttachmentInstance, DeferredAttachmentFailureOutcome>();\n const reporterState: AttachmentErrorReporterState = { reporter };\n const scopes: ScopeInstanceRecord[] = [];\n const readScopeState = (slot: ScopeTemplateSlot): ScopeGeneration => {\n const state = scopes[slot]?.active;\n\n if (state === undefined) throw new TypeError(`Scope slot ${slot} has no active generation value.`);\n\n return state;\n };\n const callRegistry = createModuleCallRegistry();\n const materializationBindings: (MaterializationBinding | undefined)[] = [];\n const attachments = createAttachmentInstances(\n plan,\n controllers,\n recipes,\n readScopeState,\n reporterState,\n callRegistry,\n materializationBindings,\n );\n const callTargets = createCallTargets(plan, template, attachments, controllers, readScopeState, callRegistry);\n const instanceRecord: ModuleInstanceRecord = {\n attachments,\n callRegistry,\n callTargets,\n deferredFailures,\n materializationBindings: Object.freeze(materializationBindings),\n plan,\n reporterState,\n retainScopeValues,\n scopes,\n };\n createScopeRecords(instanceRecord, scopes, controllers);\n Object.freeze(scopes);\n\n return instanceRecord;\n}\n\n/** The internal entry hands out the authentic handle; the layers inside the package pass the record itself. */\nfunction instantiateModuleTemplate(plan: CompiledModuleTemplateIR): LocalAttachmentModuleInstance {\n const record = instantiateModuleTemplateWithOptions(plan, false);\n const instance = createModuleInstanceRuntime(record);\n moduleInstances.set(instance, record);\n\n return instance;\n}\n\nfunction instantiateRetainedModuleTemplate(\n plan: CompiledModuleTemplateIR,\n reporter?: AttachmentErrorReporter,\n): ModuleInstanceRecord {\n return instantiateModuleTemplateWithOptions(plan, true, reporter);\n}\n\nfunction releaseLocalAttachmentErrorReporter(record: ModuleInstanceRecord): void {\n record.reporterState.reporter = undefined;\n}\n\nexport {\n hasActiveLocalAttachmentCallback,\n instantiateModuleTemplate,\n instantiateRetainedModuleTemplate,\n localScopeInstance,\n releaseLocalAttachmentErrorReporter,\n requireModuleInstanceRecord,\n resolveAttachmentCallTarget,\n retireLocalScopeIfActive,\n revokeLocalAttachmentModuleCallTargets,\n};\nexport type {\n LocalAttachmentCloseFailure,\n LocalAttachmentIdentity,\n LocalAttachmentModuleDiagnostics,\n LocalAttachmentModuleInstance,\n LocalScopeDrainOutcome,\n LocalScopeInstance,\n LocalScopeOpenOutcome,\n LocalScopeRetirement,\n ModuleInstanceRecord,\n} from './module-instance-types';\n"],"names":["moduleInstances","canHaveThen","value","hasActiveLocalAttachmentCallback","record","scope","_a","revokeLocalAttachmentModuleCallTargets","target","revokeCallTarget","resolveAttachmentCallTarget","call","slot","getCompiledCallTargetBindingSlot","requireLocalScopeRecord","getCompiledScopeSlot","scopeRecord","retireLocalScopeIfActive","beginScopeRetirement","createAttachmentCallRun","recipe","scopeSlot","readScopeState","input","context","state","combined","combineAbortSignals","callContext","throwIfSignalAborted","result","inheritCallExecutionMetadata","error","releaseCallExecutionMetadata","withCallTargetResultFinalizer","createNestedFeatureCallRun","resolveLocalCall","assertCallContextCurrent","bindLocalCallResolver","assertCurrent","inheritCallContextLifetime","retireCallContext","createFeatureCallRun","id","attachmentSlot","callRegistry","policy","invokeModuleCall","createModuleCallInvoker","executionContext","settleGuardedResult","createAttachmentInstances","plan","controllers","recipes","reporterState","materializationBindings","node","materializationBinding","createMaterializationBinding","lifecycle","createAttachmentLifecycleController","retireModuleAttachmentCalls","invokeAttachmentClose","withMaterializationBinding","invokeAttachmentOpen","owner","bindAttachmentLifecycleToOwner","createCallTargets","template","attachments","targetState","targets","binding","attachment","attachmentNode","compiledAttachmentCallRecipe","usesNestedFeatureCalls","run","mintAttachmentCallTarget","getOwnerGenerationAuthoritySource","createScopeRecords","instance","scopes","deferredFailures","runtime","beginScopeOpen","localScopeInstance","createModuleInstanceRuntime","instanceRecord","deferredFailureDiagnostics","getCompiledAttachmentSlot","attachmentInstance","instantiateModuleTemplateWithOptions","retainScopeValues","reporter","getCompiledTemplateRecord","compiledAttachmentRecipe","createOwnerGenerationSlot","createModuleCallRegistry","callTargets","instantiateModuleTemplate","instantiateRetainedModuleTemplate","releaseLocalAttachmentErrorReporter"],"mappings":"6yCA2DA,MAAMA,GAAkB,IAAI,QAM5B,SAASC,EAAYC,EAAc,CACjC,OAAQ,OAAOA,GAAU,UAAYA,IAAU,MAAS,OAAOA,GAAU,UAC3E,CAUA,SAASC,GAAiCC,EAA4B,CACpE,OAAOA,EAAO,OAAO,KAAKC,GAAK,OAAK,SAAAC,EAAAD,EAAM,SAAN,YAAAC,EAAc,0BAA2B,KAAO,EAAC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GAAI7F,EAAM,SAAS,EAAE,CAAE,CAAC,CAAC,EAC1G+E,EAAmB,IAAI,IACvB7B,EAA8C,CAAE,SAAAwC,CAAQ,EACxDZ,EAAgC,CAAA,EAChC7D,EAAkBV,GAA4C,OAClE,MAAMa,GAAQnB,EAAA6E,EAAOvE,CAAI,IAAX,YAAAN,EAAc,OAE5B,GAAImB,IAAU,OAAW,MAAM,IAAI,UAAU,cAAcb,CAAI,kCAAkC,EAEjG,OAAOa,CACT,EACMoB,EAAesD,EAAwB,EACvC3C,EAAkE,CAAA,EAClEc,EAAcnB,GAClBC,EACAC,EACAC,EACAhC,EACAiC,EACAV,EACAW,CAAuB,EAEnB4C,EAAchC,GAAkBhB,EAAMiB,EAAUC,EAAajB,EAAa/B,EAAgBuB,CAAY,EACtG4C,EAAuC,CAC3C,YAAAnB,EACA,aAAAzB,EACA,YAAAuD,EACA,iBAAAhB,EACA,wBAAyB,OAAO,OAAO5B,CAAuB,EAC9D,KAAAJ,EACA,cAAAG,EACA,kBAAAuC,EACA,OAAAX,GAEF,OAAAF,GAAmBQ,EAAgBN,EAAQ9B,CAAW,EACtD,OAAO,OAAO8B,CAAM,EAEbM,CACT,CAGA,SAASY,GAA0BjD,EAA8B,CAC/D,MAAMhD,EAASyF,EAAqCzC,EAAM,EAAK,EACzD8B,EAAWM,GAA4BpF,CAAM,EACnD,OAAAJ,GAAgB,IAAIkF,EAAU9E,CAAM,EAE7B8E,CACT,CAEA,SAASoB,GACPlD,EACA2C,EAAkC,CAElC,OAAOF,EAAqCzC,EAAM,GAAM2C,CAAQ,CAClE,CAEA,SAASQ,GAAoCnG,EAA4B,CACvEA,EAAO,cAAc,SAAW,MAClC"}
@@ -0,0 +1,4 @@
1
+ import type { DeclarationId } from '@opetope/core';
2
+ import type { RuntimeNodeIdentityIR } from './module-template-ir.js';
3
+ declare const runtimeIdentity: (moduleId: DeclarationId, kind: RuntimeNodeIdentityIR["kind"], key: string) => RuntimeNodeIdentityIR;
4
+ export { runtimeIdentity };
@@ -0,0 +1,2 @@
1
+ import{declarationId as i}from"@opetope/core";const n=(t,e,r)=>Object.freeze({id:i(`${t}/runtime/${e}/${r}`),key:r,kind:e,moduleId:t,stage:"runtime"});export{n as runtimeIdentity};
2
+ //# sourceMappingURL=module-runtime-identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module-runtime-identity.js","sources":["../src/module-runtime-identity.ts"],"sourcesContent":["import { declarationId } from '@opetope/core';\nimport type { DeclarationId } from '@opetope/core';\n\nimport type { RuntimeNodeIdentityIR } from './module-template-ir';\n\nconst runtimeIdentity = (\n moduleId: DeclarationId,\n kind: RuntimeNodeIdentityIR['kind'],\n key: string,\n): RuntimeNodeIdentityIR =>\n Object.freeze({ id: declarationId(`${moduleId}/runtime/${kind}/${key}`), key, kind, moduleId, stage: 'runtime' });\n\nexport { runtimeIdentity };\n"],"names":["runtimeIdentity","moduleId","kind","key","declarationId"],"mappings":"8CAKA,MAAMA,EAAkB,CACtBC,EACAC,EACAC,IAEA,OAAO,OAAO,CAAE,GAAIC,EAAc,GAAGH,CAAQ,YAAYC,CAAI,IAAIC,CAAG,EAAE,EAAG,IAAAA,EAAK,KAAAD,EAAM,SAAAD,EAAU,MAAO,SAAS,CAAE"}
@@ -0,0 +1,4 @@
1
+ import type { LocalDeferredAttachmentFailure, LocalScopeOpenOutcome, ModuleInstanceRecord, ScopeInstanceRecord } from './module-instance-types.js';
2
+ declare function deferredFailureDiagnostics(instance: ModuleInstanceRecord): readonly LocalDeferredAttachmentFailure[];
3
+ declare function beginScopeOpen(instance: ModuleInstanceRecord, scope: ScopeInstanceRecord, value: unknown): Promise<LocalScopeOpenOutcome>;
4
+ export { beginScopeOpen, deferredFailureDiagnostics };
@@ -0,0 +1,2 @@
1
+ import{reportDetachedError as u}from"@opetope/core/internal";import{beginScopeRetirement as h}from"./module-scope-retirement.js";import{openOwnerBoundAttachment as j}from"./owner-generation.js";const F=Object.freeze({kind:"ready"}),E=0,k=1,I=2,m=3;function g(n){return n.kind==="committed"&&n.state==="ready"}function D(n){return n.kind==="failed"||n.kind==="quarantined"}function P(n){return Object.freeze({error:n,kind:"rejected"})}function N(n,t,e){if(g(e)){n.deferredFailures.delete(t);return}D(e)&&n.deferredFailures.set(t,e)}function V(n){return Object.freeze([...n.deferredFailures.entries()].sort(([t],[e])=>t.slot-e.slot).map(([t,e])=>Object.freeze({attachmentId:t.id,attachmentSlot:t.slot,outcome:e})))}function p(n,t){const e=n.plan.scopes[t.slot];if(e===void 0)throw new TypeError(`Scope slot ${t.slot} lost its compiled node.`);return e}function S(n,t,e){const r=p(n,t),c=r.attachmentSlots[e];if(c===void 0)throw new TypeError(`Scope attachment slot ${e} is outside scope ${r.identity.id}.`);const i=n.plan.attachments[c];if(i===void 0||i.scopeAttachmentSlot!==e)throw new TypeError(`Scope attachment slot ${e} lost its compiled attachment node.`);return i}function z(n,t){const e=n.attachmentInstances[t];if(e===void 0||e.scopeAttachmentSlot!==t)throw new TypeError(`Scope attachment slot ${t} is not instantiated.`);return e}function s(n,t){return n==="critical"?t==="opening":t==="ready"}function y(n,t,e){if(t.rejectOpen(e),t.phase!=="opening"){u(e);return}try{h(n)}catch(r){u(r)}}function O(n,t,e){n.deferredFailures.set(t,P(e)),u(e)}function A(n){n.phase==="ready"&&n.unstartedAttachments===0&&(n.openingValue=void 0)}function T(n,t,e,r,c,i){e.attachmentStates[c]=I,i==="critical"?e.criticalPending-=1:n.deferredFailures.delete(r),i==="critical"&&e.criticalPending===0&&w(n,t,e)}function $(n,t,e,r,c,i,o){if(!(t.active!==e||!s(i,e.phase))){if(g(o)){T(n,t,e,r,c,i);return}if(e.attachmentStates[c]=m,i==="deferred"){N(n,r,o);return}if(e.failure===void 0){e.failure=Object.freeze({attachment:r,outcome:o});try{h(t)}catch(d){u(d)}}}}function q(n,t,e,r){const c=S(n,t,r);if(t.active!==e||e.attachmentStates[r]!==E||!s(c.readiness,e.phase))return;const i=z(t,r),o=e.openingValue;e.attachmentStates[r]=k,e.unstartedAttachments-=1;let d;try{d=j(i.bound,e.generation,o)}catch(a){e.attachmentStates[r]=m,c.readiness==="critical"?y(t,e,a):O(n,i,a);return}A(e),d.then(a=>$(n,t,e,i,r,c.readiness,a),a=>{if(t.active!==e||!s(c.readiness,e.phase)){u(a);return}e.attachmentStates[r]=m,c.readiness==="critical"?y(t,e,a):O(n,i,a)})}function b(n,t,e,r){p(n,t).attachmentSlots.forEach((i,o)=>{const d=o;S(n,t,d).readiness===r&&q(n,t,e,d)})}function w(n,t,e){t.active!==e||e.phase!=="opening"||(e.phase="committing",t.controller.commit(e.generation),e.retirement===void 0&&(e.phase="ready",b(n,t,e,"deferred"),A(e),e.resolveOpen(F)))}function R(n,t){if((n.phase==="committing"||n.phase==="opening")&&Object.is(n.openingValue,t))return n.openPromise;throw new TypeError("Local scope is already active or retiring.")}function C(n,t,e){b(n,t,e,"critical"),e.criticalPending===0&&w(n,t,e)}function _(n,t,e){t.rejectOpen(e),t.retirement===void 0&&h(n)}function U(n,t,e){const r=t.active;if(r!==void 0)return R(r,e);const c=p(n,t);t.attachmentInstances.forEach(l=>n.deferredFailures.delete(l));const i=t.controller.begin();let o=l=>{},d=l=>{};const a=new Promise((l,v)=>{o=v,d=l}),f={attachmentStates:new Uint8Array(t.attachmentInstances.length),callbackInvocationDepth:0,criticalPending:c.criticalAttachmentSlots.length,failure:void 0,generation:i,invokeAttachmentCallback:l=>{f.callbackInvocationDepth+=1;try{return l()}finally{f.callbackInvocationDepth-=1}},openingValue:e,openPromise:a,phase:"opening",rejectOpen:o,resolveOpen:d,retirement:void 0,unstartedAttachments:t.attachmentInstances.length,value:n.retainScopeValues?e:void 0};t.active=f;try{C(n,t,f)}catch(l){_(t,f,l)}return a}export{U as beginScopeOpen,V as deferredFailureDiagnostics};
2
+ //# sourceMappingURL=module-scope-open.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module-scope-open.js","sources":["../src/module-scope-open.ts"],"sourcesContent":["import { reportDetachedError } from '@opetope/core/internal';\nimport type { AttachmentIntentOutcome } from '@opetope/core/internal';\n\nimport type {\n AttachmentInstance,\n DeferredAttachmentFailureOutcome,\n LocalDeferredAttachmentFailure,\n LocalScopeOpenOutcome,\n ModuleInstanceRecord,\n ScopeGeneration,\n ScopeGenerationPhase,\n ScopeInstanceRecord,\n} from './module-instance-types';\nimport { beginScopeRetirement } from './module-scope-retirement';\nimport type { ScopeAttachmentSlot } from './module-template-ir';\nimport { openOwnerBoundAttachment } from './owner-generation';\n\nconst readyOpenOutcome = Object.freeze({ kind: 'ready' as const });\nconst attachmentPending = 0;\nconst attachmentOpening = 1;\nconst attachmentReady = 2;\nconst attachmentFailed = 3;\n\nfunction isReadyOutcome(outcome: AttachmentIntentOutcome): boolean {\n return outcome.kind === 'committed' && outcome.state === 'ready';\n}\n\nfunction isDeferredFailureOutcome(\n outcome: AttachmentIntentOutcome,\n): outcome is Extract<AttachmentIntentOutcome, { readonly kind: 'failed' | 'quarantined' }> {\n return outcome.kind === 'failed' || outcome.kind === 'quarantined';\n}\n\nfunction rejectedDeferredFailure(error: unknown): DeferredAttachmentFailureOutcome {\n return Object.freeze({ error, kind: 'rejected' as const });\n}\n\nfunction settleDeferredAttachment(\n instance: ModuleInstanceRecord,\n attachment: AttachmentInstance,\n outcome: AttachmentIntentOutcome,\n): void {\n if (isReadyOutcome(outcome)) {\n instance.deferredFailures.delete(attachment);\n\n return;\n }\n\n if (isDeferredFailureOutcome(outcome)) instance.deferredFailures.set(attachment, outcome);\n}\n\nfunction deferredFailureDiagnostics(instance: ModuleInstanceRecord): readonly LocalDeferredAttachmentFailure[] {\n return Object.freeze(\n [...instance.deferredFailures.entries()]\n .sort(([left], [right]) => left.slot - right.slot)\n .map(([attachment, outcome]) =>\n Object.freeze({ attachmentId: attachment.id, attachmentSlot: attachment.slot, outcome }),\n ),\n );\n}\n\nfunction requireScopeNode(instance: ModuleInstanceRecord, scope: ScopeInstanceRecord) {\n const node = instance.plan.scopes[scope.slot];\n\n if (node === undefined) throw new TypeError(`Scope slot ${scope.slot} lost its compiled node.`);\n\n return node;\n}\n\nfunction requireScopeAttachmentNode(\n instance: ModuleInstanceRecord,\n scope: ScopeInstanceRecord,\n slot: ScopeAttachmentSlot,\n) {\n const scopeNode = requireScopeNode(instance, scope);\n const attachmentSlot = scopeNode.attachmentSlots[slot];\n\n if (attachmentSlot === undefined) {\n throw new TypeError(`Scope attachment slot ${slot} is outside scope ${scopeNode.identity.id}.`);\n }\n\n const node = instance.plan.attachments[attachmentSlot];\n\n if (node === undefined || node.scopeAttachmentSlot !== slot) {\n throw new TypeError(`Scope attachment slot ${slot} lost its compiled attachment node.`);\n }\n\n return node;\n}\n\nfunction requireScopeAttachmentInstance(scope: ScopeInstanceRecord, slot: ScopeAttachmentSlot): AttachmentInstance {\n const attachment = scope.attachmentInstances[slot];\n\n if (attachment === undefined || attachment.scopeAttachmentSlot !== slot) {\n throw new TypeError(`Scope attachment slot ${slot} is not instantiated.`);\n }\n\n return attachment;\n}\n\nfunction attachmentPhaseAllowsStart(readiness: 'critical' | 'deferred', phase: ScopeGenerationPhase): boolean {\n return readiness === 'critical' ? phase === 'opening' : phase === 'ready';\n}\n\nfunction failCriticalAttachmentStart(scope: ScopeInstanceRecord, state: ScopeGeneration, error: unknown): void {\n state.rejectOpen(error);\n\n if (state.phase !== 'opening') {\n reportDetachedError(error);\n\n return;\n }\n\n try {\n beginScopeRetirement(scope);\n } catch (retirementError) {\n reportDetachedError(retirementError);\n }\n}\n\nfunction failDeferredAttachmentStart(\n instance: ModuleInstanceRecord,\n attachment: AttachmentInstance,\n error: unknown,\n): void {\n instance.deferredFailures.set(attachment, rejectedDeferredFailure(error));\n reportDetachedError(error);\n}\n\nfunction releaseOpeningValueIfFullyScheduled(state: ScopeGeneration): void {\n if (state.phase === 'ready' && state.unstartedAttachments === 0) state.openingValue = undefined;\n}\n\nfunction settleReadyAttachment(\n instance: ModuleInstanceRecord,\n scope: ScopeInstanceRecord,\n state: ScopeGeneration,\n attachment: AttachmentInstance,\n slot: ScopeAttachmentSlot,\n readiness: 'critical' | 'deferred',\n): void {\n state.attachmentStates[slot] = attachmentReady;\n\n if (readiness === 'critical') state.criticalPending -= 1;\n else instance.deferredFailures.delete(attachment);\n\n // oxlint-disable-next-line eslint/no-use-before-define -- readiness settlement closes the startup worklist\n if (readiness === 'critical' && state.criticalPending === 0) commitScopeGeneration(instance, scope, state);\n}\n\nfunction settleAttachmentOpen(\n instance: ModuleInstanceRecord,\n scope: ScopeInstanceRecord,\n state: ScopeGeneration,\n attachment: AttachmentInstance,\n slot: ScopeAttachmentSlot,\n readiness: 'critical' | 'deferred',\n outcome: AttachmentIntentOutcome,\n): void {\n if (scope.active !== state || !attachmentPhaseAllowsStart(readiness, state.phase)) return;\n\n if (isReadyOutcome(outcome)) {\n settleReadyAttachment(instance, scope, state, attachment, slot, readiness);\n\n return;\n }\n\n state.attachmentStates[slot] = attachmentFailed;\n\n if (readiness === 'deferred') {\n settleDeferredAttachment(instance, attachment, outcome);\n\n return;\n }\n\n if (state.failure !== undefined) return;\n\n state.failure = Object.freeze({ attachment, outcome });\n\n try {\n beginScopeRetirement(scope);\n } catch (error) {\n reportDetachedError(error);\n }\n}\n\nfunction startEligibleAttachment(\n instance: ModuleInstanceRecord,\n scope: ScopeInstanceRecord,\n state: ScopeGeneration,\n slot: ScopeAttachmentSlot,\n): void {\n const node = requireScopeAttachmentNode(instance, scope, slot);\n\n if (\n scope.active !== state ||\n state.attachmentStates[slot] !== attachmentPending ||\n !attachmentPhaseAllowsStart(node.readiness, state.phase)\n ) {\n return;\n }\n\n const attachment = requireScopeAttachmentInstance(scope, slot);\n const value = state.openingValue;\n state.attachmentStates[slot] = attachmentOpening;\n state.unstartedAttachments -= 1;\n\n let opening: Promise<AttachmentIntentOutcome>;\n\n try {\n opening = openOwnerBoundAttachment(attachment.bound, state.generation, value);\n } catch (error) {\n state.attachmentStates[slot] = attachmentFailed;\n\n if (node.readiness === 'critical') failCriticalAttachmentStart(scope, state, error);\n else failDeferredAttachmentStart(instance, attachment, error);\n\n return;\n }\n\n releaseOpeningValueIfFullyScheduled(state);\n\n void opening.then(\n outcome => settleAttachmentOpen(instance, scope, state, attachment, slot, node.readiness, outcome),\n (error: unknown) => {\n if (scope.active !== state || !attachmentPhaseAllowsStart(node.readiness, state.phase)) {\n reportDetachedError(error);\n\n return;\n }\n\n state.attachmentStates[slot] = attachmentFailed;\n\n if (node.readiness === 'critical') failCriticalAttachmentStart(scope, state, error);\n else failDeferredAttachmentStart(instance, attachment, error);\n },\n );\n}\n\nfunction startEligibleAttachments(\n instance: ModuleInstanceRecord,\n scope: ScopeInstanceRecord,\n state: ScopeGeneration,\n readiness: 'critical' | 'deferred',\n): void {\n const scopeNode = requireScopeNode(instance, scope);\n\n scopeNode.attachmentSlots.forEach((_attachmentSlot, index) => {\n const slot = index as ScopeAttachmentSlot;\n const node = requireScopeAttachmentNode(instance, scope, slot);\n\n if (node.readiness === readiness) startEligibleAttachment(instance, scope, state, slot);\n });\n}\n\nfunction commitScopeGeneration(\n instance: ModuleInstanceRecord,\n scope: ScopeInstanceRecord,\n state: ScopeGeneration,\n): void {\n if (scope.active !== state || state.phase !== 'opening') return;\n\n state.phase = 'committing';\n scope.controller.commit(state.generation);\n\n if (state.retirement !== undefined) return;\n\n state.phase = 'ready';\n startEligibleAttachments(instance, scope, state, 'deferred');\n releaseOpeningValueIfFullyScheduled(state);\n state.resolveOpen(readyOpenOutcome);\n}\n\nfunction joinActiveScopeOpen(active: ScopeGeneration, value: unknown): Promise<LocalScopeOpenOutcome> {\n if ((active.phase === 'committing' || active.phase === 'opening') && Object.is(active.openingValue, value)) {\n return active.openPromise;\n }\n\n throw new TypeError('Local scope is already active or retiring.');\n}\n\nfunction startCriticalAttachments(\n instance: ModuleInstanceRecord,\n scope: ScopeInstanceRecord,\n state: ScopeGeneration,\n): void {\n startEligibleAttachments(instance, scope, state, 'critical');\n\n if (state.criticalPending === 0) commitScopeGeneration(instance, scope, state);\n}\n\nfunction cleanUpFailedScopeOpen(scope: ScopeInstanceRecord, state: ScopeGeneration, error: unknown): void {\n state.rejectOpen(error);\n\n if (state.retirement === undefined) beginScopeRetirement(scope);\n}\n\nfunction beginScopeOpen(\n instance: ModuleInstanceRecord,\n scope: ScopeInstanceRecord,\n value: unknown,\n): Promise<LocalScopeOpenOutcome> {\n const active = scope.active;\n\n if (active !== undefined) return joinActiveScopeOpen(active, value);\n\n const scopeNode = requireScopeNode(instance, scope);\n scope.attachmentInstances.forEach(attachment => instance.deferredFailures.delete(attachment));\n const generation = scope.controller.begin();\n let rejectOpen = (_error: unknown): void => undefined;\n let resolveOpen = (_outcome: LocalScopeOpenOutcome): void => undefined;\n const openPromise = new Promise<LocalScopeOpenOutcome>((resolve, reject) => {\n rejectOpen = reject;\n resolveOpen = resolve;\n });\n const state: ScopeGeneration = {\n attachmentStates: new Uint8Array(scope.attachmentInstances.length),\n callbackInvocationDepth: 0,\n criticalPending: scopeNode.criticalAttachmentSlots.length,\n failure: undefined,\n generation,\n invokeAttachmentCallback: callback => {\n state.callbackInvocationDepth += 1;\n\n try {\n return callback();\n } finally {\n state.callbackInvocationDepth -= 1;\n }\n },\n openingValue: value,\n openPromise,\n phase: 'opening',\n rejectOpen,\n resolveOpen,\n retirement: undefined,\n unstartedAttachments: scope.attachmentInstances.length,\n value: instance.retainScopeValues ? value : undefined,\n };\n scope.active = state;\n\n try {\n startCriticalAttachments(instance, scope, state);\n } catch (error) {\n cleanUpFailedScopeOpen(scope, state, error);\n }\n\n return openPromise;\n}\n\nexport { beginScopeOpen, deferredFailureDiagnostics };\n"],"names":["readyOpenOutcome","attachmentPending","attachmentOpening","attachmentReady","attachmentFailed","isReadyOutcome","outcome","isDeferredFailureOutcome","rejectedDeferredFailure","error","settleDeferredAttachment","instance","attachment","deferredFailureDiagnostics","left","right","requireScopeNode","scope","node","requireScopeAttachmentNode","slot","scopeNode","attachmentSlot","requireScopeAttachmentInstance","attachmentPhaseAllowsStart","readiness","phase","failCriticalAttachmentStart","state","reportDetachedError","beginScopeRetirement","retirementError","failDeferredAttachmentStart","releaseOpeningValueIfFullyScheduled","settleReadyAttachment","commitScopeGeneration","settleAttachmentOpen","startEligibleAttachment","value","opening","openOwnerBoundAttachment","startEligibleAttachments","_attachmentSlot","index","joinActiveScopeOpen","active","startCriticalAttachments","cleanUpFailedScopeOpen","beginScopeOpen","generation","rejectOpen","_error","resolveOpen","_outcome","openPromise","resolve","reject","callback"],"mappings":"kMAiBA,MAAMA,EAAmB,OAAO,OAAO,CAAE,KAAM,OAAgB,CAAE,EAC3DC,EAAoB,EACpBC,EAAoB,EACpBC,EAAkB,EAClBC,EAAmB,EAEzB,SAASC,EAAeC,EAAgC,CACtD,OAAOA,EAAQ,OAAS,aAAeA,EAAQ,QAAU,OAC3D,CAEA,SAASC,EACPD,EAAgC,CAEhC,OAAOA,EAAQ,OAAS,UAAYA,EAAQ,OAAS,aACvD,CAEA,SAASE,EAAwBC,EAAc,CAC7C,OAAO,OAAO,OAAO,CAAE,MAAAA,EAAO,KAAM,UAAmB,CAAE,CAC3D,CAEA,SAASC,EACPC,EACAC,EACAN,EAAgC,CAEhC,GAAID,EAAeC,CAAO,EAAG,CAC3BK,EAAS,iBAAiB,OAAOC,CAAU,EAE3C,MACF,CAEIL,EAAyBD,CAAO,GAAGK,EAAS,iBAAiB,IAAIC,EAAYN,CAAO,CAC1F,CAEA,SAASO,EAA2BF,EAA8B,CAChE,OAAO,OAAO,OACZ,CAAC,GAAGA,EAAS,iBAAiB,QAAO,CAAE,EACpC,KAAK,CAAC,CAACG,CAAI,EAAG,CAACC,CAAK,IAAMD,EAAK,KAAOC,EAAM,IAAI,EAChD,IAAI,CAAC,CAACH,EAAYN,CAAO,IACxB,OAAO,OAAO,CAAE,aAAcM,EAAW,GAAI,eAAgBA,EAAW,KAAM,QAAAN,CAAO,CAAE,CAAC,CACzF,CAEP,CAEA,SAASU,EAAiBL,EAAgCM,EAA0B,CAClF,MAAMC,EAAOP,EAAS,KAAK,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AAK,CAC5C,CAEA,OAAO6C,CACT"}
@@ -0,0 +1,3 @@
1
+ import type { RetirementRecord, ScopeInstanceRecord } from './module-instance-types.js';
2
+ declare function beginScopeRetirement(scope: ScopeInstanceRecord): RetirementRecord;
3
+ export { beginScopeRetirement };
@@ -0,0 +1,2 @@
1
+ import{createAttachmentRetirementScheduler as h}from"./attachment-retirement-scheduler.js";import{retryOwnerBoundAttachmentClose as w}from"./owner-generation.js";import{retirePlannedOwnerGeneration as y,acknowledgeOwnerGenerationDrain as R}from"./owner-generation-retirement.js";const P=Object.freeze({kind:"closed"});function g(e){const n=e.ownerRetirement;if(n===void 0)throw new TypeError("Local scope retirement is already workspace.");return n}function u(e){const n=e.scope;if(n===void 0)throw new TypeError("Local scope retirement is already workspace.");return n}function d(e){const n=e.state;if(n===void 0)throw new TypeError("Local scope retirement is already workspace.");return n}function v(e){const n=g(e),t=u(e),r=d(e);R(t.controller,r.generation,n.attachments,n.retirement),e.drainPromise=void 0,e.ownerRetirement=void 0,e.prepared=void 0,e.retryPromise=void 0,e.scheduler=void 0,t.attachmentInstances.forEach(i=>t.deferredFailures.delete(i)),t.active===r&&(t.active=void 0),r.value=void 0,e.rejectPrepared=()=>{},e.resolvePrepared=()=>{},e.scope=void 0,e.state=void 0,e.handleState.outcome=P,e.handleState.record=void 0}function s(e){const n=e.scheduler;if(n===void 0)throw new TypeError("Retirement scheduler unavailable.");return n}function f(e){if(e.drainPromise===void 0){const n=e.prepared;if(n===void 0)throw new TypeError("Retirement preparation unavailable.");e.drainPromise=n.then(()=>s(e).drain())}return e.drainPromise}function b(e){if(e.retryPromise!==void 0)return e.retryPromise;const n=e.prepared;if(n===void 0)throw new TypeError("Retirement preparation unavailable.");const r=n.then(()=>s(e).retry()).finally(()=>{e.retryPromise===r&&e.handleState.outcome===void 0&&(e.retryPromise=void 0)});return e.retryPromise=r,r}function O(e){const n=e.record;if(n===void 0)throw new TypeError("Retirement record unavailable.");return n}function m(e){const n=O(e);if(d(n).callbackInvocationDepth!==0)throw new TypeError("Local scope retirement cannot be awaited from its synchronous attachment callback.");return n}function E(e){return Object.freeze({drain:()=>e.outcome===void 0?f(m(e)):Promise.resolve(e.outcome),retry:()=>e.outcome===void 0?b(m(e)):Promise.resolve(e.outcome)})}function S(e,n){let t=c=>{},r=()=>{};const i=new Promise((c,l)=>{t=l,r=c}),o={outcome:void 0,record:void 0},a={drainPromise:void 0,handleState:o,ownerRetirement:void 0,prepared:i,rejectPrepared:t,resolvePrepared:r,retryPromise:void 0,runtime:void 0,scheduler:void 0,scope:e,state:n};return o.record=a,a.runtime=E(o),a}function j(e){let n=i=>{},t=()=>{};const r=new Promise((i,o)=>{n=o,t=i});e.drainPromise=void 0,e.prepared=r,e.rejectPrepared=n,e.resolvePrepared=t,e.retryPromise=void 0}function T(e,n){const t=[];let r=0;for(const i of e.attachmentInstances)i.bound===n.attachments[r]&&(t.push(i),r+=1);if(r!==n.attachments.length)throw new TypeError("Owner retirement selected an attachment outside its compiled scope instance.");return Object.freeze(t)}function k(e,n,t){const r=n.retirement.retirements;if(r.length!==t.length)throw new TypeError("Owner retirement lost alignment with the compiled attachment graph.");return h({attachments:t,onTerminal:()=>v(e),retirements:r,retryAttachment:i=>w(i.bound)})}function x(e){const n=d(e);f(e).then(t=>{const r=n.failure;n.openingValue=void 0,r===void 0?n.resolveOpen(Object.freeze({drain:t,kind:"retired",retirement:e.runtime})):n.resolveOpen(Object.freeze({attachmentId:r.attachment.id,attachmentSlot:r.attachment.slot,drain:t,kind:"not-ready",outcome:r.outcome,retirement:e.runtime}))},t=>n.rejectOpen(t))}function p(e){var r;const n=u(e),t=d(e);t.phase="fencing",t.openingValue=void 0;try{const i=e.ownerRetirement??y(n.controller,t.generation,n.attachmentInstances.map(a=>a.bound)),o=T(n,i);e.ownerRetirement=i,e.scheduler=k(e,i,o),t.phase="retiring",e.resolvePrepared()}catch(i){throw t.openingValue=void 0,t.phase="retiring",(r=e.prepared)==null||r.catch(()=>{}),e.rejectPrepared(i),t.rejectOpen(i),i}}function A(e){const n=e.active;if(n===void 0)throw new TypeError("Cannot retire an inactive local scope.");const t=n.retirement;if(t!==void 0)return t.scheduler===void 0&&(j(t),p(t)),t;const r=n.phase==="committing"||n.phase==="opening",i=S(e,n);return n.retirement=i,r&&x(i),p(i),i}export{A as beginScopeRetirement};
2
+ //# sourceMappingURL=module-scope-retirement.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module-scope-retirement.js","sources":["../src/module-scope-retirement.ts"],"sourcesContent":["import { createAttachmentRetirementScheduler } from './attachment-retirement-scheduler';\nimport type {\n AttachmentInstance,\n AttachmentRetirementScheduler,\n LocalScopeDrainOutcome,\n LocalScopeRetirement,\n RetirementHandleState,\n RetirementRecord,\n ScopeGeneration,\n ScopeInstanceRecord,\n} from './module-instance-types';\nimport {\n acknowledgeOwnerGenerationDrain,\n retirePlannedOwnerGeneration,\n retryOwnerBoundAttachmentClose,\n} from './owner-generation';\nimport type { OwnerGenerationPlanRetirement } from './owner-generation';\n\nconst closedDrainOutcome = Object.freeze({ kind: 'closed' as const });\n\nfunction workspaceRetirementRecord(record: RetirementRecord): OwnerGenerationPlanRetirement {\n const ownerRetirement = record.ownerRetirement;\n\n if (ownerRetirement === undefined) throw new TypeError('Local scope retirement is already workspace.');\n\n return ownerRetirement;\n}\n\nfunction retirementScope(record: RetirementRecord): ScopeInstanceRecord {\n const scope = record.scope;\n\n if (scope === undefined) throw new TypeError('Local scope retirement is already workspace.');\n\n return scope;\n}\n\nfunction retirementState(record: RetirementRecord): ScopeGeneration {\n const state = record.state;\n\n if (state === undefined) throw new TypeError('Local scope retirement is already workspace.');\n\n return state;\n}\n\nfunction clearActiveRetirement(record: RetirementRecord): void {\n const ownerRetirement = workspaceRetirementRecord(record);\n const scope = retirementScope(record);\n const state = retirementState(record);\n acknowledgeOwnerGenerationDrain(\n scope.controller,\n state.generation,\n ownerRetirement.attachments,\n ownerRetirement.retirement,\n );\n record.drainPromise = undefined;\n record.ownerRetirement = undefined;\n record.prepared = undefined;\n record.retryPromise = undefined;\n record.scheduler = undefined;\n scope.attachmentInstances.forEach(attachment => scope.deferredFailures.delete(attachment));\n\n if (scope.active === state) scope.active = undefined;\n\n state.value = undefined;\n\n record.rejectPrepared = (): void => undefined;\n record.resolvePrepared = (): void => undefined;\n record.scope = undefined;\n record.state = undefined;\n record.handleState.outcome = closedDrainOutcome;\n record.handleState.record = undefined;\n}\n\nfunction preparedRetirementScheduler(record: RetirementRecord): AttachmentRetirementScheduler {\n const scheduler = record.scheduler;\n\n if (scheduler === undefined) throw new TypeError('Retirement scheduler unavailable.');\n\n return scheduler;\n}\n\nfunction drainRetirement(record: RetirementRecord): Promise<LocalScopeDrainOutcome> {\n if (record.drainPromise === undefined) {\n const prepared = record.prepared;\n\n if (prepared === undefined) throw new TypeError('Retirement preparation unavailable.');\n\n record.drainPromise = prepared.then(() => preparedRetirementScheduler(record).drain());\n }\n\n return record.drainPromise;\n}\n\nfunction retryRetirement(record: RetirementRecord): Promise<LocalScopeDrainOutcome> {\n if (record.retryPromise !== undefined) return record.retryPromise;\n\n const prepared = record.prepared;\n\n if (prepared === undefined) throw new TypeError('Retirement preparation unavailable.');\n\n const operation = prepared.then(() => preparedRetirementScheduler(record).retry());\n const singleFlight = operation.finally(() => {\n if (record.retryPromise === singleFlight && record.handleState.outcome === undefined) {\n record.retryPromise = undefined;\n }\n });\n record.retryPromise = singleFlight;\n\n return singleFlight;\n}\n\nfunction requireRetirementHandleRecord(state: RetirementHandleState): RetirementRecord {\n const record = state.record;\n\n if (record === undefined) throw new TypeError('Retirement record unavailable.');\n\n return record;\n}\n\nfunction requireExternallyCallableRetirementRecord(state: RetirementHandleState): RetirementRecord {\n const record = requireRetirementHandleRecord(state);\n\n if (retirementState(record).callbackInvocationDepth !== 0) {\n throw new TypeError('Local scope retirement cannot be awaited from its synchronous attachment callback.');\n }\n\n return record;\n}\n\nfunction createRetirementRuntime(state: RetirementHandleState): LocalScopeRetirement {\n return Object.freeze({\n drain: (): Promise<LocalScopeDrainOutcome> =>\n state.outcome === undefined\n ? drainRetirement(requireExternallyCallableRetirementRecord(state))\n : Promise.resolve(state.outcome),\n retry: (): Promise<LocalScopeDrainOutcome> =>\n state.outcome === undefined\n ? retryRetirement(requireExternallyCallableRetirementRecord(state))\n : Promise.resolve(state.outcome),\n }) as LocalScopeRetirement;\n}\n\nfunction createRetirementRecord(scope: ScopeInstanceRecord, state: ScopeGeneration): RetirementRecord {\n let rejectPrepared = (_error: unknown): void => undefined;\n let resolvePrepared = (): void => undefined;\n const prepared = new Promise<void>((resolve, reject) => {\n rejectPrepared = reject;\n resolvePrepared = resolve;\n });\n const handleState: RetirementHandleState = { outcome: undefined, record: undefined };\n const record: RetirementRecord = {\n drainPromise: undefined,\n handleState,\n ownerRetirement: undefined,\n prepared,\n rejectPrepared,\n resolvePrepared,\n retryPromise: undefined,\n runtime: undefined as unknown as LocalScopeRetirement,\n scheduler: undefined,\n scope,\n state,\n };\n handleState.record = record;\n record.runtime = createRetirementRuntime(handleState);\n\n return record;\n}\n\nfunction resetRetirementPreparation(record: RetirementRecord): void {\n let rejectPrepared = (_error: unknown): void => undefined;\n let resolvePrepared = (): void => undefined;\n const prepared = new Promise<void>((resolve, reject) => {\n rejectPrepared = reject;\n resolvePrepared = resolve;\n });\n record.drainPromise = undefined;\n record.prepared = prepared;\n record.rejectPrepared = rejectPrepared;\n record.resolvePrepared = resolvePrepared;\n record.retryPromise = undefined;\n}\n\nfunction exactAttachmentInstances(\n scope: ScopeInstanceRecord,\n planRetirement: OwnerGenerationPlanRetirement,\n): readonly AttachmentInstance[] {\n const exact: AttachmentInstance[] = [];\n let selectedIndex = 0;\n\n for (const attachment of scope.attachmentInstances) {\n if (attachment.bound !== planRetirement.attachments[selectedIndex]) continue;\n\n exact.push(attachment);\n selectedIndex += 1;\n }\n\n if (selectedIndex !== planRetirement.attachments.length) {\n throw new TypeError('Owner retirement selected an attachment outside its compiled scope instance.');\n }\n\n return Object.freeze(exact);\n}\n\nfunction createScopeRetirementScheduler(\n record: RetirementRecord,\n ownerRetirement: OwnerGenerationPlanRetirement,\n attachments: readonly AttachmentInstance[],\n): AttachmentRetirementScheduler {\n const retirements = ownerRetirement.retirement.retirements;\n\n if (retirements.length !== attachments.length) {\n throw new TypeError('Owner retirement lost alignment with the compiled attachment graph.');\n }\n\n return createAttachmentRetirementScheduler({\n attachments,\n onTerminal: () => clearActiveRetirement(record),\n retirements,\n retryAttachment: attachment => retryOwnerBoundAttachmentClose(attachment.bound),\n });\n}\n\nfunction settleOpeningAfterRetirement(record: RetirementRecord): void {\n const state = retirementState(record);\n\n void drainRetirement(record).then(\n drain => {\n const failure = state.failure;\n state.openingValue = undefined;\n\n if (failure === undefined) {\n state.resolveOpen(Object.freeze({ drain, kind: 'retired' as const, retirement: record.runtime }));\n } else {\n state.resolveOpen(\n Object.freeze({\n attachmentId: failure.attachment.id,\n attachmentSlot: failure.attachment.slot,\n drain,\n kind: 'not-ready' as const,\n outcome: failure.outcome,\n retirement: record.runtime,\n }),\n );\n }\n },\n (error: unknown) => state.rejectOpen(error),\n );\n}\n\nfunction prepareScopeRetirement(retirement: RetirementRecord): void {\n const scope = retirementScope(retirement);\n const state = retirementState(retirement);\n state.phase = 'fencing';\n state.openingValue = undefined;\n\n try {\n const planRetirement =\n retirement.ownerRetirement ??\n retirePlannedOwnerGeneration(\n scope.controller,\n state.generation,\n scope.attachmentInstances.map(attachment => attachment.bound),\n );\n const exactAttachments = exactAttachmentInstances(scope, planRetirement);\n retirement.ownerRetirement = planRetirement;\n retirement.scheduler = createScopeRetirementScheduler(retirement, planRetirement, exactAttachments);\n state.phase = 'retiring';\n retirement.resolvePrepared();\n } catch (error) {\n state.openingValue = undefined;\n state.phase = 'retiring';\n // A synchronous fence failure can make the handle unreachable before drain() observes preparation.\n void retirement.prepared?.catch(() => undefined);\n retirement.rejectPrepared(error);\n state.rejectOpen(error);\n throw error;\n }\n}\n\nfunction beginScopeRetirement(scope: ScopeInstanceRecord): RetirementRecord {\n const state = scope.active;\n\n if (state === undefined) throw new TypeError('Cannot retire an inactive local scope.');\n\n const existing = state.retirement;\n\n if (existing !== undefined) {\n if (existing.scheduler === undefined) {\n resetRetirementPreparation(existing);\n prepareScopeRetirement(existing);\n }\n\n return existing;\n }\n\n const wasOpening = state.phase === 'committing' || state.phase === 'opening';\n const retirement = createRetirementRecord(scope, state);\n state.retirement = retirement;\n\n if (wasOpening) settleOpeningAfterRetirement(retirement);\n\n prepareScopeRetirement(retirement);\n\n return retirement;\n}\n\nexport { beginScopeRetirement };\n"],"names":["closedDrainOutcome","workspaceRetirementRecord","record","ownerRetirement","retirementScope","scope","retirementState","state","clearActiveRetirement","acknowledgeOwnerGenerationDrain","attachment","preparedRetirementScheduler","scheduler","drainRetirement","prepared","retryRetirement","singleFlight","requireRetirementHandleRecord","requireExternallyCallableRetirementRecord","createRetirementRuntime","createRetirementRecord","rejectPrepared","_error","resolvePrepared","resolve","reject","handleState","resetRetirementPreparation","exactAttachmentInstances","planRetirement","exact","selectedIndex","createScopeRetirementScheduler","attachments","retirements","createAttachmentRetirementScheduler","retryOwnerBoundAttachmentClose","settleOpeningAfterRetirement","drain","failure","error","prepareScopeRetirement","retirement","retirePlannedOwnerGeneration","exactAttachments","_a","beginScopeRetirement","existing","wasOpening"],"mappings":"uRAkBA,MAAMA,EAAqB,OAAO,OAAO,CAAE,KAAM,QAAiB,CAAE,EAEpE,SAASC,EAA0BC,EAAwB,CACzD,MAAMC,EAAkBD,EAAO,gBAE/B,GAAIC,IAAoB,OAAW,MAAM,IAAI,UAAU,8CAA8C,EAErG,OAAOA,CACT,CAEA,SAASC,EAAgBF,EAAwB,CAC/C,MAAMG,EAAQH,EAAO,MAErB,GAAIG,IAAU,OAAW,MAAM,IAAI,UAAU,8CAA8C,EAE3F,OAAOA,CACT,CAEA,SAASC,EAAgBJ,EAAwB,CAC/C,MAAMK,EAAQL,EAAO,MAErB,GAAIK,IAAU,OAAW,MAAM,IAAI,UAAU,8CAA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AAuBC,EAA4B,OAC1D,MAAMrC,EAAQD,EAAgBsC,CAAU,EAClCnC,EAAQD,EAAgBoC,CAAU,EACxCnC,EAAM,MAAQ,UACdA,EAAM,aAAe,OAErB,GAAI,CACF,MAAMsB,EACJa,EAAW,iBACXC,EACEtC,EAAM,WACNE,EAAM,WACNF,EAAM,oBAAoB,IAAIK,GAAcA,EAAW,KAAK,CAAC,EAE3DkC,EAAmBhB,EAAyBvB,EAAOwB,CAAc,EACvEa,EAAW,gBAAkBb,EAC7Ba,EAAW,UAAYV,EAA+BU,EAAYb,EAAgBe,CAAgB,EAClGrC,EAAM,MAAQ,WACdmC,EAAW,gBAAe,CAC5B,OAASF,EAAO,CACd,MAAAjC,EAAM,aAAe,OACrBA,EAAM,MAAQ,YAETsC,EAAAH,EAAW,WAAX,MAAAG,EAAqB,MAAM,IAAA,IAChCH,EAAW,eAAeF,CAAK,EAC/BjC,EAAM,WAAWiC,CAAK,EAChBA,CACR,CACF,CAEA,SAASM,EAAqBzC,EAA0B,CACtD,MAAME,EAAQF,EAAM,OAEpB,GAAIE,IAAU,OAAW,MAAM,IAAI,UAAU,wCAAwC,EAErF,MAAMwC,EAAWxC,EAAM,WAEvB,GAAIwC,IAAa,OACf,OAAIA,EAAS,YAAc,SACzBpB,EAA2BoB,CAAQ,EACnCN,EAAuBM,CAAQ,GAG1BA,EAGT,MAAMC,EAAazC,EAAM,QAAU,cAAgBA,EAAM,QAAU,UAC7DmC,EAAatB,EAAuBf,EAAOE,CAAK,EACtD,OAAAA,EAAM,WAAamC,EAEfM,GAAYX,EAA6BK,CAAU,EAEvDD,EAAuBC,CAAU,EAE1BA,CACT"}
@@ -0,0 +1,59 @@
1
+ import type { DeclarationId } from '@opetope/core';
2
+ declare const attachmentTemplateSlotBrand: unique symbol;
3
+ declare const callTargetBindingSlotBrand: unique symbol;
4
+ declare const compiledModuleTemplateBrand: unique symbol;
5
+ declare const scopeAttachmentSlotBrand: unique symbol;
6
+ declare const scopeTemplateSlotBrand: unique symbol;
7
+ type AttachmentTemplateSlot = number & {
8
+ readonly [attachmentTemplateSlotBrand]: true;
9
+ };
10
+ type CallTargetBindingSlot = number & {
11
+ readonly [callTargetBindingSlotBrand]: true;
12
+ };
13
+ type ScopeAttachmentSlot = number & {
14
+ readonly [scopeAttachmentSlotBrand]: true;
15
+ };
16
+ type ScopeTemplateSlot = number & {
17
+ readonly [scopeTemplateSlotBrand]: true;
18
+ };
19
+ interface RuntimeNodeIdentityIR {
20
+ readonly id: DeclarationId;
21
+ readonly key: string;
22
+ readonly kind: 'attachment' | 'scope';
23
+ readonly moduleId: DeclarationId;
24
+ readonly stage: 'runtime';
25
+ }
26
+ interface AttachmentNodeIR {
27
+ readonly identity: RuntimeNodeIdentityIR & {
28
+ readonly kind: 'attachment';
29
+ };
30
+ readonly ownerScopeSlot: ScopeTemplateSlot;
31
+ readonly readiness: 'critical' | 'deferred';
32
+ readonly scopeAttachmentSlot: ScopeAttachmentSlot;
33
+ readonly slot: AttachmentTemplateSlot;
34
+ }
35
+ interface ScopeNodeIR {
36
+ readonly attachmentSlots: readonly AttachmentTemplateSlot[];
37
+ readonly criticalAttachmentSlots: readonly AttachmentTemplateSlot[];
38
+ readonly identity: RuntimeNodeIdentityIR & {
39
+ readonly kind: 'scope';
40
+ };
41
+ readonly slot: ScopeTemplateSlot;
42
+ }
43
+ interface CallTargetBindingIR {
44
+ readonly id: DeclarationId;
45
+ readonly key: string;
46
+ readonly kind: 'call-target-binding';
47
+ readonly moduleId: DeclarationId;
48
+ readonly slot: CallTargetBindingSlot;
49
+ readonly stage: 'runtime';
50
+ readonly withinAttachmentSlot: AttachmentTemplateSlot;
51
+ }
52
+ interface CompiledModuleTemplateIR {
53
+ readonly attachments: readonly AttachmentNodeIR[];
54
+ readonly callTargetBindings: readonly CallTargetBindingIR[];
55
+ readonly [compiledModuleTemplateBrand]: true;
56
+ readonly moduleId: DeclarationId;
57
+ readonly scopes: readonly ScopeNodeIR[];
58
+ }
59
+ export type { AttachmentNodeIR, AttachmentTemplateSlot, CallTargetBindingIR, CallTargetBindingSlot, CompiledModuleTemplateIR, RuntimeNodeIdentityIR, ScopeAttachmentSlot, ScopeNodeIR, ScopeTemplateSlot, };