@hatk/hatk 0.0.1-alpha.8 → 0.0.1-alpha.81

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 (175) hide show
  1. package/dist/adapter.d.ts +19 -0
  2. package/dist/adapter.d.ts.map +1 -0
  3. package/dist/adapter.js +111 -0
  4. package/dist/backfill.d.ts +29 -2
  5. package/dist/backfill.d.ts.map +1 -1
  6. package/dist/backfill.js +136 -51
  7. package/dist/car.d.ts +42 -10
  8. package/dist/car.d.ts.map +1 -1
  9. package/dist/car.js +154 -14
  10. package/dist/cli.js +243 -1043
  11. package/dist/config.d.ts +82 -1
  12. package/dist/config.d.ts.map +1 -1
  13. package/dist/config.js +44 -9
  14. package/dist/database/adapter-factory.d.ts +6 -0
  15. package/dist/database/adapter-factory.d.ts.map +1 -0
  16. package/dist/database/adapter-factory.js +20 -0
  17. package/dist/database/adapters/duckdb-search.d.ts +12 -0
  18. package/dist/database/adapters/duckdb-search.d.ts.map +1 -0
  19. package/dist/database/adapters/duckdb-search.js +27 -0
  20. package/dist/database/adapters/duckdb.d.ts +25 -0
  21. package/dist/database/adapters/duckdb.d.ts.map +1 -0
  22. package/dist/database/adapters/duckdb.js +161 -0
  23. package/dist/database/adapters/sqlite-search.d.ts +16 -0
  24. package/dist/database/adapters/sqlite-search.d.ts.map +1 -0
  25. package/dist/database/adapters/sqlite-search.js +76 -0
  26. package/dist/database/adapters/sqlite.d.ts +18 -0
  27. package/dist/database/adapters/sqlite.d.ts.map +1 -0
  28. package/dist/database/adapters/sqlite.js +88 -0
  29. package/dist/{db.d.ts → database/db.d.ts} +57 -6
  30. package/dist/database/db.d.ts.map +1 -0
  31. package/dist/{db.js → database/db.js} +755 -552
  32. package/dist/database/dialect.d.ts +45 -0
  33. package/dist/database/dialect.d.ts.map +1 -0
  34. package/dist/database/dialect.js +72 -0
  35. package/dist/{fts.d.ts → database/fts.d.ts} +7 -0
  36. package/dist/database/fts.d.ts.map +1 -0
  37. package/dist/{fts.js → database/fts.js} +116 -32
  38. package/dist/database/index.d.ts +7 -0
  39. package/dist/database/index.d.ts.map +1 -0
  40. package/dist/database/index.js +6 -0
  41. package/dist/database/ports.d.ts +50 -0
  42. package/dist/database/ports.d.ts.map +1 -0
  43. package/dist/database/ports.js +1 -0
  44. package/dist/{schema.d.ts → database/schema.d.ts} +14 -3
  45. package/dist/database/schema.d.ts.map +1 -0
  46. package/dist/{schema.js → database/schema.js} +81 -41
  47. package/dist/dev-entry.d.ts +8 -0
  48. package/dist/dev-entry.d.ts.map +1 -0
  49. package/dist/dev-entry.js +125 -0
  50. package/dist/feeds.d.ts +12 -8
  51. package/dist/feeds.d.ts.map +1 -1
  52. package/dist/feeds.js +51 -6
  53. package/dist/hooks.d.ts +85 -0
  54. package/dist/hooks.d.ts.map +1 -0
  55. package/dist/hooks.js +163 -0
  56. package/dist/hydrate.d.ts +7 -6
  57. package/dist/hydrate.d.ts.map +1 -1
  58. package/dist/hydrate.js +4 -16
  59. package/dist/indexer.d.ts +133 -3
  60. package/dist/indexer.d.ts.map +1 -1
  61. package/dist/indexer.js +406 -66
  62. package/dist/jetstream.d.ts +118 -0
  63. package/dist/jetstream.d.ts.map +1 -0
  64. package/dist/jetstream.js +225 -0
  65. package/dist/labels.d.ts +36 -0
  66. package/dist/labels.d.ts.map +1 -1
  67. package/dist/labels.js +71 -6
  68. package/dist/lexicon-resolve.d.ts.map +1 -1
  69. package/dist/lexicon-resolve.js +27 -112
  70. package/dist/lexicons/com/atproto/label/defs.json +75 -0
  71. package/dist/lexicons/com/atproto/moderation/defs.json +30 -0
  72. package/dist/lexicons/com/atproto/repo/strongRef.json +21 -0
  73. package/dist/lexicons/dev/hatk/applyWrites.json +87 -0
  74. package/dist/lexicons/dev/hatk/createRecord.json +40 -0
  75. package/dist/lexicons/dev/hatk/createReport.json +48 -0
  76. package/dist/lexicons/dev/hatk/deleteRecord.json +25 -0
  77. package/dist/lexicons/dev/hatk/describeCollections.json +41 -0
  78. package/dist/lexicons/dev/hatk/describeFeeds.json +29 -0
  79. package/dist/lexicons/dev/hatk/describeLabels.json +45 -0
  80. package/dist/lexicons/dev/hatk/getFeed.json +30 -0
  81. package/dist/lexicons/dev/hatk/getPreferences.json +19 -0
  82. package/dist/lexicons/dev/hatk/getRecord.json +26 -0
  83. package/dist/lexicons/dev/hatk/getRecords.json +32 -0
  84. package/dist/lexicons/dev/hatk/putPreference.json +28 -0
  85. package/dist/lexicons/dev/hatk/putRecord.json +41 -0
  86. package/dist/lexicons/dev/hatk/searchRecords.json +32 -0
  87. package/dist/lexicons/dev/hatk/uploadBlob.json +23 -0
  88. package/dist/logger.d.ts +29 -0
  89. package/dist/logger.d.ts.map +1 -1
  90. package/dist/logger.js +29 -0
  91. package/dist/main.js +169 -74
  92. package/dist/mst.d.ts +18 -1
  93. package/dist/mst.d.ts.map +1 -1
  94. package/dist/mst.js +19 -8
  95. package/dist/oauth/db.d.ts +3 -1
  96. package/dist/oauth/db.d.ts.map +1 -1
  97. package/dist/oauth/db.js +56 -19
  98. package/dist/oauth/discovery.d.ts.map +1 -1
  99. package/dist/oauth/discovery.js +13 -1
  100. package/dist/oauth/server.d.ts +92 -1
  101. package/dist/oauth/server.d.ts.map +1 -1
  102. package/dist/oauth/server.js +352 -37
  103. package/dist/oauth/service-describe.d.ts +31 -0
  104. package/dist/oauth/service-describe.d.ts.map +1 -0
  105. package/dist/oauth/service-describe.js +61 -0
  106. package/dist/oauth/session.d.ts +32 -0
  107. package/dist/oauth/session.d.ts.map +1 -0
  108. package/dist/oauth/session.js +131 -0
  109. package/dist/opengraph.d.ts +10 -0
  110. package/dist/opengraph.d.ts.map +1 -1
  111. package/dist/opengraph.js +80 -40
  112. package/dist/pds-proxy.d.ts +82 -0
  113. package/dist/pds-proxy.d.ts.map +1 -0
  114. package/dist/pds-proxy.js +356 -0
  115. package/dist/private-collections.d.ts +8 -0
  116. package/dist/private-collections.d.ts.map +1 -0
  117. package/dist/private-collections.js +22 -0
  118. package/dist/push.d.ts +54 -0
  119. package/dist/push.d.ts.map +1 -0
  120. package/dist/push.js +367 -0
  121. package/dist/renderer.d.ts +27 -0
  122. package/dist/renderer.d.ts.map +1 -0
  123. package/dist/renderer.js +46 -0
  124. package/dist/resolve-hatk.d.ts +6 -0
  125. package/dist/resolve-hatk.d.ts.map +1 -0
  126. package/dist/resolve-hatk.js +20 -0
  127. package/dist/response.d.ts +16 -0
  128. package/dist/response.d.ts.map +1 -0
  129. package/dist/response.js +69 -0
  130. package/dist/scanner.d.ts +21 -0
  131. package/dist/scanner.d.ts.map +1 -0
  132. package/dist/scanner.js +88 -0
  133. package/dist/seed.d.ts +19 -0
  134. package/dist/seed.d.ts.map +1 -1
  135. package/dist/seed.js +43 -4
  136. package/dist/server-init.d.ts +8 -0
  137. package/dist/server-init.d.ts.map +1 -0
  138. package/dist/server-init.js +62 -0
  139. package/dist/server.d.ts +26 -3
  140. package/dist/server.d.ts.map +1 -1
  141. package/dist/server.js +858 -638
  142. package/dist/setup.d.ts +28 -1
  143. package/dist/setup.d.ts.map +1 -1
  144. package/dist/setup.js +50 -3
  145. package/dist/templates/feed.tpl +14 -0
  146. package/dist/templates/hook.tpl +5 -0
  147. package/dist/templates/label.tpl +15 -0
  148. package/dist/templates/og.tpl +17 -0
  149. package/dist/templates/seed.tpl +11 -0
  150. package/dist/templates/setup.tpl +5 -0
  151. package/dist/templates/test-feed.tpl +19 -0
  152. package/dist/templates/test-xrpc.tpl +19 -0
  153. package/dist/templates/xrpc.tpl +41 -0
  154. package/dist/test.d.ts +1 -1
  155. package/dist/test.d.ts.map +1 -1
  156. package/dist/test.js +41 -32
  157. package/dist/views.js +1 -1
  158. package/dist/vite-plugin.d.ts +1 -1
  159. package/dist/vite-plugin.d.ts.map +1 -1
  160. package/dist/vite-plugin.js +254 -66
  161. package/dist/xrpc.d.ts +84 -11
  162. package/dist/xrpc.d.ts.map +1 -1
  163. package/dist/xrpc.js +211 -41
  164. package/package.json +17 -9
  165. package/public/admin-auth.js +271 -306
  166. package/public/admin.html +177 -61
  167. package/dist/db.d.ts.map +0 -1
  168. package/dist/fts.d.ts.map +0 -1
  169. package/dist/oauth/hooks.d.ts +0 -10
  170. package/dist/oauth/hooks.d.ts.map +0 -1
  171. package/dist/oauth/hooks.js +0 -40
  172. package/dist/schema.d.ts.map +0 -1
  173. package/dist/test-browser.d.ts +0 -14
  174. package/dist/test-browser.d.ts.map +0 -1
  175. package/dist/test-browser.js +0 -26
@@ -0,0 +1,26 @@
1
+ {
2
+ "lexicon": 1,
3
+ "id": "dev.hatk.getRecord",
4
+ "defs": {
5
+ "main": {
6
+ "type": "query",
7
+ "description": "Fetch a single record by AT URI.",
8
+ "parameters": {
9
+ "type": "params",
10
+ "required": ["uri"],
11
+ "properties": {
12
+ "uri": { "type": "string", "format": "at-uri" }
13
+ }
14
+ },
15
+ "output": {
16
+ "encoding": "application/json",
17
+ "schema": {
18
+ "type": "object",
19
+ "properties": {
20
+ "record": { "type": "unknown" }
21
+ }
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "lexicon": 1,
3
+ "id": "dev.hatk.getRecords",
4
+ "defs": {
5
+ "main": {
6
+ "type": "query",
7
+ "description": "List records from a collection with optional filters.",
8
+ "parameters": {
9
+ "type": "params",
10
+ "required": ["collection"],
11
+ "properties": {
12
+ "collection": { "type": "string" },
13
+ "limit": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 },
14
+ "cursor": { "type": "string" },
15
+ "sort": { "type": "string" },
16
+ "order": { "type": "string" }
17
+ }
18
+ },
19
+ "output": {
20
+ "encoding": "application/json",
21
+ "schema": {
22
+ "type": "object",
23
+ "required": ["items"],
24
+ "properties": {
25
+ "items": { "type": "array", "items": { "type": "unknown" } },
26
+ "cursor": { "type": "string" }
27
+ }
28
+ }
29
+ }
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "lexicon": 1,
3
+ "id": "dev.hatk.putPreference",
4
+ "defs": {
5
+ "main": {
6
+ "type": "procedure",
7
+ "description": "Set a single preference by key.",
8
+ "input": {
9
+ "encoding": "application/json",
10
+ "schema": {
11
+ "type": "object",
12
+ "required": ["key", "value"],
13
+ "properties": {
14
+ "key": { "type": "string" },
15
+ "value": { "type": "unknown" }
16
+ }
17
+ }
18
+ },
19
+ "output": {
20
+ "encoding": "application/json",
21
+ "schema": {
22
+ "type": "object",
23
+ "properties": {}
24
+ }
25
+ }
26
+ }
27
+ }
28
+ }
@@ -0,0 +1,41 @@
1
+ {
2
+ "lexicon": 1,
3
+ "id": "dev.hatk.putRecord",
4
+ "defs": {
5
+ "main": {
6
+ "type": "procedure",
7
+ "description": "Create or update a record via the user's PDS.",
8
+ "input": {
9
+ "encoding": "application/json",
10
+ "schema": {
11
+ "type": "object",
12
+ "required": ["collection", "rkey", "record"],
13
+ "properties": {
14
+ "collection": { "type": "string" },
15
+ "rkey": { "type": "string" },
16
+ "record": { "type": "unknown" },
17
+ "repo": { "type": "string", "format": "did" }
18
+ }
19
+ }
20
+ },
21
+ "output": {
22
+ "encoding": "application/json",
23
+ "schema": {
24
+ "type": "object",
25
+ "properties": {
26
+ "uri": { "type": "string", "format": "at-uri" },
27
+ "cid": { "type": "string", "format": "cid" },
28
+ "commit": {
29
+ "type": "object",
30
+ "properties": {
31
+ "cid": { "type": "string", "format": "cid" },
32
+ "rev": { "type": "string" }
33
+ }
34
+ },
35
+ "validationStatus": { "type": "string" }
36
+ }
37
+ }
38
+ }
39
+ }
40
+ }
41
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "lexicon": 1,
3
+ "id": "dev.hatk.searchRecords",
4
+ "defs": {
5
+ "main": {
6
+ "type": "query",
7
+ "description": "Full-text search across a collection.",
8
+ "parameters": {
9
+ "type": "params",
10
+ "required": ["collection", "q"],
11
+ "properties": {
12
+ "collection": { "type": "string" },
13
+ "q": { "type": "string", "description": "Search query" },
14
+ "limit": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 },
15
+ "cursor": { "type": "string" },
16
+ "fuzzy": { "type": "boolean", "default": true }
17
+ }
18
+ },
19
+ "output": {
20
+ "encoding": "application/json",
21
+ "schema": {
22
+ "type": "object",
23
+ "required": ["items"],
24
+ "properties": {
25
+ "items": { "type": "array", "items": { "type": "unknown" } },
26
+ "cursor": { "type": "string" }
27
+ }
28
+ }
29
+ }
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "lexicon": 1,
3
+ "id": "dev.hatk.uploadBlob",
4
+ "defs": {
5
+ "main": {
6
+ "type": "procedure",
7
+ "description": "Upload a blob via the user's PDS.",
8
+ "input": {
9
+ "encoding": "*/*"
10
+ },
11
+ "output": {
12
+ "encoding": "application/json",
13
+ "schema": {
14
+ "type": "object",
15
+ "required": ["blob"],
16
+ "properties": {
17
+ "blob": { "type": "blob" }
18
+ }
19
+ }
20
+ }
21
+ }
22
+ }
23
+ }
package/dist/logger.d.ts CHANGED
@@ -1,4 +1,33 @@
1
+ /**
2
+ * Unstructured debug log — use sparingly for human-readable dev output.
3
+ * Prefer {@link emit} for anything that should be queryable in production.
4
+ * Disabled when `DEBUG=0`.
5
+ */
1
6
  export declare function log(...args: unknown[]): void;
7
+ /**
8
+ * Emit a structured wide event as a single JSON line to stdout.
9
+ *
10
+ * Each call produces one canonical log line with a timestamp, module, operation,
11
+ * and arbitrary key-value fields — designed for columnar search and aggregation,
12
+ * not string grep. Pack as much context as possible into `fields` (request IDs,
13
+ * durations, status codes, user DIDs, counts) so a single event tells the full
14
+ * story. See https://loggingsucks.com for the philosophy behind this approach.
15
+ *
16
+ * Disabled when `DEBUG=0`.
17
+ *
18
+ * @param module - Subsystem emitting the event (e.g. "server", "indexer", "backfill")
19
+ * @param op - Operation name (e.g. "request", "commit", "memory")
20
+ * @param fields - High-cardinality key-value context — include everything relevant
21
+ */
2
22
  export declare function emit(module: string, op: string, fields: Record<string, unknown>): void;
23
+ /**
24
+ * Start a millisecond timer. Call the returned function to get elapsed ms.
25
+ * Use with {@link emit} to add `duration_ms` to wide events.
26
+ *
27
+ * @example
28
+ * const elapsed = timer()
29
+ * await doWork()
30
+ * emit('server', 'request', { path, status_code, duration_ms: elapsed() })
31
+ */
3
32
  export declare function timer(): () => number;
4
33
  //# sourceMappingURL=logger.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,wBAAgB,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAG5C;AAED,wBAAgB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAWtF;AAED,wBAAgB,KAAK,IAAI,MAAM,MAAM,CAGpC"}
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAG5C;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAWtF;AAED;;;;;;;;GAQG;AACH,wBAAgB,KAAK,IAAI,MAAM,MAAM,CAGpC"}
package/dist/logger.js CHANGED
@@ -1,8 +1,28 @@
1
+ /**
2
+ * Unstructured debug log — use sparingly for human-readable dev output.
3
+ * Prefer {@link emit} for anything that should be queryable in production.
4
+ * Disabled when `DEBUG=0`.
5
+ */
1
6
  export function log(...args) {
2
7
  if (process.env.DEBUG === '0')
3
8
  return;
4
9
  console.log(...args);
5
10
  }
11
+ /**
12
+ * Emit a structured wide event as a single JSON line to stdout.
13
+ *
14
+ * Each call produces one canonical log line with a timestamp, module, operation,
15
+ * and arbitrary key-value fields — designed for columnar search and aggregation,
16
+ * not string grep. Pack as much context as possible into `fields` (request IDs,
17
+ * durations, status codes, user DIDs, counts) so a single event tells the full
18
+ * story. See https://loggingsucks.com for the philosophy behind this approach.
19
+ *
20
+ * Disabled when `DEBUG=0`.
21
+ *
22
+ * @param module - Subsystem emitting the event (e.g. "server", "indexer", "backfill")
23
+ * @param op - Operation name (e.g. "request", "commit", "memory")
24
+ * @param fields - High-cardinality key-value context — include everything relevant
25
+ */
6
26
  export function emit(module, op, fields) {
7
27
  if (process.env.DEBUG === '0')
8
28
  return;
@@ -17,6 +37,15 @@ export function emit(module, op, fields) {
17
37
  }
18
38
  process.stdout.write(JSON.stringify(entry) + '\n');
19
39
  }
40
+ /**
41
+ * Start a millisecond timer. Call the returned function to get elapsed ms.
42
+ * Use with {@link emit} to add `duration_ms` to wide events.
43
+ *
44
+ * @example
45
+ * const elapsed = timer()
46
+ * await doWork()
47
+ * emit('server', 'request', { path, status_code, duration_ms: elapsed() })
48
+ */
20
49
  export function timer() {
21
50
  const start = performance.now();
22
51
  return () => Math.round(performance.now() - start);
package/dist/main.js CHANGED
@@ -1,29 +1,50 @@
1
1
  #!/usr/bin/env node
2
- import { mkdirSync } from 'node:fs';
2
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
3
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
4
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
5
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
6
+ });
7
+ }
8
+ return path;
9
+ };
10
+ import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
3
11
  import { dirname, resolve } from 'node:path';
12
+ import { registerHatkResolveHook } from "./resolve-hatk.js";
4
13
  import { log } from "./logger.js";
5
14
  import { loadConfig } from "./config.js";
6
- import { loadLexicons, storeLexicons, discoverCollections, generateTableSchema, generateCreateTableSQL, } from "./schema.js";
15
+ import { loadLexicons, storeLexicons, discoverCollections, buildSchemas } from "./database/schema.js";
7
16
  import { discoverViews } from "./views.js";
8
- import { initDatabase, getCursor, querySQL, backfillChildTables } from "./db.js";
17
+ import { initDatabase, getCursor, querySQL, getSqlDialect, getSchemaDump, migrateSchema } from "./database/db.js";
18
+ import { createAdapter } from "./database/adapter-factory.js";
19
+ import { getDialect } from "./database/dialect.js";
20
+ import { setSearchPort } from "./database/fts.js";
9
21
  import { initFeeds, listFeeds } from "./feeds.js";
10
- import { initXrpc, listXrpc, configureRelay } from "./xrpc.js";
22
+ import { initXrpc, listXrpc, configureRelay, configureCdn, configureOAuth, callXrpc } from "./xrpc.js";
11
23
  import { initOpengraph } from "./opengraph.js";
12
24
  import { initLabels, getLabelDefinitions } from "./labels.js";
13
- import { startIndexer } from "./indexer.js";
14
- import { rebuildAllIndexes } from "./fts.js";
15
- import { startServer } from "./server.js";
25
+ import { auxCursorKey, startAuxIndexer, startIndexer } from "./indexer.js";
26
+ import { startJetstreamIndexer } from "./jetstream.js";
27
+ import { rebuildAllIndexes } from "./database/fts.js";
28
+ import { createHandler, registerCoreHandlers } from "./server.js";
29
+ import { setPrivateCollections } from "./private-collections.js";
30
+ import { serve } from "./adapter.js";
16
31
  import { validateLexicons } from '@bigmoves/lexicon';
17
32
  import { relayHttpUrl } from "./config.js";
18
- import { runBackfill } from "./backfill.js";
33
+ import { runBackfill, configurePlc } from "./backfill.js";
19
34
  import { initOAuth } from "./oauth/server.js";
20
- import { loadOnLoginHook } from "./oauth/hooks.js";
35
+ import { parseSessionCookie, getSessionCookieName } from "./oauth/session.js";
36
+ import { loadOnLoginHook } from "./hooks.js";
37
+ import { enabledPushTransports, initPush, isPushEnabled } from "./push.js";
21
38
  import { initSetup } from "./setup.js";
22
- const configPath = process.argv[2] || 'config.yaml';
39
+ import { initServer } from "./server-init.js";
40
+ const configPath = process.argv[2] || 'hatk.config.ts';
23
41
  const configDir = dirname(resolve(configPath));
42
+ registerHatkResolveHook();
24
43
  // 1. Load config
25
- const config = loadConfig(configPath);
44
+ const config = await loadConfig(configPath);
26
45
  configureRelay(config.relay);
46
+ configurePlc(config.plc);
47
+ configureCdn(config.cdn);
27
48
  // 2. Load lexicons, validate schemas, and discover collections
28
49
  const lexicons = loadLexicons(resolve(configDir, 'lexicons'));
29
50
  const lexiconErrors = validateLexicons([...lexicons.values()]);
@@ -44,44 +65,66 @@ if (collections.length === 0) {
44
65
  log(`[main] Loaded config: ${collections.length} collections`);
45
66
  // Discover view defs from lexicons
46
67
  discoverViews();
47
- await loadOnLoginHook(resolve(configDir, 'hooks'));
48
- const schemas = [];
49
- const ddlStatements = [];
50
- for (const nsid of collections) {
51
- const lexicon = lexicons.get(nsid);
52
- if (!lexicon) {
53
- log(`[main] No lexicon found for ${nsid}, using generic JSON storage`);
54
- const genericDDL = `CREATE TABLE IF NOT EXISTS "${nsid}" (
55
- uri TEXT PRIMARY KEY,
56
- cid TEXT,
57
- did TEXT NOT NULL,
58
- indexed_at TIMESTAMP NOT NULL,
59
- data JSON
60
- );
61
- CREATE INDEX IF NOT EXISTS idx_${nsid.replace(/\./g, '_')}_indexed ON "${nsid}"(indexed_at DESC);
62
- CREATE INDEX IF NOT EXISTS idx_${nsid.replace(/\./g, '_')}_author ON "${nsid}"(did);`;
63
- schemas.push({ collection: nsid, tableName: `"${nsid}"`, columns: [], refColumns: [], children: [], unions: [] });
64
- ddlStatements.push(genericDDL);
65
- continue;
68
+ const engineDialect = getDialect(config.databaseEngine);
69
+ const { schemas, ddlStatements } = buildSchemas(lexicons, collections, engineDialect);
70
+ for (const s of schemas) {
71
+ if (s.columns.length === 0) {
72
+ log(`[main] No lexicon found for ${s.collection}, using generic JSON storage`);
73
+ }
74
+ else {
75
+ log(`[main] Schema for ${s.collection}: ${s.columns.length} columns, ${s.unions.length} unions`);
66
76
  }
67
- const schema = generateTableSchema(nsid, lexicon, lexicons);
68
- schemas.push(schema);
69
- ddlStatements.push(generateCreateTableSQL(schema));
70
- log(`[main] Schema for ${nsid}: ${schema.columns.length} columns, ${schema.unions.length} unions`);
71
77
  }
72
- // 3. Ensure data directory exists and initialize DuckDB
78
+ // 3. Ensure data directory exists and initialize database
73
79
  if (config.database !== ':memory:') {
74
80
  mkdirSync(dirname(config.database), { recursive: true });
75
81
  }
76
- await initDatabase(config.database, schemas, ddlStatements);
77
- log(`[main] DuckDB initialized (${config.database === ':memory:' ? 'in-memory' : config.database})`);
78
- // 3a. Backfill child tables for decomposed arrays (one-time migration)
79
- await backfillChildTables();
80
- // 3b. Run setup hooks (after DB init, before server)
81
- await initSetup(resolve(configDir, 'setup'));
82
+ const { adapter, searchPort } = await createAdapter(config.databaseEngine);
83
+ setSearchPort(searchPort);
84
+ await initDatabase(adapter, config.database, schemas, ddlStatements);
85
+ log(`[main] Database initialized (${config.databaseEngine}, ${config.database === ':memory:' ? 'in-memory' : config.database})`);
86
+ // Auto-migrate schema if lexicons changed
87
+ const migrationChanges = await migrateSchema(schemas);
88
+ if (migrationChanges.length > 0) {
89
+ log(`[main] Applied ${migrationChanges.length} schema migration(s)`);
90
+ }
91
+ // 3b. Run setup hooks, feeds, xrpc, og, labels
92
+ const serverDir = resolve(configDir, 'server');
93
+ if (existsSync(serverDir)) {
94
+ // New: single server/ directory
95
+ await initServer(serverDir);
96
+ }
97
+ else {
98
+ // Legacy: separate directories
99
+ await initSetup(resolve(configDir, 'setup'));
100
+ await loadOnLoginHook(resolve(configDir, 'hooks'));
101
+ await initFeeds(resolve(configDir, 'feeds'));
102
+ log(`[main] Feeds initialized: ${listFeeds()
103
+ .map((f) => f.name)
104
+ .join(', ') || 'none'}`);
105
+ await initXrpc(resolve(configDir, 'xrpc'));
106
+ log(`[main] XRPC handlers initialized: ${listXrpc().join(', ') || 'none'}`);
107
+ await initOpengraph(resolve(configDir, 'og'));
108
+ log(`[main] OpenGraph initialized`);
109
+ await initLabels(resolve(configDir, 'labels'));
110
+ log(`[main] Labels initialized: ${getLabelDefinitions().length} definitions`);
111
+ }
112
+ // Register built-in dev.hatk.* handlers so callXrpc() can find them
113
+ setPrivateCollections(config.privateCollections);
114
+ registerCoreHandlers(collections, config.oauth);
115
+ configureOAuth(config.oauth);
116
+ // Write db/schema.sql (after setup, so setup-created tables are included)
117
+ try {
118
+ const schemaDir = resolve(configDir, 'db');
119
+ mkdirSync(schemaDir, { recursive: true });
120
+ const schemaDump = await getSchemaDump();
121
+ writeFileSync(resolve(schemaDir, 'schema.sql'), `-- This file is auto-generated by hatk on startup. Do not edit.\n-- Database engine: ${config.databaseEngine}\n\n${schemaDump}\n`);
122
+ log(`[main] Schema written to db/schema.sql`);
123
+ }
124
+ catch { }
82
125
  // Detect orphaned tables
83
126
  try {
84
- const existingTables = await querySQL(`SELECT table_name FROM information_schema.tables WHERE table_schema = 'main' AND table_name NOT LIKE '\\_%' ESCAPE '\\'`);
127
+ const existingTables = (await querySQL(getSqlDialect().listTablesQuery));
85
128
  for (const row of existingTables) {
86
129
  const tableName = row.table_name;
87
130
  const isChildTable = collections.some((c) => tableName.startsWith(c + '__'));
@@ -91,24 +134,65 @@ try {
91
134
  }
92
135
  }
93
136
  catch { }
94
- // 4. Initialize feeds, xrpc handlers, og, labels from directories
95
- await initFeeds(resolve(configDir, 'feeds'));
96
- log(`[main] Feeds initialized: ${listFeeds()
97
- .map((f) => f.name)
98
- .join(', ') || 'none'}`);
99
- await initXrpc(resolve(configDir, 'xrpc'));
100
- log(`[main] XRPC handlers initialized: ${listXrpc().join(', ') || 'none'}`);
101
- await initOpengraph(resolve(configDir, 'og'));
102
- log(`[main] OpenGraph initialized`);
103
- await initLabels(resolve(configDir, 'labels'));
104
- log(`[main] Labels initialized: ${getLabelDefinitions().length} definitions`);
105
137
  if (config.oauth) {
106
138
  await initOAuth(config.oauth, config.plc, config.relay);
107
139
  log(`[main] OAuth initialized (issuer: ${config.oauth.issuer})`);
108
140
  }
141
+ if (config.push) {
142
+ initPush(config.push, configDir);
143
+ if (isPushEnabled()) {
144
+ log(`[main] Push initialized (${enabledPushTransports().join(', ')})`);
145
+ }
146
+ else {
147
+ log(`[main] Push configured but no usable credential — push disabled`);
148
+ }
149
+ }
109
150
  // 5. Start server immediately (don't wait for backfill)
110
151
  const collectionSet = new Set(collections);
111
- startServer(config.port, collections, config.publicDir, config.oauth, config.admins);
152
+ const backfillOpts = {
153
+ pdsUrl: relayHttpUrl(config.relay),
154
+ extraPdsUrls: config.relays.map(relayHttpUrl),
155
+ plcUrl: config.plc,
156
+ collections: collectionSet,
157
+ config: config.backfill,
158
+ };
159
+ function runBackfillAndRestart() {
160
+ runBackfill(backfillOpts)
161
+ .then(async (recordCount) => {
162
+ log('[main] Backfill complete, building FTS indexes...');
163
+ await rebuildAllIndexes(collections);
164
+ log('[main] FTS indexes ready');
165
+ return recordCount;
166
+ })
167
+ .then((recordCount) => {
168
+ if (recordCount > 0 && !process.env.DEV_MODE) {
169
+ log('[main] Restarting to reclaim memory...');
170
+ process.exit(1);
171
+ }
172
+ })
173
+ .catch((err) => {
174
+ console.error('[main] Backfill error:', err.message);
175
+ });
176
+ }
177
+ const handler = createHandler({
178
+ collections,
179
+ publicDir: config.publicDir,
180
+ oauth: config.oauth,
181
+ admins: config.admins,
182
+ onResync: runBackfillAndRestart,
183
+ });
184
+ globalThis.__hatk_callXrpc = callXrpc;
185
+ globalThis.__hatk_parseSessionCookie = parseSessionCookie;
186
+ globalThis.__hatk_sessionCookieName = getSessionCookieName();
187
+ // Detect SvelteKit build output and use it as fallback handler
188
+ let fallback = undefined;
189
+ const sveltekitHandler = resolve(configDir, 'build', 'handler.js');
190
+ if (existsSync(sveltekitHandler)) {
191
+ const sk = await import(__rewriteRelativeImportExtension(/* @vite-ignore */ sveltekitHandler));
192
+ fallback = sk.handler;
193
+ log(`[main] SvelteKit handler loaded from build/handler.js`);
194
+ }
195
+ serve(handler, config.port, undefined, fallback);
112
196
  log(`\nhatk running:`);
113
197
  log(` Relay: ${config.relay}`);
114
198
  log(` Database: ${config.database}`);
@@ -118,31 +202,42 @@ log(` Feeds: ${listFeeds()
118
202
  .map((f) => f.name)
119
203
  .join(', ')}`);
120
204
  // 6. Start indexer with cursor
121
- const cursor = await getCursor('relay');
122
- startIndexer({
123
- relayUrl: config.relay,
205
+ // HATK_IGNORE_SAVED_CURSOR=1 boots from the live firehose instead of the saved
206
+ // cursor — the escape hatch when a stale cursor would make the relay replay its
207
+ // retention window at line rate (see checkpointCursor in indexer.ts). Unset it
208
+ // after one boot so later restarts resume normally.
209
+ const ignoreSavedCursor = Boolean(process.env.HATK_IGNORE_SAVED_CURSOR);
210
+ if (ignoreSavedCursor)
211
+ log('[main] HATK_IGNORE_SAVED_CURSOR set — starting indexer from live');
212
+ // Each source keeps its own cursor row: relay seqs and Jetstream seqs are
213
+ // different coordinate systems, so switching sources must not resume one from
214
+ // the other's value.
215
+ const indexerCore = {
216
+ plcUrl: config.plc,
124
217
  collections: collectionSet,
125
218
  signalCollections: config.backfill.signalCollections ? new Set(config.backfill.signalCollections) : undefined,
126
219
  pinnedRepos: config.backfill.repos ? new Set(config.backfill.repos) : undefined,
127
- cursor,
128
220
  fetchTimeout: config.backfill.fetchTimeout,
129
221
  maxRetries: config.backfill.maxRetries,
222
+ parallelism: config.backfill.parallelism,
130
223
  ftsRebuildInterval: config.ftsRebuildInterval,
131
- });
224
+ };
225
+ if (config.jetstream) {
226
+ const cursor = ignoreSavedCursor ? null : await getCursor('jetstream');
227
+ startJetstreamIndexer({ ...indexerCore, jetstreamUrl: config.jetstream.url, cursor });
228
+ }
229
+ else {
230
+ const cursor = ignoreSavedCursor ? null : await getCursor('relay');
231
+ startIndexer({ ...indexerCore, relayUrl: config.relay, cursor });
232
+ for (const relayUrl of config.relays) {
233
+ const auxCursor = ignoreSavedCursor ? null : await getCursor(auxCursorKey(relayUrl));
234
+ startAuxIndexer({ relayUrl, collections: collectionSet, cursor: auxCursor });
235
+ }
236
+ }
132
237
  // 7. Run backfill in background
133
- runBackfill({
134
- pdsUrl: relayHttpUrl(config.relay),
135
- plcUrl: config.plc,
136
- collections: collectionSet,
137
- config: config.backfill,
138
- })
139
- .then(() => {
140
- log('[main] Backfill complete, rebuilding FTS indexes...');
141
- return rebuildAllIndexes(collections);
142
- })
143
- .then(() => {
144
- log('[main] FTS indexes ready');
145
- })
146
- .catch((err) => {
147
- console.error('[main] Backfill error:', err.message);
238
+ runBackfillAndRestart();
239
+ // Graceful shutdown
240
+ process.on('SIGTERM', () => {
241
+ log('[main] Received SIGTERM, shutting down...');
242
+ process.exit(0);
148
243
  });
package/dist/mst.d.ts CHANGED
@@ -1,6 +1,23 @@
1
+ /** A single entry from a Merkle Search Tree — a record path paired with its content CID. */
1
2
  export interface MstEntry {
3
+ /** Record path, e.g. "xyz.marketplace.listing/3mfniulnr7c2g" */
2
4
  path: string;
5
+ /** CID of the record's CBOR block */
3
6
  cid: string;
4
7
  }
5
- export declare function walkMst(blocks: Map<string, Uint8Array>, rootCid: string): MstEntry[];
8
+ /**
9
+ * Walk an AT Protocol Merkle Search Tree (MST) in key order, yielding every record entry.
10
+ *
11
+ * The MST is a prefix-compressed B+ tree used by AT Protocol repositories to map
12
+ * record paths to CIDs. Each node contains a left subtree pointer, an array of entries
13
+ * (each with a prefix length, key suffix, value CID, and right subtree pointer), and
14
+ * keys are reconstructed by combining the prefix of the previous key with the suffix.
15
+ *
16
+ * @param blocks - Block store that resolves CIDs to raw CBOR bytes
17
+ * @param rootCid - CID of the MST root node
18
+ * @yields {MstEntry} Record entries in lexicographic key order
19
+ */
20
+ export declare function walkMst(blocks: {
21
+ get(cid: string): Uint8Array | undefined;
22
+ }, rootCid: string): Generator<MstEntry>;
6
23
  //# sourceMappingURL=mst.d.ts.map
package/dist/mst.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mst.d.ts","sourceRoot":"","sources":["../src/mst.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAA;IACZ,GAAG,EAAE,MAAM,CAAA;CACZ;AAED,wBAAgB,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,EAAE,OAAO,EAAE,MAAM,GAAG,QAAQ,EAAE,CAiCpF"}
1
+ {"version":3,"file":"mst.d.ts","sourceRoot":"","sources":["../src/mst.ts"],"names":[],"mappings":"AAEA,4FAA4F;AAC5F,MAAM,WAAW,QAAQ;IACvB,gEAAgE;IAChE,IAAI,EAAE,MAAM,CAAA;IACZ,qCAAqC;IACrC,GAAG,EAAE,MAAM,CAAA;CACZ;AAED;;;;;;;;;;;GAWG;AACH,wBAAiB,OAAO,CAAC,MAAM,EAAE;IAAE,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAAA;CAAE,EAAE,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,CA+BnH"}
package/dist/mst.js CHANGED
@@ -1,14 +1,26 @@
1
1
  import { cborDecode } from "./cbor.js";
2
- export function walkMst(blocks, rootCid) {
3
- const entries = [];
4
- function visit(cid, prefix) {
2
+ /**
3
+ * Walk an AT Protocol Merkle Search Tree (MST) in key order, yielding every record entry.
4
+ *
5
+ * The MST is a prefix-compressed B+ tree used by AT Protocol repositories to map
6
+ * record paths to CIDs. Each node contains a left subtree pointer, an array of entries
7
+ * (each with a prefix length, key suffix, value CID, and right subtree pointer), and
8
+ * keys are reconstructed by combining the prefix of the previous key with the suffix.
9
+ *
10
+ * @param blocks - Block store that resolves CIDs to raw CBOR bytes
11
+ * @param rootCid - CID of the MST root node
12
+ * @yields {MstEntry} Record entries in lexicographic key order
13
+ */
14
+ export function* walkMst(blocks, rootCid) {
15
+ /** Recursively visit an MST node, reconstructing full keys from prefix-compressed entries. */
16
+ function* visit(cid, prefix) {
5
17
  const data = blocks.get(cid);
6
18
  if (!data)
7
19
  return prefix;
8
20
  const { value: node } = cborDecode(data);
9
21
  // Visit left subtree
10
22
  if (node.l?.$link)
11
- visit(node.l.$link, prefix);
23
+ yield* visit(node.l.$link, prefix);
12
24
  let lastKey = prefix;
13
25
  for (const entry of node.e || []) {
14
26
  const keySuffix = entry.k instanceof Uint8Array ? new TextDecoder().decode(entry.k) : entry.k;
@@ -16,15 +28,14 @@ export function walkMst(blocks, rootCid) {
16
28
  const fullKey = lastKey.substring(0, prefixLen) + keySuffix;
17
29
  lastKey = fullKey;
18
30
  if (entry.v?.$link) {
19
- entries.push({ path: fullKey, cid: entry.v.$link });
31
+ yield { path: fullKey, cid: entry.v.$link };
20
32
  }
21
33
  // Visit right subtree
22
34
  if (entry.t?.$link) {
23
- visit(entry.t.$link, lastKey);
35
+ yield* visit(entry.t.$link, lastKey);
24
36
  }
25
37
  }
26
38
  return lastKey;
27
39
  }
28
- visit(rootCid, '');
29
- return entries;
40
+ yield* visit(rootCid, '');
30
41
  }