@tsplc/compiler 0.6.1 → 0.6.2

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.
@@ -0,0 +1,900 @@
1
+ import ts from "typescript";
2
+ import { copied, from, joined, type Mapped } from "../positions";
3
+ import { namesSdk, sdkModules, unaliased, valueSymbol } from "../sdk";
4
+ import { plainName } from "./layouts";
5
+ import { isExported } from "./model";
6
+
7
+ /** Whether an initializer is what a module of constants may hold: literals, tables of them, names, a task or the service client. */
8
+ export const constantInitializer = (
9
+ node: ts.Expression,
10
+ checker: ts.TypeChecker,
11
+ sdk: string,
12
+ ): boolean => {
13
+ if (
14
+ ts.isNumericLiteral(node) ||
15
+ ts.isStringLiteral(node) ||
16
+ ts.isNoSubstitutionTemplateLiteral(node) ||
17
+ ts.isBigIntLiteral(node) ||
18
+ node.kind === ts.SyntaxKind.TrueKeyword ||
19
+ node.kind === ts.SyntaxKind.FalseKeyword
20
+ ) {
21
+ return true;
22
+ }
23
+ if (ts.isPrefixUnaryExpression(node)) {
24
+ return constantInitializer(node.operand, checker, sdk);
25
+ }
26
+ if (
27
+ ts.isAsExpression(node) ||
28
+ ts.isSatisfiesExpression(node) ||
29
+ ts.isParenthesizedExpression(node)
30
+ ) {
31
+ return constantInitializer(node.expression, checker, sdk);
32
+ }
33
+ if (ts.isPropertyAccessExpression(node)) {
34
+ return ts.isIdentifier(node.expression);
35
+ }
36
+ if (ts.isIdentifier(node)) {
37
+ return true;
38
+ }
39
+ if (ts.isObjectLiteralExpression(node)) {
40
+ return node.properties.every(
41
+ (property) =>
42
+ (ts.isPropertyAssignment(property) &&
43
+ constantInitializer(property.initializer, checker, sdk)) ||
44
+ ts.isShorthandPropertyAssignment(property),
45
+ );
46
+ }
47
+ if (ts.isArrayLiteralExpression(node)) {
48
+ return node.elements.every((element) =>
49
+ constantInitializer(element, checker, sdk),
50
+ );
51
+ }
52
+ if (ts.isCallExpression(node)) {
53
+ return (
54
+ namesSdk(checker, sdk, node.expression, "createServiceClient") ||
55
+ definesTask(node, checker, sdk)
56
+ );
57
+ }
58
+ return false;
59
+ };
60
+
61
+ /** Whether `call` is `tasks.define(...)` or `backgroundTasks.define(...)`, which the async lowering compiles as written. */
62
+ export const definesTask = (
63
+ call: ts.CallExpression,
64
+ checker: ts.TypeChecker,
65
+ sdk: string,
66
+ ): boolean =>
67
+ ts.isPropertyAccessExpression(call.expression) &&
68
+ call.expression.name.text === "define" &&
69
+ (namesSdk(checker, sdk, call.expression.expression, "tasks") ||
70
+ namesSdk(checker, sdk, call.expression.expression, "backgroundTasks"));
71
+
72
+ /** A module's statements that create the service client. */
73
+ export const serviceClients = (
74
+ source: ts.SourceFile,
75
+ checker: ts.TypeChecker,
76
+ sdk: string,
77
+ ): ts.Statement[] =>
78
+ source.statements.filter(
79
+ (statement) =>
80
+ ts.isVariableStatement(statement) &&
81
+ statement.declarationList.declarations.every(
82
+ (declaration) =>
83
+ declaration.initializer &&
84
+ ts.isCallExpression(declaration.initializer) &&
85
+ namesSdk(
86
+ checker,
87
+ sdk,
88
+ declaration.initializer.expression,
89
+ "createServiceClient",
90
+ ),
91
+ ),
92
+ );
93
+
94
+ /** Whether an import names one of the SDK's modules, which every module can import. */
95
+ const importsSdk = (statement: ts.ImportDeclaration): boolean => {
96
+ const specifier = statement.moduleSpecifier;
97
+ return (
98
+ ts.isStringLiteral(specifier) &&
99
+ Object.values(sdkModules).some((module) => module === specifier.text)
100
+ );
101
+ };
102
+
103
+ /** The statement of a module-level `const` declared by a plain name; undefined for any other declaration. */
104
+ const constantStatement = (
105
+ declaration: ts.Declaration | undefined,
106
+ ): ts.VariableStatement | undefined => {
107
+ if (
108
+ !declaration ||
109
+ !ts.isVariableDeclaration(declaration) ||
110
+ !ts.isIdentifier(declaration.name) ||
111
+ !(declaration.parent.flags & ts.NodeFlags.Const)
112
+ ) {
113
+ return undefined;
114
+ }
115
+ const statement = declaration.parent.parent;
116
+ return ts.isVariableStatement(statement) && ts.isSourceFile(statement.parent)
117
+ ? statement
118
+ : undefined;
119
+ };
120
+
121
+ /** Whether a type is one literal value, or a readonly table of them, as `as const` gives. */
122
+ const literalType = (checker: ts.TypeChecker, type: ts.Type): boolean => {
123
+ if (type.isLiteral() || type.flags & ts.TypeFlags.BooleanLiteral) {
124
+ return true;
125
+ }
126
+ if (
127
+ !(type.flags & ts.TypeFlags.Object) ||
128
+ type.getCallSignatures().length ||
129
+ type.getConstructSignatures().length
130
+ ) {
131
+ return false;
132
+ }
133
+ if (checker.isTupleType(type)) {
134
+ return checker
135
+ .getTypeArguments(type as ts.TypeReference)
136
+ .every((item) => literalType(checker, item));
137
+ }
138
+ const properties = type.getProperties();
139
+ return (
140
+ properties.length > 0 &&
141
+ !type.getStringIndexType() &&
142
+ !type.getNumberIndexType() &&
143
+ properties.every((property) => {
144
+ const declaration = property.valueDeclaration;
145
+ return (
146
+ declaration !== undefined &&
147
+ ts.isPropertyAssignment(declaration) &&
148
+ literalType(checker, checker.getTypeOfSymbol(property))
149
+ );
150
+ })
151
+ );
152
+ };
153
+
154
+ /** A module-level const whose type is a literal value, which a module can declare without its value. */
155
+ const literalConstant = (
156
+ checker: ts.TypeChecker,
157
+ symbol: ts.Symbol,
158
+ ): ts.VariableDeclaration | undefined => {
159
+ const declaration = symbol.valueDeclaration;
160
+ return declaration &&
161
+ ts.isVariableDeclaration(declaration) &&
162
+ constantStatement(declaration) &&
163
+ literalType(checker, checker.getTypeAtLocation(declaration.name))
164
+ ? declaration
165
+ : undefined;
166
+ };
167
+
168
+ /** Each identifier under `node` that is no part of a type: what the code there reads. */
169
+ const readNames = (node: ts.Node): ts.Identifier[] => {
170
+ const found: ts.Identifier[] = [];
171
+ const visit = (inner: ts.Node): void => {
172
+ if (ts.isTypeNode(inner)) {
173
+ return;
174
+ }
175
+ if (ts.isIdentifier(inner)) {
176
+ found.push(inner);
177
+ }
178
+ ts.forEachChild(inner, visit);
179
+ };
180
+ visit(node);
181
+ return found;
182
+ };
183
+
184
+ /** Each identifier under `node`, in code and in types. */
185
+ const allNames = (node: ts.Node): ts.Identifier[] => {
186
+ const found: ts.Identifier[] = [];
187
+ const visit = (inner: ts.Node): void => {
188
+ if (ts.isIdentifier(inner)) {
189
+ found.push(inner);
190
+ }
191
+ ts.forEachChild(inner, visit);
192
+ };
193
+ visit(node);
194
+ return found;
195
+ };
196
+
197
+ /**
198
+ * What of each rewritten module the PLC compiles. A cut-down module is there for TypeScript and
199
+ * for other modules' types: only the constants named in `compiled` are PLC code. The entry module
200
+ * is PLC code but for the names in `declared`, which it only declares for other modules to import.
201
+ */
202
+ export type Uncompiled =
203
+ | { compiled: ReadonlySet<string> }
204
+ | { declared: ReadonlySet<string> };
205
+
206
+ /**
207
+ * Decides what stays of each plain module once its code and state have moved into the generated
208
+ * program, statement by statement:
209
+ * - its types, and its enums, stay as written;
210
+ * - a class is declared without its code, when a type that stays names it;
211
+ * - a constant stays as written when a module of constants reads it, since that module compiles as
212
+ * written and needs the value; any other constant of one literal value is declared without it,
213
+ * which is all a server's schema reads;
214
+ * - the service client it creates stays, as it does in a module of constants;
215
+ * - its re-exports stay, less the names their module no longer exports, and its imports become
216
+ * type imports, less those names, except where a constant that stays reads the value.
217
+ *
218
+ * Nothing else stays: functions and state are in the generated modules.
219
+ */
220
+ export class Reduction {
221
+ /** The constants a module of constants reads, each staying as written. */
222
+ private readonly needed = new Set<ts.VariableDeclaration>();
223
+ /** The classes a type that stays names, each declared without its code. */
224
+ private readonly classes = new Set<ts.ClassDeclaration>();
225
+ /** Whether each constant may stay as written, once asked. */
226
+ private readonly plain = new Map<ts.VariableDeclaration, boolean>();
227
+ private readonly cutDown: ReadonlySet<ts.SourceFile>;
228
+ private entryDeclares: ReadonlySet<string> = new Set();
229
+ private readonly runtime: ReadonlySet<ts.SourceFile>;
230
+
231
+ constructor(
232
+ private readonly checker: ts.TypeChecker,
233
+ private readonly sdk: string,
234
+ private readonly options: {
235
+ /** The program's own modules. */
236
+ runtime: readonly ts.SourceFile[];
237
+ /** Modules the compiled program keeps as written. */
238
+ kept: (file: string) => boolean;
239
+ entry: ts.SourceFile;
240
+ /** The bindings scan code assigns, which are state. */
241
+ written: ReadonlySet<ts.Symbol>;
242
+ /** The bindings the config's `io` reaches state through. */
243
+ bound: ReadonlySet<string>;
244
+ },
245
+ ) {
246
+ const { runtime, kept, entry } = options;
247
+ this.runtime = new Set(runtime);
248
+ this.cutDown = new Set(
249
+ runtime.filter((source) => source !== entry && !kept(source.fileName)),
250
+ );
251
+ for (const source of runtime) {
252
+ if (!kept(source.fileName)) {
253
+ continue;
254
+ }
255
+ for (const statement of source.statements) {
256
+ // Importing or re-exporting a name reads nothing: the code that uses it does.
257
+ if (
258
+ !ts.isImportDeclaration(statement) &&
259
+ !ts.isExportDeclaration(statement)
260
+ ) {
261
+ this.need(statement);
262
+ }
263
+ }
264
+ }
265
+ for (const source of runtime) {
266
+ if (kept(source.fileName)) {
267
+ this.declareClasses(source);
268
+ }
269
+ if (!this.cutDown.has(source)) {
270
+ continue;
271
+ }
272
+ for (const statement of source.statements) {
273
+ if (
274
+ ts.isInterfaceDeclaration(statement) ||
275
+ ts.isTypeAliasDeclaration(statement) ||
276
+ this.keptWritten(statement)
277
+ ) {
278
+ this.declareClasses(statement);
279
+ }
280
+ }
281
+ }
282
+ }
283
+
284
+ /** The modules cut down, which hold no PLC code but the constants a module of constants reads. */
285
+ get modules(): readonly ts.SourceFile[] {
286
+ return [...this.cutDown];
287
+ }
288
+
289
+ /** Marks the constants of cut-down modules that the code under `node` reads, and those they read. */
290
+ private need(node: ts.Node): void {
291
+ for (const name of readNames(node)) {
292
+ const symbol = valueSymbol(this.checker, name);
293
+ const declaration =
294
+ symbol && unaliased(this.checker, symbol).valueDeclaration;
295
+ if (
296
+ declaration &&
297
+ ts.isVariableDeclaration(declaration) &&
298
+ this.cutDown.has(declaration.getSourceFile()) &&
299
+ !this.needed.has(declaration) &&
300
+ this.staysWritten(declaration)
301
+ ) {
302
+ // A statement stays whole, so every constant it declares is read.
303
+ const list = declaration.parent;
304
+ for (const each of ts.isVariableDeclarationList(list)
305
+ ? list.declarations
306
+ : []) {
307
+ this.needed.add(each);
308
+ if (each.initializer) {
309
+ this.need(each.initializer);
310
+ }
311
+ }
312
+ }
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Whether a cut-down module's constant can stay as written: it is a literal, or a table of
318
+ * literals and of other values that stay, and neither scan code nor the hardware writes it.
319
+ */
320
+ private staysWritten(declaration: ts.VariableDeclaration): boolean {
321
+ const known = this.plain.get(declaration);
322
+ if (known !== undefined) {
323
+ return known;
324
+ }
325
+ // A constant can't read itself, so one asked about again while being decided is not at fault.
326
+ this.plain.set(declaration, true);
327
+ const statement = constantStatement(declaration);
328
+ const stays = Boolean(
329
+ statement?.declarationList.declarations.every((each) =>
330
+ this.dataOnly(each),
331
+ ),
332
+ );
333
+ this.plain.set(declaration, stays);
334
+ return stays;
335
+ }
336
+
337
+ private dataOnly(declaration: ts.VariableDeclaration): boolean {
338
+ const { checker, sdk } = this;
339
+ const { written, bound } = this.options;
340
+ const symbol = checker.getSymbolAtLocation(declaration.name);
341
+ const initializer = declaration.initializer;
342
+ const calls = (node: ts.Node): boolean =>
343
+ ts.isCallExpression(node) || Boolean(ts.forEachChild(node, calls));
344
+ return (
345
+ ts.isIdentifier(declaration.name) &&
346
+ initializer !== undefined &&
347
+ constantInitializer(initializer, checker, sdk) &&
348
+ !calls(initializer) &&
349
+ !(symbol && written.has(symbol)) &&
350
+ !bound.has(declaration.name.text) &&
351
+ readNames(initializer).every((name) => this.readable(name))
352
+ );
353
+ }
354
+
355
+ /** Whether what `name` reads still has its value once every module is rewritten. */
356
+ private readable(name: ts.Identifier): boolean {
357
+ // A property's own name reads nothing.
358
+ if (
359
+ (ts.isPropertyAccessExpression(name.parent) &&
360
+ name.parent.name === name) ||
361
+ (ts.isPropertyAssignment(name.parent) && name.parent.name === name)
362
+ ) {
363
+ return true;
364
+ }
365
+ const symbol = valueSymbol(this.checker, name);
366
+ const declaration =
367
+ symbol && unaliased(this.checker, symbol).valueDeclaration;
368
+ if (!declaration) {
369
+ return true;
370
+ }
371
+ const source = declaration.getSourceFile();
372
+ if (!this.runtime.has(source) || this.options.kept(source.fileName)) {
373
+ return true;
374
+ }
375
+ // What the entry module declares is settled only once its code is generated.
376
+ if (ts.isEnumDeclaration(declaration)) {
377
+ return source !== this.options.entry && this.keepsEnum(declaration);
378
+ }
379
+ return (
380
+ ts.isVariableDeclaration(declaration) &&
381
+ this.cutDown.has(source) &&
382
+ this.staysWritten(declaration)
383
+ );
384
+ }
385
+
386
+ /** Whether a statement of a cut-down module stays as written because a module of constants reads it. */
387
+ private keptWritten(statement: ts.Statement): boolean {
388
+ return (
389
+ ts.isVariableStatement(statement) &&
390
+ statement.declarationList.declarations.some((declaration) =>
391
+ this.needed.has(declaration),
392
+ )
393
+ );
394
+ }
395
+
396
+ /** Marks the classes of cut-down modules that anything under `node` names, and those their members name. */
397
+ private declareClasses(node: ts.Node): void {
398
+ for (const name of allNames(node)) {
399
+ const symbol = this.checker.getSymbolAtLocation(name);
400
+ this.declareClass(symbol && unaliased(this.checker, symbol));
401
+ }
402
+ }
403
+
404
+ private declareClass(symbol: ts.Symbol | undefined): void {
405
+ const declaration = symbol?.declarations?.find(ts.isClassDeclaration);
406
+ if (
407
+ !symbol ||
408
+ !declaration?.name ||
409
+ !this.cutDown.has(declaration.getSourceFile()) ||
410
+ this.classes.has(declaration)
411
+ ) {
412
+ return;
413
+ }
414
+ this.classes.add(declaration);
415
+ // Its members are declared by their types, written or inferred, which may name more classes.
416
+ const instance = this.checker.getDeclaredTypeOfSymbol(symbol);
417
+ for (const property of this.checker.getPropertiesOfType(instance)) {
418
+ const member = property.valueDeclaration;
419
+ if (
420
+ member &&
421
+ !(ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Private)
422
+ ) {
423
+ this.declareTypeClasses(
424
+ this.checker.getTypeOfSymbolAtLocation(property, declaration),
425
+ new Set(),
426
+ );
427
+ }
428
+ }
429
+ }
430
+
431
+ /** Marks the classes a member's type names: the type itself, a union's parts, and an array's or a generic's arguments. */
432
+ private declareTypeClasses(type: ts.Type, seen: Set<ts.Type>): void {
433
+ if (seen.has(type) || seen.size > 64) {
434
+ return;
435
+ }
436
+ seen.add(type);
437
+ this.declareClass(type.getSymbol());
438
+ const parts = [
439
+ ...(type.isUnionOrIntersection() ? type.types : []),
440
+ ...(type.aliasTypeArguments ?? []),
441
+ ...(type.flags & ts.TypeFlags.Object &&
442
+ (type as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference
443
+ ? this.checker.getTypeArguments(type as ts.TypeReference)
444
+ : []),
445
+ ];
446
+ for (const part of parts) {
447
+ this.declareTypeClasses(part, seen);
448
+ }
449
+ }
450
+
451
+ /**
452
+ * Whether an enum's declaration stays in its module as written. One whose member is computed
453
+ * from a constant doesn't: the constant may not stay.
454
+ */
455
+ keepsEnum(declaration: ts.EnumDeclaration): boolean {
456
+ const source = declaration.getSourceFile();
457
+ if (!this.runtime.has(source) || this.options.kept(source.fileName)) {
458
+ return true;
459
+ }
460
+ const fixed = declaration.members.every(
461
+ (member) =>
462
+ !member.initializer ||
463
+ readNames(member.initializer).every((name) => {
464
+ const symbol = this.checker.getSymbolAtLocation(name);
465
+ return (
466
+ symbol !== undefined &&
467
+ Boolean(symbol.flags & ts.SymbolFlags.EnumMember)
468
+ );
469
+ }),
470
+ );
471
+ // The entry module is written anew, and declares again only the enums it exports.
472
+ return (
473
+ fixed &&
474
+ (source !== this.options.entry || this.exportedByName(declaration))
475
+ );
476
+ }
477
+
478
+ /** Whether an enum is one the generated modules can import from its own module, by its own name. */
479
+ sharesEnum(declaration: ts.EnumDeclaration): boolean {
480
+ return this.keepsEnum(declaration) && this.exportedByName(declaration);
481
+ }
482
+
483
+ /** Why the generated modules can't import an enum that `sharesEnum` refuses, for the program's author. */
484
+ enumRefusal(declaration: ts.EnumDeclaration): string {
485
+ const name = declaration.name.text;
486
+ return this.exportedByName(declaration)
487
+ ? `${name}: give each member of this enum a literal value. The generated code stores the enum and imports it from its module, where a member computed from a constant can't stay.`
488
+ : `${name}: export this enum from its module. The generated code stores it, and imports it from there.`;
489
+ }
490
+
491
+ private exportedByName(declaration: ts.EnumDeclaration): boolean {
492
+ const module = this.checker.getSymbolAtLocation(
493
+ declaration.getSourceFile(),
494
+ );
495
+ const symbol = this.checker.getSymbolAtLocation(declaration.name);
496
+ const exported =
497
+ module &&
498
+ this.checker
499
+ .getExportsOfModule(module)
500
+ .find((candidate) => candidate.name === declaration.name.text);
501
+ return (
502
+ isExported(declaration) ||
503
+ (exported !== undefined &&
504
+ symbol !== undefined &&
505
+ unaliased(this.checker, exported) === symbol)
506
+ );
507
+ }
508
+
509
+ /**
510
+ * Whether a module still exports `symbol`'s value once every module is rewritten. A type always
511
+ * survives; the entry module is written anew, and exports only its scan functions, its exported
512
+ * enums and the constants it declares.
513
+ */
514
+ survives(symbol: ts.Symbol): boolean {
515
+ const declaration = symbol.valueDeclaration;
516
+ if (!(symbol.flags & ts.SymbolFlags.Value) || !declaration) {
517
+ return true;
518
+ }
519
+ const source = declaration.getSourceFile();
520
+ if (!this.runtime.has(source) || this.options.kept(source.fileName)) {
521
+ return true;
522
+ }
523
+ if (source === this.options.entry) {
524
+ return this.exportedNames(symbol).some((name) =>
525
+ this.entryDeclares.has(name),
526
+ );
527
+ }
528
+ if (ts.isEnumDeclaration(declaration)) {
529
+ return this.keepsEnum(declaration);
530
+ }
531
+ if (ts.isClassDeclaration(declaration)) {
532
+ return this.classes.has(declaration);
533
+ }
534
+ return (
535
+ ts.isVariableDeclaration(declaration) &&
536
+ (this.needed.has(declaration) ||
537
+ literalConstant(this.checker, symbol) !== undefined ||
538
+ serviceClients(source, this.checker, this.sdk).includes(
539
+ declaration.parent.parent,
540
+ ))
541
+ );
542
+ }
543
+
544
+ /** The names the entry module exports `symbol` by. */
545
+ private exportedNames(symbol: ts.Symbol): string[] {
546
+ const module = this.checker.getSymbolAtLocation(this.options.entry);
547
+ return (module ? this.checker.getExportsOfModule(module) : [])
548
+ .filter((exported) => unaliased(this.checker, exported) === symbol)
549
+ .map((exported) => exported.name);
550
+ }
551
+
552
+ /**
553
+ * Tells which of its exported enums and constants the generated entry module did declare, by
554
+ * name: it leaves out one whose name its own code uses, and other modules' imports follow.
555
+ */
556
+ declaredByEntry(names: ReadonlySet<string>): void {
557
+ this.entryDeclares = names;
558
+ }
559
+
560
+ /** The constants of a cut-down module that stay as written, which the PLC compiles. */
561
+ compiled(source: ts.SourceFile): Set<string> {
562
+ return new Set(
563
+ [...this.needed]
564
+ .filter((declaration) => declaration.getSourceFile() === source)
565
+ .map((declaration) => declaration.name.getText()),
566
+ );
567
+ }
568
+
569
+ /** A plain module, cut down to what stays of it. */
570
+ module(source: ts.SourceFile): Mapped {
571
+ const { checker, sdk } = this;
572
+ const clients = serviceClients(source, checker, sdk);
573
+ // The imports a constant that stays reads the value of.
574
+ const read = new Set(
575
+ source.statements
576
+ .filter((statement) => this.keptWritten(statement))
577
+ .flatMap(readNames)
578
+ .flatMap((name) => valueSymbol(checker, name) ?? []),
579
+ );
580
+ return joined(
581
+ [
582
+ ...source.statements.flatMap((statement): Mapped[] => {
583
+ if (
584
+ ts.isInterfaceDeclaration(statement) ||
585
+ ts.isTypeAliasDeclaration(statement) ||
586
+ (ts.isEnumDeclaration(statement) && this.keepsEnum(statement)) ||
587
+ clients.includes(statement) ||
588
+ this.keptWritten(statement)
589
+ ) {
590
+ return [copied(statement)];
591
+ }
592
+ if (ts.isClassDeclaration(statement)) {
593
+ return this.classes.has(statement)
594
+ ? [from(statement, this.declaredClass(statement))]
595
+ : [];
596
+ }
597
+ if (ts.isImportDeclaration(statement)) {
598
+ return statement.importClause?.isTypeOnly ||
599
+ (clients.length > 0 && importsSdk(statement))
600
+ ? [copied(statement)]
601
+ : this.imports(statement, read);
602
+ }
603
+ if (ts.isExportDeclaration(statement) && statement.moduleSpecifier) {
604
+ return this.reExports(statement);
605
+ }
606
+ return [];
607
+ }),
608
+ ...this.listedExports(source, (declaration) =>
609
+ this.stays(declaration, clients),
610
+ ).lines,
611
+ "export {};",
612
+ ],
613
+ "\n",
614
+ );
615
+ }
616
+
617
+ /** Whether a cut-down module's own declaration is still in it, under its own name. */
618
+ private stays(
619
+ declaration: ts.Declaration,
620
+ clients: readonly ts.Statement[],
621
+ ): boolean {
622
+ if (
623
+ ts.isInterfaceDeclaration(declaration) ||
624
+ ts.isTypeAliasDeclaration(declaration)
625
+ ) {
626
+ return true;
627
+ }
628
+ if (ts.isEnumDeclaration(declaration)) {
629
+ return this.keepsEnum(declaration);
630
+ }
631
+ if (ts.isClassDeclaration(declaration)) {
632
+ return this.classes.has(declaration);
633
+ }
634
+ return (
635
+ ts.isVariableDeclaration(declaration) &&
636
+ (this.needed.has(declaration) ||
637
+ clients.includes(declaration.parent.parent))
638
+ );
639
+ }
640
+
641
+ /**
642
+ * What the generated entry module declares besides its code, for other modules and the server
643
+ * to import: the enums the entry exports, as written, and its exported constants of one literal
644
+ * value, without their values. None is PLC code of the entry's.
645
+ */
646
+ entry(): {
647
+ enums: { name: string; line: Mapped }[];
648
+ constants: { name: string; line: Mapped }[];
649
+ } {
650
+ const source = this.options.entry;
651
+ const enums = source.statements
652
+ .filter(ts.isEnumDeclaration)
653
+ .filter((statement) => this.sharesEnum(statement));
654
+ // An enum the entry exports in a list is exported where it is declared here.
655
+ const text = (statement: ts.EnumDeclaration): Mapped =>
656
+ isExported(statement)
657
+ ? copied(statement)
658
+ : joined(["export ", copied(statement)], "");
659
+ return {
660
+ enums: enums.map((statement) => ({
661
+ name: statement.name.text,
662
+ line: text(statement),
663
+ })),
664
+ constants: this.listedExports(source, () => false).declared,
665
+ };
666
+ }
667
+
668
+ /**
669
+ * The exports a module's statements that stay don't carry themselves: a name its export list or
670
+ * default export gives a declaration that `stays`, and each exported constant of one literal
671
+ * value that doesn't stay, declared without its value. A server's schema can size a wire field
672
+ * by such a constant, and reads that size from its type.
673
+ */
674
+ private listedExports(
675
+ source: ts.SourceFile,
676
+ stays: (declaration: ts.Declaration) => boolean,
677
+ ): { lines: Mapped[]; declared: { name: string; line: Mapped }[] } {
678
+ const { checker } = this;
679
+ const module = checker.getSymbolAtLocation(source);
680
+ const lines: Mapped[] = [];
681
+ const declared: { name: string; line: Mapped }[] = [];
682
+ for (const exported of module ? checker.getExportsOfModule(module) : []) {
683
+ // A name re-exported from another module is that module's to declare.
684
+ const here = exported.declarations?.find(
685
+ (declaration) =>
686
+ declaration.getSourceFile() === source &&
687
+ !(
688
+ ts.isExportSpecifier(declaration) &&
689
+ declaration.parent.parent.moduleSpecifier
690
+ ),
691
+ );
692
+ const target = unaliased(checker, exported);
693
+ const declaration = target.declarations?.find(
694
+ (candidate) =>
695
+ candidate.getSourceFile() === source &&
696
+ !ts.isExportSpecifier(candidate) &&
697
+ !ts.isExportAssignment(candidate),
698
+ );
699
+ if (!here || !declaration) {
700
+ continue;
701
+ }
702
+ const isDefault = exported.name === "default";
703
+ if (stays(declaration)) {
704
+ // A declaration exported where it is declared carries its own export.
705
+ if (here === declaration && !isDefault) {
706
+ continue;
707
+ }
708
+ // A class declared without its code exports itself, default or not.
709
+ if (here === declaration && ts.isClassDeclaration(declaration)) {
710
+ continue;
711
+ }
712
+ const keyword =
713
+ target.flags & ts.SymbolFlags.Value ? "export" : "export type";
714
+ lines.push(
715
+ from(
716
+ here,
717
+ isDefault
718
+ ? `export default ${target.name};`
719
+ : `${keyword} { ${target.name === exported.name ? target.name : `${target.name} as ${exported.name}`} };`,
720
+ ),
721
+ );
722
+ continue;
723
+ }
724
+ const constant = literalConstant(checker, target);
725
+ // The entry module's code is PLC code, where a default export has no meaning.
726
+ if (!constant || (isDefault && source === this.options.entry)) {
727
+ continue;
728
+ }
729
+ const type = checker.typeToString(
730
+ checker.getTypeAtLocation(constant.name),
731
+ undefined,
732
+ ts.TypeFormatFlags.NoTruncation,
733
+ );
734
+ const line = from(
735
+ constant,
736
+ isDefault
737
+ ? `declare const tsplcDefault: ${type};\nexport default tsplcDefault;`
738
+ : `export declare const ${exported.name}: ${type};`,
739
+ );
740
+ declared.push({ name: exported.name, line });
741
+ lines.push(line);
742
+ }
743
+ return { lines, declared };
744
+ }
745
+
746
+ /**
747
+ * An import's names that the module they come from still exports. Each is imported as a type,
748
+ * which is all the declarations left can use, unless a constant that stays reads its value.
749
+ */
750
+ private imports(
751
+ statement: ts.ImportDeclaration,
752
+ read: ReadonlySet<ts.Symbol>,
753
+ ): Mapped[] {
754
+ const { checker } = this;
755
+ const clause = statement.importClause;
756
+ if (!clause) {
757
+ return [];
758
+ }
759
+ const local = (name: ts.Identifier) => checker.getSymbolAtLocation(name);
760
+ const surviving = (name: ts.Identifier): boolean => {
761
+ const symbol = local(name);
762
+ return symbol !== undefined && this.survives(unaliased(checker, symbol));
763
+ };
764
+ const isRead = (name: ts.Identifier): boolean => {
765
+ const symbol = local(name);
766
+ return symbol !== undefined && read.has(symbol);
767
+ };
768
+ const specifier = statement.moduleSpecifier.getText();
769
+ const bindings = clause.namedBindings;
770
+ const named =
771
+ bindings && ts.isNamedImports(bindings)
772
+ ? bindings.elements.filter((element) => surviving(element.name))
773
+ : [];
774
+ const list = (elements: readonly ts.ImportSpecifier[]): string =>
775
+ elements
776
+ .map((element) =>
777
+ element.propertyName
778
+ ? `${element.propertyName.getText()} as ${element.name.text}`
779
+ : element.name.text,
780
+ )
781
+ .join(", ");
782
+ const values = named.filter(
783
+ (element) => !element.isTypeOnly && isRead(element.name),
784
+ );
785
+ const types = named.filter((element) => !values.includes(element));
786
+ const lines: string[] = [];
787
+ if (clause.name && surviving(clause.name)) {
788
+ lines.push(
789
+ `${isRead(clause.name) ? "import" : "import type"} ${clause.name.text} from ${specifier};`,
790
+ );
791
+ }
792
+ if (bindings && ts.isNamespaceImport(bindings)) {
793
+ lines.push(
794
+ `${isRead(bindings.name) ? "import" : "import type"} * as ${bindings.name.text} from ${specifier};`,
795
+ );
796
+ }
797
+ if (values.length) {
798
+ lines.push(`import { ${list(values)} } from ${specifier};`);
799
+ }
800
+ if (types.length) {
801
+ lines.push(`import type { ${list(types)} } from ${specifier};`);
802
+ }
803
+ return lines.map((line) => from(statement, line));
804
+ }
805
+
806
+ /** A re-export, without the names the module it names no longer exports. */
807
+ private reExports(statement: ts.ExportDeclaration): Mapped[] {
808
+ const clause = statement.exportClause;
809
+ if (statement.isTypeOnly || !clause || !ts.isNamedExports(clause)) {
810
+ return [copied(statement)];
811
+ }
812
+ const kept = clause.elements.filter((element) => {
813
+ const symbol = this.checker.getSymbolAtLocation(element.name);
814
+ return (
815
+ element.isTypeOnly ||
816
+ (symbol !== undefined && this.survives(unaliased(this.checker, symbol)))
817
+ );
818
+ });
819
+ return kept.length
820
+ ? [
821
+ from(
822
+ statement,
823
+ `export { ${kept.map((element) => element.getText()).join(", ")} } from ${statement.moduleSpecifier?.getText()};`,
824
+ ),
825
+ ]
826
+ : [];
827
+ }
828
+
829
+ /**
830
+ * A class as a declaration of what its instances hold: every field and method, its base classes'
831
+ * among them, with the type each was written with or has. That is what a type naming the class
832
+ * needs; the class's code is in the generated program.
833
+ */
834
+ private declaredClass(node: ts.ClassDeclaration): string {
835
+ const { checker } = this;
836
+ const symbol = node.name && checker.getSymbolAtLocation(node.name);
837
+ const name = node.name?.text ?? "";
838
+ const flags = ts.TypeFormatFlags.NoTruncation;
839
+ const members = symbol
840
+ ? checker
841
+ .getPropertiesOfType(checker.getDeclaredTypeOfSymbol(symbol))
842
+ .flatMap((property): string[] => {
843
+ const member = property.valueDeclaration;
844
+ if (!member || !plainName(property.name)) {
845
+ return [];
846
+ }
847
+ const modifiers = ts.getCombinedModifierFlags(member);
848
+ // A private member has no type other code may use, only its name.
849
+ if (modifiers & ts.ModifierFlags.Private) {
850
+ return [`private ${property.name};`];
851
+ }
852
+ const access =
853
+ modifiers & ts.ModifierFlags.Protected ? "protected " : "";
854
+ const type = checker.getTypeOfSymbolAtLocation(property, node);
855
+ if (property.flags & ts.SymbolFlags.Method) {
856
+ return type
857
+ .getCallSignatures()
858
+ .map(
859
+ (signature) =>
860
+ `${access}${property.name}${checker.signatureToString(signature, node, flags)};`,
861
+ );
862
+ }
863
+ const written =
864
+ (ts.isPropertyDeclaration(member) || ts.isParameter(member)) &&
865
+ member.type &&
866
+ member.getSourceFile() === node.getSourceFile()
867
+ ? member.type.getText()
868
+ : checker.typeToString(type, node, flags);
869
+ const readonly =
870
+ modifiers & ts.ModifierFlags.Readonly ||
871
+ (property.flags & ts.SymbolFlags.GetAccessor &&
872
+ !(property.flags & ts.SymbolFlags.SetAccessor))
873
+ ? "readonly "
874
+ : "";
875
+ const optional =
876
+ property.flags & ts.SymbolFlags.Optional ? "?" : "";
877
+ return [
878
+ `${access}${readonly}${property.name}${optional}: ${written};`,
879
+ ];
880
+ })
881
+ : [];
882
+ const modifiers = ts.getCombinedModifierFlags(node);
883
+ const isDefault = Boolean(modifiers & ts.ModifierFlags.Default);
884
+ const head = [
885
+ modifiers & ts.ModifierFlags.Export && !isDefault ? "export " : "",
886
+ "declare ",
887
+ modifiers & ts.ModifierFlags.Abstract ? "abstract " : "",
888
+ `class ${name}`,
889
+ node.typeParameters
890
+ ? `<${node.typeParameters.map((parameter) => parameter.getText()).join(", ")}>`
891
+ : "",
892
+ ].join("");
893
+ return [
894
+ `${head} {`,
895
+ ...members.map((member) => `\t${member}`),
896
+ "}",
897
+ ...(isDefault ? [`export default ${name};`] : []),
898
+ ].join("\n");
899
+ }
900
+ }