Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@based/server

Package Overview
Dependencies
Maintainers
7
Versions
112
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@based/server - npm Package Compare versions

Comparing version 6.9.0 to 7.0.1

dist/incoming/http/handleRequest.d.ts

1

dist/auth/defaultConfig.d.ts
import { Authorize, VerifyAuthState } from '@based/functions';
export declare const defaultAuthorize: Authorize;
export declare const defaultVerifyAuthState: VerifyAuthState;
//# sourceMappingURL=defaultConfig.d.ts.map

@@ -1,11 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultVerifyAuthState = exports.defaultAuthorize = void 0;
const utils_1 = require("@saulx/utils");
const defaultAuthorize = async () => {
import { deepEqual } from '@saulx/utils';
export const defaultAuthorize = async () => {
return true;
};
exports.defaultAuthorize = defaultAuthorize;
const defaultVerifyAuthState = async (based, ctx, authState) => {
if (ctx.session && !(0, utils_1.deepEqual)(authState, ctx.session.authState)) {
export const defaultVerifyAuthState = async (_, ctx, authState) => {
if (ctx.session && !deepEqual(authState, ctx.session.authState)) {
return authState;

@@ -15,3 +11,2 @@ }

};
exports.defaultVerifyAuthState = defaultVerifyAuthState;
//# sourceMappingURL=defaultConfig.js.map

@@ -1,5 +0,5 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { Context, AuthState, WebSocketSession, Authorize, AuthorizeConnection, VerifyAuthState } from '@based/functions';
import parseAuthState from './parseAuthState';
import parseJSONAuthState from './parseJSONAuthState';
import parseAuthState from './parseAuthState.js';
import parseJSONAuthState from './parseJSONAuthState.js';
export { parseAuthState };

@@ -34,2 +34,1 @@ export { parseJSONAuthState };

}
//# sourceMappingURL=index.d.ts.map

@@ -1,20 +0,16 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasedAuth = exports.parseJSONAuthState = exports.parseAuthState = void 0;
const protocol_1 = require("../protocol");
const functions_1 = require("@based/functions");
const defaultConfig_1 = require("./defaultConfig");
const parseAuthState_1 = __importDefault(require("./parseAuthState"));
exports.parseAuthState = parseAuthState_1.default;
const parseJSONAuthState_1 = __importDefault(require("./parseJSONAuthState"));
exports.parseJSONAuthState = parseJSONAuthState_1.default;
const auth_1 = require("../incoming/ws/auth");
const utils_1 = require("@saulx/utils");
class BasedAuth {
import { encodeAuthResponse, valueToBuffer } from '../protocol.js';
import { isWsContext, } from '@based/functions';
import { defaultAuthorize, defaultVerifyAuthState } from './defaultConfig.js';
import parseAuthState from './parseAuthState.js';
import parseJSONAuthState from './parseJSONAuthState.js';
import { reEvaulateUnauthorized } from '../incoming/ws/auth.js';
import { deepEqual } from '@saulx/utils';
export { parseAuthState };
export { parseJSONAuthState };
export class BasedAuth {
server;
authorizeConnection;
verifyAuthState = defaultVerifyAuthState;
authorize = defaultAuthorize;
constructor(server, config = {}) {
this.verifyAuthState = defaultConfig_1.defaultVerifyAuthState;
this.authorize = defaultConfig_1.defaultAuthorize;
this.server = server;

@@ -51,9 +47,11 @@ this.updateConfig(config);

}
if (typeof ctx.session.authState === 'object' && typeof verified === 'object' && (0, utils_1.deepEqual)(ctx.session.authState, verified)) {
if (typeof ctx.session.authState === 'object' &&
typeof verified === 'object' &&
deepEqual(ctx.session.authState, verified)) {
return;
}
ctx.session.authState = verified;
if ((0, functions_1.isWsContext)(ctx)) {
if (isWsContext(ctx)) {
if (verified.token) {
(0, auth_1.reEvaulateUnauthorized)(this.server, ctx);
reEvaulateUnauthorized(this.server, ctx);
}

@@ -68,10 +66,9 @@ this.sendAuthState(ctx, verified);

decodeAuthState(authState) {
return (0, parseAuthState_1.default)(authState);
return parseAuthState(authState);
}
/** Sets the `authState` on the client. */
sendAuthState(ctx, authState) {
ctx.session?.ws.send((0, protocol_1.encodeAuthResponse)((0, protocol_1.valueToBuffer)(authState)), true, false);
ctx.session?.ws.send(encodeAuthResponse(valueToBuffer(authState)), true, false);
}
}
exports.BasedAuth = BasedAuth;
//# sourceMappingURL=index.js.map
import { AuthState } from '@based/functions';
declare const _default: (authState: any) => AuthState;
export default _default;
//# sourceMappingURL=parseAuthState.d.ts.map

@@ -1,5 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@saulx/utils");
const { decode } = (0, utils_1.createEncoder)([
import { createEncoder } from '@saulx/utils';
const { decode } = createEncoder([
'(',

@@ -24,3 +22,3 @@ ')',

], ['0']);
exports.default = (authState) => {
export default (authState) => {
if (authState === undefined) {

@@ -27,0 +25,0 @@ return {};

import { AuthState } from '@based/functions';
declare const _default: (authorization: string) => AuthState;
export default _default;
//# sourceMappingURL=parseJSONAuthState.d.ts.map

@@ -1,4 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (authorization) => {
export default (authorization) => {
try {

@@ -5,0 +3,0 @@ const authState = JSON.parse(decodeURIComponent(authorization));

@@ -1,2 +0,2 @@

import { BasedServer } from './server';
import { BasedServer } from './server.js';
import { HttpSession, Context, WebSocketSession, BasedRoute, BasedFunctionConfig } from '@based/functions';

@@ -7,4 +7,3 @@ type ClientSession = HttpSession | WebSocketSession;

export declare const defaultAuthError: AuthErrorHandler;
export declare const authorize: <S extends ClientSession = ClientSession, R extends BasedRoute<import("@based/functions").BasedFunctionTypes, "name" | "type"> = BasedRoute<import("@based/functions").BasedFunctionTypes, "name" | "type">, P = any>(route: R, server: BasedServer, ctx: Context<S>, payload: P, isAuthorized: IsAuthorizedHandler<S, R, P>, id?: number, checksum?: number, isPublic?: boolean, authError?: AuthErrorHandler<S, R, P>) => void;
export declare const authorize: <S extends ClientSession = ClientSession, R extends BasedRoute = BasedRoute, P = any>(route: R, server: BasedServer, ctx: Context<S>, payload: P, isAuthorized: IsAuthorizedHandler<S, R, P>, id?: number, checksum?: number, isPublic?: boolean, authError?: AuthErrorHandler<S, R, P>) => void;
export {};
//# sourceMappingURL=authorize.d.ts.map

@@ -1,14 +0,11 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.authorize = exports.defaultAuthError = void 0;
const sendError_1 = require("./sendError");
const error_1 = require("./error");
const functions_1 = require("@based/functions");
const installFn_1 = require("./installFn");
const defaultAuthError = (route, server, ctx, payload, id, checksum, err) => {
import { sendError } from './sendError.js';
import { BasedErrorCode } from './error/index.js';
import { isBasedRoute, } from '@based/functions';
import { installFn } from './installFn.js';
export const defaultAuthError = (route, server, ctx, _payload, id, _checksum, err) => {
const code = err
? error_1.BasedErrorCode.AuthorizeFunctionError
: error_1.BasedErrorCode.AuthorizeRejectedError;
if (id && (0, functions_1.isBasedRoute)('channel', route)) {
(0, sendError_1.sendError)(server, ctx, code, {
? BasedErrorCode.AuthorizeFunctionError
: BasedErrorCode.AuthorizeRejectedError;
if (id && isBasedRoute('channel', route)) {
sendError(server, ctx, code, {
route,

@@ -20,4 +17,4 @@ err,

}
if (id && (0, functions_1.isBasedRoute)('query', route)) {
(0, sendError_1.sendError)(server, ctx, code, {
if (id && isBasedRoute('query', route)) {
sendError(server, ctx, code, {
route,

@@ -30,3 +27,3 @@ err,

if (id) {
(0, sendError_1.sendError)(server, ctx, code, {
sendError(server, ctx, code, {
route,

@@ -38,3 +35,3 @@ err,

}
(0, sendError_1.sendError)(server, ctx, code, {
sendError(server, ctx, code, {
route,

@@ -44,8 +41,7 @@ err,

};
exports.defaultAuthError = defaultAuthError;
const authorize = (route, server, ctx, payload, isAuthorized, id, checksum, isPublic = false, authError = exports.defaultAuthError) => {
export const authorize = (route, server, ctx, payload, isAuthorized, id, checksum, isPublic = false, authError = defaultAuthError) => {
if (!ctx.session) {
return;
}
(0, installFn_1.installFn)(server, ctx, route, id).then((spec) => {
installFn(server, ctx, route, id).then((spec) => {
if (spec === null) {

@@ -64,3 +60,3 @@ return;

!authError(route, server, ctx, payload, id, checksum)) {
(0, exports.defaultAuthError)(route, server, ctx, payload, id, checksum);
defaultAuthError(route, server, ctx, payload, id, checksum);
}

@@ -74,3 +70,3 @@ return;

!authError(route, server, ctx, payload, id, checksum, err)) {
(0, exports.defaultAuthError)(route, server, ctx, payload, id, checksum, err);
defaultAuthError(route, server, ctx, payload, id, checksum, err);
}

@@ -80,3 +76,2 @@ });

};
exports.authorize = authorize;
//# sourceMappingURL=authorize.js.map

@@ -1,3 +0,2 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
export declare const cleanUpChannels: (server: BasedServer) => void;
//# sourceMappingURL=cleanup.d.ts.map

@@ -1,4 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanUpChannels = void 0;
const destroyChannel = (server, channel) => {

@@ -23,3 +20,3 @@ const id = channel.id;

};
const cleanUpChannels = (server) => {
export const cleanUpChannels = (server) => {
if (!server.channelCleanTimeout) {

@@ -48,3 +45,3 @@ const cycleTime = Math.max(server.channelCleanupCycle, 500);

server.channelCleanupCycle = Math.round(shortestCycleTime / 2);
(0, exports.cleanUpChannels)(server);
cleanUpChannels(server);
}

@@ -54,3 +51,2 @@ }, cycleTime);

};
exports.cleanUpChannels = cleanUpChannels;
//# sourceMappingURL=cleanup.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../server';
import { ActiveChannel } from './types';
import { BasedServer } from '../server.js';
import { ActiveChannel } from './types.js';
export declare const createChannel: (server: BasedServer, name: string, id: number, payload: any, noStart?: boolean) => ActiveChannel;
//# sourceMappingURL=create.d.ts.map

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createChannel = void 0;
const start_1 = require("./start");
const get_1 = require("./get");
const createChannel = (server, name, id, payload, noStart) => {
if ((0, get_1.hasChannel)(server, id)) {
import { startChannel } from './start.js';
import { hasChannel } from './get.js';
export const createChannel = (server, name, id, payload, noStart) => {
if (hasChannel(server, id)) {
const msg = `Allready has channel ${name} ${id}`;

@@ -28,7 +25,6 @@ console.error(msg);

if (!noStart) {
(0, start_1.startChannel)(server, id);
startChannel(server, id);
}
return channel;
};
exports.createChannel = createChannel;
//# sourceMappingURL=create.js.map

@@ -1,5 +0,4 @@

import { BasedServer } from '../server';
import { ActiveChannel } from './types';
import { BasedServer } from '../server.js';
import { ActiveChannel } from './types.js';
export declare const updateDestroyTimer: (server: BasedServer, channel: ActiveChannel) => void;
export declare const destroyChannel: (server: BasedServer, id: number) => void;
//# sourceMappingURL=destroy.d.ts.map

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.destroyChannel = exports.updateDestroyTimer = void 0;
const functions_1 = require("@based/functions");
const cleanup_1 = require("./cleanup");
const updateDestroyTimer = (server, channel) => {
import { isBasedFunctionConfig } from '@based/functions';
import { cleanUpChannels } from './cleanup.js';
export const updateDestroyTimer = (server, channel) => {
const spec = server.functions.specs[channel.name];
if (spec && !(0, functions_1.isBasedFunctionConfig)('channel', spec)) {
if (spec && !isBasedFunctionConfig('channel', spec)) {
console.error('channel updateDestroyTimer - Not channel spec!', spec, channel.name);

@@ -23,5 +20,4 @@ return;

};
exports.updateDestroyTimer = updateDestroyTimer;
// dont use timer just use counter to remove it over time
const destroyChannel = (server, id) => {
export const destroyChannel = (server, id) => {
const channel = server.activeChannelsById.get(id);

@@ -44,7 +40,6 @@ if (!channel) {

if (channel.timeTillDestroy === null) {
(0, exports.updateDestroyTimer)(server, channel);
(0, cleanup_1.cleanUpChannels)(server);
updateDestroyTimer(server, channel);
cleanUpChannels(server);
}
};
exports.destroyChannel = destroyChannel;
//# sourceMappingURL=destroy.js.map

@@ -1,5 +0,4 @@

import { ActiveChannel } from './types';
import { BasedServer } from '../server';
import { ActiveChannel } from './types.js';
import { BasedServer } from '../server.js';
export declare const stopRemoveChannel: (channel: ActiveChannel) => void;
export declare const extendChannel: (server: BasedServer, channel: ActiveChannel) => void;
//# sourceMappingURL=extend.d.ts.map
export declare const extendChannel: (_server: BasedServer, channel: ActiveChannel) => void;

@@ -1,5 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendChannel = exports.stopRemoveChannel = void 0;
const stopRemoveChannel = (channel) => {
export const stopRemoveChannel = (channel) => {
if (channel.timeTillDestroy) {

@@ -9,4 +6,3 @@ channel.timeTillDestroy = null;

};
exports.stopRemoveChannel = stopRemoveChannel;
const extendChannel = (server, channel) => {
export const extendChannel = (_server, channel) => {
if (channel.closeAfterIdleTime && channel.timeTillDestroy !== null) {

@@ -16,3 +12,2 @@ channel.timeTillDestroy = channel.closeAfterIdleTime;

};
exports.extendChannel = extendChannel;
//# sourceMappingURL=extend.js.map

@@ -1,5 +0,4 @@

import { ActiveChannel } from './types';
import { BasedServer } from '../server';
import { ActiveChannel } from './types.js';
import { BasedServer } from '../server.js';
export declare const getChannelAndStopRemove: (server: BasedServer, id: number) => ActiveChannel;
export declare const hasChannel: (server: BasedServer, id: number) => Boolean;
//# sourceMappingURL=get.d.ts.map

@@ -1,15 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasChannel = exports.getChannelAndStopRemove = void 0;
const extend_1 = require("./extend");
const getChannelAndStopRemove = (server, id) => {
import { stopRemoveChannel } from './extend.js';
export const getChannelAndStopRemove = (server, id) => {
const obs = server.activeChannelsById.get(id);
(0, extend_1.stopRemoveChannel)(obs);
stopRemoveChannel(obs);
return obs;
};
exports.getChannelAndStopRemove = getChannelAndStopRemove;
const hasChannel = (server, id) => {
export const hasChannel = (server, id) => {
return server.activeChannelsById.has(id);
};
exports.hasChannel = hasChannel;
//# sourceMappingURL=get.js.map

@@ -1,9 +0,8 @@

export * from './types';
export * from './get';
export * from './create';
export * from './start';
export * from './subscribe';
export * from './unsub';
export * from './destroy';
export * from './extend';
//# sourceMappingURL=index.d.ts.map
export * from './types.js';
export * from './get.js';
export * from './create.js';
export * from './start.js';
export * from './subscribe.js';
export * from './unsub.js';
export * from './destroy.js';
export * from './extend.js';

@@ -1,25 +0,9 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./types"), exports);
__exportStar(require("./get"), exports);
__exportStar(require("./create"), exports);
__exportStar(require("./start"), exports);
__exportStar(require("./subscribe"), exports);
__exportStar(require("./unsub"), exports);
__exportStar(require("./destroy"), exports);
__exportStar(require("./extend"), exports);
export * from './types.js';
export * from './get.js';
export * from './create.js';
export * from './start.js';
export * from './subscribe.js';
export * from './unsub.js';
export * from './destroy.js';
export * from './extend.js';
//# sourceMappingURL=index.js.map

@@ -1,3 +0,2 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
export declare const startChannel: (server: BasedServer, id: number, fromInstall?: boolean) => void;
//# sourceMappingURL=start.d.ts.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.startChannel = void 0;
const protocol_1 = require("../protocol");
const error_1 = require("../error");
const functions_1 = require("@based/functions");
import { valueToBuffer, encodeChannelMessage, encodeErrorResponse, } from '../protocol.js';
import { BasedErrorCode, createError } from '../error/index.js';
import { isBasedFunctionConfig } from '@based/functions';
const updateChannelListener = (server, channel, msg) => {
if (channel.clients.size) {
const data = (0, protocol_1.encodeChannelMessage)(channel.id, (0, protocol_1.valueToBuffer)(msg));
const data = encodeChannelMessage(channel.id, valueToBuffer(msg));
server.uwsApp.publish(String(channel.id), data, true, false);

@@ -21,3 +18,3 @@ }

err instanceof Error
? (0, error_1.createError)(server, {
? createError(server, {
session: {

@@ -29,3 +26,3 @@ type: 'channel',

},
}, error_1.BasedErrorCode.FunctionError, {
}, BasedErrorCode.FunctionError, {
err,

@@ -42,3 +39,3 @@ channelId: channel.id,

if (channel.clients.size) {
server.uwsApp.publish(String(channel.id), (0, protocol_1.encodeErrorResponse)((0, protocol_1.valueToBuffer)(err)), true, false);
server.uwsApp.publish(String(channel.id), encodeErrorResponse(valueToBuffer(err)), true, false);
}

@@ -51,3 +48,3 @@ if (channel.functionChannelClients.size) {

};
const startChannel = (server, id, fromInstall) => {
export const startChannel = (server, id, fromInstall) => {
const channel = server.activeChannelsById.get(id);

@@ -66,3 +63,3 @@ if (channel.closeFunction) {

}
if (!spec || !(0, functions_1.isBasedFunctionConfig)('channel', spec)) {
if (!spec || !isBasedFunctionConfig('channel', spec)) {
console.warn('Start channel - cannot find channel function spec', channel.name);

@@ -92,3 +89,2 @@ return;

let throtDebounced = false;
let timer;
const update = (msg) => {

@@ -101,3 +97,3 @@ if (isThrottled) {

isThrottled = true;
timer = setTimeout(() => {
setTimeout(() => {
if (throtDebounced && !channel.isDestroyed) {

@@ -125,3 +121,2 @@ updateChannelListener(server, channel, tempMsg);

};
exports.startChannel = startChannel;
//# sourceMappingURL=start.js.map

@@ -1,5 +0,4 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { WebSocketSession, Context, ChannelMessageFunctionInternal } from '@based/functions';
export declare const subscribeChannel: (server: BasedServer, id: number, ctx: Context<WebSocketSession>) => void;
export declare const subscribeChannelFunction: (server: BasedServer, id: number, update: ChannelMessageFunctionInternal) => void;
//# sourceMappingURL=subscribe.d.ts.map

@@ -1,7 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.subscribeChannelFunction = exports.subscribeChannel = void 0;
const get_1 = require("./get");
const start_1 = require("./start");
const subscribeChannel = (server, id, ctx) => {
import { getChannelAndStopRemove } from './get.js';
import { startChannel } from './start.js';
export const subscribeChannel = (server, id, ctx) => {
const session = ctx.session;

@@ -12,3 +9,3 @@ if (!session) {

ctx.session.ws.subscribe(String(id));
const channel = (0, get_1.getChannelAndStopRemove)(server, id);
const channel = getChannelAndStopRemove(server, id);
if (server.channelEvents) {

@@ -20,8 +17,7 @@ server.channelEvents.subscribe(channel, ctx);

if (!channel.isActive && !channel.doesNotExist) {
(0, start_1.startChannel)(server, id);
startChannel(server, id);
}
};
exports.subscribeChannel = subscribeChannel;
const subscribeChannelFunction = (server, id, update) => {
const channel = (0, get_1.getChannelAndStopRemove)(server, id);
export const subscribeChannelFunction = (server, id, update) => {
const channel = getChannelAndStopRemove(server, id);
if (channel.functionChannelClients.add(update)) {

@@ -33,6 +29,5 @@ if (server.channelEvents) {

if (!channel.isActive && !channel.doesNotExist) {
(0, start_1.startChannel)(server, id);
startChannel(server, id);
}
};
exports.subscribeChannelFunction = subscribeChannelFunction;
//# sourceMappingURL=subscribe.js.map

@@ -15,2 +15,1 @@ import { ChannelMessageFunctionInternal } from '@based/functions';

};
//# sourceMappingURL=types.d.ts.map

@@ -1,4 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};
// periodic clean up
//# sourceMappingURL=types.js.map

@@ -1,2 +0,2 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { WebSocketSession, Context, ChannelMessageFunction } from '@based/functions';

@@ -6,2 +6,1 @@ export declare const unsubscribeFunction: (server: BasedServer, id: number, update: ChannelMessageFunction) => true | void;

export declare const unsubscribeChannelIgnoreClient: (server: BasedServer, id: number, ctx: Context<WebSocketSession>) => void;
//# sourceMappingURL=unsub.d.ts.map

@@ -1,6 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsubscribeChannelIgnoreClient = exports.unsubscribeChannel = exports.unsubscribeFunction = void 0;
const destroy_1 = require("./destroy");
const unsubscribeFunction = (server, id, update) => {
import { destroyChannel } from './destroy.js';
export const unsubscribeFunction = (server, id, update) => {
const channel = server.activeChannelsById.get(id);

@@ -14,8 +11,7 @@ if (!channel) {

}
(0, destroy_1.destroyChannel)(server, id);
destroyChannel(server, id);
return true;
}
};
exports.unsubscribeFunction = unsubscribeFunction;
const unsubscribeChannel = (server, id, ctx) => {
export const unsubscribeChannel = (server, id, ctx) => {
const session = ctx.session;

@@ -38,8 +34,7 @@ if (!session) {

}
(0, destroy_1.destroyChannel)(server, id);
destroyChannel(server, id);
return true;
}
};
exports.unsubscribeChannel = unsubscribeChannel;
const unsubscribeChannelIgnoreClient = (server, id, ctx) => {
export const unsubscribeChannelIgnoreClient = (server, id, ctx) => {
const session = ctx.session;

@@ -56,5 +51,4 @@ if (!session) {

}
(0, destroy_1.destroyChannel)(server, id);
destroyChannel(server, id);
};
exports.unsubscribeChannelIgnoreClient = unsubscribeChannelIgnoreClient;
//# sourceMappingURL=unsub.js.map

@@ -1,2 +0,2 @@

/// <reference types="node" />
/// <reference types="node" resolution-mode="require"/>
export declare const compress: (payload: string | Buffer, encoding?: string) => Promise<{

@@ -6,2 +6,1 @@ payload: Buffer | string;

}>;
//# sourceMappingURL=compress.d.ts.map

@@ -1,13 +0,7 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.compress = void 0;
const node_zlib_1 = __importDefault(require("node:zlib"));
const node_util_1 = require("node:util");
const protocol_1 = require("./protocol");
const deflate = (0, node_util_1.promisify)(node_zlib_1.default.deflate);
const gzip = (0, node_util_1.promisify)(node_zlib_1.default.gzip);
const br = (0, node_util_1.promisify)(node_zlib_1.default.brotliCompress);
import zlib from 'node:zlib';
import { promisify } from 'node:util';
import { COMPRESS_FROM_BYTES } from './protocol.js';
const deflate = promisify(zlib.deflate);
const gzip = promisify(zlib.gzip);
const br = promisify(zlib.brotliCompress);
/*

@@ -19,5 +13,5 @@ Content-Encoding: gzip

*/
const COMPRESS_STRING_LEN = Math.ceil(protocol_1.COMPRESS_FROM_BYTES / 1.5);
const compress = async (payload, encoding) => {
if (payload instanceof Buffer && payload.byteLength <= protocol_1.COMPRESS_FROM_BYTES) {
const COMPRESS_STRING_LEN = Math.ceil(COMPRESS_FROM_BYTES / 1.5);
export const compress = async (payload, encoding) => {
if (payload instanceof Buffer && payload.byteLength <= COMPRESS_FROM_BYTES) {
return { payload };

@@ -55,3 +49,2 @@ }

};
exports.compress = compress;
//# sourceMappingURL=compress.js.map

@@ -1,2 +0,2 @@

import { BasedErrorCode, ErrorHandler } from './types';
import { BasedErrorCode, ErrorHandler } from './types.js';
type ErrorType = {

@@ -7,2 +7,1 @@ [K in BasedErrorCode]: ErrorHandler<K>;

export {};
//# sourceMappingURL=errorTypeHandlers.d.ts.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorTypeHandlers = void 0;
const types_1 = require("./types");
import { BasedErrorCode } from './types.js';
const addName = (payload) => {
return payload.name ? `[${payload.name}] ` : '';
};
exports.errorTypeHandlers = {
[types_1.BasedErrorCode.MissingAuthStateProtocolHeader]: {
export const errorTypeHandlers = {
[BasedErrorCode.MissingAuthStateProtocolHeader]: {
statusCode: 500,

@@ -14,3 +11,3 @@ statusMessage: 'Internal Server Error',

},
[types_1.BasedErrorCode.RateLimit]: {
[BasedErrorCode.RateLimit]: {
statusCode: 429,

@@ -20,3 +17,3 @@ statusMessage: 'Rate limit',

},
[types_1.BasedErrorCode.Block]: {
[BasedErrorCode.Block]: {
statusCode: 429,

@@ -26,3 +23,3 @@ statusMessage: 'Blocked ip',

},
[types_1.BasedErrorCode.IncorrectAccessKey]: {
[BasedErrorCode.IncorrectAccessKey]: {
statusCode: 429,

@@ -32,3 +29,3 @@ statusMessage: 'Rate limit',

},
[types_1.BasedErrorCode.FunctionError]: {
[BasedErrorCode.FunctionError]: {
statusCode: 500,

@@ -46,3 +43,3 @@ statusMessage: 'Internal Server Error',

},
[types_1.BasedErrorCode.ObserveCallbackError]: {
[BasedErrorCode.ObserveCallbackError]: {
statusCode: 500,

@@ -54,3 +51,3 @@ statusMessage: 'Internal Server Error',

},
[types_1.BasedErrorCode.FunctionNotFound]: {
[BasedErrorCode.FunctionNotFound]: {
statusCode: 404,

@@ -63,3 +60,3 @@ statusMessage: 'Not Found',

},
[types_1.BasedErrorCode.FunctionIsWrongType]: {
[BasedErrorCode.FunctionIsWrongType]: {
statusCode: 400,

@@ -71,3 +68,3 @@ statusMessage: 'Incorrect Protocol',

},
[types_1.BasedErrorCode.AuthorizeFunctionError]: {
[BasedErrorCode.AuthorizeFunctionError]: {
statusCode: 403,

@@ -85,3 +82,3 @@ statusMessage: 'Forbidden',

},
[types_1.BasedErrorCode.AuthorizeRejectedError]: {
[BasedErrorCode.AuthorizeRejectedError]: {
statusCode: 403,

@@ -91,3 +88,3 @@ statusMessage: 'Forbidden',

},
[types_1.BasedErrorCode.InvalidPayload]: {
[BasedErrorCode.InvalidPayload]: {
statusCode: 400,

@@ -97,3 +94,3 @@ statusMessage: 'Bad Request',

},
[types_1.BasedErrorCode.NoBinaryProtocol]: {
[BasedErrorCode.NoBinaryProtocol]: {
statusCode: 400,

@@ -103,3 +100,3 @@ statusMessage: 'Protocol mismatch',

},
[types_1.BasedErrorCode.PayloadTooLarge]: {
[BasedErrorCode.PayloadTooLarge]: {
statusCode: 413,

@@ -109,3 +106,3 @@ statusMessage: 'Payload Too Large',

},
[types_1.BasedErrorCode.ChunkTooLarge]: {
[BasedErrorCode.ChunkTooLarge]: {
statusCode: 413,

@@ -115,3 +112,3 @@ statusMessage: 'Payload Too Large',

},
[types_1.BasedErrorCode.UnsupportedContentEncoding]: {
[BasedErrorCode.UnsupportedContentEncoding]: {
statusCode: 400,

@@ -121,3 +118,3 @@ statusMessage: 'Incorrect content encoding',

},
[types_1.BasedErrorCode.LengthRequired]: {
[BasedErrorCode.LengthRequired]: {
statusCode: 411,

@@ -127,3 +124,3 @@ statusMessage: 'Length Required',

},
[types_1.BasedErrorCode.MethodNotAllowed]: {
[BasedErrorCode.MethodNotAllowed]: {
statusCode: 405,

@@ -133,3 +130,3 @@ statusMessage: 'Method Not Allowed',

},
[types_1.BasedErrorCode.NoOservableCacheAvailable]: {
[BasedErrorCode.NoOservableCacheAvailable]: {
statusCode: 500,

@@ -136,0 +133,0 @@ statusMessage: 'Internal Server Error',

@@ -1,5 +0,5 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { Context } from '@based/functions';
import { BasedErrorCode, ErrorPayload, BasedErrorData } from './types';
export * from './types';
import { BasedErrorCode, ErrorPayload, BasedErrorData } from './types.js';
export * from './types.js';
export declare function createErrorData<T extends BasedErrorCode>(code: T, payload: ErrorPayload[T]): {

@@ -13,6 +13,5 @@ code: T;

path: string;
type: "function" | "channel" | "query" | "stream" | "app";
type: "function" | "channel" | "query" | "stream" | "app" | "job";
};
};
export declare function createError<T extends BasedErrorCode>(server: BasedServer, context: Context, code: T, payload: ErrorPayload[T]): BasedErrorData<T>;
//# sourceMappingURL=index.d.ts.map

@@ -1,31 +0,14 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createError = exports.createErrorData = void 0;
const functions_1 = require("@based/functions");
const types_1 = require("./types");
const errorTypeHandlers_1 = require("./errorTypeHandlers");
__exportStar(require("./types"), exports);
function createErrorData(code, payload) {
const type = errorTypeHandlers_1.errorTypeHandlers[code];
import { isAnyBasedRoute } from '@based/functions';
import { EMPTY_ROUTE, } from './types.js';
import { errorTypeHandlers } from './errorTypeHandlers.js';
export * from './types.js';
export function createErrorData(code, payload) {
const type = errorTypeHandlers[code];
const route = !payload
? types_1.EMPTY_ROUTE
: (0, functions_1.isAnyBasedRoute)(payload)
? EMPTY_ROUTE
: isAnyBasedRoute(payload)
? payload
: 'route' in payload
? payload.route
: types_1.EMPTY_ROUTE;
: EMPTY_ROUTE;
return {

@@ -43,4 +26,3 @@ code,

}
exports.createErrorData = createErrorData;
function createError(server, context, code, payload) {
export function createError(server, context, code, payload) {
const errorData = createErrorData(code, payload);

@@ -64,3 +46,2 @@ if ('requestId' in payload) {

}
exports.createError = createError;
//# sourceMappingURL=index.js.map

@@ -96,2 +96,1 @@ import { BasedRoute } from '@based/functions';

export {};
//# sourceMappingURL=types.d.ts.map

@@ -1,5 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasedErrorCode = exports.EMPTY_ROUTE = void 0;
exports.EMPTY_ROUTE = {
export const EMPTY_ROUTE = {
name: 'no-route',

@@ -9,3 +6,3 @@ path: '',

};
var BasedErrorCode;
export var BasedErrorCode;
(function (BasedErrorCode) {

@@ -30,3 +27,3 @@ BasedErrorCode[BasedErrorCode["FunctionError"] = 50001] = "FunctionError";

BasedErrorCode[BasedErrorCode["Block"] = 90001] = "Block";
})(BasedErrorCode = exports.BasedErrorCode || (exports.BasedErrorCode = {}));
})(BasedErrorCode || (BasedErrorCode = {}));
//# sourceMappingURL=types.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { Context } from '@based/functions';
export declare const callFunction: (server: BasedServer, name: string, ctx: Context, payload: any) => Promise<any>;
//# sourceMappingURL=callFunction.d.ts.map

@@ -1,15 +0,12 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callFunction = void 0;
const error_1 = require("../error");
const verifyRoute_1 = require("../verifyRoute");
const installFn_1 = require("../installFn");
const callFunction = async (server, name, ctx, payload) => {
const route = (0, verifyRoute_1.verifyRoute)(server, server.client.ctx, 'function', server.functions.route(name), name);
import { BasedErrorCode, createError } from '../error/index.js';
import { verifyRoute } from '../verifyRoute.js';
import { installFn } from '../installFn.js';
export const callFunction = async (server, name, ctx, payload) => {
const route = verifyRoute(server, server.client.ctx, 'function', server.functions.route(name), name);
if (route === null) {
return;
}
const spec = await (0, installFn_1.installFn)(server, server.client.ctx, route);
const spec = await installFn(server, server.client.ctx, route);
if (!spec) {
throw (0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionNotFound, {
throw createError(server, ctx, BasedErrorCode.FunctionNotFound, {
route,

@@ -21,3 +18,3 @@ });

if (!client) {
throw (0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
throw createError(server, ctx, BasedErrorCode.FunctionError, {
route,

@@ -31,3 +28,3 @@ err: new Error('Cannot find client ' + spec.relay),

catch (err) {
throw (0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
throw createError(server, ctx, BasedErrorCode.FunctionError, {
route,

@@ -42,3 +39,3 @@ err,

catch (err) {
throw (0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
throw createError(server, ctx, BasedErrorCode.FunctionError, {
route,

@@ -49,3 +46,2 @@ err,

};
exports.callFunction = callFunction;
//# sourceMappingURL=callFunction.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { ChannelMessageFunctionInternal } from '@based/functions';
export declare const subscribeChannel: (server: BasedServer, name: string, id: number, payload: any, update: ChannelMessageFunctionInternal) => (() => void);
//# sourceMappingURL=channelSubscribe.d.ts.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.subscribeChannel = void 0;
const verifyRoute_1 = require("../verifyRoute");
const channel_1 = require("../channel");
const installFn_1 = require("../installFn");
const error_1 = require("../error");
const subscribeChannel = (server, name, id, payload, update) => {
const route = (0, verifyRoute_1.verifyRoute)(server, server.client.ctx, 'channel', server.functions.route(name), name, id);
import { verifyRoute } from '../verifyRoute.js';
import { unsubscribeFunction, subscribeChannelFunction, hasChannel, createChannel, } from '../channel/index.js';
import { installFn } from '../installFn.js';
import { createError, BasedErrorCode } from '../error/index.js';
export const subscribeChannel = (server, name, id, payload, update) => {
const route = verifyRoute(server, server.client.ctx, 'channel', server.functions.route(name), name, id);
if (route === null) {

@@ -19,9 +16,9 @@ throw new Error(`[${name}] No session in ctx`);

isClosed = true;
(0, channel_1.unsubscribeFunction)(server, id, update);
unsubscribeFunction(server, id, update);
};
if ((0, channel_1.hasChannel)(server, id)) {
(0, channel_1.subscribeChannelFunction)(server, id, update);
if (hasChannel(server, id)) {
subscribeChannelFunction(server, id, update);
return close;
}
(0, installFn_1.installFn)(server, server.client.ctx, route).then((spec) => {
installFn(server, server.client.ctx, route).then((spec) => {
if (isClosed) {

@@ -31,3 +28,3 @@ return;

if (spec === null) {
update(null, (0, error_1.createError)(server, server.client.ctx, error_1.BasedErrorCode.FunctionNotFound, {
update(null, createError(server, server.client.ctx, BasedErrorCode.FunctionNotFound, {
route,

@@ -37,10 +34,9 @@ }));

}
if (!(0, channel_1.hasChannel)(server, id)) {
(0, channel_1.createChannel)(server, name, id, payload, true);
if (!hasChannel(server, id)) {
createChannel(server, name, id, payload, true);
}
(0, channel_1.subscribeChannelFunction)(server, id, update);
subscribeChannelFunction(server, id, update);
});
return close;
};
exports.subscribeChannel = subscribeChannel;
//# sourceMappingURL=channelSubscribe.js.map

@@ -11,2 +11,1 @@ import { BasedChannel as BasedChannelAbstract, ChannelMessageFunction, Context, InternalSessionClient } from '@based/functions';

}
//# sourceMappingURL=channel.d.ts.map

@@ -1,9 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasedChannel = void 0;
const functions_1 = require("@based/functions");
const query_1 = require("../../query");
const publish_1 = require("../publish");
const channelSubscribe_1 = require("../channelSubscribe");
class BasedChannel extends functions_1.BasedChannel {
import { BasedChannel as BasedChannelAbstract, } from '@based/functions';
import { genObservableId } from '../../query/index.js';
import { publish } from '../publish.js';
import { subscribeChannel } from '../channelSubscribe.js';
export class BasedChannel extends BasedChannelAbstract {
payload;
name;
id;
ctx;
constructor(ctx, name, payload) {

@@ -13,7 +14,7 @@ super();

this.payload = payload;
this.id = (0, query_1.genObservableId)(name, payload);
this.id = genObservableId(name, payload);
this.name = name;
}
subscribe(onMessage, onError) {
return (0, channelSubscribe_1.subscribeChannel)(this.ctx.session.client.server, this.name, this.id, this.payload, (msg, err) => {
return subscribeChannel(this.ctx.session.client.server, this.name, this.id, this.payload, (msg, err) => {
if (err) {

@@ -29,6 +30,5 @@ if (onError) {

publish(message, ctx = this.ctx) {
(0, publish_1.publish)(this.ctx.session.client.server, this.name, ctx, this.id, this.payload, message);
publish(this.ctx.session.client.server, this.name, ctx, this.id, this.payload, message);
}
}
exports.BasedChannel = BasedChannel;
//# sourceMappingURL=channel.js.map

@@ -1,5 +0,5 @@

/// <reference types="node" />
import { BasedServer } from '../../server';
import { BasedQuery } from './query';
import { BasedChannel } from './channel';
/// <reference types="node" resolution-mode="require"/>
import { BasedServer } from '../../server.js';
import { BasedQuery } from './query.js';
import { BasedChannel } from './channel.js';
import util from 'node:util';

@@ -21,2 +21,1 @@ import { AuthState, BasedFunctionClient as BasedfunctionClientAbstract, Context, InternalSessionClient, StreamFunctionOpts, Session } from '@based/functions';

}
//# sourceMappingURL=index.d.ts.map

@@ -1,14 +0,9 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasedFunctionClient = void 0;
const callFunction_1 = require("../callFunction");
const query_1 = require("./query");
const channel_1 = require("./channel");
const stream_1 = require("../stream");
const node_util_1 = __importDefault(require("node:util"));
const functions_1 = require("@based/functions");
class BasedFunctionClient extends functions_1.BasedFunctionClient {
import { callFunction } from '../callFunction.js';
import { BasedQuery } from './query.js';
import { BasedChannel } from './channel.js';
import { streamFunction } from '../stream.js';
import util from 'node:util';
import { BasedFunctionClient as BasedfunctionClientAbstract, isClientContext, isWsContext, } from '@based/functions';
export class BasedFunctionClient extends BasedfunctionClientAbstract {
ctx;
constructor(server) {

@@ -26,13 +21,13 @@ super();

call(name, payload, ctx = this.ctx) {
return (0, callFunction_1.callFunction)(this.server, name, ctx, payload);
return callFunction(this.server, name, ctx, payload);
}
query(name, payload) {
return new query_1.BasedQuery(this.ctx, name, payload);
return new BasedQuery(this.ctx, name, payload);
}
channel(name, payload) {
return new channel_1.BasedChannel(this.ctx, name, payload);
return new BasedChannel(this.ctx, name, payload);
}
async stream(name, streamOpts, ctx = this.ctx) {
// make later
return (0, stream_1.streamFunction)(this.server, name, ctx, streamOpts);
return streamFunction(this.server, name, ctx, streamOpts);
}

@@ -46,3 +41,3 @@ renewAuthState(ctx, authState) {

}
if (!(0, functions_1.isClientContext)(ctx)) {
if (!isClientContext(ctx)) {
return;

@@ -54,3 +49,3 @@ }

sendAuthState(ctx, authState) {
if (!(0, functions_1.isWsContext)(ctx)) {
if (!isWsContext(ctx)) {
return;

@@ -60,7 +55,6 @@ }

}
[node_util_1.default.inspect.custom]() {
[util.inspect.custom]() {
return `[BasedFunctionClient]`;
}
}
exports.BasedFunctionClient = BasedFunctionClient;
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

import { ObservableUpdateFunction, ObserveErrorListener } from '../../query';
import { ObservableUpdateFunction, ObserveErrorListener } from '../../query/index.js';
import { BasedQuery as BasedQueryAbstract, Context, InternalSessionClient } from '@based/functions';

@@ -12,2 +12,1 @@ export declare class BasedQuery extends BasedQueryAbstract {

}
//# sourceMappingURL=query.d.ts.map

@@ -1,8 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasedQuery = void 0;
const observe_1 = require("../observe");
const get_1 = require("../get");
const functions_1 = require("@based/functions");
class BasedQuery extends functions_1.BasedQuery {
import { observe } from '../observe.js';
import { get } from '../get.js';
import { BasedQuery as BasedQueryAbstract, } from '@based/functions';
export class BasedQuery extends BasedQueryAbstract {
query;
name;
ctx;
constructor(ctx, name, payload) {

@@ -15,3 +15,3 @@ super();

subscribe(onData, onError) {
return (0, observe_1.observe)(this.ctx.session.client.server, this.name, this.ctx, this.query, onData, onError);
return observe(this.ctx.session.client.server, this.name, this.ctx, this.query, onData, onError);
}

@@ -29,6 +29,5 @@ async getWhen(condition) {

async get() {
return (0, get_1.get)(this.ctx.session.client.server, this.name, this.ctx, this.query);
return get(this.ctx.session.client.server, this.name, this.ctx, this.query);
}
}
exports.BasedQuery = BasedQuery;
//# sourceMappingURL=query.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { Context } from '@based/functions';
export declare const get: (server: BasedServer, name: string, ctx: Context, payload: any) => Promise<any>;
//# sourceMappingURL=get.d.ts.map

@@ -1,10 +0,7 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.get = void 0;
const error_1 = require("../error");
const query_1 = require("../query");
const verifyRoute_1 = require("../verifyRoute");
const installFn_1 = require("../installFn");
import { BasedErrorCode, createError } from '../error/index.js';
import { genObservableId, hasObs, createObs, subscribeNext, getObsAndStopRemove, destroyObs, start, } from '../query/index.js';
import { verifyRoute } from '../verifyRoute.js';
import { installFn } from '../installFn.js';
const getObsData = (resolve, reject, server, id, ctx, route) => {
const obs = (0, query_1.getObsAndStopRemove)(server, id);
const obs = getObsAndStopRemove(server, id);
if (server.queryEvents) {

@@ -14,3 +11,3 @@ server.queryEvents.get(obs);

if (obs.error) {
reject((0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
reject(createError(server, ctx, BasedErrorCode.FunctionError, {
route,

@@ -26,4 +23,4 @@ observableId: id,

}
(0, query_1.subscribeNext)(obs, (err) => {
(0, query_1.destroyObs)(server, id);
subscribeNext(obs, (err) => {
destroyObs(server, id);
if (err) {

@@ -37,7 +34,7 @@ reject(err);

};
const get = (server, name, ctx, payload) => {
export const get = (server, name, ctx, payload) => {
return new Promise((resolve, reject) => {
let route;
try {
route = (0, verifyRoute_1.verifyRoute)(server, server.client.ctx, 'query', server.functions.route(name), name);
route = verifyRoute(server, server.client.ctx, 'query', server.functions.route(name), name);
if (route === null) {

@@ -52,7 +49,7 @@ reject(new Error(`[${name}] No session in ctx`));

}
const id = (0, query_1.genObservableId)(name, payload);
if (!(0, query_1.hasObs)(server, id)) {
(0, installFn_1.installFn)(server, server.client.ctx, route).then((spec) => {
const id = genObservableId(name, payload);
if (!hasObs(server, id)) {
installFn(server, server.client.ctx, route).then((spec) => {
if (!spec) {
reject((0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionNotFound, {
reject(createError(server, ctx, BasedErrorCode.FunctionNotFound, {
route,

@@ -62,6 +59,6 @@ }));

}
if (!(0, query_1.hasObs)(server, id)) {
(0, query_1.createObs)(server, name, id, payload, true);
if (!hasObs(server, id)) {
createObs(server, name, id, payload, true);
getObsData(resolve, reject, server, id, ctx, route);
(0, query_1.start)(server, id);
start(server, id);
}

@@ -78,3 +75,2 @@ else {

};
exports.get = get;
//# sourceMappingURL=get.js.map

@@ -1,9 +0,7 @@

export * from './callFunction';
export * from './get';
export * from './client';
export { decode } from '../protocol';
export * from './observe';
export * from './stream';
export * from './publish';
export * from './channelSubscribe';
//# sourceMappingURL=index.d.ts.map
export * from './callFunction.js';
export * from './get.js';
export * from './client/index.js';
export * from './observe.js';
export * from './stream.js';
export * from './publish.js';
export * from './channelSubscribe.js';

@@ -1,27 +0,8 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decode = void 0;
__exportStar(require("./callFunction"), exports);
__exportStar(require("./get"), exports);
__exportStar(require("./client"), exports);
var protocol_1 = require("../protocol");
Object.defineProperty(exports, "decode", { enumerable: true, get: function () { return protocol_1.decode; } });
__exportStar(require("./observe"), exports);
__exportStar(require("./stream"), exports);
__exportStar(require("./publish"), exports);
__exportStar(require("./channelSubscribe"), exports);
export * from './callFunction.js';
export * from './get.js';
export * from './client/index.js';
export * from './observe.js';
export * from './stream.js';
export * from './publish.js';
export * from './channelSubscribe.js';
//# sourceMappingURL=index.js.map

@@ -1,5 +0,4 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { Context } from '@based/functions';
import { ObservableUpdateFunction, ObserveErrorListener } from '../query';
import { ObservableUpdateFunction, ObserveErrorListener } from '../query/index.js';
export declare const observe: (server: BasedServer, name: string, ctx: Context, payload: any, update: ObservableUpdateFunction, error: ObserveErrorListener) => (() => void);
//# sourceMappingURL=observe.d.ts.map

@@ -1,11 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.observe = void 0;
const error_1 = require("../error");
const verifyRoute_1 = require("../verifyRoute");
const query_1 = require("../query");
const installFn_1 = require("../installFn");
const observe = (server, name, ctx, payload, update, error) => {
const id = (0, query_1.genObservableId)(name, payload);
const route = (0, verifyRoute_1.verifyRoute)(server, server.client.ctx, 'query', server.functions.route(name), name, id);
import { BasedErrorCode, createError } from '../error/index.js';
import { verifyRoute } from '../verifyRoute.js';
import { genObservableId, hasObs, createObs, subscribeFunction, unsubscribeFunction, } from '../query/index.js';
import { installFn } from '../installFn.js';
export const observe = (server, name, ctx, payload, update, error) => {
const id = genObservableId(name, payload);
const route = verifyRoute(server, server.client.ctx, 'query', server.functions.route(name), name, id);
if (route === null) {

@@ -20,9 +17,9 @@ throw new Error(`[${name}] No session in ctx`);

isClosed = true;
(0, query_1.unsubscribeFunction)(server, id, update);
unsubscribeFunction(server, id, update);
};
if ((0, query_1.hasObs)(server, id)) {
(0, query_1.subscribeFunction)(server, id, update);
if (hasObs(server, id)) {
subscribeFunction(server, id, update);
return close;
}
(0, installFn_1.installFn)(server, server.client.ctx, route).then((spec) => {
installFn(server, server.client.ctx, route).then((spec) => {
if (isClosed) {

@@ -32,3 +29,3 @@ return;

if (spec === null) {
error((0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionNotFound, {
error(createError(server, ctx, BasedErrorCode.FunctionNotFound, {
route,

@@ -38,10 +35,9 @@ }));

}
if (!(0, query_1.hasObs)(server, id)) {
(0, query_1.createObs)(server, name, id, payload);
if (!hasObs(server, id)) {
createObs(server, name, id, payload);
}
(0, query_1.subscribeFunction)(server, id, update);
subscribeFunction(server, id, update);
});
return close;
};
exports.observe = observe;
//# sourceMappingURL=observe.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { Context } from '@based/functions';
export declare const publish: (server: BasedServer, name: string, ctx: Context, id: number, payload: any, msg: any) => void;
//# sourceMappingURL=publish.d.ts.map

@@ -1,13 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.publish = void 0;
const verifyRoute_1 = require("../verifyRoute");
const installFn_1 = require("../installFn");
const error_1 = require("../error");
const publish = (server, name, ctx, id, payload, msg) => {
const route = (0, verifyRoute_1.verifyRoute)(server, server.client.ctx, 'channel', server.functions.route(name), name);
import { verifyRoute } from '../verifyRoute.js';
import { installFn } from '../installFn.js';
import { BasedErrorCode, createError } from '../error/index.js';
export const publish = (server, name, ctx, id, payload, msg) => {
const route = verifyRoute(server, server.client.ctx, 'channel', server.functions.route(name), name);
if (route === null) {
return;
}
(0, installFn_1.installFn)(server, server.client.ctx, route).then((fn) => {
installFn(server, server.client.ctx, route).then((fn) => {
if (fn === null) {

@@ -21,3 +18,3 @@ return;

// Will emit the error
(0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
createError(server, ctx, BasedErrorCode.FunctionError, {
err,

@@ -29,3 +26,2 @@ route,

};
exports.publish = publish;
//# sourceMappingURL=publish.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { Context, StreamFunctionOpts } from '@based/functions';
export declare const streamFunction: (server: BasedServer, name: string, ctx: Context, streamOpts: StreamFunctionOpts) => Promise<any>;
//# sourceMappingURL=stream.d.ts.map

@@ -1,24 +0,21 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.streamFunction = void 0;
const error_1 = require("../error");
const functions_1 = require("@based/functions");
const verifyRoute_1 = require("../verifyRoute");
const installFn_1 = require("../installFn");
import { BasedErrorCode, createError } from '../error/index.js';
import { BasedDataStream, isStreamFunctionOpts, } from '@based/functions';
import { verifyRoute } from '../verifyRoute.js';
import { installFn } from '../installFn.js';
const wrapStream = (stream, size) => {
if (stream instanceof functions_1.BasedDataStream) {
if (stream instanceof BasedDataStream) {
return stream;
}
const s = new functions_1.BasedDataStream(size);
const s = new BasedDataStream(size);
stream.pipe(s);
return s;
};
const streamFunction = async (server, name, ctx, streamOpts) => {
const route = (0, verifyRoute_1.verifyRoute)(server, server.client.ctx, 'stream', server.functions.route(name), name);
export const streamFunction = async (server, name, ctx, streamOpts) => {
const route = verifyRoute(server, server.client.ctx, 'stream', server.functions.route(name), name);
if (route === null) {
return;
}
const fn = await (0, installFn_1.installFn)(server, server.client.ctx, route);
const fn = await installFn(server, server.client.ctx, route);
if (!fn) {
throw (0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionNotFound, {
throw createError(server, ctx, BasedErrorCode.FunctionNotFound, {
route,

@@ -28,3 +25,3 @@ });

let file;
if ((0, functions_1.isStreamFunctionOpts)(streamOpts)) {
if (isStreamFunctionOpts(streamOpts)) {
const stream = wrapStream(streamOpts.contents, streamOpts.size);

@@ -46,3 +43,3 @@ file = {

: contents;
const stream = new functions_1.BasedDataStream(buffer.byteLength);
const stream = new BasedDataStream(buffer.byteLength);
file = {

@@ -63,3 +60,3 @@ stream,

catch (err) {
throw (0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
throw createError(server, ctx, BasedErrorCode.FunctionError, {
route,

@@ -70,3 +67,2 @@ err,

};
exports.streamFunction = streamFunction;
//# sourceMappingURL=stream.js.map
import { BasedFunctionConfig } from '@based/functions';
export declare const genVersion: (spec: BasedFunctionConfig) => number;
//# sourceMappingURL=genVersion.d.ts.map

@@ -1,13 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.genVersion = void 0;
const functions_1 = require("@based/functions");
const hash_1 = require("@saulx/hash");
const genVersion = (spec) => {
if ((0, functions_1.isBasedFunctionConfig)('channel', spec)) {
import { isBasedFunctionConfig } from '@based/functions';
import { hashObjectIgnoreKeyOrder, hash } from '@saulx/hash';
export const genVersion = (spec) => {
if (isBasedFunctionConfig('channel', spec)) {
const { subscriber, publisher, relay } = spec;
if (!subscriber && !publisher && relay) {
return (0, hash_1.hash)(spec.relay);
return hash(spec.relay);
}
return (0, hash_1.hashObjectIgnoreKeyOrder)({
return hashObjectIgnoreKeyOrder({
subscriber: subscriber ? subscriber.toString() : '',

@@ -19,3 +16,3 @@ publisher: publisher ? publisher.toString() : '',

if (spec.relay) {
return (0, hash_1.hash)(spec.relay);
return hash(spec.relay);
}

@@ -25,7 +22,6 @@ else {

const { fn } = spec;
return (0, hash_1.hash)(fn.toString());
return hash(fn.toString());
}
}
};
exports.genVersion = genVersion;
//# sourceMappingURL=genVersion.js.map

@@ -1,7 +0,7 @@

/// <reference types="node" />
import type { BasedServer } from '../server';
/// <reference types="node" resolution-mode="require"/>
import type { BasedServer } from '../server.js';
import { Optional } from 'utility-types';
import { BasedRoute, BasedFunctionConfig, BasedFunctionConfigs, BasedRoutes, BasedFunctionConfigComplete, BasedRouteComplete } from '@based/functions';
import { FunctionConfig } from './types';
export * from './types';
import { FunctionConfig } from './types.js';
export * from './types.js';
export declare class BasedFunctions {

@@ -55,2 +55,1 @@ server: BasedServer;

}
//# sourceMappingURL=index.d.ts.map

@@ -1,39 +0,25 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasedFunctions = void 0;
const functions_1 = require("@based/functions");
const utils_1 = require("@saulx/utils");
const timeout_1 = require("./timeout");
const query_1 = require("../query");
const channel_1 = require("../channel");
const genVersion_1 = require("./genVersion");
__exportStar(require("./types"), exports);
class BasedFunctions {
import { isBasedFunctionConfig, } from '@based/functions';
import { deepMerge, deepEqual } from '@saulx/utils';
import { fnIsTimedOut, updateTimeoutCounter } from './timeout.js';
import { destroyObs, start } from '../query/index.js';
import { destroyChannel, startChannel } from '../channel/index.js';
import { genVersion } from './genVersion.js';
export * from './types.js';
export class BasedFunctions {
server;
reqId = 0;
config;
unregisterTimeout;
installsInProgress = {};
maxPayLoadSizeDefaults = {
stream: 5e6,
query: 2500,
function: 20e3,
channel: 500,
};
paths = {};
specs = {};
routes = {};
beingUninstalled = {};
constructor(server, config) {
this.reqId = 0;
this.installsInProgress = {};
this.maxPayLoadSizeDefaults = {
stream: 5e6,
query: 2500,
function: 20e3,
channel: 500,
};
this.paths = {};
this.specs = {};
this.routes = {};
this.beingUninstalled = {};
this.server = server;

@@ -50,3 +36,3 @@ if (config) {

if (this.config) {
(0, utils_1.deepMerge)(this.config, config);
deepMerge(this.config, config);
}

@@ -145,3 +131,3 @@ else {

// @ts-ignore added name allready
spec.version = (0, genVersion_1.genVersion)(spec);
spec.version = genVersion(spec);
}

@@ -197,3 +183,3 @@ const nSpec = spec;

}
if ((0, utils_1.deepEqual)(spec, this.specs[spec.name])) {
if (deepEqual(spec, this.specs[spec.name])) {
return false;

@@ -220,5 +206,5 @@ }

if (this.specs[spec.name] && this.server.activeChannels[spec.name]) {
if (!(0, functions_1.isBasedFunctionConfig)('channel', spec)) {
if (!isBasedFunctionConfig('channel', spec)) {
for (const [id] of this.server.activeChannels[spec.name]) {
(0, channel_1.destroyChannel)(this.server, id);
destroyChannel(this.server, id);
}

@@ -229,3 +215,3 @@ }

for (const [id] of this.server.activeChannels[spec.name]) {
(0, channel_1.startChannel)(this.server, id, true);
startChannel(this.server, id, true);
}

@@ -237,5 +223,5 @@ }

this.server.activeObservables[spec.name]) {
if (!(0, functions_1.isBasedFunctionConfig)('query', spec)) {
if (!isBasedFunctionConfig('query', spec)) {
for (const [id] of this.server.activeObservables[spec.name]) {
(0, query_1.destroyObs)(this.server, id);
destroyObs(this.server, id);
}

@@ -246,3 +232,3 @@ }

for (const [id] of this.server.activeObservables[spec.name]) {
(0, query_1.start)(this.server, id);
start(this.server, id);
}

@@ -259,11 +245,11 @@ }

const spec = this.specs[name];
if ((0, functions_1.isBasedFunctionConfig)('query', spec) &&
if (isBasedFunctionConfig('query', spec) &&
this.server.activeObservables[name]) {
(0, timeout_1.updateTimeoutCounter)(spec);
updateTimeoutCounter(spec);
}
else if ((0, functions_1.isBasedFunctionConfig)('channel', spec) &&
else if (isBasedFunctionConfig('channel', spec) &&
this.server.activeChannels[name]) {
(0, timeout_1.updateTimeoutCounter)(spec);
updateTimeoutCounter(spec);
}
else if ((0, timeout_1.fnIsTimedOut)(spec)) {
else if (fnIsTimedOut(spec)) {
q.push(this.uninstall(name, spec));

@@ -343,3 +329,3 @@ }

}
(0, timeout_1.updateTimeoutCounter)(spec);
updateTimeoutCounter(spec);
return spec;

@@ -354,7 +340,7 @@ }

}
if ((0, functions_1.isBasedFunctionConfig)('query', spec)) {
if (isBasedFunctionConfig('query', spec)) {
const activeObs = this.server.activeObservables[name];
if (activeObs) {
for (const [id] of activeObs) {
(0, query_1.destroyObs)(this.server, id);
destroyObs(this.server, id);
}

@@ -364,7 +350,7 @@ delete this.server.activeObservables[name];

}
if ((0, functions_1.isBasedFunctionConfig)('channel', spec)) {
if (isBasedFunctionConfig('channel', spec)) {
const activeChannel = this.server.activeChannels[name];
if (activeChannel) {
for (const [id] of activeChannel) {
(0, channel_1.destroyChannel)(this.server, id);
destroyChannel(this.server, id);
}

@@ -378,3 +364,2 @@ delete this.server.activeChannels[name];

}
exports.BasedFunctions = BasedFunctions;
//# sourceMappingURL=index.js.map
import type { BasedFunctionConfigComplete } from '@based/functions';
export declare const fnIsTimedOut: (spec: BasedFunctionConfigComplete) => boolean;
export declare const updateTimeoutCounter: (spec: BasedFunctionConfigComplete) => void;
//# sourceMappingURL=timeout.d.ts.map

@@ -1,5 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateTimeoutCounter = exports.fnIsTimedOut = void 0;
const fnIsTimedOut = (spec) => {
export const fnIsTimedOut = (spec) => {
if (spec.timeoutCounter !== -1) {

@@ -15,4 +12,3 @@ if (spec.timeoutCounter === 0) {

};
exports.fnIsTimedOut = fnIsTimedOut;
const updateTimeoutCounter = (spec) => {
export const updateTimeoutCounter = (spec) => {
if (spec.timeoutCounter !== -1) {

@@ -25,3 +21,2 @@ spec.timeoutCounter =

};
exports.updateTimeoutCounter = updateTimeoutCounter;
//# sourceMappingURL=timeout.js.map
import { BasedFunctionConfig, BasedRoutes, BasedRouteComplete, BasedFunctionConfigs, BasedFunctionConfigComplete } from '@based/functions';
import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
export type FunctionConfig = {

@@ -36,2 +36,1 @@ /** Default number to close channels & queries when no subscribers are active in ms */

};
//# sourceMappingURL=types.d.ts.map

@@ -1,3 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};
//# sourceMappingURL=types.js.map
import { HttpSession } from '@based/functions';
import { IsAuthorizedHandler } from '../../authorize';
import { IsAuthorizedHandler } from '../../authorize.js';
export declare const httpFunction: IsAuthorizedHandler<HttpSession>;
//# sourceMappingURL=function.d.ts.map

@@ -1,12 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.httpFunction = void 0;
const sendHttpResponse_1 = require("../../sendHttpResponse");
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
const httpFunction = async (route, spec, server, ctx, payload) => {
import { sendHttpResponse } from '../../sendHttpResponse.js';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
export const httpFunction = async (route, spec, server, ctx, payload) => {
if (spec.relay) {
const client = server.clients[spec.relay.client];
if (!client) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
err: new Error('Cannot find client ' + spec.relay),

@@ -29,6 +26,6 @@ route,

if (!status) {
(0, sendHttpResponse_1.sendHttpResponse)(ctx, responseData, headers);
sendHttpResponse(ctx, responseData, headers);
}
else {
(0, sendHttpResponse_1.sendHttpResponse)(ctx, responseData, headers, typeof status === 'string' ? status : String(status));
sendHttpResponse(ctx, responseData, headers, typeof status === 'string' ? status : String(status));
}

@@ -39,6 +36,6 @@ };

}
(0, sendHttpResponse_1.sendHttpResponse)(ctx, result);
sendHttpResponse(ctx, result);
})
.catch((err) => {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
err,

@@ -62,6 +59,6 @@ route,

if (!status) {
(0, sendHttpResponse_1.sendHttpResponse)(ctx, responseData, headers);
sendHttpResponse(ctx, responseData, headers);
}
else {
(0, sendHttpResponse_1.sendHttpResponse)(ctx, responseData, headers, typeof status === 'string' ? status : String(status));
sendHttpResponse(ctx, responseData, headers, typeof status === 'string' ? status : String(status));
}

@@ -72,6 +69,6 @@ };

}
(0, sendHttpResponse_1.sendHttpResponse)(ctx, result);
sendHttpResponse(ctx, result);
})
.catch((err) => {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
err,

@@ -82,3 +79,2 @@ route,

};
exports.httpFunction = httpFunction;
//# sourceMappingURL=function.js.map
import uws from '@based/uws';
import { BasedServer } from '../../server';
import { BasedServer } from '../../server.js';
export declare const httpHandler: (server: BasedServer, req: uws.HttpRequest, res: uws.HttpResponse) => void;
//# sourceMappingURL=index.d.ts.map

@@ -1,50 +0,15 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.httpHandler = void 0;
const functions_1 = require("@based/functions");
const function_1 = require("./function");
const streamFunction_1 = require("./streamFunction");
const query_1 = require("./query");
const readBody_1 = require("./readBody");
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
const security_1 = require("../../security");
const parseQuery_1 = __importDefault(require("./parseQuery"));
const auth_1 = require("../../auth");
const authorize_1 = require("../../authorize");
const sendHttpResponse_1 = require("../../sendHttpResponse");
const publish_1 = require("./publish");
import { isBasedRoute } from '@based/functions';
import { httpFunction } from './function.js';
import { httpStreamFunction } from './streamFunction/index.js';
import { httpGet } from './query.js';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
import { blockIncomingRequest, rateLimitRequest, endRateLimitHttp, } from '../../security.js';
import { parseAuthState, parseJSONAuthState } from '../../auth/index.js';
import { authorize } from '../../authorize.js';
import { end } from '../../sendHttpResponse.js';
import { httpPublish } from './publish.js';
import { handleRequest } from './handleRequest.js';
let clientId = 0;
const handleRequest = (server, method, ctx, route, ready) => {
if (method === 'post') {
(0, readBody_1.readBody)(server, ctx, ready, route);
}
else {
ready((0, parseQuery_1.default)(ctx));
}
};
const getQuery = (req) => {
const obj = {};
const string = req.getQuery();
let index = 0;
let index2;
let index3;
do {
index2 = string.indexOf('=', index);
if (index2 === -1) {
index2 = string.length;
}
index3 = string.indexOf('&', index2 + 1);
if (index3 === -1) {
index3 = string.length;
}
obj[string.slice(index, index2)] = string.slice(index2 + 1, index3);
index = index3 + 1;
} while (index3 !== string.length);
return obj;
};
const httpHandler = (server, req, res) => {
export const httpHandler = (server, req, res) => {
res.onAborted(() => {

@@ -56,3 +21,3 @@ ctx.session.res = null;

const ip = server.getIp(res, req);
if ((0, security_1.blockIncomingRequest)(server, ip, res, req, server.rateLimit.http, 1)) {
if (blockIncomingRequest(server, ip, res, req, server.rateLimit.http, 1)) {
return;

@@ -65,3 +30,3 @@ }

if (route === null || route.internalOnly === true) {
(0, sendError_1.sendError)(server, {
sendError(server, {
session: {

@@ -79,3 +44,3 @@ url,

},
}, error_1.BasedErrorCode.FunctionNotFound, path[1]
}, BasedErrorCode.FunctionNotFound, path[1]
? { route: { name: path[1], type: 'function' } }

@@ -88,28 +53,22 @@ : { route: { name: '', path: url, type: 'function' } });

let authorization = req.getHeader('authorization');
if (!authorization && req.getQuery()) {
const query = getQuery(req);
if (query.authorization) {
authorization = query.authorization;
if (authorization) {
if (authorization.length > 5e3) {
sendError(server, {
session: {
url,
ua: req.getHeader('user-agent'),
ip,
method,
origin: req.getHeader('origin'),
id: ++clientId,
headers: {},
authState: {},
res,
req,
},
}, BasedErrorCode.PayloadTooLarge, { route: { name: 'authorize', type: 'function' } });
return;
}
authState = parseAuthState(authorization);
}
if (authorization.length > 5e3) {
(0, sendError_1.sendError)(server, {
session: {
url,
ua: req.getHeader('user-agent'),
ip,
method,
origin: req.getHeader('origin'),
id: ++clientId,
headers: {},
authState: {},
res,
req,
},
}, error_1.BasedErrorCode.PayloadTooLarge, { route: { name: 'authorize', type: 'function' } });
return;
}
if (authorization) {
authState = (0, auth_1.parseAuthState)(authorization);
}
else {

@@ -119,3 +78,3 @@ // TODO: remove this when c++ client can encode

if (authorization) {
authState = (0, auth_1.parseJSONAuthState)(authorization);
authState = parseJSONAuthState(authorization);
}

@@ -167,4 +126,4 @@ }

}
if ((0, security_1.rateLimitRequest)(server, ctx, route.rateLimitTokens, server.rateLimit.http)) {
(0, security_1.endRateLimitHttp)(res);
if (rateLimitRequest(server, ctx, route.rateLimitTokens, server.rateLimit.http)) {
endRateLimitHttp(res);
return;

@@ -184,3 +143,3 @@ }

// Zero allowed, but not for streams
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.LengthRequired, route);
sendError(server, ctx, BasedErrorCode.LengthRequired, route);
return;

@@ -196,6 +155,6 @@ }

}
if ((0, functions_1.isBasedRoute)('query', route)) {
if (isBasedRoute('query', route)) {
// Handle HEAD
if (method !== 'post' && method !== 'get') {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.MethodNotAllowed, route);
sendError(server, ctx, BasedErrorCode.MethodNotAllowed, route);
return;

@@ -207,13 +166,13 @@ }

handleRequest(server, method, ctx, route, (payload) => {
(0, query_1.httpGet)(route, payload, ctx, server, checksum);
httpGet(route, payload, ctx, server, checksum);
});
return;
}
if ((0, functions_1.isBasedRoute)('stream', route)) {
if (isBasedRoute('stream', route)) {
if (method === 'options') {
(0, sendHttpResponse_1.end)(ctx);
end(ctx);
return;
}
if (method !== 'post') {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.MethodNotAllowed, route);
sendError(server, ctx, BasedErrorCode.MethodNotAllowed, route);
return;

@@ -223,29 +182,28 @@ }

// Zero is also not allowed for streams
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.LengthRequired, route);
sendError(server, ctx, BasedErrorCode.LengthRequired, route);
return;
}
(0, streamFunction_1.httpStreamFunction)(server, ctx, route);
httpStreamFunction(server, ctx, route);
return;
}
if ((0, functions_1.isBasedRoute)('channel', route)) {
if (isBasedRoute('channel', route)) {
if (method !== 'post' && method !== 'get') {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.MethodNotAllowed, route);
sendError(server, ctx, BasedErrorCode.MethodNotAllowed, route);
return;
}
handleRequest(server, method, ctx, route, (payload) => {
(0, authorize_1.authorize)(route, server, ctx, payload, publish_1.httpPublish, undefined, undefined, route.publicPublisher || route.public);
authorize(route, server, ctx, payload, httpPublish, undefined, undefined, route.publicPublisher || route.public);
});
return;
}
if ((0, functions_1.isBasedRoute)('function', route)) {
if (isBasedRoute('function', route)) {
if (method !== 'post' && method !== 'get') {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.MethodNotAllowed, route);
sendError(server, ctx, BasedErrorCode.MethodNotAllowed, route);
return;
}
handleRequest(server, method, ctx, route, (payload) => {
(0, authorize_1.authorize)(route, server, ctx, payload, function_1.httpFunction);
authorize(route, server, ctx, payload, httpFunction);
});
}
};
exports.httpHandler = httpHandler;
//# sourceMappingURL=index.js.map

@@ -1,5 +0,4 @@

import { Context, HttpSession } from '@based/functions';
import { BasedRoute, Context, HttpSession } from '@based/functions';
import { parseQuery } from '@saulx/utils';
declare const _default: (ctx: Context<HttpSession>) => ReturnType<typeof parseQuery>;
declare const _default: (ctx: Context<HttpSession>, route: BasedRoute) => ReturnType<typeof parseQuery>;
export default _default;
//# sourceMappingURL=parseQuery.d.ts.map

@@ -1,6 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@saulx/utils");
const auth_1 = require("../../auth");
exports.default = (ctx) => {
import { parseQuery } from '@saulx/utils';
import { parseAuthState } from '../../auth/index.js';
export default (ctx, route) => {
if (!('query' in ctx.session)) {

@@ -13,4 +11,4 @@ return;

try {
ctx.session.parsedQuery = (0, utils_1.parseQuery)(ctx.session.query);
// TODO chekc if this is a good idea (can also call it 'autState')
ctx.session.parsedQuery = parseQuery(ctx.session.query);
// TODO check if this is a good idea (can also call it 'authState')
if (!ctx.session.authState.token &&

@@ -20,3 +18,6 @@ !ctx.session.authState.refreshToken &&

'token' in ctx.session.parsedQuery) {
ctx.session.authState = (0, auth_1.parseAuthState)(ctx.session.parsedQuery.token);
ctx.session.authState = parseAuthState(ctx.session.parsedQuery.token);
if (route.type === 'query') {
delete ctx.session.parsedQuery.token;
}
}

@@ -23,0 +24,0 @@ return ctx.session.parsedQuery;

import { HttpSession } from '@based/functions';
import { IsAuthorizedHandler } from '../../authorize';
import { IsAuthorizedHandler } from '../../authorize.js';
export declare const httpPublish: IsAuthorizedHandler<HttpSession>;
//# sourceMappingURL=publish.d.ts.map

@@ -1,11 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.httpPublish = void 0;
const sendHttpResponse_1 = require("../../sendHttpResponse");
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
const installFn_1 = require("../../installFn");
const query_1 = require("../../query");
const channel_1 = require("../../channel");
const httpPublish = async (route, spec, server, ctx, payload) => {
import { sendHttpResponse } from '../../sendHttpResponse.js';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
import { installFn } from '../../installFn.js';
import { genObservableId } from '../../query/index.js';
import { hasChannel, createChannel, destroyChannel, extendChannel, } from '../../channel/index.js';
export const httpPublish = async (route, _spec, server, ctx, payload) => {
// parse channel payload / msg

@@ -46,13 +43,13 @@ let msg;

const name = route.name;
const id = (0, query_1.genObservableId)(name, channelPayload);
(0, installFn_1.installFn)(server, ctx, route).then(async (spec) => {
const id = genObservableId(name, channelPayload);
installFn(server, ctx, route).then(async (spec) => {
if (spec === null) {
return;
}
if (!(0, channel_1.hasChannel)(server, id)) {
(0, channel_1.createChannel)(server, name, id, channelPayload, true);
(0, channel_1.destroyChannel)(server, id);
if (!hasChannel(server, id)) {
createChannel(server, name, id, channelPayload, true);
destroyChannel(server, id);
}
else {
(0, channel_1.extendChannel)(server, server.activeChannelsById.get(id));
extendChannel(server, server.activeChannelsById.get(id));
}

@@ -63,3 +60,3 @@ try {

const send = (responseData, headers, status) => {
(0, sendHttpResponse_1.sendHttpResponse)(ctx, responseData, headers, status !== undefined
sendHttpResponse(ctx, responseData, headers, status !== undefined
? typeof status === 'string'

@@ -73,6 +70,6 @@ ? status

}
(0, sendHttpResponse_1.sendHttpResponse)(ctx, undefined);
sendHttpResponse(ctx, undefined);
}
catch (err) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
err,

@@ -84,3 +81,2 @@ route,

};
exports.httpPublish = httpPublish;
//# sourceMappingURL=publish.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../../server';
import { BasedServer } from '../../server.js';
import { HttpSession, Context, BasedRoute } from '@based/functions';
export declare const httpGet: (route: BasedRoute<'query'>, payload: any, ctx: Context<HttpSession>, server: BasedServer, checksum: number) => void;
//# sourceMappingURL=query.d.ts.map

@@ -1,21 +0,14 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.httpGet = void 0;
const sendHttpResponse_1 = require("../../sendHttpResponse");
const compress_1 = require("../../compress");
const query_1 = require("../../query");
const node_zlib_1 = __importDefault(require("node:zlib"));
const utils_1 = require("@saulx/utils");
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
const node_util_1 = require("node:util");
const authorize_1 = require("../../authorize");
const inflate = (0, node_util_1.promisify)(node_zlib_1.default.inflateRaw);
import { end, sendHeaders } from '../../sendHttpResponse.js';
import { compress } from '../../compress.js';
import { createObs, destroyObs, getObsAndStopRemove, hasObs, sendObsGetError, subscribeNext, start, genObservableId, } from '../../query/index.js';
import zlib from 'node:zlib';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
import { promisify } from 'node:util';
import { authorize } from '../../authorize.js';
const inflate = promisify(zlib.inflateRaw);
const sendCacheSwapEncoding = async (server, route, ctx, buffer, checksum, headers, status = '200 OK') => {
try {
const inflated = await inflate(buffer.slice(20));
const { payload, encoding } = await (0, compress_1.compress)(inflated, ctx.session.headers.encoding);
const { payload, encoding } = await compress(inflated, ctx.session.headers.encoding);
if (!ctx.session.res) {

@@ -26,3 +19,3 @@ return;

if (headers) {
(0, sendHttpResponse_1.sendHeaders)(ctx, headers);
sendHeaders(ctx, headers);
}

@@ -34,7 +27,7 @@ ctx.session.res.writeStatus(status);

ctx.session.res.writeHeader('ETag', String(checksum));
(0, sendHttpResponse_1.end)(ctx, payload);
end(ctx, payload);
});
}
catch (err) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.UnsupportedContentEncoding, route);
sendError(server, ctx, BasedErrorCode.UnsupportedContentEncoding, route);
}

@@ -45,3 +38,3 @@ };

if (headers) {
(0, sendHttpResponse_1.sendHeaders)(ctx, headers);
sendHeaders(ctx, headers);
}

@@ -53,3 +46,3 @@ ctx.session.res.writeStatus(status);

}
(0, sendHttpResponse_1.end)(ctx, buffer.slice(20));
end(ctx, buffer.slice(20));
});

@@ -60,6 +53,6 @@ };

if (headers) {
(0, sendHttpResponse_1.sendHeaders)(ctx, headers);
sendHeaders(ctx, headers);
}
ctx.session.res.writeStatus(status);
(0, sendHttpResponse_1.end)(ctx);
end(ctx);
});

@@ -69,3 +62,3 @@ };

if (!ctx.session) {
(0, query_1.destroyObs)(server, id);
destroyObs(server, id);
return;

@@ -76,3 +69,3 @@ }

if (!obs.cache) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.NoOservableCacheAvailable, {
sendError(server, ctx, BasedErrorCode.NoOservableCacheAvailable, {
observableId: id,

@@ -97,3 +90,3 @@ route: { name: obs.name, type: 'query' },

}
(0, query_1.destroyObs)(server, id);
destroyObs(server, id);
};

@@ -103,3 +96,3 @@ const sendGetResponse = (route, spec, server, id, obs, checksum, ctx) => {

// response data does not work for query responses
const send = (responseData, headers, status) => {
const send = (_responseData, headers, status) => {
sendGetResponseInternal(route, server, id, obs, checksum, ctx, headers, typeof status === 'string' ? status : String(status));

@@ -113,3 +106,3 @@ };

const getFromExisting = (server, id, ctx, route, spec, checksum) => {
const obs = (0, query_1.getObsAndStopRemove)(server, id);
const obs = getObsAndStopRemove(server, id);
if (server.queryEvents) {

@@ -119,3 +112,3 @@ server.queryEvents.get(obs, ctx);

if (obs.error) {
(0, query_1.sendObsGetError)(server, ctx, obs.id, obs.error);
sendObsGetError(server, ctx, obs.id, obs.error);
return;

@@ -127,3 +120,3 @@ }

}
(0, query_1.subscribeNext)(obs, (err) => {
subscribeNext(obs, (err) => {
if (!ctx.session) {

@@ -133,3 +126,3 @@ return;

if (err) {
(0, query_1.sendObsGetError)(server, ctx, obs.id, err);
sendObsGetError(server, ctx, obs.id, err);
}

@@ -143,13 +136,13 @@ else {

const name = route.name;
if ((0, query_1.hasObs)(server, id)) {
if (hasObs(server, id)) {
getFromExisting(server, id, ctx, route, spec, checksum);
return;
}
const obs = (0, query_1.createObs)(server, name, id, payload, true);
const obs = createObs(server, name, id, payload, true);
if (server.queryEvents) {
server.queryEvents.get(obs, ctx);
}
(0, query_1.subscribeNext)(obs, (err) => {
subscribeNext(obs, (err) => {
if (err) {
(0, query_1.sendObsGetError)(server, ctx, obs.id, err);
sendObsGetError(server, ctx, obs.id, err);
}

@@ -160,17 +153,10 @@ else {

});
(0, query_1.start)(server, id);
start(server, id);
};
const httpGet = (route, payload, ctx, server, checksum) => {
export const httpGet = (route, payload, ctx, server, checksum) => {
if (!ctx.session) {
return;
}
if (payload === undefined && 'query' in ctx.session) {
try {
payload = (0, utils_1.parseQuery)(decodeURIComponent(ctx.session.query));
}
catch (err) { }
}
(0, authorize_1.authorize)(route, server, ctx, payload, isAuthorized, (0, query_1.genObservableId)(route.name, payload), checksum);
authorize(route, server, ctx, payload, isAuthorized, genObservableId(route.name, payload), checksum);
};
exports.httpGet = httpGet;
//# sourceMappingURL=query.js.map
import { HttpSession, Context, BasedRoute } from '@based/functions';
import { BasedServer } from '../../server';
import { BasedServer } from '../../server.js';
export declare const parseHttpPayload: (server: BasedServer, ctx: Context<HttpSession>, data: Uint8Array, route: BasedRoute) => any;
export declare const readBody: (server: BasedServer, ctx: Context<HttpSession>, onData: (data: any | void) => void, route: BasedRoute) => void;
//# sourceMappingURL=readBody.d.ts.map

@@ -1,10 +0,4 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readBody = exports.parseHttpPayload = void 0;
const node_zlib_1 = __importDefault(require("node:zlib"));
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
import zlib from 'node:zlib';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
const decoder = new TextDecoder('utf-8');

@@ -16,3 +10,3 @@ const MAX_CHUNK_SIZE = 1024 * 1024;

};
const parseHttpPayload = (server, ctx, data, route) => {
export const parseHttpPayload = (server, ctx, data, route) => {
const contentType = ctx.session.headers['content-type'];

@@ -30,3 +24,3 @@ if (!contentType || contentType.startsWith('application/json')) {

catch (err) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.InvalidPayload, { route });
sendError(server, ctx, BasedErrorCode.InvalidPayload, { route });
}

@@ -42,4 +36,3 @@ }

};
exports.parseHttpPayload = parseHttpPayload;
const readBody = (server, ctx, onData, route) => {
export const readBody = (server, ctx, onData, route) => {
if (!ctx.session) {

@@ -50,3 +43,3 @@ return;

if (contentLen > route.maxPayloadSize) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.PayloadTooLarge, { route });
sendError(server, ctx, BasedErrorCode.PayloadTooLarge, { route });
return;

@@ -59,9 +52,9 @@ }

if (contentEncoding === 'deflate') {
uncompressStream = node_zlib_1.default.createInflate(UNCOMPRESS_OPTS);
uncompressStream = zlib.createInflate(UNCOMPRESS_OPTS);
}
else if (contentEncoding === 'gzip') {
uncompressStream = node_zlib_1.default.createGunzip(UNCOMPRESS_OPTS);
uncompressStream = zlib.createGunzip(UNCOMPRESS_OPTS);
}
else if (contentEncoding === 'br') {
uncompressStream = node_zlib_1.default.createBrotliDecompress(UNCOMPRESS_OPTS);
uncompressStream = zlib.createBrotliDecompress(UNCOMPRESS_OPTS);
}

@@ -72,3 +65,3 @@ if (uncompressStream) {

if (size > route.maxPayloadSize) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.PayloadTooLarge, { route });
sendError(server, ctx, BasedErrorCode.PayloadTooLarge, { route });
uncompressStream.destroy();

@@ -78,3 +71,3 @@ return;

if (c.byteLength > MAX_CHUNK_SIZE) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.ChunkTooLarge, route);
sendError(server, ctx, BasedErrorCode.ChunkTooLarge, route);
uncompressStream.destroy();

@@ -110,7 +103,7 @@ return;

// readValue
onData((0, exports.parseHttpPayload)(server, ctx, buf, route));
onData(parseHttpPayload(server, ctx, buf, route));
});
}
else {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.InvalidPayload, { route });
sendError(server, ctx, BasedErrorCode.InvalidPayload, { route });
}

@@ -125,7 +118,7 @@ }

if (size > route.maxPayloadSize) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.PayloadTooLarge, { route });
sendError(server, ctx, BasedErrorCode.PayloadTooLarge, { route });
return;
}
if (c.byteLength > MAX_CHUNK_SIZE) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.ChunkTooLarge, route);
sendError(server, ctx, BasedErrorCode.ChunkTooLarge, route);
return;

@@ -137,3 +130,3 @@ }

// readValue
onData((0, exports.parseHttpPayload)(server, ctx, buf, route));
onData(parseHttpPayload(server, ctx, buf, route));
}

@@ -143,3 +136,2 @@ });

};
exports.readBody = readBody;
//# sourceMappingURL=readBody.js.map
declare const _default: (mimeType: string) => string | false;
export default _default;
//# sourceMappingURL=getExtension.d.ts.map

@@ -1,8 +0,3 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const mime_types_1 = __importDefault(require("mime-types"));
exports.default = (mimeType) => {
import mimeTypes from 'mime-types';
export default (mimeType) => {
const [mime, type] = mimeType.split('/');

@@ -19,3 +14,3 @@ if (mime === 'font') {

else {
const t = mime_types_1.default.extension(mimeType);
const t = mimeTypes.extension(mimeType);
if (t === 'markdown') {

@@ -22,0 +17,0 @@ return 'md';

@@ -1,4 +0,3 @@

import { BasedServer } from '../../../server';
import { BasedServer } from '../../../server.js';
import { HttpSession, Context, BasedRoute } from '@based/functions';
export declare const httpStreamFunction: (server: BasedServer, ctx: Context<HttpSession>, route: BasedRoute<'stream'>) => void;
//# sourceMappingURL=index.d.ts.map

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.httpStreamFunction = void 0;
const sendError_1 = require("../../../sendError");
const error_1 = require("../../../error");
const multiPart_1 = require("./multiPart");
const stream_1 = require("./stream");
const httpStreamFunction = (server, ctx, route) => {
import { sendError } from '../../../sendError.js';
import { BasedErrorCode } from '../../../error/index.js';
import { multiPart } from './multiPart/index.js';
import { singleStream } from './stream/index.js';
export const httpStreamFunction = (server, ctx, route) => {
if (!ctx.session) {

@@ -14,3 +11,3 @@ return;

if (route.maxPayloadSize > -1 && route.maxPayloadSize < size) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.PayloadTooLarge, { route });
sendError(server, ctx, BasedErrorCode.PayloadTooLarge, { route });
return;

@@ -20,8 +17,7 @@ }

if (type && type.startsWith('multipart/form-data')) {
(0, multiPart_1.multiPart)(server, ctx, route);
multiPart(server, ctx, route);
return;
}
(0, stream_1.singleStream)(server, ctx, route, type, size);
singleStream(server, ctx, route, type, size);
};
exports.httpStreamFunction = httpStreamFunction;
//# sourceMappingURL=index.js.map
import { HttpSession, Context, BasedRoute } from '@based/functions';
import { BasedServer } from '../../../../server';
import { BasedServer } from '../../../../server.js';
export declare const multiPart: (server: BasedServer, ctx: Context<HttpSession>, route: BasedRoute<'stream'>) => void;
//# sourceMappingURL=index.d.ts.map

@@ -1,11 +0,5 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.multiPart = void 0;
const installFn_1 = require("../../../../installFn");
const readFormData_1 = __importDefault(require("./readFormData"));
const error_1 = require("../../../../error");
const sendHttpResponse_1 = require("../../../../sendHttpResponse");
import { installFn } from '../../../../installFn.js';
import readFormData from './readFormData.js';
import { BasedErrorCode, createErrorData, } from '../../../../error/index.js';
import { sendHttpResponse } from '../../../../sendHttpResponse.js';
const handleFile = async (server, ctx, installedFn, file, route) => {

@@ -15,3 +9,3 @@ const spec = await installedFn;

return {
error: (0, error_1.createErrorData)(error_1.BasedErrorCode.FunctionNotFound, {
error: createErrorData(BasedErrorCode.FunctionNotFound, {
route,

@@ -25,3 +19,3 @@ }),

return {
error: (0, error_1.createErrorData)(error_1.BasedErrorCode.AuthorizeRejectedError, {
error: createErrorData(BasedErrorCode.AuthorizeRejectedError, {
route,

@@ -34,3 +28,3 @@ }),

return {
error: (0, error_1.createErrorData)(error_1.BasedErrorCode.AuthorizeFunctionError, {
error: createErrorData(BasedErrorCode.AuthorizeFunctionError, {
route,

@@ -47,8 +41,8 @@ err,

return {
error: (0, error_1.createErrorData)(error_1.BasedErrorCode.FunctionError, { err, route }),
error: createErrorData(BasedErrorCode.FunctionError, { err, route }),
};
}
};
const multiPart = (server, ctx, route) => {
const installedFn = (0, installFn_1.installFn)(server, server.client.ctx, route);
export const multiPart = (server, ctx, route) => {
const installedFn = installFn(server, server.client.ctx, route);
const pendingFiles = [];

@@ -61,8 +55,7 @@ const onFile = (file) => {

if (ctx.session) {
(0, sendHttpResponse_1.sendHttpResponse)(ctx, results);
sendHttpResponse(ctx, results);
}
};
(0, readFormData_1.default)(ctx, server, route, onFile, ready);
readFormData(ctx, server, route, onFile, ready);
};
exports.multiPart = multiPart;
//# sourceMappingURL=index.js.map
import { HttpSession, Context, StreamPayload, BasedRoute } from '@based/functions';
import { BasedServer } from '../../../../server';
import { BasedServer } from '../../../../server.js';
export type FileOptions = {

@@ -12,2 +12,1 @@ name?: string;

export default _default;
//# sourceMappingURL=readFormData.d.ts.map

@@ -1,10 +0,5 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const functions_1 = require("@based/functions");
const error_1 = require("../../../../error");
const sendError_1 = require("../../../../sendError");
const getExtension_1 = __importDefault(require("../getExtension"));
import { BasedDataStream, } from '@based/functions';
import { BasedErrorCode } from '../../../../error/index.js';
import { sendError } from '../../../../sendError.js';
import getExtension from '../getExtension.js';
const MAX_CHUNK_SIZE = 1024 * 1024 * 5;

@@ -56,3 +51,3 @@ // only use this if you have an individual file else its just all

};
exports.default = (ctx, server, route, onFile, isReady) => {
export default (ctx, server, route, onFile, isReady) => {
const files = [];

@@ -70,3 +65,3 @@ const contentLength = ctx.session.headers['content-length'];

if (chunk.byteLength > MAX_CHUNK_SIZE) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.ChunkTooLarge, route);
sendError(server, ctx, BasedErrorCode.ChunkTooLarge, route);
for (const file of files) {

@@ -126,3 +121,3 @@ file.stream.destroy();

const file = {
stream: new functions_1.BasedDataStream(0),
stream: new BasedDataStream(0),
headersSet: 0,

@@ -138,3 +133,3 @@ opts: {},

// TODO: invalid file error
return (0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.InvalidPayload, { route });
return sendError(server, ctx, BasedErrorCode.InvalidPayload, { route });
}

@@ -160,3 +155,3 @@ if (!isWriting && collectMeta) {

// TODO: invalid file error
return (0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.InvalidPayload, {
return sendError(server, ctx, BasedErrorCode.InvalidPayload, {
route,

@@ -172,3 +167,3 @@ });

// TODO: invalid file (can speficy in route potentialy...)
return (0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.InvalidPayload, {
return sendError(server, ctx, BasedErrorCode.InvalidPayload, {
route,

@@ -178,3 +173,3 @@ });

file.opts.type = mimeType;
const extension = (0, getExtension_1.default)(mimeType);
const extension = getExtension(mimeType);
if (extension) {

@@ -181,0 +176,0 @@ file.opts.extension = extension;

import { HttpSession, Context, BasedDataStream, BasedRoute } from '@based/functions';
import { BasedServer } from '../../../../server';
import { BasedServer } from '../../../../server.js';
declare const _default: (server: BasedServer, route: BasedRoute<'stream'>, ctx: Context<HttpSession>, size: number) => BasedDataStream;
export default _default;
//# sourceMappingURL=createStream.d.ts.map

@@ -1,10 +0,5 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const functions_1 = require("@based/functions");
const sendError_1 = require("../../../../sendError");
const node_zlib_1 = __importDefault(require("node:zlib"));
const error_1 = require("../../../../error");
import { BasedDataStream, } from '@based/functions';
import { sendError } from '../../../../sendError.js';
import zlib from 'node:zlib';
import { BasedErrorCode } from '../../../../error/index.js';
const MAX_CHUNK_SIZE = 1024 * 1024 * 5;

@@ -14,4 +9,4 @@ const UNCOMPRESS_OPTS = {

};
exports.default = (server, route, ctx, size) => {
const stream = new functions_1.BasedDataStream(size);
export default (server, route, ctx, size) => {
const stream = new BasedDataStream(size);
const contentEncoding = ctx.session.headers['content-encoding'];

@@ -21,9 +16,9 @@ if (contentEncoding) {

if (contentEncoding === 'deflate') {
uncompressStream = node_zlib_1.default.createInflate(UNCOMPRESS_OPTS);
uncompressStream = zlib.createInflate(UNCOMPRESS_OPTS);
}
else if (contentEncoding === 'gzip') {
uncompressStream = node_zlib_1.default.createGunzip(UNCOMPRESS_OPTS);
uncompressStream = zlib.createGunzip(UNCOMPRESS_OPTS);
}
else if (contentEncoding === 'br') {
uncompressStream = node_zlib_1.default.createBrotliDecompress(UNCOMPRESS_OPTS);
uncompressStream = zlib.createBrotliDecompress(UNCOMPRESS_OPTS);
}

@@ -33,3 +28,3 @@ if (uncompressStream) {

if (c.byteLength > MAX_CHUNK_SIZE) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.ChunkTooLarge, route);
sendError(server, ctx, BasedErrorCode.ChunkTooLarge, route);
uncompressStream.destroy();

@@ -51,3 +46,3 @@ stream.destroy();

console.warn('Uncompress error', route, contentEncoding, err);
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.ChunkTooLarge, route);
sendError(server, ctx, BasedErrorCode.ChunkTooLarge, route);
uncompressStream.destroy();

@@ -59,3 +54,3 @@ stream.destroy();

else {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.UnsupportedContentEncoding, route);
sendError(server, ctx, BasedErrorCode.UnsupportedContentEncoding, route);
}

@@ -66,3 +61,3 @@ }

if (c.byteLength > MAX_CHUNK_SIZE) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.ChunkTooLarge, route);
sendError(server, ctx, BasedErrorCode.ChunkTooLarge, route);
stream.destroy();

@@ -69,0 +64,0 @@ return;

@@ -1,4 +0,3 @@

import { BasedServer } from '../../../../server';
import { BasedServer } from '../../../../server.js';
import { HttpSession, Context, BasedRoute } from '@based/functions';
export declare const singleStream: (server: BasedServer, ctx: Context<HttpSession>, route: BasedRoute<'stream'>, type: string, size: number) => void;
//# sourceMappingURL=index.d.ts.map

@@ -1,21 +0,15 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.singleStream = void 0;
const createStream_1 = __importDefault(require("./createStream"));
const sendError_1 = require("../../../../sendError");
const getExtension_1 = __importDefault(require("../getExtension"));
const error_1 = require("../../../../error");
const sendHttpResponse_1 = require("../../../../sendHttpResponse");
const mime_types_1 = __importDefault(require("mime-types"));
const utils_1 = require("@saulx/utils");
const installFn_1 = require("../../../../installFn");
const authorize_1 = require("../../../../authorize");
const singleStream = (server, ctx, route, type, size) => {
import createDataStream from './createStream.js';
import { sendError } from '../../../../sendError.js';
import getExtension from '../getExtension.js';
import { BasedErrorCode } from '../../../../error/index.js';
import { sendHttpResponse } from '../../../../sendHttpResponse.js';
import mimeTypes from 'mime-types';
import { parseQuery } from '@saulx/utils';
import { installFn } from '../../../../installFn.js';
import { authorize } from '../../../../authorize.js';
export const singleStream = (server, ctx, route, type, size) => {
const extension = ctx.session.req.getHeader('content-extension');
const fileName = ctx.session.req.getHeader('content-name') || '';
if (extension) {
const mime = mime_types_1.default.lookup(extension);
const mime = mimeTypes.lookup(extension);
if (mime) {

@@ -25,7 +19,7 @@ type = ctx.session.headers['content-type'] = mime;

}
const stream = (0, createStream_1.default)(server, route, ctx, size);
const stream = createDataStream(server, route, ctx, size);
let payload;
if ('query' in ctx.session) {
try {
payload = (0, utils_1.parseQuery)(decodeURIComponent(ctx.session.query));
payload = parseQuery(decodeURIComponent(ctx.session.query));
}

@@ -40,6 +34,6 @@ catch (err) { }

fileName,
extension: (0, getExtension_1.default)(type) || '',
extension: getExtension(type) || '',
};
(0, authorize_1.authorize)(route, server, ctx, streamPayload, () => {
(0, installFn_1.installFn)(server, ctx, route).then((spec) => {
authorize(route, server, ctx, streamPayload, () => {
installFn(server, ctx, route).then((spec) => {
if (spec === null) {

@@ -52,3 +46,3 @@ stream.destroy();

.catch((err) => {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
err,

@@ -60,7 +54,7 @@ route,

if (stream.readableEnded || stream.listenerCount('data') === 0) {
(0, sendHttpResponse_1.sendHttpResponse)(ctx, r);
sendHttpResponse(ctx, r);
}
else {
stream.on('end', () => {
(0, sendHttpResponse_1.sendHttpResponse)(ctx, r);
sendHttpResponse(ctx, r);
});

@@ -74,3 +68,2 @@ }

};
exports.singleStream = singleStream;
//# sourceMappingURL=index.js.map

@@ -1,4 +0,3 @@

import type { BasedServer, ServerOptions } from '../server';
import type { BasedServer, ServerOptions } from '../server.js';
declare const _default: (server: BasedServer, { key, cert, port, ws: wsOptions, disableRest, disableWs }: ServerOptions) => void;
export default _default;
//# sourceMappingURL=index.d.ts.map

@@ -1,16 +0,11 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const uws_1 = __importDefault(require("@based/uws"));
const upgrade_1 = require("./upgrade");
const ws_1 = require("./ws");
const query_1 = require("../query");
const channel_1 = require("../channel");
const http_1 = require("./http");
const auth_1 = require("./ws/auth");
exports.default = (server, { key, cert, port, ws: wsOptions = {}, disableRest, disableWs }) => {
import uws from '@based/uws';
import { upgradeAuthorize, upgrade } from './upgrade.js';
import { message } from './ws/index.js';
import { unsubscribeWsIgnoreClient } from '../query/index.js';
import { unsubscribeChannelIgnoreClient } from '../channel/index.js';
import { httpHandler } from './http/index.js';
import { sendAndVerifyAuthMessage } from './ws/auth.js';
export default (server, { key, cert, port, ws: wsOptions = {}, disableRest, disableWs }) => {
const app = key && cert
? uws_1.default.SSLApp({
? uws.SSLApp({
key_file_name: key,

@@ -20,3 +15,3 @@ cert_file_name: cert,

})
: uws_1.default.App();
: uws.App();
if (port) {

@@ -44,6 +39,6 @@ server.port = port;

? (res, req, ctx) => {
(0, upgrade_1.upgradeAuthorize)(server, res, req, ctx);
upgradeAuthorize(server, res, req, ctx);
}
: (res, req, ctx) => {
(0, upgrade_1.upgrade)(server, res, req, ctx);
upgrade(server, res, req, ctx);
},

@@ -53,3 +48,3 @@ message: (ws, data, isBinary) => {

// @ts-ignore
(0, ws_1.message)(server, session.c, data, isBinary);
message(server, session.c, data, isBinary);
},

@@ -66,3 +61,3 @@ open: (ws) => {

if (session.authState.token || session.authState.refreshToken) {
(0, auth_1.sendAndVerifyAuthMessage)(server, ctx);
sendAndVerifyAuthMessage(server, ctx);
}

@@ -74,5 +69,5 @@ }

session.obs.forEach((id) => {
if ((0, query_1.unsubscribeWsIgnoreClient)(server, id, session.c)) {
if (unsubscribeWsIgnoreClient(server, id, session.c)) {
// This is here for channels so we do not need to keep a seperate obs set on clients
(0, channel_1.unsubscribeChannelIgnoreClient)(server, id, session.c);
unsubscribeChannelIgnoreClient(server, id, session.c);
}

@@ -97,5 +92,5 @@ });

if (!disableRest) {
app.get('/*', (res, req) => (0, http_1.httpHandler)(server, req, res));
app.post('/*', (res, req) => (0, http_1.httpHandler)(server, req, res));
app.options('/*', (res, req) => (0, http_1.httpHandler)(server, req, res));
app.get('/*', (res, req) => httpHandler(server, req, res));
app.post('/*', (res, req) => httpHandler(server, req, res));
app.options('/*', (res, req) => httpHandler(server, req, res));
}

@@ -102,0 +97,0 @@ server.uwsApp = app;

import uws from '@based/uws';
import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
export declare const upgrade: (server: BasedServer, res: uws.HttpResponse, req: uws.HttpRequest, ctx: uws.us_socket_context_t) => void;
export declare const upgradeAuthorize: (server: BasedServer, res: uws.HttpResponse, req: uws.HttpRequest, ctx: uws.us_socket_context_t) => void;
//# sourceMappingURL=upgrade.d.ts.map

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.upgradeAuthorize = exports.upgrade = void 0;
const auth_1 = require("../auth");
const security_1 = require("../security");
import { parseAuthState } from '../auth/index.js';
import { blockIncomingRequest } from '../security.js';
// import { BasedErrorCode } from '../error'
let clientId = 0;
const upgradeInternal = (server, res, req,
const upgradeInternal = (_server, res, req,
// eslint-disable-next-line

@@ -40,3 +37,3 @@ ctx, ip) => {

authState: secWebSocketProtocol
? (0, auth_1.parseAuthState)(secWebSocketProtocol)
? parseAuthState(secWebSocketProtocol)
: {},

@@ -47,7 +44,7 @@ origin,

};
const upgrade = (server, res, req,
export const upgrade = (server, res, req,
// eslint-disable-next-line
ctx) => {
const ip = server.getIp(res, req);
if ((0, security_1.blockIncomingRequest)(server, ip, res, req, server.rateLimit.ws, 10)) {
if (blockIncomingRequest(server, ip, res, req, server.rateLimit.ws, 10)) {
return;

@@ -57,4 +54,3 @@ }

};
exports.upgrade = upgrade;
const upgradeAuthorize = (server, res, req,
export const upgradeAuthorize = (server, res, req,
// eslint-disable-next-line

@@ -67,3 +63,3 @@ ctx) => {

const ip = server.getIp(res, req);
if ((0, security_1.blockIncomingRequest)(server, ip, res, req, server.rateLimit.ws, 10)) {
if (blockIncomingRequest(server, ip, res, req, server.rateLimit.ws, 10)) {
return;

@@ -84,3 +80,2 @@ }

};
exports.upgradeAuthorize = upgradeAuthorize;
//# sourceMappingURL=upgrade.js.map

@@ -1,7 +0,6 @@

import { BasedServer } from '../../server';
import { BasedServer } from '../../server.js';
import { WebSocketSession, Context } from '@based/functions';
import { BinaryMessageHandler } from './types';
import { BinaryMessageHandler } from './types.js';
export declare const reEvaulateUnauthorized: (server: BasedServer, ctx: Context<WebSocketSession>) => void;
export declare const authMessage: BinaryMessageHandler;
export declare const sendAndVerifyAuthMessage: (server: BasedServer, ctx: Context<WebSocketSession>) => Promise<void>;
//# sourceMappingURL=auth.d.ts.map

@@ -1,11 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendAndVerifyAuthMessage = exports.authMessage = exports.reEvaulateUnauthorized = void 0;
const protocol_1 = require("../../protocol");
const query_1 = require("./query");
const security_1 = require("../../security");
const channelSubscribe_1 = require("./channelSubscribe");
const installFn_1 = require("../../installFn");
const authorize_1 = require("../../authorize");
const sendAuthMessage = (ctx, payload) => ctx.session?.ws.send((0, protocol_1.encodeAuthResponse)((0, protocol_1.valueToBuffer)(payload)), true, false);
import { valueToBuffer, decodePayload, encodeAuthResponse, } from '../../protocol.js';
import { enableSubscribe } from './query.js';
import { rateLimitRequest } from '../../security.js';
import { enableChannelSubscribe } from './channelSubscribe.js';
import { installFn } from '../../installFn.js';
import { authorize } from '../../authorize.js';
const sendAuthMessage = (ctx, payload) => ctx.session?.ws.send(encodeAuthResponse(valueToBuffer(payload)), true, false);
const parse = (payload) => {

@@ -19,3 +16,3 @@ try {

};
const reEvaulateUnauthorized = (server, ctx) => {
export const reEvaulateUnauthorized = (server, ctx) => {
const session = ctx.session;

@@ -32,7 +29,7 @@ if (!session) {

};
(0, installFn_1.installFn)(server, ctx, route, id).then((spec) => {
(0, authorize_1.authorize)(route, server, ctx, payload, () => {
installFn(server, ctx, route, id).then((spec) => {
authorize(route, server, ctx, payload, () => {
session.unauthorizedObs.delete(obs);
if (spec) {
(0, query_1.enableSubscribe)(route, spec, server, ctx, payload, id, checksum);
enableSubscribe(route, spec, server, ctx, payload, id, checksum);
}

@@ -50,7 +47,7 @@ });

};
(0, installFn_1.installFn)(server, ctx, route, id).then((spec) => {
(0, authorize_1.authorize)(route, server, ctx, payload, () => {
installFn(server, ctx, route, id).then((spec) => {
authorize(route, server, ctx, payload, () => {
session.unauthorizedChannels.delete(channel);
if (spec) {
(0, channelSubscribe_1.enableChannelSubscribe)(route, spec, server, ctx, payload, id);
enableChannelSubscribe(route, spec, server, ctx, payload, id);
}

@@ -62,5 +59,4 @@ });

};
exports.reEvaulateUnauthorized = reEvaulateUnauthorized;
const authMessage = (arr, start, len, isDeflate, ctx, server) => {
if ((0, security_1.rateLimitRequest)(server, ctx, 10, server.rateLimit.ws)) {
export const authMessage = (arr, start, len, isDeflate, ctx, server) => {
if (rateLimitRequest(server, ctx, 10, server.rateLimit.ws)) {
ctx.session.ws.close();

@@ -73,3 +69,3 @@ return false;

// | 4 header | * payload |
const payload = (0, protocol_1.decodePayload)(new Uint8Array(arr.slice(start + 4, start + len)), isDeflate);
const payload = decodePayload(new Uint8Array(arr.slice(start + 4, start + len)), isDeflate);
const authState = parse(payload);

@@ -88,3 +84,3 @@ server.auth

}
(0, exports.reEvaulateUnauthorized)(server, ctx);
reEvaulateUnauthorized(server, ctx);
sendAuthMessage(ctx, verified);

@@ -105,5 +101,4 @@ })

};
exports.authMessage = authMessage;
// send and verify
const sendAndVerifyAuthMessage = async (server, ctx) => {
export const sendAndVerifyAuthMessage = async (server, ctx) => {
const session = ctx.session;

@@ -125,3 +120,2 @@ if (!session) {

};
exports.sendAndVerifyAuthMessage = sendAndVerifyAuthMessage;
//# sourceMappingURL=auth.js.map

@@ -1,3 +0,2 @@

import { BinaryMessageHandler } from './types';
import { BinaryMessageHandler } from './types.js';
export declare const channelPublishMessage: BinaryMessageHandler;
//# sourceMappingURL=channelPublish.d.ts.map

@@ -1,11 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.channelPublishMessage = void 0;
const protocol_1 = require("../../protocol");
const security_1 = require("../../security");
const verifyRoute_1 = require("../../verifyRoute");
const channel_1 = require("../../channel");
const authorize_1 = require("../../authorize");
const sendError_1 = require("../../sendError");
const error_1 = require("../../error");
import { readUint8, decodePayload, parsePayload } from '../../protocol.js';
import { rateLimitRequest } from '../../security.js';
import { verifyRoute } from '../../verifyRoute.js';
import { extendChannel, hasChannel } from '../../channel/index.js';
import { authorize } from '../../authorize.js';
import { sendError } from '../../sendError.js';
import { BasedErrorCode } from '../../error/index.js';
const publish = (route, spec, server, ctx, payload, id) => {

@@ -26,3 +23,3 @@ const channel = server.activeChannelsById.get(id);

catch (err) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
channelId: id,

@@ -34,8 +31,8 @@ err,

};
const channelPublishMessage = (arr, start, len, isDeflate, ctx, server) => {
export const channelPublishMessage = (arr, start, len, isDeflate, ctx, server) => {
// | 4 header | 8 id | * payload |
const id = (0, protocol_1.readUint8)(arr, start + 4, 8);
const id = readUint8(arr, start + 4, 8);
// how to determine it does not exist?
if (!(0, channel_1.hasChannel)(server, id)) {
if ((0, security_1.rateLimitRequest)(server, ctx, 1, server.rateLimit.ws)) {
if (!hasChannel(server, id)) {
if (rateLimitRequest(server, ctx, 1, server.rateLimit.ws)) {
ctx.session.ws.close();

@@ -48,9 +45,9 @@ return false;

const channel = server.activeChannelsById.get(id);
(0, channel_1.extendChannel)(server, channel);
extendChannel(server, channel);
const name = channel.name;
const route = (0, verifyRoute_1.verifyRoute)(server, ctx, 'channel', server.functions.route(name), name, id);
const route = verifyRoute(server, ctx, 'channel', server.functions.route(name), name, id);
if (route === null) {
return true;
}
if ((0, security_1.rateLimitRequest)(server, ctx, route.rateLimitTokens, server.rateLimit.ws)) {
if (rateLimitRequest(server, ctx, route.rateLimitTokens, server.rateLimit.ws)) {
ctx.session.ws.close();

@@ -64,7 +61,6 @@ return false;

? undefined
: (0, protocol_1.parsePayload)((0, protocol_1.decodePayload)(new Uint8Array(arr.slice(start + 12, start + len)), isDeflate));
(0, authorize_1.authorize)(route, server, ctx, payload, publish, id, undefined, route.publicPublisher);
: parsePayload(decodePayload(new Uint8Array(arr.slice(start + 12, start + len)), isDeflate));
authorize(route, server, ctx, payload, publish, id, undefined, route.publicPublisher);
return true;
};
exports.channelPublishMessage = channelPublishMessage;
//# sourceMappingURL=channelPublish.js.map
import { WebSocketSession, BasedRoute } from '@based/functions';
import { IsAuthorizedHandler } from '../../authorize';
import { BinaryMessageHandler } from './types';
import { IsAuthorizedHandler } from '../../authorize.js';
import { BinaryMessageHandler } from './types.js';
export declare const enableChannelSubscribe: IsAuthorizedHandler<WebSocketSession, BasedRoute<'channel'>>;
export declare const channelSubscribeMessage: BinaryMessageHandler;
export declare const unsubscribeChannelMessage: BinaryMessageHandler;
//# sourceMappingURL=channelSubscribe.d.ts.map

@@ -1,15 +0,12 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsubscribeChannelMessage = exports.channelSubscribeMessage = exports.enableChannelSubscribe = void 0;
const protocol_1 = require("../../protocol");
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
const security_1 = require("../../security");
const verifyRoute_1 = require("../../verifyRoute");
const installFn_1 = require("../../installFn");
const authorize_1 = require("../../authorize");
const channel_1 = require("../../channel");
const enableChannelSubscribe = (route, spec, server, ctx, payload, id) => {
if ((0, channel_1.hasChannel)(server, id)) {
(0, channel_1.subscribeChannel)(server, id, ctx);
import { readUint8, decodeName, decodePayload, parsePayload, } from '../../protocol.js';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
import { rateLimitRequest } from '../../security.js';
import { verifyRoute } from '../../verifyRoute.js';
import { installFn } from '../../installFn.js';
import { authorize, } from '../../authorize.js';
import { hasChannel, subscribeChannel, createChannel, unsubscribeChannel, destroyChannel, extendChannel, } from '../../channel/index.js';
export const enableChannelSubscribe = (route, _spec, server, ctx, payload, id) => {
if (hasChannel(server, id)) {
subscribeChannel(server, id, ctx);
return;

@@ -21,9 +18,8 @@ }

}
if (!(0, channel_1.hasChannel)(server, id)) {
(0, channel_1.createChannel)(server, route.name, id, payload, true);
if (!hasChannel(server, id)) {
createChannel(server, route.name, id, payload, true);
}
(0, channel_1.subscribeChannel)(server, id, ctx);
subscribeChannel(server, id, ctx);
};
exports.enableChannelSubscribe = enableChannelSubscribe;
const isNotAuthorized = (route, server, ctx, payload, id) => {
const isNotAuthorized = (route, _server, ctx, payload, id) => {
const session = ctx.session;

@@ -39,3 +35,3 @@ if (!session.unauthorizedChannels) {

};
const channelSubscribeMessage = (arr, start, len,
export const channelSubscribeMessage = (arr, start, len,
// isDeflate is used differently here

@@ -45,8 +41,8 @@ isChannelIdRequester, ctx, server) => {

const nameLen = arr[start + 12];
const id = (0, protocol_1.readUint8)(arr, start + 4, 8);
const name = (0, protocol_1.decodeName)(arr, start + 13, start + 13 + nameLen);
const id = readUint8(arr, start + 4, 8);
const name = decodeName(arr, start + 13, start + 13 + nameLen);
if (!name || !id) {
return false;
}
const route = (0, verifyRoute_1.verifyRoute)(server, ctx, 'channel', server.functions.route(name), name, id);
const route = verifyRoute(server, ctx, 'channel', server.functions.route(name), name, id);
const tmpRoute = route || {

@@ -58,3 +54,3 @@ rateLimitTokens: 10,

};
if ((0, security_1.rateLimitRequest)(server, ctx,
if (rateLimitRequest(server, ctx,
// Requesting the id multiple times is something that should not happen - so probably a bad actor

@@ -73,9 +69,9 @@ isChannelIdRequester

// TODO: Add authorization here....
if (!(0, channel_1.hasChannel)(server, id)) {
if (!hasChannel(server, id)) {
const payload = len === nameLen + 13
? undefined
: (0, protocol_1.parsePayload)((0, protocol_1.decodePayload)(new Uint8Array(arr.slice(start + 13 + nameLen, start + len)), false));
: parsePayload(decodePayload(new Uint8Array(arr.slice(start + 13 + nameLen, start + len)), false));
// This has to be done instantly so publish can be received immediatly
const channel = (0, channel_1.createChannel)(server, name, id, payload, true);
(0, installFn_1.installFn)(server, ctx, tmpRoute, id).then((spec) => {
const channel = createChannel(server, name, id, payload, true);
installFn(server, ctx, tmpRoute, id).then((spec) => {
if (spec === null) {

@@ -87,7 +83,7 @@ channel.doesNotExist = true;

}
(0, channel_1.destroyChannel)(server, id);
destroyChannel(server, id);
});
return true;
}
(0, channel_1.extendChannel)(server, server.activeChannelsById.get(id));
extendChannel(server, server.activeChannelsById.get(id));
return true;

@@ -100,3 +96,3 @@ }

if (len > tmpRoute.maxPayloadSize) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.PayloadTooLarge, {
sendError(server, ctx, BasedErrorCode.PayloadTooLarge, {
route: tmpRoute,

@@ -114,9 +110,8 @@ channelId: id,

? undefined
: (0, protocol_1.parsePayload)((0, protocol_1.decodePayload)(new Uint8Array(arr.slice(start + 13 + nameLen, start + len)), false));
: parsePayload(decodePayload(new Uint8Array(arr.slice(start + 13 + nameLen, start + len)), false));
session.obs.add(id);
(0, authorize_1.authorize)(route, server, ctx, payload, exports.enableChannelSubscribe, id, 0, false, isNotAuthorized);
authorize(route, server, ctx, payload, enableChannelSubscribe, id, 0, false, isNotAuthorized);
return true;
};
exports.channelSubscribeMessage = channelSubscribeMessage;
const unsubscribeChannelMessage = (arr, start, len, isDeflate, ctx, server) => {
export const unsubscribeChannelMessage = (arr, start, _len, _isDeflate, ctx, server) => {
// | 4 header | 8 id |

@@ -126,7 +121,7 @@ if (!ctx.session) {

}
const id = (0, protocol_1.readUint8)(arr, start + 4, 8);
const id = readUint8(arr, start + 4, 8);
if (!id) {
return false;
}
if ((0, channel_1.unsubscribeChannel)(server, id, ctx)) {
if (unsubscribeChannel(server, id, ctx)) {
ctx.session.ws.unsubscribe(String(id));

@@ -136,3 +131,2 @@ }

};
exports.unsubscribeChannelMessage = unsubscribeChannelMessage;
//# sourceMappingURL=channelSubscribe.js.map

@@ -1,3 +0,2 @@

import { BinaryMessageHandler } from './types';
import { BinaryMessageHandler } from './types.js';
export declare const functionMessage: BinaryMessageHandler;
//# sourceMappingURL=function.d.ts.map

@@ -1,12 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.functionMessage = void 0;
const protocol_1 = require("../../protocol");
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
const security_1 = require("../../security");
const verifyRoute_1 = require("../../verifyRoute");
const authorize_1 = require("../../authorize");
const stream_1 = require("stream");
const utils_1 = require("@saulx/utils");
import { readUint8, decodeName, decodePayload, encodeFunctionResponse, valueToBuffer, parsePayload, } from '../../protocol.js';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
import { rateLimitRequest } from '../../security.js';
import { verifyRoute } from '../../verifyRoute.js';
import { authorize } from '../../authorize.js';
import { Duplex, Readable } from 'stream';
import { readStream } from '@saulx/utils';
// combine authorize with installfn AuthorizeAndInstall

@@ -17,3 +14,3 @@ const sendFunction = (route, spec, server, ctx, payload, requestId) => {

if (!client) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
route,

@@ -28,6 +25,6 @@ requestId,

.then(async (v) => {
ctx.session?.ws.send((0, protocol_1.encodeFunctionResponse)(requestId, (0, protocol_1.valueToBuffer)(v)), true, false);
ctx.session?.ws.send(encodeFunctionResponse(requestId, valueToBuffer(v)), true, false);
})
.catch((err) => {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
route,

@@ -44,9 +41,9 @@ requestId,

// TODO: allow chunked reply!
if (v && (v instanceof stream_1.Duplex || v instanceof stream_1.Readable)) {
v = await (0, utils_1.readStream)(v);
if (v && (v instanceof Duplex || v instanceof Readable)) {
v = await readStream(v);
}
ctx.session?.ws.send((0, protocol_1.encodeFunctionResponse)(requestId, (0, protocol_1.valueToBuffer)(v)), true, false);
ctx.session?.ws.send(encodeFunctionResponse(requestId, valueToBuffer(v)), true, false);
})
.catch((err) => {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.FunctionError, {
sendError(server, ctx, BasedErrorCode.FunctionError, {
route,

@@ -58,11 +55,11 @@ requestId,

};
const functionMessage = (arr, start, len, isDeflate, ctx, server) => {
export const functionMessage = (arr, start, len, isDeflate, ctx, server) => {
// | 4 header | 3 id | 1 name length | * name | * payload |
const requestId = (0, protocol_1.readUint8)(arr, start + 4, 3);
const requestId = readUint8(arr, start + 4, 3);
const nameLen = arr[start + 7];
const name = (0, protocol_1.decodeName)(arr, start + 8, start + 8 + nameLen);
const name = decodeName(arr, start + 8, start + 8 + nameLen);
if (!name || !requestId) {
return false;
}
const route = (0, verifyRoute_1.verifyRoute)(server, ctx, 'function', server.functions.route(name), name, requestId);
const route = verifyRoute(server, ctx, 'function', server.functions.route(name), name, requestId);
// TODO: add strictness setting - if strict return false here

@@ -72,3 +69,3 @@ if (route === null) {

}
if ((0, security_1.rateLimitRequest)(server, ctx, route.rateLimitTokens, server.rateLimit.ws)) {
if (rateLimitRequest(server, ctx, route.rateLimitTokens, server.rateLimit.ws)) {
ctx.session.ws.close();

@@ -78,3 +75,3 @@ return false;

if (len > route.maxPayloadSize) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.PayloadTooLarge, {
sendError(server, ctx, BasedErrorCode.PayloadTooLarge, {
route,

@@ -87,7 +84,6 @@ requestId,

? undefined
: (0, protocol_1.parsePayload)((0, protocol_1.decodePayload)(new Uint8Array(arr.slice(start + 8 + nameLen, start + len)), isDeflate));
(0, authorize_1.authorize)(route, server, ctx, payload, sendFunction, requestId);
: parsePayload(decodePayload(new Uint8Array(arr.slice(start + 8 + nameLen, start + len)), isDeflate));
authorize(route, server, ctx, payload, sendFunction, requestId);
return true;
};
exports.functionMessage = functionMessage;
//# sourceMappingURL=function.js.map

@@ -1,3 +0,2 @@

import { BinaryMessageHandler } from './types';
import { BinaryMessageHandler } from './types.js';
export declare const getMessage: BinaryMessageHandler;
//# sourceMappingURL=get.d.ts.map

@@ -1,32 +0,29 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getMessage = void 0;
const protocol_1 = require("../../protocol");
const query_1 = require("../../query");
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
const security_1 = require("../../security");
const verifyRoute_1 = require("../../verifyRoute");
const authorize_1 = require("../../authorize");
import { decodePayload, decodeName, readUint8, encodeGetResponse, parsePayload, } from '../../protocol.js';
import { createObs, destroyObs, subscribeNext, getObsAndStopRemove, hasObs, start, sendObsWs, sendObsGetError, } from '../../query/index.js';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
import { rateLimitRequest } from '../../security.js';
import { verifyRoute } from '../../verifyRoute.js';
import { authorize, } from '../../authorize.js';
const sendGetData = (server, id, obs, checksum, ctx) => {
if (!ctx.session) {
(0, query_1.destroyObs)(server, id);
destroyObs(server, id);
return;
}
if (checksum === 0) {
(0, query_1.sendObsWs)(ctx, obs.cache, obs);
sendObsWs(ctx, obs.cache, obs);
}
else if (checksum === obs.checksum) {
ctx.session.ws.send((0, protocol_1.encodeGetResponse)(id), true, false);
ctx.session.ws.send(encodeGetResponse(id), true, false);
}
else if (obs.diffCache && obs.previousChecksum === checksum) {
(0, query_1.sendObsWs)(ctx, obs.diffCache, obs);
sendObsWs(ctx, obs.diffCache, obs);
}
else {
(0, query_1.sendObsWs)(ctx, obs.cache, obs);
sendObsWs(ctx, obs.cache, obs);
}
(0, query_1.destroyObs)(server, id);
destroyObs(server, id);
};
const getFromExisting = (server, id, ctx, checksum) => {
const obs = (0, query_1.getObsAndStopRemove)(server, id);
const obs = getObsAndStopRemove(server, id);
if (server.queryEvents) {

@@ -36,3 +33,3 @@ server.queryEvents.get(obs, ctx);

if (obs.error) {
(0, query_1.sendObsGetError)(server, ctx, id, obs.error);
sendObsGetError(server, ctx, id, obs.error);
return;

@@ -44,5 +41,5 @@ }

}
(0, query_1.subscribeNext)(obs, (err) => {
subscribeNext(obs, (err) => {
if (err) {
(0, query_1.sendObsGetError)(server, ctx, id, err);
sendObsGetError(server, ctx, id, err);
}

@@ -54,4 +51,4 @@ else {

};
const isAuthorized = (route, spec, server, ctx, payload, id, checksum) => {
if ((0, query_1.hasObs)(server, id)) {
const isAuthorized = (route, _spec, server, ctx, payload, id, checksum) => {
if (hasObs(server, id)) {
getFromExisting(server, id, ctx, checksum);

@@ -64,7 +61,7 @@ return;

}
if ((0, query_1.hasObs)(server, id)) {
if (hasObs(server, id)) {
getFromExisting(server, id, ctx, checksum);
return;
}
const obs = (0, query_1.createObs)(server, route.name, id, payload, true);
const obs = createObs(server, route.name, id, payload, true);
if (server.queryEvents) {

@@ -74,5 +71,5 @@ server.queryEvents.get(obs, ctx);

if (!session.obs.has(id)) {
(0, query_1.subscribeNext)(obs, (err) => {
subscribeNext(obs, (err) => {
if (err) {
(0, query_1.sendObsGetError)(server, ctx, id, err);
sendObsGetError(server, ctx, id, err);
}

@@ -84,5 +81,5 @@ else {

}
(0, query_1.start)(server, id);
start(server, id);
};
const isNotAuthorized = (route, server, ctx, payload, id, checksum) => {
const isNotAuthorized = (route, _server, ctx, payload, id, checksum) => {
const session = ctx.session;

@@ -99,12 +96,12 @@ if (!session.unauthorizedObs) {

};
const getMessage = (arr, start, len, isDeflate, ctx, server) => {
export const getMessage = (arr, start, len, isDeflate, ctx, server) => {
// | 4 header | 8 id | 8 checksum | 1 name length | * name | * payload |
const nameLen = arr[start + 20];
const id = (0, protocol_1.readUint8)(arr, start + 4, 8);
const checksum = (0, protocol_1.readUint8)(arr, start + 12, 8);
const name = (0, protocol_1.decodeName)(arr, start + 21, start + 21 + nameLen);
const id = readUint8(arr, start + 4, 8);
const checksum = readUint8(arr, start + 12, 8);
const name = decodeName(arr, start + 21, start + 21 + nameLen);
if (!name || !id) {
return false;
}
const route = (0, verifyRoute_1.verifyRoute)(server, ctx, 'query', server.functions.route(name), name, id);
const route = verifyRoute(server, ctx, 'query', server.functions.route(name), name, id);
// TODO: add strictness setting - if strict return false here

@@ -114,3 +111,3 @@ if (route === null) {

}
if ((0, security_1.rateLimitRequest)(server, ctx, route.rateLimitTokens, server.rateLimit.ws)) {
if (rateLimitRequest(server, ctx, route.rateLimitTokens, server.rateLimit.ws)) {
ctx.session.ws.close();

@@ -120,3 +117,3 @@ return false;

if (route.maxPayloadSize !== -1 && len > route.maxPayloadSize) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.PayloadTooLarge, {
sendError(server, ctx, BasedErrorCode.PayloadTooLarge, {
route,

@@ -129,7 +126,6 @@ observableId: id,

? undefined
: (0, protocol_1.parsePayload)((0, protocol_1.decodePayload)(new Uint8Array(arr.slice(start + 21 + nameLen, start + len)), isDeflate));
(0, authorize_1.authorize)(route, server, ctx, payload, isAuthorized, id, checksum, false, isNotAuthorized);
: parsePayload(decodePayload(new Uint8Array(arr.slice(start + 21 + nameLen, start + len)), isDeflate));
authorize(route, server, ctx, payload, isAuthorized, id, checksum, false, isNotAuthorized);
return true;
};
exports.getMessage = getMessage;
//# sourceMappingURL=get.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../../server';
import { BasedServer } from '../../server.js';
import { WebSocketSession, Context } from '@based/functions';
export declare const message: (server: BasedServer, ctx: Context<WebSocketSession>, msg: ArrayBuffer, isBinary: boolean) => void;
//# sourceMappingURL=index.d.ts.map

@@ -1,21 +0,18 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.message = void 0;
const protocol_1 = require("../../protocol");
const function_1 = require("./function");
const query_1 = require("./query");
const auth_1 = require("./auth");
const get_1 = require("./get");
const error_1 = require("../../error");
const channelSubscribe_1 = require("./channelSubscribe");
const channelPublish_1 = require("./channelPublish");
import { decodeHeader, readUint8 } from '../../protocol.js';
import { functionMessage } from './function.js';
import { subscribeMessage, unsubscribeMessage } from './query.js';
import { authMessage } from './auth.js';
import { getMessage } from './get.js';
import { BasedErrorCode, createError } from '../../error/index.js';
import { channelSubscribeMessage, unsubscribeChannelMessage, } from './channelSubscribe.js';
import { channelPublishMessage } from './channelPublish.js';
const reader = (server, ctx, arr, start) => {
const { len, isDeflate, type } = (0, protocol_1.decodeHeader)((0, protocol_1.readUint8)(arr, start, 4));
const { len, isDeflate, type } = decodeHeader(readUint8(arr, start, 4));
const next = len + start;
// type 0 = function
if (type === 0 && (0, function_1.functionMessage)(arr, start, len, isDeflate, ctx, server)) {
if (type === 0 && functionMessage(arr, start, len, isDeflate, ctx, server)) {
return next;
}
// type 1 = subscribe
if (type === 1 && (0, query_1.subscribeMessage)(arr, start, len, isDeflate, ctx, server)) {
if (type === 1 && subscribeMessage(arr, start, len, isDeflate, ctx, server)) {
return next;

@@ -25,11 +22,11 @@ }

if (type === 2 &&
(0, query_1.unsubscribeMessage)(arr, start, len, isDeflate, ctx, server)) {
unsubscribeMessage(arr, start, len, isDeflate, ctx, server)) {
return next;
}
// type 3 = get
if (type === 3 && (0, get_1.getMessage)(arr, start, len, isDeflate, ctx, server)) {
if (type === 3 && getMessage(arr, start, len, isDeflate, ctx, server)) {
return next;
}
// type 4 = auth
if (type === 4 && (0, auth_1.authMessage)(arr, start, len, isDeflate, ctx, server)) {
if (type === 4 && authMessage(arr, start, len, isDeflate, ctx, server)) {
return next;

@@ -39,3 +36,3 @@ }

if (type === 5 &&
(0, channelSubscribe_1.channelSubscribeMessage)(arr, start, len, isDeflate, ctx, server)) {
channelSubscribeMessage(arr, start, len, isDeflate, ctx, server)) {
return next;

@@ -45,3 +42,3 @@ }

if (type === 6 &&
(0, channelPublish_1.channelPublishMessage)(arr, start, len, isDeflate, ctx, server)) {
channelPublishMessage(arr, start, len, isDeflate, ctx, server)) {
return next;

@@ -51,3 +48,3 @@ }

if (type === 7 &&
(0, channelSubscribe_1.unsubscribeChannelMessage)(arr, start, len, isDeflate, ctx, server)) {
unsubscribeChannelMessage(arr, start, len, isDeflate, ctx, server)) {
return next;

@@ -57,3 +54,3 @@ }

};
const message = (server, ctx, msg, isBinary) => {
export const message = (server, ctx, msg, isBinary) => {
if (!ctx.session) {

@@ -63,3 +60,3 @@ return;

if (!isBinary) {
(0, error_1.createError)(server, ctx, error_1.BasedErrorCode.NoBinaryProtocol, {
createError(server, ctx, BasedErrorCode.NoBinaryProtocol, {
buffer: msg,

@@ -87,3 +84,2 @@ });

};
exports.message = message;
//# sourceMappingURL=index.js.map
import { WebSocketSession, BasedRoute } from '@based/functions';
import { IsAuthorizedHandler } from '../../authorize';
import { BinaryMessageHandler } from './types';
import { IsAuthorizedHandler } from '../../authorize.js';
import { BinaryMessageHandler } from './types.js';
export declare const enableSubscribe: IsAuthorizedHandler<WebSocketSession, BasedRoute<'query'>>;
export declare const subscribeMessage: BinaryMessageHandler;
export declare const unsubscribeMessage: BinaryMessageHandler;
//# sourceMappingURL=query.d.ts.map

@@ -1,14 +0,11 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsubscribeMessage = exports.subscribeMessage = exports.enableSubscribe = void 0;
const protocol_1 = require("../../protocol");
const query_1 = require("../../query");
const error_1 = require("../../error");
const sendError_1 = require("../../sendError");
const security_1 = require("../../security");
const verifyRoute_1 = require("../../verifyRoute");
const authorize_1 = require("../../authorize");
const enableSubscribe = (route, psec, server, ctx, payload, id, checksum) => {
if ((0, query_1.hasObs)(server, id)) {
(0, query_1.subscribeWs)(server, id, checksum, ctx);
import { decodePayload, decodeName, readUint8, parsePayload, } from '../../protocol.js';
import { createObs, unsubscribeWs, subscribeWs, hasObs, } from '../../query/index.js';
import { BasedErrorCode } from '../../error/index.js';
import { sendError } from '../../sendError.js';
import { rateLimitRequest } from '../../security.js';
import { verifyRoute } from '../../verifyRoute.js';
import { authorize, } from '../../authorize.js';
export const enableSubscribe = (route, _spec, server, ctx, payload, id, checksum) => {
if (hasObs(server, id)) {
subscribeWs(server, id, checksum, ctx);
return;

@@ -20,9 +17,8 @@ }

}
if (!(0, query_1.hasObs)(server, id)) {
(0, query_1.createObs)(server, route.name, id, payload);
if (!hasObs(server, id)) {
createObs(server, route.name, id, payload);
}
(0, query_1.subscribeWs)(server, id, checksum, ctx);
subscribeWs(server, id, checksum, ctx);
};
exports.enableSubscribe = enableSubscribe;
const isNotAuthorized = (route, server, ctx, payload, id, checksum) => {
const isNotAuthorized = (route, _server, ctx, payload, id, checksum) => {
const session = ctx.session;

@@ -39,12 +35,12 @@ if (!session.unauthorizedObs) {

};
const subscribeMessage = (arr, start, len, isDeflate, ctx, server) => {
export const subscribeMessage = (arr, start, len, isDeflate, ctx, server) => {
// | 4 header | 8 id | 8 checksum | 1 name length | * name | * payload |
const nameLen = arr[start + 20];
const id = (0, protocol_1.readUint8)(arr, start + 4, 8);
const checksum = (0, protocol_1.readUint8)(arr, start + 12, 8);
const name = (0, protocol_1.decodeName)(arr, start + 21, start + 21 + nameLen);
const id = readUint8(arr, start + 4, 8);
const checksum = readUint8(arr, start + 12, 8);
const name = decodeName(arr, start + 21, start + 21 + nameLen);
if (!name || !id) {
return false;
}
const route = (0, verifyRoute_1.verifyRoute)(server, ctx, 'query', server.functions.route(name), name, id);
const route = verifyRoute(server, ctx, 'query', server.functions.route(name), name, id);
// TODO: add strictness setting - if strict return false here

@@ -54,3 +50,3 @@ if (route === null) {

}
if ((0, security_1.rateLimitRequest)(server, ctx, route.rateLimitTokens, server.rateLimit.ws)) {
if (rateLimitRequest(server, ctx, route.rateLimitTokens, server.rateLimit.ws)) {
ctx.session.ws.close();

@@ -60,3 +56,3 @@ return false;

if (route.maxPayloadSize !== -1 && len > route.maxPayloadSize) {
(0, sendError_1.sendError)(server, ctx, error_1.BasedErrorCode.PayloadTooLarge, {
sendError(server, ctx, BasedErrorCode.PayloadTooLarge, {
route,

@@ -74,9 +70,8 @@ observableId: id,

? undefined
: (0, protocol_1.parsePayload)((0, protocol_1.decodePayload)(new Uint8Array(arr.slice(start + 21 + nameLen, start + len)), isDeflate));
: parsePayload(decodePayload(new Uint8Array(arr.slice(start + 21 + nameLen, start + len)), isDeflate));
session.obs.add(id);
(0, authorize_1.authorize)(route, server, ctx, payload, exports.enableSubscribe, id, checksum, false, isNotAuthorized);
authorize(route, server, ctx, payload, enableSubscribe, id, checksum, false, isNotAuthorized);
return true;
};
exports.subscribeMessage = subscribeMessage;
const unsubscribeMessage = (arr, start, len, isDeflate, ctx, server) => {
export const unsubscribeMessage = (arr, start, _len, _isDeflate, ctx, server) => {
// | 4 header | 8 id |

@@ -86,7 +81,7 @@ if (!ctx.session) {

}
const id = (0, protocol_1.readUint8)(arr, start + 4, 8);
const id = readUint8(arr, start + 4, 8);
if (!id) {
return false;
}
if ((0, query_1.unsubscribeWs)(server, id, ctx)) {
if (unsubscribeWs(server, id, ctx)) {
ctx.session.ws.unsubscribe(String(id));

@@ -96,3 +91,2 @@ }

};
exports.unsubscribeMessage = unsubscribeMessage;
//# sourceMappingURL=query.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../../server';
import { BasedServer } from '../../server.js';
import { WebSocketSession, Context } from '@based/functions';
export type BinaryMessageHandler = (arr: Uint8Array, start: number, len: number, isDeflate: boolean, ctx: Context<WebSocketSession>, server: BasedServer) => boolean;
//# sourceMappingURL=types.d.ts.map

@@ -1,3 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};
//# sourceMappingURL=types.js.map

@@ -1,10 +0,9 @@

export { compress } from './compress';
export { sendHttpResponse } from './sendHttpResponse';
export { sendError } from './sendError';
export * from './server';
export * from './functions/types';
export * from './error';
export * from './functionApi';
export * from './query/types';
export * from './protocol';
//# sourceMappingURL=index.d.ts.map
export { compress } from './compress.js';
export { sendHttpResponse } from './sendHttpResponse.js';
export { sendError } from './sendError.js';
export * from './server.js';
export * from './functions/types.js';
export * from './error/index.js';
export * from './functionApi/index.js';
export * from './query/types.js';
export * from './protocol.js';

@@ -1,30 +0,10 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendError = exports.sendHttpResponse = exports.compress = void 0;
var compress_1 = require("./compress");
Object.defineProperty(exports, "compress", { enumerable: true, get: function () { return compress_1.compress; } });
var sendHttpResponse_1 = require("./sendHttpResponse");
Object.defineProperty(exports, "sendHttpResponse", { enumerable: true, get: function () { return sendHttpResponse_1.sendHttpResponse; } });
var sendError_1 = require("./sendError");
Object.defineProperty(exports, "sendError", { enumerable: true, get: function () { return sendError_1.sendError; } });
__exportStar(require("./server"), exports);
__exportStar(require("./functions/types"), exports);
__exportStar(require("./error"), exports);
__exportStar(require("./functionApi"), exports);
__exportStar(require("./query/types"), exports);
__exportStar(require("./protocol"), exports);
export { compress } from './compress.js';
export { sendHttpResponse } from './sendHttpResponse.js';
export { sendError } from './sendError.js';
export * from './server.js';
export * from './functions/types.js';
export * from './error/index.js';
export * from './functionApi/index.js';
export * from './query/types.js';
export * from './protocol.js';
//# sourceMappingURL=index.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from './server';
import { Context, BasedRoute, BasedFunctionConfig, BasedFunctionTypes } from '@based/functions';
export declare const installFn: <R extends BasedRoute<BasedFunctionTypes, "name" | "type">>(server: BasedServer, ctx: Context, route: R, id?: number) => Promise<BasedFunctionConfig<R["type"]>>;
//# sourceMappingURL=installFn.d.ts.map
import { BasedServer } from './server.js';
import { Context, BasedRoute, BasedFunctionConfig } from '@based/functions';
export declare const installFn: <R extends BasedRoute>(server: BasedServer, ctx: Context, route: R, id?: number) => Promise<BasedFunctionConfig<R["type"]>>;

@@ -1,14 +0,11 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.installFn = void 0;
const functions_1 = require("@based/functions");
const sendError_1 = require("./sendError");
const error_1 = require("./error");
const functionNotFound = (server, ctx, route, type, id) => {
if (!(0, functions_1.isClientContext)(ctx)) {
import { isClientContext, isBasedFunctionConfig, } from '@based/functions';
import { sendSimpleError } from './sendError.js';
import { BasedErrorCode } from './error/index.js';
const functionNotFound = (server, ctx, route, _type, id) => {
if (!isClientContext(ctx)) {
return;
}
(0, sendError_1.sendSimpleError)(server, ctx, error_1.BasedErrorCode.FunctionNotFound, { type: route.type, name: route.name }, id);
sendSimpleError(server, ctx, BasedErrorCode.FunctionNotFound, { type: route.type, name: route.name }, id);
};
const installFn = async (server, ctx, route, id) => {
export const installFn = async (server, ctx, route, id) => {
if (!route) {

@@ -27,7 +24,7 @@ return null;

}
if (!(0, functions_1.isBasedFunctionConfig)(type, route)) {
if (!(0, functions_1.isClientContext)(ctx)) {
if (!isBasedFunctionConfig(type, route)) {
if (!isClientContext(ctx)) {
return null;
}
(0, sendError_1.sendSimpleError)(server, ctx, error_1.BasedErrorCode.FunctionIsWrongType, { name, type }, id);
sendSimpleError(server, ctx, BasedErrorCode.FunctionIsWrongType, { name, type }, id);
return null;

@@ -43,3 +40,2 @@ }

};
exports.installFn = installFn;
//# sourceMappingURL=installFn.js.map

@@ -1,2 +0,2 @@

/// <reference types="node" />
/// <reference types="node" resolution-mode="require"/>
export declare const COMPRESS_FROM_BYTES = 150;

@@ -24,2 +24,1 @@ export declare const decodeHeader: (nr: number) => {

export declare const decode: (buffer: Uint8Array) => any;
//# sourceMappingURL=protocol.d.ts.map

@@ -1,11 +0,5 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.decode = exports.encodeChannelMessage = exports.encodeErrorResponse = exports.encodeAuthResponse = exports.encodeObservableDiffResponse = exports.encodeObservableResponse = exports.updateId = exports.encodeGetResponse = exports.encodeFunctionResponse = exports.decodeName = exports.parsePayload = exports.decodePayload = exports.valueToBuffer = exports.encodeHeader = exports.readUint8 = exports.storeUint8 = exports.decodeHeader = exports.COMPRESS_FROM_BYTES = void 0;
const node_zlib_1 = __importDefault(require("node:zlib"));
import zlib from 'node:zlib';
const textDecoder = new TextDecoder();
exports.COMPRESS_FROM_BYTES = 150;
const decodeHeader = (nr) => {
export const COMPRESS_FROM_BYTES = 150;
export const decodeHeader = (nr) => {
// 4 bytes

@@ -33,4 +27,3 @@ // type (3 bits)

};
exports.decodeHeader = decodeHeader;
const storeUint8 = (buff, n, start, len) => {
export const storeUint8 = (buff, n, start, len) => {
for (let index = start; index < start + len; index++) {

@@ -42,4 +35,3 @@ const byte = n & 0xff;

};
exports.storeUint8 = storeUint8;
const readUint8 = (buff, start, len) => {
export const readUint8 = (buff, start, len) => {
let n = 0;

@@ -52,4 +44,3 @@ const s = len - 1 + start;

};
exports.readUint8 = readUint8;
const encodeHeader = (type, isDeflate, len) => {
export const encodeHeader = (type, isDeflate, len) => {
// 4 bytes

@@ -71,4 +62,3 @@ // type (3 bits)

};
exports.encodeHeader = encodeHeader;
const valueToBuffer = (payload) => {
export const valueToBuffer = (payload) => {
// can use a more elloborate typed response e.g. number etc in there

@@ -81,4 +71,3 @@ if (payload === undefined) {

};
exports.valueToBuffer = valueToBuffer;
const decodePayload = (payload, isDeflate) => {
export const decodePayload = (payload, isDeflate) => {
if (!isDeflate) {

@@ -88,3 +77,3 @@ return textDecoder.decode(payload);

try {
const buffer = node_zlib_1.default.inflateRawSync(payload);
const buffer = zlib.inflateRawSync(payload);
return textDecoder.decode(buffer);

@@ -96,4 +85,3 @@ }

};
exports.decodePayload = decodePayload;
const parsePayload = (payload) => {
export const parsePayload = (payload) => {
if (typeof payload === 'string') {

@@ -107,9 +95,7 @@ try {

};
exports.parsePayload = parsePayload;
const decodeName = (arr, start, end) => {
export const decodeName = (arr, start, end) => {
const name = new Uint8Array(arr.slice(start, end));
return textDecoder.decode(name);
};
exports.decodeName = decodeName;
const encodeFunctionResponse = (id, buffer) => {
export const encodeFunctionResponse = (id, buffer) => {
// Type 0

@@ -121,5 +107,5 @@ // | 4 header | 3 id | * payload |

const chunks = 1;
if (buffer.length > exports.COMPRESS_FROM_BYTES) {
if (buffer.length > COMPRESS_FROM_BYTES) {
isDeflate = true;
buffer = node_zlib_1.default.deflateRawSync(buffer, {});
buffer = zlib.deflateRawSync(buffer, {});
}

@@ -130,7 +116,7 @@ if (chunks === 1) {

const msgSize = idSize + buffer.length;
const header = (0, exports.encodeHeader)(0, isDeflate, msgSize);
const header = encodeHeader(0, isDeflate, msgSize);
// not very nessecary but ok
const array = new Uint8Array(headerSize + msgSize);
(0, exports.storeUint8)(array, header, 0, 4);
(0, exports.storeUint8)(array, id, 4, 3);
storeUint8(array, header, 0, 4);
storeUint8(array, id, 4, 3);
if (buffer.length) {

@@ -146,33 +132,30 @@ array.set(buffer, 7);

};
exports.encodeFunctionResponse = encodeFunctionResponse;
const encodeGetResponse = (id) => {
export const encodeGetResponse = (id) => {
// Type 4
// | 4 header | 8 id |
const header = (0, exports.encodeHeader)(3, false, 8);
const header = encodeHeader(3, false, 8);
const array = new Uint8Array(12);
(0, exports.storeUint8)(array, header, 0, 4);
(0, exports.storeUint8)(array, id, 4, 8);
storeUint8(array, header, 0, 4);
storeUint8(array, id, 4, 8);
return array;
};
exports.encodeGetResponse = encodeGetResponse;
const updateId = (payload, id) => {
export const updateId = (payload, id) => {
const prevId = payload.slice(4, 12);
(0, exports.storeUint8)(payload, id, 4, 8);
storeUint8(payload, id, 4, 8);
return prevId;
};
exports.updateId = updateId;
const encodeObservableResponse = (id, checksum, buffer) => {
export const encodeObservableResponse = (id, checksum, buffer) => {
// Type 1 (full data)
// | 4 header | 8 id | 8 checksum | * payload |
let isDeflate = false;
if (buffer.length > exports.COMPRESS_FROM_BYTES) {
if (buffer.length > COMPRESS_FROM_BYTES) {
isDeflate = true;
buffer = node_zlib_1.default.deflateRawSync(buffer, {});
buffer = zlib.deflateRawSync(buffer, {});
}
const msgSize = 16 + buffer.length;
const header = (0, exports.encodeHeader)(1, isDeflate, msgSize);
const header = encodeHeader(1, isDeflate, msgSize);
const array = new Uint8Array(4 + msgSize);
(0, exports.storeUint8)(array, header, 0, 4);
(0, exports.storeUint8)(array, id, 4, 8);
(0, exports.storeUint8)(array, checksum, 12, 8);
storeUint8(array, header, 0, 4);
storeUint8(array, id, 4, 8);
storeUint8(array, checksum, 12, 8);
if (buffer.length) {

@@ -183,18 +166,17 @@ array.set(buffer, 20);

};
exports.encodeObservableResponse = encodeObservableResponse;
const encodeObservableDiffResponse = (id, checksum, previousChecksum, buffer) => {
export const encodeObservableDiffResponse = (id, checksum, previousChecksum, buffer) => {
// Type 2 (diff data)
// | 4 header | 8 id | 8 checksum | 8 previousChecksum | * diff |
let isDeflate = false;
if (buffer.length > exports.COMPRESS_FROM_BYTES) {
if (buffer.length > COMPRESS_FROM_BYTES) {
isDeflate = true;
buffer = node_zlib_1.default.deflateRawSync(buffer, {});
buffer = zlib.deflateRawSync(buffer, {});
}
const msgSize = 24 + buffer.length;
const header = (0, exports.encodeHeader)(2, isDeflate, msgSize);
const header = encodeHeader(2, isDeflate, msgSize);
const array = new Uint8Array(4 + msgSize);
(0, exports.storeUint8)(array, header, 0, 4);
(0, exports.storeUint8)(array, id, 4, 8);
(0, exports.storeUint8)(array, checksum, 12, 8);
(0, exports.storeUint8)(array, previousChecksum, 20, 8);
storeUint8(array, header, 0, 4);
storeUint8(array, id, 4, 8);
storeUint8(array, checksum, 12, 8);
storeUint8(array, previousChecksum, 20, 8);
if (buffer.length) {

@@ -205,15 +187,14 @@ array.set(buffer, 28);

};
exports.encodeObservableDiffResponse = encodeObservableDiffResponse;
const encodeSimpleResponse = (type, buffer) => {
// | 4 header | * payload |
let isDeflate = false;
if (buffer.length > exports.COMPRESS_FROM_BYTES) {
if (buffer.length > COMPRESS_FROM_BYTES) {
isDeflate = true;
buffer = node_zlib_1.default.deflateRawSync(buffer, {});
buffer = zlib.deflateRawSync(buffer, {});
}
const headerSize = 4;
const msgSize = buffer.length;
const header = (0, exports.encodeHeader)(type, isDeflate, msgSize);
const header = encodeHeader(type, isDeflate, msgSize);
const array = new Uint8Array(headerSize + msgSize);
(0, exports.storeUint8)(array, header, 0, 4);
storeUint8(array, header, 0, 4);
if (buffer.length) {

@@ -224,26 +205,24 @@ array.set(buffer, 4);

};
const encodeAuthResponse = (buffer) => {
export const encodeAuthResponse = (buffer) => {
// Type 4
return encodeSimpleResponse(4, buffer);
};
exports.encodeAuthResponse = encodeAuthResponse;
const encodeErrorResponse = (buffer) => {
export const encodeErrorResponse = (buffer) => {
// Type 5
return encodeSimpleResponse(5, buffer);
};
exports.encodeErrorResponse = encodeErrorResponse;
const encodeChannelMessage = (id, buffer) => {
export const encodeChannelMessage = (id, buffer) => {
// Type 7.0 (fill data)
// | 4 header | 1 subType | 8 id | * payload |
let isDeflate = false;
if (buffer.length > exports.COMPRESS_FROM_BYTES) {
if (buffer.length > COMPRESS_FROM_BYTES) {
isDeflate = true;
buffer = node_zlib_1.default.deflateRawSync(buffer, {});
buffer = zlib.deflateRawSync(buffer, {});
}
const msgSize = 8 + buffer.length + 1;
const header = (0, exports.encodeHeader)(7, isDeflate, msgSize);
const header = encodeHeader(7, isDeflate, msgSize);
const array = new Uint8Array(4 + msgSize);
(0, exports.storeUint8)(array, 0, 4, 1);
(0, exports.storeUint8)(array, header, 0, 4);
(0, exports.storeUint8)(array, id, 5, 8);
storeUint8(array, 0, 4, 1);
storeUint8(array, header, 0, 4);
storeUint8(array, id, 5, 8);
if (buffer.length) {

@@ -254,6 +233,5 @@ array.set(buffer, 13);

};
exports.encodeChannelMessage = encodeChannelMessage;
const decode = (buffer) => {
const header = (0, exports.readUint8)(buffer, 0, 4);
const { isDeflate, len, type } = (0, exports.decodeHeader)(header);
export const decode = (buffer) => {
const header = readUint8(buffer, 0, 4);
const { isDeflate, len, type } = decodeHeader(header);
if (type === 1) {

@@ -266,6 +244,5 @@ // | 4 header | 8 id | 8 checksum | * payload |

const end = len + 4;
return (0, exports.decodePayload)(buffer.slice(start, end), isDeflate);
return decodePayload(buffer.slice(start, end), isDeflate);
}
};
exports.decode = decode;
//# sourceMappingURL=protocol.js.map

@@ -1,3 +0,2 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
export declare const cleanUpObs: (server: BasedServer) => void;
//# sourceMappingURL=cleanup.d.ts.map

@@ -1,4 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanUpObs = void 0;
const destroyObs = (server, obs) => {

@@ -22,3 +19,3 @@ const id = obs.id;

};
const cleanUpObs = (server) => {
export const cleanUpObs = (server) => {
if (!server.obsCleanTimeout) {

@@ -48,3 +45,3 @@ const cycleTime = Math.max(server.obsCleanupCycle, 500);

server.obsCleanupCycle = shortestCycleTime;
(0, exports.cleanUpObs)(server);
cleanUpObs(server);
}

@@ -54,3 +51,2 @@ }, cycleTime);

};
exports.cleanUpObs = cleanUpObs;
//# sourceMappingURL=cleanup.js.map

@@ -1,4 +0,3 @@

import { BasedServer } from '../server';
import { ActiveObservable } from './types';
import { BasedServer } from '../server.js';
import { ActiveObservable } from './types.js';
export declare const createObs: (server: BasedServer, name: string, id: number, payload: any, noStart?: boolean) => ActiveObservable;
//# sourceMappingURL=create.d.ts.map

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createObs = void 0;
const start_1 = require("./start");
const get_1 = require("./get");
const createObs = (server, name, id, payload, noStart) => {
if ((0, get_1.hasObs)(server, id)) {
import { start } from './start/index.js';
import { hasObs } from './get.js';
export const createObs = (server, name, id, payload, noStart) => {
if (hasObs(server, id)) {
const msg = `Allready has observable ${name} ${id}`;

@@ -31,6 +28,5 @@ console.error(msg);

}
(0, start_1.start)(server, id);
start(server, id);
return obs;
};
exports.createObs = createObs;
//# sourceMappingURL=create.js.map

@@ -1,5 +0,4 @@

import { BasedServer } from '../server';
import { ActiveObservable } from './types';
import { BasedServer } from '../server.js';
import { ActiveObservable } from './types.js';
export declare const updateDestroyTimer: (server: BasedServer, channel: ActiveObservable) => void;
export declare const destroyObs: (server: BasedServer, id: number) => void;
//# sourceMappingURL=destroy.d.ts.map

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.destroyObs = exports.updateDestroyTimer = void 0;
const cleanup_1 = require("./cleanup");
const functions_1 = require("@based/functions");
const updateDestroyTimer = (server, channel) => {
import { cleanUpObs } from './cleanup.js';
import { isBasedFunctionConfig } from '@based/functions';
export const updateDestroyTimer = (server, channel) => {
const spec = server.functions.specs[channel.name];
if (!spec || !(0, functions_1.isBasedFunctionConfig)('query', spec)) {
if (!spec || !isBasedFunctionConfig('query', spec)) {
console.warn('destroyObs - Cannot find obs function spec -', channel.name);

@@ -20,5 +17,4 @@ return;

};
exports.updateDestroyTimer = updateDestroyTimer;
// dont use timer just use counter to remove it over time
const destroyObs = (server, id) => {
export const destroyObs = (server, id) => {
const obs = server.activeObservablesById.get(id);

@@ -43,7 +39,6 @@ if (!obs) {

if (obs.timeTillDestroy === null) {
(0, exports.updateDestroyTimer)(server, obs);
(0, cleanup_1.cleanUpObs)(server);
updateDestroyTimer(server, obs);
cleanUpObs(server);
}
};
exports.destroyObs = destroyObs;
//# sourceMappingURL=destroy.js.map

@@ -1,3 +0,2 @@

import { ActiveObservable } from './types';
import { ActiveObservable } from './types.js';
export declare const extendCache: (obs: ActiveObservable) => void;
//# sourceMappingURL=extendCache.d.ts.map

@@ -1,5 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendCache = void 0;
const extendCache = (obs) => {
export const extendCache = (obs) => {
if (obs.timeTillDestroy) {

@@ -9,3 +6,2 @@ obs.timeTillDestroy = null;

};
exports.extendCache = extendCache;
//# sourceMappingURL=extendCache.js.map
export declare const genObservableId: (name: string, payload: any) => number;
//# sourceMappingURL=genObservableId.d.ts.map

@@ -1,12 +0,8 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.genObservableId = void 0;
const hash_1 = require("@saulx/hash");
const genObservableId = (name, payload) => {
import { hashObjectIgnoreKeyOrder, hash } from '@saulx/hash';
export const genObservableId = (name, payload) => {
if (payload === undefined) {
return (0, hash_1.hash)(name);
return hash(name);
}
return (0, hash_1.hashObjectIgnoreKeyOrder)([name, payload]);
return hashObjectIgnoreKeyOrder([name, payload]);
};
exports.genObservableId = genObservableId;
//# sourceMappingURL=genObservableId.js.map

@@ -1,5 +0,4 @@

import { ActiveObservable } from './types';
import { BasedServer } from '../server';
import { ActiveObservable } from './types.js';
import { BasedServer } from '../server.js';
export declare const getObsAndStopRemove: (server: BasedServer, id: number) => ActiveObservable;
export declare const hasObs: (server: BasedServer, id: number) => Boolean;
//# sourceMappingURL=get.d.ts.map

@@ -1,15 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasObs = exports.getObsAndStopRemove = void 0;
const extendCache_1 = require("./extendCache");
const getObsAndStopRemove = (server, id) => {
import { extendCache } from './extendCache.js';
export const getObsAndStopRemove = (server, id) => {
const obs = server.activeObservablesById.get(id);
(0, extendCache_1.extendCache)(obs);
extendCache(obs);
return obs;
};
exports.getObsAndStopRemove = getObsAndStopRemove;
const hasObs = (server, id) => {
export const hasObs = (server, id) => {
return server.activeObservablesById.has(id);
};
exports.hasObs = hasObs;
//# sourceMappingURL=get.js.map

@@ -1,11 +0,10 @@

export * from './subscribe';
export * from './unsub';
export * from './destroy';
export * from './create';
export * from './extendCache';
export * from './start';
export * from './send';
export * from './get';
export * from './types';
export * from './genObservableId';
//# sourceMappingURL=index.d.ts.map
export * from './subscribe.js';
export * from './unsub.js';
export * from './destroy.js';
export * from './create.js';
export * from './extendCache.js';
export * from './start/index.js';
export * from './send.js';
export * from './get.js';
export * from './types.js';
export * from './genObservableId.js';

@@ -1,27 +0,11 @@

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./subscribe"), exports);
__exportStar(require("./unsub"), exports);
__exportStar(require("./destroy"), exports);
__exportStar(require("./create"), exports);
__exportStar(require("./extendCache"), exports);
__exportStar(require("./start"), exports);
__exportStar(require("./send"), exports);
__exportStar(require("./get"), exports);
__exportStar(require("./types"), exports);
__exportStar(require("./genObservableId"), exports);
export * from './subscribe.js';
export * from './unsub.js';
export * from './destroy.js';
export * from './create.js';
export * from './extendCache.js';
export * from './start/index.js';
export * from './send.js';
export * from './get.js';
export * from './types.js';
export * from './genObservableId.js';
//# sourceMappingURL=index.js.map
import { Context, WebSocketSession, HttpSession } from '@based/functions';
import { BasedServer } from '../server';
import { ActiveObservable, ObservableError } from './types';
import { BasedServer } from '../server.js';
import { ActiveObservable, ObservableError } from './types.js';
export declare const sendObsWs: (ctx: Context<WebSocketSession>, buffer: Uint8Array, obs: ActiveObservable) => void;
export declare const sendObsGetError: (server: BasedServer, ctx: Context<WebSocketSession | HttpSession>, id: number, err: ObservableError) => void;
//# sourceMappingURL=send.d.ts.map

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendObsGetError = exports.sendObsWs = void 0;
const protocol_1 = require("../protocol");
const destroy_1 = require("./destroy");
const sendError_1 = require("../sendError");
const sendObsWs = (ctx, buffer, obs) => {
import { updateId } from '../protocol.js';
import { destroyObs } from './destroy.js';
import { sendErrorData } from '../sendError.js';
export const sendObsWs = (ctx, buffer, obs) => {
if (!ctx.session) {

@@ -12,3 +9,3 @@ return;

if (obs.reusedCache) {
const prevId = (0, protocol_1.updateId)(buffer, obs.id);
const prevId = updateId(buffer, obs.id);
ctx.session.ws.send(buffer, true, false);

@@ -21,8 +18,6 @@ buffer.set(prevId, 4);

};
exports.sendObsWs = sendObsWs;
const sendObsGetError = (server, ctx, id, err) => {
(0, sendError_1.sendErrorData)(ctx, err);
(0, destroy_1.destroyObs)(server, id);
export const sendObsGetError = (server, ctx, id, err) => {
sendErrorData(ctx, err);
destroyObs(server, id);
};
exports.sendObsGetError = sendObsGetError;
//# sourceMappingURL=send.js.map

@@ -1,4 +0,3 @@

import { ActiveObservable, ObservableError } from '../types';
import { BasedServer } from '../../server';
import { ActiveObservable, ObservableError } from '../types.js';
import { BasedServer } from '../../server.js';
export declare const errorListener: (server: BasedServer, obs: ActiveObservable, err: Error | ObservableError) => void;
//# sourceMappingURL=error.d.ts.map

@@ -1,7 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorListener = void 0;
const error_1 = require("../../error");
const protocol_1 = require("../../protocol");
const errorListener = (server, obs, err) => {
import { createError, BasedErrorCode } from '../../error/index.js';
import { encodeErrorResponse, valueToBuffer } from '../../protocol.js';
export const errorListener = (server, obs, err) => {
delete obs.cache;

@@ -15,5 +12,5 @@ delete obs.diffCache;

err instanceof Error
? (0, error_1.createError)(server, {
? createError(server, {
session: { type: 'query', id: obs.id, name: obs.name, headers: {} },
}, error_1.BasedErrorCode.FunctionError, {
}, BasedErrorCode.FunctionError, {
err,

@@ -30,3 +27,3 @@ observableId: obs.id,

if (obs.clients.size) {
server.uwsApp.publish(String(obs.id), (0, protocol_1.encodeErrorResponse)((0, protocol_1.valueToBuffer)(obs.error)), true, false);
server.uwsApp.publish(String(obs.id), encodeErrorResponse(valueToBuffer(obs.error)), true, false);
}

@@ -45,3 +42,2 @@ // TODO: Change this make it one error handler

};
exports.errorListener = errorListener;
//# sourceMappingURL=error.js.map

@@ -1,3 +0,2 @@

import { BasedServer } from '../../server';
import { BasedServer } from '../../server.js';
export declare const start: (server: BasedServer, id: number) => void;
//# sourceMappingURL=index.d.ts.map

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.start = void 0;
const update_1 = require("./update");
const error_1 = require("./error");
const relay_1 = require("./relay");
const functions_1 = require("@based/functions");
const start = (server, id) => {
import { updateListener } from './update.js';
import { errorListener } from './error.js';
import { relay } from './relay.js';
import { isBasedFunctionConfig } from '@based/functions';
export const start = (server, id) => {
const obs = server.activeObservablesById.get(id);

@@ -15,3 +12,3 @@ if (obs.closeFunction) {

const spec = server.functions.specs[obs.name];
if (!spec || !(0, functions_1.isBasedFunctionConfig)('query', spec)) {
if (!spec || !isBasedFunctionConfig('query', spec)) {
console.warn('Cannot find observable function spec!', obs.name);

@@ -23,6 +20,6 @@ return;

if (err) {
(0, error_1.errorListener)(server, obs, err);
errorListener(server, obs, err);
return;
}
(0, update_1.updateListener)(server, obs, data, checksum, cache, diff, fromChecksum, isDeflate);
updateListener(server, obs, data, checksum, cache, diff, fromChecksum, isDeflate);
};

@@ -32,3 +29,2 @@ let isThrottled;

let throtDebounced = false;
let timer;
const update = spec.throttle

@@ -42,3 +38,3 @@ ? (...args) => {

isThrottled = true;
timer = setTimeout(() => {
setTimeout(() => {
if (throtDebounced && !obs.isDestroyed) {

@@ -62,6 +58,6 @@ // @ts-ignore

if (!client) {
(0, error_1.errorListener)(server, obs, new Error(`Relay client ${spec.relay} does not exist`));
errorListener(server, obs, new Error(`Relay client ${spec.relay} does not exist`));
return;
}
(0, relay_1.relay)(server, spec.relay, obs, client, update);
relay(server, spec.relay, obs, client, update);
}

@@ -71,3 +67,3 @@ else {

const r = spec.fn(server.client, payload, update, (err) => {
(0, error_1.errorListener)(server, obs, err);
errorListener(server, obs, err);
});

@@ -84,3 +80,3 @@ if (r instanceof Promise) {

if (!(obs.isDestroyed || startId !== obs.startId)) {
(0, error_1.errorListener)(server, obs, err);
errorListener(server, obs, err);
}

@@ -95,3 +91,3 @@ });

if (!(obs.isDestroyed || startId !== obs.startId)) {
(0, error_1.errorListener)(server, obs, err);
errorListener(server, obs, err);
}

@@ -101,3 +97,2 @@ }

};
exports.start = start;
//# sourceMappingURL=index.js.map
import { ObservableUpdateFunction } from '@based/functions';
import { BasedServer } from '../../server';
import { ActiveObservable } from '../types';
import { BasedServer } from '../../server.js';
import { ActiveObservable } from '../types.js';
export declare const relay: (server: BasedServer, relay: {

@@ -8,2 +8,1 @@ target?: string;

}, obs: ActiveObservable, client: any, update: ObservableUpdateFunction) => void;
//# sourceMappingURL=relay.d.ts.map

@@ -1,14 +0,10 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.relay = void 0;
const error_1 = require("./error");
import { errorListener } from './error.js';
// this has to be super optmized!
const relay = (server, relay, obs, client, update) => {
export const relay = (server, relay, obs, client, update) => {
obs.closeFunction = client
.query(relay.target ?? obs.name, obs.payload)
.subscribe(update, (err) => {
(0, error_1.errorListener)(server, obs, err);
errorListener(server, obs, err);
});
};
exports.relay = relay;
//# sourceMappingURL=relay.js.map

@@ -1,4 +0,3 @@

import { ActiveObservable } from '../types';
import { BasedServer } from '../../server';
import { ActiveObservable } from '../types.js';
import { BasedServer } from '../../server.js';
export declare const updateListener: (server: BasedServer, obs: ActiveObservable, data: any, checksum?: number, reusedData?: Uint8Array, diff?: any, previousChecksum?: number, isDeflate?: boolean) => void;
//# sourceMappingURL=update.d.ts.map

@@ -1,9 +0,9 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateListener = void 0;
const protocol_1 = require("../../protocol");
const utils_1 = require("@saulx/utils");
const hash_1 = require("@saulx/hash");
const diff_1 = require("@saulx/diff");
const updateListener = (server, obs, data, checksum, reusedData, diff, previousChecksum, isDeflate) => {
import { updateId, valueToBuffer, encodeObservableResponse, encodeObservableDiffResponse, } from '../../protocol.js';
import { deepCopy } from '@saulx/utils';
import { hashObjectIgnoreKeyOrder, hash } from '@saulx/hash';
import { createPatch } from '@saulx/diff';
export const updateListener = (server, obs, data, checksum, reusedData, diff, previousChecksum, isDeflate) => {
if (!server.uwsApp) {
return;
}
if (checksum === undefined) {

@@ -15,6 +15,6 @@ if (data === undefined) {

if (typeof data === 'object' && data !== null) {
checksum = (0, hash_1.hashObjectIgnoreKeyOrder)(data);
checksum = hashObjectIgnoreKeyOrder(data);
}
else {
checksum = (0, hash_1.hash)(data);
checksum = hash(data);
}

@@ -42,3 +42,3 @@ }

obs.reusedCache = false;
const buff = (0, protocol_1.valueToBuffer)(data);
const buff = valueToBuffer(data);
const t = typeof data;

@@ -67,6 +67,6 @@ if (t === 'string' || t === 'number' || t === 'boolean') {

if (obs.rawData) {
diff = (0, diff_1.createPatch)(obs.rawData, data);
diff = createPatch(obs.rawData, data);
obs.previousChecksum = obs.checksum;
}
obs.rawData = (0, utils_1.deepCopy)(data);
obs.rawData = deepCopy(data);
}

@@ -79,6 +79,6 @@ else if (obs.rawData) {

;
[encodedData, isDeflate] = (0, protocol_1.encodeObservableResponse)(obs.id, checksum, buff);
[encodedData, isDeflate] = encodeObservableResponse(obs.id, checksum, buff);
if (diff) {
const diffBuff = (0, protocol_1.valueToBuffer)(diff);
const encodedDiffData = (0, protocol_1.encodeObservableDiffResponse)(obs.id, checksum, obs.previousChecksum, diffBuff);
const diffBuff = valueToBuffer(diff);
const encodedDiffData = encodeObservableDiffResponse(obs.id, checksum, obs.previousChecksum, diffBuff);
obs.diffCache = encodedDiffData;

@@ -95,3 +95,3 @@ }

if (obs.reusedCache) {
prevDiffId = (0, protocol_1.updateId)(obs.diffCache, obs.id);
prevDiffId = updateId(obs.diffCache, obs.id);
}

@@ -102,3 +102,3 @@ server.uwsApp.publish(String(obs.id), obs.diffCache, true, false);

if (obs.reusedCache) {
prevId = (0, protocol_1.updateId)(encodedData, obs.id);
prevId = updateId(encodedData, obs.id);
}

@@ -126,3 +126,2 @@ server.uwsApp.publish(String(obs.id), encodedData, true, false);

};
exports.updateListener = updateListener;
//# sourceMappingURL=update.js.map

@@ -1,4 +0,4 @@

import { BasedServer } from '../server';
import { ActiveObservable, ObservableUpdateFunction } from './types';
import { BasedErrorCode, BasedErrorData } from '../error';
import { BasedServer } from '../server.js';
import { ActiveObservable, ObservableUpdateFunction } from './types.js';
import { BasedErrorCode, BasedErrorData } from '../error/index.js';
import { WebSocketSession, Context } from '@based/functions';

@@ -8,2 +8,1 @@ export declare const subscribeWs: (server: BasedServer, id: number, checksum: number, ctx: Context<WebSocketSession>) => void;

export declare const subscribeNext: (obs: ActiveObservable, onNext: (err?: BasedErrorData<BasedErrorCode.FunctionError>) => void) => void;
//# sourceMappingURL=subscribe.d.ts.map

@@ -1,9 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.subscribeNext = exports.subscribeFunction = exports.subscribeWs = void 0;
const extendCache_1 = require("./extendCache");
const send_1 = require("./send");
const get_1 = require("./get");
const sendError_1 = require("../sendError");
const subscribeWs = (server, id, checksum, ctx) => {
import { extendCache } from './extendCache.js';
import { sendObsWs } from './send.js';
import { getObsAndStopRemove } from './get.js';
import { sendErrorData } from '../sendError.js';
export const subscribeWs = (server, id, checksum, ctx) => {
const session = ctx.session;

@@ -14,7 +11,7 @@ if (!session) {

ctx.session.ws.subscribe(String(id));
const obs = (0, get_1.getObsAndStopRemove)(server, id);
const obs = getObsAndStopRemove(server, id);
session.obs.add(id);
obs.clients.add(session.id);
if (obs.error) {
(0, sendError_1.sendErrorData)(ctx, obs.error);
sendErrorData(ctx, obs.error);
return;

@@ -27,12 +24,11 @@ }

if (obs.diffCache && obs.previousChecksum === checksum) {
(0, send_1.sendObsWs)(ctx, obs.diffCache, obs);
sendObsWs(ctx, obs.diffCache, obs);
}
else {
(0, send_1.sendObsWs)(ctx, obs.cache, obs);
sendObsWs(ctx, obs.cache, obs);
}
}
};
exports.subscribeWs = subscribeWs;
const subscribeFunction = (server, id, update) => {
const obs = (0, get_1.getObsAndStopRemove)(server, id);
export const subscribeFunction = (server, id, update) => {
const obs = getObsAndStopRemove(server, id);
if (obs.functionObserveClients.add(update)) {

@@ -47,5 +43,4 @@ if (server.queryEvents) {

};
exports.subscribeFunction = subscribeFunction;
const subscribeNext = (obs, onNext) => {
(0, extendCache_1.extendCache)(obs);
export const subscribeNext = (obs, onNext) => {
extendCache(obs);
if (!obs.onNextData) {

@@ -56,3 +51,2 @@ obs.onNextData = new Set();

};
exports.subscribeNext = subscribeNext;
//# sourceMappingURL=subscribe.js.map

@@ -1,2 +0,2 @@

import { BasedErrorCode, BasedErrorData } from '../error';
import { BasedErrorCode, BasedErrorData } from '../error/index.js';
export type ObservableError = BasedErrorData<BasedErrorCode.FunctionError> | BasedErrorData<BasedErrorCode.FunctionIsWrongType> | BasedErrorData<BasedErrorCode.FunctionNotFound>;

@@ -26,2 +26,1 @@ export type ObservableUpdateFunction = (data: any, checksum?: number, err?: null | ObservableError, cache?: Uint8Array, diff?: any, fromChecksum?: number, isDeflate?: boolean) => void;

};
//# sourceMappingURL=types.d.ts.map

@@ -1,3 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
export {};
//# sourceMappingURL=types.js.map

@@ -1,7 +0,6 @@

import { BasedServer } from '../server';
import { BasedServer } from '../server.js';
import { WebSocketSession, Context } from '@based/functions';
import { ObservableUpdateFunction } from './types';
import { ObservableUpdateFunction } from './types.js';
export declare const unsubscribeFunction: (server: BasedServer, id: number, update: ObservableUpdateFunction) => true | void;
export declare const unsubscribeWs: (server: BasedServer, id: number, ctx: Context<WebSocketSession>) => true | void;
export declare const unsubscribeWsIgnoreClient: (server: BasedServer, id: number, ctx: Context<WebSocketSession>) => true | void;
//# sourceMappingURL=unsub.d.ts.map

@@ -1,6 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsubscribeWsIgnoreClient = exports.unsubscribeWs = exports.unsubscribeFunction = void 0;
const destroy_1 = require("./destroy");
const unsubscribeFunction = (server, id, update) => {
import { destroyObs } from './destroy.js';
export const unsubscribeFunction = (server, id, update) => {
const obs = server.activeObservablesById.get(id);

@@ -14,8 +11,7 @@ if (!obs) {

}
(0, destroy_1.destroyObs)(server, id);
destroyObs(server, id);
return true;
}
};
exports.unsubscribeFunction = unsubscribeFunction;
const unsubscribeWs = (server, id, ctx) => {
export const unsubscribeWs = (server, id, ctx) => {
const session = ctx.session;

@@ -35,8 +31,7 @@ if (!session || !session.obs.has(id)) {

}
(0, destroy_1.destroyObs)(server, id);
destroyObs(server, id);
return true;
}
};
exports.unsubscribeWs = unsubscribeWs;
const unsubscribeWsIgnoreClient = (server, id, ctx) => {
export const unsubscribeWsIgnoreClient = (server, id, ctx) => {
const session = ctx.session;

@@ -53,5 +48,4 @@ if (!session) {

}
(0, destroy_1.destroyObs)(server, id);
destroyObs(server, id);
};
exports.unsubscribeWsIgnoreClient = unsubscribeWsIgnoreClient;
//# sourceMappingURL=unsub.js.map

@@ -1,2 +0,2 @@

import type { BasedServer } from './server';
import type { BasedServer } from './server.js';
import uws from '@based/uws';

@@ -7,2 +7,1 @@ import { HttpSession, WebSocketSession, Context } from '@based/functions';

export declare const blockIncomingRequest: (server: BasedServer, ip: string, res: uws.HttpResponse, req: uws.HttpRequest, max: number, tokens: number) => boolean;
//# sourceMappingURL=security.d.ts.map

@@ -1,5 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.blockIncomingRequest = exports.endRateLimitHttp = exports.rateLimitRequest = void 0;
const error_1 = require("./error");
import { BasedErrorCode } from './error/index.js';
var IsBlocked;

@@ -29,3 +26,3 @@ (function (IsBlocked) {

server.emit('error', server.client.ctx, {
code: error_1.BasedErrorCode.Block,
code: BasedErrorCode.Block,
blockedEvents,

@@ -59,3 +56,3 @@ });

};
const rateLimitRequest = (server, ctx, tokens, max) => {
export const rateLimitRequest = (server, ctx, tokens, max) => {
if (!ctx.session) {

@@ -70,8 +67,7 @@ return false;

if (code === 2) {
server.emit('error', ctx, { code: error_1.BasedErrorCode.RateLimit });
server.emit('error', ctx, { code: BasedErrorCode.RateLimit });
}
return true;
};
exports.rateLimitRequest = rateLimitRequest;
const endRateLimitHttp = (res) => {
export const endRateLimitHttp = (res) => {
res.cork(() => {

@@ -82,4 +78,3 @@ res.writeStatus('429 Too Many Requests');

};
exports.endRateLimitHttp = endRateLimitHttp;
const blockIncomingRequest = (server, ip, res, req, max, tokens) => {
export const blockIncomingRequest = (server, ip, res, req, max, tokens) => {
if (server.allowedIps.has(ip)) {

@@ -107,8 +102,7 @@ return false;

},
}, { code: error_1.BasedErrorCode.RateLimit });
}, { code: BasedErrorCode.RateLimit });
}
(0, exports.endRateLimitHttp)(res);
endRateLimitHttp(res);
return true;
};
exports.blockIncomingRequest = blockIncomingRequest;
//# sourceMappingURL=security.js.map

@@ -1,4 +0,4 @@

import { BasedServer } from './server';
import { BasedServer } from './server.js';
import { HttpSession, WebSocketSession, Context, BasedRoute } from '@based/functions';
import { BasedErrorCode, ErrorPayload, BasedErrorData } from './error';
import { BasedErrorCode, ErrorPayload, BasedErrorData } from './error/index.js';
export declare function sendHttpError<T extends BasedErrorCode>(server: BasedServer, ctx: Context<HttpSession>, basedCode: T, payload: ErrorPayload[T]): void;

@@ -8,2 +8,1 @@ export declare function sendErrorData(ctx: Context<WebSocketSession | HttpSession>, errorData: BasedErrorData): void;

export declare function sendSimpleError<T extends BasedErrorCode>(server: BasedServer, ctx: Context<WebSocketSession | HttpSession>, basedCode: T, route: BasedRoute, id?: number, payload?: ErrorPayload[T]): void;
//# sourceMappingURL=sendError.d.ts.map

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendSimpleError = exports.sendError = exports.sendErrorData = exports.sendHttpError = void 0;
const sendHttpResponse_1 = require("./sendHttpResponse");
const functions_1 = require("@based/functions");
const protocol_1 = require("./protocol");
const error_1 = require("./error");
import { end } from './sendHttpResponse.js';
import { isHttpContext, isWsSession, } from '@based/functions';
import { valueToBuffer, encodeErrorResponse } from './protocol.js';
import { createError, } from './error/index.js';
const sendHttpErrorData = (errorData, ctx) => {

@@ -15,3 +12,3 @@ const { code, message, statusCode, statusMessage } = errorData;

}
(0, sendHttpResponse_1.end)(ctx, JSON.stringify({
end(ctx, JSON.stringify({
error: message,

@@ -22,36 +19,33 @@ code,

};
function sendHttpError(server, ctx, basedCode, payload) {
export function sendHttpError(server, ctx, basedCode, payload) {
if (!ctx.session) {
return;
}
const errData = (0, error_1.createError)(server, ctx, basedCode, payload);
const errData = createError(server, ctx, basedCode, payload);
sendHttpErrorData(errData, ctx);
}
exports.sendHttpError = sendHttpError;
function sendErrorData(ctx, errorData) {
export function sendErrorData(ctx, errorData) {
if (!ctx.session) {
return;
}
if ((0, functions_1.isHttpContext)(ctx)) {
if (isHttpContext(ctx)) {
sendHttpErrorData(errorData, ctx);
}
else if ((0, functions_1.isWsSession)(ctx.session)) {
ctx.session.ws.send((0, protocol_1.encodeErrorResponse)((0, protocol_1.valueToBuffer)(errorData)), true, false);
else if (isWsSession(ctx.session)) {
ctx.session.ws.send(encodeErrorResponse(valueToBuffer(errorData)), true, false);
}
}
exports.sendErrorData = sendErrorData;
function sendError(server, ctx, basedCode, payload) {
export function sendError(server, ctx, basedCode, payload) {
if (!ctx.session) {
return;
}
if ((0, functions_1.isHttpContext)(ctx)) {
if (isHttpContext(ctx)) {
return sendHttpError(server, ctx, basedCode, payload);
}
else if ((0, functions_1.isWsSession)(ctx.session)) {
const errorData = (0, error_1.createError)(server, ctx, basedCode, payload);
ctx.session.ws.send((0, protocol_1.encodeErrorResponse)((0, protocol_1.valueToBuffer)(errorData)), true, false);
else if (isWsSession(ctx.session)) {
const errorData = createError(server, ctx, basedCode, payload);
ctx.session.ws.send(encodeErrorResponse(valueToBuffer(errorData)), true, false);
}
}
exports.sendError = sendError;
function sendSimpleError(server, ctx, basedCode, route, id, payload) {
export function sendSimpleError(server, ctx, basedCode, route, id, payload) {
if (!ctx.session) {

@@ -79,11 +73,10 @@ return;

}
if ((0, functions_1.isHttpContext)(ctx)) {
if (isHttpContext(ctx)) {
return sendHttpError(server, ctx, basedCode, payload);
}
else if ((0, functions_1.isWsSession)(ctx.session)) {
const errorData = (0, error_1.createError)(server, ctx, basedCode, payload);
ctx.session.ws.send((0, protocol_1.encodeErrorResponse)((0, protocol_1.valueToBuffer)(errorData)), true, false);
else if (isWsSession(ctx.session)) {
const errorData = createError(server, ctx, basedCode, payload);
ctx.session.ws.send(encodeErrorResponse(valueToBuffer(errorData)), true, false);
}
}
exports.sendSimpleError = sendSimpleError;
//# sourceMappingURL=sendError.js.map

@@ -1,2 +0,2 @@

/// <reference types="node" />
/// <reference types="node" resolution-mode="require"/>
import { Context, HttpSession, HttpHeaders } from '@based/functions';

@@ -6,2 +6,1 @@ export declare const end: (ctx: Context<HttpSession>, payload?: string | Buffer | Uint8Array) => void;

export declare const sendHttpResponse: (ctx: Context<HttpSession>, result: any, headers?: HttpHeaders, statusCode?: string) => void;
//# sourceMappingURL=sendHttpResponse.d.ts.map

@@ -1,7 +0,4 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendHttpResponse = exports.sendHeaders = exports.end = void 0;
const stream_1 = require("stream");
const compress_1 = require("./compress");
const end = (ctx, payload) => {
import { Duplex, Readable } from 'stream';
import { compress } from './compress.js';
export const end = (ctx, payload) => {
if (!ctx.session) {

@@ -25,4 +22,3 @@ return;

};
exports.end = end;
const sendHeaders = (ctx, headers) => {
export const sendHeaders = (ctx, headers) => {
for (const header in headers) {

@@ -37,4 +33,3 @@ const value = headers[header];

};
exports.sendHeaders = sendHeaders;
const sendHttpResponse = (ctx, result, headers, statusCode = '200 OK') => {
export const sendHttpResponse = (ctx, result, headers, statusCode = '200 OK') => {
// handle custom http response here...

@@ -50,3 +45,3 @@ if (!ctx.session) {

if (headers) {
(0, exports.sendHeaders)(ctx, headers);
sendHeaders(ctx, headers);
}

@@ -62,7 +57,7 @@ ctx.session.res.end();

}
else if (result instanceof stream_1.Readable || result instanceof stream_1.Duplex) {
else if (result instanceof Readable || result instanceof Duplex) {
ctx.session.res.cork(() => {
ctx.session.res.writeStatus(statusCode);
if (headers) {
(0, exports.sendHeaders)(ctx, headers);
sendHeaders(ctx, headers);
}

@@ -82,3 +77,3 @@ });

}
(0, compress_1.compress)(parsed, headers && ('Content-Encoding' in headers || 'content-encoding' in headers)
compress(parsed, headers && ('Content-Encoding' in headers || 'content-encoding' in headers)
? undefined

@@ -90,3 +85,3 @@ : ctx.session.headers.encoding).then(({ payload, encoding }) => {

if (headers) {
(0, exports.sendHeaders)(ctx, headers);
sendHeaders(ctx, headers);
if (!('Cache-Control' in headers || 'cache-control' in headers)) {

@@ -105,3 +100,3 @@ ctx.session.res.writeHeader('Cache-Control', 'max-age=0, must-revalidate');

}
(0, exports.end)(ctx, payload);
end(ctx, payload);
});

@@ -111,3 +106,2 @@ }

};
exports.sendHttpResponse = sendHttpResponse;
//# sourceMappingURL=sendHttpResponse.js.map

@@ -1,11 +0,11 @@

/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import { Context, BasedFunctionClient, WebSocketSession, HttpSession, Geo } from '@based/functions';
import type { ActiveObservable } from './query';
import type { ActiveObservable } from './query/index.js';
import uws from '@based/uws';
import { BasedFunctions, FunctionConfig } from './functions';
import { BasedAuth, AuthConfig } from './auth';
import { BasedErrorCode, BasedErrorData } from './error';
import { BasedFunctionClient as BasedServerFunctionClient } from './functionApi';
import { ActiveChannel } from './channel';
import { BasedFunctions, FunctionConfig } from './functions/index.js';
import { BasedAuth, AuthConfig } from './auth/index.js';
import { BasedErrorCode, BasedErrorData } from './error/index.js';
import { BasedFunctionClient as BasedServerFunctionClient } from './functionApi/index.js';
import { ActiveChannel } from './channel/index.js';
import util from 'node:util';

@@ -144,2 +144,1 @@ type EventMap = {

export {};
//# sourceMappingURL=server.d.ts.map

@@ -1,16 +0,12 @@

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasedServer = void 0;
const functions_1 = require("@based/functions");
const uws_1 = __importDefault(require("@based/uws"));
const incoming_1 = __importDefault(require("./incoming"));
const functions_2 = require("./functions");
const auth_1 = require("./auth");
const utils_1 = require("@saulx/utils");
const picocolors = require("picocolors");
const functionApi_1 = require("./functionApi");
const node_util_1 = __importDefault(require("node:util"));
import { createRequire as _createRequire } from "module";
const __require = _createRequire(import.meta.url);
import { isClientContext, } from '@based/functions';
import uws from '@based/uws';
import initNetwork from './incoming/index.js';
import { BasedFunctions } from './functions/index.js';
import { BasedAuth } from './auth/index.js';
import { wait } from '@saulx/utils';
const picocolors = __require("picocolors");
import { BasedFunctionClient as BasedServerFunctionClient } from './functionApi/index.js';
import util from 'node:util';
/**

@@ -47,47 +43,61 @@ Based server

*/
class BasedServer {
[node_util_1.default.inspect.custom]() {
export class BasedServer {
clients; // for now any...
client;
functions;
auth;
port;
uwsApp;
silent;
queryEvents;
channelEvents;
rateLimit = {
ws: 2e3,
http: 1e3,
drain: 500,
};
listenSocket;
geo = async (ctx) => {
if (!ctx.session) {
throw new Error('Session expired while parsing geo location');
}
if (isClientContext(ctx)) {
return {
country: 'NL',
ip: ctx.session.ip,
accuracy: 0,
long: 0,
lat: 0,
regions: [],
};
}
else {
throw new Error('Cannot parse geo location from a non external context');
}
};
getIp = (res) => {
return Buffer.from(res.getRemoteAddressAsText()).toString();
};
blockedIps = new Set();
// opposite of blockedIps can never get blocked
allowedIps = new Set();
// per ip so consitent unfortanetly
// check how large it is and make a loop to downgrade it
rateLimitCounter = new Map();
requestsCounterInProgress = false;
requestsCounterTimeout;
obsCleanTimeout;
obsCleanupCycle = 30e3;
activeObservables = {};
activeObservablesById = new Map();
channelCleanTimeout;
channelCleanupCycle = 30e3;
activeChannels = {};
activeChannelsById = new Map();
listeners = {};
workerRequest;
[util.inspect.custom]() {
return `BasedServer [${this.port}]`;
}
constructor(opts) {
this.rateLimit = {
ws: 2e3,
http: 1e3,
drain: 500,
};
this.geo = async (ctx) => {
if (!ctx.session) {
throw new Error('Session expired while parsing geo location');
}
if ((0, functions_1.isClientContext)(ctx)) {
return {
country: 'NL',
ip: ctx.session.ip,
accuracy: 0,
long: 0,
lat: 0,
regions: [],
};
}
else {
throw new Error('Cannot parse geo location from a non external context');
}
};
this.getIp = (res) => {
return Buffer.from(res.getRemoteAddressAsText()).toString();
};
this.blockedIps = new Set();
// opposite of blockedIps can never get blocked
this.allowedIps = new Set();
// per ip so consitent unfortanetly
// check how large it is and make a loop to downgrade it
this.rateLimitCounter = new Map();
this.requestsCounterInProgress = false;
this.obsCleanupCycle = 30e3;
this.activeObservables = {};
this.activeObservablesById = new Map();
this.channelCleanupCycle = 30e3;
this.activeChannels = {};
this.activeChannelsById = new Map();
this.listeners = {};
if (opts.query) {

@@ -103,4 +113,4 @@ this.queryEvents = opts.query;

this.clients = opts.clients ?? {};
this.functions = new functions_2.BasedFunctions(this, opts.functions);
this.auth = new auth_1.BasedAuth(this, opts.auth);
this.functions = new BasedFunctions(this, opts.functions);
this.auth = new BasedAuth(this, opts.auth);
if (opts.client) {

@@ -111,3 +121,3 @@ // @ts-ignore - allow different ones if you want a special client

else {
this.client = new functionApi_1.BasedFunctionClient(this);
this.client = new BasedServerFunctionClient(this);
}

@@ -123,3 +133,3 @@ if (opts.rateLimit) {

}
(0, incoming_1.default)(this, opts);
initNetwork(this, opts);
}

@@ -172,3 +182,3 @@ emit(type, client, val, err) {

}
await (0, utils_1.wait)(10);
await wait(10);
return new Promise((resolve, reject) => {

@@ -194,3 +204,3 @@ this.uwsApp.listen(this.port, sharedSocket ? 0 : 1, (listenSocket) => {

if (this.listenSocket) {
uws_1.default.us_listen_socket_close(this.listenSocket);
uws.us_listen_socket_close(this.listenSocket);
this.listenSocket = null;

@@ -202,3 +212,2 @@ }

}
exports.BasedServer = BasedServer;
//# sourceMappingURL=server.js.map
import { Context, BasedRoute, BasedFunctionTypes } from '@based/functions';
import { BasedServer } from './server';
export declare const verifyRoute: <T extends BasedFunctionTypes>(server: BasedServer, ctx: Context, type: T, route: BasedRoute | null, name: string, id?: number) => BasedRoute<T, "name" | "type">;
//# sourceMappingURL=verifyRoute.d.ts.map
import { BasedServer } from './server.js';
export declare const verifyRoute: <T extends BasedFunctionTypes>(server: BasedServer, ctx: Context, type: T, route: BasedRoute | null, name: string, id?: number) => BasedRoute<T>;

@@ -1,8 +0,5 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyRoute = void 0;
const functions_1 = require("@based/functions");
const sendError_1 = require("./sendError");
const error_1 = require("./error");
const verifyRoute = (server, ctx = server.client.ctx, type, route, name, id) => {
import { isClientContext, isBasedRoute, } from '@based/functions';
import { sendSimpleError } from './sendError.js';
import { BasedErrorCode, createError } from './error/index.js';
export const verifyRoute = (server, ctx = server.client.ctx, type, route, name, id) => {
if (!ctx.session) {

@@ -12,4 +9,4 @@ return null;

if (!route) {
if (!(0, functions_1.isClientContext)(ctx)) {
throw (0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionNotFound, {
if (!isClientContext(ctx)) {
throw createError(server, ctx, BasedErrorCode.FunctionNotFound, {
route: {

@@ -21,12 +18,12 @@ name,

}
(0, sendError_1.sendSimpleError)(server, ctx, error_1.BasedErrorCode.FunctionNotFound, { name, type }, id);
sendSimpleError(server, ctx, BasedErrorCode.FunctionNotFound, { name, type }, id);
return null;
}
if (route.internalOnly === true && (0, functions_1.isClientContext)(ctx)) {
(0, sendError_1.sendSimpleError)(server, ctx, error_1.BasedErrorCode.FunctionNotFound, { name, type }, id);
if (route.internalOnly === true && isClientContext(ctx)) {
sendSimpleError(server, ctx, BasedErrorCode.FunctionNotFound, { name, type }, id);
return null;
}
if (!(0, functions_1.isBasedRoute)(type, route)) {
if (!(0, functions_1.isClientContext)(ctx)) {
throw (0, error_1.createError)(server, ctx, error_1.BasedErrorCode.FunctionIsWrongType, {
if (!isBasedRoute(type, route)) {
if (!isClientContext(ctx)) {
throw createError(server, ctx, BasedErrorCode.FunctionIsWrongType, {
route,

@@ -36,3 +33,3 @@ observableId: id,

}
(0, sendError_1.sendSimpleError)(server, ctx, error_1.BasedErrorCode.FunctionIsWrongType, { name, type }, id);
sendSimpleError(server, ctx, BasedErrorCode.FunctionIsWrongType, { name, type }, id);
return null;

@@ -43,3 +40,2 @@ }

};
exports.verifyRoute = verifyRoute;
//# sourceMappingURL=verifyRoute.js.map
{
"name": "@based/server",
"version": "6.9.0",
"version": "7.0.1",
"license": "MIT",
"main": "./dist/index.js",
"type": "module",
"files": [

@@ -11,9 +12,4 @@ "package.json",

],
"exports": {
".": "./dist/index.js",
"./worker": "./dist/worker/api.js",
"./dist/worker/api": "./dist/worker/api.js"
},
"scripts": {
"build": "npx tsc",
"build": "npx tsc",
"watch": "npm run build -- --watch",

@@ -25,5 +21,5 @@ "clean": "rimraf {.turbo,dist,node_modules}"

"@based/uws": "^4.1.0",
"@saulx/diff": "^1.1.4",
"@saulx/hash": "^2.0.0",
"@saulx/utils": "^3.5.0",
"@saulx/diff": "^2.0.1",
"@saulx/hash": "^3.0.0",
"@saulx/utils": "^4.0.1",
"picocolors": "^1.0.0",

@@ -33,11 +29,11 @@ "jsonexport": "^3.2.0",

"mime-types": "^2.1.31",
"@based/functions": "^2.2.3"
"@based/functions": "^3.0.0"
},
"devDependencies": {
"@types/mime-types": "2.1.1",
"@types/node": "^17.0.23",
"ts-node": "^10.1.0",
"typescript": "^4.3.5",
"@saulx/tsconfig": "^1.0.5",
"@saulx/prettier-config": "^1.0.0",
"typescript": "^5.2.2",
"rimraf": "^3.0.2"
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc