@agentic-kit/db-tools 0.12.47 → 0.13.1

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 (180) hide show
  1. package/README.md +18 -4
  2. package/access/findings.d.ts +93 -0
  3. package/access/findings.js +434 -0
  4. package/access/index.d.ts +5 -0
  5. package/access/index.js +27 -0
  6. package/access/policies.d.ts +142 -0
  7. package/access/policies.js +338 -0
  8. package/access/provisioning.d.ts +121 -0
  9. package/access/provisioning.js +381 -0
  10. package/access/rule-check.d.ts +52 -0
  11. package/access/rule-check.js +307 -0
  12. package/access/words.d.ts +38 -0
  13. package/access/words.js +530 -0
  14. package/app-workspace.d.ts +1 -0
  15. package/app-workspace.js +7 -9
  16. package/blueprint/blueprint-defaults.d.ts +9 -0
  17. package/blueprint/blueprint-defaults.js +77 -0
  18. package/blueprint/blueprint-schema.d.ts +68 -0
  19. package/blueprint/blueprint-schema.js +139 -0
  20. package/blueprint/field-type.d.ts +4 -0
  21. package/blueprint/field-type.js +100 -0
  22. package/blueprint/internal-policies.d.ts +1 -0
  23. package/blueprint/internal-policies.js +10 -0
  24. package/blueprint-construction.d.ts +10 -6
  25. package/blueprint-construction.js +34 -25
  26. package/context.d.ts +15 -0
  27. package/context.js +132 -69
  28. package/db-probe.d.ts +1 -1
  29. package/db-probe.js +19 -4
  30. package/esm/access/findings.d.ts +93 -0
  31. package/esm/access/findings.js +428 -0
  32. package/esm/access/index.d.ts +5 -0
  33. package/esm/access/index.js +5 -0
  34. package/esm/access/policies.d.ts +142 -0
  35. package/esm/access/policies.js +315 -0
  36. package/esm/access/provisioning.d.ts +121 -0
  37. package/esm/access/provisioning.js +375 -0
  38. package/esm/access/rule-check.d.ts +52 -0
  39. package/esm/access/rule-check.js +297 -0
  40. package/esm/access/words.d.ts +38 -0
  41. package/esm/access/words.js +524 -0
  42. package/esm/app-workspace.d.ts +1 -0
  43. package/esm/app-workspace.js +7 -10
  44. package/esm/blueprint/blueprint-defaults.d.ts +9 -0
  45. package/esm/blueprint/blueprint-defaults.js +74 -0
  46. package/esm/blueprint/blueprint-schema.d.ts +68 -0
  47. package/esm/blueprint/blueprint-schema.js +134 -0
  48. package/esm/blueprint/field-type.d.ts +4 -0
  49. package/esm/blueprint/field-type.js +95 -0
  50. package/esm/blueprint/internal-policies.d.ts +1 -0
  51. package/esm/blueprint/internal-policies.js +7 -0
  52. package/esm/blueprint-construction.d.ts +10 -6
  53. package/esm/blueprint-construction.js +32 -24
  54. package/esm/context.d.ts +15 -0
  55. package/esm/context.js +133 -70
  56. package/esm/db-probe.d.ts +1 -1
  57. package/esm/db-probe.js +21 -6
  58. package/esm/failure.d.ts +89 -0
  59. package/esm/failure.js +362 -0
  60. package/esm/gate.d.ts +6 -4
  61. package/esm/gate.js +42 -14
  62. package/esm/graphql-http.d.ts +27 -6
  63. package/esm/graphql-http.js +96 -24
  64. package/esm/host.d.ts +33 -8
  65. package/esm/host.js +42 -2
  66. package/esm/index.d.ts +22 -12
  67. package/esm/index.js +21 -39
  68. package/esm/provision-database/env-file.d.ts +7 -0
  69. package/esm/provision-database/env-file.js +30 -0
  70. package/esm/provision-database/preset-match.js +1 -2
  71. package/esm/provision-database/provision.d.ts +21 -4
  72. package/esm/provision-database/provision.js +330 -85
  73. package/esm/provision-database/request-database.d.ts +22 -3
  74. package/esm/provision-database/request-database.js +46 -13
  75. package/esm/ready.d.ts +20 -0
  76. package/esm/ready.js +45 -0
  77. package/esm/run-codegen/barrels.js +1 -1
  78. package/esm/run-codegen/endpoints.js +5 -6
  79. package/esm/schema-model/normalize.js +1 -1
  80. package/esm/schema-model.js +4 -5
  81. package/esm/schema-resolve.d.ts +50 -0
  82. package/esm/schema-resolve.js +200 -14
  83. package/esm/table-access.d.ts +116 -0
  84. package/esm/table-access.js +418 -0
  85. package/esm/tools/access.d.ts +218 -0
  86. package/esm/tools/access.js +651 -0
  87. package/esm/tools/add-policies.d.ts +44 -12
  88. package/esm/tools/add-policies.js +84 -84
  89. package/esm/tools/add-records.d.ts +23 -2
  90. package/esm/tools/add-records.js +113 -75
  91. package/esm/tools/add-relation-schema.d.ts +5 -5
  92. package/esm/tools/add-relation-schema.js +13 -14
  93. package/esm/tools/add-relation.d.ts +11 -2
  94. package/esm/tools/add-relation.js +68 -31
  95. package/esm/tools/create-api-key.d.ts +18 -4
  96. package/esm/tools/create-api-key.js +105 -54
  97. package/esm/tools/describe-schema.d.ts +5 -7
  98. package/esm/tools/describe-schema.js +41 -118
  99. package/esm/tools/entity-types.d.ts +54 -0
  100. package/esm/tools/entity-types.js +233 -0
  101. package/esm/tools/index.d.ts +26 -0
  102. package/esm/tools/index.js +151 -0
  103. package/esm/tools/mutations.d.ts +36 -7
  104. package/esm/tools/mutations.js +245 -99
  105. package/esm/tools/provision-blueprint.d.ts +25 -1
  106. package/esm/tools/provision-blueprint.js +184 -42
  107. package/esm/tools/provision-database.d.ts +7 -5
  108. package/esm/tools/provision-database.js +31 -17
  109. package/esm/tools/run-codegen.d.ts +27 -4
  110. package/esm/tools/run-codegen.js +143 -76
  111. package/esm/tools/templates.d.ts +30 -7
  112. package/esm/tools/templates.js +166 -95
  113. package/failure.d.ts +89 -0
  114. package/failure.js +375 -0
  115. package/gate.d.ts +6 -4
  116. package/gate.js +41 -13
  117. package/graphql-http.d.ts +27 -6
  118. package/graphql-http.js +105 -25
  119. package/host.d.ts +33 -8
  120. package/host.js +45 -2
  121. package/index.d.ts +22 -12
  122. package/index.js +86 -43
  123. package/package.json +6 -5
  124. package/provision-database/env-file.d.ts +7 -0
  125. package/provision-database/env-file.js +32 -1
  126. package/provision-database/preset-match.js +1 -2
  127. package/provision-database/provision.d.ts +21 -4
  128. package/provision-database/provision.js +327 -81
  129. package/provision-database/request-database.d.ts +22 -3
  130. package/provision-database/request-database.js +49 -14
  131. package/ready.d.ts +20 -0
  132. package/ready.js +52 -0
  133. package/run-codegen/barrels.js +1 -1
  134. package/run-codegen/endpoints.js +5 -6
  135. package/schema-model/normalize.js +4 -4
  136. package/schema-model.js +4 -5
  137. package/schema-resolve.d.ts +50 -0
  138. package/schema-resolve.js +209 -14
  139. package/table-access.d.ts +116 -0
  140. package/table-access.js +437 -0
  141. package/tools/access.d.ts +218 -0
  142. package/tools/access.js +669 -0
  143. package/tools/add-policies.d.ts +44 -12
  144. package/tools/add-policies.js +86 -84
  145. package/tools/add-records.d.ts +23 -2
  146. package/tools/add-records.js +113 -74
  147. package/tools/add-relation-schema.d.ts +5 -5
  148. package/tools/add-relation-schema.js +13 -14
  149. package/tools/add-relation.d.ts +11 -2
  150. package/tools/add-relation.js +69 -31
  151. package/tools/create-api-key.d.ts +18 -4
  152. package/tools/create-api-key.js +104 -53
  153. package/tools/describe-schema.d.ts +5 -7
  154. package/tools/describe-schema.js +40 -117
  155. package/tools/entity-types.d.ts +54 -0
  156. package/tools/entity-types.js +240 -0
  157. package/tools/index.d.ts +26 -0
  158. package/tools/index.js +154 -0
  159. package/tools/mutations.d.ts +36 -7
  160. package/tools/mutations.js +252 -101
  161. package/tools/provision-blueprint.d.ts +25 -1
  162. package/tools/provision-blueprint.js +186 -43
  163. package/tools/provision-database.d.ts +7 -5
  164. package/tools/provision-database.js +33 -18
  165. package/tools/run-codegen.d.ts +27 -4
  166. package/tools/run-codegen.js +141 -73
  167. package/tools/templates.d.ts +30 -7
  168. package/tools/templates.js +167 -94
  169. package/esm/policy/add-policies-to-table.d.ts +0 -26
  170. package/esm/policy/add-policies-to-table.js +0 -66
  171. package/esm/policy/provision-helpers.d.ts +0 -38
  172. package/esm/policy/provision-helpers.js +0 -50
  173. package/esm/tools/manage-entity-types.d.ts +0 -40
  174. package/esm/tools/manage-entity-types.js +0 -201
  175. package/policy/add-policies-to-table.d.ts +0 -26
  176. package/policy/add-policies-to-table.js +0 -71
  177. package/policy/provision-helpers.d.ts +0 -38
  178. package/policy/provision-helpers.js +0 -58
  179. package/tools/manage-entity-types.d.ts +0 -40
  180. package/tools/manage-entity-types.js +0 -206
package/context.js CHANGED
@@ -15,7 +15,14 @@ const node_path_1 = __importDefault(require("node:path"));
15
15
  const sdk_1 = require("@constructive-io/sdk");
16
16
  const dotenv_1 = require("12factor-env/dotenv");
17
17
  const db_probe_1 = require("./db-probe");
18
+ const failure_1 = require("./failure");
18
19
  const host_1 = require("./host");
20
+ const env_file_1 = require("./provision-database/env-file");
21
+ // The failure's code is `code` unless `why.code` names a more precise one.
22
+ function unresolved(code, why, cause) {
23
+ const failure = { ...why, code: why.code ?? code };
24
+ return { context: null, reason: (0, failure_1.failureText)(failure), code, ...(cause ? { cause } : {}), failure };
25
+ }
19
26
  // The project values pi needs, and where they come from. A scaffolded project
20
27
  // folder carries binding metadata in `.env`; a headless host — a container,
21
28
  // a Job, CI — injects values without writing credentials into a git clone.
@@ -64,29 +71,37 @@ async function resolveProjectContext(input, options = {}) {
64
71
  const fileBacked = typeof input === 'string';
65
72
  const source = fileBacked ? await fromEnvFile(input) : input;
66
73
  if (!source) {
67
- return {
68
- context: null,
69
- reason: 'No .env found in the project. Provision a Constructive database first (scaffold the project), then retry.',
70
- code: 'no-env',
71
- };
74
+ return unresolved('no-env', {
75
+ message: 'No .env found in the project.',
76
+ hint: 'Create a database for this directory (the person approves it), then retry.',
77
+ calls: [failure_1.NEW_DATABASE],
78
+ });
72
79
  }
73
80
  const env = Object.fromEntries(exports.CONTEXT_ENV_KEYS.map((key) => [key, fileBacked && key === 'ACCESS_TOKEN' ? undefined : readContextValue(source, key)]));
81
+ const invalid = (0, env_file_1.invalidBindingKeys)(env);
82
+ if (invalid.length)
83
+ return unresolved('missing-credentials', (0, failure_1.invalidBinding)(invalid, fileBacked ? '.env' : 'the injected project context'));
74
84
  const accessToken = env.ACCESS_TOKEN;
75
85
  const databaseId = env.DATABASE_ID;
76
86
  if (!databaseId || (!fileBacked && !accessToken)) {
77
- return {
78
- context: null,
79
- reason: fileBacked
80
- ? 'Project is not connected to a Constructive database yet (missing DATABASE_ID in .env). Provision the database first, then retry.'
81
- : `Missing ${exports.CONTEXT_ENV_PREFIX}ACCESS_TOKEN or ${exports.CONTEXT_ENV_PREFIX}DATABASE_ID from the injected project context.`,
82
- code: 'missing-credentials',
83
- };
87
+ return unresolved('missing-credentials', fileBacked
88
+ ? {
89
+ message: 'Project is not connected to a Constructive database yet (missing DATABASE_ID in .env).',
90
+ hint: 'Bind this directory to a database (the person approves it), then retry.',
91
+ calls: [failure_1.NEW_DATABASE],
92
+ }
93
+ : {
94
+ message: `Missing ${exports.CONTEXT_ENV_PREFIX}ACCESS_TOKEN or ${exports.CONTEXT_ENV_PREFIX}DATABASE_ID from the injected project context.`,
95
+ });
84
96
  }
85
97
  // A source-supplied pin wins for the DATA plane (the access key belongs to
86
98
  // whatever backend wrote it); otherwise fall back to the app's backend-config
87
99
  // store (environment-aware) so app + harness share one endpoint source.
88
100
  const host = (0, host_1.getHost)();
89
- const backend = host.backendConfig();
101
+ const backendRead = (0, host_1.readBackendConfig)(host);
102
+ if (backendRead.kind === 'failed')
103
+ return unresolved('no-backend', backendRead.failure);
104
+ const backend = backendRead.value;
90
105
  const controlApiEndpoint = backend?.apiEndpoint;
91
106
  const controlModulesEndpoint = backend?.modulesEndpoint;
92
107
  // The whole control plane (binding probe, schema resolution, blueprint/schema
@@ -95,17 +110,20 @@ async function resolveProjectContext(input, options = {}) {
95
110
  // surfaces. An explicitly injected key stays in the context for the data plane only.
96
111
  // The bearer is only ever sent to the app-configured backend — never a
97
112
  // source-pinned endpoint, which an untrusted cloned project controls.
98
- const account = host.account();
113
+ const accountRead = await (0, host_1.readAccount)(host);
114
+ if (accountRead.kind === 'failed')
115
+ return unresolved('missing-credentials', accountRead.failure);
116
+ const account = accountRead.value;
99
117
  const accountBearer = account?.apiKey ?? account?.accessToken;
100
118
  if (!accountBearer) {
101
- return {
102
- context: null,
103
- reason: `No usable account credential to reach the Constructive control plane. ${host.signInHint ?? 'Sign in to the app, then retry.'}`,
104
- code: 'missing-credentials',
105
- };
119
+ return unresolved('missing-credentials', {
120
+ code: 'signed-out',
121
+ message: 'No usable account credential to reach the Constructive control plane.',
122
+ hint: host.signInHint ?? 'Sign in to the app, then retry.',
123
+ });
106
124
  }
107
125
  if (!controlApiEndpoint || !controlModulesEndpoint) {
108
- return { context: null, reason: (0, host_1.noBackendReason)(host.signInHint), code: 'no-backend' };
126
+ return unresolved('no-backend', (0, failure_1.noBackendFailure)(host.signInHint));
109
127
  }
110
128
  const apiEndpoint = env.API_ENDPOINT || controlApiEndpoint;
111
129
  const modulesEndpoint = env.MODULES_ENDPOINT || controlModulesEndpoint;
@@ -121,19 +139,14 @@ async function resolveProjectContext(input, options = {}) {
121
139
  signInHint: host.signInHint,
122
140
  });
123
141
  if (probe.status === 'unreachable') {
124
- return {
125
- context: null,
126
- reason: unreachableReason(controlApiEndpoint, probe.cause, probe.detail),
127
- code: 'backend-unreachable',
128
- cause: probe.cause,
129
- };
142
+ return unresolved('backend-unreachable', unreachableFailure(controlApiEndpoint, probe.cause, probe.detail), probe.cause);
130
143
  }
131
144
  if (probe.status === 'missing') {
132
- return {
133
- context: null,
134
- reason: `The bound database (DATABASE_ID=${databaseId}) no longer exists on this backend, or this account lost access to it. ${(0, host_1.reprovisionAdvice)(host)}`,
135
- code: 'db-missing',
136
- };
145
+ return unresolved('db-missing', {
146
+ message: `The bound database (DATABASE_ID=${databaseId}) no longer exists on this backend, or this account lost access to it.`,
147
+ hint: (0, host_1.reprovisionAdvice)(host),
148
+ ...(0, host_1.replaceCall)(host),
149
+ });
137
150
  }
138
151
  // Schemas are account-scoped: a live binding under a different account is
139
152
  // never shown in the Schemas tab or written to by the agent. The project's
@@ -146,21 +159,19 @@ async function resolveProjectContext(input, options = {}) {
146
159
  probe.ownerId &&
147
160
  sessionUserId &&
148
161
  probe.ownerId !== sessionUserId) {
149
- return {
150
- context: null,
151
- reason: `The bound database (DATABASE_ID=${databaseId}) was provisioned under a different account than the one signed in. ${(0, host_1.reprovisionAdvice)(host)}`,
152
- code: 'account-mismatch',
153
- };
162
+ return unresolved('account-mismatch', {
163
+ message: `The bound database (DATABASE_ID=${databaseId}) was provisioned under a different account than the one signed in.`,
164
+ hint: (0, host_1.reprovisionAdvice)(host),
165
+ ...(0, host_1.replaceCall)(host),
166
+ });
154
167
  }
155
168
  // A suspended database still holds its data, so it is never a reason to
156
169
  // reprovision: nothing can read or change it until the hold is lifted.
157
170
  if (probe.status === 'suspended') {
158
171
  const why = probe.suspendedReason ? ` (${probe.suspendedReason})` : '';
159
- return {
160
- context: null,
161
- reason: `The bound database (DATABASE_ID=${databaseId}) is suspended${why} since ${probe.suspendedAt}. Its data is kept, but nothing can read or change it until the suspension is lifted.`,
162
- code: 'db-suspended',
163
- };
172
+ return unresolved('db-suspended', {
173
+ message: `The bound database (DATABASE_ID=${databaseId}) is suspended${why} since ${probe.suspendedAt}. Its data is kept, but nothing can read or change it until the suspension is lifted.`,
174
+ });
164
175
  }
165
176
  const databaseName = env.DATABASE_NAME || probe.name || '';
166
177
  const ownerId = probe.ownerId || env.OWNER_ID || undefined;
@@ -168,9 +179,8 @@ async function resolveProjectContext(input, options = {}) {
168
179
  ? deriveSubdomainEndpoint(apiEndpoint, `api-${databaseName}`)
169
180
  : '';
170
181
  const schema = await resolveSchemaId(apiClient, databaseId);
171
- if ('reason' in schema) {
172
- return { context: null, reason: schema.reason, code: 'schema-unresolved' };
173
- }
182
+ if ('failure' in schema)
183
+ return unresolved('schema-unresolved', schema.failure);
174
184
  const schemaId = schema.id;
175
185
  return {
176
186
  context: {
@@ -179,6 +189,10 @@ async function resolveProjectContext(input, options = {}) {
179
189
  databaseId,
180
190
  schemaId,
181
191
  ownerId,
192
+ accountUserId: account.userId,
193
+ ...(account.email ? { accountEmail: account.email } : {}),
194
+ ...(account.agent ? { accountAgent: account.agent } : {}),
195
+ controlApiEndpoint,
182
196
  apiEndpoint,
183
197
  modulesEndpoint,
184
198
  databaseName,
@@ -189,21 +203,53 @@ async function resolveProjectContext(input, options = {}) {
189
203
  reason: '',
190
204
  };
191
205
  }
192
- function unreachableReason(endpoint, cause, detail) {
206
+ function unreachableFailure(endpoint, cause, detail) {
193
207
  switch (cause) {
194
208
  case 'auth':
195
209
  // The probe's detail says the credential was rejected and how to sign in.
196
- return `Could not check the bound database on the Constructive backend at ${endpoint}: ${detail}`;
210
+ return {
211
+ code: 'signed-out',
212
+ message: `Could not check the bound database on the Constructive backend at ${endpoint}: ${detail}`,
213
+ };
197
214
  case 'error':
198
- return `The Constructive backend at ${endpoint} answered with an error while checking the bound database (${detail}). Retry; if it keeps failing, check the backend's logs.`;
215
+ return {
216
+ code: 'backend-unreachable',
217
+ message: `The Constructive backend at ${endpoint} answered with an error while checking the bound database (${detail}).`,
218
+ hint: "Retry; if it keeps failing, check the backend's logs.",
219
+ retryable: true,
220
+ };
199
221
  case 'server':
200
- return `The Constructive backend at ${endpoint} is failing (${detail}). Check it is running, then retry.`;
222
+ return {
223
+ code: 'backend-unreachable',
224
+ message: `The Constructive backend at ${endpoint} is failing (${detail}).`,
225
+ hint: 'Check it is running, then retry.',
226
+ retryable: true,
227
+ };
228
+ case 'rate-limited':
229
+ return {
230
+ code: 'rate-limited',
231
+ message: `The Constructive backend at ${endpoint} is limiting how many requests it takes (${detail}).`,
232
+ hint: 'Wait, as long as the message says when the backend gave a time, then call again.',
233
+ retryable: true,
234
+ };
201
235
  default:
202
- return `Could not reach the Constructive backend at ${endpoint} (${detail}). Check it is running, then retry.`;
236
+ return {
237
+ code: 'backend-unreachable',
238
+ message: `Could not reach the Constructive backend at ${endpoint} (${detail}).`,
239
+ hint: 'Check it is running, then retry.',
240
+ retryable: true,
241
+ };
203
242
  }
204
243
  }
205
- const needsAuthReason = () => `Not signed in to the app database yet. ${(0, host_1.getHost)().signInHint ??
206
- 'Sign in from the Sheets tab, or open the Preview and sign in to your app, then try again.'}`;
244
+ function appSignedOut(why = 'Not signed in to the app database yet.') {
245
+ const failure = {
246
+ code: 'app-signed-out',
247
+ message: why,
248
+ hint: (0, host_1.getHost)().signInHint ??
249
+ 'Sign in from the Sheets tab, or open the Preview and sign in to your app, then try again.',
250
+ };
251
+ return { reason: (0, failure_1.failureText)(failure), failure };
252
+ }
207
253
  // Resolve a data-plane token for record operations: serve the broker's active
208
254
  // account while valid, otherwise harvest the token the user created by signing
209
255
  // into their app in the Preview and adopt it into the broker. Also returns the
@@ -216,17 +262,22 @@ async function resolveDataToken(context) {
216
262
  const active = broker?.getActiveToken(context.databaseId);
217
263
  if (active)
218
264
  return { token: active.token, userId: active.userId };
219
- const preview = host.previewToken ? await host.previewToken() : null;
220
- if (!preview)
221
- return { reason: needsAuthReason() };
222
- if (broker?.isInvalidToken(context.databaseId, preview.accessToken)) {
223
- return { reason: needsAuthReason() };
265
+ let preview = null;
266
+ try {
267
+ preview = host.previewToken ? await host.previewToken() : null;
224
268
  }
269
+ catch (err) {
270
+ return appSignedOut(`Could not read the app sign-in: ${err instanceof Error ? err.message : String(err)}`);
271
+ }
272
+ if (!preview)
273
+ return appSignedOut();
274
+ if (broker?.isInvalidToken(context.databaseId, preview.accessToken))
275
+ return appSignedOut();
225
276
  const parsed = preview.accessTokenExpiresAt ? Date.parse(preview.accessTokenExpiresAt) : NaN;
226
277
  const expiresAt = Number.isNaN(parsed) ? Date.now() + 60 * 60 * 1000 : parsed;
227
278
  const skewMs = host.dataTokenSkewMs ?? host_1.DEFAULT_DATA_TOKEN_SKEW_MS;
228
279
  if (expiresAt <= Date.now() + skewMs)
229
- return { reason: needsAuthReason() };
280
+ return appSignedOut();
230
281
  broker?.adoptToken(context.databaseId, {
231
282
  userId: preview.userId,
232
283
  token: preview.accessToken,
@@ -237,7 +288,7 @@ async function resolveDataToken(context) {
237
288
  }
238
289
  // Per-DB endpoints are deterministic on the provisioning subdomain (= DATABASE_NAME):
239
290
  // each plane swaps the first host label of its control-plane endpoint
240
- // (e.g. api.localhost -> api-myapp.localhost, auth.localhost -> auth-myapp.localhost).
291
+ // (e.g. api.example.com -> api-myapp.example.com, auth.example.com -> auth-myapp.example.com).
241
292
  function deriveSubdomainEndpoint(baseEndpoint, firstLabel) {
242
293
  try {
243
294
  const url = new URL(baseEndpoint);
@@ -258,7 +309,7 @@ function deriveSubdomainEndpoint(baseEndpoint, firstLabel) {
258
309
  async function resolveOrgName(ownerId) {
259
310
  try {
260
311
  const host = (0, host_1.getHost)();
261
- const account = host.account();
312
+ const account = await host.account();
262
313
  const bearer = account?.apiKey ?? account?.accessToken;
263
314
  if (!bearer)
264
315
  return undefined;
@@ -290,20 +341,32 @@ async function resolveOrgName(ownerId) {
290
341
  // `name` is the logical schema name, identical on every backend; the physical
291
342
  // (possibly hashed) name is `schemaName`.
292
343
  async function resolveSchemaId(apiClient, databaseId) {
293
- const result = await apiClient.schema
294
- .findMany({
295
- select: { id: true, name: true },
296
- where: { databaseId: { equalTo: databaseId }, name: { equalTo: 'app_public' } },
297
- })
298
- .execute();
299
- if (!result.ok) {
300
- const detail = result.errors?.[0]?.message ?? 'unknown error';
301
- return { reason: `Could not query the app_public schema for database ${databaseId}: ${detail}` };
344
+ // The answer's code decides (a sign-in that ended is signed-out); an answer no code explains is this step's.
345
+ const action = `Could not query the app_public schema for database ${databaseId}`;
346
+ const queryFailed = (failure) => ({
347
+ failure: failure.code === 'failed' ? { ...failure, code: 'schema-unresolved' } : failure,
348
+ });
349
+ let result;
350
+ try {
351
+ result = await apiClient.schema
352
+ .findMany({
353
+ select: { id: true, name: true },
354
+ where: { databaseId: { equalTo: databaseId }, name: { equalTo: 'app_public' } },
355
+ })
356
+ .execute();
357
+ }
358
+ catch (err) {
359
+ return queryFailed((0, failure_1.failureFromError)(err, action));
302
360
  }
361
+ if (!result.ok)
362
+ return queryFailed((0, failure_1.failureFromErrors)(result.errors ?? [], action));
303
363
  const appPublic = (result.data.schemas?.nodes ?? []).find((s) => s?.name === 'app_public');
304
364
  if (!appPublic?.id) {
305
365
  return {
306
- reason: `Database ${databaseId} has no app_public schema. The database may not be fully provisioned yet.`,
366
+ failure: {
367
+ code: 'schema-unresolved',
368
+ message: `Database ${databaseId} has no app_public schema. The database may not be fully provisioned yet.`,
369
+ },
307
370
  };
308
371
  }
309
372
  return { id: appPublic.id };
package/db-probe.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { postGraphQL } from './graphql-http';
2
- export type UnreachableCause = 'network' | 'server' | 'auth' | 'error';
2
+ export type UnreachableCause = 'network' | 'server' | 'rate-limited' | 'auth' | 'error';
3
3
  export type DatabaseProbe = {
4
4
  status: 'found';
5
5
  databaseId: string;
package/db-probe.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.probeDatabase = probeDatabase;
4
4
  exports.probeBoundDatabase = probeBoundDatabase;
5
+ const failure_1 = require("./failure");
5
6
  const graphql_http_1 = require("./graphql-http");
6
7
  const host_1 = require("./host");
7
8
  const FIELDS = 'id name ownerId hash suspendedAt suspendedReason';
@@ -64,12 +65,16 @@ async function probeDatabase(args) {
64
65
  return { status: 'found', ...found };
65
66
  }
66
67
  function unreachable(databaseId, errors, signInHint) {
67
- const detail = (0, graphql_http_1.errorsText)(errors);
68
+ const detail = (0, graphql_http_1.answerText)(errors);
68
69
  switch ((0, graphql_http_1.classifyBackendErrors)(errors)) {
69
70
  case 'network':
70
71
  return { status: 'unreachable', databaseId, cause: 'network', detail };
71
72
  case 'server':
72
73
  return { status: 'unreachable', databaseId, cause: 'server', detail };
74
+ case 'rate-limited': {
75
+ const seconds = (0, graphql_http_1.retryAfterOf)(errors);
76
+ return { status: 'unreachable', databaseId, cause: 'rate-limited', detail: seconds === undefined ? detail : `${detail}; it asks to wait ${seconds} seconds` };
77
+ }
73
78
  case 'auth':
74
79
  case 'forbidden':
75
80
  // A rejected ACCOUNT credential is never evidence the binding is dead.
@@ -77,7 +82,7 @@ function unreachable(databaseId, errors, signInHint) {
77
82
  status: 'unreachable',
78
83
  databaseId,
79
84
  cause: 'auth',
80
- detail: `${detail}: the account credential was rejected. ${signInHint ?? 'Sign in again, then retry.'}`,
85
+ detail: `the account credential was rejected (${detail}). ${signInHint ?? 'Sign in again, then retry.'}`,
81
86
  };
82
87
  default:
83
88
  return { status: 'unreachable', databaseId, cause: 'error', detail };
@@ -90,7 +95,17 @@ function unreachable(databaseId, errors, signInHint) {
90
95
  */
91
96
  async function probeBoundDatabase(databaseId) {
92
97
  const host = (0, host_1.getHost)();
93
- const account = host.account();
98
+ // A host that cannot give its backend (a wrong override, an incomplete
99
+ // context) fails both reads; its own reason must win over "sign in".
100
+ const backendRead = (0, host_1.readBackendConfig)(host);
101
+ if (backendRead.kind === 'failed') {
102
+ return { status: 'unreachable', databaseId, cause: 'error', detail: (0, failure_1.failureText)(backendRead.failure) };
103
+ }
104
+ const accountRead = await (0, host_1.readAccount)(host);
105
+ if (accountRead.kind === 'failed') {
106
+ return { status: 'unreachable', databaseId, cause: 'auth', detail: (0, failure_1.failureText)(accountRead.failure) };
107
+ }
108
+ const account = accountRead.value;
94
109
  const bearer = account?.apiKey ?? account?.accessToken;
95
110
  if (!bearer) {
96
111
  return {
@@ -100,7 +115,7 @@ async function probeBoundDatabase(databaseId) {
100
115
  detail: `No usable account credential. ${host.signInHint ?? 'Sign in to the app, then retry.'}`,
101
116
  };
102
117
  }
103
- const endpoint = host.backendConfig()?.apiEndpoint;
118
+ const endpoint = backendRead.value?.apiEndpoint;
104
119
  if (!endpoint) {
105
120
  return { status: 'unreachable', databaseId, cause: 'error', detail: (0, host_1.noBackendReason)(host.signInHint) };
106
121
  }
@@ -0,0 +1,93 @@
1
+ import { type AccessOperation, type TablePolicy } from './policies';
2
+ import { type AddedColumn, type ColumnDefault } from './provisioning';
3
+ import { type RelatedColumns } from './words';
4
+ /**
5
+ * What one rule of an Authz node checks: `member` (a member of the app or of a team), `named` (a person the row names),
6
+ * `shared` (a person given an explicit share), `anyone` (it checks the row only), `session` (the kind of session),
7
+ * `mixed` (it depends on nested parts), `none` (no one).
8
+ */
9
+ export interface AccessCheck {
10
+ person: 'member' | 'named' | 'shared' | 'anyone' | 'session' | 'mixed' | 'none';
11
+ /** For `member`: the app, a team the row names, or any team the row's owner shares with the person. */
12
+ scope?: 'app' | 'row' | 'peer';
13
+ /** The parameter that holds the row's owner column, when the row must name the person. */
14
+ owner?: string;
15
+ /** The parameter that holds the column of the team the row names. */
16
+ team?: string;
17
+ /** Meant as a limit on top of a grant, not as a grant. */
18
+ limit?: boolean;
19
+ /** Every row passes, with no check. */
20
+ always?: boolean;
21
+ }
22
+ export declare const ACCESS_CHECKS: Record<string, AccessCheck>;
23
+ /** One column of a table. */
24
+ export interface TableField {
25
+ name: string;
26
+ /** NOT NULL. */
27
+ required: boolean;
28
+ /** The default as the backend stores it (a FieldDefault), `null` for none, `'unknown'` when it cannot be read. */
29
+ default: ColumnDefault;
30
+ /** The type name, for example `uuid` or `text[]`, when known. */
31
+ type?: string;
32
+ }
33
+ export interface TableAccessInput {
34
+ policies: TablePolicy[];
35
+ /** When known. A grant to 'public' counts for every role. */
36
+ grants?: Array<{
37
+ roles: string[];
38
+ privileges: unknown[];
39
+ }>;
40
+ /** When known. */
41
+ rls_enabled?: boolean;
42
+ /** The table's columns, when known. */
43
+ fields?: TableField[];
44
+ /** The columns of other tables the rules name, by table id and by table name, when the reader read them. */
45
+ related?: RelatedColumns;
46
+ }
47
+ export interface AccessFinding {
48
+ /** Stable, kebab-case. */
49
+ id: string;
50
+ level: 'high' | 'medium' | 'low';
51
+ summary: string;
52
+ risk: string;
53
+ fix: string;
54
+ operations: AccessOperation[];
55
+ /** The columns the finding is about, when it is about columns. */
56
+ columns?: string[];
57
+ /** One sentence for each of those columns, when the finding differs by column. */
58
+ details?: string[];
59
+ }
60
+ /** A column the rules' Data nodes add that the table already has, but not as the node makes it. */
61
+ export interface ColumnGap {
62
+ column: string;
63
+ /** The Data node that adds the column. */
64
+ node: string;
65
+ /** The column as the node makes it. */
66
+ expected: AddedColumn;
67
+ /** The column the table has. */
68
+ actual: TableField;
69
+ /** What differs. A default or a type the table does not say (`'unknown'`, no `type`) does not differ. */
70
+ gaps: Array<'type' | 'required' | 'default'>;
71
+ }
72
+ /**
73
+ * The columns the rules' Data nodes add that the table has with another type, another NOT NULL, or another default. A
74
+ * generator keeps a column the table already has as it is, so the rule then reads a column it did not make.
75
+ */
76
+ export declare function columnGaps(given: TableField[], policies: Array<Pick<TablePolicy, 'type' | 'data'>>): ColumnGap[];
77
+ /** A column of the table one rule reads: the Authz node, its parameter (a path for a nested one) and the column. */
78
+ export interface ColumnRead {
79
+ type: string;
80
+ param: string;
81
+ column: string;
82
+ }
83
+ /**
84
+ * The columns of the table the rules read: each rule, its `with_check`, and the nodes nested in them, from the nodes'
85
+ * column parameters (registry defaults apply). `unknown` names the rule types with a part whose columns cannot be told:
86
+ * a stored raw expression, a type the registry does not have, or data its schema does not describe.
87
+ */
88
+ export declare function columnsReadByPolicies(policies: Array<Pick<TablePolicy, 'type' | 'data' | 'with_check'>>): {
89
+ columns: ColumnRead[];
90
+ unknown: string[];
91
+ };
92
+ /** What may be wrong with the rules of one table, by the shapes the backend docs warn about. */
93
+ export declare function accessFindings(input: TableAccessInput): AccessFinding[];