Skip to content

Commit

Permalink
fix: solve todo
Browse files Browse the repository at this point in the history
  • Loading branch information
CurryYangxx committed May 7, 2024
1 parent 784b92d commit 9d9d86a
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 37 deletions.
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/insomnia/src/main/window-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,6 @@ export function createWindow(): ElectronBrowserWindow {
preload: path.join(__dirname, 'preload.js'),
zoomFactor: getZoomFactor(),
nodeIntegration: true,
nodeIntegrationInWorker: true,
webviewTag: true,
// TODO: enable context isolation
contextIsolation: false,
Expand Down
97 changes: 64 additions & 33 deletions packages/insomnia/src/ui/routes/design.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
useParams,
useRouteLoaderData,
} from 'react-router-dom';
import { useUnmount } from 'react-use';
import { SwaggerUIBundle } from 'swagger-ui-dist';
import YAML from 'yaml';
import YAMLSourceMap from 'yaml-source-map';
Expand Down Expand Up @@ -235,8 +236,12 @@ const Design: FC = () => {
};
}, []);

useEffect(() => {
// use this ref to handle codemirror lint race conditions, only the id matching the latest will be updated
const lintIdRef = useRef(0);

const registerCodeMirrorLint = (ruleset?: Ruleset) => {
CodeMirror.registerHelper('lint', 'openapi', async (contents: string) => {
console.log('run lint');
// @TODO: Conisderations and things we need to verify/test:
// - Should we spawn a new worker on every lint command or use a shared worker?
// - Does this function handle race conditions? e.g. if a lint finishes late does it replace another lint that ran with latest contents?
Expand All @@ -245,56 +250,82 @@ const Design: FC = () => {
const worker = new Worker(new URL('../worker/spectral.ts', import.meta.url), {
type: 'module',
});
const currentLintId = ++lintIdRef.current;
lintIdRef.current = currentLintId;
// const worker = new SharedWorker(new URL('../worker/spectral.ts', import.meta.url), {
// type: 'module',
// });

const func = async () => {
let ruleset: Ruleset;

try {
ruleset = await window.main.loadSpectralRuleset({ rulesetPath });
} catch (e) {
console.error('Failed to load spectral ruleset', e);
}
return new Promise<ISpectralDiagnostic[]>((resolve, reject) => {

worker.onmessage = e => {
if (false) {
resolve(e.data);
} else {
reject();
}
};

return new Promise<ISpectralDiagnostic[]>(resolve => {
// worker.onerror = e => {
// console.log('worker error', e);
// }
worker.postMessage({
contents,
ruleset,
});

worker.onmessage = e => {
resolve(e.data);
};
});
};

const diagnostics = await func();
try {
const diagnostics = await func();

const lintResult = diagnostics.map(({ severity, code, message, range }) => {
return {
from: CodeMirror.Pos(
range.start.line,
range.start.character
),
to: CodeMirror.Pos(range.end.line, range.end.character),
message: `${code} ${message}`,
severity: ['error', 'warning'][severity] ?? 'info',
type: (['error', 'warning'][severity] ?? 'info') as LintMessage['type'],
range,
line: range.start.line,
};
});
setLintMessages?.(lintResult);
return lintResult;
const lintResult = diagnostics.map(({ severity, code, message, range }) => {
return {
from: CodeMirror.Pos(
range.start.line,
range.start.character
),
to: CodeMirror.Pos(range.end.line, range.end.character),
message: `${code} ${message}`,
severity: ['error', 'warning'][severity] ?? 'info',
type: (['error', 'warning'][severity] ?? 'info') as LintMessage['type'],
range,
line: range.start.line,
};
});
setLintMessages?.(lintResult);
return lintResult;
} catch (e) {
return [];
};
});
};

const loadRuleset = useCallback(async () => {
let ruleset: Ruleset | undefined;

try {
ruleset = rulesetPath ? await window.main.loadSpectralRuleset({ rulesetPath }) : undefined;
} catch (e) {
console.error('Failed to load spectral ruleset', e);
}
registerCodeMirrorLint(ruleset);
// when first time into document editor, the lint helper register later than codemirror init, we need to trigger lint through execute setOption
editor.current?.tryToSetOption('lint', { ...lintOptions });

return () => {
// delete the helper to avoid it run multiple times when user enter the page next time
CodeMirror.registerHelper('lint', 'openapi', undefined);
};
}, [rulesetPath, lintOptions]);

useEffect(() => {
loadRuleset();
}, [rulesetPath, loadRuleset]);

useUnmount(() => {
// delete the helper to avoid it run multiple times when user enter the page next time
CodeMirror.registerHelper('lint', 'openapi', undefined);
});

const onCodeEditorChange = useMemo(() => {
const handler = async (contents: string) => {
updateApiSpecFetcher.submit(
Expand Down
13 changes: 11 additions & 2 deletions packages/insomnia/src/ui/worker/spectral.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,26 @@ interface SpectralRunParams {
ruleset?: Ruleset;
}

// onconnect = event => {
// const port = event.ports[0];

// port.onmessage = e => {
// port.postMessage('1');
// // new Spectral();
// port.postMessage('2');
// };
// };

const spectralRun = async ({ contents, ruleset }: SpectralRunParams) => {
try {
const spectral = new Spectral();

spectral.setRuleset(ruleset || oas as RulesetDefinition);

const diagnostics = await spectral.run(contents);

postMessage(diagnostics);
} catch (err) {
postMessage(err);
postMessage([]);
}
};

Expand Down

0 comments on commit 9d9d86a

Please sign in to comment.