web-dc-api 0.0.87 → 0.0.89

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 (142) hide show
  1. package/dist/cjs/index.js +1 -0
  2. package/dist/cjs/protobuf-BVBdi7Hh.js +1 -0
  3. package/dist/dc.min.js +1 -19
  4. package/dist/esm/chunks/protobuf-CbxDm-Gy.js +1 -0
  5. package/dist/esm/index.js +1 -0
  6. package/dist/index.d.ts +947 -886
  7. package/package.json +14 -17
  8. package/dist/index.cjs.js +0 -19
  9. package/dist/index.esm.js +0 -19
  10. package/lib/common/blowfish/block.ts +0 -259
  11. package/lib/common/blowfish/cipher.ts +0 -144
  12. package/lib/common/blowfish/const.ts +0 -195
  13. package/lib/common/chain.ts +0 -469
  14. package/lib/common/commonclient.ts +0 -202
  15. package/lib/common/constants.ts +0 -55
  16. package/lib/common/dc-key/ed25519.ts +0 -343
  17. package/lib/common/dc-key/keyManager.ts +0 -424
  18. package/lib/common/dcapi.ts +0 -98
  19. package/lib/common/dcutil.ts +0 -595
  20. package/lib/common/define.ts +0 -66
  21. package/lib/common/error.ts +0 -67
  22. package/lib/common/grpc-dc.ts +0 -104
  23. package/lib/common/module-system.ts +0 -184
  24. package/lib/common/service-worker.ts +0 -234
  25. package/lib/common/types/types.ts +0 -344
  26. package/lib/dc.ts +0 -694
  27. package/lib/implements/account/client.ts +0 -185
  28. package/lib/implements/account/manager.ts +0 -683
  29. package/lib/implements/aiproxy/client.ts +0 -357
  30. package/lib/implements/aiproxy/manager.ts +0 -670
  31. package/lib/implements/cache/client.ts +0 -105
  32. package/lib/implements/cache/manager.ts +0 -127
  33. package/lib/implements/comment/client.ts +0 -982
  34. package/lib/implements/comment/manager.ts +0 -1151
  35. package/lib/implements/dc/client.ts +0 -51
  36. package/lib/implements/dc/manager.ts +0 -33
  37. package/lib/implements/file/client.ts +0 -253
  38. package/lib/implements/file/file-cache-manager.ts +0 -142
  39. package/lib/implements/file/manager.ts +0 -1240
  40. package/lib/implements/file/seekableFileStream.ts +0 -344
  41. package/lib/implements/file/streamwriter.ts +0 -322
  42. package/lib/implements/keyvalue/client.ts +0 -376
  43. package/lib/implements/keyvalue/manager.ts +0 -759
  44. package/lib/implements/message/client.ts +0 -250
  45. package/lib/implements/message/manager.ts +0 -215
  46. package/lib/implements/threaddb/cbor/coding.ts +0 -62
  47. package/lib/implements/threaddb/cbor/event.ts +0 -336
  48. package/lib/implements/threaddb/cbor/node.ts +0 -542
  49. package/lib/implements/threaddb/cbor/record.ts +0 -398
  50. package/lib/implements/threaddb/common/AsyncMutex.ts +0 -24
  51. package/lib/implements/threaddb/common/addrinfo.ts +0 -135
  52. package/lib/implements/threaddb/common/dispatcher.ts +0 -81
  53. package/lib/implements/threaddb/common/idbstore-adapter.ts +0 -260
  54. package/lib/implements/threaddb/common/json-patcher.ts +0 -204
  55. package/lib/implements/threaddb/common/key.ts +0 -290
  56. package/lib/implements/threaddb/common/level-adapter.ts +0 -235
  57. package/lib/implements/threaddb/common/lineReader.ts +0 -79
  58. package/lib/implements/threaddb/common/logstore.ts +0 -215
  59. package/lib/implements/threaddb/common/transformed-datastore.ts +0 -308
  60. package/lib/implements/threaddb/core/app.ts +0 -202
  61. package/lib/implements/threaddb/core/core.ts +0 -230
  62. package/lib/implements/threaddb/core/db.ts +0 -249
  63. package/lib/implements/threaddb/core/event.ts +0 -54
  64. package/lib/implements/threaddb/core/head.ts +0 -89
  65. package/lib/implements/threaddb/core/identity.ts +0 -171
  66. package/lib/implements/threaddb/core/logstore.ts +0 -137
  67. package/lib/implements/threaddb/core/options.ts +0 -14
  68. package/lib/implements/threaddb/core/record.ts +0 -54
  69. package/lib/implements/threaddb/db/collection.ts +0 -1910
  70. package/lib/implements/threaddb/db/db.ts +0 -698
  71. package/lib/implements/threaddb/db/json2Query.ts +0 -192
  72. package/lib/implements/threaddb/db/query.ts +0 -524
  73. package/lib/implements/threaddb/dbclient.ts +0 -443
  74. package/lib/implements/threaddb/dbmanager.ts +0 -1901
  75. package/lib/implements/threaddb/lsstoreds/addr_book.ts +0 -452
  76. package/lib/implements/threaddb/lsstoreds/cache.ts +0 -36
  77. package/lib/implements/threaddb/lsstoreds/cyclic_batch.ts +0 -87
  78. package/lib/implements/threaddb/lsstoreds/global.ts +0 -151
  79. package/lib/implements/threaddb/lsstoreds/headbook.ts +0 -280
  80. package/lib/implements/threaddb/lsstoreds/keybook.ts +0 -297
  81. package/lib/implements/threaddb/lsstoreds/logstore.ts +0 -29
  82. package/lib/implements/threaddb/lsstoreds/metadata.ts +0 -223
  83. package/lib/implements/threaddb/net/define.ts +0 -138
  84. package/lib/implements/threaddb/net/grpcClient.ts +0 -582
  85. package/lib/implements/threaddb/net/grpcserver.ts +0 -146
  86. package/lib/implements/threaddb/net/net.ts +0 -2006
  87. package/lib/implements/threaddb/pb/lstore.proto +0 -38
  88. package/lib/implements/threaddb/pb/lstore.ts +0 -393
  89. package/lib/implements/threaddb/pb/lstore_pb.d.ts +0 -433
  90. package/lib/implements/threaddb/pb/lstore_pb.js +0 -1085
  91. package/lib/implements/threaddb/pb/net.proto +0 -194
  92. package/lib/implements/threaddb/pb/net_pb.d.ts +0 -2349
  93. package/lib/implements/threaddb/pb/net_pb.js +0 -5525
  94. package/lib/implements/threaddb/pb/proto-custom-types.ts +0 -212
  95. package/lib/implements/util/client.ts +0 -72
  96. package/lib/implements/util/manager.ts +0 -146
  97. package/lib/implements/wallet/manager.ts +0 -664
  98. package/lib/index.ts +0 -57
  99. package/lib/interfaces/DCContext.ts +0 -51
  100. package/lib/interfaces/aiproxy-interface.ts +0 -145
  101. package/lib/interfaces/auth-interface.ts +0 -118
  102. package/lib/interfaces/cache-interface.ts +0 -22
  103. package/lib/interfaces/client-interface.ts +0 -11
  104. package/lib/interfaces/comment-interface.ts +0 -167
  105. package/lib/interfaces/database-interface.ts +0 -169
  106. package/lib/interfaces/file-interface.ts +0 -120
  107. package/lib/interfaces/index.ts +0 -10
  108. package/lib/interfaces/keyvalue-interface.ts +0 -156
  109. package/lib/interfaces/message-interface.ts +0 -22
  110. package/lib/interfaces/util-interface.ts +0 -31
  111. package/lib/modules/aiproxy-module.ts +0 -246
  112. package/lib/modules/auth-module.ts +0 -753
  113. package/lib/modules/cache-module.ts +0 -99
  114. package/lib/modules/client-module.ts +0 -71
  115. package/lib/modules/comment-module.ts +0 -429
  116. package/lib/modules/database-module.ts +0 -598
  117. package/lib/modules/file-module.ts +0 -291
  118. package/lib/modules/index.ts +0 -13
  119. package/lib/modules/keyvalue-module.ts +0 -379
  120. package/lib/modules/message-module.ts +0 -107
  121. package/lib/modules/util-module.ts +0 -148
  122. package/lib/polyfills/process-env-browser.ts +0 -1
  123. package/lib/proto/datasource.ts +0 -93
  124. package/lib/proto/dcnet.proto +0 -1601
  125. package/lib/proto/dcnet_proto.d.ts +0 -22857
  126. package/lib/proto/dcnet_proto.js +0 -55204
  127. package/lib/proto/dcnet_proto_sparse.js +0 -55166
  128. package/lib/proto/oidfetch.proto +0 -25
  129. package/lib/proto/oidfetch_proto.d.ts +0 -585
  130. package/lib/proto/oidfetch_proto.js +0 -1247
  131. package/lib/serverless/babel-browser.ts +0 -39
  132. package/lib/serverless/base_entity.ts +0 -78
  133. package/lib/serverless/base_repository.ts +0 -414
  134. package/lib/serverless/browser_schema_extractor.ts +0 -283
  135. package/lib/serverless/decorator_factory.ts +0 -322
  136. package/lib/util/BrowserLineReader.ts +0 -73
  137. package/lib/util/base64.ts +0 -105
  138. package/lib/util/bcrypt.ts +0 -206
  139. package/lib/util/curve25519Encryption.ts +0 -418
  140. package/lib/util/dccrypt.ts +0 -73
  141. package/lib/util/logger.ts +0 -104
  142. package/lib/util/utils.ts +0 -289
@@ -1,202 +0,0 @@
1
- // app.ts
2
- import EventEmitter from 'eventemitter3';
3
- import { ThreadID } from '@textile/threads-id'
4
- import { IThreadRecord } from './record'
5
- import { Key as ThreadKey } from '../common/key';
6
- import { IThreadLogInfo, SymKey, ThreadInfo } from './core';
7
- import { ThreadToken } from './identity';
8
- import { Ed25519PubKey } from '../../../common/dc-key/ed25519';
9
- import { INet as net_Net } from './core'
10
- import { Context } from './core'
11
- import { IPLDNode } from './core';
12
- import { PeerId } from '@libp2p/interface';
13
- import { Head } from './head';
14
- import {net as net_pb} from "../pb/net_pb";
15
- import { DBClient } from '../dbclient';
16
- import { Blocks } from 'helia';
17
- import { AsyncMutex } from '../common/AsyncMutex';
18
-
19
-
20
- // 类型定义
21
- export type PubKey = Ed25519PubKey
22
- export type Token = Uint8Array
23
-
24
- // 错误定义
25
- export const ErrThreadInUse = new Error('thread is in use')
26
- export const ErrInvalidNetRecordBody = new Error('app denied net record body')
27
-
28
- // 核心接口
29
- export interface App {
30
- validateNetRecordBody( body: IPLDNode, identity: PubKey): Promise<Error | undefined>
31
- handleNetRecord( rec: IThreadRecord, key?: ThreadKey): Promise<Error | undefined>
32
- getNetRecordCreateTime(rec: IThreadRecord, key?: ThreadKey): Promise<BigInt>
33
- }
34
-
35
- // 本地事件总线实现
36
- export class LocalEventsBus {
37
- private bus = new EventEmitter()
38
- private static readonly busTimeout = 15000 // 15秒
39
-
40
- send(event: LocalEvent): Promise<void> {
41
- return new Promise((resolve, reject) => {
42
- const timeout = setTimeout(() =>
43
- reject(new Error('Event send timeout')), LocalEventsBus.busTimeout
44
- )
45
-
46
- this.bus.emit('event', event, () => {
47
- clearTimeout(timeout)
48
- resolve()
49
- })
50
- })
51
- }
52
-
53
- listen(): LocalEventListener {
54
- return new LocalEventListener(this.bus)
55
- }
56
-
57
- discard() {
58
- this.bus.removeAllListeners()
59
- }
60
- }
61
-
62
- export class LocalEventListener {
63
- private handler: (event: LocalEvent) => void
64
-
65
- constructor(private bus: EventEmitter) {
66
- this.handler = (event: LocalEvent) => this.onEvent(event)
67
- bus.on('event', this.handler)
68
- }
69
-
70
- private onEvent(event: LocalEvent) {
71
- // 处理事件
72
- }
73
-
74
- discard() {
75
- this.bus.off('event', this.handler)
76
- }
77
- }
78
-
79
- export interface LocalEvent {
80
- node: IPLDNode
81
- token: ThreadToken
82
- }
83
-
84
- // 网络接口
85
- export interface Net extends net_Net {
86
- bstore: Blocks;
87
- connectApp(app: App, threadId: ThreadID): Promise<Connector>
88
-
89
- createRecord(
90
- threadId: ThreadID,
91
- body: IPLDNode,
92
- options?: { threadToken?: ThreadToken, apiToken?: Token }
93
- ): Promise<IThreadRecord>
94
-
95
- validate(
96
- id: ThreadID,
97
- token?: ThreadToken
98
- ): Promise<Ed25519PubKey |undefined>
99
- exchange(id: ThreadID): Promise<void>
100
- threadOffsets(tid: ThreadID): Promise<[Record<string, Head>, PeerId[]]>
101
- buildGetRecordsRequest(
102
- tid: ThreadID,
103
- offsets: Record<string,Head>,
104
- limit: number
105
- ): Promise<{ req: net_pb.pb.IGetRecordsRequest, serviceKey: SymKey }>
106
- updateRecordsFromPeer(tid: ThreadID,peerId: PeerId|null,client?:DBClient): Promise<void>
107
- getMutexForThread(threadId: string): AsyncMutex
108
- preLoadLogs(tid: ThreadID, logs: net_pb.pb.Log[]): Promise<void>
109
- createExternalLogsIfNotExist(tid: ThreadID, logs: IThreadLogInfo[]): Promise<void>
110
- createExternalLogsIfNotExistForPreload(tid: ThreadID, logs: IThreadLogInfo[]): Promise<void>
111
- }
112
-
113
- // 连接器实现
114
- export class Connector {
115
- public readonly token: Token
116
-
117
- constructor(
118
- public net: Net,
119
- private app: App,
120
- private threadInfo: ThreadInfo
121
- ) {
122
- if (!threadInfo.key?.canRead()) {
123
- throw new Error(`Read key not found for thread ${threadInfo.id}`)
124
- }
125
- this.token = this.generateRandomBytes(32)
126
- }
127
-
128
- get threadId(): ThreadID {
129
- return this.threadInfo.id
130
- }
131
-
132
- get threadKey(): ThreadKey|undefined {
133
- return this.threadInfo.key
134
- }
135
-
136
-
137
- // 调用 net.createRecord 并提供线程 ID 和 API 令牌
138
- async createNetRecord(
139
- body: IPLDNode,
140
- token?: ThreadToken
141
- ): Promise<IThreadRecord> {
142
- return this.net.createRecord(
143
- this.threadId,
144
- body,
145
- {
146
- ...(token !== undefined ? { threadToken: token } : {}),
147
- apiToken: this.token
148
- }
149
- );
150
- }
151
-
152
- // 验证线程令牌
153
- async validate(
154
- token?: ThreadToken
155
- ): Promise<Error | undefined> {
156
- try{
157
- await this.net.validate( this.threadId, token);
158
- return
159
- }catch(err:any){
160
- return err
161
- }
162
- }
163
-
164
- // 调用连接应用的 ValidateNetRecordBody
165
- async validateNetRecordBody(
166
- body: IPLDNode,
167
- identity: PubKey
168
- ): Promise<Error|undefined> {
169
- return this.app.validateNetRecordBody( body, identity);
170
- }
171
-
172
- // 调用连接应用的 HandleNetRecord 并提供线程密钥
173
- async handleNetRecord(
174
- rec: IThreadRecord
175
- ): Promise<Error | undefined> {
176
- return this.app.handleNetRecord( rec, this.threadKey);
177
- }
178
-
179
- // 调用连接应用的 GetNetRecordCreateTime 解析记录创建时间
180
- async getNetRecordCreateTime(
181
- rec: IThreadRecord
182
- ): Promise<BigInt> {
183
- return this.app.getNetRecordCreateTime(rec, this.threadKey);
184
- }
185
-
186
- private generateRandomBytes(size: number): Uint8Array {
187
- return crypto.getRandomValues(new Uint8Array(size))
188
- }
189
- }
190
-
191
- // 工具函数
192
- export function NewConnector(
193
- app: App,
194
- net: Net,
195
- threadInfo: ThreadInfo
196
- ): [Connector | null, Error | null] {
197
- try {
198
- return [new Connector(net, app, threadInfo), null]
199
- } catch (err) {
200
- return [null, err as Error]
201
- }
202
- }
@@ -1,230 +0,0 @@
1
-
2
-
3
- import { Key,Datastore,Query,Batch } from 'interface-datastore';
4
- import { Key as ThreadKey } from '../common/key';
5
- import { ThreadID } from '@textile/threads-id';
6
- import type { PeerId,PublicKey,PrivateKey } from "@libp2p/interface";
7
- import { Multiaddr as TMultiaddr } from '@multiformats/multiaddr';
8
- import { Head } from './head';
9
- import { type AnySchema, type JSONSchemaType } from "ajv";
10
- import { dcnet } from "../../../proto/dcnet_proto";
11
- import { EventCodec } from "./db";
12
- import type { CID } from 'multiformats/cid'
13
- import { Link } from 'multiformats/link'
14
- import { DAGCBOR} from '@helia/dag-cbor'
15
- import { ThreadToken } from './identity';
16
- import { Ed25519PrivKey, Ed25519PubKey } from '../../../common/dc-key/ed25519';
17
- import {net as net_pb} from "../pb/net_pb";
18
- import { Protocol } from '../net/define';
19
-
20
-
21
-
22
- // 上下文接口
23
- export interface Context {
24
- signal?: AbortSignal | undefined
25
- deadline?: Date | undefined
26
- }
27
-
28
- export interface IPLDNode {
29
- cid(): CID
30
- links(): Link[]
31
- size(): number
32
- data(): Uint8Array
33
- }
34
-
35
-
36
- export interface IBlock {
37
- data(): Uint8Array;
38
- cid(): CID;
39
- }
40
-
41
-
42
- // 接口定义
43
- export interface INet {
44
- createThread( id: ThreadID, options: { token: ThreadToken; logKey?: Ed25519PrivKey|Ed25519PubKey, threadKey?: ThreadKey }): Promise<ThreadInfo>;
45
- addThread(addr: ThreadMuliaddr,options: { token?: ThreadToken | undefined; logKey?: Ed25519PrivKey | Ed25519PubKey | undefined; threadKey?: ThreadKey | undefined } ): Promise<ThreadInfo>;
46
- getThread( id: ThreadID, ...opts: any[]): Promise<ThreadInfo>;
47
- getThreadFromPeer( id: ThreadID, peer: PeerId, options: { token?: ThreadToken }): Promise<ThreadInfo>;
48
- deleteThread( id: ThreadID, ...opts: any[]): Promise<void>;
49
- pullThread( id: ThreadID,timeout: number, options: { token?: ThreadToken | undefined; multiPeersFlag?: boolean | undefined;} ): Promise<void>;
50
- getPbLogs( id: ThreadID): Promise<[net_pb.pb.ILog[], IThreadInfo]>;
51
- }
52
-
53
-
54
-
55
- export interface ICollectionConfig {
56
- name: string;
57
- schema: AnySchema;
58
- indexes?: Index[];
59
- writeValidator?: string;
60
- readFilter?: string;
61
- }
62
-
63
- export interface Index {
64
- path: string;
65
- unique: boolean;
66
- }
67
-
68
- export interface DBInfo {
69
- name: string;
70
- addrs: string[];
71
- key: Uint8Array;
72
- }
73
-
74
-
75
-
76
-
77
- export class NewOptions {
78
- name?: string | undefined;
79
- collections?: ICollectionConfig[] | undefined;
80
- eventCodec?: EventCodec | undefined;
81
- debug?: boolean | undefined;
82
- key?: ThreadKey | undefined;
83
- logKey?: Ed25519PrivKey | Ed25519PubKey | undefined;
84
- block?: boolean | undefined;
85
- token?: ThreadToken | undefined;
86
-
87
- constructor(init?: Partial<NewOptions>) {
88
- Object.assign(this, init);
89
- }
90
- }
91
-
92
- export type Token = Uint8Array;
93
-
94
- class TokenUtil {
95
- // 判断两个 Token 是否相等
96
- static equal(t: Token, b: Token): boolean {
97
- if (t.length !== b.length) {
98
- return false;
99
- }
100
- for (let i = 0; i < t.length; i++) {
101
- if (t[i] !== b[i]) {
102
- return false;
103
- }
104
- }
105
- return true;
106
- }
107
- }
108
-
109
- export interface ManagedOptions {
110
- name: string;
111
- key: ThreadKey;
112
- logKey: Ed25519PrivKey | Ed25519PubKey;
113
- token?: ThreadToken;
114
- collections: ICollectionConfig[];
115
- block: boolean;
116
- }
117
-
118
-
119
- // ======== 事务接口 ========
120
-
121
-
122
- // ======== 键转换接口 ========
123
-
124
-
125
- export interface AbortOptions {
126
- signal?: AbortSignal
127
- }
128
-
129
-
130
-
131
-
132
-
133
-
134
-
135
- // 定义对称密钥类型
136
- export interface SymKey {
137
- key: CryptoKey;
138
- raw: Uint8Array;
139
- }
140
-
141
-
142
- export class ThreadMuliaddr{
143
- addr: TMultiaddr
144
- id: ThreadID
145
- constructor(addr: TMultiaddr, id: ThreadID) {
146
- this.id = id
147
- this.addr = addr
148
- }
149
- getMultiaddrString(): string {
150
- const addr = this.addr.toString()
151
- const id = this.id.toString()
152
- const addrStr = addr + '/' + Protocol.name + '/' + id
153
- return addrStr
154
- }
155
- }
156
-
157
- // 定义 Thread Info 的接口
158
- export interface IThreadInfo {
159
- id: ThreadID;
160
- key: ThreadKey | undefined;
161
- logs: IThreadLogInfo[];
162
- addrs: ThreadMuliaddr[];
163
- getFirstPrivKeyLog() :IThreadLogInfo | undefined
164
- }
165
-
166
- export interface IDBInfo {
167
- id: string;
168
- name: string;
169
- addrs: string[];
170
- key: string | undefined;
171
- }
172
-
173
- export class ThreadInfo implements IThreadInfo {
174
- public id: ThreadID;
175
- public logs: IThreadLogInfo[];
176
- public addrs: ThreadMuliaddr[];
177
- public key: ThreadKey | undefined;
178
- constructor(
179
- id: ThreadID,
180
- logs: IThreadLogInfo[],
181
- addrs: ThreadMuliaddr[] ,
182
- key?: ThreadKey,
183
- ) {
184
- this.id = id;
185
- this.logs = logs;
186
- this.addrs = addrs;
187
- if (key) {
188
- this.key = key;
189
- }else {
190
- this.key = undefined;
191
- }
192
-
193
- }
194
-
195
-
196
- public getFirstPrivKeyLog() :IThreadLogInfo | undefined {
197
- for (const lg of this.logs) {
198
- if (lg.privKey) {
199
- return lg
200
- }
201
- }
202
- return
203
- }
204
-
205
- }
206
-
207
- export interface IThreadLogInfo {
208
- // id is the log's identifier.
209
- id: PeerId;
210
- // privKey is the log's private key.
211
- privKey?: PrivateKey;
212
- // pubKey is the log's public key.
213
- pubKey?: PublicKey;
214
- // Addrs are the addresses associated with the given log.
215
- addrs: TMultiaddr[];
216
- // Managed logs are any logs directly added/created by the host, and/or logs for which we have the private key
217
- managed: boolean;
218
- // Head is the log's current head.
219
- head?: Head;
220
- }
221
-
222
- // 定义 Store 接口
223
- export interface Store {
224
- addThread(info: IThreadInfo): Promise<void>;
225
- addLog(id: ThreadID, logInfo: IThreadLogInfo): Promise<void>;
226
- putBytes(id: ThreadID, identity: string, bytes: Uint8Array): Promise<void>;
227
- }
228
-
229
-
230
-
@@ -1,249 +0,0 @@
1
- import { ulid } from 'ulid';
2
- import { Key, Query,Batch, Datastore } from 'interface-datastore';
3
-
4
- import { IPLDNode } from './core';
5
- import {ThreadToken} from './identity';
6
- import { Ed25519PubKey as PubKey} from "../../../common/dc-key/ed25519";
7
- import { Connector,LocalEventsBus } from './app';
8
- import { Dispatcher } from '../common/dispatcher';
9
-
10
-
11
- export const Errors = {
12
- ErrDBNotFound: new Error('db not found'),
13
- ErrDBExists: new Error('db already exists'),
14
- ErrInvalidName: new Error('invalid name'),
15
- ErrThreadReadKeyRequired: new Error('thread read key required'),
16
- ErrorThreadIDValidation: new Error('thread id validation error'),
17
- ErrThreadNotFound: new Error('thread not found'),
18
- ErrLogNotFound: new Error('log not found'),
19
- ErrLogExists: new Error('log already exists'),
20
- ErrP2pNetworkNotInit: new Error('p2p network not initialized'),
21
- ErrNoDbManager: new Error('no db manager'),
22
- ErrNoDcPeerConnected: new Error('no dc peer connected'),
23
- ErrInvalidCollectionSchema: new Error("the collection schema _id property must be a string"),
24
- ErrCannotIndexIDField: new Error(`cannot create custom index `),
25
- ErrCollectionNotFound: new Error('collection not found'),
26
- ErrNodeAddrIsNull: new Error('node address is null'),
27
- ErrNoThreadOnDc: new Error('no thread on dc'),
28
- ErrNoDcNodeClient: new Error('no dc node client'),
29
- ErrFileNotFound: new Error('file not found'),
30
- };
31
-
32
- export const pullThreadBackgroundTimeout = 3600000; // 1 hour in milliseconds
33
- export const PullTimeout = 20000; // 20 seconds in milliseconds
34
-
35
- export const dsPrefix = new Key("/db");
36
- export const DBPrefix = {
37
- dsPrefix: dsPrefix,
38
- dsName: dsPrefix.child(new Key("name")),
39
- dsSchemas: dsPrefix.child(new Key("schema")),
40
- dsIndexes: dsPrefix.child(new Key("index")),
41
- dsValidators: dsPrefix.child(new Key("validator")),
42
- dsFilters: dsPrefix.child(new Key("filter")),
43
- dsVerno: dsPrefix.child(new Key("verno")),
44
- }
45
- export const idFieldName = "_id";
46
- export const modFieldName = "_mod";
47
-
48
-
49
-
50
-
51
-
52
- export type InstanceID = string;
53
- export const EmptyInstanceID: InstanceID = '';
54
-
55
- // NewInstanceID generates a new identity for an instance.
56
- export function NewInstanceID(): InstanceID {
57
- const id = ulid();
58
- return id.toLowerCase();
59
- }
60
-
61
- // InstanceID string representation
62
- export function instanceIDToString(id: InstanceID): string {
63
- return id;
64
- }
65
-
66
-
67
- export enum CoreActionType {
68
- Create = 0,
69
- Save = 1,
70
- Delete = 2
71
- }
72
-
73
-
74
-
75
- /**
76
- * Transaction class for collections
77
- */
78
- export interface ITxn{
79
- /**
80
- * Create new instances
81
- */
82
- create(...newInstances: Uint8Array[]): Promise<InstanceID[]>;
83
- /**
84
- * Verify instance changes without saving them
85
- */
86
- verify(...updated: Uint8Array[]): Promise<void>;
87
- /**
88
- * Save instance changes
89
- */
90
- save(...updated: Uint8Array[]): Promise<void>;
91
- /**
92
- * Delete instances
93
- */
94
- delete(...ids: InstanceID[]): Promise<void>;
95
- /**
96
- * Check if instances exist
97
- */
98
- has(...ids: InstanceID[]): Promise<boolean>;
99
- /**
100
- * Find instance by ID
101
- */
102
- findByID(id: InstanceID): Promise<Object> ;
103
- /**
104
- * Find instances matching a query
105
- */
106
- find(q?: Query): Promise<Object[]>;
107
- /**
108
- * Get instances modified since a specific time
109
- *
110
- * The _mod field tracks modified instances, but not those that have been deleted, so we need
111
- * to query the dispatcher for all (unique) instances in this collection that have been modified
112
- * at all since `time`.
113
- */
114
- modifiedSince(time: number): Promise<InstanceID[]>;
115
- /**
116
- * Commit the transaction
117
- */
118
- commit(): Promise<void>;
119
-
120
- /**
121
- * Discard the transaction
122
- */
123
- discard(): void;
124
- /**
125
- * Refresh collection reference
126
- */
127
- refreshCollection(): void
128
- }
129
- export interface ICollection {
130
- baseKey(): Key ;
131
- getName(): string ;
132
- getSchema(): Uint8Array;
133
- getWriteValidator(): Uint8Array;
134
- getReadFilter(): Uint8Array;
135
- readTxn(fn: (txn: ITxn) => Promise<void> , token?: ThreadToken): Promise<void> ;
136
- writeTxn(fn: (txn: ITxn) => Promise<void> , token?: ThreadToken): Promise<void>
137
- findByID(id: InstanceID, token?: ThreadToken): Promise<Object> ;
138
- create(v: Uint8Array, token?: ThreadToken): Promise<InstanceID> ;
139
- createMany(vs: Uint8Array[], token?: ThreadToken): Promise<InstanceID[]> ;
140
- delete(id: InstanceID, token?: ThreadToken): Promise<void> ;
141
- deleteMany(ids: InstanceID[], token?: ThreadToken): Promise<void> ;
142
- save(v: Uint8Array, token?: ThreadToken): Promise<void> ;
143
- saveMany(vs: Uint8Array[], token?: ThreadToken): Promise<void> ;
144
- verify(v: Uint8Array, token?: ThreadToken): Promise<void>;
145
- verifyMany(vs: Uint8Array[], token?: ThreadToken): Promise<void> ;
146
- has(id: InstanceID, token?: ThreadToken): Promise<boolean>;
147
- hasMany(ids: InstanceID[], token?: ThreadToken): Promise<boolean> ;
148
- find(q: Query, token?: ThreadToken): Promise<Object[]>
149
- modifiedSince(time: number, token?: ThreadToken): Promise<InstanceID[]>;
150
- validInstance(v: Uint8Array): void;
151
- validWrite(identity: PubKey, e: Event): Promise<void>;
152
- filterRead(identity: PubKey, instance: Uint8Array): Promise<Uint8Array | null>;
153
- }
154
- export interface IDB {
155
- datastore: TxnDatastoreExtended;
156
- connector: Connector|null; //
157
- dispatcher: Dispatcher | null;
158
- eventcodec: EventCodec;
159
- localEventsBus: LocalEventsBus | null;
160
- collections: Map<string, ICollection> ;
161
- readTxn(collection: ICollection, fn: (txn: ITxn) => Promise<void> , token?: ThreadToken): Promise<void>;
162
- writeTxn(collection: ICollection, fn: (txn: ITxn) => Promise<void> , token?: ThreadToken): Promise<void>;
163
- notifyTxnEvents(node: IPLDNode, token?: ThreadToken): Promise<void>;
164
- }
165
-
166
-
167
- export interface Event<T = any> {
168
- /** 事件时间戳 (Unix纳秒时间戳) */
169
- readonly timestamp: BigInt;
170
- /** 关联的实例ID */
171
- readonly instanceID: InstanceID;
172
- /** 所属集合名称 */
173
- readonly collection: string;
174
- /** 事件负载数据 */
175
- readonly payload: T;
176
-
177
- /** 序列化为Uint8Array */
178
- marshal(): Promise<Uint8Array>;
179
- }
180
-
181
-
182
- export interface QueryResult {
183
- key: string;
184
- value: Uint8Array;
185
- size?: number;
186
- }
187
-
188
- export interface QueryExt extends Query {
189
- seekPrefix?: string;
190
- }
191
-
192
- export interface Transaction {
193
- put( key: Key, value: Uint8Array): Promise<Key>;
194
- delete( key: Key): Promise<void>;
195
- get( key: Key): Promise<Uint8Array|undefined>;
196
- has( key: Key): Promise<boolean>;
197
- commit(): Promise<void>;
198
- discard(): void;
199
- query( q: Query): AsyncIterable<QueryResult>;
200
- queryExtended( q: QueryExt): AsyncIterable<QueryResult>;
201
- }
202
-
203
-
204
- interface DatastoreExtensions {
205
- newTransactionExtended( readOnly: boolean): Promise<Transaction>
206
- queryExtended( q: QueryExt): AsyncIterable<QueryResult>
207
- }
208
-
209
- export interface TxnDatastoreExtended extends Datastore, DatastoreExtensions {
210
- batch(): Batch;
211
- newTransactionExtended( readOnly: boolean): Promise<Transaction>
212
- }
213
-
214
- export type IndexFunc = (
215
- collection: string,
216
- key: Key,
217
- txn: Transaction ,
218
- oldData?: Uint8Array,
219
- newData?: Uint8Array,
220
-
221
- ) => Promise<void>;
222
-
223
- export interface Action {
224
- type: CoreActionType;
225
- instanceID: InstanceID;
226
- collectionName: string;
227
- previous?: Uint8Array;
228
- current?: Uint8Array;
229
- }
230
-
231
- export interface ReduceAction {
232
- type: CoreActionType;
233
- collection: string;
234
- instanceID: InstanceID;
235
- }
236
- export interface EventCodec {
237
- reduce(
238
- events: Event[],
239
- store: TxnDatastoreExtended,
240
- baseKey: Key,
241
- indexFn: IndexFunc
242
- ): Promise<ReduceAction[]>;
243
-
244
- create(actions: Action[]): Promise<[Event[], IPLDNode ]>;
245
-
246
- eventsFromBytes(data: Uint8Array): Promise<Event[]> ;
247
-
248
- }
249
-