@quatronic/sdk 0.6.1-rc.4 → 0.7.0-rc.11

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 (46) hide show
  1. package/README.md +26 -0
  2. package/dist/cli/legacy/qdc-sourcemaps.js +237 -0
  3. package/dist/cli/legacy/qdc-test-report.js +200 -0
  4. package/dist/cli/skills-postinstall.js +603 -0
  5. package/dist/cli/skills.js +499 -0
  6. package/dist/cli/sourcemaps.js +9 -9
  7. package/dist/cli/test-report.js +2 -2
  8. package/dist/next/auth/index.js.map +1 -1
  9. package/dist/next/config/index.js +1 -1
  10. package/dist/next/config/index.js.map +1 -1
  11. package/migrations/no-raw-fetch/codemod.mjs +97 -0
  12. package/migrations/no-raw-fetch/instructions.md +68 -0
  13. package/migrations/no-raw-fetch/meta.json +6 -0
  14. package/package.json +17 -6
  15. package/postinstall.mjs +9 -0
  16. package/skills/.gitattributes +1 -0
  17. package/skills/catalog.json +24 -0
  18. package/skills/qore-add-api-route/SKILL.md +58 -0
  19. package/skills/qore-add-connection/SKILL.next.md +149 -0
  20. package/skills/qore-add-connection/SKILL.node.md +160 -0
  21. package/skills/qore-add-db-table/SKILL.md +88 -0
  22. package/skills/qore-add-db-table/references/cross-module-reference.md +74 -0
  23. package/skills/qore-add-feature/SKILL.md +77 -0
  24. package/skills/qore-add-integration/SKILL.next.md +217 -0
  25. package/skills/qore-add-integration/SKILL.node.md +216 -0
  26. package/skills/qore-add-page/SKILL.md +53 -0
  27. package/skills/qore-author-skill/SKILL.md +136 -0
  28. package/skills/qore-debug-issue/SKILL.md +48 -0
  29. package/skills/qore-enable-auth-method/SKILL.md +91 -0
  30. package/skills/qore-observability/SKILL.md +89 -0
  31. package/skills/qore-observability/references/errors.md +87 -0
  32. package/skills/qore-observability/references/logs.md +69 -0
  33. package/skills/qore-observability/references/tracing.md +58 -0
  34. package/skills/qore-recommended-tools/SKILL.md +58 -0
  35. package/skills/qore-secure-io/SKILL.md +174 -0
  36. package/skills/qore-ship-checklist/SKILL.md +80 -0
  37. package/skills/qore-translate-strings/SKILL.md +36 -0
  38. package/skills/qore-use-addons/SKILL.md +175 -0
  39. package/skills/qore-use-database/SKILL.md +222 -0
  40. package/skills/qore-use-design-system/SKILL.md +76 -0
  41. package/skills/qore-use-mail-domain/SKILL.next.md +67 -0
  42. package/skills/qore-use-mail-domain/SKILL.node.md +62 -0
  43. package/skills/qore-use-permissions/SKILL.md +116 -0
  44. package/skills/qore-verify-user/SKILL.md +56 -0
  45. package/dist/next/auth/migrations/0001_init.sql +0 -31
  46. package/dist/next/auth/migrations/0002_id_token.sql +0 -1
@@ -0,0 +1,160 @@
1
+ ---
2
+ name: qore-add-connection
3
+ description: Wire a module-to-module connection — declare its env, guard an incoming request with requireConnection, call out with connection().fetch, and fail-fast at startup with assertConnection. Use when this backend talks to another Quatronic module.
4
+ allowed-tools: Bash(pnpm:*), Edit, Read
5
+ ---
6
+
7
+ # Add a connection
8
+
9
+ A connection links two Quatronic modules. The portal injects the env on both
10
+ sides when the connection is wired (`CONN_<ALIAS>_URL`, `CONN_<ALIAS>_TOKEN` for
11
+ a service; `CONN_<ALIAS>_URI`/`_HOST`/… for a resource). `<ALIAS>` is the
12
+ provider slug uppercased, non-alphanumerics collapsed to `_`. The SDK reads only
13
+ this env — it never calls the portal at runtime.
14
+
15
+ > A single-module app has no connections. Only follow this once the portal shows
16
+ > a wired connection for this module (its env keys exist in the Secrets tab).
17
+
18
+ This module is a plain `node:http` service (no framework), so the provider side
19
+ needs one small adapter — step 4 covers it.
20
+
21
+ ## Kinds of connection
22
+
23
+ `connection(alias)` returns one handle with four methods — which one you call
24
+ depends on what the alias was wired to in the portal:
25
+
26
+ - **`.fetch(path, init?)`** — the alias is another **module** (a service
27
+ connection). This is module-to-module talking directly over the network via
28
+ its own API, authenticated with a shared-secret token in the
29
+ `X-QDC-Connection-Token` header. No addon involved.
30
+ - **`.postgres()` / `.redis()` / `.s3()`** — the alias is a **resource** (an
31
+ addon: Postgres, Redis, or object storage) this module was granted access
32
+ to. These return typed connection material (URI, host, credentials, …), not
33
+ an HTTP client — you pass it to your own DB/cache/S3 client.
34
+
35
+ `assertConnection(alias, kind)` takes the matching `kind` too: `"service"` for
36
+ `.fetch()`, `"postgres"`/`"redis"`/`"s3"` for the resource accessors.
37
+ `requireConnection` (step 4) is provider-side only — a resource connection has
38
+ no inbound side, so it's only ever used for service connections.
39
+
40
+ ## 1. Declare the connection's env (consumer side only)
41
+
42
+ **Only do this when THIS module calls out** via `.fetch()`/`.postgres()`/
43
+ `.redis()`/`.s3()` (steps 2-3). If this module is only the **provider** guarding
44
+ an inbound request (step 4), skip this step entirely — see the note there.
45
+
46
+ Add the keys to the schema in `src/config/env.ts` so a missing wire is a clear
47
+ startup error, not a mystery failure. For a service connection to `billing-api`
48
+ (alias `BILLING_API`):
49
+
50
+ ```ts
51
+ // inside `const schema = z.object({ ... })`
52
+ CONN_BILLING_API_URL: z.string().url(),
53
+ CONN_BILLING_API_TOKEN: z.string().min(1),
54
+ ```
55
+
56
+ ## 2. Fail-fast at startup
57
+
58
+ In `src/index.ts`, before `server.listen(...)`, assert every wire this module
59
+ declares:
60
+
61
+ ```ts
62
+ import { assertConnection } from "@quatronic/sdk/node/connections"
63
+
64
+ assertConnection("billing-api", "service") // reads process.env by default
65
+ ```
66
+
67
+ ## 3. Call out to the other module
68
+
69
+ ```ts
70
+ import { connection } from "@quatronic/sdk/node/connections"
71
+
72
+ const res = await connection("billing-api").fetch("/invoices", { method: "GET" })
73
+ // connection() reads process.env; the X-QDC-Connection-Token header is added
74
+ // from CONN_BILLING_API_TOKEN automatically. Default 10s timeout.
75
+ const invoices = await res.json()
76
+ ```
77
+
78
+ For a resource connection, use the typed accessor instead of `.fetch`:
79
+
80
+ ```ts
81
+ const { uri } = connection("main-db").postgres() // { uri, host?, port?, user?, password?, db? }
82
+ const { url } = connection("cache").redis()
83
+ const { endpoint, bucket, accessKey, secretKey } = connection("media").s3()
84
+ ```
85
+
86
+ ## 4. Guard an incoming connection request
87
+
88
+ When THIS module is the provider, protect the receiving handler.
89
+ **No `env.ts` schema entry needed for this** — unlike step 1, `requireConnection`
90
+ doesn't take or need an alias: it scans `process.env` for every `CONN_*_TOKEN`
91
+ key present and matches the incoming request's token against all of them, so
92
+ it works with whatever alias the portal happened to derive on the consumer's
93
+ side. Also note the portal never gives a provider its own `CONN_<ALIAS>_URL` —
94
+ only a consumer gets a `_URL` — so requiring `CONN_<ALIAS>_URL` in this
95
+ module's `env.ts` when it's provider-only will always fail (crash-loop) since
96
+ that key can never exist.
97
+
98
+ `requireConnection` reads a Web-standard `Headers` object — `node:http` gives
99
+ you a plain header map, so adapt it with `Headers` (already global in Node 18+):
100
+
101
+ ```ts
102
+ // src/index.ts (or a handler module it dispatches to)
103
+ import { requireConnection, ConnectionError } from "@quatronic/sdk/node/connections"
104
+ import type { IncomingMessage, ServerResponse } from "node:http"
105
+
106
+ function toWebHeaders(raw: IncomingMessage["headers"]): Headers {
107
+ const headers = new Headers()
108
+ for (const [key, value] of Object.entries(raw)) {
109
+ if (value === undefined) continue
110
+ headers.set(key, Array.isArray(value) ? value.join(", ") : value)
111
+ }
112
+ return headers
113
+ }
114
+
115
+ async function handleInbound(req: IncomingMessage, res: ServerResponse): Promise<void> {
116
+ try {
117
+ const alias = await requireConnection({ headers: toWebHeaders(req.headers) } as Request)
118
+ // ... handle the trusted request; `alias` tells you which consumer wired in
119
+ res.writeHead(200, { "content-type": "application/json" })
120
+ res.end(JSON.stringify({ ok: true, from: alias }))
121
+ } catch (e) {
122
+ if (e instanceof ConnectionError) {
123
+ res.writeHead(e.status, { "content-type": "application/json" })
124
+ res.end(JSON.stringify({ error: e.code }))
125
+ return
126
+ }
127
+ throw e
128
+ }
129
+ }
130
+ ```
131
+
132
+ `requireConnection` is `async` (it uses Web Crypto for a constant-time token
133
+ compare) — always `await` it. It throws `ConnectionError` with code `not_wired`
134
+ / `missing_token` / `invalid_token` (status 401).
135
+
136
+ ### Fail-fast that an inbound connection is wired (optional)
137
+
138
+ A provider-only module can assert at boot that *some* connection is wired to it.
139
+ Because the provider doesn't know its callers' aliases, `assertConnection` (step
140
+ 2, alias-specific) doesn't apply — use the alias-agnostic `assertInboundConnection`:
141
+
142
+ ```ts
143
+ // src/index.ts, before server.listen(...)
144
+ import { assertInboundConnection } from "@quatronic/sdk/node/connections"
145
+
146
+ assertInboundConnection() // throws not_wired (500) if no CONN_*_TOKEN is present
147
+ ```
148
+
149
+ Do **not** implement this by calling `requireConnection` with a tokenless
150
+ `Request`. `requireConnection` always logs a `qore.connection.rejected` /
151
+ `missing_token` warning before it throws, so a tokenless probe emits a
152
+ misleading rejection on **every healthy boot**. `assertInboundConnection` reads
153
+ the env directly and stays silent when a connection is wired.
154
+
155
+ ## 5. Ship it
156
+
157
+ Run `pnpm build` (type-checks and compiles) before a PR.
158
+
159
+ > A worked, non-wired reference lives at `src/examples/connection.example.ts`.
160
+ > The service is started by the SDK's Sentry register (`--import @quatronic/sdk/node/sentry/register`); don't change the start command.
@@ -0,0 +1,88 @@
1
+ ---
2
+ name: qore-add-db-table
3
+ description: Add a database table or column with Drizzle, including the migration. Use whenever a feature needs to persist new data, when a column is added to an existing table, and especially when a column will hold an id, slug or key of something that already exists somewhere (a user, an account, a spot, an order, a product) — the skill works out where that identifier comes from and records it. Use it even when the user only says "add a table", "store X per user" or "save which Y it belongs to". App tables live on the app schema; the SDK owns the auth schema.
4
+ allowed-tools: Bash(pnpm:*), Edit, Read, Glob, Grep
5
+ ---
6
+
7
+ # Add a DB table + migration
8
+
9
+ 1. Define the table in `src/db/schema.ts` on `appSchema = pgSchema("app")`
10
+ (the SDK owns the separate `auth` schema — never put app tables there):
11
+ ```ts
12
+ export const widgets = appSchema.table("widgets", {
13
+ id: uuid("id").primaryKey().defaultRandom(),
14
+ keycloakSub: text("keycloak_sub").notNull(),
15
+ name: text("name").notNull(),
16
+ createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
17
+ })
18
+ export type Widget = typeof widgets.$inferSelect
19
+ export type NewWidget = typeof widgets.$inferInsert
20
+ ```
21
+ 2. For every column that identifies something — an id, a slug, a key, "who",
22
+ "which" — work out where it comes from before you write it. See
23
+ [Columns that identify something](#columns-that-identify-something) below.
24
+ This is the step that is easy to skip and expensive to skip.
25
+ 3. Generate the migration:
26
+ ```
27
+ pnpm db:generate
28
+ ```
29
+ This writes `src/db/migrations/NNNN_*.sql` and updates `meta/`. **Commit both.**
30
+ 4. Do NOT hand-edit generated SQL or `src/db/migrations/meta/`. To change a
31
+ table, edit `schema.ts` and re-run `pnpm db:generate`. (A *custom* migration
32
+ you create yourself for a cross-module reference is different — see below.)
33
+ 5. Migrations apply automatically at boot: `src/instrumentation.ts` calls
34
+ `runAppMigrations` (defined in `src/lib/migrate.ts`) — there is no separate
35
+ migrate command.
36
+ 6. Run the full local check loop — `pnpm lint && pnpm typecheck && pnpm test:run
37
+ && pnpm build` — then /qore-ship-checklist before a PR. To wire the
38
+ table into a form and Server Action, see /qore-add-feature.
39
+
40
+ ## Columns that identify something
41
+
42
+ A column that holds an id, a slug or a key points at something, and that
43
+ something often lives outside this table. Postgres only knows about the link
44
+ when it is a foreign key inside this database. For every other case the
45
+ knowledge is in your head now and nowhere later: `qore db erd` cannot draw the
46
+ link, and the next developer cannot tell `account_id` from a random uuid.
47
+
48
+ The user will rarely tell you where it comes from — to them "a spot" is just a
49
+ spot. So look it up instead of guessing. Search for the *concept*, not only the
50
+ literal word: "strand" is `spots`, "melding" is `sightings`, "wie" or "gebruiker"
51
+ is the signed-in user. Three cases, checked in this order:
52
+
53
+ 1. **This database.** Grep this module's `src/db/schema.ts` for the table.
54
+ Found → a real foreign key: `uuid("spot_id").notNull().references(() => spots.id, { onDelete: "cascade" })`
55
+ (pick the delete rule the feature needs). This is the only case where Postgres
56
+ guards the link, so prefer it whenever the table is here.
57
+
58
+ 2. **The signed-in user.** "wie", "gebruiker", "account", "eigenaar", "created
59
+ by", "per user" — and no `accounts`/`users` table of our own anywhere in the
60
+ app → the identity is Keycloak's `sub`. Store it exactly as `user_profiles`
61
+ does: `keycloakSub: text("keycloak_sub").notNull()`, no foreign key (the IdP
62
+ owns it; tooling recognises this column by its name). Do not invent an
63
+ `account_id` uuid for this; there is no accounts table to point at.
64
+
65
+ 3. **Another module of this app.** The modules of an app are cloned side by side:
66
+ this module's siblings are the directories next to it, under the folder that
67
+ holds `qore.workspace.json`. Search them for the table or resource:
68
+ - Drizzle schemas: `*/src/db/schema.ts`
69
+ - plain SQL migrations: `*/src/db/migrations/*.sql`, `*/migrations/*.sql`
70
+ - API routes when a module has no database of its own: `*/src/api/routes.ts`,
71
+ `*/src/app/api/**/route.ts`
72
+ Also grep this module for `connection("<alias>")`: a value that arrives through
73
+ a connection is by definition from that module, and the alias names it.
74
+
75
+ Found → a **cross-module reference**: an ordinary column of the target's type
76
+ (uuid for an `id`, text for a slug) with the link declared next to it, so that
77
+ the database carries the knowledge. Follow
78
+ [references/cross-module-reference.md](references/cross-module-reference.md)
79
+ — it is a custom migration with one `COMMENT ON COLUMN`, not a foreign key,
80
+ because a foreign key cannot cross databases. Name the column after the
81
+ target's key (`spot_id` when the other module exposes ids, `spot_slug` when
82
+ its stable key is a slug).
83
+
84
+ When a name exists both here and in a sibling (both the frontend and the backend
85
+ have `sightings`), this module's own table wins unless the user clearly means the
86
+ other one; say which one you took. When none of the three cases applies and the
87
+ request does not say what the column identifies, ask one question and name the
88
+ candidates you found — do not pick one silently.
@@ -0,0 +1,74 @@
1
+ # Declaring a cross-module reference
2
+
3
+ A column that stores the id (or slug) of a row that lives in another module's
4
+ database cannot be a foreign key: Postgres cannot look into another database.
5
+ The link still has to be recorded somewhere the database itself carries, so that
6
+ `qore db erd` draws it, the next developer sees it, and it survives a rewrite of
7
+ the application code. That place is a comment on the column.
8
+
9
+ ## The comment
10
+
11
+ One line, starting with an arrow, then the module and the target:
12
+
13
+ ```
14
+ -> <module-slug>:<schema>.<table>.<column>
15
+ ```
16
+
17
+ - `<module-slug>` is the module as the portal knows it — the same name as the
18
+ connection alias (`connection("zeevonk-backend")` → `zeevonk-backend`) and as
19
+ the sibling directory in the workspace.
20
+ - When the other module has no database and the thing is an API resource, point
21
+ at the endpoint and the field instead:
22
+ `-> zeevonk-backend:GET /beaches .slug`
23
+ - Free text may follow the target, e.g. `(no FK: other database)`.
24
+
25
+ Tooling reads only the part up to the first space after the target; keep it
26
+ exact (`public.spots.id`, not `spots`).
27
+
28
+ ## Writing it: a custom migration
29
+
30
+ Drizzle cannot express column comments (there is no `.comment()` on a column and
31
+ `drizzle-kit generate` never emits `COMMENT ON`), so the comment goes into a
32
+ migration you write yourself. That is not the same as hand-editing generated
33
+ SQL: a custom migration is a separate journal entry that drizzle-kit creates for
34
+ you and never touches again, and `pnpm db:generate` stays clean afterwards (the
35
+ CI drift check keeps passing).
36
+
37
+ Order matters: the column must exist before the comment can be set, so generate
38
+ the schema migration first.
39
+
40
+ ```sh
41
+ pnpm db:generate # the column itself
42
+ pnpm db:generate --custom --name=favourite_spots_spot_id_ref
43
+ ```
44
+
45
+ The second command writes an empty `src/db/migrations/NNNN_favourite_spots_spot_id_ref.sql`
46
+ and registers it in `meta/_journal.json`. Put the comment in that file:
47
+
48
+ ```sql
49
+ COMMENT ON COLUMN "app"."favourite_spots"."spot_id" IS '-> zeevonk-backend:public.spots.id (no FK: other database)';
50
+ ```
51
+
52
+ Commit the SQL file together with `meta/`. Migrations run at boot in journal
53
+ order, so the comment lands right after the column.
54
+
55
+ In `schema.ts`, give the column a short comment with the same target, so a reader
56
+ of the code sees it without opening the migration:
57
+
58
+ ```ts
59
+ // `spot_id` is `public.spots.id` in zeevonk-backend; no FK across databases.
60
+ spotId: uuid("spot_id").notNull(),
61
+ ```
62
+
63
+ ## When the SDK provides `crossRef`
64
+
65
+ Check whether `@quatronic/sdk/next/db` exports `crossRef`
66
+ (`node_modules/@quatronic/sdk/dist/next/db/index.d.ts`). If it does, use it
67
+ instead of the custom migration:
68
+
69
+ ```ts
70
+ spotId: crossRef("spot_id", "zeevonk-backend", "public.spots.id").notNull(),
71
+ ```
72
+
73
+ It defines the same uuid column and the SDK writes the comment at boot, right
74
+ after the migrations. Until then, the custom migration above is the way.
@@ -0,0 +1,77 @@
1
+ ---
2
+ name: qore-add-feature
3
+ description: Add a vertical feature slice (schema, server queries/mutations, server action, components){{#if auth}} mirroring src/features/profile/{{/if}}. Use when adding app functionality that has its own data and forms.
4
+ allowed-tools: Bash(pnpm:*), Edit, Read
5
+ ---
6
+
7
+ {{#if auth}}> Gating access by role/permission? See /qore-use-permissions.{{#if auth=keycloak}} Added a role key? Run `qore roles sync` yourself, then ask before `qore roles use` (§3 there).{{/if}}
8
+
9
+
10
+ {{/if}}Import UI from `@/components/ui` (the house kit) — see the qore-use-design-system skill.
11
+
12
+ # Add a feature slice
13
+
14
+ A feature is a vertical slice: its own data access, server logic, and UI,
15
+ under `src/features/<name>/`:
16
+
17
+ ```
18
+ src/features/<name>/
19
+ components/ # feature-scoped React components
20
+ server/ # queries, mutations, server actions — this feature's data logic
21
+ hooks/ # feature-scoped React hooks
22
+ index.ts # the feature's ONLY public surface
23
+ ```
24
+
25
+ Not every feature needs all three subfolders — only create `components/`,
26
+ `server/`, or `hooks/` if the feature actually has that kind of code.
27
+ `index.ts` is required for every feature: other code (other features,
28
+ `src/app/**`, `src/components/**`, …) may only import a feature through its
29
+ `index.ts`, never by reaching into `components/`, `server/`, or `hooks/`
30
+ directly. This is enforced by `eslint-plugin-boundaries`
31
+ (`boundaries/no-private`, `allowUncles: false`) — see
32
+ `src/features/README.md` for the full rule set, including:
33
+
34
+ - `feature -> app` imports are forbidden (a feature must never import from
35
+ `src/app/**`).
36
+ - `shared -> feature` and `shared -> app` are forbidden too — `src/{components,hooks,lib,config,styles,i18n}`
37
+ must stay free of feature- and app-specific knowledge.
38
+ - Cross-feature access is only ever through the other feature's `index.ts`.
39
+
40
+ {{#if auth}}Mirror `src/features/profile/`:
41
+ {{else}}Create the slice under `src/features/<name>/` (this app starts without
42
+ feature slices — this layout is the convention):
43
+ {{/if}}
44
+
45
+ - `schema.ts` — zod schemas for the feature's inputs.
46
+ - `types.ts` — derived types + an action-state discriminated union
47
+ (`{ status: "idle" | "success" | "error", message?: string }`).
48
+ {{#if db}}- `server/queries.ts` — Drizzle reads.
49
+ - `server/mutations.ts` — Drizzle writes.
50
+ {{else}}- `server/` — data access for the feature (no database module is installed; talk to your data source here).
51
+ {{/if}}- `actions.ts` — `"use server"` entry points. {{#if auth}}Authenticate with
52
+ `getRequireAuth()` first, validate{{else}}Validate{{/if}} `FormData` with the zod schema via
53
+ `safeParse`, return the typed action-state union on failure, call a mutation,
54
+ then `revalidatePath(...)`. Server actions are traced automatically; let
55
+ unexpected failures throw.
56
+ - `components/` — client components driving the actions with `useActionState`.
57
+ - `index.ts` — re-export exactly what other code is allowed to use
58
+ (components, server actions, types — not raw queries/mutations unless
59
+ they're meant to be called directly).
60
+ - All user-facing strings go through next-intl (`useTranslations`), with keys
61
+ in BOTH `messages/nl.json` and `messages/en.json` — see
62
+ /qore-translate-strings. Make zod validation messages message keys
63
+ (e.g. `"profile.displayNameRequired"`) and resolve them at the display site
64
+ with a root `useTranslations()` translator{{#if auth}}, mirroring `profile/`{{/if}}.
65
+
66
+ {{#if db}}Add any new table to `src/db/schema.ts` on `appSchema = pgSchema("app")`, then
67
+ `pnpm db:generate` and commit the generated migration (see
68
+ /qore-add-db-table). {{/if}}Add a unit test next to the schema (`*.test.ts`) like
69
+ {{#if auth}}`profile/schema.test.ts`{{else}}`<feature>/schema.test.ts`{{/if}}.
70
+
71
+ Before you finish, walk the decision table in /qore-observability for each step of the feature.
72
+ Most steps need nothing; add only what answers a production question.
73
+
74
+ Finish with the full local check loop — `pnpm lint && pnpm typecheck &&
75
+ pnpm test:run && pnpm build` — then run /qore-ship-checklist before opening
76
+ a PR. Every feature needs a unit test for its schema/logic, and an integration
77
+ test (`*.integration.test.ts`) when its behaviour is in the database.
@@ -0,0 +1,217 @@
1
+ ---
2
+ name: qore-add-integration
3
+ description: Declare and call an external API (SAP, a vendor REST/OData/SOAP service) — declare it in src/config/integrations.ts with env-var names, add the keys to env.ts, call it with integration(alias).get/post; assertIntegrations warns at startup about unset keys. Use when this app talks to anything that is not another Quatronic module.
4
+ allowed-tools: Bash(pnpm:*), Edit, Read
5
+ ---
6
+
7
+ # Add an integration
8
+
9
+ An integration is an external system this app calls over HTTP: SAP, a vendor
10
+ REST or OData API, a SOAP endpoint, a partner's GraphQL. It is declared once in
11
+ `src/config/integrations.ts`, and that declaration is what the portal reads to
12
+ show the app's Integrations tab — which systems the app talks to, under which
13
+ env keys, with a Probe button per environment. The values (base URL, credentials)
14
+ are never in code: they live in the portal's Secrets tab and reach the app as
15
+ env, exactly like every other secret.
16
+
17
+ **Integration vs connection.** A *connection* (`/qore-add-connection`) is
18
+ another Quatronic module or a resource the portal wired for you — its `CONN_*`
19
+ env is injected by the platform. An *integration* is anything outside the
20
+ platform; you name the env keys, and the portal only knows about them because
21
+ this file says so. If the other end is a Quatronic module, stop here and use the
22
+ connection skill.
23
+
24
+ ## Auth kinds
25
+
26
+ | `auth.kind` | Fields (env key names unless noted) | Header sent |
27
+ |---|---|---|
28
+ | `none` | — | nothing |
29
+ | `api_key_header` | `header` (a literal header name), `apiKey` | `<header>: <value>` |
30
+ | `bearer_static` | `token` | `Authorization: Bearer …` |
31
+ | `basic` | `username`, `password` | `Authorization: Basic …` |
32
+ | `oauth2_client_credentials` | `tokenUrl`, `clientId`, `clientSecret`, optional `scope`, `audience`, `credentialsIn` (`"basic"` literal default, or `"body"`) | `Authorization: Bearer …` from a cached client-credentials token |
33
+
34
+ The SDK fetches and caches the OAuth2 token for you (refreshed 30 s before it
35
+ expires, one in-flight request per token URL). A failed token call throws
36
+ `IntegrationError` `token_failed` with the status only — never the response body.
37
+
38
+ ## 1. Declare it in `src/config/integrations.ts`
39
+
40
+ ```ts
41
+ import { createIntegrationClient, defineIntegrations } from "@quatronic/sdk/next/integrations"
42
+
43
+ export const integrations = defineIntegrations({
44
+ sap: {
45
+ label: "SAP S/4HANA Cloud",
46
+ protocol: "odata", // rest | odata | soap | graphql — a label for the portal, nothing else
47
+ baseUrl: "SAP_BASE_URL",
48
+ auth: {
49
+ kind: "oauth2_client_credentials",
50
+ tokenUrl: "SAP_TOKEN_URL",
51
+ clientId: "SAP_CLIENT_ID",
52
+ clientSecret: "SAP_CLIENT_SECRET",
53
+ },
54
+ config: {
55
+ companyCode: "SAP_COMPANY_CODE",
56
+ timeoutMs: { key: "SAP_TIMEOUT_MS", optional: true, default: 10_000 },
57
+ },
58
+ },
59
+ })
60
+
61
+ export const integration = createIntegrationClient(integrations)
62
+ ```
63
+
64
+ Rules for the keys:
65
+
66
+ - Every value is an **env var name**, upper snake case, prefixed with the alias:
67
+ `<ALIAS>_BASE_URL`, `<ALIAS>_CLIENT_SECRET`, `<ALIAS>_COMPANY_CODE`. The
68
+ secret itself is never in this file, and the portal never stores a value it
69
+ read from code.
70
+ - A `config` entry is either a bare key (required) or
71
+ `{ key, optional: true, default }`. Read it back with
72
+ `integration("sap").config().companyCode`.
73
+ - Never use the `QORE_INTEGRATION_` or `CONN_` prefixes — both are reserved;
74
+ `assertIntegrations` warns about them at boot (`reserved_key`).
75
+ - `defineIntegrations` is an identity with a `const` generic, so
76
+ `integration("sap")` is typed and `integration("spa")` is a compile error.
77
+ Keep the file a literal object. The portal's extractor reads this file
78
+ **and every call site** statically, and skips anything it cannot read as a
79
+ literal (step 4 says what that means for a call).
80
+
81
+ ## 2. Declare the env in `src/config/env.ts` and `.env.example`
82
+
83
+ The zod schema is the one list of env this app reads — an integration key that
84
+ is not in it is invisible to `serverEnv()` and to `qore env pull`. Add every
85
+ key from step 1. Whether a key is required in the zod schema is this app's own
86
+ decision, and it is a real one: a required key that is unset fails every
87
+ `serverEnv()` call, so the whole app is down. Make a key required only when
88
+ the app cannot do its job without that integration; otherwise mark it
89
+ `.optional()` and let a missing value cost only the calls to it:
90
+
91
+ ```ts
92
+ // inside serverSchema = z.object({ ... })
93
+ SAP_BASE_URL: z.string().url(),
94
+ SAP_TOKEN_URL: z.string().url(),
95
+ SAP_CLIENT_ID: z.string().min(1),
96
+ SAP_CLIENT_SECRET: z.string().min(1),
97
+ SAP_COMPANY_CODE: z.string().min(1),
98
+ SAP_TIMEOUT_MS: z.coerce.number().optional(),
99
+ ```
100
+
101
+ Add the same keys to `.env.example` with a blank value (never a real one), so
102
+ a colleague's `pnpm bootstrap` knows what to ask the portal for. Then set the
103
+ values per environment in the portal's Secrets tab; the Integrations tab shows
104
+ which keys are still unset.
105
+
106
+ ## 3. Startup warnings (already wired)
107
+
108
+ `src/instrumentation.ts` calls `assertIntegrations(integrations)` on the Node
109
+ runtime at boot. Nothing to add. It **never throws**: integrations are a
110
+ visibility tool, and an unset key (an obsolete integration, a vendor not
111
+ contracted in this environment) must not take the app down. It logs one
112
+ line per problem and returns them:
113
+
114
+ ```
115
+ [integrations] Integration "sap" is missing env key "SAP_CLIENT_SECRET"; calls to it will fail until it is set
116
+ ```
117
+
118
+ The call itself then fails with `IntegrationError` `missing_env`, so handle
119
+ that where a missing integration should degrade gracefully. The portal's
120
+ Integrations tab shows the same keys as missing per environment.
121
+
122
+ ## 4. Call it
123
+
124
+ ```ts
125
+ import { integration } from "@/config/integrations"
126
+
127
+ // GET with a path parameter and a query string. `{id}` is expanded with
128
+ // encodeURIComponent; a missing param throws `missing_param`.
129
+ const res = await integration("sap").get("/A_SalesOrder('{id}')", {
130
+ params: { id },
131
+ query: { $expand: "to_Item" },
132
+ })
133
+ if (!res.ok) throw new Error(`sap returned ${res.status}`)
134
+ const order = await res.json()
135
+
136
+ // POST with a JSON body (serialised for you, content-type set).
137
+ await integration("sap").post("/A_SalesOrder", { body: { SalesOrderType: "OR" } })
138
+
139
+ // Non-secret config from the declaration.
140
+ const { companyCode } = integration("sap").config()
141
+ ```
142
+
143
+ `integration(alias)` returns a handle with `get` / `post` / `put` / `patch` /
144
+ `delete` and a generic `request(method, path, req?)`. The request object is
145
+ `{ params?, query?, body?, headers?, timeoutMs?, signal? }`; the default timeout
146
+ is 10 s, and a caller's `signal` is chained to it. The base URL and the auth
147
+ header come from env, so the call site only ever names a **relative** path.
148
+
149
+ **Write the alias and the path at the call site, as literals.** The portal
150
+ reads `integration("sap").get("/A_SalesOrder")` from source, not from values,
151
+ so the Integrations tab lists exactly the endpoints written that way. A path
152
+ held in a variable, a constant or a helper's parameter still reaches the API,
153
+ and the endpoint silently drops off the tab. So does every call through an
154
+ alias in a variable, or through a handle kept in one
155
+ (`const sap = integration("sap")`). A placeholder or a template literal is
156
+ fine: `"/A_SalesOrder('{id}')"` with `params`, or a `${…}` substitution, are
157
+ both listed with the hole as `{id}`. Prefer `params` for anything a caller
158
+ supplied, because it is URL-encoded and a raw substitution is not.
159
+
160
+ Shared configuration, timeouts and response handling may go in a helper. The
161
+ path may not:
162
+
163
+ ```ts
164
+ // Options every SAP call shares, in one place.
165
+ const sapOptions = (req: IntegrationRequest = {}): IntegrationRequest => ({ timeoutMs: 5_000, ...req })
166
+
167
+ // The path stays inline, so the portal lists this endpoint.
168
+ const res = await integration("sap").get("/A_SalesOrderItem", sapOptions({ query: { $top: 50 } }))
169
+ ```
170
+
171
+ `IntegrationRequest` is exported next to `integration` from the SDK subpath.
172
+ `pnpm lint` warns on all three shapes (`qdc/integration-static-call`,
173
+ QDC-NET-003).
174
+
175
+ `IntegrationError` (`code` ∈ `not_declared` | `missing_env` | `reserved_key` |
176
+ `absolute_url` | `missing_param` | `token_failed`, status 500) means *this app*
177
+ is misconfigured — it is never the vendor being down. A vendor error is an
178
+ ordinary non-ok `Response`; handle it like any other HTTP status.
179
+
180
+ Every call is a Sentry span named `→ sap GET /A_SalesOrder('{id}')` with
181
+ `qore.span.type: "integration_call"`, `qore.integration.alias`, the path
182
+ template and the response status — no URL, no headers, no body. Set
183
+ `QORE_INTEGRATION_SAP_LOGGING=1` in an environment to also get one JSON log line
184
+ per call (`qore.integration.call`: alias, method, template, status, duration).
185
+
186
+ ## 5. Don't
187
+
188
+ - **Don't call `fetch("https://…")` directly.** `pnpm lint` flags it
189
+ (`qdc/no-undeclared-external-call`, QDC-NET-002), and the portal lists the host
190
+ as "detected, not declared" — an integration nobody can probe or audit.
191
+ Declare it in step 1 and call it through `integration(alias)`.
192
+ - **Don't pass the path in from elsewhere.** `integration("weather").get(path)`
193
+ inside a helper works at runtime, and the portal never sees the endpoint.
194
+ `pnpm lint` warns (`qdc/integration-static-call`, QDC-NET-003). Write the
195
+ literal at every call site, and let the helper take the options.
196
+ - **Don't pass an absolute URL to `.get`/`.post`.** The base URL belongs to the
197
+ declaration; the client refuses `http(s)://…` paths (`absolute_url`), which is
198
+ what keeps a path parameter from redirecting a call to another host.
199
+ - **Don't put a credential in `config`, in `.env.example`, or in a log line.**
200
+ `apiKey` / `token` / `password` / `clientSecret` are the secret fields; the
201
+ SDK never logs them and neither should you. A failed call's span and
202
+ error carry no secret, so reporting one is safe; whether to report it at all
203
+ follows /qore-observability (unexpected: let it throw; expected: no capture).
204
+ - **Don't bypass `env.ts`.** Reading `process.env.SAP_BASE_URL` directly skips
205
+ validation and leaves `qore env pull` unaware of the key.
206
+
207
+ ## 6. Ship it
208
+
209
+ Run the full local check loop — `pnpm lint && pnpm typecheck && pnpm test:run &&
210
+ pnpm build` — then /qore-ship-checklist before a PR.
211
+
212
+ After it deploys, open the module's Integrations tab in the portal: it should
213
+ list every endpoint you call. One missing means its alias or path is not
214
+ written as a literal at the call site (step 4).
215
+
216
+ > A worked, non-wired reference lives at `docs/examples/integration.example.ts`.
217
+ > Don't hand-edit the auth/SDK boundary (`src/instrumentation.ts`, `src/proxy.ts`).