json-as 0.5.39 → 0.5.42

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/asconfig.json CHANGED
@@ -11,8 +11,5 @@
11
11
  },
12
12
  "options": {
13
13
  "transform": ["./transform"],
14
- "bindings": "esm",
15
- "exportStart": "_start"
16
- },
17
- "extends": "./node_modules/@assemblyscript/wasi-shim/asconfig.json"
14
+ "bindings": "esm"}
18
15
  }
@@ -33,13 +33,24 @@ class Player {
33
33
  isVerified: boolean;
34
34
  }
35
35
 
36
- class Nullable {}
36
+ class Nullable { }
37
37
  type Null = Nullable | null;
38
38
 
39
39
  describe("Ser/de Nulls", () => {
40
40
  canSerde<Null>(null);
41
41
  });
42
42
 
43
+ describe("Ser/de Strings", () => {
44
+ it("should ser/de strings", () => {
45
+ canSerde<string>("abcdefg");
46
+ canSerde<string>('st"ring" w""ith quotes"');
47
+ canSerde<string>('string \"with random spa\nces and \nnewlines\n\n\n');
48
+ canSerde<string>(
49
+ 'string with colon : comma , brace [ ] bracket { } and quote " and other quote \\"'
50
+ );
51
+ });
52
+ });
53
+
43
54
  describe("Ser/de Numbers", () => {
44
55
  it("should ser/de integers", () => {
45
56
  canSerde<i32>(0);
@@ -48,34 +59,6 @@ describe("Ser/de Numbers", () => {
48
59
  canSerde<u64>(101);
49
60
  canSerde<i32>(-100);
50
61
  canSerde<i64>(-101);
51
-
52
- // canSerde<u128>(u128.from("0"))
53
- // canSerde<u128>(u128.from("100"))
54
- // canSerde<u128>(u128.from("101"))
55
-
56
- /* canSerde<u128Safe>(u128Safe.from("0"))
57
- canSerde<u128Safe>(u128Safe.from("100"))
58
- canSerde<u128Safe>(u128Safe.from("101"))
59
-
60
- canSerde<u256>(u256.fromU128(u128.from("0")))
61
- canSerde<u256>(u256.fromU128(u128.from("100")))
62
- canSerde<u256>(u256.fromU128(u128.from("101")))
63
-
64
- canSerde<u256Safe>(u256Safe.fromU128(u128.from("0")))
65
- canSerde<u256Safe>(u256Safe.fromU128(u128.from("100")))
66
- canSerde<u256Safe>(u256Safe.fromU128(u128.from("101")))
67
-
68
- canSerde<i128>(i128.from("0"))
69
- canSerde<i128>(i128.from("100"))
70
- canSerde<i128>(i128.from("101"))
71
-
72
- canSerde<i128Safe>(i128Safe.from("0"))
73
- canSerde<i128Safe>(i128Safe.from("100"))
74
- canSerde<i128Safe>(i128Safe.from("101"))
75
- canSerde<i128Safe>(i128Safe.from("-100"))
76
- canSerde<i128Safe>(i128Safe.from("-101"))
77
- */
78
- //canSerde<i256Safe>(new i256Safe(10, 11, 500, 501))
79
62
  });
80
63
 
81
64
  it("should ser/de floats", () => {
@@ -98,30 +81,13 @@ describe("Ser/de Numbers", () => {
98
81
  canSerde<boolean>(false);
99
82
  });
100
83
 
101
- it("should ser/de strings", () => {
102
- canSerde<string>("abcdefg");
103
- canSerde<string>('st"ring" w""ith quotes"');
104
- canSerde<string>(
105
- 'string \t\r\\"with ran\tdom spa\nces and \nnewlines\n\n\n'
106
- );
107
- canSerde<string>(
108
- 'string with colon : comma , brace [ ] bracket { } and quote " and other quote \\"'
109
- );
110
- });
111
-
112
84
  it("should ser/de BigInt objects", () => {
113
- /* canSerde<i32>(0);
85
+ canSerde<i32>(0);
114
86
 
115
87
  canSerde<u32>(100);
116
88
  canSerde<u64>(101);
117
89
  canSerde<i32>(-100);
118
90
  canSerde<i64>(-101);
119
- canSerde<u128>(u128.from("0"))
120
- canSerde<u128>(u128.from("100"))
121
- canSerde<u128>(u128.from("101"))
122
- canSerde<u128>(u128.from("-100"))
123
- canSerde<u128>(u128.from("-101"))
124
- */
125
91
  });
126
92
  });
127
93
 
@@ -144,13 +110,7 @@ describe("Ser/de Array", () => {
144
110
  });
145
111
 
146
112
  it("should ser/de string arrays", () => {
147
- // ["abcdefg","st\\"ring\\" w\\"\\"ith quotes\\"","string \\t\\r\\"with ran\\tdom spa\\nces and \\nnewlines\\n\\n\\n","string with colon : comma , brace [ ] bracket { } and quote \\" and other quote \\""]
148
- canSerde<string[]>([
149
- "abcdefg",
150
- 'st"ring" w""ith quotes"',
151
- 'string \t\r"with ran\tdom spa\nces and \nnewlines\n\n\n',
152
- 'string with colon : comma , brace [ ] bracket { } and quote " and other quote "',
153
- ]);
113
+ canSerde<string[]>(['string \"with random spa\nces and \nnewlines\n\n\n']);
154
114
  });
155
115
 
156
116
  it("should ser/de nested integer arrays", () => {
@@ -174,17 +134,6 @@ describe("Ser/de Array", () => {
174
134
  canSerde<boolean[][]>([[true], [false]]);
175
135
  });
176
136
 
177
- it("should ser/de string arrays", () => {
178
- canSerde<string[][]>([
179
- ["abcdefg"],
180
- ['st"ring" w""ith quotes"'],
181
- ['string \t\r\\"with ran\tdom spa\nces and \nnewlines\n\n\n'],
182
- [
183
- 'string with colon : comma , brace [ ] bracket { } and quote " and other quote \\"',
184
- ],
185
- ]);
186
- });
187
-
188
137
  it("should ser/de object arrays", () => {
189
138
  canSerde<Vec3[]>([
190
139
  {
@@ -272,10 +272,10 @@ export namespace JSON {
272
272
  if (char === 34 || char === 92) {
273
273
  result += (<string>data).slice(last, i) + "\\";
274
274
  last = i;
275
- i++;
275
+ //i++;
276
276
  } else if (char <= 13 && char >= 8) {
277
277
  result += (<string>data).slice(last, i);
278
- last = ++i;
278
+ last = i + 1;
279
279
  switch (char) {
280
280
  case 8: {
281
281
  result += "\\b";
@@ -322,40 +322,37 @@ export namespace JSON {
322
322
  result += data.slice(last, i - 1);
323
323
  if (char === 34) {
324
324
  result += '"';
325
- last = ++i;
326
- } else if (char === 110) {
327
- result += "\n";
328
- last = ++i;
329
- // 92 98 114 116 102 117
325
+ last = i + 1;
330
326
  } else if (char >= 92 && char <= 117) {
331
327
  switch (char) {
332
328
  case 92: {
333
329
  result += "\\";
334
- last = ++i;
330
+ last = i + 1;
335
331
  break;
336
332
  }
337
333
  case 98: {
338
334
  result += "\b";
339
- last = ++i;
335
+ last = i + 1;
340
336
  break;
341
337
  }
342
- case 110: {
343
- result += "\n";
344
- last = ++i;
345
- }
346
338
  case 102: {
347
339
  result += "\f";
348
- last = ++i;
340
+ last = i + 1;
341
+ break;
342
+ }
343
+ case 110: {
344
+ result += "\n";
345
+ last = i + 1;
349
346
  break;
350
347
  }
351
348
  case 114: {
352
349
  result += "\r";
353
- last = ++i;
350
+ last = i + 1;
354
351
  break;
355
352
  }
356
353
  case 116: {
357
354
  result += "\t";
358
- last = ++i;
355
+ last = i + 1;
359
356
  break;
360
357
  }
361
358
  default: {
@@ -366,7 +363,7 @@ export namespace JSON {
366
363
  ) {
367
364
  result += "\u000b";
368
365
  i += 4;
369
- last = ++i;
366
+ last = i + 1;
370
367
  }
371
368
  break;
372
369
  }
@@ -579,7 +576,7 @@ export namespace JSON {
579
576
  lastPos = i;
580
577
  } else if (unsafeCharCodeAt(data, i - 1) !== backSlashCode) {
581
578
  instr = false;
582
- result.push(data.slice(lastPos + 1, i).replaceAll('\\"', '"'));
579
+ result.push(parseString(data.slice(lastPos, i)));
583
580
  }
584
581
  }
585
582
  }
@@ -89,13 +89,28 @@ export function getArrayDepth<T>(depth: i32 = 1): i32 {
89
89
  export function atoi_fast<T extends number>(str: string, offset: i32 = 0): T {
90
90
  // @ts-ignore
91
91
  let val: T = 0;
92
- for (; offset < str.length << 1; offset += 2) {
92
+ let firstChar = load<u16>(changetype<usize>(str) + <usize>offset);
93
+ if (firstChar === 45) {
94
+ offset += 2;
95
+ for (; offset < str.length << 1; offset += 2) {
96
+ // @ts-ignore
97
+ val =
98
+ (val << 1) +
99
+ (val << 3) +
100
+ (load<u16>(changetype<usize>(str) + <usize>offset) - 48);
101
+ // We use load because in this case, there is no need to have bounds-checking
102
+ }
93
103
  // @ts-ignore
94
- val =
95
- (val << 1) +
96
- (val << 3) +
97
- (load<u16>(changetype<usize>(str) + <usize>offset) - 48);
98
- // We use load because in this case, there is no need to have bounds-checking
104
+ val = -val;
105
+ } else {
106
+ for (; offset < str.length << 1; offset += 2) {
107
+ // @ts-ignore
108
+ val =
109
+ (val << 1) +
110
+ (val << 3) +
111
+ (load<u16>(changetype<usize>(str) + <usize>offset) - 48);
112
+ // We use load because in this case, there is no need to have bounds-checking
113
+ }
99
114
  }
100
115
  return val;
101
116
  }
@@ -114,6 +129,10 @@ export function parseSciInteger<T extends number>(str: string): T {
114
129
  // @ts-ignore
115
130
  let val: T = 0;
116
131
  let offset = 0;
132
+ let firstChar = load<u16>(changetype<usize>(str) + <usize>offset);
133
+ if (firstChar === 45) {
134
+ offset = 2;
135
+ }
117
136
  for (; offset < str.length << 1; offset += 2) {
118
137
  const char = load<u16>(changetype<usize>(str) + <usize>offset);
119
138
  if (char === 101 || char === 69) {
@@ -134,6 +153,9 @@ export function parseSciInteger<T extends number>(str: string): T {
134
153
  val = (val << 1) + (val << 3) + (char - 48);
135
154
  // We use load because in this case, there is no need to have bounds-checking
136
155
  }
156
+ if (firstChar === 45) {
157
+ val = -val;
158
+ }
137
159
  return val;
138
160
  }
139
161
 
@@ -141,15 +163,16 @@ export function parseSciInteger<T extends number>(str: string): T {
141
163
  @inline
142
164
  function sciNote<T extends number>(num: T): T {
143
165
  let res = 1;
144
- if (num > 0) {
145
- for (let i = 0; i < num; i++) {
146
- res *= 10;
147
- }
148
- } else {
149
- for (let i = 0; i < num; i++) {
150
- res /= 10;
166
+ // @ts-ignore
167
+ if (num > 0) {
168
+ for (let i: T = 0; i < num; i++) {
169
+ res *= 10;
170
+ }
171
+ } else {
172
+ for (let i: T = 0; i < num; i++) {
173
+ res /= 10;
174
+ }
151
175
  }
152
- }
153
176
  // @ts-ignore
154
177
  return res;
155
- }
178
+ }
package/assembly/test.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { JSON } from "./src/json";
2
2
  import { atoi_fast, parseSciInteger } from "./src/util";
3
3
  import * as a from "util/number";
4
+ // "st\"ring\" w\"\"ith quotes\""
5
+
4
6
  @json
5
7
  class Vec3 {
6
8
  x!: f32;
@@ -53,8 +55,38 @@ console.log("123 - " + parseSciInteger<i32>("123").toString());
53
55
  console.log("1230 - " + parseSciInteger<i32>("123e1").toString());
54
56
  console.log("12300 - " + parseSciInteger<i32>("123e2").toString());
55
57
  console.log("123000 - " + parseSciInteger<i32>("123e3").toString());
56
- console.log("32 - " + parseSciInteger<i32>("123e-1").toString());
58
+ console.log("12 - " + parseSciInteger<i32>("123e-1").toString());
59
+ console.log(parseSciInteger<i32>("100").toString());
60
+ console.log(parseSciInteger<i32>("-100").toString());
57
61
 
62
+ console.log(JSON.stringify("abcdefg"));
63
+ console.log('"abcdefg"')
64
+ console.log(JSON.stringify('st"ring" w""ith quotes"'));
65
+ console.log('"st\\"ring\\" w\\"\\"ith quotes\\""')
66
+ console.log(JSON.stringify(['string "with random spa\nces and \nnewlines\n\n\n']));
67
+ console.log(JSON.stringify(JSON.parse<string[]>(JSON.stringify(['string "with random spa\nces and \nnewlines\n\n\n']))));
68
+ console.log('"string \\"with random spa\\nces and \\nnewlines\\n\\n\\n"')
69
+ console.log(JSON.stringify('string with colon : comma , brace [ ] bracket { } and quote " and other quote "'));
70
+ /*console.log(JSON.stringify(JSON.parse<string[]>(JSON.stringify([
71
+ "abcdefg",
72
+ 'st"ring" w""ith quotes"',
73
+ 'string \t\r"with ran\tdom spa\nces and \nnewlines\n\n\n',
74
+ 'string with colon : comma , brace [ ] bracket { } and quote " and other quote "',
75
+ ]))));
76
+ console.log('["abcdefg","st\"ring\" w\"\"ith quotes\"","string \t\r\"with ran\tdom spa\nces and \nnewlines\n\n\n","string with colon : comma , brace [ ] bracket { } and quote \" and other quote \""]');/*
77
+ console.log(
78
+ JSON.stringify(
79
+ JSON.parse<string[]>(
80
+ JSON.stringify([
81
+ "abcdefg",
82
+ 'st"ring" w""ith quotes"',
83
+ 'string \t\r"with ran\tdom spa\nces and \nnewlines\n\n\n',
84
+ 'string with colon : comma , brace [ ] bracket { } and quote " and other quote "',
85
+ ])
86
+ )
87
+ )
88
+ );
89
+ /*
58
90
  const str = changetype<string>(new ArrayBuffer(6));
59
91
  console.log("istr:");
60
92
  console.log("123 - " + istr8(123));
@@ -244,3 +276,4 @@ export function istr64<T extends number>(int: T): string {
244
276
  // 9 = 57
245
277
 
246
278
  console.log(JSON.stringify("h\\i from gray\bson"));
279
+ */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-as",
3
- "version": "0.5.39",
3
+ "version": "0.5.42",
4
4
  "description": "JSON encoder/decoder for AssemblyScript",
5
5
  "types": "assembly/index.ts",
6
6
  "author": "Jairus Tanaka",
@@ -1,4 +1,4 @@
1
- import { toString, isStdlib } from "visitor-as/dist/utils.js";
1
+ import { getName, toString, isStdlib } from "visitor-as/dist/utils.js";
2
2
  import { BaseVisitor, SimpleParser } from "visitor-as/dist/index.js";
3
3
  import { Transform } from "assemblyscript/dist/transform.js";
4
4
  class SchemaData {
@@ -19,23 +19,48 @@ class AsJSONTransform extends BaseVisitor {
19
19
  this.sources = [];
20
20
  }
21
21
  visitMethodDeclaration() { }
22
+ visitFieldDeclaration(node) {
23
+ if (toString(node).startsWith("static"))
24
+ return;
25
+ const lineText = toString(node);
26
+ if (lineText.startsWith("private"))
27
+ return;
28
+ const name = getName(node);
29
+ if (!node.type) {
30
+ throw new Error(`Field ${name} is missing a type declaration`);
31
+ }
32
+ let type = getName(node.type);
33
+ // @ts-ignore
34
+ this.currentClass.encodeStmts.push(`"${name}":\${JSON.stringify<${type}>(this.${name})},`);
35
+ // @ts-ignore
36
+ //this.decodeStmts.push(
37
+ // `${name}: JSON.parseObjectValue<${type}>(values.get("${name}")),\n`
38
+ //);
39
+ // @ts-ignore
40
+ this.currentClass.setDataStmts.push(`if (key.length === ${name.length} && (memory.compare(changetype<usize>("${name}"), changetype<usize>(key), ${name.length}) == 0)) {
41
+ this.${name} = JSON.parseObjectValue<${type}>(value);
42
+ return;
43
+ }
44
+ `);
45
+ // @ts-ignore
46
+ //this.checkDecodeStmts.push(
47
+ // ' if (!values.has("${name}")) throw new Error("Key "${name}" was not found. Cannot instantiate object.");\n'
48
+ //);
49
+ }
22
50
  visitClassDeclaration(node) {
23
- var _c;
51
+ var _a;
24
52
  const className = node.name.text;
25
- if (!((_c = node.decorators) === null || _c === void 0 ? void 0 : _c.length))
53
+ if (!((_a = node.decorators) === null || _a === void 0 ? void 0 : _a.length))
26
54
  return;
27
55
  let foundDecorator = false;
28
56
  for (const decorator of node.decorators) {
29
- if (
30
57
  // @ts-ignore
31
- decorator.name.text.toLowerCase() == "json" ||
32
- // @ts-ignore
33
- decorator.name.text.toLowerCase() == "serializable")
58
+ if (decorator.name.text.toLowerCase() == "json" || decorator.name.text.toLowerCase() == "serializable")
34
59
  foundDecorator = true;
35
60
  }
36
61
  if (!foundDecorator)
37
62
  return;
38
- // Prevent from being triggered twice.
63
+ // Prevent from being triggered twice
39
64
  for (const member of node.members) {
40
65
  if (member.name.text == "__JSON_Serialize")
41
66
  return;
@@ -48,7 +73,7 @@ class AsJSONTransform extends BaseVisitor {
48
73
  parent: node.extendsType ? toString(node.extendsType) : "",
49
74
  node: node,
50
75
  encodeStmts: [],
51
- setDataStmts: [],
76
+ setDataStmts: []
52
77
  };
53
78
  if (this.currentClass.parent.length > 0) {
54
79
  const parentSchema = this.schemasList.find((v) => v.name == this.currentClass.parent);
@@ -57,64 +82,17 @@ class AsJSONTransform extends BaseVisitor {
57
82
  this.currentClass.encodeStmts.push(...parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.encodeStmts);
58
83
  }
59
84
  else {
60
- console.error("Class extends " +
61
- this.currentClass.parent +
62
- ", but parent class not found. Maybe add the @json decorator over parent class?");
85
+ console.error("Class extends " + this.currentClass.parent + ", but parent class not found. Maybe add the @json decorator over parent class?");
63
86
  }
64
87
  }
65
88
  const parentSchema = this.schemasList.find((v) => v.name == this.currentClass.parent);
66
- const members = [
67
- ...node.members,
68
- ...(parentSchema ? parentSchema.node.members : []),
69
- ];
70
- for (const mem of members) {
71
- // @ts-ignore
72
- if (mem.type && mem.type.name && mem.type.name.identifier.text) {
73
- const member = mem;
74
- if (toString(member).startsWith("static"))
75
- return;
76
- const lineText = toString(member);
77
- if (lineText.startsWith("private"))
78
- return;
79
- // @ts-ignore
80
- let type = toString(member.type);
81
- const name = member.name.text;
82
- this.currentClass.keys.push(name);
83
- // @ts-ignore
84
- this.currentClass.types.push(type);
85
- // @ts-ignore
86
- if ([
87
- "u8",
88
- "i8",
89
- "u16",
90
- "i16",
91
- "u32",
92
- "i32",
93
- "f32",
94
- "u64",
95
- "i64",
96
- "f64",
97
- ].includes(type.toLowerCase())) {
98
- this.currentClass.encodeStmts.push(`"${name}":\${this.${name}.toString()},`);
99
- }
100
- else {
101
- this.currentClass.encodeStmts.push(`"${name}":\${JSON.stringify<${type}>(this.${name})},`);
102
- }
103
- // @ts-ignore
104
- this.currentClass.setDataStmts.push(`if (key == "${name}") {
105
- this.${name} = JSON.parseObjectValue<${type}>(value);
106
- return;
107
- }
108
- `);
109
- }
110
- }
89
+ const members = [...node.members, ...(parentSchema ? parentSchema.node.members : [])];
90
+ this.visit(members);
111
91
  let serializeFunc = "";
112
92
  if (this.currentClass.encodeStmts.length > 0) {
113
93
  const stmt = this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1];
114
- this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1] =
115
- stmt.slice(0, stmt.length - 1);
94
+ this.currentClass.encodeStmts[this.currentClass.encodeStmts.length - 1] = stmt.slice(0, stmt.length - 1);
116
95
  serializeFunc = `
117
- @inline
118
96
  __JSON_Serialize(): string {
119
97
  return \`{${this.currentClass.encodeStmts.join("")}}\`;
120
98
  }
@@ -122,18 +100,16 @@ class AsJSONTransform extends BaseVisitor {
122
100
  }
123
101
  else {
124
102
  serializeFunc = `
125
- @inline
126
103
  __JSON_Serialize(): string {
127
104
  return "{}";
128
105
  }
129
106
  `;
130
107
  }
131
108
  const setKeyFunc = `
132
- @inline
133
109
  __JSON_Set_Key(key: string, value: string): void {
134
110
  ${
135
- // @ts-ignore
136
- this.currentClass.setDataStmts.join("")}
111
+ // @ts-ignore
112
+ this.currentClass.setDataStmts.join("")}
137
113
  }
138
114
  `;
139
115
  const serializeMethod = SimpleParser.parseClassMember(serializeFunc, node);
@@ -151,23 +127,18 @@ export default class Transformer extends Transform {
151
127
  afterParse(parser) {
152
128
  // Create new transform
153
129
  const transformer = new AsJSONTransform();
154
- // Sort the sources so that user scripts are visited last
155
- const sources = parser.sources
156
- .filter((source) => !isStdlib(source))
157
- .sort((_a, _b) => {
158
- const a = _a.internalPath;
159
- const b = _b.internalPath;
130
+ // Loop over every source
131
+ const sources = parser.sources.filter(source => !isStdlib(source)).sort((_a, _b) => {
132
+ const a = _a.internalPath
133
+ const b = _b.internalPath
160
134
  if (a[0] === "~" && b[0] !== "~") {
161
135
  return -1;
162
- }
163
- else if (a[0] !== "~" && b[0] === "~") {
136
+ } else if (a[0] !== "~" && b[0] === "~") {
164
137
  return 1;
165
- }
166
- else {
138
+ } else {
167
139
  return 0;
168
140
  }
169
- });
170
- // Loop over every source
141
+ })
171
142
  for (const source of sources) {
172
143
  // Ignore all lib and std. Visit everything else.
173
144
  if (!isStdlib(source)) {
@@ -175,4 +146,4 @@ export default class Transformer extends Transform {
175
146
  }
176
147
  }
177
148
  }
178
- }
149
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@json-as/transform",
3
- "version": "0.5.39",
3
+ "version": "0.5.42",
4
4
  "description": "JSON encoder/decoder for AssemblyScript",
5
5
  "main": "./lib/index.js",
6
6
  "author": "Jairus Tanaka",