iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎐

packelyze - Your TypeScript can be even smaller

に公開
2023/06/13
2件

I released @mizchi/optools for aggressive compression using TypeScript definition files. It's still experimental, but it should work reasonably well. Use at your own risk.

Update: Renamed optools to packelyze. This is because the CLI name optools conflicted with a command provided by ImageMagick.

https://github.com/mizchi/packelyze/tree/main/cli

The trial-and-error process can be found at https://zenn.dev/mizchi/scraps/1bdf01f5efb147.

I created this library during my working hours at Plaid, where I am employed.

Target Users

  • Library authors
  • Frontend developers with strict build size constraints (third-party scripts, etc. This is why I created it for work)
  • Frontend authors who want to reduce build size even at some risk

Motivation

Although TypeScript code could theoretically be compressed much further by using its type information, Terser targets plain JS. As a result, it assumes object access and dynamic rewrites, preventing aggressive compression.

For example, the following code performs poorly during compression.

class InnerClass {
  publicMethod() {
    this.privateMethod();
    return this;
  }
  privateMethod() {}
}

export class MyClass {
  value = 1;
  hello() {
    new InnerClass().publicMethod().publicMethod().publicMethod();
    return this; 
  }
}

const myClass = new MyClass();
console.log(myClass.hello().value);

Minifying this results in the following:

class e{publicMethod(){return this.privateMethod(),this}privateMethod(){}}export class MyClass{value=1;hello(){return(new e).publicMethod().publicMethod().publicMethod(),this}}const t=new MyClass;console.log(t.publicMethod().value);

Ideally, only MyClass and hello should be preserved, and all other variables should be shortened to a single character (mangled). In other words, it should look like this:

class s{o(){return this.p(),this}p(){}}export class MyClass{value=1;hello(){return(new s).o().o().o(),this}}const l=new MyClass;console.log(l.hello().value);

In short, I wrote a library to do exactly that.

Usage

$ npm install @mizchi/optools -D 

Alternatively, you can use npx directly (e.g., $ npx @mizchi/optools analyze-dts -i lib/index.d.ts -o _analyzed.json).

To use optools, generate the type definition files (.d.ts) for your codebase beforehand.

Example tsconfig.json to generate lib/*.d.ts:

{
  "compilerOptions": {
    "rootDir": "src",
    "outDir": "lib",
    "declaration": true,
    "emitDeclarationOnly": true,
  }
}

Running tsc -p . or similar will output the types.

Using the type definition file of the entry point of that codebase (e.g., lib/index.d.ts) as input, output the analysis results as _analyzed.json.

$ npx @mizchi/optools analyze-dts -i lib/index.d.ts -o _analyzed.json

Pass this analysis result _analyzed.json to Terser's mangle.properties.reserved. In doing so, pass the most aggressive option .* to the regex. This means everything except analyzed.reserved will be subject to mangling.

vite.config.ts
import { defineConfig } from "vite";
import analyzed from "./_analyzed.json";

export default defineConfig({
  build: {
    // use terser: because esbuild does not support mangle properties builtins
    minify: "terser",
    terserOptions: {
      mangle: {
        properties: {
          regex: /.*/,
          reserved: analyzed.reserved,
        },
      },
    },
  },
});

Unfortunately, this could not be used with esbuild --minify. While Terser respects built-in properties using its internal dictionary, esbuild will crush them if they match the regex. I haven't checked swc yet.

As a result, everything except the exported public interfaces becomes a target for compression, significantly reducing the code size.

While providing the entry point's type definition to this interface might seem meaningless if it's not a library (as nothing is exported), it can also be used for declaring external side effects, which I will describe later.

Note: Declaring External Side Effects

While this is sufficient within the scope of ESM inputs and outputs, it doesn't account for external side effects. For instance, it might mangle keys inside objects passed to fetch() or postMessage(). This could cause a problem where code like {keepMe: 1} is sent to a server as {o: 1}.

(Slightly off-topic, but at this stage, one starts to want an Effect System found in some functional languages. However, implementing that in TypeScript is no easy task.)

Therefore, you need to inform optools of these types by using export type in your entry point, such as src/index.ts.

src/index.ts
export type __Effects =
  | MySendBodyType
  | MySendResponseType
  // ... others
  ;

If you are generating type definitions via OpenAPI or similar, you would likely just use export type * from "./types".

Recently, I created a library called @mizchi/zero-runtime which allows declaring types for raw fetch.

import type { TypedFetch, JSON$stringifyT, JSON$parseT } from "@mizchi/zero-runtime";

const stringifyT = JSON.stringify as JSON$stringifyT;

const fetch = window.fetch as TypedFetch<{
  // Self
  "": {
    "/api/:xxx": {
      methodType: "GET";
      bodyType: { text: string; number: number; boolean: boolean };
      headersType: { "Content-Type": "application/json" };
      responseType: { text: string; number: number; boolean: boolean };
    } | {
      methodType: "POST";
      bodyType: { postData: number };
      headersType: { "Content-Type": "application/json" };
      responseType: { ok: boolean };
    };
    "/api/nested/:pid": {
      methodType: "GET";
      bodyType: { nested: 1 };
      headersType: { "Content-Type": "application/json" };
      responseType: { text: string; number: number; boolean: boolean };
    };
    "/search": {
      methodType: "GET";
      headersType: { "Content-Type": "application/json" };
      responseType: { text: string };
      // NOTE: Not handle as type yet.
      searchType: { q: string }
    },
  },
  // with host
  "https://z.test": {
    "/send": {
      methodType: "POST";
      bodyType: { text: string; };
      headersType: { "Content-Type": "application/json" };
      responseType: { ok: boolean };
    };
  };
}>;
const res = await fetchT("/api/xxxeuoau", {
  method: "GET",
  headers: {
    "Content-Type": "application/json",
  },
  body: stringifyT({ text: "text", number: 1, boolean: true }),
});

I also created a validator called lizod. It is designed to be used with TypedFetch from @mizchi/zero-runtime. By preparing validators and types to use with typed fetch, the pieces needed to use optools safely come together naturally.

https://zenn.dev/mizchi/articles/lizod-is-lightweight-zod

Of course, verification is necessary to see if this can truly be used safely, and it cannot be called "production ready" yet. In places where non-type-safe TypeScript operations are performed, or if eval() or new Function() are used internally, the safety is quite compromised. To be blunt, it is a tool that cannot be used properly unless you can pre-emptively account for side effects and reflection occurring within the code.

benchmark

I picked some libraries and compared the size after minification with and without optools.

https://github.com/mizchi/optools/tree/main/examples/benchmark

23K hono-usage.js
19K hono.js
45K react-library.js
52K zod-usage.js
2.8M May 25 20:57 typescript.js
terser with optools

21K hono-usage.js
17K hono.js
41K react-library.js
43K zod-usage.js
2.1M typescript.js

TypeScript has shrunk to about 75% of its original size. This is likely because it contains many internal namespaces that are not exposed externally, which were effectively compressed.

Since code that hasn't been mangled is generally easier to compress using Huffman coding, let's look at the difference after applying gzip.

805K typescript.js.gz
700K typescript.js.gz

Even then, there is still a difference of nearly 100KB. It's fair to say that optools is effective.

"There's no way I can use such aggressive compression! Let me verify its safety somehow!"

To address this, I created a snapshot testing pattern using Vitest.

vite.config.ts
import { defineConfig } from "vite";
import analyzed from "./_analyzed.json";
import { minify } from "terser";

export default defineConfig({
  plugins: [
    {
      name: "optools safety check",
      enforce: "post",
      async transform(code, id) {
        if (!process.env.OPTOOLS_CHECK) return;
        if (id.endsWith(".js") || id.endsWith('.ts' || id.endsWith('.tsx'))) {
          const result = await minify(code, {
            compress: false
            mangle: {
              module: true,
              properties: {
                regex: /^.*$/,
                reserved: analyzed.reserved,
              },
            },
          });
          return result.code;
        }
      },
    },
  ],
});

If OPTOOLS_CHECK is true, this minifier is applied to individual file loads. (Note that this can be quite heavy as it runs Terser on every file when enabled.)

I then test whether the internal objects match the snapshot against this.

src/fetch.test.ts
import { expect, test } from "vitest";
import type { JSON$stringifyT } from "@mizchi/zero-runtime";

const stringifyT = JSON.stringify as JSON$stringifyT;

test("keep send body", async () => {
  // Create a large object within the codebase
  const body = stringifyT({ keepMe: "hello" });
  expect(body).toMatchSnapshot();
});

You run this twice with different environment variables:

$ pnpm vitest --run # it creates __snapshot__
$ OPTOOLS_CHECK=1 pnpm vitest --run # should match with result with mangling

If the snapshots match, you can guarantee that the properties were not incorrectly mangled.

Internal Implementation

This section is for those who want to know the internal details.

During my investigation, I found a Rollup plugin called rollup-plugin-dts. Upon closer inspection, it's not just a simple Rollup plugin; it handles the process of bundling type definition files into one, something that TypeScript itself doesn't provide. The author seemed frustrated that the TypeScript core team doesn't support this feature.

https://github.com/Swatinem/rollup-plugin-dts#why
https://github.com/Microsoft/TypeScript/issues/4433

Impressively, rollup-plugin-dts uses Rollup's tree-shaking functionality (I haven't tracked the implementation details precisely, but presumably so) to drop type definitions that aren't exported. This means that if you analyze the single, final bundled type definition, only the actual public interfaces remain.

When you analyze https://github.com/mizchi/optools/tree/main/examples/playground, the following type definition file is generated. It can be output using the --printDts flag.

$ pnpm tsc -p . # emit
$ npx @mizchi/optools analyze-dts -i lib/index.d.ts --printDts
// bundled.d.ts
type Output = {
    result: {
        value: number;
    };
};
type PubType = {
    pubTypeKey: number;
};
interface InterfaceType {
    ikey: number;
}
declare function sub(opts: {
    xxx: number;
    yyy: string;
}): {
    value: number;
};
declare function effect(str: string): Promise<Response>;
declare class PublicClass {
    #private;
    "A-B"(): void;
    publicMethod(): Output;
    private privateMethod;
    private privateMethod2;
    private privateMethod3;
    private privateMethod4;
}
declare module PublicModule {
    module nested {
        const y = 1;
    }
    interface PublicModuleInterface {
    }
    class PublicModuleClass {
        publicModuleClassMethod(): Output;
        private privateModuleClassMethod;
    }
    type PublicModuleType = {
        pubModType: number;
    };
    const pubModConst = 1;
}

export { InterfaceType, PubType, PublicClass, PublicModule, effect, sub };

I implemented the logic to analyze these type definitions and extract only the keys of TypeLiteral and the public properties of class myself.

https://github.com/mizchi/optools/blob/main/cli/src/analyzer.mts#L8-L155

optools relies heavily on rollup-plugin-dts; this library already handles the process of bundling type definition files while preserving only the public interfaces.

What I actually implemented was just the part that traverses the AST of the bundled .d.ts file to extract the public interfaces.

Understanding this, a tip for users is that the smaller you keep your public interfaces, the higher the compression efficiency will be.

Future

To be honest, compared to what I originally envisioned, it ended up as a product of compromise—it simply lists likely keys without being able to distinguish their call sites, leading to many false positives. Nevertheless, I was able to implement something quite effective, so I believe the approach was correct.

As documented in my trial-and-error scrap, I originally intended to analyze all input TypeScript source code and every lexical scope to track dead code, rather than just using type definition files. I gave up on this for now as the implementation and execution costs would likely be enormous. I can already see a future where someone tells me to rewrite it in Rust.

In the future, I plan to tackle that challenge and investigate further what can fundamentally be achieved.

Discussion

ムニエルムニエル

最初のコードブロックのmyClass.publicMethod()は、myClass.hello()の間違いですかね?