@ddd-ts/freeze 0.0.36 → 0.0.38
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/LICENSE +21 -0
- package/dist/index.js +6 -8
- package/dist/index.mjs +4 -0
- package/dist/references/freeze.decorator.js +8 -7
- package/dist/references/freeze.decorator.mjs +9 -0
- package/dist/references/freeze.function.js +6 -5
- package/dist/references/freeze.function.mjs +5 -0
- package/package.json +42 -31
- package/dist/divergence/divergence.js +0 -3
- package/dist/divergence/divergence.js.map +0 -1
- package/dist/divergence/divergence.spec.js +0 -117
- package/dist/divergence/divergence.spec.js.map +0 -1
- package/dist/entrypoints/freeze-decorator.entrypoint.js +0 -101
- package/dist/entrypoints/freeze-decorator.entrypoint.js.map +0 -1
- package/dist/entrypoints/freeze-function.entrypoint.js +0 -87
- package/dist/entrypoints/freeze-function.entrypoint.js.map +0 -1
- package/dist/entrypoints/freeze.entrypoint.js +0 -5
- package/dist/entrypoints/freeze.entrypoint.js.map +0 -1
- package/dist/entrypoints/project.js +0 -10
- package/dist/entrypoints/project.js.map +0 -1
- package/dist/freeze.spec.js +0 -184
- package/dist/freeze.spec.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/references/freeze.decorator.js.map +0 -1
- package/dist/references/freeze.function.js.map +0 -1
- package/dist/utils/explore-type.js +0 -151
- package/dist/utils/explore-type.js.map +0 -1
- package/dist/utils/get-pretty-type.js +0 -24
- package/dist/utils/get-pretty-type.js.map +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Aetherall
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
Object.defineProperty(exports, "freeze", { enumerable: true, get: function () { return freeze_function_1.freeze; } });
|
|
8
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_freeze_decorator = require('./references/freeze.decorator.js');
|
|
3
|
+
const require_freeze_function = require('./references/freeze.function.js');
|
|
4
|
+
|
|
5
|
+
exports.Freeze = require_freeze_decorator.Freeze;
|
|
6
|
+
exports.freeze = require_freeze_function.freeze;
|
package/dist/index.mjs
ADDED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
exports.Freeze = Freeze;
|
|
1
|
+
|
|
2
|
+
//#region src/references/freeze.decorator.ts
|
|
4
3
|
function Freeze() {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
return (target) => {
|
|
5
|
+
return target;
|
|
6
|
+
};
|
|
8
7
|
}
|
|
9
|
-
|
|
8
|
+
|
|
9
|
+
//#endregion
|
|
10
|
+
exports.Freeze = Freeze;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
//#
|
|
1
|
+
|
|
2
|
+
//#region src/references/freeze.function.ts
|
|
3
|
+
function freeze(..._args) {}
|
|
4
|
+
|
|
5
|
+
//#endregion
|
|
6
|
+
exports.freeze = freeze;
|
package/package.json
CHANGED
|
@@ -1,32 +1,43 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
2
|
+
"name": "@ddd-ts/freeze",
|
|
3
|
+
"version": "0.0.38",
|
|
4
|
+
"types": "dist/index.d.ts",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"url": "git+https://github.com/ddd-ts/monorepo"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"bin": {
|
|
13
|
+
"freeze": "dist/entrypoints/freeze.entrypoint.js"
|
|
14
|
+
},
|
|
15
|
+
"peerDependencies": {
|
|
16
|
+
"ts-morph": "^23.0.0",
|
|
17
|
+
"typescript": "^5.5.4"
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@ddd-ts/core": "0.0.38",
|
|
21
|
+
"@ddd-ts/shape": "0.0.38",
|
|
22
|
+
"@ddd-ts/traits": "0.0.38",
|
|
23
|
+
"@ddd-ts/types": "0.0.38"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@ddd-ts/tools": "0.0.38",
|
|
27
|
+
"@types/jest": "^29.5.1",
|
|
28
|
+
"@types/node": "^17.0.13"
|
|
29
|
+
},
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"import": "./dist/index.mjs",
|
|
33
|
+
"require": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"main": "./dist/index.js",
|
|
38
|
+
"module": "./dist/index.mjs",
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsdown --config node_modules/@ddd-ts/tools/tsdown.config.js",
|
|
41
|
+
"test": "jest --config node_modules/@ddd-ts/tools/jest.config.js"
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"divergence.js","sourceRoot":"","sources":["../../src/divergence/divergence.ts"],"names":[],"mappings":"","sourcesContent":["export type UnionToIntersection<U> = (\n U extends unknown\n ? (k: U) => void\n : never\n) extends (k: infer I) => void\n ? I\n : never;\nexport type PopUnion<U> = UnionToOvlds<U> extends (a: infer A) => void\n ? A\n : never;\n\nexport type UnionToArray<T, A extends unknown[] = []> = IsUnion<T> extends true\n ? UnionToArray<Exclude<T, PopUnion<T>>, [PopUnion<T>, ...A]>\n : [T, ...A];\ntype CountUnion<T> = UnionToArray<T> extends infer U extends any[]\n ? U[\"length\"]\n : never;\n\ntype UnshiftUnion<U> = UnionToArray<U> extends [infer F, ...any[]] ? F : never;\n\ntype UnionToOvlds<U> = UnionToIntersection<\n U extends any ? (f: U) => void : never\n>;\ntype IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;\n\ntype IsStringLiteral<T> = T extends string\n ? string extends T\n ? false\n : true\n : false;\n\ntype FindBestKeyForMatching<FromUnion, ToUnion> = UnshiftUnion<\n keyof FromUnion extends infer K\n ? K extends keyof FromUnion & keyof ToUnion\n ? CountUnion<Pick<FromUnion, K>[K]> extends CountUnion<FromUnion>\n ? [IsStringLiteral<FromUnion[K]>, IsStringLiteral<ToUnion[K]>] extends [\n true,\n true,\n ]\n ? K\n : never\n : never\n : never\n : never\n>;\n\n// OBJECT\nexport type Expand<T> = T extends infer O\n ? { [K in keyof O]: O[K] } & {}\n : never;\ntype Access<T, K> = K extends keyof T ? T[K] : never;\ntype OnlyFromKeys<From, To> = Exclude<Exclude<keyof From, keyof To>, symbol>;\ntype OnlyToKeys<From, To> = Exclude<Exclude<keyof To, keyof From>, symbol>;\ntype OmitNever<T> = {\n [K in keyof T as T[K] extends never ? never : K]: T[K];\n} & {};\n\ntype ObjectDivergence<From, To, Acc extends any[]> = OmitNever<\n {\n [K in keyof From & keyof To]: Divergence<\n Access<From, K>,\n Access<To, K>,\n Acc\n >;\n } & {\n [K in OnlyFromKeys<From, To> as `+${K}`]: From[K];\n } & {\n [K in OnlyToKeys<From, To> as `-${K}`]: To[K];\n }\n> extends infer Result\n ? {} extends Result\n ? never\n : Result\n : never;\n\n// INDEXED\ntype IndexedTypeKey<From, To> = ({\n [K in keyof From]: K;\n} & {\n [K in keyof To]: K;\n})[keyof From | keyof To];\n\ntype IndexedTypeDiff<From, To, Acc extends any[]> = IndexedTypeKey<\n From,\n To\n> extends infer U extends keyof From & keyof To\n ? Divergence<From[U], To[U], Acc>\n : never;\ntype IsIndexedType<T> = [T] extends [never]\n ? false\n : T extends object\n ? string extends keyof T\n ? true\n : number extends keyof T\n ? true\n : symbol extends keyof T\n ? true\n : false\n : false;\n\n// UNION\n\ntype DiffBestMatchForObject<\n Item,\n Union,\n K,\n Acc extends any[],\n> = IsNever<K> extends false\n ? K extends keyof Union & keyof Item\n ? Extract<Union, { [P in K]: Item[P] }> extends infer BestMatch\n ? IsNever<BestMatch> extends false\n ? Divergence<Item, BestMatch, Acc> extends infer D\n ? IsNever<D> extends false\n ? Expand<{ [P in K]: Item[P] } & D>\n : never\n : never\n : never\n : never\n : never\n : never;\n\ntype DiffBestMatch<Item, Union, BestKey, Acc extends any[]> = PopUnion<\n Item extends any[]\n ? ArrayDivergence<Item, Extract<Union, any[]>, Acc>\n : Item extends object\n ? DiffBestMatchForObject<Item, Extract<Union, object>, BestKey, Acc>\n : never\n>;\n\ntype PerfectMatch<Item, Union, TotalUnion, Acc extends any[]> = Union extends [\n infer F,\n ...infer R,\n]\n ? Divergence<Item, F, Acc> extends infer D\n ? IsNever<D> extends true\n ? F\n : PerfectMatch<Item, R, TotalUnion, Acc>\n : \"!![PerfectMatch] Could not infer D\"\n : never; // end of recursion\n\ntype GetChange<Item, Union, BestKey, Acc extends any[]> = PerfectMatch<\n Item,\n UnionToArray<Union>,\n BestKey,\n Acc\n> extends infer P\n ? IsNever<P> extends false\n ? never\n : DiffBestMatch<Item, Union, BestKey, Acc> extends infer D\n ? IsNever<D> extends false\n ? { \"~\": D }\n : { \"+\": Item }\n : \"!![GetChange] Could not infer D\"\n : \"!![GetChange] Could not infer P\";\n\nexport type ArrayUnionDivergence<\n From,\n To,\n BestKey,\n Acc extends any[],\n Divergences extends { \"~\": unknown; \"+\": unknown } = {\n \"~\": never;\n \"+\": never;\n },\n> = From extends [infer F, ...infer Rest]\n ? GetChange<F, To, BestKey, Acc> extends infer Change\n ? IsNever<Change> extends true\n ? ArrayUnionDivergence<Rest, To, BestKey, Acc, Divergences>\n : Change extends { \"+\": infer A }\n ? ArrayUnionDivergence<\n Rest,\n To,\n BestKey,\n Acc,\n { \"~\": Divergences[\"~\"]; \"+\": Divergences[\"+\"] | A }\n >\n : Change extends { \"~\": infer C }\n ? ArrayUnionDivergence<\n Rest,\n To,\n BestKey,\n Acc,\n { \"~\": Divergences[\"~\"] | C; \"+\": Divergences[\"+\"] }\n >\n : never\n : ArrayUnionDivergence<Rest, To, BestKey, Acc, Divergences>\n : OmitNever<Divergences> extends infer Result\n ? {} extends Result\n ? never\n : Result\n : never;\n\nexport type UnionDivergence<From, To, Acc extends any[]> = ArrayUnionDivergence<\n UnionToArray<From>,\n To,\n FindBestKeyForMatching<Extract<To, object>, Extract<From, object>>,\n Acc\n>;\n\ntype IsAtLeastOneUnion<L, R> = IsUnion<L> extends true\n ? true\n : IsUnion<R> extends true\n ? true\n : false;\n\nexport type IsNever<T> = [T] extends [never] ? true : false;\n\ntype AtLeastOneEmptyObject<L, R> = {} extends Required<L>\n ? true\n : {} extends Required<R>\n ? true\n : false;\n\ntype EmptyObjectDivergence<From, To> = [{}, {}] extends [From, To]\n ? never\n : [From, \"!=\", To];\n\ntype SimpleDivergence<From, To> = From extends To ? never : [From, \"!=\", To];\n\n// ARRAY\n\ntype AtLeastOneArray<From, To> = From extends Array<unknown>\n ? true\n : To extends Array<unknown>\n ? true\n : false;\n\ntype ArrayDivergence<From, To, Acc extends any[]> = From extends Array<infer F>\n ? To extends Array<infer T>\n ? Divergence<F, T, Acc> extends infer D\n ? IsNever<D> extends true\n ? never\n : { [key: number]: D }\n : never\n : [\"[]?\", Divergence<F, To, Acc>]\n : To extends Array<infer T>\n ? [\"[]!\", Divergence<From, T, Acc>]\n : never;\n\ntype Equals<T, U> = [T] extends [U] ? ([U] extends [T] ? true : false) : false;\n\ntype Has<Item, Array extends any[]> = Array extends [infer F, ...infer R]\n ? Equals<Item, F> extends true\n ? true\n : Has<Item, R>\n : false;\n\ntype Primitive = string | number | boolean | null | undefined | Date;\n\ntype AtLeastOnePrimitive<From, To> = From extends Primitive\n ? true\n : To extends Primitive\n ? true\n : false;\n\ntype PrimitiveDivergence<From, To> = AtLeastOnePrimitive<From, To> extends true\n ? SimpleDivergence<From, To>\n : never;\n\n// DIVERGENCE\nexport type Divergence<From, To, Acc extends any[] = []> = Equals<\n From,\n To\n> extends true\n ? never\n : Acc[\"length\"] extends 20\n ? { error: \"Max depth reached\" }\n : Has<From, [To, ...Acc]> extends true\n ? never\n : [IsNever<From>, IsNever<To>] extends [false, false]\n ? AtLeastOneArray<From, To> extends true\n ? ArrayDivergence<From, To, [...Acc, From]>\n : [IsIndexedType<From>, IsIndexedType<To>] extends [true, true]\n ? IndexedTypeDiff<From, To, [...Acc, From]>\n : IsAtLeastOneUnion<From, To> extends true\n ? UnionDivergence<From, To, Acc>\n : AtLeastOnePrimitive<From, To> extends true\n ? PrimitiveDivergence<From, To>\n : AtLeastOneEmptyObject<From, To> extends true\n ? EmptyObjectDivergence<From, To>\n : [From, To] extends [object, object]\n ? ObjectDivergence<From, To, [...Acc, From]>\n : SimpleDivergence<From, To>\n : {};\n"]}
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
{
|
|
4
|
-
// it should return never when left and right are the same
|
|
5
|
-
const a = {};
|
|
6
|
-
const b = {};
|
|
7
|
-
const c = {};
|
|
8
|
-
// const d: never = {} as Divergence<[], []>;
|
|
9
|
-
const e = {};
|
|
10
|
-
const f = {};
|
|
11
|
-
const g = {};
|
|
12
|
-
}
|
|
13
|
-
{
|
|
14
|
-
const error = ["", "!=", 0];
|
|
15
|
-
}
|
|
16
|
-
{
|
|
17
|
-
const error = {
|
|
18
|
-
a: ["", "!=", 0],
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
{
|
|
22
|
-
const error = {
|
|
23
|
-
b: {
|
|
24
|
-
c: [0, "!=", ""],
|
|
25
|
-
},
|
|
26
|
-
};
|
|
27
|
-
}
|
|
28
|
-
{
|
|
29
|
-
const error = {
|
|
30
|
-
a: [{}, "!=", ""],
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
{
|
|
34
|
-
const error = {
|
|
35
|
-
a: ["", "!=", { a: true }],
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
{
|
|
39
|
-
const error = {
|
|
40
|
-
b: {
|
|
41
|
-
"-d": "",
|
|
42
|
-
},
|
|
43
|
-
};
|
|
44
|
-
}
|
|
45
|
-
{
|
|
46
|
-
const error = {
|
|
47
|
-
a: ["", "!=", 0],
|
|
48
|
-
b: {
|
|
49
|
-
c: [0, "!=", ""],
|
|
50
|
-
},
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
{
|
|
54
|
-
const a = undefined;
|
|
55
|
-
}
|
|
56
|
-
{
|
|
57
|
-
const error = {
|
|
58
|
-
a: {
|
|
59
|
-
b: {
|
|
60
|
-
c: {
|
|
61
|
-
"+": { e: "" },
|
|
62
|
-
},
|
|
63
|
-
},
|
|
64
|
-
},
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
{
|
|
68
|
-
const error = {
|
|
69
|
-
a: {
|
|
70
|
-
b: {
|
|
71
|
-
c: {
|
|
72
|
-
d: {
|
|
73
|
-
"+": "",
|
|
74
|
-
},
|
|
75
|
-
},
|
|
76
|
-
},
|
|
77
|
-
},
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
{
|
|
81
|
-
const check = true;
|
|
82
|
-
}
|
|
83
|
-
{
|
|
84
|
-
const error = {
|
|
85
|
-
a: {
|
|
86
|
-
b: [
|
|
87
|
-
{
|
|
88
|
-
c: {
|
|
89
|
-
"~": { b: [0, "!=", ""], type: "b" },
|
|
90
|
-
},
|
|
91
|
-
},
|
|
92
|
-
],
|
|
93
|
-
},
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
{
|
|
97
|
-
const check = true;
|
|
98
|
-
}
|
|
99
|
-
{
|
|
100
|
-
const check = true;
|
|
101
|
-
}
|
|
102
|
-
{
|
|
103
|
-
const check = {};
|
|
104
|
-
}
|
|
105
|
-
{
|
|
106
|
-
const check = true;
|
|
107
|
-
}
|
|
108
|
-
{
|
|
109
|
-
const check = true;
|
|
110
|
-
}
|
|
111
|
-
{
|
|
112
|
-
const check = true;
|
|
113
|
-
}
|
|
114
|
-
it("this is a type test file", () => {
|
|
115
|
-
expect(true).toBe(true);
|
|
116
|
-
});
|
|
117
|
-
//# sourceMappingURL=divergence.spec.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"divergence.spec.js","sourceRoot":"","sources":["../../src/divergence/divergence.spec.ts"],"names":[],"mappings":";;AAIA,CAAC;IACC,0DAA0D;IAC1D,MAAM,CAAC,GAAU,EAAgC,CAAC;IAClD,MAAM,CAAC,GAAU,EAAgC,CAAC;IAClD,MAAM,CAAC,GAAU,EAAwB,CAAC;IAC1C,6CAA6C;IAC7C,MAAM,CAAC,GAAU,EAA4B,CAAC;IAC9C,MAAM,CAAC,GAAU,EAAkD,CAAC;IAIpE,MAAM,CAAC,GAAU,EAAwB,CAAC;AAC5C,CAAC;AAED,CAAC;IAMC,MAAM,KAAK,GAAM,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjC,CAAC;AAED,CAAC;IAMC,MAAM,KAAK,GAAM;QACf,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;KACjB,CAAC;AACJ,CAAC;AAED,CAAC;IAMC,MAAM,KAAK,GAAM;QACf,CAAC,EAAE;YACD,CAAC,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC;SACjB;KACF,CAAC;AACJ,CAAC;AAED,CAAC;IAMC,MAAM,KAAK,GAAM;QACf,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC;KAClB,CAAC;AACJ,CAAC;AAED,CAAC;IAMC,MAAM,KAAK,GAAM;QACf,CAAC,EAAE,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC;KAC3B,CAAC;AACJ,CAAC;AAED,CAAC;IAMC,MAAM,KAAK,GAAM;QACf,CAAC,EAAE;YACD,IAAI,EAAE,EAAE;SACT;KACF,CAAC;AACJ,CAAC;AAED,CAAC;IAMC,MAAM,KAAK,GAA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I,CAAC;AAC1C,CAAC;AAED,EAAE,CAAC,0BAA0B,EAAE,GAAG,EAAE;IAClC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC,CAAC,CAAC","sourcesContent":["import { Divergence, type UnionDivergence } from \"./divergence\";\n\ntype Equals<X, Y> = [X] extends [Y] ? ([Y] extends [X] ? true : false) : false;\n\n{\n // it should return never when left and right are the same\n const a: never = {} as Divergence<string, string>;\n const b: never = {} as Divergence<number, number>;\n const c: never = {} as Divergence<{}, {}>;\n // const d: never = {} as Divergence<[], []>;\n const e: never = {} as Divergence<true, true>;\n const f: never = {} as Divergence<string | number, number | string>;\n\n type ga = { a: string | number } | { b: string };\n type gb = { a: number | string } | { b: string };\n const g: never = {} as Divergence<ga, gb>;\n}\n\n{\n // it should detect top level differences\n type L = string;\n type R = number;\n type D = Divergence<L, R>;\n\n const error: D = [\"\", \"!=\", 0];\n}\n\n{\n // it should detect shallow differences\n type L = { a: string };\n type R = { a: number };\n type D = Divergence<L, R>;\n\n const error: D = {\n a: [\"\", \"!=\", 0],\n };\n}\n\n{\n // it should detect deep differences\n type L = { a: string; b: { c: number } };\n type R = { a: string; b: { c: string } };\n type D = Divergence<L, R>;\n\n const error: D = {\n b: {\n c: [0, \"!=\", \"\"],\n },\n };\n}\n\n{\n // it should detect when left is an object but right isnt\n type L = { a: {} };\n type R = { a: string };\n type D = Divergence<L, R>;\n\n const error: D = {\n a: [{}, \"!=\", \"\"],\n };\n}\n\n{\n // it should detect when right is an object but left isnt\n type L = { a: string };\n type R = { a: { a: true } };\n type D = Divergence<L, R>;\n\n const error: D = {\n a: [\"\", \"!=\", { a: true }],\n };\n}\n\n{\n // it should detect missing properties\n type L = { a: string; b: { c: number } };\n type R = { a: string; b: { c: number; d: string } };\n type D = Divergence<L, R>;\n\n const error: D = {\n b: {\n \"-d\": \"\",\n },\n };\n}\n\n{\n // it should detect multiple differences\n type L = { a: string; b: { c: number } };\n type R = { a: number; b: { c: string } };\n type D = Divergence<L, R>;\n\n const error: D = {\n a: [\"\", \"!=\", 0],\n b: {\n c: [0, \"!=\", \"\"],\n },\n };\n}\n\n{\n // it should not detect unions with compatible types\n type L = { type: \"room\"; thing: true } | { type: \"folder\"; other: true };\n type R =\n | { type: \"room\"; thing: true }\n | { type: \"folder\"; other: true | false };\n\n type D = Divergence<L, R>;\n const a: D = undefined as never;\n}\n\n{\n // it should detect deep unions with uncompatible types\n type L = { a: { b: { c: { d: number } | { e: string } } } };\n type R = { a: { b: { c: { d: number } | { e: number } } } };\n type D = Divergence<L, R>;\n\n const error: D = {\n a: {\n b: {\n c: {\n \"+\": { e: \"\" },\n },\n },\n },\n };\n}\n\n{\n type L = { a: { b: { c: { d: number | string } } } };\n type R = { a: { b: { c: { d: number } } } };\n type D = Divergence<L, R>;\n\n const error: D = {\n a: {\n b: {\n c: {\n d: {\n \"+\": \"\",\n },\n },\n },\n },\n };\n}\n\n{\n // it should detect diffs in unions\n\n type L = { type: \"a\"; a: string } | { type: \"b\"; b: number };\n type R = { type: \"a\"; a: string } | { type: \"b\"; b: string } | undefined;\n\n type D = Divergence<L, R>;\n\n type expected = {\n \"~\": {\n type: \"b\";\n b: [number, \"!=\", string];\n };\n };\n\n const check: Equals<D, expected> = true;\n}\n\n{\n type L = {\n a: {\n b: {\n c: { type: \"a\"; a: string } | { type: \"b\"; b: number };\n }[];\n };\n };\n\n type R = {\n a: {\n b: {\n c: { type: \"a\"; a: string } | { type: \"b\"; b: string };\n }[];\n };\n };\n\n type D = Divergence<L, R>;\n\n type check = D;\n\n const error: D = {\n a: {\n b: [\n {\n c: {\n \"~\": { b: [0, \"!=\", \"\"], type: \"b\" },\n },\n },\n ],\n },\n };\n}\n\n{\n type Rec<T> = { next: Rec<T>; value: T };\n\n type R = Rec<number>;\n type L = Rec<string>;\n\n type D = Divergence<L, R>;\n\n type expected = { value: [string, \"!=\", number] };\n\n const check: Equals<D, expected> = true;\n}\n\n{\n type Option<T> = { type: T; a: T };\n type Options =\n | Option<string>\n | Option<number>\n | Option<boolean>\n | Option<null>\n | Option<{\n a: string;\n b: number;\n }>;\n\n type Rec<T> = { next: Rec<T>; value: T };\n\n type L = {\n id: string;\n options: Rec<Options>;\n };\n\n type R = {\n id: string;\n options: Options;\n };\n\n type D = Divergence<L[\"options\"], R[\"options\"]>;\n\n type expected = {\n \"+\": Rec<Options>;\n };\n\n const check: Equals<D, expected> = true;\n}\n\n{\n type Recursive = {\n name: string;\n children: undefined | Recursive[];\n };\n\n type L = {\n a: Recursive[];\n };\n\n type R = {\n a: Recursive[];\n b: true;\n };\n\n // type Narrow<T extends A | B> = T;\n\n // type L = Narrow<B>;\n // type R = Narrow<A>;\n\n type D = Divergence<L, R>;\n\n type expected = never;\n\n const check: Equals<D, expected> = {} as never;\n}\n\n{\n // should not infinite recurse when no best key on union\n\n type L = { type: string; e: boolean };\n type R = { type: \"a\"; e: boolean } | { type: \"b\"; e: boolean };\n\n type D = Divergence<L, R>;\n\n type expected = { \"+\": L };\n const check: Equals<D, expected> = true;\n}\n\n{\n // should work with optional properties\n\n type L = { a?: { value: 1 } | { value: 2 } };\n type R = { a: { value: 1 } | { value: 3 } };\n\n type D = Divergence<L, R>;\n\n type expected = {\n a: {\n \"+\":\n | {\n value: 2;\n }\n | undefined;\n };\n };\n const check: Equals<D, expected> = true;\n}\n\n{\n type L =\n | undefined\n | ({ type: \"a\"; value: 1 } | { type: \"b\"; value: 2 } | { type: \"c\" })[]\n | ({ type: \"d\" } | { type: \"e\"; value: 4 })[];\n\n type R =\n | undefined\n | ({ type: \"a\"; value: 1 } | { type: \"b\"; value: 3 } | { type: \"c\" })[]\n | ({ type: \"d\" } | { type: \"e\" })[];\n\n type D = UnionDivergence<L, R, []>;\n\n type expected = {\n \"~\":\n | {\n [key: number]: {\n \"~\": {\n type: \"b\";\n value: [2, \"!=\", 3];\n };\n };\n }\n | {\n [key: number]: {\n \"~\": {\n type: \"e\";\n \"+value\": 4;\n };\n };\n };\n };\n\n const check: Equals<D, expected> = true;\n}\n\nit(\"this is a type test file\", () => {\n expect(true).toBe(true);\n});\n"]}
|
|
@@ -1,101 +0,0 @@
|
|
|
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
|
-
const ts_morph_1 = require("ts-morph");
|
|
7
|
-
const node_path_1 = require("node:path");
|
|
8
|
-
const explore_type_1 = require("../utils/explore-type");
|
|
9
|
-
const node_fs_1 = __importDefault(require("node:fs"));
|
|
10
|
-
const project_1 = require("./project");
|
|
11
|
-
const cwd = process.cwd();
|
|
12
|
-
const decoratorFile = project_1.project.getSourceFile(`${__dirname}/../references/freeze.decorator.d.ts`);
|
|
13
|
-
if (!decoratorFile) {
|
|
14
|
-
throw new Error("The @Freeze decorator is not used in the project.");
|
|
15
|
-
}
|
|
16
|
-
const references = decoratorFile.getFunction("Freeze")?.findReferences();
|
|
17
|
-
if (!references) {
|
|
18
|
-
throw new Error("The @Freeze decorator is imported, but not used in the project.");
|
|
19
|
-
}
|
|
20
|
-
function lowercasefirstletter(str) {
|
|
21
|
-
return str.charAt(0).toLowerCase() + str.slice(1);
|
|
22
|
-
}
|
|
23
|
-
for (const ref of references) {
|
|
24
|
-
for (const refref of ref.getReferences()) {
|
|
25
|
-
const decorator = refref
|
|
26
|
-
.getNode()
|
|
27
|
-
.getParent()
|
|
28
|
-
?.getParent()
|
|
29
|
-
?.asKind(ts_morph_1.ts.SyntaxKind.Decorator);
|
|
30
|
-
if (!decorator)
|
|
31
|
-
continue;
|
|
32
|
-
const rpath = (0, node_path_1.relative)(cwd, decorator.getSourceFile().getFilePath());
|
|
33
|
-
const classDeclaration = decorator.getParentIfKind(ts_morph_1.ts.SyntaxKind.ClassDeclaration);
|
|
34
|
-
if (!classDeclaration)
|
|
35
|
-
continue;
|
|
36
|
-
const typeParameter = decorator.getTypeArguments()[0];
|
|
37
|
-
if (typeParameter) {
|
|
38
|
-
console.log(`${classDeclaration.getName()}: Already frozen with <${typeParameter.getText()}>`);
|
|
39
|
-
continue;
|
|
40
|
-
}
|
|
41
|
-
const serializeProperty = classDeclaration
|
|
42
|
-
.getType()
|
|
43
|
-
.getProperty("serialize");
|
|
44
|
-
if (!serializeProperty) {
|
|
45
|
-
console.log(`${rpath} - ${classDeclaration.getName()}: No serialize property`);
|
|
46
|
-
continue;
|
|
47
|
-
}
|
|
48
|
-
const serializeMethod = project_1.project
|
|
49
|
-
.getTypeChecker()
|
|
50
|
-
.getTypeOfSymbolAtLocation(serializeProperty, classDeclaration)
|
|
51
|
-
.getCallSignatures()[0];
|
|
52
|
-
let serialized = serializeMethod.getReturnType();
|
|
53
|
-
if (serialized.getSymbol()?.getName() === "Promise") {
|
|
54
|
-
serialized = serialized.getTypeArguments()[0];
|
|
55
|
-
}
|
|
56
|
-
const version = serialized
|
|
57
|
-
.getProperty("version")
|
|
58
|
-
?.getTypeAtLocation(classDeclaration)
|
|
59
|
-
.getText();
|
|
60
|
-
if (!version || Number.isNaN(Number(version))) {
|
|
61
|
-
console.log(`${rpath} - ${classDeclaration.getName()}: No version property (or not a number) : ${version}`);
|
|
62
|
-
continue;
|
|
63
|
-
}
|
|
64
|
-
console.log(`${rpath} - ${classDeclaration.getName()}: Freezing with version ${version}`);
|
|
65
|
-
const other = new Map();
|
|
66
|
-
const result = (0, explore_type_1.exploreType)(serialized.compilerType, project_1.project.getTypeChecker().compilerObject, other);
|
|
67
|
-
const type = serializeMethod
|
|
68
|
-
.getParameters()[0]
|
|
69
|
-
.getTypeAtLocation(classDeclaration);
|
|
70
|
-
const symbol = type.getSymbol()?.getName();
|
|
71
|
-
const aliasSymbol = type.getAliasSymbol()?.getName();
|
|
72
|
-
let name;
|
|
73
|
-
if (symbol) {
|
|
74
|
-
name = symbol;
|
|
75
|
-
console.log(`${rpath} - ${classDeclaration.getName()}: Using symbol ${symbol}`);
|
|
76
|
-
}
|
|
77
|
-
else if (aliasSymbol) {
|
|
78
|
-
name = aliasSymbol;
|
|
79
|
-
console.log(`${rpath} - ${classDeclaration.getName()}: Using aliasSymbol ${aliasSymbol}`);
|
|
80
|
-
}
|
|
81
|
-
if (!name) {
|
|
82
|
-
console.log(`${rpath} - ${classDeclaration.getName()}: Cannot find name of serialized type`);
|
|
83
|
-
continue;
|
|
84
|
-
}
|
|
85
|
-
const serializedName = `${name}Serialized${version}n`;
|
|
86
|
-
const serializedFilename = lowercasefirstletter(`${name}.serialized.${version}n`);
|
|
87
|
-
const directory = refref.getSourceFile().getDirectory();
|
|
88
|
-
decorator.getSourceFile().addImportDeclaration({
|
|
89
|
-
moduleSpecifier: `./${serializedFilename}`,
|
|
90
|
-
namedImports: [serializedName],
|
|
91
|
-
});
|
|
92
|
-
decorator.addTypeArgument(serializedName);
|
|
93
|
-
project_1.project.saveSync();
|
|
94
|
-
const output = [
|
|
95
|
-
...other.values(),
|
|
96
|
-
`export type ${serializedName} = ${result}`,
|
|
97
|
-
].join("\n");
|
|
98
|
-
node_fs_1.default.writeFileSync(`${directory.getPath()}/${serializedFilename}.ts`, output);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
//# sourceMappingURL=freeze-decorator.entrypoint.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"freeze-decorator.entrypoint.js","sourceRoot":"","sources":["../../src/entrypoints/freeze-decorator.entrypoint.ts"],"names":[],"mappings":";;;;;AAAA,uCAA8B;AAC9B,yCAAqC;AACrC,wDAAoD;AACpD,sDAAyB;AACzB,uCAAoC;AAEpC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;AAE1B,MAAM,aAAa,GAAG,iBAAO,CAAC,aAAa,CAAC,GAAG,SAAS,sCAAsC,CAAC,CAAC;AAChG,IAAI,CAAC,aAAa,EAAE,CAAC;IACnB,MAAM,IAAI,KAAK,CAAC,mD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AAe,cAAc,MAAM,MAAM,EAAE;SAC5C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEb,iBAAE,CAAC,aAAa,CAAC,GAAG,SAAS,CAAC,OAAO,EAAE,IAAI,kBAAkB,KAAK,EAAE,MAAM,CAAC,CAAC;IAC9E,CAAC;AACH,CAAC","sourcesContent":["import { ts } from \"ts-morph\";\nimport { relative } from \"node:path\";\nimport { exploreType } from \"../utils/explore-type\";\nimport fs from \"node:fs\";\nimport { project } from \"./project\";\n\nconst cwd = process.cwd();\n\nconst decoratorFile = project.getSourceFile(`${__dirname}/../references/freeze.decorator.d.ts`);\nif (!decoratorFile) {\n throw new Error(\"The @Freeze decorator is not used in the project.\");\n}\n\nconst references = decoratorFile.getFunction(\"Freeze\")?.findReferences();\n\nif (!references) {\n throw new Error(\n \"The @Freeze decorator is imported, but not used in the project.\",\n );\n}\n\nfunction lowercasefirstletter(str: string) {\n return str.charAt(0).toLowerCase() + str.slice(1);\n}\n\nfor (const ref of references) {\n for (const refref of ref.getReferences()) {\n const decorator = refref\n .getNode()\n .getParent()\n ?.getParent()\n ?.asKind(ts.SyntaxKind.Decorator);\n if (!decorator) continue;\n\n const rpath = relative(cwd, decorator.getSourceFile().getFilePath());\n\n const classDeclaration = decorator.getParentIfKind(\n ts.SyntaxKind.ClassDeclaration,\n );\n if (!classDeclaration) continue;\n\n const typeParameter = decorator.getTypeArguments()[0];\n if (typeParameter) {\n console.log(\n `${classDeclaration.getName()}: Already frozen with <${typeParameter.getText()}>`,\n );\n continue;\n }\n\n const serializeProperty = classDeclaration\n .getType()\n .getProperty(\"serialize\");\n if (!serializeProperty) {\n console.log(\n `${rpath} - ${classDeclaration.getName()}: No serialize property`,\n );\n continue;\n }\n\n const serializeMethod = project\n .getTypeChecker()\n .getTypeOfSymbolAtLocation(serializeProperty, classDeclaration)\n .getCallSignatures()[0];\n\n let serialized = serializeMethod.getReturnType();\n if (serialized.getSymbol()?.getName() === \"Promise\") {\n serialized = serialized.getTypeArguments()[0];\n }\n\n const version = serialized\n .getProperty(\"version\")\n ?.getTypeAtLocation(classDeclaration)\n .getText();\n\n if (!version || Number.isNaN(Number(version))) {\n console.log(\n `${rpath} - ${classDeclaration.getName()}: No version property (or not a number) : ${version}`,\n );\n continue;\n }\n\n console.log(\n `${rpath} - ${classDeclaration.getName()}: Freezing with version ${version}`,\n );\n const other = new Map();\n const result = exploreType(\n serialized.compilerType as any,\n project.getTypeChecker().compilerObject as any,\n other,\n );\n\n const type = serializeMethod\n .getParameters()[0]\n .getTypeAtLocation(classDeclaration);\n const symbol = type.getSymbol()?.getName();\n const aliasSymbol = type.getAliasSymbol()?.getName();\n let name: string | undefined;\n if (symbol) {\n name = symbol;\n console.log(\n `${rpath} - ${classDeclaration.getName()}: Using symbol ${symbol}`,\n );\n } else if (aliasSymbol) {\n name = aliasSymbol;\n console.log(\n `${rpath} - ${classDeclaration.getName()}: Using aliasSymbol ${aliasSymbol}`,\n );\n }\n\n if (!name) {\n console.log(\n `${rpath} - ${classDeclaration.getName()}: Cannot find name of serialized type`,\n );\n continue;\n }\n\n const serializedName = `${name}Serialized${version}n`;\n const serializedFilename = lowercasefirstletter(\n `${name}.serialized.${version}n`,\n );\n\n const directory = refref.getSourceFile().getDirectory();\n\n decorator.getSourceFile().addImportDeclaration({\n moduleSpecifier: `./${serializedFilename}`,\n namedImports: [serializedName],\n });\n\n decorator.addTypeArgument(serializedName);\n\n project.saveSync();\n\n const output = [\n ...other.values(),\n `export type ${serializedName} = ${result}`,\n ].join(\"\\n\");\n\n fs.writeFileSync(`${directory.getPath()}/${serializedFilename}.ts`, output);\n }\n}\n"]}
|
|
@@ -1,87 +0,0 @@
|
|
|
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
|
-
const ts_morph_1 = require("ts-morph");
|
|
7
|
-
const node_path_1 = require("node:path");
|
|
8
|
-
const node_fs_1 = __importDefault(require("node:fs"));
|
|
9
|
-
const explore_type_1 = require("../utils/explore-type");
|
|
10
|
-
const get_pretty_type_1 = require("../utils/get-pretty-type");
|
|
11
|
-
const project_1 = require("./project");
|
|
12
|
-
const cwd = process.cwd();
|
|
13
|
-
const functionFile = project_1.project.getSourceFile(`${__dirname}/../references/freeze.function.d.ts`);
|
|
14
|
-
if (!functionFile) {
|
|
15
|
-
throw new Error("The freeze function is not used in the project.");
|
|
16
|
-
}
|
|
17
|
-
const references = functionFile.getFunction("freeze")?.findReferences();
|
|
18
|
-
if (!references) {
|
|
19
|
-
throw new Error("The freeze function is imported, but not used in the project.");
|
|
20
|
-
}
|
|
21
|
-
function lowercasefirstletter(str) {
|
|
22
|
-
return str.charAt(0).toLowerCase() + str.slice(1);
|
|
23
|
-
}
|
|
24
|
-
for (const ref of references) {
|
|
25
|
-
for (const refref of ref.getReferences()) {
|
|
26
|
-
const callExpression = refref
|
|
27
|
-
.getNode()
|
|
28
|
-
.getParentIfKind(ts_morph_1.ts.SyntaxKind.CallExpression);
|
|
29
|
-
if (!callExpression)
|
|
30
|
-
continue;
|
|
31
|
-
const rpath = (0, node_path_1.relative)(cwd, callExpression.getSourceFile().getFilePath());
|
|
32
|
-
const typeArguments = callExpression.getTypeArguments();
|
|
33
|
-
const freezeParameters = typeArguments[0].asKind(ts_morph_1.ts.SyntaxKind.TypeLiteral);
|
|
34
|
-
const alreadyFrozen = typeArguments[1];
|
|
35
|
-
if (!freezeParameters) {
|
|
36
|
-
console.log(`${rpath}:${callExpression.getStartLineNumber()}: No freeze parameters`);
|
|
37
|
-
continue;
|
|
38
|
-
}
|
|
39
|
-
const nameProperty = freezeParameters.getProperty("name");
|
|
40
|
-
if (!nameProperty) {
|
|
41
|
-
console.log(`${rpath}:${callExpression.getStartLineNumber()}: No name property`);
|
|
42
|
-
continue;
|
|
43
|
-
}
|
|
44
|
-
const name = nameProperty.getType().getLiteralValue();
|
|
45
|
-
if (typeof name !== "string") {
|
|
46
|
-
console.log(`${rpath}:${callExpression.getStartLineNumber()}: Name is not a string literal`);
|
|
47
|
-
continue;
|
|
48
|
-
}
|
|
49
|
-
if (alreadyFrozen) {
|
|
50
|
-
console.log(`${rpath} - ${name}: Already frozen with <${alreadyFrozen.getText()}>`);
|
|
51
|
-
continue;
|
|
52
|
-
}
|
|
53
|
-
const typeProperty = freezeParameters.getProperty("type");
|
|
54
|
-
if (!typeProperty) {
|
|
55
|
-
console.log(`${rpath} - ${name}: No type property`);
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
const type = typeProperty.getType();
|
|
59
|
-
const prettyType = (0, get_pretty_type_1.getPrettyType)(type, callExpression);
|
|
60
|
-
const other = new Map();
|
|
61
|
-
let result = (0, explore_type_1.exploreType)(prettyType.type.compilerType, project_1.project.getTypeChecker().compilerObject, other);
|
|
62
|
-
const aliasName = prettyType.alias.getName();
|
|
63
|
-
prettyType.dispose();
|
|
64
|
-
for (const [key, value] of other) {
|
|
65
|
-
if (key.name !== aliasName)
|
|
66
|
-
continue;
|
|
67
|
-
result = result.replace(new RegExp(`\\b${aliasName}\\b`, "g"), value.replace(new RegExp(`^type ${aliasName} = `), ""));
|
|
68
|
-
other.delete(key);
|
|
69
|
-
}
|
|
70
|
-
const serializedName = name;
|
|
71
|
-
const serializedFilename = lowercasefirstletter(`${name}.serialized`);
|
|
72
|
-
const directory = refref.getSourceFile().getDirectory();
|
|
73
|
-
callExpression.getSourceFile().addImportDeclaration({
|
|
74
|
-
moduleSpecifier: `./${serializedFilename}`,
|
|
75
|
-
namedImports: [serializedName],
|
|
76
|
-
});
|
|
77
|
-
callExpression.addTypeArgument(serializedName);
|
|
78
|
-
project_1.project.saveSync();
|
|
79
|
-
const output = [
|
|
80
|
-
...other.values(),
|
|
81
|
-
`export type ${serializedName} = ${result}`,
|
|
82
|
-
].join("\n");
|
|
83
|
-
node_fs_1.default.writeFileSync(`${directory.getPath()}/${serializedFilename}.ts`, output);
|
|
84
|
-
console.log(`${rpath} - ${name}: Frozen as ${serializedName} in ${serializedFilename}.ts`);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
//# sourceMappingURL=freeze-function.entrypoint.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"freeze-function.entrypoint.js","sourceRoot":"","sources":["../../src/entrypoints/freeze-function.entrypoint.ts"],"names":[],"mappings":";;;;;AAAA,uCAA8B;AAC9B,yCAAqC;AACrC,sDAAyB;AACzB,wDAAoD;AACpD,8DAAyD;AACzD,uCAAoC;AAEpC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;AAE1B,MAAM,YAAY,GAAG,iBAAO,CAAC,aAAa,CAAC,GAAG,SAAS,qCAAqC,CAAC,CAAC;AAC9F,IAAI,CAAC,YAAY,EAAE,CAAC;IAClB,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,GAAG,YAAY,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,cAAc,EAAE,CAAC;AAExE,IAAI,CAAC,UAAU,EAAE,CAAC;IAChB,MAAM,IAAI,KAAK,CACb,+DAA+D,CAChE,CAAC;AACJ,CAAC;AAED,SAAS,oBAAoB,CAAC,GAAW;IACvC,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACpD,CAAC;AAED,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;IAC7B,KAAK,MAAM,MAAM,IAAI,GAAG,CAAC,aAAa,EAAE,EAAE,CAAC;QACzC,MAAM,cAAc,GAAG,MAAM;aAC1B,OAAO,EAAE;aACT,eAAe,CAAC,aAAE,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QACjD,IAAI,CAAC,cAAc;YAAE,SAAS;QAE9B,MAA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,CAAC;QAE/C,iBAAO,CAAC,QAAQ,EAAE,CAAC;QAEnB,MAAM,MAAM,GAAG;YACb,GAAG,KAAK,CAAC,MAAM,EAAE;YACjB,eAAe,cAAc,MAAM,MAAM,EAAE;SAC5C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEb,iBAAE,CAAC,aAAa,CAAC,GAAG,SAAS,CAAC,OAAO,EAAE,IAAI,kBAAkB,KAAK,EAAE,MAAM,CAAC,CAAC;QAE5E,OAAO,CAAC,GAAG,CACT,GAAG,KAAK,MAAM,IAAI,eAAe,cAAc,OAAO,kBAAkB,KAAK,CAC9E,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { ts } from \"ts-morph\";\nimport { relative } from \"node:path\";\nimport fs from \"node:fs\";\nimport { exploreType } from \"../utils/explore-type\";\nimport { getPrettyType } from \"../utils/get-pretty-type\";\nimport { project } from \"./project\";\n\nconst cwd = process.cwd();\n\nconst functionFile = project.getSourceFile(`${__dirname}/../references/freeze.function.d.ts`);\nif (!functionFile) {\n throw new Error(\"The freeze function is not used in the project.\");\n}\n\nconst references = functionFile.getFunction(\"freeze\")?.findReferences();\n\nif (!references) {\n throw new Error(\n \"The freeze function is imported, but not used in the project.\",\n );\n}\n\nfunction lowercasefirstletter(str: string) {\n return str.charAt(0).toLowerCase() + str.slice(1);\n}\n\nfor (const ref of references) {\n for (const refref of ref.getReferences()) {\n const callExpression = refref\n .getNode()\n .getParentIfKind(ts.SyntaxKind.CallExpression);\n if (!callExpression) continue;\n\n const rpath = relative(cwd, callExpression.getSourceFile().getFilePath());\n\n const typeArguments = callExpression.getTypeArguments();\n\n const freezeParameters = typeArguments[0].asKind(ts.SyntaxKind.TypeLiteral);\n const alreadyFrozen = typeArguments[1];\n\n if (!freezeParameters) {\n console.log(\n `${rpath}:${callExpression.getStartLineNumber()}: No freeze parameters`,\n );\n continue;\n }\n\n const nameProperty = freezeParameters.getProperty(\"name\");\n if (!nameProperty) {\n console.log(\n `${rpath}:${callExpression.getStartLineNumber()}: No name property`,\n );\n continue;\n }\n const name = nameProperty.getType().getLiteralValue();\n if (typeof name !== \"string\") {\n console.log(\n `${rpath}:${callExpression.getStartLineNumber()}: Name is not a string literal`,\n );\n continue;\n }\n\n if (alreadyFrozen) {\n console.log(\n `${rpath} - ${name}: Already frozen with <${alreadyFrozen.getText()}>`,\n );\n continue;\n }\n\n const typeProperty = freezeParameters.getProperty(\"type\");\n if (!typeProperty) {\n console.log(\n `${rpath} - ${name}: No type property`,\n );\n continue;\n }\n const type = typeProperty.getType();\n\n const prettyType = getPrettyType(type, callExpression);\n\n const other = new Map();\n let result = exploreType(\n prettyType.type.compilerType,\n project.getTypeChecker().compilerObject,\n other,\n );\n const aliasName = prettyType.alias.getName();\n prettyType.dispose();\n for (const [key, value] of other) {\n if (key.name !== aliasName) continue;\n result = result.replace(new RegExp(`\\\\b${aliasName}\\\\b`, \"g\"), value.replace(new RegExp(`^type ${aliasName} = `), \"\"));\n other.delete(key);\n }\n\n const serializedName = name;\n const serializedFilename = lowercasefirstletter(\n `${name}.serialized`,\n );\n\n const directory = refref.getSourceFile().getDirectory();\n\n callExpression.getSourceFile().addImportDeclaration({\n moduleSpecifier: `./${serializedFilename}`,\n namedImports: [serializedName],\n });\n\n callExpression.addTypeArgument(serializedName);\n\n project.saveSync();\n\n const output = [\n ...other.values(),\n `export type ${serializedName} = ${result}`,\n ].join(\"\\n\");\n\n fs.writeFileSync(`${directory.getPath()}/${serializedFilename}.ts`, output);\n\n console.log(\n `${rpath} - ${name}: Frozen as ${serializedName} in ${serializedFilename}.ts`,\n );\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"freeze.entrypoint.js","sourceRoot":"","sources":["../../src/entrypoints/freeze.entrypoint.ts"],"names":[],"mappings":";;AAAA,yCAAuC;AACvC,wCAAsC","sourcesContent":["import './freeze-decorator.entrypoint';\nimport './freeze-function.entrypoint';\n"]}
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.project = void 0;
|
|
4
|
-
const ts_morph_1 = require("ts-morph");
|
|
5
|
-
const cwd = process.cwd();
|
|
6
|
-
const tsConfigFilePath = `${cwd}/tsconfig.json`;
|
|
7
|
-
exports.project = new ts_morph_1.Project({
|
|
8
|
-
tsConfigFilePath,
|
|
9
|
-
});
|
|
10
|
-
//# sourceMappingURL=project.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"project.js","sourceRoot":"","sources":["../../src/entrypoints/project.ts"],"names":[],"mappings":";;;AAAA,uCAAmC;AAEnC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;AAC1B,MAAM,gBAAgB,GAAG,GAAG,GAAG,gBAAgB,CAAC;AAEnC,QAAA,OAAO,GAAG,IAAI,kBAAO,CAAC;IACjC,gBAAgB;CACjB,CAAC,CAAC","sourcesContent":["import { Project } from \"ts-morph\";\n\nconst cwd = process.cwd();\nconst tsConfigFilePath = `${cwd}/tsconfig.json`;\n\nexport const project = new Project({\n tsConfigFilePath,\n});\n"]}
|
package/dist/freeze.spec.js
DELETED
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
-
};
|
|
38
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
const ts = __importStar(require("typescript"));
|
|
40
|
-
const explore_type_1 = require("./utils/explore-type");
|
|
41
|
-
const node_assert_1 = __importDefault(require("node:assert"));
|
|
42
|
-
function findCalls(source) {
|
|
43
|
-
const children = source.getChildren();
|
|
44
|
-
const innerCalls = children.flatMap((c) => findCalls(c));
|
|
45
|
-
if (ts.isCallExpression(source)) {
|
|
46
|
-
innerCalls.push(source);
|
|
47
|
-
}
|
|
48
|
-
return innerCalls;
|
|
49
|
-
}
|
|
50
|
-
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
|
51
|
-
function testFreeze(id, value) {
|
|
52
|
-
const file = __filename;
|
|
53
|
-
const program = ts.createProgram([file], { strictNullChecks: true });
|
|
54
|
-
const checker = program.getTypeChecker();
|
|
55
|
-
// biome-ignore lint/style/noNonNullAssertion: <explanation>
|
|
56
|
-
const sourceFile = program
|
|
57
|
-
.getSourceFiles()
|
|
58
|
-
.find((s) => s.fileName.includes(file));
|
|
59
|
-
const test = findCalls(sourceFile).find((c) => c.getText().startsWith("testFreeze") &&
|
|
60
|
-
c.arguments[0].getText().includes(id));
|
|
61
|
-
node_assert_1.default.ok(test, `Could not find testFreeze call with id ${id}`);
|
|
62
|
-
const toFreeze = test.arguments[1];
|
|
63
|
-
const type = checker.getTypeAtLocation(toFreeze);
|
|
64
|
-
// Explore the type definition
|
|
65
|
-
const other = new Map();
|
|
66
|
-
const explored = (0, explore_type_1.exploreType)(type, checker, other);
|
|
67
|
-
const typeDefinitions = [...other.values()].join("\n");
|
|
68
|
-
return `${typeDefinitions}\ntype Output = ${explored};`;
|
|
69
|
-
}
|
|
70
|
-
describe("freeze", () => {
|
|
71
|
-
it("should freeze a value", () => {
|
|
72
|
-
const result = testFreeze("1", { a: 1, b: new Date() });
|
|
73
|
-
expect(result).toEqual("\ntype Output = { a: number; b: Date; };");
|
|
74
|
-
});
|
|
75
|
-
it("should freeze a value with a nested object", () => {
|
|
76
|
-
const result = testFreeze("2", {});
|
|
77
|
-
expect(result).toEqual([
|
|
78
|
-
"type Thing = { a: number; b: { c: number; }; }",
|
|
79
|
-
"type Output = Thing;",
|
|
80
|
-
].join("\n"));
|
|
81
|
-
});
|
|
82
|
-
it("should freeze a value with a nested array", () => {
|
|
83
|
-
const result = testFreeze("3", {});
|
|
84
|
-
expect(result).toEqual([
|
|
85
|
-
"type Thing = { a: number; b: (number)[]; }",
|
|
86
|
-
"type Output = Thing;",
|
|
87
|
-
].join("\n"));
|
|
88
|
-
});
|
|
89
|
-
it("should freeze a value referencing another one", () => {
|
|
90
|
-
const result = testFreeze("4", {});
|
|
91
|
-
expect(result).toEqual([
|
|
92
|
-
"type Thing = { a: string; }",
|
|
93
|
-
"type OtherThing = { b: Thing; }",
|
|
94
|
-
"type Output = OtherThing;",
|
|
95
|
-
].join("\n"));
|
|
96
|
-
});
|
|
97
|
-
it("should freeze a value referencing another one 2", () => {
|
|
98
|
-
const result = testFreeze("41", {});
|
|
99
|
-
expect(result).toEqual(["type Thing = { a: Thing; }", "type Output = Thing;"].join("\n"));
|
|
100
|
-
});
|
|
101
|
-
it("should freeze a cross-recursive value", () => {
|
|
102
|
-
const result = testFreeze("5", {});
|
|
103
|
-
expect(result).toEqual([
|
|
104
|
-
"type Thing = { a: number; b: OtherThing; }",
|
|
105
|
-
"type OtherThing = { c: Thing; }",
|
|
106
|
-
"type Output = OtherThing;",
|
|
107
|
-
].join("\n"));
|
|
108
|
-
});
|
|
109
|
-
it("should freeze a value with a nested union", () => {
|
|
110
|
-
const result = testFreeze("6", {});
|
|
111
|
-
expect(result).toEqual([
|
|
112
|
-
"type Thing = { a: number; b: string | number; c: (string | number)[]; }",
|
|
113
|
-
"type Output = Thing;",
|
|
114
|
-
].join("\n"));
|
|
115
|
-
});
|
|
116
|
-
it("should freeze a value with a nested intersection", () => {
|
|
117
|
-
const result = testFreeze("7", {});
|
|
118
|
-
expect(result).toEqual([
|
|
119
|
-
`type Thing = { a: number; b: { a: "1"; } & { b: "2"; }; }`,
|
|
120
|
-
"type Output = Thing;",
|
|
121
|
-
].join("\n"));
|
|
122
|
-
});
|
|
123
|
-
it("should freeze a readonly array", () => {
|
|
124
|
-
const result = testFreeze("9", {});
|
|
125
|
-
expect(result).toEqual([
|
|
126
|
-
"type Thing = { a: number; b: readonly (number)[]; }",
|
|
127
|
-
"type Output = Thing;",
|
|
128
|
-
].join("\n"));
|
|
129
|
-
});
|
|
130
|
-
it("should freeze a readonly object", () => {
|
|
131
|
-
const result = testFreeze("10", {});
|
|
132
|
-
expect(result).toEqual([
|
|
133
|
-
"type Thing = { readonly a: number; readonly b: readonly ({ readonly c: number; })[]; }",
|
|
134
|
-
"type Output = Thing;",
|
|
135
|
-
].join("\n"));
|
|
136
|
-
});
|
|
137
|
-
it.skip("should freeze a value with a nested tuple", () => {
|
|
138
|
-
const result = testFreeze("8", {});
|
|
139
|
-
expect(result).toEqual([
|
|
140
|
-
"type Thing = { a: number; b: [number, number]; c: readonly [number, number]; }",
|
|
141
|
-
"type Output = Thing;",
|
|
142
|
-
].join("\n"));
|
|
143
|
-
});
|
|
144
|
-
it("should support indexed object types", () => {
|
|
145
|
-
const result = testFreeze("11", {});
|
|
146
|
-
expect(result).toEqual([
|
|
147
|
-
"type Thing = { [key: string]: number; test: number; }",
|
|
148
|
-
"type Output = Thing;",
|
|
149
|
-
].join("\n"));
|
|
150
|
-
});
|
|
151
|
-
it("should support records", () => {
|
|
152
|
-
const result = testFreeze("12", {});
|
|
153
|
-
expect(result).toEqual(["", "type Output = Record<string, number>;"].join("\n"));
|
|
154
|
-
});
|
|
155
|
-
it("should coalesce enum members to their value", () => {
|
|
156
|
-
let Thing;
|
|
157
|
-
(function (Thing) {
|
|
158
|
-
Thing["A"] = "0";
|
|
159
|
-
Thing[Thing["B"] = 1] = "B";
|
|
160
|
-
Thing[Thing["C"] = 2] = "C";
|
|
161
|
-
})(Thing || (Thing = {}));
|
|
162
|
-
const resultA = testFreeze("13", Thing.A);
|
|
163
|
-
expect(resultA).toEqual(["", 'type Output = "0";'].join("\n"));
|
|
164
|
-
const resultB = testFreeze("14", Thing.B);
|
|
165
|
-
expect(resultB).toEqual(["", "type Output = 1;"].join("\n"));
|
|
166
|
-
});
|
|
167
|
-
// it("should freeze a value referencing a generic", () => {
|
|
168
|
-
// const thing = (a: number) => ({ a });
|
|
169
|
-
// type OtherThing = { b: ReturnType<typeof thing> };
|
|
170
|
-
// const result = testFreeze("13", {} as OtherThing);
|
|
171
|
-
// expect(result).toEqual(
|
|
172
|
-
// ["type Thing<T> = { a: T; }", "type Output = Thing<number>;"].join("\n"),
|
|
173
|
-
// );
|
|
174
|
-
// });
|
|
175
|
-
it("should freeze string literal types", () => {
|
|
176
|
-
const result = testFreeze("15", {});
|
|
177
|
-
expect(result).toEqual(["", 'type Output = undefined | "a";'].join("\n"));
|
|
178
|
-
});
|
|
179
|
-
it.skip("should freeze a generic", () => {
|
|
180
|
-
const result = testFreeze("16", {});
|
|
181
|
-
expect(result).toEqual(["type Thing<T> = { a: T; }", "type Output = Thing<number>;"].join("\n"));
|
|
182
|
-
});
|
|
183
|
-
});
|
|
184
|
-
//# sourceMappingURL=freeze.spec.js.map
|
package/dist/freeze.spec.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"freeze.spec.js","sourceRoot":"","sources":["../src/freeze.spec.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAiC;AACjC,uDAAmD;AACnD,8DAAiC;AAEjC,SAAS,SAAS,CAAC,MAAe;IAChC,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;IACtC,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACzD,IAAI,EAAE,CAAC,gBAAgB,CAAC,MAAM,CAAC,EAAE,CAAC;QAChC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1B,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,4DAA4D;AAC5D,SAAS,UAAU,CAAC,EAAU,EAAE,KAAU;IACxC,MAAM,IAAI,GAAG,UAAU,CAAC;IAExB,MAAM,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC,CAAC;IACrE,MAAM,OAAO,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAEzC,4DAA4D;IAC5D,MAAM,UAAU,GAAG,OAAO;SACvB,cAAc,EAAE;SAChB,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC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AC5D,yCAAyC;IACzC,sDAAsD;IAEtD,sDAAsD;IAEtD,2BAA2B;IAC3B,8EAA8E;IAC9E,MAAM;IACN,MAAM;IAEN,EAAE,CAAC,oCAAoC,EAAE,GAAG,EAAE;QAC5C,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,EAAE,EAAqB,CAAC,CAAC;QACvD,MAAM,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,gCAAgC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,IAAI,CAAC,yBAAyB,EAAE,GAAG,EAAE;QAGtC,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,EAAE,EAAmB,CAAC,CAAC;QAErD,MAAM,CAAC,MAAM,CAAC,CAAC,OAAO,CACpB,CAAC,2BAA2B,EAAE,8BAA8B,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CACzE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import * as ts from \"typescript\";\nimport { exploreType } from \"./utils/explore-type\";\nimport assert from \"node:assert\";\n\nfunction findCalls(source: ts.Node): ts.CallExpression[] {\n const children = source.getChildren();\n const innerCalls = children.flatMap((c) => findCalls(c));\n if (ts.isCallExpression(source)) {\n innerCalls.push(source);\n }\n return innerCalls;\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: <explanation>\nfunction testFreeze(id: string, value: any) {\n const file = __filename;\n\n const program = ts.createProgram([file], { strictNullChecks: true });\n const checker = program.getTypeChecker();\n\n // biome-ignore lint/style/noNonNullAssertion: <explanation>\n const sourceFile = program\n .getSourceFiles()\n .find((s) => s.fileName.includes(file))!;\n\n const test = findCalls(sourceFile).find((c) =>\n c.getText().startsWith(\"testFreeze\") &&\n c.arguments[0].getText().includes(id),\n );\n assert.ok(test, `Could not find testFreeze call with id ${id}`);\n const toFreeze = test.arguments[1];\n\n const type = checker.getTypeAtLocation(toFreeze);\n\n // Explore the type definition\n const other = new Map();\n const explored = exploreType(type, checker, other);\n const typeDefinitions = [...other.values()].join(\"\\n\");\n return `${typeDefinitions}\\ntype Output = ${explored};`;\n}\n\ndescribe(\"freeze\", () => {\n it(\"should freeze a value\", () => {\n const result = testFreeze(\"1\", { a: 1, b: new Date() });\n\n expect(result).toEqual(\"\\ntype Output = { a: number; b: Date; };\");\n });\n\n it(\"should freeze a value with a nested object\", () => {\n type Thing = { a: number; b: { c: number } };\n\n const result = testFreeze(\"2\", {} as Thing);\n\n expect(result).toEqual(\n [\n \"type Thing = { a: number; b: { c: number; }; }\",\n \"type Output = Thing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should freeze a value with a nested array\", () => {\n type Thing = { a: number; b: number[] };\n\n const result = testFreeze(\"3\", {} as Thing);\n\n expect(result).toEqual(\n [\n \"type Thing = { a: number; b: (number)[]; }\",\n \"type Output = Thing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should freeze a value referencing another one\", () => {\n type Thing = { a: string };\n type OtherThing = { b: Thing };\n\n const result = testFreeze(\"4\", {} as OtherThing);\n\n expect(result).toEqual(\n [\n \"type Thing = { a: string; }\",\n \"type OtherThing = { b: Thing; }\",\n \"type Output = OtherThing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should freeze a value referencing another one 2\", () => {\n type Thing = { a: Thing };\n const result = testFreeze(\"41\", {} as Thing);\n\n expect(result).toEqual(\n [\"type Thing = { a: Thing; }\", \"type Output = Thing;\"].join(\"\\n\"),\n );\n });\n\n it(\"should freeze a cross-recursive value\", () => {\n type Thing = { a: number; b: OtherThing };\n type OtherThing = { c: Thing };\n\n const result = testFreeze(\"5\", {} as OtherThing);\n\n expect(result).toEqual(\n [\n \"type Thing = { a: number; b: OtherThing; }\",\n \"type OtherThing = { c: Thing; }\",\n \"type Output = OtherThing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should freeze a value with a nested union\", () => {\n type Thing = { a: number; b: string | number; c: (string | number)[] };\n\n const result = testFreeze(\"6\", {} as Thing);\n\n expect(result).toEqual(\n [\n \"type Thing = { a: number; b: string | number; c: (string | number)[]; }\",\n \"type Output = Thing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should freeze a value with a nested intersection\", () => {\n type Thing = { a: number; b: { a: \"1\" } & { b: \"2\" } };\n\n const result = testFreeze(\"7\", {} as Thing);\n\n expect(result).toEqual(\n [\n `type Thing = { a: number; b: { a: \"1\"; } & { b: \"2\"; }; }`,\n \"type Output = Thing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should freeze a readonly array\", () => {\n type Thing = { a: number; b: readonly number[] };\n\n const result = testFreeze(\"9\", {} as Thing);\n\n expect(result).toEqual(\n [\n \"type Thing = { a: number; b: readonly (number)[]; }\",\n \"type Output = Thing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should freeze a readonly object\", () => {\n type Thing = {\n readonly a: number;\n readonly b: readonly { readonly c: number }[];\n };\n\n const result = testFreeze(\"10\", {} as Thing);\n\n expect(result).toEqual(\n [\n \"type Thing = { readonly a: number; readonly b: readonly ({ readonly c: number; })[]; }\",\n \"type Output = Thing;\",\n ].join(\"\\n\"),\n );\n });\n\n it.skip(\"should freeze a value with a nested tuple\", () => {\n type Thing = {\n a: number;\n b: [number, number];\n c: readonly [number, number];\n };\n\n const result = testFreeze(\"8\", {} as Thing);\n\n expect(result).toEqual(\n [\n \"type Thing = { a: number; b: [number, number]; c: readonly [number, number]; }\",\n \"type Output = Thing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should support indexed object types\", () => {\n type Thing = { [key: string]: number; test: number };\n const result = testFreeze(\"11\", {} as Thing);\n expect(result).toEqual(\n [\n \"type Thing = { [key: string]: number; test: number; }\",\n \"type Output = Thing;\",\n ].join(\"\\n\"),\n );\n });\n\n it(\"should support records\", () => {\n type Thing = Record<string, number>;\n const result = testFreeze(\"12\", {} as Thing);\n expect(result).toEqual(\n [\"\", \"type Output = Record<string, number>;\"].join(\"\\n\"),\n );\n });\n\n it(\"should coalesce enum members to their value\", () => {\n enum Thing {\n A = \"0\",\n B = 1,\n C = 2,\n }\n const resultA = testFreeze(\"13\", Thing.A);\n expect(resultA).toEqual([\"\", 'type Output = \"0\";'].join(\"\\n\"));\n\n const resultB = testFreeze(\"14\", Thing.B);\n expect(resultB).toEqual([\"\", \"type Output = 1;\"].join(\"\\n\"));\n });\n\n // it(\"should freeze a value referencing a generic\", () => {\n // \tconst thing = (a: number) => ({ a });\n // \ttype OtherThing = { b: ReturnType<typeof thing> };\n\n // \tconst result = testFreeze(\"13\", {} as OtherThing);\n\n // \texpect(result).toEqual(\n // \t\t[\"type Thing<T> = { a: T; }\", \"type Output = Thing<number>;\"].join(\"\\n\"),\n // \t);\n // });\n\n it(\"should freeze string literal types\", () => {\n const result = testFreeze(\"15\", {} as \"a\" | undefined);\n expect(result).toEqual([\"\", 'type Output = undefined | \"a\";'].join(\"\\n\"));\n });\n\n it.skip(\"should freeze a generic\", () => {\n type Thing<T> = { a: T };\n\n const result = testFreeze(\"16\", {} as Thing<number>);\n\n expect(result).toEqual(\n [\"type Thing<T> = { a: T; }\", \"type Output = Thing<number>;\"].join(\"\\n\"),\n );\n });\n});\n"]}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,kEAAuD;AAA9C,0GAAA,MAAM,OAAA;AACf,gEAAsD;AAA7C,yGAAA,MAAM,OAAA","sourcesContent":["export { Freeze } from \"./references/freeze.decorator\";\nexport { freeze } from \"./references/freeze.function\";\nexport { type Divergence } from \"./divergence/divergence\";\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"freeze.decorator.js","sourceRoot":"","sources":["../../src/references/freeze.decorator.ts"],"names":[],"mappings":";;AAQA,wBAaC;AAbD,SAAgB,MAAM;IACpB,OAAO,CAIL,MAAS,EAKD,EAAE;QACV,OAAO,MAAa,CAAC;IACvB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { Divergence, Expand, IsNever } from \"../divergence/divergence\";\n\ntype Freezable<T> = {\n serialize(...args: any[]): T;\n};\n\ntype Ctor<T> = abstract new (...args: any[]) => T;\n\nexport function Freeze<Frozen = any>() {\n return <\n C extends Ctor<Freezable<any>>,\n Serialized extends Awaited<ReturnType<InstanceType<C>[\"serialize\"]>>,\n >(\n target: C,\n ): Divergence<Serialized, Frozen> extends infer D\n ? IsNever<D> extends true\n ? C\n : Expand<D>\n : never => {\n return target as any;\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"freeze.function.js","sourceRoot":"","sources":["../../src/references/freeze.function.ts"],"names":[],"mappings":";;AAOA,wBASK;AATL,SAAgB,MAAM,CAIpB,GAAG,KAIK,IACN,CAAC","sourcesContent":["import type { Divergence, Expand, IsNever } from \"../divergence/divergence\";\n\ntype FreezeParameters<T, NAME extends string> = {\n type: T;\n name: NAME;\n}\n\nexport function freeze<\n T extends FreezeParameters<any, string>,\n FROZEN = never,\n>(\n ..._args: Divergence<T['type'], NoInfer<FROZEN>> extends infer D\n ? IsNever<D> extends true\n ? [{}]\n : [Expand<D>]\n : [{}]\n) { }\n"]}
|
|
@@ -1,151 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
-
var ownKeys = function(o) {
|
|
20
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
-
var ar = [];
|
|
22
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
-
return ar;
|
|
24
|
-
};
|
|
25
|
-
return ownKeys(o);
|
|
26
|
-
};
|
|
27
|
-
return function (mod) {
|
|
28
|
-
if (mod && mod.__esModule) return mod;
|
|
29
|
-
var result = {};
|
|
30
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
-
__setModuleDefault(result, mod);
|
|
32
|
-
return result;
|
|
33
|
-
};
|
|
34
|
-
})();
|
|
35
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.exploreType = exploreType;
|
|
37
|
-
const ts = __importStar(require("typescript"));
|
|
38
|
-
function exploreType(type, checker, declarations = new Map(), seen = new Set(["Date", "Record"])) {
|
|
39
|
-
// seen.add(type.symbol?.getName() || "");
|
|
40
|
-
if (type.aliasSymbol && seen.has(type.aliasSymbol.getName())) {
|
|
41
|
-
const a = type.aliasTypeArguments;
|
|
42
|
-
return `${type.aliasSymbol.name}${a
|
|
43
|
-
? `<${a
|
|
44
|
-
.map((a) => exploreType(a, checker, declarations, seen))
|
|
45
|
-
.join(", ")}>`
|
|
46
|
-
: ""}`;
|
|
47
|
-
}
|
|
48
|
-
if (type.aliasSymbol) {
|
|
49
|
-
const aliasType = checker.getDeclaredTypeOfSymbol(type.aliasSymbol);
|
|
50
|
-
seen.add(type.aliasSymbol.getName());
|
|
51
|
-
const definition = exploreNativeType(aliasType, checker, declarations, seen);
|
|
52
|
-
declarations.set(type.aliasSymbol, `type ${type.aliasSymbol.name} = ${definition}`);
|
|
53
|
-
return exploreType(aliasType, checker, declarations, seen);
|
|
54
|
-
}
|
|
55
|
-
return exploreNativeType(type, checker, declarations, seen);
|
|
56
|
-
}
|
|
57
|
-
const PrimitiveFlag = 402784252;
|
|
58
|
-
function exploreNativeType(type, checker, declarations = new Map(), seen = new Set()) {
|
|
59
|
-
if (type.flags & ts.TypeFlags.EnumLiteral) {
|
|
60
|
-
const v = type.value;
|
|
61
|
-
if (typeof v === "string") {
|
|
62
|
-
return `"${v}"`;
|
|
63
|
-
}
|
|
64
|
-
return v;
|
|
65
|
-
}
|
|
66
|
-
if (type.flags & PrimitiveFlag) {
|
|
67
|
-
return checker.typeToString(type);
|
|
68
|
-
}
|
|
69
|
-
if (type.isUnionOrIntersection()) {
|
|
70
|
-
const operator = type.isUnion() ? "|" : "&";
|
|
71
|
-
return type.types
|
|
72
|
-
.map((t) => exploreType(t, checker, declarations, seen))
|
|
73
|
-
.join(` ${operator} `);
|
|
74
|
-
}
|
|
75
|
-
if (type.getSymbol()?.getName() === "ReadonlyArray") {
|
|
76
|
-
const typeReference = type;
|
|
77
|
-
const elementType = typeReference.typeArguments
|
|
78
|
-
? typeReference.typeArguments[0]
|
|
79
|
-
: undefined;
|
|
80
|
-
return elementType
|
|
81
|
-
? `readonly (${exploreType(elementType, checker, declarations, seen)})[]`
|
|
82
|
-
: "ReadonlyArray<any>";
|
|
83
|
-
}
|
|
84
|
-
if (checker.isTupleType(type)) {
|
|
85
|
-
const typeReference = type;
|
|
86
|
-
const elementTypes = typeReference.typeArguments || [];
|
|
87
|
-
return `[${elementTypes
|
|
88
|
-
.map((t) => exploreType(t, checker, declarations, seen))
|
|
89
|
-
.join(", ")}]`;
|
|
90
|
-
}
|
|
91
|
-
if (checker.isArrayType(type)) {
|
|
92
|
-
const typeReference = type;
|
|
93
|
-
const elementType = typeReference.typeArguments
|
|
94
|
-
? typeReference.typeArguments[0]
|
|
95
|
-
: undefined;
|
|
96
|
-
return elementType
|
|
97
|
-
? `(${exploreType(elementType, checker, declarations, seen)})[]`
|
|
98
|
-
: "any[]";
|
|
99
|
-
}
|
|
100
|
-
if (type.aliasTypeArguments) {
|
|
101
|
-
const typeReference = type;
|
|
102
|
-
const elementTypes = typeReference.aliasTypeArguments || [];
|
|
103
|
-
return `${type.aliasSymbol?.name}<${elementTypes
|
|
104
|
-
.map((t) => t.symbol.name)
|
|
105
|
-
.join(", ")}>`;
|
|
106
|
-
}
|
|
107
|
-
if (type.getSymbol()?.getName() === "Date") {
|
|
108
|
-
return "Date";
|
|
109
|
-
}
|
|
110
|
-
if (type.flags & ts.TypeFlags.Object) {
|
|
111
|
-
const properties = checker.getPropertiesOfType(type);
|
|
112
|
-
const indexInfos = checker.getIndexInfosOfType(type);
|
|
113
|
-
let index = "";
|
|
114
|
-
if (indexInfos.length > 0) {
|
|
115
|
-
const indexInfo = indexInfos[0];
|
|
116
|
-
const indexType = indexInfo.keyType;
|
|
117
|
-
const indexTypeString = exploreType(indexType, checker, declarations, seen);
|
|
118
|
-
const valueType = indexInfo.type;
|
|
119
|
-
const valueTypeString = exploreType(valueType, checker, declarations, seen);
|
|
120
|
-
index = `[key: ${indexTypeString}]: ${valueTypeString}; `;
|
|
121
|
-
}
|
|
122
|
-
return `{ ${index}${properties.reduce((acc, property) => {
|
|
123
|
-
const propertyType = checker.getTypeOfSymbol(property);
|
|
124
|
-
const optional = property.flags & ts.SymbolFlags.Optional ? "?" : "";
|
|
125
|
-
const readonly = property
|
|
126
|
-
.getDeclarations()
|
|
127
|
-
?.some((declaration) => ts.isPropertySignature(declaration) &&
|
|
128
|
-
declaration.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ReadonlyKeyword))
|
|
129
|
-
? "readonly "
|
|
130
|
-
: "";
|
|
131
|
-
return `${acc}${readonly}${property.name}${optional}: ${exploreType(propertyType, checker, declarations, seen)}; `;
|
|
132
|
-
}, "")}}`;
|
|
133
|
-
}
|
|
134
|
-
if (type.flags & ts.TypeFlags.TypeParameter) {
|
|
135
|
-
return type.symbol.name;
|
|
136
|
-
}
|
|
137
|
-
return JSON.stringify({
|
|
138
|
-
name: checker.typeToString(type),
|
|
139
|
-
flags: listTypeFlagsNames(type.flags),
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
function listTypeFlagsNames(flags) {
|
|
143
|
-
const names = [];
|
|
144
|
-
for (const flagName in ts.TypeFlags) {
|
|
145
|
-
if (ts.TypeFlags[flagName] & flags) {
|
|
146
|
-
names.push([flagName, ts.TypeFlags[flagName]]);
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
return names;
|
|
150
|
-
}
|
|
151
|
-
//# sourceMappingURL=explore-type.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"explore-type.js","sourceRoot":"","sources":["../../src/utils/explore-type.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,kCAmCC;AArCD,+CAAiC;AAEjC,SAAgB,WAAW,CACzB,IAAa,EACb,OAAuB,EACvB,eAAuC,IAAI,GAAG,EAAE,EAChD,OAAoB,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAE/C,0CAA0C;IAC1C,IAAI,IAAI,CAAC,WAAW,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;QAC7D,MAAM,CAAC,GAAG,IAAI,CAAC,kBAAkB,CAAC;QAClC,OAAO,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,GAC7B,CAAC;YACC,CAAC,CAAC,IAAI,CAAC;iBACF,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,YAAY,EAAE,IAAI,CAAC,CAAC;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,CAAC,IAAI,CAAC,KAAK,CAAC;KACtC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAa;IACvC,MAAM,KAAK,GAAG,EAAE,CAAC;IACjB,KAAK,MAAM,QAAQ,IAAI,EAAE,CAAC,SAAS,EAAE,CAAC;QACpC,IAAK,EAAE,CAAC,SAAS,CAAC,QAAe,CAAS,GAAG,KAAK,EAAE,CAAC;YACnD,KAAK,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,SAAS,CAAC,QAAe,CAAC,CAAC,CAAC,CAAC;QACxD,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import * as ts from \"typescript\";\n\nexport function exploreType(\n type: ts.Type,\n checker: ts.TypeChecker,\n declarations: Map<ts.Symbol, string> = new Map(),\n seen: Set<string> = new Set([\"Date\", \"Record\"]),\n): string {\n // seen.add(type.symbol?.getName() || \"\");\n if (type.aliasSymbol && seen.has(type.aliasSymbol.getName())) {\n const a = type.aliasTypeArguments;\n return `${type.aliasSymbol.name}${\n a\n ? `<${a\n .map((a) => exploreType(a, checker, declarations, seen))\n .join(\", \")}>`\n : \"\"\n }`;\n }\n\n if (type.aliasSymbol) {\n const aliasType = checker.getDeclaredTypeOfSymbol(type.aliasSymbol);\n seen.add(type.aliasSymbol.getName());\n const definition = exploreNativeType(\n aliasType,\n checker,\n declarations,\n seen,\n );\n declarations.set(\n type.aliasSymbol,\n `type ${type.aliasSymbol.name} = ${definition}`,\n );\n return exploreType(aliasType, checker, declarations, seen);\n }\n\n return exploreNativeType(type, checker, declarations, seen);\n}\n\nconst PrimitiveFlag = 402784252;\n\nfunction exploreNativeType(\n type: ts.Type,\n checker: ts.TypeChecker,\n declarations: Map<ts.Symbol, string> = new Map(),\n seen: Set<string> = new Set(),\n): string {\n if (type.flags & ts.TypeFlags.EnumLiteral) {\n const v = (type as any).value;\n if (typeof v === \"string\") {\n return `\"${v}\"`;\n }\n return v;\n }\n\n if (type.flags & PrimitiveFlag) {\n return checker.typeToString(type);\n }\n if (type.isUnionOrIntersection()) {\n const operator = type.isUnion() ? \"|\" : \"&\";\n return type.types\n .map((t) => exploreType(t, checker, declarations, seen))\n .join(` ${operator} `);\n }\n\n if (type.getSymbol()?.getName() === \"ReadonlyArray\") {\n const typeReference = type as ts.TypeReference;\n const elementType = typeReference.typeArguments\n ? typeReference.typeArguments[0]\n : undefined;\n return elementType\n ? `readonly (${exploreType(elementType, checker, declarations, seen)})[]`\n : \"ReadonlyArray<any>\";\n }\n\n if (checker.isTupleType(type)) {\n const typeReference = type as ts.TypeReference;\n const elementTypes = typeReference.typeArguments || [];\n return `[${elementTypes\n .map((t) => exploreType(t, checker, declarations, seen))\n .join(\", \")}]`;\n }\n\n if (checker.isArrayType(type)) {\n const typeReference = type as ts.TypeReference;\n const elementType = typeReference.typeArguments\n ? typeReference.typeArguments[0]\n : undefined;\n return elementType\n ? `(${exploreType(elementType, checker, declarations, seen)})[]`\n : \"any[]\";\n }\n\n if (type.aliasTypeArguments) {\n const typeReference = type as ts.TypeReference;\n const elementTypes = typeReference.aliasTypeArguments || [];\n return `${type.aliasSymbol?.name}<${elementTypes\n .map((t) => t.symbol.name)\n .join(\", \")}>`;\n }\n\n if (type.getSymbol()?.getName() === \"Date\") {\n return \"Date\";\n }\n\n if (type.flags & ts.TypeFlags.Object) {\n const properties = checker.getPropertiesOfType(type);\n\n const indexInfos = checker.getIndexInfosOfType(type);\n\n let index = \"\";\n if (indexInfos.length > 0) {\n const indexInfo = indexInfos[0];\n const indexType = indexInfo.keyType;\n const indexTypeString = exploreType(\n indexType,\n checker,\n declarations,\n seen,\n );\n const valueType = indexInfo.type;\n const valueTypeString = exploreType(\n valueType,\n checker,\n declarations,\n seen,\n );\n index = `[key: ${indexTypeString}]: ${valueTypeString}; `;\n }\n\n return `{ ${index}${properties.reduce((acc, property) => {\n const propertyType = checker.getTypeOfSymbol(property);\n const optional = property.flags & ts.SymbolFlags.Optional ? \"?\" : \"\";\n const readonly = property\n .getDeclarations()\n ?.some(\n (declaration) =>\n ts.isPropertySignature(declaration) &&\n declaration.modifiers?.some(\n (modifier) => modifier.kind === ts.SyntaxKind.ReadonlyKeyword,\n ),\n )\n ? \"readonly \"\n : \"\";\n return `${acc}${readonly}${property.name}${optional}: ${exploreType(\n propertyType,\n checker,\n declarations,\n seen,\n )}; `;\n }, \"\")}}`;\n }\n\n if (type.flags & ts.TypeFlags.TypeParameter) {\n return (type as ts.TypeParameter).symbol.name;\n }\n\n return JSON.stringify({\n name: checker.typeToString(type),\n flags: listTypeFlagsNames(type.flags),\n });\n}\n\nfunction listTypeFlagsNames(flags: number) {\n const names = [];\n for (const flagName in ts.TypeFlags) {\n if ((ts.TypeFlags[flagName as any] as any) & flags) {\n names.push([flagName, ts.TypeFlags[flagName as any]]);\n }\n }\n return names;\n}\n"]}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getPrettyType = getPrettyType;
|
|
4
|
-
const ts_morph_1 = require("ts-morph");
|
|
5
|
-
function getPrettyType(type, contextNode) {
|
|
6
|
-
const project = contextNode.getProject();
|
|
7
|
-
const checker = project.getTypeChecker().compilerObject;
|
|
8
|
-
const typeTextForEmbedding = checker.typeToString(type.compilerType, contextNode.compilerNode, ts_morph_1.ts.TypeFormatFlags.NoTruncation |
|
|
9
|
-
ts_morph_1.ts.TypeFormatFlags.UseFullyQualifiedType |
|
|
10
|
-
ts_morph_1.ts.TypeFormatFlags.InTypeAlias);
|
|
11
|
-
const fileName = `__pretty_${Date.now()}_${Math.random().toString(16).slice(2)}.ts`;
|
|
12
|
-
const sf = project.createSourceFile(fileName, `
|
|
13
|
-
type Pretty<T> = { [K in keyof T]: T[K] } & {};
|
|
14
|
-
declare const __v: ${typeTextForEmbedding};
|
|
15
|
-
export type __X = Pretty<typeof __v>;
|
|
16
|
-
`, { overwrite: true });
|
|
17
|
-
const alias = sf.getTypeAliasOrThrow("__X");
|
|
18
|
-
const pretty = alias.getType();
|
|
19
|
-
const dispose = () => {
|
|
20
|
-
project.removeSourceFile(sf);
|
|
21
|
-
};
|
|
22
|
-
return { type: pretty, alias, dispose };
|
|
23
|
-
}
|
|
24
|
-
//# sourceMappingURL=get-pretty-type.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"get-pretty-type.js","sourceRoot":"","sources":["../../src/utils/get-pretty-type.ts"],"names":[],"mappings":";;AAEA,sCAmCC;AArCD,uCAAyE;AAEzE,SAAgB,aAAa,CAAC,IAAU,EAAE,WAAiB;IAKzD,MAAM,OAAO,GAAY,WAAW,CAAC,UAAU,EAAE,CAAC;IAClD,MAAM,OAAO,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,cAAc,CAAC;IAExD,MAAM,oBAAoB,GAAG,OAAO,CAAC,YAAY,CAC/C,IAAI,CAAC,YAAY,EACjB,WAAW,CAAC,YAAY,EACxB,aAAE,CAAC,eAAe,CAAC,YAAY;QAC/B,aAAE,CAAC,eAAe,CAAC,qBAAqB;QACxC,aAAE,CAAC,eAAe,CAAC,WAAW,CAC/B,CAAC;IAEF,MAAM,QAAQ,GAAG,YAAY,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC;IACpF,MAAM,EAAE,GAAG,OAAO,CAAC,gBAAgB,CACjC,QAAQ,EACR;;2BAEuB,oBAAoB;;KAE1C,EACD,EAAE,SAAS,EAAE,IAAI,EAAE,CACpB,CAAC;IAEF,MAAM,KAAK,GAAG,EAAE,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC;IAC5C,MAAM,MAAM,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;IAE/B,MAAM,OAAO,GAAG,GAAG,EAAE;QACnB,OAAO,CAAC,gBAAgB,CAAC,EAAE,CAAC,CAAC;IAC/B,CAAC,CAAC;IAEF,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["import { Type, TypeAliasDeclaration, Project, ts, Node } from \"ts-morph\";\n\nexport function getPrettyType(type: Type, contextNode: Node): {\n type: Type;\n alias: TypeAliasDeclaration;\n dispose: () => void;\n} {\n const project: Project = contextNode.getProject();\n const checker = project.getTypeChecker().compilerObject;\n\n const typeTextForEmbedding = checker.typeToString(\n type.compilerType,\n contextNode.compilerNode,\n ts.TypeFormatFlags.NoTruncation |\n ts.TypeFormatFlags.UseFullyQualifiedType |\n ts.TypeFormatFlags.InTypeAlias\n );\n\n const fileName = `__pretty_${Date.now()}_${Math.random().toString(16).slice(2)}.ts`;\n const sf = project.createSourceFile(\n fileName,\n `\n type Pretty<T> = { [K in keyof T]: T[K] } & {};\n declare const __v: ${typeTextForEmbedding};\n export type __X = Pretty<typeof __v>;\n `,\n { overwrite: true }\n );\n\n const alias = sf.getTypeAliasOrThrow(\"__X\");\n const pretty = alias.getType();\n\n const dispose = () => {\n project.removeSourceFile(sf);\n };\n\n return { type: pretty, alias, dispose };\n}\n"]}
|