Skip to content
File

Blob: types/src/transforms/importable.ts

typescript46 lines
1// Copyright (c) 2022-2023 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5import ts from "typescript";
6import { ensureStatementModifiers } from "./helpers";
7 
8// This ensures that all top-level nodes are `export`ed, and removes
9// `declare module` blocks.
10//
11// ```ts
12// declare class A { ... }
13// declare module "thing" {
14// class B { ... }
15// }
16// ```
17//
18// --- transforms to --->
19//
20// ```ts
21// export declare class A { ... }
22// ```
23export function createImportableTransformer(): ts.TransformerFactory<ts.SourceFile> {
24 return (ctx) => {
25 return (node) => {
26 const visitor = createVisitor(ctx);
27 return ts.visitEachChild(node, visitor, ctx);
28 };
29 };
30}
31 
32function createVisitor(ctx: ts.TransformationContext): ts.Visitor {
33 return (node: ts.Node) => {
34 // Remove `module` declarations (e.g. `declare module "assets:*" {...}`) as
35 // these can't be `export`ed, and don't really make sense in non-ambient
36 // declarations
37 if (
38 ts.isModuleDeclaration(node) &&
39 (node.flags & ts.NodeFlags.Namespace) === 0
40 ) {
41 return;
42 }
43 return ensureStatementModifiers(ctx, node, { export: true });
44 };
45}