@nakafa/aksara-contracts 0.46.0 → 0.47.1

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 (65) hide show
  1. package/README.md +4 -0
  2. package/dist/content.d.ts +8 -6
  3. package/dist/content.js +8 -3
  4. package/dist/math/arc.js +5 -1
  5. package/dist/math/base.js +6 -6
  6. package/dist/math/collision.d.ts +4 -4
  7. package/dist/math/collision.js +15 -9
  8. package/dist/math/coordinate.d.ts +24 -13
  9. package/dist/math/coordinate.js +16 -2
  10. package/dist/math/extent.d.ts +26 -17
  11. package/dist/math/extent.js +18 -2
  12. package/dist/math/intersection.d.ts +21 -11
  13. package/dist/math/intersection.js +14 -1
  14. package/dist/math/precision.js +3 -3
  15. package/dist/math/proximity.d.ts +11 -7
  16. package/dist/math/proximity.js +21 -4
  17. package/dist/math/rational.d.ts +6 -5
  18. package/dist/math/rational.js +6 -1
  19. package/dist/math/resolution.d.ts +1 -1
  20. package/dist/math/resolution.js +12 -4
  21. package/dist/math/scene.d.ts +22 -3
  22. package/dist/preview/auth.js +2 -1
  23. package/dist/preview/target.js +7 -0
  24. package/dist/program/curriculum.js +2 -1
  25. package/dist/program/snapshot/digest.js +32 -31
  26. package/dist/program/snapshot/hash.js +2 -1
  27. package/dist/program/spec.js +2 -1
  28. package/dist/projection/article.js +2 -1
  29. package/dist/projection/material.js +2 -1
  30. package/dist/projection/page.js +2 -1
  31. package/dist/projection/question.d.ts +544 -17
  32. package/dist/projection/question.js +17 -3
  33. package/dist/projection/verify.d.ts +4 -3
  34. package/dist/projection/verify.js +14 -7
  35. package/dist/question/answer.d.ts +12 -6
  36. package/dist/question/answer.js +17 -2
  37. package/dist/question/item.js +5 -4
  38. package/dist/question/response.js +3 -3
  39. package/dist/question/rubric.js +2 -1
  40. package/dist/quran/identity.js +11 -0
  41. package/dist/quran/notes.js +13 -0
  42. package/dist/quran/provenance.js +3 -2
  43. package/dist/quran/snapshot/digest.js +4 -3
  44. package/dist/quran/snapshot/hash.js +2 -1
  45. package/dist/quran/snapshot/row/hash.js +5 -4
  46. package/dist/quran/snapshot/spec.js +3 -2
  47. package/dist/renderer/compatibility.js +8 -5
  48. package/dist/renderer/contract.js +5 -4
  49. package/dist/runtime/protected/limits.js +2 -1
  50. package/dist/runtime/protected/spec.js +3 -3
  51. package/dist/text/json.d.ts +5 -0
  52. package/dist/text/json.js +5 -0
  53. package/dist/transport/request.d.ts +108 -108
  54. package/dist/tryout/closure/accounting.js +5 -4
  55. package/dist/tryout/closure/placement.js +3 -2
  56. package/dist/tryout/hash/catalog.js +11 -10
  57. package/dist/tryout/hash/content.js +2 -1
  58. package/dist/tryout/hash/placement.js +2 -1
  59. package/dist/tryout/language.js +2 -4
  60. package/dist/tryout/runtime/canonical.js +2 -1
  61. package/dist/tryout/scoring.d.ts +13 -9
  62. package/dist/tryout/scoring.js +17 -8
  63. package/dist/tryout/snapshot/canonical.js +2 -1
  64. package/dist/tryout/snapshot/hash.js +2 -1
  65. package/package.json +5 -1
@@ -1,4 +1,4 @@
1
- import { Effect, Schema, Stream } from "effect";
1
+ import { Effect, MutableHashMap, Option, Schema, Stream } from "effect";
2
2
  import { compareContentHeads, routeIdentity } from "#contracts/content";
3
3
  import { PublicPathSchema, ReleaseIdSchema, Sha256HashSchema, } from "#contracts/ids";
4
4
  import { digestProjections } from "#contracts/projection/digest";
@@ -31,6 +31,16 @@ export class ProjectionDigestError extends Schema.TaggedError()("ProjectionDiges
31
31
  releaseId: ReleaseIdSchema,
32
32
  }) {
33
33
  }
34
+ /** Creates the replay state that one stream of projections shares while it decodes. */
35
+ function projectionState() {
36
+ return {
37
+ firstIndexByRoute: MutableHashMap.empty(),
38
+ previous: undefined,
39
+ };
40
+ }
41
+ const VerifiedContentProjectionsSchema = Schema.Struct({
42
+ count: Schema.Finite,
43
+ });
34
44
  /** Decodes one row and applies canonical order and route uniqueness rules. */
35
45
  const decodeProjection = Effect.fn("AksaraContracts.decodeProjection")(function* (state, source, projectionIndex) {
36
46
  const projection = yield* Schema.decodeUnknownEffect(ContentProjectionSchema)(source, { onExcessProperty: "error" }).pipe(Effect.mapError(() => new ProjectionDecodeError({ projectionIndex })));
@@ -44,7 +54,7 @@ const decodeProjection = Effect.fn("AksaraContracts.decodeProjection")(function*
44
54
  }
45
55
  const { appLocale, publicPath } = projection;
46
56
  const identity = routeIdentity({ appLocale, publicPath });
47
- const firstIndex = state.firstIndexByRoute.get(identity);
57
+ const firstIndex = Option.getOrUndefined(MutableHashMap.get(state.firstIndexByRoute, identity));
48
58
  if (firstIndex !== undefined) {
49
59
  return yield* new ProjectionRouteError({
50
60
  duplicateIndex: projectionIndex,
@@ -52,16 +62,13 @@ const decodeProjection = Effect.fn("AksaraContracts.decodeProjection")(function*
52
62
  publicPath,
53
63
  });
54
64
  }
55
- state.firstIndexByRoute.set(identity, projectionIndex);
65
+ MutableHashMap.set(state.firstIndexByRoute, identity, projectionIndex);
56
66
  return projection;
57
67
  });
58
68
  /** Strictly decodes a replayable canonical content projection stream. */
59
69
  export function decodeContentProjections(projections) {
60
70
  return Stream.unwrap(Effect.sync(() => {
61
- const state = {
62
- firstIndexByRoute: new Map(),
63
- previous: undefined,
64
- };
71
+ const state = projectionState();
65
72
  return projections.pipe(Stream.zipWithIndex, Stream.mapEffect(([source, projectionIndex]) => decodeProjection(state, source, projectionIndex)));
66
73
  }));
67
74
  }
@@ -70,11 +70,12 @@ export type QuestionAnswerKey = typeof QuestionAnswerKeySchema.Type;
70
70
  * positive integer denominator that is one for a typed decimal. `fraction`
71
71
  * records that the learner wrote `p/q`.
72
72
  */
73
- export interface QuestionNumberAnswer {
74
- readonly denominator: BigDecimal.BigDecimal;
75
- readonly fraction: boolean;
76
- readonly numerator: BigDecimal.BigDecimal;
77
- }
73
+ declare const QuestionNumberAnswerSchema: Schema.Struct<{
74
+ readonly denominator: Schema.BigDecimal;
75
+ readonly fraction: Schema.Boolean;
76
+ readonly numerator: Schema.BigDecimal;
77
+ }>;
78
+ export type QuestionNumberAnswer = typeof QuestionNumberAnswerSchema.Type;
78
79
  /**
79
80
  * Checks whether one typed learner answer is blank: nothing remains once it is
80
81
  * read as visible text, so whitespace and invisible format characters alone
@@ -94,7 +95,11 @@ export declare function isBlankAnswer(answer: string): boolean;
94
95
  * separators, exponents, mixed numbers such as `1 1/2`, and empty input are
95
96
  * not numbers.
96
97
  */
97
- export declare function readNumberAnswer(input: string, language: AppLocaleCode): Option.Option<QuestionNumberAnswer>;
98
+ export declare function readNumberAnswer(input: string, language: AppLocaleCode): Option.Option<{
99
+ readonly denominator: BigDecimal.BigDecimal;
100
+ readonly fraction: boolean;
101
+ readonly numerator: BigDecimal.BigDecimal;
102
+ }>;
98
103
  /**
99
104
  * Grades one typed learner answer against its key, as every runtime must. A
100
105
  * text key matches when the answer normalizes to one accepted answer. A
@@ -147,3 +152,4 @@ export declare function canonicalQuestionAnswerKeyStructure(key: QuestionAnswerK
147
152
  ignoreCase: boolean;
148
153
  kind: "text";
149
154
  };
155
+ export {};
@@ -1,4 +1,4 @@
1
- import { BigDecimal, Option, Schema, String as Str } from "effect";
1
+ import { BigDecimal, HashSet, Option, Schema, String as Str } from "effect";
2
2
  const DECIMAL_PATTERN = /^(?:0|-?[1-9]\d*|-?(?:0|[1-9]\d*)\.\d*[1-9])$/u;
3
3
  const UNTYPABLE_CHARACTER_PATTERN = /[\p{Cc}\p{Cf}]|[^\S ]/u;
4
4
  const FORMAT_CHARACTER_PATTERN = /\p{Cf}/gu;
@@ -77,6 +77,11 @@ function visibleText(text) {
77
77
  .trim()
78
78
  .replace(WHITESPACE_PATTERN, " ");
79
79
  }
80
+ /** Text grading rules that every learner and accepted answer passes through. */
81
+ const TextKeyRulesSchema = Schema.Struct({
82
+ collapseWhitespace: Schema.Boolean,
83
+ ignoreCase: Schema.Boolean,
84
+ });
80
85
  /**
81
86
  * Normalizes one learner or accepted text answer exactly as graders compare
82
87
  * it. `ignoreCase` first applies the locale-independent Unicode lowercase
@@ -94,7 +99,7 @@ function normalizeTextAnswer(text, rules) {
94
99
  /** Checks that no two accepted answers grade as the same normalized text. */
95
100
  function hasDistinctAcceptedAnswers(key) {
96
101
  const normalized = key.acceptedAnswers.map((text) => normalizeTextAnswer(text, key));
97
- return new Set(normalized).size === normalized.length;
102
+ return HashSet.size(HashSet.fromIterable(normalized)) === normalized.length;
98
103
  }
99
104
  /**
100
105
  * Deterministic text answer key written in the delivery language. A learner
@@ -115,6 +120,16 @@ export const QuestionAnswerKeySchema = Schema.Union([
115
120
  QuestionNumberKeySchema,
116
121
  QuestionTextKeySchema,
117
122
  ]);
123
+ /**
124
+ * One learner number read exactly as `numerator / denominator`, with a
125
+ * positive integer denominator that is one for a typed decimal. `fraction`
126
+ * records that the learner wrote `p/q`.
127
+ */
128
+ const QuestionNumberAnswerSchema = Schema.Struct({
129
+ denominator: Schema.BigDecimal,
130
+ fraction: Schema.Boolean,
131
+ numerator: Schema.BigDecimal,
132
+ });
118
133
  /** Reads one signed ASCII number, where U+2212 is a minus sign. */
119
134
  function readSigned(text) {
120
135
  return BigDecimal.fromString(text.trim().replace("\u2212", "-"));
@@ -1,10 +1,11 @@
1
- import { Effect, Schema, Struct } from "effect";
1
+ import { Effect, Record as Rec, Schema, Struct } from "effect";
2
2
  import { AppLocaleCodeSchema, ArtifactLocaleSchema, artifactLocaleCode, } from "#contracts/locale";
3
3
  import { QuestionAnswerKeySchema } from "#contracts/question/answer";
4
4
  import { QuestionResponseLabelSchema } from "#contracts/question/label";
5
5
  import { AuthoredQuestionPointsSchema } from "#contracts/question/points";
6
6
  import { canonicalQuestionResponseStructure, QuestionResponseSchema, } from "#contracts/question/response";
7
7
  import { freezeQuestionRubric, QuestionRubricResponseSourceSchema, } from "#contracts/question/rubric";
8
+ import { encodeJsonText } from "#contracts/text/json";
8
9
  import { TryoutKeySchema } from "#contracts/tryout/key";
9
10
  const PositiveOrderSchema = Schema.Int.pipe(Schema.check(Schema.isGreaterThan(0)));
10
11
  /** One source-authored option before stable runtime identities are derived. */
@@ -122,11 +123,11 @@ function freezeQuestionResponse(response) {
122
123
  }
123
124
  /** Serializes response shape and answer key for locale comparison. */
124
125
  function responseStructure(response) {
125
- return JSON.stringify(canonicalQuestionResponseStructure(freezeQuestionResponse(response)));
126
+ return encodeJsonText(canonicalQuestionResponseStructure(freezeQuestionResponse(response)));
126
127
  }
127
128
  /** Requires locale siblings to preserve one response format and answer key. */
128
129
  function hasCoherentLocalizedResponses(input) {
129
- const responses = Object.values(input.responses).filter((response) => response !== undefined);
130
+ const responses = Rec.values(input.responses).filter((response) => response !== undefined);
130
131
  const [first] = responses;
131
132
  return (first !== undefined &&
132
133
  responses.every((response) => responseStructure(response) === responseStructure(first)));
@@ -134,7 +135,7 @@ function hasCoherentLocalizedResponses(input) {
134
135
  /** Requires a rubric item to take its worth from the rubric total alone. */
135
136
  function hasCoherentPoints(input) {
136
137
  return (input.points === undefined ||
137
- Object.values(input.responses).every((response) => response?.kind !== "rubric"));
138
+ Rec.values(input.responses).every((response) => response?.kind !== "rubric"));
138
139
  }
139
140
  /**
140
141
  * Complete source-owned item with optional shared-stimulus identity and points.
@@ -1,4 +1,4 @@
1
- import { Schema } from "effect";
1
+ import { HashSet, Schema } from "effect";
2
2
  import { canonicalQuestionAnswerKey, canonicalQuestionAnswerKeyStructure, QuestionAnswerKeySchema, } from "#contracts/question/answer";
3
3
  import { QuestionResponseLabelSchema } from "#contracts/question/label";
4
4
  import { canonicalQuestionRubric, canonicalQuestionRubricStructure, QuestionRubricResponseSchema, } from "#contracts/question/rubric";
@@ -58,13 +58,13 @@ const QuestionCategoryStatementSchema = Schema.Struct({
58
58
  });
59
59
  /** Checks stable category and statement identities plus valid references. */
60
60
  function hasCanonicalCategories(input) {
61
- const categoryKeys = new Set(input.categories.map(({ categoryKey }) => categoryKey));
61
+ const categoryKeys = HashSet.fromIterable(input.categories.map(({ categoryKey }) => categoryKey));
62
62
  return (input.categories.length >= 2 &&
63
63
  input.statements.length > 0 &&
64
64
  input.categories.every(({ categoryKey, order }, index) => order === index + 1 && categoryKey === `category-${order}`) &&
65
65
  input.statements.every(({ correctCategoryKey, order, statementKey }, index) => order === index + 1 &&
66
66
  statementKey === `statement-${order}` &&
67
- categoryKeys.has(correctCategoryKey)));
67
+ HashSet.has(categoryKeys, correctCategoryKey)));
68
68
  }
69
69
  const CategoryResponseSchema = Schema.Struct({
70
70
  categories: Schema.Array(QuestionCategorySchema),
@@ -16,7 +16,8 @@ export const QuestionRubricLabelSchema = Schema.Record(ActiveAppLocaleCodeSchema
16
16
  /**
17
17
  * Checks one criterion scale: two or more levels whose points strictly
18
18
  * ascend. A final-answer criterion has exactly two levels and its lower level
19
- * is worth zero, because a wrong result earns nothing.
19
+ * is worth zero, because a wrong result earns nothing. The criterion holds the
20
+ * scale facts shared by authored, frozen, and label-free rubric criteria.
20
21
  */
21
22
  function hasOrderedScale(criterion) {
22
23
  let previous = -1;
@@ -33,6 +33,10 @@ export const QuranNameProvenanceScopeSchema = Schema.TemplateLiteral([
33
33
  AppLocaleCodeSchema,
34
34
  "-surah-name",
35
35
  ]);
36
+ const QuranNameBindingSchema = Schema.Struct({
37
+ scope: QuranNameProvenanceScopeSchema,
38
+ sourceId: QuranEmbeddedSourceIdSchema,
39
+ });
36
40
  const QURAN_NAME_BY_LOCALE = {
37
41
  [ENGLISH_APP_LOCALE_CODE]: {
38
42
  scope: "en-surah-name",
@@ -47,6 +51,10 @@ const QURAN_NAME_BY_LOCALE = {
47
51
  sourceId: "kemenag-names",
48
52
  },
49
53
  };
54
+ const QuranTranslationBindingSchema = Schema.Struct({
55
+ scope: QuranTranslationProvenanceScopeSchema,
56
+ sourceId: QuranEmbeddedSourceIdSchema,
57
+ });
50
58
  const QURAN_TRANSLATION_BY_LOCALE = {
51
59
  [ENGLISH_APP_LOCALE_CODE]: {
52
60
  scope: "en-translation",
@@ -61,6 +69,9 @@ const QURAN_TRANSLATION_BY_LOCALE = {
61
69
  sourceId: "quranenc-indonesian",
62
70
  },
63
71
  };
72
+ const QuranTafsirBindingSchema = Schema.Struct({
73
+ sourceId: QuranSourceIdSchema,
74
+ });
64
75
  const QURAN_TAFSIR_BY_LOCALE = {
65
76
  [ENGLISH_APP_LOCALE_CODE]: { sourceId: "mokhtasar-english" },
66
77
  [GERMAN_APP_LOCALE_CODE]: { sourceId: "mokhtasar-german" },
@@ -34,6 +34,19 @@ export class QuranTranslationNotesError extends Schema.TaggedError()("QuranTrans
34
34
  ]),
35
35
  }) {
36
36
  }
37
+ const MarkerSchema = Schema.Struct({
38
+ end: Schema.Finite,
39
+ number: Schema.Finite,
40
+ start: Schema.Finite,
41
+ });
42
+ const TranslationAnalysisSchema = Schema.Union([
43
+ Schema.TaggedStruct("Failure", {
44
+ reason: QuranTranslationNotesError.fields.reason,
45
+ }),
46
+ Schema.TaggedStruct("Success", {
47
+ document: QuranTranslationDocumentSchema,
48
+ }),
49
+ ]);
37
50
  const QuranTranslationSourceSchema = Schema.Struct({
38
51
  footnotes: Schema.String,
39
52
  text: QuranMeaningfulTextSchema,
@@ -6,6 +6,7 @@ import { canonicalizeQuranAttribution } from "#contracts/quran/attribution";
6
6
  import { QuranNameProvenanceScopeSchema, QuranTranslationProvenanceScopeSchema, quranNameProvenanceScope, quranNameSourceForScope, quranTafsirSourceId, quranTranslationProvenanceScope, quranTranslationSourceForScope, } from "#contracts/quran/identity";
7
7
  import { QuranProvenanceStatusSchema } from "#contracts/quran/snapshot/spec";
8
8
  import { hasCompleteQuranSourceCopy, QuranSourceAttributionSchema, } from "#contracts/quran/source";
9
+ import { encodeJsonText } from "#contracts/text/json";
9
10
  /** Quran source fields that require independent provenance decisions. */
10
11
  const QuranStaticProvenanceScopeSchema = Schema.Literals([
11
12
  "arabic-text",
@@ -106,7 +107,7 @@ export class QuranProvenanceHashError extends Schema.TaggedError()("QuranProvena
106
107
  const PROVENANCE_DOMAIN = "nakafa.aksara.quran-provenance";
107
108
  /** Produces stable JSON for one reviewed Quran provenance record. */
108
109
  export function canonicalizeQuranProvenance(record) {
109
- return JSON.stringify({
110
+ return encodeJsonText({
110
111
  attribution: canonicalizeQuranAttribution(record.attribution),
111
112
  evidence: record.evidence,
112
113
  scope: record.scope,
@@ -119,7 +120,7 @@ export const hashQuranProvenance = Effect.fn("AksaraContracts.hashQuranProvenanc
119
120
  try: () => {
120
121
  const hash = createHash("sha256")
121
122
  .update(`${PROVENANCE_DOMAIN}\n`)
122
- .update(JSON.stringify(input.activeAppLocales))
123
+ .update(encodeJsonText(input.activeAppLocales))
123
124
  .update("\n");
124
125
  for (const record of input.records) {
125
126
  hash.update(canonicalizeQuranProvenance(record));
@@ -5,6 +5,7 @@ import { AppLocaleSchema } from "#contracts/locale";
5
5
  import { hashQuranRow, QuranRowHashError, } from "#contracts/quran/snapshot/row/hash";
6
6
  import { quranSourceIds } from "#contracts/quran/source";
7
7
  import { QURAN_ATTRIBUTION_COUNT, QURAN_CHUNK_SIZE, QURAN_SURAH_COUNT, QURAN_VERSE_COUNT, } from "#contracts/quran/spec";
8
+ import { encodeJsonText } from "#contracts/text/json";
8
9
  const RUNTIME_DOMAIN = "nakafa.aksara.quran-runtime";
9
10
  const SEARCH_DOMAIN = "nakafa.aksara.quran-search";
10
11
  const PROJECTION_DOMAIN = "nakafa.aksara.quran-projection";
@@ -112,9 +113,9 @@ class QuranDigestState {
112
113
  const expectedTafsir = this.#activeAppLocales.includes(AppLocaleSchema.make("id"))
113
114
  ? ["id"]
114
115
  : [];
115
- return payload.verses.every((verse) => JSON.stringify(verse.translations.map((translation) => translation.appLocale)) === JSON.stringify(this.#activeAppLocales) &&
116
- JSON.stringify(verse.tafsir.map((tafsir) => tafsir.appLocale)) ===
117
- JSON.stringify(expectedTafsir));
116
+ return payload.verses.every((verse) => encodeJsonText(verse.translations.map((translation) => translation.appLocale)) === encodeJsonText(this.#activeAppLocales) &&
117
+ encodeJsonText(verse.tafsir.map((tafsir) => tafsir.appLocale)) ===
118
+ encodeJsonText(expectedTafsir));
118
119
  }
119
120
  /** Advances deterministic identity state after one accepted row. */
120
121
  advance(payload) {
@@ -2,13 +2,14 @@ import { createHash } from "node:crypto";
2
2
  import { Effect, Schema } from "effect";
3
3
  import { Sha256HashSchema } from "#contracts/ids";
4
4
  import { QURAN_SNAPSHOT_FORMAT, QuranSnapshotSchema, } from "#contracts/quran/snapshot/spec";
5
+ import { encodeJsonText } from "#contracts/text/json";
5
6
  const SNAPSHOT_DOMAIN = "nakafa.aksara.localized-quran-snapshot";
6
7
  /** Node could not compute a deterministic Quran snapshot identity. */
7
8
  export class QuranSnapshotHashError extends Schema.TaggedError()("QuranSnapshotHashError", {}) {
8
9
  }
9
10
  /** Serializes Quran snapshot facts in stable signed field order. */
10
11
  export function canonicalizeQuranSnapshot(input) {
11
- return JSON.stringify({
12
+ return encodeJsonText({
12
13
  activeAppLocales: input.activeAppLocales,
13
14
  attributionCount: input.attributionCount,
14
15
  chunkCount: input.chunkCount,
@@ -4,6 +4,7 @@ import { canonicalizeLearningGraphIdentity } from "#contracts/graph/spec";
4
4
  import { Sha256HashSchema } from "#contracts/ids";
5
5
  import { canonicalizeQuranAttribution } from "#contracts/quran/attribution";
6
6
  import { QuranSnapshotRowSchema, } from "#contracts/quran/snapshot/row";
7
+ import { encodeJsonText } from "#contracts/text/json";
7
8
  const ROW_DOMAIN = "nakafa.aksara.quran-row";
8
9
  /** Node could not compute a deterministic Quran row identity. */
9
10
  export class QuranRowHashError extends Schema.TaggedError()("QuranRowHashError", { scope: Schema.Literals(["digest", "row"]) }) {
@@ -54,7 +55,7 @@ function canonicalizeVerse(verse) {
54
55
  /** Produces stable JSON for one exhaustive current Quran payload. */
55
56
  export function canonicalizeQuranRow(payload) {
56
57
  if (payload.kind === "quran-attribution") {
57
- return JSON.stringify({
58
+ return encodeJsonText({
58
59
  activeAppLocales: payload.activeAppLocales,
59
60
  kind: payload.kind,
60
61
  sources: payload.sources.map(canonicalizeQuranAttribution),
@@ -62,7 +63,7 @@ export function canonicalizeQuranRow(payload) {
62
63
  });
63
64
  }
64
65
  if (payload.kind === "quran-surah") {
65
- return JSON.stringify({
66
+ return encodeJsonText({
66
67
  kind: payload.kind,
67
68
  name: {
68
69
  arabic: payload.name.arabic,
@@ -82,7 +83,7 @@ export function canonicalizeQuranRow(payload) {
82
83
  });
83
84
  }
84
85
  if (payload.kind === "quran-chunk") {
85
- return JSON.stringify({
86
+ return encodeJsonText({
86
87
  firstQuranNumber: payload.firstQuranNumber,
87
88
  firstVerse: payload.firstVerse,
88
89
  kind: payload.kind,
@@ -91,7 +92,7 @@ export function canonicalizeQuranRow(payload) {
91
92
  verses: payload.verses.map(canonicalizeVerse),
92
93
  });
93
94
  }
94
- return JSON.stringify({
95
+ return encodeJsonText({
95
96
  appLocale: payload.appLocale,
96
97
  graph: canonicalizeLearningGraphIdentity(payload.graph),
97
98
  kind: payload.kind,
@@ -3,6 +3,7 @@ import { Sha256HashSchema } from "#contracts/ids";
3
3
  import { ActiveAppLocaleListSchema, AppLocaleSchema, } from "#contracts/locale";
4
4
  import { quranSourceFileCount } from "#contracts/quran/source";
5
5
  import { QURAN_ATTRIBUTION_COUNT, QURAN_SURAH_COUNT, QURAN_VERSE_COUNT, } from "#contracts/quran/spec";
6
+ import { encodeJsonText } from "#contracts/text/json";
6
7
  /** Semantic wire identity of the current localized Quran snapshot. */
7
8
  export const QURAN_SNAPSHOT_FORMAT = "localized-quran-snapshot";
8
9
  const CountSchema = Schema.Int.pipe(Schema.check(Schema.isGreaterThanOrEqualTo(0)));
@@ -39,8 +40,8 @@ function hasCompleteSnapshotCounts(input) {
39
40
  input.verseCount === QURAN_VERSE_COUNT &&
40
41
  input.searchCount === QURAN_SURAH_COUNT * input.activeAppLocales.length &&
41
42
  input.sourceFileCount === quranSourceFileCount(input.activeAppLocales) &&
42
- JSON.stringify(input.tafsirLocales) ===
43
- JSON.stringify(hasIndonesian ? ["id"] : []));
43
+ encodeJsonText(input.tafsirLocales) ===
44
+ encodeJsonText(hasIndonesian ? ["id"] : []));
44
45
  }
45
46
  /** Checks runtime and search arithmetic for complete projection inventory. */
46
47
  function hasCoherentProjectionCounts(input) {
@@ -1,4 +1,4 @@
1
- import { Effect, Schema } from "effect";
1
+ import { Effect, HashSet, Schema } from "effect";
2
2
  import { ArtifactRendererComponentMissingError, ArtifactRendererDomainUnpublishedError, } from "#contracts/artifact/spec";
3
3
  import { RendererComponentNameSchema, } from "#contracts/renderer/component";
4
4
  import { selectRendererDomainCapability, } from "#contracts/renderer/contract";
@@ -19,9 +19,9 @@ export class RendererManifestComponentUnsupportedError extends Schema.TaggedErro
19
19
  }
20
20
  /** Requires every frozen renderer name from one physical registry. */
21
21
  const verifyCapabilitySuperset = Effect.fn("AksaraContracts.verifyRendererCapabilitySuperset")(function* (frozen, live, rendererScope) {
22
- const supported = new Set(live);
22
+ const supported = HashSet.fromIterable(live);
23
23
  for (const componentName of frozen) {
24
- if (supported.has(componentName)) {
24
+ if (HashSet.has(supported, componentName)) {
25
25
  continue;
26
26
  }
27
27
  return yield* new RendererManifestComponentUnsupportedError({
@@ -58,9 +58,12 @@ export const verifyContentRendererCompatibility = Effect.fn("AksaraContracts.ver
58
58
  });
59
59
  }
60
60
  const domain = yield* selectRendererDomainCapability(manifest, payload.rendererDomain);
61
- const available = new Set([...manifest.base, ...domain.components]);
61
+ const available = HashSet.fromIterable([
62
+ ...manifest.base,
63
+ ...domain.components,
64
+ ]);
62
65
  for (const componentName of payload.requiredComponents) {
63
- if (!available.has(componentName)) {
66
+ if (!HashSet.has(available, componentName)) {
64
67
  return yield* new ArtifactRendererComponentMissingError({
65
68
  componentName,
66
69
  contentKey: payload.contentKey,
@@ -1,7 +1,8 @@
1
- import { Effect, Schema } from "effect";
1
+ import { Effect, HashSet, Schema } from "effect";
2
2
  import { Sha256HashSchema } from "#contracts/ids";
3
3
  import { RendererComponentsSchema, } from "#contracts/renderer/component";
4
4
  import { RENDERER_DOMAINS, RendererDomainSchema, } from "#contracts/renderer/domain";
5
+ import { encodeJsonText } from "#contracts/text/json";
5
6
  import { compareCodeUnits } from "#contracts/text/order";
6
7
  /** Stable format for the one current domain-scoped renderer manifest. */
7
8
  export const RENDERER_MANIFEST_FORMAT = "nakafa-mdx-renderer";
@@ -30,10 +31,10 @@ export const RendererManifestDomainsSchema = Schema.Array(RendererDomainCapabili
30
31
  }));
31
32
  /** Keeps base component names out of every route-owned registry. */
32
33
  function hasDistinctBaseComponents(manifest) {
33
- const baseNames = new Set(manifest.base);
34
+ const baseNames = HashSet.fromIterable(manifest.base);
34
35
  for (const domain of manifest.domains) {
35
36
  for (const name of domain.components) {
36
- if (baseNames.has(name)) {
37
+ if (HashSet.has(baseNames, name)) {
37
38
  return false;
38
39
  }
39
40
  }
@@ -72,7 +73,7 @@ export class RendererManifestHashMismatchError extends Schema.TaggedError()("Ren
72
73
  }
73
74
  /** Serializes the exact domain-scoped renderer tuple covered by SHA-256. */
74
75
  export function canonicalizeRendererManifestContract(input) {
75
- return JSON.stringify([
76
+ return encodeJsonText([
76
77
  RENDERER_MANIFEST_FORMAT,
77
78
  input.base,
78
79
  sortRendererDomains(input.domains).map(({ name, components }) => ({
@@ -1,3 +1,4 @@
1
+ import { encodeJsonText } from "#contracts/text/json";
1
2
  /** Maximum protected selectors accepted in one retained-snapshot read. */
2
3
  export const MAX_PROTECTED_RUNTIME_SELECTORS = 64;
3
4
  /** Maximum UTF-8 bytes accepted by the protected batch endpoint. */
@@ -6,7 +7,7 @@ export const MAX_PROTECTED_RUNTIME_REQUEST_BYTES = 64 * 1024;
6
7
  export const MAX_PROTECTED_RUNTIME_RESPONSE_BYTES = 4 * 1024 * 1024;
7
8
  /** Measures the exact JSON bytes written by the protected HTTP response. */
8
9
  export function protectedRuntimeResponseBytes(response) {
9
- return new TextEncoder().encode(JSON.stringify(response)).byteLength;
10
+ return new TextEncoder().encode(encodeJsonText(response)).byteLength;
10
11
  }
11
12
  /** Keeps every found result inside the protected response wire ceiling. */
12
13
  export function hasBoundedProtectedRuntimeResponse(response) {
@@ -1,4 +1,4 @@
1
- import { Effect, Schema } from "effect";
1
+ import { Effect, HashSet, Schema } from "effect";
2
2
  import { SignedContentArtifactSchema, } from "#contracts/content";
3
3
  import { decodeContract } from "#contracts/decode";
4
4
  import { ContentKeySchema, CorpusSourcePathSchema, Sha256HashSchema, } from "#contracts/ids";
@@ -33,7 +33,7 @@ export const ProtectedContentRuntimeSelectorSchema = Schema.Struct({
33
33
  /** Checks a batch never requests the same immutable artifact twice. */
34
34
  function hasUniqueSelectors(selectors) {
35
35
  const hashes = selectors.map(({ artifactHash }) => artifactHash);
36
- return new Set(hashes).size === hashes.length;
36
+ return HashSet.size(HashSet.fromIterable(hashes)) === hashes.length;
37
37
  }
38
38
  const ProtectedContentRuntimeSelectorsSchema = Schema.Array(ProtectedContentRuntimeSelectorSchema).pipe(Schema.check(Schema.isMinLength(1)), Schema.check(Schema.isMaxLength(MAX_PROTECTED_RUNTIME_SELECTORS)), Schema.check(Schema.makeFilter(hasUniqueSelectors, {
39
39
  message: "Expected unique protected runtime artifact selectors.",
@@ -53,7 +53,7 @@ export const ProtectedContentRuntimeItemSchema = Schema.Struct({
53
53
  /** Checks one protected response never repeats an immutable artifact. */
54
54
  function hasUniqueArtifacts(items) {
55
55
  const hashes = items.map(({ artifact }) => artifact.artifactHash);
56
- return new Set(hashes).size === hashes.length;
56
+ return HashSet.size(HashSet.fromIterable(hashes)) === hashes.length;
57
57
  }
58
58
  const ProtectedContentRuntimeItemsSchema = Schema.Array(ProtectedContentRuntimeItemSchema).pipe(Schema.check(Schema.isMinLength(1)), Schema.check(Schema.isMaxLength(MAX_PROTECTED_RUNTIME_SELECTORS)), Schema.check(Schema.makeFilter(hasUniqueArtifacts, {
59
59
  message: "Expected unique protected runtime artifacts.",
@@ -0,0 +1,5 @@
1
+ import { Schema } from "effect";
2
+ /** The JSON text codec: JSON.stringify when encoding and JSON.parse when decoding, nothing else. */
3
+ export declare const JsonTextSchema: Schema.fromJsonString<Schema.Unknown>;
4
+ /** Writes a value as JSON text with exactly the bytes JSON.stringify writes. */
5
+ export declare const encodeJsonText: (input: unknown, options?: import("effect/SchemaAST").ParseOptions) => string;
@@ -0,0 +1,5 @@
1
+ import { Schema } from "effect";
2
+ /** The JSON text codec: JSON.stringify when encoding and JSON.parse when decoding, nothing else. */
3
+ export const JsonTextSchema = Schema.fromJsonString(Schema.Unknown);
4
+ /** Writes a value as JSON text with exactly the bytes JSON.stringify writes. */
5
+ export const encodeJsonText = Schema.encodeSync(JsonTextSchema);