@quatronic/sdk 0.7.1-rc.8 → 0.7.1-test.167ddea

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 (101) hide show
  1. package/dist/chunk-5RAO3LPF.js +116 -0
  2. package/dist/chunk-5RAO3LPF.js.map +1 -0
  3. package/dist/{chunk-G7VPNC6M.js → chunk-IFESUTF2.js} +21 -100
  4. package/dist/chunk-IFESUTF2.js.map +1 -0
  5. package/dist/{chunk-2AYDFLKR.js → chunk-NMJOF3ZM.js} +6 -104
  6. package/dist/chunk-NMJOF3ZM.js.map +1 -0
  7. package/dist/chunk-P7HNHLW7.js +65 -0
  8. package/dist/chunk-P7HNHLW7.js.map +1 -0
  9. package/dist/chunk-POZI4OKJ.js +20 -0
  10. package/dist/chunk-POZI4OKJ.js.map +1 -0
  11. package/dist/chunk-TPBRMW5N.js +197 -0
  12. package/dist/chunk-TPBRMW5N.js.map +1 -0
  13. package/dist/chunk-YFZB5EW6.js +107 -0
  14. package/dist/chunk-YFZB5EW6.js.map +1 -0
  15. package/dist/cli/legacy/qdc-sourcemaps.js +16 -6
  16. package/dist/cli/skills-postinstall.js +4 -3
  17. package/dist/cli/skills.js +4 -3
  18. package/dist/cli/sourcemaps.js +16 -6
  19. package/dist/integrations/index.d.ts +3 -75
  20. package/dist/integrations/index.js +6 -4
  21. package/dist/mail/index.d.ts +9 -0
  22. package/dist/mail/index.js +26 -0
  23. package/dist/mail/index.js.map +1 -0
  24. package/dist/next/auth/index.js +2 -152
  25. package/dist/next/auth/index.js.map +1 -1
  26. package/dist/next/boot/index.d.ts +39 -0
  27. package/dist/next/boot/index.js +22 -0
  28. package/dist/next/boot/index.js.map +1 -0
  29. package/dist/next/db/index.d.ts +27 -1
  30. package/dist/next/db/index.js +45 -3
  31. package/dist/next/db/index.js.map +1 -1
  32. package/dist/next/global-error/index.d.ts +9 -0
  33. package/dist/next/global-error/index.js +17 -0
  34. package/dist/next/global-error/index.js.map +1 -0
  35. package/dist/next/integrations/index.d.ts +2 -1
  36. package/dist/next/integrations/index.js +6 -4
  37. package/dist/next/platform/index.d.ts +19 -0
  38. package/dist/next/platform/index.js +44 -0
  39. package/dist/next/platform/index.js.map +1 -0
  40. package/dist/next/security/index.d.ts +23 -1
  41. package/dist/next/security/index.js +40 -57
  42. package/dist/next/security/index.js.map +1 -1
  43. package/dist/next/security/testing.js +10 -1
  44. package/dist/next/security/testing.js.map +1 -1
  45. package/dist/next/sentry/client.js +2 -1
  46. package/dist/next/sentry/client.js.map +1 -1
  47. package/dist/next/sentry/index.d.ts +1 -0
  48. package/dist/next/sentry/index.js +5 -1
  49. package/dist/next/sentry/index.js.map +1 -1
  50. package/dist/next/sentry/register.js +6 -13
  51. package/dist/next/sentry/register.js.map +1 -1
  52. package/dist/node/boot/index.d.ts +9 -0
  53. package/dist/node/boot/index.js +13 -0
  54. package/dist/node/boot/index.js.map +1 -0
  55. package/dist/node/integrations/index.d.ts +2 -1
  56. package/dist/node/integrations/index.js +6 -4
  57. package/dist/node/sentry/index.d.ts +3 -0
  58. package/dist/node/sentry/index.js +7 -0
  59. package/dist/node/sentry/index.js.map +1 -0
  60. package/dist/node/sentry/register.js +2 -1
  61. package/dist/node/sentry/register.js.map +1 -1
  62. package/dist/node-YQDRNIYH.js +33 -0
  63. package/dist/node-YQDRNIYH.js.map +1 -0
  64. package/dist/types-Cl7g4ego.d.ts +80 -0
  65. package/migrations/bootstrap-qore-env/codemod.mjs +77 -0
  66. package/migrations/bootstrap-qore-env/instructions.md +28 -0
  67. package/migrations/bootstrap-qore-env/meta.json +7 -0
  68. package/migrations/global-error/codemod.mjs +28 -0
  69. package/migrations/global-error/instructions.md +26 -0
  70. package/migrations/global-error/meta.json +7 -0
  71. package/migrations/local-db-port/codemod.mjs +61 -0
  72. package/migrations/local-db-port/instructions.md +45 -0
  73. package/migrations/local-db-port/meta.json +7 -0
  74. package/migrations/mail-reexport/codemod.mjs +64 -0
  75. package/migrations/mail-reexport/instructions.md +27 -0
  76. package/migrations/mail-reexport/meta.json +7 -0
  77. package/migrations/no-raw-fetch/meta.json +1 -1
  78. package/migrations/platform-routes/codemod.mjs +45 -0
  79. package/migrations/platform-routes/instructions.md +30 -0
  80. package/migrations/platform-routes/meta.json +7 -0
  81. package/migrations/qore-boot/codemod.mjs +271 -0
  82. package/migrations/qore-boot/instructions.md +74 -0
  83. package/migrations/qore-boot/meta.json +7 -0
  84. package/migrations/qore-proxy/codemod.mjs +88 -0
  85. package/migrations/qore-proxy/instructions.md +56 -0
  86. package/migrations/qore-proxy/meta.json +7 -0
  87. package/migrations/run.mjs +334 -0
  88. package/migrations/sourcemaps-finalize/codemod.mjs +63 -0
  89. package/migrations/sourcemaps-finalize/instructions.md +56 -0
  90. package/migrations/sourcemaps-finalize/meta.json +7 -0
  91. package/package.json +27 -2
  92. package/skills/catalog.json +1 -0
  93. package/skills/qore-add-env-key/SKILL.md +57 -0
  94. package/skills/qore-add-integration/SKILL.next.md +13 -7
  95. package/skills/qore-add-integration/SKILL.node.md +13 -7
  96. package/skills/qore-author-skill/SKILL.md +1 -0
  97. package/workspace-requirements.json +4 -0
  98. package/dist/chunk-2AYDFLKR.js.map +0 -1
  99. package/dist/chunk-BJN7YE63.js +0 -46
  100. package/dist/chunk-BJN7YE63.js.map +0 -1
  101. package/dist/chunk-G7VPNC6M.js.map +0 -1
@@ -0,0 +1,197 @@
1
+ import {
2
+ resolvePostgresConfig
3
+ } from "./chunk-4MBB2UQW.js";
4
+
5
+ // src/db-core/migration-db.ts
6
+ import { Pool } from "pg";
7
+ import { drizzle } from "drizzle-orm/node-postgres";
8
+ import { sql } from "drizzle-orm";
9
+ function createMigrationDb(databaseUrl) {
10
+ const pool = new Pool(resolvePostgresConfig(databaseUrl));
11
+ return { db: drizzle(pool), close: () => pool.end() };
12
+ }
13
+ function parseRoleFromUrl(databaseUrl) {
14
+ return decodeURIComponent(new URL(databaseUrl).username);
15
+ }
16
+ async function isCurrentUser(db, role) {
17
+ const result = await db.execute(
18
+ sql.raw(`SELECT current_user AS "current_user"`)
19
+ );
20
+ return result.rows[0]?.current_user === role;
21
+ }
22
+ async function grantRuntimeDefaultPrivileges(db, schema, runtimeRole) {
23
+ if (await isCurrentUser(db, runtimeRole)) {
24
+ return;
25
+ }
26
+ await db.execute(
27
+ sql.raw(`GRANT USAGE ON SCHEMA "${schema}" TO "${runtimeRole}"`)
28
+ );
29
+ await db.execute(
30
+ sql.raw(
31
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA "${schema}" GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO "${runtimeRole}"`
32
+ )
33
+ );
34
+ await db.execute(
35
+ sql.raw(
36
+ `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA "${schema}" TO "${runtimeRole}"`
37
+ )
38
+ );
39
+ }
40
+
41
+ // src/auth-core/migrate.ts
42
+ import { sql as sql2 } from "drizzle-orm";
43
+ var MIGRATION_0001_SCHEMA = `
44
+ CREATE SCHEMA IF NOT EXISTS auth;
45
+ `;
46
+ var MIGRATION_0001_TABLES = `
47
+ CREATE TABLE IF NOT EXISTS auth.sessions (
48
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
49
+ user_sub varchar(64) NOT NULL,
50
+ user_email varchar(320),
51
+ organization_id varchar(64),
52
+ organization_alias varchar(255),
53
+ access_token text NOT NULL,
54
+ access_expires_at timestamptz NOT NULL,
55
+ refresh_ct bytea NOT NULL,
56
+ refresh_iv bytea NOT NULL,
57
+ refresh_expires_at timestamptz NOT NULL,
58
+ created_at timestamptz NOT NULL DEFAULT now(),
59
+ updated_at timestamptz NOT NULL DEFAULT now(),
60
+ revoked_at timestamptz
61
+ );
62
+
63
+ CREATE INDEX IF NOT EXISTS ix_auth_sessions_user_sub
64
+ ON auth.sessions(user_sub) WHERE revoked_at IS NULL;
65
+
66
+ CREATE TABLE IF NOT EXISTS auth.login_state (
67
+ state varchar(128) PRIMARY KEY,
68
+ code_verifier varchar(255) NOT NULL,
69
+ redirect_path text NOT NULL DEFAULT '/',
70
+ created_at timestamptz NOT NULL DEFAULT now(),
71
+ expires_at timestamptz NOT NULL
72
+ );
73
+
74
+ CREATE INDEX IF NOT EXISTS ix_auth_login_state_expires
75
+ ON auth.login_state(expires_at);
76
+ `;
77
+ var MIGRATION_0002_ID_TOKEN = `
78
+ ALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS id_token text;
79
+ `;
80
+ var MIGRATION_0003_FORCED_REAUTH = `
81
+ ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS forced_reauth boolean NOT NULL DEFAULT false;
82
+ `;
83
+ var MIGRATION_0004_NONCE = `
84
+ ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS nonce varchar(128);
85
+ `;
86
+ var MIGRATION_0005_RETRIED = `
87
+ ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS retried boolean NOT NULL DEFAULT false;
88
+ `;
89
+ var MIGRATION_0006_PENDING_CONFIRM = `
90
+ ALTER TABLE auth.sessions
91
+ ADD COLUMN IF NOT EXISTS pending_identity_confirm boolean NOT NULL DEFAULT false;
92
+ `;
93
+ var MIGRATION_0007_EXPECTED_IDENTITY = `
94
+ ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);
95
+ ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);
96
+ `;
97
+ async function probe(db, expression) {
98
+ const result = await db.execute(
99
+ sql2.raw(`SELECT (${expression}) AS "applied"`)
100
+ );
101
+ return result.rows[0]?.applied === true;
102
+ }
103
+ var schemaExists = (schema) => (db) => probe(db, `EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '${schema}')`);
104
+ var relationsExist = (...relations) => (db) => {
105
+ const tuples = relations.map(([schema, name]) => `('${schema}','${name}')`).join(", ");
106
+ return probe(
107
+ db,
108
+ `(SELECT count(*) FROM pg_class c
109
+ JOIN pg_namespace n ON n.oid = c.relnamespace
110
+ WHERE (n.nspname, c.relname) IN (${tuples})) = ${relations.length}`
111
+ );
112
+ };
113
+ var columnsExist = (...columns) => (db) => {
114
+ const tuples = columns.map(([schema, table, column]) => `('${schema}','${table}','${column}')`).join(", ");
115
+ return probe(
116
+ db,
117
+ `(SELECT count(*) FROM pg_attribute a
118
+ JOIN pg_class c ON c.oid = a.attrelid
119
+ JOIN pg_namespace n ON n.oid = c.relnamespace
120
+ WHERE a.attnum > 0 AND NOT a.attisdropped
121
+ AND (n.nspname, c.relname, a.attname) IN (${tuples})) = ${columns.length}`
122
+ );
123
+ };
124
+ var MIGRATIONS = [
125
+ {
126
+ name: "0001_init:schema",
127
+ sql: MIGRATION_0001_SCHEMA,
128
+ isApplied: schemaExists("auth")
129
+ },
130
+ {
131
+ name: "0001_init:tables",
132
+ sql: MIGRATION_0001_TABLES,
133
+ isApplied: relationsExist(
134
+ ["auth", "sessions"],
135
+ ["auth", "ix_auth_sessions_user_sub"],
136
+ ["auth", "login_state"],
137
+ ["auth", "ix_auth_login_state_expires"]
138
+ )
139
+ },
140
+ {
141
+ name: "0002_id_token",
142
+ sql: MIGRATION_0002_ID_TOKEN,
143
+ isApplied: columnsExist(["auth", "sessions", "id_token"])
144
+ },
145
+ {
146
+ name: "0003_forced_reauth",
147
+ sql: MIGRATION_0003_FORCED_REAUTH,
148
+ isApplied: columnsExist(["auth", "login_state", "forced_reauth"])
149
+ },
150
+ {
151
+ name: "0004_nonce",
152
+ sql: MIGRATION_0004_NONCE,
153
+ isApplied: columnsExist(["auth", "login_state", "nonce"])
154
+ },
155
+ {
156
+ name: "0005_retried",
157
+ sql: MIGRATION_0005_RETRIED,
158
+ isApplied: columnsExist(["auth", "login_state", "retried"])
159
+ },
160
+ {
161
+ name: "0006_pending_confirm",
162
+ sql: MIGRATION_0006_PENDING_CONFIRM,
163
+ isApplied: columnsExist(["auth", "sessions", "pending_identity_confirm"])
164
+ },
165
+ {
166
+ name: "0007_expected_identity",
167
+ sql: MIGRATION_0007_EXPECTED_IDENTITY,
168
+ isApplied: columnsExist(
169
+ ["auth", "login_state", "expected_sub"],
170
+ ["auth", "login_state", "expected_email"]
171
+ )
172
+ }
173
+ ];
174
+ async function runAuthMigrations(db, opts = {}) {
175
+ for (const migration of MIGRATIONS) {
176
+ try {
177
+ if (await migration.isApplied(db)) {
178
+ continue;
179
+ }
180
+ await db.execute(sql2.raw(migration.sql));
181
+ } catch (err) {
182
+ const message = err instanceof Error ? err.message : String(err);
183
+ throw new Error(`auth migration "${migration.name}" failed: ${message}`, { cause: err });
184
+ }
185
+ }
186
+ if (opts.runtimeRole) {
187
+ await grantRuntimeDefaultPrivileges(db, "auth", opts.runtimeRole);
188
+ }
189
+ }
190
+
191
+ export {
192
+ createMigrationDb,
193
+ parseRoleFromUrl,
194
+ grantRuntimeDefaultPrivileges,
195
+ runAuthMigrations
196
+ };
197
+ //# sourceMappingURL=chunk-TPBRMW5N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/db-core/migration-db.ts","../src/auth-core/migrate.ts"],"sourcesContent":["import { Pool } from \"pg\"\nimport { drizzle, type NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { sql } from \"drizzle-orm\"\nimport { resolvePostgresConfig } from \"./postgres-config\"\n\nexport interface MigrationDb {\n readonly db: NodePgDatabase\n readonly close: () => Promise<void>\n}\n\n// Migrations get their own short-lived pool, separate from the app's\n// long-lived runtime pool — it exists only for the duration of the boot-time\n// migration call and is torn down immediately after.\nexport function createMigrationDb(databaseUrl: string): MigrationDb {\n const pool = new Pool(resolvePostgresConfig(databaseUrl))\n return { db: drizzle(pool), close: () => pool.end() }\n}\n\n// The addon's regular/admin credentials are both delivered as full DSNs\n// (POSTGRES_URI / POSTGRES_URI_ADMIN — see the templates SecretGroup\n// addonDependencies mapping), not as separate username/password fields, so\n// callers that need the runtime role's name for a GRANT statement parse it\n// out of the runtime connection string instead of reading it separately.\nexport function parseRoleFromUrl(databaseUrl: string): string {\n return decodeURIComponent(new URL(databaseUrl).username)\n}\n\n// `current_user` is compared as the server reports it, so the comparison holds\n// for a role whose name needed quoting in the DSN.\nasync function isCurrentUser(db: NodePgDatabase, role: string): Promise<boolean> {\n const result = await db.execute<{ current_user: string }>(\n sql.raw(`SELECT current_user AS \"current_user\"`),\n )\n return result.rows[0]?.current_user === role\n}\n\n// Safe to call on every boot, whether or not the migrator and runtime roles\n// are the same (the fallback case for environments that haven't opted into a\n// separate migration role yet — see MIGRATION_DATABASE_URL fallback in\n// portal-api/portal-web). ALTER DEFAULT PRIVILEGES only binds objects created\n// after it runs, so this also explicitly grants on ALL TABLES to cover\n// whatever this same run just created.\n//\n// The fallback case is skipped outright rather than issued anyway: granting a\n// role privileges to itself is either redundant (it owns the objects, so it\n// already holds everything) or impossible (it does not, so GRANT raises `must\n// be owner of table …` / `permission denied for schema …`). Issuing it made\n// that second case a boot-time failure on an environment where there was\n// nothing whatsoever to grant.\nexport async function grantRuntimeDefaultPrivileges(\n db: NodePgDatabase,\n schema: string,\n runtimeRole: string,\n): Promise<void> {\n if (await isCurrentUser(db, runtimeRole)) {\n return\n }\n await db.execute(\n sql.raw(`GRANT USAGE ON SCHEMA \"${schema}\" TO \"${runtimeRole}\"`),\n )\n await db.execute(\n sql.raw(\n `ALTER DEFAULT PRIVILEGES IN SCHEMA \"${schema}\" GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO \"${runtimeRole}\"`,\n ),\n )\n await db.execute(\n sql.raw(\n `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA \"${schema}\" TO \"${runtimeRole}\"`,\n ),\n )\n}\n","import { sql } from \"drizzle-orm\"\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { grantRuntimeDefaultPrivileges } from \"../db-core/migration-db\"\n\n// Migrations are inlined as string constants rather than read from .sql files\n// at runtime. A runtime `readFile` does not survive bundlers that only trace\n// JS — notably Next.js standalone output, where the .sql is omitted and the\n// read ENOENTs, crashing the instrumentation hook and 500-ing the whole app.\n// Inlining keeps the SQL in the bundled JS so it works in every consumer.\n\n// Split out of what used to be a single MIGRATION_0001_INIT on purpose, and\n// the reason generalises to every statement below it: **Postgres checks the\n// connecting role's privileges before it evaluates `IF NOT EXISTS`.** So an\n// already-applied statement is not a no-op for a role that lacks the right —\n// it is an error:\n//\n// - `CREATE SCHEMA IF NOT EXISTS auth` needs CREATE on the *database* →\n// `permission denied for database <db>` (SQLSTATE 42501)\n// - `CREATE INDEX IF NOT EXISTS` and `ALTER TABLE ... ADD COLUMN IF NOT\n// EXISTS` need *ownership* of the table → `must be owner of table\n// sessions` (also 42501)\n//\n// That is the normal shape of a least-privileged runtime role against an\n// already-provisioned database, and because migrations run in order one such\n// error aborts every statement after it. It has now bitten staging twice: the\n// first time `login_state.forced_reauth` never landed and every\n// `/api/auth/login` 500'd; the second time `0001_init:tables` failed on its\n// `CREATE INDEX` with `must be owner of table sessions`, again blocking every\n// later ALTER even though there was nothing at all to do.\n//\n// So each migration below carries an `isApplied` catalog probe and the runner\n// skips it when its effect is already present. Catalog lookups need nothing\n// beyond CONNECT, so a role with only DML inside an up-to-date `auth` schema\n// gets through cleanly, while a migration that genuinely still has work to do\n// is attempted and — if the role cannot do it — fails loudly, by name.\nconst MIGRATION_0001_SCHEMA = `\nCREATE SCHEMA IF NOT EXISTS auth;\n`\n\nconst MIGRATION_0001_TABLES = `\nCREATE TABLE IF NOT EXISTS auth.sessions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n user_sub varchar(64) NOT NULL,\n user_email varchar(320),\n organization_id varchar(64),\n organization_alias varchar(255),\n access_token text NOT NULL,\n access_expires_at timestamptz NOT NULL,\n refresh_ct bytea NOT NULL,\n refresh_iv bytea NOT NULL,\n refresh_expires_at timestamptz NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n revoked_at timestamptz\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_sessions_user_sub\n ON auth.sessions(user_sub) WHERE revoked_at IS NULL;\n\nCREATE TABLE IF NOT EXISTS auth.login_state (\n state varchar(128) PRIMARY KEY,\n code_verifier varchar(255) NOT NULL,\n redirect_path text NOT NULL DEFAULT '/',\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_login_state_expires\n ON auth.login_state(expires_at);\n`\n\n// The KC ID token, so RP-initiated logout can pass it as `id_token_hint` —\n// without it, Keycloak's end-session endpoint falls back to showing a logout\n// confirmation page. Nullable: existing sessions predate this column until\n// their next login or token refresh backfills it.\nconst MIGRATION_0002_ID_TOKEN = `\nALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS id_token text;\n`\n\n// Records that this login asked Keycloak to re-authenticate (prompt=login +\n// max_age=0). The callback needs it to know whether the ID token's auth_time\n// MUST prove a fresh authentication (OIDC 3.1.2.1) — without the flag it cannot\n// tell a forced login from an ordinary SSO continuation.\nconst MIGRATION_0003_FORCED_REAUTH = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS forced_reauth boolean NOT NULL DEFAULT false;\n`\n\n// OIDC 3.1.3.7 (11): the nonce sent on the authorization request must be\n// checked against the ID token's claim. Nullable because rows written by an\n// older build have none; the callback treats a null nonce on the row as\n// \"nothing to check\" so an in-flight login survives the deploy.\nconst MIGRATION_0004_NONCE = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS nonce varchar(128);\n`\n\n// Bounds the one-and-only restart the callback grants on Keycloak's explicit\n// \"start over\" signals (authentication_expired / login_required). The\n// callback URL is Keycloak's fixed redirect_uri, so Keycloak never echoes our\n// own query parameters back to it — a guard read off the callback's query\n// string can never fire in production. The restarted login (our own request\n// to /api/auth/login?retried=1) stamps this column on the NEW row instead, so\n// the second callback can see it on the row rather than in a URL Keycloak\n// controls. NOT NULL DEFAULT false: every row, old or new, starts un-retried.\nconst MIGRATION_0005_RETRIED = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS retried boolean NOT NULL DEFAULT false;\n`\n\n// A session created for an identity that did not match what the login expected\n// exists, holds real tokens, and grants nothing until a human confirms it.\n//\n// DELIBERATELY `DEFAULT false` rather than a nullable column with a backfill:\n// these migrations re-run on every app start, so an `UPDATE ... WHERE\n// pending_identity_confirm IS NULL` would confirm every row still awaiting a\n// human on the next deploy — silently adopting exactly the identity this\n// mechanism exists to stop. A default means pre-existing rows are already\n// confirmed, which is correct: they were issued under the old rules.\nconst MIGRATION_0006_PENDING_CONFIRM = `\nALTER TABLE auth.sessions\n ADD COLUMN IF NOT EXISTS pending_identity_confirm boolean NOT NULL DEFAULT false;\n`\n\n// Who this login was supposed to end up as: the subject of the session being\n// replaced, and/or the address the user typed. The callback compares Keycloak's\n// answer against these instead of adopting whatever comes back. Nullable: a\n// clean first login on a fresh browser expects nobody in particular.\nconst MIGRATION_0007_EXPECTED_IDENTITY = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);\n`\n\ninterface Migration {\n // Named so a failure can say *which* statement broke — see the catch below.\n readonly name: string\n readonly sql: string\n // \"Is this migration's effect already present?\" Answered from the catalogs\n // only, so it never needs a privilege the migration itself would need. A\n // partially-applied migration must answer `false` (the SQL is written to be\n // idempotent, so re-running the applied half is harmless).\n readonly isApplied: (db: NodePgDatabase) => Promise<boolean>\n // A migration may only add to the schema: a prod rollback keeps the\n // database, and the previous release must still work on it\n // (scripts/migration-lint.mjs refuses anything else). `true` marks the rare\n // migration that removes or tightens something on purpose; ship it only once\n // no prod still runs a version that reads the old shape.\n readonly contract?: boolean\n}\n\n// All probes funnel through here: one boolean expression, evaluated by the\n// server. Every one of them reads `pg_catalog` directly rather than going\n// through `to_regclass`/`to_regnamespace` or `information_schema`, both of\n// which are privilege-sensitive in ways that defeat the purpose: `to_regclass`\n// resolves the name and so raises `permission denied for schema auth` for a\n// role without USAGE, and `information_schema.columns` silently hides columns\n// the role holds no privilege on — reporting an applied migration as missing\n// and sending us straight into the ALTER we were trying to avoid. The catalogs\n// themselves are world-readable.\nasync function probe(db: NodePgDatabase, expression: string): Promise<boolean> {\n const result = await db.execute<{ applied: boolean }>(\n sql.raw(`SELECT (${expression}) AS \"applied\"`),\n )\n return result.rows[0]?.applied === true\n}\n\nconst schemaExists = (schema: string) => (db: NodePgDatabase) =>\n probe(db, `EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '${schema}')`)\n\n// Tables and indexes alike — both live in `pg_class`.\nconst relationsExist =\n (...relations: readonly (readonly [schema: string, name: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = relations.map(([schema, name]) => `('${schema}','${name}')`).join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE (n.nspname, c.relname) IN (${tuples})) = ${relations.length}`,\n )\n }\n\nconst columnsExist =\n (...columns: readonly (readonly [schema: string, table: string, column: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = columns\n .map(([schema, table, column]) => `('${schema}','${table}','${column}')`)\n .join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE a.attnum > 0 AND NOT a.attisdropped\n AND (n.nspname, c.relname, a.attname) IN (${tuples})) = ${columns.length}`,\n )\n }\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n name: \"0001_init:schema\",\n sql: MIGRATION_0001_SCHEMA,\n isApplied: schemaExists(\"auth\"),\n },\n {\n name: \"0001_init:tables\",\n sql: MIGRATION_0001_TABLES,\n isApplied: relationsExist(\n [\"auth\", \"sessions\"],\n [\"auth\", \"ix_auth_sessions_user_sub\"],\n [\"auth\", \"login_state\"],\n [\"auth\", \"ix_auth_login_state_expires\"],\n ),\n },\n {\n name: \"0002_id_token\",\n sql: MIGRATION_0002_ID_TOKEN,\n isApplied: columnsExist([\"auth\", \"sessions\", \"id_token\"]),\n },\n {\n name: \"0003_forced_reauth\",\n sql: MIGRATION_0003_FORCED_REAUTH,\n isApplied: columnsExist([\"auth\", \"login_state\", \"forced_reauth\"]),\n },\n {\n name: \"0004_nonce\",\n sql: MIGRATION_0004_NONCE,\n isApplied: columnsExist([\"auth\", \"login_state\", \"nonce\"]),\n },\n {\n name: \"0005_retried\",\n sql: MIGRATION_0005_RETRIED,\n isApplied: columnsExist([\"auth\", \"login_state\", \"retried\"]),\n },\n {\n name: \"0006_pending_confirm\",\n sql: MIGRATION_0006_PENDING_CONFIRM,\n isApplied: columnsExist([\"auth\", \"sessions\", \"pending_identity_confirm\"]),\n },\n {\n name: \"0007_expected_identity\",\n sql: MIGRATION_0007_EXPECTED_IDENTITY,\n isApplied: columnsExist(\n [\"auth\", \"login_state\", \"expected_sub\"],\n [\"auth\", \"login_state\", \"expected_email\"],\n ),\n },\n]\n\nexport interface RunAuthMigrationsOptions {\n // When provided, grants this role SELECT/INSERT/UPDATE/DELETE on every\n // table in the `auth` schema — both ones this call just created and ones a\n // future boot's migrations will create. Omit for a single-role setup (the\n // fallback state of an environment that hasn't opted into a separate\n // migration role yet); passing it is what makes it safe for `db` to\n // connect as an admin/owner role while the app itself never does.\n readonly runtimeRole?: string\n}\n\nexport async function runAuthMigrations(\n db: NodePgDatabase,\n opts: RunAuthMigrationsOptions = {},\n): Promise<void> {\n for (const migration of MIGRATIONS) {\n try {\n if (await migration.isApplied(db)) {\n // Already there — do not issue the statement at all. See the comment\n // above MIGRATION_0001_SCHEMA for why relying on `IF NOT EXISTS` to make\n // it a no-op is not safe under every role.\n continue\n }\n await db.execute(sql.raw(migration.sql))\n } catch (err) {\n // Re-thrown, not swallowed: the caller decides what to do with a failed\n // migration. Naming the statement is what turns a bare \"permission\n // denied for database x\" into something you can actually act on; the\n // `cause` keeps the original Postgres error (code, detail, etc.) intact.\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`auth migration \"${migration.name}\" failed: ${message}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AW;AAAA,EAClE;AACF;","names":["sql","sql"]}
@@ -0,0 +1,107 @@
1
+ import {
2
+ setTelemetryHooks
3
+ } from "./chunk-MET4SIMB.js";
4
+ import {
5
+ makeDevSinkTransport
6
+ } from "./chunk-7ASQHY7O.js";
7
+ import {
8
+ SECRET_PARAMS,
9
+ scrubEvent,
10
+ scrubLog,
11
+ scrubSpan
12
+ } from "./chunk-IFESUTF2.js";
13
+
14
+ // src/sentry-core/noise.ts
15
+ var NOISE_EXACT = /* @__PURE__ */ new Set(["/favicon.ico", "/api/auth/me"]);
16
+ var RSC_QUERY_RE = /[?&]_rsc=/;
17
+ function isNoisePath(rawUrl, opts = {}) {
18
+ if (RSC_QUERY_RE.test(rawUrl)) return true;
19
+ const path = (rawUrl.split("?")[0] ?? "").trim();
20
+ if (!path) return false;
21
+ if (NOISE_EXACT.has(path)) return true;
22
+ if (path.endsWith(".map")) return true;
23
+ if (path.startsWith("/_next/")) return true;
24
+ if ((opts.noisePrefixes ?? []).some((p) => path.startsWith(p))) return true;
25
+ if (opts.healthPath && path === opts.healthPath) return true;
26
+ return false;
27
+ }
28
+
29
+ // src/sentry-core/sampler.ts
30
+ var MUTATIONS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
31
+ var str = (v) => typeof v === "string" && v ? v : void 0;
32
+ function pathOf(ctx) {
33
+ const a = ctx.attributes ?? {};
34
+ return str(a["url.path"]) ?? str(a["http.target"]) ?? ctx.name.split(" ")[1];
35
+ }
36
+ function createTracesSampler(policy) {
37
+ return (ctx) => {
38
+ const path = pathOf(ctx);
39
+ if (path && isNoisePath(path, { healthPath: policy.healthPath })) return 0;
40
+ const a = ctx.attributes ?? {};
41
+ const method = (str(a["http.request.method"]) ?? str(a["http.method"]) ?? "").toUpperCase();
42
+ if (MUTATIONS.has(method)) return 1;
43
+ return ctx.inheritOrSampleWith(policy.production ? policy.readRate : 1);
44
+ };
45
+ }
46
+
47
+ // src/sentry-core/options.ts
48
+ function isTty() {
49
+ try {
50
+ return typeof process !== "undefined" && process.stdout?.isTTY === true;
51
+ } catch {
52
+ return false;
53
+ }
54
+ }
55
+ function buildOptions(runtime, cfg) {
56
+ return {
57
+ dsn: cfg.dsn,
58
+ environment: cfg.environment,
59
+ release: cfg.release,
60
+ sendDefaultPii: false,
61
+ dataCollection: {
62
+ userInfo: false,
63
+ cookies: false,
64
+ httpHeaders: { request: false, response: false },
65
+ httpBodies: [],
66
+ databaseQueryData: false,
67
+ stackFrameVariables: false,
68
+ genAI: { inputs: false, outputs: false },
69
+ urlQueryParams: { deny: [...SECRET_PARAMS] }
70
+ },
71
+ enableLogs: true,
72
+ tracesSampler: createTracesSampler({
73
+ production: cfg.environment === "production",
74
+ readRate: cfg.readSampleRate,
75
+ healthPath: cfg.healthPath
76
+ }),
77
+ tracePropagationTargets: runtime === "browser" ? [/^\//] : cfg.connOrigins,
78
+ beforeSend: scrubEvent,
79
+ beforeSendTransaction: scrubEvent,
80
+ beforeSendLog: scrubLog,
81
+ beforeSendSpan: scrubSpan,
82
+ initialScope: { tags: cfg.tags },
83
+ ...cfg.local ? { transport: makeDevSinkTransport({ traces: cfg.devTraces ?? "line", color: runtime !== "browser" && isTty() }) } : {}
84
+ };
85
+ }
86
+
87
+ // src/sentry-core/init.ts
88
+ var DONE = /* @__PURE__ */ Symbol.for("@quatronic/sdk.sentry-initialised");
89
+ var holder = globalThis;
90
+ function initSentry(sentry, runtime, cfg, extra = {}) {
91
+ if (!cfg || holder[DONE]) return false;
92
+ holder[DONE] = true;
93
+ try {
94
+ const extras = typeof extra === "function" ? extra() : extra;
95
+ sentry.init({ ...extras, ...buildOptions(runtime, cfg) });
96
+ } catch (err) {
97
+ console.error("[qore] Sentry init failed", err);
98
+ return false;
99
+ }
100
+ setTelemetryHooks({ log: sentry.logger, setUser: (u) => sentry.setUser(u) });
101
+ return true;
102
+ }
103
+
104
+ export {
105
+ initSentry
106
+ };
107
+ //# sourceMappingURL=chunk-YFZB5EW6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sentry-core/noise.ts","../src/sentry-core/sampler.ts","../src/sentry-core/options.ts","../src/sentry-core/init.ts"],"sourcesContent":["// Pure predicate deciding whether an HTTP request is infrastructural noise that\n// should never become a span: a `_rsc` query param, `/favicon.ico`, the SDK's\n// session poll, source maps, `/_next/*`, plus the caller's prefixes and health path.\n\nexport interface NoiseFilterOptions {\n healthPath?: string\n noisePrefixes?: string[]\n}\n\n// `/api/auth/me` is the SDK's own session poll (PortalProvider fires it on every\n// page mount): a heartbeat, not user activity.\nconst NOISE_EXACT = new Set([\"/favicon.ico\", \"/api/auth/me\"])\n\n// React Server Components navigations/prefetches carry a `?_rsc=` query param;\n// they look like real routes, so a path-prefix filter misses them.\nconst RSC_QUERY_RE = /[?&]_rsc=/\n\nexport function isNoisePath(rawUrl: string, opts: NoiseFilterOptions = {}): boolean {\n if (RSC_QUERY_RE.test(rawUrl)) return true\n const path = (rawUrl.split(\"?\")[0] ?? \"\").trim()\n if (!path) return false\n if (NOISE_EXACT.has(path)) return true\n if (path.endsWith(\".map\")) return true\n if (path.startsWith(\"/_next/\")) return true\n if ((opts.noisePrefixes ?? []).some((p) => path.startsWith(p))) return true\n if (opts.healthPath && path === opts.healthPath) return true\n return false\n}\n","import { isNoisePath } from \"./noise\"\n\nexport interface SamplingContextLike {\n name: string\n attributes?: Record<string, unknown>\n inheritOrSampleWith: (fallback: number) => number\n}\n\nconst MUTATIONS = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"])\n\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" && v ? v : undefined)\n\nfunction pathOf(ctx: SamplingContextLike): string | undefined {\n const a = ctx.attributes ?? {}\n return str(a[\"url.path\"]) ?? str(a[\"http.target\"]) ?? ctx.name.split(\" \")[1]\n}\n\nexport function createTracesSampler(policy: { production: boolean; readRate: number; healthPath: string }) {\n return (ctx: SamplingContextLike): number => {\n const path = pathOf(ctx)\n if (path && isNoisePath(path, { healthPath: policy.healthPath })) return 0\n const a = ctx.attributes ?? {}\n const method = (str(a[\"http.request.method\"]) ?? str(a[\"http.method\"]) ?? \"\").toUpperCase()\n if (MUTATIONS.has(method)) return 1\n return ctx.inheritOrSampleWith(policy.production ? policy.readRate : 1)\n }\n}\n","import { makeDevSinkTransport } from \"./dev-sink\"\nimport type { SentryConfig } from \"./env\"\nimport { createTracesSampler, type SamplingContextLike } from \"./sampler\"\nimport { SECRET_PARAMS, scrubEvent, scrubLog, scrubSpan } from \"./scrub\"\n\nexport type Runtime = \"node\" | \"edge\" | \"browser\"\n\n// Structural copy of @sentry/core's DataCollection (10.75+): stop PII at collection,\n// the scrubbers stay as the backstop. Older 10.x ignores the unknown option.\nexport interface QoreDataCollection {\n userInfo: false\n cookies: false\n httpHeaders: { request: false; response: false }\n httpBodies: []\n databaseQueryData: false\n stackFrameVariables: false\n genAI: { inputs: false; outputs: false }\n urlQueryParams: { deny: string[] }\n}\n\nexport interface QoreSentryOptions {\n dsn: string\n environment: string\n release?: string\n sendDefaultPii: false\n dataCollection: QoreDataCollection\n enableLogs: true\n tracesSampler: (ctx: SamplingContextLike) => number\n tracePropagationTargets: Array<string | RegExp>\n beforeSend: typeof scrubEvent\n beforeSendTransaction: typeof scrubEvent\n beforeSendLog: typeof scrubLog\n beforeSendSpan: typeof scrubSpan\n initialScope: { tags: Record<string, string> }\n transport?: ReturnType<typeof makeDevSinkTransport>\n}\n\nfunction isTty(): boolean {\n try {\n return typeof process !== \"undefined\" && process.stdout?.isTTY === true\n } catch {\n return false\n }\n}\n\nexport function buildOptions(runtime: Runtime, cfg: SentryConfig): QoreSentryOptions {\n return {\n dsn: cfg.dsn,\n environment: cfg.environment,\n release: cfg.release,\n sendDefaultPii: false,\n dataCollection: {\n userInfo: false,\n cookies: false,\n httpHeaders: { request: false, response: false },\n httpBodies: [],\n databaseQueryData: false,\n stackFrameVariables: false,\n genAI: { inputs: false, outputs: false },\n urlQueryParams: { deny: [...SECRET_PARAMS] },\n },\n enableLogs: true,\n tracesSampler: createTracesSampler({\n production: cfg.environment === \"production\",\n readRate: cfg.readSampleRate,\n healthPath: cfg.healthPath,\n }),\n tracePropagationTargets: runtime === \"browser\" ? [/^\\//] : cfg.connOrigins,\n beforeSend: scrubEvent,\n beforeSendTransaction: scrubEvent,\n beforeSendLog: scrubLog,\n beforeSendSpan: scrubSpan,\n initialScope: { tags: cfg.tags },\n ...(cfg.local\n ? { transport: makeDevSinkTransport({ traces: cfg.devTraces ?? \"line\", color: runtime !== \"browser\" && isTty() }) }\n : {}),\n }\n}\n","import { setTelemetryHooks } from \"../telemetry-hooks\"\nimport type { SentryConfig } from \"./env\"\nimport { buildOptions, type Runtime } from \"./options\"\n\nexport interface SentryLike {\n init(options: object): unknown\n logger: Record<\"debug\" | \"info\" | \"warn\" | \"error\", (msg: string, attrs?: Record<string, string | number | boolean>) => void>\n setUser(user: { id: string } | null): void\n}\n\nconst DONE = Symbol.for(\"@quatronic/sdk.sentry-initialised\")\ntype Holder = { [DONE]?: boolean }\nconst holder = globalThis as Holder\n\n// A factory `extra` runs only once the guard passes, inside the try: integrations\n// such as Replay throw when constructed twice.\nexport function initSentry(\n sentry: SentryLike,\n runtime: Runtime,\n cfg: SentryConfig | null,\n extra: object | (() => object) = {},\n): boolean {\n if (!cfg || holder[DONE]) return false\n holder[DONE] = true\n try {\n const extras = typeof extra === \"function\" ? extra() : extra\n sentry.init({ ...extras, ...buildOptions(runtime, cfg) })\n } catch (err) {\n console.error(\"[qore] Sentry init failed\", err)\n return false\n }\n setTelemetryHooks({ log: sentry.logger, setUser: (u) => sentry.setUser(u) })\n return true\n}\n\nexport function resetSentryInitForTests(): void {\n delete holder[DONE]\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,IAAM,cAAc,oBAAI,IAAI,CAAC,gBAAgB,cAAc,CAAC;AAI5D,IAAM,eAAe;AAEd,SAAS,YAAY,QAAgB,OAA2B,CAAC,GAAY;AAClF,MAAI,aAAa,KAAK,MAAM,EAAG,QAAO;AACtC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Q,MAAM,6BAA6B,GAAG;AAC9C,WAAO;AAAA,EACT;AACA,oBAAkB,EAAE,KAAK,OAAO,QAAQ,SAAS,CAAC,MAAM,OAAO,QAAQ,CAAC,EAAE,CAAC;AAC3E,SAAO;AACT;","names":[]}
@@ -23,13 +23,14 @@ var BUNDLE = /^[a-z0-9][a-z0-9-]{0,31}$/;
23
23
  var SCRIPT = /\.(js|mjs|cjs)$/;
24
24
  var MAPPING_URL = /^\/\/# sourceMappingURL=(\S+)[ \t]*$/gm;
25
25
  var STANDALONE_SERVER = "standalone/.next/server/";
26
+ var isCommand = (cmd) => cmd === "upload" || cmd === "finalize";
26
27
  function parseArgs(argv) {
27
28
  const [cmd, dir, ...rest] = argv;
28
- if (cmd !== "upload" || !dir) return { error: "usage: qore-sourcemaps upload <dir> [--bundle <name>]" };
29
+ if (!isCommand(cmd) || !dir) return { error: "usage: qore-sourcemaps upload|finalize <dir> [--bundle <name>]" };
29
30
  let bundle = "app";
30
31
  if (rest[0] === "--bundle") bundle = rest[1] ?? "";
31
32
  if (!BUNDLE.test(bundle)) return { error: `invalid bundle name: ${bundle}` };
32
- return { dir, bundle };
33
+ return { cmd, dir, bundle };
33
34
  }
34
35
  function nextRoots(has) {
35
36
  if (!has("BUILD_ID") || !has("server")) return null;
@@ -122,11 +123,11 @@ async function runCommand(cmd, args) {
122
123
  env: { ...process.env, COPYFILE_DISABLE: "1" }
123
124
  });
124
125
  }
125
- function walkDir(dir, prefix = "") {
126
+ function walkDir(dir, prefix = "", modules = false) {
126
127
  const out = [];
127
128
  for (const d of readdirSync(join(dir, prefix), { withFileTypes: true })) {
128
129
  const rel = prefix ? `${prefix}/${d.name}` : d.name;
129
- if (d.isDirectory() && d.name !== "node_modules") out.push(...walkDir(dir, rel));
130
+ if (d.isDirectory() && (modules || d.name !== "node_modules")) out.push(...walkDir(dir, rel, modules));
130
131
  else if (d.isFile()) out.push(rel);
131
132
  }
132
133
  return out;
@@ -134,6 +135,7 @@ function walkDir(dir, prefix = "") {
134
135
  var defaultIo = () => ({
135
136
  env: process.env,
136
137
  walk: (dir) => walkDir(dir),
138
+ walkAll: (dir) => walkDir(dir, "", true),
137
139
  exists: existsSync,
138
140
  readText: (p) => readFileSync(p, "utf8"),
139
141
  writeText: (p, t) => writeFileSync(p, t),
@@ -154,11 +156,18 @@ function tryRemove(io, path) {
154
156
  } catch {
155
157
  }
156
158
  }
159
+ function removeAllMaps(io, dir) {
160
+ try {
161
+ for (const p of io.walkAll(dir)) if (p.endsWith(".map")) tryRemove(io, join(dir, p));
162
+ } catch (err) {
163
+ console.warn(`qore-sourcemaps: cleanup skipped: ${describe(err, io.env.QORE_BUILD_UPLOAD_TOKEN)}`);
164
+ }
165
+ }
157
166
  async function main(argv = process.argv.slice(2), io = defaultIo()) {
158
167
  const args = parseArgs(argv);
159
168
  if ("error" in args) {
160
169
  console.warn(`qore-sourcemaps: ${args.error}`);
161
- const dir2 = argv[0] === "upload" ? argv[1] : void 0;
170
+ const dir2 = isCommand(argv[0]) ? argv[1] : void 0;
162
171
  if (dir2 && !dir2.startsWith("-")) {
163
172
  try {
164
173
  for (const m of listMaps(io.walk(dir2))) tryRemove(io, join(dir2, m));
@@ -168,7 +177,7 @@ async function main(argv = process.argv.slice(2), io = defaultIo()) {
168
177
  }
169
178
  return;
170
179
  }
171
- const { dir, bundle } = args;
180
+ const { cmd, dir, bundle } = args;
172
181
  const at = (rel) => join(dir, rel);
173
182
  let maps = [];
174
183
  const scratch = [];
@@ -222,6 +231,7 @@ async function main(argv = process.argv.slice(2), io = defaultIo()) {
222
231
  } finally {
223
232
  for (const m of maps) tryRemove(io, at(m));
224
233
  for (const s of scratch) tryRemove(io, s);
234
+ if (cmd === "finalize") removeAllMaps(io, dir);
225
235
  }
226
236
  }
227
237
  function isMainModule() {
@@ -163,9 +163,10 @@ extension file.
163
163
 
164
164
  ## Contract skills
165
165
 
166
- \`qore-add-integration\`, \`qore-add-connection\`, \`qore-use-permissions\`,
167
- \`qore-observability\` and \`qore-use-database\` produce code the portal reads:
168
- the Integrations tab, connections, roles, Monitoring, the local database. An
166
+ \`qore-add-env-key\`, \`qore-add-integration\`, \`qore-add-connection\`,
167
+ \`qore-use-permissions\`, \`qore-observability\` and \`qore-use-database\`
168
+ produce code the portal reads: the Secrets tab, the Integrations tab,
169
+ connections, roles, Monitoring, the local database. An
169
170
  extension may add to them but not relax them, and turning one off does not turn
170
171
  off the SDK's lint rules that check the same things.
171
172
 
@@ -162,9 +162,10 @@ extension file.
162
162
 
163
163
  ## Contract skills
164
164
 
165
- \`qore-add-integration\`, \`qore-add-connection\`, \`qore-use-permissions\`,
166
- \`qore-observability\` and \`qore-use-database\` produce code the portal reads:
167
- the Integrations tab, connections, roles, Monitoring, the local database. An
165
+ \`qore-add-env-key\`, \`qore-add-integration\`, \`qore-add-connection\`,
166
+ \`qore-use-permissions\`, \`qore-observability\` and \`qore-use-database\`
167
+ produce code the portal reads: the Secrets tab, the Integrations tab,
168
+ connections, roles, Monitoring, the local database. An
168
169
  extension may add to them but not relax them, and turning one off does not turn
169
170
  off the SDK's lint rules that check the same things.
170
171
 
@@ -15,13 +15,14 @@ var BUNDLE = /^[a-z0-9][a-z0-9-]{0,31}$/;
15
15
  var SCRIPT = /\.(js|mjs|cjs)$/;
16
16
  var MAPPING_URL = /^\/\/# sourceMappingURL=(\S+)[ \t]*$/gm;
17
17
  var STANDALONE_SERVER = "standalone/.next/server/";
18
+ var isCommand = (cmd) => cmd === "upload" || cmd === "finalize";
18
19
  function parseArgs(argv) {
19
20
  const [cmd, dir, ...rest] = argv;
20
- if (cmd !== "upload" || !dir) return { error: "usage: qore-sourcemaps upload <dir> [--bundle <name>]" };
21
+ if (!isCommand(cmd) || !dir) return { error: "usage: qore-sourcemaps upload|finalize <dir> [--bundle <name>]" };
21
22
  let bundle = "app";
22
23
  if (rest[0] === "--bundle") bundle = rest[1] ?? "";
23
24
  if (!BUNDLE.test(bundle)) return { error: `invalid bundle name: ${bundle}` };
24
- return { dir, bundle };
25
+ return { cmd, dir, bundle };
25
26
  }
26
27
  function nextRoots(has) {
27
28
  if (!has("BUILD_ID") || !has("server")) return null;
@@ -114,11 +115,11 @@ async function runCommand(cmd, args) {
114
115
  env: { ...process.env, COPYFILE_DISABLE: "1" }
115
116
  });
116
117
  }
117
- function walkDir(dir, prefix = "") {
118
+ function walkDir(dir, prefix = "", modules = false) {
118
119
  const out = [];
119
120
  for (const d of readdirSync(join(dir, prefix), { withFileTypes: true })) {
120
121
  const rel = prefix ? `${prefix}/${d.name}` : d.name;
121
- if (d.isDirectory() && d.name !== "node_modules") out.push(...walkDir(dir, rel));
122
+ if (d.isDirectory() && (modules || d.name !== "node_modules")) out.push(...walkDir(dir, rel, modules));
122
123
  else if (d.isFile()) out.push(rel);
123
124
  }
124
125
  return out;
@@ -126,6 +127,7 @@ function walkDir(dir, prefix = "") {
126
127
  var defaultIo = () => ({
127
128
  env: process.env,
128
129
  walk: (dir) => walkDir(dir),
130
+ walkAll: (dir) => walkDir(dir, "", true),
129
131
  exists: existsSync,
130
132
  readText: (p) => readFileSync(p, "utf8"),
131
133
  writeText: (p, t) => writeFileSync(p, t),
@@ -146,11 +148,18 @@ function tryRemove(io, path) {
146
148
  } catch {
147
149
  }
148
150
  }
151
+ function removeAllMaps(io, dir) {
152
+ try {
153
+ for (const p of io.walkAll(dir)) if (p.endsWith(".map")) tryRemove(io, join(dir, p));
154
+ } catch (err) {
155
+ console.warn(`qore-sourcemaps: cleanup skipped: ${describe(err, io.env.QORE_BUILD_UPLOAD_TOKEN)}`);
156
+ }
157
+ }
149
158
  async function main(argv = process.argv.slice(2), io = defaultIo()) {
150
159
  const args = parseArgs(argv);
151
160
  if ("error" in args) {
152
161
  console.warn(`qore-sourcemaps: ${args.error}`);
153
- const dir2 = argv[0] === "upload" ? argv[1] : void 0;
162
+ const dir2 = isCommand(argv[0]) ? argv[1] : void 0;
154
163
  if (dir2 && !dir2.startsWith("-")) {
155
164
  try {
156
165
  for (const m of listMaps(io.walk(dir2))) tryRemove(io, join(dir2, m));
@@ -160,7 +169,7 @@ async function main(argv = process.argv.slice(2), io = defaultIo()) {
160
169
  }
161
170
  return;
162
171
  }
163
- const { dir, bundle } = args;
172
+ const { cmd, dir, bundle } = args;
164
173
  const at = (rel) => join(dir, rel);
165
174
  let maps = [];
166
175
  const scratch = [];
@@ -214,6 +223,7 @@ async function main(argv = process.argv.slice(2), io = defaultIo()) {
214
223
  } finally {
215
224
  for (const m of maps) tryRemove(io, at(m));
216
225
  for (const s of scratch) tryRemove(io, s);
226
+ if (cmd === "finalize") removeAllMaps(io, dir);
217
227
  }
218
228
  }
219
229
  function isMainModule() {
@@ -1,79 +1,7 @@
1
+ import { I as IntegrationMap, a as IntegrationDefinition, E as EnvRef } from '../types-Cl7g4ego.js';
2
+ export { A as AUTH_ENV_FIELDS, b as AUTH_SECRET_FIELDS, c as AuthKind, d as EnvKey, e as IntegrationAuth, P as Protocol, R as RESERVED_KEY_PREFIX, f as defineIntegrations } from '../types-Cl7g4ego.js';
1
3
  import { E as Env } from '../env-R-bci5RU.js';
2
4
 
3
- /**
4
- * How an integration authenticates. Every field except `header` and
5
- * `credentialsIn` names an **env key** — the SDK reads the value from the
6
- * environment at call time, never from the declaration — so a declaration can
7
- * sit in source control and carry no secret.
8
- */
9
- type AuthKind = "none" | "api_key_header" | "bearer_static" | "basic" | "oauth2_client_credentials";
10
- /** What the API speaks. Informational for the portal; the client sends bytes either way. */
11
- type Protocol = "rest" | "odata" | "soap" | "graphql";
12
- /** The name of an env var, e.g. `SAP_BASE_URL`. */
13
- type EnvKey = string;
14
- /**
15
- * A reference to an env var. The short form is required; the object form can
16
- * be optional and carry a default the app falls back on when the key is unset.
17
- */
18
- type EnvRef = EnvKey | {
19
- key: EnvKey;
20
- optional?: boolean;
21
- default?: string | number | boolean;
22
- };
23
- type IntegrationAuth = {
24
- kind: "none";
25
- } | {
26
- kind: "api_key_header";
27
- header: string;
28
- apiKey: EnvKey;
29
- } | {
30
- kind: "bearer_static";
31
- token: EnvKey;
32
- } | {
33
- kind: "basic";
34
- username: EnvKey;
35
- password: EnvKey;
36
- } | {
37
- kind: "oauth2_client_credentials";
38
- tokenUrl: EnvKey;
39
- clientId: EnvKey;
40
- clientSecret: EnvKey;
41
- scope?: EnvKey;
42
- audience?: EnvKey;
43
- /** Where the client credentials go on the token request. Default `"header"`. */
44
- credentialsIn?: "header" | "body";
45
- };
46
- interface IntegrationDefinition {
47
- /** Human name shown in the portal, e.g. "SAP S/4HANA Cloud". */
48
- label: string;
49
- protocol: Protocol;
50
- /** Env key holding the base URL for this environment. */
51
- baseUrl: EnvKey;
52
- auth: IntegrationAuth;
53
- /** Further env the app reads for this integration, by logical name. */
54
- config?: Record<string, EnvRef>;
55
- }
56
- type IntegrationMap = Record<string, IntegrationDefinition>;
57
- /**
58
- * Identity function that pins the literal types of the map, so an alias typo
59
- * at a call site is a compile error (`keyof M`) rather than a runtime
60
- * `not_declared`. Same shape as `definePermissions` in `auth-core`.
61
- */
62
- declare function defineIntegrations<const M extends IntegrationMap>(map: M): M;
63
- /**
64
- * Which fields of each auth kind name an env key. Shared with the manifest
65
- * extractor and the portal, which derive the required-env list from a
66
- * declaration without evaluating app code.
67
- */
68
- declare const AUTH_ENV_FIELDS: Record<AuthKind, readonly string[]>;
69
- /** Auth fields whose env value is a secret, so the portal masks it. */
70
- declare const AUTH_SECRET_FIELDS: readonly ["apiKey", "token", "password", "clientSecret"];
71
- /**
72
- * Env keys under this prefix belong to the platform
73
- * (`QORE_INTEGRATION_<ALIAS>_LOGGING` today). A declaration may not claim one.
74
- */
75
- declare const RESERVED_KEY_PREFIX = "QORE_INTEGRATION_";
76
-
77
5
  interface IntegrationProblem {
78
6
  alias: string;
79
7
  key: string;
@@ -213,4 +141,4 @@ declare const INTEGRATION_SPAN_TYPE_ATTR = "qore.span.type";
213
141
  /** A cached OAuth2 token is refreshed this long before it expires. */
214
142
  declare const OAUTH_REFRESH_SKEW_MS = 30000;
215
143
 
216
- export { AUTH_ENV_FIELDS, AUTH_SECRET_FIELDS, type AuthKind, DEFAULT_INTEGRATION_TIMEOUT_MS, type EnvKey, type EnvRef, INTEGRATION_ALIAS_ATTR, INTEGRATION_SPAN_TYPE, INTEGRATION_SPAN_TYPE_ATTR, type IntegrationAuth, type IntegrationClient, type IntegrationConfig, type IntegrationDefinition, IntegrationError, type IntegrationErrorCode, type IntegrationHandle, type IntegrationMap, type IntegrationProblem, type IntegrationRequest, OAUTH_REFRESH_SKEW_MS, PLATFORM_MANAGED_HOSTS, type ParamValue, type Protocol, RESERVED_KEY_PREFIX, allKeys, assertIntegrations, createIntegrationClient, defineIntegrations, isPlatformManagedHost, loggingEnabled, loggingKey, readRef, requiredKeys };
144
+ export { DEFAULT_INTEGRATION_TIMEOUT_MS, EnvRef, INTEGRATION_ALIAS_ATTR, INTEGRATION_SPAN_TYPE, INTEGRATION_SPAN_TYPE_ATTR, type IntegrationClient, type IntegrationConfig, IntegrationDefinition, IntegrationError, type IntegrationErrorCode, type IntegrationHandle, IntegrationMap, type IntegrationProblem, type IntegrationRequest, OAUTH_REFRESH_SKEW_MS, PLATFORM_MANAGED_HOSTS, type ParamValue, allKeys, assertIntegrations, createIntegrationClient, isPlatformManagedHost, loggingEnabled, loggingKey, readRef, requiredKeys };