@sharedcontext/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ export { CLIENT_ID_MAX, CONTRACT, FUTURE_SKEW_S, MAX_BODY_BYTES, MAX_CONTENT_DEPTH, SCHEMA_MAJOR, TICKET_KIND, TYPE_TAG, } from "./constants.js";
2
+ export { CanonicalJsonError, canonicalContent, canonicalJson, compareUtf8, formatFloat, isCanonicalContent, isWellFormed, utf8, utf8Length, type Json, type JsonInput, } from "./canonical.js";
3
+ export { TemplateError, eventId, eventTemplate, nodeTagOptional, serializeNip01, sha256Hex, signEvent, verifyEvent, verifyShape, type EventTemplate, type SharedcontextSigner, type SignedEvent, type StoredEvent, type TemplateInput, } from "./event.js";
4
+ export { AUTH_REASONS, ENVELOPE_REASONS, KNOWN_REASONS, REJECT_REASONS, TOOL_REASONS, knownCode, type EnvelopeReason, type RejectReason, } from "./reasons.js";
5
+ export { SCHEMA_FILES, checkEvent, checkStoredEvent, contentTypes, schemaDocument, schemaText, validate, type SchemaFile, type ValidationResult, } from "./schema.js";
6
+ export { DEFAULT_TIMEOUT_MS, SharedcontextClient, SharedcontextRefused, SharedcontextUnavailable, type FetchLike, type FetchResponseLike, type SharedcontextClientOptions, } from "./client.js";
7
+ export type * from "./types.js";
8
+ export * from "./generated/content.js";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ // sharedcontext: the sharedcontext/1 work contract for JavaScript and TypeScript.
2
+ export { CLIENT_ID_MAX, CONTRACT, FUTURE_SKEW_S, MAX_BODY_BYTES, MAX_CONTENT_DEPTH, SCHEMA_MAJOR, TICKET_KIND, TYPE_TAG, } from "./constants.js";
3
+ export { CanonicalJsonError, canonicalContent, canonicalJson, compareUtf8, formatFloat, isCanonicalContent, isWellFormed, utf8, utf8Length, } from "./canonical.js";
4
+ export { TemplateError, eventId, eventTemplate, nodeTagOptional, serializeNip01, sha256Hex, signEvent, verifyEvent, verifyShape, } from "./event.js";
5
+ export { AUTH_REASONS, ENVELOPE_REASONS, KNOWN_REASONS, REJECT_REASONS, TOOL_REASONS, knownCode, } from "./reasons.js";
6
+ export { SCHEMA_FILES, checkEvent, checkStoredEvent, contentTypes, schemaDocument, schemaText, validate, } from "./schema.js";
7
+ export { DEFAULT_TIMEOUT_MS, SharedcontextClient, SharedcontextRefused, SharedcontextUnavailable, } from "./client.js";
8
+ export * from "./generated/content.js";
@@ -0,0 +1,14 @@
1
+ /** Why the log refused an event: `signed::RejectReason`, in its order, as `snake_case`. */
2
+ export declare const REJECT_REASONS: readonly ["bad_signature", "bad_id", "malformed", "missing_tag", "bad_tag", "content_not_canonical", "future_timestamp", "unsupported_schema_major", "unknown_type", "wrong_kind", "bad_payload", "unknown_field", "duplicate", "unknown_actor", "actor_expired", "past_timestamp", "rate_limited", "policy_unresolved", "role_not_allowed", "node_not_found", "node_closed", "duplicate_node", "parent_not_found", "depth_exceeded", "project_mismatch", "project_not_created", "already_claimed", "handoff_pending", "lease_lapsed", "no_live_claim", "not_claimant", "max_hold", "lease_too_long", "too_many_open_claims", "not_claimable", "gate_open", "gate_mismatch", "claim_mismatch", "stale_expiry", "done_requires_evidence", "close_rule_unmet", "has_live_covers", "not_closed", "field_not_owned", "invalid_value", "invalid_edge", "split_not_partition", "cycle", "body_too_large", "wrong_node_kind", "stale_from", "no_policy_row", "policy_forbids", "budget_exhausted", "sponsor_not_allowed", "actor_inactive", "approval_required", "repo_out_of_scope", "no_decision", "unknown_step", "evaluator_out_of_scope", "run_signer_mismatch", "last_steward"];
3
+ export type RejectReason = (typeof REJECT_REASONS)[number];
4
+ /** The reasons a stateless check of one event can give (`RejectReason::is_envelope`). */
5
+ export declare const ENVELOPE_REASONS: readonly ["bad_signature", "bad_id", "malformed", "missing_tag", "bad_tag", "content_not_canonical", "future_timestamp", "wrong_kind"];
6
+ export type EnvelopeReason = (typeof ENVELOPE_REASONS)[number];
7
+ /** The MCP tools' own refusals (a structured error result's `reason`, or `refused` for `changes`). */
8
+ export declare const TOOL_REASONS: readonly ["bad_arguments", "bad_payload", "claim_not_found", "invalid_args", "missing_argument", "node_not_found", "project_not_created", "run_not_found", "unavailable", "unknown_field", "unknown_tool", "unsigned_write", "wrong_tool_for_type", "feed_off", "cursor_invalid", "cursor_ahead", "cursor_gone"];
9
+ /** The service's sign-in refusals: the `reason` of a 401 or 403 answer from `/mcp`. */
10
+ export declare const AUTH_REASONS: readonly ["alg", "audience", "claims", "crit", "expired", "issuer", "jwks_unavailable", "lifetime", "malformed", "missing", "no_actor", "not_yet_valid", "org", "raw_key", "scope", "signature", "signer_not_caller", "unknown_credential", "unknown_kid"];
11
+ /** Every code a `SharedcontextRefused` may carry, besides the generic `refused` and `http_<status>`. */
12
+ export declare const KNOWN_REASONS: ReadonlySet<string>;
13
+ /** `v` when it is one of `known`, else null. */
14
+ export declare function knownCode(v: unknown, known?: ReadonlySet<string>): string | null;
@@ -0,0 +1,142 @@
1
+ // The stable codes the service answers with. Only these reach a `SharedcontextRefused`: anything
2
+ // else a server sends (a message, echoed input, a token in an error body) becomes a generic code,
3
+ // so logging or serialising an error cannot print what the server sent. Each list is the Rust
4
+ // core's (test/reasons.test.mjs reads them from crates/sharedcontext/src and compares).
5
+ /** Why the log refused an event: `signed::RejectReason`, in its order, as `snake_case`. */
6
+ export const REJECT_REASONS = [
7
+ // 1. signature and envelope
8
+ "bad_signature",
9
+ "bad_id",
10
+ "malformed",
11
+ "missing_tag",
12
+ "bad_tag",
13
+ "content_not_canonical",
14
+ "future_timestamp",
15
+ // 2. schema version and type
16
+ "unsupported_schema_major",
17
+ "unknown_type",
18
+ "wrong_kind",
19
+ "bad_payload",
20
+ "unknown_field",
21
+ // 3. idempotency
22
+ "duplicate",
23
+ // 4. actor
24
+ "unknown_actor",
25
+ "actor_expired",
26
+ "past_timestamp",
27
+ "rate_limited",
28
+ "policy_unresolved",
29
+ "role_not_allowed",
30
+ // 5. project and node
31
+ "node_not_found",
32
+ "node_closed",
33
+ "duplicate_node",
34
+ "parent_not_found",
35
+ "depth_exceeded",
36
+ "project_mismatch",
37
+ "project_not_created",
38
+ // 6. kind rules
39
+ "already_claimed",
40
+ "handoff_pending",
41
+ "lease_lapsed",
42
+ "no_live_claim",
43
+ "not_claimant",
44
+ "max_hold",
45
+ "lease_too_long",
46
+ "too_many_open_claims",
47
+ "not_claimable",
48
+ "gate_open",
49
+ "gate_mismatch",
50
+ "claim_mismatch",
51
+ "stale_expiry",
52
+ "done_requires_evidence",
53
+ "close_rule_unmet",
54
+ "has_live_covers",
55
+ "not_closed",
56
+ "field_not_owned",
57
+ "invalid_value",
58
+ "invalid_edge",
59
+ "split_not_partition",
60
+ "cycle",
61
+ "body_too_large",
62
+ "wrong_node_kind",
63
+ // 7. transition policy
64
+ "stale_from",
65
+ "no_policy_row",
66
+ "policy_forbids",
67
+ // 8. org model
68
+ "budget_exhausted",
69
+ "sponsor_not_allowed",
70
+ "actor_inactive",
71
+ "approval_required",
72
+ // 9. multi-repo projects (1.1)
73
+ "repo_out_of_scope",
74
+ // 10. the execution vocabulary (1.5)
75
+ "no_decision",
76
+ "unknown_step",
77
+ // 11. an outside evaluator
78
+ "evaluator_out_of_scope",
79
+ "run_signer_mismatch",
80
+ // 12. people from the directory
81
+ "last_steward",
82
+ ];
83
+ /** The reasons a stateless check of one event can give (`RejectReason::is_envelope`). */
84
+ export const ENVELOPE_REASONS = [
85
+ "bad_signature",
86
+ "bad_id",
87
+ "malformed",
88
+ "missing_tag",
89
+ "bad_tag",
90
+ "content_not_canonical",
91
+ "future_timestamp",
92
+ "wrong_kind",
93
+ ];
94
+ /** The MCP tools' own refusals (a structured error result's `reason`, or `refused` for `changes`). */
95
+ export const TOOL_REASONS = [
96
+ "bad_arguments",
97
+ "bad_payload",
98
+ "claim_not_found",
99
+ "invalid_args",
100
+ "missing_argument",
101
+ "node_not_found",
102
+ "project_not_created",
103
+ "run_not_found",
104
+ "unavailable",
105
+ "unknown_field",
106
+ "unknown_tool",
107
+ "unsigned_write",
108
+ "wrong_tool_for_type",
109
+ // the change feed's refusals (changes.schema.json ChangesRefusal)
110
+ "feed_off",
111
+ "cursor_invalid",
112
+ "cursor_ahead",
113
+ "cursor_gone",
114
+ ];
115
+ /** The service's sign-in refusals: the `reason` of a 401 or 403 answer from `/mcp`. */
116
+ export const AUTH_REASONS = [
117
+ "alg",
118
+ "audience",
119
+ "claims",
120
+ "crit",
121
+ "expired",
122
+ "issuer",
123
+ "jwks_unavailable",
124
+ "lifetime",
125
+ "malformed",
126
+ "missing",
127
+ "no_actor",
128
+ "not_yet_valid",
129
+ "org",
130
+ "raw_key",
131
+ "scope",
132
+ "signature",
133
+ "signer_not_caller",
134
+ "unknown_credential",
135
+ "unknown_kid",
136
+ ];
137
+ /** Every code a `SharedcontextRefused` may carry, besides the generic `refused` and `http_<status>`. */
138
+ export const KNOWN_REASONS = new Set([...REJECT_REASONS, ...TOOL_REASONS, ...AUTH_REASONS, "unauthorized", "forbidden"]);
139
+ /** `v` when it is one of `known`, else null. */
140
+ export function knownCode(v, known = KNOWN_REASONS) {
141
+ return typeof v === "string" && known.has(v) ? v : null;
142
+ }
@@ -0,0 +1,29 @@
1
+ import { SCHEMA_FILES, type SchemaFile } from "./generated/schemas.js";
2
+ export { SCHEMA_FILES, type SchemaFile };
3
+ /** A schema file of the contract, parsed (for example `event.schema.json`, `history/content-1.0.schema.json`). */
4
+ export declare function schemaDocument(file: SchemaFile): unknown;
5
+ /** The exact text of a schema file, as shipped in `schemas/` (also importable as `sharedcontext/schemas/<file>`). */
6
+ export declare function schemaText(file: SchemaFile): string;
7
+ /** The JSON type of a value as JSON Schema names it (`integer` for a whole number). */
8
+ export declare const typeOf: (v: unknown) => string;
9
+ /** What `validate` answers: `errors` lists each failure as `path: message`. */
10
+ export interface ValidationResult {
11
+ valid: boolean;
12
+ errors: string[];
13
+ }
14
+ /**
15
+ * Validate `value` against a schema of the contract: a file (`event.schema.json`) or a place in one
16
+ * (`content.schema.json#/$defs/node.created`, `mcp-tools.schema.json#/$defs/SubscribeArgs`).
17
+ * `path` names the value in the messages (default `$`).
18
+ */
19
+ export declare function validate(schema: string, value: unknown, path?: string): ValidationResult;
20
+ /**
21
+ * Every refusal the contract's shape gives a work event: the envelope schema, the NIP-01 id,
22
+ * canonical content, and the content by its `w` tag (`content.schema.json`; a type it does not
23
+ * define is `unknown_type`). An empty list when the shape passes. The signature is not checked.
24
+ */
25
+ export declare function checkEvent(event: unknown): Promise<string[]>;
26
+ /** A stored event (`{seq, received_at, policy_version, event}`): the stored shape around the event, then `checkEvent`. */
27
+ export declare function checkStoredEvent(row: unknown): Promise<string[]>;
28
+ /** The `w` types `checkEvent` knows: the event types of content.schema.json. */
29
+ export declare function contentTypes(): string[];
package/dist/schema.js ADDED
@@ -0,0 +1,265 @@
1
+ // A small JSON Schema (draft 2020-12) validator for the sharedcontext/1 schemas this package ships,
2
+ // and the contract's checks of a work event that go beyond the schema (NIP-01 id, canonical
3
+ // content, content by the `w` tag).
4
+ //
5
+ // It has no dependencies and implements only the keywords those schemas use, refusing any other,
6
+ // so a schema cannot silently rely on something this check does not enforce. `format` is an
7
+ // annotation (not checked); `contentMediaType: application/json` with `contentSchema` is applied as
8
+ // an assertion (the string is parsed and validated). It answers what the repository's own contract
9
+ // check answers, error for error (test/schema.test.mjs runs both over the contract's cases and the
10
+ // fixture log). Signatures are not verified.
11
+ import { compareUtf8, isCanonicalContent } from "./canonical.js";
12
+ import { eventId } from "./event.js";
13
+ import { SCHEMA_FILES, SCHEMA_TEXT } from "./generated/schemas.js";
14
+ export { SCHEMA_FILES };
15
+ const ANNOTATIONS = new Set(["$schema", "$comment", "title", "description", "format", "examples", "default", "deprecated", "readOnly", "writeOnly", "contentMediaType"]);
16
+ const docs = new Map();
17
+ /** A schema file of the contract, parsed (for example `event.schema.json`, `history/content-1.0.schema.json`). */
18
+ export function schemaDocument(file) {
19
+ if (!SCHEMA_FILES.includes(file))
20
+ throw new Error(`no schema file ${file} in sharedcontext/1`);
21
+ if (!docs.has(file))
22
+ docs.set(file, JSON.parse(SCHEMA_TEXT[file]));
23
+ return docs.get(file);
24
+ }
25
+ /** The exact text of a schema file, as shipped in `schemas/` (also importable as `sharedcontext/schemas/<file>`). */
26
+ export function schemaText(file) {
27
+ schemaDocument(file);
28
+ return SCHEMA_TEXT[file];
29
+ }
30
+ function pointer(doc, frag, where) {
31
+ if (!frag)
32
+ return doc;
33
+ if (!frag.startsWith("/"))
34
+ throw new Error(`${where}: only JSON pointer fragments are supported, got #${frag}`);
35
+ let cur = doc;
36
+ for (const raw of frag.slice(1).split("/")) {
37
+ const key = decodeURIComponent(raw).replace(/~1/g, "/").replace(/~0/g, "~");
38
+ if (cur === null || typeof cur !== "object" || !(key in cur))
39
+ throw new Error(`${where}: unresolved $ref fragment #${frag}`);
40
+ cur = cur[key];
41
+ }
42
+ return cur;
43
+ }
44
+ function resolvePath(from, path) {
45
+ const parts = from.split("/").slice(0, -1);
46
+ for (const p of path.split("/")) {
47
+ if (p === "..")
48
+ parts.pop();
49
+ else if (p !== ".")
50
+ parts.push(p);
51
+ }
52
+ return parts.join("/");
53
+ }
54
+ /** Resolve a $ref against the file it appears in. */
55
+ function resolveRef(ref, file) {
56
+ const [path, frag] = ref.split("#");
57
+ const target = path ? resolvePath(file, path) : file;
58
+ if (!SCHEMA_FILES.includes(target))
59
+ throw new Error(`${file}: $ref to a missing file ${ref}`);
60
+ return { schema: pointer(schemaDocument(target), frag ?? "", `${file} $ref ${ref}`), file: target };
61
+ }
62
+ /** The JSON type of a value as JSON Schema names it (`integer` for a whole number). */
63
+ export const typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v === "number" ? (Number.isInteger(v) ? "integer" : "number") : typeof v;
64
+ const typeMatches = (v, t) => t === typeOf(v) || (t === "number" && typeOf(v) === "integer");
65
+ function canon(v) {
66
+ if (Array.isArray(v))
67
+ return v.map(canon);
68
+ if (v !== null && typeof v === "object") {
69
+ const keys = Object.keys(v).sort(compareUtf8);
70
+ return Object.fromEntries(keys.map((k) => [k, canon(v[k])]));
71
+ }
72
+ return v;
73
+ }
74
+ const deepEqual = (a, b) => JSON.stringify(canon(a)) === JSON.stringify(canon(b));
75
+ const codePoints = (s) => [...s].length;
76
+ function check(value, schema, file, path) {
77
+ if (schema === true)
78
+ return [];
79
+ if (schema === false)
80
+ return [`${path}: no value is allowed here`];
81
+ const errs = [];
82
+ const sub = (v, s, p, f = file) => check(v, s, f, p);
83
+ const isObj = typeOf(value) === "object";
84
+ const obj = value;
85
+ for (const [k, kv] of Object.entries(schema)) {
86
+ switch (k) {
87
+ case "$ref": {
88
+ const r = resolveRef(kv, file);
89
+ errs.push(...sub(value, r.schema, path, r.file));
90
+ break;
91
+ }
92
+ case "type": {
93
+ const ts = Array.isArray(kv) ? kv : [kv];
94
+ if (!ts.some((t) => typeMatches(value, t)))
95
+ errs.push(`${path}: expected ${ts.join(" or ")}, got ${typeOf(value)}`);
96
+ break;
97
+ }
98
+ case "enum":
99
+ if (!kv.some((e) => deepEqual(e, value)))
100
+ errs.push(`${path}: ${JSON.stringify(value)} is not one of ${JSON.stringify(kv)}`);
101
+ break;
102
+ case "const":
103
+ if (!deepEqual(kv, value))
104
+ errs.push(`${path}: expected ${JSON.stringify(kv)}, got ${JSON.stringify(value)}`);
105
+ break;
106
+ case "properties":
107
+ if (isObj)
108
+ for (const [n, s] of Object.entries(kv))
109
+ if (n in obj)
110
+ errs.push(...sub(obj[n], s, `${path}.${n}`));
111
+ break;
112
+ case "required":
113
+ if (isObj)
114
+ for (const n of kv)
115
+ if (!(n in obj))
116
+ errs.push(`${path}: missing required field ${n}`);
117
+ break;
118
+ case "additionalProperties":
119
+ if (isObj) {
120
+ const known = new Set(Object.keys(schema.properties ?? {}));
121
+ for (const n of Object.keys(obj)) {
122
+ if (known.has(n))
123
+ continue;
124
+ if (kv === false)
125
+ errs.push(`${path}: field ${n} is not defined`);
126
+ else
127
+ errs.push(...sub(obj[n], kv, `${path}.${n}`));
128
+ }
129
+ }
130
+ break;
131
+ case "prefixItems":
132
+ if (Array.isArray(value))
133
+ kv.forEach((s, i) => i < value.length && errs.push(...sub(value[i], s, `${path}[${i}]`)));
134
+ break;
135
+ case "items":
136
+ if (Array.isArray(value))
137
+ for (let i = (schema.prefixItems ?? []).length; i < value.length; i++)
138
+ errs.push(...sub(value[i], kv, `${path}[${i}]`));
139
+ break;
140
+ case "minItems":
141
+ if (Array.isArray(value) && value.length < kv)
142
+ errs.push(`${path}: fewer than ${kv} items`);
143
+ break;
144
+ case "maxItems":
145
+ if (Array.isArray(value) && value.length > kv)
146
+ errs.push(`${path}: more than ${kv} items`);
147
+ break;
148
+ case "contains":
149
+ if (Array.isArray(value) && !value.some((v, i) => sub(v, kv, `${path}[${i}]`).length === 0))
150
+ errs.push(`${path}: no item matches the required shape${kv.$ref ? ` (${kv.$ref})` : ""}`);
151
+ break;
152
+ case "minLength":
153
+ if (typeof value === "string" && codePoints(value) < kv)
154
+ errs.push(`${path}: shorter than ${kv}`);
155
+ break;
156
+ case "maxLength":
157
+ if (typeof value === "string" && codePoints(value) > kv)
158
+ errs.push(`${path}: longer than ${kv}`);
159
+ break;
160
+ case "pattern":
161
+ if (typeof value === "string" && !new RegExp(kv, "u").test(value))
162
+ errs.push(`${path}: does not match ${kv}`);
163
+ break;
164
+ case "minimum":
165
+ if (typeof value === "number" && value < kv)
166
+ errs.push(`${path}: below ${kv}`);
167
+ break;
168
+ case "maximum":
169
+ if (typeof value === "number" && value > kv)
170
+ errs.push(`${path}: above ${kv}`);
171
+ break;
172
+ case "allOf":
173
+ kv.forEach((s) => errs.push(...sub(value, s, path)));
174
+ break;
175
+ case "anyOf":
176
+ if (!kv.some((s) => sub(value, s, path).length === 0))
177
+ errs.push(`${path}: matches none of anyOf (${kv.map((s) => sub(value, s, path)[0]).join(" | ")})`);
178
+ break;
179
+ case "oneOf": {
180
+ const n = kv.filter((s) => sub(value, s, path).length === 0).length;
181
+ if (n !== 1)
182
+ errs.push(`${path}: matches ${n} of oneOf, expected exactly 1`);
183
+ break;
184
+ }
185
+ case "not":
186
+ if (sub(value, kv, path).length === 0)
187
+ errs.push(`${path}: matches a shape that is not allowed`);
188
+ break;
189
+ case "if": {
190
+ const branch = sub(value, kv, path).length === 0 ? schema.then : schema.else;
191
+ if (branch !== undefined)
192
+ errs.push(...sub(value, branch, path));
193
+ break;
194
+ }
195
+ case "contentSchema":
196
+ if (typeof value === "string" && schema.contentMediaType === "application/json") {
197
+ let parsed;
198
+ try {
199
+ parsed = JSON.parse(value);
200
+ }
201
+ catch {
202
+ errs.push(`${path}: not JSON`);
203
+ break;
204
+ }
205
+ errs.push(...sub(parsed, kv, `${path}(json)`));
206
+ }
207
+ break;
208
+ default:
209
+ if (!ANNOTATIONS.has(k) && !["then", "else", "$defs"].includes(k))
210
+ throw new Error(`unsupported keyword ${k}`);
211
+ }
212
+ }
213
+ return errs;
214
+ }
215
+ /**
216
+ * Validate `value` against a schema of the contract: a file (`event.schema.json`) or a place in one
217
+ * (`content.schema.json#/$defs/node.created`, `mcp-tools.schema.json#/$defs/SubscribeArgs`).
218
+ * `path` names the value in the messages (default `$`).
219
+ */
220
+ export function validate(schema, value, path = "$") {
221
+ const { schema: s, file } = resolveRef(schema.includes("#") ? schema : `${schema}#`, "");
222
+ const errors = check(value, s, file, path);
223
+ return { valid: errors.length === 0, errors };
224
+ }
225
+ const SHAPE_TYPES = /^[a-z_]+\.[a-z_]+$/;
226
+ /**
227
+ * Every refusal the contract's shape gives a work event: the envelope schema, the NIP-01 id,
228
+ * canonical content, and the content by its `w` tag (`content.schema.json`; a type it does not
229
+ * define is `unknown_type`). An empty list when the shape passes. The signature is not checked.
230
+ */
231
+ export async function checkEvent(event) {
232
+ const errs = check(event, schemaDocument("event.schema.json"), "event.schema.json", "event");
233
+ const e = event;
234
+ if (e && typeof e === "object" && typeof e.content === "string") {
235
+ if (Array.isArray(e.tags) && typeof e.pubkey === "string" && (await eventId(e)) !== e.id)
236
+ errs.push("event.id: not the NIP-01 id of the event (bad_id)");
237
+ if (!contentParsesCanonical(e.content))
238
+ errs.push("event.content: not canonical JSON (content_not_canonical)");
239
+ const w = Array.isArray(e.tags) ? e.tags.find((t) => Array.isArray(t) && t[0] === "w")?.[1] : undefined;
240
+ const defs = schemaDocument("content.schema.json").$defs;
241
+ if (w && !(w in defs))
242
+ errs.push(`event: unknown type ${w} (unknown_type)`);
243
+ else if (w) {
244
+ try {
245
+ errs.push(...check(JSON.parse(e.content), defs[w], "content.schema.json", `content<${w}>`));
246
+ }
247
+ catch {
248
+ /* reported as not canonical */
249
+ }
250
+ }
251
+ }
252
+ return errs;
253
+ }
254
+ function contentParsesCanonical(content) {
255
+ return isCanonicalContent(content);
256
+ }
257
+ /** A stored event (`{seq, received_at, policy_version, event}`): the stored shape around the event, then `checkEvent`. */
258
+ export async function checkStoredEvent(row) {
259
+ const outer = check(row, schemaDocument("stored-event.schema.json"), "stored-event.schema.json", "line").filter((e) => !e.startsWith("line.event"));
260
+ return [...outer, ...(await checkEvent(row?.event))];
261
+ }
262
+ /** The `w` types `checkEvent` knows: the event types of content.schema.json. */
263
+ export function contentTypes() {
264
+ return Object.keys(schemaDocument("content.schema.json").$defs).filter((k) => SHAPE_TYPES.test(k));
265
+ }