@snowtop/ent 0.1.0-alpha1 → 0.1.0-alpha10

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.
Files changed (78) hide show
  1. package/action/action.d.ts +2 -0
  2. package/action/executor.d.ts +1 -1
  3. package/action/orchestrator.d.ts +10 -2
  4. package/action/orchestrator.js +128 -34
  5. package/core/base.d.ts +6 -2
  6. package/core/base.js +16 -0
  7. package/core/clause.d.ts +24 -3
  8. package/core/clause.js +246 -5
  9. package/core/config.d.ts +18 -0
  10. package/core/config.js +17 -0
  11. package/core/db.d.ts +3 -3
  12. package/core/db.js +2 -0
  13. package/core/ent.d.ts +2 -4
  14. package/core/ent.js +72 -25
  15. package/core/loaders/assoc_edge_loader.d.ts +1 -1
  16. package/core/loaders/assoc_edge_loader.js +5 -4
  17. package/core/loaders/index_loader.js +1 -0
  18. package/core/loaders/object_loader.d.ts +7 -2
  19. package/core/loaders/object_loader.js +59 -4
  20. package/core/privacy.d.ts +1 -1
  21. package/core/privacy.js +3 -0
  22. package/core/viewer.d.ts +1 -0
  23. package/core/viewer.js +4 -0
  24. package/graphql/builtins/connection.js +3 -3
  25. package/graphql/builtins/edge.js +2 -2
  26. package/graphql/builtins/node.js +1 -1
  27. package/graphql/graphql.d.ts +3 -2
  28. package/graphql/graphql.js +24 -23
  29. package/graphql/index.d.ts +1 -0
  30. package/graphql/index.js +3 -1
  31. package/graphql/mutations/union.d.ts +2 -0
  32. package/graphql/mutations/union.js +35 -0
  33. package/graphql/node_resolver.d.ts +0 -1
  34. package/graphql/query/connection_type.js +6 -6
  35. package/graphql/query/page_info.js +4 -4
  36. package/graphql/query/shared_assoc_test.js +2 -2
  37. package/graphql/scalars/time.d.ts +1 -1
  38. package/index.d.ts +16 -1
  39. package/index.js +18 -5
  40. package/package.json +3 -3
  41. package/parse_schema/parse.d.ts +21 -4
  42. package/parse_schema/parse.js +79 -8
  43. package/schema/base_schema.d.ts +36 -1
  44. package/schema/base_schema.js +48 -2
  45. package/schema/field.d.ts +1 -1
  46. package/schema/field.js +11 -3
  47. package/schema/index.d.ts +4 -2
  48. package/schema/index.js +10 -1
  49. package/schema/schema.d.ts +56 -4
  50. package/schema/schema.js +126 -5
  51. package/schema/struct_field.d.ts +17 -0
  52. package/schema/struct_field.js +102 -0
  53. package/schema/union_field.d.ts +23 -0
  54. package/schema/union_field.js +79 -0
  55. package/scripts/custom_graphql.js +122 -15
  56. package/scripts/read_schema.js +15 -1
  57. package/scripts/transform_code.d.ts +1 -0
  58. package/scripts/transform_code.js +114 -0
  59. package/scripts/transform_schema.js +190 -121
  60. package/testutils/builder.d.ts +13 -9
  61. package/testutils/builder.js +64 -8
  62. package/testutils/context/test_context.d.ts +2 -2
  63. package/testutils/context/test_context.js +7 -1
  64. package/testutils/db/test_db.d.ts +2 -1
  65. package/testutils/db/test_db.js +13 -4
  66. package/testutils/ent-graphql-tests/index.d.ts +2 -0
  67. package/testutils/ent-graphql-tests/index.js +26 -17
  68. package/testutils/fake_data/fake_contact.d.ts +3 -7
  69. package/testutils/fake_data/fake_contact.js +14 -19
  70. package/testutils/fake_data/fake_event.d.ts +3 -7
  71. package/testutils/fake_data/fake_event.js +20 -25
  72. package/testutils/fake_data/fake_user.d.ts +3 -7
  73. package/testutils/fake_data/fake_user.js +22 -27
  74. package/testutils/fake_data/test_helpers.js +1 -1
  75. package/tsc/ast.d.ts +20 -0
  76. package/tsc/ast.js +131 -0
  77. package/tsc/compilerOptions.d.ts +5 -0
  78. package/tsc/compilerOptions.js +35 -1
@@ -336,7 +336,7 @@ class TempDB {
336
336
  getTables() {
337
337
  return this.tables;
338
338
  }
339
- async beforeAll() {
339
+ async beforeAll(setupConnString = true) {
340
340
  if (this.dialect === db_1.Dialect.Postgres) {
341
341
  const user = process.env.POSTGRES_USER || "";
342
342
  const password = process.env.POSTGRES_PASSWORD || "";
@@ -348,11 +348,17 @@ class TempDB {
348
348
  await this.client.connect();
349
349
  this.db = randomDB();
350
350
  await this.client.query(`CREATE DATABASE ${this.db}`);
351
- if (user && password) {
352
- process.env.DB_CONNECTION_STRING = `postgres://${user}:${password}@localhost:5432/${this.db}`;
351
+ if (setupConnString) {
352
+ if (user && password) {
353
+ process.env.DB_CONNECTION_STRING = `postgres://${user}:${password}@localhost:5432/${this.db}`;
354
+ }
355
+ else {
356
+ process.env.DB_CONNECTION_STRING = `postgres://localhost/${this.db}?`;
357
+ }
353
358
  }
354
359
  else {
355
- process.env.DB_CONNECTION_STRING = `postgres://localhost/${this.db}?`;
360
+ // will probably be setup via loadConfig
361
+ delete process.env.DB_CONNECTION_STRING;
356
362
  }
357
363
  this.dbClient = new pg_1.Client({
358
364
  host: "localhost",
@@ -397,6 +403,9 @@ class TempDB {
397
403
  await this.client.query(`DROP DATABASE ${this.db}`);
398
404
  await this.client.end();
399
405
  }
406
+ getDB() {
407
+ return this.db;
408
+ }
400
409
  async dropAll() {
401
410
  for (const [t, _] of this.tables) {
402
411
  await this.drop(t);
@@ -16,6 +16,8 @@ interface queryConfig {
16
16
  callback?: (res: supertest.Response) => void;
17
17
  inlineFragmentRoot?: string;
18
18
  customHandlers?: RequestHandler[];
19
+ server?: any;
20
+ graphQLPath?: string;
19
21
  }
20
22
  export interface queryRootConfig extends queryConfig {
21
23
  root: string;
@@ -26,7 +26,7 @@ exports.expectMutation = exports.expectQueryFromRoot = void 0;
26
26
  // NB: this is copied from ent-graphql-tests package until I have time to figure out how to share code here effectively
27
27
  // the circular dependencies btw this package and ent-graphql-tests seems to imply something needs to change
28
28
  const express_1 = __importDefault(require("express"));
29
- const express_graphql_1 = require("express-graphql");
29
+ const graphql_helix_1 = require("graphql-helix");
30
30
  const graphql_1 = require("graphql");
31
31
  const auth_1 = require("../../auth");
32
32
  const supertest_1 = __importDefault(require("supertest"));
@@ -45,18 +45,23 @@ function server(config) {
45
45
  if (config.init) {
46
46
  config.init(app);
47
47
  }
48
+ app.use(express_1.default.json());
48
49
  let handlers = config.customHandlers || [];
49
- handlers.push((0, express_graphql_1.graphqlHTTP)((request, response) => {
50
- const doWork = async () => {
51
- let context = await (0, auth_1.buildContext)(request, response);
52
- return {
53
- schema: config.schema,
54
- context,
55
- };
56
- };
57
- return doWork();
58
- }));
59
- app.use("/graphql", ...handlers);
50
+ handlers.push(async (req, res) => {
51
+ const { operationName, query, variables } = (0, graphql_helix_1.getGraphQLParameters)(req);
52
+ const result = await (0, graphql_helix_1.processRequest)({
53
+ operationName,
54
+ query,
55
+ variables,
56
+ request: req,
57
+ schema: config.schema,
58
+ contextFactory: async (executionContext) => {
59
+ return (0, auth_1.buildContext)(req, res);
60
+ },
61
+ });
62
+ await (0, graphql_helix_1.sendResult)(result, res);
63
+ });
64
+ app.use(config.graphQLPath || "/graphql", ...handlers);
60
65
  return app;
61
66
  }
62
67
  function getInnerType(typ, list) {
@@ -72,14 +77,14 @@ function makeGraphQLRequest(config, query, fieldArgs) {
72
77
  let test;
73
78
  if (config.test) {
74
79
  if (typeof config.test === "function") {
75
- test = config.test(server(config));
80
+ test = config.test(config.server ? config.server : server(config));
76
81
  }
77
82
  else {
78
83
  test = config.test;
79
84
  }
80
85
  }
81
86
  else {
82
- test = (0, supertest_1.default)(server(config));
87
+ test = (0, supertest_1.default)(config.server ? config.server : server(config));
83
88
  }
84
89
  let files = new Map();
85
90
  // handle files
@@ -104,7 +109,9 @@ function makeGraphQLRequest(config, query, fieldArgs) {
104
109
  }
105
110
  });
106
111
  if (files.size) {
107
- let ret = test.post("/graphql").set(config.headers || {});
112
+ let ret = test
113
+ .post(config.graphQLPath || "/graphql")
114
+ .set(config.headers || {});
108
115
  ret.field("operations", JSON.stringify({
109
116
  query: query,
110
117
  variables: config.args,
@@ -130,7 +137,7 @@ function makeGraphQLRequest(config, query, fieldArgs) {
130
137
  return [
131
138
  test,
132
139
  test
133
- .post("/graphql")
140
+ .post(config.graphQLPath || "/graphql")
134
141
  .set(config.headers || {})
135
142
  .send({
136
143
  query: query,
@@ -353,7 +360,9 @@ async function expectFromRoot(config, ...options) {
353
360
  else {
354
361
  expect(res.ok, `expected ok response. instead got ${res.status} and result ${JSON.stringify(res.body)}`);
355
362
  }
356
- if (!res.ok) {
363
+ // res.ok = true in graphql-helix when there's errors...
364
+ // res.ok = false in express-graphql when there's errors...
365
+ if (!res.ok || (res.body.errors && res.body.errors.length > 0)) {
357
366
  let errors = res.body.errors;
358
367
  expect(errors.length).toBeGreaterThan(0);
359
368
  if (config.expectedError) {
@@ -1,6 +1,5 @@
1
1
  import { ID, Ent, Viewer, Data, LoadEntOptions, PrivacyPolicy } from "../../core/base";
2
- import { BuilderSchema, SimpleBuilder } from "../builder";
3
- import { BaseEntSchema, FieldMap } from "../../schema";
2
+ import { SimpleBuilder } from "../builder";
4
3
  import { NodeType } from "./const";
5
4
  import { ObjectLoaderFactory } from "../../core/loaders";
6
5
  export declare class FakeContact implements Ent {
@@ -14,7 +13,7 @@ export declare class FakeContact implements Ent {
14
13
  readonly lastName: string;
15
14
  readonly emailAddress: string;
16
15
  readonly userID: ID;
17
- privacyPolicy: PrivacyPolicy;
16
+ getPrivacyPolicy(): PrivacyPolicy<this>;
18
17
  constructor(viewer: Viewer, data: Data);
19
18
  static getFields(): string[];
20
19
  static getTestTable(): import("../db/test_db").Table;
@@ -22,10 +21,7 @@ export declare class FakeContact implements Ent {
22
21
  static load(v: Viewer, id: ID): Promise<FakeContact | null>;
23
22
  static loadX(v: Viewer, id: ID): Promise<FakeContact>;
24
23
  }
25
- export declare class FakeContactSchema extends BaseEntSchema implements BuilderSchema<FakeContact> {
26
- ent: typeof FakeContact;
27
- fields: FieldMap;
28
- }
24
+ export declare const FakeContactSchema: import("../builder").BuilderSchema<FakeContact>;
29
25
  export interface ContactCreateInput {
30
26
  firstName: string;
31
27
  lastName: string;
@@ -13,9 +13,6 @@ class FakeContact {
13
13
  constructor(viewer, data) {
14
14
  this.viewer = viewer;
15
15
  this.nodeType = const_1.NodeType.FakeContact;
16
- this.privacyPolicy = {
17
- rules: [new privacy_1.AllowIfViewerIsRule("userID"), privacy_1.AlwaysDenyRule],
18
- };
19
16
  this.data = data;
20
17
  this.id = data.id;
21
18
  this.createdAt = (0, convert_1.convertDate)(data.created_at);
@@ -25,6 +22,11 @@ class FakeContact {
25
22
  this.emailAddress = data.email_address;
26
23
  this.userID = data.user_id;
27
24
  }
25
+ getPrivacyPolicy() {
26
+ return {
27
+ rules: [new privacy_1.AllowIfViewerIsRule("userID"), privacy_1.AlwaysDenyRule],
28
+ };
29
+ }
28
30
  static getFields() {
29
31
  return [
30
32
  "id",
@@ -59,21 +61,14 @@ class FakeContact {
59
61
  }
60
62
  }
61
63
  exports.FakeContact = FakeContact;
62
- class FakeContactSchema extends schema_1.BaseEntSchema {
63
- constructor() {
64
- super(...arguments);
65
- this.ent = FakeContact;
66
- this.fields = {
67
- firstName: (0, schema_1.StringType)(),
68
- lastName: (0, schema_1.StringType)(),
69
- emailAddress: (0, schema_1.StringType)(),
70
- userID: (0, schema_1.UUIDType)({
71
- foreignKey: { schema: "User", column: "ID" },
72
- }),
73
- };
74
- }
75
- }
76
- exports.FakeContactSchema = FakeContactSchema;
64
+ exports.FakeContactSchema = (0, builder_1.getBuilderSchemaFromFields)({
65
+ firstName: (0, schema_1.StringType)(),
66
+ lastName: (0, schema_1.StringType)(),
67
+ emailAddress: (0, schema_1.StringType)(),
68
+ userID: (0, schema_1.UUIDType)({
69
+ foreignKey: { schema: "User", column: "ID" },
70
+ }),
71
+ }, FakeContact);
77
72
  function getContactBuilder(viewer, input) {
78
73
  const m = new Map();
79
74
  for (const key in input) {
@@ -82,7 +77,7 @@ function getContactBuilder(viewer, input) {
82
77
  //To lock in the value of Date now incase of advanceTo/advanceBy
83
78
  m.set("createdAt", new Date());
84
79
  m.set("updatedAt", new Date());
85
- return new builder_1.SimpleBuilder(viewer, new FakeContactSchema(), m);
80
+ return new builder_1.SimpleBuilder(viewer, exports.FakeContactSchema, m);
86
81
  }
87
82
  exports.getContactBuilder = getContactBuilder;
88
83
  async function createContact(viewer, input) {
@@ -1,6 +1,5 @@
1
1
  import { ID, Ent, Viewer, Data, LoadEntOptions, PrivacyPolicy } from "../../core/base";
2
- import { BuilderSchema, SimpleBuilder } from "../builder";
3
- import { BaseEntSchema, FieldMap } from "../../schema";
2
+ import { SimpleBuilder } from "../builder";
4
3
  import { NodeType } from "./const";
5
4
  export declare class FakeEvent implements Ent {
6
5
  viewer: Viewer;
@@ -15,7 +14,7 @@ export declare class FakeEvent implements Ent {
15
14
  readonly title: string;
16
15
  readonly description: string | null;
17
16
  readonly userID: ID;
18
- privacyPolicy: PrivacyPolicy;
17
+ getPrivacyPolicy(): PrivacyPolicy<this>;
19
18
  constructor(viewer: Viewer, data: Data);
20
19
  private static getFields;
21
20
  static getTestTable(): import("../db/test_db").Table;
@@ -23,10 +22,7 @@ export declare class FakeEvent implements Ent {
23
22
  static load(v: Viewer, id: ID): Promise<FakeEvent | null>;
24
23
  static loadX(v: Viewer, id: ID): Promise<FakeEvent>;
25
24
  }
26
- export declare class FakeEventSchema extends BaseEntSchema implements BuilderSchema<FakeEvent> {
27
- ent: typeof FakeEvent;
28
- fields: FieldMap;
29
- }
25
+ export declare const FakeEventSchema: import("../builder").BuilderSchema<FakeEvent>;
30
26
  export interface EventCreateInput {
31
27
  startTime: Date;
32
28
  endTime?: Date | null;
@@ -13,7 +13,6 @@ class FakeEvent {
13
13
  constructor(viewer, data) {
14
14
  this.viewer = viewer;
15
15
  this.nodeType = const_1.NodeType.FakeEvent;
16
- this.privacyPolicy = privacy_1.AlwaysAllowPrivacyPolicy;
17
16
  this.data = data;
18
17
  this.id = data.id;
19
18
  this.createdAt = (0, convert_1.convertDate)(data.created_at);
@@ -25,6 +24,9 @@ class FakeEvent {
25
24
  this.description = data.description;
26
25
  this.userID = data.user_id;
27
26
  }
27
+ getPrivacyPolicy() {
28
+ return privacy_1.AlwaysAllowPrivacyPolicy;
29
+ }
28
30
  static getFields() {
29
31
  return [
30
32
  "id",
@@ -63,35 +65,28 @@ class FakeEvent {
63
65
  }
64
66
  }
65
67
  exports.FakeEvent = FakeEvent;
66
- class FakeEventSchema extends schema_1.BaseEntSchema {
67
- constructor() {
68
- super(...arguments);
69
- this.ent = FakeEvent;
70
- this.fields = {
71
- startTime: (0, schema_1.TimestampType)({
72
- index: true,
73
- }),
74
- endTime: (0, schema_1.TimestampType)({
75
- nullable: true,
76
- }),
77
- title: (0, schema_1.StringType)(),
78
- location: (0, schema_1.StringType)(),
79
- description: (0, schema_1.StringType)({
80
- nullable: true,
81
- }),
82
- userID: (0, schema_1.UUIDType)({
83
- foreignKey: { schema: "User", column: "ID" },
84
- }),
85
- };
86
- }
87
- }
88
- exports.FakeEventSchema = FakeEventSchema;
68
+ exports.FakeEventSchema = (0, builder_1.getBuilderSchemaFromFields)({
69
+ startTime: (0, schema_1.TimestampType)({
70
+ index: true,
71
+ }),
72
+ endTime: (0, schema_1.TimestampType)({
73
+ nullable: true,
74
+ }),
75
+ title: (0, schema_1.StringType)(),
76
+ location: (0, schema_1.StringType)(),
77
+ description: (0, schema_1.StringType)({
78
+ nullable: true,
79
+ }),
80
+ userID: (0, schema_1.UUIDType)({
81
+ foreignKey: { schema: "User", column: "ID" },
82
+ }),
83
+ }, FakeEvent);
89
84
  function getEventBuilder(viewer, input) {
90
85
  const m = new Map();
91
86
  for (const key in input) {
92
87
  m.set(key, input[key]);
93
88
  }
94
- return new builder_1.SimpleBuilder(viewer, new FakeEventSchema(), m);
89
+ return new builder_1.SimpleBuilder(viewer, exports.FakeEventSchema, m);
95
90
  }
96
91
  exports.getEventBuilder = getEventBuilder;
97
92
  async function createEvent(viewer, input) {
@@ -1,6 +1,5 @@
1
1
  import { ID, Ent, Viewer, Data, LoadEntOptions, PrivacyPolicy } from "../../core/base";
2
- import { BuilderSchema, SimpleAction } from "../builder";
3
- import { BaseEntSchema, FieldMap } from "../../schema";
2
+ import { SimpleAction } from "../builder";
4
3
  import { NodeType } from "./const";
5
4
  import { IDViewer, IDViewerOptions } from "../../core/viewer";
6
5
  import { ObjectLoaderFactory } from "../../core/loaders";
@@ -24,7 +23,7 @@ export declare class FakeUser implements Ent {
24
23
  readonly emailAddress: string;
25
24
  readonly phoneNumber: string | null;
26
25
  protected readonly password: string | null;
27
- privacyPolicy: PrivacyPolicy;
26
+ getPrivacyPolicy(): PrivacyPolicy<this>;
28
27
  constructor(viewer: Viewer, data: Data);
29
28
  static getFields(): string[];
30
29
  static getTestTable(): import("../db/test_db").Table;
@@ -32,10 +31,7 @@ export declare class FakeUser implements Ent {
32
31
  static load(v: Viewer, id: ID): Promise<FakeUser | null>;
33
32
  static loadX(v: Viewer, id: ID): Promise<FakeUser>;
34
33
  }
35
- export declare class FakeUserSchema extends BaseEntSchema implements BuilderSchema<FakeUser> {
36
- ent: typeof FakeUser;
37
- fields: FieldMap;
38
- }
34
+ export declare const FakeUserSchema: import("../builder").BuilderSchema<FakeUser>;
39
35
  export interface UserCreateInput {
40
36
  firstName: string;
41
37
  lastName: string;
@@ -26,7 +26,18 @@ class FakeUser {
26
26
  constructor(viewer, data) {
27
27
  this.viewer = viewer;
28
28
  this.nodeType = const_1.NodeType.FakeUser;
29
- this.privacyPolicy = {
29
+ this.data = data;
30
+ this.id = data.id;
31
+ this.createdAt = (0, convert_1.convertDate)(data.created_at);
32
+ this.updatedAt = (0, convert_1.convertDate)(data.updated_at);
33
+ this.firstName = data.first_name;
34
+ this.lastName = data.last_name;
35
+ this.emailAddress = data.email_address;
36
+ this.phoneNumber = data.phone_number;
37
+ this.password = data.password;
38
+ }
39
+ getPrivacyPolicy() {
40
+ return {
30
41
  rules: [
31
42
  privacy_1.AllowIfViewerRule,
32
43
  //can view user if friends
@@ -48,15 +59,6 @@ class FakeUser {
48
59
  privacy_1.AlwaysDenyRule,
49
60
  ],
50
61
  };
51
- this.data = data;
52
- this.id = data.id;
53
- this.createdAt = (0, convert_1.convertDate)(data.created_at);
54
- this.updatedAt = (0, convert_1.convertDate)(data.updated_at);
55
- this.firstName = data.first_name;
56
- this.lastName = data.last_name;
57
- this.emailAddress = data.email_address;
58
- this.phoneNumber = data.phone_number;
59
- this.password = data.password;
60
62
  }
61
63
  static getFields() {
62
64
  return [
@@ -89,22 +91,15 @@ class FakeUser {
89
91
  }
90
92
  }
91
93
  exports.FakeUser = FakeUser;
92
- class FakeUserSchema extends schema_1.BaseEntSchema {
93
- constructor() {
94
- super(...arguments);
95
- this.ent = FakeUser;
96
- this.fields = {
97
- firstName: (0, schema_1.StringType)(),
98
- lastName: (0, schema_1.StringType)(),
99
- emailAddress: (0, schema_1.StringType)(),
100
- phoneNumber: (0, schema_1.StringType)(),
101
- password: (0, schema_1.StringType)({
102
- nullable: true,
103
- }),
104
- };
105
- }
106
- }
107
- exports.FakeUserSchema = FakeUserSchema;
94
+ exports.FakeUserSchema = (0, builder_1.getBuilderSchemaFromFields)({
95
+ firstName: (0, schema_1.StringType)(),
96
+ lastName: (0, schema_1.StringType)(),
97
+ emailAddress: (0, schema_1.StringType)(),
98
+ phoneNumber: (0, schema_1.StringType)(),
99
+ password: (0, schema_1.StringType)({
100
+ nullable: true,
101
+ }),
102
+ }, FakeUser);
108
103
  function getUserBuilder(viewer, input) {
109
104
  const action = getUserAction(viewer, input);
110
105
  return action.builder;
@@ -115,7 +110,7 @@ function getUserAction(viewer, input) {
115
110
  for (const key in input) {
116
111
  m.set(key, input[key]);
117
112
  }
118
- const action = new builder_1.SimpleAction(viewer, new FakeUserSchema(), m);
113
+ const action = new builder_1.SimpleAction(viewer, exports.FakeUserSchema, m);
119
114
  action.viewerForEntLoad = (data) => {
120
115
  // load the created ent using a VC of the newly created user.
121
116
  return new viewer_1.IDViewer(data.id);
@@ -107,7 +107,7 @@ async function createUserPlusFriendRequests(input, slice) {
107
107
  return createTestUser(input);
108
108
  }));
109
109
  expect(friendRequests.length).toBe(userInputs.length);
110
- await addEdge(user, new _1.FakeUserSchema(), _1.EdgeType.UserToFriendRequests, true, ...friendRequests);
110
+ await addEdge(user, _1.FakeUserSchema, _1.EdgeType.UserToFriendRequests, true, ...friendRequests);
111
111
  return [user, friendRequests];
112
112
  }
113
113
  exports.createUserPlusFriendRequests = createUserPlusFriendRequests;
package/tsc/ast.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import ts from "typescript";
2
+ export declare function getPreText(fileContents: string, node: ts.Node, sourceFile: ts.SourceFile): string;
3
+ export interface ClassInfo {
4
+ extends?: string;
5
+ comment: string;
6
+ name: string;
7
+ export?: boolean;
8
+ default?: boolean;
9
+ implements?: string[];
10
+ wrapClassContents(inner: string): string;
11
+ }
12
+ export declare function getClassInfo(fileContents: string, sourceFile: ts.SourceFile, node: ts.ClassDeclaration): ClassInfo | undefined;
13
+ declare type transformImportFn = (imp: string) => string;
14
+ interface transformOpts {
15
+ removeImports?: string[];
16
+ newImports?: string[];
17
+ transform?: transformImportFn;
18
+ }
19
+ export declare function transformImport(fileContents: string, importNode: ts.ImportDeclaration, sourceFile: ts.SourceFile, opts?: transformOpts): string | undefined;
20
+ export {};
package/tsc/ast.js ADDED
@@ -0,0 +1,131 @@
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
+ exports.transformImport = exports.getClassInfo = exports.getPreText = void 0;
7
+ const typescript_1 = __importDefault(require("typescript"));
8
+ function getPreText(fileContents, node, sourceFile) {
9
+ return fileContents.substring(node.getFullStart(), node.getStart(sourceFile));
10
+ }
11
+ exports.getPreText = getPreText;
12
+ function getClassInfo(fileContents, sourceFile, node) {
13
+ let className = node.name?.text;
14
+ let classExtends;
15
+ let impl = [];
16
+ if (node.heritageClauses) {
17
+ for (const hc of node.heritageClauses) {
18
+ switch (hc.token) {
19
+ case typescript_1.default.SyntaxKind.ImplementsKeyword:
20
+ for (const type of hc.types) {
21
+ impl.push(type.expression.getText(sourceFile));
22
+ }
23
+ break;
24
+ case typescript_1.default.SyntaxKind.ExtendsKeyword:
25
+ // can only extend one class
26
+ for (const type of hc.types) {
27
+ const text = type.expression.getText(sourceFile);
28
+ classExtends = text;
29
+ }
30
+ break;
31
+ }
32
+ }
33
+ }
34
+ // we probably still don't need all of this...
35
+ if (!className || !node.heritageClauses || !classExtends) {
36
+ return undefined;
37
+ }
38
+ let hasExport = false;
39
+ let hasDefault = false;
40
+ let comment = getPreText(fileContents, node, sourceFile);
41
+ const wrapClassContents = (inner) => {
42
+ let ret = `${comment}`;
43
+ if (hasExport) {
44
+ ret += "export ";
45
+ }
46
+ if (hasDefault) {
47
+ ret += "default ";
48
+ }
49
+ ret += `class ${className} `;
50
+ if (classExtends) {
51
+ ret += `extends ${classExtends} `;
52
+ }
53
+ if (impl.length) {
54
+ ret += `implements ${impl.join(", ")}`;
55
+ }
56
+ return `${ret}{
57
+ ${inner}
58
+ }`;
59
+ };
60
+ if (node.modifiers) {
61
+ for (const mod of node.modifiers) {
62
+ const text = mod.getText(sourceFile);
63
+ if (text === "export") {
64
+ hasExport = true;
65
+ }
66
+ else if (text === "default") {
67
+ hasDefault = true;
68
+ }
69
+ }
70
+ }
71
+ return {
72
+ name: className,
73
+ extends: classExtends,
74
+ comment,
75
+ implements: impl,
76
+ wrapClassContents,
77
+ export: hasExport,
78
+ default: hasDefault,
79
+ };
80
+ }
81
+ exports.getClassInfo = getClassInfo;
82
+ function transformImport(fileContents, importNode, sourceFile, opts) {
83
+ // remove quotes too
84
+ const text = importNode.moduleSpecifier.getText(sourceFile).slice(1, -1);
85
+ if (text !== "@snowtop/ent" &&
86
+ text !== "@snowtop/ent/schema" &&
87
+ text !== "@snowtop/ent/schema/") {
88
+ return;
89
+ }
90
+ const importText = importNode.importClause?.getText(sourceFile) || "";
91
+ const start = importText.indexOf("{");
92
+ const end = importText.lastIndexOf("}");
93
+ if (start === -1 || end === -1) {
94
+ return;
95
+ }
96
+ const imports = importText
97
+ .substring(start + 1, end)
98
+ // .trim()
99
+ .split(",");
100
+ let removeImportsMap = {};
101
+ if (opts?.removeImports) {
102
+ opts.removeImports.forEach((imp) => (removeImportsMap[imp] = true));
103
+ }
104
+ let finalImports = new Set();
105
+ for (let i = 0; i < imports.length; i++) {
106
+ let imp = imports[i].trim();
107
+ if (imp === "") {
108
+ continue;
109
+ }
110
+ if (opts?.transform) {
111
+ imp = opts.transform(imp);
112
+ }
113
+ if (removeImportsMap[imp]) {
114
+ continue;
115
+ }
116
+ finalImports.add(imp);
117
+ }
118
+ if (opts?.newImports) {
119
+ opts.newImports.forEach((imp) => finalImports.add(imp));
120
+ }
121
+ const comment = getPreText(fileContents, importNode, sourceFile);
122
+ return (comment +
123
+ "import " +
124
+ importText.substring(0, start + 1) +
125
+ Array.from(finalImports).join(", ") +
126
+ importText.substring(end) +
127
+ ' from "' +
128
+ text +
129
+ '";');
130
+ }
131
+ exports.transformImport = transformImport;
@@ -1,2 +1,7 @@
1
1
  import ts from "typescript";
2
2
  export declare function readCompilerOptions(filePath: string): ts.CompilerOptions;
3
+ export declare function getTarget(target?: string): ts.ScriptTarget.ES3 | ts.ScriptTarget.ES5 | ts.ScriptTarget.ES2015 | ts.ScriptTarget.ES2016 | ts.ScriptTarget.ES2017 | ts.ScriptTarget.ES2018 | ts.ScriptTarget.ES2019 | ts.ScriptTarget.ES2020 | ts.ScriptTarget.ES2021 | ts.ScriptTarget.ESNext;
4
+ export declare function createSourceFile(target: ts.ScriptTarget, file: string): {
5
+ contents: string;
6
+ sourceFile: ts.SourceFile;
7
+ };
@@ -22,7 +22,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
22
22
  return (mod && mod.__esModule) ? mod : { "default": mod };
23
23
  };
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.readCompilerOptions = void 0;
25
+ exports.createSourceFile = exports.getTarget = exports.readCompilerOptions = void 0;
26
26
  const fs = __importStar(require("fs"));
27
27
  const json5_1 = __importDefault(require("json5"));
28
28
  const typescript_1 = __importDefault(require("typescript"));
@@ -59,3 +59,37 @@ function readCompilerOptions(filePath) {
59
59
  return options;
60
60
  }
61
61
  exports.readCompilerOptions = readCompilerOptions;
62
+ function getTarget(target) {
63
+ switch (target?.toLowerCase()) {
64
+ case "es2015":
65
+ return typescript_1.default.ScriptTarget.ES2015;
66
+ case "es2016":
67
+ return typescript_1.default.ScriptTarget.ES2016;
68
+ case "es2017":
69
+ return typescript_1.default.ScriptTarget.ES2017;
70
+ case "es2018":
71
+ return typescript_1.default.ScriptTarget.ES2018;
72
+ case "es2019":
73
+ return typescript_1.default.ScriptTarget.ES2019;
74
+ case "es2020":
75
+ return typescript_1.default.ScriptTarget.ES2020;
76
+ case "es2021":
77
+ return typescript_1.default.ScriptTarget.ES2021;
78
+ case "es3":
79
+ return typescript_1.default.ScriptTarget.ES3;
80
+ case "es5":
81
+ return typescript_1.default.ScriptTarget.ES5;
82
+ case "esnext":
83
+ return typescript_1.default.ScriptTarget.ESNext;
84
+ default:
85
+ return typescript_1.default.ScriptTarget.ESNext;
86
+ }
87
+ }
88
+ exports.getTarget = getTarget;
89
+ function createSourceFile(target, file) {
90
+ let contents = fs.readFileSync(file).toString();
91
+ // go through the file and print everything back if not starting immediately after other position
92
+ const sourceFile = typescript_1.default.createSourceFile(file, contents, target, false, typescript_1.default.ScriptKind.TS);
93
+ return { contents, sourceFile };
94
+ }
95
+ exports.createSourceFile = createSourceFile;