@emulators/slack 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/store.ts","../src/helpers.ts","../src/routes/auth.ts","../src/routes/chat.ts","../src/routes/conversations.ts","../src/routes/users.ts","../src/routes/reactions.ts","../src/routes/team.ts","../src/routes/oauth.ts","../../core/src/store.ts","../../core/src/server.ts","../../core/src/webhooks.ts","../../core/src/middleware/error-handler.ts","../../core/src/middleware/auth.ts","../../core/src/debug.ts","../../core/src/fonts.ts","../../core/src/middleware/pagination.ts","../../core/src/ui.ts","../../core/src/oauth-helpers.ts","../src/routes/webhooks.ts","../src/routes/inspector.ts","../src/index.ts"],"sourcesContent":["import { Store, type Collection } from \"@emulators/core\";\nimport type { SlackTeam, SlackUser, SlackChannel, SlackMessage, SlackBot, SlackOAuthApp, SlackIncomingWebhook } from \"./entities.js\";\n\nexport interface SlackStore {\n teams: Collection<SlackTeam>;\n users: Collection<SlackUser>;\n channels: Collection<SlackChannel>;\n messages: Collection<SlackMessage>;\n bots: Collection<SlackBot>;\n oauthApps: Collection<SlackOAuthApp>;\n incomingWebhooks: Collection<SlackIncomingWebhook>;\n}\n\nexport function getSlackStore(store: Store): SlackStore {\n return {\n teams: store.collection<SlackTeam>(\"slack.teams\", [\"team_id\"]),\n users: store.collection<SlackUser>(\"slack.users\", [\"user_id\", \"email\"]),\n channels: store.collection<SlackChannel>(\"slack.channels\", [\"channel_id\", \"name\"]),\n messages: store.collection<SlackMessage>(\"slack.messages\", [\"ts\", \"channel_id\"]),\n bots: store.collection<SlackBot>(\"slack.bots\", [\"bot_id\"]),\n oauthApps: store.collection<SlackOAuthApp>(\"slack.oauth_apps\", [\"client_id\"]),\n incomingWebhooks: store.collection<SlackIncomingWebhook>(\"slack.incoming_webhooks\", [\"token\"]),\n };\n}\n","import { randomBytes } from \"crypto\";\nimport type { Context } from \"hono\";\n\nlet tsCounter = 0;\n\nexport function generateSlackId(prefix: string): string {\n return prefix + randomBytes(5).toString(\"hex\").toUpperCase().slice(0, 9);\n}\n\nexport function generateTs(): string {\n const now = Math.floor(Date.now() / 1000);\n tsCounter++;\n return `${now}.${String(tsCounter).padStart(6, \"0\")}`;\n}\n\nexport function slackOk<T extends Record<string, unknown>>(c: Context, data: T) {\n return c.json({ ok: true, ...data });\n}\n\nexport function slackError(c: Context, error: string, status = 200) {\n return c.json({ ok: false, error }, status);\n}\n\nexport async function parseSlackBody(c: Context): Promise<Record<string, unknown>> {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const rawText = await c.req.text();\n\n if (contentType.includes(\"application/json\")) {\n try {\n return JSON.parse(rawText);\n } catch {\n return {};\n }\n }\n\n // Slack SDKs send application/x-www-form-urlencoded by default\n const params = new URLSearchParams(rawText);\n const result: Record<string, unknown> = {};\n for (const [key, value] of params) {\n result[key] = value;\n }\n return result;\n}\n\nexport function resetTsCounter(): void {\n tsCounter = 0;\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\nimport { slackOk, slackError } from \"../helpers.js\";\n\nexport function authRoutes(ctx: RouteContext): void {\n const { app, store } = ctx;\n const ss = () => getSlackStore(store);\n\n // auth.test - verify token, return user/team info\n app.post(\"/api/auth.test\", (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) {\n return slackError(c, \"not_authed\");\n }\n\n // Look up by user_id first, then fall back to name (for token-based auth\n // where the token login may be the username rather than the user_id)\n const user = ss().users.findOneBy(\"user_id\", authUser.login)\n ?? ss().users.all().find((u) => u.name === authUser.login);\n if (!user) {\n return slackError(c, \"invalid_auth\");\n }\n\n const team = ss().teams.all()[0];\n return slackOk(c, {\n url: `https://${team?.domain ?? \"emulate\"}.slack.com/`,\n team: team?.name ?? \"Emulate\",\n user: user.name,\n team_id: team?.team_id ?? \"T000000001\",\n user_id: user.user_id,\n bot_id: user.is_bot ? user.user_id : undefined,\n });\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\nimport { generateTs, slackOk, slackError, parseSlackBody } from \"../helpers.js\";\n\nexport function chatRoutes(ctx: RouteContext): void {\n const { app, store, webhooks } = ctx;\n const ss = () => getSlackStore(store);\n\n // chat.postMessage\n app.post(\"/api/chat.postMessage\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const text = typeof body.text === \"string\" ? body.text : \"\";\n const thread_ts = typeof body.thread_ts === \"string\" ? body.thread_ts : undefined;\n\n if (!channel) return slackError(c, \"channel_not_found\");\n\n const ch = ss().channels.findOneBy(\"channel_id\", channel)\n ?? ss().channels.findOneBy(\"name\", channel);\n if (!ch) return slackError(c, \"channel_not_found\");\n\n const ts = generateTs();\n const msg = ss().messages.insert({\n ts,\n channel_id: ch.channel_id,\n user: authUser.login,\n text,\n type: \"message\" as const,\n thread_ts,\n reply_count: 0,\n reply_users: [],\n reactions: [],\n });\n\n // Update parent thread reply count\n if (thread_ts) {\n const parent = ss().messages.all().find((m) => m.ts === thread_ts && m.channel_id === ch.channel_id);\n if (parent) {\n const replyUsers = parent.reply_users.includes(authUser.login)\n ? parent.reply_users\n : [...parent.reply_users, authUser.login];\n ss().messages.update(parent.id, {\n reply_count: parent.reply_count + 1,\n reply_users: replyUsers,\n });\n }\n }\n\n await webhooks.dispatch(\"message\", {\n type: \"event_callback\",\n event: {\n type: \"message\",\n channel: ch.channel_id,\n user: authUser.login,\n text,\n ts,\n thread_ts,\n },\n });\n\n return slackOk(c, {\n channel: ch.channel_id,\n ts,\n message: {\n text: msg.text,\n user: msg.user,\n type: msg.type,\n ts: msg.ts,\n thread_ts: msg.thread_ts,\n },\n });\n });\n\n // chat.update\n app.post(\"/api/chat.update\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const ts = typeof body.ts === \"string\" ? body.ts : \"\";\n const text = typeof body.text === \"string\" ? body.text : \"\";\n\n if (!channel || !ts) return slackError(c, \"message_not_found\");\n\n const msg = ss().messages.all().find((m) => m.ts === ts && m.channel_id === channel);\n if (!msg) return slackError(c, \"message_not_found\");\n\n ss().messages.update(msg.id, { text });\n\n return slackOk(c, {\n channel,\n ts,\n text,\n });\n });\n\n // chat.delete\n app.post(\"/api/chat.delete\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const ts = typeof body.ts === \"string\" ? body.ts : \"\";\n\n if (!channel || !ts) return slackError(c, \"message_not_found\");\n\n const msg = ss().messages.all().find((m) => m.ts === ts && m.channel_id === channel);\n if (!msg) return slackError(c, \"message_not_found\");\n\n ss().messages.delete(msg.id);\n\n return slackOk(c, { channel, ts });\n });\n\n // chat.meMessage\n app.post(\"/api/chat.meMessage\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const text = typeof body.text === \"string\" ? body.text : \"\";\n\n if (!channel) return slackError(c, \"channel_not_found\");\n\n const ch = ss().channels.findOneBy(\"channel_id\", channel)\n ?? ss().channels.findOneBy(\"name\", channel);\n if (!ch) return slackError(c, \"channel_not_found\");\n\n const ts = generateTs();\n ss().messages.insert({\n ts,\n channel_id: ch.channel_id,\n user: authUser.login,\n text,\n type: \"message\" as const,\n subtype: \"me_message\",\n reply_count: 0,\n reply_users: [],\n reactions: [],\n });\n\n return slackOk(c, { channel: ch.channel_id, ts });\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\nimport { generateSlackId, slackOk, slackError, parseSlackBody } from \"../helpers.js\";\n\nexport function conversationsRoutes(ctx: RouteContext): void {\n const { app, store } = ctx;\n const ss = () => getSlackStore(store);\n\n // conversations.list\n app.post(\"/api/conversations.list\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const limit = Math.min(Number(body.limit) || 100, 1000);\n const cursor = typeof body.cursor === \"string\" ? body.cursor : \"\";\n\n const allChannels = ss().channels.all().filter((ch) => !ch.is_archived);\n\n // Simple cursor pagination using channel id\n let startIndex = 0;\n if (cursor) {\n const idx = allChannels.findIndex((ch) => ch.channel_id === cursor);\n if (idx >= 0) startIndex = idx;\n }\n\n const page = allChannels.slice(startIndex, startIndex + limit);\n const nextCursor = startIndex + limit < allChannels.length\n ? allChannels[startIndex + limit].channel_id\n : \"\";\n\n return slackOk(c, {\n channels: page.map(formatChannel),\n response_metadata: { next_cursor: nextCursor },\n });\n });\n\n // conversations.info\n app.post(\"/api/conversations.info\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n\n const ch = ss().channels.findOneBy(\"channel_id\", channel);\n if (!ch) return slackError(c, \"channel_not_found\");\n\n return slackOk(c, { channel: formatChannel(ch) });\n });\n\n // conversations.create\n app.post(\"/api/conversations.create\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const name = typeof body.name === \"string\" ? body.name : \"\";\n const isPrivate = body.is_private === true || body.is_private === \"true\";\n\n if (!name) return slackError(c, \"invalid_name_specials\");\n\n // Check for duplicate name\n const existing = ss().channels.findOneBy(\"name\", name);\n if (existing) return slackError(c, \"name_taken\");\n\n const team = ss().teams.all()[0];\n const channelId = generateSlackId(\"C\");\n const now = Math.floor(Date.now() / 1000);\n\n const ch = ss().channels.insert({\n channel_id: channelId,\n team_id: team?.team_id ?? \"T000000001\",\n name,\n is_channel: !isPrivate,\n is_private: isPrivate,\n is_archived: false,\n topic: { value: \"\", creator: \"\", last_set: 0 },\n purpose: { value: \"\", creator: authUser.login, last_set: now },\n members: [authUser.login],\n creator: authUser.login,\n num_members: 1,\n });\n\n return slackOk(c, { channel: formatChannel(ch) });\n });\n\n // conversations.history\n app.post(\"/api/conversations.history\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const limit = Math.min(Number(body.limit) || 100, 1000);\n const cursor = typeof body.cursor === \"string\" ? body.cursor : \"\";\n\n if (!channel) return slackError(c, \"channel_not_found\");\n\n const ch = ss().channels.findOneBy(\"channel_id\", channel);\n if (!ch) return slackError(c, \"channel_not_found\");\n\n // Get top-level messages (no thread_ts or thread_ts === ts)\n const allMessages = ss().messages\n .findBy(\"channel_id\", channel)\n .filter((m) => !m.thread_ts || m.thread_ts === m.ts)\n .sort((a, b) => (b.ts > a.ts ? 1 : -1));\n\n let startIndex = 0;\n if (cursor) {\n const idx = allMessages.findIndex((m) => m.ts === cursor);\n if (idx >= 0) startIndex = idx;\n }\n\n const page = allMessages.slice(startIndex, startIndex + limit);\n const hasMore = startIndex + limit < allMessages.length;\n const nextCursor = hasMore ? allMessages[startIndex + limit].ts : \"\";\n\n return slackOk(c, {\n messages: page.map(formatMessage),\n has_more: hasMore,\n response_metadata: { next_cursor: nextCursor },\n });\n });\n\n // conversations.replies\n app.post(\"/api/conversations.replies\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const ts = typeof body.ts === \"string\" ? body.ts : \"\";\n\n if (!channel || !ts) return slackError(c, \"channel_not_found\");\n\n const allMessages = ss().messages\n .findBy(\"channel_id\", channel)\n .filter((m) => m.ts === ts || m.thread_ts === ts)\n .sort((a, b) => (a.ts > b.ts ? 1 : -1));\n\n return slackOk(c, {\n messages: allMessages.map(formatMessage),\n has_more: false,\n });\n });\n\n // conversations.join\n app.post(\"/api/conversations.join\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n\n const ch = ss().channels.findOneBy(\"channel_id\", channel);\n if (!ch) return slackError(c, \"channel_not_found\");\n\n if (!ch.members.includes(authUser.login)) {\n ss().channels.update(ch.id, {\n members: [...ch.members, authUser.login],\n num_members: ch.num_members + 1,\n });\n }\n\n const updated = ss().channels.findOneBy(\"channel_id\", channel)!;\n return slackOk(c, { channel: formatChannel(updated) });\n });\n\n // conversations.leave\n app.post(\"/api/conversations.leave\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n\n const ch = ss().channels.findOneBy(\"channel_id\", channel);\n if (!ch) return slackError(c, \"channel_not_found\");\n\n if (ch.members.includes(authUser.login)) {\n ss().channels.update(ch.id, {\n members: ch.members.filter((m) => m !== authUser.login),\n num_members: Math.max(0, ch.num_members - 1),\n });\n }\n\n return slackOk(c, {});\n });\n\n // conversations.members\n app.post(\"/api/conversations.members\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n\n const ch = ss().channels.findOneBy(\"channel_id\", channel);\n if (!ch) return slackError(c, \"channel_not_found\");\n\n return slackOk(c, {\n members: ch.members,\n response_metadata: { next_cursor: \"\" },\n });\n });\n}\n\nfunction formatChannel(ch: {\n channel_id: string;\n name: string;\n is_channel: boolean;\n is_private: boolean;\n is_archived: boolean;\n topic: { value: string; creator: string; last_set: number };\n purpose: { value: string; creator: string; last_set: number };\n creator: string;\n num_members: number;\n created_at: string;\n}) {\n return {\n id: ch.channel_id,\n name: ch.name,\n is_channel: ch.is_channel,\n is_private: ch.is_private,\n is_archived: ch.is_archived,\n topic: ch.topic,\n purpose: ch.purpose,\n creator: ch.creator,\n num_members: ch.num_members,\n created: Math.floor(new Date(ch.created_at).getTime() / 1000),\n };\n}\n\nfunction formatMessage(msg: {\n ts: string;\n user: string;\n text: string;\n type: string;\n subtype?: string;\n thread_ts?: string;\n reply_count: number;\n reply_users: string[];\n reactions: Array<{ name: string; users: string[]; count: number }>;\n}) {\n return {\n type: msg.type,\n user: msg.user,\n text: msg.text,\n ts: msg.ts,\n ...(msg.subtype ? { subtype: msg.subtype } : {}),\n ...(msg.thread_ts ? { thread_ts: msg.thread_ts } : {}),\n ...(msg.reply_count > 0 ? { reply_count: msg.reply_count, reply_users: msg.reply_users } : {}),\n ...(msg.reactions.length > 0 ? { reactions: msg.reactions } : {}),\n };\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\nimport { slackOk, slackError, parseSlackBody } from \"../helpers.js\";\nimport type { SlackUser } from \"../entities.js\";\n\nexport function usersRoutes(ctx: RouteContext): void {\n const { app, store } = ctx;\n const ss = () => getSlackStore(store);\n\n // users.list\n app.post(\"/api/users.list\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const limit = Math.min(Number(body.limit) || 100, 1000);\n const cursor = typeof body.cursor === \"string\" ? body.cursor : \"\";\n\n const allUsers = ss().users.all().filter((u) => !u.deleted);\n\n let startIndex = 0;\n if (cursor) {\n const idx = allUsers.findIndex((u) => u.user_id === cursor);\n if (idx >= 0) startIndex = idx;\n }\n\n const page = allUsers.slice(startIndex, startIndex + limit);\n const nextCursor = startIndex + limit < allUsers.length\n ? allUsers[startIndex + limit].user_id\n : \"\";\n\n return slackOk(c, {\n members: page.map(formatUser),\n response_metadata: { next_cursor: nextCursor },\n });\n });\n\n // users.info\n app.post(\"/api/users.info\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const userId = typeof body.user === \"string\" ? body.user : \"\";\n\n const user = ss().users.findOneBy(\"user_id\", userId);\n if (!user) return slackError(c, \"user_not_found\");\n\n return slackOk(c, { user: formatUser(user) });\n });\n\n // users.lookupByEmail\n app.post(\"/api/users.lookupByEmail\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const email = typeof body.email === \"string\" ? body.email : \"\";\n\n if (!email) return slackError(c, \"users_not_found\");\n\n const user = ss().users.findOneBy(\"email\", email);\n if (!user) return slackError(c, \"users_not_found\");\n\n return slackOk(c, { user: formatUser(user) });\n });\n}\n\nfunction formatUser(u: SlackUser) {\n return {\n id: u.user_id,\n team_id: u.team_id,\n name: u.name,\n real_name: u.real_name,\n is_admin: u.is_admin,\n is_bot: u.is_bot,\n deleted: u.deleted,\n profile: u.profile,\n };\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\nimport { slackOk, slackError, parseSlackBody } from \"../helpers.js\";\n\nexport function reactionsRoutes(ctx: RouteContext): void {\n const { app, store, webhooks } = ctx;\n const ss = () => getSlackStore(store);\n\n // reactions.add\n app.post(\"/api/reactions.add\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const timestamp = typeof body.timestamp === \"string\" ? body.timestamp : \"\";\n const name = typeof body.name === \"string\" ? body.name : \"\";\n\n if (!name) return slackError(c, \"invalid_name\");\n\n const msg = ss().messages.all().find((m) => m.ts === timestamp && m.channel_id === channel);\n if (!msg) return slackError(c, \"message_not_found\");\n\n const reactions = [...msg.reactions];\n const existing = reactions.find((r) => r.name === name);\n if (existing) {\n if (existing.users.includes(authUser.login)) {\n return slackError(c, \"already_reacted\");\n }\n existing.users.push(authUser.login);\n existing.count++;\n } else {\n reactions.push({ name, users: [authUser.login], count: 1 });\n }\n\n ss().messages.update(msg.id, { reactions });\n\n await webhooks.dispatch(\"reaction_added\", {\n type: \"event_callback\",\n event: {\n type: \"reaction_added\",\n user: authUser.login,\n reaction: name,\n item: { type: \"message\", channel, ts: timestamp },\n },\n });\n\n return slackOk(c, {});\n });\n\n // reactions.remove\n app.post(\"/api/reactions.remove\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const timestamp = typeof body.timestamp === \"string\" ? body.timestamp : \"\";\n const name = typeof body.name === \"string\" ? body.name : \"\";\n\n if (!name) return slackError(c, \"invalid_name\");\n\n const msg = ss().messages.all().find((m) => m.ts === timestamp && m.channel_id === channel);\n if (!msg) return slackError(c, \"message_not_found\");\n\n const reactions = [...msg.reactions];\n const existing = reactions.find((r) => r.name === name);\n if (!existing || !existing.users.includes(authUser.login)) {\n return slackError(c, \"no_reaction\");\n }\n\n existing.users = existing.users.filter((u) => u !== authUser.login);\n existing.count--;\n\n const filtered = reactions.filter((r) => r.count > 0);\n ss().messages.update(msg.id, { reactions: filtered });\n\n await webhooks.dispatch(\"reaction_removed\", {\n type: \"event_callback\",\n event: {\n type: \"reaction_removed\",\n user: authUser.login,\n reaction: name,\n item: { type: \"message\", channel, ts: timestamp },\n },\n });\n\n return slackOk(c, {});\n });\n\n // reactions.get\n app.post(\"/api/reactions.get\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const channel = typeof body.channel === \"string\" ? body.channel : \"\";\n const timestamp = typeof body.timestamp === \"string\" ? body.timestamp : \"\";\n\n const msg = ss().messages.all().find((m) => m.ts === timestamp && m.channel_id === channel);\n if (!msg) return slackError(c, \"message_not_found\");\n\n return slackOk(c, {\n type: \"message\",\n message: {\n type: msg.type,\n text: msg.text,\n ts: msg.ts,\n reactions: msg.reactions,\n },\n });\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\nimport { slackOk, slackError, parseSlackBody } from \"../helpers.js\";\n\nexport function teamRoutes(ctx: RouteContext): void {\n const { app, store } = ctx;\n const ss = () => getSlackStore(store);\n\n // team.info\n app.post(\"/api/team.info\", (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const team = ss().teams.all()[0];\n if (!team) return slackError(c, \"team_not_found\");\n\n return slackOk(c, {\n team: {\n id: team.team_id,\n name: team.name,\n domain: team.domain,\n },\n });\n });\n\n // bots.info\n app.post(\"/api/bots.info\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) return slackError(c, \"not_authed\");\n\n const body = await parseSlackBody(c);\n const botId = typeof body.bot === \"string\" ? body.bot : \"\";\n\n const bot = ss().bots.findOneBy(\"bot_id\", botId);\n if (!bot) return slackError(c, \"bot_not_found\");\n\n return slackOk(c, {\n bot: {\n id: bot.bot_id,\n name: bot.name,\n deleted: bot.deleted,\n icons: bot.icons,\n },\n });\n });\n}\n","import { randomBytes } from \"crypto\";\nimport type { RouteContext } from \"@emulators/core\";\nimport {\n escapeHtml,\n escapeAttr,\n renderCardPage,\n renderErrorPage,\n renderUserButton,\n matchesRedirectUri,\n constantTimeSecretEqual,\n bodyStr,\n debug,\n} from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\n\ntype PendingCode = {\n userId: string;\n scope: string;\n redirectUri: string;\n clientId: string;\n created_at: number;\n};\n\nconst PENDING_CODE_TTL_MS = 10 * 60 * 1000;\nconst SERVICE_LABEL = \"Slack\";\n\nfunction getPendingCodes(store: import(\"@emulators/core\").Store): Map<string, PendingCode> {\n let map = store.getData<Map<string, PendingCode>>(\"slack.oauth.pendingCodes\");\n if (!map) {\n map = new Map();\n store.setData(\"slack.oauth.pendingCodes\", map);\n }\n return map;\n}\n\nfunction isPendingCodeExpired(p: PendingCode): boolean {\n return Date.now() - p.created_at > PENDING_CODE_TTL_MS;\n}\n\nexport function oauthRoutes({ app, store, baseUrl, tokenMap }: RouteContext): void {\n const ss = () => getSlackStore(store);\n\n // Authorization page - renders the consent UI\n app.get(\"/oauth/v2/authorize\", (c) => {\n const client_id = c.req.query(\"client_id\") ?? \"\";\n const redirect_uri = c.req.query(\"redirect_uri\") ?? \"\";\n const scope = c.req.query(\"scope\") ?? \"\";\n const state = c.req.query(\"state\") ?? \"\";\n\n const appsConfigured = ss().oauthApps.all().length > 0;\n let appName = \"\";\n if (appsConfigured) {\n const oauthApp = ss().oauthApps.findOneBy(\"client_id\", client_id);\n if (!oauthApp) {\n return c.html(\n renderErrorPage(\"Application not found\", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),\n 400\n );\n }\n if (redirect_uri && !matchesRedirectUri(redirect_uri, oauthApp.redirect_uris)) {\n return c.html(\n renderErrorPage(\"Redirect URI mismatch\", \"The redirect_uri is not registered for this application.\", SERVICE_LABEL),\n 400\n );\n }\n appName = oauthApp.name;\n }\n\n const subtitleText = appName\n ? `Authorize <strong>${escapeHtml(appName)}</strong> to access your Slack workspace.`\n : \"Choose a user to authorize.\";\n\n const users = ss().users.all().filter((u) => !u.deleted && !u.is_bot);\n const userButtons = users\n .map((user) => {\n return renderUserButton({\n letter: (user.name[0] ?? \"?\").toUpperCase(),\n login: user.name,\n name: user.real_name,\n email: user.email,\n formAction: \"/oauth/v2/authorize/callback\",\n hiddenFields: {\n user_id: user.user_id,\n redirect_uri,\n scope,\n state,\n client_id,\n },\n });\n })\n .join(\"\\n\");\n\n const body = users.length === 0\n ? '<p class=\"empty\">No users in the emulator store.</p>'\n : userButtons;\n\n return c.html(renderCardPage(\"Sign in to Slack\", subtitleText, body, SERVICE_LABEL));\n });\n\n // Authorization callback\n app.post(\"/oauth/v2/authorize/callback\", async (c) => {\n const body = await c.req.parseBody();\n const userId = bodyStr(body.user_id);\n const redirect_uri = bodyStr(body.redirect_uri);\n const scope = bodyStr(body.scope);\n const state = bodyStr(body.state);\n const client_id = bodyStr(body.client_id);\n\n const code = randomBytes(20).toString(\"hex\");\n\n getPendingCodes(store).set(code, {\n userId,\n scope,\n redirectUri: redirect_uri,\n clientId: client_id,\n created_at: Date.now(),\n });\n\n debug(\"slack.oauth\", `[Slack callback] code=${code.slice(0, 8)}... user=${userId}`);\n\n const url = new URL(redirect_uri);\n url.searchParams.set(\"code\", code);\n if (state) url.searchParams.set(\"state\", state);\n\n return c.redirect(url.toString(), 302);\n });\n\n // oauth.v2.access - token exchange\n app.post(\"/api/oauth.v2.access\", async (c) => {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const rawText = await c.req.text();\n\n let body: Record<string, unknown>;\n if (contentType.includes(\"application/json\")) {\n try { body = JSON.parse(rawText); } catch { body = {}; }\n } else {\n body = Object.fromEntries(new URLSearchParams(rawText));\n }\n\n const code = typeof body.code === \"string\" ? body.code : \"\";\n const client_id = typeof body.client_id === \"string\" ? body.client_id : \"\";\n const client_secret = typeof body.client_secret === \"string\" ? body.client_secret : \"\";\n\n const appsConfigured = ss().oauthApps.all().length > 0;\n if (appsConfigured) {\n const oauthApp = ss().oauthApps.findOneBy(\"client_id\", client_id);\n if (!oauthApp) {\n return c.json({ ok: false, error: \"invalid_client_id\" });\n }\n if (!constantTimeSecretEqual(client_secret, oauthApp.client_secret)) {\n return c.json({ ok: false, error: \"invalid_client_id\" });\n }\n }\n\n const pendingMap = getPendingCodes(store);\n const pending = pendingMap.get(code);\n if (!pending) {\n return c.json({ ok: false, error: \"invalid_code\" });\n }\n if (isPendingCodeExpired(pending)) {\n pendingMap.delete(code);\n return c.json({ ok: false, error: \"invalid_code\" });\n }\n\n pendingMap.delete(code);\n\n const user = ss().users.findOneBy(\"user_id\", pending.userId);\n if (!user) {\n return c.json({ ok: false, error: \"invalid_code\" });\n }\n\n const accessToken = \"xoxb-\" + randomBytes(20).toString(\"base64url\");\n const team = ss().teams.all()[0];\n\n if (tokenMap) {\n const scopes = pending.scope ? pending.scope.split(/[,\\s]+/).filter(Boolean) : [];\n tokenMap.set(accessToken, { login: user.user_id, id: user.id, scopes });\n }\n\n debug(\"slack.oauth\", `[Slack token] issued token for ${user.name}`);\n\n return c.json({\n ok: true,\n access_token: accessToken,\n token_type: \"bot\",\n scope: pending.scope || \"chat:write,channels:read\",\n bot_user_id: user.user_id,\n app_id: client_id,\n team: {\n id: team?.team_id ?? \"T000000001\",\n name: team?.name ?? \"Emulate\",\n },\n authed_user: {\n id: user.user_id,\n },\n });\n });\n}\n","export interface Entity {\n id: number;\n created_at: string;\n updated_at: string;\n}\n\nexport type InsertInput<T extends Entity> = Omit<T, \"id\" | \"created_at\" | \"updated_at\"> & { id?: number };\n\nexport type FilterFn<T> = (item: T) => boolean;\nexport type SortFn<T> = (a: T, b: T) => number;\n\nexport interface QueryOptions<T> {\n filter?: FilterFn<T>;\n sort?: SortFn<T>;\n page?: number;\n per_page?: number;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n total_count: number;\n page: number;\n per_page: number;\n has_next: boolean;\n has_prev: boolean;\n}\n\nexport class Collection<T extends Entity> {\n private items = new Map<number, T>();\n private indexes = new Map<string, Map<string | number, Set<number>>>();\n private autoId = 1;\n readonly fieldNames: string[];\n\n constructor(private indexFields: (keyof T)[] = []) {\n this.fieldNames = indexFields.map(String).sort();\n for (const field of indexFields) {\n this.indexes.set(String(field), new Map());\n }\n }\n\n private addToIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n if (!indexMap.has(key)) {\n indexMap.set(key, new Set());\n }\n indexMap.get(key)!.add(item.id);\n }\n }\n\n private removeFromIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n indexMap.get(key)?.delete(item.id);\n }\n }\n\n insert(data: InsertInput<T>): T {\n const now = new Date().toISOString();\n const explicitId = data.id != null && data.id > 0 ? data.id : undefined;\n const id = explicitId ?? this.autoId++;\n if (id >= this.autoId) {\n this.autoId = id + 1;\n }\n const item = {\n ...data,\n id,\n created_at: now,\n updated_at: now,\n } as unknown as T;\n this.items.set(id, item);\n this.addToIndex(item);\n return item;\n }\n\n get(id: number): T | undefined {\n return this.items.get(id);\n }\n\n findBy(field: keyof T, value: T[keyof T] | string | number): T[] {\n if (this.indexes.has(String(field))) {\n const ids = this.indexes.get(String(field))!.get(String(value));\n if (!ids) return [];\n return Array.from(ids).map((id) => this.items.get(id)!).filter(Boolean);\n }\n return this.all().filter((item) => item[field] === value);\n }\n\n findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined {\n return this.findBy(field, value)[0];\n }\n\n update(id: number, data: Partial<T>): T | undefined {\n const existing = this.items.get(id);\n if (!existing) return undefined;\n this.removeFromIndex(existing);\n const updated = {\n ...existing,\n ...data,\n id,\n updated_at: new Date().toISOString(),\n } as T;\n this.items.set(id, updated);\n this.addToIndex(updated);\n return updated;\n }\n\n delete(id: number): boolean {\n const existing = this.items.get(id);\n if (!existing) return false;\n this.removeFromIndex(existing);\n return this.items.delete(id);\n }\n\n all(): T[] {\n return Array.from(this.items.values());\n }\n\n query(options: QueryOptions<T> = {}): PaginatedResult<T> {\n let results = this.all();\n\n if (options.filter) {\n results = results.filter(options.filter);\n }\n\n const total_count = results.length;\n\n if (options.sort) {\n results.sort(options.sort);\n }\n\n const page = options.page ?? 1;\n const per_page = Math.min(options.per_page ?? 30, 100);\n const start = (page - 1) * per_page;\n const paged = results.slice(start, start + per_page);\n\n return {\n items: paged,\n total_count,\n page,\n per_page,\n has_next: start + per_page < total_count,\n has_prev: page > 1,\n };\n }\n\n count(filter?: FilterFn<T>): number {\n if (!filter) return this.items.size;\n return this.all().filter(filter).length;\n }\n\n clear(): void {\n this.items.clear();\n for (const indexMap of this.indexes.values()) {\n indexMap.clear();\n }\n this.autoId = 1;\n }\n}\n\nexport class Store {\n private collections = new Map<string, Collection<any>>();\n private _data = new Map<string, unknown>();\n\n collection<T extends Entity>(name: string, indexFields: (keyof T)[] = []): Collection<T> {\n const existing = this.collections.get(name);\n if (existing) {\n if (indexFields.length > 0) {\n const requested = indexFields.map(String).sort();\n if (existing.fieldNames.length !== requested.length || existing.fieldNames.some((f, i) => f !== requested[i])) {\n throw new Error(\n `Collection \"${name}\" already exists with indexes [${existing.fieldNames}] but was requested with [${requested}]`\n );\n }\n }\n return existing as Collection<T>;\n }\n const col = new Collection<T>(indexFields);\n this.collections.set(name, col);\n return col;\n }\n\n getData<V>(key: string): V | undefined {\n return this._data.get(key) as V | undefined;\n }\n\n setData<V>(key: string, value: V): void {\n this._data.set(key, value);\n }\n\n reset(): void {\n for (const collection of this.collections.values()) {\n collection.clear();\n }\n this._data.clear();\n }\n}\n","import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport { authMiddleware, type AuthFallback, type TokenMap, type AppKeyResolver, type AppEnv } from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.js\";\n\nexport interface ServerOptions {\n port?: number;\n baseUrl?: string;\n docsUrl?: string;\n tokens?: Record<string, { login: string; id: number; scopes?: string[] }>;\n appKeyResolver?: AppKeyResolver;\n fallbackUser?: AuthFallback;\n}\n\nexport function createServer(plugin: ServicePlugin, options: ServerOptions = {}) {\n const port = options.port ?? 4000;\n const baseUrl = options.baseUrl ?? `http://localhost:${port}`;\n\n const app = new Hono<AppEnv>();\n const store = new Store();\n const webhooks = new WebhookDispatcher();\n\n const tokenMap: TokenMap = new Map();\n if (options.tokens) {\n for (const [token, user] of Object.entries(options.tokens)) {\n tokenMap.set(token, {\n login: user.login,\n id: user.id,\n scopes: user.scopes ?? [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n });\n }\n }\n\n const docsUrl = options.docsUrl ?? `https://emulate.dev/${plugin.name}`;\n\n registerFontRoutes(app);\n\n app.onError(createApiErrorHandler(docsUrl));\n app.use(\"*\", cors());\n app.use(\"*\", createErrorHandler(docsUrl));\n app.use(\"*\", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser));\n\n const rateLimitCounters = new Map<string, { remaining: number; resetAt: number }>();\n let lastPruneAt = Math.floor(Date.now() / 1000);\n\n app.use(\"*\", async (c, next) => {\n const token = c.get(\"authToken\") ?? \"__anonymous__\";\n const now = Math.floor(Date.now() / 1000);\n\n if (now - lastPruneAt > 3600) {\n for (const [key, val] of rateLimitCounters) {\n if (val.resetAt <= now) rateLimitCounters.delete(key);\n }\n lastPruneAt = now;\n }\n\n let counter = rateLimitCounters.get(token);\n if (!counter || counter.resetAt <= now) {\n counter = { remaining: 5000, resetAt: now + 3600 };\n rateLimitCounters.set(token, counter);\n }\n\n counter.remaining = Math.max(0, counter.remaining - 1);\n\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", String(counter.remaining));\n c.header(\"X-RateLimit-Reset\", String(counter.resetAt));\n c.header(\"X-RateLimit-Resource\", \"core\");\n\n if (counter.remaining === 0) {\n return c.json(\n {\n message: \"API rate limit exceeded\",\n documentation_url: docsUrl,\n },\n 403\n );\n }\n\n await next();\n });\n\n plugin.register(app, store, webhooks, baseUrl, tokenMap);\n\n app.notFound((c) =>\n c.json(\n {\n message: \"Not Found\",\n documentation_url: docsUrl,\n },\n 404\n )\n );\n\n return { app, store, webhooks, port, baseUrl, tokenMap };\n}\n","import { createHmac } from \"crypto\";\n\nexport interface WebhookSubscription {\n id: number;\n url: string;\n events: string[];\n active: boolean;\n secret?: string;\n owner: string;\n repo?: string;\n}\n\nexport interface WebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n payload: unknown;\n status_code: number | null;\n delivered_at: string;\n duration: number | null;\n success: boolean;\n}\n\nconst MAX_DELIVERIES = 1000;\n\nexport class WebhookDispatcher {\n private subscriptions: WebhookSubscription[] = [];\n private deliveries: WebhookDelivery[] = [];\n private subscriptionIdCounter = 1;\n private deliveryIdCounter = 1;\n\n register(sub: Omit<WebhookSubscription, \"id\"> & { id?: number }): WebhookSubscription {\n const { id: explicitId, ...rest } = sub;\n const id = explicitId !== undefined ? explicitId : this.subscriptionIdCounter++;\n if (id >= this.subscriptionIdCounter) {\n this.subscriptionIdCounter = id + 1;\n }\n const subscription: WebhookSubscription = { ...rest, id };\n this.subscriptions.push(subscription);\n return subscription;\n }\n\n unregister(id: number): boolean {\n const idx = this.subscriptions.findIndex((s) => s.id === id);\n if (idx === -1) return false;\n this.subscriptions.splice(idx, 1);\n return true;\n }\n\n getSubscription(id: number): WebhookSubscription | undefined {\n return this.subscriptions.find((s) => s.id === id);\n }\n\n getSubscriptions(owner?: string, repo?: string): WebhookSubscription[] {\n return this.subscriptions.filter((s) => {\n if (owner && s.owner !== owner) return false;\n if (repo !== undefined && s.repo !== repo) return false;\n return true;\n });\n }\n\n updateSubscription(\n id: number,\n data: Partial<Pick<WebhookSubscription, \"url\" | \"events\" | \"active\" | \"secret\">>\n ): WebhookSubscription | undefined {\n const sub = this.subscriptions.find((s) => s.id === id);\n if (!sub) return undefined;\n Object.assign(sub, data);\n return sub;\n }\n\n async dispatch(event: string, action: string | undefined, payload: unknown, owner: string, repo?: string): Promise<void> {\n const matchingSubs = this.subscriptions.filter((s) => {\n if (!s.active) return false;\n if (s.owner !== owner) return false;\n if (repo !== undefined) {\n if (s.repo !== repo) return false;\n } else if (s.repo !== undefined) {\n return false;\n }\n return (\n event === \"ping\" ||\n s.events.includes(\"*\") ||\n s.events.includes(event)\n );\n });\n\n for (const sub of matchingSubs) {\n const delivery: WebhookDelivery = {\n id: this.deliveryIdCounter++,\n hook_id: sub.id,\n event,\n action,\n payload,\n status_code: null,\n delivered_at: new Date().toISOString(),\n duration: null,\n success: false,\n };\n\n const body = JSON.stringify(payload);\n\n const signatureHeaders: Record<string, string> = {};\n if (sub.secret) {\n const hmac = createHmac(\"sha256\", sub.secret).update(body).digest(\"hex\");\n signatureHeaders[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n const start = Date.now();\n const response = await fetch(sub.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(delivery.id),\n ...signatureHeaders,\n },\n body,\n signal: AbortSignal.timeout(10000),\n });\n delivery.duration = Date.now() - start;\n delivery.status_code = response.status;\n delivery.success = response.ok;\n } catch {\n delivery.duration = 0;\n delivery.success = false;\n }\n\n this.deliveries.push(delivery);\n if (this.deliveries.length > MAX_DELIVERIES) {\n this.deliveries.splice(0, this.deliveries.length - MAX_DELIVERIES);\n }\n }\n }\n\n getDeliveries(hookId?: number): WebhookDelivery[] {\n if (hookId !== undefined) {\n return this.deliveries.filter((d) => d.hook_id === hookId);\n }\n return [...this.deliveries];\n }\n\n clear(): void {\n this.subscriptions.length = 0;\n this.deliveries.length = 0;\n this.subscriptionIdCounter = 1;\n this.deliveryIdCounter = 1;\n }\n}\n","import type { Context, ErrorHandler, MiddlewareHandler } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\n\nconst DEFAULT_DOCS_URL = \"https://emulate.dev\";\n\nfunction getDocsUrl(c: Context): string {\n return (c.get(\"docsUrl\") as string | undefined) ?? DEFAULT_DOCS_URL;\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const s = (err as { status: unknown }).status;\n if (typeof s === \"number\" && Number.isFinite(s)) return s;\n }\n return 500;\n}\n\n/**\n * Use with `app.onError(...)`. Hono routes handler throws to the app error handler, not to outer middleware try/catch.\n */\nexport function createApiErrorHandler(documentationUrl?: string): ErrorHandler {\n return (err, c) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n const status = errorStatus(err);\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return c.json(\n {\n message,\n documentation_url: getDocsUrl(c),\n },\n status as ContentfulStatusCode\n );\n };\n}\n\n/** Sets `docsUrl` on the context for successful responses; register `createApiErrorHandler` for thrown `ApiError`s. */\nexport function createErrorHandler(documentationUrl?: string): MiddlewareHandler {\n return async (c, next) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n await next();\n };\n}\n\nexport const errorHandler: MiddlewareHandler = createErrorHandler();\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public errors?: Array<{ resource: string; field: string; code: string }>\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport function notFound(resource?: string): ApiError {\n return new ApiError(404, resource ? `${resource} not found` : \"Not Found\");\n}\n\nexport function validationError(message: string, errors?: ApiError[\"errors\"]): ApiError {\n return new ApiError(422, message, errors);\n}\n\nexport function unauthorized(): ApiError {\n return new ApiError(401, \"Requires authentication\");\n}\n\nexport function forbidden(): ApiError {\n return new ApiError(403, \"Forbidden\");\n}\n\nexport async function parseJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n throw new ApiError(400, \"Problems parsing JSON\");\n }\n}\n","import type { Context, Next } from \"hono\";\nimport { jwtVerify, importPKCS8 } from \"jose\";\nimport { debug } from \"../debug.js\";\n\nexport interface AuthUser {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport interface AuthApp {\n appId: number;\n slug: string;\n name: string;\n}\n\nexport interface AuthInstallation {\n installationId: number;\n appId: number;\n permissions: Record<string, string>;\n repositoryIds: number[];\n repositorySelection: \"all\" | \"selected\";\n}\n\nexport type TokenMap = Map<string, AuthUser>;\n\nexport type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\n };\n};\n\nexport interface AppKeyResolver {\n (appId: number): { privateKey: string; slug: string; name: string } | null;\n}\n\nexport interface AuthFallback {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) {\n return async (c: Context, next: Next) => {\n const authHeader = c.req.header(\"Authorization\");\n if (authHeader) {\n const token = authHeader.replace(/^(Bearer|token)\\s+/i, \"\").trim();\n\n if (token.startsWith(\"eyJ\") && appKeyResolver) {\n try {\n const [, payloadB64] = token.split(\".\");\n const payload = JSON.parse(\n Buffer.from(payloadB64, \"base64url\").toString()\n );\n const appId = typeof payload.iss === \"string\" ? parseInt(payload.iss, 10) : payload.iss;\n\n if (typeof appId === \"number\" && !isNaN(appId)) {\n const appInfo = appKeyResolver(appId);\n if (appInfo) {\n const key = await importPKCS8(appInfo.privateKey, \"RS256\");\n await jwtVerify(token, key, { algorithms: [\"RS256\"] });\n c.set(\"authApp\", {\n appId,\n slug: appInfo.slug,\n name: appInfo.name,\n } satisfies AuthApp);\n }\n }\n } catch {\n // JWT verification failed\n }\n } else {\n let user = tokens.get(token);\n if (!user && fallbackUser && token.length > 0) {\n debug(\"auth\", \"fallback user for unknown token\", { login: fallbackUser.login, id: fallbackUser.id });\n user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes };\n }\n if (user) {\n c.set(\"authUser\", user);\n c.set(\"authToken\", token);\n c.set(\"authScopes\", user.scopes);\n }\n }\n }\n await next();\n };\n}\n\nexport function requireAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authUser\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"Requires authentication\",\n documentation_url: docsUrl,\n },\n 401\n );\n }\n await next();\n };\n}\n\nexport function requireAppAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authApp\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: docsUrl,\n },\n 401\n );\n }\n await next();\n };\n}\n","const isDebug = typeof process !== \"undefined\" && (process.env.DEBUG === \"1\" || process.env.DEBUG === \"true\" || process.env.EMULATE_DEBUG === \"1\");\n\nexport function debug(label: string, ...args: unknown[]): void {\n if (isDebug) {\n console.log(`[${label}]`, ...args);\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\nimport type { Hono } from \"hono\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nconst FONTS: Record<string, Buffer> = {\n \"geist-sans.woff2\": readFileSync(join(__dirname, \"fonts\", \"geist-sans.woff2\")),\n \"GeistPixel-Square.woff2\": readFileSync(join(__dirname, \"fonts\", \"GeistPixel-Square.woff2\")),\n};\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n const buf = FONTS[name];\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"font/woff2\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n });\n });\n}\n","import type { Context } from \"hono\";\n\nexport interface PaginationParams {\n page: number;\n per_page: number;\n}\n\nexport function parsePagination(c: Context): PaginationParams {\n const page = Math.max(1, parseInt(c.req.query(\"page\") ?? \"1\", 10) || 1);\n const per_page = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n return { page, per_page };\n}\n\nexport function setLinkHeader(\n c: Context,\n totalCount: number,\n page: number,\n perPage: number\n): void {\n const lastPage = Math.max(1, Math.ceil(totalCount / perPage));\n const baseUrl = new URL(c.req.url);\n const links: string[] = [];\n\n const makeLink = (p: number, rel: string) => {\n baseUrl.searchParams.set(\"page\", String(p));\n baseUrl.searchParams.set(\"per_page\", String(perPage));\n return `<${baseUrl.toString()}>; rel=\"${rel}\"`;\n };\n\n if (page < lastPage) {\n links.push(makeLink(page + 1, \"next\"));\n links.push(makeLink(lastPage, \"last\"));\n }\n if (page > 1) {\n links.push(makeLink(1, \"first\"));\n links.push(makeLink(page - 1, \"prev\"));\n }\n\n if (links.length > 0) {\n c.header(\"Link\", links.join(\", \"));\n }\n}\n","export function escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"&#39;\");\n}\n\nconst CSS = `\n@font-face{\n font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;\n src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');\n}\n@font-face{\n font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;\n src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');\n}\n*{box-sizing:border-box;margin:0;padding:0}\nbody{\n font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;\n background:#000;color:#33ff00;min-height:100vh;\n -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;\n}\n.emu-bar{\n border-bottom:1px solid #0a3300;padding:10px 20px;\n display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;\n}\n.emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}\n.emu-bar-links{margin-left:auto;display:flex;gap:16px;}\n.emu-bar-links a{\n color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;\n}\n.emu-bar-links a:hover{color:#33ff00;}\n.emu-bar-links a .full{display:inline;}\n.emu-bar-links a .short{display:none;}\n@media(max-width:600px){\n .emu-bar-links a .full{display:none;}\n .emu-bar-links a .short{display:inline;}\n}\n\n.content{\n display:flex;align-items:center;justify-content:center;\n min-height:calc(100vh - 42px);padding:24px 16px;\n}\n.content-inner{width:100%;max-width:420px;}\n.card-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;\n}\n.card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}\n.powered-by{\n position:fixed;bottom:0;left:0;right:0;\n text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;\n font-family:'Geist Pixel',monospace;\n}\n.powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.powered-by a:hover{color:#33ff00;}\n\n.error-title{\n font-family:'Geist Pixel',monospace;\n color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;\n}\n.error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}\n.error-card{text-align:center;}\n\n.user-form{margin-bottom:8px;}\n.user-form:last-of-type{margin-bottom:0;}\n.user-btn{\n width:100%;display:flex;align-items:center;gap:12px;\n padding:10px 12px;border:1px solid #0a3300;border-radius:8px;\n background:#000;color:inherit;cursor:pointer;text-align:left;\n font:inherit;transition:border-color .15s;\n}\n.user-btn:hover{border-color:#33ff00;}\n.avatar{\n width:36px;height:36px;border-radius:50%;\n background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.user-text{min-width:0;}\n.user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}\n.user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}\n.user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}\n\n.settings-layout{\n max-width:920px;margin:0 auto;padding:28px 20px;\n display:flex;gap:28px;\n}\n.settings-sidebar{width:200px;flex-shrink:0;}\n.settings-sidebar a{\n display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;\n text-decoration:none;font-size:.8125rem;transition:color .15s;\n}\n.settings-sidebar a:hover{color:#33ff00;}\n.settings-sidebar a.active{color:#33ff00;font-weight:600;}\n.settings-main{flex:1;min-width:0;}\n\n.s-card{\n padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;\n}\n.s-card:last-child{border-bottom:none;}\n.s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}\n.s-icon{\n width:42px;height:42px;border-radius:8px;\n background:#0a3300;display:flex;align-items:center;justify-content:center;\n font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.s-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.25rem;font-weight:600;color:#33ff00;\n}\n.s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.section-heading{\n font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;\n display:flex;align-items:center;justify-content:space-between;\n}\n.perm-list{list-style:none;}\n.perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}\n.check{color:#33ff00;}\n.org-row{\n display:flex;align-items:center;gap:8px;padding:7px 0;\n border-bottom:1px solid #0a3300;font-size:.8125rem;\n}\n.org-row:last-child{border-bottom:none;}\n.org-icon{\n width:22px;height:22px;border-radius:4px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;\n font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.org-name{font-weight:600;color:#33ff00;}\n.badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}\n.badge-granted{background:#0a3300;color:#33ff00;}\n.badge-denied{background:#1a0a0a;color:#ff4444;}\n.badge-requested{background:#0a3300;color:#1a8c00;}\n.btn-revoke{\n display:inline-block;padding:5px 14px;border-radius:6px;\n border:1px solid #0a3300;background:transparent;color:#ff4444;\n font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;\n}\n.btn-revoke:hover{border-color:#ff4444;}\n.info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}\n.app-link{\n display:flex;align-items:center;gap:12px;padding:12px;\n border:1px solid #0a3300;border-radius:8px;background:#000;\n text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;\n}\n.app-link:hover{border-color:#33ff00;}\n.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}\n.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}\n.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}\n`;\n\nconst POWERED_BY = `<div class=\"powered-by\">Powered by <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\">emulate</a></div>`;\n\nfunction emuBar(service?: string): string {\n const title = service ? `${escapeHtml(service)} Emulator` : \"Emulator\";\n return `<div class=\"emu-bar\">\n <span class=\"emu-bar-title\">${title}</span>\n <nav class=\"emu-bar-links\">\n <a href=\"https://github.com/vercel-labs/emulate/issues\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Report Issue</span><span class=\"short\">Report</span></a>\n <a href=\"https://github.com/vercel-labs/emulate\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Source Code</span><span class=\"short\">Source</span></a>\n <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Learn More</span><span class=\"short\">Learn</span></a>\n </nav>\n</div>`;\n}\n\nfunction head(title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/>\n<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(\n title: string,\n subtitle: string,\n body: string,\n service?: string\n): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\">\n <div class=\"card-title\">${escapeHtml(title)}</div>\n <div class=\"card-subtitle\">${subtitle}</div>\n ${body}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderErrorPage(title: string, message: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner error-card\">\n <div class=\"error-title\">${escapeHtml(title)}</div>\n <div class=\"error-msg\">${escapeHtml(message)}</div>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderSettingsPage(\n title: string,\n sidebarHtml: string,\n bodyHtml: string,\n service?: string\n): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"settings-layout\">\n <nav class=\"settings-sidebar\">${sidebarHtml}</nav>\n <div class=\"settings-main\">${bodyHtml}</div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface UserButtonOptions {\n letter: string;\n login: string;\n name?: string;\n email?: string;\n formAction: string;\n hiddenFields: Record<string, string>;\n}\n\nexport function renderUserButton(opts: UserButtonOptions): string {\n const hiddens = Object.entries(opts.hiddenFields)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\");\n\n const nameLine = opts.name\n ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>`\n : \"\";\n const emailLine = opts.email\n ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>`\n : \"\";\n\n return `<form class=\"user-form\" method=\"post\" action=\"${escapeAttr(opts.formAction)}\">\n${hiddens}\n<button type=\"submit\" class=\"user-btn\">\n <span class=\"avatar\">${escapeHtml(opts.letter)}</span>\n <span class=\"user-text\">\n <span class=\"user-login\">${escapeHtml(opts.login)}</span>\n ${nameLine}${emailLine}\n </span>\n</button>\n</form>`;\n}\n","import { timingSafeEqual } from \"crypto\";\n\nexport function normalizeUri(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.origin}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return uri.replace(/\\/+$/, \"\").split(\"?\")[0];\n }\n}\n\nexport function matchesRedirectUri(incoming: string, registered: string[]): boolean {\n const normalized = normalizeUri(incoming);\n return registered.some((r) => normalizeUri(r) === normalized);\n}\n\nexport function constantTimeSecretEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a, \"utf-8\");\n const bufB = Buffer.from(b, \"utf-8\");\n if (bufA.length !== bufB.length) return false;\n return timingSafeEqual(bufA, bufB);\n}\n\nexport function bodyStr(v: unknown): string {\n if (typeof v === \"string\") return v;\n if (Array.isArray(v) && typeof v[0] === \"string\") return v[0];\n return \"\";\n}\n\nexport function parseCookies(header: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.split(\"=\");\n if (k) cookies[k.trim()] = v.join(\"=\").trim();\n }\n return cookies;\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\nimport { generateTs } from \"../helpers.js\";\n\nexport function webhookRoutes(ctx: RouteContext): void {\n const { app, store, webhooks } = ctx;\n const ss = () => getSlackStore(store);\n\n // Incoming Webhooks - POST /services/:teamId/:botId/:token\n // The simplest Slack integration: apps POST JSON to send a message to a channel.\n app.post(\"/services/:teamId/:botId/:token\", async (c) => {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const rawText = await c.req.text();\n\n let body: Record<string, unknown>;\n if (contentType.includes(\"application/json\")) {\n try {\n body = JSON.parse(rawText);\n } catch {\n return c.text(\"invalid_payload\", 400);\n }\n } else {\n // Slack also accepts form-urlencoded with a \"payload\" field\n const params = new URLSearchParams(rawText);\n const payload = params.get(\"payload\");\n if (payload) {\n try {\n body = JSON.parse(payload);\n } catch {\n return c.text(\"invalid_payload\", 400);\n }\n } else {\n body = {};\n }\n }\n\n const text = typeof body.text === \"string\" ? body.text : \"\";\n const channelName = typeof body.channel === \"string\" ? body.channel : \"\";\n const threadTs = typeof body.thread_ts === \"string\" ? body.thread_ts : undefined;\n\n if (!text && !body.blocks && !body.attachments) {\n return c.text(\"no_text\", 400);\n }\n\n // Find target channel: explicit channel, webhook default, or #general\n const webhook = ss().incomingWebhooks.all().find(\n (w) => w.token === c.req.param(\"token\")\n );\n\n let targetChannel = channelName\n ? (ss().channels.findOneBy(\"name\", channelName) ?? ss().channels.findOneBy(\"channel_id\", channelName))\n : null;\n\n if (!targetChannel && webhook) {\n targetChannel = ss().channels.findOneBy(\"name\", webhook.default_channel)\n ?? ss().channels.findOneBy(\"channel_id\", webhook.default_channel);\n }\n\n if (!targetChannel) {\n targetChannel = ss().channels.findOneBy(\"name\", \"general\");\n }\n\n if (!targetChannel) {\n return c.text(\"channel_not_found\", 404);\n }\n\n const ts = generateTs();\n const botId = c.req.param(\"botId\");\n\n ss().messages.insert({\n ts,\n channel_id: targetChannel.channel_id,\n user: botId,\n text: text || \"(rich message)\",\n type: \"message\" as const,\n subtype: \"bot_message\",\n thread_ts: threadTs,\n reply_count: 0,\n reply_users: [],\n reactions: [],\n });\n\n await webhooks.dispatch(\"message\", {\n type: \"event_callback\",\n event: {\n type: \"message\",\n subtype: \"bot_message\",\n channel: targetChannel.channel_id,\n bot_id: botId,\n text: text || \"(rich message)\",\n ts,\n thread_ts: threadTs,\n },\n });\n\n return c.text(\"ok\");\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { escapeHtml, renderSettingsPage } from \"@emulators/core\";\nimport { getSlackStore } from \"../store.js\";\nimport type { SlackMessage, SlackChannel } from \"../entities.js\";\n\nconst SERVICE_LABEL = \"Slack\";\n\nfunction timeAgo(isoDate: string): string {\n const seconds = Math.floor((Date.now() - new Date(isoDate).getTime()) / 1000);\n if (seconds < 60) return \"just now\";\n if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;\n if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;\n return `${Math.floor(seconds / 86400)}d ago`;\n}\n\nfunction renderReactions(reactions: Array<{ name: string; count: number }>): string {\n if (!reactions || reactions.length === 0) return \"\";\n const badges = reactions\n .map((r) => `<span class=\"badge badge-granted\">:${escapeHtml(r.name)}: ${r.count}</span>`)\n .join(\" \");\n return `<div style=\"margin-top:4px\">${badges}</div>`;\n}\n\nfunction renderMessage(msg: SlackMessage, users: Map<string, string>): string {\n const displayName = users.get(msg.user) ?? msg.user;\n const isBot = msg.subtype === \"bot_message\";\n const letter = isBot ? \"B\" : (displayName[0] ?? \"?\").toUpperCase();\n const threadBadge = msg.reply_count > 0\n ? ` <span class=\"badge badge-requested\">${msg.reply_count} ${msg.reply_count === 1 ? \"reply\" : \"replies\"}</span>`\n : \"\";\n const threadIndicator = msg.thread_ts && msg.thread_ts !== msg.ts\n ? `<span class=\"badge badge-denied\">thread</span> `\n : \"\";\n\n return `<div class=\"org-row\">\n <span class=\"org-icon\">${escapeHtml(letter)}</span>\n <span class=\"org-name\">${escapeHtml(displayName)}${isBot ? ' <span class=\"badge badge-granted\">bot</span>' : \"\"}</span>\n <span class=\"user-meta\" style=\"margin-left:auto\">${timeAgo(msg.created_at)}</span>\n</div>\n<div class=\"info-text\">${threadIndicator}${escapeHtml(msg.text)}${threadBadge}</div>\n${renderReactions(msg.reactions)}`;\n}\n\nfunction renderChannelSidebar(channels: SlackChannel[], activeId: string): string {\n return channels\n .map((ch) => {\n const active = ch.channel_id === activeId ? ' class=\"active\"' : \"\";\n const prefix = ch.is_private ? \"🔒 \" : \"# \";\n return `<a href=\"/?channel=${escapeHtml(ch.channel_id)}\"${active}>${prefix}${escapeHtml(ch.name)}</a>`;\n })\n .join(\"\\n\");\n}\n\nexport function inspectorRoutes(ctx: RouteContext): void {\n const { app, store } = ctx;\n const ss = () => getSlackStore(store);\n\n // Message Inspector - the visual dashboard\n app.get(\"/\", (c) => {\n const channels = ss().channels.all().filter((ch) => !ch.is_archived);\n const team = ss().teams.all()[0];\n\n if (channels.length === 0) {\n return c.html(renderSettingsPage(\n \"Slack Inspector\",\n \"<p class='empty'>No channels</p>\",\n \"<p class='empty'>No channels in the emulator store.</p>\",\n SERVICE_LABEL\n ));\n }\n\n // Pick active channel from query param or default to first\n const requestedChannel = c.req.query(\"channel\") ?? \"\";\n const activeChannel = channels.find((ch) => ch.channel_id === requestedChannel) ?? channels[0];\n\n // Build user lookup map\n const userMap = new Map<string, string>();\n for (const u of ss().users.all()) {\n userMap.set(u.user_id, u.name);\n userMap.set(u.name, u.name);\n }\n for (const b of ss().bots.all()) {\n userMap.set(b.bot_id, b.name);\n }\n\n // Get messages for the active channel, newest first\n const messages = ss().messages\n .findBy(\"channel_id\", activeChannel.channel_id)\n .sort((a, b) => (b.ts > a.ts ? 1 : -1))\n .slice(0, 50);\n\n const sidebar = renderChannelSidebar(channels, activeChannel.channel_id);\n\n // Build the message list\n const messageHtml = messages.length === 0\n ? '<p class=\"empty\">No messages yet. Post one with chat.postMessage or an incoming webhook.</p>'\n : messages.map((m) => renderMessage(m, userMap)).join(\"\\n<div style='height:8px'></div>\\n\");\n\n const stats = `${ss().users.all().length} users, ${channels.length} channels, ${ss().messages.all().length} messages`;\n\n const bodyHtml = `\n<div class=\"s-card\">\n <div class=\"s-card-header\">\n <div class=\"s-icon\">#</div>\n <div>\n <div class=\"s-title\">${escapeHtml(activeChannel.name)}</div>\n <div class=\"s-subtitle\">${escapeHtml(activeChannel.topic.value || \"No topic set\")} - ${activeChannel.num_members} members</div>\n </div>\n </div>\n <div class=\"section-heading\">\n Messages\n <span class=\"user-meta\">${stats}</span>\n </div>\n ${messageHtml}\n</div>`;\n\n return c.html(renderSettingsPage(\n `${team?.name ?? \"Slack\"} - Message Inspector`,\n sidebar,\n bodyHtml,\n SERVICE_LABEL\n ));\n });\n}\n","import type { Hono } from \"hono\";\nimport type { ServicePlugin, Store, WebhookDispatcher, TokenMap, AppEnv, RouteContext } from \"@emulators/core\";\nimport { getSlackStore } from \"./store.js\";\nimport { generateSlackId } from \"./helpers.js\";\nimport { authRoutes } from \"./routes/auth.js\";\nimport { chatRoutes } from \"./routes/chat.js\";\nimport { conversationsRoutes } from \"./routes/conversations.js\";\nimport { usersRoutes } from \"./routes/users.js\";\nimport { reactionsRoutes } from \"./routes/reactions.js\";\nimport { teamRoutes } from \"./routes/team.js\";\nimport { oauthRoutes } from \"./routes/oauth.js\";\nimport { webhookRoutes } from \"./routes/webhooks.js\";\nimport { inspectorRoutes } from \"./routes/inspector.js\";\n\nexport { getSlackStore, type SlackStore } from \"./store.js\";\nexport * from \"./entities.js\";\n\nexport interface SlackSeedConfig {\n port?: number;\n team?: {\n name?: string;\n domain?: string;\n };\n users?: Array<{\n name: string;\n real_name?: string;\n email?: string;\n is_admin?: boolean;\n }>;\n channels?: Array<{\n name: string;\n topic?: string;\n purpose?: string;\n is_private?: boolean;\n }>;\n bots?: Array<{\n name: string;\n }>;\n oauth_apps?: Array<{\n client_id: string;\n client_secret: string;\n name: string;\n redirect_uris: string[];\n }>;\n incoming_webhooks?: Array<{\n channel: string;\n label?: string;\n }>;\n signing_secret?: string;\n}\n\nfunction seedDefaults(store: Store, _baseUrl: string): void {\n const ss = getSlackStore(store);\n\n const teamId = \"T000000001\";\n\n ss.teams.insert({\n team_id: teamId,\n name: \"Emulate\",\n domain: \"emulate\",\n });\n\n const userId = \"U000000001\";\n ss.users.insert({\n user_id: userId,\n team_id: teamId,\n name: \"admin\",\n real_name: \"Admin User\",\n email: \"admin@emulate.dev\",\n is_admin: true,\n is_bot: false,\n deleted: false,\n profile: {\n display_name: \"admin\",\n real_name: \"Admin User\",\n email: \"admin@emulate.dev\",\n image_48: \"\",\n image_192: \"\",\n },\n });\n\n ss.channels.insert({\n channel_id: \"C000000001\",\n team_id: teamId,\n name: \"general\",\n is_channel: true,\n is_private: false,\n is_archived: false,\n topic: { value: \"General discussion\", creator: userId, last_set: Math.floor(Date.now() / 1000) },\n purpose: { value: \"A place for general discussion\", creator: userId, last_set: Math.floor(Date.now() / 1000) },\n members: [userId],\n creator: userId,\n num_members: 1,\n });\n\n ss.channels.insert({\n channel_id: \"C000000002\",\n team_id: teamId,\n name: \"random\",\n is_channel: true,\n is_private: false,\n is_archived: false,\n topic: { value: \"Random stuff\", creator: userId, last_set: Math.floor(Date.now() / 1000) },\n purpose: { value: \"A place for non-work-related chatter\", creator: userId, last_set: Math.floor(Date.now() / 1000) },\n members: [userId],\n creator: userId,\n num_members: 1,\n });\n\n // Default incoming webhook for #general\n ss.incomingWebhooks.insert({\n token: \"X000000001\",\n team_id: teamId,\n bot_id: \"B000000001\",\n default_channel: \"general\",\n label: \"Default Webhook\",\n url: `/services/${teamId}/B000000001/X000000001`,\n });\n}\n\nexport function seedFromConfig(store: Store, _baseUrl: string, config: SlackSeedConfig): void {\n const ss = getSlackStore(store);\n\n if (config.team) {\n const existing = ss.teams.all()[0];\n if (existing) {\n ss.teams.update(existing.id, {\n name: config.team.name ?? existing.name,\n domain: config.team.domain ?? existing.domain,\n });\n }\n }\n\n const team = ss.teams.all()[0];\n const teamId = team?.team_id ?? \"T000000001\";\n\n if (config.users) {\n for (const u of config.users) {\n const existing = ss.users.all().find((eu) => eu.name === u.name);\n if (existing) continue;\n\n const userId = generateSlackId(\"U\");\n const email = u.email ?? `${u.name}@emulate.dev`;\n ss.users.insert({\n user_id: userId,\n team_id: teamId,\n name: u.name,\n real_name: u.real_name ?? u.name,\n email,\n is_admin: u.is_admin ?? false,\n is_bot: false,\n deleted: false,\n profile: {\n display_name: u.name,\n real_name: u.real_name ?? u.name,\n email,\n image_48: \"\",\n image_192: \"\",\n },\n });\n }\n }\n\n if (config.channels) {\n for (const ch of config.channels) {\n const existing = ss.channels.findOneBy(\"name\", ch.name);\n if (existing) continue;\n\n const creator = ss.users.all()[0]?.user_id ?? \"U000000001\";\n const now = Math.floor(Date.now() / 1000);\n const isPrivate = ch.is_private ?? false;\n\n ss.channels.insert({\n channel_id: generateSlackId(\"C\"),\n team_id: teamId,\n name: ch.name,\n is_channel: !isPrivate,\n is_private: isPrivate,\n is_archived: false,\n topic: { value: ch.topic ?? \"\", creator, last_set: now },\n purpose: { value: ch.purpose ?? \"\", creator, last_set: now },\n members: ss.users.all().map((u) => u.user_id),\n creator,\n num_members: ss.users.all().length,\n });\n }\n }\n\n if (config.bots) {\n for (const b of config.bots) {\n const existing = ss.bots.all().find((eb) => eb.name === b.name);\n if (existing) continue;\n\n ss.bots.insert({\n bot_id: generateSlackId(\"B\"),\n name: b.name,\n deleted: false,\n icons: { image_48: \"\" },\n });\n }\n }\n\n if (config.oauth_apps) {\n for (const oa of config.oauth_apps) {\n const existing = ss.oauthApps.findOneBy(\"client_id\", oa.client_id);\n if (existing) continue;\n\n ss.oauthApps.insert({\n client_id: oa.client_id,\n client_secret: oa.client_secret,\n name: oa.name,\n redirect_uris: oa.redirect_uris,\n });\n }\n }\n\n if (config.incoming_webhooks) {\n const firstBot = ss.bots.all()[0];\n const botId = firstBot?.bot_id ?? \"B000000001\";\n\n for (const wh of config.incoming_webhooks) {\n const token = generateSlackId(\"X\");\n ss.incomingWebhooks.insert({\n token,\n team_id: teamId,\n bot_id: botId,\n default_channel: wh.channel,\n label: wh.label ?? wh.channel,\n url: `/services/${teamId}/${botId}/${token}`,\n });\n }\n }\n\n if (config.signing_secret) {\n store.setData(\"slack.signing_secret\", config.signing_secret);\n }\n}\n\nexport const slackPlugin: ServicePlugin = {\n name: \"slack\",\n register(app: Hono<AppEnv>, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void {\n const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap };\n authRoutes(ctx);\n chatRoutes(ctx);\n conversationsRoutes(ctx);\n usersRoutes(ctx);\n reactionsRoutes(ctx);\n teamRoutes(ctx);\n oauthRoutes(ctx);\n webhookRoutes(ctx);\n inspectorRoutes(ctx);\n },\n seed(store: Store, baseUrl: string): void {\n seedDefaults(store, baseUrl);\n },\n};\n\nexport default slackPlugin;\n"],"mappings":";AAaO,SAAS,cAAc,OAA0B;AACtD,SAAO;AAAA,IACL,OAAO,MAAM,WAAsB,eAAe,CAAC,SAAS,CAAC;AAAA,IAC7D,OAAO,MAAM,WAAsB,eAAe,CAAC,WAAW,OAAO,CAAC;AAAA,IACtE,UAAU,MAAM,WAAyB,kBAAkB,CAAC,cAAc,MAAM,CAAC;AAAA,IACjF,UAAU,MAAM,WAAyB,kB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AG;AACvB,gBAAY,GAAG;AACf,oBAAgB,GAAG;AACnB,eAAW,GAAG;AACd,gBAAY,GAAG;AACf,kBAAc,GAAG;AACjB,oBAAgB,GAAG;AAAA,EACrB;AAAA,EACA,KAAK,OAAc,SAAuB;AACxC,iBAAa,OAAO,OAAO;AAAA,EAC7B;AACF;AAEA,IAAO,gBAAQ;","names":["randomBytes","randomBytes","SERVICE_LABEL"]}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@emulators/slack",
3
+ "version": "0.3.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "homepage": "https://emulate.dev",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/vercel-labs/emulate.git",
18
+ "directory": "packages/@emulators/slack"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/vercel-labs/emulate/issues"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "dependencies": {
30
+ "hono": "^4",
31
+ "@emulators/core": "0.3.0"
32
+ },
33
+ "devDependencies": {
34
+ "tsup": "^8",
35
+ "typescript": "^5.7",
36
+ "vitest": "^4.1.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup --clean",
40
+ "dev": "tsup --watch",
41
+ "test": "vitest run",
42
+ "clean": "rm -rf dist .turbo"
43
+ }
44
+ }