Skip to content

Commit

Permalink
Revert "Greatly cleanup and works towards ESM (#32)"
Browse files Browse the repository at this point in the history
This reverts commit b10a3ed.
  • Loading branch information
mark-wiemer authored Sep 28, 2024
1 parent b10a3ed commit dbcf18a
Show file tree
Hide file tree
Showing 42 changed files with 2,154 additions and 270 deletions.
6 changes: 4 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ node_modules
*.vsix
scripts/*
*.js
*.cjs
*.js.map
*.tsbuildinfo
**/dist/**/*.d.ts
**/dist/**/*.d.ts

# Vitest
coverage
2 changes: 1 addition & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ scripts/*
server/expr_parser/*

client/src/browserClientMain.ts
client/src/extension.cts
client/src/extension.ts
client/src/test/utils.ts
server/src/ahkProvider.ts
server/src/browserServerMain.ts
Expand Down
19 changes: 19 additions & 0 deletions .vscode-test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// https://github.com/microsoft/vscode-test-cli
import { defineConfig } from '@vscode/test-cli';
import { execSync } from 'child_process';

let vscode_path = undefined;
try {
const m = execSync(
'chcp 65001 && reg query HKCR\\vscode\\shell\\open\\command',
{ encoding: 'utf8' },
).match(/REG_SZ\s+("([^"]+)"|\S+)/);
vscode_path = m[2] || m[1];
} catch {}

export default defineConfig({
files: 'client/dist/test/**/*.e2e.js',
useInstallation: vscode_path && {
fromPath: vscode_path,
},
});
3 changes: 2 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"recommendations": [
"aaron-bond.better-comments",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode"
"esbenp.prettier-vscode",
"vitest.explorer"
]
}
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceFolder}"],
"env": {
"VSCODE_AHK_SERVER_PATH": "server/dist/server.cjs",
"VSCODE_AHK_SERVER_PATH": "server/dist/server.js",
"SYNTAXES_PATH": "syntaxes"
},
"outFiles": ["${workspaceFolder}/client/dist/**/*.js"],
Expand Down
40 changes: 40 additions & 0 deletions .vscode/snippets.code-snippets
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
// Place your ahk2 workspace snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is
// used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
// Placeholders with the same ids are connected.
// Example:
// "Print to console": {
// "scope": "javascript,typescript",
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }

"Add unit test": {
"scope": "typescript",
"prefix": "describe",
"body": [
"describe('$1', () => {",
"\ttest.concurrent.each<",
"\t[",
"\t\tname: string,",
"\t\t\targs: Parameters<typeof $1>,",
"\t\t\texpected: ReturnType<typeof $1>,",
"\t\t]",
"\t>([",
"\t['$2', [$3], $4],",
"\t])('%s', (_name, args, expected) => {",
"\t\tconst result = $1(...args);",
"\t\texpect(result).toBe(expected);",
"\t});",
"});",
],
"description": "Add Vitest test.concurrent.each in a describe block",
},
}
6 changes: 3 additions & 3 deletions build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ console.log(
build({
entryPoints: [path.join('./server/src/server.ts')],
bundle: true,
outfile: path.join('./server/dist/server.cjs'),
outfile: path.join('./server/dist/server.js'),
external: ['vscode'],
format: 'cjs',
platform: 'node',
Expand All @@ -25,9 +25,9 @@ build({
// Node client (not necessary for AHK++, but super fast)
// https://esbuild.github.io/api
build({
entryPoints: [path.join('./client/src/extension.cts')],
entryPoints: [path.join('./client/src/extension.ts')],
bundle: true,
outfile: path.join('./client/dist/extension.cjs'),
outfile: path.join('./client/dist/extension.js'),
external: ['vscode'],
format: 'cjs',
platform: 'node',
Expand Down
4 changes: 0 additions & 4 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@
"description": "VSCode part of a language server",
"license": "MIT",
"version": "0.0.1",
"type": "module",
"scripts": {
"compile-ts": "tsc"
},
"engines": {
"vscode": "^1.43.0"
}
Expand Down
127 changes: 127 additions & 0 deletions client/src/browserClientMain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
//* ⚠️ Not currently used in AHK++

/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { commands, ExtensionContext, languages, Range, RelativePattern, SnippetString, Uri, window, workspace, WorkspaceEdit } from 'vscode';
import { LanguageClient } from 'vscode-languageclient/browser';

let client: LanguageClient;

// this method is called when vs code is activated
export function activate(context: ExtensionContext) {
const serverMain = Uri.joinPath(context.extensionUri, 'server/dist/browserServerMain.js');
/* eslint-disable-next-line */
const request_handlers: Record<string, (...params: any[]) => any> = {
'ahk2.getActiveTextEditorUriAndPosition': () => {
const editor = window.activeTextEditor;
if (!editor) return;
const uri = editor.document.uri.toString(), position = editor.selection.end;
return { uri, position };
},
'ahk2.insertSnippet': async (params: [string, Range?]) => {
const editor = window.activeTextEditor;
if (!editor) return;
if (params[1]) {
const { start, end } = params[1];
await editor.insertSnippet(new SnippetString(params[0]), new Range(start.line, start.character, end.line, end.character));
} else
editor.insertSnippet(new SnippetString(params[0]));
},
'ahk2.setTextDocumentLanguage': async (params: [string, string?]) => {
const lang = params[1] || 'ahk';
if (!(await languages.getLanguages()).includes(lang)) {
window.showErrorMessage(`Unknown language id: ${lang}`);
return;
}
const uri = params[0], it = workspace.textDocuments.find(it => it.uri.toString() === uri);
it && languages.setTextDocumentLanguage(it, lang);
},
'ahk2.getWorkspaceFiles': async (params: string[]) => {
const all = !params.length;
if (workspace.workspaceFolders) {
if (all)
return (await workspace.findFiles('**/*.{ahk,ah2,ahk2}')).forEach(it => it.toString());
else {
const files: string[] = [];
for (const folder of workspace.workspaceFolders)
if (params.includes(folder.uri.toString().toLowerCase()))
files.push(...(await workspace.findFiles(new RelativePattern(folder, '*.{ahk,ah2,ahk2}'))).map(it => it.toString()));
return files;
}
}
},
'ahk2.getWorkspaceFileContent': async (params: string[]) => (await workspace.openTextDocument(Uri.parse(params[0]))).getText()
};

client = new LanguageClient('AutoHotkey2', 'AutoHotkey2', {
documentSelector: [{ language: 'ahk2' }],
markdown: { isTrusted: true, supportHtml: true },
initializationOptions: {
extensionUri: context.extensionUri.toString(),
commands: Object.keys(request_handlers),
...JSON.parse(JSON.stringify(workspace.getConfiguration('AutoHotkey2')))
}
}, new Worker(serverMain.toString()));

context.subscriptions.push(
commands.registerTextEditorCommand('ahk2.update.versioninfo', async textEditor => {
const infos: { content: string, uri: string, range: Range, single: boolean }[] | null = await client.sendRequest('ahk2.getVersionInfo', textEditor.document.uri.toString());
if (!infos?.length) {
await textEditor.insertSnippet(new SnippetString([
"/************************************************************************",
" * @description ${1:}",
" * @author ${2:}",
" * @date ${3:$CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE}",
" * @version ${4:0.0.0}",
" ***********************************************************************/",
"", ""
].join('\n')), new Range(0, 0, 0, 0));
} else {
const d = new Date;
let contents: string[] = [], value: string | undefined;
for (const info of infos) {
if (info.single)
contents.push(info.content.replace(
/(?<=^;\s*@ahk2exe-setversion\s+)(\S+|(?=[\r\n]))/i,
s => (value ||= s, '\0')));
else contents.push(info.content.replace(
/(?<=^\s*[;*]?\s*@date[:\s]\s*)(\S+|(?=[\r\n]))/im,
date => [d.getFullYear(), d.getMonth() + 1, d.getDate()].map(
n => n.toString().padStart(2, '0')).join(date.includes('.') ? '.' : '/')
).replace(/(?<=^\s*[;*]?\s*@version[:\s]\s*)(\S+|(?=[\r\n]))/im, s => (value ||= s, '\0')));
}
if (value !== undefined) {
value = await window.showInputBox({
value, prompt: 'Enter version info'
});
if (!value)
return;
contents = contents.map(s => s.replace('\0', value!));
}
const ed = new WorkspaceEdit(), uri = textEditor.document.uri;
infos.forEach(it => it.content !== (value = contents.shift()) &&
ed.replace(uri, it.range, value!));
ed.size && workspace.applyEdit(ed);
}
}),
commands.registerTextEditorCommand('ahk2.switch', textEditor => {
const doc = textEditor.document;
languages.setTextDocumentLanguage(doc, doc.languageId === 'ahk2' ? 'ahk' : 'ahk2');
}),
workspace.onDidCloseTextDocument(e => {
client.sendNotification('onDidCloseTextDocument', e.isClosed ?
{ uri: '', id: '' } : { uri: e.uri.toString(), id: e.languageId });
})
);

client.start().then(() => {
Object.entries(request_handlers).forEach(handler => client.onRequest(...handler));
});
}

export function deactivate() {
return client?.stop();
}
File renamed without changes.
Loading

0 comments on commit dbcf18a

Please sign in to comment.