Skip to content

Commit

Permalink
feat: sdk post-build package.json script
Browse files Browse the repository at this point in the history
  • Loading branch information
Keyrxng committed Nov 6, 2024
1 parent 4f8aca9 commit 8883bbf
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 1 deletion.
64 changes: 64 additions & 0 deletions sdk-build-script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import PACKAGE from "./package.json";
import fs from "fs/promises";

type Exports = Record<string, { import?: string; require?: string; types: string }>;

interface PackageJson {
name: string;
version: string;
description: string;
main: string;
types: string;
author: string;
license: string;
keywords: string[];
exports: Exports
}

export async function createCleanPackageJson(dirName: string, base = false, dirs?: string[]) {
console.log(`Creating package.json for ${dirName}...`);
let exports: Exports;

if (base && dirs) {
exports = {
".": {
types: `./dist/index.d.ts`,
},
};

for (const dir of dirs) {
exports[`./${dir}`] = {
import: `./dist/${dir}/index.mjs`,
require: `./dist/${dir}/index.js`,
types: `./dist/${dir}/index.d.ts`,
};
}
} else {
exports = {
[`.`]: {
import: `./index.mjs`,
require: `./index.js`,
types: `./index.d.ts`,
},
};
}

const packageJson = {
name: PACKAGE.name,
version: PACKAGE.version,
description: PACKAGE.description,
main: PACKAGE.main,
module: PACKAGE.module,
types: PACKAGE.typings,
author: PACKAGE.author,
license: PACKAGE.license,
keywords: PACKAGE.keywords,
exports
};

await writeDirPackageJson(base ? "dist" : dirName, packageJson);
}

async function writeDirPackageJson(dirName: string, packageJson: PackageJson) {
await fs.writeFile(`./${dirName === "dist" ? "dist" : `dist/${dirName}`}/package.json`, JSON.stringify(packageJson, null, 2));
}
21 changes: 20 additions & 1 deletion tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,31 @@
import { defineConfig } from "tsup";
import { createCleanPackageJson } from "./sdk-build-script";

const entries = ["src/sdk/index.ts", "src/types/index.ts"];

export default defineConfig({
entry: ["src/sdk/index.ts"],
entry: ["src/sdk/index.ts", "src/types/index.ts"],
format: ["cjs", "esm"],
outDir: "dist",
splitting: false,
sourcemap: false,
clean: true,
dts: true,
legacyOutput: false,
onSuccess: async () => {
await buildPackageJsons();
},
});

/**
* 1. Cleans up the SDK dist package.json
* 2. Pretty sure this is required for declaring multiple directories in the exports field
*/
async function buildPackageJsons() {
const dirs = entries.map((entry) => entry.split("/")[1]);
for (const entry of dirs) {
await createCleanPackageJson(entry);
}

await createCleanPackageJson("", true, dirs)
}

0 comments on commit 8883bbf

Please sign in to comment.