snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
130
packages/apps/base-runtime/src/handlers/app/construct.ts
Normal file
130
packages/apps/base-runtime/src/handlers/app/construct.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import type { IParseAppPackageResult } from '@rocket.chat/apps/dist/server/compiler/IParseAppPackageResult';
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { sanitizeDeprecatedUsage } from '../../lib/sanitizeDeprecatedUsage';
|
||||
|
||||
/**
|
||||
* A platform-dependent `require` used to resolve the modules an app is allowed
|
||||
* to load (native `node:` modules, a small allow-list of npm packages, and
|
||||
* apps-engine files). Each runtime injects its own via {@link setSandboxRequire}
|
||||
* — Node hands over its global `require`, Deno hands over its `createRequire`
|
||||
* shim that knows how to resolve compiled apps-engine paths.
|
||||
*/
|
||||
type SandboxRequire = (module: string) => unknown;
|
||||
|
||||
function defaultSandboxRequire(): never {
|
||||
throw new Error('No sandbox require has been injected; the runtime adapter must call setSandboxRequire() during bootstrap');
|
||||
}
|
||||
|
||||
let sandboxRequire: SandboxRequire = defaultSandboxRequire;
|
||||
|
||||
export function setSandboxRequire(newRequire: SandboxRequire): void {
|
||||
sandboxRequire = newRequire;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra globals bound into the app's eval shell on top of the common ones
|
||||
* (`exports`, `module`, `require`, `console`, `globalThis`). Node needs none;
|
||||
* Deno injects a `Buffer` and shadows `Deno` with `undefined`. Injecting them
|
||||
* as data keeps the eval-shell skeleton single-source.
|
||||
*/
|
||||
type SandboxGlobals = Record<string, unknown>;
|
||||
|
||||
let sandboxGlobals: SandboxGlobals = {};
|
||||
|
||||
export function setSandboxGlobals(globals: SandboxGlobals): void {
|
||||
sandboxGlobals = globals;
|
||||
}
|
||||
|
||||
function wrapAppCode(code: string): (require: SandboxRequire) => Promise<Record<string, unknown>> {
|
||||
const globals = sandboxGlobals;
|
||||
// The common globals are bound by name; any platform-specific extras are
|
||||
// spread in by name from the injected `sandboxGlobals`, so the shell
|
||||
// skeleton stays identical across runtimes.
|
||||
const extraNames = Object.keys(globals);
|
||||
const extraParams = extraNames.length ? `,${extraNames.join(',')}` : '';
|
||||
const extraArgs = extraNames.map((name) => `,__globals[${JSON.stringify(name)}]`).join('');
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- This is the reason we run in a separate process
|
||||
const fn = new Function(
|
||||
'require',
|
||||
'__globals',
|
||||
`
|
||||
const exports = {};
|
||||
const module = { exports };
|
||||
const _error = console.error.bind(console);
|
||||
const _console = {
|
||||
log: _error,
|
||||
error: _error,
|
||||
debug: _error,
|
||||
info: _error,
|
||||
warn: _error,
|
||||
};
|
||||
|
||||
const result = (async (exports,module,require,console,globalThis${extraParams}) => {
|
||||
${code};
|
||||
})(exports,module,require,_console,undefined${extraArgs});
|
||||
|
||||
return result.then(() => module.exports);`,
|
||||
) as (require: SandboxRequire, globals: SandboxGlobals) => Promise<Record<string, unknown>>;
|
||||
|
||||
return (require: SandboxRequire) => fn(require, globals);
|
||||
}
|
||||
|
||||
type AppConstructor = new (...args: unknown[]) => App;
|
||||
|
||||
export default async function handleConstructApp(request: RequestContext): Promise<boolean> {
|
||||
const { params } = request;
|
||||
|
||||
if (!Array.isArray(params)) {
|
||||
throw new Error('Invalid params', { cause: 'invalid_param_type' });
|
||||
}
|
||||
|
||||
const [appPackage] = params as [IParseAppPackageResult];
|
||||
|
||||
if (!appPackage?.info?.id || !appPackage?.info?.classFile || !appPackage?.files) {
|
||||
throw new Error('Invalid params', { cause: 'invalid_param_type' });
|
||||
}
|
||||
|
||||
AppObjectRegistry.set('id', appPackage.info.id);
|
||||
const source = sanitizeDeprecatedUsage(appPackage.files[appPackage.info.classFile]);
|
||||
|
||||
const exports = await wrapAppCode(source)(sandboxRequire);
|
||||
|
||||
// This is the same naive logic we've been using in the App Compiler
|
||||
// Applying the correct type here is quite difficult because of the dynamic nature of the code
|
||||
const appClass = Object.values(exports)[0] as AppConstructor;
|
||||
|
||||
const app = new appClass(appPackage.info, request.context.logger, AppAccessorsInstance.getDefaultAppAccessors());
|
||||
|
||||
if (typeof app.getName !== 'function') {
|
||||
throw new Error('App must contain a getName function');
|
||||
}
|
||||
|
||||
if (typeof app.getNameSlug !== 'function') {
|
||||
throw new Error('App must contain a getNameSlug function');
|
||||
}
|
||||
|
||||
if (typeof app.getVersion !== 'function') {
|
||||
throw new Error('App must contain a getVersion function');
|
||||
}
|
||||
|
||||
if (typeof app.getID !== 'function') {
|
||||
throw new Error('App must contain a getID function');
|
||||
}
|
||||
|
||||
if (typeof app.getDescription !== 'function') {
|
||||
throw new Error('App must contain a getDescription function');
|
||||
}
|
||||
|
||||
if (typeof app.getRequiredApiVersion !== 'function') {
|
||||
throw new Error('App must contain a getRequiredApiVersion function');
|
||||
}
|
||||
|
||||
AppObjectRegistry.set('app', app);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
import type { AppStatus } from '@rocket.chat/apps-engine/definition/AppStatus';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
|
||||
export default function handleGetStatus(): Promise<AppStatus> {
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.getStatus !== 'function') {
|
||||
throw new Error('App must contain a getStatus function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
return app.getStatus();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default async function handleInitialize(request: RequestContext): Promise<boolean> {
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.initialize !== 'function') {
|
||||
throw new Error('App must contain an initialize function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
await app.initialize.call(
|
||||
wrapAppForRequest(app, request),
|
||||
AppAccessorsInstance.getConfigurationExtend(),
|
||||
AppAccessorsInstance.getEnvironmentRead(),
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default async function handleOnDisable(request: RequestContext): Promise<boolean> {
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.onDisable !== 'function') {
|
||||
throw new Error('App must contain an onDisable function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
await app.onDisable.call(wrapAppForRequest(app, request), AppAccessorsInstance.getConfigurationModify());
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default function handleOnEnable(request: RequestContext): Promise<boolean> {
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.onEnable !== 'function') {
|
||||
throw new Error('App must contain an onEnable function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
return app.onEnable.call(
|
||||
wrapAppForRequest(app, request),
|
||||
AppAccessorsInstance.getEnvironmentRead(),
|
||||
AppAccessorsInstance.getConfigurationModify(),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default async function handleOnInstall(request: RequestContext): Promise<boolean> {
|
||||
const { params } = request;
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.onInstall !== 'function') {
|
||||
throw new Error('App must contain an onInstall function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
if (!Array.isArray(params)) {
|
||||
throw new Error('Invalid params', { cause: 'invalid_param_type' });
|
||||
}
|
||||
|
||||
const [context] = params as [Record<string, unknown>];
|
||||
|
||||
await app.onInstall.call(
|
||||
wrapAppForRequest(app, request),
|
||||
context,
|
||||
AppAccessorsInstance.getReader(),
|
||||
AppAccessorsInstance.getHttp(),
|
||||
AppAccessorsInstance.getPersistence(),
|
||||
AppAccessorsInstance.getModifier(),
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default function handleOnPreSettingUpdate(request: RequestContext): Promise<object> {
|
||||
const { params } = request;
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.onPreSettingUpdate !== 'function') {
|
||||
throw new Error('App must contain an onPreSettingUpdate function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
if (!Array.isArray(params)) {
|
||||
throw new Error('Invalid params', { cause: 'invalid_param_type' });
|
||||
}
|
||||
|
||||
const [setting] = params as [Record<string, unknown>];
|
||||
|
||||
return app.onPreSettingUpdate.call(
|
||||
wrapAppForRequest(app, request),
|
||||
setting,
|
||||
AppAccessorsInstance.getConfigurationModify(),
|
||||
AppAccessorsInstance.getReader(),
|
||||
AppAccessorsInstance.getHttp(),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default async function handleOnSettingUpdated(request: RequestContext): Promise<boolean> {
|
||||
const { params } = request;
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.onSettingUpdated !== 'function') {
|
||||
throw new Error('App must contain an onSettingUpdated function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
if (!Array.isArray(params)) {
|
||||
throw new Error('Invalid params', { cause: 'invalid_param_type' });
|
||||
}
|
||||
|
||||
const [setting] = params as [Record<string, unknown>];
|
||||
|
||||
await app.onSettingUpdated.call(
|
||||
wrapAppForRequest(app, request),
|
||||
setting,
|
||||
AppAccessorsInstance.getConfigurationModify(),
|
||||
AppAccessorsInstance.getReader(),
|
||||
AppAccessorsInstance.getHttp(),
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default async function handleOnUninstall(request: RequestContext): Promise<boolean> {
|
||||
const { params } = request;
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.onUninstall !== 'function') {
|
||||
throw new Error('App must contain an onUninstall function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
if (!Array.isArray(params)) {
|
||||
throw new Error('Invalid params', { cause: 'invalid_param_type' });
|
||||
}
|
||||
|
||||
const [context] = params as [Record<string, unknown>];
|
||||
|
||||
await app.onUninstall.call(
|
||||
wrapAppForRequest(app, request),
|
||||
context,
|
||||
AppAccessorsInstance.getReader(),
|
||||
AppAccessorsInstance.getHttp(),
|
||||
AppAccessorsInstance.getPersistence(),
|
||||
AppAccessorsInstance.getModifier(),
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default async function handleOnUpdate(request: RequestContext): Promise<boolean> {
|
||||
const { params } = request;
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (typeof app?.onUpdate !== 'function') {
|
||||
throw new Error('App must contain an onUpdate function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
if (!Array.isArray(params)) {
|
||||
throw new Error('Invalid params', { cause: 'invalid_param_type' });
|
||||
}
|
||||
|
||||
const [context] = params as [Record<string, unknown>];
|
||||
|
||||
await app.onUpdate.call(
|
||||
wrapAppForRequest(app, request),
|
||||
context,
|
||||
AppAccessorsInstance.getReader(),
|
||||
AppAccessorsInstance.getHttp(),
|
||||
AppAccessorsInstance.getPersistence(),
|
||||
AppAccessorsInstance.getModifier(),
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
import { AppStatus } from '@rocket.chat/apps-engine/definition/AppStatus';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
|
||||
export default async function handleSetStatus(request: RequestContext): Promise<null> {
|
||||
const { params } = request;
|
||||
|
||||
if (!Array.isArray(params) || !Object.values(AppStatus).includes(params[0])) {
|
||||
throw new Error('Invalid params', { cause: 'invalid_param_type' });
|
||||
}
|
||||
|
||||
const [status] = params as [typeof AppStatus];
|
||||
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
|
||||
if (!app || typeof (app as unknown as Record<string, unknown>).setStatus !== 'function') {
|
||||
throw new Error('App must contain a setStatus function', {
|
||||
cause: 'invalid_app',
|
||||
});
|
||||
}
|
||||
|
||||
await (app as unknown as { setStatus(status: typeof AppStatus): Promise<void> }).setStatus.call(wrapAppForRequest(app, request), status);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Buffer } from 'node:buffer';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
import type { App } from '@rocket.chat/apps-engine/definition/App';
|
||||
import { AppsEngineException } from '@rocket.chat/apps-engine/definition/exceptions/AppsEngineException';
|
||||
import type { IFileUploadContext } from '@rocket.chat/apps-engine/definition/uploads/IFileUploadContext';
|
||||
import type { IUploadDetails } from '@rocket.chat/apps-engine/definition/uploads/IUploadDetails';
|
||||
import type { Defined } from 'jsonrpc-lite';
|
||||
import { JsonRpcError } from 'jsonrpc-lite';
|
||||
|
||||
import { AppObjectRegistry } from '../../AppObjectRegistry';
|
||||
import { AppAccessorsInstance } from '../../lib/accessors/mod';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { wrapAppForRequest } from '../../lib/wrapAppForRequest';
|
||||
import { assertAppAvailable, assertHandlerFunction, isPlainObject } from '../lib/assertions';
|
||||
|
||||
export const uploadEvents = ['executePreFileUpload'] as const;
|
||||
|
||||
function assertIsUpload(v: unknown): asserts v is IUploadDetails {
|
||||
if (isPlainObject(v) && !!v.rid && (!!v.userId || !!v.visitorToken)) return;
|
||||
|
||||
throw JsonRpcError.invalidParams({ err: `Invalid 'file' parameter. Expected IUploadDetails, got`, value: v });
|
||||
}
|
||||
|
||||
function assertString(v: unknown): asserts v is string {
|
||||
if (v && typeof v === 'string') return;
|
||||
|
||||
throw JsonRpcError.invalidParams({ err: `Invalid 'path' parameter. Expected string, got`, value: v });
|
||||
}
|
||||
|
||||
export default async function handleUploadEvents(request: RequestContext): Promise<Defined | JsonRpcError> {
|
||||
const { method: rawMethod, params } = request as {
|
||||
method: `app:${(typeof uploadEvents)[number]}`;
|
||||
params: [{ file?: IUploadDetails; path?: string }];
|
||||
};
|
||||
const [, method] = rawMethod.split(':') as ['app', (typeof uploadEvents)[number]];
|
||||
|
||||
try {
|
||||
const [{ file, path }] = params;
|
||||
|
||||
const app = AppObjectRegistry.get<App>('app');
|
||||
const handlerFunction = app?.[method as keyof App] as unknown;
|
||||
|
||||
assertAppAvailable(app);
|
||||
assertHandlerFunction(handlerFunction);
|
||||
assertIsUpload(file);
|
||||
assertString(path);
|
||||
|
||||
let context: IFileUploadContext;
|
||||
|
||||
switch (method) {
|
||||
case 'executePreFileUpload': {
|
||||
const fileContents = await readFile(path);
|
||||
context = { file, content: Buffer.from(fileContents) };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return await handlerFunction.call(
|
||||
wrapAppForRequest(app, request),
|
||||
context,
|
||||
AppAccessorsInstance.getReader(),
|
||||
AppAccessorsInstance.getHttp(),
|
||||
AppAccessorsInstance.getPersistence(),
|
||||
AppAccessorsInstance.getModifier(),
|
||||
);
|
||||
} catch (e) {
|
||||
if (e?.name === AppsEngineException.name) {
|
||||
return new JsonRpcError(e.message, AppsEngineException.JSONRPC_ERROR_CODE, { name: e.name });
|
||||
}
|
||||
|
||||
if (e instanceof JsonRpcError) {
|
||||
return e;
|
||||
}
|
||||
|
||||
return JsonRpcError.internalError({
|
||||
err: e.message,
|
||||
...(e.code && { code: e.code }),
|
||||
});
|
||||
}
|
||||
}
|
||||
116
packages/apps/base-runtime/src/handlers/app/handler.ts
Normal file
116
packages/apps/base-runtime/src/handlers/app/handler.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import type { Defined } from 'jsonrpc-lite';
|
||||
import { JsonRpcError } from 'jsonrpc-lite';
|
||||
|
||||
import handleConstructApp from './construct';
|
||||
import handleGetStatus from './handleGetStatus';
|
||||
import handleInitialize from './handleInitialize';
|
||||
import handleOnDisable from './handleOnDisable';
|
||||
import handleOnEnable from './handleOnEnable';
|
||||
import handleOnInstall from './handleOnInstall';
|
||||
import handleOnPreSettingUpdate from './handleOnPreSettingUpdate';
|
||||
import handleOnSettingUpdated from './handleOnSettingUpdated';
|
||||
import handleOnUninstall from './handleOnUninstall';
|
||||
import handleOnUpdate from './handleOnUpdate';
|
||||
import handleSetStatus from './handleSetStatus';
|
||||
import handleUploadEvents, { uploadEvents } from './handleUploadEvents';
|
||||
import type { RequestContext } from '../../lib/requestContext';
|
||||
import { isOneOf } from '../lib/assertions';
|
||||
import handleListener from '../listener/handler';
|
||||
import handleUIKitInteraction, { uikitInteractions } from '../uikit/handler';
|
||||
|
||||
export default async function handleApp(request: RequestContext): Promise<Defined | JsonRpcError> {
|
||||
const { method } = request;
|
||||
const { logger } = request.context;
|
||||
const [, appMethod] = method.split(':');
|
||||
|
||||
try {
|
||||
// We don't want the getStatus method to generate logs, so we handle it separately
|
||||
if (appMethod === 'getStatus') {
|
||||
return await handleGetStatus();
|
||||
}
|
||||
|
||||
logger.debug({ msg: `A method is being called...`, appMethod });
|
||||
|
||||
const formatResult = (result: Defined | JsonRpcError): Defined | JsonRpcError => {
|
||||
if (result instanceof JsonRpcError) {
|
||||
logger.debug({
|
||||
msg: `'${appMethod}' was unsuccessful.`,
|
||||
appMethod,
|
||||
err: result,
|
||||
errorMessage: result.message,
|
||||
});
|
||||
} else {
|
||||
logger.debug({
|
||||
msg: `'${appMethod}' was successfully called! The result is:`,
|
||||
appMethod,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
let result: Promise<Defined | JsonRpcError> | undefined = undefined;
|
||||
|
||||
if (isOneOf(appMethod, uploadEvents)) {
|
||||
result = handleUploadEvents(request);
|
||||
} else if (isOneOf(appMethod, uikitInteractions)) {
|
||||
result = handleUIKitInteraction(request);
|
||||
} else if (appMethod.startsWith('check') || appMethod.startsWith('execute')) {
|
||||
result = handleListener(request);
|
||||
}
|
||||
|
||||
switch (appMethod) {
|
||||
case 'construct':
|
||||
result = handleConstructApp(request);
|
||||
break;
|
||||
case 'initialize':
|
||||
result = handleInitialize(request);
|
||||
break;
|
||||
case 'setStatus':
|
||||
result = handleSetStatus(request);
|
||||
break;
|
||||
case 'onEnable':
|
||||
result = handleOnEnable(request);
|
||||
break;
|
||||
case 'onDisable':
|
||||
result = handleOnDisable(request);
|
||||
break;
|
||||
case 'onInstall':
|
||||
result = handleOnInstall(request);
|
||||
break;
|
||||
case 'onUninstall':
|
||||
result = handleOnUninstall(request);
|
||||
break;
|
||||
case 'onPreSettingUpdate':
|
||||
result = handleOnPreSettingUpdate(request);
|
||||
break;
|
||||
case 'onSettingUpdated':
|
||||
result = handleOnSettingUpdated(request);
|
||||
break;
|
||||
case 'onUpdate':
|
||||
result = handleOnUpdate(request);
|
||||
break;
|
||||
}
|
||||
|
||||
if (typeof result === 'undefined') {
|
||||
throw new JsonRpcError(`Unknown method "${appMethod}"`, -32601);
|
||||
}
|
||||
|
||||
return await result.then(formatResult);
|
||||
} catch (e: unknown) {
|
||||
if (!(e instanceof Error)) {
|
||||
return new JsonRpcError('Unknown error', -32000, e);
|
||||
}
|
||||
|
||||
if ((e.cause as string)?.includes('invalid_param_type')) {
|
||||
return JsonRpcError.invalidParams(null);
|
||||
}
|
||||
|
||||
if ((e.cause as string)?.includes('invalid_app')) {
|
||||
return JsonRpcError.internalError({ message: 'App unavailable' });
|
||||
}
|
||||
|
||||
return new JsonRpcError(e.message, -32000, e);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user