usebecky 0.0.0-stage → 0.2.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 (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,162 @@
1
+ import { UseBeckyError } from '../lib/errors.ts';
2
+ import type { HttpClient } from '../lib/http.ts';
3
+ import type { ColumnName, ColumnValue, FunctionArgs, FunctionName, FunctionReturns, InsertOf, RowOf, SchemaOf, SelectResult, TableName, UpdateOf } from './types.ts';
4
+ /** What every database call resolves to. Check `error` first. */
5
+ export type QueryResult<T> = {
6
+ data: T;
7
+ error: null;
8
+ count: number | null;
9
+ status: number;
10
+ } | {
11
+ data: null;
12
+ error: UseBeckyError;
13
+ count: null;
14
+ status: number;
15
+ };
16
+ export type CountOption = 'exact' | 'planned' | 'estimated';
17
+ type Method = 'GET' | 'HEAD' | 'POST' | 'PATCH' | 'DELETE';
18
+ type Mode = 'many' | 'single' | 'maybeSingle';
19
+ interface BuilderState {
20
+ http: HttpClient;
21
+ method: Method;
22
+ path: string;
23
+ params: Array<[string, string]>;
24
+ prefer: Record<string, string>;
25
+ body?: unknown;
26
+ mode: Mode;
27
+ isRpc: boolean;
28
+ signal?: AbortSignal;
29
+ }
30
+ export declare function parseContentRange(header: string | null | undefined): number | null;
31
+ export declare class QueryBuilder<Row = any, Result = any> implements PromiseLike<QueryResult<Result>> {
32
+ protected s: BuilderState;
33
+ constructor(state: BuilderState);
34
+ private add;
35
+ private set;
36
+ /** column = value */
37
+ eq<K extends ColumnName<Row>>(column: K, value: ColumnValue<Row, K>): this;
38
+ /** column <> value */
39
+ neq<K extends ColumnName<Row>>(column: K, value: ColumnValue<Row, K>): this;
40
+ /** column > value */
41
+ gt<K extends ColumnName<Row>>(column: K, value: ColumnValue<Row, K>): this;
42
+ /** column >= value */
43
+ gte<K extends ColumnName<Row>>(column: K, value: ColumnValue<Row, K>): this;
44
+ /** column < value */
45
+ lt<K extends ColumnName<Row>>(column: K, value: ColumnValue<Row, K>): this;
46
+ /** column <= value */
47
+ lte<K extends ColumnName<Row>>(column: K, value: ColumnValue<Row, K>): this;
48
+ /** Case-sensitive pattern match. Use `%` (or `*`) as the wildcard: `.like('title', '%milk%')` */
49
+ like(column: ColumnName<Row>, pattern: string): this;
50
+ /** Case-insensitive pattern match: `.ilike('email', '%@gmail.com')` */
51
+ ilike(column: ColumnName<Row>, pattern: string): this;
52
+ /** `IS NULL`, `IS TRUE`, `IS FALSE` */
53
+ is(column: ColumnName<Row>, value: null | boolean): this;
54
+ /** column is one of the values: `.in('status', ['open', 'pending'])` */
55
+ in<K extends ColumnName<Row>>(column: K, values: ReadonlyArray<ColumnValue<Row, K>>): this;
56
+ /** Array/JSON/range column contains every value: `.contains('tags', ['a', 'b'])` */
57
+ contains(column: ColumnName<Row>, value: string | readonly unknown[] | Record<string, unknown>): this;
58
+ /** Every element of the column is in `value`. */
59
+ containedBy(column: ColumnName<Row>, value: string | readonly unknown[] | Record<string, unknown>): this;
60
+ /** Array/range column shares at least one element with `value`. */
61
+ overlaps(column: ColumnName<Row>, value: string | readonly unknown[]): this;
62
+ /** Full-text search: `.textSearch('body', 'cats & dogs', { config: 'english' })` */
63
+ textSearch(column: ColumnName<Row>, query: string, options?: {
64
+ config?: string;
65
+ type?: 'plain' | 'phrase' | 'websearch';
66
+ }): this;
67
+ /** Negate a filter: `.not('status', 'eq', 'done')`, `.not('id', 'in', [1, 2])` */
68
+ not(column: ColumnName<Row>, operator: string, value: unknown): this;
69
+ /** Match any of the filters: `.or('status.eq.open,priority.gt.3')` */
70
+ or(filters: string, options?: {
71
+ referencedTable?: string;
72
+ }): this;
73
+ /** Shorthand for several `.eq()`: `.match({ user_id: id, done: false })` */
74
+ match(query: Partial<IsRecord<Row>> | Record<string, unknown>): this;
75
+ /** Any PostgREST operator, unescaped: `.filter('tags', 'cs', '{a,b}')` */
76
+ filter(column: ColumnName<Row>, operator: string, value: unknown): this;
77
+ /**
78
+ * Choose columns. After insert/update/upsert/delete this returns the changed rows
79
+ * (otherwise those return `data: null`).
80
+ */
81
+ select<Q extends string = '*'>(columns?: Q, options?: {
82
+ count?: CountOption;
83
+ }): QueryBuilder<Row, SelectResult<Row, Q>[]>;
84
+ /** Sort: `.order('created_at', { ascending: false })`. Call again to add a tiebreaker. */
85
+ order(column: ColumnName<Row>, options?: {
86
+ ascending?: boolean;
87
+ nullsFirst?: boolean;
88
+ referencedTable?: string;
89
+ }): this;
90
+ /** Return at most `count` rows. */
91
+ limit(count: number, options?: {
92
+ referencedTable?: string;
93
+ }): this;
94
+ /** Rows `from` to `to` (inclusive, 0-based): `.range(0, 9)` is the first 10 rows. */
95
+ range(from: number, to: number, options?: {
96
+ referencedTable?: string;
97
+ }): this;
98
+ /** Return one row as an object instead of an array. Errors if there is not exactly one. */
99
+ single(): QueryBuilder<Row, Result extends Array<infer E> ? E : Result>;
100
+ /** Return one row, or `null` when nothing matches. Errors if more than one matches. */
101
+ maybeSingle(): QueryBuilder<Row, Result extends Array<infer E> ? E | null : Result | null>;
102
+ /** Cancel the request with an AbortController signal. */
103
+ abortSignal(signal: AbortSignal): this;
104
+ /** Override the result type (for when you know better than the types). */
105
+ returns<T>(): QueryBuilder<Row, T>;
106
+ then<TResult1 = QueryResult<Result>, TResult2 = never>(onfulfilled?: ((value: QueryResult<Result>) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
107
+ private execute;
108
+ }
109
+ type IsRecord<T> = T extends Record<string, any> ? T : Record<string, unknown>;
110
+ export declare class TableQuery<Row = any, Insert = any, Update = any> {
111
+ private http;
112
+ private path;
113
+ constructor(http: HttpClient, table: string);
114
+ private builder;
115
+ /**
116
+ * Read rows. `columns` uses PostgREST syntax: `'id, title, author:profiles(name)'`.
117
+ * `{ count: 'exact' }` also returns the total number of matching rows; add `head: true` to skip the rows.
118
+ */
119
+ select<Q extends string = '*'>(columns?: Q, options?: {
120
+ count?: CountOption;
121
+ head?: boolean;
122
+ }): QueryBuilder<Row, SelectResult<Row, Q>[]>;
123
+ /** Insert one row or many. Chain `.select()` to get the new rows back. */
124
+ insert(values: Insert | Insert[], options?: {
125
+ count?: CountOption;
126
+ defaultToNull?: boolean;
127
+ }): QueryBuilder<Row, null>;
128
+ /** Insert, or update when a row with the same primary key (or `onConflict` columns) exists. */
129
+ upsert(values: Insert | Insert[], options?: {
130
+ onConflict?: string;
131
+ ignoreDuplicates?: boolean;
132
+ count?: CountOption;
133
+ defaultToNull?: boolean;
134
+ }): QueryBuilder<Row, null>;
135
+ /** Update matching rows. Always add a filter, e.g. `.eq('id', id)`. */
136
+ update(values: Update, options?: {
137
+ count?: CountOption;
138
+ }): QueryBuilder<Row, null>;
139
+ /** Delete matching rows. Always add a filter, e.g. `.eq('id', id)`. */
140
+ delete(options?: {
141
+ count?: CountOption;
142
+ }): QueryBuilder<Row, null>;
143
+ }
144
+ export declare function rpcQuery(http: HttpClient, fn: string, args: Record<string, unknown> | undefined, options?: {
145
+ head?: boolean;
146
+ get?: boolean;
147
+ count?: CountOption;
148
+ }): QueryBuilder<any, any>;
149
+ /** Database access bound to one HTTP client (and therefore one role/user). */
150
+ export declare class Database<DB = any> {
151
+ protected http: HttpClient;
152
+ constructor(http: HttpClient);
153
+ /** Start a query on a table or view: `baas.from('todos').select()` */
154
+ from<T extends TableName<SchemaOf<DB>>>(table: T): TableQuery<RowOf<SchemaOf<DB>, T>, InsertOf<SchemaOf<DB>, T>, UpdateOf<SchemaOf<DB>, T>>;
155
+ /** Call a Postgres function: `baas.rpc('add_points', { amount: 5 })` */
156
+ rpc<F extends FunctionName<SchemaOf<DB>>>(fn: F, args?: FunctionArgs<SchemaOf<DB>, F>, options?: {
157
+ head?: boolean;
158
+ get?: boolean;
159
+ count?: CountOption;
160
+ }): QueryBuilder<FunctionReturns<SchemaOf<DB>, F> extends Array<infer E> ? E : any, FunctionReturns<SchemaOf<DB>, F>>;
161
+ }
162
+ export {};
@@ -0,0 +1,336 @@
1
+ // PostgREST-style query builder: chainable, and `await`-able (it is a thenable).
2
+ //
3
+ // const { data, error, count } = await baas.from('todos').select('*', { count: 'exact' }).eq('done', false).limit(20)
4
+ import { UseBeckyError } from "../lib/errors.js";
5
+ // ---- value formatting -----------------------------------------------------------------------
6
+ function fmt(v) {
7
+ if (v === null || v === undefined)
8
+ return 'null';
9
+ if (v instanceof Date)
10
+ return v.toISOString();
11
+ if (typeof v === 'object')
12
+ return JSON.stringify(v);
13
+ return String(v);
14
+ }
15
+ function quote(v, reserved) {
16
+ const s = fmt(v);
17
+ if (s === '' || reserved.test(s))
18
+ return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
19
+ return s;
20
+ }
21
+ /** `in.(a,b,"c d")` */
22
+ function fmtList(values) {
23
+ return `(${values.map((v) => (v === null ? 'null' : quote(v, /[,()"\\\s]/))).join(',')})`;
24
+ }
25
+ /** Postgres array literal `{a,b,"c d"}` */
26
+ function fmtArray(values) {
27
+ return `{${values.map((v) => (v === null ? 'NULL' : quote(v, /[,{}"\\\s]/))).join(',')}}`;
28
+ }
29
+ function fmtContains(value) {
30
+ if (Array.isArray(value))
31
+ return fmtArray(value);
32
+ if (typeof value === 'string')
33
+ return value;
34
+ return JSON.stringify(value);
35
+ }
36
+ function fmtOperand(operator, value) {
37
+ if (operator === 'in' && Array.isArray(value))
38
+ return fmtList(value);
39
+ if ((operator === 'cs' || operator === 'cd' || operator === 'ov') && typeof value !== 'string')
40
+ return fmtContains(value);
41
+ if ((operator === 'like' || operator === 'ilike') && typeof value === 'string')
42
+ return value.replace(/%/g, '*');
43
+ return fmt(value);
44
+ }
45
+ export function parseContentRange(header) {
46
+ if (!header)
47
+ return null;
48
+ const total = header.split('/')[1];
49
+ if (!total || total === '*')
50
+ return null;
51
+ const n = Number(total);
52
+ return Number.isFinite(n) ? n : null;
53
+ }
54
+ // ---- builder ----------------------------------------------------------------------------------
55
+ export class QueryBuilder {
56
+ s;
57
+ constructor(state) {
58
+ this.s = state;
59
+ }
60
+ add(key, value) {
61
+ this.s.params.push([key, value]);
62
+ return this;
63
+ }
64
+ set(key, value) {
65
+ this.s.params = this.s.params.filter(([k]) => k !== key);
66
+ this.s.params.push([key, value]);
67
+ return this;
68
+ }
69
+ // ---- filters ----
70
+ /** column = value */
71
+ eq(column, value) {
72
+ return this.add(column, `eq.${fmt(value)}`);
73
+ }
74
+ /** column <> value */
75
+ neq(column, value) {
76
+ return this.add(column, `neq.${fmt(value)}`);
77
+ }
78
+ /** column > value */
79
+ gt(column, value) {
80
+ return this.add(column, `gt.${fmt(value)}`);
81
+ }
82
+ /** column >= value */
83
+ gte(column, value) {
84
+ return this.add(column, `gte.${fmt(value)}`);
85
+ }
86
+ /** column < value */
87
+ lt(column, value) {
88
+ return this.add(column, `lt.${fmt(value)}`);
89
+ }
90
+ /** column <= value */
91
+ lte(column, value) {
92
+ return this.add(column, `lte.${fmt(value)}`);
93
+ }
94
+ /** Case-sensitive pattern match. Use `%` (or `*`) as the wildcard: `.like('title', '%milk%')` */
95
+ like(column, pattern) {
96
+ return this.add(column, `like.${fmtOperand('like', pattern)}`);
97
+ }
98
+ /** Case-insensitive pattern match: `.ilike('email', '%@gmail.com')` */
99
+ ilike(column, pattern) {
100
+ return this.add(column, `ilike.${fmtOperand('ilike', pattern)}`);
101
+ }
102
+ /** `IS NULL`, `IS TRUE`, `IS FALSE` */
103
+ is(column, value) {
104
+ return this.add(column, `is.${fmt(value)}`);
105
+ }
106
+ /** column is one of the values: `.in('status', ['open', 'pending'])` */
107
+ in(column, values) {
108
+ return this.add(column, `in.${fmtList(values)}`);
109
+ }
110
+ /** Array/JSON/range column contains every value: `.contains('tags', ['a', 'b'])` */
111
+ contains(column, value) {
112
+ return this.add(column, `cs.${fmtContains(value)}`);
113
+ }
114
+ /** Every element of the column is in `value`. */
115
+ containedBy(column, value) {
116
+ return this.add(column, `cd.${fmtContains(value)}`);
117
+ }
118
+ /** Array/range column shares at least one element with `value`. */
119
+ overlaps(column, value) {
120
+ return this.add(column, `ov.${fmtContains(value)}`);
121
+ }
122
+ /** Full-text search: `.textSearch('body', 'cats & dogs', { config: 'english' })` */
123
+ textSearch(column, query, options = {}) {
124
+ const op = options.type === 'plain' ? 'plfts' : options.type === 'phrase' ? 'phfts' : options.type === 'websearch' ? 'wfts' : 'fts';
125
+ return this.add(column, `${op}${options.config ? `(${options.config})` : ''}.${query}`);
126
+ }
127
+ /** Negate a filter: `.not('status', 'eq', 'done')`, `.not('id', 'in', [1, 2])` */
128
+ not(column, operator, value) {
129
+ return this.add(column, `not.${operator}.${fmtOperand(operator, value)}`);
130
+ }
131
+ /** Match any of the filters: `.or('status.eq.open,priority.gt.3')` */
132
+ or(filters, options = {}) {
133
+ return this.add(options.referencedTable ? `${options.referencedTable}.or` : 'or', `(${filters})`);
134
+ }
135
+ /** Shorthand for several `.eq()`: `.match({ user_id: id, done: false })` */
136
+ match(query) {
137
+ for (const [k, v] of Object.entries(query))
138
+ this.add(k, `eq.${fmt(v)}`);
139
+ return this;
140
+ }
141
+ /** Any PostgREST operator, unescaped: `.filter('tags', 'cs', '{a,b}')` */
142
+ filter(column, operator, value) {
143
+ return this.add(column, `${operator}.${fmtOperand(operator, value)}`);
144
+ }
145
+ // ---- modifiers ----
146
+ /**
147
+ * Choose columns. After insert/update/upsert/delete this returns the changed rows
148
+ * (otherwise those return `data: null`).
149
+ */
150
+ select(columns, options = {}) {
151
+ this.set('select', cleanColumns(columns ?? '*'));
152
+ if (this.s.method !== 'GET' && this.s.method !== 'HEAD' && !this.s.isRpc)
153
+ this.s.prefer.return = 'representation';
154
+ if (options.count)
155
+ this.s.prefer.count = options.count;
156
+ return this;
157
+ }
158
+ /** Sort: `.order('created_at', { ascending: false })`. Call again to add a tiebreaker. */
159
+ order(column, options = {}) {
160
+ const key = options.referencedTable ? `${options.referencedTable}.order` : 'order';
161
+ const value = `${column}.${options.ascending === false ? 'desc' : 'asc'}${options.nullsFirst === undefined ? '' : options.nullsFirst ? '.nullsfirst' : '.nullslast'}`;
162
+ const existing = this.s.params.find(([k]) => k === key);
163
+ if (existing)
164
+ existing[1] = `${existing[1]},${value}`;
165
+ else
166
+ this.add(key, value);
167
+ return this;
168
+ }
169
+ /** Return at most `count` rows. */
170
+ limit(count, options = {}) {
171
+ return this.set(options.referencedTable ? `${options.referencedTable}.limit` : 'limit', String(count));
172
+ }
173
+ /** Rows `from` to `to` (inclusive, 0-based): `.range(0, 9)` is the first 10 rows. */
174
+ range(from, to, options = {}) {
175
+ const prefix = options.referencedTable ? `${options.referencedTable}.` : '';
176
+ this.set(`${prefix}offset`, String(from));
177
+ return this.set(`${prefix}limit`, String(to - from + 1));
178
+ }
179
+ /** Return one row as an object instead of an array. Errors if there is not exactly one. */
180
+ single() {
181
+ this.s.mode = 'single';
182
+ return this;
183
+ }
184
+ /** Return one row, or `null` when nothing matches. Errors if more than one matches. */
185
+ maybeSingle() {
186
+ this.s.mode = 'maybeSingle';
187
+ return this;
188
+ }
189
+ /** Cancel the request with an AbortController signal. */
190
+ abortSignal(signal) {
191
+ this.s.signal = signal;
192
+ return this;
193
+ }
194
+ /** Override the result type (for when you know better than the types). */
195
+ returns() {
196
+ return this;
197
+ }
198
+ // ---- execution ----
199
+ then(onfulfilled, onrejected) {
200
+ return this.execute().then(onfulfilled, onrejected);
201
+ }
202
+ async execute() {
203
+ const s = this.s;
204
+ const headers = {};
205
+ const prefer = Object.entries(s.prefer).map(([k, v]) => `${k}=${v}`);
206
+ if (prefer.length)
207
+ headers.prefer = prefer.join(',');
208
+ if (s.mode === 'single' && !s.isRpc)
209
+ headers.accept = 'application/vnd.pgrst.object+json';
210
+ const res = await s.http.request(s.path, { method: s.method, query: s.params, headers, body: s.body, signal: s.signal });
211
+ if (res.error)
212
+ return { data: null, error: res.error, count: null, status: res.status };
213
+ const count = parseContentRange(res.headers?.get('content-range'));
214
+ let data = res.data;
215
+ if (s.mode === 'single' && Array.isArray(data)) {
216
+ if (data.length !== 1)
217
+ return { data: null, error: notSingle(data.length, false), count: null, status: 406 };
218
+ data = data[0];
219
+ }
220
+ else if (s.mode === 'maybeSingle') {
221
+ if (Array.isArray(data)) {
222
+ if (data.length > 1)
223
+ return { data: null, error: notSingle(data.length, true), count: null, status: 406 };
224
+ data = data[0] ?? null;
225
+ }
226
+ else if (data === undefined)
227
+ data = null;
228
+ }
229
+ return { data, error: null, count, status: res.status };
230
+ }
231
+ }
232
+ function notSingle(n, maybe) {
233
+ return new UseBeckyError({
234
+ code: 'not_single_row',
235
+ message: maybe ? `Expected at most one row, but found ${n}.` : `Expected exactly one row, but found ${n}.`,
236
+ hint: maybe ? 'Add a filter that matches a single row, like .eq("id", id).' : n === 0 ? 'Nothing matched. Use .maybeSingle() if the row might not exist.' : 'Add a filter that matches a single row, like .eq("id", id).',
237
+ status: 406,
238
+ });
239
+ }
240
+ /** Remove whitespace outside of double quotes: `id, title` → `id,title`. */
241
+ function cleanColumns(columns) {
242
+ let quoted = false;
243
+ let out = '';
244
+ for (const ch of columns) {
245
+ if (ch === '"')
246
+ quoted = !quoted;
247
+ if (!quoted && /\s/.test(ch))
248
+ continue;
249
+ out += ch;
250
+ }
251
+ return out;
252
+ }
253
+ // ---- entry points: from(table) and rpc(fn) -------------------------------------------------
254
+ export class TableQuery {
255
+ http;
256
+ path;
257
+ constructor(http, table) {
258
+ this.http = http;
259
+ this.path = `/rest/v1/${encodeURIComponent(table)}`;
260
+ }
261
+ builder(method, body) {
262
+ return new QueryBuilder({ http: this.http, method, path: this.path, params: [], prefer: {}, body, mode: 'many', isRpc: false });
263
+ }
264
+ /**
265
+ * Read rows. `columns` uses PostgREST syntax: `'id, title, author:profiles(name)'`.
266
+ * `{ count: 'exact' }` also returns the total number of matching rows; add `head: true` to skip the rows.
267
+ */
268
+ select(columns, options = {}) {
269
+ const b = this.builder(options.head ? 'HEAD' : 'GET');
270
+ return b.select(columns, { count: options.count });
271
+ }
272
+ /** Insert one row or many. Chain `.select()` to get the new rows back. */
273
+ insert(values, options = {}) {
274
+ const b = this.builder('POST', values);
275
+ applyWriteOptions(b, options);
276
+ return b;
277
+ }
278
+ /** Insert, or update when a row with the same primary key (or `onConflict` columns) exists. */
279
+ upsert(values, options = {}) {
280
+ const b = this.builder('POST', values);
281
+ b.s.prefer.resolution = options.ignoreDuplicates ? 'ignore-duplicates' : 'merge-duplicates';
282
+ if (options.onConflict)
283
+ b.s.params.push(['on_conflict', options.onConflict.replace(/\s/g, '')]);
284
+ applyWriteOptions(b, options);
285
+ return b;
286
+ }
287
+ /** Update matching rows. Always add a filter, e.g. `.eq('id', id)`. */
288
+ update(values, options = {}) {
289
+ const b = this.builder('PATCH', values);
290
+ applyWriteOptions(b, options);
291
+ return b;
292
+ }
293
+ /** Delete matching rows. Always add a filter, e.g. `.eq('id', id)`. */
294
+ delete(options = {}) {
295
+ const b = this.builder('DELETE');
296
+ applyWriteOptions(b, options);
297
+ return b;
298
+ }
299
+ }
300
+ function applyWriteOptions(b, options) {
301
+ const s = b.s;
302
+ if (options.count)
303
+ s.prefer.count = options.count;
304
+ if (options.defaultToNull === false)
305
+ s.prefer.missing = 'default';
306
+ }
307
+ export function rpcQuery(http, fn, args, options = {}) {
308
+ const params = [];
309
+ let method = 'POST';
310
+ let body = args ?? {};
311
+ if (options.head || options.get) {
312
+ method = options.head ? 'HEAD' : 'GET';
313
+ for (const [k, v] of Object.entries(args ?? {}))
314
+ params.push([k, Array.isArray(v) ? fmtArray(v) : fmt(v)]);
315
+ body = undefined;
316
+ }
317
+ const prefer = {};
318
+ if (options.count)
319
+ prefer.count = options.count;
320
+ return new QueryBuilder({ http, method, path: `/rest/v1/rpc/${encodeURIComponent(fn)}`, params, prefer, body, mode: 'many', isRpc: true });
321
+ }
322
+ /** Database access bound to one HTTP client (and therefore one role/user). */
323
+ export class Database {
324
+ http;
325
+ constructor(http) {
326
+ this.http = http;
327
+ }
328
+ /** Start a query on a table or view: `baas.from('todos').select()` */
329
+ from(table) {
330
+ return new TableQuery(this.http, table);
331
+ }
332
+ /** Call a Postgres function: `baas.rpc('add_points', { amount: 5 })` */
333
+ rpc(fn, args, options = {}) {
334
+ return rpcQuery(this.http, fn, args, options);
335
+ }
336
+ }
@@ -0,0 +1,93 @@
1
+ export type IsAny<T> = 0 extends 1 & T ? true : false;
2
+ export interface GenericTable {
3
+ Row: Record<string, any>;
4
+ Insert?: Record<string, any>;
5
+ Update?: Record<string, any>;
6
+ }
7
+ export interface GenericFunction {
8
+ Args?: any;
9
+ Returns: unknown;
10
+ }
11
+ export interface GenericSchema {
12
+ Tables: Record<string, GenericTable>;
13
+ Views?: Record<string, GenericTable>;
14
+ Functions?: Record<string, GenericFunction>;
15
+ }
16
+ type AnySchema = {
17
+ Tables: Record<string, {
18
+ Row: any;
19
+ Insert: any;
20
+ Update: any;
21
+ }>;
22
+ Views: Record<string, {
23
+ Row: any;
24
+ Insert: any;
25
+ Update: any;
26
+ }>;
27
+ Functions: Record<string, {
28
+ Args: any;
29
+ Returns: any;
30
+ }>;
31
+ };
32
+ /** The `public` schema of a Database type (or a permissive schema when none is given). */
33
+ export type SchemaOf<DB> = IsAny<DB> extends true ? AnySchema : DB extends {
34
+ public: infer S;
35
+ } ? S : AnySchema;
36
+ type TablesOf<S> = S extends {
37
+ Tables: infer T;
38
+ } ? T : {};
39
+ type ViewsOf<S> = S extends {
40
+ Views: infer V;
41
+ } ? V : {};
42
+ type FunctionsOf<S> = S extends {
43
+ Functions: infer F;
44
+ } ? F : {};
45
+ export type TableName<S> = (keyof TablesOf<S> & string) | (keyof ViewsOf<S> & string);
46
+ export type RowOf<S, N> = N extends keyof TablesOf<S> ? TablesOf<S>[N] extends {
47
+ Row: infer R;
48
+ } ? R : any : N extends keyof ViewsOf<S> ? ViewsOf<S>[N] extends {
49
+ Row: infer R;
50
+ } ? R : any : any;
51
+ export type InsertOf<S, N> = N extends keyof TablesOf<S> ? TablesOf<S>[N] extends {
52
+ Insert: infer I;
53
+ } ? I : Partial<RowOf<S, N>> : Partial<RowOf<S, N>>;
54
+ export type UpdateOf<S, N> = N extends keyof TablesOf<S> ? TablesOf<S>[N] extends {
55
+ Update: infer U;
56
+ } ? U : Partial<RowOf<S, N>> : Partial<RowOf<S, N>>;
57
+ export type FunctionName<S> = keyof FunctionsOf<S> & string;
58
+ export type FunctionArgs<S, F> = F extends keyof FunctionsOf<S> ? (FunctionsOf<S>[F] extends {
59
+ Args: infer A;
60
+ } ? A : Record<string, unknown>) : Record<string, unknown>;
61
+ export type FunctionReturns<S, F> = F extends keyof FunctionsOf<S> ? (FunctionsOf<S>[F] extends {
62
+ Returns: infer R;
63
+ } ? R : any) : any;
64
+ /** Column names for autocomplete; any string is still accepted (e.g. `comments.approved`). */
65
+ export type ColumnName<Row> = IsAny<Row> extends true ? string : (keyof Row & string) | (string & {});
66
+ export type ColumnValue<Row, K> = IsAny<Row> extends true ? any : K extends keyof Row ? Row[K] : unknown;
67
+ type Whitespace = ' ' | '\n' | '\t' | '\r';
68
+ type TrimLeft<S extends string> = S extends `${Whitespace}${infer R}` ? TrimLeft<R> : S;
69
+ type TrimRight<S extends string> = S extends `${infer R}${Whitespace}` ? TrimRight<R> : S;
70
+ type Trim<S extends string> = TrimLeft<TrimRight<S>>;
71
+ /** Split on top-level commas (commas inside parentheses belong to embedded resources). */
72
+ type SplitTop<S extends string, Depth extends unknown[] = [], Cur extends string = '', Acc extends string[] = []> = S extends `${infer C}${infer Rest}` ? C extends '(' ? SplitTop<Rest, [...Depth, 0], `${Cur}${C}`, Acc> : C extends ')' ? SplitTop<Rest, Depth extends [unknown, ...infer D] ? D : [], `${Cur}${C}`, Acc> : C extends ',' ? Depth extends [] ? SplitTop<Rest, Depth, '', [...Acc, Cur]> : SplitTop<Rest, Depth, `${Cur}${C}`, Acc> : SplitTop<Rest, Depth, `${Cur}${C}`, Acc> : [...Acc, Cur];
73
+ type CastType<T extends string> = Trim<T> extends 'text' | 'varchar' | 'char' | 'uuid' | 'citext' | 'date' | 'timestamptz' | 'timestamp' ? string : Trim<T> extends 'int' | 'int2' | 'int4' | 'int8' | 'integer' | 'bigint' | 'smallint' | 'float4' | 'float8' | 'real' | 'numeric' | 'double precision' ? number : Trim<T> extends 'bool' | 'boolean' ? boolean : unknown;
74
+ /** Output key for an un-aliased expression: `meta->>color` → `color`, `col::text` → `col`. */
75
+ type ExprKey<E extends string> = E extends `${infer C}::${string}` ? ExprKey<C> : E extends `${string}->>${infer K}` ? ExprKey<K> : E extends `${string}->${infer K}` ? ExprKey<K> : Trim<E>;
76
+ type ExprValue<Row, E extends string> = E extends `${string}::${infer T}` ? CastType<T> : E extends `${string}->>${string}` ? string | null : E extends `${string}->${string}` ? unknown : Trim<E> extends keyof Row ? Row[Trim<E>] : unknown;
77
+ type EmbedKey<H extends string> = Trim<H> extends `${infer A}:${string}` ? Trim<A> : Trim<H> extends `${infer T}!${string}` ? Trim<T> : Trim<H>;
78
+ type ParseField<Row, F extends string> = F extends '' ? {} : F extends '*' ? Row : F extends `${infer Head}(${string}` ? {
79
+ [K in EmbedKey<Head>]: any;
80
+ } : F extends `${infer Alias}:${infer Rest}` ? Rest extends `:${string}` ? {
81
+ [K in ExprKey<F>]: ExprValue<Row, F>;
82
+ } : {
83
+ [K in Trim<Alias>]: ExprValue<Row, Rest>;
84
+ } : {
85
+ [K in ExprKey<F>]: ExprValue<Row, F>;
86
+ };
87
+ type MergeFields<Row, Parts extends string[]> = Parts extends [infer H extends string, ...infer T extends string[]] ? ParseField<Row, Trim<H>> & MergeFields<Row, T> : {};
88
+ type Simplify<T> = {
89
+ [K in keyof T]: T[K];
90
+ } & {};
91
+ /** The row type you get back from `.select('id, title, author:profiles(name)')`. */
92
+ export type SelectResult<Row, Q extends string> = IsAny<Row> extends true ? any : string extends Q ? Row : Simplify<MergeFields<Row, SplitTop<Q>>>;
93
+ export {};
@@ -0,0 +1,4 @@
1
+ // Type helpers that turn a generated `Database` type (from `npx usebecky types`) into
2
+ // autocomplete for table names, columns, inserts, updates, select() results and rpc() args.
3
+ // Without a Database type everything is `any`, so nothing gets in your way.
4
+ export {};
@@ -0,0 +1,65 @@
1
+ import type { ConsentRef } from '../analytics/client.ts';
2
+ import type { HttpClient } from '../lib/http.ts';
3
+ import type { Result } from '../lib/types.ts';
4
+ /** A value you can send for a field. Lists are for checkbox groups. */
5
+ export type FormValue = string | number | boolean | string[] | null | undefined;
6
+ /** What `submit()` accepts: a plain object, a `FormData`, or an HTML `<form>` element. */
7
+ export type FormInput = Record<string, FormValue> | FormData | {
8
+ readonly elements: unknown;
9
+ };
10
+ export interface FormSubmitResult {
11
+ /** Always true when `error` is null. */
12
+ ok: boolean;
13
+ /** The form's success message, e.g. "Thanks! We'll get back to you soon." Show it to the visitor. */
14
+ message: string;
15
+ }
16
+ /** Options for `submit()`. */
17
+ export interface FormSubmitOptions {
18
+ /** Token from the Turnstile / hCaptcha widget, when bot protection is on for forms
19
+ * (Dashboard → Settings → Bot protection). `GET /forms/v1/f/:id` tells you the site key. */
20
+ captchaToken?: string;
21
+ }
22
+ export interface PublicFormField {
23
+ name: string;
24
+ label: string;
25
+ type: 'text' | 'email' | 'textarea' | 'select' | 'checkbox' | 'phone' | 'url' | 'number';
26
+ required: boolean;
27
+ options?: string[];
28
+ }
29
+ /** The public definition of a form (enough to render it yourself). */
30
+ export interface PublicForm {
31
+ id: string;
32
+ key: string;
33
+ name: string;
34
+ fields: PublicFormField[];
35
+ success_message: string;
36
+ enabled: boolean;
37
+ /** "Offer your newsletter" is on: show a "Send me the newsletter" checkbox and send `_newsletter: true` when it's
38
+ * ticked (the person then gets the newsletter's confirmation email). Older servers leave it out. */
39
+ newsletter_optin?: boolean;
40
+ submit_url: string;
41
+ /** Set when the form needs a captcha: show this widget and pass its token to `submit()`. */
42
+ captcha?: {
43
+ provider: 'turnstile' | 'hcaptcha';
44
+ site_key: string;
45
+ } | null;
46
+ }
47
+ export declare class FormsClient {
48
+ private http;
49
+ private consent;
50
+ /** `consent`: the visitor's consent state for a server-side tagging extension (generate_lead), see `analytics.consentRef()`. */
51
+ constructor(http: HttpClient, consent?: () => Promise<ConsentRef | undefined>);
52
+ /**
53
+ * Send a submission to a form made in Dashboard → Forms.
54
+ *
55
+ * await baas.forms.submit('contact', { name: 'Ada', email: 'ada@example.com', message: 'Hi!' })
56
+ * await baas.forms.submit('contact', event.currentTarget) // a <form> element (React onSubmit)
57
+ *
58
+ * `formIdOrKey` is the form's key (e.g. "contact") or its id ("f_..."). Field names must match the
59
+ * form's fields; extra fields are kept too. Fields starting with "_" are reserved.
60
+ * With bot protection on: `await baas.forms.submit('contact', values, { captchaToken })`.
61
+ */
62
+ submit(formIdOrKey: string, data: FormInput, options?: FormSubmitOptions): Promise<Result<FormSubmitResult>>;
63
+ /** The public definition of a form (name, fields, success message), e.g. to render it yourself. */
64
+ get(formIdOrKey: string): Promise<Result<PublicForm>>;
65
+ }