@jini-ai/core 0.7.2 → 0.7.3-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (343) hide show
  1. package/README.md +40 -12
  2. package/dist/admin-runtime/admin-api-error.d.ts +68 -0
  3. package/dist/admin-runtime/admin-api-error.js +72 -0
  4. package/dist/admin-runtime/admin-config-error.d.ts +8 -0
  5. package/dist/admin-runtime/admin-config-error.js +11 -0
  6. package/dist/admin-runtime/controller-store.d.ts +20 -0
  7. package/dist/admin-runtime/controller-store.js +32 -0
  8. package/dist/admin-runtime/index.d.ts +13 -0
  9. package/dist/admin-runtime/index.js +12 -0
  10. package/dist/admin-runtime/panel-access.d.ts +88 -0
  11. package/dist/admin-runtime/panel-access.js +76 -0
  12. package/dist/admin-runtime/query-suffix.d.ts +5 -0
  13. package/dist/admin-runtime/query-suffix.js +5 -0
  14. package/dist/agent-handles/element-handles.d.ts +134 -0
  15. package/dist/agent-handles/element-handles.js +45 -0
  16. package/dist/agent-handles/field-descriptor.d.ts +28 -0
  17. package/dist/agent-handles/field-descriptor.js +3 -0
  18. package/dist/agent-handles/handle.d.ts +109 -0
  19. package/dist/agent-handles/handle.js +109 -0
  20. package/dist/agent-handles/index.d.ts +9 -0
  21. package/dist/agent-handles/index.js +6 -0
  22. package/dist/agent-handles/list-handles.d.ts +46 -0
  23. package/dist/agent-handles/list-handles.js +67 -0
  24. package/dist/agent-handles/secret-attrs.d.ts +14 -0
  25. package/dist/agent-handles/secret-attrs.js +13 -0
  26. package/dist/approval-batch-chain.d.ts +45 -0
  27. package/dist/approval-batch-chain.js +75 -0
  28. package/dist/approval.d.ts +33 -14
  29. package/dist/approval.js +57 -43
  30. package/dist/batch-tool-inputs.js +24 -20
  31. package/dist/contracts/admin-module.d.ts +166 -0
  32. package/dist/contracts/admin-module.js +14 -0
  33. package/dist/contracts/agents/definition.d.ts +459 -0
  34. package/dist/contracts/agents/definition.js +2 -0
  35. package/dist/contracts/agents/index.d.ts +7 -0
  36. package/dist/contracts/agents/index.js +2 -0
  37. package/dist/contracts/agents/launch.d.ts +64 -0
  38. package/dist/contracts/agents/launch.js +2 -0
  39. package/dist/contracts/agents/model-catalog.d.ts +213 -0
  40. package/dist/contracts/agents/model-catalog.js +4 -0
  41. package/dist/contracts/agents/native-tool-policy.d.ts +42 -0
  42. package/dist/contracts/agents/native-tool-policy.js +2 -0
  43. package/dist/contracts/ai-trace/capture.d.ts +17 -0
  44. package/dist/contracts/ai-trace/capture.js +43 -0
  45. package/dist/contracts/ai-trace/classify.d.ts +12 -0
  46. package/dist/contracts/ai-trace/classify.js +16 -0
  47. package/dist/contracts/ai-trace/index.d.ts +13 -0
  48. package/dist/contracts/ai-trace/index.js +6 -0
  49. package/dist/contracts/ai-trace/recorder.d.ts +64 -0
  50. package/dist/contracts/ai-trace/recorder.js +283 -0
  51. package/dist/contracts/ai-trace/sinks.d.ts +51 -0
  52. package/dist/contracts/ai-trace/sinks.js +153 -0
  53. package/dist/contracts/ai-trace/types.d.ts +123 -0
  54. package/dist/contracts/ai-trace/types.js +17 -0
  55. package/dist/contracts/ai-trace/usage.d.ts +16 -0
  56. package/dist/contracts/ai-trace/usage.js +45 -0
  57. package/dist/contracts/blob.d.ts +31 -0
  58. package/dist/contracts/blob.js +10 -0
  59. package/dist/contracts/capabilities.d.ts +95 -0
  60. package/dist/contracts/capabilities.js +111 -0
  61. package/dist/contracts/charts.d.ts +75 -0
  62. package/dist/contracts/charts.js +4 -0
  63. package/dist/contracts/env.d.ts +96 -0
  64. package/dist/contracts/env.js +6 -0
  65. package/dist/contracts/events/change-set.d.ts +106 -0
  66. package/dist/contracts/events/change-set.js +2 -0
  67. package/dist/contracts/events/command.d.ts +118 -0
  68. package/dist/contracts/events/command.js +2 -0
  69. package/dist/contracts/events/ports.d.ts +172 -0
  70. package/dist/contracts/events/ports.js +2 -0
  71. package/dist/contracts/events.d.ts +5 -0
  72. package/dist/contracts/events.js +2 -0
  73. package/dist/contracts/forms.d.ts +110 -0
  74. package/dist/contracts/forms.js +4 -0
  75. package/dist/contracts/hosted-mcp/config.d.ts +19 -0
  76. package/dist/contracts/hosted-mcp/record.d.ts +61 -4
  77. package/dist/contracts/mail/email-sender.d.ts +118 -0
  78. package/dist/contracts/mail/email-sender.js +20 -0
  79. package/dist/contracts/mail/smtp-payload.d.ts +32 -0
  80. package/dist/contracts/mail/smtp-payload.js +2 -0
  81. package/dist/contracts/mail.d.ts +2 -0
  82. package/dist/contracts/mail.js +1 -1
  83. package/dist/contracts/observability.d.ts +235 -0
  84. package/dist/contracts/observability.js +28 -0
  85. package/dist/contracts/plugin-sdk.d.ts +186 -0
  86. package/dist/contracts/plugin-sdk.js +39 -0
  87. package/dist/contracts/runtime/command.d.ts +41 -0
  88. package/dist/contracts/runtime/command.js +60 -0
  89. package/dist/contracts/runtime/environment.d.ts +18 -0
  90. package/dist/contracts/runtime/environment.js +26 -0
  91. package/dist/contracts/runtime/file-lock.d.ts +94 -0
  92. package/dist/contracts/runtime/file-lock.js +25 -0
  93. package/dist/contracts/runtime/fs.d.ts +33 -0
  94. package/dist/contracts/runtime/fs.js +2 -0
  95. package/dist/contracts/runtime/http.d.ts +89 -0
  96. package/dist/contracts/runtime/http.js +2 -0
  97. package/dist/contracts/runtime/platform.d.ts +3 -0
  98. package/dist/contracts/runtime/platform.js +2 -0
  99. package/dist/contracts/runtime/process.d.ts +40 -0
  100. package/dist/contracts/runtime/process.js +31 -0
  101. package/dist/contracts/runtime/reader.d.ts +11 -0
  102. package/dist/contracts/runtime/reader.js +2 -0
  103. package/dist/contracts/runtime/terminal.d.ts +99 -0
  104. package/dist/contracts/runtime/terminal.js +2 -0
  105. package/dist/contracts/runtime/testing.d.ts +84 -0
  106. package/dist/contracts/runtime/testing.js +116 -0
  107. package/dist/contracts/runtime.d.ts +10 -0
  108. package/dist/contracts/runtime.js +10 -0
  109. package/dist/contracts/server/api-error.d.ts +43 -0
  110. package/dist/contracts/server/api-error.js +49 -0
  111. package/dist/contracts/server/auth.d.ts +20 -0
  112. package/dist/contracts/server/auth.js +21 -0
  113. package/dist/contracts/server/conformance.d.ts +25 -0
  114. package/dist/contracts/server/conformance.js +50 -0
  115. package/dist/contracts/server/json-route.d.ts +176 -0
  116. package/dist/contracts/server/json-route.js +155 -0
  117. package/dist/contracts/server/middleware.d.ts +35 -0
  118. package/dist/contracts/server/middleware.js +56 -0
  119. package/dist/contracts/server/origin.d.ts +44 -0
  120. package/dist/contracts/server/origin.js +32 -0
  121. package/dist/contracts/server/query.d.ts +16 -0
  122. package/dist/contracts/server/query.js +69 -0
  123. package/dist/contracts/server/rate-limit.d.ts +20 -0
  124. package/dist/contracts/server/rate-limit.js +8 -0
  125. package/dist/contracts/server/request-body.d.ts +26 -0
  126. package/dist/contracts/server/request-body.js +82 -0
  127. package/dist/contracts/server/result.d.ts +17 -0
  128. package/dist/contracts/server/result.js +5 -0
  129. package/dist/contracts/server/route-table.d.ts +54 -0
  130. package/dist/contracts/server/route-table.js +119 -0
  131. package/dist/contracts/server/same-origin-write.d.ts +18 -0
  132. package/dist/contracts/server/same-origin-write.js +31 -0
  133. package/dist/contracts/server/security-headers.d.ts +30 -0
  134. package/dist/contracts/server/security-headers.js +35 -0
  135. package/dist/contracts/server/sse.d.ts +82 -0
  136. package/dist/contracts/server/sse.js +103 -0
  137. package/dist/contracts/server/testing.d.ts +59 -0
  138. package/dist/contracts/server/testing.js +68 -0
  139. package/dist/contracts/server/verified-origin/configured-origin.d.ts +37 -0
  140. package/dist/contracts/server/verified-origin/configured-origin.js +103 -0
  141. package/dist/contracts/server/verified-origin/index.d.ts +7 -0
  142. package/dist/contracts/server/verified-origin/index.js +6 -0
  143. package/dist/contracts/server/verified-origin/loopback-host.d.ts +9 -0
  144. package/dist/contracts/server/verified-origin/loopback-host.js +17 -0
  145. package/dist/contracts/server/verified-origin/origin.d.ts +64 -0
  146. package/dist/contracts/server/verified-origin/origin.js +162 -0
  147. package/dist/contracts/server/verified-origin/ports.d.ts +38 -0
  148. package/dist/contracts/server/verified-origin/ports.js +2 -0
  149. package/dist/contracts/server/verified-origin/repo.memory.d.ts +32 -0
  150. package/dist/contracts/server/verified-origin/repo.memory.js +34 -0
  151. package/dist/contracts/server/verified-origin/site-path.d.ts +113 -0
  152. package/dist/contracts/server/verified-origin/site-path.js +188 -0
  153. package/dist/contracts/server/verified-origin/types.d.ts +33 -0
  154. package/dist/contracts/server/verified-origin/types.js +30 -0
  155. package/dist/contracts/server.d.ts +46 -2
  156. package/dist/contracts/server.js +17 -3
  157. package/dist/contracts/storage/kernel.d.ts +86 -0
  158. package/dist/contracts/storage/kernel.js +38 -0
  159. package/dist/contracts/storage/migration.d.ts +32 -0
  160. package/dist/contracts/storage/migration.js +2 -0
  161. package/dist/contracts/storage/rows.d.ts +33 -0
  162. package/dist/contracts/storage/rows.js +42 -0
  163. package/dist/contracts/storage/sqlite.d.ts +113 -0
  164. package/dist/contracts/storage/sqlite.js +8 -0
  165. package/dist/contracts/storage/values.d.ts +25 -0
  166. package/dist/contracts/storage/values.js +25 -0
  167. package/dist/contracts/storage.d.ts +8 -0
  168. package/dist/contracts/storage.js +6 -0
  169. package/dist/contracts/vault/invariants.d.ts +26 -0
  170. package/dist/contracts/vault/invariants.js +49 -0
  171. package/dist/contracts/vault.d.ts +1 -0
  172. package/dist/contracts/vault.js +1 -1
  173. package/dist/env/coercers.d.ts +21 -0
  174. package/dist/env/coercers.js +68 -0
  175. package/dist/env/describe-env-for-diagnostics.d.ts +16 -0
  176. package/dist/env/describe-env-for-diagnostics.js +23 -0
  177. package/dist/env/format-env-issue.d.ts +13 -0
  178. package/dist/env/format-env-issue.js +22 -0
  179. package/dist/env/parse-env.d.ts +24 -0
  180. package/dist/env/parse-env.js +102 -0
  181. package/dist/env/value-echo.d.ts +17 -0
  182. package/dist/env/value-echo.js +42 -0
  183. package/dist/errors/approved-cause.d.ts +36 -0
  184. package/dist/errors/approved-cause.js +17 -0
  185. package/dist/errors/bindings.d.ts +61 -0
  186. package/dist/errors/bindings.js +57 -0
  187. package/dist/errors/catalog.d.ts +84 -0
  188. package/dist/errors/catalog.js +151 -0
  189. package/dist/errors/disclosure.d.ts +48 -0
  190. package/dist/errors/disclosure.js +27 -0
  191. package/dist/errors/error-id.d.ts +26 -0
  192. package/dist/errors/error-id.js +23 -0
  193. package/dist/errors/idioms.d.ts +73 -0
  194. package/dist/errors/idioms.js +85 -0
  195. package/dist/errors/incident-text.d.ts +16 -0
  196. package/dist/errors/incident-text.js +77 -0
  197. package/dist/errors/reporter.d.ts +94 -0
  198. package/dist/errors/reporter.js +152 -0
  199. package/dist/errors/sentences.d.ts +68 -0
  200. package/dist/errors/sentences.js +93 -0
  201. package/dist/errors/testing.d.ts +50 -0
  202. package/dist/errors/testing.js +44 -0
  203. package/dist/fetch/cache.d.ts +12 -5
  204. package/dist/fetch/cache.js +46 -47
  205. package/dist/fetch/index.d.ts +1 -1
  206. package/dist/fetch/loader-read.d.ts +6 -2
  207. package/dist/fetch/loader-read.js +4 -4
  208. package/dist/format-error-for-log.d.ts +15 -0
  209. package/dist/format-error-for-log.js +55 -0
  210. package/dist/gated-mutations/gateway.d.ts +2 -0
  211. package/dist/gated-mutations/gateway.js +4 -1
  212. package/dist/host-read-vocabulary.d.ts +47 -0
  213. package/dist/host-read-vocabulary.js +44 -0
  214. package/dist/index.d.ts +5 -1
  215. package/dist/index.js +4 -0
  216. package/dist/list-page.d.ts +93 -0
  217. package/dist/list-page.js +154 -0
  218. package/dist/model-facing-tool-errors.d.ts +67 -5
  219. package/dist/model-facing-tool-errors.js +155 -19
  220. package/dist/net/endpoint-policy.d.ts +39 -0
  221. package/dist/net/endpoint-policy.js +218 -0
  222. package/dist/net/fetch-timeouts.d.ts +38 -0
  223. package/dist/net/fetch-timeouts.js +31 -0
  224. package/dist/net/index.d.ts +4 -0
  225. package/dist/net/index.js +4 -0
  226. package/dist/net/loopback.d.ts +13 -0
  227. package/dist/net/loopback.js +39 -0
  228. package/dist/optimistic-concurrency.d.ts +183 -0
  229. package/dist/optimistic-concurrency.js +222 -0
  230. package/dist/primitives/errors.d.ts +9 -0
  231. package/dist/primitives/errors.js +12 -0
  232. package/dist/primitives/ids.d.ts +0 -2
  233. package/dist/primitives/ids.js +1 -4
  234. package/dist/primitives/index.d.ts +3 -0
  235. package/dist/primitives/index.js +2 -0
  236. package/dist/primitives/logger.d.ts +36 -1
  237. package/dist/primitives/logger.js +125 -9
  238. package/dist/primitives/node-shape.d.ts +24 -0
  239. package/dist/primitives/node-shape.js +21 -0
  240. package/dist/primitives/time.d.ts +9 -2
  241. package/dist/primitives/time.js +4 -3
  242. package/dist/provider-registry.js +26 -20
  243. package/dist/records.d.ts +40 -7
  244. package/dist/records.js +37 -3
  245. package/dist/redact.d.ts +1 -84
  246. package/dist/redact.js +2 -826
  247. package/dist/redaction-collectors.d.ts +7 -0
  248. package/dist/redaction-collectors.js +152 -0
  249. package/dist/redaction-exact-secrets.d.ts +14 -0
  250. package/dist/redaction-exact-secrets.js +115 -0
  251. package/dist/redaction-labels.d.ts +14 -0
  252. package/dist/redaction-labels.js +156 -0
  253. package/dist/redaction-patterns.d.ts +54 -0
  254. package/dist/redaction-patterns.js +178 -0
  255. package/dist/redaction-spans.d.ts +31 -0
  256. package/dist/redaction-spans.js +83 -0
  257. package/dist/registration-kit.d.ts +1 -1
  258. package/dist/revision-conflict-error.d.ts +18 -0
  259. package/dist/revision-conflict-error.js +20 -0
  260. package/dist/secret-shapes.d.ts +50 -0
  261. package/dist/secret-shapes.js +105 -0
  262. package/dist/settings/agent-tools.js +22 -8
  263. package/dist/settings/agent-value-write-tools.d.ts +4 -1
  264. package/dist/settings/agent-value-write-tools.js +7 -6
  265. package/dist/settings/agent-writable-preferences.d.ts +3 -1
  266. package/dist/settings/agent-writable-preferences.js +1 -1
  267. package/dist/settings/agent-write-denylist.d.ts +7 -4
  268. package/dist/settings/agent-write-denylist.js +1 -1
  269. package/dist/settings/{express/cms-adapter.d.ts → cms-adapter.d.ts} +3 -2
  270. package/dist/settings/{express/cms-adapter.js → cms-adapter.js} +21 -11
  271. package/dist/settings/definitions-dispatch.js +3 -1
  272. package/dist/settings/ensure-definitions.js +3 -1
  273. package/dist/settings/errors.d.ts +1 -13
  274. package/dist/settings/errors.js +2 -15
  275. package/dist/settings/index.d.ts +11 -2
  276. package/dist/settings/index.js +10 -2
  277. package/dist/settings/purge-service.js +63 -86
  278. package/dist/settings/{express/contracts.d.ts → route-policy.d.ts} +53 -47
  279. package/dist/settings/{express/shared.js → route-policy.js} +1 -16
  280. package/dist/settings/settings.d.ts +19 -11
  281. package/dist/settings/settings.js +9 -11
  282. package/dist/settings/tool-registrations.d.ts +3 -3
  283. package/dist/settings/tool-registrations.js +130 -125
  284. package/dist/settings/types.d.ts +1 -1
  285. package/dist/settings/write-definition-rename.d.ts +37 -0
  286. package/dist/settings/write-definition-rename.js +119 -0
  287. package/dist/settings/write-definition-retype.d.ts +61 -0
  288. package/dist/settings/write-definition-retype.js +109 -0
  289. package/dist/settings/write-definition-status.d.ts +81 -0
  290. package/dist/settings/write-definition-status.js +121 -0
  291. package/dist/settings/write-reset.d.ts +34 -0
  292. package/dist/settings/write-reset.js +73 -0
  293. package/dist/settings/write-service.d.ts +16 -287
  294. package/dist/settings/write-service.js +49 -681
  295. package/dist/settings/write-value-revisions.d.ts +68 -0
  296. package/dist/settings/write-value-revisions.js +124 -0
  297. package/dist/settings/write-values.d.ts +96 -0
  298. package/dist/settings/write-values.js +83 -0
  299. package/dist/surface-exchanges.d.ts +2 -2
  300. package/dist/text/dictionary-translator.d.ts +19 -0
  301. package/dist/text/dictionary-translator.js +14 -0
  302. package/dist/text/format-byte-size.d.ts +25 -0
  303. package/dist/text/format-byte-size.js +25 -0
  304. package/dist/text/format-timestamp.d.ts +22 -0
  305. package/dist/text/format-timestamp.js +57 -0
  306. package/dist/text/index.d.ts +12 -0
  307. package/dist/text/index.js +9 -0
  308. package/dist/text/is-abort-error.d.ts +5 -0
  309. package/dist/text/is-abort-error.js +5 -0
  310. package/dist/text/mime.d.ts +5 -0
  311. package/dist/text/mime.js +21 -0
  312. package/dist/text/redact-urls.d.ts +7 -0
  313. package/dist/text/redact-urls.js +5 -0
  314. package/dist/text/resolve-active-tab-id.d.ts +13 -0
  315. package/dist/text/resolve-active-tab-id.js +15 -0
  316. package/dist/text/sanitize-untrusted-text.d.ts +1 -1
  317. package/dist/text/sanitize-untrusted-text.js +2 -1
  318. package/dist/text/tagged-text-suppression.d.ts +103 -0
  319. package/dist/text/tagged-text-suppression.js +143 -0
  320. package/dist/text/template-i18n.d.ts +37 -0
  321. package/dist/text/template-i18n.js +48 -0
  322. package/dist/tool-call-text.d.ts +59 -0
  323. package/dist/tool-call-text.js +62 -0
  324. package/dist/tool-input-envelope.js +8 -4
  325. package/dist/tool-input-normalization.js +8 -1
  326. package/dist/tool-input-repairs.d.ts +58 -0
  327. package/dist/tool-input-repairs.js +154 -0
  328. package/dist/tool-tokens.js +1 -1
  329. package/dist/user-facing-error.d.ts +1 -1
  330. package/dist/user-facing-error.js +3 -1
  331. package/package.json +235 -14
  332. package/plugin-directory.d.ts +2 -2
  333. package/plugin-directory.js +16 -10
  334. package/dist/settings/express/contracts.js +0 -2
  335. package/dist/settings/express/http-request.d.ts +0 -33
  336. package/dist/settings/express/http-request.js +0 -50
  337. package/dist/settings/express/http.d.ts +0 -10
  338. package/dist/settings/express/http.js +0 -196
  339. package/dist/settings/express/index.d.ts +0 -5
  340. package/dist/settings/express/index.js +0 -4
  341. package/dist/settings/express/shared.d.ts +0 -68
  342. package/dist/settings/express/stream.d.ts +0 -24
  343. package/dist/settings/express/stream.js +0 -171
@@ -0,0 +1,222 @@
1
+ /**
2
+ * @file The one optimistic-concurrency vocabulary every editable record shares (refactor pattern
3
+ * "lost updates", 2026-11-13).
4
+ *
5
+ * Why it exists: whole-record saves (PUT routes, `*_update`/`*_set` tools, full-row upserts) wrote
6
+ * whatever the caller sent over whatever was stored, so two editors — or a person and the assistant
7
+ * — silently overwrote each other. Posts, pages, entries, menus and content types already closed
8
+ * this with an integer `version` column, an `expectedVersion` basis and a `409 VERSION_CONFLICT`;
9
+ * each domain spelled its own error class and envelope. This module is that same contract once, so
10
+ * every remaining site applies one pattern instead of inventing a sixth spelling.
11
+ *
12
+ * Deliberately storage- and server-neutral: no query builder, no HTTP framework. A repo reports how
13
+ * many rows its conditional write changed and how to read the live version; a route turns the error
14
+ * into a plain JSON body with whatever server it runs on.
15
+ */
16
+ import { ToolInputError } from './tool-input-errors.js';
17
+ import { SettingsRevisionConflictError } from './revision-conflict-error.js';
18
+ /** The machine-readable code every arm publishes for a superseded basis — the same string posts,
19
+ * entries, menus and content types already send, so existing admin classifiers keep working. */
20
+ export const VERSION_CONFLICT_CODE = 'VERSION_CONFLICT';
21
+ /**
22
+ * A compare-and-set write lost: the record moved on (or was deleted) after the caller read it.
23
+ * Nothing was written. Resending the same request cannot succeed; re-reading can.
24
+ */
25
+ export class RecordVersionConflictError extends Error {
26
+ code = VERSION_CONFLICT_CODE;
27
+ /** Plain-words noun for the record, e.g. `webhook`, `MCP server`. */
28
+ recordKind;
29
+ recordId;
30
+ /** The version the caller read. */
31
+ expectedVersion;
32
+ /** The version stored now, or `null` when the record no longer exists. */
33
+ currentVersion;
34
+ constructor(required, optional = {}) {
35
+ const now = required.currentVersion === null ? 'it has since been deleted' : `it is now version ${required.currentVersion}`;
36
+ super(`This ${required.recordKind} was changed by someone else after you opened it (you had version ${required.expectedVersion}, ${now}). ` +
37
+ 'Nothing was saved. Reload it to see the latest version, then make your change again.', optional);
38
+ this.name = 'RecordVersionConflictError';
39
+ this.recordKind = required.recordKind;
40
+ this.recordId = required.recordId;
41
+ this.expectedVersion = required.expectedVersion;
42
+ this.currentVersion = required.currentVersion;
43
+ }
44
+ }
45
+ /**
46
+ * The basis off an untrusted input. `undefined` means the caller did not send one (legacy
47
+ * last-write-wins callers); anything present must be a non-negative integer.
48
+ *
49
+ * Throws instead of coercing: a mistyped `"3"` read as "no basis" would turn a client that believes
50
+ * it is protected into an unguarded overwrite — the exact bug this closes.
51
+ *
52
+ * @throws {ToolInputError} `'<field>' must be a non-negative integer when present`.
53
+ * @complexity O(1).
54
+ */
55
+ export function parseExpectedVersion(required, optional = {}) {
56
+ const { value } = required;
57
+ if (value === undefined)
58
+ return undefined;
59
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
60
+ throw new ToolInputError({ message: `'${optional.field ?? 'expectedVersion'}' must be a non-negative integer when present` });
61
+ }
62
+ return value;
63
+ }
64
+ /**
65
+ * Like {@link parseExpectedVersion} but the basis is mandatory — for assistant write tools, where
66
+ * the model always reads a record before replacing it, so a missing basis is a caller mistake.
67
+ *
68
+ * @throws {ToolInputError} with plain recovery words when missing or malformed.
69
+ * @complexity O(1).
70
+ */
71
+ export function requireExpectedVersion(required, optional = {}) {
72
+ const field = optional.field ?? 'expectedVersion';
73
+ const parsed = parseExpectedVersion({ value: required.value }, { field });
74
+ if (parsed === undefined) {
75
+ throw new ToolInputError({ message: `'${field}' is required: call ${required.readToolId} first and pass the record's current version.` });
76
+ }
77
+ return parsed;
78
+ }
79
+ /**
80
+ * Finishes a conditional write (`UPDATE … WHERE version = :expectedVersion`). Changed rows ⇒ done;
81
+ * none ⇒ re-read the live version (for the message) and throw.
82
+ *
83
+ * @param required.changedRows - What the driver reported (`numUpdatedRows`, `changes`, `rowCount`).
84
+ * @param required.readCurrentVersion - Reads the stored version, `null` when the row is gone.
85
+ * @throws {RecordVersionConflictError} when no row changed.
86
+ * @complexity O(1) plus one read on a miss.
87
+ */
88
+ export async function assertVersionedWrite(required, _optional = {}) {
89
+ if (Number(required.changedRows) > 0)
90
+ return;
91
+ throw new RecordVersionConflictError({
92
+ recordKind: required.recordKind,
93
+ recordId: required.recordId,
94
+ expectedVersion: required.expectedVersion,
95
+ currentVersion: await required.readCurrentVersion(),
96
+ });
97
+ }
98
+ /**
99
+ * A settings-ledger conflict (`settings` `set(…, { expectedRevisionSeq })` / `clear`) as the shared
100
+ * conflict, so a route or tool that writes settings maps ONE error class to 409 / model guidance.
101
+ * Why a bridge, not a second check: the ledger already compares the value row's `seq` inside its
102
+ * revision-stream lock; only its error spelling differs. Any other error comes back unchanged, so
103
+ * callers can `throw fromSettingsRevisionConflict({ error, setting })` in a catch.
104
+ *
105
+ * @param required.setting - `<namespace>.<key>` of the value that was written.
106
+ * @complexity O(1).
107
+ */
108
+ export function fromSettingsRevisionConflict(required, _optional = {}) {
109
+ const { error } = required;
110
+ if (!(error instanceof SettingsRevisionConflictError))
111
+ return error;
112
+ return new RecordVersionConflictError({ recordKind: 'setting', recordId: required.setting, expectedVersion: error.expectedRevisionSeq, currentVersion: error.actualRevisionSeq }, { cause: error });
113
+ }
114
+ /**
115
+ * The 409 body. `details` carries the versions as fields so the admin "Copy details" text and any
116
+ * client can show "yours N, theirs M" without parsing prose. Same `{ error, code, details }` shape
117
+ * `features/post/expected-version.ts` in a host already sends.
118
+ *
119
+ * @complexity O(1).
120
+ */
121
+ export function versionConflictBody(required, _optional = {}) {
122
+ const { error } = required;
123
+ return {
124
+ error: error.message,
125
+ code: VERSION_CONFLICT_CODE,
126
+ details: {
127
+ recordKind: error.recordKind,
128
+ recordId: error.recordId,
129
+ expectedVersion: error.expectedVersion,
130
+ currentVersion: error.currentVersion,
131
+ },
132
+ };
133
+ }
134
+ /** The machine-readable code for a save that named no version (HTTP status 428). */
135
+ export const VERSION_REQUIRED_CODE = 'VERSION_REQUIRED';
136
+ /** The one plain-words answer for a save that named no version, shared by the error and its 428 body. */
137
+ export const VERSION_REQUIRED_MESSAGE = "This save did not say which version you were editing, so nothing was saved (it could have overwritten someone else's change). Reload, make your change again, and save.";
138
+ /**
139
+ * A save for an editable record arrived without saying which version the person was editing, so it
140
+ * could have overwritten someone else's change. Nothing was written. Re-reading and saving again can
141
+ * succeed.
142
+ */
143
+ export class RecordVersionRequiredError extends Error {
144
+ code = VERSION_REQUIRED_CODE;
145
+ /** The input field that should have carried the version. */
146
+ field;
147
+ constructor(required, optional = {}) {
148
+ super(VERSION_REQUIRED_MESSAGE, optional);
149
+ this.name = 'RecordVersionRequiredError';
150
+ this.field = required.field;
151
+ }
152
+ }
153
+ /**
154
+ * Like {@link parseExpectedVersion} but the basis is mandatory for an editor save (a person's form),
155
+ * and a missing one is its own error so a route can answer 428 instead of a generic 400.
156
+ *
157
+ * @throws {ToolInputError} when present but malformed.
158
+ * @throws {RecordVersionRequiredError} when missing.
159
+ * @complexity O(1).
160
+ */
161
+ export function requireEditorVersion(required, optional = {}) {
162
+ const field = optional.field ?? 'expectedVersion';
163
+ const parsed = parseExpectedVersion({ value: required.value }, { field });
164
+ if (parsed === undefined)
165
+ throw new RecordVersionRequiredError({ field });
166
+ return parsed;
167
+ }
168
+ /**
169
+ * The 428 body for a save that named no version. HTTP status 428.
170
+ *
171
+ * @complexity O(1).
172
+ */
173
+ export function versionRequiredBody(required, _optional = {}) {
174
+ const { error } = required;
175
+ return { error: VERSION_REQUIRED_MESSAGE, code: VERSION_REQUIRED_CODE, details: { field: error.field } };
176
+ }
177
+ /**
178
+ * The model-facing rule for a domain's allowlist: publishes the plain message plus what to do next,
179
+ * so the assistant re-reads instead of resending the same stale call (or giving up).
180
+ *
181
+ * @complexity O(1).
182
+ */
183
+ export function versionConflictRule(required, _optional = {}) {
184
+ return {
185
+ error: RecordVersionConflictError,
186
+ code: VERSION_CONFLICT_CODE,
187
+ guidance: `Your change was NOT applied and nothing was overwritten. Call ${required.readToolId} again, ` +
188
+ "reapply the change on top of what it returns, and resend with that result's `version` as `expectedVersion`. " +
189
+ 'Do not resend this call unchanged. If the other change conflicts with what the person asked for, tell them instead of choosing.',
190
+ };
191
+ }
192
+ /**
193
+ * An internal, single-purpose change (a status flip, an adoption, a rename) applied to a versioned
194
+ * record: read it, derive the next state from what was read, write it conditionally on the version
195
+ * that was read. If the write misses, read again and re-apply the same change once (rule M4), then
196
+ * report the conflict. A person's or an agent's edit never goes through here: it carries its own
197
+ * basis and is never retried for them.
198
+ *
199
+ * @param required.read - Reads the record, `null` when it does not exist.
200
+ * @param required.build - Derives the next record from the one just read; `null` means nothing to write.
201
+ * @param required.write - The conditional write (`WHERE version = current.version`); `true` when it applied.
202
+ * @returns the record as written, or `null` when it does not exist or `build` had nothing to write.
203
+ * @throws {RecordVersionConflictError} when the write missed twice.
204
+ * @complexity O(1) writes; at most two reads, two builds and one extra read for the message.
205
+ */
206
+ export async function applyInternalChange(required, _optional = {}) {
207
+ let expectedVersion = 0;
208
+ for (let attempt = 0; attempt < 2; attempt += 1) {
209
+ const current = await required.read();
210
+ if (!current)
211
+ return null;
212
+ expectedVersion = current.version;
213
+ const next = await required.build(current);
214
+ if (!next)
215
+ return null;
216
+ if (await required.write({ current, next }))
217
+ return next;
218
+ }
219
+ const latest = await required.read();
220
+ throw new RecordVersionConflictError({ recordKind: required.recordKind, recordId: required.recordId, expectedVersion, currentVersion: latest?.version ?? null });
221
+ }
222
+ //# sourceMappingURL=optimistic-concurrency.js.map
@@ -0,0 +1,9 @@
1
+ /** A Node-style `error.code` as a string, or `null` when the thrown value carries none. */
2
+ export declare function errorCodeOf({ error }: {
3
+ error: unknown;
4
+ }, _optional?: Record<string, never>): string | null;
5
+ /** A human-readable message from an unknown thrown value. */
6
+ export declare function errorMessageOf({ error }: {
7
+ error: unknown;
8
+ }, _optional?: Record<string, never>): string;
9
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1,12 @@
1
+ /** A Node-style `error.code` as a string, or `null` when the thrown value carries none. */
2
+ export function errorCodeOf({ error }, _optional = {}) {
3
+ if (typeof error !== 'object' || error === null || !('code' in error))
4
+ return null;
5
+ const { code } = error;
6
+ return code === null || code === undefined ? null : String(code);
7
+ }
8
+ /** A human-readable message from an unknown thrown value. */
9
+ export function errorMessageOf({ error }, _optional = {}) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
12
+ //# sourceMappingURL=errors.js.map
@@ -3,6 +3,4 @@ export type UUID = string;
3
3
  export interface IdGenerator {
4
4
  newId(): string;
5
5
  }
6
- /** Uses the host's cryptographic UUID generator; no insecure random fallback. */
7
- export declare function createRandomUuidGenerator(): IdGenerator;
8
6
  //# sourceMappingURL=ids.d.ts.map
@@ -1,5 +1,2 @@
1
- /** Uses the host's cryptographic UUID generator; no insecure random fallback. */
2
- export function createRandomUuidGenerator() {
3
- return { newId: () => globalThis.crypto.randomUUID() };
4
- }
1
+ export {};
5
2
  //# sourceMappingURL=ids.js.map
@@ -1,4 +1,5 @@
1
1
  export * from './time.js';
2
+ export * from './errors.js';
2
3
  export * from './ids.js';
3
4
  export * from './json.js';
4
5
  export * from './http.js';
@@ -9,4 +10,6 @@ export * from './result.js';
9
10
  export * from './paths.js';
10
11
  export * from './tasks.js';
11
12
  export { trimChars, trimCharsEnd, trimCharsStart } from './trim-chars.js';
13
+ export { hasAttributeOnAnyNodeShape } from './node-shape.js';
14
+ export type { NodeShape } from './node-shape.js';
12
15
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export * from './time.js';
2
+ export * from './errors.js';
2
3
  export * from './ids.js';
3
4
  export * from './json.js';
4
5
  export * from './http.js';
@@ -8,4 +9,5 @@ export * from './result.js';
8
9
  export * from './paths.js';
9
10
  export * from './tasks.js';
10
11
  export { trimChars, trimCharsEnd, trimCharsStart } from './trim-chars.js';
12
+ export { hasAttributeOnAnyNodeShape } from './node-shape.js';
11
13
  //# sourceMappingURL=index.js.map
@@ -19,8 +19,43 @@ export interface Logger {
19
19
  error?: unknown;
20
20
  }): void;
21
21
  }
22
- /** Minimal console adapter with a required host-owned prefix and structured metadata. */
22
+ /** One log call exactly as the caller made it, original error objects included. */
23
+ export interface LogDiagnosticRecord {
24
+ readonly level: 'info' | 'warn' | 'error';
25
+ readonly message: string;
26
+ readonly meta?: Record<string, unknown>;
27
+ readonly error?: unknown;
28
+ }
29
+ /** A host-owned sink for full diagnostics; the host applies its own redaction and storage. */
30
+ export type LogDiagnosticsSink = (record: LogDiagnosticRecord) => void;
31
+ /**
32
+ * Meta as a default sink may write it, at every depth: a payload key (`error`, `err`, `reason`,
33
+ * `cause`, `message`, `stack`), any `Error`, and any error-shaped object (own `message` or `stack`:
34
+ * `throw { message }`, an upstream JSON error) become `describeErrorForLog` text (class + approved
35
+ * code, `object`/`string` for a non-Error); other plain objects and arrays are projected the same
36
+ * way; any other object (a class instance, a Map, a response) becomes a fixed placeholder; strings,
37
+ * numbers and booleans under any other key pass through as the caller's own structured fields
38
+ * (`runId`, counts). A caught value under a non-payload key is the log-safety gate's finding.
39
+ * Never throws: each field is read once inside a guard, so a throwing getter or a revoked Proxy
40
+ * becomes `[unreadable]` instead of replacing the failure being logged. Originals reach only a host
41
+ * `diagnostics` sink.
42
+ * @complexity O(200) projected entries per call (a shared budget; at most 50 per level, depth 4).
43
+ */
44
+ export declare function describeLogMeta(required: {
45
+ meta: Record<string, unknown>;
46
+ }, _optional?: Record<string, never>): Record<string, unknown>;
47
+ /**
48
+ * Minimal console adapter with a required host-owned prefix and structured metadata.
49
+ * The console line carries safe metadata only: a caught error's text or stack can quote untrusted
50
+ * input or a credential no redaction pattern knows. A host that wants the full error injects
51
+ * `diagnostics`, which receives every call unchanged; a throwing sink never stops the console line.
52
+ * @param required.prefix Host-owned line prefix ('' for none).
53
+ * @param optional.diagnostics Host sink for the full record.
54
+ * @complexity O(projected meta, see `describeLogMeta`) per call.
55
+ */
23
56
  export declare function createConsoleLogger({ prefix }: {
24
57
  prefix: string;
58
+ }, { diagnostics }?: {
59
+ diagnostics?: LogDiagnosticsSink;
25
60
  }): Logger;
26
61
  //# sourceMappingURL=logger.d.ts.map
@@ -1,17 +1,133 @@
1
- /** Minimal console adapter with a required host-owned prefix and structured metadata. */
2
- export function createConsoleLogger({ prefix }) {
3
- const write = (level, message, optional) => {
4
- const args = [prefix ? `${prefix} ${message}` : message];
1
+ import { describeErrorForLog } from '../model-facing-tool-errors.js';
2
+ /** Fixed words a default sink writes in place of a value it will not print. */
3
+ const OPAQUE_VALUE = '[object]';
4
+ const FUNCTION_VALUE = '[function]';
5
+ const SYMBOL_VALUE = '[symbol]';
6
+ const UNREADABLE_VALUE = '[unreadable]';
7
+ const TOO_DEEP_VALUE = '[nested too deep]';
8
+ const TOO_LARGE_VALUE = '[too many entries]';
9
+ /** Bounds per call: a log line is not a data dump, and a cycle must end. Per-level limits alone still
10
+ * allowed ~50^3 entries on one call (meta of arrays of objects), so one total budget is shared by
11
+ * the whole projection; once spent, objects become {@link TOO_LARGE_VALUE} and further keys drop. */
12
+ const MAX_META_DEPTH = 4;
13
+ const MAX_META_ENTRIES = 50;
14
+ const MAX_META_TOTAL_ENTRIES = 200;
15
+ /** Payload keys: whatever sits under them is a caught value or its text, so it is described, never
16
+ * printed. `message`/`stack` belong here too: the line already has its own message. */
17
+ const PAYLOAD_KEY = /^(error|err|reason|cause|message|stack)$/;
18
+ /**
19
+ * Meta as a default sink may write it, at every depth: a payload key (`error`, `err`, `reason`,
20
+ * `cause`, `message`, `stack`), any `Error`, and any error-shaped object (own `message` or `stack`:
21
+ * `throw { message }`, an upstream JSON error) become `describeErrorForLog` text (class + approved
22
+ * code, `object`/`string` for a non-Error); other plain objects and arrays are projected the same
23
+ * way; any other object (a class instance, a Map, a response) becomes a fixed placeholder; strings,
24
+ * numbers and booleans under any other key pass through as the caller's own structured fields
25
+ * (`runId`, counts). A caught value under a non-payload key is the log-safety gate's finding.
26
+ * Never throws: each field is read once inside a guard, so a throwing getter or a revoked Proxy
27
+ * becomes `[unreadable]` instead of replacing the failure being logged. Originals reach only a host
28
+ * `diagnostics` sink.
29
+ * @complexity O(200) projected entries per call (a shared budget; at most 50 per level, depth 4).
30
+ */
31
+ export function describeLogMeta(required, _optional = {}) {
32
+ try {
33
+ const { meta } = required;
34
+ // The whole meta can itself be a thrown plain object.
35
+ if (isErrorShaped({ value: meta }))
36
+ return { meta: describeErrorForLog({ err: meta }) };
37
+ return projectRecord({ record: meta, depth: 1, budget: { left: MAX_META_TOTAL_ENTRIES } });
38
+ }
39
+ catch {
40
+ // Even the key list could not be read (a Proxy whose `ownKeys` throws): fixed words only.
41
+ return { meta: UNREADABLE_VALUE };
42
+ }
43
+ }
44
+ /** An object carrying its own `message` or `stack`: a thrown value, whatever its prototype. May
45
+ * throw on a hostile Proxy; every caller is inside a guard. */
46
+ function isErrorShaped({ value }, _optional = {}) {
47
+ return Object.prototype.hasOwnProperty.call(value, 'message') || Object.prototype.hasOwnProperty.call(value, 'stack');
48
+ }
49
+ /** How many of `available` entries this container may project; takes them from the shared budget. */
50
+ function takeEntries({ available, budget }, _optional = {}) {
51
+ const count = Math.min(available, MAX_META_ENTRIES, budget.left);
52
+ budget.left -= count;
53
+ return count;
54
+ }
55
+ function projectRecord({ record, depth, budget }, _optional = {}) {
56
+ const allKeys = Object.keys(record);
57
+ const keys = allKeys.slice(0, takeEntries({ available: allKeys.length, budget }));
58
+ return Object.fromEntries(keys.map(key => [key, projectEntry({ key, read: () => record[key], depth, budget })]));
59
+ }
60
+ function projectArray({ list, depth, budget }, _optional = {}) {
61
+ const length = takeEntries({ available: list.length, budget });
62
+ return Array.from({ length }, (_, index) => projectEntry({ key: String(index), read: () => list[index], depth, budget }));
63
+ }
64
+ /** One field, read once and projected; a throwing read or check becomes fixed words. */
65
+ function projectEntry({ key, read, depth, budget }, _optional = {}) {
66
+ try {
67
+ const value = read();
68
+ if (PAYLOAD_KEY.test(key) || value instanceof Error)
69
+ return describeErrorForLog({ err: value });
70
+ return typeof value === 'object' && value !== null ? projectObject({ value, depth, budget }) : projectScalar({ value });
71
+ }
72
+ catch {
73
+ return UNREADABLE_VALUE;
74
+ }
75
+ }
76
+ function projectObject({ value, depth, budget }, _optional = {}) {
77
+ if (isErrorShaped({ value }))
78
+ return describeErrorForLog({ err: value });
79
+ if (depth >= MAX_META_DEPTH)
80
+ return TOO_DEEP_VALUE;
81
+ if (budget.left <= 0)
82
+ return TOO_LARGE_VALUE;
83
+ if (Array.isArray(value))
84
+ return projectArray({ list: value, depth: depth + 1, budget });
85
+ const prototype = Object.getPrototypeOf(value);
86
+ return prototype === Object.prototype || prototype === null ? projectRecord({ record: value, depth: depth + 1, budget }) : OPAQUE_VALUE;
87
+ }
88
+ function projectScalar({ value }, _optional = {}) {
89
+ if (typeof value === 'function')
90
+ return FUNCTION_VALUE;
91
+ if (typeof value === 'symbol')
92
+ return SYMBOL_VALUE;
93
+ // JSON cannot write a bigint; its digits are the caller's own number.
94
+ return typeof value === 'bigint' ? value.toString() : value;
95
+ }
96
+ /**
97
+ * Minimal console adapter with a required host-owned prefix and structured metadata.
98
+ * The console line carries safe metadata only: a caught error's text or stack can quote untrusted
99
+ * input or a credential no redaction pattern knows. A host that wants the full error injects
100
+ * `diagnostics`, which receives every call unchanged; a throwing sink never stops the console line.
101
+ * @param required.prefix Host-owned line prefix ('' for none).
102
+ * @param optional.diagnostics Host sink for the full record.
103
+ * @complexity O(projected meta, see `describeLogMeta`) per call.
104
+ */
105
+ export function createConsoleLogger({ prefix }, { diagnostics } = {}) {
106
+ const write = ({ level, message }, optional = {}) => {
107
+ const line = prefix ? `${prefix} ${message}` : message;
108
+ const args = [line];
5
109
  if (optional.meta !== undefined)
6
- args.push(optional.meta);
110
+ args.push(describeLogMeta({ meta: optional.meta }));
7
111
  if (optional.error !== undefined)
8
- args.push(optional.error);
112
+ args.push(describeErrorForLog({ err: optional.error }));
9
113
  console[level](...args);
114
+ if (diagnostics !== undefined)
115
+ deliverDiagnostics({ diagnostics, record: { level, message: line, ...optional } });
10
116
  };
11
117
  return {
12
- info: ({ message }, optional = {}) => write('info', message, optional),
13
- warn: ({ message }, optional = {}) => write('warn', message, optional),
14
- error: ({ message }, optional = {}) => write('error', message, optional),
118
+ info: ({ message }, optional = {}) => write({ level: 'info', message }, optional),
119
+ warn: ({ message }, optional = {}) => write({ level: 'warn', message }, optional),
120
+ error: ({ message }, optional = {}) => write({ level: 'error', message }, optional),
15
121
  };
16
122
  }
123
+ function deliverDiagnostics({ diagnostics, record }, _optional = {}) {
124
+ try {
125
+ diagnostics(record);
126
+ }
127
+ catch (sinkError) {
128
+ // The host sink failed: the console line above already recorded the call; record the sink's
129
+ // own failure (class only) so it is not lost, and never throw from a log call.
130
+ console.error('Diagnostics sink failed.', describeErrorForLog({ err: sinkError }));
131
+ }
132
+ }
17
133
  //# sourceMappingURL=logger.js.map
@@ -0,0 +1,24 @@
1
+ /** @file Attribute lookup that works on a DOM element and on a lightweight parsed node alike. */
2
+ /** The structural slice of an element the lookup needs; a DOM `Element` and a parsed-node object both fit. */
3
+ export interface NodeShape {
4
+ readonly hasAttribute?: (name: string) => boolean;
5
+ readonly attributes?: unknown;
6
+ }
7
+ /**
8
+ * `isComponent` (passed to `editor.Components.addType` — see `react/hooks/useInteractiveHtmlEditor.ts`)
9
+ * is not always called with a real DOM `Element`. GrapesJS also invokes it during headless/internal
10
+ * re-parses — confirmed live: `ComponentTextView.syncContent`'s re-parse of RTE-edited content
11
+ * (`Components.parseString` -> `ParserHtml.detectNode`) passes a lightweight parsed-node object
12
+ * instead, whose `attributes` is a plain object rather than a DOM `NamedNodeMap`, with no
13
+ * `.hasAttribute` method at all. Calling `.hasAttribute` unconditionally throws a `TypeError` inside
14
+ * GrapesJS's own parser on every RTE-driven edit, which silently aborts that re-parse before it ever
15
+ * reaches the component model. `el.attributes` is present on both shapes (a real `NamedNodeMap` or
16
+ * GrapesJS's plain object), so checking it directly is the one path guaranteed to work regardless of
17
+ * which parse mode called this. An `isProtectedElement` predicate passed to `InteractiveHtmlEditor`
18
+ * that checks attributes should use this instead of `el.hasAttribute` directly.
19
+ */
20
+ export declare function hasAttributeOnAnyNodeShape({ node, attribute }: {
21
+ node: NodeShape;
22
+ attribute: string;
23
+ }, _optional?: Record<string, never>): boolean;
24
+ //# sourceMappingURL=node-shape.d.ts.map
@@ -0,0 +1,21 @@
1
+ /** @file Attribute lookup that works on a DOM element and on a lightweight parsed node alike. */
2
+ /**
3
+ * `isComponent` (passed to `editor.Components.addType` — see `react/hooks/useInteractiveHtmlEditor.ts`)
4
+ * is not always called with a real DOM `Element`. GrapesJS also invokes it during headless/internal
5
+ * re-parses — confirmed live: `ComponentTextView.syncContent`'s re-parse of RTE-edited content
6
+ * (`Components.parseString` -> `ParserHtml.detectNode`) passes a lightweight parsed-node object
7
+ * instead, whose `attributes` is a plain object rather than a DOM `NamedNodeMap`, with no
8
+ * `.hasAttribute` method at all. Calling `.hasAttribute` unconditionally throws a `TypeError` inside
9
+ * GrapesJS's own parser on every RTE-driven edit, which silently aborts that re-parse before it ever
10
+ * reaches the component model. `el.attributes` is present on both shapes (a real `NamedNodeMap` or
11
+ * GrapesJS's plain object), so checking it directly is the one path guaranteed to work regardless of
12
+ * which parse mode called this. An `isProtectedElement` predicate passed to `InteractiveHtmlEditor`
13
+ * that checks attributes should use this instead of `el.hasAttribute` directly.
14
+ */
15
+ export function hasAttributeOnAnyNodeShape({ node, attribute }, _optional = {}) {
16
+ if (typeof node.hasAttribute === 'function')
17
+ return node.hasAttribute(attribute);
18
+ const { attributes } = node;
19
+ return typeof attributes === 'object' && attributes !== null && Object.prototype.hasOwnProperty.call(attributes, attribute);
20
+ }
21
+ //# sourceMappingURL=node-shape.js.map
@@ -4,8 +4,15 @@ export type ISODateTime = string;
4
4
  export interface Clock {
5
5
  nowMs(): number;
6
6
  }
7
- /** Default wall clock; inject a Clock to control time in application code. */
8
- export declare function createSystemClock(): Clock;
7
+ /** A host clock that reads ISO strings, the shape older host ports expose. */
8
+ export interface IsoClock {
9
+ nowIso(): string;
10
+ }
11
+ /** Adapts an ISO-string clock to {@link Clock}; a `Clock` passes through unchanged.
12
+ * @complexity O(1); each `nowMs()` parses one ISO string. */
13
+ export declare function toMsClock({ clock }: {
14
+ clock: Clock | IsoClock;
15
+ }, _optional?: Record<string, never>): Clock;
9
16
  /** Converts epoch milliseconds using the standard UTC ISO representation. Invalid time throws. */
10
17
  export declare function toIsoDateTime({ epochMs }: {
11
18
  epochMs: number;
@@ -1,6 +1,7 @@
1
- /** Default wall clock; inject a Clock to control time in application code. */
2
- export function createSystemClock() {
3
- return { nowMs: () => Date.now() };
1
+ /** Adapts an ISO-string clock to {@link Clock}; a `Clock` passes through unchanged.
2
+ * @complexity O(1); each `nowMs()` parses one ISO string. */
3
+ export function toMsClock({ clock }, _optional = {}) {
4
+ return "nowMs" in clock ? clock : { nowMs: () => Date.parse(clock.nowIso()) };
4
5
  }
5
6
  /** Converts epoch milliseconds using the standard UTC ISO representation. Invalid time throws. */
6
7
  export function toIsoDateTime({ epochMs }) {
@@ -42,6 +42,30 @@ function safeId(required, _optional = {}) {
42
42
  return '';
43
43
  }
44
44
  }
45
+ /** Fail fast when the configured default id is not a legal provider id. */
46
+ function assertDefaultProviderId({ contract, defaultProviderId }) {
47
+ if (defaultProviderId !== undefined && !PROVIDER_ID_PATTERN.test(defaultProviderId)) {
48
+ throw new ProviderRegistryError({ code: 'invalid_id', message: `${contract} default provider id '${defaultProviderId}' must match ${PROVIDER_ID_PATTERN.source}` });
49
+ }
50
+ }
51
+ /** Validate and register a plugin contribution; every rejection is recorded via `refuse`, never thrown. */
52
+ function contributeChecked({ input, contract, providers, refuse }, optional = {}) {
53
+ const { definition, pluginId, contract: declared } = input;
54
+ const providerId = String(definition.id);
55
+ if (declared !== undefined && declared !== contract) {
56
+ return refuse({ fault: { code: 'contract_mismatch', message: `plugin '${pluginId}' contributed provider '${providerId}' for contract '${declared}', not '${contract}'` }, pluginId, providerId });
57
+ }
58
+ const fault = definitionFault({ contract, definition }, { ...(optional.validate ? { validate: optional.validate } : {}) });
59
+ if (fault)
60
+ return refuse({ fault, pluginId, providerId });
61
+ const existing = providers.get(providerId);
62
+ if (existing) {
63
+ const owner = existing.pluginId === undefined ? 'the built-in provider' : `plugin '${existing.pluginId}'`;
64
+ return refuse({ fault: { code: 'duplicate', message: `${contract} provider '${providerId}' from plugin '${pluginId}' was not loaded: already registered by ${owner}` }, pluginId, providerId });
65
+ }
66
+ providers.set(providerId, frozenEntry({ definition, origin: 'plugin' }, { pluginId }));
67
+ return true;
68
+ }
45
69
  function frozenEntry(required, optional = {}) {
46
70
  const { id, provider, label } = required.definition;
47
71
  return Object.freeze({
@@ -65,9 +89,7 @@ function frozenEntry(required, optional = {}) {
65
89
  export function createProviderRegistry(required, optional = {}) {
66
90
  const { contract } = required;
67
91
  const { defaultProviderId, validate } = optional;
68
- if (defaultProviderId !== undefined && !PROVIDER_ID_PATTERN.test(defaultProviderId)) {
69
- throw new ProviderRegistryError({ code: 'invalid_id', message: `${contract} default provider id '${defaultProviderId}' must match ${PROVIDER_ID_PATTERN.source}` });
70
- }
92
+ assertDefaultProviderId({ contract, defaultProviderId });
71
93
  const providers = new Map();
72
94
  const refused = [];
73
95
  const refuse = (input) => {
@@ -94,7 +116,7 @@ export function createProviderRegistry(required, optional = {}) {
94
116
  // Third-party input: a throwing validator, id or provider getter is refused, never propagated
95
117
  // (core registrations keep the throwing policy above).
96
118
  try {
97
- return contributeChecked(input);
119
+ return contributeChecked({ input, contract, providers, refuse }, { ...(validate ? { validate } : {}) });
98
120
  }
99
121
  catch {
100
122
  return refuse({ fault: { code: 'invalid_provider', message: `${contract} provider from plugin '${input.pluginId}' was not loaded: its definition could not be validated` }, pluginId: input.pluginId, providerId: safeId({ definition: input.definition }) });
@@ -106,22 +128,6 @@ export function createProviderRegistry(required, optional = {}) {
106
128
  getDefault() { return defaultProviderId === undefined ? undefined : providers.get(defaultProviderId); },
107
129
  refusals() { return Object.freeze([...refused]); },
108
130
  };
109
- function contributeChecked({ definition, pluginId, contract: declared }) {
110
- const providerId = String(definition.id);
111
- if (declared !== undefined && declared !== contract) {
112
- return refuse({ fault: { code: 'contract_mismatch', message: `plugin '${pluginId}' contributed provider '${providerId}' for contract '${declared}', not '${contract}'` }, pluginId, providerId });
113
- }
114
- const fault = definitionFault({ contract, definition }, { ...(validate ? { validate } : {}) });
115
- if (fault)
116
- return refuse({ fault, pluginId, providerId });
117
- const existing = providers.get(providerId);
118
- if (existing) {
119
- const owner = existing.pluginId === undefined ? 'the built-in provider' : `plugin '${existing.pluginId}'`;
120
- return refuse({ fault: { code: 'duplicate', message: `${contract} provider '${providerId}' from plugin '${pluginId}' was not loaded: already registered by ${owner}` }, pluginId, providerId });
121
- }
122
- providers.set(providerId, frozenEntry({ definition, origin: 'plugin' }, { pluginId }));
123
- return true;
124
- }
125
131
  for (const definition of optional.seed ?? [])
126
132
  registry.register({ definition });
127
133
  return registry;