harn-stdlib 0.10.40

Embedded Harn standard library source catalog
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/**
 * std/schema — ergonomic schema builders and typed-value helpers
 *
 * Import with: import "std/schema"
 *
 * @effects: []
 * @errors: []
 */
pub import {
  JsonTypedReport,
  JsonTypedStage,
  SchemaContract,
  SchemaContractFailure,
  SchemaFailure,
  SchemaIssue,
  SchemaReport,
  SchemaResult,
  SchemaValidator,
  SchemaValidatorOptions,
  ValidationIssue,
  ValidationRule,
} from "std/schema/contracts"

fn __validation_schema_issue(raw: unknown) -> ValidationIssue {
  if type_of(raw) != "dict" {
    return {code: "schema.invalid", message: to_string(raw), metadata: {schema_issue: raw}}
  }
  let issue: ValidationIssue = {
    code: to_string(raw?.code ?? "schema.invalid"),
    message: to_string(raw?.message ?? raw),
    metadata: {schema_issue: raw},
  }
  if raw?.path != nil {
    issue = issue + {path: to_string(raw.path)}
  }
  return issue
}

fn __validation_schema_issues(found: list<unknown>) -> list<ValidationIssue> {
  let issues: list<ValidationIssue> = []
  for raw in found {
    issues = issues + [__validation_schema_issue(raw)]
  }
  return issues
}

/**
 * Build one named validation rule. Return an empty issue list on success.
 *
 * @effects: []
 * @errors: [validation]
 */
pub fn validation_rule<T>(
  name: string,
  check: fn(T) -> list<ValidationIssue>,
) -> ValidationRule<T> {
  const clean_name = trim(name)
  if clean_name == "" {
    throw "std/schema: validation rule name is required"
  }
  return {name: clean_name, check: check}
}

/**
 * Build one stable issue returned by a validation rule.
 *
 * @effects: []
 * @errors: [validation]
 */
pub fn validation_issue(
  code: string,
  message: string,
  path: string? = nil,
  metadata: dict? = nil,
) -> ValidationIssue {
  const clean_code = trim(code)
  const clean_message = trim(message)
  if clean_code == "" || clean_message == "" {
    throw "std/schema: validation issue code and message are required"
  }
  let issue: ValidationIssue = {code: clean_code, message: clean_message}
  if path != nil {
    issue = issue + {path: path}
  }
  if metadata != nil {
    issue = issue + {metadata: metadata}
  }
  return issue
}

/**
 * Bind a structural schema to ordered deterministic validation rules.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_contract<T>(
  schema: Schema<T>,
  rules: list<ValidationRule<T>>,
  apply_defaults: bool = false,
) -> SchemaContract<T> {
  return {schema: schema, rules: rules, apply_defaults: apply_defaults}
}

/**
 * Structurally validate a value, then collect every rule issue in order. The
 * function never throws: a broken rule becomes a `rule_error` failure.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_contract_check<T>(
  value: unknown,
  contract: SchemaContract<T>,
) -> Result<T, SchemaContractFailure> {
  const report = schema_report(value, contract.schema, contract.apply_defaults)
  if !report.ok {
    const failure: SchemaContractFailure = {
      kind: "schema_invalid",
      detail: report.message,
      issues: __validation_schema_issues(report.issues),
    }
    return Err(failure)
  }
  const validated: T = report.value
  let issues: list<ValidationIssue> = []
  for rule in contract.rules {
    const checked = try {
      rule.check(validated)
    }
    if !is_ok(checked) {
      const message = to_string(unwrap_err(checked)?.message ?? unwrap_err(checked))
      const failure: SchemaContractFailure = {
        kind: "rule_error",
        detail: "validation rule '" + rule.name + "' failed: " + message,
        issues: [{code: "rule.error", message: message, rule: rule.name}],
      }
      return Err(failure)
    }
    for issue in unwrap(checked) {
      issues = issues
        + [
        if issue.rule == nil {
          issue + {rule: rule.name}
        } else {
          issue
        },
      ]
    }
  }
  if len(issues) > 0 {
    const failure: SchemaContractFailure = {
      kind: "rule_failed",
      detail: to_string(len(issues)) + " validation issue(s)",
      issues: issues,
    }
    return Err(failure)
  }
  return Ok(validated)
}

/**
 * Build a schema that accepts any value.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_any() -> any {
  return {type: "any"}
}

/**
 * Build a schema that accepts strings.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_string() -> any {
  return {type: "string"}
}

/**
 * Build a schema that accepts integers.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_int() -> any {
  return {type: "int"}
}

/**
 * Build a schema that accepts floats.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_float() -> any {
  return {type: "float"}
}

/**
 * Build a schema that accepts booleans.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_bool() -> any {
  return {type: "bool"}
}

/**
 * Build a schema that accepts only `nil`.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_nil() -> any {
  return {type: "nil"}
}

/**
 * Build a schema that accepts only the given constant value.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_literal(value: unknown) -> any {
  return {const: value}
}

/**
 * Build a schema that accepts any value in `values`.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_enum(values: list<unknown>) -> any {
  return {enum: values}
}

/**
 * Build a list schema, optionally constraining item shape and adding options.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_list(item_schema: unknown = nil, options: dict? = nil) -> any {
  let out: dict = {type: "list"}
  if item_schema != nil {
    out = out + {items: item_schema}
  }
  if options != nil {
    out = schema_extend(out, options)
  }
  return out
}

/**
 * Alias for `schema_list(...)` using array terminology.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_array(item_schema: unknown = nil, options: dict? = nil) -> any {
  return schema_list(item_schema, options)
}

/**
 * Build a dict schema, optionally constraining value shape and adding options.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_dict(value_schema: unknown = nil, options: dict? = nil) -> any {
  let out: dict = {type: "dict"}
  if value_schema != nil {
    out = out + {additional_properties: value_schema}
  }
  if options != nil {
    out = schema_extend(out, options)
  }
  return out
}

/**
 * Tag a field schema as required or optional for use in `schema_object`.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_field(schema: dict, required: bool = true) -> any {
  return schema + {required: required}
}

/**
 * Build an object schema from a `{name: field_schema}` map. Fields default to
 * required unless tagged with `schema_field(..., false)` or `schema_default`.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_object(fields: dict, options: dict? = nil) -> any {
  let properties = {}
  let required = []
  for entry in fields {
    const raw_schema = entry.value
    const is_required = raw_schema.required == nil || raw_schema.required
    const field_schema = schema_omit(raw_schema, ["required"])
    properties = properties + {[entry.key]: field_schema}
    if is_required {
      required = required + [entry.key]
    }
  }
  let out: dict = {type: "dict", properties: properties}
  if len(required) > 0 {
    out = out + {required: required}
  }
  if options != nil {
    out = schema_extend(out, options)
  }
  return out
}

/**
 * Return a dict/object schema that rejects unknown keys.
 *
 * This is the preferred builder for option bags, receipts, structured LLM
 * outputs, and host-contract payloads where unexpected keys should fail closed
 * instead of drifting through validation.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_closed_object(fields: dict, options: dict? = nil) -> any {
  if options == nil {
    return schema_object(fields, {additional_properties: false})
  }
  return schema_object(fields, options + {additional_properties: false})
}

/**
 * Alias for `schema_closed_object(...)` using strict-schema terminology.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_strict_object(fields: dict, options: dict? = nil) -> any {
  return schema_closed_object(fields, options)
}

/**
 * Build a union schema matching any one of `branches`.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_union(branches: list<unknown>) -> any {
  return {union: branches}
}

/**
 * Build an intersection schema matching all of `branches`.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_all_of(branches: list<unknown>) -> any {
  return {all_of: branches}
}

/**
 * Return `schema` widened to also accept `nil`.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_nullable(schema: dict) -> any {
  return schema_extend(schema, {nullable: true})
}

/**
 * Return `schema` made optional with the given default value.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_default(schema: dict, value: unknown) -> any {
  return schema + {default: value, required: false}
}

/**
 * Return a schema keeping only the named keys.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_pick_keys(schema: dict, keys: list<string>) -> any {
  return schema_pick(schema, keys)
}

/**
 * Return a schema dropping the named keys.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_omit_keys(schema: dict, keys: list<string>) -> any {
  return schema_omit(schema, keys)
}

/**
 * Return a schema with every field made optional.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_partial_deep(schema: dict) -> any {
  return schema_partial(schema)
}

/**
 * Render `schema` as a JSON Schema dict.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_json(schema: unknown) -> dict {
  return schema_to_json_schema(schema)
}

/**
 * Render `schema` as an OpenAPI Schema dict.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_openapi(schema: unknown) -> dict {
  return schema_to_openapi_schema(schema)
}

/**
 * Return a reusable validator object for a schema.
 *
 * This is the preferred boundary shape when a harness author needs to validate
 * several values against the same contract without repeating freeform
 * `schema_*` calls or hand-written `type_of` guards.
 *
 * @effects: []
 * @errors: []
 */
pub fn schema_validator<T>(
  schema: dict | Schema<T>,
  options: SchemaValidatorOptions? = nil,
) -> SchemaValidator<T> {
  const default_apply_defaults = options?.apply_defaults ?? false
  return {
    schema: schema,
    is: fn(value) { return schema_is(value, schema) },
    check: fn(value) { return schema_check(value, schema) },
    parse: fn(value) { return schema_parse(value, schema) },
    report: fn(value, apply_defaults = default_apply_defaults) { return schema_report(
      value,
      schema,
      apply_defaults,
    ) },
    expect: fn(value, apply_defaults = default_apply_defaults) { return schema_expect(
      value,
      schema,
      apply_defaults,
    ) },
    errors: fn(value, apply_defaults = default_apply_defaults) { return schema_report(
      value,
      schema,
      apply_defaults,
    ).errors },
    issues: fn(value, apply_defaults = default_apply_defaults) { return schema_report(
      value,
      schema,
      apply_defaults,
    ).issues },
    json_schema: fn() { return schema_to_json_schema(schema) },
    openapi_schema: fn() { return schema_to_openapi_schema(schema) },
  }
}

/**
 * Convert a JSON Schema dict into a native schema definition.
 *
 * @effects: []
 * @errors: []
 */
pub fn from_json_schema(schema: dict) -> any {
  return schema_from_json_schema(schema)
}

/**
 * Convert an OpenAPI Schema dict into a native schema definition.
 *
 * @effects: []
 * @errors: []
 */
pub fn from_openapi_schema(schema: dict) -> any {
  return schema_from_openapi_schema(schema)
}

/**
 * Validate a value and return `Result.Ok(value)` or `Result.Err(SchemaFailure)`.
 *
 * @effects: []
 * @errors: []
 */
pub fn get_typed_result<T>(
  value: unknown,
  schema: dict | Schema<T>,
  apply_defaults: bool = false,
) -> SchemaResult<T> {
  if apply_defaults {
    return schema_parse(value, schema)
  }
  return schema_check(value, schema)
}

/**
 * Validate a value and return a structured `SchemaReport`.
 *
 * @effects: []
 * @errors: []
 */
pub fn get_typed_report<T>(
  value: unknown,
  schema: dict | Schema<T>,
  apply_defaults: bool = false,
) -> SchemaReport<T> {
  // `schema_report` builds the report shape dynamically; contracts.harn owns the
  // `SchemaReport<T>` type. Bind through `any` so the runtime value adopts the
  // declared contract without re-describing the shape here.
  const report: any = schema_report(value, schema, apply_defaults)
  return report
}

/**
 * Parse JSON text and validate the parsed value against a schema in one step.
 * `stage` is `json_parse` when the text is malformed, otherwise `schema`.
 *
 * @effects: []
 * @errors: []
 */
pub fn parse_json_typed_report<T>(
  text: string,
  schema: dict | Schema<T>,
  apply_defaults: bool = false,
) -> JsonTypedReport<T> {
  const parsed = try {
    json_parse(text ?? "")
  }
  if !is_ok(parsed) {
    // JSON never reached the schema; report the parse failure at the json_parse
    // stage. Bind through `any` so the literal adopts the generic
    // `JsonTypedReport<T>` contract owned in contracts.harn.
    const message: string = to_string(unwrap_err(parsed)?.message ?? "invalid JSON")
    const failure: any = {
      ok: false,
      message: message,
      errors: [message],
      issues: [],
      stage: "json_parse",
    }
    return failure
  }
  const report: any = get_typed_report(unwrap(parsed), schema, apply_defaults) + {stage: "schema"}
  return report
}

/**
 * Parse JSON text and return the typed/defaulted value, or `fallback` if either
 * JSON parsing or schema validation fails.
 *
 * @effects: []
 * @errors: []
 */
pub fn parse_json_typed<T>(
  text: string,
  schema: dict | Schema<T>,
  fallback: T? = nil,
  apply_defaults: bool = false,
) -> T? {
  const report = parse_json_typed_report(text, schema, apply_defaults)
  if report.ok {
    return report.value
  }
  return fallback
}

/**
 * Return structured validation issues for a value/schema pair.
 *
 * @effects: []
 * @errors: []
 */
pub fn get_typed_issues<T>(
  value: unknown,
  schema: dict | Schema<T>,
  apply_defaults: bool = false,
) -> list<SchemaIssue> {
  return get_typed_report(value, schema, apply_defaults).issues
}

/**
 * Return rendered validation error messages for a value/schema pair.
 *
 * @effects: []
 * @errors: []
 */
pub fn get_typed_errors<T>(
  value: unknown,
  schema: dict | Schema<T>,
  apply_defaults: bool = false,
) -> list<string> {
  return get_typed_report(value, schema, apply_defaults).errors
}

/**
 * Validate a value and return the normalized/defaulted value, throwing on failure.
 *
 * @effects: []
 * @errors: ["schema validation failure"]
 */
pub fn get_typed_value<T>(
  value: unknown,
  schema: dict | Schema<T>,
  apply_defaults: bool = false,
) -> T {
  return schema_expect(value, schema, apply_defaults)
}

/**
 * Alias for `get_typed_value` when the caller wants assertion-style wording.
 *
 * @effects: []
 * @errors: ["schema validation failure"]
 */
pub fn expect_typed_value<T>(
  value: unknown,
  schema: dict | Schema<T>,
  apply_defaults: bool = false,
) -> T {
  return get_typed_value(value, schema, apply_defaults)
}

/**
 * Report whether `value` satisfies `schema`.
 *
 * @effects: []
 * @errors: []
 */
pub fn is_type(value: unknown, schema: unknown) -> bool {
  return schema_is(value, schema)
}