@quatronic/sdk 0.7.0-rc.9 → 0.7.0-test.0d8c736

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 (81) hide show
  1. package/dist/{chunk-2AYDFLKR.js → chunk-F3NHTHFO.js} +6 -104
  2. package/dist/chunk-F3NHTHFO.js.map +1 -0
  3. package/dist/chunk-P7HNHLW7.js +65 -0
  4. package/dist/chunk-P7HNHLW7.js.map +1 -0
  5. package/dist/chunk-QMOZDE3U.js +158 -0
  6. package/dist/chunk-QMOZDE3U.js.map +1 -0
  7. package/dist/chunk-TOBGX4CZ.js +109 -0
  8. package/dist/chunk-TOBGX4CZ.js.map +1 -0
  9. package/dist/chunk-WU7N4PET.js +20 -0
  10. package/dist/chunk-WU7N4PET.js.map +1 -0
  11. package/dist/cli/legacy/qdc-sourcemaps.js +16 -6
  12. package/dist/cli/skills-postinstall.js +133 -3
  13. package/dist/cli/skills.js +133 -3
  14. package/dist/cli/sourcemaps.js +16 -6
  15. package/dist/integrations/index.d.ts +3 -75
  16. package/dist/integrations/index.js +6 -4
  17. package/dist/mail/index.d.ts +9 -0
  18. package/dist/mail/index.js +26 -0
  19. package/dist/mail/index.js.map +1 -0
  20. package/dist/next/auth/index.d.ts +12 -0
  21. package/dist/next/auth/index.js +14 -155
  22. package/dist/next/auth/index.js.map +1 -1
  23. package/dist/next/boot/index.d.ts +33 -0
  24. package/dist/next/boot/index.js +21 -0
  25. package/dist/next/boot/index.js.map +1 -0
  26. package/dist/next/db/index.d.ts +18 -1
  27. package/dist/next/db/index.js +25 -0
  28. package/dist/next/db/index.js.map +1 -1
  29. package/dist/next/global-error/index.d.ts +9 -0
  30. package/dist/next/global-error/index.js +17 -0
  31. package/dist/next/global-error/index.js.map +1 -0
  32. package/dist/next/integrations/index.d.ts +2 -1
  33. package/dist/next/integrations/index.js +6 -4
  34. package/dist/next/platform/index.d.ts +19 -0
  35. package/dist/next/platform/index.js +44 -0
  36. package/dist/next/platform/index.js.map +1 -0
  37. package/dist/next/security/index.d.ts +23 -1
  38. package/dist/next/security/index.js +38 -55
  39. package/dist/next/security/index.js.map +1 -1
  40. package/dist/next/sentry/register.js +5 -13
  41. package/dist/next/sentry/register.js.map +1 -1
  42. package/dist/next/users/index.js +7 -4
  43. package/dist/next/users/index.js.map +1 -1
  44. package/dist/node/boot/index.d.ts +9 -0
  45. package/dist/node/boot/index.js +13 -0
  46. package/dist/node/boot/index.js.map +1 -0
  47. package/dist/node/integrations/index.d.ts +2 -1
  48. package/dist/node/integrations/index.js +6 -4
  49. package/dist/node-Z7ERWJDZ.js +46 -0
  50. package/dist/node-Z7ERWJDZ.js.map +1 -0
  51. package/dist/types-CAwj03sM.d.ts +75 -0
  52. package/migrations/bootstrap-qore-env/codemod.mjs +77 -0
  53. package/migrations/bootstrap-qore-env/instructions.md +28 -0
  54. package/migrations/bootstrap-qore-env/meta.json +7 -0
  55. package/migrations/global-error/codemod.mjs +28 -0
  56. package/migrations/global-error/instructions.md +26 -0
  57. package/migrations/global-error/meta.json +7 -0
  58. package/migrations/local-db-port/codemod.mjs +61 -0
  59. package/migrations/local-db-port/instructions.md +35 -0
  60. package/migrations/local-db-port/meta.json +7 -0
  61. package/migrations/mail-reexport/codemod.mjs +64 -0
  62. package/migrations/mail-reexport/instructions.md +27 -0
  63. package/migrations/mail-reexport/meta.json +7 -0
  64. package/migrations/platform-routes/codemod.mjs +45 -0
  65. package/migrations/platform-routes/instructions.md +30 -0
  66. package/migrations/platform-routes/meta.json +7 -0
  67. package/migrations/qore-boot/codemod.mjs +261 -0
  68. package/migrations/qore-boot/instructions.md +74 -0
  69. package/migrations/qore-boot/meta.json +7 -0
  70. package/migrations/qore-proxy/codemod.mjs +88 -0
  71. package/migrations/qore-proxy/instructions.md +56 -0
  72. package/migrations/qore-proxy/meta.json +7 -0
  73. package/migrations/run.mjs +322 -0
  74. package/migrations/sourcemaps-finalize/codemod.mjs +63 -0
  75. package/migrations/sourcemaps-finalize/instructions.md +56 -0
  76. package/migrations/sourcemaps-finalize/meta.json +7 -0
  77. package/package.json +26 -4
  78. package/skills/qore-enable-auth-method/SKILL.md +4 -3
  79. package/skills/qore-use-mail-domain/SKILL.next.md +4 -4
  80. package/workspace-requirements.json +4 -0
  81. package/dist/chunk-2AYDFLKR.js.map +0 -1
@@ -0,0 +1,322 @@
1
+ // Runs the SDK's code migrations against an app checkout and reports, per
2
+ // file, what happened. The portal's upgrade bot calls it after bumping the
3
+ // SDK and puts the report in the pull request; a person can call it too:
4
+ //
5
+ // node node_modules/@quatronic/sdk/migrations/run.mjs --app . --from 0.6.0
6
+ //
7
+ // A migration is a folder next to this file (see the sdk-code-migration
8
+ // skill). Its codemod.mjs exports a `transformer(file, api)` that returns the
9
+ // new source, `undefined` to leave the file alone, or `null` to delete it, and
10
+ // optionally a `create(api)` that returns files to add. Every migration fails
11
+ // closed per file: it rewrites a file it fully recognises or leaves it
12
+ // byte-identical and says why through `api.report`.
13
+ //
14
+ // Imports nothing but node builtins. jscodeshift comes from the caller
15
+ // (`--jscodeshift <dir it is installed in>`), and only a migration whose
16
+ // codemod parses code needs it; `parser = "text"` codemods get the raw text.
17
+ import { createHash } from "node:crypto"
18
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"
19
+ import { createRequire } from "node:module"
20
+ import { dirname, join, resolve } from "node:path"
21
+ import { fileURLToPath, pathToFileURL } from "node:url"
22
+
23
+ const HERE = dirname(fileURLToPath(import.meta.url))
24
+ const DEFAULT_TARGETS = ["src/**/*.{ts,tsx,js,jsx,mjs,cjs}"]
25
+ const SKIP_DIRS = new Set(["node_modules", ".git", ".next", "dist", "build", "coverage", ".turbo"])
26
+
27
+ /**
28
+ * @typedef {"migrated" | "removed" | "added" | "manual" | "kept"} Status
29
+ * @typedef {{ status: "manual" | "kept", reason: string }} Note
30
+ * @typedef {{ path: string, status: Status, reason?: string }} FileResult
31
+ * @typedef {{ id: string, files: FileResult[] }} MigrationResult
32
+ * @typedef {{
33
+ * id: string,
34
+ * rule: string | null,
35
+ * introducedIn: string,
36
+ * testOnly?: boolean,
37
+ * targets?: string[],
38
+ * order?: number,
39
+ * }} Meta
40
+ * @typedef {{ meta: Meta, dir: string }} Migration
41
+ */
42
+
43
+ /**
44
+ * What a historical template rendering is compared on: line endings, trailing
45
+ * whitespace, trailing semicolons and blank-line runs are what a formatter
46
+ * changes without changing the code. Used by the tier-1 tables, so a file a
47
+ * team only reformatted still counts as untouched.
48
+ *
49
+ * @param {string} source
50
+ */
51
+ export function normalize(source) {
52
+ return source
53
+ .replace(/\r\n?/g, "\n")
54
+ .split("\n")
55
+ .map((l) => l.replace(/\s+$/, "").replace(/;+$/, ""))
56
+ .join("\n")
57
+ .replace(/\n{3,}/g, "\n\n")
58
+ .trim()
59
+ }
60
+
61
+ /**
62
+ * A parsing codemod's output in the file's own style: recast prints the lines
63
+ * it creates with the platform's line ending and a semicolon. The file's line
64
+ * ending wins, and in a file with no semicolon-terminated line the new lines
65
+ * lose theirs, so the formatter has nothing to do.
66
+ *
67
+ * @param {string} source @param {string} out
68
+ */
69
+ export function keepStyle(source, out) {
70
+ const eol = source.includes("\r\n") ? "\r\n" : "\n"
71
+ const lines = out.split(/\r?\n/)
72
+ const had = source.split(/\r?\n/)
73
+ if (!had.some((l) => /;\s*$/.test(l))) {
74
+ const old = new Set(had)
75
+ for (let i = 0; i < lines.length; i++) {
76
+ const l = lines[i] ?? ""
77
+ if (!old.has(l)) lines[i] = l.replace(/;(\s*)$/, "$1")
78
+ }
79
+ }
80
+ return lines.join(eol)
81
+ }
82
+
83
+ /** sha256 of the normalized source, first 16 hex characters. */
84
+ export function fingerprint(/** @type {string} */ source) {
85
+ return createHash("sha256").update(normalize(source)).digest("hex").slice(0, 16)
86
+ }
87
+
88
+ /** @param {string} v */
89
+ function semver(v) {
90
+ return v.split(".").map((n) => Number.parseInt(n, 10) || 0)
91
+ }
92
+
93
+ /** @param {string} a @param {string} b */
94
+ export function compareVersions(a, b) {
95
+ const x = semver(a)
96
+ const y = semver(b)
97
+ for (let i = 0; i < 3; i++) {
98
+ const d = (x[i] ?? 0) - (y[i] ?? 0)
99
+ if (d !== 0) return d
100
+ }
101
+ return 0
102
+ }
103
+
104
+ /**
105
+ * A glob as a RegExp over `/`-separated relative paths: `**` spans
106
+ * directories, `*` and `?` stay inside one, `{a,b}` is an alternation.
107
+ *
108
+ * @param {string} glob
109
+ */
110
+ export function globToRegExp(glob) {
111
+ let re = ""
112
+ for (let i = 0; i < glob.length; i++) {
113
+ const c = glob[i] ?? ""
114
+ if (c === "*" && glob[i + 1] === "*") {
115
+ i++
116
+ if (glob[i + 1] === "/") {
117
+ i++
118
+ re += "(?:.*/)?"
119
+ } else re += ".*"
120
+ } else if (c === "*") re += "[^/]*"
121
+ else if (c === "?") re += "[^/]"
122
+ else if (c === "{") {
123
+ const end = glob.indexOf("}", i)
124
+ re += `(?:${glob
125
+ .slice(i + 1, end)
126
+ .split(",")
127
+ .map((s) => s.replace(/[.+^$()|[\]\\]/g, "\\$&"))
128
+ .join("|")})`
129
+ i = end
130
+ } else re += c.replace(/[.+^$()|[\]\\]/g, "\\$&")
131
+ }
132
+ return new RegExp(`^${re}$`)
133
+ }
134
+
135
+ /** @param {string} root @returns {string[]} relative, `/`-separated */
136
+ function walk(root, rel = "") {
137
+ /** @type {string[]} */
138
+ const out = []
139
+ for (const e of readdirSync(join(root, rel), { withFileTypes: true })) {
140
+ const path = rel ? `${rel}/${e.name}` : e.name
141
+ if (e.isDirectory()) {
142
+ if (!SKIP_DIRS.has(e.name)) out.push(...walk(root, path))
143
+ } else if (e.isFile()) out.push(path)
144
+ }
145
+ return out.sort()
146
+ }
147
+
148
+ /** @param {string} dir */
149
+ export function readMeta(dir) {
150
+ return /** @type {Meta} */ (JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")))
151
+ }
152
+
153
+ /**
154
+ * The migrations a bump from `from` (exclusive) to `to` (inclusive) carries,
155
+ * in the order they must run: `order`, then the version that introduced
156
+ * them, then id. `only` picks by id regardless of version.
157
+ *
158
+ * @param {{ dir?: string, from?: string, to?: string, only?: string[], includeTestOnly?: boolean }} opts
159
+ * @returns {Migration[]}
160
+ */
161
+ export function selectMigrations(opts = {}) {
162
+ const dir = opts.dir ?? HERE
163
+ const all = readdirSync(dir, { withFileTypes: true })
164
+ .filter((e) => e.isDirectory())
165
+ .map((e) => ({ meta: readMeta(join(dir, e.name)), dir: join(dir, e.name) }))
166
+ const picked = all.filter(({ meta }) => {
167
+ if (opts.only) return opts.only.includes(meta.id)
168
+ if (meta.testOnly && !opts.includeTestOnly) return false
169
+ if (opts.from && compareVersions(meta.introducedIn, opts.from) <= 0) return false
170
+ if (opts.to && compareVersions(meta.introducedIn, opts.to) > 0) return false
171
+ return true
172
+ })
173
+ return picked.sort(
174
+ (a, b) =>
175
+ (a.meta.order ?? 0) - (b.meta.order ?? 0) ||
176
+ compareVersions(a.meta.introducedIn, b.meta.introducedIn) ||
177
+ a.meta.id.localeCompare(b.meta.id),
178
+ )
179
+ }
180
+
181
+ /**
182
+ * Runs `migrations` in order on the checkout at `root`, writing the results
183
+ * in place. One migration sees what the ones before it wrote.
184
+ *
185
+ * @param {{ root: string, migrations: Migration[], jscodeshift?: any }} opts
186
+ * @returns {Promise<MigrationResult[]>}
187
+ */
188
+ export async function runMigrations({ root, migrations, jscodeshift }) {
189
+ /** @type {MigrationResult[]} */
190
+ const results = []
191
+ for (const m of migrations) {
192
+ const mod = existsSync(join(m.dir, "codemod.mjs"))
193
+ ? await import(pathToFileURL(join(m.dir, "codemod.mjs")).href)
194
+ : null
195
+ /** @type {FileResult[]} */
196
+ const files = []
197
+ results.push({ id: m.meta.id, files })
198
+ if (!mod) continue
199
+
200
+ const parser = mod.parser ?? "tsx"
201
+ if (parser !== "text" && !jscodeshift) {
202
+ throw new Error(`migration ${m.meta.id} parses ${parser} and needs jscodeshift (--jscodeshift <dir>)`)
203
+ }
204
+ const j = parser === "text" ? undefined : jscodeshift.withParser(parser)
205
+ const abs = (/** @type {string} */ p) => join(root, ...p.split("/"))
206
+ const base = {
207
+ jscodeshift: j,
208
+ j,
209
+ stats: () => {},
210
+ fingerprint,
211
+ normalize,
212
+ exists: (/** @type {string} */ p) => existsSync(abs(p)),
213
+ read: (/** @type {string} */ p) => (existsSync(abs(p)) ? readFileSync(abs(p), "utf8") : null),
214
+ }
215
+
216
+ const targets = (m.meta.targets ?? DEFAULT_TARGETS).map(globToRegExp)
217
+ const paths = typeof mod.default === "function" ? walk(root).filter((p) => targets.some((t) => t.test(p))) : []
218
+ for (const path of paths) {
219
+ const source = readFileSync(abs(path), "utf8")
220
+ /** @type {Note | null} */
221
+ let note = null
222
+ const api = { ...base, report: (/** @type {Note} */ n) => (note = n) }
223
+ let out
224
+ try {
225
+ out = mod.default({ path, source }, api)
226
+ if (parser !== "text" && typeof out === "string") out = keepStyle(source, out)
227
+ } catch (err) {
228
+ files.push({ path, status: "manual", reason: `the codemod failed: ${err instanceof Error ? err.message : String(err)}` })
229
+ continue
230
+ }
231
+ if (out === null) {
232
+ rmSync(abs(path))
233
+ files.push({ path, status: "removed" })
234
+ } else if (typeof out === "string" && out !== source) {
235
+ writeFileSync(abs(path), out)
236
+ files.push({ path, status: "migrated" })
237
+ } else if (note) {
238
+ const n = /** @type {Note} */ (note)
239
+ files.push({ path, status: n.status, reason: n.reason })
240
+ }
241
+ }
242
+
243
+ if (typeof mod.create === "function") {
244
+ /** @type {Note[]} */
245
+ const notes = []
246
+ const api = { ...base, report: (/** @type {Note & { path: string }} */ n) => notes.push(n) }
247
+ for (const f of mod.create(api) ?? []) {
248
+ if (existsSync(abs(f.path))) continue
249
+ mkdirSync(dirname(abs(f.path)), { recursive: true })
250
+ writeFileSync(abs(f.path), f.source)
251
+ files.push({ path: f.path, status: "added" })
252
+ }
253
+ for (const n of /** @type {(Note & { path: string })[]} */ (notes)) {
254
+ files.push({ path: n.path, status: n.status, reason: n.reason })
255
+ }
256
+ }
257
+ }
258
+ return results
259
+ }
260
+
261
+ const HEADINGS = /** @type {const} */ ([
262
+ ["manual", "Needs a manual change"],
263
+ ["kept", "Left as is (changed by the team)"],
264
+ ["migrated", "Migrated"],
265
+ ["added", "Added"],
266
+ ["removed", "Removed"],
267
+ ])
268
+
269
+ /**
270
+ * The report as Markdown for a pull request body. Manual work comes first:
271
+ * that is what a reviewer has to act on.
272
+ *
273
+ * @param {MigrationResult[]} results
274
+ */
275
+ export function reportMarkdown(results) {
276
+ if (results.length === 0) return ""
277
+ const lines = ["## Code migrations", ""]
278
+ lines.push(`Ran: ${results.map((r) => `\`${r.id}\``).join(", ")}.`, "")
279
+ const all = results.flatMap((r) => r.files.map((f) => ({ ...f, id: r.id })))
280
+ if (all.length === 0) lines.push("Nothing in this app needed a change.")
281
+ for (const [status, heading] of HEADINGS) {
282
+ const rows = all.filter((f) => f.status === status)
283
+ if (rows.length === 0) continue
284
+ lines.push(`### ${heading}`, "")
285
+ for (const f of rows) lines.push(`- \`${f.path}\` (${f.id})${f.reason ? `: ${f.reason}` : ""}`)
286
+ lines.push("")
287
+ }
288
+ return `${lines.join("\n").trimEnd()}\n`
289
+ }
290
+
291
+ /** @param {string | undefined} dir */
292
+ function loadJscodeshift(dir) {
293
+ // createRequire takes an absolute path only; `--jscodeshift deps` is relative.
294
+ const req = createRequire(dir ? join(resolve(dir), "noop.js") : import.meta.url)
295
+ try {
296
+ return req("jscodeshift")
297
+ } catch {
298
+ return undefined
299
+ }
300
+ }
301
+
302
+ // CLI: node run.mjs --app <dir> [--from <version>] [--to <version>]
303
+ // [--only id,id] [--test-only] [--jscodeshift <dir>] [--report <file>]
304
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
305
+ const arg = (/** @type {string} */ name) => {
306
+ const i = process.argv.indexOf(name)
307
+ return i > 0 ? process.argv[i + 1] : undefined
308
+ }
309
+ const app = arg("--app") ?? "."
310
+ const to = arg("--to") ?? JSON.parse(readFileSync(join(HERE, "../package.json"), "utf8")).version
311
+ const only = arg("--only")?.split(",")
312
+ const migrations = selectMigrations({
313
+ from: arg("--from"),
314
+ to,
315
+ ...(only ? { only } : {}),
316
+ includeTestOnly: process.argv.includes("--test-only"),
317
+ })
318
+ const results = await runMigrations({ root: app, migrations, jscodeshift: loadJscodeshift(arg("--jscodeshift")) })
319
+ const report = arg("--report")
320
+ if (report) writeFileSync(report, `${JSON.stringify(results, null, 2)}\n`)
321
+ process.stdout.write(reportMarkdown(results))
322
+ }
@@ -0,0 +1,63 @@
1
+ // Code migration sourcemaps-finalize. The Dockerfile's source-map handling
2
+ // becomes one SDK step:
3
+ //
4
+ // RUN pnpm exec qore-sourcemaps finalize <dir>
5
+ //
6
+ // `finalize` is the build's platform step: a new one ships inside it with an
7
+ // SDK release instead of as a Dockerfile edit. It never fails the build.
8
+ //
9
+ // Two shapes migrate, both as line edits, so a Dockerfile the team changed
10
+ // elsewhere migrates too:
11
+ //
12
+ // - the pair "upload, then delete the maps" becomes the one step. The legacy
13
+ // `qdc-sourcemaps` name is replaced as well: it uploads nothing since the
14
+ // upload moved behind the portal.
15
+ // - a Dockerfile without any source-map step (Next apps that uploaded from
16
+ // inside `next build` until 2026-09-29, backends that never uploaded) gets
17
+ // the step after its one `RUN pnpm build` in the build stage, with the two
18
+ // build arguments it reads.
19
+ export const parser = "text"
20
+
21
+ const PAIR = /^RUN pnpm exec (?:qore|qdc)-sourcemaps upload (\S+) \|\| true\r?\nRUN find (\S+) -name '\*\.map' -delete[ \t]*$/m
22
+ const BUILD = /^RUN pnpm (?:run )?build[ \t]*$/gm
23
+ const SEE = "see the sourcemaps-finalize instructions"
24
+
25
+ const isNext = (api) => ["next.config.mjs", "next.config.ts", "next.config.js"].some((p) => api.exists(p))
26
+
27
+ /** Adds the step after the build stage's single `RUN pnpm build`, or null when that line is not unambiguous. */
28
+ function addStep(source, dir) {
29
+ const froms = [...source.matchAll(/^FROM /gm)]
30
+ if (froms.length === 0) return null
31
+ const stage = froms.length > 1 ? source.slice(0, froms[1].index) : source
32
+ const builds = [...stage.matchAll(BUILD)]
33
+ if (builds.length !== 1) return null
34
+ const at = builds[0].index
35
+ const line = builds[0][0]
36
+ const before = /^ARG QORE_BUILD_UPLOAD_URL\b/m.test(stage) ? "" : `ARG QORE_BUILD_UPLOAD_URL=""\n`
37
+ const after = /^ARG QORE_BUILD_UPLOAD_TOKEN\b/m.test(stage) ? "" : `ARG QORE_BUILD_UPLOAD_TOKEN=""\n`
38
+ const step =
39
+ `${before}${line}\n` +
40
+ `# Platform build step: hands the source maps to Qore, then strips them from\n` +
41
+ `# the image. Never fails the build.\n` +
42
+ `${after}RUN pnpm exec qore-sourcemaps finalize ${dir}`
43
+ return source.slice(0, at) + step + source.slice(at + line.length)
44
+ }
45
+
46
+ export default function transformer(file, api) {
47
+ if (file.path !== "Dockerfile") return undefined
48
+ if (/qore-sourcemaps finalize /.test(file.source)) return undefined
49
+ const m = PAIR.exec(file.source)
50
+ if (m && m[1] === m[2]) return file.source.replace(PAIR, `RUN pnpm exec qore-sourcemaps finalize ${m[1]}`)
51
+ if (file.source.includes("sentry-cli")) {
52
+ return void api.report({
53
+ status: "manual",
54
+ reason: `uploads source maps with a Sentry token in the build; replace that step with qore-sourcemaps finalize, ${SEE}`,
55
+ })
56
+ }
57
+ if (/(?:qore|qdc)-sourcemaps/.test(file.source)) {
58
+ return void api.report({ status: "manual", reason: `changed by the team; replace the source-map lines with qore-sourcemaps finalize, ${SEE}` })
59
+ }
60
+ const added = addStep(file.source, isNext(api) ? ".next" : "dist")
61
+ if (added !== null) return added
62
+ return void api.report({ status: "manual", reason: `has no source-map step and no single \`RUN pnpm build\` to add it after, ${SEE}` })
63
+ }
@@ -0,0 +1,56 @@
1
+ # sourcemaps-finalize: one platform step in the Dockerfile
2
+
3
+ The Dockerfile used to carry two source-map lines: hand the maps to Qore, then
4
+ delete them so the image does not ship your source. Both are now one SDK step,
5
+ so a new platform build step arrives with an SDK release instead of a
6
+ Dockerfile edit:
7
+
8
+ ```dockerfile
9
+ RUN pnpm exec qore-sourcemaps finalize .next # dist for a backend
10
+ ```
11
+
12
+ It never fails the build: a refused or failed upload is a warning.
13
+
14
+ The upgrade bot runs this for you:
15
+
16
+ ```bash
17
+ node node_modules/@quatronic/sdk/migrations/run.mjs --only sourcemaps-finalize
18
+ ```
19
+
20
+ It replaces the pair
21
+
22
+ ```dockerfile
23
+ RUN pnpm exec qore-sourcemaps upload .next || true # or qdc-sourcemaps
24
+ RUN find .next -name '*.map' -delete
25
+ ```
26
+
27
+ wherever it is, even in a Dockerfile your team changed elsewhere. The old
28
+ `qdc-sourcemaps` name uploads nothing any more, so those apps get their source
29
+ maps back with this change.
30
+
31
+ A Dockerfile without any source-map step gets the step after its `RUN pnpm
32
+ build`, with the two build arguments it reads (see below). That covers Next apps
33
+ generated until 2026-09-29, which uploaded from inside `next build`, and
34
+ backends, which did not upload at all.
35
+
36
+ ## By hand
37
+
38
+ The step needs the upload settings as build arguments. In the build stage, put
39
+ the URL before the build (the SDK's Next config keeps the maps only when it is
40
+ set) and the token after it:
41
+
42
+ ```dockerfile
43
+ ARG NF_GIT_SHA=""
44
+ ENV SENTRY_RELEASE=$NF_GIT_SHA
45
+ ARG QORE_BUILD_UPLOAD_URL=""
46
+ RUN pnpm build
47
+ ARG QORE_BUILD_UPLOAD_TOKEN=""
48
+ RUN pnpm exec qore-sourcemaps finalize .next
49
+ ```
50
+
51
+ A Dockerfile that runs `sentry-cli` itself (generated 2026-09-29 to 2026-10-12)
52
+ uploads with a Sentry token inside the build. Delete that `RUN` block and its
53
+ `SENTRY_AUTH_TOKEN`/`SENTRY_ORG`/`SENTRY_PROJECT`/`SENTRY_URL`/`SENTRY_REPO`
54
+ arguments, and use the lines above. So does a Dockerfile that builds with `npm run build`
55
+ (backends generated before 2026-08-21): switch it to pnpm first, as the template
56
+ did.
@@ -0,0 +1,7 @@
1
+ {
2
+ "id": "sourcemaps-finalize",
3
+ "rule": null,
4
+ "introducedIn": "0.7.0",
5
+ "targets": ["Dockerfile"],
6
+ "order": 10
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quatronic/sdk",
3
- "version": "0.7.0-rc.9",
3
+ "version": "0.7.0-test.0d8c736",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -12,7 +12,8 @@
12
12
  "migrations",
13
13
  "semgrep",
14
14
  "skills",
15
- "postinstall.mjs"
15
+ "postinstall.mjs",
16
+ "workspace-requirements.json"
16
17
  ],
17
18
  "bin": {
18
19
  "qore-skills": "./dist/cli/skills.js",
@@ -122,6 +123,26 @@
122
123
  "./next/db": {
123
124
  "types": "./dist/next/db/index.d.ts",
124
125
  "import": "./dist/next/db/index.js"
126
+ },
127
+ "./mail": {
128
+ "types": "./dist/mail/index.d.ts",
129
+ "import": "./dist/mail/index.js"
130
+ },
131
+ "./next/boot": {
132
+ "types": "./dist/next/boot/index.d.ts",
133
+ "import": "./dist/next/boot/index.js"
134
+ },
135
+ "./node/boot": {
136
+ "types": "./dist/node/boot/index.d.ts",
137
+ "import": "./dist/node/boot/index.js"
138
+ },
139
+ "./next/global-error": {
140
+ "types": "./dist/next/global-error/index.d.ts",
141
+ "import": "./dist/next/global-error/index.js"
142
+ },
143
+ "./next/platform": {
144
+ "types": "./dist/next/platform/index.d.ts",
145
+ "import": "./dist/next/platform/index.js"
125
146
  }
126
147
  },
127
148
  "scripts": {
@@ -199,7 +220,7 @@
199
220
  "@types/pg": "^8.11.10",
200
221
  "@types/react": "^18.3.17",
201
222
  "@types/react-dom": "^18.3.5",
202
- "@vitest/coverage-v8": "^2.1.9",
223
+ "@vitest/coverage-v8": "^4.1.12",
203
224
  "better-auth": "^1.6.24",
204
225
  "drizzle-kit": "^0.30.1",
205
226
  "drizzle-orm": "^0.38.2",
@@ -215,6 +236,7 @@
215
236
  "tsup": "^8.3.5",
216
237
  "typescript": "^5.7.2",
217
238
  "typescript-eslint": "^8.61.1",
218
- "vitest": "^2.1.8"
239
+ "vite": "8.3.5",
240
+ "vitest": "^4.1.12"
219
241
  }
220
242
  }
@@ -47,8 +47,8 @@ No migration; no new table.
47
47
  ## Recipe: Magic link
48
48
 
49
49
  No migration — reuses the `verification` table. Emails go through
50
- `sendEmail` (`src/lib/email`), which logs to the console when
51
- `RESEND_API_KEY` is unset, so it works locally without a mail provider.
50
+ `sendEmail` (`src/lib/email`), which prints the mail to the terminal under
51
+ `pnpm dev` when no mail key is set, so it works locally without a mail provider.
52
52
 
53
53
  1. In `src/lib/auth.ts`: uncomment `// import { magicLink … }` at the top
54
54
  (merge it into the existing `better-auth/plugins` import), then uncomment the
@@ -61,7 +61,8 @@ No migration — reuses the `verification` table. Emails go through
61
61
  needed. Add `magicLinkEmail` to the existing `@/lib/email` import at the
62
62
  top of `src/lib/auth.ts`; the `magicLink({ sendMagicLink … })` block
63
63
  uncommented in step 1 already calls it.
64
- 5. For real email delivery set `RESEND_API_KEY` + `EMAIL_FROM`.
64
+ 5. For real email delivery, link a mail domain to this module in the portal
65
+ (or set `RESEND_API_KEY` + `EMAIL_FROM` for a Resend key of your own).
65
66
  6. Run the check loop.
66
67
 
67
68
  ## Recipe: Two-factor (TOTP)
@@ -56,10 +56,10 @@ Worked example: `docs/examples/mail.example.ts`.
56
56
  ## This is not auth email
57
57
 
58
58
  If this app has Better Auth (`next-betterauth`), verification and magic-link
59
- email already flow through `src/lib/email/send.ts` and its own
60
- `RESEND_API_KEY`/`EMAIL_FROM` — a separate mechanism tied to the portal's
61
- platform sender, not to a per-module linked domain. Don't merge the two;
62
- `sendMail` here is for this module's own business email.
59
+ email already flow through `src/lib/email/send.ts`. It sends over the same
60
+ linked domain (or the app's own `RESEND_API_KEY`/`EMAIL_FROM` when set), but
61
+ with its own templates. Don't route auth email through `sendMail`; `sendMail`
62
+ here is for this module's own business email.
63
63
 
64
64
  ## Ship it
65
65
 
@@ -0,0 +1,4 @@
1
+ {
2
+ "allowBuilds": ["@quatronic/sdk", "@sentry/cli"],
3
+ "minimumReleaseAgeExclude": ["@quatronic/sdk"]
4
+ }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/integrations-core/types.ts","../src/integrations-core/env.ts","../src/integrations-core/assertIntegrations.ts","../src/integrations-core/constants.ts","../src/integrations-core/errors.ts","../src/integrations-core/client.ts","../src/integrations-core/base64.ts","../src/integrations-core/oauth2.ts"],"sourcesContent":["/**\n * How an integration authenticates. Every field except `header` and\n * `credentialsIn` names an **env key** — the SDK reads the value from the\n * environment at call time, never from the declaration — so a declaration can\n * sit in source control and carry no secret.\n */\nexport type AuthKind =\n | \"none\"\n | \"api_key_header\"\n | \"bearer_static\"\n | \"basic\"\n | \"oauth2_client_credentials\"\n\n/** What the API speaks. Informational for the portal; the client sends bytes either way. */\nexport type Protocol = \"rest\" | \"odata\" | \"soap\" | \"graphql\"\n\n/** The name of an env var, e.g. `SAP_BASE_URL`. */\nexport type EnvKey = string\n\n/**\n * A reference to an env var. The short form is required; the object form can\n * be optional and carry a default the app falls back on when the key is unset.\n */\nexport type EnvRef =\n | EnvKey\n | { key: EnvKey; optional?: boolean; default?: string | number | boolean }\n\nexport type IntegrationAuth =\n | { kind: \"none\" }\n | { kind: \"api_key_header\"; header: string; apiKey: EnvKey }\n | { kind: \"bearer_static\"; token: EnvKey }\n | { kind: \"basic\"; username: EnvKey; password: EnvKey }\n | {\n kind: \"oauth2_client_credentials\"\n tokenUrl: EnvKey\n clientId: EnvKey\n clientSecret: EnvKey\n scope?: EnvKey\n audience?: EnvKey\n /** Where the client credentials go on the token request. Default `\"header\"`. */\n credentialsIn?: \"header\" | \"body\"\n }\n\nexport interface IntegrationDefinition {\n /** Human name shown in the portal, e.g. \"SAP S/4HANA Cloud\". */\n label: string\n protocol: Protocol\n /** Env key holding the base URL for this environment. */\n baseUrl: EnvKey\n auth: IntegrationAuth\n /** Further env the app reads for this integration, by logical name. */\n config?: Record<string, EnvRef>\n}\n\nexport type IntegrationMap = Record<string, IntegrationDefinition>\n\n/**\n * Identity function that pins the literal types of the map, so an alias typo\n * at a call site is a compile error (`keyof M`) rather than a runtime\n * `not_declared`. Same shape as `definePermissions` in `auth-core`.\n */\nexport function defineIntegrations<const M extends IntegrationMap>(map: M): M {\n return map\n}\n\n/**\n * Which fields of each auth kind name an env key. Shared with the manifest\n * extractor and the portal, which derive the required-env list from a\n * declaration without evaluating app code.\n */\nexport const AUTH_ENV_FIELDS: Record<AuthKind, readonly string[]> = {\n none: [],\n api_key_header: [\"apiKey\"],\n bearer_static: [\"token\"],\n basic: [\"username\", \"password\"],\n oauth2_client_credentials: [\"tokenUrl\", \"clientId\", \"clientSecret\", \"scope\", \"audience\"],\n}\n\n/** Auth fields whose env value is a secret, so the portal masks it. */\nexport const AUTH_SECRET_FIELDS = [\"apiKey\", \"token\", \"password\", \"clientSecret\"] as const\n\n/**\n * Env keys under this prefix belong to the platform\n * (`QORE_INTEGRATION_<ALIAS>_LOGGING` today). A declaration may not claim one.\n */\nexport const RESERVED_KEY_PREFIX = \"QORE_INTEGRATION_\"\n","import { normalizeAlias, type Env } from \"../connections-core/env\"\nimport {\n AUTH_ENV_FIELDS,\n RESERVED_KEY_PREFIX,\n type EnvRef,\n type IntegrationDefinition,\n} from \"./types\"\n\nexport type { Env }\n\nexport function refKey(ref: EnvRef): string {\n return typeof ref === \"string\" ? ref : ref.key\n}\n\nfunction refOptional(ref: EnvRef): boolean {\n return typeof ref !== \"string\" && (ref.optional === true || ref.default !== undefined)\n}\n\n/** The auth fields of `def` that are set, as env keys. */\nfunction authKeys(def: IntegrationDefinition): string[] {\n const auth = def.auth as unknown as Record<string, unknown>\n return AUTH_ENV_FIELDS[def.auth.kind]\n .map((field) => auth[field])\n .filter((key): key is string => typeof key === \"string\" && key !== \"\")\n}\n\n/**\n * Every env key the integration cannot run without: the base URL, every auth\n * field that is set, and every config ref that is neither optional nor\n * defaulted. Order is stable so an error message reads the same twice.\n */\nexport function requiredKeys(def: IntegrationDefinition): string[] {\n const keys = [def.baseUrl, ...authKeys(def)]\n for (const ref of Object.values(def.config ?? {})) {\n if (!refOptional(ref)) keys.push(refKey(ref))\n }\n return [...new Set(keys)]\n}\n\n/** Every env key the declaration names, required or not. */\nexport function allKeys(def: IntegrationDefinition): string[] {\n const keys = [def.baseUrl, ...authKeys(def)]\n for (const ref of Object.values(def.config ?? {})) keys.push(refKey(ref))\n return [...new Set(keys)]\n}\n\n/**\n * Read one ref from `env`, applying its default when the key is unset or\n * empty. A default comes back as declared (a number or boolean stays typed);\n * an env value is always a string.\n */\nexport function readRef(env: Env, ref: EnvRef): string | number | boolean | undefined {\n const value = env[refKey(ref)]\n if (value !== undefined && value !== \"\") return value\n return typeof ref === \"string\" ? undefined : ref.default\n}\n\n/** `QORE_INTEGRATION_<ALIAS>_LOGGING` — the one reserved key v1 reads. */\nexport function loggingKey(alias: string): string {\n return `${RESERVED_KEY_PREFIX}${normalizeAlias(alias)}_LOGGING`\n}\n\n/** Whether the per-call JSON log line is switched on for this alias (\"1\" or \"true\"). */\nexport function loggingEnabled(env: Env, alias: string): boolean {\n const value = env[loggingKey(alias)]\n return value === \"1\" || value?.toLowerCase() === \"true\"\n}\n","import { defaultEnv, type Env } from \"../connections-core/env\"\nimport { allKeys, requiredKeys } from \"./env\"\nimport { RESERVED_KEY_PREFIX, type IntegrationMap } from \"./types\"\n\nconst ENV_KEY_RE = /^[A-Z][A-Z0-9_]*$/\n\nexport interface IntegrationProblem {\n alias: string\n key: string\n /** `missing_env`: a required key is unset or empty. `reserved_key`: the declaration claims a key it may not. */\n code: \"missing_env\" | \"reserved_key\"\n message: string\n}\n\n/**\n * Report, at app startup, what is wrong with the declared integrations: a\n * required env key that is unset, or a key the declaration may not claim.\n * **It never throws.** Integrations are a visibility tool: an API key that is\n * not set (an obsolete integration, a vendor not contracted in this\n * environment) must cost the calls to that one integration — they fail with\n * `missing_env` — never the boot of the whole app. Each problem is logged as\n * one warning and returned, so a caller may act on them if it chooses.\n */\nexport function assertIntegrations(\n map: IntegrationMap,\n opts: { env?: Env; warn?: (message: string) => void } = {},\n): IntegrationProblem[] {\n const env = opts.env ?? defaultEnv()\n const warn = opts.warn ?? ((message: string) => console.warn(message))\n const problems: IntegrationProblem[] = []\n\n for (const [alias, def] of Object.entries(map)) {\n for (const key of allKeys(def)) {\n let why: string | undefined\n if (key.startsWith(RESERVED_KEY_PREFIX)) {\n why = `${RESERVED_KEY_PREFIX}* keys are reserved by the platform`\n } else if (key.startsWith(\"CONN_\")) {\n why = \"CONN_* keys belong to module connections, not integrations\"\n } else if (!ENV_KEY_RE.test(key)) {\n why = \"an env key is uppercase letters, digits and underscores\"\n }\n if (why) {\n problems.push({\n alias,\n key,\n code: \"reserved_key\",\n message: `Integration \"${alias}\" declares env key \"${key}\": ${why}`,\n })\n }\n }\n for (const key of requiredKeys(def)) {\n const value = env[key]\n if (value === undefined || value === \"\") {\n problems.push({\n alias,\n key,\n code: \"missing_env\",\n message: `Integration \"${alias}\" is missing env key \"${key}\"; calls to it will fail until it is set`,\n })\n }\n }\n }\n\n for (const p of problems) warn(`[integrations] ${p.message}`)\n return problems\n}\n","/** Default request timeout for integration(alias).request, overridable per call. */\nexport const DEFAULT_INTEGRATION_TIMEOUT_MS = 10_000\n\n/** `qore.span.type` value on an integration call's span. */\nexport const INTEGRATION_SPAN_TYPE = \"integration_call\"\n\n/** OTel span attribute carrying the declared alias, which the portal maps to the integration. */\nexport const INTEGRATION_ALIAS_ATTR = \"qore.integration.alias\"\n\n/** OTel span attribute naming the span's kind, shared with connections (`outbound_call`). */\nexport const INTEGRATION_SPAN_TYPE_ATTR = \"qore.span.type\"\n\n/** A cached OAuth2 token is refreshed this long before it expires. */\nexport const OAUTH_REFRESH_SKEW_MS = 30_000\n","/** Why an integration call refused. */\nexport type IntegrationErrorCode =\n | \"not_declared\" // alias is not a key of the declared map\n | \"missing_env\" // a required env key for the alias is unset or empty\n | \"reserved_key\" // unused since assertIntegrations reports instead of throwing; kept so the type does not narrow\n | \"absolute_url\" // request() was given a full URL, which would bypass the declared base\n | \"missing_param\" // a `{name}` in the path template has no value in `params`\n | \"token_failed\" // the OAuth2 token endpoint refused, or answered without an access_token\n\n/**\n * Single error shape for the integrations subpath, mirroring ConnectionError.\n * Every code here is a configuration or programming error on the app's side,\n * so `status` defaults to 500.\n */\nexport class IntegrationError extends Error {\n readonly code: IntegrationErrorCode\n readonly status: number\n\n constructor(code: IntegrationErrorCode, opts?: { message?: string; status?: number }) {\n super(opts?.message ?? code)\n this.name = \"IntegrationError\"\n this.code = code\n this.status = opts?.status ?? 500\n }\n}\n","import { SpanStatusCode, trace } from \"@opentelemetry/api\"\nimport { defaultEnv, type Env } from \"../connections-core/env\"\nimport { toBase64 } from \"./base64\"\nimport {\n DEFAULT_INTEGRATION_TIMEOUT_MS,\n INTEGRATION_ALIAS_ATTR,\n INTEGRATION_SPAN_TYPE,\n INTEGRATION_SPAN_TYPE_ATTR,\n} from \"./constants\"\nimport { loggingEnabled, readRef } from \"./env\"\nimport { IntegrationError } from \"./errors\"\nimport { getClientCredentialsToken } from \"./oauth2\"\nimport type { EnvRef, IntegrationDefinition, IntegrationMap } from \"./types\"\n\nexport type ParamValue = string | number | boolean\n\nexport interface IntegrationRequest {\n /** Values for the `{name}` placeholders in the path template; each is URI-encoded. */\n params?: Record<string, ParamValue>\n /** Query string, appended with URLSearchParams; `undefined` entries are skipped. */\n query?: Record<string, ParamValue | undefined>\n /**\n * Request body. A string, FormData, Blob, ArrayBuffer, typed array or\n * URLSearchParams is sent as is; anything else is JSON-encoded with\n * `content-type: application/json` unless the caller set one.\n */\n body?: unknown\n headers?: HeadersInit\n timeoutMs?: number\n signal?: AbortSignal\n}\n\n/** The resolved values of a definition's `config` refs, by their logical name. */\nexport type IntegrationConfig<D extends IntegrationDefinition> = D extends {\n config: infer C extends Record<string, EnvRef>\n}\n ? { [K in keyof C]: string | number | boolean | undefined }\n : Record<string, never>\n\nexport interface IntegrationHandle<D extends IntegrationDefinition = IntegrationDefinition> {\n readonly alias: string\n readonly definition: D\n /** The `config` refs read from env, defaults applied. */\n config(): IntegrationConfig<D>\n /**\n * One call against the declared base URL. `pathTemplate` is relative and\n * may hold `{name}` placeholders filled from `params`; an absolute URL is\n * refused so the integration cannot be pointed somewhere else per call.\n */\n request(method: string, pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n get(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n post(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n put(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n patch(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n delete(pathTemplate: string, req?: IntegrationRequest): Promise<Response>\n}\n\n/**\n * `integration(alias)`, typed against the declared map so an alias that is\n * not a key fails to compile.\n */\nexport type IntegrationClient<M extends IntegrationMap> = <K extends keyof M & string>(\n alias: K,\n) => IntegrationHandle<M[K]>\n\nconst PLACEHOLDER_RE = /\\{([^{}]+)\\}/g\n\nfunction isRawBody(body: unknown): body is BodyInit {\n if (typeof body === \"string\") return true\n if (typeof URLSearchParams !== \"undefined\" && body instanceof URLSearchParams) return true\n if (typeof FormData !== \"undefined\" && body instanceof FormData) return true\n if (typeof Blob !== \"undefined\" && body instanceof Blob) return true\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return true\n return false\n}\n\n/**\n * Bind a declared map to an env. The app calls this once in\n * `src/config/integrations.ts` and exports the result as `integration`:\n *\n * export const integrations = defineIntegrations({ sap: { ... } })\n * export const integration = createIntegrationClient(integrations)\n *\n * const res = await integration(\"sap\").get(\"/A_SalesOrder('{id}')\", { params: { id } })\n *\n * There is no global registry on purpose: a handle only exists for an alias\n * the map declares, which is what lets the portal trust the declaration.\n */\nexport function createIntegrationClient<M extends IntegrationMap>(\n map: M,\n opts: { env?: Env } = {},\n): IntegrationClient<M> {\n const envOf = (): Env => opts.env ?? defaultEnv()\n\n return <K extends keyof M & string>(alias: K): IntegrationHandle<M[K]> => {\n const definition = map[alias]\n if (!definition) {\n throw new IntegrationError(\"not_declared\", {\n message: `Integration \"${alias}\" is not declared; declared: ${Object.keys(map).join(\", \") || \"(none)\"}`,\n })\n }\n return createHandle(alias, definition, envOf)\n }\n}\n\nfunction createHandle<D extends IntegrationDefinition>(\n alias: string,\n definition: D,\n envOf: () => Env,\n): IntegrationHandle<D> {\n function required(env: Env, key: string): string {\n const value = env[key]\n if (value === undefined || value === \"\") {\n throw new IntegrationError(\"missing_env\", {\n message: `Integration \"${alias}\" is missing ${key}`,\n })\n }\n return value\n }\n\n async function authHeaders(env: Env, headers: Headers, timeoutMs: number): Promise<void> {\n const auth = definition.auth\n switch (auth.kind) {\n case \"none\":\n return\n case \"api_key_header\":\n headers.set(auth.header, required(env, auth.apiKey))\n return\n case \"bearer_static\":\n headers.set(\"authorization\", `Bearer ${required(env, auth.token)}`)\n return\n case \"basic\":\n headers.set(\n \"authorization\",\n `Basic ${toBase64(`${required(env, auth.username)}:${required(env, auth.password)}`)}`,\n )\n return\n case \"oauth2_client_credentials\": {\n const token = await getClientCredentialsToken(alias, auth, env, timeoutMs)\n headers.set(\"authorization\", `Bearer ${token}`)\n return\n }\n }\n }\n\n async function request(\n method: string,\n pathTemplate: string,\n req: IntegrationRequest = {},\n ): Promise<Response> {\n const env = envOf()\n const METHOD = method.toUpperCase()\n const base = required(env, definition.baseUrl)\n\n // The declaration is the one place that says where this integration\n // lives. A full URL per call would make the handle an arbitrary-request\n // primitive that carries the integration's credentials to whatever host\n // it names, so unlike connection().fetch this refuses from day one.\n if (/^https?:\\/\\//i.test(pathTemplate)) {\n throw new IntegrationError(\"absolute_url\", {\n message: `Integration \"${alias}\" was given an absolute URL; pass a path relative to ${definition.baseUrl}`,\n })\n }\n\n const path = pathTemplate.replace(PLACEHOLDER_RE, (_match, name: string) => {\n const value = req.params?.[name]\n if (value === undefined) {\n throw new IntegrationError(\"missing_param\", {\n message: `Integration \"${alias}\": path \"${pathTemplate}\" needs params.${name}`,\n })\n }\n return encodeURIComponent(String(value))\n })\n\n let url = base.replace(/\\/+$/, \"\") + \"/\" + path.replace(/^\\/+/, \"\")\n if (req.query) {\n const search = new URLSearchParams()\n for (const [key, value] of Object.entries(req.query)) {\n if (value !== undefined) search.append(key, String(value))\n }\n const qs = search.toString()\n if (qs) url += (url.includes(\"?\") ? \"&\" : \"?\") + qs\n }\n\n const { timeoutMs = DEFAULT_INTEGRATION_TIMEOUT_MS, signal: caller } = req\n const headers = new Headers(req.headers)\n\n let body: BodyInit | undefined\n if (req.body !== undefined) {\n if (isRawBody(req.body)) {\n body = req.body\n } else {\n body = JSON.stringify(req.body)\n if (!headers.has(\"content-type\")) headers.set(\"content-type\", \"application/json\")\n }\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n if (caller) {\n if (caller.aborted) controller.abort()\n else caller.addEventListener(\"abort\", () => controller.abort(), { once: true })\n }\n\n const log = loggingEnabled(env, alias)\n const startedAt = Date.now()\n const tracer = trace.getTracer(\"@quatronic/sdk\")\n // Named after the template, not the expanded path, so the portal can group\n // calls per endpoint; the alias attribute is what it maps to the declaration.\n return tracer.startActiveSpan(\n `→ ${alias} ${METHOD} ${pathTemplate}`,\n {\n attributes: {\n [INTEGRATION_SPAN_TYPE_ATTR]: INTEGRATION_SPAN_TYPE,\n [INTEGRATION_ALIAS_ATTR]: alias,\n \"url.template\": pathTemplate,\n \"http.request.method\": METHOD,\n },\n },\n async (span) => {\n try {\n await authHeaders(env, headers, timeoutMs)\n const res = await fetch(url, { method: METHOD, headers, body, signal: controller.signal })\n span.setAttribute(\"http.response.status_code\", res.status)\n if (res.status >= 500) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${res.status}` })\n }\n if (log) {\n // Alias, method, template, status, duration. Never the URL (it may\n // carry ids), never headers (credentials), never a body.\n console.info(\n JSON.stringify({\n level: \"info\",\n event: \"qore.integration.call\",\n alias,\n method: METHOD,\n template: pathTemplate,\n status: res.status,\n durationMs: Date.now() - startedAt,\n }),\n )\n }\n return res\n } catch (err) {\n span.recordException(err as Error)\n span.setStatus({ code: SpanStatusCode.ERROR })\n if (log) {\n console.info(\n JSON.stringify({\n level: \"info\",\n event: \"qore.integration.call\",\n alias,\n method: METHOD,\n template: pathTemplate,\n status: null,\n error: (err as Error)?.name ?? \"Error\",\n durationMs: Date.now() - startedAt,\n }),\n )\n }\n throw err\n } finally {\n span.end()\n clearTimeout(timer)\n }\n },\n )\n }\n\n return {\n alias,\n definition,\n config() {\n const env = envOf()\n const out: Record<string, string | number | boolean | undefined> = {}\n for (const [name, ref] of Object.entries(definition.config ?? {})) {\n out[name] = readRef(env, ref)\n }\n return out as IntegrationConfig<D>\n },\n request,\n get: (path, req) => request(\"GET\", path, req),\n post: (path, req) => request(\"POST\", path, req),\n put: (path, req) => request(\"PUT\", path, req),\n patch: (path, req) => request(\"PATCH\", path, req),\n delete: (path, req) => request(\"DELETE\", path, req),\n }\n}\n","/**\n * Base64 for the `Authorization: Basic` header. `Buffer` on Node, which is\n * where an integration call runs (a route handler, a server action, a backend\n * job); `btoa` as the edge fallback, which is Latin-1 only — a credential with\n * characters outside that range needs the node runtime.\n */\nexport function toBase64(text: string): string {\n if (typeof Buffer !== \"undefined\") return Buffer.from(text, \"utf8\").toString(\"base64\")\n return btoa(text)\n}\n","import { SpanStatusCode, trace } from \"@opentelemetry/api\"\nimport type { Env } from \"../connections-core/env\"\nimport { toBase64 } from \"./base64\"\nimport {\n INTEGRATION_ALIAS_ATTR,\n INTEGRATION_SPAN_TYPE,\n INTEGRATION_SPAN_TYPE_ATTR,\n OAUTH_REFRESH_SKEW_MS,\n} from \"./constants\"\nimport { IntegrationError } from \"./errors\"\nimport type { IntegrationAuth } from \"./types\"\n\nexport type OAuth2ClientCredentials = Extract<IntegrationAuth, { kind: \"oauth2_client_credentials\" }>\n\ninterface CacheEntry {\n accessToken?: string\n expiresAt: number\n inFlight?: Promise<string>\n}\n\n/** When `expires_in` is absent, assume a short-lived token rather than a permanent one. */\nconst DEFAULT_EXPIRES_IN_S = 300\n\n/**\n * One cache per process, keyed on what makes a token distinct. Two aliases\n * pointing at the same token endpoint with the same client share one token,\n * which is what the issuer would hand out anyway.\n */\nconst cache = new Map<string, CacheEntry>()\n\n/** Test-only: forget every cached token. Not exported from the public barrels. */\nexport function __resetIntegrationTokenCache(): void {\n cache.clear()\n}\n\nfunction required(env: Env, alias: string, key: string): string {\n const value = env[key]\n if (value === undefined || value === \"\") {\n throw new IntegrationError(\"missing_env\", {\n message: `Integration \"${alias}\" is missing ${key}`,\n })\n }\n return value\n}\n\nfunction optional(env: Env, key: string | undefined): string | undefined {\n if (!key) return undefined\n const value = env[key]\n return value === \"\" ? undefined : value\n}\n\n/**\n * A bearer token for an OAuth2 client-credentials integration: cached until\n * shortly before it expires, fetched once when several calls race for it.\n * The token request gets its own span (`→ <alias> token`) so a slow or\n * refusing issuer shows up as itself, not as a slow API call.\n */\nexport async function getClientCredentialsToken(\n alias: string,\n auth: OAuth2ClientCredentials,\n env: Env,\n timeoutMs: number,\n): Promise<string> {\n const tokenUrl = required(env, alias, auth.tokenUrl)\n const clientId = required(env, alias, auth.clientId)\n const clientSecret = required(env, alias, auth.clientSecret)\n const scope = optional(env, auth.scope)\n const audience = optional(env, auth.audience)\n\n const key = `${tokenUrl}|${clientId}|${scope ?? \"\"}|${audience ?? \"\"}`\n const entry = cache.get(key)\n if (entry?.accessToken && entry.expiresAt - OAUTH_REFRESH_SKEW_MS > Date.now()) {\n return entry.accessToken\n }\n if (entry?.inFlight) return entry.inFlight\n\n const inFlight = fetchToken(alias, {\n tokenUrl,\n clientId,\n clientSecret,\n scope,\n audience,\n credentialsIn: auth.credentialsIn ?? \"header\",\n timeoutMs,\n })\n .then((token) => {\n cache.set(key, { accessToken: token.accessToken, expiresAt: token.expiresAt })\n return token.accessToken\n })\n .catch((err: unknown) => {\n // Keep whatever was cached (possibly still usable within the skew), drop the in-flight marker.\n const current = cache.get(key)\n if (current?.inFlight === inFlight) {\n if (current.accessToken) cache.set(key, { accessToken: current.accessToken, expiresAt: current.expiresAt })\n else cache.delete(key)\n }\n throw err\n })\n cache.set(key, { ...(entry ?? { expiresAt: 0 }), inFlight })\n return inFlight\n}\n\ninterface TokenRequest {\n tokenUrl: string\n clientId: string\n clientSecret: string\n scope?: string\n audience?: string\n credentialsIn: \"header\" | \"body\"\n timeoutMs: number\n}\n\nasync function fetchToken(\n alias: string,\n req: TokenRequest,\n): Promise<{ accessToken: string; expiresAt: number }> {\n const form = new URLSearchParams({ grant_type: \"client_credentials\" })\n if (req.scope) form.set(\"scope\", req.scope)\n if (req.audience) form.set(\"audience\", req.audience)\n const headers = new Headers({\n \"content-type\": \"application/x-www-form-urlencoded\",\n accept: \"application/json\",\n })\n if (req.credentialsIn === \"body\") {\n form.set(\"client_id\", req.clientId)\n form.set(\"client_secret\", req.clientSecret)\n } else {\n headers.set(\"authorization\", `Basic ${toBase64(`${req.clientId}:${req.clientSecret}`)}`)\n }\n\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), req.timeoutMs)\n\n const tracer = trace.getTracer(\"@quatronic/sdk\")\n return tracer.startActiveSpan(\n `→ ${alias} token`,\n {\n attributes: {\n [INTEGRATION_SPAN_TYPE_ATTR]: INTEGRATION_SPAN_TYPE,\n [INTEGRATION_ALIAS_ATTR]: alias,\n \"http.request.method\": \"POST\",\n },\n },\n async (span) => {\n try {\n const res = await fetch(req.tokenUrl, {\n method: \"POST\",\n headers,\n body: form.toString(),\n signal: controller.signal,\n })\n span.setAttribute(\"http.response.status_code\", res.status)\n if (!res.ok) {\n // Status only. The issuer's body can echo the request, credentials included.\n span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${res.status}` })\n throw new IntegrationError(\"token_failed\", {\n message: `OAuth2 token request for \"${alias}\" failed with HTTP ${res.status}`,\n })\n }\n let payload: unknown\n try {\n payload = await res.json()\n } catch {\n payload = undefined\n }\n const body = (payload ?? {}) as { access_token?: unknown; expires_in?: unknown }\n if (typeof body.access_token !== \"string\" || body.access_token === \"\") {\n span.setStatus({ code: SpanStatusCode.ERROR, message: \"no access_token\" })\n throw new IntegrationError(\"token_failed\", {\n message: `OAuth2 token response for \"${alias}\" carried no access_token`,\n })\n }\n const expiresIn = Number(body.expires_in)\n const seconds = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : DEFAULT_EXPIRES_IN_S\n return { accessToken: body.access_token, expiresAt: Date.now() + seconds * 1000 }\n } catch (err) {\n if (!(err instanceof IntegrationError)) {\n span.recordException(err as Error)\n span.setStatus({ code: SpanStatusCode.ERROR })\n }\n throw err\n } finally {\n span.end()\n clearTimeout(timer)\n }\n },\n )\n}\n"],"mappings":";;;;;;AA6DO,SAAS,mBAAmD,KAAW;AAC5E,SAAO;AACT;AAOO,IAAM,kBAAuD;AAAA,EAClE,MAAM,CAAC;AAAA,EACP,gBAAgB,CAAC,QAAQ;AAAA,EACzB,eAAe,CAAC,OAAO;AAAA,EACvB,OAAO,CAAC,YAAY,UAAU;AAAA,EAC9B,2BAA2B,CAAC,YAAY,YAAY,gBAAgB,SAAS,UAAU;AACzF;AAGO,IAAM,qBAAqB,CAAC,UAAU,SAAS,YAAY,cAAc;AAMzE,IAAM,sBAAsB;;;AC3E5B,SAAS,OAAO,KAAqB;AAC1C,SAAO,OAAO,QAAQ,WAAW,MAAM,IAAI;AAC7C;AAEA,SAAS,YAAY,KAAsB;AACzC,SAAO,OAAO,QAAQ,aAAa,IAAI,aAAa,QAAQ,IAAI,YAAY;AAC9E;AAGA,SAAS,SAAS,KAAsC;AACtD,QAAM,OAAO,IAAI;AACjB,SAAO,gBAAgB,IAAI,KAAK,IAAI,EACjC,IAAI,CAAC,UAAU,KAAK,KAAK,CAAC,EAC1B,OAAO,CAAC,QAAuB,OAAO,QAAQ,YAAY,QAAQ,EAAE;AACzE;AAOO,SAAS,aAAa,KAAsC;AACjE,QAAM,OAAO,CAAC,IAAI,SAAS,GAAG,SAAS,GAAG,CAAC;AAC3C,aAAW,OAAO,OAAO,OAAO,IAAI,UAAU,CAAC,CAAC,GAAG;AACjD,QAAI,CAAC,YAAY,GAAG,EAAG,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