tina4-nodejs 3.13.92 → 3.13.95

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 (193) hide show
  1. package/CLAUDE.md +170 -28
  2. package/README.md +2 -2
  3. package/package.json +13 -9
  4. package/packages/cli/dist/bin.js +33126 -30055
  5. package/packages/cli/src/commands/metrics.ts +17 -11
  6. package/packages/cli/src/commands/serve.ts +10 -9
  7. package/packages/core/dist/index.js +33062 -29908
  8. package/packages/core/src/ai.ts +7 -1
  9. package/packages/core/src/auth.ts +191 -39
  10. package/packages/core/src/background.ts +19 -19
  11. package/packages/core/src/cache.ts +492 -49
  12. package/packages/core/src/devAdmin.ts +79 -32
  13. package/packages/core/src/devMailbox.ts +20 -44
  14. package/packages/core/src/dispatchPipeline.ts +285 -0
  15. package/packages/core/src/dotenv.ts +185 -40
  16. package/packages/core/src/index.ts +7 -6
  17. package/packages/core/src/logger.ts +257 -36
  18. package/packages/core/src/mcp.ts +1 -1
  19. package/packages/core/src/messenger.ts +81 -13
  20. package/packages/core/src/metrics.ts +199 -961
  21. package/packages/core/src/middleware.ts +390 -123
  22. package/packages/core/src/queue.ts +188 -32
  23. package/packages/core/src/queueBackends/kafkaBackend.ts +109 -13
  24. package/packages/core/src/queueBackends/liteBackend.ts +13 -0
  25. package/packages/core/src/queueBackends/mongoBackend.ts +101 -9
  26. package/packages/core/src/queueBackends/rabbitmqBackend.ts +22 -4
  27. package/packages/core/src/rateLimiter.ts +10 -5
  28. package/packages/core/src/request.ts +6 -9
  29. package/packages/core/src/response.ts +46 -1
  30. package/packages/core/src/router.ts +29 -4
  31. package/packages/core/src/server.ts +751 -414
  32. package/packages/core/src/session.ts +244 -27
  33. package/packages/core/src/sessionHandlers/childError.ts +72 -0
  34. package/packages/core/src/sessionHandlers/databaseHandler.ts +338 -48
  35. package/packages/core/src/sessionHandlers/memcachedHandler.ts +181 -0
  36. package/packages/core/src/sessionHandlers/mongoClient.ts +293 -202
  37. package/packages/core/src/sessionHandlers/mongoHandler.ts +88 -8
  38. package/packages/core/src/sessionHandlers/respClient.ts +16 -143
  39. package/packages/core/src/sessionHandlers/sqlClient.ts +290 -0
  40. package/packages/core/src/sessionHandlers/syncBridge.ts +190 -0
  41. package/packages/core/src/sessionHandlers/syncSocket.ts +236 -0
  42. package/packages/core/src/testClient.ts +18 -5
  43. package/packages/core/src/trustedProxy.ts +249 -0
  44. package/packages/core/src/types.ts +29 -5
  45. package/packages/core/src/websocket.ts +66 -0
  46. package/packages/frond/dist/index.js +74 -31
  47. package/packages/frond/src/engine.ts +99 -33
  48. package/packages/orm/dist/index.js +26554 -23400
  49. package/packages/orm/src/adapters/firebird.ts +183 -56
  50. package/packages/orm/src/adapters/mongodb.ts +25 -4
  51. package/packages/orm/src/adapters/mssql.ts +114 -29
  52. package/packages/orm/src/adapters/mysql.ts +103 -40
  53. package/packages/orm/src/adapters/odbc.ts +44 -21
  54. package/packages/orm/src/adapters/postgres.ts +118 -26
  55. package/packages/orm/src/adapters/sqlDialect.ts +120 -0
  56. package/packages/orm/src/adapters/sqlite.ts +64 -25
  57. package/packages/orm/src/baseModel.ts +135 -40
  58. package/packages/orm/src/cachedDatabase.ts +43 -19
  59. package/packages/orm/src/connectTimeout.ts +265 -0
  60. package/packages/orm/src/database.ts +338 -198
  61. package/packages/orm/src/databaseResult.ts +65 -13
  62. package/packages/orm/src/databaseUrl.ts +484 -0
  63. package/packages/orm/src/docstore.ts +386 -145
  64. package/packages/orm/src/index.ts +13 -3
  65. package/packages/orm/src/migration.ts +18 -3
  66. package/packages/orm/src/queryBuilder.ts +38 -4
  67. package/packages/orm/src/sqlTranslator.ts +310 -4
  68. package/packages/orm/src/types.ts +15 -4
  69. package/types/cli/src/bin.d.ts +92 -0
  70. package/types/cli/src/commands/build.d.ts +2 -0
  71. package/types/cli/src/commands/generate.d.ts +47 -0
  72. package/types/cli/src/commands/init.d.ts +1 -0
  73. package/types/cli/src/commands/metrics.d.ts +6 -0
  74. package/types/cli/src/commands/migrate.d.ts +1 -0
  75. package/types/cli/src/commands/migrateCreate.d.ts +1 -0
  76. package/types/cli/src/commands/migrateRollback.d.ts +1 -0
  77. package/types/cli/src/commands/migrateStatus.d.ts +1 -0
  78. package/types/cli/src/commands/queue.d.ts +20 -0
  79. package/types/cli/src/commands/routes.d.ts +1 -0
  80. package/types/cli/src/commands/seed.d.ts +1 -0
  81. package/types/cli/src/commands/serve.d.ts +6 -0
  82. package/types/cli/src/commands/test.d.ts +1 -0
  83. package/types/core/src/ai.d.ts +64 -0
  84. package/types/core/src/api.d.ts +262 -0
  85. package/types/core/src/auth.d.ts +177 -0
  86. package/types/core/src/authGate.d.ts +20 -0
  87. package/types/core/src/background.d.ts +34 -0
  88. package/types/core/src/cache.d.ts +163 -0
  89. package/types/core/src/constants.d.ts +38 -0
  90. package/types/core/src/container.d.ts +44 -0
  91. package/types/core/src/context/chunker.d.ts +31 -0
  92. package/types/core/src/context/index.d.ts +93 -0
  93. package/types/core/src/devAdmin.d.ts +179 -0
  94. package/types/core/src/devMailbox.d.ts +54 -0
  95. package/types/core/src/dispatchPipeline.d.ts +117 -0
  96. package/types/core/src/docs.d.ts +141 -0
  97. package/types/core/src/docsAutoDiscovery.d.ts +6 -0
  98. package/types/core/src/dotenv.d.ts +87 -0
  99. package/types/core/src/env.d.ts +28 -0
  100. package/types/core/src/errorOverlay.d.ts +36 -0
  101. package/types/core/src/events.d.ts +75 -0
  102. package/types/core/src/fakeData.d.ts +55 -0
  103. package/types/core/src/feedback.d.ts +90 -0
  104. package/types/core/src/graphql.d.ts +207 -0
  105. package/types/core/src/health.d.ts +22 -0
  106. package/types/core/src/htmlElement.d.ts +75 -0
  107. package/types/core/src/i18n.d.ts +37 -0
  108. package/types/core/src/index.d.ts +92 -0
  109. package/types/core/src/job.d.ts +39 -0
  110. package/types/core/src/logger.d.ts +200 -0
  111. package/types/core/src/mcp.d.ts +248 -0
  112. package/types/core/src/messenger.d.ts +191 -0
  113. package/types/core/src/metrics.d.ts +41 -0
  114. package/types/core/src/middleware.d.ts +330 -0
  115. package/types/core/src/mqtt.d.ts +257 -0
  116. package/types/core/src/mqttMessage.d.ts +67 -0
  117. package/types/core/src/plan.d.ts +96 -0
  118. package/types/core/src/projectIndex.d.ts +56 -0
  119. package/types/core/src/queue.d.ts +268 -0
  120. package/types/core/src/queueBackends/kafkaBackend.d.ts +117 -0
  121. package/types/core/src/queueBackends/liteBackend.d.ts +128 -0
  122. package/types/core/src/queueBackends/mongoBackend.d.ts +119 -0
  123. package/types/core/src/queueBackends/rabbitmqBackend.d.ts +55 -0
  124. package/types/core/src/rateLimiter.d.ts +49 -0
  125. package/types/core/src/request.d.ts +25 -0
  126. package/types/core/src/response.d.ts +28 -0
  127. package/types/core/src/routeDiscovery.d.ts +12 -0
  128. package/types/core/src/router.d.ts +366 -0
  129. package/types/core/src/scss.d.ts +19 -0
  130. package/types/core/src/server.d.ts +146 -0
  131. package/types/core/src/service.d.ts +115 -0
  132. package/types/core/src/session.d.ts +341 -0
  133. package/types/core/src/sessionHandlers/childError.d.ts +34 -0
  134. package/types/core/src/sessionHandlers/databaseHandler.d.ts +97 -0
  135. package/types/core/src/sessionHandlers/memcachedHandler.d.ts +60 -0
  136. package/types/core/src/sessionHandlers/mongoClient.d.ts +35 -0
  137. package/types/core/src/sessionHandlers/mongoHandler.d.ts +109 -0
  138. package/types/core/src/sessionHandlers/respClient.d.ts +22 -0
  139. package/types/core/src/sessionHandlers/sqlClient.d.ts +39 -0
  140. package/types/core/src/sessionHandlers/syncBridge.d.ts +91 -0
  141. package/types/core/src/sessionHandlers/syncSocket.d.ts +49 -0
  142. package/types/core/src/sessionHandlers/valkeyHandler.d.ts +65 -0
  143. package/types/core/src/static.d.ts +2 -0
  144. package/types/core/src/test.d.ts +94 -0
  145. package/types/core/src/testClient.d.ts +36 -0
  146. package/types/core/src/testing.d.ts +58 -0
  147. package/types/core/src/trustedProxy.d.ts +44 -0
  148. package/types/core/src/types.d.ts +242 -0
  149. package/types/core/src/validator.d.ts +52 -0
  150. package/types/core/src/websocket.d.ts +402 -0
  151. package/types/core/src/websocketBackplane.d.ts +166 -0
  152. package/types/core/src/websocketConnection.d.ts +54 -0
  153. package/types/core/src/wsdl.d.ts +101 -0
  154. package/types/frond/src/engine.d.ts +263 -0
  155. package/types/frond/src/index.d.ts +2 -0
  156. package/types/orm/src/adapters/firebird.d.ts +183 -0
  157. package/types/orm/src/adapters/mongodb.d.ts +81 -0
  158. package/types/orm/src/adapters/mssql.d.ts +77 -0
  159. package/types/orm/src/adapters/mysql.d.ts +67 -0
  160. package/types/orm/src/adapters/odbc.d.ts +94 -0
  161. package/types/orm/src/adapters/postgres.d.ts +86 -0
  162. package/types/orm/src/adapters/sqlDialect.d.ts +71 -0
  163. package/types/orm/src/adapters/sqlite.d.ts +68 -0
  164. package/types/orm/src/autoCrud.d.ts +73 -0
  165. package/types/orm/src/baseModel.d.ts +427 -0
  166. package/types/orm/src/cachedDatabase.d.ts +190 -0
  167. package/types/orm/src/connectTimeout.d.ts +100 -0
  168. package/types/orm/src/database.d.ts +655 -0
  169. package/types/orm/src/databaseResult.d.ts +109 -0
  170. package/types/orm/src/databaseUrl.d.ts +125 -0
  171. package/types/orm/src/docstore.d.ts +241 -0
  172. package/types/orm/src/fakeData.d.ts +22 -0
  173. package/types/orm/src/index.d.ts +43 -0
  174. package/types/orm/src/migration.d.ts +275 -0
  175. package/types/orm/src/model.d.ts +7 -0
  176. package/types/orm/src/query.d.ts +14 -0
  177. package/types/orm/src/queryBuilder.d.ts +193 -0
  178. package/types/orm/src/realtime/index.d.ts +7 -0
  179. package/types/orm/src/realtime/models/attachment.d.ts +43 -0
  180. package/types/orm/src/realtime/models/channel.d.ts +32 -0
  181. package/types/orm/src/realtime/models/channelMember.d.ts +32 -0
  182. package/types/orm/src/realtime/models/message.d.ts +36 -0
  183. package/types/orm/src/realtime/models/workspace.d.ts +26 -0
  184. package/types/orm/src/realtime/realtime.d.ts +24 -0
  185. package/types/orm/src/realtime/storage.d.ts +61 -0
  186. package/types/orm/src/seeder.d.ts +118 -0
  187. package/types/orm/src/sqlTranslator.d.ts +258 -0
  188. package/types/orm/src/types.d.ts +148 -0
  189. package/types/orm/src/validation.d.ts +6 -0
  190. package/types/swagger/src/generator.d.ts +46 -0
  191. package/types/swagger/src/index.d.ts +2 -0
  192. package/types/swagger/src/ui.d.ts +11 -0
  193. package/packages/core/src/sessionHandlers/redisHandler.ts +0 -206
@@ -0,0 +1,109 @@
1
+ import type { DatabaseAdapter } from "./types.js";
2
+ /** Column metadata returned by columnInfo(). */
3
+ export interface ColumnInfoResult {
4
+ name: string;
5
+ type: string;
6
+ size: number | null;
7
+ decimals: number | null;
8
+ nullable: boolean;
9
+ primary_key: boolean;
10
+ }
11
+ /**
12
+ * DatabaseResult — wraps fetched rows with convenience methods.
13
+ *
14
+ * Mirrors Python's `DatabaseResult` dataclass from tina4_python.database.adapter.
15
+ * Provides iteration, JSON/CSV export, pagination metadata, and array-like access.
16
+ */
17
+ export declare class DatabaseResult implements Iterable<Record<string, unknown>> {
18
+ readonly records: Record<string, unknown>[];
19
+ readonly columns: string[];
20
+ readonly count: number;
21
+ readonly limit: number;
22
+ readonly offset: number;
23
+ private readonly _adapter?;
24
+ private readonly _sql?;
25
+ private _columnInfoCache?;
26
+ [index: number]: Record<string, unknown> | undefined;
27
+ constructor(records?: Record<string, unknown>[], columns?: string[], count?: number, limit?: number, offset?: number, adapter?: DatabaseAdapter, sql?: string);
28
+ /** JSON string of records. */
29
+ toJson(): string;
30
+ /** CSV with header row. */
31
+ toCsv(): string;
32
+ /** Same as records — plain array of row objects. */
33
+ toArray(): Record<string, unknown>[];
34
+ /** Pagination envelope — accepts either (page, perPage) or (offset, limit) style.
35
+ *
36
+ * When called with two arguments both >= 0 and the first >= the second
37
+ * (i.e. offset-style), pass `{ offset, limit }` as the first argument.
38
+ * The simplest way is to always use the default (page, perPage) form and
39
+ * let the autoCRUD layer supply offset/limit from the query string.
40
+ *
41
+ * Returns a superset of keys for backwards-compatibility across all clients.
42
+ */
43
+ /**
44
+ * Describe the page this result actually IS. Takes no arguments.
45
+ *
46
+ * MEASURED 2026-08-05 on a real 250-row table read with limit=20 offset=40
47
+ * (page 3 of 13): this reported page 1 of 2 and returned 10 of the 20 rows.
48
+ * It ignored the query entirely - defaulting page to 1 and perPage to 10 -
49
+ * then re-sliced the rows it was handed, which were already just that page.
50
+ * So a caller who paginated correctly at the SQL level had the answer
51
+ * silently re-paginated underneath them, with a page number that was simply
52
+ * wrong.
53
+ *
54
+ * WITH page/perPage it slices this result in memory, the behaviour GitHub
55
+ * issue #106 asked for. Valid ONLY when the result holds the WHOLE set
56
+ * (records.length >= count). A PARTIAL result cannot be sliced by page number
57
+ * without lying: MEASURED on 100,000 rows read under the default cap of 100,
58
+ * pages 1-5 of 20 were right and every page from 6 onward came back EMPTY
59
+ * while totalPages reported 5,000.
60
+ *
61
+ * `total` is `count`, and `count` is now the TRUE total for the filter in
62
+ * all four frameworks - Database.fetch runs a COUNT probe whenever it applied
63
+ * a limit. It used to be ROWS RETURNED here and in Ruby while Python and PHP
64
+ * probed, so one query answered 20 in two frameworks and 250 in the other
65
+ * two.
66
+ */
67
+ toPaginate(page?: number, perPage?: number): {
68
+ records: Record<string, unknown>[];
69
+ data: Record<string, unknown>[];
70
+ count: number;
71
+ total: number;
72
+ limit: number;
73
+ offset: number;
74
+ page: number;
75
+ per_page: number;
76
+ perPage: number;
77
+ totalPages: number;
78
+ total_pages: number;
79
+ has_next: boolean;
80
+ has_prev: boolean;
81
+ };
82
+ /** Iterable — for (const row of result) */
83
+ [Symbol.iterator](): Iterator<Record<string, unknown>>;
84
+ /** Total count — cross-framework parity with Python/Ruby. */
85
+ size(): number;
86
+ /** Number of records in this page. */
87
+ get length(): number;
88
+ /** Array-like indexed access with negative index support. */
89
+ at(index: number): Record<string, unknown> | undefined;
90
+ /** JSON.stringify support — serialises as the records array. */
91
+ toJSON(): Record<string, unknown>[];
92
+ /**
93
+ * Return column metadata for the query's table.
94
+ *
95
+ * Lazy — only queries the database when explicitly called. Caches the
96
+ * result so subsequent calls return immediately without re-querying.
97
+ */
98
+ columnInfo(): ColumnInfoResult[];
99
+ /** Extract table name from a SQL query using simple regex. */
100
+ private _extractTableFromSql;
101
+ /** Query the database adapter for column metadata. */
102
+ private _queryColumnMetadata;
103
+ /** Normalize adapter column info to standard format. */
104
+ private _normalizeColumns;
105
+ /** Parse size and decimals from a type string like VARCHAR(255) or NUMERIC(10,2). */
106
+ private _parseTypeSize;
107
+ /** Derive basic column info from record keys when no adapter is available. */
108
+ private _fallbackColumnInfo;
109
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * A parsed database connection URL, as a VALUE.
3
+ *
4
+ * Feature 5 of the feature audit. This used to be `parseDatabaseUrl()`, a single
5
+ * function with a cyclomatic complexity of 43 - the worst function measured
6
+ * anywhere in the audit - whose entire job is string-to-struct. It is now one
7
+ * small parser per engine, each well under the threshold, behind a value type
8
+ * with the same surface as PHP's `DatabaseUrl` (the reference for this row).
9
+ *
10
+ * Core Principle 6 says a connection string must mean literally the same thing
11
+ * in every framework. `test/fixtures/database_url_corpus.json` is the answer
12
+ * key, byte-identical in all four.
13
+ */
14
+ import { inspect } from "node:util";
15
+ /** The canonical engine names. Aliases resolve to these ONCE, at parse. */
16
+ export type DatabaseEngine = "sqlite" | "postgres" | "mysql" | "mssql" | "firebird" | "mongodb" | "odbc";
17
+ /**
18
+ * Remove every credential from an arbitrary connection string.
19
+ *
20
+ * THE single redaction primitive. It works on a RAW string - valid or
21
+ * malformed, a URL or an ODBC DSN - so the error paths can use it too, and it
22
+ * is what `toSafeString()` calls for the odbc form rather than hand-rolling a
23
+ * second, weaker rule.
24
+ *
25
+ * It cannot be complete on a string with no recognisable credential structure
26
+ * (`notaurl-with-hunter2` has nothing to key off), which is exactly why the
27
+ * invalid-URL error reports the scheme and host instead of any form of the
28
+ * input. Redaction is for strings we can parse enough to redact.
29
+ */
30
+ export declare function redactCredentials(raw: string): string;
31
+ /**
32
+ * DISPLAY REDACTS, FIDELITY DOES NOT. JSON.stringify, util.inspect, String() and
33
+ * toSafeString() replace the password with the redaction marker, so a log line, a
34
+ * stack or a status payload is safe. structuredClone deliberately does not: its
35
+ * contract is a faithful structural copy, and a masked clone would produce an
36
+ * object whose password is the literal "***".
37
+ *
38
+ * The consequence: DO NOT PERSIST THIS OBJECT. A DatabaseUrl structured-cloned
39
+ * onto a worker thread, into a cache or into a queue payload carries a cleartext
40
+ * credential across that boundary. Use toSafeString() instead.
41
+ * test/databaseUrlRedaction.test.ts fails the build if framework code ever does.
42
+ */
43
+ export declare class DatabaseUrl {
44
+ readonly engine: DatabaseEngine;
45
+ /** Null for sqlite and odbc - a file or a DSN string has no host. */
46
+ readonly host: string | null;
47
+ /** Null for sqlite and odbc. Otherwise always set: the engine default applies. */
48
+ readonly port: number | null;
49
+ readonly database: string;
50
+ /** Null when absent, never an empty string - absent and blank differ. */
51
+ readonly username: string | null;
52
+ readonly password: string | null;
53
+ /** ODBC only: the raw connection string handed to odbc.connect(). */
54
+ readonly connectionString: string | null;
55
+ constructor(url: string, username?: string, password?: string);
56
+ static fromEnv(key?: string): DatabaseUrl | null;
57
+ /**
58
+ * Connection target for the adapter. sqlite and odbc are the whole value.
59
+ *
60
+ * NOT SAFE TO LOG. For every network engine this is credential-free
61
+ * (host:port/database), which makes it look loggable - but the odbc branch
62
+ * returns the connection string VERBATIM, `PWD=` included, because that is
63
+ * what the driver has to receive. Log `toSafeString()`; never this.
64
+ */
65
+ dsn(): string;
66
+ /**
67
+ * The URL with the password replaced by ***.
68
+ *
69
+ * The ONLY form allowed in a log line or an error message: a connection URL in
70
+ * a log is a credential leak. Node had no such method at all before this,
71
+ * which meant every call site that wanted to log a connection target had to
72
+ * redact it by hand. It round-trips, so it stays readable as well as safe.
73
+ */
74
+ toSafeString(): string;
75
+ /**
76
+ * What `JSON.stringify(url)` emits.
77
+ *
78
+ * Without it, stringifying the value - directly, or as one field of a config
79
+ * object being logged - emitted `"password":"<the real password>"`, measured
80
+ * on this class. Python guards the same exposure with `__repr__` and Ruby
81
+ * with `#inspect`; JSON is the shape Node actually serialises into a log
82
+ * line, so it needs the guard too.
83
+ *
84
+ * Structure is preserved so the dump is still worth having: only the secret
85
+ * is masked. `null` stays `null` - an ABSENT password and a masked one are
86
+ * different facts, and flattening them would hide exactly the confusion C7
87
+ * is about.
88
+ */
89
+ toJSON(): Record<string, unknown>;
90
+ /**
91
+ * What `console.log(url)` / `util.inspect(url)` print.
92
+ *
93
+ * Node's equivalent of Python's `__repr__` and Ruby's `#inspect`, and the
94
+ * same rendering they produce - `DatabaseUrl('postgres://user:***@h:5432/db')`
95
+ * (tina4-python/tina4_python/database/database_url.py:153). Without it,
96
+ * `console.log(url)` printed the default field dump, password included.
97
+ */
98
+ [inspect.custom](): string;
99
+ private static parse;
100
+ /**
101
+ * sqlite is parsed on the RAW string. The URL class collapses `sqlite:/x` and
102
+ * `sqlite:///x`, losing the difference between a one-slash ABSOLUTE path and
103
+ * the documented three-slash RELATIVE form.
104
+ *
105
+ * sqlite:///app.db -> app.db (three slashes = relative to cwd)
106
+ * sqlite:////abs/app.db -> /abs/app.db (four slashes = absolute)
107
+ * sqlite:/abs/app.db -> /abs/app.db (one slash = a real absolute path)
108
+ * sqlite:app.db -> app.db
109
+ */
110
+ private static parseSqlite;
111
+ /**
112
+ * mssql and firebird: the URL class does not know these schemes, so they are
113
+ * matched directly.
114
+ *
115
+ * The captured path keeps its own leading slash when the URL had two, which is
116
+ * how the documented absolute Firebird form survives. The old code did
117
+ * `"/" + match[5]`, ADDING a slash - so an absolute path came back with two
118
+ * and a relative path was silently made absolute. Verified against live
119
+ * Firebird 5.0.4: the driver takes one or two leading slashes and rejects a
120
+ * relative path outright.
121
+ */
122
+ private static parseRegexForm;
123
+ /** postgres / mysql / mongodb, via the URL class. */
124
+ private static parseStandard;
125
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Tina4 DocStore - pymongo-style document storage with a zero-config SQLite (JSON1) fallback.
3
+ *
4
+ * A document store with the everyday MongoDB driver collection API, backed by
5
+ * SQLite's JSON1 extension when no MongoDB server is configured.
6
+ *
7
+ * import { getCollection, ObjectId } from "@tina4/orm";
8
+ *
9
+ * const orders = await getCollection("orders"); // SqliteCollection when no Mongo configured
10
+ * const { insertedId } = await orders.insertOne({ customer_id: 1, total: 9.99 });
11
+ * for (const o of await orders.find({ customer_id: { $in: [1, 2] } }).sort("created_at", -1).limit(10).toArray()) {
12
+ * // ...
13
+ * }
14
+ * await orders.updateOne({ _id: insertedId }, { $set: { status: "shipped" } });
15
+ *
16
+ * `getCollection(name)` returns a real MongoDB driver `Collection` when a Mongo
17
+ * URI is configured (TINA4_MONGO_URI, else TINA4_SESSION_MONGO_URI - the same
18
+ * names the queue/session Mongo backends read), and otherwise a SqliteCollection
19
+ * backed by a local SQLite file. This mirrors the file-based fallbacks the queue,
20
+ * cache, and session subsystems already provide: an app that talks to Mongo in
21
+ * production runs serverless in local dev with no code change - only the backend
22
+ * differs.
23
+ *
24
+ * A configured URI with NO driver installed throws `DocStoreDriverMissing`
25
+ * (ADR-0033). It does NOT quietly use the local SQLite store, and it no longer
26
+ * surfaces a bare ERR_MODULE_NOT_FOUND that names an npm package rather than
27
+ * the framework decision that led there.
28
+ *
29
+ * Design (the SQLite backend):
30
+ * - Each collection is a table `(_id TEXT PRIMARY KEY, doc TEXT)`; `doc` is JSON.
31
+ * - Query filters are pushed down to SQL over `json_extract(doc, '$.field')`
32
+ * (lazy, not a full in-memory scan), supporting equality, $in/$nin,
33
+ * $gt/$gte/$lt/$lte, $ne, $exists, $regex, and implicit-AND / $or / $and.
34
+ * - Updates: $set, $unset, $inc, and full-document replace.
35
+ * - Cursors: sort / limit / skip / projection.
36
+ * - IDs are a built-in 12-byte ObjectId (zero-dependency; interchangeable with
37
+ * the driver's ObjectId as a 24-hex string).
38
+ *
39
+ * Type round-trip is by value, not by wrapper object, so json_extract stays
40
+ * queryable and sortable: a Date is stored as an ISO-8601 UTC string and an
41
+ * ObjectId as its 24-hex string, and reads rehydrate a strict-ISO string back to
42
+ * a Date and a 24-hex string back to an ObjectId. That keeps range queries and
43
+ * sorts working on date and id fields - the trade-off (a plain 24-hex / ISO
44
+ * string becomes an ObjectId / Date on read) is acceptable for the local dev store.
45
+ *
46
+ * Deliberate non-goals: aggregation pipeline, $elemMatch, geo. This is the
47
+ * everyday CRUD + filter subset, not full Mongo parity.
48
+ */
49
+ import { DatabaseSync } from "node:sqlite";
50
+ /** Raised when a value cannot be parsed as an ObjectId. */
51
+ export declare class InvalidId extends Error {
52
+ constructor(message: string);
53
+ }
54
+ /**
55
+ * A 12-byte MongoDB-style ObjectId, with no external dependency.
56
+ *
57
+ * Layout: 4-byte big-endian seconds since epoch, 5-byte per-process random,
58
+ * 3-byte big-endian counter. Renders as a 24-char hex string, so it is
59
+ * interchangeable with the driver's ObjectId wherever the string form is used.
60
+ */
61
+ export declare class ObjectId {
62
+ private static _counter;
63
+ private static _process;
64
+ private readonly _bytes;
65
+ constructor(oid?: ObjectId | Buffer | Uint8Array | string | null);
66
+ private static _generate;
67
+ static isValid(value: unknown): boolean;
68
+ get binary(): Buffer;
69
+ /** The timestamp embedded in the id (the first 4 bytes), as a Date. */
70
+ get generationTime(): Date;
71
+ toString(): string;
72
+ toJSON(): string;
73
+ equals(other: unknown): boolean;
74
+ }
75
+ /** Value -> JSON-serialisable, sortable scalar form (for storage/queries). */
76
+ export declare function encodeValue(value: unknown): unknown;
77
+ /** Stored JSON value -> rich value, rehydrating ObjectId (24-hex) and Date (ISO). */
78
+ export declare function decodeValue(value: unknown): unknown;
79
+ interface CompiledFilter {
80
+ where: string;
81
+ params: unknown[];
82
+ }
83
+ /**
84
+ * Compile a Mongo-style filter object into { where, params }.
85
+ *
86
+ * Returns { where: "1=1", params: [] } for an empty filter. Supports implicit
87
+ * AND across keys, $or / $and, and the per-field operator set.
88
+ */
89
+ export declare function compileFilter(query?: Record<string, unknown> | null): CompiledFilter;
90
+ export interface InsertOneResult {
91
+ acknowledged: boolean;
92
+ insertedId: unknown;
93
+ }
94
+ export interface InsertManyResult {
95
+ acknowledged: boolean;
96
+ insertedIds: unknown[];
97
+ }
98
+ export interface UpdateResult {
99
+ acknowledged: boolean;
100
+ matchedCount: number;
101
+ modifiedCount: number;
102
+ upsertedId: unknown | null;
103
+ }
104
+ export interface DeleteResult {
105
+ acknowledged: boolean;
106
+ deletedCount: number;
107
+ }
108
+ /** Lazy result cursor. Builds and runs SQL only when materialised (toArray). */
109
+ /** The three sort spellings a real FindCursor accepts. */
110
+ export type SortSpec = string | [string, number][] | Record<string, number> | Map<string, number>;
111
+ /**
112
+ * Normalise the driver's three sort spellings to a list of [key, direction].
113
+ *
114
+ * ADR-0036. A real `FindCursor.sort()` accepts a key plus a direction, a list
115
+ * of `[key, direction]` pairs, OR an object/Map - and the driver is the shape
116
+ * this fallback imitates (ADR-0025). The object form used to throw
117
+ * `TypeError: keyOrList is not iterable` here. Measured 2026-08-04 against a
118
+ * real MongoDB: the object spelling worked on the driver and threw on the
119
+ * fallback, in three of the four frameworks.
120
+ */
121
+ export declare function sortSpec(keyOrList: SortSpec, direction?: number): [string, number][];
122
+ export declare class Cursor {
123
+ #private;
124
+ /**
125
+ * The cursor receives WHAT IT NEEDS, not the collection it came from.
126
+ *
127
+ * It used to hold the collection and reach back for `connection`, `quoted` and
128
+ * `load` - which is the only reason those three were public. ADR-0025
129
+ * corollary 1: anything the fallback needs internally is private, and a real
130
+ * FindCursor exposes none of them. Handing over the two values and calling the
131
+ * module-level loader removes the back-reference AND the public surface.
132
+ */
133
+ constructor(conn: DatabaseSync, quoted: string, where: string, params: unknown[], projection?: Record<string, unknown> | null);
134
+ sort(keyOrList: SortSpec, direction?: number): this;
135
+ limit(n: number): this;
136
+ skip(n: number): this;
137
+ /**
138
+ * Materialise the cursor into an array of decoded documents.
139
+ *
140
+ * ASYNC because the driver's FindCursor.toArray() is async (ADR-0025 clause
141
+ * 3). The work underneath is synchronous - node:sqlite has no async API - but
142
+ * the SHAPE is what a call site sees, and a shape that changes with the
143
+ * provider is the defect this fixes.
144
+ */
145
+ toArray(): Promise<Record<string, unknown>[]>;
146
+ /**
147
+ * Async iteration, matching the driver.
148
+ *
149
+ * NOTE: there is deliberately no [Symbol.iterator] here. A real FindCursor
150
+ * has ONLY Symbol.asyncIterator, so `for (const doc of cursor)` is a
151
+ * fallback-only spelling - it works locally and throws "is not iterable" the
152
+ * moment TINA4_MONGO_URI is set. Use `for await (const doc of cursor)`.
153
+ *
154
+ * toList() is gone for the same reason: the driver's FindCursor has no such
155
+ * method.
156
+ *
157
+ * ADR-0035 restored the uniform spellings in ruby and php through a
158
+ * delegator, and deliberately did NOT do so here. A delegator can only supply
159
+ * a method that is POSSIBLE on the real provider, and a synchronous iterator
160
+ * is not: a FindCursor is async-only. Adding one back on the fallback alone
161
+ * would recreate ADR-0025's worst measured defect - identical source changing
162
+ * TYPE, with a truthy Promise passing `if (doc)` for a document that does not
163
+ * exist. That is ADR-0025 corollary 3, which ADR-0035 keeps.
164
+ */
165
+ [Symbol.asyncIterator](): AsyncIterator<Record<string, unknown>>;
166
+ }
167
+ /** A SQLite-backed collection exposing the everyday MongoDB driver API. */
168
+ export declare class SqliteCollection {
169
+ #private;
170
+ constructor(conn: DatabaseSync, name: string);
171
+ insertOne(document: Record<string, unknown>): Promise<InsertOneResult>;
172
+ insertMany(documents: Record<string, unknown>[]): Promise<InsertManyResult>;
173
+ find(filter?: Record<string, unknown> | null, projection?: Record<string, unknown> | null): Cursor;
174
+ findOne(filter?: Record<string, unknown> | null, projection?: Record<string, unknown> | null): Promise<Record<string, unknown> | null>;
175
+ countDocuments(filter?: Record<string, unknown> | null): Promise<number>;
176
+ estimatedDocumentCount(): Promise<number>;
177
+ distinct(key: string, filter?: Record<string, unknown> | null): Promise<unknown[]>;
178
+ updateOne(filter: Record<string, unknown> | null | undefined, update: Record<string, unknown>, options?: {
179
+ upsert?: boolean;
180
+ }): Promise<UpdateResult>;
181
+ updateMany(filter: Record<string, unknown> | null | undefined, update: Record<string, unknown>, options?: {
182
+ upsert?: boolean;
183
+ }): Promise<UpdateResult>;
184
+ replaceOne(filter: Record<string, unknown> | null | undefined, replacement: Record<string, unknown>, options?: {
185
+ upsert?: boolean;
186
+ }): Promise<UpdateResult>;
187
+ deleteOne(filter?: Record<string, unknown> | null): Promise<DeleteResult>;
188
+ deleteMany(filter?: Record<string, unknown> | null): Promise<DeleteResult>;
189
+ drop(): Promise<void>;
190
+ }
191
+ /** A SQLite-backed document database (a file of collection tables). */
192
+ export declare class SqliteDatabase {
193
+ readonly path: string;
194
+ private readonly conn;
195
+ private readonly collections;
196
+ constructor(path?: string);
197
+ getCollection(name: string): SqliteCollection;
198
+ listCollectionNames(): string[];
199
+ close(): void;
200
+ }
201
+ /**
202
+ * A Mongo URI is configured but the MongoDB driver is not installed.
203
+ *
204
+ * ADR-0024 rule 3, settled for DocStore by ADR-0033: a provider that cannot
205
+ * honour an operation must RAISE, naming the provider and what is missing.
206
+ * Node already threw here, but with a bare ERR_MODULE_NOT_FOUND that named an
207
+ * npm package and not the framework decision that led there - so the outcome
208
+ * was loud but undocumented, and different from the other three frameworks.
209
+ */
210
+ export declare class DocStoreDriverMissing extends Error {
211
+ constructor(message: string);
212
+ }
213
+ /** True when no Mongo is configured, so the SQLite fallback is in effect. */
214
+ export declare function isServerless(): boolean;
215
+ /**
216
+ * Return a collection for `name`.
217
+ *
218
+ * A real MongoDB driver `Collection` when a Mongo URI is configured (and the
219
+ * `mongodb` driver is installed); otherwise a `SqliteCollection` backed by the
220
+ * local SQLite file. Same call sites either way - only the backend differs.
221
+ *
222
+ * ALWAYS async, on BOTH providers (ADR-0025 clause 3).
223
+ *
224
+ * It used to return a SqliteCollection SYNCHRONOUSLY in serverless mode and a
225
+ * Promise on the real-Mongo path. That made identical source change TYPE when
226
+ * TINA4_MONGO_URI was set, and a Promise is always truthy - so un-awaited code
227
+ * read a real document locally and a thenable in production, and `if (doc)`
228
+ * succeeded for a document that did not exist. The driver cannot become sync,
229
+ * so the fallback becomes async.
230
+ */
231
+ export declare function getCollection(name: string): Promise<SqliteCollection | unknown>;
232
+ /**
233
+ * Close every DocStore connection: the SQLite store and all Mongo clients.
234
+ *
235
+ * A pooled client keeps the event loop alive, so a script or test that touches
236
+ * the real provider needs a way to let the process end on its own.
237
+ */
238
+ export declare function closeDocStore(): Promise<void>;
239
+ /** Drop the cached default SQLite store (test helper). */
240
+ export declare function resetDefaultStore(): void;
241
+ export {};
@@ -0,0 +1,22 @@
1
+ import { FakeData as CoreFakeData } from "../../core/src/fakeData.js";
2
+ import type { FieldDefinition } from "./types.js";
3
+ /**
4
+ * ORM-aware FakeData — wraps the core FakeData and adds forField()
5
+ * which generates appropriate fake data based on an ORM FieldDefinition.
6
+ */
7
+ export declare class FakeData extends CoreFakeData {
8
+ constructor(seed?: number);
9
+ /**
10
+ * Generate a Date object within a year range.
11
+ * Matches the Python API's datetime() method.
12
+ */
13
+ datetime(startYear?: number, endYear?: number): Date;
14
+ /**
15
+ * Generate a fake value appropriate for an ORM field definition.
16
+ * Respects min/max, minLength/maxLength, and type constraints.
17
+ *
18
+ * @param fieldDef - An ORM FieldDefinition object
19
+ * @param columnName - Optional column name for heuristic matching (e.g. "email", "phone")
20
+ */
21
+ forField(fieldDef: FieldDefinition, columnName?: string): unknown;
22
+ }
@@ -0,0 +1,43 @@
1
+ export type { FieldType, FieldDefinition, ModelDefinition, DatabaseAdapter, DatabaseResult as DatabaseWriteResult, ColumnInfo, QueryOptions, RelationshipDefinition, PaginatedResult, } from "./types.js";
2
+ export { FetchResult } from "./types.js";
3
+ export { DatabaseResult } from "./databaseResult.js";
4
+ export type { ColumnInfoResult } from "./databaseResult.js";
5
+ export { Database, initDatabase, getAdapter, setAdapter, bindDatabase, createAdapterFromUrl, closeDatabase, parseDatabaseUrl, setNamedAdapter, getNamedAdapter, resolveDbPool, stripTrailingSemicolons, wrapWithCache, resetRequestCaches } from "./database.js";
6
+ export { adapterFetch, adapterQuery, adapterFetchOne, adapterExecute, adapterStartTransaction, adapterCommit, adapterRollback, adapterTableExists, adapterTables, adapterColumns, adapterCreateTable, extractLastInsertId, } from "./database.js";
7
+ export type { DatabaseConfig } from "./database.js";
8
+ export { DatabaseUrl, redactCredentials } from "./databaseUrl.js";
9
+ export type { DatabaseEngine } from "./databaseUrl.js";
10
+ export { discoverModels } from "./model.js";
11
+ export type { DiscoveredModel } from "./model.js";
12
+ export { syncModels, ensureMigrationTable, getNextBatch, isMigrationApplied, recordMigration, applyMigration, rollback, getAppliedMigrations, getLastBatchMigrations, removeMigrationRecord, migrate, createMigration, status, Migration, splitStatements, parseSetTerm, normalizeQuotes, sortMigrationFiles, shouldSkipCreateTable, } from "./migration.js";
13
+ export type { MigrationResult, MigrationStatus } from "./migration.js";
14
+ export { AutoCrud, generateCrudRoutes, crudEligibleModels } from "./autoCrud.js";
15
+ export type { AutoCrudOptions } from "./autoCrud.js";
16
+ export { buildQuery, parseQueryString } from "./query.js";
17
+ export { validate } from "./validation.js";
18
+ export type { ValidationError } from "./validation.js";
19
+ export { BaseModel, snakeToCamel, camelToSnake } from "./baseModel.js";
20
+ export { QueryBuilder } from "./queryBuilder.js";
21
+ export { SQLTranslator, QueryCache } from "./sqlTranslator.js";
22
+ export { DEFAULT_DATABASE_CONNECT_TIMEOUT_SECONDS, CONNECT_TIMEOUT_TOLERANCE_MS, connectTimeoutMillis, driverConnectTimeoutMillis, connectTarget, withConnectTimeout, } from "./connectTimeout.js";
23
+ export { CachedDatabaseAdapter } from "./cachedDatabase.js";
24
+ export type { CachedAdapterOptions } from "./cachedDatabase.js";
25
+ export { FakeData } from "./fakeData.js";
26
+ export { seedTable, seedOrm, seedModels, autoFieldMap } from "./seeder.js";
27
+ export type { SeedSummary, SeedOptions } from "./seeder.js";
28
+ export { ObjectId, InvalidId, DocStoreDriverMissing, SqliteDatabase, SqliteCollection, Cursor, getCollection, isServerless, resetDefaultStore, closeDocStore, encodeValue, decodeValue, compileFilter, } from "./docstore.js";
29
+ export type { InsertOneResult, InsertManyResult, UpdateResult, DeleteResult, } from "./docstore.js";
30
+ export { SQLiteAdapter } from "./adapters/sqlite.js";
31
+ export { PostgresAdapter } from "./adapters/postgres.js";
32
+ export type { PostgresConfig } from "./adapters/postgres.js";
33
+ export { MysqlAdapter } from "./adapters/mysql.js";
34
+ export type { MysqlConfig } from "./adapters/mysql.js";
35
+ export { MssqlAdapter } from "./adapters/mssql.js";
36
+ export type { MssqlConfig } from "./adapters/mssql.js";
37
+ export { FirebirdAdapter, normalizeFirebirdDbIdentifier, resolveFirebirdCharset } from "./adapters/firebird.js";
38
+ export type { FirebirdConfig } from "./adapters/firebird.js";
39
+ export { MongodbAdapter } from "./adapters/mongodb.js";
40
+ export type { MongoConfig } from "./adapters/mongodb.js";
41
+ export { OdbcAdapter } from "./adapters/odbc.js";
42
+ export type { OdbcConfig } from "./adapters/odbc.js";
43
+ export { realtime, iceServers, type RealtimeOptions, LocalStorage, S3Storage, selectStorage, storageKey, type StorageBackend, Workspace as RealtimeWorkspace, Channel as RealtimeChannel, ChannelMember as RealtimeChannelMember, Message as RealtimeMessage, Attachment as RealtimeAttachment, } from "./realtime/index.js";