Skip to content

Commit

Permalink
fix regression and clean up publish script
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Jun 13, 2024
1 parent 1990b3e commit 7b99f02
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 62 deletions.
30 changes: 16 additions & 14 deletions src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ import assert from 'node:assert';
import defaultEsbuild from '../utilities/defaultEsbuildConfig';
import { require } from '../utilities/require';
import { pathExists, pathExistsSync } from 'find-up';
import { mkdir, writeFile } from 'fs/promises';
import { mkdir, writeFile, readFile } from 'fs/promises';
import * as Preprocessor from '../utilities/preprocessor';
import { bold, magentaBright } from 'colorette';
const validExtensions = ['.ts', '.js' ];

const VALID_EXTENSIONS = ['.ts', '.js' ];

type BuildOptions = {
/**
* Define __VERSION__
Expand Down Expand Up @@ -42,13 +44,13 @@ type BuildOptions = {
*/
env?: string;
};

const CommandHandlerPlugin = (buildConfig: Partial<BuildOptions>, ambientFilePath: string, sernTsConfigPath: string) => {
return {
name: "commandhandler",
setup(build) {

const options = build.initialOptions

const defVersion = () => JSON.stringify(require(p.resolve('package.json')).version);
options.define = {
...buildConfig.define ?? {},
Expand All @@ -64,17 +66,17 @@ const CommandHandlerPlugin = (buildConfig: Partial<BuildOptions>, ambientFilePat
}
const resolveBuildConfig = (path: string|undefined, language: string) => {
if(language === 'javascript') {
return path ?? p.resolve('jsconfig.json')
return path ?? 'jsconfig.json'
}
return path ?? p.resolve('tsconfig.json')
return path ?? 'tsconfig.json'
}

export async function build(options: Record<string, any>) {
if (!options.supressWarnings) {
console.info(`${magentaBright('EXPERIMENTAL')}: This API has not been stabilized. add -W or --suppress-warnings flag to suppress`);
}
const sernConfig = await getConfig();
let buildConfig: Partial<BuildOptions> = {};
let buildConfig: BuildOptions;
const buildConfigPath = p.resolve(options.project ?? 'sern.build.js');

const defaultBuildConfig = {
Expand All @@ -83,7 +85,8 @@ export async function build(options: Record<string, any>) {
mode: options.mode ?? 'development',
dropLabels: [],
tsconfig: resolveBuildConfig(options.tsconfig, sernConfig.language),
env: options.env ?? p.resolve('.env'),
env: options.env ?? '.env',
include: []
};
if (pathExistsSync(buildConfigPath)) {
//throwable, buildConfigPath may not exist
Expand All @@ -100,7 +103,7 @@ export async function build(options: Record<string, any>) {
}
assert(buildConfig.mode === 'development' || buildConfig.mode === 'production', 'Mode is not `production` or `development`');
try {
let config = require(buildConfig.tsconfig!);
let config = JSON.parse(await readFile(buildConfig.tsconfig!, 'utf8'));
config.extends && console.warn("Extend the generated tsconfig")
} catch(e) {
console.error("no tsconfig / jsconfig found");
Expand All @@ -126,12 +129,11 @@ export async function build(options: Record<string, any>) {
await mkdir(genDir, { recursive: true });
}

const entryPoints = await glob(`./src/**/*{${validExtensions.join(',')}}`);
// const [commandsPaths, eventsPaths] = await Promise.all([
// glob(`**/*`, { withFileTypes: true, ignore: { ignored: p => p.isDirectory() }, cwd: "./src/commands/" }),
// glob(`**/*`, { withFileTypes: true, ignore: { ignored: p => p.isDirectory() }, cwd: "./src/events/" })
// ])

const entryPoints = await glob(`src/**/*{${VALID_EXTENSIONS.join(',')}}`,{
ignore: {
ignored: (p) => p.name.endsWith('.d.ts'),
}
});
//https://esbuild.github.io/content-types/#tsconfig-json
const ctx = await esbuild.context({
entryPoints,
Expand Down
69 changes: 21 additions & 48 deletions src/create-publish.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,65 +2,38 @@
* This file is meant to be run with the esm / cjs esbuild-kit loader to properly import typescript modules
*/

import { readdir, stat, mkdir, writeFile } from 'fs/promises';
import { join, basename, extname, resolve } from 'node:path';
import { readdir, mkdir, writeFile } from 'fs/promises';
import { basename, resolve, posix as pathpsx } from 'node:path';
import { pathExistsSync } from 'find-up';
import assert from 'assert';
import { once } from 'node:events';
import * as Rest from './rest';
import type { sernConfig } from './utilities/getConfig';
import type { SernConfig } from './utilities/getConfig';
import type { PublishableData, PublishableModule, Typeable } from './create-publish.d.ts';
import { cyanBright, greenBright, redBright } from 'colorette';
import { inspect } from 'node:util'
import ora from 'ora';

async function deriveFileInfo(dir: string, file: string) {
const fullPath = join(dir, file);
return {
fullPath,
fileStats: await stat(fullPath),
base: basename(file),
};
}

function isSkippable(filename: string) {
// empty string is for non extension files (directories)
const validExtensions = ['.js', '.cjs', '.mts', '.mjs', '.cts', '.ts', ''];
return filename[0] === '!' || !validExtensions.includes(extname(filename));
}

async function* readPaths(dir: string, shouldDebug: boolean): AsyncGenerator<string> {
try {
const files = await readdir(dir);
for (const file of files) {
const { fullPath, fileStats, base } = await deriveFileInfo(dir, file);

if (fileStats.isDirectory()) {
// TODO: refactor so that i dont repeat myself for files (line 71)
if (isSkippable(base)) {
if (shouldDebug) console.info(`ignored directory: ${fullPath}`);
} else {
yield* readPaths(fullPath, shouldDebug);
}
} else {
if (isSkippable(base)) {
if (shouldDebug) console.info(`ignored: ${fullPath}`);
} else {
yield 'file:///' + fullPath;
}
const files = await readdir(dir, { withFileTypes: true });
for (const file of files) {
const fullPath = pathpsx.join(dir, file.name);
if (file.isDirectory()) {
if (!file.name.startsWith('!')) {
yield* readPaths(fullPath, shouldDebug);
}
} else if (!file.name.startsWith('!')) {
yield "file:///"+resolve(fullPath);
}
} catch (err) {
throw err;
}
}

// recieved sern config
const [{ config, preloads, commandDir }] = await once(process, 'message'),
{ paths } = config as sernConfig;
{ paths } = config as SernConfig;

for (const preload of preloads) {

console.log("preloading: ", preload);
await import('file:///' + resolve(preload));
}
Expand All @@ -83,17 +56,16 @@ for await (const absPath of filePaths) {
config = config(absPath, commandModule);
}

try {
commandModule = commandModule.getInstance();
} catch {}

if ((PUBLISHABLE & commandModule.type) != 0) {
// assign defaults
const filename = basename(absPath);
const filenameNoExtension = filename.substring(0, filename.lastIndexOf('.'));
commandModule.name ??= filenameNoExtension;
commandModule.description ??= '';
commandModule.absPath = absPath;
commandModule.meta = {
absPath
}

modules.push({ commandModule, config });
}
}
Expand Down Expand Up @@ -151,7 +123,7 @@ const makePublishData = ({ commandModule, config }: Record<string, Record<string
description: makeDescription(applicationType, commandModule.description as string),
absPath: commandModule.absPath as string,
options: optionsTransformer((commandModule?.options ?? []) as Typeable[]),
dm_permission: config?.dmPermission,
dm_permission: config?.dmPermission ?? false,
default_member_permissions: serialize(config?.defaultMemberPermissions),
//@ts-ignore
integration_types: (config?.integrationTypes ?? ['Guild']).map(
Expand All @@ -161,11 +133,13 @@ const makePublishData = ({ commandModule, config }: Record<string, Record<string
} else if (s == "User") {
return 1
} else {
throw Error("IntegrationType is not one of Guild or User");
throw Error("IntegrationType is not one of Guild (0) or User (1)");
}
}),
//@ts-ignore
contexts: config?.contexts ?? undefined
contexts: config?.contexts ?? undefined,
name_localizations: commandModule.name_localizations,
description_localizations: commandModule.description_localizations
},
config,
};
Expand Down Expand Up @@ -248,7 +222,6 @@ function associateGuildIdsWithData(data: PublishableModule[]): Map<string, Publi
return guildIdMap;
}
const guildCommandMap = associateGuildIdsWithData(guildedCommands);

let guildCommandMapResponse = new Map<string, Record<string, unknown>>();

for (const [guildId, array] of guildCommandMap.entries()) {
Expand Down

0 comments on commit 7b99f02

Please sign in to comment.