dsh-context-compression-improved 0.10.4 → 0.10.5

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 (268) hide show
  1. package/$null +1 -0
  2. package/.agents/plans/improve/checklist.md +32 -0
  3. package/.agents/plans/improve/findings.md +102 -0
  4. package/.agents/plans/improve/spec.md +53 -0
  5. package/.agents/plans/improve/tasks.md +70 -0
  6. package/.gitattributes +2 -0
  7. package/.githooks/pre-push +37 -0
  8. package/.github/workflows/ci.yml +47 -0
  9. package/CHANGELOG.de.md +580 -0
  10. package/CHANGELOG.es.md +588 -0
  11. package/CHANGELOG.fr.md +576 -0
  12. package/CHANGELOG.it.md +577 -0
  13. package/CHANGELOG.ja.md +261 -0
  14. package/CHANGELOG.ko.md +254 -0
  15. package/CHANGELOG.md +549 -0
  16. package/CHANGELOG.ru.md +554 -0
  17. package/CHANGELOG.zh.md +238 -0
  18. package/CONTRIBUTING.md +22 -0
  19. package/README.de.md +96 -0
  20. package/README.es.md +96 -0
  21. package/README.fr.md +96 -0
  22. package/README.it.md +96 -0
  23. package/README.ja.md +102 -0
  24. package/README.ko.md +102 -0
  25. package/README.md +110 -15
  26. package/README.ru.md +96 -0
  27. package/README.zh.md +104 -14
  28. package/SECURITY.md +18 -0
  29. package/THIRD_PARTY_NOTICES.md +7 -25
  30. package/assets/board.png +0 -0
  31. package/assets/context.png +0 -0
  32. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  33. package/docs/assets/context-compression-selector-settings.png +0 -0
  34. package/docs/compat-0.1.5-report.md +77 -0
  35. package/docs/installation.de.md +104 -0
  36. package/docs/installation.es.md +104 -0
  37. package/docs/installation.fr.md +104 -0
  38. package/docs/installation.it.md +104 -0
  39. package/docs/installation.ja.md +78 -0
  40. package/docs/installation.ko.md +78 -0
  41. package/docs/installation.md +103 -0
  42. package/docs/installation.ru.md +104 -0
  43. package/docs/installation.zh.md +100 -0
  44. package/docs/repair-log.md +657 -0
  45. package/eslint.config.js +30 -0
  46. package/package.json +113 -126
  47. package/packages/selector/LICENSE +21 -0
  48. package/packages/selector/README.md +26 -0
  49. package/packages/selector/README.zh.md +24 -0
  50. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
  51. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
  52. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
  53. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
  54. package/packages/selector/lib/style.css +350 -0
  55. package/packages/selector/package.json +178 -0
  56. package/packages/selector/screenshots.json +3 -0
  57. package/packages/selector/src/client/CompressionProfileControls.tsx +319 -0
  58. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
  59. package/packages/selector/src/client/CompressionProfileSelector.tsx +87 -0
  60. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
  61. package/packages/selector/src/client/EstimatorControls.tsx +277 -0
  62. package/packages/selector/src/client/bridge-scope.ts +125 -0
  63. package/packages/selector/src/client/decode.ts +64 -0
  64. package/packages/selector/src/client/fab-pos.ts +71 -0
  65. package/packages/selector/src/client/index.ts +434 -0
  66. package/packages/selector/src/client/locales/de.ts +160 -0
  67. package/packages/selector/src/client/locales/es.ts +160 -0
  68. package/packages/selector/src/client/locales/fr.ts +160 -0
  69. package/packages/selector/src/client/locales/it.ts +160 -0
  70. package/packages/selector/src/client/locales/ja.ts +160 -0
  71. package/packages/selector/src/client/locales/ko.ts +160 -0
  72. package/packages/selector/src/client/locales/ru.ts +160 -0
  73. package/packages/selector/src/client/locales.ts +320 -0
  74. package/packages/selector/src/client/monitor-fab.ts +431 -0
  75. package/packages/selector/src/client/preset-options.ts +88 -0
  76. package/packages/selector/src/client/savings-card.tsx +269 -0
  77. package/packages/selector/src/client/scope-face.ts +24 -0
  78. package/packages/selector/src/client/settings-section.tsx +149 -0
  79. package/packages/selector/src/compat/host-generation.ts +96 -0
  80. package/packages/selector/src/compat/llm-messages.ts +50 -0
  81. package/packages/selector/src/compat/settings-lease.ts +108 -0
  82. package/packages/selector/src/compat/tool-result.ts +91 -0
  83. package/packages/selector/src/css-modules.d.ts +6 -0
  84. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
  85. package/packages/selector/src/estimator-catalog.ts +104 -0
  86. package/packages/selector/src/index.ts +890 -0
  87. package/packages/selector/src/invariant.ts +113 -0
  88. package/packages/selector/src/preset-overlay.ts +749 -0
  89. package/packages/selector/src/profiles.ts +451 -0
  90. package/packages/selector/src/pruner/content.ts +199 -0
  91. package/packages/selector/src/pruner/session.ts +97 -0
  92. package/packages/selector/src/pruner/state.ts +61 -0
  93. package/packages/selector/src/pruner/tuning.ts +23 -0
  94. package/packages/selector/src/pruner/types.ts +78 -0
  95. package/packages/selector/src/pruner.ts +2916 -0
  96. package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
  97. package/packages/selector/src/runtime/audit.ts +320 -0
  98. package/packages/selector/src/runtime/config.ts +800 -0
  99. package/packages/selector/src/runtime/custom-policy.ts +300 -0
  100. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
  101. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
  102. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  103. package/packages/selector/src/runtime/measurement.ts +444 -0
  104. package/packages/selector/src/runtime/monitor.ts +310 -0
  105. package/packages/selector/src/runtime/panel-command.ts +213 -0
  106. package/packages/selector/src/runtime/reducers.ts +1755 -0
  107. package/packages/selector/src/runtime/retrieve.ts +505 -0
  108. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  109. package/packages/selector/src/runtime/savings-projection.ts +229 -0
  110. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  111. package/packages/selector/src/runtime/savings.ts +526 -0
  112. package/packages/selector/src/runtime/session-events.ts +30 -0
  113. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  114. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  115. package/packages/selector/src/runtime/stats-db.ts +492 -0
  116. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  117. package/packages/selector/src/runtime/stats-sync.ts +307 -0
  118. package/packages/selector/src/runtime/summary-command.ts +127 -0
  119. package/packages/selector/src/runtime/tail-trim.ts +177 -0
  120. package/packages/selector/src/runtime/token-count.ts +72 -0
  121. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  122. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  123. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  124. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  125. package/packages/selector/src/runtime/tokenpilot/dedup.ts +82 -0
  126. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
  127. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  128. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  129. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  130. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  131. package/packages/selector/src/runtime/tokenpilot/locator.ts +129 -0
  132. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
  133. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  134. package/packages/selector/src/runtime/tool-names.ts +36 -0
  135. package/packages/selector/src/runtime/toolclass.ts +103 -0
  136. package/packages/selector/src/runtime/types.ts +368 -0
  137. package/packages/selector/src/runtime/value.ts +48 -0
  138. package/packages/selector/src/settings-bridge.ts +175 -0
  139. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  140. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
  141. package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
  142. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
  143. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
  144. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  145. package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
  146. package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
  147. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
  148. package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
  149. package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
  150. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
  151. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  154. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  155. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  156. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
  157. package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
  158. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
  159. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
  160. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
  161. package/packages/selector/tests/profiles.client.spec.tsx +436 -0
  162. package/packages/selector/tests/ptc-custom-write.client.spec.ts +86 -0
  163. package/packages/selector/tests/public/package-contract.client.spec.ts +86 -0
  164. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
  165. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
  166. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  167. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  168. package/packages/selector/tests/runtime/audit.spec.ts +275 -0
  169. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
  170. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  171. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
  172. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
  173. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
  174. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
  175. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  176. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
  177. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  178. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
  179. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
  180. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  181. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  182. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  183. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  184. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  185. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  186. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  187. package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
  188. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  189. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  190. package/packages/selector/tests/runtime/ptc-profile.spec.ts +133 -0
  191. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2795 -0
  192. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  193. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  194. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  195. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  196. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  197. package/packages/selector/tests/runtime/savings.spec.ts +139 -0
  198. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  199. package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
  200. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  201. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  202. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  203. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  204. package/packages/selector/tests/runtime/stats-backfill.spec.ts +350 -0
  205. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  206. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  207. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  208. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  209. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  210. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
  211. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  212. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
  213. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
  214. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
  215. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +121 -0
  216. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
  217. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  218. package/packages/selector/tests/runtime/value.spec.ts +23 -0
  219. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  220. package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
  221. package/packages/selector/tests/standing-generation.host.spec.ts +724 -0
  222. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
  223. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
  224. package/packages/selector/tests/support/mock-adapter.ts +37 -0
  225. package/packages/selector/tests/support/ui-primitives.tsx +34 -0
  226. package/packages/selector/tsconfig.json +11 -0
  227. package/packages/selector/tsdown.client.config.ts +102 -0
  228. package/packages/selector/tsdown.config.ts +20 -0
  229. package/pnpm-workspace.yaml +76 -0
  230. package/screenshots.json +6 -3
  231. package/scripts/capture-profile-baseline.mjs +42 -0
  232. package/scripts/cell-browser-e2e.mjs +354 -0
  233. package/scripts/generate-tokenizer-fixtures.py +81 -0
  234. package/scripts/generate-vision-fixtures.py +208 -0
  235. package/scripts/hosts.mjs +79 -0
  236. package/scripts/packed-components-smoke.mjs +763 -0
  237. package/scripts/packed-install-e2e.mjs +1346 -0
  238. package/scripts/sync-hosts.mjs +174 -0
  239. package/scripts/toolclass-corpus-replay.mjs +281 -0
  240. package/scripts/verify-release.mjs +338 -0
  241. package/tests/TEST_INVENTORY.md +41 -0
  242. package/tsconfig.base.json +18 -0
  243. package/tsconfig.json +7 -0
  244. package/tsconfig.tests.json +15 -0
  245. package/vitest.built.config.ts +9 -0
  246. package/vitest.config.ts +54 -0
  247. /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  248. /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
  249. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
  250. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
  251. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  252. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  253. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  254. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  255. /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
  256. /package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +0 -0
  257. /package/{lib → packages/selector/lib}/client.d.ts +0 -0
  258. /package/{lib → packages/selector/lib}/client.js +0 -0
  259. /package/{lib → packages/selector/lib}/index.d.ts +0 -0
  260. /package/{lib → packages/selector/lib}/index.js +0 -0
  261. /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
  262. /package/{lib → packages/selector/lib}/invariant.js +0 -0
  263. /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
  264. /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
  265. /package/{lib → packages/selector/lib}/pruner.js +0 -0
  266. /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
  267. /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
  268. /package/{lib → packages/selector/lib}/tool-result.js +0 -0
@@ -0,0 +1,647 @@
1
+ /* Vendored verbatim from @deepseek-ai/<pkg> — third-party code, exempt from this repo's lint rules. */
2
+ /* eslint-disable */
3
+ /**
4
+ * Service Definition for the user-settings capability seam (`ctx.settings`). Providers store one raw document of
5
+ * per-namespace sections; plugins register a namespace schema and read the
6
+ * resolved value, which layers schema defaults, the registrant's composition
7
+ * `base`, and the user document section, in that order.
8
+ * @module @deepseek-ai/dsh-settings
9
+ */
10
+ import { Service } from '@deepseek-ai/cordis';
11
+ import { deepEqualJson, deepFreeze } from './util-values.js';
12
+ import { redactSecrets } from "./redact.js";
13
+ export { redactSecrets } from "./redact.js";
14
+ const NAMESPACE_PATTERN = /^[a-z][a-z0-9-]*$/;
15
+ function parseSettingsNamespace(value) {
16
+ if (!NAMESPACE_PATTERN.test(value)) {
17
+ throw new TypeError(`settings namespace "${value}" must match ${String(NAMESPACE_PATTERN)}`);
18
+ }
19
+ return value;
20
+ }
21
+ /**
22
+ * A write refused because the namespace moved since the caller read it. The
23
+ * Service Definition's serialized write queue orders writes; it cannot tell a fresh writer
24
+ * from one holding a stale snapshot, which is what this reports.
25
+ */
26
+ export class SettingsConflictError extends Error {
27
+ /** Stable machine code for wire layers mapping this to their own taxonomy. */
28
+ code = 'SETTINGS_CONFLICT';
29
+ /** The revision the write expected. */
30
+ expected;
31
+ /** The revision the namespace actually stands at. */
32
+ actual;
33
+ /**
34
+ * @param ns - the namespace whose write was refused.
35
+ * @param expected - the revision the caller sent.
36
+ * @param actual - the revision now stored.
37
+ */
38
+ constructor(ns, expected, actual) {
39
+ super(`settings namespace "${ns}" changed since it was read (expected revision ${String(expected)}, now ${String(actual)})`);
40
+ this.name = 'SettingsConflictError';
41
+ this.expected = expected;
42
+ this.actual = actual;
43
+ }
44
+ }
45
+ /** Whether a value is a plain data object (not an array, null, or class instance). */
46
+ function isPlainObject(value) {
47
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
48
+ return false;
49
+ const proto = Object.getPrototypeOf(value);
50
+ return proto === Object.prototype || proto === null;
51
+ }
52
+ /** Apply one path op to a detached section, returning the next section. */
53
+ function applyPathOp(section, op) {
54
+ const [head, ...rest] = op.path;
55
+ // The empty path addresses the section itself.
56
+ if (head === undefined) {
57
+ if (op.op === 'unset')
58
+ return {};
59
+ if (!isPlainObject(op.value)) {
60
+ throw new TypeError('settings mutate: setting the section root requires a plain object');
61
+ }
62
+ return { ...op.value };
63
+ }
64
+ if (rest.length === 0) {
65
+ if (op.op === 'set')
66
+ return { ...section, [head]: op.value };
67
+ const { [head]: _removed, ...kept } = section;
68
+ return kept;
69
+ }
70
+ const child = section[head];
71
+ if (!isPlainObject(child)) {
72
+ // Unsetting through an absent path is already satisfied; setting through
73
+ // one creates the intermediate objects it needs.
74
+ if (op.op === 'unset')
75
+ return section;
76
+ return { ...section, [head]: applyPathOp({}, { ...op, path: rest }) };
77
+ }
78
+ return { ...section, [head]: applyPathOp(child, { ...op, path: rest }) };
79
+ }
80
+ /** Human label for a value that lossless JSON cannot represent (numbers reject inline). */
81
+ function describeRejected(value) {
82
+ if (value === undefined)
83
+ return 'undefined';
84
+ if (typeof value === 'object' && value !== null) {
85
+ const proto = Object.getPrototypeOf(value);
86
+ const name = proto?.constructor?.name;
87
+ return name === undefined || name === 'Object' ? 'a non-plain object' : `a ${name}`;
88
+ }
89
+ return `a ${typeof value}`;
90
+ }
91
+ /**
92
+ * Detach and validate one write input in a single walk before persistence:
93
+ * only JSON data (plain objects, arrays, strings, finite numbers,
94
+ * booleans, `null`) may reach a provider document. `structuredClone` alone
95
+ * would admit Dates, Maps, BigInts, and cycles that YAML/JSON storage then
96
+ * silently distorts on the reload round-trip. `undefined` entries in objects
97
+ * are skipped — the same sparse-patch semantics as {@link mergeLayers} — while
98
+ * an `undefined` array entry is rejected rather than coerced.
99
+ * @param root - plain-object write input (caller-checked).
100
+ * @param reject - builds the validation error from a value label and its `$`-rooted path.
101
+ * @returns the detached JSON-compatible clone.
102
+ */
103
+ function cloneJsonShaped(root, reject) {
104
+ const visiting = new WeakSet();
105
+ const clone = (value, path) => {
106
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
107
+ return value;
108
+ if (typeof value === 'number') {
109
+ if (!Number.isFinite(value))
110
+ throw reject('a non-finite number', path);
111
+ return value;
112
+ }
113
+ if (Array.isArray(value)) {
114
+ if (visiting.has(value))
115
+ throw reject('a circular reference', path);
116
+ visiting.add(value);
117
+ const entries = value.map((entry, index) => clone(entry, `${path}[${index}]`));
118
+ // Un-mark on exit so one object referenced twice without a cycle passes.
119
+ visiting.delete(value);
120
+ return entries;
121
+ }
122
+ if (isPlainObject(value)) {
123
+ if (visiting.has(value))
124
+ throw reject('a circular reference', path);
125
+ visiting.add(value);
126
+ // TODO(settings-json-properties): Use property-safe construction here and
127
+ // in mergeLayers so valid JSON keys such as "__proto__" remain own data.
128
+ const out = {};
129
+ for (const [key, entry] of Object.entries(value)) {
130
+ if (entry === undefined)
131
+ continue;
132
+ out[key] = clone(entry, `${path}.${key}`);
133
+ }
134
+ visiting.delete(value);
135
+ return out;
136
+ }
137
+ throw reject(describeRejected(value), path);
138
+ };
139
+ return clone(root, '$');
140
+ }
141
+ /**
142
+ * Layer `over` onto `under`: plain objects merge recursively, every other
143
+ * value (arrays included) replaces the lower layer wholesale. `over` never
144
+ * carries `undefined` entries — sections come from parsed documents and write
145
+ * snapshots pass {@link cloneJsonShaped}, which strips them so a sparse patch
146
+ * cannot erase lower keys.
147
+ */
148
+ function mergeLayers(under, over) {
149
+ if (over === undefined)
150
+ return under;
151
+ if (!isPlainObject(under) || !isPlainObject(over))
152
+ return over;
153
+ const merged = { ...under };
154
+ for (const [key, value] of Object.entries(over)) {
155
+ merged[key] = key in merged ? mergeLayers(merged[key], value) : value;
156
+ }
157
+ return merged;
158
+ }
159
+ /**
160
+ * Abstract settings service. Providers implement raw-document storage
161
+ * (`load`/`persist`) and push external changes through {@link Settings.publish};
162
+ * the base class owns namespace registration, resolution, validation, change
163
+ * detection, and the `settings/updated` commit event.
164
+ */
165
+ export class SettingsProvider extends Service {
166
+ registrations = new Map();
167
+ /** Latest published raw document; empty until the provider's first publish. */
168
+ document = {};
169
+ /** Per-namespace write chains; settled tails, so a failure never poisons the queue. */
170
+ writeQueues = new Map();
171
+ /** In-flight watcher invocation segments, drained by the dispose teardown. */
172
+ pendingTails = new Set();
173
+ /** Set at service dispose: refuse new writes while queued ones drain. */
174
+ stopped = false;
175
+ /** Opaque read of {@link stopped}: control flow cannot narrow it across awaits. */
176
+ isStopped() {
177
+ return this.stopped;
178
+ }
179
+ constructor(ctx) {
180
+ super(ctx, 'settings');
181
+ }
182
+ /**
183
+ * Load the provider's document once and publish it before the service
184
+ * becomes injectable, and register the write-drain teardown. Providers with
185
+ * their own init (watchers, connections) delegate here first via
186
+ * `yield* super[Service.init]()`; their disposers then run before the drain.
187
+ */
188
+ async *[Service.init]() {
189
+ yield async () => {
190
+ // Teardown: refuse new writes and new watcher starts, then wait until
191
+ // every queued write chain and every started watcher invocation settles
192
+ // so disposal completes only once storage and observers are quiescent.
193
+ // Invocations queued but not yet started skip via the stopped check.
194
+ this.stopped = true;
195
+ await Promise.allSettled([...this.writeQueues.values(), ...this.pendingTails]);
196
+ };
197
+ this.publish(await this.load());
198
+ }
199
+ /**
200
+ * Absolute path of the provider's user-editable document, when its storage
201
+ * is one local file. Configuration surfaces use this only as availability
202
+ * metadata; the guarded open operation resolves the path again Host-side.
203
+ * Non-file providers leave it undefined and expose no open-document affordance.
204
+ * @returns the absolute local document path, or undefined for non-file storage.
205
+ */
206
+ get documentPath() {
207
+ return undefined;
208
+ }
209
+ /**
210
+ * Prepare the provider's user-editable document for a native editor. File
211
+ * providers may materialize an absent document before returning its path;
212
+ * non-file providers return undefined.
213
+ * @returns the absolute local document path, or undefined for non-file storage.
214
+ */
215
+ prepareDocument() {
216
+ return Promise.resolve(this.documentPath);
217
+ }
218
+ /**
219
+ * Register a namespace schema and receive its owner scope. The registration
220
+ * is an effect on the calling plugin's fiber: disposing that fiber removes
221
+ * the namespace and its observers. An invalid stored section fails the
222
+ * registration itself — the earliest point where the schema can judge it.
223
+ * @param ns - unique namespace; duplicate registration fails loud.
224
+ * @param schema - schemastery schema resolving this namespace's value.
225
+ * @param options - composition `base` layer and effect timing.
226
+ * @returns the owner scope for reads, observation, and updates.
227
+ * @throws {TypeError} when `ns` is not a lowercase hyphenated identifier.
228
+ */
229
+ register(ns, schema, options) {
230
+ const parsedNs = parseSettingsNamespace(ns);
231
+ if (this.registrations.has(parsedNs)) {
232
+ throw new Error(`settings namespace "${parsedNs}" is already registered`);
233
+ }
234
+ const registration = {
235
+ ns: parsedNs,
236
+ schema: schema,
237
+ base: options?.base,
238
+ applies: options?.applies ?? 'live',
239
+ ...options?.validate === undefined
240
+ ? {}
241
+ : { validate: options.validate },
242
+ resolved: deepFreeze(this.resolve(schema, options?.base, this.section(parsedNs), options?.validate)),
243
+ revision: 0,
244
+ watchers: new Set(),
245
+ };
246
+ this.ctx.effect(() => {
247
+ this.registrations.set(parsedNs, registration);
248
+ // TODO(settings-registration-quiescence): Deactivate every watcher and await
249
+ // its tail on disposal so callbacks cannot outlive the registrant fiber.
250
+ return () => this.registrations.delete(parsedNs);
251
+ }, `settings.register(${JSON.stringify(String(parsedNs))})`);
252
+ return {
253
+ get: () => registration.resolved,
254
+ watch: (callback) => {
255
+ const watcher = { callback: callback, tail: Promise.resolve(), active: true };
256
+ registration.watchers.add(watcher);
257
+ return () => {
258
+ watcher.active = false;
259
+ registration.watchers.delete(watcher);
260
+ };
261
+ },
262
+ update: patch => this.update(parsedNs, patch),
263
+ replace: section => this.replace(parsedNs, section),
264
+ };
265
+ }
266
+ /**
267
+ * Attach one optional-settings consumer to this provider. The consumer
268
+ * registers its composition entry as the base layer while this provider is
269
+ * present, then falls back to that entry if the provider detaches.
270
+ * @param owner - consumer context whose unload suppresses fallback work.
271
+ * @param ns - consumer-owned settings namespace.
272
+ * @param schema - schema resolving the namespace.
273
+ * @param entry - composition entry used as the base and fallback value.
274
+ * @param hooks - source sink, change notification, and optional validation.
275
+ * @throws {TypeError} when `ns` is not a lowercase hyphenated identifier.
276
+ */
277
+ installSection(owner, ns, schema, entry, hooks) {
278
+ const scope = this.register(ns, schema, {
279
+ base: entry,
280
+ ...hooks.validate === undefined ? {} : { validate: hooks.validate },
281
+ });
282
+ hooks.setSource(() => scope.get());
283
+ this.ctx.effect(() => () => {
284
+ // Losing the provider leaves the consumer running; unloading the
285
+ // consumer does not, so only the former needs fallback work.
286
+ if (isUnloading(owner))
287
+ return;
288
+ hooks.setSource(() => entry);
289
+ hooks.onChange();
290
+ });
291
+ hooks.onChange();
292
+ scope.watch(() => {
293
+ if (isUnloading(owner))
294
+ return;
295
+ hooks.onChange();
296
+ });
297
+ }
298
+ /**
299
+ * Describe every registered namespace for configuration surfaces, including
300
+ * the composition `base` and raw user layers so a form can mark which fields
301
+ * the user overrode (presence in `user`) and what a reset returns to.
302
+ * @param options - redaction switch; wire surfaces must redact.
303
+ * @returns one descriptor per registered namespace, in registration order.
304
+ */
305
+ describe(options) {
306
+ return [...this.registrations.values()].map((registration) => {
307
+ let user;
308
+ try {
309
+ user = this.section(registration.ns);
310
+ }
311
+ catch {
312
+ // A malformed stored section already warned at publish and kept the
313
+ // last good resolved value; only that malformed shape can throw here,
314
+ // and describing it as "no user layer" keeps this read total.
315
+ user = undefined;
316
+ }
317
+ const base = registration.base === undefined ? undefined : structuredClone(registration.base);
318
+ const detachedUser = user === undefined ? undefined : structuredClone(user);
319
+ const descriptor = {
320
+ ns: registration.ns,
321
+ schema: registration.schema.toJSON(),
322
+ value: registration.resolved,
323
+ revision: registration.revision,
324
+ ...base === undefined ? {} : { base },
325
+ ...detachedUser === undefined ? {} : { user: detachedUser },
326
+ applies: registration.applies,
327
+ };
328
+ if (options?.redactSecrets !== true)
329
+ return descriptor;
330
+ const schema = registration.schema;
331
+ const redacted = redactSecrets(schema, registration.resolved);
332
+ return {
333
+ ...descriptor,
334
+ value: redacted.value,
335
+ ...base === undefined ? {} : { base: redactSecrets(schema, base).value },
336
+ ...detachedUser === undefined ? {} : { user: redactSecrets(schema, detachedUser).value },
337
+ secrets: redacted.secrets,
338
+ };
339
+ });
340
+ }
341
+ /**
342
+ * Read one registered namespace's resolved value.
343
+ * @param ns - the namespace to read.
344
+ * @returns the resolved value, or `undefined` while unregistered.
345
+ * @throws {TypeError} when `ns` is not a lowercase hyphenated identifier.
346
+ */
347
+ get(ns) {
348
+ return this.registrations.get(parseSettingsNamespace(ns))?.resolved;
349
+ }
350
+ /**
351
+ * Merge a patch into one registered namespace's user layer, validate the
352
+ * resolved candidate, persist through the provider, then commit and emit.
353
+ * A validation failure rejects before anything is persisted. Writes to one
354
+ * namespace are serialized: concurrent updates apply in call order, each
355
+ * merging over the previous write's committed section.
356
+ * @param ns - the registered namespace to update.
357
+ * @param patch - plain-object patch over the user section.
358
+ * @param expectedRevision - the descriptor `revision` the caller read; a
359
+ * namespace that moved past it rejects with {@link SettingsConflictError}.
360
+ * @throws {TypeError} when `ns` is not a lowercase hyphenated identifier.
361
+ */
362
+ async update(ns, patch, expectedRevision) {
363
+ return this.write(parseSettingsNamespace(ns), patch, 'merge', expectedRevision);
364
+ }
365
+ /**
366
+ * Replace one registered namespace's user section wholesale, validate,
367
+ * persist, then commit and emit. Keys absent from `section` fall back to the
368
+ * composition `base` and schema defaults — this is the removal/reset path a
369
+ * merge-only patch cannot express (`replace({})` re-inherits everything).
370
+ * @param ns - the registered namespace to replace.
371
+ * @param section - the complete next user section.
372
+ * @param expectedRevision - the descriptor `revision` the caller read; a
373
+ * namespace that moved past it rejects with {@link SettingsConflictError}.
374
+ * @throws {TypeError} when `ns` is not a lowercase hyphenated identifier.
375
+ */
376
+ async replace(ns, section, expectedRevision) {
377
+ return this.write(parseSettingsNamespace(ns), section, 'replace', expectedRevision);
378
+ }
379
+ /**
380
+ * Apply path-addressed edits to one registered namespace's user section,
381
+ * validate, persist, then commit and emit. The ops are applied to the
382
+ * section as it stands when the write reaches the front of the queue, so a
383
+ * caller never has to restate fields it did not touch — and, crucially,
384
+ * cannot delete fields it never saw. This is the write path for any caller
385
+ * holding a redacted view; `replace` remains the wholesale reset.
386
+ * @param ns - the registered namespace to edit.
387
+ * @param ops - ordered path edits; later ops observe earlier ones.
388
+ * @param expectedRevision - the descriptor `revision` the caller read; a
389
+ * namespace that moved past it rejects with {@link SettingsConflictError}.
390
+ * @throws {TypeError} when `ns` is not a lowercase hyphenated identifier.
391
+ */
392
+ async mutate(ns, ops, expectedRevision) {
393
+ const parsedNs = parseSettingsNamespace(ns);
394
+ if (!Array.isArray(ops))
395
+ throw new TypeError(`settings mutate for "${parsedNs}" must be an array of path ops`);
396
+ for (const op of ops) {
397
+ if (!isPlainObject(op) || (op['op'] !== 'set' && op['op'] !== 'unset')) {
398
+ throw new TypeError(`settings mutate for "${parsedNs}" ops must be {op:'set'|'unset', path}`);
399
+ }
400
+ if (!Array.isArray(op['path']) || op['path'].some(part => typeof part !== 'string')) {
401
+ throw new TypeError(`settings mutate for "${parsedNs}" op paths must be arrays of strings`);
402
+ }
403
+ }
404
+ return this.write(parsedNs, ops, 'mutate', expectedRevision);
405
+ }
406
+ /** Validate a write, then queue it on the namespace's serialized write chain. */
407
+ write(ns, input, mode, expectedRevision) {
408
+ const verb = mode === 'merge' ? 'update' : mode === 'replace' ? 'replace' : 'mutate';
409
+ const registration = this.registrations.get(ns);
410
+ if (registration === undefined) {
411
+ throw new Error(`settings namespace "${ns}" is not registered`);
412
+ }
413
+ if (this.isStopped()) {
414
+ throw new Error(`settings service is disposed: "${ns}" cannot be written`);
415
+ }
416
+ if (!this.writable) {
417
+ throw new Error(`settings provider is read-only: "${ns}" cannot be updated in-process`);
418
+ }
419
+ // A mutate's ops array is wrapped so one JSON-shape walk covers both
420
+ // shapes; merge/replace carry the section itself.
421
+ let payload;
422
+ if (mode === 'mutate') {
423
+ payload = { ops: input };
424
+ }
425
+ else {
426
+ if (!isPlainObject(input))
427
+ throw new TypeError(`settings ${verb} for "${ns}" must be a plain object`);
428
+ payload = input;
429
+ }
430
+ // Snapshot at call time: the queue must never read a caller-owned object
431
+ // the caller may keep mutating while the write waits its turn. The same
432
+ // walk rejects values that JSON cannot preserve (see cloneJsonShaped).
433
+ const snapshot = cloneJsonShaped(payload, (label, path) => new TypeError(`settings ${verb} for "${ns}" must contain only JSON-compatible data (found ${label} at ${path})`));
434
+ const previous = this.writeQueues.get(ns) ?? Promise.resolve();
435
+ // Chain past a failed predecessor: one rejected write must not poison the
436
+ // namespace queue for every later caller.
437
+ const run = previous.catch(() => undefined).then(async () => {
438
+ if (this.isStopped()) {
439
+ throw new Error(`settings service was disposed before the queued "${ns}" ${verb} ran`);
440
+ }
441
+ if (this.registrations.get(ns) !== registration) {
442
+ throw new Error(`settings namespace "${ns}" registration was disposed before the queued ${verb} ran`);
443
+ }
444
+ // Every mode derives from the section as it stands NOW, at the front of
445
+ // the queue — never from whatever the caller last saw.
446
+ const current = this.section(ns) ?? {};
447
+ // The revision check belongs HERE, not at call time: the queue orders
448
+ // writes but cannot tell a fresh writer from one holding a snapshot
449
+ // that a predecessor already superseded.
450
+ if (expectedRevision !== undefined && expectedRevision !== registration.revision) {
451
+ throw new SettingsConflictError(ns, expectedRevision, registration.revision);
452
+ }
453
+ const section = mode === 'merge'
454
+ ? mergeLayers(current, snapshot)
455
+ : mode === 'replace'
456
+ ? snapshot
457
+ : snapshot['ops'].reduce(applyPathOp, current);
458
+ const next = deepFreeze(this.resolve(registration.schema, registration.base, section, registration.validate));
459
+ await this.persist(ns, section);
460
+ // The write reached storage either way; the cache must say so. Commit
461
+ // only when this registration is still the namespace owner — a fiber
462
+ // disposed (or replaced) mid-persist must not receive the notification.
463
+ this.document[ns] = section;
464
+ // TODO(settings-replacement-resync): Re-resolve any replacement registration
465
+ // from this persisted section so an old in-flight write cannot leave it stale.
466
+ if (this.registrations.get(ns) === registration && !this.isStopped()) {
467
+ this.bumpRevision(registration, current, section);
468
+ this.commit(registration, next, 'update');
469
+ }
470
+ });
471
+ this.writeQueues.set(ns, run);
472
+ return run;
473
+ }
474
+ /**
475
+ * Provider hook: commit a complete raw document observed in storage. Each
476
+ * registered namespace re-resolves; an invalid section keeps that
477
+ * namespace's last good value and warns, other namespaces still commit.
478
+ * @param doc - the detached raw document (unregistered sections preserved).
479
+ * @param source - change origin; defaults to `provider`.
480
+ */
481
+ publish(doc, source = 'provider') {
482
+ // Read every raw section BEFORE swapping the document, so the revision
483
+ // bump below compares what was stored with what now is — an external edit
484
+ // moves the revision exactly like an in-process write.
485
+ const before = new Map();
486
+ for (const registration of this.registrations.values()) {
487
+ try {
488
+ before.set(registration.ns, this.section(registration.ns));
489
+ }
490
+ catch {
491
+ // A malformed stored section is not a readable "before"; treating it
492
+ // as absent still bumps against any well-formed replacement.
493
+ before.set(registration.ns, undefined);
494
+ }
495
+ }
496
+ this.document = doc;
497
+ for (const registration of this.registrations.values()) {
498
+ let next;
499
+ try {
500
+ next = deepFreeze(this.resolve(registration.schema, registration.base, this.section(registration.ns), registration.validate));
501
+ }
502
+ catch (error) {
503
+ this.ctx.logger.warn('settings: keeping last good "%s" after invalid stored section', registration.ns);
504
+ this.ctx.logger.warn(error);
505
+ continue;
506
+ }
507
+ this.bumpRevision(registration, before.get(registration.ns), this.section(registration.ns));
508
+ this.commit(registration, next, source);
509
+ }
510
+ }
511
+ /** Read one namespace's raw user section, rejecting non-object sections. */
512
+ section(ns) {
513
+ const section = this.document[ns];
514
+ if (section === undefined)
515
+ return undefined;
516
+ if (!isPlainObject(section)) {
517
+ throw new TypeError(`settings section "${ns}" must be an object of keys`);
518
+ }
519
+ return section;
520
+ }
521
+ /** Resolve one namespace value: schema defaults, then `base`, then the user layer. */
522
+ resolve(schema, base, section, validate) {
523
+ // The merged candidate is untyped by construction; the schema call is the
524
+ // runtime validation that admits it into T.
525
+ const value = schema(mergeLayers(base, section));
526
+ // The owner's own check runs on the admitted value, so it sees defaults
527
+ // and the composition base exactly as the owner will.
528
+ validate?.(value);
529
+ return value;
530
+ }
531
+ /**
532
+ * Advance a namespace's revision when its RAW section changed, and announce
533
+ * it. Deliberately independent of {@link commit}'s resolved-value equality:
534
+ * storing an override equal to the composition base leaves the resolved
535
+ * value alone but changes what the document says, which is exactly what a
536
+ * configuration surface must re-read.
537
+ */
538
+ bumpRevision(registration, before, after) {
539
+ if (deepEqualJson(before, after))
540
+ return;
541
+ registration.revision += 1;
542
+ this.emitDocumentUpdated(registration.ns, registration.revision);
543
+ }
544
+ /** Contained fan-out of `settings/document-updated`, mirroring {@link commit}'s. */
545
+ emitDocumentUpdated(ns, revision) {
546
+ let invariantFailure;
547
+ const args = ['settings/document-updated', ns, revision];
548
+ for (const listener of this.ctx.events.dispatch('emit', args)) {
549
+ try {
550
+ const returned = listener(ns, revision);
551
+ if (returned != null && typeof returned.then === 'function') {
552
+ void Promise.resolve(returned).then(undefined, (error) => {
553
+ this.warnListenerFailure(ns, error);
554
+ });
555
+ }
556
+ }
557
+ catch (error) {
558
+ if (error?.code === 'INVARIANT') {
559
+ invariantFailure ??= error;
560
+ continue;
561
+ }
562
+ this.warnListenerFailure(ns, error);
563
+ }
564
+ }
565
+ if (invariantFailure !== undefined)
566
+ throw invariantFailure;
567
+ }
568
+ /** Commit a resolved value when changed: swap, notify watchers, emit the event. */
569
+ commit(registration, next, source) {
570
+ const prev = registration.resolved;
571
+ if (deepEqualJson(next, prev))
572
+ return;
573
+ registration.resolved = next;
574
+ for (const watcher of [...registration.watchers]) {
575
+ // Serialize per watcher: invocations of one callback run one at a time
576
+ // in commit order, so a slow stale invocation can never apply after a
577
+ // newer one. Sync throws and async rejections land in the same handler.
578
+ // The activity check runs when the queued invocation would start, so a
579
+ // disposer (or service stop) that ran while it waited prevents the
580
+ // start entirely; started invocations drain at service dispose.
581
+ const segment = watcher.tail
582
+ .then(() => {
583
+ if (!watcher.active || this.isStopped())
584
+ return;
585
+ return watcher.callback(next, prev);
586
+ })
587
+ .then(() => undefined, (error) => {
588
+ this.warnWatcherFailure(registration.ns, error);
589
+ });
590
+ watcher.tail = segment;
591
+ this.pendingTails.add(segment);
592
+ void segment.then(() => this.pendingTails.delete(segment));
593
+ }
594
+ // Fan the event out one listener at a time (the plain emit stops at the
595
+ // first throwing listener, starving the rest). Invariant violations are
596
+ // harness-fatal by design and rethrow after every listener ran; any other
597
+ // failure is contained so one broken observer cannot wedge the commit
598
+ // path (and, through it, a provider's reload loop).
599
+ let invariantFailure;
600
+ const args = ['settings/updated', registration.ns, next, prev, source];
601
+ for (const listener of this.ctx.events.dispatch('emit', args)) {
602
+ try {
603
+ const returned = listener(registration.ns, next, prev, source);
604
+ if (returned != null && typeof returned.then === 'function') {
605
+ // An emit listener may still be an async function; its rejection
606
+ // cannot reach the synchronous INVARIANT rethrow below, so it is
607
+ // contained here instead of becoming an unhandled rejection.
608
+ void Promise.resolve(returned).then(undefined, (error) => {
609
+ this.warnListenerFailure(registration.ns, error);
610
+ });
611
+ }
612
+ }
613
+ catch (error) {
614
+ if (error?.code === 'INVARIANT') {
615
+ invariantFailure ??= error;
616
+ continue;
617
+ }
618
+ this.warnListenerFailure(registration.ns, error);
619
+ }
620
+ }
621
+ if (invariantFailure !== undefined)
622
+ throw invariantFailure;
623
+ }
624
+ /** Contained-watcher diagnostic shared by the sync and async failure paths. */
625
+ warnWatcherFailure(ns, error) {
626
+ this.ctx.logger.warn('settings: watcher for "%s" failed', ns);
627
+ this.ctx.logger.warn(error);
628
+ }
629
+ /** Contained-listener diagnostic shared by the sync and async failure paths. */
630
+ warnListenerFailure(ns, error) {
631
+ this.ctx.logger.warn('settings: a settings/updated listener for "%s" failed', ns);
632
+ this.ctx.logger.warn(error);
633
+ }
634
+ }
635
+ /**
636
+ * Value mirror of the `FiberState` members {@link isUnloading} compares
637
+ * against: a const enum has no runtime object to import, and the value is
638
+ * needed at runtime (same rationale as the CLI boot driver's mirror).
639
+ */
640
+ const FIBER_DISPOSED = 4;
641
+ const FIBER_UNLOADING = 5;
642
+ /** Whether the consumer's own fiber is tearing down (not just losing the settings service). */
643
+ function isUnloading(ctx) {
644
+ const state = ctx.fiber.state;
645
+ return state === FIBER_UNLOADING || state === FIBER_DISPOSED;
646
+ }
647
+ export default SettingsProvider;