@atscript/typescript 0.2.9 → 0.2.10

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.
package/dist/utils.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as DECIMAL_RE, A as propAtChain, B as acceptsNull$1, C as createAnnotatedTypeNode, D as isAnnotatedType, E as defineAnnotatedType, F as VALIDATOR_MESSAGES, G as $ak, H as detectDiscriminator, I as formatCodeOf, J as metaEmpty, K as $nr, L as formatValidatorMessage, M as ValidatorError, N as unionDiscriminator, O as isAnnotatedTypeOfPrimitive, P as VALIDATOR_ERROR_CODES, Q as typeWriteCount, R as localizeErrors, S as annotate, T as createObjectTypeDef, U as jsonSchemaPattern, V as registerCompiledCheck, W as statelessRegExp, X as invalidateCompiledValidators, Y as watchLayer, Z as touched, _ as pendingStatements, a as userTextOf, b as cutKey, c as $blk, d as $fc, et as VALIDATOR_KEYS, f as $ft, g as appliedBlockModules, h as $sh, i as userTextKeys, j as Validator, k as isPhantomType, l as $end, m as $q, nt as boundOf, o as uniqueName, p as $ps, q as LayerMap, r as registerUserText, s as $alias, t as $ut, tt as arrayKeyProps, u as $f, w as createMetadataMap, x as enterCut, y as cutAs, z as messagesTranslator } from "./user-text-fz-TpY_H.mjs";
1
+ import { $ as DECIMAL_RE, A as propAtChain, B as acceptsNull$2, C as createAnnotatedTypeNode, D as isAnnotatedType, E as defineAnnotatedType, F as VALIDATOR_MESSAGES, G as $ak, H as detectDiscriminator, I as formatCodeOf, J as metaEmpty, K as $nr, L as formatValidatorMessage, M as ValidatorError, N as unionDiscriminator, O as isAnnotatedTypeOfPrimitive, P as VALIDATOR_ERROR_CODES, Q as typeWriteCount, R as localizeErrors, S as annotate, T as createObjectTypeDef, U as jsonSchemaPattern, V as registerCompiledCheck, W as statelessRegExp, X as invalidateCompiledValidators, Y as watchLayer, Z as touched, _ as pendingStatements, a as userTextOf, b as cutKey, c as $blk, d as $fc, et as VALIDATOR_KEYS, f as $ft, g as appliedBlockModules, h as $sh, i as userTextKeys, j as Validator, k as isPhantomType, l as $end, m as $q, nt as boundOf, o as uniqueName, p as $ps, q as LayerMap, r as registerUserText, s as $alias, t as $ut, tt as arrayKeyProps, u as $f, w as createMetadataMap, x as enterCut, y as cutAs, z as messagesTranslator } from "./user-text-DS0lorlV.mjs";
2
2
 
3
3
  //#region packages/typescript/src/runtime/copy-on-change.ts
4
4
  /**
@@ -683,7 +683,7 @@ function collectLeaves(items, out) {
683
683
  * `inherited`: the normalizer flags of the unions `def` is in.
684
684
  */ function holds(def, input, inherited = 0) {
685
685
  if (input === void 0) return true;
686
- if (input === null) return def.optional === true || acceptsNull$1(def);
686
+ if (input === null) return def.optional === true || acceptsNull$2(def);
687
687
  const type = def.type;
688
688
  switch (type.kind) {
689
689
  case "": {
@@ -771,6 +771,338 @@ function collectLeaves(items, out) {
771
771
  return result === NO_MATCH ? input : result;
772
772
  }
773
773
 
774
+ //#endregion
775
+ //#region packages/typescript/src/runtime/json-schema-strict.ts
776
+ /** The keywords every provider takes: the shape of the schema, its notes and literals. */ const BASE_KEYWORDS = {
777
+ type: true,
778
+ properties: true,
779
+ required: true,
780
+ additionalProperties: true,
781
+ items: true,
782
+ anyOf: true,
783
+ $ref: true,
784
+ $defs: true,
785
+ enum: true,
786
+ const: true,
787
+ title: true,
788
+ description: true
789
+ };
790
+ /** The string formats both providers list. */ const FORMATS = new Set([
791
+ "date-time",
792
+ "time",
793
+ "date",
794
+ "duration",
795
+ "email",
796
+ "hostname",
797
+ "ipv4",
798
+ "ipv6",
799
+ "uuid"
800
+ ]);
801
+ /**
802
+ * OpenAI Structured Outputs / `strict: true` function calling: every property required
803
+ * (optional ones nullable), objects closed, an object root, no `allOf`; patterns without
804
+ * lookaround, backreferences or modifier groups, numeric bounds and `minItems` / `maxItems`
805
+ * kept; string lengths, `uniqueItems` and key counts dropped. Recursion is allowed.
806
+ */ const OPENAI_STRICT = {
807
+ name: "openai",
808
+ keywords: {
809
+ ...BASE_KEYWORDS,
810
+ pattern: (value) => decodablePattern(value),
811
+ format: (value) => FORMATS.has(value),
812
+ minimum: true,
813
+ maximum: true,
814
+ exclusiveMinimum: true,
815
+ exclusiveMaximum: true,
816
+ multipleOf: true,
817
+ minItems: true,
818
+ maxItems: true
819
+ },
820
+ requireAll: true,
821
+ collapseAllOf: true,
822
+ describeDropped: true,
823
+ allowRecursion: true,
824
+ objectRoot: true
825
+ };
826
+ /**
827
+ * Anthropic strict tool use / structured outputs: objects closed, an object root (a tool's
828
+ * `input_schema`), no recursion; simple patterns kept (no lookaround, backreferences, word
829
+ * boundaries or large `{n,m}`), `minItems` only `0` / `1`; numeric bounds, string lengths,
830
+ * `maxItems`, `uniqueItems` and key counts dropped. `allOf` is allowed
831
+ * except with a `$ref` (collapsed). Optional properties stay optional.
832
+ */ const ANTHROPIC_STRICT = {
833
+ name: "anthropic",
834
+ keywords: {
835
+ ...BASE_KEYWORDS,
836
+ allOf: true,
837
+ pattern: (value) => simplePattern(value),
838
+ format: (value) => FORMATS.has(value) || value === "uri",
839
+ minItems: (value) => value === 0 || value === 1
840
+ },
841
+ requireAll: false,
842
+ collapseAllOf: true,
843
+ describeDropped: true,
844
+ allowRecursion: false,
845
+ objectRoot: true
846
+ };
847
+ /** The largest `{n,m}` bound a simple pattern has (see {@link simplePattern}). */ const SIMPLE_BOUND = 100;
848
+ /**
849
+ * A pattern without lookaround, backreferences, word boundaries, Unicode property escapes,
850
+ * modifier groups or `{n,m}` bounds above {@link SIMPLE_BOUND} (Anthropic's simple patterns).
851
+ * Named groups are fine; `\b` in a class is a backspace.
852
+ */ function simplePattern(pattern) {
853
+ return scanPattern(pattern, true);
854
+ }
855
+ /** A pattern without lookaround, backreferences or modifier groups (OpenAI). */ function decodablePattern(pattern) {
856
+ return scanPattern(pattern, false);
857
+ }
858
+ /** {@link simplePattern} (`simple`), else {@link decodablePattern}. */ function scanPattern(pattern, simple) {
859
+ let inClass = false;
860
+ for (let i = 0; i < pattern.length; i++) {
861
+ const c = pattern[i];
862
+ if (c === "\\") {
863
+ const next = pattern[++i];
864
+ if (next === void 0 || /[1-9k]/.test(next)) return false;
865
+ if (simple && (/[pPB]/.test(next) || next === "b" && !inClass)) return false;
866
+ } else if (inClass) inClass = c !== "]";
867
+ else if (c === "[") inClass = true;
868
+ else if (c === "(" && pattern[i + 1] === "?") {
869
+ const kind = pattern[i + 2];
870
+ const named = kind === "<" && pattern[i + 3] !== "=" && pattern[i + 3] !== "!";
871
+ if (kind !== ":" && !named) return false;
872
+ } else if (simple && c === "{") {
873
+ const bounds = /^\{(\d+)(?:,(\d*))?\}/.exec(pattern.slice(i));
874
+ if (bounds && (Number(bounds[1]) > SIMPLE_BOUND || Number(bounds[2] || 0) > SIMPLE_BOUND)) return false;
875
+ }
876
+ }
877
+ return true;
878
+ }
879
+ /** The `$defs` name a `$ref` this builder writes points to. */ function refName(ref) {
880
+ return ref.slice(8);
881
+ }
882
+ /** The `$defs` names `schema` refers to (through any keyword but `$defs`). */ function refsOf(schema, out = /* @__PURE__ */ new Set()) {
883
+ if (Array.isArray(schema)) for (const item of schema) refsOf(item, out);
884
+ else if (schema && typeof schema === "object") {
885
+ for (const [key, value] of Object.entries(schema)) if (key === "$ref" && typeof value === "string") out.add(refName(value));
886
+ else if (key !== "$defs") refsOf(value, out);
887
+ }
888
+ return out;
889
+ }
890
+ /** The refs of each `$defs` entry, by name. */ function edgesOf(defs) {
891
+ return new Map(Object.entries(defs).map(([name, def]) => [name, refsOf(def)]));
892
+ }
893
+ /** The `$defs` names reachable from `from` through `edges`. */ function reachable(from, edges) {
894
+ const seen = /* @__PURE__ */ new Set();
895
+ const stack = [...from];
896
+ for (let name = stack.pop(); name !== void 0; name = stack.pop()) if (!seen.has(name)) {
897
+ seen.add(name);
898
+ stack.push(...edges.get(name) ?? []);
899
+ }
900
+ return seen;
901
+ }
902
+ /** The first `$defs` entry that refers to itself, through any others; `undefined`: none. */ function recursiveDef(defs) {
903
+ const edges = edgesOf(defs);
904
+ return [...edges.keys()].find((name) => reachable(edges.get(name), edges).has(name));
905
+ }
906
+ /** `n` `one`(s): `1 item`, `2 items`. */ function count(n, one, many = `${one}s`) {
907
+ return `${n} ${n === 1 ? one : many}`;
908
+ }
909
+ /** A dropped keyword in plain words (`pattern` `\S`: the `@meta.required` check). */ function describe(keyword, value) {
910
+ switch (keyword) {
911
+ case "minLength": return `At least ${count(value, "character")}.`;
912
+ case "maxLength": return `At most ${count(value, "character")}.`;
913
+ case "pattern": return value === "\\S" ? "Must not be blank." : `Must match the pattern ${JSON.stringify(value)}.`;
914
+ case "format": return `Format: ${value}.`;
915
+ case "minimum": return `Minimum ${value}.`;
916
+ case "maximum": return `Maximum ${value}.`;
917
+ case "exclusiveMinimum": return `Greater than ${value}.`;
918
+ case "exclusiveMaximum": return `Less than ${value}.`;
919
+ case "multipleOf": return `A multiple of ${value}.`;
920
+ case "minItems": return `At least ${count(value, "item")}.`;
921
+ case "maxItems": return `At most ${count(value, "item")}.`;
922
+ case "uniqueItems": return value ? "Items must be unique." : "";
923
+ case "minProperties": return `At least ${count(value, "property", "properties")}.`;
924
+ case "maxProperties": return `At most ${count(value, "property", "properties")}.`;
925
+ default: return `${keyword}: ${JSON.stringify(value)}.`;
926
+ }
927
+ }
928
+ /** A schema `type` of objects (`'object'`, or a type list with it: an optional object). */ function isObjectType(type) {
929
+ return type === "object" || Array.isArray(type) && type.includes("object");
930
+ }
931
+ /** Whether `schema` accepts `null` as it is (a `null` type, value or `anyOf` member). */ function acceptsNull$1(schema) {
932
+ if ("const" in schema) return schema.const === null;
933
+ if (Array.isArray(schema.enum)) return schema.enum.includes(null);
934
+ if (schema.type !== void 0) return schema.type === "null" || Array.isArray(schema.type) && schema.type.includes("null");
935
+ return Array.isArray(schema.anyOf) && schema.anyOf.some(acceptsNull$1);
936
+ }
937
+ /**
938
+ * `schema` also accepting `null`: `type: [t, 'null']` for a plain typed schema, else an `anyOf`
939
+ * with a `null` member (the title / description stay beside it).
940
+ */ function orNull(schema) {
941
+ if (acceptsNull$1(schema)) return schema;
942
+ if (schema.type !== void 0 && !("const" in schema) && schema.enum === void 0) return {
943
+ ...schema,
944
+ type: [schema.type, "null"].flat()
945
+ };
946
+ const { title, description, ...body } = schema;
947
+ const notes = {};
948
+ if (title !== void 0) notes.title = title;
949
+ if (description !== void 0) notes.description = description;
950
+ return {
951
+ anyOf: [...Object.keys(body).length === 1 && Array.isArray(body.anyOf) ? body.anyOf : [body], { type: "null" }],
952
+ ...notes
953
+ };
954
+ }
955
+ /**
956
+ * Object schema `out` with every property required (`requireAll`): those not in `required`
957
+ * (optional) made nullable.
958
+ */ function requireAll(out, required) {
959
+ const properties = out.properties ?? {};
960
+ const keys = Object.keys(properties);
961
+ const requiredKeys = new Set(required);
962
+ for (const key of keys) if (!requiredKeys.has(key)) properties[key] = orNull(properties[key]);
963
+ if (keys.length > 0) out.required = keys;
964
+ else delete out.required;
965
+ }
966
+ /** Whether `schema` carries the `@meta.required` check of a string (the pattern `\S`). */ function hasBlankCheck(schema) {
967
+ return schema.pattern === "\\S" || Array.isArray(schema.allOf) && schema.allOf.some((item) => item.pattern === "\\S");
968
+ }
969
+ /**
970
+ * `out` with the `dropped` keywords described in its `description` (`blank`: it has the
971
+ * `@meta.required` check, kept or described, which says what its `minLength: 1` would). A lone
972
+ * `$ref` takes no keywords beside it: it moves into an `anyOf` of its own.
973
+ */ function described(out, dropped, blank) {
974
+ const notes = dropped.filter(([key, value]) => !(blank && key === "minLength" && value === 1)).map(([key, value]) => describe(key, value)).filter(Boolean).join(" ");
975
+ if (!notes) return out;
976
+ let schema = out;
977
+ if (schema.$ref !== void 0) {
978
+ const { $ref, ...rest } = schema;
979
+ schema = {
980
+ anyOf: [{ $ref }],
981
+ ...rest
982
+ };
983
+ }
984
+ schema.description = schema.description ? `${schema.description}\n\n${notes}` : notes;
985
+ return schema;
986
+ }
987
+ /**
988
+ * `schema` (built closed by {@link buildJsonSchema}) rewritten to `profile` (see
989
+ * {@link TStrictProfile}). Throws for a shape the profile can't take.
990
+ */ function strictSchema(schema, profile) {
991
+ const fail = (what) => {
992
+ throw new Error(`buildJsonSchema (strict: ${profile.name}): ${what}`);
993
+ };
994
+ const defs = schema.$defs ?? {};
995
+ if (!profile.allowRecursion) {
996
+ const recursive = recursiveDef(defs);
997
+ if (recursive !== void 0) fail(`recursive type "${recursive}" is not supported`);
998
+ }
999
+ if (profile.objectRoot && schema.type !== "object") fail("the root must be an object type");
1000
+ const allowed = (keyword, value) => {
1001
+ const rule = profile.keywords[keyword];
1002
+ return rule === true || rule !== void 0 && rule(value);
1003
+ };
1004
+ /** `$defs` entries being inlined (a use of an entry inside itself stays a reference). */ const inlining = /* @__PURE__ */ new Set();
1005
+ /**
1006
+ * `s` rewritten; the constraints it drops are described on it. `part`: a subschema of an
1007
+ * `allOf` (a constraint of the schema it sits in, no type of its own).
1008
+ */ const rewrite = (s, at, part = false) => {
1009
+ /** The dropped keywords and their values (described at the end). */ const dropped = [];
1010
+ /** The `$defs` entries inlined here (see `collapse`). */ const entered = [];
1011
+ let source = profile.collapseAllOf ? collapse(s, dropped, entered) : s;
1012
+ if (source.oneOf && !profile.keywords.oneOf) {
1013
+ const { oneOf, discriminator: _, ...rest } = source;
1014
+ source = {
1015
+ ...rest,
1016
+ anyOf: oneOf
1017
+ };
1018
+ }
1019
+ const where = at || "the root";
1020
+ if (Array.isArray(source.items)) fail(`a tuple (at ${where}) has no strict schema`);
1021
+ if (source.patternProperties !== void 0) fail(`a record (at ${where}) has no strict schema; use an array of key/value objects`);
1022
+ if (!part && source.type === void 0 && source.anyOf === void 0 && source.allOf === void 0 && source.$ref === void 0 && source.not === void 0 && !("const" in source) && source.enum === void 0) fail(`a value of any type (at ${where}) has no strict schema`);
1023
+ const out = {};
1024
+ for (const [key, value] of Object.entries(source)) {
1025
+ if (key === "discriminator" && !profile.keywords.discriminator) continue;
1026
+ if (!allowed(key, value)) {
1027
+ if (key === "allOf" || key === "not") fail(`${key === "allOf" ? "an intersection" : "an impossible type"} (at ${where}) has no strict schema`);
1028
+ dropped.push([key, value]);
1029
+ continue;
1030
+ }
1031
+ out[key] = rewriteValue(key, value, at);
1032
+ }
1033
+ for (const name of entered) inlining.delete(name);
1034
+ if (isObjectType(out.type)) {
1035
+ out.additionalProperties = false;
1036
+ if (profile.requireAll) requireAll(out, source.required);
1037
+ }
1038
+ return profile.describeDropped && dropped.length > 0 ? described(out, dropped, hasBlankCheck(s) || hasBlankCheck(source)) : out;
1039
+ };
1040
+ /** The value of keyword `key` rewritten (its subschemas). */ const rewriteValue = (key, value, at) => {
1041
+ switch (key) {
1042
+ case "properties": return Object.fromEntries(Object.entries(value).map(([name, p]) => [name, rewrite(p, at ? `${at}.${name}` : name)]));
1043
+ case "items": return rewrite(value, `${at}[]`);
1044
+ case "anyOf": return value.map((item) => rewrite(item, at));
1045
+ case "allOf": return value.map((item) => rewrite(item, at, true));
1046
+ case "$defs": return Object.fromEntries(Object.entries(value).map(([name, d]) => {
1047
+ inlining.add(name);
1048
+ const entry = rewrite(d, `$defs.${name}`);
1049
+ inlining.delete(name);
1050
+ return [name, entry];
1051
+ }));
1052
+ default: return value;
1053
+ }
1054
+ };
1055
+ /**
1056
+ * `s` with its `allOf` collapsed (see `collapseAllOf`): what it drops in `dropped`, the
1057
+ * `$defs` entries it inlines in `entered` (and `inlining`, until `s` is rewritten).
1058
+ */ const collapse = (s, dropped, entered) => {
1059
+ if (!Array.isArray(s.allOf)) return s;
1060
+ const { allOf, ...rest } = s;
1061
+ const ref = allOf.length === 1 && Object.keys(allOf[0]).length === 1 ? allOf[0].$ref : void 0;
1062
+ if (typeof ref === "string") {
1063
+ const name = refName(ref);
1064
+ const target = defs[name];
1065
+ if (target === void 0 || inlining.has(name)) return {
1066
+ anyOf: [{ $ref: ref }],
1067
+ ...rest
1068
+ };
1069
+ inlining.add(name);
1070
+ entered.push(name);
1071
+ return collapse({
1072
+ ...target,
1073
+ ...rest
1074
+ }, dropped, entered);
1075
+ }
1076
+ if (!allOf.every((item) => Object.keys(item).length === 1 && "pattern" in item)) return s;
1077
+ if (profile.keywords.allOf) {
1078
+ const kept = allOf.filter((item) => {
1079
+ if (allowed("pattern", item.pattern)) return true;
1080
+ dropped.push(["pattern", item.pattern]);
1081
+ return false;
1082
+ });
1083
+ if (kept.length > 1 || kept.length === 1 && rest.pattern !== void 0) return {
1084
+ ...rest,
1085
+ allOf: kept
1086
+ };
1087
+ return kept.length === 1 ? {
1088
+ ...rest,
1089
+ pattern: kept[0].pattern
1090
+ } : rest;
1091
+ }
1092
+ const out = { ...rest };
1093
+ for (const { pattern } of allOf) if (out.pattern === void 0 && allowed("pattern", pattern)) out.pattern = pattern;
1094
+ else dropped.push(["pattern", pattern]);
1095
+ return out;
1096
+ };
1097
+ const out = rewrite(schema, "");
1098
+ if (out.$defs) {
1099
+ const used = reachable(refsOf(out), edgesOf(out.$defs));
1100
+ for (const name of Object.keys(out.$defs)) if (!used.has(name)) delete out.$defs[name];
1101
+ if (Object.keys(out.$defs).length === 0) delete out.$defs;
1102
+ }
1103
+ return out;
1104
+ }
1105
+
774
1106
  //#endregion
775
1107
  //#region packages/typescript/src/runtime/traverse.ts
776
1108
  /**
@@ -839,6 +1171,11 @@ function collectLeaves(items, out) {
839
1171
  * @param opts - {@link TJsonSchemaOptions}.
840
1172
  * @returns A JSON Schema object.
841
1173
  */ function buildJsonSchema(type, opts) {
1174
+ if (opts?.strict) return strictSchema(buildJsonSchema(type, {
1175
+ ...opts,
1176
+ strict: void 0,
1177
+ closed: true
1178
+ }), opts.strict);
842
1179
  const closed = opts?.closed === true;
843
1180
  const annotations = opts?.annotations !== false;
844
1181
  const enums = opts?.enums !== false;
@@ -1688,6 +2025,91 @@ const DEF_REF = /^#\/\$defs\/(.+)$/;
1688
2025
  return out;
1689
2026
  }
1690
2027
 
2028
+ //#endregion
2029
+ //#region packages/typescript/src/runtime/drop-optional-nulls.ts
2030
+ /**
2031
+ * What `value` looks like without the `null` values the model sends for fields it leaves out under
2032
+ * a `requireAll` profile (`OPENAI_STRICT`), before it goes to the validator. The validator
2033
+ * takes a missing optional field, but not `null` on an optional `@meta.required` one.
2034
+ *
2035
+ * A `null` is dropped only from an optional field whose type does not accept `null`: for
2036
+ * `x?: string | null` it stays (`null` and a missing field mean different things, e.g. "clear"
2037
+ * and "keep" in a patch). In a union, the branch its discriminator picks applies; else every
2038
+ * branch does, and a key is dropped only when every branch (and, in an intersection, every part)
2039
+ * that declares it has it optional and not accepting `null`: one that needs the `null` keeps it.
2040
+ *
2041
+ * Copy-on-change: `value` is never mutated (a frozen one works); the same reference comes back
2042
+ * when nothing is dropped, else a copy with the changed objects and arrays rebuilt.
2043
+ */ function dropOptionalNulls(type, value) {
2044
+ return dropNulls([type], value);
2045
+ }
2046
+ /** The discriminator of a union, found once per union type. */ const discriminators = /* @__PURE__ */ new WeakMap();
2047
+ function discriminatorOf(union) {
2048
+ let disc = discriminators.get(union);
2049
+ if (disc === void 0) {
2050
+ disc = detectDiscriminator(union.items);
2051
+ discriminators.set(union, disc);
2052
+ }
2053
+ return disc;
2054
+ }
2055
+ /**
2056
+ * The defs `value` is checked against, unions and intersections expanded: the branch a
2057
+ * discriminator picks, else every branch.
2058
+ */ function expand(defs, value, out) {
2059
+ for (const def of defs) {
2060
+ const type = def.type;
2061
+ if (type.kind === "union" || type.kind === "intersection") {
2062
+ const union = type;
2063
+ const isObject = value !== null && typeof value === "object" && !Array.isArray(value);
2064
+ const disc = type.kind === "union" && isObject ? discriminatorOf(union) : null;
2065
+ const picked = disc ? disc.indexMapping[String(value[disc.propertyName])] : void 0;
2066
+ expand(picked === void 0 ? union.items : [union.items[picked]], value, out);
2067
+ } else out.push(def);
2068
+ }
2069
+ }
2070
+ /** {@link dropOptionalNulls} of `value` as every one of `defs` (alternatives or parts). */ function dropNulls(defs, value) {
2071
+ if (value === null || typeof value !== "object") return value;
2072
+ const leaves = [];
2073
+ expand(defs, value, leaves);
2074
+ if (Array.isArray(value)) return dropNullsOfArray(leaves, value);
2075
+ let out;
2076
+ for (const key of Object.keys(value)) {
2077
+ const current = value[key];
2078
+ if (current !== null && typeof current !== "object") continue;
2079
+ const declared = [];
2080
+ for (const leaf of leaves) {
2081
+ const prop = leaf.type.kind === "object" ? leaf.type.props.get(key) : void 0;
2082
+ if (prop !== void 0 && !isPhantomType(prop)) declared.push(prop);
2083
+ }
2084
+ if (declared.length === 0) continue;
2085
+ if (current === null) {
2086
+ if (declared.every((prop) => prop.optional && !acceptsNull$2(prop))) {
2087
+ out ?? (out = { ...value });
2088
+ delete out[key];
2089
+ }
2090
+ continue;
2091
+ }
2092
+ const next = dropNulls(declared, current);
2093
+ if (next !== current) {
2094
+ out ?? (out = { ...value });
2095
+ out[key] = next;
2096
+ }
2097
+ }
2098
+ return out ?? value;
2099
+ }
2100
+ /** {@link dropNulls} of an array `value`: the items of every array and tuple among `leaves`. */ function dropNullsOfArray(leaves, value) {
2101
+ return mapList(value, (item, i) => {
2102
+ if (item === null || typeof item !== "object") return item;
2103
+ const declared = [];
2104
+ for (const leaf of leaves) {
2105
+ const type = leaf.type;
2106
+ if (type.kind === "array") declared.push(type.of);
2107
+ else if (type.kind === "tuple" && i < type.items.length) declared.push(type.items[i]);
2108
+ }
2109
+ return dropNulls(declared, item);
2110
+ });
2111
+ }
2112
+
1691
2113
  //#endregion
1692
2114
  //#region packages/typescript/src/runtime/default-value.ts
1693
2115
  /**
@@ -2635,6 +3057,26 @@ function* deserializeTypeDef(t, resolved) {
2635
3057
  texts
2636
3058
  };
2637
3059
  }
3060
+ /**
3061
+ * Translates the value of one metadata key (live, as a compiled type holds it — not serialized)
3062
+ * with `t`, by the rules {@link translateServed} applies to serialized metadata, so a client
3063
+ * translating compiled types reads one catalogue with the server: a text key's string (each item
3064
+ * of a `multiple` list; the named fields of a value object, e.g. `message` of `meta.required`) is
3065
+ * replaced by `t(text)` — except a primitive's built-in format message, which is reported by its
3066
+ * code. Returns `value` itself when the key holds no user text or nothing is translated; it is
3067
+ * never changed.
3068
+ *
3069
+ * Expressions are left as they are: their string literals are translated in a served type's
3070
+ * `texts`, and a client translates what an expression returns (by exact match), not its source.
3071
+ *
3072
+ * @example
3073
+ * ```ts
3074
+ * const label = translateUserText('meta.label', 'Street', text => dict[text]) // dict['Street']
3075
+ * ```
3076
+ */ function translateUserText(key, value, t) {
3077
+ const mode = userTextOf(key);
3078
+ return mode === void 0 ? value : walk(value, mode, { t });
3079
+ }
2638
3080
  /** `value` translated as `mode` says; the `metadata` objects within it translated too. */ function walk(value, mode, ctx) {
2639
3081
  if (Array.isArray(value)) return mapList(value, (item) => walk(item, mode === "metadata" ? void 0 : mode, ctx));
2640
3082
  if (typeof value === "string") {
@@ -2643,6 +3085,7 @@ function* deserializeTypeDef(t, resolved) {
2643
3085
  return value;
2644
3086
  }
2645
3087
  if (typeof value !== "object" || value === null) return value;
3088
+ if (ctx.texts === void 0 && typeof mode !== "object") return value;
2646
3089
  return mapEntries(value, (key, item) => walk(item, modeOf(key, mode), ctx));
2647
3090
  }
2648
3091
  /**
@@ -2657,10 +3100,12 @@ function* deserializeTypeDef(t, resolved) {
2657
3100
  const out = ctx.t(text);
2658
3101
  return typeof out === "string" ? out : void 0;
2659
3102
  }
2660
- /** Adds the translated string literals of expression `source` to `ctx.texts`. */ function collectLiterals(source, ctx) {
2661
- for (const literal of stringLiterals(source)) if (!Object.hasOwn(ctx.texts, literal)) {
3103
+ /** Adds the translated string literals of expression `source` to `ctx.texts` (a served type only). */ function collectLiterals(source, ctx) {
3104
+ const { texts } = ctx;
3105
+ if (!texts) return;
3106
+ for (const literal of stringLiterals(source)) if (!Object.hasOwn(texts, literal)) {
2662
3107
  const translated = translate(literal, ctx);
2663
- if (translated !== void 0 && translated !== literal) ctx.texts[literal] = translated;
3108
+ if (translated !== void 0 && translated !== literal) texts[literal] = translated;
2664
3109
  }
2665
3110
  }
2666
3111
  /** Single-character escapes and what they stand for (a line continuation stands for nothing). */ const ESCAPES = {
@@ -2816,4 +3261,4 @@ let LiteralScanner = class LiteralScanner {
2816
3261
  }
2817
3262
 
2818
3263
  //#endregion
2819
- export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, LayerMap, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, typeHasNormalizers, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
3264
+ export { $ak, $alias, $blk, $end, $f, $fc, $ft, $nr, $ps, $q, $sh, $ut, ANTHROPIC_STRICT, LayerMap, OPENAI_STRICT, SERIALIZE_VERSION, VALIDATOR_ERROR_CODES, VALIDATOR_MESSAGES, Validator, ValidatorError, annotate, appliedBlockModules, buildJsonSchema, bundledSchemaOf, coerceForType, coerceScalar, createAnnotatedTypeNode, createDataFromAnnotatedType, defineAnnotatedType, deserializeAnnotatedType, detectDiscriminator, dropOptionalNulls, flattenAnnotatedType, forAnnotatedType, formatValidatorMessage, fromJsonSchema, invalidateCompiledValidators, isAnnotatedType, isAnnotatedTypeOfPrimitive, isPhantomType, lazyJsonSchema, localizeErrors, mergeJsonSchemas, messagesTranslator, metaEmpty, normalizeForType, pendingStatements, registerCompiledCheck, registerUserText, serializeAnnotatedType, throwFeatureDisabled, translateServed, translateUserText, typeHasNormalizers, unionDiscriminator, userTextKeys, userTextOf, watchLayer };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/typescript",
3
- "version": "0.2.9",
3
+ "version": "0.2.10",
4
4
  "description": "Atscript: typescript-gen support.",
5
5
  "keywords": [
6
6
  "annotations",
@@ -63,18 +63,18 @@
63
63
  "./package.json": "./package.json"
64
64
  },
65
65
  "dependencies": {
66
- "@moostjs/event-cli": "^0.7.4",
67
- "moost": "^0.7.4"
66
+ "@moostjs/event-cli": "^0.7.5",
67
+ "moost": "^0.7.5"
68
68
  },
69
69
  "devDependencies": {
70
- "@atscript/db": "^0.1.172",
71
- "@uniqu/core": "^0.2.1",
70
+ "@atscript/db": "^0.1.174",
71
+ "@uniqu/core": "^0.2.2",
72
72
  "ajv": "8.20.0",
73
73
  "vitest": "4.1.12"
74
74
  },
75
75
  "peerDependencies": {
76
76
  "@atscript/db": "^0.1.159",
77
- "@atscript/core": "^0.2.9"
77
+ "@atscript/core": "^0.2.10"
78
78
  },
79
79
  "peerDependenciesMeta": {
80
80
  "@atscript/db": {