Open History to see the last commit
1import type { OwnerDefinition } from './shape-owner.js'
2
3export class ShapeDefinitionError extends Error {}
4export interface ConfiguredTable {
5 namespace: string
6 table: string
7 primaryKey: readonly string[]
8 columns: OwnerDefinition['schema']
9}
10
11const identifier = /^(?:"(?:[^"]|"")*"|[A-Za-z_][A-Za-z0-9_$]*)/
12const quote = (value: string) => `"${value.replaceAll('"', '""')}"`
13function name(token: string): string {
14 return token.startsWith('"')
15 ? token.slice(1, -1).replaceAll('""', '"')
16 : token.toLowerCase()
17}
18function fail(message: string): never {
19 throw new ShapeDefinitionError(message)
20}
21
22/** Configured root/projection; authorized WHERE SQL passes directly to Realtime. */
23export function resolveConfiguredShape(
24 url: URL,
25 tables: readonly ConfiguredTable[]
26): OwnerDefinition {
27 for (const key of ['table', 'columns', 'where', 'params', 'log', 'replica'])
28 if (url.searchParams.getAll(key).length > 1)
29 fail(`Repeated shape parameter: ${key}`)
30 const requested = url.searchParams.get('table') ?? fail('Missing table')
31 const table = tables.find(
32 (t) =>
33 requested === t.table ||
34 requested === `${t.namespace}.${t.table}` ||
35 requested === `${quote(t.namespace)}.${quote(t.table)}`
36 )
37 if (!table) fail('Table is not configured')
38 if (!table.primaryKey.length) fail('Shape tables require a primary key')
39 let projection = Object.keys(table.columns)
40 const configured = url.searchParams.get('columns')
41 if (configured !== null) {
42 projection = []
43 let remaining = configured.trim()
44 while (remaining) {
45 const match = identifier.exec(remaining)
46 if (!match) fail('Invalid projection')
47 projection.push(name(match[0]))
48 remaining = remaining.slice(match[0].length).trimStart()
49 if (remaining.startsWith(',')) {
50 remaining = remaining.slice(1).trimStart()
51 if (!remaining) fail('Invalid projection')
52 } else if (remaining) fail('Invalid projection')
53 }
54 if (!projection.length || new Set(projection).size !== projection.length)
55 fail('Invalid projection')
56 }
57 for (const col of [...projection, ...table.primaryKey])
58 if (!Object.hasOwn(table.columns, col)) fail('Unknown column')
59 const selection = [
60 ...projection,
61 ...table.primaryKey.filter((p) => !projection.includes(p)),
62 ]
63 const baseSql = `SELECT ${selection.map(quote).join(', ')} FROM ${quote(table.namespace)}.${quote(table.table)}`
64 let sql = baseSql
65 const parameters: (string | boolean | null)[] = []
66 const where = url.searchParams.get('where')
67 if (where !== null) {
68 if (!where.trim()) fail('Empty WHERE expression')
69 // Realtime owns SQL parsing/validation. The caller's authorize callback
70 // must authorize the predicate before handing the definition to a shape.
71 // A newline keeps a trailing line comment separate from the wrapper.
72 sql = `${baseSql} WHERE (\n${where}\n)`
73 let bindings: unknown = {}
74 const encoded = url.searchParams.get('params')
75 if (encoded !== null) {
76 try {
77 bindings = JSON.parse(encoded)
78 } catch {
79 fail('Invalid filter parameters')
80 }
81 }
82 const bracketed = [...url.searchParams].filter(([key]) =>
83 key.startsWith('params[')
84 )
85 if (bracketed.length) {
86 if (encoded !== null) fail('Ambiguous filter parameter encodings')
87 const values: Record<string, string> = Object.create(null)
88 for (const [key, value] of bracketed) {
89 const position = /^params\[([1-9][0-9]*)\]$/.exec(key)?.[1]
90 if (
91 !position ||
92 !Number.isSafeInteger(Number(position)) ||
93 Number(position) > 65535 ||
94 Object.hasOwn(values, position)
95 )
96 fail('Invalid or repeated filter parameter')
97 values[position] = value
98 }
99 bindings = values
100 }
101 if (!bindings || typeof bindings !== 'object')
102 fail('Invalid filter parameters')
103 const keys = Object.keys(bindings)
104 if (
105 !Array.isArray(bindings) &&
106 keys.some((key) => !/^[1-9][0-9]*$/.test(key) || Number(key) > 65535)
107 )
108 fail('Invalid filter parameter position')
109 const maxPosition = Array.isArray(bindings)
110 ? bindings.length
111 : keys.reduce((max, key) => Math.max(max, Number(key)), 0)
112 if (maxPosition > 65535) fail('Too many filter parameters')
113 for (let position = 1; position <= maxPosition; position++) {
114 const key = Array.isArray(bindings)
115 ? String(position - 1)
116 : String(position)
117 if (!Object.hasOwn(bindings, key)) fail('Missing filter parameter')
118 let value = (bindings as Record<string, unknown>)[key]
119 if (
120 value !== null &&
121 typeof value !== 'string' &&
122 typeof value !== 'boolean' &&
123 typeof value !== 'number'
124 )
125 fail('Filter parameter must be scalar')
126 if (typeof value === 'number') {
127 if (
128 !Number.isFinite(value) ||
129 (Number.isInteger(value) && !Number.isSafeInteger(value))
130 )
131 fail('Numeric parameter loses precision; pass a string')
132 value = String(value)
133 }
134 parameters.push(value as string | boolean | null)
135 }
136 }
137 const logMode = url.searchParams.get('log') ?? 'full'
138 const replica = url.searchParams.get('replica') ?? 'default'
139 if (!['full', 'changes_only'].includes(logMode)) fail('Unsupported log mode')
140 if (!['default', 'full'].includes(replica)) fail('Unsupported replica mode')
141 return {
142 query: {
143 sql,
144 parameters,
145 },
146 namespace: table.namespace,
147 table: table.table,
148 primaryKey: table.primaryKey,
149 projection,
150 schema: Object.fromEntries(projection.map((p) => [p, table.columns[p]])),
151 ...(logMode === 'changes_only' ? ({ logMode } as const) : {}),
152 ...(replica === 'full' ? ({ replica } as const) : {}),
153 }
154}