Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

4.7 KB
Raw Blame
import templateAcls from './constants/acl.constant.json';
import { AGENTS_WITH_NEXT_STEPS_SHOWN } from './constants/general';

export const generateKeyTemplateVar = (keyName: string): string => `{{KEY(${keyName})}}`;

export const hasAnyAccess = (currentAcls: object) => {
  const aclsArray = Object.keys(currentAcls)
    .filter((aclKey) => !currentAcls[aclKey].internal && !templateAcls.page[aclKey]?.internal)
    .map((aclKey) => ({
      access: currentAcls[aclKey]?.access,
      name: templateAcls?.page[aclKey]?.name,
      internal: templateAcls?.page[aclKey]?.internal,
    }));

  return aclsArray.some((acl) => acl.access !== '');
};

export const getInitials = (name: string, email: string) => {
  return name ? name.charAt(0).toUpperCase() : email.charAt(0).toUpperCase();
};

export const extractInitials = (name: string) => {
  return name
    .split(' ')
    .map((n) => n.charAt(0))
    .join('')
    .toUpperCase();
};

/**
 * Validates and sanitizes a redirect path to prevent open redirect vulnerabilities
 * @param path - The path to validate
 * @returns A safe path string or '/' if invalid
 * @example
 * // Returns '/dashboard'
 * sanitizeRedirectPath('/dashboard')
 *
 * // Returns '/search?q=test'
 * sanitizeRedirectPath('/search?q=test')
 *
 * // Returns '/' (invalid - contains protocol)
 * sanitizeRedirectPath('https://evil.com/hack')
 *
 * // Returns '/' (invalid - protocol-relative URL)
 * sanitizeRedirectPath('//evil.com/hack')
 *
 * // Returns '/' (invalid URL)
 * sanitizeRedirectPath('not-a-url')
 */
export const sanitizeRedirectPath = (path: string): string => {
  try {
    if (path.includes('://') || path.startsWith('//')) {
      return '/';
    }

    const urlObject = new URL(path, 'https://smythos.com'); // here smythos.com doesn't matter, we just need the pathname and search params
    return `${urlObject.pathname}${urlObject.search}`;
  } catch {
    return '/';
  }
};

export const getShownAgentIds = () => {
  const data = localStorage.getItem(AGENTS_WITH_NEXT_STEPS_SHOWN);
  return data ? JSON.parse(data) : [];
};

export const recordNextStepsShown = (agentId: string): void => {
  const seenAgents = getShownAgentIds();
  const uniqueAgents = [...new Set([...seenAgents, agentId])];
  localStorage.setItem(AGENTS_WITH_NEXT_STEPS_SHOWN, JSON.stringify(uniqueAgents));
};

export const shouldShowNextSteps = (agentId: string) => {
  const seenAgents = getShownAgentIds();
  return !seenAgents.includes(agentId);
};

export function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export function isProdEnv() {
  // this comes from rollup-fe.config.mjs
  return process.env.NODE_ENV === 'production';
}

/**
 * Supported query param value types for safe URL serialization.
 *
 * Notes:
 * - Arrays/objects are intentionally not supported to avoid ambiguous encoding.
 * - `null`/`undefined` values should typically be omitted from query strings.
 */
export type QueryParamValue = string | number | boolean | null | undefined;

/**
 * Plain query params object shape.
 */
export type QueryParams = Record<string, QueryParamValue>;

/**
 * Builds a query string from a params object while omitting unset or invalid values.
 *
 * Omits:
 * - `undefined` and `null`
 * - empty strings (including whitespace-only)
 * - literal strings 'undefined' and 'null' (common accidental coercions)
 *
 * @param params - Plain query params object.
 * @returns Serialized query string WITHOUT the leading '?'.
 */
export const buildQueryString = (params: QueryParams | undefined): string => {
  if (!params) return '';

  const searchParams = new URLSearchParams();

  for (const [key, rawValue] of Object.entries(params)) {
    if (rawValue === undefined || rawValue === null) continue;

    if (typeof rawValue === 'string') {
      const trimmed = rawValue.trim();
      if (trimmed.length === 0 || trimmed === 'undefined' || trimmed === 'null') continue;
      searchParams.set(key, trimmed);
      continue;
    }

    // Numbers/booleans are safe to stringify.
    searchParams.set(key, `${rawValue}`);
  }

  return searchParams.toString();
};

/**
 * Returns a URL with the provided query params appended (if any).
 *
 * - Uses `buildQueryString` to omit unset/invalid values.
 * - Preserves existing query params on the base URL by appending with '&'.
 *
 * @param baseUrl - URL path or full URL.
 * @param params - Query params to append.
 * @returns `baseUrl` if no query params remain after sanitization; otherwise `baseUrl` with query.
 */
export const withQueryParams = (baseUrl: string, params: QueryParams | undefined): string => {
  const queryString = buildQueryString(params);
  if (queryString.length === 0) return baseUrl;

  const joiner = baseUrl.includes('?') ? '&' : '?';
  return `${baseUrl}${joiner}${queryString}`;
};