@fireproof/core 0.19.120 → 0.19.121
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/deno.json +2 -2
- package/index.cjs +624 -1026
- package/index.cjs.map +1 -1
- package/index.d.cts +26 -60
- package/index.d.ts +26 -60
- package/index.js +394 -97
- package/index.js.map +1 -1
- package/metafile-cjs.json +1 -1
- package/metafile-esm.json +1 -1
- package/node/index.cjs +374 -0
- package/node/index.cjs.map +1 -0
- package/node/index.d.cts +43 -0
- package/node/index.d.ts +43 -0
- package/node/index.js +279 -0
- package/node/index.js.map +1 -0
- package/node/{mem-filesystem.js → mem-filesystem-LPPT7QV5.js} +1 -1
- package/node/metafile-cjs.json +1 -1
- package/node/metafile-esm.json +1 -1
- package/package.json +16 -14
- package/react/index.cjs.map +1 -1
- package/react/index.d.cts +4 -33
- package/react/index.d.ts +4 -33
- package/react/index.js.map +1 -1
- package/react/metafile-cjs.json +1 -1
- package/react/metafile-esm.json +1 -1
- package/tests/blockstore/keyed-crypto.test.ts +4 -2
- package/tests/fireproof/config.test.ts +133 -142
- package/web/{gateway-impl.cjs → index.cjs} +58 -9
- package/web/index.cjs.map +1 -0
- package/web/index.d.cts +44 -0
- package/web/index.d.ts +44 -0
- package/web/{gateway-impl.js → index.js} +52 -5
- package/web/index.js.map +1 -0
- package/web/metafile-cjs.json +1 -1
- package/web/metafile-esm.json +1 -1
- package/chunk-7EWIAXTM.js +0 -7
- package/chunk-7EWIAXTM.js.map +0 -1
- package/chunk-F4FC6B2T.js +0 -63
- package/chunk-F4FC6B2T.js.map +0 -1
- package/chunk-PZ5AY32C.js +0 -10
- package/chunk-PZ5AY32C.js.map +0 -1
- package/chunk-RXC4JGJT.js +0 -301
- package/chunk-RXC4JGJT.js.map +0 -1
- package/gateway-C62S56GY.js +0 -66
- package/gateway-C62S56GY.js.map +0 -1
- package/gateway-VVS4QWDA.js +0 -145
- package/gateway-VVS4QWDA.js.map +0 -1
- package/key-bag-file-PWZ3QE7B.js +0 -55
- package/key-bag-file-PWZ3QE7B.js.map +0 -1
- package/key-bag-indexdb-SYG3YD4D.js +0 -51
- package/key-bag-indexdb-SYG3YD4D.js.map +0 -1
- package/node/mem-filesystem.cjs +0 -72
- package/node/mem-filesystem.cjs.map +0 -1
- package/node/mem-filesystem.d.cts +0 -25
- package/node/mem-filesystem.d.ts +0 -25
- package/node/node-filesystem.cjs +0 -86
- package/node/node-filesystem.cjs.map +0 -1
- package/node/node-filesystem.d.cts +0 -35
- package/node/node-filesystem.d.ts +0 -35
- package/node/node-filesystem.js +0 -44
- package/node/node-filesystem.js.map +0 -1
- package/utils-ZVVGAXFE.js +0 -13
- package/utils-ZVVGAXFE.js.map +0 -1
- package/web/gateway-impl.cjs.map +0 -1
- package/web/gateway-impl.d.cts +0 -31
- package/web/gateway-impl.d.ts +0 -31
- package/web/gateway-impl.js.map +0 -1
- /package/node/{mem-filesystem.js.map → mem-filesystem-LPPT7QV5.js.map} +0 -0
package/react/index.d.ts
CHANGED
|
@@ -1,39 +1,10 @@
|
|
|
1
|
-
import { Database, ConfigOpts, DocTypes, IndexKeyType
|
|
2
|
-
import { EventLink } from '@fireproof/vendor/@web3-storage/pail/clock/api';
|
|
3
|
-
import { Operation } from '@fireproof/vendor/@web3-storage/pail/crdt/api';
|
|
4
|
-
import { Link, Version } from 'multiformats';
|
|
1
|
+
import { Database, ConfigOpts, DocTypes, IndexKeyType, DocFragment, DocWithId, IndexRow, MapFn, QueryOpts, AllDocsQueryOpts, ClockHead, ChangesOptions, DocSet, DocResponse } from '@fireproof/core';
|
|
5
2
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
type ClockLink = EventLink<Operation>;
|
|
9
|
-
type ClockHead = ClockLink[];
|
|
10
|
-
type DocFragment = Uint8Array | string | number | boolean | null | AnyLink | DocFragment[] | object;
|
|
11
|
-
type KeyLiteral = string | number | boolean;
|
|
12
|
-
type IndexKeyType = KeyLiteral | KeyLiteral[];
|
|
13
|
-
interface QueryOpts<K extends IndexKeyType> {
|
|
14
|
-
readonly descending?: boolean;
|
|
15
|
-
readonly limit?: number;
|
|
16
|
-
includeDocs?: boolean;
|
|
17
|
-
readonly range?: [IndexKeyType, IndexKeyType];
|
|
18
|
-
readonly key?: DocFragment;
|
|
19
|
-
readonly keys?: DocFragment[];
|
|
20
|
-
prefix?: IndexKeyType;
|
|
21
|
-
}
|
|
22
|
-
interface AllDocsQueryOpts extends QueryOpts<string> {
|
|
23
|
-
readonly key?: string;
|
|
24
|
-
readonly keys?: string[];
|
|
25
|
-
prefix?: string;
|
|
26
|
-
}
|
|
27
|
-
interface ChangesOptions {
|
|
28
|
-
readonly dirty?: boolean;
|
|
29
|
-
readonly limit?: number;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
interface LiveQueryResult<T extends DocTypes, K extends IndexKeyType$1, R extends DocFragment$1 = T> {
|
|
3
|
+
interface LiveQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> {
|
|
33
4
|
readonly docs: DocWithId<T>[];
|
|
34
5
|
readonly rows: IndexRow<K, T, R>[];
|
|
35
6
|
}
|
|
36
|
-
type UseLiveQuery = <T extends DocTypes, K extends IndexKeyType
|
|
7
|
+
type UseLiveQuery = <T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(mapFn: string | MapFn<T>, query?: QueryOpts<K>, initialRows?: IndexRow<K, T, R>[]) => LiveQueryResult<T, K, R>;
|
|
37
8
|
interface AllDocsResult<T extends DocTypes> {
|
|
38
9
|
readonly docs: DocWithId<T>[];
|
|
39
10
|
}
|
|
@@ -69,7 +40,7 @@ interface TLUseDocument {
|
|
|
69
40
|
declare const useDocument: TLUseDocument;
|
|
70
41
|
|
|
71
42
|
interface TLUseLiveQuery {
|
|
72
|
-
<T extends DocTypes, K extends IndexKeyType
|
|
43
|
+
<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T>(...args: Parameters<UseLiveQuery>): LiveQueryResult<T, K, R>;
|
|
73
44
|
database: Database;
|
|
74
45
|
}
|
|
75
46
|
declare const useLiveQuery: TLUseLiveQuery;
|
package/react/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/react/useFireproof.ts","../../../src/react/useDocument.ts","../../../src/react/useLiveQuery.ts","../../../src/react/useAllDocs.ts","../../../src/react/useChanges.ts"],"sourcesContent":["import type {\n ConfigOpts,\n Database,\n DocFragment,\n DocResponse,\n DocSet,\n DocTypes,\n DocWithId,\n IndexKeyType,\n IndexRow,\n MapFn,\n QueryOpts,\n} from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { AllDocsQueryOpts, ChangesOptions, ClockHead } from \"../types.js\";\n\nexport interface LiveQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> {\n readonly docs: DocWithId<T>[];\n readonly rows: IndexRow<K, T, R>[];\n}\n\nexport type UseLiveQuery = <T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: string | MapFn<T>,\n query?: QueryOpts<K>,\n initialRows?: IndexRow<K, T, R>[],\n) => LiveQueryResult<T, K, R>;\n\nexport interface AllDocsResult<T extends DocTypes> {\n readonly docs: DocWithId<T>[];\n}\n\nexport interface ChangesResult<T extends DocTypes> {\n readonly docs: DocWithId<T>[];\n}\n\nexport type UseAllDocs = <T extends DocTypes>(query?: AllDocsQueryOpts) => AllDocsResult<T>;\n\nexport type UseChanges = <T extends DocTypes>(since: ClockHead, opts: ChangesOptions) => ChangesResult<T>;\n\ninterface UpdateDocFnOptions {\n readonly replace?: boolean;\n readonly reset?: boolean;\n}\n\ntype UpdateDocFn<T extends DocTypes> = (newDoc?: DocSet<T>, options?: UpdateDocFnOptions) => void;\n\ntype StoreDocFn<T extends DocTypes> = (existingDoc?: DocWithId<T>) => Promise<DocResponse>;\n\ntype DeleteDocFn<T extends DocTypes> = (existingDoc?: DocWithId<T>) => Promise<DocResponse>;\n\nexport type UseDocumentResult<T extends DocTypes> = [DocWithId<T>, UpdateDocFn<T>, StoreDocFn<T>, DeleteDocFn<T>];\n\nexport type UseDocumentInitialDocOrFn<T extends DocTypes> = DocSet<T> | (() => DocSet<T>);\nexport type UseDocument = <T extends DocTypes>(initialDocOrFn: UseDocumentInitialDocOrFn<T>) => UseDocumentResult<T>;\n\nexport interface UseFireproof {\n readonly database: Database;\n /**\n * ## Summary\n *\n * React hook that provides the ability to create/update/save new Fireproof documents into your custom Fireproof database.\n * The creation occurs when you do not pass in an `_id` as part of your initial document -- the database will assign a new\n * one when you call the provided `save` handler. The hook also provides generics support so you can inline your custom type into\n * the invocation to receive type-safety and auto-complete support in your IDE.\n *\n * ## Usage\n *\n * ```tsx\n * const [todo, setTodo, saveTodo] = useDocument<Todo>({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n *\n * const [doc, setDoc, saveDoc] = useDocument<Customer>({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * })\n * ```\n *\n * ## Overview\n *\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useDocument: UseDocument;\n /**\n * ## Summary\n * React hook that provides access to live query results, enabling real-time updates in your app.\n *\n * ## Usage\n * ```tsx\n * const result = useLiveQuery(\"date\"); // using string key\n * const result = useLiveQuery('date', { limit: 10, descending: true }) // key + options\n * const result = useLiveQuery<CustomType>(\"date\"); // using generics\n * const result = useLiveQuery((doc) => doc.date)); // using map function\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useLiveQuery: UseLiveQuery;\n /**\n * ## Summary\n * React hook that provides access to all documents in the database, sorted by `_id`.\n *\n * ## Usage\n * ```tsx\n * const result = useAllDocs({ limit: 10, descending: true }); // with options\n * const result = useAllDocs(); // without options\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useAllDocs: UseAllDocs;\n /**\n * ## Summary\n * React hook that provides access to all new documents in the database added since the last time the changes was called\n *\n * ## Usage\n * ```tsx\n * const result = useChanges(prevresult.clock,{limit:10}); // with options\n * const result = useChanges(); // without options\n * const database = useChanges.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs`, `useChanges` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useChanges: UseChanges;\n}\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\n\n/**\n *\n * ## Summary\n *\n * React hook to create a custom-named Fireproof database and provides the utility hooks to query against it.\n *\n * ## Usage\n * ```tsx\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\");\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\", { ...options });\n * ```\n *\n * ## Overview\n *\n * TL;DR: Only use this hook if you need to configure a database name other than the default `useFireproof`.\n *\n * For most applications, using the `useLiveQuery` or `useDocument` hooks exported from `use-fireproof` should\n * suffice for the majority of use-cases. Under the hood, they act against a database named `useFireproof` instantiated with\n * default configurations. However, if you need to do a custom database setup or configure a database name more to your liking\n * than the default `useFireproof`, then use `useFireproof` as it exists for that purpose. It will provide you with the\n * custom database accessor and *lexically scoped* versions of `useLiveQuery` and `useDocument` that act against said\n * custom database.\n *\n */\nexport function useFireproof(name: string | Database = \"useFireproof\", config: ConfigOpts = {}): UseFireproof {\n const database = typeof name === \"string\" ? fireproof(name, config) : name;\n\n function useDocument<T extends DocTypes>(initialDocOrFn: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n let initialDoc: DocSet<T>;\n if (typeof initialDocOrFn === \"function\") {\n initialDoc = initialDocOrFn();\n } else {\n initialDoc = initialDocOrFn;\n }\n\n // We purposely refetch the docId everytime to check if it has changed\n const docId = initialDoc._id ?? \"\";\n\n // We do not want to force consumers to memoize their initial document so we do it for them.\n // We use the stringified generator function to ensure that the memoization is stable across renders.\n // const initialDoc = useMemo(initialDocFn, [initialDocFn.toString()]);\n const [doc, setDoc] = useState(initialDoc);\n\n const refreshDoc = useCallback(async () => {\n // todo add option for mvcc checks\n const doc = docId ? await database.get<T>(docId).catch(() => initialDoc) : initialDoc;\n setDoc(doc);\n }, [docId]);\n\n const saveDoc: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n const res = await database.put(existingDoc ?? doc);\n // If the document was created, then we need to update the local state with the new `_id`\n if (!existingDoc && !doc._id) setDoc((d) => ({ ...d, _id: res.id }));\n return res;\n },\n [doc],\n );\n\n const deleteDoc: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? docId;\n const doc = await database.get<T>(id).catch(() => undefined);\n if (!doc) throw database.logger.Error().Str(\"id\", id).Msg(`Document not found`).AsError();\n const res = await database.del(id);\n setDoc(initialDoc);\n return res;\n },\n [docId, initialDoc],\n );\n\n const updateDoc: UpdateDocFn<T> = useCallback(\n (newDoc, opts = { replace: false, reset: false }) => {\n if (!newDoc) return void (opts.reset ? setDoc(initialDoc) : refreshDoc());\n setDoc((d) => (opts.replace ? (newDoc as DocWithId<T>) : { ...d, ...newDoc }));\n },\n [refreshDoc, initialDoc],\n );\n\n useEffect(() => {\n if (!docId) return;\n return database.subscribe((changes) => {\n if (changes.find((c) => c._id === docId)) {\n void refreshDoc(); // todo use change.value\n }\n });\n }, [docId, refreshDoc]);\n\n useEffect(() => {\n void refreshDoc();\n }, [refreshDoc]);\n\n return [{ _id: docId, ...doc }, updateDoc, saveDoc, deleteDoc];\n }\n\n function useLiveQuery<T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: MapFn<T> | string,\n query = {},\n initialRows: IndexRow<K, T, R>[] = [],\n ): LiveQueryResult<T, K, R> {\n const [result, setResult] = useState<LiveQueryResult<T, K, R>>(() => ({\n rows: initialRows,\n docs: initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r),\n }));\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.query<K, T, R>(mapFn, query);\n setResult({ ...res, docs: res.rows.map((r) => r.doc as DocWithId<T>) });\n }, [mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n function useAllDocs<T extends DocTypes>(query: AllDocsQueryOpts = {}): AllDocsResult<T> {\n const [result, setResult] = useState<AllDocsResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.allDocs<T>(query);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n function useChanges<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): ChangesResult<T> {\n const [result, setResult] = useState<ChangesResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(opts), [opts]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.changes<T>(since, opts);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [since, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n","import { Database, DocTypes, DocWithId } from \"@fireproof/core\";\n\nimport { UseDocument, UseDocumentResult, useFireproof } from \"./useFireproof.js\";\n\nexport interface TLUseDocument {\n <T extends DocTypes>(initialDoc: DocWithId<T>): UseDocumentResult<T>;\n database: Database;\n}\n\nfunction topLevelUseDocument(...args: Parameters<UseDocument>) {\n const { useDocument, database } = useFireproof();\n (topLevelUseDocument as TLUseDocument).database = database;\n return useDocument(...args);\n}\n\n/**\n * ## Summary\n *\n * React hook that provides the ability to create new Fireproof documents. The creation occurs when\n * you do not pass in an `_id` as part of your initial document -- the database will assign a new one when\n * you call the provided `save` handler This uses the default database named `useFireproof` under the hood which you can also\n * access via the `database` accessor.\n *\n * ## Usage\n *\n * ```tsx\n * const [todo, setTodo, saveTodo] = useDocument(() => ({\n * text: '',\n * date: Date.now(),\n * completed: false\n * }))\n *\n * const [doc, setDoc, saveDoc] = useDocument(() => ({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * }))\n *\n * const database = useDocument.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useDocument = topLevelUseDocument as TLUseDocument;\n","import { Database, DocFragment, DocTypes, IndexKeyType } from \"@fireproof/core\";\n\nimport { LiveQueryResult, useFireproof, UseLiveQuery } from \"./useFireproof.js\";\n\nexport interface TLUseLiveQuery {\n <T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T>(\n ...args: Parameters<UseLiveQuery>\n ): LiveQueryResult<T, K, R>;\n database: Database;\n}\n\nfunction topLevelUseLiveQuery(...args: Parameters<UseLiveQuery>) {\n const { useLiveQuery, database } = useFireproof();\n (topLevelUseLiveQuery as TLUseLiveQuery).database = database;\n return useLiveQuery(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to live query results, enabling real-time updates in your app. This uses\n * the default database named \"useFireproof\" under the hood which you can also access via the `database` accessor.\n *\n * ## Usage\n * ```tsx\n * const results = useLiveQuery(\"date\"); // using string\n * const results = useLiveQuery((doc) => doc.date)); // using map function\n * const database = useLiveQuery.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useLiveQuery = topLevelUseLiveQuery as TLUseLiveQuery;\n","import { Database, DocTypes } from \"@fireproof/core\";\n\nimport { AllDocsResult, useFireproof, UseAllDocs } from \"./useFireproof.js\";\n\nexport interface TLUseAllDocs {\n <T extends DocTypes>(...args: Parameters<UseAllDocs>): AllDocsResult<T>;\n database: Database;\n}\n\nfunction topLevelUseAllDocs(...args: Parameters<UseAllDocs>) {\n const { useAllDocs, database } = useFireproof();\n (topLevelUseAllDocs as TLUseAllDocs).database = database;\n return useAllDocs(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to all documents in the database, sorted by `_id`.\n *\n * ## Usage\n * ```tsx\n * const result = useAllDocs({ limit: 10, descending: true }); // with options\n * const result = useAllDocs(); // without options\n * const database = useAllDocs.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useAllDocs = topLevelUseAllDocs as TLUseAllDocs;\n","import { Database, DocTypes } from \"@fireproof/core\";\n\nimport { ChangesResult, useFireproof, UseChanges } from \"./useFireproof.js\";\n\nexport interface TLUseChanges {\n <T extends DocTypes>(...args: Parameters<UseChanges>): ChangesResult<T>;\n database: Database;\n}\n\nfunction topLevelUseChanges(...args: Parameters<UseChanges>) {\n const { useChanges, database } = useFireproof();\n (topLevelUseChanges as TLUseChanges).database = database;\n return useChanges(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to all new documents in the database added since the last time the changes was called\n *\n * ## Usage\n * ```tsx\n * const result = useChanges(prevresult.clock,{limit:10}); // with options\n * const result = useChanges(); // without options\n * const database = useChanges.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs`, `useChanges` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useChanges = topLevelUseChanges as TLUseChanges;\n"],"mappings":";AAaA,SAAS,iBAAiB;AAC1B,SAAS,aAAa,WAAW,SAAS,gBAAgB;AAoInD,IAAM,eAAe,CAAC;AA0BtB,SAAS,aAAa,OAA0B,gBAAgB,SAAqB,CAAC,GAAiB;AAC5G,QAAM,WAAW,OAAO,SAAS,WAAW,UAAU,MAAM,MAAM,IAAI;AAEtE,WAASA,aAAgC,gBAAoE;AAC3G,QAAI;AACJ,QAAI,OAAO,mBAAmB,YAAY;AACxC,mBAAa,eAAe;AAAA,IAC9B,OAAO;AACL,mBAAa;AAAA,IACf;AAGA,UAAM,QAAQ,WAAW,OAAO;AAKhC,UAAM,CAAC,KAAK,MAAM,IAAI,SAAS,UAAU;AAEzC,UAAM,aAAa,YAAY,YAAY;AAEzC,YAAMC,OAAM,QAAQ,MAAM,SAAS,IAAO,KAAK,EAAE,MAAM,MAAM,UAAU,IAAI;AAC3E,aAAOA,IAAG;AAAA,IACZ,GAAG,CAAC,KAAK,CAAC;AAEV,UAAM,UAAyB;AAAA,MAC7B,OAAO,gBAAgB;AACrB,cAAM,MAAM,MAAM,SAAS,IAAI,eAAe,GAAG;AAEjD,YAAI,CAAC,eAAe,CAAC,IAAI,IAAK,QAAO,CAAC,OAAO,EAAE,GAAG,GAAG,KAAK,IAAI,GAAG,EAAE;AACnE,eAAO;AAAA,MACT;AAAA,MACA,CAAC,GAAG;AAAA,IACN;AAEA,UAAM,YAA4B;AAAA,MAChC,OAAO,gBAAgB;AACrB,cAAM,KAAK,aAAa,OAAO;AAC/B,cAAMA,OAAM,MAAM,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M,MAAM,SAAS,QAAW,OAAO,IAAI;AACjD,gBAAU,EAAE,GAAG,KAAK,MAAM,IAAI,KAAK,IAAI,CAAC,MAAM,EAAE,KAAqB,EAAE,CAAC;AAAA,IAC1E,GAAG,CAAC,OAAO,WAAW,CAAC;AAEvB,cAAU,MAAM;AACd,kBAAY;AACZ,aAAO,SAAS,UAAU,WAAW;AAAA,IACvC,GAAG,CAAC,WAAW,CAAC;AAEhB,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,UAAU,cAAAF,eAAc,aAAAF,cAAa,YAAAG,aAAY,YAAAC,YAAW;AACvE;;;AC7SA,SAAS,uBAAuB,MAA+B;AAC7D,QAAM,EAAE,aAAAC,cAAa,SAAS,IAAI,aAAa;AAC/C,EAAC,oBAAsC,WAAW;AAClD,SAAOA,aAAY,GAAG,IAAI;AAC5B;AAkCO,IAAM,cAAc;;;ACpC3B,SAAS,wBAAwB,MAAgC;AAC/D,QAAM,EAAE,cAAAC,eAAc,SAAS,IAAI,aAAa;AAChD,EAAC,qBAAwC,WAAW;AACpD,SAAOA,cAAa,GAAG,IAAI;AAC7B;AAmBO,IAAM,eAAe;;;ACzB5B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;;;ACtB1B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;","names":["useDocument","doc","useLiveQuery","useAllDocs","useChanges","useDocument","useLiveQuery","useAllDocs","useChanges"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/react/useFireproof.ts","../../../src/react/useDocument.ts","../../../src/react/useLiveQuery.ts","../../../src/react/useAllDocs.ts","../../../src/react/useChanges.ts"],"sourcesContent":["import type {\n ConfigOpts,\n Database,\n DocFragment,\n DocResponse,\n DocSet,\n DocTypes,\n DocWithId,\n IndexKeyType,\n IndexRow,\n MapFn,\n QueryOpts,\n} from \"@fireproof/core\";\nimport { fireproof } from \"@fireproof/core\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AllDocsQueryOpts, ChangesOptions, ClockHead } from \"@fireproof/core\";\n\nexport interface LiveQueryResult<T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T> {\n readonly docs: DocWithId<T>[];\n readonly rows: IndexRow<K, T, R>[];\n}\n\nexport type UseLiveQuery = <T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: string | MapFn<T>,\n query?: QueryOpts<K>,\n initialRows?: IndexRow<K, T, R>[],\n) => LiveQueryResult<T, K, R>;\n\nexport interface AllDocsResult<T extends DocTypes> {\n readonly docs: DocWithId<T>[];\n}\n\nexport interface ChangesResult<T extends DocTypes> {\n readonly docs: DocWithId<T>[];\n}\n\nexport type UseAllDocs = <T extends DocTypes>(query?: AllDocsQueryOpts) => AllDocsResult<T>;\n\nexport type UseChanges = <T extends DocTypes>(since: ClockHead, opts: ChangesOptions) => ChangesResult<T>;\n\ninterface UpdateDocFnOptions {\n readonly replace?: boolean;\n readonly reset?: boolean;\n}\n\ntype UpdateDocFn<T extends DocTypes> = (newDoc?: DocSet<T>, options?: UpdateDocFnOptions) => void;\n\ntype StoreDocFn<T extends DocTypes> = (existingDoc?: DocWithId<T>) => Promise<DocResponse>;\n\ntype DeleteDocFn<T extends DocTypes> = (existingDoc?: DocWithId<T>) => Promise<DocResponse>;\n\nexport type UseDocumentResult<T extends DocTypes> = [DocWithId<T>, UpdateDocFn<T>, StoreDocFn<T>, DeleteDocFn<T>];\n\nexport type UseDocumentInitialDocOrFn<T extends DocTypes> = DocSet<T> | (() => DocSet<T>);\nexport type UseDocument = <T extends DocTypes>(initialDocOrFn: UseDocumentInitialDocOrFn<T>) => UseDocumentResult<T>;\n\nexport interface UseFireproof {\n readonly database: Database;\n /**\n * ## Summary\n *\n * React hook that provides the ability to create/update/save new Fireproof documents into your custom Fireproof database.\n * The creation occurs when you do not pass in an `_id` as part of your initial document -- the database will assign a new\n * one when you call the provided `save` handler. The hook also provides generics support so you can inline your custom type into\n * the invocation to receive type-safety and auto-complete support in your IDE.\n *\n * ## Usage\n *\n * ```tsx\n * const [todo, setTodo, saveTodo] = useDocument<Todo>({\n * text: '',\n * date: Date.now(),\n * completed: false\n * })\n *\n * const [doc, setDoc, saveDoc] = useDocument<Customer>({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * })\n * ```\n *\n * ## Overview\n *\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useDocument: UseDocument;\n /**\n * ## Summary\n * React hook that provides access to live query results, enabling real-time updates in your app.\n *\n * ## Usage\n * ```tsx\n * const result = useLiveQuery(\"date\"); // using string key\n * const result = useLiveQuery('date', { limit: 10, descending: true }) // key + options\n * const result = useLiveQuery<CustomType>(\"date\"); // using generics\n * const result = useLiveQuery((doc) => doc.date)); // using map function\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useLiveQuery: UseLiveQuery;\n /**\n * ## Summary\n * React hook that provides access to all documents in the database, sorted by `_id`.\n *\n * ## Usage\n * ```tsx\n * const result = useAllDocs({ limit: 10, descending: true }); // with options\n * const result = useAllDocs(); // without options\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useAllDocs: UseAllDocs;\n /**\n * ## Summary\n * React hook that provides access to all new documents in the database added since the last time the changes was called\n *\n * ## Usage\n * ```tsx\n * const result = useChanges(prevresult.clock,{limit:10}); // with options\n * const result = useChanges(); // without options\n * const database = useChanges.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs`, `useChanges` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\n readonly useChanges: UseChanges;\n}\n\n/**\n * @deprecated Use the `useFireproof` hook instead\n */\nexport const FireproofCtx = {} as UseFireproof;\n\n/**\n *\n * ## Summary\n *\n * React hook to create a custom-named Fireproof database and provides the utility hooks to query against it.\n *\n * ## Usage\n * ```tsx\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\");\n * const { database, useLiveQuery, useDocument } = useFireproof(\"dbname\", { ...options });\n * ```\n *\n * ## Overview\n *\n * TL;DR: Only use this hook if you need to configure a database name other than the default `useFireproof`.\n *\n * For most applications, using the `useLiveQuery` or `useDocument` hooks exported from `use-fireproof` should\n * suffice for the majority of use-cases. Under the hood, they act against a database named `useFireproof` instantiated with\n * default configurations. However, if you need to do a custom database setup or configure a database name more to your liking\n * than the default `useFireproof`, then use `useFireproof` as it exists for that purpose. It will provide you with the\n * custom database accessor and *lexically scoped* versions of `useLiveQuery` and `useDocument` that act against said\n * custom database.\n *\n */\nexport function useFireproof(name: string | Database = \"useFireproof\", config: ConfigOpts = {}): UseFireproof {\n const database = typeof name === \"string\" ? fireproof(name, config) : name;\n\n function useDocument<T extends DocTypes>(initialDocOrFn: UseDocumentInitialDocOrFn<T>): UseDocumentResult<T> {\n let initialDoc: DocSet<T>;\n if (typeof initialDocOrFn === \"function\") {\n initialDoc = initialDocOrFn();\n } else {\n initialDoc = initialDocOrFn;\n }\n\n // We purposely refetch the docId everytime to check if it has changed\n const docId = initialDoc._id ?? \"\";\n\n // We do not want to force consumers to memoize their initial document so we do it for them.\n // We use the stringified generator function to ensure that the memoization is stable across renders.\n // const initialDoc = useMemo(initialDocFn, [initialDocFn.toString()]);\n const [doc, setDoc] = useState(initialDoc);\n\n const refreshDoc = useCallback(async () => {\n // todo add option for mvcc checks\n const doc = docId ? await database.get<T>(docId).catch(() => initialDoc) : initialDoc;\n setDoc(doc);\n }, [docId]);\n\n const saveDoc: StoreDocFn<T> = useCallback(\n async (existingDoc) => {\n const res = await database.put(existingDoc ?? doc);\n // If the document was created, then we need to update the local state with the new `_id`\n if (!existingDoc && !doc._id) setDoc((d) => ({ ...d, _id: res.id }));\n return res;\n },\n [doc],\n );\n\n const deleteDoc: DeleteDocFn<T> = useCallback(\n async (existingDoc) => {\n const id = existingDoc?._id ?? docId;\n const doc = await database.get<T>(id).catch(() => undefined);\n if (!doc) throw database.logger.Error().Str(\"id\", id).Msg(`Document not found`).AsError();\n const res = await database.del(id);\n setDoc(initialDoc);\n return res;\n },\n [docId, initialDoc],\n );\n\n const updateDoc: UpdateDocFn<T> = useCallback(\n (newDoc, opts = { replace: false, reset: false }) => {\n if (!newDoc) return void (opts.reset ? setDoc(initialDoc) : refreshDoc());\n setDoc((d) => (opts.replace ? (newDoc as DocWithId<T>) : { ...d, ...newDoc }));\n },\n [refreshDoc, initialDoc],\n );\n\n useEffect(() => {\n if (!docId) return;\n return database.subscribe((changes) => {\n if (changes.find((c) => c._id === docId)) {\n void refreshDoc(); // todo use change.value\n }\n });\n }, [docId, refreshDoc]);\n\n useEffect(() => {\n void refreshDoc();\n }, [refreshDoc]);\n\n return [{ _id: docId, ...doc }, updateDoc, saveDoc, deleteDoc];\n }\n\n function useLiveQuery<T extends DocTypes, K extends IndexKeyType = string, R extends DocFragment = T>(\n mapFn: MapFn<T> | string,\n query = {},\n initialRows: IndexRow<K, T, R>[] = [],\n ): LiveQueryResult<T, K, R> {\n const [result, setResult] = useState<LiveQueryResult<T, K, R>>(() => ({\n rows: initialRows,\n docs: initialRows.map((r) => r.doc).filter((r): r is DocWithId<T> => !!r),\n }));\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n const mapFnString = useMemo(() => mapFn.toString(), [mapFn]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.query<K, T, R>(mapFn, query);\n setResult({ ...res, docs: res.rows.map((r) => r.doc as DocWithId<T>) });\n }, [mapFnString, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n function useAllDocs<T extends DocTypes>(query: AllDocsQueryOpts = {}): AllDocsResult<T> {\n const [result, setResult] = useState<AllDocsResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(query), [query]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.allDocs<T>(query);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n function useChanges<T extends DocTypes>(since: ClockHead = [], opts: ChangesOptions = {}): ChangesResult<T> {\n const [result, setResult] = useState<ChangesResult<T>>({\n docs: [],\n });\n\n const queryString = useMemo(() => JSON.stringify(opts), [opts]);\n\n const refreshRows = useCallback(async () => {\n const res = await database.changes<T>(since, opts);\n setResult({ ...res, docs: res.rows.map((r) => r.value as DocWithId<T>) });\n }, [since, queryString]);\n\n useEffect(() => {\n refreshRows(); // Initial data fetch\n return database.subscribe(refreshRows);\n }, [refreshRows]);\n\n return result;\n }\n\n return { database, useLiveQuery, useDocument, useAllDocs, useChanges };\n}\n","import { Database, DocTypes, DocWithId } from \"@fireproof/core\";\n\nimport { UseDocument, UseDocumentResult, useFireproof } from \"./useFireproof.js\";\n\nexport interface TLUseDocument {\n <T extends DocTypes>(initialDoc: DocWithId<T>): UseDocumentResult<T>;\n database: Database;\n}\n\nfunction topLevelUseDocument(...args: Parameters<UseDocument>) {\n const { useDocument, database } = useFireproof();\n (topLevelUseDocument as TLUseDocument).database = database;\n return useDocument(...args);\n}\n\n/**\n * ## Summary\n *\n * React hook that provides the ability to create new Fireproof documents. The creation occurs when\n * you do not pass in an `_id` as part of your initial document -- the database will assign a new one when\n * you call the provided `save` handler This uses the default database named `useFireproof` under the hood which you can also\n * access via the `database` accessor.\n *\n * ## Usage\n *\n * ```tsx\n * const [todo, setTodo, saveTodo] = useDocument(() => ({\n * text: '',\n * date: Date.now(),\n * completed: false\n * }))\n *\n * const [doc, setDoc, saveDoc] = useDocument(() => ({\n * _id: `${props.customerId}-profile`, // you can imagine `customerId` as a prop passed in\n * name: \"\",\n * company: \"\",\n * startedAt: Date.now()\n * }))\n *\n * const database = useDocument.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useDocument = topLevelUseDocument as TLUseDocument;\n","import { Database, DocFragment, DocTypes, IndexKeyType } from \"@fireproof/core\";\n\nimport { LiveQueryResult, useFireproof, UseLiveQuery } from \"./useFireproof.js\";\n\nexport interface TLUseLiveQuery {\n <T extends DocTypes, K extends IndexKeyType, R extends DocFragment = T>(\n ...args: Parameters<UseLiveQuery>\n ): LiveQueryResult<T, K, R>;\n database: Database;\n}\n\nfunction topLevelUseLiveQuery(...args: Parameters<UseLiveQuery>) {\n const { useLiveQuery, database } = useFireproof();\n (topLevelUseLiveQuery as TLUseLiveQuery).database = database;\n return useLiveQuery(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to live query results, enabling real-time updates in your app. This uses\n * the default database named \"useFireproof\" under the hood which you can also access via the `database` accessor.\n *\n * ## Usage\n * ```tsx\n * const results = useLiveQuery(\"date\"); // using string\n * const results = useLiveQuery((doc) => doc.date)); // using map function\n * const database = useLiveQuery.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useLiveQuery` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useLiveQuery = topLevelUseLiveQuery as TLUseLiveQuery;\n","import { Database, DocTypes } from \"@fireproof/core\";\n\nimport { AllDocsResult, useFireproof, UseAllDocs } from \"./useFireproof.js\";\n\nexport interface TLUseAllDocs {\n <T extends DocTypes>(...args: Parameters<UseAllDocs>): AllDocsResult<T>;\n database: Database;\n}\n\nfunction topLevelUseAllDocs(...args: Parameters<UseAllDocs>) {\n const { useAllDocs, database } = useFireproof();\n (topLevelUseAllDocs as TLUseAllDocs).database = database;\n return useAllDocs(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to all documents in the database, sorted by `_id`.\n *\n * ## Usage\n * ```tsx\n * const result = useAllDocs({ limit: 10, descending: true }); // with options\n * const result = useAllDocs(); // without options\n * const database = useAllDocs.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs` and `useDocument` APIs. By default, Fireproof stores data in the browser's\n * local storage.\n */\nexport const useAllDocs = topLevelUseAllDocs as TLUseAllDocs;\n","import { Database, DocTypes } from \"@fireproof/core\";\n\nimport { ChangesResult, useFireproof, UseChanges } from \"./useFireproof.js\";\n\nexport interface TLUseChanges {\n <T extends DocTypes>(...args: Parameters<UseChanges>): ChangesResult<T>;\n database: Database;\n}\n\nfunction topLevelUseChanges(...args: Parameters<UseChanges>) {\n const { useChanges, database } = useFireproof();\n (topLevelUseChanges as TLUseChanges).database = database;\n return useChanges(...args);\n}\n\n/**\n * ## Summary\n * React hook that provides access to all new documents in the database added since the last time the changes was called\n *\n * ## Usage\n * ```tsx\n * const result = useChanges(prevresult.clock,{limit:10}); // with options\n * const result = useChanges(); // without options\n * const database = useChanges.database; // underlying \"useFireproof\" database accessor\n * ```\n *\n * ## Overview\n * Changes made via remote sync peers, or other members of your cloud replica group will appear automatically\n * when you use the `useAllDocs`, `useChanges` and `useDocument` APIs. By default, Fireproof stores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AU,WAAW;AAAA,IACvC,GAAG,CAAC,WAAW,CAAC;AAEhB,WAAO;AAAA,EACT;AAEA,SAAO,EAAE,UAAU,cAAAF,eAAc,aAAAF,cAAa,YAAAG,aAAY,YAAAC,YAAW;AACvE;;;AC7SA,SAAS,uBAAuB,MAA+B;AAC7D,QAAM,EAAE,aAAAC,cAAa,SAAS,IAAI,aAAa;AAC/C,EAAC,oBAAsC,WAAW;AAClD,SAAOA,aAAY,GAAG,IAAI;AAC5B;AAkCO,IAAM,cAAc;;;ACpC3B,SAAS,wBAAwB,MAAgC;AAC/D,QAAM,EAAE,cAAAC,eAAc,SAAS,IAAI,aAAa;AAChD,EAAC,qBAAwC,WAAW;AACpD,SAAOA,cAAa,GAAG,IAAI;AAC7B;AAmBO,IAAM,eAAe;;;ACzB5B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;;;ACtB1B,SAAS,sBAAsB,MAA8B;AAC3D,QAAM,EAAE,YAAAC,aAAY,SAAS,IAAI,aAAa;AAC9C,EAAC,mBAAoC,WAAW;AAChD,SAAOA,YAAW,GAAG,IAAI;AAC3B;AAkBO,IAAM,aAAa;","names":["useDocument","doc","useLiveQuery","useAllDocs","useChanges","useDocument","useLiveQuery","useAllDocs","useChanges"]}
|
package/react/metafile-cjs.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/react/useFireproof.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/react/useFireproof.ts":{"bytes":11390,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/useDocument.ts":{"bytes":1680,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useLiveQuery.ts":{"bytes":1409,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useAllDocs.ts":{"bytes":1146,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useChanges.ts":{"bytes":1191,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/index.ts":{"bytes":439,"imports":[{"path":"src/react/useDocument.ts","kind":"import-statement","original":"./useDocument.js"},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"},{"path":"src/react/useLiveQuery.ts","kind":"import-statement","original":"./useLiveQuery.js"},{"path":"src/react/useAllDocs.ts","kind":"import-statement","original":"./useAllDocs.js"},{"path":"src/react/useChanges.ts","kind":"import-statement","original":"./useChanges.js"}],"format":"esm"}},"outputs":{"dist/fireproof-core/react/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":22077},"dist/fireproof-core/react/index.cjs":{"imports":[{"path":"@fireproof/core","kind":"require-call","external":true},{"path":"react","kind":"require-call","external":true}],"exports":[],"entryPoint":"src/react/index.ts","inputs":{"src/react/index.ts":{"bytesInOutput":305},"src/react/useFireproof.ts":{"bytesInOutput":4237},"src/react/useDocument.ts":{"bytesInOutput":222},"src/react/useLiveQuery.ts":{"bytesInOutput":229},"src/react/useAllDocs.ts":{"bytesInOutput":215},"src/react/useChanges.ts":{"bytesInOutput":215}},"bytes":6390}}}
|
package/react/metafile-esm.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/react/useFireproof.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/react/useFireproof.ts":{"bytes":11390,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/react/useDocument.ts":{"bytes":1680,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useLiveQuery.ts":{"bytes":1409,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useAllDocs.ts":{"bytes":1146,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/useChanges.ts":{"bytes":1191,"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"}],"format":"esm"},"src/react/index.ts":{"bytes":439,"imports":[{"path":"src/react/useDocument.ts","kind":"import-statement","original":"./useDocument.js"},{"path":"src/react/useFireproof.ts","kind":"import-statement","original":"./useFireproof.js"},{"path":"src/react/useLiveQuery.ts","kind":"import-statement","original":"./useLiveQuery.js"},{"path":"src/react/useAllDocs.ts","kind":"import-statement","original":"./useAllDocs.js"},{"path":"src/react/useChanges.ts","kind":"import-statement","original":"./useChanges.js"}],"format":"esm"}},"outputs":{"dist/fireproof-core/react/index.js.map":{"imports":[],"exports":[],"inputs":{},"bytes":21510},"dist/fireproof-core/react/index.js":{"imports":[{"path":"@fireproof/core","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"exports":["FireproofCtx","useAllDocs","useChanges","useDocument","useFireproof","useLiveQuery"],"entryPoint":"src/react/index.ts","inputs":{"src/react/useFireproof.ts":{"bytesInOutput":3889},"src/react/useDocument.ts":{"bytesInOutput":222},"src/react/index.ts":{"bytesInOutput":0},"src/react/useLiveQuery.ts":{"bytesInOutput":229},"src/react/useAllDocs.ts":{"bytesInOutput":215},"src/react/useChanges.ts":{"bytesInOutput":215}},"bytes":5016}}}
|
|
@@ -3,6 +3,8 @@ import { BuildURI, Logger, MockLogger, runtimeFn, toCryptoRuntime, URI } from "@
|
|
|
3
3
|
import { base58btc } from "multiformats/bases/base58";
|
|
4
4
|
import { sha256 as hasher } from "multiformats/hashes/sha2";
|
|
5
5
|
import * as dagCodec from "@fireproof/vendor/@ipld/dag-cbor";
|
|
6
|
+
import type { KeyBagProviderIndexDB } from "@fireproof/core/web";
|
|
7
|
+
import type { KeyBagProviderFile } from "@fireproof/core/node";
|
|
6
8
|
|
|
7
9
|
describe("KeyBag", () => {
|
|
8
10
|
let url: URI;
|
|
@@ -88,11 +90,11 @@ describe("KeyBag", () => {
|
|
|
88
90
|
let diskBag2: rt.kb.KeyItem;
|
|
89
91
|
const provider = await kb.rt.getBag();
|
|
90
92
|
if (runtimeFn().isBrowser) {
|
|
91
|
-
const p = provider as
|
|
93
|
+
const p = provider as KeyBagProviderIndexDB;
|
|
92
94
|
diskBag = await p._prepare().then((db) => db.get("bag", name));
|
|
93
95
|
diskBag2 = await p._prepare().then((db) => db.get("bag", name2));
|
|
94
96
|
} else {
|
|
95
|
-
const p = provider as
|
|
97
|
+
const p = provider as KeyBagProviderFile;
|
|
96
98
|
const { sysFS } = await p._prepare(name);
|
|
97
99
|
|
|
98
100
|
diskBag = await sysFS.readfile((await p._prepare(name)).fName).then((data) => {
|
|
@@ -1,172 +1,163 @@
|
|
|
1
1
|
import { describe, it, expect, beforeAll } from "vitest";
|
|
2
|
-
import { dataDir, ensureSuperThis, fireproof, rt } from "@fireproof/core";
|
|
2
|
+
import { dataDir, ensureSuperThis, fireproof, rt, SysFileSystem } from "@fireproof/core";
|
|
3
3
|
import { runtimeFn, URI } from "@adviser/cement";
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
let _my_app = "my-app";
|
|
20
|
-
function my_app() {
|
|
21
|
-
return _my_app;
|
|
22
|
-
}
|
|
23
|
-
function params(store: string) {
|
|
24
|
-
return Object.entries({
|
|
25
|
-
store,
|
|
26
|
-
name: my_app(),
|
|
27
|
-
storekey: `@${my_app()}:${store}@`,
|
|
28
|
-
version: rt.FILESTORE_VERSION,
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
const sthis = ensureSuperThis();
|
|
32
|
-
beforeAll(async () => {
|
|
33
|
-
await sthis.start();
|
|
34
|
-
if (runtimeFn().isNodeIsh) {
|
|
35
|
-
const fpStorageUrl = sthis.env.get("FP_STORAGE_URL");
|
|
36
|
-
if (fpStorageUrl) {
|
|
37
|
-
const url = URI.from(fpStorageUrl);
|
|
38
|
-
_my_app = `my-app-${url.protocol.replace(/:$/, "")}:${url.getParam("fs") || "fs"}`;
|
|
39
|
-
}
|
|
5
|
+
let _my_app = "my-app";
|
|
6
|
+
function my_app() {
|
|
7
|
+
return _my_app;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
if (runtimeFn().isNodeIsh) {
|
|
11
|
+
describe("fireproof/config", () => {
|
|
12
|
+
function params(store: string) {
|
|
13
|
+
return Object.entries({
|
|
14
|
+
store,
|
|
15
|
+
name: my_app(),
|
|
16
|
+
storekey: `@${my_app()}:${store}@`,
|
|
17
|
+
version: rt.FILESTORE_VERSION,
|
|
18
|
+
});
|
|
40
19
|
}
|
|
41
|
-
|
|
20
|
+
const sthis = ensureSuperThis();
|
|
21
|
+
let getFileSystem: (url: URI) => Promise<SysFileSystem>;
|
|
22
|
+
beforeAll(async () => {
|
|
23
|
+
await sthis.start();
|
|
24
|
+
if (runtimeFn().isNodeIsh) {
|
|
25
|
+
const fpStorageUrl = sthis.env.get("FP_STORAGE_URL");
|
|
26
|
+
if (fpStorageUrl) {
|
|
27
|
+
const url = URI.from(fpStorageUrl);
|
|
28
|
+
_my_app = `my-app-${url.protocol.replace(/:$/, "")}:${url.getParam("fs") || "fs"}`;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const node = await import("@fireproof/core/node");
|
|
32
|
+
getFileSystem = node.getFileSystem;
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("node default", async () => {
|
|
36
|
+
const old = sthis.env.get("FP_STORAGE_URL");
|
|
37
|
+
sthis.env.delete("FP_STORAGE_URL");
|
|
38
|
+
let baseDir = dataDir(sthis, my_app()).pathname;
|
|
39
|
+
baseDir = sthis.pathOps.join(baseDir, rt.FILESTORE_VERSION, my_app());
|
|
40
|
+
|
|
41
|
+
const sysfs = await getFileSystem(URI.from(baseDir));
|
|
42
|
+
await sysfs.rm(baseDir, { recursive: true }).catch(() => {
|
|
43
|
+
/* */
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
expect(baseDir).toMatch(new RegExp(`/\\.fireproof/${rt.FILESTORE_VERSION}/${my_app()}`));
|
|
42
47
|
|
|
43
|
-
if (!runtimeFn().isNodeIsh) {
|
|
44
|
-
it("default", async () => {
|
|
45
48
|
const db = fireproof(my_app());
|
|
46
49
|
await db.put({ name: "my-app" });
|
|
47
50
|
expect(db.name).toBe(my_app());
|
|
51
|
+
const carStore = await db.blockstore.loader?.carStore();
|
|
52
|
+
|
|
53
|
+
for (const [param, value] of Object.entries({
|
|
54
|
+
store: "data",
|
|
55
|
+
name: my_app(),
|
|
56
|
+
storekey: `@${my_app()}:data@`,
|
|
57
|
+
version: rt.FILESTORE_VERSION,
|
|
58
|
+
})) {
|
|
59
|
+
expect(carStore?.url().getParam(param)).toBe(value);
|
|
60
|
+
}
|
|
61
|
+
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "data"))).isDirectory()).toBeTruthy();
|
|
48
62
|
|
|
49
63
|
const fileStore = await db.blockstore.loader?.fileStore();
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
64
|
+
for (const [param, value] of params("data")) {
|
|
65
|
+
expect(fileStore?.url().getParam(param)).toBe(value);
|
|
66
|
+
}
|
|
53
67
|
const metaStore = await db.blockstore.loader?.metaStore();
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
expect(carStore?.url().toString()).toMatch(
|
|
60
|
-
new RegExp(`indexdb://fp\\?name=my-app&store=data&storekey=%40my-app%3Adata%40&version=${rt.INDEXDB_VERSION}`),
|
|
61
|
-
);
|
|
62
|
-
|
|
68
|
+
for (const [param, value] of params("meta")) {
|
|
69
|
+
expect(metaStore?.url().getParam(param)).toBe(value);
|
|
70
|
+
}
|
|
71
|
+
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "meta"))).isDirectory()).toBeTruthy();
|
|
72
|
+
sthis.env.set("FP_STORAGE_URL", old);
|
|
63
73
|
await db.close();
|
|
64
74
|
});
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
it("node default", async () => {
|
|
68
|
-
const old = sthis.env.get("FP_STORAGE_URL");
|
|
69
|
-
sthis.env.delete("FP_STORAGE_URL");
|
|
70
|
-
let baseDir = dataDir(sthis, my_app()).pathname;
|
|
71
|
-
baseDir = sthis.pathOps.join(baseDir, rt.FILESTORE_VERSION, my_app());
|
|
72
|
-
|
|
73
|
-
const sysfs = await rt.getFileSystem(URI.from(baseDir));
|
|
74
|
-
await sysfs.rm(baseDir, { recursive: true }).catch(() => {
|
|
75
|
-
/* */
|
|
76
|
-
});
|
|
77
75
|
|
|
78
|
-
|
|
76
|
+
it("set by env", async () => {
|
|
77
|
+
const old = sthis.env.get("FP_STORAGE_URL");
|
|
78
|
+
const testUrl = URI.merge(`./dist/env`, old);
|
|
79
|
+
sthis.env.set("FP_STORAGE_URL", testUrl.toString());
|
|
79
80
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
expect(db.name).toBe(my_app());
|
|
83
|
-
const carStore = await db.blockstore.loader?.carStore();
|
|
81
|
+
let baseDir = dataDir(sthis, my_app()).pathname;
|
|
82
|
+
baseDir = sthis.pathOps.join(baseDir, rt.FILESTORE_VERSION, my_app());
|
|
84
83
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
version: rt.FILESTORE_VERSION,
|
|
90
|
-
})) {
|
|
91
|
-
expect(carStore?.url().getParam(param)).toBe(value);
|
|
92
|
-
}
|
|
93
|
-
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "data"))).isDirectory()).toBeTruthy();
|
|
84
|
+
const sysfs = await getFileSystem(testUrl);
|
|
85
|
+
await sysfs.rm(baseDir, { recursive: true }).catch(() => {
|
|
86
|
+
/* */
|
|
87
|
+
});
|
|
94
88
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
expect(
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
89
|
+
const db = fireproof(my_app());
|
|
90
|
+
await db.put({ name: "my-app" });
|
|
91
|
+
expect(db.name).toBe(my_app());
|
|
92
|
+
const carStore = await db.blockstore.loader?.carStore();
|
|
93
|
+
for (const [param, value] of params("data")) {
|
|
94
|
+
expect(carStore?.url().getParam(param)).toBe(value);
|
|
95
|
+
}
|
|
96
|
+
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "data"))).isDirectory()).toBeTruthy();
|
|
97
|
+
const fileStore = await db.blockstore.loader?.fileStore();
|
|
98
|
+
for (const [param, value] of params("data")) {
|
|
99
|
+
expect(fileStore?.url().getParam(param)).toBe(value);
|
|
100
|
+
}
|
|
101
|
+
const metaStore = await db.blockstore.loader?.metaStore();
|
|
102
|
+
for (const [param, value] of params("meta")) {
|
|
103
|
+
expect(metaStore?.url().getParam(param)).toBe(value);
|
|
104
|
+
}
|
|
105
|
+
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "meta"))).isDirectory()).toBeTruthy();
|
|
106
|
+
await db.close();
|
|
107
|
+
sthis.env.set("FP_STORAGE_URL", old);
|
|
108
|
+
});
|
|
107
109
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
sthis.env.set("FP_STORAGE_URL", testUrl.toString());
|
|
110
|
+
it("file path", async () => {
|
|
111
|
+
let baseDir = "./dist/data".replace(/\?.*$/, "").replace(/^file:\/\//, "");
|
|
112
|
+
baseDir = sthis.pathOps.join(baseDir, rt.FILESTORE_VERSION, my_app());
|
|
112
113
|
|
|
113
|
-
|
|
114
|
-
|
|
114
|
+
const base = "./dist/data";
|
|
115
|
+
const sysfs = await getFileSystem(URI.from(base));
|
|
116
|
+
await sysfs.rm(baseDir, { recursive: true }).catch(() => {
|
|
117
|
+
/* */
|
|
118
|
+
});
|
|
115
119
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
120
|
+
const db = fireproof(my_app(), { store: { stores: { base } } });
|
|
121
|
+
// console.log(`>>>>>>>>>>>>>>>file-path`)
|
|
122
|
+
await db.put({ name: "my-app" });
|
|
123
|
+
expect(db.name).toBe(my_app());
|
|
124
|
+
const carStore = await db.blockstore.loader?.carStore();
|
|
125
|
+
for (const [param, value] of params("data")) {
|
|
126
|
+
expect(carStore?.url().getParam(param)).toBe(value);
|
|
127
|
+
}
|
|
128
|
+
const fileStore = await db.blockstore.loader?.fileStore();
|
|
129
|
+
for (const [param, value] of params("data")) {
|
|
130
|
+
expect(fileStore?.url().getParam(param)).toBe(value);
|
|
131
|
+
}
|
|
132
|
+
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "data"))).isDirectory()).toBeTruthy();
|
|
133
|
+
const metaStore = await db.blockstore.loader?.metaStore();
|
|
134
|
+
for (const [param, value] of params("meta")) {
|
|
135
|
+
expect(metaStore?.url().getParam(param)).toBe(value);
|
|
136
|
+
}
|
|
137
|
+
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "meta"))).isDirectory()).toBeTruthy();
|
|
138
|
+
await db.close();
|
|
119
139
|
});
|
|
120
|
-
|
|
140
|
+
});
|
|
141
|
+
} else {
|
|
142
|
+
it("default", async () => {
|
|
121
143
|
const db = fireproof(my_app());
|
|
122
144
|
await db.put({ name: "my-app" });
|
|
123
145
|
expect(db.name).toBe(my_app());
|
|
124
|
-
|
|
125
|
-
for (const [param, value] of params("data")) {
|
|
126
|
-
expect(carStore?.url().getParam(param)).toBe(value);
|
|
127
|
-
}
|
|
128
|
-
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "data"))).isDirectory()).toBeTruthy();
|
|
146
|
+
|
|
129
147
|
const fileStore = await db.blockstore.loader?.fileStore();
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
148
|
+
expect(fileStore?.url().toString()).toMatch(
|
|
149
|
+
new RegExp(`indexdb://fp\\?name=my-app&store=data&storekey=%40my-app%3Adata%40&version=${rt.INDEXDB_VERSION}`),
|
|
150
|
+
);
|
|
133
151
|
const metaStore = await db.blockstore.loader?.metaStore();
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "meta"))).isDirectory()).toBeTruthy();
|
|
138
|
-
await db.close();
|
|
139
|
-
sthis.env.set("FP_STORAGE_URL", old);
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
it("file path", async () => {
|
|
143
|
-
let baseDir = "./dist/data".replace(/\?.*$/, "").replace(/^file:\/\//, "");
|
|
144
|
-
baseDir = sthis.pathOps.join(baseDir, rt.FILESTORE_VERSION, my_app());
|
|
145
|
-
|
|
146
|
-
const base = "./dist/data";
|
|
147
|
-
const sysfs = await rt.getFileSystem(URI.from(base));
|
|
148
|
-
await sysfs.rm(baseDir, { recursive: true }).catch(() => {
|
|
149
|
-
/* */
|
|
150
|
-
});
|
|
152
|
+
expect(metaStore?.url().toString()).toMatch(
|
|
153
|
+
new RegExp(`indexdb://fp\\?name=my-app&store=meta&storekey=%40my-app%3Ameta%40&version=${rt.INDEXDB_VERSION}`),
|
|
154
|
+
);
|
|
151
155
|
|
|
152
|
-
const db = fireproof(my_app(), { store: { stores: { base } } });
|
|
153
|
-
// console.log(`>>>>>>>>>>>>>>>file-path`)
|
|
154
|
-
await db.put({ name: "my-app" });
|
|
155
|
-
expect(db.name).toBe(my_app());
|
|
156
156
|
const carStore = await db.blockstore.loader?.carStore();
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
for (const [param, value] of params("data")) {
|
|
162
|
-
expect(fileStore?.url().getParam(param)).toBe(value);
|
|
163
|
-
}
|
|
164
|
-
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "data"))).isDirectory()).toBeTruthy();
|
|
165
|
-
const metaStore = await db.blockstore.loader?.metaStore();
|
|
166
|
-
for (const [param, value] of params("meta")) {
|
|
167
|
-
expect(metaStore?.url().getParam(param)).toBe(value);
|
|
168
|
-
}
|
|
169
|
-
expect((await sysfs.stat(sthis.pathOps.join(baseDir, "meta"))).isDirectory()).toBeTruthy();
|
|
157
|
+
expect(carStore?.url().toString()).toMatch(
|
|
158
|
+
new RegExp(`indexdb://fp\\?name=my-app&store=data&storekey=%40my-app%3Adata%40&version=${rt.INDEXDB_VERSION}`),
|
|
159
|
+
);
|
|
160
|
+
|
|
170
161
|
await db.close();
|
|
171
162
|
});
|
|
172
|
-
}
|
|
163
|
+
}
|
|
@@ -17,14 +17,20 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
17
|
};
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
|
|
20
|
-
// src/runtime/gateways/indexdb/web/
|
|
21
|
-
var
|
|
22
|
-
__export(
|
|
23
|
-
|
|
24
|
-
|
|
20
|
+
// src/runtime/gateways/indexdb/web/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
GatewayImpl: () => IndexDBGateway,
|
|
24
|
+
GatewayTestImpl: () => IndexDBTestGateway,
|
|
25
|
+
IndexDBGateway: () => IndexDBGateway,
|
|
26
|
+
IndexDBTestGateway: () => IndexDBTestGateway,
|
|
27
|
+
KeyBagProviderImpl: () => KeyBagProviderIndexDB,
|
|
28
|
+
KeyBagProviderIndexDB: () => KeyBagProviderIndexDB,
|
|
25
29
|
getIndexDBName: () => getIndexDBName
|
|
26
30
|
});
|
|
27
|
-
module.exports = __toCommonJS(
|
|
31
|
+
module.exports = __toCommonJS(index_exports);
|
|
32
|
+
|
|
33
|
+
// src/runtime/gateways/indexdb/web/gateway-impl.ts
|
|
28
34
|
var import_idb = require("idb");
|
|
29
35
|
var import_cement = require("@adviser/cement");
|
|
30
36
|
|
|
@@ -87,7 +93,7 @@ function getIndexDBName(iurl, sthis) {
|
|
|
87
93
|
dbName
|
|
88
94
|
};
|
|
89
95
|
}
|
|
90
|
-
var
|
|
96
|
+
var IndexDBGateway = class {
|
|
91
97
|
constructor(sthis) {
|
|
92
98
|
this.logger = (0, import_core.ensureLogger)(sthis, "IndexDBGateway");
|
|
93
99
|
this.sthis = sthis;
|
|
@@ -163,7 +169,7 @@ var IndexDBGatewayImpl = class {
|
|
|
163
169
|
});
|
|
164
170
|
}
|
|
165
171
|
};
|
|
166
|
-
var
|
|
172
|
+
var IndexDBTestGateway = class {
|
|
167
173
|
constructor(sthis) {
|
|
168
174
|
this.sthis = sthis;
|
|
169
175
|
this.logger = (0, import_core.ensureLogger)(sthis, "IndexDBTestStore", {});
|
|
@@ -180,4 +186,47 @@ var IndexDBTestStore = class {
|
|
|
180
186
|
return bytes;
|
|
181
187
|
}
|
|
182
188
|
};
|
|
183
|
-
|
|
189
|
+
|
|
190
|
+
// src/runtime/gateways/indexdb/web/key-bag-indexdb.ts
|
|
191
|
+
var import_idb2 = require("idb");
|
|
192
|
+
var import_cement2 = require("@adviser/cement");
|
|
193
|
+
var import_core2 = require("@fireproof/core");
|
|
194
|
+
var KeyBagProviderIndexDB = class {
|
|
195
|
+
constructor(url, sthis) {
|
|
196
|
+
this._db = new import_cement2.ResolveOnce();
|
|
197
|
+
this.sthis = sthis;
|
|
198
|
+
this.logger = sthis.logger;
|
|
199
|
+
this.url = url;
|
|
200
|
+
this.dbName = import_core2.rt.getPath(this.url, this.sthis);
|
|
201
|
+
}
|
|
202
|
+
async _prepare() {
|
|
203
|
+
return this._db.once(async () => {
|
|
204
|
+
return await (0, import_idb2.openDB)(this.dbName, 1, {
|
|
205
|
+
upgrade(db) {
|
|
206
|
+
["bag"].map((store) => {
|
|
207
|
+
db.createObjectStore(store, {
|
|
208
|
+
autoIncrement: false
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
async get(id) {
|
|
216
|
+
const db = await this._prepare();
|
|
217
|
+
const tx = db.transaction(["bag"], "readonly");
|
|
218
|
+
const keyItem = await tx.objectStore("bag").get(id);
|
|
219
|
+
await tx.done;
|
|
220
|
+
if (!keyItem) {
|
|
221
|
+
return void 0;
|
|
222
|
+
}
|
|
223
|
+
return keyItem;
|
|
224
|
+
}
|
|
225
|
+
async set(id, item) {
|
|
226
|
+
const db = await this._prepare();
|
|
227
|
+
const tx = db.transaction(["bag"], "readwrite");
|
|
228
|
+
await tx.objectStore("bag").put(item, id);
|
|
229
|
+
await tx.done;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
//# sourceMappingURL=index.cjs.map
|