Skip to content

Commit

Permalink
chore(cli,client,runtime,screenshot,sys,testing): fix typescript issues
Browse files Browse the repository at this point in the history
  • Loading branch information
khanhduy1407 committed Dec 6, 2024
1 parent 9e9e335 commit 1e6d201
Show file tree
Hide file tree
Showing 17 changed files with 60 additions and 34 deletions.
4 changes: 2 additions & 2 deletions src/cli/find-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { CompilerSystem, Diagnostic } from '../declarations';
*/
export type FindConfigOptions = {
sys: CompilerSystem;
configPath: string;
configPath?: string | null;
};

/**
Expand Down Expand Up @@ -38,7 +38,7 @@ export const findConfig = async (opts: FindConfigOptions): Promise<result.Result
configPath = normalizePath(sys.platformPath.join(cwd, configPath));
} else {
// config path already an absolute path, we're good here
configPath = normalizePath(opts.configPath);
configPath = normalizePath(configPath);
}
} else {
// nothing was passed in, use the current working directory
Expand Down
2 changes: 1 addition & 1 deletion src/cli/task-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const taskBuild = async (coreCompiler: CoreCompiler, config: d.ValidatedC
config,
results.hydrateAppFilePath,
results.componentGraph,
null,
undefined,
);
config.logger.printDiagnostics(prerenderDiagnostics);

Expand Down
8 changes: 4 additions & 4 deletions src/cli/task-prerender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const taskPrerender = async (coreCompiler: CoreCompiler, config: Validate

const srcIndexHtmlPath = config.srcIndexHtml;

const diagnostics = await runPrerenderTask(coreCompiler, config, hydrateAppFilePath, null, srcIndexHtmlPath);
const diagnostics = await runPrerenderTask(coreCompiler, config, hydrateAppFilePath, undefined, srcIndexHtmlPath);
config.logger.printDiagnostics(diagnostics);

if (diagnostics.some((d) => d.level === 'error')) {
Expand All @@ -27,9 +27,9 @@ export const taskPrerender = async (coreCompiler: CoreCompiler, config: Validate
export const runPrerenderTask = async (
coreCompiler: CoreCompiler,
config: ValidatedConfig,
hydrateAppFilePath: string,
componentGraph: BuildResultsComponentGraph,
srcIndexHtmlPath: string,
hydrateAppFilePath?: string,
componentGraph?: BuildResultsComponentGraph,
srcIndexHtmlPath?: string,
) => {
const diagnostics: Diagnostic[] = [];

Expand Down
6 changes: 6 additions & 0 deletions src/cli/task-serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ export const taskServe = async (config: ValidatedConfig) => {
config.maxConcurrentWorkers = 1;
config.devServer.root = isString(config.flags.root) ? config.flags.root : config.sys.getCurrentDirectory();

if (!config.sys.getDevServerExecutingPath || !config.sys.dynamicImport || !config.sys.onProcessInterrupt) {
throw new Error(
`Environment doesn't provide required functions: getDevServerExecutingPath, dynamicImport, onProcessInterrupt`,
);
}

const devServerPath = config.sys.getDevServerExecutingPath();
const { start }: typeof import('@rindo/core/dev-server') = await config.sys.dynamicImport(devServerPath);
const devServer = await start(config.devServer, config.logger);
Expand Down
4 changes: 2 additions & 2 deletions src/cli/task-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ export const taskTest = async (config: ValidatedConfig): Promise<void> => {
}

// ensure we've got the required modules installed
const diagnostics = await config.sys.lazyRequire.ensure(config.rootDir, ensureModuleIds);
if (diagnostics.length > 0) {
const diagnostics = await config.sys.lazyRequire?.ensure(config.rootDir, ensureModuleIds);
if (diagnostics && diagnostics.length > 0) {
config.logger.printDiagnostics(diagnostics);
return config.sys.exit(1);
}
Expand Down
6 changes: 6 additions & 0 deletions src/cli/task-watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ export const taskWatch = async (coreCompiler: CoreCompiler, config: ValidatedCon
const compiler = await coreCompiler.createCompiler(config);
const watcher = await compiler.createWatcher();

if (!config.sys.getDevServerExecutingPath || !config.sys.dynamicImport || !config.sys.onProcessInterrupt) {
throw new Error(
`Environment doesn't provide required functions: getDevServerExecutingPath, dynamicImport, onProcessInterrupt`,
);
}

if (config.flags.serve) {
const devServerPath = config.sys.getDevServerExecutingPath();
const { start }: typeof import('@rindo/core/dev-server') = await config.sys.dynamicImport(devServerPath);
Expand Down
12 changes: 8 additions & 4 deletions src/cli/telemetry/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export function hasAppTarget(config: d.ValidatedConfig): boolean {
}

export function isUsingYarn(sys: d.CompilerSystem) {
return sys.getEnvironmentVar('npm_execpath')?.includes('yarn') || false;
return sys.getEnvironmentVar?.('npm_execpath')?.includes('yarn') || false;
}

/**
Expand Down Expand Up @@ -347,12 +347,12 @@ async function npmPackages(sys: d.CompilerSystem, familyPackages: [string, strin
async function yarnPackages(sys: d.CompilerSystem, familyPackages: [string, string][]): Promise<string[]> {
const appRootDir = sys.getCurrentDirectory();
const yarnLock = sys.readFileSync(sys.resolvePath(appRootDir + '/yarn.lock'));
const yarnLockYml = sys.parseYarnLockFile(yarnLock);
const yarnLockYml = sys.parseYarnLockFile?.(yarnLock);

return familyPackages.map(([k, v]) => {
const identifiedVersion = `${k}@${v}`;
let version = yarnLockYml.object[identifiedVersion]?.version;
version = version.includes('undefined') ? sanitizeDeclaredVersion(identifiedVersion) : version;
let version = yarnLockYml?.object[identifiedVersion]?.version;
version = version && version.includes('undefined') ? sanitizeDeclaredVersion(identifiedVersion) : version;
return `${k}@${version}`;
});
}
Expand Down Expand Up @@ -425,6 +425,10 @@ async function sendTelemetry(sys: d.CompilerSystem, config: d.ValidatedConfig, d
sent_at: now,
};

if (!sys.fetch) {
throw new Error('No fetch implementation available');
}

// This request is only made if telemetry is on.
const response = await sys.fetch('https://familyjs-api.web.app/events/metrics', {
method: 'POST',
Expand Down
4 changes: 3 additions & 1 deletion src/client/client-load-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const loadModule = (
cmpMeta: d.ComponentRuntimeMeta,
hostRef: d.HostRef,
hmrVersionId?: string,
): Promise<d.ComponentConstructor | undefined> | d.ComponentConstructor => {
): Promise<d.ComponentConstructor | undefined> | d.ComponentConstructor | undefined => {
// loadModuleImport
const exportName = cmpMeta.$tagName$.replace(/-/g, '_');
const bundleId = cmpMeta.$lazyBundleId$;
Expand All @@ -36,6 +36,8 @@ export const loadModule = (
`Trying to lazily load component <${cmpMeta.$tagName$}> with style mode "${hostRef.$modeName$}", but it does not exist.`,
);
return undefined;
} else if (!bundleId) {
return undefined;
}
const module = !BUILD.hotModuleReplacement ? cmpModules.get(bundleId) : false;
if (module) {
Expand Down
6 changes: 3 additions & 3 deletions src/declarations/rindo-public-compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2643,9 +2643,9 @@ export interface ResolveModuleOptions {

export interface PrerenderStartOptions {
buildId?: string;
hydrateAppFilePath: string;
componentGraph: BuildResultsComponentGraph;
srcIndexHtmlPath: string;
hydrateAppFilePath?: string;
componentGraph?: BuildResultsComponentGraph;
srcIndexHtmlPath?: string;
}

export interface PrerenderResults {
Expand Down
9 changes: 5 additions & 4 deletions src/runtime/host-listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import type * as d from '../declarations';
export const addHostEventListeners = (
elm: d.HostElement,
hostRef: d.HostRef,
listeners: d.ComponentRuntimeHostListener[],
attachParentListeners: boolean,
listeners?: d.ComponentRuntimeHostListener[],
attachParentListeners?: boolean,
) => {
if (BUILD.hostListener && listeners) {
// this is called immediately within the element's constructor
Expand Down Expand Up @@ -46,7 +46,7 @@ const hostListenerProxy = (hostRef: d.HostRef, methodName: string) => (ev: Event
if (BUILD.lazyLoad) {
if (hostRef.$flags$ & HOST_FLAGS.isListenReady) {
// instance is ready, let's call it's member method for this event
hostRef.$lazyInstance$[methodName](ev);
hostRef.$lazyInstance$?.[methodName](ev);
} else {
(hostRef.$queuedListeners$ = hostRef.$queuedListeners$ || []).push([methodName, ev]);
}
Expand All @@ -62,7 +62,8 @@ const getHostListenerTarget = (elm: Element, flags: number): EventTarget => {
if (BUILD.hostListenerTargetDocument && flags & LISTENER_FLAGS.TargetDocument) return doc;
if (BUILD.hostListenerTargetWindow && flags & LISTENER_FLAGS.TargetWindow) return win;
if (BUILD.hostListenerTargetBody && flags & LISTENER_FLAGS.TargetBody) return doc.body;
if (BUILD.hostListenerTargetParent && flags & LISTENER_FLAGS.TargetParent) return elm.parentElement;
if (BUILD.hostListenerTargetParent && flags & LISTENER_FLAGS.TargetParent && elm.parentElement)
return elm.parentElement;
return elm;
};

Expand Down
4 changes: 4 additions & 0 deletions src/screenshot/pixel-match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ function getMismatchedPixels(pixelMatchInput: d.PixelMatchInput) {
includeAA: false,
});

if (typeof process.send !== 'function') {
throw new Error('`getMismatchedPixels` must be run in a child process.');
}

process.send(mismatchedPixels);
}
}
Expand Down
3 changes: 1 addition & 2 deletions src/screenshot/screenshot-compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ export async function compareScreenshot(
const currentImagePath = join(screenshotBuildData.imagesDir, currentImageName);

await writeScreenshotImage(currentImagePath, currentScreenshotBuf);
currentScreenshotBuf = null;

if (testPath) {
testPath = normalizePath(relative(screenshotBuildData.rootDir, testPath));
Expand Down Expand Up @@ -179,7 +178,7 @@ async function getMismatchedPixels(
reject(err);
});

pixelMatchProcess.stderr.on('data', (data) => {
pixelMatchProcess.stderr?.on('data', (data) => {
error = data.toString();
});

Expand Down
2 changes: 1 addition & 1 deletion src/screenshot/screenshot-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export async function writeScreenshotData(dataDir: string, screenshotData: d.Scr
}

export async function readScreenshotData(dataDir: string, screenshotId: string) {
let rtn: d.Screenshot = null;
let rtn: d.Screenshot | null = null;

try {
const dataFilePath = getDataFilePath(dataDir, screenshotId);
Expand Down
2 changes: 1 addition & 1 deletion src/sys/node/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export function createNodeLoggerSys(): TerminalLoggerSys {
return (promise = promise.then(() => {
return new Promise<any>((resolve) => {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0, null);
readline.cursorTo(process.stdout, 0, undefined);
process.stdout.write(text, resolve);
});
}));
Expand Down
6 changes: 3 additions & 3 deletions src/sys/node/logger/terminal-logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export const createTerminalLogger = (loggerSys: TerminalLoggerSys): Logger => {
}
};

const timespanStart = (startMsg: string, debug: boolean, appendTo: string[]) => {
const timespanStart = (startMsg: string, debug: boolean, appendTo?: string[]) => {
const msg = [`${startMsg} ${dim('...')}`];

if (debug) {
Expand Down Expand Up @@ -151,7 +151,7 @@ export const createTerminalLogger = (loggerSys: TerminalLoggerSys): Logger => {
textBold: boolean,
newLineSuffix: boolean,
debug: boolean,
appendTo: string[],
appendTo?: string[],
) => {
let msg = finishMsg;

Expand Down Expand Up @@ -400,7 +400,7 @@ export const createTerminalLogger = (loggerSys: TerminalLoggerSys): Logger => {
* @param errorLength the length of the error, how many characters should be highlighted
* @returns the highlighted error
*/
const highlightError = (errorLine: string, errorCharStart: number, errorLength: number): string => {
const highlightError = (errorLine: string, errorCharStart: number, errorLength: number = 0): string => {
let rightSideChars = errorLine.length - errorCharStart + errorLength - 1;
while (errorLine.length + INDENT.length > loggerSys.getColumns()) {
if (errorCharStart > errorLine.length - errorCharStart + errorLength && errorCharStart > 5) {
Expand Down
8 changes: 6 additions & 2 deletions src/testing/jest/jest-rindo-connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,19 @@ const getJestFacade = (): JestFacade => {
if (version <= 27) {
JEST_RINDO_FACADE = new Jest27Rindo();
} else if (version === 28) {
JEST_RINDO_FACADE = new Jest28Rindo();
JEST_RINDO_FACADE = new Jest28Rindo() as JestFacade;
} else if (version === 29) {
JEST_RINDO_FACADE = new Jest29Rindo();
JEST_RINDO_FACADE = new Jest29Rindo() as JestFacade;
} else {
// in Rindo 4.X, defaulting to jest 27 infrastructure is the default behavior.
JEST_RINDO_FACADE = new Jest27Rindo();
}
}

if (!JEST_RINDO_FACADE) {
throw new Error('Rindo could not determine the Jest version being used.');
}

return JEST_RINDO_FACADE;
};

Expand Down
8 changes: 4 additions & 4 deletions src/testing/mock-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export function mockFetchReset() {
}

export const mockFetch = {
json(data: any, url?: string) {
json(data: any, url: string) {
const rsp = new MockResponse(JSON.stringify(data, null, 2), {
headers: new MockHeaders({
'Content-Type': 'application/json',
Expand All @@ -112,7 +112,7 @@ export const mockFetch = {
setMockedResponse(rsp, url, false);
},

text(data: string, url?: string) {
text(data: string, url: string) {
const rsp = new MockResponse(data, {
headers: new MockHeaders({
'Content-Type': 'text/plain',
Expand All @@ -121,11 +121,11 @@ export const mockFetch = {
setMockedResponse(rsp, url, false);
},

response(rsp: MockResponse, url?: string) {
response(rsp: MockResponse, url: string) {
setMockedResponse(rsp, url, false);
},

reject(rsp?: MockResponse, url?: string) {
reject(rsp: MockResponse, url: string) {
setMockedResponse(rsp, url, true);
},

Expand Down

0 comments on commit 1e6d201

Please sign in to comment.