code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
async toggleServerStatus(name) {
const server = this.mcpServerConfigs.find((s) => s.name === name);
if (!server)
return {
success: false,
error: `MCP server ${name} not found in config file.`,
};
const mcp = this.mcps[name];
const online = !!mcp ? !!(await mcp.ping()) : false; // If the server is not in the mcps object, it is not running
if (online) {
const killed = this.pruneMCPServer(name);
return {
success: killed,
error: killed ? null : `Failed to kill MCP server: ${name}`,
};
} else {
const startupResult = await this.startMCPServer(name);
return { success: startupResult.success, error: startupResult.error };
}
}
|
Toggle the MCP server (start or stop)
@param {string} name - The name of the MCP server to toggle
@returns {Promise<{success: boolean, error: string | null}>}
|
toggleServerStatus
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/index.js
|
MIT
|
async deleteServer(name) {
const server = this.mcpServerConfigs.find((s) => s.name === name);
if (!server)
return {
success: false,
error: `MCP server ${name} not found in config file.`,
};
const mcp = this.mcps[name];
const online = !!mcp ? !!(await mcp.ping()) : false; // If the server is not in the mcps object, it is not running
if (online) this.pruneMCPServer(name);
this.removeMCPServerFromConfig(name);
delete this.mcps[name];
delete this.mcpLoadingResults[name];
this.log(`MCP server was killed and removed from config file: ${name}`);
return { success: true, error: null };
}
|
Delete the MCP server - will also remove it from the config file
@param {string} name - The name of the MCP server to delete
@returns {Promise<{success: boolean, error: string | null}>}
|
deleteServer
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/index.js
|
MIT
|
constructor() {
if (MCPHypervisor._instance) return MCPHypervisor._instance;
MCPHypervisor._instance = this;
this.log("Initializing MCP Hypervisor - subsequent calls will boot faster");
this.#setupConfigFile();
return this;
}
|
The results of the MCP server loading process.
@type { { [key: string]: {status: 'success' | 'failed', message: string} } }
|
constructor
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
log(text, ...args) {
console.log(`\x1b[36m[${this.constructor.name}]\x1b[0m ${text}`, ...args);
}
|
Setup the MCP server definitions file.
Will create the file/directory if it doesn't exist already in storage/plugins with blank options
|
log
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
get mcpServerConfigs() {
const servers = safeJsonParse(
fs.readFileSync(this.mcpServerJSONPath, "utf8"),
{ mcpServers: {} }
);
return Object.entries(servers.mcpServers).map(([name, server]) => ({
name,
server,
}));
}
|
Get the MCP servers from the JSON file.
@returns { { name: string, server: { command: string, args: string[], env: { [key: string]: string } } }[] } The MCP servers.
|
mcpServerConfigs
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
removeMCPServerFromConfig(name) {
const servers = safeJsonParse(
fs.readFileSync(this.mcpServerJSONPath, "utf8"),
{ mcpServers: {} }
);
if (!servers.mcpServers[name]) return false;
delete servers.mcpServers[name];
fs.writeFileSync(
this.mcpServerJSONPath,
JSON.stringify(servers, null, 2),
"utf8"
);
this.log(`MCP server ${name} removed from config file`);
return true;
}
|
Remove the MCP server from the config file
@param {string} name - The name of the MCP server to remove
@returns {boolean} - True if the MCP server was removed, false otherwise
|
removeMCPServerFromConfig
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
async reloadMCPServers() {
this.pruneMCPServers();
await this.bootMCPServers();
}
|
Reload the MCP servers - can be used to reload the MCP servers without restarting the server or app
and will also apply changes to the config file if any where made.
|
reloadMCPServers
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
async startMCPServer(name) {
if (this.mcps[name])
return { success: false, error: `MCP server ${name} already running` };
const config = this.mcpServerConfigs.find((s) => s.name === name);
if (!config)
return {
success: false,
error: `MCP server ${name} not found in config file`,
};
try {
await this.#startMCPServer(config);
this.mcpLoadingResults[name] = {
status: "success",
message: `Successfully connected to MCP server: ${name}`,
};
return { success: true, message: `MCP server ${name} started` };
} catch (e) {
this.log(`Failed to start single MCP server: ${name}`, {
error: e.message,
code: e.code,
syscall: e.syscall,
path: e.path,
stack: e.stack,
});
this.mcpLoadingResults[name] = {
status: "failed",
message: `Failed to start MCP server: ${name} [${e.code || "NO_CODE"}] ${e.message}`,
};
// Clean up failed connection
if (this.mcps[name]) {
this.mcps[name].close();
delete this.mcps[name];
}
return { success: false, error: e.message };
}
}
|
Start a single MCP server by its server name - public method
@param {string} name - The name of the MCP server to start
@returns {Promise<{success: boolean, error: string | null}>}
|
startMCPServer
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
pruneMCPServer(name) {
if (!name || !this.mcps[name]) return true;
this.log(`Pruning MCP server: ${name}`);
const mcp = this.mcps[name];
const childProcess = mcp.transport._process;
if (childProcess) childProcess.kill(1);
mcp.transport.close();
delete this.mcps[name];
this.mcpLoadingResults[name] = {
status: "failed",
message: `Server was stopped manually by the administrator.`,
};
return true;
}
|
Prune a single MCP server by its server name
@param {string} name - The name of the MCP server to prune
@returns {boolean} - True if the MCP server was pruned, false otherwise
|
pruneMCPServer
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
pruneMCPServers() {
this.log(`Pruning ${Object.keys(this.mcps).length} MCP servers...`);
for (const name of Object.keys(this.mcps)) {
if (!this.mcps[name]) continue;
const mcp = this.mcps[name];
const childProcess = mcp.transport._process;
if (childProcess)
this.log(`Killing MCP ${name} (PID: ${childProcess.pid})`, {
killed: childProcess.kill(1),
});
mcp.transport.close();
mcp.close();
}
this.mcps = {};
this.mcpLoadingResults = {};
}
|
Prune the MCP servers - pkills and forgets all MCP servers
@returns {void}
|
pruneMCPServers
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
createHttpTransport(server) {
const url = new URL(server.url);
// If the server block has a type property then use that to determine the transport type
switch (server.type) {
case "streamable":
return new StreamableHTTPClientTransport(url, {
requestInit: {
headers: server.headers,
},
});
default:
return new SSEClientTransport(url, {
requestInit: {
headers: server.headers,
},
});
}
}
|
Create MCP client transport for http MCP server.
@param {Object} server - The server definition
@returns {StreamableHTTPClientTransport | SSEClientTransport} - The server transport
|
createHttpTransport
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
async bootMCPServers() {
if (Object.keys(this.mcps).length > 0) {
this.log("MCP Servers already running, skipping boot.");
return this.mcpLoadingResults;
}
const serverDefinitions = this.mcpServerConfigs;
for (const { name, server } of serverDefinitions) {
if (
server.anythingllm?.hasOwnProperty("autoStart") &&
server.anythingllm.autoStart === false
) {
this.log(
`MCP server ${name} has anythingllm.autoStart property set to false, skipping boot!`
);
this.mcpLoadingResults[name] = {
status: "failed",
message: `MCP server ${name} has anythingllm.autoStart property set to false, boot skipped!`,
};
continue;
}
try {
await this.#startMCPServer({ name, server });
// Verify the connection is alive?
// if (!(await mcp.ping())) throw new Error('Connection failed to establish');
this.mcpLoadingResults[name] = {
status: "success",
message: `Successfully connected to MCP server: ${name}`,
};
} catch (e) {
this.log(`Failed to start MCP server: ${name}`, {
error: e.message,
code: e.code,
syscall: e.syscall,
path: e.path,
stack: e.stack, // Adding stack trace for better debugging
});
this.mcpLoadingResults[name] = {
status: "failed",
message: `Failed to start MCP server: ${name} [${e.code || "NO_CODE"}] ${e.message}`,
};
// Clean up failed connection
if (this.mcps[name]) {
this.mcps[name].close();
delete this.mcps[name];
}
}
}
const runningServers = Object.keys(this.mcps);
this.log(
`Successfully started ${runningServers.length} MCP servers:`,
runningServers
);
return this.mcpLoadingResults;
}
|
Boot the MCP servers according to the server definitions.
This function will skip booting MCP servers if they are already running.
@returns { Promise<{ [key: string]: {status: string, message: string} }> } The results of the boot process.
|
bootMCPServers
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/MCP/hypervisor/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/MCP/hypervisor/index.js
|
MIT
|
function chatHistoryViewable(_request, response, next) {
if ("DISABLE_VIEW_CHAT_HISTORY" in process.env)
return response
.status(422)
.send("This feature has been disabled by the administrator.");
next();
}
|
A simple middleware that validates that the chat history is viewable.
via the `DISABLE_VIEW_CHAT_HISTORY` environment variable being set AT ALL.
@param {Request} request - The request object.
@param {Response} response - The response object.
@param {NextFunction} next - The next function.
|
chatHistoryViewable
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/chatHistoryViewable.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/chatHistoryViewable.js
|
MIT
|
function communityHubDownloadsEnabled(request, response, next) {
if (!("COMMUNITY_HUB_BUNDLE_DOWNLOADS_ENABLED" in process.env)) {
return response.status(422).json({
error:
"Community Hub bundle downloads are not enabled. The system administrator must enable this feature manually to allow this instance to download these types of items. See https://docs.anythingllm.com/configuration#anythingllm-hub-agent-skills",
});
}
// If the admin specifically did not set the system to `allow_all` then downloads are limited to verified items or private items only.
// This is to prevent users from downloading unverified items and importing them into their own instance without understanding the risks.
const item = response.locals.bundleItem;
if (
!item.verified &&
item.visibility !== "private" &&
process.env.COMMUNITY_HUB_BUNDLE_DOWNLOADS_ENABLED !== "allow_all"
) {
return response.status(422).json({
error:
"Community hub bundle downloads are limited to verified public items or private team items only. Please contact the system administrator to review or modify this setting. See https://docs.anythingllm.com/configuration#anythingllm-hub-agent-skills",
});
}
next();
}
|
### Must be called after `communityHubItem`
Checks if community hub bundle downloads are enabled. The reason this functionality is disabled
by default is that since AgentSkills, Workspaces, and DataConnectors are all imported from the
community hub via unzipping a bundle - it would be possible for a malicious user to craft and
download a malicious bundle and import it into their own hosted instance. To avoid this, this
functionality is disabled by default and must be enabled manually by the system administrator.
On hosted systems, this would not be an issue since the user cannot modify this setting, but those
who self-host can still unlock this feature manually by setting the environment variable
which would require someone who likely has the capacity to understand the risks and the
implications of importing unverified items that can run code on their system, container, or instance.
@see {@link https://docs.anythingllm.com/docs/community-hub/import}
@param {import("express").Request} request
@param {import("express").Response} response
@param {import("express").NextFunction} next
@returns {void}
|
communityHubDownloadsEnabled
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/communityHubDownloadsEnabled.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/communityHubDownloadsEnabled.js
|
MIT
|
async function communityHubItem(request, response, next) {
const { importId } = reqBody(request);
if (!importId)
return response.status(500).json({
success: false,
error: "Import ID is required",
});
const {
url,
item,
error: fetchError,
} = await CommunityHub.getBundleItem(importId);
if (fetchError)
return response.status(500).json({
success: false,
error: fetchError,
});
response.locals.bundleItem = item;
response.locals.bundleUrl = url;
next();
}
|
Fetch the bundle item from the community hub.
Sets `response.locals.bundleItem` and `response.locals.bundleUrl`.
|
communityHubItem
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/communityHubDownloadsEnabled.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/communityHubDownloadsEnabled.js
|
MIT
|
function strictMultiUserRoleValid(allowedRoles = DEFAULT_ROLES) {
return async (request, response, next) => {
// If the access-control is allowable for all - skip validations and continue;
if (allowedRoles.includes(ROLES.all)) {
next();
return;
}
const multiUserMode =
response.locals?.multiUserMode ??
(await SystemSettings.isMultiUserMode());
if (!multiUserMode) return response.sendStatus(401).end();
const user =
response.locals?.user ?? (await userFromSession(request, response));
if (allowedRoles.includes(user?.role)) {
next();
return;
}
return response.sendStatus(401).end();
};
}
|
Explicitly check that multi user mode is enabled as well as that the
requesting user has the appropriate role to modify or call the URL.
@param {string[]} allowedRoles - The roles that are allowed to access the route
@returns {function}
|
strictMultiUserRoleValid
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/multiUserProtected.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/multiUserProtected.js
|
MIT
|
function flexUserRoleValid(allowedRoles = DEFAULT_ROLES) {
return async (request, response, next) => {
// If the access-control is allowable for all - skip validations and continue;
// It does not matter if multi-user or not.
if (allowedRoles.includes(ROLES.all)) {
next();
return;
}
// Bypass if not in multi-user mode
const multiUserMode =
response.locals?.multiUserMode ??
(await SystemSettings.isMultiUserMode());
if (!multiUserMode) {
next();
return;
}
const user =
response.locals?.user ?? (await userFromSession(request, response));
if (allowedRoles.includes(user?.role)) {
next();
return;
}
return response.sendStatus(401).end();
};
}
|
Apply role permission checks IF the current system is in multi-user mode.
This is relevant for routes that are shared between MUM and single-user mode.
@param {string[]} allowedRoles - The roles that are allowed to access the route
@returns {function}
|
flexUserRoleValid
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/multiUserProtected.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/multiUserProtected.js
|
MIT
|
async function isMultiUserSetup(_request, response, next) {
const multiUserMode = await SystemSettings.isMultiUserMode();
if (!multiUserMode) {
response.status(403).json({
error: "Invalid request",
});
return;
}
next();
return;
}
|
Apply role permission checks IF the current system is in multi-user mode.
This is relevant for routes that are shared between MUM and single-user mode.
@param {string[]} allowedRoles - The roles that are allowed to access the route
@returns {function}
|
isMultiUserSetup
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/multiUserProtected.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/multiUserProtected.js
|
MIT
|
async function simpleSSOEnabled(_, response, next) {
if (!("SIMPLE_SSO_ENABLED" in process.env)) {
return response
.status(403)
.send(
"Simple SSO is not enabled. It must be enabled to validate or issue temporary auth tokens."
);
}
// If the multi-user mode response local is not set, we need to check if it's enabled.
if (!("multiUserMode" in response.locals)) {
const multiUserMode = await SystemSettings.isMultiUserMode();
response.locals.multiUserMode = multiUserMode;
}
if (!response.locals.multiUserMode) {
return response
.status(403)
.send(
"Multi-User mode is not enabled. It must be enabled to use Simple SSO."
);
}
next();
}
|
Checks if simple SSO is enabled for issuance of temporary auth tokens.
Note: This middleware must be called after `validApiKey`.
@param {import("express").Request} request
@param {import("express").Response} response
@param {import("express").NextFunction} next
@returns {void}
|
simpleSSOEnabled
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/simpleSSOEnabled.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/simpleSSOEnabled.js
|
MIT
|
function simpleSSOLoginDisabled() {
return (
"SIMPLE_SSO_ENABLED" in process.env && "SIMPLE_SSO_NO_LOGIN" in process.env
);
}
|
Checks if simple SSO login is disabled by checking if the
SIMPLE_SSO_NO_LOGIN environment variable is set as well as
SIMPLE_SSO_ENABLED is set.
This check should only be run when in multi-user mode when used.
@returns {boolean}
|
simpleSSOLoginDisabled
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/simpleSSOEnabled.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/simpleSSOEnabled.js
|
MIT
|
async function simpleSSOLoginDisabledMiddleware(_, response, next) {
if (!("multiUserMode" in response.locals)) {
const multiUserMode = await SystemSettings.isMultiUserMode();
response.locals.multiUserMode = multiUserMode;
}
if (response.locals.multiUserMode && simpleSSOLoginDisabled()) {
response.status(403).json({
success: false,
error: "Login via credentials has been disabled by the administrator.",
});
return;
}
next();
}
|
Middleware that checks if simple SSO login is disabled by checking if the
SIMPLE_SSO_NO_LOGIN environment variable is set as well as
SIMPLE_SSO_ENABLED is set.
This middleware will 403 if SSO is enabled and no login is allowed and
the system is in multi-user mode. Otherwise, it will call next.
@param {import("express").Request} request
@param {import("express").Response} response
@param {import("express").NextFunction} next
@returns {void}
|
simpleSSOLoginDisabledMiddleware
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/middleware/simpleSSOEnabled.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/middleware/simpleSSOEnabled.js
|
MIT
|
function isNullOrNaN(value) {
if (value === null) return true;
return isNaN(value);
}
|
@typedef {object} DocumentMetadata
@property {string} id - eg; "123e4567-e89b-12d3-a456-426614174000"
@property {string} url - eg; "file://example.com/index.html"
@property {string} title - eg; "example.com/index.html"
@property {string} docAuthor - eg; "no author found"
@property {string} description - eg; "No description found."
@property {string} docSource - eg; "URL link uploaded by the user."
@property {string} chunkSource - eg; link://https://example.com
@property {string} published - ISO 8601 date string
@property {number} wordCount - Number of words in the document
@property {string} pageContent - The raw text content of the document
@property {number} token_count_estimate - Number of tokens in the document
|
isNullOrNaN
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
constructor(config = {}) {
/*
config can be a ton of things depending on what is required or optional by the specific splitter.
Non-splitter related keys
{
splitByFilename: string, // TODO
}
------
Default: "RecursiveCharacterTextSplitter"
Config: {
chunkSize: number,
chunkOverlap: number,
chunkHeaderMeta: object | null, // Gets appended to top of each chunk as metadata
}
------
*/
this.config = config;
this.#splitter = this.#setSplitter(config);
}
|
@typedef {object} DocumentMetadata
@property {string} id - eg; "123e4567-e89b-12d3-a456-426614174000"
@property {string} url - eg; "file://example.com/index.html"
@property {string} title - eg; "example.com/index.html"
@property {string} docAuthor - eg; "no author found"
@property {string} description - eg; "No description found."
@property {string} docSource - eg; "URL link uploaded by the user."
@property {string} chunkSource - eg; link://https://example.com
@property {string} published - ISO 8601 date string
@property {number} wordCount - Number of words in the document
@property {string} pageContent - The raw text content of the document
@property {number} token_count_estimate - Number of tokens in the document
|
constructor
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
log(text, ...args) {
console.log(`\x1b[35m[TextSplitter]\x1b[0m ${text}`, ...args);
}
|
@typedef {object} DocumentMetadata
@property {string} id - eg; "123e4567-e89b-12d3-a456-426614174000"
@property {string} url - eg; "file://example.com/index.html"
@property {string} title - eg; "example.com/index.html"
@property {string} docAuthor - eg; "no author found"
@property {string} description - eg; "No description found."
@property {string} docSource - eg; "URL link uploaded by the user."
@property {string} chunkSource - eg; link://https://example.com
@property {string} published - ISO 8601 date string
@property {number} wordCount - Number of words in the document
@property {string} pageContent - The raw text content of the document
@property {number} token_count_estimate - Number of tokens in the document
|
log
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
static buildHeaderMeta(metadata = {}) {
if (!metadata || Object.keys(metadata).length === 0) return null;
const PLUCK_MAP = {
title: {
as: "sourceDocument",
pluck: (metadata) => {
return metadata?.title || null;
},
},
published: {
as: "published",
pluck: (metadata) => {
return metadata?.published || null;
},
},
chunkSource: {
as: "source",
pluck: (metadata) => {
const validPrefixes = ["link://", "youtube://"];
// If the chunkSource is a link or youtube link, we can add the URL
// as its source in the metadata so the LLM can use it for context.
// eg prompt: Where did you get this information? -> answer: "from https://example.com"
if (
!metadata?.chunkSource || // Exists
!metadata?.chunkSource.length || // Is not empty
typeof metadata.chunkSource !== "string" || // Is a string
!validPrefixes.some(
(prefix) => metadata.chunkSource.startsWith(prefix) // Has a valid prefix we respect
)
)
return null;
// We know a prefix is present, so we can split on it and return the rest.
// If nothing is found, return null and it will not be added to the metadata.
let source = null;
for (const prefix of validPrefixes) {
source = metadata.chunkSource.split(prefix)?.[1] || null;
if (source) break;
}
return source;
},
},
};
const pluckedData = {};
Object.entries(PLUCK_MAP).forEach(([key, value]) => {
if (!(key in metadata)) return; // Skip if the metadata key is not present.
const pluckedValue = value.pluck(metadata);
if (!pluckedValue) return; // Skip if the plucked value is null/empty.
pluckedData[value.as] = pluckedValue;
});
return pluckedData;
}
|
Creates a string of metadata to be prepended to each chunk.
@param {DocumentMetadata} metadata - Metadata to be prepended to each chunk.
@returns {{[key: ('title' | 'published' | 'source')]: string}} Object of metadata that will be prepended to each chunk.
|
buildHeaderMeta
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
stringifyHeader() {
if (!this.config.chunkHeaderMeta) return null;
let content = "";
Object.entries(this.config.chunkHeaderMeta).map(([key, value]) => {
if (!key || !value) return;
content += `${key}: ${value}\n`;
});
if (!content) return null;
return `<document_metadata>\n${content}</document_metadata>\n\n`;
}
|
Creates a string of metadata to be prepended to each chunk.
|
stringifyHeader
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
async splitText(documentText) {
return this.#splitter._splitText(documentText);
}
|
Creates a string of metadata to be prepended to each chunk.
|
splitText
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
constructor({ chunkSize, chunkOverlap, chunkHeader = null }) {
const {
RecursiveCharacterTextSplitter,
} = require("@langchain/textsplitters");
this.log(`Will split with`, { chunkSize, chunkOverlap });
this.chunkHeader = chunkHeader;
this.engine = new RecursiveCharacterTextSplitter({
chunkSize,
chunkOverlap,
});
}
|
Creates a string of metadata to be prepended to each chunk.
|
constructor
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
log(text, ...args) {
console.log(`\x1b[35m[RecursiveSplitter]\x1b[0m ${text}`, ...args);
}
|
Creates a string of metadata to be prepended to each chunk.
|
log
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
async _splitText(documentText) {
if (!this.chunkHeader) return this.engine.splitText(documentText);
const strings = await this.engine.splitText(documentText);
const documents = await this.engine.createDocuments(strings, [], {
chunkHeader: this.chunkHeader,
});
return documents
.filter((doc) => !!doc.pageContent)
.map((doc) => doc.pageContent);
}
|
Creates a string of metadata to be prepended to each chunk.
|
_splitText
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextSplitter/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextSplitter/index.js
|
MIT
|
async ttsBuffer(textInput) {
try {
const result = await this.openai.audio.speech.create({
model: "tts-1",
voice: this.voice,
input: textInput,
});
return Buffer.from(await result.arrayBuffer());
} catch (e) {
console.error(e);
}
return null;
}
|
Generates a buffer from the given text input using the OpenAI compatible TTS service.
@param {string} textInput - The text to be converted to audio.
@returns {Promise<Buffer>} A buffer containing the audio data.
|
ttsBuffer
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/TextToSpeech/openAiGeneric/index.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/TextToSpeech/openAiGeneric/index.js
|
MIT
|
async function resetAllVectorStores({ vectorDbKey }) {
try {
const workspaces = await Workspace.where();
purgeEntireVectorCache(); // Purges the entire vector-cache folder.
await DocumentVectors.delete(); // Deletes all document vectors from the database.
await Document.delete(); // Deletes all documents from the database.
await EventLogs.logEvent("workspace_vectors_reset", {
reason: "System vector configuration changed",
});
console.log(
"Resetting anythingllm managed vector namespaces for",
vectorDbKey
);
const VectorDb = getVectorDbClass(vectorDbKey);
if (vectorDbKey === "pgvector") {
/*
pgvector has a reset method that drops the entire embedding table
which is required since if this function is called we will need to
reset the embedding column VECTOR dimension value and you cannot change
the dimension value of an existing vector column.
*/
await VectorDb.reset();
} else {
for (const workspace of workspaces) {
try {
await VectorDb["delete-namespace"]({ namespace: workspace.slug });
} catch (e) {
console.error(e.message);
}
}
}
return true;
} catch (error) {
console.error("Failed to reset vector stores:", error);
return false;
}
}
|
Resets all vector database and associated content:
- Purges the entire vector-cache folder.
- Deletes all document vectors from the database.
- Deletes all documents from the database.
- Deletes all vector db namespaces for each workspace.
- Logs an event indicating the reset.
@param {string} vectorDbKey - The _previous_ vector database provider name that we will be resetting.
@returns {Promise<boolean>} - True if successful, false otherwise.
|
resetAllVectorStores
|
javascript
|
Mintplex-Labs/anything-llm
|
server/utils/vectorStore/resetAllVectorStores.js
|
https://github.com/Mintplex-Labs/anything-llm/blob/master/server/utils/vectorStore/resetAllVectorStores.js
|
MIT
|
constructor (path, name, options) {
super()
this.grpc = grpc
this.servers = []
this.ports = []
this.data = {}
// app options / settings
this.context = new Context()
this.env = process.env.NODE_ENV || 'development'
if (path) {
this.addService(path, name, options)
}
}
|
Create a gRPC service
@class
@param {String|Object} path - Optional path to the protocol buffer definition file
- Object specifying <code>root</code> directory and <code>file</code> to load
- Loaded grpc object
- The static service proto object itself
@param {Object} name - Optional name of the service or an array of names. Otherwise all services are used.
In case of proto path the name of the service as defined in the proto definition.
In case of proto object the name of the constructor.
@param {Object} options - Options to be passed to <code>grpc.load</code>
|
constructor
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
addService (path, name, options) {
const load = typeof path === 'string' || (_.isObject(path) && path.root && path.file)
let proto = path
if (load) {
let protoFilePath = path
const loadOptions = Object.assign({}, options)
if (typeof path === 'object' && path.root && path.file) {
protoFilePath = path.file
if (!loadOptions.includeDirs) {
// Support either multiple or single paths.
loadOptions.includeDirs = Array.isArray(path.root) ? path.root : [path.root]
}
}
const pd = protoLoader.loadSync(protoFilePath, loadOptions)
proto = grpc.loadPackageDefinition(pd)
}
const data = mu.getServiceDefinitions(proto)
if (!name) {
name = Object.keys(data)
} else if (typeof name === 'string') {
name = [name]
}
for (const k in data) {
const v = data[k]
if (name.indexOf(k) >= 0 || name.indexOf(v.shortServiceName) >= 0) {
v.middleware = []
v.handlers = {}
for (const method in v.methods) {
v.handlers[method] = null
}
this.data[k] = v
}
}
if (!this.name) {
if (Array.isArray(name)) {
this.name = name[0]
}
}
}
|
Add the service and initialize the app with the proto.
Basically this can be used if you don't have the data at app construction time for some reason.
This is different than `grpc.Server.addService()`.
@param {String|Object} path - Path to the protocol buffer definition file
- Object specifying <code>root</code> directory and <code>file</code> to load
- Loaded grpc object
- The static service proto object itself
@param {Object} name - Optional name of the service or an array of names. Otherwise all services are used.
In case of proto path the name of the service as defined in the proto definition.
In case of proto object the name of the constructor.
@param {Object} options - Options to be passed to <code>grpc.load</code>
|
addService
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
use (service, name, ...fns) {
if (typeof service === 'function') {
const isFunction = typeof name === 'function'
for (const serviceName in this.data) {
const _service = this.data[serviceName]
if (isFunction) {
_service.middleware = _service.middleware.concat(service, name, fns)
} else {
_service.middleware = _service.middleware.concat(service, fns)
}
}
} else if (typeof service === 'object') {
// we have object notation
const testKey = Object.keys(service)[0]
if (typeof service[testKey] === 'function' || Array.isArray(service[testKey])) {
// first property of object is a function or array
// that means we have service-level middleware of RPC handlers
for (const key in service) {
// lets try to match the key to any service name first
const val = service[key]
const serviceName = this._getMatchingServiceName(key)
if (serviceName) {
// we have a matching service
// lets add service-level middleware to that service
this.data[serviceName].middleware.push(val)
} else {
// we need to find the matching function to set it as handler
const { serviceName, methodName } = this._getMatchingCall(key)
if (serviceName && methodName) {
if (typeof val === 'function') {
this.use(serviceName, methodName, val)
} else {
this.use(serviceName, methodName, ...val)
}
} else {
throw new TypeError(`Unknown method: ${key}`)
}
}
}
} else if (typeof service[testKey] === 'object') {
for (const serviceName in service) {
for (const middlewareName in service[serviceName]) {
const middleware = service[serviceName][middlewareName]
if (typeof middleware === 'function') {
this.use(serviceName, middlewareName, middleware)
} else if (Array.isArray(middleware)) {
this.use(serviceName, middlewareName, ...middleware)
} else {
throw new TypeError(`Handler for ${middlewareName} is not a function or array`)
}
}
}
} else {
throw new TypeError(`Invalid type for handler for ${testKey}`)
}
} else {
if (typeof name !== 'string') {
// name is a function pre-pand it to fns
fns.unshift(name)
// service param can either be a service name or a function name
// first lets try to match a service
const serviceName = this._getMatchingServiceName(service)
if (serviceName) {
// we have a matching service
// lets add service-level middleware to that service
const sd = this.data[serviceName]
sd.middleware = sd.middleware.concat(fns)
return
} else {
// service param is a function name
// lets try to find the matching call and service
const { serviceName, methodName } = this._getMatchingCall(service)
if (!serviceName || !methodName) {
throw new Error(`Unknown identifier: ${service}`)
}
this.use(serviceName, methodName, ...fns)
return
}
}
// we have a string service, and string name
const serviceName = this._getMatchingServiceName(service)
if (!serviceName) {
throw new Error(`Unknown service ${service}`)
}
const sd = this.data[serviceName]
let methodName
for (const _methodName in sd.methods) {
if (this._getMatchingHandlerName(sd.methods[_methodName], _methodName, name)) {
methodName = _methodName
break
}
}
if (!methodName) {
throw new Error(`Unknown method ${name} for service ${serviceName}`)
}
if (sd.handlers[methodName]) {
throw new Error(`Handler for ${name} already defined for service ${serviceName}`)
}
sd.handlers[methodName] = sd.middleware.concat(fns)
}
}
|
Define middleware and handlers.
@param {String|Object} service Service name
@param {String|Function} name RPC name
@param {Function|Array} fns - Middleware and/or handler
@example <caption>Define handler for RPC function 'getUser' in first service we find that has that call name.</caption>
app.use('getUser', getUser)
@example <caption>Define handler with middleware for RPC function 'getUser' in first service we find that has that call name.</caption>
app.use('getUser', mw1, mw2, getUser)
@example <caption>Define handler with middleware for RPC function 'getUser' in service 'MyService'. We pick first service that matches the name.</caption>
app.use('MyService', 'getUser', mw1, mw2, getUser)
@example <caption>Define handler with middleware for rpc function 'getUser' in service 'MyService' with full package name.</caption>
app.use('myorg.myapi.v1.MyService', 'getUser', mw1, mw2, getUser)
@example <caption>Using destructuring define handlers for rpc functions 'getUser' and 'deleteUser'. Here we would match the first service that has a `getUser` RPC method.</caption>
app.use({ getUser, deleteUser })
@example <caption>Apply middleware to all handlers for a given service. We match first service that has the given name.</caption>
app.use('MyService', mw1)
@example <caption>Apply middleware to all handlers for a given service using full namespaced package name.</caption>
app.use('myorg.myapi.v1.MyService', mw1)
@example <caption>Using destructuring define handlers for RPC functions 'getUser' and 'deleteUser'. We match first service that has the given name.</caption>
// deleteUser has middleware mw1 and mw2
app.use({ MyService: { getUser, deleteUser: [mw1, mw2, deleteUser] } })
@example <caption>Using destructuring define handlers for RPC functions 'getUser' and 'deleteUser'.</caption>
// deleteUser has middleware mw1 and mw2
app.use({ 'myorg.myapi.v1.MyService': { getUser, deleteUser: [mw1, mw2, deleteUser] } })
@example <caption>Multiple services using object notation.</caption>
app.use(mw1) // global for all services
app.use('MyService', mw2) // applies to first matched service named 'MyService'
app.use({
'myorg.myapi.v1.MyService': { // matches MyService
sayGoodbye: handler1, // has mw1, mw2
sayHello: [ mw3, handler2 ] // has mw1, mw2, mw3
},
'myorg.myapi.v1.MyOtherService': {
saySomething: handler3 // only has mw1
}
})
|
use
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
callback (descriptor, mw) {
const handler = compose(mw)
if (!this.listeners('error').length) this.on('error', this.onerror)
return (call, callback) => {
const context = this._createContext(call, descriptor)
return exec(context, handler, callback)
}
}
|
Define middleware and handlers.
@param {String|Object} service Service name
@param {String|Function} name RPC name
@param {Function|Array} fns - Middleware and/or handler
@example <caption>Define handler for RPC function 'getUser' in first service we find that has that call name.</caption>
app.use('getUser', getUser)
@example <caption>Define handler with middleware for RPC function 'getUser' in first service we find that has that call name.</caption>
app.use('getUser', mw1, mw2, getUser)
@example <caption>Define handler with middleware for RPC function 'getUser' in service 'MyService'. We pick first service that matches the name.</caption>
app.use('MyService', 'getUser', mw1, mw2, getUser)
@example <caption>Define handler with middleware for rpc function 'getUser' in service 'MyService' with full package name.</caption>
app.use('myorg.myapi.v1.MyService', 'getUser', mw1, mw2, getUser)
@example <caption>Using destructuring define handlers for rpc functions 'getUser' and 'deleteUser'. Here we would match the first service that has a `getUser` RPC method.</caption>
app.use({ getUser, deleteUser })
@example <caption>Apply middleware to all handlers for a given service. We match first service that has the given name.</caption>
app.use('MyService', mw1)
@example <caption>Apply middleware to all handlers for a given service using full namespaced package name.</caption>
app.use('myorg.myapi.v1.MyService', mw1)
@example <caption>Using destructuring define handlers for RPC functions 'getUser' and 'deleteUser'. We match first service that has the given name.</caption>
// deleteUser has middleware mw1 and mw2
app.use({ MyService: { getUser, deleteUser: [mw1, mw2, deleteUser] } })
@example <caption>Using destructuring define handlers for RPC functions 'getUser' and 'deleteUser'.</caption>
// deleteUser has middleware mw1 and mw2
app.use({ 'myorg.myapi.v1.MyService': { getUser, deleteUser: [mw1, mw2, deleteUser] } })
@example <caption>Multiple services using object notation.</caption>
app.use(mw1) // global for all services
app.use('MyService', mw2) // applies to first matched service named 'MyService'
app.use({
'myorg.myapi.v1.MyService': { // matches MyService
sayGoodbye: handler1, // has mw1, mw2
sayHello: [ mw3, handler2 ] // has mw1, mw2, mw3
},
'myorg.myapi.v1.MyOtherService': {
saySomething: handler3 // only has mw1
}
})
|
callback
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
onerror (err, ctx) {
assert(err instanceof Error, `non-error thrown: ${err}`)
if (this.silent) return
const msg = err.stack || err.toString()
console.error()
console.error(msg.replace(/^/gm, ' '))
console.error()
}
|
Default error handler.
@param {Error} err
|
onerror
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
async start (port, creds, options) {
if (_.isObject(port)) {
if (_.isObject(creds)) {
options = creds
}
creds = port
port = null
}
if (!port || typeof port !== 'string' || (typeof port === 'string' && port.length === 0)) {
port = '127.0.0.1:0'
}
if (!creds || !_.isObject(creds)) {
creds = this.grpc.ServerCredentials.createInsecure()
}
const server = new this.grpc.Server(options)
server.tryShutdownAsync = util.promisify(server.tryShutdown)
const bindAsync = util.promisify(server.bindAsync).bind(server)
for (const sn in this.data) {
const sd = this.data[sn]
const handlerValues = Object.values(sd.handlers).filter(Boolean)
const hasHandlers = handlerValues && handlerValues.length
if (sd.handlers && hasHandlers) {
const composed = {}
for (const k in sd.handlers) {
const v = sd.handlers[k]
if (!v) { continue }
const md = sd.methods[k]
const shortComposedKey = md.originalName || _.camelCase(md.name)
composed[shortComposedKey] = this.callback(sd.methods[k], v)
}
server.addService(sd.service, composed)
}
}
const bound = await bindAsync(port, creds)
if (!bound) {
throw new Error(`Failed to bind to port: ${port}`)
}
this.ports.push(bound)
server.start()
this.servers.push({
server,
port
})
return server
}
|
Start the service. All middleware and handlers have to be set up prior to calling <code>start</code>.
Throws in case we fail to bind to the given port.
@param {String} port - The hostport for the service. Default: <code>127.0.0.1:0</code>
@param {Object} creds - Credentials options. Default: <code>grpc.ServerCredentials.createInsecure()</code>
@param {Object} options - The start options to be passed to `grpc.Server` constructor.
@return {Promise<Object>} server - The <code>grpc.Server</code> instance
@example
app.start('localhost:50051')
@example <caption>Start same app on multiple ports</caption>
app.start('127.0.0.1:50050')
app.start('127.0.0.1:50051')
|
start
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
async close () {
await Promise.all(this.servers.map(({ server }) => server.tryShutdownAsync()))
}
|
Close the service(s).
@example
app.close()
|
close
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
toJSON () {
const own = Object.getOwnPropertyNames(this)
const props = _.pull(own, ...REMOVE_PROPS, ...EE_PROPS)
return _.pick(this, props)
}
|
Return JSON representation.
We only bother showing settings.
@return {Object}
@api public
|
toJSON
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
_createContext (call, descriptor) {
const type = mu.getCallTypeFromCall(call) || mu.getCallTypeFromDescriptor(descriptor)
const { name, fullName, service } = descriptor
const pkgName = descriptor.package
const context = new Context()
Object.assign(context, this.context)
context.request = new Request(call, type)
context.response = new Response(call, type)
Object.assign(context, {
name,
fullName,
service,
app: this,
package: pkgName,
locals: {} // set fresh locals
})
return context
}
|
@member {Boolean} silent Whether to supress logging errors in <code>onerror</code>. Default: <code>false</code>, that is errors will be logged to `stderr`.
@memberof Mali#
|
_createContext
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
_getMatchingServiceName (key) {
if (this.data[key]) {
return key
}
for (const serviceName in this.data) {
if (serviceName.endsWith('.' + key)) {
return serviceName
}
}
return null
}
|
@member {Boolean} silent Whether to supress logging errors in <code>onerror</code>. Default: <code>false</code>, that is errors will be logged to `stderr`.
@memberof Mali#
|
_getMatchingServiceName
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
_getMatchingCall (key) {
for (const _serviceName in this.data) {
const service = this.data[_serviceName]
for (const _methodName in service.methods) {
const method = service.methods[_methodName]
if (this._getMatchingHandlerName(method, _methodName, key)) {
return { methodName: key, serviceName: _serviceName }
}
}
}
return { serviceName: null, methodName: null }
}
|
@member {Boolean} silent Whether to supress logging errors in <code>onerror</code>. Default: <code>false</code>, that is errors will be logged to `stderr`.
@memberof Mali#
|
_getMatchingCall
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
_getMatchingHandlerName (handler, name, value) {
return name === value ||
name.endsWith('/' + value) ||
(handler?.originalName === value) ||
(handler?.name === value) ||
(handler && _.camelCase(handler.name) === _.camelCase(value))
}
|
@member {Boolean} silent Whether to supress logging errors in <code>onerror</code>. Default: <code>false</code>, that is errors will be logged to `stderr`.
@memberof Mali#
|
_getMatchingHandlerName
|
javascript
|
malijs/mali
|
lib/app.js
|
https://github.com/malijs/mali/blob/master/lib/app.js
|
Apache-2.0
|
function create (metadata) {
if (typeof metadata !== 'object') {
return
}
if (metadata instanceof grpc.Metadata) {
return metadata
}
const meta = new grpc.Metadata()
for (const k in metadata) {
const v = metadata[k]
if (Buffer.isBuffer(v)) {
meta.set(k, v)
} else if (v !== null && typeof v !== 'undefined') {
const toAdd = typeof v === 'string' ? v : v.toString()
if (toAdd) {
meta.set(k, toAdd)
}
}
}
return meta
}
|
Utility helper function to create <code>Metadata</code> object from plain Javascript object
This strictly just calls <code>Metadata.add</code> with the key / value map of objects.
If the value is a <code>Buffer</code> it's passed as is.
If the value is a <code>Sting</code> it's passed as is.
Else if the value defined and not a string we simply call <code>toString()</code>.
Note that <code>Metadata</code> only accept string or buffer values.
@param {Object} metadata Plain javascript object to tranform into <code>Metadata</code>
If an instance of <code>Metadata</code> is passed in it is simply returned
@return {Metadata} An instance of <code>Metadata</code>, or `undefined` if input is not an object
|
create
|
javascript
|
malijs/mali
|
lib/metadata.js
|
https://github.com/malijs/mali/blob/master/lib/metadata.js
|
Apache-2.0
|
constructor (call, type) {
this.call = call
this.type = type
if (call.metadata instanceof grpc.Metadata) {
this.metadata = call.metadata.getMap()
} else {
this.metadata = call.metadata
}
if (type === CallType.RESPONSE_STREAM ||
type === CallType.UNARY) {
this.req = call.request
} else {
this.req = call
}
}
|
Creates a Mali Request instance
@param {Object} call the grpc call instance
@param {String} type the call type. one of `@malijs/call-types` enums.
|
constructor
|
javascript
|
malijs/mali
|
lib/request.js
|
https://github.com/malijs/mali/blob/master/lib/request.js
|
Apache-2.0
|
getMetadata () {
return Metadata.create(this.metadata)
}
|
Gets the requests metadata as a `grpc.Metadata` object instance
@return {Object} request metadata
|
getMetadata
|
javascript
|
malijs/mali
|
lib/request.js
|
https://github.com/malijs/mali/blob/master/lib/request.js
|
Apache-2.0
|
get (field) {
let val
if (this.metadata) {
val = this.metadata[field]
}
return val
}
|
Gets specific request metadata field value
@param {*} field the metadata field name
@return {*} the metadata value for the field
@example
console.log(ctx.request.get('foo')) // 'bar'
|
get
|
javascript
|
malijs/mali
|
lib/request.js
|
https://github.com/malijs/mali/blob/master/lib/request.js
|
Apache-2.0
|
constructor (call, type) {
this.call = call
this.type = type
if (type === CallType.DUPLEX) {
this.res = call
}
}
|
Creates a Mali Response instance
@param {Object} call the grpc call instance
@param {String} type the call type. one of `@malijs/call-types` enums.
|
constructor
|
javascript
|
malijs/mali
|
lib/response.js
|
https://github.com/malijs/mali/blob/master/lib/response.js
|
Apache-2.0
|
set (field, val) {
if (arguments.length === 2) {
if (!this.metadata) {
this.metadata = {}
}
this.metadata[field] = val
} else {
const md = field instanceof grpc.Metadata ? field.getMap() : field
if (typeof md === 'object') {
for (const key in md) {
this.set(key, md[key])
}
}
}
}
|
Sets specific response header metadata field value
@param {String|Object} field the metadata field name or object for metadata
@param {*} [val] the value of the field
@example <caption>Using string field name and value</caption>
ctx.response.set('foo', 'bar')
@example <caption>Using object</caption>
ctx.response.set({
foo: 'bar'
})
|
set
|
javascript
|
malijs/mali
|
lib/response.js
|
https://github.com/malijs/mali/blob/master/lib/response.js
|
Apache-2.0
|
get (field) {
let val
if (this.metadata) {
val = this.metadata[field]
}
return val
}
|
Gets the response header metadata value
@param {String} field the field name
@return {*} the metadata field value
@example
console.log(ctx.response.get('foo')) // 'bar'
|
get
|
javascript
|
malijs/mali
|
lib/response.js
|
https://github.com/malijs/mali/blob/master/lib/response.js
|
Apache-2.0
|
getMetadata () {
return Metadata.create(this.metadata)
}
|
Gets the response metadata as a `grpc.Metadata` object instance
@return {Object} response metadata
|
getMetadata
|
javascript
|
malijs/mali
|
lib/response.js
|
https://github.com/malijs/mali/blob/master/lib/response.js
|
Apache-2.0
|
sendMetadata (md) {
// if forcing send reset our metadata
if (md && (typeof md === 'object' || md instanceof grpc.Metadata)) {
this.metadata = null
this.set(md)
}
const data = this.getMetadata()
if (data) {
this.call.sendMetadata(data)
}
}
|
Sends the response header metadata. Optionally (re)sets the header metadata as well.
@param {Object} md optional header metadata object to set into the request before sending
if there is existing metadata in the response it is cleared
if param is not provided `sendMetadata` sends the existing metadata in the response
@example <caption>Set and send</caption>
ctx.response.sendMetadata({
foo: 'bar'
})
@example <caption>Set and send later</caption>
ctx.response.set('foo', 'bar')
// ... later
ctx.response.sendMetadata()
|
sendMetadata
|
javascript
|
malijs/mali
|
lib/response.js
|
https://github.com/malijs/mali/blob/master/lib/response.js
|
Apache-2.0
|
getStatus (field) {
let val
if (this.status) {
val = this.status[field]
}
return val
}
|
Gets the response status / trailer metadata value
@param {String} field the field name
@return {*} the metadata field value
@example
console.log(ctx.response.getStatus('bar')) // 'baz'
|
getStatus
|
javascript
|
malijs/mali
|
lib/response.js
|
https://github.com/malijs/mali/blob/master/lib/response.js
|
Apache-2.0
|
setStatus (field, val) {
if (arguments.length === 2) {
if (!this.status) {
this.status = {}
}
this.status[field] = val
} else {
const md = field instanceof grpc.Metadata ? field.getMap() : field
if (typeof md === 'object') {
for (const key in md) {
this.setStatus(key, md[key])
}
}
}
}
|
Sets specific response status / trailer metadata field value
@param {String|Object} field the metadata field name or object for metadata
@param {*} val the value of the field
@example <caption>Using string field name and value</caption>
ctx.response.setStatus('foo', 'bar')
@example <caption>Using object</caption>
ctx.response.setStatus({
foo: 'bar'
})
|
setStatus
|
javascript
|
malijs/mali
|
lib/response.js
|
https://github.com/malijs/mali/blob/master/lib/response.js
|
Apache-2.0
|
getStatusMetadata () {
return Metadata.create(this.status, { addEmpty: false })
}
|
Gets the response status / trailer metadata as a `grpc.Metadata` object instance
@return {Object} response status / trailer metadata
|
getStatusMetadata
|
javascript
|
malijs/mali
|
lib/response.js
|
https://github.com/malijs/mali/blob/master/lib/response.js
|
Apache-2.0
|
function isInt(n) {
return Number(n) === n && n % 1 === 0;
}
|
The scroll callback is called when the user scrolls
@callback ScrollCallback
@param {{x: Number, y: Number}} position
@param {string} direction
|
isInt
|
javascript
|
terwanerik/ScrollTrigger
|
dist/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
|
MIT
|
function isFloat(n) {
return Number(n) === n && n % 1 !== 0;
}
|
The scroll callback is called when the user scrolls
@callback ScrollCallback
@param {{x: Number, y: Number}} position
@param {string} direction
|
isFloat
|
javascript
|
terwanerik/ScrollTrigger
|
dist/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
|
MIT
|
function Trigger(element, options) {
_classCallCheck(this, Trigger);
this.element = element;
options = extend_default()(new DefaultOptions().trigger, options);
this.offset = options.offset;
this.toggle = options.toggle;
this.once = options.once;
this.visible = null;
this.active = true;
}
|
Creates a new Trigger from the given element and options
@param {Element|HTMLElement} element
@param {DefaultOptions.trigger} [options=DefaultOptions.trigger] options
|
Trigger
|
javascript
|
terwanerik/ScrollTrigger
|
dist/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
|
MIT
|
function TriggerCollection(triggers) {
TriggerCollection_classCallCheck(this, TriggerCollection);
/**
* @member {Trigger[]}
*/
this.triggers = triggers instanceof Array ? triggers : [];
}
|
Initializes the collection
@param {Trigger[]} [triggers=[]] triggers A set of triggers to init with, optional
|
TriggerCollection
|
javascript
|
terwanerik/ScrollTrigger
|
dist/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
|
MIT
|
function ScrollAnimationLoop(options, callback) {
ScrollAnimationLoop_classCallCheck(this, ScrollAnimationLoop);
this._parseOptions(options);
if (typeof callback === 'function') {
this.callback = callback;
}
this.direction = 'none';
this.position = this.getPosition();
this.lastAction = this._getTimestamp();
this._startRun();
this._boundListener = this._didScroll.bind(this);
this.element.addEventListener('scroll', this._boundListener);
}
|
ScrollAnimationLoop constructor.
Starts a requestAnimationFrame loop as long as the user has scrolled the scrollElement. Stops after a certain time.
@param {DefaultOptions.scroll} [options=DefaultOptions.scroll] options The options for the loop
@param {ScrollCallback} callback [loop=null] The loop callback
|
ScrollAnimationLoop
|
javascript
|
terwanerik/ScrollTrigger
|
dist/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
|
MIT
|
function ScrollTrigger(options) {
ScrollTrigger_classCallCheck(this, ScrollTrigger);
this._parseOptions(options);
this._initCollection();
this._initLoop();
}
|
Constructor for the scroll trigger
@param {DefaultOptions} [options=DefaultOptions] options
|
ScrollTrigger
|
javascript
|
terwanerik/ScrollTrigger
|
dist/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/dist/ScrollTrigger.js
|
MIT
|
constructor(options) {
this._parseOptions(options)
this._initCollection()
this._initLoop()
}
|
Constructor for the scroll trigger
@param {DefaultOptions} [options=DefaultOptions] options
|
constructor
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
_parseOptions(options) {
options = extend(new DefaultOptions(), options)
this.defaultTrigger = options.trigger
this.scrollOptions = options.scroll
}
|
Parses the options
@param {DefaultOptions} [options=DefaultOptions] options
@private
|
_parseOptions
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
_initCollection() {
const scrollAttributes = document.querySelectorAll('[data-scroll]')
let elements = []
if (scrollAttributes.length > 0) {
elements = this.createTriggers(scrollAttributes)
}
this.collection = new TriggerCollection(elements)
}
|
Initializes the collection, picks all [data-scroll] elements as initial elements
@private
|
_initCollection
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
_scrollCallback(position, direction) {
this.collection.call((trigger) => {
trigger.checkVisibility(this.scrollOptions.element, direction)
})
this.scrollOptions.callback(position, direction)
}
|
Callback for checking triggers
@param {{x: number, y: number}} position
@param {string} direction
@private
|
_scrollCallback
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
createTrigger(element, options) {
return new Trigger(element, extend(this.defaultTrigger, options))
}
|
Creates a Trigger object from a given element and optional option set
@param {HTMLElement} element
@param {DefaultOptions.trigger} [options=DefaultOptions.trigger] options
@returns Trigger
|
createTrigger
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
createTriggers(elements, options) {
let triggers = []
elements.each((element) => {
triggers.push(this.createTrigger(element, options))
})
return triggers
}
|
Creates an array of triggers
@param {HTMLElement[]|NodeList} elements
@param {Object} [options=null] options
@returns {Trigger[]} Array of triggers
|
createTriggers
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
add(objects, options) {
if (objects instanceof HTMLElement) {
this.collection.add(this.createTrigger(objects, options))
return this
}
if (objects instanceof Trigger) {
this.collection.add(objects)
return this
}
if (objects instanceof NodeList) {
this.collection.add(this.createTriggers(objects, options))
return this
}
if (Array.isArray(objects) && objects.length && objects[0] instanceof Trigger) {
this.collection.add(objects)
return this
}
if (Array.isArray(objects) && objects.length && objects[0] instanceof HTMLElement) {
this.collection.add(this.createTriggers(objects, options))
return this
}
// assume it's a query string
this.collection.add(this.createTriggers(document.querySelectorAll(objects), options))
return this
}
|
Adds triggers
@param {string|HTMLElement|NodeList|Trigger|Trigger[]} objects A list of objects or a query
@param {Object} [options=null] options
@returns {ScrollTrigger}
|
add
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
remove(objects) {
if (objects instanceof Trigger) {
this.collection.remove(objects)
return this
}
if (Array.isArray(objects) && objects.length && objects[0] instanceof Trigger) {
this.collection.remove(objects)
return this
}
if (objects instanceof HTMLElement) {
this.collection.remove(this.search(objects))
return this
}
if (Array.isArray(objects) && objects.length && objects[0] instanceof HTMLElement) {
this.collection.remove(this.search(objects))
return this
}
if (objects instanceof NodeList) {
this.collection.remove(this.search(objects))
return this
}
if (Array.isArray(objects) && objects.length && objects[0] instanceof Trigger) {
this.collection.remove(objects)
return this
}
// assume it's a query string
this.collection.remove(this.query(objects.toString()))
return this
}
|
Removes triggers
@param {string|HTMLElement|NodeList|Trigger|Trigger[]} objects A list of objects or a query
@returns {ScrollTrigger}
|
remove
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
query(selector) {
return this.collection.query(selector)
}
|
Lookup one or multiple triggers by a query string
@param {string} selector
@returns {Trigger[]}
|
query
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
search(element) {
return this.collection.search(element)
}
|
Lookup one or multiple triggers by a certain HTMLElement or NodeList
@param {HTMLElement|HTMLElement[]|NodeList} element
@returns {Trigger|Trigger[]|null}
|
search
|
javascript
|
terwanerik/ScrollTrigger
|
src/ScrollTrigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/ScrollTrigger.js
|
MIT
|
constructor(options, callback) {
this._parseOptions(options)
if (typeof callback === 'function') {
this.callback = callback
}
this.direction = 'none'
this.position = this.getPosition()
this.lastAction = this._getTimestamp()
this._startRun()
this._boundListener = this._didScroll.bind(this)
this.element.addEventListener('scroll', this._boundListener)
}
|
ScrollAnimationLoop constructor.
Starts a requestAnimationFrame loop as long as the user has scrolled the scrollElement. Stops after a certain time.
@param {DefaultOptions.scroll} [options=DefaultOptions.scroll] options The options for the loop
@param {ScrollCallback} callback [loop=null] The loop callback
|
constructor
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/ScrollAnimationLoop.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js
|
MIT
|
_parseOptions(options) {
let defaults = new DefaultOptions().scroll
if (typeof options != 'function') {
defaults.callback = () => {}
defaults = extend(defaults, options)
} else {
defaults.callback = options
}
this.element = defaults.element
this.sustain = defaults.sustain
this.callback = defaults.callback
this.startCallback = defaults.start
this.stopCallback = defaults.stop
this.directionChange = defaults.directionChange
}
|
Parses the options
@param {DefaultOptions.scroll} [options=DefaultOptions.scroll] options The options for the loop
@private
|
_parseOptions
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/ScrollAnimationLoop.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js
|
MIT
|
_didScroll() {
const newPosition = this.getPosition()
if (this.position !== newPosition) {
let newDirection = this.direction
if (newPosition.x !== this.position.x) {
newDirection = newPosition.x > this.position.x ? 'right' : 'left'
} else if (newPosition.y !== this.position.y) {
newDirection = newPosition.y > this.position.y ? 'bottom' : 'top'
} else {
newDirection = 'none'
}
if (newDirection !== this.direction) {
this.direction = newDirection
if (typeof this.directionChange === 'function') {
this.directionChange(this.direction)
}
}
this.position = newPosition
this.lastAction = this._getTimestamp()
} else {
this.direction = 'none'
}
if (!this.running) {
this._startRun()
}
}
|
Callback when the user scrolled the element
@private
|
_didScroll
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/ScrollAnimationLoop.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js
|
MIT
|
_startRun() {
this.running = true
if (typeof this.startCallback === 'function') {
this.startCallback()
}
this._loop()
}
|
Starts the loop, calls the start callback
@private
|
_startRun
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/ScrollAnimationLoop.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js
|
MIT
|
_stopRun() {
this.running = false
if (typeof this.stopCallback === 'function') {
this.stopCallback()
}
}
|
Stops the loop, calls the stop callback
@private
|
_stopRun
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/ScrollAnimationLoop.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js
|
MIT
|
getPosition() {
const left = this.element.pageXOffset || this.element.scrollLeft || document.documentElement.scrollLeft || 0
const top = this.element.pageYOffset || this.element.scrollTop || document.documentElement.scrollTop || 0
return { x: left, y: top }
}
|
The current position of the element
@returns {{x: number, y: number}}
|
getPosition
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/ScrollAnimationLoop.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js
|
MIT
|
_getTimestamp() {
return Number(Date.now())
}
|
The current timestamp in ms
@returns {number}
@private
|
_getTimestamp
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/ScrollAnimationLoop.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js
|
MIT
|
_tick() {
this.callback(this.position, this.direction)
const now = this._getTimestamp()
if (now - this.lastAction > this.sustain) {
this._stopRun()
}
if (this.running) {
this._loop()
}
}
|
One single tick of the animation
@private
|
_tick
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/ScrollAnimationLoop.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/ScrollAnimationLoop.js
|
MIT
|
constructor(element, options) {
this.element = element
options = extend(new DefaultOptions().trigger, options)
this.offset = options.offset
this.toggle = options.toggle
this.once = options.once
this.visible = null
this.active = true
}
|
Creates a new Trigger from the given element and options
@param {Element|HTMLElement} element
@param {DefaultOptions.trigger} [options=DefaultOptions.trigger] options
|
constructor
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/Trigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js
|
MIT
|
checkVisibility(parent, direction) {
if (!this.active) {
return this.visible
}
const parentWidth = parent.offsetWidth || parent.innerWidth || 0
const parentHeight = parent.offsetHeight || parent.innerHeight || 0
const parentFrame = { w: parentWidth, h: parentHeight }
const rect = this.getBounds()
const visible = this._checkVisibility(rect, parentFrame, direction)
if (visible !== this.visible) {
this.visible = visible
const response = this._toggleCallback()
if (response instanceof Promise) {
response.then(this._toggleClass.bind(this)).catch(e => {
console.error('Trigger promise failed')
console.error(e)
})
} else {
this._toggleClass()
}
if (this.visible && this.once) {
this.active = false
}
} else if (visible) {
if (typeof this.toggle.callback.visible == 'function') {
return this.toggle.callback.visible.call(this.element, this)
}
}
return visible
}
|
Checks if the Trigger is in the viewport, calls the callbacks and toggles the classes
@param {HTMLElement|HTMLDocument|Window} parent
@param {string} direction top, bottom, left, right
@returns {boolean} If the element is visible
|
checkVisibility
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/Trigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js
|
MIT
|
getBounds() {
return this.element.getBoundingClientRect()
}
|
Get the bounds of this element
@return {ClientRect | DOMRect}
|
getBounds
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/Trigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js
|
MIT
|
_getElementOffset(rect, direction) {
let offset = { x: 0, y: 0 }
if (typeof this.offset.element.x === 'function') {
offset.x = rect.width * this.offset.element.x(this, rect, direction)
} else if (isFloat(this.offset.element.x)) {
offset.x = rect.width * this.offset.element.x
} else if (isInt(this.offset.element.x)) {
offset.x = this.offset.element.x
}
if (typeof this.offset.element.y === 'function') {
offset.y = rect.height * this.offset.element.y(this, rect, direction)
} else if (isFloat(this.offset.element.y)) {
offset.y = rect.height * this.offset.element.y
} else if (isInt(this.offset.element.y)) {
offset.y = this.offset.element.y
}
return offset
}
|
Get the calculated offset to place on the element
@param {ClientRect} rect
@param {string} direction top, bottom, left, right
@returns {{x: number, y: number}}
@private
|
_getElementOffset
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/Trigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js
|
MIT
|
_getViewportOffset(parent, direction) {
let offset = { x: 0, y: 0 }
if (typeof this.offset.viewport.x === 'function') {
offset.x = parent.w * this.offset.viewport.x(this, parent, direction)
} else if (isFloat(this.offset.viewport.x)) {
offset.x = parent.w * this.offset.viewport.x
} else if (isInt(this.offset.viewport.x)) {
offset.x = this.offset.viewport.x
}
if (typeof this.offset.viewport.y === 'function') {
offset.y = parent.h * this.offset.viewport.y(this, parent, direction)
} else if (isFloat(this.offset.viewport.y)) {
offset.y = parent.h * this.offset.viewport.y
} else if (isInt(this.offset.viewport.y)) {
offset.y = this.offset.viewport.y
}
return offset
}
|
Get the calculated offset to place on the viewport
@param {{w: number, h: number}} parent
@param {string} direction top, bottom, left, right
@returns {{x: number, y: number}}
@private
|
_getViewportOffset
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/Trigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js
|
MIT
|
_checkVisibility(rect, parent, direction) {
const elementOffset = this._getElementOffset(rect, direction)
const viewportOffset = this._getViewportOffset(parent, direction)
let visible = true
if ((rect.left - viewportOffset.x) < -(rect.width - elementOffset.x)) {
visible = false
}
if ((rect.left + viewportOffset.x) > (parent.w - elementOffset.x)) {
visible = false
}
if ((rect.top - viewportOffset.y) < -(rect.height - elementOffset.y)) {
visible = false
}
if ((rect.top + viewportOffset.y) > (parent.h - elementOffset.y)) {
visible = false
}
return visible
}
|
Check the visibility of the trigger in the viewport, with offsets applied
@param {ClientRect} rect
@param {{w: number, h: number}} parent
@param {string} direction top, bottom, left, right
@returns {boolean}
@private
|
_checkVisibility
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/Trigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js
|
MIT
|
_toggleCallback() {
if (this.visible) {
if (typeof this.toggle.callback.in == 'function') {
return this.toggle.callback.in.call(this.element, this)
}
} else {
if (typeof this.toggle.callback.out == 'function') {
return this.toggle.callback.out.call(this.element, this)
}
}
}
|
Toggles the callback
@private
@return null|Promise
|
_toggleCallback
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/Trigger.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/Trigger.js
|
MIT
|
constructor(triggers) {
/**
* @member {Trigger[]}
*/
this.triggers = triggers instanceof Array ? triggers : []
}
|
Initializes the collection
@param {Trigger[]} [triggers=[]] triggers A set of triggers to init with, optional
|
constructor
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/TriggerCollection.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js
|
MIT
|
add(objects) {
if (objects instanceof Trigger) {
// single
return this.triggers.push(objects)
}
objects.each((trigger) => {
if (trigger instanceof Trigger) {
this.triggers.push(trigger)
} else {
console.error('Object added to TriggerCollection is not a Trigger. Object: ', trigger)
}
})
}
|
Adds one or multiple Trigger objects
@param {Trigger|Trigger[]} objects
|
add
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/TriggerCollection.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js
|
MIT
|
remove(objects) {
if (objects instanceof Trigger) {
objects = [objects]
}
this.triggers = this.triggers.filter((trigger) => {
let hit = false
objects.each((object) => {
if (object == trigger) {
hit = true
}
})
return !hit
})
}
|
Removes one or multiple Trigger objects
@param {Trigger|Trigger[]} objects
|
remove
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/TriggerCollection.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js
|
MIT
|
query(selector) {
return this.triggers.filter((trigger) => {
const element = trigger.element
const parent = element.parentNode
const nodes = [].slice.call(parent.querySelectorAll(selector))
return nodes.indexOf(element) > -1
})
}
|
Lookup one or multiple triggers by a query string
@param {string} selector
@returns {Trigger[]}
|
query
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/TriggerCollection.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js
|
MIT
|
search(element) {
const found = this.triggers.filter((trigger) => {
if (element instanceof NodeList || Array.isArray(element)) {
let hit = false
element.each((el) => {
if (trigger.element == el) {
hit = true
}
})
return hit
}
return trigger.element == element
})
return found.length == 0 ? null : (found.length > 1 ? found : found[0])
}
|
Lookup one or multiple triggers by a certain HTMLElement or NodeList
@param {HTMLElement|HTMLElement[]|NodeList} element
@returns {Trigger|Trigger[]|null}
|
search
|
javascript
|
terwanerik/ScrollTrigger
|
src/scripts/TriggerCollection.js
|
https://github.com/terwanerik/ScrollTrigger/blob/master/src/scripts/TriggerCollection.js
|
MIT
|
function iterate() {
fs.stat(paths[complete], function(err, stats) {
if (err) {
return callback(err);
}
var pathTime = stats.mtime.getTime();
var comparisonTime = time.getTime();
var difference = pathTime - comparisonTime;
if (difference > tolerance) {
return callback(null, true);
} else {
override(paths[complete], time, function(include) {
if (include) {
callback(null, true);
} else {
++complete;
if (complete >= paths.length) {
return callback(null, false);
}
iterate();
}
});
}
});
}
|
Determine if any of the given files are newer than the provided time.
@param {Array.<string>} paths List of file paths.
@param {Date} time The comparison time.
@param {number} tolerance Maximum time in milliseconds that the destination
file is allowed to be newer than the source file to compensate for
imprecisions in modification times in file systems.
@param {function(string, Date, function(boolean))} override Override.
@param {function(Err, boolean)} callback Callback called with any error and
a boolean indicating whether any one of the supplied files is newer than
the comparison time.
|
iterate
|
javascript
|
tschaub/grunt-newer
|
lib/util.js
|
https://github.com/tschaub/grunt-newer/blob/master/lib/util.js
|
MIT
|
function override(filePath, time, include) {
var details = {
task: taskName,
target: targetName,
path: filePath,
time: time
};
options.override(details, include);
}
|
Special handling for tasks that expect the `files` config to be a string
or array of string source paths.
|
override
|
javascript
|
tschaub/grunt-newer
|
tasks/newer.js
|
https://github.com/tschaub/grunt-newer/blob/master/tasks/newer.js
|
MIT
|
function spawnGrunt(dir, done) {
var gruntfile = path.join(dir, 'gruntfile.js');
if (!fs.existsSync(gruntfile)) {
done(new Error('Cannot find gruntfile.js: ' + gruntfile));
} else {
var node = process.argv[0];
var grunt = process.argv[1]; // assumes grunt drives these tests
var child = cp.spawn(node, [grunt, '--verbose', '--stack'], {cwd: dir});
done(null, child);
}
}
|
Spawn a Grunt process.
@param {string} dir Directory with gruntfile.js.
@param {function(Error, Process)} done Callback.
|
spawnGrunt
|
javascript
|
tschaub/grunt-newer
|
test/helper.js
|
https://github.com/tschaub/grunt-newer/blob/master/test/helper.js
|
MIT
|
function cloneFixture(name, done) {
var fixture = path.join(fixtures, name);
if (!fs.existsSync(tmpDir)) {
fs.mkdirSync(tmpDir);
}
tmp.dir({dir: tmpDir}, function(error, dir) {
if (error) {
return done(error);
}
var scratch = path.join(dir, name);
wrench.copyDirRecursive(fixture, scratch, function(error) {
done(error, scratch);
});
});
}
|
Set up before running tests.
@param {string} name Fixture name.
@param {function} done Callback.
|
cloneFixture
|
javascript
|
tschaub/grunt-newer
|
test/helper.js
|
https://github.com/tschaub/grunt-newer/blob/master/test/helper.js
|
MIT
|
function prune(obj) {
return {
src: obj.src,
dest: obj.dest
};
}
|
Create a clone of the object with just src and dest properties.
@param {Object} obj Source object.
@return {Object} Pruned clone.
|
prune
|
javascript
|
tschaub/grunt-newer
|
test/integration/tasks/index.js
|
https://github.com/tschaub/grunt-newer/blob/master/test/integration/tasks/index.js
|
MIT
|
function filter(files) {
return files.map(prune).filter(function(obj) {
return obj.src && obj.src.length > 0;
});
}
|
Remove files config objects with no src files.
@param {Array} files Array of files config objects.
@return {Array} Filtered array of files config objects.
|
filter
|
javascript
|
tschaub/grunt-newer
|
test/integration/tasks/index.js
|
https://github.com/tschaub/grunt-newer/blob/master/test/integration/tasks/index.js
|
MIT
|
constructor(path, methods, middleware, opts = {}) {
this.opts = opts;
this.name = this.opts.name || null;
this.methods = [];
this.paramNames = [];
this.stack = Array.isArray(middleware) ? middleware : [middleware];
for (const method of methods) {
const l = this.methods.push(method.toUpperCase());
if (this.methods[l - 1] === 'GET') this.methods.unshift('HEAD');
}
// ensure middleware is a function
for (let i = 0; i < this.stack.length; i++) {
const fn = this.stack[i];
const type = typeof fn;
if (type !== 'function')
throw new Error(
`${methods.toString()} \`${
this.opts.name || path
}\`: \`middleware\` must be a function, not \`${type}\``
);
}
this.path = path;
this.regexp = pathToRegexp(path, this.paramNames, this.opts);
}
|
Initialize a new routing Layer with given `method`, `path`, and `middleware`.
@param {String|RegExp} path Path string or regular expression.
@param {Array} methods Array of HTTP verbs.
@param {Array} middleware Layer callback/middleware or series of.
@param {Object=} opts
@param {String=} opts.name route name
@param {String=} opts.sensitive case sensitive (default: false)
@param {String=} opts.strict require the trailing slash (default: false)
@returns {Layer}
@private
|
constructor
|
javascript
|
koajs/router
|
lib/layer.js
|
https://github.com/koajs/router/blob/master/lib/layer.js
|
MIT
|
match(path) {
return this.regexp.test(path);
}
|
Returns whether request `path` matches route.
@param {String} path
@returns {Boolean}
@private
|
match
|
javascript
|
koajs/router
|
lib/layer.js
|
https://github.com/koajs/router/blob/master/lib/layer.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.