Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create mocks to call accessors from Deno #670

Merged
merged 6 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions deno-runtime/deno.jsonc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"imports": {
"@rocket.chat/apps-engine/": "./../src/",
"acorn": "npm:[email protected]",
"acorn-walk": "npm:[email protected]",
"astring": "npm:[email protected]"
Expand Down
80 changes: 80 additions & 0 deletions deno-runtime/lib/accessors/_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { beforeEach, describe, it } from 'https://deno.land/[email protected]/testing/bdd.ts';
import { assertEquals } from "https://deno.land/[email protected]/assert/assert_equals.ts";

import { AppAccessors, getProxify } from "./mod.ts";

describe('AppAccessors', () => {
let appAccessors: AppAccessors;
const proxify = getProxify((r) => Promise.resolve({
id: Math.random().toString(36).substring(2),
jsonrpc: '2.0',
result: r,
serialize() {
return JSON.stringify(this);
}
}));

beforeEach(() => {
appAccessors = new AppAccessors(proxify);
});

it('creates the correct format for IRead calls', async () => {
const roomRead = appAccessors.getReader().getRoomReader();
const room = await roomRead.getById('123');

assertEquals(room.result, {
params: ['123'],
method: 'accessor:getReader:getRoomReader:getById',
});
});

it('creates the correct format for IEnvironmentRead calls from IRead', async () => {
const reader = appAccessors.getReader().getEnvironmentReader().getEnvironmentVariables();
const room = await reader.getValueByName('NODE_ENV');

assertEquals(room.result, {
params: ['NODE_ENV'],
method: 'accessor:getReader:getEnvironmentReader:getEnvironmentVariables:getValueByName',
});
});

it('creates the correct format for IEvironmentRead calls', async () => {
const envRead = appAccessors.getEnvironmentRead();
const env = await envRead.getServerSettings().getValueById('123');

assertEquals(env.result, {
params: ['123'],
method: 'accessor:getEnvironmentRead:getServerSettings:getValueById',
});
});

it('creates the correct format for IEvironmentWrite calls', async () => {
const envRead = appAccessors.getEnvironmentWrite();
const env = await envRead.getServerSettings().incrementValue('123', 6);

assertEquals(env.result, {
params: ['123', 6],
method: 'accessor:getEnvironmentWrite:getServerSettings:incrementValue',
});
});

it('creates the correct format for IConfigurationModify calls', async () => {
const configModify = appAccessors.getConfigurationModify();
const command = await configModify.slashCommands.modifySlashCommand({
command: 'test',
i18nDescription: 'test',
i18nParamsExample: 'test',
providesPreview: true,
});

assertEquals(command.result, {
params: [{
command: 'test',
i18nDescription: 'test',
i18nParamsExample: 'test',
providesPreview: true,
}],
method: 'accessor:getConfigurationModify:slashCommands:modifySlashCommand',
});
});
});
170 changes: 164 additions & 6 deletions deno-runtime/lib/accessors/mod.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,169 @@
// @ts-ignore - this is a hack to make the tests work
import type { IAppAccessors } from '@rocket.chat/apps-engine/definition/accessors/IAppAccessors.ts';
import type { IEnvironmentWrite } from '@rocket.chat/apps-engine/definition/accessors/IEnvironmentWrite.ts';
import type { IEnvironmentRead } from '@rocket.chat/apps-engine/definition/accessors/IEnvironmentRead.ts';
import type { IConfigurationModify } from '@rocket.chat/apps-engine/definition/accessors/IConfigurationModify.ts';
import type { IRead } from '@rocket.chat/apps-engine/definition/accessors/IRead.ts';
import type { IModify } from '@rocket.chat/apps-engine/definition/accessors/IModify.ts';
import type { IPersistence } from '@rocket.chat/apps-engine/definition/accessors/IPersistence.ts';
import type { IHttp } from '@rocket.chat/apps-engine/definition/accessors/IHttp.ts';
import type { IConfigurationExtend } from '@rocket.chat/apps-engine/definition/accessors/IConfigurationExtend.ts';

export function proxify(namespace: string) {
return new Proxy({}, {
get(target: unknown, prop: string): unknown {
return (...args: unknown[]) => {
return {};
import * as Messenger from '../messenger.ts';

export const getProxify = (call: typeof Messenger.sendRequest) => function proxify<T>(namespace: string): T {
return new Proxy(
{ __kind: namespace }, // debugging purposes
{
get:
(_target: unknown, prop: string) =>
(...params: unknown[]) =>
call({
method: `accessor:${namespace}:${prop}`,
params,
}),
},
) as T;
}

export class AppAccessors {
private defaultAppAccessors?: IAppAccessors;
private environmentRead?: IEnvironmentRead;
private environmentWriter?: IEnvironmentWrite;
private configModifier?: IConfigurationModify;
private configExtender?: IConfigurationExtend;
private reader?: IRead;
private modifier?: IModify;
private persistence?: IPersistence;
private http?: IHttp;

constructor(private readonly proxify: <T>(n: string) => T) {}

public getEnvironmentRead(): IEnvironmentRead {
if (!this.environmentRead) {
this.environmentRead = {
getSettings: () => this.proxify('getEnvironmentRead:getSettings'),
getServerSettings: () => this.proxify('getEnvironmentRead:getServerSettings'),
getEnvironmentVariables: () => this.proxify('getEnvironmentRead:getEnvironmentVariables'),
};
}

return this.environmentRead;
}

public getEnvironmentWrite() {
if (!this.environmentWriter) {
this.environmentWriter = {
getSettings: () => this.proxify('getEnvironmentWrite:getSettings'),
getServerSettings: () => this.proxify('getEnvironmentWrite:getServerSettings'),
};
}

return this.environmentWriter;
}

public getConfigurationModify() {
if (!this.configModifier) {
this.configModifier = {
scheduler: this.proxify('getConfigurationModify:scheduler'),
slashCommands: this.proxify('getConfigurationModify:slashCommands'),
serverSettings: this.proxify('getConfigurationModify:serverSettings'),
};
}

return this.configModifier;
}

public getConifgurationExtend() {
if (!this.configExtender) {
this.configExtender = {
ui: this.proxify('getConfigurationExtend:ui'),
api: this.proxify('getConfigurationExtend:api'),
http: this.proxify('getConfigurationExtend:http'),
settings: this.proxify('getConfigurationExtend:settings'),
scheduler: this.proxify('getConfigurationExtend:scheduler'),
slashCommands: this.proxify('getConfigurationExtend:slashCommands'),
externalComponents: this.proxify('getConfigurationExtend:externalComponents'),
videoConfProviders: this.proxify('getConfigurationExtend:videoConfProviders'),
}
}

return this.configExtender;
}

public getDefaultAppAccessors() {
if (!this.defaultAppAccessors) {
this.defaultAppAccessors = {
environmentReader: this.getEnvironmentRead(),
environmentWriter: this.getEnvironmentWrite(),
reader: this.getReader(),
http: this.getHttp(),
providedApiEndpoints: this.proxify('providedApiEndpoints'),
};
}
})

return this.defaultAppAccessors;
}

public getReader() {
if (!this.reader) {
this.reader = {
getEnvironmentReader: () => ({
getSettings: () => this.proxify('getReader:getEnvironmentReader:getSettings'),
getServerSettings: () => this.proxify('getReader:getEnvironmentReader:getServerSettings'),
getEnvironmentVariables: () => this.proxify('getReader:getEnvironmentReader:getEnvironmentVariables'),
}),
getMessageReader: () => this.proxify('getReader:getMessageReader'),
getPersistenceReader: () => this.proxify('getReader:getPersistenceReader'),
getRoomReader: () => this.proxify('getReader:getRoomReader'),
getUserReader: () => this.proxify('getReader:getUserReader'),
getNotifier: () => this.proxify('getReader:getNotifier'),
getLivechatReader: () => this.proxify('getReader:getLivechatReader'),
getUploadReader: () => this.proxify('getReader:getUploadReader'),
getCloudWorkspaceReader: () => this.proxify('getReader:getCloudWorkspaceReader'),
getVideoConferenceReader: () => this.proxify('getReader:getVideoConferenceReader'),
getOAuthAppsReader: () => this.proxify('getReader:getOAuthAppsReader'),
getThreadReader: () => this.proxify('getReader:getThreadReader'),
getRoleReader: () => this.proxify('getReader:getRoleReader'),
};
}

return this.reader;
}

public getModifier() {
if (!this.modifier) {
this.modifier = {
getCreator: () => this.proxify('getModifier:getCreator'), // can't be proxy
getUpdater: () => this.proxify('getModifier:getUpdater'), // can't be proxy
getDeleter: () => this.proxify('getModifier:getDeleter'),
getExtender: () => this.proxify('getModifier:getExtender'), // can't be proxy
getNotifier: () => this.proxify('getModifier:getNotifier'),
getUiController: () => this.proxify('getModifier:getUiController'),
getScheduler: () => this.proxify('getModifier:getScheduler'),
getOAuthAppsModifier: () => this.proxify('getModifier:getOAuthAppsModifier'),
getModerationModifier: () => this.proxify('getModifier:getModerationModifier'),
}
}

return this.modifier;
}

public getPersistence() {
if (!this.persistence) {
this.persistence = this.proxify('getPersistence');
}

return this.persistence;
}

public getHttp() {
if (!this.http) {
this.http = this.proxify('getHttp');
}

return this.http;
}
}

export const AppAccessorsInstance = new AppAccessors(getProxify(Messenger.sendRequest.bind(Messenger)));
2 changes: 1 addition & 1 deletion deno-runtime/lib/ast/tests/operations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
SimpleCallExpressionOfFoo,
SyncFunctionDeclarationWithAsyncCallExpression,
} from './data/ast_blocks.ts';
import { AnyNode, ArrowFunctionExpression, AssignmentExpression, AwaitExpression, CallExpression, Expression, MethodDefinition, ReturnStatement, VariableDeclaration } from '../../../acorn.d.ts';
import { AnyNode, ArrowFunctionExpression, AssignmentExpression, AwaitExpression, Expression, MethodDefinition, ReturnStatement, VariableDeclaration } from '../../../acorn.d.ts';
import { assertNotEquals } from 'https://deno.land/[email protected]/assert/assert_not_equals.ts';

describe('getFunctionIdentifier', () => {
Expand Down
4 changes: 2 additions & 2 deletions deno-runtime/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ if (!Deno.args.includes('--subprocess')) {

import { createRequire } from 'node:module';
import { sanitizeDeprecatedUsage } from "./lib/sanitizeDeprecatedUsage.ts";
import { proxify } from "./lib/accessors/mod.ts";
import { AppAccessorsInstance } from "./lib/accessors/mod.ts";
import * as Messenger from "./lib/messenger.ts";

const require = createRequire(import.meta.url);
Expand Down Expand Up @@ -59,7 +59,7 @@ async function handlInitializeApp({ id, source }: { id: string; source: string }
const exports = await wrapAppCode(source)(require);
// This is the same naive logic we've been using in the App Compiler
const appClass = Object.values(exports)[0] as typeof App;
const app = new appClass({ author: {} }, proxify('logger'), proxify('AppAccessors'));
const app = new appClass({ author: {} }, proxify('logger'), AppAccessorsInstance.getDefaultAppAccessors());

if (typeof app.getName !== 'function') {
throw new Error('App must contain a getName function');
Expand Down
Loading