json-as 0.9.17 → 0.9.19

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.
@@ -3,458 +3,510 @@ import { toString, isStdlib } from "visitor-as/dist/utils.js";
3
3
  import { BaseVisitor, SimpleParser } from "visitor-as/dist/index.js";
4
4
  import { Transform } from "assemblyscript/dist/transform.js";
5
5
  class JSONTransform extends BaseVisitor {
6
- constructor() {
7
- super(...arguments);
8
- this.schemasList = [];
9
- this.sources = new Set();
6
+ constructor() {
7
+ super(...arguments);
8
+ this.schemasList = [];
9
+ this.sources = new Set();
10
+ }
11
+ visitMethodDeclaration() {}
12
+ visitClassDeclaration(node) {
13
+ if (!node.decorators?.length) return;
14
+ let found = false;
15
+ for (const decorator of node.decorators) {
16
+ const name = decorator.name.text;
17
+ if (name === "json" || name === "serializable") {
18
+ found = true;
19
+ break;
20
+ }
10
21
  }
11
- visitMethodDeclaration() { }
12
- visitClassDeclaration(node) {
13
- if (!node.decorators?.length)
14
- return;
15
- let found = false;
16
- for (const decorator of node.decorators) {
17
- const name = decorator.name.text;
18
- if (name === "json" || name === "serializable") {
19
- found = true;
20
- break;
21
- }
22
- }
23
- if (!found)
24
- return;
25
- const schema = new SchemaData();
26
- schema.node = node;
27
- schema.name = node.name.text;
28
- const members = [
29
- ...node.members.filter(v => v.kind === 54 /* NodeKind.FieldDeclaration */)
30
- ];
31
- if (node.extendsType) {
32
- schema.parent = this.schemasList.find((v) => v.name == node.extendsType?.name.identifier.text);
33
- if (schema.parent?.members) {
34
- for (let i = schema.parent.members.length - 1; i >= 0; i--) {
35
- const replace = schema.members.find((v) => v.name == schema.parent?.members[i]?.name);
36
- if (!replace) {
37
- //schema.members.unshift(schema.parent?.members[i]!);
38
- members.unshift(schema.parent?.members[i].node);
39
- }
40
- }
41
- }
42
- }
43
- if (!members.length) {
44
- let SERIALIZE_RAW_EMPTY = "__SERIALIZE(): string {\n return \"{}\";\n}";
45
- //let SERIALIZE_PRETTY_EMPTY = "__SERIALIZE_PRETTY(): string {\n return \"{}\";\n}";
46
- let INITIALIZE_EMPTY = "__INITIALIZE(): this {\n return this;\n}";
47
- let DESERIALIZE_EMPTY = "__DESERIALIZE(data: string, key_start: i32, key_end: i32, value_start: i32, value_end: i32): boolean {\n return false;\n}";
48
- if (process.env["JSON_DEBUG"]) {
49
- console.log(SERIALIZE_RAW_EMPTY);
50
- //console.log(SERIALIZE_PRETTY_EMPTY);
51
- console.log(INITIALIZE_EMPTY);
52
- console.log(DESERIALIZE_EMPTY);
53
- }
54
- const SERIALIZE_RAW_METHOD_EMPTY = SimpleParser.parseClassMember(SERIALIZE_RAW_EMPTY, node);
55
- //const SERIALIZE_PRETTY_METHOD = SimpleParser.parseClassMember(SERIALIZE_PRETTY, node);
56
- const INITIALIZE_METHOD_EMPTY = SimpleParser.parseClassMember(INITIALIZE_EMPTY, node);
57
- const DESERIALIZE_METHOD_EMPTY = SimpleParser.parseClassMember(DESERIALIZE_EMPTY, node);
58
- if (!node.members.find(v => v.name.text == "__SERIALIZE"))
59
- node.members.push(SERIALIZE_RAW_METHOD_EMPTY);
60
- if (!node.members.find(v => v.name.text == "__INITIALIZE"))
61
- node.members.push(INITIALIZE_METHOD_EMPTY);
62
- if (!node.members.find(v => v.name.text == "__DESERIALIZE"))
63
- node.members.push(DESERIALIZE_METHOD_EMPTY);
64
- this.schemasList.push(schema);
65
- }
66
- for (const member of members) {
67
- const name = member.name;
68
- if (!(member instanceof FieldDeclaration))
69
- continue;
70
- if (!member.type) {
71
- throw new Error("Fields must be strongly typed! Found " + toString(member) + " at " + node.range.source.normalizedPath);
72
- }
73
- const type = toString(member.type);
74
- if (type.startsWith("(") && type.includes("=>"))
75
- continue;
76
- const value = member.initializer ? toString(member.initializer) : null;
77
- if (member.flags == 32 /* CommonFlags.Static */)
78
- continue;
79
- if (member.flags === 512 /* CommonFlags.Private */)
80
- continue;
81
- if (member.flags === 1024 /* CommonFlags.Protected */)
82
- continue;
83
- if (member.decorators && member.decorators.find((v) => v.name.text == "omit"))
84
- continue;
85
- const mem = new Property();
86
- mem.name = name.text;
87
- mem.type = type;
88
- mem.value = value;
89
- mem.node = member;
90
- if (member.decorators) {
91
- let decorator = null;
92
- if (decorator = member.decorators.find(v => v.name.text == "alias")) {
93
- if (decorator.name.text == "alias") {
94
- if (!decorator.args?.length)
95
- throw new Error("Expected 1 argument but got zero at @alias in " + node.range.source.normalizedPath);
96
- mem.flags.push(PropertyFlags.Alias);
97
- mem.alias = decorator.args[0].value;
98
- }
99
- }
100
- for (let i = 0; i < (member.decorators).length; i++) {
101
- const decorator = member.decorators[i];
102
- if (decorator.name.text == "omitnull") {
103
- mem.flags.push(PropertyFlags.OmitNull);
104
- }
105
- else if (decorator.name.text == "omitif") {
106
- if (!decorator.args?.length)
107
- throw new Error("Expected 1 argument but got zero at @omitif in " + node.range.source.normalizedPath);
108
- mem.args?.push(decorator.args[0].value);
109
- mem.flags.push(PropertyFlags.OmitIf);
110
- }
111
- else if (decorator.name.text == "flatten") {
112
- if (!decorator.args?.length)
113
- throw new Error("Expected 1 argument but got zero at @flatten in " + node.range.source.normalizedPath);
114
- mem.flags.push(PropertyFlags.Flatten);
115
- mem.args = [decorator.args[0].value];
116
- }
117
- }
118
- }
119
- if (!mem.flags.length) {
120
- mem.flags = [PropertyFlags.None];
121
- if (type == "JSON.Raw") {
122
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${this." + name.text + "}";
123
- mem.deserialize = "this." + name.text + " = " + "data.substring(value_start, value_end);";
124
- }
125
- else {
126
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${__SERIALIZE<" + type + ">(this." + name.text + ")}";
127
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end));";
128
- }
129
- }
130
- if (mem.flags.includes(PropertyFlags.OmitNull)) {
131
- mem.serialize = "${changetype<usize>(this." + mem.name + ") == <usize>0" + " ? \"\" : '" + escapeString(JSON.stringify(mem.alias || mem.name)) + ":' + __SERIALIZE<" + type + ">(this." + name.text + ") + \",\"}";
132
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end));";
133
- }
134
- else if (mem.flags.includes(PropertyFlags.OmitIf)) {
135
- mem.serialize = "${" + mem.args[0] + " ? \"\" : '" + escapeString(JSON.stringify(mem.alias || mem.name)) + ":' + __SERIALIZE<" + type + ">(this." + name.text + ") + \",\"}";
136
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end));";
137
- }
138
- else if (mem.flags.includes(PropertyFlags.Alias)) {
139
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${__SERIALIZE<" + type + ">(this." + name.text + ")}";
140
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end));";
141
- mem.name = name.text;
142
- }
143
- else if (mem.flags.includes(PropertyFlags.Flatten)) {
144
- const nullable = mem.node.type.isNullable;
145
- if (nullable) {
146
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${this." + name.text + " ? __SERIALIZE(changetype<nonnull<" + type + ">>(this." + name.text + ")" + (mem.args?.length ? '.' + mem.args.join(".") : '') + ") : \"null\"}";
147
- mem.deserialize = "if (value_end - value_start == 4 && load<u64>(changetype<usize>(data) + <usize>(value_start << 1)) == " + charCodeAt64("null", 0) + ") {\n this." + name.text + " = null;\n } else {\n this." + name.text + " = " + "__DESERIALIZE<" + type + ">('{\"" + mem.args[0] + "\":' + data.substring(value_start, value_end) + \"}\");\n }";
148
- }
149
- else {
150
- mem.serialize = escapeString(JSON.stringify(mem.alias || mem.name)) + ":${this." + name.text + " ? __SERIALIZE(this." + name.text + (mem.args?.length ? '.' + mem.args.join(".") : '') + ") : \"null\"}";
151
- mem.deserialize = "this." + name.text + " = " + "__DESERIALIZE<" + type + ">('{\"" + mem.args[0] + "\":' + data.substring(value_start, value_end) + \"}\");";
152
- }
153
- mem.name = name.text;
154
- }
155
- const t = mem.node.type.name?.identifier.text;
156
- if (this.schemasList.find(v => v.name == t)) {
157
- mem.initialize = "this." + name.text + " = changetype<nonnull<" + mem.type + ">>(__new(offsetof<nonnull<" + mem.type + ">>(), idof<nonnull<" + mem.type + ">>()));\n changetype<nonnull<" + mem.type + ">>(this." + name.text + ").__INITIALIZE()";
158
- }
159
- else if (mem.value) {
160
- mem.initialize = "this." + name.text + " = " + mem.value;
161
- }
162
- else if (t === "Map") {
163
- mem.initialize = "this." + name.text + " = new " + mem.type + "()";
164
- }
165
- else if (t === "string") {
166
- mem.initialize = "this." + name.text + " = \"\"";
167
- }
168
- else if (t === "Array") {
169
- mem.initialize = "this." + name.text + " = instantiate<" + mem.type + ">()";
170
- }
171
- else if (t === "bool" || t === "boolean") {
172
- mem.initialize = "this." + name.text + " = false";
173
- }
174
- else if (t === "JSON.Raw") {
175
- mem.initialize = "this." + name.text + " = \"\"";
176
- }
177
- else if (t === "u8" ||
178
- t === "u16" ||
179
- t === "u32" ||
180
- t === "u64" ||
181
- t === "i8" ||
182
- t === "i16" ||
183
- t === "i32" ||
184
- t === "i64") {
185
- mem.initialize = "this." + name.text + " = 0";
186
- }
187
- else if (t === "f32" ||
188
- t === "f64") {
189
- mem.initialize = "this." + name.text + " = 0.0";
190
- }
191
- schema.members.push(mem);
192
- }
193
- let SERIALIZE_RAW = "__SERIALIZE(): string {\n let out = `{";
194
- let SERIALIZE_PRETTY = "__SERIALIZE_PRETTY(): string {\n let out = `{";
195
- let INITIALIZE = "__INITIALIZE(): this {\n";
196
- let DESERIALIZE = "__DESERIALIZE(data: string, key_start: i32, key_end: i32, value_start: i32, value_end: i32): boolean {\n const len = key_end - key_start;\n";
197
- let indent = " ";
198
- if (!schema.members.length)
199
- return;
200
- found = false;
201
- if (schema.members[0]?.flags.includes(PropertyFlags.OmitNull)
202
- || schema.members[0]?.flags.includes(PropertyFlags.OmitIf)) {
203
- SERIALIZE_RAW += schema.members[0]?.serialize;
204
- SERIALIZE_PRETTY += "\\n" + schema.members[0]?.serialize;
22
+ if (!found) return;
23
+ const schema = new SchemaData();
24
+ schema.node = node;
25
+ schema.name = node.name.text;
26
+ const members = [
27
+ ...node.members.filter(
28
+ (v) => v.kind === 54 /* NodeKind.FieldDeclaration */,
29
+ ),
30
+ ];
31
+ if (node.extendsType) {
32
+ schema.parent = this.schemasList.find(
33
+ (v) => v.name == node.extendsType?.name.identifier.text,
34
+ );
35
+ if (schema.parent?.members) {
36
+ for (let i = schema.parent.members.length - 1; i >= 0; i--) {
37
+ const replace = schema.members.find(
38
+ (v) => v.name == schema.parent?.members[i]?.name,
39
+ );
40
+ if (!replace) {
41
+ members.unshift(schema.parent?.members[i].node);
42
+ }
205
43
  }
206
- else {
207
- SERIALIZE_RAW += schema.members[0]?.serialize + ",";
208
- SERIALIZE_PRETTY += "\\n" + schema.members[0]?.serialize + ",\\n";
209
- found = true;
210
- }
211
- if (schema.members[0]?.initialize)
212
- INITIALIZE += " " + schema.members[0]?.initialize + ";\n";
213
- for (let i = 1; i < schema.members.length; i++) {
214
- const member = schema.members[i];
215
- if (member.initialize)
216
- INITIALIZE += " " + member.initialize + ";\n";
217
- if (member.flags.includes(PropertyFlags.OmitNull)
218
- || member.flags.includes(PropertyFlags.OmitIf)) {
219
- SERIALIZE_RAW += member.serialize;
220
- SERIALIZE_PRETTY += member.serialize;
221
- }
222
- else {
223
- SERIALIZE_RAW += member.serialize + ",";
224
- SERIALIZE_PRETTY += indent + member.serialize + ",\\n";
225
- found = true;
226
- }
44
+ }
45
+ }
46
+ if (!members.length) {
47
+ let SERIALIZE_RAW_EMPTY = '__SERIALIZE(): string {\n return "{}";\n}';
48
+ //let SERIALIZE_PRETTY_EMPTY = "__SERIALIZE_PRETTY(): string {\n return \"{}\";\n}";
49
+ let INITIALIZE_EMPTY = "__INITIALIZE(): this {\n return this;\n}";
50
+ let DESERIALIZE_EMPTY =
51
+ "__DESERIALIZE(data: string, key_start: i32, key_end: i32, value_start: i32, value_end: i32): boolean {\n return false;\n}";
52
+ if (process.env["JSON_DEBUG"]) {
53
+ console.log(SERIALIZE_RAW_EMPTY);
54
+ //console.log(SERIALIZE_PRETTY_EMPTY);
55
+ console.log(INITIALIZE_EMPTY);
56
+ console.log(DESERIALIZE_EMPTY);
57
+ }
58
+ const SERIALIZE_RAW_METHOD_EMPTY = SimpleParser.parseClassMember(
59
+ SERIALIZE_RAW_EMPTY,
60
+ node,
61
+ );
62
+ //const SERIALIZE_PRETTY_METHOD = SimpleParser.parseClassMember(SERIALIZE_PRETTY, node);
63
+ const INITIALIZE_METHOD_EMPTY = SimpleParser.parseClassMember(
64
+ INITIALIZE_EMPTY,
65
+ node,
66
+ );
67
+ const DESERIALIZE_METHOD_EMPTY = SimpleParser.parseClassMember(
68
+ DESERIALIZE_EMPTY,
69
+ node,
70
+ );
71
+ if (!node.members.find((v) => v.name.text == "__SERIALIZE"))
72
+ node.members.push(SERIALIZE_RAW_METHOD_EMPTY);
73
+ if (!node.members.find((v) => v.name.text == "__INITIALIZE"))
74
+ node.members.push(INITIALIZE_METHOD_EMPTY);
75
+ if (!node.members.find((v) => v.name.text == "__DESERIALIZE"))
76
+ node.members.push(DESERIALIZE_METHOD_EMPTY);
77
+ this.schemasList.push(schema);
78
+ }
79
+ for (const member of members) {
80
+ const name = member.name;
81
+ if (!(member instanceof FieldDeclaration)) continue;
82
+ if (!member.type) {
83
+ throw new Error(
84
+ "Fields must be strongly typed! Found " +
85
+ toString(member) +
86
+ " at " +
87
+ node.range.source.normalizedPath,
88
+ );
89
+ }
90
+ const type = toString(member.type);
91
+ if (type.startsWith("(") && type.includes("=>")) continue;
92
+ const value = member.initializer ? toString(member.initializer) : null;
93
+ if (member.flags == 32 /* CommonFlags.Static */) continue;
94
+ if (member.flags === 512 /* CommonFlags.Private */) continue;
95
+ if (member.flags === 1024 /* CommonFlags.Protected */) continue;
96
+ const mem = new Property();
97
+ mem.name = name.text;
98
+ mem.type = type;
99
+ mem.value = value;
100
+ mem.node = member;
101
+ if (type == "JSON.Raw") {
102
+ mem.flags.set(PropertyFlags.JSON_Raw, []);
103
+ }
104
+ if (member.decorators) {
105
+ for (const decorator of member.decorators) {
106
+ const decoratorName = decorator.name.text;
107
+ const args = getArgs(decorator.args);
108
+ switch (decoratorName) {
109
+ case "alias": {
110
+ if (!args.length)
111
+ throw new Error(
112
+ "Expected 1 argument but got zero at @alias in " +
113
+ node.range.source.normalizedPath,
114
+ );
115
+ mem.alias = args[0];
116
+ mem.flags.set(PropertyFlags.Alias, args);
117
+ break;
118
+ }
119
+ case "omit": {
120
+ mem.flags.set(PropertyFlags.Omit, args);
121
+ break;
122
+ }
123
+ case "omitif": {
124
+ if (!decorator.args?.length)
125
+ throw new Error(
126
+ "Expected 1 argument but got zero at @omitif in " +
127
+ node.range.source.normalizedPath,
128
+ );
129
+ mem.flags.set(PropertyFlags.OmitIf, args);
130
+ break;
131
+ }
132
+ case "omitnull": {
133
+ mem.flags.set(PropertyFlags.OmitNull, args);
134
+ break;
135
+ }
136
+ }
227
137
  }
228
- if (found) {
229
- SERIALIZE_RAW += "`;\n store<u16>(changetype<usize>(out) + ((out.length - 1) << 1), 125);\n return out;\n}";
230
- SERIALIZE_PRETTY += "`;\n store<u32>(changetype<usize>(out) + ((out.length - 2) << 1), 8192010);\n return out;\n}";
138
+ }
139
+ mem.generate();
140
+ if (this.schemasList.find((v) => v.name == type)) {
141
+ mem.initialize =
142
+ "this." +
143
+ name.text +
144
+ " = changetype<nonnull<" +
145
+ mem.type +
146
+ ">>(__new(offsetof<nonnull<" +
147
+ mem.type +
148
+ ">>(), idof<nonnull<" +
149
+ mem.type +
150
+ ">>()));\n changetype<nonnull<" +
151
+ mem.type +
152
+ ">>(this." +
153
+ name.text +
154
+ ").__INITIALIZE()";
155
+ } else if (mem.value) {
156
+ mem.initialize = "this." + name.text + " = " + mem.value;
157
+ } else if (type === "Map") {
158
+ mem.initialize = "this." + name.text + " = new " + mem.type + "()";
159
+ } else if (type === "string") {
160
+ mem.initialize = "this." + name.text + ' = ""';
161
+ } else if (type === "Array") {
162
+ mem.initialize =
163
+ "this." + name.text + " = instantiate<" + mem.type + ">()";
164
+ } else if (type === "bool" || type === "boolean") {
165
+ mem.initialize = "this." + name.text + " = false";
166
+ } else if (type === "JSON.Raw") {
167
+ mem.initialize = "this." + name.text + ' = ""';
168
+ } else if (
169
+ type === "u8" ||
170
+ type === "u16" ||
171
+ type === "u32" ||
172
+ type === "u64" ||
173
+ type === "i8" ||
174
+ type === "i16" ||
175
+ type === "i32" ||
176
+ type === "i64"
177
+ ) {
178
+ mem.initialize = "this." + name.text + " = 0";
179
+ } else if (type === "f32" || type === "f64") {
180
+ mem.initialize = "this." + name.text + " = 0.0";
181
+ }
182
+ schema.members.push(mem);
183
+ }
184
+ let SERIALIZE_RAW = "__SERIALIZE(): string {\n let out = `{";
185
+ let SERIALIZE_PRETTY = "__SERIALIZE_PRETTY(): string {\n let out = `{";
186
+ let INITIALIZE = "__INITIALIZE(): this {\n";
187
+ let DESERIALIZE =
188
+ "__DESERIALIZE(data: string, key_start: i32, key_end: i32, value_start: i32, value_end: i32): boolean {\n const len = key_end - key_start;\n";
189
+ let indent = " ";
190
+ if (!schema.members.length) return;
191
+ found = false;
192
+ if (
193
+ schema.members[0]?.flags.has(PropertyFlags.OmitNull) ||
194
+ schema.members[0]?.flags.has(PropertyFlags.OmitIf)
195
+ ) {
196
+ SERIALIZE_RAW += schema.members[0]?.serialize;
197
+ SERIALIZE_PRETTY += "\\n" + schema.members[0]?.serialize;
198
+ } else {
199
+ SERIALIZE_RAW += schema.members[0]?.serialize + ",";
200
+ SERIALIZE_PRETTY += "\\n" + schema.members[0]?.serialize + ",\\n";
201
+ found = true;
202
+ }
203
+ if (schema.members[0]?.initialize)
204
+ INITIALIZE += " " + schema.members[0]?.initialize + ";\n";
205
+ for (let i = 1; i < schema.members.length; i++) {
206
+ const member = schema.members[i];
207
+ if (member.initialize) INITIALIZE += " " + member.initialize + ";\n";
208
+ if (
209
+ member.flags.has(PropertyFlags.OmitNull) ||
210
+ member.flags.has(PropertyFlags.OmitIf)
211
+ ) {
212
+ SERIALIZE_RAW += member.serialize;
213
+ SERIALIZE_PRETTY += member.serialize;
214
+ } else {
215
+ SERIALIZE_RAW += member.serialize + ",";
216
+ SERIALIZE_PRETTY += indent + member.serialize + ",\\n";
217
+ found = true;
218
+ }
219
+ }
220
+ if (found) {
221
+ SERIALIZE_RAW +=
222
+ "`;\n store<u16>(changetype<usize>(out) + ((out.length - 1) << 1), 125);\n return out;\n}";
223
+ SERIALIZE_PRETTY +=
224
+ "`;\n store<u32>(changetype<usize>(out) + ((out.length - 2) << 1), 8192010);\n return out;\n}";
225
+ } else {
226
+ SERIALIZE_RAW += "`;\n};";
227
+ SERIALIZE_PRETTY += "`;\n};";
228
+ }
229
+ INITIALIZE += " return this;\n}";
230
+ const sortedMembers = [];
231
+ const _sorted = schema.members.sort(
232
+ (a, b) => a.name.length - b.name.length,
233
+ );
234
+ let len = 0;
235
+ let offset = 0;
236
+ sortedMembers.push([_sorted[0]]);
237
+ len = _sorted[0]?.name.length;
238
+ for (let i = 1; i < _sorted.length; i++) {
239
+ const member = _sorted[i];
240
+ if (member.alias?.length || member.name.length > len) {
241
+ sortedMembers.push([member]);
242
+ len = member.alias?.length || member.name.length;
243
+ offset++;
244
+ } else {
245
+ sortedMembers[offset].push(member);
246
+ }
247
+ }
248
+ let first = true;
249
+ for (const memberSet of sortedMembers) {
250
+ const firstMember = memberSet[0];
251
+ const name = encodeKey(firstMember.alias || firstMember.name);
252
+ if (name.length === 1) {
253
+ if (first) {
254
+ DESERIALIZE +=
255
+ " if (1 === len) {\n switch (load<u16>(changetype<usize>(data) + (key_start << 1))) {\n";
256
+ first = false;
257
+ } else {
258
+ DESERIALIZE +=
259
+ "else if (1 === len) {\n switch (load<u16>(changetype<usize>(data) + (key_start << 1))) {\n";
231
260
  }
232
- else {
233
- SERIALIZE_RAW += "`;\n};";
234
- SERIALIZE_PRETTY += "`;\n};";
261
+ } else if (name.length === 2) {
262
+ if (first) {
263
+ DESERIALIZE +=
264
+ " if (2 === len) {\n switch (load<u32>(changetype<usize>(data) + (key_start << 1))) {\n";
265
+ first = false;
266
+ } else {
267
+ DESERIALIZE +=
268
+ "else if (2 === len) {\n switch (load<u32>(changetype<usize>(data) + (key_start << 1))) {\n";
235
269
  }
236
- INITIALIZE += " return this;\n}";
237
- const sortedMembers = [];
238
- const _sorted = schema.members.sort((a, b) => a.name.length - b.name.length);
239
- let len = 0;
240
- let offset = 0;
241
- sortedMembers.push([_sorted[0]]);
242
- len = _sorted[0]?.name.length;
243
- for (let i = 1; i < _sorted.length; i++) {
244
- const member = _sorted[i];
245
- if (member.alias?.length || member.name.length > len) {
246
- sortedMembers.push([member]);
247
- len = member.alias?.length || member.name.length;
248
- offset++;
249
- }
250
- else {
251
- sortedMembers[offset].push(member);
252
- }
270
+ } else if (name.length === 4) {
271
+ if (first) {
272
+ DESERIALIZE +=
273
+ " if (4 === len) {\n const code = load<u64>(changetype<usize>(data) + (key_start << 1));\n";
274
+ first = false;
275
+ } else {
276
+ DESERIALIZE +=
277
+ "else if (4 === len) {\n const code = load<u64>(changetype<usize>(data) + (key_start << 1));\n";
253
278
  }
254
- let first = true;
255
- for (const memberSet of sortedMembers) {
256
- const firstMember = memberSet[0];
257
- const name = encodeKey(firstMember.alias || firstMember.name);
258
- if (name.length === 1) {
259
- if (first) {
260
- DESERIALIZE += " if (1 === len) {\n switch (load<u16>(changetype<usize>(data) + (key_start << 1))) {\n";
261
- first = false;
262
- }
263
- else {
264
- DESERIALIZE += "else if (1 === len) {\n switch (load<u16>(changetype<usize>(data) + (key_start << 1))) {\n";
265
- }
266
- }
267
- else if (name.length === 2) {
268
- if (first) {
269
- DESERIALIZE += " if (2 === len) {\n switch (load<u32>(changetype<usize>(data) + (key_start << 1))) {\n";
270
- first = false;
271
- }
272
- else {
273
- DESERIALIZE += "else if (2 === len) {\n switch (load<u32>(changetype<usize>(data) + (key_start << 1))) {\n";
274
- }
275
- }
276
- else if (name.length === 4) {
277
- if (first) {
278
- DESERIALIZE += " if (4 === len) {\n const code = load<u64>(changetype<usize>(data) + (key_start << 1));\n";
279
- first = false;
280
- }
281
- else {
282
- DESERIALIZE += "else if (4 === len) {\n const code = load<u64>(changetype<usize>(data) + (key_start << 1));\n";
283
- }
284
- }
285
- else {
286
- if (first) {
287
- DESERIALIZE += " if (" + name.length + " === len) {\n";
288
- first = false;
289
- }
290
- else {
291
- DESERIALIZE += "else if (" + name.length + " === len) {\n";
292
- }
293
- }
294
- let f = true;
295
- for (let i = 0; i < memberSet.length; i++) {
296
- const member = memberSet[i];
297
- if (!member.deserialize)
298
- continue;
299
- const name = encodeKey(member.alias || member.name);
300
- if (name.length === 1) {
301
- DESERIALIZE += ` case ${name.charCodeAt(0)}: {\n ${member.deserialize}\n return true;\n }\n`;
302
- }
303
- else if (name.length === 2) {
304
- DESERIALIZE += ` case ${charCodeAt32(name, 0)}: {\n ${member.deserialize}\n return true;\n }\n`;
305
- }
306
- else if (name.length === 4) {
307
- if (f) {
308
- f = false;
309
- DESERIALIZE += ` if (${charCodeAt64(name, 0)} === code) {\n ${member.deserialize}\n return true;\n }\n`;
310
- }
311
- else {
312
- DESERIALIZE = DESERIALIZE.slice(0, DESERIALIZE.length - 1) + `else if (${charCodeAt64(name, 0)} === code) {\n ${member.deserialize}\n return true;\n }\n`;
313
- }
314
- }
315
- else {
316
- if (f) {
317
- f = false;
318
- DESERIALIZE += ` if (0 == memory.compare(changetype<usize>("${escapeQuote(escapeSlash(name))}"), changetype<usize>(data) + (key_start << 1), ${name.length << 1})) {\n ${member.deserialize}\n return true;\n }\n`;
319
- }
320
- else {
321
- DESERIALIZE = DESERIALIZE.slice(0, DESERIALIZE.length - 1) + ` else if (0 == memory.compare(changetype<usize>("${escapeQuote(escapeSlash(name))}"), changetype<usize>(data) + (key_start << 1), ${name.length << 1})) {\n ${member.deserialize}\n return true;\n }\n`;
322
- }
323
- }
324
- }
325
- if (name.length < 3) {
326
- DESERIALIZE += ` default: {\n return false;\n }\n }\n`;
327
- }
328
- else if (name.length == 4) {
329
- DESERIALIZE = DESERIALIZE.slice(0, DESERIALIZE.length - 1) + ` else {\n return false;\n }\n`;
330
- }
331
- else {
332
- DESERIALIZE = DESERIALIZE.slice(0, DESERIALIZE.length - 1) + ` else {\n return false;\n }\n`;
333
- }
334
- DESERIALIZE += " } ";
279
+ } else {
280
+ if (first) {
281
+ DESERIALIZE += " if (" + name.length + " === len) {\n";
282
+ first = false;
283
+ } else {
284
+ DESERIALIZE += "else if (" + name.length + " === len) {\n";
335
285
  }
336
- DESERIALIZE += "\n return false;\n}";
337
- //console.log(sortedMembers);
338
- if (process.env["JSON_DEBUG"]) {
339
- console.log(SERIALIZE_RAW);
340
- //console.log(SERIALIZE_PRETTY);
341
- console.log(INITIALIZE);
342
- console.log(DESERIALIZE);
286
+ }
287
+ let f = true;
288
+ for (let i = 0; i < memberSet.length; i++) {
289
+ const member = memberSet[i];
290
+ if (!member.deserialize) continue;
291
+ const name = encodeKey(member.alias || member.name);
292
+ if (name.length === 1) {
293
+ DESERIALIZE += ` case ${name.charCodeAt(0)}: {\n ${member.deserialize}\n return true;\n }\n`;
294
+ } else if (name.length === 2) {
295
+ DESERIALIZE += ` case ${charCodeAt32(name, 0)}: {\n ${member.deserialize}\n return true;\n }\n`;
296
+ } else if (name.length === 4) {
297
+ if (f) {
298
+ f = false;
299
+ DESERIALIZE += ` if (${charCodeAt64(name, 0)} === code) {\n ${member.deserialize}\n return true;\n }\n`;
300
+ } else {
301
+ DESERIALIZE =
302
+ DESERIALIZE.slice(0, DESERIALIZE.length - 1) +
303
+ `else if (${charCodeAt64(name, 0)} === code) {\n ${member.deserialize}\n return true;\n }\n`;
304
+ }
305
+ } else {
306
+ if (f) {
307
+ f = false;
308
+ DESERIALIZE += ` if (0 == memory.compare(changetype<usize>("${escapeQuote(escapeSlash(name))}"), changetype<usize>(data) + (key_start << 1), ${name.length << 1})) {\n ${member.deserialize}\n return true;\n }\n`;
309
+ } else {
310
+ DESERIALIZE =
311
+ DESERIALIZE.slice(0, DESERIALIZE.length - 1) +
312
+ ` else if (0 == memory.compare(changetype<usize>("${escapeQuote(escapeSlash(name))}"), changetype<usize>(data) + (key_start << 1), ${name.length << 1})) {\n ${member.deserialize}\n return true;\n }\n`;
313
+ }
343
314
  }
344
- const SERIALIZE_RAW_METHOD = SimpleParser.parseClassMember(SERIALIZE_RAW, node);
345
- //const SERIALIZE_PRETTY_METHOD = SimpleParser.parseClassMember(SERIALIZE_PRETTY, node);
346
- const INITIALIZE_METHOD = SimpleParser.parseClassMember(INITIALIZE, node);
347
- const DESERIALIZE_METHOD = SimpleParser.parseClassMember(DESERIALIZE, node);
348
- if (!node.members.find(v => v.name.text == "__SERIALIZE"))
349
- node.members.push(SERIALIZE_RAW_METHOD);
350
- if (!node.members.find(v => v.name.text == "__INITIALIZE"))
351
- node.members.push(INITIALIZE_METHOD);
352
- if (!node.members.find(v => v.name.text == "__DESERIALIZE"))
353
- node.members.push(DESERIALIZE_METHOD);
354
- this.schemasList.push(schema);
315
+ }
316
+ if (name.length < 3) {
317
+ DESERIALIZE += ` default: {\n return false;\n }\n }\n`;
318
+ } else if (name.length == 4) {
319
+ DESERIALIZE =
320
+ DESERIALIZE.slice(0, DESERIALIZE.length - 1) +
321
+ ` else {\n return false;\n }\n`;
322
+ } else {
323
+ DESERIALIZE =
324
+ DESERIALIZE.slice(0, DESERIALIZE.length - 1) +
325
+ ` else {\n return false;\n }\n`;
326
+ }
327
+ DESERIALIZE += " } ";
355
328
  }
356
- visitSource(node) {
357
- super.visitSource(node);
358
- // Only add the import statement to sources that have JSON decorated classes.
359
- if (!this.sources.has(node)) {
360
- return;
361
- }
329
+ DESERIALIZE += "\n return false;\n}";
330
+ //console.log(sortedMembers);
331
+ if (process.env["JSON_DEBUG"]) {
332
+ console.log(SERIALIZE_RAW);
333
+ //console.log(SERIALIZE_PRETTY);
334
+ console.log(INITIALIZE);
335
+ console.log(DESERIALIZE);
362
336
  }
337
+ const SERIALIZE_RAW_METHOD = SimpleParser.parseClassMember(
338
+ SERIALIZE_RAW,
339
+ node,
340
+ );
341
+ //const SERIALIZE_PRETTY_METHOD = SimpleParser.parseClassMember(SERIALIZE_PRETTY, node);
342
+ const INITIALIZE_METHOD = SimpleParser.parseClassMember(INITIALIZE, node);
343
+ const DESERIALIZE_METHOD = SimpleParser.parseClassMember(DESERIALIZE, node);
344
+ if (!node.members.find((v) => v.name.text == "__SERIALIZE"))
345
+ node.members.push(SERIALIZE_RAW_METHOD);
346
+ if (!node.members.find((v) => v.name.text == "__INITIALIZE"))
347
+ node.members.push(INITIALIZE_METHOD);
348
+ if (!node.members.find((v) => v.name.text == "__DESERIALIZE"))
349
+ node.members.push(DESERIALIZE_METHOD);
350
+ this.schemasList.push(schema);
351
+ }
352
+ visitSource(node) {
353
+ super.visitSource(node);
354
+ // Only add the import statement to sources that have JSON decorated classes.
355
+ if (!this.sources.has(node)) {
356
+ return;
357
+ }
358
+ }
363
359
  }
364
360
  export default class Transformer extends Transform {
365
- // Trigger the transform after parse.
366
- afterParse(parser) {
367
- // Create new transform
368
- const transformer = new JSONTransform();
369
- // Sort the sources so that user scripts are visited last
370
- const sources = parser.sources
371
- .filter((source) => !isStdlib(source))
372
- .sort((_a, _b) => {
373
- const a = _a.internalPath;
374
- const b = _b.internalPath;
375
- if (a[0] === "~" && b[0] !== "~") {
376
- return -1;
377
- }
378
- else if (a[0] !== "~" && b[0] === "~") {
379
- return 1;
380
- }
381
- else {
382
- return 0;
383
- }
384
- });
385
- // Loop over every source
386
- for (const source of sources) {
387
- // Ignore all lib and std. Visit everything else.
388
- if (!isStdlib(source)) {
389
- transformer.visit(source);
390
- }
391
- }
392
- // Check that every parent and child class is hooked up correctly
393
- const schemas = transformer.schemasList;
394
- for (const schema of schemas) {
395
- if (schema.parent) {
396
- const parent = schemas.find((v) => v.name === schema.parent?.name);
397
- if (!parent)
398
- throw new Error(`Class ${schema.name} extends its parent class ${schema.parent}, but ${schema.parent} does not include a @json or @serializable decorator! Add the decorator and rebuild.`);
399
- }
361
+ // Trigger the transform after parse.
362
+ afterParse(parser) {
363
+ // Create new transform
364
+ const transformer = new JSONTransform();
365
+ // Sort the sources so that user scripts are visited last
366
+ const sources = parser.sources
367
+ .filter((source) => !isStdlib(source))
368
+ .sort((_a, _b) => {
369
+ const a = _a.internalPath;
370
+ const b = _b.internalPath;
371
+ if (a[0] === "~" && b[0] !== "~") {
372
+ return -1;
373
+ } else if (a[0] !== "~" && b[0] === "~") {
374
+ return 1;
375
+ } else {
376
+ return 0;
400
377
  }
378
+ });
379
+ // Loop over every source
380
+ for (const source of sources) {
381
+ // Ignore all lib and std. Visit everything else.
382
+ if (!isStdlib(source)) {
383
+ transformer.visit(source);
384
+ }
401
385
  }
386
+ // Check that every parent and child class is hooked up correctly
387
+ const schemas = transformer.schemasList;
388
+ for (const schema of schemas) {
389
+ if (schema.parent) {
390
+ const parent = schemas.find((v) => v.name === schema.parent?.name);
391
+ if (!parent)
392
+ throw new Error(
393
+ `Class ${schema.name} extends its parent class ${schema.parent}, but ${schema.parent} does not include a @json or @serializable decorator! Add the decorator and rebuild.`,
394
+ );
395
+ }
396
+ }
397
+ }
402
398
  }
403
399
  var PropertyFlags;
404
400
  (function (PropertyFlags) {
405
- PropertyFlags[PropertyFlags["None"] = 0] = "None";
406
- PropertyFlags[PropertyFlags["Omit"] = 1] = "Omit";
407
- PropertyFlags[PropertyFlags["OmitNull"] = 2] = "OmitNull";
408
- PropertyFlags[PropertyFlags["OmitIf"] = 3] = "OmitIf";
409
- PropertyFlags[PropertyFlags["Alias"] = 4] = "Alias";
410
- PropertyFlags[PropertyFlags["Flatten"] = 5] = "Flatten";
401
+ PropertyFlags[(PropertyFlags["Omit"] = 0)] = "Omit";
402
+ PropertyFlags[(PropertyFlags["OmitNull"] = 1)] = "OmitNull";
403
+ PropertyFlags[(PropertyFlags["OmitIf"] = 2)] = "OmitIf";
404
+ PropertyFlags[(PropertyFlags["Alias"] = 3)] = "Alias";
405
+ PropertyFlags[(PropertyFlags["JSON_Raw"] = 4)] = "JSON_Raw";
411
406
  })(PropertyFlags || (PropertyFlags = {}));
412
407
  class Property {
413
- constructor() {
414
- this.name = "";
415
- this.alias = null;
416
- this.type = "";
417
- this.value = null;
418
- this.flags = [];
419
- this.args = [];
420
- this.serialize = null;
421
- this.deserialize = null;
422
- this.initialize = null;
408
+ constructor() {
409
+ this.name = "";
410
+ this.alias = null;
411
+ this.type = "";
412
+ this.value = null;
413
+ this.flags = new Map();
414
+ this.serialize = null;
415
+ this.deserialize = null;
416
+ this.initialize = null;
417
+ this.right_s = "";
418
+ this.right_d = "";
419
+ }
420
+ generate() {
421
+ const name = this.name;
422
+ const escapedName = escapeString(JSON.stringify(this.alias || this.name));
423
+ const type = this.type;
424
+ if (this.flags.has(PropertyFlags.Omit)) return;
425
+ if (this.flags.has(PropertyFlags.JSON_Raw)) {
426
+ this.right_s = "this." + name;
427
+ this.right_d = "data.substring(value_start, value_end);";
428
+ } else {
429
+ this.right_s = "__SERIALIZE<" + type + ">(this." + name + ")";
430
+ this.right_d =
431
+ "__DESERIALIZE<" + type + ">(data.substring(value_start, value_end))";
432
+ }
433
+ if (this.flags.has(PropertyFlags.OmitIf)) {
434
+ const condition = this.flags.get(PropertyFlags.OmitIf)[0];
435
+ if (!condition)
436
+ throw new Error(
437
+ "Could not find condition when using decorator @omitif! Provide at least one condition",
438
+ );
439
+ this.serialize =
440
+ "${" +
441
+ condition +
442
+ ' ? "" : \'' +
443
+ escapedName +
444
+ ":' + " +
445
+ this.right_s +
446
+ ' + ","}';
447
+ this.deserialize = "this." + name + " = " + this.right_d + ";";
448
+ } else if (this.flags.has(PropertyFlags.OmitNull)) {
449
+ this.serialize =
450
+ "${changetype<usize>(this." +
451
+ name +
452
+ ") == <usize>0" +
453
+ ' ? "" : \'' +
454
+ escapedName +
455
+ ":' + " +
456
+ this.right_s +
457
+ ' + ","}';
458
+ this.deserialize = "this." + name + " = " + this.right_d + ";";
459
+ } else {
460
+ this.serialize = escapedName + ":${" + this.right_s + "}";
461
+ this.deserialize = "this." + name + " = " + this.right_d + ";";
423
462
  }
463
+ }
424
464
  }
425
465
  class SchemaData {
426
- constructor() {
427
- this.name = "";
428
- this.members = [];
429
- this.parent = null;
430
- }
466
+ constructor() {
467
+ this.name = "";
468
+ this.members = [];
469
+ this.parent = null;
470
+ }
431
471
  }
432
472
  function charCodeAt32(data, offset) {
433
- return (data.charCodeAt(offset + 1) << 16) | data.charCodeAt(offset);
473
+ return (data.charCodeAt(offset + 1) << 16) | data.charCodeAt(offset);
434
474
  }
435
475
  function charCodeAt64(data, offset) {
436
- if (offset + 3 >= data.length) {
437
- throw new Error("The string must have at least 4 characters from the specified offset.");
438
- }
439
- const firstCharCode = BigInt(data.charCodeAt(offset));
440
- const secondCharCode = BigInt(data.charCodeAt(offset + 1));
441
- const thirdCharCode = BigInt(data.charCodeAt(offset + 2));
442
- const fourthCharCode = BigInt(data.charCodeAt(offset + 3));
443
- const u64Value = (fourthCharCode << 48n) | (thirdCharCode << 32n) | (secondCharCode << 16n) | firstCharCode;
444
- return u64Value;
476
+ if (offset + 3 >= data.length) {
477
+ throw new Error(
478
+ "The string must have at least 4 characters from the specified offset.",
479
+ );
480
+ }
481
+ const firstCharCode = BigInt(data.charCodeAt(offset));
482
+ const secondCharCode = BigInt(data.charCodeAt(offset + 1));
483
+ const thirdCharCode = BigInt(data.charCodeAt(offset + 2));
484
+ const fourthCharCode = BigInt(data.charCodeAt(offset + 3));
485
+ const u64Value =
486
+ (fourthCharCode << 48n) |
487
+ (thirdCharCode << 32n) |
488
+ (secondCharCode << 16n) |
489
+ firstCharCode;
490
+ return u64Value;
445
491
  }
446
492
  function encodeKey(key) {
447
- const data = JSON.stringify(key);
448
- return data.slice(1, data.length - 1);
493
+ const data = JSON.stringify(key);
494
+ return data.slice(1, data.length - 1);
449
495
  }
450
496
  function escapeString(data) {
451
- return data.replace(/\\/g, "\\\\")
452
- .replace(/\`/g, '\\`');
497
+ return data.replace(/\\/g, "\\\\").replace(/\`/g, "\\`");
453
498
  }
454
499
  function escapeSlash(data) {
455
- return data.replace(/\\/g, "\\\\")
456
- .replace(/\`/g, '\\`');
500
+ return data.replace(/\\/g, "\\\\").replace(/\`/g, "\\`");
457
501
  }
458
502
  function escapeQuote(data) {
459
- return data.replace(/\"/g, "\\\"");
503
+ return data.replace(/\"/g, '\\"');
504
+ }
505
+ function getArgs(args) {
506
+ if (!args) return [];
507
+ let out = [];
508
+ for (const arg of args) {
509
+ out.push(toString(arg));
510
+ }
511
+ return out;
460
512
  }