Skip to content

Commit

Permalink
feat: Remove support for Sync methods (#4989)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason3S authored Nov 20, 2023
1 parent 6e8c7e9 commit e02ee73
Show file tree
Hide file tree
Showing 31 changed files with 255 additions and 259 deletions.
66 changes: 43 additions & 23 deletions packages/cspell-io/src/node/file/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,31 @@ import { describe, expect, test } from 'vitest';
import { fetchHead, fetchURL } from './fetch.js';
// import {} from './_fetch.js';

const timeout = 20000;

const testOptions = { timeout };

describe('fetch', () => {
test('fetch url', async () => {
const url = new URL('https://example.com/');
const response = await fetch(url);
expect(response.ok).toBe(true);
expect(await response.text()).toMatch('Example Domain');
});

test('fetchURL', async () => {
const url = new URL('https://example.com/');
const response = await fetchURL(url);
expect(response).toBeInstanceOf(Buffer);
});
test(
'fetch url',
async () => {
const url = new URL('https://example.com/');
const response = await fetch(url);
expect(response.ok).toBe(true);
expect(await response.text()).toMatch('Example Domain');
},
testOptions,
);

test(
'fetchURL',
async () => {
const url = new URL('https://example.com/');
const response = await fetchURL(url);
expect(response).toBeInstanceOf(Buffer);
},
testOptions,
);

/*
test.each`
Expand All @@ -29,27 +41,35 @@ describe('fetch', () => {
// console.log('%o', toObj(response));
expect(response.get('etag')).toEqual(expect.any(String));
expect(Number.parseInt(response.get('content-length') || '', 10)).toBeGreaterThan(0);
});
}, testOptions);
*/

test.each`
url
${'https://example.com/'}
`('fetchHead $url', async ({ url }) => {
const response = await fetchHead(url);
// console.log('%o', toObj(response));
expect(response.get('etag')).toEqual(expect.any(String));
expect(Number.parseInt(response.get('content-length') || '', 10)).toBeGreaterThan(0);
});
`(
'fetchHead $url',
async ({ url }) => {
const response = await fetchHead(url);
// console.log('%o', toObj(response));
expect(response.get('etag')).toEqual(expect.any(String));
expect(Number.parseInt(response.get('content-length') || '', 10)).toBeGreaterThan(0);
},
testOptions,
);

test.each`
url | expected
${'https://x.example.com/'} | ${'getaddrinfo ENOTFOUND x.example.com'}
${'https://interglot.com/not_found/file.txt'} | ${/URL not found|getaddrinfo EAI_AGAIN/}
`('fetchURL with error', async ({ url, expected }) => {
url = new URL(url);
await expect(fetchURL(url)).rejects.toThrowError(expected);
});
`(
'fetchURL with error',
async ({ url, expected }) => {
url = new URL(url);
await expect(fetchURL(url)).rejects.toThrowError(expected);
},
testOptions,
);
});

// function toObj(m: Iterable<[string, string]>): Record<string, string> {
Expand Down
24 changes: 8 additions & 16 deletions packages/cspell-lib/api/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -409,8 +409,8 @@ interface ImportFileRefWithError$1 extends ImportFileRef {
* - relative path `./path/to/file` (relative to the current working directory)
* - package `@cspell/dict-typescript/cspell-ext.json`
*/
declare function readSettings(filename: string): CSpellSettingsI$1;
declare function readSettings(filename: string, defaultValues: CSpellSettingsWST$1): CSpellSettingsI$1;
declare function readSettings(filename: string | URL): Promise<CSpellSettingsI$1>;
declare function readSettings(filename: string | URL, pnpSettings: PnPSettingsOptional): Promise<CSpellSettingsI$1>;
/**
* Read / import a cspell configuration file.
* @param filename - the path to the file.
Expand All @@ -420,16 +420,16 @@ declare function readSettings(filename: string, defaultValues: CSpellSettingsWST
* - package `@cspell/dict-typescript/cspell-ext.json` searches for node_modules relative to `relativeTo`
* @param relativeTo - absolute path to start searching for relative files or node_modules.
*/
declare function readSettings(filename: string, relativeTo: string): CSpellSettingsI$1;
declare function readSettings(filename: string, relativeTo: string, defaultValues: CSpellSettingsWST$1): CSpellSettingsI$1;
declare function readSettings(filename: string | URL, relativeTo: string | URL): Promise<CSpellSettingsI$1>;
declare function readSettings(filename: string | URL, relativeTo: string | URL, pnpSettings: PnPSettingsOptional): Promise<CSpellSettingsI$1>;

/**
*
* @param filenames - settings files to read
* @returns combined configuration
* @deprecated true
*/
declare function readSettingsFiles(filenames: string[]): CSpellSettingsI$1;
declare function readSettingsFiles(filenames: string[]): Promise<CSpellSettingsI$1>;

type CSpellSettingsWST = AdvancedCSpellSettingsWithSourceTrace;
type CSpellSettingsWSTO = OptionalOrUndefined<AdvancedCSpellSettingsWithSourceTrace>;
Expand Down Expand Up @@ -466,7 +466,7 @@ interface ConfigurationDependencies {
declare function extractDependencies(settings: CSpellSettingsWSTO | CSpellSettingsI): ConfigurationDependencies;

declare function getDefaultSettings(useDefaultDictionaries?: boolean): CSpellSettingsInternal;
declare function getDefaultBundledSettings(): CSpellSettingsInternal;
declare function getDefaultBundledSettingsAsync(): Promise<CSpellSettingsInternal>;

declare function combineTextAndLanguageSettings(settings: CSpellUserSettings, text: string | undefined, languageId: string | string[]): CSpellSettingsInternal;

Expand Down Expand Up @@ -668,14 +668,6 @@ declare class DocumentValidator {
*/
constructor(doc: TextDocument, options: DocumentValidatorOptions, settings: CSpellUserSettings);
get ready(): boolean;
/**
* Prepare to validate a document.
* This will load all the necessary configuration and dictionaries.
*
* @deprecated
* @deprecationMessage Use the async `prepare` method.
*/
prepareSync(): void;
prepare(): Promise<void>;
private _prepareAsync;
private _updatePrep;
Expand Down Expand Up @@ -845,7 +837,7 @@ interface DetermineFinalDocumentSettingsResult {
* `languageId` - if defined will be used to select appropriate file type dictionaries.
* @param settings - The near final settings. Should already be the combination of all configuration files.
*/
declare function determineFinalDocumentSettings(document: DocumentWithText, settings: CSpellUserSettings): DetermineFinalDocumentSettingsResult;
declare function determineFinalDocumentSettings(document: DocumentWithText, settings: CSpellUserSettings): Promise<DetermineFinalDocumentSettingsResult>;

interface TraceResult {
word: string;
Expand Down Expand Up @@ -908,4 +900,4 @@ declare function clearCachedFiles(): Promise<void>;
*/
declare function getDictionary(settings: CSpellUserSettings): Promise<SpellingDictionaryCollection>;

export { type CheckTextInfo, type ConfigurationDependencies, type CreateTextDocumentParams, type DetermineFinalDocumentSettingsResult, type Document, DocumentValidator, type DocumentValidatorOptions, ENV_CSPELL_GLOB_ROOT, type ExcludeFilesGlobMap, type ExclusionFunction, exclusionHelper_d as ExclusionHelper, type FeatureFlag, FeatureFlags, ImportError, type ImportFileRefWithError, IncludeExcludeFlag, type IncludeExcludeOptions, index_link_d as Link, type Logger, type SpellCheckFileOptions, type SpellCheckFileResult, SpellingDictionaryLoadError, type SuggestedWord, SuggestionError, type SuggestionOptions, type SuggestionsForWordResult, text_d as Text, type TextDocument, type TextDocumentLine, type TextDocumentRef, type TextInfoItem, type TraceOptions, type TraceResult, UnknownFeatureFlagError, type ValidationIssue, calcOverrideSettings, checkFilenameMatchesGlob, checkText, checkTextDocument, clearCachedFiles, clearCachedSettingsFiles, combineTextAndLanguageSettings, combineTextAndLanguageSettings as constructSettingsForText, createTextDocument, currentSettingsFileVersion, defaultConfigFilenames, defaultFileName, defaultFileName as defaultSettingsFilename, determineFinalDocumentSettings, extractDependencies, extractImportErrors, fileToDocument, fileToTextDocument, finalizeSettings, getCachedFileSize, getDefaultBundledSettings, getDefaultSettings, getDictionary, getGlobalSettings, getLanguagesForBasename as getLanguageIdsForBaseFilename, getLanguagesForExt, getLogger, getSources, getSystemFeatureFlags, isBinaryFile, isSpellingDictionaryLoadError, loadConfig, loadPnP, loadPnPSync, mergeInDocSettings, mergeSettings, readRawSettings, readSettings, readSettingsFiles, refreshDictionaryCache, resolveFile, searchForConfig, sectionCSpell, setLogger, shouldCheckDocument, spellCheckDocument, spellCheckFile, suggestionsForWord, suggestionsForWords, traceWords, traceWordsAsync, updateTextDocument, validateText };
export { type CheckTextInfo, type ConfigurationDependencies, type CreateTextDocumentParams, type DetermineFinalDocumentSettingsResult, type Document, DocumentValidator, type DocumentValidatorOptions, ENV_CSPELL_GLOB_ROOT, type ExcludeFilesGlobMap, type ExclusionFunction, exclusionHelper_d as ExclusionHelper, type FeatureFlag, FeatureFlags, ImportError, type ImportFileRefWithError, IncludeExcludeFlag, type IncludeExcludeOptions, index_link_d as Link, type Logger, type SpellCheckFileOptions, type SpellCheckFileResult, SpellingDictionaryLoadError, type SuggestedWord, SuggestionError, type SuggestionOptions, type SuggestionsForWordResult, text_d as Text, type TextDocument, type TextDocumentLine, type TextDocumentRef, type TextInfoItem, type TraceOptions, type TraceResult, UnknownFeatureFlagError, type ValidationIssue, calcOverrideSettings, checkFilenameMatchesGlob, checkText, checkTextDocument, clearCachedFiles, clearCachedSettingsFiles, combineTextAndLanguageSettings, combineTextAndLanguageSettings as constructSettingsForText, createTextDocument, currentSettingsFileVersion, defaultConfigFilenames, defaultFileName, defaultFileName as defaultSettingsFilename, determineFinalDocumentSettings, extractDependencies, extractImportErrors, fileToDocument, fileToTextDocument, finalizeSettings, getCachedFileSize, getDefaultBundledSettingsAsync, getDefaultSettings, getDictionary, getGlobalSettings, getLanguagesForBasename as getLanguageIdsForBaseFilename, getLanguagesForExt, getLogger, getSources, getSystemFeatureFlags, isBinaryFile, isSpellingDictionaryLoadError, loadConfig, loadPnP, loadPnPSync, mergeInDocSettings, mergeSettings, readRawSettings, readSettings, readSettingsFiles, refreshDictionaryCache, resolveFile, searchForConfig, sectionCSpell, setLogger, shouldCheckDocument, spellCheckDocument, spellCheckFile, suggestionsForWord, suggestionsForWords, traceWords, traceWordsAsync, updateTextDocument, validateText };
40 changes: 20 additions & 20 deletions packages/cspell-lib/src/lib/Settings/CSpellSettingsServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
readSettingsFiles,
} from './Controller/configLoader/index.js';
import { calcOverrideSettings, checkFilenameMatchesGlob, getSources, mergeSettings } from './CSpellSettingsServer.js';
import { _defaultSettings, getDefaultBundledSettings } from './DefaultSettings.js';
import { _defaultSettings, getDefaultBundledSettingsAsync } from './DefaultSettings.js';

const samplesDir = pathPackageSamples;
const pathSrc = path.join(pathPackageRoot, 'src');
Expand Down Expand Up @@ -186,47 +186,47 @@ describe('Validate CSpellSettingsServer', () => {
${rpr('./cspell.config.json')} | ${pathSrc} | ${rpr('./cspell.config.json')}
${'@cspell/cspell-bundled-dicts/cspell-default.json'} | ${pathSrc} | ${require.resolve('@cspell/cspell-bundled-dicts/cspell-default.json')}
${'@cspell/cspell-bundled-dicts/cspell-default.json'} | ${undefined} | ${require.resolve('@cspell/cspell-bundled-dicts/cspell-default.json')}
`('tests readSettings $filename $relativeTo', ({ filename, relativeTo, refFilename }) => {
const settings = readSettings(filename, relativeTo);
`('tests readSettings $filename $relativeTo', async ({ filename, relativeTo, refFilename }) => {
const settings = await readSettings(filename, relativeTo);
expect(settings.__importRef?.filename).toBe(refFilename);
expect(settings.__importRef?.error).toBeUndefined();
expect(settings.import).toBeUndefined();
});

test('tests loading project cspell.json file', () => {
test('tests loading project cspell.json file', async () => {
const filename = path.join(pathPackageSamples, 'linked/cspell-missing.json');
const settings = readSettings(filename);
const settings = await readSettings(filename);
expect(Object.keys(settings)).not.toHaveLength(0);
expect(settings.words).toBeUndefined();
});

test('tests loading a cSpell.json file', () => {
test('tests loading a cSpell.json file', async () => {
const filename = path.join(pathPackageSamples, 'linked/cspell-import.json');
const settings = readSettings(filename);
const settings = await readSettings(filename);
expect(Object.keys(settings)).not.toHaveLength(0);
expect(settings.words).toEqual(expect.arrayContaining(['import']));
});

test('readSettingsFiles cSpell.json', () => {
test('readSettingsFiles cSpell.json', async () => {
const filename = path.join(pathPackageSamples, 'linked/cspell-import.json');
const settings = readSettingsFiles([filename]);
const settings = await readSettingsFiles([filename]);
expect(Object.keys(settings)).not.toHaveLength(0);
expect(settings.words).toEqual(expect.arrayContaining(['import']));
});

test('tests loading a cSpell.json with multiple imports file', () => {
test('tests loading a cSpell.json with multiple imports file', async () => {
const filename = path.join(pathPackageSamples, 'linked/cspell-imports.json');
const settings = readSettings(filename);
const settings = await readSettings(filename);
expect(Object.keys(settings)).not.toHaveLength(0);
expect(settings.words).toEqual(expect.arrayContaining(['import']));
expect(settings.words).toEqual(expect.arrayContaining(['imports']));
// cspell:word leuk
expect(settings.words).toEqual(expect.arrayContaining(['leuk']));
});

test('tests loading a cSpell.json with a missing import file', () => {
test('tests loading a cSpell.json with a missing import file', async () => {
const filename = path.join(pathPackageSamples, 'linked/cspell-import-missing.json');
const settings = readSettings(filename);
const settings = await readSettings(filename);
expect(settings.__importRef?.filename).toBe(path.resolve(filename));
expect(settings.__imports?.size).toBe(2);
const errors = extractImportErrors(settings);
Expand All @@ -237,30 +237,30 @@ describe('Validate CSpellSettingsServer', () => {
expect(errors.map((ref) => ref.error.toString())).toContainEqual(expect.stringMatching('Failed to read'));
});

test('makes sure global settings is an object', () => {
test('makes sure global settings is an object', async () => {
const settings = getGlobalSettings();
expect(Object.keys(settings)).not.toHaveLength(0);
const merged = mergeSettings(getDefaultBundledSettings(), getGlobalSettings());
const merged = mergeSettings(await getDefaultBundledSettingsAsync(), getGlobalSettings());
expect(Object.keys(merged)).not.toHaveLength(0);
});

test('verify clearing the file cache works', () => {
mergeSettings(getDefaultBundledSettings(), getGlobalSettings());
test('verify clearing the file cache works', async () => {
mergeSettings(await getDefaultBundledSettingsAsync(), getGlobalSettings());
expect(getCachedFileSize()).toBeGreaterThan(0);
clearCachedSettingsFiles();
expect(getCachedFileSize()).toBe(0);
});

test('the loaded defaults contain expected settings', () => {
const settings = getDefaultBundledSettings();
test('the loaded defaults contain expected settings', async () => {
const settings = await getDefaultBundledSettingsAsync();
const sources = getSources(settings);
const sourceNames = sources.map((s) => s.name || '?');
expect(sourceNames).toEqual(expect.arrayContaining([_defaultSettings.name]));
});

test('loading circular imports (readSettings)', async () => {
const configFile = path.join(samplesDir, 'linked/cspell.circularA.json');
const config = readSettings(configFile);
const config = await readSettings(configFile);
expect(config?.ignorePaths).toEqual(
expect.arrayContaining([
{
Expand Down
Loading

0 comments on commit e02ee73

Please sign in to comment.