ORM SDK in TypeScript
Reactive ORM library for NextGraph: use reactive (typed) objects that automatically sync to NextGraph’s encrypted, local-first storage.
For a walk-through you can see the the expense-tracker example apps for discrete JSON documents or typed graph documents.
Why?
Different CRDTs have different APIs. We want to make it as easy as possible to use them in the same way:
You modify a plain old TypeScript object and that updates the CRDT.
Vice versa, the CRDT is modified and that is reflected in your TS object.
We offer this for React, Vue, and Svelte.
Note that we support discrete (JSON) CRDT and graph (RDF) CRDT ORMs.
- For graphs, you specify a schema using a SHEX shape and optionally a scope. This provides you with typing support.
- For discrete CRDTs, all you need is a document ID (NURI).
Table of Contents
Installation
pnpm add @ng-org/orm @ng-org/web
For schema generation, also install:
pnpm add -D @ng-org/shex-orm
Start
You are strongly advised to look at the example apps for discrete JSON documents and typed graph documents.
Before using the ORM, initialize NextGraph in your app entry point:
import { ng, init } from "@ng-org/web";
import { initNg } from "@ng-org/orm";
await init(
async (event) => {
// The ORM needs to have access to ng,
// the interface to the engine running in WASM.
initNg(ng, event.session);
},
true,
[],
);
Then use useShape() for graphs, or useDiscrete() for discrete documents.
In some cases, you may want to use advanced features managing subscriptions with the engine.
With an OrmSubscription, you can manage things like transactions manually.
This is useful for example when you want to manage a state across components.
See OrmSubscription.getOrCreate(ShapeType, scope) for graphs
and DiscreteOrmSubscription.getOrCreate(documentId) for discrete documents.
Internally, the OrmSubscription keeps a signalObject, a proxied, reactive object. When modifications are made, this makes the frontend components rerender and sends the update to the engine to be persisted.
In all cases, you have to create a document first with ng.doc_create().
Graph ORM: Defining Schemas
Define your data model using SHEX (Shape Expressions): See @ng-org/shex-orm for details.
shapes/shex/dogShape.shex:
PREFIX ex: <http://example.org/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
ex:Dog {
a [ex:Dog] ;
ex:name xsd:string ;
ex:age xsd:integer ? ;
ex:toys xsd:string * ;
}
Generate TypeScript types. Add the following to your package.json scripts and run build:orm:
"build:orm": "rdf-orm build --input ./src/shapes/shex --output ./src/shapes/orm"
Frontend Framework Usage
The SDK offers hooks for discrete and graph-based CRDTs for Svelte, Vue and React:
- discrete CRDTs for
- Svelte 5: useDiscrete
- Svelte 3/4: useDiscrete
- Vue: useDiscrete
- React: useDiscrete
- graph CRDTs for:
All of them have the same logic. They create a 2-way binding to the engine. You can modify the returned object like any other JSON object. Changes are immediately reflected in the CRDT and the components rerender. When the component unmounts, the subscription is closed.
// Queries the graphs with NURI did:ng:o:g1 and did:ng:o:g2 and with subject s1 or s2.
const expenses: DeepSignal<Set<Expense>> = useShape(ExpenseShapeType, {
graphs: ["did:ng:o:g1", "did:ng:o:g2"],
subjects: ["<s1 IRI>", "<s2 IRI>"],
});
// Use expenses in your component
// and modify them to trigger a rerender and persist them.
// ...
Working with Data
The ORM is designed to make working with data as normal as possible. You get an object as you are used to it and when you change properties, they are automatically persisted and synced with other devices. Conversely, modifications arrive at the ORM objects immediately and your components rerender.
Creating a Document
First, you need a document to store and get your data. With the document NURI, you can then create ORM objects.
// Create a new NextGraph document
const docNuri = await ng.doc_create(
session_id,
"Graph", // Or "YMap" or "Automerge", for discrete
"data:graph", // Or "data:json" : "data:map" for Automerge or YJs
"store",
undefined,
);
// Add class to RDF part of the document so we can find it again.
await ng.sparql_update(
session_id,
`INSERT DATA { GRAPH <${documentId}> {<${documentId}> a <${APPLICATION_CLASS_IRI}> } }`,
documentId,
);
To find your document, you can make a sparql query as well:
const ret = await ng.sparql_query(
session_id,
`SELECT ?storeId WHERE { GRAPH ?storeId { ?s a <${APPLICATION_CLASS_IRI}> } }`,
undefined,
undefined,
);
let documentId = ret?.results.bindings?.[0]?.storeId?.value;
Using and Modifying ORM Objects
There are multiple ways to get and modify data:
- Get and modify the data returned by a
useShape()oruseDiscrete()hook inside a component. - Get and modify the signalObject of the subscription returned by
Orm(Discrete)Subscription.getOrCreate(). - For graph ORMs: Call
insertObject()orgetObjects(no 2-way binding).
const dogSubscription = OrmSubscription.getOrCreate(DogShape, {
graphs: [docNuri],
});
await dogSubscription.readyPromise;
// If we used OrmDiscreteSubscription, the signalObject type would be array or object.
const dogSet: DeepSignal<Set<Dog>> = dogSubscription.signalObject;
dogs.add({
// Required: The document NURI. May be set to `""` for nested objects (will be inherited from parent object then).
"@graph": docNuri,
"@type": "did:ng:x:Dog", // Required: RDF type
"@id": "", // Empty string = auto-generate subject IRI
name: "Mr Puppy",
age: 2,
toys: new Set(["ball", "rope"]),
});
// When you know that only one element is in the set, you can call `.first()` to get it.
const aDog = dogs.first();
aDog.age += 1;
aDog.toy.add("bone");
// Utility to find objects in sets:
const sameDog = dogs.getBy(aDog["@graph"], aDog["@id"]);
// sameSog === aDog.
dogs.delete(aDog);
Note that the graph CRDT supports sets only, the discrete CRDTs arrays only.
Graph ORM: Relationships
To reference external objects, you can use their @id.
casey.friends.add(jackNuri);
// When the child object is a nested object that you do not have in memory,
// you can establish the link by adding an object that contains the `@id` property only.
shoppingExpense.category.add({ "@id": "<Subject IRI of expense category>" });
// Link objects by storing the target's `@id` NURI/IRI:
dog.owner = jackNuri;
// Resolve the relationship
const jack = people.find((p) => p["@id"] === dog.owner);
Note that when you delete a nested object from a parent, only the linkage to it is removed. The nested object itself (its quads) are not deleted.
Reference
Classes
DiscreteOrmSubscription
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:44
Class for managing RDF-based ORM subscriptions with the engine.
You have two options on how to interact with the ORM:
- Use a hook for your favorite framework under
@ng-org/orm/react|vue|svelte - Call OrmSubscription.getOrCreate to create a subscription manually
For more information about RDF-based ORM subscriptions, follow the tutorial at the top of this file.
Properties
documentId
readonlydocumentId:string
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:49
The document ID (NURI) of the subscribed document.
inTransaction
readonlyinTransaction:boolean=false
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:61
True, if a transaction is running.
pendingPatches
pendingPatches:
Patch[] |undefined
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:63
Aggregation of patches to be sent when in transaction.
readyPromise
readyPromise:
Promise<void>
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:65
Await to ensure that the subscription is established and the data arrived.
Accessors
signalObject
Get Signature
get signalObject():
DeepSignal<DiscreteArray|DiscreteObject> |undefined
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:110
The signalObject containing all data of the document (once subscription is established). The object behaves like a regular object or array with a couple of additions:
- Modifications are immediately propagated back to the database.
- Database changes are immediately reflected in the object.
- Watch for object changes using watchDeepSignal.
- Objects in arrays receive a unique
@idproperty.
Returns
DeepSignal<DiscreteArray | DiscreteObject> | undefined
Methods
beginTransaction()
beginTransaction():
void
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:307
Begins a transaction that batches changes to be committed to the database. This is useful for performance reasons.
Note that this does not disable reactivity of the signalObject.
Modifications keep being rendered instantly.
Returns
void
close()
close():
void
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:220
Stop the subscription.
If there is more than one subscription with the document ID, the orm subscription won’t close yet.
Additionally, the closing of the subscription is delayed by a couple hundred milliseconds so that when frontend frameworks unmount and soon mount a component again with the same document ID, we reuse the same orm subscription.
Returns
void
commitTransaction()
commitTransaction():
Promise<void>
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:329
Commits a transactions sending all modifications made during the transaction
(started with beginTransaction) to the database.
Returns
Promise<void>
Throws
if no transaction is open.
getOrCreate()
staticgetOrCreate<T>(documentId):DiscreteOrmSubscription
Defined in: sdk/js/orm/src/connector/discrete/discreteOrmSubscriptionHandler.ts:192
Returns an OrmSubscription which subscribes to the given document in a 2-way binding.
You find the document data in the signalObject,
once readyPromise resolves.
This is a DeepSignal object or array, depending on
your CRDT document (e.g. YArray vs YMap). The signalObject
behaves like a regular set to the outside but has a couple
of additional features:
- Modifications are propagated back to the document.
Note that multiple immediate modifications in the same task,
e.g.
obj[0] = "foo"; obj[1] = "bar"are batched together and sent in a subsequent microtask. - External document changes are immediately reflected in the object.
- Watch for object changes using watchDeepSignal.
You can use transactions, to prevent excessive calls to the engine with beginTransaction and commitTransaction.
In many cases, you are advised to use a hook for your
favorite framework under @ng-org/orm/react|vue|svelte
instead of calling getOrCreate directly.
Call `close, to close the subscription.
Note: If another call to getOrCreate was previously made
and close was not called on it (or only shortly after),
it will return the same OrmSubscription (pooling).
Type Parameters
T
T extends BaseType
Parameters
documentId
string
The document ID (NURI) of the CRDT
Returns
Example
// We assume you have created a CRDT document already, as below.
// const documentId = await ng.doc_create(
// session_id,
// crdt, // "Automerge" | "YMap" | "YArray". YArray is for root arrays, the other two have objects at root.
// crdt === "Automerge" ? "data:json" : crdt === "YMap ? "data:map" : "data:array",
// "store",
// undefined
// );
const subscription = DiscreteOrmSubscription.getOrCreate(documentId);
// Wait for data.
await subscription.readyPromise;
const document = subscription.signalObject;
if (!document.expenses) {
document.expenses = [];
}
document.expenses.push({
name: "New Expense name",
description: "Expense description",
});
// Await promise to run the below code in a new task.
// That will have push the changes to the database.
await Promise.resolve();
// Here, the expense modifications have been committed
// (unless you had previously called subscription.beginTransaction()).
// The data is available in subscriptions running on a different device too.
subscription.close();
// If you create a new subscription with the same document within a couple of 100ms,
// The subscription hasn't been closed and the old one is returned so that the data
// is available instantly. This is especially useful in the context of unmounting and remounting frontend frameworks.
const subscription2 = DiscreteOrmSubscription.getOrCreate(documentId);
subscription2.signalObject.expenses.push({
name: "Second expense",
description: "Second description",
});
subscription2.close();
OrmSubscription
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:46
Class for managing RDF-based ORM subscriptions with the engine.
You have two options on how to interact with the ORM:
- Use a hook for your favorite framework under
@ng-org/orm/react|vue|svelte - Call OrmSubscription.getOrCreate to create a subscription manually
For more information about RDF-based ORM subscriptions, see the README and follow the tutorial.
Type Parameters
T
T extends BaseType
Properties
inTransaction
inTransaction:
boolean=false
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:78
True, if a transaction is running.
pendingPatches
pendingPatches:
Patch[] |undefined
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:80
Aggregation of patches to be sent when in transaction.
readyPromise
readyPromise:
Promise<void>
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:82
Await to ensure that the subscription is established and the data arrived.
scope
readonlyscope:Scope
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:53
The Scope of the subscription.
shapeType
readonlyshapeType:ShapeType<T>
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:51
The shape type that is subscribed to.
signalObject
readonlysignalObject:DeepSignalSet<T>
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:67
The signalObject containing all data matching the shape and scope (once subscription is established). The object is of type DeepSignalSet which to the outside behaves like a regular set but has a couple of additional features:
- Modifications are immediately propagated back to the database.
- Database changes are immediately reflected in the object.
.getBy(graphIri, subjectIri)utility for quicker access to objects in set..first()utility to get the first element added to the set.- the iterator utilities, e.g.
.map(),.filter(), … - Watch for object changes using watchDeepSignal.
suspendDeepWatcher
suspendDeepWatcher:
boolean
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:76
When true, modifications from the signalObject are not processed.
Methods
beginTransaction()
beginTransaction():
void
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:404
Begins a transaction that batches changes to be committed to the database. This is useful for performance reasons.
Note that this does not disable reactivity of the signalObject.
Modifications keep being rendered.
Returns
void
close()
close():
void
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:262
Stop the subscription.
If there is more than one subscription with the same shape type and scope the orm subscription will persist.
Additionally, the closing of the subscription is delayed by a couple hundred milliseconds so that when frontend frameworks unmount and soon mount a component again with the same shape type and scope, we reuse the same orm subscription.
Returns
void
commitTransaction()
commitTransaction():
Promise<void>
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:423
Commits a transactions sending all modifications made during the transaction
(started with beginTransaction) to the database.
Returns
Promise<void>
getOrCreate()
staticgetOrCreate<T>(shapeType,scope):OrmSubscription<T>
Defined in: sdk/js/orm/src/connector/ormSubscriptionHandler.ts:229
Returns an OrmSubscription which subscribes to the given ShapeType and Scope in a 2-way binding.
You find the data and objects matching the shape and scope
in the signalObject once readyPromise resolves. This is a DeepSignalSet which
to the outside behaves like a regular set but has a couple of
additional features:
- Modifications are propagated back to the database.
Note that multiple immediate modifications in the same task,
e.g.
obj[0] = "foo"; obj[1] = "bar"are batched together and sent in a subsequent microtask. - Database changes are immediately reflected in the object.
.getBy(graphIri, subjectIri)utility for quicker access to objects in set..first()utility to get the first element added to the set.- the iterator utilities, e.g.
.map(),.filter(), … - Watch for object changes using watchDeepSignal.
You can use transactions, to prevent excessive calls to the database with beginTransaction and commitTransaction.
In many cases, you are advised to use a hook for your
favorite framework under @ng-org/orm/react|vue|svelte
instead of calling getOrCreate directly.
Call close, to close the subscription.
Note: If another call to getOrCreate was previously made
and close was not called on it (or only shortly after),
it will return the same OrmSubscription.
Type Parameters
T
T extends BaseType
Parameters
shapeType
ShapeType<T>
The ShapeType
scope
The Scope. If no scope is given, the whole store is considered.
Returns
Example
// We assume you have created a graph document already, as below.
// const documentId = await ng.doc_create(
// session_id,
// "Graph",
// "data:graph",
// "store",
// undefined
// );
const subscription = OrmSubscription.getOrCreate(ExpenseShapeType, {graphs: [graphIri]});
// Wait for data.
await subscription.readyPromise;
const expense = subscription.signalObject.first()
expense.name = "updated name";
expense.description = "updated description";
// Await promise to run the below code in a new task.
// That will push the changes to the database.
await Promise.resolve();
// Here, the expense modifications have been have been committed
// (unless you had previously called subscription.beginTransaction()).
// The data is available in subscriptions running on a different device too.
subscription.close();
// If you create a new subscription with the same document within a couple of 100ms,
// The subscription hasn't been closed and the old one is returned so that the data
// is available instantly. This is especially useful in the context of frontend frameworks.
const subscription2 = OrmSubscription.getOrCreate(ExpenseShapeType, {graphs: [graphIri]});
subscription2.signalObject.add({
"@graph": graphIri,
"@id": "", // Leave empty to auto-assign one.
name": "A new expense",
description: "A new description"
});
subscription2.close()
Interfaces
DeepSignalSet
Defined in: sdk/js/alien-deepsignals/src/types.ts:187
Type alias for DeepSignal<Set<T>> and reactive Set wrapper that accepts raw or proxied entries.
Additionally it is decorated with DeepSignalSetProps.
Extends
Set<DeepSignal<T>>.DeepSignalObjectProps<Set<T>>.SetIterator<DeepSignal<T>>.DeepSignalSetProps<T>
Type Parameters
T
T
Properties
__raw__
__raw__:
Set
Defined in: sdk/js/alien-deepsignals/src/types.ts:156
The original raw object.
Inherited from
DeepSignalObjectProps.__raw__
[toStringTag]
readonly[toStringTag]:string
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts:145
Inherited from
Set.[toStringTag]
size
readonlysize:number
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.collection.d.ts:112
Returns
the number of (unique) elements in Set.
Inherited from
Set.size
Methods
[dispose]()
[dispose]():
void
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.disposable.d.ts:36
Returns
void
Inherited from
SetIterator.[dispose]
[iterator]()
[iterator]():
SetIterator<DeepSignal<T>>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:198
Iterates over values in the set.
Returns
SetIterator<DeepSignal<T>>
Inherited from
Set.[iterator]
add()
add(
value):this
Defined in: sdk/js/alien-deepsignals/src/types.ts:192
Appends a new element with a specified value to the end of the Set.
Parameters
value
T | DeepSignal<T>
Returns
this
Overrides
Set.add
clear()
clear():
void
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.collection.d.ts:95
Returns
void
Inherited from
Set.clear
delete()
delete(
value):boolean
Defined in: sdk/js/alien-deepsignals/src/types.ts:193
Removes a specified value from the Set.
Parameters
value
T | DeepSignal<T>
Returns
boolean
Returns true if an element in the Set existed and has been removed, or false if the element does not exist.
Overrides
Set.delete
difference()
difference<
U>(other):Set<DeepSignal<T>>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.collection.d.ts:48
Type Parameters
U
U
Parameters
other
ReadonlySetLike<U>
Returns
Set<DeepSignal<T>>
a new Set containing all the elements in this Set which are not also in the argument.
Inherited from
Set.difference
drop()
drop(
count):IteratorObject<DeepSignal<T>,undefined,unknown>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:74
Creates an iterator whose values are the values from this iterator after skipping the provided count.
Parameters
count
number
The number of values to drop.
Returns
IteratorObject<DeepSignal<T>, undefined, unknown>
Inherited from
SetIterator.drop
entries()
entries():
SetIterator<[DeepSignal<T>,DeepSignal<T>]>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:203
Returns an iterable of [v,v] pairs for every value v in the set.
Returns
SetIterator<[DeepSignal<T>, DeepSignal<T>]>
Inherited from
Set.entries
every()
every(
predicate):boolean
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:122
Determines whether all the members of this iterator satisfy the specified test.
Parameters
predicate
(value, index) => unknown
A function that accepts up to two arguments. The every method calls the predicate function for each element in this iterator until the predicate returns false, or until the end of this iterator.
Returns
boolean
Inherited from
SetIterator.every
filter()
Call Signature
filter<
S>(predicate):IteratorObject<S,undefined,unknown>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:56
Creates an iterator whose values are those from this iterator for which the provided predicate returns true.
Type Parameters
S
S
Parameters
predicate
(value, index) => value is S
A function that accepts up to two arguments to be used to test values from the underlying iterator.
Returns
IteratorObject<S, undefined, unknown>
Inherited from
SetIterator.filter
Call Signature
filter(
predicate):IteratorObject<DeepSignal<T>,undefined,unknown>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:62
Creates an iterator whose values are those from this iterator for which the provided predicate returns true.
Parameters
predicate
(value, index) => unknown
A function that accepts up to two arguments to be used to test values from the underlying iterator.
Returns
IteratorObject<DeepSignal<T>, undefined, unknown>
Inherited from
SetIterator.filter
find()
Call Signature
find<
S>(predicate):S|undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:131
Returns the value of the first element in this iterator where predicate is true, and undefined otherwise.
Type Parameters
S
S
Parameters
predicate
(value, index) => value is S
find calls predicate once for each element of this iterator, in order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
Returns
S | undefined
Inherited from
SetIterator.find
Call Signature
find(
predicate):DeepSignal<T> |undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:132
Parameters
predicate
(value, index) => unknown
Returns
DeepSignal<T> | undefined
Inherited from
SetIterator.find
first()
first():
Textendsobject?DeepSignal<T> :T|undefined
Defined in: sdk/js/alien-deepsignals/src/types.ts:164
Get the element that was first inserted into the set.
Returns
T extends object ? DeepSignal<T> : T | undefined
Inherited from
flatMap()
flatMap<
U>(callback):IteratorObject<U,undefined,unknown>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:80
Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables.
Type Parameters
U
U
Parameters
callback
(value, index) => Iterator<U, unknown, undefined> | Iterable<U, unknown, undefined>
A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result.
Returns
IteratorObject<U, undefined, unknown>
Inherited from
SetIterator.flatMap
forEach()
Call Signature
forEach(
callbackfn,thisArg?):void
Defined in: sdk/js/alien-deepsignals/src/types.ts:195
Executes a provided function once per each value in the Set object, in insertion order.
Parameters
callbackfn
(value, value2, set) => void
thisArg?
any
Returns
void
Overrides
Set.forEach
Call Signature
forEach(
callbackfn,thisArg?):void
Defined in: sdk/js/alien-deepsignals/src/types.ts:203
Executes a provided function once per each value in the Set object, in insertion order.
Parameters
callbackfn
(value, index) => void
thisArg?
any
Returns
void
Overrides
Set.forEach
getBy()
getBy(
graphIri,subjectIri):DeepSignal<T> |undefined
Defined in: sdk/js/alien-deepsignals/src/types.ts:180
Retrieve an object from the Set by its @graph and @id.
Parameters
graphIri
string
The @graph NURI of the object.
subjectIri
string
The @subject IRI of the object.
Returns
DeepSignal<T> | undefined
The proxied entry if found, undefined otherwise.
Inherited from
getById()
getById(
id):DeepSignal<T> |undefined
Defined in: sdk/js/alien-deepsignals/src/types.ts:171
Retrieve an entry from the Set by its synthetic set ID.
Parameters
id
The synthetic ID (string or number) assigned to the entry.
string | number
Returns
DeepSignal<T> | undefined
The proxied entry if found, undefined otherwise.
Inherited from
has()
has(
value):boolean
Defined in: sdk/js/alien-deepsignals/src/types.ts:194
Parameters
value
T | DeepSignal<T>
Returns
boolean
a boolean indicating whether an element with the specified value exists in the Set or not.
Overrides
Set.has
intersection()
intersection<
U>(other):Set<DeepSignal<T> &U>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.collection.d.ts:44
Type Parameters
U
U
Parameters
other
ReadonlySetLike<U>
Returns
Set<DeepSignal<T> & U>
a new Set containing all the elements which are both in this Set and in the argument.
Inherited from
Set.intersection
isDisjointFrom()
isDisjointFrom(
other):boolean
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.collection.d.ts:64
Parameters
other
ReadonlySetLike<unknown>
Returns
boolean
a boolean indicating whether this Set has no elements in common with the argument.
Inherited from
Set.isDisjointFrom
isSubsetOf()
isSubsetOf(
other):boolean
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.collection.d.ts:56
Parameters
other
ReadonlySetLike<unknown>
Returns
boolean
a boolean indicating whether all the elements in this Set are also in the argument.
Inherited from
Set.isSubsetOf
isSupersetOf()
isSupersetOf(
other):boolean
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.collection.d.ts:60
Parameters
other
ReadonlySetLike<unknown>
Returns
boolean
a boolean indicating whether all the elements in the argument are also in this Set.
Inherited from
Set.isSupersetOf
keys()
keys():
SetIterator<DeepSignal<T>>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:208
Despite its name, returns an iterable of the values in the set.
Returns
SetIterator<DeepSignal<T>>
Inherited from
Set.keys
map()
map<
U>(callbackfn):IteratorObject<U,undefined,unknown>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:50
Creates an iterator whose values are the result of applying the callback to the values from this iterator.
Type Parameters
U
U
Parameters
callbackfn
(value, index) => U
A function that accepts up to two arguments to be used to transform values from the underlying iterator.
Returns
IteratorObject<U, undefined, unknown>
Inherited from
SetIterator.map
next()
next(…
__namedParameters):IteratorResult<DeepSignal<T>,undefined>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:43
Parameters
__namedParameters
[] | [unknown]
Returns
IteratorResult<DeepSignal<T>, undefined>
Inherited from
SetIterator.next
reduce()
Call Signature
reduce(
callbackfn):DeepSignal
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:87
Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
Parameters
callbackfn
(previousValue, currentValue, currentIndex) => DeepSignal
A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator.
Returns
Inherited from
SetIterator.reduce
Call Signature
reduce(
callbackfn,initialValue):DeepSignal
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:88
Parameters
callbackfn
(previousValue, currentValue, currentIndex) => DeepSignal
initialValue
Returns
Inherited from
SetIterator.reduce
Call Signature
reduce<
U>(callbackfn,initialValue):U
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:95
Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
Type Parameters
U
U
Parameters
callbackfn
(previousValue, currentValue, currentIndex) => U
A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator.
initialValue
U
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator.
Returns
U
Inherited from
SetIterator.reduce
return()?
optionalreturn(value?):IteratorResult<DeepSignal<T>,undefined>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:44
Parameters
value?
undefined
Returns
IteratorResult<DeepSignal<T>, undefined>
Inherited from
SetIterator.return
some()
some(
predicate):boolean
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:114
Determines whether the specified callback function returns true for any element of this iterator.
Parameters
predicate
(value, index) => unknown
A function that accepts up to two arguments. The some method calls the predicate function for each element in this iterator until the predicate returns a value true, or until the end of the iterator.
Returns
boolean
Inherited from
SetIterator.some
symmetricDifference()
symmetricDifference<
U>(other):Set<DeepSignal<T> |U>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.collection.d.ts:52
Type Parameters
U
U
Parameters
other
ReadonlySetLike<U>
Returns
Set<DeepSignal<T> | U>
a new Set containing all the elements which are in either this Set or in the argument, but not in both.
Inherited from
Set.symmetricDifference
take()
take(
limit):IteratorObject<DeepSignal<T>,undefined,unknown>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:68
Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached.
Parameters
limit
number
The maximum number of values to yield.
Returns
IteratorObject<DeepSignal<T>, undefined, unknown>
Inherited from
SetIterator.take
throw()?
optionalthrow(e?):IteratorResult<DeepSignal<T>,undefined>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:45
Parameters
e?
any
Returns
IteratorResult<DeepSignal<T>, undefined>
Inherited from
SetIterator.throw
toArray()
toArray():
DeepSignal<T>[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.iterator.d.ts:100
Creates a new array from the values yielded by this iterator.
Returns
DeepSignal<T>[]
Inherited from
SetIterator.toArray
union()
union<
U>(other):Set<DeepSignal<T> |U>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.esnext.collection.d.ts:40
Type Parameters
U
U
Parameters
other
ReadonlySetLike<U>
Returns
Set<DeepSignal<T> | U>
a new Set containing all the elements in this Set and also all the elements in the argument.
Inherited from
Set.union
values()
values():
SetIterator<DeepSignal<T>>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:213
Returns an iterable of values in the set.
Returns
SetIterator<DeepSignal<T>>
Inherited from
Set.values
DiscreteArray
Defined in: sdk/js/orm/src/types.ts:56
An allowed array in the CRDT.
Extends
Array<DiscreteType>
Indexable
[n: number]: DiscreteType
Properties
[unscopables]
readonly[unscopables]:object
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.symbol.wellknown.d.ts:97
Is an object whose properties have the value ‘true’ when they will be absent when used in a ‘with’ statement.
Index Signature
[key: number]: boolean | undefined
[iterator]?
optional[iterator]:boolean
[unscopables]?
readonlyoptional[unscopables]:boolean
Is an object whose properties have the value ‘true’ when they will be absent when used in a ‘with’ statement.
at?
optionalat:boolean
concat?
optionalconcat:boolean
copyWithin?
optionalcopyWithin:boolean
entries?
optionalentries:boolean
every?
optionalevery:boolean
fill?
optionalfill:boolean
filter?
optionalfilter:boolean
find?
optionalfind:boolean
findIndex?
optionalfindIndex:boolean
findLast?
optionalfindLast:boolean
findLastIndex?
optionalfindLastIndex:boolean
flat?
optionalflat:boolean
flatMap?
optionalflatMap:boolean
forEach?
optionalforEach:boolean
includes?
optionalincludes:boolean
indexOf?
optionalindexOf:boolean
join?
optionaljoin:boolean
keys?
optionalkeys:boolean
lastIndexOf?
optionallastIndexOf:boolean
length?
optionallength:boolean
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
map?
optionalmap:boolean
pop?
optionalpop:boolean
push?
optionalpush:boolean
reduce?
optionalreduce:boolean
reduceRight?
optionalreduceRight:boolean
reverse?
optionalreverse:boolean
shift?
optionalshift:boolean
slice?
optionalslice:boolean
some?
optionalsome:boolean
sort?
optionalsort:boolean
splice?
optionalsplice:boolean
toLocaleString?
optionaltoLocaleString:boolean
toReversed?
optionaltoReversed:boolean
toSorted?
optionaltoSorted:boolean
toSpliced?
optionaltoSpliced:boolean
toString?
optionaltoString:boolean
unshift?
optionalunshift:boolean
values?
optionalvalues:boolean
with?
optionalwith:boolean
Inherited from
Array.[unscopables]
length
length:
number
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1329
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
Inherited from
Array.length
Methods
[iterator]()
[iterator]():
ArrayIterator<DiscreteType>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:78
Iterator
Returns
ArrayIterator<DiscreteType>
Inherited from
Array.[iterator]
at()
at(
index):DiscreteType|undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2022.array.d.ts:24
Returns the item located at the specified index.
Parameters
index
number
The zero-based index of the desired code unit. A negative index will count back from the last item.
Returns
DiscreteType | undefined
Inherited from
Array.at
concat()
Call Signature
concat(…
items):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1353
Combines two or more arrays. This method returns a new array without modifying any existing arrays.
Parameters
items
…ConcatArray<DiscreteType>[]
Additional arrays and/or items to add to the end of the array.
Returns
Inherited from
Array.concat
Call Signature
concat(…
items):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1359
Combines two or more arrays. This method returns a new array without modifying any existing arrays.
Parameters
items
…(DiscreteType | ConcatArray<DiscreteType>)[]
Additional arrays and/or items to add to the end of the array.
Returns
Inherited from
Array.concat
copyWithin()
copyWithin(
target,start,end?):this
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.core.d.ts:62
Returns the this object after copying a section of the array identified by start and end to the same array starting at position target
Parameters
target
number
If target is negative, it is treated as length+target where length is the length of the array.
start
number
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end?
number
If not specified, length of the this object is used as its default value.
Returns
this
Inherited from
Array.copyWithin
entries()
entries():
ArrayIterator<[number,DiscreteType]>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:83
Returns an iterable of key, value pairs for every entry in the array
Returns
ArrayIterator<[number, DiscreteType]>
Inherited from
Array.entries
every()
Call Signature
every<
S>(predicate,thisArg?):this is S[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1440
Determines whether all the members of an array satisfy the specified test.
Type Parameters
S
S extends DiscreteType
Parameters
predicate
(value, index, array) => value is S
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg?
any
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
Returns
this is S[]
Inherited from
Array.every
Call Signature
every(
predicate,thisArg?):boolean
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1449
Determines whether all the members of an array satisfy the specified test.
Parameters
predicate
(value, index, array) => unknown
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg?
any
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
Returns
boolean
Inherited from
Array.every
fill()
fill(
value,start?,end?):this
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.core.d.ts:51
Changes all array elements from start to end index to a static value and returns the modified array
Parameters
value
value to fill array section with
start?
number
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end?
number
index to stop filling the array at. If end is negative, it is treated as length+end.
Returns
this
Inherited from
Array.fill
filter()
Call Signature
filter<
S>(predicate,thisArg?):S[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1476
Returns the elements of an array that meet the condition specified in a callback function.
Type Parameters
S
S extends DiscreteType
Parameters
predicate
(value, index, array) => value is S
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg?
any
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
Returns
S[]
Inherited from
Array.filter
Call Signature
filter(
predicate,thisArg?):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1482
Returns the elements of an array that meet the condition specified in a callback function.
Parameters
predicate
(value, index, array) => unknown
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg?
any
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
Returns
Inherited from
Array.filter
find()
Call Signature
find<
S>(predicate,thisArg?):S|undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.core.d.ts:29
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
Type Parameters
S
S extends DiscreteType
Parameters
predicate
(value, index, obj) => value is S
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg?
any
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
Returns
S | undefined
Inherited from
Array.find
Call Signature
find(
predicate,thisArg?):DiscreteType|undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.core.d.ts:30
Parameters
predicate
(value, index, obj) => unknown
thisArg?
any
Returns
DiscreteType | undefined
Inherited from
Array.find
findIndex()
findIndex(
predicate,thisArg?):number
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.core.d.ts:41
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
Parameters
predicate
(value, index, obj) => unknown
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg?
any
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
Returns
number
Inherited from
Array.findIndex
findLast()
Call Signature
findLast<
S>(predicate,thisArg?):S|undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2023.array.d.ts:29
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
Type Parameters
S
S extends DiscreteType
Parameters
predicate
(value, index, array) => value is S
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg?
any
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
Returns
S | undefined
Inherited from
Array.findLast
Call Signature
findLast(
predicate,thisArg?):DiscreteType|undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2023.array.d.ts:30
Parameters
predicate
(value, index, array) => unknown
thisArg?
any
Returns
DiscreteType | undefined
Inherited from
Array.findLast
findLastIndex()
findLastIndex(
predicate,thisArg?):number
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2023.array.d.ts:41
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
Parameters
predicate
(value, index, array) => unknown
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg?
any
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
Returns
number
Inherited from
Array.findLastIndex
flat()
flat<
A,D>(this,depth?):FlatArray<A,D>[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2019.array.d.ts:75
Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Type Parameters
A
A
D
D extends number = 1
Parameters
this
A
depth?
D
The maximum recursion depth
Returns
FlatArray<A, D>[]
Inherited from
Array.flat
flatMap()
flatMap<
U,This>(callback,thisArg?):U[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2019.array.d.ts:64
Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.
Type Parameters
U
U
This
This = undefined
Parameters
callback
(this, value, index, array) => U | readonly U[]
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg?
This
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.
Returns
U[]
Inherited from
Array.flatMap
forEach()
forEach(
callbackfn,thisArg?):void
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1464
Performs the specified action for each element in an array.
Parameters
callbackfn
(value, index, array) => void
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg?
any
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
Returns
void
Inherited from
Array.forEach
includes()
includes(
searchElement,fromIndex?):boolean
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2016.array.include.d.ts:25
Determines whether an array includes a certain element, returning true or false as appropriate.
Parameters
searchElement
The element to search for.
fromIndex?
number
The position in this array at which to begin searching for searchElement.
Returns
boolean
Inherited from
Array.includes
indexOf()
indexOf(
searchElement,fromIndex?):number
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1425
Returns the index of the first occurrence of a value in an array, or -1 if it is not present.
Parameters
searchElement
The value to locate in the array.
fromIndex?
number
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
Returns
number
Inherited from
Array.indexOf
join()
join(
separator?):string
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1364
Adds all the elements of an array into a string, separated by the specified separator string.
Parameters
separator?
string
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.
Returns
string
Inherited from
Array.join
keys()
keys():
ArrayIterator<number>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:88
Returns an iterable of keys in the array
Returns
ArrayIterator<number>
Inherited from
Array.keys
lastIndexOf()
lastIndexOf(
searchElement,fromIndex?):number
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1431
Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.
Parameters
searchElement
The value to locate in the array.
fromIndex?
number
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.
Returns
number
Inherited from
Array.lastIndexOf
map()
map<
U>(callbackfn,thisArg?):U[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1470
Calls a defined callback function on each element of an array, and returns an array that contains the results.
Type Parameters
U
U
Parameters
callbackfn
(value, index, array) => U
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg?
any
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
Returns
U[]
Inherited from
Array.map
pop()
pop():
DiscreteType|undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1342
Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.
Returns
DiscreteType | undefined
Inherited from
Array.pop
push()
push(…
items):number
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1347
Appends new elements to the end of an array, and returns the new length of the array.
Parameters
items
…DiscreteType[]
New elements to add to the array.
Returns
number
Inherited from
Array.push
reduce()
Call Signature
reduce(
callbackfn):DiscreteType
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1488
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
Parameters
callbackfn
(previousValue, currentValue, currentIndex, array) => DiscreteType
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
Returns
Inherited from
Array.reduce
Call Signature
reduce(
callbackfn,initialValue):DiscreteType
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1489
Parameters
callbackfn
(previousValue, currentValue, currentIndex, array) => DiscreteType
initialValue
Returns
Inherited from
Array.reduce
Call Signature
reduce<
U>(callbackfn,initialValue):U
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1495
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
Type Parameters
U
U
Parameters
callbackfn
(previousValue, currentValue, currentIndex, array) => U
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
U
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
Returns
U
Inherited from
Array.reduce
reduceRight()
Call Signature
reduceRight(
callbackfn):DiscreteType
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1501
Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
Parameters
callbackfn
(previousValue, currentValue, currentIndex, array) => DiscreteType
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
Returns
Inherited from
Array.reduceRight
Call Signature
reduceRight(
callbackfn,initialValue):DiscreteType
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1502
Parameters
callbackfn
(previousValue, currentValue, currentIndex, array) => DiscreteType
initialValue
Returns
Inherited from
Array.reduceRight
Call Signature
reduceRight<
U>(callbackfn,initialValue):U
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1508
Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
Type Parameters
U
U
Parameters
callbackfn
(previousValue, currentValue, currentIndex, array) => U
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
U
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
Returns
U
Inherited from
Array.reduceRight
reverse()
reverse():
DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1369
Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.
Returns
Inherited from
Array.reverse
shift()
shift():
DiscreteType|undefined
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1374
Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.
Returns
DiscreteType | undefined
Inherited from
Array.shift
slice()
slice(
start?,end?):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1384
Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.
Parameters
start?
number
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end?
number
The end index of the specified portion of the array. This is exclusive of the element at the index ‘end’. If end is undefined, then the slice extends to the end of the array.
Returns
Inherited from
Array.slice
some()
some(
predicate,thisArg?):boolean
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1458
Determines whether the specified callback function returns true for any element of an array.
Parameters
predicate
(value, index, array) => unknown
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg?
any
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
Returns
boolean
Inherited from
Array.some
sort()
sort(
compareFn?):this
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1395
Sorts an array in place. This method mutates the array and returns a reference to the same array.
Parameters
compareFn?
(a, b) => number
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they’re equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
[11, 2, 22, 1].sort((a, b) => a - b);
Returns
this
Inherited from
Array.sort
splice()
Call Signature
splice(
start,deleteCount?):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1404
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
Parameters
start
number
The zero-based location in the array from which to start removing elements.
deleteCount?
number
The number of elements to remove. Omitting this argument will remove all elements from the start paramater location to end of the array. If value of this argument is either a negative number, zero, undefined, or a type that cannot be converted to an integer, the function will evaluate the argument as zero and not remove any elements.
Returns
An array containing the elements that were deleted.
Inherited from
Array.splice
Call Signature
splice(
start,deleteCount, …items):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1414
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
Parameters
start
number
The zero-based location in the array from which to start removing elements.
deleteCount
number
The number of elements to remove. If value of this argument is either a negative number, zero, undefined, or a type that cannot be converted to an integer, the function will evaluate the argument as zero and not remove any elements.
items
…DiscreteType[]
Elements to insert into the array in place of the deleted elements.
Returns
An array containing the elements that were deleted.
Inherited from
Array.splice
toLocaleString()
Call Signature
toLocaleString():
string
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1337
Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.
Returns
string
Inherited from
Array.toLocaleString
Call Signature
toLocaleString(
locales,options?):string
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.core.d.ts:64
Parameters
locales
string | string[]
options?
NumberFormatOptions & DateTimeFormatOptions
Returns
string
Inherited from
Array.toLocaleString
toReversed()
toReversed():
DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2023.array.d.ts:46
Returns a copy of an array with its elements reversed.
Returns
Inherited from
Array.toReversed
toSorted()
toSorted(
compareFn?):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2023.array.d.ts:57
Returns a copy of an array with its elements sorted.
Parameters
compareFn?
(a, b) => number
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they’re equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order.
[11, 2, 22, 1].toSorted((a, b) => a - b); // [1, 2, 11, 22]
Returns
Inherited from
Array.toSorted
toSpliced()
Call Signature
toSpliced(
start,deleteCount, …items):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2023.array.d.ts:66
Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.
Parameters
start
number
The zero-based location in the array from which to start removing elements.
deleteCount
number
The number of elements to remove.
items
…DiscreteType[]
Elements to insert into the copied array in place of the deleted elements.
Returns
The copied array.
Inherited from
Array.toSpliced
Call Signature
toSpliced(
start,deleteCount?):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2023.array.d.ts:74
Copies an array and removes elements while returning the remaining elements.
Parameters
start
number
The zero-based location in the array from which to start removing elements.
deleteCount?
number
The number of elements to remove.
Returns
A copy of the original array with the remaining elements.
Inherited from
Array.toSpliced
toString()
toString():
string
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1333
Returns a string representation of an array.
Returns
string
Inherited from
Array.toString
unshift()
unshift(…
items):number
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es5.d.ts:1419
Inserts new elements at the start of an array, and returns the new length of the array.
Parameters
items
…DiscreteType[]
Elements to insert at the start of the array.
Returns
number
Inherited from
Array.unshift
values()
values():
ArrayIterator<DiscreteType>
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2015.iterable.d.ts:93
Returns an iterable of values in the array
Returns
ArrayIterator<DiscreteType>
Inherited from
Array.values
with()
with(
index,value):DiscreteType[]
Defined in: node_modules/.pnpm/typescript@5.9.3/node_modules/typescript/lib/lib.es2023.array.d.ts:85
Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.
Parameters
index
number
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.
Returns
The copied array with the updated value.
Inherited from
Array.with
DiscreteObject
Defined in: sdk/js/orm/src/types.ts:59
An allowed object in the CRDT.
Indexable
[key: string]: DiscreteType
DiscreteRootObject
Defined in: sdk/js/orm/src/types.ts:84
The root object for reading and modifying the CRDT as a plain object.
Indexable
[key: string]: string | number | boolean | DiscreteObject | DiscreteRootArray
Type Aliases
DeepSignal
DeepSignal<
T> =TextendsFunction?T:Textendsstring|number|boolean?T:TextendsDeepSignalObjectProps<any> |DeepSignalObjectProps<any>[] ?T:Textends infer I[] ?DeepSignal<I>[] :TextendsSet<infer S> ?DeepSignalSet<S> :Textendsobject?DeepSignalObject<T> :T
Defined in: sdk/js/alien-deepsignals/src/types.ts:214
The object returned by the deepSignal function.
It is decorated with utility functions for sets, see DeepSignalSetProps
and a __raw__ prop to get the underlying non-reactive object.
Type Parameters
T
T
DeepSignalObject
DeepSignalObject<
T> ={ [K in keyof T]: DeepSignal<T[K]> }
Defined in: sdk/js/alien-deepsignals/src/types.ts:228
Type Parameters
T
T extends object
DiscreteCrdt
DiscreteCrdt =
"YMap"|"YArray"|"Automerge"
Defined in: sdk/js/orm/src/types.ts:101
The supported discrete (JSON) CRDTs. Automerge and YMap require objects as roots. YArray requires an array as root.
DiscreteRoot
DiscreteRoot =
DiscreteRootArray|DiscreteRootObject
Defined in: sdk/js/orm/src/types.ts:94
A discrete document’s root object, either an array or an object.
DiscreteRootArray
DiscreteRootArray = (
DiscreteArray|string|number|boolean|DiscreteObject&object)[]
Defined in: sdk/js/orm/src/types.ts:73
The root array for reading and modifying the CRDT as a plain object.
DiscreteType
DiscreteType =
DiscreteArray|DiscreteObject|string|number|boolean
Defined in: sdk/js/orm/src/types.ts:63
An allowed type in the CRDT.
Scope
Scope =
object
Defined in: sdk/js/orm/src/types.ts:25
When dealing with shapes (RDF-based graph database ORMs):
The scope of a shape request.
In most cases, it is recommended to use a narrow scope for performance.
You can filter results by subjects and graphs. Only objects in that scope will be returned.
Example
// Contains all expense objects with `@id` <s1 IRI> or <s2 IRI> and `@graph` <g1 NURI> or <g2 NURI>
const expenses: DeepSignal<Set<Expense>> = useShape(ExpenseShape, {
graphs: ["<graph1 NURI>", "<graph2 NURI>"],
subjects: ["<subject1 IRI>", "<subject2 IRI>"],
});
Properties
graphs?
optionalgraphs:string[]
Defined in: sdk/js/orm/src/types.ts:32
The graphs to filter for. If more than one NURI is provided, the union of all graphs is considered.
- Set value to
["did:ng:i"]or[""]for whole dataset. - Setting value to
[]or leaving itundefined, no objects are returned.
subjects?
optionalsubjects:string[]
Defined in: sdk/js/orm/src/types.ts:37
Subjects to filter for. Set to [] or leave it undefined for no filtering.
Session
Session =
object
Defined in: sdk/js/orm/src/connector/initNg.ts:14
A NextGraph session with an engine.
Indexable
[key: string]: unknown
Properties
ng
ng: typeof
NG
Defined in: sdk/js/orm/src/connector/initNg.ts:19
private_store_id
private_store_id:
string
Defined in: sdk/js/orm/src/connector/initNg.ts:17
protected_store_id
protected_store_id:
string
Defined in: sdk/js/orm/src/connector/initNg.ts:16
public_store_id
public_store_id:
string
Defined in: sdk/js/orm/src/connector/initNg.ts:18
session_id
session_id:
string|number
Defined in: sdk/js/orm/src/connector/initNg.ts:15
Variables
effect()
consteffect: (fn) => () =>void=alienEffect
Defined in: sdk/js/alien-deepsignals/src/core.ts:107
Re-export of alien-signals effect function.
Callback reruns on every signal modification that is used within its callback.
Parameters
fn
() => void
Returns
():
void
Returns
void
ngSession
constngSession:Promise<{ng:__module;session:Session; }>
Defined in: sdk/js/orm/src/connector/initNg.ts:26
Resolves to the NG session and the ng implementation.
Functions
getObjects()
getObjects<
T>(shapeType,scope?):Promise<DeepSignalSet<T>>
Defined in: sdk/js/orm/src/connector/getObjects.ts:23
Utility for retrieving objects once without establishing a two-way subscription.
Type Parameters
T
T extends BaseType
Parameters
shapeType
ShapeType<T>
The shape type of the objects to be retrieved.
scope?
Scope = {}
The scope of the objects to be retrieved.
Returns
Promise<DeepSignalSet<T>>
A set of all objects matching the shape and scope
getRaw()
getRaw<
T>(value):any
Defined in: sdk/js/alien-deepsignals/src/deepSignal.ts:1455
Get the original, raw value of a deep signal.
Type Parameters
T
T extends object
Parameters
value
T | DeepSignal<T>
Returns
any
initNg()
initNg(
ngImpl,session):void
Defined in: sdk/js/orm/src/connector/initNg.ts:61
Initialize the ORM by passing the ng implementation and session.
This is the first thing you need to to before using the ORM.
Parameters
ngImpl
__module
The NextGraph API, e.g. exported from @ng-org/web.
session
The established NextGraph session.
Returns
void
Example
import { ng, init } from "@ng-org/web";
import { initNg as initNgSignals, Session } from "@ng-org/orm";
let session: Session;
// Call as early as possible as it will redirect to the auth page.
await init(
async (event: any) => {
session = event.session;
session!.ng ??= ng;
// Call initNgSignals
initNgSignals(ng, session);
},
true,
[],
);
insertObject()
insertObject<
T>(shapeType,object):Promise<void>
Defined in: sdk/js/orm/src/connector/insertObject.ts:20
Utility for adding ORM-typed objects to the database without the need for subscribing to documents.
Type Parameters
T
T extends BaseType
Parameters
shapeType
ShapeType<T>
The shape type of the objects to be inserted.
object
T
The object to be inserted.
Returns
Promise<void>
reactUseDiscrete()
reactUseDiscrete<
T>(documentId):object
Defined in: sdk/js/orm/src/frontendAdapters/react/useDiscrete.ts:118
Hook to subscribe to an existing discrete (JSON) CRDT document. You can modify the returned object like any other JSON object. Changes are immediately reflected in the CRDT document.
Establishes a 2-way binding: Modifications to the object are immediately committed; changes coming from the engine (or other components) cause an immediate rerender.
In comparison to reactUseShape, discrete CRDTs are untyped. You can put any JSON data inside and need to validate the schema yourself.
Type Parameters
T
T = DiscreteRoot
Parameters
documentId
The NURI of the CRDT document.
string | undefined
Returns
object
An object that contains as doc the reactive DeepSignal object or undefined if documentId is undefined.
doc
doc:
DeepSignal<T> |undefined=docOrUndefined
Example
// We assume you have created a CRDT document already, as below.
// const documentId = await ng.doc_create(
// session_id,
// crdt, // "Automerge" | "YMap" | "YArray". YArray is for root arrays, the other two have objects at root.
// crdt === "Automerge" ? "data:json" : crdt === "YMap ? "data:map" : "data:array",
// "store",
// undefined
// );
function Expenses({ documentId }: { documentId: string }) {
const { doc } = useDiscrete(documentId);
// If the CRDT document is still empty, we need to initialize it.
if (doc && !doc.expenses) {
doc.expenses = [];
}
const expenses = doc?.expenses;
const createExpense = useCallback(() => {
// Note that we use *expense["@id"]* as a key in the expense list.
// Every object added to a CRDT array gets a stable `@id` property assigned
// which you can use for referencing objects in arrays even as
// objects are removed or added from the array.
// The `@id` is a NURI with the schema `<documentId>:d:<object-specific id>`.
// Since the `@id` is generated in the engine, the object is
// *preliminarily given a mock id* which will be replaced immediately.
expenses.push({
title: "New expense",
date: new Date().toISOString(),
});
}, [expenses]);
// Still loading?
if (!doc) return <div>Loading...</div>;
return (
<div>
<button onClick={() => createExpense()}>+ Add expense</button>
<div>
{expenses.length === 0 ? (
<p>No expenses yet.</p>
) : (
expenses.map((expense) => (
<ExpenseCard key={expense["@id"]} expense={expense} />
))
)}
</div>
</div>
);
}
In the ExpenseCard component:
function ExpenseCard({expense}: {expense: Expense}) {
return (
<input
value={expense.title}
onChange={(e) => {
expense.title = e.target.value; // Changes trigger rerender.
}}
/>
<div>
<p>Date</p>
<p>{expense.doc}
</div
);
}
reactUseShape()
reactUseShape<
T>(shape,scope):DeepSignalSet<T>
Defined in: sdk/js/orm/src/frontendAdapters/react/useShape.ts:86
Hook to subscribe to RDF data in the graph database using a shape, see ShapeType.
Returns a DeepSignalSet of objects matching the shape and that are within the scope. Establishes a 2-way binding: Modifications to the object are immediately committed, changes coming from the engine (or other components) cause an immediate rerender.
Type Parameters
T
T extends BaseType
Parameters
shape
ShapeType<T>
The ShapeType the objects should have (generated by the shex-orm tool).
scope
The Scope as graph string or scope object with graphs and subjects.
string | Scope | undefined
Returns
A DeepSignalSet with the orm objects or an empty set, if still loading.
If the scope is explicitly set to undefined, an empty set is returned which errors
if you try to make modifications on it.
Example
function Expenses() {
const expenses: DeepSignal<Set<Expense>> = useShape(ExpenseShapeType, {
graphs: ["<graph NURI>"],
});
const createExpense = useCallback(() => {
expenses.add({
"@graph": `<graph NURI>`,
"@type": "http://example.org/Expense",
"@id": "", // Assigns ID automatically, if set to "".
title: "New expense",
dateOfPurchase: obj.dateOfPurchase ?? new Date().toISOString(),
});
}, [expenses]);
const expensesSorted = [...expenses].sort((a, b) =>
a.dateOfPurchase.localeCompare(b.dateOfPurchase),
);
// Note that if you use `@id` (the subject IRI) as key, you need to ensure that it is unique within your scope.
// If it is not (i.e. there are two graphs with the same subject), use the combination of `@graph` and `@id`.
return (
<div>
<button onClick={() => createExpense({})}>+ Add expense</button>
<div>
{expensesSorted.length === 0 ? (
<p>No expenses yet.</p>
) : (
expensesSorted.map((expense) => (
// You can modify the expense's properties in the ExpenseCard component
// which will instantly trigger a rerender.
<ExpenseCard key={expense["@id"]} expense={expense} />
))
)}
</div>
</div>
);
}
svelte4UseDiscrete()
svelte4UseDiscrete<
T>(documentIdOrPromise):object
Defined in: sdk/js/orm/src/frontendAdapters/svelte4/useDiscrete.svelte.ts:100
Svelte 3/4 hook to subscribe to discrete (JSON) CRDT documents. You can modify the returned object like any other JSON object. Changes are immediately reflected in the CRDT.
Establishes a 2-way binding: Modifications to the object are immediately committed, changes coming from the backend (or other components) cause an immediate rerender.
In comparison to svelte4UseShape, discrete CRDTs are untyped. You can put any JSON data inside and need to validate the schema yourself.
Type Parameters
T
T = DiscreteRoot
Parameters
documentIdOrPromise
The NURI of the CRDT document or a promise to that.
string | Promise<string> | undefined
Returns
object
The store of the reactive JSON object of the CRDT document or undefined.
doc
doc:
UseDeepSignalResult<T|undefined>
Example
<script lang="ts">
// We assume you have created a CRDT document already, as below.
// const documentId = await ng.doc_create(
// session_id,
// crdt, // "Automerge" | "YMap" | "YArray"
// crdt === "Automerge" ? "data:json" : crdt === "YMap ? "data:map" : "data:array",
// "store",
// undefined
const doc = useDiscrete(documentIdPromise);
// If the CRDT document is still empty, we need to initialize it.
$: if (doc && !doc.expenses) {
doc.expenses = [];
}
// Call doc.expenses.push({title: "Example title"}), to add new elements.
// Note that we use expense["@id"] NURI as a key in the expense list.
// Every object added to a CRDT array gets a stable `@id` property assigned
// which you can use for referencing objects in arrays even as
// objects are removed from the array.
// Since the `@id` is generated in the backend, the object is preliminarily
// given a mock ID which will be replaced immediately
</script>
<section>
<div>
{#if !doc}
Loading...
{:else if doc.expenses.length === 0}
<p>
Nothing tracked yet - log your first purchase to kick things off.
</p>
{:else}
{#each doc.expenses as expense, index (expense['@id']) }
<ExpenseCard
expense={expense}
/>
{/each}
{/if}
</div>
</section>
In the ExpenseCard component:
let {
expense = $bindable(),
}: { expense: Expense; } = $props();
</script>
<div>
<input
value={expense.title ?? ""}
oninput={(event) => {expense.title = event.currentTarget?.value ?? ""}}
placeholder="Expense title"
/>
</div>
svelte4UseShape()
svelte4UseShape<
T>(shape,scope):UseShapeStoreResult<Set<T>>
Defined in: sdk/js/orm/src/frontendAdapters/svelte4/useShape.svelte.ts:94
Svelte 3/4 hook to subscribe to RDF data in the graph database using a shape, see ShapeType.
Returns a DeepSignalSet store containing the objects matching the shape and that are within the scope. Establishes a 2-way binding: Modifications to the object are immediately committed, changes coming from the backend (or other components) cause an immediate rerender.
Type Parameters
T
T extends BaseType
Parameters
shape
ShapeType<T>
The ShapeType the objects should have (generated by the shex-orm tool).
scope
The Scope as graph string or scope object with graphs and subjects.
string | Scope | undefined
Returns
UseShapeStoreResult<Set<T>>
A DeepSignalSet with the orm objects or an empty set, if still loading.
If the scope is explicitly set to undefined, an empty set is returned which errors
if you try to make modifications on it.
Example
<script lang="ts">
// Gets all expense objects with `@id` <s1 IRI> or <s2 IRI> and `@graph` <g1 NURI> or <g2 NURI>
const expenses: DeepSignal<Set<Expense>> = useShape(ExpenseShape,
{graphs: ["<g1 NURI>", "<g2 NURI>"],
subjects: ["<s1 NURI>", "<s2 NURI>"]});
const expensesSorted = computed(() => expenses.sort((a, b) =>
a.dateOfPurchase.localeCompare(b.dateOfPurchase)
));
// Call expenses.add({"@graph": "<g1 or g2 NURI>", "@id": "", title: "Example title"}), to add new elements.
// Leave `@id` an empty string to auto-generate a subject IRI (adjust your scope accordingly).
// Note that if you use `@id` (the subject IRI) as key, you need to ensure that it is unique within your scope.
// If it is not (i.e. there are two graphs with the same subject), use the combination of `@graph` and `@id`.
</script>
<section>
<div>
{# if expensesSorted.length === 0}
<p>
No expense yet.
</p>
{:else}
{#each expensesSorted as expense, index (expense['@id']) }
<ExpenseCard
expense={expense}
/>
{/each}
{/if}
</div>
</section>
In the ExpenseCard component:
let {
expense = $bindable(),
}: { expense: Expense; } = $props();
</script>
<div>
<input
bind:value={expense.title}
placeholder="Expense title"
/>
</div>
svelteUseDiscrete()
svelteUseDiscrete<
T>(documentIdOrPromise):object
Defined in: sdk/js/orm/src/frontendAdapters/svelte/useDiscrete.svelte.ts:105
Svelte 5 hook to subscribe to existing discrete (JSON) CRDT documents. You can modify the returned object like any other JSON object. Changes are immediately reflected in the CRDT.
Establishes a 2-way binding: Modifications to the object are immediately committed, changes coming from the engine (or other components) cause an immediate rerender.
In comparison to svelteUseShape, discrete CRDTs are untyped. You can put any JSON data inside and need to validate the schema yourself.
Type Parameters
T
T = DiscreteRoot
Parameters
documentIdOrPromise
The NURI of the CRDT document or a promise to that.
string | Promise<string> | undefined
Returns
object
The reactive JSON object of the CRDT document.
doc
doc:
DeepSignal<T|undefined>
Example
<script lang="ts">
// We assume you have created a CRDT document already, as below.
// const documentId = await ng.doc_create(
// session_id,
// crdt, // "Automerge" | "YMap" | "YArray"
// crdt === "Automerge" ? "data:json" : crdt === "YMap ? "data:map" : "data:array",
// "store",
// undefined,
// );
const { doc } = useDiscrete(documentIdPromise);
$effect(() => {
// If the CRDT document is still empty, we need to initialize it.
if (doc && !doc.expenses) {
doc.expenses = [];
}
});
const createExpense = () => {
// Note that we use *expense["@id"]* as a key in the expense list.
// Every object added to a CRDT array gets a stable `@id` property assigned
// which you can use for referencing objects in arrays even as
// preceding objects are removed or added from the array.
// The `@id` is an NURI with the schema `<documentId>:d:<object-specific id>`.
// Since the `@id` is generated in the engine, the object is
// *preliminarily given a mock id* which will be replaced immediately.
expenses.push({
title: "New expense",
date: new Date().toISOString(),
});
};
</script>
<section>
<div>
<button on:click={() => createExpense({})}/>
{#if !doc}
Loading...
{:else if doc.expenses.length === 0}
<p>
Nothing tracked yet - log your first purchase to kick things off.
</p>
{:else}
{#each doc.expenses as expense, index (expense['@id']) }
<ExpenseCard
expense={expense}
/>
{/each}
{/if}
</div>
</section>
In the ExpenseCard component:
let {
expense = $bindable(),
}: { expense: Expense; } = $props();
</script>
<div>
<input
bind:value={expense.title}
/>
</div>
svelteUseShape()
svelteUseShape<
T>(shape,scope):DeepSignalSet<T>
Defined in: sdk/js/orm/src/frontendAdapters/svelte/useShape.svelte.ts:96
Svelte 5 hook to subscribe to RDF data in the graph database using a shape, see ShapeType.
Returns a DeepSignalSet that contain the objects matching the shape and that are within the scope. Establishes a 2-way binding: Modifications to the object are immediately committed, changes coming from the engine (or other components) cause an immediate rerender.
Type Parameters
T
T extends BaseType
Parameters
shape
ShapeType<T>
The ShapeType the objects should have (generated by the @ng-org/shex-orm tool).
scope
The Scope as graph string or scope object with graphs and subjects.
string | Scope | undefined
Returns
A DeepSignalSet with the orm objects or an empty set, if still loading.
If the scope is explicitly set to undefined, an empty set is returned which errors
if you try to make modifications on it.
Example
<script lang="ts">
// Gets all expense objects with `@id` <s1 IRI> or <s2 IRI> and `@graph` <g1 NURI> or <g2 NURI>
const expenses: DeepSignal<Set<Expense>> = useShape(ExpenseShapeType,
{graphs: ["<g1 NURI>", "<g2 NURI>"],
subjects: ["<s1 NURI>", "<s2 NURI>"]});
const expensesSorted = computed(() => expenses.sort((a, b) =>
a.dateOfPurchase.localeCompare(b.dateOfPurchase)
));
const createExpense = () => {
expenses.add({
"@graph": `<graph NURI>`,
"@type": "http://example.org/Expense",
"@id": "", // Assigns ID automatically, if set to "".
title: "New expense",
dateOfPurchase: obj.dateOfPurchase ?? new Date().toISOString(),
});
};
// Note that if you use `@id` (the subject IRI) as key, you need to ensure that it is unique within your scope.
// If it is not (i.e. there are two graphs with the same subject), use the combination of `@graph` and `@id`.
</script>
<section>
<div>
<button on:click={() => createExpense()}>
+ Add expense
</button>
{# if expensesSorted.length === 0}
<p>
No expense yet.
</p>
{:else}
{#each expensesSorted as expense, index (expense['@id']) }
<ExpenseCard
expense={expense}
/>
{/each}
{/if}
</div>
</section>
In the ExpenseCard component:
<script lang="ts">
let {
expense,
}: { expense: DeepSignal<Expense>; } = $props();
</script>
<div>
<input
bind:value={expense.title}
/>
</div>
vueUseDiscrete()
vueUseDiscrete<
T>(documentId):ToRefs<{doc:T; }>
Defined in: sdk/js/orm/src/frontendAdapters/vue/useDiscrete.ts:118
Hook to subscribe to an existing discrete (JSON) CRDT document. You can modify the returned object like any other JSON object. Changes are immediately reflected in the CRDT document.
Establishes a 2-way binding: Modifications to the object are immediately committed, changes coming from the engine (or other components) cause an immediate rerender.
In comparison to useShape, discrete CRDTs are untyped.
You can put any JSON data inside and need to validate the schema yourself.
Type Parameters
T
T = DiscreteRoot
Parameters
documentId
MaybeRefOrGetter<string | undefined>
The NURI of the CRDT document or undefined as MaybeRefOrGetter.
Returns
ToRefs<{ doc: T; }>
An object that contains as data the reactive DeepSignal object or undefined if not loaded yet or documentId is undefined.
Example
<script lang="ts">
// We assume you have created a CRDT document already, as below.
// const documentId = await ng.doc_create(
// session_id,
// crdt, // "Automerge" | "YMap" | "YArray"
// crdt === "Automerge" ? "data:json" : crdt === "YMap ? "data:map" : "data:array",
// "store",
// undefined
// );
const { doc } = useDiscrete(documentId);
// If document is new, we need to set up the basic structure.
effect(() => {
if (doc.value && !doc.value.expenses) {
doc.value.expenses = [];
}
});
const createExpense = () => {
// Note that we use *expense["@id"]* as a key in the expense list.
// Every object added to a CRDT array gets a stable `@id` property assigned
// which you can use for referencing objects in arrays even as
// objects are removed or added from the array.
// The `@id` is an NURI with the schema `<documentId>:d:<object-specific id>`.
// Since the `@id` is generated in the engine, the object is
// *preliminarily given a mock id* which will be replaced immediately.
doc.value.expenses.push({
title: "New expense",
date: new Date().toISOString(),
});
};
</script>
<template>
<div v-if="!doc">Loading...</div>
<div v-else>
<p v-if="expenses.length === 0">No expenses yet.</p>
<template v-else>
<button @click="{()" ="">createExpense()} > + Add expense</button>
<ExpenseCard
v-for="expense in expenses"
:key="expense['@id']"
:expense="expense"
/>
</template>
</div>
</template>
In the ExpenseCard component:
<script lang="ts">
const { expense } = defineProps<{
expense: DeepSignal<Expense>;
}>();
// If you modify expense in the component,
// the changes are immediately propagated to other consuming components
// And persisted in the database.
</script>
<template>
<input v-model="expense.title" placeholder="Expense title" />
</template>
vueUseShape()
vueUseShape<
T>(shape,scope):DeepSignalSet<T>
Defined in: sdk/js/orm/src/frontendAdapters/vue/useShape.ts:89
Hook to subscribe to RDF data in the graph database using a shape, see ShapeType. The returned objects are as easy to use as other TypeScript objects.
Returns a DeepSignalSet of objects matching the shape and that are within the scope. Establishes a 2-way binding: Modifications to the object are immediately committed, changes coming from the backend (or other components) cause an immediate rerender.
Type Parameters
T
T extends BaseType
Parameters
shape
ShapeType<T>
The ShapeType the objects should have (generated by the shex-orm tool).
scope
The Scope as graph string or scope object with graphs and subjects.
string | Scope | undefined
Returns
A DeepSignalSet with the orm objects or an empty set, if still loading.
If the scope is explicitly set to undefined, an empty set is returned which errors
if you try to make modifications on it.
Example
<script lang="ts">
// Contains all expense objects with `@id` <s1 IRI> or <s2 IRI> and `@graph` <g1 NURI> or <g2 NURI>
const expenses: DeepSignal<Set<Expense>> = useShape(ExpenseShapeType, {
graphs: ["<g1 NURI>", "<g2 NURI>"],
subjects: ["<s1 IRI>", "<s2 IRI>"],
});
const expensesSorted = computed(() =>
[...expenses].sort((a, b) =>
a.dateOfPurchase.localeCompare(b.dateOfPurchase),
),
);
// Simply call expenses.add({"@graph": "<g1 or g2 NURI>", "@id": "", title: "Example title"}), to add new elements.
// Leave `@id` an empty string to auto-generate a subject NURI (adjust your scope accordingly).
// Note that if you use `@id` (the subject IRI) as key, you need to ensure that it is unique within your scope.
// If it is not (i.e. there are two graphs with the same subject), use the combination of `@graph` and `@id`.
</script>
<template>
<div>
<p v-if="expensesSorted.length === 0">No expenses yet.</p>
<template v-else>
<ExpenseCard
v-for="expense in expensesSorted"
:key="expense['@id'])"
:expense="expense"
/>
</template>
</div>
</template>
In the ExpenseCard component:
<script lang="ts">
const { expense } = defineProps<{
expense: DeepSignal<Expense>;
}>();
// If you modify expense in the component,
// the changes are immediately propagated to other consuming components.
// And persisted in the database.
</script>
<template>
<input v-model="expense.title" placeholder="Expense title" />
</template>
watch()
watch<
T>(source,callback,options?):object
Defined in: sdk/js/alien-deepsignals/src/watch.ts:89
Watch for changes to a deepSignal.
Whenever a change is made, callback is called with the patches describing the change and the new value.
If you set triggerInstantly, the callback is called on every property change.
If not, all changes are aggregated and callback is called in a microtask when
the current task finishes, e.g. await is called (meaning it supports batching).
When objects are added to Sets, their synthetic ID (usually @id) becomes part of the patch path. This allows patches to uniquely identify which Set entry is being mutated.
const state = deepSignal(
{ s: new Set() },
{ ...}
);
watch(state, ({ patches }) => {
console.log(JSON.stringify(patches));
});
state.s.add({ data: "test" });
// Will log:
// [
// {"path":["s","did:ng:o:123"],"op":"add","type":"object"},
// {"path":["s","did:ng:o:123","@id"],"op":"add","value":"did:ng:o:123"},
// {"path":["s","did:ng:o:123","data"],"op":"add","value":"test"}
// ]
state.s.getById("did:ng:o:123")!.data = "new value"
// Will log:
// [
// {"path":["s","did:ng:o:123","data"],"op":"add","value":"new value"}
// ]
Type Parameters
T
T extends object
Parameters
source
DeepSignalSet<T> | DeepSignalObject<T> | DeepSignal<T>
callback
options?
WatchOptions = {}
Returns
object
registerCleanup
registerCleanup:
RegisterCleanup
stopListening()
stopListening: () =>
void
Returns
void