@cosmoops/connect-sdk 0.7.0 → 0.15.0

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 (154) hide show
  1. package/CHANGELOG.md +662 -0
  2. package/README.md +376 -124
  3. package/dist/cjs/cli/doctor.js +3 -3
  4. package/dist/cjs/cli/init.js +3 -3
  5. package/dist/cjs/client/components/access-gate.js +59 -5
  6. package/dist/cjs/client/components/ai-format.js +135 -0
  7. package/dist/cjs/client/components/ai-widgets.js +232 -0
  8. package/dist/cjs/client/components/app-shell.js +80 -45
  9. package/dist/cjs/client/components/apps-grid.js +3 -2
  10. package/dist/cjs/client/components/ask-ai.js +353 -0
  11. package/dist/cjs/client/components/confirm-dialog.js +40 -0
  12. package/dist/cjs/client/components/cursor-pagination.js +22 -0
  13. package/dist/cjs/client/components/filter-tabs.js +24 -0
  14. package/dist/cjs/client/components/grievance-notice.js +30 -0
  15. package/dist/cjs/client/components/link-button.js +17 -10
  16. package/dist/cjs/client/components/logo.js +4 -3
  17. package/dist/cjs/client/components/nav.js +42 -1
  18. package/dist/cjs/client/components/plan-pricing.js +27 -0
  19. package/dist/cjs/client/components/plans.js +1 -1
  20. package/dist/cjs/client/components/platform-gate.js +48 -0
  21. package/dist/cjs/client/components/shell-context.js +149 -0
  22. package/dist/cjs/client/components/side-nav.js +50 -24
  23. package/dist/cjs/client/components/sidebar.js +127 -0
  24. package/dist/cjs/client/components/subscribe-dialog.js +2 -2
  25. package/dist/cjs/client/components/subscription.js +1 -1
  26. package/dist/cjs/client/components/user-menu.js +122 -40
  27. package/dist/cjs/client/components/workspace-switcher.js +100 -0
  28. package/dist/cjs/client/components/workspace-type-gate.js +48 -0
  29. package/dist/cjs/client/index.js +98 -3
  30. package/dist/cjs/client/provider.js +100 -2
  31. package/dist/cjs/client/use-checkout.js +9 -5
  32. package/dist/cjs/errors.js +1 -1
  33. package/dist/cjs/index.js +11 -1
  34. package/dist/cjs/next/index.js +2 -2
  35. package/dist/cjs/server/client.js +25 -2
  36. package/dist/cjs/server/handler.js +237 -16
  37. package/dist/cjs/server/http.js +52 -26
  38. package/dist/cjs/server/resources/acting-as.js +16 -0
  39. package/dist/cjs/server/resources/ai.js +15 -2
  40. package/dist/cjs/server/resources/data.js +374 -0
  41. package/dist/cjs/server/resources/entitlements.js +41 -0
  42. package/dist/cjs/server/resources/identity.js +9 -3
  43. package/dist/cjs/server/resources/kv.js +84 -0
  44. package/dist/cjs/server/resources/platform.js +43 -0
  45. package/dist/cjs/server/resources/sessions.js +1 -1
  46. package/dist/cjs/server/resources/workspaces.js +74 -0
  47. package/dist/cjs/store.js +152 -0
  48. package/dist/cjs/ui/empty-state.js +28 -0
  49. package/dist/cjs/ui/index.js +44 -0
  50. package/dist/cjs/ui/page-header.js +27 -0
  51. package/dist/cjs/ui/page-shell.js +44 -0
  52. package/dist/cjs/ui/section.js +20 -0
  53. package/dist/cjs/ui/setting-row.js +14 -0
  54. package/dist/cjs/ui/status-chip.js +17 -0
  55. package/dist/esm/cli/doctor.js +3 -3
  56. package/dist/esm/cli/init.js +3 -3
  57. package/dist/esm/client/components/access-gate.js +60 -6
  58. package/dist/esm/client/components/ai-format.js +129 -0
  59. package/dist/esm/client/components/ai-widgets.js +223 -0
  60. package/dist/esm/client/components/app-shell.js +85 -50
  61. package/dist/esm/client/components/apps-grid.js +3 -2
  62. package/dist/esm/client/components/ask-ai.js +350 -0
  63. package/dist/esm/client/components/confirm-dialog.js +37 -0
  64. package/dist/esm/client/components/cursor-pagination.js +19 -0
  65. package/dist/esm/client/components/filter-tabs.js +21 -0
  66. package/dist/esm/client/components/grievance-notice.js +27 -0
  67. package/dist/esm/client/components/link-button.js +17 -10
  68. package/dist/esm/client/components/logo.js +4 -3
  69. package/dist/esm/client/components/nav.js +41 -1
  70. package/dist/esm/client/components/plan-pricing.js +25 -0
  71. package/dist/esm/client/components/plans.js +2 -2
  72. package/dist/esm/client/components/platform-gate.js +45 -0
  73. package/dist/esm/client/components/shell-context.js +141 -0
  74. package/dist/esm/client/components/side-nav.js +49 -22
  75. package/dist/esm/client/components/sidebar.js +120 -0
  76. package/dist/esm/client/components/subscribe-dialog.js +3 -3
  77. package/dist/esm/client/components/subscription.js +2 -2
  78. package/dist/esm/client/components/user-menu.js +121 -41
  79. package/dist/esm/client/components/workspace-switcher.js +97 -0
  80. package/dist/esm/client/components/workspace-type-gate.js +45 -0
  81. package/dist/esm/client/index.js +58 -5
  82. package/dist/esm/client/provider.js +94 -2
  83. package/dist/esm/client/use-checkout.js +9 -5
  84. package/dist/esm/errors.js +1 -1
  85. package/dist/esm/index.js +1 -0
  86. package/dist/esm/next/index.js +2 -2
  87. package/dist/esm/server/client.js +25 -2
  88. package/dist/esm/server/handler.js +237 -16
  89. package/dist/esm/server/http.js +52 -26
  90. package/dist/esm/server/resources/acting-as.js +13 -0
  91. package/dist/esm/server/resources/ai.js +15 -2
  92. package/dist/esm/server/resources/data.js +369 -0
  93. package/dist/esm/server/resources/entitlements.js +41 -0
  94. package/dist/esm/server/resources/identity.js +9 -3
  95. package/dist/esm/server/resources/kv.js +80 -0
  96. package/dist/esm/server/resources/platform.js +39 -0
  97. package/dist/esm/server/resources/sessions.js +1 -1
  98. package/dist/esm/server/resources/workspaces.js +70 -0
  99. package/dist/esm/store.js +141 -0
  100. package/dist/esm/ui/empty-state.js +25 -0
  101. package/dist/esm/ui/index.js +34 -0
  102. package/dist/esm/ui/page-header.js +24 -0
  103. package/dist/esm/ui/page-shell.js +41 -0
  104. package/dist/esm/ui/section.js +17 -0
  105. package/dist/esm/ui/setting-row.js +11 -0
  106. package/dist/esm/ui/status-chip.js +14 -0
  107. package/dist/theme.css +87 -0
  108. package/dist/types/client/components/access-gate.d.ts +17 -3
  109. package/dist/types/client/components/ai-format.d.ts +24 -0
  110. package/dist/types/client/components/ai-widgets.d.ts +42 -0
  111. package/dist/types/client/components/app-shell.d.ts +85 -31
  112. package/dist/types/client/components/apps-grid.d.ts +11 -2
  113. package/dist/types/client/components/ask-ai.d.ts +73 -0
  114. package/dist/types/client/components/confirm-dialog.d.ts +34 -0
  115. package/dist/types/client/components/cursor-pagination.d.ts +27 -0
  116. package/dist/types/client/components/filter-tabs.d.ts +26 -0
  117. package/dist/types/client/components/grievance-notice.d.ts +31 -0
  118. package/dist/types/client/components/link-button.d.ts +32 -9
  119. package/dist/types/client/components/logo.d.ts +18 -2
  120. package/dist/types/client/components/nav.d.ts +27 -3
  121. package/dist/types/client/components/plan-pricing.d.ts +10 -0
  122. package/dist/types/client/components/platform-gate.d.ts +53 -0
  123. package/dist/types/client/components/shell-context.d.ts +116 -0
  124. package/dist/types/client/components/side-nav.d.ts +28 -14
  125. package/dist/types/client/components/sidebar.d.ts +95 -0
  126. package/dist/types/client/components/user-menu.d.ts +70 -23
  127. package/dist/types/client/components/workspace-switcher.d.ts +49 -0
  128. package/dist/types/client/components/workspace-type-gate.d.ts +48 -0
  129. package/dist/types/client/index.d.ts +36 -7
  130. package/dist/types/client/provider.d.ts +149 -3
  131. package/dist/types/client/use-checkout.d.ts +8 -4
  132. package/dist/types/errors.d.ts +1 -1
  133. package/dist/types/index.d.ts +2 -0
  134. package/dist/types/next/index.d.ts +1 -1
  135. package/dist/types/server/client.d.ts +25 -2
  136. package/dist/types/server/http.d.ts +14 -3
  137. package/dist/types/server/index.d.ts +4 -0
  138. package/dist/types/server/resources/acting-as.d.ts +11 -0
  139. package/dist/types/server/resources/ai.d.ts +9 -1
  140. package/dist/types/server/resources/data.d.ts +258 -0
  141. package/dist/types/server/resources/entitlements.d.ts +33 -1
  142. package/dist/types/server/resources/kv.d.ts +63 -0
  143. package/dist/types/server/resources/platform.d.ts +32 -0
  144. package/dist/types/server/resources/workspaces.d.ts +55 -0
  145. package/dist/types/store.d.ts +96 -0
  146. package/dist/types/types.d.ts +491 -13
  147. package/dist/types/ui/empty-state.d.ts +34 -0
  148. package/dist/types/ui/index.d.ts +40 -0
  149. package/dist/types/ui/page-header.d.ts +34 -0
  150. package/dist/types/ui/page-shell.d.ts +39 -0
  151. package/dist/types/ui/section.d.ts +26 -0
  152. package/dist/types/ui/setting-row.d.ts +18 -0
  153. package/dist/types/ui/status-chip.d.ts +36 -0
  154. package/package.json +13 -3
@@ -0,0 +1,369 @@
1
+ import { ConnectError } from "../../errors.js";
2
+ import { pathSegment, request } from "../http.js";
3
+ import { actingAs } from "./acting-as.js";
4
+ /**
5
+ * Your application's own document store - a dedicated Firestore database that
6
+ * only Connect can reach.
7
+ *
8
+ * You hold no Firebase credential and write no security rules. Collections are
9
+ * declared in the Console; an undeclared name is refused rather than created,
10
+ * and `workspaceId` is a path segment rather than a filter, so a query cannot
11
+ * cross tenants.
12
+ *
13
+ * **A query needs an index for its shape, and there are two ways to have one.**
14
+ * Firestore maintains a single-field index automatically, which covers one
15
+ * filter, or an `orderBy` on that same field. Anything wider - two filters, or
16
+ * a filter ordered by a different field - needs a composite index **declared
17
+ * on your application's Store tab**, which Connect then builds in your
18
+ * database. A query with no matching index is refused up front, naming the
19
+ * index to declare, rather than failing later with a Firestore index error
20
+ * pointing at a console you cannot open.
21
+ *
22
+ * **Dates are ISO-8601 strings.** The store writes what you send it, and JSON
23
+ * has no date type, so a `Date` must be sent as `toISOString()`. That is not a
24
+ * compromise: UTC ISO strings sort lexicographically in chronological order,
25
+ * so ordering and range filters on them behave exactly as they would on a
26
+ * timestamp - and Connect's own `_createdAt`/`_updatedAt` come back in the
27
+ * same form.
28
+ *
29
+ * **`workspaceId` is omitted for master data.** A collection declared
30
+ * application-scoped in the Console belongs to no workspace - one copy, owned
31
+ * by you, read by every tenant. Those are written with your API key only,
32
+ * never on behalf of a user: a write permission is something a *workspace*
33
+ * grants, so honouring one on shared data would give one tenant's admin reach
34
+ * over every other tenant's reference data.
35
+ *
36
+ * **`asUser` is how you act on behalf of a signed-in user.** Pass the opaque
37
+ * `sessionToken` you were given at sign-in and Connect resolves the user and
38
+ * their workspace from it - checking the collection's declared permission
39
+ * against what that member actually holds, and **ignoring `workspaceId`
40
+ * entirely**. Without it you are the application itself: your API key's scopes
41
+ * are the only gate, and the per-user permissions do not apply. The bridge
42
+ * (`createConnectHandler`) always passes it, which is what makes the browser
43
+ * path safe.
44
+ */
45
+ export class DataResource {
46
+ transport;
47
+ constructor(transport) {
48
+ this.transport = transport;
49
+ }
50
+ /** Reads one document. Throws `ConnectError` with status 404 when it does not exist. */
51
+ get(input) {
52
+ return request(this.transport, {
53
+ method: "GET",
54
+ path: `/data/${pathSegment(input.collection, "collection")}/${pathSegment(input.id, "id")}`,
55
+ query: { workspaceId: input.workspaceId },
56
+ headers: actingAs(input.asUser),
57
+ });
58
+ }
59
+ /**
60
+ * Lists a collection, one page at a time.
61
+ *
62
+ * `filters` are ANDed. More than one, or one combined with an `orderBy` on a
63
+ * different field, needs a composite index declared on the Store tab - see
64
+ * the class note above.
65
+ *
66
+ * `limit` defaults to 50 and caps at 200. Page by passing the previous
67
+ * page's `nextCursor`; a `null` `nextCursor` is the end of the collection.
68
+ */
69
+ query(input) {
70
+ return request(this.transport, {
71
+ method: "GET",
72
+ path: `/data/${pathSegment(input.collection, "collection")}`,
73
+ headers: actingAs(input.asUser),
74
+ query: {
75
+ workspaceId: input.workspaceId,
76
+ // JSON rather than flattened params: a filter *value* is typed, and
77
+ // `42`, `"42"` and `true` are three different queries that a flattened
78
+ // form collapses into one.
79
+ filters: input.filters?.length ? JSON.stringify(input.filters) : undefined,
80
+ orderBy: input.orderBy ? JSON.stringify(input.orderBy) : undefined,
81
+ limit: input.limit,
82
+ cursor: input.cursor ?? undefined,
83
+ },
84
+ });
85
+ }
86
+ /**
87
+ * Counts, sums and averages a filtered collection - **in Firestore**, not by
88
+ * reading the rows back and adding them up.
89
+ *
90
+ * That distinction is the whole point. An aggregation is billed by the index
91
+ * entries it scans rather than by the documents it would have returned, so a
92
+ * dashboard tile over ten thousand rows costs a handful of reads and stays
93
+ * flat as the collection grows. Paging the rows into your own process to sum
94
+ * them is an unbounded read, and it is what every integration does when
95
+ * there is no aggregate call to reach for.
96
+ *
97
+ * ```ts
98
+ * const { values } = await connect.data.aggregate({
99
+ * workspaceId,
100
+ * collection: "deals",
101
+ * filters: [{ field: "outcome", op: "==", value: "won" }],
102
+ * aggregations: [
103
+ * { op: "count", alias: "count" },
104
+ * { op: "sum", field: "value", alias: "total" },
105
+ * ],
106
+ * });
107
+ * ```
108
+ *
109
+ * A `sum` or `avg` over nothing answers `null` rather than `0`, because
110
+ * "nothing matched" and "the total is zero" are different facts.
111
+ *
112
+ * The index it needs is the one its **filters** need plus the aggregated
113
+ * field - Firestore reads a sum out of the index rather than out of the
114
+ * documents.
115
+ *
116
+ * There is no `orderBy`, `limit` or `cursor`: the aggregate of an ordered
117
+ * page is the aggregate of the whole filtered set.
118
+ */
119
+ aggregate(input) {
120
+ return request(this.transport, {
121
+ method: "GET",
122
+ path: `/data-aggregate/${pathSegment(input.collection, "collection")}`,
123
+ headers: actingAs(input.asUser),
124
+ query: {
125
+ workspaceId: input.workspaceId,
126
+ aggregations: JSON.stringify(input.aggregations.map((aggregation) => ({
127
+ op: aggregation.op,
128
+ field: aggregation.field ?? null,
129
+ alias: aggregation.alias,
130
+ }))),
131
+ filters: input.filters?.length ? JSON.stringify(input.filters) : undefined,
132
+ },
133
+ });
134
+ }
135
+ /**
136
+ * Reads one collection across **every workspace at once** - your own
137
+ * back-office view of your whole customer base. Each row carries the
138
+ * `workspaceId` it came from.
139
+ *
140
+ * Needs the `data:read:all` scope, and the collection must be marked
141
+ * cross-workspace in the Console. There is deliberately **no `asUser`**: a
142
+ * scan is never available on behalf of a signed-in user, because a workspace
143
+ * admin is an admin of their own workspace and not of your other customers.
144
+ *
145
+ * Filtering and ordering follow the same index rules as `query`, and
146
+ * additionally need collection-group scope. Connect creates those from the
147
+ * declaration - the single-field ones when you mark a field queryable, and a
148
+ * group-scoped copy of every composite index the collection declares. A scan
149
+ * issued in the minutes after that declaration may fail while the index
150
+ * builds.
151
+ */
152
+ scan(input) {
153
+ return request(this.transport, {
154
+ method: "GET",
155
+ path: `/data-scan/${pathSegment(input.collection, "collection")}`,
156
+ query: {
157
+ filters: input.filters?.length ? JSON.stringify(input.filters) : undefined,
158
+ orderBy: input.orderBy ? JSON.stringify(input.orderBy) : undefined,
159
+ limit: input.limit,
160
+ cursor: input.cursor ?? undefined,
161
+ },
162
+ });
163
+ }
164
+ /**
165
+ * Creates a document. Pass `id` to choose it, or omit it and one is
166
+ * allocated. An `id` that already exists throws with status 409 - use
167
+ * `replace` to overwrite deliberately.
168
+ */
169
+ create(input) {
170
+ return request(this.transport, {
171
+ method: "POST",
172
+ path: `/data/${pathSegment(input.collection, "collection")}`,
173
+ headers: actingAs(input.asUser),
174
+ json: { workspaceId: input.workspaceId, id: input.id ?? null, data: input.data },
175
+ });
176
+ }
177
+ /** Replaces every field, creating the document if it does not exist. `_createdAt`/`_createdBy` survive. */
178
+ replace(input) {
179
+ return this.write(input, "replace");
180
+ }
181
+ /** Merges top-level fields into an existing document. Throws with status 404 if it does not exist. */
182
+ update(input) {
183
+ return this.write(input, "merge");
184
+ }
185
+ /** Idempotent - deleting a document that is not there succeeds. */
186
+ async delete(input) {
187
+ await request(this.transport, {
188
+ method: "DELETE",
189
+ path: `/data/${pathSegment(input.collection, "collection")}/${pathSegment(input.id, "id")}`,
190
+ query: { workspaceId: input.workspaceId },
191
+ headers: actingAs(input.asUser),
192
+ });
193
+ }
194
+ /**
195
+ * Applies a set of writes atomically, across as many of your collections as
196
+ * they name. All of them land, or none.
197
+ *
198
+ * This is the store's answer to a database transaction, and the shape is
199
+ * deliberate: **you never hold one**. A transaction handle passed across an
200
+ * HTTP boundary is a server-side lock whose duration your network controls,
201
+ * with Firestore's sixty-second ceiling and lock contention as the failure
202
+ * mode. Instead you read, decide, and commit *conditional on nothing having
203
+ * moved* - Connect runs the whole set as one short transaction on its side.
204
+ *
205
+ * ```ts
206
+ * await connect.data.commit({
207
+ * workspaceId,
208
+ * operations: [
209
+ * { op: "create", collection: "ledger", id, data: entry },
210
+ * {
211
+ * op: "merge",
212
+ * collection: "funds",
213
+ * id: entry.fundId,
214
+ * data: { balancePaise: increment(entry.amountPaise) },
215
+ * },
216
+ * ],
217
+ * });
218
+ * ```
219
+ *
220
+ * A precondition that no longer holds throws `ConnectError` with status 409
221
+ * and **writes nothing** - see `transaction`, which re-reads and retries for
222
+ * you. Note that the example above needs no precondition at all: an
223
+ * `increment` is commutative, so concurrent commits both land correctly.
224
+ *
225
+ * Returns the id each operation wrote, in order - which is how you learn the
226
+ * id a `create` without one was given.
227
+ */
228
+ commit(input) {
229
+ return request(this.transport, {
230
+ method: "POST",
231
+ path: "/data-commit",
232
+ headers: actingAs(input.asUser),
233
+ json: {
234
+ workspaceId: input.workspaceId,
235
+ operations: input.operations.map((operation) => ({
236
+ op: operation.op,
237
+ collection: operation.collection,
238
+ id: operation.id ?? null,
239
+ data: operation.data ?? null,
240
+ precondition: operation.precondition ?? null,
241
+ })),
242
+ },
243
+ });
244
+ }
245
+ /**
246
+ * Read, decide, commit - retried when the world moved underneath you.
247
+ *
248
+ * The optimistic-concurrency loop, written once. `build` reads whatever it
249
+ * needs and returns the operations to apply; if any precondition among them
250
+ * has gone stale by the time Connect looks, the commit is rejected whole and
251
+ * `build` runs again against fresh reads.
252
+ *
253
+ * ```ts
254
+ * await connect.data.transaction(async () => {
255
+ * const fund = await connect.data.get({ workspaceId, collection: "funds", id });
256
+ * if (!fund.data.active) throw new Error("That fund is closed.");
257
+ * return [
258
+ * {
259
+ * op: "merge",
260
+ * collection: "funds",
261
+ * id,
262
+ * data: { balancePaise: increment(amount) },
263
+ * precondition: unchangedSince(fund),
264
+ * },
265
+ * ];
266
+ * });
267
+ * ```
268
+ *
269
+ * **Only a 409 is retried.** A 403 or a validation error means the operation
270
+ * was wrong rather than late, and retrying it would turn one clear failure
271
+ * into `attempts` identical ones. An error thrown by `build` itself - the
272
+ * closed-fund check above - is not retried either: it is a decision, not a
273
+ * collision.
274
+ *
275
+ * `build` must be free of side effects outside the returned operations,
276
+ * because it can run more than once. That is the price of not holding a
277
+ * lock, and it is the same contract Firestore's own `runTransaction` states
278
+ * for the same reason.
279
+ */
280
+ async transaction(build, options = {}) {
281
+ const attempts = options.attempts ?? 4;
282
+ let lastConflict;
283
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
284
+ const operations = await build();
285
+ try {
286
+ return await this.commit({
287
+ workspaceId: options.workspaceId,
288
+ operations,
289
+ asUser: options.asUser,
290
+ });
291
+ }
292
+ catch (error) {
293
+ if (!isConflict(error))
294
+ throw error;
295
+ lastConflict = error;
296
+ }
297
+ }
298
+ throw lastConflict;
299
+ }
300
+ write(input, mode) {
301
+ return request(this.transport, {
302
+ method: "PUT",
303
+ path: `/data/${pathSegment(input.collection, "collection")}/${pathSegment(input.id, "id")}`,
304
+ headers: { "x-store-write-mode": mode, ...actingAs(input.asUser) },
305
+ json: { workspaceId: input.workspaceId, data: input.data },
306
+ });
307
+ }
308
+ }
309
+ /**
310
+ * A stale precondition, as opposed to any other refusal.
311
+ *
312
+ * Matched on the status rather than on the message, which is not part of any
313
+ * contract - and narrowly, because retrying anything else turns one honest
314
+ * failure into four.
315
+ */
316
+ function isConflict(error) {
317
+ return error instanceof ConnectError && error.status === 409;
318
+ }
319
+ /**
320
+ * A raw store passthrough, for `createConnectHandler` and nothing else.
321
+ *
322
+ * The bridge relays a browser's `/data/*` and `/kv/*` request without
323
+ * reconstructing it into a typed call - it has a path, a body and a session
324
+ * token, and re-parsing them into `get`/`query`/`create` only to serialise
325
+ * them again would be a second implementation of the same URL grammar, drifting
326
+ * from this one.
327
+ *
328
+ * **Deliberately not a generic proxy.** The path is refused unless it is one
329
+ * of the store endpoints, so this cannot become a way to reach the rest of the
330
+ * application API under a browser's control - which is the property the bridge
331
+ * has always been careful to keep.
332
+ *
333
+ * `/data-scan/` is deliberately **not** in that set. A scan crosses every
334
+ * tenant, and Connect refuses one made on behalf of a user anyway - but a
335
+ * browser should not be able to *ask*, so the refusal happens here rather than
336
+ * a round trip away.
337
+ */
338
+ /**
339
+ * The store paths a browser may reach through the bridge: documents, the
340
+ * key/value store, aggregations, and atomic commits. Anchored, so a path like
341
+ * `/data-scan/tickets` cannot slip through on a prefix match.
342
+ */
343
+ const STORE_PATHS = /^\/(?:data|kv|data-aggregate)\/|^\/data-commit$/;
344
+ // `async` so the refusal below arrives as a rejected promise rather than a
345
+ // synchronous throw. A function typed `Promise<Response>` that sometimes
346
+ // throws before returning one is the kind of thing a caller's `.catch()`
347
+ // misses.
348
+ export async function storePassthrough(transport, spec) {
349
+ // The query string is stripped first: the bridge appends `?workspaceId=…`
350
+ // to every relayed path, and an anchored match against the whole thing would
351
+ // reject `/data-commit?workspaceId=…` for having one.
352
+ if (!STORE_PATHS.test(spec.path.split("?")[0] ?? "")) {
353
+ throw new ConnectError({
354
+ status: 0,
355
+ code: "validation_error",
356
+ message: `storePassthrough only serves the store endpoints, not "${spec.path}"`,
357
+ endpoint: "client",
358
+ });
359
+ }
360
+ return request(transport, {
361
+ method: spec.method,
362
+ path: spec.path,
363
+ json: spec.json,
364
+ headers: spec.headers,
365
+ // The bridge hands Connect's response straight back to the browser, status
366
+ // and all, rather than parsing and re-encoding it.
367
+ raw: true,
368
+ });
369
+ }
@@ -42,4 +42,45 @@ export class EntitlementsResource {
42
42
  const result = await this.getSubscription(workspaceId);
43
43
  return result.hasActiveSubscription && (result.plan?.features.includes(feature) ?? false);
44
44
  }
45
+ /**
46
+ * One page of the workspaces subscribed to your application, newest first.
47
+ *
48
+ * The inverse of `getSubscription`, which asks about one workspace you
49
+ * already know. This asks who your subscribers *are* - what a partner
50
+ * dashboard, an MRR total or a churn report is built on.
51
+ *
52
+ * Rate-limited far more tightly than the per-workspace read (10/min per
53
+ * key, against 60): it walks your whole subscriber base and is a reporting
54
+ * call, not a per-request gate. Use `getSubscription` in a hot path.
55
+ *
56
+ * Your application is resolved from the API key, so there is no parameter
57
+ * for it and no way to ask about anyone else's.
58
+ */
59
+ listSubscribers(options = {}) {
60
+ return request(this.transport, {
61
+ method: "GET",
62
+ path: "/subscriptions",
63
+ query: { status: options.status, before: options.before, limit: options.limit },
64
+ });
65
+ }
66
+ /**
67
+ * Every subscriber, paged through for you.
68
+ *
69
+ * An async generator rather than an array: a large subscriber base is
70
+ * exactly where an accidental full materialisation hurts, and `for await`
71
+ * reads the same as a loop over one page.
72
+ */
73
+ async *iterateSubscribers(options = {}) {
74
+ let before;
75
+ do {
76
+ const page = await this.listSubscribers({
77
+ status: options.status,
78
+ limit: options.pageSize,
79
+ before,
80
+ });
81
+ for (const item of page.items)
82
+ yield item;
83
+ before = page.nextBefore ?? undefined;
84
+ } while (before);
85
+ }
45
86
  }
@@ -66,7 +66,10 @@ export class IdentityResource {
66
66
  sessionTokenExpiresIn: wire.session_token_expires_in,
67
67
  user: wire.user,
68
68
  subscription: wire.subscription,
69
- applicationRole: wire.applicationRole,
69
+ role: wire.role,
70
+ permissions: wire.permissions,
71
+ staff: wire.staff,
72
+ audience: wire.audience,
70
73
  };
71
74
  }
72
75
  /**
@@ -136,7 +139,10 @@ export class IdentityResource {
136
139
  return {
137
140
  user: wire.user,
138
141
  subscription: wire.subscription,
139
- applicationRole: wire.applicationRole,
142
+ role: wire.role,
143
+ permissions: wire.permissions,
144
+ staff: wire.staff,
145
+ audience: wire.audience,
140
146
  sessionExpiresAt: wire.session_expires_at,
141
147
  };
142
148
  }
@@ -177,7 +183,7 @@ export class IdentityResource {
177
183
  throw new ConnectError({
178
184
  status: 0,
179
185
  code: "missing_client_id",
180
- message: "identity.* needs `clientId`. Pass it to `new ConnectClient({ clientId, apiKey })` - it is shown in this application's Integration tab, under Connect client.",
186
+ message: "identity.* needs `clientId`. Pass it to `new ConnectClient({ clientId, apiKey })` - it is shown in this application's Connect client section.",
181
187
  endpoint: "identity",
182
188
  });
183
189
  }
@@ -0,0 +1,80 @@
1
+ import { pathSegment, request } from "../http.js";
2
+ import { actingAs } from "./acting-as.js";
3
+ /**
4
+ * Your application's key/value store - small values addressed by namespace and
5
+ * key, per workspace.
6
+ *
7
+ * Use it for what a document store is bad at: a feature flag, a cached
8
+ * computation, a counter, a draft nobody needs to query. Anything you want to
9
+ * *find* rather than *fetch* belongs in `data`.
10
+ *
11
+ * Namespaces are declared in the Console exactly like collections. Keys are
12
+ * `[A-Za-z0-9_-]` up to 64 characters, and values are JSON up to 128 KB.
13
+ *
14
+ * `asUser` behaves exactly as it does on `DataResource` - pass a signed-in
15
+ * user's `sessionToken` and Connect derives the user and workspace from it,
16
+ * checking the namespace's declared permission against their live roles.
17
+ */
18
+ export class KvResource {
19
+ transport;
20
+ constructor(transport) {
21
+ this.transport = transport;
22
+ }
23
+ /**
24
+ * Reads one key. Throws `ConnectError` with status 404 when the key is
25
+ * absent **or expired** - expiry is evaluated on read, so there is no window
26
+ * where a stale value is still served.
27
+ */
28
+ get(input) {
29
+ return request(this.transport, {
30
+ method: "GET",
31
+ path: this.path(input.namespace, input.key),
32
+ query: { workspaceId: input.workspaceId },
33
+ headers: actingAs(input.asUser),
34
+ });
35
+ }
36
+ /**
37
+ * Pages a namespace in key order.
38
+ *
39
+ * Expired entries are filtered out after paging, so a page can come back
40
+ * shorter than `limit` while still having a `nextCursor` - treat
41
+ * `nextCursor` as the only signal that more keys exist, never an empty page.
42
+ */
43
+ list(input) {
44
+ return request(this.transport, {
45
+ method: "GET",
46
+ path: `/kv/${pathSegment(input.namespace, "namespace")}`,
47
+ headers: actingAs(input.asUser),
48
+ query: {
49
+ workspaceId: input.workspaceId,
50
+ limit: input.limit,
51
+ cursor: input.cursor ?? undefined,
52
+ },
53
+ });
54
+ }
55
+ /** Sets a value, replacing whatever was there. `ttlSeconds` expires it; omit for no expiry. */
56
+ set(input) {
57
+ return request(this.transport, {
58
+ method: "PUT",
59
+ path: this.path(input.namespace, input.key),
60
+ headers: actingAs(input.asUser),
61
+ json: {
62
+ workspaceId: input.workspaceId,
63
+ value: input.value,
64
+ ttlSeconds: input.ttlSeconds ?? null,
65
+ },
66
+ });
67
+ }
68
+ /** Idempotent - deleting an absent key succeeds. */
69
+ async delete(input) {
70
+ await request(this.transport, {
71
+ method: "DELETE",
72
+ path: this.path(input.namespace, input.key),
73
+ query: { workspaceId: input.workspaceId },
74
+ headers: actingAs(input.asUser),
75
+ });
76
+ }
77
+ path(namespace, key) {
78
+ return `/kv/${pathSegment(namespace, "namespace")}/${pathSegment(key, "key")}`;
79
+ }
80
+ }
@@ -0,0 +1,39 @@
1
+ import { request } from "../http.js";
2
+ /**
3
+ * Facts about the platform itself, rather than about a workspace or a user.
4
+ *
5
+ * One method today, and the resource exists anyway rather than hanging
6
+ * `getCompanyProfile` off `identity` or `workspaces`: neither of those is
7
+ * what it is about. This answers "who operates the thing my application runs
8
+ * on", which is a different subject from every other resource here, and a
9
+ * misfiled method is harder to find than an obvious one-method namespace.
10
+ */
11
+ export class PlatformResource {
12
+ transport;
13
+ constructor(transport) {
14
+ this.transport = transport;
15
+ }
16
+ /**
17
+ * The operating entity's legal identity and its DPDP grievance channel.
18
+ *
19
+ * Takes no `workspaceId` and takes no `asUser` - the answer is the same for
20
+ * every tenant and every caller, because it is a fact about the platform.
21
+ *
22
+ * Returns the inner `companyProfile` rather than the envelope, matching
23
+ * `apps.list()` and `billing.listPlans()`: the wrapper is a wire detail, and
24
+ * every caller would destructure it on the next line.
25
+ *
26
+ * **Do not copy the result into your own configuration.** Cache it if you
27
+ * render it on a hot path - Connect already sends
28
+ * `s-maxage=3600, stale-while-revalidate=86400` - but the reason this is an
29
+ * endpoint at all is that a grievance officer copied into `.env` goes stale
30
+ * without anyone finding out.
31
+ */
32
+ async getCompanyProfile() {
33
+ const result = await request(this.transport, {
34
+ method: "GET",
35
+ path: "/company-profile",
36
+ });
37
+ return result.companyProfile;
38
+ }
39
+ }
@@ -69,7 +69,7 @@ export class SessionsResource {
69
69
  throw new ConnectError({
70
70
  status: 0,
71
71
  code: "missing_client_id",
72
- message: "sessions.* needs `clientId`. Pass it to `new ConnectClient({ clientId, apiKey })` - it is shown in this application's Integration tab, under Connect client.",
72
+ message: "sessions.* needs `clientId`. Pass it to `new ConnectClient({ clientId, apiKey })` - it is shown in this application's Connect client section.",
73
73
  endpoint: "sessions",
74
74
  });
75
75
  }
@@ -0,0 +1,70 @@
1
+ import { actingAs } from "./acting-as.js";
2
+ import { request } from "../http.js";
3
+ /**
4
+ * Which workspaces the signed-in user belongs to, moving between them, and who
5
+ * else is on the team.
6
+ *
7
+ * **Every call here needs `asUser`** - the signed-in user's opaque
8
+ * `sessionToken`. There is no application-wide form of any of these: they take
9
+ * no `userId` and no `workspaceId`, and resolve both from the token. That is
10
+ * what makes the whole module safe to reach from a browser through
11
+ * `createConnectHandler`, and it is why a partner cannot enumerate another
12
+ * tenant's team with their own API key.
13
+ */
14
+ export class WorkspacesResource {
15
+ transport;
16
+ constructor(transport) {
17
+ this.transport = transport;
18
+ }
19
+ /**
20
+ * The workspaces this user could switch to.
21
+ *
22
+ * Rows carry `inAudience` and `subscribed` so a switcher can show a
23
+ * workspace it cannot select, with the reason. Hiding it instead reads as
24
+ * data loss to the person who owns it.
25
+ */
26
+ async list(options) {
27
+ const result = await request(this.transport, {
28
+ method: "GET",
29
+ path: "/workspaces",
30
+ headers: actingAs(options.asUser),
31
+ });
32
+ return result.workspaces;
33
+ }
34
+ /**
35
+ * Moves this session to another workspace, returning a **new session
36
+ * token**. The one you passed is revoked.
37
+ *
38
+ * Persist the result before navigating - dropping it signs the user out,
39
+ * because the old token no longer works.
40
+ *
41
+ * Throws with status 404 when the workspace does not exist *or* the user is
42
+ * not a member (deliberately indistinguishable), and 403 when it is outside
43
+ * your audience, requires an MFA factor they have not enrolled, or is the
44
+ * workspace they are already on.
45
+ */
46
+ switch(input, options) {
47
+ return request(this.transport, {
48
+ method: "POST",
49
+ path: "/workspaces/switch",
50
+ headers: actingAs(options.asUser),
51
+ json: input,
52
+ });
53
+ }
54
+ /**
55
+ * The team of the workspace this session is on.
56
+ *
57
+ * Members carry permissions already resolved for *your* application, not raw
58
+ * Connect roles - so you never reimplement Connect's role resolution, and
59
+ * you are told nothing about the customer's Connect account beyond what your
60
+ * application needs.
61
+ */
62
+ async members(options) {
63
+ const result = await request(this.transport, {
64
+ method: "GET",
65
+ path: "/workspaces/members",
66
+ headers: actingAs(options.asUser),
67
+ });
68
+ return result.members;
69
+ }
70
+ }