@snowtop/ent 0.1.0-alpha16 → 0.1.0-alpha24

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/core/ent.d.ts CHANGED
@@ -145,7 +145,7 @@ export declare class AssocEdgeData {
145
145
  edgeTable: string;
146
146
  constructor(data: Data);
147
147
  }
148
- export declare const assocEdgeLoader: DataLoader<any, any, any>;
148
+ export declare const assocEdgeLoader: DataLoader<ID, Data | null, ID>;
149
149
  export declare function loadEdgeData(edgeType: string): Promise<AssocEdgeData | null>;
150
150
  export declare function loadEdgeDatas(...edgeTypes: string[]): Promise<Map<string, AssocEdgeData>>;
151
151
  export interface AssocEdgeConstructor<T extends AssocEdge> {
@@ -172,8 +172,8 @@ interface loadEdgeForIDOptions<T extends AssocEdge> extends loadCustomEdgesOptio
172
172
  }
173
173
  export declare function loadEdgeForID2<T extends AssocEdge>(options: loadEdgeForIDOptions<T>): Promise<T | undefined>;
174
174
  export declare function loadNodesByEdge<T extends Ent>(viewer: Viewer, id1: ID, edgeType: string, options: LoadEntOptions<T>): Promise<T[]>;
175
- export declare function applyPrivacyPolicyForRow<T extends Ent>(viewer: Viewer, options: LoadEntOptions<T>, row: Data | null): Promise<T | null>;
176
- export declare function applyPrivacyPolicyForRowX<T extends Ent>(viewer: Viewer, options: LoadEntOptions<T>, row: Data): Promise<T>;
177
- export declare function applyPrivacyPolicyForRows<T extends Ent>(viewer: Viewer, rows: Data[], options: LoadEntOptions<T>): Promise<Map<ID, T>>;
175
+ export declare function applyPrivacyPolicyForRow<TEnt extends Ent<TViewer>, TViewer extends Viewer>(viewer: TViewer, options: LoadEntOptions<TEnt, TViewer>, row: Data | null): Promise<TEnt | null>;
176
+ export declare function applyPrivacyPolicyForRowX<TEnt extends Ent<TViewer>, TViewer extends Viewer>(viewer: TViewer, options: LoadEntOptions<TEnt, TViewer>, row: Data): Promise<TEnt>;
177
+ export declare function applyPrivacyPolicyForRows<TEnt extends Ent<TViewer>, TViewer extends Viewer>(viewer: TViewer, rows: Data[], options: LoadEntOptions<TEnt, TViewer>): Promise<Map<ID, TEnt>>;
178
178
  export declare function getEdgeTypeInGroup<T extends string>(viewer: Viewer, id1: ID, id2: ID, m: Map<T, string>): Promise<[T, AssocEdge] | undefined>;
179
179
  export {};
package/core/ent.js CHANGED
@@ -61,6 +61,7 @@ function createDataLoader(options) {
61
61
  if ((0, logger_1.logEnabled)("query")) {
62
62
  loaderOptions.cacheMap = new cacheMap(options);
63
63
  }
64
+ // something here brokwn with strict:true
64
65
  return new dataloader_1.default(async (ids) => {
65
66
  if (!ids.length) {
66
67
  return [];
@@ -436,6 +437,7 @@ class EditNodeOperation {
436
437
  constructor(options, existingEnt = null) {
437
438
  this.options = options;
438
439
  this.existingEnt = existingEnt;
440
+ this.row = null;
439
441
  this.placeholderID = options.placeholderID;
440
442
  }
441
443
  resolve(executor) {
@@ -474,6 +476,7 @@ class EditNodeOperation {
474
476
  this.row = await editRow(queryer, options, this.existingEnt.id, "RETURNING *");
475
477
  }
476
478
  else {
479
+ // @ts-ignore
477
480
  this.row = this.existingEnt["data"];
478
481
  }
479
482
  }
@@ -524,6 +527,7 @@ class EditNodeOperation {
524
527
  this.reloadRow(queryer, this.existingEnt.id, options);
525
528
  }
526
529
  else {
530
+ // @ts-ignore
527
531
  this.row = this.existingEnt["data"];
528
532
  }
529
533
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowtop/ent",
3
- "version": "0.1.0-alpha16",
3
+ "version": "0.1.0-alpha24",
4
4
  "description": "snowtop ent framework",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
package/schema/schema.js CHANGED
@@ -121,6 +121,7 @@ function getFieldsWithPrivacy(value, fieldMap) {
121
121
  m.set(info.dbCol, privacyPolicy);
122
122
  }
123
123
  }
124
+ return;
124
125
  }
125
126
  for (const name in fields) {
126
127
  const field = fields[name];
@@ -0,0 +1,36 @@
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 transform_1 = require("../tsc/transform");
7
+ const transform_schema_1 = require("../tsc/transform_schema");
8
+ const transform_ent_1 = require("../tsc/transform_ent");
9
+ const move_generated_1 = require("../tsc/move_generated");
10
+ const transform_action_1 = require("../tsc/transform_action");
11
+ const minimist_1 = __importDefault(require("minimist"));
12
+ const ast_1 = require("../tsc/ast");
13
+ // todo-sqlite
14
+ // ts-node-script --swc --project ./tsconfig.json -r tsconfig-paths/register ../../ts/src/scripts/migrate_v0.1.ts --transform_schema --old_base_class BaseEntTodoSchema --new_schema_class TodoEntSchema --transform_path src/schema/patterns/base
15
+ function main() {
16
+ const customInfo = (0, ast_1.getCustomInfo)();
17
+ const options = (0, minimist_1.default)(process.argv.slice(2));
18
+ // install 0.1.x dependencies
19
+ // maybe provide options to make this easier if someone wants to do this in steps to see what's happening
20
+ if (options.move_generated) {
21
+ (0, move_generated_1.moveGenerated)(customInfo.relativeImports);
22
+ }
23
+ // codegen write-all --disable-custom-graphql
24
+ if (options.transform_schema) {
25
+ (0, transform_1.transform)(new transform_schema_1.TransformSchema(customInfo.relativeImports, options.old_base_class, options.new_schema_class, options.transform_path));
26
+ }
27
+ // codegen write-all --disable-custom-graphql
28
+ if (options.transform_ent) {
29
+ (0, transform_1.transform)(new transform_ent_1.TransformEnt());
30
+ }
31
+ if (options.transform_action) {
32
+ (0, transform_1.transform)(new transform_action_1.TransformAction(customInfo));
33
+ }
34
+ // codegen write-all
35
+ }
36
+ main();
package/tsc/ast.d.ts CHANGED
@@ -15,18 +15,29 @@ interface transformOpts {
15
15
  removeImports?: string[];
16
16
  newImports?: string[];
17
17
  transform?: transformImportFn;
18
- transformPath?: string;
18
+ transformPath: string;
19
19
  }
20
- export declare function transformImport(fileContents: string, importNode: ts.ImportDeclaration, sourceFile: ts.SourceFile, opts?: transformOpts): string | undefined;
20
+ export declare function transformImport(fileContents: string, importNode: ts.ImportDeclaration, sourceFile: ts.SourceFile, opts: transformOpts): string | undefined;
21
21
  export declare function updateImportPath(fileContents: string, importNode: ts.ImportDeclaration, sourceFile: ts.SourceFile, newPath: string): string | undefined;
22
22
  export declare function isRelativeImport(node: ts.ImportDeclaration, sourceFile: ts.SourceFile): boolean;
23
23
  export declare function isRelativeGeneratedImport(node: ts.ImportDeclaration, sourceFile: ts.SourceFile): boolean;
24
+ export declare function isSrcGeneratedImport(node: ts.ImportDeclaration, sourceFile: ts.SourceFile): boolean;
24
25
  interface importInfo {
25
26
  imports: string[];
26
27
  start: number;
27
28
  end: number;
28
29
  importText: string;
29
30
  importPath: string;
31
+ default?: string;
30
32
  }
31
33
  export declare function getImportInfo(imp: ts.ImportDeclaration, sourceFile: ts.SourceFile): importInfo | undefined;
34
+ export declare function transformRelative(file: string, importPath: string, relative?: boolean): string;
35
+ export interface customInfo {
36
+ viewerInfo: {
37
+ path: string;
38
+ name: string;
39
+ };
40
+ relativeImports?: boolean;
41
+ }
42
+ export declare function getCustomInfo(): customInfo;
32
43
  export {};
package/tsc/ast.js CHANGED
@@ -1,10 +1,32 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
2
21
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
22
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
23
  };
5
24
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getImportInfo = exports.isRelativeGeneratedImport = exports.isRelativeImport = exports.updateImportPath = exports.transformImport = exports.getClassInfo = exports.getPreText = void 0;
25
+ exports.getCustomInfo = exports.transformRelative = exports.getImportInfo = exports.isSrcGeneratedImport = exports.isRelativeGeneratedImport = exports.isRelativeImport = exports.updateImportPath = exports.transformImport = exports.getClassInfo = exports.getPreText = void 0;
7
26
  const typescript_1 = __importDefault(require("typescript"));
27
+ const path = __importStar(require("path"));
28
+ const js_yaml_1 = require("js-yaml");
29
+ const fs = __importStar(require("fs"));
8
30
  function getPreText(fileContents, node, sourceFile) {
9
31
  return fileContents.substring(node.getFullStart(), node.getStart(sourceFile));
10
32
  }
@@ -31,8 +53,7 @@ function getClassInfo(fileContents, sourceFile, node) {
31
53
  }
32
54
  }
33
55
  }
34
- // we probably still don't need all of this...
35
- if (!className || !node.heritageClauses || !classExtends) {
56
+ if (!className) {
36
57
  return undefined;
37
58
  }
38
59
  let hasExport = false;
@@ -82,26 +103,22 @@ exports.getClassInfo = getClassInfo;
82
103
  function transformImport(fileContents, importNode, sourceFile, opts) {
83
104
  // remove quotes too
84
105
  const text = importNode.moduleSpecifier.getText(sourceFile).slice(1, -1);
85
- if (opts?.transformPath) {
86
- if (text !== opts.transformPath) {
87
- return;
88
- }
89
- }
90
- else {
91
- if (text !== "@snowtop/ent" &&
92
- text !== "@snowtop/ent/schema" &&
93
- text !== "@snowtop/ent/schema/") {
94
- return;
95
- }
106
+ if (text != opts.transformPath) {
107
+ return;
96
108
  }
97
109
  const impInfo = getImportInfo(importNode, sourceFile);
98
110
  if (!impInfo) {
99
111
  return;
100
112
  }
101
- const { imports, start, end, importText } = impInfo;
113
+ let { imports, start, end, importText, default: def } = impInfo;
102
114
  let removeImportsMap = {};
103
115
  if (opts?.removeImports) {
104
- opts.removeImports.forEach((imp) => (removeImportsMap[imp] = true));
116
+ opts.removeImports.forEach((imp) => {
117
+ removeImportsMap[imp] = true;
118
+ if (def === imp) {
119
+ def = "";
120
+ }
121
+ });
105
122
  }
106
123
  let finalImports = new Set();
107
124
  for (let i = 0; i < imports.length; i++) {
@@ -123,9 +140,13 @@ function transformImport(fileContents, importNode, sourceFile, opts) {
123
140
  const comment = getPreText(fileContents, importNode, sourceFile);
124
141
  return (comment +
125
142
  "import " +
126
- importText.substring(0, start + 1) +
143
+ // add default
144
+ (def || "") +
145
+ // should probably always be "{" now that we support default
146
+ (start >= 0 ? importText.substring(0, start + 1) : "{") +
127
147
  Array.from(finalImports).join(", ") +
128
- importText.substring(end) +
148
+ // should probably always be "}"
149
+ (end >= 0 ? importText.substring(end) : "}") +
129
150
  ' from "' +
130
151
  text +
131
152
  '";');
@@ -165,23 +186,79 @@ function isRelativeGeneratedImport(node, sourceFile) {
165
186
  text.indexOf("/generated") !== -1);
166
187
  }
167
188
  exports.isRelativeGeneratedImport = isRelativeGeneratedImport;
189
+ function isSrcGeneratedImport(node, sourceFile) {
190
+ const text = node.moduleSpecifier.getText(sourceFile).slice(1, -1);
191
+ return text.startsWith("src") && text.includes("/generated");
192
+ }
193
+ exports.isSrcGeneratedImport = isSrcGeneratedImport;
194
+ // TODO doesn't support default + {} yet
168
195
  function getImportInfo(imp, sourceFile) {
169
196
  const importText = imp.importClause?.getText(sourceFile) || "";
170
197
  const start = importText.indexOf("{");
171
198
  const end = importText.lastIndexOf("}");
172
199
  const text = imp.moduleSpecifier.getText(sourceFile).slice(1, -1);
173
- if (start === -1 || end === -1) {
200
+ if ((start === -1 || end === -1) && !importText.length) {
174
201
  return;
175
202
  }
203
+ let imports = [];
204
+ let def;
205
+ if (start !== -1 && end !== -1) {
206
+ imports = importText
207
+ .substring(start + 1, end)
208
+ //.trim()
209
+ .split(",");
210
+ }
211
+ else {
212
+ def = importText;
213
+ }
176
214
  return {
177
215
  importPath: text,
178
216
  importText,
179
217
  start,
180
218
  end,
181
- imports: importText
182
- .substring(start + 1, end)
183
- //.trim()
184
- .split(","),
219
+ imports,
220
+ default: def,
185
221
  };
186
222
  }
187
223
  exports.getImportInfo = getImportInfo;
224
+ function transformRelative(file, importPath, relative) {
225
+ if (!relative || !importPath.startsWith("src")) {
226
+ return importPath;
227
+ }
228
+ const fileFullPath = path.join(process.cwd(), file);
229
+ const impFullPath = path.join(process.cwd(), importPath);
230
+ // relative path is from directory
231
+ return normalizePath(path.relative(path.dirname(fileFullPath), impFullPath));
232
+ }
233
+ exports.transformRelative = transformRelative;
234
+ function normalizePath(p) {
235
+ if (p.endsWith("..")) {
236
+ return p + "/";
237
+ }
238
+ return p;
239
+ }
240
+ function getCustomInfo() {
241
+ let yaml = {};
242
+ let relativeImports = false;
243
+ try {
244
+ yaml = (0, js_yaml_1.load)(fs.readFileSync(path.join(process.cwd(), "ent.yml"), {
245
+ encoding: "utf8",
246
+ }));
247
+ relativeImports = yaml?.codegen?.relativeImports || false;
248
+ if (yaml?.codegen?.templatizedViewer) {
249
+ return {
250
+ viewerInfo: yaml.codegen.templatizedViewer,
251
+ relativeImports,
252
+ };
253
+ }
254
+ }
255
+ catch (e) { }
256
+ return {
257
+ viewerInfo: {
258
+ path: "@snowtop/ent",
259
+ name: "Viewer",
260
+ },
261
+ relativeImports,
262
+ };
263
+ }
264
+ exports.getCustomInfo = getCustomInfo;
@@ -0,0 +1 @@
1
+ export declare function moveGenerated(relativeImports: boolean): void;
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.moveGenerated = void 0;
26
+ const glob_1 = require("glob");
27
+ const path = __importStar(require("path"));
28
+ const fs = __importStar(require("fs"));
29
+ const typescript_1 = __importDefault(require("typescript"));
30
+ const ast_1 = require("./ast");
31
+ const transform_1 = require("./transform");
32
+ class MoveFiles {
33
+ constructor(globPath) {
34
+ this.globPath = globPath;
35
+ }
36
+ move() {
37
+ const files = glob_1.glob.sync(this.globPath);
38
+ moveFiles(files);
39
+ }
40
+ }
41
+ class TransformImports {
42
+ constructor(glob, prettierGlob, relativeImports, checkRelativeImportsValid) {
43
+ this.glob = glob;
44
+ this.prettierGlob = prettierGlob;
45
+ this.relativeImports = relativeImports;
46
+ this.checkRelativeImportsValid = checkRelativeImportsValid;
47
+ this.globOptions = {
48
+ ignore: ["node_modules/**"],
49
+ };
50
+ this.cwd = process.cwd();
51
+ }
52
+ traverseChild(sourceFile, contents, file, node) {
53
+ if (!typescript_1.default.isImportDeclaration(node)) {
54
+ return { node };
55
+ }
56
+ let dirPath = path.join(this.cwd, file, "..");
57
+ const newImportPath = this.getNewImportPath(node, file, sourceFile, dirPath);
58
+ if (!newImportPath) {
59
+ return { node };
60
+ }
61
+ const v = (0, ast_1.updateImportPath)(contents, node, sourceFile, newImportPath);
62
+ return {
63
+ traversed: true,
64
+ rawString: v,
65
+ };
66
+ }
67
+ getNewImportPath(node, file, sourceFile, dirPath) {
68
+ const text = node.moduleSpecifier.getText(sourceFile).slice(1, -1);
69
+ // it's relative and has generated in there, continue
70
+ // do relative imports path regardless of if relative imports is on or not
71
+ if ((0, ast_1.isRelativeGeneratedImport)(node, sourceFile)) {
72
+ const oldPath = path.join(dirPath, text);
73
+ const relFromRoot = path.relative(".", oldPath);
74
+ const conv = transformPath(relFromRoot);
75
+ if (!conv || conv.newFile === relFromRoot) {
76
+ return;
77
+ }
78
+ return path.relative(dirPath, conv.newFile);
79
+ }
80
+ if (this.checkRelativeImportsValid && (0, ast_1.isRelativeImport)(node, sourceFile)) {
81
+ const parts = file.split(path.sep);
82
+ if (parts.length === 5 &&
83
+ parts.slice(0, 3).join(path.sep) ===
84
+ ["src", "graphql", "generated"].join(path.sep)) {
85
+ // we have custom graphql import paths
86
+ // src/graphql/generated/mutations|resolvers/foo_type.ts
87
+ // which used to be
88
+ // src/graphql/mutations|resolvers/generated/foo_type.ts
89
+ // we probably have a broken import.
90
+ // try and fix it...
91
+ let temp = parts[2];
92
+ parts[2] = parts[3];
93
+ parts[3] = temp;
94
+ const oldPath = parts.join(path.sep);
95
+ let oldDir = path.join(this.cwd, oldPath, "..");
96
+ let importPath = path.join(oldDir, text);
97
+ let exists = fs.statSync(importPath + ".ts", { throwIfNoEntry: false });
98
+ if (!exists) {
99
+ // doesn't exist. sadly has to be fixed manually. could theoretically also be a directory but we shouldn't have that
100
+ return;
101
+ }
102
+ return path.relative(dirPath, importPath);
103
+ }
104
+ }
105
+ // if relative imports, we done.
106
+ if (this.relativeImports) {
107
+ return;
108
+ }
109
+ // non relative, only transform src paths with generated
110
+ if ((0, ast_1.isSrcGeneratedImport)(node, sourceFile)) {
111
+ const conv = transformPath(text);
112
+ if (!conv || conv.newFile === text) {
113
+ return;
114
+ }
115
+ return conv.newFile;
116
+ }
117
+ return;
118
+ }
119
+ }
120
+ function transformPath(old) {
121
+ const parts = old.split(path.sep);
122
+ if (parts.length < 3) {
123
+ return;
124
+ }
125
+ const changedParts = parts
126
+ .slice(0, 2)
127
+ .concat("generated")
128
+ .concat(parts.slice(2).filter((v) => v !== "generated"));
129
+ const newFile = changedParts.join(path.sep);
130
+ return { changedParts, newFile };
131
+ }
132
+ function moveFiles(files) {
133
+ files.forEach((file) => {
134
+ const conv = transformPath(file);
135
+ if (!conv) {
136
+ return;
137
+ }
138
+ const { changedParts, newFile } = conv;
139
+ if (file === newFile) {
140
+ return;
141
+ }
142
+ // check if directory exists, if not, create recursive dir
143
+ const p = changedParts.slice(0, changedParts.length - 1).join(path.sep);
144
+ const statInfo = fs.statSync(p, { throwIfNoEntry: false });
145
+ if (!statInfo) {
146
+ fs.mkdirSync(p, {
147
+ recursive: true,
148
+ });
149
+ }
150
+ // move file to new location
151
+ fs.renameSync(file, newFile);
152
+ });
153
+ }
154
+ function moveGenerated(relativeImports) {
155
+ new MoveFiles("src/ent/**/generated/**/**.ts").move();
156
+ new MoveFiles("src/graphql/**/generated/**/**.ts").move();
157
+ (0, transform_1.transform)(new TransformImports("src/ent/**/*.ts", "src/ent/**/*.ts", relativeImports));
158
+ (0, transform_1.transform)(new TransformImports("src/graphql/**/*.ts", "src/graphql/**/*.ts", relativeImports, true));
159
+ }
160
+ exports.moveGenerated = moveGenerated;
@@ -0,0 +1,21 @@
1
+ import { IOptions } from "glob";
2
+ import ts from "typescript";
3
+ interface TraverseChildResponse {
4
+ node?: ts.Node;
5
+ rawString?: string;
6
+ traversed?: boolean;
7
+ imports?: Map<string, string[]>;
8
+ removeImports?: string[];
9
+ }
10
+ export interface TransformFile {
11
+ glob: string;
12
+ globOptions?: IOptions;
13
+ preprocessFile?: (contents: string, file: string, sourceFile: ts.SourceFile) => boolean;
14
+ traverseChild(sourceFile: ts.SourceFile, contents: string, file: string, node: ts.Node): TraverseChildResponse | undefined;
15
+ filter?(files: string[]): string[];
16
+ fileToWrite?(file: string): string;
17
+ postProcess?(file: string): void;
18
+ prettierGlob?: string;
19
+ }
20
+ export declare function transform(transform: TransformFile): void;
21
+ export {};
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.transform = void 0;
26
+ const glob_1 = require("glob");
27
+ const typescript_1 = __importDefault(require("typescript"));
28
+ const child_process_1 = require("child_process");
29
+ const fs = __importStar(require("fs"));
30
+ const ast_1 = require("./ast");
31
+ const compilerOptions_1 = require("./compilerOptions");
32
+ function normalizePath(p) {
33
+ if (p.endsWith("..")) {
34
+ return p + "/";
35
+ }
36
+ return p;
37
+ }
38
+ function transform(transform) {
39
+ let files = glob_1.glob.sync(transform.glob, transform.globOptions);
40
+ const target = (0, compilerOptions_1.getTargetFromCurrentDir)();
41
+ if (transform.filter) {
42
+ files = transform.filter(files);
43
+ }
44
+ files.forEach((file) => {
45
+ let { contents, sourceFile } = (0, compilerOptions_1.createSourceFile)(target, file);
46
+ let nodes = [];
47
+ let imports = new Map();
48
+ let removeImports = [];
49
+ let traversed = false;
50
+ let seenImports = new Map();
51
+ typescript_1.default.forEachChild(sourceFile, function (node) {
52
+ if (typescript_1.default.isImportDeclaration(node)) {
53
+ const imp = (0, ast_1.getImportInfo)(node, sourceFile);
54
+ if (imp) {
55
+ imp.imports.forEach((v) => {
56
+ v = v.trim();
57
+ v && seenImports.set(v, true);
58
+ });
59
+ }
60
+ }
61
+ const ret = transform.traverseChild(sourceFile, contents, file, node);
62
+ if (!ret) {
63
+ return;
64
+ }
65
+ if (ret.node || ret.rawString) {
66
+ nodes.push(ret);
67
+ }
68
+ if (ret.imports) {
69
+ for (const [k, v] of ret.imports) {
70
+ imports.set(k, v);
71
+ }
72
+ }
73
+ if (ret.traversed) {
74
+ traversed = ret.traversed;
75
+ }
76
+ if (ret.removeImports?.length) {
77
+ removeImports.push(...ret.removeImports);
78
+ }
79
+ });
80
+ if (!traversed) {
81
+ return;
82
+ }
83
+ let newContents = "";
84
+ let afterProcessed = false;
85
+ let seen = new Map();
86
+ const processAfterImport = () => {
87
+ // do this for the first non-import node we see
88
+ // we want to add new imports to end of imports and there's an assumption that imports are ordered
89
+ // at top of file
90
+ if (!afterProcessed) {
91
+ for (const [imp, list] of imports) {
92
+ if (seen.has(imp)) {
93
+ continue;
94
+ }
95
+ const final = list.filter((v) => !seenImports.has(v));
96
+ if (final.length) {
97
+ newContents += `\nimport { ${final.join(", ")} } from "${imp}"`;
98
+ }
99
+ }
100
+ afterProcessed = true;
101
+ }
102
+ };
103
+ for (const node of nodes) {
104
+ if (node.node) {
105
+ if (typescript_1.default.isImportDeclaration(node.node)) {
106
+ const impInfo = (0, ast_1.getImportInfo)(node.node, sourceFile);
107
+ // console.debug(impInfo);
108
+ if (impInfo) {
109
+ const impPath = normalizePath(impInfo.importPath);
110
+ const list = imports.get(impPath);
111
+ // path exists, we care about it
112
+ if (list !== undefined) {
113
+ let transformed = (0, ast_1.transformImport)(contents, node.node, sourceFile, {
114
+ // if we've done this path before, don't try and add
115
+ // but still try and do any removals since we don't know which of the imports
116
+ // has it
117
+ newImports: seen.has(impPath) ? undefined : list,
118
+ removeImports,
119
+ // don't use normalized path here, we wanna use the path that's in code...
120
+ transformPath: impInfo.importPath,
121
+ });
122
+ if (transformed) {
123
+ newContents += transformed;
124
+ seen.set(impPath, true);
125
+ continue;
126
+ }
127
+ }
128
+ }
129
+ }
130
+ else {
131
+ if (!typescript_1.default.isExportDeclaration(node.node) &&
132
+ !isRequireStatement(node.node, sourceFile)) {
133
+ processAfterImport();
134
+ }
135
+ }
136
+ newContents += node.node.getFullText(sourceFile);
137
+ }
138
+ else if (node.rawString) {
139
+ processAfterImport();
140
+ newContents += node.rawString;
141
+ }
142
+ else {
143
+ throw new Error(`malformed node with no node or rawString`);
144
+ }
145
+ }
146
+ let writeFile = file;
147
+ if (transform.fileToWrite) {
148
+ writeFile = transform.fileToWrite(file);
149
+ }
150
+ fs.writeFileSync(writeFile, newContents);
151
+ if (transform.postProcess) {
152
+ transform.postProcess(file);
153
+ }
154
+ });
155
+ if (transform.prettierGlob) {
156
+ (0, child_process_1.execSync)(`prettier ${transform.prettierGlob} --write`);
157
+ }
158
+ }
159
+ exports.transform = transform;
160
+ function isRequireStatement(node, sourceFile) {
161
+ if (node.kind !== typescript_1.default.SyntaxKind.VariableStatement) {
162
+ return false;
163
+ }
164
+ const v = node;
165
+ // v.declarationList
166
+ const text = v.declarationList.declarations[0].getFullText(sourceFile);
167
+ return text.includes("require(");
168
+ }