Skip to content

Commit

Permalink
chore: explicit return type
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Sep 15, 2024
1 parent f8a3f1f commit 1d27094
Show file tree
Hide file tree
Showing 43 changed files with 412 additions and 350 deletions.
2 changes: 1 addition & 1 deletion docs/.vitepress/components/LanguagesList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { usePlayground } from '../store/playground'
const play = usePlayground()
const showModel = ref(false)
function preview(id: string) {
function preview(id: string): void {
play.lang = id
showModel.value = true
}
Expand Down
8 changes: 4 additions & 4 deletions docs/.vitepress/store/playground.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// <reference types="vite/client" />

import type { BundledLanguageInfo, BundledThemeInfo } from 'shiki'
import type { BundledLanguageInfo, BundledThemeInfo } from '@shikijs/types'
import { useLocalStorage } from '@vueuse/core'
import { acceptHMRUpdate, defineStore } from 'pinia'
import { ref, shallowRef, watch } from 'vue'
Expand Down Expand Up @@ -31,7 +31,7 @@ export const usePlayground = defineStore('playground', () => {
const preStyle = ref('')
const isLoading = ref(true)

function randomize() {
function randomize(): void {
if (allLanguages.value.length && allThemes.value.length) {
lang.value = allLanguages.value[Math.floor(Math.random() * allLanguages.value.length)].id as any
theme.value = allThemes.value[Math.floor(Math.random() * allThemes.value.length)].id as any
Expand All @@ -46,7 +46,7 @@ export const usePlayground = defineStore('playground', () => {

const samplesCache = new Map<string, Promise<string | undefined>>()

function fetchSample(id: string) {
function fetchSample(id: string): Promise<string | undefined> {
if (!samplesCache.has(id)) {
samplesCache.set(id, fetch(`https://raw.githubusercontent.com/antfu/textmate-grammars-themes/main/samples/${id}.sample`)
.then(r => r.text())
Expand Down Expand Up @@ -86,7 +86,7 @@ export const usePlayground = defineStore('playground', () => {
run()
}, { immediate: true })

function run() {
function run(): void {
output.value = highlighter.codeToHtml(input.value, {
lang: lang.value,
theme: theme.value,
Expand Down
4 changes: 2 additions & 2 deletions docs/packages/vitepress.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ export default defineConfig({
And then in your [`.vitepress/theme/index.ts`](https://vitepress.dev/guide/custom-theme), install the Vue plugin and import the css with `@shikijs/vitepress-twoslash/styles.css`.

```ts twoslash
import type { EnhanceAppContext } from 'vitepress' // [!code hl]
// @noErrors: true
// .vitepress/theme/index.ts
import TwoslashFloatingVue from '@shikijs/vitepress-twoslash/client' // [!code hl]
import type { EnhanceAppContext } from 'vitepress'
import TwoslashFloatingVue from '@shikijs/vitepress-twoslash/client'
import Theme from 'vitepress/theme'

import '@shikijs/vitepress-twoslash/style.css' // [!code hl]
Expand Down
1 change: 1 addition & 0 deletions docs/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"target": "ESNext",
"module": "esnext",
Expand Down
13 changes: 13 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import antfu from '@antfu/eslint-config'

export default antfu(
{
type: 'lib',
formatters: {
html: false,
markdown: true,
Expand All @@ -12,6 +13,12 @@ export default antfu(
overrides: {
'unicorn/prefer-node-protocol': 'off',
'import/first': 'off',
'ts/explicit-function-return-type': 'off',
},
},
vue: {
overrides: {
'ts/explicit-function-return-type': 'off',
},
},
ignores: [
Expand All @@ -29,4 +36,10 @@ export default antfu(
'ts/no-invalid-this': 'off',
},
},
{
files: ['docs/**/*.([cm])?[jt]s(x)?'],
rules: {
'ts/explicit-function-return-type': 'off',
},
},
)
3 changes: 1 addition & 2 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* eslint-disable no-console */
import type { BundledLanguage } from 'shiki'
import fs from 'node:fs/promises'
import { parse } from 'node:path'
Expand All @@ -9,7 +8,7 @@ import { codeToANSI } from './code-to-ansi'
export async function run(
argv = process.argv.slice(2),
log = console.log,
) {
): Promise<void> {
const options = minimist(argv)
const {
theme = 'vitesse-dark',
Expand Down
8 changes: 4 additions & 4 deletions packages/cli/src/colors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function normalizeHex(hex: string) {
function normalizeHex(hex: string): string {
hex = hex.replace(/#/, '')
if (hex.length === 3)
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
Expand All @@ -9,7 +9,7 @@ function normalizeHex(hex: string) {
return hex.toLowerCase()
}

function hexToRgba(hex: string) {
function hexToRgba(hex: string): { r: number, g: number, b: number, a: number } {
hex = normalizeHex(hex)
const r = Number.parseInt(hex.slice(0, 2), 16)
const g = Number.parseInt(hex.slice(2, 4), 16)
Expand All @@ -18,7 +18,7 @@ function hexToRgba(hex: string) {
return { r, g, b, a }
}

function RgbToHex(r: number, g: number, b: number) {
function RgbToHex(r: number, g: number, b: number): string {
return [r, g, b]
.map((x) => {
const hex = x.toString(16)
Expand All @@ -27,7 +27,7 @@ function RgbToHex(r: number, g: number, b: number) {
.join('')
}

export function hexApplyAlpha(hex: string, type: 'dark' | 'light' = 'dark') {
export function hexApplyAlpha(hex: string, type: 'dark' | 'light' = 'dark'): string {
const { r, g, b, a } = hexToRgba(hex)
if (type === 'dark')
return RgbToHex(r * a, g * a, b * a)
Expand Down
20 changes: 18 additions & 2 deletions packages/compat/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,23 @@ export * from './types'
export { normalizeTheme } from 'shiki'
export { normalizeTheme as toShikiTheme } from 'shiki'

export async function getHighlighter(options: Partial<HighlighterOptions> = {}) {
export interface ShikiCompatHighlighter {
ansiToHtml: (code: string, options?: AnsiToHtmlOptions) => string

codeToHtml: ((code: string, options: CodeToHtmlOptions) => string)
& ((code: string, lang: StringLiteralUnion<BuiltinLanguage>, theme?: StringLiteralUnion<BuiltinTheme>, options?: CodeToHtmlOptionsExtra) => string)

codeToThemedTokens: (code: string, lang: BuiltinLanguage, theme?: BuiltinTheme, options?: CodeToTokensBaseOptions<BuiltinLanguage, BuiltinTheme>) => ThemedToken[][]
codeToTokensBase: (code: string, lang: BuiltinLanguage, theme?: BuiltinTheme, options?: CodeToTokensBaseOptions<BuiltinLanguage, BuiltinTheme>) => ThemedToken[][]
getBackgroundColor: (theme: BuiltinTheme | ThemeRegistrationAny | string) => string
getForegroundColor: (theme: BuiltinTheme | ThemeRegistrationAny | string) => string
ansiToThemedTokens: (ansi: string, options?: CodeToTokensBaseOptions) => ThemedToken[][]
setColorReplacements: (...args: any[]) => void
getLoadedThemes: () => string[]
getLoadedLanguages: () => string[]
}

export async function getHighlighter(options: Partial<HighlighterOptions> = {}): Promise<ShikiCompatHighlighter> {
const themes = options.themes || []
const langs = options.langs || []

Expand Down Expand Up @@ -89,7 +105,7 @@ export async function getHighlighter(options: Partial<HighlighterOptions> = {})
function ansiToThemedTokens(
ansi: string,
options: CodeToTokensBaseOptions = {},
) {
): ThemedToken[][] {
const theme = shiki.getTheme(options.theme || shiki.getLoadedThemes()[0])
return tokenizeAnsiWithTheme(theme, ansi)
}
Expand Down
5 changes: 3 additions & 2 deletions packages/compat/src/stub.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const _warned = new Set<string>()
function warnOnce(message: string) {

function warnOnce(message: string): void {
if (!_warned.has(message)) {
console.warn(`[shiki-compat]: ${message}`)
_warned.add(message)
}
}
function stubFunction(name: string) {
function stubFunction(name: string): () => void {
return () => {
warnOnce(`\`${name}\` is a stub function in \`shiki-compat\` and does nothing.`)
}
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/constructors/bundle-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,12 +192,14 @@ export interface ShorthandsBundle<L extends string, T extends string> {
getLastGrammarState: (code: string, options: CodeToTokensBaseOptions<L, T>) => Promise<GrammarState>
}

export function makeSingletonHighlighter<L extends string, T extends string>(createHighlighter: CreateHighlighterFactory<L, T>) {
export function makeSingletonHighlighter<L extends string, T extends string>(
createHighlighter: CreateHighlighterFactory<L, T>,
): (options?: Partial<BundledHighlighterOptions<L, T>>) => Promise<HighlighterGeneric<L, T>> {
let _shiki: ReturnType<typeof createHighlighter>

async function getSingletonHighlighter(
options: Partial<BundledHighlighterOptions<L, T>> = {},
) {
): Promise<HighlighterGeneric<L, T>> {
if (!_shiki) {
_shiki = createHighlighter({
...options,
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/constructors/highlighter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,14 @@ export function createHighlighterCoreSync(options: HighlighterCoreOptions<true>
}
}

export function makeSingletonHighlighterCore(createHighlighter: typeof createHighlighterCore) {
export function makeSingletonHighlighterCore(
createHighlighter: typeof createHighlighterCore,
): (options?: Partial<HighlighterCoreOptions>) => Promise<HighlighterCore> {
let _shiki: ReturnType<typeof createHighlighterCore>

async function getSingletonHighlighterCore(
options: Partial<HighlighterCoreOptions> = {},
) {
): Promise<HighlighterCore> {
if (!_shiki) {
_shiki = createHighlighter({
...options,
Expand Down
24 changes: 14 additions & 10 deletions packages/core/src/constructors/internal-sync.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {
Grammar,
HighlighterCoreOptions,
LanguageInput,
LanguageRegistration,
Expand Down Expand Up @@ -42,7 +43,7 @@ export function createShikiInternalSync(options: HighlighterCoreOptions<true>):

let _lastTheme: string | ThemeRegistrationAny

function getLanguage(name: string | LanguageRegistration) {
function getLanguage(name: string | LanguageRegistration): Grammar {
ensureNotDisposed()
const _lang = _registry.getGrammar(typeof name === 'string' ? name : name.name)
if (!_lang)
Expand All @@ -60,7 +61,10 @@ export function createShikiInternalSync(options: HighlighterCoreOptions<true>):
return _theme
}

function setTheme(name: string | ThemeRegistrationAny) {
function setTheme(name: string | ThemeRegistrationAny): {
theme: ThemeRegistrationResolved
colorMap: string[]
} {
ensureNotDisposed()
const theme = getTheme(name)
if (_lastTheme !== name) {
Expand All @@ -74,43 +78,43 @@ export function createShikiInternalSync(options: HighlighterCoreOptions<true>):
}
}

function getLoadedThemes() {
function getLoadedThemes(): string[] {
ensureNotDisposed()
return _registry.getLoadedThemes()
}

function getLoadedLanguages() {
function getLoadedLanguages(): string[] {
ensureNotDisposed()
return _registry.getLoadedLanguages()
}

function loadLanguageSync(...langs: MaybeArray<LanguageRegistration>[]) {
function loadLanguageSync(...langs: MaybeArray<LanguageRegistration>[]): void {
ensureNotDisposed()
_registry.loadLanguages(langs.flat(1))
}

async function loadLanguage(...langs: (LanguageInput | SpecialLanguage)[]) {
async function loadLanguage(...langs: (LanguageInput | SpecialLanguage)[]): Promise<void> {
return loadLanguageSync(await resolveLangs(langs))
}

async function loadThemeSync(...themes: MaybeArray<ThemeRegistrationAny>[]) {
function loadThemeSync(...themes: MaybeArray<ThemeRegistrationAny>[]): void {
ensureNotDisposed()
for (const theme of themes.flat(1)) {
_registry.loadTheme(theme)
}
}

async function loadTheme(...themes: (ThemeInput | SpecialTheme)[]) {
async function loadTheme(...themes: (ThemeInput | SpecialTheme)[]): Promise<void> {
ensureNotDisposed()
return loadThemeSync(await resolveThemes(themes))
}

function ensureNotDisposed() {
function ensureNotDisposed(): void {
if (isDisposed)
throw new ShikiError('Shiki instance has been disposed')
}

function dispose() {
function dispose(): void {
if (isDisposed)
return
isDisposed = true
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/engines/oniguruma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ let _defaultWasmLoader: LoadWasmOptions | undefined
* Set the default wasm loader for `loadWasm`.
* @internal
*/
export function setDefaultWasmLoader(_loader: LoadWasmOptions) {
export function setDefaultWasmLoader(_loader: LoadWasmOptions): void {
_defaultWasmLoader = _loader
}

/**
* @internal
*/
export function getDefaultWasmLoader() {
export function getDefaultWasmLoader(): LoadWasmOptions | undefined {
return _defaultWasmLoader
}
8 changes: 4 additions & 4 deletions packages/core/src/highlight/code-to-hast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export function codeToHast(
codeToHast: (_code, _options) => codeToHast(internal, _code, _options),
codeToTokens: (_code, _options) => codeToTokens(internal, _code, _options),
},
) {
): Root {
let input = code

for (const transformer of getTransformers(options))
Expand Down Expand Up @@ -79,7 +79,7 @@ export function tokensToHast(
tokens: ThemedToken[][],
options: CodeToHastRenderOptions,
transformerContext: ShikiTransformerContextSource,
) {
): Root {
const transformers = getTransformers(options)

const lines: (Element | Text)[] = []
Expand Down Expand Up @@ -212,7 +212,7 @@ export function tokensToHast(
return result
}

function mergeWhitespaceTokens(tokens: ThemedToken[][]) {
function mergeWhitespaceTokens(tokens: ThemedToken[][]): ThemedToken[][] {
return tokens.map((line) => {
const newLine: ThemedToken[] = []
let carryOnContent = ''
Expand Down Expand Up @@ -255,7 +255,7 @@ function mergeWhitespaceTokens(tokens: ThemedToken[][]) {
})
}

function splitWhitespaceTokens(tokens: ThemedToken[][]) {
function splitWhitespaceTokens(tokens: ThemedToken[][]): ThemedToken[][] {
return tokens.map((line) => {
return line.flatMap((token) => {
if (token.content.match(/^\s+$/))
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/highlight/code-to-tokens-ansi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function tokenizeAnsiWithTheme(
/**
* Adds 50% alpha to a hex color string or the "-dim" postfix to a CSS variable
*/
function dimColor(color: string) {
function dimColor(color: string): string {
const hexMatch = color.match(/#([0-9a-f]{3})([0-9a-f]{3})?([0-9a-f]{2})?/)
if (hexMatch) {
if (hexMatch[3]) {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/highlight/code-to-tokens-themes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export function codeToTokensWithThemes(
* - `console . log ( " hello " )` (8 tokens)
* - `console . log ( " hello " )` (8 tokens)
*/
export function syncThemesTokenization(...themes: ThemedToken[][][]) {
export function syncThemesTokenization(...themes: ThemedToken[][][]): ThemedToken[][][] {
const outThemes = themes.map<ThemedToken[][]>(() => [])
const count = themes.length

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/highlight/code-to-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ function mergeToken(
variantsOrder: string[],
cssVariablePrefix: string,
defaultColor: string | boolean,
) {
): ThemedToken {
const token: ThemedToken = {
content: merged.content,
explanation: merged.explanation,
Expand Down
Loading

0 comments on commit 1d27094

Please sign in to comment.