@openplanr/protocol 0.11.0 → 0.13.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.
@@ -2,7 +2,8 @@
2
2
  /**
3
3
  * Minimal JSON Schema (draft 2020-12) subset extracted from conformance/runner.mjs.
4
4
  * Supports the constructs used by packaged Protocol schemas, including local
5
- * JSON-pointer and caller-resolved external `$ref` references.
5
+ * JSON-pointer and caller-resolved external `$ref` references. Any other keyword or
6
+ * format is reported as an error rather than ignored.
6
7
  *
7
8
  * Zero third-party deps. Safe to import from node:test suites.
8
9
  */
@@ -30,6 +31,146 @@ const matchesType = (v, t) => {
30
31
 
31
32
  const FORMAT_DATE = /^\d{4}-\d{2}-\d{2}$/;
32
33
  const FORMAT_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
34
+ const SUPPORTED_FORMATS = new Set(['date', 'date-time']);
35
+
36
+ const ANNOTATION_KEYWORDS = [
37
+ '$schema',
38
+ '$id',
39
+ '$defs',
40
+ '$comment',
41
+ 'title',
42
+ 'description',
43
+ 'default',
44
+ 'examples',
45
+ 'deprecated',
46
+ 'readOnly',
47
+ 'writeOnly',
48
+ ];
49
+ const VALIDATION_KEYWORDS = [
50
+ '$ref',
51
+ 'type',
52
+ 'const',
53
+ 'enum',
54
+ 'minLength',
55
+ 'maxLength',
56
+ 'pattern',
57
+ 'format',
58
+ 'minimum',
59
+ 'maximum',
60
+ 'exclusiveMinimum',
61
+ 'minItems',
62
+ 'maxItems',
63
+ 'prefixItems',
64
+ 'items',
65
+ 'uniqueItems',
66
+ 'contains',
67
+ 'minContains',
68
+ 'maxContains',
69
+ 'required',
70
+ 'properties',
71
+ 'additionalProperties',
72
+ 'maxProperties',
73
+ 'dependentRequired',
74
+ 'unevaluatedProperties',
75
+ 'oneOf',
76
+ 'anyOf',
77
+ 'allOf',
78
+ 'if',
79
+ 'then',
80
+ 'else',
81
+ 'not',
82
+ ];
83
+ const KNOWN_KEYWORDS = new Set([...ANNOTATION_KEYWORDS, ...VALIDATION_KEYWORDS]);
84
+ const TYPE_NAMES = new Set(['array', 'boolean', 'integer', 'null', 'number', 'object', 'string']);
85
+
86
+ const isSchema = (value) =>
87
+ typeof value === 'boolean' ||
88
+ (value !== null && typeof value === 'object' && !Array.isArray(value));
89
+ /** @type {(value: unknown) => value is Record<string, unknown>} */
90
+ const isPlainObject = (value) =>
91
+ value !== null && typeof value === 'object' && !Array.isArray(value);
92
+ const isCount = (value) => Number.isSafeInteger(value) && value >= 0;
93
+ /** @type {(value: unknown) => value is string[]} */
94
+ const isUniqueStrings = (value) =>
95
+ Array.isArray(value) &&
96
+ value.every((item) => typeof item === 'string') &&
97
+ new Set(value).size === value.length;
98
+ const isSchemaArray = (value) => Array.isArray(value) && value.length > 0 && value.every(isSchema);
99
+ const isSchemaMap = (value) => isPlainObject(value) && Object.values(value).every(isSchema);
100
+ /** @type {Map<string, RegExp | null>} */
101
+ const compiledPatterns = new Map();
102
+ const MAX_COMPILED_PATTERNS = 1024;
103
+ /** @type {(source: string) => RegExp | null} */
104
+ const tryCompilePattern = (source) => {
105
+ try {
106
+ return new RegExp(source);
107
+ } catch (error) {
108
+ if (error instanceof SyntaxError) return null;
109
+ throw error;
110
+ }
111
+ };
112
+ /** Returns the compiled pattern, or null when it is not a valid regular expression. */
113
+ const compilePattern = (source) => {
114
+ if (!compiledPatterns.has(source)) {
115
+ if (compiledPatterns.size >= MAX_COMPILED_PATTERNS) compiledPatterns.clear();
116
+ compiledPatterns.set(source, tryCompilePattern(source));
117
+ }
118
+ return compiledPatterns.get(source) ?? null;
119
+ };
120
+
121
+ const describeValue = (value) => {
122
+ const text = String(JSON.stringify(value));
123
+ return text.length > 80 ? `${text.slice(0, 77)}...` : text;
124
+ };
125
+
126
+ /**
127
+ * Expected value shape of each supported keyword, per draft 2020-12.
128
+ * @type {Record<string, [string, (value: unknown) => boolean]>}
129
+ */
130
+ const KEYWORD_SHAPES = {
131
+ $ref: ['a string', (value) => typeof value === 'string'],
132
+ $defs: ['an object of schemas', isSchemaMap],
133
+ type: [
134
+ 'a type name or a non-empty array of unique type names',
135
+ (value) =>
136
+ (typeof value === 'string' && TYPE_NAMES.has(value)) ||
137
+ (isUniqueStrings(value) && value.length > 0 && value.every((name) => TYPE_NAMES.has(name))),
138
+ ],
139
+ enum: ['an array', Array.isArray],
140
+ minLength: ['a non-negative integer', isCount],
141
+ maxLength: ['a non-negative integer', isCount],
142
+ pattern: [
143
+ 'a valid regular expression string',
144
+ (value) => typeof value === 'string' && compilePattern(value) !== null,
145
+ ],
146
+ minimum: ['a finite number', Number.isFinite],
147
+ maximum: ['a finite number', Number.isFinite],
148
+ exclusiveMinimum: ['a finite number', Number.isFinite],
149
+ minItems: ['a non-negative integer', isCount],
150
+ maxItems: ['a non-negative integer', isCount],
151
+ prefixItems: ['a non-empty array of schemas', isSchemaArray],
152
+ items: ['a schema', isSchema],
153
+ uniqueItems: ['a boolean', (value) => typeof value === 'boolean'],
154
+ contains: ['a schema', isSchema],
155
+ minContains: ['a non-negative integer', isCount],
156
+ maxContains: ['a non-negative integer', isCount],
157
+ required: ['an array of unique strings', isUniqueStrings],
158
+ properties: ['an object of schemas', isSchemaMap],
159
+ additionalProperties: ['a schema', isSchema],
160
+ maxProperties: ['a non-negative integer', isCount],
161
+ dependentRequired: [
162
+ 'an object of unique string arrays',
163
+ (value) => isPlainObject(value) && Object.values(value).every(isUniqueStrings),
164
+ ],
165
+ unevaluatedProperties: ['a schema', isSchema],
166
+ oneOf: ['a non-empty array of schemas', isSchemaArray],
167
+ anyOf: ['a non-empty array of schemas', isSchemaArray],
168
+ allOf: ['a non-empty array of schemas', isSchemaArray],
169
+ if: ['a schema', isSchema],
170
+ then: ['a schema', isSchema],
171
+ else: ['a schema', isSchema],
172
+ not: ['a schema', isSchema],
173
+ };
33
174
 
34
175
  function resolveJsonPointer(root, reference) {
35
176
  if (reference === '#') return root;
@@ -41,12 +182,73 @@ function resolveJsonPointer(root, reference) {
41
182
  .reduce((value, part) => value?.[part], root);
42
183
  }
43
184
 
185
+ /** Frozen schema nodes that passed every node check; a mutable node is re-checked on each call. */
186
+ const wellFormedSchemas = new WeakSet();
187
+
188
+ /** True when the node and every keyword value its checks read can no longer change. */
189
+ const isFrozenNode = (schema) =>
190
+ Object.isFrozen(schema) &&
191
+ Object.values(schema).every(Object.isFrozen) &&
192
+ (!isPlainObject(schema.dependentRequired) ||
193
+ Object.values(schema.dependentRequired).every(Object.isFrozen));
194
+
195
+ /**
196
+ * Records unsupported keywords and formats and malformed keyword values, once per schema node.
197
+ * They go to a shared sink so `not`, `if` and combinator branches cannot swallow them.
198
+ */
199
+ const checkSchemaNode = (schema, path, context) => {
200
+ if (wellFormedSchemas.has(schema) || context.checkedSchemas.has(schema)) return;
201
+ context.checkedSchemas.add(schema);
202
+ const errorCount = context.schemaErrors.length;
203
+ for (const keyword of Object.keys(schema)) {
204
+ if (!KNOWN_KEYWORDS.has(keyword) && !keyword.startsWith('x-')) {
205
+ context.schemaErrors.push({
206
+ path,
207
+ rule: 'unsupported-keyword',
208
+ detail: `schema keyword '${keyword}' is not supported by this validator`,
209
+ });
210
+ }
211
+ }
212
+ if (Object.hasOwn(schema, 'format') && !SUPPORTED_FORMATS.has(schema.format)) {
213
+ context.schemaErrors.push({
214
+ path,
215
+ rule: 'unsupported-format',
216
+ detail: `schema format ${JSON.stringify(schema.format)} is not supported by this validator`,
217
+ });
218
+ }
219
+ for (const [keyword, [expected, isValid]] of Object.entries(KEYWORD_SHAPES)) {
220
+ if (Object.hasOwn(schema, keyword) && !isValid(schema[keyword])) {
221
+ context.schemaErrors.push({
222
+ path,
223
+ rule: 'schema',
224
+ detail: `schema keyword '${keyword}' must be ${expected}, got ${describeValue(schema[keyword])}`,
225
+ });
226
+ }
227
+ }
228
+ if (context.schemaErrors.length === errorCount && isFrozenNode(schema)) {
229
+ wellFormedSchemas.add(schema);
230
+ }
231
+ };
232
+
233
+ /** Records an unresolvable or circular `$ref` once per schema node. */
234
+ const reportReference = (schema, path, detail, context) => {
235
+ if (context.reportedReferences.has(schema)) return;
236
+ context.reportedReferences.add(schema);
237
+ context.schemaErrors.push({ path, rule: '$ref', detail });
238
+ };
239
+
240
+ /** Validates one node and returns the object property names it evaluated. */
44
241
  const validateNode = (value, schema, path, errs, context) => {
45
- if (schema === true) return;
242
+ /** @type {Set<string>} */
243
+ const evaluated = new Set();
244
+ if (schema === true) return evaluated;
46
245
  if (schema === false) {
47
246
  errs.push({ path, rule: 'schema:false', detail: 'value not allowed' });
48
- return;
247
+ return evaluated;
49
248
  }
249
+ // A non-schema child is reported by its parent's keyword-shape check.
250
+ if (!isSchema(schema)) return evaluated;
251
+ checkSchemaNode(schema, path, context);
50
252
 
51
253
  if (typeof schema?.$ref === 'string') {
52
254
  const reference = schema.$ref;
@@ -61,21 +263,27 @@ const validateNode = (value, schema, path, errs, context) => {
61
263
  nextRoot = result?.rootSchema ?? resolved;
62
264
  resolvedBase = result?.base ?? resolved?.$id ?? context.base;
63
265
  }
64
- if (!resolved) {
65
- errs.push({ path, rule: '$ref', detail: `could not resolve schema reference ${reference}` });
66
- return;
266
+ if (!isSchema(resolved)) {
267
+ const detail =
268
+ resolved === undefined || resolved === null
269
+ ? `could not resolve schema reference ${reference}`
270
+ : `schema reference ${reference} resolved to ${typeOf(resolved)}, not a schema`;
271
+ reportReference(schema, path, detail, context);
272
+ return evaluated;
67
273
  }
68
- const referenceKey = `${context.base ?? '<root>'}:${reference}`;
274
+ // Recursion that descends into the instance changes `path`; only a repeat at the same location loops.
275
+ const referenceKey = `${path} ${context.base ?? '<root>'}:${reference}`;
69
276
  if (context.referenceStack.includes(referenceKey)) {
70
- errs.push({ path, rule: '$ref', detail: `circular schema reference ${reference}` });
71
- return;
277
+ reportReference(schema, path, `circular schema reference ${reference}`, context);
278
+ return evaluated;
72
279
  }
73
- validateNode(value, resolved, path, errs, {
280
+ const referenced = validateNode(value, resolved, path, errs, {
74
281
  ...context,
75
282
  rootSchema: nextRoot,
76
283
  base: resolvedBase,
77
284
  referenceStack: [...context.referenceStack, referenceKey],
78
285
  });
286
+ for (const key of referenced) evaluated.add(key);
79
287
  }
80
288
 
81
289
  if (schema.type !== undefined) {
@@ -86,7 +294,7 @@ const validateNode = (value, schema, path, errs, context) => {
86
294
  rule: 'type',
87
295
  detail: `expected ${types.join('|')}, got ${typeOf(value)}`,
88
296
  });
89
- return;
297
+ return evaluated;
90
298
  }
91
299
  }
92
300
 
@@ -125,22 +333,13 @@ const validateNode = (value, schema, path, errs, context) => {
125
333
  detail: `length ${value.length} > ${schema.maxLength}`,
126
334
  });
127
335
  }
128
- if (typeof schema.pattern === 'string') {
129
- try {
130
- if (!new RegExp(schema.pattern).test(value)) {
131
- errs.push({
132
- path,
133
- rule: 'pattern',
134
- detail: `value ${JSON.stringify(value)} does not match /${schema.pattern}/`,
135
- });
136
- }
137
- } catch (e) {
138
- errs.push({
139
- path,
140
- rule: 'pattern',
141
- detail: `invalid regex /${schema.pattern}/: ${e instanceof Error ? e.message : String(e)}`,
142
- });
143
- }
336
+ const pattern = typeof schema.pattern === 'string' ? compilePattern(schema.pattern) : null;
337
+ if (pattern && !pattern.test(value)) {
338
+ errs.push({
339
+ path,
340
+ rule: 'pattern',
341
+ detail: `value ${JSON.stringify(value)} does not match /${schema.pattern}/`,
342
+ });
144
343
  }
145
344
  if (typeof schema.format === 'string') {
146
345
  if (schema.format === 'date' && !FORMAT_DATE.test(value)) {
@@ -166,6 +365,13 @@ const validateNode = (value, schema, path, errs, context) => {
166
365
  if (typeof schema.maximum === 'number' && value > schema.maximum) {
167
366
  errs.push({ path, rule: 'maximum', detail: `value ${value} > ${schema.maximum}` });
168
367
  }
368
+ if (typeof schema.exclusiveMinimum === 'number' && value <= schema.exclusiveMinimum) {
369
+ errs.push({
370
+ path,
371
+ rule: 'exclusiveMinimum',
372
+ detail: `value ${value} <= ${schema.exclusiveMinimum}`,
373
+ });
374
+ }
169
375
  }
170
376
 
171
377
  if (Array.isArray(value)) {
@@ -231,8 +437,34 @@ const validateNode = (value, schema, path, errs, context) => {
231
437
  }
232
438
  }
233
439
  }
440
+ if (
441
+ typeof schema.maxProperties === 'number' &&
442
+ Object.keys(value).length > schema.maxProperties
443
+ ) {
444
+ errs.push({
445
+ path,
446
+ rule: 'maxProperties',
447
+ detail: `property count ${Object.keys(value).length} > ${schema.maxProperties}`,
448
+ });
449
+ }
450
+ if (schema.dependentRequired !== null && typeof schema.dependentRequired === 'object') {
451
+ for (const [trigger, dependencies] of Object.entries(schema.dependentRequired)) {
452
+ if (!Object.hasOwn(value, trigger) || !Array.isArray(dependencies)) continue;
453
+ for (const dependency of dependencies) {
454
+ if (!Object.hasOwn(value, dependency)) {
455
+ errs.push({
456
+ path,
457
+ rule: 'dependentRequired',
458
+ detail: `property '${trigger}' requires property '${dependency}'`,
459
+ });
460
+ }
461
+ }
462
+ }
463
+ }
234
464
  const props = schema.properties || {};
235
465
  for (const [k, v] of Object.entries(value)) {
466
+ if (Object.hasOwn(props, k)) evaluated.add(k);
467
+ else if (schema.additionalProperties !== undefined) evaluated.add(k);
236
468
  if (!Object.hasOwn(props, k)) {
237
469
  if (schema.additionalProperties === false) {
238
470
  errs.push({ path, rule: 'additionalProperties', detail: `unknown property '${k}'` });
@@ -253,8 +485,11 @@ const validateNode = (value, schema, path, errs, context) => {
253
485
  let matched = 0;
254
486
  for (const sub of schema.oneOf) {
255
487
  const e = [];
256
- validateNode(value, sub, path, e, context);
257
- if (e.length === 0) matched++;
488
+ const branch = validateNode(value, sub, path, e, context);
489
+ if (e.length === 0) {
490
+ matched++;
491
+ for (const key of branch) evaluated.add(key);
492
+ }
258
493
  }
259
494
  if (matched !== 1) {
260
495
  const titles = schema.oneOf.map((s) => s.title || '(unnamed)').join(' | ');
@@ -270,8 +505,11 @@ const validateNode = (value, schema, path, errs, context) => {
270
505
  let matched = 0;
271
506
  for (const sub of schema.anyOf) {
272
507
  const candidateErrors = [];
273
- validateNode(value, sub, path, candidateErrors, context);
274
- if (candidateErrors.length === 0) matched += 1;
508
+ const branch = validateNode(value, sub, path, candidateErrors, context);
509
+ if (candidateErrors.length === 0) {
510
+ matched += 1;
511
+ for (const key of branch) evaluated.add(key);
512
+ }
275
513
  }
276
514
  if (matched === 0) {
277
515
  const titles = schema.anyOf.map((sub) => sub.title || '(unnamed)').join(' | ');
@@ -285,15 +523,22 @@ const validateNode = (value, schema, path, errs, context) => {
285
523
 
286
524
  if (Array.isArray(schema.allOf)) {
287
525
  for (const sub of schema.allOf) {
288
- validateNode(value, sub, path, errs, context);
526
+ for (const key of validateNode(value, sub, path, errs, context)) evaluated.add(key);
289
527
  }
290
528
  }
291
529
 
292
530
  if (schema.if !== undefined) {
293
531
  const conditionErrors = [];
294
- validateNode(value, schema.if, path, conditionErrors, context);
295
- const branch = conditionErrors.length === 0 ? schema.then : schema.else;
296
- if (branch !== undefined) validateNode(value, branch, path, errs, context);
532
+ const condition = validateNode(value, schema.if, path, conditionErrors, context);
533
+ const passed = conditionErrors.length === 0;
534
+ if (passed) for (const key of condition) evaluated.add(key);
535
+ const branch = passed ? schema.then : schema.else;
536
+ if (branch !== undefined) {
537
+ const branchErrors = [];
538
+ const branchEvaluated = validateNode(value, branch, path, branchErrors, context);
539
+ errs.push(...branchErrors);
540
+ if (branchErrors.length === 0) for (const key of branchEvaluated) evaluated.add(key);
541
+ }
297
542
  }
298
543
 
299
544
  if (schema.not !== undefined) {
@@ -303,6 +548,24 @@ const validateNode = (value, schema, path, errs, context) => {
303
548
  errs.push({ path, rule: 'not', detail: 'value matched a forbidden subschema' });
304
549
  }
305
550
  }
551
+
552
+ if (
553
+ schema.unevaluatedProperties !== undefined &&
554
+ value !== null &&
555
+ typeof value === 'object' &&
556
+ !Array.isArray(value)
557
+ ) {
558
+ for (const [k, v] of Object.entries(value)) {
559
+ if (evaluated.has(k)) continue;
560
+ if (schema.unevaluatedProperties === false) {
561
+ errs.push({ path, rule: 'unevaluatedProperties', detail: `unevaluated property '${k}'` });
562
+ } else {
563
+ validateNode(v, schema.unevaluatedProperties, `${path}.${k}`, errs, context);
564
+ }
565
+ evaluated.add(k);
566
+ }
567
+ }
568
+ return evaluated;
306
569
  };
307
570
 
308
571
  /** @type {typeof import('./json-schema.d.mts').validateJson} */
@@ -315,13 +578,27 @@ export const validateJson = (
315
578
  } = {},
316
579
  ) => {
317
580
  const errs = [];
581
+ /** @type {{ path: string, rule: string, detail: string }[]} */
582
+ const schemaErrors = [];
583
+ if (!isSchema(schema)) {
584
+ return [
585
+ {
586
+ path: '$',
587
+ rule: 'schema',
588
+ detail: `expected a schema object or boolean, got ${typeOf(schema)}`,
589
+ },
590
+ ];
591
+ }
318
592
  validateNode(value, schema, '$', errs, {
319
593
  rootSchema: schema,
320
594
  resolveRef,
321
595
  base,
322
596
  referenceStack: [],
597
+ schemaErrors,
598
+ checkedSchemas: new WeakSet(),
599
+ reportedReferences: new WeakSet(),
323
600
  });
324
- return errs;
601
+ return [...schemaErrors, ...errs];
325
602
  };
326
603
 
327
604
  /**
@@ -111,6 +111,7 @@ const EXPECTED_SKILLS = Object.freeze([
111
111
  'planr-chair-review',
112
112
  'planr-challenger-review',
113
113
  'planr-cmo-review',
114
+ 'planr-connect',
114
115
  'planr-coo-review',
115
116
  'planr-cpo-review',
116
117
  'planr-cto-review',
@@ -128,6 +129,7 @@ const EXPECTED_SKILLS = Object.freeze([
128
129
  'planr-plan',
129
130
  'planr-plan-review',
130
131
  'planr-release',
132
+ 'planr-share',
131
133
  'planr-ship',
132
134
  'planr-spec',
133
135
  'planr-sprint',