@atscript/typescript 0.0.28 → 0.0.30

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/cli.cjs CHANGED
@@ -154,7 +154,7 @@ var BaseRenderer = class extends CodePrinter {
154
154
  renderInterface(node) {}
155
155
  renderType(node) {}
156
156
  transformFromPath(path$3) {
157
- return path$3 + ".as";
157
+ return `${path$3}.as`;
158
158
  }
159
159
  renderImport(node) {
160
160
  const def = node.getDefinition();
@@ -204,7 +204,7 @@ function wrapProp(name) {
204
204
  return name;
205
205
  }
206
206
  function escapeQuotes(str) {
207
- return str.replace(/"/g, "\\\"").replace(/\\/g, "\\\\");
207
+ return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
208
208
  }
209
209
 
210
210
  //#endregion
@@ -219,7 +219,7 @@ function _define_property$3(obj, key, value) {
219
219
  else obj[key] = value;
220
220
  return obj;
221
221
  }
222
- var TypeRenderer = class extends BaseRenderer {
222
+ var TypeRenderer = class TypeRenderer extends BaseRenderer {
223
223
  pre() {
224
224
  this.writeln("// prettier-ignore-start");
225
225
  this.writeln("/* eslint-disable */");
@@ -229,11 +229,16 @@ var TypeRenderer = class extends BaseRenderer {
229
229
  this.writeln(" * Do not edit this file!");
230
230
  this.writeln(" */");
231
231
  this.writeln();
232
- this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TMetadataMap, Validator, TAtscriptAnnotatedTypeConstructor, TValidatorOptions } from \"@atscript/typescript\"");
232
+ this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TMetadataMap, Validator, TAtscriptAnnotatedTypeConstructor, TValidatorOptions } from \"@atscript/typescript/utils\"");
233
233
  }
234
234
  post() {
235
235
  this.writeln("// prettier-ignore-end");
236
236
  }
237
+ renderTypeDefString(def) {
238
+ const newThis = new TypeRenderer(this.doc, this.opts);
239
+ newThis.renderTypeDef(def);
240
+ return newThis.toString();
241
+ }
237
242
  renderTypeDef(def) {
238
243
  if (!def) {
239
244
  this.write("unknown");
@@ -282,33 +287,33 @@ var TypeRenderer = class extends BaseRenderer {
282
287
  renderStructure(struct, asClass) {
283
288
  this.blockln("{}");
284
289
  const patterns = [];
285
- let hasProp = false;
290
+ const propsDefs = new Set();
286
291
  for (const prop of Array.from(struct.props.values())) {
287
292
  if (prop.token("identifier")?.pattern) {
288
293
  patterns.push(prop);
289
294
  continue;
290
295
  }
291
- hasProp = true;
292
296
  const optional = !!prop.token("optional");
293
297
  this.write(wrapProp(prop.id), optional ? "?" : "", ": ");
294
- this.renderTypeDef(prop.getDefinition());
295
- this.writeln();
298
+ const renderedDef = this.renderTypeDefString(prop.getDefinition());
299
+ propsDefs.add(renderedDef);
300
+ renderedDef.split("\n").forEach((l) => this.writeln(l));
296
301
  }
297
302
  if (patterns.length) {
298
303
  this.write(`[key: string]: `);
299
- if (hasProp) this.writeln("any");
300
- else if (patterns.length === 1) {
301
- this.renderTypeDef(patterns[0].getDefinition());
302
- this.writeln();
303
- } else {
304
- this.indent();
305
- for (const prop of patterns) {
304
+ if (patterns.length > 0) {
305
+ for (const prop of patterns) propsDefs.add(this.renderTypeDefString(prop.getDefinition()));
306
+ const defs = Array.from(propsDefs);
307
+ if (defs.length > 1) {
308
+ this.indent();
309
+ for (const def of defs) {
310
+ this.writeln();
311
+ this.write("| ");
312
+ def.split("\n").forEach((l) => this.write(l.trim()));
313
+ }
314
+ this.unindent();
306
315
  this.writeln();
307
- this.write("| ");
308
- this.renderTypeDef(prop.getDefinition());
309
- }
310
- this.unindent();
311
- this.writeln();
316
+ } else defs[0].split("\n").forEach((l) => this.writeln(l));
312
317
  }
313
318
  }
314
319
  if (asClass) {
@@ -359,7 +364,7 @@ else if ((0, __atscript_core.isPrimitive)(realDef)) typeDef = "TAtscriptTypeFina
359
364
  this.writeln(`const type: ${typeDef}`);
360
365
  this.writeln(`const metadata: TMetadataMap<AtscriptMetadata>`);
361
366
  this.writeln(`const validator: <TT extends TAtscriptAnnotatedTypeConstructor = ${node.id}>(opts?: Partial<TValidatorOptions>) => Validator<TT>`);
362
- if (this.opts?.jsonSchema) this.writeln("const toJsonSchema: () => any");
367
+ this.writeln("const toJsonSchema: () => any");
363
368
  this.popln();
364
369
  }
365
370
  renderJsDoc(node) {
@@ -497,7 +502,7 @@ var Validator = class {
497
502
  }
498
503
  validateTuple(def, value) {
499
504
  if (!Array.isArray(value) || value.length !== def.type.items.length) {
500
- this.error("Expected array of length " + def.type.items.length);
505
+ this.error(`Expected array of length ${def.type.items.length}`);
501
506
  return false;
502
507
  }
503
508
  let i = 0;
@@ -550,7 +555,7 @@ var Validator = class {
550
555
  const typeKeys = new Set();
551
556
  const skipList = new Set();
552
557
  if (this.opts.skipList) {
553
- const path$3 = this.stackPath.length > 1 ? this.path + "." : "";
558
+ const path$3 = this.stackPath.length > 1 ? `${this.path}.` : "";
554
559
  this.opts.skipList.forEach((item) => {
555
560
  if (item.startsWith(path$3)) {
556
561
  const key = item.slice(path$3.length);
@@ -940,7 +945,7 @@ var JsRenderer = class extends BaseRenderer {
940
945
  this.writeln("/* eslint-disable */");
941
946
  const imports = ["defineAnnotatedType as $"];
942
947
  if (!this.opts?.preRenderJsonSchema) imports.push("buildJsonSchema as $$");
943
- this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript"`);
948
+ this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
944
949
  }
945
950
  post() {
946
951
  for (const node of this.postAnnotate) {
@@ -985,7 +990,7 @@ var JsRenderer = class extends BaseRenderer {
985
990
  this.writeln("static __is_atscript_annotated_type = true");
986
991
  this.writeln("static type = {}");
987
992
  this.writeln("static metadata = new Map()");
988
- if (this.opts?.jsonSchema) if (typeof this.opts.jsonSchema === "object" && this.opts.jsonSchema.preRender) {
993
+ if (this.opts?.preRenderJsonSchema) {
989
994
  const schema = JSON.stringify(buildJsonSchema(this.toAnnotatedType(node)));
990
995
  this.writeln(`static _jsonSchema = ${schema}`);
991
996
  this.writeln("static toJsonSchema() {");
package/dist/index.cjs CHANGED
@@ -1,5 +1,4 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, '__esModule', { value: true });
3
2
  //#region rolldown:runtime
4
3
  var __create = Object.create;
5
4
  var __defProp = Object.defineProperty;
@@ -152,7 +151,7 @@ var BaseRenderer = class extends CodePrinter {
152
151
  renderInterface(node) {}
153
152
  renderType(node) {}
154
153
  transformFromPath(path$2) {
155
- return path$2 + ".as";
154
+ return `${path$2}.as`;
156
155
  }
157
156
  renderImport(node) {
158
157
  const def = node.getDefinition();
@@ -202,7 +201,7 @@ function wrapProp(name) {
202
201
  return name;
203
202
  }
204
203
  function escapeQuotes(str) {
205
- return str.replace(/"/g, "\\\"").replace(/\\/g, "\\\\");
204
+ return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
206
205
  }
207
206
 
208
207
  //#endregion
@@ -217,7 +216,7 @@ function _define_property$2(obj, key, value) {
217
216
  else obj[key] = value;
218
217
  return obj;
219
218
  }
220
- var TypeRenderer = class extends BaseRenderer {
219
+ var TypeRenderer = class TypeRenderer extends BaseRenderer {
221
220
  pre() {
222
221
  this.writeln("// prettier-ignore-start");
223
222
  this.writeln("/* eslint-disable */");
@@ -227,11 +226,16 @@ var TypeRenderer = class extends BaseRenderer {
227
226
  this.writeln(" * Do not edit this file!");
228
227
  this.writeln(" */");
229
228
  this.writeln();
230
- this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TMetadataMap, Validator, TAtscriptAnnotatedTypeConstructor, TValidatorOptions } from \"@atscript/typescript\"");
229
+ this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TMetadataMap, Validator, TAtscriptAnnotatedTypeConstructor, TValidatorOptions } from \"@atscript/typescript/utils\"");
231
230
  }
232
231
  post() {
233
232
  this.writeln("// prettier-ignore-end");
234
233
  }
234
+ renderTypeDefString(def) {
235
+ const newThis = new TypeRenderer(this.doc, this.opts);
236
+ newThis.renderTypeDef(def);
237
+ return newThis.toString();
238
+ }
235
239
  renderTypeDef(def) {
236
240
  if (!def) {
237
241
  this.write("unknown");
@@ -280,33 +284,33 @@ var TypeRenderer = class extends BaseRenderer {
280
284
  renderStructure(struct, asClass) {
281
285
  this.blockln("{}");
282
286
  const patterns = [];
283
- let hasProp = false;
287
+ const propsDefs = new Set();
284
288
  for (const prop of Array.from(struct.props.values())) {
285
289
  if (prop.token("identifier")?.pattern) {
286
290
  patterns.push(prop);
287
291
  continue;
288
292
  }
289
- hasProp = true;
290
293
  const optional = !!prop.token("optional");
291
294
  this.write(wrapProp(prop.id), optional ? "?" : "", ": ");
292
- this.renderTypeDef(prop.getDefinition());
293
- this.writeln();
295
+ const renderedDef = this.renderTypeDefString(prop.getDefinition());
296
+ propsDefs.add(renderedDef);
297
+ renderedDef.split("\n").forEach((l) => this.writeln(l));
294
298
  }
295
299
  if (patterns.length) {
296
300
  this.write(`[key: string]: `);
297
- if (hasProp) this.writeln("any");
298
- else if (patterns.length === 1) {
299
- this.renderTypeDef(patterns[0].getDefinition());
300
- this.writeln();
301
- } else {
302
- this.indent();
303
- for (const prop of patterns) {
301
+ if (patterns.length > 0) {
302
+ for (const prop of patterns) propsDefs.add(this.renderTypeDefString(prop.getDefinition()));
303
+ const defs = Array.from(propsDefs);
304
+ if (defs.length > 1) {
305
+ this.indent();
306
+ for (const def of defs) {
307
+ this.writeln();
308
+ this.write("| ");
309
+ def.split("\n").forEach((l) => this.write(l.trim()));
310
+ }
311
+ this.unindent();
304
312
  this.writeln();
305
- this.write("| ");
306
- this.renderTypeDef(prop.getDefinition());
307
- }
308
- this.unindent();
309
- this.writeln();
313
+ } else defs[0].split("\n").forEach((l) => this.writeln(l));
310
314
  }
311
315
  }
312
316
  if (asClass) {
@@ -357,7 +361,7 @@ else if ((0, __atscript_core.isPrimitive)(realDef)) typeDef = "TAtscriptTypeFina
357
361
  this.writeln(`const type: ${typeDef}`);
358
362
  this.writeln(`const metadata: TMetadataMap<AtscriptMetadata>`);
359
363
  this.writeln(`const validator: <TT extends TAtscriptAnnotatedTypeConstructor = ${node.id}>(opts?: Partial<TValidatorOptions>) => Validator<TT>`);
360
- if (this.opts?.jsonSchema) this.writeln("const toJsonSchema: () => any");
364
+ this.writeln("const toJsonSchema: () => any");
361
365
  this.popln();
362
366
  }
363
367
  renderJsDoc(node) {
@@ -495,7 +499,7 @@ var Validator = class {
495
499
  }
496
500
  validateTuple(def, value) {
497
501
  if (!Array.isArray(value) || value.length !== def.type.items.length) {
498
- this.error("Expected array of length " + def.type.items.length);
502
+ this.error(`Expected array of length ${def.type.items.length}`);
499
503
  return false;
500
504
  }
501
505
  let i = 0;
@@ -548,7 +552,7 @@ var Validator = class {
548
552
  const typeKeys = new Set();
549
553
  const skipList = new Set();
550
554
  if (this.opts.skipList) {
551
- const path$2 = this.stackPath.length > 1 ? this.path + "." : "";
555
+ const path$2 = this.stackPath.length > 1 ? `${this.path}.` : "";
552
556
  this.opts.skipList.forEach((item) => {
553
557
  if (item.startsWith(path$2)) {
554
558
  const key = item.slice(path$2.length);
@@ -838,19 +842,6 @@ else this.$metadata.set(key, value);
838
842
  };
839
843
  return handle;
840
844
  }
841
- function isAnnotatedTypeOfPrimitive(t) {
842
- if (["array", "object"].includes(t.type.kind)) return false;
843
- if (!t.type.kind) return true;
844
- if ([
845
- "union",
846
- "tuple",
847
- "intersection"
848
- ].includes(t.type.kind)) {
849
- for (const item of t.type.items) if (!isAnnotatedTypeOfPrimitive(item)) return false;
850
- return true;
851
- }
852
- return false;
853
- }
854
845
 
855
846
  //#endregion
856
847
  //#region packages/typescript/src/json-schema.ts
@@ -951,7 +942,7 @@ var JsRenderer = class extends BaseRenderer {
951
942
  this.writeln("/* eslint-disable */");
952
943
  const imports = ["defineAnnotatedType as $"];
953
944
  if (!this.opts?.preRenderJsonSchema) imports.push("buildJsonSchema as $$");
954
- this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript"`);
945
+ this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
955
946
  }
956
947
  post() {
957
948
  for (const node of this.postAnnotate) {
@@ -996,7 +987,7 @@ var JsRenderer = class extends BaseRenderer {
996
987
  this.writeln("static __is_atscript_annotated_type = true");
997
988
  this.writeln("static type = {}");
998
989
  this.writeln("static metadata = new Map()");
999
- if (this.opts?.jsonSchema) if (typeof this.opts.jsonSchema === "object" && this.opts.jsonSchema.preRender) {
990
+ if (this.opts?.preRenderJsonSchema) {
1000
991
  const schema = JSON.stringify(buildJsonSchema(this.toAnnotatedType(node)));
1001
992
  this.writeln(`static _jsonSchema = ${schema}`);
1002
993
  this.writeln("static toJsonSchema() {");
@@ -1354,10 +1345,4 @@ else return t.optional ? `${t.type} | true` : t.type;
1354
1345
  var src_default = tsPlugin;
1355
1346
 
1356
1347
  //#endregion
1357
- exports.Validator = Validator
1358
- exports.ValidatorError = ValidatorError
1359
- exports.buildJsonSchema = buildJsonSchema
1360
- exports.default = src_default
1361
- exports.defineAnnotatedType = defineAnnotatedType
1362
- exports.isAnnotatedType = isAnnotatedType
1363
- exports.isAnnotatedTypeOfPrimitive = isAnnotatedTypeOfPrimitive
1348
+ module.exports = src_default;
package/dist/index.d.ts CHANGED
@@ -8,135 +8,4 @@ interface TTsPluginOptions {
8
8
  }
9
9
  declare const tsPlugin: (opts?: TTsPluginOptions) => TAtscriptPlugin;
10
10
 
11
- interface TError {
12
- path: string;
13
- message: string;
14
- details?: TError[];
15
- }
16
- type TValidatorPlugin = (ctx: TValidatorPluginContext, def: TAtscriptAnnotatedType, value: any) => boolean | undefined;
17
- interface TValidatorOptions {
18
- partial: boolean | 'deep' | ((type: TAtscriptAnnotatedType<TAtscriptTypeObject>, path: string) => boolean);
19
- replace?: (type: TAtscriptAnnotatedType, path: string) => TAtscriptAnnotatedType;
20
- plugins: TValidatorPlugin[];
21
- unknwonProps: 'strip' | 'ignore' | 'error';
22
- errorLimit: number;
23
- skipList?: Set<string>;
24
- }
25
- interface TValidatorPluginContext {
26
- opts: Validator<any>['opts'];
27
- validateAnnotatedType: Validator<any>['validateAnnotatedType'];
28
- error: Validator<any>['error'];
29
- path: Validator<any>['path'];
30
- }
31
- declare class Validator<T extends TAtscriptAnnotatedTypeConstructor> {
32
- protected readonly def: T | TAtscriptAnnotatedType<any>;
33
- protected opts: TValidatorOptions;
34
- constructor(def: T | TAtscriptAnnotatedType<any>, opts?: Partial<TValidatorOptions>);
35
- errors: TError[];
36
- protected stackErrors: TError[][];
37
- protected stackPath: string[];
38
- protected isLimitExceeded(): boolean;
39
- protected push(name: string): void;
40
- protected pop(saveErrors: boolean): TError[] | undefined;
41
- protected clear(): void;
42
- protected error(message: string, path?: string, details?: TError[]): void;
43
- protected throw(): void;
44
- validate<TT = T>(value: any, safe?: boolean): value is TT;
45
- protected validateSafe(def: TAtscriptAnnotatedType, value: any): boolean;
46
- protected get path(): string;
47
- protected validateAnnotatedType(def: TAtscriptAnnotatedType, value: any): boolean;
48
- protected validateUnion(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, value: any): boolean;
49
- protected validateIntersection(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, value: any): boolean;
50
- protected validateTuple(def: TAtscriptAnnotatedType<TAtscriptTypeComplex>, value: any): boolean;
51
- protected validateArray(def: TAtscriptAnnotatedType<TAtscriptTypeArray>, value: any): boolean;
52
- protected validateObject(def: TAtscriptAnnotatedType<TAtscriptTypeObject>, value: any): boolean;
53
- protected validatePrimitive(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: any): boolean;
54
- protected validateString(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: string): boolean;
55
- protected validateNumber(def: TAtscriptAnnotatedType<TAtscriptTypeFinal>, value: number): boolean;
56
- }
57
- declare class ValidatorError extends Error {
58
- readonly errors: TError[];
59
- name: string;
60
- constructor(errors: TError[]);
61
- }
62
-
63
- interface TAtscriptTypeComplex {
64
- kind: 'union' | 'intersection' | 'tuple';
65
- items: TAtscriptAnnotatedType[];
66
- tags: Set<AtscriptPrimitiveTags>;
67
- }
68
- interface TAtscriptTypeArray {
69
- kind: 'array';
70
- of: TAtscriptAnnotatedType;
71
- tags: Set<AtscriptPrimitiveTags>;
72
- }
73
- interface TAtscriptTypeObject<K extends string = string> {
74
- kind: 'object';
75
- props: Map<K, TAtscriptAnnotatedType>;
76
- propsPatterns: {
77
- pattern: RegExp;
78
- def: TAtscriptAnnotatedType;
79
- }[];
80
- tags: Set<AtscriptPrimitiveTags>;
81
- }
82
- interface TAtscriptTypeFinal {
83
- kind: '';
84
- /**
85
- * design type
86
- */
87
- designType: 'string' | 'number' | 'boolean' | 'undefined' | 'null' | 'object' | 'any' | 'never';
88
- /**
89
- * value for literals
90
- */
91
- value?: string | number | boolean;
92
- tags: Set<AtscriptPrimitiveTags>;
93
- }
94
- type TAtscriptTypeDef = TAtscriptTypeComplex | TAtscriptTypeFinal | TAtscriptTypeArray | TAtscriptTypeObject<string>;
95
- interface TAtscriptAnnotatedType<T = TAtscriptTypeDef> {
96
- __is_atscript_annotated_type: true;
97
- type: T;
98
- validator: <TT extends TAtscriptAnnotatedTypeConstructor>(opts?: Partial<TValidatorOptions>) => Validator<TT>;
99
- metadata: TMetadataMap<AtscriptMetadata>;
100
- optional?: boolean;
101
- }
102
- type TAtscriptAnnotatedTypeConstructor = TAtscriptAnnotatedType & (new (...args: any[]) => any);
103
- /**
104
- * Type Guard to check if a type is atscript-annotated
105
- */
106
- declare function isAnnotatedType(type: any): type is TAtscriptAnnotatedType;
107
- type TKind = '' | 'array' | 'object' | 'union' | 'intersection' | 'tuple';
108
- declare function defineAnnotatedType(_kind?: TKind, base?: any): TAnnotatedTypeHandle;
109
- /**
110
- * Atscript Metadata Map with typed setters/getters
111
- */
112
- interface TMetadataMap<O extends object> extends Map<keyof O, O[keyof O]> {
113
- get<K extends keyof O>(key: K): O[K] | undefined;
114
- set<K extends keyof O>(key: K, value: O[K]): this;
115
- }
116
- interface TAnnotatedTypeHandle {
117
- $type: TAtscriptAnnotatedType;
118
- $def: {
119
- kind: TKind;
120
- } & Omit<TAtscriptTypeComplex, 'kind'> & Omit<TAtscriptTypeFinal, 'kind'> & Omit<TAtscriptTypeArray, 'kind'> & Omit<TAtscriptTypeObject<string>, 'kind'>;
121
- $metadata: TMetadataMap<AtscriptMetadata>;
122
- _existingObject: TAtscriptAnnotatedType | undefined;
123
- tags(...tags: string[]): TAnnotatedTypeHandle;
124
- designType(value: TAtscriptTypeFinal['designType']): TAnnotatedTypeHandle;
125
- value(value: string | number | boolean): TAnnotatedTypeHandle;
126
- of(value: TAtscriptAnnotatedType): TAnnotatedTypeHandle;
127
- item(value: TAtscriptAnnotatedType): TAnnotatedTypeHandle;
128
- prop(name: string, value: TAtscriptAnnotatedType): TAnnotatedTypeHandle;
129
- propPattern(pattern: RegExp, value: TAtscriptAnnotatedType): TAnnotatedTypeHandle;
130
- optional(value?: boolean): TAnnotatedTypeHandle;
131
- copyMetadata(fromMetadata: TMetadataMap<AtscriptMetadata>): TAnnotatedTypeHandle;
132
- refTo(type: TAtscriptAnnotatedType & {
133
- name?: string;
134
- }, chain?: string[]): TAnnotatedTypeHandle;
135
- annotate(key: keyof AtscriptMetadata, value: any, asArray?: boolean): TAnnotatedTypeHandle;
136
- }
137
- declare function isAnnotatedTypeOfPrimitive(t: TAtscriptAnnotatedType): boolean;
138
-
139
- type TJsonSchema = Record<string, any>;
140
- declare function buildJsonSchema(type: TAtscriptAnnotatedType): TJsonSchema;
141
-
142
- export { type TAnnotatedTypeHandle, type TAtscriptAnnotatedType, type TAtscriptAnnotatedTypeConstructor, type TAtscriptTypeArray, type TAtscriptTypeComplex, type TAtscriptTypeDef, type TAtscriptTypeFinal, type TAtscriptTypeObject, type TJsonSchema, type TMetadataMap, type TValidatorOptions, type TValidatorPlugin, type TValidatorPluginContext, Validator, ValidatorError, buildJsonSchema, tsPlugin as default, defineAnnotatedType, isAnnotatedType, isAnnotatedTypeOfPrimitive };
11
+ export { tsPlugin as default };
package/dist/index.mjs CHANGED
@@ -127,7 +127,7 @@ var BaseRenderer = class extends CodePrinter {
127
127
  renderInterface(node) {}
128
128
  renderType(node) {}
129
129
  transformFromPath(path$1) {
130
- return path$1 + ".as";
130
+ return `${path$1}.as`;
131
131
  }
132
132
  renderImport(node) {
133
133
  const def = node.getDefinition();
@@ -177,7 +177,7 @@ function wrapProp(name) {
177
177
  return name;
178
178
  }
179
179
  function escapeQuotes(str) {
180
- return str.replace(/"/g, "\\\"").replace(/\\/g, "\\\\");
180
+ return str.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
181
181
  }
182
182
 
183
183
  //#endregion
@@ -192,7 +192,7 @@ function _define_property$2(obj, key, value) {
192
192
  else obj[key] = value;
193
193
  return obj;
194
194
  }
195
- var TypeRenderer = class extends BaseRenderer {
195
+ var TypeRenderer = class TypeRenderer extends BaseRenderer {
196
196
  pre() {
197
197
  this.writeln("// prettier-ignore-start");
198
198
  this.writeln("/* eslint-disable */");
@@ -202,11 +202,16 @@ var TypeRenderer = class extends BaseRenderer {
202
202
  this.writeln(" * Do not edit this file!");
203
203
  this.writeln(" */");
204
204
  this.writeln();
205
- this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TMetadataMap, Validator, TAtscriptAnnotatedTypeConstructor, TValidatorOptions } from \"@atscript/typescript\"");
205
+ this.writeln("import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TMetadataMap, Validator, TAtscriptAnnotatedTypeConstructor, TValidatorOptions } from \"@atscript/typescript/utils\"");
206
206
  }
207
207
  post() {
208
208
  this.writeln("// prettier-ignore-end");
209
209
  }
210
+ renderTypeDefString(def) {
211
+ const newThis = new TypeRenderer(this.doc, this.opts);
212
+ newThis.renderTypeDef(def);
213
+ return newThis.toString();
214
+ }
210
215
  renderTypeDef(def) {
211
216
  if (!def) {
212
217
  this.write("unknown");
@@ -255,33 +260,33 @@ var TypeRenderer = class extends BaseRenderer {
255
260
  renderStructure(struct, asClass) {
256
261
  this.blockln("{}");
257
262
  const patterns = [];
258
- let hasProp = false;
263
+ const propsDefs = new Set();
259
264
  for (const prop of Array.from(struct.props.values())) {
260
265
  if (prop.token("identifier")?.pattern) {
261
266
  patterns.push(prop);
262
267
  continue;
263
268
  }
264
- hasProp = true;
265
269
  const optional = !!prop.token("optional");
266
270
  this.write(wrapProp(prop.id), optional ? "?" : "", ": ");
267
- this.renderTypeDef(prop.getDefinition());
268
- this.writeln();
271
+ const renderedDef = this.renderTypeDefString(prop.getDefinition());
272
+ propsDefs.add(renderedDef);
273
+ renderedDef.split("\n").forEach((l) => this.writeln(l));
269
274
  }
270
275
  if (patterns.length) {
271
276
  this.write(`[key: string]: `);
272
- if (hasProp) this.writeln("any");
273
- else if (patterns.length === 1) {
274
- this.renderTypeDef(patterns[0].getDefinition());
275
- this.writeln();
276
- } else {
277
- this.indent();
278
- for (const prop of patterns) {
277
+ if (patterns.length > 0) {
278
+ for (const prop of patterns) propsDefs.add(this.renderTypeDefString(prop.getDefinition()));
279
+ const defs = Array.from(propsDefs);
280
+ if (defs.length > 1) {
281
+ this.indent();
282
+ for (const def of defs) {
283
+ this.writeln();
284
+ this.write("| ");
285
+ def.split("\n").forEach((l) => this.write(l.trim()));
286
+ }
287
+ this.unindent();
279
288
  this.writeln();
280
- this.write("| ");
281
- this.renderTypeDef(prop.getDefinition());
282
- }
283
- this.unindent();
284
- this.writeln();
289
+ } else defs[0].split("\n").forEach((l) => this.writeln(l));
285
290
  }
286
291
  }
287
292
  if (asClass) {
@@ -332,7 +337,7 @@ else if (isPrimitive(realDef)) typeDef = "TAtscriptTypeFinal";
332
337
  this.writeln(`const type: ${typeDef}`);
333
338
  this.writeln(`const metadata: TMetadataMap<AtscriptMetadata>`);
334
339
  this.writeln(`const validator: <TT extends TAtscriptAnnotatedTypeConstructor = ${node.id}>(opts?: Partial<TValidatorOptions>) => Validator<TT>`);
335
- if (this.opts?.jsonSchema) this.writeln("const toJsonSchema: () => any");
340
+ this.writeln("const toJsonSchema: () => any");
336
341
  this.popln();
337
342
  }
338
343
  renderJsDoc(node) {
@@ -470,7 +475,7 @@ var Validator = class {
470
475
  }
471
476
  validateTuple(def, value) {
472
477
  if (!Array.isArray(value) || value.length !== def.type.items.length) {
473
- this.error("Expected array of length " + def.type.items.length);
478
+ this.error(`Expected array of length ${def.type.items.length}`);
474
479
  return false;
475
480
  }
476
481
  let i = 0;
@@ -523,7 +528,7 @@ var Validator = class {
523
528
  const typeKeys = new Set();
524
529
  const skipList = new Set();
525
530
  if (this.opts.skipList) {
526
- const path$1 = this.stackPath.length > 1 ? this.path + "." : "";
531
+ const path$1 = this.stackPath.length > 1 ? `${this.path}.` : "";
527
532
  this.opts.skipList.forEach((item) => {
528
533
  if (item.startsWith(path$1)) {
529
534
  const key = item.slice(path$1.length);
@@ -813,19 +818,6 @@ else this.$metadata.set(key, value);
813
818
  };
814
819
  return handle;
815
820
  }
816
- function isAnnotatedTypeOfPrimitive(t) {
817
- if (["array", "object"].includes(t.type.kind)) return false;
818
- if (!t.type.kind) return true;
819
- if ([
820
- "union",
821
- "tuple",
822
- "intersection"
823
- ].includes(t.type.kind)) {
824
- for (const item of t.type.items) if (!isAnnotatedTypeOfPrimitive(item)) return false;
825
- return true;
826
- }
827
- return false;
828
- }
829
821
 
830
822
  //#endregion
831
823
  //#region packages/typescript/src/json-schema.ts
@@ -926,7 +918,7 @@ var JsRenderer = class extends BaseRenderer {
926
918
  this.writeln("/* eslint-disable */");
927
919
  const imports = ["defineAnnotatedType as $"];
928
920
  if (!this.opts?.preRenderJsonSchema) imports.push("buildJsonSchema as $$");
929
- this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript"`);
921
+ this.writeln(`import { ${imports.join(", ")} } from "@atscript/typescript/utils"`);
930
922
  }
931
923
  post() {
932
924
  for (const node of this.postAnnotate) {
@@ -971,7 +963,7 @@ var JsRenderer = class extends BaseRenderer {
971
963
  this.writeln("static __is_atscript_annotated_type = true");
972
964
  this.writeln("static type = {}");
973
965
  this.writeln("static metadata = new Map()");
974
- if (this.opts?.jsonSchema) if (typeof this.opts.jsonSchema === "object" && this.opts.jsonSchema.preRender) {
966
+ if (this.opts?.preRenderJsonSchema) {
975
967
  const schema = JSON.stringify(buildJsonSchema(this.toAnnotatedType(node)));
976
968
  this.writeln(`static _jsonSchema = ${schema}`);
977
969
  this.writeln("static toJsonSchema() {");
@@ -1329,4 +1321,4 @@ else return t.optional ? `${t.type} | true` : t.type;
1329
1321
  var src_default = tsPlugin;
1330
1322
 
1331
1323
  //#endregion
1332
- export { Validator, ValidatorError, buildJsonSchema, src_default as default, defineAnnotatedType, isAnnotatedType, isAnnotatedTypeOfPrimitive };
1324
+ export { src_default as default };