@twinsearth/fang-dsh-plugin 0.0.0-stage → 3.3.4

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 (144) hide show
  1. package/CLA.md +79 -0
  2. package/LICENSE-COMMERCIAL +78 -0
  3. package/LICENSE-CORE +661 -0
  4. package/LICENSE-SDK +21 -0
  5. package/LICENSES/cordis-MIT.txt +39 -0
  6. package/NOTICE +95 -0
  7. package/README.md +158 -2
  8. package/client.js +7287 -0
  9. package/cordis.patch.yml +163 -0
  10. package/defaults/umbrella-rules.yaml +113 -0
  11. package/docs/CONTRACT-INTEROP.md +77 -0
  12. package/docs/CRASH-SAFETY.md +69 -0
  13. package/docs/DECISION-RELAY.md +46 -0
  14. package/docs/DSH-ARCHITECTURE-MAP.md +73 -0
  15. package/docs/FORK-SEED.md +64 -0
  16. package/docs/MAIN-CITY-GATE.md +58 -0
  17. package/docs/OVERLAY-MASTER-SWITCH.md +35 -0
  18. package/docs/PACKAGE-RENAME-v3.3.3.md +40 -0
  19. package/docs/PM-DECISION-POLICY.md +61 -0
  20. package/docs/WORKFLOW-UI.md +86 -0
  21. package/icon.svg +8 -0
  22. package/locale/en.json +6 -0
  23. package/locale/zh.json +6 -0
  24. package/package.json +71 -4
  25. package/sdk/README.md +65 -0
  26. package/sdk/examples/status-badge/README.md +16 -0
  27. package/sdk/examples/status-badge/client.js +60 -0
  28. package/sdk/examples/status-badge/cordis.patch.yml +7 -0
  29. package/sdk/examples/status-badge/index.js +12 -0
  30. package/sdk/examples/status-badge/package.json +24 -0
  31. package/sdk/templates/plugin/README.md +36 -0
  32. package/sdk/templates/plugin/client.js +35 -0
  33. package/sdk/templates/plugin/cordis.patch.yml +8 -0
  34. package/sdk/templates/plugin/icon.svg +5 -0
  35. package/sdk/templates/plugin/index.js +23 -0
  36. package/sdk/templates/plugin/locale/en.json +6 -0
  37. package/sdk/templates/plugin/package.json +36 -0
  38. package/src/compose.mjs +67 -0
  39. package/src/contract/VENDOR.json +16 -0
  40. package/src/contract/client.js +93 -0
  41. package/src/contract/constants.js +94 -0
  42. package/src/contract/envelope.js +83 -0
  43. package/src/contract/index.js +20 -0
  44. package/src/contract/negotiate.js +106 -0
  45. package/src/contract/relay.js +223 -0
  46. package/src/contract/server.js +77 -0
  47. package/src/contract/transports.js +319 -0
  48. package/src/index.mjs +11 -0
  49. package/src/kernel/core.mjs +100 -0
  50. package/src/kernel/extensions.mjs +61 -0
  51. package/src/kernel/fsx.mjs +349 -0
  52. package/src/kernel/index.mjs +21 -0
  53. package/src/kernel/ledger.mjs +94 -0
  54. package/src/kernel/paths.mjs +182 -0
  55. package/src/kernel/role.mjs +68 -0
  56. package/src/kernel/rounds.mjs +172 -0
  57. package/src/kernel/schema.mjs +5 -0
  58. package/src/kernel/types.mjs +266 -0
  59. package/src/kernel/vendor/cosmokit.mjs +421 -0
  60. package/src/kernel/vendor/schemastery.mjs +638 -0
  61. package/src/lib/adapter-client.mjs +383 -0
  62. package/src/lib/adapter-protocol.mjs +243 -0
  63. package/src/lib/ai-secret-store.mjs +202 -0
  64. package/src/lib/boot-guard.mjs +186 -0
  65. package/src/lib/branch-store.mjs +84 -0
  66. package/src/lib/branch.mjs +74 -0
  67. package/src/lib/bridge-client.mjs +133 -0
  68. package/src/lib/broker-adapter.mjs +67 -0
  69. package/src/lib/broker.mjs +45 -0
  70. package/src/lib/business-producers.mjs +109 -0
  71. package/src/lib/command-cache.mjs +209 -0
  72. package/src/lib/compat.mjs +170 -0
  73. package/src/lib/composer-journal.mjs +128 -0
  74. package/src/lib/container/index.mjs +806 -0
  75. package/src/lib/decision-events.mjs +129 -0
  76. package/src/lib/decision-ingest-client.mjs +41 -0
  77. package/src/lib/decision-outbox.mjs +129 -0
  78. package/src/lib/decision-policy.mjs +52 -0
  79. package/src/lib/default-essence.mjs +61 -0
  80. package/src/lib/desktop-launch.mjs +138 -0
  81. package/src/lib/essence.mjs +1211 -0
  82. package/src/lib/fork-client.mjs +410 -0
  83. package/src/lib/fork-config-lock.mjs +166 -0
  84. package/src/lib/fork-seed.mjs +304 -0
  85. package/src/lib/fork-sessions.mjs +183 -0
  86. package/src/lib/fork-supervision-settings.mjs +58 -0
  87. package/src/lib/fork-supervisor.mjs +122 -0
  88. package/src/lib/fs-guard.mjs +28 -0
  89. package/src/lib/http-auth.mjs +162 -0
  90. package/src/lib/idle-audit.mjs +178 -0
  91. package/src/lib/interaction-poke.mjs +61 -0
  92. package/src/lib/main-gate.mjs +579 -0
  93. package/src/lib/mirror-etag.mjs +92 -0
  94. package/src/lib/mirror-official-source.mjs +93 -0
  95. package/src/lib/mirror.mjs +478 -0
  96. package/src/lib/mother-link.mjs +156 -0
  97. package/src/lib/mutex.mjs +31 -0
  98. package/src/lib/permissions.mjs +115 -0
  99. package/src/lib/pnpm-store.mjs +189 -0
  100. package/src/lib/preferences.mjs +212 -0
  101. package/src/lib/producer-contract.mjs +162 -0
  102. package/src/lib/reflow.mjs +41 -0
  103. package/src/lib/remote.mjs +408 -0
  104. package/src/lib/restart-contract.mjs +752 -0
  105. package/src/lib/roots.mjs +30 -0
  106. package/src/lib/rule-registry.mjs +1127 -0
  107. package/src/lib/runtime-capture.mjs +307 -0
  108. package/src/lib/semaphore.mjs +34 -0
  109. package/src/lib/session-bundle.mjs +138 -0
  110. package/src/lib/session-format.mjs +672 -0
  111. package/src/lib/sse-parser.mjs +102 -0
  112. package/src/lib/ssrf-guard.mjs +170 -0
  113. package/src/lib/status-store.mjs +257 -0
  114. package/src/lib/task-handle.mjs +622 -0
  115. package/src/lib/ui-actions.mjs +55 -0
  116. package/src/lib/umbrella.mjs +1661 -0
  117. package/src/lib/upgrade-coordinator.mjs +107 -0
  118. package/src/lib/upgrade-status.mjs +43 -0
  119. package/src/plugins/adapter.mjs +1468 -0
  120. package/src/plugins/approver.mjs +1210 -0
  121. package/src/plugins/auditor.mjs +330 -0
  122. package/src/plugins/buffer-keeper.mjs +522 -0
  123. package/src/plugins/decision-center.mjs +2581 -0
  124. package/src/plugins/forker.mjs +1610 -0
  125. package/src/plugins/healer.mjs +702 -0
  126. package/src/plugins/hot-reloader.mjs +274 -0
  127. package/src/plugins/imports.mjs +247 -0
  128. package/src/plugins/orchestrator.mjs +3938 -0
  129. package/src/plugins/restart-guard.mjs +1022 -0
  130. package/src/plugins/router.mjs +714 -0
  131. package/src/plugins/scorer.mjs +661 -0
  132. package/src/plugins/session-bridge.mjs +166 -0
  133. package/src/plugins/session-catalog.mjs +771 -0
  134. package/src/plugins/session-router.mjs +125 -0
  135. package/src/plugins/session-sync.mjs +171 -0
  136. package/src/plugins/umbrella.mjs +419 -0
  137. package/tools/boot-guard.mjs +95 -0
  138. package/tools/decision-ingest.mjs +53 -0
  139. package/tools/desktop-launch.mjs +71 -0
  140. package/tools/fangctl.mjs +408 -0
  141. package/tools/gate/main-city.mjs +204 -0
  142. package/tools/mcp/server.mjs +121 -0
  143. package/tools/mcp/tools.mjs +65 -0
  144. package/tools/recover-queue.mjs +133 -0
@@ -0,0 +1,266 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 dsh-Fang contributors — see LICENSE-CORE.
3
+ // dsh-Fang kernel — the shared vocabulary of the 1 orchestrator + 9 sub-plugins.
4
+ // Kept as plain constants so plugin code, tests and the client half agree on names.
5
+
6
+ /** Host service keys. Every sub-plugin provides exactly one; subplugins read peers through `ctx.get`. */
7
+ export const SERVICE = {
8
+ orchestrator: 'fang',
9
+ forker: 'fangForker',
10
+ scorer: 'fangScorer',
11
+ healer: 'fangHealer',
12
+ approver: 'fangApprover',
13
+ hotReloader: 'fangHotReloader',
14
+ restart: 'fangRestart',
15
+ buffer: 'fangBuffer',
16
+ auditor: 'fangAudit',
17
+ router: 'fangRouter',
18
+ umbrella: 'fangUmbrella',
19
+ adapter: 'fangAdapter',
20
+ commercial: 'fangCommercial',
21
+ sessionCatalog: 'fangSessionCatalog',
22
+ sessionBridge: 'fangSessionBridge',
23
+ sessionSync: 'fangSessionSync',
24
+ sessionRouter: 'fangSessionRouter',
25
+ link: 'fangLink',
26
+ mirror: 'fangMirror',
27
+ decisionCenter: 'fangDecisionCenter',
28
+ contract: 'fangContract',
29
+ queueJournal: 'fangQueueJournal',
30
+ }
31
+
32
+ /** Loader row ids used by cordis.patch.yml. */
33
+ export const ROW = {
34
+ orchestrator: 'fang-orchestrator',
35
+ forker: 'fang-forker',
36
+ scorer: 'fang-scorer',
37
+ healer: 'fang-healer',
38
+ approver: 'fang-approver',
39
+ hotReloader: 'fang-hot-reloader',
40
+ restart: 'fang-restart-guard',
41
+ buffer: 'fang-buffer-keeper',
42
+ auditor: 'fang-auditor',
43
+ router: 'fang-router',
44
+ umbrella: 'fang-umbrella',
45
+ sessionCatalog: 'fang-session-catalog',
46
+ sessionBridge: 'fang-session-bridge',
47
+ sessionSync: 'fang-session-sync',
48
+ sessionRouter: 'fang-session-router',
49
+ decisionCenter: 'fang-decision-center',
50
+ queueJournal: 'fang-queue-journal',
51
+ }
52
+
53
+ export const FORK_STATUS = {
54
+ PROVISIONING: 'provisioning',
55
+ RUNNING: 'running',
56
+ CRASHED: 'crashed',
57
+ STOPPED: 'stopped',
58
+ REAPED: 'reaped',
59
+ }
60
+
61
+ /** Risk vocabulary shared by scorer / approver / restart-guard. */
62
+ export const RISK = { BLUE: 'blue', YELLOW: 'yellow', RED: 'red' }
63
+
64
+ /**
65
+ * Action light vocabulary (v2.7.6, `fang-umbrella`).
66
+ *
67
+ * `RISK` above is the *approval* enum of restart-guard (three levels, no "nothing to
68
+ * approve"). The umbrella light is four levels because it also has to say "no side
69
+ * effect at all" — green. Mapping: green → auto-allow, blue → auto-allow + mark,
70
+ * yellow → ask, red → ask(critical)/deny/delegate.
71
+ */
72
+ export const LIGHT = { GREEN: 'green', BLUE: 'blue', YELLOW: 'yellow', RED: 'red' }
73
+
74
+ /** Light severity order; higher rank == more dangerous. */
75
+ export const LIGHT_RANK = { green: 1, blue: 2, yellow: 3, red: 4 }
76
+
77
+
78
+ /** Static plugin grades (A safest .. E veto). */
79
+ export const GRADE = ['A', 'B', 'C', 'D', 'E']
80
+
81
+ export const GRADE_COLOR = { A: 'green', B: 'blue', C: 'yellow', D: 'red', E: 'red' }
82
+
83
+ /** Router outcomes. */
84
+ export const ROUTE = { SANDBOX: 'sandbox', CONTAINER: 'container', DENY: 'deny' }
85
+
86
+ /** Restart-guard state machine (mother level only). */
87
+ export const GUARD_STATE = {
88
+ IDLE: 'idle',
89
+ COLLECTING: 'collecting',
90
+ AWAITING: 'awaiting',
91
+ EXECUTING: 'executing',
92
+ }
93
+
94
+ /** Buffer watcher three-state judgement. */
95
+ export const BUFFER_STATE = { SETTLED: 'settled', WRITING: 'writing', PENDING_HIGH_RISK: 'pending-high-risk' }
96
+
97
+ /** Audit record kinds written by the auditor. */
98
+ export const AUDIT = {
99
+ BOOT: 'boot',
100
+ BOOT_VERIFY: 'boot-verify',
101
+ FORK_CREATED: 'fork-created',
102
+ FORK_STARTED: 'fork-started',
103
+ FORK_CRASHED: 'fork-crashed',
104
+ FORK_SUPERVISION: 'fork-supervision',
105
+ FORK_REAPED: 'fork-reaped',
106
+ FORK_HEALTH: 'fork-health',
107
+ PROMOTE_REQUESTED: 'promote-requested',
108
+ PROMOTE_COMMITTED: 'promote-committed',
109
+ PROMOTE_FAILED: 'promote-failed',
110
+ RESTART_REQUESTED: 'restart-requested',
111
+ RESTART_RESOLVED: 'restart-resolved',
112
+ RESTART_DENIED: 'restart-denied',
113
+ SHUTDOWN_GRACEFUL: 'shutdown-graceful',
114
+ APPROVAL_REQUESTED: 'approval-requested',
115
+ APPROVAL_DECIDED: 'approval-decided',
116
+ SNapshot_CREATED: 'snapshot-created',
117
+ ROLLBACK: 'rollback',
118
+ ROUND_OPEN: 'round-open',
119
+ ROUND_RESET: 'round-reset',
120
+ SCORE: 'score',
121
+ UMBRELLA_DECISION: 'umbrella-decision',
122
+ UMBRELLA_STRICT_MODE: 'umbrella-strict-mode',
123
+ ROUTE: 'route',
124
+ BUFFER_FLUSH: 'buffer-flush',
125
+ TASK_READY: 'task-ready',
126
+ TASK_ARCHIVED: 'task-archived',
127
+ TASK_RESTORED: 'task-restored',
128
+ ADAPTER_HANDSHAKE: 'adapter-handshake',
129
+ ROUTE_CONFIRMED: 'route-confirmed',
130
+ LINK_PROBE: 'link-probe',
131
+ RUNTIME_ERROR: 'runtime-error',
132
+ }
133
+
134
+ export const FANG_VERSION = '3.3.4'
135
+
136
+ /**
137
+ * @typedef {object} ForkInfo
138
+ * @property {string} forkId
139
+ * @property {string} taskTitle
140
+ * @property {'provisioning'|'running'|'crashed'|'stopped'|'reaped'} status
141
+ * @property {number|null} pid
142
+ * @property {number|null} port
143
+ * @property {string} homeDir
144
+ * @property {string} profile
145
+ * @property {string|null} url
146
+ * @property {number} createdAt
147
+ * @property {number} restarts
148
+ * @property {object|null} health
149
+ */
150
+
151
+ /**
152
+ * @typedef {object} Assessment
153
+ * @property {'A'|'B'|'C'|'D'|'E'} grade
154
+ * @property {number} score
155
+ * @property {'green'|'blue'|'yellow'|'red'} color
156
+ * @property {boolean} veto
157
+ * @property {string[]} reasons
158
+ * @property {{id:string, weight:number}[]} signals
159
+ */
160
+
161
+ /**
162
+ * @typedef {object} ImpactReport
163
+ * @property {string[]} activeForks
164
+ * @property {string[]} pendingPromotes
165
+ * @property {string[]} dirtyBuffers
166
+ * @property {number} activeSessions
167
+ */
168
+
169
+
170
+ /** Task lifecycle (v2): a task is the product-facing unit, a fork is its process. */
171
+ export const TASK_STATUS = {
172
+ PROVISIONING: 'provisioning',
173
+ READY: 'ready',
174
+ RUNNING: 'running',
175
+ ARCHIVED: 'archived',
176
+ FAILED: 'failed',
177
+ }
178
+
179
+ /** Adapter command vocabulary (mother → fork control channel). */
180
+ export const ADAPTER_OP = {
181
+ PING: 'ping',
182
+ STATUS: 'status',
183
+ FLUSH_BUFFER: 'flush-buffer',
184
+ SCORE_PLUGIN: 'score-plugin',
185
+ READ_PLUGIN: 'read-plugin',
186
+ ROUTE_CONFIRM: 'route-confirm',
187
+ APPROVALS: 'approvals',
188
+ APPROVAL_DECIDE: 'approval-decide',
189
+ ARCHIVE: 'archive',
190
+ FORK_SESSION: 'fork-session',
191
+ DECISION_INGEST: 'decision-ingest',
192
+ }
193
+
194
+ /** Adapter HTTP route suffixes (fork side). */
195
+ export const ADAPTER_ROUTE = {
196
+ HELLO: '/adapter/hello',
197
+ IDENTITY: '/adapter/identity',
198
+ CLIENT_REPORT: '/adapter/client-report',
199
+ STATUS: '/adapter/status',
200
+ APPROVALS: '/adapter/approvals',
201
+ AUDIT: '/adapter/audit',
202
+ COMMAND: '/adapter/command',
203
+ // ── v3(docs/PROTOCOL-V3.md §4):与 v2 五条并存,向后兼容 ──
204
+ VERSION: '/adapter/version',
205
+ HEALTH: '/adapter/health',
206
+ STATE: '/adapter/state',
207
+ EVENTS: '/adapter/events',
208
+ COMMANDS: '/adapter/commands',
209
+ }
210
+
211
+ /**
212
+ * Adapter 协议版本(v2.6.1 起)。两侧编译期常量:母体用它做版本协商,分身
213
+ * 在 /adapter/version 与 /adapter/state 里回报。
214
+ */
215
+ export const ADAPTER_PROTOCOL_VERSION = 3
216
+ /** 母体可接受的最低协议版本(v1 = 无版本号的 v2.0 握手,按 legacy 处理)。 */
217
+ export const ADAPTER_PROTOCOL_MIN = 1
218
+
219
+ /** Adapter 事件种类(SSE 下行,docs/PROTOCOL-V3.md §6)。 */
220
+ export const ADAPTER_EVENT = {
221
+ STATE_CHANGED: 'state-changed',
222
+ PLUGIN_STATE: 'plugin-state',
223
+ APPROVAL_REQUESTED: 'approval-requested',
224
+ APPROVAL_RESOLVED: 'approval-resolved',
225
+ AUDIT: 'audit',
226
+ COMMAND: 'command',
227
+ COMMAND_PROGRESS: 'command-progress',
228
+ COMMAND_DONE: 'command-done',
229
+ ERROR: 'error',
230
+ }
231
+
232
+ /**
233
+ * Adapter 错误码 → HTTP 状态码(docs/PROTOCOL-V3.md §8)。
234
+ * 未登记的 code 一律 500:宁可让母体看到一个明确的失败,也不要假装成功。
235
+ */
236
+ export const ADAPTER_ERROR_STATUS = {
237
+ 'bad-request': 400,
238
+ 'invalid-json': 400,
239
+ 'invalid-payload': 400,
240
+ 'missing-op': 400,
241
+ 'unknown-op': 400,
242
+ 'path-escape': 400,
243
+ 'file-too-large': 400,
244
+ 'total-too-large': 400,
245
+ 'binary-file': 400,
246
+ 'body-too-large': 413,
247
+ 'cursor-invalid': 400,
248
+ 'command-id-invalid': 400,
249
+ unauthorized: 401,
250
+ 'not-found': 404,
251
+ 'plugin-not-found': 404,
252
+ 'session-changed': 409,
253
+ 'state-conflict': 409,
254
+ 'not-pending': 409,
255
+ 'service-unavailable': 409,
256
+ 'not-configured': 409,
257
+ conflict: 409,
258
+ timeout: 409,
259
+ 'cursor-expired': 410,
260
+ 'handler-threw': 500,
261
+ 'internal-error': 500,
262
+ 'not-ready': 503,
263
+ }
264
+
265
+ /** Container (AppContainer) executor states. */
266
+ export const CONTAINER = { DISABLED: 'disabled', UNAVAILABLE: 'unavailable', READY: 'ready' }
@@ -0,0 +1,421 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Copyright (c) 2022-present Shigma and cordis contributors (upstream: https://github.com/shigma/cordis)
3
+ // Vendored into dsh-Fang; see LICENSES/cordis-MIT.txt.
4
+ //#region lib/types/misc.js
5
+ /** No-op callback returning `undefined` at runtime and `any` at type level. */
6
+ function noop() {}
7
+ /** Return true when a value is `null` or `undefined`. */
8
+ function isNullable(value) {
9
+ return value === null || value === void 0;
10
+ }
11
+ /** Return true when a value is neither `null` nor `undefined`. */
12
+ function isNonNullable(value) {
13
+ return !isNullable(value);
14
+ }
15
+ /** Return true for non-array object values. */
16
+ function isPlainObject(data) {
17
+ return data && typeof data === "object" && !Array.isArray(data);
18
+ }
19
+ /** Filter object entries and return a new object. */
20
+ function filterKeys(object, filter) {
21
+ return Object.fromEntries(Object.entries(object).filter(([key, value]) => filter(key, value)));
22
+ }
23
+ /** Map object values while preserving the original key set. */
24
+ function mapValues(object, transform) {
25
+ return Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transform(value, key)]));
26
+ }
27
+ /** Pick selected keys from an object, optionally including `undefined` values. */
28
+ function pick(source, keys, forced) {
29
+ if (!keys) return { ...source };
30
+ const result = {};
31
+ for (const key of keys) if (forced || source[key] !== void 0) result[key] = source[key];
32
+ return result;
33
+ }
34
+ /** Omit selected keys from a shallow object copy. */
35
+ function omit(source, keys) {
36
+ if (!keys) return { ...source };
37
+ const result = { ...source };
38
+ for (const key of keys) Reflect.deleteProperty(result, key);
39
+ return result;
40
+ }
41
+ /** Define a non-enumerable writable property and return the object. */
42
+ function defineProperty(object, key, value) {
43
+ return Object.defineProperty(object, key, {
44
+ writable: true,
45
+ value,
46
+ enumerable: false
47
+ });
48
+ }
49
+ //#endregion
50
+ //#region lib/types/array.js
51
+ /** Return true when every item in `array2` is present in `array1`. */
52
+ function contain(array1, array2) {
53
+ return array2.every((item) => array1.includes(item));
54
+ }
55
+ /** Return items that appear in both arrays. */
56
+ function intersection(array1, array2) {
57
+ return array1.filter((item) => array2.includes(item));
58
+ }
59
+ /** Return items from `array1` that do not appear in `array2`. */
60
+ function difference(array1, array2) {
61
+ return array1.filter((item) => !array2.includes(item));
62
+ }
63
+ /** Return the set-union of two arrays while preserving first occurrence order. */
64
+ function union(array1, array2) {
65
+ return Array.from(new Set([...array1, ...array2]));
66
+ }
67
+ /** Remove duplicate values while preserving first occurrence order. */
68
+ function deduplicate(array) {
69
+ return [...new Set(array)];
70
+ }
71
+ /** Remove one item from an array and report whether it was found. */
72
+ function remove(list, item) {
73
+ const index = list?.indexOf(item);
74
+ if (index >= 0) {
75
+ list.splice(index, 1);
76
+ return true;
77
+ } else return false;
78
+ }
79
+ /** Normalize nullish, scalar, or array input to an array. */
80
+ function makeArray(source) {
81
+ return Array.isArray(source) ? source : isNullable(source) ? [] : [source];
82
+ }
83
+ //#endregion
84
+ //#region lib/types/volatile.js
85
+ /** Shared config references used by schema validators and plugin runtimes. */
86
+ const write = Symbol.for("cosmokit.volatile.write");
87
+ function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
88
+ if (typeof value === "function") throw new TypeError("volatile config cannot contain functions");
89
+ if (value === null || typeof value !== "object") return value;
90
+ if (ancestors.has(value)) throw new TypeError("volatile config cannot contain cycles");
91
+ ancestors.add(value);
92
+ try {
93
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => snapshot(item, ancestors)));
94
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new TypeError("volatile config objects must be plain objects or arrays");
95
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshot(item, ancestors)])));
96
+ } finally {
97
+ ancestors.delete(value);
98
+ }
99
+ }
100
+ /**
101
+ * Create a detached reference containing an immutable copy of the supplied data.
102
+ * @param value - validated config data; class instances and functions are unsupported.
103
+ * @returns a reference whose value is updated only by its owning runtime.
104
+ */
105
+ function createVolatile(value) {
106
+ let current = snapshot(value);
107
+ return Object.freeze({
108
+ get: () => current,
109
+ [write]: (value) => {
110
+ current = value;
111
+ }
112
+ });
113
+ }
114
+ /**
115
+ * Identify references across ESM/CJS copies of the shared library.
116
+ * @param value - a parsed config value.
117
+ * @returns whether the value implements the shared reference protocol.
118
+ */
119
+ function isVolatile(value) {
120
+ return typeof value === "object" && value !== null && write in value;
121
+ }
122
+ /**
123
+ * Collect config references without descending into their snapshots or opaque objects.
124
+ * @internal
125
+ * @param value - parsed config; cyclic ordinary fields are visited once per path.
126
+ * @returns references and their object-key paths, including an empty path for a root reference.
127
+ */
128
+ function volatileEntries(value) {
129
+ const ancestors = /* @__PURE__ */ new Set();
130
+ function visit(value, path) {
131
+ if (isVolatile(value)) return [{
132
+ path,
133
+ ref: value
134
+ }];
135
+ if (!value || typeof value !== "object" || ancestors.has(value)) return [];
136
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return [];
137
+ ancestors.add(value);
138
+ try {
139
+ return Object.entries(value).flatMap(([key, child]) => visit(child, [...path, key]));
140
+ } finally {
141
+ ancestors.delete(value);
142
+ }
143
+ }
144
+ return visit(value, []);
145
+ }
146
+ /**
147
+ * Commit an already validated immutable snapshot from another reference.
148
+ * @internal
149
+ * @param target - the owning plugin's stable reference.
150
+ * @param source - a newly parsed candidate reference.
151
+ */
152
+ function updateVolatile(target, source) {
153
+ target[write](source.get());
154
+ }
155
+ //#endregion
156
+ //#region lib/types/types.js
157
+ /** Test values using `instanceof` with a `toStringTag` fallback. */
158
+ function is(type, value) {
159
+ if (arguments.length === 1) return (value) => is(type, value);
160
+ return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type;
161
+ }
162
+ function isArrayBufferLike(value) {
163
+ return is("ArrayBuffer", value) || is("SharedArrayBuffer", value);
164
+ }
165
+ function isArrayBufferSource(value) {
166
+ return isArrayBufferLike(value) || ArrayBuffer.isView(value);
167
+ }
168
+ /** Binary source detection and base64/hex conversion helpers. */
169
+ var Binary;
170
+ (function(Binary) {
171
+ Binary.is = isArrayBufferLike;
172
+ Binary.isSource = isArrayBufferSource;
173
+ function fromSource(source) {
174
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
175
+ else return source;
176
+ }
177
+ Binary.fromSource = fromSource;
178
+ function toBase64(source) {
179
+ source = fromSource(source);
180
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64");
181
+ let binary = "";
182
+ const bytes = new Uint8Array(source);
183
+ for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
184
+ return btoa(binary);
185
+ }
186
+ Binary.toBase64 = toBase64;
187
+ function fromBase64(source) {
188
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64"));
189
+ return Uint8Array.from(atob(source), (c) => c.charCodeAt(0));
190
+ }
191
+ Binary.fromBase64 = fromBase64;
192
+ function toHex(source) {
193
+ source = fromSource(source);
194
+ if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex");
195
+ return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join("");
196
+ }
197
+ Binary.toHex = toHex;
198
+ function fromHex(source) {
199
+ if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex"));
200
+ const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1);
201
+ const buffer = [];
202
+ for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16));
203
+ return Uint8Array.from(buffer).buffer;
204
+ }
205
+ Binary.fromHex = fromHex;
206
+ })(Binary || (Binary = {}));
207
+ /** Decode a base64 string into binary data. */
208
+ const base64ToArrayBuffer = Binary.fromBase64;
209
+ /** Encode binary data as base64. */
210
+ const arrayBufferToBase64 = Binary.toBase64;
211
+ /** Decode a hex string into binary data. */
212
+ const hexToArrayBuffer = Binary.fromHex;
213
+ /** Encode binary data as hex. */
214
+ const arrayBufferToHex = Binary.toHex;
215
+ /** Deep-clone common JavaScript values while preserving prototypes and cycles. */
216
+ function clone(source, refs = /* @__PURE__ */ new Map()) {
217
+ if (!source || typeof source !== "object") return source;
218
+ if (is("Date", source)) return new Date(source.valueOf());
219
+ if (is("RegExp", source)) return new RegExp(source.source, source.flags);
220
+ if (isArrayBufferLike(source)) return source.slice(0);
221
+ if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
222
+ const cached = refs.get(source);
223
+ if (cached) return cached;
224
+ if (Array.isArray(source)) {
225
+ const result = [];
226
+ refs.set(source, result);
227
+ source.forEach((value, index) => {
228
+ result[index] = Reflect.apply(clone, null, [value, refs]);
229
+ });
230
+ return result;
231
+ }
232
+ const result = Object.create(Object.getPrototypeOf(source));
233
+ refs.set(source, result);
234
+ for (const key of Reflect.ownKeys(source)) {
235
+ const descriptor = { ...Reflect.getOwnPropertyDescriptor(source, key) };
236
+ if ("value" in descriptor) descriptor.value = Reflect.apply(clone, null, [descriptor.value, refs]);
237
+ Reflect.defineProperty(result, key, descriptor);
238
+ }
239
+ return result;
240
+ }
241
+ /**
242
+ * Compare values recursively, treating two volatile references as equal regardless of value.
243
+ * Strict comparison distinguishes null/undefined, treats opaque objects by identity,
244
+ * compares URLs by normalized href, treats array holes as undefined, and considers distinct cyclic structures unequal.
245
+ * @param a - first value.
246
+ * @param b - second value.
247
+ * @param strict - whether to require strict data equality outside volatile references.
248
+ * @returns whether the values compare equal.
249
+ */
250
+ function deepEqual(a, b, strict) {
251
+ const ancestors = /* @__PURE__ */ new Set();
252
+ function compare(a, b) {
253
+ if (a === b) return true;
254
+ if (isVolatile(a) || isVolatile(b)) return isVolatile(a) && isVolatile(b);
255
+ if (!strict && isNullable(a) && isNullable(b)) return true;
256
+ if (typeof a !== typeof b || typeof a !== "object" || !a || !b) return false;
257
+ if (ancestors.has(a)) return false;
258
+ function check(test, then) {
259
+ return test(a) ? test(b) ? then(a, b) : false : test(b) ? false : void 0;
260
+ }
261
+ ancestors.add(a);
262
+ try {
263
+ return check(Array.isArray, (a, b) => {
264
+ if (a.length !== b.length) return false;
265
+ for (let index = 0; index < a.length; index++) if (!compare(a[index], b[index])) return false;
266
+ return true;
267
+ }) ?? check(is("Date"), (a, b) => a.valueOf() === b.valueOf()) ?? check(is("URL"), (a, b) => a.href === b.href) ?? check(is("RegExp"), (a, b) => a.source === b.source && a.flags === b.flags) ?? check(isArrayBufferLike, (a, b) => {
268
+ if (a.byteLength !== b.byteLength) return false;
269
+ const viewA = new Uint8Array(a);
270
+ const viewB = new Uint8Array(b);
271
+ for (let i = 0; i < viewA.length; i++) if (viewA[i] !== viewB[i]) return false;
272
+ return true;
273
+ }) ?? ((!strict || [a, b].every((value) => Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) && Object.keys({
274
+ ...a,
275
+ ...b
276
+ }).every((key) => compare(a[key], b[key])));
277
+ } finally {
278
+ ancestors.delete(a);
279
+ }
280
+ }
281
+ return compare(a, b);
282
+ }
283
+ //#endregion
284
+ //#region lib/types/string.js
285
+ /** Uppercase the first character of a string. */
286
+ function capitalize(source) {
287
+ return source.charAt(0).toUpperCase() + source.slice(1);
288
+ }
289
+ /** Lowercase the first character of a string. */
290
+ function uncapitalize(source) {
291
+ return source.charAt(0).toLowerCase() + source.slice(1);
292
+ }
293
+ /** Convert dash or underscore delimited text to camelCase. */
294
+ function camelCase(source) {
295
+ return source.replace(/[_-][a-z]/g, (str) => str.slice(1).toUpperCase());
296
+ }
297
+ function tokenize(source, delimiters, delimiter) {
298
+ const output = [];
299
+ let state = 0;
300
+ for (let i = 0; i < source.length; i++) {
301
+ const code = source.charCodeAt(i);
302
+ if (code >= 65 && code <= 90) {
303
+ if (state === 1) {
304
+ const next = source.charCodeAt(i + 1);
305
+ if (next >= 97 && next <= 122) output.push(delimiter);
306
+ output.push(code + 32);
307
+ } else {
308
+ if (state !== 0) output.push(delimiter);
309
+ output.push(code + 32);
310
+ }
311
+ state = 1;
312
+ } else if (code >= 97 && code <= 122) {
313
+ output.push(code);
314
+ state = 2;
315
+ } else if (delimiters.includes(code)) {
316
+ if (state !== 0) output.push(delimiter);
317
+ state = 0;
318
+ } else output.push(code);
319
+ }
320
+ return String.fromCharCode(...output);
321
+ }
322
+ /** Convert text to dash-delimited parameter case. */
323
+ function paramCase(source) {
324
+ return tokenize(source, [45, 95], 45);
325
+ }
326
+ /** Convert text to underscore-delimited snake case. */
327
+ function snakeCase(source) {
328
+ return tokenize(source, [45, 95], 95);
329
+ }
330
+ /** Runtime alias for `camelCase`. */
331
+ const camelize = camelCase;
332
+ /** Runtime alias for `paramCase`. */
333
+ const hyphenate = paramCase;
334
+ /** Format a property key as a JavaScript member access suffix. */
335
+ function formatProperty(key) {
336
+ if (typeof key !== "string") return `[${key.toString()}]`;
337
+ return /^[a-z_$][\w$]*$/i.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
338
+ }
339
+ /** Remove one trailing slash from a path string. */
340
+ function trimSlash(source) {
341
+ return source.replace(/\/$/, "");
342
+ }
343
+ /** Ensure a path starts with `/` and has no trailing slash. */
344
+ function sanitize(source) {
345
+ if (!source.startsWith("/")) source = "/" + source;
346
+ return trimSlash(source);
347
+ }
348
+ //#endregion
349
+ //#region lib/types/time.js
350
+ /** Time constants plus parsing and formatting helpers. */
351
+ var Time;
352
+ (function(Time) {
353
+ Time.millisecond = 1;
354
+ Time.second = 1e3;
355
+ Time.minute = Time.second * 60;
356
+ Time.hour = Time.minute * 60;
357
+ Time.day = Time.hour * 24;
358
+ Time.week = Time.day * 7;
359
+ let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset();
360
+ function setTimezoneOffset(offset) {
361
+ timezoneOffset = offset;
362
+ }
363
+ Time.setTimezoneOffset = setTimezoneOffset;
364
+ function getTimezoneOffset() {
365
+ return timezoneOffset;
366
+ }
367
+ Time.getTimezoneOffset = getTimezoneOffset;
368
+ function getDateNumber(date = /* @__PURE__ */ new Date(), offset) {
369
+ if (typeof date === "number") date = new Date(date);
370
+ if (offset === void 0) offset = timezoneOffset;
371
+ return Math.floor((date.valueOf() / Time.minute - offset) / 1440);
372
+ }
373
+ Time.getDateNumber = getDateNumber;
374
+ function fromDateNumber(value, offset) {
375
+ const date = new Date(value * Time.day);
376
+ if (offset === void 0) offset = timezoneOffset;
377
+ return new Date(+date + offset * Time.minute);
378
+ }
379
+ Time.fromDateNumber = fromDateNumber;
380
+ const numeric = /\d+(?:\.\d+)?/.source;
381
+ const timeRegExp = new RegExp(`^${[
382
+ "w(?:eek(?:s)?)?",
383
+ "d(?:ay(?:s)?)?",
384
+ "h(?:our(?:s)?)?",
385
+ "m(?:in(?:ute)?(?:s)?)?",
386
+ "s(?:ec(?:ond)?(?:s)?)?"
387
+ ].map((unit) => `(${numeric}${unit})?`).join("")}$`);
388
+ function parseTime(source) {
389
+ const capture = timeRegExp.exec(source);
390
+ if (!capture) return 0;
391
+ return (parseFloat(capture[1]) * Time.week || 0) + (parseFloat(capture[2]) * Time.day || 0) + (parseFloat(capture[3]) * Time.hour || 0) + (parseFloat(capture[4]) * Time.minute || 0) + (parseFloat(capture[5]) * Time.second || 0);
392
+ }
393
+ Time.parseTime = parseTime;
394
+ function parseDate(date) {
395
+ const parsed = parseTime(date);
396
+ if (parsed) date = Date.now() + parsed;
397
+ else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`;
398
+ else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`;
399
+ return date ? new Date(date) : /* @__PURE__ */ new Date();
400
+ }
401
+ Time.parseDate = parseDate;
402
+ function format(ms) {
403
+ const abs = Math.abs(ms);
404
+ if (abs >= Time.day - Time.hour / 2) return Math.round(ms / Time.day) + "d";
405
+ else if (abs >= Time.hour - Time.minute / 2) return Math.round(ms / Time.hour) + "h";
406
+ else if (abs >= Time.minute - Time.second / 2) return Math.round(ms / Time.minute) + "m";
407
+ else if (abs >= Time.second) return Math.round(ms / Time.second) + "s";
408
+ return ms + "ms";
409
+ }
410
+ Time.format = format;
411
+ function toDigits(source, length = 2) {
412
+ return source.toString().padStart(length, "0");
413
+ }
414
+ Time.toDigits = toDigits;
415
+ function template(template, time = /* @__PURE__ */ new Date()) {
416
+ return template.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3));
417
+ }
418
+ Time.template = template;
419
+ })(Time || (Time = {}));
420
+ //#endregion
421
+ export { Binary, Time, arrayBufferToBase64, arrayBufferToHex, base64ToArrayBuffer, camelCase, camelize, capitalize, clone, contain, createVolatile, deduplicate, deepEqual, defineProperty, difference, filterKeys, formatProperty, hexToArrayBuffer, hyphenate, intersection, is, isNonNullable, isNullable, isPlainObject, isVolatile, makeArray, mapValues, mapValues as valueMap, noop, omit, paramCase, pick, remove, sanitize, snakeCase, trimSlash, uncapitalize, union, updateVolatile, volatileEntries };