Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,191 @@
# OpenSpec Change: enterprise-slack-client
- **Change ID**: enterprise-slack-client
- **Package**: `@suaveplan/slack-client`
- **Category**: universal
- **Target path**: `universal/social/slack-client`
- **Status**: IN PROGRESS
- **Date**: 2026-04-24
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/slack-client.md`
---
## Summary
Deliver `@suaveplan/slack-client` on the genesis branch from scratch at enterprise quality. The package provides a generic Slack API client: Web API method wrappers for messaging (`chat.postMessage`, `chat.update`, `chat.delete`), channel management (`conversations.*`), user info (`users.*`), file uploads, Block Kit message builder, Incoming Webhooks, Event subscription parsing with signature verification, slash-command payload parsing, interactive component payload handling, and a `SlackClient` facade. Injectable fetch and crypto; no Slack SDK dependency. Genesis adds structured errors, Zod schemas, OTel instrumentation, retry with circuit breaker, and `AbortSignal` cancellation.
---
## Current-state audit (genesis)
The package does not exist on genesis yet — this is a fresh build.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/error` (`workspace:^`) | `SlackError`; `SLACK.*` error codes |
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock` |
| `@suaveplan/retry` (`workspace:^`) | Retry + circuit breaker for API calls |
| `@suaveplan/crypto` (`workspace:^`) | HMAC-SHA256 request signature verification |
| `zod` (`catalog:forms`) | Schema validation |
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters |
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check` (all `catalog:testing`).
---
## Public API surface
### `SlackClient`
```ts
class SlackClient {
constructor(options: SlackClientOptions)
// Messaging
postMessage(options: PostMessageOptions): Promise<SlackMessageResponse>
updateMessage(options: UpdateMessageOptions): Promise<SlackMessageResponse>
deleteMessage(channel: string, ts: string): Promise<void>
// Channels
listConversations(options?: ListConversationsOptions): AsyncGenerator<SlackChannel>
getConversationInfo(channel: string): Promise<SlackChannel>
// Users
getUserInfo(userId: string): Promise<SlackUser>
getUserByEmail(email: string): Promise<SlackUser>
// Files
uploadFile(options: FileUploadOptions): Promise<SlackFile>
// Webhooks
postToWebhook(url: string, payload: WebhookPayload): Promise<void>
}
interface SlackClientOptions {
token: string
signingSecret?: string // for event verification
retryOptions?: RetryOptions
fetch?: typeof globalThis.fetch
clock?: Clock
logger?: LoggerLike
}
```
### Block Kit builder
```ts
function createMessage(text: string): MessageBuilder
interface MessageBuilder {
section(text: string): MessageBuilder
divider(): MessageBuilder
image(url: string, altText: string): MessageBuilder
actions(...elements: ActionElement[]): MessageBuilder
context(...elements: ContextElement[]): MessageBuilder
build(): SlackBlocks
}
```
### Event handling
```ts
function verifySlackSignature(
body: string,
timestamp: string,
signature: string,
signingSecret: string,
options?: { maxAgeSeconds?: number; clock?: Clock }
): boolean
function parseSlackEvent(body: unknown): SlackEvent
function parseSlashCommand(body: unknown): SlashCommand
function parseInteractivePayload(body: unknown): InteractivePayload
```
### Error codes
```ts
type SlackErrorCode =
| 'SLACK_AUTH_FAILED'
| 'SLACK_API_ERROR'
| 'SLACK_RATE_LIMITED'
| 'SLACK_SIGNATURE_INVALID'
| 'SLACK_CHANNEL_NOT_FOUND'
| 'SLACK_USER_NOT_FOUND'
| 'SLACK_ABORTED'
```
---
## Genesis additions
1. **`SlackError`** extends `SuaveplanError` with seven stable codes.
2. **Zod schemas** for `PostMessageOptions`, `SlackEvent`, `SlashCommand`, `InteractivePayload`, `SlackChannel`, `SlackUser`, `SlackFile`.
3. **Rate-limit handling** — respects `Retry-After` header from Slack 429 responses; integrates with `@suaveplan/retry`.
4. **Circuit breaker** — wraps all API calls via `@suaveplan/retry` circuit breaker; opens after 5 consecutive failures.
5. **OTel instrumentation** — span `slack.api_call` with attribute `slack.method`; counter `slack.api_total`; histogram `slack.api_duration_ms`.
6. **Property-based tests** — Block Kit builder produces valid JSON structures for arbitrary sequences of builder calls.
---
## File layout
```text
universal/social/slack-client/
package.json
tsconfig.json
vitest.config.ts
src/
index.ts
error-codes.ts
constants/
index.ts
types/
common.ts
common.md
core/
slack-client/
slack-client.ts
slack-client.md
slack-client.types.ts
slack-client.test.ts
index.ts
api-caller/
api-caller.ts
api-caller.md
api-caller.test.ts
index.ts
blocks/
message-builder/
message-builder.ts
message-builder.md
message-builder.test.ts
index.ts
events/
event-parser/
event-parser.ts
event-parser.md
event-parser.test.ts
index.ts
signature-verifier/
signature-verifier.ts
signature-verifier.md
signature-verifier.test.ts
index.ts
__benchmarks__/
slack-client.bench.ts
tests/
integration.test.ts
property.test.ts
```
---
## Impact
**Downstream consumers**: `@suaveplan/message-bridge`, `@suaveplan/notification-channel`.
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/retry`, `@suaveplan/crypto`.

View File

@@ -0,0 +1,69 @@
# Tasks: enterprise-slack-client
**Change ID**: enterprise-slack-client
**Package**: `@suaveplan/slack-client`
**Target path**: `universal/social/slack-client`
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/retry`, `@suaveplan/crypto`
---
## 0. Pre-flight (non-negotiable)
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
## 1. Scaffold
- [ ] Create `universal/social/slack-client/` with `src/`, `tests/`, `src/__benchmarks__/` and all feature subdirectories per the layout in `proposal.md`.
- [ ] Write `package.json` at version `0.1.0` with `"type": "module"`, `"sideEffects": false`, correct `exports` map, `dependencies`, and `devDependencies`.
- [ ] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
- [ ] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config`.
- [ ] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check` scripts.
---
## 2. Types + errors
- [ ] `src/types/common.ts` — `SlackClientOptions`, `PostMessageOptions`, `UpdateMessageOptions`, `ListConversationsOptions`, `FileUploadOptions`, `WebhookPayload`, `SlackMessageResponse`, `SlackChannel`, `SlackUser`, `SlackFile`, `SlackEvent`, `SlashCommand`, `InteractivePayload`, `SlackBlocks`, `ActionElement`, `ContextElement`.
- [ ] `src/types/common.md` (≥200 words, both examples, API reference).
- [ ] `src/error-codes.ts` — `SlackErrorCode` (7 codes), metadata, register, eager call.
- [ ] `src/types/schemas.ts` + `schemas.md` — Zod schemas.
---
## 3. Core modules
- [ ] **`src/core/api-caller/`** — `ApiCaller`: wraps `fetch` calls to `https://slack.com/api/`; sets `Authorization: Bearer` header; parses JSON response; throws `SLACK_API_ERROR` on `ok:false`; throws `SLACK_RATE_LIMITED` on 429 and includes `retry_after`; wraps calls with `@suaveplan/retry` circuit breaker. Tests: success, api error (ok:false), rate-limit (429), circuit breaker opens after 5 failures.
- [ ] **`src/core/slack-client/`** — `SlackClient`: implements all public methods via `ApiCaller`. `listConversations` uses cursor pagination (returns `AsyncGenerator`). Tests: `postMessage` happy path, `updateMessage`, `deleteMessage`, `getUserByEmail`, `uploadFile`, `postToWebhook`.
- [ ] **`src/blocks/message-builder/`** — `createMessage(text)`: fluent builder; `build()` returns `SlackBlocks`. Tests: section, divider, image, actions, context; chaining; empty message.
- [ ] **`src/events/signature-verifier/`** — `verifySlackSignature(body, timestamp, signature, signingSecret, options)`: HMAC-SHA256 via `@suaveplan/crypto`; constant-time comparison; reject if `|now - ts| > maxAgeSeconds` (default 300). Tests: valid, tampered body, expired, missing timestamp.
- [ ] **`src/events/event-parser/`** — `parseSlackEvent`, `parseSlashCommand`, `parseInteractivePayload`: Zod validation. Tests: each payload type, invalid payload throws.
---
## 4. OTel instrumentation
- [ ] Span `slack.api_call` with attribute `slack.method` on every API call; counter `slack.api_total`; histogram `slack.api_duration_ms`.
---
## 5. Property-based tests (`tests/property.test.ts`)
- [ ] Block Kit builder: for arbitrary sequences of `section`/`divider`/`image` calls, `build()` always returns a valid `SlackBlocks` object with correct `type` fields.
---
## 6. Benchmarks (`src/__benchmarks__/slack-client.bench.ts`)
- [ ] `createMessage` builder chain (10 sections) 100 000 times.
---
## 7. Docs + verify
- [ ] One `.md` per implementation file (≥200 words, both examples, API reference). Root `README.md`.
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/slack-client` — green.
- [ ] `bunx turbo test:coverage --filter=@suaveplan/slack-client` — 100%.
- [ ] `bun scripts/publish.ts --package @suaveplan/slack-client`.
- [ ] Archive: `openspec/archive/2026-04-24-enterprise-slack-client/`.