@fabrika/auth-core 0.9.0-dev.8 → 0.9.0-dev.9

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/auth-core",
3
- "version": "0.9.0-dev.8",
3
+ "version": "0.9.0-dev.9",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
package/src/ops.ts CHANGED
@@ -1653,6 +1653,228 @@ function loadOrder(tables: readonly DescribedTable[], cycle: ReadonlyMap<string,
1653
1653
  return order
1654
1654
  }
1655
1655
 
1656
+ /**
1657
+ * The schema `planOpsDump` reads, from the PRAGMAs workerd admits, of every table a dump holds. An `INITIALLY DEFERRED`
1658
+ * clause is read from the table's SQL outside its quotes and comments, and marks every foreign key of its table; the
1659
+ * names a `CHECK` reads come from the same SQL (`checkNamesOf`).
1660
+ */
1661
+ export function describeOpsDumpSchema(query: OpsDumpSchemaQuery): OpsDumpSchema {
1662
+ const tables: OpsDumpSchemaTable[] = []
1663
+ for (const row of query('PRAGMA table_list')) {
1664
+ const name = schemaText(row['name'])
1665
+ const type = schemaText(row['type'])
1666
+ if (schemaText(row['schema']) !== 'main' || type === 'view' || !dumpedTable(name)) {
1667
+ continue
1668
+ }
1669
+ const virtual = type === 'virtual'
1670
+ const sql = query(`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = ?`, name)[0]?.['sql']
1671
+ const clauses = typeof sql === 'string' ? unquotedSql(sql) : null
1672
+ tables.push({
1673
+ name,
1674
+ virtual,
1675
+ withoutRowid: schemaFlag(row['wr']),
1676
+ checkNames: typeof sql === 'string' ? checkNamesOf(sql) : null,
1677
+ // A virtual table is refused whatever it holds, and its module may not be loaded to describe it.
1678
+ columns: virtual ? [] : describeColumns(query, name),
1679
+ indexes: virtual ? [] : describeIndexes(query, name),
1680
+ foreignKeys: virtual ? [] : describeForeignKeys(query, name, clauses === null || /\binitially\s+deferred\b/i.test(clauses)),
1681
+ })
1682
+ }
1683
+ return { tables }
1684
+ }
1685
+
1686
+ function describeColumns(query: OpsDumpSchemaQuery, table: string): OpsDumpSchemaColumn[] {
1687
+ return query(`PRAGMA table_xinfo(${sqlLiteral(table)})`).map((row) => {
1688
+ const hidden = schemaInteger(row['hidden'])
1689
+ return {
1690
+ name: schemaText(row['name']),
1691
+ type: schemaText(row['type']),
1692
+ notNull: schemaFlag(row['notnull']),
1693
+ primaryKey: schemaInteger(row['pk']),
1694
+ generated: hidden === 2 || hidden === 3,
1695
+ }
1696
+ })
1697
+ }
1698
+
1699
+ function describeIndexes(query: OpsDumpSchemaQuery, table: string): OpsDumpSchemaIndex[] {
1700
+ return query(`PRAGMA index_list(${sqlLiteral(table)})`).map((row) => {
1701
+ const origin = row['origin']
1702
+ if (origin !== 'c' && origin !== 'u' && origin !== 'pk') {
1703
+ throw new Error('PRAGMA index_list answered an origin SQLite does not write')
1704
+ }
1705
+ const columns = query(`PRAGMA index_xinfo(${sqlLiteral(schemaText(row['name']))})`)
1706
+ .filter((column) => schemaFlag(column['key']))
1707
+ .sort((left, right) => schemaInteger(left['seqno']) - schemaInteger(right['seqno']))
1708
+ .map((column) => typeof column['name'] === 'string' ? column['name'] : null)
1709
+ return { unique: schemaFlag(row['unique']), origin, partial: schemaFlag(row['partial']), columns }
1710
+ })
1711
+ }
1712
+
1713
+ function describeForeignKeys(query: OpsDumpSchemaQuery, table: string, initiallyDeferred: boolean): OpsDumpSchemaForeignKey[] {
1714
+ const keys = new Map<number, { parent: string; rows: { seq: number; from: string; to: string | null }[] }>()
1715
+ for (const row of query(`PRAGMA foreign_key_list(${sqlLiteral(table)})`)) {
1716
+ const id = schemaInteger(row['id'])
1717
+ const to = row['to']
1718
+ const entry = { seq: schemaInteger(row['seq']), from: schemaText(row['from']), to: typeof to === 'string' ? to : null }
1719
+ const key = keys.get(id)
1720
+ if (key === undefined) {
1721
+ keys.set(id, { parent: schemaText(row['table']), rows: [entry] })
1722
+ } else {
1723
+ key.rows.push(entry)
1724
+ }
1725
+ }
1726
+ return [...keys.entries()].sort(([left], [right]) => left - right).map(([, key]) => {
1727
+ const rows = key.rows.sort((left, right) => left.seq - right.seq)
1728
+ const references = rows.flatMap((row) => row.to === null ? [] : [row.to])
1729
+ if (references.length !== 0 && references.length !== rows.length) {
1730
+ throw new Error('PRAGMA foreign_key_list named the parent columns of a key only in part')
1731
+ }
1732
+ return { parent: key.parent, columns: rows.map((row) => row.from), references: references.length === 0 ? null : references, initiallyDeferred }
1733
+ })
1734
+ }
1735
+
1736
+ type SqlToken =
1737
+ | { readonly kind: 'name'; readonly text: string; readonly quoted: boolean }
1738
+ | { readonly kind: 'open' | 'close' | 'other' }
1739
+
1740
+ const WORD_CHAR = /[A-Za-z0-9_$\u0080-\uffff]/
1741
+
1742
+ /**
1743
+ * The names the `CHECK` clauses of a table's `sql` read: every word and quoted identifier between a `CHECK` keyword's
1744
+ * parentheses, ASCII-lowercase, keywords and numbers included, so it lists at least every column a `CHECK` reads. A
1745
+ * string literal and a comment name nothing; a double-quoted string, which SQLite may read as either, counts as a name.
1746
+ * `null` when the text does not scan (an unclosed quote, comment or parenthesis), which counts as naming every column.
1747
+ */
1748
+ export function checkNamesOf(sql: string): string[] | null {
1749
+ const tokens = sqlTokens(sql)
1750
+ if (tokens === null) return null
1751
+ const names: string[] = []
1752
+ for (let index = 0; index < tokens.length; index++) {
1753
+ const token = tokens[index]
1754
+ if (token?.kind !== 'name' || token.quoted || asciiLower(token.text) !== 'check' || tokens[index + 1]?.kind !== 'open') continue
1755
+ let depth = 0
1756
+ let end = index + 1
1757
+ for (; end < tokens.length; end++) {
1758
+ const inner = tokens[end]
1759
+ if (inner?.kind === 'open') depth++
1760
+ else if (inner?.kind === 'close' && --depth === 0) break
1761
+ else if (inner?.kind === 'name') names.push(asciiLower(inner.text))
1762
+ }
1763
+ if (end === tokens.length) return null
1764
+ index = end
1765
+ }
1766
+ return names
1767
+ }
1768
+
1769
+ /** `sql` as words, quoted identifiers and parentheses; string literals, comments and whitespace dropped. */
1770
+ function sqlTokens(sql: string): SqlToken[] | null {
1771
+ const tokens: SqlToken[] = []
1772
+ let index = 0
1773
+ while (index < sql.length) {
1774
+ const char = sql.charAt(index)
1775
+ if (sql.startsWith('--', index)) {
1776
+ const end = sql.indexOf('\n', index)
1777
+ index = end < 0 ? sql.length : end + 1
1778
+ } else if (sql.startsWith('/*', index)) {
1779
+ const end = sql.indexOf('*/', index + 2)
1780
+ if (end < 0) return null
1781
+ index = end + 2
1782
+ } else if (char === "'" || char === '"' || char === '`' || char === '[') {
1783
+ const close = char === '[' ? ']' : char
1784
+ let end = index + 1
1785
+ let text = ''
1786
+ for (;;) {
1787
+ const next = sql.indexOf(close, end)
1788
+ if (next < 0) return null
1789
+ text += sql.slice(end, next)
1790
+ if (close !== ']' && sql.charAt(next + 1) === close) {
1791
+ text += close
1792
+ end = next + 2
1793
+ continue
1794
+ }
1795
+ end = next + 1
1796
+ break
1797
+ }
1798
+ if (char !== "'") tokens.push({ kind: 'name', text, quoted: true })
1799
+ index = end
1800
+ } else if (WORD_CHAR.test(char)) {
1801
+ let end = index + 1
1802
+ while (end < sql.length && WORD_CHAR.test(sql.charAt(end))) end++
1803
+ tokens.push({ kind: 'name', text: sql.slice(index, end), quoted: false })
1804
+ index = end
1805
+ } else {
1806
+ if (char === '(') tokens.push({ kind: 'open' })
1807
+ else if (char === ')') tokens.push({ kind: 'close' })
1808
+ else if (!/\s/.test(char)) tokens.push({ kind: 'other' })
1809
+ index++
1810
+ }
1811
+ }
1812
+ return tokens
1813
+ }
1814
+
1815
+ /** `sql` with its string literals, quoted identifiers and comments blanked, so a keyword search finds only clauses. */
1816
+ function unquotedSql(sql: string): string {
1817
+ let out = ''
1818
+ let index = 0
1819
+ while (index < sql.length) {
1820
+ const char = sql.charAt(index)
1821
+ const close = char === "'" ? "'" : char === '"' ? '"' : char === '`' ? '`' : char === '[' ? ']' : null
1822
+ if (close !== null) {
1823
+ let end = index + 1
1824
+ for (;;) {
1825
+ end = sql.indexOf(close, end)
1826
+ if (end < 0 || close === ']' || sql.charAt(end + 1) !== close) break
1827
+ end += 2
1828
+ }
1829
+ index = end < 0 ? sql.length : end + 1
1830
+ out += ' '
1831
+ } else if (sql.startsWith('--', index)) {
1832
+ const end = sql.indexOf('\n', index)
1833
+ index = end < 0 ? sql.length : end + 1
1834
+ out += ' '
1835
+ } else if (sql.startsWith('/*', index)) {
1836
+ const end = sql.indexOf('*/', index + 2)
1837
+ index = end < 0 ? sql.length : end + 2
1838
+ out += ' '
1839
+ } else {
1840
+ out += char
1841
+ index++
1842
+ }
1843
+ }
1844
+ return out
1845
+ }
1846
+
1847
+ /** One statement's rows, as a Durable Object's `sql.exec(...).toArray()` or a `bun:sqlite` query answers them. */
1848
+ export type OpsDumpSchemaQuery = (sql: string, ...bindings: string[]) => readonly Readonly<Record<string, unknown>>[]
1849
+
1850
+ /** Whether a dump holds `name`: no SQLite internal table but `sqlite_sequence`, and none of Cloudflare's `_cf_` ones. */
1851
+ function dumpedTable(name: string): boolean {
1852
+ return !name.startsWith('_cf_') && (!name.startsWith('sqlite_') || name === 'sqlite_sequence')
1853
+ }
1854
+
1855
+ function sqlLiteral(value: string): string {
1856
+ return `'${value.replaceAll("'", "''")}'`
1857
+ }
1858
+
1859
+ // SQLite's own answers: a value of another type is a broken runtime, never input to refuse.
1860
+ function schemaText(value: unknown): string {
1861
+ if (typeof value !== 'string') {
1862
+ throw new Error('SQLite answered a schema name or SQL that is not text')
1863
+ }
1864
+ return value
1865
+ }
1866
+
1867
+ function schemaInteger(value: unknown): number {
1868
+ if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
1869
+ throw new Error('SQLite answered a schema number that is not an integer')
1870
+ }
1871
+ return value
1872
+ }
1873
+
1874
+ function schemaFlag(value: unknown): boolean {
1875
+ return schemaInteger(value) !== 0
1876
+ }
1877
+
1656
1878
  /** Whether every deferred column of `table` can hold `NULL` from its part until the link pass, with nothing to violate. */
1657
1879
  function takesTemporaryNull(table: OpsDumpSchemaTable, deferred: readonly OpsDumpSchemaColumn[], referenced: ReadonlySet<string>): boolean {
1658
1880
  // A `CHECK` answers the same for a `NULL` in a column it does not read; a generated column may read a deferred one.
@@ -640,3 +640,18 @@ export interface OpsDataRefusal {
640
640
  readonly table: string | null;
641
641
  }
642
642
  export declare function parseOpsDataRefusal(body: unknown): OpsDataRefusal | null;
643
+ /**
644
+ * The schema `planOpsDump` reads, from the PRAGMAs workerd admits, of every table a dump holds. An `INITIALLY DEFERRED`
645
+ * clause is read from the table's SQL outside its quotes and comments, and marks every foreign key of its table; the
646
+ * names a `CHECK` reads come from the same SQL (`checkNamesOf`).
647
+ */
648
+ export declare function describeOpsDumpSchema(query: OpsDumpSchemaQuery): OpsDumpSchema;
649
+ /**
650
+ * The names the `CHECK` clauses of a table's `sql` read: every word and quoted identifier between a `CHECK` keyword's
651
+ * parentheses, ASCII-lowercase, keywords and numbers included, so it lists at least every column a `CHECK` reads. A
652
+ * string literal and a comment name nothing; a double-quoted string, which SQLite may read as either, counts as a name.
653
+ * `null` when the text does not scan (an unclosed quote, comment or parenthesis), which counts as naming every column.
654
+ */
655
+ export declare function checkNamesOf(sql: string): string[] | null;
656
+ /** One statement's rows, as a Durable Object's `sql.exec(...).toArray()` or a `bun:sqlite` query answers them. */
657
+ export type OpsDumpSchemaQuery = (sql: string, ...bindings: string[]) => readonly Readonly<Record<string, unknown>>[];