--- name: viasocket-apps-api description: >- Every viaSocket Apps API call as a plain-HTTP function, and the module to copy. Use it when a product's server needs to find apps, let users connect them, run their actions, hear their events, or list, pause and delete what runs. --- # The apps module Back to the skill: https://viasocket.com/docs/skill.md Everything a product does in its users’ apps, as the functions of one file: find an app in the catalog, let a user connect it, run any of its actions with that user’s connection, hear its events, and list, pause or delete what runs. Copy the module once into the product’s server; every other document names these functions. The order to call them in: https://viasocket.com/docs/skill/actions-and-events.md. The Connect button: https://viasocket.com/docs/skill/connect.md. ## Functions ```ts // catalog: public, no token searchApps(text) → [{ name, appslugname, iconurl }] // appslugname is the slug every function takes listApps({ offset?, category? }) → [{ appslugname, name, iconurl, category }] // 200 a page; category is a list of names (["Marketing", "Communication"]) // one user: embedToken makes the token on your server; runAction, runCode, sampleEvent and listEvents send no token; every other call here goes to flow-api.viasocket.com, signed with the embed token inside embedToken(userId, { expiresIn? }) → token // no option: it never expires; the token endpoint of https://viasocket.com/docs/skill/connect.md hands the browser one with { expiresIn: '1h' }; the no-expiry token is for the server and never reaches a browser listActions(userId, slug, { type? }) → { service_id, actions: [{ key, name, type, version, versions, action_id, pauses, … }] } // actions and triggers (type: "trigger"): the keys and versions the calls take, read at run time; pauses: null, or why a step with it waits (delay, async, intervention) serviceIdFor(userId, slug) → service_id // only the Connect popup and the prebuilt UI take it listEvents(userId, slug) → { service, actions: [...], triggers: [...] } // each with input_schema, for a form listConnections(userId) → [{ identifier: auth_id, service_id, service_name, connection_label, isExpired, … }] revokeConnection(userId, authId) findEnabledApp(userId, slug, authId?) → script_id | null // active or paused; authId: that connection's flow, for a user with two connections to one app enableApp(userId, slug, authId) → script_id // a credential: server only listOptions(userId, slug, actionKey, { fieldKey, authId, existingFields, version?, search?, paginate? }) → { options: [{ label, value }], paginate, hasMore, message } runAction(scriptId, actionKey, inputData, { version? }) → the app’s response // version: its number, like 'v55'. Pin it when code fills the inputData: a newer version may rename or add fields; throws when no flow has the script_id runCode(scriptId, code, inputData, { action?, version? }) → what the code returned // your JavaScript with the user’s connection sampleEvent(triggerId, authId, authType?, inputData?) → one real event // triggerId: the trigger’s action_id from listActions; authType: the app's service.auth_type, accepted but not needed (the trigger's version carries its own) subscribeEvent(userId, slug, triggerKey, authId, inputData, { code | webhook }, { version?, meta? }) → script_id updateSubscription(userId, scriptId, { code }) listFlows(userId) → [{ id: script_id, status, title, webhook, payload, service_id, auth_id, … }] // webhook: the URL that runs the flow; payload: the body it expects; service_id and auth_id: what an enabled app was enabled with setFlowStatus(userId, scriptId, status) // 0 delete, 1 resume or restore, 2 pause renameFlow(userId, scriptId, { title, description, meta }) ``` ## The module It runs on the server only. It needs `npm i jsonwebtoken` and the `.env` of https://viasocket.com/docs/skill/setup.md. On CommonJS projects without `"type": "module"`, name it `viasocket.mjs`. In another language, port it as is: each function's URL and body are in its code (including the id in `sampleEvent`'s URL, which stays as written), and `https://flow-api.viasocket.com` calls send `embedToken(userId)` as `authorization`. A port sends a `User-Agent` header of its own on every call: the catalog host refuses some libraries’ default one (Python’s `urllib` gets a 403 with `error code: 1010`). ```js // viasocket.js (or viasocket.mjs) import jwt from 'jsonwebtoken' const API = 'https://flow-api.viasocket.com' const RUN = 'https://flow.sokt.io' const SERVICES = '/embed/services' // the readable routes: an app by its slug, an action or trigger by its key const PLUGS = 'https://plug-service.viasocket.com' export const embedToken = (userId, { expiresIn } = {}) => // server calls: no option, the token never expires. One handed to a browser: { expiresIn: '1h' }, minted per page load jwt.sign( { org_id: process.env.VIASOCKET_ORG_ID, project_id: process.env.VIASOCKET_PROJECT_ID, unique_identifier: String(userId) }, process.env.VIASOCKET_EMBED_SECRET, { algorithm: 'HS256', ...(expiresIn ? { expiresIn } : {}) }) export async function apiCall(userId, method, path, body) { const response = await fetch(API + path, { method, headers: { 'Content-Type': 'application/json', authorization: embedToken(userId) }, // bare token, no Bearer body: body === undefined ? undefined : JSON.stringify(body) }) const text = await response.text() let payload = null try { payload = JSON.parse(text) } catch { payload = text } if (!response.ok || payload?.success === false) { const shown = path.replace(/\/(enable|revoke|updatestatus|updateflowembed|update-subscribed-event)\/[^/?]+/, '/$1/') // an auth_id or script_id never lands in error text or logs const error = new Error(payload?.message || `viaSocket ${shown}: ${response.status}`) Object.assign(error, { status: response.status, body: payload }) // the status and the API's whole answer throw error } return payload.data } async function postJson(url, body) { const shown = url.split('?')[0].replace(/\/func\/.*/, '/func/') // the script_id, and the auth_id in sampleEvent's query, never land in error text or logs const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) const text = await res.text() let parsed try { parsed = JSON.parse(text) } catch { throw new Error(`${shown}: ${res.status} ${text.slice(0, 200)}`) } // A failed run answers 400 with { success: false, errorMsg: { status, message, data } }: the app's own status and message if (!res.ok || parsed?.success === false) throw Object.assign(new Error(parsed?.errorMsg?.message || parsed?.message || `${shown}: ${res.status}`), { status: res.status, body: parsed }) return parsed } // ---- catalog export async function searchApps(text) { if (!text.trim()) return [] const res = await fetch(`${PLUGS}/plugins/search?prefix=${encodeURIComponent(text)}`) return (await res.json())?.data?.rows || [] } export async function listApps({ offset = 0, category } = {}) { const params = new URLSearchParams({ limit: '200', offset: String(offset), ...(category ? { category } : {}) }) const res = await fetch(`${PLUGS}/api/v1/plugins/all?${params}`) return (await res.json())?.data || [] } // ---- one user const listings = new Map() // slug → { at, body }, kept 10 minutes: keys and versions change rarely export async function listActions(userId, slug, { type } = {}) { const cached = listings.get(slug) const body = cached && Date.now() - cached.at < 600000 ? cached.body : await apiCall(userId, 'GET', `${SERVICES}/${encodeURIComponent(slug)}/actions`) // 404: no app has that slug listings.set(slug, { at: Date.now(), body }) return type ? { ...body, actions: body.actions.filter((action) => action.type === type) } : body } export const serviceIdFor = async (userId, slug) => (await listActions(userId, slug)).service_id // only the Connect popup and the prebuilt UI take it const catalogs = new Map() // slug → { at, body }, kept 10 minutes; an empty or failed answer is not kept export async function listEvents(userId, slug) { // every event with its input_schema, for a form const cached = catalogs.get(slug) if (cached && Date.now() - cached.at < 600000) return cached.body const res = await fetch(`${PLUGS}/api/v1/plugins/${encodeURIComponent(slug)}/actions`) // 404: no app has that slug const app = res.ok ? await res.json() : null const events = app?.service?.name && (app.actions?.length || app.triggers?.length) ? app : null if (events) catalogs.set(slug, { at: Date.now(), body: events }) return events } export const listConnections = (userId) => apiCall(userId, 'GET', '/embed/authentications') export const revokeConnection = (userId, authId) => apiCall(userId, 'DELETE', `/embed/authentications/revoke/${authId}`) export const listFlows = async (userId) => (await apiCall(userId, 'GET', `/projects/${process.env.VIASOCKET_PROJECT_ID}/integrations`))?.flows || [] export const setFlowStatus = (userId, scriptId, status) => apiCall(userId, 'PUT', `/embed/updatestatus/${scriptId}?status=${status}`) export const renameFlow = (userId, scriptId, { title, description, meta }) => apiCall(userId, 'PUT', `/projects/updateflowembed/${scriptId}`, { title, description, meta }) export async function findEnabledApp(userId, slug, authId) { // authId: only that connection's flow, for a user with two connections to one app const serviceId = await serviceIdFor(userId, slug) // active or paused: a paused one runs again after setFlowStatus(userId, id, 1), never enabled twice return (await listFlows(userId)).find((f) => f.service_id === serviceId && (!authId || f.auth_id === authId) && (f.status === 'active' || f.status === 'paused'))?.id || null } export async function enableApp(userId, slug, authId) { return (await apiCall(userId, 'POST', `${SERVICES}/${encodeURIComponent(slug)}/enable/${authId}`)).script_id } export async function listOptions(userId, slug, actionKey, { fieldKey, authId, existingFields = {}, version, search, paginate }) { const data = await apiCall(userId, 'POST', `${SERVICES}/${encodeURIComponent(slug)}/actions/${encodeURIComponent(actionKey)}/options`, { auth_id: authId, fieldKey, existingFields, ...(version ? { version } : {}), ...(search ? { search } : {}), ...(paginate != null ? { paginate } : {}) }) // paginate: send it back for the next page while hasMore; message: a note the field answered, for the user to see return { options: data?.options || [], paginate: data?.paginate ?? null, hasMore: Boolean(data?.has_more), message: data?.message } } export async function runAction(scriptId, actionKey, inputData, { version } = {}) { // no token: the script_id is the credential const payload = await postJson(`${RUN}/func/${scriptId}`, { action: actionKey, ...(version ? { version } : {}), inputData }) // No flow has that script_id: the runtime answers 200 { data: { success: true }, message: 'Flow Queued', flowHitId } and runs nothing if (payload?.message === 'Flow Queued' && typeof payload?.flowHitId === 'string' && !('success' in payload)) throw Object.assign(new Error('runAction: no flow has this script_id (unknown or deleted)'), { status: 200, body: payload }) // a failure already threw in postJson (message, status, body); some actions answer with their own body, others in an envelope const envelope = typeof payload?.success === 'boolean' && 'data' in payload return envelope ? payload.data : payload } export async function runCode(scriptId, code, inputData = {}, { action, version } = {}) { // your JavaScript with the user's connection: context.inputData, context.authData, axios, fetch return postJson(`${RUN}/func/${scriptId}`, { custom_code: code, inputData, ...(action ? { action } : {}), ...(version ? { version } : {}) }) } export async function sampleEvent(triggerId, authId, authType, inputData = {}) { // takes the trigger_id, not its version id; authType may be left out const params = new URLSearchParams({ action_id: triggerId, auth_id: authId, ...(authType ? { authType } : {}) }) const url = `${RUN}/func/scrijZpnr8zJ?${params}` const body = await postJson(url, { context: { inputData } }) if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error(`sampleEvent: ${JSON.stringify(body)}: pass the trigger_id and a live auth_id`) const { viasocket_help, ...event } = body // viasocket_help is a note, not a field return event } export async function subscribeEvent(userId, slug, triggerKey, authId, inputData, delivery, { version, meta = {} } = {}) { return (await apiCall(userId, 'POST', `${SERVICES}/${encodeURIComponent(slug)}/triggers/${encodeURIComponent(triggerKey)}/subscribe`, { auth_id: authId, inputData, ...delivery, ...(version ? { version } : {}), meta })).script_id } export const updateSubscription = (userId, scriptId, changes) => apiCall(userId, 'PUT', `/embed/update-subscribed-event/${scriptId}`, changes) ``` END OF PAGE