{"name":"hyperdb","version":"6.5.0","author":{"name":"Holepunch Inc"},"license":"Apache-2.0","_id":"hyperdb@6.5.0","maintainers":[{"name":"mafintosh","email":"mathiasbuus@gmail.com"},{"name":"andrewosh","email":"andrewosh@gmail.com"}],"homepage":"https://github.com/holepunchto/hyperdb","bugs":{"url":"https://github.com/holepunchto/hyperdb/issues"},"dist":{"shasum":"71e578040365c3aa74034a23b50d6663d9a8899c","tarball":"http://registry-npm.ywwl.com/hyperdb/download/hyperdb-6.5.0.tgz","fileCount":16,"integrity":"sha512-FQyj0QhWnDGQhjdWzeJJZvhLYcXIYn4duMRMxEdbd2iZWWFAUWKQW4Qg+Cx1si8xFLCD8OepDv+utG9ugw+Y8A==","signatures":[{"sig":"MEUCIQCe2ryZ46KQbRkQZSKMeF2ntJ9hbYlTI9snN3ZErrTCIwIgYPLqm6mJI8sruU9iApMtzovOFCB7NROqucKBWZnkto8=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":96177,"size":24759,"noattachment":false,"key":"/hyperdb/-/hyperdb-6.5.0.tgz"},"exports":{".":"./index.js","./builder":{"import":"./builder/index.mjs","default":"./builder/index.js"},"./package":"./package.json","./runtime":{"import":"./runtime.mjs","default":"./runtime.js"}},"gitHead":"a53ade444505986304aadfd133c14369ee396873","imports":{"fs":{"bare":"bare-fs","default":"fs"},"path":{"bare":"bare-path","default":"path"}},"scripts":{"lint":"prettier --check . && lunte","test":"brittle-node test/*.js","format":"prettier --write .","generate":"rm -rf test/fixtures/generated && node test/fixtures/generate.js"},"_npmUser":{"name":"mafintosh","email":"mathiasbuus@gmail.com"},"repository":{"url":"git+https://github.com/holepunchto/hyperdb.git","type":"git"},"_npmVersion":"11.12.1","description":"P2P Indexable Database","directories":{},"_nodeVersion":"24.13.0","dependencies":{"b4a":"^1.6.6","streamx":"^2.20.0","hyperbee":"^2.24.2","hypercore":"^11.26.0","refcounter":"^1.0.0","scope-lock":"^1.2.4","hyperschema":"^1.9.2","index-encoder":"^3.4.0","rocksdb-native":"^3.0.0","generate-string":"^1.0.1","compact-encoding":"^2.15.0","generate-object-property":"^2.0.0"},"_hasShrinkwrap":false,"devDependencies":{"lunte":"^1.3.0","brittle":"^3.7.0","prettier":"^3.6.2","test-tmp":"^1.2.1","corestore":"^7.8.0","hyperbee2":"^2.7.1","prettier-config-holepunch":"^2.0.0"},"_npmOperationalInternal":{"tmp":"tmp/hyperdb_6.5.0_1774903634327_0.07180848173050047","host":"s3://npm-registry-packages-npm-production"},"readme":"# hyperdb\n\nDatabase built for P2P and local indexing\n\n```\nnpm install hyperdb\n```\n\n## Usage\n\nFirst generate your definition with the builder.\nThe definition defines the schemas and collections you wanna use.\n\n```js\n// build.js\nconst Hyperschema = require('hyperschema')\nconst HyperDB = require('hyperdb/builder')\n\nconst SCHEMA_DIR = './spec/hyperschema' // where the schema definitions are written\nconst DB_DIR = './spec/hyperdb' // Where to install db definition\n\n// Hyperschema definitions\nconst schema = Hyperschema.from(SCHEMA_DIR)\nconst example = schema.namespace('example')\n\n// Define 'members'\nexample.register({\n  name: 'members',\n  compact: true,\n  fields: [\n    {\n      name: 'name',\n      type: 'string',\n      required: true\n    },\n    {\n      name: 'age',\n      type: 'uint',\n      required: true\n    }\n  ]\n})\nHyperschema.toDisk(schema)\n\n// Hyperdb collection definitions\nconst db = HyperDB.from(SCHEMA_DIR, DB_DIR)\nconst exampleDB = db.namespace('example')\n\n// Import helpers (see next step)\nexampleDB.require('./helpers.js')\n\n// Define collections of structs\nexampleDB.collections.register({\n  name: 'members',\n  schema: '@example/members',\n  key: ['name']\n})\n\n// Define index over collection\nexampleDB.indexes.register({\n  name: 'members-by-name',\n  collection: '@example/members',\n  unique: true,\n  key: {\n    type: 'string',\n    map: 'mapNameToLowerCase'\n  }\n})\n\nHyperDB.toDisk(db)\n```\n\nDefine helper functions in `helpers.js`:\n\n```js\n// helpers.js\nexports.mapNameToLowerCase = (record, context) => {\n  const name = record.name.toLowerCase().trim()\n  return name ? [name] : []\n}\n```\n\nRun `node build.js` to build the spec.\n\nThen boot your db. You can use the same definition for a fully local db and a P2P one.\n\n```js\n// run.mjs\nimport HyperDB from 'hyperdb'\nimport def from './spec/hyperdb/index.js'\n\n// first choose your engine\nconst db = HyperDB.rocks('./my-rocks.db', def)\n\n// Add some entries\nawait db.insert('@example/members', { name: 'maf', age: 37 })\nawait db.insert('@example/members', { name: 'sean', age: 36 })\nawait db.flush() // commit changes\n\n// Query collection\nconst maf = await db.get('@example/members', { name: 'maf' })\nconsole.log('maf', maf)\n```\n\nIt is that simple.\n\n## API\n\n#### `db = Hyperdb.bee(hypercore, definition, [options])`\n\nMake a db backed by Hyperbee. P2P!\n\nAvailable `options`:\n\n```\n{\n  autoUpdate: false, // Whether the database should update when the underlying hyperbee does\n  writable: true // Whether the database is writable\n}\n```\n\nFor Hyperbee backed databases, the database does not update it's state when the bee updates. Setting `autoUpdate` to `true` makes this automatic. Otherwise the database can be manually updated with `db.update()`.\n\n#### `db = Hyperdb.rocks(path, definition, [options])`\n\nMake a db backed by RocksDB. Local only!\n\nAvailable `options`:\n\n```\n{\n  readOnly: false, // Whether the database be read-only\n  writable: true // Whether the database is writable\n}\n```\n\n#### `queryStream = db.find(collectionOrIndex, query, [options])`\n\nQuery the database. `collectionOrIndex` is the identifier you defined in your builder.\n\nThe query looks like this\n\n```js\n{\n  gt: { ... },\n  gte: { ... },\n  lt: { ...},\n  lte: { ...}\n}\n```\n\nAnd options include\n\n```js\n{\n  limit, // how many max?\n  reverse: false // reverse stream?\n}\n```\n\nSee the basic tests for an easy example on how queries look like.\n\nThe `queryStream` is a streamx readable stream that yields the documents you search for.\n\nA query is always running on a snapshot, meaning any inserts/deletes you do while this is running\nwill not impact the query stream itself.\n\n#### `all = await queryStream.toArray()`\n\nStream helper to simply get all the remaining entries in the stream.\n\n#### `one = await queryStream.one()`\n\nStream helper to simply get the last entry in the stream.\n\n#### `doc = await db.findOne(collectionOrIndex, query, [options])`\n\nAlias for `await find(...).one()`\n\n#### `doc = await db.get(collection, query)`\n\nGet a document from a collection that matches the `query`. The `query` object will be converted into a key to check against the `collection`.\n\n#### `[a, b, ...] = await db.getAll([[collection, query], ...])`\n\nGet multiple documents in parallel. For composeability if you pass a Promise as one of the entries,\nits echoed back.\n\n#### `await db.insert(collection, doc)`\n\nInsert a document into a collection. NOTE: you have to flush the db later for this to be persisted.\n\n#### `await db.delete(collection, query)`\n\nDelete a document from a collection matching the query. NOTE: you have to flush the db later for this to be persisted.\n\n#### `await db.insertAll([[collection, doc, opts?], ...])`\n\nInsert multiple documents in parallel. Options include `{ type: 'delete' }` which makes the batch\ninterpret the insert as a delete for that item.\n\n#### `bool = db.updated([collection], [query])`\n\nReturns a boolean indicating if this database was updated since last time it was flushed. Pass a collection and doc query to know if a specific record was updated.\n\n#### `const stream = db.changes(range = {})`\n\nReturns a stream of changes to the database. The `range` can have the\nfollowing properties:\n\n```\n{\n  gte: seq, // Start with this seq (inclusive)\n  gt: seq, // Start after this index\n  lte: seq, // Stop after this index\n  lt: seq, // Stop before this index\n}\n```\n\n`seq` is the sequence number for the underlying Hyperbee node.\n\nOnly supported with Hyperbee engine.\n\n#### `const stream = db.diff(collection, query = {})`\n\nReturns a stream of `{ left, right }` objects describing how a collection\nchanged between an earlier point in the database's history and the database as\nit is now. `left` is the document as it was then, `right` is the document as it\nis now, and either side is `null` when the document did not exist there:\n\n```\n{ left: null, right: doc } // inserted\n{ left: doc, right: null } // deleted\n{ left: doc, right: doc } // updated\n```\n\nThe `query` looks like this\n\n```js\n{\n  from, // head to diff against, defaults to the empty database\n  gt: { ... },\n  gte: { ... },\n  lt: { ... },\n  lte: { ... },\n  limit // how many max?\n}\n```\n\n`from` is a head, ie. `{ key, length }`, as returned by `db.engine.head()`, the\nsame value `db.changes({ from })` takes. It defaults to the empty database, so\n`db.diff(collection)` streams every document as an insert.\n\nThe range is bounded to the given collection, and documents are streamed in key\norder, so `reverse` is not supported. Diffing an index is not supported either,\nsince an index only sees changes that move its own keys.\n\nOnly committed state is compared, inserts and deletes that have not been flushed\nyet are not included.\n\nOnly supported with the Hyperbee2 engine.\n\n#### `await db.flush()`\n\nFlush all changes to the db\n\n#### `db.watch(cb)`\n\nRegister a callback to trigger when database updates.\n\n#### `db.unwatch(cb)`\n\nRemove watch callback.\n\n#### `db.reload()`\n\nReload the internal snapshot. Clears the memory state.\n\n#### `db = db.snapshot()`\n\nMake a readonly snapshot of the database. All reads/streams are locked in time on a snapshot from the time you call the snapshot method.\n\n#### `db = db.transaction()`\n\nMake a writable snapshot of the database. All reads/streams are locked in time on a snapshot from the time you call the snapshot method.\nWhen you flush this one, it updates the main instance also.\n\nWarnings:\n\n- Transactions must always be closed. Flushing a transaction closes it, but when a transaction is cancelled (for example due to an error), `transaction.close()` has to be called explicitly.\n- Transactions must not be run in parallel. If you do not want to write your own locking mechanism, use `await db.exclusiveTransaction()` instead.\n\n#### `db = await db.exclusiveTransaction()`\n\nLike `db.transaction()`, but with a built-in lock to ensure transactions do not run concurrently.\n\n#### `await db.ready()`\n\nWait for the database to fully open.\n\n#### `await db.close()`\n\nClose the database. You have to close any snapshots you use also.\n\n#### `db.closed`\n\nWhether the database has been closed.\n\n#### `db.writable`\n\nWhether the database can be written to.\n\n#### `db.readable`\n\nWhether the database can be read.\n\n## Builder API\n\nWe can define what the schema of collections and the documents they contain using the builder API. A common pattern is to create a `build.js` script that is run whenever the database schema changes. See the [example](./builder/example/example.js).\n\nThe builder API can be imported via the `builder` subpath:\n\n```js\nconst HyperdbBuilder = require('hyperdb/builder')\n```\n\n#### `const db = HyperdbBuilder.from(SCHEMA_DIR, DB_DIR)`\n\nLoad a builder instance `db` with the `hyperschema` definitions (aka `SCHEMA_DIR`) and with existing `hyperdb` definitions (aka `DB_DIR`).\n\n`SCHEMA_DIR` is either the `hyperschema` definition object or the directory path to load from disk.\n\n`DB_DIR` is either the existing database definition as a object or the directory path to load from disk.\n\n#### `HyperdbBuilder.toDisk(db, DB_DIR, opts = { esm: false })`\n\nPersist the builder instance `db` to the path passed as `DB_DIR`. If `DB_DIR` is falsy, the builder will use the `db.dbDir` path from `db`. This method is usually called at the end of the `build.js` script.\n\nIf the `esm` option is set to true, the code generated will be an ESM module.\n\n#### `const namespacedDb = db.namespace(namespace)`\n\nCreate a namespaced db for defining multiple sets of database definitions on one database.\n\n#### `db.require(path)`\n\nLoad helper functions to be used in the database as callbacks for index maps.\n\n### Collections\n\n#### `db.collections.register(description)`\n\nRegister collection with the `description`.\n\nA `description` has the following form:\n\n```\n{\n  name: 'collection-name',\n  schema: '@schema-ns/struct-name', // identifier for the collections schema\n  key?: ['keyField1', 'keyField2'], // the definition of the primary key to lookup collection entries\n  derived?: false // Whether it is derived collection and so shouldnt be versioned\n}\n```\n\nElements in the `key` array should go from least to most specific, but often contain only one field that uniquely identifies the collection entry. Keys can use a 'dot notation' to specify nested properties of the collection entry's struct, for example:\n\n```js\n// Hyperschema\nconst dbSchema = schema.namespace('db')\ndbSchema.register({\n  name: 'foo',\n  fields: [{ name: 'id', type: 'string', required: true }]\n})\n\ndbSchema.register({\n  name: 'nested',\n  fields: [\n    { name: 'foo', type: '@db/foo', required: true }, // nested struct\n    { name: 'bar', type: 'bool' }\n  ]\n})\n\n// Hyperdb Builder\nconst db = HyperdbBuilder.from(SCHEMA_DIR, DB_DIR)\ndb.collections.register({\n  name: 'nested-foo',\n  schema: '@db/nested',\n  key: ['foo.id'] // uses `foo`'s `id` property as the key\n})\n```\n\n### Indexes\n\n#### `db.indexes.register(description)`\n\nRegister an index with the given `description`.\n\nA `description` has the following form:\n\n```\n{\n  name: 'index-name',\n  collection: '@ns/collection', // The collection the index is a lookup into.\n  unique: false, // whether index keys are unique, aka only return one document\n  key: ['other-field'] || {\n    type: 'string', // Key schema type\n    map: 'indexMapFunctionName' // The function name (registered via db.require()) to map over the collection w/ to create the index\n  }\n}\n```\n\nIf `unique` is `false`, the primary key of the document will be added to the index key to ensure entries do not clobber one another.\n\n##### Key Mapping\n\nIndexes support defining `key` as an array of fields just like Collections, but also support a mapping callback to derive keys from indexed entries. This callback has the following function signature:\n\n```js\nfunction keyMap (record, context): Array<any> {}\n```\n\nThe return type of the mapping callback is always an array but the type of the elements in that array are defined as a `hyperschema` type with the `type` property like so:\n\n```js\n// helpers.js\nexports.keyMap = (record, context) => [{ name: record.name, age: record.age }]\n\n// schema.js\n// ... Defining db, it's collections\ndb.require('./helpers.js')\ndb.indexes.register({\n  name: 'mapped-index',\n  collection: '@ns/collection',\n  key: {\n    type: {\n      // a struct\n      fields: [\n        {\n          name: 'name',\n          type: 'string'\n        },\n        {\n          name: 'age',\n          type: 'uint'\n        }\n      ]\n    },\n    map: 'keyMap' // the callback name from helpers.js\n  }\n})\n```\n\n## License\n\nApache-2.0\n","publish_time":1774903634479,"_cnpm_publish_time":1774903634479,"dist-tags":{"latest":"6.11.1","tmp":"4.22.3"}}