@apibara/indexer 2.0.0-beta.9 → 2.1.0-beta.2

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 (127) hide show
  1. package/dist/index.cjs +271 -39
  2. package/dist/index.d.cts +1 -16
  3. package/dist/index.d.mts +1 -16
  4. package/dist/index.d.ts +1 -16
  5. package/dist/index.mjs +262 -25
  6. package/dist/internal/index.cjs +10 -0
  7. package/dist/internal/index.d.cts +3 -0
  8. package/dist/internal/index.d.mts +3 -0
  9. package/dist/internal/index.d.ts +3 -0
  10. package/dist/internal/index.mjs +8 -0
  11. package/dist/internal/plugins.cjs +38 -0
  12. package/dist/internal/plugins.d.cts +13 -0
  13. package/dist/internal/plugins.d.mts +13 -0
  14. package/dist/internal/plugins.d.ts +13 -0
  15. package/dist/internal/plugins.mjs +34 -0
  16. package/dist/internal/testing.cjs +118 -0
  17. package/dist/internal/testing.d.cts +42 -0
  18. package/dist/internal/testing.d.mts +42 -0
  19. package/dist/internal/testing.d.ts +42 -0
  20. package/dist/internal/testing.mjs +113 -0
  21. package/dist/plugins/index.cjs +39 -3
  22. package/dist/plugins/index.d.cts +16 -2
  23. package/dist/plugins/index.d.mts +16 -2
  24. package/dist/plugins/index.d.ts +16 -2
  25. package/dist/plugins/index.mjs +36 -3
  26. package/dist/shared/indexer.077335f3.cjs +15 -0
  27. package/dist/shared/indexer.2416906c.cjs +29 -0
  28. package/dist/shared/indexer.601ceab0.cjs +7 -0
  29. package/dist/shared/indexer.9b21ddd2.mjs +5 -0
  30. package/dist/shared/indexer.a55ad619.mjs +12 -0
  31. package/dist/shared/indexer.fedcd831.d.cts +100 -0
  32. package/dist/shared/indexer.fedcd831.d.mts +100 -0
  33. package/dist/shared/indexer.fedcd831.d.ts +100 -0
  34. package/dist/shared/indexer.ff25c953.mjs +26 -0
  35. package/dist/testing/index.cjs +52 -50
  36. package/dist/testing/index.d.cts +8 -36
  37. package/dist/testing/index.d.mts +8 -36
  38. package/dist/testing/index.d.ts +8 -36
  39. package/dist/testing/index.mjs +47 -47
  40. package/dist/vcr/index.cjs +84 -17
  41. package/dist/vcr/index.d.cts +16 -7
  42. package/dist/vcr/index.d.mts +16 -7
  43. package/dist/vcr/index.d.ts +16 -7
  44. package/dist/vcr/index.mjs +75 -11
  45. package/package.json +22 -42
  46. package/src/compose.test.ts +76 -0
  47. package/src/compose.ts +71 -0
  48. package/src/context.ts +14 -8
  49. package/src/index.ts +0 -5
  50. package/src/indexer.test.ts +125 -186
  51. package/src/indexer.ts +278 -151
  52. package/src/internal/index.ts +6 -0
  53. package/src/internal/plugins.ts +1 -0
  54. package/src/internal/testing.ts +148 -0
  55. package/src/plugins/config.ts +4 -4
  56. package/src/plugins/context.ts +40 -0
  57. package/src/plugins/index.ts +8 -1
  58. package/src/plugins/logger.ts +30 -0
  59. package/src/plugins/persistence.ts +24 -187
  60. package/src/testing/index.ts +58 -3
  61. package/src/vcr/record.ts +5 -3
  62. package/src/vcr/replay.ts +8 -18
  63. package/dist/plugins/kv.cjs +0 -131
  64. package/dist/plugins/kv.d.cts +0 -32
  65. package/dist/plugins/kv.d.mts +0 -32
  66. package/dist/plugins/kv.d.ts +0 -32
  67. package/dist/plugins/kv.mjs +0 -124
  68. package/dist/plugins/persistence.cjs +0 -182
  69. package/dist/plugins/persistence.d.cts +0 -50
  70. package/dist/plugins/persistence.d.mts +0 -50
  71. package/dist/plugins/persistence.d.ts +0 -50
  72. package/dist/plugins/persistence.mjs +0 -179
  73. package/dist/shared/indexer.2c23c9cd.mjs +0 -35
  74. package/dist/shared/indexer.318d3617.cjs +0 -47
  75. package/dist/shared/indexer.36530330.mjs +0 -249
  76. package/dist/shared/indexer.500fd281.d.cts +0 -23
  77. package/dist/shared/indexer.541d43eb.cjs +0 -266
  78. package/dist/shared/indexer.93d6b2eb.mjs +0 -17
  79. package/dist/shared/indexer.a8b7ab1f.cjs +0 -25
  80. package/dist/shared/indexer.b9c8f0d8.d.cts +0 -19
  81. package/dist/shared/indexer.b9c8f0d8.d.mts +0 -19
  82. package/dist/shared/indexer.b9c8f0d8.d.ts +0 -19
  83. package/dist/shared/indexer.c7ed6b83.d.cts +0 -82
  84. package/dist/shared/indexer.e1856641.d.mts +0 -23
  85. package/dist/shared/indexer.e4f2430f.d.ts +0 -23
  86. package/dist/shared/indexer.e8bd138d.d.mts +0 -82
  87. package/dist/shared/indexer.f761abcd.d.ts +0 -82
  88. package/dist/sinks/csv.cjs +0 -85
  89. package/dist/sinks/csv.d.cts +0 -66
  90. package/dist/sinks/csv.d.mts +0 -66
  91. package/dist/sinks/csv.d.ts +0 -66
  92. package/dist/sinks/csv.mjs +0 -78
  93. package/dist/sinks/drizzle/index.cjs +0 -212
  94. package/dist/sinks/drizzle/index.d.cts +0 -153
  95. package/dist/sinks/drizzle/index.d.mts +0 -153
  96. package/dist/sinks/drizzle/index.d.ts +0 -153
  97. package/dist/sinks/drizzle/index.mjs +0 -198
  98. package/dist/sinks/sqlite.cjs +0 -90
  99. package/dist/sinks/sqlite.d.cts +0 -71
  100. package/dist/sinks/sqlite.d.mts +0 -71
  101. package/dist/sinks/sqlite.d.ts +0 -71
  102. package/dist/sinks/sqlite.mjs +0 -87
  103. package/src/hooks/index.ts +0 -2
  104. package/src/hooks/useKVStore.ts +0 -12
  105. package/src/hooks/useSink.ts +0 -13
  106. package/src/plugins/kv.test.ts +0 -120
  107. package/src/plugins/kv.ts +0 -132
  108. package/src/plugins/persistence.test.ts +0 -151
  109. package/src/sink.ts +0 -36
  110. package/src/sinks/csv.test.ts +0 -65
  111. package/src/sinks/csv.ts +0 -159
  112. package/src/sinks/drizzle/Int8Range.ts +0 -52
  113. package/src/sinks/drizzle/delete.ts +0 -42
  114. package/src/sinks/drizzle/drizzle.test.ts +0 -239
  115. package/src/sinks/drizzle/drizzle.ts +0 -115
  116. package/src/sinks/drizzle/index.ts +0 -6
  117. package/src/sinks/drizzle/insert.ts +0 -42
  118. package/src/sinks/drizzle/select.ts +0 -44
  119. package/src/sinks/drizzle/transaction.ts +0 -49
  120. package/src/sinks/drizzle/update.ts +0 -47
  121. package/src/sinks/drizzle/utils.ts +0 -99
  122. package/src/sinks/sqlite.test.ts +0 -99
  123. package/src/sinks/sqlite.ts +0 -170
  124. package/src/testing/helper.ts +0 -13
  125. package/src/testing/indexer.ts +0 -35
  126. package/src/testing/setup.ts +0 -59
  127. package/src/testing/vcr.ts +0 -54
@@ -1,151 +0,0 @@
1
- import type { Cursor } from "@apibara/protocol";
2
- import {
3
- type MockBlock,
4
- MockClient,
5
- type MockFilter,
6
- } from "@apibara/protocol/testing";
7
- import Database from "better-sqlite3";
8
- import { klona } from "klona/full";
9
- import { describe, expect, it } from "vitest";
10
- import { run } from "../indexer";
11
- import { generateMockMessages } from "../testing";
12
- import { getMockIndexer } from "../testing/indexer";
13
- import { SqlitePersistence, sqlitePersistence } from "./persistence";
14
-
15
- describe("Persistence", () => {
16
- const initDB = () => {
17
- const db = new Database(":memory:");
18
- SqlitePersistence.initialize(db);
19
- return db;
20
- };
21
-
22
- it("should handle storing and updating a cursor & filter", () => {
23
- const db = initDB();
24
- const store = new SqlitePersistence<MockFilter>(db);
25
-
26
- // Assert there's no data
27
- let latest = store.get();
28
-
29
- expect(latest.cursor).toBeUndefined();
30
- expect(latest.filter).toBeUndefined();
31
-
32
- // Insert value
33
- const cursor: Cursor = {
34
- orderKey: 5_000_000n,
35
- };
36
- const filter: MockFilter = {
37
- filter: "X",
38
- };
39
- store.put({ cursor, filter });
40
-
41
- // Check that value was stored
42
- latest = store.get();
43
-
44
- expect(latest.cursor).toEqual({
45
- orderKey: 5_000_000n,
46
- uniqueKey: null,
47
- });
48
- expect(latest.filter).toEqual({
49
- filter: "X",
50
- });
51
-
52
- // Update value
53
- const updatedCursor: Cursor = {
54
- orderKey: 5_000_010n,
55
- uniqueKey: "0x1234567890",
56
- };
57
- const updatedFilter: MockFilter = {
58
- filter: "Y",
59
- };
60
-
61
- store.put({ cursor: updatedCursor, filter: updatedFilter });
62
-
63
- // Check that value was updated
64
- latest = store.get();
65
-
66
- expect(latest.cursor).toEqual({
67
- orderKey: 5_000_010n,
68
- uniqueKey: "0x1234567890",
69
- });
70
- expect(latest.filter).toEqual({
71
- filter: "Y",
72
- });
73
-
74
- db.close();
75
- });
76
-
77
- it("should handle storing and deleting a cursor & filter", () => {
78
- const db = initDB();
79
- const store = new SqlitePersistence(db);
80
-
81
- // Assert there's no data
82
- let latest = store.get();
83
- expect(latest.cursor).toBeUndefined();
84
- expect(latest.filter).toBeUndefined();
85
-
86
- // Insert value
87
- const cursor: Cursor = {
88
- orderKey: 5_000_000n,
89
- };
90
- const filter: MockFilter = {
91
- filter: "X",
92
- };
93
- store.put({ cursor, filter });
94
-
95
- // Check that value was stored
96
- latest = store.get();
97
- expect(latest.cursor).toEqual({
98
- orderKey: 5_000_000n,
99
- uniqueKey: null,
100
- });
101
- expect(latest.filter).toEqual({
102
- filter: "X",
103
- });
104
-
105
- // Delete value
106
- store.del();
107
-
108
- // Check there's no data
109
- latest = store.get();
110
- expect(latest.cursor).toBeUndefined();
111
- expect(latest.filter).toBeUndefined();
112
-
113
- db.close();
114
- });
115
-
116
- it("should work with indexer and store cursor of last message", async () => {
117
- const client = new MockClient<MockFilter, MockBlock>((request, options) => {
118
- return messages;
119
- });
120
-
121
- const db = new Database(":memory:");
122
-
123
- // create mock indexer with persistence plugin
124
- const indexer = klona(
125
- getMockIndexer({
126
- plugins: [
127
- sqlitePersistence({
128
- database: db,
129
- }),
130
- ],
131
- }),
132
- );
133
-
134
- await run(client, indexer);
135
-
136
- const store = new SqlitePersistence<MockFilter>(db);
137
-
138
- const latest = store.get();
139
-
140
- expect(latest.cursor).toMatchInlineSnapshot(`
141
- {
142
- "orderKey": 5000009n,
143
- "uniqueKey": null,
144
- }
145
- `);
146
-
147
- db.close();
148
- });
149
- });
150
-
151
- const messages = generateMockMessages();
package/src/sink.ts DELETED
@@ -1,36 +0,0 @@
1
- import type { Cursor, DataFinality } from "@apibara/protocol";
2
- import consola from "consola";
3
-
4
- export type SinkData = Record<string, unknown>;
5
-
6
- export type SinkCursorParams = {
7
- cursor?: Cursor;
8
- endCursor?: Cursor;
9
- finality: DataFinality;
10
- };
11
-
12
- export abstract class Sink<TTxnParams = unknown> {
13
- abstract transaction(
14
- { cursor, endCursor, finality }: SinkCursorParams,
15
- cb: (params: TTxnParams) => Promise<void>,
16
- ): Promise<void>;
17
-
18
- abstract invalidate(cursor?: Cursor): Promise<void>;
19
- }
20
-
21
- export class DefaultSink extends Sink<unknown> {
22
- async transaction(
23
- { cursor, endCursor, finality }: SinkCursorParams,
24
- cb: (params: unknown) => Promise<void>,
25
- ): Promise<void> {
26
- await cb({});
27
- }
28
-
29
- async invalidate(cursor?: Cursor) {
30
- consola.info(`Invalidating cursor ${cursor?.orderKey}`);
31
- }
32
- }
33
-
34
- export function defaultSink() {
35
- return new DefaultSink();
36
- }
@@ -1,65 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import {
3
- type MockBlock,
4
- MockClient,
5
- type MockFilter,
6
- } from "@apibara/protocol/testing";
7
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
8
- import { useSink } from "../hooks";
9
- import { run } from "../indexer";
10
- import {} from "../plugins/persistence";
11
- import { generateMockMessages } from "../testing";
12
- import { getMockIndexer } from "../testing/indexer";
13
- import { csv } from "./csv";
14
-
15
- describe("Run Test", () => {
16
- async function cleanup() {
17
- try {
18
- await fs.unlink("test.csv");
19
- } catch {}
20
- }
21
-
22
- beforeEach(async () => {
23
- await cleanup();
24
- });
25
-
26
- afterEach(async () => {
27
- await cleanup();
28
- });
29
-
30
- it("should store in csv file via csv sink", async () => {
31
- const client = new MockClient<MockFilter, MockBlock>((request, options) => {
32
- return generateMockMessages();
33
- });
34
-
35
- const sink = csv({ filepath: "test.csv" });
36
- await run(
37
- client,
38
- getMockIndexer({
39
- sink,
40
- override: {
41
- transform: async ({ context, endCursor, block: { data } }) => {
42
- const { writer } = useSink({ context });
43
- writer.insert([{ data }]);
44
- },
45
- },
46
- }),
47
- );
48
-
49
- const csvData = await fs.readFile("test.csv", "utf-8");
50
-
51
- expect(csvData).toMatchInlineSnapshot(`
52
- "5000000,5000000
53
- 5000001,5000001
54
- 5000002,5000002
55
- 5000003,5000003
56
- 5000004,5000004
57
- 5000005,5000005
58
- 5000006,5000006
59
- 5000007,5000007
60
- 5000008,5000008
61
- 5000009,5000009
62
- "
63
- `);
64
- });
65
- });
package/src/sinks/csv.ts DELETED
@@ -1,159 +0,0 @@
1
- import fs from "node:fs";
2
- import type { Cursor } from "@apibara/protocol";
3
- import { type Options, type Stringifier, stringify } from "csv-stringify";
4
- import { Sink, type SinkCursorParams, type SinkData } from "../sink";
5
-
6
- export type CsvArgs = {
7
- /**
8
- * csv-stringy options
9
- * @reference https://csv.js.org/stringify/options/
10
- */
11
- csvOptions?: Options;
12
- /**
13
- * filepath for your csv file
14
- */
15
- filepath: string;
16
- };
17
-
18
- export type CsvSinkOptions = {
19
- /**
20
- * An optional column name used to store the cursor value. If specified,
21
- * the value of this column must match the `endCursor.orderKey` for each row.
22
- */
23
- cursorColumn?: string;
24
- };
25
-
26
- type TxnContext = {
27
- buffer: SinkData[];
28
- };
29
-
30
- type TxnParams = {
31
- writer: {
32
- insert: (data: SinkData[]) => void;
33
- };
34
- };
35
-
36
- const transactionHelper = (context: TxnContext) => {
37
- return {
38
- insert: (data: SinkData[]) => {
39
- context.buffer.push(...data);
40
- },
41
- };
42
- };
43
-
44
- /**
45
- * A sink that writes data to a CSV file.
46
- *
47
- * @example
48
- *
49
- * ```ts
50
- * const sink = csv({
51
- * filepath: "./data.csv",
52
- * csvOptions: {
53
- * header: true,
54
- * },
55
- * });
56
- *
57
- * ...
58
- * async transform({context, endCursor}){
59
- * const { writer } = useSink(context);
60
- * const insertHelper = writer(endCursor);
61
- *
62
- * insertHelper.insert([
63
- * { id: 1, name: "John" },
64
- * { id: 2, name: "Jane" },
65
- * ]);
66
- * }
67
- *
68
- * ```
69
- */
70
- export class CsvSink extends Sink {
71
- constructor(
72
- private _stringifier: Stringifier,
73
- private _config: CsvSinkOptions,
74
- ) {
75
- super();
76
- }
77
-
78
- private async write({
79
- data,
80
- endCursor,
81
- }: { data: SinkData[]; endCursor?: Cursor }) {
82
- // adds a "_cursor" property if "cursorColumn" is not specified by user
83
- data = this.processCursorColumn(data, endCursor);
84
- // Insert the data into csv
85
- await this.insertToCSV(data);
86
- }
87
-
88
- async transaction(
89
- { cursor, endCursor, finality }: SinkCursorParams,
90
- cb: (params: TxnParams) => Promise<void>,
91
- ) {
92
- const context: TxnContext = {
93
- buffer: [],
94
- };
95
-
96
- const writer = transactionHelper(context);
97
-
98
- await cb({ writer });
99
- await this.write({ data: context.buffer, endCursor });
100
- }
101
-
102
- async invalidate(cursor?: Cursor) {
103
- // TODO: Implement
104
- throw new Error("Not implemented");
105
- }
106
-
107
- private async insertToCSV(data: SinkData[]) {
108
- if (data.length === 0) return;
109
-
110
- return await new Promise<void>((resolve, reject) => {
111
- for (const row of data) {
112
- this._stringifier.write(row, (err) => {
113
- if (err) throw new Error(err.message);
114
-
115
- // resolve when all rows are inserted into csv
116
- if (row === data[data.length - 1]) {
117
- resolve();
118
- }
119
- });
120
- }
121
- });
122
- }
123
-
124
- private processCursorColumn(
125
- data: SinkData[],
126
- endCursor?: Cursor,
127
- ): SinkData[] {
128
- const { cursorColumn } = this._config;
129
-
130
- if (
131
- cursorColumn &&
132
- data.some(
133
- (row) => Number(row[cursorColumn]) !== Number(endCursor?.orderKey),
134
- )
135
- ) {
136
- throw new Error(
137
- `Mismatch of ${cursorColumn} and Cursor ${Number(endCursor?.orderKey)}`,
138
- );
139
- }
140
-
141
- if (cursorColumn) {
142
- return data;
143
- }
144
-
145
- return data.map((row) => ({
146
- ...row,
147
- _cursor: Number(endCursor?.orderKey),
148
- }));
149
- }
150
- }
151
-
152
- export const csv = (args: CsvArgs & CsvSinkOptions) => {
153
- const { csvOptions, filepath, ...sinkOptions } = args;
154
- const stringifier = stringify({ ...csvOptions });
155
-
156
- const writeStream = fs.createWriteStream(filepath, { flags: "a" });
157
- stringifier.pipe(writeStream);
158
- return new CsvSink(stringifier, sinkOptions);
159
- };
@@ -1,52 +0,0 @@
1
- import { customType } from "drizzle-orm/pg-core";
2
- import type { Range } from "postgres-range";
3
- import {
4
- parse as rangeParse,
5
- serialize as rangeSerialize,
6
- } from "postgres-range";
7
-
8
- type Comparable = string | number;
9
-
10
- type RangeBound<T extends Comparable> =
11
- | T
12
- | {
13
- value: T;
14
- inclusive: boolean;
15
- };
16
-
17
- export class Int8Range {
18
- constructor(public readonly range: Range<number>) {}
19
-
20
- get start(): RangeBound<number> | null {
21
- return this.range.lower != null
22
- ? {
23
- value: this.range.lower,
24
- inclusive: this.range.isLowerBoundClosed(),
25
- }
26
- : null;
27
- }
28
-
29
- get end(): RangeBound<number> | null {
30
- return this.range.upper != null
31
- ? {
32
- value: this.range.upper,
33
- inclusive: this.range.isUpperBoundClosed(),
34
- }
35
- : null;
36
- }
37
- }
38
-
39
- export const int8range = customType<{
40
- data: Int8Range;
41
- }>({
42
- dataType: () => "int8range",
43
- fromDriver: (value: unknown): Int8Range => {
44
- if (typeof value !== "string") {
45
- throw new Error("Expected string");
46
- }
47
-
48
- const parsed = rangeParse(value, (val) => Number.parseInt(val, 10));
49
- return new Int8Range(parsed);
50
- },
51
- toDriver: (value: Int8Range): string => rangeSerialize(value.range),
52
- });
@@ -1,42 +0,0 @@
1
- import type { Cursor } from "@apibara/protocol";
2
- import {
3
- type ExtractTablesWithRelations,
4
- type SQL,
5
- type TablesRelationalConfig,
6
- sql,
7
- } from "drizzle-orm";
8
- import type {
9
- PgQueryResultHKT,
10
- PgTable,
11
- PgTransaction,
12
- PgUpdateBase,
13
- } from "drizzle-orm/pg-core";
14
-
15
- export class DrizzleSinkDelete<
16
- TTable extends PgTable,
17
- TQueryResult extends PgQueryResultHKT,
18
- TFullSchema extends Record<string, unknown> = Record<string, never>,
19
- TSchema extends
20
- TablesRelationalConfig = ExtractTablesWithRelations<TFullSchema>,
21
- > {
22
- constructor(
23
- private db: PgTransaction<TQueryResult, TFullSchema, TSchema>,
24
- private table: TTable,
25
- private endCursor?: Cursor,
26
- ) {}
27
-
28
- //@ts-ignore
29
- where(where: SQL): Omit<
30
- // for type safety used PgUpdateBase instead of PgDeleteBase
31
- PgUpdateBase<TTable, TQueryResult, undefined, false, "where">,
32
- "where"
33
- > {
34
- return this.db
35
- .update(this.table)
36
- .set({
37
- // @ts-ignore
38
- _cursor: sql`int8range(lower(_cursor), ${Number(this.endCursor?.orderKey!)}, '[)')`,
39
- })
40
- .where(where);
41
- }
42
- }