Skip to content

Commit

Permalink
fix: multiple bugs (#119)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes authored Oct 5, 2023
1 parent 5a68916 commit d9ca5ff
Show file tree
Hide file tree
Showing 7 changed files with 156 additions and 122 deletions.
184 changes: 92 additions & 92 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"@favware/npm-deprecate": "1.0.7",
"@types/prompts": "2.4.4",
"prettier": "2.8.8",
"tsup": "6.7.0",
"tsup": "^6.7.0",
"typescript": "5.2.2"
},
"engines": {
Expand Down
38 changes: 23 additions & 15 deletions src/commands/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,18 @@ export async function build(options: Record<string, any>) {
},
});
const buildConfigPath = resolve(options.project ?? 'sern.build.js');

const resolveBuildConfig = (path: string|undefined, language: string) => {
if(language === 'javascript') {
return path ?? resolve('jsconfig.json')
}
return path ?? resolve('tsconfig.json')
}
const defaultBuildConfig = {
defineVersion: true,
format: options.format ?? 'esm',
mode: options.mode ?? 'development',
dropLabels: [],
tsconfig: options.tsconfig ?? resolve('tsconfig.json'),

tsconfig: resolveBuildConfig(options.tsconfig, sernConfig.language),
env: options.env ?? resolve('.env'),
};
if (pathExistsSync(buildConfigPath)) {
Expand Down Expand Up @@ -100,20 +104,24 @@ export async function build(options: Record<string, any>) {
buildConfig.mode = env.NODE_ENV as 'production' | 'development';
console.log(magentaBright('NODE_ENV:'), 'Found NODE_ENV variable, setting `mode` to this.');
}

assert(buildConfig.mode === 'development' || buildConfig.mode === 'production', 'Mode is not `production` or `development`');

const defaultTsConfig = {
extends: './.sern/tsconfig.json',
};
!buildConfig.tsconfig && console.log('Using default options for tsconfig', defaultTsConfig);
const tsconfigRaw = require(buildConfig.tsconfig!);

sernConfig.language === 'typescript' &&
tsconfigRaw &&
!tsconfigRaw.extends &&
(console.warn('tsconfig does not contain an "extends". Will not use sern automatic path aliasing'),
console.warn('For projects that predate sern build and want to fully integrate, extend the tsconfig generated in .sern'),
console.warn('Extend preexisting tsconfig with top level: "extends": "./.sern/tsconfig.json"'));
try {
let config = require(buildConfig.tsconfig!);
config.extends && console.warn("Please ensure to extend the generated tsconfig")
} catch(e) {
console.warn("no tsconfig / jsconfig found");
console.warn(`Please create a ${sernConfig.language === 'javascript' ? 'jsconfig.json' : 'tsconfig.json' }`);
console.warn("It should have at least extend the generated one sern makes.")
console.warn(`
{
"extends": "./.sern/tsconfig.json",
}`.trim())
throw e;
}

console.log(bold('Building with:'));
console.log(' ', magentaBright('defineVersion'), buildConfig.defineVersion);
console.log(' ', magentaBright('format'), buildConfig.format);
Expand Down Expand Up @@ -150,7 +158,7 @@ export async function build(options: Record<string, any>) {
await esbuild.build({
entryPoints,
plugins: [imageLoader, ...(buildConfig.esbuildPlugins ?? [])],
...defaultEsbuild(buildConfig.format!, tsconfigRaw),
...defaultEsbuild(buildConfig.format!, buildConfig.tsconfig),
define,
dropLabels: [buildConfig.mode === 'production' ? '__DEV__' : '__PROD__', ...buildConfig.dropLabels!],
});
Expand Down
2 changes: 1 addition & 1 deletion src/commands/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export async function publish(commandDir: string | undefined, args: Partial<Publ
// assign args.import to empty array if non existent
args.import ??= [];

args.token && console.info('token passed through command line');
args.token && console.info('Token passed through command line');
args.applicationId && console.info('applicationId passed through command line');
commandDir && console.info('Publishing with override path: ', commandDir);

Expand Down
39 changes: 32 additions & 7 deletions src/create-publish.mts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import type { sernConfig } from './utilities/getConfig';
import type { PublishableData, PublishableModule, Typeable } from './create-publish.d.ts';
import { cyanBright, greenBright, redBright } from 'colorette';
import ora from 'ora';
import type { TheoreticalEnv } from './types/config';

async function deriveFileInfo(dir: string, file: string) {
const fullPath = join(dir, file);
Expand Down Expand Up @@ -58,7 +57,10 @@ async function* readPaths(dir: string, shouldDebug: boolean): AsyncGenerator<str
// recieved sern config
const [{ config, preloads, commandDir }] = await once(process, 'message'),
{ paths } = config as sernConfig;

for (const preload of preloads) {

console.log("preloading: ", preload);
await import('file:///' + resolve(preload));
}

Expand Down Expand Up @@ -126,6 +128,18 @@ const makeDescription = (type: number, desc: string) => {
}
return desc;
};
const serialize = (permissions: unknown) => {
if(typeof permissions === 'bigint' || typeof permissions === 'number') {
return permissions.toString();
}

if(Array.isArray(permissions)) {
return permissions
.reduce((acc, cur) => acc | cur, BigInt(0))
.toString()
}
return null;
}

const makePublishData = ({ commandModule, config }: Record<string, Record<string, unknown>>) => {
const applicationType = intoApplicationType(commandModule.type as number);
Expand All @@ -137,7 +151,7 @@ const makePublishData = ({ commandModule, config }: Record<string, Record<string
absPath: commandModule.absPath as string,
options: optionsTransformer((commandModule?.options ?? []) as Typeable[]),
dm_permission: config?.dmPermission,
default_member_permissions: config?.defaultMemberPermissions ?? null,
default_member_permissions: serialize(config?.defaultMemberPermissions),
},
config,
};
Expand Down Expand Up @@ -173,12 +187,17 @@ const res = await rest.updateGlobal(globalCommands);
let globalCommandsResponse: unknown;

if (res.ok) {
spin.succeed(`All ${cyanBright('Global')} commands published`);
globalCommands.length && spin.succeed(`All ${cyanBright('Global')} commands published`);
globalCommandsResponse = await res.json();
} else {
spin.fail(`Failed to publish global commands [Code: ${redBright(res.status)}]`);
if (res.status === 429) {
throw Error('Chill out homie, too many requests');
switch(res.status) {
case 400 :
throw Error("400: Ensure your commands have proper fields and data with left nothing out");
case 404 :
throw Error("Forbidden 404. Is you application id and/or token correct?")
case 429:
throw Error('Chill out homie, too many requests')
}
console.error(
'errors:',
Expand Down Expand Up @@ -208,7 +227,6 @@ function associateGuildIdsWithData(data: PublishableModule[]): Map<string, Publi
});
}
});

return guildIdMap;
}
const guildCommandMap = associateGuildIdsWithData(guildedCommands);
Expand All @@ -227,7 +245,14 @@ for (const [guildId, array] of guildCommandMap.entries()) {
spin.succeed(`[${greenBright(guildId)}] Successfully updated commands for guild`);
} else {
spin.fail(`[${redBright(guildId)}] Failed to update commands for guild, Reason: ${result.message}`);
throw Error(result.message);
switch(response.status) {
case 400 :
throw Error("400: Ensure your commands have proper fields and data and left nothing out");
case 404 :
throw Error("Forbidden 404. Is you application id and/or token correct?")
case 429:
throw Error('Chill out homie, too many requests')
}
}
}
const remoteData = {
Expand Down
4 changes: 2 additions & 2 deletions src/utilities/defaultEsbuildConfig.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type esbuild from 'esbuild';
import { resolve } from 'path';

export default (format: 'cjs' | 'esm', tsconfigRaw: unknown) =>
export default (format: 'cjs' | 'esm', tsconfig: string|undefined) =>
({
platform: 'node',
format,
tsconfigRaw: tsconfigRaw as esbuild.TsconfigRaw,
tsconfig: tsconfig,
logLevel: 'info',
minify: false,
outdir: resolve('dist'),
Expand Down
9 changes: 5 additions & 4 deletions tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { defineConfig } from 'tsup';
import { createRequire } from 'node:module';
const shared = {
entry: ['src/index.ts', 'src/create-publish.mts', 'src/commands/**', 'sern-tsconfig.json'],
entry: [
'src/index.ts',
'src/create-publish.mts',
'src/commands/**',
],
clean: true,
sourcemap: true,
};
Expand All @@ -18,8 +22,5 @@ export default defineConfig({
define: {
__VERSION__: `"${createRequire(import.meta.url)('./package.json').version}"`,
},
loader: {
'.json': 'file',
},
...shared,
});

0 comments on commit d9ca5ff

Please sign in to comment.