ludicord 2.2.1 → 2.2.4

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.
Files changed (166) hide show
  1. package/README.md +8 -6
  2. package/bin/ludicord.js +0 -0
  3. package/dist/api/runtime.d.ts +4 -0
  4. package/dist/api/runtime.js +61 -10
  5. package/dist/auth/client.d.ts +10 -0
  6. package/dist/auth/client.js +58 -8
  7. package/dist/auth/index.d.ts +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/auth/server.js +154 -34
  10. package/dist/auth/types.d.ts +5 -0
  11. package/dist/cli/index.js +14 -13
  12. package/dist/cli/project-commands.js +49 -34
  13. package/dist/compiler/build.js +37 -128
  14. package/dist/compiler/client-entry.d.ts +4 -0
  15. package/dist/compiler/client-entry.js +35 -0
  16. package/dist/compiler/client-tooling.d.ts +5 -0
  17. package/dist/compiler/client-tooling.js +97 -0
  18. package/dist/compiler/scanner.js +8 -0
  19. package/dist/compiler/server-bundle.d.ts +11 -0
  20. package/dist/compiler/server-bundle.js +31 -0
  21. package/dist/compiler/type-generation.js +11 -2
  22. package/dist/config/defaults.js +28 -2
  23. package/dist/config/environment.d.ts +2 -0
  24. package/dist/config/environment.js +18 -0
  25. package/dist/discord/data.d.ts +21 -0
  26. package/dist/discord/data.js +91 -0
  27. package/dist/discord/events.d.ts +42 -4
  28. package/dist/discord/events.js +120 -41
  29. package/dist/discord/index.d.ts +4 -2
  30. package/dist/discord/index.js +2 -1
  31. package/dist/discord/runtime.d.ts +2 -2
  32. package/dist/discord/runtime.js +9 -13
  33. package/dist/discord/testing.d.ts +1 -0
  34. package/dist/discord/testing.js +10 -0
  35. package/dist/manifests/types.d.ts +4 -0
  36. package/dist/navigation/index.d.ts +2 -0
  37. package/dist/runtime/client/dev-panel.d.ts +2 -0
  38. package/dist/runtime/client/dev-panel.js +63 -0
  39. package/dist/runtime/client/embed-router.d.ts +4 -1
  40. package/dist/runtime/client/embed-router.js +69 -17
  41. package/dist/runtime/client/files.d.ts +23 -0
  42. package/dist/runtime/client/files.js +12 -0
  43. package/dist/runtime/client/minimize-card.js +4 -4
  44. package/dist/runtime/client/minimize.d.ts +1 -0
  45. package/dist/runtime/client/minimize.js +1 -0
  46. package/dist/runtime/client/root.d.ts +7 -0
  47. package/dist/runtime/client/root.js +19 -0
  48. package/dist/runtime/index.d.ts +8 -4
  49. package/dist/runtime/index.js +14 -2
  50. package/dist/runtime/server/dev-server.d.ts +1 -0
  51. package/dist/runtime/server/dev-server.js +294 -319
  52. package/dist/runtime/server/diagnostics.d.ts +17 -0
  53. package/dist/runtime/server/diagnostics.js +87 -0
  54. package/dist/runtime/server/index.d.ts +5 -0
  55. package/dist/runtime/server/index.js +3 -0
  56. package/dist/runtime/server/production-server.js +14 -0
  57. package/dist/security/discord.d.ts +9 -0
  58. package/dist/security/discord.js +37 -7
  59. package/dist/security/secret-scan.d.ts +3 -0
  60. package/dist/security/secret-scan.js +40 -0
  61. package/dist/server/discord-rest.d.ts +45 -0
  62. package/dist/server/discord-rest.js +46 -0
  63. package/dist/server/index.d.ts +2 -0
  64. package/dist/server/index.js +1 -0
  65. package/dist/sessions/cookies.d.ts +4 -1
  66. package/dist/sessions/cookies.js +17 -4
  67. package/dist/sessions/crypto.js +6 -0
  68. package/dist/testing/index.d.ts +13 -0
  69. package/dist/testing/index.js +24 -0
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/dist/ws/client.d.ts +6 -0
  73. package/dist/ws/client.js +46 -10
  74. package/dist/ws/server.d.ts +4 -0
  75. package/dist/ws/server.js +35 -14
  76. package/package.json +31 -4
  77. package/dist/api/runtime.d.ts.map +0 -1
  78. package/dist/api/runtime.js.map +0 -1
  79. package/dist/auth/client.d.ts.map +0 -1
  80. package/dist/auth/client.js.map +0 -1
  81. package/dist/auth/index.d.ts.map +0 -1
  82. package/dist/auth/index.js.map +0 -1
  83. package/dist/auth/server.d.ts.map +0 -1
  84. package/dist/auth/server.js.map +0 -1
  85. package/dist/auth/types.d.ts.map +0 -1
  86. package/dist/auth/types.js.map +0 -1
  87. package/dist/cli/index.d.ts.map +0 -1
  88. package/dist/cli/index.js.map +0 -1
  89. package/dist/cli/project-commands.d.ts.map +0 -1
  90. package/dist/cli/project-commands.js.map +0 -1
  91. package/dist/compiler/build.d.ts.map +0 -1
  92. package/dist/compiler/build.js.map +0 -1
  93. package/dist/compiler/index.d.ts.map +0 -1
  94. package/dist/compiler/index.js.map +0 -1
  95. package/dist/compiler/scanner.d.ts.map +0 -1
  96. package/dist/compiler/scanner.js.map +0 -1
  97. package/dist/compiler/type-generation.d.ts.map +0 -1
  98. package/dist/compiler/type-generation.js.map +0 -1
  99. package/dist/compiler/write-manifests.d.ts.map +0 -1
  100. package/dist/compiler/write-manifests.js.map +0 -1
  101. package/dist/config/defaults.d.ts.map +0 -1
  102. package/dist/config/defaults.js.map +0 -1
  103. package/dist/config/index.d.ts.map +0 -1
  104. package/dist/config/index.js.map +0 -1
  105. package/dist/config/loader.d.ts.map +0 -1
  106. package/dist/config/loader.js.map +0 -1
  107. package/dist/config/project-root.d.ts.map +0 -1
  108. package/dist/config/project-root.js.map +0 -1
  109. package/dist/config/types.d.ts.map +0 -1
  110. package/dist/config/types.js.map +0 -1
  111. package/dist/discord/events.d.ts.map +0 -1
  112. package/dist/discord/events.js.map +0 -1
  113. package/dist/discord/index.d.ts.map +0 -1
  114. package/dist/discord/index.js.map +0 -1
  115. package/dist/discord/runtime.d.ts.map +0 -1
  116. package/dist/discord/runtime.js.map +0 -1
  117. package/dist/discord/safe-area.d.ts.map +0 -1
  118. package/dist/discord/safe-area.js.map +0 -1
  119. package/dist/discord/testing.d.ts.map +0 -1
  120. package/dist/discord/testing.js.map +0 -1
  121. package/dist/index.d.ts.map +0 -1
  122. package/dist/index.js.map +0 -1
  123. package/dist/manifests/types.d.ts.map +0 -1
  124. package/dist/manifests/types.js.map +0 -1
  125. package/dist/navigation/index.d.ts.map +0 -1
  126. package/dist/navigation/index.js.map +0 -1
  127. package/dist/router/match.d.ts.map +0 -1
  128. package/dist/router/match.js.map +0 -1
  129. package/dist/runtime/client/embed-router.d.ts.map +0 -1
  130. package/dist/runtime/client/embed-router.js.map +0 -1
  131. package/dist/runtime/client/minimize-card.d.ts.map +0 -1
  132. package/dist/runtime/client/minimize-card.js.map +0 -1
  133. package/dist/runtime/client/minimize.d.ts.map +0 -1
  134. package/dist/runtime/client/minimize.js.map +0 -1
  135. package/dist/runtime/index.d.ts.map +0 -1
  136. package/dist/runtime/index.js.map +0 -1
  137. package/dist/runtime/server/dev-server.d.ts.map +0 -1
  138. package/dist/runtime/server/dev-server.js.map +0 -1
  139. package/dist/runtime/server/production-server.d.ts.map +0 -1
  140. package/dist/runtime/server/production-server.js.map +0 -1
  141. package/dist/security/discord.d.ts.map +0 -1
  142. package/dist/security/discord.js.map +0 -1
  143. package/dist/security/index.d.ts.map +0 -1
  144. package/dist/security/index.js.map +0 -1
  145. package/dist/server/index.d.ts.map +0 -1
  146. package/dist/server/index.js.map +0 -1
  147. package/dist/server/session.d.ts.map +0 -1
  148. package/dist/server/session.js.map +0 -1
  149. package/dist/server/types.d.ts.map +0 -1
  150. package/dist/server/types.js.map +0 -1
  151. package/dist/sessions/cookies.d.ts.map +0 -1
  152. package/dist/sessions/cookies.js.map +0 -1
  153. package/dist/sessions/crypto.d.ts.map +0 -1
  154. package/dist/sessions/crypto.js.map +0 -1
  155. package/dist/shared/errors.d.ts.map +0 -1
  156. package/dist/shared/errors.js.map +0 -1
  157. package/dist/testing/index.d.ts.map +0 -1
  158. package/dist/testing/index.js.map +0 -1
  159. package/dist/version.d.ts.map +0 -1
  160. package/dist/version.js.map +0 -1
  161. package/dist/ws/client.d.ts.map +0 -1
  162. package/dist/ws/client.js.map +0 -1
  163. package/dist/ws/index.d.ts.map +0 -1
  164. package/dist/ws/index.js.map +0 -1
  165. package/dist/ws/server.d.ts.map +0 -1
  166. package/dist/ws/server.js.map +0 -1
@@ -0,0 +1,11 @@
1
+ import type { LudicordManifests } from "../manifests/types.js";
2
+ export declare function bundleServerGraph(root: string, output: string, manifests: LudicordManifests): Promise<{
3
+ bundles: {
4
+ source: string;
5
+ bundle: string;
6
+ kind: "api" | "ws";
7
+ }[];
8
+ dependencies: Set<string>;
9
+ loadModule<T>(absoluteFile: string): Promise<T>;
10
+ }>;
11
+ //# sourceMappingURL=server-bundle.d.ts.map
@@ -0,0 +1,31 @@
1
+ import path from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { build } from "esbuild";
4
+ export async function bundleServerGraph(root, output, manifests) {
5
+ const routes = [...manifests.api.map((route, index) => ({ ...route, name: `api/${index}` })),
6
+ ...manifests.websocket.map((route, index) => ({ ...route, name: `ws/${index}` }))];
7
+ const bundles = routes.map((route) => ({ source: route.file, bundle: `${route.name}.mjs`, kind: route.kind }));
8
+ const dependencies = new Set();
9
+ if (routes.length > 0) {
10
+ const result = await build({
11
+ absWorkingDir: root,
12
+ entryPoints: routes.map((route) => ({ in: path.join(root, route.file), out: route.name })),
13
+ outdir: output, outExtension: { ".js": ".mjs" },
14
+ chunkNames: "shared/[name]-[hash]", platform: "node", format: "esm", target: "node20",
15
+ bundle: true, splitting: true, sourcemap: true, packages: "external", logLevel: "silent", metafile: true,
16
+ });
17
+ for (const input of Object.keys(result.metafile.inputs))
18
+ dependencies.add(path.resolve(root, input));
19
+ }
20
+ const bySource = new Map(bundles.map((route) => [path.resolve(root, route.source), path.join(output, route.bundle)]));
21
+ return {
22
+ bundles, dependencies,
23
+ async loadModule(absoluteFile) {
24
+ const bundle = bySource.get(path.resolve(absoluteFile));
25
+ if (bundle === undefined)
26
+ throw new Error("LUDICORD3003: Server route has no compiled module.");
27
+ return import(pathToFileURL(bundle).href);
28
+ },
29
+ };
30
+ }
31
+ //# sourceMappingURL=server-bundle.js.map
@@ -41,6 +41,7 @@ function generatedSource(manifests, config) {
41
41
  const params = manifests.embeds
42
42
  .map((entry) => ` readonly ${JSON.stringify(entry.route)}: ${paramsType(entry)};`)
43
43
  .join("\n");
44
+ const routeParams = (entries) => entries.map((entry) => ` readonly ${JSON.stringify(entry.route)}: ${paramsType(entry)};`).join("\n");
44
45
  const embedPatterns = manifests.embeds.map(({ route }) => JSON.stringify(route));
45
46
  return `// Generated by Ludicord. Changes will be replaced by ludicord dev or ludicord build.
46
47
  import "ludicord/navigation";
@@ -53,6 +54,12 @@ declare module "ludicord/navigation" {
53
54
  readonly websocket: ${routeUnion(manifests.websocket)};
54
55
  readonly embedParams: {
55
56
  ${params}
57
+ };
58
+ readonly apiParams: {
59
+ ${routeParams(manifests.api)}
60
+ };
61
+ readonly websocketParams: {
62
+ ${routeParams(manifests.websocket)}
56
63
  };
57
64
  readonly config: {
58
65
  readonly defaultEmbed: ${JSON.stringify(config.activity.defaultEmbed)};
@@ -76,8 +83,10 @@ export function generateLudicordTypes(projectRoot, manifests, config) {
76
83
  const publicFile = path.join(root, "ludicord.generated.d.ts");
77
84
  const internalFile = path.join(root, ".ludicord", "types", "routes.d.ts");
78
85
  mkdirSync(path.dirname(internalFile), { recursive: true });
79
- writeFileSync(publicFile, source, "utf8");
80
- writeFileSync(internalFile, source, "utf8");
86
+ if (!existsSync(publicFile) || readFileSync(publicFile, "utf8") !== source)
87
+ writeFileSync(publicFile, source, "utf8");
88
+ if (!existsSync(internalFile) || readFileSync(internalFile, "utf8") !== source)
89
+ writeFileSync(internalFile, source, "utf8");
81
90
  ensureLudicordEnv(root);
82
91
  return publicFile;
83
92
  }
@@ -1,6 +1,6 @@
1
1
  export function resolveConfig(config = {}) {
2
- const clientId = config.discord?.clientId;
3
- return {
2
+ const clientId = config.discord?.clientId ?? process.env.LUDICORD_DISCORD_CLIENT_ID;
3
+ const resolved = {
4
4
  discord: {
5
5
  ...(clientId === undefined ? {} : { clientId }),
6
6
  scopes: [...(config.discord?.scopes ?? ["identify"])],
@@ -36,5 +36,31 @@ export function resolveConfig(config = {}) {
36
36
  },
37
37
  },
38
38
  };
39
+ const fail = (field) => { throw new TypeError("LUDICORD0004: Invalid " + field + " in ludicord.config.mjs."); };
40
+ const integer = (value, min, max, field) => { if (!Number.isSafeInteger(value) || value < min || value > max)
41
+ fail(field); };
42
+ integer(resolved.server.port, 0, 65535, "server.port");
43
+ integer(resolved.websocket.heartbeatInterval, 1, 2_147_483_647, "websocket.heartbeatInterval");
44
+ integer(resolved.websocket.maxPayload, 1, 1_073_741_824, "websocket.maxPayload");
45
+ integer(resolved.websocket.reconnect.attempts, 0, 10000, "websocket.reconnect.attempts");
46
+ integer(resolved.websocket.reconnect.initialDelay, 0, 2_147_483_647, "websocket.reconnect.initialDelay");
47
+ integer(resolved.websocket.reconnect.maxDelay, resolved.websocket.reconnect.initialDelay, 2_147_483_647, "websocket.reconnect.maxDelay");
48
+ if (!["allow", "mock", "error"].includes(resolved.activity.outsideDiscord))
49
+ fail("activity.outsideDiscord");
50
+ if (typeof resolved.activity.defaultEmbed !== "string" || !resolved.activity.defaultEmbed.trim())
51
+ fail("activity.defaultEmbed");
52
+ if (typeof resolved.server.host !== "string" || !resolved.server.host.trim())
53
+ fail("server.host");
54
+ if (resolved.server.allowedHosts !== true && (!Array.isArray(resolved.server.allowedHosts) || resolved.server.allowedHosts.some((host) => typeof host !== "string" || !host.trim())))
55
+ fail("server.allowedHosts");
56
+ if (resolved.discord.auth.session !== "encrypted-cookie")
57
+ fail("discord.auth.session");
58
+ if (!Array.isArray(resolved.discord.scopes) || resolved.discord.scopes.some((scope) => typeof scope !== "string" || !scope.trim()))
59
+ fail("discord.scopes");
60
+ for (const [field, value] of Object.entries({ "discord.auth.required": resolved.discord.auth.required, "discord.auth.proxyVerification": resolved.discord.auth.proxyVerification, "discord.auth.activityInstanceVerification": resolved.discord.auth.activityInstanceVerification, "websocket.enabled": resolved.websocket.enabled, "websocket.compression": resolved.websocket.compression, "websocket.reconnect.enabled": resolved.websocket.reconnect.enabled })) {
61
+ if (typeof value !== "boolean")
62
+ fail(field);
63
+ }
64
+ return resolved;
39
65
  }
40
66
  //# sourceMappingURL=defaults.js.map
@@ -0,0 +1,2 @@
1
+ export declare function loadProjectEnvironment(projectRoot: string, mode: string): void;
2
+ //# sourceMappingURL=environment.d.ts.map
@@ -0,0 +1,18 @@
1
+ import { loadEnv } from "vite";
2
+ // Keep explicit shell values authoritative, while allowing .env edits between commands.
3
+ const loadedValues = new Map();
4
+ export function loadProjectEnvironment(projectRoot, mode) {
5
+ for (const [name, value] of loadedValues) {
6
+ if (process.env[name] === value)
7
+ delete process.env[name];
8
+ }
9
+ loadedValues.clear();
10
+ const environment = loadEnv(mode, projectRoot, "");
11
+ for (const [name, value] of Object.entries(environment)) {
12
+ if (process.env[name] === undefined) {
13
+ process.env[name] = value;
14
+ loadedValues.set(name, value);
15
+ }
16
+ }
17
+ }
18
+ //# sourceMappingURL=environment.js.map
@@ -0,0 +1,21 @@
1
+ import type { DiscordSDK } from "@discord/embedded-app-sdk";
2
+ import type { LudicordGuildMember } from "./events.js";
3
+ type Commands = DiscordSDK["commands"];
4
+ export type LudicordDiscordCommand = Exclude<keyof Commands, "authorize" | "authenticate">;
5
+ export declare function useDiscordCommands(): {
6
+ supports(name: LudicordDiscordCommand): boolean;
7
+ call<T extends LudicordDiscordCommand>(name: T, ...args: Parameters<Commands[T]>): Promise<Awaited<ReturnType<Commands[T]>>>;
8
+ };
9
+ export declare function useDiscordGuildMembers(options?: {
10
+ readonly limit?: number;
11
+ readonly enabled?: boolean;
12
+ }): {
13
+ readonly members: readonly LudicordGuildMember[];
14
+ readonly status: "idle" | "ready" | "error" | "loading";
15
+ readonly error: Error | null;
16
+ readonly hasMore: boolean;
17
+ readonly refresh: () => void;
18
+ readonly loadMore: () => void;
19
+ };
20
+ export {};
21
+ //# sourceMappingURL=data.d.ts.map
@@ -0,0 +1,91 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { useDiscord } from "./runtime.js";
3
+ import { addDiscordDiagnostic, useDiscordGuild } from "./events.js";
4
+ import { useAuthStatus } from "../auth/client.js";
5
+ export function useDiscordCommands() {
6
+ const discord = useDiscord();
7
+ return useMemo(() => ({
8
+ supports(name) { return typeof discord.sdk?.commands?.[name] === "function"; },
9
+ async call(name, ...args) {
10
+ const command = discord.sdk?.commands?.[name];
11
+ if (discord.status !== "ready" || typeof command !== "function") {
12
+ const message = `LUDICORD5010: Discord command ${name} is not available in this client.`;
13
+ addDiscordDiagnostic(message);
14
+ throw new Error(message);
15
+ }
16
+ try {
17
+ return await command.apply(discord.sdk?.commands, args);
18
+ }
19
+ catch (cause) {
20
+ const message = `LUDICORD5011: Discord command ${name} failed. Check its required scopes and client support.`;
21
+ addDiscordDiagnostic(message);
22
+ throw new Error(message, { cause });
23
+ }
24
+ },
25
+ }), [discord.sdk, discord.status]);
26
+ }
27
+ export function useDiscordGuildMembers(options = {}) {
28
+ const guild = useDiscordGuild();
29
+ const auth = useAuthStatus();
30
+ const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 100) || 100));
31
+ const previousGuild = useRef(undefined);
32
+ const enabled = options.enabled !== false && auth === "authenticated" && guild !== null;
33
+ const [members, setMembers] = useState([]);
34
+ const [status, setStatus] = useState("idle");
35
+ const [error, setError] = useState(null);
36
+ const [next, setNext] = useState(null);
37
+ const [request, setRequest] = useState({ revision: 0, after: "" });
38
+ useEffect(() => {
39
+ if (!enabled) {
40
+ setMembers([]);
41
+ setError(null);
42
+ setStatus("idle");
43
+ setNext(null);
44
+ previousGuild.current = undefined;
45
+ return;
46
+ }
47
+ const changedGuild = previousGuild.current !== guild?.id;
48
+ previousGuild.current = guild?.id;
49
+ const after = changedGuild ? "" : request.after;
50
+ if (changedGuild) {
51
+ setMembers([]);
52
+ setNext(null);
53
+ if (request.after) {
54
+ setRequest((current) => ({ revision: current.revision + 1, after: "" }));
55
+ return;
56
+ }
57
+ }
58
+ const abort = new AbortController();
59
+ setStatus("loading");
60
+ setError(null);
61
+ void fetch(`/_ludicord/auth/guild-members?limit=${limit}${after ? `&after=${encodeURIComponent(after)}` : ""}`, { credentials: "include", signal: abort.signal })
62
+ .then(async (response) => {
63
+ const body = await response.json();
64
+ if (!response.ok)
65
+ throw new Error(body.message ?? "Discord guild members are unavailable.");
66
+ if (abort.signal.aborted)
67
+ return;
68
+ const page = (body.members ?? []).map((member) => ({
69
+ user: { id: member.user.id, username: member.user.username, displayName: member.user.global_name ?? member.user.username,
70
+ avatar: member.user.avatar ? `https://cdn.discordapp.com/avatars/${member.user.id}/${member.user.avatar}.png` : null },
71
+ nickname: member.nick ?? null, roles: member.roles ?? [], ...(member.joined_at === undefined ? {} : { joinedAt: member.joined_at }),
72
+ }));
73
+ setMembers((current) => after === "" ? page : [...current.filter((item) => !page.some((entry) => entry.user.id === item.user.id)), ...page]);
74
+ setNext(body.next ?? null);
75
+ setStatus("ready");
76
+ }).catch((cause) => {
77
+ if (abort.signal.aborted)
78
+ return;
79
+ const failure = cause instanceof Error ? cause : new Error("Discord guild members are unavailable.");
80
+ setError(failure);
81
+ setStatus("error");
82
+ addDiscordDiagnostic(failure.message);
83
+ });
84
+ return () => abort.abort();
85
+ }, [enabled, guild?.id, limit, request]);
86
+ const refresh = useCallback(() => setRequest((current) => ({ revision: current.revision + 1, after: "" })), []);
87
+ const loadMore = useCallback(() => { if (next !== null && status !== "loading")
88
+ setRequest((current) => ({ revision: current.revision + 1, after: next })); }, [next, status]);
89
+ return { members, status, error, hasMore: next !== null, refresh, loadMore };
90
+ }
91
+ //# sourceMappingURL=data.js.map
@@ -12,11 +12,24 @@ export interface LudicordDiscordChannel {
12
12
  readonly name?: string;
13
13
  readonly type?: number;
14
14
  readonly topic?: string;
15
+ readonly guildId?: string;
16
+ readonly kind?: string;
17
+ readonly isVoice?: boolean;
15
18
  }
16
19
  export interface LudicordDiscordGuild {
17
20
  readonly id: string;
18
21
  readonly name?: string;
19
22
  readonly icon?: string | null;
23
+ readonly description?: string | null;
24
+ readonly memberCount?: number;
25
+ readonly features?: readonly string[];
26
+ }
27
+ export interface LudicordGuildMember {
28
+ readonly user: LudicordDiscordUser;
29
+ readonly nickname?: string | null;
30
+ readonly avatar?: string | null;
31
+ readonly roles: readonly string[];
32
+ readonly joinedAt?: string;
20
33
  }
21
34
  export interface LudicordParticipant {
22
35
  readonly id: string;
@@ -44,16 +57,41 @@ export interface LudicordDiscordEventSnapshot {
44
57
  readonly locale: string | null;
45
58
  readonly diagnostics: readonly string[];
46
59
  readonly scopes: readonly string[];
60
+ readonly channelMembers: readonly LudicordDiscordUser[];
61
+ readonly currentGuildMember: LudicordGuildMember | null;
62
+ readonly entitlements: readonly Readonly<Record<string, unknown>>[];
47
63
  }
48
- export declare function initializeDiscordEventStore(sdk: DiscordSdkLike, scopes?: readonly string[]): Promise<void>;
49
- export declare function initializeDiscordEventsFromEnvironment(discord: DiscordRuntimeSnapshot): Promise<void>;
50
- export declare function setDiscordUserFromAuth(user: LudicordSessionUser): void;
51
- export declare function setDiscordGuildFromAuth(guildId: string | undefined, guildName: string | undefined): void;
64
+ export declare function channelTypeName(type: number): string;
65
+ export declare function addDiscordDiagnostic(message: string): void;
66
+ export declare function initializeDiscordEventStore(sdk: DiscordSdkLike, scopes?: readonly string[], channelId?: string, guildId?: string): Promise<void>;
67
+ export declare function initializeDiscordEventsFromEnvironment(discord: DiscordRuntimeSnapshot, grantedScopes?: readonly string[]): Promise<void>;
68
+ export declare function setDiscordUserFromAuth(user: LudicordSessionUser | null): void;
69
+ export declare function enrichDiscordContext(context: {
70
+ guild?: {
71
+ id: string;
72
+ name: string;
73
+ icon?: string | null;
74
+ description?: string | null;
75
+ approximate_member_count?: number;
76
+ features?: readonly string[];
77
+ };
78
+ channel?: {
79
+ id: string;
80
+ name?: string;
81
+ type: number;
82
+ guild_id?: string;
83
+ topic?: string | null;
84
+ };
85
+ }): void;
86
+ export declare function setDiscordGuildFromAuth(guildId: string | undefined, guildName: string | undefined, guildIcon?: string | null): void;
52
87
  export declare function diagnoseDiscordScope(scope: string, feature: string): void;
53
88
  export declare function useDiscordUser(): LudicordDiscordUser | null;
54
89
  export declare function useDiscordChannel(): LudicordDiscordChannel | null;
55
90
  export declare function useDiscordGuild(): LudicordDiscordGuild | null;
56
91
  export declare function useParticipants(): readonly LudicordParticipant[];
92
+ export declare function useChannelMembers(): readonly LudicordDiscordUser[];
93
+ export declare function useCurrentGuildMember(): LudicordGuildMember | null;
94
+ export declare function useDiscordEntitlements(): readonly Readonly<Record<string, unknown>>[];
57
95
  export declare function useVoiceState(): readonly LudicordVoiceState[];
58
96
  export declare function useSpeakingUsers(): readonly string[];
59
97
  export declare function useIsSpeaking(userId: string | null | undefined): boolean;
@@ -33,6 +33,9 @@ class DiscordEventStore {
33
33
  locale: null,
34
34
  diagnostics: [],
35
35
  scopes: [],
36
+ channelMembers: [],
37
+ currentGuildMember: null,
38
+ entitlements: [],
36
39
  };
37
40
  listeners = new Set();
38
41
  subscribe = (listener) => {
@@ -99,14 +102,13 @@ function normalizeParticipant(value) {
99
102
  : undefined;
100
103
  if (id === undefined)
101
104
  return null;
105
+ const displayName = [source.nickname, source.display_name, source.global_name, source.username].find((value) => typeof value === "string" && value !== "");
102
106
  return {
103
107
  id,
104
108
  ...(typeof source.username === "string"
105
109
  ? { username: source.username }
106
110
  : {}),
107
- ...(typeof source.display_name === "string"
108
- ? { displayName: source.display_name }
109
- : {}),
111
+ ...(displayName === undefined ? {} : { displayName }),
110
112
  ...(typeof source.avatar === "string" || source.avatar === null
111
113
  ? { avatar: discordAvatarUrl(id, source.avatar) }
112
114
  : {}),
@@ -127,11 +129,12 @@ function normalizeVoiceState(payload) {
127
129
  if (typeof value !== "object" || value === null)
128
130
  return null;
129
131
  const source = value;
132
+ const payloadUser = valueFromPayload(payload, ["user"]);
130
133
  const userId = typeof source.user_id === "string"
131
134
  ? source.user_id
132
135
  : typeof source.userId === "string"
133
136
  ? source.userId
134
- : undefined;
137
+ : stringFromPayload(payloadUser, ["id"]);
135
138
  if (userId === undefined)
136
139
  return null;
137
140
  return {
@@ -186,8 +189,26 @@ function eventHandler(event, payload) {
186
189
  });
187
190
  return;
188
191
  }
189
- if (event === "CURRENT_GUILD_MEMBER_UPDATE")
192
+ if (event === "CURRENT_GUILD_MEMBER_UPDATE") {
193
+ const source = payload;
194
+ const user = normalizeUser(valueFromPayload(payload, ["user"])) ?? eventStore.getSnapshot().user;
195
+ if (source !== null && typeof source === "object" && user !== null) {
196
+ const nickname = typeof source.nick === "string" ? source.nick : null;
197
+ eventStore.update({ currentGuildMember: {
198
+ user, nickname,
199
+ roles: Array.isArray(source.roles) ? source.roles.filter((role) => typeof role === "string") : [],
200
+ avatar: typeof source.avatar === "string" ? source.avatar : null,
201
+ } });
202
+ }
190
203
  return;
204
+ }
205
+ if (event === "ENTITLEMENT_CREATE" && typeof payload === "object" && payload !== null) {
206
+ const entitlement = (valueFromPayload(payload, ["entitlement"]) ?? payload);
207
+ if (typeof entitlement.id !== "string")
208
+ return;
209
+ eventStore.update((current) => ({ ...current, entitlements: [...current.entitlements.filter((item) => item.id !== entitlement.id), entitlement].slice(-500) }));
210
+ return;
211
+ }
191
212
  if (event === "ACTIVITY_LAYOUT_MODE_UPDATE") {
192
213
  eventStore.update({
193
214
  layoutMode: layoutModeFromPayload(payload) ?? null,
@@ -196,22 +217,33 @@ function eventHandler(event, payload) {
196
217
  }
197
218
  if (event === "ORIENTATION_UPDATE") {
198
219
  eventStore.update({
199
- orientation: stringFromPayload(payload, ["orientation"]) ?? null,
220
+ orientation: stringFromPayload(payload, ["orientation"]) ??
221
+ { 0: "portrait", 1: "landscape" }[Number(valueFromPayload(payload, ["screen_orientation"]))] ?? null,
200
222
  });
201
223
  return;
202
224
  }
203
225
  if (event === "THERMAL_STATE_UPDATE") {
204
226
  eventStore.update({
205
- thermalState: stringFromPayload(payload, ["thermal_state", "thermalState"]) ?? null,
227
+ thermalState: stringFromPayload(payload, ["thermal_state", "thermalState"]) ??
228
+ { 0: "nominal", 1: "fair", 2: "serious", 3: "critical" }[Number(valueFromPayload(payload, ["thermal_state", "thermalState"]))] ?? null,
206
229
  });
207
230
  }
208
231
  }
232
+ async function bounded(operation) {
233
+ let timer;
234
+ try {
235
+ return await Promise.race([operation, new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error("Discord capability timed out.")), 5000); })]);
236
+ }
237
+ finally {
238
+ clearTimeout(timer);
239
+ }
240
+ }
209
241
  async function initialParticipants(sdk) {
210
- const command = sdk.commands?.getActivityInstanceConnectedParticipants;
242
+ const command = sdk.commands?.getInstanceConnectedParticipants ?? sdk.commands?.getActivityInstanceConnectedParticipants;
211
243
  if (typeof command !== "function")
212
244
  return;
213
245
  try {
214
- const result = await command();
246
+ const result = await bounded(command.call(sdk.commands));
215
247
  eventStore.update({ participants: normalizeParticipants(result) });
216
248
  }
217
249
  catch {
@@ -224,7 +256,7 @@ async function initialChannel(sdk, channelId) {
224
256
  if (commands === undefined || channelId === undefined || typeof command !== "function")
225
257
  return;
226
258
  try {
227
- const result = await command.call(commands, { channel_id: channelId });
259
+ const result = await bounded(command.call(commands, { channel_id: channelId }));
228
260
  if (typeof result !== "object" || result === null)
229
261
  return;
230
262
  const channel = result;
@@ -235,6 +267,8 @@ async function initialChannel(sdk, channelId) {
235
267
  ...(typeof channel.name === "string" ? { name: channel.name } : {}),
236
268
  ...(typeof channel.type === "number" ? { type: channel.type } : {}),
237
269
  ...(typeof channel.topic === "string" ? { topic: channel.topic } : {}),
270
+ ...(typeof channel.guild_id === "string" ? { guildId: channel.guild_id } : {}),
271
+ ...(typeof channel.type === "number" ? { kind: channelTypeName(channel.type), isVoice: channel.type === 2 || channel.type === 13 } : {}),
238
272
  },
239
273
  ...(typeof channel.guild_id === "string"
240
274
  ? {
@@ -245,53 +279,85 @@ async function initialChannel(sdk, channelId) {
245
279
  }
246
280
  : {}),
247
281
  }));
282
+ const voices = valueFromPayload(result, ["voice_states"]);
283
+ if (Array.isArray(voices)) {
284
+ eventStore.update({
285
+ voiceStates: voices.map(normalizeVoiceState).filter((value) => value !== null),
286
+ channelMembers: voices.map((voice) => normalizeUser(valueFromPayload(voice, ["user"]))).filter((value) => value !== null),
287
+ });
288
+ }
248
289
  }
249
290
  catch {
250
- // Channel lookup requires the guilds scope and may be unavailable.
291
+ addDiscordDiagnostic("Channel details unavailable. Guild channels require the guilds scope; group DMs also require approved dm_channels.read access.");
251
292
  }
252
293
  }
253
- export async function initializeDiscordEventStore(sdk, scopes = []) {
294
+ export function channelTypeName(type) {
295
+ return { 0: "text", 1: "dm", 2: "voice", 3: "group-dm", 4: "category", 5: "announcement", 10: "announcement-thread", 11: "public-thread", 12: "private-thread", 13: "stage", 14: "directory", 15: "forum", 16: "media" }[type] ?? "unknown";
296
+ }
297
+ export function addDiscordDiagnostic(message) {
298
+ const current = eventStore.getSnapshot();
299
+ if (!current.diagnostics.includes(message))
300
+ eventStore.update({ diagnostics: [...current.diagnostics, message] });
301
+ }
302
+ export async function initializeDiscordEventStore(sdk, scopes = [], channelId, guildId) {
254
303
  if (activeController?.sdk === sdk)
255
304
  return;
256
305
  await activeController?.cleanup();
257
306
  eventStore.update({ scopes: [...scopes] });
258
307
  const subscriptions = [];
259
- if (typeof sdk.subscribe === "function") {
260
- for (const event of EVENT_NAMES) {
261
- const listener = (payload) => eventHandler(event, payload);
262
- try {
263
- await sdk.subscribe(event, listener);
264
- subscriptions.push({ event, listener });
265
- }
266
- catch {
267
- // Unsupported optional events are ignored by capability.
268
- }
269
- }
270
- }
308
+ let active = true;
271
309
  activeController = {
272
310
  sdk,
273
311
  async cleanup() {
274
- if (typeof sdk.unsubscribe === "function") {
275
- await Promise.allSettled(subscriptions.map(({ event, listener }) => sdk.unsubscribe?.(event, listener)));
276
- }
312
+ active = false;
313
+ if (typeof sdk.unsubscribe === "function")
314
+ await Promise.allSettled(subscriptions.map(({ event, listener, args }) => bounded(Promise.resolve(sdk.unsubscribe?.(event, listener, args)))));
277
315
  },
278
316
  };
279
- await initialParticipants(sdk);
317
+ if (typeof sdk.subscribe === "function") {
318
+ await Promise.all(EVENT_NAMES.map(async (event) => {
319
+ const listener = (payload) => { if (active)
320
+ eventHandler(event, payload); };
321
+ const args = channelId !== undefined && ["VOICE_STATE_UPDATE", "SPEAKING_START", "SPEAKING_STOP"].includes(event)
322
+ ? { channel_id: channelId } : event === "CURRENT_GUILD_MEMBER_UPDATE" && guildId !== undefined ? { guild_id: guildId } : undefined;
323
+ subscriptions.push({ event, listener, ...(args === undefined ? {} : { args }) });
324
+ try {
325
+ await bounded(Promise.resolve(sdk.subscribe?.(event, listener, args)));
326
+ }
327
+ catch { /* Optional capabilities must not block the Activity. */ }
328
+ }));
329
+ }
330
+ if (active)
331
+ await initialParticipants(sdk);
280
332
  }
281
- export async function initializeDiscordEventsFromEnvironment(discord) {
333
+ export async function initializeDiscordEventsFromEnvironment(discord, grantedScopes) {
282
334
  if (discord.status !== "ready" || discord.sdk === null)
283
335
  return;
284
336
  const config = globalThis.__LUDICORD_PUBLIC_CONFIG__;
285
- await initializeDiscordEventStore(discord.sdk, config?.scopes ?? ["identify"]);
337
+ await initializeDiscordEventStore(discord.sdk, grantedScopes ?? config?.scopes ?? ["identify"], discord.channelId, discord.guildId);
286
338
  const effectiveChannelId = discord.channelId ?? discord.sdk.channelId;
287
339
  const effectiveGuildId = discord.guildId ?? discord.sdk.guildId;
288
340
  eventStore.update({
289
341
  channel: effectiveChannelId === undefined ? null : { id: effectiveChannelId },
290
- guild: effectiveGuildId === undefined ? null : { id: effectiveGuildId },
342
+ guild: effectiveGuildId === undefined ? null : { ...eventStore.getSnapshot().guild, id: effectiveGuildId },
291
343
  });
292
344
  await initialChannel(discord.sdk, effectiveChannelId);
345
+ const localeCommand = discord.sdk.commands?.userSettingsGetLocale;
346
+ if (typeof localeCommand === "function") {
347
+ try {
348
+ const result = await bounded(localeCommand.call(discord.sdk.commands));
349
+ const locale = stringFromPayload(result, ["locale"]);
350
+ if (locale !== undefined)
351
+ eventStore.update({ locale });
352
+ }
353
+ catch { /* Optional on older clients. */ }
354
+ }
293
355
  }
294
356
  export function setDiscordUserFromAuth(user) {
357
+ if (user === null) {
358
+ eventStore.update({ user: null, currentGuildMember: null, guild: null, channel: null, channelMembers: [], entitlements: [], scopes: [] });
359
+ return;
360
+ }
295
361
  eventStore.update({
296
362
  user: {
297
363
  id: user.id,
@@ -301,17 +367,27 @@ export function setDiscordUserFromAuth(user) {
301
367
  },
302
368
  });
303
369
  }
304
- export function setDiscordGuildFromAuth(guildId, guildName) {
305
- if (guildId !== undefined || guildName !== undefined) {
306
- eventStore.update((current) => ({
307
- ...current,
308
- guild: {
309
- id: guildId ?? current.guild?.id ?? "",
310
- ...(guildName ? { name: guildName } : current.guild?.name ? { name: current.guild.name } : {}),
311
- ...(current.guild?.icon ? { icon: current.guild.icon } : {}),
312
- },
313
- }));
370
+ export function enrichDiscordContext(context) {
371
+ const guild = context.guild;
372
+ const channel = context.channel;
373
+ if (guild)
374
+ eventStore.update({ guild: { id: guild.id, name: guild.name, icon: guild.icon ? `https://cdn.discordapp.com/icons/${guild.id}/${guild.icon}.png` : null,
375
+ ...(guild.description === undefined ? {} : { description: guild.description }), ...(guild.approximate_member_count === undefined ? {} : { memberCount: guild.approximate_member_count }), ...(guild.features === undefined ? {} : { features: guild.features }) } });
376
+ if (channel)
377
+ eventStore.update({ channel: { id: channel.id, type: channel.type, kind: channelTypeName(channel.type), isVoice: [2, 13].includes(channel.type),
378
+ ...(channel.name === undefined ? {} : { name: channel.name }), ...(channel.guild_id === undefined ? {} : { guildId: channel.guild_id }), ...(channel.topic == null ? {} : { topic: channel.topic }) } });
379
+ }
380
+ export function setDiscordGuildFromAuth(guildId, guildName, guildIcon) {
381
+ if (guildId === undefined) {
382
+ eventStore.update({ guild: null });
383
+ return;
314
384
  }
385
+ const previous = eventStore.getSnapshot().guild;
386
+ eventStore.update({ guild: {
387
+ ...(previous?.id === guildId ? previous : {}), id: guildId,
388
+ ...(guildName === undefined ? {} : { name: guildName }),
389
+ ...(guildIcon === undefined ? {} : { icon: guildIcon }),
390
+ } });
315
391
  }
316
392
  export function diagnoseDiscordScope(scope, feature) {
317
393
  const snapshot = eventStore.getSnapshot();
@@ -353,6 +429,9 @@ export function useDiscordGuild() {
353
429
  export function useParticipants() {
354
430
  return useEventSnapshot().participants;
355
431
  }
432
+ export function useChannelMembers() { return useEventSnapshot().channelMembers; }
433
+ export function useCurrentGuildMember() { return useEventSnapshot().currentGuildMember; }
434
+ export function useDiscordEntitlements() { return useEventSnapshot().entitlements; }
356
435
  export function useVoiceState() {
357
436
  diagnoseDiscordScope("rpc.voice.read", "useVoiceState()");
358
437
  return useEventSnapshot().voiceStates;
@@ -1,7 +1,9 @@
1
1
  export { initializeDiscord, initializeDiscordFromEnvironment, useActivityInstance, useDiscord, } from "./runtime.js";
2
- export { useActivityLayoutMode, useDiscordChannel, useDiscordDiagnostics, useDiscordGuild, useDiscordLocale, useDiscordUser, useOrientation, useIsSpeaking, useParticipantVoiceState, useParticipants, useSpeakingUsers, useThermalState, useVoiceState, } from "./events.js";
2
+ export { useActivityLayoutMode, useDiscordChannel, useDiscordDiagnostics, useDiscordGuild, useDiscordLocale, useDiscordUser, useOrientation, useIsSpeaking, useParticipantVoiceState, useParticipants, useSpeakingUsers, useThermalState, useVoiceState, useChannelMembers, useCurrentGuildMember, useDiscordEntitlements, channelTypeName, } from "./events.js";
3
3
  export { LUDICORD_SAFE_AREA_CSS, LUDICORD_SAFE_AREA_STYLE_ID, getLudicordSafeAreaInsets, installLudicordSafeAreaVariables, useLudicordSafeArea, } from "./safe-area.js";
4
4
  export type { ActivityInstanceState, LudicordDiscordStatus, DiscordRuntimeOptions, DiscordRuntimeSnapshot, DiscordSdkLike, } from "./runtime.js";
5
- export type { LudicordDiscordChannel, LudicordDiscordEventSnapshot, LudicordDiscordGuild, LudicordDiscordUser, LudicordParticipant, LudicordVoiceState, } from "./events.js";
5
+ export type { LudicordDiscordChannel, LudicordDiscordEventSnapshot, LudicordDiscordGuild, LudicordDiscordUser, LudicordParticipant, LudicordVoiceState, LudicordGuildMember, } from "./events.js";
6
6
  export type { LudicordSafeAreaInsets } from "./safe-area.js";
7
+ export { useDiscordCommands, useDiscordGuildMembers } from "./data.js";
8
+ export type { LudicordDiscordCommand } from "./data.js";
7
9
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export { initializeDiscord, initializeDiscordFromEnvironment, useActivityInstance, useDiscord, } from "./runtime.js";
2
- export { useActivityLayoutMode, useDiscordChannel, useDiscordDiagnostics, useDiscordGuild, useDiscordLocale, useDiscordUser, useOrientation, useIsSpeaking, useParticipantVoiceState, useParticipants, useSpeakingUsers, useThermalState, useVoiceState, } from "./events.js";
2
+ export { useActivityLayoutMode, useDiscordChannel, useDiscordDiagnostics, useDiscordGuild, useDiscordLocale, useDiscordUser, useOrientation, useIsSpeaking, useParticipantVoiceState, useParticipants, useSpeakingUsers, useThermalState, useVoiceState, useChannelMembers, useCurrentGuildMember, useDiscordEntitlements, channelTypeName, } from "./events.js";
3
3
  export { LUDICORD_SAFE_AREA_CSS, LUDICORD_SAFE_AREA_STYLE_ID, getLudicordSafeAreaInsets, installLudicordSafeAreaVariables, useLudicordSafeArea, } from "./safe-area.js";
4
+ export { useDiscordCommands, useDiscordGuildMembers } from "./data.js";
4
5
  //# sourceMappingURL=index.js.map
@@ -2,8 +2,8 @@ export type LudicordDiscordStatus = "idle" | "connecting" | "ready" | "outside-d
2
2
  export interface DiscordSdkLike {
3
3
  ready(): Promise<void>;
4
4
  readonly commands?: Readonly<Record<string, unknown>>;
5
- subscribe?(event: string, listener: (payload: unknown) => void): Promise<void> | void;
6
- unsubscribe?(event: string, listener: (payload: unknown) => void): Promise<void> | void;
5
+ subscribe?(event: string, listener: (payload: unknown) => void, args?: Readonly<Record<string, unknown>>): Promise<void> | void;
6
+ unsubscribe?(event: string, listener: (payload: unknown) => void, args?: Readonly<Record<string, unknown>>): Promise<void> | void;
7
7
  readonly instanceId?: string | null;
8
8
  readonly channelId?: string | null;
9
9
  readonly guildId?: string | null;