quicktype-core 23.0.141 → 23.0.143

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/index.d.ts CHANGED
@@ -49,3 +49,4 @@ export { RubyTargetLanguage, RubyRenderer, rubyOptions } from "./language/ruby";
49
49
  export { CrystalTargetLanguage, CrystalRenderer } from "./language/Crystal";
50
50
  export { HaskellTargetLanguage, HaskellRenderer, haskellOptions } from "./language/Haskell";
51
51
  export { DartTargetLanguage, DartRenderer, dartOptions } from "./language/Dart";
52
+ export { ElixirTargetLanguage, ElixirRenderer, elixirOptions } from "./language/Elixir";
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ClassType = exports.ArrayType = exports.PrimitiveType = exports.Type = exports.messageAssert = exports.messageError = exports.QuickTypeError = exports.trainMarkovChain = exports.isLetterOrDigit = exports.legalizeCharacters = exports.allUpperWordStyle = exports.firstUpperWordStyle = exports.combineWords = exports.capitalize = exports.splitIntoWords = exports.inflateBase64 = exports.checkArray = exports.checkStringMap = exports.parseJSON = exports.assertNever = exports.defined = exports.assert = exports.panic = exports.IssueAnnotationData = exports.Namer = exports.funPrefixNamer = exports.Name = exports.parenIfNeeded = exports.singleWord = exports.modifySource = exports.languageNamed = exports.defaultTargetLanguages = exports.TargetLanguage = exports.getOptionValues = exports.Option = exports.Ref = exports.JSONSchemaInput = exports.jsonInputForTargetLanguage = exports.JSONInput = exports.InputData = exports.CompressedJSON = exports.inferenceFlagsObject = exports.defaultInferenceFlags = exports.inferenceFlagNames = exports.inferenceFlags = exports.combineRenderResults = exports.quicktype = exports.quicktypeMultiFileSync = exports.quicktypeMultiFile = exports.getTargetLanguage = void 0;
4
4
  exports.JavaScriptPropTypesRenderer = exports.JavaScriptPropTypesTargetLanguage = exports.javaScriptOptions = exports.JavaScriptRenderer = exports.JavaScriptTargetLanguage = exports.javaOptions = exports.JavaRenderer = exports.JavaTargetLanguage = exports.objcOptions = exports.ObjectiveCRenderer = exports.ObjectiveCTargetLanguage = exports.goOptions = exports.GoRenderer = exports.GoTargetLanguage = exports.pythonOptions = exports.PythonRenderer = exports.PythonTargetLanguage = exports.CSharpRenderer = exports.cSharpOptions = exports.CSharpTargetLanguage = exports.cPlusPlusOptions = exports.CPlusPlusRenderer = exports.CPlusPlusTargetLanguage = exports.cJSONOptions = exports.CJSONRenderer = exports.CJSONTargetLanguage = exports.uriTypeAttributeKind = exports.ConvenienceRenderer = exports.nullableFromUnion = exports.matchType = exports.removeNullFromUnion = exports.StringTypes = exports.namesTypeAttributeKind = exports.makeNamesTypeAttributes = exports.TypeNames = exports.emptyTypeAttributes = exports.TypeAttributeKind = exports.derefTypeRef = exports.TypeBuilder = exports.sourcesFromPostmanCollection = exports.JSONSchemaStore = exports.FetchingJSONSchemaStore = exports.readFromFileOrURL = exports.readableFromFileOrURL = exports.getStream = exports.ObjectType = exports.UnionType = exports.MapType = exports.EnumType = exports.ClassProperty = void 0;
5
- exports.dartOptions = exports.DartRenderer = exports.DartTargetLanguage = exports.haskellOptions = exports.HaskellRenderer = exports.HaskellTargetLanguage = exports.CrystalRenderer = exports.CrystalTargetLanguage = exports.rubyOptions = exports.RubyRenderer = exports.RubyTargetLanguage = exports.rustOptions = exports.RustRenderer = exports.RustTargetLanguage = exports.JSONSchemaRenderer = exports.JSONSchemaTargetLanguage = exports.elmOptions = exports.ElmRenderer = exports.ElmTargetLanguage = exports.SmithyOptions = exports.Smithy4sRenderer = exports.SmithyTargetLanguage = exports.scala3Options = exports.Scala3Renderer = exports.Scala3TargetLanguage = exports.kotlinOptions = exports.KotlinRenderer = exports.KotlinTargetLanguage = exports.swiftOptions = exports.SwiftRenderer = exports.SwiftTargetLanguage = exports.tsFlowOptions = exports.FlowRenderer = exports.FlowTargetLanguage = exports.TypeScriptRenderer = exports.TypeScriptTargetLanguage = exports.javaScriptPropTypesOptions = void 0;
5
+ exports.elixirOptions = exports.ElixirRenderer = exports.ElixirTargetLanguage = exports.dartOptions = exports.DartRenderer = exports.DartTargetLanguage = exports.haskellOptions = exports.HaskellRenderer = exports.HaskellTargetLanguage = exports.CrystalRenderer = exports.CrystalTargetLanguage = exports.rubyOptions = exports.RubyRenderer = exports.RubyTargetLanguage = exports.rustOptions = exports.RustRenderer = exports.RustTargetLanguage = exports.JSONSchemaRenderer = exports.JSONSchemaTargetLanguage = exports.elmOptions = exports.ElmRenderer = exports.ElmTargetLanguage = exports.SmithyOptions = exports.Smithy4sRenderer = exports.SmithyTargetLanguage = exports.scala3Options = exports.Scala3Renderer = exports.Scala3TargetLanguage = exports.kotlinOptions = exports.KotlinRenderer = exports.KotlinTargetLanguage = exports.swiftOptions = exports.SwiftRenderer = exports.SwiftTargetLanguage = exports.tsFlowOptions = exports.FlowRenderer = exports.FlowTargetLanguage = exports.TypeScriptRenderer = exports.TypeScriptTargetLanguage = exports.javaScriptPropTypesOptions = void 0;
6
6
  var Run_1 = require("./Run");
7
7
  Object.defineProperty(exports, "getTargetLanguage", { enumerable: true, get: function () { return Run_1.getTargetLanguage; } });
8
8
  Object.defineProperty(exports, "quicktypeMultiFile", { enumerable: true, get: function () { return Run_1.quicktypeMultiFile; } });
@@ -190,3 +190,7 @@ var Dart_1 = require("./language/Dart");
190
190
  Object.defineProperty(exports, "DartTargetLanguage", { enumerable: true, get: function () { return Dart_1.DartTargetLanguage; } });
191
191
  Object.defineProperty(exports, "DartRenderer", { enumerable: true, get: function () { return Dart_1.DartRenderer; } });
192
192
  Object.defineProperty(exports, "dartOptions", { enumerable: true, get: function () { return Dart_1.dartOptions; } });
193
+ var Elixir_1 = require("./language/Elixir");
194
+ Object.defineProperty(exports, "ElixirTargetLanguage", { enumerable: true, get: function () { return Elixir_1.ElixirTargetLanguage; } });
195
+ Object.defineProperty(exports, "ElixirRenderer", { enumerable: true, get: function () { return Elixir_1.ElixirRenderer; } });
196
+ Object.defineProperty(exports, "elixirOptions", { enumerable: true, get: function () { return Elixir_1.elixirOptions; } });
@@ -27,6 +27,7 @@ const Haskell_1 = require("./Haskell");
27
27
  const TypeScriptZod_1 = require("./TypeScriptZod");
28
28
  const Php_1 = require("./Php");
29
29
  const TypeScriptEffectSchema_1 = require("./TypeScriptEffectSchema");
30
+ const Elixir_1 = require("./Elixir");
30
31
  exports.all = [
31
32
  new CSharp_1.CSharpTargetLanguage(),
32
33
  new Golang_1.GoTargetLanguage(),
@@ -53,6 +54,7 @@ exports.all = [
53
54
  new Haskell_1.HaskellTargetLanguage(),
54
55
  new TypeScriptZod_1.TypeScriptZodTargetLanguage(),
55
56
  new TypeScriptEffectSchema_1.TypeScriptEffectSchemaTargetLanguage(),
57
+ new Elixir_1.ElixirTargetLanguage(),
56
58
  new Php_1.PhpTargetLanguage()
57
59
  ];
58
60
  function languageNamed(name, targetLanguages) {
@@ -0,0 +1,50 @@
1
+ import { Sourcelike } from "../Source";
2
+ import { Namer, Name } from "../Naming";
3
+ import { ConvenienceRenderer, ForbiddenWordsInfo } from "../ConvenienceRenderer";
4
+ import { TargetLanguage } from "../TargetLanguage";
5
+ import { Option, BooleanOption, OptionValues, StringOption } from "../RendererOptions";
6
+ import { Type, ClassType } from "../Type";
7
+ import { RenderContext } from "../Renderer";
8
+ export declare const elixirOptions: {
9
+ justTypes: BooleanOption;
10
+ namespace: StringOption;
11
+ };
12
+ export declare class ElixirTargetLanguage extends TargetLanguage {
13
+ constructor();
14
+ protected getOptions(): Option<any>[];
15
+ get supportsOptionalClassProperties(): boolean;
16
+ protected get defaultIndentation(): string;
17
+ protected makeRenderer(renderContext: RenderContext, untypedOptionValues: {
18
+ [name: string]: any;
19
+ }): ElixirRenderer;
20
+ }
21
+ export declare class ElixirRenderer extends ConvenienceRenderer {
22
+ private readonly _options;
23
+ constructor(targetLanguage: TargetLanguage, renderContext: RenderContext, _options: OptionValues<typeof elixirOptions>);
24
+ protected get commentLineStart(): string;
25
+ protected get needsTypeDeclarationBeforeUse(): boolean;
26
+ protected canBeForwardDeclared(t: Type): boolean;
27
+ protected forbiddenNamesForGlobalNamespace(): string[];
28
+ protected forbiddenForObjectProperties(_c: ClassType, _classNamed: Name): ForbiddenWordsInfo;
29
+ protected makeNamedTypeNamer(): Namer;
30
+ protected namerForObjectProperty(): Namer;
31
+ protected makeUnionMemberNamer(): Namer;
32
+ protected makeEnumCaseNamer(): Namer;
33
+ private nameForNamedTypeWithNamespace;
34
+ private nameWithNamespace;
35
+ private elixirType;
36
+ private patternMatchClauseDecode;
37
+ private patternMatchClauseEncode;
38
+ private sortAndFilterPatternMatchTypes;
39
+ private emitPatternMatches;
40
+ private nameOfTransformFunction;
41
+ private fromDynamic;
42
+ private toDynamic;
43
+ private emitBlock;
44
+ protected emitDescriptionBlock(lines: Sourcelike[]): void;
45
+ private emitModule;
46
+ private isValidAtom;
47
+ private emitEnum;
48
+ private emitUnion;
49
+ protected emitSourceStructure(): void;
50
+ }
@@ -0,0 +1,868 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ElixirRenderer = exports.ElixirTargetLanguage = exports.elixirOptions = void 0;
7
+ const unicode_properties_1 = __importDefault(require("unicode-properties"));
8
+ const Naming_1 = require("../Naming");
9
+ const ConvenienceRenderer_1 = require("../ConvenienceRenderer");
10
+ const TargetLanguage_1 = require("../TargetLanguage");
11
+ const RendererOptions_1 = require("../RendererOptions");
12
+ const Type_1 = require("../Type");
13
+ const TypeUtils_1 = require("../TypeUtils");
14
+ const Strings_1 = require("../support/Strings");
15
+ const forbiddenModuleNames = [
16
+ "Access",
17
+ "Agent",
18
+ "Any",
19
+ "Application",
20
+ "ArgumentError",
21
+ "ArithmeticError",
22
+ "Atom",
23
+ "BadArityError",
24
+ "BadBooleanError",
25
+ "BadFunctionError",
26
+ "BadMapError",
27
+ "BadStructError",
28
+ "Base",
29
+ "Behaviour",
30
+ "Bitwise",
31
+ "Calendar",
32
+ "CaseClauseError",
33
+ "Code",
34
+ "Collectable",
35
+ "CondClauseError",
36
+ "Config",
37
+ "Date",
38
+ "DateTime",
39
+ "Dict",
40
+ "DynamicSupervisor",
41
+ "Enum",
42
+ "ErlangError",
43
+ "Exception",
44
+ "File",
45
+ "Float",
46
+ "Function",
47
+ "FunctionClauseError",
48
+ "GenEvent",
49
+ "GenServer",
50
+ "HashDict",
51
+ "HashSet",
52
+ "IO",
53
+ "Inspect",
54
+ "Integer",
55
+ "Kernel",
56
+ "KeyError",
57
+ "Keyword",
58
+ "List",
59
+ "Macro",
60
+ "Map",
61
+ "MapSet",
62
+ "MatchError",
63
+ "Module",
64
+ "Node",
65
+ "OptionParser",
66
+ "Path",
67
+ "Port",
68
+ "Process",
69
+ "Protocol",
70
+ "Range",
71
+ "Record",
72
+ "Regex",
73
+ "Registry",
74
+ "RuntimeError",
75
+ "Set",
76
+ "Stream",
77
+ "String",
78
+ "StringIO",
79
+ "Supervisor",
80
+ "SyntaxError",
81
+ "System",
82
+ "SystemLimitError",
83
+ "Task",
84
+ "Time",
85
+ "TokenMissingError",
86
+ "Tuple",
87
+ "URI",
88
+ "UndefinedFunctionError",
89
+ "UnicodeConversionError",
90
+ "Version",
91
+ "WithClauseError"
92
+ ];
93
+ const reservedWords = [
94
+ "def",
95
+ "defmodule",
96
+ "use",
97
+ "import",
98
+ "alias",
99
+ "true",
100
+ "false",
101
+ "nil",
102
+ "when",
103
+ "and",
104
+ "or",
105
+ "not",
106
+ "in",
107
+ "fn",
108
+ "do",
109
+ "end",
110
+ "catch",
111
+ "rescue",
112
+ "after",
113
+ "else"
114
+ ];
115
+ function unicodeEscape(codePoint) {
116
+ return `\\u{${(0, Strings_1.intToHex)(codePoint, 0)}}`;
117
+ }
118
+ function capitalizeFirstLetter(str) {
119
+ return str.charAt(0).toUpperCase() + str.slice(1);
120
+ }
121
+ const stringEscape = (0, Strings_1.utf32ConcatMap)((0, Strings_1.escapeNonPrintableMapper)(Strings_1.isPrintable, unicodeEscape));
122
+ function escapeDoubleQuotes(str) {
123
+ return str.replace(/"/g, '\\"');
124
+ }
125
+ function escapeNewLines(str) {
126
+ return str.replace(/\n/g, "\\n");
127
+ }
128
+ exports.elixirOptions = {
129
+ justTypes: new RendererOptions_1.BooleanOption("just-types", "Plain types only", false),
130
+ namespace: new RendererOptions_1.StringOption("namespace", "Specify a module namespace", "NAME", "")
131
+ };
132
+ class ElixirTargetLanguage extends TargetLanguage_1.TargetLanguage {
133
+ constructor() {
134
+ super("Elixir", ["elixir"], "ex");
135
+ }
136
+ getOptions() {
137
+ return [exports.elixirOptions.justTypes, exports.elixirOptions.namespace];
138
+ }
139
+ get supportsOptionalClassProperties() {
140
+ return true;
141
+ }
142
+ get defaultIndentation() {
143
+ return " ";
144
+ }
145
+ makeRenderer(renderContext, untypedOptionValues) {
146
+ return new ElixirRenderer(this, renderContext, (0, RendererOptions_1.getOptionValues)(exports.elixirOptions, untypedOptionValues));
147
+ }
148
+ }
149
+ exports.ElixirTargetLanguage = ElixirTargetLanguage;
150
+ const isStartCharacter = Strings_1.isLetterOrUnderscore;
151
+ function isPartCharacter(utf16Unit) {
152
+ const category = unicode_properties_1.default.getCategory(utf16Unit);
153
+ return ["Nd", "Pc", "Mn", "Mc"].indexOf(category) >= 0 || isStartCharacter(utf16Unit);
154
+ }
155
+ const legalizeName = (0, Strings_1.legalizeCharacters)(isPartCharacter);
156
+ function simpleNameStyle(original, uppercase) {
157
+ if (/^[0-9]+$/.test(original)) {
158
+ original = `${original}N`;
159
+ }
160
+ const words = (0, Strings_1.splitIntoWords)(original);
161
+ return (0, Strings_1.combineWords)(words, legalizeName, uppercase ? Strings_1.firstUpperWordStyle : Strings_1.allLowerWordStyle, uppercase ? Strings_1.firstUpperWordStyle : Strings_1.allLowerWordStyle, Strings_1.allUpperWordStyle, Strings_1.allUpperWordStyle, "", isStartCharacter);
162
+ }
163
+ function memberNameStyle(original) {
164
+ const words = (0, Strings_1.splitIntoWords)(original);
165
+ return (0, Strings_1.combineWords)(words, legalizeName, Strings_1.allLowerWordStyle, Strings_1.allLowerWordStyle, Strings_1.allLowerWordStyle, Strings_1.allLowerWordStyle, "_", isStartCharacter);
166
+ }
167
+ class ElixirRenderer extends ConvenienceRenderer_1.ConvenienceRenderer {
168
+ constructor(targetLanguage, renderContext, _options) {
169
+ super(targetLanguage, renderContext);
170
+ this._options = _options;
171
+ }
172
+ get commentLineStart() {
173
+ return "# ";
174
+ }
175
+ get needsTypeDeclarationBeforeUse() {
176
+ return true;
177
+ }
178
+ canBeForwardDeclared(t) {
179
+ return "class" === t.kind;
180
+ }
181
+ forbiddenNamesForGlobalNamespace() {
182
+ return [...forbiddenModuleNames, ...reservedWords.map(word => capitalizeFirstLetter(word))];
183
+ }
184
+ forbiddenForObjectProperties(_c, _classNamed) {
185
+ return { names: reservedWords, includeGlobalForbidden: true };
186
+ }
187
+ makeNamedTypeNamer() {
188
+ return new Naming_1.Namer("types", n => simpleNameStyle(n, true), []);
189
+ }
190
+ namerForObjectProperty() {
191
+ return new Naming_1.Namer("properties", memberNameStyle, []);
192
+ }
193
+ makeUnionMemberNamer() {
194
+ return new Naming_1.Namer("properties", memberNameStyle, []);
195
+ }
196
+ makeEnumCaseNamer() {
197
+ return new Naming_1.Namer("enum-cases", n => simpleNameStyle(n, true), []);
198
+ }
199
+ nameForNamedTypeWithNamespace(t) {
200
+ if (this._options.namespace) {
201
+ return [this._options.namespace, ".", this.nameForNamedType(t)];
202
+ }
203
+ else {
204
+ return [this.nameForNamedType(t)];
205
+ }
206
+ }
207
+ nameWithNamespace(n) {
208
+ if (this._options.namespace) {
209
+ return [this._options.namespace, ".", n];
210
+ }
211
+ else {
212
+ return [n];
213
+ }
214
+ }
215
+ elixirType(t, isOptional = false) {
216
+ const optional = isOptional ? " | nil" : "";
217
+ return (0, TypeUtils_1.matchType)(t, _anyType => ["any()", optional], _nullType => ["nil"], _boolType => ["boolean()", optional], _integerType => ["integer()", optional], _doubleType => ["float()", optional], _stringType => ["String.t()", optional], arrayType => ["[", this.elixirType(arrayType.items), "]", optional], classType => [this.nameForNamedTypeWithNamespace(classType), ".t()", optional], mapType => ["%{String.t() => ", this.elixirType(mapType.values), "}", optional], enumType => [this.nameForNamedTypeWithNamespace(enumType), ".t()", optional], unionType => {
218
+ const children = [...unionType.getChildren()].map(t => this.elixirType(t));
219
+ return [
220
+ children.flatMap((element, index) => (index === children.length - 1 ? element : [element, " | "])),
221
+ optional
222
+ ];
223
+ });
224
+ }
225
+ patternMatchClauseDecode(t, attributeName, suffix = "") {
226
+ return (0, TypeUtils_1.matchType)(t, _anyType => [], _nullType => ["def decode_", attributeName, suffix, "(value) when is_nil(value), do: value"], _boolType => ["def decode_", attributeName, suffix, "(value) when is_boolean(value), do: value"], _integerType => ["def decode_", attributeName, suffix, "(value) when is_integer(value), do: value"], _doubleType => [
227
+ "def decode_",
228
+ attributeName,
229
+ suffix,
230
+ "(value) when is_float(value), do: value\n",
231
+ "def decode_",
232
+ attributeName,
233
+ suffix,
234
+ "(value) when is_integer(value), do: value"
235
+ ], _stringType => ["def decode_", attributeName, suffix, "(value) when is_binary(value), do: value"], _arrayType => ["def decode_", attributeName, suffix, "(value) when is_list(value), do: value"], classType => {
236
+ const requiredAttributeArgs = [];
237
+ this.forEachClassProperty(classType, "none", (_name, jsonName, p) => {
238
+ if (!p.isOptional) {
239
+ requiredAttributeArgs.push(['"', jsonName, '" => _,']);
240
+ }
241
+ });
242
+ return [
243
+ "def decode_",
244
+ attributeName,
245
+ suffix,
246
+ "(%{",
247
+ requiredAttributeArgs,
248
+ "} = value), do: ",
249
+ this.nameForNamedTypeWithNamespace(classType),
250
+ ".from_map(value)"
251
+ ];
252
+ }, _mapType => ["def decode_", attributeName, suffix, "(value) when is_map(value), do: value"], enumType => [
253
+ "def decode_",
254
+ attributeName,
255
+ suffix,
256
+ "(value) when is_binary(value)",
257
+ ", do: ",
258
+ this.nameForNamedTypeWithNamespace(enumType),
259
+ ".decode(value)"
260
+ ], _unionType => []);
261
+ }
262
+ patternMatchClauseEncode(t, attributeName, suffix = "") {
263
+ return (0, TypeUtils_1.matchType)(t, _anyType => [], _nullType => ["def encode_", attributeName, suffix, "(value) when is_nil(value), do: value"], _boolType => ["def encode_", attributeName, suffix, "(value) when is_boolean(value), do: value"], _integerType => ["def encode_", attributeName, suffix, "(value) when is_integer(value), do: value"], _doubleType => [
264
+ "def encode_",
265
+ attributeName,
266
+ suffix,
267
+ "(value) when is_float(value), do: value\n",
268
+ "def encode_",
269
+ attributeName,
270
+ suffix,
271
+ "(value) when is_integer(value), do: value"
272
+ ], _stringType => ["def encode_", attributeName, suffix, "(value) when is_binary(value), do: value"], _arrayType => ["def encode_", attributeName, suffix, "(value) when is_list(value), do: value"], classType => {
273
+ const requiredAttributeArgs = [];
274
+ this.forEachClassProperty(classType, "none", (_name, jsonName, p) => {
275
+ if (!p.isOptional) {
276
+ requiredAttributeArgs.push(['"', jsonName, '" => _,']);
277
+ }
278
+ });
279
+ return [
280
+ "def encode_",
281
+ attributeName,
282
+ suffix,
283
+ "(%",
284
+ this.nameForNamedTypeWithNamespace(classType),
285
+ "{} = value), do: ",
286
+ this.nameForNamedTypeWithNamespace(classType),
287
+ ".to_map(value)"
288
+ ];
289
+ }, _mapType => ["def encode_", attributeName, suffix, "(value) when is_map(value), do: value"], enumType => [
290
+ "def encode_",
291
+ attributeName,
292
+ suffix,
293
+ "(value) when is_atom(value)",
294
+ ", do: ",
295
+ this.nameForNamedTypeWithNamespace(enumType),
296
+ ".encode(value)"
297
+ ], _unionType => []);
298
+ }
299
+ sortAndFilterPatternMatchTypes(types) {
300
+ return types
301
+ .filter(type => !(type instanceof Type_1.UnionType))
302
+ .sort((a, b) => {
303
+ if (a instanceof Type_1.ClassType && !(b instanceof Type_1.ClassType)) {
304
+ return -1;
305
+ }
306
+ else if (b instanceof Type_1.ClassType && !(a instanceof Type_1.ClassType)) {
307
+ return 1;
308
+ }
309
+ else if (a.kind === "bool" && b.kind !== "bool") {
310
+ return -1;
311
+ }
312
+ else if (b.kind === "bool" && a.kind !== "bool") {
313
+ return 1;
314
+ }
315
+ else if (a instanceof Type_1.EnumType && !(b instanceof Type_1.EnumType)) {
316
+ return -1;
317
+ }
318
+ else if (b instanceof Type_1.EnumType && !(a instanceof Type_1.EnumType)) {
319
+ return 1;
320
+ }
321
+ else if (a.isPrimitive() && !b.isPrimitive()) {
322
+ return -1;
323
+ }
324
+ else if (b.isPrimitive() && !a.isPrimitive()) {
325
+ return 1;
326
+ }
327
+ else {
328
+ return 0;
329
+ }
330
+ });
331
+ }
332
+ emitPatternMatches(types, name, parentName, suffix = "", optional = false) {
333
+ this.ensureBlankLine();
334
+ let typesToMatch = this.sortAndFilterPatternMatchTypes(types);
335
+ if (typesToMatch.length < 2) {
336
+ return;
337
+ }
338
+ if (typesToMatch.find(type => type.kind === "double")) {
339
+ typesToMatch = typesToMatch.filter(type => type.kind !== "integer");
340
+ }
341
+ typesToMatch.forEach(type => {
342
+ this.emitLine(this.patternMatchClauseDecode(type, name, suffix));
343
+ });
344
+ if (optional && !typesToMatch.find(type => type.kind === "null")) {
345
+ this.emitLine("def decode_", name, suffix, "(value) when is_nil(value), do: value");
346
+ }
347
+ this.emitLine("def decode_", name, suffix, '(_), do: {:error, "Unexpected type when decoding ', parentName, ".", name, '"}');
348
+ this.ensureBlankLine();
349
+ typesToMatch.forEach(type => {
350
+ this.emitLine(this.patternMatchClauseEncode(type, name, suffix));
351
+ });
352
+ if (optional && !typesToMatch.find(type => type.kind === "null")) {
353
+ this.emitLine("def encode_", name, suffix, "(value) when is_nil(value), do: value");
354
+ }
355
+ this.emitLine("def encode_", name, suffix, '(_), do: {:error, "Unexpected type when encoding ', parentName, ".", name, '"}');
356
+ this.ensureBlankLine();
357
+ }
358
+ nameOfTransformFunction(t, name, encode = false, prefix = "") {
359
+ let mode = "decode";
360
+ if (encode) {
361
+ mode = "encode";
362
+ }
363
+ return (0, TypeUtils_1.matchType)(t, _anyType => [], _nullType => [], _boolType => [], _integerType => [], _doubleType => [], _stringType => [], _arrayType => [], classType => [this.nameForNamedTypeWithNamespace(classType), `.${encode ? "to" : "from"}_map`], _mapType => [], enumType => {
364
+ return [this.nameForNamedTypeWithNamespace(enumType), `.${mode}`];
365
+ }, _unionType => {
366
+ return [`${mode}_`, name, prefix];
367
+ });
368
+ }
369
+ fromDynamic(t, jsonName, name, optional = false) {
370
+ const primitive = ['m["', jsonName, '"]'];
371
+ return (0, TypeUtils_1.matchType)(t, _anyType => primitive, _nullType => primitive, _boolType => primitive, _integerType => primitive, _doubleType => primitive, _stringType => primitive, arrayType => {
372
+ const arrayElement = arrayType.items;
373
+ if (arrayElement instanceof Type_1.ArrayType) {
374
+ return primitive;
375
+ }
376
+ else if (arrayElement.isPrimitive()) {
377
+ return primitive;
378
+ }
379
+ else if (arrayElement instanceof Type_1.MapType) {
380
+ return primitive;
381
+ }
382
+ else {
383
+ if (optional) {
384
+ return [
385
+ "m",
386
+ '["',
387
+ jsonName,
388
+ '"] && Enum.map(m["',
389
+ jsonName,
390
+ '"], &',
391
+ this.nameOfTransformFunction(arrayElement, name, false, "_element"),
392
+ "/1)"
393
+ ];
394
+ }
395
+ else {
396
+ return [
397
+ 'Enum.map(m["',
398
+ jsonName,
399
+ '"], &',
400
+ this.nameOfTransformFunction(arrayElement, name, false, "_element"),
401
+ "/1)"
402
+ ];
403
+ }
404
+ }
405
+ }, classType => [
406
+ optional ? [primitive, " && "] : "",
407
+ this.nameForNamedTypeWithNamespace(classType),
408
+ ".from_map(",
409
+ primitive,
410
+ ")"
411
+ ], mapType => {
412
+ const mapValueTypes = [...mapType.values.getChildren()];
413
+ const mapValueTypesNotPrimitive = mapValueTypes.filter(type => !(type instanceof Type_1.PrimitiveType));
414
+ if (mapValueTypesNotPrimitive.length === 0) {
415
+ return [primitive];
416
+ }
417
+ else {
418
+ if (mapType.values.kind === "union") {
419
+ return [
420
+ 'm["',
421
+ jsonName,
422
+ '"]\n|> Map.new(fn {key, value} -> {key, ',
423
+ this.nameOfTransformFunction(mapType.values, jsonName, false),
424
+ "_value(value)} end)"
425
+ ];
426
+ }
427
+ else if (mapType.values instanceof Type_1.EnumType || mapType.values instanceof Type_1.ClassType) {
428
+ return [
429
+ 'm["',
430
+ jsonName,
431
+ '"]\n|> Map.new(fn {key, value} -> {key, ',
432
+ this.nameOfTransformFunction(mapType.values, jsonName, false),
433
+ "(value)} end)"
434
+ ];
435
+ }
436
+ return [primitive];
437
+ }
438
+ }, enumType => {
439
+ return [
440
+ optional ? [primitive, " && "] : "",
441
+ this.nameOfTransformFunction(enumType, name),
442
+ "(",
443
+ primitive,
444
+ ")"
445
+ ];
446
+ }, unionType => {
447
+ const unionTypes = [...unionType.getChildren()];
448
+ const unionPrimitiveTypes = unionTypes.filter(type => type.isPrimitive());
449
+ if (unionTypes.length === unionPrimitiveTypes.length) {
450
+ return ['m["', jsonName, '"]'];
451
+ }
452
+ const nullable = (0, TypeUtils_1.nullableFromUnion)(unionType);
453
+ if (nullable !== null) {
454
+ if (nullable instanceof Type_1.ClassType) {
455
+ return this.fromDynamic(nullable, jsonName, name, true);
456
+ }
457
+ const nullableTypes = [...nullable.getChildren()];
458
+ if (nullableTypes.length < 2) {
459
+ return this.fromDynamic(nullable, jsonName, name, true);
460
+ }
461
+ return ['m["', jsonName, '"] && decode_', name, '(m["', jsonName, '"])'];
462
+ }
463
+ return ["decode_", name, '(m["', jsonName, '"])'];
464
+ });
465
+ }
466
+ toDynamic(t, e, optional = false) {
467
+ const expression = ["struct.", e];
468
+ return (0, TypeUtils_1.matchType)(t, _anyType => expression, _nullType => expression, _boolType => expression, _integerType => expression, _doubleType => expression, _stringType => expression, arrayType => {
469
+ const arrayElement = arrayType.items;
470
+ if (arrayElement instanceof Type_1.ArrayType) {
471
+ return expression;
472
+ }
473
+ if (arrayElement.isPrimitive()) {
474
+ return expression;
475
+ }
476
+ else if (arrayElement instanceof Type_1.MapType) {
477
+ return expression;
478
+ }
479
+ else {
480
+ if (arrayElement.kind === "array") {
481
+ return expression;
482
+ }
483
+ else {
484
+ if (optional) {
485
+ return [
486
+ "struct.",
487
+ e,
488
+ " && Enum.map(struct.",
489
+ e,
490
+ ", &",
491
+ this.nameOfTransformFunction(arrayElement, e, true, "_element"),
492
+ "/1)"
493
+ ];
494
+ }
495
+ else {
496
+ return [
497
+ "struct.",
498
+ e,
499
+ " && Enum.map(struct.",
500
+ e,
501
+ ", &",
502
+ this.nameOfTransformFunction(arrayElement, e, true, "_element"),
503
+ "/1)"
504
+ ];
505
+ }
506
+ }
507
+ }
508
+ }, classType => [
509
+ optional ? ["struct.", e, " && "] : "",
510
+ this.nameForNamedTypeWithNamespace(classType),
511
+ ".to_map(",
512
+ "struct.",
513
+ e,
514
+ ")"
515
+ ], mapType => {
516
+ const mapValueTypes = [...mapType.values.getChildren()];
517
+ const mapValueTypesNotPrimitive = mapValueTypes.filter(type => !(type instanceof Type_1.PrimitiveType));
518
+ if (mapValueTypesNotPrimitive.length === 0) {
519
+ return [expression];
520
+ }
521
+ else {
522
+ if (mapType.values.kind === "union") {
523
+ return [
524
+ "struct.",
525
+ e,
526
+ "\n|> Map.new(fn {key, value} -> {key, ",
527
+ this.nameOfTransformFunction(mapType.values, e, true),
528
+ "_value(value)} end)"
529
+ ];
530
+ }
531
+ else if (mapType.values instanceof Type_1.EnumType || mapType.values instanceof Type_1.ClassType) {
532
+ return [
533
+ "struct.",
534
+ e,
535
+ "\n|> Map.new(fn {key, value} -> {key, ",
536
+ this.nameOfTransformFunction(mapType.values, e, true),
537
+ "(value)} end)"
538
+ ];
539
+ }
540
+ return [expression];
541
+ }
542
+ }, enumType => {
543
+ return [
544
+ optional ? ["struct.", e, " && "] : "",
545
+ this.nameForNamedTypeWithNamespace(enumType),
546
+ ".encode(struct.",
547
+ e,
548
+ ")"
549
+ ];
550
+ }, unionType => {
551
+ const unionTypes = [...unionType.getChildren()];
552
+ const unionPrimitiveTypes = unionTypes.filter(type => type.isPrimitive());
553
+ if (unionTypes.length === unionPrimitiveTypes.length) {
554
+ return ["struct.", e];
555
+ }
556
+ const nullable = (0, TypeUtils_1.nullableFromUnion)(unionType);
557
+ if (nullable !== null) {
558
+ if (nullable instanceof Type_1.ClassType) {
559
+ return this.toDynamic(nullable, e, true);
560
+ }
561
+ const nullableTypes = [...nullable.getChildren()];
562
+ if (nullableTypes.length < 2) {
563
+ return this.toDynamic(nullable, e, true);
564
+ }
565
+ return ["struct.", e, " && encode_", e, "(struct.", e, ")"];
566
+ }
567
+ return ["encode_", e, "(struct.", e, ")"];
568
+ });
569
+ }
570
+ emitBlock(source, emit) {
571
+ this.emitLine(source);
572
+ this.indent(emit);
573
+ this.emitLine("end");
574
+ }
575
+ emitDescriptionBlock(lines) {
576
+ this.emitCommentLines(lines, {
577
+ firstLineStart: '@moduledoc """\n',
578
+ lineStart: "",
579
+ afterComment: '"""'
580
+ });
581
+ }
582
+ emitModule(c, moduleName) {
583
+ this.emitBlock(["defmodule ", this.nameWithNamespace(moduleName), " do"], () => {
584
+ var _a;
585
+ const structDescription = (_a = this.descriptionForType(c)) !== null && _a !== void 0 ? _a : [];
586
+ const attributeDescriptions = [];
587
+ this.forEachClassProperty(c, "none", (name, jsonName, _p) => {
588
+ const attributeDescription = this.descriptionForClassProperty(c, jsonName);
589
+ if (attributeDescription) {
590
+ attributeDescriptions.push(["- `:", name, "` - ", attributeDescription]);
591
+ }
592
+ });
593
+ if (structDescription.length || attributeDescriptions.length) {
594
+ this.emitDescription([...structDescription, ...attributeDescriptions]);
595
+ this.ensureBlankLine();
596
+ }
597
+ const requiredAttributes = [];
598
+ this.forEachClassProperty(c, "none", (name, _jsonName, p) => {
599
+ if (!p.isOptional) {
600
+ if (requiredAttributes.length === 0) {
601
+ requiredAttributes.push([":", name]);
602
+ }
603
+ else {
604
+ requiredAttributes.push([", :", name]);
605
+ }
606
+ }
607
+ });
608
+ if (requiredAttributes.length) {
609
+ this.emitLine(["@enforce_keys [", requiredAttributes, "]"]);
610
+ }
611
+ const attributeNames = [];
612
+ this.forEachClassProperty(c, "none", (name, _jsonName, _p) => {
613
+ if (attributeNames.length === 0) {
614
+ attributeNames.push([":", name]);
615
+ }
616
+ else {
617
+ attributeNames.push([", :", name]);
618
+ }
619
+ });
620
+ this.emitLine(["defstruct [", attributeNames, "]"]);
621
+ this.ensureBlankLine();
622
+ const typeDefinitionTable = [[["@type "], ["t :: %__MODULE__{"]]];
623
+ let count = c.getProperties().size;
624
+ this.forEachClassProperty(c, "none", (name, _jsonName, p) => {
625
+ const last = --count === 0;
626
+ const attributeRow = [
627
+ [],
628
+ [" ", name, ": ", this.elixirType(p.type), p.isOptional ? " | nil" : "", last ? "" : ","]
629
+ ];
630
+ typeDefinitionTable.push(attributeRow);
631
+ });
632
+ typeDefinitionTable.push([[], ["}"]]);
633
+ this.emitTable(typeDefinitionTable);
634
+ if (this._options.justTypes) {
635
+ return;
636
+ }
637
+ this.forEachClassProperty(c, "none", (name, _jsonName, p) => {
638
+ if (p.type.kind === "union") {
639
+ const unionTypes = [...p.type.getChildren()];
640
+ const unionPrimitiveTypes = unionTypes.filter(type => type.isPrimitive());
641
+ if (unionTypes.length === unionPrimitiveTypes.length) {
642
+ return;
643
+ }
644
+ const unionTypesNonNull = unionTypes.filter(type => type.kind !== "null");
645
+ if (unionTypesNonNull.length === 1) {
646
+ let suffix = "";
647
+ let itemTypes = [];
648
+ if (unionTypesNonNull[0] instanceof Type_1.ArrayType) {
649
+ suffix = "_element";
650
+ itemTypes = [...unionTypesNonNull[0].getChildren()];
651
+ }
652
+ else if (unionTypesNonNull[0] instanceof Type_1.MapType) {
653
+ suffix = "_value";
654
+ itemTypes = [...unionTypesNonNull[0].getChildren()];
655
+ }
656
+ if (itemTypes.length === 1 && itemTypes[0] instanceof Type_1.UnionType) {
657
+ itemTypes = [...itemTypes[0].getChildren()];
658
+ }
659
+ this.emitPatternMatches(itemTypes, name, this.nameForNamedTypeWithNamespace(c), suffix, p.isOptional);
660
+ }
661
+ else {
662
+ this.emitPatternMatches(unionTypes, name, this.nameForNamedTypeWithNamespace(c), "", p.isOptional);
663
+ }
664
+ }
665
+ else if (p.type.kind === "array") {
666
+ const arrayType = p.type;
667
+ if (arrayType.items instanceof Type_1.UnionType) {
668
+ const unionType = arrayType.items;
669
+ const typesInUnion = [...unionType.getChildren()];
670
+ this.emitPatternMatches(typesInUnion, name, this.nameForNamedTypeWithNamespace(c), "_element");
671
+ }
672
+ }
673
+ else if (p.type.kind === "map") {
674
+ const mapType = p.type;
675
+ if (mapType.values instanceof Type_1.UnionType) {
676
+ const unionType = mapType.values;
677
+ const typesInUnion = [...unionType.getChildren()];
678
+ this.emitPatternMatches(typesInUnion, name, this.nameForNamedTypeWithNamespace(c), "_value");
679
+ }
680
+ }
681
+ });
682
+ let propCount = 0;
683
+ this.forEachClassProperty(c, "none", (_name, _jsonName, _p) => {
684
+ propCount++;
685
+ });
686
+ const isEmpty = propCount ? false : true;
687
+ this.ensureBlankLine();
688
+ this.emitBlock([`def from_map(${isEmpty ? "_" : ""}m) do`], () => {
689
+ this.emitLine("%", this.nameWithNamespace(moduleName), "{");
690
+ this.indent(() => {
691
+ this.forEachClassProperty(c, "none", (name, jsonName, p) => {
692
+ jsonName = escapeDoubleQuotes(jsonName);
693
+ jsonName = escapeNewLines(jsonName);
694
+ const expression = this.fromDynamic(p.type, jsonName, name, p.isOptional);
695
+ this.emitLine(name, ": ", expression, ",");
696
+ });
697
+ });
698
+ this.emitLine("}");
699
+ });
700
+ this.ensureBlankLine();
701
+ this.emitBlock("def from_json(json) do", () => {
702
+ this.emitMultiline(`json
703
+ |> Jason.decode!()
704
+ |> from_map()`);
705
+ });
706
+ this.ensureBlankLine();
707
+ this.emitBlock([`def to_map(${isEmpty ? "_" : ""}struct) do`], () => {
708
+ this.emitLine("%{");
709
+ this.indent(() => {
710
+ this.forEachClassProperty(c, "none", (name, jsonName, p) => {
711
+ const expression = this.toDynamic(p.type, name, p.isOptional);
712
+ this.emitLine([[`"${stringEscape(jsonName)}"`], [" => ", expression, ","]]);
713
+ });
714
+ });
715
+ this.emitLine("}");
716
+ });
717
+ this.ensureBlankLine();
718
+ this.emitBlock("def to_json(struct) do", () => {
719
+ this.emitMultiline(`struct
720
+ |> to_map()
721
+ |> Jason.encode!()`);
722
+ });
723
+ });
724
+ }
725
+ isValidAtom(str) {
726
+ function isLetter(char) {
727
+ return /^[A-Za-z_]$/.test(char);
728
+ }
729
+ function isLetterOrDigit(char) {
730
+ return /^[A-Za-z0-9_]$/.test(char);
731
+ }
732
+ if (str.length === 0) {
733
+ return false;
734
+ }
735
+ const firstChar = str[0];
736
+ if (!isLetter(firstChar)) {
737
+ return false;
738
+ }
739
+ for (let i = 1; i < str.length; i++) {
740
+ const char = str[i];
741
+ if (!isLetterOrDigit(char) && char !== "@" && !(i === str.length - 1 && (char === "!" || char === "?"))) {
742
+ return false;
743
+ }
744
+ }
745
+ return true;
746
+ }
747
+ emitEnum(e, enumName) {
748
+ this.emitBlock(["defmodule ", this.nameWithNamespace(enumName), " do"], () => {
749
+ this.emitDescription(this.descriptionForType(e));
750
+ this.emitLine("@valid_enum_members [");
751
+ this.indent(() => {
752
+ this.forEachEnumCase(e, "none", (_name, json) => {
753
+ if (this.isValidAtom(json)) {
754
+ this.emitLine(":", json, ",");
755
+ }
756
+ else {
757
+ this.emitLine(":", `"${json}"`, ",");
758
+ }
759
+ });
760
+ });
761
+ this.emitLine("]");
762
+ this.ensureBlankLine();
763
+ this.emitMultiline(`def valid_atom?(value), do: value in @valid_enum_members
764
+
765
+ def valid_atom_string?(value) do
766
+ try do
767
+ atom = String.to_existing_atom(value)
768
+ atom in @valid_enum_members
769
+ rescue
770
+ ArgumentError -> false
771
+ end
772
+ end
773
+
774
+ def encode(value) do
775
+ if valid_atom?(value) do
776
+ Atom.to_string(value)
777
+ else
778
+ {:error, "Unexpected value when encoding atom: #{inspect(value)}"}
779
+ end
780
+ end
781
+
782
+ def decode(value) do
783
+ if valid_atom_string?(value) do
784
+ String.to_existing_atom(value)
785
+ else
786
+ {:error, "Unexpected value when decoding atom: #{inspect(value)}"}
787
+ end
788
+ end
789
+
790
+ def from_json(json) do
791
+ json
792
+ |> Jason.decode!()
793
+ |> decode()
794
+ end
795
+
796
+ def to_json(data) do
797
+ data
798
+ |> encode()
799
+ |> Jason.encode!()
800
+ end`);
801
+ });
802
+ }
803
+ emitUnion(_u, _unionName) {
804
+ return;
805
+ }
806
+ emitSourceStructure() {
807
+ if (this.leadingComments !== undefined) {
808
+ this.emitComments(this.leadingComments);
809
+ }
810
+ else if (!this._options.justTypes) {
811
+ this.emitMultiline(`# This file was autogenerated using quicktype https://github.com/quicktype/quicktype
812
+ #
813
+ # Add Jason to your mix.exs`);
814
+ this.forEachTopLevel("none", (_topLevel, name) => {
815
+ this.emitLine("#");
816
+ this.emitLine("# Decode a JSON string: ", this.nameWithNamespace(name), ".from_json(data)");
817
+ this.emitLine("# Encode into a JSON string: ", this.nameWithNamespace(name), ".to_json(struct)");
818
+ });
819
+ }
820
+ this.ensureBlankLine();
821
+ this.forEachNamedType("leading-and-interposing", (c, n) => this.emitModule(c, n), (e, n) => this.emitEnum(e, n), (u, n) => this.emitUnion(u, n));
822
+ if (!this._options.justTypes) {
823
+ this.forEachTopLevel("leading-and-interposing", (topLevel, name) => {
824
+ const isTopLevelArray = "array" === topLevel.kind;
825
+ this.emitBlock(["defmodule ", this.nameWithNamespace(name), " do"], () => {
826
+ var _a;
827
+ const description = (_a = this.descriptionForType(topLevel)) !== null && _a !== void 0 ? _a : [];
828
+ if (description.length) {
829
+ this.emitDescription([...description]);
830
+ this.ensureBlankLine();
831
+ }
832
+ if (isTopLevelArray) {
833
+ const arrayElement = topLevel.items;
834
+ let isUnion = false;
835
+ if (arrayElement instanceof Type_1.UnionType) {
836
+ this.emitPatternMatches([...arrayElement.getChildren()], "element", name);
837
+ isUnion = true;
838
+ }
839
+ this.emitBlock("def from_json(json) do", () => {
840
+ this.emitLine("json");
841
+ this.emitLine("|> Jason.decode!()");
842
+ this.emitLine("|> Enum.map(&", isUnion
843
+ ? ["decode_element/1)"]
844
+ : [this.nameWithNamespace(name), "Element.from_map/1)"]);
845
+ });
846
+ this.ensureBlankLine();
847
+ this.emitBlock("def to_json(list) do", () => {
848
+ this.emitLine("Enum.map(list, &", isUnion
849
+ ? ["encode_element/1)"]
850
+ : [this.nameWithNamespace(name), "Element.to_map/1)"]);
851
+ this.emitLine("|> Jason.encode!()");
852
+ });
853
+ }
854
+ else {
855
+ this.emitBlock("def from_json(json) do", () => {
856
+ this.emitLine("Jason.decode!(json)");
857
+ });
858
+ this.ensureBlankLine();
859
+ this.emitBlock("def to_json(data) do", () => {
860
+ this.emitLine("Jason.encode!(data)");
861
+ });
862
+ }
863
+ });
864
+ }, t => this.namedTypeToNameForTopLevel(t) === undefined);
865
+ }
866
+ }
867
+ }
868
+ exports.ElixirRenderer = ElixirRenderer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "quicktype-core",
3
- "version": "23.0.141",
3
+ "version": "23.0.143",
4
4
  "description": "The quicktype engine as a library",
5
5
  "license": "Apache-2.0",
6
6
  "main": "dist/index.js",