Skip to content

Commit

Permalink
chore: Provide logger in Vite plugin mode
Browse files Browse the repository at this point in the history
  • Loading branch information
spring-raining committed Jan 14, 2025
1 parent 1eae4a9 commit 02b3d77
Show file tree
Hide file tree
Showing 8 changed files with 121 additions and 32 deletions.
52 changes: 46 additions & 6 deletions docs/api-javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ build({

**options.executableBrowser?**: `string` = `...`

**options.host?**: `string` \| `boolean` = `...`

**options.ignoreHttpsErrors?**: `boolean` = `...`

**options.image?**: `string` = `...`
Expand All @@ -68,12 +70,16 @@ build({

**options.language?**: `string` = `...`

**options.logLevel?**: `"silent"` \| `"info"` \| `"verbose"` \| `"debug"` = `...`
**options.logger?**: `LoggerInterface` = `...`

**options.logLevel?**: `"info"` \| `"silent"` \| `"verbose"` \| `"debug"` = `...`

**options.openViewer?**: `boolean` = `...`

**options.output?**: `string` \| `object` & `object` \| (`string` \| `object` & `object`)[] = `...`

**options.port?**: `number` = `...`

**options.preflight?**: `"press-ready"` \| `"press-ready-local"` = `...`

**options.preflightOption?**: `string` \| `string`[] = `...`
Expand Down Expand Up @@ -114,6 +120,10 @@ build({

**options.viewerParam?**: `string` = `...`

**options.vite?**: `UserConfig` = `...`

**options.viteConfigFile?**: `string` \| `boolean` = `...`

#### Returns

`Promise`\<`void`\>
Expand Down Expand Up @@ -152,6 +162,8 @@ build({

**inlineConfig.executableBrowser?**: `string` = `...`

**inlineConfig.host?**: `string` \| `boolean` = `...`

**inlineConfig.ignoreHttpsErrors?**: `boolean` = `...`

**inlineConfig.image?**: `string` = `...`
Expand All @@ -160,12 +172,16 @@ build({

**inlineConfig.language?**: `string` = `...`

**inlineConfig.logLevel?**: `"silent"` \| `"info"` \| `"verbose"` \| `"debug"` = `...`
**inlineConfig.logger?**: `LoggerInterface` = `...`

**inlineConfig.logLevel?**: `"info"` \| `"silent"` \| `"verbose"` \| `"debug"` = `...`

**inlineConfig.openViewer?**: `boolean` = `...`

**inlineConfig.output?**: `string` \| `object` & `object` \| (`string` \| `object` & `object`)[] = `...`

**inlineConfig.port?**: `number` = `...`

**inlineConfig.preflight?**: `"press-ready"` \| `"press-ready-local"` = `...`

**inlineConfig.preflightOption?**: `string` \| `string`[] = `...`
Expand Down Expand Up @@ -206,6 +222,10 @@ build({

**inlineConfig.viewerParam?**: `string` = `...`

**inlineConfig.vite?**: `UserConfig` = `...`

**inlineConfig.viteConfigFile?**: `string` \| `boolean` = `...`

#### Returns

`Promise`\<`Plugin`[]\>
Expand Down Expand Up @@ -246,6 +266,8 @@ Initialize a new vivliostyle.config.js file.

**options.executableBrowser?**: `string` = `...`

**options.host?**: `string` \| `boolean` = `...`

**options.ignoreHttpsErrors?**: `boolean` = `...`

**options.image?**: `string` = `...`
Expand All @@ -254,12 +276,16 @@ Initialize a new vivliostyle.config.js file.

**options.language?**: `string` = `...`

**options.logLevel?**: `"silent"` \| `"info"` \| `"verbose"` \| `"debug"` = `...`
**options.logger?**: `LoggerInterface` = `...`

**options.logLevel?**: `"info"` \| `"silent"` \| `"verbose"` \| `"debug"` = `...`

**options.openViewer?**: `boolean` = `...`

**options.output?**: `string` \| `object` & `object` \| (`string` \| `object` & `object`)[] = `...`

**options.port?**: `number` = `...`

**options.preflight?**: `"press-ready"` \| `"press-ready-local"` = `...`

**options.preflightOption?**: `string` \| `string`[] = `...`
Expand Down Expand Up @@ -300,6 +326,10 @@ Initialize a new vivliostyle.config.js file.

**options.viewerParam?**: `string` = `...`

**options.vite?**: `UserConfig` = `...`

**options.viteConfigFile?**: `string` \| `boolean` = `...`

#### Returns

`Promise`\<`void`\>
Expand All @@ -308,7 +338,7 @@ Initialize a new vivliostyle.config.js file.

### preview()

> **preview**(`options`): `Promise`\<`void`\>
> **preview**(`options`): `Promise`\<`ViteDevServer`\>
Open a browser for previewing the publication.

Expand Down Expand Up @@ -340,6 +370,8 @@ Open a browser for previewing the publication.

**options.executableBrowser?**: `string` = `...`

**options.host?**: `string` \| `boolean` = `...`

**options.ignoreHttpsErrors?**: `boolean` = `...`

**options.image?**: `string` = `...`
Expand All @@ -348,12 +380,16 @@ Open a browser for previewing the publication.

**options.language?**: `string` = `...`

**options.logLevel?**: `"silent"` \| `"info"` \| `"verbose"` \| `"debug"` = `...`
**options.logger?**: `LoggerInterface` = `...`

**options.logLevel?**: `"info"` \| `"silent"` \| `"verbose"` \| `"debug"` = `...`

**options.openViewer?**: `boolean` = `...`

**options.output?**: `string` \| `object` & `object` \| (`string` \| `object` & `object`)[] = `...`

**options.port?**: `number` = `...`

**options.preflight?**: `"press-ready"` \| `"press-ready-local"` = `...`

**options.preflightOption?**: `string` \| `string`[] = `...`
Expand Down Expand Up @@ -394,9 +430,13 @@ Open a browser for previewing the publication.

**options.viewerParam?**: `string` = `...`

**options.vite?**: `UserConfig` = `...`

**options.viteConfigFile?**: `string` \| `boolean` = `...`

#### Returns

`Promise`\<`void`\>
`Promise`\<`ViteDevServer`\>

## Type Aliases

Expand Down
11 changes: 11 additions & 0 deletions src/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Metadata, StringifyMarkdownOptions } from '@vivliostyle/vfm';
import { type Processor } from 'unified';
import upath from 'upath';
import * as v from 'valibot';
import { LoggerInterface } from '../logger.js';

const $ = (strings: TemplateStringsArray, ...values: any[]) => {
const lines = String.raw({ raw: strings }, ...values).split('\n');
Expand Down Expand Up @@ -1159,6 +1160,15 @@ export const VivliostyleInlineConfig = v.pipe(
Port the server should listen on. (default: \`13000\`)
`),
),
logger: v.pipe(
v.custom<LoggerInterface>(() => true),
v.metadata({
typeString: 'LoggerInterface',
}),
v.description($`
Custom logger interface.
`),
),
}),
),
v.check(
Expand Down Expand Up @@ -1211,4 +1221,5 @@ export type InlineOptions = Pick<
| 'openViewer'
| 'enableStaticServe'
| 'enableViewerStartPage'
| 'logger'
>;
1 change: 1 addition & 0 deletions src/core/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { cwd, isInContainer, runExitHandlers } from '../util.js';

export async function build(inlineConfig: ParsedVivliostyleInlineConfig) {
Logger.setLogLevel(inlineConfig.logLevel);
Logger.setCustomLogger(inlineConfig.logger);
Logger.debug('build > inlineConfig %O', inlineConfig);

let vivliostyleConfig =
Expand Down
1 change: 1 addition & 0 deletions src/core/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { cwd, runExitHandlers } from '../util.js';

export async function init(inlineConfig: ParsedVivliostyleInlineConfig) {
Logger.setLogLevel(inlineConfig.logLevel);
Logger.setCustomLogger(inlineConfig.logger);

const vivliostyleConfigPath = upath.join(
inlineConfig.cwd ?? cwd,
Expand Down
1 change: 1 addition & 0 deletions src/core/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { createViteServer, getViewerFullUrl } from '../server.js';

export async function preview(inlineConfig: ParsedVivliostyleInlineConfig) {
Logger.setLogLevel(inlineConfig.logLevel);
Logger.setCustomLogger(inlineConfig.logger);
Logger.debug('preview > inlineConfig %O', inlineConfig);

let vivliostyleConfig =
Expand Down
46 changes: 34 additions & 12 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import {
blueBright,
gray,
greenBright,
red,
redBright,
yellow,
yellowBright,
} from 'yoctocolors';
import { isInContainer } from './util.js';
Expand All @@ -23,13 +21,20 @@ const successSymbol = greenBright('SUCCESS');
const warnSymbol = yellowBright('WARN');
const errorSymbol = redBright('ERROR');

export interface LoggerInterface {
info(message: string): void;
warn(message: string): void;
error(message: string): void;
}

export class Logger {
/**
* 0: silent 1: info 2: verbose 3: debug
*/
static #logLevel: 0 | 1 | 2 | 3 = 0;
static #loggerInstance: Logger | undefined;
static #nonBlockingLogPrinted = false;
static #customLogger: LoggerInterface | undefined;

static debug = debug('vs-cli');

Expand All @@ -39,7 +44,8 @@ export class Logger {

static get isInteractive() {
return Boolean(
process.stderr.isTTY &&
!this.#customLogger &&
process.stderr.isTTY &&
process.env.TERM !== 'dumb' &&
!('CI' in process.env) &&
!import.meta.env?.VITEST &&
Expand Down Expand Up @@ -109,15 +115,21 @@ export class Logger {
this.#nonBlockingLogPrinted = false;
}

static getMessage(message: string, symbol?: string) {
return !this.#customLogger && symbol ? `${symbol} ${message}` : message;
}

static #nonBlockingLog(
fallback: (...messages: any[]) => void,
logMethod: 'warn' | 'error' | 'info',
message: string,
) {
if (!this.#spinner || !this.isInteractive) {
if (isInContainer()) {
message = `${gray('[Docker]')} ${message}`;
}
this.#logLevel >= 3 ? this.debug(message) : fallback(message);
this.#logLevel >= 3
? this.debug(message)
: (this.#customLogger || console)[logMethod](message);
return;
}
this.logUpdate(this.#spinner.text);
Expand All @@ -130,16 +142,19 @@ export class Logger {
if (this.#logLevel < 1) {
return;
}
this.#nonBlockingLog(console.log, `${successSymbol} ${messages.join(' ')}`);
this.#nonBlockingLog(
'info',
this.getMessage(messages.join(' '), successSymbol),
);
}

static logError(...messages: any[]) {
if (this.#logLevel < 1) {
return;
}
this.#nonBlockingLog(
console.error,
`${errorSymbol} ${red(messages.join(' '))}`,
'error',
this.getMessage(messages.join(' '), errorSymbol),
);
}

Expand All @@ -148,23 +163,26 @@ export class Logger {
return;
}
this.#nonBlockingLog(
console.warn,
`${warnSymbol} ${yellow(messages.join(' '))}`,
'warn',
this.getMessage(messages.join(' '), warnSymbol),
);
}

static logInfo(...messages: any[]) {
if (this.#logLevel < 1) {
return;
}
this.#nonBlockingLog(console.info, `${infoSymbol} ${messages.join(' ')}`);
this.#nonBlockingLog(
'info',
this.getMessage(messages.join(' '), infoSymbol),
);
}

static logVerbose(...messages: any[]) {
if (this.#logLevel < 2) {
return;
}
this.#nonBlockingLog(console.log, messages.join(' '));
this.#nonBlockingLog('info', this.getMessage(messages.join(' ')));
}

static setLogLevel(level?: 'silent' | 'info' | 'verbose' | 'debug') {
Expand All @@ -184,6 +202,10 @@ export class Logger {
}
}

static setCustomLogger(logger: LoggerInterface | undefined) {
this.#customLogger = logger;
}

#_spinner: Spinner;

constructor() {
Expand Down
7 changes: 3 additions & 4 deletions src/processor/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,14 +212,13 @@ export async function transformManuscript(
}
} else if (source?.type === 'uri') {
resourceLoader = new ResourceLoader();
const virtualConsole = createVirtualConsole(() => {
// TODO: handle console messages
});
try {
await getJsdomFromUrlOrFile({
src: source.href,
resourceLoader,
virtualConsole,
virtualConsole: createVirtualConsole((error) => {
Logger.logError(`Failed to fetch resources: ${error.detail}`);
}),
});
} catch (error: any) {
throw new DetailError(
Expand Down
Loading

0 comments on commit 02b3d77

Please sign in to comment.