@composable-os/cli 0.0.0-stage → 0.1.0-beta.11

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 (184) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +24 -2
  3. package/dist/accounts-UHYLCLEY.js +45 -0
  4. package/dist/blocks-5IFU25J6.js +233 -0
  5. package/dist/chunk-2ABSVMGB.js +13 -0
  6. package/dist/chunk-2IVEVPMY.js +669 -0
  7. package/dist/chunk-2TWV3SVB.js +349 -0
  8. package/dist/chunk-2XC5JLBO.js +1931 -0
  9. package/dist/chunk-324WJXNP.js +320 -0
  10. package/dist/chunk-5KSXSK7Y.js +47 -0
  11. package/dist/chunk-6ELZRNUU.js +116 -0
  12. package/dist/chunk-6UWRT4VM.js +220 -0
  13. package/dist/chunk-6WGFA2IV.js +643 -0
  14. package/dist/chunk-6XTU2MTP.js +11278 -0
  15. package/dist/chunk-7CQGMVDO.js +63 -0
  16. package/dist/chunk-7D4GKZOX.js +615 -0
  17. package/dist/chunk-7OGCMQXG.js +284 -0
  18. package/dist/chunk-DHS2CV2M.js +139 -0
  19. package/dist/chunk-DU6OIFOU.js +2358 -0
  20. package/dist/chunk-E4WCYTCT.js +347 -0
  21. package/dist/chunk-E64SG24J.js +88 -0
  22. package/dist/chunk-FJIZGS5Q.js +698 -0
  23. package/dist/chunk-GYTEW66E.js +50 -0
  24. package/dist/chunk-HDIOVFAZ.js +544 -0
  25. package/dist/chunk-K34UKWEI.js +298 -0
  26. package/dist/chunk-KGHA67HG.js +765 -0
  27. package/dist/chunk-LAAL4YGR.js +365 -0
  28. package/dist/chunk-LO6WGU5Y.js +26189 -0
  29. package/dist/chunk-MBIKVRAC.js +1425 -0
  30. package/dist/chunk-P6UWZ6QQ.js +426 -0
  31. package/dist/chunk-PDD2ETVF.js +1302 -0
  32. package/dist/chunk-UB4I2QKR.js +31575 -0
  33. package/dist/chunk-WHKJGF36.js +2418 -0
  34. package/dist/chunk-XIDLW3EP.js +15471 -0
  35. package/dist/chunk-YFTLIEWU.js +504 -0
  36. package/dist/chunk-YNUZRTPH.js +182 -0
  37. package/dist/chunk-ZAWES2UD.js +9364 -0
  38. package/dist/chunk-ZZFWMVJO.js +704 -0
  39. package/dist/cli-5UNY5G5L.js +136 -0
  40. package/dist/cli-UYZMVQMR.js +24534 -0
  41. package/dist/cli.js +25 -0
  42. package/dist/client-repo-SE4EKG6W.js +55 -0
  43. package/dist/create.js +25 -0
  44. package/dist/fields-FTWWMD7N.js +50 -0
  45. package/dist/grants-LOW6TSWD.js +32 -0
  46. package/dist/invoke-6KVT6WJI.js +41 -0
  47. package/dist/moves-E2HKYCTK.js +41 -0
  48. package/dist/order-U4KZLLSJ.js +19 -0
  49. package/dist/person-UHLVBVLR.js +67 -0
  50. package/dist/plan-on-sale-TJPFCNL7.js +26 -0
  51. package/dist/platform/migrations/0001_init.sql +59 -0
  52. package/dist/platform/migrations/0002_users_settings.sql +34 -0
  53. package/dist/platform/migrations/0003_people_organisations.sql +225 -0
  54. package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
  55. package/dist/platform/migrations/0005_views_audit.sql +79 -0
  56. package/dist/platform/migrations/0006_search.sql +223 -0
  57. package/dist/platform/migrations/0007_crm_views.sql +141 -0
  58. package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
  59. package/dist/platform/migrations/0010_approval_queue.sql +90 -0
  60. package/dist/platform/migrations/0011_connected_apps.sql +36 -0
  61. package/dist/platform/migrations/0020_extensions.sql +373 -0
  62. package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
  63. package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
  64. package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
  65. package/dist/platform/migrations/0061_audit_retention.sql +95 -0
  66. package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
  67. package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
  68. package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
  69. package/dist/platform/migrations/0065_storage_stats.sql +13 -0
  70. package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
  71. package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
  72. package/dist/platform/migrations/0100_stage_history.sql +54 -0
  73. package/dist/platform/migrations/0110_integrations.sql +103 -0
  74. package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
  75. package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
  76. package/dist/platform/migrations/0130_automations.sql +113 -0
  77. package/dist/platform/migrations/0131_notifications.sql +29 -0
  78. package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
  79. package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
  80. package/dist/platform/migrations/0160_releases.sql +41 -0
  81. package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
  82. package/dist/platform/migrations/0170_automation_connections.sql +32 -0
  83. package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
  84. package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
  85. package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
  86. package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
  87. package/dist/platform/migrations/0210_daily_digest.sql +33 -0
  88. package/dist/platform/migrations/0220_entitlements.sql +13 -0
  89. package/dist/platform/migrations/0221_support_grants.sql +33 -0
  90. package/dist/platform/migrations/0250_judge.sql +11 -0
  91. package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
  92. package/dist/platform/migrations/0252_judge_usage.sql +14 -0
  93. package/dist/platform/migrations/0255_summary_checks.sql +9 -0
  94. package/dist/platform/migrations/0256_outbound_check.sql +9 -0
  95. package/dist/platform/migrations/0260_ai_usage.sql +20 -0
  96. package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
  97. package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
  98. package/dist/platform/migrations/0320_duplicates.sql +41 -0
  99. package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
  100. package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
  101. package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
  102. package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
  103. package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
  104. package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
  105. package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
  106. package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
  107. package/dist/platform/migrations/0362_voice_usage.sql +17 -0
  108. package/dist/platform/migrations/0365_routines.sql +38 -0
  109. package/dist/platform/migrations/0370_approval_execution.sql +20 -0
  110. package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
  111. package/dist/platform/migrations/0380_rec_views.sql +94 -0
  112. package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
  113. package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
  114. package/dist/platform/migrations/0402_erase_requests.sql +34 -0
  115. package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
  116. package/dist/platform/migrations/0411_device_sessions.sql +33 -0
  117. package/dist/platform/migrations/0420_transition_history.sql +100 -0
  118. package/dist/platform/migrations/0421_orders.sql +134 -0
  119. package/dist/platform/migrations/0422_order_payments.sql +109 -0
  120. package/dist/platform/migrations/0440_capacity.sql +100 -0
  121. package/dist/platform/migrations/0441_capacity_views.sql +40 -0
  122. package/dist/platform/migrations/0450_order_grants.sql +21 -0
  123. package/dist/platform/migrations/0451_pack_roles.sql +18 -0
  124. package/dist/platform/migrations/0460_content.sql +59 -0
  125. package/dist/platform/migrations/0461_media.sql +52 -0
  126. package/dist/platform/migrations/0470_publish_versions.sql +36 -0
  127. package/dist/platform/migrations/0471_permission_grants.sql +18 -0
  128. package/dist/platform/migrations/0490_staff_invites.sql +40 -0
  129. package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
  130. package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
  131. package/dist/platform/migrations/0500_published_media_field.sql +25 -0
  132. package/dist/platform/migrations/0501_import_keys.sql +23 -0
  133. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  134. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  135. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  136. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  137. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  138. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  139. package/dist/platform/migrations/0533_allowances.sql +262 -0
  140. package/dist/platform/migrations/0560_recurring.sql +75 -0
  141. package/dist/platform/migrations/0580_subscription_grants.sql +21 -0
  142. package/dist/platform/migrations/0581_once_per_person.sql +34 -0
  143. package/dist/platform/migrations/0600_tool_actions_ran_at_queue.sql +22 -0
  144. package/dist/platform/migrations/0610_waitlists.sql +54 -0
  145. package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
  146. package/dist/platform/migrations/0650_person_links.sql +90 -0
  147. package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
  148. package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
  149. package/dist/platform/sdk/allowance.ts +522 -0
  150. package/dist/platform/sdk/automation-check.ts +534 -0
  151. package/dist/platform/sdk/automation.ts +743 -0
  152. package/dist/platform/sdk/behaviour.ts +215 -0
  153. package/dist/platform/sdk/capacity.ts +303 -0
  154. package/dist/platform/sdk/contract.ts +909 -0
  155. package/dist/platform/sdk/document.ts +935 -0
  156. package/dist/platform/sdk/field-types.ts +111 -0
  157. package/dist/platform/sdk/formula/ast.ts +72 -0
  158. package/dist/platform/sdk/formula/compile.ts +454 -0
  159. package/dist/platform/sdk/formula/index.ts +4 -0
  160. package/dist/platform/sdk/formula/parser.ts +417 -0
  161. package/dist/platform/sdk/index.ts +36 -0
  162. package/dist/platform/sdk/manifest.ts +1785 -0
  163. package/dist/platform/sdk/media.ts +108 -0
  164. package/dist/platform/sdk/permissions.ts +60 -0
  165. package/dist/platform/sdk/recurring.ts +321 -0
  166. package/dist/platform/sdk/renamed.ts +63 -0
  167. package/dist/platform/sdk/rich-text-fixture.ts +68 -0
  168. package/dist/platform/sdk/rich-text.ts +221 -0
  169. package/dist/platform/sdk/runtime.ts +410 -0
  170. package/dist/platform/sdk/sellable.ts +1138 -0
  171. package/dist/platform/sdk/slug.ts +25 -0
  172. package/dist/platform/sdk/states.ts +598 -0
  173. package/dist/platform/sdk/testing.ts +847 -0
  174. package/dist/platform/sdk/unique.ts +81 -0
  175. package/dist/products-2H5DR232.js +11 -0
  176. package/dist/run-7P4RQALH.js +648 -0
  177. package/dist/run-PO3W5BFA.js +508 -0
  178. package/dist/run-ZCGFMEZF.js +309 -0
  179. package/dist/src-CRO35DYY.js +46 -0
  180. package/dist/src-I3IJ4NKC.js +354 -0
  181. package/dist/token-MOJUA2U6.js +70 -0
  182. package/dist/token-util-TENRN4V7.js +6 -0
  183. package/dist/visibility-TVXZ67FD.js +41 -0
  184. package/package.json +33 -4
@@ -0,0 +1,935 @@
1
+ // The structured document field (stage 41, ADR 0445): a field whose value is one JSON document,
2
+ // checked against a schema the object declares. A program's layout is one; stage 28's `richText`
3
+ // is one fixed schema of this kind.
4
+ //
5
+ // layout: {
6
+ // type: "document",
7
+ // label: "Layout",
8
+ // schema: { root: { type: "object", fields: { weeks: { type: "array", max: 52, of: ... } } } },
9
+ // maxBytes: 262_144,
10
+ // paths: { weekCount: { label: "Weeks", path: "weeks", count: true } },
11
+ // }
12
+ //
13
+ // The schema language is plain data, so a manifest carries it and the host, the check and the
14
+ // test host read the same declaration. It is small on purpose: objects with named fields (every
15
+ // key known, nothing else accepted), lists with a maximum, text with a maximum, numbers with
16
+ // bounds, true or false, one of a fixed set of words, the id of a record of a named object, a
17
+ // tagged union of objects, and named definitions a schema may use again (for nesting, as rich
18
+ // text's lists do). There is no free pattern: a text node may name the characters it allows.
19
+ //
20
+ // Validation never repairs a value. It returns every fault (up to a limit) with the path of the
21
+ // fault, as a list of keys and indexes from the document's root.
22
+ //
23
+ // An object node may be `private`: removed from what a customer or the public reads
24
+ // (`redactDocument`), unless its `unless` key is true (a coach's note marked as shown to
25
+ // members). The host does that at the visibility seam; staff read the whole document.
26
+ //
27
+ // An object node may also be for `holders` (stage 42, ADR 0477): removed, or some of its keys
28
+ // removed, from what an outsider reads unless they hold access to the record (the seam's one
29
+ // question, visibility/access.ts) or its `unless` key is true (a lesson marked as a free
30
+ // preview). A `ref` to `media` may name the kind of item it takes (`media: "video"`).
31
+
32
+ /** The most a document may be, in bytes of its JSON, whatever a field declares. */
33
+ export const DOCUMENT_MAX_BYTES = 524_288;
34
+ /** A field that declares no `maxBytes`. */
35
+ export const DOCUMENT_DEFAULT_BYTES = 65_536;
36
+ /** The deepest a value may nest (objects and lists), and a schema. */
37
+ export const DOCUMENT_MAX_DEPTH = 24;
38
+ /** The most entries any one list may declare. */
39
+ export const DOCUMENT_MAX_LIST = 1000;
40
+ /** The longest a text node may declare, and the default when it declares none. */
41
+ export const DOCUMENT_MAX_TEXT = 20_000;
42
+ export const DOCUMENT_DEFAULT_TEXT = 1000;
43
+ /** Faults reported for one value, at most. */
44
+ export const DOCUMENT_MAX_ISSUES = 20;
45
+ /** Declared paths (view columns) per field, at most. */
46
+ export const DOCUMENT_MAX_PATHS = 12;
47
+
48
+ const ID_RE = /^[a-z][a-z0-9]{0,9}_[A-Za-z0-9]{1,60}$/;
49
+ const KEY_RE = /^[a-z][a-zA-Z0-9]{0,39}$/;
50
+ const OBJECT_RE = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)?$/;
51
+ // Control characters other than tab and newline (and a lone carriage return) are refused.
52
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it finds.
53
+ const CONTROL_RE = /[\u0000-\u0008\u000b-\u001f\u007f]/;
54
+ // Markup a text node with `noMarkup` refuses (ADR 0440): the start of a tag, closing tag, comment
55
+ // or processing instruction, and any character reference, named or numeric.
56
+ const MARKUP_RE = /<[A-Za-z!/?]|&(?:#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z][A-Za-z0-9]*);/;
57
+ // What a link may be. No quote, angle bracket, backslash, backtick or space anywhere.
58
+ const URL_TAIL = "[^\\s<>\"'`\\\\]*";
59
+ const WEB_RE = new RegExp(
60
+ `^https?://[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?(?::[0-9]{1,5})?(?:[/?#]${URL_TAIL})?$`,
61
+ "i",
62
+ );
63
+ const MAILTO_RE = /^mailto:[^\s<>"'`\\:/][^\s<>"'`\\]*$/i;
64
+ const TEL_RE = /^tel:[+0-9 ().-]{3,40}$/i;
65
+ const PATH_RE = new RegExp(`^/(?![/\\\\])${URL_TAIL}$`);
66
+ const ANCHOR_RE = /^#[A-Za-z0-9_-]{1,100}$/;
67
+
68
+ /** Whether `value` is a link of the given kind (a text node's `href`). */
69
+ export function isDocumentHref(value: string, kind: "web" | "link"): boolean {
70
+ if (WEB_RE.test(value)) return true;
71
+ if (kind === "web") return false;
72
+ return (
73
+ MAILTO_RE.test(value) || TEL_RE.test(value) || PATH_RE.test(value) || ANCHOR_RE.test(value)
74
+ );
75
+ }
76
+
77
+ /** Whether `value` holds markup a `noMarkup` text node refuses. */
78
+ export function hasMarkup(value: string): boolean {
79
+ return MARKUP_RE.test(value);
80
+ }
81
+
82
+ interface NodeBase {
83
+ /** For people and models: what the node holds. */
84
+ description?: string;
85
+ /** In an object's `fields`: the key may be left out. */
86
+ optional?: boolean;
87
+ }
88
+
89
+ export interface DocumentObjectNode extends NodeBase {
90
+ type: "object";
91
+ fields: Record<string, DocumentNode>;
92
+ /**
93
+ * Removed when a customer or the public reads the document. `{ unless: "<key>" }` keeps it when
94
+ * that boolean key of the object is true (a note marked as shown to members).
95
+ */
96
+ private?: true | { unless: string };
97
+ /**
98
+ * For holders only (stage 42, ADR 0477): removed when someone outside the org who does not
99
+ * hold access to the record reads the document. `true` or `{ unless }` removes the whole object,
100
+ * as `private` does; `{ keys, unless? }` removes only those keys of it (a lesson's video and
101
+ * notes, while its title stays). `unless` names a boolean key of this object that keeps it (a
102
+ * free preview).
103
+ */
104
+ holders?: DocumentHolders;
105
+ }
106
+
107
+ /** What of an object node is for holders only: see `DocumentObjectNode.holders`. */
108
+ export type DocumentHolders =
109
+ | true
110
+ | { unless: string; keys?: undefined }
111
+ | { keys: readonly string[]; unless?: string };
112
+
113
+ /** The kinds of media item (stage 42, ADR 0475). */
114
+ export type DocumentMediaKind = "image" | "video" | "file";
115
+ export interface DocumentArrayNode extends NodeBase {
116
+ type: "array";
117
+ of: DocumentNode;
118
+ max: number;
119
+ min?: number;
120
+ /** A key of the listed objects whose values must differ (labels, level numbers). */
121
+ unique?: string;
122
+ /**
123
+ * With `unique`: the key's values must differ across every list this node holds in the
124
+ * document, not only within one (stage 42: a lesson's key across all sections, since progress
125
+ * is kept by it).
126
+ */
127
+ uniqueAcross?: boolean;
128
+ }
129
+ export interface DocumentTextNode extends NodeBase {
130
+ type: "text";
131
+ /** Characters at most. Default 1000. */
132
+ max?: number;
133
+ min?: number;
134
+ /** Newlines allowed. */
135
+ multiline?: boolean;
136
+ /** The only characters allowed, e.g. "0123456789X" for a tempo. */
137
+ chars?: string;
138
+ /**
139
+ * Refuses markup (stage 28, ADR 0440): an HTML tag, closing tag, comment or processing
140
+ * instruction (`<b`, `</`, `<!`, `<?`) and a character reference (`&amp;`, `&#60;`). A lone
141
+ * `<` before a space or a digit is text. Rich text's text is always this.
142
+ */
143
+ noMarkup?: boolean;
144
+ /**
145
+ * The text is a link (stage 28, ADR 0440). `web`: an absolute `http:` or `https:` URL.
146
+ * `link`: that, or `mailto:`, `tel:`, a path on the site (`/about`, never `//host`) or an
147
+ * anchor (`#top`). Any other scheme (`javascript:`, `data:`, `vbscript:`) is refused.
148
+ */
149
+ href?: "web" | "link";
150
+ }
151
+ export interface DocumentNumberNode extends NodeBase {
152
+ type: "number";
153
+ min?: number;
154
+ max?: number;
155
+ integer?: boolean;
156
+ /** Multiples of this from `min` (or 0): 0.5 for an RPE. */
157
+ step?: number;
158
+ }
159
+ export interface DocumentBooleanNode extends NodeBase {
160
+ type: "boolean";
161
+ }
162
+ export interface DocumentChoiceNode extends NodeBase {
163
+ type: "choice";
164
+ options: readonly string[];
165
+ }
166
+ /** The id of a live record of `to`, checked by the host when the document is written. */
167
+ export interface DocumentRefNode extends NodeBase {
168
+ type: "ref";
169
+ to: string;
170
+ /**
171
+ * For a ref to `media` (stage 42, ADR 0475): the kind of item it takes, checked by the host on
172
+ * write; a video must also be ready. Left out, any live item.
173
+ */
174
+ media?: DocumentMediaKind;
175
+ }
176
+ /** One of several object shapes, told apart by the value of `tag`. */
177
+ export interface DocumentUnionNode extends NodeBase {
178
+ type: "union";
179
+ tag: string;
180
+ variants: Record<string, DocumentObjectNode>;
181
+ }
182
+ /** A named definition of the schema's `defs`. */
183
+ export interface DocumentUseNode extends NodeBase {
184
+ type: "use";
185
+ def: string;
186
+ }
187
+
188
+ export type DocumentNode =
189
+ | DocumentObjectNode
190
+ | DocumentArrayNode
191
+ | DocumentTextNode
192
+ | DocumentNumberNode
193
+ | DocumentBooleanNode
194
+ | DocumentChoiceNode
195
+ | DocumentRefNode
196
+ | DocumentUnionNode
197
+ | DocumentUseNode;
198
+
199
+ export interface DocumentSchema {
200
+ root: DocumentObjectNode;
201
+ defs?: Record<string, DocumentNode>;
202
+ }
203
+
204
+ /**
205
+ * A value inside the document that the object's rec_* view shows as a column of its own, which
206
+ * lists, filters, sorts and dashboards read like any field: `path` is keys from the root through
207
+ * objects only (`title`, `meta.level`). With `count`, the path names a list and the column is its
208
+ * length.
209
+ */
210
+ export interface DocumentPathSpec {
211
+ label: string;
212
+ path: string;
213
+ count?: boolean;
214
+ description?: string;
215
+ }
216
+
217
+ /** What a declared path reads as: the type of its column. */
218
+ export type DocumentPathType = "text" | "number" | "boolean" | "id";
219
+
220
+ /** A fault in a value: where, and what is wrong. */
221
+ export interface DocumentIssue {
222
+ path: (string | number)[];
223
+ message: string;
224
+ }
225
+
226
+ export type DocumentResult =
227
+ | { ok: true; value: unknown; bytes: number }
228
+ | { ok: false; issues: DocumentIssue[] };
229
+
230
+ const isObject = (value: unknown): value is Record<string, unknown> =>
231
+ typeof value === "object" && value !== null && !Array.isArray(value);
232
+
233
+ /** Bytes of a value's JSON, as stored. */
234
+ export function documentBytes(value: unknown): number {
235
+ // UTF-8 length by hand: the SDK is type-checked with no DOM or runtime library.
236
+ const text = JSON.stringify(value) ?? "";
237
+ let bytes = 0;
238
+ for (const char of text) {
239
+ const code = char.codePointAt(0) ?? 0;
240
+ bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
241
+ }
242
+ return bytes;
243
+ }
244
+
245
+ // --- Checking a schema ---------------------------------------------------------------------------
246
+
247
+ /**
248
+ * What is wrong with a declared schema, as `[path, message]` pairs (the path from the schema's
249
+ * own root: `root.fields.weeks.of`). Empty when nothing is. `knownObjects`, when given, holds the
250
+ * objects a `ref` may name.
251
+ */
252
+ export function checkDocumentSchema(
253
+ schema: unknown,
254
+ knownObjects?: ReadonlySet<string>,
255
+ ): [string, string][] {
256
+ const problems: [string, string][] = [];
257
+ const add = (path: string, message: string) => {
258
+ if (problems.length < 50) problems.push([path, message]);
259
+ };
260
+ if (!isObject(schema)) {
261
+ add("", "A document schema is an object with a `root` object node");
262
+ return problems;
263
+ }
264
+ for (const key of Object.keys(schema)) {
265
+ if (key !== "root" && key !== "defs") add(key, `Unknown key "${key}" (root, defs)`);
266
+ }
267
+ const defs = isObject(schema.defs) ? schema.defs : {};
268
+ if (schema.defs !== undefined && !isObject(schema.defs)) add("defs", "defs is an object");
269
+ for (const name of Object.keys(defs)) {
270
+ if (!KEY_RE.test(name)) add(`defs.${name}`, "A definition's name is camelCase");
271
+ }
272
+
273
+ const node = (path: string, value: unknown, depth: number, inFields: boolean): void => {
274
+ if (depth > DOCUMENT_MAX_DEPTH) {
275
+ add(path, `The schema nests deeper than ${DOCUMENT_MAX_DEPTH}`);
276
+ return;
277
+ }
278
+ if (!isObject(value)) {
279
+ add(path, "A node is an object with a `type`");
280
+ return;
281
+ }
282
+ const allowed = new Set(["type", "description", "optional"]);
283
+ const expect = (...keys: string[]) => {
284
+ for (const key of keys) allowed.add(key);
285
+ };
286
+ if (value.optional !== undefined && (typeof value.optional !== "boolean" || !inFields)) {
287
+ add(`${path}.optional`, "optional is true or false, on a field of an object");
288
+ }
289
+ if (value.description !== undefined && typeof value.description !== "string") {
290
+ add(`${path}.description`, "description is text");
291
+ }
292
+ const num = (key: string, opts: { int?: boolean; min?: number; max?: number } = {}) => {
293
+ const v = value[key];
294
+ if (v === undefined) return undefined;
295
+ if (typeof v !== "number" || !Number.isFinite(v) || (opts.int && !Number.isInteger(v))) {
296
+ add(`${path}.${key}`, `${key} is ${opts.int ? "a whole number" : "a number"}`);
297
+ return undefined;
298
+ }
299
+ if (opts.min !== undefined && v < opts.min)
300
+ add(`${path}.${key}`, `${key} is at least ${opts.min}`);
301
+ if (opts.max !== undefined && v > opts.max)
302
+ add(`${path}.${key}`, `${key} is at most ${opts.max}`);
303
+ return v;
304
+ };
305
+ switch (value.type) {
306
+ case "object": {
307
+ expect("fields", "private", "holders");
308
+ object(path, value, depth);
309
+ break;
310
+ }
311
+ case "array": {
312
+ expect("of", "max", "min", "unique", "uniqueAcross");
313
+ if (value.uniqueAcross !== undefined && (value.uniqueAcross !== true || !value.unique)) {
314
+ add(`${path}.uniqueAcross`, "uniqueAcross is true, beside unique");
315
+ }
316
+ const max = num("max", { int: true, min: 1, max: DOCUMENT_MAX_LIST });
317
+ if (value.max === undefined) add(`${path}.max`, "A list declares its most entries (max)");
318
+ const min = num("min", { int: true, min: 0 });
319
+ if (min !== undefined && max !== undefined && min > max)
320
+ add(`${path}.min`, "min is above max");
321
+ node(`${path}.of`, value.of, depth + 1, false);
322
+ if (value.unique !== undefined) {
323
+ const of = resolve(value.of);
324
+ // The key of an object, or of every variant of a union.
325
+ const shapes =
326
+ of?.type === "object"
327
+ ? [of]
328
+ : of?.type === "union"
329
+ ? Object.values(of.variants ?? {})
330
+ : [];
331
+ const keyNodes = shapes.map((shape) => resolve(shape.fields?.[String(value.unique)]));
332
+ if (
333
+ typeof value.unique !== "string" ||
334
+ !keyNodes.length ||
335
+ keyNodes.some((n) => !n || !["text", "number", "choice", "ref"].includes(n.type))
336
+ ) {
337
+ add(
338
+ `${path}.unique`,
339
+ "unique names a text, number, choice or ref key of the listed objects",
340
+ );
341
+ }
342
+ }
343
+ break;
344
+ }
345
+ case "text": {
346
+ expect("max", "min", "multiline", "chars", "noMarkup", "href");
347
+ if (value.noMarkup !== undefined && typeof value.noMarkup !== "boolean") {
348
+ add(`${path}.noMarkup`, "noMarkup is true or false");
349
+ }
350
+ if (value.href !== undefined && value.href !== "web" && value.href !== "link") {
351
+ add(`${path}.href`, "href is web or link");
352
+ }
353
+ const max = num("max", { int: true, min: 1, max: DOCUMENT_MAX_TEXT });
354
+ const min = num("min", { int: true, min: 0 });
355
+ if (min !== undefined && (max ?? DOCUMENT_DEFAULT_TEXT) < min)
356
+ add(`${path}.min`, "min is above max");
357
+ if (value.multiline !== undefined && typeof value.multiline !== "boolean") {
358
+ add(`${path}.multiline`, "multiline is true or false");
359
+ }
360
+ if (
361
+ value.chars !== undefined &&
362
+ (typeof value.chars !== "string" || !value.chars.length || value.chars.length > 200)
363
+ ) {
364
+ add(`${path}.chars`, "chars is the allowed characters, 1 to 200 of them");
365
+ }
366
+ break;
367
+ }
368
+ case "number": {
369
+ expect("min", "max", "integer", "step");
370
+ const min = num("min");
371
+ const max = num("max");
372
+ if (min !== undefined && max !== undefined && min > max)
373
+ add(`${path}.min`, "min is above max");
374
+ if (value.integer !== undefined && typeof value.integer !== "boolean") {
375
+ add(`${path}.integer`, "integer is true or false");
376
+ }
377
+ const step = num("step");
378
+ if (step !== undefined && step <= 0) add(`${path}.step`, "step is above 0");
379
+ break;
380
+ }
381
+ case "boolean":
382
+ break;
383
+ case "choice": {
384
+ expect("options");
385
+ const options = value.options;
386
+ if (
387
+ !Array.isArray(options) ||
388
+ !options.length ||
389
+ options.length > 100 ||
390
+ options.some((o) => typeof o !== "string" || !o.length || o.length > 100)
391
+ ) {
392
+ add(`${path}.options`, "A choice lists 1 to 100 words");
393
+ } else if (new Set(options).size !== options.length) {
394
+ add(`${path}.options`, "A choice lists each word once");
395
+ }
396
+ break;
397
+ }
398
+ case "ref": {
399
+ expect("to", "media");
400
+ if (typeof value.to !== "string" || !OBJECT_RE.test(value.to)) {
401
+ add(`${path}.to`, "A ref names an object: `<extension>.<object>` or a core object");
402
+ } else if (knownObjects && !knownObjects.has(value.to)) {
403
+ add(`${path}.to`, `Unknown object "${value.to}"`);
404
+ }
405
+ if (value.media !== undefined) {
406
+ if (value.to !== "media") add(`${path}.media`, "media is for a ref to media");
407
+ else if (!["image", "video", "file"].includes(String(value.media))) {
408
+ add(`${path}.media`, "media is image, video or file");
409
+ }
410
+ }
411
+ break;
412
+ }
413
+ case "union": {
414
+ expect("tag", "variants");
415
+ if (typeof value.tag !== "string" || !KEY_RE.test(value.tag)) {
416
+ add(`${path}.tag`, "A union's tag is a camelCase key");
417
+ }
418
+ if (!isObject(value.variants) || !Object.keys(value.variants).length) {
419
+ add(`${path}.variants`, "A union has at least one variant");
420
+ break;
421
+ }
422
+ for (const [name, variant] of Object.entries(value.variants)) {
423
+ const vp = `${path}.variants.${name}`;
424
+ if (!name.length || name.length > 100) add(vp, "A variant's name is 1 to 100 characters");
425
+ if (!isObject(variant) || variant.type !== "object") {
426
+ add(vp, "A variant is an object node");
427
+ continue;
428
+ }
429
+ if (
430
+ isObject(variant.fields) &&
431
+ typeof value.tag === "string" &&
432
+ value.tag in variant.fields
433
+ ) {
434
+ add(
435
+ `${vp}.fields.${value.tag}`,
436
+ "A variant does not declare its union's tag: the host does",
437
+ );
438
+ }
439
+ node(vp, variant, depth + 1, false);
440
+ }
441
+ break;
442
+ }
443
+ case "use": {
444
+ expect("def");
445
+ if (typeof value.def !== "string" || !Object.hasOwn(defs, value.def)) {
446
+ add(`${path}.def`, `"${String(value.def)}" is not one of the schema's defs`);
447
+ }
448
+ break;
449
+ }
450
+ default:
451
+ add(
452
+ `${path}.type`,
453
+ "type is one of object, array, text, number, boolean, choice, ref, union, use",
454
+ );
455
+ return;
456
+ }
457
+ for (const key of Object.keys(value)) {
458
+ if (!allowed.has(key))
459
+ add(`${path}.${key}`, `Unknown key "${key}" on a ${String(value.type)} node`);
460
+ }
461
+ };
462
+
463
+ const object = (path: string, value: Record<string, unknown>, depth: number) => {
464
+ if (!isObject(value.fields)) {
465
+ add(`${path}.fields`, "An object node lists its fields");
466
+ return;
467
+ }
468
+ const keys = Object.keys(value.fields);
469
+ if (keys.length > 100) add(`${path}.fields`, "An object has at most 100 fields");
470
+ for (const key of keys) {
471
+ if (!KEY_RE.test(key)) add(`${path}.fields.${key}`, "A field's key is camelCase");
472
+ node(`${path}.fields.${key}`, value.fields[key], depth + 1, true);
473
+ }
474
+ const priv = value.private;
475
+ if (priv !== undefined && priv !== true) {
476
+ const unless = isObject(priv) ? priv.unless : undefined;
477
+ const flag =
478
+ typeof unless === "string" ? (value.fields as Record<string, unknown>)[unless] : undefined;
479
+ if (!isObject(flag) || flag.type !== "boolean") {
480
+ add(`${path}.private`, "private is true, or { unless: <a boolean key of this object> }");
481
+ }
482
+ }
483
+ const holders = value.holders;
484
+ if (holders !== undefined && holders !== true) {
485
+ const fields = value.fields as Record<string, unknown>;
486
+ const shape = isObject(holders) ? holders : null;
487
+ const unless = shape?.unless;
488
+ const keys = shape?.keys;
489
+ const flag = typeof unless === "string" ? fields[unless] : undefined;
490
+ const badUnless = unless !== undefined && (!isObject(flag) || flag.type !== "boolean");
491
+ const badKeys =
492
+ keys !== undefined &&
493
+ (!Array.isArray(keys) ||
494
+ !keys.length ||
495
+ keys.some((k) => typeof k !== "string" || !Object.hasOwn(fields, k) || k === unless));
496
+ const extra = shape ? Object.keys(shape).filter((k) => k !== "unless" && k !== "keys") : [];
497
+ if (
498
+ !shape ||
499
+ (unless === undefined && keys === undefined) ||
500
+ badUnless ||
501
+ badKeys ||
502
+ extra.length
503
+ ) {
504
+ add(
505
+ `${path}.holders`,
506
+ "holders is true, { unless: <a boolean key> } or { keys: [<keys of this object>], unless? }",
507
+ );
508
+ }
509
+ }
510
+ };
511
+
512
+ const resolve = (value: unknown, seen = new Set<string>()): DocumentNode | undefined => {
513
+ if (!isObject(value)) return undefined;
514
+ if (value.type !== "use") return value as unknown as DocumentNode;
515
+ const name = String(value.def);
516
+ if (seen.has(name) || !Object.hasOwn(defs, name)) return undefined;
517
+ seen.add(name);
518
+ return resolve(defs[name], seen);
519
+ };
520
+
521
+ if (!isObject(schema.root) || schema.root.type !== "object") {
522
+ add("root", "root is an object node");
523
+ } else {
524
+ node("root", schema.root, 0, false);
525
+ }
526
+ for (const [name, def] of Object.entries(defs)) node(`defs.${name}`, def, 0, false);
527
+ // A definition that only names itself (a: use a) would never reach a value.
528
+ for (const name of Object.keys(defs)) {
529
+ if (!resolve({ type: "use", def: name }))
530
+ add(`defs.${name}`, "A definition must reach a node that is not `use`");
531
+ }
532
+ return problems;
533
+ }
534
+
535
+ /** The node a declared path reaches, or why it reaches none. */
536
+ export function documentPathNode(
537
+ schema: DocumentSchema,
538
+ spec: Pick<DocumentPathSpec, "path" | "count">,
539
+ ): { type: DocumentPathType } | string {
540
+ const keys = spec.path.split(".");
541
+ if (!keys.length || keys.some((key) => !KEY_RE.test(key))) {
542
+ return "A path is camelCase keys joined by dots, from the document's root";
543
+ }
544
+ let current: DocumentNode | undefined = schema.root;
545
+ for (const key of keys) {
546
+ const at = useOf(schema, current);
547
+ if (at?.type !== "object")
548
+ return `"${spec.path}" passes through something that is not an object`;
549
+ // A column of the view is read whole: a part for holders only cannot be one (ADR 0477).
550
+ if (at.holders && (at.holders === true || !at.holders.keys || at.holders.keys.includes(key))) {
551
+ return `"${spec.path}" is in a part for holders only, which a column cannot keep from others`;
552
+ }
553
+ current = at.fields[key];
554
+ if (!current) return `"${spec.path}" is not in the schema (no "${key}")`;
555
+ }
556
+ const end = useOf(schema, current);
557
+ if (spec.count) {
558
+ return end?.type === "array"
559
+ ? { type: "number" }
560
+ : `"${spec.path}" is not a list, so it has no count`;
561
+ }
562
+ switch (end?.type) {
563
+ case "text":
564
+ case "choice":
565
+ return { type: "text" };
566
+ case "number":
567
+ return { type: "number" };
568
+ case "boolean":
569
+ return { type: "boolean" };
570
+ case "ref":
571
+ return { type: "id" };
572
+ default:
573
+ return `"${spec.path}" is not a text, number, boolean, choice or ref (use count for a list)`;
574
+ }
575
+ }
576
+
577
+ /** The JSON path SQLite reads a declared path with: `$.meta.level`. */
578
+ export function documentJsonPath(path: string): string {
579
+ if (!path.split(".").every((key) => KEY_RE.test(key)))
580
+ throw new Error(`Bad document path ${path}`);
581
+ return `$.${path}`;
582
+ }
583
+
584
+ function useOf(schema: DocumentSchema, node: DocumentNode | undefined): DocumentNode | undefined {
585
+ let current = node;
586
+ for (let hops = 0; current?.type === "use" && hops < 20; hops += 1) {
587
+ current = schema.defs?.[current.def];
588
+ }
589
+ return current?.type === "use" ? undefined : current;
590
+ }
591
+
592
+ // --- Validating a value ----------------------------------------------------------------------------
593
+
594
+ /**
595
+ * Checks `value` against `schema`: every fault, with its path, or the value and its size. A value
596
+ * over `maxBytes` (capped at DOCUMENT_MAX_BYTES) is refused before it is walked.
597
+ */
598
+ export function validateDocument(
599
+ schema: DocumentSchema,
600
+ value: unknown,
601
+ options: { maxBytes?: number } = {},
602
+ ): DocumentResult {
603
+ const limit = Math.min(options.maxBytes ?? DOCUMENT_DEFAULT_BYTES, DOCUMENT_MAX_BYTES);
604
+ let bytes: number;
605
+ try {
606
+ bytes = documentBytes(value);
607
+ } catch {
608
+ return { ok: false, issues: [{ path: [], message: "The document is not JSON" }] };
609
+ }
610
+ if (bytes > limit) {
611
+ return {
612
+ ok: false,
613
+ issues: [{ path: [], message: `The document is ${bytes} bytes; at most ${limit}` }],
614
+ };
615
+ }
616
+ const issues: DocumentIssue[] = [];
617
+ const acrossLists = new Map<DocumentArrayNode, Map<string, string>>();
618
+ const fault = (path: (string | number)[], message: string) => {
619
+ if (issues.length < DOCUMENT_MAX_ISSUES) issues.push({ path: [...path], message });
620
+ };
621
+ const walk = (node: DocumentNode, v: unknown, path: (string | number)[], depth: number) => {
622
+ if (issues.length >= DOCUMENT_MAX_ISSUES) return;
623
+ if (depth > DOCUMENT_MAX_DEPTH) {
624
+ fault(path, `Nested deeper than ${DOCUMENT_MAX_DEPTH}`);
625
+ return;
626
+ }
627
+ switch (node.type) {
628
+ case "use": {
629
+ const target = useOf(schema, node);
630
+ if (!target) fault(path, `The schema's definition "${node.def}" is missing`);
631
+ else walk(target, v, path, depth);
632
+ return;
633
+ }
634
+ case "object":
635
+ objectValue(node, v, path, depth, null);
636
+ return;
637
+ case "union": {
638
+ if (!isObject(v)) {
639
+ fault(path, `Expected an object with "${node.tag}"`);
640
+ return;
641
+ }
642
+ const tag = v[node.tag];
643
+ const variant =
644
+ typeof tag === "string" && Object.hasOwn(node.variants, tag)
645
+ ? node.variants[tag]
646
+ : undefined;
647
+ if (!variant) {
648
+ fault([...path, node.tag], `Expected one of ${Object.keys(node.variants).join(", ")}`);
649
+ return;
650
+ }
651
+ objectValue(variant, v, path, depth, node.tag);
652
+ return;
653
+ }
654
+ case "array": {
655
+ if (!Array.isArray(v)) {
656
+ fault(path, "Expected a list");
657
+ return;
658
+ }
659
+ if (v.length > node.max) fault(path, `At most ${node.max} entries (this has ${v.length})`);
660
+ if (node.min !== undefined && v.length < node.min) {
661
+ fault(path, `At least ${node.min} ${node.min === 1 ? "entry" : "entries"}`);
662
+ }
663
+ const seen = new Map<string, number>();
664
+ // Across every list of this node in the document: the first place each key was used.
665
+ let across = node.uniqueAcross ? acrossLists.get(node) : undefined;
666
+ if (node.uniqueAcross && !across) {
667
+ across = new Map();
668
+ acrossLists.set(node, across);
669
+ }
670
+ v.slice(0, node.max).forEach((item, i) => {
671
+ walk(node.of, item, [...path, i], depth + 1);
672
+ if (node.unique && isObject(item) && item[node.unique] !== undefined) {
673
+ const key = JSON.stringify(item[node.unique]);
674
+ const first = seen.get(key);
675
+ const elsewhere = across?.get(key);
676
+ if (first !== undefined) {
677
+ fault(
678
+ [...path, i, node.unique],
679
+ `${JSON.stringify(item[node.unique])} is there twice (also entry ${first})`,
680
+ );
681
+ } else if (elsewhere !== undefined) {
682
+ fault(
683
+ [...path, i, node.unique],
684
+ `${JSON.stringify(item[node.unique])} is used already (at ${elsewhere})`,
685
+ );
686
+ } else {
687
+ seen.set(key, i);
688
+ across?.set(key, [...path, i].join("."));
689
+ }
690
+ }
691
+ });
692
+ return;
693
+ }
694
+ case "text": {
695
+ if (typeof v !== "string") {
696
+ fault(path, "Expected text");
697
+ return;
698
+ }
699
+ const max = node.max ?? DOCUMENT_DEFAULT_TEXT;
700
+ if (v.length > max) fault(path, `At most ${max} characters (this has ${v.length})`);
701
+ if (node.min !== undefined && v.length < node.min)
702
+ fault(path, `At least ${node.min} characters`);
703
+ if (CONTROL_RE.test(v)) fault(path, "Control characters are not allowed");
704
+ else if (!node.multiline && /[\r\n]/.test(v)) fault(path, "One line only");
705
+ if (node.chars) {
706
+ const allowed = new Set(node.chars);
707
+ const bad = [...v].find((c) => !allowed.has(c));
708
+ if (bad !== undefined) fault(path, `"${bad}" is not allowed here (only ${node.chars})`);
709
+ }
710
+ if (node.noMarkup && MARKUP_RE.test(v)) {
711
+ fault(path, "Markup is not allowed: rich text is data, not HTML");
712
+ }
713
+ if (node.href && !isDocumentHref(v, node.href)) {
714
+ fault(
715
+ path,
716
+ node.href === "web"
717
+ ? "Expected an http or https address"
718
+ : "Expected an http, https, mailto or tel address, a path on the site or an anchor",
719
+ );
720
+ }
721
+ return;
722
+ }
723
+ case "number": {
724
+ if (typeof v !== "number" || !Number.isFinite(v)) {
725
+ fault(path, "Expected a number");
726
+ return;
727
+ }
728
+ if (node.integer && !Number.isInteger(v)) fault(path, "Expected a whole number");
729
+ if (node.min !== undefined && v < node.min) fault(path, `At least ${node.min}`);
730
+ if (node.max !== undefined && v > node.max) fault(path, `At most ${node.max}`);
731
+ if (node.step !== undefined) {
732
+ const steps = (v - (node.min ?? 0)) / node.step;
733
+ if (Math.abs(steps - Math.round(steps)) > 1e-9) fault(path, `In steps of ${node.step}`);
734
+ }
735
+ return;
736
+ }
737
+ case "boolean":
738
+ if (typeof v !== "boolean") fault(path, "Expected true or false");
739
+ return;
740
+ case "choice":
741
+ if (typeof v !== "string" || !node.options.includes(v)) {
742
+ fault(path, `Expected one of ${node.options.join(", ")}`);
743
+ }
744
+ return;
745
+ case "ref":
746
+ if (typeof v !== "string" || !ID_RE.test(v)) fault(path, `Expected the id of a ${node.to}`);
747
+ return;
748
+ }
749
+ };
750
+ const objectValue = (
751
+ node: DocumentObjectNode,
752
+ v: unknown,
753
+ path: (string | number)[],
754
+ depth: number,
755
+ tag: string | null,
756
+ ) => {
757
+ if (!isObject(v)) {
758
+ fault(path, "Expected an object");
759
+ return;
760
+ }
761
+ for (const key of Object.keys(v)) {
762
+ if (key === tag) continue;
763
+ if (!Object.hasOwn(node.fields, key)) {
764
+ fault([...path, key], `Unknown key "${key}"`);
765
+ }
766
+ }
767
+ for (const [key, child] of Object.entries(node.fields)) {
768
+ if (!Object.hasOwn(v, key) || v[key] === undefined) {
769
+ if (!child.optional) fault([...path, key], "Required");
770
+ continue;
771
+ }
772
+ walk(child, v[key], [...path, key], depth + 1);
773
+ }
774
+ };
775
+ walk(schema.root, value, [], 0);
776
+ return issues.length ? { ok: false, issues } : { ok: true, value, bytes };
777
+ }
778
+
779
+ /** "weeks.0.sessions.2: Required", for messages. */
780
+ export function formatDocumentIssue(issue: DocumentIssue): string {
781
+ return issue.path.length ? `${issue.path.join(".")}: ${issue.message}` : issue.message;
782
+ }
783
+
784
+ // --- Reading a value -----------------------------------------------------------------------------
785
+
786
+ /** One `ref` of a value: the object it names, the id, where it is, and a media ref's kind. */
787
+ export interface DocumentRef {
788
+ to: string;
789
+ id: string;
790
+ path: (string | number)[];
791
+ media?: DocumentMediaKind;
792
+ }
793
+
794
+ /** Every `ref` in a valid value: the object it names, the id, and where it is. */
795
+ export function documentRefs(schema: DocumentSchema, value: unknown): DocumentRef[] {
796
+ const refs: DocumentRef[] = [];
797
+ visit(schema, value, (node, v, path) => {
798
+ if (node.type === "ref" && typeof v === "string") {
799
+ refs.push({ to: node.to, id: v, path, ...(node.media ? { media: node.media } : {}) });
800
+ }
801
+ });
802
+ return refs;
803
+ }
804
+
805
+ /** Who outside the org may read a part of a document (ADR 0477). */
806
+ export type DocumentReach = "all" | "holders" | "private";
807
+
808
+ /**
809
+ * The media items a value names, each with who outside the org reads the part it is in: `all`
810
+ * (anyone who may read the field), `holders` (only a reader who holds access to the record) or
811
+ * `private` (no one outside the org). Read from `redactDocument` itself, so it is exactly what the
812
+ * seam shows. An item named in several parts has the widest reach of them.
813
+ */
814
+ export function documentMediaReach(
815
+ schema: DocumentSchema,
816
+ value: unknown,
817
+ mediaObject = "media",
818
+ ): Map<string, DocumentReach> {
819
+ const ids = (v: unknown) =>
820
+ new Set(
821
+ v === null || v === undefined
822
+ ? []
823
+ : documentRefs(schema, v)
824
+ .filter((r) => r.to === mediaObject)
825
+ .map((r) => r.id),
826
+ );
827
+ const everyone = ids(redactDocument(schema, value, { holder: false }));
828
+ const holders = ids(redactDocument(schema, value, { holder: true }));
829
+ const reach = new Map<string, DocumentReach>();
830
+ for (const id of ids(value)) {
831
+ reach.set(id, everyone.has(id) ? "all" : holders.has(id) ? "holders" : "private");
832
+ }
833
+ return reach;
834
+ }
835
+
836
+ /**
837
+ * The document as someone outside the org may read it: every `private` object removed (from a
838
+ * list, its entry; from an object, its key), unless its `unless` key is true. Unless `holder` is
839
+ * true (the reader holds access to the record, ADR 0477), every `holders` object is removed the
840
+ * same way and every `holders` key of an object dropped, unless its `unless` key is true. A value
841
+ * that does not fit the schema is returned as null: an outsider is never shown what was not
842
+ * checked.
843
+ */
844
+ export function redactDocument(
845
+ schema: DocumentSchema,
846
+ value: unknown,
847
+ options: { holder?: boolean } = {},
848
+ ): unknown {
849
+ const holder = options.holder === true;
850
+ if (value === null || value === undefined) return value ?? null;
851
+ const strip = (
852
+ node: DocumentNode | undefined,
853
+ v: unknown,
854
+ depth: number,
855
+ ): { keep: boolean; value: unknown } => {
856
+ const at = useOf(schema, node);
857
+ if (!at || depth > DOCUMENT_MAX_DEPTH) return { keep: false, value: null };
858
+ switch (at.type) {
859
+ case "object":
860
+ case "union": {
861
+ if (!isObject(v)) return { keep: false, value: null };
862
+ const shape: DocumentObjectNode | undefined =
863
+ at.type === "object" ? at : at.variants[String(v[at.tag])];
864
+ if (!shape) return { keep: false, value: null };
865
+ if (shape.private) {
866
+ const unless = shape.private === true ? null : shape.private.unless;
867
+ if (!unless || v[unless] !== true) return { keep: false, value: null };
868
+ }
869
+ // Holders' parts (ADR 0477): for a reader without access, the object or its listed keys.
870
+ let dropped: ReadonlySet<string> | null = null;
871
+ const h = shape.holders;
872
+ if (h && !holder) {
873
+ const unless = h === true ? undefined : h.unless;
874
+ const open = unless !== undefined && v[unless] === true;
875
+ if (!open) {
876
+ const keys = h === true ? undefined : h.keys;
877
+ if (!keys) return { keep: false, value: null };
878
+ dropped = new Set(keys);
879
+ }
880
+ }
881
+ const out: Record<string, unknown> = {};
882
+ if (at.type === "union") out[at.tag] = v[at.tag];
883
+ for (const [key, child] of Object.entries(shape.fields)) {
884
+ if (!Object.hasOwn(v, key) || dropped?.has(key)) continue;
885
+ const kept = strip(child, v[key], depth + 1);
886
+ if (kept.keep) out[key] = kept.value;
887
+ }
888
+ return { keep: true, value: out };
889
+ }
890
+ case "array": {
891
+ if (!Array.isArray(v)) return { keep: false, value: null };
892
+ return {
893
+ keep: true,
894
+ value: v
895
+ .map((item) => strip(at.of, item, depth + 1))
896
+ .filter((r) => r.keep)
897
+ .map((r) => r.value),
898
+ };
899
+ }
900
+ default:
901
+ return { keep: true, value: v };
902
+ }
903
+ };
904
+ if (!validateDocument(schema, value, { maxBytes: DOCUMENT_MAX_BYTES }).ok) return null;
905
+ const result = strip(schema.root, value, 0);
906
+ return result.keep ? result.value : null;
907
+ }
908
+
909
+ function visit(
910
+ schema: DocumentSchema,
911
+ value: unknown,
912
+ each: (node: DocumentNode, value: unknown, path: (string | number)[]) => void,
913
+ ): void {
914
+ const walk = (
915
+ node: DocumentNode | undefined,
916
+ v: unknown,
917
+ path: (string | number)[],
918
+ depth: number,
919
+ ) => {
920
+ const at = useOf(schema, node);
921
+ if (!at || depth > DOCUMENT_MAX_DEPTH) return;
922
+ each(at, v, path);
923
+ if (at.type === "array" && Array.isArray(v)) {
924
+ v.forEach((item, i) => {
925
+ walk(at.of, item, [...path, i], depth + 1);
926
+ });
927
+ } else if ((at.type === "object" || at.type === "union") && isObject(v)) {
928
+ const shape = at.type === "object" ? at : at.variants[String(v[at.tag])];
929
+ for (const [key, child] of Object.entries(shape?.fields ?? {})) {
930
+ if (Object.hasOwn(v, key)) walk(child, v[key], [...path, key], depth + 1);
931
+ }
932
+ }
933
+ };
934
+ walk(schema.root, value, [], 0);
935
+ }