@homeflare/alchemy 0.30.0 → 0.31.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.
Files changed (35) hide show
  1. package/README.md +22 -0
  2. package/dist/discord/application-command.d.ts +52 -0
  3. package/dist/discord/application-command.d.ts.map +1 -0
  4. package/dist/discord/command-form.d.ts +62 -0
  5. package/dist/discord/command-form.d.ts.map +1 -0
  6. package/dist/discord/credentials.d.ts +35 -0
  7. package/dist/discord/credentials.d.ts.map +1 -0
  8. package/dist/discord/fake-discord.d.ts +44 -0
  9. package/dist/discord/fake-discord.d.ts.map +1 -0
  10. package/dist/discord/guild-application-command.d.ts +53 -0
  11. package/dist/discord/guild-application-command.d.ts.map +1 -0
  12. package/dist/discord/index.d.ts +12 -0
  13. package/dist/discord/index.d.ts.map +1 -0
  14. package/dist/discord/index.js +193 -0
  15. package/dist/discord/index.js.map +15 -0
  16. package/dist/discord/providers.d.ts +15 -0
  17. package/dist/discord/providers.d.ts.map +1 -0
  18. package/dist/discord/resource.d.ts +75 -0
  19. package/dist/discord/resource.d.ts.map +1 -0
  20. package/docs/credentials.md +9 -0
  21. package/docs/discord.md +129 -0
  22. package/docs/upstream-conformance.md +17 -1
  23. package/package.json +5 -1
  24. package/src/discord/application-command.test.ts +103 -0
  25. package/src/discord/application-command.ts +109 -0
  26. package/src/discord/command-form.test.ts +144 -0
  27. package/src/discord/command-form.ts +133 -0
  28. package/src/discord/credentials.ts +36 -0
  29. package/src/discord/fake-discord.ts +70 -0
  30. package/src/discord/guild-application-command.test.ts +215 -0
  31. package/src/discord/guild-application-command.ts +129 -0
  32. package/src/discord/index.ts +31 -0
  33. package/src/discord/providers.ts +18 -0
  34. package/src/discord/resource.ts +164 -0
  35. package/src/discord/retry.test.ts +74 -0
@@ -0,0 +1,164 @@
1
+ /**
2
+ * One shape for every Discord application-command object — global and guild-scoped alike.
3
+ *
4
+ * ⛔ THE ALTERNATIVE IS COPYING THE SAME READ/RECONCILE/DELETE PER RESOURCE. `application-command.ts`
5
+ * and `guild-application-command.ts` differ only in which distilled operations they call and
6
+ * whether `guild_id` is part of identity — so the read/diff/reconcile/delete flow lives here
7
+ * once, mirroring `../netbox/resource.ts`'s `netboxOperations`/`netboxHandlers` split.
8
+ *
9
+ * ★ UNLIKE NETBOX, THIS FOLLOWS UPSTREAM'S `Snippet.ts` READ/RECONCILE SHAPE EXACTLY (S7–S9), NOT
10
+ * netbox's "adopt silently" gap (H1). Discord commands carry no ownership marker of any kind —
11
+ * no tags, no metadata field a bot could stamp — so this is precisely the "marker-less API" S8
12
+ * describes, and `Snippet.ts@v2.0.0-beta.79#read` is the cited reference: an existing match is
13
+ * `Unowned(attrs)` on a cold read (no persisted `output`), and plain attributes on a warm read
14
+ * (persisted `output` says we already made or adopted this exact command). `adopt(true)` (H5),
15
+ * piped onto each resource by the constructors in the two resource files, is what turns that
16
+ * `Unowned` into a silent one-time takeover instead of an `OwnedBySomeoneElse` refusal.
17
+ *
18
+ * ★ RECONCILE IS ONE UPSERT CALL, LIKE `Snippet.ts`'s `putSnippet`. Discord's own docs for both
19
+ * Create Global/Guild Application Command say a command with the same name (and type) as an
20
+ * existing one OVERWRITES it — the create endpoint is a true upsert, not a create-only call that
21
+ * 409s on a name collision. ⚠️ REASONED NOT MEASURED (no token available to this task; see
22
+ * `docs/discord.md`): this is Discord's documented behaviour, unchanged across API v10, but it
23
+ * has not been exercised against the real API by this change. One call therefore converges
24
+ * greenfield create, routine update AND adoption alike — there is no separate PATCH path, and
25
+ * S10's "zero write calls when there is no drift" is still honoured because `reconcile` skips
26
+ * the call entirely when `spec.matches` already holds.
27
+ *
28
+ * ⚠️ `list` ANSWERS EMPTY, ON PURPOSE, EVEN THOUGH THE DISTILLED LIST OPERATIONS EXIST. A bot's
29
+ * guild command set is exactly what `hf-discord-halibut.service` bulk-overwrites at every
30
+ * restart (see `docs/discord.md#halibut`); a `nuke` that enumerated and swept every live command
31
+ * would fight that ownership, not just this resource's own declarations. Adoption stays
32
+ * explicit, the same reasoning netbox's `list` gives for a shared instance predating the kit.
33
+ */
34
+ import { Unowned } from 'alchemy/AdoptPolicy';
35
+ import { isResolved } from 'alchemy/Diff';
36
+ import type { Input } from 'alchemy/Input';
37
+ import type { DiscordOpContext } from '@distilled.cloud/discord/Protocol';
38
+ import * as Effect from 'effect/Effect';
39
+ import type * as HttpClient from 'effect/unstable/http/HttpClient';
40
+ import { CredentialsFromEnv } from './credentials.ts';
41
+
42
+ /**
43
+ * What every stack must still provide after `discordHandlers` bakes in `CredentialsFromEnv`
44
+ * (below): the transport. `DiscordOpContext` is `Credentials | HttpClient.HttpClient`, so once
45
+ * `Credentials` is supplied, `HttpClient.HttpClient` is what remains — mirroring
46
+ * `../netbox/resource.ts#NetboxRequirements`.
47
+ */
48
+ export type DiscordRequirements = HttpClient.HttpClient;
49
+
50
+ /** Every Discord command resource's identity key, regardless of scope. */
51
+ export interface DiscordCommandIdentity {
52
+ readonly name: string;
53
+ }
54
+
55
+ /**
56
+ * One Discord command object's distilled calls. `Live` is whatever the SDK decodes
57
+ * (`ApplicationCommandResponse`); `E` is left to each resource file to declare, so a call site's
58
+ * precise error union (in practice always `DiscordOpError` — see `protocol.ts` — because every
59
+ * generated Discord operation shares one error channel) flows straight through.
60
+ */
61
+ export type DiscordSpec<
62
+ Props extends DiscordCommandIdentity,
63
+ Live,
64
+ Attributes extends object,
65
+ E,
66
+ > = {
67
+ /** Locate the live command by its declared name within this spec's scope (app, or app+guild). */
68
+ readonly fetchByName: (props: Props) => Effect.Effect<Live | undefined, E, DiscordOpContext>;
69
+ readonly attributes: (live: Live) => Attributes;
70
+ readonly matches: (attributes: Attributes, props: Props) => boolean;
71
+ readonly upsertBody: (props: Props) => Record<string, unknown>;
72
+ /** POST create-or-overwrite — see the upsert note above. */
73
+ readonly upsert: (
74
+ props: Props,
75
+ body: Record<string, unknown>,
76
+ ) => Effect.Effect<Live, E, DiscordOpContext>;
77
+ readonly destroy: (props: Props, live: Live) => Effect.Effect<unknown, E, DiscordOpContext>;
78
+ /** For error messages and test descriptions. */
79
+ readonly describe: (props: Props) => string;
80
+ };
81
+
82
+ export const discordOperations = <
83
+ Props extends DiscordCommandIdentity,
84
+ Live,
85
+ Attributes extends object,
86
+ E,
87
+ >(
88
+ spec: DiscordSpec<Props, Live, Attributes, E>,
89
+ ) => ({
90
+ read: ({ olds, output }: { olds: Props; output: Attributes | undefined }) =>
91
+ Effect.gen(function* () {
92
+ const live = yield* spec.fetchByName(olds);
93
+ if (live === undefined) return undefined;
94
+ const attrs = spec.attributes(live);
95
+ // Warm read: a prior apply already created or adopted this exact command — ours.
96
+ if (output !== undefined) return attrs;
97
+ // Cold read (fresh store, or state lost): no ownership marker exists on this vendor,
98
+ // so any match is `Unowned` until `adopt(true)` (or `--adopt`) says otherwise (S7, S8).
99
+ return Unowned(attrs);
100
+ }),
101
+
102
+ diff: (news: Input<Props>, output: Attributes | undefined) =>
103
+ Effect.gen(function* () {
104
+ if (output === undefined || !isResolved(news)) return undefined;
105
+ const live = yield* spec.fetchByName(news);
106
+ if (live === undefined) return { action: 'update' } as const;
107
+ return spec.matches(spec.attributes(live), news)
108
+ ? ({ action: 'noop' } as const)
109
+ : ({ action: 'update' } as const);
110
+ }),
111
+
112
+ reconcile: (news: Props) =>
113
+ Effect.gen(function* () {
114
+ const before = yield* spec.fetchByName(news);
115
+ if (before !== undefined && spec.matches(spec.attributes(before), news)) {
116
+ // Already exactly what is declared — S10: no write.
117
+ return spec.attributes(before);
118
+ }
119
+ const body = spec.upsertBody(news);
120
+ const after = yield* spec.upsert(news, body);
121
+ return spec.attributes(after);
122
+ }),
123
+
124
+ // ⚠️ GAP, NOT SOLVED: a TOCTOU race between the fetch above and the delete call below could
125
+ // see Discord answer 404 on a command that vanished between the two — S11 asks that race to
126
+ // be treated as success, `catchTag('NotFound', …)`. The SDK's declared error type for every
127
+ // operation does not include `NotFound` (see `docs/discord.md#sdk-gaps` — measured, not
128
+ // assumed), so there is no typed tag to catch here without an unsafe cast. Left unhandled.
129
+ destroy: (olds: Props) =>
130
+ Effect.gen(function* () {
131
+ const live = yield* spec.fetchByName(olds);
132
+ if (live === undefined) return;
133
+ yield* spec.destroy(olds, live);
134
+ }),
135
+ });
136
+
137
+ /**
138
+ * The four provider handlers for a spec'd Discord command, wired once.
139
+ *
140
+ * ★ CREDENTIALS ARE PROVIDED HERE, ONCE. `CredentialsFromEnv` resolves `DISCORD_BOT_TOKEN` /
141
+ * `DISCORD_TOKEN` on the calling fiber per request (credentials.ts), so this closure keeps that
142
+ * laziness — nothing is captured at module load.
143
+ */
144
+ export const discordHandlers = <
145
+ Props extends DiscordCommandIdentity,
146
+ Live,
147
+ Attributes extends object,
148
+ E,
149
+ >(
150
+ spec: DiscordSpec<Props, Live, Attributes, E>,
151
+ ) => {
152
+ const ops = discordOperations(spec);
153
+ const withCredentials = <A>(effect: Effect.Effect<A, E, DiscordOpContext>) =>
154
+ Effect.provide(effect, CredentialsFromEnv);
155
+ return {
156
+ list: () => Effect.succeed([]),
157
+ read: ({ olds, output }: { olds: Props; output: Attributes | undefined }) =>
158
+ withCredentials(ops.read({ olds, output })),
159
+ diff: ({ news, output }: { news: Input<Props>; output: Attributes | undefined }) =>
160
+ withCredentials(ops.diff(news, output)),
161
+ reconcile: ({ news }: { news: Props }) => withCredentials(ops.reconcile(news)),
162
+ delete: ({ olds }: { olds: Props }) => withCredentials(ops.destroy(olds)),
163
+ };
164
+ };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Discord's 429 handling — proving the SDK's OWN default retry policy (`@distilled.cloud/core`'s
3
+ * `makeDefault`, threaded through every operation via `retry: Retry.Retry` — see `resource.ts`'s
4
+ * header note and `docs/discord.md#rate-limits`), not a house re-implementation. This file exists
5
+ * because "respect Discord's rate limits with a bounded retry" is a requirement this task must
6
+ * satisfy, and the honest way to satisfy it here is to prove the SDK already does — nothing in
7
+ * `resource.ts` installs a `Discord.Retry.policy` of its own, so if this test ever failed to
8
+ * retry, or failed to STOP retrying, there would be nothing in this package to fix; the fix would
9
+ * be in `@distilled.cloud/discord`.
10
+ *
11
+ * ⛔ A TEST THAT CANNOT FAIL PROVES NOTHING. Both cases below assert on the fake's own call count
12
+ * (`fake.seen.length`), not just on the eventual Effect outcome — a policy that retried once,
13
+ * or one that retried forever, would each still "eventually succeed" or "eventually fail" on
14
+ * SOME outcome; the call count is what makes "bounded" a real, checkable claim rather than an
15
+ * assumption the test's own passing would not have caught.
16
+ */
17
+ import { describe, expect, test } from 'bun:test';
18
+ import * as Effect from 'effect/Effect';
19
+ import { spec } from './guild-application-command.ts';
20
+ import type { GuildApplicationCommandProps } from './guild-application-command.ts';
21
+ import { fakeDiscord, fakeDiscordLayer, fakeRateLimited } from './fake-discord.ts';
22
+
23
+ const APP = '111111111111111111';
24
+ const GUILD = '222222222222222222';
25
+ const CMD_PATH = `/applications/${APP}/guilds/${GUILD}/commands`;
26
+ const PROPS: GuildApplicationCommandProps = { applicationId: APP, guildId: GUILD, name: 'ping' };
27
+
28
+ const liveCommand = () => ({
29
+ application_id: APP,
30
+ default_member_permissions: null,
31
+ description: '',
32
+ guild_id: GUILD,
33
+ id: '999',
34
+ name: 'ping',
35
+ nsfw: false,
36
+ type: 1,
37
+ version: '1',
38
+ });
39
+
40
+ describe('the SDK default Retry policy on a 429', () => {
41
+ test('two 429s (Retry-After: 0) then a 200 — retried, and it converges', async () => {
42
+ const fake = fakeDiscord((method, url, _body, callNumber) => {
43
+ if (method !== 'GET' || url.pathname !== CMD_PATH) return new Response(null, { status: 500 });
44
+ return callNumber <= 2 ? fakeRateLimited(0) : Response.json([liveCommand()]);
45
+ });
46
+ const live = await Effect.runPromise(
47
+ spec.fetchByName(PROPS).pipe(Effect.provide(fakeDiscordLayer(fake.fetch))),
48
+ );
49
+ expect(live?.id).toBe('999');
50
+ expect(fake.seen).toHaveLength(3);
51
+ }, 15_000);
52
+
53
+ /**
54
+ * ★ THE BOUND ITSELF. `@distilled.cloud/core`'s `makeDefault` caps this at `Schedule.recurs(8)`
55
+ * — 8 retries, 9 attempts total — regardless of how long the server keeps answering 429. A
56
+ * server that never recovers must still let the caller find out, in bounded time, rather than
57
+ * parking the fiber forever; that is the literal meaning of "bounded retry".
58
+ */
59
+ test('429 forever is a bounded number of attempts, then a typed failure — never an infinite loop', async () => {
60
+ const fake = fakeDiscord((method, url) =>
61
+ method === 'GET' && url.pathname === CMD_PATH
62
+ ? fakeRateLimited(0)
63
+ : new Response(null, { status: 500 }),
64
+ );
65
+ const failure = await Effect.runPromise(
66
+ Effect.flip(spec.fetchByName(PROPS).pipe(Effect.provide(fakeDiscordLayer(fake.fetch)))),
67
+ );
68
+ expect(failure._tag).toBe('TooManyRequests');
69
+ // 1 initial attempt + at most 8 retries. Strictly greater than 1 proves a retry happened at
70
+ // all; at most 9 proves it stopped rather than continuing past the documented bound.
71
+ expect(fake.seen.length).toBeGreaterThan(1);
72
+ expect(fake.seen.length).toBeLessThanOrEqual(9);
73
+ }, 15_000);
74
+ });